opensubdiv-rs 0.7.0

A faithful Rust port of Pixar's OpenSubdiv subdivision-surface library (Sdc / Vtr / Far layers)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! The topology refiner and its factory (port of
//! `opensubdiv/far/topologyRefiner.h` and
//! `opensubdiv/far/topologyRefinerFactory.h`).

use super::fvar::FVarChannel;
use super::topology_descriptor::TopologyDescriptor;
use crate::sdc::{self, Scheme, SchemeType};
use crate::vtr::{Level, Refinement, TopologyError};
use crate::Index;

/// Options controlling uniform refinement
/// (`Far::TopologyRefiner::UniformOptions`).
#[derive(Debug, Clone, Copy)]
pub struct UniformOptions {
    /// The number of refinement iterations to apply.
    pub refinement_level: usize,
}

impl UniformOptions {
    /// Refine uniformly `refinement_level` times.
    pub fn new(refinement_level: usize) -> Self {
        Self { refinement_level }
    }
}

/// Options controlling feature-adaptive refinement
/// (`Far::TopologyRefiner::AdaptiveOptions`).
#[derive(Debug, Clone, Copy)]
pub struct AdaptiveOptions {
    /// The maximum level of refinement applied to isolate irregular
    /// features (`isolationLevel`), capped at
    /// [`MAX_ISOLATION_LEVEL`](Self::MAX_ISOLATION_LEVEL).
    pub isolation_level: usize,
    /// Represent regular faces along a semi-sharp crease as single-crease
    /// patches instead of isolating the crease (`useSingleCreasePatch`).
    /// Applies to the Catmark scheme only.
    ///
    /// A face whose corners are regular and which a single straight
    /// semi-sharp crease of uniform sharpness bounds on one side is not
    /// refined further: the [`super::PatchTable`] covers it with one exact
    /// [`super::PatchType::Regular`] patch carrying the crease's sharpness
    /// ([`super::PatchTable::single_crease_sharpness`]), rather than with
    /// `4^level` patches down to where the crease decays (or to the
    /// isolation cap). Off by default, as in OpenSubdiv.
    pub use_single_crease_patch: bool,
    /// Also isolate the irregular features of face-varying channels
    /// (`considerFVarChannels`): a face is refined further when the value
    /// mesh of a channel that is not linear
    /// ([`FVarLinearInterpolation::All`](crate::sdc::FVarLinearInterpolation::All))
    /// is irregular around it — at seam junctions, fvar darts and
    /// irregular seam corners, say — even where the vertex topology is
    /// regular.
    ///
    /// Without it, such a face is patched where its vertex topology becomes
    /// regular, and its face-varying patch
    /// ([`super::PatchTable::evaluate_basis_face_varying`]) is a Gregory
    /// end cap at that level: an approximation of the channel's limit
    /// there. With it, the face-varying patches approximate the limit as
    /// closely as the vertex patches do, at the cost of more patches. Off
    /// by default, as in OpenSubdiv.
    pub consider_fvar_channels: bool,
}

impl AdaptiveOptions {
    /// The deepest isolation level [`TopologyRefiner::refine_adaptive`]
    /// applies; larger requests are clamped to it. As in OpenSubdiv
    /// (whose `isolationLevel` is documented for `0..=10`), features not
    /// resolved by then are capped with Gregory patches, which also keeps
    /// every [`super::PatchParam::depth`] well within the range the
    /// parametric scale `2^depth` is computed for.
    pub const MAX_ISOLATION_LEVEL: usize = 10;

    /// Isolate irregular features up to `isolation_level` levels deep
    /// (at most [`MAX_ISOLATION_LEVEL`](Self::MAX_ISOLATION_LEVEL)).
    pub fn new(isolation_level: usize) -> Self {
        Self {
            isolation_level,
            use_single_crease_patch: false,
            consider_fvar_channels: false,
        }
    }

    /// Enable or disable single-crease patches
    /// ([`use_single_crease_patch`](Self::use_single_crease_patch)).
    pub fn with_single_crease_patch(mut self, enabled: bool) -> Self {
        self.use_single_crease_patch = enabled;
        self
    }

