Skip to content

ordito.texture

Bake per-vertex attributes into UV-space textures and sample them back.

The functions here operate on an existing UV map (from a disk parameterization or a mesh file, e.g. loaded via load_mesh): they rasterize per-vertex attributes into a square texture and sample a texture back to per-vertex values, and rasterize which face covers each pixel of any window of UV space. They are a Warp software-rasterizer replacement for an OpenGL/moderngl pipeline, keeping all data on the input Warp device.

Computing a UV map from mesh connectivity (parameterization) is a separate concern and is not part of this module.

See rasterize_attribute, rasterize_discrete_attribute, rasterize_face_indices, remap_attribute_from_uv, and remap_discrete_attribute_from_uv.

Functions:

Name Description
rasterize_attribute

Rasterize a per-vertex attribute into a square UV-space texture.

rasterize_discrete_attribute

Rasterize a per-vertex discrete label into a square UV-space class image.

rasterize_face_indices

Index of the face covering every pixel of a window of UV space: a visibility buffer.

remap_attribute_from_uv

Sample a UV-space texture back to per-vertex values.

remap_discrete_attribute_from_uv

Sample a UV-space class image back to per-vertex labels.

rasterize_attribute

rasterize_attribute(
    uv: array[vec2],
    faces: array[int32],
    attribute: ArrayNdFloat32,
    resolution: int,
    *,
    subpixel_bits: int | None = None,
) -> odt.Array3dFloat32

Rasterize a per-vertex attribute into a square UV-space texture.

Each triangle is rasterized in UV space and its per-vertex attribute is barycentrically interpolated at every covered pixel center. Pixels not covered by any triangle stay 0. Where triangles overlap (degenerate for a valid parameterization), the lowest-index face wins.

Parameters:

Name Type Description Default
uv array[vec2]

(n_vertices,) per-vertex UV coordinates in [0, 1]. Non-finite rows (e.g. unreferenced vertices left NaN by a disk parameterization) are ignored; by construction no face indexes them.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
attribute ArrayNdFloat32

(n_vertices, n_channels) per-vertex attribute to interpolate.

required
resolution int

Output image size in pixels (square).

required
subpixel_bits int | None

When given, every vertex is first snapped to the nearest 1 / 2 ** subpixel_bits of a pixel, as a GPU rasterizer snaps it before testing coverage and interpolating; 8 reproduces OpenGL on current NVIDIA drivers. None (the default) rasterizes the UVs as given.

None

Returns:

Type Description
Array3dFloat32

(resolution, resolution, n_channels) image on uv.device. Row 0 corresponds to v = 1 (vertical flip), matching the sampling convention of remap_attribute_from_uv.

Raises:

Type Description
TypeError

If attribute is not a rank-2 wp.float32 array.

ValueError

If resolution is not positive, if uv and attribute disagree on their row count, if any finite UV lies outside [0, 1], or if subpixel_bits is negative.

RuntimeError

If uv, faces and attribute are not all on one device.

See Also

remap_attribute_from_uv rasterize_discrete_attribute

Examples:

Bake the u coordinate of a unit-square grid into an 8 x 8 texture; the top-right pixel centre sits at u = 7.5 / 8:

import warp as wp

import ordito as od

