177 lines
6.5 KiB
Python
177 lines
6.5 KiB
Python
#!/usr/bin/env python3
|
|
"""Extract flat ACIS 3DSOLID faces and DXF MESH entities to Y-up OBJ/GLB."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import json
|
|
import sys
|
|
from collections import Counter
|
|
from pathlib import Path
|
|
|
|
|
|
CURVED_RECORDS = (
|
|
"cone-surface",
|
|
"sphere-surface",
|
|
"spline-surface",
|
|
"torus-surface",
|
|
"cylinder-surface",
|
|
"swept-surface",
|
|
"revolution-surface",
|
|
)
|
|
|
|
|
|
def import_dependencies(vendor_dir: Path):
|
|
if vendor_dir.exists():
|
|
sys.path.insert(0, str(vendor_dir.resolve()))
|
|
try:
|
|
import ezdxf
|
|
import numpy as np
|
|
import trimesh
|
|
from ezdxf.acis import api as acis
|
|
except ImportError as exc:
|
|
raise SystemExit("Install requirements-core.txt (ezdxf, numpy, trimesh) before extracting solids") from exc
|
|
return ezdxf, np, trimesh, acis
|
|
|
|
|
|
def triangles_from_face_vertices(faces) -> list[list[tuple[float, float, float]]]:
|
|
triangles = []
|
|
for face in faces:
|
|
points = [(float(point.x), float(point.y), float(point.z)) for point in face]
|
|
if len(points) == 3:
|
|
triangles.append(points)
|
|
elif len(points) > 3:
|
|
for index in range(1, len(points) - 1):
|
|
triangles.append([points[0], points[index], points[index + 1]])
|
|
return triangles
|
|
|
|
|
|
def mesh_entity_triangles(entity) -> list[list[tuple[float, float, float]]]:
|
|
vertices = [
|
|
(
|
|
float(point.x if hasattr(point, "x") else point[0]),
|
|
float(point.y if hasattr(point, "y") else point[1]),
|
|
float(point.z if hasattr(point, "z") else point[2]),
|
|
)
|
|
for point in entity.vertices
|
|
]
|
|
triangles = []
|
|
for face in entity.faces:
|
|
indices = [int(index) for index in face]
|
|
if len(indices) < 3:
|
|
continue
|
|
for index in range(1, len(indices) - 1):
|
|
triangles.append([vertices[indices[0]], vertices[indices[index]], vertices[indices[index + 1]]])
|
|
return triangles
|
|
|
|
|
|
def trimesh_from_triangles(triangles, np, trimesh):
|
|
if not triangles:
|
|
return None
|
|
vertices = np.asarray(triangles, dtype=np.float64).reshape(-1, 3)
|
|
faces = np.arange(len(vertices), dtype=np.int64).reshape(-1, 3)
|
|
finite = np.isfinite(vertices).all(axis=1)
|
|
if not finite.all():
|
|
good_faces = finite.reshape(-1, 3).all(axis=1)
|
|
faces = faces[good_faces]
|
|
if len(faces) == 0:
|
|
return None
|
|
mesh = trimesh.Trimesh(vertices=vertices, faces=faces, process=False)
|
|
tri = mesh.vertices[mesh.faces]
|
|
areas = np.linalg.norm(np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]), axis=1) * 0.5
|
|
mesh.update_faces(np.isfinite(areas) & (areas > 1e-9))
|
|
mesh.remove_unreferenced_vertices()
|
|
if len(mesh.faces) == 0:
|
|
return None
|
|
# DXF/OBJ is Z-up; glTF is Y-up.
|
|
mesh.apply_transform(np.array([[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1.0]]))
|
|
return mesh
|
|
|
|
|
|
def acis_text(entity) -> str:
|
|
sat = getattr(entity, "sat", None)
|
|
if sat:
|
|
return "\n".join(str(item) for item in sat)
|
|
sab = getattr(entity, "sab", None)
|
|
return bytes(sab or b"").decode("latin1", errors="ignore")
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("--dxf", required=True, help="ODA-converted R2000+ DXF containing 3DSOLID/MESH")
|
|
parser.add_argument("--out-glb", required=True)
|
|
parser.add_argument("--out-obj")
|
|
parser.add_argument("--report", required=True)
|
|
parser.add_argument("--vendor-dir", default="work/vendor")
|
|
args = parser.parse_args()
|
|
ezdxf, np, trimesh, acis = import_dependencies(Path(args.vendor_dir))
|
|
doc = ezdxf.readfile(args.dxf)
|
|
scene = trimesh.Scene()
|
|
report = {
|
|
"report_version": 1,
|
|
"source": str(Path(args.dxf)),
|
|
"entities": Counter(),
|
|
"acis_bodies": 0,
|
|
"captured_meshes": 0,
|
|
"captured_triangles": 0,
|
|
"curved_records": Counter(),
|
|
"failures": [],
|
|
}
|
|
index = 0
|
|
for entity in doc.modelspace():
|
|
kind = entity.dxftype()
|
|
if kind not in {"3DSOLID", "BODY", "REGION", "MESH"}:
|
|
continue
|
|
report["entities"][kind] += 1
|
|
if kind == "MESH":
|
|
candidates = [mesh_entity_triangles(entity)]
|
|
else:
|
|
text = acis_text(entity).lower()
|
|
for record in CURVED_RECORDS:
|
|
report["curved_records"][record] += text.count(record)
|
|
candidates = []
|
|
try:
|
|
bodies = acis.load_dxf(entity)
|
|
report["acis_bodies"] += len(bodies)
|
|
for body in bodies:
|
|
for mesh in acis.mesh_from_body(body, merge_lumps=False):
|
|
candidates.append(triangles_from_face_vertices(mesh.tessellation(max_vertex_count=3)))
|
|
except Exception as exc:
|
|
report["failures"].append({"handle": entity.dxf.handle, "type": kind, "error": str(exc)})
|
|
for triangles in candidates:
|
|
mesh = trimesh_from_triangles(triangles, np, trimesh)
|
|
if mesh is None:
|
|
continue
|
|
index += 1
|
|
scene.add_geometry(mesh, node_name=f"SOLID_{index:03d}__mesh", geom_name=f"SOLID_{index:03d}__mesh")
|
|
report["captured_meshes"] += 1
|
|
report["captured_triangles"] += int(len(mesh.faces))
|
|
report["entities"] = dict(report["entities"])
|
|
report["curved_records"] = {key: value for key, value in report["curved_records"].items() if value}
|
|
curved_total = sum(report["curved_records"].values())
|
|
report["status"] = "PASS" if report["captured_meshes"] else "FAIL"
|
|
report["limitations"] = (
|
|
f"{curved_total} curved ACIS surface record(s) require a full CAD kernel and were not tessellated."
|
|
if curved_total
|
|
else "Only flat polygonal ACIS faces and DXF MESH entities are supported."
|
|
)
|
|
report_path = Path(args.report)
|
|
report_path.parent.mkdir(parents=True, exist_ok=True)
|
|
report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
if not report["captured_meshes"]:
|
|
print("GATE FAIL [solid_mesh_captured]: no flat ACIS/MESH geometry could be extracted", file=sys.stderr)
|
|
return 3
|
|
glb = Path(args.out_glb)
|
|
glb.parent.mkdir(parents=True, exist_ok=True)
|
|
scene.export(glb)
|
|
if args.out_obj:
|
|
obj = Path(args.out_obj)
|
|
obj.parent.mkdir(parents=True, exist_ok=True)
|
|
scene.export(obj)
|
|
print(json.dumps({"glb": str(glb), "meshes": index, "report": str(report_path)}, ensure_ascii=False))
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|