cesium
Version:
CesiumJS is a JavaScript library for creating 3D globes and 2D maps in a web browser without a plugin.
1,226 lines (1,127 loc) • 202 kB
JavaScript
define([
'../Core/BoundingSphere',
'../Core/Cartesian2',
'../Core/Cartesian3',
'../Core/Cartesian4',
'../Core/Cartographic',
'../Core/clone',
'../Core/Color',
'../Core/combine',
'../Core/defaultValue',
'../Core/defined',
'../Core/defineProperties',
'../Core/destroyObject',
'../Core/DeveloperError',
'../Core/DistanceDisplayCondition',
'../Core/FeatureDetection',
'../Core/getAbsoluteUri',
'../Core/getMagic',
'../Core/getStringFromTypedArray',
'../Core/IndexDatatype',
'../Core/loadCRN',
'../Core/loadImageFromTypedArray',
'../Core/loadKTX',
'../Core/Math',
'../Core/Matrix2',
'../Core/Matrix3',
'../Core/Matrix4',
'../Core/PixelFormat',
'../Core/Plane',
'../Core/PrimitiveType',
'../Core/Quaternion',
'../Core/Queue',
'../Core/Resource',
'../Core/RuntimeError',
'../Core/Transforms',
'../Core/WebGLConstants',
'../Renderer/Buffer',
'../Renderer/BufferUsage',
'../Renderer/DrawCommand',
'../Renderer/Pass',
'../Renderer/RenderState',
'../Renderer/Sampler',
'../Renderer/ShaderProgram',
'../Renderer/ShaderSource',
'../Renderer/Texture',
'../Renderer/TextureMinificationFilter',
'../Renderer/TextureWrap',
'../Renderer/VertexArray',
'../ThirdParty/GltfPipeline/addDefaults',
'../ThirdParty/GltfPipeline/addPipelineExtras',
'../ThirdParty/GltfPipeline/ForEach',
'../ThirdParty/GltfPipeline/getAccessorByteStride',
'../ThirdParty/GltfPipeline/numberOfComponentsForType',
'../ThirdParty/GltfPipeline/parseBinaryGltf',
'../ThirdParty/GltfPipeline/processModelMaterialsCommon',
'../ThirdParty/GltfPipeline/processPbrMetallicRoughness',
'../ThirdParty/GltfPipeline/updateVersion',
'../ThirdParty/Uri',
'../ThirdParty/when',
'./AttributeType',
'./Axis',
'./BlendingState',
'./ClippingPlaneCollection',
'./ColorBlendMode',
'./DracoLoader',
'./getClipAndStyleCode',
'./getClippingFunction',
'./HeightReference',
'./JobType',
'./ModelAnimationCache',
'./ModelAnimationCollection',
'./ModelLoadResources',
'./ModelMaterial',
'./ModelMesh',
'./ModelNode',
'./ModelUtility',
'./SceneMode',
'./ShadowMode'
], function(
BoundingSphere,
Cartesian2,
Cartesian3,
Cartesian4,
Cartographic,
clone,
Color,
combine,
defaultValue,
defined,
defineProperties,
destroyObject,
DeveloperError,
DistanceDisplayCondition,
FeatureDetection,
getAbsoluteUri,
getMagic,
getStringFromTypedArray,
IndexDatatype,
loadCRN,
loadImageFromTypedArray,
loadKTX,
CesiumMath,
Matrix2,
Matrix3,
Matrix4,
PixelFormat,
Plane,
PrimitiveType,
Quaternion,
Queue,
Resource,
RuntimeError,
Transforms,
WebGLConstants,
Buffer,
BufferUsage,
DrawCommand,
Pass,
RenderState,
Sampler,
ShaderProgram,
ShaderSource,
Texture,
TextureMinificationFilter,
TextureWrap,
VertexArray,
addDefaults,
addPipelineExtras,
ForEach,
getAccessorByteStride,
numberOfComponentsForType,
parseBinaryGltf,
processModelMaterialsCommon,
processPbrMetallicRoughness,
updateVersion,
Uri,
when,
AttributeType,
Axis,
BlendingState,
ClippingPlaneCollection,
ColorBlendMode,
DracoLoader,
getClipAndStyleCode,
getClippingFunction,
HeightReference,
JobType,
ModelAnimationCache,
ModelAnimationCollection,
ModelLoadResources,
ModelMaterial,
ModelMesh,
ModelNode,
ModelUtility,
SceneMode,
ShadowMode) {
'use strict';
// Bail out if the browser doesn't support typed arrays, to prevent the setup function
// from failing, since we won't be able to create a WebGL context anyway.
if (!FeatureDetection.supportsTypedArrays()) {
return {};
}
var boundingSphereCartesian3Scratch = new Cartesian3();
var ModelState = {
NEEDS_LOAD : 0,
LOADING : 1,
LOADED : 2, // Renderable, but textures can still be pending when incrementallyLoadTextures is true.
FAILED : 3
};
// glTF MIME types discussed in https://github.com/KhronosGroup/glTF/issues/412 and https://github.com/KhronosGroup/glTF/issues/943
var defaultModelAccept = 'model/gltf-binary,model/gltf+json;q=0.8,application/json;q=0.2,*/*;q=0.01';
///////////////////////////////////////////////////////////////////////////
function setCachedGltf(model, cachedGltf) {
model._cachedGltf = cachedGltf;
}
// glTF JSON can be big given embedded geometry, textures, and animations, so we
// cache it across all models using the same url/cache-key. This also reduces the
// slight overhead in assigning defaults to missing values.
//
// Note that this is a global cache, compared to renderer resources, which
// are cached per context.
function CachedGltf(options) {
this._gltf = options.gltf;
this.ready = options.ready;
this.modelsToLoad = [];
this.count = 0;
}
defineProperties(CachedGltf.prototype, {
gltf : {
set : function(value) {
this._gltf = value;
},
get : function() {
return this._gltf;
}
}
});
CachedGltf.prototype.makeReady = function(gltfJson) {
this.gltf = gltfJson;
var models = this.modelsToLoad;
var length = models.length;
for (var i = 0; i < length; ++i) {
var m = models[i];
if (!m.isDestroyed()) {
setCachedGltf(m, this);
}
}
this.modelsToLoad = undefined;
this.ready = true;
};
var gltfCache = {};
///////////////////////////////////////////////////////////////////////////
/**
* A 3D model based on glTF, the runtime asset format for WebGL, OpenGL ES, and OpenGL.
* <p>
* Cesium includes support for geometry and materials, glTF animations, and glTF skinning.
* In addition, individual glTF nodes are pickable with {@link Scene#pick} and animatable
* with {@link Model#getNode}. glTF cameras and lights are not currently supported.
* </p>
* <p>
* An external glTF asset is created with {@link Model.fromGltf}. glTF JSON can also be
* created at runtime and passed to this constructor function. In either case, the
* {@link Model#readyPromise} is resolved 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>
* Cesium supports glTF assets with the following extensions:
* <ul>
* <li>
* {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Khronos/KHR_binary_glTF/README.md|KHR_binary_glTF}
* </li><li>
* {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Khronos/KHR_materials_common/README.md|KHR_materials_common}
* </li><li>
* {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Vendor/WEB3D_quantized_attributes/README.md|WEB3D_quantized_attributes}
* </li><li>
* {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_draco_mesh_compression/README.md|KHR_draco_mesh_compression}
* </li>
* </ul>
* </p>
* <p>
* For high-precision rendering, Cesium supports the {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Vendor/CESIUM_RTC/README.md|CESIUM_RTC} extension, which introduces the
* CESIUM_RTC_MODELVIEW parameter semantic that says the node is in WGS84 coordinates translated
* relative to a local origin.
* </p>
*
* @alias Model
* @constructor
*
* @param {Object} [options] Object with the following properties:
* @param {Object|ArrayBuffer|Uint8Array} [options.gltf] The object for the glTF JSON or an arraybuffer of Binary glTF defined by the KHR_binary_glTF extension.
* @param {Resource|String} [options.basePath=''] The base path that paths in the glTF JSON are relative to.
* @param {Boolean} [options.show=true] Determines if the model primitive will be shown.
* @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the model from model to world coordinates.
* @param {Number} [options.scale=1.0] A uniform scale applied to this model.
* @param {Number} [options.minimumPixelSize=0.0] The approximate minimum pixel size of the model regardless of zoom.
* @param {Number} [options.maximumScale] The maximum scale size of a model. An upper limit for minimumPixelSize.
* @param {Object} [options.id] A user-defined object to return when the model is picked with {@link Scene#pick}.
* @param {Boolean} [options.allowPicking=true] When <code>true</code>, each glTF mesh and primitive is pickable with {@link Scene#pick}.
* @param {Boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the model is loaded.
* @param {Boolean} [options.asynchronous=true] Determines if model WebGL resource creation will be spread out over several frames or block until completion once all glTF files are loaded.
* @param {Boolean} [options.clampAnimations=true] Determines if the model's animations should hold a pose over frames where no keyframes are specified.
* @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the model casts or receives shadows from each light source.
* @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for each draw command in the model.
* @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the model in wireframe.
* @param {HeightReference} [options.heightReference] Determines how the model is drawn relative to terrain.
* @param {Scene} [options.scene] Must be passed in for models that use the height reference property.
* @param {DistanceDisplayCondition} [options.distanceDisplayCondition] The condition specifying at what distance from the camera that this model will be displayed.
* @param {Color} [options.color=Color.WHITE] A color that blends with the model's rendered color.
* @param {ColorBlendMode} [options.colorBlendMode=ColorBlendMode.HIGHLIGHT] Defines how the color blends with the model.
* @param {Number} [options.colorBlendAmount=0.5] 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.
* @param {Color} [options.silhouetteColor=Color.RED] The silhouette color. If more than 256 models have silhouettes enabled, there is a small chance that overlapping models will have minor artifacts.
* @param {Number} [options.silhouetteSize=0.0] The size of the silhouette in pixels.
* @param {ClippingPlaneCollection} [options.clippingPlanes] The {@link ClippingPlaneCollection} used to selectively disable rendering the model.
* @param {Boolean} [options.dequantizeInShader=true] Determines if a {@link https://github.com/google/draco|Draco} encoded model is dequantized on the GPU. This decreases total memory usage for encoded models.
*
* @exception {DeveloperError} bgltf is not a valid Binary glTF file.
* @exception {DeveloperError} Only glTF Binary version 1 is supported.
*
* @see Model.fromGltf
*
* @demo {@link https://cesiumjs.org/Cesium/Apps/Sandcastle/index.html?src=3D%20Models.html|Cesium Sandcastle Models Demo}
*/
function Model(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
var cacheKey = options.cacheKey;
this._cacheKey = cacheKey;
this._cachedGltf = undefined;
this._releaseGltfJson = defaultValue(options.releaseGltfJson, false);
var cachedGltf;
if (defined(cacheKey) && defined(gltfCache[cacheKey]) && gltfCache[cacheKey].ready) {
// glTF JSON is in cache and ready
cachedGltf = gltfCache[cacheKey];
++cachedGltf.count;
} else {
// glTF was explicitly provided, e.g., when a user uses the Model constructor directly
var gltf = options.gltf;
if (defined(gltf)) {
if (gltf instanceof ArrayBuffer) {
gltf = new Uint8Array(gltf);
}
if (gltf instanceof Uint8Array) {
// Binary glTF
var parsedGltf = parseBinaryGltf(gltf);
cachedGltf = new CachedGltf({
gltf : parsedGltf,
ready : true
});
} else {
// Normal glTF (JSON)
cachedGltf = new CachedGltf({
gltf : options.gltf,
ready : true
});
}
cachedGltf.count = 1;
if (defined(cacheKey)) {
gltfCache[cacheKey] = cachedGltf;
}
}
}
setCachedGltf(this, cachedGltf);
var basePath = defaultValue(options.basePath, '');
this._resource = Resource.createIfNeeded(basePath);
/**
* Determines if the model primitive will be shown.
*
* @type {Boolean}
*
* @default true
*/
this.show = defaultValue(options.show, true);
/**
* The silhouette color.
*
* @type {Color}
*
* @default Color.RED
*/
this.silhouetteColor = defaultValue(options.silhouetteColor, Color.RED);
this._silhouetteColor = new Color();
this._silhouetteColorPreviousAlpha = 1.0;
this._normalAttributeName = undefined;
/**
* The size of the silhouette in pixels.
*
* @type {Number}
*
* @default 0.0
*/
this.silhouetteSize = defaultValue(options.silhouetteSize, 0.0);
/**
* 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 WGS84 coordinates.
* Local reference frames can be used by providing a different transformation matrix, like that returned
* by {@link Transforms.eastNorthUpToFixedFrame}.
*
* @type {Matrix4}
*
* @default {@link Matrix4.IDENTITY}
*
* @example
* var origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
* m.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
*/
this.modelMatrix = Matrix4.clone(defaultValue(options.modelMatrix, Matrix4.IDENTITY));
this._modelMatrix = Matrix4.clone(this.modelMatrix);
this._clampedModelMatrix = undefined;
/**
* A uniform scale applied to this model before the {@link Model#modelMatrix}.
* Values greater than <code>1.0</code> increase the size of the model; values
* less than <code>1.0</code> decrease.
*
* @type {Number}
*
* @default 1.0
*/
this.scale = defaultValue(options.scale, 1.0);
this._scale = this.scale;
/**
* 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.
*
* @type {Number}
*
* @default 0.0
*/
this.minimumPixelSize = defaultValue(options.minimumPixelSize, 0.0);
this._minimumPixelSize = this.minimumPixelSize;
/**
* The maximum scale size for a model. This can be used to give
* an upper limit to the {@link Model#minimumPixelSize}, ensuring that the model
* is never an unreasonable scale.
*
* @type {Number}
*/
this.maximumScale = options.maximumScale;
this._maximumScale = this.maximumScale;
/**
* User-defined object returned when the model is picked.
*
* @type Object
*
* @default undefined
*
* @see Scene#pick
*/
this.id = options.id;
this._id = options.id;
/**
* Returns the height reference of the model
*
* @memberof Model.prototype
*
* @type {HeightReference}
*
* @default HeightReference.NONE
*/
this.heightReference = defaultValue(options.heightReference, HeightReference.NONE);
this._heightReference = this.heightReference;
this._heightChanged = false;
this._removeUpdateHeightCallback = undefined;
var scene = options.scene;
this._scene = scene;
if (defined(scene) && defined(scene.terrainProviderChanged)) {
this._terrainProviderChangedCallback = scene.terrainProviderChanged.addEventListener(function() {
this._heightChanged = true;
}, this);
}
/**
* Used for picking primitives that wrap a model.
*
* @private
*/
this._pickObject = options.pickObject;
this._allowPicking = defaultValue(options.allowPicking, true);
this._ready = false;
this._readyPromise = when.defer();
/**
* The currently playing glTF animations.
*
* @type {ModelAnimationCollection}
*/
this.activeAnimations = new ModelAnimationCollection(this);
/**
* Determines if the model's animations should hold a pose over frames where no keyframes are specified.
*
* @type {Boolean}
*/
this.clampAnimations = defaultValue(options.clampAnimations, true);
this._defaultTexture = undefined;
this._incrementallyLoadTextures = defaultValue(options.incrementallyLoadTextures, true);
this._asynchronous = defaultValue(options.asynchronous, true);
/**
* Determines whether the model casts or receives shadows from each light source.
*
* @type {ShadowMode}
*
* @default ShadowMode.ENABLED
*/
this.shadows = defaultValue(options.shadows, ShadowMode.ENABLED);
this._shadows = this.shadows;
/**
* A color that blends with the model's rendered color.
*
* @type {Color}
*
* @default Color.WHITE
*/
this.color = defaultValue(options.color, Color.WHITE);
this._color = new Color();
this._colorPreviousAlpha = 1.0;
this._hasPremultipliedAlpha = false;
/**
* Defines how the color blends with the model.
*
* @type {ColorBlendMode}
*
* @default ColorBlendMode.HIGHLIGHT
*/
this.colorBlendMode = defaultValue(options.colorBlendMode, ColorBlendMode.HIGHLIGHT);
/**
* 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.
*
* @type {Number}
*
* @default 0.5
*/
this.colorBlendAmount = defaultValue(options.colorBlendAmount, 0.5);
this._colorShadingEnabled = false;
this._clippingPlanes = undefined;
this.clippingPlanes = options.clippingPlanes;
// Used for checking if shaders need to be regenerated due to clipping plane changes.
this._clippingPlanesState = 0;
/**
* 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. A glTF primitive corresponds
* to one draw command. A glTF mesh has an array of primitives, often of length one.
* </p>
*
* @type {Boolean}
*
* @default false
*/
this.debugShowBoundingVolume = defaultValue(options.debugShowBoundingVolume, false);
this._debugShowBoundingVolume = false;
/**
* This property is for debugging only; it is not for production use nor is it optimized.
* <p>
* Draws the model in wireframe.
* </p>
*
* @type {Boolean}
*
* @default false
*/
this.debugWireframe = defaultValue(options.debugWireframe, false);
this._debugWireframe = false;
this._distanceDisplayCondition = options.distanceDisplayCondition;
// Undocumented options
this._addBatchIdToGeneratedShaders = options.addBatchIdToGeneratedShaders;
this._precreatedAttributes = options.precreatedAttributes;
this._vertexShaderLoaded = options.vertexShaderLoaded;
this._fragmentShaderLoaded = options.fragmentShaderLoaded;
this._uniformMapLoaded = options.uniformMapLoaded;
this._pickVertexShaderLoaded = options.pickVertexShaderLoaded;
this._pickFragmentShaderLoaded = options.pickFragmentShaderLoaded;
this._pickUniformMapLoaded = options.pickUniformMapLoaded;
this._ignoreCommands = defaultValue(options.ignoreCommands, false);
this._requestType = options.requestType;
this._upAxis = defaultValue(options.upAxis, Axis.Y);
/**
* @private
* @readonly
*/
this.cull = defaultValue(options.cull, true);
/**
* @private
* @readonly
*/
this.opaquePass = defaultValue(options.opaquePass, Pass.OPAQUE);
this._computedModelMatrix = new Matrix4(); // Derived from modelMatrix and scale
this._modelViewMatrix = Matrix4.clone(Matrix4.IDENTITY); // Derived from modelMatrix, scale, and the current view matrix
this._initialRadius = undefined; // Radius without model's scale property, model-matrix scale, animations, or skins
this._boundingSphere = undefined;
this._scaledBoundingSphere = new BoundingSphere();
this._state = ModelState.NEEDS_LOAD;
this._loadResources = undefined;
this._mode = undefined;
this._perNodeShowDirty = false; // true when the Cesium API was used to change a node's show property
this._cesiumAnimationsDirty = false; // true when the Cesium API, not a glTF animation, changed a node transform
this._dirty = false; // true when the model was transformed this frame
this._maxDirtyNumber = 0; // Used in place of a dirty boolean flag to avoid an extra graph traversal
this._runtime = {
animations : undefined,
rootNodes : undefined,
nodes : undefined, // Indexed with the node property's name, i.e., glTF id
nodesByName : undefined, // Indexed with name property in the node
skinnedNodes : undefined,
meshesByName : undefined, // Indexed with the name property in the mesh
materialsByName : undefined, // Indexed with the name property in the material
materialsById : undefined // Indexed with the material's property name
};
this._uniformMaps = {}; // Not cached since it can be targeted by glTF animation
this._extensionsUsed = undefined; // Cached used glTF extensions
this._extensionsRequired = undefined; // Cached required glTF extensions
this._quantizedUniforms = {}; // Quantized uniforms for each program for WEB3D_quantized_attributes
this._programPrimitives = {};
this._rendererResources = { // Cached between models with the same url/cache-key
buffers : {},
vertexArrays : {},
programs : {},
pickPrograms : {},
silhouettePrograms : {},
textures : {},
samplers : {},
renderStates : {}
};
this._cachedRendererResources = undefined;
this._loadRendererResourcesFromCache = false;
this._updatedGltfVersion = false;
this._dequantizeInShader = defaultValue(options.dequantizeInShader, true);
this._decodedData = {};
this._cachedGeometryByteLength = 0;
this._cachedTexturesByteLength = 0;
this._geometryByteLength = 0;
this._texturesByteLength = 0;
this._trianglesLength = 0;
// Hold references to programs and shaders for shader reconstruction.
// Hold these separately because _cachedGltf may get released (this.releaseGltfJson)
this._sourcePrograms = undefined;
this._sourceShaders = undefined;
this._quantizedVertexShaders = {};
this._nodeCommands = [];
this._pickIds = [];
// CESIUM_RTC extension
this._rtcCenter = undefined; // reference to either 3D or 2D
this._rtcCenterEye = undefined; // in eye coordinates
this._rtcCenter3D = undefined; // in world coordinates
this._rtcCenter2D = undefined; // in projected world coordinates
}
defineProperties(Model.prototype, {
/**
* The object for the glTF JSON, including properties with default values omitted
* from the JSON provided to this model.
*
* @memberof Model.prototype
*
* @type {Object}
* @readonly
*
* @default undefined
*/
gltf : {
get : function() {
return defined(this._cachedGltf) ? this._cachedGltf.gltf : undefined;
}
},
/**
* When <code>true</code>, the glTF JSON is not stored with the model once the model is
* loaded (when {@link Model#ready} is <code>true</code>). This saves memory when
* geometry, textures, and animations are embedded in the .gltf file, which is the
* default for the {@link https://cesiumjs.org/convertmodel.html|Cesium model converter}.
* This is especially useful for cases like 3D buildings, where each .gltf model is unique
* and caching the glTF JSON is not effective.
*
* @memberof Model.prototype
*
* @type {Boolean}
* @readonly
*
* @default false
*
* @private
*/
releaseGltfJson : {
get : function() {
return this._releaseGltfJson;
}
},
/**
* The key identifying this model in the model cache for glTF JSON, renderer resources, and animations.
* Caching saves memory and improves loading speed when several models with the same url are created.
* <p>
* This key is automatically generated when the model is created with {@link Model.fromGltf}. If the model
* is created directly from glTF JSON using the {@link Model} constructor, this key can be manually
* provided; otherwise, the model will not be changed.
* </p>
*
* @memberof Model.prototype
*
* @type {String}
* @readonly
*
* @private
*/
cacheKey : {
get : function() {
return this._cacheKey;
}
},
/**
* The base path that paths in the glTF JSON are relative to. The base
* path is the same path as the path containing the .gltf file
* minus the .gltf file, when binary, image, and shader files are
* in the same directory as the .gltf. When this is <code>''</code>,
* the app's base path is used.
*
* @memberof Model.prototype
*
* @type {String}
* @readonly
*
* @default ''
*/
basePath : {
get : function() {
return this._resource.url;
}
},
/**
* The model's bounding sphere in its local coordinate system. This does not take into
* account glTF animations and skins nor does it take into account {@link Model#minimumPixelSize}.
*
* @memberof Model.prototype
*
* @type {BoundingSphere}
* @readonly
*
* @default undefined
*
* @exception {DeveloperError} The model is not loaded. Use Model.readyPromise or wait for Model.ready to be true.
*
* @example
* // Center in WGS84 coordinates
* var center = Cesium.Matrix4.multiplyByPoint(model.modelMatrix, model.boundingSphere.center, new Cesium.Cartesian3());
*/
boundingSphere : {
get : function() {
//>>includeStart('debug', pragmas.debug);
if (this._state !== ModelState.LOADED) {
throw new DeveloperError('The model is not loaded. Use Model.readyPromise or wait for Model.ready to be true.');
}
//>>includeEnd('debug');
var modelMatrix = this.modelMatrix;
if ((this.heightReference !== HeightReference.NONE) && this._clampedModelMatrix) {
modelMatrix = this._clampedModelMatrix;
}
var nonUniformScale = Matrix4.getScale(modelMatrix, boundingSphereCartesian3Scratch);
var scale = defined(this.maximumScale) ? Math.min(this.maximumScale, this.scale) : this.scale;
Cartesian3.multiplyByScalar(nonUniformScale, scale, nonUniformScale);
var scaledBoundingSphere = this._scaledBoundingSphere;
scaledBoundingSphere.center = Cartesian3.multiplyComponents(this._boundingSphere.center, nonUniformScale, scaledBoundingSphere.center);
scaledBoundingSphere.radius = Cartesian3.maximumComponent(nonUniformScale) * this._initialRadius;
if (defined(this._rtcCenter)) {
Cartesian3.add(this._rtcCenter, scaledBoundingSphere.center, scaledBoundingSphere.center);
}
return scaledBoundingSphere;
}
},
/**
* 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. This is set to
* <code>true</code> right before {@link Model#readyPromise} is resolved.
*
* @memberof Model.prototype
*
* @type {Boolean}
* @readonly
*
* @default false
*/
ready : {
get : function() {
return this._ready;
}
},
/**
* Gets the promise that will be resolved when this model is ready to render, i.e., when the external binary, image,
* and shader files were downloaded and the WebGL resources were created.
* <p>
* This promise is resolved at the end of the frame before the first frame the model is rendered in.
* </p>
*
* @memberof Model.prototype
* @type {Promise.<Model>}
* @readonly
*
* @example
* // Play all animations at half-speed when the model is ready to render
* Cesium.when(model.readyPromise).then(function(model) {
* model.activeAnimations.addAll({
* speedup : 0.5
* });
* }).otherwise(function(error){
* window.alert(error);
* });
*
* @see Model#ready
*/
readyPromise : {
get : function() {
return this._readyPromise.promise;
}
},
/**
* Determines if model WebGL resource creation will be spread out over several frames or
* block until completion once all glTF files are loaded.
*
* @memberof Model.prototype
*
* @type {Boolean}
* @readonly
*
* @default true
*/
asynchronous : {
get : function() {
return this._asynchronous;
}
},
/**
* When <code>true</code>, each glTF mesh and primitive is pickable with {@link Scene#pick}. When <code>false</code>, GPU memory is saved.
*
* @memberof Model.prototype
*
* @type {Boolean}
* @readonly
*
* @default true
*/
allowPicking : {
get : function() {
return this._allowPicking;
}
},
/**
* Determine if textures may continue to stream in after the model is loaded.
*
* @memberof Model.prototype
*
* @type {Boolean}
* @readonly
*
* @default true
*/
incrementallyLoadTextures : {
get : function() {
return this._incrementallyLoadTextures;
}
},
/**
* Return the number of pending texture loads.
*
* @memberof Model.prototype
*
* @type {Number}
* @readonly
*/
pendingTextureLoads : {
get : function() {
return defined(this._loadResources) ? this._loadResources.pendingTextureLoads : 0;
}
},
/**
* Returns true if the model was transformed this frame
*
* @memberof Model.prototype
*
* @type {Boolean}
* @readonly
*
* @private
*/
dirty : {
get : function() {
return this._dirty;
}
},
/**
* Gets or sets the condition specifying at what distance from the camera that this model will be displayed.
* @memberof Model.prototype
* @type {DistanceDisplayCondition}
* @default undefined
*/
distanceDisplayCondition : {
get : function() {
return this._distanceDisplayCondition;
},
set : function(value) {
//>>includeStart('debug', pragmas.debug);
if (defined(value) && value.far <= value.near) {
throw new DeveloperError('far must be greater than near');
}
//>>includeEnd('debug');
this._distanceDisplayCondition = DistanceDisplayCondition.clone(value, this._distanceDisplayCondition);
}
},
extensionsUsed : {
get : function() {
if (!defined(this._extensionsUsed)) {
this._extensionsUsed = ModelUtility.getUsedExtensions(this.gltf);
}
return this._extensionsUsed;
}
},
extensionsRequired : {
get : function() {
if (!defined(this._extensionsRequired)) {
this._extensionsRequired = ModelUtility.getRequiredExtensions(this.gltf);
}
return this._extensionsRequired;
}
},
/**
* Gets the model's up-axis.
* By default models are y-up according to the glTF spec, however geo-referenced models will typically be z-up.
*
* @memberof Model.prototype
*
* @type {Number}
* @default Axis.Y
* @readonly
*
* @private
*/
upAxis : {
get : function() {
return this._upAxis;
}
},
/**
* Gets the model's triangle count.
*
* @private
*/
trianglesLength : {
get : function() {
return this._trianglesLength;
}
},
/**
* Gets the model's geometry memory in bytes. This includes all vertex and index buffers.
*
* @private
*/
geometryByteLength : {
get : function() {
return this._geometryByteLength;
}
},
/**
* Gets the model's texture memory in bytes.
*
* @private
*/
texturesByteLength : {
get : function() {
return this._texturesByteLength;
}
},
/**
* Gets the model's cached geometry memory in bytes. This includes all vertex and index buffers.
*
* @private
*/
cachedGeometryByteLength : {
get : function() {
return this._cachedGeometryByteLength;
}
},
/**
* Gets the model's cached texture memory in bytes.
*
* @private
*/
cachedTexturesByteLength : {
get : function() {
return this._cachedTexturesByteLength;
}
},
/**
* The {@link ClippingPlaneCollection} used to selectively disable rendering the model.
*
* @memberof Model.prototype
*
* @type {ClippingPlaneCollection}
*/
clippingPlanes : {
get : function() {
return this._clippingPlanes;
},
set : function(value) {
if (value === this._clippingPlanes) {
return;
}
// Handle destroying, checking of unknown, checking for existing ownership
ClippingPlaneCollection.setOwner(value, this, '_clippingPlanes');
}
}
});
function silhouetteSupported(context) {
return context.stencilBuffer;
}
function isColorShadingEnabled(model) {
return !Color.equals(model.color, Color.WHITE) || (model.colorBlendMode !== ColorBlendMode.HIGHLIGHT);
}
function isClippingEnabled(model) {
var clippingPlanes = model._clippingPlanes;
return defined(clippingPlanes) && clippingPlanes.enabled;
}
/**
* Determines if silhouettes are supported.
*
* @param {Scene} scene The scene.
* @returns {Boolean} <code>true</code> if silhouettes are supported; otherwise, returns <code>false</code>
*/
Model.silhouetteSupported = function(scene) {
return silhouetteSupported(scene.context);
};
function containsGltfMagic(uint8Array) {
var magic = getMagic(uint8Array);
return magic === 'glTF';
}
/**
* <p>
* Creates a model from a glTF asset. 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, the {@link Model#readyPromise} is resolved.
* </p>
* <p>
* The model can be a traditional glTF asset with a .gltf extension or a Binary glTF using the
* KHR_binary_glTF extension with a .glb extension.
* </p>
* <p>
* Cesium supports glTF assets with the following extensions:
* <ul>
* <li>
* {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Khronos/KHR_binary_glTF/README.md|KHR_binary_glTF}
* </li><li>
* {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Khronos/KHR_materials_common/README.md|KHR_materials_common}
* </li><li>
* {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Vendor/WEB3D_quantized_attributes/README.md|WEB3D_quantized_attributes}
* </li><li>
* {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/2.0/Khronos/KHR_draco_mesh_compression/README.md|KHR_draco_mesh_compression}
* </li>
* </ul>
* </p>
* <p>
* For high-precision rendering, Cesium supports the {@link https://github.com/KhronosGroup/glTF/blob/master/extensions/1.0/Vendor/CESIUM_RTC/README.md|CESIUM_RTC} extension, which introduces the
* CESIUM_RTC_MODELVIEW parameter semantic that says the node is in WGS84 coordinates translated
* relative to a local origin.
* </p>
*
* @param {Object} options Object with the following properties:
* @param {Resource|String} options.url The url to the .gltf file.
* @param {Resource|String} [options.basePath] The base path that paths in the glTF JSON are relative to.
* @param {Boolean} [options.show=true] Determines if the model primitive will be shown.
* @param {Matrix4} [options.modelMatrix=Matrix4.IDENTITY] The 4x4 transformation matrix that transforms the model from model to world coordinates.
* @param {Number} [options.scale=1.0] A uniform scale applied to this model.
* @param {Number} [options.minimumPixelSize=0.0] The approximate minimum pixel size of the model regardless of zoom.
* @param {Number} [options.maximumScale] The maximum scale for the model.
* @param {Object} [options.id] A user-defined object to return when the model is picked with {@link Scene#pick}.
* @param {Boolean} [options.allowPicking=true] When <code>true</code>, each glTF mesh and primitive is pickable with {@link Scene#pick}.
* @param {Boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the model is loaded.
* @param {Boolean} [options.asynchronous=true] Determines if model WebGL resource creation will be spread out over several frames or block until completion once all glTF files are loaded.
* @param {Boolean} [options.clampAnimations=true] Determines if the model's animations should hold a pose over frames where no keyframes are specified.
* @param {ShadowMode} [options.shadows=ShadowMode.ENABLED] Determines whether the model casts or receives shadows from each light source.
* @param {Boolean} [options.debugShowBoundingVolume=false] For debugging only. Draws the bounding sphere for each {@link DrawCommand} in the model.
* @param {Boolean} [options.debugWireframe=false] For debugging only. Draws the model in wireframe.
* @param {HeightReference} [options.heightReference] Determines how the model is drawn relative to terrain.
* @param {Scene} [options.scene] Must be passed in for models that use the height reference property.
* @param {DistanceDisplayCondition} [options.distanceDisplayCondition] The condition specifying at what distance from the camera that this model will be displayed.
* @param {Color} [options.color=Color.WHITE] A color that blends with the model's rendered color.
* @param {ColorBlendMode} [options.colorBlendMode=ColorBlendMode.HIGHLIGHT] Defines how the color blends with the model.
* @param {Number} [options.colorBlendAmount=0.5] 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.
* @param {Color} [options.silhouetteColor=Color.RED] The silhouette color. If more than 256 models have silhouettes enabled, there is a small chance that overlapping models will have minor artifacts.
* @param {Number} [options.silhouetteSize=0.0] The size of the silhouette in pixels.
* @param {ClippingPlaneCollection} [options.clippingPlanes] The {@link ClippingPlaneCollection} used to selectively disable rendering the model.
* @param {Boolean} [options.dequantizeInShader=true] Determines if a {@link https://github.com/google/draco|Draco} encoded model is dequantized on the GPU. This decreases total memory usage for encoded models.
*
* @returns {Model} The newly created model.
*
* @exception {DeveloperError} bgltf is not a valid Binary glTF file.
* @exception {DeveloperError} Only glTF Binary version 1 is supported.
*
* @example
* // Example 1. Create a model from a glTF asset
* var model = scene.primitives.add(Cesium.Model.fromGltf({
* url : './duck/duck.gltf'
* }));
*
* @example
* // Example 2. Create model and provide all properties and events
* var origin = Cesium.Cartesian3.fromDegrees(-95.0, 40.0, 200000.0);
* var modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
*
* var model = scene.primitives.add(Cesium.Model.fromGltf({
* url : './duck/duck.gltf',
* show : true, // default
* modelMatrix : modelMatrix,
* scale : 2.0, // double size
* minimumPixelSize : 128, // never smaller than 128 pixels
* maximumScale: 20000, // never larger than 20000 * model size (overrides minimumPixelSize)
* allowPicking : false, // not pickable
* debugShowBoundingVolume : false, // default
* debugWireframe : false
* }));
*
* model.readyPromise.then(function(model) {
* // Play all animations when the model is ready to render
* model.activeAnimations.addAll();
* });
*/
Model.fromGltf = function(options) {
//>>includeStart('debug', pragmas.debug);
if (!defined(options) || !defined(options.url)) {
throw new DeveloperError('options.url is required');
}
//>>includeEnd('debug');
var url = options.url;
options = clone(options);
// Create resource for the model file
var modelResource = Resource.createIfNeeded(url);
// Setup basePath to get dependent files
var basePath = defaultValue(options.basePath, modelResource.clone());
var resource = Resource.createIfNeeded(basePath);
// If no cache key is provided, use the absolute URL, since two URLs with
// different relative paths could point to the same model.
var cacheKey = defaultValue(options.cacheKey, getAbsoluteUri(modelResource.url));
if (defined(options.basePath) && !defined(options.cacheKey)) {
cacheKey += resource.url;
}
options.cacheKey = cacheKey;
options.basePath = resource;
var model = new Model(options);
var cachedGltf = gltfCache[cacheKey];
if (!defined(cachedGltf)) {
cachedGltf = new CachedGltf({
ready : false
});
cachedGltf.count = 1;
cachedGltf.modelsToLoad.push(model);
setCachedGltf(model, cachedGltf);
gltfCache[cacheKey] = cachedGltf;
// Add Accept header if we need it
if (!defined(modelResource.headers.Accept)) {
modelResource.headers.Accept = defaultModelAccept;
}
modelResource.fetchArrayBuffer().then(function(arrayBuffer) {
var array = new Uint8Array(arrayBuffer);
if (containsGltfMagic(array)) {
// Load binary glTF
var parsedGltf = parseBinaryGltf(array);
// KHR_binary_glTF is from the beginning of the binary section
cachedGltf.makeReady(parsedGltf, array);
} else {
// Load text (JSON) glTF
var json = getStringFromTypedArray(array);
cachedGltf.makeReady(JSON.parse(json));
}
}).otherwise(getFailedLoadFunction(model, 'model', url));
} else if (!cachedGltf.ready) {
// Cache hit but the fetchArrayBu