Skip to content

KBE3D / KBCore / Cesium / Model

类: Model

<div class="notice"> To construct a Model, call Model.fromGltfAsync. Do not call the constructor directly. </div> A 3D model based on glTF, the runtime asset format for WebGL, OpenGL ES, and OpenGL. Cesium supports glTF assets with the following extensions: <ul> <li> AGI_articulations

</li> <li> CESIUM_primitive_outline </li> <li> CESIUM_RTC </li> <li> EXT_instance_features </li> <li> EXT_mesh_features </li> <li> EXT_mesh_gpu_instancing </li> <li> EXT_mesh_primitive_restart </li> <li> EXT_meshopt_compression </li> <li> EXT_structural_metadata </li> <li> EXT_texture_webp </li> <li> KHR_draco_mesh_compression </li> <li> KHR_techniques_webgl </li> <li> KHR_materials_common </li> <li> KHR_materials_pbrSpecularGlossiness </li> <li> KHR_materials_unlit </li> <li> KHR_mesh_quantization </li> <li> KHR_texture_basisu </li> <li> KHR_texture_transform </li> <li> WEB3D_quantized_attributes </li> <li> NGA_gpm_local (experimental) </li> </ul> <p> Note: for models with compressed textures using the KHR_texture_basisu extension, we recommend power of 2 textures in both dimensions for maximum compatibility. This is because some samplers require power of 2 textures (Using textures in WebGL) and KHR_texture_basisu requires multiple of 4 dimensions (KHR_texture_basisu additional requirements). </p>

属性

modelMatrix

modelMatrix: Matrix4

The 4x4 transformation matrix that transforms the model from model to world coordinates. When this is the identity matrix, the model is drawn in world coordinates, i.e., Earth's Cartesian WGS84 coordinates. Local reference frames can be used by providing a different transformation matrix, like that returned by Transforms.eastNorthUpToFixedFrame.

示例

ts
const origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
m.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);

showOutline

showOutline: boolean

Whether to display the outline for models using the CESIUM_primitive_outline

extension. When true, outlines are displayed. When false, outlines are not displayed.


outlineColor

outlineColor: Color

The color to use when rendering outlines.


ready

readonly ready: boolean

When <code>true</code>, this model is ready to render, i.e., the external binary, image, and shader files were downloaded and the WebGL resources were created.


errorEvent

readonly errorEvent: Event

Gets an event that is raised when the model encounters an asynchronous rendering error. By subscribing to the event, you will be notified of the error and can potentially recover from it. Event listeners are passed an instance of ModelError.


readyEvent

readonly readyEvent: Event

Gets an event that is raised when the model is loaded and ready for rendering, i.e. when the external resources have been downloaded and the WebGL resources are created. Event listeners are passed an instance of the Model.

<p> If Model.incrementallyLoadTextures is true, this event will be raised before all textures are loaded and ready for rendering. Subscribe to Model.texturesReadyEvent to be notified when the textures are ready. </p>


texturesReadyEvent

readonly texturesReadyEvent: Event

Gets an event that, if Model.incrementallyLoadTextures is true, is raised when the model textures are loaded and ready for rendering, i.e. when the external resources have been downloaded and the WebGL resources are created. Event listeners are passed an instance of the Model.


activeAnimations

readonly activeAnimations: ModelAnimationCollection

The currently playing glTF animations.


clampAnimations

clampAnimations: boolean

Determines if the model's animations should hold a pose over frames where no keyframes are specified.


pointCloudShading

pointCloudShading: PointCloudShading

Point cloud shading settings for controlling point cloud attenuation and lighting. For 3D Tiles, this is inherited from the Cesium3DTileset.


customShader

customShader: CustomShader

The model's custom shader, if it exists. Using custom shaders with a Cesium3DTileStyle may lead to undefined behavior.


heightReference

heightReference: HeightReference

The height reference of the model, which determines how the model is drawn relative to terrain.


distanceDisplayCondition

distanceDisplayCondition: DistanceDisplayCondition

Gets or sets the distance display condition, which specifies at what distance from the camera this model will be displayed.


id

id: any

A user-defined object that is returned when the model is picked.


style

style: Cesium3DTileStyle

The style to apply to the features in the model. Cannot be applied if a CustomShader is also applied.


color

color: Color

The color to blend with the model's rendered color.


colorBlendMode

colorBlendMode: Cesium3DTileColorBlendMode | ColorBlendMode

