diff --git a/eslint.config.js b/eslint.config.js index d57e8462d51..489f1213dac 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -79,7 +79,12 @@ export default [ "eslint-seatbelt/configure": "error", "no-unused-vars": [ "error", - { vars: "all", args: "none", caughtErrors: "none" }, + { + vars: "all", + args: "none", + caughtErrors: "none", + ignoreRestSiblings: true, + }, ], // There were too many errors to address when this was first turned on. // Using eslint-seatbelt to gradually address them diff --git a/packages/engine/Source/Scene/GltfJsonLoader.js b/packages/engine/Source/Scene/GltfJsonLoader.js index d95516c16bb..dd5fb5a2467 100644 --- a/packages/engine/Source/Scene/GltfJsonLoader.js +++ b/packages/engine/Source/Scene/GltfJsonLoader.js @@ -179,7 +179,7 @@ async function upgradeVersion(gltfJsonLoader, gltf) { !usesExtension(gltf, "KHR_techniques_webgl") && !usesExtension(gltf, "KHR_materials_common") ) { - return Promise.resolve(); + return gltf; } // Load all buffers into memory. updateVersion will read and in some cases modify @@ -212,7 +212,7 @@ async function upgradeVersion(gltfJsonLoader, gltf) { }); await Promise.all(promises); - updateVersion(gltf); + return updateVersion(gltf); } function decodeDataUris(gltf) { @@ -258,7 +258,7 @@ async function processGltfJson(gltfJsonLoader, gltf) { addPipelineExtras(gltf); await decodeDataUris(gltf); - await upgradeVersion(gltfJsonLoader, gltf); + gltf = await upgradeVersion(gltfJsonLoader, gltf); addDefaults(gltf); await loadEmbeddedBuffers(gltfJsonLoader, gltf); removePipelineExtras(gltf); diff --git a/packages/gltf/SchemaTypes/Extensions/3DTILES_shape_ellipsoid_region.ts b/packages/gltf/SchemaTypes/Extensions/3DTILES_shape_ellipsoid_region.ts new file mode 100644 index 00000000000..f625b7994a2 --- /dev/null +++ b/packages/gltf/SchemaTypes/Extensions/3DTILES_shape_ellipsoid_region.ts @@ -0,0 +1,51 @@ +// Generated from the glTF JSON schemas at: +// https://github.com/CesiumGS/glTF/tree/e68efc9086f60743c331a2c757a1ffadcdb5d532/extensions/2.1/Vendor/3DTILES_shape_ellipsoid_region/schema +// Do not edit; rerun `npm run generate-types -w @cesium/gltf` instead. + +import type { Gltf2 } from "../Gltf2.js"; + +/** @internal */ +export namespace _3DTILES_shape_ellipsoid_region { + export interface Shape extends Gltf2.Property { + /** + * The minimum height of the region relative to the ellipsoid's surface, in + * meters. May be negative. + */ + minimumHeight: number; + /** + * The maximum height of the region relative to the ellipsoid's surface, in + * meters. May be negative. + */ + maximumHeight: number; + /** + * The minimum latitude of the region, in radians. Must be in the range + * [-pi/2, pi/2]. + * + * @default -1.57079632679 + */ + minimumLatitude?: number; + /** + * The maximum latitude of the region, in radians. Must be in the range + * [-pi/2, pi/2]. + * + * @default 1.57079632679 + */ + maximumLatitude?: number; + /** + * The minimum longitude of the region, in radians. Minimum and maximum + * longitude must evaluate to (0 <= abs(maximumLongitude - minimumLongitude) + * <= 2 * pi). + * + * @default -3.14159265359 + */ + minimumLongitude?: number; + /** + * The maximum longitude of the region, in radians. Minimum and maximum + * longitude must evaluate to (0 <= abs(maximumLongitude - minimumLongitude) + * <= 2 * pi). + * + * @default 3.14159265359 + */ + maximumLongitude?: number; + } +} diff --git a/packages/gltf/SchemaTypes/Gltf2.ts b/packages/gltf/SchemaTypes/Gltf2.ts index 47840cf9415..21c76b749db 100644 --- a/packages/gltf/SchemaTypes/Gltf2.ts +++ b/packages/gltf/SchemaTypes/Gltf2.ts @@ -5,6 +5,7 @@ // See packages/gltf/README.md#generated-gltf-types. import type { _3DTILES_implicit_tiling } from "./Extensions/3DTILES_implicit_tiling.js"; +import type { _3DTILES_shape_ellipsoid_region } from "./Extensions/3DTILES_shape_ellipsoid_region.js"; import type { _3DTILES_subtree } from "./Extensions/3DTILES_subtree.js"; import type { _3DTILES_tileset } from "./Extensions/3DTILES_tileset.js"; import type { _3DTILES_tileset_voxels } from "./Extensions/3DTILES_tileset_voxels.js"; @@ -1330,6 +1331,11 @@ export namespace Gltf2 { * Parameter values defining a sphere shape. */ sphere?: Gltf2.Shape.Sphere; + /** + * JSON object with extension objects. Property names correspond to glTF + * extension names and property values are extension-specific objects. + */ + extensions?: Gltf2.Shape.Extensions; } export namespace Shape { /** @@ -1437,6 +1443,12 @@ export namespace Gltf2 { */ sizeZ?: number; } + export interface Extensions extends Gltf2.Property.Extensions { + /** + * (glTF 2.1) + */ + "3DTILES_shape_ellipsoid_region"?: _3DTILES_shape_ellipsoid_region.Shape; + } /** * A sphere, centered at the origin in local space with a radius equal in * all directions, with normals facing outwards. (glTF 2.1) diff --git a/packages/gltf/SchemaTypes/index.ts b/packages/gltf/SchemaTypes/index.ts index ea50f808817..4d7322a3943 100644 --- a/packages/gltf/SchemaTypes/index.ts +++ b/packages/gltf/SchemaTypes/index.ts @@ -4,6 +4,7 @@ export type * from "./Gltf1.js"; export type * from "./Gltf2.js"; export type * from "./Extensions/3DTILES_implicit_tiling.js"; +export type * from "./Extensions/3DTILES_shape_ellipsoid_region.js"; export type * from "./Extensions/3DTILES_subtree.js"; export type * from "./Extensions/3DTILES_tileset.js"; export type * from "./Extensions/3DTILES_tileset_voxels.js"; diff --git a/packages/gltf/Source/ForEach.js b/packages/gltf/Source/ForEach.js index 0985a1a345e..81c7bd2637a 100644 --- a/packages/gltf/Source/ForEach.js +++ b/packages/gltf/Source/ForEach.js @@ -1,5 +1,7 @@ import { defined } from "@cesium/core"; +/** @import { Gltf1, Gltf2 } from "../SchemaTypes/index.js"; */ +/** @import { Gltf08 } from "./Gltf08.js"; */ /** @import { ForEachElementHandler } from "./ForEachElementHandler.js"; */ /** @import { ForEachIdHandler } from "./ForEachIdHandler.js"; */ /** @import { ForEachNamedHandler } from "./ForEachNamedHandler.js"; */ @@ -15,9 +17,10 @@ const ForEach = {}; /** * Fallback for glTF 1.0 * - * @param {Object|undefined} objects The id-keyed objects to iterate over. - * @param {ForEachElementHandler} handler Called with each object and its id. - * @returns {*} The first defined value returned by the handler. + * @template T + * @param {Record|undefined} objects The id-keyed objects to iterate over. + * @param {ForEachElementHandler} handler Called with each object and its id. + * @returns {unknown} The first defined value returned by the handler. * * @private */ @@ -37,9 +40,10 @@ ForEach.objectLegacy = function (objects, handler) { }; /** - * @param {object[]|undefined} arrayOfObjects The objects to iterate over. - * @param {ForEachElementHandler} handler Called with each object and its index. - * @returns {*} The first defined value returned by the handler. + * @template T + * @param {T[]|undefined} arrayOfObjects The objects to iterate over. + * @param {ForEachElementHandler} handler Called with each object and its index. + * @returns {unknown} The first defined value returned by the handler. * * @private */ @@ -58,40 +62,21 @@ ForEach.object = function (arrayOfObjects, handler) { }; /** - * Supports glTF 1.0 and 2.0 - * - * @param {*} gltf A javascript object containing a glTF asset. - * @param {string} name The name of the top-level glTF property. - * @param {ForEachElementHandler} handler Called with each element and its index or id. - * @returns {*} The first defined value returned by the handler. - * - * @private - */ -ForEach.topLevel = function (gltf, name, handler) { - const gltfProperty = gltf[name]; - if (defined(gltfProperty) && !Array.isArray(gltfProperty)) { - return ForEach.objectLegacy(gltfProperty, handler); - } - - return ForEach.object(gltfProperty, handler); -}; - -/** - * @param {*} gltf A javascript object containing a glTF asset. - * @param {ForEachElementHandler} handler Called with each accessor. - * @returns {*} The first defined value returned by the handler. + * @param {Gltf2} gltf A javascript object containing a glTF asset. + * @param {ForEachElementHandler} handler Called with each accessor. + * @returns {unknown} The first defined value returned by the handler. * * @private */ ForEach.accessor = function (gltf, handler) { - return ForEach.topLevel(gltf, "accessors", handler); + return ForEach.object(gltf.accessors, handler); }; /** - * @param {*} gltf A javascript object containing a glTF asset. + * @param {Gltf2} gltf A javascript object containing a glTF asset. * @param {string} semantic The attribute semantic prefix to match. * @param {ForEachIdHandler} handler Called once with each matching accessor id. - * @returns {*} The first defined value returned by the handler. + * @returns {unknown} The first defined value returned by the handler. * * @private */ @@ -144,9 +129,9 @@ ForEach.accessorWithSemantic = function (gltf, semantic, handler) { }; /** - * @param {*} gltf A javascript object containing a glTF asset. + * @param {Gltf2} gltf A javascript object containing a glTF asset. * @param {ForEachIdHandler} handler Called once with each accessor id used by a vertex attribute. - * @returns {*} The first defined value returned by the handler. + * @returns {unknown} The first defined value returned by the handler. * * @private */ @@ -193,9 +178,9 @@ ForEach.accessorContainingVertexAttributeData = function (gltf, handler) { }; /** - * @param {*} gltf A javascript object containing a glTF asset. + * @param {Gltf2} gltf A javascript object containing a glTF asset. * @param {ForEachIdHandler} handler Called once with each accessor id used for indices. - * @returns {*} The first defined value returned by the handler. + * @returns {unknown} The first defined value returned by the handler. * * @private */ @@ -218,20 +203,20 @@ ForEach.accessorContainingIndexData = function (gltf, handler) { }; /** - * @param {*} gltf A javascript object containing a glTF asset. - * @param {ForEachElementHandler} handler Called with each animation. - * @returns {*} The first defined value returned by the handler. + * @param {Gltf2} gltf A javascript object containing a glTF asset. + * @param {ForEachElementHandler} handler Called with each animation. + * @returns {unknown} The first defined value returned by the handler. * * @private */ ForEach.animation = function (gltf, handler) { - return ForEach.topLevel(gltf, "animations", handler); + return ForEach.object(gltf.animations, handler); }; /** - * @param {*} animation A glTF animation. - * @param {ForEachElementHandler} handler Called with each channel. - * @returns {*} The first defined value returned by the handler. + * @param {Gltf2.Animation} animation A glTF animation. + * @param {ForEachElementHandler} handler Called with each channel. + * @returns {unknown} The first defined value returned by the handler. * * @private */ @@ -241,9 +226,9 @@ ForEach.animationChannel = function (animation, handler) { }; /** - * @param {*} animation A glTF animation. - * @param {ForEachElementHandler} handler Called with each sampler. - * @returns {*} The first defined value returned by the handler. + * @param {Gltf2.Animation} animation A glTF animation. + * @param {ForEachElementHandler} handler Called with each sampler. + * @returns {unknown} The first defined value returned by the handler. * * @private */ @@ -253,95 +238,57 @@ ForEach.animationSampler = function (animation, handler) { }; /** - * @param {*} gltf A javascript object containing a glTF asset. - * @param {ForEachElementHandler} handler Called with each buffer. - * @returns {*} The first defined value returned by the handler. + * @param {Gltf08 | Gltf1 | Gltf2} gltf A javascript object containing a glTF asset. + * @param {ForEachElementHandler} handler Called with each buffer. + * @returns {unknown} The first defined value returned by the handler. * * @private */ ForEach.buffer = function (gltf, handler) { - return ForEach.topLevel(gltf, "buffers", handler); + const buffers = gltf.buffers; + if (Array.isArray(buffers)) { + return ForEach.object(buffers, handler); + } + return ForEach.objectLegacy(buffers, handler); }; /** - * @param {*} gltf A javascript object containing a glTF asset. - * @param {ForEachElementHandler} handler Called with each buffer view. - * @returns {*} The first defined value returned by the handler. + * @param {Gltf2} gltf A javascript object containing a glTF asset. + * @param {ForEachElementHandler} handler Called with each buffer view. + * @returns {unknown} The first defined value returned by the handler. * * @private */ ForEach.bufferView = function (gltf, handler) { - return ForEach.topLevel(gltf, "bufferViews", handler); -}; - -/** - * @param {*} gltf A javascript object containing a glTF asset. - * @param {ForEachElementHandler} handler Called with each camera. - * @returns {*} The first defined value returned by the handler. - * - * @private - */ -ForEach.camera = function (gltf, handler) { - return ForEach.topLevel(gltf, "cameras", handler); + return ForEach.object(gltf.bufferViews, handler); }; /** - * @param {*} gltf A javascript object containing a glTF asset. - * @param {ForEachElementHandler} handler Called with each image. - * @returns {*} The first defined value returned by the handler. - * - * @private - */ -ForEach.image = function (gltf, handler) { - return ForEach.topLevel(gltf, "images", handler); -}; - -/** - * @param {*} gltf A javascript object containing a glTF asset. - * @param {ForEachElementHandler} handler Called with each material. - * @returns {*} The first defined value returned by the handler. + * @param {Gltf2} gltf A javascript object containing a glTF asset. + * @param {ForEachElementHandler} handler Called with each material. + * @returns {unknown} The first defined value returned by the handler. * * @private */ ForEach.material = function (gltf, handler) { - return ForEach.topLevel(gltf, "materials", handler); -}; - -/** - * @param {*} material A glTF material. - * @param {ForEachNamedHandler} handler Called with each material value and its name. - * @returns {*} The first defined value returned by the handler. - * - * @private - */ -ForEach.materialValue = function (material, handler) { - const values = material.values; - for (const name in values) { - if (Object.prototype.hasOwnProperty.call(values, name)) { - const value = handler(values[name], name); - - if (defined(value)) { - return value; - } - } - } + return ForEach.object(gltf.materials, handler); }; /** - * @param {*} gltf A javascript object containing a glTF asset. - * @param {ForEachElementHandler} handler Called with each mesh. - * @returns {*} The first defined value returned by the handler. + * @param {Gltf2} gltf A javascript object containing a glTF asset. + * @param {ForEachElementHandler} handler Called with each mesh. + * @returns {unknown} The first defined value returned by the handler. * * @private */ ForEach.mesh = function (gltf, handler) { - return ForEach.topLevel(gltf, "meshes", handler); + return ForEach.object(gltf.meshes, handler); }; /** - * @param {*} mesh A glTF mesh. - * @param {ForEachElementHandler} handler Called with each primitive. - * @returns {*} The first defined value returned by the handler. + * @param {Gltf2.Mesh} mesh A glTF mesh. + * @param {ForEachElementHandler} handler Called with each primitive. + * @returns {unknown} The first defined value returned by the handler. * * @private */ @@ -361,9 +308,9 @@ ForEach.meshPrimitive = function (mesh, handler) { }; /** - * @param {*} primitive A glTF mesh primitive. - * @param {ForEachNamedHandler} handler Called with each attribute's accessor id and semantic. - * @returns {*} The first defined value returned by the handler. + * @param {Gltf2.Mesh.Primitive} primitive A glTF mesh primitive. + * @param {ForEachNamedHandler} handler Called with each attribute's accessor id and semantic. + * @returns {unknown} The first defined value returned by the handler. * * @private */ @@ -381,9 +328,9 @@ ForEach.meshPrimitiveAttribute = function (primitive, handler) { }; /** - * @param {*} primitive A glTF mesh primitive. - * @param {ForEachElementHandler} handler Called with each morph target. - * @returns {*} The first defined value returned by the handler. + * @param {Gltf2.Mesh.Primitive} primitive A glTF mesh primitive. + * @param {ForEachElementHandler>} handler Called with each morph target. + * @returns {unknown} The first defined value returned by the handler. * * @private */ @@ -403,8 +350,8 @@ ForEach.meshPrimitiveTarget = function (primitive, handler) { /** * @param {Object} target A glTF morph target. - * @param {ForEachNamedHandler} handler Called with each attribute's accessor id and semantic. - * @returns {*} The first defined value returned by the handler. + * @param {ForEachNamedHandler} handler Called with each attribute's accessor id and semantic. + * @returns {unknown} The first defined value returned by the handler. * * @private */ @@ -422,58 +369,25 @@ ForEach.meshPrimitiveTargetAttribute = function (target, handler) { }; /** - * @param {*} gltf A javascript object containing a glTF asset. - * @param {ForEachElementHandler} handler Called with each node. - * @returns {*} The first defined value returned by the handler. + * @param {Gltf2} gltf A javascript object containing a glTF asset. + * @param {ForEachElementHandler} handler Called with each node. + * @returns {unknown} The first defined value returned by the handler. * * @private */ ForEach.node = function (gltf, handler) { - return ForEach.topLevel(gltf, "nodes", handler); + return ForEach.object(gltf.nodes, handler); }; /** - * @param {*} gltf A javascript object containing a glTF asset. - * @param {ForEachElementHandler} handler Called with each sampler. - * @returns {*} The first defined value returned by the handler. + * @param {Gltf2} gltf A javascript object containing a glTF asset. + * @param {ForEachElementHandler} handler Called with each sampler. + * @returns {unknown} The first defined value returned by the handler. * * @private */ ForEach.sampler = function (gltf, handler) { - return ForEach.topLevel(gltf, "samplers", handler); -}; - -/** - * @param {*} gltf A javascript object containing a glTF asset. - * @param {ForEachElementHandler} handler Called with each scene. - * @returns {*} The first defined value returned by the handler. - * - * @private - */ -ForEach.scene = function (gltf, handler) { - return ForEach.topLevel(gltf, "scenes", handler); -}; - -/** - * @param {*} gltf A javascript object containing a glTF asset. - * @param {ForEachElementHandler} handler Called with each skin. - * @returns {*} The first defined value returned by the handler. - * - * @private - */ -ForEach.skin = function (gltf, handler) { - return ForEach.topLevel(gltf, "skins", handler); -}; - -/** - * @param {*} gltf A javascript object containing a glTF asset. - * @param {ForEachElementHandler} handler Called with each texture. - * @returns {*} The first defined value returned by the handler. - * - * @private - */ -ForEach.texture = function (gltf, handler) { - return ForEach.topLevel(gltf, "textures", handler); + return ForEach.object(gltf.samplers, handler); }; export default ForEach; diff --git a/packages/gltf/Source/ForEachElementHandler.ts b/packages/gltf/Source/ForEachElementHandler.ts index bbb3033deea..cca2c9d23fd 100644 --- a/packages/gltf/Source/ForEachElementHandler.ts +++ b/packages/gltf/Source/ForEachElementHandler.ts @@ -6,7 +6,7 @@ * * @internal */ -export type ForEachElementHandler = ( - element: any, +export type ForEachElementHandler = ( + element: T, index: number | string, -) => any; +) => unknown; diff --git a/packages/gltf/Source/ForEachIdHandler.ts b/packages/gltf/Source/ForEachIdHandler.ts index b201cf949e1..b48c6be5d17 100644 --- a/packages/gltf/Source/ForEachIdHandler.ts +++ b/packages/gltf/Source/ForEachIdHandler.ts @@ -5,4 +5,4 @@ * * @private */ -export type ForEachIdHandler = (id: number) => any; +export type ForEachIdHandler = (id: number) => unknown; diff --git a/packages/gltf/Source/ForEachNamedHandler.ts b/packages/gltf/Source/ForEachNamedHandler.ts index cf77fe7c3b1..683bd6f3ca4 100644 --- a/packages/gltf/Source/ForEachNamedHandler.ts +++ b/packages/gltf/Source/ForEachNamedHandler.ts @@ -6,4 +6,4 @@ * * @private */ -export type ForEachNamedHandler = (value: any, name: string) => any; +export type ForEachNamedHandler = (value: T, name: string) => unknown; diff --git a/packages/gltf/Source/Gltf08.ts b/packages/gltf/Source/Gltf08.ts new file mode 100644 index 00000000000..3a7403652f7 --- /dev/null +++ b/packages/gltf/Source/Gltf08.ts @@ -0,0 +1,67 @@ +import type { Gltf1 } from "../SchemaTypes/index.js"; + +/** + * The glTF 0.8 properties that gltf08to1 reads. There is no schema for glTF 0.8. + * + * @internal + */ +export interface Gltf08 extends Omit< + Gltf1, + "asset" | "materials" | "meshes" | "nodes" | "techniques" +> { + version?: string | number; + asset?: Gltf08.Asset; + allExtensions?: string[]; + lights?: unknown; + materials?: Record; + meshes?: Record; + nodes?: Record; + techniques?: Record; +} + +/** + * @internal + */ +export namespace Gltf08 { + export interface Asset extends Omit { + profile?: string; + version?: string; + } + + export interface Material extends Gltf1.Material { + instanceTechnique?: Pick; + } + + export interface Mesh extends Omit { + primitives?: Gltf08.Mesh.Primitive[]; + } + + export namespace Mesh { + export interface Primitive extends Gltf1.Mesh.Primitive { + primitive?: Gltf1.Mesh.Primitive["mode"]; + } + } + + export interface Node extends Gltf1.Node { + /** + * An axis-angle rotation: the axis, then the angle in radians. + */ + rotation?: [number, number, number, number]; + instanceSkin?: Pick; + } + + export interface Technique extends Omit { + pass?: string; + passes?: Record; + } + + export namespace Technique { + export interface Pass { + instanceProgram: { + program: string; + uniforms?: Gltf1.Technique["uniforms"]; + }; + states?: Gltf1.Technique["states"]; + } + } +} diff --git a/packages/gltf/Source/IdMaps.ts b/packages/gltf/Source/IdMaps.ts new file mode 100644 index 00000000000..bf80111c36a --- /dev/null +++ b/packages/gltf/Source/IdMaps.ts @@ -0,0 +1,30 @@ +import type { Gltf1 } from "../SchemaTypes/index.js"; + +/** + * The id-keyed top-level objects of a glTF 1.0 asset that become arrays in glTF 2.0. + * + * @private + */ +export type IdMapKey = keyof Pick< + Gltf1, + | "accessors" + | "animations" + | "buffers" + | "bufferViews" + | "cameras" + | "images" + | "materials" + | "meshes" + | "nodes" + | "samplers" + | "scenes" + | "skins" + | "textures" +>; + +/** + * Maps the id of each object in a glTF 1.0 asset to the index of its glTF 2.0 object. + * + * @private + */ +export type IdMaps = Record>; diff --git a/packages/gltf/Source/KHR_materials_common.ts b/packages/gltf/Source/KHR_materials_common.ts new file mode 100644 index 00000000000..0417c16d5f7 --- /dev/null +++ b/packages/gltf/Source/KHR_materials_common.ts @@ -0,0 +1,16 @@ +/** + * @private + */ +export namespace KHR_materials_common { + /** + * The KHR_materials_common material extension, which has no schema file. + * + * @private + */ + export interface Material { + technique?: string; + values?: Record; + doubleSided?: boolean; + transparent?: boolean; + } +} diff --git a/packages/gltf/Source/addPipelineExtras.js b/packages/gltf/Source/addPipelineExtras.js index 1135fc3f2f6..a941817403b 100644 --- a/packages/gltf/Source/addPipelineExtras.js +++ b/packages/gltf/Source/addPipelineExtras.js @@ -1,13 +1,14 @@ import ForEach from "./ForEach.js"; /** @import { Gltf1, Gltf2 } from "../SchemaTypes/index.js"; */ +/** @import { Gltf08 } from "./Gltf08.js"; */ /** * Adds extras._pipeline to each buffer in the glTF asset, to hold the buffer's data. * This stage runs before updateVersion and handles both glTF 1.0 and glTF 2.0 assets. * - * @param {Gltf1 | Gltf2} gltf A javascript object containing a glTF asset. - * @returns {Gltf1 | Gltf2} The glTF asset with the added pipeline extras. + * @param {Gltf08 | Gltf1 | Gltf2} gltf A javascript object containing a glTF asset. + * @returns {Gltf08 | Gltf1 | Gltf2} The glTF asset with the added pipeline extras. * * @internal */ diff --git a/packages/gltf/Source/constructBoundingVolumeJson.js b/packages/gltf/Source/constructBoundingVolumeJson.js index f60aae7ddef..1c6d7727ea7 100644 --- a/packages/gltf/Source/constructBoundingVolumeJson.js +++ b/packages/gltf/Source/constructBoundingVolumeJson.js @@ -6,7 +6,7 @@ import { defined, } from "@cesium/core"; -/** @import { Gltf2 } from "../SchemaTypes/index.js"; */ +/** @import { Gltf2, _3DTILES_shape_ellipsoid_region } from "../SchemaTypes/index.js"; */ /** * Converts the boundingVolume of a glTF node using the 3DTILES_tileset @@ -45,7 +45,7 @@ function constructBoundingVolumeJson(boundingVolumeJson, shapes) { } /** - * @param {unknown} ellipsoidRegion The 3DTILES_shape_ellipsoid_region extension object. + * @param {_3DTILES_shape_ellipsoid_region.Shape} ellipsoidRegion * @returns {{region: number[]}} * * @private @@ -58,9 +58,7 @@ function constructRegion(ellipsoidRegion) { maximumLatitude = Math.PI / 2.0, minimumHeight, maximumHeight, - } = /** @type {{minimumLongitude: (number|undefined), minimumLatitude: (number|undefined), maximumLongitude: (number|undefined), maximumLatitude: (number|undefined), minimumHeight: number, maximumHeight: number}} */ ( - ellipsoidRegion - ); + } = ellipsoidRegion; return { region: [ minimumLongitude, diff --git a/packages/gltf/Source/convert08Material.js b/packages/gltf/Source/convert08Material.js new file mode 100644 index 00000000000..ba1c6201b8f --- /dev/null +++ b/packages/gltf/Source/convert08Material.js @@ -0,0 +1,18 @@ +/** @import { Gltf1 } from "../SchemaTypes/index.js"; */ +/** @import { Gltf08 } from "./Gltf08.js"; */ + +/** + * Returns a copy of a glTF 0.8 material with the technique and values of its + * instanceTechnique moved onto the material. + * + * @param {Gltf08.Material} material + * @returns {Gltf1.Material} + * + * @private + */ +function convert08Material(material) { + const { instanceTechnique, ...rest } = material; + return { ...rest, ...instanceTechnique }; +} + +export default convert08Material; diff --git a/packages/gltf/Source/forEachBuffer.js b/packages/gltf/Source/forEachBuffer.js index a11e105aee8..b5f2d3c46b6 100644 --- a/packages/gltf/Source/forEachBuffer.js +++ b/packages/gltf/Source/forEachBuffer.js @@ -1,14 +1,15 @@ import ForEach from "./ForEach.js"; /** @import { Gltf1, Gltf2 } from "../SchemaTypes/index.js"; */ +/** @import { Gltf08 } from "./Gltf08.js"; */ /** @import { ForEachElementHandler } from "./ForEachElementHandler.js"; */ /** * Calls the handler with each buffer in a glTF. * - * @param {Gltf1 | Gltf2} gltf A javascript object containing a glTF asset. - * @param {ForEachElementHandler} handler Called with each buffer. - * @returns {*} The first defined value returned by the handler. + * @param {Gltf08 | Gltf1 | Gltf2} gltf A javascript object containing a glTF asset. + * @param {ForEachElementHandler} handler Called with each buffer. + * @returns {unknown} The first defined value returned by the handler. * * @internal */ diff --git a/packages/gltf/Source/gltf08to1.js b/packages/gltf/Source/gltf08to1.js new file mode 100644 index 00000000000..6b53cf3d60b --- /dev/null +++ b/packages/gltf/Source/gltf08to1.js @@ -0,0 +1,234 @@ +import { + Cartesian3, + ComponentDatatype, + Quaternion, + WebGLConstants, + defined, +} from "@cesium/core"; +import convert08Material from "./convert08Material.js"; +import numberOfComponentsForType from "./numberOfComponentsForType.js"; + +/** @import { Gltf1 } from "../SchemaTypes/index.js"; */ +/** @import { Gltf08 } from "./Gltf08.js"; */ +/** @import { PipelineBuffer } from "./PipelineBuffer.js"; */ + +/** + * Builds a glTF 1.0 asset from a glTF 0.8 asset. + * + * @param {Gltf08} gltf The glTF 0.8 asset. The keyframe rotations of its rotation + * animations are modified in place in its buffers. + * @returns {Gltf1} The glTF 1.0 asset. It shares objects with the input, so + * modifying it can modify the input. + * + * @private + */ +function gltf08to1(gltf) { + const { + version, + asset, + allExtensions, + // gltf.lights is not used by PBR materials + lights, + materials, + meshes, + nodes, + techniques, + ...rest + } = gltf; + + convert08AnimationRotations(gltf); + + // A glTF 0.8 profile is a string, which glTF 1.0 doesn't allow + const { profile, ...convertedAsset } = asset ?? {}; + /** @type {Gltf1} */ + const result = { ...rest, asset: { ...convertedAsset, version: "1.0" } }; + if (defined(allExtensions)) { + result.extensionsUsed = allExtensions; + } + if (defined(materials)) { + result.materials = convertValues(materials, convert08Material); + } + if (defined(meshes)) { + result.meshes = convertValues(meshes, convert08Mesh); + } + if (defined(nodes)) { + result.nodes = convertValues(nodes, convert08Node); + } + if (defined(techniques)) { + result.techniques = convertValues(techniques, convert08Technique); + } + return result; +} + +/** + * Converts each value of an object, keeping its key. + * + * @template T, U + * @param {Record} objects + * @param {function(T): U} convert + * @returns {Record} + * + * @private + */ +function convertValues(objects, convert) { + return Object.fromEntries( + Object.entries(objects).map(([id, object]) => [id, convert(object)]), + ); +} + +/** + * @param {Gltf08.Mesh} mesh + * @returns {Gltf1.Mesh} + * + * @private + */ +function convert08Mesh(mesh) { + const { primitives, ...rest } = mesh; + if (!defined(primitives)) { + return rest; + } + + return { ...rest, primitives: primitives.map(convert08Primitive) }; +} + +/** + * Converts the glTF 0.8 primitive.primitive property to primitive.mode. + * + * @param {Gltf08.Mesh.Primitive} primitive + * @returns {Gltf1.Mesh.Primitive} + * + * @private + */ +function convert08Primitive(primitive) { + const { primitive: primitiveMode, ...rest } = primitive; + return { + ...rest, + mode: rest.mode ?? primitiveMode ?? WebGLConstants.TRIANGLES, + }; +} + +const scratchAxis = new Cartesian3(); +const scratchQuaternion = new Quaternion(); + +/** + * Converts a glTF 0.8 axis-angle rotation to a quaternion, and moves the properties + * of the deprecated node.instanceSkin onto the node. + * + * @param {Gltf08.Node} node + * @returns {Gltf1.Node} + * + * @private + */ +function convert08Node(node) { + const { rotation, instanceSkin, ...rest } = node; + /** @type {Gltf1.Node} */ + const convertedNode = { ...rest }; + if (defined(rotation)) { + Cartesian3.fromArray(rotation, 0, scratchAxis); + const quaternion = Quaternion.fromAxisAngle( + scratchAxis, + rotation[3], + scratchQuaternion, + ); + convertedNode.rotation = [ + quaternion.x, + quaternion.y, + quaternion.z, + quaternion.w, + ]; + } + if (defined(instanceSkin)) { + convertedNode.skeletons = instanceSkin.skeletons; + convertedNode.skin = instanceSkin.skin; + convertedNode.meshes = instanceSkin.meshes; + } + return convertedNode; +} + +/** + * Moves the program, uniforms, and states of a glTF 0.8 technique's pass onto the + * technique. + * + * @param {Gltf08.Technique} technique + * @returns {Gltf1.Technique} + * + * @private + */ +function convert08Technique(technique) { + const { pass: passName, passes, ...rest } = technique; + const pass = passes?.[passName ?? "defaultPass"]; + return { + ...rest, + program: pass?.instanceProgram.program, + uniforms: rest.uniforms ?? pass?.instanceProgram.uniforms, + states: rest.states ?? pass?.states, + }; +} + +/** + * Converts the keyframe rotations of glTF 0.8 rotation animations from axis-angle + * to quaternions, in place in the buffer data. + * + * @param {Gltf08} gltf The glTF 0.8 asset. The keyframe rotations of its rotation + * animations are modified in place in its buffers. + * + * @private + */ +function convert08AnimationRotations(gltf) { + const accessors = gltf.accessors; + const bufferViews = gltf.bufferViews; + const buffers = gltf.buffers; + /** @type {Object} */ + const updatedAccessors = {}; + const axis = new Cartesian3(); + const quat = new Quaternion(); + for (const animation of Object.values(gltf.animations ?? {})) { + const channels = animation.channels; + if (!defined(channels)) { + continue; + } + + const parameters = animation.parameters; + const samplers = animation.samplers; + const channelsLength = channels.length; + for (let i = 0; i < channelsLength; ++i) { + const channel = channels[i]; + if (channel.target.path !== "rotation") { + continue; + } + + const accessorId = parameters[samplers[channel.sampler].output]; + if (defined(updatedAccessors[accessorId])) { + continue; + } + updatedAccessors[accessorId] = true; + const accessor = accessors[accessorId]; + const bufferView = bufferViews[accessor.bufferView]; + const buffer = /** @type {PipelineBuffer} */ (buffers[bufferView.buffer]); + const source = buffer.extras._pipeline.source; + const byteOffset = + source.byteOffset + bufferView.byteOffset + accessor.byteOffset; + const componentType = accessor.componentType; + const count = accessor.count; + const componentsLength = numberOfComponentsForType(accessor.type); + const length = accessor.count * componentsLength; + // @ts-expect-error https://github.com/CesiumGS/cesium/issues/13420 + const typedArray = ComponentDatatype.createArrayBufferView( + componentType, + source.buffer, + byteOffset, + length, + ); + + for (let j = 0; j < count; j++) { + const offset = j * componentsLength; + Cartesian3.unpack(typedArray, offset, axis); + const angle = typedArray[offset + 3]; + Quaternion.fromAxisAngle(axis, angle, quat); + Quaternion.pack(quat, typedArray, offset); + } + } + } +} + +export default gltf08to1; diff --git a/packages/gltf/Source/parseGlb.js b/packages/gltf/Source/parseGlb.js index 86acb1666be..eeb36bc3c47 100644 --- a/packages/gltf/Source/parseGlb.js +++ b/packages/gltf/Source/parseGlb.js @@ -8,6 +8,7 @@ import addPipelineExtras from "./addPipelineExtras.js"; import removeExtensionsUsed from "./removeExtensionsUsed.js"; /** @import { Gltf1, Gltf2 } from "../SchemaTypes/index.js"; */ +/** @import { Gltf08 } from "./Gltf08.js"; */ const sizeOfUint32 = 4; @@ -17,7 +18,8 @@ const sizeOfUint32 = 4; * The returned glTF has pipeline extras included. The embedded binary data is stored in gltf.buffers[0].extras._pipeline.source. * * @param {Uint8Array} glb The glb data to parse. - * @returns {Gltf1 | Gltf2} A javascript object containing a glTF asset with pipeline extras included. + * @returns {Gltf08 | Gltf1 | Gltf2} A javascript object containing a glTF asset with + * pipeline extras included. * * @internal */ diff --git a/packages/gltf/Source/removeExtension.js b/packages/gltf/Source/removeExtension.js index 5ba6f07a349..5843d6272fc 100644 --- a/packages/gltf/Source/removeExtension.js +++ b/packages/gltf/Source/removeExtension.js @@ -9,7 +9,7 @@ import removeExtensionsUsed from "./removeExtensionsUsed.js"; * @param {Gltf2} gltf A javascript object containing a glTF asset. * @param {string} extension The extension to remove. * - * @returns {*} The extension data removed from gltf.extensions. + * @returns {unknown} The extension data removed from gltf.extensions. * * @private */ @@ -20,9 +20,9 @@ function removeExtension(gltf, extension) { } /** - * @param {*} object + * @param {unknown} object * @param {string} extension - * @returns {*} + * @returns {unknown} * * @private */ @@ -37,20 +37,23 @@ function removeExtensionAndTraverse(object, extension) { typeof object === "object" && object.constructor === Object ) { - const extensions = object.extensions; + const properties = /** @type {Record} */ (object); + const extensions = /** @type {Record|undefined} */ ( + properties.extensions + ); let extensionData; if (defined(extensions)) { extensionData = extensions[extension]; if (defined(extensionData)) { delete extensions[extension]; if (Object.keys(extensions).length === 0) { - delete object.extensions; + delete properties.extensions; } } } - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - removeExtensionAndTraverse(object[key], extension); + for (const key in properties) { + if (Object.prototype.hasOwnProperty.call(properties, key)) { + removeExtensionAndTraverse(properties[key], extension); } } return extensionData; diff --git a/packages/gltf/Source/removePipelineExtras.js b/packages/gltf/Source/removePipelineExtras.js index f5a54ab9117..036fc11f791 100644 --- a/packages/gltf/Source/removePipelineExtras.js +++ b/packages/gltf/Source/removePipelineExtras.js @@ -14,7 +14,7 @@ import ForEach from "./ForEach.js"; */ function removePipelineExtras(gltf) { ForEach.buffer(gltf, function (buffer) { - removeExtras(buffer); + removeExtras(/** @type {PipelineBuffer} */ (buffer)); }); return gltf; diff --git a/packages/gltf/Source/updateVersion.js b/packages/gltf/Source/updateVersion.js index c5f33a35f7c..deafca95a76 100644 --- a/packages/gltf/Source/updateVersion.js +++ b/packages/gltf/Source/updateVersion.js @@ -3,33 +3,25 @@ import { Cartesian4, ComponentDatatype, Matrix4, - Quaternion, WebGLConstants, - clone, defined, } from "@cesium/core"; import addExtensionsUsed from "./addExtensionsUsed.js"; import addToArray from "./addToArray.js"; +import convert08Material from "./convert08Material.js"; import findAccessorMinMax from "./findAccessorMinMax.js"; import ForEach from "./ForEach.js"; -import getAccessorByteStride from "./getAccessorByteStride.js"; +import gltf08to1 from "./gltf08to1.js"; import numberOfComponentsForType from "./numberOfComponentsForType.js"; import updateAccessorComponentTypes from "./updateAccessorComponentTypes.js"; import removeExtension from "./removeExtension.js"; /** @import { Gltf1, Gltf2 } from "../SchemaTypes/index.js"; */ +/** @import { Gltf08 } from "./Gltf08.js"; */ /** @import { Rgba } from "./Rgba.js"; */ - -/** - * @type {Object} - * - * @private - */ -const updateFunctions = { - 0.8: glTF08to10, - "1.0": glTF10to20, - "2.0": undefined, -}; +/** @import { IdMaps, IdMapKey } from "./IdMaps.js"; */ +/** @import { KHR_materials_common } from "./KHR_materials_common.js"; */ +/** @import { PipelineBuffer } from "./PipelineBuffer.js"; */ /** * Update a glTF 0.8 or 1.x asset to version 2.0, and convert `KHR_techniques_webgl` and @@ -38,34 +30,28 @@ const updateFunctions = { * Applies changes made to the glTF spec between revisions so that the core library * only has to handle the latest version. * - * @param {Gltf1 | Gltf2} gltf A javascript object containing a glTF asset. - * @returns {Gltf2} The updated glTF asset. + * @param {Gltf08 | Gltf1 | Gltf2} gltf A javascript object containing a glTF asset. + * It may be modified in place. + * @returns {Gltf2} The updated glTF asset, which may be a new object. Use it in place + * of the input. * * @internal */ function updateVersion(gltf) { - const gltfAny = /** @type {any} */ (gltf); // glTF 0.8 stores its version on the root, possibly as a number - let version = String(gltfAny.version ?? gltfAny.asset?.version ?? "1.0"); + const rootVersion = /** @type {Gltf08} */ (gltf).version; + const version = String(rootVersion ?? gltf.asset?.version ?? "1.0"); + + let updatedGltf; if (version.startsWith("0.8")) { - version = "0.8"; + updatedGltf = gltf1to2(gltf08to1(/** @type {Gltf08} */ (gltf))); } else if (version.split(".")[0] === "1") { // Some assets may be labeled 1.1, but glTF 1.0 is the only 1.x specification - version = "1.0"; - } - - let updateFunction; - if (Object.prototype.hasOwnProperty.call(updateFunctions, version)) { - updateFunction = updateFunctions[version]; - } - - while (defined(updateFunction)) { - updateFunction(gltfAny); - version = gltfAny.asset.version; - updateFunction = updateFunctions[version]; + updatedGltf = gltf1to2(/** @type {Gltf1} */ (gltf)); + } else { + updatedGltf = /** @type {Gltf2} */ (gltf); } - const updatedGltf = /** @type {Gltf2} */ (gltfAny); convertTechniquesWebglToPbr(updatedGltf); convertMaterialsCommonToPbr(updatedGltf); @@ -73,498 +59,233 @@ function updateVersion(gltf) { } /** - * @param {any} gltf + * Copies id-keyed glTF 1.0 objects into an array. Each copy without a name is named + * after its id. * - * @private - */ -function updateInstanceTechniques(gltf) { - ForEach.objectLegacy(gltf.materials, function (material) { - const instanceTechnique = material.instanceTechnique; - if (!defined(instanceTechnique)) { - return; - } - - material.technique = instanceTechnique.technique; - material.values = instanceTechnique.values; - delete material.instanceTechnique; - }); -} - -/** - * @param {any} gltf + * @template {{ name?: string }} T + * @param {Record|undefined} objects + * @returns {T[]} * * @private */ -function setPrimitiveModes(gltf) { - ForEach.objectLegacy(gltf.meshes, function (mesh) { - const primitives = mesh.primitives; - if (!defined(primitives)) { - return; - } - - const primitivesLength = primitives.length; - for (let i = 0; i < primitivesLength; ++i) { - const primitive = primitives[i]; - const defaultMode = primitive.primitive ?? WebGLConstants.TRIANGLES; - primitive.mode = primitive.mode ?? defaultMode; - delete primitive.primitive; - } - }); +function objectToArray(objects) { + return Object.entries(objects ?? {}).map(([id, object]) => ({ + ...object, + name: object.name ?? id, + })); } /** - * @param {any} gltf + * Maps each key of a glTF 1.0 object to the corresponding index in a glTF 2.0 array. + * + * @param {Record|undefined} objects + * @returns {Record} * * @private */ -function updateNodes(gltf) { - const axis = new Cartesian3(); - const quat = new Quaternion(); - ForEach.objectLegacy(gltf.nodes, function (node) { - if (defined(node.rotation)) { - const rotation = node.rotation; - Cartesian3.fromArray(rotation, 0, axis); - Quaternion.fromAxisAngle(axis, rotation[3], quat); - node.rotation = [quat.x, quat.y, quat.z, quat.w]; - } - const instanceSkin = node.instanceSkin; - if (defined(instanceSkin)) { - node.skeletons = instanceSkin.skeletons; - node.skin = instanceSkin.skin; - node.meshes = instanceSkin.meshes; - delete node.instanceSkin; - } +function getIdMap(objects) { + /** @type {Record} */ + const idMap = {}; + Object.keys(objects ?? {}).forEach((id, index) => { + idMap[id] = index; }); + return idMap; } /** - * @param {any} gltf + * Converts the nodes, then splits the second and later meshes of each node into + * child nodes, appended after the converted nodes. + * + * @param {Gltf1.Node[]} nodes + * @param {IdMaps} idMaps + * @returns {Gltf2.Node[]} * * @private */ -function updateAnimations(gltf) { - const accessors = gltf.accessors; - const bufferViews = gltf.bufferViews; - const buffers = gltf.buffers; - /** @type {Object} */ - const updatedAccessors = {}; - const axis = new Cartesian3(); - const quat = new Quaternion(); - ForEach.objectLegacy(gltf.animations, function (animation) { - const channels = animation.channels; - if (!defined(channels)) { - return; +function convertNodes(nodes, idMaps) { + const convertedNodes = nodes.map((node) => convertNode(node, idMaps)); + + for (let i = 0; i < nodes.length; ++i) { + const meshIds = nodes[i].meshes ?? []; + for (let j = 1; j < meshIds.length; ++j) { + const meshNodeIndex = addToArray(convertedNodes, { + mesh: idMaps.meshes[meshIds[j]], + }); + const convertedNode = convertedNodes[i]; + convertedNode.children = convertedNode.children ?? []; + convertedNode.children.push(meshNodeIndex); } + } - const parameters = animation.parameters; - const samplers = animation.samplers; - const channelsLength = channels.length; - for (let i = 0; i < channelsLength; ++i) { - const channel = channels[i]; - if (channel.target.path !== "rotation") { - continue; - } - - const accessorId = parameters[samplers[channel.sampler].output]; - if (defined(updatedAccessors[accessorId])) { - continue; - } - updatedAccessors[accessorId] = true; - const accessor = accessors[accessorId]; - const bufferView = bufferViews[accessor.bufferView]; - const buffer = buffers[bufferView.buffer]; - const source = buffer.extras._pipeline.source; - const byteOffset = - source.byteOffset + bufferView.byteOffset + accessor.byteOffset; - const componentType = accessor.componentType; - const count = accessor.count; - const componentsLength = numberOfComponentsForType(accessor.type); - const length = accessor.count * componentsLength; - // @ts-expect-error https://github.com/CesiumGS/cesium/issues/13420 - const typedArray = ComponentDatatype.createArrayBufferView( - componentType, - source.buffer, - byteOffset, - length, - ); - - for (let j = 0; j < count; j++) { - const offset = j * componentsLength; - Cartesian3.unpack(typedArray, offset, axis); - const angle = typedArray[offset + 3]; - Quaternion.fromAxisAngle(axis, angle, quat); - Quaternion.pack(quat, typedArray, offset); - } - } - }); + return convertedNodes; } /** - * @param {any} gltf + * @param {Gltf1.Node} node + * @param {IdMaps} idMaps + * @returns {Gltf2.Node} * * @private */ -function removeTechniquePasses(gltf) { - ForEach.objectLegacy(gltf.techniques, function (technique) { - const passes = technique.passes; - if (!defined(passes)) { - return; - } - - const passName = technique.pass ?? "defaultPass"; - if (Object.prototype.hasOwnProperty.call(passes, passName)) { - const pass = passes[passName]; - technique.uniforms = technique.uniforms ?? pass.instanceProgram.uniforms; - technique.states = technique.states ?? pass.states; +function convertNode(node, idMaps) { + const { camera, children, skeletons, skin, jointName, meshes, ...rest } = + node; + /** @type {Gltf2.Node} */ + const convertedNode = { ...rest }; + if (defined(camera)) { + convertedNode.camera = idMaps.cameras[camera]; + } + if (defined(children)) { + const convertedChildren = convertNodeIds(children, idMaps.nodes); + if (convertedChildren.length > 0) { + convertedNode.children = convertedChildren; } - delete technique.passes; - delete technique.pass; - }); + } + if (defined(skin)) { + convertedNode.skin = idMaps.skins[skin]; + } + if (defined(meshes) && meshes.length > 0) { + convertedNode.mesh = idMaps.meshes[meshes[0]]; + } + return convertedNode; } /** - * @param {any} gltf + * Converts node ids to indices, leaving out the ids of nodes that were removed. + * + * @param {string[]} nodeIds + * @param {Record} nodeMap + * @returns {number[]} * * @private */ -function glTF08to10(gltf) { - if (!defined(gltf.asset)) { - gltf.asset = {}; - } - gltf.asset.version = "1.0"; - // Version property should be in asset, not on the root element - if (defined(gltf.version)) { - delete gltf.version; - } - // material.instanceTechnique properties should be directly on the material - updateInstanceTechniques(gltf); - // primitive.primitive should be primitive.mode - setPrimitiveModes(gltf); - // Node rotation should be quaternion, not axis-angle - // node.instanceSkin is deprecated - updateNodes(gltf); - // Animations that target rotations should be quaternion, not axis-angle - updateAnimations(gltf); - // technique.pass and techniques.passes are deprecated - removeTechniquePasses(gltf); - // gltf.allExtensions -> extensionsUsed - if (defined(gltf.allExtensions)) { - gltf.extensionsUsed = gltf.allExtensions; - delete gltf.allExtensions; - } - // gltf.lights is not used by PBR materials - delete gltf.lights; +function convertNodeIds(nodeIds, nodeMap) { + return nodeIds + .filter((nodeId) => defined(nodeMap[nodeId])) + .map((nodeId) => nodeMap[nodeId]); } /** - * @param {any} gltf + * @param {Gltf1.Scene} scene + * @param {IdMaps} idMaps + * @returns {Gltf2.Scene} * * @private */ -function removeAnimationSamplersIndirection(gltf) { - ForEach.objectLegacy(gltf.animations, function (animation) { - const parameters = animation.parameters; - if (!defined(parameters)) { - return; - } - - ForEach.objectLegacy(animation.samplers, function (sampler) { - sampler.input = parameters[sampler.input]; - sampler.output = parameters[sampler.output]; - }); - delete animation.parameters; - }); +function convertScene(scene, idMaps) { + const { nodes, ...rest } = scene; + /** @type {Gltf2.Scene} */ + const convertedScene = { ...rest }; + if (defined(nodes)) { + convertedScene.nodes = convertNodeIds(nodes, idMaps.nodes); + } + return convertedScene; } /** - * @param {Object} object - * @param {Object} mapping - * @returns {object[]} + * @param {Gltf1.Skin} skin + * @param {Record} jointNames The node index of each joint name. + * @param {number|undefined} skeleton The node index of the skeleton of the skin. + * @param {IdMaps} idMaps + * @returns {Gltf2.Skin} * * @private */ -function objectToArray(object, mapping) { - /** @type {object[]} */ - const array = []; - ForEach.objectLegacy(object, function (value, id) { - mapping[id] = array.length; - array.push(value); - if (!defined(value.name)) { - value.name = id; - } - }); - return array; +function convertSkin(skin, jointNames, skeleton, idMaps) { + const { inverseBindMatrices, jointNames: skinJointNames, ...rest } = skin; + /** @type {Gltf2.Skin} */ + const convertedSkin = { + ...rest, + joints: (skinJointNames ?? []).map((jointName) => jointNames[jointName]), + }; + if (defined(inverseBindMatrices)) { + convertedSkin.inverseBindMatrices = idMaps.accessors[inverseBindMatrices]; + } + if (defined(skeleton)) { + convertedSkin.skeleton = skeleton; + } + return convertedSkin; } /** - * @param {any} gltf + * @param {Gltf1.Node[]} nodes + * @returns {Record} The node index of each joint name. * * @private */ -function objectsToArrays(gltf) { - /** @type {Object>} */ - const globalMapping = { - accessors: {}, - animations: {}, - buffers: {}, - bufferViews: {}, - cameras: {}, - images: {}, - materials: {}, - meshes: {}, - nodes: {}, - samplers: {}, - scenes: {}, - skins: {}, - textures: {}, - techniques: {}, - }; - - // Map joint names to id names - /** @type {Object} */ - const jointNameToId = {}; - ForEach.objectLegacy(gltf.nodes, function (node, id) { - const jointName = node.jointName; +function getJointNames(nodes) { + /** @type {Record} */ + const jointNames = {}; + for (let i = 0; i < nodes.length; ++i) { + const jointName = nodes[i].jointName; if (defined(jointName)) { - jointNameToId[jointName] = id; + jointNames[jointName] = i; } - }); - - // Convert top level objects to arrays - for (const topLevelId in gltf) { - if ( - !Object.prototype.hasOwnProperty.call(gltf, topLevelId) || - !defined(globalMapping[topLevelId]) - ) { - continue; - } - - /** @type {Object} */ - const objectMapping = {}; - const object = gltf[topLevelId]; - gltf[topLevelId] = objectToArray(object, objectMapping); - globalMapping[topLevelId] = objectMapping; - } - - // Remap joint names to array indexes - ForEach.objectLegacy(jointNameToId, function (nodeId, jointName) { - jointNameToId[jointName] = globalMapping.nodes[nodeId]; - }); - - // Fix references - if (defined(gltf.scene)) { - gltf.scene = globalMapping.scenes[gltf.scene]; } - ForEach.bufferView(gltf, function (bufferView) { - if (defined(bufferView.buffer)) { - bufferView.buffer = globalMapping.buffers[bufferView.buffer]; - } - }); - ForEach.accessor(gltf, function (accessor) { - if (defined(accessor.bufferView)) { - accessor.bufferView = globalMapping.bufferViews[accessor.bufferView]; - } - }); - ForEach.mesh(gltf, function (mesh) { - ForEach.meshPrimitive(mesh, function (primitive) { - if (defined(primitive.indices)) { - primitive.indices = globalMapping.accessors[primitive.indices]; - } - ForEach.meshPrimitiveAttribute( - primitive, - function (accessorId, semantic) { - primitive.attributes[semantic] = globalMapping.accessors[accessorId]; - }, - ); - if (defined(primitive.material)) { - primitive.material = globalMapping.materials[primitive.material]; - } - }); - }); - ForEach.node(gltf, function (node) { - let children = node.children; - if (defined(children)) { - const childrenLength = children.length; - for (let i = 0; i < childrenLength; ++i) { - children[i] = globalMapping.nodes[children[i]]; - } - } - if (defined(node.meshes)) { - // Split out meshes on nodes - const meshes = node.meshes; - const meshesLength = meshes.length; - if (meshesLength > 0) { - node.mesh = globalMapping.meshes[meshes[0]]; - for (let i = 1; i < meshesLength; ++i) { - const meshNode = { - mesh: globalMapping.meshes[meshes[i]], - }; - const meshNodeId = addToArray(gltf.nodes, meshNode); - if (!defined(children)) { - children = []; - node.children = children; - } - children.push(meshNodeId); - } - } - delete node.meshes; - } - if (defined(node.camera)) { - node.camera = globalMapping.cameras[node.camera]; - } - if (defined(node.skin)) { - node.skin = globalMapping.skins[node.skin]; - } - if (defined(node.skeletons)) { - // Assign skeletons to skins - const skeletons = node.skeletons; - const skeletonsLength = skeletons.length; - if (skeletonsLength > 0 && defined(node.skin)) { - const skin = gltf.skins[node.skin]; - skin.skeleton = globalMapping.nodes[skeletons[0]]; - } - delete node.skeletons; - } - if (defined(node.jointName)) { - delete node.jointName; - } - }); - ForEach.skin(gltf, function (skin) { - if (defined(skin.inverseBindMatrices)) { - skin.inverseBindMatrices = - globalMapping.accessors[skin.inverseBindMatrices]; - } - const jointNames = skin.jointNames; - if (defined(jointNames)) { - const joints = []; - const jointNamesLength = jointNames.length; - for (let i = 0; i < jointNamesLength; ++i) { - joints[i] = jointNameToId[jointNames[i]]; - } - skin.joints = joints; - delete skin.jointNames; - } - }); - ForEach.scene(gltf, function (scene) { - const sceneNodes = scene.nodes; - if (defined(sceneNodes)) { - const sceneNodesLength = sceneNodes.length; - for (let i = 0; i < sceneNodesLength; ++i) { - sceneNodes[i] = globalMapping.nodes[sceneNodes[i]]; - } - } - }); - ForEach.animation(gltf, function (animation) { - /** @type {Object} */ - const samplerMapping = {}; - animation.samplers = objectToArray(animation.samplers, samplerMapping); - ForEach.animationSampler(animation, function (sampler) { - sampler.input = globalMapping.accessors[sampler.input]; - sampler.output = globalMapping.accessors[sampler.output]; - }); - ForEach.animationChannel(animation, function (channel) { - channel.sampler = samplerMapping[channel.sampler]; - const target = channel.target; - if (defined(target)) { - target.node = globalMapping.nodes[target.id]; - delete target.id; - } - }); - }); - ForEach.material(gltf, function (material) { - if (defined(material.technique)) { - material.technique = globalMapping.techniques[material.technique]; - } - ForEach.materialValue(material, function (value, name) { - if (typeof value === "string") { - material.values[name] = { - index: globalMapping.textures[value], - }; - } - }); - const extensions = material.extensions; - if (defined(extensions)) { - const materialsCommon = extensions.KHR_materials_common; - if (defined(materialsCommon) && defined(materialsCommon.values)) { - ForEach.materialValue(materialsCommon, function (value, name) { - if (typeof value === "string") { - materialsCommon.values[name] = { - index: globalMapping.textures[value], - }; - } - }); - } - } - }); - ForEach.image(gltf, function (image) { - const extensions = image.extensions; - if (defined(extensions)) { - const binaryGltf = extensions.KHR_binary_glTF; - if (defined(binaryGltf)) { - image.bufferView = globalMapping.bufferViews[binaryGltf.bufferView]; - image.mimeType = binaryGltf.mimeType; - delete extensions.KHR_binary_glTF; - } - if (Object.keys(extensions).length === 0) { - delete image.extensions; - } - } - }); - ForEach.texture(gltf, function (texture) { - if (defined(texture.sampler)) { - texture.sampler = globalMapping.samplers[texture.sampler]; - } - if (defined(texture.source)) { - texture.source = globalMapping.images[texture.source]; - } - }); + return jointNames; } /** - * @param {any} gltf + * @param {Gltf1.Node[]} nodes + * @param {IdMaps} idMaps + * @returns {Record} The node index of the skeleton of each skin, by skin index. * * @private */ -function removeAnimationSamplerNames(gltf) { - ForEach.animation(gltf, function (animation) { - ForEach.animationSampler(animation, function (sampler) { - delete sampler.name; - }); - }); +function getSkeletons(nodes, idMaps) { + /** @type {Record} */ + const skeletons = {}; + for (const node of nodes) { + const { skin, skeletons: skeletonIds } = node; + if (defined(skin) && defined(skeletonIds) && skeletonIds.length > 0) { + skeletons[idMaps.skins[skin]] = idMaps.nodes[skeletonIds[0]]; + } + } + return skeletons; } /** - * @param {any} gltf + * Deletes the empty top-level arrays. glTF 2.0 allows them to be missing but not empty. + * + * @param {Gltf2} gltf * * @private */ function removeEmptyArrays(gltf) { - for (const topLevelId in gltf) { - if (!Object.prototype.hasOwnProperty.call(gltf, topLevelId)) { - continue; - } - - const array = gltf[topLevelId]; - if (Array.isArray(array) && array.length === 0) { - delete gltf[topLevelId]; + /** @type {Array} */ + const arrayNames = [ + "accessors", + "animations", + "buffers", + "bufferViews", + "cameras", + "images", + "materials", + "meshes", + "nodes", + "samplers", + "scenes", + "skins", + "textures", + "extensionsUsed", + "extensionsRequired", + ]; + for (const arrayName of arrayNames) { + if (defined(gltf[arrayName]) && gltf[arrayName].length === 0) { + delete gltf[arrayName]; } } - ForEach.node(gltf, function (node) { - if (defined(node.children) && node.children.length === 0) { - delete node.children; - } - }); } /** - * @param {any} gltf + * @param {Gltf1.Asset} asset + * @returns {Gltf2.Asset} * * @private */ -function stripAsset(gltf) { - const asset = gltf.asset; - delete asset.profile; - delete asset.premultipliedAlpha; +function convertAsset(asset) { + const { profile, premultipliedAlpha, ...convertedAsset } = asset; + return { ...convertedAsset, version: "2.0" }; } /** @@ -576,72 +297,109 @@ const knownExtensions = { CESIUM_RTC: true, WEB3D_quantized_attributes: true, }; + /** - * @param {any} gltf + * @param {Gltf1.Buffer} buffer + * @returns {Gltf2.Buffer} * * @private */ -function requireKnownExtensions(gltf) { - const extensionsUsed = gltf.extensionsUsed; - gltf.extensionsRequired = gltf.extensionsRequired ?? []; - if (defined(extensionsUsed)) { - const extensionsUsedLength = extensionsUsed.length; - for (let i = 0; i < extensionsUsedLength; ++i) { - const extension = extensionsUsed[i]; - if (defined(knownExtensions[extension])) { - gltf.extensionsRequired.push(extension); - } - } +function convertBuffer(buffer) { + const { type, ...convertedBuffer } = buffer; + const pipelineBuffer = /** @type {PipelineBuffer} */ (buffer); + return { + ...convertedBuffer, + byteLength: + buffer.byteLength ?? pipelineBuffer.extras._pipeline.source.length, + }; +} + +/** + * @param {Gltf1.Texture} texture + * @param {IdMaps} idMaps + * @returns {Gltf2.Texture} + * + * @private + */ +function convertTexture(texture, idMaps) { + const { format, internalFormat, target, type, sampler, source, ...rest } = + texture; + /** @type {Gltf2.Texture} */ + const convertedTexture = { ...rest }; + if (defined(sampler)) { + convertedTexture.sampler = idMaps.samplers[sampler]; } + if (defined(source)) { + convertedTexture.source = idMaps.images[source]; + } + return convertedTexture; } /** - * @param {any} gltf + * @param {Gltf1.Image} image + * @param {IdMaps} idMaps + * @returns {Gltf2.Image} * * @private */ -function removeBufferType(gltf) { - ForEach.buffer(gltf, function (buffer) { - delete buffer.type; - }); +function convertImage(image, idMaps) { + const { extensions, ...rest } = image; + /** @type {Gltf2.Image} */ + const convertedImage = { ...rest }; + if (!defined(extensions)) { + return convertedImage; + } + + const { KHR_binary_glTF: binaryGltf, ...otherExtensions } = extensions; + if (defined(binaryGltf)) { + convertedImage.bufferView = idMaps.bufferViews[binaryGltf.bufferView]; + convertedImage.mimeType = binaryGltf.mimeType; + } + if (Object.keys(otherExtensions).length > 0) { + convertedImage.extensions = otherExtensions; + } + return convertedImage; } /** - * @param {any} gltf + * @param {Gltf1.Mesh} mesh + * @param {IdMaps} idMaps + * @returns {Gltf2.Mesh} * * @private */ -function removeTextureProperties(gltf) { - ForEach.texture(gltf, function (texture) { - delete texture.format; - delete texture.internalFormat; - delete texture.target; - delete texture.type; - }); +function convertMesh(mesh, idMaps) { + const { primitives, ...rest } = mesh; + return { + ...rest, + primitives: (primitives ?? []).map((primitive) => + convertMeshPrimitive(primitive, idMaps), + ), + }; } /** - * @param {any} gltf + * @param {Gltf1.Mesh.Primitive} primitive + * @param {IdMaps} idMaps + * @returns {Gltf2.Mesh.Primitive} * * @private */ -function requireAttributeSetIndex(gltf) { - ForEach.mesh(gltf, function (mesh) { - ForEach.meshPrimitive(mesh, function (primitive) { - ForEach.meshPrimitiveAttribute( - primitive, - function (accessorId, semantic) { - if (semantic === "TEXCOORD") { - primitive.attributes.TEXCOORD_0 = accessorId; - } else if (semantic === "COLOR") { - primitive.attributes.COLOR_0 = accessorId; - } - }, - ); - delete primitive.attributes.TEXCOORD; - delete primitive.attributes.COLOR; - }); - }); +function convertMeshPrimitive(primitive, idMaps) { + const { attributes, indices, material, ...rest } = primitive; + /** @type {Gltf2.Mesh.Primitive} */ + const convertedPrimitive = { ...rest, attributes: {} }; + for (const [semantic, accessorId] of Object.entries(attributes ?? {})) { + convertedPrimitive.attributes[convertAttributeSemantic(semantic)] = + idMaps.accessors[accessorId]; + } + if (defined(indices)) { + convertedPrimitive.indices = idMaps.accessors[indices]; + } + if (defined(material)) { + convertedPrimitive.material = idMaps.materials[material]; + } + return convertedPrimitive; } /** @@ -667,212 +425,342 @@ const indexedSemantics = { WEIGHT: "WEIGHTS", WEIGHTS: "WEIGHTS", }; + /** - * @param {any} gltf + * @param {string} semantic + * @returns {string} * * @private */ -function underscoreApplicationSpecificSemantics(gltf) { - /** @type {Object} */ - const mappedSemantics = {}; - ForEach.mesh(gltf, function (mesh) { - ForEach.meshPrimitive(mesh, function (primitive) { - ForEach.meshPrimitiveAttribute( - primitive, - function (accessorId, semantic) { - if (semantic.charAt(0) !== "_") { - const setIndex = semantic.search(/_[0-9]+/g); - let strippedSemantic = semantic; - let suffix = "_0"; - if (setIndex >= 0) { - strippedSemantic = semantic.substring(0, setIndex); - suffix = semantic.substring(setIndex); - } - let newSemantic; - const indexedSemantic = indexedSemantics[strippedSemantic]; - if (defined(indexedSemantic)) { - newSemantic = indexedSemantic + suffix; - mappedSemantics[semantic] = newSemantic; - } else if (!defined(knownSemantics[strippedSemantic])) { - newSemantic = `_${semantic}`; - mappedSemantics[semantic] = newSemantic; - } - } - }, - ); - ForEach.objectLegacy( - mappedSemantics, - function (mappedSemantic, semantic) { - const accessorId = primitive.attributes[semantic]; - if (defined(accessorId)) { - delete primitive.attributes[semantic]; - primitive.attributes[mappedSemantic] = accessorId; - } - }, - ); - }); - }); +function convertAttributeSemantic(semantic) { + if (semantic.charAt(0) === "_") { + return semantic; + } + + // Indexed semantics without a set index, such as TEXCOORD, get the set index _0 + const setIndex = semantic.search(/_[0-9]+/g); + let strippedSemantic = semantic; + let suffix = "_0"; + if (setIndex >= 0) { + strippedSemantic = semantic.substring(0, setIndex); + suffix = semantic.substring(setIndex); + } + const indexedSemantic = indexedSemantics[strippedSemantic]; + if (defined(indexedSemantic)) { + return indexedSemantic + suffix; + } + + // Application-specific semantics start with an underscore + if (!defined(knownSemantics[strippedSemantic])) { + return `_${semantic}`; + } + + return semantic; } /** - * @param {any} gltf + * @param {Gltf1.Animation} animation + * @param {IdMaps} idMaps + * @returns {Gltf2.Animation} * * @private */ -function clampCameraParameters(gltf) { - ForEach.camera(gltf, function (camera) { - const perspective = camera.perspective; - if (defined(perspective)) { - const aspectRatio = perspective.aspectRatio; - if (defined(aspectRatio) && aspectRatio === 0.0) { - delete perspective.aspectRatio; - } - const yfov = perspective.yfov; - if (defined(yfov) && yfov === 0.0) { - perspective.yfov = 1.0; - } - } - }); +function convertAnimation(animation, idMaps) { + const { parameters, samplers, channels, ...rest } = animation; + + /** @type {Record} */ + const samplerMap = {}; + /** @type {Gltf2.Animation.Sampler[]} */ + const convertedSamplers = []; + for (const [samplerId, sampler] of Object.entries(samplers ?? {})) { + samplerMap[samplerId] = convertedSamplers.length; + convertedSamplers.push( + convertAnimationSampler(sampler, parameters, idMaps), + ); + } + + return { + ...rest, + channels: (channels ?? []).map((channel) => + convertAnimationChannel(channel, samplerMap, idMaps), + ), + samplers: convertedSamplers, + }; } /** - * @param {any} gltf - * @param {any} accessor - * @returns {number} + * @param {Gltf1.Animation.Channel} channel + * @param {Record} samplerMap + * @param {IdMaps} idMaps + * @returns {Gltf2.Animation.Channel} * * @private */ -function computeAccessorByteStride(gltf, accessor) { - return defined(accessor.byteStride) && accessor.byteStride !== 0 - ? accessor.byteStride - : getAccessorByteStride(gltf, accessor); +function convertAnimationChannel(channel, samplerMap, idMaps) { + const { sampler, target, ...rest } = channel; + const { id, ...targetRest } = target; + return { + ...rest, + sampler: samplerMap[sampler], + target: { ...targetRest, node: idMaps.nodes[id] }, + }; } /** - * @param {any} gltf + * @param {Gltf1.Animation.Sampler} sampler + * @param {Record|undefined} parameters + * @param {IdMaps} idMaps + * @returns {Gltf2.Animation.Sampler} * * @private */ -function requireByteLength(gltf) { - ForEach.buffer(gltf, function (buffer) { - if (!defined(buffer.byteLength)) { - buffer.byteLength = buffer.extras._pipeline.source.length; - } - }); - ForEach.accessor(gltf, function (accessor) { - const bufferViewId = accessor.bufferView; - if (defined(bufferViewId)) { - const bufferView = gltf.bufferViews[bufferViewId]; - const accessorByteStride = computeAccessorByteStride(gltf, accessor); - const accessorByteEnd = - accessor.byteOffset + accessor.count * accessorByteStride; - bufferView.byteLength = Math.max( - bufferView.byteLength ?? 0, - accessorByteEnd, - ); - } - }); +function convertAnimationSampler(sampler, parameters, idMaps) { + const { input, output, ...rest } = sampler; + // A sampler refers to its accessors through the names in animation.parameters + const inputAccessorId = defined(parameters) ? parameters[input] : input; + const outputAccessorId = defined(parameters) ? parameters[output] : output; + return { + ...rest, + input: idMaps.accessors[inputAccessorId], + output: idMaps.accessors[outputAccessorId], + }; } /** - * @param {any} gltf + * @param {Gltf1.Camera} camera + * @returns {Gltf2.Camera} * * @private */ -function moveByteStrideToBufferView(gltf) { - const bufferViews = gltf.bufferViews; +function convertCamera(camera) { + if (!defined(camera.perspective)) { + return { ...camera }; + } - /** @type {Object} */ - const bufferViewHasVertexAttributes = {}; - ForEach.accessorContainingVertexAttributeData(gltf, function (accessorId) { - const accessor = gltf.accessors[accessorId]; - if (defined(accessor.bufferView)) { - bufferViewHasVertexAttributes[accessor.bufferView] = true; + // Fix zero values in perspective + const perspective = { ...camera.perspective }; + if (perspective.aspectRatio === 0.0) { + delete perspective.aspectRatio; + } + if (perspective.yfov === 0.0) { + perspective.yfov = 1.0; + } + return { ...camera, perspective: perspective }; +} + +/** + * Converts the bufferViews and accessors, splitting each bufferView into a bufferView + * for each group of its accessors with the same byte stride. + * + * @param {Gltf1.BufferView[]} bufferViews + * @param {Gltf1.Accessor[]} accessors + * @param {Gltf1.Image[]} images + * @param {Gltf1.Mesh[]} meshes + * @param {IdMaps} idMaps + * @returns {Pick} + * + * @private + */ +function convertBufferViewsAndAccessors( + bufferViews, + accessors, + images, + meshes, + idMaps, +) { + // Find the bufferViews used by images + /** @type {Set} */ + const imageBufferViewIndices = new Set(); + for (const image of images) { + const binaryGltf = image.extensions?.KHR_binary_glTF; + if (defined(binaryGltf)) { + imageBufferViewIndices.add(idMaps.bufferViews[binaryGltf.bufferView]); } - }); + } - /** @type {Object} */ - const bufferViewHasImage = {}; - ForEach.image(gltf, function (image) { - if (defined(image.bufferView)) { - bufferViewHasImage[image.bufferView] = true; + // Find the accessors used as vertex attributes + /** @type {Set} */ + const attributeAccessorIndices = new Set(); + for (const mesh of meshes) { + for (const primitive of mesh.primitives ?? []) { + for (const accessorId of Object.values(primitive.attributes ?? {})) { + attributeAccessorIndices.add(idMaps.accessors[accessorId]); + } } - }); + } - // Map buffer views to a list of accessors - /** @type {Object} */ - const bufferViewMap = {}; - ForEach.accessor(gltf, function (accessor) { - if (defined(accessor.bufferView)) { - bufferViewMap[accessor.bufferView] = - bufferViewMap[accessor.bufferView] ?? []; - bufferViewMap[accessor.bufferView].push(accessor); + // Find each accessor's byte stride and the byte offset just past its last element, + // and list the accessors in each bufferView + /** @type {number[]} */ + const byteStrides = []; + /** @type {number[]} */ + const byteEnds = []; + const bufferViewAccessorIndices = bufferViews.map( + () => /** @type {number[]} */ ([]), + ); + for (let i = 0; i < accessors.length; ++i) { + const accessor = accessors[i]; + const elementByteSize = + // @ts-expect-error https://github.com/CesiumGS/cesium/issues/13420 + ComponentDatatype.getSizeInBytes(accessor.componentType) * + numberOfComponentsForType(accessor.type); + const byteStride = + defined(accessor.byteStride) && accessor.byteStride !== 0 + ? accessor.byteStride + : elementByteSize; + byteStrides.push(byteStride); + byteEnds.push( + accessor.byteOffset + (accessor.count - 1) * byteStride + elementByteSize, + ); + + const bufferViewIndex = idMaps.bufferViews[accessor.bufferView]; + if (defined(bufferViewIndex)) { + bufferViewAccessorIndices[bufferViewIndex].push(i); } - }); + } - // Split accessors with different byte strides - for (const bufferViewId in bufferViewMap) { - if (!Object.prototype.hasOwnProperty.call(bufferViewMap, bufferViewId)) { - continue; + // Convert each bufferView, and record the glTF 2.0 bufferView and byteOffset of + // each accessor. Converted glTF 1.0 bufferViews keep their indices, and new + // bufferViews are appended after them. + /** @type {Gltf2.BufferView[]} */ + const convertedBufferViews = new Array(bufferViews.length); + /** @type {number[]} */ + const accessorBufferViews = []; + /** @type {number[]} */ + const accessorByteOffsets = []; + for (let i = 0; i < bufferViews.length; ++i) { + const bufferView = bufferViews[i]; + const accessorIndices = bufferViewAccessorIndices[i].sort( + (a, b) => accessors[a].byteOffset - accessors[b].byteOffset, + ); + + // A glTF 2.0 bufferView has one byteStride for all its accessors, + // so split accessors with different byte strides + /** @type {number[][]} */ + const groups = []; + for (const accessorIndex of accessorIndices) { + const group = groups[groups.length - 1]; + if ( + defined(group) && + byteStrides[group[0]] === byteStrides[accessorIndex] + ) { + group.push(accessorIndex); + } else { + groups.push([accessorIndex]); + } } - const bufferView = bufferViews[bufferViewId]; - const bufferViewByteOffset = bufferView.byteOffset; - const accessors = bufferViewMap[bufferViewId]; - accessors.sort(function (a, b) { - return a.byteOffset - b.byteOffset; - }); - // Writing the first group's byteStride to the buffer view changes what getAccessorByteStride returns - const accessorByteStrides = accessors.map(function (accessor) { - return computeAccessorByteStride(gltf, accessor); - }); - let currentByteOffset = 0; - let currentIndex = 0; - const accessorsLength = accessors.length; - for (let i = 0; i < accessorsLength; ++i) { - const accessor = accessors[i]; - const accessorByteStride = accessorByteStrides[i]; - const accessorByteOffset = accessor.byteOffset; - const accessorByteLength = accessor.count * accessorByteStride; - delete accessor.byteStride; - - const hasNextAccessor = i < accessorsLength - 1; - const nextAccessorByteStride = hasNextAccessor - ? accessorByteStrides[i + 1] - : undefined; - if (accessorByteStride === nextAccessorByteStride) { - continue; + // The first group's bufferView takes the glTF 1.0 bufferView's index. If there + // are no groups, or an image uses the whole bufferView, convert it as it is. + const firstGroupKeepsIndex = + groups.length > 0 && !imageBufferViewIndices.has(i); + if (!firstGroupKeepsIndex) { + convertedBufferViews[i] = convertBufferView( + bufferView, + bufferView.byteOffset, + bufferView.byteLength ?? 0, + idMaps, + ); + } + + // Strided data isn't repacked, so keep its byteStride. (Not valid glTF 2.0 + // except for vertex attributes: we should repack other data.) + const hasVertexAttributes = accessorIndices.some((accessorIndex) => + attributeAccessorIndices.has(accessorIndex), + ); + for (let j = 0; j < groups.length; ++j) { + // Each group gets a segment of the bufferView, from its first accessor to the end + // of its last element. The first segment starts at the start of the bufferView. + const group = groups[j]; + const groupByteOffset = j === 0 ? 0 : accessors[group[0]].byteOffset; + const groupByteEnd = Math.max( + ...group.map((accessorIndex) => byteEnds[accessorIndex]), + ); + const groupBufferView = convertBufferView( + bufferView, + bufferView.byteOffset + groupByteOffset, + groupByteEnd - groupByteOffset, + idMaps, + ); + if (hasVertexAttributes) { + groupBufferView.byteStride = byteStrides[group[0]]; } - // The first group of accessors keeps the original buffer view, unless an image needs its full byte range - let groupBufferView = bufferView; - if (currentIndex > 0 || bufferViewHasImage[bufferViewId]) { - groupBufferView = clone(bufferView, true); - const groupBufferViewId = addToArray(bufferViews, groupBufferView); - for (let j = currentIndex; j <= i; ++j) { - const groupAccessor = accessors[j]; - groupAccessor.bufferView = groupBufferViewId; - groupAccessor.byteOffset = - groupAccessor.byteOffset - currentByteOffset; - } + let groupBufferViewIndex; + if (j === 0 && firstGroupKeepsIndex) { + convertedBufferViews[i] = groupBufferView; + groupBufferViewIndex = i; + } else { + groupBufferViewIndex = addToArray( + convertedBufferViews, + groupBufferView, + ); } - if (bufferViewHasVertexAttributes[bufferViewId]) { - groupBufferView.byteStride = accessorByteStride; + + // Accessor byte offsets are relative to the start of the segment + for (const accessorIndex of group) { + accessorBufferViews[accessorIndex] = groupBufferViewIndex; + accessorByteOffsets[accessorIndex] = + accessors[accessorIndex].byteOffset - groupByteOffset; } - groupBufferView.byteOffset = bufferViewByteOffset + currentByteOffset; - groupBufferView.byteLength = - accessorByteOffset + accessorByteLength - currentByteOffset; - // Set current byte offset to next accessor's byte offset - currentByteOffset = hasNextAccessor - ? accessors[i + 1].byteOffset - : undefined; - currentIndex = i + 1; } } + + return { + bufferViews: convertedBufferViews, + accessors: accessors.map((accessor, i) => + convertAccessor(accessor, accessorBufferViews[i], accessorByteOffsets[i]), + ), + }; +} + +/** + * Converts a segment of a glTF 1.0 bufferView to a glTF 2.0 bufferView. + * + * @param {Gltf1.BufferView} bufferView + * @param {number} byteOffset The byte offset of the segment in the buffer. + * @param {number} byteLength The byte length of the segment. + * @param {IdMaps} idMaps + * @returns {Gltf2.BufferView} + * + * @private + */ +function convertBufferView(bufferView, byteOffset, byteLength, idMaps) { + const { buffer, ...rest } = bufferView; + return { + ...rest, + buffer: idMaps.buffers[buffer], + byteOffset: byteOffset, + byteLength: byteLength, + }; } /** - * @param {any} gltf + * Converts a glTF 1.0 accessor to a glTF 2.0 accessor in the given bufferView. + * + * @param {Gltf1.Accessor} accessor + * @param {number} [bufferViewIndex] The index of the glTF 2.0 bufferView. + * @param {number} [byteOffsetInBufferView] The byte offset of the accessor in that bufferView. + * @returns {Gltf2.Accessor} + * + * @private + */ +function convertAccessor(accessor, bufferViewIndex, byteOffsetInBufferView) { + const { bufferView, byteOffset, byteStride, ...rest } = accessor; + // bufferViewIndex may be undefined for badly formed input + if (!defined(bufferViewIndex)) { + // Return an accessor without a bufferView, which will read as zeros + return rest; + } + return { + ...rest, + bufferView: bufferViewIndex, + byteOffset: byteOffsetInBufferView, + }; +} + +/** + * @param {Gltf2} gltf * * @private */ @@ -888,14 +776,16 @@ function requirePositionAccessorMinMax(gltf) { } /** - * @param {any} node + * @param {Gltf1.Node} node + * @param {Record} nodes The nodes not yet found empty. * @returns {boolean} * * @private */ -function isNodeEmpty(node) { +function isNodeEmpty(node, nodes) { return ( - (!defined(node.children) || node.children.length === 0) && + (!defined(node.children) || + node.children.every((childId) => !defined(nodes[childId]))) && (!defined(node.meshes) || node.meshes.length === 0) && !defined(node.camera) && !defined(node.skin) && @@ -917,60 +807,32 @@ function isNodeEmpty(node) { } /** - * @param {any} gltf - * @param {string|number} nodeId + * Returns a copy of the id-keyed nodes without the empty nodes. Also discards parent + * nodes that are empty after their empty children are discarded. * - * @private - */ -function deleteNode(gltf, nodeId) { - // Remove from list of nodes in scene - ForEach.scene(gltf, function (scene) { - const sceneNodes = scene.nodes; - if (defined(sceneNodes)) { - const sceneNodesLength = sceneNodes.length; - for (let i = sceneNodesLength; i >= 0; --i) { - if (sceneNodes[i] === nodeId) { - sceneNodes.splice(i, 1); - return; - } - } - } - }); - - // Remove parent node's reference to this node, and delete the parent if also empty - ForEach.node(gltf, function (parentNode, parentNodeId) { - if (defined(parentNode.children)) { - const index = parentNode.children.indexOf(nodeId); - if (index > -1) { - parentNode.children.splice(index, 1); - - if (isNodeEmpty(parentNode)) { - deleteNode(gltf, parentNodeId); - } - } - } - }); - - delete gltf.nodes[nodeId]; -} - -/** - * @param {any} gltf + * @param {Record} nodes + * @returns {Record} The nodes that aren't empty. * * @private */ -function removeEmptyNodes(gltf) { - ForEach.node(gltf, function (node, nodeId) { - if (isNodeEmpty(node)) { - deleteNode(gltf, nodeId); +function getNonEmptyNodes(nodes) { + const nonEmptyNodes = { ...nodes }; + let removedNode; + do { + removedNode = false; + for (const nodeId of Object.keys(nonEmptyNodes)) { + if (isNodeEmpty(nonEmptyNodes[nodeId], nonEmptyNodes)) { + delete nonEmptyNodes[nodeId]; + removedNode = true; + } } - }); + } while (removedNode); - return gltf; + return nonEmptyNodes; } /** - * @param {any} gltf + * @param {Gltf2} gltf * * @private */ @@ -988,7 +850,7 @@ function requireAnimationAccessorMinMax(gltf) { } /** - * @param {any} gltf + * @param {Gltf2} gltf * * @private */ @@ -1007,58 +869,113 @@ function validatePresentAccessorMinMax(gltf) { } /** - * @param {any} gltf + * Builds a glTF 2.0 asset from a glTF 1.0 asset. + * + * @param {Gltf1} gltf + * @returns {Gltf2} The glTF 2.0 asset. It shares objects with the input, so + * modifying it can modify the input. * * @private */ -function glTF10to20(gltf) { - gltf.asset = gltf.asset ?? {}; - gltf.asset.version = "2.0"; - // Techniques are converted to PBR materials, which don't use shaders - delete gltf.programs; - delete gltf.shaders; - delete gltf.glExtensionsUsed; - // material.instanceTechnique properties should be directly on the material. instanceTechnique is a gltf 0.8 property but is seen in some 1.0 models. - updateInstanceTechniques(gltf); - // animation.samplers now refers directly to accessors and animation.parameters should be removed - removeAnimationSamplersIndirection(gltf); - // Remove empty nodes and re-assign referencing indices - removeEmptyNodes(gltf); - // Top-level objects are now arrays referenced by index instead of id - objectsToArrays(gltf); - // Animation.sampler objects cannot have names - removeAnimationSamplerNames(gltf); - // asset.profile no longer exists - stripAsset(gltf); - // Move known extensions from extensionsUsed to extensionsRequired - requireKnownExtensions(gltf); - // bufferView.byteLength and buffer.byteLength are required - requireByteLength(gltf); - // byteStride moved from accessor to bufferView - moveByteStrideToBufferView(gltf); +function gltf1to2(gltf) { + const nonEmptyNodes = getNonEmptyNodes(gltf.nodes ?? {}); + + /** @type {IdMaps} */ + const idMaps = { + accessors: getIdMap(gltf.accessors), + animations: getIdMap(gltf.animations), + buffers: getIdMap(gltf.buffers), + bufferViews: getIdMap(gltf.bufferViews), + cameras: getIdMap(gltf.cameras), + images: getIdMap(gltf.images), + materials: getIdMap(gltf.materials), + meshes: getIdMap(gltf.meshes), + nodes: getIdMap(nonEmptyNodes), + samplers: getIdMap(gltf.samplers), + scenes: getIdMap(gltf.scenes), + skins: getIdMap(gltf.skins), + textures: getIdMap(gltf.textures), + }; + + // Copy the id-keyed top-level objects into arrays + const accessors = objectToArray(gltf.accessors); + const animations = objectToArray(gltf.animations); + const buffers = objectToArray(gltf.buffers); + const bufferViews = objectToArray(gltf.bufferViews); + const cameras = objectToArray(gltf.cameras); + const images = objectToArray(gltf.images); + const materials = objectToArray(gltf.materials); + const meshes = objectToArray(gltf.meshes); + const nodes = objectToArray(nonEmptyNodes); + const samplers = objectToArray(gltf.samplers); + const scenes = objectToArray(gltf.scenes); + const skins = objectToArray(gltf.skins); + const textures = objectToArray(gltf.textures); + + const convertedBufferViewsAndAccessors = convertBufferViewsAndAccessors( + bufferViews, + accessors, + images, + meshes, + idMaps, + ); + const techniques = gltf.techniques ?? {}; + const jointNames = getJointNames(nodes); + const skeletons = getSkeletons(nodes, idMaps); + const extensionsUsed = gltf.extensionsUsed ?? []; + + // Techniques are converted to PBR materials, so programs, shaders, techniques, + // and glExtensionsUsed are left out + /** @type {Gltf2} */ + const result = { + asset: convertAsset(gltf.asset ?? { version: "1.0" }), + accessors: convertedBufferViewsAndAccessors.accessors, + animations: animations.map((animation) => + convertAnimation(animation, idMaps), + ), + buffers: buffers.map((buffer) => convertBuffer(buffer)), + bufferViews: convertedBufferViewsAndAccessors.bufferViews, + cameras: cameras.map((camera) => convertCamera(camera)), + images: images.map((image) => convertImage(image, idMaps)), + materials: materials.map((material) => + convertMaterial(material, techniques, idMaps), + ), + meshes: meshes.map((mesh) => convertMesh(mesh, idMaps)), + nodes: convertNodes(nodes, idMaps), + samplers: samplers, + scenes: scenes.map((scene) => convertScene(scene, idMaps)), + skins: skins.map((skin, index) => + convertSkin(skin, jointNames, skeletons[index], idMaps), + ), + textures: textures.map((texture) => convertTexture(texture, idMaps)), + extensionsUsed: extensionsUsed, + extensionsRequired: extensionsUsed.filter((extension) => + defined(knownExtensions[extension]), + ), + }; + if (defined(gltf.scene)) { + result.scene = idMaps.scenes[gltf.scene]; + } + if (defined(gltf.extensions)) { + result.extensions = gltf.extensions; + } + if (defined(gltf.extras)) { + result.extras = gltf.extras; + } + + // The result is not a valid glTF 2.0 asset until these passes run. // accessor.min and accessor.max must be defined for accessors containing POSITION attributes - requirePositionAccessorMinMax(gltf); + requirePositionAccessorMinMax(result); // An animation sampler's input accessor must have min and max properties defined - requireAnimationAccessorMinMax(gltf); - // When an acccessor has a min- or max, then it is recomputed, to capture the actual + requireAnimationAccessorMinMax(result); + // When an accessor has a min- or max, then it is recomputed, to capture the actual // value, and not use the (possibly imprecise) value from the input - validatePresentAccessorMinMax(gltf); - // buffer.type is unnecessary and should be removed - removeBufferType(gltf); - // Remove format, internalFormat, target, and type - removeTextureProperties(gltf); - // TEXCOORD and COLOR attributes must be written with a set index (TEXCOORD_#) - requireAttributeSetIndex(gltf); - // Add underscores to application-specific parameters - underscoreApplicationSpecificSemantics(gltf); + validatePresentAccessorMinMax(result); // Accessors referenced by JOINTS_0 and WEIGHTS_0 attributes must have correct component types - updateAccessorComponentTypes(gltf); - // Clamp camera parameters - clampCameraParameters(gltf); - // Techniques are replaced by PBR materials - convertTechniquesToPbr(gltf); - // Remove empty arrays - removeEmptyArrays(gltf); + updateAccessorComponentTypes(result); + removeEmptyArrays(result); + + return result; } // It's not possible to upgrade glTF 1.0 shaders to 2.0 PBR materials in a generic way, @@ -1087,23 +1004,34 @@ function initializePbrMaterial(material) { } /** - * @param {*} value - * @returns {boolean} + * @param {unknown} value + * @returns {Gltf2.Material.TextureInfo|undefined} The value, if it's a texture. * * @private */ -function isTexture(value) { - return defined(value.index); +function asTexture(value) { + if ( + typeof value === "object" && + value !== null && + "index" in value && + defined(value.index) + ) { + return /** @type {Gltf2.Material.TextureInfo} */ (value); + } + return undefined; } /** - * @param {*} value - * @returns {boolean} + * @param {unknown} value + * @returns {Rgba|undefined} The value, if it's an array of four numbers. * * @private */ -function isVec4(value) { - return Array.isArray(value) && value.length === 4; +function asVec4(value) { + if (Array.isArray(value) && value.length === 4) { + return /** @type {Rgba} */ (value); + } + return undefined; } /** @@ -1139,7 +1067,7 @@ function srgbToLinear(srgb) { /** * @param {Gltf2.Material} material - * @param {Object} values + * @param {Record} values * * @private */ @@ -1148,75 +1076,139 @@ function assignBaseColorFromUniforms(material, values) { ForEach.objectLegacy( values, /** - * @param {*} value + * @param {unknown} value * @param {string} name */ function (value, name) { + const texture = asTexture(value); + const color = asVec4(value); if ( defaultBaseColorTextureNames.indexOf(name) !== -1 && - isTexture(value) + defined(texture) ) { initializePbrMaterial(material); - material.pbrMetallicRoughness.baseColorTexture = value; + material.pbrMetallicRoughness.baseColorTexture = texture; } else if ( defaultBaseColorFactorNames.indexOf(name) !== -1 && - isVec4(value) + defined(color) ) { initializePbrMaterial(material); - material.pbrMetallicRoughness.baseColorFactor = srgbToLinear(value); + material.pbrMetallicRoughness.baseColorFactor = srgbToLinear(color); } }, ); } /** - * @param {any} gltf + * @param {Gltf1.Material} material + * @param {Record} techniques The techniques of the asset by id. + * @param {IdMaps} idMaps + * @returns {Gltf2.Material} * * @private */ -function convertTechniquesToPbr(gltf) { - ForEach.material(gltf, function (material) { - if (!defined(material.technique)) { - return; - } - - // glTF 1.0 material values are keyed by technique parameter name - const technique = gltf.techniques[material.technique]; - /** @type {Object} */ - const uniformNames = {}; - ForEach.objectLegacy( - technique.uniforms, - function (parameterName, uniformName) { - uniformNames[parameterName] = uniformName; - }, +function convertMaterial(material, techniques, idMaps) { + // Some non-compliant glTF 1.0 assets have the glTF 0.8 + // material.instanceTechnique property + const { + technique: techniqueId, + values, + extensions, + ...rest + } = convert08Material(material); + /** @type {Gltf2.Material} */ + const convertedMaterial = { ...rest }; + if (defined(extensions)) { + convertedMaterial.extensions = convertMaterialExtensions( + extensions, + idMaps, ); - // The material value order decides which value becomes the base color - /** @type {Object} */ - const uniformValues = {}; - ForEach.objectLegacy(material.values, function (value, parameterName) { - const uniformName = uniformNames[parameterName]; - if (defined(uniformName)) { - uniformValues[uniformName] = value; - } - }); - assignBaseColorFromUniforms(material, uniformValues); + } - const states = technique.states; - if (defined(states)) { - const enabled = states.enable ?? []; - if (enabled.indexOf(WebGLConstants.BLEND) !== -1) { - material.alphaMode = "BLEND"; - } - if (enabled.indexOf(WebGLConstants.CULL_FACE) === -1) { - material.doubleSided = true; - } + const technique = defined(techniqueId) ? techniques[techniqueId] : undefined; + if (!defined(technique)) { + return convertedMaterial; + } + + // glTF 1.0 material values are keyed by technique parameter name + const convertedValues = convertMaterialValues(values ?? {}, idMaps); + /** @type {Record} */ + const uniformNames = {}; + for (const [uniformName, parameterName] of Object.entries( + technique.uniforms ?? {}, + )) { + uniformNames[parameterName] = uniformName; + } + // The material value order decides which value becomes the base color + /** @type {Record} */ + const uniformValues = {}; + for (const [parameterName, value] of Object.entries(convertedValues)) { + const uniformName = uniformNames[parameterName]; + if (defined(uniformName)) { + uniformValues[uniformName] = value; + } + } + assignBaseColorFromUniforms(convertedMaterial, uniformValues); + + const states = technique.states; + if (defined(states)) { + /** @type {number[]} */ + const enabled = states.enable ?? []; + if (enabled.indexOf(WebGLConstants.BLEND) !== -1) { + convertedMaterial.alphaMode = "BLEND"; } + if (enabled.indexOf(WebGLConstants.CULL_FACE) === -1) { + convertedMaterial.doubleSided = true; + } + } - delete material.technique; - delete material.values; - }); + return convertedMaterial; +} - delete gltf.techniques; +/** + * @param {Gltf1.Property.Extensions} extensions + * @param {IdMaps} idMaps + * @returns {Gltf2.Material.Extensions} + * + * @private + */ +function convertMaterialExtensions(extensions, idMaps) { + // The KHR_materials_common material extension has no schema file + const materialsCommon = + /** @type {KHR_materials_common.Material|undefined} */ ( + extensions.KHR_materials_common + ); + const values = materialsCommon?.values; + if (!defined(values)) { + return extensions; + } + + return { + ...extensions, + KHR_materials_common: { + ...materialsCommon, + values: convertMaterialValues(values, idMaps), + }, + }; +} + +/** + * Converts the texture ids in material values to texture indices. + * + * @param {Record} values + * @param {IdMaps} idMaps + * @returns {Record} + * + * @private + */ +function convertMaterialValues(values, idMaps) { + /** @type {Record} */ + const convertedValues = {}; + for (const [name, value] of Object.entries(values)) { + convertedValues[name] = + typeof value === "string" ? { index: idMaps.textures[value] } : value; + } + return convertedValues; } /** @@ -1237,33 +1229,33 @@ function convertTechniquesWebglToPbr(gltf) { /** * @param {Gltf2.Material} material - * @param {*} baseColor + * @param {unknown} baseColor * * @private */ function assignAsBaseColor(material, baseColor) { - if (defined(baseColor)) { - if (isVec4(baseColor)) { - material.pbrMetallicRoughness.baseColorFactor = srgbToLinear(baseColor); - } else if (isTexture(baseColor)) { - material.pbrMetallicRoughness.baseColorTexture = baseColor; - } + const color = asVec4(baseColor); + const texture = asTexture(baseColor); + if (defined(color)) { + material.pbrMetallicRoughness.baseColorFactor = srgbToLinear(color); + } else if (defined(texture)) { + material.pbrMetallicRoughness.baseColorTexture = texture; } } /** * @param {Gltf2.Material} material - * @param {*} emissive + * @param {unknown} emissive * * @private */ function assignAsEmissive(material, emissive) { - if (defined(emissive)) { - if (isVec4(emissive)) { - material.emissiveFactor = emissive.slice(0, 3); - } else if (isTexture(emissive)) { - material.emissiveTexture = emissive; - } + const color = asVec4(emissive); + const texture = asTexture(emissive); + if (defined(color)) { + material.emissiveFactor = [color[0], color[1], color[2]]; + } else if (defined(texture)) { + material.emissiveTexture = texture; } } @@ -1275,7 +1267,10 @@ function assignAsEmissive(material, emissive) { function convertMaterialsCommonToPbr(gltf) { // Future work: convert KHR_materials_common lights to KHR_lights_punctual ForEach.material(gltf, function (material) { - const materialsCommon = (material.extensions ?? {}).KHR_materials_common; + const materialsCommon = + /** @type {KHR_materials_common.Material|undefined} */ ( + material.extensions?.KHR_materials_common + ); if (!defined(materialsCommon)) { // Nothing to do return; @@ -1285,7 +1280,7 @@ function convertMaterialsCommonToPbr(gltf) { const ambient = values.ambient; const diffuse = values.diffuse; const emission = values.emission; - const transparency = values.transparency; + const transparency = /** @type {number|undefined} */ (values.transparency); // These actually exist on the extension object, not the values object despite what's shown in the spec const doubleSided = materialsCommon.doubleSided; diff --git a/packages/gltf/Source/usesExtension.js b/packages/gltf/Source/usesExtension.js index b4d7b82364e..1932ff97c18 100644 --- a/packages/gltf/Source/usesExtension.js +++ b/packages/gltf/Source/usesExtension.js @@ -1,11 +1,12 @@ import { defined } from "@cesium/core"; /** @import { Gltf1, Gltf2 } from "../SchemaTypes/index.js"; */ +/** @import { Gltf08 } from "./Gltf08.js"; */ /** * Checks whether the glTF uses the given extension. * - * @param {Gltf1 | Gltf2} gltf A javascript object containing a glTF asset. + * @param {Gltf08 | Gltf1 | Gltf2} gltf A javascript object containing a glTF asset. * @param {string} extension The name of the extension. * @returns {boolean} Whether the glTF uses the given extension. * diff --git a/packages/gltf/Specs/ForEachSpec.js b/packages/gltf/Specs/ForEachSpec.js index b888aed2172..bf69ebc6295 100644 --- a/packages/gltf/Specs/ForEachSpec.js +++ b/packages/gltf/Specs/ForEachSpec.js @@ -344,73 +344,6 @@ describe("ForEach", function () { expect(returnValue).toBe(gltf.bufferViews[1]); }); - it("loops over cameras", function () { - const gltf = { - cameras: [ - { - perspective: { - yfov: 0.0, - znear: 0.0, - }, - }, - { - perspective: { - yfov: 1.0, - znear: 1.0, - }, - }, - ], - }; - const returnValue = ForEach.camera(gltf, (camera, index) => { - expect(camera.perspective.yfov).toBe(index); - expect(camera.perspective.znear).toBe(index); - if (index === 1) { - return camera; - } - }); - expect(returnValue).toBe(gltf.cameras[1]); - }); - - it("loops over images", function () { - const gltf = { - images: [ - { - bufferView: 0, - }, - { - bufferView: 1, - }, - ], - }; - const returnValue = ForEach.image(gltf, (image, index) => { - expect(image.bufferView).toBe(index); - if (index === 1) { - return image; - } - }); - expect(returnValue).toBe(gltf.images[1]); - }); - - it("loops over images (gltf 1.0)", function () { - const gltf = { - images: { - image0: { - uri: "image0.png", - }, - image1: { - uri: "image1.png", - }, - }, - }; - const returnValue = ForEach.image(gltf, (image, name) => { - expect(image.uri).toBe(`${name}.png`); - if (name === "image1") { - return image; - } - }); - expect(returnValue).toBe(gltf.images["image1"]); - }); - it("loops over materials", function () { const gltf = { materials: [ @@ -431,30 +364,6 @@ describe("ForEach", function () { expect(returnValue).toBe(gltf.materials[1]); }); - it("loops over legacy material values", function () { - const material = { - name: "Texture", - values: { - diffuse: { - index: 0, - }, - shininess: 256, - specular: [0.2, 0.2, 0.2, 1], - }, - }; - - let count = 0; - const returnValue = ForEach.materialValue(material, (value, materialId) => { - expect(value).toBeDefined(); - count++; - if (materialId === "specular") { - return value; - } - }); - expect(count).toBe(3); - expect(returnValue).toBe(material.values["specular"]); - }); - it("loops over meshes", function () { const gltf = { meshes: [ @@ -686,67 +595,4 @@ describe("ForEach", function () { expect(returnValue).toBe(gltf.samplers[1]); }); - - it("loops over scenes", function () { - const gltf = { - scenes: [ - { - nodes: [0], - }, - { - nodes: [1], - }, - ], - }; - const returnValue = ForEach.scene(gltf, (scene, index) => { - expect(scene.nodes[0]).toBe(index); - - if (index === 1) { - return scene; - } - }); - expect(returnValue).toBe(gltf.scenes[1]); - }); - - it("loops over each skin", function () { - const gltf = { - skins: [ - { - joints: [0], - }, - { - joints: [1], - }, - ], - }; - const returnValue = ForEach.skin(gltf, (skin, index) => { - expect(skin.joints[0]).toBe(index); - - if (index === 1) { - return skin; - } - }); - expect(returnValue).toBe(gltf.skins[1]); - }); - - it("loops over each texture", function () { - const gltf = { - textures: [ - { - source: 0, - }, - { - source: 1, - }, - ], - }; - const returnValue = ForEach.texture(gltf, (texture, index) => { - expect(texture.source).toBe(index); - - if (index === 1) { - return texture; - } - }); - expect(returnValue).toBe(gltf.textures[1]); - }); }); diff --git a/packages/gltf/Specs/updateVersionSpec.js b/packages/gltf/Specs/updateVersionSpec.js index 5dcb6a488c0..7133864813c 100644 --- a/packages/gltf/Specs/updateVersionSpec.js +++ b/packages/gltf/Specs/updateVersionSpec.js @@ -10,6 +10,7 @@ import { updateVersion, } from "../index.js"; import ForEach from "../Source/ForEach.js"; +import readAccessorPacked from "../Source/readAccessorPacked.js"; const gltf1Techniques = "./Data/Models/glTF-1.0/box/box.gltf"; const gltf1TechniquesTextured = @@ -77,17 +78,17 @@ async function loadGltf(url) { describe("updateVersion", function () { it("treats a glTF with no version as 1.0 and updates it to 2.0", function () { const gltf = {}; - updateVersion(gltf); - expect(gltf.asset.version).toEqual("2.0"); + const updatedGltf = updateVersion(gltf); + expect(updatedGltf.asset.version).toEqual("2.0"); }); it("updates empty glTF with version from 0.8 to 2.0", function () { const gltf = { version: "0.8", }; - updateVersion(gltf); - expect(gltf.version).toBeUndefined(); - expect(gltf.asset.version).toEqual("2.0"); + const updatedGltf = updateVersion(gltf); + expect(updatedGltf.version).toBeUndefined(); + expect(updatedGltf.asset.version).toEqual("2.0"); }); it("updates empty glTF with version 1.0 to 2.0", function () { @@ -96,8 +97,8 @@ describe("updateVersion", function () { version: "1.0", }, }; - updateVersion(gltf); - expect(gltf.asset.version).toEqual("2.0"); + const updatedGltf = updateVersion(gltf); + expect(updatedGltf.asset.version).toEqual("2.0"); }); it("updates a glTF with non-standard version to 2.0", function () { @@ -106,8 +107,8 @@ describe("updateVersion", function () { version: "1.0.1", }, }; - updateVersion(gltf); - expect(gltf.asset.version).toEqual("2.0"); + const updatedGltf = updateVersion(gltf); + expect(updatedGltf.asset.version).toEqual("2.0"); }); it("does not update a glTF with an unknown version", function () { @@ -116,8 +117,8 @@ describe("updateVersion", function () { version: "3.0", }, }; - updateVersion(gltf); - expect(gltf.asset.version).toEqual("3.0"); + const updatedGltf = updateVersion(gltf); + expect(updatedGltf.asset.version).toEqual("3.0"); }); it("updates glTF from 0.8 to 2.0", function () { @@ -340,25 +341,25 @@ describe("updateVersion", function () { }, }; - updateVersion(gltf); + const updatedGltf = updateVersion(gltf); // Asset updates: version set to 2.0, profile removed - expect(gltf.asset.version).toEqual("2.0"); - expect(gltf.asset.profile).toBeUndefined(); + expect(updatedGltf.asset.version).toEqual("2.0"); + expect(updatedGltf.asset.profile).toBeUndefined(); // Top-level version removed - expect(gltf.version).toBeUndefined(); + expect(updatedGltf.version).toBeUndefined(); // allExtensions renamed to extensionsUsed - expect(gltf.extensionsUsed).toEqual(["extension"]); - expect(gltf.allExtensions).toBeUndefined(); + expect(updatedGltf.extensionsUsed).toEqual(["extension"]); + expect(updatedGltf.allExtensions).toBeUndefined(); - // gltf.lights removed - expect(gltf.lights).toBeUndefined(); - expect(gltf.extensions).toBeUndefined(); + // updatedGltf.lights removed + expect(updatedGltf.lights).toBeUndefined(); + expect(updatedGltf.extensions).toBeUndefined(); // material.instanceTechnique and technique pass converted to a PBR material - const material = gltf.materials[0]; + const material = updatedGltf.materials[0]; expect(material.instanceTechnique).toBeUndefined(); expect(material.technique).toBeUndefined(); expect(material.values).toBeUndefined(); @@ -367,26 +368,28 @@ describe("updateVersion", function () { ]); expect(material.alphaMode).toBe("BLEND"); expect(material.doubleSided).toBe(true); - expect(gltf.techniques).toBeUndefined(); + expect(updatedGltf.techniques).toBeUndefined(); // primitive.primitive renamed to primitive.mode - const primitive = gltf.meshes[0].primitives[0]; + const primitive = updatedGltf.meshes[0].primitives[0]; expect(primitive.primitive).toBeUndefined(); expect(primitive.mode).toEqual(WebGLConstants.TRIANGLES); // node.instanceSkin is split into node.skin, node.mesh, and skin.skeleton - const node = getNodeByName(gltf, "node"); - const skeleton = getNodeByName(gltf, "skeleton"); + const node = getNodeByName(updatedGltf, "node"); + const skeleton = getNodeByName(updatedGltf, "skeleton"); expect(node.instanceSkin).toBeUndefined(); expect(node.mesh).toBe(0); expect(node.skin).toBe(0); - expect(gltf.skins[0].skeleton).toBe(gltf.nodes.indexOf(skeleton)); + expect(updatedGltf.skins[0].skeleton).toBe( + updatedGltf.nodes.indexOf(skeleton), + ); // Node rotation converted from axis-angle to quaternion expect(node.rotation).toEqual([0.0, 0.0, 0.0, 1.0]); // Animation rotations converted from axis-angle to quaternion - const { source } = gltf.buffers[0].extras._pipeline; + const { source } = updatedGltf.buffers[0].extras._pipeline; expect(source).toEqual(expectedBuffer); }); @@ -715,23 +718,23 @@ describe("updateVersion", function () { glExtensionsUsed: ["OES_element_index_uint"], }; - updateVersion(gltf); + const updatedGltf = updateVersion(gltf); // Asset updates: version set to 2.0, profile removed - expect(gltf.asset.version).toEqual("2.0"); - expect(gltf.asset.profile).toBeUndefined(); + expect(updatedGltf.asset.version).toEqual("2.0"); + expect(updatedGltf.asset.profile).toBeUndefined(); // Extensions used become extensions required - const extensionsUsed = gltf.extensionsUsed; + const extensionsUsed = updatedGltf.extensionsUsed; expect(extensionsUsed).toEqual([ "WEB3D_quantized_attributes", "UNKOWN_EXTENSION", ]); - const extensionsRequired = gltf.extensionsRequired; + const extensionsRequired = updatedGltf.extensionsRequired; expect(extensionsRequired).toEqual(["WEB3D_quantized_attributes"]); // animation.parameters removed - const animation = gltf.animations[0]; + const animation = updatedGltf.animations[0]; const sampler = animation.samplers[0]; expect(sampler.name).toBeUndefined(); expect(sampler.input).toEqual(2); @@ -739,18 +742,20 @@ describe("updateVersion", function () { expect(animation.parameters).toBeUndefined(); // Empty arrays removed - expect(gltf.samplers).toBeUndefined(); - expect(getNodeByName(gltf, "nodeWithoutChildren").children).toBeUndefined(); + expect(updatedGltf.samplers).toBeUndefined(); + expect( + getNodeByName(updatedGltf, "nodeWithoutChildren").children, + ).toBeUndefined(); // Empty nodes removed - expect(getNodeByName(gltf, "nonEmptyNodeParent")).toBeDefined(); - expect(getNodeByName(gltf, "emptyNodeParent")).toBeUndefined(); - expect(getNodeByName(gltf, "emptyNode")).toBeUndefined(); - expect(getNodeByName(gltf, "lightNode")).toBeDefined(); - expect(gltf.scenes[0].nodes.length).toBe(2); + expect(getNodeByName(updatedGltf, "nonEmptyNodeParent")).toBeDefined(); + expect(getNodeByName(updatedGltf, "emptyNodeParent")).toBeUndefined(); + expect(getNodeByName(updatedGltf, "emptyNode")).toBeUndefined(); + expect(getNodeByName(updatedGltf, "lightNode")).toBeDefined(); + expect(updatedGltf.scenes[0].nodes.length).toBe(2); // Technique converted to a PBR material, using uniform names to find the base color - const material = gltf.materials[0]; + const material = updatedGltf.materials[0]; expect(material.technique).toBeUndefined(); expect(material.values).toBeUndefined(); expect(material.extensions).toBeUndefined(); @@ -759,13 +764,13 @@ describe("updateVersion", function () { ]); expect(material.doubleSided).toBeUndefined(); expect(material.alphaMode).toBe("BLEND"); - expect(gltf.techniques).toBeUndefined(); - expect(gltf.programs).toBeUndefined(); - expect(gltf.shaders).toBeUndefined(); - expect(gltf.extensions).toBeUndefined(); + expect(updatedGltf.techniques).toBeUndefined(); + expect(updatedGltf.programs).toBeUndefined(); + expect(updatedGltf.shaders).toBeUndefined(); + expect(updatedGltf.extensions).toBeUndefined(); // TEXCOORD and COLOR are now TEXCOORD_0 and COLOR_0 - const primitive = gltf.meshes[0].primitives[0]; + const primitive = updatedGltf.meshes[0].primitives[0]; expect(primitive.attributes.TEXCOORD).toBeUndefined(); expect(primitive.attributes.TEXCOORD_0).toEqual(6); expect(primitive.attributes.COLOR).toBeUndefined(); @@ -783,24 +788,26 @@ describe("updateVersion", function () { expect(primitive.attributes._TEMPERATURE).toEqual(10); // JOINTS_0 has converted component type - expect(gltf.accessors[8].componentType).toBe(WebGLConstants.UNSIGNED_SHORT); + expect(updatedGltf.accessors[8].componentType).toBe( + WebGLConstants.UNSIGNED_SHORT, + ); // Clamp camera parameters - const camera = gltf.cameras[0]; + const camera = updatedGltf.cameras[0]; expect(camera.perspective.aspectRatio).toBeUndefined(); expect(camera.perspective.yfov).toEqual(1.0); // Sets byteLength for buffers and bufferViews - const buffer = gltf.buffers[0]; + const buffer = updatedGltf.buffers[0]; expect(buffer.type).toBeUndefined(); expect(buffer.byteLength).toEqual(source.byteLength); - const bufferView = getBufferViewByName(gltf, "bufferView"); + const bufferView = getBufferViewByName(updatedGltf, "bufferView"); expect(bufferView.byteLength).toEqual(12); // Min and max are added to all POSITION accessors - ForEach.accessorWithSemantic(gltf, "POSITION", (accessorId) => { - const accessor = gltf.accessors[accessorId]; + ForEach.accessorWithSemantic(updatedGltf, "POSITION", (accessorId) => { + const accessor = updatedGltf.accessors[accessorId]; expect(accessor.min.length).toEqual( numberOfComponentsForType(accessor.type), ); @@ -810,9 +817,9 @@ describe("updateVersion", function () { }); // Min and max are added to all animation sampler input accessors - ForEach.animation(gltf, (animation) => { + ForEach.animation(updatedGltf, (animation) => { ForEach.animationSampler(animation, (sampler) => { - const accessor = gltf.accessors[sampler.input]; + const accessor = updatedGltf.accessors[sampler.input]; expect(accessor.min.length).toEqual( numberOfComponentsForType(accessor.type), ); @@ -823,11 +830,15 @@ describe("updateVersion", function () { }); // byteStride moved from accessor to bufferView - const positionAccessor = gltf.accessors[primitive.attributes.POSITION]; - const normalAccessor = gltf.accessors[primitive.attributes.NORMAL]; - const texcoordAccessor = gltf.accessors[primitive.attributes.TEXCOORD_0]; - const positionBufferView = gltf.bufferViews[positionAccessor.bufferView]; - const texcoordBufferView = gltf.bufferViews[texcoordAccessor.bufferView]; + const positionAccessor = + updatedGltf.accessors[primitive.attributes.POSITION]; + const normalAccessor = updatedGltf.accessors[primitive.attributes.NORMAL]; + const texcoordAccessor = + updatedGltf.accessors[primitive.attributes.TEXCOORD_0]; + const positionBufferView = + updatedGltf.bufferViews[positionAccessor.bufferView]; + const texcoordBufferView = + updatedGltf.bufferViews[texcoordAccessor.bufferView]; expect(positionAccessor.bufferView).toBe(1); expect(normalAccessor.bufferView).toBe(2); expect(texcoordAccessor.bufferView).toBe(2); @@ -842,7 +853,7 @@ describe("updateVersion", function () { expect(texcoordAccessor.byteStride).toBeUndefined(); // glExtensionsUsed removed - expect(gltf.glExtensionsUsed).toBeUndefined(); + expect(updatedGltf.glExtensionsUsed).toBeUndefined(); }); function createTechniqueGltf(states) { @@ -864,35 +875,38 @@ describe("updateVersion", function () { } it("sets material.doubleSided if a glTF 1.0 technique does not enable CULL_FACE", function () { - let gltf = createTechniqueGltf({ - enable: [WebGLConstants.DEPTH_TEST, WebGLConstants.CULL_FACE], - }); - updateVersion(gltf); - expect(gltf.materials[0].doubleSided).toBeUndefined(); + let updatedGltf = updateVersion( + createTechniqueGltf({ + enable: [WebGLConstants.DEPTH_TEST, WebGLConstants.CULL_FACE], + }), + ); + expect(updatedGltf.materials[0].doubleSided).toBeUndefined(); - gltf = createTechniqueGltf({ - enable: [WebGLConstants.DEPTH_TEST], - }); - updateVersion(gltf); - expect(gltf.materials[0].doubleSided).toBe(true); + updatedGltf = updateVersion( + createTechniqueGltf({ + enable: [WebGLConstants.DEPTH_TEST], + }), + ); + expect(updatedGltf.materials[0].doubleSided).toBe(true); - gltf = createTechniqueGltf(undefined); - updateVersion(gltf); - expect(gltf.materials[0].doubleSided).toBeUndefined(); + updatedGltf = updateVersion(createTechniqueGltf(undefined)); + expect(updatedGltf.materials[0].doubleSided).toBeUndefined(); }); it("sets material.alphaMode if a glTF 1.0 technique enables BLEND", function () { - let gltf = createTechniqueGltf({ - enable: [WebGLConstants.DEPTH_TEST, WebGLConstants.BLEND], - }); - updateVersion(gltf); - expect(gltf.materials[0].alphaMode).toBe("BLEND"); + let updatedGltf = updateVersion( + createTechniqueGltf({ + enable: [WebGLConstants.DEPTH_TEST, WebGLConstants.BLEND], + }), + ); + expect(updatedGltf.materials[0].alphaMode).toBe("BLEND"); - gltf = createTechniqueGltf({ - enable: [WebGLConstants.DEPTH_TEST], - }); - updateVersion(gltf); - expect(gltf.materials[0].alphaMode).toBeUndefined(); + updatedGltf = updateVersion( + createTechniqueGltf({ + enable: [WebGLConstants.DEPTH_TEST], + }), + ); + expect(updatedGltf.materials[0].alphaMode).toBeUndefined(); }); it("chooses the base color texture of a glTF 1.0 technique in material value order", function () { @@ -922,8 +936,10 @@ describe("updateVersion", function () { diffuseTexture: {}, }, }; - updateVersion(gltf); - expect(gltf.materials[0].pbrMetallicRoughness.baseColorTexture).toEqual({ + const updatedGltf = updateVersion(gltf); + expect( + updatedGltf.materials[0].pbrMetallicRoughness.baseColorTexture, + ).toEqual({ index: 1, }); }); @@ -968,25 +984,148 @@ describe("updateVersion", function () { }, }; - updateVersion(gltf); + const updatedGltf = updateVersion(gltf); - const image = gltf.images[0]; - const imageBufferView = gltf.bufferViews[image.bufferView]; + const image = updatedGltf.images[0]; + const imageBufferView = updatedGltf.bufferViews[image.bufferView]; expect(imageBufferView.byteOffset).toBe(12); expect(imageBufferView.byteLength).toBe(68); - const accessor = gltf.accessors[0]; + const accessor = updatedGltf.accessors[0]; expect(accessor.bufferView).not.toBe(image.bufferView); - const accessorBufferView = gltf.bufferViews[accessor.bufferView]; + const accessorBufferView = updatedGltf.bufferViews[accessor.bufferView]; expect(accessorBufferView.byteOffset).toBe(12); expect(accessorBufferView.byteLength).toBe(4); }); + it("puts interleaved glTF 1.0 vertex attributes in one buffer view", function () { + const gltf = { + asset: { + version: "1.0", + }, + buffers: { + buffer: { + byteLength: 72, + extras: { + _pipeline: { + source: new Uint8Array(new Float32Array(18).buffer), + }, + }, + }, + }, + bufferViews: { + bufferView: { + buffer: "buffer", + byteOffset: 0, + }, + }, + accessors: { + accessorPosition: { + bufferView: "bufferView", + byteOffset: 0, + byteStride: 24, + componentType: WebGLConstants.FLOAT, + count: 3, + type: "VEC3", + }, + accessorNormal: { + bufferView: "bufferView", + byteOffset: 12, + byteStride: 24, + componentType: WebGLConstants.FLOAT, + count: 3, + type: "VEC3", + }, + }, + meshes: { + mesh: { + primitives: [ + { + attributes: { + POSITION: "accessorPosition", + NORMAL: "accessorNormal", + }, + }, + ], + }, + }, + }; + + const updatedGltf = updateVersion(gltf); + + expect(updatedGltf.bufferViews.length).toBe(1); + expect(updatedGltf.accessors[0].bufferView).toBe(0); + expect(updatedGltf.accessors[1].bufferView).toBe(0); + expect(updatedGltf.bufferViews[0].byteStride).toBe(24); + expect(updatedGltf.bufferViews[0].byteLength).toBe(72); + }); + + it("keeps the values of a strided accessor in a glTF 1.0 buffer view with vertex attributes", function () { + const values = new Float32Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]); + const gltf = { + asset: { + version: "1.0", + }, + buffers: { + buffer: { + byteLength: 48, + extras: { + _pipeline: { + source: new Uint8Array(values.buffer), + }, + }, + }, + }, + bufferViews: { + bufferView: { + buffer: "buffer", + byteOffset: 0, + }, + }, + accessors: { + accessorPosition: { + bufferView: "bufferView", + byteOffset: 0, + byteStride: 12, + componentType: WebGLConstants.FLOAT, + count: 3, + type: "VEC3", + }, + // Every other float, starting at float 9: [9, 11] + accessorStrided: { + bufferView: "bufferView", + byteOffset: 36, + byteStride: 8, + componentType: WebGLConstants.FLOAT, + count: 2, + type: "SCALAR", + }, + }, + meshes: { + mesh: { + primitives: [ + { + attributes: { + POSITION: "accessorPosition", + }, + }, + ], + }, + }, + }; + + const updatedGltf = updateVersion(gltf); + + expect(readAccessorPacked(updatedGltf, updatedGltf.accessors[1])).toEqual([ + 9, 11, + ]); + }); + it("updates glTF 1.0 techniques to PBR materials", async function () { const gltf = await loadGltf(gltf1Techniques); - updateVersion(gltf); + const updatedGltf = updateVersion(gltf); - const material = gltf.materials[0]; + const material = updatedGltf.materials[0]; expect(material.pbrMetallicRoughness.roughnessFactor).toBe(1.0); expect(material.pbrMetallicRoughness.metallicFactor).toBe(0.0); expect( @@ -1000,16 +1139,16 @@ describe("updateVersion", function () { expect(material.pbrMetallicRoughness.baseColorFactor[2]).toBe(0.0); expect(material.pbrMetallicRoughness.baseColorFactor[3]).toBe(1.0); - expect(gltf.extensionsRequired).toBeUndefined(); - expect(gltf.extensionsUsed).toBeUndefined(); + expect(updatedGltf.extensionsRequired).toBeUndefined(); + expect(updatedGltf.extensionsUsed).toBeUndefined(); expect(material.extensions).toBeUndefined(); }); it("updates glTF 1.0 techniques with textures to PBR materials", async function () { const gltf = await loadGltf(gltf1TechniquesTextured); - updateVersion(gltf); + const updatedGltf = updateVersion(gltf); - const material = gltf.materials[0]; + const material = updatedGltf.materials[0]; expect(material.pbrMetallicRoughness.roughnessFactor).toBe(1.0); expect(material.pbrMetallicRoughness.metallicFactor).toBe(0.0); expect(material.pbrMetallicRoughness.baseColorTexture.index).toBe(0); @@ -1017,9 +1156,9 @@ describe("updateVersion", function () { it("updates glTF 1.0 with KHR_materials_common to PBR materials", async function () { const gltf = await loadGltf(gltf1MaterialsCommon); - updateVersion(gltf); + const updatedGltf = updateVersion(gltf); - const material = gltf.materials[0]; + const material = updatedGltf.materials[0]; expect(material.pbrMetallicRoughness.roughnessFactor).toBe(1.0); expect(material.pbrMetallicRoughness.metallicFactor).toBe(0.0); expect( @@ -1035,16 +1174,16 @@ describe("updateVersion", function () { expect(material.doubleSided).toBe(false); expect(material.alphaMode).toBe("OPAQUE"); - expect(gltf.extensionsRequired).toBeUndefined(); - expect(gltf.extensionsUsed).toBeUndefined(); + expect(updatedGltf.extensionsRequired).toBeUndefined(); + expect(updatedGltf.extensionsUsed).toBeUndefined(); expect(material.extensions).toBeUndefined(); }); it("updates glTF 1.0 with KHR_materials_common with textures to PBR materials", async function () { const gltf = await loadGltf(gltf1MaterialsCommonTextured); - updateVersion(gltf); + const updatedGltf = updateVersion(gltf); - const material = gltf.materials[0]; + const material = updatedGltf.materials[0]; expect(material.pbrMetallicRoughness.roughnessFactor).toBe(1.0); expect(material.pbrMetallicRoughness.metallicFactor).toBe(0.0); expect(material.pbrMetallicRoughness.baseColorTexture.index).toBe(0); @@ -1058,11 +1197,11 @@ describe("updateVersion", function () { const materialsCommon = gltf.materials["Effect-Red"].extensions.KHR_materials_common; materialsCommon.technique = "CONSTANT"; - updateVersion(gltf); + const updatedGltf = updateVersion(gltf); - const material = gltf.materials[0]; + const material = updatedGltf.materials[0]; expect(material.extensions.KHR_materials_unlit).toBeDefined(); - expect(gltf.extensionsUsed.indexOf("KHR_materials_unlit") !== -1); + expect(updatedGltf.extensionsUsed.indexOf("KHR_materials_unlit") !== -1); }); it("updates glTF 1.0 with KHR_materials_common with CONSTANT technique to PBR materials using emissive as the base color texture when diffuse is not present", async function () { @@ -1075,12 +1214,12 @@ describe("updateVersion", function () { materialsCommon.values.emission = materialsCommon.values.diffuse; delete materialsCommon.values.diffuse; materialsCommon.technique = "CONSTANT"; - updateVersion(gltf); + const updatedGltf = updateVersion(gltf); - const material = gltf.materials[0]; + const material = updatedGltf.materials[0]; expect(material.pbrMetallicRoughness.baseColorTexture).toBeDefined(); expect(material.extensions.KHR_materials_unlit).toBeDefined(); - expect(gltf.extensionsUsed.indexOf("KHR_materials_unlit") !== -1); + expect(updatedGltf.extensionsUsed.indexOf("KHR_materials_unlit") !== -1); }); it("updates glTF 1.0 with KHR_materials_common with other values to PBR materials", async function () { @@ -1095,9 +1234,9 @@ describe("updateVersion", function () { materialsCommon.values.emission = [0.2, 0.2, 0.2, 1.0]; materialsCommon.values.transparency = 0.5; - updateVersion(gltf); + const updatedGltf = updateVersion(gltf); - const material = gltf.materials[0]; + const material = updatedGltf.materials[0]; expect(material.emissiveFactor).toEqual([0.2, 0.2, 0.2]); expect(material.doubleSided).toBe(true); expect(material.alphaMode).toBe("BLEND"); @@ -1106,25 +1245,25 @@ describe("updateVersion", function () { it("updates glTF 2.0 with KHR_techniques_webgl to PBR materials", async function () { const gltf = await loadGltf(gltf2TechniquesTextured); - updateVersion(gltf); + const updatedGltf = updateVersion(gltf); - const material = gltf.materials[0]; + const material = updatedGltf.materials[0]; expect(material.pbrMetallicRoughness.roughnessFactor).toBe(1.0); expect(material.pbrMetallicRoughness.metallicFactor).toBe(0.0); expect(material.pbrMetallicRoughness.baseColorTexture.index).toBe(0); - expect(gltf.extensionsRequired).toBeUndefined(); - expect(gltf.extensionsUsed).toBeUndefined(); + expect(updatedGltf.extensionsRequired).toBeUndefined(); + expect(updatedGltf.extensionsUsed).toBeUndefined(); expect(material.extensions).toBeUndefined(); }); it("keeps the version of glTF 2.1 with KHR_techniques_webgl and converts it to PBR materials", async function () { const gltf = await loadGltf(gltf2TechniquesTextured); gltf.asset.version = "2.1"; - updateVersion(gltf); + const updatedGltf = updateVersion(gltf); - expect(gltf.asset.version).toEqual("2.1"); - const material = gltf.materials[0]; + expect(updatedGltf.asset.version).toEqual("2.1"); + const material = updatedGltf.materials[0]; expect(material.pbrMetallicRoughness.baseColorTexture.index).toBe(0); expect(material.extensions).toBeUndefined(); }); diff --git a/packages/gltf/gltf.entry.d.ts b/packages/gltf/gltf.entry.d.ts index d77918aece0..e1a2d83ffb8 100644 --- a/packages/gltf/gltf.entry.d.ts +++ b/packages/gltf/gltf.entry.d.ts @@ -2,3 +2,4 @@ export * from "./Build/Types/index.js"; export type * from "./Build/Types/SchemaTypes/index.js"; export type { ComponentReader } from "./Build/Types/Source/ComponentReader.js"; export type { ForEachElementHandler } from "./Build/Types/Source/ForEachElementHandler.js"; +export type { Gltf08 } from "./Build/Types/Source/Gltf08.js"; diff --git a/packages/gltf/scripts/gltfSchemaSources.json b/packages/gltf/scripts/gltfSchemaSources.json index 9f106bda47a..b2b5036b301 100644 --- a/packages/gltf/scripts/gltfSchemaSources.json +++ b/packages/gltf/scripts/gltfSchemaSources.json @@ -34,6 +34,20 @@ ] } }, + "3DTILES_shape_ellipsoid_region": { + "repository": "CesiumGS/glTF", + "branch": "3d-tiles-2.0", + "commit": "e68efc9086f60743c331a2c757a1ffadcdb5d532", + "schemaDirectory": "extensions/2.1/Vendor/3DTILES_shape_ellipsoid_region/schema", + "core": [ + "2.1" + ], + "extends": { + "shape.3DTILES_shape_ellipsoid_region.schema.json": [ + "shape" + ] + } + }, "3DTILES_subtree": { "repository": "CesiumGS/glTF", "branch": "3d-tiles-2.0",