Skip to content

ordito.repair

Removing what should not be in a mesh: redundant elements, bad triangles and inconsistent winding.

make_solid is the composite most callers want -- a broken digitised surface in, a single watertight solid out -- and everything below is a stage of it that is also useful on its own.

Five defects are visible in the index buffer alone, and each has a remover: remove_unreferenced_vertices, remove_duplicated_vertices, resolve_duplicated_faces, remove_degenerate_faces, and collapse_small_triangles.

A sixth remover answers a different question -- not which elements are wrong but which parts of the mesh are not the mesh: remove_small_components drops face-connected components that are too small, by face count, area or bounding-box diameter. It is the first step of every repair pipeline, and the debris it removes is not defective in itself.

Two further defects need geometry rather than topology to detect, so they are found by a threshold rather than a rule: validation.face_defective_mask flags faces that are too thin, misoriented against their neighbourhood, or folded back over it. remove_folded_faces deletes the folded ones and flip_t_vertices flips away the slivers a T-junction leaves behind.

The verb predicts the return shape, and that is a rule rather than a coincidence:

  • remove_* / collapse_* change the element count, so they return (vertices, faces) or more -- there is a new position buffer because vertices went away or moved.
  • make_* preserve positions and counts and rewrite only the index buffer, so they return faces alone -- unless the name is a whole-mesh outcome rather than a property of the index buffer, which is make_solid alone. It is the composite of most of this module and returns (vertices, faces) like the removers it runs; the three property-fixers beside it (make_winding_consistent, make_volume, make_normals_outward) return faces.
  • reverse_winding is the one verb outside that scheme and obeys the same shape rule for the same reason: it rewrites only the index buffer, so it returns faces. It is not a make_* because it establishes no property -- it flips orientation unconditionally, where the three make_* fixers decide face by face.
  • A verb that only moves vertices returns the positions alone, since neither buffer of indices changes: flatten_degree3_vertices is the only one, and it is here rather than in ordito.smoothing -- whose every member has that same signature -- because it is the gentler half of a pair with remove_degree3_vertices: same defect, same test, one answering it by deleting the vertex and one by flattening the bump.
  • *_mask are detectors: they return a wp.array[wp.bool] and mutate nothing; they live in ordito.validation.

flip_t_vertices is named for the make_* pattern rather than the remove_* one because it removes nothing: it flips the long edge of each sliver a T-junction leaves, so the face count is unchanged and only faces comes back. straighten_boundary is the same shape under a geometric verb.

Functions:

Name Description
make_solid

Turn a broken digitised surface into a single watertight solid.

remove_unreferenced_vertices

Remove vertices not referenced by any face and remap face indices.

remove_duplicated_vertices

Merge duplicate vertex positions up to a coordinate tolerance and remap face indices.

duplicate_vertex_inverse

Map each vertex to the slot of its coincident-vertex equivalence class.

split_vertices_by_corner_values

Split each vertex into one copy per distinct value its corners carry.

resolve_duplicated_faces

Resolve duplicated triangles, by default cancelling oppositely wound copies.

remove_degenerate_faces

Drop degenerate (zero-area) triangles and reindex, keeping vertex positions unchanged.

remove_non_manifold_faces

Remove faces touching a non-manifold (>2-incident) edge, leaving the mesh edge-manifold.

remove_degenerate_and_non_manifold_faces

Drop degenerate faces, then faces on a non-manifold edge, compacting the vertices once.

remove_small_components

Drop face-connected components that are too small, by one of four measures of "small".

split_non_manifold_vertices

Make a mesh manifold and orientable by duplicating vertices, keeping every face.

collapse_small_triangles

Collapse triangles smaller than a bounding-box-relative area threshold.

fix_degeneracies

Remove needle and cap triangles and tiny edges by local flips and collapses around them.

straighten_boundary

Close concave notches in the mesh's rim, one triangle at a time.

remove_degree3_vertices

Remove interior vertices with exactly three incident faces, collapsing each fan to one triangle.

flatten_degree3_vertices

Flatten each interior valence-3 vertex into the plane of its three neighbours.

reverse_winding

Reverse every face's winding, flipping the surface's orientation.

make_winding_consistent

Flip faces so every shared edge is traversed in opposite directions by its two faces.

make_volume

Orient faces so the mesh encloses a positive signed volume (normals point outward).

make_normals_outward

Make winding consistent and orient normals outward (winding fix followed by inversion fix).

remove_folded_faces

Drop faces that fold back over their own ring, and reindex.

fix_self_intersections

Remove a mesh's self-intersections, either locally or by rebuilding it.

remove_tunnels

Remove thin handles by cutting along their short tunnel loops and sealing the two rims.

flip_t_vertices

Repair T-vertices by flipping the long edge of each sliver they create.

make_solid

make_solid(
    vertices: array[vec3],
    faces: array[int32],
    *,
    keep_largest: bool = True,
    join_components: bool = False,
    max_iter: int = 10,
    inner_iter: int = 3,
    return_provenance: Literal[False] = False,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32]]
make_solid(
    vertices: array[vec3],
    faces: array[int32],
    *,
    keep_largest: bool = True,
    join_components: bool = False,
    max_iter: int = 10,
    inner_iter: int = 3,
    return_provenance: Literal[True],
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    od.interpolation.Provenance,
]
make_solid(
    vertices: array[vec3],
    faces: array[int32],
    *,
    keep_largest: bool = True,
    join_components: bool = False,
    max_iter: int = 10,
    inner_iter: int = 3,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        od.interpolation.Provenance,
    ]
)

Turn a broken digitised surface into a single watertight solid.

The composite this module's pieces exist to make possible: debris removed, holes closed, degeneracies collapsed and self-intersections cut out and refilled, alternating until nothing is left to fix. Every stage is a public function here or in ordito.holes; what this adds is the order and the loop, which is where the difficulty actually is -- closing a hole can create a self-intersection, and cutting one out reopens a hole.

The stages, in order:

  1. The connectivity repair that does not look like a stage at all until it is missing: remove_unreferenced_vertices, make_winding_consistent and split_non_manifold_vertices. Without it a mesh whose defect is a non-manifold edge comes back with the right Euler characteristic and one component and is still not watertight, because no later stage looks at edge manifoldness.
  2. keep_largest -> remove_small_components, so the scan debris goes before anything expensive runs on it.
  3. join_components -> holes.join_closest_components, for an input whose pieces are meant to be one surface rather than a largest piece plus rubbish. Mutually useful with keep_largest rather than exclusive: keep the big piece and weld what is left.
  4. holes.fill_min_weight if any boundary remains.
  5. Up to max_iter rounds of remove_degenerate_faces and collapse_small_triangles, then fix_self_intersections at max_iter=inner_iter. The loop exits as soon as a round changes nothing.
  6. A final fill if stage 4 reopened a boundary -- which it routinely does, since cutting an intersecting region out is what opens one. Nothing geometric runs after it, and that is not an omission: filling a 3-vertex rim produces one sliver, a degeneracy pass deletes the sliver and reopens the rim, and the two trade the same faces indefinitely.

Under keep_largest the component filter runs inside stage 4 as well as at the top, and that is not belt and braces: cutting an intersecting band out can disconnect the surface, so the extra piece does not exist yet when stage 1 looks.

It returns the best it managed, not a guarantee

There is no success flag, deliberately. Convergence is not guaranteed for any input -- a patch can intersect something, and its repair can open another hole -- so on a stubborn mesh this returns a partly repaired surface rather than looping harder or raising. Ask validation.is_watertight if the answer matters.

join_components is where that bites in practice: welding several shells leaves one rim spanning all of them, and if that rim is badly non-planar the minimum-weight patch across it self-intersects, so stage 4 cuts the patch out and undoes the join. Hemispherical bowls joined at coplanar rims converge to one solid; the same bowls tilted relative to each other come back as separate shells. Rims far from coplanar want holes.stitch_loops or a per-pair holes.bridge_edges followed by a targeted fill, not this.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
keep_largest bool

Drop every connected component but the one with the most faces, first.

True
join_components bool

Bridge the remaining open components together instead of leaving them separate.

False
max_iter int

Cap on the alternating degeneracy / self-intersection rounds.

10
inner_iter int

Cap on the cut-and-refill passes inside each self-intersection repair.

3
return_provenance bool

If True, also return the Provenance that carries any per-vertex or per-face field onto the result.

False

Returns:

Name Type Description
new_vertices array[vec3]

(n_new_vertices,) positions of the repaired mesh, on vertices.device.

new_faces array[int32]

(3 * n_new_faces,) flat face buffer of the repaired mesh.

provenance Provenance

Only when return_provenance is True: every stage's provenance chained. A vertex the vertex split copies, a component filter or collapse keeps, names its input vertex; a patch vertex a refill inserts interpolates the rim vertices it was placed between; a face names the input face it is or was cut from, and a fill, join or refill patch face has no source (-1).

Raises:

Type Description
ValueError

If max_iter or inner_iter is negative, or if a face references a vertex index vertices does not cover.

RuntimeError

If vertices and faces are not all on one device.

See Also

validation.is_watertight The question this does not answer for you. remove_small_components fix_self_intersections holes.fill_min_weight make_normals_outward What to run afterwards if the winding has to face outward as well as be consistent.

Examples:

An icosphere with three faces missing and a speck of debris beside it comes back as one closed sphere:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
debris_vertices, debris_faces = od.creation.tetrahedron()
broken_vertices = wp.array(
    np.concatenate([vertices.numpy(), 0.1 * debris_vertices.numpy() + 3.0]), dtype=wp.vec3
)
broken_faces = wp.array(
    np.concatenate([faces.numpy()[9:], debris_faces.numpy() + vertices.shape[0]]),
    dtype=wp.int32,
)
print(od.validation.is_watertight(broken_vertices, broken_faces))  # False
print(len(od.boundary.boundary_loops(broken_vertices, broken_faces)))  # 3
solid_vertices, solid_faces = od.repair.make_solid(broken_vertices, broken_faces)
print(od.validation.is_watertight(solid_vertices, solid_faces))  # True
print(od.measures.euler_characteristic(solid_faces))  # 2
Source code in ordito/repair.py
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
def make_solid(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    keep_largest: bool = True,
    join_components: bool = False,
    max_iter: int = 10,
    inner_iter: int = 3,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], od.interpolation.Provenance]
):
    """
    Turn a broken digitised surface into a single watertight solid.

    The composite this module's pieces exist to make possible: debris removed, holes closed,
    degeneracies collapsed and self-intersections cut out and refilled, alternating until nothing is
    left to fix. Every stage is a public function here or in [`ordito.holes`][ordito.holes]; what
    this adds is the order and the loop, which is where the difficulty actually is -- closing a hole
    can create a self-intersection, and cutting one out reopens a hole.

    The stages, in order:

    0. The connectivity repair that does not look like a stage at all until it is missing:
       [`remove_unreferenced_vertices`][ordito.repair.remove_unreferenced_vertices],
       [`make_winding_consistent`][ordito.repair.make_winding_consistent] and
       [`split_non_manifold_vertices`][ordito.repair.split_non_manifold_vertices]. Without it a
       mesh whose defect is a non-manifold *edge* comes back with the right Euler characteristic and
       one component and is still not watertight, because no later stage looks at edge manifoldness.
    1. ``keep_largest`` -> [`remove_small_components`][ordito.repair.remove_small_components], so
       the scan debris goes before anything expensive runs on it.
    2. ``join_components`` ->
       [`holes.join_closest_components`][ordito.holes.join_closest_components], for an input
       whose pieces are meant to be one surface rather than a largest piece plus rubbish. Mutually
       useful with ``keep_largest`` rather than exclusive: keep the big piece *and* weld what is
       left.
    3. [`holes.fill_min_weight`][ordito.holes.fill_min_weight] if any boundary remains.
    4. Up to ``max_iter`` rounds of
       [`remove_degenerate_faces`][ordito.repair.remove_degenerate_faces] and
       [`collapse_small_triangles`][ordito.repair.collapse_small_triangles], then
       [`fix_self_intersections`][ordito.repair.fix_self_intersections] at ``max_iter=inner_iter``.
       The loop exits as soon as a round changes nothing.
    5. A final fill if stage 4 reopened a boundary -- which it routinely does, since cutting an
       intersecting region out is what opens one. Nothing geometric runs after it, and that is not
       an omission: filling a 3-vertex rim produces one sliver, a degeneracy pass deletes the sliver
       and reopens the rim, and the two trade the same faces indefinitely.

    Under ``keep_largest`` the component filter runs **inside** stage 4 as well as at the top, and
    that is not belt and braces: cutting an intersecting band out can disconnect the surface, so the
    extra piece does not exist yet when stage 1 looks.

    !!! warning "It returns the best it managed, not a guarantee"
        There is no success flag, deliberately. Convergence is not guaranteed for any input -- a
        patch can intersect something, and its repair can open another hole -- so on a stubborn mesh
        this returns a *partly* repaired surface rather than looping harder or raising. Ask
        [`validation.is_watertight`][ordito.validation.is_watertight] if the answer matters.

        ``join_components`` is where that bites in practice: welding several shells leaves **one**
        rim spanning all of them, and if that rim is badly non-planar the minimum-weight patch
        across it self-intersects, so stage 4 cuts the patch out and undoes the join. Hemispherical
        bowls joined at coplanar rims converge to one solid; the same bowls tilted relative to each
        other come back as separate shells. Rims far from coplanar want
        [`holes.stitch_loops`][ordito.holes.stitch_loops] or a per-pair
        [`holes.bridge_edges`][ordito.holes.bridge_edges] followed by a targeted fill, not this.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    keep_largest
        Drop every connected component but the one with the most faces, first.
    join_components
        Bridge the remaining open components together instead of leaving them separate.
    max_iter
        Cap on the alternating degeneracy / self-intersection rounds.
    inner_iter
        Cap on the cut-and-refill passes inside each self-intersection repair.
    return_provenance
        If ``True``, also return the [`Provenance`][ordito.interpolation.Provenance] that carries
        any per-vertex or per-face field onto the result.

    Returns
    -------
    new_vertices : wp.array[wp.vec3]
        ``(n_new_vertices,)`` positions of the repaired mesh, on ``vertices.device``.
    new_faces : wp.array[wp.int32]
        ``(3 * n_new_faces,)`` flat face buffer of the repaired mesh.
    provenance : Provenance
        Only when ``return_provenance`` is ``True``: every stage's provenance chained. A vertex
        the vertex split copies, a component filter or collapse keeps, names its input vertex; a
        patch vertex a refill inserts interpolates the rim vertices it was placed between; a face
        names the input face it is or was cut from, and a fill, join or refill patch face has no
        source (``-1``).

    Raises
    ------
    ValueError
        If ``max_iter`` or ``inner_iter`` is negative, or if a face references a vertex index
        ``vertices`` does not cover.
    RuntimeError
        If ``vertices`` and ``faces`` are not all on one device.

    See Also
    --------
    [`validation.is_watertight`][ordito.validation.is_watertight]
        The question this does not answer for you.
    [`remove_small_components`][ordito.repair.remove_small_components]
    [`fix_self_intersections`][ordito.repair.fix_self_intersections]
    [`holes.fill_min_weight`][ordito.holes.fill_min_weight]
    [`make_normals_outward`][ordito.repair.make_normals_outward]
        What to run afterwards if the winding has to face outward as well as be consistent.

    Examples
    --------
    An icosphere with three faces missing and a speck of debris beside it comes back as one
    closed sphere:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    debris_vertices, debris_faces = od.creation.tetrahedron()
    broken_vertices = wp.array(
        np.concatenate([vertices.numpy(), 0.1 * debris_vertices.numpy() + 3.0]), dtype=wp.vec3
    )
    broken_faces = wp.array(
        np.concatenate([faces.numpy()[9:], debris_faces.numpy() + vertices.shape[0]]),
        dtype=wp.int32,
    )
    print(od.validation.is_watertight(broken_vertices, broken_faces))  # False
    print(len(od.boundary.boundary_loops(broken_vertices, broken_faces)))  # 3
    solid_vertices, solid_faces = od.repair.make_solid(broken_vertices, broken_faces)
    print(od.validation.is_watertight(solid_vertices, solid_faces))  # True
    print(od.measures.euler_characteristic(solid_faces))  # 2
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    if max_iter < 0 or inner_iter < 0:
        raise ValueError(
            f"max_iter and inner_iter must be non-negative, got {max_iter}, {inner_iter}"
        )

    if faces.size == 0:
        return _unchanged(vertices, faces, return_provenance)

    # This is the trust boundary for "a broken digitised surface": every stage below indexes
    # ``vertices[faces]`` without a bound check, the same way every other per-face kernel wrapper in
    # this package does, so an out-of-range index arriving here would otherwise reach the first one
    # silently rather than raising a Python exception.
    require_valid_faces(faces, vertices.size, "make_solid")

    # Stage 0. The reference does this inside its *loader*, which is why it is easy to leave out and
    # why leaving it out is dangerous: skipping it can leave a mesh at the right Euler
    # characteristic and one component while still **not watertight**, because nothing downstream
    # addresses a non-manifold edge.
    # ``make_winding_consistent`` then ``split_non_manifold_vertices`` over one pairing of the
    # halfedges: the flip carries the mates over to the wound faces, which the split reads. The
    # split keeps only the vertices a face names, so it is the unreferenced-vertex removal too: the
    # pairing and the winding read vertex indices only for equality, and the split numbers its
    # vertices by corner, so a compaction first would change nothing it returns. It also turns
    # the mates into twins, which pair the split faces into their components without a pairing of
    # their own for the component filter.
    n_input_vertices, n_input_faces = vertices.size, faces.size // 3
    wound, twins = _wound_with_mates(faces, vertices.size)
    vertices, faces, source = _split_corners(vertices, wound, twins, twins)
    # Each stage's provenance when one is asked for, chained at the end: the winding keeps every
    # face where it was and the split copies each vertex from ``source``.
    steps: list[od.interpolation.Provenance] | None = None
    if return_provenance:
        steps = [
            od.interpolation.Provenance(
                source,
                od.array.arange(n_input_faces, device=faces.device),
                None,
                n_input_vertices,
                n_input_faces,
            )
        ]

    # Every stage below is a deterministic function of the mesh it is handed, and ``version`` counts
    # the changes made to the mesh, so a stage is skipped while the mesh is still one it is known
    # to leave alone: the output of the last run of an idempotent stage (degeneracy removal, the
    # collapse to a fixpoint, the largest-component filter), or a mesh the cut-and-refill found
    # nothing to cut in. Each stage reports a change exactly: the removers only drop faces and
    # compact the vertices those keep, so equal counts are an identical mesh; the fill only adds
    # faces; the cut-and-refill returns its own input when it cuts nothing.
    version = 0
    clean_after = {"degenerate": -1, "collapse": -1, "cut": -1, "components": -1}

    def counts() -> tuple[int, int]:
        return vertices.size, faces.size

    if keep_largest:
        vertices, faces, kept = _remove_small_components(
            vertices, faces, mates=twins, with_provenance=steps is not None
        )
        if steps is not None:
            assert kept is not None
            steps.append(kept)
        clean_after["components"] = version
    if join_components:
        if steps is not None:
            faces, joined = od.holes.join_closest_components(
                vertices, faces, return_provenance=True
            )
            steps.append(joined)
        else:
            faces = od.holes.join_closest_components(vertices, faces)
        version += 1

    # The fill finds the rims itself and returns the faces unchanged (a copy) when there is none, so
    # no separate boundary test runs first.
    before = counts()
    # A component filter has compacted the faces, so their indices are below the vertex count by
    # construction and the fill needs no reduction to bound them; the caller's own faces keep it,
    # as the guard against a negative index.
    if steps is not None:
        faces, filled = od.holes.fill_min_weight(
            vertices,
            faces,
            n_vertices=vertices.size if keep_largest else None,
            return_provenance=True,
        )
        steps.append(filled)
    else:
        faces = od.holes.fill_min_weight(
            vertices, faces, n_vertices=vertices.size if keep_largest else None
        )
    version += int(counts() != before)
    for _ in range(max_iter):
        n_faces_before = faces.size
        for name, remover in (
            ("degenerate", remove_degenerate_faces),
            ("collapse", collapse_small_triangles),
        ):
            if clean_after[name] != version:
                before = counts()
                if steps is not None:
                    vertices, faces, removed = remover(vertices, faces, return_provenance=True)
                    steps.append(removed)
                else:
                    vertices, faces = remover(vertices, faces)
                version += int(counts() != before)
                clean_after[name] = version
        # The collapse runs on the degeneracy pass's output and keeps only faces passing the same
        # test (its remap applies the predicate on the positions it keeps), so what it returns is
        # also a mesh that pass leaves alone.
        if clean_after["collapse"] == version:
            clean_after["degenerate"] = version
        if clean_after["cut"] != version:
            uncut = faces
            vertices, faces = _cut_and_refill(vertices, faces, 1, inner_iter, steps)
            if faces is uncut:
                clean_after["cut"] = version
            else:
                version += 1
        # Cutting an intersecting band out can *disconnect* the surface, so the component filter has
        # to run again here and not only at the top: a single pass at the start cannot see a
        # component that did not exist yet.
        if keep_largest and clean_after["components"] != version:
            before = counts()
            vertices, faces = _largest_component(vertices, faces, steps)
            if counts() != before:
                # A subset of the faces on the same positions: what the three stages above found
                # nothing to do in still holds nothing for them (no degenerate face, none below the
                # collapse's threshold, which a smaller box only lowers, no crossing pair).
                for name in ("degenerate", "collapse", "cut"):
                    if clean_after[name] == version:
                        clean_after[name] = version + 1
                version += 1
            clean_after["components"] = version
        if faces.size == n_faces_before:
            break

    # Stage 4 opens a rim whenever it cuts an intersecting region out, so the last fill is not a
    # belt-and-braces repeat of stage 3 -- it is what makes the common case come back closed. And
    # nothing geometric may run *after* it: filling a small rim produces one sliver, degeneracy
    # removal deletes that sliver and reopens the rim, and the two then trade the same faces
    # forever -- so the fill goes last.
    before = counts()
    # The faces here are a compacting stage's output, or else the ones the first fill left: it
    # range-checked them whenever it filled a rim, and with none filled there is none here to fill.
    # Either way the bound is the vertex count.
    if steps is not None:
        faces, filled = od.holes.fill_min_weight(
            vertices, faces, n_vertices=vertices.size, return_provenance=True
        )
        steps.append(filled)
    else:
        faces = od.holes.fill_min_weight(vertices, faces, n_vertices=vertices.size)
    version += int(counts() != before)
    if keep_largest and clean_after["components"] != version:
        vertices, faces = _largest_component(vertices, faces, steps)
    if steps is None:
        return vertices, faces
    provenance = _chained_steps(steps, n_input_vertices, n_input_faces, vertices.device)
    return vertices, faces, provenance

remove_unreferenced_vertices

remove_unreferenced_vertices(
    vertices: array[vec3],
    faces: array[int32],
    *,
    return_provenance: Literal[False] = False,
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    wp.array[wp.int32],
]
remove_unreferenced_vertices(
    vertices: array[vec3],
    faces: array[int32],
    *,
    return_provenance: Literal[True],
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    wp.array[wp.int32],
    od.interpolation.Provenance,
]
remove_unreferenced_vertices(
    vertices: array[vec3],
    faces: array[int32],
    *,
    return_provenance: bool = False,
) -> (
    tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        wp.array[wp.int32],
    ]
    | tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        wp.array[wp.int32],
        od.interpolation.Provenance,
    ]
)

Remove vertices not referenced by any face and remap face indices.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
return_provenance bool

If True, also return the Provenance that carries any per-vertex or per-face field onto the result.

False

Returns:

Name Type Description
new_vertices array[vec3]

(n_referenced,) referenced vertices only, compacted from index zero.

new_faces array[int32]

(3 * n_faces,) face buffer with indices remapped into new_vertices.

remap array[int32]

(n_vertices,) old-to-new map (-1 when unreferenced).

provenance Provenance

Only when return_provenance is True: each output vertex is a copy of the input vertex its vertex_index names (the new-to-old map), and every face keeps its index.

Raises:

Type Description
RuntimeError

If vertices and faces are not all on one device.

Examples:

A stray vertex no face uses is dropped and maps to -1:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.box()
padded = wp.array(np.vstack([vertices.numpy(), [5.0, 5.0, 5.0]]), dtype=wp.vec3)
new_vertices, new_faces, remap = od.repair.remove_unreferenced_vertices(padded, faces)
print(padded.shape, new_vertices.shape)  # (9,) (8,)
print(remap.numpy().tolist())  # [0, 1, 2, 3, 4, 5, 6, 7, -1]
_, _, _, provenance = od.repair.remove_unreferenced_vertices(
    padded, faces, return_provenance=True
)
print(provenance.vertex_index.numpy().tolist())  # [0, 1, 2, 3, 4, 5, 6, 7]
Source code in ordito/repair.py
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
def remove_unreferenced_vertices(
    vertices: wp.array[wp.vec3], faces: wp.array[wp.int32], *, return_provenance: bool = False
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32], wp.array[wp.int32]]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], wp.array[wp.int32], od.interpolation.Provenance]
):
    """
    Remove vertices not referenced by any face and remap face indices.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    return_provenance
        If ``True``, also return the [`Provenance`][ordito.interpolation.Provenance] that carries
        any per-vertex or per-face field onto the result.

    Returns
    -------
    new_vertices : wp.array[wp.vec3]
        ``(n_referenced,)`` referenced vertices only, compacted from index zero.
    new_faces : wp.array[wp.int32]
        ``(3 * n_faces,)`` face buffer with indices remapped into ``new_vertices``.
    remap : wp.array[wp.int32]
        ``(n_vertices,)`` old-to-new map (``-1`` when unreferenced).
    provenance : Provenance
        Only when ``return_provenance`` is ``True``: each output vertex is a copy of the input
        vertex its ``vertex_index`` names (the new-to-old map), and every face keeps its index.

    Raises
    ------
    RuntimeError
        If ``vertices`` and ``faces`` are not all on one device.

    Examples
    --------
    A stray vertex no face uses is dropped and maps to ``-1``:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    padded = wp.array(np.vstack([vertices.numpy(), [5.0, 5.0, 5.0]]), dtype=wp.vec3)
    new_vertices, new_faces, remap = od.repair.remove_unreferenced_vertices(padded, faces)
    print(padded.shape, new_vertices.shape)  # (9,) (8,)
    print(remap.numpy().tolist())  # [0, 1, 2, 3, 4, 5, 6, 7, -1]
    _, _, _, provenance = od.repair.remove_unreferenced_vertices(
        padded, faces, return_provenance=True
    )
    print(provenance.vertex_index.numpy().tolist())  # [0, 1, 2, 3, 4, 5, 6, 7]
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    device = faces.device
    n_vertices = vertices.size
    n_faces = faces.size // 3

    # The referenced flags are marked as ``int32`` and scanned in place, and one pass reads the scan
    # to write all three maps and the remapped faces: the tail of the scan is the referenced count,
    # which sizes the outputs and is the one readback. The provenance's identity face map is
    # written by the same pass, into the new-to-old map's allocation.
    remap = _launch.empty(n_vertices, dtype=wp.int32, device=device)
    face_index = None
    if n_vertices == 0:
        new_vertices = _launch.empty(0, dtype=wp.vec3, device=device)
        inverse = _launch.empty(0, dtype=wp.int32, device=device)
        new_faces = od.array.remap_indices(faces, remap)
        if return_provenance:
            face_index = od.array.arange(n_faces, device=device)
    else:
        inclusive = _launch.zeros(n_vertices, dtype=wp.int32, device=device)
        n_indices = faces.size
        if n_indices > 0:
            _launch.launch(
                kernel_repair.mark_referenced,
                dim=n_indices,
                inputs=[faces, inclusive],
                device=device,
            )
        # The referenced count sizes the outputs.
        n_referenced = scan_count(inclusive)
        new_vertices = _launch.empty(n_referenced, dtype=wp.vec3, device=device)
        if return_provenance:
            inverse, face_index = _launch.carve(wp.int32, (n_referenced, n_faces), device)
        else:
            inverse = _launch.empty(n_referenced, dtype=wp.int32, device=device)
        new_faces = _launch.empty(n_indices, dtype=wp.int32, device=device)
        _launch.launch(
            kernel_repair.compact_referenced,
            dim=max(n_vertices, n_indices),
            inputs=[
                vertices,
                faces,
                inclusive,
                remap,
                new_vertices,
                inverse,
                new_faces,
                face_index,
            ],
            device=device,
        )

    if face_index is None:
        return new_vertices, new_faces, remap
    provenance = od.interpolation.Provenance(inverse, face_index, None, n_vertices, n_faces)
    return new_vertices, new_faces, remap, provenance