Defines how the color blends with the model.


colorBlendAmount

colorBlendAmount: number

Value used to determine the color strength when the <code>colorBlendMode</code> is <code>MIX</code>. A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with any value in-between resulting in a mix of the two.


silhouetteColor

silhouetteColor: Color

The silhouette color.


silhouetteSize

silhouetteSize: number

The size of the silhouette in pixels.


boundingSphere

readonly boundingSphere: BoundingSphere

Gets the model's bounding sphere in world space. This does not take into account glTF animations, skins, or morph targets. It also does not account for Model#minimumPixelSize.


debugShowBoundingVolume

debugShowBoundingVolume: boolean

This property is for debugging only; it is not for production use nor is it optimized. <p> Draws the bounding sphere for each draw command in the model. </p>


debugWireframe

debugWireframe: boolean

This property is for debugging only; it is not for production use nor is it optimized. <p> Draws the model in wireframe. </p>


show

show: boolean

Whether or not to render the model.


featureIdLabel

featureIdLabel: string

Label of the feature ID set to use for picking and styling. <p> 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. </p> <p> If featureIdLabel is set to 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. </p>


instanceFeatureIdLabel

instanceFeatureIdLabel: string

Label of the instance feature ID set used for picking and styling. <p> 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. </p>


clippingPlanes

clippingPlanes: ClippingPlaneCollection

The ClippingPlaneCollection used to selectively disable rendering the model.


clippingPolygons

clippingPolygons: ClippingPolygonCollection

The ClippingPolygonCollection used to selectively disable rendering the model.


enableVerticalExaggeration

enableVerticalExaggeration: boolean

If <code>true</code>, the model is exaggerated along the ellipsoid normal when Scene.verticalExaggeration is set to a value other than <code>1.0</code>.

示例

ts
// Exaggerate terrain by a factor of 2, but prevent model exaggeration
scene.verticalExaggeration = 2.0;
model.enableVerticalExaggeration = false;

lightColor

lightColor: Cartesian3

The directional light color when shading the model. When <code>undefined</code> the scene's light color is used instead. <p> Disabling additional light sources by setting <code>model.imageBasedLighting.imageBasedLightingFactor = new Cartesian2(0.0, 0.0)</code> will make the model much darker. Here, increasing the intensity of the light source will make the model brighter. </p>


imageBasedLighting

imageBasedLighting: ImageBasedLighting

The properties for managing image-based lighting on this model.


environmentMapManager

readonly environmentMapManager: DynamicEnvironmentMapManager

The properties for managing dynamic environment maps on this model. Affects lighting.

示例

ts
// Change the ground color used for a model's environment map to a forest green
const environmentMapManager = model.environmentMapManager;
environmentMapManager.groundColor = Cesium.Color.fromCssColorString("#203b34");

backFaceCulling

backFaceCulling: boolean

Whether to cull back-facing geometry. When true, back face culling is determined by the material's doubleSided property; when false, back face culling is disabled. Back faces are not culled if Model#color is translucent or Model#silhouetteSize is greater than 0.0.


scale

scale: number

A uniform scale applied to this model before the Model#modelMatrix. Values greater than <code>1.0</code> increase the size of the model; values less than <code>1.0</code> decrease.


minimumPixelSize

minimumPixelSize: number

The approximate minimum pixel size of the model regardless of zoom. This can be used to ensure that a model is visible even when the viewer zooms out. When <code>0.0</code>, no minimum size is enforced.


maximumScale

maximumScale: number

The maximum scale size for a model. This can be used to give an upper limit to the Model#minimumPixelSize, ensuring that the model is never an unreasonable scale.


shadows

shadows: ShadowMode

Determines whether the model casts or receives shadows from light sources.


credit

readonly credit: Credit

Gets the credit that will be displayed for the model.


showCreditsOnScreen

showCreditsOnScreen: boolean

Gets or sets whether the credits of the model will be displayed on the screen.


splitDirection

splitDirection: SplitDirection

The SplitDirection to apply to this model.


classificationType

readonly classificationType: ClassificationType