vertices, faces = od.creation.grid(count=(5, 5), center=False)
uv = wp.array(vertices.numpy()[:, :2], dtype=wp.vec2)
attribute = wp.array(vertices.numpy()[:, :1], dtype=wp.float32)
image = od.texture.rasterize_attribute(uv, faces, attribute, 8)
print(image.shape)  # (8, 8, 1)
print(f"{image.numpy()[0, 7, 0]:.4f}")  # 0.9375
Source code in ordito/texture.py
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def rasterize_attribute(
    uv: wp.array[wp.vec2],
    faces: wp.array[wp.int32],
    attribute: odt.ArrayNdFloat32,
    resolution: int,
    *,
    subpixel_bits: int | None = None,
) -> odt.Array3dFloat32:
    """
    Rasterize a per-vertex attribute into a square UV-space texture.

    Each triangle is rasterized in UV space and its per-vertex attribute is barycentrically
    interpolated at every covered pixel center. Pixels not covered by any triangle stay ``0``.
    Where triangles overlap (degenerate for a valid parameterization), the lowest-index face wins.

    Parameters
    ----------
    uv
        ``(n_vertices,)`` per-vertex UV coordinates in ``[0, 1]``. Non-finite rows (e.g.
        unreferenced vertices left ``NaN`` by a disk parameterization) are ignored; by
        construction no face indexes them.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    attribute
        ``(n_vertices, n_channels)`` per-vertex attribute to interpolate.
    resolution
        Output image size in pixels (square).
    subpixel_bits
        When given, every vertex is first snapped to the nearest ``1 / 2 ** subpixel_bits`` of a
        pixel, as a GPU rasterizer snaps it before testing coverage and interpolating; ``8``
        reproduces OpenGL on current NVIDIA drivers. ``None`` (the default) rasterizes the UVs as
        given.

    Returns
    -------
    Array3dFloat32
        ``(resolution, resolution, n_channels)`` image on ``uv.device``. Row ``0`` corresponds to
        ``v = 1`` (vertical flip), matching the sampling convention of
        [`remap_attribute_from_uv`][ordito.texture.remap_attribute_from_uv].

    Raises
    ------
    TypeError
        If ``attribute`` is not a rank-2 ``wp.float32`` array.
    ValueError
        If ``resolution`` is not positive, if ``uv`` and ``attribute`` disagree on their row
        count, if any finite UV lies outside ``[0, 1]``, or if ``subpixel_bits`` is negative.
    RuntimeError
        If ``uv``, ``faces`` and ``attribute`` are not all on one device.

    See Also
    --------
    [`remap_attribute_from_uv`][ordito.texture.remap_attribute_from_uv]
    [`rasterize_discrete_attribute`][ordito.texture.rasterize_discrete_attribute]

    Examples
    --------
    Bake the ``u`` coordinate of a unit-square grid into an 8 x 8 texture; the top-right
    pixel centre sits at ``u = 7.5 / 8``:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.grid(count=(5, 5), center=False)
    uv = wp.array(vertices.numpy()[:, :2], dtype=wp.vec2)
    attribute = wp.array(vertices.numpy()[:, :1], dtype=wp.float32)
    image = od.texture.rasterize_attribute(uv, faces, attribute, 8)
    print(image.shape)  # (8, 8, 1)
    print(f"{image.numpy()[0, 7, 0]:.4f}")  # 0.9375
    ```
    """
    require_same_device(uv=uv, faces=faces, attribute=attribute)
    odt.ensure_ndim(attribute, 2, dtype=wp.float32)
    n_channels = int(attribute.shape[1])
    _check_rasterize_inputs(uv, int(attribute.shape[0]), resolution)
    uv = _snapped_uv(uv, resolution, subpixel_bits)

    device = uv.device
    owner = _rasterize_owner(uv, faces, resolution, _launch.empty(0, dtype=wp.int32, device=device))
    # Every pixel is written by the resolve pass, covered or not.
    image = _launch.empty((resolution, resolution, n_channels), dtype=wp.float32, device=device)
    _launch.launch(
        kernel_texture.rasterize_pixels,
        dim=(resolution, resolution),
        inputs=[uv, faces, attribute, n_channels, owner, image],
        device=device,
    )
    return odt.as_array3d(image, wp.float32)

rasterize_discrete_attribute

rasterize_discrete_attribute(
    uv: array[vec2],
    faces: array[int32],
    attribute: array[int32],
    resolution: int,
    *,
    subpixel_bits: int | None = None,
) -> odt.Array2dInt32

Rasterize a per-vertex discrete label into a square UV-space class image.

At each covered pixel the label with the greatest barycentric weight is emitted (weights of vertices sharing a label sum; ties resolve to the lowest label value). This is equivalent to one-hot encoding the labels, interpolating, and taking the per-pixel argmax. Pixels not covered by any triangle are set to -1.

