opensubdiv-petite 0.3.1

Wrapper around parts of Pixar’s OpenSubdiv
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
//! Topology refinement.
//!
//! [`TopologyRefiner`] is the building block for many other useful structs in
//! `far`. It performs refinement of an arbitrary mesh and provides access to
//! the refined mesh topology.
//!
//! It can be used for primvar refinement directly
//! through a [`PrimvarRefiner`](super::primvar_refiner::PrimvarRefiner).  Or
//! indirectly by being used to create a
//! [`StencilTable`](super::stencil_table::StencilTable), or a `PatchTable`,
//! etc.
//!
//! `TopologyRefiner` provides these refinement methods:
//! * [`refine_uniform()`](TopologyRefiner::refine_uniform()) – Does uniform
//!   refinenment as specified in the [`UniformRefinementOptions`].
//! * [`refine_adaptive()`](TopologyRefiner::refine_adaptive()) – Does adaptive
//!   refinement as specified in the [`AdaptiveRefinementOptions`].
//!
//! The result can be accessed via:
//! * [`level()`](TopologyRefiner::level()) – Gives access to the refined
//!   topology at through a [`TopologyLevel`] instance.
use opensubdiv_petite_sys as sys;
use std::convert::TryInto;

use crate::far::TopologyDescriptor;
use crate::{Error, Index};
type Result<T, E = Error> = std::result::Result<T, E>;

/// Stores topology data for a specified set of refinement options.
pub struct TopologyRefiner(pub(crate) sys::topology_refiner::TopologyRefinerPtr);

impl TopologyRefiner {
    /// Create a new topology refiner.
    pub fn new(descriptor: TopologyDescriptor, options: TopologyRefinerOptions) -> Result<Self> {
        let sdc_options = sys::sdc::Options {
            _vtxBoundInterp: match options.boundary_interpolation {
                Some(interp) => interp as _,
                None => sys::far::topology_refiner::VTX_BOUNDARY_NONE,
            },
            _fvarLinInterp: match options.face_varying_linear_interpolation {
                Some(interp) => interp as _,
                None => sys::far::topology_refiner::FVAR_LINEAR_NONE,
            },
            _creasingMethod: options.creasing_method as _,
            _triangleSub: options.triangle_subdivision as _,
        };

        let mut sys_options: sys::far::topology_refiner::TopologyRefinerFactoryOptions =
            unsafe { std::mem::zeroed() };
        sys_options.schemeType = options.scheme as _;
        sys_options.schemeOptions = sdc_options;

        #[cfg(feature = "topology_validation")]
        sys_options.set_validateFullTopology(true as _);

        let ptr = unsafe {
            sys::far::topology_refiner::TopologyRefinerFactory_TopologyDescriptor_Create(
                &descriptor.descriptor as _,
                sys_options,
            )
        };

        if ptr.is_null() {
            Err(Error::CreateTopologyRefinerFailed)
        } else {
            Ok(Self(ptr))
        }
    }

    /// Returns the subdivision options.
    #[inline]
    pub fn options(&self) -> TopologyRefinerOptions {
        let options = unsafe { &(*self.0)._subdivOptions };
        TopologyRefinerOptions {
            scheme: unsafe { (*self.0)._subdivType }
                .try_into()
                .expect("invalid subdivision scheme from C++"),
            boundary_interpolation: if options._vtxBoundInterp
                == sys::far::topology_refiner::VTX_BOUNDARY_NONE
            {
                None
            } else {
                Some(
                    options
                        ._vtxBoundInterp
                        .try_into()
                        .expect("invalid boundary interpolation from C++"),
                )
            },
            face_varying_linear_interpolation: if options._fvarLinInterp
                == sys::far::topology_refiner::FVAR_LINEAR_NONE
            {
                None
            } else {
                Some(
                    options
                        ._fvarLinInterp
                        .try_into()
                        .expect("invalid face-varying interpolation from C++"),
                )
            },
            creasing_method: options
                ._creasingMethod
                .try_into()
                .expect("invalid creasing method from C++"),
            triangle_subdivision: options
                ._triangleSub
                .try_into()
                .expect("invalid triangle subdivision from C++"),
        }
    }