    /// Enable or disable the isolation of face-varying features
    /// ([`consider_fvar_channels`](Self::consider_fvar_channels)).
    pub fn with_consider_fvar_channels(mut self, enabled: bool) -> Self {
        self.consider_fvar_channels = enabled;
        self
    }
}

/// Public interface to the topology of one refinement level
/// (`Far::TopologyLevel`) — a thin view over a [`crate::vtr::Level`].
#[derive(Debug, Clone, Copy)]
pub struct TopologyLevel<'a> {
    level: &'a Level,
    fvar_channels: &'a [FVarChannel],
    level_index: usize,
}

impl<'a> TopologyLevel<'a> {
    /// The number of vertices in this level (`GetNumVertices`).
    pub fn num_vertices(&self) -> usize {
        self.level.num_vertices()
    }

    /// The number of edges in this level (`GetNumEdges`).
    pub fn num_edges(&self) -> usize {
        self.level.num_edges()
    }

    /// The number of faces in this level (`GetNumFaces`).
    pub fn num_faces(&self) -> usize {
        self.level.num_faces()
    }

    /// Total number of face-vertex pairs (`GetNumFaceVerticesTotal`).
    pub fn num_face_vertices_total(&self) -> usize {
        self.level.num_face_vertices_total()
    }

    /// The vertices of `face`, in winding order (`GetFaceVertices`).
    pub fn face_vertices(&self, face: usize) -> &'a [Index] {
        self.level.face_vertices(face)
    }

    /// The edges of `face` (`GetFaceEdges`).
    pub fn face_edges(&self, face: usize) -> &'a [Index] {
        self.level.face_edges(face)
    }

    /// The two end vertices of `edge` (`GetEdgeVertices`).
    pub fn edge_vertices(&self, edge: usize) -> [Index; 2] {
        self.level.edge_vertices(edge)
    }

    /// The faces incident `edge` (`GetEdgeFaces`).
    pub fn edge_faces(&self, edge: usize) -> &'a [Index] {
        self.level.edge_faces(edge)
    }

    /// The faces incident `vertex` (`GetVertexFaces`).
    pub fn vertex_faces(&self, vertex: usize) -> &'a [Index] {
        self.level.vertex_faces(vertex)
    }

    /// The edges incident `vertex` (`GetVertexEdges`).
    pub fn vertex_edges(&self, vertex: usize) -> &'a [Index] {
        self.level.vertex_edges(vertex)
    }

    /// Find the edge connecting two vertices (`FindEdge`).
    pub fn find_edge(&self, v0: Index, v1: Index) -> Option<Index> {
        self.level.find_edge(v0, v1)
    }

    /// The effective sharpness of `edge` (`GetEdgeSharpness`). Boundary
    /// sharpening implied by the boundary-interpolation option is included.
    pub fn edge_sharpness(&self, edge: usize) -> f32 {
        self.level.edge_sharpness(edge)
    }

    /// The effective sharpness of `vertex` (`GetVertexSharpness`).
    pub fn vertex_sharpness(&self, vertex: usize) -> f32 {
        self.level.vertex_sharpness(vertex)
    }

    /// Does `edge` lie on a mesh boundary (`IsEdgeBoundary`)?
    pub fn is_edge_boundary(&self, edge: usize) -> bool {
        self.level.is_edge_boundary(edge)
    }

    /// Is `edge` non-manifold, i.e. shared by more than two faces
    /// (`IsEdgeNonManifold`)?
    pub fn is_edge_non_manifold(&self, edge: usize) -> bool {
        self.level.is_edge_non_manifold(edge)
    }

    /// Does `vertex` lie on a mesh boundary (`IsVertexBoundary`)?
    pub fn is_vertex_boundary(&self, vertex: usize) -> bool {
        self.level.is_vertex_boundary(vertex)
    }

    /// Is `face` tagged as a hole (`IsFaceHole`)?
    pub fn is_face_hole(&self, face: usize) -> bool {
        self.level.is_face_hole(face)
    }

    /// The number of face-varying channels (`GetNumFVarChannels`).
    pub fn num_fvar_channels(&self) -> usize {
        self.fvar_channels.len()
    }

    /// The number of face-varying values of `channel` at this level
    /// (`GetNumFVarValues`).
    pub fn num_fvar_values(&self, channel: usize) -> usize {
        self.fvar_channels[channel].num_values(self.level_index)
    }

    /// The face-varying values associated with the corners of `face`, in the
    /// same winding order as [`face_vertices`](Self::face_vertices)
    /// (`GetFaceFVarValues`).
    pub fn face_fvar_values(&self, face: usize, channel: usize) -> &'a [Index] {
        self.fvar_channels[channel].face_values(self.level_index, face)
    }

    pub(super) fn inner(&self) -> &'a Level {
        self.level
    }
}