remove_duplicated_vertices

remove_duplicated_vertices(
    vertices: array[vec3],
    faces: array[int32],
    epsilon: float = 0.0,
    *,
    vertex_values: array[Any] | None = None,
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    wp.array[wp.int32],
    wp.array[wp.int32],
]

Merge duplicate vertex positions up to a coordinate tolerance and remap face indices.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
epsilon float

Uniqueness tolerance. Positive values snap coordinates to round(v / epsilon), so the tolerance is absolute and is the one you chose. 0 instead groups by a relative bucket about 2.4e-4 wide (see Notes) — pass an explicit epsilon unless that is what you want.

0.0
vertex_values array[Any] | None

(n_vertices,) per-vertex attribute that must also agree, exactly, for two vertices to merge: a UV, a normal, a colour or a label. Coincident vertices that carry different values stay apart, so welding a mesh unwelded along its UV seams closes everything but the seams. wp.float32 or wp.int32 scalars or vectors; -0.0 equals 0.0. None merges by position alone.

None

Returns:

Name Type Description
unique_vertices array[vec3]

(n_unique,) deduplicated vertex positions (first occurrence per equivalence class), in order of first occurrence -- the order of Open3D's remove_duplicated_vertices, VTK's vtkCleanPolyData and MeshLab's -- so a mesh with no duplicates comes back unchanged.

unique_indices array[int32]

(n_unique,) original indices into vertices for each output row.

inverse array[int32]

(n_vertices,) map from each input vertex to its slot in unique_vertices.

unique_faces array[int32]

(3 * n_faces,) face buffer with indices remapped into unique_vertices.

Raises:

Type Description
ValueError

If vertex_values does not have one entry per vertex.

TypeError

If vertex_values' scalar type is not wp.float32 or wp.int32.

RuntimeError

If vertices, faces and vertex_values are not all on one device.

Notes

Both tolerance modes quantize positions and group by cell, so both separate a pair straddling a cell boundary however close it is. That is worth knowing about epsilon=0 in particular, which is not an exact-equality test despite requiring no tolerance: it buckets by the high bits of each coordinate's float32 representation, giving a relative cell about 2.4e-4 wide. So 1.0 and 1.000244 merge, while two adjacent float32 values on either side of a bucket edge do not. Prefer an explicit epsilon whenever the tolerance matters; use 0 only to collapse positions that are already bitwise equal, which it does reliably (including across +0.0 / -0.0).

Duplicates that are known from construction rather than measured are better collapsed directly: see revolve, which derives them from its profile instead of hashing positions.

See Also

duplicate_vertex_inverse hash_vector_rows ordito.seams.cut_along_edges The inverse operation: welding coincident positions back together closes every cut it makes.

Examples:

A cube stored as a triangle soup, three private vertices per face, is not watertight until its coincident corners are welded:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.box()
soup_vertices = wp.array(vertices.numpy()[faces.numpy()], dtype=wp.vec3)
soup_faces = wp.array(np.arange(36), dtype=wp.int32)
print(od.validation.is_watertight(soup_vertices, soup_faces))  # False
welded, _, inverse, welded_faces = od.repair.remove_duplicated_vertices(
    soup_vertices, soup_faces, epsilon=1e-6
)
print(soup_vertices.shape, welded.shape)  # (36,) (8,)
print(od.validation.is_watertight(welded, welded_faces))  # True
Source code in ordito/repair.py
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
def remove_duplicated_vertices(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    epsilon: float = 0.0,
    *,
    vertex_values: wp.array[Any] | None = None,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32], wp.array[wp.int32], wp.array[wp.int32]]:
    """
    Merge duplicate vertex positions up to a coordinate tolerance and remap face indices.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    epsilon
        Uniqueness tolerance. Positive values snap coordinates to ``round(v / epsilon)``, so the
        tolerance is absolute and is the one you chose. ``0`` instead groups by a *relative*
        bucket about ``2.4e-4`` wide (see Notes) — pass an explicit ``epsilon`` unless that is
        what you want.
    vertex_values
        ``(n_vertices,)`` per-vertex attribute that must also agree, exactly, for two vertices to
        merge: a UV, a normal, a colour or a label. Coincident vertices that carry different values
        stay apart, so welding a mesh unwelded along its UV seams closes everything but the seams.
        ``wp.float32`` or ``wp.int32`` scalars or vectors; ``-0.0`` equals ``0.0``. ``None``
        merges by position alone.

    Returns
    -------
    unique_vertices : wp.array[wp.vec3]
        ``(n_unique,)`` deduplicated vertex positions (first occurrence per equivalence class), in
        order of first occurrence -- the order of Open3D's ``remove_duplicated_vertices``, VTK's
        ``vtkCleanPolyData`` and MeshLab's -- so a mesh with no duplicates comes back unchanged.
    unique_indices : wp.array[wp.int32]
        ``(n_unique,)`` original indices into ``vertices`` for each output row.
    inverse : wp.array[wp.int32]
        ``(n_vertices,)`` map from each input vertex to its slot in ``unique_vertices``.
    unique_faces : wp.array[wp.int32]
        ``(3 * n_faces,)`` face buffer with indices remapped into ``unique_vertices``.

    Raises
    ------
    ValueError
        If ``vertex_values`` does not have one entry per vertex.
    TypeError
        If ``vertex_values``' scalar type is not ``wp.float32`` or ``wp.int32``.
    RuntimeError
        If ``vertices``, ``faces`` and ``vertex_values`` are not all on one device.

    Notes
    -----
    Both tolerance modes quantize positions and group by cell, so both separate a pair straddling a
    cell boundary however close it is. That is worth knowing about ``epsilon=0`` in particular,
    which is **not** an exact-equality test despite requiring no tolerance: it buckets by the high
    bits of each coordinate's ``float32`` representation, giving a *relative* cell about ``2.4e-4``
    wide. So ``1.0`` and ``1.000244`` merge, while two adjacent ``float32`` values on either side of
    a bucket edge do not. Prefer an explicit ``epsilon`` whenever the tolerance matters; use ``0``
    only to collapse positions that are already bitwise equal, which it does reliably (including
    across ``+0.0`` / ``-0.0``).

    Duplicates that are known from construction rather than measured are better collapsed directly:
    see [`revolve`][ordito.creation.revolve], which derives them from its profile instead of
    hashing positions.

    See Also
    --------
    [`duplicate_vertex_inverse`][ordito.repair.duplicate_vertex_inverse]
    [`hash_vector_rows`][ordito.grouping.hash_vector_rows]
    [`ordito.seams.cut_along_edges`][ordito.seams.cut_along_edges]
        The inverse operation: welding coincident positions back together closes every cut it makes.

    Examples
    --------
    A cube stored as a triangle soup, three private vertices per face, is not watertight until its
    coincident corners are welded:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    soup_vertices = wp.array(vertices.numpy()[faces.numpy()], dtype=wp.vec3)
    soup_faces = wp.array(np.arange(36), dtype=wp.int32)
    print(od.validation.is_watertight(soup_vertices, soup_faces))  # False
    welded, _, inverse, welded_faces = od.repair.remove_duplicated_vertices(
        soup_vertices, soup_faces, epsilon=1e-6
    )
    print(soup_vertices.shape, welded.shape)  # (36,) (8,)
    print(od.validation.is_watertight(welded, welded_faces))  # True
    ```
    """
    require_same_device(vertices=vertices, faces=faces, vertex_values=vertex_values)
    # Each class's first occurrence comes with the inverse, read off the grouping's stable sort.
    inverse, unique_indices = _vertex_classes(vertices, epsilon)
    if vertex_values is not None:
        if vertex_values.size != vertices.size:
            raise ValueError(
                f"vertex_values must have one entry per vertex, got {vertex_values.size} for "
                f"{vertices.size} vertices"
            )
        # Each position class split by the values its vertices carry, then numbered again by
        # first occurrence.
        inverse, unique_indices = _exact_value_classes(
            inverse, vertex_values, max(unique_indices.size, 1)
        )
        inverse, unique_indices = _numbered_by_first_occurrence(inverse, unique_indices)
    unique_vertices = od.array.gather(vertices, unique_indices)
    unique_faces = od.array.remap_indices(faces, inverse)
    return unique_vertices, unique_indices, inverse, unique_faces

duplicate_vertex_inverse

duplicate_vertex_inverse(
    vertices: array[vec3], epsilon: float
) -> wp.array[wp.int32]

Map each vertex to the slot of its coincident-vertex equivalence class.

The inverse map produced by welding vertices at epsilon tolerance, without also computing the deduplicated vertex/face buffers — useful for remapping per-vertex attributes (colors, UVs, ...) to match a remove_duplicated_vertices call made with the same epsilon.

This is the shared equivalence map the dedup remaps by, not a remover -- which is why it lives here rather than in ordito.grouping beside first_occurrence_indices, whose shape it has. Its key is a tolerance-quantized position, and choosing that tolerance is mesh-repair policy; grouping is deliberately dtype-generic and geometry-free, so an epsilon there would be the first crack in that contract.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
epsilon float

Uniqueness tolerance, with the same meaning as in remove_duplicated_vertices: positive values snap coordinates to round(v / epsilon), while 0 groups by a relative bucket about 2.4e-4 wide rather than testing for equality.

required

Returns:

Type Description
array[int32]

(n_vertices,) map from each input vertex to its slot in the deduplicated set.

See Also

remove_duplicated_vertices The remover this map is the shared half of. hash_vector_rows grouping.first_occurrence_indices The geometry-free counterpart: the same class-to-representative reduction over any key.

Examples:

The 36 corners of a cube's triangle soup fall into 8 classes:

import warp as wp

import ordito as od

vertices, faces = od.creation.box()
soup_vertices = wp.array(vertices.numpy()[faces.numpy()], dtype=wp.vec3)
inverse = od.repair.duplicate_vertex_inverse(soup_vertices, 1e-6)
print(inverse.shape, int(inverse.numpy().max()) + 1)  # (36,) 8
Source code in ordito/repair.py
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
def duplicate_vertex_inverse(vertices: wp.array[wp.vec3], epsilon: float) -> wp.array[wp.int32]:
    """
    Map each vertex to the slot of its coincident-vertex equivalence class.

    The inverse map produced by welding vertices at ``epsilon`` tolerance, without also
    computing the deduplicated vertex/face buffers — useful for remapping per-vertex
    attributes (colors, UVs, ...) to match a [`remove_duplicated_vertices`]
    [ordito.repair.remove_duplicated_vertices] call made with the same ``epsilon``.

    This is the shared equivalence map the dedup remaps by, not a remover -- which is why it lives
    here rather than in [`ordito.grouping`][ordito.grouping] beside
    [`first_occurrence_indices`][ordito.grouping.first_occurrence_indices], whose shape it has. Its
    key is a *tolerance-quantized position*, and choosing that tolerance is mesh-repair policy;
    ``grouping`` is deliberately dtype-generic and geometry-free, so an ``epsilon`` there would be
    the first crack in that contract.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    epsilon
        Uniqueness tolerance, with the same meaning as in
        [`remove_duplicated_vertices`][ordito.repair.remove_duplicated_vertices]: positive values
        snap coordinates to ``round(v / epsilon)``, while ``0`` groups by a *relative* bucket about
        ``2.4e-4`` wide rather than testing for equality.

    Returns
    -------
    wp.array[wp.int32]
        ``(n_vertices,)`` map from each input vertex to its slot in the deduplicated set.

    See Also
    --------
    [`remove_duplicated_vertices`][ordito.repair.remove_duplicated_vertices]
        The remover this map is the shared half of.
    [`hash_vector_rows`][ordito.grouping.hash_vector_rows]
    [`grouping.first_occurrence_indices`][ordito.grouping.first_occurrence_indices]
        The geometry-free counterpart: the same class-to-representative reduction over any key.

    Examples
    --------
    The 36 corners of a cube's triangle soup fall into 8 classes:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    soup_vertices = wp.array(vertices.numpy()[faces.numpy()], dtype=wp.vec3)
    inverse = od.repair.duplicate_vertex_inverse(soup_vertices, 1e-6)
    print(inverse.shape, int(inverse.numpy().max()) + 1)  # (36,) 8
    ```
    """
    return _vertex_classes(vertices, epsilon)[0]

split_vertices_by_corner_values

split_vertices_by_corner_values(
    vertices: array[vec3],
    faces: array[int32],
    corner_values: array[Any],
    *,
    return_provenance: Literal[False] = False,
) -> tuple[
    wp.array[wp.vec3], wp.array[wp.int32], wp.array[Any]
]
split_vertices_by_corner_values(
    vertices: array[vec3],
    faces: array[int32],
    corner_values: array[Any],
    *,
    return_provenance: Literal[True],
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    wp.array[Any],
    od.interpolation.Provenance,
]
split_vertices_by_corner_values(
    vertices: array[vec3],
    faces: array[int32],
    corner_values: array[Any],
    *,
    return_provenance: bool = False,
) -> (
    tuple[
        wp.array[wp.vec3], wp.array[wp.int32], wp.array[Any]
    ]
    | tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        wp.array[Any],
        od.interpolation.Provenance,
    ]
)

Split each vertex into one copy per distinct value its corners carry.

A face-varying attribute -- a UV atlas, hard normals, per-face colours -- stores a value per corner, and two faces meeting at a vertex may disagree about it: across a UV seam the same position has two texcoords. Renderers, file formats such as glTF and every per-vertex function in this package want one value per vertex instead, which takes a vertex for each distinct (vertex, value) pair. This builds exactly that: corners at the same vertex with equal values share an output vertex, corners that disagree get their own, and every output vertex sits where its input vertex did. A vertex whose corners all agree is not split.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
corner_values array[Any]

(3 * n_faces,) value of each corner, in faces' order: wp.float32 or wp.int32 scalars or vectors (wp.vec2 for a UV atlas, wp.vec3 for a normal, wp.vec4 for a colour). Equal means bitwise equal, -0.0 and 0.0 excepted, so snap values computed with rounding error first.

required
return_provenance bool

If True, also return the Provenance that carries any other per-vertex or per-face field onto the split mesh.

False

Returns:

Name Type Description
new_vertices array[vec3]

(n_out_vertices,) one vertex per distinct (vertex, value) pair, ordered by input vertex. A vertex no face references has no corner and is dropped.

new_faces array[int32]

(3 * n_faces,) the same faces in the same order, over new_vertices.

new_values array

(n_out_vertices,) the value of each output vertex, of corner_values' dtype, so that new_values[new_faces] == corner_values.

provenance Provenance

Only when return_provenance is True: each output vertex is a copy of the input vertex it was split from, and the faces are the input faces in order.

Raises:

Type Description
ValueError

If corner_values does not have one entry per corner.

TypeError

If corner_values' scalar type is not wp.float32 or wp.int32.

RuntimeError

If vertices, faces and corner_values are not all on one device.

See Also

remove_duplicated_vertices The inverse: vertex_values=new_values welds the copies back wherever the values agree. ordito.seams.uv_seam_edges The edges along which a per-corner atlas tears. ordito.seams.cut_along_edges A split by a chosen edge set rather than by values.

Examples:

A box with a colour per side: each cube corner splits into the three colours of the three sides meeting there:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.box()
normals, _ = od.triangles.face_normals_and_areas(vertices, faces)
corner_colors = wp.array(np.repeat(np.abs(normals.numpy()), 3, axis=0), dtype=wp.vec3)
new_vertices, new_faces, colors = od.repair.split_vertices_by_corner_values(
    vertices, faces, corner_colors
)
print(new_vertices.shape, colors.shape)  # (24,) (24,)
print(np.array_equal(colors.numpy()[new_faces.numpy()], corner_colors.numpy()))  # True
Source code in ordito/repair.py
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
def split_vertices_by_corner_values(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    corner_values: wp.array[Any],
    *,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32], wp.array[Any]]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], wp.array[Any], od.interpolation.Provenance]
):
    """
    Split each vertex into one copy per distinct value its corners carry.

    A face-varying attribute -- a UV atlas, hard normals, per-face colours -- stores a value per
    *corner*, and two faces meeting at a vertex may disagree about it: across a UV seam the same
    position has two texcoords. Renderers, file formats such as glTF and every per-vertex function
    in this package want one value per vertex instead, which takes a vertex for each distinct
    ``(vertex, value)`` pair. This builds exactly that: corners at the same vertex with equal values
    share an output vertex, corners that disagree get their own, and every output vertex sits where
    its input vertex did. A vertex whose corners all agree is not split.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    corner_values
        ``(3 * n_faces,)`` value of each corner, in ``faces``' order: ``wp.float32`` or ``wp.int32``
        scalars or vectors (``wp.vec2`` for a UV atlas, ``wp.vec3`` for a normal, ``wp.vec4`` for a
        colour). Equal means bitwise equal, ``-0.0`` and ``0.0`` excepted, so snap values computed
        with rounding error first.
    return_provenance
        If ``True``, also return the [`Provenance`][ordito.interpolation.Provenance] that carries
        any other per-vertex or per-face field onto the split mesh.

    Returns
    -------
    new_vertices : wp.array[wp.vec3]
        ``(n_out_vertices,)`` one vertex per distinct ``(vertex, value)`` pair, ordered by input
        vertex. A vertex no face references has no corner and is dropped.
    new_faces : wp.array[wp.int32]
        ``(3 * n_faces,)`` the same faces in the same order, over ``new_vertices``.
    new_values : wp.array
        ``(n_out_vertices,)`` the value of each output vertex, of ``corner_values``' dtype, so that
        ``new_values[new_faces] == corner_values``.
    provenance : Provenance
        Only when ``return_provenance`` is ``True``: each output vertex is a copy of the input
        vertex it was split from, and the faces are the input faces in order.

    Raises
    ------
    ValueError
        If ``corner_values`` does not have one entry per corner.
    TypeError
        If ``corner_values``' scalar type is not ``wp.float32`` or ``wp.int32``.
    RuntimeError
        If ``vertices``, ``faces`` and ``corner_values`` are not all on one device.

    See Also
    --------
    [`remove_duplicated_vertices`][ordito.repair.remove_duplicated_vertices]
        The inverse: ``vertex_values=new_values`` welds the copies back wherever the values agree.
    [`ordito.seams.uv_seam_edges`][ordito.seams.uv_seam_edges]
        The edges along which a per-corner atlas tears.
    [`ordito.seams.cut_along_edges`][ordito.seams.cut_along_edges]
        A split by a chosen edge set rather than by values.

    Examples
    --------
    A box with a colour per side: each cube corner splits into the three colours of the three
    sides meeting there:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    normals, _ = od.triangles.face_normals_and_areas(vertices, faces)
    corner_colors = wp.array(np.repeat(np.abs(normals.numpy()), 3, axis=0), dtype=wp.vec3)
    new_vertices, new_faces, colors = od.repair.split_vertices_by_corner_values(
        vertices, faces, corner_colors
    )
    print(new_vertices.shape, colors.shape)  # (24,) (24,)
    print(np.array_equal(colors.numpy()[new_faces.numpy()], corner_colors.numpy()))  # True
    ```
    """
    require_same_device(vertices=vertices, faces=faces, corner_values=corner_values)
    device = vertices.device
    n_corners = faces.size
    if corner_values.size != n_corners:
        raise ValueError(
            f"corner_values must have one entry per corner, got {corner_values.size} for "
            f"{n_corners} corners"
        )
    corner_class, first = _exact_value_classes(faces, corner_values, max(vertices.size, 1))
    n_out = first.size
    new_vertices = _launch.empty(n_out, dtype=wp.vec3, device=device)
    source = _launch.empty(n_out, dtype=wp.int32, device=device)
    if n_out > 0:
        _launch.launch(
            kernel_repair.split_corner_outputs,
            dim=n_out,
            inputs=[vertices, faces, first],
            outputs=[new_vertices, source],
            device=device,
        )
    new_values = od.array.gather(corner_values, first)
    if not return_provenance:
        return new_vertices, corner_class, new_values
    n_faces = n_corners // 3
    provenance = od.interpolation.Provenance(
        source, od.array.arange(n_faces, device=device), None, vertices.size, n_faces
    )
    return new_vertices, corner_class, new_values, provenance

resolve_duplicated_faces

resolve_duplicated_faces(
    faces: array[int32],
    *,
    n_vertices: int | None = None,
    method: Literal[
        "cancel", "igl", "open3d", "meshlab"
    ] = "cancel",
) -> tuple[wp.array[wp.int32], wp.array[wp.int32]]

Resolve duplicated triangles, by default cancelling oppositely wound copies.

A duplicate group is the faces sharing one vertex set. Under method="cancel" (the default) and "igl" a face counts +1 when it is wound as the group's first face and -1 when reversed, and the group's signed count decides:

  • equal positive and negative counts: remove all copies;
  • one extra positive copy: keep the first positively oriented face;
  • one extra negative copy: keep the first negatively oriented face;
  • otherwise (two or more surplus copies of one winding) the group is not orientable: "cancel" raises ValueError, "igl" drops the whole group, as igl::resolve_duplicated_faces does.

"open3d" and "meshlab" cancel nothing: each keeps one face per group, the first occurrence. Open3D's remove_duplicated_triangles groups by winding too, so a face and its reversed copy are two groups and both stay; MeshLab's meshing_remove_duplicate_faces groups by vertex set alone, so one of them stays (MeshLab keeps whichever its unstable sort puts last; this keeps the first).

Parameters:

Name Type Description Default
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
n_vertices int | None

Optional exclusive bound on the vertex indices, typically the vertex count. Trusted, not checked: it spares the reduction that otherwise range-checks faces and infers the bound, and its host readback.

None
method Literal['cancel', 'igl', 'open3d', 'meshlab']

"cancel" (default), "igl", "open3d" or "meshlab": the rule above.

'cancel'

Returns:

Name Type Description
resolved_faces array[int32]

(3 * n_kept,) flat buffer of kept faces, one per surviving group. Under "igl" in libigl's order: the groups ascending lexicographically by their sorted corner indices. Under "cancel", "open3d" and "meshlab" in input order (ascending kept_indices), as Open3D and MeshLab return them; "cancel" keeps the same faces as "igl" wherever the input has no non-orientable group.

kept_indices array[int32]

(n_kept,) original face indices into the input faces buffer, in the same order.

Raises:

Type Description
ValueError

If method is not one of the four names; under "cancel", if a duplicate group's signed count is not orientable, i.e. its positive and negative copies differ by more than one; or if n_vertices is None and a face index is negative.

Examples:

A face and its reversed copy cancel, opening a hole; a third copy settles the pair in its own orientation:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.box()
rows = faces.numpy().reshape(-1, 3)
cancelled = wp.array(np.concatenate([rows, rows[:1, ::-1]]).ravel(), dtype=wp.int32)
resolved, kept = od.repair.resolve_duplicated_faces(cancelled)
print(resolved.shape[0] // 3, sorted(kept.numpy().tolist())[:3])  # 11 [1, 2, 3]
tripled = wp.array(np.concatenate([rows, rows[:1, ::-1], rows[:1]]).ravel(), dtype=wp.int32)
resolved, kept = od.repair.resolve_duplicated_faces(tripled)
print(resolved.shape[0] // 3)  # 12

Open3D's rule keeps both windings, MeshLab's one face of the pair:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.box()
rows = faces.numpy().reshape(-1, 3)
doubled = wp.array(np.concatenate([rows, rows[:1, ::-1]]).ravel(), dtype=wp.int32)
print(od.repair.resolve_duplicated_faces(doubled, method="open3d")[1].shape[0])  # 13
print(od.repair.resolve_duplicated_faces(doubled, method="meshlab")[1].shape[0])  # 12
Source code in ordito/repair.py
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
def resolve_duplicated_faces(
    faces: wp.array[wp.int32],
    *,
    n_vertices: int | None = None,
    method: Literal["cancel", "igl", "open3d", "meshlab"] = "cancel",
) -> tuple[wp.array[wp.int32], wp.array[wp.int32]]:
    """
    Resolve duplicated triangles, by default cancelling oppositely wound copies.

    A duplicate group is the faces sharing one vertex set. Under ``method="cancel"`` (the default)
    and ``"igl"`` a face counts ``+1`` when it is wound as the group's first face and ``-1`` when
    reversed, and the group's signed count decides:

    - equal positive and negative counts: remove all copies;
    - one extra positive copy: keep the first positively oriented face;
    - one extra negative copy: keep the first negatively oriented face;
    - otherwise (two or more surplus copies of one winding) the group is not orientable:
      ``"cancel"`` raises ``ValueError``, ``"igl"`` drops the whole group, as
      ``igl::resolve_duplicated_faces`` does.

    ``"open3d"`` and ``"meshlab"`` cancel nothing: each keeps one face per group, the first
    occurrence. Open3D's ``remove_duplicated_triangles`` groups by winding too, so a face and its
    reversed copy are two groups and both stay; MeshLab's ``meshing_remove_duplicate_faces`` groups
    by vertex set alone, so one of them stays (MeshLab keeps whichever its unstable sort puts last;
    this keeps the first).

    Parameters
    ----------
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    n_vertices
        Optional exclusive bound on the vertex indices, typically the vertex count. Trusted, not
        checked: it spares the reduction that otherwise range-checks ``faces`` and infers the
        bound, and its host readback.
    method
        ``"cancel"`` (default), ``"igl"``, ``"open3d"`` or ``"meshlab"``: the rule above.

    Returns
    -------
    resolved_faces : wp.array[wp.int32]
        ``(3 * n_kept,)`` flat buffer of kept faces, one per surviving group. Under ``"igl"`` in
        libigl's order: the groups ascending lexicographically by their sorted corner indices.
        Under ``"cancel"``, ``"open3d"`` and ``"meshlab"`` in input order (ascending
        ``kept_indices``), as Open3D and MeshLab return them; ``"cancel"`` keeps the same faces as
        ``"igl"`` wherever the input has no non-orientable group.
    kept_indices : wp.array[wp.int32]
        ``(n_kept,)`` original face indices into the input ``faces`` buffer, in the same order.

    Raises
    ------
    ValueError
        If ``method`` is not one of the four names; under ``"cancel"``, if a duplicate group's
        signed count is not orientable, i.e. its positive and negative copies differ by more than
        one; or if ``n_vertices`` is ``None`` and a face index is negative.

    Examples
    --------
    A face and its reversed copy cancel, opening a hole; a third copy settles the pair in its own
    orientation:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    rows = faces.numpy().reshape(-1, 3)
    cancelled = wp.array(np.concatenate([rows, rows[:1, ::-1]]).ravel(), dtype=wp.int32)
    resolved, kept = od.repair.resolve_duplicated_faces(cancelled)
    print(resolved.shape[0] // 3, sorted(kept.numpy().tolist())[:3])  # 11 [1, 2, 3]
    tripled = wp.array(np.concatenate([rows, rows[:1, ::-1], rows[:1]]).ravel(), dtype=wp.int32)
    resolved, kept = od.repair.resolve_duplicated_faces(tripled)
    print(resolved.shape[0] // 3)  # 12
    ```

    Open3D's rule keeps both windings, MeshLab's one face of the pair:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    rows = faces.numpy().reshape(-1, 3)
    doubled = wp.array(np.concatenate([rows, rows[:1, ::-1]]).ravel(), dtype=wp.int32)
    print(od.repair.resolve_duplicated_faces(doubled, method="open3d")[1].shape[0])  # 13
    print(od.repair.resolve_duplicated_faces(doubled, method="meshlab")[1].shape[0])  # 12
    ```
    """
    if method not in ("cancel", "igl", "open3d", "meshlab"):
        raise ValueError(f"method must be 'cancel', 'igl', 'open3d' or 'meshlab', got {method!r}")
    n_faces = faces.size // 3
    device = faces.device
    if n_faces == 0:
        empty = _launch.empty(0, dtype=wp.int32, device=device)
        return empty, empty

    if n_vertices is None:
        # The range check and the key radix ``grouping.unique_faces`` takes without a bound.
        n_vertices = checked_index_bound(*index_extrema(faces), "faces")
    # CUDA groups the faces in rings, with no sort; the CPU sorts, its radix sort cheaper there
    # than the ring walks (rings 1.1-1.5x the sort's time for the first occurrence, 2.2-2.9x for
    # the cancelling rule, sphere_small to dragon).
    rings = not wp.get_device(device).is_cpu
    if method in ("open3d", "meshlab"):
        oriented = method == "open3d"
        if rings:
            ringed = _first_occurrence_faces_in_rings(faces, n_vertices, oriented=oriented)
            if ringed is not None:
                return ringed
        return _first_occurrence_faces(faces, n_vertices, oriented=oriented)
    if rings:
        if method == "igl":
            ringed = _resolved_faces_in_rings(faces, n_vertices)
        else:
            ringed = _cancelled_faces_in_rings(faces, n_vertices)
        if ringed is not None:
            return ringed
    # Orientation-free keys ordered as the sorted rows are lexicographically, with the identity
    # payload, sorted, and then each run of equal keys -- one duplicate group, its faces in
    # ascending index -- decided by the thread at its start: no unique table, inverse or per-group
    # statistics are written between the sort and the decision. Three sorted indices below
    # ``n_vertices`` pack below ``n_vertices ** 3``.
    keys = _launch.empty(2 * n_faces, dtype=wp.uint64, device=device)
    # The sort's payload and, behind it, the keep flags with the error word right behind them, so
    # one readback takes the kept count and the error together: one zeroed allocation, as only
    # the error word needs its zero (the flags are written whole).
    order, flags = _launch.carve(wp.int32, [2 * n_faces, n_faces + 1], device, zeroed=True)
    _launch.launch(
        kernel_repair.pack_lexicographic_face_keys_and_order,
        dim=n_faces,
        inputs=[faces, wp.uint64(n_vertices), keys, order],
        device=device,
    )
    end_bit = _launch.key_bits(n_vertices**3)
    _launch.radix_sort_pairs(keys, order, count=n_faces, end_bit=end_bit)
    # Under "igl" the keep flags at the sorted positions, the decided face of each run start beside
    # them in the payload's upper half (the sort's scratch until now); under "cancel" a flag at
    # each kept face's own index of the zeroed flags, and no decided faces.
    igl_order = method == "igl"
    keep = _launch.view(order, n_faces, 2 * n_faces)
    _launch.launch(
        kernel_repair.resolve_duplicate_runs,
        dim=n_faces,
        inputs=[faces, keys, order, n_faces, int(igl_order), int(not igl_order)],
        outputs=[keep, flags],
        device=device,
    )
    # Scanned in place, a kept face's flag becomes its output row plus one: in ascending key order
    # (libigl's emission order) under "igl", in input order under "cancel"; the last entry is the
    # kept total.
    ranks = odt.as_dense(flags[:n_faces])
    _launch.array_scan(ranks, out_array=ranks, inclusive=True)
    n_kept, error_word = read_values(flags, n_faces - 1, 2)
    if error_word != 0:
        _raise_duplicate_group(faces, keys, order, n_faces - error_word)

    resolved = _launch.empty(3 * n_kept, dtype=wp.int32, device=device)
    kept_wp = _launch.empty(n_kept, dtype=wp.int32, device=device)
    if n_kept > 0:
        if igl_order:
            _launch.launch(
                kernel_repair.compact_kept_duplicate_runs,
                dim=n_faces,
                inputs=[faces, keep, ranks],
                outputs=[resolved, kept_wp],
                device=device,
            )
        else:
            _launch.launch(
                kernel_repair.compact_scanned_faces_and_indices,
                dim=n_faces,
                inputs=[ranks, faces],
                outputs=[resolved, kept_wp],
                device=device,
            )
    return resolved, kept_wp

remove_degenerate_faces

remove_degenerate_faces(
    vertices: array[vec3],
    faces: array[int32],
    *,
    return_provenance: Literal[False] = False,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32]]
remove_degenerate_faces(
    vertices: array[vec3],
    faces: array[int32],
    *,
    return_provenance: Literal[True],
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    od.interpolation.Provenance,
]
remove_degenerate_faces(
    vertices: array[vec3],
    faces: array[int32],
    *,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        od.interpolation.Provenance,
    ]
)

