Cesium3DTileset.js 114 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210
  1. import ApproximateTerrainHeights from "../Core/ApproximateTerrainHeights.js";
  2. import Cartesian2 from "../Core/Cartesian2.js";
  3. import Cartesian3 from "../Core/Cartesian3.js";
  4. import Cartographic from "../Core/Cartographic.js";
  5. import Check from "../Core/Check.js";
  6. import clone from "../Core/clone.js";
  7. import Credit from "../Core/Credit.js";
  8. import defaultValue from "../Core/defaultValue.js";
  9. import defer from "../Core/defer.js";
  10. import defined from "../Core/defined.js";
  11. import deprecationWarning from "../Core/deprecationWarning.js";
  12. import destroyObject from "../Core/destroyObject.js";
  13. import DeveloperError from "../Core/DeveloperError.js";
  14. import Ellipsoid from "../Core/Ellipsoid.js";
  15. import Event from "../Core/Event.js";
  16. import ExperimentalFeatures from "../Core/ExperimentalFeatures.js";
  17. import ImageBasedLighting from "./ImageBasedLighting.js";
  18. import JulianDate from "../Core/JulianDate.js";
  19. import ManagedArray from "../Core/ManagedArray.js";
  20. import CesiumMath from "../Core/Math.js";
  21. import Matrix4 from "../Core/Matrix4.js";
  22. import Resource from "../Core/Resource.js";
  23. import RuntimeError from "../Core/RuntimeError.js";
  24. import Transforms from "../Core/Transforms.js";
  25. import ClearCommand from "../Renderer/ClearCommand.js";
  26. import Pass from "../Renderer/Pass.js";
  27. import RenderState from "../Renderer/RenderState.js";
  28. import Axis from "./Axis.js";
  29. import Cesium3DTile from "./Cesium3DTile.js";
  30. import Cesium3DTileColorBlendMode from "./Cesium3DTileColorBlendMode.js";
  31. import Cesium3DTileContentState from "./Cesium3DTileContentState.js";
  32. import Cesium3DTilesetMetadata from "./Cesium3DTilesetMetadata.js";
  33. import Cesium3DTileOptimizations from "./Cesium3DTileOptimizations.js";
  34. import Cesium3DTilePass from "./Cesium3DTilePass.js";
  35. import Cesium3DTileRefine from "./Cesium3DTileRefine.js";
  36. import Cesium3DTilesetCache from "./Cesium3DTilesetCache.js";
  37. import Cesium3DTilesetHeatmap from "./Cesium3DTilesetHeatmap.js";
  38. import Cesium3DTilesetStatistics from "./Cesium3DTilesetStatistics.js";
  39. import Cesium3DTileStyleEngine from "./Cesium3DTileStyleEngine.js";
  40. import ClippingPlaneCollection from "./ClippingPlaneCollection.js";
  41. import hasExtension from "./hasExtension.js";
  42. import ImplicitTileset from "./ImplicitTileset.js";
  43. import ImplicitTileCoordinates from "./ImplicitTileCoordinates.js";
  44. import LabelCollection from "./LabelCollection.js";
  45. import PointCloudEyeDomeLighting from "./PointCloudEyeDomeLighting.js";
  46. import PointCloudShading from "./PointCloudShading.js";
  47. import ResourceCache from "./ResourceCache.js";
  48. import SceneMode from "./SceneMode.js";
  49. import ShadowMode from "./ShadowMode.js";
  50. import SplitDirection from "./SplitDirection.js";
  51. import StencilConstants from "./StencilConstants.js";
  52. import TileBoundingRegion from "./TileBoundingRegion.js";
  53. import TileBoundingSphere from "./TileBoundingSphere.js";
  54. import TileOrientedBoundingBox from "./TileOrientedBoundingBox.js";
  55. /**
  56. * A {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification|3D Tiles tileset},
  57. * used for streaming massive heterogeneous 3D geospatial datasets.
  58. *
  59. * @alias Cesium3DTileset
  60. * @constructor
  61. *
  62. * @param {Object} options Object with the following properties:
  63. * @param {Resource|String|Promise<Resource>|Promise<String>} options.url The url to a tileset JSON file.
  64. * @param {Boolean} [options.show=true] Determines if the tileset will be shown.
  65. * @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] A 4x4 transformation matrix that transforms the tileset's root tile.
  66. * @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the tileset casts or receives shadows from light sources.
  67. * @param {Number} [options.maximumScreenSpaceError=16] The maximum screen space error used to drive level of detail refinement.
  68. * @param {Number} [options.maximumMemoryUsage=512] The maximum amount of memory in MB that can be used by the tileset.
  69. * @param {Boolean} [options.cullWithChildrenBounds=true] Optimization option. Whether to cull tiles using the union of their children bounding volumes.
  70. * @param {Boolean} [options.cullRequestsWhileMoving=true] Optimization option. Don't request tiles that will likely be unused when they come back because of the camera's movement. This optimization only applies to stationary tilesets.
  71. * @param {Number} [options.cullRequestsWhileMovingMultiplier=60.0] Optimization option. Multiplier used in culling requests while moving. Larger is more aggressive culling, smaller less aggressive culling.
  72. * @param {Boolean} [options.preloadWhenHidden=false] Preload tiles when <code>tileset.show</code> is <code>false</code>. Loads tiles as if the tileset is visible but does not render them.
  73. * @param {Boolean} [options.preloadFlightDestinations=true] Optimization option. Preload tiles at the camera's flight destination while the camera is in flight.
  74. * @param {Boolean} [options.preferLeaves=false] Optimization option. Prefer loading of leaves first.
  75. * @param {Boolean} [options.dynamicScreenSpaceError=false] Optimization option. Reduce the screen space error for tiles that are further away from the camera.
  76. * @param {Number} [options.dynamicScreenSpaceErrorDensity=0.00278] Density used to adjust the dynamic screen space error, similar to fog density.
  77. * @param {Number} [options.dynamicScreenSpaceErrorFactor=4.0] A factor used to increase the computed dynamic screen space error.
  78. * @param {Number} [options.dynamicScreenSpaceErrorHeightFalloff=0.25] A ratio of the tileset's height at which the density starts to falloff.
  79. * @param {Number} [options.progressiveResolutionHeightFraction=0.3] Optimization option. If between (0.0, 0.5], tiles at or above the screen space error for the reduced screen resolution of <code>progressiveResolutionHeightFraction*screenHeight</code> will be prioritized first. This can help get a quick layer of tiles down while full resolution tiles continue to load.
  80. * @param {Boolean} [options.foveatedScreenSpaceError=true] Optimization option. Prioritize loading tiles in the center of the screen by temporarily raising the screen space error for tiles around the edge of the screen. Screen space error returns to normal once all the tiles in the center of the screen as determined by the {@link Cesium3DTileset#foveatedConeSize} are loaded.
  81. * @param {Number} [options.foveatedConeSize=0.1] Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control the cone size that determines which tiles are deferred. Tiles that are inside this cone are loaded immediately. Tiles outside the cone are potentially deferred based on how far outside the cone they are and their screen space error. This is controlled by {@link Cesium3DTileset#foveatedInterpolationCallback} and {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation}. Setting this to 0.0 means the cone will be the line formed by the camera position and its view direction. Setting this to 1.0 means the cone encompasses the entire field of view of the camera, disabling the effect.
  82. * @param {Number} [options.foveatedMinimumScreenSpaceErrorRelaxation=0.0] Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control the starting screen space error relaxation for tiles outside the foveated cone. The screen space error will be raised starting with tileset value up to {@link Cesium3DTileset#maximumScreenSpaceError} based on the provided {@link Cesium3DTileset#foveatedInterpolationCallback}.
  83. * @param {Cesium3DTileset.foveatedInterpolationCallback} [options.foveatedInterpolationCallback=Math.lerp] Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control how much to raise the screen space error for tiles outside the foveated cone, interpolating between {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation} and {@link Cesium3DTileset#maximumScreenSpaceError}
  84. * @param {Number} [options.foveatedTimeDelay=0.2] Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control how long in seconds to wait after the camera stops moving before deferred tiles start loading in. This time delay prevents requesting tiles around the edges of the screen when the camera is moving. Setting this to 0.0 will immediately request all tiles in any given view.
  85. * @param {Boolean} [options.skipLevelOfDetail=false] Optimization option. Determines if level of detail skipping should be applied during the traversal.
  86. * @param {Number} [options.baseScreenSpaceError=1024] When <code>skipLevelOfDetail</code> is <code>true</code>, the screen space error that must be reached before skipping levels of detail.
  87. * @param {Number} [options.skipScreenSpaceErrorFactor=16] When <code>skipLevelOfDetail</code> is <code>true</code>, a multiplier defining the minimum screen space error to skip. Used in conjunction with <code>skipLevels</code> to determine which tiles to load.
  88. * @param {Number} [options.skipLevels=1] When <code>skipLevelOfDetail</code> is <code>true</code>, a constant defining the minimum number of levels to skip when loading tiles. When it is 0, no levels are skipped. Used in conjunction with <code>skipScreenSpaceErrorFactor</code> to determine which tiles to load.
  89. * @param {Boolean} [options.immediatelyLoadDesiredLevelOfDetail=false] When <code>skipLevelOfDetail</code> is <code>true</code>, only tiles that meet the maximum screen space error will ever be downloaded. Skipping factors are ignored and just the desired tiles are loaded.
  90. * @param {Boolean} [options.loadSiblings=false] When <code>skipLevelOfDetail</code> is <code>true</code>, determines whether siblings of visible tiles are always downloaded during traversal.
  91. * @param {ClippingPlaneCollection} [options.clippingPlanes] The {@link ClippingPlaneCollection} used to selectively disable rendering the tileset.
  92. * @param {ClassificationType} [options.classificationType] Determines whether terrain, 3D Tiles or both will be classified by this tileset. See {@link Cesium3DTileset#classificationType} for details about restrictions and limitations.
  93. * @param {Ellipsoid} [options.ellipsoid=Ellipsoid.WGS84] The ellipsoid determining the size and shape of the globe.
  94. * @param {Object} [options.pointCloudShading] Options for constructing a {@link PointCloudShading} object to control point attenuation based on geometric error and lighting.
  95. * @param {Cartesian3} [options.lightColor] The light color when shading models. When <code>undefined</code> the scene's light color is used instead.
  96. * @param {ImageBasedLighting} [options.imageBasedLighting] The properties for managing image-based lighting for this tileset.
  97. * @param {Cartesian2} [options.imageBasedLightingFactor=new Cartesian2(1.0, 1.0)] Scales the diffuse and specular image-based lighting from the earth, sky, atmosphere and star skybox. Deprecated in Cesium 1.92, will be removed in Cesium 1.94.
  98. * @param {Number} [options.luminanceAtZenith=0.2] The sun's luminance at the zenith in kilo candela per meter squared to use for this model's procedural environment map. Deprecated in Cesium 1.92, will be removed in Cesium 1.94.
  99. * @param {Cartesian3[]} [options.sphericalHarmonicCoefficients] The third order spherical harmonic coefficients used for the diffuse color of image-based lighting. Deprecated in Cesium 1.92, will be removed in Cesium 1.94.
  100. * @param {String} [options.specularEnvironmentMaps] A URL to a KTX2 file that contains a cube map of the specular lighting and the convoluted specular mipmaps. Deprecated in Cesium 1.92, will be removed in Cesium 1.94.
  101. * @param {Boolean} [options.backFaceCulling=true] Whether to cull back-facing geometry. When true, back face culling is determined by the glTF material's doubleSided property; when false, back face culling is disabled.
  102. * @param {Boolean} [options.showOutline=true] Whether to display the outline for models using the {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/CESIUM_primitive_outline|CESIUM_primitive_outline} extension. When true, outlines are displayed. When false, outlines are not displayed.
  103. * @param {Boolean} [options.vectorClassificationOnly=false] Indicates that only the tileset's vector tiles should be used for classification.
  104. * @param {Boolean} [options.vectorKeepDecodedPositions=false] Whether vector tiles should keep decoded positions in memory. This is used with {@link Cesium3DTileFeature.getPolylinePositions}.
  105. * @param {String|Number} [options.featureIdLabel="featureId_0"] Label of the feature ID set to use for picking and styling. For EXT_mesh_features, this is the feature ID's label property, or "featureId_N" (where N is the index in the featureIds array) when not specified. EXT_feature_metadata did not have a label field, so such feature ID sets are always labeled "featureId_N" where N is the index in the list of all feature Ids, where feature ID attributes are listed before feature ID textures. If featureIdLabel is an integer N, it is converted to the string "featureId_N" automatically. If both per-primitive and per-instance feature IDs are present, the instance feature IDs take priority.
  106. * @param {String|Number} [options.instanceFeatureIdLabel="instanceFeatureId_0"] Label of the instance feature ID set used for picking and styling. If instanceFeatureIdLabel is set to an integer N, it is converted to the string "instanceFeatureId_N" automatically. If both per-primitive and per-instance feature IDs are present, the instance feature IDs take priority.
  107. * @param {Boolean} [options.showCreditsOnScreen=false] Whether to display the credits of this tileset on screen.
  108. * @param {SplitDirection} [options.splitDirection=SplitDirection.NONE] The {@link SplitDirection} split to apply to this tileset.
  109. * @param {String} [options.debugHeatmapTilePropertyName] The tile variable to colorize as a heatmap. All rendered tiles will be colorized relative to each other's specified variable value.
  110. * @param {Boolean} [options.debugFreezeFrame=false] For debugging only. Determines if only the tiles from last frame should be used for rendering.
  111. * @param {Boolean} [options.debugColorizeTiles=false] For debugging only. When true, assigns a random color to each tile.
  112. * @param {Boolean} [options.debugWireframe=false] For debugging only. When true, render's each tile's content as a wireframe.
  113. * @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. When true, renders the bounding volume for each tile.
  114. * @param {Boolean} [options.debugShowContentBoundingVolume=false] For debugging only. When true, renders the bounding volume for each tile's content.
  115. * @param {Boolean} [options.debugShowViewerRequestVolume=false] For debugging only. When true, renders the viewer request volume for each tile.
  116. * @param {Boolean} [options.debugShowGeometricError=false] For debugging only. When true, draws labels to indicate the geometric error of each tile.
  117. * @param {Boolean} [options.debugShowRenderingStatistics=false] For debugging only. When true, draws labels to indicate the number of commands, points, triangles and features for each tile.
  118. * @param {Boolean} [options.debugShowMemoryUsage=false] For debugging only. When true, draws labels to indicate the texture and geometry memory in megabytes used by each tile.
  119. * @param {Boolean} [options.debugShowUrl=false] For debugging only. When true, draws labels to indicate the url of each tile.
  120. *
  121. * @exception {DeveloperError} The tileset must be 3D Tiles version 0.0 or 1.0.
  122. *
  123. * @example
  124. * const tileset = scene.primitives.add(new Cesium.Cesium3DTileset({
  125. * url : 'http://localhost:8002/tilesets/Seattle/tileset.json'
  126. * }));
  127. *
  128. * @example
  129. * // Common setting for the skipLevelOfDetail optimization
  130. * const tileset = scene.primitives.add(new Cesium.Cesium3DTileset({
  131. * url : 'http://localhost:8002/tilesets/Seattle/tileset.json',
  132. * skipLevelOfDetail : true,
  133. * baseScreenSpaceError : 1024,
  134. * skipScreenSpaceErrorFactor : 16,
  135. * skipLevels : 1,
  136. * immediatelyLoadDesiredLevelOfDetail : false,
  137. * loadSiblings : false,
  138. * cullWithChildrenBounds : true
  139. * }));
  140. *
  141. * @example
  142. * // Common settings for the dynamicScreenSpaceError optimization
  143. * const tileset = scene.primitives.add(new Cesium.Cesium3DTileset({
  144. * url : 'http://localhost:8002/tilesets/Seattle/tileset.json',
  145. * dynamicScreenSpaceError : true,
  146. * dynamicScreenSpaceErrorDensity : 0.00278,
  147. * dynamicScreenSpaceErrorFactor : 4.0,
  148. * dynamicScreenSpaceErrorHeightFalloff : 0.25
  149. * }));
  150. *
  151. * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification|3D Tiles specification}
  152. */
  153. function Cesium3DTileset(options) {
  154. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  155. //>>includeStart('debug', pragmas.debug);
  156. Check.defined("options.url", options.url);
  157. //>>includeEnd('debug');
  158. this._url = undefined;
  159. this._basePath = undefined;
  160. this._root = undefined;
  161. this._resource = undefined;
  162. this._asset = undefined; // Metadata for the entire tileset
  163. this._properties = undefined; // Metadata for per-model/point/etc properties
  164. this._geometricError = undefined; // Geometric error when the tree is not rendered at all
  165. this._extensionsUsed = undefined;
  166. this._extensions = undefined;
  167. this._gltfUpAxis = undefined;
  168. this._cache = new Cesium3DTilesetCache();
  169. this._processingQueue = [];
  170. this._selectedTiles = [];
  171. this._emptyTiles = [];
  172. this._requestedTiles = [];
  173. this._selectedTilesToStyle = [];
  174. this._loadTimestamp = undefined;
  175. this._timeSinceLoad = 0.0;
  176. this._updatedVisibilityFrame = 0;
  177. this._updatedModelMatrixFrame = 0;
  178. this._modelMatrixChanged = false;
  179. this._previousModelMatrix = undefined;
  180. this._extras = undefined;
  181. this._credits = undefined;
  182. this._showCreditsOnScreen = defaultValue(options.showCreditsOnScreen, false);
  183. this._cullWithChildrenBounds = defaultValue(
  184. options.cullWithChildrenBounds,
  185. true
  186. );
  187. this._allTilesAdditive = true;
  188. this._hasMixedContent = false;
  189. this._stencilClearCommand = undefined;
  190. this._backfaceCommands = new ManagedArray();
  191. this._maximumScreenSpaceError = defaultValue(
  192. options.maximumScreenSpaceError,
  193. 16
  194. );
  195. this._maximumMemoryUsage = defaultValue(options.maximumMemoryUsage, 512);
  196. this._styleEngine = new Cesium3DTileStyleEngine();
  197. this._modelMatrix = defined(options.modelMatrix)
  198. ? Matrix4.clone(options.modelMatrix)
  199. : Matrix4.clone(Matrix4.IDENTITY);
  200. this._statistics = new Cesium3DTilesetStatistics();
  201. this._statisticsLast = new Cesium3DTilesetStatistics();
  202. this._statisticsPerPass = new Array(Cesium3DTilePass.NUMBER_OF_PASSES);
  203. for (let i = 0; i < Cesium3DTilePass.NUMBER_OF_PASSES; ++i) {
  204. this._statisticsPerPass[i] = new Cesium3DTilesetStatistics();
  205. }
  206. this._requestedTilesInFlight = [];
  207. this._maximumPriority = {
  208. foveatedFactor: -Number.MAX_VALUE,
  209. depth: -Number.MAX_VALUE,
  210. distance: -Number.MAX_VALUE,
  211. reverseScreenSpaceError: -Number.MAX_VALUE,
  212. };
  213. this._minimumPriority = {
  214. foveatedFactor: Number.MAX_VALUE,
  215. depth: Number.MAX_VALUE,
  216. distance: Number.MAX_VALUE,
  217. reverseScreenSpaceError: Number.MAX_VALUE,
  218. };
  219. this._heatmap = new Cesium3DTilesetHeatmap(
  220. options.debugHeatmapTilePropertyName
  221. );
  222. /**
  223. * Optimization option. Don't request tiles that will likely be unused when they come back because of the camera's movement. This optimization only applies to stationary tilesets.
  224. *
  225. * @type {Boolean}
  226. * @default true
  227. */
  228. this.cullRequestsWhileMoving = defaultValue(
  229. options.cullRequestsWhileMoving,
  230. true
  231. );
  232. this._cullRequestsWhileMoving = false;
  233. /**
  234. * Optimization option. Multiplier used in culling requests while moving. Larger is more aggressive culling, smaller less aggressive culling.
  235. *
  236. * @type {Number}
  237. * @default 60.0
  238. */
  239. this.cullRequestsWhileMovingMultiplier = defaultValue(
  240. options.cullRequestsWhileMovingMultiplier,
  241. 60.0
  242. );
  243. /**
  244. * Optimization option. If between (0.0, 0.5], tiles at or above the screen space error for the reduced screen resolution of <code>progressiveResolutionHeightFraction*screenHeight</code> will be prioritized first. This can help get a quick layer of tiles down while full resolution tiles continue to load.
  245. *
  246. * @type {Number}
  247. * @default 0.3
  248. */
  249. this.progressiveResolutionHeightFraction = CesiumMath.clamp(
  250. defaultValue(options.progressiveResolutionHeightFraction, 0.3),
  251. 0.0,
  252. 0.5
  253. );
  254. /**
  255. * Optimization option. Prefer loading of leaves first.
  256. *
  257. * @type {Boolean}
  258. * @default false
  259. */
  260. this.preferLeaves = defaultValue(options.preferLeaves, false);
  261. this._tilesLoaded = false;
  262. this._initialTilesLoaded = false;
  263. this._tileDebugLabels = undefined;
  264. this._readyPromise = defer();
  265. this._classificationType = options.classificationType;
  266. this._ellipsoid = defaultValue(options.ellipsoid, Ellipsoid.WGS84);
  267. this._initialClippingPlanesOriginMatrix = Matrix4.IDENTITY; // Computed from the tileset JSON.
  268. this._clippingPlanesOriginMatrix = undefined; // Combines the above with any run-time transforms.
  269. this._clippingPlanesOriginMatrixDirty = true;
  270. this._vectorClassificationOnly = defaultValue(
  271. options.vectorClassificationOnly,
  272. false
  273. );
  274. this._vectorKeepDecodedPositions = defaultValue(
  275. options.vectorKeepDecodedPositions,
  276. false
  277. );
  278. /**
  279. * Preload tiles when <code>tileset.show</code> is <code>false</code>. Loads tiles as if the tileset is visible but does not render them.
  280. *
  281. * @type {Boolean}
  282. * @default false
  283. */
  284. this.preloadWhenHidden = defaultValue(options.preloadWhenHidden, false);
  285. /**
  286. * Optimization option. Fetch tiles at the camera's flight destination while the camera is in flight.
  287. *
  288. * @type {Boolean}
  289. * @default true
  290. */
  291. this.preloadFlightDestinations = defaultValue(
  292. options.preloadFlightDestinations,
  293. true
  294. );
  295. this._pass = undefined; // Cesium3DTilePass
  296. /**
  297. * Optimization option. Whether the tileset should refine based on a dynamic screen space error. Tiles that are further
  298. * away will be rendered with lower detail than closer tiles. This improves performance by rendering fewer
  299. * tiles and making less requests, but may result in a slight drop in visual quality for tiles in the distance.
  300. * The algorithm is biased towards "street views" where the camera is close to the ground plane of the tileset and looking
  301. * at the horizon. In addition results are more accurate for tightly fitting bounding volumes like box and region.
  302. *
  303. * @type {Boolean}
  304. * @default false
  305. */
  306. this.dynamicScreenSpaceError = defaultValue(
  307. options.dynamicScreenSpaceError,
  308. false
  309. );
  310. /**
  311. * Optimization option. Prioritize loading tiles in the center of the screen by temporarily raising the
  312. * screen space error for tiles around the edge of the screen. Screen space error returns to normal once all
  313. * the tiles in the center of the screen as determined by the {@link Cesium3DTileset#foveatedConeSize} are loaded.
  314. *
  315. * @type {Boolean}
  316. * @default true
  317. */
  318. this.foveatedScreenSpaceError = defaultValue(
  319. options.foveatedScreenSpaceError,
  320. true
  321. );
  322. this._foveatedConeSize = defaultValue(options.foveatedConeSize, 0.1);
  323. this._foveatedMinimumScreenSpaceErrorRelaxation = defaultValue(
  324. options.foveatedMinimumScreenSpaceErrorRelaxation,
  325. 0.0
  326. );
  327. /**
  328. * Gets or sets a callback to control how much to raise the screen space error for tiles outside the foveated cone,
  329. * interpolating between {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation} and {@link Cesium3DTileset#maximumScreenSpaceError}.
  330. *
  331. * @type {Cesium3DTileset.foveatedInterpolationCallback}
  332. */
  333. this.foveatedInterpolationCallback = defaultValue(
  334. options.foveatedInterpolationCallback,
  335. CesiumMath.lerp
  336. );
  337. /**
  338. * Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control
  339. * how long in seconds to wait after the camera stops moving before deferred tiles start loading in.
  340. * This time delay prevents requesting tiles around the edges of the screen when the camera is moving.
  341. * Setting this to 0.0 will immediately request all tiles in any given view.
  342. *
  343. * @type {Number}
  344. * @default 0.2
  345. */
  346. this.foveatedTimeDelay = defaultValue(options.foveatedTimeDelay, 0.2);
  347. /**
  348. * A scalar that determines the density used to adjust the dynamic screen space error, similar to {@link Fog}. Increasing this
  349. * value has the effect of increasing the maximum screen space error for all tiles, but in a non-linear fashion.
  350. * The error starts at 0.0 and increases exponentially until a midpoint is reached, and then approaches 1.0 asymptotically.
  351. * This has the effect of keeping high detail in the closer tiles and lower detail in the further tiles, with all tiles
  352. * beyond a certain distance all roughly having an error of 1.0.
  353. * <p>
  354. * The dynamic error is in the range [0.0, 1.0) and is multiplied by <code>dynamicScreenSpaceErrorFactor</code> to produce the
  355. * final dynamic error. This dynamic error is then subtracted from the tile's actual screen space error.
  356. * </p>
  357. * <p>
  358. * Increasing <code>dynamicScreenSpaceErrorDensity</code> has the effect of moving the error midpoint closer to the camera.
  359. * It is analogous to moving fog closer to the camera.
  360. * </p>
  361. *
  362. * @type {Number}
  363. * @default 0.00278
  364. */
  365. this.dynamicScreenSpaceErrorDensity = 0.00278;
  366. /**
  367. * A factor used to increase the screen space error of tiles for dynamic screen space error. As this value increases less tiles
  368. * are requested for rendering and tiles in the distance will have lower detail. If set to zero, the feature will be disabled.
  369. *
  370. * @type {Number}
  371. * @default 4.0
  372. */
  373. this.dynamicScreenSpaceErrorFactor = 4.0;
  374. /**
  375. * A ratio of the tileset's height at which the density starts to falloff. If the camera is below this height the
  376. * full computed density is applied, otherwise the density falls off. This has the effect of higher density at
  377. * street level views.
  378. * <p>
  379. * Valid values are between 0.0 and 1.0.
  380. * </p>
  381. *
  382. * @type {Number}
  383. * @default 0.25
  384. */
  385. this.dynamicScreenSpaceErrorHeightFalloff = 0.25;
  386. this._dynamicScreenSpaceErrorComputedDensity = 0.0; // Updated based on the camera position and direction
  387. /**
  388. * Determines whether the tileset casts or receives shadows from light sources.
  389. * <p>
  390. * Enabling shadows has a performance impact. A tileset that casts shadows must be rendered twice, once from the camera and again from the light's point of view.
  391. * </p>
  392. * <p>
  393. * Shadows are rendered only when {@link Viewer#shadows} is <code>true</code>.
  394. * </p>
  395. *
  396. * @type {ShadowMode}
  397. * @default ShadowMode.ENABLED
  398. */
  399. this.shadows = defaultValue(options.shadows, ShadowMode.ENABLED);
  400. /**
  401. * Determines if the tileset will be shown.
  402. *
  403. * @type {Boolean}
  404. * @default true
  405. */
  406. this.show = defaultValue(options.show, true);
  407. /**
  408. * Defines how per-feature colors set from the Cesium API or declarative styling blend with the source colors from
  409. * the original feature, e.g. glTF material or per-point color in the tile.
  410. *
  411. * @type {Cesium3DTileColorBlendMode}
  412. * @default Cesium3DTileColorBlendMode.HIGHLIGHT
  413. */
  414. this.colorBlendMode = Cesium3DTileColorBlendMode.HIGHLIGHT;
  415. /**
  416. * Defines the value used to linearly interpolate between the source color and feature color when the {@link Cesium3DTileset#colorBlendMode} is <code>MIX</code>.
  417. * A value of 0.0 results in the source color while a value of 1.0 results in the feature color, with any value in-between
  418. * resulting in a mix of the source color and feature color.
  419. *
  420. * @type {Number}
  421. * @default 0.5
  422. */
  423. this.colorBlendAmount = 0.5;
  424. this._pointCloudShading = new PointCloudShading(options.pointCloudShading);
  425. this._pointCloudEyeDomeLighting = new PointCloudEyeDomeLighting();
  426. /**
  427. * The event fired to indicate progress of loading new tiles. This event is fired when a new tile
  428. * is requested, when a requested tile is finished downloading, and when a downloaded tile has been
  429. * processed and is ready to render.
  430. * <p>
  431. * The number of pending tile requests, <code>numberOfPendingRequests</code>, and number of tiles
  432. * processing, <code>numberOfTilesProcessing</code> are passed to the event listener.
  433. * </p>
  434. * <p>
  435. * This event is fired at the end of the frame after the scene is rendered.
  436. * </p>
  437. *
  438. * @type {Event}
  439. * @default new Event()
  440. *
  441. * @example
  442. * tileset.loadProgress.addEventListener(function(numberOfPendingRequests, numberOfTilesProcessing) {
  443. * if ((numberOfPendingRequests === 0) && (numberOfTilesProcessing === 0)) {
  444. * console.log('Stopped loading');
  445. * return;
  446. * }
  447. *
  448. * console.log('Loading: requests: ' + numberOfPendingRequests + ', processing: ' + numberOfTilesProcessing);
  449. * });
  450. */
  451. this.loadProgress = new Event();
  452. /**
  453. * The event fired to indicate that all tiles that meet the screen space error this frame are loaded. The tileset
  454. * is completely loaded for this view.
  455. * <p>
  456. * This event is fired at the end of the frame after the scene is rendered.
  457. * </p>
  458. *
  459. * @type {Event}
  460. * @default new Event()
  461. *
  462. * @example
  463. * tileset.allTilesLoaded.addEventListener(function() {
  464. * console.log('All tiles are loaded');
  465. * });
  466. *
  467. * @see Cesium3DTileset#tilesLoaded
  468. */
  469. this.allTilesLoaded = new Event();
  470. /**
  471. * The event fired to indicate that all tiles that meet the screen space error this frame are loaded. This event
  472. * is fired once when all tiles in the initial view are loaded.
  473. * <p>
  474. * This event is fired at the end of the frame after the scene is rendered.
  475. * </p>
  476. *
  477. * @type {Event}
  478. * @default new Event()
  479. *
  480. * @example
  481. * tileset.initialTilesLoaded.addEventListener(function() {
  482. * console.log('Initial tiles are loaded');
  483. * });
  484. *
  485. * @see Cesium3DTileset#allTilesLoaded
  486. */
  487. this.initialTilesLoaded = new Event();
  488. /**
  489. * The event fired to indicate that a tile's content was loaded.
  490. * <p>
  491. * The loaded {@link Cesium3DTile} is passed to the event listener.
  492. * </p>
  493. * <p>
  494. * This event is fired during the tileset traversal while the frame is being rendered
  495. * so that updates to the tile take effect in the same frame. Do not create or modify
  496. * Cesium entities or primitives during the event listener.
  497. * </p>
  498. *
  499. * @type {Event}
  500. * @default new Event()
  501. *
  502. * @example
  503. * tileset.tileLoad.addEventListener(function(tile) {
  504. * console.log('A tile was loaded.');
  505. * });
  506. */
  507. this.tileLoad = new Event();
  508. /**
  509. * The event fired to indicate that a tile's content was unloaded.
  510. * <p>
  511. * The unloaded {@link Cesium3DTile} is passed to the event listener.
  512. * </p>
  513. * <p>
  514. * This event is fired immediately before the tile's content is unloaded while the frame is being
  515. * rendered so that the event listener has access to the tile's content. Do not create
  516. * or modify Cesium entities or primitives during the event listener.
  517. * </p>
  518. *
  519. * @type {Event}
  520. * @default new Event()
  521. *
  522. * @example
  523. * tileset.tileUnload.addEventListener(function(tile) {
  524. * console.log('A tile was unloaded from the cache.');
  525. * });
  526. *
  527. * @see Cesium3DTileset#maximumMemoryUsage
  528. * @see Cesium3DTileset#trimLoadedTiles
  529. */
  530. this.tileUnload = new Event();
  531. /**
  532. * The event fired to indicate that a tile's content failed to load.
  533. * <p>
  534. * If there are no event listeners, error messages will be logged to the console.
  535. * </p>
  536. * <p>
  537. * The error object passed to the listener contains two properties:
  538. * <ul>
  539. * <li><code>url</code>: the url of the failed tile.</li>
  540. * <li><code>message</code>: the error message.</li>
  541. * </ul>
  542. * <p>
  543. * If multiple contents are present, this event is raised once per inner content with errors.
  544. * </p>
  545. *
  546. * @type {Event}
  547. * @default new Event()
  548. *
  549. * @example
  550. * tileset.tileFailed.addEventListener(function(error) {
  551. * console.log('An error occurred loading tile: ' + error.url);
  552. * console.log('Error: ' + error.message);
  553. * });
  554. */
  555. this.tileFailed = new Event();
  556. /**
  557. * This event fires once for each visible tile in a frame. This can be used to manually
  558. * style a tileset.
  559. * <p>
  560. * The visible {@link Cesium3DTile} is passed to the event listener.
  561. * </p>
  562. * <p>
  563. * This event is fired during the tileset traversal while the frame is being rendered
  564. * so that updates to the tile take effect in the same frame. Do not create or modify
  565. * Cesium entities or primitives during the event listener.
  566. * </p>
  567. *
  568. * @type {Event}
  569. * @default new Event()
  570. *
  571. * @example
  572. * tileset.tileVisible.addEventListener(function(tile) {
  573. * if (tile.content instanceof Cesium.Batched3DModel3DTileContent) {
  574. * console.log('A Batched 3D Model tile is visible.');
  575. * }
  576. * });
  577. *
  578. * @example
  579. * // Apply a red style and then manually set random colors for every other feature when the tile becomes visible.
  580. * tileset.style = new Cesium.Cesium3DTileStyle({
  581. * color : 'color("red")'
  582. * });
  583. * tileset.tileVisible.addEventListener(function(tile) {
  584. * const content = tile.content;
  585. * const featuresLength = content.featuresLength;
  586. * for (let i = 0; i < featuresLength; i+=2) {
  587. * content.getFeature(i).color = Cesium.Color.fromRandom();
  588. * }
  589. * });
  590. */
  591. this.tileVisible = new Event();
  592. /**
  593. * Optimization option. Determines if level of detail skipping should be applied during the traversal.
  594. * <p>
  595. * The common strategy for replacement-refinement traversal is to store all levels of the tree in memory and require
  596. * all children to be loaded before the parent can refine. With this optimization levels of the tree can be skipped
  597. * entirely and children can be rendered alongside their parents. The tileset requires significantly less memory when
  598. * using this optimization.
  599. * </p>
  600. *
  601. * @type {Boolean}
  602. * @default false
  603. */
  604. this.skipLevelOfDetail = defaultValue(options.skipLevelOfDetail, false);
  605. this._skipLevelOfDetail = this.skipLevelOfDetail;
  606. this._disableSkipLevelOfDetail = false;
  607. /**
  608. * The screen space error that must be reached before skipping levels of detail.
  609. * <p>
  610. * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
  611. * </p>
  612. *
  613. * @type {Number}
  614. * @default 1024
  615. */
  616. this.baseScreenSpaceError = defaultValue(options.baseScreenSpaceError, 1024);
  617. /**
  618. * Multiplier defining the minimum screen space error to skip.
  619. * For example, if a tile has screen space error of 100, no tiles will be loaded unless they
  620. * are leaves or have a screen space error <code><= 100 / skipScreenSpaceErrorFactor</code>.
  621. * <p>
  622. * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
  623. * </p>
  624. *
  625. * @type {Number}
  626. * @default 16
  627. */
  628. this.skipScreenSpaceErrorFactor = defaultValue(
  629. options.skipScreenSpaceErrorFactor,
  630. 16
  631. );
  632. /**
  633. * Constant defining the minimum number of levels to skip when loading tiles. When it is 0, no levels are skipped.
  634. * For example, if a tile is level 1, no tiles will be loaded unless they are at level greater than 2.
  635. * <p>
  636. * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
  637. * </p>
  638. *
  639. * @type {Number}
  640. * @default 1
  641. */
  642. this.skipLevels = defaultValue(options.skipLevels, 1);
  643. /**
  644. * When true, only tiles that meet the maximum screen space error will ever be downloaded.
  645. * Skipping factors are ignored and just the desired tiles are loaded.
  646. * <p>
  647. * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
  648. * </p>
  649. *
  650. * @type {Boolean}
  651. * @default false
  652. */
  653. this.immediatelyLoadDesiredLevelOfDetail = defaultValue(
  654. options.immediatelyLoadDesiredLevelOfDetail,
  655. false
  656. );
  657. /**
  658. * Determines whether siblings of visible tiles are always downloaded during traversal.
  659. * This may be useful for ensuring that tiles are already available when the viewer turns left/right.
  660. * <p>
  661. * Only used when {@link Cesium3DTileset#skipLevelOfDetail} is <code>true</code>.
  662. * </p>
  663. *
  664. * @type {Boolean}
  665. * @default false
  666. */
  667. this.loadSiblings = defaultValue(options.loadSiblings, false);
  668. this._clippingPlanes = undefined;
  669. this.clippingPlanes = options.clippingPlanes;
  670. const hasIndividualIBLParameters =
  671. defined(options.imageBasedLightingFactor) ||
  672. defined(options.luminanceAtZenith) ||
  673. defined(options.sphericalHarmonicCoefficients) ||
  674. defined(options.specularEnvironmentMaps);
  675. if (defined(options.imageBasedLighting)) {
  676. this._imageBasedLighting = options.imageBasedLighting;
  677. this._shouldDestroyImageBasedLighting = false;
  678. } else if (hasIndividualIBLParameters) {
  679. deprecationWarning(
  680. "ImageBasedLightingConstructor",
  681. "Individual image-based lighting parameters were deprecated in Cesium 1.92. They will be removed in version 1.94. Use options.imageBasedLighting instead."
  682. );
  683. // Create image-based lighting from the old constructor parameters.
  684. this._imageBasedLighting = new ImageBasedLighting({
  685. imageBasedLightingFactor: options.imageBasedLightingFactor,
  686. luminanceAtZenith: options.luminanceAtZenith,
  687. sphericalHarmonicCoefficients: options.sphericalHarmonicCoefficients,
  688. specularEnvironmentMaps: options.specularEnvironmentMaps,
  689. });
  690. this._shouldDestroyImageBasedLighting = true;
  691. } else {
  692. this._imageBasedLighting = new ImageBasedLighting();
  693. this._shouldDestroyImageBasedLighting = true;
  694. }
  695. /**
  696. * The light color when shading models. When <code>undefined</code> the scene's light color is used instead.
  697. * <p>
  698. * For example, disabling additional light sources by setting <code>model.imageBasedLighting.imageBasedLightingFactor = new Cartesian2(0.0, 0.0)</code> will make the
  699. * model much darker. Here, increasing the intensity of the light source will make the model brighter.
  700. * </p>
  701. *
  702. * @type {Cartesian3}
  703. * @default undefined
  704. */
  705. this.lightColor = options.lightColor;
  706. /**
  707. * Whether to cull back-facing geometry. When true, back face culling is determined
  708. * by the glTF material's doubleSided property; when false, back face culling is disabled.
  709. *
  710. * @type {Boolean}
  711. * @default true
  712. */
  713. this.backFaceCulling = defaultValue(options.backFaceCulling, true);
  714. /**
  715. * Whether to display the outline for models using the
  716. * {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/CESIUM_primitive_outline|CESIUM_primitive_outline} extension.
  717. * When true, outlines are displayed. When false, outlines are not displayed.
  718. *
  719. * @type {Boolean}
  720. * @readonly
  721. *
  722. * @default true
  723. */
  724. this.showOutline = defaultValue(options.showOutline, true);
  725. /**
  726. * The {@link SplitDirection} to apply to this tileset.
  727. *
  728. * @type {SplitDirection}
  729. * @default {@link SplitDirection.NONE}
  730. */
  731. this.splitDirection = defaultValue(
  732. options.splitDirection,
  733. SplitDirection.NONE
  734. );
  735. /**
  736. * This property is for debugging only; it is not optimized for production use.
  737. * <p>
  738. * Determines if only the tiles from last frame should be used for rendering. This
  739. * effectively "freezes" the tileset to the previous frame so it is possible to zoom
  740. * out and see what was rendered.
  741. * </p>
  742. *
  743. * @type {Boolean}
  744. * @default false
  745. */
  746. this.debugFreezeFrame = defaultValue(options.debugFreezeFrame, false);
  747. /**
  748. * This property is for debugging only; it is not optimized for production use.
  749. * <p>
  750. * When true, assigns a random color to each tile. This is useful for visualizing
  751. * what features belong to what tiles, especially with additive refinement where features
  752. * from parent tiles may be interleaved with features from child tiles.
  753. * </p>
  754. *
  755. * @type {Boolean}
  756. * @default false
  757. */
  758. this.debugColorizeTiles = defaultValue(options.debugColorizeTiles, false);
  759. /**
  760. * This property is for debugging only; it is not optimized for production use.
  761. * <p>
  762. * When true, renders each tile's content as a wireframe.
  763. * </p>
  764. *
  765. * @type {Boolean}
  766. * @default false
  767. */
  768. this.debugWireframe = defaultValue(options.debugWireframe, false);
  769. /**
  770. * This property is for debugging only; it is not optimized for production use.
  771. * <p>
  772. * When true, renders the bounding volume for each visible tile. The bounding volume is
  773. * white if the tile has a content bounding volume or is empty; otherwise, it is red. Tiles that don't meet the
  774. * screen space error and are still refining to their descendants are yellow.
  775. * </p>
  776. *
  777. * @type {Boolean}
  778. * @default false
  779. */
  780. this.debugShowBoundingVolume = defaultValue(
  781. options.debugShowBoundingVolume,
  782. false
  783. );
  784. /**
  785. * This property is for debugging only; it is not optimized for production use.
  786. * <p>
  787. * When true, renders the bounding volume for each visible tile's content. The bounding volume is
  788. * blue if the tile has a content bounding volume; otherwise it is red.
  789. * </p>
  790. *
  791. * @type {Boolean}
  792. * @default false
  793. */
  794. this.debugShowContentBoundingVolume = defaultValue(
  795. options.debugShowContentBoundingVolume,
  796. false
  797. );
  798. /**
  799. * This property is for debugging only; it is not optimized for production use.
  800. * <p>
  801. * When true, renders the viewer request volume for each tile.
  802. * </p>
  803. *
  804. * @type {Boolean}
  805. * @default false
  806. */
  807. this.debugShowViewerRequestVolume = defaultValue(
  808. options.debugShowViewerRequestVolume,
  809. false
  810. );
  811. this._tileDebugLabels = undefined;
  812. this.debugPickedTileLabelOnly = false;
  813. this.debugPickedTile = undefined;
  814. this.debugPickPosition = undefined;
  815. /**
  816. * This property is for debugging only; it is not optimized for production use.
  817. * <p>
  818. * When true, draws labels to indicate the geometric error of each tile.
  819. * </p>
  820. *
  821. * @type {Boolean}
  822. * @default false
  823. */
  824. this.debugShowGeometricError = defaultValue(
  825. options.debugShowGeometricError,
  826. false
  827. );
  828. /**
  829. * This property is for debugging only; it is not optimized for production use.
  830. * <p>
  831. * When true, draws labels to indicate the number of commands, points, triangles and features of each tile.
  832. * </p>
  833. *
  834. * @type {Boolean}
  835. * @default false
  836. */
  837. this.debugShowRenderingStatistics = defaultValue(
  838. options.debugShowRenderingStatistics,
  839. false
  840. );
  841. /**
  842. * This property is for debugging only; it is not optimized for production use.
  843. * <p>
  844. * When true, draws labels to indicate the geometry and texture memory usage of each tile.
  845. * </p>
  846. *
  847. * @type {Boolean}
  848. * @default false
  849. */
  850. this.debugShowMemoryUsage = defaultValue(options.debugShowMemoryUsage, false);
  851. /**
  852. * This property is for debugging only; it is not optimized for production use.
  853. * <p>
  854. * When true, draws labels to indicate the url of each tile.
  855. * </p>
  856. *
  857. * @type {Boolean}
  858. * @default false
  859. */
  860. this.debugShowUrl = defaultValue(options.debugShowUrl, false);
  861. /**
  862. * Function for examining vector lines as they are being streamed.
  863. *
  864. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  865. *
  866. * @type {Function}
  867. */
  868. this.examineVectorLinesFunction = undefined;
  869. // this is the underlying Cesium3DTileMetadata object, whether it came from
  870. // the 3DTILES_metadata extension or a 3D Tiles 1.1 tileset JSON. Getters
  871. // like tileset.metadata and tileset.schema will delegate to this object.
  872. this._metadataExtension = undefined;
  873. this._customShader = options.customShader;
  874. /**
  875. * If true, {@link ModelExperimental} will be used instead of {@link Model}
  876. * for each tile with a glTF or 3D Tiles 1.0 content (where applicable).
  877. * <p>
  878. * The value defaults to {@link ExperimentalFeatures.enableModelExperimental}.
  879. * </p>
  880. *
  881. * @memberof Cesium3DTileset.prototype
  882. * @type {Boolean}
  883. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  884. */
  885. this.enableModelExperimental = defaultValue(
  886. options.enableModelExperimental,
  887. ExperimentalFeatures.enableModelExperimental
  888. );
  889. let featureIdLabel = defaultValue(options.featureIdLabel, "featureId_0");
  890. if (typeof featureIdLabel === "number") {
  891. featureIdLabel = `featureId_${featureIdLabel}`;
  892. }
  893. this._featureIdLabel = featureIdLabel;
  894. let instanceFeatureIdLabel = defaultValue(
  895. options.instanceFeatureIdLabel,
  896. "instanceFeatureId_0"
  897. );
  898. if (typeof instanceFeatureIdLabel === "number") {
  899. instanceFeatureIdLabel = `instanceFeatureId_${instanceFeatureIdLabel}`;
  900. }
  901. this._instanceFeatureIdLabel = instanceFeatureIdLabel;
  902. this._schemaLoader = undefined;
  903. const that = this;
  904. let resource;
  905. Promise.resolve(options.url)
  906. .then(function (url) {
  907. let basePath;
  908. resource = Resource.createIfNeeded(url);
  909. that._resource = resource;
  910. // ion resources have a credits property we can use for additional attribution.
  911. that._credits = resource.credits;
  912. if (resource.extension === "json") {
  913. basePath = resource.getBaseUri(true);
  914. } else if (resource.isDataUri) {
  915. basePath = "";
  916. }
  917. that._url = resource.url;
  918. that._basePath = basePath;
  919. return Cesium3DTileset.loadJson(resource);
  920. })
  921. .then(function (tilesetJson) {
  922. // This needs to be called before loadTileset() so tile metadata
  923. // can be initialized synchronously in the Cesium3DTile constructor
  924. return processMetadataExtension(that, tilesetJson);
  925. })
  926. .then(function (tilesetJson) {
  927. that._root = that.loadTileset(resource, tilesetJson);
  928. const gltfUpAxis = defined(tilesetJson.asset.gltfUpAxis)
  929. ? Axis.fromName(tilesetJson.asset.gltfUpAxis)
  930. : Axis.Y;
  931. const asset = tilesetJson.asset;
  932. that._asset = asset;
  933. that._properties = tilesetJson.properties;
  934. that._geometricError = tilesetJson.geometricError;
  935. that._extensionsUsed = tilesetJson.extensionsUsed;
  936. that._extensions = tilesetJson.extensions;
  937. that._gltfUpAxis = gltfUpAxis;
  938. that._extras = tilesetJson.extras;
  939. const extras = asset.extras;
  940. if (
  941. defined(extras) &&
  942. defined(extras.cesium) &&
  943. defined(extras.cesium.credits)
  944. ) {
  945. const extraCredits = extras.cesium.credits;
  946. let credits = that._credits;
  947. if (!defined(credits)) {
  948. credits = [];
  949. that._credits = credits;
  950. }
  951. for (let i = 0; i < extraCredits.length; ++i) {
  952. const credit = extraCredits[i];
  953. credits.push(new Credit(credit.html, that._showCreditsOnScreen));
  954. }
  955. }
  956. // Save the original, untransformed bounding volume position so we can apply
  957. // the tile transform and model matrix at run time
  958. const boundingVolume = that._root.createBoundingVolume(
  959. tilesetJson.root.boundingVolume,
  960. Matrix4.IDENTITY
  961. );
  962. const clippingPlanesOrigin = boundingVolume.boundingSphere.center;
  963. // If this origin is above the surface of the earth
  964. // we want to apply an ENU orientation as our best guess of orientation.
  965. // Otherwise, we assume it gets its position/orientation completely from the
  966. // root tile transform and the tileset's model matrix
  967. const originCartographic = that._ellipsoid.cartesianToCartographic(
  968. clippingPlanesOrigin
  969. );
  970. if (
  971. defined(originCartographic) &&
  972. originCartographic.height >
  973. ApproximateTerrainHeights._defaultMinTerrainHeight
  974. ) {
  975. that._initialClippingPlanesOriginMatrix = Transforms.eastNorthUpToFixedFrame(
  976. clippingPlanesOrigin
  977. );
  978. }
  979. that._clippingPlanesOriginMatrix = Matrix4.clone(
  980. that._initialClippingPlanesOriginMatrix
  981. );
  982. that._readyPromise.resolve(that);
  983. })
  984. .catch(function (error) {
  985. that._readyPromise.reject(error);
  986. });
  987. }
  988. Object.defineProperties(Cesium3DTileset.prototype, {
  989. /**
  990. * NOTE: This getter exists so that `Picking.js` can differentiate between
  991. * PrimitiveCollection and Cesium3DTileset objects without inflating
  992. * the size of the module via `instanceof Cesium3DTileset`
  993. * @private
  994. */
  995. isCesium3DTileset: {
  996. get: function () {
  997. return true;
  998. },
  999. },
  1000. /**
  1001. * Gets the tileset's asset object property, which contains metadata about the tileset.
  1002. * <p>
  1003. * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification#reference-asset|asset schema reference}
  1004. * in the 3D Tiles spec for the full set of properties.
  1005. * </p>
  1006. *
  1007. * @memberof Cesium3DTileset.prototype
  1008. *
  1009. * @type {Object}
  1010. * @readonly
  1011. *
  1012. * @exception {DeveloperError} The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
  1013. */
  1014. asset: {
  1015. get: function () {
  1016. //>>includeStart('debug', pragmas.debug);
  1017. if (!this.ready) {
  1018. throw new DeveloperError(
  1019. "The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true."
  1020. );
  1021. }
  1022. //>>includeEnd('debug');
  1023. return this._asset;
  1024. },
  1025. },
  1026. /**
  1027. * Gets the tileset's extensions object property.
  1028. *
  1029. * @memberof Cesium3DTileset.prototype
  1030. *
  1031. * @type {Object}
  1032. * @readonly
  1033. *
  1034. * @exception {DeveloperError} The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
  1035. */
  1036. extensions: {
  1037. get: function () {
  1038. //>>includeStart('debug', pragmas.debug);
  1039. if (!this.ready) {
  1040. throw new DeveloperError(
  1041. "The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true."
  1042. );
  1043. }
  1044. //>>includeEnd('debug');
  1045. return this._extensions;
  1046. },
  1047. },
  1048. /**
  1049. * The {@link ClippingPlaneCollection} used to selectively disable rendering the tileset.
  1050. *
  1051. * @memberof Cesium3DTileset.prototype
  1052. *
  1053. * @type {ClippingPlaneCollection}
  1054. */
  1055. clippingPlanes: {
  1056. get: function () {
  1057. return this._clippingPlanes;
  1058. },
  1059. set: function (value) {
  1060. ClippingPlaneCollection.setOwner(value, this, "_clippingPlanes");
  1061. },
  1062. },
  1063. /**
  1064. * Gets the tileset's properties dictionary object, which contains metadata about per-feature properties.
  1065. * <p>
  1066. * See the {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification#reference-properties|properties schema reference}
  1067. * in the 3D Tiles spec for the full set of properties.
  1068. * </p>
  1069. *
  1070. * @memberof Cesium3DTileset.prototype
  1071. *
  1072. * @type {Object}
  1073. * @readonly
  1074. *
  1075. * @exception {DeveloperError} The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
  1076. *
  1077. * @example
  1078. * console.log('Maximum building height: ' + tileset.properties.height.maximum);
  1079. * console.log('Minimum building height: ' + tileset.properties.height.minimum);
  1080. *
  1081. * @see Cesium3DTileFeature#getProperty
  1082. * @see Cesium3DTileFeature#setProperty
  1083. */
  1084. properties: {
  1085. get: function () {
  1086. //>>includeStart('debug', pragmas.debug);
  1087. if (!this.ready) {
  1088. throw new DeveloperError(
  1089. "The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true."
  1090. );
  1091. }
  1092. //>>includeEnd('debug');
  1093. return this._properties;
  1094. },
  1095. },
  1096. /**
  1097. * When <code>true</code>, the tileset's root tile is loaded and the tileset is ready to render.
  1098. * This is set to <code>true</code> right before {@link Cesium3DTileset#readyPromise} is resolved.
  1099. *
  1100. * @memberof Cesium3DTileset.prototype
  1101. *
  1102. * @type {Boolean}
  1103. * @readonly
  1104. *
  1105. * @default false
  1106. */
  1107. ready: {
  1108. get: function () {
  1109. return defined(this._root);
  1110. },
  1111. },
  1112. /**
  1113. * Gets the promise that will be resolved when the tileset's root tile is loaded and the tileset is ready to render.
  1114. * <p>
  1115. * This promise is resolved at the end of the frame before the first frame the tileset is rendered in.
  1116. * </p>
  1117. *
  1118. * @memberof Cesium3DTileset.prototype
  1119. *
  1120. * @type {Promise.<Cesium3DTileset>}
  1121. * @readonly
  1122. *
  1123. * @example
  1124. * tileset.readyPromise.then(function(tileset) {
  1125. * // tile.properties is not defined until readyPromise resolves.
  1126. * const properties = tileset.properties;
  1127. * if (Cesium.defined(properties)) {
  1128. * for (const name in properties) {
  1129. * console.log(properties[name]);
  1130. * }
  1131. * }
  1132. * });
  1133. */
  1134. readyPromise: {
  1135. get: function () {
  1136. return this._readyPromise.promise;
  1137. },
  1138. },
  1139. /**
  1140. * When <code>true</code>, all tiles that meet the screen space error this frame are loaded. The tileset is
  1141. * completely loaded for this view.
  1142. *
  1143. * @memberof Cesium3DTileset.prototype
  1144. *
  1145. * @type {Boolean}
  1146. * @readonly
  1147. *
  1148. * @default false
  1149. *
  1150. * @see Cesium3DTileset#allTilesLoaded
  1151. */
  1152. tilesLoaded: {
  1153. get: function () {
  1154. return this._tilesLoaded;
  1155. },
  1156. },
  1157. /**
  1158. * The resource used to fetch the tileset JSON file
  1159. *
  1160. * @memberof Cesium3DTileset.prototype
  1161. *
  1162. * @type {Resource}
  1163. * @readonly
  1164. */
  1165. resource: {
  1166. get: function () {
  1167. return this._resource;
  1168. },
  1169. },
  1170. /**
  1171. * The base path that non-absolute paths in tileset JSON file are relative to.
  1172. *
  1173. * @memberof Cesium3DTileset.prototype
  1174. *
  1175. * @type {String}
  1176. * @readonly
  1177. * @deprecated
  1178. */
  1179. basePath: {
  1180. get: function () {
  1181. deprecationWarning(
  1182. "Cesium3DTileset.basePath",
  1183. "Cesium3DTileset.basePath has been deprecated. All tiles are relative to the url of the tileset JSON file that contains them. Use the url property instead."
  1184. );
  1185. return this._basePath;
  1186. },
  1187. },
  1188. /**
  1189. * The style, defined using the
  1190. * {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language},
  1191. * applied to each feature in the tileset.
  1192. * <p>
  1193. * Assign <code>undefined</code> to remove the style, which will restore the visual
  1194. * appearance of the tileset to its default when no style was applied.
  1195. * </p>
  1196. * <p>
  1197. * The style is applied to a tile before the {@link Cesium3DTileset#tileVisible}
  1198. * event is raised, so code in <code>tileVisible</code> can manually set a feature's
  1199. * properties (e.g. color and show) after the style is applied. When
  1200. * a new style is assigned any manually set properties are overwritten.
  1201. * </p>
  1202. * <p>
  1203. * Use an always "true" condition to specify the Color for all objects that are not
  1204. * overridden by pre-existing conditions. Otherwise, the default color Cesium.Color.White
  1205. * will be used. Similarly, use an always "true" condition to specify the show property
  1206. * for all objects that are not overridden by pre-existing conditions. Otherwise, the
  1207. * default show value true will be used.
  1208. * </p>
  1209. *
  1210. * @memberof Cesium3DTileset.prototype
  1211. *
  1212. * @type {Cesium3DTileStyle|undefined}
  1213. *
  1214. * @default undefined
  1215. *
  1216. * @example
  1217. * tileset.style = new Cesium.Cesium3DTileStyle({
  1218. * color : {
  1219. * conditions : [
  1220. * ['${Height} >= 100', 'color("purple", 0.5)'],
  1221. * ['${Height} >= 50', 'color("red")'],
  1222. * ['true', 'color("blue")']
  1223. * ]
  1224. * },
  1225. * show : '${Height} > 0',
  1226. * meta : {
  1227. * description : '"Building id ${id} has height ${Height}."'
  1228. * }
  1229. * });
  1230. *
  1231. * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification/Styling|3D Tiles Styling language}
  1232. */
  1233. style: {
  1234. get: function () {
  1235. return this._styleEngine.style;
  1236. },
  1237. set: function (value) {
  1238. this._styleEngine.style = value;
  1239. },
  1240. },
  1241. /**
  1242. * A custom shader to apply to all tiles in the tileset. Only used for
  1243. * contents that use {@link ModelExperimental}. Using custom shaders with a
  1244. * {@link Cesium3DTileStyle} may lead to undefined behavior.
  1245. * <p>
  1246. * To enable {@link ModelExperimental}, set {@link ExperimentalFeatures.enableModelExperimental} or tileset.enableModelExperimental to <code>true</code>.
  1247. * </p>
  1248. *
  1249. * @memberof Cesium3DTileset.prototype
  1250. *
  1251. * @type {CustomShader|undefined}
  1252. *
  1253. * @default undefined
  1254. *
  1255. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  1256. */
  1257. customShader: {
  1258. get: function () {
  1259. return this._customShader;
  1260. },
  1261. set: function (value) {
  1262. this._customShader = value;
  1263. },
  1264. },
  1265. /**
  1266. * The tileset's schema, groups, tileset metadata and other details from the
  1267. * 3DTILES_metadata extension or a 3D Tiles 1.1 tileset JSON. This getter is
  1268. * for internal use by other classes.
  1269. *
  1270. * @memberof Cesium3DTileset.prototype
  1271. * @type {Cesium3DTilesetMetadata}
  1272. * @private
  1273. * @readonly
  1274. *
  1275. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  1276. */
  1277. metadataExtension: {
  1278. get: function () {
  1279. return this._metadataExtension;
  1280. },
  1281. },
  1282. /**
  1283. * The metadata properties attached to the tileset as a whole.
  1284. *
  1285. * @memberof Cesium3DTileset.prototype
  1286. *
  1287. * @type {TilesetMetadata}
  1288. * @private
  1289. * @readonly
  1290. *
  1291. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  1292. */
  1293. metadata: {
  1294. get: function () {
  1295. if (defined(this._metadataExtension)) {
  1296. return this._metadataExtension.tileset;
  1297. }
  1298. return undefined;
  1299. },
  1300. },
  1301. /**
  1302. * The metadata schema used in this tileset. Shorthand for
  1303. * <code>tileset.metadataExtension.schema</code>
  1304. *
  1305. * @memberof Cesium3DTileset.prototype
  1306. *
  1307. * @type {MetadataSchema}
  1308. * @private
  1309. * @readonly
  1310. *
  1311. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  1312. */
  1313. schema: {
  1314. get: function () {
  1315. if (defined(this._metadataExtension)) {
  1316. return this._metadataExtension.schema;
  1317. }
  1318. return undefined;
  1319. },
  1320. },
  1321. /**
  1322. * The maximum screen space error used to drive level of detail refinement. This value helps determine when a tile
  1323. * refines to its descendants, and therefore plays a major role in balancing performance with visual quality.
  1324. * <p>
  1325. * A tile's screen space error is roughly equivalent to the number of pixels wide that would be drawn if a sphere with a
  1326. * radius equal to the tile's <b>geometric error</b> were rendered at the tile's position. If this value exceeds
  1327. * <code>maximumScreenSpaceError</code> the tile refines to its descendants.
  1328. * </p>
  1329. * <p>
  1330. * Depending on the tileset, <code>maximumScreenSpaceError</code> may need to be tweaked to achieve the right balance.
  1331. * Higher values provide better performance but lower visual quality.
  1332. * </p>
  1333. *
  1334. * @memberof Cesium3DTileset.prototype
  1335. *
  1336. * @type {Number}
  1337. * @default 16
  1338. *
  1339. * @exception {DeveloperError} <code>maximumScreenSpaceError</code> must be greater than or equal to zero.
  1340. */
  1341. maximumScreenSpaceError: {
  1342. get: function () {
  1343. return this._maximumScreenSpaceError;
  1344. },
  1345. set: function (value) {
  1346. //>>includeStart('debug', pragmas.debug);
  1347. Check.typeOf.number.greaterThanOrEquals(
  1348. "maximumScreenSpaceError",
  1349. value,
  1350. 0
  1351. );
  1352. //>>includeEnd('debug');
  1353. this._maximumScreenSpaceError = value;
  1354. },
  1355. },
  1356. /**
  1357. * The maximum amount of GPU memory (in MB) that may be used to cache tiles. This value is estimated from
  1358. * geometry, textures, and batch table textures of loaded tiles. For point clouds, this value also
  1359. * includes per-point metadata.
  1360. * <p>
  1361. * Tiles not in view are unloaded to enforce this.
  1362. * </p>
  1363. * <p>
  1364. * If decreasing this value results in unloading tiles, the tiles are unloaded the next frame.
  1365. * </p>
  1366. * <p>
  1367. * If tiles sized more than <code>maximumMemoryUsage</code> are needed
  1368. * to meet the desired screen space error, determined by {@link Cesium3DTileset#maximumScreenSpaceError},
  1369. * for the current view, then the memory usage of the tiles loaded will exceed
  1370. * <code>maximumMemoryUsage</code>. For example, if the maximum is 256 MB, but
  1371. * 300 MB of tiles are needed to meet the screen space error, then 300 MB of tiles may be loaded. When
  1372. * these tiles go out of view, they will be unloaded.
  1373. * </p>
  1374. *
  1375. * @memberof Cesium3DTileset.prototype
  1376. *
  1377. * @type {Number}
  1378. * @default 512
  1379. *
  1380. * @exception {DeveloperError} <code>maximumMemoryUsage</code> must be greater than or equal to zero.
  1381. * @see Cesium3DTileset#totalMemoryUsageInBytes
  1382. */
  1383. maximumMemoryUsage: {
  1384. get: function () {
  1385. return this._maximumMemoryUsage;
  1386. },
  1387. set: function (value) {
  1388. //>>includeStart('debug', pragmas.debug);
  1389. Check.typeOf.number.greaterThanOrEquals("value", value, 0);
  1390. //>>includeEnd('debug');
  1391. this._maximumMemoryUsage = value;
  1392. },
  1393. },
  1394. /**
  1395. * Options for controlling point size based on geometric error and eye dome lighting.
  1396. *
  1397. * @memberof Cesium3DTileset.prototype
  1398. *
  1399. * @type {PointCloudShading}
  1400. */
  1401. pointCloudShading: {
  1402. get: function () {
  1403. return this._pointCloudShading;
  1404. },
  1405. set: function (value) {
  1406. //>>includeStart('debug', pragmas.debug);
  1407. Check.defined("pointCloudShading", value);
  1408. //>>includeEnd('debug');
  1409. this._pointCloudShading = value;
  1410. },
  1411. },
  1412. /**
  1413. * The root tile.
  1414. *
  1415. * @memberOf Cesium3DTileset.prototype
  1416. *
  1417. * @type {Cesium3DTile}
  1418. * @readonly
  1419. *
  1420. * @exception {DeveloperError} The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
  1421. */
  1422. root: {
  1423. get: function () {
  1424. //>>includeStart('debug', pragmas.debug);
  1425. if (!this.ready) {
  1426. throw new DeveloperError(
  1427. "The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true."
  1428. );
  1429. }
  1430. //>>includeEnd('debug');
  1431. return this._root;
  1432. },
  1433. },
  1434. /**
  1435. * The tileset's bounding sphere.
  1436. *
  1437. * @memberof Cesium3DTileset.prototype
  1438. *
  1439. * @type {BoundingSphere}
  1440. * @readonly
  1441. *
  1442. * @exception {DeveloperError} The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
  1443. *
  1444. * @example
  1445. * const tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
  1446. * url : 'http://localhost:8002/tilesets/Seattle/tileset.json'
  1447. * }));
  1448. *
  1449. * tileset.readyPromise.then(function(tileset) {
  1450. * // Set the camera to view the newly added tileset
  1451. * viewer.camera.viewBoundingSphere(tileset.boundingSphere, new Cesium.HeadingPitchRange(0, -0.5, 0));
  1452. * });
  1453. */
  1454. boundingSphere: {
  1455. get: function () {
  1456. //>>includeStart('debug', pragmas.debug);
  1457. if (!this.ready) {
  1458. throw new DeveloperError(
  1459. "The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true."
  1460. );
  1461. }
  1462. //>>includeEnd('debug');
  1463. this._root.updateTransform(this._modelMatrix);
  1464. return this._root.boundingSphere;
  1465. },
  1466. },
  1467. /**
  1468. * A 4x4 transformation matrix that transforms the entire tileset.
  1469. *
  1470. * @memberof Cesium3DTileset.prototype
  1471. *
  1472. * @type {Matrix4}
  1473. * @default Matrix4.IDENTITY
  1474. *
  1475. * @example
  1476. * // Adjust a tileset's height from the globe's surface.
  1477. * const heightOffset = 20.0;
  1478. * const boundingSphere = tileset.boundingSphere;
  1479. * const cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
  1480. * const surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
  1481. * const offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, heightOffset);
  1482. * const translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
  1483. * tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
  1484. */
  1485. modelMatrix: {
  1486. get: function () {
  1487. return this._modelMatrix;
  1488. },
  1489. set: function (value) {
  1490. this._modelMatrix = Matrix4.clone(value, this._modelMatrix);
  1491. },
  1492. },
  1493. /**
  1494. * Returns the time, in milliseconds, since the tileset was loaded and first updated.
  1495. *
  1496. * @memberof Cesium3DTileset.prototype
  1497. *
  1498. * @type {Number}
  1499. * @readonly
  1500. */
  1501. timeSinceLoad: {
  1502. get: function () {
  1503. return this._timeSinceLoad;
  1504. },
  1505. },
  1506. /**
  1507. * The total amount of GPU memory in bytes used by the tileset. This value is estimated from
  1508. * geometry, texture, and batch table textures of loaded tiles. For point clouds, this value also
  1509. * includes per-point metadata.
  1510. *
  1511. * @memberof Cesium3DTileset.prototype
  1512. *
  1513. * @type {Number}
  1514. * @readonly
  1515. *
  1516. * @see Cesium3DTileset#maximumMemoryUsage
  1517. */
  1518. totalMemoryUsageInBytes: {
  1519. get: function () {
  1520. const statistics = this._statistics;
  1521. return (
  1522. statistics.texturesByteLength +
  1523. statistics.geometryByteLength +
  1524. statistics.batchTableByteLength
  1525. );
  1526. },
  1527. },
  1528. /**
  1529. * @private
  1530. */
  1531. clippingPlanesOriginMatrix: {
  1532. get: function () {
  1533. if (!defined(this._clippingPlanesOriginMatrix)) {
  1534. return Matrix4.IDENTITY;
  1535. }
  1536. if (this._clippingPlanesOriginMatrixDirty) {
  1537. Matrix4.multiply(
  1538. this.root.computedTransform,
  1539. this._initialClippingPlanesOriginMatrix,
  1540. this._clippingPlanesOriginMatrix
  1541. );
  1542. this._clippingPlanesOriginMatrixDirty = false;
  1543. }
  1544. return this._clippingPlanesOriginMatrix;
  1545. },
  1546. },
  1547. /**
  1548. * @private
  1549. */
  1550. styleEngine: {
  1551. get: function () {
  1552. return this._styleEngine;
  1553. },
  1554. },
  1555. /**
  1556. * @private
  1557. */
  1558. statistics: {
  1559. get: function () {
  1560. return this._statistics;
  1561. },
  1562. },
  1563. /**
  1564. * Determines whether terrain, 3D Tiles or both will be classified by this tileset.
  1565. * <p>
  1566. * This option is only applied to tilesets containing batched 3D models, geometry data, or vector data. Even when undefined, vector data and geometry data
  1567. * must render as classifications and will default to rendering on both terrain and other 3D Tiles tilesets.
  1568. * </p>
  1569. * <p>
  1570. * When enabled for batched 3D model tilesets, there are a few requirements/limitations on the glTF:
  1571. * <ul>
  1572. * <li>POSITION and _BATCHID semantics are required.</li>
  1573. * <li>All indices with the same batch id must occupy contiguous sections of the index buffer.</li>
  1574. * <li>All shaders and techniques are ignored. The generated shader simply multiplies the position by the model-view-projection matrix.</li>
  1575. * <li>The only supported extensions are CESIUM_RTC and WEB3D_quantized_attributes.</li>
  1576. * <li>Only one node is supported.</li>
  1577. * <li>Only one mesh per node is supported.</li>
  1578. * <li>Only one primitive per mesh is supported.</li>
  1579. * </ul>
  1580. * </p>
  1581. *
  1582. * @memberof Cesium3DTileset.prototype
  1583. *
  1584. * @type {ClassificationType}
  1585. * @default undefined
  1586. *
  1587. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  1588. * @readonly
  1589. */
  1590. classificationType: {
  1591. get: function () {
  1592. return this._classificationType;
  1593. },
  1594. },
  1595. /**
  1596. * Gets an ellipsoid describing the shape of the globe.
  1597. *
  1598. * @memberof Cesium3DTileset.prototype
  1599. *
  1600. * @type {Ellipsoid}
  1601. * @readonly
  1602. */
  1603. ellipsoid: {
  1604. get: function () {
  1605. return this._ellipsoid;
  1606. },
  1607. },
  1608. /**
  1609. * Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control the cone size that determines which tiles are deferred.
  1610. * Tiles that are inside this cone are loaded immediately. Tiles outside the cone are potentially deferred based on how far outside the cone they are and {@link Cesium3DTileset#foveatedInterpolationCallback} and {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation}.
  1611. * Setting this to 0.0 means the cone will be the line formed by the camera position and its view direction. Setting this to 1.0 means the cone encompasses the entire field of view of the camera, essentially disabling the effect.
  1612. *
  1613. * @memberof Cesium3DTileset.prototype
  1614. *
  1615. * @type {Number}
  1616. * @default 0.3
  1617. */
  1618. foveatedConeSize: {
  1619. get: function () {
  1620. return this._foveatedConeSize;
  1621. },
  1622. set: function (value) {
  1623. //>>includeStart('debug', pragmas.debug);
  1624. Check.typeOf.number.greaterThanOrEquals("foveatedConeSize", value, 0.0);
  1625. Check.typeOf.number.lessThanOrEquals("foveatedConeSize", value, 1.0);
  1626. //>>includeEnd('debug');
  1627. this._foveatedConeSize = value;
  1628. },
  1629. },
  1630. /**
  1631. * Optimization option. Used when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control the starting screen space error relaxation for tiles outside the foveated cone.
  1632. * The screen space error will be raised starting with this value up to {@link Cesium3DTileset#maximumScreenSpaceError} based on the provided {@link Cesium3DTileset#foveatedInterpolationCallback}.
  1633. *
  1634. * @memberof Cesium3DTileset.prototype
  1635. *
  1636. * @type {Number}
  1637. * @default 0.0
  1638. */
  1639. foveatedMinimumScreenSpaceErrorRelaxation: {
  1640. get: function () {
  1641. return this._foveatedMinimumScreenSpaceErrorRelaxation;
  1642. },
  1643. set: function (value) {
  1644. //>>includeStart('debug', pragmas.debug);
  1645. Check.typeOf.number.greaterThanOrEquals(
  1646. "foveatedMinimumScreenSpaceErrorRelaxation",
  1647. value,
  1648. 0.0
  1649. );
  1650. Check.typeOf.number.lessThanOrEquals(
  1651. "foveatedMinimumScreenSpaceErrorRelaxation",
  1652. value,
  1653. this.maximumScreenSpaceError
  1654. );
  1655. //>>includeEnd('debug');
  1656. this._foveatedMinimumScreenSpaceErrorRelaxation = value;
  1657. },
  1658. },
  1659. /**
  1660. * Returns the <code>extras</code> property at the top-level of the tileset JSON, which contains application specific metadata.
  1661. * Returns <code>undefined</code> if <code>extras</code> does not exist.
  1662. *
  1663. * @memberof Cesium3DTileset.prototype
  1664. *
  1665. * @exception {DeveloperError} The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true.
  1666. *
  1667. * @type {*}
  1668. * @readonly
  1669. *
  1670. * @see {@link https://github.com/CesiumGS/3d-tiles/tree/main/specification#specifying-extensions-and-application-specific-extras|Extras in the 3D Tiles specification.}
  1671. */
  1672. extras: {
  1673. get: function () {
  1674. //>>includeStart('debug', pragmas.debug);
  1675. if (!this.ready) {
  1676. throw new DeveloperError(
  1677. "The tileset is not loaded. Use Cesium3DTileset.readyPromise or wait for Cesium3DTileset.ready to be true."
  1678. );
  1679. }
  1680. //>>includeEnd('debug');
  1681. return this._extras;
  1682. },
  1683. },
  1684. /**
  1685. * The properties for managing image-based lighting on this tileset.
  1686. *
  1687. * @memberof Cesium3DTileset.prototype
  1688. *
  1689. * @type {ImageBasedLighting}
  1690. */
  1691. imageBasedLighting: {
  1692. get: function () {
  1693. return this._imageBasedLighting;
  1694. },
  1695. set: function (value) {
  1696. //>>includeStart('debug', pragmas.debug);
  1697. Check.typeOf.object("imageBasedLighting", this._imageBasedLighting);
  1698. //>>includeEnd('debug');
  1699. if (value !== this._imageBasedLighting) {
  1700. if (
  1701. this._shouldDestroyImageBasedLighting &&
  1702. !this._imageBasedLighting.isDestroyed()
  1703. ) {
  1704. this._imageBasedLighting.destroy();
  1705. }
  1706. this._imageBasedLighting = value;
  1707. this._shouldDestroyImageBasedLighting = false;
  1708. }
  1709. },
  1710. },
  1711. /**
  1712. * Cesium adds lighting from the earth, sky, atmosphere, and star skybox. This cartesian is used to scale the final
  1713. * diffuse and specular lighting contribution from those sources to the final color. A value of 0.0 will disable those light sources.
  1714. *
  1715. * @memberof Cesium3DTileset.prototype
  1716. *
  1717. * @type {Cartesian2}
  1718. * @default Cartesian2(1.0, 1.0)
  1719. */
  1720. imageBasedLightingFactor: {
  1721. get: function () {
  1722. return this._imageBasedLighting.imageBasedLightingFactor;
  1723. },
  1724. set: function (value) {
  1725. this._imageBasedLighting.imageBasedLightingFactor = value;
  1726. },
  1727. },
  1728. /**
  1729. * The sun's luminance at the zenith in kilo candela per meter squared to use for this model's procedural environment map.
  1730. * This is used when {@link Cesium3DTileset#specularEnvironmentMaps} and {@link Cesium3DTileset#sphericalHarmonicCoefficients} are not defined.
  1731. *
  1732. * @memberof Cesium3DTileset.prototype
  1733. *
  1734. * @type {Number}
  1735. * @default 0.2
  1736. */
  1737. luminanceAtZenith: {
  1738. get: function () {
  1739. return this._imageBasedLighting.luminanceAtZenith;
  1740. },
  1741. set: function (value) {
  1742. this._imageBasedLighting.luminanceAtZenith = value;
  1743. },
  1744. },
  1745. /**
  1746. * The third order spherical harmonic coefficients used for the diffuse color of image-based lighting. When <code>undefined</code>, a diffuse irradiance
  1747. * computed from the atmosphere color is used.
  1748. * <p>
  1749. * There are nine <code>Cartesian3</code> coefficients.
  1750. * The order of the coefficients is: L<sub>0,0</sub>, L<sub>1,-1</sub>, L<sub>1,0</sub>, L<sub>1,1</sub>, L<sub>2,-2</sub>, L<sub>2,-1</sub>, L<sub>2,0</sub>, L<sub>2,1</sub>, L<sub>2,2</sub>
  1751. * </p>
  1752. *
  1753. * These values can be obtained by preprocessing the environment map using the <code>cmgen</code> tool of
  1754. * {@link https://github.com/google/filament/releases|Google's Filament project}. This will also generate a KTX file that can be
  1755. * supplied to {@link Cesium3DTileset#specularEnvironmentMaps}.
  1756. *
  1757. * @memberof Cesium3DTileset.prototype
  1758. *
  1759. * @type {Cartesian3[]}
  1760. *
  1761. * @demo {@link https://sandcastle.cesium.com/index.html?src=Image-Based Lighting.html|Sandcastle Image Based Lighting Demo}
  1762. * @see {@link https://graphics.stanford.edu/papers/envmap/envmap.pdf|An Efficient Representation for Irradiance Environment Maps}
  1763. */
  1764. sphericalHarmonicCoefficients: {
  1765. get: function () {
  1766. return this._imageBasedLighting.sphericalHarmonicCoefficients;
  1767. },
  1768. set: function (value) {
  1769. this._imageBasedLighting.sphericalHarmonicCoefficients = value;
  1770. },
  1771. },
  1772. /**
  1773. * A URL to a KTX file that contains a cube map of the specular lighting and the convoluted specular mipmaps.
  1774. *
  1775. * @memberof Cesium3DTileset.prototype
  1776. *
  1777. * @type {String}
  1778. *
  1779. * @demo {@link https://sandcastle.cesium.com/index.html?src=Image-Based Lighting.html|Sandcastle Image Based Lighting Demo}
  1780. * @see Cesium3DTileset#sphericalHarmonicCoefficients
  1781. */
  1782. specularEnvironmentMaps: {
  1783. get: function () {
  1784. return this._imageBasedLighting.specularEnvironmentMaps;
  1785. },
  1786. set: function (value) {
  1787. this._imageBasedLighting.specularEnvironmentMaps = value;
  1788. },
  1789. },
  1790. /**
  1791. * Indicates that only the tileset's vector tiles should be used for classification.
  1792. *
  1793. * @memberof Cesium3DTileset.prototype
  1794. *
  1795. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  1796. *
  1797. * @type {Boolean}
  1798. * @default false
  1799. */
  1800. vectorClassificationOnly: {
  1801. get: function () {
  1802. return this._vectorClassificationOnly;
  1803. },
  1804. },
  1805. /**
  1806. * Whether vector tiles should keep decoded positions in memory.
  1807. * This is used with {@link Cesium3DTileFeature.getPolylinePositions}.
  1808. *
  1809. * @memberof Cesium3DTileset.prototype
  1810. *
  1811. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  1812. *
  1813. * @type {Boolean}
  1814. * @default false
  1815. */
  1816. vectorKeepDecodedPositions: {
  1817. get: function () {
  1818. return this._vectorKeepDecodedPositions;
  1819. },
  1820. },
  1821. /**
  1822. * Determines whether the credits of the tileset will be displayed on the screen
  1823. *
  1824. * @memberof Cesium3DTileset.prototype
  1825. *
  1826. * @type {Boolean}
  1827. * @default false
  1828. */
  1829. showCreditsOnScreen: {
  1830. get: function () {
  1831. return this._showCreditsOnScreen;
  1832. },
  1833. set: function (value) {
  1834. this._showCreditsOnScreen = value;
  1835. },
  1836. },
  1837. /**
  1838. * Label of the feature ID set to use for picking and styling.
  1839. * <p>
  1840. * For EXT_mesh_features, this is the feature ID's label property, or
  1841. * "featureId_N" (where N is the index in the featureIds array) when not
  1842. * specified. EXT_feature_metadata did not have a label field, so such
  1843. * feature ID sets are always labeled "featureId_N" where N is the index in
  1844. * the list of all feature Ids, where feature ID attributes are listed before
  1845. * feature ID textures.
  1846. * </p>
  1847. * <p>
  1848. * If featureIdLabel is set to an integer N, it is converted to
  1849. * the string "featureId_N" automatically. If both per-primitive and
  1850. * per-instance feature IDs are present, the instance feature IDs take
  1851. * priority.
  1852. * </p>
  1853. *
  1854. * @memberof Cesium3DTileset.prototype
  1855. *
  1856. * @type {String}
  1857. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  1858. */
  1859. featureIdLabel: {
  1860. get: function () {
  1861. return this._featureIdLabel;
  1862. },
  1863. set: function (value) {
  1864. // indices get converted into featureId_N
  1865. if (typeof value === "number") {
  1866. value = `featureId_${value}`;
  1867. }
  1868. //>>includeStart('debug', pragmas.debug);
  1869. Check.typeOf.string("value", value);
  1870. //>>includeEnd('debug');
  1871. this._featureIdLabel = value;
  1872. },
  1873. },
  1874. /**
  1875. * Label of the instance feature ID set used for picking and styling.
  1876. * <p>
  1877. * If instanceFeatureIdLabel is set to an integer N, it is converted to
  1878. * the string "instanceFeatureId_N" automatically.
  1879. * If both per-primitive and per-instance feature IDs are present, the
  1880. * instance feature IDs take priority.
  1881. * </p>
  1882. *
  1883. * @memberof Cesium3DTileset.prototype
  1884. *
  1885. * @type {String}
  1886. * @experimental This feature is using part of the 3D Tiles spec that is not final and is subject to change without Cesium's standard deprecation policy.
  1887. */
  1888. instanceFeatureIdLabel: {
  1889. get: function () {
  1890. return this._instanceFeatureIdLabel;
  1891. },
  1892. set: function (value) {
  1893. // indices get converted into instanceFeatureId_N
  1894. if (typeof value === "number") {
  1895. value = `instanceFeatureId_${value}`;
  1896. }
  1897. //>>includeStart('debug', pragmas.debug);
  1898. Check.typeOf.string("value", value);
  1899. //>>includeEnd('debug');
  1900. this._instanceFeatureIdLabel = value;
  1901. },
  1902. },
  1903. });
  1904. /**
  1905. * Provides a hook to override the method used to request the tileset json
  1906. * useful when fetching tilesets from remote servers
  1907. * @param {Resource|String} tilesetUrl The url of the json file to be fetched
  1908. * @returns {Promise.<Object>} A promise that resolves with the fetched json data
  1909. */
  1910. Cesium3DTileset.loadJson = function (tilesetUrl) {
  1911. const resource = Resource.createIfNeeded(tilesetUrl);
  1912. return resource.fetchJson();
  1913. };
  1914. /**
  1915. * Marks the tileset's {@link Cesium3DTileset#style} as dirty, which forces all
  1916. * features to re-evaluate the style in the next frame each is visible.
  1917. */
  1918. Cesium3DTileset.prototype.makeStyleDirty = function () {
  1919. this._styleEngine.makeDirty();
  1920. };
  1921. /**
  1922. * Loads the main tileset JSON file or a tileset JSON file referenced from a tile.
  1923. *
  1924. * @private
  1925. */
  1926. Cesium3DTileset.prototype.loadTileset = function (
  1927. resource,
  1928. tilesetJson,
  1929. parentTile
  1930. ) {
  1931. const asset = tilesetJson.asset;
  1932. if (!defined(asset)) {
  1933. throw new RuntimeError("Tileset must have an asset property.");
  1934. }
  1935. if (
  1936. asset.version !== "0.0" &&
  1937. asset.version !== "1.0" &&
  1938. asset.version !== "1.1"
  1939. ) {
  1940. throw new RuntimeError(
  1941. "The tileset must be 3D Tiles version 0.0, 1.0, or 1.1"
  1942. );
  1943. }
  1944. if (defined(tilesetJson.extensionsRequired)) {
  1945. Cesium3DTileset.checkSupportedExtensions(tilesetJson.extensionsRequired);
  1946. }
  1947. const statistics = this._statistics;
  1948. const tilesetVersion = asset.tilesetVersion;
  1949. if (defined(tilesetVersion)) {
  1950. // Append the tileset version to the resource
  1951. this._basePath += `?v=${tilesetVersion}`;
  1952. resource = resource.clone();
  1953. resource.setQueryParameters({ v: tilesetVersion });
  1954. }
  1955. // A tileset JSON file referenced from a tile may exist in a different directory than the root tileset.
  1956. // Get the basePath relative to the external tileset.
  1957. const rootTile = makeTile(this, resource, tilesetJson.root, parentTile);
  1958. // If there is a parentTile, add the root of the currently loading tileset
  1959. // to parentTile's children, and update its _depth.
  1960. if (defined(parentTile)) {
  1961. parentTile.children.push(rootTile);
  1962. rootTile._depth = parentTile._depth + 1;
  1963. }
  1964. const stack = [];
  1965. stack.push(rootTile);
  1966. while (stack.length > 0) {
  1967. const tile = stack.pop();
  1968. ++statistics.numberOfTilesTotal;
  1969. this._allTilesAdditive =
  1970. this._allTilesAdditive && tile.refine === Cesium3DTileRefine.ADD;
  1971. const children = tile._header.children;
  1972. if (defined(children)) {
  1973. const length = children.length;
  1974. for (let i = 0; i < length; ++i) {
  1975. const childHeader = children[i];
  1976. const childTile = makeTile(this, resource, childHeader, tile);
  1977. tile.children.push(childTile);
  1978. childTile._depth = tile._depth + 1;
  1979. stack.push(childTile);
  1980. }
  1981. }
  1982. if (this._cullWithChildrenBounds) {
  1983. Cesium3DTileOptimizations.checkChildrenWithinParent(tile);
  1984. }
  1985. }
  1986. return rootTile;
  1987. };
  1988. /**
  1989. * Make a {@link Cesium3DTile} for a specific tile. If the tile's header has implicit
  1990. * tiling (3D Tiles 1.1) or uses the <code>3DTILES_implicit_tiling</code> extension,
  1991. * it creates a placeholder tile instead for lazy evaluation of the implicit tileset.
  1992. *
  1993. * @param {Cesium3DTileset} tileset The tileset
  1994. * @param {Resource} baseResource The base resource for the tileset
  1995. * @param {Object} tileHeader The JSON header for the tile
  1996. * @param {Cesium3DTile} [parentTile] The parent tile of the new tile
  1997. * @returns {Cesium3DTile} The newly created tile
  1998. *
  1999. * @private
  2000. */
  2001. function makeTile(tileset, baseResource, tileHeader, parentTile) {
  2002. const hasImplicitTiling =
  2003. defined(tileHeader.implicitTiling) ||
  2004. hasExtension(tileHeader, "3DTILES_implicit_tiling");
  2005. if (hasImplicitTiling) {
  2006. const metadataSchema = tileset.schema;
  2007. const implicitTileset = new ImplicitTileset(
  2008. baseResource,
  2009. tileHeader,
  2010. metadataSchema
  2011. );
  2012. const rootCoordinates = new ImplicitTileCoordinates({
  2013. subdivisionScheme: implicitTileset.subdivisionScheme,
  2014. subtreeLevels: implicitTileset.subtreeLevels,
  2015. level: 0,
  2016. x: 0,
  2017. y: 0,
  2018. // The constructor will only use this for octrees.
  2019. z: 0,
  2020. });
  2021. // Create a placeholder Cesium3DTile that has an ImplicitTileset
  2022. // object and whose content will resolve to an Implicit3DTileContent
  2023. const contentUri = implicitTileset.subtreeUriTemplate.getDerivedResource({
  2024. templateValues: rootCoordinates.getTemplateValues(),
  2025. }).url;
  2026. const deepCopy = true;
  2027. const tileJson = clone(tileHeader, deepCopy);
  2028. // Replace contents with the subtree
  2029. tileJson.contents = [
  2030. {
  2031. uri: contentUri,
  2032. },
  2033. ];
  2034. delete tileJson.content;
  2035. // The placeholder tile does not have any extensions. If there are any
  2036. // extensions beyond 3DTILES_implicit_tiling, Implicit3DTileContent will
  2037. // copy them to the transcoded tiles.
  2038. delete tileJson.extensions;
  2039. const tile = new Cesium3DTile(tileset, baseResource, tileJson, parentTile);
  2040. tile.implicitTileset = implicitTileset;
  2041. tile.implicitCoordinates = rootCoordinates;
  2042. return tile;
  2043. }
  2044. return new Cesium3DTile(tileset, baseResource, tileHeader, parentTile);
  2045. }
  2046. /**
  2047. * If tileset metadata is present, initialize the {@link Cesium3DTilesetMetadata}
  2048. * instance. This is asynchronous since metadata schemas may be external.
  2049. *
  2050. * @param {Cesium3DTileset} tileset The tileset
  2051. * @param {Object} tilesetJson The tileset JSON
  2052. * @return {Promise<Object>} A promise that resolves to tilesetJson for chaining.
  2053. * @private
  2054. */
  2055. function processMetadataExtension(tileset, tilesetJson) {
  2056. const metadataJson = hasExtension(tilesetJson, "3DTILES_metadata")
  2057. ? tilesetJson.extensions["3DTILES_metadata"]
  2058. : tilesetJson;
  2059. let schemaLoader;
  2060. if (defined(metadataJson.schemaUri)) {
  2061. const resource = tileset._resource.getDerivedResource({
  2062. url: metadataJson.schemaUri,
  2063. });
  2064. schemaLoader = ResourceCache.loadSchema({
  2065. resource: resource,
  2066. });
  2067. } else if (defined(metadataJson.schema)) {
  2068. schemaLoader = ResourceCache.loadSchema({
  2069. schema: metadataJson.schema,
  2070. });
  2071. } else {
  2072. return Promise.resolve(tilesetJson);
  2073. }
  2074. tileset._schemaLoader = schemaLoader;
  2075. return schemaLoader.promise.then(function (schemaLoader) {
  2076. tileset._metadataExtension = new Cesium3DTilesetMetadata({
  2077. schema: schemaLoader.schema,
  2078. metadataJson: metadataJson,
  2079. });
  2080. return tilesetJson;
  2081. });
  2082. }
  2083. const scratchPositionNormal = new Cartesian3();
  2084. const scratchCartographic = new Cartographic();
  2085. const scratchMatrix = new Matrix4();
  2086. const scratchCenter = new Cartesian3();
  2087. const scratchPosition = new Cartesian3();
  2088. const scratchDirection = new Cartesian3();
  2089. function updateDynamicScreenSpaceError(tileset, frameState) {
  2090. let up;
  2091. let direction;
  2092. let height;
  2093. let minimumHeight;
  2094. let maximumHeight;
  2095. const camera = frameState.camera;
  2096. const root = tileset._root;
  2097. const tileBoundingVolume = root.contentBoundingVolume;
  2098. if (tileBoundingVolume instanceof TileBoundingRegion) {
  2099. up = Cartesian3.normalize(camera.positionWC, scratchPositionNormal);
  2100. direction = camera.directionWC;
  2101. height = camera.positionCartographic.height;
  2102. minimumHeight = tileBoundingVolume.minimumHeight;
  2103. maximumHeight = tileBoundingVolume.maximumHeight;
  2104. } else {
  2105. // Transform camera position and direction into the local coordinate system of the tileset
  2106. const transformLocal = Matrix4.inverseTransformation(
  2107. root.computedTransform,
  2108. scratchMatrix
  2109. );
  2110. const ellipsoid = frameState.mapProjection.ellipsoid;
  2111. const boundingVolume = tileBoundingVolume.boundingVolume;
  2112. const centerLocal = Matrix4.multiplyByPoint(
  2113. transformLocal,
  2114. boundingVolume.center,
  2115. scratchCenter
  2116. );
  2117. if (Cartesian3.magnitude(centerLocal) > ellipsoid.minimumRadius) {
  2118. // The tileset is defined in WGS84. Approximate the minimum and maximum height.
  2119. const centerCartographic = Cartographic.fromCartesian(
  2120. centerLocal,
  2121. ellipsoid,
  2122. scratchCartographic
  2123. );
  2124. up = Cartesian3.normalize(camera.positionWC, scratchPositionNormal);
  2125. direction = camera.directionWC;
  2126. height = camera.positionCartographic.height;
  2127. minimumHeight = 0.0;
  2128. maximumHeight = centerCartographic.height * 2.0;
  2129. } else {
  2130. // The tileset is defined in local coordinates (z-up)
  2131. const positionLocal = Matrix4.multiplyByPoint(
  2132. transformLocal,
  2133. camera.positionWC,
  2134. scratchPosition
  2135. );
  2136. up = Cartesian3.UNIT_Z;
  2137. direction = Matrix4.multiplyByPointAsVector(
  2138. transformLocal,
  2139. camera.directionWC,
  2140. scratchDirection
  2141. );
  2142. direction = Cartesian3.normalize(direction, direction);
  2143. height = positionLocal.z;
  2144. if (tileBoundingVolume instanceof TileOrientedBoundingBox) {
  2145. // Assuming z-up, the last component stores the half-height of the box
  2146. const boxHeight = root._header.boundingVolume.box[11];
  2147. minimumHeight = centerLocal.z - boxHeight;
  2148. maximumHeight = centerLocal.z + boxHeight;
  2149. } else if (tileBoundingVolume instanceof TileBoundingSphere) {
  2150. const radius = boundingVolume.radius;
  2151. minimumHeight = centerLocal.z - radius;
  2152. maximumHeight = centerLocal.z + radius;
  2153. }
  2154. }
  2155. }
  2156. // The range where the density starts to lessen. Start at the quarter height of the tileset.
  2157. const heightFalloff = tileset.dynamicScreenSpaceErrorHeightFalloff;
  2158. const heightClose =
  2159. minimumHeight + (maximumHeight - minimumHeight) * heightFalloff;
  2160. const heightFar = maximumHeight;
  2161. const t = CesiumMath.clamp(
  2162. (height - heightClose) / (heightFar - heightClose),
  2163. 0.0,
  2164. 1.0
  2165. );
  2166. // Increase density as the camera tilts towards the horizon
  2167. const dot = Math.abs(Cartesian3.dot(direction, up));
  2168. let horizonFactor = 1.0 - dot;
  2169. // Weaken the horizon factor as the camera height increases, implying the camera is further away from the tileset.
  2170. // The goal is to increase density for the "street view", not when viewing the tileset from a distance.
  2171. horizonFactor = horizonFactor * (1.0 - t);
  2172. let density = tileset.dynamicScreenSpaceErrorDensity;
  2173. density *= horizonFactor;
  2174. tileset._dynamicScreenSpaceErrorComputedDensity = density;
  2175. }
  2176. ///////////////////////////////////////////////////////////////////////////
  2177. function requestContent(tileset, tile) {
  2178. if (tile.hasEmptyContent) {
  2179. return;
  2180. }
  2181. const statistics = tileset._statistics;
  2182. const expired = tile.contentExpired;
  2183. const attemptedRequests = tile.requestContent();
  2184. if (attemptedRequests > 0) {
  2185. statistics.numberOfAttemptedRequests += attemptedRequests;
  2186. return;
  2187. }
  2188. if (expired) {
  2189. if (tile.hasTilesetContent || tile.hasImplicitContent) {
  2190. destroySubtree(tileset, tile);
  2191. } else {
  2192. statistics.decrementLoadCounts(tile.content);
  2193. --statistics.numberOfTilesWithContentReady;
  2194. }
  2195. }
  2196. tileset._requestedTilesInFlight.push(tile);
  2197. tile.contentReadyToProcessPromise.then(addToProcessingQueue(tileset, tile));
  2198. tile.contentReadyPromise
  2199. .then(handleTileSuccess(tileset, tile))
  2200. .catch(handleTileFailure(tileset, tile));
  2201. }
  2202. function sortRequestByPriority(a, b) {
  2203. return a._priority - b._priority;
  2204. }
  2205. /**
  2206. * Perform any pass invariant tasks here. Called after the render pass.
  2207. * @private
  2208. */
  2209. Cesium3DTileset.prototype.postPassesUpdate = function (frameState) {
  2210. if (!this.ready) {
  2211. return;
  2212. }
  2213. cancelOutOfViewRequests(this, frameState);
  2214. raiseLoadProgressEvent(this, frameState);
  2215. this._cache.unloadTiles(this, unloadTile);
  2216. this._styleEngine.resetDirty();
  2217. };
  2218. /**
  2219. * Perform any pass invariant tasks here. Called before any passes are executed.
  2220. * @private
  2221. */
  2222. Cesium3DTileset.prototype.prePassesUpdate = function (frameState) {
  2223. if (!this.ready) {
  2224. return;
  2225. }
  2226. processTiles(this, frameState);
  2227. // Update clipping planes
  2228. const clippingPlanes = this._clippingPlanes;
  2229. this._clippingPlanesOriginMatrixDirty = true;
  2230. if (defined(clippingPlanes) && clippingPlanes.enabled) {
  2231. clippingPlanes.update(frameState);
  2232. }
  2233. if (!defined(this._loadTimestamp)) {
  2234. this._loadTimestamp = JulianDate.clone(frameState.time);
  2235. }
  2236. this._timeSinceLoad = Math.max(
  2237. JulianDate.secondsDifference(frameState.time, this._loadTimestamp) * 1000,
  2238. 0.0
  2239. );
  2240. this._skipLevelOfDetail =
  2241. this.skipLevelOfDetail &&
  2242. !defined(this._classificationType) &&
  2243. !this._disableSkipLevelOfDetail &&
  2244. !this._allTilesAdditive;
  2245. if (this.dynamicScreenSpaceError) {
  2246. updateDynamicScreenSpaceError(this, frameState);
  2247. }
  2248. if (frameState.newFrame) {
  2249. this._cache.reset();
  2250. }
  2251. };
  2252. function cancelOutOfViewRequests(tileset, frameState) {
  2253. const requestedTilesInFlight = tileset._requestedTilesInFlight;
  2254. let removeCount = 0;
  2255. const length = requestedTilesInFlight.length;
  2256. for (let i = 0; i < length; ++i) {
  2257. const tile = requestedTilesInFlight[i];
  2258. // NOTE: This is framerate dependant so make sure the threshold check is small
  2259. const outOfView = frameState.frameNumber - tile._touchedFrame >= 1;
  2260. if (tile._contentState !== Cesium3DTileContentState.LOADING) {
  2261. // No longer fetching from host, don't need to track it anymore. Gets marked as LOADING in Cesium3DTile::requestContent().
  2262. ++removeCount;
  2263. continue;
  2264. } else if (outOfView) {
  2265. // RequestScheduler will take care of cancelling it
  2266. tile.cancelRequests();
  2267. ++removeCount;
  2268. continue;
  2269. }
  2270. if (removeCount > 0) {
  2271. requestedTilesInFlight[i - removeCount] = tile;
  2272. }
  2273. }
  2274. requestedTilesInFlight.length -= removeCount;
  2275. }
  2276. function requestTiles(tileset, isAsync) {
  2277. // Sort requests by priority before making any requests.
  2278. // This makes it less likely that requests will be cancelled after being issued.
  2279. const requestedTiles = tileset._requestedTiles;
  2280. const length = requestedTiles.length;
  2281. requestedTiles.sort(sortRequestByPriority);
  2282. for (let i = 0; i < length; ++i) {
  2283. requestContent(tileset, requestedTiles[i]);
  2284. }
  2285. }
  2286. function addToProcessingQueue(tileset, tile) {
  2287. return function () {
  2288. tileset._processingQueue.push(tile);
  2289. ++tileset._statistics.numberOfTilesProcessing;
  2290. };
  2291. }
  2292. function handleTileFailure(tileset, tile) {
  2293. return function (error) {
  2294. const url = tile._contentResource.url;
  2295. const message = defined(error.message) ? error.message : error.toString();
  2296. if (tileset.tileFailed.numberOfListeners > 0) {
  2297. tileset.tileFailed.raiseEvent({
  2298. url: url,
  2299. message: message,
  2300. });
  2301. } else {
  2302. console.log(`A 3D tile failed to load: ${url}`);
  2303. console.log(`Error: ${message}`);
  2304. }
  2305. };
  2306. }
  2307. function handleTileSuccess(tileset, tile) {
  2308. return function () {
  2309. --tileset._statistics.numberOfTilesProcessing;
  2310. if (!tile.hasTilesetContent && !tile.hasImplicitContent) {
  2311. // RESEARCH_IDEA: ability to unload tiles (without content) for an
  2312. // external tileset when all the tiles are unloaded.
  2313. tileset._statistics.incrementLoadCounts(tile.content);
  2314. ++tileset._statistics.numberOfTilesWithContentReady;
  2315. ++tileset._statistics.numberOfLoadedTilesTotal;
  2316. // Add to the tile cache. Previously expired tiles are already in the cache and won't get re-added.
  2317. tileset._cache.add(tile);
  2318. }
  2319. tileset.tileLoad.raiseEvent(tile);
  2320. };
  2321. }
  2322. function filterProcessingQueue(tileset) {
  2323. const tiles = tileset._processingQueue;
  2324. const length = tiles.length;
  2325. let removeCount = 0;
  2326. for (let i = 0; i < length; ++i) {
  2327. const tile = tiles[i];
  2328. if (tile._contentState !== Cesium3DTileContentState.PROCESSING) {
  2329. ++removeCount;
  2330. continue;
  2331. }
  2332. if (removeCount > 0) {
  2333. tiles[i - removeCount] = tile;
  2334. }
  2335. }
  2336. tiles.length -= removeCount;
  2337. }
  2338. function processTiles(tileset, frameState) {
  2339. filterProcessingQueue(tileset);
  2340. const tiles = tileset._processingQueue;
  2341. const length = tiles.length;
  2342. // Process tiles in the PROCESSING state so they will eventually move to the READY state.
  2343. for (let i = 0; i < length; ++i) {
  2344. tiles[i].process(tileset, frameState);
  2345. }
  2346. }
  2347. ///////////////////////////////////////////////////////////////////////////
  2348. const scratchCartesian = new Cartesian3();
  2349. const stringOptions = {
  2350. maximumFractionDigits: 3,
  2351. };
  2352. function formatMemoryString(memorySizeInBytes) {
  2353. const memoryInMegabytes = memorySizeInBytes / 1048576;
  2354. if (memoryInMegabytes < 1.0) {
  2355. return memoryInMegabytes.toLocaleString(undefined, stringOptions);
  2356. }
  2357. return Math.round(memoryInMegabytes).toLocaleString();
  2358. }
  2359. function computeTileLabelPosition(tile) {
  2360. const boundingVolume = tile.boundingVolume.boundingVolume;
  2361. const halfAxes = boundingVolume.halfAxes;
  2362. const radius = boundingVolume.radius;
  2363. let position = Cartesian3.clone(boundingVolume.center, scratchCartesian);
  2364. if (defined(halfAxes)) {
  2365. position.x += 0.75 * (halfAxes[0] + halfAxes[3] + halfAxes[6]);
  2366. position.y += 0.75 * (halfAxes[1] + halfAxes[4] + halfAxes[7]);
  2367. position.z += 0.75 * (halfAxes[2] + halfAxes[5] + halfAxes[8]);
  2368. } else if (defined(radius)) {
  2369. let normal = Cartesian3.normalize(boundingVolume.center, scratchCartesian);
  2370. normal = Cartesian3.multiplyByScalar(
  2371. normal,
  2372. 0.75 * radius,
  2373. scratchCartesian
  2374. );
  2375. position = Cartesian3.add(normal, boundingVolume.center, scratchCartesian);
  2376. }
  2377. return position;
  2378. }
  2379. function addTileDebugLabel(tile, tileset, position) {
  2380. let labelString = "";
  2381. let attributes = 0;
  2382. if (tileset.debugShowGeometricError) {
  2383. labelString += `\nGeometric error: ${tile.geometricError}`;
  2384. attributes++;
  2385. }
  2386. if (tileset.debugShowRenderingStatistics) {
  2387. labelString += `\nCommands: ${tile.commandsLength}`;
  2388. attributes++;
  2389. // Don't display number of points or triangles if 0.
  2390. const numberOfPoints = tile.content.pointsLength;
  2391. if (numberOfPoints > 0) {
  2392. labelString += `\nPoints: ${tile.content.pointsLength}`;
  2393. attributes++;
  2394. }
  2395. const numberOfTriangles = tile.content.trianglesLength;
  2396. if (numberOfTriangles > 0) {
  2397. labelString += `\nTriangles: ${tile.content.trianglesLength}`;
  2398. attributes++;
  2399. }
  2400. labelString += `\nFeatures: ${tile.content.featuresLength}`;
  2401. attributes++;
  2402. }
  2403. if (tileset.debugShowMemoryUsage) {
  2404. labelString += `\nTexture Memory: ${formatMemoryString(
  2405. tile.content.texturesByteLength
  2406. )}`;
  2407. labelString += `\nGeometry Memory: ${formatMemoryString(
  2408. tile.content.geometryByteLength
  2409. )}`;
  2410. attributes += 2;
  2411. }
  2412. if (tileset.debugShowUrl) {
  2413. if (tile.hasMultipleContents) {
  2414. labelString += "\nUrls:";
  2415. const urls = tile.content.innerContentUrls;
  2416. for (let i = 0; i < urls.length; i++) {
  2417. labelString += `\n- ${urls[i]}`;
  2418. }
  2419. attributes += urls.length;
  2420. } else {
  2421. labelString += `\nUrl: ${tile._header.content.uri}`;
  2422. attributes++;
  2423. }
  2424. }
  2425. const newLabel = {
  2426. text: labelString.substring(1),
  2427. position: position,
  2428. font: `${19 - attributes}px sans-serif`,
  2429. showBackground: true,
  2430. disableDepthTestDistance: Number.POSITIVE_INFINITY,
  2431. };
  2432. return tileset._tileDebugLabels.add(newLabel);
  2433. }
  2434. function updateTileDebugLabels(tileset, frameState) {
  2435. let i;
  2436. let tile;
  2437. const selectedTiles = tileset._selectedTiles;
  2438. const selectedLength = selectedTiles.length;
  2439. const emptyTiles = tileset._emptyTiles;
  2440. const emptyLength = emptyTiles.length;
  2441. tileset._tileDebugLabels.removeAll();
  2442. if (tileset.debugPickedTileLabelOnly) {
  2443. if (defined(tileset.debugPickedTile)) {
  2444. const position = defined(tileset.debugPickPosition)
  2445. ? tileset.debugPickPosition
  2446. : computeTileLabelPosition(tileset.debugPickedTile);
  2447. const label = addTileDebugLabel(
  2448. tileset.debugPickedTile,
  2449. tileset,
  2450. position
  2451. );
  2452. label.pixelOffset = new Cartesian2(15, -15); // Offset to avoid picking the label.
  2453. }
  2454. } else {
  2455. for (i = 0; i < selectedLength; ++i) {
  2456. tile = selectedTiles[i];
  2457. addTileDebugLabel(tile, tileset, computeTileLabelPosition(tile));
  2458. }
  2459. for (i = 0; i < emptyLength; ++i) {
  2460. tile = emptyTiles[i];
  2461. if (tile.hasTilesetContent || tile.hasImplicitContent) {
  2462. addTileDebugLabel(tile, tileset, computeTileLabelPosition(tile));
  2463. }
  2464. }
  2465. }
  2466. tileset._tileDebugLabels.update(frameState);
  2467. }
  2468. function updateTiles(tileset, frameState, passOptions) {
  2469. tileset._styleEngine.applyStyle(tileset);
  2470. const isRender = passOptions.isRender;
  2471. const statistics = tileset._statistics;
  2472. const commandList = frameState.commandList;
  2473. const numberOfInitialCommands = commandList.length;
  2474. const selectedTiles = tileset._selectedTiles;
  2475. const selectedLength = selectedTiles.length;
  2476. const emptyTiles = tileset._emptyTiles;
  2477. const emptyLength = emptyTiles.length;
  2478. const tileVisible = tileset.tileVisible;
  2479. let i;
  2480. let tile;
  2481. const bivariateVisibilityTest =
  2482. tileset._skipLevelOfDetail &&
  2483. tileset._hasMixedContent &&
  2484. frameState.context.stencilBuffer &&
  2485. selectedLength > 0;
  2486. tileset._backfaceCommands.length = 0;
  2487. if (bivariateVisibilityTest) {
  2488. if (!defined(tileset._stencilClearCommand)) {
  2489. tileset._stencilClearCommand = new ClearCommand({
  2490. stencil: 0,
  2491. pass: Pass.CESIUM_3D_TILE,
  2492. renderState: RenderState.fromCache({
  2493. stencilMask: StencilConstants.SKIP_LOD_MASK,
  2494. }),
  2495. });
  2496. }
  2497. commandList.push(tileset._stencilClearCommand);
  2498. }
  2499. const lengthBeforeUpdate = commandList.length;
  2500. for (i = 0; i < selectedLength; ++i) {
  2501. tile = selectedTiles[i];
  2502. // Raise the tileVisible event before update in case the tileVisible event
  2503. // handler makes changes that update needs to apply to WebGL resources
  2504. if (isRender) {
  2505. tileVisible.raiseEvent(tile);
  2506. }
  2507. tile.update(tileset, frameState, passOptions);
  2508. statistics.incrementSelectionCounts(tile.content);
  2509. ++statistics.selected;
  2510. }
  2511. for (i = 0; i < emptyLength; ++i) {
  2512. tile = emptyTiles[i];
  2513. tile.update(tileset, frameState, passOptions);
  2514. }
  2515. let addedCommandsLength = commandList.length - lengthBeforeUpdate;
  2516. tileset._backfaceCommands.trim();
  2517. if (bivariateVisibilityTest) {
  2518. /*
  2519. * Consider 'effective leaf' tiles as selected tiles that have no selected descendants. They may have children,
  2520. * but they are currently our effective leaves because they do not have selected descendants. These tiles
  2521. * are those where with tile._finalResolution === true.
  2522. * Let 'unresolved' tiles be those with tile._finalResolution === false.
  2523. *
  2524. * 1. Render just the backfaces of unresolved tiles in order to lay down z
  2525. * 2. Render all frontfaces wherever tile._selectionDepth > stencilBuffer.
  2526. * Replace stencilBuffer with tile._selectionDepth, when passing the z test.
  2527. * Because children are always drawn before ancestors {@link Cesium3DTilesetTraversal#traverseAndSelect},
  2528. * this effectively draws children first and does not draw ancestors if a descendant has already
  2529. * been drawn at that pixel.
  2530. * Step 1 prevents child tiles from appearing on top when they are truly behind ancestor content.
  2531. * If they are behind the backfaces of the ancestor, then they will not be drawn.
  2532. *
  2533. * NOTE: Step 2 sometimes causes visual artifacts when backfacing child content has some faces that
  2534. * partially face the camera and are inside of the ancestor content. Because they are inside, they will
  2535. * not be culled by the depth writes in Step 1, and because they partially face the camera, the stencil tests
  2536. * will draw them on top of the ancestor content.
  2537. *
  2538. * NOTE: Because we always render backfaces of unresolved tiles, if the camera is looking at the backfaces
  2539. * of an object, they will always be drawn while loading, even if backface culling is enabled.
  2540. */
  2541. const backfaceCommands = tileset._backfaceCommands.values;
  2542. const backfaceCommandsLength = backfaceCommands.length;
  2543. commandList.length += backfaceCommandsLength;
  2544. // copy commands to the back of the commandList
  2545. for (i = addedCommandsLength - 1; i >= 0; --i) {
  2546. commandList[lengthBeforeUpdate + backfaceCommandsLength + i] =
  2547. commandList[lengthBeforeUpdate + i];
  2548. }
  2549. // move backface commands to the front of the commandList
  2550. for (i = 0; i < backfaceCommandsLength; ++i) {
  2551. commandList[lengthBeforeUpdate + i] = backfaceCommands[i];
  2552. }
  2553. }
  2554. // Number of commands added by each update above
  2555. addedCommandsLength = commandList.length - numberOfInitialCommands;
  2556. statistics.numberOfCommands = addedCommandsLength;
  2557. // Only run EDL if simple attenuation is on
  2558. if (
  2559. isRender &&
  2560. tileset.pointCloudShading.attenuation &&
  2561. tileset.pointCloudShading.eyeDomeLighting &&
  2562. addedCommandsLength > 0
  2563. ) {
  2564. tileset._pointCloudEyeDomeLighting.update(
  2565. frameState,
  2566. numberOfInitialCommands,
  2567. tileset.pointCloudShading,
  2568. tileset.boundingSphere
  2569. );
  2570. }
  2571. if (isRender) {
  2572. if (
  2573. tileset.debugShowGeometricError ||
  2574. tileset.debugShowRenderingStatistics ||
  2575. tileset.debugShowMemoryUsage ||
  2576. tileset.debugShowUrl
  2577. ) {
  2578. if (!defined(tileset._tileDebugLabels)) {
  2579. tileset._tileDebugLabels = new LabelCollection();
  2580. }
  2581. updateTileDebugLabels(tileset, frameState);
  2582. } else {
  2583. tileset._tileDebugLabels =
  2584. tileset._tileDebugLabels && tileset._tileDebugLabels.destroy();
  2585. }
  2586. }
  2587. }
  2588. const scratchStack = [];
  2589. function destroySubtree(tileset, tile) {
  2590. const root = tile;
  2591. const stack = scratchStack;
  2592. stack.push(tile);
  2593. while (stack.length > 0) {
  2594. tile = stack.pop();
  2595. const children = tile.children;
  2596. const length = children.length;
  2597. for (let i = 0; i < length; ++i) {
  2598. stack.push(children[i]);
  2599. }
  2600. if (tile !== root) {
  2601. destroyTile(tileset, tile);
  2602. --tileset._statistics.numberOfTilesTotal;
  2603. }
  2604. }
  2605. root.children = [];
  2606. }
  2607. function unloadTile(tileset, tile) {
  2608. tileset.tileUnload.raiseEvent(tile);
  2609. tileset._statistics.decrementLoadCounts(tile.content);
  2610. --tileset._statistics.numberOfTilesWithContentReady;
  2611. tile.unloadContent();
  2612. }
  2613. function destroyTile(tileset, tile) {
  2614. tileset._cache.unloadTile(tileset, tile, unloadTile);
  2615. tile.destroy();
  2616. }
  2617. /**
  2618. * Unloads all tiles that weren't selected the previous frame. This can be used to
  2619. * explicitly manage the tile cache and reduce the total number of tiles loaded below
  2620. * {@link Cesium3DTileset#maximumMemoryUsage}.
  2621. * <p>
  2622. * Tile unloads occur at the next frame to keep all the WebGL delete calls
  2623. * within the render loop.
  2624. * </p>
  2625. */
  2626. Cesium3DTileset.prototype.trimLoadedTiles = function () {
  2627. this._cache.trim();
  2628. };
  2629. ///////////////////////////////////////////////////////////////////////////
  2630. function raiseLoadProgressEvent(tileset, frameState) {
  2631. const statistics = tileset._statistics;
  2632. const statisticsLast = tileset._statisticsLast;
  2633. const numberOfPendingRequests = statistics.numberOfPendingRequests;
  2634. const numberOfTilesProcessing = statistics.numberOfTilesProcessing;
  2635. const lastNumberOfPendingRequest = statisticsLast.numberOfPendingRequests;
  2636. const lastNumberOfTilesProcessing = statisticsLast.numberOfTilesProcessing;
  2637. Cesium3DTilesetStatistics.clone(statistics, statisticsLast);
  2638. const progressChanged =
  2639. numberOfPendingRequests !== lastNumberOfPendingRequest ||
  2640. numberOfTilesProcessing !== lastNumberOfTilesProcessing;
  2641. if (progressChanged) {
  2642. frameState.afterRender.push(function () {
  2643. tileset.loadProgress.raiseEvent(
  2644. numberOfPendingRequests,
  2645. numberOfTilesProcessing
  2646. );
  2647. });
  2648. }
  2649. tileset._tilesLoaded =
  2650. statistics.numberOfPendingRequests === 0 &&
  2651. statistics.numberOfTilesProcessing === 0 &&
  2652. statistics.numberOfAttemptedRequests === 0;
  2653. // Events are raised (added to the afterRender queue) here since promises
  2654. // may resolve outside of the update loop that then raise events, e.g.,
  2655. // model's readyPromise.
  2656. if (progressChanged && tileset._tilesLoaded) {
  2657. frameState.afterRender.push(function () {
  2658. tileset.allTilesLoaded.raiseEvent();
  2659. });
  2660. if (!tileset._initialTilesLoaded) {
  2661. tileset._initialTilesLoaded = true;
  2662. frameState.afterRender.push(function () {
  2663. tileset.initialTilesLoaded.raiseEvent();
  2664. });
  2665. }
  2666. }
  2667. }
  2668. function resetMinimumMaximum(tileset) {
  2669. tileset._heatmap.resetMinimumMaximum();
  2670. tileset._minimumPriority.depth = Number.MAX_VALUE;
  2671. tileset._maximumPriority.depth = -Number.MAX_VALUE;
  2672. tileset._minimumPriority.foveatedFactor = Number.MAX_VALUE;
  2673. tileset._maximumPriority.foveatedFactor = -Number.MAX_VALUE;
  2674. tileset._minimumPriority.distance = Number.MAX_VALUE;
  2675. tileset._maximumPriority.distance = -Number.MAX_VALUE;
  2676. tileset._minimumPriority.reverseScreenSpaceError = Number.MAX_VALUE;
  2677. tileset._maximumPriority.reverseScreenSpaceError = -Number.MAX_VALUE;
  2678. }
  2679. function detectModelMatrixChanged(tileset, frameState) {
  2680. if (
  2681. frameState.frameNumber !== tileset._updatedModelMatrixFrame ||
  2682. !defined(tileset._previousModelMatrix)
  2683. ) {
  2684. tileset._updatedModelMatrixFrame = frameState.frameNumber;
  2685. tileset._modelMatrixChanged = !Matrix4.equals(
  2686. tileset.modelMatrix,
  2687. tileset._previousModelMatrix
  2688. );
  2689. if (tileset._modelMatrixChanged) {
  2690. tileset._previousModelMatrix = Matrix4.clone(
  2691. tileset.modelMatrix,
  2692. tileset._previousModelMatrix
  2693. );
  2694. }
  2695. }
  2696. }
  2697. ///////////////////////////////////////////////////////////////////////////
  2698. function update(tileset, frameState, passStatistics, passOptions) {
  2699. if (frameState.mode === SceneMode.MORPHING) {
  2700. return false;
  2701. }
  2702. if (!tileset.ready) {
  2703. return false;
  2704. }
  2705. const statistics = tileset._statistics;
  2706. statistics.clear();
  2707. const isRender = passOptions.isRender;
  2708. // Resets the visibility check for each pass
  2709. ++tileset._updatedVisibilityFrame;
  2710. // Update any tracked min max values
  2711. resetMinimumMaximum(tileset);
  2712. detectModelMatrixChanged(tileset, frameState);
  2713. tileset._cullRequestsWhileMoving =
  2714. tileset.cullRequestsWhileMoving && !tileset._modelMatrixChanged;
  2715. const ready = passOptions.traversal.selectTiles(tileset, frameState);
  2716. if (passOptions.requestTiles) {
  2717. requestTiles(tileset);
  2718. }
  2719. updateTiles(tileset, frameState, passOptions);
  2720. // Update pass statistics
  2721. Cesium3DTilesetStatistics.clone(statistics, passStatistics);
  2722. if (isRender) {
  2723. const credits = tileset._credits;
  2724. if (defined(credits) && statistics.selected !== 0) {
  2725. const length = credits.length;
  2726. for (let i = 0; i < length; ++i) {
  2727. const credit = credits[i];
  2728. credit.showOnScreen = tileset._showCreditsOnScreen;
  2729. frameState.creditDisplay.addCredit(credit);
  2730. }
  2731. }
  2732. }
  2733. return ready;
  2734. }
  2735. /**
  2736. * @private
  2737. */
  2738. Cesium3DTileset.prototype.update = function (frameState) {
  2739. this.updateForPass(frameState, frameState.tilesetPassState);
  2740. };
  2741. /**
  2742. * @private
  2743. */
  2744. Cesium3DTileset.prototype.updateForPass = function (
  2745. frameState,
  2746. tilesetPassState
  2747. ) {
  2748. //>>includeStart('debug', pragmas.debug);
  2749. Check.typeOf.object("frameState", frameState);
  2750. Check.typeOf.object("tilesetPassState", tilesetPassState);
  2751. //>>includeEnd('debug');
  2752. const pass = tilesetPassState.pass;
  2753. if (
  2754. (pass === Cesium3DTilePass.PRELOAD &&
  2755. (!this.preloadWhenHidden || this.show)) ||
  2756. (pass === Cesium3DTilePass.PRELOAD_FLIGHT &&
  2757. (!this.preloadFlightDestinations ||
  2758. (!this.show && !this.preloadWhenHidden))) ||
  2759. (pass === Cesium3DTilePass.REQUEST_RENDER_MODE_DEFER_CHECK &&
  2760. ((!this._cullRequestsWhileMoving && this.foveatedTimeDelay <= 0) ||
  2761. !this.show))
  2762. ) {
  2763. return;
  2764. }
  2765. const originalCommandList = frameState.commandList;
  2766. const originalCamera = frameState.camera;
  2767. const originalCullingVolume = frameState.cullingVolume;
  2768. tilesetPassState.ready = false;
  2769. const passOptions = Cesium3DTilePass.getPassOptions(pass);
  2770. const ignoreCommands = passOptions.ignoreCommands;
  2771. const commandList = defaultValue(
  2772. tilesetPassState.commandList,
  2773. originalCommandList
  2774. );
  2775. const commandStart = commandList.length;
  2776. frameState.commandList = commandList;
  2777. frameState.camera = defaultValue(tilesetPassState.camera, originalCamera);
  2778. frameState.cullingVolume = defaultValue(
  2779. tilesetPassState.cullingVolume,
  2780. originalCullingVolume
  2781. );
  2782. const passStatistics = this._statisticsPerPass[pass];
  2783. if (this.show || ignoreCommands) {
  2784. this._pass = pass;
  2785. tilesetPassState.ready = update(
  2786. this,
  2787. frameState,
  2788. passStatistics,
  2789. passOptions
  2790. );
  2791. }
  2792. if (ignoreCommands) {
  2793. commandList.length = commandStart;
  2794. }
  2795. frameState.commandList = originalCommandList;
  2796. frameState.camera = originalCamera;
  2797. frameState.cullingVolume = originalCullingVolume;
  2798. };
  2799. /**
  2800. * <code>true</code> if the tileset JSON file lists the extension in extensionsUsed; otherwise, <code>false</code>.
  2801. * @param {String} extensionName The name of the extension to check.
  2802. *
  2803. * @returns {Boolean} <code>true</code> if the tileset JSON file lists the extension in extensionsUsed; otherwise, <code>false</code>.
  2804. */
  2805. Cesium3DTileset.prototype.hasExtension = function (extensionName) {
  2806. if (!defined(this._extensionsUsed)) {
  2807. return false;
  2808. }
  2809. return this._extensionsUsed.indexOf(extensionName) > -1;
  2810. };
  2811. /**
  2812. * Returns true if this object was destroyed; otherwise, false.
  2813. * <br /><br />
  2814. * If this object was destroyed, it should not be used; calling any function other than
  2815. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception.
  2816. *
  2817. * @returns {Boolean} <code>true</code> if this object was destroyed; otherwise, <code>false</code>.
  2818. *
  2819. * @see Cesium3DTileset#destroy
  2820. */
  2821. Cesium3DTileset.prototype.isDestroyed = function () {
  2822. return false;
  2823. };
  2824. /**
  2825. * Destroys the WebGL resources held by this object. Destroying an object allows for deterministic
  2826. * release of WebGL resources, instead of relying on the garbage collector to destroy this object.
  2827. * <br /><br />
  2828. * Once an object is destroyed, it should not be used; calling any function other than
  2829. * <code>isDestroyed</code> will result in a {@link DeveloperError} exception. Therefore,
  2830. * assign the return value (<code>undefined</code>) to the object as done in the example.
  2831. *
  2832. * @exception {DeveloperError} This object was destroyed, i.e., destroy() was called.
  2833. *
  2834. * @example
  2835. * tileset = tileset && tileset.destroy();
  2836. *
  2837. * @see Cesium3DTileset#isDestroyed
  2838. */
  2839. Cesium3DTileset.prototype.destroy = function () {
  2840. this._tileDebugLabels =
  2841. this._tileDebugLabels && this._tileDebugLabels.destroy();
  2842. this._clippingPlanes = this._clippingPlanes && this._clippingPlanes.destroy();
  2843. if (defined(this._schemaLoader)) {
  2844. ResourceCache.unload(this._schemaLoader);
  2845. }
  2846. // Traverse the tree and destroy all tiles
  2847. if (defined(this._root)) {
  2848. const stack = scratchStack;
  2849. stack.push(this._root);
  2850. while (stack.length > 0) {
  2851. const tile = stack.pop();
  2852. tile.destroy();
  2853. const children = tile.children;
  2854. const length = children.length;
  2855. for (let i = 0; i < length; ++i) {
  2856. stack.push(children[i]);
  2857. }
  2858. }
  2859. }
  2860. this._root = undefined;
  2861. if (
  2862. this._shouldDestroyImageBasedLighting &&
  2863. !this._imageBasedLighting.isDestroyed()
  2864. ) {
  2865. this._imageBasedLighting.destroy();
  2866. }
  2867. this._imageBasedLighting = undefined;
  2868. return destroyObject(this);
  2869. };
  2870. Cesium3DTileset.supportedExtensions = {
  2871. "3DTILES_metadata": true,
  2872. "3DTILES_implicit_tiling": true,
  2873. "3DTILES_content_gltf": true,
  2874. "3DTILES_multiple_contents": true,
  2875. "3DTILES_bounding_volume_S2": true,
  2876. "3DTILES_batch_table_hierarchy": true,
  2877. "3DTILES_draco_point_compression": true,
  2878. };
  2879. /**
  2880. * Checks to see if a given extension is supported by Cesium3DTileset. If
  2881. * the extension is not supported by Cesium3DTileset, it throws a RuntimeError.
  2882. *
  2883. * @param {Object} extensionsRequired The extensions we wish to check
  2884. *
  2885. * @private
  2886. */
  2887. Cesium3DTileset.checkSupportedExtensions = function (extensionsRequired) {
  2888. for (let i = 0; i < extensionsRequired.length; i++) {
  2889. if (!Cesium3DTileset.supportedExtensions[extensionsRequired[i]]) {
  2890. throw new RuntimeError(
  2891. `Unsupported 3D Tiles Extension: ${extensionsRequired[i]}`
  2892. );
  2893. }
  2894. }
  2895. };
  2896. /**
  2897. * Optimization option. Used as a callback when {@link Cesium3DTileset#foveatedScreenSpaceError} is true to control how much to raise the screen space error for tiles outside the foveated cone,
  2898. * interpolating between {@link Cesium3DTileset#foveatedMinimumScreenSpaceErrorRelaxation} and {@link Cesium3DTileset#maximumScreenSpaceError}.
  2899. *
  2900. * @callback Cesium3DTileset.foveatedInterpolationCallback
  2901. * @default Math.lerp
  2902. *
  2903. * @param {Number} p The start value to interpolate.
  2904. * @param {Number} q The end value to interpolate.
  2905. * @param {Number} time The time of interpolation generally in the range <code>[0.0, 1.0]</code>.
  2906. * @returns {Number} The interpolated value.
  2907. */
  2908. export default Cesium3DTileset;