Parameters:

Name Type Description Default
uv array[vec2]

(n_vertices,) per-vertex UV coordinates in [0, 1]. Non-finite rows are ignored.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
attribute array[int32]

(n_vertices,) per-vertex labels, all >= 0.

required
resolution int

Output image size in pixels (square).

required
subpixel_bits int | None

As in rasterize_attribute: snap every vertex to the nearest 1 / 2 ** subpixel_bits of a pixel first.

None

Returns:

Type Description
Array2dInt32

(resolution, resolution) class image with values in [-1, n_classes - 1] (-1 marks uncovered pixels), on uv.device.

Raises:

Type Description
ValueError

If any entry of attribute is negative, if resolution is not positive, if uv and attribute disagree on their row count, if any finite UV lies outside [0, 1], or if subpixel_bits is negative.

RuntimeError

If uv, faces and attribute are not all on one device.

See Also

remap_discrete_attribute_from_uv rasterize_attribute

Examples:

Label the grid vertices right of x = 0.5 1 and the rest 0; a pixel takes the label with the greater interpolated weight:

import warp as wp

import ordito as od

vertices, faces = od.creation.grid(count=(5, 5), center=False)
uv = wp.array(vertices.numpy()[:, :2], dtype=wp.vec2)
labels = wp.array((vertices.numpy()[:, 0] > 0.5).astype("int32"), dtype=wp.int32)
class_image = od.texture.rasterize_discrete_attribute(uv, faces, labels, 8)
print(class_image.shape)  # (8, 8)
print(class_image.numpy()[0].tolist())  # [0, 0, 0, 0, 0, 1, 1, 1]
Source code in ordito/texture.py
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
def rasterize_discrete_attribute(
    uv: wp.array[wp.vec2],
    faces: wp.array[wp.int32],
    attribute: wp.array[wp.int32],
    resolution: int,
    *,
    subpixel_bits: int | None = None,
) -> odt.Array2dInt32:
    """
    Rasterize a per-vertex discrete label into a square UV-space class image.

    At each covered pixel the label with the greatest barycentric weight is emitted (weights of
    vertices sharing a label sum; ties resolve to the lowest label value). This is equivalent to
    one-hot encoding the labels, interpolating, and taking the per-pixel ``argmax``. Pixels not
    covered by any triangle are set to ``-1``.

    Parameters
    ----------
    uv
        ``(n_vertices,)`` per-vertex UV coordinates in ``[0, 1]``. Non-finite rows are
        ignored.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    attribute
        ``(n_vertices,)`` per-vertex labels, all ``>= 0``.
    resolution
        Output image size in pixels (square).
    subpixel_bits
        As in [`rasterize_attribute`][ordito.texture.rasterize_attribute]: snap every vertex to the
        nearest ``1 / 2 ** subpixel_bits`` of a pixel first.

    Returns
    -------
    Array2dInt32
        ``(resolution, resolution)`` class image with values in ``[-1, n_classes - 1]`` (``-1``
        marks uncovered pixels), on ``uv.device``.

    Raises
    ------
    ValueError
        If any entry of ``attribute`` is negative, if ``resolution`` is not positive, if ``uv``
        and ``attribute`` disagree on their row count, if any finite UV lies outside ``[0, 1]``,
        or if ``subpixel_bits`` is negative.
    RuntimeError
        If ``uv``, ``faces`` and ``attribute`` are not all on one device.

    See Also
    --------
    [`remap_discrete_attribute_from_uv`][ordito.texture.remap_discrete_attribute_from_uv]
    [`rasterize_attribute`][ordito.texture.rasterize_attribute]

    Examples
    --------
    Label the grid vertices right of ``x = 0.5`` ``1`` and the rest ``0``; a pixel takes the label
    with the greater interpolated weight:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.grid(count=(5, 5), center=False)
    uv = wp.array(vertices.numpy()[:, :2], dtype=wp.vec2)
    labels = wp.array((vertices.numpy()[:, 0] > 0.5).astype("int32"), dtype=wp.int32)
    class_image = od.texture.rasterize_discrete_attribute(uv, faces, labels, 8)
    print(class_image.shape)  # (8, 8)
    print(class_image.numpy()[0].tolist())  # [0, 0, 0, 0, 0, 1, 1, 1]
    ```
    """
    require_same_device(uv=uv, faces=faces, attribute=attribute)
    odt.ensure_ndim(attribute, 1, dtype=wp.int32)
    n_vertices = attribute.size
    _check_rasterize_inputs(uv, n_vertices, resolution)
    uv = _snapped_uv(uv, resolution, subpixel_bits)

    device = uv.device
    owner = _rasterize_owner(uv, faces, resolution, attribute)
    # Every pixel is written by the resolve pass, covered or not.
    labels_image = _launch.empty((resolution, resolution), dtype=wp.int32, device=device)
    _launch.launch(
        kernel_texture.rasterize_label_pixels,
        dim=(resolution, resolution),
        inputs=[uv, faces, attribute, owner, labels_image],
        device=device,
    )
    return odt.as_array2d(labels_image, wp.int32)

