Skip to main content

Document

Struct Document 

Source
pub struct Document {
    pub facts: Map<String, Value>,
    /* private fields */
}
Expand description

A model as a glTF 2.0 document: its JSON, its buffers’ bytes, and facts about the source.

It owns all it holds, so it outlives whatever it was read from, and a clone shares the buffers’ bytes rather than copying them. Document::default draws nothing; a Mesh converts into one.

Fields§

§facts: Map<String, Value>

Facts worth recording about the source: triangles, and per format points, lines, vertices, voxels, voxel_size, models, objects, colors, application, and for motion capture joints, channels, frames, frame_time and dropped_frames.

Implementations§

Source§

impl Document

Source

pub fn json(&self) -> &Map<String, Value>

The glTF JSON. Its buffers have no uri: their bytes are held by the document (see Document::buffer).

Source

pub fn json_mut(&mut self) -> &mut Map<String, Value>

The glTF JSON, to change. Its buffers list must stay one entry for each buffer the document holds: add buffers with Document::push_buffer, and leave out a uri, which is ignored.

Source

pub fn source_info(&self) -> SourceInfo

What the file this was read from says about itself: its units, up axis, frame rate, author, tool and dates, each declared, assumed or unknown, and what the reader converted (see crate::source). A glTF file read as it is reports glTF’s own: meters, +Y up, right-handed, its generator and copyright.

Source

pub fn max_triangles(&self) -> usize

The most triangles Document::flatten draws before it refuses: the load’s Keep::max_triangles, or MAX_TRIANGLES for a document built otherwise.

Source

pub fn set_max_triangles(&mut self, n: usize)

Sets the most triangles Document::flatten draws before it refuses, as Keep::max_triangles does for a load: values past TRIANGLE_CEILING are clamped.

Source

pub fn lines_and_points(&self) -> bool

Whether Document::flatten draws points and lines: the load’s Keep::lines_and_points, or true for a document built otherwise.

Source

pub fn set_lines_and_points(&mut self, on: bool)

Sets whether Document::flatten draws points and lines, as Keep::lines_and_points does for a load.

Source

pub fn max_points(&self) -> usize

The most points and line segments Document::flatten draws before it refuses: the load’s Keep::max_points, or MAX_POINTS for a document built otherwise.

Source

pub fn set_max_points(&mut self, n: usize)

Sets the most points and line segments Document::flatten draws before it refuses, as Keep::max_points does for a load: values past TRIANGLE_CEILING are clamped.

Source

pub fn buffer(&self, i: usize) -> Result<Cow<'_, [u8]>>

Buffer i’s bytes, whole (borrowed when they are in one piece).

§Errors

When buffer i doesn’t exist or holds no bytes (a meshopt fallback buffer).

Source

pub fn push_buffer(&mut self, bytes: impl Into<Bytes>) -> usize

Adds a buffer holding bytes (a Vec<u8> or Bytes, neither copied); returns its index. A JSON buffers that isn’t a list (left so by Document::json_mut) is first rebuilt as one entry for each buffer the document holds.

Source

pub fn to_glb(&self) -> Result<Vec<u8>>

The document as a GLB.

§Errors

When a buffer holds fewer bytes than it declares or the GLB would be over 4 GiB.

Source

pub fn to_glb_with(&self, options: &CompressOptions) -> Result<Vec<u8>>

The document as a GLB, meshopt-compressed as options say: as gltf::compress_with on Document::to_glb’s bytes, without writing them out and parsing them back first.

use polysmelt::gltf::CompressOptions;
let small = doc.to_glb_with(&CompressOptions::KHR)?;
§Errors

As Document::to_glb and compress_with.

Source

pub fn write_glb<W: Write>(&self, w: W) -> Result<()>

Writes the document as a GLB: the JSON with every buffer’s bytes in its binary chunk, each where its buffer views (and meshopt data) now point. Writes go straight to w, a piece at a time: wrap a file in a BufWriter.

let doc = polysmelt::open("models/Duck.dae")?;
let file = std::fs::File::create("Duck.glb")?;
doc.write_glb(std::io::BufWriter::new(file))?;
§Errors

As Document::to_glb, and when writing fails.

Source

pub fn to_fbx(&self) -> Result<Vec<u8>>

The document as binary FBX (7.4; 7.5 when it’s over 4 GiB), the other format written in full beside GLB: the default scene’s nodes as models, meshes as geometry with every UV and color set, materials (with their glTF parameters kept alongside the classic ones), embedded textures, skins with their bind pose, morph targets as blend shapes, every animation as an animation stack of its own, cameras, lights and node extras. Points aren’t written: FBX has no geometry for them. The same document always gives the same bytes.

