Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add vertex attributes in path #2356

Merged
merged 5 commits into from
Feb 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions tests/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

import os
import sys
import io
import json
import copy
import time
Expand Down Expand Up @@ -567,6 +568,47 @@ def roundtrip(exported, file_type, **kwargs):
)


def to_glb_bytes(geom: trimesh.Geometry) -> bytes:
"""
Returns the content of the binary glTF file for the given geometry.

Parameters
----------
geom : trimesh.Geometry
Geometry to export

Returns
-------
data : bytes
Content of the binary glTF file
"""
data = trimesh.exchange.gltf.export_glb(geom)

return data


def from_glb_bytes(data: bytes) -> trimesh.Scene:
"""
Returns the scene from the given binary glTF file content.

Parameters
----------
data : bytes
Content of the binary glTF file

Returns
-------
scene : trimesh.Scene
Scene
"""
bytes_stream = io.BytesIO(data)
kwargs = trimesh.exchange.gltf.load_glb(bytes_stream)

scene = trimesh.exchange.load._load_kwargs(kwargs)

return scene


# all the JSON files with truth data
data = _load_data()

Expand Down
26 changes: 26 additions & 0 deletions tests/test_paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,32 @@ def test_discrete():
d.process()


def test_path():
path = g.trimesh.path.Path3D(
entities=[
g.trimesh.path.entities.Line(
points=[0, 1, 2]
)
],
vertices=[[0, 0, 0], [1, 0, 0], [1, 1, 0]],
vertex_attributes={
"_test": g.np.array([1, 2, 3], dtype=g.np.float32)
}
)

glb_data = g.to_glb_bytes(path)
loaded_scene = g.from_glb_bytes(glb_data)

loaded_path = loaded_scene.geometry["geometry_0"]
loaded_path.process()

assert isinstance(loaded_path, g.trimesh.path.Path3D)

assert loaded_path.vertices.shape == (3, 3)
assert len(loaded_path.entities) == 1
assert len(loaded_path.vertex_attributes["_test"]) == 3


def test_poly():
p = g.get_mesh("2D/LM2.dxf")
assert p.is_closed
Expand Down
32 changes: 32 additions & 0 deletions trimesh/exchange/gltf.py
Original file line number Diff line number Diff line change
Expand Up @@ -1165,6 +1165,31 @@ def _append_path(path, name, tree, buffer_items):
# add color to attributes
current["primitives"][0]["attributes"]["COLOR_0"] = acc_color

# for each attribute with a leading underscore, assign them to path
# vertex_attributes
for key, attrib in path.vertex_attributes.items():
# Application specific attributes must be
# prefixed with an underscore
if not key.startswith("_"):
key = "_" + key

# GLTF has no floating point type larger than 32 bits so clip
# any float64 or larger to float32
if attrib.dtype.kind == "f" and attrib.dtype.itemsize > 4:
data = attrib.astype(np.float32)
else:
data = attrib

data = util.stack_lines(data).reshape((-1,))

# store custom vertex attributes
current["primitives"][0]["attributes"][key] = _data_append(
acc=tree["accessors"],
buff=buffer_items,
blob=_build_accessor(data),
data=data,
)

tree["meshes"].append(current)


Expand Down Expand Up @@ -1525,6 +1550,13 @@ def _read_buffers(

kwargs["vertices"] = access[attr["POSITION"]]
kwargs["entities"] = [Line(points=np.arange(len(kwargs["vertices"])))]

# custom attributes starting with a `_`
custom = {
a: access[attr[a]] for a in attr.keys() if a.startswith("_")
}
if len(custom) > 0:
kwargs["vertex_attributes"] = custom
elif mode == _GL_POINTS:
kwargs["vertices"] = access[attr["POSITION"]]
visuals = None
Expand Down
8 changes: 8 additions & 0 deletions trimesh/path/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ def __init__(
metadata: Optional[Dict] = None,
process: bool = True,
colors=None,
vertex_attributes: Optional[Dict] = None,
**kwargs,
):
"""
Expand Down Expand Up @@ -105,6 +106,10 @@ def __init__(
if isinstance(metadata, dict):
self.metadata.update(metadata)

self.vertex_attributes = {}
if vertex_attributes is not None:
self.vertex_attributes.update(vertex_attributes)

# cache will dump whenever self.crc changes
self._cache = caching.Cache(id_function=self.__hash__)

Expand Down Expand Up @@ -523,6 +528,9 @@ def merge_vertices(self, digits=None):

unique, inverse = grouping.unique_rows(self.vertices, digits=digits)
self.vertices = self.vertices[unique]
self.vertex_attributes = {
key: np.array(value)[unique] for key, value in self.vertex_attributes.items()
}

entities_ok = np.ones(len(self.entities), dtype=bool)

Expand Down