rasterize_face_indices

rasterize_face_indices(
    uv: array[vec2],
    faces: array[int32],
    origin: Sequence[float],
    pixel_size: float,
    shape: tuple[int, int],
    *,
    face_priority: array[float32] | None = None,
) -> odt.Array2dInt32

Index of the face covering every pixel of a window of UV space: a visibility buffer.

The window spans origin to origin + (columns, rows) * pixel_size, with row 0 at its top (vertical flip), as in rasterize_attribute: pixel (i, j) is the UV point origin + (j + 0.5, rows - i - 0.5) * pixel_size. A face covers a pixel when its UV triangle holds the pixel's centre, edges included, so faces sharing an edge leave no gap between them. Where several faces cover a pixel, the one of lowest face_priority wins, and between equal priorities (or with none given) the one of lowest index.

Parameters:

Name Type Description Default
uv array[vec2]

(n_vertices,) per-vertex UV coordinates, in any units: not limited to [0, 1]. A face with a non-finite corner covers nothing.

required
faces array[int32]

(3 * n_faces,) flat triangle index buffer.

required
origin Sequence[float]

UV of the window's lower-left corner, (u, v).

required
pixel_size float

Side of a pixel in UV units.

required
shape tuple[int, int]

(rows, columns) of the window.

required
face_priority array[float32] | None

(n_faces,) priority of every face, the lowest winning where faces overlap; -0.0 ties with 0.0 and NaN loses to every number. None lets the face index decide.

None

Returns:

Type Description
Array2dInt32

(rows, columns) index of the face covering every pixel, -1 where none does, row 0 at the window's top, on uv.device.

Raises:

Type Description
TypeError

If face_priority is not a rank-1 wp.float32 array.

ValueError

If shape holds no pixel, pixel_size is not positive and finite, origin is not two finite numbers, or face_priority does not hold one value a face.

RuntimeError

If uv, faces and face_priority are not all on one device.

See Also

rasterize_attribute

Examples:

A window of 4 x 4 pixels over the right half of a unit-square grid and beyond: its two right-hand columns lie past u = 1, where no face is.

import warp as wp

import ordito as od

