CesiumWidget.js 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. import buildModuleUrl from "../Core/buildModuleUrl.js";
  2. import Cartesian3 from "../Core/Cartesian3.js";
  3. import Clock from "../Core/Clock.js";
  4. import defaultValue from "../Core/defaultValue.js";
  5. import defined from "../Core/defined.js";
  6. import deprecationWarning from "../Core/deprecationWarning.js";
  7. import destroyObject from "../Core/destroyObject.js";
  8. import DeveloperError from "../Core/DeveloperError.js";
  9. import Ellipsoid from "../Core/Ellipsoid.js";
  10. import FeatureDetection from "../Core/FeatureDetection.js";
  11. import formatError from "../Core/formatError.js";
  12. import getElement from "../DataSources/getElement.js";
  13. import Globe from "../Scene/Globe.js";
  14. import ImageryLayer from "../Scene/ImageryLayer.js";
  15. import Moon from "../Scene/Moon.js";
  16. import Scene from "../Scene/Scene.js";
  17. import SceneMode from "../Scene/SceneMode.js";
  18. import ScreenSpaceEventHandler from "../Core/ScreenSpaceEventHandler.js";
  19. import ShadowMode from "../Scene/ShadowMode.js";
  20. import SkyAtmosphere from "../Scene/SkyAtmosphere.js";
  21. import SkyBox from "../Scene/SkyBox.js";
  22. import Sun from "../Scene/Sun.js";
  23. function getDefaultSkyBoxUrl(suffix) {
  24. return buildModuleUrl(`Assets/Textures/SkyBox/tycho2t3_80_${suffix}.jpg`);
  25. }
  26. function startRenderLoop(widget) {
  27. widget._renderLoopRunning = true;
  28. let lastFrameTime = 0;
  29. function render(frameTime) {
  30. if (widget.isDestroyed()) {
  31. return;
  32. }
  33. if (widget._useDefaultRenderLoop) {
  34. try {
  35. const targetFrameRate = widget._targetFrameRate;
  36. if (!defined(targetFrameRate)) {
  37. widget.resize();
  38. widget.render();
  39. requestAnimationFrame(render);
  40. } else {
  41. const interval = 1000.0 / targetFrameRate;
  42. const delta = frameTime - lastFrameTime;
  43. if (delta > interval) {
  44. widget.resize();
  45. widget.render();
  46. lastFrameTime = frameTime - (delta % interval);
  47. }
  48. requestAnimationFrame(render);
  49. }
  50. } catch (error) {
  51. widget._useDefaultRenderLoop = false;
  52. widget._renderLoopRunning = false;
  53. if (widget._showRenderLoopErrors) {
  54. const title =
  55. "An error occurred while rendering. Rendering has stopped.";
  56. widget.showErrorPanel(title, undefined, error);
  57. }
  58. }
  59. } else {
  60. widget._renderLoopRunning = false;
  61. }
  62. }
  63. requestAnimationFrame(render);
  64. }
  65. function configurePixelRatio(widget) {
  66. let pixelRatio = widget._useBrowserRecommendedResolution
  67. ? 1.0
  68. : window.devicePixelRatio;
  69. pixelRatio *= widget._resolutionScale;
  70. if (defined(widget._scene)) {
  71. widget._scene.pixelRatio = pixelRatio;
  72. }
  73. return pixelRatio;
  74. }
  75. function configureCanvasSize(widget) {
  76. const canvas = widget._canvas;
  77. let width = canvas.clientWidth;
  78. let height = canvas.clientHeight;
  79. const pixelRatio = configurePixelRatio(widget);
  80. widget._canvasClientWidth = width;
  81. widget._canvasClientHeight = height;
  82. width *= pixelRatio;
  83. height *= pixelRatio;
  84. canvas.width = width;
  85. canvas.height = height;
  86. widget._canRender = width !== 0 && height !== 0;
  87. widget._lastDevicePixelRatio = window.devicePixelRatio;
  88. }
  89. function configureCameraFrustum(widget) {
  90. const canvas = widget._canvas;
  91. const width = canvas.width;
  92. const height = canvas.height;
  93. if (width !== 0 && height !== 0) {
  94. const frustum = widget._scene.camera.frustum;
  95. if (defined(frustum.aspectRatio)) {
  96. frustum.aspectRatio = width / height;
  97. } else {
  98. frustum.top = frustum.right * (height / width);
  99. frustum.bottom = -frustum.top;
  100. }
  101. }
  102. }
  103. /**
  104. * A widget containing a Cesium scene.
  105. *
  106. * @alias CesiumWidget
  107. * @constructor
  108. *
  109. * @param {Element|string} container The DOM element or ID that will contain the widget.
  110. * @param {object} [options] Object with the following properties:
  111. * @param {Clock} [options.clock=new Clock()] The clock to use to control current time.
  112. * @param {ImageryProvider | false} [options.imageryProvider=createWorldImagery()] The imagery provider to serve as the base layer. If set to <code>false</code>, no imagery provider will be added. Deprecated.
  113. * @param {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.
  114. * @param {TerrainProvider} [options.terrainProvider=new EllipsoidTerrainProvider] The terrain provider.
  115. * @param {Terrain} [options.terrain] A terrain object which handles asynchronous terrain provider. Can only specify if options.terrainProvider is undefined.
  116. * @param {SkyBox| false} [options.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.
  117. * @param {SkyAtmosphere | false} [options.skyAtmosphere] Blue sky, and the glow around the Earth's limb. Set to <code>false</code> to turn it off.
  118. * @param {SceneMode} [options.sceneMode=SceneMode.SCENE3D] The initial scene mode.
  119. * @param {boolean} [options.scene3DOnly=false] When <code>true</code>, each geometry instance will only be rendered in 3D to save GPU memory.
  120. * @param {boolean} [options.orderIndependentTranslucency=true] If true and the configuration supports it, use order independent translucency.
  121. * @param {MapProjection} [options.mapProjection=new GeographicProjection()] The map projection to use in 2D and Columbus View modes.
  122. * @param {Globe | false} [options.globe=new Globe(mapProjection.ellipsoid)] The globe to use in the scene. If set to <code>false</code>, no globe will be added.
  123. * @param {boolean} [options.useDefaultRenderLoop=true] True if this widget should control the render loop, false otherwise.
  124. * @param {boolean} [options.useBrowserRecommendedResolution=true] If true, render at the browser's recommended resolution and ignore <code>window.devicePixelRatio</code>.
  125. * @param {number} [options.targetFrameRate] The target frame rate when using the default render loop.
  126. * @param {boolean} [options.showRenderLoopErrors=true] If true, this widget will automatically display an HTML panel to the user containing the error, if a render loop error occurs.
  127. * @param {ContextOptions} [options.contextOptions] Context and WebGL creation properties passed to {@link Scene}.
  128. * @param {Element|string} [options.creditContainer] The DOM element or ID that will contain the {@link CreditDisplay}. If not specified, the credits are added
  129. * to the bottom of the widget itself.
  130. * @param {Element|string} [options.creditViewport] The DOM element or ID that will contain the credit pop up created by the {@link CreditDisplay}. If not specified, it will appear over the widget itself.
  131. * @param {boolean} [options.shadows=false] Determines if shadows are cast by light sources.
  132. * @param {ShadowMode} [options.terrainShadows=ShadowMode.RECEIVE_ONLY] Determines if the terrain casts or receives shadows from light sources.
  133. * @param {MapMode2D} [options.mapMode2D=MapMode2D.INFINITE_SCROLL] Determines if the 2D map is rotatable or can be scrolled infinitely in the horizontal direction.
  134. * @param {boolean} [options.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.
  135. * @param {boolean} [options.requestRenderMode=false] If true, rendering a frame will only occur when needed as determined by changes within the scene. Enabling improves performance of the application, 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}.
  136. * @param {number} [options.maximumRenderTimeChange=0.0] If requestRenderMode is true, this value defines the maximum change in simulation time allowed before a render is requested. See {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}.
  137. * @param {number} [options.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.
  138. *
  139. * @exception {DeveloperError} Element with id "container" does not exist in the document.
  140. *
  141. * @demo {@link https://sandcastle.cesium.com/index.html?src=Cesium%20Widget.html|Cesium Sandcastle Cesium Widget Demo}
  142. *
  143. * @example
  144. * // For each example, include a link to CesiumWidget.css stylesheet in HTML head,
  145. * // and in the body, include: <div id="cesiumContainer"></div>
  146. *
  147. * // Widget with no terrain and default Bing Maps imagery provider.
  148. * const widget = new Cesium.CesiumWidget("cesiumContainer");
  149. *
  150. * // Widget with ion imagery and Cesium World Terrain.
  151. * const widget2 = new Cesium.CesiumWidget("cesiumContainer", {
  152. * baseLayer: Cesium.ImageryLayer.fromWorldTerrain(),
  153. * terrain: Cesium.Terrain.fromWorldTerrain()
  154. * skyBox: new Cesium.SkyBox({
  155. * sources: {
  156. * positiveX: "stars/TychoSkymapII.t3_08192x04096_80_px.jpg",
  157. * negativeX: "stars/TychoSkymapII.t3_08192x04096_80_mx.jpg",
  158. * positiveY: "stars/TychoSkymapII.t3_08192x04096_80_py.jpg",
  159. * negativeY: "stars/TychoSkymapII.t3_08192x04096_80_my.jpg",
  160. * positiveZ: "stars/TychoSkymapII.t3_08192x04096_80_pz.jpg",
  161. * negativeZ: "stars/TychoSkymapII.t3_08192x04096_80_mz.jpg"
  162. * }
  163. * }),
  164. * // Show Columbus View map with Web Mercator projection
  165. * sceneMode: Cesium.SceneMode.COLUMBUS_VIEW,
  166. * mapProjection: new Cesium.WebMercatorProjection()
  167. * });
  168. */
  169. function CesiumWidget(container, options) {
  170. //>>includeStart('debug', pragmas.debug);
  171. if (!defined(container)) {
  172. throw new DeveloperError("container is required.");
  173. }
  174. //>>includeEnd('debug');
  175. container = getElement(container);
  176. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  177. //Configure the widget DOM elements
  178. const element = document.createElement("div");
  179. element.className = "cesium-widget";
  180. container.appendChild(element);
  181. const canvas = document.createElement("canvas");
  182. const supportsImageRenderingPixelated = FeatureDetection.supportsImageRenderingPixelated();
  183. this._supportsImageRenderingPixelated = supportsImageRenderingPixelated;
  184. if (supportsImageRenderingPixelated) {
  185. canvas.style.imageRendering = FeatureDetection.imageRenderingValue();
  186. }
  187. canvas.oncontextmenu = function () {
  188. return false;
  189. };
  190. canvas.onselectstart = function () {
  191. return false;
  192. };
  193. // Interacting with a canvas does not automatically blur the previously focused element.
  194. // This leads to unexpected interaction if the last element was an input field.
  195. // For example, clicking the mouse wheel could lead to the value in the field changing
  196. // unexpectedly. The solution is to blur whatever has focus as soon as canvas interaction begins.
  197. // Although in some cases the active element needs to stay active even after interacting with the canvas,
  198. // for example when clicking on it only for getting the data of a clicked position or an entity.
  199. // For this case, the `blurActiveElementOnCanvasFocus` can be passed with false to avoid blurring
  200. // the active element after interacting with the canvas.
  201. function blurActiveElement() {
  202. if (canvas !== canvas.ownerDocument.activeElement) {
  203. canvas.ownerDocument.activeElement.blur();
  204. }
  205. }
  206. const blurActiveElementOnCanvasFocus = defaultValue(
  207. options.blurActiveElementOnCanvasFocus,
  208. true
  209. );
  210. if (blurActiveElementOnCanvasFocus) {
  211. canvas.addEventListener("mousedown", blurActiveElement);
  212. canvas.addEventListener("pointerdown", blurActiveElement);
  213. }
  214. element.appendChild(canvas);
  215. const innerCreditContainer = document.createElement("div");
  216. innerCreditContainer.className = "cesium-widget-credits";
  217. const creditContainer = defined(options.creditContainer)
  218. ? getElement(options.creditContainer)
  219. : element;
  220. creditContainer.appendChild(innerCreditContainer);
  221. const creditViewport = defined(options.creditViewport)
  222. ? getElement(options.creditViewport)
  223. : element;
  224. const showRenderLoopErrors = defaultValue(options.showRenderLoopErrors, true);
  225. const useBrowserRecommendedResolution = defaultValue(
  226. options.useBrowserRecommendedResolution,
  227. true
  228. );
  229. this._element = element;
  230. this._container = container;
  231. this._canvas = canvas;
  232. this._canvasClientWidth = 0;
  233. this._canvasClientHeight = 0;
  234. this._lastDevicePixelRatio = 0;
  235. this._creditViewport = creditViewport;
  236. this._creditContainer = creditContainer;
  237. this._innerCreditContainer = innerCreditContainer;
  238. this._canRender = false;
  239. this._renderLoopRunning = false;
  240. this._showRenderLoopErrors = showRenderLoopErrors;
  241. this._resolutionScale = 1.0;
  242. this._useBrowserRecommendedResolution = useBrowserRecommendedResolution;
  243. this._forceResize = false;
  244. this._clock = defined(options.clock) ? options.clock : new Clock();
  245. configureCanvasSize(this);
  246. try {
  247. const scene = new Scene({
  248. canvas: canvas,
  249. contextOptions: options.contextOptions,
  250. creditContainer: innerCreditContainer,
  251. creditViewport: creditViewport,
  252. mapProjection: options.mapProjection,
  253. orderIndependentTranslucency: options.orderIndependentTranslucency,
  254. scene3DOnly: defaultValue(options.scene3DOnly, false),
  255. shadows: options.shadows,
  256. mapMode2D: options.mapMode2D,
  257. requestRenderMode: options.requestRenderMode,
  258. maximumRenderTimeChange: options.maximumRenderTimeChange,
  259. depthPlaneEllipsoidOffset: options.depthPlaneEllipsoidOffset,
  260. msaaSamples: options.msaaSamples,
  261. });
  262. this._scene = scene;
  263. scene.camera.constrainedAxis = Cartesian3.UNIT_Z;
  264. configurePixelRatio(this);
  265. configureCameraFrustum(this);
  266. const ellipsoid = defaultValue(
  267. scene.mapProjection.ellipsoid,
  268. Ellipsoid.WGS84
  269. );
  270. let globe = options.globe;
  271. if (!defined(globe)) {
  272. globe = new Globe(ellipsoid);
  273. }
  274. if (globe !== false) {
  275. scene.globe = globe;
  276. scene.globe.shadows = defaultValue(
  277. options.terrainShadows,
  278. ShadowMode.RECEIVE_ONLY
  279. );
  280. }
  281. let skyBox = options.skyBox;
  282. if (!defined(skyBox)) {
  283. skyBox = new SkyBox({
  284. sources: {
  285. positiveX: getDefaultSkyBoxUrl("px"),
  286. negativeX: getDefaultSkyBoxUrl("mx"),
  287. positiveY: getDefaultSkyBoxUrl("py"),
  288. negativeY: getDefaultSkyBoxUrl("my"),
  289. positiveZ: getDefaultSkyBoxUrl("pz"),
  290. negativeZ: getDefaultSkyBoxUrl("mz"),
  291. },
  292. });
  293. }
  294. if (skyBox !== false) {
  295. scene.skyBox = skyBox;
  296. scene.sun = new Sun();
  297. scene.moon = new Moon();
  298. }
  299. // Blue sky, and the glow around the Earth's limb.
  300. let skyAtmosphere = options.skyAtmosphere;
  301. if (!defined(skyAtmosphere)) {
  302. skyAtmosphere = new SkyAtmosphere(ellipsoid);
  303. }
  304. if (skyAtmosphere !== false) {
  305. scene.skyAtmosphere = skyAtmosphere;
  306. }
  307. if (defined(options.imageryProvider)) {
  308. deprecationWarning(
  309. "CesiumWidget options.imageryProvider",
  310. "options.imageryProvider was deprecated in CesiumJS 1.104. It will be in CesiumJS 1.107. Use options.baseLayer instead."
  311. );
  312. }
  313. // Set the base imagery layer
  314. let baseLayer = options.baseLayer;
  315. if (
  316. options.globe !== false &&
  317. baseLayer !== false &&
  318. options.imageryProvider !== false
  319. ) {
  320. if (defined(options.imageryProvider) && !defined(baseLayer)) {
  321. baseLayer = new ImageryLayer(options.imageryProvider);
  322. }
  323. if (!defined(baseLayer)) {
  324. baseLayer = ImageryLayer.fromWorldImagery();
  325. }
  326. scene.imageryLayers.add(baseLayer);
  327. }
  328. // Set the terrain provider if one is provided.
  329. if (defined(options.terrainProvider) && options.globe !== false) {
  330. scene.terrainProvider = options.terrainProvider;
  331. }
  332. if (defined(options.terrain) && options.globe !== false) {
  333. //>>includeStart('debug', pragmas.debug);
  334. if (defined(options.terrainProvider)) {
  335. throw new DeveloperError(
  336. "Specify either options.terrainProvider or options.terrain."
  337. );
  338. }
  339. //>>includeEnd('debug')
  340. scene.setTerrain(options.terrain);
  341. }
  342. this._screenSpaceEventHandler = new ScreenSpaceEventHandler(canvas);
  343. if (defined(options.sceneMode)) {
  344. if (options.sceneMode === SceneMode.SCENE2D) {
  345. this._scene.morphTo2D(0);
  346. }
  347. if (options.sceneMode === SceneMode.COLUMBUS_VIEW) {
  348. this._scene.morphToColumbusView(0);
  349. }
  350. }
  351. this._useDefaultRenderLoop = undefined;
  352. this.useDefaultRenderLoop = defaultValue(
  353. options.useDefaultRenderLoop,
  354. true
  355. );
  356. this._targetFrameRate = undefined;
  357. this.targetFrameRate = options.targetFrameRate;
  358. const that = this;
  359. this._onRenderError = function (scene, error) {
  360. that._useDefaultRenderLoop = false;
  361. that._renderLoopRunning = false;
  362. if (that._showRenderLoopErrors) {
  363. const title =
  364. "An error occurred while rendering. Rendering has stopped.";
  365. that.showErrorPanel(title, undefined, error);
  366. }
  367. };
  368. scene.renderError.addEventListener(this._onRenderError);
  369. } catch (error) {
  370. if (showRenderLoopErrors) {
  371. const title = "Error constructing CesiumWidget.";
  372. const message =
  373. 'Visit <a href="http://get.webgl.org">http://get.webgl.org</a> to verify that your web browser and hardware support WebGL. Consider trying a different web browser or updating your video drivers. Detailed error information is below:';
  374. this.showErrorPanel(title, message, error);
  375. }
  376. throw error;
  377. }
  378. }
  379. Object.defineProperties(CesiumWidget.prototype, {
  380. /**
  381. * Gets the parent container.
  382. * @memberof CesiumWidget.prototype
  383. *
  384. * @type {Element}
  385. * @readonly
  386. */
  387. container: {
  388. get: function () {
  389. return this._container;
  390. },
  391. },
  392. /**
  393. * Gets the canvas.
  394. * @memberof CesiumWidget.prototype
  395. *
  396. * @type {HTMLCanvasElement}
  397. * @readonly
  398. */
  399. canvas: {
  400. get: function () {
  401. return this._canvas;
  402. },
  403. },
  404. /**
  405. * Gets the credit container.
  406. * @memberof CesiumWidget.prototype
  407. *
  408. * @type {Element}
  409. * @readonly
  410. */
  411. creditContainer: {
  412. get: function () {
  413. return this._creditContainer;
  414. },
  415. },
  416. /**
  417. * Gets the credit viewport
  418. * @memberof CesiumWidget.prototype
  419. *
  420. * @type {Element}
  421. * @readonly
  422. */
  423. creditViewport: {
  424. get: function () {
  425. return this._creditViewport;
  426. },
  427. },
  428. /**
  429. * Gets the scene.
  430. * @memberof CesiumWidget.prototype
  431. *
  432. * @type {Scene}
  433. * @readonly
  434. */
  435. scene: {
  436. get: function () {
  437. return this._scene;
  438. },
  439. },
  440. /**
  441. * Gets the collection of image layers that will be rendered on the globe.
  442. * @memberof CesiumWidget.prototype
  443. *
  444. * @type {ImageryLayerCollection}
  445. * @readonly
  446. */
  447. imageryLayers: {
  448. get: function () {
  449. return this._scene.imageryLayers;
  450. },
  451. },
  452. /**
  453. * The terrain provider providing surface geometry for the globe.
  454. * @memberof CesiumWidget.prototype
  455. *
  456. * @type {TerrainProvider}
  457. */
  458. terrainProvider: {
  459. get: function () {
  460. return this._scene.terrainProvider;
  461. },
  462. set: function (terrainProvider) {
  463. this._scene.terrainProvider = terrainProvider;
  464. },
  465. },
  466. /**
  467. * Manages the list of credits to display on screen and in the lightbox.
  468. * @memberof CesiumWidget.prototype
  469. *
  470. * @type {CreditDisplay}
  471. */
  472. creditDisplay: {
  473. get: function () {
  474. return this._scene.frameState.creditDisplay;
  475. },
  476. },
  477. /**
  478. * Gets the camera.
  479. * @memberof CesiumWidget.prototype
  480. *
  481. * @type {Camera}
  482. * @readonly
  483. */
  484. camera: {
  485. get: function () {
  486. return this._scene.camera;
  487. },
  488. },
  489. /**
  490. * Gets the clock.
  491. * @memberof CesiumWidget.prototype
  492. *
  493. * @type {Clock}
  494. * @readonly
  495. */
  496. clock: {
  497. get: function () {
  498. return this._clock;
  499. },
  500. },
  501. /**
  502. * Gets the screen space event handler.
  503. * @memberof CesiumWidget.prototype
  504. *
  505. * @type {ScreenSpaceEventHandler}
  506. * @readonly
  507. */
  508. screenSpaceEventHandler: {
  509. get: function () {
  510. return this._screenSpaceEventHandler;
  511. },
  512. },
  513. /**
  514. * Gets or sets the target frame rate of the widget when <code>useDefaultRenderLoop</code>
  515. * is true. If undefined, the browser's requestAnimationFrame implementation
  516. * determines the frame rate. If defined, this value must be greater than 0. A value higher
  517. * than the underlying requestAnimationFrame implementation will have no effect.
  518. * @memberof CesiumWidget.prototype
  519. *
  520. * @type {number}
  521. */
  522. targetFrameRate: {
  523. get: function () {
  524. return this._targetFrameRate;
  525. },
  526. set: function (value) {
  527. //>>includeStart('debug', pragmas.debug);
  528. if (value <= 0) {
  529. throw new DeveloperError(
  530. "targetFrameRate must be greater than 0, or undefined."
  531. );
  532. }
  533. //>>includeEnd('debug');
  534. this._targetFrameRate = value;
  535. },
  536. },
  537. /**
  538. * Gets or sets whether or not this widget should control the render loop.
  539. * If true the widget will use requestAnimationFrame to
  540. * perform rendering and resizing of the widget, as well as drive the
  541. * simulation clock. If set to false, you must manually call the
  542. * <code>resize</code>, <code>render</code> methods as part of a custom
  543. * render loop. If an error occurs during rendering, {@link Scene}'s
  544. * <code>renderError</code> event will be raised and this property
  545. * will be set to false. It must be set back to true to continue rendering
  546. * after the error.
  547. * @memberof CesiumWidget.prototype
  548. *
  549. * @type {boolean}
  550. */
  551. useDefaultRenderLoop: {
  552. get: function () {
  553. return this._useDefaultRenderLoop;
  554. },
  555. set: function (value) {
  556. if (this._useDefaultRenderLoop !== value) {
  557. this._useDefaultRenderLoop = value;
  558. if (value && !this._renderLoopRunning) {
  559. startRenderLoop(this);
  560. }
  561. }
  562. },
  563. },
  564. /**
  565. * Gets or sets a scaling factor for rendering resolution. Values less than 1.0 can improve
  566. * performance on less powerful devices while values greater than 1.0 will render at a higher
  567. * resolution and then scale down, resulting in improved visual fidelity.
  568. * For example, if the widget is laid out at a size of 640x480, setting this value to 0.5
  569. * will cause the scene to be rendered at 320x240 and then scaled up while setting
  570. * it to 2.0 will cause the scene to be rendered at 1280x960 and then scaled down.
  571. * @memberof CesiumWidget.prototype
  572. *
  573. * @type {number}
  574. * @default 1.0
  575. */
  576. resolutionScale: {
  577. get: function () {
  578. return this._resolutionScale;
  579. },
  580. set: function (value) {
  581. //>>includeStart('debug', pragmas.debug);
  582. if (value <= 0) {
  583. throw new DeveloperError("resolutionScale must be greater than 0.");
  584. }
  585. //>>includeEnd('debug');
  586. if (this._resolutionScale !== value) {
  587. this._resolutionScale = value;
  588. this._forceResize = true;
  589. }
  590. },
  591. },
  592. /**
  593. * Boolean flag indicating if the browser's recommended resolution is used.
  594. * If true, the browser's device pixel ratio is ignored and 1.0 is used instead,
  595. * effectively rendering based on CSS pixels instead of device pixels. This can improve
  596. * performance on less powerful devices that have high pixel density. When false, rendering
  597. * will be in device pixels. {@link CesiumWidget#resolutionScale} will still take effect whether
  598. * this flag is true or false.
  599. * @memberof CesiumWidget.prototype
  600. *
  601. * @type {boolean}
  602. * @default true
  603. */
  604. useBrowserRecommendedResolution: {
  605. get: function () {
  606. return this._useBrowserRecommendedResolution;
  607. },
  608. set: function (value) {
  609. if (this._useBrowserRecommendedResolution !== value) {
  610. this._useBrowserRecommendedResolution = value;
  611. this._forceResize = true;
  612. }
  613. },
  614. },
  615. });
  616. /**
  617. * Show an error panel to the user containing a title and a longer error message,
  618. * which can be dismissed using an OK button. This panel is displayed automatically
  619. * when a render loop error occurs, if showRenderLoopErrors was not false when the
  620. * widget was constructed.
  621. *
  622. * @param {string} title The title to be displayed on the error panel. This string is interpreted as text.
  623. * @param {string} [message] A helpful, user-facing message to display prior to the detailed error information. This string is interpreted as HTML.
  624. * @param {string} [error] The error to be displayed on the error panel. This string is formatted using {@link formatError} and then displayed as text.
  625. */
  626. CesiumWidget.prototype.showErrorPanel = function (title, message, error) {
  627. const element = this._element;
  628. const overlay = document.createElement("div");
  629. overlay.className = "cesium-widget-errorPanel";
  630. const content = document.createElement("div");
  631. content.className = "cesium-widget-errorPanel-content";
  632. overlay.appendChild(content);
  633. const errorHeader = document.createElement("div");
  634. errorHeader.className = "cesium-widget-errorPanel-header";
  635. errorHeader.appendChild(document.createTextNode(title));
  636. content.appendChild(errorHeader);
  637. const errorPanelScroller = document.createElement("div");
  638. errorPanelScroller.className = "cesium-widget-errorPanel-scroll";
  639. content.appendChild(errorPanelScroller);
  640. function resizeCallback() {
  641. errorPanelScroller.style.maxHeight = `${Math.max(
  642. Math.round(element.clientHeight * 0.9 - 100),
  643. 30
  644. )}px`;
  645. }
  646. resizeCallback();
  647. if (defined(window.addEventListener)) {
  648. window.addEventListener("resize", resizeCallback, false);
  649. }
  650. const hasMessage = defined(message);
  651. const hasError = defined(error);
  652. if (hasMessage || hasError) {
  653. const errorMessage = document.createElement("div");
  654. errorMessage.className = "cesium-widget-errorPanel-message";
  655. errorPanelScroller.appendChild(errorMessage);
  656. if (hasError) {
  657. let errorDetails = formatError(error);
  658. if (!hasMessage) {
  659. if (typeof error === "string") {
  660. error = new Error(error);
  661. }
  662. message = formatError({
  663. name: error.name,
  664. message: error.message,
  665. });
  666. errorDetails = error.stack;
  667. }
  668. //IE8 does not have a console object unless the dev tools are open.
  669. if (typeof console !== "undefined") {
  670. console.error(`${title}\n${message}\n${errorDetails}`);
  671. }
  672. const errorMessageDetails = document.createElement("div");
  673. errorMessageDetails.className =
  674. "cesium-widget-errorPanel-message-details collapsed";
  675. const moreDetails = document.createElement("span");
  676. moreDetails.className = "cesium-widget-errorPanel-more-details";
  677. moreDetails.appendChild(document.createTextNode("See more..."));
  678. errorMessageDetails.appendChild(moreDetails);
  679. errorMessageDetails.onclick = function (e) {
  680. errorMessageDetails.removeChild(moreDetails);
  681. errorMessageDetails.appendChild(document.createTextNode(errorDetails));
  682. errorMessageDetails.className =
  683. "cesium-widget-errorPanel-message-details";
  684. content.className = "cesium-widget-errorPanel-content expanded";
  685. errorMessageDetails.onclick = undefined;
  686. };
  687. errorPanelScroller.appendChild(errorMessageDetails);
  688. }
  689. errorMessage.innerHTML = `<p>${message}</p>`;
  690. }
  691. const buttonPanel = document.createElement("div");
  692. buttonPanel.className = "cesium-widget-errorPanel-buttonPanel";
  693. content.appendChild(buttonPanel);
  694. const okButton = document.createElement("button");
  695. okButton.setAttribute("type", "button");
  696. okButton.className = "cesium-button";
  697. okButton.appendChild(document.createTextNode("OK"));
  698. okButton.onclick = function () {
  699. if (defined(resizeCallback) && defined(window.removeEventListener)) {
  700. window.removeEventListener("resize", resizeCallback, false);
  701. }
  702. element.removeChild(overlay);
  703. };
  704. buttonPanel.appendChild(okButton);
  705. element.appendChild(overlay);
  706. };
  707. /**
  708. * @returns {boolean} true if the object has been destroyed, false otherwise.
  709. */
  710. CesiumWidget.prototype.isDestroyed = function () {
  711. return false;
  712. };
  713. /**
  714. * Destroys the widget. Should be called if permanently
  715. * removing the widget from layout.
  716. */
  717. CesiumWidget.prototype.destroy = function () {
  718. if (defined(this._scene)) {
  719. this._scene.renderError.removeEventListener(this._onRenderError);
  720. this._scene = this._scene.destroy();
  721. }
  722. this._container.removeChild(this._element);
  723. this._creditContainer.removeChild(this._innerCreditContainer);
  724. destroyObject(this);
  725. };
  726. /**
  727. * Updates the canvas size, camera aspect ratio, and viewport size.
  728. * This function is called automatically as needed unless
  729. * <code>useDefaultRenderLoop</code> is set to false.
  730. */
  731. CesiumWidget.prototype.resize = function () {
  732. const canvas = this._canvas;
  733. if (
  734. !this._forceResize &&
  735. this._canvasClientWidth === canvas.clientWidth &&
  736. this._canvasClientHeight === canvas.clientHeight &&
  737. this._lastDevicePixelRatio === window.devicePixelRatio
  738. ) {
  739. return;
  740. }
  741. this._forceResize = false;
  742. configureCanvasSize(this);
  743. configureCameraFrustum(this);
  744. this._scene.requestRender();
  745. };
  746. /**
  747. * Renders the scene. This function is called automatically
  748. * unless <code>useDefaultRenderLoop</code> is set to false;
  749. */
  750. CesiumWidget.prototype.render = function () {
  751. if (this._canRender) {
  752. this._scene.initializeFrame();
  753. const currentTime = this._clock.tick();
  754. this._scene.render(currentTime);
  755. } else {
  756. this._clock.tick();
  757. }
  758. };
  759. export default CesiumWidget;