Skip to content

meshproc

Drop-in for trimesh.grouping.merge_vertices.

Same signature, same semantics, same result - see this module's docstring for what is different underneath. Operates in place via mesh.update_vertices, so visuals, normals and vertex attributes are carried along exactly as they are by trimesh's version.

PARAMETER DESCRIPTION
mesh

TYPE: trimesh.Trimesh

merge_tex
            If True, merge vertices regardless of UV coordinates.

TYPE: bool DEFAULT: None

merge_norm
            If True, merge vertices regardless of vertex normals.

TYPE: bool DEFAULT: None

digits_vertex
            Decimal digits to consider for vertex positions.
            Defaults to trimesh's `tol.merge`.

TYPE: int DEFAULT: None

digits_norm
            Decimal digits to consider for unit normals.

TYPE: int DEFAULT: None

digits_uv
            Decimal digits to consider for UV coordinates.

TYPE: int DEFAULT: None

Source code in navis/utils/meshproc.py
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def merge_vertices(
    mesh,
    merge_tex=None,
    merge_norm=None,
    digits_vertex=None,
    digits_norm=None,
    digits_uv=None,
):
    """Drop-in for `trimesh.grouping.merge_vertices`.

    Same signature, same semantics, same result - see this module's docstring
    for what is different underneath. Operates in place via
    `mesh.update_vertices`, so visuals, normals and vertex attributes are
    carried along exactly as they are by trimesh's version.

    Parameters
    ----------
    mesh :              trimesh.Trimesh
    merge_tex :         bool, optional
                        If True, merge vertices regardless of UV coordinates.
    merge_norm :        bool, optional
                        If True, merge vertices regardless of vertex normals.
    digits_vertex :     int, optional
                        Decimal digits to consider for vertex positions.
                        Defaults to trimesh's `tol.merge`.
    digits_norm :       int, optional
                        Decimal digits to consider for unit normals.
    digits_uv :         int, optional
                        Decimal digits to consider for UV coordinates.

    """
    if len(mesh.vertices) == 0:
        return

    merge_tex = False if merge_tex is None else merge_tex
    merge_norm = False if merge_norm is None else merge_norm
    digits_norm = 2 if digits_norm is None else digits_norm
    digits_uv = 4 if digits_uv is None else digits_uv
    if digits_vertex is None:
        digits_vertex = util.decimal_to_digits(tol.merge)

    # Unreferenced vertices are dropped rather than grouped - they cost work and
    # no face names them.
    if hasattr(mesh, "faces") and len(mesh.faces) > 0:
        referenced = np.zeros(len(mesh.vertices), dtype=bool)
        referenced[mesh.faces] = True
    else:
        referenced = np.ones(len(mesh.vertices), dtype=bool)

    stacked = [mesh.vertices * (10**digits_vertex)]

    # A textured mesh has to keep vertices that differ only in UV apart, and
    # likewise for vertex normals - so those ride along as extra columns.
    if (
        not merge_tex
        and mesh.visual.defined
        and mesh.visual.kind == "texture"
        and mesh.visual.uv is not None
        and len(mesh.visual.uv) == len(mesh.vertices)
    ):
        stacked.append(mesh.visual.uv * (10**digits_uv))

    normals = mesh._cache["vertex_normals"]
    if not merge_norm and np.shape(normals) == mesh.vertices.shape:
        stacked.append(normals * (10**digits_norm))

    # Usually just the coordinates, and `column_stack` would copy them for
    # nothing.
    stacked = stacked[0] if len(stacked) == 1 else np.column_stack(stacked)
    stacked = stacked.round().astype(np.int64)

    keep, groups = unique_rows(stacked if referenced.all() else stacked[referenced])

    inverse = np.zeros(len(mesh.vertices), dtype=np.int64)
    inverse[referenced] = groups
    mask = np.flatnonzero(referenced)[keep]
    mesh.update_vertices(mask=mask, inverse=inverse)

Trimesh's process=True, on bare arrays.

Drops non-finite vertices, then merges duplicates - the two passes trimesh.Trimesh(..., process=True, validate=False) runs, with the same result but without building a mesh object to throw away afterwards. Where there is an object to build, install :func:merge_vertices on it as navis.Volume and navis.utils.TrimeshPlus do - the merge then follows the object rather than happening once on the way in.

Note that validate=True adds a face-level clean-up which this does not do; callers that want it should go through trimesh (see navis.Mesh).

PARAMETER DESCRIPTION
vertices

TYPE: (N, 3) array

faces

TYPE: (M, 3) array | None

RETURNS DESCRIPTION
vertices

TYPE: (K, 3) float64 array

faces

TYPE: (M, 3) int64 array