vertices, faces = od.creation.grid(count=(3, 3), center=False)
uv = wp.array(vertices.numpy()[:, :2], dtype=wp.vec2)
face_image = od.texture.rasterize_face_indices(uv, faces, (0.5, 0.0), 0.25, (4, 4))
print(face_image.shape)  # (4, 4)
print(int((face_image.numpy() < 0).sum()))  # 8
Source code in ordito/texture.py
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
def rasterize_face_indices(
    uv: wp.array[wp.vec2],
    faces: wp.array[wp.int32],
    origin: Sequence[float],
    pixel_size: float,
    shape: tuple[int, int],
    *,
    face_priority: wp.array[wp.float32] | None = None,
) -> odt.Array2dInt32:
    """
    Index of the face covering every pixel of a window of UV space: a visibility buffer.

    The window spans ``origin`` to ``origin + (columns, rows) * pixel_size``, with row ``0`` at its
    top (vertical flip), as in [`rasterize_attribute`][ordito.texture.rasterize_attribute]: pixel
    ``(i, j)`` is the UV point ``origin + (j + 0.5, rows - i - 0.5) * pixel_size``. A
    face covers a pixel when its UV triangle holds the pixel's centre, edges included, so faces
    sharing an edge leave no gap between them. Where several faces cover a pixel, the one of
    lowest ``face_priority`` wins, and between equal priorities (or with none given) the one of
    lowest index.

    Parameters
    ----------
    uv
        ``(n_vertices,)`` per-vertex UV coordinates, in any units: not limited to ``[0, 1]``. A
        face with a non-finite corner covers nothing.
    faces
        ``(3 * n_faces,)`` flat triangle index buffer.
    origin
        UV of the window's lower-left corner, ``(u, v)``.
    pixel_size
        Side of a pixel in UV units.
    shape
        ``(rows, columns)`` of the window.
    face_priority
        ``(n_faces,)`` priority of every face, the lowest winning where faces overlap; ``-0.0``
        ties with ``0.0`` and ``NaN`` loses to every number. ``None`` lets the face index decide.

    Returns
    -------
    Array2dInt32
        ``(rows, columns)`` index of the face covering every pixel, ``-1`` where none does, row
        ``0`` at the window's top, on ``uv.device``.

    Raises
    ------
    TypeError
        If ``face_priority`` is not a rank-1 ``wp.float32`` array.
    ValueError
        If ``shape`` holds no pixel, ``pixel_size`` is not positive and finite, ``origin`` is not
        two finite numbers, or ``face_priority`` does not hold one value a face.
    RuntimeError
        If ``uv``, ``faces`` and ``face_priority`` are not all on one device.

    See Also
    --------
    [`rasterize_attribute`][ordito.texture.rasterize_attribute]

    Examples
    --------
    A window of 4 x 4 pixels over the right half of a unit-square grid and beyond: its two
    right-hand columns lie past ``u = 1``, where no face is.

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.grid(count=(3, 3), center=False)
    uv = wp.array(vertices.numpy()[:, :2], dtype=wp.vec2)
    face_image = od.texture.rasterize_face_indices(uv, faces, (0.5, 0.0), 0.25, (4, 4))
    print(face_image.shape)  # (4, 4)
    print(int((face_image.numpy() < 0).sum()))  # 8
    ```
    """
    require_same_device(uv=uv, faces=faces, face_priority=face_priority)
    rows, columns = (int(count) for count in shape)
    if rows <= 0 or columns <= 0:
        raise ValueError(f"shape must hold pixels, got {tuple(shape)}")
    if not (math.isfinite(pixel_size) and pixel_size > 0.0):
        raise ValueError(f"pixel_size must be positive and finite, got {pixel_size}")
    origin_u, origin_v = (float(coordinate) for coordinate in origin)
    if not (math.isfinite(origin_u) and math.isfinite(origin_v)):
        raise ValueError(f"origin must be finite, got {tuple(origin)}")
    device = uv.device
    n_faces = faces.size // 3
    if face_priority is None:
        priority = _launch.empty(0, dtype=wp.float32, device=device)
    else:
        odt.ensure_ndim(face_priority, 1, dtype=wp.float32)
        if face_priority.size != n_faces:
            raise ValueError(
                f"face_priority must hold one value a face: {face_priority.size} for {n_faces}"
            )
        priority = face_priority
    if n_faces == 0:
        return odt.as_array2d(
            _launch.full((rows, columns), -1, dtype=wp.int32, device=device), wp.int32
        )

    n_pixels = rows * columns
    keys = _launch.full(n_pixels, kernel_texture.NO_FACE_KEY, dtype=wp.uint64, device=device)
    keys_2d = keys.reshape((rows, columns))
    # Every vertex in the window's pixel frame, formed in float64 once rather than by every thread
    # of a face's split.
    pixels = _launch.empty(uv.size, dtype=wp.vec2, device=device)
    _launch.map(
        kernel_texture.window_pixel,
        uv,
        wp.vec2d(origin_u, origin_v),
        wp.float64(1.0 / pixel_size),
        wp.float64(rows),
        out=pixels,
    )
    slices = _owner_slices(n_faces, math.sqrt(n_pixels), device)
    if slices == 1:
        _launch.launch(
            kernel_texture.rasterize_face_keys,
            dim=n_faces,
            inputs=[pixels, faces, priority, keys_2d],
            device=device,
        )
    else:
        _launch.launch(
            kernel_texture.rasterize_face_keys_sliced,
            dim=n_faces * slices,
            inputs=[pixels, faces, priority, slices, keys_2d],
            device=device,
        )
    # Every pixel is written by the map, covered or not.
    face_image = _launch.empty(n_pixels, dtype=wp.int32, device=device)
    _launch.map(kernel_texture.face_of_key, keys, out=face_image)
    return odt.as_array2d(face_image.reshape((rows, columns)), wp.int32)