    /// Returns true if uniform refinement has been applied.
    #[inline]
    pub fn is_uniform(&self) -> bool {
        unsafe { (*self.0)._isUniform() != 0 }
    }

    /// Returns the number of refinement levels.
    #[inline]
    pub fn refinement_levels(&self) -> usize {
        unsafe { sys::far::topology_refiner::TopologyRefiner_GetNumLevels(self.0) as _ }
    }

    /// Returns the maximum vertex valence in all levels
    #[inline]
    pub fn max_valence(&self) -> usize {
        unsafe { (*self.0)._maxValence as _ }
    }

    /// Returns `true` if faces have been tagged as holes.
    #[inline]
    pub fn has_holes(&self) -> bool {
        unsafe { (*self.0)._hasHoles() != 0 }
    }

    /// Returns the total number of vertices in all levels.
    #[inline]
    pub fn vertex_count_all_levels(&self) -> usize {
        unsafe { sys::far::topology_refiner::TopologyRefiner_GetNumVerticesTotal(self.0) as _ }
    }

    /// Returns the total number of vertices in all levels.
    #[deprecated(since = "0.3.0", note = "Use `vertex_count_all_levels` instead")]
    #[inline]
    pub fn vertex_total_count(&self) -> usize {
        self.vertex_count_all_levels()
    }

    /// Returns the total number of vertices in all levels.
    #[deprecated(since = "0.3.0", note = "Use `vertex_count_all_levels` instead")]
    #[inline]
    pub fn vertices_total_len(&self) -> usize {
        self.vertex_count_all_levels()
    }

    /// Returns the total number of edges in all levels.
    #[inline]
    pub fn edge_count_all_levels(&self) -> usize {
        unsafe { sys::far::topology_refiner::TopologyRefiner_GetNumEdgesTotal(self.0) as _ }
    }

    /// Returns the total number of edges in all levels.
    #[deprecated(since = "0.3.0", note = "Use `edge_count_all_levels` instead")]
    #[inline]
    pub fn edge_total_count(&self) -> usize {
        self.edge_count_all_levels()
    }

    /// Returns the total number of edges in all levels.
    #[deprecated(since = "0.3.0", note = "Use `edge_count_all_levels` instead")]
    #[inline]
    pub fn edges_total_len(&self) -> usize {
        self.edge_count_all_levels()
    }

    /// Returns the total number of faces in all levels.
    #[inline]
    pub fn face_count_all_levels(&self) -> usize {
        unsafe { sys::far::topology_refiner::TopologyRefiner_GetNumFacesTotal(self.0) as _ }
    }

    /// Returns the total number of faces in all levels.
    #[deprecated(since = "0.3.0", note = "Use `face_count_all_levels` instead")]
    #[inline]
    pub fn face_total_count(&self) -> usize {
        self.face_count_all_levels()
    }

    /// Returns the total number of faces in all levels.
    #[deprecated(since = "0.3.0", note = "Use `face_count_all_levels` instead")]
    #[inline]
    pub fn faces_total_len(&self) -> usize {
        self.face_count_all_levels()
    }

    /// Returns the total number of face vertices in all levels.
    #[inline]
    pub fn face_vertex_count_all_levels(&self) -> usize {
        unsafe { sys::far::topology_refiner::TopologyRefiner_GetNumFaceVerticesTotal(self.0) as _ }
    }

    /// Returns the total number of face vertices in all levels.
    #[deprecated(since = "0.3.0", note = "Use `face_vertex_count_all_levels` instead")]
    #[inline]
    pub fn face_vertex_total_count(&self) -> usize {
        self.face_vertex_count_all_levels()
    }

    /// Returns the total number of face vertices in all levels.
    #[deprecated(since = "0.3.0", note = "Use `face_vertex_count_all_levels` instead")]
    #[inline]
    pub fn face_vertices_total_len(&self) -> usize {
        self.face_vertex_count_all_levels()
    }

    /// Returns the highest level of refinement.
    #[inline]
    pub fn max_level(&self) -> usize {
        unsafe { (*self.0)._maxLevel() as _ }
    }

