opensubdiv_rs/far/fvar.rs
1//! Face-varying channel refinement.
2//!
3//! Port of the face-varying support spread across OpenSubdiv's
4//! `vtr/fvarLevel.{h,cpp}`, `vtr/fvarRefinement.{h,cpp}` and the
5//! face-varying paths of `far/topologyRefiner` / `far/primvarRefiner`.
6//!
7//! A face-varying channel assigns a *value index* to every face-corner, so
8//! data such as UVs can be discontinuous ("seamed") across edges. The key
9//! observation — equivalent to how OpenSubdiv tags fvar topology — is that a
10//! channel forms a mesh of its own: its "vertices" are the channel *values*
11//! and its faces mirror the mesh faces, with corners remapped to value
12//! indices. Where neighboring faces disagree on values, that value-mesh
13//! simply has two distinct (boundary) edges instead of one shared interior
14//! edge: **seams are boundaries of the value mesh**.
15//!
16//! A channel is therefore represented as a [`Level`] per refinement level and
17//! refined with the same [`Refinement`] machinery as the geometry, after
18//! encoding the channel's [linear-interpolation
19//! rule](crate::sdc::FVarLinearInterpolation) as sharpness on that value
20//! mesh. As in OpenSubdiv, a value is a property of a *geometric vertex*: a
21//! value index reused at several vertices (a deduplicated UV, say) is one
22//! independent value at each of them, so the base value mesh gets one vertex
23//! per distinct (vertex, value index) pair. The caller's indices are kept for
24//! the base level's API and for gathering the source values of the first
25//! interpolation step; refined levels only ever see the split values.
26//!
27//! The linear-interpolation rules map onto the value mesh as follows:
28//!
29//! * `All` — every mask is linear; no sharpening needed.
30//! * `None` — value-mesh boundaries (seams) subdivide as smooth crease
31//! curves: boundary edges are sharpened (like
32//! [`VtxBoundaryInterpolation::EdgeOnly`](crate::sdc::VtxBoundaryInterpolation)).
33//! * `CornersOnly` — additionally pins values incident exactly one face
34//! (like `EdgeAndCorner`).
35//! * `CornersPlus1` — additionally pins all values at vertices where three
36//! or more distinct values meet ("junctions").
37//! * `CornersPlus2` — additionally pins values at fvar darts (an interior
38//! vertex where a seam terminates) and at concave corners: where exactly
39//! two values meet and one of them is a corner (spans a single face), the
40//! other spans the remaining faces around the vertex and is pinned too.
41//! * `Boundaries` — every boundary/seam value is pinned, making all fvar
42//! boundaries piecewise linear.
43//!
44//! Geometric sharpness (creases/corners and sharpened mesh boundaries) is
45//! transferred onto the value mesh so that fvar data respects the same sharp
46//! features as vertex data.
47
48use crate::sdc::{self, Crease, FVarLinearInterpolation, Scheme, SchemeType};
49use crate::vtr::{Level, Refinement, TopologyError};
50use crate::Index;
51use std::borrow::Cow;
52
53/// One face-varying channel of a
54/// [`TopologyRefiner`](super::TopologyRefiner): the hierarchy of value-mesh
55/// levels refined in lockstep with the geometry.
56#[derive(Debug, Clone)]
57pub struct FVarChannel {
58 linear_interpolation: FVarLinearInterpolation,
59 /// Scheme used to refine and interpolate the value mesh. Same scheme
60 /// type as the geometry, but with the boundary-interpolation option
61 /// derived from the channel's linear-interpolation rule.
62 scheme: Scheme,
63 /// True when every mask is linear (`FVarLinearInterpolation::All`).
64 linear: bool,
65 /// The number of values the channel was described with.
66 num_base_values: usize,
67 /// The caller's value index of each base-level face-corner.
68 base_face_values: Vec<Index>,
69 /// The caller's value index of each base value-mesh vertex, when some
70 /// index is reused at several geometric vertices and the value mesh
71 /// therefore has more vertices than the channel has values; `None`
72 /// when the two coincide.
73 base_value_sources: Option<Vec<Index>>,
74 levels: Vec<Level>,
75 refinements: Vec<Refinement>,
76}
77
78impl FVarChannel {
79 /// Build the base level of a channel from its per-corner value indices,
80 /// validating them against the geometry's base level.
81 pub(super) fn create(
82 geometry: &Level,
83 scheme_type: SchemeType,
84 options: sdc::Options,
85 channel_index: usize,
86 num_values: usize,
87 value_indices: &[Index],
88 ) -> Result<FVarChannel, TopologyError> {
89 if value_indices.len() != geometry.num_face_vertices_total() {
90 return Err(TopologyError::FVarValueCountMismatch {
91 channel: channel_index,
92 expected: geometry.num_face_vertices_total(),
93 actual: value_indices.len(),
94 });
95 }
96 for &v in value_indices {
97 if v as usize >= num_values {
98 return Err(TopologyError::FVarValueIndexOutOfRange {
99 channel: channel_index,
100 index: v,
101 });
102 }
103 }
104
105 let mode = options.fvar_linear_interpolation;
106 let linear = mode == FVarLinearInterpolation::All;
107 let scheme = Scheme::new(scheme_type, channel_options(options));
108
109 // Build the value mesh: same faces as the geometry, corners remapped
110 // to value indices, with an index reused at several geometric
111 // vertices split into one value-mesh vertex per vertex.
112 let verts_per_face: Vec<usize> = (0..geometry.num_faces())
113 .map(|f| geometry.face_vertices(f).len())
114 .collect();
115 let (split_indices, base_value_sources) =
116 split_reused_values(geometry, num_values, value_indices);
117 let num_split_values = base_value_sources.as_ref().map_or(num_values, Vec::len);
118 let mut value_mesh =
119 Level::from_face_vertices(num_split_values, &verts_per_face, &split_indices)?;
120
121 if !linear {
122 // Transfer geometric sharpness onto the value mesh so creases
123 // and sharpened mesh boundaries also affect fvar data. Corner
124 // `i` of face `f` associates geometric edge/vertex with the
125 // value-mesh edge/value at the same position.
126 for f in 0..geometry.num_faces() {
127 let geom_edges = geometry.face_edges(f);
128 let geom_verts = geometry.face_vertices(f);
129 let fvar_edges = value_mesh.face_edges(f).to_vec();
130 let fvar_values = value_mesh.face_vertices(f).to_vec();
131 for i in 0..geom_verts.len() {
132 let ge = geom_edges[i] as usize;
133 let fe = fvar_edges[i] as usize;
134 let es = geometry
135 .edge_sharpness(ge)
136 .max(value_mesh.edge_sharpness(fe));
137 value_mesh.set_edge_sharpness(fe, es);
138
139 let gv = geom_verts[i] as usize;
140 let fv = fvar_values[i] as usize;
141 let vs = geometry
142 .vertex_sharpness(gv)
143 .max(value_mesh.vertex_sharpness(fv));
144 value_mesh.set_vertex_sharpness(fv, vs);
145 }
146 }
147
148 // Fvar boundaries (mesh boundaries and seams) subdivide as
149 // creases; `EdgeAndCorner`-mapped modes also pin one-face values.
150 value_mesh.sharpen_boundaries(scheme.crease());
151
152 apply_mode_sharpening(mode, geometry, &mut value_mesh);
153 }
154
155 Ok(FVarChannel {
156 linear_interpolation: mode,
157 scheme,
158 linear,
159 num_base_values: num_values,
160 base_face_values: value_indices.to_vec(),
161 base_value_sources,
162 levels: vec![value_mesh],
163 refinements: Vec::new(),
164 })
165 }
166
167 /// Refine the channel by one level, in lockstep with the geometry:
168 /// `included` is the geometry's mask of faces to refine (its selection
169 /// already expanded to the one-ring support), or `None` for uniform
170 /// refinement. The value mesh's faces mirror the geometry's, so the
171 /// same mask applies — it must not be re-expanded on the value mesh,
172 /// whose seams split vertices and would include fewer support faces,
173 /// leaving the two meshes with different child faces.
174 pub(super) fn refine_once(&mut self, included: Option<&[bool]>) {
175 let parent = self.levels.last().unwrap();
176 let (mut child, refinement) = match included {
177 Some(included) => Refinement::refine_included(parent, &self.scheme, included),
178 None => Refinement::refine(parent, &self.scheme),
179 }
180 .expect("refined face-varying topology is always internally consistent");
181 // `Boundaries` pins *every* boundary value, including the values
182 // newly created on boundary/seam edges, so it must be re-applied at
183 // each level (the other modes' pins persist through vertex-sharpness
184 // subdivision or `sharpen_boundaries`).
185 if self.linear_interpolation == FVarLinearInterpolation::Boundaries {
186 pin_boundary_values(&mut child);
187 }
188 self.levels.push(child);
189 self.refinements.push(refinement);
190 }
191
192 /// The channel's linear-interpolation rule.
193 pub fn linear_interpolation(&self) -> FVarLinearInterpolation {
194 self.linear_interpolation
195 }
196
197 pub(super) fn scheme(&self) -> &Scheme {
198 &self.scheme
199 }
200
201 pub(super) fn is_linear(&self) -> bool {
202 self.linear
203 }
204
205 pub(super) fn level(&self, level: usize) -> &Level {
206 &self.levels[level]
207 }
208
209 /// The number of values at `level` as seen by the channel's user: the
210 /// number of values it was described with at the base level, and the
211 /// value-mesh vertex count above.
212 pub(super) fn num_values(&self, level: usize) -> usize {
213 if level == 0 {
214 self.num_base_values
215 } else {
216 self.levels[level].num_vertices()
217 }
218 }
219
220 /// The values at the corners of `face` at `level`: the caller's indices
221 /// at the base level, value-mesh vertices above.
222 pub(super) fn face_values(&self, level: usize, face: usize) -> &[Index] {
223 if level == 0 {
224 let level0 = &self.levels[0];
225 let start = level0.face_vertices_offset(face);
226 &self.base_face_values[start..start + level0.face_vertices(face).len()]
227 } else {
228 self.levels[level].face_vertices(face)
229 }
230 }
231
232 /// Source values for interpolating from the base level, one per base
233 /// value-mesh vertex: `src` itself when every value is used at a single
234 /// geometric vertex, or `src` gathered through the split.
235 pub(super) fn base_source_values<'a, T: Clone>(&self, src: &'a [T]) -> Cow<'a, [T]> {
236 assert!(
237 src.len() >= self.num_base_values,
238 "src buffer too small: {} values, expected at least {}",
239 src.len(),
240 self.num_base_values
241 );
242 match &self.base_value_sources {
243 None => Cow::Borrowed(src),
244 Some(sources) => Cow::Owned(sources.iter().map(|&v| src[v as usize].clone()).collect()),
245 }
246 }
247
248 /// The caller's value index of each base value-mesh vertex, when some
249 /// index is reused at several geometric vertices (see
250 /// [`split_reused_values`]); `None` when the two coincide.
251 pub(super) fn base_value_sources(&self) -> Option<&[Index]> {
252 self.base_value_sources.as_deref()
253 }
254
255 pub(super) fn refinement(&self, level: usize) -> &Refinement {
256 &self.refinements[level - 1]
257 }
258}
259
260/// Split value indices reused at several geometric vertices into one value
261/// per (vertex, index) pair. Returns the per-corner indices of the split
262/// values and, when any index had to be split, the caller's index of each
263/// split value. The first vertex using an index keeps that index, so that
264/// the split is the identity whenever no index is reused.
265fn split_reused_values(
266 geometry: &Level,
267 num_values: usize,
268 value_indices: &[Index],
269) -> (Vec<Index>, Option<Vec<Index>>) {
270 // Geometric vertex at which each value was first seen.
271 let mut first_vertex: Vec<Option<Index>> = vec![None; num_values];
272 // Extra (value, split id) pairs of each geometric vertex.
273 let mut extra_at_vertex: Vec<Vec<(Index, Index)>> = vec![Vec::new(); geometry.num_vertices()];
274 let mut sources: Vec<Index> = (0..num_values as Index).collect();
275
276 let mut split = Vec::with_capacity(value_indices.len());
277 let mut corner = 0;
278 for f in 0..geometry.num_faces() {
279 for &v in geometry.face_vertices(f) {
280 let val = value_indices[corner];
281 corner += 1;
282 let id = match first_vertex[val as usize] {
283 None => {
284 first_vertex[val as usize] = Some(v);
285 val
286 }
287 Some(first) if first == v => val,
288 Some(_) => {
289 let extra = &mut extra_at_vertex[v as usize];
290 match extra.iter().find(|(existing, _)| *existing == val) {
291 Some(&(_, id)) => id,
292 None => {
293 let id = sources.len() as Index;
294 sources.push(val);
295 extra.push((val, id));
296 id
297 }
298 }
299 }
300 };
301 split.push(id);
302 }
303 }
304 let sources = (sources.len() > num_values).then_some(sources);
305 (split, sources)
306}
307
308/// The value-mesh boundary interpolation implied by each fvar
309/// linear-interpolation rule.
310fn channel_options(options: sdc::Options) -> sdc::Options {
311 use sdc::VtxBoundaryInterpolation::{EdgeAndCorner, EdgeOnly};
312 let vtx = match options.fvar_linear_interpolation {
313 FVarLinearInterpolation::All | FVarLinearInterpolation::None => EdgeOnly,
314 FVarLinearInterpolation::CornersOnly
315 | FVarLinearInterpolation::CornersPlus1
316 | FVarLinearInterpolation::CornersPlus2
317 | FVarLinearInterpolation::Boundaries => EdgeAndCorner,
318 };
319 options.with_vtx_boundary_interpolation(vtx)
320}
321
322fn apply_mode_sharpening(mode: FVarLinearInterpolation, geometry: &Level, value_mesh: &mut Level) {
323 match mode {
324 FVarLinearInterpolation::All
325 | FVarLinearInterpolation::None
326 | FVarLinearInterpolation::CornersOnly => {}
327 FVarLinearInterpolation::CornersPlus1 | FVarLinearInterpolation::CornersPlus2 => {
328 // Distinct values meeting at each geometric vertex, with the
329 // number of incident faces each value spans there.
330 let mut values_at_vertex: Vec<Vec<(Index, usize)>> =
331 vec![Vec::new(); geometry.num_vertices()];
332 for f in 0..geometry.num_faces() {
333 let gv = geometry.face_vertices(f);
334 let fv = value_mesh.face_vertices(f);
335 for (&v, &val) in gv.iter().zip(fv) {
336 let vals = &mut values_at_vertex[v as usize];
337 match vals.iter_mut().find(|(existing, _)| *existing == val) {
338 Some((_, span)) => *span += 1,
339 None => vals.push((val, 1)),
340 }
341 }
342 }
343 for (v, vals) in values_at_vertex.iter().enumerate() {
344 // Junctions: three or more values meeting at a vertex.
345 let junction = vals.len() > 2;
346 // Darts (`CornersPlus2` only): an interior vertex whose single
347 // value nevertheless lies on an fvar boundary — a seam
348 // terminates here.
349 let dart = mode == FVarLinearInterpolation::CornersPlus2
350 && vals.len() == 1
351 && !geometry.is_vertex_boundary(v)
352 && value_mesh.is_vertex_boundary(vals[0].0 as usize);
353 // Concave corners (`CornersPlus2` only): exactly two values
354 // meet and one of them is a corner (spans a single face), so
355 // the other spans all remaining faces around the vertex — a
356 // reflex corner of its UV island. OpenSubdiv sharpens both
357 // (`sharpenBothIfOneCorner` in `FVarLevel`); the corner is
358 // already pinned, so this pins the concave value.
359 let concave = mode == FVarLinearInterpolation::CornersPlus2
360 && vals.len() == 2
361 && (vals[0].1 == 1 || vals[1].1 == 1);
362 if junction || dart || concave {
363 for &(val, _) in vals {
364 value_mesh.set_vertex_sharpness(val as usize, sdc::SHARPNESS_INFINITE);
365 }
366 }
367 }
368 }
369 FVarLinearInterpolation::Boundaries => pin_boundary_values(value_mesh),
370 }
371}
372
373/// Pin (make infinitely sharp) every value lying on a boundary of the value
374/// mesh, so fvar boundaries and seams interpolate linearly.
375fn pin_boundary_values(value_mesh: &mut Level) {
376 for v in 0..value_mesh.num_vertices() {
377 if value_mesh.is_vertex_boundary(v) && !Crease::is_infinite(value_mesh.vertex_sharpness(v))
378 {
379 value_mesh.set_vertex_sharpness(v, sdc::SHARPNESS_INFINITE);
380 }
381 }
382}