remap_attribute_from_uv

remap_attribute_from_uv(
    uv: array[vec2],
    image: Array2dFloat32 | Array3dFloat32,
    *,
    order: Literal[0, 1] = 1,
) -> odt.Array2dFloat32

Sample a UV-space texture back to per-vertex values.

Inverse of rasterize_attribute. Sampling uses the same pixel-center convention as rasterize_attribute (col = u * W - 0.5, row = (1 - v) * H - 0.5) and clamps to the nearest edge pixel, so vertices on the coverage boundary read the boundary value instead of blending toward 0. Vertices whose UV is non-finite are not sampled; their output row is NaN on every channel.

Parameters:

Name Type Description Default
uv array[vec2]

(n_vertices,) per-vertex UV coordinates in [0, 1]. Non-finite rows yield NaN output rows.

required
image Array2dFloat32 | Array3dFloat32

(H, W) or (H, W, C) float32 UV-space texture to sample.

required
order Literal[0, 1]

Interpolation order: 1 for bilinear (default), 0 for nearest-neighbor.

1

Returns:

Type Description
Array2dFloat32

(n_vertices, C) per-vertex values on uv.device (C == 1 for a 2D input image). Non-finite-UV rows are NaN.

Raises:

Type Description
TypeError

If image is neither rank 2 nor rank 3.

ValueError

If order is not 0 or 1, or if any finite UV lies outside [0, 1].

RuntimeError

If uv and image are not all on one device.

See Also

rasterize_attribute

Examples:

A texture baked from a per-vertex value samples back to nearly the same value:

import warp as wp

import ordito as od