/// Stores the hierarchy of refined topology levels and the refinements
/// between them (`Far::TopologyRefiner`).
#[derive(Debug, Clone)]
pub struct TopologyRefiner {
    scheme: Scheme,
    options: sdc::Options,
    levels: Vec<Level>,
    refinements: Vec<Refinement>,
    fvar_channels: Vec<FVarChannel>,
    /// True when the hierarchy was produced by [`refine_adaptive`]
    /// (`Self::refine_adaptive`); levels above 0 are then sparse.
    adaptive: bool,
    /// For each refinement step, the faces of the parent level that were
    /// selected for refinement (all `true` for uniform steps).
    selections: Vec<Vec<bool>>,
    /// Did adaptive refinement leave single-crease patches unrefined
    /// ([`AdaptiveOptions::use_single_crease_patch`])?
    single_crease_patch: bool,
}

impl TopologyRefiner {
    /// The subdivision scheme of this refiner (`GetSchemeType`).
    pub fn scheme_type(&self) -> SchemeType {
        self.scheme.scheme_type()
    }

    /// The subdivision options of this refiner (`GetSchemeOptions`).
    pub fn scheme_options(&self) -> sdc::Options {
        self.options
    }

    pub(super) fn scheme(&self) -> &Scheme {
        &self.scheme
    }

    /// The number of refinement levels, including the base level
    /// (`GetNumLevels`).
    pub fn num_levels(&self) -> usize {
        self.levels.len()
    }

    /// The highest refinement level (`GetMaxLevel`).
    pub fn max_level(&self) -> usize {
        self.levels.len() - 1
    }