Gets the model's classification type. This determines whether terrain, 3D Tiles, or both will be classified by this model. <p> Additionally, there are a few requirements/limitations: <ul> <li>The glTF cannot contain morph targets, skins, or animations.</li> <li>The glTF cannot contain the <code>EXT_mesh_gpu_instancing</code> extension.</li> <li>Only meshes with TRIANGLES can be used to classify other assets.</li> <li>The meshes must be watertight.</li> <li>The POSITION attribute is required.</li> <li>If feature IDs and an index buffer are both present, all indices with the same feature id must occupy contiguous sections of the index buffer.</li> <li>If feature IDs are present without an index buffer, all positions with the same feature id must occupy contiguous sections of the position buffer.</li> </ul> </p> <p> The 3D Tiles or terrain receiving the classification must be opaque. </p>

方法

fromGltfAsync()

static fromGltfAsync(options: { url: string | Resource; basePath?: string | Resource; show?: boolean; modelMatrix?: Matrix4; scale?: number; enableVerticalExaggeration?: boolean; minimumPixelSize?: number; maximumScale?: number; id?: any; allowPicking?: boolean; incrementallyLoadTextures?: boolean; asynchronous?: boolean; clampAnimations?: boolean; shadows?: ShadowMode; releaseGltfJson?: boolean; debugShowBoundingVolume?: boolean; enableDebugWireframe?: boolean; debugWireframe?: boolean; cull?: boolean; opaquePass?: boolean; upAxis?: Axis; forwardAxis?: Axis; customShader?: CustomShader; content?: Cesium3DTileContent; heightReference?: HeightReference; scene?: Scene; distanceDisplayCondition?: DistanceDisplayCondition; color?: Color; colorBlendMode?: ColorBlendMode; colorBlendAmount?: number; silhouetteColor?: Color; silhouetteSize?: number; enableShowOutline?: boolean; showOutline?: boolean; outlineColor?: Color; clippingPlanes?: ClippingPlaneCollection; clippingPolygons?: ClippingPolygonCollection; lightColor?: Cartesian3; imageBasedLighting?: ImageBasedLighting; environmentMapOptions?: ConstructorOptions; backFaceCulling?: boolean; credit?: string | Credit; showCreditsOnScreen?: boolean; splitDirection?: SplitDirection; projectTo2D?: boolean; enablePick?: boolean; featureIdLabel?: string | number; instanceFeatureIdLabel?: string | number; pointCloudShading?: any; classificationType?: ClassificationType; gltfCallback?: GltfCallback; }): Promise<Model>

<p> Asynchronously creates a model from a glTF asset. This function returns a promise that resolves when the model is ready to render, i.e., when the external binary, image, and shader files are downloaded and the WebGL resources are created. </p> <p> The model can be a traditional glTF asset with a .gltf extension or a Binary glTF using the .glb extension.

参数

options

Object with the following properties:

url

string | Resource

The url to the .gltf or .glb file.

basePath?

string | Resource

The base path that paths in the glTF JSON are relative to.

show?

boolean

Whether or not to render the model.

modelMatrix?

Matrix4

The 4x4 transformation matrix that transforms the model from model to world coordinates.

scale?

number

A uniform scale applied to this model.

enableVerticalExaggeration?

boolean

If <code>true</code>, the model is exaggerated along the ellipsoid normal when Scene.verticalExaggeration is set to a value other than <code>1.0</code>.

minimumPixelSize?

number

The approximate minimum pixel size of the model regardless of zoom.

maximumScale?

number

The maximum scale size of a model. An upper limit for minimumPixelSize.

id?

any

A user-defined object to return when the model is picked with Scene#pick.

allowPicking?

boolean

When <code>true</code>, each primitive is pickable with Scene#pick.

incrementallyLoadTextures?

boolean

Determine if textures may continue to stream in after the model is loaded.

asynchronous?

boolean

Determines if model WebGL resource creation will be spread out over several frames or block until completion once all glTF files are loaded.

clampAnimations?

boolean

Determines if the model's animations should hold a pose over frames where no keyframes are specified.

shadows?

ShadowMode

Determines whether the model casts or receives shadows from light sources.

releaseGltfJson?

boolean

When true, the glTF JSON is released once the glTF is loaded. This is is especially useful for cases like 3D Tiles, where each .gltf model is unique and caching the glTF JSON is not effective.

debugShowBoundingVolume?

boolean

For debugging only. Draws the bounding sphere for each draw command in the model.

enableDebugWireframe?

boolean

For debugging only. This must be set to true for debugWireframe to work in WebGL1. This cannot be set after the model has loaded.

debugWireframe?

boolean

For debugging only. Draws the model in wireframe. Will only work for WebGL1 if enableDebugWireframe is set to true.

cull?

boolean