Source code in navis/utils/meshproc.py
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
def process(vertices, faces):
    """Trimesh's `process=True`, on bare arrays.

    Drops non-finite vertices, then merges duplicates - the two passes
    `trimesh.Trimesh(..., process=True, validate=False)` runs, with the same
    result but without building a mesh object to throw away afterwards. Where
    there *is* an object to build, install :func:`merge_vertices` on it as
    `navis.Volume` and `navis.utils.TrimeshPlus` do - the merge then follows the
    object rather than happening once on the way in.

    Note that `validate=True` adds a face-level clean-up which this does not
    do; callers that want it should go through trimesh (see `navis.Mesh`).

    Parameters
    ----------
    vertices :  (N, 3) array
    faces :     (M, 3) array | None

    Returns
    -------
    vertices :  (K, 3) float64 array
    faces :     (M, 3) int64 array

    """
    # Same coercion trimesh's own setters do, so that what comes out of here
    # does not depend on what went in.
    vertices = np.asarray(vertices, order="C", dtype=np.float64)
    if faces is None:
        faces = np.zeros((0, 3), dtype=np.int64)
    else:
        faces = np.asarray(faces, order="C", dtype=np.int64)

    n = len(vertices)
    if not n:
        return vertices, faces

    # --- non-finite vertices. The scalar check first: it is an order of
    # magnitude cheaper than the per-row one and answers "no" for every mesh
    # that is not broken.
    if not np.isfinite(vertices).all():
        finite = np.isfinite(vertices).all(axis=1)
        # A face naming a dropped vertex is either dropped too (trimesh >= 5)
        # or left pointing at vertex 0, which is what trimesh's
        # `update_vertices` does with an unmapped index.
        if _DROPS_NONFINITE_FACES and len(faces):
            faces = faces[finite[faces].all(axis=1)]
        inverse = np.zeros(n, dtype=np.int64)
        inverse[finite] = np.arange(finite.sum())
        vertices = vertices[finite]
        faces = inverse[faces]
        n = len(vertices)
        if not n:
            return vertices, faces

    # --- duplicate vertices
    referenced = np.ones(n, dtype=bool)
    if len(faces):
        referenced = np.zeros(n, dtype=bool)
        referenced[faces] = True

    # Skipping the copy where every vertex is referenced is worth a branch; the
    # rest of the bookkeeping below is already a no-op in that case.
    subset = vertices if referenced.all() else vertices[referenced]
    quantized = np.round(subset * 10 ** util.decimal_to_digits(tol.merge))
    keep, groups = unique_rows(quantized.astype(np.int64))

    # `keep` indexes the referenced subset, so this can only hold if every
    # vertex is referenced and none of them merged.
    if len(keep) == n:
        return vertices, faces

    inverse = np.zeros(n, dtype=np.int64)
    inverse[referenced] = groups
    return vertices[np.flatnonzero(referenced)[keep]], inverse[faces]

Group identical rows, numbered in order of first occurrence.

Equivalent to trimesh.grouping.unique_rows(rows, keep_order=True), but without the sort: rows are folded into one integer each and grouped by hash.

PARAMETER DESCRIPTION
rows
    Integers. Floats would make the packing lossy and are rejected
    by the callers here, which quantize before calling.

TYPE: (N, M) array

RETURNS DESCRIPTION
index

rows[index] are the distinct rows, in the order they first appear.

TYPE: (K, ) int array

inverse

Group of each row, such that rows[index][inverse] == rows.

TYPE: (N, ) int array

Source code in navis/utils/meshproc.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def unique_rows(rows):
    """Group identical rows, numbered in order of first occurrence.

    Equivalent to `trimesh.grouping.unique_rows(rows, keep_order=True)`, but
    without the sort: rows are folded into one integer each and grouped by hash.

    Parameters
    ----------
    rows :      (N, M) array
                Integers. Floats would make the packing lossy and are rejected
                by the callers here, which quantize before calling.

    Returns
    -------
    index :     (K, ) int array
                `rows[index]` are the distinct rows, in the order they first
                appear.
    inverse :   (N, ) int array
                Group of each row, such that `rows[index][inverse] == rows`.

    """
    rows = np.asarray(rows)
    n = len(rows)
    if not n:
        return np.zeros(0, dtype=np.intp), np.zeros(0, dtype=np.intp)

    # `sort=False` numbers the groups in order of first appearance, which is the
    # order asked for here - so no renumbering is needed, and `index` below comes
    # out ascending on its own.
    group, uniq = pd.factorize(_row_key(rows), sort=False)
    group = group.astype(np.intp, copy=False)

    # Lowest row index per group. Scattering back to front means the last write
    # wins, and the last write is the earliest row.
    index = np.empty(len(uniq), dtype=np.intp)
    index[group[::-1]] = np.arange(n - 1, -1, -1)
    return index, group