vertices, faces = od.creation.grid(count=(5, 5), center=False)
uv = wp.array(vertices.numpy()[:, :2], dtype=wp.vec2)
attribute = wp.array(vertices.numpy()[:, :1], dtype=wp.float32)
image = od.texture.rasterize_attribute(uv, faces, attribute, 64)
values = od.texture.remap_attribute_from_uv(uv, image)
print(values.shape)  # (25, 1)
print(abs(values.numpy() - attribute.numpy()).max() < 0.01)  # True
Source code in ordito/texture.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
def remap_attribute_from_uv(
    uv: wp.array[wp.vec2],
    image: odt.Array2dFloat32 | odt.Array3dFloat32,
    *,
    order: Literal[0, 1] = 1,
) -> odt.Array2dFloat32:
    """
    Sample a UV-space texture back to per-vertex values.

    Inverse of [`rasterize_attribute`][ordito.texture.rasterize_attribute].
    Sampling uses the same pixel-center convention as
    [`rasterize_attribute`][ordito.texture.rasterize_attribute] (``col = u * W - 0.5``,
    ``row = (1 - v) * H - 0.5``) and clamps to the nearest edge pixel, so vertices on the
    coverage boundary read the boundary value instead of blending toward ``0``. Vertices whose
    UV is non-finite are not sampled; their output row is ``NaN`` on every channel.

    Parameters
    ----------
    uv
        ``(n_vertices,)`` per-vertex UV coordinates in ``[0, 1]``. Non-finite rows yield
        ``NaN`` output rows.
    image
        ``(H, W)`` or ``(H, W, C)`` ``float32`` UV-space texture to sample.
    order
        Interpolation order: ``1`` for bilinear (default), ``0`` for nearest-neighbor.

    Returns
    -------
    Array2dFloat32
        ``(n_vertices, C)`` per-vertex values on ``uv.device`` (``C == 1`` for a 2D input
        image). Non-finite-UV rows are ``NaN``.

    Raises
    ------
    TypeError
        If ``image`` is neither rank 2 nor rank 3.
    ValueError
        If ``order`` is not ``0`` or ``1``, or if any finite UV lies outside ``[0, 1]``.
    RuntimeError
        If ``uv`` and ``image`` are not all on one device.

    See Also
    --------
    [`rasterize_attribute`][ordito.texture.rasterize_attribute]

    Examples
    --------
    A texture baked from a per-vertex value samples back to nearly the same value:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.grid(count=(5, 5), center=False)
    uv = wp.array(vertices.numpy()[:, :2], dtype=wp.vec2)
    attribute = wp.array(vertices.numpy()[:, :1], dtype=wp.float32)
    image = od.texture.rasterize_attribute(uv, faces, attribute, 64)
    values = od.texture.remap_attribute_from_uv(uv, image)
    print(values.shape)  # (25, 1)
    print(abs(values.numpy() - attribute.numpy()).max() < 0.01)  # True
    ```
    """
    require_same_device(uv=uv, image=image)
    if order not in (0, 1):
        raise ValueError(f"order must be 0 (nearest) or 1 (bilinear), got {order!r}")
    if int(image.ndim) == 2:
        height, width = int(image.shape[0]), int(image.shape[1])
        n_channels = 1
        image3d = image.reshape((height, width, 1))
    elif int(image.ndim) == 3:
        n_channels = int(image.shape[2])
        image3d = image
    else:
        raise TypeError(f"image must be (H, W) or (H, W, C), got ndim={image.ndim}")
    odt.ensure_ndim(image3d, 3, dtype=wp.float32)

    device = uv.device
    n_vertices = uv.size
    out_values = odt.empty_2d((n_vertices, n_channels), wp.float32, device=device)
    if n_vertices > 0:
        # ``order`` is rejected above rather than defaulted here: an ``if order == 1 else``
        # sampled nearest-neighbour for every off-menu value, so a caller whose interpolation
        # order arrived through a variable got a plausible image and no error.
        mode = kernel_texture.SAMPLE_BILINEAR if order == 1 else kernel_texture.SAMPLE_NEAREST
        flag = _launch.zeros(1, dtype=wp.int32, device=device)
        _launch.launch(
            kernel_texture.sample_texture,
            dim=n_vertices,
            inputs=[uv, image3d, n_channels, mode, out_values, flag],
            device=device,
        )
        _raise_on_uv_flag(flag)
    return odt.as_array2d(out_values, wp.float32)

remap_discrete_attribute_from_uv

remap_discrete_attribute_from_uv(
    uv: array[vec2], class_image: Array2dInt32
) -> odt.Array1dInt32

Sample a UV-space class image back to per-vertex labels.

Inverse of rasterize_discrete_attribute. Nearest-neighbor sampling is used so labels are never blended, including the -1 uncovered sentinel. Vertices whose UV is non-finite cannot be sampled and map to the same -1 sentinel.

Parameters:

Name Type Description Default
uv array[vec2]

(n_vertices,) per-vertex UV coordinates in [0, 1]. Non-finite rows yield -1.

required
class_image Array2dInt32

