Skip to main content

Import

Struct Import 

Source
pub struct Import {
    pub document: Document,
    pub resources: ResourceStore,
    pub input_format: GltfContainerFormat,
    /* private fields */
}
Expand description

Lossless glTF document plus its resolved resources.

Fields§

§document: Document

Lossless parsed glTF document.

§resources: ResourceStore

Resolved buffer resources indexed by document buffer index.

§input_format: GltfContainerFormat

Container format from which this import was read.

Implementations§

Source§

impl Import

Source

pub fn compress_primitive( &mut self, mesh: MeshIndex, primitive: usize, options: CompressionOptions, ) -> Result<CompressionReport>

Compresses one ordinary triangle primitive atomically.

The document and resolved resources are updated only after encoding, validation, reference remapping, and output-limit checks all succeed. In CompressionMode::DracoOnly the operation rejects unregistered extensions whose binary references cannot be remapped safely.

Examples found in repository?
examples/gltf_tool.rs (line 55)
40fn main() -> Result<(), Box<dyn std::error::Error>> {
41    let mut args = std::env::args_os().skip(1);
42    let input = PathBuf::from(args.next().ok_or_else(|| {
43        io::Error::new(
44            io::ErrorKind::InvalidInput,
45            "usage: gltf_tool <input.gltf|input.glb> [output.glb]",
46        )
47    })?);
48    let output = args.next().map(PathBuf::from);
49    if args.next().is_some() {
50        return Err(io::Error::new(io::ErrorKind::InvalidInput, "too many arguments").into());
51    }
52
53    let mut import = draco_gltf::import(&input)?;
54    if let Some(output) = output {
55        let report = import.compress_primitive(MeshIndex(0), 0, CompressionOptions::default())?;
56        let bytes = import.to_bytes(OutputFormat::GlbV2)?;
57        std::fs::write(output, bytes)?;
58        println!("compression_report={report:?}");
59    } else {
60        let (primitives, faces) = decoded_draco_stats(&import)?;
61        println!("decoded_draco_primitives={primitives} decoded_faces={faces}");
62    }
63    Ok(())
64}
Source§

impl Import

Source

pub fn write_primitive( &mut self, primitive: PrimitiveIndex, geometry: &PackedGeometry, options: GeometryWriteOptions, ) -> Result<GeometryWriteReport>

Replaces one primitive’s geometry atomically.

Raw storage is the default. The existing material, extras, morph targets with the same vertex count, and unrelated extensions remain on the primitive. Shared source accessors are never modified in place.

Source

pub fn push_primitive( &mut self, mesh: MeshIndex, geometry: &PackedGeometry, options: GeometryWriteOptions, ) -> Result<PrimitiveIndex>

Appends packed geometry to an existing mesh atomically.

Returns the stable location accepted by Import::read_primitive and Import::write_primitive.

Source

pub fn from_geometry( geometry: &PackedGeometry, profile: ValidationProfile, options: GeometryWriteOptions, ) -> Result<Self>

Creates a minimal scene containing one packed primitive.

use draco_gltf::{
    ComponentType, GeometryWriteOptions, Import, PackedAttribute,
    PackedGeometry, PrimitiveMode, ValidationProfile,
};

let position = PackedAttribute::new(
    "POSITION", 1, 3, ComponentType::F32, false, vec![0; 12],
)?;
let geometry = PackedGeometry::new(PrimitiveMode::Points, vec![position], None)?;
let scene = Import::from_geometry(
    &geometry,
    ValidationProfile::Gltf20,
    GeometryWriteOptions::default(),
)?;
assert_eq!(scene.document.meshes().len(), 1);
Source§

impl Import

Source

pub fn validate(&self, extensions: &ExtensionRegistry) -> Result<()>

Validates the document and all registered extension handlers.

With strict-validation, this also checks the complete scene graph.

Source

pub fn draco_primitives(&self) -> impl Iterator<Item = PrimitiveRef<'_>> + '_

Iterates primitives carrying the built-in Draco extension.

Examples found in repository?
examples/gltf_tool.rs (line 11)
8fn decoded_draco_stats(import: &Import) -> Result<(usize, usize), Box<dyn std::error::Error>> {
9    let mut primitives = 0usize;
10    let mut faces = 0usize;
11    for primitive in import.draco_primitives() {
12        let mesh = import.decode_draco_primitive(primitive)?;
13        if mesh.num_faces() == 0 {
14            return Err(io::Error::new(
15                io::ErrorKind::InvalidData,
16                "Draco primitive decoded to zero faces",
17            )
18            .into());
19        }
20        primitives = primitives.checked_add(1).ok_or_else(|| {
21            io::Error::new(
22                io::ErrorKind::InvalidData,
23                "decoded primitive count overflow",
24            )
25        })?;
26        faces = faces.checked_add(mesh.num_faces()).ok_or_else(|| {
27            io::Error::new(io::ErrorKind::InvalidData, "decoded face count overflow")
28        })?;
29    }
30    if primitives == 0 || faces == 0 {
31        return Err(io::Error::new(
32            io::ErrorKind::InvalidData,
33            "document contains no decodable Draco triangle faces",
34        )
35        .into());
36    }
37    Ok((primitives, faces))
38}
Source