Drop degenerate (zero-area) triangles and reindex, keeping vertex positions unchanged.

Mirrors trimesh.Trimesh.nondegenerate_faces + update_faces: a face is degenerate when two of its vertices coincide or its three vertices are collinear, detected by face_nondegenerate_mask (both triangle altitudes exceed the merge tolerance). Surviving faces are unchanged; vertices left unreferenced after the drop are removed by the reindexing in submesh_from_face_mask.

Unlike collapse_small_triangles, no vertices are merged and no edges are collapsed: this only removes faces already degenerate in the input.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
return_provenance bool

If True, also return the Provenance that carries any per-vertex or per-face field onto the result.

False

Returns:

Name Type Description
new_vertices array[vec3]

(n_new_vertices,) vertices still referenced by a non-degenerate face, compacted from index zero.

new_faces array[int32]

(3 * n_new_faces,) flat buffer of the non-degenerate faces, remapped into new_vertices.

provenance Provenance

Only when return_provenance is True: each output vertex is a copy of an input vertex, and each output face of the input face it is.

Raises:

Type Description
RuntimeError

If vertices and faces are not all on one device.

See Also

collapse_small_triangles face_nondegenerate_mask trimesh.triangles.nondegenerate

Examples:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.box()
with_sliver = wp.array(np.concatenate([faces.numpy(), [0, 1, 1]]), dtype=wp.int32)
new_vertices, new_faces = od.repair.remove_degenerate_faces(vertices, with_sliver)
print(with_sliver.shape[0] // 3, new_faces.shape[0] // 3)  # 13 12
Source code in ordito/repair.py
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
def remove_degenerate_faces(
    vertices: wp.array[wp.vec3], faces: wp.array[wp.int32], *, return_provenance: bool = False
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], od.interpolation.Provenance]
):
    """
    Drop degenerate (zero-area) triangles and reindex, keeping vertex positions unchanged.

    Mirrors ``trimesh.Trimesh.nondegenerate_faces`` + ``update_faces``: a face is degenerate when
    two of its vertices coincide or its three vertices are collinear, detected by
    [`face_nondegenerate_mask`][ordito.triangles.face_nondegenerate_mask] (both triangle altitudes
    exceed the merge tolerance). Surviving faces are unchanged; vertices left unreferenced after the
    drop are removed by the reindexing in
    [`submesh_from_face_mask`][ordito.selection.submesh_from_face_mask].

    Unlike [`collapse_small_triangles`][ordito.repair.collapse_small_triangles], no vertices are
    merged and no edges are collapsed: this only removes faces already degenerate in the input.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    return_provenance
        If ``True``, also return the [`Provenance`][ordito.interpolation.Provenance] that carries
        any per-vertex or per-face field onto the result.

    Returns
    -------
    new_vertices : wp.array[wp.vec3]
        ``(n_new_vertices,)`` vertices still referenced by a non-degenerate face, compacted from
        index zero.
    new_faces : wp.array[wp.int32]
        ``(3 * n_new_faces,)`` flat buffer of the non-degenerate faces, remapped into
        ``new_vertices``.
    provenance : Provenance
        Only when ``return_provenance`` is ``True``: each output vertex is a copy of an input
        vertex, and each output face of the input face it is.

    Raises
    ------
    RuntimeError
        If ``vertices`` and ``faces`` are not all on one device.

    See Also
    --------
    [`collapse_small_triangles`][ordito.repair.collapse_small_triangles]
    [`face_nondegenerate_mask`][ordito.triangles.face_nondegenerate_mask]
    [`trimesh.triangles.nondegenerate`][]

    Examples
    --------
    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    with_sliver = wp.array(np.concatenate([faces.numpy(), [0, 1, 1]]), dtype=wp.int32)
    new_vertices, new_faces = od.repair.remove_degenerate_faces(vertices, with_sliver)
    print(with_sliver.shape[0] // 3, new_faces.shape[0] // 3)  # 13 12
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    n_faces = faces.size // 3
    if n_faces == 0:
        if return_provenance:
            return (
                _launch.clone(vertices),
                _launch.clone(faces),
                od.interpolation.Provenance.identity(vertices.size, 0, vertices.device),
            )
        return _launch.clone(vertices), _launch.clone(faces)

    # The degeneracy test marks the survivors for the compaction in the pass that decides them.
    keep_mask = _launch.empty(n_faces, dtype=wp.bool, device=faces.device)
    ranks = _launch.zeros(n_faces + vertices.size, dtype=wp.int32, device=faces.device)
    _launch.launch(
        kernel_repair.mark_nondegenerate_faces,
        dim=n_faces,
        inputs=[vertices, faces, keep_mask, ranks],
        device=faces.device,
    )
    new_vertices, new_faces, vertex_index, _ranks = _compact_marked_submesh(
        vertices, faces, keep_mask, ranks, keep_masked=True, with_index=return_provenance
    )
    if not return_provenance:
        return new_vertices, new_faces
    provenance = od.interpolation.Provenance(
        vertex_index, od.array.flatnonzero(keep_mask), None, vertices.size, n_faces
    )
    return new_vertices, new_faces, provenance

remove_non_manifold_faces

remove_non_manifold_faces(
    vertices: array[vec3],
    faces: array[int32],
    max_iter: int = 3,
    *,
    method: Literal["all", "meshlab"] = "all",
    return_provenance: Literal[False] = False,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32]]
remove_non_manifold_faces(
    vertices: array[vec3],
    faces: array[int32],
    max_iter: int = 3,
    *,
    method: Literal["all", "meshlab"] = "all",
    return_provenance: Literal[True],
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    od.interpolation.Provenance,
]
remove_non_manifold_faces(
    vertices: array[vec3],
    faces: array[int32],
    max_iter: int = 3,
    *,
    method: Literal["all", "meshlab"] = "all",
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        od.interpolation.Provenance,
    ]
)

Remove faces touching a non-manifold (>2-incident) edge, leaving the mesh edge-manifold.

Keeps only faces whose three edges are each used by at most two faces (edge_manifold_mask). Dropping a face only lowers the share count of its own edges, and every edge used three or more times loses all its faces, so one pass leaves every edge used at most twice: a further pass would keep every face.

method="meshlab" removes fewer faces: visiting the faces on a non-manifold edge from the smallest area up (ties by face index), it deletes a face while one of its edges still has more than two faces, so each such edge keeps its two largest faces where they do not conflict. A duplicated face loses one copy rather than both and its neighbour, and a fin on an edge goes alone. This is MeshLab's meshing_repair_non_manifold_edges(method="Remove Faces"); the visit runs as rounds in which every face whose smaller rivals on its edges have been decided decides at once, so the number of rounds is the longest chain of faces of increasing area linked through shared non-manifold edges, one host readback each.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
max_iter int

Maximum number of removal passes. One pass already reaches the fixpoint, so every value from 1 gives the same answer; 0 removes nothing. Unread under method="meshlab", which runs until every face on a non-manifold edge is decided.

3
method Literal['all', 'meshlab']

Which faces go.

  • "all" (default) — every face on a non-manifold edge.
  • "meshlab" — the smallest first, until each edge is manifold (see above).

"all" is the default because it is one pass with no host readback, and its rule reads the topology alone, so no face area decides which sheet survives. "meshlab" removes far fewer faces (around a fin it keeps the surface and drops the fin), at the cost of a round of readbacks per link in its chain of decisions.

'all'
return_provenance bool

If True, also return the Provenance that carries any per-vertex or per-face field onto the result.

False

Returns:

Name Type Description
new_vertices array[vec3]

(n_new_vertices,) vertices still referenced after non-manifold faces are dropped, compacted from index zero; vertices itself, not a copy, when no face is dropped.

new_faces array[int32]

(3 * n_new_faces,) flat buffer of the surviving (edge-manifold) faces; faces itself, not a copy, when no face is dropped.

provenance Provenance

Only when return_provenance is True: each output vertex is a copy of an input vertex, and each output face of the input face it is.

Raises:

Type Description
ValueError

If method is not "all" or "meshlab".

RuntimeError

If vertices and faces are not all on one device.

See Also

remove_degenerate_faces remove_degenerate_and_non_manifold_faces edge_manifold_mask

Examples:

A fin glued to one edge of a cube gives that edge three faces; all three go:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.box()
a, b = faces.numpy()[:2]
fin_vertices = wp.array(np.vstack([vertices.numpy(), [0.0, 0.0, 2.0]]), dtype=wp.vec3)
fin_faces = wp.array(np.concatenate([faces.numpy(), [a, b, 8]]), dtype=wp.int32)
print(od.validation.is_edge_manifold(fin_faces))  # False
new_vertices, new_faces = od.repair.remove_non_manifold_faces(fin_vertices, fin_faces)
print(new_faces.shape[0] // 3, od.validation.is_edge_manifold(new_faces))  # 10 True

method="meshlab" deletes the fin alone, the smallest face on that edge:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.box()
a, b = faces.numpy()[:2]
fin_vertices = wp.array(np.vstack([vertices.numpy(), [0.0, 0.0, 0.2]]), dtype=wp.vec3)
fin_faces = wp.array(np.concatenate([faces.numpy(), [a, b, 8]]), dtype=wp.int32)
_, new_faces = od.repair.remove_non_manifold_faces(fin_vertices, fin_faces, method="meshlab")
print(new_faces.shape[0] // 3, od.validation.is_edge_manifold(new_faces))  # 12 True
Source code in ordito/repair.py
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
def remove_non_manifold_faces(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    max_iter: int = 3,
    *,
    method: Literal["all", "meshlab"] = "all",
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], od.interpolation.Provenance]
):
    """
    Remove faces touching a non-manifold (>2-incident) edge, leaving the mesh edge-manifold.

    Keeps only faces whose three edges are each used by at most two faces
    ([`edge_manifold_mask`][ordito.validation.edge_manifold_mask]). Dropping a face only lowers the
    share count of its own edges, and every edge used three or more times loses all its faces, so
    one pass leaves every edge used at most twice: a further pass would keep every face.

    ``method="meshlab"`` removes fewer faces: visiting the faces on a non-manifold edge from the
    smallest area up (ties by face index), it deletes a face while one of its edges still has more
    than two faces, so each such edge keeps its two largest faces where they do not conflict. A
    duplicated face loses one copy rather than both and its neighbour, and a fin on an edge goes
    alone. This is MeshLab's ``meshing_repair_non_manifold_edges(method="Remove Faces")``; the
    visit runs as rounds in which every face whose smaller rivals on its edges have been decided
    decides at once, so the number of rounds is the longest chain of faces of increasing area
    linked through shared non-manifold edges, one host readback each.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    max_iter
        Maximum number of removal passes. One pass already reaches the fixpoint, so every value
        from ``1`` gives the same answer; ``0`` removes nothing. Unread under
        ``method="meshlab"``, which runs until every face on a non-manifold edge is decided.
    method
        Which faces go.

        - ``"all"`` (default) — every face on a non-manifold edge.
        - ``"meshlab"`` — the smallest first, until each edge is manifold (see above).

        ``"all"`` is the default because it is one pass with no host readback, and its rule reads
        the topology alone, so no face area decides which sheet survives. ``"meshlab"`` removes far
        fewer faces (around a fin it keeps the surface and drops the fin), at the cost of a round of
        readbacks per link in its chain of decisions.
    return_provenance
        If ``True``, also return the [`Provenance`][ordito.interpolation.Provenance] that carries
        any per-vertex or per-face field onto the result.

    Returns
    -------
    new_vertices : wp.array[wp.vec3]
        ``(n_new_vertices,)`` vertices still referenced after non-manifold faces are dropped,
        compacted from index zero; ``vertices`` itself, not a copy, when no face is dropped.
    new_faces : wp.array[wp.int32]
        ``(3 * n_new_faces,)`` flat buffer of the surviving (edge-manifold) faces; ``faces``
        itself, not a copy, when no face is dropped.
    provenance : Provenance
        Only when ``return_provenance`` is ``True``: each output vertex is a copy of an input
        vertex, and each output face of the input face it is.

    Raises
    ------
    ValueError
        If ``method`` is not ``"all"`` or ``"meshlab"``.
    RuntimeError
        If ``vertices`` and ``faces`` are not all on one device.

    See Also
    --------
    [`remove_degenerate_faces`][ordito.repair.remove_degenerate_faces]
    [`remove_degenerate_and_non_manifold_faces`][ordito.repair.remove_degenerate_and_non_manifold_faces]
    [`edge_manifold_mask`][ordito.validation.edge_manifold_mask]

    Examples
    --------
    A fin glued to one edge of a cube gives that edge three faces; all three go:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    a, b = faces.numpy()[:2]
    fin_vertices = wp.array(np.vstack([vertices.numpy(), [0.0, 0.0, 2.0]]), dtype=wp.vec3)
    fin_faces = wp.array(np.concatenate([faces.numpy(), [a, b, 8]]), dtype=wp.int32)
    print(od.validation.is_edge_manifold(fin_faces))  # False
    new_vertices, new_faces = od.repair.remove_non_manifold_faces(fin_vertices, fin_faces)
    print(new_faces.shape[0] // 3, od.validation.is_edge_manifold(new_faces))  # 10 True
    ```

    ``method="meshlab"`` deletes the fin alone, the smallest face on that edge:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    a, b = faces.numpy()[:2]
    fin_vertices = wp.array(np.vstack([vertices.numpy(), [0.0, 0.0, 0.2]]), dtype=wp.vec3)
    fin_faces = wp.array(np.concatenate([faces.numpy(), [a, b, 8]]), dtype=wp.int32)
    _, new_faces = od.repair.remove_non_manifold_faces(fin_vertices, fin_faces, method="meshlab")
    print(new_faces.shape[0] // 3, od.validation.is_edge_manifold(new_faces))  # 12 True
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    if method not in ("all", "meshlab"):
        raise ValueError(f"method must be 'all' or 'meshlab', got {method!r}")
    if method == "meshlab":
        keep = _smallest_first_survivors(vertices, faces)
        if keep is None:
            return _unchanged(vertices, faces, return_provenance)
        if return_provenance:
            return od.selection.submesh_from_face_mask(
                vertices, faces, keep, return_provenance=True
            )
        return od.selection.submesh_from_face_mask(vertices, faces, keep)
    # The radix of the edge keys; any bound above every index groups the edges identically, so the
    # vertex count serves every pass over a subset of the faces, as it does for
    # ``remove_degenerate_and_non_manifold_faces``, with no reduction and readback to infer one.
    survivors, keep = _edge_manifold_survivors(faces, None, vertices.size, max_iter)
    if keep is None:
        return _unchanged(vertices, faces, return_provenance)
    if return_provenance:
        # No prefilter, so the survivors are ``faces`` itself and the mask is over them.
        return od.selection.submesh_from_face_mask(
            vertices, survivors, keep, return_provenance=True
        )
    return od.selection.submesh_from_face_mask(vertices, survivors, keep)

remove_degenerate_and_non_manifold_faces

remove_degenerate_and_non_manifold_faces(
    vertices: array[vec3],
    faces: array[int32],
    max_iter: int = 3,
    *,
    return_provenance: Literal[False] = False,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32]]
remove_degenerate_and_non_manifold_faces(
    vertices: array[vec3],
    faces: array[int32],
    max_iter: int = 3,
    *,
    return_provenance: Literal[True],
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    od.interpolation.Provenance,
]
remove_degenerate_and_non_manifold_faces(
    vertices: array[vec3],
    faces: array[int32],
    max_iter: int = 3,
    *,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        od.interpolation.Provenance,
    ]
)

Drop degenerate faces, then faces on a non-manifold edge, compacting the vertices once.

The same answer as remove_degenerate_faces followed by remove_non_manifold_faces, byte for byte. The manifold test reads only face indices and every compaction preserves the order of both the faces and the vertices, so the manifold pass runs over the input's own vertex numbering and the referenced vertices are compacted once, at the end.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer, every index in [0, n_vertices).

required
max_iter int

Maximum number of non-manifold removal passes, as in remove_non_manifold_faces: every value from 1 gives the same answer.

3
return_provenance bool

If True, also return the Provenance that carries any per-vertex or per-face field onto the result.

False

Returns:

Name Type Description
new_vertices array[vec3]

(n_new_vertices,) vertices still referenced by a surviving face, compacted from index zero.

new_faces array[int32]

(3 * n_new_faces,) flat buffer of the surviving faces, remapped into new_vertices.

provenance Provenance

Only when return_provenance is True: each output vertex is a copy of an input vertex, and each output face of the input face it is.

Raises:

Type Description
RuntimeError

If vertices and faces are not all on one device.

See Also

remove_degenerate_faces remove_non_manifold_faces

Examples:

A cube with a fin on one edge and a zero-area face:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.box()
a, b = faces.numpy()[:2]
broken_vertices = wp.array(np.vstack([vertices.numpy(), [0.0, 0.0, 2.0]]), dtype=wp.vec3)
broken_faces = wp.array(np.concatenate([faces.numpy(), [a, b, 8, 0, 1, 1]]), dtype=wp.int32)
new_vertices, new_faces = od.repair.remove_degenerate_and_non_manifold_faces(
    broken_vertices, broken_faces
)
print(broken_faces.shape[0] // 3, new_faces.shape[0] // 3)  # 14 10
print(od.validation.is_edge_manifold(new_faces))  # True
Source code in ordito/repair.py
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
def remove_degenerate_and_non_manifold_faces(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    max_iter: int = 3,
    *,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], od.interpolation.Provenance]
):
    """
    Drop degenerate faces, then faces on a non-manifold edge, compacting the vertices once.

    The same answer as [`remove_degenerate_faces`][ordito.repair.remove_degenerate_faces]
    followed by [`remove_non_manifold_faces`][ordito.repair.remove_non_manifold_faces], byte for
    byte. The manifold test reads only face indices and every compaction preserves the order of
    both the faces and the vertices, so the manifold pass runs over the input's own vertex
    numbering and the referenced vertices are compacted once, at the end.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer, every index in
        ``[0, n_vertices)``.
    max_iter
        Maximum number of non-manifold removal passes, as in
        [`remove_non_manifold_faces`][ordito.repair.remove_non_manifold_faces]: every value from
        ``1`` gives the same answer.
    return_provenance
        If ``True``, also return the [`Provenance`][ordito.interpolation.Provenance] that carries
        any per-vertex or per-face field onto the result.

    Returns
    -------
    new_vertices : wp.array[wp.vec3]
        ``(n_new_vertices,)`` vertices still referenced by a surviving face, compacted from index
        zero.
    new_faces : wp.array[wp.int32]
        ``(3 * n_new_faces,)`` flat buffer of the surviving faces, remapped into
        ``new_vertices``.
    provenance : Provenance
        Only when ``return_provenance`` is ``True``: each output vertex is a copy of an input
        vertex, and each output face of the input face it is.

    Raises
    ------
    RuntimeError
        If ``vertices`` and ``faces`` are not all on one device.

    See Also
    --------
    [`remove_degenerate_faces`][ordito.repair.remove_degenerate_faces]
    [`remove_non_manifold_faces`][ordito.repair.remove_non_manifold_faces]

    Examples
    --------
    A cube with a fin on one edge and a zero-area face:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    a, b = faces.numpy()[:2]
    broken_vertices = wp.array(np.vstack([vertices.numpy(), [0.0, 0.0, 2.0]]), dtype=wp.vec3)
    broken_faces = wp.array(np.concatenate([faces.numpy(), [a, b, 8, 0, 1, 1]]), dtype=wp.int32)
    new_vertices, new_faces = od.repair.remove_degenerate_and_non_manifold_faces(
        broken_vertices, broken_faces
    )
    print(broken_faces.shape[0] // 3, new_faces.shape[0] // 3)  # 14 10
    print(od.validation.is_edge_manifold(new_faces))  # True
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    if faces.size == 0:
        if return_provenance:
            return (
                _launch.clone(vertices),
                _launch.clone(faces),
                od.interpolation.Provenance.identity(vertices.size, 0, vertices.device),
            )
        return _launch.clone(vertices), _launch.clone(faces)
    # ``triangles.face_nondegenerate_mask`` with the flags its survivors are compacted from, in the
    # one pass.
    n_faces = faces.size // 3
    keep = _launch.empty(n_faces, dtype=wp.bool, device=faces.device)
    keep_flags = _launch.empty(n_faces, dtype=wp.int32, device=faces.device)
    _launch.launch(
        kernel_repair.nondegenerate_face_flags,
        dim=n_faces,
        inputs=[vertices, faces],
        outputs=[keep, keep_flags],
        device=faces.device,
    )
    nondegenerate = keep
    survivors, keep = _edge_manifold_survivors(faces, (keep, keep_flags), vertices.size, max_iter)
    assert keep is not None
    if not return_provenance:
        return od.selection.submesh_from_face_mask(vertices, survivors, keep)
    new_vertices, new_faces, provenance = od.selection.submesh_from_face_mask(
        vertices, survivors, keep, return_provenance=True
    )
    if survivors is not faces:
        # The mask is over the nondegenerate faces, compacted in face order.
        face_index = od.array.gather(od.array.flatnonzero(nondegenerate), provenance.face_index)
        provenance = provenance._replace(face_index=face_index, n_faces=n_faces)
    return new_vertices, new_faces, provenance

remove_small_components

remove_small_components(
    vertices: array[vec3],
    faces: array[int32],
    *,
    keep_largest: bool = False,
    min_faces: int | None = None,
    min_area: float | None = None,
    min_diameter: float | None = None,
    labels: array[int32] | None = None,
    return_provenance: Literal[False] = False,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32]]
remove_small_components(
    vertices: array[vec3],
    faces: array[int32],
    *,
    keep_largest: bool = False,
    min_faces: int | None = None,
    min_area: float | None = None,
    min_diameter: float | None = None,
    labels: array[int32] | None = None,
    return_provenance: Literal[True],
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    od.interpolation.Provenance,
]
remove_small_components(
    vertices: array[vec3],
    faces: array[int32],
    *,
    keep_largest: bool = False,
    min_faces: int | None = None,
    min_area: float | None = None,
    min_diameter: float | None = None,
    labels: array[int32] | None = None,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        od.interpolation.Provenance,
    ]
)

Drop face-connected components that are too small, by one of four measures of "small".

Debris -- a stray shell from a scan, a sliver left by a boolean, a component a decimation stranded -- is what every repair pipeline removes first, and until now combine.split handed back every component and left the caller to write the argmax. This is that step, and it stays on the device: the per-component statistic is accumulated by one scatter and thresholded by one kernel, so nothing is read back and no component is ever materialized as its own mesh.

Exactly one criterion may be given, because they are four different questions rather than four spellings of one and combining them would hide which one rejected a component:

  • keep_largest keeps the single component with the most faces and drops every other, so the result always has exactly one component. Face count, not area or diameter: a small dense shell outranks a large coarse one. A tie goes to the component whose lowest face index is smallest, which makes the choice deterministic rather than dependent on thread order.
  • min_faces keeps components with at least that many faces -- scale-free, and the measure that tracks how much data a component carries.
  • min_area keeps components whose summed triangle area reaches it.
  • min_diameter keeps components whose axis-aligned bounding-box diagonal reaches it, which is the measure that survives a component being a thin sheet of many tiny triangles.

All three min_* bounds are inclusive, matching the reference implementations: a component of exactly the threshold face count, or of exactly the threshold diagonal, survives.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
keep_largest bool

Keep only the component with the most faces.

False
min_faces int | None

Minimum face count for a component to be kept.

None
min_area float | None

Minimum summed triangle area for a component to be kept. Under is_deterministic each component's area is summed exactly, so a component at the threshold is kept or dropped the same way on every call.

None
min_diameter float | None

Minimum bounding-box diagonal for a component to be kept.

None
labels array[int32] | None

(n_faces,) face component labels of faces, each a face id naming its component, as face_connected_component_labels returns them (Trimesh.face_connected_component_labels), to spare the labelling. Trusted, not checked.

None
return_provenance bool

If True, also return the Provenance that carries any per-vertex or per-face field onto the result.

False

Returns:

Name Type Description
new_vertices array[vec3]

(n_new_vertices,) vertices of the surviving components, compacted from index zero.

new_faces array[int32]

(3 * n_new_faces,) flat buffer of the surviving faces, in their input order.

provenance Provenance

Only when return_provenance is True: each output vertex is a copy of an input vertex, and each output face of the input face it is.

Raises:

Type Description
ValueError

If no criterion is given, or if more than one is.

RuntimeError

If vertices, faces and labels are not all on one device.

See Also

combine.split The whole decomposition, when every component is wanted rather than a subset. holes.join_closest_components The other answer to a multi-component mesh -- weld the pieces together instead of discarding them. adjacency.face_connected_component_labels The labelling this thresholds. remove_non_manifold_faces

Notes

A component's label is a representative face index rather than a dense 0..k-1 id, so the per-component statistic is an n_faces-long array of which only k slots are ever written. That is deliberate: densifying the labels first would cost a sort and a search per face to save an allocation, and it is the allocation that is cheap.

Examples:

A small tetrahedron floating beside a sphere is dropped, whether by keeping the largest component or by a face-count threshold:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
debris_vertices, debris_faces = od.creation.tetrahedron()
noisy_vertices = wp.array(
    np.concatenate([vertices.numpy(), 0.1 * debris_vertices.numpy() + 3.0]), dtype=wp.vec3
)
noisy_faces = wp.array(
    np.concatenate([faces.numpy(), debris_faces.numpy() + vertices.shape[0]]), dtype=wp.int32
)
print(noisy_vertices.shape, noisy_faces.shape[0] // 3)  # (166,) 324
kept_vertices, kept_faces = od.repair.remove_small_components(
    noisy_vertices, noisy_faces, keep_largest=True
)
print(kept_vertices.shape, kept_faces.shape[0] // 3)  # (162,) 320
kept_vertices, kept_faces = od.repair.remove_small_components(
    noisy_vertices, noisy_faces, min_faces=10
)
print(kept_vertices.shape, kept_faces.shape[0] // 3)  # (162,) 320
Source code in ordito/repair.py
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
def remove_small_components(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    keep_largest: bool = False,
    min_faces: int | None = None,
    min_area: float | None = None,
    min_diameter: float | None = None,
    labels: wp.array[wp.int32] | None = None,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], od.interpolation.Provenance]
):
    """
    Drop face-connected components that are too small, by one of four measures of "small".

    Debris -- a stray shell from a scan, a sliver left by a boolean, a component a decimation
    stranded -- is what every repair pipeline removes first, and until now
    [`combine.split`][ordito.combine.split] handed back *every* component and left the caller to
    write the argmax. This is that step, and it stays on the device: the per-component statistic is
    accumulated by one scatter and thresholded by one kernel, so nothing is read back and no
    component is ever materialized as its own mesh.

    Exactly one criterion may be given, because they are four different questions rather than four
    spellings of one and combining them would hide which one rejected a component:

    - ``keep_largest`` keeps the single component with the **most faces** and drops every other, so
      the result always has exactly one component. Face count, not area or diameter: a small dense
      shell outranks a large coarse one. A tie goes to the component whose lowest face index is
      smallest, which makes the choice deterministic rather than dependent on thread order.
    - ``min_faces`` keeps components with at least that many faces -- scale-free, and the measure
      that tracks *how much data* a component carries.
    - ``min_area`` keeps components whose summed triangle area reaches it.
    - ``min_diameter`` keeps components whose axis-aligned bounding-box diagonal reaches it, which
      is the measure that survives a component being a thin sheet of many tiny triangles.

    All three ``min_*`` bounds are **inclusive**, matching the reference implementations: a
    component of exactly the threshold face count, or of exactly the threshold diagonal, survives.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    keep_largest
        Keep only the component with the most faces.
    min_faces
        Minimum face count for a component to be kept.
    min_area
        Minimum summed triangle area for a component to be kept. Under
        [`is_deterministic`][ordito.config.is_deterministic] each component's area is summed
        exactly, so a component at the threshold is kept or dropped the same way on every call.
    min_diameter
        Minimum bounding-box diagonal for a component to be kept.
    labels
        ``(n_faces,)`` face component labels of ``faces``, each a face id naming its component, as
        [`face_connected_component_labels`][ordito.adjacency.face_connected_component_labels]
        returns them
        ([`Trimesh.face_connected_component_labels`][ordito.mesh.Trimesh.face_connected_component_labels]),
        to spare the labelling. Trusted, not checked.
    return_provenance
        If ``True``, also return the [`Provenance`][ordito.interpolation.Provenance] that carries
        any per-vertex or per-face field onto the result.

    Returns
    -------
    new_vertices : wp.array[wp.vec3]
        ``(n_new_vertices,)`` vertices of the surviving components, compacted from index zero.
    new_faces : wp.array[wp.int32]
        ``(3 * n_new_faces,)`` flat buffer of the surviving faces, in their input order.
    provenance : Provenance
        Only when ``return_provenance`` is ``True``: each output vertex is a copy of an input
        vertex, and each output face of the input face it is.

    Raises
    ------
    ValueError
        If no criterion is given, or if more than one is.
    RuntimeError
        If ``vertices``, ``faces`` and ``labels`` are not all on one device.

    See Also
    --------
    [`combine.split`][ordito.combine.split]
        The whole decomposition, when every component is wanted rather than a subset.
    [`holes.join_closest_components`][ordito.holes.join_closest_components]
        The other answer to a multi-component mesh -- weld the pieces together instead of
        discarding them.
    [`adjacency.face_connected_component_labels`][ordito.adjacency.face_connected_component_labels]
        The labelling this thresholds.
    [`remove_non_manifold_faces`][ordito.repair.remove_non_manifold_faces]

    Notes
    -----
    A component's label is a representative *face* index rather than a dense ``0..k-1`` id, so the
    per-component statistic is an ``n_faces``-long array of which only ``k`` slots are ever written.
    That is deliberate: densifying the labels first would cost a sort and a search per face to save
    an allocation, and it is the allocation that is cheap.

    Examples
    --------
    A small tetrahedron floating beside a sphere is dropped, whether by keeping the largest
    component or by a face-count threshold:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    debris_vertices, debris_faces = od.creation.tetrahedron()
    noisy_vertices = wp.array(
        np.concatenate([vertices.numpy(), 0.1 * debris_vertices.numpy() + 3.0]), dtype=wp.vec3
    )
    noisy_faces = wp.array(
        np.concatenate([faces.numpy(), debris_faces.numpy() + vertices.shape[0]]), dtype=wp.int32
    )
    print(noisy_vertices.shape, noisy_faces.shape[0] // 3)  # (166,) 324
    kept_vertices, kept_faces = od.repair.remove_small_components(
        noisy_vertices, noisy_faces, keep_largest=True
    )
    print(kept_vertices.shape, kept_faces.shape[0] // 3)  # (162,) 320
    kept_vertices, kept_faces = od.repair.remove_small_components(
        noisy_vertices, noisy_faces, min_faces=10
    )
    print(kept_vertices.shape, kept_faces.shape[0] // 3)  # (162,) 320
    ```
    """
    require_same_device(vertices=vertices, faces=faces, labels=labels)
    given = (keep_largest, min_faces is not None, min_area is not None, min_diameter is not None)
    if sum(given) != 1:
        raise ValueError(
            "pass exactly one of keep_largest, min_faces, min_area or min_diameter, "
            f"got {sum(given)}"
        )
    new_vertices, new_faces, provenance = _remove_small_components(
        vertices,
        faces,
        min_faces=min_faces,
        min_area=min_area,
        min_diameter=min_diameter,
        labels=labels,
        with_provenance=return_provenance,
    )
    if provenance is None:
        return new_vertices, new_faces
    return new_vertices, new_faces, provenance

split_non_manifold_vertices

split_non_manifold_vertices(
    vertices: array[vec3],
    faces: array[int32],
    *,
    mates: array[int32] | None = None,
    return_provenance: Literal[False] = False,
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    wp.array[wp.int32],
]
split_non_manifold_vertices(
    vertices: array[vec3],
    faces: array[int32],
    *,
    mates: array[int32] | None = None,
    return_provenance: Literal[True],
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    wp.array[wp.int32],
    od.interpolation.Provenance,
]
split_non_manifold_vertices(
    vertices: array[vec3],
    faces: array[int32],
    *,
    mates: array[int32] | None = None,
    return_provenance: bool = False,
) -> (
    tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        wp.array[wp.int32],
    ]
    | tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        wp.array[wp.int32],
        od.interpolation.Provenance,
    ]
)

Make a mesh manifold and orientable by duplicating vertices, keeping every face.

The non-lossy counterpart of remove_non_manifold_faces, which deletes geometry to reach the same property: this changes no position and drops no triangle, it only splits vertices apart, so the surface is unchanged and the face count is exactly preserved. Use it to feed a mesh to code that requires manifold input -- several reference libraries (e.g. potpourri3d) reject non-manifold meshes outright, and so do ordito's own halfedge consumers.

Two corners are kept together only across an edge that is manifold and consistently oriented: exactly one half-edge each way. Every other edge -- a boundary edge, one shared by three or more faces, or one whose two faces traverse it the same way -- separates the copies. So a bowtie vertex splits in two, an edge with three faces splits into three boundary edges, and a flipped face is cut free of its neighbours rather than reoriented (that is make_winding_consistent's job, and running it first leaves less to split).

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
mates array[int32] | None

(3 * n_faces,) halfedge_mates of faces when the caller holds them (Trimesh.halfedge_mates), to spare pairing the halfedges again. Trusted, not checked.

None
return_provenance bool

If True, also return the Provenance that carries any per-vertex or per-face field onto the result.

False

Returns:

Name Type Description
new_vertices array[vec3]

(n_new,) positions with n_new >= n_referenced; each is a copy of the original vertex it came from, so the point set is unchanged as a set.

new_faces array[int32]

(3 * n_faces,) flat buffer of the same n_faces triangles in input order, indexing new_vertices.

source array[int32]

(n_new,) map from each new vertex to the original it duplicates, so new_vertices == vertices[source] and a per-vertex attribute transfers with gather. This is igl.split_nonmanifold's SVI.

provenance Provenance

Only when return_provenance is True: each output vertex is a copy of source, and the faces are the input faces in order.

Raises:

Type Description
RuntimeError

If vertices, faces and mates are not all on one device.

Notes

Vertices unreferenced by any face are dropped, since a new vertex only exists as some face's corner -- the same convention as remove_unreferenced_vertices, and the reason this function cannot simply return an n_vertices-length remap.

Remove degenerate faces first, with remove_degenerate_faces: a triangle with a repeated index has two corners at one vertex that no edge can join, so it survives as two copies of that vertex and the face stays degenerate.

The implementation is a connected-components pass over a graph of 3 * n_faces corner nodes rather than a per-vertex star walk: the half-edges are paired by their undirected edge, and a union-find joins the two corner pairs of every edge whose pair runs it both ways, as connected_component_labels_from_edges does for an edge list. igl::split_nonmanifold instead explodes the mesh to 3 * n_faces singleton vertices and greedily re-merges pairs, re-testing manifoldness after each candidate -- order-dependent and sequential by construction. The two agree exactly on a manifold mesh, a bowtie vertex, a consistently-wound fan of three faces on one edge, a flipped face and an open boundary.

They differ on one input class, by design. Where an edge carries one half-edge in one direction and several in the other -- which is what a duplicated face produces -- igl keeps one arbitrarily chosen pair joined, while this splits every copy. Both results are edge- and vertex-manifold with the input's face count; this one is order-independent and makes no arbitrary choice. Note that resolve_duplicated_faces is not a way around the difference: the cancellation rules it implements cover a +1/-1 imbalance, so a face duplicated in the same orientation makes it raise rather than dropping the copy.

See Also

remove_non_manifold_faces make_winding_consistent remove_degenerate_faces is_edge_manifold igl.split_nonmanifold

Examples:

Two cubes touching at one corner share a bowtie vertex; splitting it adds one vertex and keeps all 24 faces:

import numpy as np
import warp as wp

import ordito as od

lower_vertices, lower_faces = od.creation.box(bounds=[[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
upper_vertices, upper_faces = od.creation.box(bounds=[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]])
vertices = wp.array(np.vstack([lower_vertices.numpy(), upper_vertices.numpy()]), dtype=wp.vec3)
faces = wp.array(np.concatenate([lower_faces.numpy(), upper_faces.numpy() + 8]), dtype=wp.int32)
vertices, _, _, faces = od.repair.remove_duplicated_vertices(vertices, faces, epsilon=1e-6)
print(vertices.shape, od.validation.is_vertex_manifold(faces))  # (15,) False
new_vertices, new_faces, source = od.repair.split_non_manifold_vertices(vertices, faces)
print(new_vertices.shape, new_faces.shape[0] // 3)  # (16,) 24
print(od.validation.is_vertex_manifold(new_faces))  # True
Source code in ordito/repair.py
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
def split_non_manifold_vertices(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    mates: wp.array[wp.int32] | None = None,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32], wp.array[wp.int32]]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], wp.array[wp.int32], od.interpolation.Provenance]
):
    """

    Make a mesh manifold and orientable by duplicating vertices, keeping every face.

    The non-lossy counterpart of
    [`remove_non_manifold_faces`][ordito.repair.remove_non_manifold_faces], which deletes geometry
    to reach the same property: this changes no position and drops no triangle, it only splits
    vertices apart, so the surface is unchanged and the face count is exactly preserved. Use it to
    feed a mesh to code that requires manifold input -- several reference libraries (e.g.
    potpourri3d) reject non-manifold meshes outright, and so do ordito's own halfedge consumers.

    Two corners are kept together only across an edge that is **manifold and consistently
    oriented**: exactly one half-edge each way. Every other edge -- a boundary edge, one shared by
    three or more faces, or one whose two faces traverse it the same way -- separates the copies. So
    a bowtie vertex splits in two, an edge with three faces splits into three boundary edges, and a
    flipped face is cut free of its neighbours rather than reoriented (that is
    [`make_winding_consistent`][ordito.repair.make_winding_consistent]'s job, and running it first
    leaves less to split).


    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    mates
        ``(3 * n_faces,)`` [`halfedge_mates`][ordito.halfedge.halfedge_mates] of ``faces`` when the
        caller holds them ([`Trimesh.halfedge_mates`][ordito.mesh.Trimesh.halfedge_mates]), to spare
        pairing the halfedges again. Trusted, not checked.
    return_provenance
        If ``True``, also return the [`Provenance`][ordito.interpolation.Provenance] that carries
        any per-vertex or per-face field onto the result.

    Returns
    -------
    new_vertices : wp.array[wp.vec3]
        ``(n_new,)`` positions with ``n_new >= n_referenced``; each is a copy of the original vertex
        it came from, so the point set is unchanged as a *set*.
    new_faces : wp.array[wp.int32]
        ``(3 * n_faces,)`` flat buffer of the same ``n_faces`` triangles in input order, indexing
        ``new_vertices``.
    source : wp.array[wp.int32]
        ``(n_new,)`` map from each new vertex to the original it duplicates, so
        ``new_vertices == vertices[source]`` and a per-vertex attribute transfers with
        [`gather`][ordito.array.gather]. This is ``igl.split_nonmanifold``'s ``SVI``.
    provenance : Provenance
        Only when ``return_provenance`` is ``True``: each output vertex is a copy of ``source``,
        and the faces are the input faces in order.

    Raises
    ------
    RuntimeError
        If ``vertices``, ``faces`` and ``mates`` are not all on one device.

    Notes
    -----
    Vertices unreferenced by any face are **dropped**, since a new vertex only exists as some face's
    corner -- the same convention as
    [`remove_unreferenced_vertices`][ordito.repair.remove_unreferenced_vertices], and the reason
    this function cannot simply return an ``n_vertices``-length remap.

    Remove degenerate faces first, with
    [`remove_degenerate_faces`][ordito.repair.remove_degenerate_faces]: a triangle with a repeated
    index has two corners at one vertex that no edge can join, so it survives as two copies of that
    vertex and the face stays degenerate.

    The implementation is a connected-components pass over a graph of ``3 * n_faces`` corner nodes
    rather than a per-vertex star walk: the half-edges are paired by their undirected edge, and a
    union-find joins the two corner pairs of every edge whose pair runs it both ways, as
    [`connected_component_labels_from_edges`][ordito.graph.connected_component_labels_from_edges]
    does for an edge list. ``igl::split_nonmanifold`` instead explodes the mesh to ``3 * n_faces``
    singleton vertices and greedily re-merges pairs, re-testing manifoldness after each candidate --
    order-dependent and sequential by construction. The two agree exactly on a manifold mesh, a
    bowtie vertex, a consistently-wound fan of three faces on one edge, a flipped face and an open
    boundary.

    **They differ on one input class, by design.** Where an edge carries one half-edge in one
    direction and *several* in the other -- which is what a duplicated face produces -- igl keeps
    one arbitrarily chosen pair joined, while this splits every copy. Both results are edge- and
    vertex-manifold with the input's face count; this one is order-independent and makes no
    arbitrary choice. Note that
    [`resolve_duplicated_faces`][ordito.repair.resolve_duplicated_faces] is not a way around the
    difference: the cancellation rules it implements cover a ``+1``/``-1`` imbalance, so a face
    duplicated in the *same* orientation makes it raise rather than dropping the copy.

    See Also
    --------
    [`remove_non_manifold_faces`][ordito.repair.remove_non_manifold_faces]
    [`make_winding_consistent`][ordito.repair.make_winding_consistent]
    [`remove_degenerate_faces`][ordito.repair.remove_degenerate_faces]
    [`is_edge_manifold`][ordito.validation.is_edge_manifold]
    ``igl.split_nonmanifold``

    Examples
    --------
    Two cubes touching at one corner share a bowtie vertex; splitting it adds one vertex and keeps
    all 24 faces:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    lower_vertices, lower_faces = od.creation.box(bounds=[[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]])
    upper_vertices, upper_faces = od.creation.box(bounds=[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]])
    vertices = wp.array(np.vstack([lower_vertices.numpy(), upper_vertices.numpy()]), dtype=wp.vec3)
    faces = wp.array(np.concatenate([lower_faces.numpy(), upper_faces.numpy() + 8]), dtype=wp.int32)
    vertices, _, _, faces = od.repair.remove_duplicated_vertices(vertices, faces, epsilon=1e-6)
    print(vertices.shape, od.validation.is_vertex_manifold(faces))  # (15,) False
    new_vertices, new_faces, source = od.repair.split_non_manifold_vertices(vertices, faces)
    print(new_vertices.shape, new_faces.shape[0] // 3)  # (16,) 24
    print(od.validation.is_vertex_manifold(new_faces))  # True
    ```
    """
    require_same_device(vertices=vertices, faces=faces, mates=mates)
    device = faces.device
    n_faces = faces.size // 3
    if n_faces == 0:
        empty_index = _launch.empty(0, dtype=wp.int32, device=device)
        new_vertices = _launch.empty(0, dtype=wp.vec3, device=vertices.device)
        if return_provenance:
            provenance = od.interpolation.Provenance(
                empty_index, empty_index, None, vertices.size, 0
            )
            return new_vertices, faces, empty_index, provenance
        return new_vertices, faces, empty_index

    if mates is None:
        mates = od.halfedge.halfedge_mates(faces, vertices.size)
    new_vertices, new_faces, source = _split_corners(vertices, faces, mates)
    if not return_provenance:
        return new_vertices, new_faces, source
    provenance = od.interpolation.Provenance(
        source, od.array.arange(n_faces, device=device), None, vertices.size, n_faces
    )
    return new_vertices, new_faces, source, provenance

collapse_small_triangles

collapse_small_triangles(
    vertices: array[vec3],
    faces: array[int32],
    epsilon: float = 1e-06,
    *,
    bounds: tuple[vec3, vec3] | None = None,
    return_provenance: Literal[False] = False,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32]]
collapse_small_triangles(
    vertices: array[vec3],
    faces: array[int32],
    epsilon: float = 1e-06,
    *,
    bounds: tuple[vec3, vec3] | None = None,
    return_provenance: Literal[True],
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    od.interpolation.Provenance,
]
collapse_small_triangles(
    vertices: array[vec3],
    faces: array[int32],
    epsilon: float = 1e-06,
    *,
    bounds: tuple[vec3, vec3] | None = None,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        od.interpolation.Provenance,
    ]
)

Collapse triangles smaller than a bounding-box-relative area threshold.

Mirrors igl::collapse_small_triangles. A triangle is small when its doubled area is below 2 * epsilon * bbd ** 2, where bbd is the diagonal of the axis-aligned bounding box of vertices. Each small triangle has its shortest edge collapsed by merging that edge's two endpoints; the merged face (now carrying a repeated vertex) is discarded. The process repeats to a fixpoint, so triangles that only become small after a neighbouring collapse are also removed.

This subsumes degenerate-triangle removal: an exactly degenerate face (zero area) is always below the threshold, so passing a small epsilon removes it. To drop only degenerate faces without any bounding-box-relative collapsing, use remove_degenerate_faces.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
epsilon float

Relative area tolerance. The doubled-area threshold is 2 * epsilon * bbd ** 2; larger values collapse more (and larger) triangles.

1e-06
bounds tuple[vec3, vec3] | None

The box enclosing vertices when the caller holds it, typically Trimesh.bounds. Its diagonal scales epsilon, so passing it spares the reduction and readback that measure the box again. Trusted, not checked.

None
return_provenance bool

If True, also return the Provenance that carries any per-vertex or per-face field onto the result.

False

Returns:

Name Type Description
new_vertices array[vec3]

(n_new_vertices,) vertices surviving the collapse, compacted from index zero.

new_faces array[int32]

(3 * n_new_faces,) flat buffer of the surviving faces, remapped into new_vertices.

provenance Provenance

Only when return_provenance is True: each output vertex is a copy of the vertex its collapsed class kept (whose position it has), and each output face of the input face it is, its corners moved onto those vertices.

Raises:

Type Description
RuntimeError

If vertices and faces are not all on one device.

See Also

remove_degenerate_faces face_nondegenerate_mask fix_degeneracies

Notes

Where igl::collapse_small_triangles merges vertices by a sequentially updated index map and recurses until no edge collapses, this resolves all shortest-edge merges of one pass at once via the connected-components closure of connected_component_labels_from_edges, then loops over the shrinking mesh. Both converge to a mesh with no sub-threshold triangle. The surviving vertex of a collapsed edge keeps the position of the component representative (the lowest original index in its class) rather than libigl's longest-edge-preserving endpoint; for sub-threshold triangles the two endpoints are close enough that the difference is negligible. The bounding-box diagonal is measured once on the input vertices so the threshold is fixed across iterations.

Examples:

Moving a grid vertex onto its neighbour crushes the two triangles between them; collapsing merges the pair:

import warp as wp

import ordito as od

vertices, faces = od.creation.grid(count=(4, 4))
positions = vertices.numpy()
positions[6] = positions[5] + [1e-5, 0.0, 0.0]
crushed = wp.array(positions, dtype=wp.vec3)
new_vertices, new_faces = od.repair.collapse_small_triangles(crushed, faces)
print(vertices.shape, faces.shape[0] // 3)  # (16,) 18
print(new_vertices.shape, new_faces.shape[0] // 3)  # (15,) 16
Source code in ordito/repair.py
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
def collapse_small_triangles(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    epsilon: float = 1e-6,
    *,
    bounds: tuple[wp.vec3, wp.vec3] | None = None,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], od.interpolation.Provenance]
):
    """
    Collapse triangles smaller than a bounding-box-relative area threshold.

    Mirrors ``igl::collapse_small_triangles``. A triangle is *small* when its doubled area is below
    ``2 * epsilon * bbd ** 2``, where ``bbd`` is the diagonal of the axis-aligned bounding box of
    ``vertices``. Each small triangle has its **shortest edge** collapsed by merging that edge's two
    endpoints; the merged face (now carrying a repeated vertex) is discarded. The process repeats to
    a fixpoint, so triangles that only become small after a neighbouring collapse are also removed.

    This subsumes degenerate-triangle removal: an exactly degenerate face (zero area) is always
    below the threshold, so passing a small ``epsilon`` removes it. To drop only degenerate faces
    without any bounding-box-relative collapsing, use
    [`remove_degenerate_faces`][ordito.repair.remove_degenerate_faces].

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    epsilon
        Relative area tolerance. The doubled-area threshold is ``2 * epsilon * bbd ** 2``; larger
        values collapse more (and larger) triangles.
    bounds
        The box enclosing ``vertices`` when the caller holds it, typically
        [`Trimesh.bounds`][ordito.mesh.Trimesh.bounds]. Its diagonal scales ``epsilon``, so passing
        it spares the reduction and readback that measure the box again. Trusted, not checked.
    return_provenance
        If ``True``, also return the [`Provenance`][ordito.interpolation.Provenance] that carries
        any per-vertex or per-face field onto the result.

    Returns
    -------
    new_vertices : wp.array[wp.vec3]
        ``(n_new_vertices,)`` vertices surviving the collapse, compacted from index zero.
    new_faces : wp.array[wp.int32]
        ``(3 * n_new_faces,)`` flat buffer of the surviving faces, remapped into
        ``new_vertices``.
    provenance : Provenance
        Only when ``return_provenance`` is ``True``: each output vertex is a copy of the vertex
        its collapsed class kept (whose position it has), and each output face of the input face
        it is, its corners moved onto those vertices.

    Raises
    ------
    RuntimeError
        If ``vertices`` and ``faces`` are not all on one device.

    See Also
    --------
    [`remove_degenerate_faces`][ordito.repair.remove_degenerate_faces]
    [`face_nondegenerate_mask`][ordito.triangles.face_nondegenerate_mask]
    [`fix_degeneracies`][ordito.repair.fix_degeneracies]

    Notes
    -----
    Where ``igl::collapse_small_triangles`` merges vertices by a sequentially updated index map and
    recurses until no edge collapses, this resolves all shortest-edge merges of one pass at once via
    the connected-components closure of
    [`connected_component_labels_from_edges`][ordito.graph.connected_component_labels_from_edges],
    then loops over the shrinking mesh. Both converge to a mesh with no sub-threshold triangle. The
    surviving vertex of a collapsed edge keeps the position of the component representative (the
    lowest original index in its class) rather than libigl's longest-edge-preserving endpoint; for
    sub-threshold triangles the two endpoints are close enough that the difference is negligible.
    The bounding-box diagonal is measured once on the input ``vertices`` so the threshold is fixed
    across iterations.

    Examples
    --------
    Moving a grid vertex onto its neighbour crushes the two triangles between them; collapsing
    merges the pair:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.grid(count=(4, 4))
    positions = vertices.numpy()
    positions[6] = positions[5] + [1e-5, 0.0, 0.0]
    crushed = wp.array(positions, dtype=wp.vec3)
    new_vertices, new_faces = od.repair.collapse_small_triangles(crushed, faces)
    print(vertices.shape, faces.shape[0] // 3)  # (16,) 18
    print(new_vertices.shape, new_faces.shape[0] // 3)  # (15,) 16
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    device = faces.device
    n_faces = faces.size // 3
    if n_faces == 0 or vertices.size == 0:
        return _unchanged(_launch.clone(vertices), _launch.clone(faces), return_provenance)

    bbd = (
        od.bounds.enclosing_diagonal(vertices)
        if bounds is None
        else od.bounds.box_diagonal(*bounds)
    )
    min_dbl_area = wp.float32(2.0 * epsilon * bbd * bbd)

    current_vertices = vertices
    current_faces = faces
    max_iterations = faces.size  # bounded: each collapsing pass drops at least one face
    # Two small-face counters for the whole loop, never reset: slot 0 counts the input's small faces
    # as the first pass finds them, slot 1 the small faces each pass leaves behind, counted by the
    # remap that decides them. So the stopping test is one 4-byte read rather than a per-face flag
    # buffer reduced on the device first, a pass left none exactly when slot 1 did not move, and
    # the pass after the last collapse is never launched.
    n_small = _launch.zeros(2, dtype=wp.int32, device=device)
    n_left = odt.as_dense(n_small[1:])
    small_so_far = 0
    # The passes' provenances chained, each a compaction's vertex map and kept faces.
    provenance = (
        od.interpolation.Provenance.identity(vertices.size, n_faces, device)
        if return_provenance
        else None
    )
    for iteration in range(max_iterations):
        n_current = current_faces.size // 3
        if n_current == 0:
            break

        n_vertices = current_vertices.size
        # The pass's unfilled ``int32`` tables in one allocation: the collapse pairs and the
        # remapped corners, both written whole. The submesh marks need their zero, which a pass
        # that collapses nothing would pay for, so they are allocated past that test.
        pair_rows, remapped_faces = _launch.carve(
            wp.int32, [2 * n_current, current_faces.size], device
        )
        pairs = odt.as_array2d(pair_rows.reshape((n_current, 2)), wp.int32)
        _launch.launch(
            kernel_repair.small_triangle_collapse_edges,
            dim=n_current,
            inputs=[current_vertices, current_faces, min_dbl_area, pairs, n_small],
            device=device,
        )
        if iteration == 0 and int(read_scalar(n_small, 0)) == 0:
            break

        # Non-flagged faces emit a self-pair (i0, i0); these are self-loops that leave the
        # connected-components closure unchanged, so all rows can be passed without filtering.
        # ``validate=False``: the pairs are vertex indices read straight out of the face buffer
        # this function is repairing, which every kernel around it already indexes unchecked.
        labels = od.graph.connected_component_labels_from_edges(
            pairs, node_count=n_vertices, validate=False
        )

        # Each label is its class's smallest vertex, so remapping every corner to its label points
        # it at the representative's own position, with no dense class numbering built first. One
        # pass remaps the corners, keeps the faces ``triangles.face_nondegenerate_mask`` would
        # keep, and marks them for the submesh extraction, which then keeps exactly the vertices the
        # surviving faces name -- only representatives -- in ascending index order, which is
        # ascending label order. ``wp.empty``: the pass writes every mask entry.
        keep_mask = _launch.empty(n_current, dtype=wp.bool, device=device)
        ranks = _launch.zeros(n_current + n_vertices, dtype=wp.int32, device=device)
        _launch.launch(
            kernel_repair.remap_mark_nondegenerate_faces,
            dim=n_current,
            inputs=[current_vertices, current_faces, labels, min_dbl_area],
            outputs=[remapped_faces, keep_mask, ranks, n_left],
            device=device,
        )
        pass_vertices = current_vertices
        current_vertices, current_faces, vertex_index, _ranks = _compact_marked_submesh(
            current_vertices,
            remapped_faces,
            keep_mask,
            ranks,
            keep_masked=True,
            with_index=return_provenance,
        )
        if provenance is not None:
            assert vertex_index is not None
            provenance = provenance.then(
                od.interpolation.Provenance(
                    vertex_index,
                    od.array.flatnonzero(keep_mask),
                    None,
                    pass_vertices.size,
                    n_current,
                )
            )
        small_total = int(read_scalar(n_small, 1))
        if small_total == small_so_far:
            break
        small_so_far = small_total

    if provenance is None:
        return current_vertices, current_faces
    return current_vertices, current_faces, provenance

fix_degeneracies

fix_degeneracies(
    vertices: array[vec3],
    faces: array[int32],
    max_deviation: float,
    *,
    tiny_edge_length: float = 0.0,
    critical_aspect_ratio: float = 10000.0,
    max_angle_change: float = 60.0,
    region_rings: int = 3,
    max_iter: int = 10,
    return_provenance: Literal[False] = False,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32]]
fix_degeneracies(
    vertices: array[vec3],
    faces: array[int32],
    max_deviation: float,
    *,
    tiny_edge_length: float = 0.0,
    critical_aspect_ratio: float = 10000.0,
    max_angle_change: float = 60.0,
    region_rings: int = 3,
    max_iter: int = 10,
    return_provenance: Literal[True],
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    od.interpolation.Provenance,
]
fix_degeneracies(
    vertices: array[vec3],
    faces: array[int32],
    max_deviation: float,
    *,
    tiny_edge_length: float = 0.0,
    critical_aspect_ratio: float = 10000.0,
    max_angle_change: float = 60.0,
    region_rings: int = 3,
    max_iter: int = 10,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        od.interpolation.Provenance,
    ]
)

Remove needle and cap triangles and tiny edges by local flips and collapses around them.

A triangle is degenerate when its aspect ratio (circumradius over twice the inradius, the aspect_ratio of face_quality) reaches critical_aspect_ratio. The repair works in a region: the degenerate faces and those on an edge no longer than tiny_edge_length, grown by region_rings rings of neighbouring faces. Inside it, two local moves alternate until no collapse remains:

  • Flip every edge whose other diagonal makes the smaller larger circumcircle (on planar input the Delaunay test of flip_to_delaunay), when the flip moves the surface by at most max_deviation and changes the dihedral angle across it by at most max_angle_change (a quad holding a degenerate face may exceed the angle). This is what fixes a cap, whose apex sits on its long edge.
  • Collapse every edge no longer than max_deviation, shortest first, into the endpoint whose removal moves the surface least. This is what fixes a needle. A collapse that would leave a face of aspect ratio above 20 is skipped, unless a face it touches was already worse or its edge is no longer than tiny_edge_length.

The surface keeps its topology: a collapse that would pinch a handle or a sheet shut (the link condition) is skipped, as is one that would fold a face over unless a degenerate face is involved, and boundary vertices stay on the boundary.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions. Never modified.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
max_deviation float

Longest edge collapsed and largest surface move of a flip, in mesh units. A collapse keeps one endpoint in place, so it too moves the surface by at most this length.

required
tiny_edge_length float

Edges no longer than this collapse whatever the shape they leave, and seed the region.

0.0
critical_aspect_ratio float

Aspect ratio from which a triangle counts as degenerate (1 is equilateral).

10000.0
max_angle_change float

Largest change of dihedral angle, in degrees, a flip may make.

60.0
region_rings int

Rings of faces the region extends past the faces that seed it.

3
max_iter int

Cap on the alternating flip-and-collapse rounds.

10
return_provenance bool

If True, also return the Provenance that carries any per-vertex or per-face field onto the result.

False

Returns:

Name Type Description
vertices array[vec3]

(n_new_vertices,) vertex positions, compacted from index zero when a collapse ran.

faces array[int32]

(3 * n_new_faces,) flat triangle index buffer.

provenance Provenance

Only when return_provenance is True: each output vertex is the endpoint a collapse kept in place, so it copies that input vertex, and each output face names the input face whose slot it holds after the flips and collapses rewrote its corners.

Raises:

Type Description
ValueError

If max_deviation, tiny_edge_length or region_rings is negative, critical_aspect_ratio is below 1, or max_angle_change is outside [0, 180].

RuntimeError

If vertices and faces are not all on one device.

See Also

collapse_small_triangles flip_t_vertices ordito.remesh.flip_to_delaunay

Notes

The collapses of one pass are a conflict-free independent set, each neighbourhood's winner chosen by a hashed priority rather than by length, so they are applied together but never overlap; the sequence differs from a serial shortest-edge-first queue, and so does the triangulation it ends on. The region is fixed when the call starts and follows the surviving vertices, so the moves never spread past it. A degenerate triangle no move can fix (a cap on the boundary, a needle whose collapse would leave worse faces) is left in place.

Examples:

Sliding a grid vertex up to its neighbour makes two needles; the fix collapses their short edge:

import warp as wp

import ordito as od

vertices, faces = od.creation.grid(count=(4, 4))
positions = vertices.numpy()
positions[6] = positions[5] + [0.0, 1e-5, 0.0]
needled = wp.array(positions, dtype=wp.vec3)
new_vertices, new_faces = od.repair.fix_degeneracies(needled, faces, 1e-3)
print(new_vertices.shape, new_faces.shape[0] // 3)  # (15,) 16
print(f"{od.triangles.face_quality(new_vertices, new_faces).numpy().max():.1f}")  # 1.2
Source code in ordito/repair.py
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
def fix_degeneracies(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    max_deviation: float,
    *,
    tiny_edge_length: float = 0.0,
    critical_aspect_ratio: float = 1e4,
    max_angle_change: float = 60.0,
    region_rings: int = 3,
    max_iter: int = 10,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], od.interpolation.Provenance]
):
    """
    Remove needle and cap triangles and tiny edges by local flips and collapses around them.

    A triangle is *degenerate* when its aspect ratio (circumradius over twice the inradius, the
    ``aspect_ratio`` of [`face_quality`][ordito.triangles.face_quality]) reaches
    ``critical_aspect_ratio``. The repair works in a **region**: the degenerate faces and those on
    an edge no longer than ``tiny_edge_length``, grown by ``region_rings`` rings of neighbouring
    faces. Inside it, two local moves alternate until no collapse remains:

    - **Flip** every edge whose other diagonal makes the smaller larger circumcircle (on planar
      input the Delaunay test of [`flip_to_delaunay`][ordito.remesh.flip_to_delaunay]), when the
      flip moves the surface by at most ``max_deviation`` and changes the dihedral angle across it
      by at most ``max_angle_change`` (a quad holding a degenerate face may exceed the angle).
      This is what fixes a *cap*, whose apex sits on its long edge.
    - **Collapse** every edge no longer than ``max_deviation``, shortest first, into the endpoint
      whose removal moves the surface least. This is what fixes a *needle*. A collapse that would
      leave a face of aspect ratio above 20 is skipped, unless a face it touches was already worse
      or its edge is no longer than ``tiny_edge_length``.

    The surface keeps its topology: a collapse that would pinch a handle or a sheet shut (the link
    condition) is skipped, as is one that would fold a face over unless a degenerate face is
    involved, and boundary vertices stay on the boundary.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions. Never modified.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    max_deviation
        Longest edge collapsed and largest surface move of a flip, in mesh units. A collapse keeps
        one endpoint in place, so it too moves the surface by at most this length.
    tiny_edge_length
        Edges no longer than this collapse whatever the shape they leave, and seed the region.
    critical_aspect_ratio
        Aspect ratio from which a triangle counts as degenerate (``1`` is equilateral).
    max_angle_change
        Largest change of dihedral angle, in **degrees**, a flip may make.
    region_rings
        Rings of faces the region extends past the faces that seed it.
    max_iter
        Cap on the alternating flip-and-collapse rounds.
    return_provenance
        If ``True``, also return the [`Provenance`][ordito.interpolation.Provenance] that carries
        any per-vertex or per-face field onto the result.

    Returns
    -------
    vertices : wp.array[wp.vec3]
        ``(n_new_vertices,)`` vertex positions, compacted from index zero when a collapse ran.
    faces : wp.array[wp.int32]
        ``(3 * n_new_faces,)`` flat triangle index buffer.
    provenance : Provenance
        Only when ``return_provenance`` is ``True``: each output vertex is the endpoint a collapse
        kept in place, so it copies that input vertex, and each output face names the input face
        whose slot it holds after the flips and collapses rewrote its corners.

    Raises
    ------
    ValueError
        If ``max_deviation``, ``tiny_edge_length`` or ``region_rings`` is negative,
        ``critical_aspect_ratio`` is below ``1``, or ``max_angle_change`` is outside ``[0, 180]``.
    RuntimeError
        If ``vertices`` and ``faces`` are not all on one device.

    See Also
    --------
    [`collapse_small_triangles`][ordito.repair.collapse_small_triangles]
    [`flip_t_vertices`][ordito.repair.flip_t_vertices]
    [`ordito.remesh.flip_to_delaunay`][ordito.remesh.flip_to_delaunay]

    Notes
    -----
    The collapses of one pass are a conflict-free independent set, each neighbourhood's winner
    chosen by a hashed priority rather than by length, so they are applied together but never
    overlap; the sequence differs from a serial shortest-edge-first queue, and so does the
    triangulation it ends on.
    The region is fixed when the call starts and follows the surviving vertices, so the moves never
    spread past it. A degenerate triangle no move can fix (a cap on the boundary, a needle whose
    collapse would leave worse faces) is left in place.

    Examples
    --------
    Sliding a grid vertex up to its neighbour makes two needles; the fix collapses their short
    edge:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.grid(count=(4, 4))
    positions = vertices.numpy()
    positions[6] = positions[5] + [0.0, 1e-5, 0.0]
    needled = wp.array(positions, dtype=wp.vec3)
    new_vertices, new_faces = od.repair.fix_degeneracies(needled, faces, 1e-3)
    print(new_vertices.shape, new_faces.shape[0] // 3)  # (15,) 16
    print(f"{od.triangles.face_quality(new_vertices, new_faces).numpy().max():.1f}")  # 1.2
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    if max_deviation < 0.0:
        raise ValueError(f"max_deviation must be non-negative, got {max_deviation}")
    if tiny_edge_length < 0.0:
        raise ValueError(f"tiny_edge_length must be non-negative, got {tiny_edge_length}")
    if critical_aspect_ratio < 1.0:
        raise ValueError(f"critical_aspect_ratio must be at least 1, got {critical_aspect_ratio}")
    if not 0.0 <= max_angle_change <= 180.0:
        raise ValueError(f"max_angle_change must be in [0, 180] degrees, got {max_angle_change}")
    if region_rings < 0:
        raise ValueError(f"region_rings must be non-negative, got {region_rings}")

    device = faces.device
    n_faces = faces.size // 3
    if n_faces == 0:
        return _unchanged(_launch.clone(vertices), _launch.clone(faces), return_provenance)
    seeds = _launch.zeros(vertices.size, dtype=wp.bool, device=device)
    n_seeds = _launch.zeros(1, dtype=wp.int32, device=device)
    _launch.launch(
        kernel_repair.mark_degeneracy_seeds,
        dim=n_faces,
        inputs=[
            vertices,
            faces,
            wp.float32(critical_aspect_ratio),
            wp.float32(tiny_edge_length),
            seeds,
            n_seeds,
        ],
        device=device,
    )
    # The one readback before any work: a mesh with nothing to repair costs one pass.
    if int(read_scalar(n_seeds, 0)) == 0:
        return _unchanged(_launch.clone(vertices), _launch.clone(faces), return_provenance)
    # The region is held per vertex, a face being inside when its three corners are: the collapse
    # passes compact it with the vertices, which a face mask would not survive.
    grown = od.selection.expand_vertex_mask(faces, seeds, region_rings)
    region = _launch.empty(vertices.size, dtype=wp.float32, device=device)
    _launch.map(kernel_repair.region_weight, grown, out=region)

    degeneracy = wp.vec3(tiny_edge_length, max_deviation, critical_aspect_ratio)
    # Only the boundary is a feature: a degenerate face's normal is noise, so a dihedral test would
    # freeze exactly the vertices that must move.
    feature = wp.float32(math.pi)
    current_vertices = vertices
    current_faces = faces
    # Collapses only ever remove faces, so one flag buffer sized for the input serves every round
    # through its leading entries.
    region_flags = _launch.empty(n_faces, dtype=wp.int32, device=device)
    # Each committed collapse pass's provenance when one is asked for; a flip keeps each face in
    # its slot, so it changes no source.
    steps: list[od.interpolation.Provenance] | None = [] if return_provenance else None
    for _ in range(max_iter):
        n_current = current_faces.size
        # The caller's buffer is copied before the first flips; every later one is this call's own
        # (a flip or collapse output) and is flipped in place.
        flipped = (
            _launch.empty(n_current, dtype=wp.int32, device=device)
            if current_faces is faces
            else current_faces
        )
        face_region = _launch.view(region_flags, 0, n_current // 3)
        _launch.launch(
            kernel_repair.faces_in_vertex_region,
            dim=n_current // 3,
            inputs=[current_faces, region],
            outputs=[flipped, face_region],
            device=device,
        )
        current_faces = flipped
        _flip_region_faces(
            current_vertices,
            current_faces,
            face_region,
            math.radians(max_angle_change),
            max_deviation,
            _DEGENERACY_FLIP_ITERATIONS,
            critical_aspect_ratio=critical_aspect_ratio,
        )
        current_vertices, current_faces, _incidence, kept_region = _collapse_pass(
            current_vertices,
            current_faces,
            region,
            0.0,
            feature,
            max_passes=_DEGENERACY_COLLAPSE_PASSES,
            degeneracy=degeneracy,
            rounds=_DEGENERACY_COLLAPSE_ROUNDS,
            passes=steps,
        )
        assert kept_region is not None
        region = kept_region
        # Each committed collapse removes a face, and flips never undo a flip fixpoint on unchanged
        # positions, so a round without one ends the repair.
        if current_faces.size == n_current:
            break
    if current_vertices is vertices:
        current_vertices = _launch.clone(vertices)
    if steps is None:
        return current_vertices, current_faces
    provenance = _chained_steps(steps, vertices.size, n_faces, device)
    return current_vertices, current_faces, provenance

straighten_boundary

straighten_boundary(
    vertices: array[vec3],
    faces: array[int32],
    *,
    min_normal_dot: float = 0.9,
    max_aspect_ratio: float = 10.0,
    iterations: int = 1,
    return_count: Literal[False] = False,
) -> wp.array[wp.int32]
straighten_boundary(
    vertices: array[vec3],
    faces: array[int32],
    *,
    min_normal_dot: float = 0.9,
    max_aspect_ratio: float = 10.0,
    iterations: int = 1,
    return_count: Literal[True],
) -> tuple[wp.array[wp.int32], int]
straighten_boundary(
    vertices: array[vec3],
    faces: array[int32],
    *,
    min_normal_dot: float = 0.9,
    max_aspect_ratio: float = 10.0,
    iterations: int = 1,
    return_count: bool = False,
) -> wp.array[wp.int32] | tuple[wp.array[wp.int32], int]

Close concave notches in the mesh's rim, one triangle at a time.

A rim that came out of a clip, a decimation or a scan is ragged: it zig-zags by one triangle even where the surface is smooth. Each pass adds the single triangle that spans a rim vertex's two neighbours, wherever that triangle faces the same way as the surface it joins and is not a sliver. No vertex moves and none is added -- the mesh only gains faces, so the interior is untouched and every existing index stays valid.

Two gates, and both matter. min_normal_dot is what distinguishes a notch from a corner: a convex rim corner would be closed by a triangle facing away from the surface, and filling it folds the mesh over. max_aspect_ratio stops the pass trading a ragged rim for a fan of slivers. Neither has a natural default, which is why both are keywords rather than constants.

Adjacent notches share a rim edge, so one pass closes a maximal independent set of them -- lowest index wins, deterministically -- and iterations passes go round again on what is left. A pass that closes nothing ends the loop early.

Edge-manifoldness is not enough to make the rim a set of simple loops: at a bowtie rim vertex two loops are pinched at one point, so that vertex has two outgoing boundary halfedges and no single successor. The rim is therefore followed by halfedge rather than by vertex, which gives each loop its own links: both notches at such a vertex are closed, neither is attached across the pinch, and the answer is the same on every device.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions. Read only; nothing moves.

required
faces array[int32]

(3 * n_faces,) triangle index buffer. Must be edge-manifold, since the rim is found through the halfedge twins.

required
min_normal_dot float

Minimum cosine between the new triangle's normal and each of the two rim faces it will border. 1.0 accepts only a perfectly flat notch; 0.0 accepts any notch that is not folded back on the surface.

0.9
max_aspect_ratio float

Largest circum-radius over twice the in-radius the new triangle may have, as face_quality measures it.

10.0
iterations int

Number of independent-set passes.

1
return_count bool

If True, also return added.

False

Returns:

Name Type Description
faces array[int32]

(3 * n_new_faces,) flat triangle index buffer with the new triangles appended. The vertex buffer is unchanged and is not returned.

added (int, optional)

Present when return_count=True. How many triangles were added, summed over the passes. Zero means no notch passed both gates, and the buffer is the input's. A diagnostic: the pass loop already stops itself when a pass closes nothing, so a caller needs this only to report what happened.

Raises:

Type Description
ValueError

If iterations is negative, or propagated from halfedge_twins when the mesh is not edge-manifold.

RuntimeError

If vertices and faces are not all on one device.

See Also

fill_min_weight Closes a rim completely; this only tidies its shape and leaves it open. ears Finds the faces with two rim edges, which is the dual situation -- an ear sticks out where a notch cuts in. boundary_loops

Examples:

Deleting a rim triangle of a grid cuts a notch; one pass closes it again:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.grid(count=(5, 5))
notched = wp.array(np.delete(faces.numpy().reshape(-1, 3), 1, axis=0).ravel(), dtype=wp.int32)
straightened, added = od.repair.straighten_boundary(vertices, notched, return_count=True)
print(notched.shape[0] // 3, straightened.shape[0] // 3, added)  # 31 32 1
Source code in ordito/repair.py
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
def straighten_boundary(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    min_normal_dot: float = 0.9,
    max_aspect_ratio: float = 10.0,
    iterations: int = 1,
    return_count: bool = False,
) -> wp.array[wp.int32] | tuple[wp.array[wp.int32], int]:
    """
    Close concave notches in the mesh's rim, one triangle at a time.

    A rim that came out of a clip, a decimation or a scan is *ragged*: it zig-zags by one triangle
    even where the surface is smooth. Each pass adds the single triangle that spans a rim vertex's
    two neighbours, wherever that triangle faces the same way as the surface it joins and is not a
    sliver. No vertex moves and none is added -- the mesh only gains faces, so the interior is
    untouched and every existing index stays valid.

    Two gates, and both matter. ``min_normal_dot`` is what distinguishes a notch from a corner: a
    *convex* rim corner would be closed by a triangle facing away from the surface, and filling it
    folds the mesh over. ``max_aspect_ratio`` stops the pass trading a ragged rim for a fan of
    slivers. Neither has a natural default, which is why both are keywords rather than constants.

    Adjacent notches share a rim edge, so one pass closes a maximal independent set of them --
    lowest index wins, deterministically -- and ``iterations`` passes go round again on what is
    left. A pass that closes nothing ends the loop early.

    Edge-manifoldness is not enough to make the rim a set of simple loops: at a *bowtie* rim
    vertex two loops are pinched at one point, so that vertex has two outgoing boundary halfedges
    and no single successor. The rim is therefore followed by halfedge rather than by vertex, which
    gives each loop its own links: both notches at such a vertex are closed, neither is attached
    across the pinch, and the answer is the same on every device.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions. Read only; nothing moves.
    faces
        ``(3 * n_faces,)`` triangle index buffer. Must be edge-manifold, since the
        rim is found through the halfedge twins.
    min_normal_dot
        Minimum cosine between the new triangle's normal and each of the two rim faces it will
        border. ``1.0`` accepts only a perfectly flat notch; ``0.0`` accepts any notch that is not
        folded back on the surface.
    max_aspect_ratio
        Largest circum-radius over twice the in-radius the new triangle may have, as
        [`face_quality`][ordito.triangles.face_quality] measures it.
    iterations
        Number of independent-set passes.
    return_count
        If ``True``, also return ``added``.

    Returns
    -------
    faces : wp.array[wp.int32]
        ``(3 * n_new_faces,)`` flat triangle index buffer with the new triangles appended. The
        vertex buffer is unchanged and is not returned.
    added : int, optional
        Present when ``return_count=True``. How many triangles were added, summed over the passes.
        Zero means no notch passed both gates, and the buffer is the input's. A diagnostic: the
        pass loop already stops itself when a pass closes nothing, so a caller needs this only to
        report what happened.

    Raises
    ------
    ValueError
        If ``iterations`` is negative, or propagated from
        [`halfedge_twins`][ordito.halfedge.halfedge_twins] when the mesh is not edge-manifold.
    RuntimeError
        If ``vertices`` and ``faces`` are not all on one device.

    See Also
    --------
    [`fill_min_weight`][ordito.holes.fill_min_weight]
        Closes a rim *completely*; this only tidies its shape and leaves it open.
    [`ears`][ordito.boundary.ears]
        Finds the faces with two rim edges, which is the dual situation -- an ear sticks out where a
        notch cuts in.
    [`boundary_loops`][ordito.boundary.boundary_loops]

    Examples
    --------
    Deleting a rim triangle of a grid cuts a notch; one pass closes it again:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.grid(count=(5, 5))
    notched = wp.array(np.delete(faces.numpy().reshape(-1, 3), 1, axis=0).ravel(), dtype=wp.int32)
    straightened, added = od.repair.straighten_boundary(vertices, notched, return_count=True)
    print(notched.shape[0] // 3, straightened.shape[0] // 3, added)  # 31 32 1
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    if iterations < 0:
        raise ValueError(f"iterations must be non-negative, got {iterations}")
    device = faces.device
    n_vertices = vertices.size
    if n_vertices == 0 or faces.size == 0 or iterations == 0:
        return (faces, 0) if return_count else faces

    added = 0
    # One emit cursor for the whole loop, allocated zeroed and re-zeroed before each later pass
    # rather than reallocated: a small buffer per pass is an allocation where a memset does. Two
    # slots behind it take the pass's twin rejections, read back with the cursor rather than in a
    # synchronization of their own.
    cursor_and_defects = _launch.zeros(3, dtype=wp.int32, device=device)
    cursor = _launch.view(cursor_and_defects, 0, 1)
    for iteration in range(iterations):
        if iteration > 0:
            _launch.zero_(cursor_and_defects)
        n_faces = faces.size // 3
        n_halfedges = 3 * n_faces
        twins = od.halfedge.halfedge_twins(
            faces, n_vertices=n_vertices, defect_counts=_launch.view(cursor_and_defects, 1, 3)
        )
        # Keyed by halfedge, not by vertex: a bowtie rim vertex carries two rim loops and has no
        # single successor, and edge-manifoldness -- all `halfedge_twins` checks -- does not
        # exclude one. One slot per halfedge gives each loop its own links and one writer each.
        # Both link tables are halves of one buffer: one allocation and one fill.
        rim_links = _launch.full(2 * n_halfedges, -1, dtype=wp.int32, device=device)
        rim_next = odt.as_dense(rim_links[:n_halfedges])
        rim_prev = odt.as_dense(rim_links[n_halfedges:])
        # ``wp.empty``: the pass writes every halfedge's candidate flag.
        candidate = _launch.empty(n_halfedges, dtype=wp.bool, device=device)
        # One launch: a halfedge's notch test needs only the successor this same thread computes,
        # so linking the rim and classifying it are one pass rather than two with the link table
        # written out and read back between them.
        _launch.launch(
            kernel_repair.collect_rim_links_and_candidates,
            dim=n_halfedges,
            inputs=[
                vertices,
                faces,
                twins,
                wp.float32(min_normal_dot),
                wp.float32(max_aspect_ratio),
                rim_next,
                rim_prev,
                candidate,
            ],
            device=device,
        )
        # One notch per boundary halfedge at most, and a pinched rim can carry more of those than
        # the mesh has vertices, so the bound is the halfedge count.
        new_faces = _launch.empty(3 * n_halfedges, dtype=wp.int32, device=device)
        _launch.launch(
            kernel_repair.emit_straighten_faces,
            dim=n_halfedges,
            inputs=[
                faces,
                rim_next,
                rim_prev,
                candidate,
                cursor,
                new_faces.reshape((n_halfedges, 3)),
            ],
            device=device,
        )
        # One readback per pass, and it is the loop's own stopping test: how many notches the pass
        # actually closed is a device-side fact and a Python loop cannot branch on it otherwise.
        n_added, *defects = read_values(cursor_and_defects, 0, 3)
        raise_twin_defects(defects)
        if n_added == 0:
            break
        # The emitted prefix goes straight behind the current faces in one exact-size buffer: one
        # allocation and two copies, where trimming the emit and then concatenating cost two of
        # each and a third copy.
        grown = _launch.empty(faces.size + 3 * n_added, dtype=wp.int32, device=device)
        _launch.copy(grown, faces, count=faces.size)
        _launch.copy(grown, new_faces, dest_offset=faces.size, count=3 * n_added)
        faces = grown
        added += n_added
    return (faces, added) if return_count else faces

remove_degree3_vertices

remove_degree3_vertices(
    vertices: array[vec3],
    faces: array[int32],
    *,
    max_iter: int = 8,
    return_count: Literal[False] = False,
    return_provenance: Literal[False] = False,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32]]
remove_degree3_vertices(
    vertices: array[vec3],
    faces: array[int32],
    *,
    max_iter: int = 8,
    return_count: Literal[True],
    return_provenance: Literal[False] = False,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32], int]
remove_degree3_vertices(
    vertices: array[vec3],
    faces: array[int32],
    *,
    max_iter: int = 8,
    return_count: Literal[False] = False,
    return_provenance: Literal[True],
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    od.interpolation.Provenance,
]
remove_degree3_vertices(
    vertices: array[vec3],
    faces: array[int32],
    *,
    max_iter: int = 8,
    return_count: Literal[True],
    return_provenance: Literal[True],
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    int,
    od.interpolation.Provenance,
]
remove_degree3_vertices(
    vertices: array[vec3],
    faces: array[int32],
    *,
    max_iter: int = 8,
    return_count: bool = False,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], int]
    | tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        od.interpolation.Provenance,
    ]
    | tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        int,
        od.interpolation.Provenance,
    ]
)

Remove interior vertices with exactly three incident faces, collapsing each fan to one triangle.

A valence-3 interior vertex carries no information the surface needs: its three faces tile the triangle formed by its three neighbours, so deleting it and keeping that triangle changes the connectivity and nothing else. They are a standard residue of subdivision, of decimation and of hole filling, and they make every downstream valence statistic worse.

Adjacent candidates share faces, so a pass removes a maximal independent set -- the lowest-indexed of any two neighbouring candidates wins, deterministically -- and the loop repeats until none is left or max_iter passes have run. Removing one vertex can create another, which is why return_count reports what happened rather than promising it.

The other half of a double-face pass already exists

A pair of triangles on the same three vertices is resolve_duplicated_faces' job, and this function deliberately does not repeat it. The two together are what a "remove double faces" pass means elsewhere; they are kept apart because they have different orientation rules and different answers on a non-orientable mesh.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) triangle index buffer. Must be edge-manifold, since the fan around a vertex is what this reasons about. A pinched (vertex-non-manifold) vertex is accepted and is never a candidate: its faces do not close into one fan of three.

required
max_iter int

Cap on the number of passes. Each pass removes an independent set, so a chain of adjacent candidates needs one pass per link; the default covers any chain length likely in practice.

8
return_count bool

If True, also return removed.

False
return_provenance bool

If True, also return the Provenance that carries any per-vertex or per-face field onto the result.

False

Returns:

Name Type Description
vertices array[vec3]

(n_new_vertices,) positions of the result, with the removed vertices compacted away. No position moves.

faces array[int32]

(3 * n_new_faces,) flat triangle index buffer, three faces shorter per removed vertex plus one longer.

removed (int, optional)

Present when return_count=True. How many vertices were removed. Zero means the input had none and the buffers are it. A diagnostic: the pass loop stops itself when a pass finds no candidate, so nothing about calling this correctly depends on reading the count.

provenance Provenance

Only when return_provenance is True: each output vertex is a copy of the input vertex it is, and each output face of the input face it is; a fan's replacement triangle takes the fan face holding the fan's lowest halfedge, chained through earlier passes.

Raises:

Type Description
ValueError

If max_iter is negative, or (when a pass runs) if an edge is shared by three or more faces or both of an edge's halfedges traverse it the same way -- the two meshes halfedge_twins rejects, tested without building its table.

RuntimeError

If vertices and faces are not all on one device.

See Also

flatten_degree3_vertices The geometric answer to the same defect: move the vertex instead of deleting it, which leaves the connectivity and every per-vertex attribute intact. resolve_duplicated_faces The other half: triangles repeated on the same three vertices. remove_degenerate_faces Removes faces by geometry; this one removes a vertex by its connectivity alone. vertex_one_rings The whole fan of every vertex; this reads only the three faces of a candidate.

Examples:

A cube face split into a three-triangle fan around a raised apex loses the apex and gets its triangle back:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.box()
a, b, c = faces.numpy()[:3]
apex = vertices.numpy()[[a, b, c]].mean(axis=0) + [-0.2, 0.0, 0.0]
bumped_vertices = wp.array(np.vstack([vertices.numpy(), apex]), dtype=wp.vec3)
fan = [a, b, 8, b, c, 8, c, a, 8]
bumped_faces = wp.array(np.concatenate([fan, faces.numpy()[3:]]), dtype=wp.int32)
print(bumped_vertices.shape, bumped_faces.shape[0] // 3)  # (9,) 14
new_vertices, new_faces, removed = od.repair.remove_degree3_vertices(
    bumped_vertices, bumped_faces, return_count=True
)
print(new_vertices.shape, new_faces.shape[0] // 3, removed)  # (8,) 12 1
Source code in ordito/repair.py
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
def remove_degree3_vertices(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    max_iter: int = 8,
    return_count: bool = False,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], int]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], od.interpolation.Provenance]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], int, od.interpolation.Provenance]
):
    """
    Remove interior vertices with exactly three incident faces, collapsing each fan to one triangle.

    A valence-3 interior vertex carries no information the surface needs: its three faces tile the
    triangle formed by its three neighbours, so deleting it and keeping that triangle changes the
    connectivity and nothing else. They are a standard residue of subdivision, of decimation and of
    hole filling, and they make every downstream valence statistic worse.

    Adjacent candidates share faces, so a pass removes a maximal **independent** set -- the
    lowest-indexed of any two neighbouring candidates wins, deterministically -- and the loop
    repeats until none is left or ``max_iter`` passes have run. Removing one vertex can create
    another, which is why ``return_count`` reports what happened rather than promising it.

    !!! note "The other half of a double-face pass already exists"
        A pair of triangles on the same three vertices is
        [`resolve_duplicated_faces`][ordito.repair.resolve_duplicated_faces]' job, and this
        function deliberately does not repeat it. The two together are what a "remove double faces"
        pass means elsewhere; they are kept apart because they have different orientation rules and
        different answers on a non-orientable mesh.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` triangle index buffer. Must be edge-manifold, since the
        fan around a vertex is what this reasons about. A pinched (vertex-non-manifold) vertex is
        accepted and is never a candidate: its faces do not close into one fan of three.
    max_iter
        Cap on the number of passes. Each pass removes an independent set, so a chain of adjacent
        candidates needs one pass per link; the default covers any chain length likely in practice.
    return_count
        If ``True``, also return ``removed``.
    return_provenance
        If ``True``, also return the [`Provenance`][ordito.interpolation.Provenance] that carries
        any per-vertex or per-face field onto the result.

    Returns
    -------
    vertices : wp.array[wp.vec3]
        ``(n_new_vertices,)`` positions of the result, with the removed vertices compacted away. No
        position moves.
    faces : wp.array[wp.int32]
        ``(3 * n_new_faces,)`` flat triangle index buffer, three faces shorter per removed vertex
        plus one longer.
    removed : int, optional
        Present when ``return_count=True``. How many vertices were removed. Zero means the input
        had none and the buffers are it. A diagnostic: the pass loop stops itself when a pass finds
        no candidate, so nothing about calling this correctly depends on reading the count.
    provenance : Provenance
        Only when ``return_provenance`` is ``True``: each output vertex is a copy of the input
        vertex it is, and each output face of the input face it is; a fan's replacement triangle
        takes the fan face holding the fan's lowest halfedge, chained through earlier passes.

    Raises
    ------
    ValueError
        If ``max_iter`` is negative, or (when a pass runs) if an edge is shared by three or more
        faces or both of an edge's halfedges traverse it the same way -- the two meshes
        [`halfedge_twins`][ordito.halfedge.halfedge_twins] rejects, tested without building its
        table.
    RuntimeError
        If ``vertices`` and ``faces`` are not all on one device.

    See Also
    --------
    [`flatten_degree3_vertices`][ordito.repair.flatten_degree3_vertices]
        The geometric answer to the same defect: move the vertex instead of deleting it, which
        leaves the connectivity and every per-vertex attribute intact.
    [`resolve_duplicated_faces`][ordito.repair.resolve_duplicated_faces]
        The other half: triangles repeated on the same three vertices.
    [`remove_degenerate_faces`][ordito.repair.remove_degenerate_faces]
        Removes faces by *geometry*; this one removes a vertex by its connectivity alone.
    [`vertex_one_rings`][ordito.halfedge.vertex_one_rings]
        The whole fan of every vertex; this reads only the three faces of a candidate.

    Examples
    --------
    A cube face split into a three-triangle fan around a raised apex loses the apex and gets its
    triangle back:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    a, b, c = faces.numpy()[:3]
    apex = vertices.numpy()[[a, b, c]].mean(axis=0) + [-0.2, 0.0, 0.0]
    bumped_vertices = wp.array(np.vstack([vertices.numpy(), apex]), dtype=wp.vec3)
    fan = [a, b, 8, b, c, 8, c, a, 8]
    bumped_faces = wp.array(np.concatenate([fan, faces.numpy()[3:]]), dtype=wp.int32)
    print(bumped_vertices.shape, bumped_faces.shape[0] // 3)  # (9,) 14
    new_vertices, new_faces, removed = od.repair.remove_degree3_vertices(
        bumped_vertices, bumped_faces, return_count=True
    )
    print(new_vertices.shape, new_faces.shape[0] // 3, removed)  # (8,) 12 1
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    if max_iter < 0:
        raise ValueError(f"max_iter must be non-negative, got {max_iter}")
    device = faces.device
    n_vertices = vertices.size
    n_input = faces.size // 3
    if n_input == 0 or max_iter == 0:
        unchanged = (
            od.interpolation.Provenance.identity(n_vertices, n_input, device)
            if return_provenance
            else None
        )
        return _degree3_result(vertices, faces, 0, return_count, unchanged)
    # The documented edge-manifold check, on the input only: the twin defects of the halfedge
    # mates, counted inside pass 0's first launch and read back with that pass's counters,
    # rather than a twin table the pass never reads. Replacing an interior degree-3 fan by the one
    # triangle over its rim keeps every rim edge at two faces with the same orientation, so a pass
    # cannot make a valid mesh invalid and later passes do not re-prove it.
    input_mates = od.halfedge.halfedge_mates(faces, n_vertices)
    # The passes run over one fixed-capacity face buffer rather than compacting after each: a
    # replaced fan's three faces keep their rows with their kept flag cleared, and the replacements
    # are appended after the last used row. Each removal takes three kept faces and adds one, so at
    # most ``n_input // 2`` rows are ever appended; kept rows in buffer order are exactly the order
    # a compaction after every pass gives, so the output is compacted once, after the loop, with no
    # per-pass scan, compaction or allocation.
    #
    # The loop stays on the host, with one small read per pass: recording the passes costs more
    # than those reads at the pass counts real meshes take (``kernels/repair.degree3_fan_tables``).
    n_slots = n_input + max(n_input // 2, 1)
    # One zeroed buffer: the kept flags; the referenced flags the final compaction scans with them
    # (one in-place scan over both); the append cursor (the removed count) and pass 0's two
    # twin-defect counts and referenced vertex count; then, zeroed per pass, the next-pass
    # candidate count and each vertex's corner count, link sum and decrement tally
    # (``degree3_fan_tables`` and ``emit_degree3_replacement`` say what each means). The cursor
    # through the candidate count is what each pass reads, in one copy. The views are stamped by
    # one ``array.split`` rather than sliced one by one.
    tail = n_slots + n_vertices
    per_pass = tail + 4
    state = _launch.zeros(per_pass + 1 + 3 * n_vertices, dtype=wp.int32, device=device)
    bounds = [0, n_slots, tail, tail + 1, per_pass, per_pass + 1]
    bounds += [per_pass + 1 + n_vertices, per_pass + 1 + 2 * n_vertices, state.size]
    kept, referenced, cursor, defects, next_candidates, counts, link_sums, lost = od.array.split(
        state, bounds
    )
    tables = state[per_pass:]
    fan_rows, face_slots = _launch.carve(wp.int32, [3 * n_vertices, 3 * n_slots], device)
    # The input face each row came from, which a replacement takes from its fan: only for a
    # provenance, and its rows past the input are written as replacements are appended.
    slot_sources = od.array.arange(n_slots, device=device) if return_provenance else None
    fans = odt.as_array2d(fan_rows.reshape((n_vertices, 3)), wp.int32)
    new_faces = odt.as_dense(face_slots[3 * n_input :]).reshape((n_slots - n_input, 3))
    emit_inputs = [
        face_slots,
        fans,
        counts,
        link_sums,
        n_input,
        cursor,
        slot_sources,
        lost,
        kept,
        new_faces,
        next_candidates,
    ]
    _launch.launch(
        kernel_repair.degree3_fan_tables_input,
        dim=3 * n_input,
        inputs=[faces, input_mates, counts, link_sums, fans, face_slots, kept, defects],
        device=device,
    )
    _launch.launch(
        kernel_repair.emit_degree3_replacement, dim=n_vertices, inputs=emit_inputs, device=device
    )
    # One readback per pass, carrying both of the loop's host decisions: the removed count, which
    # ends the call when pass 0 found nothing and sizes the next pass, and the next-pass candidate
    # count, which skips the pass that would only learn it finds nothing. Pass 0's also carries the
    # input validation, whose failure discards that pass.
    removed, n_nonmanifold, n_misoriented, n_referenced, n_next = read_values(state, tail, 5)
    _raise_degree3_defects(n_nonmanifold, n_misoriented)
    if removed == 0:
        unchanged = (
            od.interpolation.Provenance.identity(n_vertices, n_input, device)
            if return_provenance
            else None
        )
        return _degree3_result(vertices, faces, 0, return_count, unchanged)
    for _pass_index in range(1, max_iter):
        if n_next == 0:
            break
        _launch.zero_(tables)
        _launch.launch(
            kernel_repair.degree3_fan_tables,
            dim=3 * (n_input + removed),
            inputs=[face_slots, kept, counts, link_sums, fans],
            device=device,
        )
        _launch.launch(
            kernel_repair.emit_degree3_replacement,
            dim=n_vertices,
            inputs=emit_inputs,
            device=device,
        )
        removed, _nonmanifold, _misoriented, _referenced, n_next = read_values(state, tail, 5)
    n_used = n_input + removed
    # Compacted **once**, after the loop rather than inside it -- the kept faces and, as
    # ``remove_unreferenced_vertices`` would, the vertices they reference. A dead vertex has an
    # empty ring and so is never a candidate, which is what makes deferring safe.
    _launch.launch(
        kernel_repair.mark_kept_face_vertices,
        dim=3 * n_used,
        inputs=[face_slots, kept, referenced],
        device=device,
    )
    scanned = state[:tail]
    _launch.array_scan(scanned, out_array=scanned, inclusive=True)
    # Both output sizes are known: each removal drops two faces net and exactly one vertex, the
    # fan's centre (the replacement face references the whole rim).
    n_kept = n_input - 2 * removed
    n_referenced -= removed
    out_vertices = _launch.empty(n_referenced, dtype=wp.vec3, device=device)
    out_faces = _launch.empty(3 * n_kept, dtype=wp.int32, device=device)
    _launch.launch(
        kernel_repair.compact_kept_faces_and_vertices,
        dim=max(n_vertices, n_used),
        inputs=[vertices, face_slots, kept, referenced, n_kept, out_vertices, out_faces],
        device=device,
    )
    provenance = None
    if slot_sources is not None:
        vertex_index = _launch.empty(n_referenced, dtype=wp.int32, device=device)
        face_index = _launch.empty(n_kept, dtype=wp.int32, device=device)
        _launch.launch(
            kernel_repair.degree3_provenance_maps,
            dim=max(n_vertices, n_used),
            inputs=[n_vertices, slot_sources, kept, referenced, n_kept, vertex_index, face_index],
            device=device,
        )
        provenance = od.interpolation.Provenance(
            vertex_index, face_index, None, n_vertices, n_input
        )
    return _degree3_result(out_vertices, out_faces, removed, return_count, provenance)

flatten_degree3_vertices

flatten_degree3_vertices(
    vertices: array[vec3],
    faces: array[int32],
    region: array[bool] | None = None,
    *,
    max_iter: int = 8,
    rings: tuple[array[int32], array[int32], array[bool]]
    | None = None,
) -> wp.array[wp.vec3]

Flatten each interior valence-3 vertex into the plane of its three neighbours.

A valence-3 interior vertex sits on a little tetrahedral bump: three triangles meeting at a point over the triangle its neighbours form. Moving it to their centroid puts it in that triangle's plane, so the bump disappears and the three faces become coplanar -- which is what makes a subdivision, a decimation or a hole fill stop leaving visible pimples.

The gentler half of a pair. remove_degree3_vertices answers the same defect by deleting the vertex and keeping one triangle, which changes the connectivity; this keeps every vertex and every face and only moves positions, so a caller holding per-vertex attributes or a face selection can use it and the other one would invalidate both.

Two interior valence-3 vertices can be neighbours -- a tetrahedron is four of them, each adjacent to the other three -- and moving both at once puts neither in the other's new plane. So a pass flattens a maximal independent set of them, lowest index wins, exactly as remove_degree3_vertices does, and max_iter passes go round again on the candidates left over. Every vertex lands in its neighbours' plane as it is moved, which is the guarantee the name makes; where two candidates are adjacent the later one sees the earlier one's new position, so the order the passes impose is part of the answer rather than an implementation detail. The loop stops as soon as no candidate is left, so the usual mesh -- where no two candidates touch -- takes one pass and one check.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) triangle index buffer. Must be edge-manifold, since the fan around a vertex is what this reasons about.

required
region array[bool] | None

(n_vertices,) mask restricting which vertices may be flattened. None flattens every one that qualifies. Masked-out vertices are also excluded from the independence rule, since a vertex that cannot move cannot spoil a neighbour's plane.

None
max_iter int

Cap on the number of passes. Each pass flattens an independent set, so a chain of adjacent candidates needs one pass per link; the default covers any chain length likely in practice -- a tetrahedron, the densest case there is, needs four.

8
rings tuple[array[int32], array[int32], array[bool]] | None

Optional precomputed vertex_one_rings as (ring_halfedges, offsets, is_boundary). Depends on the connectivity alone, so one CSR serves every fan walk over the same mesh -- Trimesh.vertex_one_rings has it cached, and passing it skips the vertex-manifold check and the host readback that check costs.

None

Returns:

Type Description
array[vec3]

(n_vertices,) positions on vertices.device, with the selected vertices at their neighbours' centroid. Connectivity is untouched, so faces stays valid.

Raises:

Type Description
ValueError

If max_iter is negative, if region is not a length-n_vertices wp.bool array, or propagated from halfedge_twins when the mesh is not edge-manifold.

RuntimeError

If vertices, faces, region and rings are not all on one device.

See Also

remove_degree3_vertices The topological answer to the same defect: delete the vertex instead of moving it. equalize_triangle_areas Relaxes every vertex toward an area objective, where this hard-sets only the valence-3 ones.

Examples:

A cube face split into a three-triangle fan around a raised apex: the apex drops back into the face, and the cube's volume returns to 1:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.box()
a, b, c = faces.numpy()[:3]
apex = vertices.numpy()[[a, b, c]].mean(axis=0) + [-0.2, 0.0, 0.0]
bumped_vertices = wp.array(np.vstack([vertices.numpy(), apex]), dtype=wp.vec3)
fan = [a, b, 8, b, c, 8, c, a, 8]
bumped_faces = wp.array(np.concatenate([fan, faces.numpy()[3:]]), dtype=wp.int32)
flattened = od.repair.flatten_degree3_vertices(bumped_vertices, bumped_faces)
print(np.round(flattened.numpy()[8], 4))  # [-0.5    -0.1667  0.1667]
print(f"{od.measures.volume(bumped_vertices, bumped_faces):.4f}")  # 1.0333
print(f"{od.measures.volume(flattened, bumped_faces):.4f}")  # 1.0000
Source code in ordito/repair.py
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
def flatten_degree3_vertices(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    region: wp.array[wp.bool] | None = None,
    *,
    max_iter: int = 8,
    rings: tuple[wp.array[wp.int32], wp.array[wp.int32], wp.array[wp.bool]] | None = None,
) -> wp.array[wp.vec3]:
    """
    Flatten each interior valence-3 vertex into the plane of its three neighbours.

    A valence-3 interior vertex sits on a little tetrahedral bump: three triangles meeting at a
    point over the triangle its neighbours form. Moving it to their centroid puts it **in** that
    triangle's plane, so the bump disappears and the three faces become coplanar -- which is what
    makes a subdivision, a decimation or a hole fill stop leaving visible pimples.

    The gentler half of a pair.
    [`remove_degree3_vertices`][ordito.repair.remove_degree3_vertices]
    answers the same defect by deleting the vertex and keeping one triangle, which changes the
    connectivity; this keeps every vertex and every face and only moves positions, so a caller
    holding per-vertex attributes or a face selection can use it and the other one would invalidate
    both.

    Two interior valence-3 vertices **can** be neighbours -- a tetrahedron is four of them, each
    adjacent to the other three -- and moving both at once puts neither in the other's new plane.
    So a pass flattens a maximal **independent** set of them, lowest index wins, exactly as
    [`remove_degree3_vertices`][ordito.repair.remove_degree3_vertices] does, and ``max_iter``
    passes go round again on the candidates left over. Every vertex lands in its neighbours' plane
    as it is moved, which is the guarantee the name makes; where two candidates are adjacent the
    later one sees the earlier one's new position, so the order the passes impose is part of the
    answer rather than an implementation detail. The loop stops as soon as no candidate is left, so
    the usual mesh -- where no two candidates touch -- takes one pass and one check.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` triangle index buffer. Must be edge-manifold, since the
        fan around a vertex is what this reasons about.
    region
        ``(n_vertices,)`` mask restricting which vertices may be flattened. ``None``
        flattens every one that qualifies. Masked-out vertices are also excluded from the
        independence rule, since a vertex that cannot move cannot spoil a neighbour's plane.
    max_iter
        Cap on the number of passes. Each pass flattens an independent set, so a chain of adjacent
        candidates needs one pass per link; the default covers any chain length likely in practice
        -- a tetrahedron, the densest case there is, needs four.
    rings
        Optional precomputed [`vertex_one_rings`][ordito.halfedge.vertex_one_rings] as
        ``(ring_halfedges, offsets, is_boundary)``. Depends on the connectivity alone, so one CSR
        serves every fan walk over the same mesh --
        [`Trimesh.vertex_one_rings`][ordito.mesh.Trimesh.vertex_one_rings] has it cached, and
        passing it skips the vertex-manifold check and the host readback that check costs.

    Returns
    -------
    wp.array[wp.vec3]
        ``(n_vertices,)`` positions on ``vertices.device``, with the selected vertices at their
        neighbours' centroid. Connectivity is untouched, so ``faces`` stays valid.

    Raises
    ------
    ValueError
        If ``max_iter`` is negative, if ``region`` is not a length-``n_vertices`` ``wp.bool``
        array, or propagated from
        [`halfedge_twins`][ordito.halfedge.halfedge_twins] when the mesh is not edge-manifold.
    RuntimeError
        If ``vertices``, ``faces``, ``region`` and ``rings`` are not all on one device.

    See Also
    --------
    [`remove_degree3_vertices`][ordito.repair.remove_degree3_vertices]
        The topological answer to the same defect: delete the vertex instead of moving it.
    [`equalize_triangle_areas`][ordito.smoothing.equalize_triangle_areas]
        Relaxes every vertex toward an area objective, where this hard-sets only the valence-3 ones.

    Examples
    --------
    A cube face split into a three-triangle fan around a raised apex: the apex drops back into the
    face, and the cube's volume returns to 1:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.box()
    a, b, c = faces.numpy()[:3]
    apex = vertices.numpy()[[a, b, c]].mean(axis=0) + [-0.2, 0.0, 0.0]
    bumped_vertices = wp.array(np.vstack([vertices.numpy(), apex]), dtype=wp.vec3)
    fan = [a, b, 8, b, c, 8, c, a, 8]
    bumped_faces = wp.array(np.concatenate([fan, faces.numpy()[3:]]), dtype=wp.int32)
    flattened = od.repair.flatten_degree3_vertices(bumped_vertices, bumped_faces)
    print(np.round(flattened.numpy()[8], 4))  # [-0.5    -0.1667  0.1667]
    print(f"{od.measures.volume(bumped_vertices, bumped_faces):.4f}")  # 1.0333
    print(f"{od.measures.volume(flattened, bumped_faces):.4f}")  # 1.0000
    ```
    """
    require_same_device(vertices=vertices, faces=faces, region=region, rings=rings)
    if max_iter < 0:
        raise ValueError(f"max_iter must be non-negative, got {max_iter}")
    device = faces.device
    n_vertices = vertices.size
    if n_vertices == 0 or faces.size == 0 or max_iter == 0:
        return _launch.clone(vertices)
    if region is not None and (
        len(region.shape) != 1 or region.size != n_vertices or region.dtype is not wp.bool
    ):
        raise ValueError(
            f"region must be a length-{n_vertices} wp.bool array, got shape {tuple(region.shape)} "
            f"of {region.dtype}"
        )

    ring_halfedges, ring_offsets, is_boundary = (
        rings if rings is not None else od.halfedge.vertex_one_rings(faces, n_vertices=n_vertices)
    )
    # The two candidate masks the passes alternate between, in one allocation.
    candidate, remaining = _launch.carve(wp.bool, [n_vertices, n_vertices], device)
    if region is None:
        _launch.map(
            kernel_repair.is_interior_degree3,
            ring_offsets[:-1],
            ring_offsets[1:],
            is_boundary,
            out=candidate,
        )
    else:
        _launch.map(
            kernel_repair.is_interior_degree3_in_region,
            ring_offsets[:-1],
            ring_offsets[1:],
            is_boundary,
            region,
            out=candidate,
        )

    positions = vertices
    # Scratch hoisted out of the loop: the connectivity and the vertex count are both invariant
    # here, so a pass reuses these rather than allocating. The two position buffers alternate so
    # the caller's own ``vertices`` is never written -- pass 0 reads it and writes ``buffers[0]``,
    # pass 1 reads that and writes ``buffers[1]``, and so on -- and the two candidate masks
    # alternate the same way, each pass writing the next one's.
    # Allocated on first use, not upfront: the common mesh has no two candidates adjacent, so the
    # loop runs a single pass and only ever needs one of the two.
    buffers: dict[int, wp.array[wp.vec3]] = {}
    for iteration in range(max_iter):
        # Adjacent candidates have to be separated before anything moves -- see the kernel comment
        # for what flattening both ends of an edge at once does to a tetrahedron. The lowest
        # remaining index always wins its own conflict, so every pass retires at least one
        # candidate and the loop cannot spin.
        slot = iteration % 2
        if slot not in buffers:
            buffers[slot] = _launch.empty(n_vertices, dtype=wp.vec3, device=device)
        flattened = buffers[slot]
        # One launch: choosing the independent set, moving the vertices it chose and retiring them
        # from the candidates are the same thread's decision about the same vertex.
        _launch.launch(
            kernel_repair.select_and_flatten_degree3,
            dim=n_vertices,
            inputs=[positions, faces, ring_offsets, ring_halfedges, candidate],
            outputs=[remaining, flattened],
            device=device,
        )
        positions = flattened
        candidate, remaining = remaining, candidate
        if iteration + 1 == max_iter:
            break
        # One readback per pass beyond the first, and it is the loop's own termination test: how
        # many candidates are still unflattened is a device-side fact and a Python loop cannot
        # branch on it otherwise. It is taken *after* the pass rather than before so that a mesh
        # with no two candidates adjacent -- the usual one -- pays exactly one, and ``max_iter=1``
        # pays none. The connectivity never changes here, so nothing above the loop is rebuilt.
        #
        # Read back and reduced on the host rather than through ``reduce``: a bool mask is one byte
        # per vertex, so below about half a million elements the copy is cheaper than the launch a
        # device reduction costs. This call is over the *vertex* count, so
        # it stays on the readback at every registry mesh.
        if not bool(read_array(candidate).any()):
            break
    return positions

reverse_winding

reverse_winding(faces: array[int32]) -> wp.array[wp.int32]

Reverse every face's winding, flipping the surface's orientation.

Rewrites each triangle (a, b, c) as (c, b, a), which negates every face normal and the enclosed signed volume. Unconditional: unlike make_winding_consistent and make_normals_outward, which decide per face, this flips all of them, so a consistently wound mesh stays consistent and an inconsistent one stays inconsistent.

Parameters:

Name Type Description Default
faces array[int32]

(3 * n_faces,) triangle index buffer.

required

Returns:

Type Description
array[int32]

(3 * n_faces,) new face buffer. faces is not modified.

Notes

An involution: applying it twice returns the original buffer exactly.

Each face's signed volume negates exactly -- reversing a triangle's corners swaps two arguments of a scalar triple product, which negates the same floating-point products rather than recomputing them -- so the total negates bit-for-bit wherever the reduction visits faces in a fixed order. The example below prints the volumes rounded, since only that holds independently of the reduction.

The corner that stays first is a convention, and this one matches np.fliplr -- which is what trimesh.Trimesh.invert applies, so the two agree elementwise rather than only up to a rotation of each row. The per-face flippers write the same reversal.

See Also

ordito.mesh.Trimesh.invert The cached-mesh form, which carries what survives a flip. make_winding_consistent make_normals_outward ordito.validation.is_winding_consistent

Examples:

Reversing a cube turns it inside out, and its signed volume negates:

import ordito as od

vertices, faces = od.creation.box()
flipped = od.repair.reverse_winding(faces)
print(faces.numpy()[:3], flipped.numpy()[:3])  # [1 3 0] [0 3 1]
print(f"{od.measures.volume(vertices, faces):.4f}")  # 1.0000
print(f"{od.measures.volume(vertices, flipped):.4f}")  # -1.0000
Source code in ordito/repair.py
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
def reverse_winding(faces: wp.array[wp.int32]) -> wp.array[wp.int32]:
    """
    Reverse every face's winding, flipping the surface's orientation.

    Rewrites each triangle ``(a, b, c)`` as ``(c, b, a)``, which negates every face normal and the
    enclosed signed volume. Unconditional: unlike
    [`make_winding_consistent`][ordito.repair.make_winding_consistent] and
    [`make_normals_outward`][ordito.repair.make_normals_outward], which decide per face, this
    flips all of them, so a consistently wound mesh stays consistent and an inconsistent one stays
    inconsistent.

    Parameters
    ----------
    faces
        ``(3 * n_faces,)`` triangle index buffer.

    Returns
    -------
    wp.array[wp.int32]
        ``(3 * n_faces,)`` new face buffer. ``faces`` is not modified.

    Notes
    -----
    An involution: applying it twice returns the original buffer exactly.

    Each face's signed volume negates *exactly* -- reversing a triangle's corners swaps two
    arguments of a scalar triple product, which negates the same floating-point products rather
    than recomputing them -- so the total negates bit-for-bit wherever the reduction visits faces
    in a fixed order. The example below prints the volumes rounded, since only that holds
    independently of the reduction.

    The corner that stays first is a convention, and this one matches ``np.fliplr`` -- which is
    what ``trimesh.Trimesh.invert`` applies, so the two agree elementwise rather than only up to a
    rotation of each row. The per-face flippers write the same reversal.

    See Also
    --------
    [`ordito.mesh.Trimesh.invert`][]
        The cached-mesh form, which carries what survives a flip.
    [`make_winding_consistent`][ordito.repair.make_winding_consistent]
    [`make_normals_outward`][ordito.repair.make_normals_outward]
    [`ordito.validation.is_winding_consistent`][]

    Examples
    --------
    Reversing a cube turns it inside out, and its signed volume negates:

    ```python
    import ordito as od

    vertices, faces = od.creation.box()
    flipped = od.repair.reverse_winding(faces)
    print(faces.numpy()[:3], flipped.numpy()[:3])  # [1 3 0] [0 3 1]
    print(f"{od.measures.volume(vertices, faces):.4f}")  # 1.0000
    print(f"{od.measures.volume(vertices, flipped):.4f}")  # -1.0000
    ```
    """
    reversed_faces = _launch.empty(faces.size, dtype=wp.int32, device=faces.device)
    n_faces = faces.size // 3
    if n_faces > 0:
        _launch.launch(
            kernel_repair.reverse_face_winding,
            dim=n_faces,
            inputs=[faces, reversed_faces],
            device=faces.device,
        )
    return reversed_faces

make_winding_consistent

make_winding_consistent(
    faces: array[int32], *, n_vertices: int | None = None
) -> wp.array[wp.int32]

Flip faces so every shared edge is traversed in opposite directions by its two faces.

Reuses the orientation flood-fill of face_flip_mask (each connected component seeded at its lowest-indexed face) and reverses the winding of every face whose orientation bit is set. The result satisfies is_winding_consistent whenever one exists, which is to say whenever the mesh is is_orientable; an already-consistent mesh is returned unchanged. Mirrors trimesh.repair.fix_winding.

Parameters:

Name Type Description Default
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
n_vertices int | None

Optional exclusive bound on the vertex indices, forwarded to face_flip_mask, which pairs faster with it. It does not change the answer, and it is trusted, not checked: it must exceed every index.

None

Returns:

Type Description
array[int32]

(3 * n_faces,) new flat face buffer with corrected winding, on faces.device. Vertices are unchanged.

See Also

is_winding_consistent face_flip_mask make_normals_outward

Notes

Each connected component keeps the winding of its lowest-indexed face, so on an orientable mesh the result is a deterministic function of faces on either device; trimesh.repair.fix_winding's BFS likewise keeps its seed face's winding, though its seed choice is its own. Use make_volume afterwards to also orient normals outward.

On a non-orientable mesh no consistent winding exists, so this cannot succeed and does not fail either: the flood-fill orients everything it reaches and the contradiction is left on a seam. The seam can even end up with more inconsistent edges than before the pass ran, not merely the same ones — so treat the result as unrepaired rather than partly repaired, and test with is_orientable first if that matters. Under is_deterministic the seam is a function of faces too (face_flip_mask says which).

Examples:

Every seventh face of an icosphere flipped, face 0 among them: the whole mesh follows face 0, so it comes out consistent but inside out:

import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
rows = faces.numpy().reshape(-1, 3)
rows[::7] = rows[::7, ::-1]
mixed = wp.array(rows.ravel(), dtype=wp.int32)
print(od.validation.is_winding_consistent(mixed))  # False
consistent = od.repair.make_winding_consistent(mixed)
print(od.validation.is_winding_consistent(consistent))  # True
print(f"{od.measures.volume(vertices, consistent):.3f}")  # -4.047
Source code in ordito/repair.py
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
def make_winding_consistent(
    faces: wp.array[wp.int32], *, n_vertices: int | None = None
) -> wp.array[wp.int32]:
    """
    Flip faces so every shared edge is traversed in opposite directions by its two faces.

    Reuses the orientation flood-fill of
    [`face_flip_mask`][ordito.validation.face_flip_mask] (each connected component seeded at
    its lowest-indexed face) and reverses the winding of every face whose orientation bit is
    set. The result satisfies
    [`is_winding_consistent`][ordito.validation.is_winding_consistent] **whenever one exists**,
    which is to say whenever the mesh is
    [`is_orientable`][ordito.validation.is_orientable]; an already-consistent mesh is returned
    unchanged. Mirrors ``trimesh.repair.fix_winding``.

    Parameters
    ----------
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    n_vertices
        Optional exclusive bound on the vertex indices, forwarded to
        [`face_flip_mask`][ordito.validation.face_flip_mask], which pairs faster with it. It does
        not change the answer, and it is trusted, not checked: it must exceed every index.

    Returns
    -------
    wp.array[wp.int32]
        ``(3 * n_faces,)`` new flat face buffer with corrected winding, on ``faces.device``.
        Vertices are unchanged.

    See Also
    --------
    [`is_winding_consistent`][ordito.validation.is_winding_consistent]
    [`face_flip_mask`][ordito.validation.face_flip_mask]
    [`make_normals_outward`][ordito.repair.make_normals_outward]

    Notes
    -----
    Each connected component keeps the winding of its lowest-indexed face, so on an orientable
    mesh the result is a deterministic function of ``faces`` on either device;
    ``trimesh.repair.fix_winding``'s BFS likewise keeps its seed face's winding, though its seed
    choice is its own. Use [`make_volume`][ordito.repair.make_volume] afterwards to also orient
    normals outward.

    On a **non-orientable** mesh no consistent winding exists, so this cannot succeed and does not
    fail either: the flood-fill orients everything it reaches and the contradiction is left on a
    seam. The seam can even end up with *more* inconsistent edges than before the pass ran, not
    merely the same ones — so treat the result as unrepaired rather than partly repaired, and test
    with [`is_orientable`][ordito.validation.is_orientable] first if that matters. Under
    [`is_deterministic`][ordito.config.is_deterministic] the seam is a function of ``faces`` too
    ([`face_flip_mask`][ordito.validation.face_flip_mask] says which).

    Examples
    --------
    Every seventh face of an icosphere flipped, face 0 among them: the whole mesh follows face 0,
    so it comes out consistent but inside out:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    rows = faces.numpy().reshape(-1, 3)
    rows[::7] = rows[::7, ::-1]
    mixed = wp.array(rows.ravel(), dtype=wp.int32)
    print(od.validation.is_winding_consistent(mixed))  # False
    consistent = od.repair.make_winding_consistent(mixed)
    print(od.validation.is_winding_consistent(consistent))  # True
    print(f"{od.measures.volume(vertices, consistent):.3f}")  # -4.047
    ```
    """
    n_faces = faces.size // 3
    device = faces.device
    if n_faces == 0:
        return _launch.empty(0, dtype=wp.int32, device=device)

    # The flip mask's parity words, solved straight off the halfedge mates with no adjacency table
    # and no host read of its length -- the bits ``face_orientation_bits`` gives -- and read by the
    # flip itself, so the mask is never stored.
    words = _face_flip_words(faces, n_vertices, None)
    out_faces = _launch.empty(3 * n_faces, dtype=wp.int32, device=device)
    _launch.launch(
        kernel_repair.flip_faces_by_parity,
        dim=n_faces,
        inputs=[faces, words, out_faces],
        device=device,
    )
    return out_faces

make_volume

make_volume(
    vertices: array[vec3],
    faces: array[int32],
    *,
    multibody: bool = False,
    mates: array[int32] | None = None,
) -> wp.array[wp.int32]

Orient faces so the mesh encloses a positive signed volume (normals point outward).

Mirrors trimesh.repair.fix_inversion. With multibody=False (default) the mesh is only corrected when it is watertight (every undirected edge shared by exactly two faces) and its total signed volume is negative, in which case every face is reversed. With multibody=True each connected component is corrected independently by the sign of its own signed volume.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
multibody bool

When True correct each connected component independently rather than the mesh as a whole. Under is_deterministic each component's volume is summed exactly, so a component of near-zero volume is flipped or kept the same way on every call.

False
mates array[int32] | None

(3 * n_faces,) halfedge_mates of faces when the caller holds them (Trimesh.halfedge_mates), to spare pairing the halfedges again. Trusted, not checked.

None

Returns:

Type Description
array[int32]

(3 * n_faces,) new flat face buffer with outward-oriented normals, on faces.device. Vertices are unchanged.

Raises:

Type Description
RuntimeError

If vertices, faces and mates are not all on one device.

See Also

is_volume Test whether this succeeded. volume Measure the result. make_winding_consistent make_normals_outward

Notes

The signed volume is sum(dot(v0, cross(v1, v2)) / 6) measured from the origin, as in is_volume. Unlike trimesh.repair.fix_inversion's multibody path, this does not skip components that are not watertight/consistently wound: an open component's signed volume is ill-defined and may be flipped spuriously. Run make_winding_consistent first (see make_normals_outward) and reserve multibody for meshes whose bodies are individually closed.

Examples:

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
inside_out = od.repair.reverse_winding(faces)
print(od.validation.is_volume(vertices, inside_out))  # False
fixed = od.repair.make_volume(vertices, inside_out)
print(od.validation.is_volume(vertices, fixed))  # True
print(f"{od.measures.volume(vertices, fixed):.3f}")  # 4.047
Source code in ordito/repair.py
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
def make_volume(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    multibody: bool = False,
    mates: wp.array[wp.int32] | None = None,
) -> wp.array[wp.int32]:
    """
    Orient faces so the mesh encloses a positive signed volume (normals point outward).

    Mirrors ``trimesh.repair.fix_inversion``. With ``multibody=False`` (default) the mesh is only
    corrected when it is watertight (every undirected edge shared by exactly two faces) and its
    total signed volume is negative, in which case every face is reversed. With ``multibody=True``
    each connected component is corrected independently by the sign of its own signed volume.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    multibody
        When ``True`` correct each connected component independently rather than the mesh as a
        whole. Under [`is_deterministic`][ordito.config.is_deterministic] each component's volume
        is summed exactly, so a component of near-zero volume is flipped or kept the same way on
        every call.
    mates
        ``(3 * n_faces,)`` [`halfedge_mates`][ordito.halfedge.halfedge_mates] of ``faces`` when the
        caller holds them ([`Trimesh.halfedge_mates`][ordito.mesh.Trimesh.halfedge_mates]), to spare
        pairing the halfedges again. Trusted, not checked.

    Returns
    -------
    wp.array[wp.int32]
        ``(3 * n_faces,)`` new flat face buffer with outward-oriented normals, on
        ``faces.device``. Vertices are unchanged.

    Raises
    ------
    RuntimeError
        If ``vertices``, ``faces`` and ``mates`` are not all on one device.

    See Also
    --------
    [`is_volume`][ordito.validation.is_volume]
        Test whether this succeeded.
    [`volume`][ordito.measures.volume]
        Measure the result.
    [`make_winding_consistent`][ordito.repair.make_winding_consistent]
    [`make_normals_outward`][ordito.repair.make_normals_outward]

    Notes
    -----
    The signed volume is ``sum(dot(v0, cross(v1, v2)) / 6)`` measured from the origin, as in
    [`is_volume`][ordito.validation.is_volume]. Unlike ``trimesh.repair.fix_inversion``'s
    multibody path, this does not skip components that are not watertight/consistently wound: an
    open component's signed volume is ill-defined and may be flipped spuriously. Run
    [`make_winding_consistent`][ordito.repair.make_winding_consistent] first (see
    [`make_normals_outward`][ordito.repair.make_normals_outward]) and reserve ``multibody``
    for meshes whose bodies are individually closed.

    Examples
    --------
    ```python
    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    inside_out = od.repair.reverse_winding(faces)
    print(od.validation.is_volume(vertices, inside_out))  # False
    fixed = od.repair.make_volume(vertices, inside_out)
    print(od.validation.is_volume(vertices, fixed))  # True
    print(f"{od.measures.volume(vertices, fixed):.3f}")  # 4.047
    ```
    """
    require_same_device(vertices=vertices, faces=faces, mates=mates)
    return _outward_faces(vertices, faces, multibody=multibody, owned=False, mates=mates)

make_normals_outward

make_normals_outward(
    vertices: array[vec3],
    faces: array[int32],
    *,
    multibody: bool = False,
) -> wp.array[wp.int32]

Make winding consistent and orient normals outward (winding fix followed by inversion fix).

Equivalent to trimesh.repair.fix_normals: first make_winding_consistent gives every connected component a coherent winding, then make_volume flips it (or each body, with multibody=True) so normals point outward. On a watertight, orientable mesh the result satisfies is_volume.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
multibody bool

Forwarded to make_volume: correct each connected component independently.

False

Returns:

Type Description
array[int32]

(3 * n_faces,) new flat face buffer with consistent winding and outward normals, on faces.device. Vertices are unchanged.

Raises:

Type Description
RuntimeError

If vertices and faces are not all on one device.

See Also

make_winding_consistent make_volume is_volume

Examples:

Every seventh face of an icosphere flipped comes back consistent and facing out:

import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
rows = faces.numpy().reshape(-1, 3)
rows[::7] = rows[::7, ::-1]
mixed = wp.array(rows.ravel(), dtype=wp.int32)
print(od.validation.is_winding_consistent(mixed))  # False
outward = od.repair.make_normals_outward(vertices, mixed)
print(od.validation.is_winding_consistent(outward))  # True
print(f"{od.measures.volume(vertices, outward):.3f}")  # 4.047
Source code in ordito/repair.py
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
def make_normals_outward(
    vertices: wp.array[wp.vec3], faces: wp.array[wp.int32], *, multibody: bool = False
) -> wp.array[wp.int32]:
    """
    Make winding consistent and orient normals outward (winding fix followed by inversion fix).

    Equivalent to ``trimesh.repair.fix_normals``: first
    [`make_winding_consistent`][ordito.repair.make_winding_consistent] gives every connected
    component a coherent winding, then [`make_volume`][ordito.repair.make_volume] flips it (or each
    body, with ``multibody=True``) so normals point outward. On a watertight, orientable mesh the
    result satisfies [`is_volume`][ordito.validation.is_volume].

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    multibody
        Forwarded to [`make_volume`][ordito.repair.make_volume]: correct each connected component
        independently.

    Returns
    -------
    wp.array[wp.int32]
        ``(3 * n_faces,)`` new flat face buffer with consistent winding and outward normals, on
        ``faces.device``. Vertices are unchanged.

    Raises
    ------
    RuntimeError
        If ``vertices`` and ``faces`` are not all on one device.

    See Also
    --------
    [`make_winding_consistent`][ordito.repair.make_winding_consistent]
    [`make_volume`][ordito.repair.make_volume]
    [`is_volume`][ordito.validation.is_volume]

    Examples
    --------
    Every seventh face of an icosphere flipped comes back consistent and facing out:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    rows = faces.numpy().reshape(-1, 3)
    rows[::7] = rows[::7, ::-1]
    mixed = wp.array(rows.ravel(), dtype=wp.int32)
    print(od.validation.is_winding_consistent(mixed))  # False
    outward = od.repair.make_normals_outward(vertices, mixed)
    print(od.validation.is_winding_consistent(outward))  # True
    print(f"{od.measures.volume(vertices, outward):.3f}")  # 4.047
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    if faces.size // 3 == 0:
        return _launch.empty(0, dtype=wp.int32, device=faces.device)
    # ``make_winding_consistent`` carrying the halfedge mates over to the wound faces, which the
    # orientation test reads rather than pairing the halfedges again. ``wound`` is this call's own
    # buffer, so a mesh already facing outward returns it as it is.
    wound, wound_mates = _wound_with_mates(faces, vertices.size)
    return _outward_faces(vertices, wound, multibody=multibody, owned=True, mates=wound_mates)

remove_folded_faces

remove_folded_faces(
    vertices: array[vec3],
    faces: array[int32],
    *,
    angle: float = 160.0,
    mates: array[int32] | None = None,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32]]

Drop faces that fold back over their own ring, and reindex.

A fold is a pair of neighbouring faces whose dihedral angle is near pi: the two triangles lie almost on top of each other with opposite normals, which is what a badly reconstructed or self-intersecting patch looks like locally. Of the two, the face dropped is the one whose normal points against its neighbours' summed normals -- the one turned back over its ring; the other agrees with its surroundings and is kept. Such a face contributes no surface and breaks every normal-based computation downstream, so removing it is a repair rather than a simplification.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
angle float

Dihedral threshold in degrees; a face with a neighbour above it is dropped when it also faces against its neighbours (see above). MeshLab's folded_faces_angle_threshold, whose default of 160 is this one. Must be in (0, 180].

160.0
mates array[int32] | None

(3 * n_faces,) halfedge_mates of faces when the caller holds them (Trimesh.halfedge_mates), to spare pairing the halfedges again. Trusted, not checked.

None

Returns:

Name Type Description
new_vertices array[vec3]

(n_new_vertices,) vertices still referenced by a kept face, compacted from index zero.

new_faces array[int32]

(3 * n_new_faces,) flat buffer of the kept faces, remapped into new_vertices.

Raises:

Type Description
RuntimeError

If vertices, faces and mates are not all on one device.

ValueError

If angle is not in (0, 180].

See Also

validation.face_defective_mask flip_t_vertices remove_degenerate_faces

Notes

MeshLab's meshing_remove_folded_faces flips the offending edge instead of deleting the face, which preserves the face count but can only help when the fold is a triangulation mistake rather than genuinely folded geometry. Deletion is the choice the rest of this module makes (see remove_degenerate_faces and remove_non_manifold_faces), and it leaves a hole that ordito.holes can retriangulate properly.

Examples:

Dragging a grid vertex past its neighbour turns two triangles upside down; both are dropped:

import warp as wp

import ordito as od

vertices, faces = od.creation.grid(count=(5, 5))
positions = vertices.numpy()
positions[6] += [0.3, 0.0, 0.0]
folded = wp.array(positions, dtype=wp.vec3)
normals, _ = od.triangles.face_normals_and_areas(folded, faces)
print(int((normals.numpy()[:, 2] < 0.0).sum()))  # 2
new_vertices, new_faces = od.repair.remove_folded_faces(folded, faces)
print(faces.shape[0] // 3, new_faces.shape[0] // 3)  # 32 30
Source code in ordito/repair.py
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
def remove_folded_faces(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    angle: float = 160.0,
    mates: wp.array[wp.int32] | None = None,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32]]:
    """
    Drop faces that fold back over their own ring, and reindex.

    A fold is a pair of neighbouring faces whose dihedral angle is near ``pi``: the two triangles
    lie almost on top of each other with opposite normals, which is what a badly reconstructed or
    self-intersecting patch looks like locally. Of the two, the face dropped is the one whose
    normal points against its neighbours' summed normals -- the one turned back over its ring; the
    other agrees with its surroundings and is kept. Such a face contributes no surface and breaks
    every normal-based computation downstream, so removing it is a repair rather than a
    simplification.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    angle
        Dihedral threshold in **degrees**; a face with a neighbour above it is dropped when it also
        faces against its neighbours (see above). MeshLab's
        ``folded_faces_angle_threshold``, whose default of ``160`` is this one. Must be in
        ``(0, 180]``.
    mates
        ``(3 * n_faces,)`` [`halfedge_mates`][ordito.halfedge.halfedge_mates] of ``faces`` when the
        caller holds them ([`Trimesh.halfedge_mates`][ordito.mesh.Trimesh.halfedge_mates]), to spare
        pairing the halfedges again. Trusted, not checked.

    Returns
    -------
    new_vertices : wp.array[wp.vec3]
        ``(n_new_vertices,)`` vertices still referenced by a kept face, compacted from index zero.
    new_faces : wp.array[wp.int32]
        ``(3 * n_new_faces,)`` flat buffer of the kept faces, remapped into ``new_vertices``.

    Raises
    ------
    RuntimeError
        If ``vertices``, ``faces`` and ``mates`` are not all on one device.
    ValueError
        If ``angle`` is not in ``(0, 180]``.

    See Also
    --------
    [`validation.face_defective_mask`][ordito.validation.face_defective_mask]
    [`flip_t_vertices`][ordito.repair.flip_t_vertices]
    [`remove_degenerate_faces`][ordito.repair.remove_degenerate_faces]

    Notes
    -----
    MeshLab's ``meshing_remove_folded_faces`` *flips* the offending edge instead of deleting the
    face, which preserves the face count but can only help when the fold is a triangulation mistake
    rather than genuinely folded geometry. Deletion is the choice the rest of this module makes (see
    [`remove_degenerate_faces`][ordito.repair.remove_degenerate_faces] and
    [`remove_non_manifold_faces`][ordito.repair.remove_non_manifold_faces]), and it leaves a hole
    that [`ordito.holes`][ordito.holes] can retriangulate properly.

    Examples
    --------
    Dragging a grid vertex past its neighbour turns two triangles upside down; both are dropped:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.grid(count=(5, 5))
    positions = vertices.numpy()
    positions[6] += [0.3, 0.0, 0.0]
    folded = wp.array(positions, dtype=wp.vec3)
    normals, _ = od.triangles.face_normals_and_areas(folded, faces)
    print(int((normals.numpy()[:, 2] < 0.0).sum()))  # 2
    new_vertices, new_faces = od.repair.remove_folded_faces(folded, faces)
    print(faces.shape[0] // 3, new_faces.shape[0] // 3)  # 32 30
    ```
    """
    require_same_device(vertices=vertices, faces=faces, mates=mates)
    if not 0.0 < angle <= 180.0:
        raise ValueError(f"angle must be in (0, 180] degrees, got {angle}")
    device = faces.device
    n_faces = faces.size // 3
    if n_faces == 0:
        return _launch.clone(vertices), _launch.clone(faces)
    if mates is None:
        mates = od.halfedge.halfedge_mates(faces, vertices.size)
    # The fold decision and the submesh extraction's marking pass in one launch; the keep mask it
    # writes is what the compaction reads.
    keep = _launch.empty(n_faces, dtype=wp.bool, device=device)
    ranks = _launch.zeros(n_faces + vertices.size, dtype=wp.int32, device=device)
    _launch.launch(
        kernel_repair.mark_unfolded_faces,
        dim=n_faces,
        inputs=[vertices, faces, None, mates, wp.float32(math.radians(angle)), keep, ranks],
        device=device,
    )
    new_vertices, new_faces, _vertex_index, _ranks = _compact_marked_submesh(
        vertices, faces, keep, ranks, keep_masked=True, with_index=False
    )
    return new_vertices, new_faces

fix_self_intersections

fix_self_intersections(
    vertices: array[vec3],
    faces: array[int32],
    *,
    method: Literal["local", "voxel"] = "local",
    max_expand: int = 1,
    max_iter: int = 3,
    voxel_size: float | None = None,
    return_provenance: Literal[False] = False,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32]]
fix_self_intersections(
    vertices: array[vec3],
    faces: array[int32],
    *,
    method: Literal["local", "voxel"] = "local",
    max_expand: int = 1,
    max_iter: int = 3,
    voxel_size: float | None = None,
    return_provenance: Literal[True],
) -> tuple[
    wp.array[wp.vec3],
    wp.array[wp.int32],
    od.interpolation.Provenance,
]
fix_self_intersections(
    vertices: array[vec3],
    faces: array[int32],
    *,
    method: Literal["local", "voxel"] = "local",
    max_expand: int = 1,
    max_iter: int = 3,
    voxel_size: float | None = None,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[
        wp.array[wp.vec3],
        wp.array[wp.int32],
        od.interpolation.Provenance,
    ]
)

Remove a mesh's self-intersections, either locally or by rebuilding it.

ordito.validation.face_self_intersecting_mask detects a self-intersection; this is the repair, in the two forms that exist:

  • "local" cuts the trouble out and rebuilds it. The intersecting faces are dilated by max_expand rings, that region is deleted, and the rims it opens are refilled by the minimum-weight patch -- so the surface away from the intersection is untouched. Iterated, because a patch can intersect something itself.
  • "voxel" rebuilds the whole surface as the zero level set of its own signed distance field. A level set cannot self-intersect, so this always terminates and resamples everything -- including the parts that were fine. Read the qualification in the Notes: the level set is clean, its triangulation can still carry an artifact at an ambiguous marching-cubes cell.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
method Literal['local', 'voxel']

"local" (default) to cut and refill, "voxel" to rebuild through a distance field.

'local'
max_expand int

Rings of faces added around each intersecting face before deleting, in the "local" method. Larger takes more surface with it and is likelier to succeed in one pass.

1
max_iter int

Cap on cut-and-refill passes. The loop also stops as soon as nothing intersects. Raising it does not help a deep interpenetration and inflates the mesh; see the Notes.

3
voxel_size float | None

Lattice spacing for the "voxel" method. None uses 1/128 of the bounding-box diagonal.

None
return_provenance bool

If True, also return the Provenance that carries any per-vertex or per-face field onto the result.

False

Returns:

Name Type Description
new_vertices array[vec3]

(n_new_vertices,) vertices on vertices.device. A clean input is returned as a copy.

new_faces array[int32]

(3 * n_new_faces,) faces on vertices.device.

provenance Provenance

Only when return_provenance is True. Under "local", the cut-and-refill passes' provenances chained, as refill_region reports them: what survives every cut is its own source and the patches' faces have none. Under "voxel" nothing of the input survives, so no vertex or face has a source (-1).

Raises:

Type Description
ValueError

If method is not "local" or "voxel", max_expand is negative, or max_iter is less than 1.

RuntimeError

If vertices and faces are not all on one device.

Notes

Success is not guaranteed by either method, and neither is asserted. For "local": a region whose rim cannot be triangulated without crossing something, or one that grows to swallow the mesh, leaves intersections behind; the loop stops at max_iter and returns what it has. For "voxel": the level set is clean, but marching cubes can emit a touching or non-manifold pair at an ambiguous cell, and that is resolution-dependent -- a finer lattice can introduce a handful of such faces where a coarser one has none. Check with ordito.validation.is_self_intersecting when it matters.

What the "local" method is for. It clears a shallow self-intersection outright -- a torus whose tube passes through itself can be fully cleared at either dilation budget -- and only reduces a deep one, such as two icospheres overlapping by a third of their diameter. That is the method's shape rather than a tuning failure: cutting out a lens-shaped overlap leaves a rim whose minimum-weight patch runs back through the other shell, so the pass converges only where the damage is a band. Reach for "voxel" when two closed pieces genuinely interpenetrate -- a level set has no notion of two shells.

On that input class the result is nondeterministic and max_iter is not a quality knob. Past a certain point, raising it does not reduce the residual intersections further while the face count climbs past the input's -- each pass refills a rim the next one cuts out again. Repeated runs on one input can also differ, from the refill chain's own atomic-ordering nondeterminism, so that variation is not a regression. Do not raise max_iter hoping for convergence on a deep interpenetration; the answer is "voxel".

The two methods differ in what they preserve, not in quality. "local" keeps the input's triangulation everywhere it did not cut, so a per-vertex attribute survives outside the patch; "voxel" keeps nothing but the shape, and its accuracy is the lattice's.

See Also

ordito.validation.face_self_intersecting_mask The detector, and what to check the result with. ordito.holes.refill_region The cut-and-refill step each "local" pass runs. ordito.levelset.offset_mesh The same level-set machinery at a non-zero distance.

Examples:

An icosphere with one vertex pulled through to the far side is cut and refilled locally:

import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
positions = vertices.numpy()
positions[0] *= -1.25
spiked = wp.array(positions, dtype=wp.vec3)
print(od.validation.is_self_intersecting(wp.Mesh(points=spiked, indices=faces)))  # True
clean_vertices, clean_faces = od.repair.fix_self_intersections(spiked, faces)
clean_mesh = wp.Mesh(points=clean_vertices, indices=clean_faces)
print(od.validation.is_self_intersecting(clean_mesh))  # False
print(od.validation.is_watertight(clean_vertices, clean_faces))  # True

Two interpenetrating spheres need the "voxel" rebuild, which merges them into one shell:

import numpy as np
import warp as wp

import ordito as od

vertices, faces = od.creation.icosphere(subdivisions=2)
shifted = vertices.numpy() + [1.0, 0.0, 0.0]
pair_vertices = wp.array(np.vstack([vertices.numpy(), shifted]), dtype=wp.vec3)
pair_faces = wp.array(
    np.concatenate([faces.numpy(), faces.numpy() + vertices.shape[0]]), dtype=wp.int32
)
pair_mesh = wp.Mesh(points=pair_vertices, indices=pair_faces)
print(od.validation.is_self_intersecting(pair_mesh))  # True
merged_vertices, merged_faces = od.repair.fix_self_intersections(
    pair_vertices, pair_faces, method="voxel", voxel_size=0.1
)
print(od.validation.is_watertight(merged_vertices, merged_faces))  # True
Source code in ordito/repair.py
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
def fix_self_intersections(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    method: Literal["local", "voxel"] = "local",
    max_expand: int = 1,
    max_iter: int = 3,
    voxel_size: float | None = None,
    return_provenance: bool = False,
) -> (
    tuple[wp.array[wp.vec3], wp.array[wp.int32]]
    | tuple[wp.array[wp.vec3], wp.array[wp.int32], od.interpolation.Provenance]
):
    """

    Remove a mesh's self-intersections, either locally or by rebuilding it.

    [`ordito.validation.face_self_intersecting_mask`][ordito.validation.face_self_intersecting_mask]
    detects a self-intersection; this is the repair, in the two forms that exist:

    - ``"local"`` cuts the trouble out and rebuilds it. The intersecting faces are dilated by
      ``max_expand`` rings, that region is deleted, and the rims it opens are refilled by the
      minimum-weight patch -- so the surface away from the intersection is **untouched**. Iterated,
      because a patch can intersect something itself.
    - ``"voxel"`` rebuilds the whole surface as the zero level set of its own signed distance field.
      A level set cannot self-intersect, so this always terminates and resamples everything --
      including the parts that were fine. Read the qualification in the Notes: the level set is
      clean, its *triangulation* can still carry an artifact at an ambiguous marching-cubes cell.


    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    method
        ``"local"`` (default) to cut and refill, ``"voxel"`` to rebuild through a distance field.
    max_expand
        Rings of faces added around each intersecting face before deleting, in the ``"local"``
        method. Larger takes more surface with it and is likelier to succeed in one pass.
    max_iter
        Cap on cut-and-refill passes. The loop also stops as soon as nothing intersects. Raising it
        does **not** help a deep interpenetration and inflates the mesh; see the Notes.
    voxel_size
        Lattice spacing for the ``"voxel"`` method. ``None`` uses 1/128 of the bounding-box
        diagonal.
    return_provenance
        If ``True``, also return the [`Provenance`][ordito.interpolation.Provenance] that carries
        any per-vertex or per-face field onto the result.

    Returns
    -------
    new_vertices : wp.array[wp.vec3]
        ``(n_new_vertices,)`` vertices on ``vertices.device``. A clean input is returned as a copy.
    new_faces : wp.array[wp.int32]
        ``(3 * n_new_faces,)`` faces on ``vertices.device``.
    provenance : Provenance
        Only when ``return_provenance`` is ``True``. Under ``"local"``, the cut-and-refill passes'
        provenances chained, as [`refill_region`][ordito.holes.refill_region] reports them: what
        survives every cut is its own source and the patches' faces have none. Under ``"voxel"``
        nothing of the input survives, so no vertex or face has a source (``-1``).

    Raises
    ------
    ValueError
        If ``method`` is not ``"local"`` or ``"voxel"``, ``max_expand`` is negative, or ``max_iter``
        is less than 1.
    RuntimeError
        If ``vertices`` and ``faces`` are not all on one device.

    Notes
    -----
    **Success is not guaranteed by either method, and neither is asserted.** For ``"local"``: a
    region whose rim cannot be triangulated without crossing something, or one that grows to swallow
    the mesh, leaves intersections behind; the loop stops at ``max_iter`` and returns what it has.
    For ``"voxel"``: the level set is clean, but marching cubes can emit a touching or non-manifold
    pair at an ambiguous cell, and that is resolution-dependent -- a finer lattice can introduce a
    handful of such faces where a coarser one has none. Check with
    [`ordito.validation.is_self_intersecting`][ordito.validation.is_self_intersecting] when it
    matters.

    **What the ``"local"`` method is for.** It clears a *shallow* self-intersection outright -- a
    torus whose tube passes through itself can be fully cleared at either dilation budget -- and
    only reduces a *deep* one, such as two icospheres overlapping by a third of their diameter. That
    is the method's shape rather than a tuning failure: cutting out a lens-shaped overlap leaves a
    rim whose minimum-weight patch runs back through the other shell, so the pass converges only
    where the damage is a band. Reach for ``"voxel"`` when two closed pieces genuinely
    interpenetrate -- a level set has no notion of two shells.

    **On that input class the result is nondeterministic and ``max_iter`` is not a quality knob.**
    Past a certain point, raising it does not reduce the residual intersections further while the
    face count climbs past the input's -- each pass refills a rim the next one cuts out again.
    Repeated runs on one input can also differ, from the refill chain's own atomic-ordering
    nondeterminism, so that variation is not a regression. Do not raise ``max_iter`` hoping for
    convergence on a deep interpenetration; the answer is ``"voxel"``.

    The two methods differ in what they preserve, not in quality. ``"local"`` keeps the input's
    triangulation everywhere it did not cut, so a per-vertex attribute survives outside the patch;
    ``"voxel"`` keeps nothing but the shape, and its accuracy is the lattice's.

    See Also
    --------
    [`ordito.validation.face_self_intersecting_mask`][ordito.validation.face_self_intersecting_mask]
        The detector, and what to check the result with.
    [`ordito.holes.refill_region`][ordito.holes.refill_region]
        The cut-and-refill step each ``"local"`` pass runs.
    [`ordito.levelset.offset_mesh`][ordito.levelset.offset_mesh]
        The same level-set machinery at a non-zero distance.

    Examples
    --------
    An icosphere with one vertex pulled through to the far side is cut and refilled locally:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    positions = vertices.numpy()
    positions[0] *= -1.25
    spiked = wp.array(positions, dtype=wp.vec3)
    print(od.validation.is_self_intersecting(wp.Mesh(points=spiked, indices=faces)))  # True
    clean_vertices, clean_faces = od.repair.fix_self_intersections(spiked, faces)
    clean_mesh = wp.Mesh(points=clean_vertices, indices=clean_faces)
    print(od.validation.is_self_intersecting(clean_mesh))  # False
    print(od.validation.is_watertight(clean_vertices, clean_faces))  # True
    ```

    Two interpenetrating spheres need the ``"voxel"`` rebuild, which merges them into one shell:

    ```python
    import numpy as np
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.icosphere(subdivisions=2)
    shifted = vertices.numpy() + [1.0, 0.0, 0.0]
    pair_vertices = wp.array(np.vstack([vertices.numpy(), shifted]), dtype=wp.vec3)
    pair_faces = wp.array(
        np.concatenate([faces.numpy(), faces.numpy() + vertices.shape[0]]), dtype=wp.int32
    )
    pair_mesh = wp.Mesh(points=pair_vertices, indices=pair_faces)
    print(od.validation.is_self_intersecting(pair_mesh))  # True
    merged_vertices, merged_faces = od.repair.fix_self_intersections(
        pair_vertices, pair_faces, method="voxel", voxel_size=0.1
    )
    print(od.validation.is_watertight(merged_vertices, merged_faces))  # True
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    if method not in ("local", "voxel"):
        raise ValueError(f"method must be 'local' or 'voxel', got {method!r}")
    if max_expand < 0:
        raise ValueError("max_expand must be non-negative")
    if max_iter < 1:
        raise ValueError("max_iter must be at least 1")

    if faces.size == 0:
        return _unchanged(_launch.clone(vertices), _launch.clone(faces), return_provenance)

    if method == "voxel":
        spacing = voxel_size
        if spacing is None:
            spacing = float(od.bounds.enclosing_diagonal(vertices)) / _VOXEL_REBUILD_RESOLUTION
        shape, box = od.proximity.signed_distance_lattice(vertices, spacing, pad=2)
        new_vertices, new_faces = od.levelset.signed_distance_level_set(
            vertices, faces, 0.0, shape, bounds=box, sign_mode="winding"
        )
        if not return_provenance:
            return new_vertices, new_faces
        device = vertices.device
        provenance = od.interpolation.Provenance(
            _launch.full(new_vertices.size, -1, dtype=wp.int32, device=device),
            _launch.full(new_faces.size // 3, -1, dtype=wp.int32, device=device),
            None,
            vertices.size,
            faces.size // 3,
        )
        return new_vertices, new_faces, provenance

    # The input buffers are only read until the first refill replaces them, so the copy a clean
    # input is owed is taken here rather than paid on every pass.
    steps: list[od.interpolation.Provenance] | None = [] if return_provenance else None
    new_vertices, new_faces = _cut_and_refill(vertices, faces, max_expand, max_iter, steps)
    if new_faces is faces:
        return _unchanged(_launch.clone(vertices), _launch.clone(faces), return_provenance)
    if steps is None:
        return new_vertices, new_faces
    provenance = _chained_steps(steps, vertices.size, faces.size // 3, vertices.device)
    return new_vertices, new_faces, provenance

remove_tunnels

remove_tunnels(
    vertices: array[vec3],
    faces: array[int32],
    max_length: float,
    *,
    metric: str = "plane_normalized",
    max_iter: int = 100,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32], int]

Remove thin handles by cutting along their short tunnel loops and sealing the two rims.

A handle is a genus the surface did not need: a scanning artifact where two sheets fused, or a reconstruction that bridged across a gap. Its signature is a short non-contractible loop -- short being the whole test, since every genus of the intended shape has loops the size of the shape. So: take a homology basis, shorten each loop within its class (shorten_loop), keep the ones that come in under max_length, cut along those and fill the boundary loops the cut opens. Cutting a surface along a non-separating cycle and sealing the two rims it creates drops the genus by exactly one, so 2 * removed is the rise in euler_characteristic -- verified rather than reported, and the invariant to assert if you extend this.

The basis is the greedy system of loops through a root vertex (homology_generators), so a handle near the root comes out as its own short loop. One far from the root can come out only inside a combination with other classes, which no shortening within the class can separate again; so when no loop of that basis is short enough, every vertex of the shortened basis is searched for the shortest non-separating loop through it, along mesh edges and within max_length / 2 of it. Every non-separating loop crosses the basis, so this search finds the shortest one on the surface: a call returns 0 only when no non-separating edge loop is within max_length, and every handle whose girth along the edges is under max_length is removed by calling it until then. The loops this search finds are shortest-path loops already and are cut as found. Its cost grows with the number of vertices within max_length / 2 of the basis, and the call that finds nothing, the last one of the documented loop, always runs it.

Nothing is removed when no loop is short enough, and the input is returned unchanged -- so this is safe to run on a mesh whose genus is intended, provided max_length is below the scale of its real handles.

One disjoint pass per call

The loops kept are pairwise vertex-disjoint, shortest first. Cutting along two loops that cross is not the same operation as cutting along each in turn -- the shared vertex is split by both cuts at once -- and without the restriction the genus can stop dropping one per loop, or the surface can shatter into extra pieces. Disjoint loops can still be dependent, together bounding a piece of the surface that cutting along all of them would split off, so the longest loop of any such family is left uncut and the result stays one connected surface. The cost is that one call removes at most one tunnel per disjoint family, so a mesh whose basis loops all overlap needs to be run again. Call it in a loop until removed is 0.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions.

required
faces array[int32]

(3 * n_faces,) triangle index buffer. Must be a closed, connected, edge-manifold surface, which is what the homology basis needs.

required
max_length float

Loops at or under this length are removed. It is an absolute length in the mesh's own units, so scale it off something intrinsic -- the mean edge length times the number of triangles a real handle would take to go round.

required
metric str

Triangulation metric for the two rims, as fill_min_weight takes it.

'plane_normalized'
max_iter int

Sweep cap handed to shorten_loop. Shortening is what makes the length test meaningful: a tree-cotree loop around a thin handle can be many times the handle's own girth, so an unshortened basis under-reports every tunnel.

100

Returns:

Name Type Description
vertices array[vec3]

(n_new_vertices,) positions of the result. Longer than the input's wherever the cut split a vertex; the existing positions are unchanged and no new position is invented, since the rims are filled over their own vertices.

faces array[int32]

(3 * n_new_faces,) flat triangle index buffer, the cut mesh plus the fill triangles.

removed int

How many loops were cut. Zero means nothing was short enough, and the buffers are the input's.

Returned unconditionally, unlike the diagnostic counts on straighten_boundary and remove_degree3_vertices, which sit behind a return_count keyword. This one is part of the answer rather than a report on it: one call removes at most one tunnel per disjoint family, so the documented usage is to loop until it reads zero, and a caller who cannot see it cannot use the function correctly. remesh.intrinsic_delaunay's iteration count is unconditional for the same reason.

Raises:

Type Description
ValueError

If max_length is negative, or the mesh has a boundary (a surface with boundary has a different homology basis, so "tunnel" is not defined by this test).

RuntimeError

If vertices and faces are not all on one device.

See Also

shorten_loop Makes the length test meaningful, and is where the loops come from. homology_generators fix_self_intersections The other topological repair here: that one removes crossings, this one removes genus.

Examples:

A thin torus has a short loop around its tube (length about 1.26) and a long one around its hole; cutting the short one leaves a sphere:

import ordito as od

vertices, faces = od.creation.torus(1.0, 0.2, major_sections=24, minor_sections=8)
print(od.measures.euler_characteristic(faces))  # 0
new_vertices, new_faces, removed = od.repair.remove_tunnels(vertices, faces, max_length=2.0)
print(removed, od.measures.euler_characteristic(new_faces))  # 1 2
print(od.validation.is_watertight(new_vertices, new_faces))  # True
_, _, removed = od.repair.remove_tunnels(vertices, faces, max_length=0.5)
print(removed)  # 0
Source code in ordito/repair.py
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
def remove_tunnels(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    max_length: float,
    *,
    metric: str = "plane_normalized",
    max_iter: int = 100,
) -> tuple[wp.array[wp.vec3], wp.array[wp.int32], int]:
    """
    Remove thin handles by cutting along their short tunnel loops and sealing the two rims.

    A handle is a genus the surface did not need: a scanning artifact where two sheets fused, or a
    reconstruction that bridged across a gap. Its signature is a **short non-contractible loop** --
    short being the whole test, since every genus of the intended shape has loops the size of the
    shape. So: take a homology basis, shorten each loop within its class
    ([`shorten_loop`][ordito.geodesic_walk.shorten_loop]), keep the ones that come in under
    ``max_length``, cut along those and fill the boundary loops the cut opens. Cutting a surface
    along a non-separating cycle and sealing the two rims it creates drops the genus by exactly one,
    so ``2 * removed`` is the rise in
    [`euler_characteristic`][ordito.measures.euler_characteristic] -- verified rather than
    reported, and the invariant to assert if you extend this.

    The basis is the greedy system of loops through a root vertex
    ([`homology_generators`][ordito.homology.homology_generators]), so a handle near the root comes
    out as its own short loop. One far from the root can come out only inside a combination with
    other classes, which no shortening within the class can separate again; so when no loop of that
    basis is short enough, every vertex of the shortened basis is searched for the shortest
    non-separating loop through it, along mesh edges and within ``max_length / 2`` of it. Every
    non-separating loop crosses the basis, so this search finds the shortest one on the surface:
    a call returns ``0`` only when **no** non-separating edge loop is within ``max_length``, and
    every handle whose girth along the edges is under ``max_length`` is removed by calling it until
    then. The loops this search finds are shortest-path loops already and are cut as found. Its
    cost grows with the number of vertices within ``max_length / 2`` of the basis, and the call
    that finds nothing, the last one of the documented loop, always runs it.

    Nothing is removed when no loop is short enough, and the input is returned unchanged -- so this
    is safe to run on a mesh whose genus is intended, provided ``max_length`` is below the scale of
    its real handles.

    !!! note "One disjoint pass per call"
        The loops kept are pairwise **vertex-disjoint**, shortest first. Cutting along two loops
        that cross is not the same operation as cutting along each in turn -- the shared vertex is
        split by both cuts at once -- and without the restriction the genus can stop dropping one
        per loop, or the surface can shatter into extra pieces. Disjoint loops can still be
        **dependent**, together bounding a piece of the surface that cutting along all of them
        would split off, so the longest loop of any such family is left uncut and the result stays
        one connected surface. The cost is that one call removes at most one tunnel per disjoint
        family, so a mesh whose basis loops all overlap needs to be run again. Call it in a loop
        until ``removed`` is ``0``.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions.
    faces
        ``(3 * n_faces,)`` triangle index buffer. Must be a closed, connected,
        edge-manifold surface, which is what the homology basis needs.
    max_length
        Loops at or under this length are removed. It is an absolute length in the mesh's own
        units, so scale it off something intrinsic -- the mean edge length times the number of
        triangles a real handle would take to go round.
    metric
        Triangulation metric for the two rims, as
        [`fill_min_weight`][ordito.holes.fill_min_weight] takes it.
    max_iter
        Sweep cap handed to [`shorten_loop`][ordito.geodesic_walk.shorten_loop]. Shortening is what
        makes the length test meaningful: a tree-cotree loop around a thin handle can be many times
        the handle's own girth, so an unshortened basis under-reports every tunnel.

    Returns
    -------
    vertices : wp.array[wp.vec3]
        ``(n_new_vertices,)`` positions of the result. Longer than the input's wherever the cut
        split a vertex; the existing positions are unchanged and no new position is invented, since
        the rims are filled over their own vertices.
    faces : wp.array[wp.int32]
        ``(3 * n_new_faces,)`` flat triangle index buffer, the cut mesh plus the fill triangles.
    removed : int
        How many loops were cut. Zero means nothing was short enough, and the buffers are the
        input's.

        Returned **unconditionally**, unlike the diagnostic counts on
        [`straighten_boundary`][ordito.repair.straighten_boundary] and
        [`remove_degree3_vertices`][ordito.repair.remove_degree3_vertices], which sit behind
        a ``return_count`` keyword. This one is part of the answer rather than a report on it: one
        call removes at most one tunnel per disjoint family, so the documented usage is to loop
        until it reads zero, and a caller who cannot see it cannot use the function correctly.
        [`remesh.intrinsic_delaunay`][ordito.remesh.intrinsic_delaunay]'s iteration count is
        unconditional for the same reason.

    Raises
    ------
    ValueError
        If ``max_length`` is negative, or the mesh has a boundary (a surface with boundary has a
        different homology basis, so "tunnel" is not defined by this test).
    RuntimeError
        If ``vertices`` and ``faces`` are not all on one device.

    See Also
    --------
    [`shorten_loop`][ordito.geodesic_walk.shorten_loop]
        Makes the length test meaningful, and is where the loops come from.
    [`homology_generators`][ordito.homology.homology_generators]
    [`fix_self_intersections`][ordito.repair.fix_self_intersections]
        The other topological repair here: that one removes crossings, this one removes genus.

    Examples
    --------
    A thin torus has a short loop around its tube (length about 1.26) and a long one around its
    hole; cutting the short one leaves a sphere:

    ```python
    import ordito as od

    vertices, faces = od.creation.torus(1.0, 0.2, major_sections=24, minor_sections=8)
    print(od.measures.euler_characteristic(faces))  # 0
    new_vertices, new_faces, removed = od.repair.remove_tunnels(vertices, faces, max_length=2.0)
    print(removed, od.measures.euler_characteristic(new_faces))  # 1 2
    print(od.validation.is_watertight(new_vertices, new_faces))  # True
    _, _, removed = od.repair.remove_tunnels(vertices, faces, max_length=0.5)
    print(removed)  # 0
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    if max_length < 0.0:
        raise ValueError(f"max_length must be non-negative, got {max_length}")
    basis = _shortened_basis(vertices, faces, max_iter)
    if basis is None:
        return vertices, faces, 0
    selected = _disjoint_loops([loop for length, loop in basis.short if length <= max_length])
    if not selected:
        # The basis is the greedy one through its root, so a handle far from the root can appear
        # only inside a longer combination of classes. Before answering "nothing is short", search
        # every vertex of the basis for the shortest non-separating loop through it: every
        # non-separating loop crosses some basis loop, so a short one passes through one of them.
        selected = _disjoint_loops(_short_loops_through_basis(vertices, faces, basis, max_length))
    if not selected:
        return vertices, faces, 0

    # Disjoint is not independent: a family of disjoint non-trivial loops can still bound a piece
    # of the surface between them, and cutting along all of it splits that piece off instead of
    # dropping the genus by one per loop. The face labels of the cut mesh say which -- every
    # component after the first is one loop too many -- and they are read before cutting, so the
    # mesh is cut once, along the family that survives.
    labels, sides = _cut_face_labels(faces, selected, basis.twins)
    labels_np = read_array(labels)
    if np.unique(labels_np).size > 1:
        selected = _independent_loops(selected, labels_np, sides())
    cut_vertices, cut_faces = _cut_along_loops(vertices, faces, selected, basis.twins)
    cut_vertices = cast("wp.array[wp.vec3]", cut_vertices)
    # The cut writes every face index below its own vertex count, so the fill needs no reduction
    # to bound them.
    return (
        cut_vertices,
        od.holes.fill_min_weight(
            cut_vertices, cut_faces, metric=metric, n_vertices=cut_vertices.size
        ),
        len(selected),
    )

flip_t_vertices

flip_t_vertices(
    vertices: array[vec3],
    faces: array[int32],
    *,
    threshold: float = 40.0,
    max_iter: int = 10,
) -> wp.array[wp.int32]

Repair T-vertices by flipping the long edge of each sliver they create.

A T-vertex is a vertex that sits in the interior of a neighbouring triangle's edge rather than at one of its corners — the classic symptom of two patches stitched at different resolutions. The vertex is topologically fine, but the triangle opposite it is a sliver: its apex lies (nearly) on the far edge, which sends its circumradius-to-inradius ratio to infinity and makes every cotangent weight, normal and curvature estimate around it unusable.

The repair is a flip, not a deletion: flipping the sliver's long edge moves the diagonal off the T and leaves two well-shaped triangles, with the same vertices and the same face count.

Parameters:

Name Type Description Default
vertices array[vec3]

(n_vertices,) mesh vertex positions. Never modified.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
threshold float

Longest edge over the height onto it above which a triangle counts as a T-vertex sliver; that longest edge is the one flipped. The reciprocal of the "area_max_side" measure of face_quality (about 2 / sqrt(3) for an equilateral triangle, unbounded above). MeshLab's meshing_remove_t_vertices threshold, whose default of 40 is this one. Must be positive.

40.0
max_iter int

Maximum number of parallel flip passes. Each pass commits a conflict-free independent set of flips; MeshLab's repeat=True is the same idea serially.

10

Returns:

Type Description
array[int32]

(3 * n_faces,) flat face buffer with the slivers re-triangulated, on faces.device (a copy; the input is not modified).

Raises:

Type Description
RuntimeError

If vertices and faces are not all on one device.

See Also

ordito.remesh.flip_by_objective remove_folded_faces collapse_small_triangles

Notes

A flip cannot fix a T-vertex on the mesh boundary or on a non-manifold edge, because there is no second triangle to flip against. MeshLab offers an edge collapse method for that case; here the equivalent is collapse_small_triangles, which removes the sliver by merging its short edge instead.

Examples:

Vertex 2 sits a hair above the edge (0, 1) of the triangle below it, making triangle (0, 1, 2) a sliver; one flip replaces the edge by (2, 3):

import warp as wp

import ordito as od

vertices = wp.array(
    [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [1.0, 0.01, 0.0], [1.0, -1.0, 0.0], [1.0, 1.0, 0.0]],
    dtype=wp.vec3,
)
faces = wp.array([0, 3, 1, 0, 1, 2, 0, 2, 4, 2, 1, 4], dtype=wp.int32)
print(f"{od.triangles.face_quality(vertices, faces).numpy().max():.0f}")  # 5001
flipped = od.repair.flip_t_vertices(vertices, faces)
print(flipped.numpy().reshape(-1, 3).tolist())  # [[1, 2, 3], [0, 3, 2], [0, 2, 4], [2, 1, 4]]
print(f"{od.triangles.face_quality(vertices, flipped).numpy().max():.2f}")  # 1.22
Source code in ordito/repair.py
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
def flip_t_vertices(
    vertices: wp.array[wp.vec3],
    faces: wp.array[wp.int32],
    *,
    threshold: float = 40.0,
    max_iter: int = 10,
) -> wp.array[wp.int32]:
    """
    Repair T-vertices by flipping the long edge of each sliver they create.

    A **T-vertex** is a vertex that sits in the interior of a neighbouring triangle's edge rather
    than at one of its corners — the classic symptom of two patches stitched at different
    resolutions. The vertex is topologically fine, but the triangle opposite it is a sliver: its
    apex lies (nearly) on the far edge, which sends its circumradius-to-inradius ratio to infinity
    and makes every cotangent weight, normal and curvature estimate around it unusable.

    The repair is a flip, not a deletion: flipping the sliver's long edge moves the diagonal off the
    T and leaves two well-shaped triangles, with the same vertices and the same face count.

    Parameters
    ----------
    vertices
        ``(n_vertices,)`` mesh vertex positions. Never modified.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    threshold
        Longest edge over the height onto it above which a triangle counts as a T-vertex
        sliver; that longest edge is the one flipped. The reciprocal of the ``"area_max_side"``
        measure of [`face_quality`][ordito.triangles.face_quality] (about ``2 / sqrt(3)`` for an
        equilateral triangle, unbounded above). MeshLab's ``meshing_remove_t_vertices``
        threshold, whose default of ``40`` is this one. Must be positive.
    max_iter
        Maximum number of parallel flip passes. Each pass commits a conflict-free independent set of
        flips; MeshLab's ``repeat=True`` is the same idea serially.

    Returns
    -------
    wp.array[wp.int32]
        ``(3 * n_faces,)`` flat face buffer with the slivers re-triangulated, on ``faces.device``
        (a copy; the input is not modified).

    Raises
    ------
    RuntimeError
        If ``vertices`` and ``faces`` are not all on one device.

    See Also
    --------
    [`ordito.remesh.flip_by_objective`][ordito.remesh.flip_by_objective]
    [`remove_folded_faces`][ordito.repair.remove_folded_faces]
    [`collapse_small_triangles`][ordito.repair.collapse_small_triangles]

    Notes
    -----
    A flip cannot fix a T-vertex on the mesh **boundary** or on a non-manifold edge, because there
    is no second triangle to flip against. MeshLab offers an edge *collapse* method for that case;
    here the equivalent is [`collapse_small_triangles`][ordito.repair.collapse_small_triangles],
    which removes the sliver by merging its short edge instead.

    Examples
    --------
    Vertex 2 sits a hair above the edge ``(0, 1)`` of the triangle below it, making triangle
    ``(0, 1, 2)`` a sliver; one flip replaces the edge by ``(2, 3)``:

    ```python
    import warp as wp

    import ordito as od

    vertices = wp.array(
        [[0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [1.0, 0.01, 0.0], [1.0, -1.0, 0.0], [1.0, 1.0, 0.0]],
        dtype=wp.vec3,
    )
    faces = wp.array([0, 3, 1, 0, 1, 2, 0, 2, 4, 2, 1, 4], dtype=wp.int32)
    print(f"{od.triangles.face_quality(vertices, faces).numpy().max():.0f}")  # 5001
    flipped = od.repair.flip_t_vertices(vertices, faces)
    print(flipped.numpy().reshape(-1, 3).tolist())  # [[1, 2, 3], [0, 3, 2], [0, 2, 4], [2, 1, 4]]
    print(f"{od.triangles.face_quality(vertices, flipped).numpy().max():.2f}")  # 1.22
    ```
    """
    require_same_device(vertices=vertices, faces=faces)
    return od.remesh.flip_by_objective(
        vertices, faces, objective="t_vertex", aspect_threshold=threshold, max_iter=max_iter
    )