(H, W) class image (values e.g. in [-1, n_classes - 1]).

required

Returns:

Type Description
Array1dInt32

(n_vertices,) per-vertex labels on uv.device. Non-finite-UV rows are -1.

Raises:

Type Description
ValueError

If any finite UV lies outside [0, 1].

RuntimeError

If uv and class_image are not all on one device.

See Also

rasterize_discrete_attribute remap_attribute_from_uv

Examples:

A class image baked from per-vertex labels samples back to the same labels:

import warp as wp

import ordito as od

vertices, faces = od.creation.grid(count=(5, 5), center=False)
uv = wp.array(vertices.numpy()[:, :2], dtype=wp.vec2)
labels = wp.array((vertices.numpy()[:, 0] > 0.5).astype("int32"), dtype=wp.int32)
class_image = od.texture.rasterize_discrete_attribute(uv, faces, labels, 64)
remapped = od.texture.remap_discrete_attribute_from_uv(uv, class_image)
print((remapped.numpy() == labels.numpy()).all())  # True
Source code in ordito/texture.py
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
def remap_discrete_attribute_from_uv(
    uv: wp.array[wp.vec2], class_image: odt.Array2dInt32
) -> odt.Array1dInt32:
    """
    Sample a UV-space class image back to per-vertex labels.

    Inverse of [`rasterize_discrete_attribute`][ordito.texture.rasterize_discrete_attribute].
    Nearest-neighbor sampling is used so labels are never blended, including the ``-1`` uncovered
    sentinel. Vertices whose UV is non-finite cannot be sampled and map to the same ``-1``
    sentinel.

    Parameters
    ----------
    uv
        ``(n_vertices,)`` per-vertex UV coordinates in ``[0, 1]``. Non-finite rows yield
        ``-1``.
    class_image
        ``(H, W)`` class image (values e.g. in ``[-1, n_classes - 1]``).

    Returns
    -------
    Array1dInt32
        ``(n_vertices,)`` per-vertex labels on ``uv.device``. Non-finite-UV rows
        are ``-1``.

    Raises
    ------
    ValueError
        If any finite UV lies outside ``[0, 1]``.
    RuntimeError
        If ``uv`` and ``class_image`` are not all on one device.

    See Also
    --------
    [`rasterize_discrete_attribute`][ordito.texture.rasterize_discrete_attribute]
    [`remap_attribute_from_uv`][ordito.texture.remap_attribute_from_uv]

    Examples
    --------
    A class image baked from per-vertex labels samples back to the same labels:

    ```python
    import warp as wp

    import ordito as od

    vertices, faces = od.creation.grid(count=(5, 5), center=False)
    uv = wp.array(vertices.numpy()[:, :2], dtype=wp.vec2)
    labels = wp.array((vertices.numpy()[:, 0] > 0.5).astype("int32"), dtype=wp.int32)
    class_image = od.texture.rasterize_discrete_attribute(uv, faces, labels, 64)
    remapped = od.texture.remap_discrete_attribute_from_uv(uv, class_image)
    print((remapped.numpy() == labels.numpy()).all())  # True
    ```
    """
    require_same_device(uv=uv, class_image=class_image)
    odt.ensure_ndim(class_image, 2, dtype=wp.int32)

    device = uv.device
    n_vertices = uv.size
    if n_vertices == 0:
        return odt.empty_1d(0, wp.int32, device=device)
    # The labels and, behind them, the range flag: one allocation, the flag's slot zeroed.
    labels_and_flag = _launch.empty(n_vertices + 1, dtype=wp.int32, device=device)
    out_labels = _launch.view(labels_and_flag, 0, n_vertices)
    flag = _launch.view(labels_and_flag, n_vertices, n_vertices + 1)
    _launch.zero_(flag)
    _launch.launch(
        kernel_texture.sample_class_image,
        dim=n_vertices,
        inputs=[uv, class_image, out_labels, flag],
        device=device,
    )
    _raise_on_uv_flag(flag)
    return out_labels