let fbx = doc.to_fbx()?;
assert!(fbx.starts_with(b"Kaydara FBX Binary"));
§Errors

When an accessor or buffer the scene uses is malformed or doesn’t decode, a mesh has more vertices than FBX indexes (2^31), or a single array would be over 4 GiB.

Source

pub fn to_fbx_with(&self, options: &FbxOptions) -> Result<Vec<u8>>

Document::to_fbx with options: threads to share the work over. The bytes are the same whatever they are.

use polysmelt::FbxOptions;
let fbx = doc.to_fbx_with(&FbxOptions::default().with_threads(0))?;
assert_eq!(fbx, doc.to_fbx()?);
§Errors

As Document::to_fbx.

Source

pub fn write_fbx<W: Write>(&self, w: W) -> Result<()>

Writes the document as binary FBX, as Document::to_fbx makes it. The file is assembled before it’s written, then written a record at a time: wrap a file in a BufWriter.

let doc = polysmelt::open("models/Fox.glb")?;
let file = std::fs::File::create("Fox.fbx")?;
doc.write_fbx(std::io::BufWriter::new(file))?;
§Errors

As Document::to_fbx, and when writing fails.

Source

pub fn write_fbx_with<W: Write>(&self, w: W, options: &FbxOptions) -> Result<()>

Document::write_fbx with options, as Document::to_fbx_with takes them.

§Errors

As Document::to_fbx, and when writing fails.

Source§

impl Document

Source

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

Rewrites the document as plain glTF 2.0 that any reader takes:

  • meshopt-compressed buffer views (EXT_meshopt_compression, KHR_meshopt_compression) decoded;
  • Draco-compressed primitives (KHR_draco_mesh_compression, with the draco feature) decoded into accessors of their own, attributes as floats (integer ones, such as JOINTS_n, in their declared component type) and indices as declared;
  • quantized POSITION, NORMAL, TANGENT and TEXCOORD_n accessors (KHR_mesh_quantization), morph targets’ included, converted to floats with the same values a reader would see, and their bounds recomputed. Node transforms are kept, so a mesh quantized with a scaling node draws where it did;
  • indices holding their type’s largest value (255 as bytes, 65535 as shorts), which glTF forbids and WebGL 2 reads as a primitive restart, widened to the next type.

Those extensions leave extensionsUsed and extensionsRequired, and buffers nothing points into any more (meshopt fallbacks, buffers that held only compressed data) are dropped. Decoded data goes into a new buffer; compressed data sharing a buffer with other views stays where it was. Everything else (animation, skins, materials, unknown extensions and extras, required ones too) is untouched. A document without these is left as it is.

§Errors

When compressed data doesn’t decode, an accessor is malformed, or the document uses Draco without the draco feature (unless it carries uncompressed data beside it). The document is unchanged then.

Source§

impl Document

Source

pub fn repair(&mut self)

Puts right what the glTF 2.0 specification forbids and can be fixed without changing what the document draws or how it moves:

  • indices naming no vertex dropped with the triangle, line or point using them (strips, loops and fans becoming lists), and primitives left with none removed;
  • non-finite floats in vertex attributes, animation keys and inverse bind matrices set to 0;
  • normals, tangents and rotation keys made unit length (a zero normal takes its faces’ normal), tangents’ handedness made ±1, and each vertex’s skin weights scaled to sum to 1;
  • animation keys sorted by time, of keys at the same time the last kept;
  • animation and inverse bind matrix data copied out of interleaved buffer views, and vertex attributes sharing a buffer view without a stride given views of their own;
  • min and max added where they’re required and corrected where they’re wrong (per-instance attributes’ too);
  • texture coordinate sets a material reads but a primitive lacks filled in (by another set, or zeros), as are gaps in their numbering;
  • node hierarchies made trees (a second parent, or a cycle, loses the link), and scene roots that are children dropped;
  • empty lists removed.

Rewritten data goes into a new buffer. Document::write_glb and Document::to_glb do this to what they write, so calling it first is needed only to look at the result.

Source§

impl Document

Source

pub fn rig(&self) -> Result<Rig>

The document’s nodes, skins and animations, accessors read. A document loaded with a Keep that drops animation, skins or morphs has none of those.

§Errors

When a skin or animation names an accessor, buffer or node that doesn’t exist, or whose data runs past its buffer.

Source§

impl Document

Source

pub fn flatten(&self, pose: Pose) -> Result<Option<Mesh>>

The triangles, lines and points the default scene draws in pose, as one mesh with every transform, instance, morph and skin baked in; None when it draws nothing. Lines and points are left out when Document::lines_and_points says so.

§Errors

