Skip to main content

opensubdiv_rs/osd/
patch_basis.rs

1//! Patch basis evaluation from a packed [`PatchParam`] (port of
2//! `OsdEvaluatePatchBasis` in `opensubdiv/osd/patchBasis.h`).
3//!
4//! This is the function a GPU patch kernel runs per evaluation point, kept
5//! on the CPU as the reference a shader port is checked against: it reads
6//! only the descriptor code, the packed parameter and the ptex-face
7//! coordinates, and returns weights over the patch's control points in
8//! index-buffer order.
9
10use super::types::{patch_descriptor, PatchParam};
11use crate::far::gregory;
12use crate::far::loop_patch;
13use crate::far::patch_table::{bspline_basis, crease_basis_oriented};
14
15/// The basis weights of one patch at one location: the limit point is
16/// `Σ point[k] · cv[k]` over the patch's
17/// [`num_points`](Self::num_points) control points, and likewise its first
18/// derivatives along the ptex face's `u` and `v`.
19#[derive(Debug, Clone, Copy, PartialEq)]
20pub struct PatchWeights {
21    /// The number of control points of the patch; the arrays are zero past
22    /// it.
23    pub num_points: usize,
24    /// Weights of the limit position.
25    pub point: [f32; 20],
26    /// Weights of the derivative along the ptex face's `u`.
27    pub du: [f32; 20],
28    /// Weights of the derivative along the ptex face's `v`.
29    pub dv: [f32; 20],
30}
31
32/// Evaluate the basis of a patch of descriptor code `desc` with packed
33/// parameter `param` at ptex-face coordinates `(u, v)`
34/// (`OsdEvaluatePatchBasis`), or `None` for a code no
35/// [`GpuPatchTable`](super::GpuPatchTable) emits.
36///
37/// Boundary masks and single creases are read as described on
38/// [`PatchParam`]; derivatives are scaled to the ptex face's parameter
39/// space, and negated for inverted triangles.
40pub fn evaluate_patch_basis(desc: u32, param: &PatchParam, u: f32, v: f32) -> Option<PatchWeights> {
41    let num_points = patch_descriptor::num_control_vertices(desc);
42    if num_points == 0 {
43        return None;
44    }
45    let triangular = patch_descriptor::is_triangular(desc);
46    let (s, t) = if triangular {
47        param.normalize_triangle(u, v)
48    } else {
49        param.normalize(u, v)
50    };
51    let mut scale = 1.0 / param.param_fraction();
52    if triangular && param.is_triangle_rotated() {
53        scale = -scale;
54    }
55
56    let mut w = PatchWeights {
57        num_points,
58        point: [0.0; 20],
59        du: [0.0; 20],
60        dv: [0.0; 20],
61    };
62    let mut set = |k: usize, p: f32, ds: f32, dt: f32| {
63        w.point[k] = p;
64        w.du[k] = ds * scale;
65        w.dv[k] = dt * scale;
66    };
67
68    match desc {
69        patch_descriptor::REGULAR => {
70            let (bu, dbu, bv, dbv) = if param.sharpness > 0.0 {
71                single_crease_basis(param.boundary(), param.sharpness, s, t)
72            } else {
73                let (mut bu, mut dbu) = bspline_basis(s);
74                let (mut bv, mut dbv) = bspline_basis(t);
75                adjust_boundary_weights(param.boundary(), &mut bu, &mut bv);
76                adjust_boundary_weights(param.boundary(), &mut dbu, &mut dbv);
77                (bu, dbu, bv, dbv)
78            };
79            for j in 0..4 {
80                for i in 0..4 {
81                    set(4 * j + i, bu[i] * bv[j], dbu[i] * bv[j], bu[i] * dbv[j]);
82                }
83            }
84        }
85        patch_descriptor::GREGORY_BASIS => {
86            let (p, ds, dt) = gregory::evaluate_basis(s, t);
87            for k in 0..20 {
88                set(k, p[k], ds[k], dt[k]);
89            }
90        }
91        patch_descriptor::QUADS => {
92            let p = [(1.0 - s) * (1.0 - t), s * (1.0 - t), s * t, (1.0 - s) * t];
93            let ds = [-(1.0 - t), 1.0 - t, t, -t];
94            let dt = [-(1.0 - s), -s, s, 1.0 - s];
95            for k in 0..4 {
96                set(k, p[k], ds[k], dt[k]);
97            }
98        }
99        patch_descriptor::LOOP => {
100            let (mut p, mut ds, mut dt) = loop_patch::box_spline_basis(s, t);
101            let boundary = param.boundary();
102            adjust_box_spline_tri_boundary_weights(boundary, &mut p);
103            adjust_box_spline_tri_boundary_weights(boundary, &mut ds);
104            adjust_box_spline_tri_boundary_weights(boundary, &mut dt);
105            for k in 0..12 {
106                set(k, p[k], ds[k], dt[k]);
107            }
108        }
109        patch_descriptor::GREGORY_TRIANGLE => {
110            let (p, ds, dt) = loop_patch::evaluate_basis(s, t);
111            for k in 0..18 {
112                set(k, p[k], ds[k], dt[k]);
113            }
114        }
115        _ => {
116            debug_assert_eq!(desc, patch_descriptor::TRIANGLES);
117            let p = [1.0 - s - t, s, t];
118            let ds = [-1.0, 1.0, 0.0];
119            let dt = [-1.0, 0.0, 1.0];
120            for k in 0..3 {
121                set(k, p[k], ds[k], dt[k]);
122            }
123        }
124    }
125    Some(w)
126}
127
128type Basis4 = ([f32; 4], [f32; 4]);
129
130/// The two univariate bases of a single-crease patch whose crease lies on
131/// the face edge named by the one bit set in `boundary`: the exact limit
132/// profile of a crease of sharpness `sharpness` across it, the B-spline
133/// along it.
134fn single_crease_basis(
135    boundary: u32,
136    sharpness: f32,
137    s: f32,
138    t: f32,
139) -> ([f32; 4], [f32; 4], [f32; 4], [f32; 4]) {
140    // Edges 3 and 1 are the columns at s = 0 and s = 1, edges 0 and 2 the
141    // rows at t = 0 and t = 1.
142    let edge = boundary.trailing_zeros();
143    let (bu, dbu): Basis4 = match edge {
144        3 => crease_basis_oriented(s, sharpness, false),
145        1 => crease_basis_oriented(s, sharpness, true),
146        _ => bspline_basis(s),
147    };
148    let (bv, dbv): Basis4 = match edge {
149        0 => crease_basis_oriented(t, sharpness, false),
150        2 => crease_basis_oriented(t, sharpness, true),
151        _ => bspline_basis(t),
152    };
153    (bu, dbu, bv, dbv)
154}
155
156/// Fold the phantom rows and columns of a boundary B-spline patch onto the
157/// next two by the reflection `2a - b`, in each univariate basis
158/// (`OsdAdjustBoundaryWeights`).
159fn adjust_boundary_weights(boundary: u32, s_weights: &mut [f32; 4], t_weights: &mut [f32; 4]) {
160    if boundary & 1 != 0 {
161        t_weights[2] -= t_weights[0];
162        t_weights[1] += t_weights[0] * 2.0;
163        t_weights[0] = 0.0;
164    }
165    if boundary & 2 != 0 {
166        s_weights[1] -= s_weights[3];
167        s_weights[2] += s_weights[3] * 2.0;
168        s_weights[3] = 0.0;
169    }
170    if boundary & 4 != 0 {
171        t_weights[1] -= t_weights[3];
172        t_weights[2] += t_weights[3] * 2.0;
173        t_weights[3] = 0.0;
174    }
175    if boundary & 8 != 0 {
176        s_weights[2] -= s_weights[0];
177        s_weights[1] += s_weights[0] * 2.0;
178        s_weights[0] = 0.0;
179    }
180}
181
182/// Fold the weights of the phantom points of a boundary box-spline
183/// triangle onto real ones (`Osd_adjustBoxSplineTriBoundaryWeights`):
184/// beyond a boundary edge by the parallelogram rule, through a corner where
185/// two boundary edges meet by the point reflection, and beyond a boundary
186/// vertex along the lattice line through it.
187fn adjust_box_spline_tri_boundary_weights(boundary: u32, w: &mut [f32; 12]) {
188    if boundary == 0 {
189        return;
190    }
191    let upper = (boundary >> 3) & 0x3;
192    let lower = boundary & 0x7;
193    let (e_bits, v_bits) = match upper {
194        // Boundary vertices only.
195        1 => (0, lower),
196        // Boundary edges, and the vertex opposite each: the edge bits
197        // rotated one to the right.
198        2 => (lower, ((lower & 1) << 2) | (lower >> 1)),
199        _ => (lower, 0),
200    };
201    let edge = [e_bits & 1 != 0, e_bits & 2 != 0, e_bits & 4 != 0];
202
203    // `fold(w, src, [(dst, factor)..])`: move src's weight onto dst.
204    fn fold(w: &mut [f32; 12], src: usize, targets: &[(usize, f32)]) {
205        let x = w[src];
206        for &(dst, factor) in targets {
207            w[dst] += factor * x;
208        }
209    }
210    // Edge e's three phantoms (P0, P1, P2), and per corner phantom the rule
211    // when the adjacent edge is also a boundary (point reflection through
212    // the corner) or not (parallelogram).
213    if edge[0] {
214        if edge[2] {
215            fold(w, 0, &[(4, 2.0), (8, -1.0)]);
216        } else {
217            fold(w, 0, &[(4, 1.0), (3, 1.0), (7, -1.0)]);
218        }
219        fold(w, 1, &[(4, 1.0), (5, 1.0), (8, -1.0)]);
220        if edge[1] {
221            fold(w, 2, &[(5, 2.0), (8, -1.0)]);
222        } else {
223            fold(w, 2, &[(5, 1.0), (6, 1.0), (9, -1.0)]);
224        }
225        w[0] = 0.0;
226        w[1] = 0.0;
227        w[2] = 0.0;
228    }
229    if edge[1] {
230        if edge[0] {
231            fold(w, 6, &[(5, 2.0), (4, -1.0)]);
232        } else {
233            fold(w, 6, &[(5, 1.0), (2, 1.0), (1, -1.0)]);
234        }
235        fold(w, 9, &[(5, 1.0), (8, 1.0), (4, -1.0)]);
236        if edge[2] {
237            fold(w, 11, &[(8, 2.0), (4, -1.0)]);
238        } else {
239            fold(w, 11, &[(8, 1.0), (10, 1.0), (7, -1.0)]);
240        }
241        w[6] = 0.0;
242        w[9] = 0.0;
243        w[11] = 0.0;
244    }
245    if edge[2] {
246        if edge[1] {
247            fold(w, 10, &[(8, 2.0), (5, -1.0)]);
248        } else {
249            fold(w, 10, &[(8, 1.0), (11, 1.0), (9, -1.0)]);
250        }
251        fold(w, 7, &[(8, 1.0), (4, 1.0), (5, -1.0)]);
252        if edge[0] {
253            fold(w, 3, &[(4, 2.0), (5, -1.0)]);
254        } else {
255            fold(w, 3, &[(4, 1.0), (0, 1.0), (1, -1.0)]);
256        }
257        w[10] = 0.0;
258        w[7] = 0.0;
259        w[3] = 0.0;
260    }
261    if v_bits & 1 != 0 {
262        fold(w, 3, &[(4, 1.0), (7, 1.0), (8, -1.0)]);
263        fold(w, 0, &[(4, 1.0), (1, 1.0), (5, -1.0)]);
264        w[3] = 0.0;
265        w[0] = 0.0;
266    }
267    if v_bits & 2 != 0 {
268        fold(w, 2, &[(5, 1.0), (1, 1.0), (4, -1.0)]);
269        fold(w, 6, &[(5, 1.0), (9, 1.0), (8, -1.0)]);
270        w[2] = 0.0;
271        w[6] = 0.0;
272    }
273    if v_bits & 4 != 0 {
274        fold(w, 11, &[(8, 1.0), (9, 1.0), (5, -1.0)]);
275        fold(w, 10, &[(8, 1.0), (7, 1.0), (4, -1.0)]);
276        w[11] = 0.0;
277        w[10] = 0.0;
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284    use crate::far::loop_patch::fold_phantom_weights;
285    use crate::INDEX_INVALID;
286
287    /// The OpenSubdiv triangle fold agrees with this crate's own phantom
288    /// rules for every wall pattern a regular neighborhood can have.
289    #[test]
290    fn box_spline_folds_match_the_phantom_rules() {
291        let edge_slots = [[0usize, 1, 2], [6, 9, 11], [3, 7, 10]];
292        let vertex_slots = [[0usize, 3], [2, 6], [10, 11]];
293        let mut cases = Vec::new();
294        for edges in 0u32..8 {
295            cases.push((edges, 0u32));
296        }
297        for vertices in 1u32..8 {
298            cases.push((0, vertices));
299        }
300        for e in 0..3u32 {
301            // An edge and the vertex opposite it.
302            cases.push((1 << e, 1 << ((e + 2) % 3)));
303        }
304        for (edges, vertices) in cases {
305            let mut cvs = [0u32; 12];
306            for k in 0..3 {
307                if edges & (1 << k) != 0 {
308                    edge_slots[k].iter().for_each(|&s| cvs[s] = INDEX_INVALID);
309                }
310                if vertices & (1 << k) != 0 {
311                    vertex_slots[k].iter().for_each(|&s| cvs[s] = INDEX_INVALID);
312                }
313            }
314            let mask = match (edges, vertices) {
315                (e, 0) => e,
316                (0, v) => v | 1 << 3,
317                (e, _) => e | 2 << 3,
318            };
319            for (s, t) in [(0.2f32, 0.3f32), (0.6, 0.1), (0.05, 0.9)] {
320                let (mut expected, _, _) = loop_patch::box_spline_basis(s, t);
321                fold_phantom_weights(&cvs, &mut expected);
322                let (mut actual, _, _) = loop_patch::box_spline_basis(s, t);
323                adjust_box_spline_tri_boundary_weights(mask, &mut actual);
324                for k in 0..12 {
325                    assert!(
326                        (actual[k] - expected[k]).abs() < 1e-6,
327                        "mask {mask:#b} slot {k}: {} vs {}",
328                        actual[k],
329                        expected[k]
330                    );
331                }
332            }
333        }
334    }
335}