opensubdiv_rs/osd/types.rs
1//! The plain-data records a GPU evaluator reads: patch arrays, packed patch
2//! parameters and patch coordinates (port of `opensubdiv/osd/types.h` and
3//! of the `OsdPatchArray` / `OsdPatchParam` / `OsdPatchCoord` structs of
4//! `osd/patchBasisTypes.h`, with `Far::PatchParam`'s bitfield layout).
5//!
6//! Every record is `#[repr(C)]` and made of 32-bit fields only, so it has
7//! no padding and the same layout as the OpenSubdiv shader structs; its
8//! `to_words` method gives that layout as `u32` words, ready to be written
9//! to a storage buffer.
10
11use crate::far::PatchType;
12
13/// `Far::PatchDescriptor::Type` codes, as stored in [`PatchArray::desc`]
14/// and read by OpenSubdiv's patch shaders.
15pub mod patch_descriptor {
16 use crate::far::PatchType;
17
18 /// Bilinear quad on 4 control vertices ([`PatchType::Quads`]).
19 pub const QUADS: u32 = 3;
20 /// Linear triangle on 3 control vertices ([`PatchType::Triangles`]).
21 pub const TRIANGLES: u32 = 4;
22 /// Quartic box-spline triangle on 12 control vertices
23 /// ([`PatchType::Loop`]).
24 pub const LOOP: u32 = 5;
25 /// Bicubic B-spline patch on 16 control vertices
26 /// ([`PatchType::Regular`], single-crease patches included).
27 pub const REGULAR: u32 = 6;
28 /// Gregory patch on 20 control points ([`PatchType::GregoryBasis`]).
29 pub const GREGORY_BASIS: u32 = 9;
30 /// Gregory triangle on 18 control points
31 /// ([`PatchType::GregoryTriangle`]).
32 pub const GREGORY_TRIANGLE: u32 = 10;
33
34 /// The descriptor code of `patch_type`.
35 pub const fn from_patch_type(patch_type: PatchType) -> u32 {
36 match patch_type {
37 PatchType::Regular => REGULAR,
38 PatchType::GregoryBasis => GREGORY_BASIS,
39 PatchType::Quads => QUADS,
40 PatchType::Loop => LOOP,
41 PatchType::GregoryTriangle => GREGORY_TRIANGLE,
42 PatchType::Triangles => TRIANGLES,
43 }
44 }
45
46 /// The patch type of descriptor code `code`, or `None` for a code no
47 /// [`GpuPatchTable`](super::super::GpuPatchTable) emits.
48 pub const fn to_patch_type(code: u32) -> Option<PatchType> {
49 match code {
50 REGULAR => Some(PatchType::Regular),
51 GREGORY_BASIS => Some(PatchType::GregoryBasis),
52 QUADS => Some(PatchType::Quads),
53 LOOP => Some(PatchType::Loop),
54 GREGORY_TRIANGLE => Some(PatchType::GregoryTriangle),
55 TRIANGLES => Some(PatchType::Triangles),
56 _ => None,
57 }
58 }
59
60 /// The number of control points of a patch of descriptor code `code`
61 /// (`PatchDescriptor::GetNumControlVertices`), `0` for an unknown code.
62 pub const fn num_control_vertices(code: u32) -> usize {
63 match code {
64 REGULAR => 16,
65 GREGORY_BASIS => 20,
66 QUADS => 4,
67 LOOP => 12,
68 GREGORY_TRIANGLE => 18,
69 TRIANGLES => 3,
70 _ => 0,
71 }
72 }
73
74 /// Is a patch of descriptor code `code` triangular (its domain
75 /// `s, t >= 0`, `s + t <= 1`)?
76 pub const fn is_triangular(code: u32) -> bool {
77 matches!(code, LOOP | GREGORY_TRIANGLE | TRIANGLES)
78 }
79}
80
81/// A run of patches of one type in a [`GpuPatchTable`](super::GpuPatchTable)
82/// (`Osd::PatchArray`, `OsdPatchArray` in the shaders).
83///
84/// The patches of the array are patches `primitive_id_base..` of the
85/// table (indices into its patch-param buffer), and patch
86/// `primitive_id_base + k` has its `stride` control points at
87/// `index_base + k * stride` in the index buffer.
88#[repr(C)]
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub struct PatchArray {
91 /// Descriptor code of the array's regular patches
92 /// ([`patch_descriptor`]); equal to [`desc`](Self::desc) for vertex
93 /// patches, as in OpenSubdiv.
94 pub reg_desc: u32,
95 /// Descriptor code of the array's patches ([`patch_descriptor`]).
96 pub desc: u32,
97 /// The number of patches in the array.
98 pub num_patches: u32,
99 /// Where the array's control points start in the index buffer.
100 pub index_base: u32,
101 /// The number of index-buffer entries per patch.
102 pub stride: u32,
103 /// The index of the array's first patch in the table (and in its
104 /// patch-param buffer).
105 pub primitive_id_base: u32,
106}
107
108impl PatchArray {
109 /// The patch type of the array, or `None` for a descriptor code no
110 /// [`GpuPatchTable`](super::GpuPatchTable) emits.
111 pub fn patch_type(&self) -> Option<PatchType> {
112 patch_descriptor::to_patch_type(self.desc)
113 }
114
115 /// The record as the six 32-bit words of `OsdPatchArray`.
116 pub fn to_words(&self) -> [u32; 6] {
117 [
118 self.reg_desc,
119 self.desc,
120 self.num_patches,
121 self.index_base,
122 self.stride,
123 self.primitive_id_base,
124 ]
125 }
126}
127
128/// A patch's parameterization packed into two words, plus its crease
129/// sharpness (`Osd::PatchParam`: `Far::PatchParam` with a `sharpness`,
130/// `OsdPatchParam` in the shaders).
131///
132/// The bit layout is `Far::PatchParam`'s:
133///
134/// | word | bits | field |
135/// |----------|---------|------------------------------------------|
136/// | `field0` | 0..28 | ptex face ([`face_id`](Self::face_id)) |
137/// | `field0` | 28..32 | transition mask (always `0`, see below) |
138/// | `field1` | 0..4 | [`depth`](Self::depth) |
139/// | `field1` | 4 | [`non_quad_root`](Self::non_quad_root) |
140/// | `field1` | 5 | [`is_regular`](Self::is_regular) |
141/// | `field1` | 7..12 | [`boundary`](Self::boundary) mask |
142/// | `field1` | 12..22 | [`v`](Self::v) |
143/// | `field1` | 22..32 | [`u`](Self::u) |
144///
145/// Patches carry no rotation: a [`GpuPatchTable`](super::GpuPatchTable)
146/// orders every patch's control points so that its `(s, t)` axes are the
147/// ptex face's `(u, v)` axes, and an inverted triangle is told by its
148/// position (`u + v >= 2^depth`, [`is_triangle_rotated`](Self::is_triangle_rotated)),
149/// as in OpenSubdiv.
150///
151/// The boundary mask has OpenSubdiv's meaning for each patch type:
152///
153/// * B-spline ([`patch_descriptor::REGULAR`]) with zero
154/// [`sharpness`](Self::sharpness): bit `k` set when face edge `k` (edge 0
155/// at `t = 0`, then counter-clockwise: `s = 1`, `t = 1`, `s = 0`) is a
156/// boundary or infinitely sharp crease, whose row or column of control
157/// points beyond is then *phantom*: its slots hold an arbitrary valid
158/// index, and its weights are folded onto the next two rows by the
159/// reflection `2a - b` (`OsdAdjustBoundaryWeights`).
160/// * B-spline with positive sharpness: a *single-crease* patch, the one
161/// set bit naming the face edge carrying the semi-sharp crease, all 16
162/// control points real. (OpenSubdiv's tessellation shaders read it the
163/// same way; its compute evaluator ignores the sharpness.)
164/// * Box-spline triangle ([`patch_descriptor::LOOP`]): the low three bits
165/// are edges or vertices, as the upper two bits say
166/// (`Osd_adjustBoxSplineTriBoundaryWeights`): `0` boundary edges only,
167/// `1` boundary vertices only, `2` boundary edges plus the vertex
168/// opposite each.
169/// * Other patch types: unused, `0`.
170///
171/// The transition mask (edges where the neighboring patch is one level
172/// deeper, for crack-free hardware tessellation) is not computed and is
173/// always `0`; parametric evaluation does not need it.
174#[repr(C)]
175#[derive(Debug, Clone, Copy, PartialEq)]
176pub struct PatchParam {
177 /// Ptex face and transition mask.
178 pub field0: u32,
179 /// Depth, flags, boundary mask and the patch's `(u, v)` cell.
180 pub field1: u32,
181 /// Sharpness of a single-crease patch's crease, `0.0` otherwise.
182 pub sharpness: f32,
183}
184
185impl PatchParam {
186 /// The deepest [`depth`](Self::depth), not counting
187 /// [`non_quad_root`](Self::non_quad_root), the packing can hold: the
188 /// `(u, v)` cell takes 10 bits per axis, as in OpenSubdiv.
189 pub const MAX_DEPTH: u32 = 10;
190
191 /// Pack the fields of a patch parameter (`Far::PatchParam::Set`). Each
192 /// field is truncated to its bit width.
193 #[allow(clippy::too_many_arguments)]
194 pub fn new(
195 face_id: u32,
196 u: u32,
197 v: u32,
198 depth: u32,
199 non_quad_root: bool,
200 boundary: u32,
201 transition: u32,
202 regular: bool,
203 sharpness: f32,
204 ) -> Self {
205 let pack = |value: u32, width: u32, offset: u32| (value & ((1 << width) - 1)) << offset;
206 PatchParam {
207 field0: pack(face_id, 28, 0) | pack(transition, 4, 28),
208 field1: pack(u, 10, 22)
209 | pack(v, 10, 12)
210 | pack(boundary, 5, 7)
211 | pack(regular as u32, 1, 5)
212 | pack(non_quad_root as u32, 1, 4)
213 | pack(depth, 4, 0),
214 sharpness,
215 }
216 }
217
218 /// The ptex face the patch belongs to (`GetFaceId`).
219 pub fn face_id(&self) -> u32 {
220 self.field0 & 0x0fff_ffff
221 }
222
223 /// The transition mask (`GetTransition`): always `0` in a
224 /// [`GpuPatchTable`](super::GpuPatchTable).
225 pub fn transition(&self) -> u32 {
226 self.field0 >> 28
227 }
228
229 /// The patch's column in the `2^(depth - non_quad_root)`-square grid
230 /// of its ptex face (`GetU`); see
231 /// [`is_triangle_rotated`](Self::is_triangle_rotated) for inverted
232 /// triangles.
233 pub fn u(&self) -> u32 {
234 (self.field1 >> 22) & 0x3ff
235 }
236
237 /// The patch's row in its ptex face's grid (`GetV`).
238 pub fn v(&self) -> u32 {
239 (self.field1 >> 12) & 0x3ff
240 }
241
242 /// The boundary mask (`GetBoundary`); see the [type docs](Self).
243 pub fn boundary(&self) -> u32 {
244 (self.field1 >> 7) & 0x1f
245 }
246
247 /// Is the patch a regular B-spline or box-spline patch (`IsRegular`)?
248 pub fn is_regular(&self) -> bool {
249 (self.field1 >> 5) & 1 != 0
250 }
251
252 /// Does the patch descend from a non-quad base face, whose level-1
253 /// children are the ptex faces (`NonQuadRoot`)? Its
254 /// [`depth`](Self::depth) then counts that first step.
255 pub fn non_quad_root(&self) -> bool {
256 (self.field1 >> 4) & 1 != 0
257 }
258
259 /// The refinement level of the patch (`GetDepth`).
260 pub fn depth(&self) -> u32 {
261 self.field1 & 0xf
262 }
263
264 /// The patch's size in its ptex face's parametric space
265 /// (`GetParamFraction`): `2^-(depth - non_quad_root)`.
266 pub fn param_fraction(&self) -> f32 {
267 1.0 / (1u32 << (self.depth() - self.non_quad_root() as u32)) as f32
268 }
269
270 /// Is this triangular patch inverted with respect to its ptex face
271 /// (`IsTriangleRotated`): the central child of a subdivided triangle,
272 /// encoded by `u + v >= 2^depth`? Its `(s, t)` axes then point along
273 /// the ptex face's `-u` and `-v`, from the corner at
274 /// `(2^depth - u, 2^depth - v) ยท 2^-depth`.
275 pub fn is_triangle_rotated(&self) -> bool {
276 self.u() + self.v() >= 1 << self.depth()
277 }
278
279 /// Convert ptex-face coordinates to the quad patch's local `(s, t)`
280 /// (`Normalize`).
281 pub fn normalize(&self, u: f32, v: f32) -> (f32, f32) {
282 let inv = 1.0 / self.param_fraction();
283 (u * inv - self.u() as f32, v * inv - self.v() as f32)
284 }
285
286 /// Convert the quad patch's local `(s, t)` to ptex-face coordinates
287 /// (`Unnormalize`).
288 pub fn unnormalize(&self, s: f32, t: f32) -> (f32, f32) {
289 let frac = self.param_fraction();
290 ((s + self.u() as f32) * frac, (t + self.v() as f32) * frac)
291 }
292
293 /// Convert ptex-face coordinates to the triangular patch's local
294 /// `(s, t)` (`NormalizeTriangle`).
295 pub fn normalize_triangle(&self, u: f32, v: f32) -> (f32, f32) {
296 if self.is_triangle_rotated() {
297 let inv = 1.0 / self.param_fraction();
298 let n = (1u32 << self.depth()) as f32;
299 (n - self.u() as f32 - u * inv, n - self.v() as f32 - v * inv)
300 } else {
301 self.normalize(u, v)
302 }
303 }
304
305 /// Convert the triangular patch's local `(s, t)` to ptex-face
306 /// coordinates (`UnnormalizeTriangle`).
307 pub fn unnormalize_triangle(&self, s: f32, t: f32) -> (f32, f32) {
308 if self.is_triangle_rotated() {
309 let frac = self.param_fraction();
310 let n = (1u32 << self.depth()) as f32;
311 (
312 (n - self.u() as f32 - s) * frac,
313 (n - self.v() as f32 - t) * frac,
314 )
315 } else {
316 self.unnormalize(s, t)
317 }
318 }
319
320 /// The record as the three 32-bit words of `OsdPatchParam`, the
321 /// sharpness as its IEEE-754 bits.
322 pub fn to_words(&self) -> [u32; 3] {
323 [self.field0, self.field1, self.sharpness.to_bits()]
324 }
325}
326
327/// A location to evaluate: a patch and a ptex-face `(u, v)` inside it
328/// (`Osd::PatchCoord`, `OsdPatchCoord` in the shaders).
329///
330/// Build one with [`GpuPatchTable::patch_coord`](super::GpuPatchTable::patch_coord)
331/// from the patch [`PatchMap::find_patch`](crate::far::PatchMap::find_patch)
332/// returns.
333#[repr(C)]
334#[derive(Debug, Clone, Copy, PartialEq)]
335pub struct PatchCoord {
336 /// The [`PatchArray`] holding the patch.
337 pub array_index: u32,
338 /// The patch, an index into the patch-param buffer.
339 pub patch_index: u32,
340 /// Where the patch's control points start in the index buffer.
341 pub vert_index: u32,
342 /// The ptex-face `u` coordinate.
343 pub s: f32,
344 /// The ptex-face `v` coordinate.
345 pub t: f32,
346}
347
348impl PatchCoord {
349 /// The record as the five 32-bit words of `OsdPatchCoord`, the
350 /// coordinates as their IEEE-754 bits.
351 pub fn to_words(&self) -> [u32; 5] {
352 [
353 self.array_index,
354 self.patch_index,
355 self.vert_index,
356 self.s.to_bits(),
357 self.t.to_bits(),
358 ]
359 }
360}
361
362#[cfg(test)]
363mod tests {
364 use super::*;
365
366 #[test]
367 fn records_have_the_shader_layouts() {
368 assert_eq!(std::mem::size_of::<PatchArray>(), 24);
369 assert_eq!(std::mem::size_of::<PatchParam>(), 12);
370 assert_eq!(std::mem::size_of::<PatchCoord>(), 20);
371 }
372
373 #[test]
374 fn patch_param_round_trips_its_fields() {
375 let p = PatchParam::new(0x0abc_def1, 1023, 517, 11, true, 0x15, 0xa, true, 2.5);
376 assert_eq!(p.face_id(), 0x0abc_def1);
377 assert_eq!(p.u(), 1023);
378 assert_eq!(p.v(), 517);
379 assert_eq!(p.depth(), 11);
380 assert!(p.non_quad_root());
381 assert_eq!(p.boundary(), 0x15);
382 assert_eq!(p.transition(), 0xa);
383 assert!(p.is_regular());
384 assert_eq!(p.to_words()[2], 2.5f32.to_bits());
385
386 // Far::PatchParam::Set's bit positions.
387 let q = PatchParam::new(7, 3, 5, 2, false, 0b1001, 0, false, 0.0);
388 assert_eq!(q.field0, 7);
389 assert_eq!(q.field1, 3 << 22 | 5 << 12 | 0b1001 << 7 | 2);
390 }
391
392 #[test]
393 fn triangle_normalization_inverts() {
394 // The central child of a depth-1 triangle.
395 let p = PatchParam::new(0, 1, 1, 1, false, 0, 0, true, 0.0);
396 assert!(p.is_triangle_rotated());
397 assert_eq!(p.unnormalize_triangle(0.0, 0.0), (0.5, 0.5));
398 assert_eq!(p.unnormalize_triangle(1.0, 0.0), (0.0, 0.5));
399 let (s, t) = p.normalize_triangle(0.3, 0.4);
400 assert!((s - 0.4).abs() < 1e-6 && (t - 0.2).abs() < 1e-6);
401 }
402
403 #[test]
404 fn descriptor_codes_round_trip() {
405 for t in [
406 PatchType::Regular,
407 PatchType::GregoryBasis,
408 PatchType::Quads,
409 PatchType::Loop,
410 PatchType::GregoryTriangle,
411 PatchType::Triangles,
412 ] {
413 let code = patch_descriptor::from_patch_type(t);
414 assert_eq!(patch_descriptor::to_patch_type(code), Some(t));
415 assert!(patch_descriptor::num_control_vertices(code) > 0);
416 }
417 assert_eq!(patch_descriptor::to_patch_type(0), None);
418 }
419}