Viewer.js 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069
  1. import BoundingSphere from '../../Core/BoundingSphere.js';
  2. import Cartesian3 from '../../Core/Cartesian3.js';
  3. import Cartographic from '../../Core/Cartographic.js';
  4. import Clock from '../../Core/Clock.js';
  5. import defaultValue from '../../Core/defaultValue.js';
  6. import defined from '../../Core/defined.js';
  7. import defineProperties from '../../Core/defineProperties.js';
  8. import destroyObject from '../../Core/destroyObject.js';
  9. import DeveloperError from '../../Core/DeveloperError.js';
  10. import Event from '../../Core/Event.js';
  11. import EventHelper from '../../Core/EventHelper.js';
  12. import HeadingPitchRange from '../../Core/HeadingPitchRange.js';
  13. import isArray from '../../Core/isArray.js';
  14. import Matrix4 from '../../Core/Matrix4.js';
  15. import ScreenSpaceEventType from '../../Core/ScreenSpaceEventType.js';
  16. import BoundingSphereState from '../../DataSources/BoundingSphereState.js';
  17. import ConstantPositionProperty from '../../DataSources/ConstantPositionProperty.js';
  18. import DataSourceCollection from '../../DataSources/DataSourceCollection.js';
  19. import DataSourceDisplay from '../../DataSources/DataSourceDisplay.js';
  20. import Entity from '../../DataSources/Entity.js';
  21. import EntityView from '../../DataSources/EntityView.js';
  22. import Property from '../../DataSources/Property.js';
  23. import Cesium3DTileset from '../../Scene/Cesium3DTileset.js';
  24. import computeFlyToLocationForRectangle from '../../Scene/computeFlyToLocationForRectangle.js';
  25. import ImageryLayer from '../../Scene/ImageryLayer.js';
  26. import SceneMode from '../../Scene/SceneMode.js';
  27. import TimeDynamicPointCloud from '../../Scene/TimeDynamicPointCloud.js';
  28. import knockout from '../../ThirdParty/knockout.js';
  29. import when from '../../ThirdParty/when.js';
  30. import Animation from '../Animation/Animation.js';
  31. import AnimationViewModel from '../Animation/AnimationViewModel.js';
  32. import BaseLayerPicker from '../BaseLayerPicker/BaseLayerPicker.js';
  33. import createDefaultImageryProviderViewModels from '../BaseLayerPicker/createDefaultImageryProviderViewModels.js';
  34. import createDefaultTerrainProviderViewModels from '../BaseLayerPicker/createDefaultTerrainProviderViewModels.js';
  35. import CesiumWidget from '../CesiumWidget/CesiumWidget.js';
  36. import ClockViewModel from '../ClockViewModel.js';
  37. import FullscreenButton from '../FullscreenButton/FullscreenButton.js';
  38. import Geocoder from '../Geocoder/Geocoder.js';
  39. import getElement from '../getElement.js';
  40. import HomeButton from '../HomeButton/HomeButton.js';
  41. import InfoBox from '../InfoBox/InfoBox.js';
  42. import NavigationHelpButton from '../NavigationHelpButton/NavigationHelpButton.js';
  43. import ProjectionPicker from '../ProjectionPicker/ProjectionPicker.js';
  44. import SceneModePicker from '../SceneModePicker/SceneModePicker.js';
  45. import SelectionIndicator from '../SelectionIndicator/SelectionIndicator.js';
  46. import subscribeAndEvaluate from '../subscribeAndEvaluate.js';
  47. import Timeline from '../Timeline/Timeline.js';
  48. import VRButton from '../VRButton/VRButton.js';
  49. var boundingSphereScratch = new BoundingSphere();
  50. function onTimelineScrubfunction(e) {
  51. var clock = e.clock;
  52. clock.currentTime = e.timeJulian;
  53. clock.shouldAnimate = false;
  54. }
  55. function pickEntity(viewer, e) {
  56. var picked = viewer.scene.pick(e.position);
  57. if (defined(picked)) {
  58. var id = defaultValue(picked.id, picked.primitive.id);
  59. if (id instanceof Entity) {
  60. return id;
  61. }
  62. }
  63. // No regular entity picked. Try picking features from imagery layers.
  64. if (defined(viewer.scene.globe)) {
  65. return pickImageryLayerFeature(viewer, e.position);
  66. }
  67. }
  68. function trackDataSourceClock(timeline, clock, dataSource) {
  69. if (defined(dataSource)) {
  70. var dataSourceClock = dataSource.clock;
  71. if (defined(dataSourceClock)) {
  72. dataSourceClock.getValue(clock);
  73. if (defined(timeline)) {
  74. timeline.updateFromClock();
  75. timeline.zoomTo(dataSourceClock.startTime, dataSourceClock.stopTime);
  76. }
  77. }
  78. }
  79. }
  80. var cartesian3Scratch = new Cartesian3();
  81. function pickImageryLayerFeature(viewer, windowPosition) {
  82. var scene = viewer.scene;
  83. var pickRay = scene.camera.getPickRay(windowPosition);
  84. var imageryLayerFeaturePromise = scene.imageryLayers.pickImageryLayerFeatures(pickRay, scene);
  85. if (!defined(imageryLayerFeaturePromise)) {
  86. return;
  87. }
  88. // Imagery layer feature picking is asynchronous, so put up a message while loading.
  89. var loadingMessage = new Entity({
  90. id : 'Loading...',
  91. description : 'Loading feature information...'
  92. });
  93. when(imageryLayerFeaturePromise, function(features) {
  94. // Has this async pick been superseded by a later one?
  95. if (viewer.selectedEntity !== loadingMessage) {
  96. return;
  97. }
  98. if (!defined(features) || features.length === 0) {
  99. viewer.selectedEntity = createNoFeaturesEntity();
  100. return;
  101. }
  102. // Select the first feature.
  103. var feature = features[0];
  104. var entity = new Entity({
  105. id : feature.name,
  106. description : feature.description
  107. });
  108. if (defined(feature.position)) {
  109. var ecfPosition = viewer.scene.globe.ellipsoid.cartographicToCartesian(feature.position, cartesian3Scratch);
  110. entity.position = new ConstantPositionProperty(ecfPosition);
  111. }
  112. viewer.selectedEntity = entity;
  113. }, function() {
  114. // Has this async pick been superseded by a later one?
  115. if (viewer.selectedEntity !== loadingMessage) {
  116. return;
  117. }
  118. viewer.selectedEntity = createNoFeaturesEntity();
  119. });
  120. return loadingMessage;
  121. }
  122. function createNoFeaturesEntity() {
  123. return new Entity({
  124. id : 'None',
  125. description : 'No features found.'
  126. });
  127. }
  128. function enableVRUI(viewer, enabled) {
  129. var geocoder = viewer._geocoder;
  130. var homeButton = viewer._homeButton;
  131. var sceneModePicker = viewer._sceneModePicker;
  132. var projectionPicker = viewer._projectionPicker;
  133. var baseLayerPicker = viewer._baseLayerPicker;
  134. var animation = viewer._animation;
  135. var timeline = viewer._timeline;
  136. var fullscreenButton = viewer._fullscreenButton;
  137. var infoBox = viewer._infoBox;
  138. var selectionIndicator = viewer._selectionIndicator;
  139. var visibility = enabled ? 'hidden' : 'visible';
  140. if (defined(geocoder)) {
  141. geocoder.container.style.visibility = visibility;
  142. }
  143. if (defined(homeButton)) {
  144. homeButton.container.style.visibility = visibility;
  145. }
  146. if (defined(sceneModePicker)) {
  147. sceneModePicker.container.style.visibility = visibility;
  148. }
  149. if (defined(projectionPicker)) {
  150. projectionPicker.container.style.visibility = visibility;
  151. }
  152. if (defined(baseLayerPicker)) {
  153. baseLayerPicker.container.style.visibility = visibility;
  154. }
  155. if (defined(animation)) {
  156. animation.container.style.visibility = visibility;
  157. }
  158. if (defined(timeline)) {
  159. timeline.container.style.visibility = visibility;
  160. }
  161. if (defined(fullscreenButton) && fullscreenButton.viewModel.isFullscreenEnabled) {
  162. fullscreenButton.container.style.visibility = visibility;
  163. }
  164. if (defined(infoBox)) {
  165. infoBox.container.style.visibility = visibility;
  166. }
  167. if (defined(selectionIndicator)) {
  168. selectionIndicator.container.style.visibility = visibility;
  169. }
  170. if (viewer._container) {
  171. var right = enabled || !defined(fullscreenButton) ? 0 : fullscreenButton.container.clientWidth;
  172. viewer._vrButton.container.style.right = right + 'px';
  173. viewer.forceResize();
  174. }
  175. }
  176. /**
  177. * A base widget for building applications. It composites all of the standard Cesium widgets into one reusable package.
  178. * The widget can always be extended by using mixins, which add functionality useful for a variety of applications.
  179. *
  180. * @alias Viewer
  181. * @constructor
  182. *
  183. * @param {Element|String} container The DOM element or ID that will contain the widget.
  184. * @param {Object} [options] Object with the following properties:
  185. * @param {Boolean} [options.animation=true] If set to false, the Animation widget will not be created.
  186. * @param {Boolean} [options.baseLayerPicker=true] If set to false, the BaseLayerPicker widget will not be created.
  187. * @param {Boolean} [options.fullscreenButton=true] If set to false, the FullscreenButton widget will not be created.
  188. * @param {Boolean} [options.vrButton=false] If set to true, the VRButton widget will be created.
  189. * @param {Boolean|GeocoderService[]} [options.geocoder=true] If set to false, the Geocoder widget will not be created.
  190. * @param {Boolean} [options.homeButton=true] If set to false, the HomeButton widget will not be created.
  191. * @param {Boolean} [options.infoBox=true] If set to false, the InfoBox widget will not be created.
  192. * @param {Boolean} [options.sceneModePicker=true] If set to false, the SceneModePicker widget will not be created.
  193. * @param {Boolean} [options.selectionIndicator=true] If set to false, the SelectionIndicator widget will not be created.
  194. * @param {Boolean} [options.timeline=true] If set to false, the Timeline widget will not be created.
  195. * @param {Boolean} [options.navigationHelpButton=true] If set to false, the navigation help button will not be created.
  196. * @param {Boolean} [options.navigationInstructionsInitiallyVisible=true] True if the navigation instructions should initially be visible, or false if the should not be shown until the user explicitly clicks the button.
  197. * @param {Boolean} [options.scene3DOnly=false] When <code>true</code>, each geometry instance will only be rendered in 3D to save GPU memory.
  198. * @param {Boolean} [options.shouldAnimate=false] <code>true</code> if the clock should attempt to advance simulation time by default, <code>false</code> otherwise. This option takes precedence over setting {@link Viewer#clockViewModel}.
  199. * @param {ClockViewModel} [options.clockViewModel=new ClockViewModel(options.clock)] The clock view model to use to control current time.
  200. * @param {ProviderViewModel} [options.selectedImageryProviderViewModel] The view model for the current base imagery layer, if not supplied the first available base layer is used. This value is only valid if options.baseLayerPicker is set to true.
  201. * @param {ProviderViewModel[]} [options.imageryProviderViewModels=createDefaultImageryProviderViewModels()] The array of ProviderViewModels to be selectable from the BaseLayerPicker. This value is only valid if options.baseLayerPicker is set to true.
  202. * @param {ProviderViewModel} [options.selectedTerrainProviderViewModel] The view model for the current base terrain layer, if not supplied the first available base layer is used. This value is only valid if options.baseLayerPicker is set to true.
  203. * @param {ProviderViewModel[]} [options.terrainProviderViewModels=createDefaultTerrainProviderViewModels()] The array of ProviderViewModels to be selectable from the BaseLayerPicker. This value is only valid if options.baseLayerPicker is set to true.
  204. * @param {ImageryProvider} [options.imageryProvider=createWorldImagery()] The imagery provider to use. This value is only valid if options.baseLayerPicker is set to false.
  205. * @param {TerrainProvider} [options.terrainProvider=new EllipsoidTerrainProvider()] The terrain provider to use
  206. * @param {SkyBox} [options.skyBox] The skybox used to render the stars. When <code>undefined</code>, the default stars are used.
  207. * @param {SkyAtmosphere} [options.skyAtmosphere] Blue sky, and the glow around the Earth's limb. Set to <code>false</code> to turn it off.
  208. * @param {Element|String} [options.fullscreenElement=document.body] The element or id to be placed into fullscreen mode when the full screen button is pressed.
  209. * @param {Boolean} [options.useDefaultRenderLoop=true] True if this widget should control the render loop, false otherwise.
  210. * @param {Number} [options.targetFrameRate] The target frame rate when using the default render loop.
  211. * @param {Boolean} [options.showRenderLoopErrors=true] If true, this widget will automatically display an HTML panel to the user containing the error, if a render loop error occurs.
  212. * @param {Boolean} [options.useBrowserRecommendedResolution=false] If true, render at the browser's recommended resolution and ignore <code>window.devicePixelRatio</code>.
  213. * @param {Boolean} [options.automaticallyTrackDataSourceClocks=true] If true, this widget will automatically track the clock settings of newly added DataSources, updating if the DataSource's clock changes. Set this to false if you want to configure the clock independently.
  214. * @param {Object} [options.contextOptions] Context and WebGL creation properties corresponding to <code>options</code> passed to {@link Scene}.
  215. * @param {SceneMode} [options.sceneMode=SceneMode.SCENE3D] The initial scene mode.
  216. * @param {MapProjection} [options.mapProjection=new GeographicProjection()] The map projection to use in 2D and Columbus View modes.
  217. * @param {Globe} [options.globe=new Globe(mapProjection.ellipsoid)] The globe to use in the scene. If set to <code>false</code>, no globe will be added.
  218. * @param {Boolean} [options.orderIndependentTranslucency=true] If true and the configuration supports it, use order independent translucency.
  219. * @param {Element|String} [options.creditContainer] The DOM element or ID that will contain the {@link CreditDisplay}. If not specified, the credits are added to the bottom of the widget itself.
  220. * @param {Element|String} [options.creditViewport] The DOM element or ID that will contain the credit pop up created by the {@link CreditDisplay}. If not specified, it will appear over the widget itself.
  221. * @param {DataSourceCollection} [options.dataSources=new DataSourceCollection()] The collection of data sources visualized by the widget. If this parameter is provided,
  222. * the instance is assumed to be owned by the caller and will not be destroyed when the viewer is destroyed.
  223. * @param {Number} [options.terrainExaggeration=1.0] A scalar used to exaggerate the terrain. Note that terrain exaggeration will not modify any other primitive as they are positioned relative to the ellipsoid.
  224. * @param {Boolean} [options.shadows=false] Determines if shadows are cast by the sun.
  225. * @param {ShadowMode} [options.terrainShadows=ShadowMode.RECEIVE_ONLY] Determines if the terrain casts or receives shadows from the sun.
  226. * @param {MapMode2D} [options.mapMode2D=MapMode2D.INFINITE_SCROLL] Determines if the 2D map is rotatable or can be scrolled infinitely in the horizontal direction.
  227. * @param {Boolean} [options.projectionPicker=false] If set to true, the ProjectionPicker widget will be created.
  228. * @param {Boolean} [options.requestRenderMode=false] If true, rendering a frame will only occur when needed as determined by changes within the scene. Enabling reduces the CPU/GPU usage of your application and uses less battery on mobile, but requires using {@link Scene#requestRender} to render a new frame explicitly in this mode. This will be necessary in many cases after making changes to the scene in other parts of the API. See {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}.
  229. * @param {Number} [options.maximumRenderTimeChange=0.0] If requestRenderMode is true, this value defines the maximum change in simulation time allowed before a render is requested. See {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}.
  230. *
  231. * @exception {DeveloperError} Element with id "container" does not exist in the document.
  232. * @exception {DeveloperError} options.selectedImageryProviderViewModel is not available when not using the BaseLayerPicker widget, specify options.imageryProvider instead.
  233. * @exception {DeveloperError} options.selectedTerrainProviderViewModel is not available when not using the BaseLayerPicker widget, specify options.terrainProvider instead.
  234. *
  235. * @see Animation
  236. * @see BaseLayerPicker
  237. * @see CesiumWidget
  238. * @see FullscreenButton
  239. * @see HomeButton
  240. * @see SceneModePicker
  241. * @see Timeline
  242. * @see viewerDragDropMixin
  243. *
  244. * @demo {@link https://sandcastle.cesium.com/index.html?src=Hello%20World.html|Cesium Sandcastle Hello World Demo}
  245. *
  246. * @example
  247. * //Initialize the viewer widget with several custom options and mixins.
  248. * var viewer = new Cesium.Viewer('cesiumContainer', {
  249. * //Start in Columbus Viewer
  250. * sceneMode : Cesium.SceneMode.COLUMBUS_VIEW,
  251. * //Use Cesium World Terrain
  252. * terrainProvider : Cesium.createWorldTerrain(),
  253. * //Hide the base layer picker
  254. * baseLayerPicker : false,
  255. * //Use OpenStreetMaps
  256. * imageryProvider : new Cesium.OpenStreetMapImageryProvider({
  257. * url : 'https://a.tile.openstreetmap.org/'
  258. * }),
  259. * // Use high-res stars downloaded from https://github.com/AnalyticalGraphicsInc/cesium-assets
  260. * skyBox : new Cesium.SkyBox({
  261. * sources : {
  262. * positiveX : 'stars/TychoSkymapII.t3_08192x04096_80_px.jpg',
  263. * negativeX : 'stars/TychoSkymapII.t3_08192x04096_80_mx.jpg',
  264. * positiveY : 'stars/TychoSkymapII.t3_08192x04096_80_py.jpg',
  265. * negativeY : 'stars/TychoSkymapII.t3_08192x04096_80_my.jpg',
  266. * positiveZ : 'stars/TychoSkymapII.t3_08192x04096_80_pz.jpg',
  267. * negativeZ : 'stars/TychoSkymapII.t3_08192x04096_80_mz.jpg'
  268. * }
  269. * }),
  270. * // Show Columbus View map with Web Mercator projection
  271. * mapProjection : new Cesium.WebMercatorProjection()
  272. * });
  273. *
  274. * //Add basic drag and drop functionality
  275. * viewer.extend(Cesium.viewerDragDropMixin);
  276. *
  277. * //Show a pop-up alert if we encounter an error when processing a dropped file
  278. * viewer.dropError.addEventListener(function(dropHandler, name, error) {
  279. * console.log(error);
  280. * window.alert(error);
  281. * });
  282. */
  283. function Viewer(container, options) {
  284. //>>includeStart('debug', pragmas.debug);
  285. if (!defined(container)) {
  286. throw new DeveloperError('container is required.');
  287. }
  288. //>>includeEnd('debug');
  289. container = getElement(container);
  290. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  291. var createBaseLayerPicker = (!defined(options.globe) || options.globe !== false) &&
  292. (!defined(options.baseLayerPicker) || options.baseLayerPicker !== false);
  293. //>>includeStart('debug', pragmas.debug);
  294. // If not using BaseLayerPicker, selectedImageryProviderViewModel is an invalid option
  295. if (!createBaseLayerPicker && defined(options.selectedImageryProviderViewModel)) {
  296. throw new DeveloperError('options.selectedImageryProviderViewModel is not available when not using the BaseLayerPicker widget. \
  297. Either specify options.imageryProvider instead or set options.baseLayerPicker to true.');
  298. }
  299. // If not using BaseLayerPicker, selectedTerrainProviderViewModel is an invalid option
  300. if (!createBaseLayerPicker && defined(options.selectedTerrainProviderViewModel)) {
  301. throw new DeveloperError('options.selectedTerrainProviderViewModel is not available when not using the BaseLayerPicker widget. \
  302. Either specify options.terrainProvider instead or set options.baseLayerPicker to true.');
  303. }
  304. //>>includeEnd('debug')
  305. var that = this;
  306. var viewerContainer = document.createElement('div');
  307. viewerContainer.className = 'cesium-viewer';
  308. container.appendChild(viewerContainer);
  309. // Cesium widget container
  310. var cesiumWidgetContainer = document.createElement('div');
  311. cesiumWidgetContainer.className = 'cesium-viewer-cesiumWidgetContainer';
  312. viewerContainer.appendChild(cesiumWidgetContainer);
  313. // Bottom container
  314. var bottomContainer = document.createElement('div');
  315. bottomContainer.className = 'cesium-viewer-bottom';
  316. viewerContainer.appendChild(bottomContainer);
  317. var scene3DOnly = defaultValue(options.scene3DOnly, false);
  318. var clock;
  319. var clockViewModel;
  320. var destroyClockViewModel = false;
  321. if (defined(options.clockViewModel)) {
  322. clockViewModel = options.clockViewModel;
  323. clock = clockViewModel.clock;
  324. } else {
  325. clock = new Clock();
  326. clockViewModel = new ClockViewModel(clock);
  327. destroyClockViewModel = true;
  328. }
  329. if (defined(options.shouldAnimate)) {
  330. clock.shouldAnimate = options.shouldAnimate;
  331. }
  332. // Cesium widget
  333. var cesiumWidget = new CesiumWidget(cesiumWidgetContainer, {
  334. imageryProvider: createBaseLayerPicker || defined(options.imageryProvider) ? false : undefined,
  335. clock : clock,
  336. skyBox : options.skyBox,
  337. skyAtmosphere : options.skyAtmosphere,
  338. sceneMode : options.sceneMode,
  339. mapProjection : options.mapProjection,
  340. globe : options.globe,
  341. orderIndependentTranslucency : options.orderIndependentTranslucency,
  342. contextOptions : options.contextOptions,
  343. useDefaultRenderLoop : options.useDefaultRenderLoop,
  344. targetFrameRate : options.targetFrameRate,
  345. showRenderLoopErrors : options.showRenderLoopErrors,
  346. useBrowserRecommendedResolution : options.useBrowserRecommendedResolution,
  347. creditContainer : defined(options.creditContainer) ? options.creditContainer : bottomContainer,
  348. creditViewport : options.creditViewport,
  349. scene3DOnly : scene3DOnly,
  350. terrainExaggeration : options.terrainExaggeration,
  351. shadows : options.shadows,
  352. terrainShadows : options.terrainShadows,
  353. mapMode2D : options.mapMode2D,
  354. requestRenderMode : options.requestRenderMode,
  355. maximumRenderTimeChange : options.maximumRenderTimeChange
  356. });
  357. var dataSourceCollection = options.dataSources;
  358. var destroyDataSourceCollection = false;
  359. if (!defined(dataSourceCollection)) {
  360. dataSourceCollection = new DataSourceCollection();
  361. destroyDataSourceCollection = true;
  362. }
  363. var scene = cesiumWidget.scene;
  364. var dataSourceDisplay = new DataSourceDisplay({
  365. scene : scene,
  366. dataSourceCollection : dataSourceCollection
  367. });
  368. var eventHelper = new EventHelper();
  369. eventHelper.add(clock.onTick, Viewer.prototype._onTick, this);
  370. eventHelper.add(scene.morphStart, Viewer.prototype._clearTrackedObject, this);
  371. // Selection Indicator
  372. var selectionIndicator;
  373. if (!defined(options.selectionIndicator) || options.selectionIndicator !== false) {
  374. var selectionIndicatorContainer = document.createElement('div');
  375. selectionIndicatorContainer.className = 'cesium-viewer-selectionIndicatorContainer';
  376. viewerContainer.appendChild(selectionIndicatorContainer);
  377. selectionIndicator = new SelectionIndicator(selectionIndicatorContainer, scene);
  378. }
  379. // Info Box
  380. var infoBox;
  381. if (!defined(options.infoBox) || options.infoBox !== false) {
  382. var infoBoxContainer = document.createElement('div');
  383. infoBoxContainer.className = 'cesium-viewer-infoBoxContainer';
  384. viewerContainer.appendChild(infoBoxContainer);
  385. infoBox = new InfoBox(infoBoxContainer);
  386. var infoBoxViewModel = infoBox.viewModel;
  387. eventHelper.add(infoBoxViewModel.cameraClicked, Viewer.prototype._onInfoBoxCameraClicked, this);
  388. eventHelper.add(infoBoxViewModel.closeClicked, Viewer.prototype._onInfoBoxClockClicked, this);
  389. }
  390. // Main Toolbar
  391. var toolbar = document.createElement('div');
  392. toolbar.className = 'cesium-viewer-toolbar';
  393. viewerContainer.appendChild(toolbar);
  394. // Geocoder
  395. var geocoder;
  396. if (!defined(options.geocoder) || options.geocoder !== false) {
  397. var geocoderContainer = document.createElement('div');
  398. geocoderContainer.className = 'cesium-viewer-geocoderContainer';
  399. toolbar.appendChild(geocoderContainer);
  400. var geocoderService;
  401. if (defined(options.geocoder) && typeof options.geocoder !== 'boolean') {
  402. geocoderService = isArray(options.geocoder) ? options.geocoder : [options.geocoder];
  403. }
  404. geocoder = new Geocoder({
  405. container : geocoderContainer,
  406. geocoderServices : geocoderService,
  407. scene : scene
  408. });
  409. // Subscribe to search so that we can clear the trackedEntity when it is clicked.
  410. eventHelper.add(geocoder.viewModel.search.beforeExecute, Viewer.prototype._clearObjects, this);
  411. }
  412. // HomeButton
  413. var homeButton;
  414. if (!defined(options.homeButton) || options.homeButton !== false) {
  415. homeButton = new HomeButton(toolbar, scene);
  416. if (defined(geocoder)) {
  417. eventHelper.add(homeButton.viewModel.command.afterExecute, function() {
  418. var viewModel = geocoder.viewModel;
  419. viewModel.searchText = '';
  420. if (viewModel.isSearchInProgress) {
  421. viewModel.search();
  422. }
  423. });
  424. }
  425. // Subscribe to the home button beforeExecute event so that we can clear the trackedEntity.
  426. eventHelper.add(homeButton.viewModel.command.beforeExecute, Viewer.prototype._clearTrackedObject, this);
  427. }
  428. // SceneModePicker
  429. // By default, we silently disable the scene mode picker if scene3DOnly is true,
  430. // but if sceneModePicker is explicitly set to true, throw an error.
  431. //>>includeStart('debug', pragmas.debug);
  432. if ((options.sceneModePicker === true) && scene3DOnly) {
  433. throw new DeveloperError('options.sceneModePicker is not available when options.scene3DOnly is set to true.');
  434. }
  435. //>>includeEnd('debug');
  436. var sceneModePicker;
  437. if (!scene3DOnly && (!defined(options.sceneModePicker) || options.sceneModePicker !== false)) {
  438. sceneModePicker = new SceneModePicker(toolbar, scene);
  439. }
  440. var projectionPicker;
  441. if (options.projectionPicker) {
  442. projectionPicker = new ProjectionPicker(toolbar, scene);
  443. }
  444. // BaseLayerPicker
  445. var baseLayerPicker;
  446. var baseLayerPickerDropDown;
  447. if (createBaseLayerPicker) {
  448. var imageryProviderViewModels = defaultValue(options.imageryProviderViewModels, createDefaultImageryProviderViewModels());
  449. var terrainProviderViewModels = defaultValue(options.terrainProviderViewModels, createDefaultTerrainProviderViewModels());
  450. baseLayerPicker = new BaseLayerPicker(toolbar, {
  451. globe : scene.globe,
  452. imageryProviderViewModels : imageryProviderViewModels,
  453. selectedImageryProviderViewModel : options.selectedImageryProviderViewModel,
  454. terrainProviderViewModels : terrainProviderViewModels,
  455. selectedTerrainProviderViewModel : options.selectedTerrainProviderViewModel
  456. });
  457. //Grab the dropdown for resize code.
  458. var elements = toolbar.getElementsByClassName('cesium-baseLayerPicker-dropDown');
  459. baseLayerPickerDropDown = elements[0];
  460. }
  461. // These need to be set after the BaseLayerPicker is created in order to take effect
  462. if (defined(options.imageryProvider) && options.imageryProvider !== false) {
  463. if (createBaseLayerPicker) {
  464. baseLayerPicker.viewModel.selectedImagery = undefined;
  465. }
  466. scene.imageryLayers.removeAll();
  467. scene.imageryLayers.addImageryProvider(options.imageryProvider);
  468. }
  469. if (defined(options.terrainProvider)) {
  470. if (createBaseLayerPicker) {
  471. baseLayerPicker.viewModel.selectedTerrain = undefined;
  472. }
  473. scene.terrainProvider = options.terrainProvider;
  474. }
  475. // Navigation Help Button
  476. var navigationHelpButton;
  477. if (!defined(options.navigationHelpButton) || options.navigationHelpButton !== false) {
  478. var showNavHelp = true;
  479. try {
  480. //window.localStorage is null if disabled in Firefox or undefined in browsers with implementation
  481. if (defined(window.localStorage)) {
  482. var hasSeenNavHelp = window.localStorage.getItem('cesium-hasSeenNavHelp');
  483. if (defined(hasSeenNavHelp) && Boolean(hasSeenNavHelp)) {
  484. showNavHelp = false;
  485. } else {
  486. window.localStorage.setItem('cesium-hasSeenNavHelp', 'true');
  487. }
  488. }
  489. } catch (e) {
  490. //Accessing window.localStorage throws if disabled in Chrome
  491. //window.localStorage.setItem throws if in Safari private browsing mode or in any browser if we are over quota.
  492. }
  493. navigationHelpButton = new NavigationHelpButton({
  494. container : toolbar,
  495. instructionsInitiallyVisible : defaultValue(options.navigationInstructionsInitiallyVisible, showNavHelp)
  496. });
  497. }
  498. // Animation
  499. var animation;
  500. if (!defined(options.animation) || options.animation !== false) {
  501. var animationContainer = document.createElement('div');
  502. animationContainer.className = 'cesium-viewer-animationContainer';
  503. viewerContainer.appendChild(animationContainer);
  504. animation = new Animation(animationContainer, new AnimationViewModel(clockViewModel));
  505. }
  506. // Timeline
  507. var timeline;
  508. if (!defined(options.timeline) || options.timeline !== false) {
  509. var timelineContainer = document.createElement('div');
  510. timelineContainer.className = 'cesium-viewer-timelineContainer';
  511. viewerContainer.appendChild(timelineContainer);
  512. timeline = new Timeline(timelineContainer, clock);
  513. timeline.addEventListener('settime', onTimelineScrubfunction, false);
  514. timeline.zoomTo(clock.startTime, clock.stopTime);
  515. }
  516. // Fullscreen
  517. var fullscreenButton;
  518. var fullscreenSubscription;
  519. var fullscreenContainer;
  520. if (!defined(options.fullscreenButton) || options.fullscreenButton !== false) {
  521. fullscreenContainer = document.createElement('div');
  522. fullscreenContainer.className = 'cesium-viewer-fullscreenContainer';
  523. viewerContainer.appendChild(fullscreenContainer);
  524. fullscreenButton = new FullscreenButton(fullscreenContainer, options.fullscreenElement);
  525. //Subscribe to fullscreenButton.viewModel.isFullscreenEnabled so
  526. //that we can hide/show the button as well as size the timeline.
  527. fullscreenSubscription = subscribeAndEvaluate(fullscreenButton.viewModel, 'isFullscreenEnabled', function(isFullscreenEnabled) {
  528. fullscreenContainer.style.display = isFullscreenEnabled ? 'block' : 'none';
  529. if (defined(timeline)) {
  530. timeline.container.style.right = fullscreenContainer.clientWidth + 'px';
  531. timeline.resize();
  532. }
  533. });
  534. }
  535. // VR
  536. var vrButton;
  537. var vrSubscription;
  538. var vrModeSubscription;
  539. if (options.vrButton) {
  540. var vrContainer = document.createElement('div');
  541. vrContainer.className = 'cesium-viewer-vrContainer';
  542. viewerContainer.appendChild(vrContainer);
  543. vrButton = new VRButton(vrContainer, scene, options.fullScreenElement);
  544. vrSubscription = subscribeAndEvaluate(vrButton.viewModel, 'isVREnabled', function(isVREnabled) {
  545. vrContainer.style.display = isVREnabled ? 'block' : 'none';
  546. if (defined(fullscreenButton)) {
  547. vrContainer.style.right = fullscreenContainer.clientWidth + 'px';
  548. }
  549. if (defined(timeline)) {
  550. timeline.container.style.right = vrContainer.clientWidth + 'px';
  551. timeline.resize();
  552. }
  553. });
  554. vrModeSubscription = subscribeAndEvaluate(vrButton.viewModel, 'isVRMode', function(isVRMode) {
  555. enableVRUI(that, isVRMode);
  556. });
  557. }
  558. //Assign all properties to this instance. No "this" assignments should
  559. //take place above this line.
  560. this._baseLayerPickerDropDown = baseLayerPickerDropDown;
  561. this._fullscreenSubscription = fullscreenSubscription;
  562. this._vrSubscription = vrSubscription;
  563. this._vrModeSubscription = vrModeSubscription;
  564. this._dataSourceChangedListeners = {};
  565. this._automaticallyTrackDataSourceClocks = defaultValue(options.automaticallyTrackDataSourceClocks, true);
  566. this._container = container;
  567. this._bottomContainer = bottomContainer;
  568. this._element = viewerContainer;
  569. this._cesiumWidget = cesiumWidget;
  570. this._selectionIndicator = selectionIndicator;
  571. this._infoBox = infoBox;
  572. this._dataSourceCollection = dataSourceCollection;
  573. this._destroyDataSourceCollection = destroyDataSourceCollection;
  574. this._dataSourceDisplay = dataSourceDisplay;
  575. this._clockViewModel = clockViewModel;
  576. this._destroyClockViewModel = destroyClockViewModel;
  577. this._toolbar = toolbar;
  578. this._homeButton = homeButton;
  579. this._sceneModePicker = sceneModePicker;
  580. this._projectionPicker = projectionPicker;
  581. this._baseLayerPicker = baseLayerPicker;
  582. this._navigationHelpButton = navigationHelpButton;
  583. this._animation = animation;
  584. this._timeline = timeline;
  585. this._fullscreenButton = fullscreenButton;
  586. this._vrButton = vrButton;
  587. this._geocoder = geocoder;
  588. this._eventHelper = eventHelper;
  589. this._lastWidth = 0;
  590. this._lastHeight = 0;
  591. this._allowDataSourcesToSuspendAnimation = true;
  592. this._entityView = undefined;
  593. this._enableInfoOrSelection = defined(infoBox) || defined(selectionIndicator);
  594. this._clockTrackedDataSource = undefined;
  595. this._trackedEntity = undefined;
  596. this._needTrackedEntityUpdate = false;
  597. this._selectedEntity = undefined;
  598. this._clockTrackedDataSource = undefined;
  599. this._zoomIsFlight = false;
  600. this._zoomTarget = undefined;
  601. this._zoomPromise = undefined;
  602. this._zoomOptions = undefined;
  603. this._selectedEntityChanged = new Event();
  604. this._trackedEntityChanged = new Event();
  605. knockout.track(this, ['_trackedEntity', '_selectedEntity', '_clockTrackedDataSource']);
  606. //Listen to data source events in order to track clock changes.
  607. eventHelper.add(dataSourceCollection.dataSourceAdded, Viewer.prototype._onDataSourceAdded, this);
  608. eventHelper.add(dataSourceCollection.dataSourceRemoved, Viewer.prototype._onDataSourceRemoved, this);
  609. // Prior to each render, check if anything needs to be resized.
  610. eventHelper.add(scene.postUpdate, Viewer.prototype.resize, this);
  611. eventHelper.add(scene.postRender, Viewer.prototype._postRender, this);
  612. // We need to subscribe to the data sources and collections so that we can clear the
  613. // tracked object when it is removed from the scene.
  614. // Subscribe to current data sources
  615. var dataSourceLength = dataSourceCollection.length;
  616. for (var i = 0; i < dataSourceLength; i++) {
  617. this._dataSourceAdded(dataSourceCollection, dataSourceCollection.get(i));
  618. }
  619. this._dataSourceAdded(undefined, dataSourceDisplay.defaultDataSource);
  620. // Hook up events so that we can subscribe to future sources.
  621. eventHelper.add(dataSourceCollection.dataSourceAdded, Viewer.prototype._dataSourceAdded, this);
  622. eventHelper.add(dataSourceCollection.dataSourceRemoved, Viewer.prototype._dataSourceRemoved, this);
  623. // Subscribe to left clicks and zoom to the picked object.
  624. function pickAndTrackObject(e) {
  625. var entity = pickEntity(that, e);
  626. if (defined(entity)) {
  627. //Only track the entity if it has a valid position at the current time.
  628. if (Property.getValueOrUndefined(entity.position, that.clock.currentTime)) {
  629. that.trackedEntity = entity;
  630. } else {
  631. that.zoomTo(entity);
  632. }
  633. } else if (defined(that.trackedEntity)) {
  634. that.trackedEntity = undefined;
  635. }
  636. }
  637. function pickAndSelectObject(e) {
  638. that.selectedEntity = pickEntity(that, e);
  639. }
  640. cesiumWidget.screenSpaceEventHandler.setInputAction(pickAndSelectObject, ScreenSpaceEventType.LEFT_CLICK);
  641. cesiumWidget.screenSpaceEventHandler.setInputAction(pickAndTrackObject, ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
  642. }
  643. defineProperties(Viewer.prototype, {
  644. /**
  645. * Gets the parent container.
  646. * @memberof Viewer.prototype
  647. * @type {Element}
  648. * @readonly
  649. */
  650. container : {
  651. get : function() {
  652. return this._container;
  653. }
  654. },
  655. /**
  656. * Gets the DOM element for the area at the bottom of the window containing the
  657. * {@link CreditDisplay} and potentially other things.
  658. * @memberof Viewer.prototype
  659. * @type {Element}
  660. * @readonly
  661. */
  662. bottomContainer : {
  663. get : function() {
  664. return this._bottomContainer;
  665. }
  666. },
  667. /**
  668. * Gets the CesiumWidget.
  669. * @memberof Viewer.prototype
  670. * @type {CesiumWidget}
  671. * @readonly
  672. */
  673. cesiumWidget : {
  674. get : function() {
  675. return this._cesiumWidget;
  676. }
  677. },
  678. /**
  679. * Gets the selection indicator.
  680. * @memberof Viewer.prototype
  681. * @type {SelectionIndicator}
  682. * @readonly
  683. */
  684. selectionIndicator : {
  685. get : function() {
  686. return this._selectionIndicator;
  687. }
  688. },
  689. /**
  690. * Gets the info box.
  691. * @memberof Viewer.prototype
  692. * @type {InfoBox}
  693. * @readonly
  694. */
  695. infoBox : {
  696. get : function() {
  697. return this._infoBox;
  698. }
  699. },
  700. /**
  701. * Gets the Geocoder.
  702. * @memberof Viewer.prototype
  703. * @type {Geocoder}
  704. * @readonly
  705. */
  706. geocoder : {
  707. get : function() {
  708. return this._geocoder;
  709. }
  710. },
  711. /**
  712. * Gets the HomeButton.
  713. * @memberof Viewer.prototype
  714. * @type {HomeButton}
  715. * @readonly
  716. */
  717. homeButton : {
  718. get : function() {
  719. return this._homeButton;
  720. }
  721. },
  722. /**
  723. * Gets the SceneModePicker.
  724. * @memberof Viewer.prototype
  725. * @type {SceneModePicker}
  726. * @readonly
  727. */
  728. sceneModePicker : {
  729. get : function() {
  730. return this._sceneModePicker;
  731. }
  732. },
  733. /**
  734. * Gets the ProjectionPicker.
  735. * @memberof Viewer.prototype
  736. * @type {ProjectionPicker}
  737. * @readonly
  738. */
  739. projectionPicker : {
  740. get : function() {
  741. return this._projectionPicker;
  742. }
  743. },
  744. /**
  745. * Gets the BaseLayerPicker.
  746. * @memberof Viewer.prototype
  747. * @type {BaseLayerPicker}
  748. * @readonly
  749. */
  750. baseLayerPicker : {
  751. get : function() {
  752. return this._baseLayerPicker;
  753. }
  754. },
  755. /**
  756. * Gets the NavigationHelpButton.
  757. * @memberof Viewer.prototype
  758. * @type {NavigationHelpButton}
  759. * @readonly
  760. */
  761. navigationHelpButton : {
  762. get : function() {
  763. return this._navigationHelpButton;
  764. }
  765. },
  766. /**
  767. * Gets the Animation widget.
  768. * @memberof Viewer.prototype
  769. * @type {Animation}
  770. * @readonly
  771. */
  772. animation : {
  773. get : function() {
  774. return this._animation;
  775. }
  776. },
  777. /**
  778. * Gets the Timeline widget.
  779. * @memberof Viewer.prototype
  780. * @type {Timeline}
  781. * @readonly
  782. */
  783. timeline : {
  784. get : function() {
  785. return this._timeline;
  786. }
  787. },
  788. /**
  789. * Gets the FullscreenButton.
  790. * @memberof Viewer.prototype
  791. * @type {FullscreenButton}
  792. * @readonly
  793. */
  794. fullscreenButton : {
  795. get : function() {
  796. return this._fullscreenButton;
  797. }
  798. },
  799. /**
  800. * Gets the VRButton.
  801. * @memberof Viewer.prototype
  802. * @type {VRButton}
  803. * @readonly
  804. */
  805. vrButton : {
  806. get : function() {
  807. return this._vrButton;
  808. }
  809. },
  810. /**
  811. * Gets the display used for {@link DataSource} visualization.
  812. * @memberof Viewer.prototype
  813. * @type {DataSourceDisplay}
  814. * @readonly
  815. */
  816. dataSourceDisplay : {
  817. get : function() {
  818. return this._dataSourceDisplay;
  819. }
  820. },
  821. /**
  822. * Gets the collection of entities not tied to a particular data source.
  823. * This is a shortcut to [dataSourceDisplay.defaultDataSource.entities]{@link Viewer#dataSourceDisplay}.
  824. * @memberof Viewer.prototype
  825. * @type {EntityCollection}
  826. * @readonly
  827. */
  828. entities : {
  829. get : function() {
  830. return this._dataSourceDisplay.defaultDataSource.entities;
  831. }
  832. },
  833. /**
  834. * Gets the set of {@link DataSource} instances to be visualized.
  835. * @memberof Viewer.prototype
  836. * @type {DataSourceCollection}
  837. * @readonly
  838. */
  839. dataSources : {
  840. get : function() {
  841. return this._dataSourceCollection;
  842. }
  843. },
  844. /**
  845. * Gets the canvas.
  846. * @memberof Viewer.prototype
  847. * @type {Canvas}
  848. * @readonly
  849. */
  850. canvas : {
  851. get : function() {
  852. return this._cesiumWidget.canvas;
  853. }
  854. },
  855. /**
  856. * Gets the scene.
  857. * @memberof Viewer.prototype
  858. * @type {Scene}
  859. * @readonly
  860. */
  861. scene : {
  862. get : function() {
  863. return this._cesiumWidget.scene;
  864. }
  865. },
  866. /**
  867. * Determines if shadows are cast by the sun.
  868. * @memberof Viewer.prototype
  869. * @type {Boolean}
  870. */
  871. shadows : {
  872. get : function() {
  873. return this.scene.shadowMap.enabled;
  874. },
  875. set : function(value) {
  876. this.scene.shadowMap.enabled = value;
  877. }
  878. },
  879. /**
  880. * Determines if the terrain casts or shadows from the sun.
  881. * @memberof Viewer.prototype
  882. * @type {ShadowMode}
  883. */
  884. terrainShadows : {
  885. get : function() {
  886. return this.scene.globe.shadows;
  887. },
  888. set : function(value) {
  889. this.scene.globe.shadows = value;
  890. }
  891. },
  892. /**
  893. * Get the scene's shadow map
  894. * @memberof Viewer.prototype
  895. * @type {ShadowMap}
  896. * @readonly
  897. */
  898. shadowMap : {
  899. get : function() {
  900. return this.scene.shadowMap;
  901. }
  902. },
  903. /**
  904. * Gets the collection of image layers that will be rendered on the globe.
  905. * @memberof Viewer.prototype
  906. *
  907. * @type {ImageryLayerCollection}
  908. * @readonly
  909. */
  910. imageryLayers : {
  911. get : function() {
  912. return this.scene.imageryLayers;
  913. }
  914. },
  915. /**
  916. * The terrain provider providing surface geometry for the globe.
  917. * @memberof Viewer.prototype
  918. *
  919. * @type {TerrainProvider}
  920. */
  921. terrainProvider : {
  922. get : function() {
  923. return this.scene.terrainProvider;
  924. },
  925. set : function(terrainProvider) {
  926. this.scene.terrainProvider = terrainProvider;
  927. }
  928. },
  929. /**
  930. * Gets the camera.
  931. * @memberof Viewer.prototype
  932. *
  933. * @type {Camera}
  934. * @readonly
  935. */
  936. camera : {
  937. get : function() {
  938. return this.scene.camera;
  939. }
  940. },
  941. /**
  942. * Gets the post-process stages.
  943. * @memberof Viewer.prototype
  944. *
  945. * @type {PostProcessStageCollection}
  946. * @readonly
  947. */
  948. postProcessStages : {
  949. get : function() {
  950. return this.scene.postProcessStages;
  951. }
  952. },
  953. /**
  954. * Gets the clock.
  955. * @memberof Viewer.prototype
  956. * @type {Clock}
  957. * @readonly
  958. */
  959. clock : {
  960. get : function() {
  961. return this._clockViewModel.clock;
  962. }
  963. },
  964. /**
  965. * Gets the clock view model.
  966. * @memberof Viewer.prototype
  967. * @type {ClockViewModel}
  968. * @readonly
  969. */
  970. clockViewModel : {
  971. get : function() {
  972. return this._clockViewModel;
  973. }
  974. },
  975. /**
  976. * Gets the screen space event handler.
  977. * @memberof Viewer.prototype
  978. * @type {ScreenSpaceEventHandler}
  979. * @readonly
  980. */
  981. screenSpaceEventHandler : {
  982. get : function() {
  983. return this._cesiumWidget.screenSpaceEventHandler;
  984. }
  985. },
  986. /**
  987. * Gets or sets the target frame rate of the widget when <code>useDefaultRenderLoop</code>
  988. * is true. If undefined, the browser's {@link requestAnimationFrame} implementation
  989. * determines the frame rate. If defined, this value must be greater than 0. A value higher
  990. * than the underlying requestAnimationFrame implementation will have no effect.
  991. * @memberof Viewer.prototype
  992. *
  993. * @type {Number}
  994. */
  995. targetFrameRate : {
  996. get : function() {
  997. return this._cesiumWidget.targetFrameRate;
  998. },
  999. set : function(value) {
  1000. this._cesiumWidget.targetFrameRate = value;
  1001. }
  1002. },
  1003. /**
  1004. * Gets or sets whether or not this widget should control the render loop.
  1005. * If set to true the widget will use {@link requestAnimationFrame} to
  1006. * perform rendering and resizing of the widget, as well as drive the
  1007. * simulation clock. If set to false, you must manually call the
  1008. * <code>resize</code>, <code>render</code> methods
  1009. * as part of a custom render loop. If an error occurs during rendering, {@link Scene}'s
  1010. * <code>renderError</code> event will be raised and this property
  1011. * will be set to false. It must be set back to true to continue rendering
  1012. * after the error.
  1013. * @memberof Viewer.prototype
  1014. *
  1015. * @type {Boolean}
  1016. */
  1017. useDefaultRenderLoop : {
  1018. get : function() {
  1019. return this._cesiumWidget.useDefaultRenderLoop;
  1020. },
  1021. set : function(value) {
  1022. this._cesiumWidget.useDefaultRenderLoop = value;
  1023. }
  1024. },
  1025. /**
  1026. * Gets or sets a scaling factor for rendering resolution. Values less than 1.0 can improve
  1027. * performance on less powerful devices while values greater than 1.0 will render at a higher
  1028. * resolution and then scale down, resulting in improved visual fidelity.
  1029. * For example, if the widget is laid out at a size of 640x480, setting this value to 0.5
  1030. * will cause the scene to be rendered at 320x240 and then scaled up while setting
  1031. * it to 2.0 will cause the scene to be rendered at 1280x960 and then scaled down.
  1032. * @memberof Viewer.prototype
  1033. *
  1034. * @type {Number}
  1035. * @default 1.0
  1036. */
  1037. resolutionScale : {
  1038. get : function() {
  1039. return this._cesiumWidget.resolutionScale;
  1040. },
  1041. set : function(value) {
  1042. this._cesiumWidget.resolutionScale = value;
  1043. }
  1044. },
  1045. /**
  1046. * Boolean flag indicating if the browser's recommended resolution is used.
  1047. * If true, the browser's device pixel ratio is ignored and 1.0 is used instead,
  1048. * effectively rendering based on CSS pixels instead of device pixels. This can improve
  1049. * performance on less powerful devices that have high pixel density. When false, rendering
  1050. * will be in device pixels. {@link Viewer#resolutionScale} will still take effect whether
  1051. * this flag is true or false.
  1052. * @memberof Viewer.prototype
  1053. *
  1054. * @type {Boolean}
  1055. * @default false
  1056. */
  1057. useBrowserRecommendedResolution : {
  1058. get : function() {
  1059. return this._cesiumWidget.useBrowserRecommendedResolution;
  1060. },
  1061. set : function(value) {
  1062. this._cesiumWidget.useBrowserRecommendedResolution = value;
  1063. }
  1064. },
  1065. /**
  1066. * Gets or sets whether or not data sources can temporarily pause
  1067. * animation in order to avoid showing an incomplete picture to the user.
  1068. * For example, if asynchronous primitives are being processed in the
  1069. * background, the clock will not advance until the geometry is ready.
  1070. *
  1071. * @memberof Viewer.prototype
  1072. *
  1073. * @type {Boolean}
  1074. */
  1075. allowDataSourcesToSuspendAnimation : {
  1076. get : function() {
  1077. return this._allowDataSourcesToSuspendAnimation;
  1078. },
  1079. set : function(value) {
  1080. this._allowDataSourcesToSuspendAnimation = value;
  1081. }
  1082. },
  1083. /**
  1084. * Gets or sets the Entity instance currently being tracked by the camera.
  1085. * @memberof Viewer.prototype
  1086. * @type {Entity}
  1087. */
  1088. trackedEntity : {
  1089. get : function() {
  1090. return this._trackedEntity;
  1091. },
  1092. set : function(value) {
  1093. if (this._trackedEntity !== value) {
  1094. this._trackedEntity = value;
  1095. //Cancel any pending zoom
  1096. cancelZoom(this);
  1097. var scene = this.scene;
  1098. var sceneMode = scene.mode;
  1099. //Stop tracking
  1100. if (!defined(value) || !defined(value.position)) {
  1101. this._needTrackedEntityUpdate = false;
  1102. if (sceneMode === SceneMode.COLUMBUS_VIEW || sceneMode === SceneMode.SCENE2D) {
  1103. scene.screenSpaceCameraController.enableTranslate = true;
  1104. }
  1105. if (sceneMode === SceneMode.COLUMBUS_VIEW || sceneMode === SceneMode.SCENE3D) {
  1106. scene.screenSpaceCameraController.enableTilt = true;
  1107. }
  1108. this._entityView = undefined;
  1109. this.camera.lookAtTransform(Matrix4.IDENTITY);
  1110. } else {
  1111. //We can't start tracking immediately, so we set a flag and start tracking
  1112. //when the bounding sphere is ready (most likely next frame).
  1113. this._needTrackedEntityUpdate = true;
  1114. }
  1115. this._trackedEntityChanged.raiseEvent(value);
  1116. this.scene.requestRender();
  1117. }
  1118. }
  1119. },
  1120. /**
  1121. * Gets or sets the object instance for which to display a selection indicator.
  1122. * @memberof Viewer.prototype
  1123. * @type {Entity}
  1124. */
  1125. selectedEntity : {
  1126. get : function() {
  1127. return this._selectedEntity;
  1128. },
  1129. set : function(value) {
  1130. if (this._selectedEntity !== value) {
  1131. this._selectedEntity = value;
  1132. var selectionIndicatorViewModel = defined(this._selectionIndicator) ? this._selectionIndicator.viewModel : undefined;
  1133. if (defined(value)) {
  1134. if (defined(selectionIndicatorViewModel)) {
  1135. selectionIndicatorViewModel.animateAppear();
  1136. }
  1137. } else if (defined(selectionIndicatorViewModel)) {
  1138. // Leave the info text in place here, it is needed during the exit animation.
  1139. selectionIndicatorViewModel.animateDepart();
  1140. }
  1141. this._selectedEntityChanged.raiseEvent(value);
  1142. }
  1143. }
  1144. },
  1145. /**
  1146. * Gets the event that is raised when the selected entity changes.
  1147. * @memberof Viewer.prototype
  1148. * @type {Event}
  1149. * @readonly
  1150. */
  1151. selectedEntityChanged : {
  1152. get : function() {
  1153. return this._selectedEntityChanged;
  1154. }
  1155. },
  1156. /**
  1157. * Gets the event that is raised when the tracked entity changes.
  1158. * @memberof Viewer.prototype
  1159. * @type {Event}
  1160. * @readonly
  1161. */
  1162. trackedEntityChanged : {
  1163. get : function() {
  1164. return this._trackedEntityChanged;
  1165. }
  1166. },
  1167. /**
  1168. * Gets or sets the data source to track with the viewer's clock.
  1169. * @memberof Viewer.prototype
  1170. * @type {DataSource}
  1171. */
  1172. clockTrackedDataSource : {
  1173. get : function() {
  1174. return this._clockTrackedDataSource;
  1175. },
  1176. set : function(value) {
  1177. if (this._clockTrackedDataSource !== value) {
  1178. this._clockTrackedDataSource = value;
  1179. trackDataSourceClock(this._timeline, this.clock, value);
  1180. }
  1181. }
  1182. }
  1183. });
  1184. /**
  1185. * Extends the base viewer functionality with the provided mixin.
  1186. * A mixin may add additional properties, functions, or other behavior
  1187. * to the provided viewer instance.
  1188. *
  1189. * @param {Viewer~ViewerMixin} mixin The Viewer mixin to add to this instance.
  1190. * @param {Object} [options] The options object to be passed to the mixin function.
  1191. *
  1192. * @see viewerDragDropMixin
  1193. */
  1194. Viewer.prototype.extend = function(mixin, options) {
  1195. //>>includeStart('debug', pragmas.debug);
  1196. if (!defined(mixin)) {
  1197. throw new DeveloperError('mixin is required.');
  1198. }
  1199. //>>includeEnd('debug')
  1200. mixin(this, options);
  1201. };
  1202. /**
  1203. * Resizes the widget to match the container size.
  1204. * This function is called automatically as needed unless
  1205. * <code>useDefaultRenderLoop</code> is set to false.
  1206. */
  1207. Viewer.prototype.resize = function() {
  1208. var cesiumWidget = this._cesiumWidget;
  1209. var container = this._container;
  1210. var width = container.clientWidth;
  1211. var height = container.clientHeight;
  1212. var animationExists = defined(this._animation);
  1213. var timelineExists = defined(this._timeline);
  1214. cesiumWidget.resize();
  1215. if (width === this._lastWidth && height === this._lastHeight) {
  1216. return;
  1217. }
  1218. var panelMaxHeight = height - 125;
  1219. var baseLayerPickerDropDown = this._baseLayerPickerDropDown;
  1220. if (defined(baseLayerPickerDropDown)) {
  1221. baseLayerPickerDropDown.style.maxHeight = panelMaxHeight + 'px';
  1222. }
  1223. if (defined(this._geocoder)) {
  1224. var geocoderSuggestions = this._geocoder.searchSuggestionsContainer;
  1225. geocoderSuggestions.style.maxHeight = panelMaxHeight + 'px';
  1226. }
  1227. if (defined(this._infoBox)) {
  1228. this._infoBox.viewModel.maxHeight = panelMaxHeight;
  1229. }
  1230. var timeline = this._timeline;
  1231. var animationContainer;
  1232. var animationWidth = 0;
  1233. var creditLeft = 0;
  1234. var creditBottom = 0;
  1235. if (animationExists && window.getComputedStyle(this._animation.container).visibility !== 'hidden') {
  1236. var lastWidth = this._lastWidth;
  1237. animationContainer = this._animation.container;
  1238. if (width > 900) {
  1239. animationWidth = 169;
  1240. if (lastWidth <= 900) {
  1241. animationContainer.style.width = '169px';
  1242. animationContainer.style.height = '112px';
  1243. this._animation.resize();
  1244. }
  1245. } else if (width >= 600) {
  1246. animationWidth = 136;
  1247. if (lastWidth < 600 || lastWidth > 900) {
  1248. animationContainer.style.width = '136px';
  1249. animationContainer.style.height = '90px';
  1250. this._animation.resize();
  1251. }
  1252. } else {
  1253. animationWidth = 106;
  1254. if (lastWidth > 600 || lastWidth === 0) {
  1255. animationContainer.style.width = '106px';
  1256. animationContainer.style.height = '70px';
  1257. this._animation.resize();
  1258. }
  1259. }
  1260. creditLeft = animationWidth + 5;
  1261. }
  1262. if (timelineExists && window.getComputedStyle(this._timeline.container).visibility !== 'hidden') {
  1263. var fullscreenButton = this._fullscreenButton;
  1264. var vrButton = this._vrButton;
  1265. var timelineContainer = timeline.container;
  1266. var timelineStyle = timelineContainer.style;
  1267. creditBottom = timelineContainer.clientHeight + 3;
  1268. timelineStyle.left = animationWidth + 'px';
  1269. var pixels = 0;
  1270. if (defined(fullscreenButton)) {
  1271. pixels += fullscreenButton.container.clientWidth;
  1272. }
  1273. if (defined(vrButton)) {
  1274. pixels += vrButton.container.clientWidth;
  1275. }
  1276. timelineStyle.right = pixels + 'px';
  1277. timeline.resize();
  1278. }
  1279. this._bottomContainer.style.left = creditLeft + 'px';
  1280. this._bottomContainer.style.bottom = creditBottom + 'px';
  1281. this._lastWidth = width;
  1282. this._lastHeight = height;
  1283. };
  1284. /**
  1285. * This forces the widget to re-think its layout, including
  1286. * widget sizes and credit placement.
  1287. */
  1288. Viewer.prototype.forceResize = function() {
  1289. this._lastWidth = 0;
  1290. this.resize();
  1291. };
  1292. /**
  1293. * Renders the scene. This function is called automatically
  1294. * unless <code>useDefaultRenderLoop</code> is set to false;
  1295. */
  1296. Viewer.prototype.render = function() {
  1297. this._cesiumWidget.render();
  1298. };
  1299. /**
  1300. * @returns {Boolean} true if the object has been destroyed, false otherwise.
  1301. */
  1302. Viewer.prototype.isDestroyed = function() {
  1303. return false;
  1304. };
  1305. /**
  1306. * Destroys the widget. Should be called if permanently
  1307. * removing the widget from layout.
  1308. */
  1309. Viewer.prototype.destroy = function() {
  1310. var i;
  1311. this.screenSpaceEventHandler.removeInputAction(ScreenSpaceEventType.LEFT_CLICK);
  1312. this.screenSpaceEventHandler.removeInputAction(ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
  1313. // Unsubscribe from data sources
  1314. var dataSources = this.dataSources;
  1315. var dataSourceLength = dataSources.length;
  1316. for (i = 0; i < dataSourceLength; i++) {
  1317. this._dataSourceRemoved(dataSources, dataSources.get(i));
  1318. }
  1319. this._dataSourceRemoved(undefined, this._dataSourceDisplay.defaultDataSource);
  1320. this._container.removeChild(this._element);
  1321. this._element.removeChild(this._toolbar);
  1322. this._eventHelper.removeAll();
  1323. if (defined(this._geocoder)) {
  1324. this._geocoder = this._geocoder.destroy();
  1325. }
  1326. if (defined(this._homeButton)) {
  1327. this._homeButton = this._homeButton.destroy();
  1328. }
  1329. if (defined(this._sceneModePicker)) {
  1330. this._sceneModePicker = this._sceneModePicker.destroy();
  1331. }
  1332. if (defined(this._projectionPicker)) {
  1333. this._projectionPicker = this._projectionPicker.destroy();
  1334. }
  1335. if (defined(this._baseLayerPicker)) {
  1336. this._baseLayerPicker = this._baseLayerPicker.destroy();
  1337. }
  1338. if (defined(this._animation)) {
  1339. this._element.removeChild(this._animation.container);
  1340. this._animation = this._animation.destroy();
  1341. }
  1342. if (defined(this._timeline)) {
  1343. this._timeline.removeEventListener('settime', onTimelineScrubfunction, false);
  1344. this._element.removeChild(this._timeline.container);
  1345. this._timeline = this._timeline.destroy();
  1346. }
  1347. if (defined(this._fullscreenButton)) {
  1348. this._fullscreenSubscription.dispose();
  1349. this._element.removeChild(this._fullscreenButton.container);
  1350. this._fullscreenButton = this._fullscreenButton.destroy();
  1351. }
  1352. if (defined(this._vrButton)) {
  1353. this._vrSubscription.dispose();
  1354. this._vrModeSubscription.dispose();
  1355. this._element.removeChild(this._vrButton.container);
  1356. this._vrButton = this._vrButton.destroy();
  1357. }
  1358. if (defined(this._infoBox)) {
  1359. this._element.removeChild(this._infoBox.container);
  1360. this._infoBox = this._infoBox.destroy();
  1361. }
  1362. if (defined(this._selectionIndicator)) {
  1363. this._element.removeChild(this._selectionIndicator.container);
  1364. this._selectionIndicator = this._selectionIndicator.destroy();
  1365. }
  1366. if (this._destroyClockViewModel) {
  1367. this._clockViewModel = this._clockViewModel.destroy();
  1368. }
  1369. this._dataSourceDisplay = this._dataSourceDisplay.destroy();
  1370. this._cesiumWidget = this._cesiumWidget.destroy();
  1371. if (this._destroyDataSourceCollection) {
  1372. this._dataSourceCollection = this._dataSourceCollection.destroy();
  1373. }
  1374. return destroyObject(this);
  1375. };
  1376. /**
  1377. * @private
  1378. */
  1379. Viewer.prototype._dataSourceAdded = function(dataSourceCollection, dataSource) {
  1380. var entityCollection = dataSource.entities;
  1381. entityCollection.collectionChanged.addEventListener(Viewer.prototype._onEntityCollectionChanged, this);
  1382. };
  1383. /**
  1384. * @private
  1385. */
  1386. Viewer.prototype._dataSourceRemoved = function(dataSourceCollection, dataSource) {
  1387. var entityCollection = dataSource.entities;
  1388. entityCollection.collectionChanged.removeEventListener(Viewer.prototype._onEntityCollectionChanged, this);
  1389. if (defined(this.trackedEntity)) {
  1390. if (entityCollection.getById(this.trackedEntity.id) === this.trackedEntity) {
  1391. this.trackedEntity = undefined;
  1392. }
  1393. }
  1394. if (defined(this.selectedEntity)) {
  1395. if (entityCollection.getById(this.selectedEntity.id) === this.selectedEntity) {
  1396. this.selectedEntity = undefined;
  1397. }
  1398. }
  1399. };
  1400. /**
  1401. * @private
  1402. */
  1403. Viewer.prototype._onTick = function(clock) {
  1404. var time = clock.currentTime;
  1405. var isUpdated = this._dataSourceDisplay.update(time);
  1406. if (this._allowDataSourcesToSuspendAnimation) {
  1407. this._clockViewModel.canAnimate = isUpdated;
  1408. }
  1409. var entityView = this._entityView;
  1410. if (defined(entityView)) {
  1411. var trackedEntity = this._trackedEntity;
  1412. var trackedState = this._dataSourceDisplay.getBoundingSphere(trackedEntity, false, boundingSphereScratch);
  1413. if (trackedState === BoundingSphereState.DONE) {
  1414. entityView.update(time, boundingSphereScratch);
  1415. }
  1416. }
  1417. var position;
  1418. var enableCamera = false;
  1419. var selectedEntity = this.selectedEntity;
  1420. var showSelection = defined(selectedEntity) && this._enableInfoOrSelection;
  1421. if (showSelection && selectedEntity.isShowing && selectedEntity.isAvailable(time)) {
  1422. var state = this._dataSourceDisplay.getBoundingSphere(selectedEntity, true, boundingSphereScratch);
  1423. if (state !== BoundingSphereState.FAILED) {
  1424. position = boundingSphereScratch.center;
  1425. } else if (defined(selectedEntity.position)) {
  1426. position = selectedEntity.position.getValue(time, position);
  1427. }
  1428. enableCamera = defined(position);
  1429. }
  1430. var selectionIndicatorViewModel = defined(this._selectionIndicator) ? this._selectionIndicator.viewModel : undefined;
  1431. if (defined(selectionIndicatorViewModel)) {
  1432. selectionIndicatorViewModel.position = Cartesian3.clone(position, selectionIndicatorViewModel.position);
  1433. selectionIndicatorViewModel.showSelection = showSelection && enableCamera;
  1434. selectionIndicatorViewModel.update();
  1435. }
  1436. var infoBoxViewModel = defined(this._infoBox) ? this._infoBox.viewModel : undefined;
  1437. if (defined(infoBoxViewModel)) {
  1438. infoBoxViewModel.showInfo = showSelection;
  1439. infoBoxViewModel.enableCamera = enableCamera;
  1440. infoBoxViewModel.isCameraTracking = (this.trackedEntity === this.selectedEntity);
  1441. if (showSelection) {
  1442. infoBoxViewModel.titleText = defaultValue(selectedEntity.name, selectedEntity.id);
  1443. infoBoxViewModel.description = Property.getValueOrDefault(selectedEntity.description, time, '');
  1444. } else {
  1445. infoBoxViewModel.titleText = '';
  1446. infoBoxViewModel.description = '';
  1447. }
  1448. }
  1449. };
  1450. /**
  1451. * @private
  1452. */
  1453. Viewer.prototype._onEntityCollectionChanged = function(collection, added, removed) {
  1454. var length = removed.length;
  1455. for (var i = 0; i < length; i++) {
  1456. var removedObject = removed[i];
  1457. if (this.trackedEntity === removedObject) {
  1458. this.trackedEntity = undefined;
  1459. }
  1460. if (this.selectedEntity === removedObject) {
  1461. this.selectedEntity = undefined;
  1462. }
  1463. }
  1464. };
  1465. /**
  1466. * @private
  1467. */
  1468. Viewer.prototype._onInfoBoxCameraClicked = function(infoBoxViewModel) {
  1469. if (infoBoxViewModel.isCameraTracking && (this.trackedEntity === this.selectedEntity)) {
  1470. this.trackedEntity = undefined;
  1471. } else {
  1472. var selectedEntity = this.selectedEntity;
  1473. var position = selectedEntity.position;
  1474. if (defined(position)) {
  1475. this.trackedEntity = this.selectedEntity;
  1476. } else {
  1477. this.zoomTo(this.selectedEntity);
  1478. }
  1479. }
  1480. };
  1481. /**
  1482. * @private
  1483. */
  1484. Viewer.prototype._clearTrackedObject = function() {
  1485. this.trackedEntity = undefined;
  1486. };
  1487. /**
  1488. * @private
  1489. */
  1490. Viewer.prototype._onInfoBoxClockClicked = function(infoBoxViewModel) {
  1491. this.selectedEntity = undefined;
  1492. };
  1493. /**
  1494. * @private
  1495. */
  1496. Viewer.prototype._clearObjects = function() {
  1497. this.trackedEntity = undefined;
  1498. this.selectedEntity = undefined;
  1499. };
  1500. /**
  1501. * @private
  1502. */
  1503. Viewer.prototype._onDataSourceChanged = function(dataSource) {
  1504. if (this.clockTrackedDataSource === dataSource) {
  1505. trackDataSourceClock(this.timeline, this.clock, dataSource);
  1506. }
  1507. };
  1508. /**
  1509. * @private
  1510. */
  1511. Viewer.prototype._onDataSourceAdded = function(dataSourceCollection, dataSource) {
  1512. if (this._automaticallyTrackDataSourceClocks) {
  1513. this.clockTrackedDataSource = dataSource;
  1514. }
  1515. var id = dataSource.entities.id;
  1516. var removalFunc = this._eventHelper.add(dataSource.changedEvent, Viewer.prototype._onDataSourceChanged, this);
  1517. this._dataSourceChangedListeners[id] = removalFunc;
  1518. };
  1519. /**
  1520. * @private
  1521. */
  1522. Viewer.prototype._onDataSourceRemoved = function(dataSourceCollection, dataSource) {
  1523. var resetClock = (this.clockTrackedDataSource === dataSource);
  1524. var id = dataSource.entities.id;
  1525. this._dataSourceChangedListeners[id]();
  1526. this._dataSourceChangedListeners[id] = undefined;
  1527. if (resetClock) {
  1528. var numDataSources = dataSourceCollection.length;
  1529. if (this._automaticallyTrackDataSourceClocks && numDataSources > 0) {
  1530. this.clockTrackedDataSource = dataSourceCollection.get(numDataSources - 1);
  1531. } else {
  1532. this.clockTrackedDataSource = undefined;
  1533. }
  1534. }
  1535. };
  1536. /**
  1537. * Asynchronously sets the camera to view the provided entity, entities, or data source.
  1538. * If the data source is still in the process of loading or the visualization is otherwise still loading,
  1539. * this method waits for the data to be ready before performing the zoom.
  1540. *
  1541. * <p>The offset is heading/pitch/range in the local east-north-up reference frame centered at the center of the bounding sphere.
  1542. * The heading and the pitch angles are defined in the local east-north-up reference frame.
  1543. * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
  1544. * angles are above the plane. Negative pitch angles are below the plane. The range is the distance from the center. If the range is
  1545. * zero, a range will be computed such that the whole bounding sphere is visible.</p>
  1546. *
  1547. * <p>In 2D, there must be a top down view. The camera will be placed above the target looking down. The height above the
  1548. * target will be the range. The heading will be determined from the offset. If the heading cannot be
  1549. * determined from the offset, the heading will be north.</p>
  1550. *
  1551. * @param {Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud|Promise.<Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud>} target The entity, array of entities, entity collection, data source, Cesium3DTileset, point cloud, or imagery layer to view. You can also pass a promise that resolves to one of the previously mentioned types.
  1552. * @param {HeadingPitchRange} [offset] The offset from the center of the entity in the local east-north-up reference frame.
  1553. * @returns {Promise.<Boolean>} A Promise that resolves to true if the zoom was successful or false if the target is not currently visualized in the scene or the zoom was cancelled.
  1554. */
  1555. Viewer.prototype.zoomTo = function(target, offset) {
  1556. var options = {
  1557. offset : offset
  1558. };
  1559. return zoomToOrFly(this, target, options, false);
  1560. };
  1561. /**
  1562. * Flies the camera to the provided entity, entities, or data source.
  1563. * If the data source is still in the process of loading or the visualization is otherwise still loading,
  1564. * this method waits for the data to be ready before performing the flight.
  1565. *
  1566. * <p>The offset is heading/pitch/range in the local east-north-up reference frame centered at the center of the bounding sphere.
  1567. * The heading and the pitch angles are defined in the local east-north-up reference frame.
  1568. * The heading is the angle from y axis and increasing towards the x axis. Pitch is the rotation from the xy-plane. Positive pitch
  1569. * angles are above the plane. Negative pitch angles are below the plane. The range is the distance from the center. If the range is
  1570. * zero, a range will be computed such that the whole bounding sphere is visible.</p>
  1571. *
  1572. * <p>In 2D, there must be a top down view. The camera will be placed above the target looking down. The height above the
  1573. * target will be the range. The heading will be determined from the offset. If the heading cannot be
  1574. * determined from the offset, the heading will be north.</p>
  1575. *
  1576. * @param {Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud|Promise.<Entity|Entity[]|EntityCollection|DataSource|ImageryLayer|Cesium3DTileset|TimeDynamicPointCloud>} target The entity, array of entities, entity collection, data source, Cesium3DTileset, point cloud, or imagery layer to view. You can also pass a promise that resolves to one of the previously mentioned types.
  1577. * @param {Object} [options] Object with the following properties:
  1578. * @param {Number} [options.duration=3.0] The duration of the flight in seconds.
  1579. * @param {Number} [options.maximumHeight] The maximum height at the peak of the flight.
  1580. * @param {HeadingPitchRange} [options.offset] The offset from the target in the local east-north-up reference frame centered at the target.
  1581. * @returns {Promise.<Boolean>} A Promise that resolves to true if the flight was successful or false if the target is not currently visualized in the scene or the flight was cancelled. //TODO: Cleanup entity mentions
  1582. */
  1583. Viewer.prototype.flyTo = function(target, options) {
  1584. return zoomToOrFly(this, target, options, true);
  1585. };
  1586. function zoomToOrFly(that, zoomTarget, options, isFlight) {
  1587. //>>includeStart('debug', pragmas.debug);
  1588. if (!defined(zoomTarget)) {
  1589. throw new DeveloperError('zoomTarget is required.');
  1590. }
  1591. //>>includeEnd('debug');
  1592. cancelZoom(that);
  1593. //We can't actually perform the zoom until all visualization is ready and
  1594. //bounding spheres have been computed. Therefore we create and return
  1595. //a deferred which will be resolved as part of the post-render step in the
  1596. //frame that actually performs the zoom
  1597. var zoomPromise = when.defer();
  1598. that._zoomPromise = zoomPromise;
  1599. that._zoomIsFlight = isFlight;
  1600. that._zoomOptions = options;
  1601. when(zoomTarget, function(zoomTarget) {
  1602. //Only perform the zoom if it wasn't cancelled before the promise resolved.
  1603. if (that._zoomPromise !== zoomPromise) {
  1604. return;
  1605. }
  1606. //If the zoom target is a rectangular imagery in an ImageLayer
  1607. if (zoomTarget instanceof ImageryLayer) {
  1608. zoomTarget.getViewableRectangle().then(function(rectangle) {
  1609. return computeFlyToLocationForRectangle(rectangle, that.scene);
  1610. }).then(function(position) {
  1611. //Only perform the zoom if it wasn't cancelled before the promise was resolved
  1612. if (that._zoomPromise === zoomPromise) {
  1613. that._zoomTarget = position;
  1614. }
  1615. });
  1616. return;
  1617. }
  1618. //If the zoom target is a Cesium3DTileset
  1619. if (zoomTarget instanceof Cesium3DTileset) {
  1620. that._zoomTarget = zoomTarget;
  1621. return;
  1622. }
  1623. //If the zoom target is a TimeDynamicPointCloud
  1624. if (zoomTarget instanceof TimeDynamicPointCloud) {
  1625. that._zoomTarget = zoomTarget;
  1626. return;
  1627. }
  1628. //If the zoom target is a data source, and it's in the middle of loading, wait for it to finish loading.
  1629. if (zoomTarget.isLoading && defined(zoomTarget.loadingEvent)) {
  1630. var removeEvent = zoomTarget.loadingEvent.addEventListener(function() {
  1631. removeEvent();
  1632. //Only perform the zoom if it wasn't cancelled before the data source finished.
  1633. if (that._zoomPromise === zoomPromise) {
  1634. that._zoomTarget = zoomTarget.entities.values.slice(0);
  1635. }
  1636. });
  1637. return;
  1638. }
  1639. //Zoom target is already an array, just copy it and return.
  1640. if (isArray(zoomTarget)) {
  1641. that._zoomTarget = zoomTarget.slice(0);
  1642. return;
  1643. }
  1644. //If zoomTarget is an EntityCollection, this will retrieve the array
  1645. zoomTarget = defaultValue(zoomTarget.values, zoomTarget);
  1646. //If zoomTarget is a DataSource, this will retrieve the array.
  1647. if (defined(zoomTarget.entities)) {
  1648. zoomTarget = zoomTarget.entities.values;
  1649. }
  1650. //Zoom target is already an array, just copy it and return.
  1651. if (isArray(zoomTarget)) {
  1652. that._zoomTarget = zoomTarget.slice(0);
  1653. } else {
  1654. //Single entity
  1655. that._zoomTarget = [zoomTarget];
  1656. }
  1657. });
  1658. that.scene.requestRender();
  1659. return zoomPromise.promise;
  1660. }
  1661. function clearZoom(viewer) {
  1662. viewer._zoomPromise = undefined;
  1663. viewer._zoomTarget = undefined;
  1664. viewer._zoomOptions = undefined;
  1665. }
  1666. function cancelZoom(viewer) {
  1667. var zoomPromise = viewer._zoomPromise;
  1668. if (defined(zoomPromise)) {
  1669. clearZoom(viewer);
  1670. zoomPromise.resolve(false);
  1671. }
  1672. }
  1673. /**
  1674. * @private
  1675. */
  1676. Viewer.prototype._postRender = function() {
  1677. updateZoomTarget(this);
  1678. updateTrackedEntity(this);
  1679. };
  1680. function updateZoomTarget(viewer) {
  1681. var target = viewer._zoomTarget;
  1682. if (!defined(target) || viewer.scene.mode === SceneMode.MORPHING) {
  1683. return;
  1684. }
  1685. var scene = viewer.scene;
  1686. var camera = scene.camera;
  1687. var zoomPromise = viewer._zoomPromise;
  1688. var zoomOptions = defaultValue(viewer._zoomOptions, {});
  1689. var options;
  1690. var boundingSphere;
  1691. // If zoomTarget was Cesium3DTileset
  1692. if (target instanceof Cesium3DTileset) {
  1693. return target.readyPromise.then(function() {
  1694. var boundingSphere = target.boundingSphere;
  1695. // If offset was originally undefined then give it base value instead of empty object
  1696. if (!defined(zoomOptions.offset)) {
  1697. zoomOptions.offset = new HeadingPitchRange(0.0, -0.5, boundingSphere.radius);
  1698. }
  1699. options = {
  1700. offset : zoomOptions.offset,
  1701. duration : zoomOptions.duration,
  1702. maximumHeight : zoomOptions.maximumHeight,
  1703. complete : function() {
  1704. zoomPromise.resolve(true);
  1705. },
  1706. cancel : function() {
  1707. zoomPromise.resolve(false);
  1708. }
  1709. };
  1710. if (viewer._zoomIsFlight) {
  1711. camera.flyToBoundingSphere(target.boundingSphere, options);
  1712. } else {
  1713. camera.viewBoundingSphere(boundingSphere, zoomOptions.offset);
  1714. camera.lookAtTransform(Matrix4.IDENTITY);
  1715. // Finish the promise
  1716. zoomPromise.resolve(true);
  1717. }
  1718. clearZoom(viewer);
  1719. });
  1720. }
  1721. // If zoomTarget was TimeDynamicPointCloud
  1722. if (target instanceof TimeDynamicPointCloud) {
  1723. return target.readyPromise.then(function() {
  1724. var boundingSphere = target.boundingSphere;
  1725. // If offset was originally undefined then give it base value instead of empty object
  1726. if (!defined(zoomOptions.offset)) {
  1727. zoomOptions.offset = new HeadingPitchRange(0.0, -0.5, boundingSphere.radius);
  1728. }
  1729. options = {
  1730. offset : zoomOptions.offset,
  1731. duration : zoomOptions.duration,
  1732. maximumHeight : zoomOptions.maximumHeight,
  1733. complete : function() {
  1734. zoomPromise.resolve(true);
  1735. },
  1736. cancel : function() {
  1737. zoomPromise.resolve(false);
  1738. }
  1739. };
  1740. if (viewer._zoomIsFlight) {
  1741. camera.flyToBoundingSphere(boundingSphere, options);
  1742. } else {
  1743. camera.viewBoundingSphere(boundingSphere, zoomOptions.offset);
  1744. camera.lookAtTransform(Matrix4.IDENTITY);
  1745. // Finish the promise
  1746. zoomPromise.resolve(true);
  1747. }
  1748. clearZoom(viewer);
  1749. });
  1750. }
  1751. // If zoomTarget was an ImageryLayer
  1752. if (target instanceof Cartographic) {
  1753. options = {
  1754. destination : scene.mapProjection.ellipsoid.cartographicToCartesian(target),
  1755. duration : zoomOptions.duration,
  1756. maximumHeight : zoomOptions.maximumHeight,
  1757. complete : function() {
  1758. zoomPromise.resolve(true);
  1759. },
  1760. cancel : function() {
  1761. zoomPromise.resolve(false);
  1762. }
  1763. };
  1764. if (viewer._zoomIsFlight) {
  1765. camera.flyTo(options);
  1766. } else {
  1767. camera.setView(options);
  1768. zoomPromise.resolve(true);
  1769. }
  1770. clearZoom(viewer);
  1771. return;
  1772. }
  1773. var entities = target;
  1774. var boundingSpheres = [];
  1775. for (var i = 0, len = entities.length; i < len; i++) {
  1776. var state = viewer._dataSourceDisplay.getBoundingSphere(entities[i], false, boundingSphereScratch);
  1777. if (state === BoundingSphereState.PENDING) {
  1778. return;
  1779. } else if (state !== BoundingSphereState.FAILED) {
  1780. boundingSpheres.push(BoundingSphere.clone(boundingSphereScratch));
  1781. }
  1782. }
  1783. if (boundingSpheres.length === 0) {
  1784. cancelZoom(viewer);
  1785. return;
  1786. }
  1787. //Stop tracking the current entity.
  1788. viewer.trackedEntity = undefined;
  1789. boundingSphere = BoundingSphere.fromBoundingSpheres(boundingSpheres);
  1790. if (!viewer._zoomIsFlight) {
  1791. camera.viewBoundingSphere(boundingSphere, zoomOptions.offset);
  1792. camera.lookAtTransform(Matrix4.IDENTITY);
  1793. clearZoom(viewer);
  1794. zoomPromise.resolve(true);
  1795. } else {
  1796. clearZoom(viewer);
  1797. camera.flyToBoundingSphere(boundingSphere, {
  1798. duration : zoomOptions.duration,
  1799. maximumHeight : zoomOptions.maximumHeight,
  1800. complete : function() {
  1801. zoomPromise.resolve(true);
  1802. },
  1803. cancel : function() {
  1804. zoomPromise.resolve(false);
  1805. },
  1806. offset : zoomOptions.offset
  1807. });
  1808. }
  1809. }
  1810. function updateTrackedEntity(viewer) {
  1811. if (!viewer._needTrackedEntityUpdate) {
  1812. return;
  1813. }
  1814. var trackedEntity = viewer._trackedEntity;
  1815. var currentTime = viewer.clock.currentTime;
  1816. //Verify we have a current position at this time. This is only triggered if a position
  1817. //has become undefined after trackedEntity is set but before the boundingSphere has been
  1818. //computed. In this case, we will track the entity once it comes back into existence.
  1819. var currentPosition = Property.getValueOrUndefined(trackedEntity.position, currentTime);
  1820. if (!defined(currentPosition)) {
  1821. return;
  1822. }
  1823. var scene = viewer.scene;
  1824. var state = viewer._dataSourceDisplay.getBoundingSphere(trackedEntity, false, boundingSphereScratch);
  1825. if (state === BoundingSphereState.PENDING) {
  1826. return;
  1827. }
  1828. var sceneMode = scene.mode;
  1829. if (sceneMode === SceneMode.COLUMBUS_VIEW || sceneMode === SceneMode.SCENE2D) {
  1830. scene.screenSpaceCameraController.enableTranslate = false;
  1831. }
  1832. if (sceneMode === SceneMode.COLUMBUS_VIEW || sceneMode === SceneMode.SCENE3D) {
  1833. scene.screenSpaceCameraController.enableTilt = false;
  1834. }
  1835. var bs = state !== BoundingSphereState.FAILED ? boundingSphereScratch : undefined;
  1836. viewer._entityView = new EntityView(trackedEntity, scene, scene.mapProjection.ellipsoid);
  1837. viewer._entityView.update(currentTime, bs);
  1838. viewer._needTrackedEntityUpdate = false;
  1839. }
  1840. /**
  1841. * A function that augments a Viewer instance with additional functionality.
  1842. * @callback Viewer~ViewerMixin
  1843. * @param {Viewer} viewer The viewer instance.
  1844. * @param {Object} options Options object to be passed to the mixin function.
  1845. *
  1846. * @see Viewer#extend
  1847. */
  1848. export default Viewer;