pub struct Mesh {
pub positions: Vec<[f32; 3]>,
pub normals: Vec<[f32; 3]>,
pub uvs: Vec<[f32; 2]>,
pub colors: Vec<[f32; 3]>,
pub indices: Vec<[u32; 3]>,
}Expand description
A triangle mesh, indexed.
normals, uvs and colors are either empty or as long as positions.
The geometry here needs none of them; they are carried so a reader and a
writer round-trip, and colors is what the vertex-colour stand-in for
texture is trained on and written from.
Fields§
§positions: Vec<[f32; 3]>§normals: Vec<[f32; 3]>§uvs: Vec<[f32; 2]>§colors: Vec<[f32; 3]>Linear RGB per vertex, 0 to 1.
indices: Vec<[u32; 3]>Implementations§
Source§impl Mesh
impl Mesh
Source§impl Mesh
impl Mesh
Sourcepub fn write_glb<P: AsRef<Path>>(&self, path: P) -> Result<(), NetworkError>
pub fn write_glb<P: AsRef<Path>>(&self, path: P) -> Result<(), NetworkError>
Writes the mesh as a .glb.
One node, one mesh, one triangle primitive, one buffer view per
attribute, and one material — an untextured PBR white, because nothing
in this pipeline produces a texture or the UVs that would place one.
Normals, UVs and vertex colours are written when the mesh carries them;
a viewer multiplies COLOR_0 by the material’s base colour, which is
why that base colour is white.
Sourcepub fn to_glb(&self) -> Result<Glb, NetworkError>
pub fn to_glb(&self) -> Result<Glb, NetworkError>
The same, kept in memory.
Source§impl Mesh
impl Mesh
Sourcepub fn bounds(&self) -> ([f32; 3], [f32; 3])
pub fn bounds(&self) -> ([f32; 3], [f32; 3])
The smallest axis-aligned box holding every vertex.
Sourcepub fn normalize(&mut self) -> Transform
pub fn normalize(&mut self) -> Transform
Centres the mesh on its bounding box and scales it to fill [-1, 1],
returning the transform that was applied.
The longest axis reaches the faces of the cube and the others fall short of them, because scaling the axes separately would change the shape.
Examples found in repository?
57fn main() -> Result<(), Box<dyn std::error::Error>> {
58 let args = parse()?;
59 std::fs::create_dir_all(&args.out)?;
60
61 let mut paths: Vec<PathBuf> = std::fs::read_dir(&args.meshes)?
62 .filter_map(|entry| entry.ok().map(|entry| entry.path()))
63 .filter(|path| {
64 path.extension().is_some_and(|extension| {
65 matches!(extension.to_ascii_lowercase().to_str(), Some("obj" | "glb"))
66 })
67 })
68 .collect();
69 paths.sort();
70 if paths.is_empty() {
71 return Err(format!("no .obj or .glb files in {}", args.meshes.display()).into());
72 }
73 println!(
74 "{} meshes, {} per shard, {} surface and {} query points each",
75 paths.len(),
76 args.shard,
77 args.surface,
78 args.queries
79 );
80
81 let sampling = QuerySampling {
82 count: args.queries,
83 near_surface: args.near_surface,
84 jitter: args.jitter,
85 extent: args.extent,
86 };
87
88 let mut index: BTreeMap<String, String> = BTreeMap::new();
89 let mut skipped = 0;
90 let mut colored = 0;
91 let started = Instant::now();
92 let shards = paths.len().div_ceil(args.shard);
93 for (number, chunk) in paths.chunks(args.shard).enumerate() {
94 let shard = format!("samples-{number:05}.safetensors");
95
96 // Already done by an earlier run: take its names and move on.
97 let done = completed(&args.out.join(&shard));
98 if !done.is_empty() {
99 for stem in &done {
100 index.insert(stem.clone(), shard.clone());
101 }
102 write_index(&args.out, &index)?;
103 println!("{shard}: {} meshes, already written", done.len());
104 continue;
105 }
106 // One shard at a time in memory. A 200K-query mesh is 3 MB here and
107 // half that on disk, so the shard size is the knob that bounds this.
108 let mut sampled: Vec<(String, [usize; 2], Vec<f32>)> = Vec::new();
109 let mut meshes = 0;
110 for path in chunk {
111 let stem = path
112 .file_stem()
113 .and_then(|stem| stem.to_str())
114 .ok_or_else(|| format!("{} has no usable name", path.display()))?
115 .to_string();
116
117 // One bad asset in a scraped dataset should not cost the whole run.
118 let mesh = match read(path) {
119 Ok(mesh) => mesh,
120 Err(error) => {
121 eprintln!("skipping {}: {error}", path.display());
122 skipped += 1;
123 continue;
124 }
125 };
126 // The seed is per mesh, so a rerun of one shard reproduces exactly
127 // the samples the first run wrote.
128 let mut rng = StdRng::seed_from_u64(args.seed ^ hash(&stem));
129 let mut mesh = mesh;
130 let placement = mesh.normalize();
131 let bvh = Bvh::build(&mesh);
132
133 let (points, normals, colors) = bvh.sample_surface_colored(args.surface, &mut rng);
134 let mut surface = Vec::with_capacity(args.surface * 6);
135 for (point, normal) in points.iter().zip(&normals) {
136 surface.extend(point);
137 surface.extend(normal);
138 }
139
140 let queries = bvh.sample_queries(&sampling, &mut rng);
141 let distances = bvh.signed_distance(&queries);
142 let mut samples = Vec::with_capacity(queries.len() * 4);
143 for (query, distance) in queries.iter().zip(&distances) {
144 samples.extend(query);
145 samples.push(*distance);
146 }
147
148 index.insert(stem.clone(), shard.clone());
149 meshes += 1;
150 sampled.push((format!("{stem}.surface"), [points.len(), 6], surface));
151 // Only the meshes that carry colour get a colour tensor; the loader
152 // treats a missing one as "this mesh trains shape only".
153 if !colors.is_empty() {
154 colored += 1;
155 sampled.push((format!("{stem}.colors"), [colors.len(), 3], colors.concat()));
156 }
157 sampled.push((format!("{stem}.queries"), [queries.len(), 4], samples));
158 sampled.push((
159 format!("{stem}.transform"),
160 [1, 4],
161 vec![
162 placement.center[0],
163 placement.center[1],
164 placement.center[2],
165 placement.scale,
166 ],
167 ));
168 }
169 if sampled.is_empty() {
170 continue;
171 }
172
173 let borrowed: Vec<(&str, &[usize], &[f32])> = sampled
174 .iter()
175 .map(|(name, shape, data)| (name.as_str(), &shape[..], &data[..]))
176 .collect();
177 safetensors::write_as(
178 args.out.join(&shard),
179 &borrowed,
180 &BTreeMap::from([
181 ("source".to_string(), "mesh_samples".to_string()),
182 ("surface".to_string(), args.surface.to_string()),
183 ("queries".to_string(), args.queries.to_string()),
184 ]),
185 Dtype::Bf16,
186 )?;
187 write_index(&args.out, &index)?;
188 println!(
189 "{shard}: {meshes} meshes, {}",
190 progress(started, number + 1, shards)
191 );
192 }
193
194 write_index(&args.out, &index)?;
195 println!(
196 "wrote {} entries to index.json, {colored} with colour, skipped {skipped}",
197 index.len()
198 );
199 Ok(())
200}Sourcepub fn recompute_normals(&mut self)
pub fn recompute_normals(&mut self)
Replaces the per-vertex normals with area-weighted face normals.
Weighting by area rather than averaging the unit face normals is what keeps a vertex where one huge triangle meets several slivers from being dominated by the slivers.
Sourcepub fn read_obj<P: AsRef<Path>>(path: P) -> Result<Self, NetworkError>
pub fn read_obj<P: AsRef<Path>>(path: P) -> Result<Self, NetworkError>
Reads a Wavefront OBJ file.
Positions, normals, texture coordinates and faces. Faces with more than three corners are fanned into triangles, which is right for the convex quads an exporter emits. Materials, groups and smoothing are skipped: the geometry is what a distance field is built from.
Source§impl Mesh
impl Mesh
Sourcepub fn simplify(&mut self, target_faces: usize) -> usize
pub fn simplify(&mut self, target_faces: usize) -> usize
Collapses edges until the mesh is down to target_faces, cheapest
first.
This is Garland and Heckbert’s quadric error metric: every vertex carries the sum of the squared-distance quadrics of the faces around it, an edge costs whatever that sum evaluates to at the point it would collapse onto, and the point itself is the one that minimizes it. A boundary edge gets an extra plane at right angles to its face, weighted heavily, so an open edge is held in place rather than eaten away.
Returns the face count it finished on, which can be above the target if there was nothing left that could be collapsed safely.
Normals are recomputed if the mesh had them. UVs are dropped: a collapse merges two vertices that generally sit in different places in a texture atlas, and inventing a coordinate for the merged one would be worse than admitting there isn’t one.
Sourcepub fn simplify_within(&mut self, max_error: f32) -> (usize, f32)
pub fn simplify_within(&mut self, max_error: f32) -> (usize, f32)
Collapses edges for as long as the quadric error stays under
max_error, and returns the face count it finished on together with the
largest error it accepted.
This is Mesh::simplify asking the other question. A face target says
how big the mesh may be and lets the error land where it lands, which is
the wrong way round for a pipeline that extracted the mesh from a field
and wants it as small as it can be without visibly moving the surface.
Given a bound, this collapses the cheap edges — a flat region, a
redundant row of vertices along a plane — and stops at the first edge
that would cost more than the bound.
The units are the metric’s, not the world’s: an error is a sum of squared distances to the planes around the edge, each weighted by the area of the face it came from. So it scales with the mesh, and the way to pick a bound is to simplify one representative mesh to a face count that looks right and use the largest error that run reports. The second return value is there for exactly that.
Everything else matches Mesh::simplify: the same metric, the same
refusal to fold a face over, normals recomputed, UVs dropped.
Trait Implementations§
Auto Trait Implementations§
impl Forget for Mesh
impl Freeze for Mesh
impl Move for Mesh
impl RefUnwindSafe for Mesh
impl Send for Mesh
impl Sync for Mesh
impl Unpin for Mesh
impl UnsafeUnpin for Mesh
impl UnwindSafe for Mesh
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more