183 lines
5.6 KiB
Python
183 lines
5.6 KiB
Python
"""Minimal Python binding for the VDE C API.
|
|
|
|
This is a ctypes bootstrap, not the final pybind11 extension.
|
|
It intentionally covers only version/kernel/mesh I/O so the ABI can be
|
|
exercised without a compiler or wheel build.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import ctypes
|
|
import os
|
|
import pathlib
|
|
import shutil
|
|
from typing import Optional, Tuple
|
|
|
|
__all__ = ["VdeError", "Kernel", "Mesh", "version", "library_path"]
|
|
|
|
|
|
class VdeError(RuntimeError):
|
|
"""Raised when the VDE C API returns an error."""
|
|
|
|
|
|
def _candidate_libraries():
|
|
env = os.environ.get("VDE_CAPI_LIBRARY")
|
|
if env:
|
|
yield pathlib.Path(env)
|
|
root = pathlib.Path(__file__).resolve().parents[2]
|
|
for name in ("libvde_capi.dll", "vde_capi.dll", "libvde_capi.so", "libvde_capi.dylib"):
|
|
yield root / "build" / "src" / name
|
|
yield root / "build" / "src" / "Release" / name
|
|
yield pathlib.Path("libvde_capi.dll")
|
|
|
|
|
|
_dll_search_dirs = []
|
|
|
|
|
|
def _load_library() -> ctypes.CDLL:
|
|
errors = []
|
|
if os.name == "nt":
|
|
candidates = []
|
|
gxx = shutil.which("g++")
|
|
if gxx:
|
|
candidates.append(pathlib.Path(gxx).resolve().parent)
|
|
env_bin = os.environ.get("VDE_MINGW_BIN")
|
|
if env_bin:
|
|
candidates.append(pathlib.Path(env_bin))
|
|
for directory in candidates:
|
|
if directory.is_dir():
|
|
_dll_search_dirs.append(os.add_dll_directory(str(directory)))
|
|
for candidate in _candidate_libraries():
|
|
try:
|
|
if candidate.exists() or candidate.parent == pathlib.Path("."):
|
|
return ctypes.CDLL(str(candidate))
|
|
except OSError as exc:
|
|
errors.append(f"{candidate}: {exc}")
|
|
raise VdeError("cannot load VDE C API library; set VDE_CAPI_LIBRARY. " + "; ".join(errors))
|
|
|
|
|
|
_lib = _load_library()
|
|
|
|
_lib.vde_version.restype = ctypes.c_char_p
|
|
_lib.vde_version.argtypes = []
|
|
_lib.vde_create.restype = ctypes.c_void_p
|
|
_lib.vde_create.argtypes = []
|
|
_lib.vde_destroy.restype = None
|
|
_lib.vde_destroy.argtypes = [ctypes.c_void_p]
|
|
_lib.vde_last_error.restype = ctypes.c_char_p
|
|
_lib.vde_last_error.argtypes = [ctypes.c_void_p]
|
|
_lib.vde_load_mesh.restype = ctypes.c_void_p
|
|
_lib.vde_load_mesh.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
|
|
_lib.vde_save_mesh.restype = ctypes.c_int
|
|
_lib.vde_save_mesh.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_char_p, ctypes.c_char_p]
|
|
_lib.vde_mesh_free.restype = None
|
|
_lib.vde_mesh_free.argtypes = [ctypes.c_void_p]
|
|
_lib.vde_mesh_num_vertices.restype = ctypes.c_size_t
|
|
_lib.vde_mesh_num_vertices.argtypes = [ctypes.c_void_p]
|
|
_lib.vde_mesh_num_faces.restype = ctypes.c_size_t
|
|
_lib.vde_mesh_num_faces.argtypes = [ctypes.c_void_p]
|
|
_lib.vde_mesh_get_bounds.restype = None
|
|
_lib.vde_mesh_get_bounds.argtypes = [ctypes.c_void_p] + [ctypes.POINTER(ctypes.c_double)] * 6
|
|
|
|
|
|
def library_path() -> str:
|
|
"""Return the loaded C API library path."""
|
|
return getattr(_lib, "_name", "")
|
|
|
|
|
|
def version() -> str:
|
|
"""Return the engine version string."""
|
|
value = _lib.vde_version()
|
|
return value.decode("utf-8", "replace") if value else ""
|
|
|
|
|
|
|
|
class Kernel:
|
|
"""Owns one VDE engine context."""
|
|
|
|
def __init__(self) -> None:
|
|
self._handle = _lib.vde_create()
|
|
if not self._handle:
|
|
raise VdeError("vde_create failed")
|
|
self._meshes = []
|
|
|
|
@property
|
|
def handle(self):
|
|
return self._handle
|
|
|
|
def last_error(self) -> str:
|
|
value = _lib.vde_last_error(self._handle)
|
|
return value.decode("utf-8", "replace") if value else ""
|
|
|
|
def load_mesh(self, path: str) -> "Mesh":
|
|
mesh = _lib.vde_load_mesh(self._handle, os.fsencode(path))
|
|
if not mesh:
|
|
raise VdeError(self.last_error() or f"cannot load mesh: {path}")
|
|
result = Mesh(self, mesh)
|
|
self._meshes.append(result)
|
|
return result
|
|
|
|
def close(self) -> None:
|
|
if self._handle:
|
|
for mesh in list(self._meshes):
|
|
mesh.close()
|
|
self._meshes.clear()
|
|
_lib.vde_destroy(self._handle)
|
|
self._handle = None
|
|
|
|
def __enter__(self) -> "Kernel":
|
|
return self
|
|
|
|
def __exit__(self, exc_type, exc, tb) -> None:
|
|
self.close()
|
|
|
|
def __del__(self):
|
|
try:
|
|
self.close()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
|
|
class Mesh:
|
|
"""A mesh handle owned by a Kernel."""
|
|
|
|
def __init__(self, kernel: Kernel, handle) -> None:
|
|
self._kernel = kernel
|
|
self._handle = handle
|
|
|
|
@property
|
|
def num_vertices(self) -> int:
|
|
return int(_lib.vde_mesh_num_vertices(self._handle))
|
|
|
|
@property
|
|
def num_faces(self) -> int:
|
|
return int(_lib.vde_mesh_num_faces(self._handle))
|
|
|
|
def bounds(self) -> Tuple[Tuple[float, float, float], Tuple[float, float, float]]:
|
|
values = [ctypes.c_double(0.0) for _ in range(6)]
|
|
pointer = (ctypes.POINTER(ctypes.c_double) * 6)(*[ctypes.pointer(v) for v in values])
|
|
_lib.vde_mesh_get_bounds(self._handle, *pointer)
|
|
return (tuple(v.value for v in values[:3]), tuple(v.value for v in values[3:]))
|
|
|
|
def save(self, path: str, fmt: str = "obj") -> None:
|
|
if not _lib.vde_save_mesh(self._kernel.handle, self._handle,
|
|
os.fsencode(path), os.fsencode(fmt)):
|
|
raise VdeError(self._kernel.last_error() or f"cannot save mesh: {path}")
|
|
|
|
def close(self) -> None:
|
|
if self._handle:
|
|
_lib.vde_mesh_free(self._handle)
|
|
self._handle = None
|
|
|
|
def __enter__(self) -> "Mesh":
|
|
return self
|
|
|
|
def __exit__(self, exc_type, exc, tb) -> None:
|
|
self.close()
|
|
|
|
def __del__(self):
|
|
try:
|
|
self.close()
|
|
except Exception:
|
|
pass
|