pub fn decode_draco_primitive( &self, primitive: PrimitiveRef<'_>, ) -> Result<Mesh>

Decodes a primitive through the supplied extension registry.

Examples found in repository?
examples/gltf_tool.rs (line 12)
8fn decoded_draco_stats(import: &Import) -> Result<(usize, usize), Box<dyn std::error::Error>> {
9    let mut primitives = 0usize;
10    let mut faces = 0usize;
11    for primitive in import.draco_primitives() {
12        let mesh = import.decode_draco_primitive(primitive)?;
13        if mesh.num_faces() == 0 {
14            return Err(io::Error::new(
15                io::ErrorKind::InvalidData,
16                "Draco primitive decoded to zero faces",
17            )
18            .into());
19        }
20        primitives = primitives.checked_add(1).ok_or_else(|| {
21            io::Error::new(
22                io::ErrorKind::InvalidData,
23                "decoded primitive count overflow",
24            )
25        })?;
26        faces = faces.checked_add(mesh.num_faces()).ok_or_else(|| {
27            io::Error::new(io::ErrorKind::InvalidData, "decoded face count overflow")
28        })?;
29    }
30    if primitives == 0 || faces == 0 {
31        return Err(io::Error::new(
32            io::ErrorKind::InvalidData,
33            "document contains no decodable Draco triangle faces",
34        )
35        .into());
36    }
37    Ok((primitives, faces))
38}
Source

pub fn read_primitive( &self, primitive: PrimitiveIndex, ) -> Result<PackedGeometry>

Reads one ordinary or Draco-compressed primitive into packed buffers.

Sparse overlays and byte strides are materialized without changing component types or normalization flags. Draco is decoded only when the draco-decode feature is enabled.

Source

pub fn to_bytes(&self, output: OutputFormat) -> Result<Vec<u8>>

Serializes this import into the requested container format.

crate::OutputFormat::GltfJson is valid only when every materialized buffer already has an embedded or external URI. For transformed scenes that need newly generated companion buffers, use Import::to_gltf_output instead. GLB output embeds all resolved buffers in one binary chunk.

let scene = import_slice(input, None)?;
let glb = scene.to_bytes(OutputFormat::GlbV2)?;
assert_eq!(&glb[0..4], b"glTF");
Examples found in repository?
examples/gltf_tool.rs (line 56)
40fn main() -> Result<(), Box<dyn std::error::Error>> {
41    let mut args = std::env::args_os().skip(1);
42    let input = PathBuf::from(args.next().ok_or_else(|| {
43        io::Error::new(
44            io::ErrorKind::InvalidInput,
45            "usage: gltf_tool <input.gltf|input.glb> [output.glb]",
46        )
47    })?);
48    let output = args.next().map(PathBuf::from);
49    if args.next().is_some() {
50        return Err(io::Error::new(io::ErrorKind::InvalidInput, "too many arguments").into());
51    }
52
53    let mut import = draco_gltf::import(&input)?;
54    if let Some(output) = output {
55        let report = import.compress_primitive(MeshIndex(0), 0, CompressionOptions::default())?;
56        let bytes = import.to_bytes(OutputFormat::GlbV2)?;
57        std::fs::write(output, bytes)?;
58        println!("compression_report={report:?}");
59    } else {
60        let (primitives, faces) = decoded_draco_stats(&import)?;
61        println!("decoded_draco_primitives={primitives} decoded_faces={faces}");
62    }
63    Ok(())
64}
Source

pub fn to_gltf_output(&self) -> Result<GltfOutput>

Serializes a self-contained .gltf output bundle.

Unlike Import::to_bytes with crate::OutputFormat::GltfJson, this method returns companion buffer payloads as well. Buffers without a URI (for example a Draco payload appended during compression) receive a deterministic buffer-{index}.bin URI in the returned JSON.

let scene = import_slice(input, None)?;
let output = scene.to_gltf_output()?;
assert!(!output.json.is_empty());
assert!(output.resources.is_empty());
Source

pub fn decompress_in_place(&mut self) -> Result<()>

Materializes all Draco primitives as ordinary indexed triangle geometry.

Source

pub fn external_files(&self) -> impl Iterator<Item = FileIndex> + '_

Lists declared glTF 2.1 files entries without resolving them.

Source

pub fn load_external_asset( &self, asset: ExternalAssetIndex, resolver: &dyn ResourceResolver, limits: &ResourceLimits, profile: ValidationProfile, extensions: &ExtensionRegistry, ) -> Result<Self>

Explicitly resolves and parses an external-asset model declaration.

Source

pub fn provenance(&self) -> &[String]

URI chain leading to this import. It is intended for diagnostics and explicit cycle detection; it never triggers recursive loading itself.

Source

pub fn load_asset( &self, file: FileIndex, resolver: &dyn ResourceResolver, limits: &ResourceLimits, profile: ValidationProfile, extensions: &ExtensionRegistry, ) -> Result<Self>

Explicitly resolves and parses one nested glTF file.

Source

pub fn load_asset_with_depth( &self, file: FileIndex, resolver: &dyn ResourceResolver, limits: &ResourceLimits, profile: ValidationProfile, extensions: &ExtensionRegistry, max_depth: usize, ) -> Result<Self>

Explicitly loads one nested asset with a caller-selected graph depth limit.

Trait Implementations§

Source§

impl Clone for Import

Source§

fn clone(&self) -> Import

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.