When the document is malformed (an accessor out of range, a scene that doesn’t exist), pose names an animation that doesn’t exist, it uses Draco without the draco feature, or it draws more than Document::max_triangles triangles or Document::max_points points and line segments.

Source

pub fn flatten_nodes(&self, nodes: &[Trs]) -> Result<Option<Mesh>>

What the default scene draws with each node in the transform nodes gives it, as Document::flatten does: for a pose worked out elsewhere, such as one retargeted from another rig, blended, or solved by IK. nodes is indexed as Rig::nodes (as Rig::pose_into fills it); nodes past its end keep their own transforms, and morph weights are the nodes’ own.

§Errors

As Document::flatten.

Source

pub fn read_floats(&self, accessor: usize) -> Result<(usize, Vec<f32>)>

Accessor accessor’s elements as floats, width to an element (a matrix’s columns in order, without padding), as a renderer reads them: meshopt-compressed views decoded, sparse substitutions applied, normalized integers mapped to [0, 1] or [-1, 1] and other integers as they are (exact below 2^24). An accessor without a buffer view reads as zeros under its sparse values, unless a Draco stream holds it: then it reads as that stream decodes (which needs the draco feature).

§Errors

When the accessor doesn’t exist, is malformed or runs past its buffer, or its compressed view doesn’t decode.

Source

pub fn read_indices(&self, accessor: usize) -> Result<Vec<u32>>

Accessor accessor’s unsigned integer scalars (indices, or anything else stored so), exactly, read as Document::read_floats reads.

§Errors

As Document::read_floats, and when the accessor isn’t unsigned integer scalars.

Source

pub fn counts(&self) -> Counts

How many triangles, points and line segments the default scene draws (every instance counted), from the JSON alone: nothing is read or decoded.

Source

pub fn bounds(&self, pose: Pose) -> Result<Option<Bounds>>

The box around every vertex the default scene draws in pose, transforms, instances, morphs and skins applied, exactly as Document::flatten places them (lines and points too, unless Document::lines_and_points leaves them out); None when it draws nothing. Only positions are read: no other attribute, material or image. A file’s own bounds (glTF’s accessor min and max) aren’t trusted, since files get them wrong.

§Errors

As Document::flatten, except that no triangle or point limit applies.

Source

pub fn triangles(&self) -> usize

How many triangles the default scene draws: Document::counts’ triangles.

Source

pub fn animation_bounds( &self, index: usize, samples: usize, ) -> Result<Option<Bounds>>

The box around every vertex the default scene draws while animation index plays: the Document::bounds of its poses at samples times spread evenly from its first key to its last, both included (one sample is the first key alone), together. A pose between samples can reach a little past the box. None when no pose draws anything.

let doc = polysmelt::open("walk.fbx")?;
// Where a camera should stand to frame the character through its whole walk.
let frame = doc.animation_bounds(0, 30)?;
§Errors

When the document has no animation index, and as Document::bounds.

Source§

impl Document

Source

pub fn images(&self) -> impl Iterator<Item = ImageHandle<'_>>

The document’s images, read or not. A load with Keep::image_bytes off leaves the images it found unread: each is a glTF image with a uri (relative to the model’s folder, for a file under it), and its handle says where it is and reads it.

Source

pub fn embed_images(&mut self, assets: &dyn Assets) -> usize

Reads every image not yet read into a buffer of its own, so the document stands alone (as a GLB from to_glb then does). Returns how many couldn’t be read; they stay references by uri.

Source§

impl Document

Source

pub fn prune(&mut self, keep: Keep)

Drops what keep doesn’t keep. The JSON stays valid glTF: references to what went are removed with it, and extensions no longer used are unlisted. Extensions Polysmelt doesn’t know that refer to dropped materials, textures or cameras may be left pointing at them. Keep::max_triangles and Keep::threads play no part here. Points and lines stay in the JSON: Keep::lines_and_points and Keep::max_points are recorded for Document::flatten (see Document::set_lines_and_points and Document::set_max_points).

Trait Implementations§

Source§

impl Clone for Document

Source§

fn clone(&self) -> Self

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
Source§

impl Debug for Document

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Document

Source§

fn default() -> Self

A document that draws nothing: only the asset glTF requires.

Source§

impl From<Mesh> for Document

Source§

fn from(mesh: Mesh) -> Self

The document for a mesh: one node drawing one mesh, a primitive per material (and one for the lines and one for the points of each, sharing its vertices), its arrays moved into the document’s buffer without a copy. Skinned primitives, when the mesh has a skeleton, are a second mesh on a node with a skin: a node per bone, and inverse bind matrices that bind the vertices where they are, so the document draws as the mesh does and moves with its bones.

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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 = !

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

fn try_from(value: U) -> Result<T, !>

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.