Whether or not to cull the model using frustum/horizon culling. If the model is part of a 3D Tiles tileset, this property will always be false, since the 3D Tiles culling system is used.

opaquePass?

boolean

The pass to use in the DrawCommand for the opaque portions of the model.

upAxis?

Axis

The up-axis of the glTF model.

forwardAxis?

Axis

The forward-axis of the glTF model.

customShader?

CustomShader

A custom shader. This will add user-defined GLSL code to the vertex and fragment shaders. Using custom shaders with a Cesium3DTileStyle may lead to undefined behavior.

content?

Cesium3DTileContent

The tile content this model belongs to. This property will be undefined if model is not loaded as part of a tileset.

heightReference?

HeightReference

Determines how the model is drawn relative to terrain.

scene?

Scene

Must be passed in for models that use the height reference property.

distanceDisplayCondition?

DistanceDisplayCondition

The condition specifying at what distance from the camera that this model will be displayed.

color?

Color

A color that blends with the model's rendered color.

colorBlendMode?

ColorBlendMode

Defines how the color blends with the model.

colorBlendAmount?

number

Value used to determine the color strength when the <code>colorBlendMode</code> is <code>MIX</code>. A value of 0.0 results in the model's rendered color while a value of 1.0 results in a solid color, with any value in-between resulting in a mix of the two.

silhouetteColor?

Color

The silhouette color. If more than 256 models have silhouettes enabled, there is a small chance that overlapping models will have minor artifacts.

silhouetteSize?

number

The size of the silhouette in pixels.

enableShowOutline?

boolean

Whether to enable outlines for models using the CESIUM_primitive_outline

extension. This can be set false to avoid post-processing geometry at load time. When false, the showOutlines and outlineColor options are ignored.

showOutline?

boolean

Whether to display the outline for models using the CESIUM_primitive_outline

extension. When true, outlines are displayed. When false, outlines are not displayed.

outlineColor?

Color

The color to use when rendering outlines.

clippingPlanes?

ClippingPlaneCollection

The ClippingPlaneCollection used to selectively disable rendering the model.

clippingPolygons?

ClippingPolygonCollection

The ClippingPolygonCollection used to selectively disable rendering the model.

lightColor?

Cartesian3

The light color when shading the model. When <code>undefined</code> the scene's light color is used instead.

imageBasedLighting?

ImageBasedLighting

The properties for managing image-based lighting on this model.

environmentMapOptions?

ConstructorOptions

The properties for managing dynamic environment maps on this model.

backFaceCulling?

boolean

Whether to cull back-facing geometry. When true, back face culling is determined by the material's doubleSided property; when false, back face culling is disabled. Back faces are not culled if the model's color is translucent.

credit?

string | Credit

A credit for the data source, which is displayed on the canvas.

showCreditsOnScreen?

boolean

Whether to display the credits of this model on screen.

splitDirection?

SplitDirection

The SplitDirection split to apply to this model.

projectTo2D?

boolean

Whether to accurately project the model's positions in 2D. If this is true, the model will be projected accurately to 2D, but it will use more memory to do so. If this is false, the model will use less memory and will still render in 2D / CV mode, but its positions may be inaccurate. This disables minimumPixelSize and prevents future modification to the model matrix. This also cannot be set after the model has loaded.

enablePick?

boolean

Whether to allow with CPU picking with <code>pick</code> when not using WebGL 2 or above. If using WebGL 2 or above, this option will be ignored. If using WebGL 1 and this is true, the <code>pick</code> operation will work correctly, but it will use more memory to do so. If running with WebGL 1 and this is false, the model will use less memory, but <code>pick</code> will always return <code>undefined</code>. This cannot be set after the model has loaded.

featureIdLabel?

string | number

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.

instanceFeatureIdLabel?

string | number

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.

pointCloudShading?

any

Options for constructing a PointCloudShading object to control point attenuation and lighting.

classificationType?

ClassificationType

Determines whether terrain, 3D Tiles or both will be classified by this model. This cannot be set after the model has loaded.

gltfCallback?

GltfCallback

A function that is called with the loaded gltf object once loaded.

返回

Promise<Model>

A promise that resolves to the created model when it is ready to render.

Examples