    /// The topology of refinement level `level` (`GetLevel`).
    pub fn level(&self, level: usize) -> TopologyLevel<'_> {
        TopologyLevel {
            level: &self.levels[level],
            fvar_channels: &self.fvar_channels,
            level_index: level,
        }
    }

    /// The number of face-varying channels (`GetNumFVarChannels`).
    pub fn num_fvar_channels(&self) -> usize {
        self.fvar_channels.len()
    }

    /// The face-varying channel `channel`.
    pub fn fvar_channel(&self, channel: usize) -> &FVarChannel {
        &self.fvar_channels[channel]
    }

    /// The refinement that produced level `level` from level `level - 1`.
    pub fn refinement(&self, level: usize) -> &Refinement {
        &self.refinements[level - 1]
    }

    /// Sum of the vertex counts of all levels (`GetNumVerticesTotal`).
    pub fn num_vertices_total(&self) -> usize {
        self.levels.iter().map(|l| l.num_vertices()).sum()
    }

    /// Sum of the face counts of all levels (`GetNumFacesTotal`).
    pub fn num_faces_total(&self) -> usize {
        self.levels.iter().map(|l| l.num_faces()).sum()
    }

    /// Refine the topology uniformly (`RefineUniform`): every face is
    /// subdivided at every iteration until `options.refinement_level` levels
    /// of refinement exist.
    ///
    /// Calling this more than once extends the existing hierarchy if the new
    /// target is deeper; it never discards levels.
    pub fn refine_uniform(&mut self, options: UniformOptions) {
        assert!(
            !self.adaptive,
            "cannot mix uniform and adaptive refinement on one refiner"
        );
        while self.max_level() < options.refinement_level {
            let num_faces = self.levels.last().unwrap().num_faces();
            let (child, refinement) = Refinement::refine(self.levels.last().unwrap(), &self.scheme)
                .expect("refined topology is always internally consistent");
            self.levels.push(child);
            self.refinements.push(refinement);
            self.selections.push(vec![true; num_faces]);
            // Face-varying channels refine in lockstep with the geometry.
            for channel in &mut self.fvar_channels {
                channel.refine_once(None);
            }
        }
    }

    /// Feature-adaptively refine the topology (`RefineAdaptive`): starting
    /// from the base level, only faces whose neighborhood prevents the
    /// limit surface from being a (boundary-aware) bicubic B-spline patch —
    /// extraordinary vertices, non-quads, semi-sharp creases, and irregular
    /// infinitely sharp features — are *selected* and subdivided, together
    /// with their one-ring support, until they resolve or
    /// `options.isolation_level` is reached. Regular infinitely sharp
    /// creases and corners are not isolated: like boundaries, they bound
    /// exact B-spline patches (OpenSubdiv's `useInfSharpPatch`); with
    /// [`AdaptiveOptions::use_single_crease_patch`], neither are regular
    /// faces bounded by a single semi-sharp crease. Levels
    /// above 0 are sparse: memory grows with the mesh's irregular features,
    /// not with `4^level`.
    ///
    /// Isolation stops at [`AdaptiveOptions::MAX_ISOLATION_LEVEL`] however
    /// deep a level is requested.
    ///
    /// Patches for an adaptively refined mesh live at mixed depths — build
    /// a [`super::PatchTable`] to evaluate the limit surface, or a
    /// [`super::LimitStencilTable`] to evaluate it straight from the base
    /// cage. [`super::PrimvarRefiner::interpolate`] and
    /// [`super::StencilTableFactory::create`] work level by level as
    /// usual; [`super::PrimvarRefiner::limit`] and
    /// [`super::StencilTableFactory::create_limit`] — the limit of the
    /// last level's vertices — require uniform refinement.
    ///
    /// For the Loop scheme the same isolation applies to triangles: faces
    /// whose three corners are regular (interior valence 6, regular
    /// boundary and crease vertices, pinned corners) are exact box-spline
    /// patches and are not refined; the rest — extraordinary vertices,
    /// semi-sharp creases, irregular boundaries and darts — descend to the
    /// isolation cap. For Bilinear only non-quad base faces need one round
    /// of isolation.
    ///
    /// With [`AdaptiveOptions::consider_fvar_channels`], faces around the
    /// irregular features of non-linear face-varying channels are isolated
    /// the same way.
    ///
    /// To isolate features around a few base faces only, use
    /// [`refine_adaptive_selected`](Self::refine_adaptive_selected).
    pub fn refine_adaptive(&mut self, options: AdaptiveOptions) {
        self.refine_adaptive_impl(options, None);
    }

    /// Feature-adaptively refine the topology around the base faces
    /// `selected_faces` only (`RefineAdaptive` with `selectedFaces`).
    ///
    /// As [`refine_adaptive`](Self::refine_adaptive), except that at the
    /// base level only the faces in `selected_faces` are inspected and
    /// isolated: the rest of the cage is left unrefined, apart from the
    /// one-ring support the selected faces' children need. Below the base
    /// level isolation proceeds as usual among the descendants of the
    /// selected faces, so each selected face is refined exactly as
    /// [`refine_adaptive`](Self::refine_adaptive) refines it, and the
    /// cost grows with the selected area instead of the cage size.
    ///
    /// Build the patches of the selected faces with
    /// [`PatchTableFactory::create_with_options_selected`](super::PatchTableFactory::create_with_options_selected):
    /// they are the patches a full refinement and a full table give those
    /// faces, and they evaluate the same limit surface. A full table built
    /// from this refiner caps the irregular faces that were not selected at
    /// the base level (and cannot cover unselected non-quad faces, which
    /// need a refinement to be patched).
    ///
    /// Unlike OpenSubdiv, where an empty `selectedFaces` array means every
    /// face, an empty `selected_faces` selects nothing and leaves the
    /// refiner unrefined. Duplicates and holes are ignored.
    ///
    /// # Panics
    ///
    /// Panics when a selected face is not a face of the base level, or, as
    /// [`refine_adaptive`](Self::refine_adaptive), when the refiner has
    /// already been refined.
    pub fn refine_adaptive_selected(&mut self, options: AdaptiveOptions, selected_faces: &[Index]) {
        let num_faces = self.levels[0].num_faces();
        if let Some(&face) = selected_faces.iter().find(|&&f| f as usize >= num_faces) {
            panic!("selected face {face} out of range ({num_faces} base faces)");
        }
        self.refine_adaptive_impl(options, Some(selected_faces));
    }

    /// Adaptive refinement, inspecting only `base_faces` (when given) at
    /// the base level.
    fn refine_adaptive_impl(&mut self, options: AdaptiveOptions, base_faces: Option<&[Index]>) {
        assert!(
            self.max_level() == 0,
            "adaptive refinement must start from an unrefined refiner"
        );
        self.adaptive = true;
        self.single_crease_patch = options.use_single_crease_patch;
        let isolation_level = options
            .isolation_level
            .min(AdaptiveOptions::MAX_ISOLATION_LEVEL);

        while self.max_level() < isolation_level {
            let level_index = self.max_level();
            let level = self.levels.last().unwrap();

            let mut selected = vec![false; level.num_faces()];
            let mut any = false;
            let mut inspect = |f: usize| {
                if !selected[f] && self.face_needs_isolation(&options, level_index, f) {
                    selected[f] = true;
                    any = true;
                }
            };
            match (level_index, base_faces) {
                (0, Some(faces)) => faces.iter().for_each(|&f| inspect(f as usize)),
                _ => (0..level.num_faces()).for_each(inspect),
            }
            if !any {
                break;
            }

            // The selection is expanded to its one-ring support once, on
            // the geometry, and that mask refines the face-varying channels
            // too: their value meshes mirror the geometry's faces but not
            // its vertex connectivity (seams split vertices), so expanding
            // on each mesh separately would refine different faces.
            let included = Refinement::expand_selection(level, &selected);
            let (child, refinement) =
                Refinement::refine_included(self.levels.last().unwrap(), &self.scheme, &included)
                    .expect("refined topology is always internally consistent");
            self.levels.push(child);
            self.refinements.push(refinement);
            for channel in &mut self.fvar_channels {
                channel.refine_once(Some(&included));
            }
            self.selections.push(selected);
        }
    }

    /// Does face `f` of the last level `level_index` need to be refined
    /// further: is it a non-hole candidate whose neighborhood — or, with
    /// [`AdaptiveOptions::consider_fvar_channels`], a non-linear channel's —
    /// is not a regular patch?
    fn face_needs_isolation(
        &self,
        options: &AdaptiveOptions,
        level_index: usize,
        f: usize,
    ) -> bool {
        let level = &self.levels[level_index];
        if level.is_face_hole(f) || !self.face_is_candidate(level_index, f) {
            return false;
        }
        let needs_isolation = |level: &Level| match self.scheme_type() {
            SchemeType::Catmark => {
                super::patch_table::gather_regular_patch(level, f).is_none()
                    && !(options.use_single_crease_patch
                        && super::patch_table::single_crease_patch(level, f).is_some())
            }
            SchemeType::Bilinear => level.face_vertices(f).len() != 4,
            SchemeType::Loop => super::loop_patch::gather_regular_patch(level, f).is_none(),
        };
        // A channel's value mesh mirrors the geometry's faces, so face `f`
        // is the same face in each.
        let fvar_needs_isolation = || {
            options.consider_fvar_channels
                && self.scheme_type() != SchemeType::Bilinear
                && self.fvar_channels.iter().any(|channel| {
                    !channel.is_linear() && needs_isolation(channel.level(level_index))
                })
        };
        needs_isolation(level) || fvar_needs_isolation()
    }

    /// Was this refiner refined adaptively (`IsAdaptive`)?
    pub fn is_adaptive(&self) -> bool {
        self.adaptive
    }

    /// Is `face` of `level` a *candidate* for patches or further isolation:
    /// the base level entirely, and above it the children of selected
    /// faces (whose neighborhoods are guaranteed complete).
    pub(super) fn face_is_candidate(&self, level: usize, face: usize) -> bool {
        if level == 0 {
            return true;
        }
        let parent = self.refinements[level - 1].child_face_parent_face(face) as usize;
        self.selections[level - 1][parent]
    }

    /// Should the patch table cover single-crease faces with single-crease
    /// patches ([`AdaptiveOptions::use_single_crease_patch`])?
    pub(super) fn uses_single_crease_patch(&self) -> bool {
        self.single_crease_patch
    }

    /// Was `face` of `level` selected for further refinement?
    pub(super) fn face_is_selected(&self, level: usize, face: usize) -> bool {
        level < self.selections.len() && self.selections[level][face]
    }
}

