Scene.js 139 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533
  1. import BoundingRectangle from "../Core/BoundingRectangle.js";
  2. import BoundingSphere from "../Core/BoundingSphere.js";
  3. import BoxGeometry from "../Core/BoxGeometry.js";
  4. import Cartesian3 from "../Core/Cartesian3.js";
  5. import Cartographic from "../Core/Cartographic.js";
  6. import Check from "../Core/Check.js";
  7. import clone from "../Core/clone.js";
  8. import Color from "../Core/Color.js";
  9. import ColorGeometryInstanceAttribute from "../Core/ColorGeometryInstanceAttribute.js";
  10. import createGuid from "../Core/createGuid.js";
  11. import CullingVolume from "../Core/CullingVolume.js";
  12. import defaultValue from "../Core/defaultValue.js";
  13. import defined from "../Core/defined.js";
  14. import destroyObject from "../Core/destroyObject.js";
  15. import DeveloperError from "../Core/DeveloperError.js";
  16. import EllipsoidGeometry from "../Core/EllipsoidGeometry.js";
  17. import Event from "../Core/Event.js";
  18. import GeographicProjection from "../Core/GeographicProjection.js";
  19. import GeometryInstance from "../Core/GeometryInstance.js";
  20. import GeometryPipeline from "../Core/GeometryPipeline.js";
  21. import Intersect from "../Core/Intersect.js";
  22. import JulianDate from "../Core/JulianDate.js";
  23. import CesiumMath from "../Core/Math.js";
  24. import Matrix4 from "../Core/Matrix4.js";
  25. import mergeSort from "../Core/mergeSort.js";
  26. import Occluder from "../Core/Occluder.js";
  27. import OrthographicFrustum from "../Core/OrthographicFrustum.js";
  28. import OrthographicOffCenterFrustum from "../Core/OrthographicOffCenterFrustum.js";
  29. import PerspectiveFrustum from "../Core/PerspectiveFrustum.js";
  30. import PerspectiveOffCenterFrustum from "../Core/PerspectiveOffCenterFrustum.js";
  31. import RequestScheduler from "../Core/RequestScheduler.js";
  32. import TaskProcessor from "../Core/TaskProcessor.js";
  33. import Transforms from "../Core/Transforms.js";
  34. import ClearCommand from "../Renderer/ClearCommand.js";
  35. import ComputeEngine from "../Renderer/ComputeEngine.js";
  36. import Context from "../Renderer/Context.js";
  37. import ContextLimits from "../Renderer/ContextLimits.js";
  38. import Pass from "../Renderer/Pass.js";
  39. import RenderState from "../Renderer/RenderState.js";
  40. import BrdfLutGenerator from "./BrdfLutGenerator.js";
  41. import Camera from "./Camera.js";
  42. import Cesium3DTilePass from "./Cesium3DTilePass.js";
  43. import Cesium3DTilePassState from "./Cesium3DTilePassState.js";
  44. import CreditDisplay from "./CreditDisplay.js";
  45. import DebugCameraPrimitive from "./DebugCameraPrimitive.js";
  46. import DepthPlane from "./DepthPlane.js";
  47. import DerivedCommand from "./DerivedCommand.js";
  48. import DeviceOrientationCameraController from "./DeviceOrientationCameraController.js";
  49. import Fog from "./Fog.js";
  50. import FrameState from "./FrameState.js";
  51. import GlobeTranslucencyState from "./GlobeTranslucencyState.js";
  52. import InvertClassification from "./InvertClassification.js";
  53. import JobScheduler from "./JobScheduler.js";
  54. import MapMode2D from "./MapMode2D.js";
  55. import OctahedralProjectedCubeMap from "./OctahedralProjectedCubeMap.js";
  56. import PerformanceDisplay from "./PerformanceDisplay.js";
  57. import PerInstanceColorAppearance from "./PerInstanceColorAppearance.js";
  58. import Picking from "./Picking.js";
  59. import PostProcessStageCollection from "./PostProcessStageCollection.js";
  60. import Primitive from "./Primitive.js";
  61. import PrimitiveCollection from "./PrimitiveCollection.js";
  62. import SceneMode from "./SceneMode.js";
  63. import SceneTransforms from "./SceneTransforms.js";
  64. import SceneTransitioner from "./SceneTransitioner.js";
  65. import ScreenSpaceCameraController from "./ScreenSpaceCameraController.js";
  66. import ShadowMap from "./ShadowMap.js";
  67. import StencilConstants from "./StencilConstants.js";
  68. import SunLight from "./SunLight.js";
  69. import SunPostProcess from "./SunPostProcess.js";
  70. import TweenCollection from "./TweenCollection.js";
  71. import View from "./View.js";
  72. import DebugInspector from "./DebugInspector.js";
  73. const requestRenderAfterFrame = function (scene) {
  74. return function () {
  75. scene.frameState.afterRender.push(function () {
  76. scene.requestRender();
  77. });
  78. };
  79. };
  80. /**
  81. * The container for all 3D graphical objects and state in a Cesium virtual scene. Generally,
  82. * a scene is not created directly; instead, it is implicitly created by {@link CesiumWidget}.
  83. *
  84. * @alias Scene
  85. * @constructor
  86. *
  87. * @param {object} options Object with the following properties:
  88. * @param {HTMLCanvasElement} options.canvas The HTML canvas element to create the scene for.
  89. * @param {ContextOptions} [options.contextOptions] Context and WebGL creation properties.
  90. * @param {Element} [options.creditContainer] The HTML element in which the credits will be displayed.
  91. * @param {Element} [options.creditViewport] The HTML element in which to display the credit popup. If not specified, the viewport will be a added as a sibling of the canvas.
  92. * @param {MapProjection} [options.mapProjection=new GeographicProjection()] The map projection to use in 2D and Columbus View modes.
  93. * @param {boolean} [options.orderIndependentTranslucency=true] If true and the configuration supports it, use order independent translucency.
  94. * @param {boolean} [options.scene3DOnly=false] If true, optimizes memory use and performance for 3D mode but disables the ability to use 2D or Columbus View.
  95. * @param {boolean} [options.shadows=false] Determines if shadows are cast by light sources.
  96. * @param {MapMode2D} [options.mapMode2D=MapMode2D.INFINITE_SCROLL] Determines if the 2D map is rotatable or can be scrolled infinitely in the horizontal direction.
  97. * @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}.
  98. * @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}.
  99. * @param {number} [options.depthPlaneEllipsoidOffset=0.0] Adjust the DepthPlane to address rendering artefacts below ellipsoid zero elevation.
  100. * @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.
  101. *
  102. * @see CesiumWidget
  103. * @see {@link http://www.khronos.org/registry/webgl/specs/latest/#5.2|WebGLContextAttributes}
  104. *
  105. * @exception {DeveloperError} options and options.canvas are required.
  106. *
  107. * @example
  108. * // Create scene without anisotropic texture filtering
  109. * const scene = new Cesium.Scene({
  110. * canvas : canvas,
  111. * contextOptions : {
  112. * allowTextureFilterAnisotropic : false
  113. * }
  114. * });
  115. */
  116. function Scene(options) {
  117. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  118. const canvas = options.canvas;
  119. let creditContainer = options.creditContainer;
  120. let creditViewport = options.creditViewport;
  121. const contextOptions = clone(options.contextOptions);
  122. //>>includeStart('debug', pragmas.debug);
  123. if (!defined(canvas)) {
  124. throw new DeveloperError("options and options.canvas are required.");
  125. }
  126. //>>includeEnd('debug');
  127. const hasCreditContainer = defined(creditContainer);
  128. const context = new Context(canvas, contextOptions);
  129. if (!hasCreditContainer) {
  130. creditContainer = document.createElement("div");
  131. creditContainer.style.position = "absolute";
  132. creditContainer.style.bottom = "0";
  133. creditContainer.style["text-shadow"] = "0 0 2px #000000";
  134. creditContainer.style.color = "#ffffff";
  135. creditContainer.style["font-size"] = "10px";
  136. creditContainer.style["padding-right"] = "5px";
  137. canvas.parentNode.appendChild(creditContainer);
  138. }
  139. if (!defined(creditViewport)) {
  140. creditViewport = canvas.parentNode;
  141. }
  142. this._id = createGuid();
  143. this._jobScheduler = new JobScheduler();
  144. this._frameState = new FrameState(
  145. context,
  146. new CreditDisplay(creditContainer, " • ", creditViewport),
  147. this._jobScheduler
  148. );
  149. this._frameState.scene3DOnly = defaultValue(options.scene3DOnly, false);
  150. this._removeCreditContainer = !hasCreditContainer;
  151. this._creditContainer = creditContainer;
  152. this._canvas = canvas;
  153. this._context = context;
  154. this._computeEngine = new ComputeEngine(context);
  155. this._globe = undefined;
  156. this._globeTranslucencyState = new GlobeTranslucencyState();
  157. this._primitives = new PrimitiveCollection();
  158. this._groundPrimitives = new PrimitiveCollection();
  159. this._globeHeight = undefined;
  160. this._cameraUnderground = false;
  161. this._logDepthBuffer = context.fragmentDepth;
  162. this._logDepthBufferDirty = true;
  163. this._tweens = new TweenCollection();
  164. this._shaderFrameCount = 0;
  165. this._sunPostProcess = undefined;
  166. this._computeCommandList = [];
  167. this._overlayCommandList = [];
  168. this._useOIT = defaultValue(options.orderIndependentTranslucency, true);
  169. this._executeOITFunction = undefined;
  170. this._depthPlane = new DepthPlane(options.depthPlaneEllipsoidOffset);
  171. this._clearColorCommand = new ClearCommand({
  172. color: new Color(),
  173. stencil: 0,
  174. owner: this,
  175. });
  176. this._depthClearCommand = new ClearCommand({
  177. depth: 1.0,
  178. owner: this,
  179. });
  180. this._stencilClearCommand = new ClearCommand({
  181. stencil: 0,
  182. });
  183. this._classificationStencilClearCommand = new ClearCommand({
  184. stencil: 0,
  185. renderState: RenderState.fromCache({
  186. stencilMask: StencilConstants.CLASSIFICATION_MASK,
  187. }),
  188. });
  189. this._depthOnlyRenderStateCache = {};
  190. this._transitioner = new SceneTransitioner(this);
  191. this._preUpdate = new Event();
  192. this._postUpdate = new Event();
  193. this._renderError = new Event();
  194. this._preRender = new Event();
  195. this._postRender = new Event();
  196. this._minimumDisableDepthTestDistance = 0.0;
  197. this._debugInspector = new DebugInspector();
  198. this._msaaSamples = defaultValue(options.msaaSamples, 1);
  199. /**
  200. * Exceptions occurring in <code>render</code> are always caught in order to raise the
  201. * <code>renderError</code> event. If this property is true, the error is rethrown
  202. * after the event is raised. If this property is false, the <code>render</code> function
  203. * returns normally after raising the event.
  204. *
  205. * @type {boolean}
  206. * @default false
  207. */
  208. this.rethrowRenderErrors = false;
  209. /**
  210. * Determines whether or not to instantly complete the
  211. * scene transition animation on user input.
  212. *
  213. * @type {boolean}
  214. * @default true
  215. */
  216. this.completeMorphOnUserInput = true;
  217. /**
  218. * The event fired at the beginning of a scene transition.
  219. * @type {Event}
  220. * @default Event()
  221. */
  222. this.morphStart = new Event();
  223. /**
  224. * The event fired at the completion of a scene transition.
  225. * @type {Event}
  226. * @default Event()
  227. */
  228. this.morphComplete = new Event();
  229. /**
  230. * The {@link SkyBox} used to draw the stars.
  231. *
  232. * @type {SkyBox}
  233. * @default undefined
  234. *
  235. * @see Scene#backgroundColor
  236. */
  237. this.skyBox = undefined;
  238. /**
  239. * The sky atmosphere drawn around the globe.
  240. *
  241. * @type {SkyAtmosphere}
  242. * @default undefined
  243. */
  244. this.skyAtmosphere = undefined;
  245. /**
  246. * The {@link Sun}.
  247. *
  248. * @type {Sun}
  249. * @default undefined
  250. */
  251. this.sun = undefined;
  252. /**
  253. * Uses a bloom filter on the sun when enabled.
  254. *
  255. * @type {boolean}
  256. * @default true
  257. */
  258. this.sunBloom = true;
  259. this._sunBloom = undefined;
  260. /**
  261. * The {@link Moon}
  262. *
  263. * @type Moon
  264. * @default undefined
  265. */
  266. this.moon = undefined;
  267. /**
  268. * The background color, which is only visible if there is no sky box, i.e., {@link Scene#skyBox} is undefined.
  269. *
  270. * @type {Color}
  271. * @default {@link Color.BLACK}
  272. *
  273. * @see Scene#skyBox
  274. */
  275. this.backgroundColor = Color.clone(Color.BLACK);
  276. this._mode = SceneMode.SCENE3D;
  277. this._mapProjection = defined(options.mapProjection)
  278. ? options.mapProjection
  279. : new GeographicProjection();
  280. /**
  281. * The current morph transition time between 2D/Columbus View and 3D,
  282. * with 0.0 being 2D or Columbus View and 1.0 being 3D.
  283. *
  284. * @type {number}
  285. * @default 1.0
  286. */
  287. this.morphTime = 1.0;
  288. /**
  289. * The far-to-near ratio of the multi-frustum when using a normal depth buffer.
  290. * <p>
  291. * This value is used to create the near and far values for each frustum of the multi-frustum. It is only used
  292. * when {@link Scene#logarithmicDepthBuffer} is <code>false</code>. When <code>logarithmicDepthBuffer</code> is
  293. * <code>true</code>, use {@link Scene#logarithmicDepthFarToNearRatio}.
  294. * </p>
  295. *
  296. * @type {number}
  297. * @default 1000.0
  298. */
  299. this.farToNearRatio = 1000.0;
  300. /**
  301. * The far-to-near ratio of the multi-frustum when using a logarithmic depth buffer.
  302. * <p>
  303. * This value is used to create the near and far values for each frustum of the multi-frustum. It is only used
  304. * when {@link Scene#logarithmicDepthBuffer} is <code>true</code>. When <code>logarithmicDepthBuffer</code> is
  305. * <code>false</code>, use {@link Scene#farToNearRatio}.
  306. * </p>
  307. *
  308. * @type {number}
  309. * @default 1e9
  310. */
  311. this.logarithmicDepthFarToNearRatio = 1e9;
  312. /**
  313. * Determines the uniform depth size in meters of each frustum of the multifrustum in 2D. If a primitive or model close
  314. * to the surface shows z-fighting, decreasing this will eliminate the artifact, but decrease performance. On the
  315. * other hand, increasing this will increase performance but may cause z-fighting among primitives close to the surface.
  316. *
  317. * @type {number}
  318. * @default 1.75e6
  319. */
  320. this.nearToFarDistance2D = 1.75e6;
  321. /**
  322. * This property is for debugging only; it is not for production use.
  323. * <p>
  324. * A function that determines what commands are executed. As shown in the examples below,
  325. * the function receives the command's <code>owner</code> as an argument, and returns a boolean indicating if the
  326. * command should be executed.
  327. * </p>
  328. * <p>
  329. * The default is <code>undefined</code>, indicating that all commands are executed.
  330. * </p>
  331. *
  332. * @type Function
  333. *
  334. * @default undefined
  335. *
  336. * @example
  337. * // Do not execute any commands.
  338. * scene.debugCommandFilter = function(command) {
  339. * return false;
  340. * };
  341. *
  342. * // Execute only the billboard's commands. That is, only draw the billboard.
  343. * const billboards = new Cesium.BillboardCollection();
  344. * scene.debugCommandFilter = function(command) {
  345. * return command.owner === billboards;
  346. * };
  347. */
  348. this.debugCommandFilter = undefined;
  349. /**
  350. * This property is for debugging only; it is not for production use.
  351. * <p>
  352. * When <code>true</code>, commands are randomly shaded. This is useful
  353. * for performance analysis to see what parts of a scene or model are
  354. * command-dense and could benefit from batching.
  355. * </p>
  356. *
  357. * @type {boolean}
  358. *
  359. * @default false
  360. */
  361. this.debugShowCommands = false;
  362. /**
  363. * This property is for debugging only; it is not for production use.
  364. * <p>
  365. * When <code>true</code>, commands are shaded based on the frustums they
  366. * overlap. Commands in the closest frustum are tinted red, commands in
  367. * the next closest are green, and commands in the farthest frustum are
  368. * blue. If a command overlaps more than one frustum, the color components
  369. * are combined, e.g., a command overlapping the first two frustums is tinted
  370. * yellow.
  371. * </p>
  372. *
  373. * @type {boolean}
  374. *
  375. * @default false
  376. */
  377. this.debugShowFrustums = false;
  378. /**
  379. * This property is for debugging only; it is not for production use.
  380. * <p>
  381. * Displays frames per second and time between frames.
  382. * </p>
  383. *
  384. * @type {boolean}
  385. *
  386. * @default false
  387. */
  388. this.debugShowFramesPerSecond = false;
  389. /**
  390. * This property is for debugging only; it is not for production use.
  391. * <p>
  392. * Indicates which frustum will have depth information displayed.
  393. * </p>
  394. *
  395. * @type {number}
  396. *
  397. * @default 1
  398. */
  399. this.debugShowDepthFrustum = 1;
  400. /**
  401. * This property is for debugging only; it is not for production use.
  402. * <p>
  403. * When <code>true</code>, draws outlines to show the boundaries of the camera frustums
  404. * </p>
  405. *
  406. * @type {boolean}
  407. *
  408. * @default false
  409. */
  410. this.debugShowFrustumPlanes = false;
  411. this._debugShowFrustumPlanes = false;
  412. this._debugFrustumPlanes = undefined;
  413. /**
  414. * When <code>true</code>, enables picking using the depth buffer.
  415. *
  416. * @type {boolean}
  417. * @default true
  418. */
  419. this.useDepthPicking = true;
  420. /**
  421. * When <code>true</code>, enables picking translucent geometry using the depth buffer. Note that {@link Scene#useDepthPicking} must also be true for enabling this to work.
  422. *
  423. * <p>
  424. * There is a decrease in performance when enabled. There are extra draw calls to write depth for
  425. * translucent geometry.
  426. * </p>
  427. *
  428. * @example
  429. * // picking the position of a translucent primitive
  430. * viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
  431. * const pickedFeature = viewer.scene.pick(movement.position);
  432. * if (!Cesium.defined(pickedFeature)) {
  433. * // nothing picked
  434. * return;
  435. * }
  436. * const worldPosition = viewer.scene.pickPosition(movement.position);
  437. * }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
  438. *
  439. * @type {boolean}
  440. * @default false
  441. */
  442. this.pickTranslucentDepth = false;
  443. /**
  444. * The time in milliseconds to wait before checking if the camera has not moved and fire the cameraMoveEnd event.
  445. * @type {number}
  446. * @default 500.0
  447. * @private
  448. */
  449. this.cameraEventWaitTime = 500.0;
  450. /**
  451. * Blends the atmosphere to geometry far from the camera for horizon views. Allows for additional
  452. * performance improvements by rendering less geometry and dispatching less terrain requests.
  453. * @type {Fog}
  454. */
  455. this.fog = new Fog();
  456. this._shadowMapCamera = new Camera(this);
  457. /**
  458. * The shadow map for the scene's light source. When enabled, models, primitives, and the globe may cast and receive shadows.
  459. * @type {ShadowMap}
  460. */
  461. this.shadowMap = new ShadowMap({
  462. context: context,
  463. lightCamera: this._shadowMapCamera,
  464. enabled: defaultValue(options.shadows, false),
  465. });
  466. /**
  467. * When <code>false</code>, 3D Tiles will render normally. When <code>true</code>, classified 3D Tile geometry will render normally and
  468. * unclassified 3D Tile geometry will render with the color multiplied by {@link Scene#invertClassificationColor}.
  469. * @type {boolean}
  470. * @default false
  471. */
  472. this.invertClassification = false;
  473. /**
  474. * The highlight color of unclassified 3D Tile geometry when {@link Scene#invertClassification} is <code>true</code>.
  475. * <p>When the color's alpha is less than 1.0, the unclassified portions of the 3D Tiles will not blend correctly with the classified positions of the 3D Tiles.</p>
  476. * <p>Also, when the color's alpha is less than 1.0, the WEBGL_depth_texture and EXT_frag_depth WebGL extensions must be supported.</p>
  477. * @type {Color}
  478. * @default Color.WHITE
  479. */
  480. this.invertClassificationColor = Color.clone(Color.WHITE);
  481. this._actualInvertClassificationColor = Color.clone(
  482. this._invertClassificationColor
  483. );
  484. this._invertClassification = new InvertClassification();
  485. /**
  486. * The focal length for use when with cardboard or WebVR.
  487. * @type {number}
  488. */
  489. this.focalLength = undefined;
  490. /**
  491. * The eye separation distance in meters for use with cardboard or WebVR.
  492. * @type {number}
  493. */
  494. this.eyeSeparation = undefined;
  495. /**
  496. * Post processing effects applied to the final render.
  497. * @type {PostProcessStageCollection}
  498. */
  499. this.postProcessStages = new PostProcessStageCollection();
  500. this._brdfLutGenerator = new BrdfLutGenerator();
  501. this._performanceDisplay = undefined;
  502. this._debugVolume = undefined;
  503. this._screenSpaceCameraController = new ScreenSpaceCameraController(this);
  504. this._cameraUnderground = false;
  505. this._mapMode2D = defaultValue(options.mapMode2D, MapMode2D.INFINITE_SCROLL);
  506. // Keeps track of the state of a frame. FrameState is the state across
  507. // the primitives of the scene. This state is for internally keeping track
  508. // of celestial and environment effects that need to be updated/rendered in
  509. // a certain order as well as updating/tracking framebuffer usage.
  510. this._environmentState = {
  511. skyBoxCommand: undefined,
  512. skyAtmosphereCommand: undefined,
  513. sunDrawCommand: undefined,
  514. sunComputeCommand: undefined,
  515. moonCommand: undefined,
  516. isSunVisible: false,
  517. isMoonVisible: false,
  518. isReadyForAtmosphere: false,
  519. isSkyAtmosphereVisible: false,
  520. clearGlobeDepth: false,
  521. useDepthPlane: false,
  522. renderTranslucentDepthForPick: false,
  523. originalFramebuffer: undefined,
  524. useGlobeDepthFramebuffer: false,
  525. useOIT: false,
  526. useInvertClassification: false,
  527. usePostProcess: false,
  528. usePostProcessSelected: false,
  529. useWebVR: false,
  530. };
  531. this._useWebVR = false;
  532. this._cameraVR = undefined;
  533. this._aspectRatioVR = undefined;
  534. /**
  535. * When <code>true</code>, rendering a frame will only occur when needed as determined by changes within the scene.
  536. * Enabling improves performance of the application, but requires using {@link Scene#requestRender}
  537. * to render a new frame explicitly in this mode. This will be necessary in many cases after making changes
  538. * to the scene in other parts of the API.
  539. *
  540. * @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
  541. * @see Scene#maximumRenderTimeChange
  542. * @see Scene#requestRender
  543. *
  544. * @type {boolean}
  545. * @default false
  546. */
  547. this.requestRenderMode = defaultValue(options.requestRenderMode, false);
  548. this._renderRequested = true;
  549. /**
  550. * If {@link Scene#requestRenderMode} is <code>true</code>, this value defines the maximum change in
  551. * simulation time allowed before a render is requested. Lower values increase the number of frames rendered
  552. * and higher values decrease the number of frames rendered. If <code>undefined</code>, changes to
  553. * the simulation time will never request a render.
  554. * This value impacts the rate of rendering for changes in the scene like lighting, entity property updates,
  555. * and animations.
  556. *
  557. * @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
  558. * @see Scene#requestRenderMode
  559. *
  560. * @type {number}
  561. * @default 0.0
  562. */
  563. this.maximumRenderTimeChange = defaultValue(
  564. options.maximumRenderTimeChange,
  565. 0.0
  566. );
  567. this._lastRenderTime = undefined;
  568. this._frameRateMonitor = undefined;
  569. this._removeRequestListenerCallback = RequestScheduler.requestCompletedEvent.addEventListener(
  570. requestRenderAfterFrame(this)
  571. );
  572. this._removeTaskProcessorListenerCallback = TaskProcessor.taskCompletedEvent.addEventListener(
  573. requestRenderAfterFrame(this)
  574. );
  575. this._removeGlobeCallbacks = [];
  576. this._removeTerrainProviderReadyListener = undefined;
  577. const viewport = new BoundingRectangle(
  578. 0,
  579. 0,
  580. context.drawingBufferWidth,
  581. context.drawingBufferHeight
  582. );
  583. const camera = new Camera(this);
  584. if (this._logDepthBuffer) {
  585. camera.frustum.near = 0.1;
  586. camera.frustum.far = 10000000000.0;
  587. }
  588. /**
  589. * The camera view for the scene camera flight destination. Used for preloading flight destination tiles.
  590. * @type {Camera}
  591. * @private
  592. */
  593. this.preloadFlightCamera = new Camera(this);
  594. /**
  595. * The culling volume for the scene camera flight destination. Used for preloading flight destination tiles.
  596. * @type {CullingVolume}
  597. * @private
  598. */
  599. this.preloadFlightCullingVolume = undefined;
  600. this._picking = new Picking(this);
  601. this._defaultView = new View(this, camera, viewport);
  602. this._view = this._defaultView;
  603. this._hdr = undefined;
  604. this._hdrDirty = undefined;
  605. this.highDynamicRange = false;
  606. this.gamma = 2.2;
  607. /**
  608. * The spherical harmonic coefficients for image-based lighting of PBR models.
  609. * @type {Cartesian3[]}
  610. */
  611. this.sphericalHarmonicCoefficients = undefined;
  612. /**
  613. * The url to the KTX2 file containing the specular environment map and convoluted mipmaps for image-based lighting of PBR models.
  614. * @type {string}
  615. */
  616. this.specularEnvironmentMaps = undefined;
  617. this._specularEnvironmentMapAtlas = undefined;
  618. /**
  619. * The light source for shading. Defaults to a directional light from the Sun.
  620. * @type {Light}
  621. */
  622. this.light = new SunLight();
  623. // Give frameState, camera, and screen space camera controller initial state before rendering
  624. updateFrameNumber(this, 0.0, JulianDate.now());
  625. this.updateFrameState();
  626. this.initializeFrame();
  627. }
  628. function updateGlobeListeners(scene, globe) {
  629. for (let i = 0; i < scene._removeGlobeCallbacks.length; ++i) {
  630. scene._removeGlobeCallbacks[i]();
  631. }
  632. scene._removeGlobeCallbacks.length = 0;
  633. const removeGlobeCallbacks = [];
  634. if (defined(globe)) {
  635. removeGlobeCallbacks.push(
  636. globe.imageryLayersUpdatedEvent.addEventListener(
  637. requestRenderAfterFrame(scene)
  638. )
  639. );
  640. removeGlobeCallbacks.push(
  641. globe.terrainProviderChanged.addEventListener(
  642. requestRenderAfterFrame(scene)
  643. )
  644. );
  645. }
  646. scene._removeGlobeCallbacks = removeGlobeCallbacks;
  647. }
  648. Object.defineProperties(Scene.prototype, {
  649. /**
  650. * Gets the canvas element to which this scene is bound.
  651. * @memberof Scene.prototype
  652. *
  653. * @type {HTMLCanvasElement}
  654. * @readonly
  655. */
  656. canvas: {
  657. get: function () {
  658. return this._canvas;
  659. },
  660. },
  661. /**
  662. * The drawingBufferHeight of the underlying GL context.
  663. * @memberof Scene.prototype
  664. *
  665. * @type {number}
  666. * @readonly
  667. *
  668. * @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferHeight|drawingBufferHeight}
  669. */
  670. drawingBufferHeight: {
  671. get: function () {
  672. return this._context.drawingBufferHeight;
  673. },
  674. },
  675. /**
  676. * The drawingBufferHeight of the underlying GL context.
  677. * @memberof Scene.prototype
  678. *
  679. * @type {number}
  680. * @readonly
  681. *
  682. * @see {@link https://www.khronos.org/registry/webgl/specs/1.0/#DOM-WebGLRenderingContext-drawingBufferHeight|drawingBufferHeight}
  683. */
  684. drawingBufferWidth: {
  685. get: function () {
  686. return this._context.drawingBufferWidth;
  687. },
  688. },
  689. /**
  690. * The maximum aliased line width, in pixels, supported by this WebGL implementation. It will be at least one.
  691. * @memberof Scene.prototype
  692. *
  693. * @type {number}
  694. * @readonly
  695. *
  696. * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>ALIASED_LINE_WIDTH_RANGE</code>.
  697. */
  698. maximumAliasedLineWidth: {
  699. get: function () {
  700. return ContextLimits.maximumAliasedLineWidth;
  701. },
  702. },
  703. /**
  704. * The maximum length in pixels of one edge of a cube map, supported by this WebGL implementation. It will be at least 16.
  705. * @memberof Scene.prototype
  706. *
  707. * @type {number}
  708. * @readonly
  709. *
  710. * @see {@link https://www.khronos.org/opengles/sdk/docs/man/xhtml/glGet.xml|glGet} with <code>GL_MAX_CUBE_MAP_TEXTURE_SIZE</code>.
  711. */
  712. maximumCubeMapSize: {
  713. get: function () {
  714. return ContextLimits.maximumCubeMapSize;
  715. },
  716. },
  717. /**
  718. * Returns <code>true</code> if the {@link Scene#pickPosition} function is supported.
  719. * @memberof Scene.prototype
  720. *
  721. * @type {boolean}
  722. * @readonly
  723. *
  724. * @see Scene#pickPosition
  725. */
  726. pickPositionSupported: {
  727. get: function () {
  728. return this._context.depthTexture;
  729. },
  730. },
  731. /**
  732. * Returns <code>true</code> if the {@link Scene#sampleHeight} and {@link Scene#sampleHeightMostDetailed} functions are supported.
  733. * @memberof Scene.prototype
  734. *
  735. * @type {boolean}
  736. * @readonly
  737. *
  738. * @see Scene#sampleHeight
  739. * @see Scene#sampleHeightMostDetailed
  740. */
  741. sampleHeightSupported: {
  742. get: function () {
  743. return this._context.depthTexture;
  744. },
  745. },
  746. /**
  747. * Returns <code>true</code> if the {@link Scene#clampToHeight} and {@link Scene#clampToHeightMostDetailed} functions are supported.
  748. * @memberof Scene.prototype
  749. *
  750. * @type {boolean}
  751. * @readonly
  752. *
  753. * @see Scene#clampToHeight
  754. * @see Scene#clampToHeightMostDetailed
  755. */
  756. clampToHeightSupported: {
  757. get: function () {
  758. return this._context.depthTexture;
  759. },
  760. },
  761. /**
  762. * Returns <code>true</code> if the {@link Scene#invertClassification} is supported.
  763. * @memberof Scene.prototype
  764. *
  765. * @type {boolean}
  766. * @readonly
  767. *
  768. * @see Scene#invertClassification
  769. */
  770. invertClassificationSupported: {
  771. get: function () {
  772. return this._context.depthTexture;
  773. },
  774. },
  775. /**
  776. * Returns <code>true</code> if specular environment maps are supported.
  777. * @memberof Scene.prototype
  778. *
  779. * @type {boolean}
  780. * @readonly
  781. *
  782. * @see Scene#specularEnvironmentMaps
  783. */
  784. specularEnvironmentMapsSupported: {
  785. get: function () {
  786. return OctahedralProjectedCubeMap.isSupported(this._context);
  787. },
  788. },
  789. /**
  790. * Gets or sets the depth-test ellipsoid.
  791. * @memberof Scene.prototype
  792. *
  793. * @type {Globe}
  794. */
  795. globe: {
  796. get: function () {
  797. return this._globe;
  798. },
  799. set: function (globe) {
  800. this._globe = this._globe && this._globe.destroy();
  801. this._globe = globe;
  802. updateGlobeListeners(this, globe);
  803. },
  804. },
  805. /**
  806. * Gets the collection of primitives.
  807. * @memberof Scene.prototype
  808. *
  809. * @type {PrimitiveCollection}
  810. * @readonly
  811. */
  812. primitives: {
  813. get: function () {
  814. return this._primitives;
  815. },
  816. },
  817. /**
  818. * Gets the collection of ground primitives.
  819. * @memberof Scene.prototype
  820. *
  821. * @type {PrimitiveCollection}
  822. * @readonly
  823. */
  824. groundPrimitives: {
  825. get: function () {
  826. return this._groundPrimitives;
  827. },
  828. },
  829. /**
  830. * Gets or sets the camera.
  831. * @memberof Scene.prototype
  832. *
  833. * @type {Camera}
  834. * @readonly
  835. */
  836. camera: {
  837. get: function () {
  838. return this._view.camera;
  839. },
  840. set: function (camera) {
  841. // For internal use only. Documentation is still @readonly.
  842. this._view.camera = camera;
  843. },
  844. },
  845. /**
  846. * Gets or sets the view.
  847. * @memberof Scene.prototype
  848. *
  849. * @type {View}
  850. * @readonly
  851. *
  852. * @private
  853. */
  854. view: {
  855. get: function () {
  856. return this._view;
  857. },
  858. set: function (view) {
  859. // For internal use only. Documentation is still @readonly.
  860. this._view = view;
  861. },
  862. },
  863. /**
  864. * Gets the default view.
  865. * @memberof Scene.prototype
  866. *
  867. * @type {View}
  868. * @readonly
  869. *
  870. * @private
  871. */
  872. defaultView: {
  873. get: function () {
  874. return this._defaultView;
  875. },
  876. },
  877. /**
  878. * Gets picking functions and state
  879. * @memberof Scene.prototype
  880. *
  881. * @type {Picking}
  882. * @readonly
  883. *
  884. * @private
  885. */
  886. picking: {
  887. get: function () {
  888. return this._picking;
  889. },
  890. },
  891. /**
  892. * Gets the controller for camera input handling.
  893. * @memberof Scene.prototype
  894. *
  895. * @type {ScreenSpaceCameraController}
  896. * @readonly
  897. */
  898. screenSpaceCameraController: {
  899. get: function () {
  900. return this._screenSpaceCameraController;
  901. },
  902. },
  903. /**
  904. * Get the map projection to use in 2D and Columbus View modes.
  905. * @memberof Scene.prototype
  906. *
  907. * @type {MapProjection}
  908. * @readonly
  909. *
  910. * @default new GeographicProjection()
  911. */
  912. mapProjection: {
  913. get: function () {
  914. return this._mapProjection;
  915. },
  916. },
  917. /**
  918. * Gets the job scheduler
  919. * @memberof Scene.prototype
  920. * @type {JobScheduler}
  921. * @readonly
  922. *
  923. * @private
  924. */
  925. jobScheduler: {
  926. get: function () {
  927. return this._jobScheduler;
  928. },
  929. },
  930. /**
  931. * Gets state information about the current scene. If called outside of a primitive's <code>update</code>
  932. * function, the previous frame's state is returned.
  933. * @memberof Scene.prototype
  934. *
  935. * @type {FrameState}
  936. * @readonly
  937. *
  938. * @private
  939. */
  940. frameState: {
  941. get: function () {
  942. return this._frameState;
  943. },
  944. },
  945. /**
  946. * Gets the environment state.
  947. * @memberof Scene.prototype
  948. *
  949. * @type {EnvironmentState}
  950. * @readonly
  951. *
  952. * @private
  953. */
  954. environmentState: {
  955. get: function () {
  956. return this._environmentState;
  957. },
  958. },
  959. /**
  960. * Gets the collection of tweens taking place in the scene.
  961. * @memberof Scene.prototype
  962. *
  963. * @type {TweenCollection}
  964. * @readonly
  965. *
  966. * @private
  967. */
  968. tweens: {
  969. get: function () {
  970. return this._tweens;
  971. },
  972. },
  973. /**
  974. * Gets the collection of image layers that will be rendered on the globe.
  975. * @memberof Scene.prototype
  976. *
  977. * @type {ImageryLayerCollection}
  978. * @readonly
  979. */
  980. imageryLayers: {
  981. get: function () {
  982. if (!defined(this.globe)) {
  983. return undefined;
  984. }
  985. return this.globe.imageryLayers;
  986. },
  987. },
  988. /**
  989. * The terrain provider providing surface geometry for the globe.
  990. * @memberof Scene.prototype
  991. *
  992. * @type {TerrainProvider}
  993. */
  994. terrainProvider: {
  995. get: function () {
  996. if (!defined(this.globe)) {
  997. return undefined;
  998. }
  999. return this.globe.terrainProvider;
  1000. },
  1001. set: function (terrainProvider) {
  1002. // Cancel any in-progress terrain update
  1003. this._removeTerrainProviderReadyListener =
  1004. this._removeTerrainProviderReadyListener &&
  1005. this._removeTerrainProviderReadyListener();
  1006. if (defined(this.globe)) {
  1007. this.globe.terrainProvider = terrainProvider;
  1008. }
  1009. },
  1010. },
  1011. /**
  1012. * Gets an event that's raised when the terrain provider is changed
  1013. * @memberof Scene.prototype
  1014. *
  1015. * @type {Event}
  1016. * @readonly
  1017. */
  1018. terrainProviderChanged: {
  1019. get: function () {
  1020. if (!defined(this.globe)) {
  1021. return undefined;
  1022. }
  1023. return this.globe.terrainProviderChanged;
  1024. },
  1025. },
  1026. /**
  1027. * Gets the event that will be raised before the scene is updated or rendered. Subscribers to the event
  1028. * receive the Scene instance as the first parameter and the current time as the second parameter.
  1029. * @memberof Scene.prototype
  1030. *
  1031. * @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
  1032. * @see Scene#postUpdate
  1033. * @see Scene#preRender
  1034. * @see Scene#postRender
  1035. *
  1036. * @type {Event}
  1037. * @readonly
  1038. */
  1039. preUpdate: {
  1040. get: function () {
  1041. return this._preUpdate;
  1042. },
  1043. },
  1044. /**
  1045. * Gets the event that will be raised immediately after the scene is updated and before the scene is rendered.
  1046. * Subscribers to the event receive the Scene instance as the first parameter and the current time as the second
  1047. * parameter.
  1048. * @memberof Scene.prototype
  1049. *
  1050. * @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
  1051. * @see Scene#preUpdate
  1052. * @see Scene#preRender
  1053. * @see Scene#postRender
  1054. *
  1055. * @type {Event}
  1056. * @readonly
  1057. */
  1058. postUpdate: {
  1059. get: function () {
  1060. return this._postUpdate;
  1061. },
  1062. },
  1063. /**
  1064. * Gets the event that will be raised when an error is thrown inside the <code>render</code> function.
  1065. * The Scene instance and the thrown error are the only two parameters passed to the event handler.
  1066. * By default, errors are not rethrown after this event is raised, but that can be changed by setting
  1067. * the <code>rethrowRenderErrors</code> property.
  1068. * @memberof Scene.prototype
  1069. *
  1070. * @type {Event}
  1071. * @readonly
  1072. */
  1073. renderError: {
  1074. get: function () {
  1075. return this._renderError;
  1076. },
  1077. },
  1078. /**
  1079. * Gets the event that will be raised after the scene is updated and immediately before the scene is rendered.
  1080. * Subscribers to the event receive the Scene instance as the first parameter and the current time as the second
  1081. * parameter.
  1082. * @memberof Scene.prototype
  1083. *
  1084. * @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
  1085. * @see Scene#preUpdate
  1086. * @see Scene#postUpdate
  1087. * @see Scene#postRender
  1088. *
  1089. * @type {Event}
  1090. * @readonly
  1091. */
  1092. preRender: {
  1093. get: function () {
  1094. return this._preRender;
  1095. },
  1096. },
  1097. /**
  1098. * Gets the event that will be raised immediately after the scene is rendered. Subscribers to the event
  1099. * receive the Scene instance as the first parameter and the current time as the second parameter.
  1100. * @memberof Scene.prototype
  1101. *
  1102. * @see {@link https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/|Improving Performance with Explicit Rendering}
  1103. * @see Scene#preUpdate
  1104. * @see Scene#postUpdate
  1105. * @see Scene#postRender
  1106. *
  1107. * @type {Event}
  1108. * @readonly
  1109. */
  1110. postRender: {
  1111. get: function () {
  1112. return this._postRender;
  1113. },
  1114. },
  1115. /**
  1116. * Gets the simulation time when the scene was last rendered. Returns undefined if the scene has not yet been
  1117. * rendered.
  1118. * @memberof Scene.prototype
  1119. *
  1120. * @type {JulianDate}
  1121. * @readonly
  1122. */
  1123. lastRenderTime: {
  1124. get: function () {
  1125. return this._lastRenderTime;
  1126. },
  1127. },
  1128. /**
  1129. * @memberof Scene.prototype
  1130. * @private
  1131. * @readonly
  1132. */
  1133. context: {
  1134. get: function () {
  1135. return this._context;
  1136. },
  1137. },
  1138. /**
  1139. * This property is for debugging only; it is not for production use.
  1140. * <p>
  1141. * When {@link Scene.debugShowFrustums} is <code>true</code>, this contains
  1142. * properties with statistics about the number of command execute per frustum.
  1143. * <code>totalCommands</code> is the total number of commands executed, ignoring
  1144. * overlap. <code>commandsInFrustums</code> is an array with the number of times
  1145. * commands are executed redundantly, e.g., how many commands overlap two or
  1146. * three frustums.
  1147. * </p>
  1148. *
  1149. * @memberof Scene.prototype
  1150. *
  1151. * @type {object}
  1152. * @readonly
  1153. *
  1154. * @default undefined
  1155. */
  1156. debugFrustumStatistics: {
  1157. get: function () {
  1158. return this._view.debugFrustumStatistics;
  1159. },
  1160. },
  1161. /**
  1162. * Gets whether or not the scene is optimized for 3D only viewing.
  1163. * @memberof Scene.prototype
  1164. * @type {boolean}
  1165. * @readonly
  1166. */
  1167. scene3DOnly: {
  1168. get: function () {
  1169. return this._frameState.scene3DOnly;
  1170. },
  1171. },
  1172. /**
  1173. * Gets whether or not the scene has order independent translucency enabled.
  1174. * Note that this only reflects the original construction option, and there are
  1175. * other factors that could prevent OIT from functioning on a given system configuration.
  1176. * @memberof Scene.prototype
  1177. * @type {boolean}
  1178. * @readonly
  1179. */
  1180. orderIndependentTranslucency: {
  1181. get: function () {
  1182. return this._useOIT;
  1183. },
  1184. },
  1185. /**
  1186. * Gets the unique identifier for this scene.
  1187. * @memberof Scene.prototype
  1188. * @type {string}
  1189. * @readonly
  1190. */
  1191. id: {
  1192. get: function () {
  1193. return this._id;
  1194. },
  1195. },
  1196. /**
  1197. * Gets or sets the current mode of the scene.
  1198. * @memberof Scene.prototype
  1199. * @type {SceneMode}
  1200. * @default {@link SceneMode.SCENE3D}
  1201. */
  1202. mode: {
  1203. get: function () {
  1204. return this._mode;
  1205. },
  1206. set: function (value) {
  1207. //>>includeStart('debug', pragmas.debug);
  1208. if (this.scene3DOnly && value !== SceneMode.SCENE3D) {
  1209. throw new DeveloperError(
  1210. "Only SceneMode.SCENE3D is valid when scene3DOnly is true."
  1211. );
  1212. }
  1213. //>>includeEnd('debug');
  1214. if (value === SceneMode.SCENE2D) {
  1215. this.morphTo2D(0);
  1216. } else if (value === SceneMode.SCENE3D) {
  1217. this.morphTo3D(0);
  1218. } else if (value === SceneMode.COLUMBUS_VIEW) {
  1219. this.morphToColumbusView(0);
  1220. //>>includeStart('debug', pragmas.debug);
  1221. } else {
  1222. throw new DeveloperError(
  1223. "value must be a valid SceneMode enumeration."
  1224. );
  1225. //>>includeEnd('debug');
  1226. }
  1227. this._mode = value;
  1228. },
  1229. },
  1230. /**
  1231. * Gets the number of frustums used in the last frame.
  1232. * @memberof Scene.prototype
  1233. * @type {FrustumCommands[]}
  1234. *
  1235. * @private
  1236. */
  1237. frustumCommandsList: {
  1238. get: function () {
  1239. return this._view.frustumCommandsList;
  1240. },
  1241. },
  1242. /**
  1243. * Gets the number of frustums used in the last frame.
  1244. * @memberof Scene.prototype
  1245. * @type {number}
  1246. *
  1247. * @private
  1248. */
  1249. numberOfFrustums: {
  1250. get: function () {
  1251. return this._view.frustumCommandsList.length;
  1252. },
  1253. },
  1254. /**
  1255. * When <code>true</code>, splits the scene into two viewports with steroscopic views for the left and right eyes.
  1256. * Used for cardboard and WebVR.
  1257. * @memberof Scene.prototype
  1258. * @type {boolean}
  1259. * @default false
  1260. */
  1261. useWebVR: {
  1262. get: function () {
  1263. return this._useWebVR;
  1264. },
  1265. set: function (value) {
  1266. //>>includeStart('debug', pragmas.debug);
  1267. if (this.camera.frustum instanceof OrthographicFrustum) {
  1268. throw new DeveloperError(
  1269. "VR is unsupported with an orthographic projection."
  1270. );
  1271. }
  1272. //>>includeEnd('debug');
  1273. this._useWebVR = value;
  1274. if (this._useWebVR) {
  1275. this._frameState.creditDisplay.container.style.visibility = "hidden";
  1276. this._cameraVR = new Camera(this);
  1277. if (!defined(this._deviceOrientationCameraController)) {
  1278. this._deviceOrientationCameraController = new DeviceOrientationCameraController(
  1279. this
  1280. );
  1281. }
  1282. this._aspectRatioVR = this.camera.frustum.aspectRatio;
  1283. } else {
  1284. this._frameState.creditDisplay.container.style.visibility = "visible";
  1285. this._cameraVR = undefined;
  1286. this._deviceOrientationCameraController =
  1287. this._deviceOrientationCameraController &&
  1288. !this._deviceOrientationCameraController.isDestroyed() &&
  1289. this._deviceOrientationCameraController.destroy();
  1290. this.camera.frustum.aspectRatio = this._aspectRatioVR;
  1291. this.camera.frustum.xOffset = 0.0;
  1292. }
  1293. },
  1294. },
  1295. /**
  1296. * Determines if the 2D map is rotatable or can be scrolled infinitely in the horizontal direction.
  1297. * @memberof Scene.prototype
  1298. * @type {MapMode2D}
  1299. * @readonly
  1300. */
  1301. mapMode2D: {
  1302. get: function () {
  1303. return this._mapMode2D;
  1304. },
  1305. },
  1306. /**
  1307. * Gets or sets the position of the splitter within the viewport. Valid values are between 0.0 and 1.0.
  1308. * @memberof Scene.prototype
  1309. *
  1310. * @type {number}
  1311. */
  1312. splitPosition: {
  1313. get: function () {
  1314. return this._frameState.splitPosition;
  1315. },
  1316. set: function (value) {
  1317. this._frameState.splitPosition = value;
  1318. },
  1319. },
  1320. /**
  1321. * The distance from the camera at which to disable the depth test of billboards, labels and points
  1322. * to, for example, prevent clipping against terrain. When set to zero, the depth test should always
  1323. * be applied. When less than zero, the depth test should never be applied. Setting the disableDepthTestDistance
  1324. * property of a billboard, label or point will override this value.
  1325. * @memberof Scene.prototype
  1326. * @type {number}
  1327. * @default 0.0
  1328. */
  1329. minimumDisableDepthTestDistance: {
  1330. get: function () {
  1331. return this._minimumDisableDepthTestDistance;
  1332. },
  1333. set: function (value) {
  1334. //>>includeStart('debug', pragmas.debug);
  1335. if (!defined(value) || value < 0.0) {
  1336. throw new DeveloperError(
  1337. "minimumDisableDepthTestDistance must be greater than or equal to 0.0."
  1338. );
  1339. }
  1340. //>>includeEnd('debug');
  1341. this._minimumDisableDepthTestDistance = value;
  1342. },
  1343. },
  1344. /**
  1345. * Whether or not to use a logarithmic depth buffer. Enabling this option will allow for less frustums in the multi-frustum,
  1346. * increasing performance. This property relies on fragmentDepth being supported.
  1347. * @memberof Scene.prototype
  1348. * @type {boolean}
  1349. */
  1350. logarithmicDepthBuffer: {
  1351. get: function () {
  1352. return this._logDepthBuffer;
  1353. },
  1354. set: function (value) {
  1355. value = this._context.fragmentDepth && value;
  1356. if (this._logDepthBuffer !== value) {
  1357. this._logDepthBuffer = value;
  1358. this._logDepthBufferDirty = true;
  1359. }
  1360. },
  1361. },
  1362. /**
  1363. * The value used for gamma correction. This is only used when rendering with high dynamic range.
  1364. * @memberof Scene.prototype
  1365. * @type {number}
  1366. * @default 2.2
  1367. */
  1368. gamma: {
  1369. get: function () {
  1370. return this._context.uniformState.gamma;
  1371. },
  1372. set: function (value) {
  1373. this._context.uniformState.gamma = value;
  1374. },
  1375. },
  1376. /**
  1377. * Whether or not to use high dynamic range rendering.
  1378. * @memberof Scene.prototype
  1379. * @type {boolean}
  1380. * @default false
  1381. */
  1382. highDynamicRange: {
  1383. get: function () {
  1384. return this._hdr;
  1385. },
  1386. set: function (value) {
  1387. const context = this._context;
  1388. const hdr =
  1389. value &&
  1390. context.depthTexture &&
  1391. (context.colorBufferFloat || context.colorBufferHalfFloat);
  1392. this._hdrDirty = hdr !== this._hdr;
  1393. this._hdr = hdr;
  1394. },
  1395. },
  1396. /**
  1397. * Whether or not high dynamic range rendering is supported.
  1398. * @memberof Scene.prototype
  1399. * @type {boolean}
  1400. * @readonly
  1401. * @default true
  1402. */
  1403. highDynamicRangeSupported: {
  1404. get: function () {
  1405. const context = this._context;
  1406. return (
  1407. context.depthTexture &&
  1408. (context.colorBufferFloat || context.colorBufferHalfFloat)
  1409. );
  1410. },
  1411. },
  1412. /**
  1413. * Whether or not the camera is underneath the globe.
  1414. * @memberof Scene.prototype
  1415. * @type {boolean}
  1416. * @readonly
  1417. * @default false
  1418. */
  1419. cameraUnderground: {
  1420. get: function () {
  1421. return this._cameraUnderground;
  1422. },
  1423. },
  1424. /**
  1425. * The sample rate of multisample antialiasing (values greater than 1 enable MSAA).
  1426. * @memberof Scene.prototype
  1427. * @type {number}
  1428. * @default 1
  1429. */
  1430. msaaSamples: {
  1431. get: function () {
  1432. return this._msaaSamples;
  1433. },
  1434. set: function (value) {
  1435. value = Math.min(value, ContextLimits.maximumSamples);
  1436. this._msaaSamples = value;
  1437. },
  1438. },
  1439. /**
  1440. * Returns <code>true</code> if the Scene's context supports MSAA.
  1441. * @memberof Scene.prototype
  1442. * @type {boolean}
  1443. * @readonly
  1444. */
  1445. msaaSupported: {
  1446. get: function () {
  1447. return this._context.msaa;
  1448. },
  1449. },
  1450. /**
  1451. * Ratio between a pixel and a density-independent pixel. Provides a standard unit of
  1452. * measure for real pixel measurements appropriate to a particular device.
  1453. *
  1454. * @memberof Scene.prototype
  1455. * @type {number}
  1456. * @default 1.0
  1457. * @private
  1458. */
  1459. pixelRatio: {
  1460. get: function () {
  1461. return this._frameState.pixelRatio;
  1462. },
  1463. set: function (value) {
  1464. this._frameState.pixelRatio = value;
  1465. },
  1466. },
  1467. /**
  1468. * @private
  1469. */
  1470. opaqueFrustumNearOffset: {
  1471. get: function () {
  1472. return 0.9999;
  1473. },
  1474. },
  1475. /**
  1476. * @private
  1477. */
  1478. globeHeight: {
  1479. get: function () {
  1480. return this._globeHeight;
  1481. },
  1482. },
  1483. });
  1484. /**
  1485. * Determines if a compressed texture format is supported.
  1486. * @param {string} format The texture format. May be the name of the format or the WebGL extension name, e.g. s3tc or WEBGL_compressed_texture_s3tc.
  1487. * @return {boolean} Whether or not the format is supported.
  1488. */
  1489. Scene.prototype.getCompressedTextureFormatSupported = function (format) {
  1490. const context = this.context;
  1491. return (
  1492. ((format === "WEBGL_compressed_texture_s3tc" || format === "s3tc") &&
  1493. context.s3tc) ||
  1494. ((format === "WEBGL_compressed_texture_pvrtc" || format === "pvrtc") &&
  1495. context.pvrtc) ||
  1496. ((format === "WEBGL_compressed_texture_etc" || format === "etc") &&
  1497. context.etc) ||
  1498. ((format === "WEBGL_compressed_texture_etc1" || format === "etc1") &&
  1499. context.etc1) ||
  1500. ((format === "WEBGL_compressed_texture_astc" || format === "astc") &&
  1501. context.astc) ||
  1502. ((format === "EXT_texture_compression_bptc" || format === "bc7") &&
  1503. context.bc7)
  1504. );
  1505. };
  1506. function updateDerivedCommands(scene, command, shadowsDirty) {
  1507. const frameState = scene._frameState;
  1508. const context = scene._context;
  1509. const oit = scene._view.oit;
  1510. const lightShadowMaps = frameState.shadowState.lightShadowMaps;
  1511. const lightShadowsEnabled = frameState.shadowState.lightShadowsEnabled;
  1512. let derivedCommands = command.derivedCommands;
  1513. if (defined(command.pickId)) {
  1514. derivedCommands.picking = DerivedCommand.createPickDerivedCommand(
  1515. scene,
  1516. command,
  1517. context,
  1518. derivedCommands.picking
  1519. );
  1520. }
  1521. if (!command.pickOnly) {
  1522. derivedCommands.depth = DerivedCommand.createDepthOnlyDerivedCommand(
  1523. scene,
  1524. command,
  1525. context,
  1526. derivedCommands.depth
  1527. );
  1528. }
  1529. derivedCommands.originalCommand = command;
  1530. if (scene._hdr) {
  1531. derivedCommands.hdr = DerivedCommand.createHdrCommand(
  1532. command,
  1533. context,
  1534. derivedCommands.hdr
  1535. );
  1536. command = derivedCommands.hdr.command;
  1537. derivedCommands = command.derivedCommands;
  1538. }
  1539. if (lightShadowsEnabled && command.receiveShadows) {
  1540. derivedCommands.shadows = ShadowMap.createReceiveDerivedCommand(
  1541. lightShadowMaps,
  1542. command,
  1543. shadowsDirty,
  1544. context,
  1545. derivedCommands.shadows
  1546. );
  1547. }
  1548. if (command.pass === Pass.TRANSLUCENT && defined(oit) && oit.isSupported()) {
  1549. if (lightShadowsEnabled && command.receiveShadows) {
  1550. derivedCommands.oit = defined(derivedCommands.oit)
  1551. ? derivedCommands.oit
  1552. : {};
  1553. derivedCommands.oit.shadows = oit.createDerivedCommands(
  1554. derivedCommands.shadows.receiveCommand,
  1555. context,
  1556. derivedCommands.oit.shadows
  1557. );
  1558. } else {
  1559. derivedCommands.oit = oit.createDerivedCommands(
  1560. command,
  1561. context,
  1562. derivedCommands.oit
  1563. );
  1564. }
  1565. }
  1566. }
  1567. /**
  1568. * @private
  1569. */
  1570. Scene.prototype.updateDerivedCommands = function (command) {
  1571. if (!defined(command.derivedCommands)) {
  1572. // Is not a DrawCommand
  1573. return;
  1574. }
  1575. const frameState = this._frameState;
  1576. const context = this._context;
  1577. // Update derived commands when any shadow maps become dirty
  1578. let shadowsDirty = false;
  1579. const lastDirtyTime = frameState.shadowState.lastDirtyTime;
  1580. if (command.lastDirtyTime !== lastDirtyTime) {
  1581. command.lastDirtyTime = lastDirtyTime;
  1582. command.dirty = true;
  1583. shadowsDirty = true;
  1584. }
  1585. const useLogDepth = frameState.useLogDepth;
  1586. const useHdr = this._hdr;
  1587. const derivedCommands = command.derivedCommands;
  1588. const hasLogDepthDerivedCommands = defined(derivedCommands.logDepth);
  1589. const hasHdrCommands = defined(derivedCommands.hdr);
  1590. const hasDerivedCommands = defined(derivedCommands.originalCommand);
  1591. const needsLogDepthDerivedCommands =
  1592. useLogDepth && !hasLogDepthDerivedCommands;
  1593. const needsHdrCommands = useHdr && !hasHdrCommands;
  1594. const needsDerivedCommands = (!useLogDepth || !useHdr) && !hasDerivedCommands;
  1595. command.dirty =
  1596. command.dirty ||
  1597. needsLogDepthDerivedCommands ||
  1598. needsHdrCommands ||
  1599. needsDerivedCommands;
  1600. if (command.dirty) {
  1601. command.dirty = false;
  1602. const shadowMaps = frameState.shadowState.shadowMaps;
  1603. const shadowsEnabled = frameState.shadowState.shadowsEnabled;
  1604. if (shadowsEnabled && command.castShadows) {
  1605. derivedCommands.shadows = ShadowMap.createCastDerivedCommand(
  1606. shadowMaps,
  1607. command,
  1608. shadowsDirty,
  1609. context,
  1610. derivedCommands.shadows
  1611. );
  1612. }
  1613. if (hasLogDepthDerivedCommands || needsLogDepthDerivedCommands) {
  1614. derivedCommands.logDepth = DerivedCommand.createLogDepthCommand(
  1615. command,
  1616. context,
  1617. derivedCommands.logDepth
  1618. );
  1619. updateDerivedCommands(
  1620. this,
  1621. derivedCommands.logDepth.command,
  1622. shadowsDirty
  1623. );
  1624. }
  1625. if (hasDerivedCommands || needsDerivedCommands) {
  1626. updateDerivedCommands(this, command, shadowsDirty);
  1627. }
  1628. }
  1629. };
  1630. const renderTilesetPassState = new Cesium3DTilePassState({
  1631. pass: Cesium3DTilePass.RENDER,
  1632. });
  1633. const preloadTilesetPassState = new Cesium3DTilePassState({
  1634. pass: Cesium3DTilePass.PRELOAD,
  1635. });
  1636. const preloadFlightTilesetPassState = new Cesium3DTilePassState({
  1637. pass: Cesium3DTilePass.PRELOAD_FLIGHT,
  1638. });
  1639. const requestRenderModeDeferCheckPassState = new Cesium3DTilePassState({
  1640. pass: Cesium3DTilePass.REQUEST_RENDER_MODE_DEFER_CHECK,
  1641. });
  1642. const scratchOccluderBoundingSphere = new BoundingSphere();
  1643. let scratchOccluder;
  1644. function getOccluder(scene) {
  1645. // TODO: The occluder is the top-level globe. When we add
  1646. // support for multiple central bodies, this should be the closest one.
  1647. const globe = scene.globe;
  1648. if (
  1649. scene._mode === SceneMode.SCENE3D &&
  1650. defined(globe) &&
  1651. globe.show &&
  1652. !scene._cameraUnderground &&
  1653. !scene._globeTranslucencyState.translucent
  1654. ) {
  1655. const ellipsoid = globe.ellipsoid;
  1656. const minimumTerrainHeight = scene.frameState.minimumTerrainHeight;
  1657. scratchOccluderBoundingSphere.radius =
  1658. ellipsoid.minimumRadius + minimumTerrainHeight;
  1659. scratchOccluder = Occluder.fromBoundingSphere(
  1660. scratchOccluderBoundingSphere,
  1661. scene.camera.positionWC,
  1662. scratchOccluder
  1663. );
  1664. return scratchOccluder;
  1665. }
  1666. return undefined;
  1667. }
  1668. /**
  1669. * @private
  1670. */
  1671. Scene.prototype.clearPasses = function (passes) {
  1672. passes.render = false;
  1673. passes.pick = false;
  1674. passes.depth = false;
  1675. passes.postProcess = false;
  1676. passes.offscreen = false;
  1677. };
  1678. function updateFrameNumber(scene, frameNumber, time) {
  1679. const frameState = scene._frameState;
  1680. frameState.frameNumber = frameNumber;
  1681. frameState.time = JulianDate.clone(time, frameState.time);
  1682. }
  1683. /**
  1684. * @private
  1685. */
  1686. Scene.prototype.updateFrameState = function () {
  1687. const camera = this.camera;
  1688. const frameState = this._frameState;
  1689. frameState.commandList.length = 0;
  1690. frameState.shadowMaps.length = 0;
  1691. frameState.brdfLutGenerator = this._brdfLutGenerator;
  1692. frameState.environmentMap = this.skyBox && this.skyBox._cubeMap;
  1693. frameState.mode = this._mode;
  1694. frameState.morphTime = this.morphTime;
  1695. frameState.mapProjection = this.mapProjection;
  1696. frameState.camera = camera;
  1697. frameState.cullingVolume = camera.frustum.computeCullingVolume(
  1698. camera.positionWC,
  1699. camera.directionWC,
  1700. camera.upWC
  1701. );
  1702. frameState.occluder = getOccluder(this);
  1703. frameState.minimumTerrainHeight = 0.0;
  1704. frameState.minimumDisableDepthTestDistance = this._minimumDisableDepthTestDistance;
  1705. frameState.invertClassification = this.invertClassification;
  1706. frameState.useLogDepth =
  1707. this._logDepthBuffer &&
  1708. !(
  1709. this.camera.frustum instanceof OrthographicFrustum ||
  1710. this.camera.frustum instanceof OrthographicOffCenterFrustum
  1711. );
  1712. frameState.light = this.light;
  1713. frameState.cameraUnderground = this._cameraUnderground;
  1714. frameState.globeTranslucencyState = this._globeTranslucencyState;
  1715. if (defined(this.globe)) {
  1716. frameState.terrainExaggeration = this.globe.terrainExaggeration;
  1717. frameState.terrainExaggerationRelativeHeight = this.globe.terrainExaggerationRelativeHeight;
  1718. }
  1719. if (
  1720. defined(this._specularEnvironmentMapAtlas) &&
  1721. this._specularEnvironmentMapAtlas.ready
  1722. ) {
  1723. frameState.specularEnvironmentMaps = this._specularEnvironmentMapAtlas.texture;
  1724. frameState.specularEnvironmentMapsMaximumLOD = this._specularEnvironmentMapAtlas.maximumMipmapLevel;
  1725. } else {
  1726. frameState.specularEnvironmentMaps = undefined;
  1727. frameState.specularEnvironmentMapsMaximumLOD = undefined;
  1728. }
  1729. frameState.sphericalHarmonicCoefficients = this.sphericalHarmonicCoefficients;
  1730. this._actualInvertClassificationColor = Color.clone(
  1731. this.invertClassificationColor,
  1732. this._actualInvertClassificationColor
  1733. );
  1734. if (!InvertClassification.isTranslucencySupported(this._context)) {
  1735. this._actualInvertClassificationColor.alpha = 1.0;
  1736. }
  1737. frameState.invertClassificationColor = this._actualInvertClassificationColor;
  1738. if (defined(this.globe)) {
  1739. frameState.maximumScreenSpaceError = this.globe.maximumScreenSpaceError;
  1740. } else {
  1741. frameState.maximumScreenSpaceError = 2;
  1742. }
  1743. this.clearPasses(frameState.passes);
  1744. frameState.tilesetPassState = undefined;
  1745. };
  1746. /**
  1747. * @private
  1748. */
  1749. Scene.prototype.isVisible = function (command, cullingVolume, occluder) {
  1750. return (
  1751. defined(command) &&
  1752. (!defined(command.boundingVolume) ||
  1753. !command.cull ||
  1754. (cullingVolume.computeVisibility(command.boundingVolume) !==
  1755. Intersect.OUTSIDE &&
  1756. (!defined(occluder) ||
  1757. !command.occlude ||
  1758. !command.boundingVolume.isOccluded(occluder))))
  1759. );
  1760. };
  1761. let transformFrom2D = new Matrix4(
  1762. 0.0,
  1763. 0.0,
  1764. 1.0,
  1765. 0.0,
  1766. 1.0,
  1767. 0.0,
  1768. 0.0,
  1769. 0.0,
  1770. 0.0,
  1771. 1.0,
  1772. 0.0,
  1773. 0.0,
  1774. 0.0,
  1775. 0.0,
  1776. 0.0,
  1777. 1.0
  1778. );
  1779. transformFrom2D = Matrix4.inverseTransformation(
  1780. transformFrom2D,
  1781. transformFrom2D
  1782. );
  1783. function debugShowBoundingVolume(command, scene, passState, debugFramebuffer) {
  1784. // Debug code to draw bounding volume for command. Not optimized!
  1785. // Assumes bounding volume is a bounding sphere or box
  1786. const frameState = scene._frameState;
  1787. const context = frameState.context;
  1788. const boundingVolume = command.boundingVolume;
  1789. if (defined(scene._debugVolume)) {
  1790. scene._debugVolume.destroy();
  1791. }
  1792. let geometry;
  1793. let center = Cartesian3.clone(boundingVolume.center);
  1794. if (frameState.mode !== SceneMode.SCENE3D) {
  1795. center = Matrix4.multiplyByPoint(transformFrom2D, center, center);
  1796. const projection = frameState.mapProjection;
  1797. const centerCartographic = projection.unproject(center);
  1798. center = projection.ellipsoid.cartographicToCartesian(centerCartographic);
  1799. }
  1800. if (defined(boundingVolume.radius)) {
  1801. const radius = boundingVolume.radius;
  1802. geometry = GeometryPipeline.toWireframe(
  1803. EllipsoidGeometry.createGeometry(
  1804. new EllipsoidGeometry({
  1805. radii: new Cartesian3(radius, radius, radius),
  1806. vertexFormat: PerInstanceColorAppearance.FLAT_VERTEX_FORMAT,
  1807. })
  1808. )
  1809. );
  1810. scene._debugVolume = new Primitive({
  1811. geometryInstances: new GeometryInstance({
  1812. geometry: geometry,
  1813. modelMatrix: Matrix4.fromTranslation(center),
  1814. attributes: {
  1815. color: new ColorGeometryInstanceAttribute(1.0, 0.0, 0.0, 1.0),
  1816. },
  1817. }),
  1818. appearance: new PerInstanceColorAppearance({
  1819. flat: true,
  1820. translucent: false,
  1821. }),
  1822. asynchronous: false,
  1823. });
  1824. } else {
  1825. const halfAxes = boundingVolume.halfAxes;
  1826. geometry = GeometryPipeline.toWireframe(
  1827. BoxGeometry.createGeometry(
  1828. BoxGeometry.fromDimensions({
  1829. dimensions: new Cartesian3(2.0, 2.0, 2.0),
  1830. vertexFormat: PerInstanceColorAppearance.FLAT_VERTEX_FORMAT,
  1831. })
  1832. )
  1833. );
  1834. scene._debugVolume = new Primitive({
  1835. geometryInstances: new GeometryInstance({
  1836. geometry: geometry,
  1837. modelMatrix: Matrix4.fromRotationTranslation(
  1838. halfAxes,
  1839. center,
  1840. new Matrix4()
  1841. ),
  1842. attributes: {
  1843. color: new ColorGeometryInstanceAttribute(1.0, 0.0, 0.0, 1.0),
  1844. },
  1845. }),
  1846. appearance: new PerInstanceColorAppearance({
  1847. flat: true,
  1848. translucent: false,
  1849. }),
  1850. asynchronous: false,
  1851. });
  1852. }
  1853. const savedCommandList = frameState.commandList;
  1854. const commandList = (frameState.commandList = []);
  1855. scene._debugVolume.update(frameState);
  1856. command = commandList[0];
  1857. if (frameState.useLogDepth) {
  1858. const logDepth = DerivedCommand.createLogDepthCommand(command, context);
  1859. command = logDepth.command;
  1860. }
  1861. let framebuffer;
  1862. if (defined(debugFramebuffer)) {
  1863. framebuffer = passState.framebuffer;
  1864. passState.framebuffer = debugFramebuffer;
  1865. }
  1866. command.execute(context, passState);
  1867. if (defined(framebuffer)) {
  1868. passState.framebuffer = framebuffer;
  1869. }
  1870. frameState.commandList = savedCommandList;
  1871. }
  1872. function executeCommand(command, scene, context, passState, debugFramebuffer) {
  1873. const frameState = scene._frameState;
  1874. if (defined(scene.debugCommandFilter) && !scene.debugCommandFilter(command)) {
  1875. return;
  1876. }
  1877. if (command instanceof ClearCommand) {
  1878. command.execute(context, passState);
  1879. return;
  1880. }
  1881. if (command.debugShowBoundingVolume && defined(command.boundingVolume)) {
  1882. debugShowBoundingVolume(command, scene, passState, debugFramebuffer);
  1883. }
  1884. if (frameState.useLogDepth && defined(command.derivedCommands.logDepth)) {
  1885. command = command.derivedCommands.logDepth.command;
  1886. }
  1887. const passes = frameState.passes;
  1888. if (
  1889. !passes.pick &&
  1890. !passes.depth &&
  1891. scene._hdr &&
  1892. defined(command.derivedCommands) &&
  1893. defined(command.derivedCommands.hdr)
  1894. ) {
  1895. command = command.derivedCommands.hdr.command;
  1896. }
  1897. if (passes.pick || passes.depth) {
  1898. if (
  1899. passes.pick &&
  1900. !passes.depth &&
  1901. defined(command.derivedCommands.picking)
  1902. ) {
  1903. command = command.derivedCommands.picking.pickCommand;
  1904. command.execute(context, passState);
  1905. return;
  1906. } else if (defined(command.derivedCommands.depth)) {
  1907. command = command.derivedCommands.depth.depthOnlyCommand;
  1908. command.execute(context, passState);
  1909. return;
  1910. }
  1911. }
  1912. if (scene.debugShowCommands || scene.debugShowFrustums) {
  1913. scene._debugInspector.executeDebugShowFrustumsCommand(
  1914. scene,
  1915. command,
  1916. passState
  1917. );
  1918. return;
  1919. }
  1920. if (
  1921. frameState.shadowState.lightShadowsEnabled &&
  1922. command.receiveShadows &&
  1923. defined(command.derivedCommands.shadows)
  1924. ) {
  1925. // If the command receives shadows, execute the derived shadows command.
  1926. // Some commands, such as OIT derived commands, do not have derived shadow commands themselves
  1927. // and instead shadowing is built-in. In this case execute the command regularly below.
  1928. command.derivedCommands.shadows.receiveCommand.execute(context, passState);
  1929. } else {
  1930. command.execute(context, passState);
  1931. }
  1932. }
  1933. function executeIdCommand(command, scene, context, passState) {
  1934. const frameState = scene._frameState;
  1935. let derivedCommands = command.derivedCommands;
  1936. if (!defined(derivedCommands)) {
  1937. return;
  1938. }
  1939. if (frameState.useLogDepth && defined(derivedCommands.logDepth)) {
  1940. command = derivedCommands.logDepth.command;
  1941. }
  1942. derivedCommands = command.derivedCommands;
  1943. if (defined(derivedCommands.picking)) {
  1944. command = derivedCommands.picking.pickCommand;
  1945. command.execute(context, passState);
  1946. } else if (defined(derivedCommands.depth)) {
  1947. command = derivedCommands.depth.depthOnlyCommand;
  1948. command.execute(context, passState);
  1949. }
  1950. }
  1951. function backToFront(a, b, position) {
  1952. return (
  1953. b.boundingVolume.distanceSquaredTo(position) -
  1954. a.boundingVolume.distanceSquaredTo(position)
  1955. );
  1956. }
  1957. function frontToBack(a, b, position) {
  1958. // When distances are equal equal favor sorting b before a. This gives render priority to commands later in the list.
  1959. return (
  1960. a.boundingVolume.distanceSquaredTo(position) -
  1961. b.boundingVolume.distanceSquaredTo(position) +
  1962. CesiumMath.EPSILON12
  1963. );
  1964. }
  1965. function executeTranslucentCommandsBackToFront(
  1966. scene,
  1967. executeFunction,
  1968. passState,
  1969. commands,
  1970. invertClassification
  1971. ) {
  1972. const context = scene.context;
  1973. mergeSort(commands, backToFront, scene.camera.positionWC);
  1974. if (defined(invertClassification)) {
  1975. executeFunction(
  1976. invertClassification.unclassifiedCommand,
  1977. scene,
  1978. context,
  1979. passState
  1980. );
  1981. }
  1982. const length = commands.length;
  1983. for (let i = 0; i < length; ++i) {
  1984. executeFunction(commands[i], scene, context, passState);
  1985. }
  1986. }
  1987. function executeTranslucentCommandsFrontToBack(
  1988. scene,
  1989. executeFunction,
  1990. passState,
  1991. commands,
  1992. invertClassification
  1993. ) {
  1994. const context = scene.context;
  1995. mergeSort(commands, frontToBack, scene.camera.positionWC);
  1996. if (defined(invertClassification)) {
  1997. executeFunction(
  1998. invertClassification.unclassifiedCommand,
  1999. scene,
  2000. context,
  2001. passState
  2002. );
  2003. }
  2004. const length = commands.length;
  2005. for (let i = 0; i < length; ++i) {
  2006. executeFunction(commands[i], scene, context, passState);
  2007. }
  2008. }
  2009. function executeVoxelCommands(scene, executeFunction, passState, commands) {
  2010. const context = scene.context;
  2011. mergeSort(commands, backToFront, scene.camera.positionWC);
  2012. const length = commands.length;
  2013. for (let i = 0; i < length; ++i) {
  2014. executeFunction(commands[i], scene, context, passState);
  2015. }
  2016. }
  2017. const scratchPerspectiveFrustum = new PerspectiveFrustum();
  2018. const scratchPerspectiveOffCenterFrustum = new PerspectiveOffCenterFrustum();
  2019. const scratchOrthographicFrustum = new OrthographicFrustum();
  2020. const scratchOrthographicOffCenterFrustum = new OrthographicOffCenterFrustum();
  2021. function executeCommands(scene, passState) {
  2022. const camera = scene.camera;
  2023. const context = scene.context;
  2024. const frameState = scene.frameState;
  2025. const us = context.uniformState;
  2026. us.updateCamera(camera);
  2027. // Create a working frustum from the original camera frustum.
  2028. let frustum;
  2029. if (defined(camera.frustum.fov)) {
  2030. frustum = camera.frustum.clone(scratchPerspectiveFrustum);
  2031. } else if (defined(camera.frustum.infiniteProjectionMatrix)) {
  2032. frustum = camera.frustum.clone(scratchPerspectiveOffCenterFrustum);
  2033. } else if (defined(camera.frustum.width)) {
  2034. frustum = camera.frustum.clone(scratchOrthographicFrustum);
  2035. } else {
  2036. frustum = camera.frustum.clone(scratchOrthographicOffCenterFrustum);
  2037. }
  2038. // Ideally, we would render the sky box and atmosphere last for
  2039. // early-z, but we would have to draw it in each frustum
  2040. frustum.near = camera.frustum.near;
  2041. frustum.far = camera.frustum.far;
  2042. us.updateFrustum(frustum);
  2043. us.updatePass(Pass.ENVIRONMENT);
  2044. const passes = frameState.passes;
  2045. const picking = passes.pick;
  2046. const environmentState = scene._environmentState;
  2047. const view = scene._view;
  2048. const renderTranslucentDepthForPick =
  2049. environmentState.renderTranslucentDepthForPick;
  2050. const useWebVR = environmentState.useWebVR;
  2051. // Do not render environment primitives during a pick pass since they do not generate picking commands.
  2052. if (!picking) {
  2053. const skyBoxCommand = environmentState.skyBoxCommand;
  2054. if (defined(skyBoxCommand)) {
  2055. executeCommand(skyBoxCommand, scene, context, passState);
  2056. }
  2057. if (environmentState.isSkyAtmosphereVisible) {
  2058. executeCommand(
  2059. environmentState.skyAtmosphereCommand,
  2060. scene,
  2061. context,
  2062. passState
  2063. );
  2064. }
  2065. if (environmentState.isSunVisible) {
  2066. environmentState.sunDrawCommand.execute(context, passState);
  2067. if (scene.sunBloom && !useWebVR) {
  2068. let framebuffer;
  2069. if (environmentState.useGlobeDepthFramebuffer) {
  2070. framebuffer = view.globeDepth.framebuffer;
  2071. } else if (environmentState.usePostProcess) {
  2072. framebuffer = view.sceneFramebuffer.framebuffer;
  2073. } else {
  2074. framebuffer = environmentState.originalFramebuffer;
  2075. }
  2076. scene._sunPostProcess.execute(context);
  2077. scene._sunPostProcess.copy(context, framebuffer);
  2078. passState.framebuffer = framebuffer;
  2079. }
  2080. }
  2081. // Moon can be seen through the atmosphere, since the sun is rendered after the atmosphere.
  2082. if (environmentState.isMoonVisible) {
  2083. environmentState.moonCommand.execute(context, passState);
  2084. }
  2085. }
  2086. // Determine how translucent surfaces will be handled.
  2087. let executeTranslucentCommands;
  2088. if (environmentState.useOIT) {
  2089. if (!defined(scene._executeOITFunction)) {
  2090. scene._executeOITFunction = function (
  2091. scene,
  2092. executeFunction,
  2093. passState,
  2094. commands,
  2095. invertClassification
  2096. ) {
  2097. view.globeDepth.prepareColorTextures(context);
  2098. view.oit.executeCommands(
  2099. scene,
  2100. executeFunction,
  2101. passState,
  2102. commands,
  2103. invertClassification
  2104. );
  2105. };
  2106. }
  2107. executeTranslucentCommands = scene._executeOITFunction;
  2108. } else if (passes.render) {
  2109. executeTranslucentCommands = executeTranslucentCommandsBackToFront;
  2110. } else {
  2111. executeTranslucentCommands = executeTranslucentCommandsFrontToBack;
  2112. }
  2113. const frustumCommandsList = view.frustumCommandsList;
  2114. const numFrustums = frustumCommandsList.length;
  2115. const clearGlobeDepth = environmentState.clearGlobeDepth;
  2116. const useDepthPlane = environmentState.useDepthPlane;
  2117. const globeTranslucencyState = scene._globeTranslucencyState;
  2118. const globeTranslucent = globeTranslucencyState.translucent;
  2119. const globeTranslucencyFramebuffer = scene._view.globeTranslucencyFramebuffer;
  2120. const clearDepth = scene._depthClearCommand;
  2121. const clearStencil = scene._stencilClearCommand;
  2122. const clearClassificationStencil = scene._classificationStencilClearCommand;
  2123. const depthPlane = scene._depthPlane;
  2124. const usePostProcessSelected = environmentState.usePostProcessSelected;
  2125. const height2D = camera.position.z;
  2126. // Execute commands in each frustum in back to front order
  2127. let j;
  2128. for (let i = 0; i < numFrustums; ++i) {
  2129. const index = numFrustums - i - 1;
  2130. const frustumCommands = frustumCommandsList[index];
  2131. if (scene.mode === SceneMode.SCENE2D) {
  2132. // To avoid z-fighting in 2D, move the camera to just before the frustum
  2133. // and scale the frustum depth to be in [1.0, nearToFarDistance2D].
  2134. camera.position.z = height2D - frustumCommands.near + 1.0;
  2135. frustum.far = Math.max(1.0, frustumCommands.far - frustumCommands.near);
  2136. frustum.near = 1.0;
  2137. us.update(frameState);
  2138. us.updateFrustum(frustum);
  2139. } else {
  2140. // Avoid tearing artifacts between adjacent frustums in the opaque passes
  2141. frustum.near =
  2142. index !== 0
  2143. ? frustumCommands.near * scene.opaqueFrustumNearOffset
  2144. : frustumCommands.near;
  2145. frustum.far = frustumCommands.far;
  2146. us.updateFrustum(frustum);
  2147. }
  2148. clearDepth.execute(context, passState);
  2149. if (context.stencilBuffer) {
  2150. clearStencil.execute(context, passState);
  2151. }
  2152. us.updatePass(Pass.GLOBE);
  2153. let commands = frustumCommands.commands[Pass.GLOBE];
  2154. let length = frustumCommands.indices[Pass.GLOBE];
  2155. if (globeTranslucent) {
  2156. globeTranslucencyState.executeGlobeCommands(
  2157. frustumCommands,
  2158. executeCommand,
  2159. globeTranslucencyFramebuffer,
  2160. scene,
  2161. passState
  2162. );
  2163. } else {
  2164. for (j = 0; j < length; ++j) {
  2165. executeCommand(commands[j], scene, context, passState);
  2166. }
  2167. }
  2168. const globeDepth = view.globeDepth;
  2169. if (defined(globeDepth) && environmentState.useGlobeDepthFramebuffer) {
  2170. globeDepth.executeCopyDepth(context, passState);
  2171. }
  2172. // Draw terrain classification
  2173. if (!environmentState.renderTranslucentDepthForPick) {
  2174. us.updatePass(Pass.TERRAIN_CLASSIFICATION);
  2175. commands = frustumCommands.commands[Pass.TERRAIN_CLASSIFICATION];
  2176. length = frustumCommands.indices[Pass.TERRAIN_CLASSIFICATION];
  2177. if (globeTranslucent) {
  2178. globeTranslucencyState.executeGlobeClassificationCommands(
  2179. frustumCommands,
  2180. executeCommand,
  2181. globeTranslucencyFramebuffer,
  2182. scene,
  2183. passState
  2184. );
  2185. } else {
  2186. for (j = 0; j < length; ++j) {
  2187. executeCommand(commands[j], scene, context, passState);
  2188. }
  2189. }
  2190. }
  2191. if (clearGlobeDepth) {
  2192. clearDepth.execute(context, passState);
  2193. if (useDepthPlane) {
  2194. depthPlane.execute(context, passState);
  2195. }
  2196. }
  2197. if (
  2198. !environmentState.useInvertClassification ||
  2199. picking ||
  2200. environmentState.renderTranslucentDepthForPick
  2201. ) {
  2202. // Common/fastest path. Draw 3D Tiles and classification normally.
  2203. // Draw 3D Tiles
  2204. us.updatePass(Pass.CESIUM_3D_TILE);
  2205. commands = frustumCommands.commands[Pass.CESIUM_3D_TILE];
  2206. length = frustumCommands.indices[Pass.CESIUM_3D_TILE];
  2207. for (j = 0; j < length; ++j) {
  2208. executeCommand(commands[j], scene, context, passState);
  2209. }
  2210. if (length > 0) {
  2211. if (defined(globeDepth) && environmentState.useGlobeDepthFramebuffer) {
  2212. // When clearGlobeDepth is true, executeUpdateDepth needs
  2213. // a globe depth texture with resolved stencil bits.
  2214. globeDepth.prepareColorTextures(context, clearGlobeDepth);
  2215. globeDepth.executeUpdateDepth(
  2216. context,
  2217. passState,
  2218. clearGlobeDepth,
  2219. globeDepth.depthStencilTexture
  2220. );
  2221. }
  2222. // Draw classifications. Modifies 3D Tiles color.
  2223. if (!environmentState.renderTranslucentDepthForPick) {
  2224. us.updatePass(Pass.CESIUM_3D_TILE_CLASSIFICATION);
  2225. commands =
  2226. frustumCommands.commands[Pass.CESIUM_3D_TILE_CLASSIFICATION];
  2227. length = frustumCommands.indices[Pass.CESIUM_3D_TILE_CLASSIFICATION];
  2228. for (j = 0; j < length; ++j) {
  2229. executeCommand(commands[j], scene, context, passState);
  2230. }
  2231. }
  2232. }
  2233. } else {
  2234. // When the invert classification color is opaque:
  2235. // Main FBO (FBO1): Main_Color + Main_DepthStencil
  2236. // Invert classification FBO (FBO2) : Invert_Color + Main_DepthStencil
  2237. //
  2238. // 1. Clear FBO2 color to vec4(0.0) for each frustum
  2239. // 2. Draw 3D Tiles to FBO2
  2240. // 3. Draw classification to FBO2
  2241. // 4. Fullscreen pass to FBO1, draw Invert_Color when:
  2242. // * Main_DepthStencil has the stencil bit set > 0 (classified)
  2243. // 5. Fullscreen pass to FBO1, draw Invert_Color * czm_invertClassificationColor when:
  2244. // * Main_DepthStencil has stencil bit set to 0 (unclassified) and
  2245. // * Invert_Color !== vec4(0.0)
  2246. //
  2247. // When the invert classification color is translucent:
  2248. // Main FBO (FBO1): Main_Color + Main_DepthStencil
  2249. // Invert classification FBO (FBO2): Invert_Color + Invert_DepthStencil
  2250. // IsClassified FBO (FBO3): IsClassified_Color + Invert_DepthStencil
  2251. //
  2252. // 1. Clear FBO2 and FBO3 color to vec4(0.0), stencil to 0, and depth to 1.0
  2253. // 2. Draw 3D Tiles to FBO2
  2254. // 3. Draw classification to FBO2
  2255. // 4. Fullscreen pass to FBO3, draw any color when
  2256. // * Invert_DepthStencil has the stencil bit set > 0 (classified)
  2257. // 5. Fullscreen pass to FBO1, draw Invert_Color when:
  2258. // * Invert_Color !== vec4(0.0) and
  2259. // * IsClassified_Color !== vec4(0.0)
  2260. // 6. Fullscreen pass to FBO1, draw Invert_Color * czm_invertClassificationColor when:
  2261. // * Invert_Color !== vec4(0.0) and
  2262. // * IsClassified_Color === vec4(0.0)
  2263. //
  2264. // NOTE: Step six when translucent invert color occurs after the TRANSLUCENT pass
  2265. //
  2266. scene._invertClassification.clear(context, passState);
  2267. const opaqueClassificationFramebuffer = passState.framebuffer;
  2268. passState.framebuffer = scene._invertClassification._fbo.framebuffer;
  2269. // Draw normally
  2270. us.updatePass(Pass.CESIUM_3D_TILE);
  2271. commands = frustumCommands.commands[Pass.CESIUM_3D_TILE];
  2272. length = frustumCommands.indices[Pass.CESIUM_3D_TILE];
  2273. for (j = 0; j < length; ++j) {
  2274. executeCommand(commands[j], scene, context, passState);
  2275. }
  2276. if (defined(globeDepth) && environmentState.useGlobeDepthFramebuffer) {
  2277. scene._invertClassification.prepareTextures(context);
  2278. globeDepth.executeUpdateDepth(
  2279. context,
  2280. passState,
  2281. clearGlobeDepth,
  2282. scene._invertClassification._fbo.getDepthStencilTexture()
  2283. );
  2284. }
  2285. // Set stencil
  2286. us.updatePass(Pass.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW);
  2287. commands =
  2288. frustumCommands.commands[
  2289. Pass.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW
  2290. ];
  2291. length =
  2292. frustumCommands.indices[Pass.CESIUM_3D_TILE_CLASSIFICATION_IGNORE_SHOW];
  2293. for (j = 0; j < length; ++j) {
  2294. executeCommand(commands[j], scene, context, passState);
  2295. }
  2296. passState.framebuffer = opaqueClassificationFramebuffer;
  2297. // Fullscreen pass to copy classified fragments
  2298. scene._invertClassification.executeClassified(context, passState);
  2299. if (frameState.invertClassificationColor.alpha === 1.0) {
  2300. // Fullscreen pass to copy unclassified fragments when alpha == 1.0
  2301. scene._invertClassification.executeUnclassified(context, passState);
  2302. }
  2303. // Clear stencil set by the classification for the next classification pass
  2304. if (length > 0 && context.stencilBuffer) {
  2305. clearClassificationStencil.execute(context, passState);
  2306. }
  2307. // Draw style over classification.
  2308. us.updatePass(Pass.CESIUM_3D_TILE_CLASSIFICATION);
  2309. commands = frustumCommands.commands[Pass.CESIUM_3D_TILE_CLASSIFICATION];
  2310. length = frustumCommands.indices[Pass.CESIUM_3D_TILE_CLASSIFICATION];
  2311. for (j = 0; j < length; ++j) {
  2312. executeCommand(commands[j], scene, context, passState);
  2313. }
  2314. }
  2315. if (length > 0 && context.stencilBuffer) {
  2316. clearStencil.execute(context, passState);
  2317. }
  2318. us.updatePass(Pass.VOXELS);
  2319. commands = frustumCommands.commands[Pass.VOXELS];
  2320. length = frustumCommands.indices[Pass.VOXELS];
  2321. commands.length = length;
  2322. executeVoxelCommands(scene, executeCommand, passState, commands);
  2323. us.updatePass(Pass.OPAQUE);
  2324. commands = frustumCommands.commands[Pass.OPAQUE];
  2325. length = frustumCommands.indices[Pass.OPAQUE];
  2326. for (j = 0; j < length; ++j) {
  2327. executeCommand(commands[j], scene, context, passState);
  2328. }
  2329. if (index !== 0 && scene.mode !== SceneMode.SCENE2D) {
  2330. // Do not overlap frustums in the translucent pass to avoid blending artifacts
  2331. frustum.near = frustumCommands.near;
  2332. us.updateFrustum(frustum);
  2333. }
  2334. let invertClassification;
  2335. if (
  2336. !picking &&
  2337. environmentState.useInvertClassification &&
  2338. frameState.invertClassificationColor.alpha < 1.0
  2339. ) {
  2340. // Fullscreen pass to copy unclassified fragments when alpha < 1.0.
  2341. // Not executed when undefined.
  2342. invertClassification = scene._invertClassification;
  2343. }
  2344. us.updatePass(Pass.TRANSLUCENT);
  2345. commands = frustumCommands.commands[Pass.TRANSLUCENT];
  2346. commands.length = frustumCommands.indices[Pass.TRANSLUCENT];
  2347. executeTranslucentCommands(
  2348. scene,
  2349. executeCommand,
  2350. passState,
  2351. commands,
  2352. invertClassification
  2353. );
  2354. // Classification for translucent 3D Tiles
  2355. const has3DTilesClassificationCommands =
  2356. frustumCommands.indices[Pass.CESIUM_3D_TILE_CLASSIFICATION] > 0;
  2357. if (
  2358. has3DTilesClassificationCommands &&
  2359. view.translucentTileClassification.isSupported()
  2360. ) {
  2361. view.translucentTileClassification.executeTranslucentCommands(
  2362. scene,
  2363. executeCommand,
  2364. passState,
  2365. commands,
  2366. globeDepth.depthStencilTexture
  2367. );
  2368. view.translucentTileClassification.executeClassificationCommands(
  2369. scene,
  2370. executeCommand,
  2371. passState,
  2372. frustumCommands
  2373. );
  2374. }
  2375. if (
  2376. context.depthTexture &&
  2377. scene.useDepthPicking &&
  2378. (environmentState.useGlobeDepthFramebuffer ||
  2379. renderTranslucentDepthForPick)
  2380. ) {
  2381. // PERFORMANCE_IDEA: Use MRT to avoid the extra copy.
  2382. const depthStencilTexture = globeDepth.depthStencilTexture;
  2383. const pickDepth = scene._picking.getPickDepth(scene, index);
  2384. pickDepth.update(context, depthStencilTexture);
  2385. pickDepth.executeCopyDepth(context, passState);
  2386. }
  2387. if (picking || !usePostProcessSelected) {
  2388. continue;
  2389. }
  2390. const originalFramebuffer = passState.framebuffer;
  2391. passState.framebuffer = view.sceneFramebuffer.getIdFramebuffer();
  2392. // reset frustum
  2393. frustum.near =
  2394. index !== 0
  2395. ? frustumCommands.near * scene.opaqueFrustumNearOffset
  2396. : frustumCommands.near;
  2397. frustum.far = frustumCommands.far;
  2398. us.updateFrustum(frustum);
  2399. us.updatePass(Pass.GLOBE);
  2400. commands = frustumCommands.commands[Pass.GLOBE];
  2401. length = frustumCommands.indices[Pass.GLOBE];
  2402. if (globeTranslucent) {
  2403. globeTranslucencyState.executeGlobeCommands(
  2404. frustumCommands,
  2405. executeIdCommand,
  2406. globeTranslucencyFramebuffer,
  2407. scene,
  2408. passState
  2409. );
  2410. } else {
  2411. for (j = 0; j < length; ++j) {
  2412. executeIdCommand(commands[j], scene, context, passState);
  2413. }
  2414. }
  2415. if (clearGlobeDepth) {
  2416. clearDepth.framebuffer = passState.framebuffer;
  2417. clearDepth.execute(context, passState);
  2418. clearDepth.framebuffer = undefined;
  2419. }
  2420. if (clearGlobeDepth && useDepthPlane) {
  2421. depthPlane.execute(context, passState);
  2422. }
  2423. us.updatePass(Pass.CESIUM_3D_TILE);
  2424. commands = frustumCommands.commands[Pass.CESIUM_3D_TILE];
  2425. length = frustumCommands.indices[Pass.CESIUM_3D_TILE];
  2426. for (j = 0; j < length; ++j) {
  2427. executeIdCommand(commands[j], scene, context, passState);
  2428. }
  2429. us.updatePass(Pass.OPAQUE);
  2430. commands = frustumCommands.commands[Pass.OPAQUE];
  2431. length = frustumCommands.indices[Pass.OPAQUE];
  2432. for (j = 0; j < length; ++j) {
  2433. executeIdCommand(commands[j], scene, context, passState);
  2434. }
  2435. us.updatePass(Pass.TRANSLUCENT);
  2436. commands = frustumCommands.commands[Pass.TRANSLUCENT];
  2437. length = frustumCommands.indices[Pass.TRANSLUCENT];
  2438. for (j = 0; j < length; ++j) {
  2439. executeIdCommand(commands[j], scene, context, passState);
  2440. }
  2441. passState.framebuffer = originalFramebuffer;
  2442. }
  2443. }
  2444. function executeComputeCommands(scene) {
  2445. const us = scene.context.uniformState;
  2446. us.updatePass(Pass.COMPUTE);
  2447. const sunComputeCommand = scene._environmentState.sunComputeCommand;
  2448. if (defined(sunComputeCommand)) {
  2449. sunComputeCommand.execute(scene._computeEngine);
  2450. }
  2451. const commandList = scene._computeCommandList;
  2452. const length = commandList.length;
  2453. for (let i = 0; i < length; ++i) {
  2454. commandList[i].execute(scene._computeEngine);
  2455. }
  2456. }
  2457. function executeOverlayCommands(scene, passState) {
  2458. const us = scene.context.uniformState;
  2459. us.updatePass(Pass.OVERLAY);
  2460. const context = scene.context;
  2461. const commandList = scene._overlayCommandList;
  2462. const length = commandList.length;
  2463. for (let i = 0; i < length; ++i) {
  2464. commandList[i].execute(context, passState);
  2465. }
  2466. }
  2467. function insertShadowCastCommands(scene, commandList, shadowMap) {
  2468. const shadowVolume = shadowMap.shadowMapCullingVolume;
  2469. const isPointLight = shadowMap.isPointLight;
  2470. const passes = shadowMap.passes;
  2471. const numberOfPasses = passes.length;
  2472. const length = commandList.length;
  2473. for (let i = 0; i < length; ++i) {
  2474. const command = commandList[i];
  2475. scene.updateDerivedCommands(command);
  2476. if (
  2477. command.castShadows &&
  2478. (command.pass === Pass.GLOBE ||
  2479. command.pass === Pass.CESIUM_3D_TILE ||
  2480. command.pass === Pass.OPAQUE ||
  2481. command.pass === Pass.TRANSLUCENT)
  2482. ) {
  2483. if (scene.isVisible(command, shadowVolume)) {
  2484. if (isPointLight) {
  2485. for (let k = 0; k < numberOfPasses; ++k) {
  2486. passes[k].commandList.push(command);
  2487. }
  2488. } else if (numberOfPasses === 1) {
  2489. passes[0].commandList.push(command);
  2490. } else {
  2491. let wasVisible = false;
  2492. // Loop over cascades from largest to smallest
  2493. for (let j = numberOfPasses - 1; j >= 0; --j) {
  2494. const cascadeVolume = passes[j].cullingVolume;
  2495. if (scene.isVisible(command, cascadeVolume)) {
  2496. passes[j].commandList.push(command);
  2497. wasVisible = true;
  2498. } else if (wasVisible) {
  2499. // If it was visible in the previous cascade but now isn't
  2500. // then there is no need to check any more cascades
  2501. break;
  2502. }
  2503. }
  2504. }
  2505. }
  2506. }
  2507. }
  2508. }
  2509. function executeShadowMapCastCommands(scene) {
  2510. const frameState = scene.frameState;
  2511. const shadowMaps = frameState.shadowState.shadowMaps;
  2512. const shadowMapLength = shadowMaps.length;
  2513. if (!frameState.shadowState.shadowsEnabled) {
  2514. return;
  2515. }
  2516. const context = scene.context;
  2517. const uniformState = context.uniformState;
  2518. for (let i = 0; i < shadowMapLength; ++i) {
  2519. const shadowMap = shadowMaps[i];
  2520. if (shadowMap.outOfView) {
  2521. continue;
  2522. }
  2523. // Reset the command lists
  2524. const passes = shadowMap.passes;
  2525. const numberOfPasses = passes.length;
  2526. for (let j = 0; j < numberOfPasses; ++j) {
  2527. passes[j].commandList.length = 0;
  2528. }
  2529. // Insert the primitive/model commands into the command lists
  2530. const sceneCommands = scene.frameState.commandList;
  2531. insertShadowCastCommands(scene, sceneCommands, shadowMap);
  2532. for (let j = 0; j < numberOfPasses; ++j) {
  2533. const pass = shadowMap.passes[j];
  2534. uniformState.updateCamera(pass.camera);
  2535. shadowMap.updatePass(context, j);
  2536. const numberOfCommands = pass.commandList.length;
  2537. for (let k = 0; k < numberOfCommands; ++k) {
  2538. const command = pass.commandList[k];
  2539. // Set the correct pass before rendering into the shadow map because some shaders
  2540. // conditionally render based on whether the pass is translucent or opaque.
  2541. uniformState.updatePass(command.pass);
  2542. executeCommand(
  2543. command.derivedCommands.shadows.castCommands[i],
  2544. scene,
  2545. context,
  2546. pass.passState
  2547. );
  2548. }
  2549. }
  2550. }
  2551. }
  2552. const scratchEyeTranslation = new Cartesian3();
  2553. /**
  2554. * @private
  2555. */
  2556. Scene.prototype.updateAndExecuteCommands = function (
  2557. passState,
  2558. backgroundColor
  2559. ) {
  2560. const frameState = this._frameState;
  2561. const mode = frameState.mode;
  2562. const useWebVR = this._environmentState.useWebVR;
  2563. if (useWebVR) {
  2564. executeWebVRCommands(this, passState, backgroundColor);
  2565. } else if (
  2566. mode !== SceneMode.SCENE2D ||
  2567. this._mapMode2D === MapMode2D.ROTATE
  2568. ) {
  2569. executeCommandsInViewport(true, this, passState, backgroundColor);
  2570. } else {
  2571. updateAndClearFramebuffers(this, passState, backgroundColor);
  2572. execute2DViewportCommands(this, passState);
  2573. }
  2574. };
  2575. function executeWebVRCommands(scene, passState, backgroundColor) {
  2576. const view = scene._view;
  2577. const camera = view.camera;
  2578. const environmentState = scene._environmentState;
  2579. const renderTranslucentDepthForPick =
  2580. environmentState.renderTranslucentDepthForPick;
  2581. updateAndClearFramebuffers(scene, passState, backgroundColor);
  2582. updateAndRenderPrimitives(scene);
  2583. view.createPotentiallyVisibleSet(scene);
  2584. executeComputeCommands(scene);
  2585. if (!renderTranslucentDepthForPick) {
  2586. executeShadowMapCastCommands(scene);
  2587. }
  2588. // Based on Calculating Stereo pairs by Paul Bourke
  2589. // http://paulbourke.net/stereographics/stereorender/
  2590. const viewport = passState.viewport;
  2591. viewport.x = 0;
  2592. viewport.y = 0;
  2593. viewport.width = viewport.width * 0.5;
  2594. const savedCamera = Camera.clone(camera, scene._cameraVR);
  2595. savedCamera.frustum = camera.frustum;
  2596. const near = camera.frustum.near;
  2597. const fo = near * defaultValue(scene.focalLength, 5.0);
  2598. const eyeSeparation = defaultValue(scene.eyeSeparation, fo / 30.0);
  2599. const eyeTranslation = Cartesian3.multiplyByScalar(
  2600. savedCamera.right,
  2601. eyeSeparation * 0.5,
  2602. scratchEyeTranslation
  2603. );
  2604. camera.frustum.aspectRatio = viewport.width / viewport.height;
  2605. const offset = (0.5 * eyeSeparation * near) / fo;
  2606. Cartesian3.add(savedCamera.position, eyeTranslation, camera.position);
  2607. camera.frustum.xOffset = offset;
  2608. executeCommands(scene, passState);
  2609. viewport.x = viewport.width;
  2610. Cartesian3.subtract(savedCamera.position, eyeTranslation, camera.position);
  2611. camera.frustum.xOffset = -offset;
  2612. executeCommands(scene, passState);
  2613. Camera.clone(savedCamera, camera);
  2614. }
  2615. const scratch2DViewportCartographic = new Cartographic(
  2616. Math.PI,
  2617. CesiumMath.PI_OVER_TWO
  2618. );
  2619. const scratch2DViewportMaxCoord = new Cartesian3();
  2620. const scratch2DViewportSavedPosition = new Cartesian3();
  2621. const scratch2DViewportTransform = new Matrix4();
  2622. const scratch2DViewportCameraTransform = new Matrix4();
  2623. const scratch2DViewportEyePoint = new Cartesian3();
  2624. const scratch2DViewportWindowCoords = new Cartesian3();
  2625. const scratch2DViewport = new BoundingRectangle();
  2626. function execute2DViewportCommands(scene, passState) {
  2627. const context = scene.context;
  2628. const frameState = scene.frameState;
  2629. const camera = scene.camera;
  2630. const originalViewport = passState.viewport;
  2631. const viewport = BoundingRectangle.clone(originalViewport, scratch2DViewport);
  2632. passState.viewport = viewport;
  2633. const maxCartographic = scratch2DViewportCartographic;
  2634. const maxCoord = scratch2DViewportMaxCoord;
  2635. const projection = scene.mapProjection;
  2636. projection.project(maxCartographic, maxCoord);
  2637. const position = Cartesian3.clone(
  2638. camera.position,
  2639. scratch2DViewportSavedPosition
  2640. );
  2641. const transform = Matrix4.clone(
  2642. camera.transform,
  2643. scratch2DViewportCameraTransform
  2644. );
  2645. const frustum = camera.frustum.clone();
  2646. camera._setTransform(Matrix4.IDENTITY);
  2647. const viewportTransformation = Matrix4.computeViewportTransformation(
  2648. viewport,
  2649. 0.0,
  2650. 1.0,
  2651. scratch2DViewportTransform
  2652. );
  2653. const projectionMatrix = camera.frustum.projectionMatrix;
  2654. const x = camera.positionWC.y;
  2655. const eyePoint = Cartesian3.fromElements(
  2656. CesiumMath.sign(x) * maxCoord.x - x,
  2657. 0.0,
  2658. -camera.positionWC.x,
  2659. scratch2DViewportEyePoint
  2660. );
  2661. const windowCoordinates = Transforms.pointToGLWindowCoordinates(
  2662. projectionMatrix,
  2663. viewportTransformation,
  2664. eyePoint,
  2665. scratch2DViewportWindowCoords
  2666. );
  2667. windowCoordinates.x = Math.floor(windowCoordinates.x);
  2668. const viewportX = viewport.x;
  2669. const viewportWidth = viewport.width;
  2670. if (
  2671. x === 0.0 ||
  2672. windowCoordinates.x <= viewportX ||
  2673. windowCoordinates.x >= viewportX + viewportWidth
  2674. ) {
  2675. executeCommandsInViewport(true, scene, passState);
  2676. } else if (
  2677. Math.abs(viewportX + viewportWidth * 0.5 - windowCoordinates.x) < 1.0
  2678. ) {
  2679. viewport.width = windowCoordinates.x - viewport.x;
  2680. camera.position.x *= CesiumMath.sign(camera.position.x);
  2681. camera.frustum.right = 0.0;
  2682. frameState.cullingVolume = camera.frustum.computeCullingVolume(
  2683. camera.positionWC,
  2684. camera.directionWC,
  2685. camera.upWC
  2686. );
  2687. context.uniformState.update(frameState);
  2688. executeCommandsInViewport(true, scene, passState);
  2689. viewport.x = windowCoordinates.x;
  2690. camera.position.x = -camera.position.x;
  2691. camera.frustum.right = -camera.frustum.left;
  2692. camera.frustum.left = 0.0;
  2693. frameState.cullingVolume = camera.frustum.computeCullingVolume(
  2694. camera.positionWC,
  2695. camera.directionWC,
  2696. camera.upWC
  2697. );
  2698. context.uniformState.update(frameState);
  2699. executeCommandsInViewport(false, scene, passState);
  2700. } else if (windowCoordinates.x > viewportX + viewportWidth * 0.5) {
  2701. viewport.width = windowCoordinates.x - viewportX;
  2702. const right = camera.frustum.right;
  2703. camera.frustum.right = maxCoord.x - x;
  2704. frameState.cullingVolume = camera.frustum.computeCullingVolume(
  2705. camera.positionWC,
  2706. camera.directionWC,
  2707. camera.upWC
  2708. );
  2709. context.uniformState.update(frameState);
  2710. executeCommandsInViewport(true, scene, passState);
  2711. viewport.x = windowCoordinates.x;
  2712. viewport.width = viewportX + viewportWidth - windowCoordinates.x;
  2713. camera.position.x = -camera.position.x;
  2714. camera.frustum.left = -camera.frustum.right;
  2715. camera.frustum.right = right - camera.frustum.right * 2.0;
  2716. frameState.cullingVolume = camera.frustum.computeCullingVolume(
  2717. camera.positionWC,
  2718. camera.directionWC,
  2719. camera.upWC
  2720. );
  2721. context.uniformState.update(frameState);
  2722. executeCommandsInViewport(false, scene, passState);
  2723. } else {
  2724. viewport.x = windowCoordinates.x;
  2725. viewport.width = viewportX + viewportWidth - windowCoordinates.x;
  2726. const left = camera.frustum.left;
  2727. camera.frustum.left = -maxCoord.x - x;
  2728. frameState.cullingVolume = camera.frustum.computeCullingVolume(
  2729. camera.positionWC,
  2730. camera.directionWC,
  2731. camera.upWC
  2732. );
  2733. context.uniformState.update(frameState);
  2734. executeCommandsInViewport(true, scene, passState);
  2735. viewport.x = viewportX;
  2736. viewport.width = windowCoordinates.x - viewportX;
  2737. camera.position.x = -camera.position.x;
  2738. camera.frustum.right = -camera.frustum.left;
  2739. camera.frustum.left = left - camera.frustum.left * 2.0;
  2740. frameState.cullingVolume = camera.frustum.computeCullingVolume(
  2741. camera.positionWC,
  2742. camera.directionWC,
  2743. camera.upWC
  2744. );
  2745. context.uniformState.update(frameState);
  2746. executeCommandsInViewport(false, scene, passState);
  2747. }
  2748. camera._setTransform(transform);
  2749. Cartesian3.clone(position, camera.position);
  2750. camera.frustum = frustum.clone();
  2751. passState.viewport = originalViewport;
  2752. }
  2753. function executeCommandsInViewport(
  2754. firstViewport,
  2755. scene,
  2756. passState,
  2757. backgroundColor
  2758. ) {
  2759. const environmentState = scene._environmentState;
  2760. const view = scene._view;
  2761. const renderTranslucentDepthForPick =
  2762. environmentState.renderTranslucentDepthForPick;
  2763. if (!firstViewport) {
  2764. scene.frameState.commandList.length = 0;
  2765. }
  2766. updateAndRenderPrimitives(scene);
  2767. view.createPotentiallyVisibleSet(scene);
  2768. if (firstViewport) {
  2769. if (defined(backgroundColor)) {
  2770. updateAndClearFramebuffers(scene, passState, backgroundColor);
  2771. }
  2772. executeComputeCommands(scene);
  2773. if (!renderTranslucentDepthForPick) {
  2774. executeShadowMapCastCommands(scene);
  2775. }
  2776. }
  2777. executeCommands(scene, passState);
  2778. }
  2779. const scratchCullingVolume = new CullingVolume();
  2780. /**
  2781. * @private
  2782. */
  2783. Scene.prototype.updateEnvironment = function () {
  2784. const frameState = this._frameState;
  2785. const view = this._view;
  2786. // Update celestial and terrestrial environment effects.
  2787. const environmentState = this._environmentState;
  2788. const renderPass = frameState.passes.render;
  2789. const offscreenPass = frameState.passes.offscreen;
  2790. const skyAtmosphere = this.skyAtmosphere;
  2791. const globe = this.globe;
  2792. const globeTranslucencyState = this._globeTranslucencyState;
  2793. if (
  2794. !renderPass ||
  2795. (this._mode !== SceneMode.SCENE2D &&
  2796. view.camera.frustum instanceof OrthographicFrustum) ||
  2797. !globeTranslucencyState.environmentVisible
  2798. ) {
  2799. environmentState.skyAtmosphereCommand = undefined;
  2800. environmentState.skyBoxCommand = undefined;
  2801. environmentState.sunDrawCommand = undefined;
  2802. environmentState.sunComputeCommand = undefined;
  2803. environmentState.moonCommand = undefined;
  2804. } else {
  2805. if (defined(skyAtmosphere)) {
  2806. if (defined(globe)) {
  2807. skyAtmosphere.setDynamicAtmosphereColor(
  2808. globe.enableLighting && globe.dynamicAtmosphereLighting,
  2809. globe.dynamicAtmosphereLightingFromSun
  2810. );
  2811. environmentState.isReadyForAtmosphere =
  2812. environmentState.isReadyForAtmosphere ||
  2813. globe._surface._tilesToRender.length > 0;
  2814. }
  2815. environmentState.skyAtmosphereCommand = skyAtmosphere.update(
  2816. frameState,
  2817. globe
  2818. );
  2819. if (defined(environmentState.skyAtmosphereCommand)) {
  2820. this.updateDerivedCommands(environmentState.skyAtmosphereCommand);
  2821. }
  2822. } else {
  2823. environmentState.skyAtmosphereCommand = undefined;
  2824. }
  2825. environmentState.skyBoxCommand = defined(this.skyBox)
  2826. ? this.skyBox.update(frameState, this._hdr)
  2827. : undefined;
  2828. const sunCommands = defined(this.sun)
  2829. ? this.sun.update(frameState, view.passState, this._hdr)
  2830. : undefined;
  2831. environmentState.sunDrawCommand = defined(sunCommands)
  2832. ? sunCommands.drawCommand
  2833. : undefined;
  2834. environmentState.sunComputeCommand = defined(sunCommands)
  2835. ? sunCommands.computeCommand
  2836. : undefined;
  2837. environmentState.moonCommand = defined(this.moon)
  2838. ? this.moon.update(frameState)
  2839. : undefined;
  2840. }
  2841. const clearGlobeDepth = (environmentState.clearGlobeDepth =
  2842. defined(globe) &&
  2843. globe.show &&
  2844. (!globe.depthTestAgainstTerrain || this.mode === SceneMode.SCENE2D));
  2845. const useDepthPlane = (environmentState.useDepthPlane =
  2846. clearGlobeDepth &&
  2847. this.mode === SceneMode.SCENE3D &&
  2848. globeTranslucencyState.useDepthPlane);
  2849. if (useDepthPlane) {
  2850. // Update the depth plane that is rendered in 3D when the primitives are
  2851. // not depth tested against terrain so primitives on the backface
  2852. // of the globe are not picked.
  2853. this._depthPlane.update(frameState);
  2854. }
  2855. environmentState.renderTranslucentDepthForPick = false;
  2856. environmentState.useWebVR =
  2857. this._useWebVR && this.mode !== SceneMode.SCENE2D && !offscreenPass;
  2858. const occluder =
  2859. frameState.mode === SceneMode.SCENE3D &&
  2860. !globeTranslucencyState.sunVisibleThroughGlobe
  2861. ? frameState.occluder
  2862. : undefined;
  2863. let cullingVolume = frameState.cullingVolume;
  2864. // get user culling volume minus the far plane.
  2865. const planes = scratchCullingVolume.planes;
  2866. for (let k = 0; k < 5; ++k) {
  2867. planes[k] = cullingVolume.planes[k];
  2868. }
  2869. cullingVolume = scratchCullingVolume;
  2870. // Determine visibility of celestial and terrestrial environment effects.
  2871. environmentState.isSkyAtmosphereVisible =
  2872. defined(environmentState.skyAtmosphereCommand) &&
  2873. environmentState.isReadyForAtmosphere;
  2874. environmentState.isSunVisible = this.isVisible(
  2875. environmentState.sunDrawCommand,
  2876. cullingVolume,
  2877. occluder
  2878. );
  2879. environmentState.isMoonVisible = this.isVisible(
  2880. environmentState.moonCommand,
  2881. cullingVolume,
  2882. occluder
  2883. );
  2884. const envMaps = this.specularEnvironmentMaps;
  2885. let envMapAtlas = this._specularEnvironmentMapAtlas;
  2886. if (
  2887. defined(envMaps) &&
  2888. (!defined(envMapAtlas) || envMapAtlas.url !== envMaps)
  2889. ) {
  2890. envMapAtlas = envMapAtlas && envMapAtlas.destroy();
  2891. this._specularEnvironmentMapAtlas = new OctahedralProjectedCubeMap(envMaps);
  2892. } else if (!defined(envMaps) && defined(envMapAtlas)) {
  2893. envMapAtlas.destroy();
  2894. this._specularEnvironmentMapAtlas = undefined;
  2895. }
  2896. if (defined(this._specularEnvironmentMapAtlas)) {
  2897. this._specularEnvironmentMapAtlas.update(frameState);
  2898. }
  2899. };
  2900. function updateDebugFrustumPlanes(scene) {
  2901. const frameState = scene._frameState;
  2902. if (scene.debugShowFrustumPlanes !== scene._debugShowFrustumPlanes) {
  2903. if (scene.debugShowFrustumPlanes) {
  2904. scene._debugFrustumPlanes = new DebugCameraPrimitive({
  2905. camera: scene.camera,
  2906. updateOnChange: false,
  2907. frustumSplits: frameState.frustumSplits,
  2908. });
  2909. } else {
  2910. scene._debugFrustumPlanes =
  2911. scene._debugFrustumPlanes && scene._debugFrustumPlanes.destroy();
  2912. }
  2913. scene._debugShowFrustumPlanes = scene.debugShowFrustumPlanes;
  2914. }
  2915. if (defined(scene._debugFrustumPlanes)) {
  2916. scene._debugFrustumPlanes.update(frameState);
  2917. }
  2918. }
  2919. function updateShadowMaps(scene) {
  2920. const frameState = scene._frameState;
  2921. const shadowMaps = frameState.shadowMaps;
  2922. const length = shadowMaps.length;
  2923. const shadowsEnabled =
  2924. length > 0 && !frameState.passes.pick && scene.mode === SceneMode.SCENE3D;
  2925. if (shadowsEnabled !== frameState.shadowState.shadowsEnabled) {
  2926. // Update derived commands when shadowsEnabled changes
  2927. ++frameState.shadowState.lastDirtyTime;
  2928. frameState.shadowState.shadowsEnabled = shadowsEnabled;
  2929. }
  2930. frameState.shadowState.lightShadowsEnabled = false;
  2931. if (!shadowsEnabled) {
  2932. return;
  2933. }
  2934. // Check if the shadow maps are different than the shadow maps last frame.
  2935. // If so, the derived commands need to be updated.
  2936. for (let j = 0; j < length; ++j) {
  2937. if (shadowMaps[j] !== frameState.shadowState.shadowMaps[j]) {
  2938. ++frameState.shadowState.lastDirtyTime;
  2939. break;
  2940. }
  2941. }
  2942. frameState.shadowState.shadowMaps.length = 0;
  2943. frameState.shadowState.lightShadowMaps.length = 0;
  2944. for (let i = 0; i < length; ++i) {
  2945. const shadowMap = shadowMaps[i];
  2946. shadowMap.update(frameState);
  2947. frameState.shadowState.shadowMaps.push(shadowMap);
  2948. if (shadowMap.fromLightSource) {
  2949. frameState.shadowState.lightShadowMaps.push(shadowMap);
  2950. frameState.shadowState.lightShadowsEnabled = true;
  2951. }
  2952. if (shadowMap.dirty) {
  2953. ++frameState.shadowState.lastDirtyTime;
  2954. shadowMap.dirty = false;
  2955. }
  2956. }
  2957. }
  2958. function updateAndRenderPrimitives(scene) {
  2959. const frameState = scene._frameState;
  2960. scene._groundPrimitives.update(frameState);
  2961. scene._primitives.update(frameState);
  2962. updateDebugFrustumPlanes(scene);
  2963. updateShadowMaps(scene);
  2964. if (scene._globe) {
  2965. scene._globe.render(frameState);
  2966. }
  2967. }
  2968. function updateAndClearFramebuffers(scene, passState, clearColor) {
  2969. const context = scene._context;
  2970. const frameState = scene._frameState;
  2971. const environmentState = scene._environmentState;
  2972. const view = scene._view;
  2973. const passes = scene._frameState.passes;
  2974. const picking = passes.pick;
  2975. if (defined(view.globeDepth)) {
  2976. view.globeDepth.picking = picking;
  2977. }
  2978. const useWebVR = environmentState.useWebVR;
  2979. // Preserve the reference to the original framebuffer.
  2980. environmentState.originalFramebuffer = passState.framebuffer;
  2981. // Manage sun bloom post-processing effect.
  2982. if (defined(scene.sun) && scene.sunBloom !== scene._sunBloom) {
  2983. if (scene.sunBloom && !useWebVR) {
  2984. scene._sunPostProcess = new SunPostProcess();
  2985. } else if (defined(scene._sunPostProcess)) {
  2986. scene._sunPostProcess = scene._sunPostProcess.destroy();
  2987. }
  2988. scene._sunBloom = scene.sunBloom;
  2989. } else if (!defined(scene.sun) && defined(scene._sunPostProcess)) {
  2990. scene._sunPostProcess = scene._sunPostProcess.destroy();
  2991. scene._sunBloom = false;
  2992. }
  2993. // Clear the pass state framebuffer.
  2994. const clear = scene._clearColorCommand;
  2995. Color.clone(clearColor, clear.color);
  2996. clear.execute(context, passState);
  2997. // Update globe depth rendering based on the current context and clear the globe depth framebuffer.
  2998. // Globe depth is copied for the pick pass to support picking batched geometries in GroundPrimitives.
  2999. const useGlobeDepthFramebuffer = (environmentState.useGlobeDepthFramebuffer = defined(
  3000. view.globeDepth
  3001. ));
  3002. if (useGlobeDepthFramebuffer) {
  3003. view.globeDepth.update(
  3004. context,
  3005. passState,
  3006. view.viewport,
  3007. scene.msaaSamples,
  3008. scene._hdr,
  3009. environmentState.clearGlobeDepth
  3010. );
  3011. view.globeDepth.clear(context, passState, clearColor);
  3012. }
  3013. // If supported, configure OIT to use the globe depth framebuffer and clear the OIT framebuffer.
  3014. const oit = view.oit;
  3015. const useOIT = (environmentState.useOIT =
  3016. !picking && defined(oit) && oit.isSupported());
  3017. if (useOIT) {
  3018. oit.update(
  3019. context,
  3020. passState,
  3021. view.globeDepth.colorFramebufferManager,
  3022. scene._hdr,
  3023. scene.msaaSamples
  3024. );
  3025. oit.clear(context, passState, clearColor);
  3026. environmentState.useOIT = oit.isSupported();
  3027. }
  3028. const postProcess = scene.postProcessStages;
  3029. let usePostProcess = (environmentState.usePostProcess =
  3030. !picking &&
  3031. (scene._hdr ||
  3032. postProcess.length > 0 ||
  3033. postProcess.ambientOcclusion.enabled ||
  3034. postProcess.fxaa.enabled ||
  3035. postProcess.bloom.enabled));
  3036. environmentState.usePostProcessSelected = false;
  3037. if (usePostProcess) {
  3038. view.sceneFramebuffer.update(
  3039. context,
  3040. view.viewport,
  3041. scene._hdr,
  3042. scene.msaaSamples
  3043. );
  3044. view.sceneFramebuffer.clear(context, passState, clearColor);
  3045. postProcess.update(context, frameState.useLogDepth, scene._hdr);
  3046. postProcess.clear(context);
  3047. usePostProcess = environmentState.usePostProcess = postProcess.ready;
  3048. environmentState.usePostProcessSelected =
  3049. usePostProcess && postProcess.hasSelected;
  3050. }
  3051. if (environmentState.isSunVisible && scene.sunBloom && !useWebVR) {
  3052. passState.framebuffer = scene._sunPostProcess.update(passState);
  3053. scene._sunPostProcess.clear(context, passState, clearColor);
  3054. } else if (useGlobeDepthFramebuffer) {
  3055. passState.framebuffer = view.globeDepth.framebuffer;
  3056. } else if (usePostProcess) {
  3057. passState.framebuffer = view.sceneFramebuffer.framebuffer;
  3058. }
  3059. if (defined(passState.framebuffer)) {
  3060. clear.execute(context, passState);
  3061. }
  3062. const useInvertClassification = (environmentState.useInvertClassification =
  3063. !picking && defined(passState.framebuffer) && scene.invertClassification);
  3064. if (useInvertClassification) {
  3065. let depthFramebuffer;
  3066. if (scene.frameState.invertClassificationColor.alpha === 1.0) {
  3067. if (environmentState.useGlobeDepthFramebuffer) {
  3068. depthFramebuffer = view.globeDepth.framebuffer;
  3069. }
  3070. }
  3071. if (defined(depthFramebuffer) || context.depthTexture) {
  3072. scene._invertClassification.previousFramebuffer = depthFramebuffer;
  3073. scene._invertClassification.update(
  3074. context,
  3075. scene.msaaSamples,
  3076. view.globeDepth.colorFramebufferManager
  3077. );
  3078. scene._invertClassification.clear(context, passState);
  3079. if (scene.frameState.invertClassificationColor.alpha < 1.0 && useOIT) {
  3080. const command = scene._invertClassification.unclassifiedCommand;
  3081. const derivedCommands = command.derivedCommands;
  3082. derivedCommands.oit = oit.createDerivedCommands(
  3083. command,
  3084. context,
  3085. derivedCommands.oit
  3086. );
  3087. }
  3088. } else {
  3089. environmentState.useInvertClassification = false;
  3090. }
  3091. }
  3092. if (scene._globeTranslucencyState.translucent) {
  3093. view.globeTranslucencyFramebuffer.updateAndClear(
  3094. scene._hdr,
  3095. view.viewport,
  3096. context,
  3097. passState
  3098. );
  3099. }
  3100. }
  3101. /**
  3102. * @private
  3103. */
  3104. Scene.prototype.resolveFramebuffers = function (passState) {
  3105. const context = this._context;
  3106. const environmentState = this._environmentState;
  3107. const view = this._view;
  3108. const globeDepth = view.globeDepth;
  3109. if (defined(globeDepth)) {
  3110. globeDepth.prepareColorTextures(context);
  3111. }
  3112. const useOIT = environmentState.useOIT;
  3113. const useGlobeDepthFramebuffer = environmentState.useGlobeDepthFramebuffer;
  3114. const usePostProcess = environmentState.usePostProcess;
  3115. const defaultFramebuffer = environmentState.originalFramebuffer;
  3116. const globeFramebuffer = useGlobeDepthFramebuffer
  3117. ? globeDepth.colorFramebufferManager
  3118. : undefined;
  3119. const sceneFramebuffer = view.sceneFramebuffer._colorFramebuffer;
  3120. const idFramebuffer = view.sceneFramebuffer.idFramebuffer;
  3121. if (useOIT) {
  3122. passState.framebuffer = usePostProcess
  3123. ? sceneFramebuffer.framebuffer
  3124. : defaultFramebuffer;
  3125. view.oit.execute(context, passState);
  3126. }
  3127. const translucentTileClassification = view.translucentTileClassification;
  3128. if (
  3129. translucentTileClassification.hasTranslucentDepth &&
  3130. translucentTileClassification.isSupported()
  3131. ) {
  3132. translucentTileClassification.execute(this, passState);
  3133. }
  3134. if (usePostProcess) {
  3135. view.sceneFramebuffer.prepareColorTextures(context);
  3136. let inputFramebuffer = sceneFramebuffer;
  3137. if (useGlobeDepthFramebuffer && !useOIT) {
  3138. inputFramebuffer = globeFramebuffer;
  3139. }
  3140. const postProcess = this.postProcessStages;
  3141. const colorTexture = inputFramebuffer.getColorTexture(0);
  3142. const idTexture = idFramebuffer.getColorTexture(0);
  3143. const depthTexture = defaultValue(
  3144. globeFramebuffer,
  3145. sceneFramebuffer
  3146. ).getDepthStencilTexture();
  3147. postProcess.execute(context, colorTexture, depthTexture, idTexture);
  3148. postProcess.copy(context, defaultFramebuffer);
  3149. }
  3150. if (!useOIT && !usePostProcess && useGlobeDepthFramebuffer) {
  3151. passState.framebuffer = defaultFramebuffer;
  3152. globeDepth.executeCopyColor(context, passState);
  3153. }
  3154. };
  3155. function callAfterRenderFunctions(scene) {
  3156. // Functions are queued up during primitive update and executed here in case
  3157. // the function modifies scene state that should remain constant over the frame.
  3158. const functions = scene._frameState.afterRender;
  3159. for (let i = 0, length = functions.length; i < length; ++i) {
  3160. const shouldRequestRender = functions[i]();
  3161. if (shouldRequestRender) {
  3162. scene.requestRender();
  3163. }
  3164. }
  3165. functions.length = 0;
  3166. }
  3167. function getGlobeHeight(scene) {
  3168. const globe = scene._globe;
  3169. const camera = scene.camera;
  3170. const cartographic = camera.positionCartographic;
  3171. if (defined(globe) && globe.show && defined(cartographic)) {
  3172. return globe.getHeight(cartographic);
  3173. }
  3174. return undefined;
  3175. }
  3176. function isCameraUnderground(scene) {
  3177. const camera = scene.camera;
  3178. const mode = scene._mode;
  3179. const globe = scene.globe;
  3180. const cameraController = scene._screenSpaceCameraController;
  3181. const cartographic = camera.positionCartographic;
  3182. if (!defined(cartographic)) {
  3183. return false;
  3184. }
  3185. if (!cameraController.onMap() && cartographic.height < 0.0) {
  3186. // The camera can go off the map while in Columbus View.
  3187. // Make a best guess as to whether it's underground by checking if its height is less than zero.
  3188. return true;
  3189. }
  3190. if (
  3191. !defined(globe) ||
  3192. !globe.show ||
  3193. mode === SceneMode.SCENE2D ||
  3194. mode === SceneMode.MORPHING
  3195. ) {
  3196. return false;
  3197. }
  3198. const globeHeight = scene._globeHeight;
  3199. return defined(globeHeight) && cartographic.height < globeHeight;
  3200. }
  3201. /**
  3202. * @private
  3203. */
  3204. Scene.prototype.initializeFrame = function () {
  3205. // Destroy released shaders and textures once every 120 frames to avoid thrashing the cache
  3206. if (this._shaderFrameCount++ === 120) {
  3207. this._shaderFrameCount = 0;
  3208. this._context.shaderCache.destroyReleasedShaderPrograms();
  3209. this._context.textureCache.destroyReleasedTextures();
  3210. }
  3211. this._tweens.update();
  3212. this._globeHeight = getGlobeHeight(this);
  3213. this._cameraUnderground = isCameraUnderground(this);
  3214. this._globeTranslucencyState.update(this);
  3215. this._screenSpaceCameraController.update();
  3216. if (defined(this._deviceOrientationCameraController)) {
  3217. this._deviceOrientationCameraController.update();
  3218. }
  3219. this.camera.update(this._mode);
  3220. this.camera._updateCameraChanged();
  3221. };
  3222. function updateDebugShowFramesPerSecond(scene, renderedThisFrame) {
  3223. if (scene.debugShowFramesPerSecond) {
  3224. if (!defined(scene._performanceDisplay)) {
  3225. const performanceContainer = document.createElement("div");
  3226. performanceContainer.className =
  3227. "cesium-performanceDisplay-defaultContainer";
  3228. const container = scene._canvas.parentNode;
  3229. container.appendChild(performanceContainer);
  3230. const performanceDisplay = new PerformanceDisplay({
  3231. container: performanceContainer,
  3232. });
  3233. scene._performanceDisplay = performanceDisplay;
  3234. scene._performanceContainer = performanceContainer;
  3235. }
  3236. scene._performanceDisplay.throttled = scene.requestRenderMode;
  3237. scene._performanceDisplay.update(renderedThisFrame);
  3238. } else if (defined(scene._performanceDisplay)) {
  3239. scene._performanceDisplay =
  3240. scene._performanceDisplay && scene._performanceDisplay.destroy();
  3241. scene._performanceContainer.parentNode.removeChild(
  3242. scene._performanceContainer
  3243. );
  3244. }
  3245. }
  3246. function prePassesUpdate(scene) {
  3247. scene._jobScheduler.resetBudgets();
  3248. const frameState = scene._frameState;
  3249. const primitives = scene.primitives;
  3250. primitives.prePassesUpdate(frameState);
  3251. if (defined(scene.globe)) {
  3252. scene.globe.update(frameState);
  3253. }
  3254. scene._picking.update();
  3255. frameState.creditDisplay.update();
  3256. }
  3257. function postPassesUpdate(scene) {
  3258. const frameState = scene._frameState;
  3259. const primitives = scene.primitives;
  3260. primitives.postPassesUpdate(frameState);
  3261. RequestScheduler.update();
  3262. }
  3263. const scratchBackgroundColor = new Color();
  3264. function render(scene) {
  3265. const frameState = scene._frameState;
  3266. const context = scene.context;
  3267. const us = context.uniformState;
  3268. const view = scene._defaultView;
  3269. scene._view = view;
  3270. scene.updateFrameState();
  3271. frameState.passes.render = true;
  3272. frameState.passes.postProcess = scene.postProcessStages.hasSelected;
  3273. frameState.tilesetPassState = renderTilesetPassState;
  3274. let backgroundColor = defaultValue(scene.backgroundColor, Color.BLACK);
  3275. if (scene._hdr) {
  3276. backgroundColor = Color.clone(backgroundColor, scratchBackgroundColor);
  3277. backgroundColor.red = Math.pow(backgroundColor.red, scene.gamma);
  3278. backgroundColor.green = Math.pow(backgroundColor.green, scene.gamma);
  3279. backgroundColor.blue = Math.pow(backgroundColor.blue, scene.gamma);
  3280. }
  3281. frameState.backgroundColor = backgroundColor;
  3282. scene.fog.update(frameState);
  3283. us.update(frameState);
  3284. const shadowMap = scene.shadowMap;
  3285. if (defined(shadowMap) && shadowMap.enabled) {
  3286. if (!defined(scene.light) || scene.light instanceof SunLight) {
  3287. // Negate the sun direction so that it is from the Sun, not to the Sun
  3288. Cartesian3.negate(us.sunDirectionWC, scene._shadowMapCamera.direction);
  3289. } else {
  3290. Cartesian3.clone(scene.light.direction, scene._shadowMapCamera.direction);
  3291. }
  3292. frameState.shadowMaps.push(shadowMap);
  3293. }
  3294. scene._computeCommandList.length = 0;
  3295. scene._overlayCommandList.length = 0;
  3296. const viewport = view.viewport;
  3297. viewport.x = 0;
  3298. viewport.y = 0;
  3299. viewport.width = context.drawingBufferWidth;
  3300. viewport.height = context.drawingBufferHeight;
  3301. const passState = view.passState;
  3302. passState.framebuffer = undefined;
  3303. passState.blendingEnabled = undefined;
  3304. passState.scissorTest = undefined;
  3305. passState.viewport = BoundingRectangle.clone(viewport, passState.viewport);
  3306. if (defined(scene.globe)) {
  3307. scene.globe.beginFrame(frameState);
  3308. }
  3309. scene.updateEnvironment();
  3310. scene.updateAndExecuteCommands(passState, backgroundColor);
  3311. scene.resolveFramebuffers(passState);
  3312. passState.framebuffer = undefined;
  3313. executeOverlayCommands(scene, passState);
  3314. if (defined(scene.globe)) {
  3315. scene.globe.endFrame(frameState);
  3316. if (!scene.globe.tilesLoaded) {
  3317. scene._renderRequested = true;
  3318. }
  3319. }
  3320. context.endFrame();
  3321. }
  3322. function tryAndCatchError(scene, functionToExecute) {
  3323. try {
  3324. functionToExecute(scene);
  3325. } catch (error) {
  3326. scene._renderError.raiseEvent(scene, error);
  3327. if (scene.rethrowRenderErrors) {
  3328. throw error;
  3329. }
  3330. }
  3331. }
  3332. function updateMostDetailedRayPicks(scene) {
  3333. return scene._picking.updateMostDetailedRayPicks(scene);
  3334. }
  3335. /**
  3336. * Update and render the scene. It is usually not necessary to call this function
  3337. * directly because {@link CesiumWidget} will do it automatically.
  3338. * @param {JulianDate} [time] The simulation time at which to render.
  3339. */
  3340. Scene.prototype.render = function (time) {
  3341. /**
  3342. *
  3343. * Pre passes update. Execute any pass invariant code that should run before the passes here.
  3344. *
  3345. */
  3346. this._preUpdate.raiseEvent(this, time);
  3347. const frameState = this._frameState;
  3348. frameState.newFrame = false;
  3349. if (!defined(time)) {
  3350. time = JulianDate.now();
  3351. }
  3352. // Determine if shouldRender
  3353. const cameraChanged = this._view.checkForCameraUpdates(this);
  3354. let shouldRender =
  3355. !this.requestRenderMode ||
  3356. this._renderRequested ||
  3357. cameraChanged ||
  3358. this._logDepthBufferDirty ||
  3359. this._hdrDirty ||
  3360. this.mode === SceneMode.MORPHING;
  3361. if (
  3362. !shouldRender &&
  3363. defined(this.maximumRenderTimeChange) &&
  3364. defined(this._lastRenderTime)
  3365. ) {
  3366. const difference = Math.abs(
  3367. JulianDate.secondsDifference(this._lastRenderTime, time)
  3368. );
  3369. shouldRender = shouldRender || difference > this.maximumRenderTimeChange;
  3370. }
  3371. if (shouldRender) {
  3372. this._lastRenderTime = JulianDate.clone(time, this._lastRenderTime);
  3373. this._renderRequested = false;
  3374. this._logDepthBufferDirty = false;
  3375. this._hdrDirty = false;
  3376. const frameNumber = CesiumMath.incrementWrap(
  3377. frameState.frameNumber,
  3378. 15000000.0,
  3379. 1.0
  3380. );
  3381. updateFrameNumber(this, frameNumber, time);
  3382. frameState.newFrame = true;
  3383. }
  3384. tryAndCatchError(this, prePassesUpdate);
  3385. /**
  3386. *
  3387. * Passes update. Add any passes here
  3388. *
  3389. */
  3390. if (this.primitives.show) {
  3391. tryAndCatchError(this, updateMostDetailedRayPicks);
  3392. tryAndCatchError(this, updatePreloadPass);
  3393. tryAndCatchError(this, updatePreloadFlightPass);
  3394. if (!shouldRender) {
  3395. tryAndCatchError(this, updateRequestRenderModeDeferCheckPass);
  3396. }
  3397. }
  3398. this._postUpdate.raiseEvent(this, time);
  3399. if (shouldRender) {
  3400. this._preRender.raiseEvent(this, time);
  3401. frameState.creditDisplay.beginFrame();
  3402. tryAndCatchError(this, render);
  3403. }
  3404. /**
  3405. *
  3406. * Post passes update. Execute any pass invariant code that should run after the passes here.
  3407. *
  3408. */
  3409. updateDebugShowFramesPerSecond(this, shouldRender);
  3410. tryAndCatchError(this, postPassesUpdate);
  3411. // Often used to trigger events (so don't want in trycatch) that the user might be subscribed to. Things like the tile load events, ready promises, etc.
  3412. // We don't want those events to resolve during the render loop because the events might add new primitives
  3413. callAfterRenderFunctions(this);
  3414. if (shouldRender) {
  3415. this._postRender.raiseEvent(this, time);
  3416. frameState.creditDisplay.endFrame();
  3417. }
  3418. };
  3419. /**
  3420. * Update and render the scene. Always forces a new render frame regardless of whether a render was
  3421. * previously requested.
  3422. * @param {JulianDate} [time] The simulation time at which to render.
  3423. *
  3424. * @private
  3425. */
  3426. Scene.prototype.forceRender = function (time) {
  3427. this._renderRequested = true;
  3428. this.render(time);
  3429. };
  3430. /**
  3431. * Requests a new rendered frame when {@link Scene#requestRenderMode} is set to <code>true</code>.
  3432. * The render rate will not exceed the {@link CesiumWidget#targetFrameRate}.
  3433. *
  3434. * @see Scene#requestRenderMode
  3435. */
  3436. Scene.prototype.requestRender = function () {
  3437. this._renderRequested = true;
  3438. };
  3439. /**
  3440. * @private
  3441. */
  3442. Scene.prototype.clampLineWidth = function (width) {
  3443. return Math.max(
  3444. ContextLimits.minimumAliasedLineWidth,
  3445. Math.min(width, ContextLimits.maximumAliasedLineWidth)
  3446. );
  3447. };
  3448. /**
  3449. * Returns an object with a `primitive` property that contains the first (top) primitive in the scene
  3450. * at a particular window coordinate or undefined if nothing is at the location. Other properties may
  3451. * potentially be set depending on the type of primitive and may be used to further identify the picked object.
  3452. * <p>
  3453. * When a feature of a 3D Tiles tileset is picked, <code>pick</code> returns a {@link Cesium3DTileFeature} object.
  3454. * </p>
  3455. *
  3456. * @example
  3457. * // On mouse over, color the feature yellow.
  3458. * handler.setInputAction(function(movement) {
  3459. * const feature = scene.pick(movement.endPosition);
  3460. * if (feature instanceof Cesium.Cesium3DTileFeature) {
  3461. * feature.color = Cesium.Color.YELLOW;
  3462. * }
  3463. * }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  3464. *
  3465. * @param {Cartesian2} windowPosition Window coordinates to perform picking on.
  3466. * @param {number} [width=3] Width of the pick rectangle.
  3467. * @param {number} [height=3] Height of the pick rectangle.
  3468. * @returns {object} Object containing the picked primitive.
  3469. */
  3470. Scene.prototype.pick = function (windowPosition, width, height) {
  3471. return this._picking.pick(this, windowPosition, width, height);
  3472. };
  3473. /**
  3474. * Returns the cartesian position reconstructed from the depth buffer and window position.
  3475. * The returned position is in world coordinates. Used internally by camera functions to
  3476. * prevent conversion to projected 2D coordinates and then back.
  3477. * <p>
  3478. * Set {@link Scene#pickTranslucentDepth} to <code>true</code> to include the depth of
  3479. * translucent primitives; otherwise, this essentially picks through translucent primitives.
  3480. * </p>
  3481. *
  3482. * @private
  3483. *
  3484. * @param {Cartesian2} windowPosition Window coordinates to perform picking on.
  3485. * @param {Cartesian3} [result] The object on which to restore the result.
  3486. * @returns {Cartesian3} The cartesian position in world coordinates.
  3487. *
  3488. * @exception {DeveloperError} Picking from the depth buffer is not supported. Check pickPositionSupported.
  3489. */
  3490. Scene.prototype.pickPositionWorldCoordinates = function (
  3491. windowPosition,
  3492. result
  3493. ) {
  3494. return this._picking.pickPositionWorldCoordinates(
  3495. this,
  3496. windowPosition,
  3497. result
  3498. );
  3499. };
  3500. /**
  3501. * Returns the cartesian position reconstructed from the depth buffer and window position.
  3502. * <p>
  3503. * The position reconstructed from the depth buffer in 2D may be slightly different from those
  3504. * reconstructed in 3D and Columbus view. This is caused by the difference in the distribution
  3505. * of depth values of perspective and orthographic projection.
  3506. * </p>
  3507. * <p>
  3508. * Set {@link Scene#pickTranslucentDepth} to <code>true</code> to include the depth of
  3509. * translucent primitives; otherwise, this essentially picks through translucent primitives.
  3510. * </p>
  3511. *
  3512. * @param {Cartesian2} windowPosition Window coordinates to perform picking on.
  3513. * @param {Cartesian3} [result] The object on which to restore the result.
  3514. * @returns {Cartesian3} The cartesian position.
  3515. *
  3516. * @exception {DeveloperError} Picking from the depth buffer is not supported. Check pickPositionSupported.
  3517. */
  3518. Scene.prototype.pickPosition = function (windowPosition, result) {
  3519. return this._picking.pickPosition(this, windowPosition, result);
  3520. };
  3521. /**
  3522. * Returns a list of objects, each containing a `primitive` property, for all primitives at
  3523. * a particular window coordinate position. Other properties may also be set depending on the
  3524. * type of primitive and may be used to further identify the picked object. The primitives in
  3525. * the list are ordered by their visual order in the scene (front to back).
  3526. *
  3527. * @param {Cartesian2} windowPosition Window coordinates to perform picking on.
  3528. * @param {number} [limit] If supplied, stop drilling after collecting this many picks.
  3529. * @param {number} [width=3] Width of the pick rectangle.
  3530. * @param {number} [height=3] Height of the pick rectangle.
  3531. * @returns {any[]} Array of objects, each containing 1 picked primitives.
  3532. *
  3533. * @exception {DeveloperError} windowPosition is undefined.
  3534. *
  3535. * @example
  3536. * const pickedObjects = scene.drillPick(new Cesium.Cartesian2(100.0, 200.0));
  3537. *
  3538. * @see Scene#pick
  3539. */
  3540. Scene.prototype.drillPick = function (windowPosition, limit, width, height) {
  3541. return this._picking.drillPick(this, windowPosition, limit, width, height);
  3542. };
  3543. function updatePreloadPass(scene) {
  3544. const frameState = scene._frameState;
  3545. preloadTilesetPassState.camera = frameState.camera;
  3546. preloadTilesetPassState.cullingVolume = frameState.cullingVolume;
  3547. const primitives = scene.primitives;
  3548. primitives.updateForPass(frameState, preloadTilesetPassState);
  3549. }
  3550. function updatePreloadFlightPass(scene) {
  3551. const frameState = scene._frameState;
  3552. const camera = frameState.camera;
  3553. if (!camera.canPreloadFlight()) {
  3554. return;
  3555. }
  3556. preloadFlightTilesetPassState.camera = scene.preloadFlightCamera;
  3557. preloadFlightTilesetPassState.cullingVolume =
  3558. scene.preloadFlightCullingVolume;
  3559. const primitives = scene.primitives;
  3560. primitives.updateForPass(frameState, preloadFlightTilesetPassState);
  3561. }
  3562. function updateRequestRenderModeDeferCheckPass(scene) {
  3563. // Check if any ignored requests are ready to go (to wake rendering up again)
  3564. scene.primitives.updateForPass(
  3565. scene._frameState,
  3566. requestRenderModeDeferCheckPassState
  3567. );
  3568. }
  3569. /**
  3570. * Returns an object containing the first object intersected by the ray and the position of intersection,
  3571. * or <code>undefined</code> if there were no intersections. The intersected object has a <code>primitive</code>
  3572. * property that contains the intersected primitive. Other properties may be set depending on the type of primitive
  3573. * and may be used to further identify the picked object. The ray must be given in world coordinates.
  3574. * <p>
  3575. * This function only picks globe tiles and 3D Tiles that are rendered in the current view. Picks all other
  3576. * primitives regardless of their visibility.
  3577. * </p>
  3578. *
  3579. * @private
  3580. *
  3581. * @param {Ray} ray The ray.
  3582. * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to exclude from the ray intersection.
  3583. * @param {number} [width=0.1] Width of the intersection volume in meters.
  3584. * @returns {object} An object containing the object and position of the first intersection.
  3585. *
  3586. * @exception {DeveloperError} Ray intersections are only supported in 3D mode.
  3587. */
  3588. Scene.prototype.pickFromRay = function (ray, objectsToExclude, width) {
  3589. return this._picking.pickFromRay(this, ray, objectsToExclude, width);
  3590. };
  3591. /**
  3592. * Returns a list of objects, each containing the object intersected by the ray and the position of intersection.
  3593. * The intersected object has a <code>primitive</code> property that contains the intersected primitive. Other
  3594. * properties may also be set depending on the type of primitive and may be used to further identify the picked object.
  3595. * The primitives in the list are ordered by first intersection to last intersection. The ray must be given in
  3596. * world coordinates.
  3597. * <p>
  3598. * This function only picks globe tiles and 3D Tiles that are rendered in the current view. Picks all other
  3599. * primitives regardless of their visibility.
  3600. * </p>
  3601. *
  3602. * @private
  3603. *
  3604. * @param {Ray} ray The ray.
  3605. * @param {number} [limit=Number.MAX_VALUE] If supplied, stop finding intersections after this many intersections.
  3606. * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to exclude from the ray intersection.
  3607. * @param {number} [width=0.1] Width of the intersection volume in meters.
  3608. * @returns {Object[]} List of objects containing the object and position of each intersection.
  3609. *
  3610. * @exception {DeveloperError} Ray intersections are only supported in 3D mode.
  3611. */
  3612. Scene.prototype.drillPickFromRay = function (
  3613. ray,
  3614. limit,
  3615. objectsToExclude,
  3616. width
  3617. ) {
  3618. return this._picking.drillPickFromRay(
  3619. this,
  3620. ray,
  3621. limit,
  3622. objectsToExclude,
  3623. width
  3624. );
  3625. };
  3626. /**
  3627. * Initiates an asynchronous {@link Scene#pickFromRay} request using the maximum level of detail for 3D Tilesets
  3628. * regardless of visibility.
  3629. *
  3630. * @private
  3631. *
  3632. * @param {Ray} ray The ray.
  3633. * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to exclude from the ray intersection.
  3634. * @param {number} [width=0.1] Width of the intersection volume in meters.
  3635. * @returns {Promise<object>} A promise that resolves to an object containing the object and position of the first intersection.
  3636. *
  3637. * @exception {DeveloperError} Ray intersections are only supported in 3D mode.
  3638. */
  3639. Scene.prototype.pickFromRayMostDetailed = function (
  3640. ray,
  3641. objectsToExclude,
  3642. width
  3643. ) {
  3644. return this._picking.pickFromRayMostDetailed(
  3645. this,
  3646. ray,
  3647. objectsToExclude,
  3648. width
  3649. );
  3650. };
  3651. /**
  3652. * Initiates an asynchronous {@link Scene#drillPickFromRay} request using the maximum level of detail for 3D Tilesets
  3653. * regardless of visibility.
  3654. *
  3655. * @private
  3656. *
  3657. * @param {Ray} ray The ray.
  3658. * @param {number} [limit=Number.MAX_VALUE] If supplied, stop finding intersections after this many intersections.
  3659. * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to exclude from the ray intersection.
  3660. * @param {number} [width=0.1] Width of the intersection volume in meters.
  3661. * @returns {Promise<Object[]>} A promise that resolves to a list of objects containing the object and position of each intersection.
  3662. *
  3663. * @exception {DeveloperError} Ray intersections are only supported in 3D mode.
  3664. */
  3665. Scene.prototype.drillPickFromRayMostDetailed = function (
  3666. ray,
  3667. limit,
  3668. objectsToExclude,
  3669. width
  3670. ) {
  3671. return this._picking.drillPickFromRayMostDetailed(
  3672. this,
  3673. ray,
  3674. limit,
  3675. objectsToExclude,
  3676. width
  3677. );
  3678. };
  3679. /**
  3680. * Returns the height of scene geometry at the given cartographic position or <code>undefined</code> if there was no
  3681. * scene geometry to sample height from. The height of the input position is ignored. May be used to clamp objects to
  3682. * the globe, 3D Tiles, or primitives in the scene.
  3683. * <p>
  3684. * This function only samples height from globe tiles and 3D Tiles that are rendered in the current view. Samples height
  3685. * from all other primitives regardless of their visibility.
  3686. * </p>
  3687. *
  3688. * @param {Cartographic} position The cartographic position to sample height from.
  3689. * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to not sample height from.
  3690. * @param {number} [width=0.1] Width of the intersection volume in meters.
  3691. * @returns {number} The height. This may be <code>undefined</code> if there was no scene geometry to sample height from.
  3692. *
  3693. * @example
  3694. * const position = new Cesium.Cartographic(-1.31968, 0.698874);
  3695. * const height = viewer.scene.sampleHeight(position);
  3696. * console.log(height);
  3697. *
  3698. * @see Scene#clampToHeight
  3699. * @see Scene#clampToHeightMostDetailed
  3700. * @see Scene#sampleHeightMostDetailed
  3701. *
  3702. * @exception {DeveloperError} sampleHeight is only supported in 3D mode.
  3703. * @exception {DeveloperError} sampleHeight requires depth texture support. Check sampleHeightSupported.
  3704. */
  3705. Scene.prototype.sampleHeight = function (position, objectsToExclude, width) {
  3706. return this._picking.sampleHeight(this, position, objectsToExclude, width);
  3707. };
  3708. /**
  3709. * Clamps the given cartesian position to the scene geometry along the geodetic surface normal. Returns the
  3710. * clamped position or <code>undefined</code> if there was no scene geometry to clamp to. May be used to clamp
  3711. * objects to the globe, 3D Tiles, or primitives in the scene.
  3712. * <p>
  3713. * This function only clamps to globe tiles and 3D Tiles that are rendered in the current view. Clamps to
  3714. * all other primitives regardless of their visibility.
  3715. * </p>
  3716. *
  3717. * @param {Cartesian3} cartesian The cartesian position.
  3718. * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to not clamp to.
  3719. * @param {number} [width=0.1] Width of the intersection volume in meters.
  3720. * @param {Cartesian3} [result] An optional object to return the clamped position.
  3721. * @returns {Cartesian3} The modified result parameter or a new Cartesian3 instance if one was not provided. This may be <code>undefined</code> if there was no scene geometry to clamp to.
  3722. *
  3723. * @example
  3724. * // Clamp an entity to the underlying scene geometry
  3725. * const position = entity.position.getValue(Cesium.JulianDate.now());
  3726. * entity.position = viewer.scene.clampToHeight(position);
  3727. *
  3728. * @see Scene#sampleHeight
  3729. * @see Scene#sampleHeightMostDetailed
  3730. * @see Scene#clampToHeightMostDetailed
  3731. *
  3732. * @exception {DeveloperError} clampToHeight is only supported in 3D mode.
  3733. * @exception {DeveloperError} clampToHeight requires depth texture support. Check clampToHeightSupported.
  3734. */
  3735. Scene.prototype.clampToHeight = function (
  3736. cartesian,
  3737. objectsToExclude,
  3738. width,
  3739. result
  3740. ) {
  3741. return this._picking.clampToHeight(
  3742. this,
  3743. cartesian,
  3744. objectsToExclude,
  3745. width,
  3746. result
  3747. );
  3748. };
  3749. /**
  3750. * Initiates an asynchronous {@link Scene#sampleHeight} query for an array of {@link Cartographic} positions
  3751. * using the maximum level of detail for 3D Tilesets in the scene. The height of the input positions is ignored.
  3752. * Returns a promise that is resolved when the query completes. Each point height is modified in place.
  3753. * If a height cannot be determined because no geometry can be sampled at that location, or another error occurs,
  3754. * the height is set to undefined.
  3755. *
  3756. * @param {Cartographic[]} positions The cartographic positions to update with sampled heights.
  3757. * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to not sample height from.
  3758. * @param {number} [width=0.1] Width of the intersection volume in meters.
  3759. * @returns {Promise<Cartographic[]>} A promise that resolves to the provided list of positions when the query has completed.
  3760. *
  3761. * @example
  3762. * const positions = [
  3763. * new Cesium.Cartographic(-1.31968, 0.69887),
  3764. * new Cesium.Cartographic(-1.10489, 0.83923)
  3765. * ];
  3766. * const promise = viewer.scene.sampleHeightMostDetailed(positions);
  3767. * promise.then(function(updatedPosition) {
  3768. * // positions[0].height and positions[1].height have been updated.
  3769. * // updatedPositions is just a reference to positions.
  3770. * }
  3771. *
  3772. * @see Scene#sampleHeight
  3773. *
  3774. * @exception {DeveloperError} sampleHeightMostDetailed is only supported in 3D mode.
  3775. * @exception {DeveloperError} sampleHeightMostDetailed requires depth texture support. Check sampleHeightSupported.
  3776. */
  3777. Scene.prototype.sampleHeightMostDetailed = function (
  3778. positions,
  3779. objectsToExclude,
  3780. width
  3781. ) {
  3782. return this._picking.sampleHeightMostDetailed(
  3783. this,
  3784. positions,
  3785. objectsToExclude,
  3786. width
  3787. );
  3788. };
  3789. /**
  3790. * Initiates an asynchronous {@link Scene#clampToHeight} query for an array of {@link Cartesian3} positions
  3791. * using the maximum level of detail for 3D Tilesets in the scene. Returns a promise that is resolved when
  3792. * the query completes. Each position is modified in place. If a position cannot be clamped because no geometry
  3793. * can be sampled at that location, or another error occurs, the element in the array is set to undefined.
  3794. *
  3795. * @param {Cartesian3[]} cartesians The cartesian positions to update with clamped positions.
  3796. * @param {Object[]} [objectsToExclude] A list of primitives, entities, or 3D Tiles features to not clamp to.
  3797. * @param {number} [width=0.1] Width of the intersection volume in meters.
  3798. * @returns {Promise<Cartesian3[]>} A promise that resolves to the provided list of positions when the query has completed.
  3799. *
  3800. * @example
  3801. * const cartesians = [
  3802. * entities[0].position.getValue(Cesium.JulianDate.now()),
  3803. * entities[1].position.getValue(Cesium.JulianDate.now())
  3804. * ];
  3805. * const promise = viewer.scene.clampToHeightMostDetailed(cartesians);
  3806. * promise.then(function(updatedCartesians) {
  3807. * entities[0].position = updatedCartesians[0];
  3808. * entities[1].position = updatedCartesians[1];
  3809. * }
  3810. *
  3811. * @see Scene#clampToHeight
  3812. *
  3813. * @exception {DeveloperError} clampToHeightMostDetailed is only supported in 3D mode.
  3814. * @exception {DeveloperError} clampToHeightMostDetailed requires depth texture support. Check clampToHeightSupported.
  3815. */
  3816. Scene.prototype.clampToHeightMostDetailed = function (
  3817. cartesians,
  3818. objectsToExclude,
  3819. width
  3820. ) {
  3821. return this._picking.clampToHeightMostDetailed(
  3822. this,
  3823. cartesians,
  3824. objectsToExclude,
  3825. width
  3826. );
  3827. };
  3828. /**
  3829. * Transforms a position in cartesian coordinates to canvas coordinates. This is commonly used to place an
  3830. * HTML element at the same screen position as an object in the scene.
  3831. *
  3832. * @param {Cartesian3} position The position in cartesian coordinates.
  3833. * @param {Cartesian2} [result] An optional object to return the input position transformed to canvas coordinates.
  3834. * @returns {Cartesian2} The modified result parameter or a new Cartesian2 instance if one was not provided. This may be <code>undefined</code> if the input position is near the center of the ellipsoid.
  3835. *
  3836. * @example
  3837. * // Output the canvas position of longitude/latitude (0, 0) every time the mouse moves.
  3838. * const scene = widget.scene;
  3839. * const ellipsoid = scene.globe.ellipsoid;
  3840. * const position = Cesium.Cartesian3.fromDegrees(0.0, 0.0);
  3841. * const handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
  3842. * handler.setInputAction(function(movement) {
  3843. * console.log(scene.cartesianToCanvasCoordinates(position));
  3844. * }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
  3845. */
  3846. Scene.prototype.cartesianToCanvasCoordinates = function (position, result) {
  3847. return SceneTransforms.wgs84ToWindowCoordinates(this, position, result);
  3848. };
  3849. /**
  3850. * Instantly completes an active transition.
  3851. */
  3852. Scene.prototype.completeMorph = function () {
  3853. this._transitioner.completeMorph();
  3854. };
  3855. /**
  3856. * Asynchronously transitions the scene to 2D.
  3857. * @param {number} [duration=2.0] The amount of time, in seconds, for transition animations to complete.
  3858. */
  3859. Scene.prototype.morphTo2D = function (duration) {
  3860. let ellipsoid;
  3861. const globe = this.globe;
  3862. if (defined(globe)) {
  3863. ellipsoid = globe.ellipsoid;
  3864. } else {
  3865. ellipsoid = this.mapProjection.ellipsoid;
  3866. }
  3867. duration = defaultValue(duration, 2.0);
  3868. this._transitioner.morphTo2D(duration, ellipsoid);
  3869. };
  3870. /**
  3871. * Asynchronously transitions the scene to Columbus View.
  3872. * @param {number} [duration=2.0] The amount of time, in seconds, for transition animations to complete.
  3873. */
  3874. Scene.prototype.morphToColumbusView = function (duration) {
  3875. let ellipsoid;
  3876. const globe = this.globe;
  3877. if (defined(globe)) {
  3878. ellipsoid = globe.ellipsoid;
  3879. } else {
  3880. ellipsoid = this.mapProjection.ellipsoid;
  3881. }
  3882. duration = defaultValue(duration, 2.0);
  3883. this._transitioner.morphToColumbusView(duration, ellipsoid);
  3884. };
  3885. /**
  3886. * Asynchronously transitions the scene to 3D.
  3887. * @param {number} [duration=2.0] The amount of time, in seconds, for transition animations to complete.
  3888. */
  3889. Scene.prototype.morphTo3D = function (duration) {
  3890. let ellipsoid;
  3891. const globe = this.globe;
  3892. if (defined(globe)) {
  3893. ellipsoid = globe.ellipsoid;
  3894. } else {
  3895. ellipsoid = this.mapProjection.ellipsoid;
  3896. }
  3897. duration = defaultValue(duration, 2.0);
  3898. this._transitioner.morphTo3D(duration, ellipsoid);
  3899. };
  3900. function setTerrain(scene, terrain) {
  3901. // Cancel any in-progress terrain update
  3902. scene._removeTerrainProviderReadyListener =
  3903. scene._removeTerrainProviderReadyListener &&
  3904. scene._removeTerrainProviderReadyListener();
  3905. // If the terrain is already loaded, set it immediately
  3906. if (terrain.ready) {
  3907. if (defined(scene.globe)) {
  3908. scene.globe.terrainProvider = terrain.provider;
  3909. }
  3910. return;
  3911. }
  3912. // Otherwise, set a placeholder
  3913. scene.globe.terrainProvider = undefined;
  3914. scene._removeTerrainProviderReadyListener = terrain.readyEvent.addEventListener(
  3915. (provider) => {
  3916. if (defined(scene) && defined(scene.globe)) {
  3917. scene.globe.terrainProvider = provider;
  3918. }
  3919. scene._removeTerrainProviderReadyListener();
  3920. }
  3921. );
  3922. }
  3923. /**
  3924. * Update the terrain providing surface geometry for the globe.
  3925. *
  3926. * @param {Terrain} terrain The terrain provider async helper
  3927. * @returns {Terrain} terrain The terrain provider async helper
  3928. *
  3929. * @example
  3930. * // Use Cesium World Terrain
  3931. * scene.setTerrain(Cesium.Terrain.fromWorldTerrain());
  3932. *
  3933. * @example
  3934. * // Use a custom terrain provider
  3935. * const terrain = new Cesium.Terrain(Cesium.CesiumTerrainProvider.fromUrl("https://myTestTerrain.com"));
  3936. * scene.setTerrain(terrain);
  3937. *
  3938. * terrain.errorEvent.addEventListener(error => {
  3939. * alert(`Encountered an error while creating terrain! ${error}`);
  3940. * });
  3941. */
  3942. Scene.prototype.setTerrain = function (terrain) {
  3943. //>>includeStart('debug', pragmas.debug);
  3944. Check.typeOf.object("terrain", terrain);
  3945. //>>includeEnd('debug');
  3946. setTerrain(this, terrain);
  3947. return terrain;
  3948. };
  3949. /**
  3950. * Returns true if this object was destroyed; otherwise, false.
  3951. * <br /><br />
  3952. * If this object was destroyed, it should not be used; calling any function other than
  3953. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  3954. *
  3955. * @returns {boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
  3956. *
  3957. * @see Scene#destroy
  3958. */
  3959. Scene.prototype.isDestroyed = function () {
  3960. return false;
  3961. };
  3962. /**
  3963. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  3964. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  3965. * <br /><br />
  3966. * Once an object is destroyed, it should not be used; calling any function other than
  3967. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  3968. * assign the return value (<code>undefined</code>) to the object as done in the example.
  3969. *
  3970. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  3971. *
  3972. *
  3973. * @example
  3974. * scene = scene && scene.destroy();
  3975. *
  3976. * @see Scene#isDestroyed
  3977. */
  3978. Scene.prototype.destroy = function () {
  3979. this._tweens.removeAll();
  3980. this._computeEngine = this._computeEngine && this._computeEngine.destroy();
  3981. this._screenSpaceCameraController =
  3982. this._screenSpaceCameraController &&
  3983. this._screenSpaceCameraController.destroy();
  3984. this._deviceOrientationCameraController =
  3985. this._deviceOrientationCameraController &&
  3986. !this._deviceOrientationCameraController.isDestroyed() &&
  3987. this._deviceOrientationCameraController.destroy();
  3988. this._primitives = this._primitives && this._primitives.destroy();
  3989. this._groundPrimitives =
  3990. this._groundPrimitives && this._groundPrimitives.destroy();
  3991. this._globe = this._globe && this._globe.destroy();
  3992. this._removeTerrainProviderReadyListener =
  3993. this._removeTerrainProviderReadyListener &&
  3994. this._removeTerrainProviderReadyListener();
  3995. this.skyBox = this.skyBox && this.skyBox.destroy();
  3996. this.skyAtmosphere = this.skyAtmosphere && this.skyAtmosphere.destroy();
  3997. this._debugSphere = this._debugSphere && this._debugSphere.destroy();
  3998. this.sun = this.sun && this.sun.destroy();
  3999. this._sunPostProcess = this._sunPostProcess && this._sunPostProcess.destroy();
  4000. this._depthPlane = this._depthPlane && this._depthPlane.destroy();
  4001. this._transitioner = this._transitioner && this._transitioner.destroy();
  4002. this._debugFrustumPlanes =
  4003. this._debugFrustumPlanes && this._debugFrustumPlanes.destroy();
  4004. this._brdfLutGenerator =
  4005. this._brdfLutGenerator && this._brdfLutGenerator.destroy();
  4006. this._picking = this._picking && this._picking.destroy();
  4007. this._defaultView = this._defaultView && this._defaultView.destroy();
  4008. this._view = undefined;
  4009. if (this._removeCreditContainer) {
  4010. this._canvas.parentNode.removeChild(this._creditContainer);
  4011. }
  4012. this.postProcessStages =
  4013. this.postProcessStages && this.postProcessStages.destroy();
  4014. this._context = this._context && this._context.destroy();
  4015. this._frameState.creditDisplay =
  4016. this._frameState.creditDisplay && this._frameState.creditDisplay.destroy();
  4017. if (defined(this._performanceDisplay)) {
  4018. this._performanceDisplay =
  4019. this._performanceDisplay && this._performanceDisplay.destroy();
  4020. this._performanceContainer.parentNode.removeChild(
  4021. this._performanceContainer
  4022. );
  4023. }
  4024. this._removeRequestListenerCallback();
  4025. this._removeTaskProcessorListenerCallback();
  4026. for (let i = 0; i < this._removeGlobeCallbacks.length; ++i) {
  4027. this._removeGlobeCallbacks[i]();
  4028. }
  4029. this._removeGlobeCallbacks.length = 0;
  4030. return destroyObject(this);
  4031. };
  4032. export default Scene;