    /// Returns a handle to access data specific to a particular refinement
    /// level.
    #[inline]
    pub fn level(&self, level: usize) -> Option<TopologyLevel<'_>> {
        if level > self.max_level() {
            None
        } else {
            let ptr = unsafe {
                sys::far::topology_refiner::TopologyRefiner_GetLevel(
                    self.0,
                    level.min(i32::MAX as usize) as i32,
                )
            };
            if ptr.is_null() {
                None
            } else {
                Some(TopologyLevel {
                    ptr,
                    refiner: std::marker::PhantomData,
                })
            }
        }
    }

    /// Refine the topology uniformly.
    ///
    /// This method applies uniform refinement to the level specified in the
    /// given [`UniformRefinementOptions`]s.
    ///
    /// # Arguments
    ///
    /// * `options` - Options controlling uniform refinement.
    #[inline]
    pub fn refine_uniform(&mut self, options: UniformRefinementOptions) {
        let mut sys_options: sys::far::topology_refiner::UniformRefinementOptions =
            unsafe { std::mem::zeroed() };

        sys_options._bitfield_1 =
            sys::far::topology_refiner::UniformRefinementOptions::new_bitfield_1(
                options.refinement_level.min(u32::MAX as usize) as u32,
                options.order_vertices_from_faces_first as _,
                options.full_topology_in_last_level as _,
            );

        unsafe {
            (*self.0).RefineUniform(sys_options);
        }
    }

    /// Refine the topology adaptively.
    ///
    /// This method applies uniform refinement to the level specified in the
    /// given [`AdaptiveRefinementOptions`]s.
    ///
    /// # Arguments
    ///
    /// * `options` - Options controlling adaptive refinement.
    /// * `selected_faces` - Indices of faces to refine adaptively.
    #[inline]
    pub fn refine_adaptive(
        &mut self,
        options: AdaptiveRefinementOptions,
        selected_faces: &[Index],
    ) {
        let mut sys_options: sys::far::topology_refiner::AdaptiveRefinementOptions =
            unsafe { std::mem::zeroed() };

        sys_options._bitfield_1 =
            sys::far::topology_refiner::AdaptiveRefinementOptions::new_bitfield_1(
                options.isolation_level.min(u32::MAX as usize) as u32,
                options.secondary_level.min(u32::MAX as usize) as u32,
                options.single_crease_patch as _,
                options.infintely_sharp_patch as _,
                options.consider_face_varying_channels as _,
                options.order_vertices_from_faces_first as _,
            );

        let const_array = sys::topology_refiner::ConstIndexArray {
            _begin: selected_faces.as_ptr() as _,
            _size: selected_faces.len().min(i32::MAX as usize) as i32,
            _phantom_0: std::marker::PhantomData,
        };

        unsafe {
            (*self.0).RefineAdaptive(sys_options, const_array);
        }
    }

    /// Unrefine the topology, keeping only the base level.
    #[inline]
    pub fn unrefine(&mut self) {
        unsafe {
            (*self.0).Unrefine();
        }
    }

    pub(crate) fn as_ptr(&self) -> sys::topology_refiner::TopologyRefinerPtr {
        self.0
    }
}

impl Drop for TopologyRefiner {
    #[inline]
    fn drop(&mut self) {
        unsafe {
            sys::far::topology_refiner::TopologyRefiner_destroy(self.0);
        }
    }
}

pub use sys::far::topology_refiner::{
    BoundaryInterpolation, CreasingMethod, FaceVaryingLinearInterpolation, Scheme,
    TriangleSubdivision,
};

use super::topology_level::TopologyLevel;