/// Factory constructing a [`TopologyRefiner`] from a
/// [`TopologyDescriptor`]
/// (`Far::TopologyRefinerFactory<TopologyDescriptor>`).
pub struct TopologyRefinerFactory;

impl TopologyRefinerFactory {
    /// Validate the descriptor and instantiate the base level of a
    /// [`TopologyRefiner`] (`TopologyRefinerFactory::Create`).
    pub fn create(
        descriptor: TopologyDescriptor<'_>,
        scheme_type: SchemeType,
        options: sdc::Options,
    ) -> Result<TopologyRefiner, TopologyError> {
        // The Loop scheme is only defined for triangular meshes.
        if scheme_type == SchemeType::Loop {
            for (f, &size) in descriptor.num_verts_per_face.iter().enumerate() {
                if size != 3 {
                    return Err(TopologyError::NonTriangularFaceForLoop { face: f, size });
                }
            }
        }

        let mut level = Level::from_face_vertices(
            descriptor.num_vertices,
            descriptor.num_verts_per_face,
            descriptor.vert_indices_per_face,
        )?;

        // Creases.
        for (pair, &weight) in descriptor
            .crease_vertex_index_pairs
            .iter()
            .zip(descriptor.crease_weights)
        {
            for &v in pair {
                if v as usize >= level.num_vertices() {
                    return Err(TopologyError::InvalidDescriptorIndex {
                        what: "crease vertex",
                        index: v,
                    });
                }
            }
            let edge = level
                .find_edge(pair[0], pair[1])
                .ok_or(TopologyError::CreaseEdgeNotFound { vertices: *pair })?;
            level.set_edge_sharpness(edge as usize, weight);
        }

        // Corners.
        for (&v, &weight) in descriptor
            .corner_vertex_indices
            .iter()
            .zip(descriptor.corner_weights)
        {
            if v as usize >= level.num_vertices() {
                return Err(TopologyError::InvalidDescriptorIndex {
                    what: "corner vertex",
                    index: v,
                });
            }
            level.set_vertex_sharpness(v as usize, weight);
        }

        // Holes.
        for &f in descriptor.hole_indices {
            if f as usize >= level.num_faces() {
                return Err(TopologyError::InvalidDescriptorIndex {
                    what: "hole face",
                    index: f,
                });
            }
            level.set_face_hole(f as usize, true);
        }

        let scheme = Scheme::new(scheme_type, options);
        level.sharpen_boundaries(scheme.crease());

        // Face-varying channels — built after boundary sharpening so the
        // geometry's effective sharpness transfers onto the value meshes.
        let mut fvar_channels = Vec::with_capacity(descriptor.fvar_channels.len());
        for (c, channel) in descriptor.fvar_channels.iter().enumerate() {
            fvar_channels.push(FVarChannel::create(
                &level,
                scheme_type,
                options,
                c,
                channel.num_values,
                channel.value_indices,
            )?);
        }

        Ok(TopologyRefiner {
            scheme,
            options,
            levels: vec![level],
            refinements: Vec::new(),
            fvar_channels,
            adaptive: false,
            selections: Vec::new(),
            single_crease_patch: false,
        })
    }
}