-
Notifications
You must be signed in to change notification settings - Fork 5
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
Feature/additional geometry file export methods #225
Merged
janbridley
merged 64 commits into
master
from
Feature/Additional-geometry-file-export-methods
Sep 13, 2024
Merged
Changes from 15 commits
Commits
Show all changes
64 commits
Select commit
Hold shift + click to select a range
9b5dc29
Import version for clearer file writing
josephburkhart 741cf5e
Add OBJ export method
josephburkhart d690f4b
Add OFF export method
josephburkhart b422c92
Add STL export method
josephburkhart e63ff8d
Add PLY export method
josephburkhart 08ce8b5
Add X3D export method
josephburkhart fe8bc7e
Add VTK export method
josephburkhart 642f867
Add HTML export method
josephburkhart 8c0ceb7
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] dc50cca
Move export methods to new file
josephburkhart 366544d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 8877438
Revise docstrings
josephburkhart 7709cc2
Merge branch 'master' into Feature/Additional-geometry-file-export-me…
janbridley d86ff7c
Fix F841
janbridley 7d4206c
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] d9aff11
Change acronym import to full name
josephburkhart 3853729
Fix star import
josephburkhart 0ab6a6f
Fix assignments of unused variables
josephburkhart 401703d
Add doctype declaration to HTML output
josephburkhart a971c24
Fix XML and HTML namespacing
josephburkhart 308b7bb
Fix linting issue
josephburkhart 4f6200e
Revise variable names for clarity
josephburkhart 4d49bb1
Add module docstring
josephburkhart 330efb0
Add convenience method to Polyhedron class
josephburkhart f0d9736
Revise docstring
josephburkhart 927b2cd
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 2113787
Change match/case to if/elif for backwards compatibility
josephburkhart 92968f4
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] d06cc4a
Revise docstring
josephburkhart fa739f5
Fix circular import
janbridley 52a21e4
Update copyright in coxeter/io.py
janbridley 85c0f52
Merge branch 'master' into Feature/Additional-geometry-file-export-me…
janbridley 7f327de
Fix D401
janbridley 85d90be
Merge branch 'master' into Feature/Additional-geometry-file-export-me…
janbridley 3e3fd1f
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] cbac8cf
Merge branch 'master' into Feature/Additional-geometry-file-export-me…
janbridley 1a19890
Fix unintended shape mutation
josephburkhart 999b09d
Limit imports to reduce loading time
josephburkhart 94ab8e9
Create io control files
josephburkhart bc35493
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 46d0859
Fix incorrect control directory
josephburkhart f4ae897
Update control files
josephburkhart 3c2078a
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 4769ec5
Update .pre-commit-config.yaml
josephburkhart 9a19e00
Update control files
josephburkhart 391834c
Delete control files
josephburkhart 3332048
Create new control files
josephburkhart bc7263c
Update .pre-commit-config.yaml
josephburkhart b5c05bb
Delete new control files
josephburkhart e9e568a
Create new control files
josephburkhart 69c0377
Update .pre-commit-config.yaml
josephburkhart 8955118
Delete new control files
josephburkhart f956ddc
Create new control files
josephburkhart 37175d3
Prevent trailing newlines
josephburkhart fe03d11
Update control files
josephburkhart b6bf215
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 763a262
Fix pre-commit regex
janbridley b2a79d1
Switch to OS-agnostic file comparison
josephburkhart 6e28a64
Check file equality by line
josephburkhart f260fd2
Merge branch 'master' into Feature/Additional-geometry-file-export-me…
josephburkhart 7f45afa
Alternate solution to circular import
josephburkhart d8b7726
Update control files
josephburkhart 43bc025
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 1c70ef1
Merge branch 'master' into Feature/Additional-geometry-file-export-me…
janbridley File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,278 @@ | ||
import os | ||
import xml.etree.ElementTree as ET | ||
|
||
import numpy as np | ||
|
||
from coxeter import __version__ | ||
|
||
|
||
def to_obj(shape, filename): | ||
"""Save shape to a wavefront OBJ file. | ||
|
||
Args: | ||
filename (str, pathlib.Path, or os.PathLike): | ||
The name or path of the output file, including the extension. | ||
|
||
Note: | ||
In OBJ files, vertices in face definitions are indexed from one. | ||
|
||
Raises | ||
------ | ||
OSError: If open() encounters a problem. | ||
""" | ||
with open(filename, "w") as file: | ||
file.write( | ||
f"# wavefront obj file written by Coxeter " | ||
f"version {__version__}\n" | ||
f"# {shape.__class__.__name__}\n\n" | ||
) | ||
|
||
for v in shape.vertices: | ||
file.write(f"v {' '.join([str(i) for i in v])}\n") | ||
|
||
file.write("\n") | ||
|
||
for f in shape.faces: | ||
file.write(f"f {' '.join([str(i+1) for i in f])}\n") | ||
|
||
|
||
def to_off(shape, filename): | ||
"""Save shape to an Object File Format (OFF) file. | ||
|
||
Args: | ||
filename (str, pathlib.Path, or os.PathLike): | ||
The name or path of the output file, including the extension. | ||
|
||
Raises | ||
------ | ||
OSError: If open() encounters a problem. | ||
""" | ||
with open(filename, "w") as file: | ||
file.write( | ||
f"OFF\n# OFF file written by Coxeter " | ||
f"version {__version__}\n" | ||
f"# {shape.__class__.__name__}\n" | ||
) | ||
|
||
file.write( | ||
f"{len(shape.vertices)} f{len(shape.faces)} " f"{len(shape.edges)}\n" | ||
) | ||
|
||
for v in shape.vertices: | ||
file.write(f"{' '.join([str(i) for i in v])}\n") | ||
|
||
for f in shape.faces: | ||
file.write(f"{len(f)} {' '.join([str(i) for i in f])}\n") | ||
|
||
|
||
def to_stl(shape, filename): | ||
"""Save shape to a stereolithography (STL) file. | ||
|
||
Args: | ||
filename (str, pathlib.Path, or os.PathLike): | ||
The name or path of the output file, including the extension. | ||
|
||
Note: | ||
The output file is ASCII-encoded. | ||
|
||
Raises | ||
------ | ||
OSError: If open() encounters a problem. | ||
""" | ||
with open(filename, "w") as file: | ||
# Shift vertices so all coordinates are positive | ||
mins = np.amin(a=shape.vertices, axis=0) | ||
for i, m in enumerate(mins): | ||
if m < 0: | ||
shape.centroid[i] -= m | ||
|
||
# Write data | ||
vs = shape.vertices | ||
file.write(f"solid {shape.__class__.__name__}\n") | ||
|
||
for f in shape.faces: | ||
# Decompose face into triangles | ||
# ref: https://stackoverflow.com/a/66586936/15426433 | ||
triangles = [[vs[f[0]], vs[b], vs[c]] for b, c in zip(f[1:], f[2:])] | ||
|
||
for t in triangles: | ||
n = np.cross(t[1] - t[0], t[2] - t[1]) # order? | ||
|
||
file.write(f"facet normal {n[0]} {n[1]} {n[2]}\n" f"\touter loop\n") | ||
for point in t: | ||
file.write(f"\t\tvertex {point[0]} {point[1]} {point[2]}\n") | ||
|
||
file.write("\tendloop\nendfacet\n") | ||
|
||
file.write(f"endsolid {shape.__class__.__name__}") | ||
|
||
|
||
def to_ply(shape, filename): | ||
"""Save shape to a Polygon File Format (PLY) file. | ||
|
||
Args: | ||
filename (str, pathlib.Path, or os.PathLike): | ||
The name or path of the output file, including the extension. | ||
|
||
Note: | ||
The output file is ASCII-encoded. | ||
|
||
Raises | ||
------ | ||
OSError: If open() encounters a problem. | ||
""" | ||
with open(filename, "w") as file: | ||
file.write( | ||
f"ply\nformat ascii 1.0\n" | ||
f"comment PLY file written by Coxeter " | ||
f"version {__version__}\n" | ||
f"comment {shape.__class__.__name__}\n" | ||
f"element vertex {len(shape.vertices)}\n" | ||
f"property float x\nproperty float y\nproperty float z\n" | ||
f"element face {len(shape.faces)}\n" | ||
f"property list uchar uint vertex_indices\n" | ||
f"end_header\n" | ||
) | ||
|
||
for v in shape.vertices: | ||
file.write(f"{' '.join([str(i) for i in v])}\n") | ||
|
||
for f in shape.faces: | ||
file.write(f"{len(f)} {' '.join([str(int(i)) for i in f])}\n") | ||
|
||
|
||
def to_x3d(shape, filename): | ||
"""Save shape to an Extensible 3D (X3D) file. | ||
|
||
Args: | ||
filename (str, pathlib.Path, or os.PathLike): | ||
The name or path of the output file, including the extension. | ||
|
||
Raises | ||
------ | ||
OSError: If open() encounters a problem. | ||
""" | ||
# TODO: translate shape so that its centroid is at the origin | ||
|
||
# Parent elements | ||
root = ET.Element( | ||
"x3d", | ||
attrib={ | ||
"profile": "Interchange", | ||
"version": "4.0", | ||
"xmlns:xsd": "http://www.w3.org/2001/XMLSchema-instance", | ||
"xsd:noNamespaceSchemaLocation": "http://www.web3d.org/specifications/x3d-4.0.xsd", | ||
}, | ||
) | ||
x3d_scene = ET.SubElement(root, "Scene") | ||
x3d_shape = ET.SubElement( | ||
x3d_scene, "shape", attrib={"DEF": f"{shape.__class__.__name__}"} | ||
) | ||
|
||
_ = ET.SubElement(x3d_shape, "Appearance") | ||
_ = ET.SubElement(x3d_appearance, "Material", attrib={"diffuseColor": "#6495ED"}) | ||
|
||
# Geometry data | ||
coordinate_indices = list(range(sum([len(f) for f in shape.faces]))) | ||
prev_index = 0 | ||
for f in shape.faces: | ||
coordinate_indices.insert(len(f) + prev_index, -1) | ||
prev_index += len(f) + 1 | ||
|
||
coordinate_points = [v for f in shape.faces for i in f for v in shape.vertices[i]] | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Consider rewriting this with numpy functions - ravel, etc. Should be possible to simplify! |
||
|
||
x3d_indexedfaceset = ET.SubElement( | ||
x3d_shape, | ||
"IndexedFaceSet", | ||
attrib={"coordIndex": " ".join([str(i) for i in coordinate_indices])}, | ||
) | ||
x3d_coordinate = ET.SubElement( | ||
x3d_indexedfaceset, | ||
"Coordinate", | ||
attrib={"point": " ".join([str(i) for i in coordinate_points])}, | ||
) | ||
|
||
# Write to file | ||
ET.ElementTree(root).write(filename, encoding="UTF-8") | ||
|
||
|
||
def to_vtk(shape, filename): | ||
"""Save shape to a legacy VTK file. | ||
|
||
Args: | ||
filename (str, pathlib.Path, or os.PathLike): | ||
The name or path of the output file, including the extension. | ||
|
||
Raises | ||
------ | ||
OSError: If open() encounters a problem. | ||
""" | ||
content = "" | ||
# Title and Header | ||
content += ( | ||
f"# vtk DataFile Version 3.0\n" | ||
f"{shape.__class__.__name__} created by " | ||
f"Coxeter version {__version__}\n" | ||
f"ASCII\n" | ||
) | ||
|
||
# Geometry | ||
content += f"DATASET POLYDATA\n" f"POINTS {len(shape.vertices)} float\n" | ||
for v in shape.vertices: | ||
content += f"{v[0]} {v[1]} {v[2]}\n" | ||
|
||
num_points = len(shape.faces) | ||
num_connections = sum([len(f) for f in shape.faces]) | ||
content += f"POLYGONS {num_points} {num_points + num_connections}\n" | ||
for f in shape.faces: | ||
content += f"{len(f)} {' '.join([str(i) for i in f])}\n" | ||
|
||
# Write file | ||
with open(filename, "wb") as file: | ||
file.write(content.encode("ascii")) | ||
|
||
|
||
def to_html(shape, filename): | ||
"""Save shape to an HTML file. | ||
|
||
This method calls shape.to_x3d to create a temporary X3D file, then | ||
parses that X3D file and creates an HTML file in its place. | ||
|
||
Args: | ||
filename (str, pathlib.Path, or os.PathLike): | ||
The name or path of the output file, including the extension. | ||
|
||
Raises | ||
------ | ||
OSError: If open() encounters a problem. | ||
""" | ||
# Create, parse, and remove x3d file | ||
to_x3d(shape, filename) | ||
x3d = ET.parse(filename) | ||
os.remove(filename) | ||
|
||
# HTML Head | ||
html = ET.Element("html") | ||
head = ET.SubElement(html, "head") | ||
script = ET.SubElement( | ||
head, | ||
"script", | ||
attrib={"type": "text/javascript", "src": "http://x3dom.org/release/x3dom.js"}, | ||
) | ||
script.text = " " # ensures the tag is not shape-closing | ||
link = ET.SubElement( | ||
head, | ||
"link", | ||
attrib={ | ||
"rel": "stylesheet", | ||
"type": "text/css", | ||
"href": "http://x3dom.org/release/x3dom.css", | ||
}, | ||
) | ||
|
||
# HTML body | ||
body = ET.SubElement(html, "body") | ||
body.append(x3d.getroot()) | ||
|
||
# Write file | ||
ET.ElementTree(html).write(filename, encoding="UTF-8") |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a nice little snippet