/// All supported options applying to a subdivision scheme.
///
/// This contains all supported options that can be applied to a subdivision
/// [`Scheme`] to affect the shape of the limit surface. These differ
/// from approximations that may be applied at a higher level -- options to
/// limit the level of feature adaptive subdivision, options to ignore
/// fractional creasing, or creasing entirely, etc. These options define the
/// shape of a particular limit surface, including the shape of primitive
/// variable data associated with it.
///
/// The intent is that these sets of options be defined at a high level and
/// propagated into the lowest-level computation in support of each subdivision
/// scheme. Ideally it remains a set of bit-fields (essentially an int) and so
/// remains light weight and easily passed around by value.
///
/// # Examples
///
/// ```
/// use opensubdiv_petite::far::{
///     BoundaryInterpolation, CreasingMethod, FaceVaryingLinearInterpolation, Scheme,
///     TopologyRefinerOptions, TriangleSubdivision,
/// };
///
/// // Create options with defaults
/// let options = TopologyRefinerOptions::default();
///
/// // Create custom options
/// let custom_options = TopologyRefinerOptions {
///     scheme: Scheme::CatmullClark,
///     boundary_interpolation: Some(BoundaryInterpolation::EdgeOnly),
///     face_varying_linear_interpolation: None, // No interpolation
///     creasing_method: CreasingMethod::Chaikin,
///     triangle_subdivision: TriangleSubdivision::Smooth,
/// };
/// ```
#[derive(Copy, Clone, Debug)]
pub struct TopologyRefinerOptions {
    pub scheme: Scheme,
    pub boundary_interpolation: Option<BoundaryInterpolation>,
    pub face_varying_linear_interpolation: Option<FaceVaryingLinearInterpolation>,
    pub creasing_method: CreasingMethod,
    pub triangle_subdivision: TriangleSubdivision,
}

impl Default for TopologyRefinerOptions {
    /// Create options with the following defaults:
    ///
    /// | Property                            | Value                                                |
    /// |-------------------------------------|------------------------------------------------------|
    /// | `scheme`                            | [`CatmullClark`](Scheme::CatmullClark)              |
    /// | `boundary_interpolation`            | `None`                                               |
    /// | `face_varying_linear_interpolation` | `Some(`[`All`](FaceVaryingLinearInterpolation::All)`)` |
    /// | `creasing_method`                   | [`Uniform`](CreasingMethod::Uniform)                |
    /// | `triangle_subdivision`              | [`CatmullClark`](TriangleSubdivision::CatmullClark) |
    fn default() -> Self {
        Self {
            scheme: Scheme::CatmullClark,
            boundary_interpolation: None,
            face_varying_linear_interpolation: Some(FaceVaryingLinearInterpolation::All),
            creasing_method: CreasingMethod::Uniform,
            triangle_subdivision: TriangleSubdivision::CatmullClark,
        }
    }
}

/// Uniform topology refinement options.
#[repr(C)]
#[derive(Copy, Clone, Debug)]
pub struct UniformRefinementOptions {
    pub refinement_level: usize,
    pub order_vertices_from_faces_first: bool,
    pub full_topology_in_last_level: bool,
}

impl Default for UniformRefinementOptions {
    /// Create uniform refinement options with the following defaults:
    ///
    /// | Property                          | Value   |
    /// |----------------                 --|---------|
    /// | `refinement_level`                | `4`     |
    /// | `order_vertices_from_faces_first` | `true`  |
    /// | `full_topology_in_last_level`     | `true`  |
    fn default() -> Self {
        Self {
            refinement_level: 4,
            order_vertices_from_faces_first: true,
            full_topology_in_last_level: true,
        }
    }
}

/// Adaptive topology refinement options.
#[derive(Copy, Clone, Debug)]
pub struct AdaptiveRefinementOptions {
    pub isolation_level: usize,
    pub secondary_level: usize,
    pub single_crease_patch: bool,
    pub infintely_sharp_patch: bool,
    pub consider_face_varying_channels: bool,
    pub order_vertices_from_faces_first: bool,
}

impl Default for AdaptiveRefinementOptions {
    /// Create adaptive refinement options with the following defaults:
    ///
    /// | Property                          | Value   |
    /// |-----------------------------------|---------|
    /// | `isolation_level`                 | `4`     |
    /// | `secondary_level`                 | `15`    |
    /// | `single_crease_patch`             | `false` |
    /// | `infintely_sharp_patch`           | `false` |
    /// | `consider_face_varying_channels`  | `false` |
    /// | `order_vertices_from_faces_first` | `false` |
    fn default() -> Self {
        Self {
            isolation_level: 4,
            secondary_level: 15,
            single_crease_patch: false,
            infintely_sharp_patch: false,
            consider_face_varying_channels: false,
            order_vertices_from_faces_first: false,
        }
    }
}