Viewer.js 79 KB

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