ts
// Load a model and add it to the scene
try {
 const model = await Cesium.Model.fromGltfAsync({
   url: "../../SampleData/models/CesiumMan/Cesium_Man.glb"
 });
 viewer.scene.primitives.add(model);
} catch (error) {
 console.log(`Failed to load model. ${error}`);
}
ts
// Position a model with modelMatrix and display it with a minimum size of 128 pixels
const position = Cesium.Cartesian3.fromDegrees(
  -123.0744619,
  44.0503706,
  5000.0
);
const headingPositionRoll = new Cesium.HeadingPitchRoll();
const fixedFrameTransform = Cesium.Transforms.localFrameToFixedFrameGenerator(
  "north",
  "west"
);
try {
 const model = await Cesium.Model.fromGltfAsync({
   url: "../../SampleData/models/CesiumAir/Cesium_Air.glb",
   modelMatrix: Cesium.Transforms.headingPitchRollToFixedFrame(
     position,
     headingPositionRoll,
     Cesium.Ellipsoid.WGS84,
     fixedFrameTransform
   ),
   minimumPixelSize: 128,
 });
 viewer.scene.primitives.add(model);
} catch (error) {
 console.log(`Failed to load model. ${error}`);
}
ts
// Load a model and play the last animation at half speed
let animations;
try {
 const model = await Cesium.Model.fromGltfAsync({
   url: "../../SampleData/models/CesiumMan/Cesium_Man.glb",
   gltfCallback: gltf => {
     animations = gltf.animations
   }
 });
 viewer.scene.primitives.add(model);
 model.readyEvent.addEventListener(() => {
   model.activeAnimations.add({
     index: animations.length - 1,
     loop: Cesium.ModelAnimationLoop.REPEAT,
     multiplier: 0.5,
   });
 });
} catch (error) {
 console.log(`Failed to load model. ${error}`);
}

getNode()

getNode(name: string): ModelNode

Returns the node with the given <code>name</code> in the glTF. This is used to modify a node's transform for user-defined animation.

参数

name

string

The name of the node in the glTF.

返回

ModelNode

The node, or undefined if no node with the name exists.

示例

ts
// Apply non-uniform scale to node "Hand"
const node = model.getNode("Hand");
node.matrix = Cesium.Matrix4.fromScale(new Cesium.Cartesian3(5.0, 1.0, 1.0), node.matrix);

setArticulationStage()

setArticulationStage(articulationStageKey: string, value: number): void

Sets the current value of an articulation stage. After setting one or multiple stage values, call Model.applyArticulations() to cause the node matrices to be recalculated.

参数

articulationStageKey

string

The name of the articulation, a space, and the name of the stage.

value

number

The numeric value of this stage of the articulation.

返回

void

示例

ts
// Sets the value of the stage named "MoveX" belonging to the articulation named "SampleArticulation"
model.setArticulationStage("SampleArticulation MoveX", 50.0);

applyArticulations()

applyArticulations(): void

Applies any modified articulation stages to the matrix of each node that participates in any articulation. Note that this will overwrite any node transformations on participating nodes.

返回

void


getExtension()

getExtension(extensionName: string): any

Returns the object that was created for the given extension.

The given name may be the name of a glTF extension, like "EXT_example_extension". If the specified extension was present in the root of the underlying glTF asset, and a loader for the specified extension has processed the extension data, then this will return the model representation of the extension.

参数

extensionName

string

The name of the extension

返回

any

The object, or undefined


makeStyleDirty()

makeStyleDirty(): void

Marks the model's Model#style as dirty, which forces all features to re-evaluate the style in the next frame the model is visible.

返回

void


update()

update(): void

Called when Viewer or CesiumWidget render the scene to get the draw commands needed to render this primitive. <p> Do not call this function directly. This is documented just to list the exceptions that may be propagated when the scene is rendered: </p>

返回

void


isDestroyed()

isDestroyed(): boolean

Returns true if this object was destroyed; otherwise, false. <br /><br /> If this object was destroyed, it should not be used; calling any function other than <code>isDestroyed</code> will result in a DeveloperError exception.

返回

boolean

true if this object was destroyed; otherwise, false.


destroy()

destroy(): void

Destroys the WebGL resources held by this object. Destroying an object allows for deterministic release of WebGL resources, instead of relying on the garbage collector to destroy this object. <br /><br /> Once an object is destroyed, it should not be used; calling any function other than <code>isDestroyed</code> will result in a DeveloperError exception. Therefore, assign the return value (<code>undefined</code>) to the object as done in the example.

返回

void

示例

ts
model = model && model.destroy();

构造函数

构造函数

new Model(): Model

返回

Model

KBE3D @3.0.0 Copyright © 2024-present KBE3D