feat: the geometry engine is C++ on OpenCASCADE, one package, prebuilt wheels

The modeling API (shapes, operators, sketches, products, queries, the reactive graph) is implemented in
C++20 on OpenCASCADE (src/cpp) and ships inside the wheel as simplecadapi._cpp.  The Python layers that stay
Python (runtime, build, artifacts, editor, inspect, exporter, translators, scene) run on it unchanged; the
previous Python test suite passes on the new engine.

Layout: src/cpp and src/simplecadapi side by side, one distribution built by scikit-build-core.
simplecadapi.core, .operators.*, .ql, .std.* and the other legacy modules are real forwarding modules; the
Python adapter layer is simplecadapi/_glue.  OCP is no longer a dependency and nothing imports it.

Release: .github/workflows/release.yml builds wheels for Linux x86_64 and aarch64, macOS arm64 and Windows
x86_64 (Python 3.10-3.13) against one static OCCT, runs the test suite on the Linux wheels and publishes to
GitHub and PyPI; ci.yml caches the static OCCT for the test jobs.

Errors: every message the library writes is English; the tag-validation and semantic-query errors render in
full with possible causes and fixes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
NiJingzhe
2026-10-24 02:55:35 +08:00
parent 29cbcc3958
commit 8971279494
1268 changed files with 140294 additions and 42143 deletions
+21
View File
@@ -0,0 +1,21 @@
find_package(Python 3.10 COMPONENTS Interpreter Development.Module REQUIRED)
find_package(pybind11 CONFIG REQUIRED)
file(GLOB _bind_sources CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/*.cpp" "${CMAKE_CURRENT_SOURCE_DIR}/occt/*.cpp")
pybind11_add_module(_native MODULE ${_bind_sources})
scad_apply_compile_options(_native)
target_link_libraries(_native PRIVATE scad::scad)
# Static OCCT + hidden visibility: the module exports PyInit__native and nothing else,
# so it cannot clash with a second OCCT in the same process (cadquery-ocp, say).
set_target_properties(_native PROPERTIES CXX_VISIBILITY_PRESET hidden)
# The extension is the module ``simplecadapi._cpp._native``: it lives in the Python package, next to its Python files
# (src/simplecadapi/_cpp/). A wheel build installs it there; a development build writes it there directly, so a
# checkout (``src`` on the path, or an editable install) imports it without any further step. One file per Python
# version (``_native.cpython-312-darwin.so``): several builds can share the directory.
get_filename_component(_package_dir "${PROJECT_SOURCE_DIR}/../simplecadapi/_cpp" ABSOLUTE)
if(SKBUILD)
install(TARGETS _native LIBRARY DESTINATION simplecadapi/_cpp)
else()
set_target_properties(_native PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${_package_dir}")
endif()
+188
View File
@@ -0,0 +1,188 @@
// Canonical JSON (RFC 8785) and artifact content hashes straight from Python containers.
//
// The Python SDK hashes every geometry-interface record, feature graph and definition through
// `canonical_bytes` (validate recursively, then rfc8785 recursively): ~25% of an arm6 build.
// These functions walk dict/list/tuple/str/int/float/bool/None objects once, in C++.
//
// Contract: a function returns the exact bytes (text) the Python implementation produces, or None
// when the value is outside the fast domain (non-dict mappings, subclasses of containers, integers
// beyond the safe range, non-finite floats, lone surrogates, non-string keys, deep nesting, cycles).
// The caller then runs the Python implementation, which raises the error it always raised -- so the
// error types and messages are the Python ones by construction, never re-implemented here.
#include <Python.h>
#include <algorithm>
#include <charconv>
#include <cmath>
#include <cstdint>
#include <string>
#include <string_view>
#include <vector>
#include "bindings.hpp"
#include "scad/io/hash.hpp"
#include "scad/io/json.hpp"
namespace {
constexpr long long kSafeInt = 9007199254740991LL;
constexpr int kMaxDepth = 48; // deeper (or cyclic) values take the Python path, which reports them
class Walker {
public:
explicit Walker(bool safe_ints) : safe_ints_(safe_ints) { out_.reserve(256); }
std::string& out() { return out_; }
// False: outside the fast domain (out_ is then meaningless).
bool walk(PyObject* o, int depth, const std::vector<std::string_view>* omit = nullptr) {
if (o == Py_None) { out_ += "null"; return true; }
if (PyBool_Check(o)) { out_ += o == Py_True ? "true" : "false"; return true; }
if (PyLong_Check(o)) return integer(o);
if (PyUnicode_Check(o)) {
std::string_view text;
if (!utf8(o, text)) return false;
scad::io::canonical_append_string(text, out_);
return true;
}
if (PyFloat_Check(o)) {
const double d = PyFloat_AS_DOUBLE(o);
if (!std::isfinite(d)) return false;
scad::io::canonical_append_number(d, out_);
return true;
}
if (depth >= kMaxDepth) return false;
if (PyList_CheckExact(o)) {
const Py_ssize_t n = PyList_GET_SIZE(o);
out_.push_back('[');
for (Py_ssize_t i = 0; i < n; ++i) {
if (i) out_.push_back(',');
if (!walk(PyList_GET_ITEM(o, i), depth + 1)) return false;
}
out_.push_back(']');
return true;
}
if (PyTuple_CheckExact(o)) {
const Py_ssize_t n = PyTuple_GET_SIZE(o);
out_.push_back('[');
for (Py_ssize_t i = 0; i < n; ++i) {
if (i) out_.push_back(',');
if (!walk(PyTuple_GET_ITEM(o, i), depth + 1)) return false;
}
out_.push_back(']');
return true;
}
if (PyDict_CheckExact(o)) return dict(o, depth, omit);
return false;
}
private:
struct Member {
std::string_view key;
PyObject* value;
};
static bool utf8(PyObject* o, std::string_view& text) {
Py_ssize_t size = 0;
const char* data = PyUnicode_AsUTF8AndSize(o, &size);
if (data == nullptr) { // lone surrogate
PyErr_Clear();
return false;
}
text = std::string_view(data, static_cast<std::size_t>(size));
return true;
}
bool integer(PyObject* o) {
int overflow = 0;
const long long v = PyLong_AsLongLongAndOverflow(o, &overflow);
if (overflow == 0 && v == -1 && PyErr_Occurred()) { PyErr_Clear(); return false; }
if (overflow == 0 && v <= kSafeInt && v >= -kSafeInt) {
char buffer[24];
const auto r = std::to_chars(buffer, buffer + sizeof buffer, v);
out_.append(buffer, r.ptr);
return true;
}
if (!safe_ints_) return false;
// _json_safe: an integer outside the JSON safe range is hashed as the string "int:<decimal>".
PyObject* text = PyObject_Str(o);
if (text == nullptr) { PyErr_Clear(); return false; }
std::string_view digits;
const bool ok = utf8(text, digits);
if (ok) scad::io::canonical_append_string(std::string("int:").append(digits), out_);
Py_DECREF(text);
return ok;
}
bool dict(PyObject* o, int depth, const std::vector<std::string_view>* omit) {
std::vector<Member> members;
members.reserve(static_cast<std::size_t>(PyDict_GET_SIZE(o)));
Py_ssize_t pos = 0;
PyObject *key = nullptr, *value = nullptr;
while (PyDict_Next(o, &pos, &key, &value)) {
if (!PyUnicode_Check(key)) return false;
std::string_view name;
if (!utf8(key, name)) return false;
if (omit != nullptr && std::find(omit->begin(), omit->end(), name) != omit->end()) continue;
members.push_back({name, value});
}
std::sort(members.begin(), members.end(),
[](const Member& a, const Member& b) { return scad::io::canonical_key_less(a.key, b.key); });
out_.push_back('{');
bool first = true;
for (const Member& member : members) {
if (!first) out_.push_back(',');
first = false;
scad::io::canonical_append_string(member.key, out_);
out_.push_back(':');
if (!walk(member.value, depth + 1)) return false;
}
out_.push_back('}');
return true;
}
std::string out_;
bool safe_ints_;
};
// The keys content_hash drops from the top level. Values stay owned by the tuple the caller passed.
bool read_omit(const py::handle& omit, std::vector<std::string_view>& out) {
if (omit.is_none()) return true;
if (!PyTuple_Check(omit.ptr()) && !PyList_Check(omit.ptr())) return false;
for (py::handle item : py::reinterpret_borrow<py::sequence>(omit)) {
if (!PyUnicode_Check(item.ptr())) return false;
Py_ssize_t size = 0;
const char* data = PyUnicode_AsUTF8AndSize(item.ptr(), &size);
if (data == nullptr) { PyErr_Clear(); return false; }
out.emplace_back(data, static_cast<std::size_t>(size));
}
return true;
}
py::object canonical_bytes(const py::handle& value, bool safe_ints) {
Walker walker(safe_ints);
if (!walker.walk(value.ptr(), 0)) return py::none();
return py::reinterpret_steal<py::object>(PyBytes_FromStringAndSize(walker.out().data(),
static_cast<Py_ssize_t>(walker.out().size())));
}
py::object canonical_hash(const py::handle& value, const py::handle& omit, bool safe_ints) {
std::vector<std::string_view> omitted;
if (!read_omit(omit, omitted)) return py::none();
if (!omitted.empty() && !PyDict_CheckExact(value.ptr())) return py::none();
Walker walker(safe_ints);
if (!walker.walk(value.ptr(), 0, omitted.empty() ? nullptr : &omitted)) return py::none();
return py::str(scad::io::sha256_tagged(walker.out()));
}
} // namespace
void bind_canonical(py::module_& m) {
m.def("canonical_bytes", &canonical_bytes, py::arg("value"), py::arg("safe_ints") = false,
"RFC 8785 bytes of a JSON-like Python value (what artifacts.canonical.canonical_bytes returns), or None "
"when the value needs the Python implementation (it raises the error). safe_ints: integers outside "
"+-(2**53-1) become the string 'int:<n>' (geometry_interface._json_safe).");
m.def("canonical_hash", &canonical_hash, py::arg("value"), py::arg("omit") = py::none(), py::arg("safe_ints") = false,
"'sha256:<hex>' of the canonical bytes of `value` without the top-level keys in `omit` (artifacts.canonical."
"content_hash), or None when the value needs the Python implementation.");
}
+102
View File
@@ -0,0 +1,102 @@
#include "bindings.hpp"
#include "scad/core/coordinate_system.hpp"
#include <cmath>
#include <cstdio>
#include "scad/core/error.hpp"
namespace {
py::array_t<double> as_array(const scad::Vec3& v) {
py::array_t<double> a(3);
auto r = a.mutable_unchecked<1>();
r(0) = v.x;
r(1) = v.y;
r(2) = v.z;
return a;
}
scad::Vec3 vec_from_python(const py::object& o) {
return o.cast<scad::Vec3>();
}
} // namespace
void bind_core(py::module_& m) {
using scad::pybind::PyVec3;
py::class_<PyVec3>(m, "Vec3")
.def(py::init([](double x, double y, double z) { return PyVec3{{x, y, z}}; }))
.def_property_readonly("x", [](const PyVec3& p) { return p.v.x; })
.def_property_readonly("y", [](const PyVec3& p) { return p.v.y; })
.def_property_readonly("z", [](const PyVec3& p) { return p.v.z; })
.def("to_tuple", [](const PyVec3& p) { return py::make_tuple(p.v.x, p.v.y, p.v.z); })
.def("__iter__", [](const PyVec3& p) { return py::iter(py::make_tuple(p.v.x, p.v.y, p.v.z)); })
.def("dot", [](const PyVec3& p, const scad::Vec3& o) { return p.v.dot(o); })
.def("norm", [](const PyVec3& p) { return p.v.norm(); })
.def("normalized", [](const PyVec3& p) {
if (p.v.norm() <= 1e-15) throw scad::ValueError("Cannot normalize a zero-length vector");
return PyVec3{p.v.normalized()};
})
.def("getAngle", [](const PyVec3& p, const scad::Vec3& o) {
const double sn = p.v.norm(), on = o.norm();
if (sn <= 1e-15 || on <= 1e-15) throw scad::ValueError("Cannot compute angle with a zero-length vector");
return std::acos(std::max(-1.0, std::min(1.0, p.v.dot(o) / (sn * on))));
})
.def("__mul__", [](const PyVec3& p, double s) { return PyVec3{p.v * s}; })
.def("__rmul__", [](const PyVec3& p, double s) { return PyVec3{p.v * s}; })
.def("__repr__", [](const PyVec3& p) {
char buf[160];
std::snprintf(buf, sizeof buf, "Vec3(%.6g, %.6g, %.6g)", p.v.x, p.v.y, p.v.z);
return std::string(buf);
});
using scad::CoordinateSystem;
using scad::Workplane;
py::class_<CoordinateSystem>(m, "CoordinateSystem")
.def(py::init([](const py::object& origin, const py::object& x_axis, const py::object& y_axis) {
return CoordinateSystem(vec_from_python(origin), vec_from_python(x_axis), vec_from_python(y_axis));
}),
py::arg("origin") = py::make_tuple(0, 0, 0), py::arg("x_axis") = py::make_tuple(1, 0, 0),
py::arg("y_axis") = py::make_tuple(0, 1, 0))
.def_property_readonly("origin", [](const CoordinateSystem& c) { return as_array(c.origin()); })
.def_property_readonly("x_axis", [](const CoordinateSystem& c) { return as_array(c.x_axis()); })
.def_property_readonly("y_axis", [](const CoordinateSystem& c) { return as_array(c.y_axis()); })
.def_property_readonly("z_axis", [](const CoordinateSystem& c) { return as_array(c.z_axis()); })
.def("transform_point", [](const CoordinateSystem& c, const py::object& p) { return as_array(c.transform_point(vec_from_python(p))); })
.def("transform_vector", [](const CoordinateSystem& c, const py::object& v) { return as_array(c.transform_vector(vec_from_python(v))); })
.def("_format_string", &CoordinateSystem::to_string, py::arg("indent") = 0)
.def("__str__", [](const CoordinateSystem& c) { return c.to_string(0); })
.def("__repr__", &CoordinateSystem::repr);
// The world frame as a module constant, like simplecadapi.WORLD_CS.
m.attr("WORLD_CS") = py::cast(scad::world_cs());
py::class_<Workplane>(m, "SimpleWorkplane")
.def(py::init([](const py::object& origin, const py::object& normal, const py::object& x_dir) {
return std::make_unique<Workplane>(vec_from_python(origin), vec_from_python(normal), vec_from_python(x_dir));
}),
py::arg("origin") = py::make_tuple(0, 0, 0), py::arg("normal") = py::make_tuple(0, 0, 1),
py::arg("x_dir") = py::make_tuple(1, 0, 0))
.def_property_readonly("cs", &Workplane::cs, py::return_value_policy::reference_internal)
.def("__enter__", [](Workplane& w) -> Workplane& { w.enter(); return w; }, py::return_value_policy::reference)
.def("__exit__", [](Workplane& w, const py::object&, const py::object&, const py::object&) { w.exit(); })
.def("_format_string", &Workplane::to_string, py::arg("indent") = 0, py::arg("show_coordinate_system") = true)
.def("__str__", [](const Workplane& w) { return w.to_string(0, true); })
.def("__repr__", &Workplane::repr);
m.attr("Workplane") = m.attr("SimpleWorkplane");
m.def("get_current_cs", [] { return scad::current_cs(); });
// use_coordinate_system(cs): context manager over the same stack.
struct CsScope {
explicit CsScope(CoordinateSystem c) : cs_(std::move(c)) {}
CoordinateSystem cs_;
std::unique_ptr<scad::CoordinateSystemScope> scope_;
};
py::class_<CsScope>(m, "_CoordinateSystemScope")
.def("__enter__", [](CsScope& s) { s.scope_ = std::make_unique<scad::CoordinateSystemScope>(s.cs_); })
.def("__exit__", [](CsScope& s, const py::object&, const py::object&, const py::object&) { s.scope_.reset(); });
m.def("use_coordinate_system", [](const CoordinateSystem& cs) { return CsScope(cs); });
}
+599
View File
@@ -0,0 +1,599 @@
// Python bindings for the "io" area: tessellation, import/export, BREP bytes,
// shape serialization and BREP region snapshots.
//
// Everything that takes a path accepts str / os.PathLike (pybind11's
// std::filesystem::path caster converts through the file-system encoding, wide
// characters on Windows). Heavy work runs with the GIL released on a copy of the
// TopoDS_Shape handle -- the semantic state is only touched while the GIL is held.
#include "bindings.hpp"
#include <pybind11/stl/filesystem.h>
#include <memory>
#include <optional>
#include <vector>
#include "scad/core/error.hpp"
#include "scad/io/brep.hpp"
#include "scad/io/brep_region.hpp"
#include "scad/io/exchange.hpp"
#include "scad/io/mesh.hpp"
#include "scad/io/serialize.hpp"
#include "scad/io/step_assembly.hpp"
#include "scad/topo/shape.hpp"
namespace {
using namespace scad;
namespace io = scad::io;
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
py::object cast_shape(const Shape& shape) {
switch (shape.kind()) {
case Kind::Vertex: return py::cast(Vertex(shape));
case Kind::Edge: return py::cast(Edge(shape));
case Kind::Wire: return py::cast(Wire(shape));
case Kind::Face: return py::cast(Face(shape));
case Kind::Shell: return py::cast(Shell(shape));
case Kind::Solid: return py::cast(Solid(shape));
case Kind::Compound: return py::cast(Compound(shape));
}
throw RuntimeError("unknown shape kind");
}
py::bytes to_py_bytes(const io::Bytes& bytes) { return py::bytes(bytes.data(), bytes.size()); }
io::Bytes from_py_bytes(const py::bytes& bytes) {
char* data = nullptr;
Py_ssize_t size = 0;
if (PYBIND11_BYTES_AS_STRING_AND_SIZE(bytes.ptr(), &data, &size) != 0) throw py::error_already_set();
return io::Bytes(data, static_cast<std::size_t>(size));
}
// A Shape or a sequence of Shapes -> TopoDS_Shapes.
std::vector<TopoDS_Shape> shapes_from(const py::object& arg) {
if (py::isinstance<Shape>(arg)) return {arg.cast<const Shape&>().wrapped()};
std::vector<TopoDS_Shape> out;
for (const py::handle item : arg) {
if (!py::isinstance<Shape>(item))
throw TypeError("expected a shape or a sequence of shapes, got " +
std::string(py::str(py::type::of(item).attr("__name__"))));
out.push_back(item.cast<const Shape&>().wrapped());
}
return out;
}
// A read-only numpy view of rows x width elements of `Elem` (a 1-d array when width is 1),
// kept alive by `owner`.
template <class Elem>
py::array view(const py::object& owner, const Elem* data, std::size_t rows, std::size_t width) {
std::vector<py::ssize_t> shape{static_cast<py::ssize_t>(rows)};
std::vector<py::ssize_t> strides{static_cast<py::ssize_t>(width * sizeof(Elem))};
if (width > 1) {
shape.push_back(static_cast<py::ssize_t>(width));
strides.push_back(static_cast<py::ssize_t>(sizeof(Elem)));
}
py::array array(py::dtype::of<Elem>(), shape, strides, data, owner);
array.attr("setflags")(py::arg("write") = false);
return array;
}
io::MeshParameters mesh_parameters(double linear, double angular, bool relative, bool parallel) {
io::MeshParameters p;
p.linear_deflection = linear;
p.angular_deflection = angular;
p.relative = relative;
p.parallel = parallel;
return p;
}
py::dict surface_report(const io::SurfaceExportReport& r) {
py::dict d;
d["output_path"] = py::str(io::path_to_utf8(r.output_path));
d["solid_count"] = r.solid_count;
d["vertex_count"] = r.vertex_count;
d["triangle_count"] = r.triangle_count;
d["linear_deflection"] = r.parameters.linear_deflection;
d["angular_deflection_degrees"] = r.parameters.angular_deflection_degrees;
d["relative"] = r.parameters.relative;
d["tessellation_backend"] = "opencascade-brep-tessellation";
return d;
}
io::SurfaceMeshParameters surface_parameters(double linear, double angular_degrees, bool relative) {
io::SurfaceMeshParameters p;
p.linear_deflection = linear;
p.angular_deflection_degrees = angular_degrees;
p.relative = relative;
return p;
}
io::RegionRootKind root_kind(const std::string& name) {
if (name == "solid") return io::RegionRootKind::Solid;
if (name == "shell") return io::RegionRootKind::Shell;
throw ValueError("root_kind must be 'solid' or 'shell'");
}
// ---------------------------------------------------------------------------
// Mesh classes
// ---------------------------------------------------------------------------
void bind_mesh(py::module_& m) {
py::class_<io::Mesh, std::shared_ptr<io::Mesh>>(
m, "Mesh",
"A triangle mesh: float32 vertices (n, 3), per-vertex normals (n, 3), uint32 triangles (m, 3) and the face\n"
"index of each triangle (m,). The arrays are read-only views of the mesh's own memory (no copy); they keep\n"
"the mesh alive.")
.def_property_readonly("vertices", [](const py::object& self) {
const auto& mesh = self.cast<const io::Mesh&>();
return view<float>(self, mesh.vertices.data(), mesh.vertex_count(), 3);
})
.def_property_readonly("normals", [](const py::object& self) {
const auto& mesh = self.cast<const io::Mesh&>();
return view<float>(self, mesh.normals.data(), mesh.vertex_count(), 3);
})
.def_property_readonly("triangles", [](const py::object& self) {
const auto& mesh = self.cast<const io::Mesh&>();
return view<std::uint32_t>(self, mesh.triangles.data(), mesh.triangle_count(), 3);
})
.def_property_readonly("face_ids", [](const py::object& self) {
const auto& mesh = self.cast<const io::Mesh&>();
return view<std::uint32_t>(self, mesh.face_ids.data(), mesh.face_ids.size(), 1);
})
.def_property_readonly(
"face_ranges",
[](const py::object& self) {
const auto& mesh = self.cast<const io::Mesh&>();
static_assert(sizeof(io::FaceRange) == 3 * sizeof(std::uint32_t));
return view<std::uint32_t>(self, reinterpret_cast<const std::uint32_t*>(mesh.face_ranges.data()),
mesh.face_ranges.size(), 3);
},
"(face_index, first_triangle, triangle_count) for every face, in face order.")
.def_property_readonly("vertex_count", [](const io::Mesh& mesh) { return mesh.vertex_count(); })
.def_property_readonly("triangle_count", [](const io::Mesh& mesh) { return mesh.triangle_count(); })
.def_property_readonly("bounds",
[](const io::Mesh& mesh) {
const auto b = mesh.bounds();
return py::make_tuple(py::make_tuple(b[0][0], b[0][1], b[0][2]),
py::make_tuple(b[1][0], b[1][1], b[1][2]));
})
.def("__repr__", [](const io::Mesh& mesh) {
return "Mesh(vertices=" + std::to_string(mesh.vertex_count()) +
", triangles=" + std::to_string(mesh.triangle_count()) + ")";
});
m.def(
"mesh",
[](const Shape& shape, double linear_deflection, double angular_deflection, bool relative, bool parallel) {
const TopoDS_Shape wrapped = shape.wrapped();
const io::MeshParameters parameters = mesh_parameters(linear_deflection, angular_deflection, relative, parallel);
io::Mesh result;
{
py::gil_scoped_release release;
result = io::mesh(wrapped, parameters);
}
return std::make_shared<io::Mesh>(std::move(result));
},
py::arg("shape"), py::arg("linear_deflection") = io::kDefaultLinearDeflection,
py::arg("angular_deflection") = io::kDefaultAngularDeflection, py::kw_only(), py::arg("relative") = false,
py::arg("parallel") = true,
"Tessellate `shape` (copy-on-mesh: the argument is not modified) into a Mesh.\n"
"Faces keep their own vertices, so normals stay sharp across edges; triangles wind outward.");
// _internal.mesh: the double-precision mesh with per-corner normals.
py::module_ internal = m.def_submodule("_internal_mesh", "simplecadapi._internal.mesh");
internal.attr("DEFAULT_LINEAR_TOLERANCE") = io::kDefaultLinearDeflection;
internal.attr("DEFAULT_ANGULAR_TOLERANCE") = io::kDefaultAngularDeflection;
internal.attr("MESH_RUNTIME_KEY") = "mesh.default";
internal.attr("MESH_ERROR_RUNTIME_KEY") = "mesh.error";
py::class_<io::FaceTriangleRange>(internal, "FaceTriangleRange")
.def_readonly("face_index", &io::FaceTriangleRange::face_index)
.def_readonly("start", &io::FaceTriangleRange::start)
.def_readonly("count", &io::FaceTriangleRange::count)
.def_readonly("source_topo_id", &io::FaceTriangleRange::source_topo_id);
py::class_<io::TriMesh, std::shared_ptr<io::TriMesh>>(internal, "TriMesh")
.def_property_readonly("vertices", [](const py::object& self) {
const auto& mesh = self.cast<const io::TriMesh&>();
return view<double>(self, mesh.vertices.data(), mesh.vertex_count(), 3);
})
.def_property_readonly("triangles", [](const py::object& self) {
const auto& mesh = self.cast<const io::TriMesh&>();
return view<std::int64_t>(self, mesh.triangles.data(), mesh.triangle_count(), 3);
})
.def_property_readonly("corner_normals",
[](const py::object& self) {
const auto& mesh = self.cast<const io::TriMesh&>();
py::array flat = view<double>(self, mesh.corner_normals.data(), mesh.triangle_count() * 3, 3);
return flat.attr("reshape")(py::make_tuple(mesh.triangle_count(), 3, 3));
})
.def_readonly("face_triangle_ranges", &io::TriMesh::face_triangle_ranges)
.def_readonly("linear_tolerance", &io::TriMesh::linear_tolerance)
.def_readonly("angular_tolerance", &io::TriMesh::angular_tolerance)
.def_property_readonly("vertex_count", [](const io::TriMesh& mesh) { return mesh.vertex_count(); })
.def_property_readonly("triangle_count", [](const io::TriMesh& mesh) { return mesh.triangle_count(); })
.def_property_readonly("bounds", [](const io::TriMesh& mesh) {
const auto b = mesh.bounds();
return py::make_tuple(py::make_tuple(b[0].x, b[0].y, b[0].z), py::make_tuple(b[1].x, b[1].y, b[1].z));
});
internal.def(
"cached_mesh",
[](const Shape& solid, double linear_tolerance, double angular_tolerance) {
// The mesh is shared with the cache and exposed read-only, so handing it out un-const is safe.
return std::const_pointer_cast<io::TriMesh>(io::cached_mesh(solid, linear_tolerance, angular_tolerance));
},
py::arg("solid"), py::kw_only(), py::arg("linear_tolerance") = io::kDefaultLinearDeflection,
py::arg("angular_tolerance") = io::kDefaultAngularDeflection);
internal.def(
"build_solid_trimesh",
[](const Shape& solid, double linear_tolerance, double angular_tolerance) {
return std::make_shared<io::TriMesh>(io::build_solid_trimesh(solid, linear_tolerance, angular_tolerance));
},
py::arg("solid"), py::kw_only(), py::arg("linear_tolerance") = io::kDefaultLinearDeflection,
py::arg("angular_tolerance") = io::kDefaultAngularDeflection);
internal.def(
"mesh_error",
[](const Shape& solid) -> py::object {
const std::string text = io::mesh_error(solid);
return text.empty() ? py::none() : py::object(py::str(text));
},
py::arg("solid"));
}
// ---------------------------------------------------------------------------
// BREP bytes, serialization, pickling
// ---------------------------------------------------------------------------
void bind_bytes(py::module_& m) {
const std::string to_brep_doc =
"to_brep() -> bytes\n"
"BinTools binary, format version 4, geometry only (no triangulation): bit-exact doubles, readable by every\n"
"OpenCASCADE >= 7.3. Hand these bytes to OCP with BinTools.Read_s(shape, io.BytesIO(data)).";
py::object any_shape = m.attr("AnyShape");
any_shape.attr("to_brep") = py::cpp_function(
[](const Shape& shape) {
const TopoDS_Shape wrapped = shape.wrapped();
io::Bytes bytes;
{
py::gil_scoped_release release;
bytes = io::to_brep_bytes(wrapped);
}
return to_py_bytes(bytes);
},
py::name("to_brep"), py::is_method(any_shape), py::doc(to_brep_doc.c_str()));
any_shape.attr("from_brep") = py::staticmethod(py::cpp_function(
[](const py::bytes& data, bool require_valid) {
const io::Bytes bytes = from_py_bytes(data);
io::BrepReadOptions options;
options.require_valid = require_valid;
TopoDS_Shape shape;
{
py::gil_scoped_release release;
shape = io::from_brep_bytes(bytes, options);
}
return cast_shape(Shape::from_occt(shape));
},
py::name("from_brep"), py::arg("data"), py::arg("require_valid") = false,
py::doc("from_brep(data: bytes) -> Shape\nThe shape (Solid, Face, ...) stored in BinTools or ASCII BRep bytes.")));
m.attr("from_brep") = any_shape.attr("from_brep");
m.def(
"canonical_brep_bytes",
[](const Shape& shape) {
const TopoDS_Shape wrapped = shape.wrapped();
io::Bytes bytes;
{
py::gil_scoped_release release;
bytes = io::canonical_brep_bytes(wrapped);
}
return to_py_bytes(bytes);
},
py::arg("shape"),
"The deterministic BREP encoding to hash (artifacts.brep.write_brep_bytes): the smallest member of the\n"
"encode/decode cycle.");
m.def(
"serialize_shape", [](const Shape& shape) { return to_py_bytes(io::serialize(shape)); }, py::arg("shape"),
"Geometry (BinTools V4) plus the tags, bindings, lineage, metadata and runtime values of every entity, in the\n"
"versioned 'SCADSHAP' container (docs/io.md).");
m.def(
"deserialize_shape", [](const py::bytes& data) { return cast_shape(io::deserialize(from_py_bytes(data))); },
py::arg("data"), "Inverse of serialize_shape.");
m.def(
"clone_semantic_view", [](const Shape& shape) { return cast_shape(shape.clone_view()); }, py::arg("shape"),
"A new root over the same geometry in which every entity carries a copy of the source entity's complete state\n"
"(tags, bindings, lineage, metadata, graph attachments) under the same topo id.");
m.def(
"_from_occt", [](const TopoDS_Shape& shape) { return cast_shape(Shape::from_occt(shape)); }, py::arg("shape"),
"A native shape for an OCCT shape (the way back from `.wrapped`).");
// pickle / copy: reduce through the container.
const py::object deserialize = m.attr("deserialize_shape");
any_shape.attr("__reduce__") = py::cpp_function(
[deserialize](const Shape& shape) {
return py::make_tuple(deserialize, py::make_tuple(to_py_bytes(io::serialize(shape))));
},
py::name("__reduce__"), py::is_method(any_shape));
}
// ---------------------------------------------------------------------------
// STEP assemblies: definitions arrive as plain dicts (see exporter/step.py).
// ---------------------------------------------------------------------------
Vec3 vec3_from(const py::handle& obj) {
const auto values = py::cast<std::vector<double>>(obj);
if (values.size() != 3) throw ValueError("expected three numbers");
return Vec3{values[0], values[1], values[2]};
}
io::StepPlacement placement_from(const py::dict& d) {
io::StepPlacement p;
p.origin = vec3_from(d["origin"]);
p.x_axis = vec3_from(d["x_axis"]);
p.y_axis = vec3_from(d["y_axis"]);
p.z_axis = vec3_from(d["z_axis"]);
return p;
}
std::vector<io::StepDefinition> definitions_from(const py::sequence& items) {
std::vector<io::StepDefinition> out;
for (const py::handle handle : items) {
const py::dict d = py::reinterpret_borrow<py::dict>(handle);
io::StepDefinition def;
def.id = d["id"].cast<std::string>();
if (d.contains("kind")) def.kind = d["kind"].cast<std::string>();
def.name = d["name"].cast<std::string>();
if (d.contains("shape") && !d["shape"].is_none()) def.shape = d["shape"].cast<const Shape&>().wrapped();
if (d.contains("metadata")) def.metadata = pybind::value_from_python(d["metadata"]);
if (d.contains("color") && !d["color"].is_none()) {
const Vec3 c = vec3_from(d["color"]);
def.color = std::array<double, 3>{c.x, c.y, c.z};
}
if (d.contains("material") && !d["material"].is_none()) {
const py::dict m = d["material"].cast<py::dict>();
io::StepMaterial material;
material.id = m["id"].cast<std::string>();
material.name = m["name"].cast<std::string>();
material.description = pybind::value_from_python(m["description"]);
if (m.contains("density") && !m["density"].is_none()) material.density = m["density"].cast<double>();
if (m.contains("density_unit")) material.density_unit = m["density_unit"].cast<std::string>();
def.material = std::move(material);
}
if (d.contains("components")) {
for (const py::handle ch : d["components"]) {
const py::dict c = py::reinterpret_borrow<py::dict>(ch);
io::StepComponent component;
component.id = c["id"].cast<std::string>();
component.name = c["name"].cast<std::string>();
component.definition_id = c["definition_id"].cast<std::string>();
component.placement = placement_from(c["placement"].cast<py::dict>());
component.metadata = pybind::value_from_python(c["metadata"]);
def.components.push_back(std::move(component));
}
}
out.push_back(std::move(def));
}
return out;
}
// ---------------------------------------------------------------------------
// Files
// ---------------------------------------------------------------------------
void bind_files(py::module_& m) {
m.def(
"export_step",
[](const py::object& shapes, const std::filesystem::path& path) {
const auto list = shapes_from(shapes);
py::gil_scoped_release release;
io::export_step_shapes(list, path);
},
py::arg("shapes"), py::arg("path"), "Write a shape, or a list of shapes (as one compound), to a STEP file.");
m.def(
"step_bytes",
[](const py::object& shapes) {
const auto list = shapes_from(shapes);
io::Bytes bytes;
{
py::gil_scoped_release release;
bytes = io::step_bytes(list);
}
return to_py_bytes(bytes);
},
py::arg("shapes"));
m.def(
"import_step",
[](const std::filesystem::path& path, bool require_single_root, bool require_valid) {
io::StepReadOptions options;
options.require_single_root = require_single_root;
options.require_valid = require_valid;
io::StepReadResult result;
{
py::gil_scoped_release release;
result = io::read_step(path, options);
}
return cast_shape(Shape::from_occt(result.shape));
},
py::arg("path"), py::kw_only(), py::arg("require_single_root") = false, py::arg("require_valid") = false,
"Read a STEP file: the single root, or a compound of every root.");
m.def(
"tessellate_solid",
[](const Shape& shape, double linear_deflection, double angular_deflection_degrees, bool relative) {
const TopoDS_Shape occ = shape.wrapped();
const io::SurfaceMeshParameters parameters =
surface_parameters(linear_deflection, angular_deflection_degrees, relative);
io::WeldedMesh mesh;
{
py::gil_scoped_release release;
mesh = io::tessellate_solid(occ, parameters);
}
const std::size_t nv = mesh.vertex_count();
py::array_t<double> vertices({static_cast<py::ssize_t>(nv), py::ssize_t{3}});
std::copy(mesh.vertices.begin(), mesh.vertices.end(), vertices.mutable_data());
py::array_t<std::int32_t> triangles({static_cast<py::ssize_t>(mesh.triangles.size()), py::ssize_t{3}});
auto* out = triangles.mutable_data();
for (const auto& t : mesh.triangles) {
*out++ = t[0];
*out++ = t[1];
*out++ = t[2];
}
return py::make_tuple(vertices, triangles);
},
py::arg("shape"), py::kw_only(), py::arg("linear_deflection") = 0.1,
py::arg("angular_deflection_degrees") = 20.0, py::arg("relative") = false,
"(vertices Nx3 float64, triangles Mx3 int32): the shape's surface tessellated, vertices welded.");
m.def(
"export_step_assembly",
[](const py::sequence& definitions, const std::string& root_id, const std::filesystem::path& path,
const std::string& schema, bool metadata_properties) {
const auto defs = definitions_from(definitions);
io::StepAssemblyOptions options;
options.schema = schema;
options.metadata_properties = metadata_properties;
io::StepAssemblyReport report;
{
py::gil_scoped_release release;
report = io::export_step_assembly(defs, root_id, path, options);
}
py::dict d;
d["schema"] = report.schema;
d["definition_ids"] = report.definition_ids;
d["occurrence_count"] = report.occurrence_count;
d["material_ids"] = report.material_ids;
d["metadata_item_count"] = report.metadata_item_count;
return d;
},
py::arg("definitions"), py::arg("root_id"), py::arg("path"), py::kw_only(), py::arg("schema") = "AP242DIS",
py::arg("metadata_properties") = true,
"AP242 STEP of a product structure (XCAF names, colours, materials, metadata properties).");
m.def(
"export_stl",
[](const py::object& shapes, const std::filesystem::path& path, double linear_deflection,
double angular_deflection_degrees, bool relative, bool ascii) -> py::object {
const auto list = shapes_from(shapes);
if (ascii) {
const io::MeshParameters parameters = mesh_parameters(
linear_deflection, angular_deflection_degrees * kPi / 180.0, relative, /*parallel=*/false);
{
py::gil_scoped_release release;
io::export_stl_ascii(list, path, parameters);
}
return py::none();
}
io::SurfaceExportReport report;
{
py::gil_scoped_release release;
report = io::export_stl(list, path, surface_parameters(linear_deflection, angular_deflection_degrees, relative));
}
return surface_report(report);
},
py::arg("shapes"), py::arg("path"), py::kw_only(), py::arg("linear_deflection") = 0.1,
py::arg("angular_deflection_degrees") = 20.0, py::arg("relative") = false, py::arg("ascii") = false,
"Binary STL of the solids' surface (vertices welded per solid) and a report dict; ascii=True writes\n"
"unwelded ASCII facets (kernel export_stl_shape) and returns None.");
m.def(
"import_stl",
[](const std::filesystem::path& path) {
io::Mesh mesh;
{
py::gil_scoped_release release;
mesh = io::read_stl(path);
}
return std::make_shared<io::Mesh>(std::move(mesh));
},
py::arg("path"), "Read a binary or ASCII STL as a Mesh (coincident vertices merged).");
m.def(
"import_stl_shape",
[](const std::filesystem::path& path, double sewing_tolerance) {
return cast_shape(io::import_stl_shape(path, sewing_tolerance));
},
py::arg("path"), py::arg("sewing_tolerance") = 1e-6,
"Read an STL as a faceted BREP (a Solid when the triangles close up).");
m.def(
"export_obj",
[](const py::object& shapes, const std::filesystem::path& path, double linear_deflection,
double angular_deflection_degrees, bool relative) {
const auto list = shapes_from(shapes);
io::SurfaceExportReport report;
{
py::gil_scoped_release release;
report = io::export_obj(list, path, surface_parameters(linear_deflection, angular_deflection_degrees, relative));
}
return surface_report(report);
},
py::arg("shapes"), py::arg("path"), py::kw_only(), py::arg("linear_deflection") = 0.1,
py::arg("angular_deflection_degrees") = 20.0, py::arg("relative") = false);
m.def(
"export_glb",
[](const py::object& shapes, const std::filesystem::path& path, double linear_deflection,
double angular_deflection, bool relative) {
const auto list = shapes_from(shapes);
const io::MeshParameters parameters = mesh_parameters(linear_deflection, angular_deflection, relative, true);
py::gil_scoped_release release;
io::export_glb(list, path, parameters);
},
py::arg("shapes"), py::arg("path"), py::kw_only(), py::arg("linear_deflection") = 0.1,
py::arg("angular_deflection") = 0.5, py::arg("relative") = false,
"Write a glTF 2.0 binary (.glb): one mesh, positions + normals + triangle indices.\n"
"Defaults are the kernel exporter's (0.1 linear, 0.5 rad angular).");
m.def(
"export_brep", [](const Shape& shape, const std::filesystem::path& path) { io::export_brep(shape, path); },
py::arg("shape"), py::arg("path"), "Write BinTools V4 BREP bytes to a file.");
m.def(
"import_brep",
[](const std::filesystem::path& path, bool require_valid) {
io::BrepReadOptions options;
options.require_valid = require_valid;
return cast_shape(io::import_brep(path, options));
},
py::arg("path"), py::arg("require_valid") = false);
}
// ---------------------------------------------------------------------------
// Region snapshots
// ---------------------------------------------------------------------------
void bind_region(py::module_& m) {
py::module_ region = m.def_submodule("_brep_region", "simplecadapi._internal.brep_region");
region.attr("MAGIC") = py::bytes(std::string(io::kBRegionMagic));
region.attr("MAJOR_VERSION") = io::kBRegionMajorVersion;
region.attr("MINOR_VERSION") = io::kBRegionMinorVersion;
region.def("default_ocp_version", &io::default_ocp_version);
region.def("region_profile", &io::region_profile, py::arg("ocp_version"));
region.def(
"read_artifact",
[](const std::filesystem::path& path, const std::string& sha256, const std::string& expected_root_kind,
const std::optional<std::filesystem::path>& replay_root) {
io::RegionFile file = io::read_artifact(path, sha256, root_kind(expected_root_kind), replay_root);
return py::make_tuple(cast_shape(Shape::from_occt(file.shape)), py::cast(file.manifest), file.sha256);
},
py::arg("path"), py::arg("sha256"), py::kw_only(), py::arg("expected_root_kind"),
py::arg("replay_root") = py::none(),
"(shape, manifest, sha256) of a hash-pinned .scadbrep file.");
region.def(
"decode_artifact",
[](const py::bytes& data, const std::optional<std::string>& expected_root_kind) {
io::DecodedRegion decoded = io::decode_artifact(
from_py_bytes(data), expected_root_kind ? std::optional(root_kind(*expected_root_kind)) : std::nullopt);
return py::make_tuple(cast_shape(Shape::from_occt(decoded.shape)), py::cast(decoded.manifest));
},
py::arg("data"), py::kw_only(), py::arg("expected_root_kind") = py::none());
region.def(
"copy_step_region_rpath",
[](const std::filesystem::path& path, const std::filesystem::path& output_path,
const std::optional<std::string>& ocp_version) {
return io::copy_step_solid_region(path, output_path, ocp_version.value_or(""));
},
py::arg("path"), py::arg("output_path"), py::kw_only(), py::arg("ocp_version") = py::none(),
"Copy one STEP solid into a .scadbrep snapshot (the whole-solid form of the Python function).");
region.def("checked_region_path", &io::checked_region_path, py::arg("path"), py::arg("for_graph"));
}
} // namespace
void bind_io(py::module_& m) {
bind_mesh(m);
bind_bytes(m);
bind_files(m);
bind_region(m);
}
@@ -0,0 +1,567 @@
// Python bindings for the "ops_features" area: the operators of operators/{features,boolean,
// transform}.py under the Python names, argument names and defaults (keyword-only where
// Python is keyword-only).
//
// The GIL is released around the kernel work, except while a ql selector is being resolved
// (a property resolver registered from Python is called back from there).
#include "bindings.hpp"
#include <optional>
#include <string>
#include <vector>
#include "scad/core/error.hpp"
#include "scad/ops/features/features.hpp"
#include "scad/ql/ql.hpp"
#include "scad/reactive/registry.hpp"
namespace {
using namespace scad;
// ---- conversions ---------------------------------------------------------------------------------------------
py::object shape_to_py(const Shape& s) {
switch (s.kind()) {
case Kind::Vertex: return py::cast(Vertex(s));
case Kind::Edge: return py::cast(Edge(s));
case Kind::Wire: return py::cast(Wire(s));
case Kind::Face: return py::cast(Face(s));
case Kind::Shell: return py::cast(Shell(s));
case Kind::Solid: return py::cast(Solid(s));
case Kind::Compound: return py::cast(Compound(s));
}
return py::none();
}
py::list shapes_to_py(const std::vector<Shape>& shapes) {
py::list out;
for (const Shape& shape : shapes) out.append(shape_to_py(shape));
return out;
}
py::list solids_to_py(const std::vector<Solid>& solids) {
py::list out;
for (const Solid& solid : solids) out.append(py::cast(solid));
return out;
}
// A list of shapes of one kind, or a ql selector that finds them.
template <class T>
Selection<T> selection_from(const py::object& value) {
if (py::isinstance<ql::ShapeSelector>(value)) return Selection<T>(value.cast<const ql::ShapeSelector&>());
std::vector<T> items;
for (const py::handle item : value) {
if (!py::isinstance<T>(item)) {
throw TypeError(std::string("expected a ") + std::string(kind_name(T::kKind)) + " or a QL selector");
}
items.push_back(item.cast<T>());
}
return Selection<T>(std::move(items));
}
// A 3-vector argument that Python validates itself: any sequence of numbers, ValueError unless it
// holds exactly three.
Scalar3 vector_arg(const py::object& value, const char* name) {
const std::string message = std::string(name) + " must contain three finite numbers";
if ((py::isinstance<py::str>(value) || py::isinstance<py::bytes>(value)) || !py::hasattr(value, "__len__") || !py::hasattr(value, "__getitem__")) throw ValueError(message);
const py::sequence items = py::reinterpret_borrow<py::sequence>(value);
if (items.size() != 3) throw ValueError(message);
Scalar3 out;
for (std::size_t i = 0; i < 3; ++i) out[i] = items[i].cast<Scalar>();
return out;
}
std::vector<Shape> shape_list(const py::object& value, const char* complaint) {
std::vector<Shape> out;
for (const py::handle item : value) {
if (!py::isinstance<Shape>(item)) throw TypeError(complaint);
out.push_back(item.cast<Shape>());
}
return out;
}
// An operator that takes `tracking_policy`: the enum member or its string value.
std::string policy_text(const py::object& value) {
if (py::isinstance<py::str>(value)) return value.cast<std::string>();
if (py::hasattr(value, "value")) return py::str(value.attr("value")).cast<std::string>();
return py::str(value).cast<std::string>();
}
// Runs `body` with the GIL released unless `keep_gil`. An exception leaves with the GIL back.
template <class F>
auto unlocked(bool keep_gil, F&& body) {
std::optional<py::gil_scoped_release> release;
if (!keep_gil) release.emplace();
return body();
}
py::tuple unit_z() { return py::make_tuple(0, 0, 1); }
py::tuple origin() { return py::make_tuple(0, 0, 0); }
// ---- sweeps of a profile ------------------------------------------------------------------------------------
SweepTags sweep_tags(OptionalString tag_prefix, OptionalString result_tag, OptionalString start, OptionalString end,
OptionalString side) {
return {std::move(tag_prefix), std::move(result_tag), std::move(start), std::move(end), std::move(side)};
}
void bind_extrusion(py::module_& m) {
m.def(
"extrude_rsolid",
[](const Shape& profile, const Scalar3& direction, const Scalar& distance, OptionalString tag_prefix,
OptionalString result_tag, OptionalString start_face_tag, OptionalString end_face_tag, OptionalString side_faces_tag) {
const SweepTags tags = sweep_tags(std::move(tag_prefix), std::move(result_tag), std::move(start_face_tag),
std::move(end_face_tag), std::move(side_faces_tag));
return unlocked(false, [&] { return extrude_rsolid(profile, direction, distance, tags); });
},
py::arg("profile"), py::arg("direction"), py::arg("distance"), py::kw_only(), py::arg("tag_prefix") = py::none(),
py::arg("result_tag") = py::none(), py::arg("start_face_tag") = py::none(), py::arg("end_face_tag") = py::none(),
py::arg("side_faces_tag") = py::none(), "Create a solid by extruding a profile, with optional role-based tags.");
m.def(
"revolve_rsolid",
[](const Shape& profile, const Scalar3& axis, const Scalar& angle, const Scalar3& origin, OptionalString tag_prefix,
OptionalString result_tag, OptionalString start_face_tag, OptionalString end_face_tag, OptionalString side_faces_tag) {
const SweepTags tags = sweep_tags(std::move(tag_prefix), std::move(result_tag), std::move(start_face_tag),
std::move(end_face_tag), std::move(side_faces_tag));
return unlocked(false, [&] { return revolve_rsolid(profile, axis, angle, origin, tags); });
},
py::arg("profile"), py::arg("axis") = unit_z(), py::arg("angle") = 360, py::arg("origin") = origin(), py::kw_only(),
py::arg("tag_prefix") = py::none(), py::arg("result_tag") = py::none(), py::arg("start_face_tag") = py::none(),
py::arg("end_face_tag") = py::none(), py::arg("side_faces_tag") = py::none(),
"Create a revolved solid, with optional kernel-role-based tags.");
}
// ---- local features ------------------------------------------------------------------------------------------
void bind_blends(py::module_& m) {
m.def(
"fillet_rsolid",
[](const Solid& solid, const py::object& edges, const Scalar& radius, OptionalString result_tag,
OptionalString generated_faces_tag) {
const EdgeSelection selection = selection_from<Edge>(edges);
const BlendTags tags{std::move(result_tag), std::move(generated_faces_tag)};
return unlocked(selection.is_selector(), [&] { return fillet_rsolid(solid, selection, radius, tags); });
},
py::arg("solid"), py::arg("edges"), py::arg("radius"), py::kw_only(), py::arg("result_tag") = py::none(),
py::arg("generated_faces_tag") = py::none(), "Apply fillets, with optional tagging of kernel-proven patch faces.");
m.def(
"chamfer_rsolid",
[](const Solid& solid, const py::object& edges, const Scalar& distance, std::optional<double> angle,
std::optional<Vec3> reference_direction, OptionalString result_tag, OptionalString generated_faces_tag) {
const EdgeSelection selection = selection_from<Edge>(edges);
const ChamferOptions options{angle, reference_direction, {std::move(result_tag), std::move(generated_faces_tag)}};
return unlocked(selection.is_selector(), [&] { return chamfer_rsolid(solid, selection, distance, options); });
},
py::arg("solid"), py::arg("edges"), py::arg("distance"), py::kw_only(), py::arg("angle") = py::none(),
py::arg("reference_direction") = py::none(), py::arg("result_tag") = py::none(),
py::arg("generated_faces_tag") = py::none(),
"Apply chamfers, with optional tagging of kernel-proven patch faces.\n\nWithout ``angle`` the chamfer is symmetric. "
"With ``angle`` (degrees between the chamfer face and the reference face) the second leg is "
"``distance * tan(angle)``; ``reference_direction`` picks the reference face per edge.");
m.def(
"shell_rsolid",
[](const Solid& solid, const py::object& faces_to_remove, const Scalar& thickness, OptionalString result_tag,
OptionalString body_faces_tag, OptionalString offset_faces_tag, OptionalString closing_faces_tag,
OptionalString wall_edges_tag) {
const FaceSelection selection = selection_from<Face>(faces_to_remove);
const ShellTags tags{std::move(result_tag), std::move(body_faces_tag), std::move(offset_faces_tag),
std::move(closing_faces_tag), std::move(wall_edges_tag)};
return unlocked(selection.is_selector(), [&] { return shell_rsolid(solid, selection, thickness, tags); });
},
py::arg("solid"), py::arg("faces_to_remove"), py::arg("thickness"), py::kw_only(), py::arg("result_tag") = py::none(),
py::arg("body_faces_tag") = py::none(), py::arg("offset_faces_tag") = py::none(),
py::arg("closing_faces_tag") = py::none(), py::arg("wall_edges_tag") = py::none(),
"Shell a solid, with optional kernel-role-based face tags.");
}
// ---- sweeps through sections ---------------------------------------------------------------------------------
void bind_sweeps(py::module_& m) {
m.def(
"loft_rsolid",
[](const py::object& profiles, bool ruled, const py::object& tracking_policy, OptionalString tag_prefix,
OptionalString result_tag, OptionalString start_face_tag, OptionalString end_face_tag, OptionalString side_faces_tag) {
const std::vector<Shape> sections = shape_list(profiles, "loft_rsolid sections must contain only Wire or Vertex objects");
const LoftOptions options{policy_text(tracking_policy),
sweep_tags(std::move(tag_prefix), std::move(result_tag), std::move(start_face_tag),
std::move(end_face_tag), std::move(side_faces_tag))};
return unlocked(false, [&] { return loft_rsolid(sections, ruled, options); });
},
py::arg("profiles"), py::arg("ruled") = false, py::kw_only(), py::arg("tracking_policy") = "full",
py::arg("tag_prefix") = py::none(), py::arg("result_tag") = py::none(), py::arg("start_face_tag") = py::none(),
py::arg("end_face_tag") = py::none(), py::arg("side_faces_tag") = py::none(),
"Create a lofted solid, with optional kernel-role-based tags.");
m.def(
"sweep_rsolid",
[](const Face& profile, const Wire& path, bool is_frenet, OptionalString tag_prefix, OptionalString result_tag,
OptionalString start_face_tag, OptionalString end_face_tag, OptionalString side_faces_tag) {
const SweepTags tags = sweep_tags(std::move(tag_prefix), std::move(result_tag), std::move(start_face_tag),
std::move(end_face_tag), std::move(side_faces_tag));
return unlocked(false, [&] { return sweep_rsolid(profile, path, is_frenet, tags); });
},
py::arg("profile"), py::arg("path"), py::arg("is_frenet") = false, py::kw_only(), py::arg("tag_prefix") = py::none(),
py::arg("result_tag") = py::none(), py::arg("start_face_tag") = py::none(), py::arg("end_face_tag") = py::none(),
py::arg("side_faces_tag") = py::none(), "Create a swept solid, with optional kernel-role-based tags.");
m.def(
"twisted_sweep_rsolid",
[](const Shape& profile, const Scalar& distance, const Scalar& twist_angle, const Scalar3& axis, const Scalar3& origin,
const Scalar& guide_radius, OptionalString tag_prefix, OptionalString result_tag, OptionalString start_face_tag,
OptionalString end_face_tag, OptionalString side_faces_tag) {
const TwistedSweepOptions options{guide_radius, sweep_tags(std::move(tag_prefix), std::move(result_tag),
std::move(start_face_tag), std::move(end_face_tag),
std::move(side_faces_tag))};
return unlocked(false, [&] { return twisted_sweep_rsolid(profile, distance, twist_angle, axis, origin, options); });
},
py::arg("profile"), py::arg("distance"), py::arg("twist_angle"), py::arg("axis") = unit_z(), py::arg("origin") = origin(),
py::kw_only(), py::arg("guide_radius") = 1.0, py::arg("tag_prefix") = py::none(), py::arg("result_tag") = py::none(),
py::arg("start_face_tag") = py::none(), py::arg("end_face_tag") = py::none(), py::arg("side_faces_tag") = py::none(),
"Sweep a planar profile along a straight axis with linear rotation (twist_angle in degrees).");
m.def(
"helical_sweep_rsolid",
[](const Wire& profile, const Scalar& pitch, const Scalar& height, const Scalar& radius, const Scalar3& center,
const Scalar3& dir, const std::string& handedness) {
return unlocked(false, [&] { return helical_sweep_rsolid(profile, pitch, height, radius, center, dir, handedness); });
},
py::arg("profile"), py::arg("pitch"), py::arg("height"), py::arg("radius"), py::arg("center") = origin(),
py::arg("dir") = unit_z(), py::kw_only(), py::arg("handedness") = "Right",
"Create a solid by sweeping a profile along a helical path.");
m.def(
"sweep_multisection_rsolid",
[](const py::object& profiles, const Wire& path, bool is_frenet, const py::object& binormal) {
const std::vector<Shape> sections = shape_list(profiles, "sections must be Face or Wire");
std::optional<Binormal> aux;
if (py::isinstance<Wire>(binormal)) aux = Binormal(binormal.cast<Wire>());
else if (!binormal.is_none()) aux = Binormal(vector_arg(binormal, "binormal"));
return unlocked(false, [&] { return sweep_multisection_rsolid(sections, path, is_frenet, aux); });
},
py::arg("profiles"), py::arg("path"), py::arg("is_frenet") = false, py::arg("binormal") = py::none(),
"Sweep through explicit ordered sections along a continuous path.");
}
// ---- derived solids ---------------------------------------------------------------------------------------------
void bind_derived(py::module_& m) {
m.def(
"offset_rsolid",
[](const Solid& solid, const Scalar& amount, const py::object& openings, double tolerance, const std::string& kind) {
const FaceSelection selection = selection_from<Face>(openings);
return unlocked(selection.is_selector(), [&] { return offset_rsolid(solid, amount, selection, {tolerance, kind}); });
},
py::arg("solid"), py::arg("amount"), py::arg("openings") = py::tuple(), py::kw_only(), py::arg("tolerance") = 1e-4,
py::arg("kind") = "ARC", "Offset a solid outward (positive) or inward (negative).");
m.def(
"draft_rsolid",
[](const Solid& solid, const py::object& faces_to_draft, const Scalar& angle, const py::object& plane_origin,
const py::object& plane_normal) {
const FaceSelection selection = selection_from<Face>(faces_to_draft);
const Scalar3 origin_value = vector_arg(plane_origin, "plane_origin"), normal_value = vector_arg(plane_normal, "plane_normal");
return unlocked(selection.is_selector(),
[&] { return draft_rsolid(solid, selection, angle, origin_value, normal_value); });
},
py::arg("solid"), py::arg("faces_to_draft"), py::arg("angle"), py::arg("plane_origin") = origin(),
py::arg("plane_normal") = unit_z(),
"Draft planar, cylindrical or conical faces by a signed angle in degrees about a neutral plane.");
m.def(
"extrude_taper_rsolid",
[](const Face& profile, const py::object& vector, const Scalar& taper, bool flip_inner) {
const Scalar3 direction = vector_arg(vector, "vector");
return unlocked(false, [&] { return extrude_taper_rsolid(profile, direction, taper, flip_inner); });
},
py::arg("profile"), py::arg("vector"), py::arg("taper"), py::arg("flip_inner") = true,
"Extrude a planar sketch face by a vector, with a taper in degrees.");
m.def(
"extrude_until_rsolid",
[](const Face& profile, const py::object& target, const py::object& direction, const py::object& until) {
std::vector<Solid> targets;
if (py::isinstance<Solid>(target)) {
targets.push_back(target.cast<Solid>());
} else {
for (const py::handle item : target) {
if (!py::isinstance<Solid>(item)) throw TypeError("target must be a Solid or a sequence of Solid");
targets.push_back(item.cast<Solid>());
}
}
const Scalar3 axis = vector_arg(direction, "direction");
const std::string mode = py::str(py::hasattr(until, "name") ? until.attr("name") : until).cast<std::string>();
return unlocked(false, [&] { return extrude_until_rsolid(profile, targets, axis, mode); });
},
py::arg("profile"), py::arg("target"), py::arg("direction") = unit_z(), py::arg("until") = "NEXT",
"Extrude a planar face until a target surface, including curved surfaces.");
m.def(
"scale_rsolid",
[](const Solid& solid, const py::object& factors, const py::object& center) {
const Scalar3 scale = vector_arg(factors, "factors"), about = vector_arg(center, "center");
return unlocked(false, [&] { return scale_rsolid(solid, scale, about); });
},
py::arg("solid"), py::arg("factors"), py::arg("center") = origin(),
"Scale a solid along the current coordinate system's axes about a center.");
m.def(
"transform_rsolid",
[](const Solid& solid, const std::vector<std::vector<Scalar>>& matrix) {
return unlocked(false, [&] { return transform_rsolid(solid, matrix); });
},
py::arg("solid"), py::arg("matrix"), "Apply a finite nonsingular 4x4 affine matrix in the current coordinate system.");
}
// ---- tracking policy and the failure diagnoses ------------------------------------------------------------------
// `with tracking_policy_scope(TrackingPolicy.GRAPH): ...`
class PolicyScope {
public:
explicit PolicyScope(TrackingPolicy policy) : policy_(policy) {}
PolicyScope& enter() {
scope_.emplace(policy_);
return *this;
}
void exit() { scope_.reset(); }
private:
TrackingPolicy policy_;
std::optional<TrackingPolicyScope> scope_;
};
void bind_tracking_policy(py::module_& m) {
py::list members;
members.append(py::make_tuple("FULL", "full"));
members.append(py::make_tuple("GRAPH", "graph"));
py::dict kwargs;
kwargs["type"] = py::module_::import("builtins").attr("str");
kwargs["module"] = "simplecadapi._cpp";
m.attr("TrackingPolicy") = py::module_::import("enum").attr("Enum")("TrackingPolicy", members, **kwargs);
py::class_<PolicyScope, std::shared_ptr<PolicyScope>>(m, "_TrackingPolicyScope")
.def("__enter__", [](const std::shared_ptr<PolicyScope>& scope) { scope->enter(); return scope; })
.def("__exit__", [](PolicyScope& scope, const py::args&) { scope.exit(); });
m.def(
"tracking_policy_scope",
[](const py::object& policy) {
const std::string text = policy_text(policy);
if (text == "full") return std::make_shared<PolicyScope>(TrackingPolicy::Full);
if (text == "graph") return std::make_shared<PolicyScope>(TrackingPolicy::Graph);
throw ValueError("'" + text + "' is not a valid TrackingPolicy");
},
py::arg("policy"), "Run a block with graph-only or full topology tracking.");
m.def("current_tracking_policy", [] { return std::string(to_string(current_tracking_policy())); });
}
py::list measurements_to_py(const std::vector<ErrorMeasurement>& measurements) {
py::list out;
for (const ErrorMeasurement& item : measurements) {
py::dict entry;
entry["name"] = item.name;
if (const auto* number = std::get_if<double>(&item.value)) entry["value"] = *number;
else {
const auto& v = std::get<std::array<double, 3>>(item.value);
entry["value"] = py::make_tuple(v[0], v[1], v[2]);
}
entry["unit"] = item.unit;
out.append(entry);
}
return out;
}
template <class Diagnosis>
void bind_diagnosis(py::module_& m, const char* name) {
py::class_<Diagnosis>(m, name)
.def_readonly("failure_kind", &Diagnosis::failure_kind)
.def_readonly("what_happened", &Diagnosis::what_happened)
.def_readonly("possible_causes", &Diagnosis::possible_causes)
.def_readonly("repair", &Diagnosis::repair)
.def_property_readonly("measurements", [](const Diagnosis& d) { return measurements_to_py(d.measurements); });
}
void bind_diagnostics(py::module_& m) {
bind_diagnosis<BlendDiagnosis>(m, "BlendDiagnosis");
bind_diagnosis<BooleanDiagnosis>(m, "BooleanDiagnosis");
m.def(
"diagnose_blend_failure",
[](const Solid& solid, const py::list& edges, double size_value, const std::string& operation_kind, const py::object& retry_single) {
std::vector<Edge> items;
for (const py::handle item : edges) items.push_back(item.cast<Edge>());
BlendRetry retry;
if (!retry_single.is_none()) retry = [&](const Edge& edge) { return py::bool_(retry_single(py::cast(edge))).cast<bool>(); };
return diagnose_blend_failure(solid, items, size_value, operation_kind, retry);
},
py::arg("solid"), py::arg("edges"), py::kw_only(), py::arg("size_value"), py::arg("operation_kind"),
py::arg("retry_single") = py::none(), "Classify a fillet/chamfer failure; None when no probe explains it.");
m.def(
"assert_blend_volume_monotonic",
[](const Solid& source, const Solid& result, const std::string&, const std::string& operation_kind,
std::optional<double> size_value, const py::list& edges) {
std::vector<Edge> items;
for (const py::handle item : edges) items.push_back(item.cast<Edge>());
assert_blend_volume_monotonic(source, result, operation_kind, size_value, items);
},
py::arg("source"), py::arg("result"), py::kw_only(), py::arg("operation"), py::arg("operation_kind"),
py::arg("size_value"), py::arg("edges"), "Raise when an all-convex blend returned more material than it was given.");
m.def(
"diagnose_boolean_failure",
[](const py::list& operands, std::optional<double> effective_tol, const std::string& operation_kind) {
std::vector<Solid> solids;
for (const py::handle item : operands) solids.push_back(item.cast<Solid>());
return diagnose_boolean_failure(solids, effective_tol, operation_kind);
},
py::arg("operands"), py::kw_only(), py::arg("effective_tol"), py::arg("operation_kind") = "union",
"Classify a boolean failure from its operands; None when none explains it.");
m.def(
"raise_loft_failure_if_diagnosed",
[](const py::object& sections, const std::string& operation) {
raise_loft_failure_if_diagnosed(shape_list(sections, "loft sections must be shapes"), operation);
},
py::arg("sections"), py::arg("operation"), "Explain a failed loft from its sections, when they do.");
}
// ---- booleans ------------------------------------------------------------------------------------------------
// The Solids of `args`, nested lists and tuples flattened; anything else is the operator's own error.
void flatten_solids(const py::handle& value, std::string_view operation, std::vector<Solid>& out) {
if (py::isinstance<Solid>(value)) {
out.push_back(value.cast<Solid>());
} else if (py::isinstance<py::list>(value) || py::isinstance<py::tuple>(value)) {
for (const py::handle item : value) flatten_solids(item, operation, out);
} else {
reject_boolean_operand(operation);
}
}
std::vector<Solid> flattened(const py::args& args, std::string_view operation) {
std::vector<Solid> out;
for (const py::handle item : args) flatten_solids(item, operation, out);
return out;
}
std::vector<Solid> solid_group(const py::object& group) {
std::vector<Solid> out;
for (const py::handle item : group) {
if (!py::isinstance<Solid>(item)) throw TypeError("boolean groups must contain Solid values");
out.push_back(item.cast<Solid>());
}
return out;
}
void bind_booleans(py::module_& m) {
m.def(
"union_rsolid",
[](const py::args& solids, bool clean, bool glue, std::optional<double> tol, const py::object& tracking_policy) {
const std::vector<Solid> operands = flattened(solids, "union_rsolid");
const UnionOptions options{clean, glue, tol, policy_text(tracking_policy)};
return unlocked(false, [&] { return union_rsolid(operands, options); });
},
py::kw_only(), py::arg("clean") = true, py::arg("glue") = false, py::arg("tol") = py::none(),
py::arg("tracking_policy") = "full", "Compute the boolean union and return one manifold solid.");
m.def(
"cut_rsolid",
[](const py::args& solids, bool skip_non_intersecting, const py::object& tracking_policy) {
const std::vector<Solid> operands = flattened(solids, "cut_rsolid");
const CutOptions options{skip_non_intersecting, policy_text(tracking_policy)};
return unlocked(false, [&] { return cut_rsolid(operands, options); });
},
py::kw_only(), py::arg("skip_non_intersecting") = true, py::arg("tracking_policy") = "full",
"Compute the boolean difference of solids: the first is the base, the rest are subtracted in order.");
m.def(
"intersect_rsolid",
[](const py::args& solids) {
const std::vector<Solid> operands = flattened(solids, "intersect_rsolid");
return unlocked(false, [&] { return intersect_rsolid(operands); });
},
"Compute the boolean intersection of solids.");
m.def(
"boolean_rsolidlist",
[](const py::object& left, const py::object& right, const std::string& operation) {
if (operation != "cut" && operation != "intersect" && operation != "union") {
throw ValueError("operation must be cut, intersect or union");
}
const std::vector<Solid> lhs = solid_group(left), rhs = solid_group(right);
return solids_to_py(unlocked(false, [&] { return boolean_rsolidlist(lhs, rhs, operation); }));
},
py::arg("left"), py::arg("right"), py::arg("operation"),
"Apply a set boolean to two body groups, retaining every result solid.");
const auto bind_2d = [&m](const char* name, Face (*fn)(const Shape&, const Shape&), const char* first, const char* second,
const char* doc) {
m.def(
name,
[fn, name, first, second](const py::object& a, const py::object& b) {
if (!py::isinstance<Shape>(a)) reject_face_operand(name, first);
if (!py::isinstance<Shape>(b)) reject_face_operand(name, second);
const Shape& left = a.cast<const Shape&>();
const Shape& right = b.cast<const Shape&>();
return unlocked(false, [&] { return fn(left, right); });
},
py::arg(first), py::arg(second), doc);
};
bind_2d("make_2d_cut_rface", &make_2d_cut_rface, "body", "tool", "Subtract one 2D face from another.");
bind_2d("make_2d_union_rface", &make_2d_union_rface, "face_a", "face_b", "Compute the boolean union of two 2D faces.");
bind_2d("make_2d_intersect_rface", &make_2d_intersect_rface, "face_a", "face_b",
"Compute the boolean intersection of two 2D faces.");
}
// ---- transforms and patterns ----------------------------------------------------------------------------------
void bind_transforms(py::module_& m) {
m.def(
"translate_shape",
[](const Shape& shape, const Scalar3& vector) {
return shape_to_py(unlocked(false, [&] { return translate_shape(shape, vector); }));
},
py::arg("shape"), py::arg("vector"), "Translate a shape by an offset vector.");
m.def(
"rotate_shape",
[](const Shape& shape, const Scalar& angle, const Scalar3& axis, const Scalar3& origin) {
return shape_to_py(unlocked(false, [&] { return rotate_shape(shape, angle, axis, origin); }));
},
py::arg("shape"), py::arg("angle"), py::arg("axis") = unit_z(), py::arg("origin") = origin(),
"Rotate a shape around an axis.");
m.def(
"mirror_shape",
[](const Shape& shape, const Scalar3& plane_origin, const Scalar3& plane_normal) {
return shape_to_py(unlocked(false, [&] { return mirror_shape(shape, plane_origin, plane_normal); }));
},
py::arg("shape"), py::arg("plane_origin"), py::arg("plane_normal"), "Mirror a shape across a plane.");
m.def(
"linear_pattern_rsolidlist",
[](const Shape& shape, const Scalar3& direction, int count, const Scalar& spacing) {
return shapes_to_py(unlocked(false, [&] { return linear_pattern_rsolidlist(shape, direction, count, spacing); }));
},
py::arg("shape"), py::arg("direction"), py::arg("count"), py::arg("spacing"), "Create a linear pattern of solids.");
m.def(
"radial_pattern_rsolidlist",
[](const Shape& shape, const Scalar3& center, const Scalar3& axis, int count, const Scalar& total_rotation_angle) {
return shapes_to_py(unlocked(false, [&] { return radial_pattern_rsolidlist(shape, center, axis, count, total_rotation_angle); }));
},
py::arg("shape"), py::arg("center"), py::arg("axis"), py::arg("count"), py::arg("total_rotation_angle"),
"Create a radial pattern of solids.");
}
} // namespace
void bind_ops_features(py::module_& m) {
bind_extrusion(m);
bind_blends(m);
bind_booleans(m);
bind_transforms(m);
bind_sweeps(m);
bind_derived(m);
bind_tracking_policy(m);
bind_diagnostics(m);
register_features_executors(reactive::ExecutorRegistry::global());
}
@@ -0,0 +1,361 @@
// Python bindings for the "ops_geometry" area: the non-surface operators of
// simplecadapi/operators/geometry.py, under the Python names, argument names and
// defaults (keyword-only where Python is keyword-only), plus the create_* aliases.
#include "bindings.hpp"
#include "scad/io/brep_region.hpp"
#include <BRepAdaptor_Curve.hxx>
#include <TopAbs_ShapeEnum.hxx>
#include <TopExp.hxx>
#include <TopTools_IndexedMapOfShape.hxx>
#include <TopoDS.hxx>
#include <gp_Pnt.hxx>
#include "scad/ops/geometry/geometry.hpp"
#include "scad/reactive/registry.hpp"
namespace {
using namespace scad;
using namespace pybind11::literals;
// Defaults as Python tuples, so help() shows (0, 0, 1) like the Python SDK.
py::tuple origin() { return py::make_tuple(0, 0, 0); }
py::tuple unit_z() { return py::make_tuple(0, 0, 1); }
// `degree` takes any number: a bool or a fraction is rejected by the operator itself, with
// its own error, as Python does (bool -> NaN is "not an integer").
double degree_of(const py::object& degree) {
if (PyBool_Check(degree.ptr())) return std::nan("");
return degree.cast<double>();
}
SplineSpec spline_spec(std::vector<ScalarPoint> control_points, const py::object& degree, std::optional<ScalarList> knots,
std::optional<std::vector<int>> multiplicities, std::optional<ScalarList> weights, bool periodic) {
return {.control_points = std::move(control_points),
.degree = degree_of(degree),
.knots = std::move(knots),
.multiplicities = std::move(multiplicities),
.weights = std::move(weights),
.periodic = periodic};
}
std::string path_text(const py::object& path) { return py::str(py::module_::import("os").attr("fspath")(path)).cast<std::string>(); }
void bind_lines(py::module_& m) {
m.def("make_point_rvertex", &make_point_rvertex, py::arg("x"), py::arg("y"), py::arg("z"),
"Create a point in 3D space and return it as a vertex.");
m.def("make_line_redge", &make_line_redge, py::arg("start"), py::arg("end"), py::kw_only(),
py::arg("tag_prefix") = py::none(), "Create a straight edge between two points.");
m.def("make_segment_redge", &make_segment_redge, py::arg("start"), py::arg("end"),
"Alias of `make_line_redge` that returns a straight edge.");
m.def("make_segment_rwire", &make_segment_rwire, py::arg("start"), py::arg("end"),
"Create a wire containing a single straight segment.");
m.def("make_polyline_rwire", &make_polyline_rwire, py::arg("points"), py::arg("closed") = false,
"Create a polyline wire from a point list.");
}
void bind_circles(py::module_& m) {
const auto profile = [](auto fn) {
return [fn](const Scalar3& center, const Scalar& radius, const Scalar3& normal, OptionalString tag_prefix,
OptionalString edge_tag) { return fn(center, radius, normal, ProfileTags{std::move(tag_prefix), std::move(edge_tag)}); };
};
m.def("make_circle_redge", &make_circle_redge, py::arg("center"), py::arg("radius"), py::arg("normal") = unit_z(),
py::kw_only(), py::arg("tag_prefix") = py::none(), "Create a circular edge.");
m.def("make_circle_rwire", profile(&make_circle_rwire), py::arg("center"), py::arg("radius"), py::arg("normal") = unit_z(),
py::kw_only(), py::arg("tag_prefix") = py::none(), py::arg("edge_tag") = py::none(), "Create a circular wire.");
m.def("make_circle_rface", profile(&make_circle_rface), py::arg("center"), py::arg("radius"), py::arg("normal") = unit_z(),
py::kw_only(), py::arg("tag_prefix") = py::none(), py::arg("edge_tag") = py::none(), "Create a circular face.");
m.def("make_ellipse_redge", &make_ellipse_redge, py::arg("center"), py::arg("major_radius"), py::arg("minor_radius"),
py::arg("normal") = unit_z(), py::kw_only(), py::arg("major_direction") = py::none(), py::arg("tag_prefix") = py::none(),
"Create a full ellipse edge.\n\n``major_direction`` orients the major axis in the ellipse plane; when\n"
"omitted the plane basis derived from ``normal`` picks it.");
const auto ellipse = [](auto fn) {
return [fn](const Scalar3& center, const Scalar& major, const Scalar& minor, const Scalar3& normal,
std::optional<Scalar3> major_direction, OptionalString tag_prefix, OptionalString edge_tag) {
return fn(center, major, minor, normal, EllipseOptions{std::move(major_direction), std::move(tag_prefix), std::move(edge_tag)});
};
};
m.def("make_ellipse_rwire", ellipse(&make_ellipse_rwire), py::arg("center"), py::arg("major_radius"), py::arg("minor_radius"),
py::arg("normal") = unit_z(), py::kw_only(), py::arg("major_direction") = py::none(), py::arg("tag_prefix") = py::none(),
py::arg("edge_tag") = py::none(), "Create an elliptical wire.");
m.def("make_ellipse_rface", ellipse(&make_ellipse_rface), py::arg("center"), py::arg("major_radius"), py::arg("minor_radius"),
py::arg("normal") = unit_z(), py::kw_only(), py::arg("major_direction") = py::none(), py::arg("tag_prefix") = py::none(),
py::arg("edge_tag") = py::none(), "Create an elliptical face.");
}
void bind_rectangles(py::module_& m) {
const auto rectangle = [](auto fn) {
return [fn](const Scalar& width, const Scalar& height, const Scalar3& center, const Scalar3& normal, OptionalString tag_prefix,
std::optional<std::vector<std::string>> edge_tags) {
return fn(width, height, center, normal, RectangleTags{std::move(tag_prefix), std::move(edge_tags)});
};
};
m.def("make_rectangle_rwire", rectangle(&make_rectangle_rwire), py::arg("width"), py::arg("height"), py::arg("center") = origin(),
py::arg("normal") = unit_z(), py::kw_only(), py::arg("tag_prefix") = py::none(), py::arg("edge_tags") = py::none(),
"Create a rectangular wire.");
m.def("make_rectangle_rface", rectangle(&make_rectangle_rface), py::arg("width"), py::arg("height"), py::arg("center") = origin(),
py::arg("normal") = unit_z(), py::kw_only(), py::arg("tag_prefix") = py::none(), py::arg("edge_tags") = py::none(),
"Create a rectangular face.");
}
void bind_arcs(py::module_& m) {
m.def("make_three_point_arc_redge", &make_three_point_arc_redge, py::arg("start"), py::arg("middle"), py::arg("end"),
"Create an arc edge from three points.");
m.def("make_three_point_arc_rwire", &make_three_point_arc_rwire, py::arg("start"), py::arg("middle"), py::arg("end"),
"Create a wire containing an arc defined by three points.");
m.def("make_angle_arc_redge", &make_angle_arc_redge, py::arg("center"), py::arg("radius"), py::arg("start_angle"),
py::arg("end_angle"), py::arg("normal") = unit_z(), "Create an arc edge from a center, radius, and angle range.");
m.def("make_angle_arc_rwire", &make_angle_arc_rwire, py::arg("center"), py::arg("radius"), py::arg("start_angle"),
py::arg("end_angle"), py::arg("normal") = unit_z(),
"Create a wire containing an arc defined by a center, radius, and angle range.");
}
void bind_splines(py::module_& m) {
const auto exact = [](auto fn) {
return [fn](std::vector<ScalarPoint> control_points, const py::object& degree, std::optional<ScalarList> knots,
std::optional<std::vector<int>> multiplicities, std::optional<ScalarList> weights, bool periodic) {
return fn(spline_spec(std::move(control_points), degree, std::move(knots), std::move(multiplicities), std::move(weights), periodic));
};
};
m.def("make_spline_redge", exact(&make_spline_redge), py::kw_only(), py::arg("control_points"), py::arg("degree") = 3,
py::arg("knots") = py::none(), py::arg("multiplicities") = py::none(), py::arg("weights") = py::none(),
py::arg("periodic") = false,
"Create an exact B-spline edge from named control-point parameters.\n\n"
"Pass sampled curve points through `fit_cubic_bspline_control_points(...)` first,\n"
"then pass the result fields explicitly as `control_points=...`, `knots=...`,\n"
"and `multiplicities=...`. `control_points` are poles, not interpolation\n"
"points; the curve generally does not pass through interior poles.");
m.def("make_spline_rwire", exact(&make_spline_rwire), py::kw_only(), py::arg("control_points"), py::arg("degree") = 3,
py::arg("knots") = py::none(), py::arg("multiplicities") = py::none(), py::arg("weights") = py::none(),
py::arg("periodic") = false, "Create a wire containing one exact B-spline edge.");
const auto interpolated = [](auto fn) {
return [fn](std::vector<ScalarPoint> points, bool periodic, const Scalar& tolerance) {
return fn(SplineInterpolation{std::move(points), periodic, tolerance});
};
};
m.def("make_interpolated_spline_redge", interpolated(&make_interpolated_spline_redge), py::kw_only(), py::arg("points"),
py::arg("periodic") = false, py::arg("tolerance") = 1.0e-6, "Interpolate an exact B-spline edge through the supplied points.");
m.def("make_interpolated_spline_rwire", interpolated(&make_interpolated_spline_rwire), py::kw_only(), py::arg("points"),
py::arg("periodic") = false, py::arg("tolerance") = 1.0e-6, "Create a one-edge wire that interpolates the supplied points.");
m.def("make_periodic_spline_rwire", &make_periodic_spline_rwire, py::kw_only(), py::arg("points"), py::arg("tolerance") = 1.0e-6,
"Create a closed periodic spline wire interpolating the supplied points.");
}
void bind_helix(py::module_& m) {
const auto helix = [](auto fn) {
return [fn](const Scalar& pitch, const Scalar& height, const Scalar& radius, const Scalar3& center, const Scalar3& dir,
const std::string& handedness) { return fn(pitch, height, radius, center, dir, handedness); };
};
m.def("make_helix_redge", helix(&make_helix_redge), py::arg("pitch"), py::arg("height"), py::arg("radius"),
py::arg("center") = origin(), py::arg("dir") = unit_z(), py::kw_only(), py::arg("handedness") = "Right",
"Create a helix edge, right- or left-handed.");
m.def("make_helix_rwire", helix(&make_helix_rwire), py::arg("pitch"), py::arg("height"), py::arg("radius"),
py::arg("center") = origin(), py::arg("dir") = unit_z(), py::kw_only(), py::arg("handedness") = "Right",
"Create a helix wire, right- or left-handed.");
}
void bind_wires_and_faces(py::module_& m) {
m.def("make_wire_from_edges_rwire", &make_wire_from_edges_rwire, py::arg("edges"), py::kw_only(),
py::arg("tag_prefix") = py::none(), "Create a wire from a list of connected edges.");
m.def("make_face_from_wire_rface", &make_face_from_wire_rface, py::arg("wire"), py::arg("normal") = unit_z(), py::kw_only(),
py::arg("tag_prefix") = py::none(), "Create a face from a closed wire.");
m.def("make_face_from_wires_rface",
[](const Shape& outer, const std::optional<std::vector<Shape>>& inner, const Scalar3& normal) {
return make_face_from_wires_rface(outer, inner.value_or(std::vector<Shape>{}), normal);
},
py::arg("outer_wire"), py::arg("inner_wires"), py::arg("normal") = unit_z(),
"Create a face from one outer closed wire and optional inner closed wires.");
}
void bind_primitives(py::module_& m) {
m.def("make_box_rsolid",
[](const Scalar& width, const Scalar& height, const Scalar& depth, const Scalar3& center, OptionalString tag_prefix,
OptionalString result_tag, OptionalString bottom, OptionalString top, OptionalString front, OptionalString back,
OptionalString left, OptionalString right) {
return make_box_rsolid(width, height, depth, center,
BoxTags{std::move(tag_prefix), std::move(result_tag), std::move(bottom), std::move(top),
std::move(front), std::move(back), std::move(left), std::move(right)});
},
py::arg("width"), py::arg("height"), py::arg("depth"), py::arg("bottom_face_center") = origin(), py::kw_only(),
py::arg("tag_prefix") = py::none(), py::arg("result_tag") = py::none(), py::arg("bottom_face_tag") = py::none(),
py::arg("top_face_tag") = py::none(), py::arg("front_face_tag") = py::none(), py::arg("back_face_tag") = py::none(),
py::arg("left_face_tag") = py::none(), py::arg("right_face_tag") = py::none(),
"Create a box with native kernel-backed Face topology tags.\n\n"
"The box extends ``depth`` along the current coordinate-system z_axis\n"
"starting at the bottom face; ``width`` spans the x_axis and ``height``\n"
"spans the y_axis.\n\n"
"Args:\n"
" width: Box size along the current coordinate-system x_axis.\n"
" height: Box size along the current coordinate-system y_axis.\n"
" depth: Box size along the current coordinate-system z_axis.\n"
" bottom_face_center: Geometric center of the box's bottom face in the\n"
" current coordinate system. The box is centered on this point\n"
" along x and y (it spans width/2 and height/2 to each side) and\n"
" extends the full ``depth`` upward along the z_axis from this\n"
" point's height. It is not a corner; to build a box\n"
" occupying x in [0, w], pass ``bottom_face_center=(w/2, h/2, z0)``.");
const auto axial_tags = [](OptionalString tag_prefix, OptionalString result_tag, OptionalString start_face, OptionalString end_face,
OptionalString side_face, OptionalString start_edge, OptionalString end_edge, OptionalString seam_edge) {
return AxialSolidTags{std::move(tag_prefix), std::move(result_tag), std::move(start_face), std::move(end_face),
std::move(side_face), std::move(start_edge), std::move(end_edge), std::move(seam_edge)};
};
m.def("make_cylinder_rsolid",
[axial_tags](const Scalar& radius, const Scalar& height, const Scalar3& center, const Scalar3& axis, OptionalString tag_prefix,
OptionalString result_tag, OptionalString start_face, OptionalString end_face, OptionalString side_face,
OptionalString start_edge, OptionalString end_edge, OptionalString seam_edge) {
return make_cylinder_rsolid(radius, height, center, axis,
axial_tags(std::move(tag_prefix), std::move(result_tag), std::move(start_face), std::move(end_face),
std::move(side_face), std::move(start_edge), std::move(end_edge), std::move(seam_edge)));
},
py::arg("radius"), py::arg("height"), py::arg("bottom_face_center") = origin(), py::arg("axis") = unit_z(), py::kw_only(),
py::arg("tag_prefix") = py::none(), py::arg("result_tag") = py::none(), py::arg("start_face_tag") = py::none(),
py::arg("end_face_tag") = py::none(), py::arg("side_face_tag") = py::none(), py::arg("start_edge_tag") = py::none(),
py::arg("end_edge_tag") = py::none(), py::arg("seam_edge_tag") = py::none(),
"Create a cylinder with native kernel-backed Face and Edge topology tags.\n\n"
"The cylinder extends ``height`` along ``axis`` from the bottom face.\n\n"
"Args:\n"
" radius: Cylinder radius.\n"
" height: Cylinder length along ``axis``.\n"
" bottom_face_center: Geometric center of the cylinder's bottom\n"
" (start) face in the current coordinate system; the solid extends\n"
" the full ``height`` along ``axis`` from this point.\n"
" axis: Direction of the cylinder axis in the current coordinate\n"
" system.");
m.def("make_cone_rsolid",
[axial_tags](const Scalar& bottom_radius, const Scalar& height, const Scalar& top_radius, const Scalar3& center,
const Scalar3& axis, OptionalString tag_prefix, OptionalString result_tag, OptionalString start_face,
OptionalString end_face, OptionalString side_face, OptionalString start_edge, OptionalString end_edge,
OptionalString seam_edge) {
return make_cone_rsolid(bottom_radius, height, top_radius, center, axis,
axial_tags(std::move(tag_prefix), std::move(result_tag), std::move(start_face), std::move(end_face),
std::move(side_face), std::move(start_edge), std::move(end_edge), std::move(seam_edge)));
},
py::arg("bottom_radius"), py::arg("height"), py::arg("top_radius") = 0.0, py::arg("bottom_face_center") = origin(),
py::arg("axis") = unit_z(), py::kw_only(), py::arg("tag_prefix") = py::none(), py::arg("result_tag") = py::none(),
py::arg("start_face_tag") = py::none(), py::arg("end_face_tag") = py::none(), py::arg("side_face_tag") = py::none(),
py::arg("start_edge_tag") = py::none(), py::arg("end_edge_tag") = py::none(), py::arg("seam_edge_tag") = py::none(),
"Create a cone or frustum with native kernel-backed topology tags.\n\n"
"The solid extends ``height`` along ``axis`` from the bottom face,\n"
"tapering from ``bottom_radius`` to ``top_radius`` (a cone when\n"
"``top_radius`` is 0).\n\n"
"Args:\n"
" bottom_radius: Radius of the bottom (start) face.\n"
" height: Frustum length along ``axis``.\n"
" top_radius: Radius of the top face; 0 produces a cone.\n"
" bottom_face_center: Geometric center of the bottom (start) face in\n"
" the current coordinate system; the solid extends the full\n"
" ``height`` along ``axis`` from this point.\n"
" axis: Direction of the frustum axis in the current coordinate\n"
" system.");
m.def("make_sphere_rsolid", &make_sphere_rsolid, py::arg("radius"), py::arg("center") = origin(), "Create a sphere solid.");
}
void bind_brep_region(py::module_& m) {
m.def("load_brep_region_rsolid",
[](const py::object& path, const std::string& sha256, const OptionalString& tag_prefix) {
return load_brep_region_rsolid(path_text(path), sha256, tag_prefix);
},
py::arg("path"), py::arg("sha256"), py::kw_only(), py::arg("tag_prefix") = py::none(),
"Load a hash-pinned, target-derived BREP region snapshot as one Solid.\n\n"
"The complete artifact SHA-256 is verified before native BREP decoding. In a\n"
"GraphSession, ``path`` must be relative and is replayed relative to the replay\n"
"process working directory. Model JSON records the locator and digest, not the\n"
"sidecar bytes.");
m.def("_brep_region_path",
[](const py::object& path, bool for_graph) { return scad::io::checked_region_path(path_text(path), for_graph); },
py::arg("path"), py::kw_only(), py::arg("for_graph"),
"The checks on a .scadbrep locator (graph replay: relative, no drive, no '..', '/' separators).");
m.def("load_brep_region_rshell",
[](const py::object& path, const std::string& sha256, const OptionalString& tag_prefix) {
return load_brep_region_rshell(path_text(path), sha256, tag_prefix);
},
py::arg("path"), py::arg("sha256"), py::kw_only(), py::arg("tag_prefix") = py::none(),
"Load a hash-pinned, target-derived BREP face region as one Shell.\n\n"
"The Shell keeps target-derived topology and is tagged with imported-sidecar\n"
"provenance. Use ordinary replayable surface operations to join it to fitted\n"
"or analytic feature faces. GraphSession requires a relative sidecar path.");
}
// The names `simplecadapi/__init__.py` exports for these operators.
void bind_aliases(py::module_& m) {
static constexpr std::pair<const char*, const char*> kAliases[] = {
{"create_angle_arc", "make_angle_arc_redge"},
{"create_angle_arc_wire", "make_angle_arc_rwire"},
{"create_arc", "make_three_point_arc_redge"},
{"create_arc_wire", "make_three_point_arc_rwire"},
{"create_box", "make_box_rsolid"},
{"create_circle_edge", "make_circle_redge"},
{"create_circle_face", "make_circle_rface"},
{"create_circle_wire", "make_circle_rwire"},
{"create_cylinder", "make_cylinder_rsolid"},
{"create_face_from_wire", "make_face_from_wire_rface"},
{"create_face_from_wires", "make_face_from_wires_rface"},
{"create_helix", "make_helix_redge"},
{"create_helix_wire", "make_helix_rwire"},
{"create_interpolated_spline", "make_interpolated_spline_redge"},
{"create_interpolated_spline_wire", "make_interpolated_spline_rwire"},
{"create_line", "make_line_redge"},
{"create_periodic_spline_wire", "make_periodic_spline_rwire"},
{"create_point", "make_point_rvertex"},
{"create_polyline_wire", "make_polyline_rwire"},
{"create_rectangle_face", "make_rectangle_rface"},
{"create_rectangle_wire", "make_rectangle_rwire"},
{"create_segment", "make_segment_redge"},
{"create_segment_wire", "make_segment_rwire"},
{"create_sphere", "make_sphere_rsolid"},
{"create_spline", "make_spline_redge"},
{"create_spline_wire", "make_spline_rwire"},
{"create_wire_from_edges", "make_wire_from_edges_rwire"},
};
for (const auto& [alias, name] : kAliases) m.attr(alias) = m.attr(name);
}
// Measurements the parity tests compare with the reference SDK (which reads them off OCP).
void bind_testing(py::module_& m) {
py::module_ t = m.def_submodule("_geometry_testing", "measurements for the geometry parity tests");
t.def("bbox", [](const Shape& shape) {
const auto b = shape.bounding_box();
return std::array<double, 6>{b.xmin, b.ymin, b.zmin, b.xmax, b.ymax, b.zmax};
});
// `count` points along an edge, evenly in parameter, for checking the winding of a curve.
t.def("sample", [](const Edge& edge, int count) {
BRepAdaptor_Curve curve(TopoDS::Edge(edge.wrapped()));
std::vector<std::array<double, 3>> points;
for (int i = 0; i <= count; ++i) {
const gp_Pnt p = curve.Value(curve.FirstParameter() + (curve.LastParameter() - curve.FirstParameter()) * i / count);
points.push_back({p.X(), p.Y(), p.Z()});
}
return points;
});
// Distinct faces / edges / vertices of the shape (TopExp::MapShapes).
t.def("counts", [](const Shape& shape) {
const auto count = [&](TopAbs_ShapeEnum kind) {
TopTools_IndexedMapOfShape map;
TopExp::MapShapes(shape.wrapped(), kind, map);
return map.Extent();
};
return py::dict("faces"_a = count(TopAbs_FACE), "edges"_a = count(TopAbs_EDGE), "vertices"_a = count(TopAbs_VERTEX));
});
}
} // namespace
void bind_ops_geometry(py::module_& m) {
bind_lines(m);
bind_circles(m);
bind_rectangles(m);
bind_arcs(m);
bind_splines(m);
bind_helix(m);
bind_wires_and_faces(m);
bind_primitives(m);
bind_brep_region(m);
bind_aliases(m);
bind_testing(m);
scad::register_geometry_executors(scad::reactive::ExecutorRegistry::global());
}
+323
View File
@@ -0,0 +1,323 @@
// Python bindings for the "product" area: the 28 operators of simplecadapi/operators/product.py
// under their Python names, argument names and defaults. The value classes are bound in
// bind_product_values.cpp.
//
// Every operator takes py::object for the arguments whose type Python checks inside its wrapped
// body, and converts them inside guard_operation, so a wrong type is the operation's
// SimpleCADError exactly as in Python (see bind_product_args.hpp).
#include "bind_product_args.hpp"
#include "scad/reactive/registry.hpp"
namespace {
using namespace scad;
using namespace scad::product_binding;
using sp::guard_operation;
const sp::Assembly& assembly_arg(const py::object& value) { return typed<sp::Assembly>(value, "assembly must be an Assembly"); }
const sp::Placement& placement_arg(const py::object& value) { return typed<sp::Placement>(value, "placement must be a Placement"); }
const sp::Part& part_arg(const py::object& value) { return typed<sp::Part>(value, "part must be a Part"); }
sp::AssemblyPtr assembly_ptr_arg(const py::object& value) {
if (!py::isinstance<sp::Assembly>(value)) throw TypeError("assembly must be an Assembly");
return value.cast<sp::AssemblyPtr>();
}
// The assembly of an add_*_constraint operator: its type is checked by the guarded wrapper in
// Python, after the Constraint has been built.
const sp::Assembly& constraint_assembly(const char* operation, const py::object& value) {
if (!py::isinstance<sp::Assembly>(value)) {
guard_operation(operation, [&]() -> int { throw TypeError("assembly must be an Assembly"); });
}
return value.cast<const sp::Assembly&>();
}
Scalar3 point_arg(const py::object& value, const char* field) {
return converted<Scalar3>(value, (std::string(field) + " must be a 3-element tuple of numbers").c_str());
}
void bind_structure(py::module_& m) {
m.def("make_material_rmaterial",
[](const py::object& material_id, const py::object& name, const py::object& density, const py::object& density_unit,
const py::object& color) {
return guard_operation("make_material_rmaterial", [&] {
sp::OptionalString unit;
if (!density_unit.is_none()) unit = py::isinstance<py::str>(density_unit) ? density_unit.cast<std::string>() : std::string();
return sp::make_material_rmaterial(text(material_id, "material_id"), optional_name(name),
optional_scalar(density, "density"), unit, optional_vec3(color, "color"));
});
},
py::arg("material_id"), py::arg("name") = py::none(), py::arg("density") = py::none(),
py::arg("density_unit") = py::none(), py::arg("color") = py::none(),
"Create a material definition for later Part assignment.\n\n"
"Material is deliberately separate from `make_part_rpart(...)`; the only\n"
"correct workflow is to create a material and then assign it to a Part with\n"
"`assign_material_rpart(...)`.");
m.def("make_placement_rplacement",
[](const py::object& origin, const py::object& x_axis, const py::object& y_axis) {
return guard_operation("make_placement_rplacement", [&] {
return sp::make_placement_rplacement(point_arg(origin, "origin"), point_arg(x_axis, "x_axis"), point_arg(y_axis, "y_axis"));
});
},
py::arg("origin"), py::arg("x_axis") = py::make_tuple(1.0, 0.0, 0.0), py::arg("y_axis") = py::make_tuple(0.0, 1.0, 0.0),
"Create a canonical right-handed placement in the active workplane.");
m.def("identity_placement_rplacement", &sp::identity_placement_rplacement,
"Create the identity placement of the active workplane.");
m.def("make_part_rpart",
[](const py::object& part_id, const py::object& body, const py::object& name) {
return guard_operation("make_part_rpart", [&] {
return sp::make_part_rpart(text(part_id, "part_id"), typed<Solid>(body, "body must be a Solid"), optional_name(name));
});
},
py::arg("part_id"), py::arg("body"), py::arg("name") = py::none(), "Wrap exactly one Solid as a semantic single-body Part.");
m.def("assign_material_rpart",
[](const py::object& part, const py::object& material) {
return guard_operation("assign_material_rpart", [&] {
return sp::assign_material_rpart(part_arg(part), typed<sp::Material>(material, "material must be a Material"));
});
},
py::arg("part"), py::arg("material"), "Assign a Material to a Part and return the updated Part.");
m.def("make_assembly_rassembly",
[](const py::object& assembly_id, const py::object& name) {
return guard_operation("make_assembly_rassembly", [&] {
return sp::make_assembly_rassembly(text(assembly_id, "assembly_id"), optional_name(name));
});
},
py::arg("assembly_id"), py::arg("name") = py::none(), "Create an empty assembly product structure.");
m.def("add_component_rassembly",
[](const py::object& assembly, const py::object& item, const py::object& component_id, const py::object& placement,
const py::object& name) {
return guard_operation("add_component_rassembly", [&] {
const sp::Assembly& target = assembly_arg(assembly);
const sp::Item chosen = item_of(item);
return sp::add_component_rassembly(target, chosen, text(component_id, "component_id"), placement_arg(placement),
optional_name(name));
});
},
py::arg("assembly"), py::arg("item"), py::arg("component_id"), py::arg("placement"), py::arg("name") = py::none(),
"Add a placed Part or subassembly component instance to an Assembly.");
m.def("place_component_rassembly",
[](const py::object& assembly, const py::object& component_id, const py::object& placement) {
return guard_operation("place_component_rassembly", [&] {
const sp::Assembly& target = assembly_arg(assembly);
return sp::place_component_rassembly(target, text(component_id, "component_id"), placement_arg(placement));
});
},
py::arg("assembly"), py::arg("component_id"), py::arg("placement"), "Move an existing assembly component by replacing its placement.");
}
void bind_connectors(py::module_& m) {
m.def("make_face_connector_rconnector",
[](const py::object& connector_id, const py::object& face, const py::object& name, const py::object& flip) {
return guard_operation("make_face_connector_rconnector", [&] {
const Face& target = typed<Face>(face, "face must be a Face");
return sp::make_face_connector_rconnector(text(connector_id, "connector_id"), target, optional_name(name), truthy(flip));
});
},
py::arg("connector_id"), py::arg("face"), py::arg("name") = py::none(), py::arg("flip") = false,
"Create a connector anchored to a Face.\n\nZ axis follows the face normal; origin is the face center.\n"
"Set flip=True to negate the Z axis (point it opposite to the normal).");
m.def("make_edge_connector_rconnector",
[](const py::object& connector_id, const py::object& edge, const py::object& name, const py::object& flip) {
return guard_operation("make_edge_connector_rconnector", [&] {
const Edge& target = typed<Edge>(edge, "edge must be an Edge");
return sp::make_edge_connector_rconnector(text(connector_id, "connector_id"), target, optional_name(name), truthy(flip));
});
},
py::arg("connector_id"), py::arg("edge"), py::arg("name") = py::none(), py::arg("flip") = false,
"Create a connector anchored to an Edge.\n\nZ axis follows the edge direction (start->end); origin is the edge midpoint.\n"
"Set flip=True to negate the Z axis.");
m.def("make_vertex_connector_rconnector",
[](const py::object& connector_id, const py::object& vertex, const py::object& name, const py::object& flip) {
return guard_operation("make_vertex_connector_rconnector", [&] {
const Vertex& target = typed<Vertex>(vertex, "vertex must be a Vertex");
return sp::make_vertex_connector_rconnector(text(connector_id, "connector_id"), target, optional_name(name), truthy(flip));
});
},
py::arg("connector_id"), py::arg("vertex"), py::arg("name") = py::none(), py::arg("flip") = false,
"Create a connector anchored to a Vertex.\n\nOrigin is the vertex point; axes are identity.\n"
"flip has no effect on vertex connectors (no direction).");
m.def("make_placement_connector_rconnector",
[](const py::object& connector_id, const py::object& placement, const py::object& name) {
return guard_operation("make_placement_connector_rconnector", [&] {
const sp::Placement& frame = placement_arg(placement);
return sp::make_placement_connector_rconnector(text(connector_id, "connector_id"), frame, optional_name(name));
});
},
py::arg("connector_id"), py::arg("placement"), py::arg("name") = py::none(),
"Create a connector anchored to an explicit local placement frame.");
m.def("add_connector_rpart",
[](const py::object& part, const py::object& connector) {
return guard_operation("add_connector_rpart", [&] {
const sp::Part& target = part_arg(part);
return sp::add_connector_rpart(target, typed<sp::Connector>(connector, "connector must be a Connector"));
});
},
py::arg("part"), py::arg("connector"), "Attach a connector datum frame to a Part definition.");
m.def("set_public_connector_rassembly",
[](const py::object& assembly, const py::object& public_id, const py::object& component_id, const py::object& connector_id,
const py::object& name) {
return guard_operation("set_public_connector_rassembly", [&] {
const sp::Assembly& target = assembly_arg(assembly);
return sp::set_public_connector_rassembly(target, text(public_id, "public_connector_id"), text(component_id, "component_id"),
text(connector_id, "connector_id"), optional_name(name));
});
},
py::arg("assembly"), py::arg("public_connector_id"), py::arg("source_component_id"), py::arg("source_connector_id"),
py::arg("name") = py::none(), "Expose an existing connector on a direct child component.");
m.def("make_connector_ref_rconnectorref",
[](const py::object& component_id, const py::object& connector_id) {
return guard_operation("make_connector_ref_rconnectorref", [&] {
return sp::make_connector_ref_rconnectorref(text(component_id, "component_id"), text(connector_id, "connector_id"));
});
},
py::arg("component_id"), py::arg("connector_id"), "Reference a connector through a component instance.");
m.def("make_scalar_limit_rscalarlimit",
[](const py::object& lower_value, const py::object& upper_value) {
return guard_operation("make_scalar_limit_rscalarlimit", [&] {
return sp::make_scalar_limit_rscalarlimit(scalar(lower_value, "lower_value"), scalar(upper_value, "upper_value"));
});
},
py::arg("lower_value"), py::arg("upper_value"), "Create a closed scalar limit for driven constraint coordinates.");
}
// The constraint operators convert their arguments outside guard_operation: Python builds the
// Constraint before the guarded part, so those errors are not wrapped.
void bind_constraints(py::module_& m) {
m.def("ground_component_rassembly",
[](const py::object& assembly, const py::object& component_id) {
return guard_operation("ground_component_rassembly", [&] {
const sp::Assembly& target = assembly_arg(assembly);
return sp::ground_component_rassembly(target, text(component_id, "component_id"));
});
},
py::arg("assembly"), py::arg("component_id"), "Ground a component at its current authored placement.");
m.def("unground_component_rassembly",
[](const py::object& assembly, const py::object& component_id) {
return guard_operation("unground_component_rassembly", [&] {
const sp::Assembly& target = assembly_arg(assembly);
return sp::unground_component_rassembly(target, text(component_id, "component_id"));
});
},
py::arg("assembly"), py::arg("component_id"), "Remove a component grounding marker.");
const auto ref = [](const py::object& value, const char* field) -> const sp::ConnectorRef& {
return typed<sp::ConnectorRef>(value, (std::string(field) + " must be a ConnectorRef").c_str());
};
const auto limit = [](const py::object& value, const char* message) -> sp::OptionalLimit {
if (value.is_none()) return std::nullopt;
return typed<sp::ScalarLimit>(value, message);
};
m.def("add_fixed_constraint_rassembly",
[ref](const py::object& assembly, const py::object& constraint_id, const py::object& a, const py::object& b, const py::object& name) {
return sp::add_fixed_constraint_rassembly(constraint_assembly("add_fixed_constraint_rassembly", assembly),
text(constraint_id, "constraint_id"), ref(a, "connector_a"),
ref(b, "connector_b"), optional_name(name));
},
py::arg("assembly"), py::arg("constraint_id"), py::arg("connector_a"), py::arg("connector_b"), py::arg("name") = py::none(),
"Constrain two component connectors to the same frame.");
m.def("add_revolute_constraint_rassembly",
[ref, limit](const py::object& assembly, const py::object& constraint_id, const py::object& a, const py::object& b,
const py::object& drive_angle_degrees, const py::object& angle_limit, const py::object& name) {
return sp::add_revolute_constraint_rassembly(
constraint_assembly("add_revolute_constraint_rassembly", assembly), text(constraint_id, "constraint_id"),
ref(a, "connector_a"), ref(b, "connector_b"), optional_scalar(drive_angle_degrees, "drive_angle_degrees"),
limit(angle_limit, "angle_limit must be a ScalarLimit"), optional_name(name));
},
py::arg("assembly"), py::arg("constraint_id"), py::arg("connector_a"), py::arg("connector_b"),
py::arg("drive_angle_degrees") = py::none(), py::arg("angle_limit") = py::none(), py::arg("name") = py::none(),
"Constrain two connectors as a revolute axis pair.");
m.def("add_prismatic_constraint_rassembly",
[ref, limit](const py::object& assembly, const py::object& constraint_id, const py::object& a, const py::object& b,
const py::object& drive_distance, const py::object& distance_limit, const py::object& name) {
return sp::add_prismatic_constraint_rassembly(
constraint_assembly("add_prismatic_constraint_rassembly", assembly), text(constraint_id, "constraint_id"),
ref(a, "connector_a"), ref(b, "connector_b"), optional_scalar(drive_distance, "drive_distance"),
limit(distance_limit, "distance_limit must be a ScalarLimit"), optional_name(name));
},
py::arg("assembly"), py::arg("constraint_id"), py::arg("connector_a"), py::arg("connector_b"),
py::arg("drive_distance") = py::none(), py::arg("distance_limit") = py::none(), py::arg("name") = py::none(),
"Constrain two connectors as a prismatic slider pair.");
m.def("add_gear_constraint_rassembly",
[ref](const py::object& assembly, const py::object& constraint_id, const py::object& a, const py::object& b,
const py::object& pitch_radius_a, const py::object& pitch_radius_b, const py::object& phase_offset, const py::object& name) {
return sp::add_gear_constraint_rassembly(constraint_assembly("add_gear_constraint_rassembly", assembly),
text(constraint_id, "constraint_id"), ref(a, "connector_a"), ref(b, "connector_b"),
scalar(pitch_radius_a, "pitch_radius_a"), scalar(pitch_radius_b, "pitch_radius_b"),
optional_scalar(phase_offset, "phase_offset"), optional_name(name));
},
py::arg("assembly"), py::arg("constraint_id"), py::arg("connector_a"), py::arg("connector_b"), py::arg("pitch_radius_a"),
py::arg("pitch_radius_b"), py::arg("phase_offset") = py::none(), py::arg("name") = py::none(),
"Couple two revolute axes as meshing gears with inverse rotation.");
m.def("add_belt_constraint_rassembly",
[ref](const py::object& assembly, const py::object& constraint_id, const py::object& a, const py::object& b,
const py::object& pulley_radius_a, const py::object& pulley_radius_b, const py::object& phase_offset, const py::object& name) {
return sp::add_belt_constraint_rassembly(constraint_assembly("add_belt_constraint_rassembly", assembly),
text(constraint_id, "constraint_id"), ref(a, "connector_a"), ref(b, "connector_b"),
scalar(pulley_radius_a, "pulley_radius_a"), scalar(pulley_radius_b, "pulley_radius_b"),
optional_scalar(phase_offset, "phase_offset"), optional_name(name));
},
py::arg("assembly"), py::arg("constraint_id"), py::arg("connector_a"), py::arg("connector_b"), py::arg("pulley_radius_a"),
py::arg("pulley_radius_b"), py::arg("phase_offset") = py::none(), py::arg("name") = py::none(),
"Couple two revolute axes as belt-linked pulleys with same-direction rotation.");
m.def("add_rack_pinion_constraint_rassembly",
[ref](const py::object& assembly, const py::object& constraint_id, const py::object& rack, const py::object& pinion,
const py::object& pitch_radius, const py::object& phase_offset, const py::object& name) {
return sp::add_rack_pinion_constraint_rassembly(
constraint_assembly("add_rack_pinion_constraint_rassembly", assembly), text(constraint_id, "constraint_id"),
ref(rack, "connector_a"), ref(pinion, "connector_b"), scalar(pitch_radius, "pitch_radius"),
optional_scalar(phase_offset, "phase_offset"), optional_name(name));
},
py::arg("assembly"), py::arg("constraint_id"), py::arg("rack_connector"), py::arg("pinion_connector"), py::arg("pitch_radius"),
py::arg("phase_offset") = py::none(), py::arg("name") = py::none(), "Couple a prismatic rack axis to a revolute pinion axis.");
}
void bind_solving(py::module_& m) {
m.def("solve_assembly_constraints_rassembly",
[](const py::object& assembly, const py::object& strict) {
return guard_operation("solve_assembly_constraints_rassembly", [&] {
return sp::solve_assembly_constraints_rassembly(assembly_ptr_arg(assembly), truthy(strict));
});
},
py::arg("assembly"), py::arg("strict") = true,
"Solve fixed, revolute, and prismatic assembly constraints.\n\n"
"Solving is limit-aware: when a constraint carries a ``ScalarLimit``\n"
"(``angle_limit`` or ``distance_limit``), the drive scalar is clamped\n"
"into the closed range before placement propagation. When no drive\n"
"scalar is present but a limit exists, the current relative-frame\n"
"scalar is projected into the bounds. Unresolvable closed kinematic\n"
"loops fall back to a golden-section search over the limit bounds.\n\n"
"A ``ConstraintReport`` is recorded on the returned assembly under the\n"
"``constraint_report`` runtime key for later inspection via\n"
"``inspect_assembly_constraints_rassembly``.");
m.def("measure_constraint_residual_rconstraintresidual",
[](const py::object& assembly, const py::object& constraint_id) {
return sp::measure_constraint_residual_rconstraintresidual(assembly_arg(assembly), text(constraint_id, "constraint_id"));
},
py::arg("assembly"), py::arg("constraint_id"), "Measure residual for one assembly constraint without mutating the assembly.");
m.def("inspect_assembly_constraints_rconstraintreport",
[](const py::object& assembly) { return sp::inspect_assembly_constraints_rconstraintreport(assembly_arg(assembly)); },
py::arg("assembly"), "Inspect all assembly constraint residuals without mutating the assembly.");
m.def("make_compound_from_assembly_rcompound",
[](const py::object& assembly) {
return guard_operation("make_compound_from_assembly_rcompound", [&] {
return sp::make_compound_from_assembly_rcompound(assembly_arg(assembly));
});
},
py::arg("assembly"), "Project an Assembly into an explicit flattened Compound geometry value.");
}
} // namespace
void bind_product(py::module_& m) {
bind_product_values(m);
bind_structure(m);
bind_connectors(m);
bind_constraints(m);
bind_solving(m);
scad::product::register_product_executors(scad::reactive::ExecutorRegistry::global());
}
@@ -0,0 +1,113 @@
// Argument conversion for the product bindings.
//
// The Python operators check their argument types inside the wrapped body, so a wrong type
// is the operation's SimpleCADError (technical details "TypeError: part must be a Part"), not
// a pybind11 overload error. The bindings therefore take py::object for every argument whose
// type is checked, and convert it here, inside scad::product::guard_operation.
#pragma once
#include <optional>
#include <string>
#include "bindings.hpp"
#include "scad/core/error.hpp"
#include "scad/product/product.hpp"
namespace scad::product_binding {
namespace sp = scad::product;
// `value` as a T, or a TypeError(message).
template <class T>
const T& typed(const py::object& value, const char* message) {
if (!py::isinstance<T>(value)) throw scad::TypeError(message);
return value.cast<const T&>();
}
template <class T>
T converted(const py::object& value, const char* message) {
try {
return value.cast<T>();
} catch (const py::cast_error&) {
throw scad::TypeError(message);
}
}
inline bool is_none(const py::object& value) { return value.is_none(); }
// str arguments: Python raises TypeError("<field> must be a string") for anything else.
inline std::string text(const py::object& value, const char* field) {
if (!py::isinstance<py::str>(value)) throw scad::TypeError(std::string(field) + " must be a string");
return value.cast<std::string>();
}
// A display name: None, or anything str() accepts.
inline sp::OptionalString optional_name(const py::object& value) {
if (value.is_none()) return std::nullopt;
return py::str(value).cast<std::string>();
}
inline scad::Scalar scalar(const py::object& value, const char* field) {
try {
return value.cast<scad::Scalar>();
} catch (const py::cast_error&) {
throw scad::TypeError(std::string(field) + " must be numeric");
}
}
inline std::optional<scad::Scalar> optional_scalar(const py::object& value, const char* field) {
if (value.is_none()) return std::nullopt;
return scalar(value, field);
}
inline double number(const py::object& value, const char* field) {
return scalar(value, field).value();
}
// Three numbers from a list or tuple.
inline Vec3 vec3(const py::object& value, const char* field) {
if (!py::isinstance<py::list>(value) && !py::isinstance<py::tuple>(value)) {
throw scad::ValueError(std::string(field) + " must be a 3-element tuple or list");
}
const py::sequence seq = py::reinterpret_borrow<py::sequence>(value);
if (seq.size() != 3) throw scad::ValueError(std::string(field) + " must be a 3-element tuple or list");
double v[3];
for (std::size_t i = 0; i < 3; ++i) {
try {
v[i] = seq[i].cast<double>();
} catch (const py::cast_error&) {
throw scad::TypeError(std::string(field) + "[" + std::to_string(i) + "] must be numeric");
}
}
return {v[0], v[1], v[2]};
}
inline std::optional<Vec3> optional_vec3(const py::object& value, const char* field) {
if (value.is_none()) return std::nullopt;
return vec3(value, field);
}
inline bool truthy(const py::object& value) { return PyObject_IsTrue(value.ptr()) == 1; }
// `item` of add_component_rassembly.
inline sp::Item item_of(const py::object& value) {
if (py::isinstance<sp::Part>(value)) return sp::Item{value.cast<sp::PartPtr>()};
if (py::isinstance<sp::Assembly>(value)) return sp::Item{value.cast<sp::AssemblyPtr>()};
throw scad::TypeError("item must be a Part or Assembly");
}
inline py::object py_item(const sp::Item& item) {
if (const auto* part = std::get_if<sp::PartPtr>(&item)) return py::cast(*part);
return py::cast(std::get<sp::AssemblyPtr>(item));
}
template <class T>
py::tuple to_tuple(const std::vector<T>& items) {
py::tuple out(items.size());
for (std::size_t i = 0; i < items.size(); ++i) out[i] = py::cast(items[i]);
return out;
}
} // namespace scad::product_binding
void bind_product_values(py::module_& m);
@@ -0,0 +1,449 @@
// The product value classes, under the names and attributes simplecadapi exports:
// Placement, Material, Part, Assembly, Component, PublicConnectorRef, Connector, ConnectorAnchor,
// ConnectorRef, GeometryRef, Constraint, ConstraintReport, ConstraintResidual, ScalarLimit.
#include "bind_product_args.hpp"
namespace {
using namespace scad;
using namespace scad::product_binding;
using namespace pybind11::literals;
// Python's repr(float).
std::string float_repr(double value) { return py::repr(py::float_(value)).cast<std::string>(); }
std::string str_repr(const std::string& value) { return py::repr(py::str(value)).cast<std::string>(); }
std::string opt_str_repr(const sp::OptionalString& value) { return value ? str_repr(*value) : "None"; }
std::string opt_float_repr(const sp::OptionalDouble& value) { return value ? float_repr(*value) : "None"; }
std::string tuple_repr(const Vec3& v) {
return "(" + float_repr(v.x) + ", " + float_repr(v.y) + ", " + float_repr(v.z) + ")";
}
py::object optional_object(const sp::OptionalString& value) { return value ? py::object(py::str(*value)) : py::none(); }
py::object optional_float(const sp::OptionalDouble& value) { return value ? py::object(py::float_(*value)) : py::none(); }
// The SemanticValueMixin methods.
template <class T, class Cls>
void bind_semantic_value(Cls& cls) {
cls.def("set_metadata", [](const T& self, const std::string& key, const Value& value) { self.set_metadata(key, value); })
.def("get_metadata", [](const T& self, const std::string& key, const Value& fallback) { return self.get_metadata(key, fallback); },
py::arg("key"), py::arg("default") = Value())
.def("_set_runtime", [](const T& self, const std::string& key, const Value& value) { self.set_runtime(key, value); })
.def("_get_runtime", [](const T& self, const std::string& key, const Value& fallback) { return self.get_runtime(key, fallback); },
py::arg("key"), py::arg("default") = Value());
}
template <class T>
py::int_ hash_of(const T& self, const std::string& text) {
(void)self;
return py::int_(py::hash(py::str(text)));
}
void bind_placement(py::module_& m) {
using sp::Placement;
py::class_<Placement, py::smart_holder> cls(m, "Placement", "Right-handed placement mapping child-local coordinates to parent coordinates.");
cls.def(py::init([](const py::object& origin, const py::object& x_axis, const py::object& y_axis, const py::object&) {
return Placement(vec3(origin, "origin"), vec3(x_axis, "x_axis"), vec3(y_axis, "y_axis"));
}),
py::arg("origin"), py::arg("x_axis") = py::make_tuple(1.0, 0.0, 0.0), py::arg("y_axis") = py::make_tuple(0.0, 1.0, 0.0),
py::arg("z_axis") = py::make_tuple(0.0, 0.0, 1.0))
.def_property_readonly("origin", &Placement::origin)
.def_property_readonly("x_axis", &Placement::x_axis)
.def_property_readonly("y_axis", &Placement::y_axis)
.def_property_readonly("z_axis", &Placement::z_axis)
.def("transform_point", [](const Placement& self, const py::object& point) { return self.transform_point(vec3(point, "point")); },
py::arg("point"))
.def("transform_vector", [](const Placement& self, const py::object& vector) { return self.transform_vector(vec3(vector, "vector")); },
py::arg("vector"))
.def("compose", [](const Placement& self, const py::object& child) {
return self.compose(typed<Placement>(child, "child must be a Placement"));
}, py::arg("child"))
.def_static("from_exact_frame", [](const py::object& o, const py::object& x, const py::object& y, const py::object& z) {
return Placement::from_exact_frame(vec3(o, "origin"), vec3(x, "x_axis"), vec3(y, "y_axis"), vec3(z, "z_axis"));
}, py::arg("origin"), py::arg("x_axis"), py::arg("y_axis"), py::arg("z_axis"))
.def("to_dict", [](const Placement& self) { return self.to_dict(); })
.def("__eq__", [](const Placement& a, const py::object& b) { return py::isinstance<Placement>(b) && a == b.cast<const Placement&>(); },
py::is_operator())
.def("__hash__", [](const Placement& self) {
return hash_of(self, tuple_repr(self.origin()) + tuple_repr(self.x_axis()) + tuple_repr(self.y_axis()));
})
.def("__repr__", [](const Placement& self) {
return "Placement(origin=" + tuple_repr(self.origin()) + ", x_axis=" + tuple_repr(self.x_axis()) +
", y_axis=" + tuple_repr(self.y_axis()) + ", z_axis=" + tuple_repr(self.z_axis()) + ")";
});
bind_semantic_value<Placement>(cls);
}
void bind_material(py::module_& m) {
using sp::Material;
py::class_<Material, py::smart_holder> cls(m, "Material", "Material definition assigned to a Part through `assign_material_rpart`.");
cls.def(py::init([](const py::object& material_id, const py::object& name, const py::object& density,
const py::object& density_unit, const py::object& color) {
sp::OptionalString unit;
if (!density_unit.is_none()) unit = py::isinstance<py::str>(density_unit) ? density_unit.cast<std::string>() : std::string();
std::optional<double> density_value;
if (!density.is_none()) density_value = number(density, "density");
return Material(text(material_id, "material_id"), optional_name(name), density_value, unit,
optional_vec3(color, "color"));
}),
py::arg("material_id"), py::arg("name") = py::none(), py::arg("density") = py::none(),
py::arg("density_unit") = py::none(), py::arg("color") = py::none())
.def_property_readonly("material_id", &Material::material_id)
.def_property_readonly("name", [](const Material& self) { return optional_object(self.name()); })
.def_property_readonly("density", [](const Material& self) { return optional_float(self.density()); })
.def_property_readonly("density_unit", [](const Material& self) { return optional_object(self.density_unit()); })
.def_property_readonly("color", [](const Material& self) -> py::object {
return self.color() ? py::cast(*self.color()) : py::none();
})
.def("to_dict", [](const Material& self) { return self.to_dict(); })
.def("__eq__", [](const Material& a, const py::object& b) { return py::isinstance<Material>(b) && a == b.cast<const Material&>(); },
py::is_operator())
.def("__hash__", [](const Material& self) { return hash_of(self, self.to_dict().dump()); })
.def("__repr__", [](const Material& self) {
return "Material(material_id=" + str_repr(self.material_id()) + ", name=" + opt_str_repr(self.name()) +
", density=" + opt_float_repr(self.density()) + ", density_unit=" + opt_str_repr(self.density_unit()) +
", color=" + (self.color() ? tuple_repr(*self.color()) : "None") + ")";
});
bind_semantic_value<Material>(cls);
}
void bind_limit_and_refs(py::module_& m) {
using sp::ConnectorRef;
using sp::ScalarLimit;
py::class_<ScalarLimit, py::smart_holder> limit(m, "ScalarLimit", "Closed scalar range for a constraint drive coordinate.");
limit.def(py::init([](const py::object& lower, const py::object& upper) {
return ScalarLimit(number(lower, "lower_value"), number(upper, "upper_value"));
}), py::arg("lower_value"), py::arg("upper_value"))
.def_property_readonly("lower_value", &ScalarLimit::lower_value)
.def_property_readonly("upper_value", &ScalarLimit::upper_value)
.def("contains", [](const ScalarLimit& self, const py::object& value) { return self.contains(number(value, "value")); },
py::arg("value"))
.def("to_dict", [](const ScalarLimit& self) { return self.to_dict(); })
.def("__eq__", [](const ScalarLimit& a, const py::object& b) { return py::isinstance<ScalarLimit>(b) && a == b.cast<const ScalarLimit&>(); },
py::is_operator())
.def("__hash__", [](const ScalarLimit& self) { return hash_of(self, self.to_dict().dump()); })
.def("__repr__", [](const ScalarLimit& self) {
return "ScalarLimit(lower_value=" + float_repr(self.lower_value()) + ", upper_value=" + float_repr(self.upper_value()) + ")";
});
bind_semantic_value<ScalarLimit>(limit);
py::class_<ConnectorRef, py::smart_holder> ref(m, "ConnectorRef", "Reference to a connector through a component instance.");
ref.def(py::init([](const py::object& component_id, const py::object& connector_id) {
return ConnectorRef(text(component_id, "component_id"), text(connector_id, "connector_id"));
}), py::arg("component_id"), py::arg("connector_id"))
.def_property_readonly("component_id", &ConnectorRef::component_id)
.def_property_readonly("connector_id", &ConnectorRef::connector_id)
.def("to_dict", [](const ConnectorRef& self) { return self.to_dict(); })
.def("__eq__", [](const ConnectorRef& a, const py::object& b) { return py::isinstance<ConnectorRef>(b) && a == b.cast<const ConnectorRef&>(); },
py::is_operator())
.def("__hash__", [](const ConnectorRef& self) { return hash_of(self, self.component_id() + "/" + self.connector_id()); })
.def("__repr__", [](const ConnectorRef& self) {
return "ConnectorRef(component_id=" + str_repr(self.component_id()) + ", connector_id=" + str_repr(self.connector_id()) + ")";
});
bind_semantic_value<ConnectorRef>(ref);
}
void bind_connectors(py::module_& m) {
using namespace sp;
py::class_<GeometryRef, py::smart_holder> geometry(m, "GeometryRef", "Serializable reference to a sub-shape selected via QL.");
geometry.def(py::init([](const py::object& kind, const py::object& source_node_id, const py::object& geo_selector, const py::object& flip) {
if (!py::isinstance<py::dict>(geo_selector)) throw scad::TypeError("geo_selector must be a dict");
sp::OptionalString source;
if (!source_node_id.is_none()) source = py::str(source_node_id).cast<std::string>();
return GeometryRef(py::str(kind).cast<std::string>(), source, geo_selector.cast<Value>(), truthy(flip));
}),
py::arg("kind"), py::arg("source_node_id"), py::arg("geo_selector"), py::arg("flip") = false)
.def_property_readonly("kind", &GeometryRef::kind)
.def_property_readonly("source_node_id", [](const GeometryRef& self) { return optional_object(self.source_node_id()); })
.def_property_readonly("geo_selector", [](const GeometryRef& self) { return self.geo_selector(); })
.def_property_readonly("flip", &GeometryRef::flip)
.def("to_dict", [](const GeometryRef& self) { return self.to_dict(); })
.def("__eq__", [](const GeometryRef& a, const py::object& b) { return py::isinstance<GeometryRef>(b) && a == b.cast<const GeometryRef&>(); },
py::is_operator());
bind_semantic_value<GeometryRef>(geometry);
py::class_<ConnectorAnchor, py::smart_holder> anchor(m, "ConnectorAnchor", "Serializable source for a connector datum frame.");
anchor.def(py::init([](const py::object& anchor_kind, const py::object& geometry_ref, const py::object& placement) {
std::optional<GeometryRef> geometry;
std::optional<Placement> frame;
if (!geometry_ref.is_none()) geometry = typed<GeometryRef>(geometry_ref, "geometry anchors require geometry_ref");
if (!placement.is_none()) frame = typed<Placement>(placement, "placement anchors require placement");
return ConnectorAnchor(py::str(anchor_kind).cast<std::string>(), geometry, frame);
}),
py::arg("anchor_kind"), py::arg("geometry_ref") = py::none(), py::arg("placement") = py::none())
.def_property_readonly("anchor_kind", &ConnectorAnchor::anchor_kind)
.def_property_readonly("geometry_ref", [](const ConnectorAnchor& self) -> py::object {
return self.geometry_ref() ? py::cast(*self.geometry_ref()) : py::none();
})
.def_property_readonly("placement", [](const ConnectorAnchor& self) -> py::object {
return self.placement() ? py::cast(*self.placement()) : py::none();
})
.def("to_dict", [](const ConnectorAnchor& self) { return self.to_dict(); })
.def("__eq__", [](const ConnectorAnchor& a, const py::object& b) { return py::isinstance<ConnectorAnchor>(b) && a == b.cast<const ConnectorAnchor&>(); },
py::is_operator());
bind_semantic_value<ConnectorAnchor>(anchor);
py::class_<Connector, py::smart_holder> connector(m, "Connector", "Semantic datum frame anchored by geometry or an explicit placement.");
connector.def(py::init([](const py::object& connector_id, const py::object& geometry_ref, const py::object& name, const py::object& anchor_value) {
std::optional<GeometryRef> geometry;
std::optional<ConnectorAnchor> anchor_of;
if (!geometry_ref.is_none()) geometry = typed<GeometryRef>(geometry_ref, "geometry_ref must be a GeometryRef when anchor is omitted");
if (!anchor_value.is_none()) anchor_of = typed<ConnectorAnchor>(anchor_value, "anchor must be a ConnectorAnchor");
return Connector(text(connector_id, "connector_id"), geometry, optional_name(name), anchor_of);
}),
py::arg("connector_id"), py::arg("geometry_ref") = py::none(), py::arg("name") = py::none(), py::arg("anchor") = py::none())
.def_property_readonly("connector_id", &Connector::connector_id)
.def_property_readonly("geometry_ref", [](const Connector& self) -> py::object {
return self.geometry_ref() ? py::cast(*self.geometry_ref()) : py::none();
})
.def_property_readonly("name", [](const Connector& self) { return optional_object(self.name()); })
.def_property_readonly("anchor", [](const Connector& self) { return self.anchor(); })
.def_property_readonly("anchor_kind", &Connector::anchor_kind)
.def_property_readonly("placement", &Connector::placement)
.def("to_dict", [](const Connector& self) { return self.to_dict(); })
.def("__eq__", [](const Connector& a, const py::object& b) { return py::isinstance<Connector>(b) && a == b.cast<const Connector&>(); },
py::is_operator());
bind_semantic_value<Connector>(connector);
}
sp::OptionalDouble opt_number(const py::object& value, const char* field) {
if (value.is_none()) return std::nullopt;
return number(value, field);
}
sp::OptionalLimit opt_limit(const py::object& value, const char* message) {
if (value.is_none()) return std::nullopt;
return typed<sp::ScalarLimit>(value, message);
}
void bind_constraints(py::module_& m) {
using namespace sp;
py::class_<Constraint, py::smart_holder> cls(m, "Constraint", "Connector-to-connector assembly constraint.");
cls.def(py::init([](const py::object& constraint_id, const py::object& constraint_kind, const py::object& a, const py::object& b,
const py::object& drive_distance, const py::object& distance_limit, const py::object& drive_angle_degrees,
const py::object& angle_limit, const py::object& pitch_radius_a, const py::object& pitch_radius_b,
const py::object& pulley_radius_a, const py::object& pulley_radius_b, const py::object& pitch_radius,
const py::object& phase_offset, const py::object& name) {
ConstraintSettings s;
s.drive_distance = opt_number(drive_distance, "drive_distance");
s.distance_limit = opt_limit(distance_limit, "distance_limit must be a ScalarLimit");
s.drive_angle_degrees = opt_number(drive_angle_degrees, "drive_angle_degrees");
s.angle_limit = opt_limit(angle_limit, "angle_limit must be a ScalarLimit");
s.pitch_radius_a = opt_number(pitch_radius_a, "pitch_radius_a");
s.pitch_radius_b = opt_number(pitch_radius_b, "pitch_radius_b");
s.pulley_radius_a = opt_number(pulley_radius_a, "pulley_radius_a");
s.pulley_radius_b = opt_number(pulley_radius_b, "pulley_radius_b");
s.pitch_radius = opt_number(pitch_radius, "pitch_radius");
s.phase_offset = opt_number(phase_offset, "phase_offset");
s.name = optional_name(name);
return Constraint(text(constraint_id, "constraint_id"), py::str(constraint_kind).cast<std::string>(),
typed<ConnectorRef>(a, "connector_a must be a ConnectorRef"),
typed<ConnectorRef>(b, "connector_b must be a ConnectorRef"), std::move(s));
}),
py::arg("constraint_id"), py::arg("constraint_kind"), py::arg("connector_a"), py::arg("connector_b"),
py::arg("drive_distance") = py::none(), py::arg("distance_limit") = py::none(),
py::arg("drive_angle_degrees") = py::none(), py::arg("angle_limit") = py::none(),
py::arg("pitch_radius_a") = py::none(), py::arg("pitch_radius_b") = py::none(),
py::arg("pulley_radius_a") = py::none(), py::arg("pulley_radius_b") = py::none(),
py::arg("pitch_radius") = py::none(), py::arg("phase_offset") = py::none(), py::arg("name") = py::none())
.def_property_readonly("constraint_id", &Constraint::constraint_id)
.def_property_readonly("constraint_kind", &Constraint::constraint_kind)
.def_property_readonly("connector_a", &Constraint::connector_a)
.def_property_readonly("connector_b", &Constraint::connector_b)
.def_property_readonly("drive_distance", [](const Constraint& c) { return optional_float(c.drive_distance()); })
.def_property_readonly("distance_limit", [](const Constraint& c) -> py::object { return c.distance_limit() ? py::cast(*c.distance_limit()) : py::none(); })
.def_property_readonly("drive_angle_degrees", [](const Constraint& c) { return optional_float(c.drive_angle_degrees()); })
.def_property_readonly("angle_limit", [](const Constraint& c) -> py::object { return c.angle_limit() ? py::cast(*c.angle_limit()) : py::none(); })
.def_property_readonly("pitch_radius_a", [](const Constraint& c) { return optional_float(c.pitch_radius_a()); })
.def_property_readonly("pitch_radius_b", [](const Constraint& c) { return optional_float(c.pitch_radius_b()); })
.def_property_readonly("pulley_radius_a", [](const Constraint& c) { return optional_float(c.pulley_radius_a()); })
.def_property_readonly("pulley_radius_b", [](const Constraint& c) { return optional_float(c.pulley_radius_b()); })
.def_property_readonly("pitch_radius", [](const Constraint& c) { return optional_float(c.pitch_radius()); })
.def_property_readonly("phase_offset", [](const Constraint& c) { return optional_float(c.phase_offset()); })
.def_property_readonly("name", [](const Constraint& c) { return optional_object(c.name()); })
.def("to_dict", [](const Constraint& self) { return self.to_dict(); })
.def("__eq__", [](const Constraint& a, const py::object& b) { return py::isinstance<Constraint>(b) && a == b.cast<const Constraint&>(); },
py::is_operator());
bind_semantic_value<Constraint>(cls);
py::class_<ConstraintResidual, py::smart_holder>(m, "ConstraintResidual", "Residual for a single assembly constraint.")
.def(py::init([](std::string constraint_id, double translation_error, double angular_error_degrees, bool within_tolerance) {
return ConstraintResidual{std::move(constraint_id), translation_error, angular_error_degrees, within_tolerance};
}),
py::arg("constraint_id"), py::arg("translation_error"), py::arg("angular_error_degrees"), py::arg("within_tolerance"))
.def_readonly("constraint_id", &ConstraintResidual::constraint_id)
.def_readonly("translation_error", &ConstraintResidual::translation_error)
.def_readonly("angular_error_degrees", &ConstraintResidual::angular_error_degrees)
.def_readonly("within_tolerance", &ConstraintResidual::within_tolerance)
.def("to_dict", [](const ConstraintResidual& self) { return self.to_dict(); })
.def("__eq__", [](const ConstraintResidual& a, const py::object& b) { return py::isinstance<ConstraintResidual>(b) && a == b.cast<const ConstraintResidual&>(); },
py::is_operator())
.def("__repr__", [](const ConstraintResidual& r) {
return "ConstraintResidual(constraint_id=" + str_repr(r.constraint_id) + ", translation_error=" + float_repr(r.translation_error) +
", angular_error_degrees=" + float_repr(r.angular_error_degrees) + ", within_tolerance=" + (r.within_tolerance ? "True" : "False") + ")";
});
py::class_<ConstraintReport, py::smart_holder>(m, "ConstraintReport", "Assembly constraint inspection report.")
.def(py::init([](bool solved, std::vector<std::string> grounded, std::vector<std::string> solved_ids,
std::vector<std::string> unsolved_ids, std::vector<ConstraintResidual> residuals) {
return ConstraintReport{solved, std::move(grounded), std::move(solved_ids), std::move(unsolved_ids), std::move(residuals)};
}),
py::arg("solved"), py::arg("grounded_component_ids"), py::arg("solved_component_ids"),
py::arg("unsolved_component_ids"), py::arg("residuals"))
.def_readonly("solved", &ConstraintReport::solved)
.def_property_readonly("grounded_component_ids", [](const ConstraintReport& r) { return to_tuple(r.grounded_component_ids); })
.def_property_readonly("solved_component_ids", [](const ConstraintReport& r) { return to_tuple(r.solved_component_ids); })
.def_property_readonly("unsolved_component_ids", [](const ConstraintReport& r) { return to_tuple(r.unsolved_component_ids); })
.def_property_readonly("residuals", [](const ConstraintReport& r) { return to_tuple(r.residuals); })
.def("to_dict", [](const ConstraintReport& self) { return self.to_dict(); })
.def("__eq__", [](const ConstraintReport& a, const py::object& b) { return py::isinstance<ConstraintReport>(b) && a == b.cast<const ConstraintReport&>(); },
py::is_operator());
}
void bind_part(py::module_& m) {
using namespace sp;
py::class_<Part, py::smart_holder> cls(m, "Part", "Single-body product item wrapping exactly one Solid.");
cls.def(py::init([](const py::object& part_id, const py::object& body, const py::object& name, const py::object& material,
const py::object& connectors) {
std::optional<Material> material_value;
if (!material.is_none()) material_value = typed<Material>(material, "material must be a Material");
std::vector<Connector> connector_values;
if (!connectors.is_none()) {
for (const py::handle item : connectors) {
connector_values.push_back(typed<Connector>(py::reinterpret_borrow<py::object>(item), "connectors must contain Connector values"));
}
}
return std::make_shared<Part>(text(part_id, "part_id"), typed<Solid>(body, "body must be a Solid"), optional_name(name),
material_value, std::move(connector_values));
}),
py::arg("part_id"), py::arg("body"), py::arg("name") = py::none(), py::arg("material") = py::none(),
py::arg("connectors") = py::tuple())
.def_property_readonly("part_id", &Part::part_id)
.def_property_readonly("body", &Part::body)
.def_property_readonly("name", [](const Part& self) { return optional_object(self.name()); })
.def_property_readonly("material", [](const Part& self) -> py::object { return self.material() ? py::cast(*self.material()) : py::none(); })
.def_property_readonly("connectors", [](const Part& self) { return to_tuple(self.connectors()); })
.def("with_material", [](const Part& self, const py::object& material) {
return std::make_shared<const Part>(self.with_material(typed<Material>(material, "material must be a Material")));
}, py::arg("material"))
.def("connector_ids", [](const Part& self) { return to_tuple(self.connector_ids()); })
.def("get_connector", [](const Part& self, const py::object& id) { return self.get_connector(text(id, "connector_id")); },
py::arg("connector_id"))
.def("with_connector", [](const Part& self, const py::object& connector) {
return std::make_shared<const Part>(self.with_connector(typed<Connector>(connector, "connector must be a Connector")));
}, py::arg("connector"))
.def("to_dict", [](const Part& self) { return self.to_dict(); })
.def("__repr__", [](const Part& self) { return "Part(part_id=" + str_repr(self.part_id()) + ", name=" + opt_str_repr(self.name()) + ")"; });
bind_semantic_value<Part>(cls);
}
void bind_assembly(py::module_& m) {
using namespace sp;
py::class_<PublicConnectorRef, py::smart_holder>(m, "PublicConnectorRef", "Public alias for an existing connector on a direct child component.")
.def(py::init([](const py::object& public_id, const py::object& component_id, const py::object& connector_id, const py::object& name) {
return PublicConnectorRef(text(public_id, "public_connector_id"), text(component_id, "component_id"),
text(connector_id, "connector_id"), optional_name(name));
}),
py::arg("public_connector_id"), py::arg("component_id"), py::arg("connector_id"), py::arg("name") = py::none())
.def_readonly("public_connector_id", &PublicConnectorRef::public_connector_id)
.def_readonly("component_id", &PublicConnectorRef::component_id)
.def_readonly("connector_id", &PublicConnectorRef::connector_id)
.def_property_readonly("name", [](const PublicConnectorRef& self) { return optional_object(self.name); })
.def("to_dict", [](const PublicConnectorRef& self) { return self.to_dict(); })
.def("__eq__", [](const PublicConnectorRef& a, const py::object& b) { return py::isinstance<PublicConnectorRef>(b) && a == b.cast<const PublicConnectorRef&>(); },
py::is_operator());
py::class_<Component, py::smart_holder>(m, "Component", "Assembly-local instance of a Part or subassembly.")
.def(py::init([](const py::object& component_id, const py::object& item, const py::object& placement, const py::object& name) {
return Component(text(component_id, "component_id"), item_of(item), typed<Placement>(placement, "placement must be a Placement"),
optional_name(name));
}),
py::arg("component_id"), py::arg("item"), py::arg("placement"), py::arg("name") = py::none())
.def_readonly("component_id", &Component::component_id)
.def_property_readonly("item", [](const Component& self) { return py_item(self.item); })
.def_readonly("placement", &Component::placement)
.def_property_readonly("name", [](const Component& self) { return optional_object(self.name); })
.def("to_dict", [](const Component& self) { return self.to_dict(); });
py::class_<Assembly, py::smart_holder> cls(m, "Assembly", "Product structure containing placed Part or subassembly components.");
cls.def(py::init([](const py::object& assembly_id, const py::object& name, const py::object& components, const py::object& publics,
const py::object& constraints, const py::object& grounded) {
std::vector<Component> component_values;
std::vector<PublicConnectorRef> public_values;
std::vector<Constraint> constraint_values;
std::vector<std::string> grounded_values;
if (!components.is_none()) {
for (const py::handle item : components) {
component_values.push_back(typed<Component>(py::reinterpret_borrow<py::object>(item), "components must contain Component values"));
}
}
if (!publics.is_none()) {
for (const py::handle item : publics) {
public_values.push_back(typed<PublicConnectorRef>(py::reinterpret_borrow<py::object>(item), "public_connectors must contain PublicConnectorRef values"));
}
}
if (!constraints.is_none()) {
for (const py::handle item : constraints) {
constraint_values.push_back(typed<Constraint>(py::reinterpret_borrow<py::object>(item), "constraints must contain Constraint values"));
}
}
if (!grounded.is_none()) {
for (const py::handle item : grounded) grounded_values.push_back(text(py::reinterpret_borrow<py::object>(item), "component_id"));
}
return std::make_shared<Assembly>(text(assembly_id, "assembly_id"), optional_name(name), std::move(component_values),
std::move(public_values), std::move(constraint_values), std::move(grounded_values));
}),
py::arg("assembly_id"), py::arg("name") = py::none(), py::arg("components") = py::tuple(),
py::arg("public_connectors") = py::tuple(), py::arg("constraints") = py::tuple(),
py::arg("grounded_component_ids") = py::tuple())
.def_property_readonly("assembly_id", &Assembly::assembly_id)
.def_property_readonly("name", [](const Assembly& self) { return optional_object(self.name()); })
.def_property_readonly("components", [](const Assembly& self) { return to_tuple(self.components()); })
.def_property_readonly("public_connectors", [](const Assembly& self) { return to_tuple(self.public_connectors()); })
.def_property_readonly("constraints", [](const Assembly& self) { return to_tuple(self.constraints()); })
.def_property_readonly("grounded_component_ids", [](const Assembly& self) { return to_tuple(self.grounded_component_ids()); })
.def("component_ids", [](const Assembly& self) { return to_tuple(self.component_ids()); })
.def("get_component", [](const Assembly& self, const py::object& id) { return self.get_component(text(id, "component_id")); },
py::arg("component_id"))
.def("with_component", [](const Assembly& self, const py::object& component) {
return std::make_shared<const Assembly>(self.with_component(typed<Component>(component, "component must be a Component")));
}, py::arg("component"))
.def("with_component_placement", [](const Assembly& self, const py::object& id, const py::object& placement) {
return std::make_shared<const Assembly>(self.with_component_placement(
text(id, "component_id"), typed<Placement>(placement, "placement must be a Placement")));
}, py::arg("component_id"), py::arg("placement"))
.def("public_connector_ids", [](const Assembly& self) { return to_tuple(self.public_connector_ids()); })
.def("get_public_connector", [](const Assembly& self, const py::object& id) {
return self.get_public_connector(text(id, "public_connector_id"));
}, py::arg("public_connector_id"))
.def("with_public_connector", [](const Assembly& self, const py::object& pub) {
return std::make_shared<const Assembly>(self.with_public_connector(typed<PublicConnectorRef>(pub, "public must be a PublicConnectorRef")));
}, py::arg("public"))
.def("constraint_ids", [](const Assembly& self) { return to_tuple(self.constraint_ids()); })
.def("get_constraint", [](const Assembly& self, const py::object& id) { return self.get_constraint(text(id, "constraint_id")); },
py::arg("constraint_id"))
.def("with_constraint", [](const Assembly& self, const py::object& constraint) {
return std::make_shared<const Assembly>(self.with_constraint(typed<Constraint>(constraint, "constraint must be a Constraint")));
}, py::arg("constraint"))
.def("with_grounded_component", [](const Assembly& self, const py::object& id) {
return std::make_shared<const Assembly>(self.with_grounded_component(text(id, "component_id")));
}, py::arg("component_id"))
.def("without_grounded_component", [](const Assembly& self, const py::object& id) {
return std::make_shared<const Assembly>(self.without_grounded_component(text(id, "component_id")));
}, py::arg("component_id"))
.def("to_dict", [](const Assembly& self) { return self.to_dict(); })
.def("__repr__", [](const Assembly& self) { return "Assembly(assembly_id=" + str_repr(self.assembly_id()) + ", name=" + opt_str_repr(self.name()) + ")"; });
bind_semantic_value<Assembly>(cls);
}
} // namespace
void bind_product_values(py::module_& m) {
bind_placement(m);
bind_material(m);
bind_limit_and_refs(m);
bind_connectors(m);
bind_constraints(m);
bind_part(m);
bind_assembly(m);
}
+639
View File
@@ -0,0 +1,639 @@
// Python bindings for the "ql" area: the module `simplecadapi.ql`, here `simplecadapi._cpp.ql`.
//
// Same names, signatures and error messages as the Python SDK:
//
// from simplecadapi._cpp import ql
// ql.faces().where(ql.prop("geom.normal.z", ">", 0.9)).exactly(1).resolve(solid)
//
// The submodule is registered under both `simplecadapi._cpp._native.ql` and
// `simplecadapi._cpp.ql`, so `import simplecadapi._cpp.ql as Q` works.
#include "bindings.hpp"
#include <BRepAlgoAPI_Cut.hxx>
#include <BRepPrimAPI_MakeBox.hxx>
#include <BRepPrimAPI_MakeCylinder.hxx>
#include <BRep_Builder.hxx>
#include <TopExp_Explorer.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Compound.hxx>
#include <gp_Ax2.hxx>
#include <algorithm>
#include <string_view>
#include "scad/core/error.hpp"
#include "scad/ql/ql.hpp"
namespace {
using namespace scad;
using scad::pybind::value_from_python;
using scad::pybind::value_to_python;
// ---- conversions ----------------------------------------------------------------------------------------------
py::object shape_to_py(const Shape& s) {
switch (s.kind()) {
case Kind::Vertex: return py::cast(Vertex(s));
case Kind::Edge: return py::cast(Edge(s));
case Kind::Wire: return py::cast(Wire(s));
case Kind::Face: return py::cast(Face(s));
case Kind::Shell: return py::cast(Shell(s));
case Kind::Solid: return py::cast(Solid(s));
case Kind::Compound: return py::cast(Compound(s));
}
return py::none();
}
py::list shapes_to_py(const std::vector<Shape>& shapes) {
py::list out;
for (const Shape& s : shapes) out.append(shape_to_py(s));
return out;
}
bool is_text(const py::handle& h) { return py::isinstance<py::str>(h) || py::isinstance<py::bytes>(h); }
// A shape, or any iterable of shapes (ShapeSelector.resolve(scope)).
ql::Scope scope_from_py(const py::object& scope, const std::string& target_kind) {
if (py::isinstance<Shape>(scope)) return ql::Scope(scope.cast<const Shape&>());
if (!is_text(scope) && !py::isinstance<py::dict>(scope) && py::hasattr(scope, "__iter__")) {
std::vector<Shape> items;
for (const py::handle item : scope) {
if (!py::isinstance<Shape>(item)) throw TypeError("QL selector scope items must be shapes");
items.push_back(item.cast<const Shape&>());
}
return ql::Scope(std::move(items));
}
throw TypeError("cannot resolve QL selector scope for target_kind=" + target_kind);
}
py::object scope_to_py(const ql::Scope& scope) {
return scope.is_list() ? py::object(shapes_to_py(scope.items())) : shape_to_py(scope.shape());
}
py::dict dict_of(const Value& v) { return py::cast<py::dict>(value_to_python(v)); }
std::string scope_name(const py::object& scope) {
if (py::isinstance<py::str>(scope)) return scope.cast<std::string>();
if (py::hasattr(scope, "value")) return py::str(scope.attr("value")).cast<std::string>();
throw TypeError("scope must be a string or a TagScope");
}
std::string text_of(const py::object& v, const char* message) {
if (!py::isinstance<py::str>(v)) throw ValueError(message);
return v.cast<std::string>();
}
// A Python callable the C++ side keeps: it never touches the interpreter once the interpreter has gone.
class PyCallable {
public:
explicit PyCallable(py::object fn) : fn_(std::move(fn)) {}
PyCallable(const PyCallable&) = delete;
PyCallable& operator=(const PyCallable&) = delete;
~PyCallable() {
if (Py_IsInitialized() == 0) {
fn_.release();
} else {
const py::gil_scoped_acquire gil;
fn_ = py::object();
}
}
[[nodiscard]] const py::object& get() const { return fn_; }
private:
py::object fn_;
};
// The sentinel resolvers return for "not mine" (simplecadapi.ql.MISSING).
struct MissingType {};
// The resolvers registered from Python, in order, for objects that are not shapes: a custom resolver is how
// QL is extended to any Python object (resolver(target, path) -> value | MISSING).
struct PyResolverEntry {
std::string prefix;
std::shared_ptr<PyCallable> resolve;
};
std::vector<PyResolverEntry>& py_resolvers() {
static std::vector<PyResolverEntry>* entries = new std::vector<PyResolverEntry>(); // outlives the interpreter
return *entries;
}
// A property path of an arbitrary object: the first registered resolver answering for the path wins.
std::optional<Value> object_property(const py::object& target, const std::string& path) {
for (const PyResolverEntry& entry : py_resolvers()) {
if (path.rfind(entry.prefix, 0) != 0) continue;
const py::object answer = entry.resolve->get()(target, path);
if (py::isinstance<MissingType>(answer)) continue;
return value_from_python(answer);
}
return std::nullopt;
}
// A predicate evaluated on an object that is not a shape: logic, and property comparisons that a registered
// resolver answers. Anything else needs a shape.
bool matches_object(const ql::Predicate& predicate, const py::object& target) {
const std::string kind = predicate.kind();
if (kind == "and" || kind == "or") {
const bool all = kind == "and";
for (const ql::Predicate& child : predicate.children())
if (matches_object(child, target) != all) return !all;
return all;
}
if (kind == "not") return !matches_object(predicate.children().front(), target);
if (kind == "property_compare") {
const Value& data = predicate.data();
const std::string path = data.find("path")->as_string();
const std::string op = data.find("op")->as_string();
const std::optional<Value> actual = object_property(target, path);
return ql::compare(actual ? *actual : Value(), ql::parse_compare_op(op), op, *data.find("value"));
}
throw TypeError("predicate '" + kind + "' needs a shape: expected AnyShape, got " +
std::string(py::str(py::type::of(target).attr("__name__"))));
}
// ---- predicate / key factories ------------------------------------------------------------------------------------
ql::Predicate comparison(const py::object& op, ql::Predicate (*make)(std::string_view, std::string_view, Value),
const std::string& path, const Value& expected) {
if (!py::isinstance<py::str>(op)) throw TypeError("op must be a string");
return make(path, op.cast<std::string>(), expected);
}
// and_/or_ of serializable predicates is itself one; anything else becomes a plain Python callable.
py::object combine(const py::args& args, bool all) {
const bool serializable =
std::all_of(args.begin(), args.end(), [](const py::handle h) { return py::isinstance<ql::Predicate>(h); });
if (serializable) {
std::vector<ql::Predicate> children;
for (const py::handle h : args) children.push_back(h.cast<ql::Predicate>());
return py::cast(all ? ql::and_(std::move(children)) : ql::or_(std::move(children)));
}
const py::tuple predicates = args;
return py::cpp_function([predicates, all](const py::object& obj) {
for (const py::handle predicate : predicates)
if (py::bool_(predicate(obj)) != all) return !all;
return all;
});
}
// ---- Query over arbitrary Python objects ---------------------------------------------------------------------------
// select() takes any iterable and any callable, like the Python Query; the typed ql::Query is for native callers.
struct PyQuery {
py::list items;
};
PyQuery query_where(const PyQuery& self, const py::object& predicate) {
py::list kept;
for (const py::handle item : self.items)
if (py::bool_(predicate(item))) kept.append(item);
return PyQuery{kept};
}
PyQuery query_order_by(const PyQuery& self, const py::object& sort_key, bool desc) {
const py::cpp_function safe_key([sort_key](const py::object& obj) {
const py::object value = sort_key(obj);
return py::make_tuple(value.is_none(), value);
});
const py::object ordered =
py::module_::import("builtins").attr("sorted")(self.items, py::arg("key") = safe_key, py::arg("reverse") = desc);
return PyQuery{py::list(ordered)};
}
PyQuery query_limit(const PyQuery& self, std::int64_t count) {
if (count <= 0) return PyQuery{py::list()};
return PyQuery{py::list(self.items[py::slice(0, count, 1)])};
}
// ---- evidence -------------------------------------------------------------------------------------------------------
py::object field_of(const py::object& item, const char* name) {
if (py::isinstance<py::dict>(item)) return item.attr("get")(name, py::none());
return py::getattr(item, name, py::none());
}
ErrorEvidence evidence_from_py(const py::object& item) {
ErrorEvidence out;
const auto text = [&](const char* name) {
const py::object v = field_of(item, name);
return v.is_none() ? std::string() : py::str(v).cast<std::string>();
};
out.kind = text("kind");
out.path = text("path");
out.view = text("view");
out.caption = text("caption");
const py::object symbols = field_of(item, "symbols");
if (!symbols.is_none()) {
const py::object pairs = py::isinstance<py::dict>(symbols) ? py::object(symbols.attr("items")()) : symbols;
for (const py::handle pair : pairs) {
const py::sequence entry = py::reinterpret_borrow<py::sequence>(pair);
out.symbols.emplace_back(py::str(entry[0]).cast<std::string>(), py::str(entry[1]).cast<std::string>());
}
}
return out;
}
// ---- raw shapes for the tests ------------------------------------------------------------------------------------------
// Stand-ins for the operators (which live in other areas) so QL tests can place and cut shapes.
Solid box_at(const Vec3& origin, double dx, double dy, double dz) {
return Solid(BRepPrimAPI_MakeBox(gp_Pnt(origin.x, origin.y, origin.z), dx, dy, dz).Solid());
}
Solid cylinder_at(const Vec3& base, double radius, double height) {
const gp_Ax2 axis(gp_Pnt(base.x, base.y, base.z), gp_Dir(0, 0, 1));
return Solid(BRepPrimAPI_MakeCylinder(axis, radius, height).Solid());
}
Solid cut_solids(const Solid& body, const Solid& tool) {
BRepAlgoAPI_Cut op(body.wrapped(), tool.wrapped());
const TopExp_Explorer solids(op.Shape(), TopAbs_SOLID);
if (!solids.More()) throw ValueError("the cut left no solid");
return Solid(TopoDS::Solid(solids.Current()));
}
Compound compound_of(const std::vector<Solid>& solids) {
BRep_Builder builder;
TopoDS_Compound compound;
builder.MakeCompound(compound);
for (const Solid& s : solids) builder.Add(compound, s.wrapped());
return Compound(compound);
}
// ---- the classes ----------------------------------------------------------------------------------------------------------
void bind_predicate(py::module_& q) {
py::class_<ql::Predicate>(q, "SerializablePredicate",
"A serializable QL predicate: (kind, data, children), also callable on a shape.")
.def(py::init([](const std::string& kind, const py::object& data, const py::object& children) {
std::vector<ql::Predicate> kids;
if (!children.is_none())
for (const py::handle child : children) kids.push_back(child.cast<ql::Predicate>());
return ql::Predicate(kind, data.is_none() ? Value::object() : value_from_python(data), std::move(kids));
}),
py::arg("kind"), py::arg("data") = py::none(), py::arg("children") = py::tuple())
.def_property_readonly("kind", &ql::Predicate::kind)
.def_property_readonly("data", [](const ql::Predicate& p) { return dict_of(p.data()); })
.def_property_readonly("children",
[](const ql::Predicate& p) {
py::list kids;
for (const ql::Predicate& child : p.children()) kids.append(py::cast(child));
return py::tuple(kids);
})
.def("__call__", [](const ql::Predicate& p, const py::object& obj) {
if (py::isinstance<Shape>(obj)) return p.matches(obj.cast<const Shape&>());
return matches_object(p, obj);
}, py::arg("obj"))
.def("to_dict", [](const ql::Predicate& p) { return dict_of(p.to_value()); })
.def_static("from_dict", [](const Value& payload) { return ql::Predicate::from_value(payload); }, py::arg("data"))
.def("__eq__", [](const ql::Predicate& a, const ql::Predicate& b) { return a == b; }, py::is_operator())
.def("__repr__", [](const ql::Predicate& p) {
py::list kids;
for (const ql::Predicate& child : p.children()) kids.append(py::cast(child));
return "SerializablePredicate(kind=" + std::string(py::repr(py::str(p.kind()))) +
", data=" + std::string(py::repr(dict_of(p.data()))) +
", children=" + std::string(py::repr(py::tuple(kids))) + ")";
});
py::class_<ql::Key>(q, "SerializableKey", "A serializable QL sort key: (kind, data), callable on a shape.")
.def(py::init([](const std::string& kind, const py::object& data) {
return ql::Key(kind, data.is_none() ? Value::object() : value_from_python(data));
}),
py::arg("kind"), py::arg("data") = py::none())
.def_property_readonly("kind", &ql::Key::kind)
.def_property_readonly("data", [](const ql::Key& k) { return dict_of(k.data()); })
.def("__call__", [](const ql::Key& k, const py::object& obj) -> py::object {
if (py::isinstance<Shape>(obj)) return py::cast(k.evaluate(obj.cast<const Shape&>()));
if (k.kind() == "property") {
const Value fallback = k.data().find("default") != nullptr ? *k.data().find("default") : Value();
const auto found = object_property(obj, k.data().find("path")->as_string());
return value_to_python(found ? *found : fallback);
}
throw TypeError("key '" + k.kind() + "' needs a shape");
}, py::arg("obj"))
.def("to_dict", [](const ql::Key& k) { return dict_of(k.to_value()); })
.def_static("from_dict", [](const Value& payload) { return ql::Key::from_value(payload); }, py::arg("data"))
.def("__eq__", [](const ql::Key& a, const ql::Key& b) { return a == b; }, py::is_operator())
.def("__repr__", [](const ql::Key& k) {
return "SerializableKey(kind=" + std::string(py::repr(py::str(k.kind()))) +
", data=" + std::string(py::repr(dict_of(k.data()))) + ")";
});
py::class_<ql::TraversalSpec>(q, "TraversalSpec")
.def(py::init([](const std::string& relation) { return ql::TraversalSpec{relation}; }), py::arg("relation"))
.def_readonly("relation", &ql::TraversalSpec::relation)
.def("to_dict", [](const ql::TraversalSpec& t) { return dict_of(t.to_value()); })
.def_static("from_dict", [](const Value& payload) { return ql::TraversalSpec::from_value(payload); },
py::arg("data"))
.def("__eq__", [](const ql::TraversalSpec& a, const ql::TraversalSpec& b) { return a == b; }, py::is_operator());
}
void bind_factories(py::module_& q) {
q.def(
"tag",
[](const py::object& pattern, const py::object& scope) {
if (!py::isinstance<py::str>(pattern)) throw TypeError("pattern must be a string");
return ql::tag(pattern.cast<std::string>(), scope_name(scope));
},
py::arg("pattern"), py::arg("scope") = "effective",
"Build a tag predicate: an exact tag, or a prefix when the pattern ends in '*'.\n\n"
"scope is one of local, inherited, effective or lineage.");
q.def(
"meta",
[](const std::string& path, const py::object& op, const Value& value_) {
return comparison(op, &ql::meta, path, value_);
},
py::arg("path"), py::arg("op"), py::arg("value_"),
"Build a metadata comparison predicate; op is one of ==, !=, >, >=, <, <=.");
q.def(
"prop",
[](const std::string& path, const py::object& op, const Value& value_) {
return comparison(op, &ql::prop, path, value_);
},
py::arg("path"), py::arg("op"), py::arg("value_"),
"Build a property comparison predicate over metadata or measured geometry (geom.*, topo.*).");
q.def("value", [](const std::string& path, const Value& fallback) { return ql::value(path, fallback); },
py::arg("path"), py::arg("default") = Value(), "Build a value key (metadata first, then geo.area/length/volume).");
q.def("key", [](const std::string& path, const Value& fallback) { return ql::key(path, fallback); },
py::arg("path"), py::arg("default") = Value(), "Build a property key.");
q.def("geo", [](const std::string& field, const Value& fallback) { return ql::geo(field, fallback); },
py::arg("field"), py::arg("default") = Value(), "Shortcut for value('geo.<field>').");
q.def("center_axis", [](const std::string& axis) { return ql::center_axis(axis); }, py::arg("axis"));
q.def("curve_type", [](const std::string& kind) { return ql::curve_type(kind); }, py::arg("kind"));
q.def("surface_type", [](const std::string& kind) { return ql::surface_type(kind); }, py::arg("kind"));
q.def("and_", [](const py::args& predicates) { return combine(predicates, true); },
"Combine predicates so all of them must match.");
q.def("or_", [](const py::args& predicates) { return combine(predicates, false); },
"Combine predicates so at least one of them must match.");
q.def(
"not_",
[](const py::object& predicate) -> py::object {
if (py::isinstance<ql::Predicate>(predicate)) return py::cast(ql::not_(predicate.cast<ql::Predicate>()));
return py::cpp_function([predicate](const py::object& obj) { return !py::bool_(predicate(obj)); });
},
py::arg("predicate"), "Negate a QL predicate.");
const auto operation_event = [](const py::object& op_name, const py::object& event) {
return ql::operation_event(text_of(op_name, "op_name must be a non-empty string"),
text_of(event, "event must be a non-empty string"));
};
q.def("operation_event", operation_event, py::arg("op_name"), py::arg("event") = "*",
"Match typed operation and topology-event metadata under track.");
q.def("op", operation_event, py::arg("op_name"), py::arg("event") = "*");
const auto origin_role = [](const py::object& role_name) {
return ql::origin_role(text_of(role_name, "role_name must be a non-empty string"));
};
q.def("origin_role", origin_role, py::arg("role_name"), "Match a typed source role under track metadata.");
q.def("origin", origin_role, py::arg("role_name"));
q.def(
"output_role",
[](const py::object& role_name) { return ql::output_role(text_of(role_name, "role_name must be a non-empty string")); },
py::arg("role_name"), "Match a kernel-proven operation output role under track metadata.");
q.def(
"source_binding",
[](const py::object& binding_id) { return ql::source_binding(text_of(binding_id, "binding_id must be a non-empty string")); },
py::arg("binding_id"), "Match a projected local binding by its exact source binding identity.");
q.def(
"source_topology",
[](const py::object& topo_id) { return ql::source_topology(text_of(topo_id, "topo_id must be a non-empty string")); },
py::arg("topo_id"), "Match a projected local binding by its exact source topology identity.");
q.def("role", [](const std::string& role_name) { return ql::role(role_name); }, py::arg("role_name"));
q.def(
"register_property_resolver",
[](const py::object& prefix, const py::object& resolver) {
if (!py::isinstance<py::str>(prefix) || prefix.cast<std::string>().empty())
throw ValueError("prefix must be a non-empty string");
const auto callable = std::make_shared<PyCallable>(resolver);
const std::string name = prefix.cast<std::string>();
auto& entries = py_resolvers();
const auto found = std::find_if(entries.begin(), entries.end(), [&](const PyResolverEntry& e) { return e.prefix == name; });
if (found != entries.end()) found->resolve = callable;
else entries.push_back({name, callable});
ql::register_property_resolver(
name, [callable](const Shape& shape, std::string_view path) -> std::optional<Value> {
const py::object answer = callable->get()(shape_to_py(shape), std::string(path));
if (py::isinstance<MissingType>(answer)) return std::nullopt;
return value_from_python(answer);
});
},
py::arg("prefix"), py::arg("resolver"),
"Answer property paths that start with `prefix`: resolver(shape, path) returns a value or ql.MISSING.");
q.def("unregister_property_resolver", [](const std::string& prefix) {
auto& entries = py_resolvers();
entries.erase(std::remove_if(entries.begin(), entries.end(), [&](const PyResolverEntry& e) { return e.prefix == prefix; }),
entries.end());
ql::unregister_property_resolver(prefix);
},
py::arg("prefix"));
}
void bind_selector(py::module_& q) {
py::class_<ql::ShapeSelector>(q, "ShapeSelector", "A fluent, serializable query over the topology of a shape.")
.def(py::init<std::string>(), py::arg("target_kind"))
.def_property_readonly("target_kind", &ql::ShapeSelector::target_kind)
.def_property_readonly("source_selector",
[](const ql::ShapeSelector& s) -> py::object {
const ql::ShapeSelector* source = s.source_selector();
return source != nullptr ? py::cast(*source) : py::none();
})
.def_property_readonly("traversal",
[](const ql::ShapeSelector& s) -> py::object {
return s.traversal() ? py::cast(*s.traversal()) : py::none();
})
.def_property_readonly("predicate",
[](const ql::ShapeSelector& s) -> py::object {
return s.predicate() ? py::cast(*s.predicate()) : py::none();
})
.def_property_readonly("order_key",
[](const ql::ShapeSelector& s) -> py::object {
return s.order_key() ? py::cast(*s.order_key()) : py::none();
})
.def_property_readonly("order_keys",
[](const ql::ShapeSelector& s) {
py::list out;
for (const auto& [sort_key, desc] : s.order_keys())
out.append(py::make_tuple(py::cast(sort_key), desc));
return py::tuple(out);
})
.def_property_readonly("order_desc", &ql::ShapeSelector::order_desc)
.def_property_readonly("limit_count",
[](const ql::ShapeSelector& s) -> py::object {
return s.limit_count() ? py::object(py::int_(*s.limit_count())) : py::none();
})
.def_property_readonly("cardinality",
[](const ql::ShapeSelector& s) {
py::dict out;
for (const auto& [mode, count] : s.cardinality()) out[py::str(mode)] = count;
return out;
})
.def_property_readonly("source_node_id",
[](const ql::ShapeSelector& s) -> py::object {
return s.source_node_id() ? py::object(py::str(*s.source_node_id())) : py::none();
})
.def_property_readonly("source_output_slot",
[](const ql::ShapeSelector& s) -> py::object {
return s.source_output_slot() ? py::object(py::int_(*s.source_output_slot())) : py::none();
})
.def_property_readonly("set_operation",
[](const ql::ShapeSelector& s) -> py::object {
return s.set_operation() ? py::object(py::str(*s.set_operation())) : py::none();
})
.def_property_readonly("operands",
[](const ql::ShapeSelector& s) {
py::list out;
for (const auto& operand : s.operands()) out.append(py::cast(operand));
return py::tuple(out);
})
.def_property_readonly("incident_face_selectors",
[](const ql::ShapeSelector& s) {
py::list out;
for (const auto& selector : s.incident_face_selectors()) out.append(py::cast(selector));
return py::tuple(out);
})
.def_property_readonly("incident_faces_distinct", &ql::ShapeSelector::incident_faces_distinct)
.def_property_readonly("incident_face_cardinality",
[](const ql::ShapeSelector& s) {
py::dict out;
if (s.incident_face_cardinality()) out["exactly"] = *s.incident_face_cardinality();
return out;
})
.def(
"where",
[](const ql::ShapeSelector& s, const py::object& predicate) {
if (!py::isinstance<ql::Predicate>(predicate))
throw TypeError("ShapeSelector.where only supports serializable QL predicates");
return s.where(predicate.cast<ql::Predicate>());
},
py::arg("predicate"))
.def(
"order_by",
[](const ql::ShapeSelector& s, const py::object& sort_key, bool desc) {
if (!py::isinstance<ql::Key>(sort_key))
throw TypeError("ShapeSelector.order_by only supports serializable QL keys");
return s.order_by(sort_key.cast<ql::Key>(), desc);
},
py::arg("key"), py::arg("desc") = false)
.def("from_source",
[](const ql::ShapeSelector& s, const std::string& node_id, int slot) { return s.from_source(node_id, slot); },
py::arg("node_id"), py::arg("output_slot") = 0)
.def("take", [](const ql::ShapeSelector& s, std::int64_t count) { return s.take(count); }, py::arg("count"))
.def("exactly", [](const ql::ShapeSelector& s, std::int64_t count) { return s.exactly(count); }, py::arg("count"))
.def("at_least", [](const ql::ShapeSelector& s, std::int64_t count) { return s.at_least(count); }, py::arg("count"))
.def("at_most", [](const ql::ShapeSelector& s, std::int64_t count) { return s.at_most(count); }, py::arg("count"))
.def("traverse",
[](const ql::ShapeSelector& s, const std::string& relation, const std::string& to_kind) {
return s.traverse(relation, to_kind);
},
py::arg("relation"), py::arg("to_kind"))
.def("boundary", [](const ql::ShapeSelector& s, const std::string& to_kind) { return s.boundary(to_kind); },
py::arg("to_kind"))
.def(
"intersection",
[](const ql::ShapeSelector& s, const py::object& other) {
if (!py::isinstance<ql::ShapeSelector>(other)) throw TypeError("intersection requires another ShapeSelector");
return s.intersection(other.cast<ql::ShapeSelector>());
},
py::arg("other"), "Return entities present in both selector result sets.")
.def(
"shared_boundary",
[](const ql::ShapeSelector& s, const py::object& other, const std::string& to_kind) {
if (!py::isinstance<ql::ShapeSelector>(other)) throw TypeError("intersection requires another ShapeSelector");
return s.shared_boundary(other.cast<ql::ShapeSelector>(), to_kind);
},
py::arg("other"), py::arg("to_kind") = "edge",
"Select current-topology boundary entities shared by both operands.")
.def(
"incident_to",
[](const ql::ShapeSelector& s, const py::args& face_selectors, bool distinct) {
if (s.target_kind() != "edge") throw ValueError("incident_to is only valid on an Edge selector");
std::vector<ql::ShapeSelector> selectors;
for (const py::handle h : face_selectors) {
if (!py::isinstance<ql::ShapeSelector>(h)) throw TypeError("incident_to requires one or more Face selectors");
selectors.push_back(h.cast<ql::ShapeSelector>());
}
return s.incident_to(std::move(selectors), distinct);
},
py::kw_only(), py::arg("distinct") = false, "Restrict Edges by their distinct incident Face witnesses.")
.def("incident_face_count",
[](const ql::ShapeSelector& s, std::int64_t exactly) { return s.incident_face_count(exactly); },
py::kw_only(), py::arg("exactly"))
.def(
"resolve",
[](const ql::ShapeSelector& s, const py::object& scope) {
return shapes_to_py(s.resolve(scope_from_py(scope, s.target_kind())));
},
py::arg("scope"), "The shapes this query picks inside `scope` (a shape or a list of shapes).")
.def("to_dict", [](const ql::ShapeSelector& s) { return dict_of(s.to_value()); })
.def_static("from_dict", [](const Value& payload) { return ql::ShapeSelector::from_value(payload); },
py::arg("data"))
.def("__eq__", [](const ql::ShapeSelector& a, const ql::ShapeSelector& b) { return a == b; }, py::is_operator())
.def("__repr__", [](const ql::ShapeSelector& s) {
return "ShapeSelector(" + std::string(py::repr(dict_of(s.to_value()))) + ")";
});
q.def("edges", [] { return ql::edges(); });
q.def("faces", [] { return ql::faces(); });
q.def("wires", [] { return ql::wires(); });
q.def("vertices", [] { return ql::vertices(); });
q.def("solids", [] { return ql::solids(); });
q.def("shells", [] { return ql::shells(); }, "Select Shell entities from a Shell or compatible topology scope.");
q.def("selector_from_dict", [](const Value& payload) { return ql::selector_from_value(payload); }, py::arg("data"));
}
void bind_query(py::module_& q) {
py::class_<PyQuery>(q, "Query")
.def(py::init([](const py::iterable& items) { return PyQuery{py::list(items)}; }), py::arg("items"))
.def("where", &query_where, py::arg("predicate"))
.def("order_by", &query_order_by, py::arg("key"), py::arg("desc") = false)
.def("limit", &query_limit, py::arg("count"))
.def("first", [](const PyQuery& self) -> py::object { return self.items.empty() ? py::none() : py::object(self.items[0]); })
.def("all", [](const PyQuery& self) { return py::list(self.items); });
q.def("select", [](const py::iterable& items) { return PyQuery{py::list(items)}; }, py::arg("items"),
"Start a QL query over a shape collection or selector scope.");
}
void bind_hooks_and_testing(py::module_& q) {
q.def(
"_set_evidence_provider",
[](const py::object& provider) {
if (provider.is_none()) {
ql::set_evidence_provider({});
return;
}
const auto callable = std::make_shared<PyCallable>(provider);
ql::set_evidence_provider([callable](const ql::EvidenceRequest& request) {
const py::tuple dedup =
py::make_tuple("ql", request.target_kind, request.mode, request.expected, request.matched.size());
const py::object rendered =
callable->get()(scope_to_py(request.scope), shapes_to_py(request.matched), request.target_kind, dedup,
shapes_to_py(request.near_misses));
std::vector<ErrorEvidence> out;
if (!rendered.is_none())
for (const py::handle item : rendered) out.push_back(evidence_from_py(py::reinterpret_borrow<py::object>(item)));
return out;
});
},
py::arg("provider"),
"Install provider(scope, matched, target_kind, dedup_key, near_misses) -> list of evidence dicts; it "
"attaches rendered views to cardinality errors. None removes it.");
py::module_ testing = q.def_submodule("_testing", "raw-OCCT shapes for the QL tests (the operators live elsewhere)");
testing.def("box_at", &box_at, py::arg("origin"), py::arg("dx"), py::arg("dy"), py::arg("dz"));
testing.def("cylinder_at", &cylinder_at, py::arg("base"), py::arg("radius"), py::arg("height"));
testing.def("cut", &cut_solids, py::arg("body"), py::arg("tool"));
testing.def("compound", &compound_of, py::arg("solids"));
}
} // namespace
void bind_ql(py::module_& m) {
py::module_ q = m.def_submodule("ql", "The selector query language: ql.faces().where(...).exactly(1).resolve(shape)");
py::module_::import("sys").attr("modules")[py::str(error_module_name() + ".ql")] = q;
py::class_<MissingType>(q, "_Missing").def("__repr__", [](const MissingType&) { return "MISSING"; });
q.attr("MISSING") = py::cast(MissingType{});
bind_predicate(q);
bind_factories(q);
bind_selector(q);
bind_query(q);
bind_hooks_and_testing(q);
}
+72
View File
@@ -0,0 +1,72 @@
// Python bindings for the reactive area: expressions, units, the operation
// graph and the recording / recomputing session. The work is split over
// bind_reactive_{units,exprs,graph,session}.cpp; this file holds the helpers
// they share and the entry point.
#include "bind_reactive_common.hpp"
#include <cmath>
#include "scad/core/error.hpp"
#include "scad/topo/shape.hpp"
namespace scad::pybind::reactive {
const py::object& numbers_real() {
// Never destroyed: a static py::object would be released after the interpreter has finalized.
PYBIND11_CONSTINIT static py::gil_safe_call_once_and_store<py::object> storage;
return storage.call_once_and_store_result([] { return py::module_::import("numbers").attr("Real"); }).get_stored();
}
double real_number(const py::handle& value, std::string_view label) {
if (PyBool_Check(value.ptr()) || PyObject_IsInstance(value.ptr(), numbers_real().ptr()) != 1) {
throw scad::TypeError(std::string(label) + " must be a real number");
}
const py::object as_float = py::reinterpret_steal<py::object>(PyNumber_Float(value.ptr()));
if (!as_float) {
if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
PyErr_Clear();
throw scad::ValueError(std::string(label) + " must be finite");
}
throw py::error_already_set();
}
return PyFloat_AS_DOUBLE(as_float.ptr());
}
double finite_real(const py::handle& value, std::string_view label) {
const double result = real_number(value, label);
if (!std::isfinite(result)) throw scad::ValueError(std::string(label) + " must be finite");
return result;
}
scad::Bindings bindings_from(const py::object& mapping) {
scad::Bindings out;
if (mapping.is_none()) return out;
for (const auto& item : py::cast<py::dict>(mapping)) {
out[py::cast<std::string>(item.first)] = real_number(item.second, "Binding '" + py::cast<std::string>(item.first) + "'");
}
return out;
}
py::object shape_to_python(const scad::Shape& shape) {
switch (shape.kind()) {
case scad::Kind::Vertex: return py::cast(scad::Vertex(shape));
case scad::Kind::Edge: return py::cast(scad::Edge(shape));
case scad::Kind::Wire: return py::cast(scad::Wire(shape));
case scad::Kind::Face: return py::cast(scad::Face(shape));
case scad::Kind::Shell: return py::cast(scad::Shell(shape));
case scad::Kind::Solid: return py::cast(scad::Solid(shape));
case scad::Kind::Compound: return py::cast(scad::Compound(shape));
}
return py::cast(shape);
}
} // namespace scad::pybind::reactive
void bind_reactive(py::module_& m) {
using namespace scad::pybind::reactive;
bind_reactive_units(m);
bind_reactive_exprs(m);
bind_reactive_graph(m);
bind_reactive_session(m);
bind_reactive_math(m);
}
@@ -0,0 +1,42 @@
// Helpers shared by the bind_reactive*.cpp files.
#pragma once
#include <string>
#include <string_view>
#include "bindings.hpp"
#include "scad/reactive/expr.hpp"
#include "scad/reactive/units.hpp"
#include "scad/topo/shape.hpp"
namespace scad::pybind::reactive {
// numbers.Real (kept alive for the life of the process).
const py::object& numbers_real();
// `_finite_scalar`: a real number (never a bool) that is finite. TypeError
// for anything else, ValueError for NaN / infinity / an int too large for a double.
double finite_real(const py::handle& value, std::string_view label);
// A real number that need not be finite (a unit scale is checked by Unit).
double real_number(const py::handle& value, std::string_view label);
// Mapping[str, float] | None -> Bindings (values must be real numbers).
scad::Bindings bindings_from(const py::object& mapping);
// A Python Unit/str -> Unit (get_unit).
scad::reactive::Unit unit_from(const py::object& value);
// The node of a Python scalar: Var/Const/Expr -> itself, a number -> a Const.
// TypeError for anything else (lift_scalar).
scad::reactive::ScalarPtr lift(const py::handle& value);
// A shape as the Python class of its kind (Solid, Face, ...).
py::object shape_to_python(const scad::Shape& shape);
void bind_reactive_units(py::module_& m);
void bind_reactive_exprs(py::module_& m);
void bind_reactive_graph(py::module_& m);
void bind_reactive_session(py::module_& m);
void bind_reactive_math(py::module_& m);
} // namespace scad::pybind::reactive
@@ -0,0 +1,415 @@
// Const, Var, Expr and their operators; var(), const(), sin() ...; the
// expression graph; canonicalize_params.
#include "bind_reactive_common.hpp"
#include <unordered_set>
#include "scad/core/error.hpp"
#include "scad/reactive/digest.hpp"
#include "scad/reactive/expr.hpp"
#include "scad/reactive/expr_graph.hpp"
namespace scad::pybind::reactive {
namespace sr = scad::reactive;
using sr::Const;
using sr::DimensionTolerance;
using sr::Expr;
using sr::ScalarNode;
using sr::ScalarPtr;
using sr::Var;
ScalarPtr lift(const py::handle& value) {
if (py::isinstance<ScalarNode>(value)) return py::cast<ScalarPtr>(value);
if (PyBool_Check(value.ptr())) throw scad::TypeError("Boolean values are not valid scalar expression inputs");
if (PyLong_Check(value.ptr()) || PyFloat_Check(value.ptr())) return sr::Const::make(real_number(value, "value"));
throw scad::TypeError("Unsupported scalar expression value: " + py::cast<std::string>(py::repr(py::type::of(value))));
}
namespace {
using ExprResult = std::shared_ptr<const Expr>;
ExprResult binary(const char* op, const ScalarPtr& self, const py::handle& other, bool reflected) {
ScalarPtr rhs = lift(other);
return Expr::make(op, reflected ? std::vector<ScalarPtr>{std::move(rhs), self} : std::vector<ScalarPtr>{self, std::move(rhs)});
}
ExprResult unary(const char* op, const ScalarPtr& value) { return Expr::make(op, {value}); }
DimensionTolerance tolerance_from(const py::object& value) {
if (py::isinstance<DimensionTolerance>(value)) return py::cast<DimensionTolerance>(value);
if (PyBool_Check(value.ptr())) throw scad::TypeError("Tolerance must be a real number or a two-value sequence");
if (PyObject_IsInstance(value.ptr(), numbers_real().ptr()) == 1) {
return DimensionTolerance::symmetric(finite_real(value, "deviation"));
}
if (py::isinstance<py::sequence>(value) && !py::isinstance<py::str>(value) && !py::isinstance<py::bytes>(value)) {
const auto seq = py::cast<py::sequence>(value);
if (py::len(seq) != 2) throw scad::ValueError("Asymmetric tolerance must contain exactly two deviations");
return DimensionTolerance(finite_real(seq[0], "lower_deviation"), finite_real(seq[1], "upper_deviation"));
}
throw scad::TypeError("Tolerance must be a real number or a two-value sequence");
}
std::optional<std::string> optional_comment(const py::object& comment) {
if (comment.is_none()) return std::nullopt;
if (!py::isinstance<py::str>(comment)) throw scad::ValueError("Variable comment must be a string when provided");
return py::cast<std::string>(comment);
}
// The editor description from var(...)'s keyword arguments.
sr::ParamUi ui_from(const py::object& ui, const py::object& control, const py::object& min, const py::object& max,
const py::object& step, const py::object& label, const py::object& group) {
sr::ParamUi out;
if (!ui.is_none()) out = sr::parse_ui_comment(py::cast<std::string>(ui));
if (!control.is_none()) out.control = py::cast<std::string>(control);
const auto number = [](const py::object& v, const char* what) {
if (PyBool_Check(v.ptr()) || !(PyLong_Check(v.ptr()) || PyFloat_Check(v.ptr()))) {
throw scad::TypeError(std::string("ui option ") + what + " must be a number");
}
return sr::UiNumber{py::cast<double>(v), PyLong_Check(v.ptr()) != 0};
};
if (!min.is_none()) out.min = number(min, "min");
if (!max.is_none()) out.max = number(max, "max");
if (!step.is_none()) out.step = number(step, "step");
if (!label.is_none()) out.label = py::cast<std::string>(label);
if (!group.is_none()) out.group = py::cast<std::string>(group);
return out;
}
std::shared_ptr<const Var> make_python_var(const py::object& name, const py::object& default_value, const py::object& comment,
const py::object& tolerance, const py::object& unit,
const py::object& tolerance_unit, const std::string& expr_id, sr::ParamUi ui) {
if (!py::isinstance<py::str>(name) || py::cast<std::string>(name).empty()) {
throw scad::ValueError("Variable name must be a non-empty string");
}
sr::VarSpec spec;
spec.name = py::cast<std::string>(name);
spec.default_value = finite_real(default_value, "Variable default");
spec.comment = optional_comment(comment);
if (!tolerance.is_none()) spec.tolerance = tolerance_from(tolerance);
if (!unit.is_none()) spec.unit = unit_from(unit);
if (!tolerance_unit.is_none()) spec.tolerance_unit = unit_from(tolerance_unit);
spec.expr_id = expr_id;
spec.ui = std::move(ui);
return Var::make(std::move(spec));
}
// `bindings` None: the defaults (what Var.evaluate() means).
double evaluate_node(const ScalarPtr& node, const py::object& bindings) {
if (bindings.is_none()) return node->eval(nullptr);
const scad::Bindings values = bindings_from(bindings);
return node->eval(&values);
}
// evaluate_scalar(): what an operator does with a scalar argument -- the active session's edits apply.
double evaluate_operand(const ScalarPtr& node, const py::object& bindings) {
if (bindings.is_none()) return node->eval(scad::ambient_bindings());
return evaluate_node(node, bindings);
}
py::object evaluate_value(const py::object& value, const py::object& bindings) {
if (py::isinstance<py::tuple>(value)) {
py::list items;
for (const auto& item : value) items.append(evaluate_value(py::reinterpret_borrow<py::object>(item), bindings));
return py::tuple(items);
}
if (py::isinstance<py::list>(value)) {
py::list out;
for (const auto& item : value) out.append(evaluate_value(py::reinterpret_borrow<py::object>(item), bindings));
return std::move(out);
}
if (py::isinstance<py::dict>(value)) {
py::dict out;
for (const auto& item : py::cast<py::dict>(value)) {
out[item.first] = evaluate_value(py::reinterpret_borrow<py::object>(item.second), bindings);
}
return std::move(out);
}
const bool scalar = py::isinstance<ScalarNode>(value) || PyLong_Check(value.ptr()) || PyFloat_Check(value.ptr());
if (scalar && !PyBool_Check(value.ptr())) return py::float_(evaluate_operand(lift(value), bindings));
return value;
}
// canonicalize_params for Python structures: tuples stay tuples, lists lists.
struct Canonical {
py::object numeric;
py::object exprs; // None when nothing in `numeric` was symbolic
};
Canonical canonicalize_value(const py::object& value, sr::ExpressionGraph& graph) {
if (py::isinstance<py::tuple>(value) || py::isinstance<py::list>(value)) {
py::list numeric, exprs;
bool any = false;
for (const auto& item : value) {
Canonical c = canonicalize_value(py::reinterpret_borrow<py::object>(item), graph);
numeric.append(c.numeric);
exprs.append(c.exprs);
any = any || !c.exprs.is_none();
}
py::object n = py::isinstance<py::tuple>(value) ? py::object(py::tuple(numeric)) : py::object(numeric);
return {n, any ? py::object(exprs) : py::none()};
}
if (py::isinstance<py::dict>(value)) {
py::dict numeric, exprs;
for (const auto& item : py::cast<py::dict>(value)) {
Canonical c = canonicalize_value(py::reinterpret_borrow<py::object>(item.second), graph);
numeric[py::str(item.first)] = c.numeric;
if (!c.exprs.is_none()) exprs[py::str(item.first)] = c.exprs;
}
return {numeric, py::len(exprs) > 0 ? py::object(exprs) : py::none()};
}
if (py::isinstance<ScalarNode>(value)) {
const ScalarPtr registered = graph.register_expr(py::cast<ScalarPtr>(value));
py::dict ref;
ref["expr_id"] = registered->expr_id();
return {py::float_(registered->eval(nullptr)), ref};
}
if ((PyLong_Check(value.ptr()) || PyFloat_Check(value.ptr())) && !PyBool_Check(value.ptr())) {
return {py::float_(py::cast<double>(value)), py::none()};
}
return {value, py::none()};
}
} // namespace
void bind_reactive_exprs(py::module_& m) {
py::class_<DimensionTolerance>(m, "DimensionTolerance")
.def(py::init([](const py::object& lower, const py::object& upper) {
return DimensionTolerance(finite_real(lower, "lower_deviation"), finite_real(upper, "upper_deviation"));
}),
py::arg("lower_deviation"), py::arg("upper_deviation"))
.def_static("symmetric", [](const py::object& deviation) {
return DimensionTolerance::symmetric(finite_real(deviation, "deviation"));
})
.def_property_readonly("lower_deviation", &DimensionTolerance::lower_deviation)
.def_property_readonly("upper_deviation", &DimensionTolerance::upper_deviation)
.def_property_readonly("width", &DimensionTolerance::width)
.def("to_dict", [](const DimensionTolerance& t) { return value_to_python(t.to_value()); })
.def_static("from_dict", [](const py::object& data) { return DimensionTolerance::from_value(value_from_python(data)); })
.def("__eq__", [](const DimensionTolerance& a, const py::object& b) {
return py::isinstance<DimensionTolerance>(b) && a == py::cast<DimensionTolerance>(b);
})
.def("__hash__", [](const DimensionTolerance& t) {
return std::hash<double>{}(t.lower_deviation()) * 31 + std::hash<double>{}(t.upper_deviation());
})
.def("__repr__", [](const DimensionTolerance& t) {
return "DimensionTolerance(lower_deviation=" + sr::py_float_repr(t.lower_deviation()) +
", upper_deviation=" + sr::py_float_repr(t.upper_deviation()) + ")";
});
// ExprBase holds the shared node; Const / Var / Expr are its three kinds.
py::class_<scad::ExprNode, py::smart_holder>(m, "_ExprNode");
py::class_<ScalarNode, scad::ExprNode, py::smart_holder> base(m, "ExprBase");
base.def_property_readonly("expr_id", &ScalarNode::expr_id)
.def("evaluate", [](const ScalarPtr& self, const py::object& bindings) { return evaluate_node(self, bindings); },
py::arg("bindings") = py::none())
.def("__float__", [](const ScalarPtr& self) { return self->eval(nullptr); })
.def("__bool__", [](const ScalarPtr&) -> bool {
throw scad::TypeError("Expression objects do not define truthiness. Evaluate them explicitly first.");
})
.def("__add__", [](const ScalarPtr& s, const py::object& o) { return binary("add", s, o, false); }, py::is_operator())
.def("__radd__", [](const ScalarPtr& s, const py::object& o) { return binary("add", s, o, true); }, py::is_operator())
.def("__sub__", [](const ScalarPtr& s, const py::object& o) { return binary("sub", s, o, false); }, py::is_operator())
.def("__rsub__", [](const ScalarPtr& s, const py::object& o) { return binary("sub", s, o, true); }, py::is_operator())
.def("__mul__", [](const ScalarPtr& s, const py::object& o) { return binary("mul", s, o, false); }, py::is_operator())
.def("__rmul__", [](const ScalarPtr& s, const py::object& o) { return binary("mul", s, o, true); }, py::is_operator())
.def("__truediv__", [](const ScalarPtr& s, const py::object& o) { return binary("div", s, o, false); }, py::is_operator())
.def("__rtruediv__", [](const ScalarPtr& s, const py::object& o) { return binary("div", s, o, true); }, py::is_operator())
.def("__pow__", [](const ScalarPtr& s, const py::object& o) { return binary("pow", s, o, false); }, py::is_operator())
.def("__rpow__", [](const ScalarPtr& s, const py::object& o) { return binary("pow", s, o, true); }, py::is_operator())
.def("__neg__", [](const ScalarPtr& s) { return unary("neg", s); })
.def("__abs__", [](const ScalarPtr& s) { return unary("abs", s); })
.def("__eq__", [](const ScalarPtr& s, const py::object& o) {
return py::isinstance<ScalarNode>(o) && sr::same_expression(*s, *py::cast<ScalarPtr>(o));
})
.def("__hash__", [](const ScalarPtr& s) { return std::hash<std::string>{}(s->expr_id()); })
.def("__repr__", [](const ScalarPtr& s) { return s->repr(); });
py::class_<Const, ScalarNode, py::smart_holder>(m, "Const")
.def(py::init([](const py::object& value, const std::string& expr_id) {
return std::const_pointer_cast<Const>(Const::make(finite_real(value, "value"), expr_id));
}),
py::arg("value"), py::arg("expr_id") = "")
.def_property_readonly("value", &Const::value);
py::class_<Var, ScalarNode, py::smart_holder>(m, "Var")
.def(py::init([](const py::object& name, const py::object& default_value, const py::object& comment,
const std::string& expr_id, const py::object& tolerance, const py::object& unit,
const py::object& tolerance_unit, const py::object& ui, const py::object& control,
const py::object& min, const py::object& max, const py::object& step, const py::object& label,
const py::object& group) {
return std::const_pointer_cast<Var>(make_python_var(name, default_value, comment, tolerance, unit,
tolerance_unit, expr_id,
ui_from(ui, control, min, max, step, label, group)));
}),
py::arg("name"), py::arg("default"), py::arg("comment") = py::none(), py::arg("expr_id") = "",
py::arg("tolerance") = py::none(), py::arg("unit") = py::none(), py::arg("tolerance_unit") = py::none(),
py::kw_only(), py::arg("ui") = py::none(), py::arg("control") = py::none(), py::arg("min") = py::none(),
py::arg("max") = py::none(), py::arg("step") = py::none(), py::arg("label") = py::none(),
py::arg("group") = py::none())
.def_property_readonly("name", &Var::name)
.def_property_readonly("default", &Var::default_value)
.def_property_readonly("comment", [](const Var& v) -> py::object {
return v.comment() ? py::object(py::str(*v.comment())) : py::none();
})
.def_property_readonly("tolerance", [](const Var& v) -> py::object {
return v.tolerance() ? py::cast(*v.tolerance()) : py::none();
})
.def_property_readonly("unit", [](const Var& v) -> py::object { return v.unit() ? py::cast(*v.unit()) : py::none(); })
.def_property_readonly("tolerance_unit", [](const Var& v) -> py::object {
return v.tolerance_unit() ? py::cast(*v.tolerance_unit()) : py::none();
})
.def_property_readonly("dimension", [](const Var& v) -> py::object {
return v.dimension() ? py::cast(*v.dimension()) : py::none();
})
.def_property_readonly("canonical_default", &Var::canonical_default)
.def_property_readonly("canonical_tolerance", [](const Var& v) -> py::object {
const auto t = v.canonical_tolerance();
return t ? py::cast(*t) : py::none();
})
.def_property_readonly("ui", [](const Var& v) { return value_to_python(v.param_spec().to_value()); })
.def("param_spec", [](const Var& v) { return value_to_python(v.param_spec().to_value()); })
.def("with_default", [](const Var& v, const py::object& value) { return v.with_default(finite_real(value, "Variable default")); })
.def("replace", [](const Var& v, const py::kwargs& changes) {
// dataclasses.replace: every field kept unless given; expr_id included.
const py::object none = py::none();
const auto get = [&](const char* key, const py::object& fallback) {
return changes.contains(key) ? py::reinterpret_borrow<py::object>(changes[key]) : fallback;
};
for (const auto& item : changes) {
const std::string key = py::cast<std::string>(item.first);
static const std::unordered_set<std::string> allowed{"name", "default", "comment", "expr_id", "tolerance",
"unit", "tolerance_unit"};
if (allowed.count(key) == 0) throw scad::TypeError("Var.replace() got an unexpected field '" + key + "'");
}
const py::object current_tolerance = v.tolerance() ? py::cast(*v.tolerance()) : none;
const py::object current_unit = v.unit() ? py::cast(*v.unit()) : none;
const py::object current_tol_unit = v.tolerance_unit() ? py::cast(*v.tolerance_unit()) : none;
const py::object current_comment = v.comment() ? py::object(py::str(*v.comment())) : none;
return make_python_var(get("name", py::str(v.name())), get("default", py::float_(v.default_value())),
get("comment", current_comment), get("tolerance", current_tolerance),
get("unit", current_unit), get("tolerance_unit", current_tol_unit),
py::cast<std::string>(get("expr_id", py::str(v.expr_id()))), v.ui());
});
py::class_<Expr, ScalarNode, py::smart_holder>(m, "Expr")
.def(py::init([](const std::string& op, const py::object& args, const std::string& expr_id) {
std::vector<ScalarPtr> nodes;
for (const auto& arg : args) {
if (!py::isinstance<ScalarNode>(arg)) throw scad::TypeError("Expression arguments must be scalar expression nodes");
nodes.push_back(py::cast<ScalarPtr>(arg));
}
return std::const_pointer_cast<Expr>(Expr::make(op, std::move(nodes), expr_id));
}),
py::arg("op"), py::arg("args"), py::arg("expr_id") = "")
.def_property_readonly("op", &Expr::op)
.def_property_readonly("args", [](const Expr& e) {
py::tuple out(e.args().size());
for (std::size_t i = 0; i < e.args().size(); ++i) out[i] = py::cast(e.args()[i]);
return out;
});
m.def("const", [](const py::object& value) { return sr::make_const(finite_real(value, "Constant value")); }, py::arg("value"));
m.def("var", [](const py::object& name, const py::object& default_value, const py::object& comment,
const py::object& tolerance, const py::object& unit, const py::object& tolerance_unit,
const py::object& ui, const py::object& control, const py::object& min, const py::object& max,
const py::object& step, const py::object& label, const py::object& group) {
return make_python_var(name, default_value, comment, tolerance, unit, tolerance_unit, "",
ui_from(ui, control, min, max, step, label, group));
},
py::arg("name"), py::arg("default"), py::arg("comment") = py::none(), py::arg("tolerance") = py::none(),
py::kw_only(), py::arg("unit") = py::none(), py::arg("tolerance_unit") = py::none(), py::arg("ui") = py::none(),
py::arg("control") = py::none(), py::arg("min") = py::none(), py::arg("max") = py::none(),
py::arg("step") = py::none(), py::arg("label") = py::none(), py::arg("group") = py::none(),
"Create a physical or legacy scalar variable.\n\n"
"`ui` (the text of a `# ui:` comment) or control/min/max/step/label/group describe the slider, number box\n"
"or toggle an editor shows for it.");
const struct {
const char* name;
const char* op;
} functions[] = {{"sin", "sin"}, {"cos", "cos"}, {"tan", "tan"}, {"sqrt", "sqrt"},
{"acos", "acos"}, {"asin", "asin"}, {"atan", "atan"}};
for (const auto& fn : functions) {
const std::string op = fn.op;
m.def(fn.name, [op](const py::object& value) { return Expr::make(op, {lift(value)}); }, py::arg("value"));
}
m.def("atan2", [](const py::object& y, const py::object& x) { return Expr::make("atan2", {lift(y), lift(x)}); },
py::arg("y"), py::arg("x"));
m.def("lift_scalar", [](const py::object& value) { return lift(value); }, py::arg("value"));
m.def("evaluate_scalar", [](const py::object& value, const py::object& bindings) { return evaluate_operand(lift(value), bindings); },
py::arg("value"), py::arg("bindings") = py::none(),
"The number a scalar stands for: defaults, the active GraphSession's variable edits, or `bindings`.");
m.def("evaluate_value", &evaluate_value, py::arg("value"), py::arg("bindings") = py::none());
m.def("infer_dimension", [](const py::object& value) -> py::object {
const auto dimension = sr::infer_dimension(lift(value));
return dimension ? py::cast(*dimension) : py::none();
}, py::arg("value"));
m.def("expression_uses_units", [](const py::object& value) { return sr::expression_uses_units(lift(value)); }, py::arg("value"));
py::class_<sr::ExpressionGraph>(m, "ExpressionGraph")
.def(py::init<>())
.def_property_readonly("node_count", &sr::ExpressionGraph::node_count)
.def("get", [](const sr::ExpressionGraph& g, const std::string& id) -> py::object {
const ScalarPtr node = g.get(id);
return node ? py::cast(node) : py::none();
}, py::arg("expr_id"))
.def("register", [](sr::ExpressionGraph& g, const py::object& value) { return g.register_expr(lift(value)); },
py::arg("value"))
.def("to_dict", [](const sr::ExpressionGraph& g) { return value_to_python(g.to_value()); })
.def_static("from_dict", [](const py::object& data) { return sr::ExpressionGraph::from_value(value_from_python(data)); });
m.def("canonicalize_params", [](const py::object& params, sr::ExpressionGraph& graph) {
py::dict numeric, exprs;
if (!params.is_none()) {
for (const auto& item : py::cast<py::dict>(params)) {
const std::string key = py::cast<std::string>(py::str(item.first));
if (sr::is_discrete_param_name(key)) {
numeric[py::str(key)] = item.second;
continue;
}
Canonical c = canonicalize_value(py::reinterpret_borrow<py::object>(item.second), graph);
numeric[py::str(key)] = c.numeric;
if (!c.exprs.is_none()) exprs[py::str(key)] = c.exprs;
}
}
return py::make_tuple(numeric, exprs);
}, py::arg("params"), py::arg("expression_graph"));
m.def("referenced_expressions", [](const py::object& param_exprs, const sr::ExpressionGraph& graph) {
const std::vector<ScalarPtr> found = sr::referenced_expressions(value_from_python(param_exprs), graph);
py::tuple out(found.size());
for (std::size_t i = 0; i < found.size(); ++i) out[i] = py::cast(found[i]);
return out;
}, py::arg("param_exprs"), py::arg("expression_graph"));
m.def("parse_ui_comment", [](const std::string& text) {
const sr::ParamUi ui = sr::parse_ui_comment(text);
const sr::ParamSpec spec = sr::make_param_spec("", sr::ParamKind::Float, Value(0.0), ui);
Value out = Value::object();
out.set("control", ui.control.empty() ? Value() : Value(ui.control));
out.set("min", ui.min ? ui.min->to_value() : Value());
out.set("max", ui.max ? ui.max->to_value() : Value());
out.set("step", ui.step ? ui.step->to_value() : Value());
out.set("unit", ui.unit ? Value(*ui.unit) : Value());
out.set("label", ui.label ? Value(*ui.label) : Value());
Value issues = Value::array();
for (const std::string& issue : ui.issues) issues.push_back(issue);
out.set("issues", issues);
(void)spec;
return value_to_python(out);
}, py::arg("text"), "Parse the text of a `# ui:` comment (slider(1, 5, step=1, unit='mm')).");
m.def("make_param_spec", [](const std::string& name, const std::string& kind, const py::object& default_value,
const py::object& ui, const std::string& declared) {
sr::ParamKind k = sr::ParamKind::Float;
if (kind == "int") k = sr::ParamKind::Int;
else if (kind == "bool") k = sr::ParamKind::Bool;
else if (kind != "float") throw scad::ValueError("kind must be 'float', 'int' or 'bool'");
const sr::ParamUi parsed = ui.is_none() ? sr::ParamUi{} : sr::parse_ui_comment(py::cast<std::string>(ui));
return value_to_python(sr::make_param_spec(name, k, value_from_python(default_value), parsed, declared).to_value());
}, py::arg("name"), py::arg("kind"), py::arg("default"), py::arg("ui") = py::none(), py::arg("declared") = "literal");
}
} // namespace scad::pybind::reactive
@@ -0,0 +1,307 @@
// OperationNode, OperationGraph, FrameNode/FrameGraph, upstream_closure.
#include "bind_reactive_common.hpp"
#include <algorithm>
#include <memory>
#include <mutex>
#include <unordered_map>
#include <pybind11/eval.h>
#include "scad/core/error.hpp"
#include "scad/reactive/errors.hpp"
#include "scad/reactive/frame.hpp"
#include "scad/reactive/graph.hpp"
namespace scad::pybind::reactive {
namespace sr = scad::reactive;
using sr::FrameGraph;
using sr::FrameNode;
using sr::NodePtr;
using sr::OperationGraph;
using sr::OperationNode;
namespace {
// Nodes restored from pickles, by (graph_id, node_id): marimo pickles every cell variable separately; two
// variables that shared a node before pickling share one node after loading. Weak, so a node nobody holds goes.
NodePtr share_restored(const NodePtr& node) {
static std::mutex mutex;
static std::unordered_map<std::string, std::weak_ptr<const OperationNode>> restored;
const std::string key = node->graph_id + '\x1f' + node->node_id;
const std::lock_guard<std::mutex> lock(mutex);
if (restored.size() > 4096) { // drop what has gone
for (auto it = restored.begin(); it != restored.end();) it = it->second.expired() ? restored.erase(it) : std::next(it);
}
if (const auto found = restored.find(key); found != restored.end()) {
if (const NodePtr existing = found->second.lock()) {
// A twin must hold the very same input objects: an input that was replaced by a newer version makes
// every node downstream of it a new version too.
const bool same_inputs = existing->inputs.size() == node->inputs.size() &&
std::equal(existing->inputs.begin(), existing->inputs.end(), node->inputs.begin());
if (same_inputs && sr::same_node_content(*existing, *node)) return existing;
}
}
restored[key] = node;
return node;
}
const char* kStaleSource = R"PY(
class StaleLineageError(ValueError):
"""Two different operations carry the same node id."""
def __init__(self, node_id):
super().__init__(
f"node '{node_id}' exists in two different versions (stale lineage); "
"re-run the cells that produced these values"
)
self.node_id = node_id
)PY";
py::tuple vec_tuple(const scad::Vec3& v) { return py::make_tuple(v.x, v.y, v.z); }
NodePtr node_from(const py::handle& value) {
if (!py::isinstance<OperationNode>(value)) throw scad::TypeError("expected an OperationNode");
return py::cast<NodePtr>(value);
}
std::vector<NodePtr> nodes_from(const py::object& items) {
std::vector<NodePtr> out;
if (items.is_none()) return out;
for (const auto& item : items) out.push_back(node_from(item));
return out;
}
Value value_or_empty(const py::object& obj) { return obj.is_none() ? Value::object() : value_from_python(obj); }
sr::FrameNode frame_from(const py::object& obj) { return py::cast<FrameNode>(obj); }
} // namespace
void bind_reactive_graph(py::module_& m) {
py::dict scope;
py::exec(kStaleSource, scope);
m.attr("StaleLineageError") = scope["StaleLineageError"];
py::register_exception_translator([](std::exception_ptr p) {
try {
if (p) std::rethrow_exception(p);
} catch (const sr::StaleLineageError& e) {
py::object cls = py::module_::import("simplecadapi._cpp._native").attr("StaleLineageError");
PyErr_SetObject(cls.ptr(), cls(e.node_id()).ptr());
}
});
py::class_<FrameNode>(m, "FrameNode")
.def(py::init([](const std::string& frame_id, const scad::Vec3& origin, const scad::Vec3& x_axis,
const scad::Vec3& y_axis, const scad::Vec3& z_axis, const py::object& parent, const py::object& metadata) {
FrameNode node{frame_id, origin, x_axis, y_axis, z_axis, std::nullopt, value_or_empty(metadata)};
if (!parent.is_none()) node.parent_frame_id = py::cast<std::string>(parent);
return node;
}),
py::arg("frame_id"), py::arg("origin"), py::arg("x_axis"), py::arg("y_axis"), py::arg("z_axis"),
py::arg("parent_frame_id") = py::none(), py::arg("metadata") = py::none())
.def_readonly("frame_id", &FrameNode::frame_id)
.def_property_readonly("origin", [](const FrameNode& f) { return vec_tuple(f.origin); })
.def_property_readonly("x_axis", [](const FrameNode& f) { return vec_tuple(f.x_axis); })
.def_property_readonly("y_axis", [](const FrameNode& f) { return vec_tuple(f.y_axis); })
.def_property_readonly("z_axis", [](const FrameNode& f) { return vec_tuple(f.z_axis); })
.def_property_readonly("parent_frame_id", [](const FrameNode& f) -> py::object {
return f.parent_frame_id ? py::object(py::str(*f.parent_frame_id)) : py::none();
})
.def_property_readonly("metadata", [](const FrameNode& f) { return value_to_python(f.metadata); })
.def("__eq__", [](const FrameNode& a, const py::object& b) { return py::isinstance<FrameNode>(b) && a == py::cast<FrameNode>(b); });
py::class_<FrameGraph>(m, "FrameGraph")
.def(py::init<>())
.def_property_readonly("node_count", &FrameGraph::node_count)
.def("add", [](FrameGraph& g, const py::object& node) {
g.add(frame_from(node));
return node; // the node that was passed, like the Python SDK
}, py::arg("node"))
.def("ensure_frame", [](FrameGraph& g, const std::string& id, const scad::Vec3& origin, const scad::Vec3& x_axis,
const scad::Vec3& y_axis, const scad::Vec3& z_axis, const py::object& parent,
const py::object& metadata) {
return g.ensure_frame(id, origin, x_axis, y_axis, z_axis,
parent.is_none() ? std::nullopt : std::optional<std::string>(py::cast<std::string>(parent)),
value_or_empty(metadata));
},
py::arg("frame_id"), py::kw_only(), py::arg("origin"), py::arg("x_axis"), py::arg("y_axis"), py::arg("z_axis"),
py::arg("parent_frame_id") = py::none(), py::arg("metadata") = py::none())
.def("to_dict", [](const FrameGraph& g) {
py::object data = value_to_python(g.to_value());
// Each frame's vectors are tuples of floats, as the SDK's FrameNode holds them.
if (data.contains("nodes"))
for (const py::handle node : data["nodes"])
for (const char* key : {"origin", "x_axis", "y_axis", "z_axis"})
if (node.contains(key) && py::isinstance<py::list>(node[key])) node[key] = py::tuple(node[key]);
return data;
})
.def_static("from_dict", [](const py::object& data) { return FrameGraph::from_value(value_from_python(data)); });
py::class_<OperationNode, py::smart_holder>(m, "OperationNode")
// A node outside any graph (pickle restore, tests): the fields of the SDK's OperationNode dataclass, in its order.
.def(py::init([](const std::string& node_id, const std::string& op, const py::object& params,
const py::object& param_exprs, const py::object& inputs, const py::object& context,
int output_count, const py::object& semantic_delta, const py::object& topo_delta,
const py::object& tags, const py::object& graph_id, const py::object& source,
const py::object& expressions, const py::object& frame) {
auto node = std::make_shared<OperationNode>();
node->node_id = node_id;
node->op = op;
node->params = value_or_empty(params);
node->param_exprs = value_or_empty(param_exprs);
node->inputs = nodes_from(inputs);
for (const NodePtr& input : node->inputs) node->bindings.push_back(sr::InputBinding{input->node_id, 0, {}});
if (!context.is_none()) node->context = value_from_python(context);
node->output_count = output_count;
if (!semantic_delta.is_none()) node->semantic_delta = py::cast<scad::SemanticDelta>(semantic_delta);
if (!topo_delta.is_none()) node->topo_delta = scad::topo_delta_from_value(value_from_python(topo_delta));
if (!tags.is_none())
for (const auto& tag : tags) node->tags.insert(py::cast<std::string>(tag));
if (!graph_id.is_none()) node->graph_id = py::cast<std::string>(graph_id);
if (!source.is_none()) node->source = value_from_python(source);
if (!expressions.is_none())
for (const auto& e : expressions) node->expressions.push_back(lift(e));
if (!frame.is_none()) node->frame = frame_from(frame);
return std::shared_ptr<const OperationNode>(std::move(node));
}),
py::arg("node_id"), py::arg("op"), py::arg("params") = py::none(), py::arg("param_exprs") = py::none(),
py::arg("inputs") = py::none(), py::arg("context") = py::none(), py::arg("output_count") = 1,
py::arg("semantic_delta") = py::none(), py::arg("topo_delta") = py::none(), py::arg("tags") = py::none(),
py::arg("graph_id") = py::none(), py::arg("source") = py::none(), py::arg("expressions") = py::none(),
py::arg("frame") = py::none())
.def_property_readonly("node_id", [](const OperationNode& n) { return n.node_id; })
.def_property_readonly("op", [](const OperationNode& n) { return n.op; })
.def_property_readonly("params", [](const OperationNode& n) { return value_to_python(n.params); })
.def_property_readonly("param_exprs", [](const OperationNode& n) { return value_to_python(n.param_exprs); })
.def_property_readonly("inputs", [](const OperationNode& n) {
py::tuple out(n.inputs.size());
for (std::size_t i = 0; i < n.inputs.size(); ++i) out[i] = py::cast(n.inputs[i]);
return out;
})
.def_property_readonly("input_bindings", [](const OperationNode& n) {
py::list out;
for (const sr::InputBinding& b : n.bindings) out.append(py::make_tuple(b.external() ? py::object(py::none()) : py::object(py::str(b.node_id)), b.output_slot, b.role));
return out;
})
.def_property_readonly("context", [](const OperationNode& n) -> py::object {
if (!n.context) return py::none();
py::object context = value_to_python(*n.context);
// The SDK's context snapshot holds each frame axis as a tuple of floats.
if (py::isinstance<py::dict>(context)) {
for (const char* key : {"origin", "x_axis", "y_axis", "z_axis"}) {
if (context.contains(key) && py::isinstance<py::list>(context[key])) context[key] = py::tuple(context[key]);
}
}
return context;
})
.def_property_readonly("output_count", [](const OperationNode& n) { return n.output_count; })
.def_property_readonly("topo_delta", [](const OperationNode& n) -> py::object {
return n.topo_delta ? value_to_python(scad::to_value(*n.topo_delta)) : py::none();
})
.def_property_readonly("semantic_delta", [](const OperationNode& n) -> py::object {
return n.semantic_delta ? py::cast(*n.semantic_delta) : py::none().cast<py::object>();
})
.def_property_readonly("tags", [](const OperationNode& n) { return py::frozenset(py::cast(n.tags)); })
.def_property_readonly("graph_id", [](const OperationNode& n) { return n.graph_id; })
.def_property_readonly("source", [](const OperationNode& n) { return n.source ? value_to_python(*n.source) : py::none().cast<py::object>(); })
.def_property_readonly("expressions", [](const OperationNode& n) {
py::tuple out(n.expressions.size());
for (std::size_t i = 0; i < n.expressions.size(); ++i) out[i] = py::cast(n.expressions[i]);
return out;
})
.def_property_readonly("symbolic", [](const OperationNode& n) {
py::dict out;
for (const auto& [path, scalar] : n.symbolic) out[py::str(path)] = py::cast(scalar);
return out;
})
.def_property_readonly("frame", [](const OperationNode& n) -> py::object { return n.frame ? py::cast(*n.frame) : py::none(); })
.def("__eq__", [](const OperationNode& a, const py::object& b) {
return py::isinstance<OperationNode>(b) && sr::same_node_content(a, *py::cast<NodePtr>(b));
})
.def_static("_share_restored", [](const py::object& node) { return share_restored(node_from(node)); }, py::arg("node"),
"The live node restored from a pickle that is the twin of `node`, or `node` itself, registered as one.")
.def("__hash__", [](const OperationNode& n) { return std::hash<std::string>{}(n.node_id); })
.def("__repr__", [](const OperationNode& n) { return "OperationNode(node_id='" + n.node_id + "', op='" + n.op + "')"; });
py::class_<OperationGraph>(m, "OperationGraph")
.def(py::init([](const py::object& graph_id, const py::object& ns) {
return OperationGraph(graph_id.is_none() ? std::string{} : py::cast<std::string>(graph_id),
ns.is_none() ? std::nullopt : std::optional<std::string>(py::cast<std::string>(ns)));
}),
py::arg("graph_id") = py::none(), py::kw_only(), py::arg("namespace") = py::none())
.def_property_readonly("graph_id", &OperationGraph::graph_id)
.def_property_readonly("namespace", [](const OperationGraph& g) -> py::object {
return g.ns() ? py::object(py::str(*g.ns())) : py::none();
})
.def("namespaced", &OperationGraph::namespaced, py::arg("prefix"))
.def("allocate_node_id", &OperationGraph::allocate_node_id, py::arg("prefix") = "node")
.def("add_node", [](OperationGraph& g, const std::string& op, const py::object& params, const py::object& param_exprs,
const py::object& inputs, const py::object& node_id, int output_count, const py::object& context,
const py::object& tags, const py::object& source, const py::object& expressions,
const py::object& frame, const py::object& semantic_delta) {
sr::NodeSpec spec;
spec.op = op;
spec.params = value_or_empty(params);
spec.param_exprs = value_or_empty(param_exprs);
spec.inputs = nodes_from(inputs);
for (const NodePtr& input : spec.inputs) spec.bindings.push_back(sr::InputBinding{input->node_id, 0, {}});
if (!node_id.is_none()) spec.node_id = py::cast<std::string>(node_id);
spec.output_count = output_count;
if (!context.is_none()) spec.context = value_from_python(context);
if (!tags.is_none()) {
for (const auto& tag : tags) spec.tags.insert(py::cast<std::string>(tag));
}
if (!source.is_none()) spec.source = value_from_python(source);
if (!expressions.is_none()) {
for (const auto& e : expressions) spec.expressions.push_back(lift(e));
}
if (!frame.is_none()) spec.frame = frame_from(frame);
if (!semantic_delta.is_none()) spec.semantic_delta = py::cast<scad::SemanticDelta>(semantic_delta);
return g.add_node(std::move(spec));
},
py::arg("op"), py::arg("params") = py::none(), py::arg("param_exprs") = py::none(), py::arg("inputs") = py::none(),
py::arg("node_id") = py::none(), py::arg("output_count") = 1, py::arg("context") = py::none(),
py::arg("tags") = py::none(), py::arg("source") = py::none(), py::arg("expressions") = py::none(),
py::arg("frame") = py::none(), py::arg("semantic_delta") = py::none())
.def("adopt", [](OperationGraph& g, const py::object& node) { return g.adopt(node_from(node)); }, py::arg("node"))
.def("get_node", [](const OperationGraph& g, const std::string& id) -> py::object {
const NodePtr node = g.get_node(id);
return node ? py::cast(node) : py::none();
}, py::arg("node_id"))
.def_property_readonly("nodes", [](const OperationGraph& g) { return py::cast(g.nodes()); })
.def_property_readonly("node_count", &OperationGraph::node_count)
.def_property_readonly("edges", [](const OperationGraph& g) { return py::set(py::cast(g.edges())); })
.def_property_readonly("edge_count", &OperationGraph::edge_count)
.def("upstream_nodes", &OperationGraph::upstream_nodes, py::arg("node_id"))
.def("downstream_nodes", &OperationGraph::downstream_nodes, py::arg("node_id"))
.def("root_nodes", &OperationGraph::root_nodes)
.def("leaf_nodes", &OperationGraph::leaf_nodes)
.def("is_dag", &OperationGraph::is_dag)
.def("topological_order", &OperationGraph::topological_order)
.def("to_dict", [](const OperationGraph& g) { return value_to_python(g.to_value()); })
.def("to_json", &OperationGraph::to_json, py::arg("indent") = 2)
.def_static("from_dict", [](const py::object& data, bool strict, const py::object& expression_graph,
const py::object& frame_graph) {
const sr::ExpressionGraph* expressions = expression_graph.is_none() ? nullptr : &py::cast<const sr::ExpressionGraph&>(expression_graph);
const sr::FrameGraph* frames = frame_graph.is_none() ? nullptr : &py::cast<const sr::FrameGraph&>(frame_graph);
return OperationGraph::from_value(value_from_python(data), strict, expressions, frames);
}, py::arg("data"), py::kw_only(), py::arg("strict") = true, py::arg("expression_graph") = py::none(),
py::arg("frame_graph") = py::none())
.def_static("from_json", [](const std::string& text, bool strict) {
return OperationGraph::from_value(value_from_python(py::module_::import("json").attr("loads")(text)), strict);
}, py::arg("json_str"), py::kw_only(), py::arg("strict") = true);
m.def("set_producer_version", [](const std::string& version) { scad::reactive::set_producer_version(version); }, py::arg("version"));
m.def("upstream_closure", [](const py::object& roots, const py::object& stop_at) {
std::function<bool(const NodePtr&)> stop;
if (!stop_at.is_none()) stop = [stop_at](const NodePtr& node) { return py::cast<bool>(stop_at(py::cast(node))); };
return sr::upstream_closure(nodes_from(roots), stop);
}, py::arg("roots"), py::kw_only(), py::arg("stop_at") = py::none());
m.def("same_node_content", [](const py::object& a, const py::object& b) {
return sr::same_node_content(*node_from(a), *node_from(b));
}, py::arg("first"), py::arg("second"));
}
} // namespace scad::pybind::reactive
@@ -0,0 +1,104 @@
// simplecadapi.math: fit_cubic_bspline_control_points and BSplineFitResult.
#include "bind_reactive_common.hpp"
#include "scad/core/error.hpp"
#include <cmath>
#include "scad/reactive/bspline_fit.hpp"
namespace scad::pybind::reactive {
namespace sr = scad::reactive;
namespace {
double as_float(const py::handle& value) {
const py::object number = py::reinterpret_steal<py::object>(PyNumber_Float(value.ptr()));
if (!number) throw py::error_already_set();
return PyFloat_AS_DOUBLE(number.ptr());
}
py::tuple tuple_of(const std::vector<double>& values) {
py::tuple out(values.size());
for (std::size_t i = 0; i < values.size(); ++i) out[i] = values[i];
return out;
}
} // namespace
void bind_reactive_math(py::module_& m) {
py::module_ math = m.def_submodule("math", "Math helpers for CAD-friendly curve parameterization.");
// Importable as <package>.math, like simplecadapi.math.
const std::string qualified = scad::error_module_name() + ".math";
math.attr("__name__") = qualified;
py::module_::import("sys").attr("modules")[py::str(qualified)] = math;
const auto bind_into = [](py::module_& target) {
py::class_<sr::BSplineFit>(target, "BSplineFitResult")
.def_readonly("degree", &sr::BSplineFit::degree)
.def_property_readonly("control_points", [](const sr::BSplineFit& f) {
py::tuple out(f.control_points.size());
for (std::size_t i = 0; i < f.control_points.size(); ++i) out[i] = tuple_of(f.control_points[i]);
return out;
})
.def_property_readonly("knots", [](const sr::BSplineFit& f) { return tuple_of(f.knots); })
.def_property_readonly("sample_parameters", [](const sr::BSplineFit& f) { return tuple_of(f.sample_parameters); })
.def_readonly("max_error", &sr::BSplineFit::max_error)
.def_readonly("rms_error", &sr::BSplineFit::rms_error)
.def_readonly("tolerance", &sr::BSplineFit::tolerance)
.def_readonly("fairing", &sr::BSplineFit::fairing)
.def_readonly("iterations", &sr::BSplineFit::iterations)
.def_readonly("converged", &sr::BSplineFit::converged)
.def_property_readonly("control_count", &sr::BSplineFit::control_count)
.def_property_readonly("dimension", &sr::BSplineFit::dimension)
.def_property_readonly("unique_knots", [](const sr::BSplineFit& f) { return tuple_of(f.unique_knots()); })
.def_property_readonly("multiplicities", [](const sr::BSplineFit& f) {
const std::vector<int> values = f.multiplicities();
py::tuple out(values.size());
for (std::size_t i = 0; i < values.size(); ++i) out[i] = values[i];
return out;
})
.def("evaluate", [](const sr::BSplineFit& f, const py::object& parameter) { return tuple_of(f.evaluate(as_float(parameter))); },
py::arg("parameter"))
.def("to_dict", [](const sr::BSplineFit& f) { return value_to_python(f.to_value()); });
target.def("fit_cubic_bspline_control_points",
[](const py::object& sample_points, const py::object& tolerance, const py::object& max_control_points,
const py::object& fairing, const py::object& duplicate_tolerance, const py::object& knot_tolerance,
bool raise_on_failure) {
sr::BSplineFitOptions options;
options.tolerance = as_float(tolerance);
options.fairing = as_float(fairing);
options.knot_tolerance = as_float(knot_tolerance);
options.duplicate_tolerance = as_float(duplicate_tolerance);
if (!max_control_points.is_none()) options.max_control_points = py::cast<int>(max_control_points);
options.raise_on_failure = raise_on_failure;
if (options.tolerance <= 0.0 || !std::isfinite(options.tolerance)) {
throw scad::ValueError("tolerance must be a finite positive number");
}
std::vector<std::vector<double>> samples;
std::size_t index = 0;
for (const auto& item : sample_points) {
std::vector<double> point;
try {
for (const auto& component : item) point.push_back(as_float(component));
} catch (const py::error_already_set&) {
throw scad::ValueError("sample point " + std::to_string(index) + " is not a numeric sequence");
}
samples.push_back(std::move(point));
++index;
}
return sr::fit_cubic_bspline_control_points(samples, options);
},
py::arg("sample_points"), py::kw_only(), py::arg("tolerance") = 1e-3, py::arg("max_control_points") = py::none(),
py::arg("fairing") = 1e-6, py::arg("duplicate_tolerance") = 1e-12, py::arg("knot_tolerance") = 1e-9,
py::arg("raise_on_failure") = true,
"Fit a minimal cubic B-spline control polygon to sampled curve points.");
};
bind_into(math);
// The top level re-exports the same objects, like simplecadapi.__init__.
m.attr("BSplineFitResult") = math.attr("BSplineFitResult");
m.attr("fit_cubic_bspline_control_points") = math.attr("fit_cubic_bspline_control_points");
}
} // namespace scad::pybind::reactive
@@ -0,0 +1,454 @@
// GraphSession (the recording session), the reactive engine's Python face, the
// executor registry, and the recording context managers.
#include "bind_reactive_common.hpp"
#include "py_lifetime.hpp"
#include <mutex>
#include <optional>
#include <unordered_map>
#include <unordered_set>
#include "scad/core/error.hpp"
#include "scad/reactive/node_registry.hpp"
#include "scad/reactive/registry.hpp"
#include "scad/reactive/session.hpp"
namespace scad::pybind::reactive {
namespace sr = scad::reactive;
using sr::NodePtr;
using sr::Session;
namespace {
// ---- Python callables as executors -----------------------------------------
// A py::function that is released with the GIL held, whichever thread drops the last copy.
struct GilSafeFunction {
py::function fn;
~GilSafeFunction() { scad::pybind::drop_python_reference(fn); }
};
sr::Executor wrap_python_executor(py::function fn) {
auto holder = std::make_shared<GilSafeFunction>(GilSafeFunction{std::move(fn)});
return [holder](const Value& params, const std::vector<OpInput>& inputs, const sr::ScalarValues& scalars) {
const py::gil_scoped_acquire gil;
py::list in;
for (const OpInput& input : inputs) in.append(py::make_tuple(shape_to_python(input.shape), input.role));
py::dict values;
for (const auto& [name, value] : scalars) values[py::str(name)] = value;
const py::object result = holder->fn(value_to_python(params), in, values);
std::vector<Shape> out;
if (result.is_none()) return out;
if (py::isinstance<Shape>(result)) {
out.push_back(py::cast<Shape>(result));
} else {
for (const auto& item : result) out.push_back(py::cast<Shape>(item));
}
return out;
};
}
// ---- Python parameter structures -> Value + symbolic paths -------------------
Value split_value(const py::handle& value, const std::string& path, sr::SymbolicParams& symbolic) {
if (py::isinstance<sr::ScalarNode>(value)) {
const sr::ScalarPtr node = py::cast<sr::ScalarPtr>(value);
symbolic.emplace_back(path, scad::Scalar(scad::ExprPtr(node)));
return Value(scad::Scalar(scad::ExprPtr(node)).value()); // honours the session's edits
}
if (py::isinstance<py::tuple>(value) || py::isinstance<py::list>(value)) {
Value out = Value::array();
std::size_t index = 0;
for (const auto& item : value) out.push_back(split_value(item, path + "[" + std::to_string(index++) + "]", symbolic));
return out;
}
if (py::isinstance<py::dict>(value)) {
Value out = Value::object();
for (const auto& item : py::cast<py::dict>(value)) {
const std::string key = py::cast<std::string>(py::str(item.first));
out.set(key, split_value(item.second, path + "." + key, symbolic));
}
return out;
}
return value_from_python(value);
}
// ---- Shapes inside a captured value -----------------------------------------
void collect_shapes(const py::handle& value, std::vector<Shape>& out, std::unordered_set<PyObject*>& seen) {
if (value.is_none() || PyUnicode_Check(value.ptr()) || PyBytes_Check(value.ptr()) || PyFloat_Check(value.ptr()) ||
PyLong_Check(value.ptr())) {
return;
}
if (!seen.insert(value.ptr()).second) return;
if (py::isinstance<Shape>(value)) {
out.push_back(py::cast<Shape>(value));
return;
}
if (py::isinstance<py::dict>(value)) {
for (const auto& item : py::cast<py::dict>(value)) {
collect_shapes(item.first, out, seen);
collect_shapes(item.second, out, seen);
}
} else if (py::isinstance<py::list>(value) || py::isinstance<py::tuple>(value) || py::isinstance<py::set>(value) ||
py::isinstance<py::frozenset>(value)) {
for (const auto& item : value) collect_shapes(item, out, seen);
} else {
const py::module_ dataclasses = py::module_::import("dataclasses");
if (py::cast<bool>(dataclasses.attr("is_dataclass")(value)) && !PyType_Check(value.ptr())) {
for (const auto& field : dataclasses.attr("fields")(value)) {
const std::string name = py::cast<std::string>(field.attr("name"));
if (name.rfind('_', 0) == 0) continue;
collect_shapes(py::getattr(value, name.c_str()), out, seen);
}
}
}
}
std::vector<Shape> shapes_in(const py::handle& value) {
std::vector<Shape> shapes;
std::unordered_set<PyObject*> seen;
collect_shapes(value, shapes, seen);
return shapes;
}
// ---- The session ------------------------------------------------------------
struct PySession;
std::mutex g_sessions_mutex;
std::unordered_map<const Session*, PySession*>& sessions() {
static std::unordered_map<const Session*, PySession*> table;
return table;
}
// The session and the Python values captured with it; findable from the Session pointer
// (get_active_session returns the very Python object).
struct PySession {
Session session;
std::vector<py::object> captured_values;
explicit PySession(Session::Options options) : session(std::move(options)) {
const std::lock_guard lock(g_sessions_mutex);
sessions()[&session] = this;
}
~PySession() {
const std::lock_guard lock(g_sessions_mutex);
sessions().erase(&session);
}
PySession(const PySession&) = delete;
PySession& operator=(const PySession&) = delete;
};
PySession* python_session_of(const Session* session) {
const std::lock_guard lock(g_sessions_mutex);
const auto found = sessions().find(session);
return found == sessions().end() ? nullptr : found->second;
}
struct PyFailure {
std::string node_id, op, message;
};
struct PyReport {
std::vector<std::string> executed, memoized, unchanged, blocked, changed;
std::vector<PyFailure> failed;
bool ok = true;
};
PyReport to_report(const sr::RecomputeReport& report) {
PyReport out;
out.executed = report.executed;
out.memoized = report.memoized;
out.unchanged = report.unchanged;
out.blocked = report.blocked;
out.changed = report.changed;
for (const sr::NodeFailure& f : report.failed) out.failed.push_back(PyFailure{f.node_id, f.op, f.message});
out.ok = report.ok();
return out;
}
struct PySuspend {
std::optional<RecorderSuspend> inner;
};
struct PyIsolated {
std::optional<sr::IsolatedRecording> inner;
};
} // namespace
void bind_reactive_session(py::module_& m) {
py::class_<PyFailure>(m, "NodeFailure")
.def_readonly("node_id", &PyFailure::node_id)
.def_readonly("op", &PyFailure::op)
.def_readonly("message", &PyFailure::message)
.def("__repr__", [](const PyFailure& f) { return "NodeFailure(node_id='" + f.node_id + "', op='" + f.op + "')"; });
py::class_<PyReport>(m, "RecomputeReport")
.def_readonly("executed", &PyReport::executed)
.def_readonly("memoized", &PyReport::memoized)
.def_readonly("unchanged", &PyReport::unchanged)
.def_readonly("blocked", &PyReport::blocked)
.def_readonly("changed", &PyReport::changed)
.def_readonly("failed", &PyReport::failed)
.def_readonly("ok", &PyReport::ok)
.def("__repr__", [](const PyReport& r) {
return "RecomputeReport(executed=" + std::to_string(r.executed.size()) + ", memoized=" +
std::to_string(r.memoized.size()) + ", unchanged=" + std::to_string(r.unchanged.size()) + ", blocked=" +
std::to_string(r.blocked.size()) + ", failed=" + std::to_string(r.failed.size()) + ")";
});
py::class_<sr::ExecutorRegistry>(m, "ExecutorRegistry")
.def(py::init<bool>(), py::arg("builtins") = true)
.def("add", [](sr::ExecutorRegistry& r, const std::string& op, const py::function& fn) {
r.add(op, wrap_python_executor(fn));
}, py::arg("op"), py::arg("executor"),
"Register fn(params, inputs, scalars) -> outputs for an operation name.")
.def("replace", [](sr::ExecutorRegistry& r, const std::string& op, const py::function& fn) {
r.replace(op, wrap_python_executor(fn));
}, py::arg("op"), py::arg("executor"))
.def("remove", &sr::ExecutorRegistry::remove, py::arg("op"))
.def("contains", &sr::ExecutorRegistry::contains, py::arg("op"))
.def("operations", &sr::ExecutorRegistry::operations);
m.def("global_executor_registry", []() -> sr::ExecutorRegistry& { return sr::ExecutorRegistry::global(); },
py::return_value_policy::reference);
m.def("register_executor", [](const std::string& op, const py::function& fn) {
sr::register_executor(op, wrap_python_executor(fn));
}, py::arg("op"), py::arg("executor"));
py::class_<PySession>(m, "GraphSession", py::dynamic_attr())
.def(py::init([](const py::object& graph_id, bool allow_external_definitions, const py::object& ns, bool shared_lineage,
bool attach_topology_refs, std::size_t memo_capacity, sr::ExecutorRegistry* registry,
const py::object& source_provider) {
// allow_external_definitions is a policy of the Python layer that records Part / Assembly
// values (simplecadapi._glue.session); the engine has nothing to do for it.
static_cast<void>(allow_external_definitions);
Session::Options options;
options.shared_lineage = shared_lineage;
if (!source_provider.is_none()) {
auto holder = std::make_shared<GilSafeFunction>(GilSafeFunction{py::reinterpret_borrow<py::function>(source_provider)});
options.source_provider = [holder]() -> std::optional<Value> {
const py::gil_scoped_acquire gil;
const py::object found = holder->fn();
if (found.is_none()) return std::nullopt;
return value_from_python(found);
};
}
if (!graph_id.is_none()) options.graph_id = py::cast<std::string>(graph_id);
if (!ns.is_none()) options.ns = py::cast<std::string>(ns);
options.attach_topology_refs = attach_topology_refs;
options.memo_capacity = memo_capacity;
options.registry = registry;
return std::make_unique<PySession>(std::move(options));
}),
py::arg("graph_id") = py::none(), py::kw_only(), py::arg("allow_external_definitions") = false,
py::arg("namespace") = py::none(), py::arg("shared_lineage") = false, py::arg("attach_topology_refs") = false,
py::arg("memo_capacity") = 128, py::arg("registry") = nullptr, py::arg("source_provider") = py::none(),
py::keep_alive<1, 8>())
// ---- GraphSession ----
.def_property_readonly("graph", [](PySession& s) -> const sr::OperationGraph& { return s.session.graph(); },
py::return_value_policy::reference_internal)
.def_property_readonly("expression_graph", [](PySession& s) -> sr::ExpressionGraph& { return s.session.expression_graph(); },
py::return_value_policy::reference_internal)
.def_property_readonly("frame_graph", [](PySession& s) -> sr::FrameGraph& { return s.session.frame_graph(); },
py::return_value_policy::reference_internal)
.def_property_readonly("registry", [](PySession& s) -> sr::ExecutorRegistry& { return s.session.registry(); },
py::return_value_policy::reference_internal)
.def("start", [](PySession& s) { s.session.start(); })
.def("stop", [](PySession& s) { s.session.stop(); })
.def("__enter__", [](py::object self) {
py::cast<PySession&>(self).session.start();
return self;
})
.def("__exit__", [](PySession& s, const py::object&, const py::object&, const py::object&) { s.session.stop(); })
.def("allocate_object_id", [](PySession& s, const std::string& prefix) { return s.session.allocate_object_id(prefix); },
py::arg("prefix"))
.def_property_readonly("result_node_ids", [](const PySession& s) { return py::tuple(py::cast(s.session.result_node_ids())); })
.def_property_readonly("has_explicit_results", [](const PySession& s) { return s.session.has_explicit_results(); })
.def_property_readonly("captured_values", [](const PySession& s) { return py::tuple(py::cast(s.captured_values)); })
.def("capture_result", [](PySession& s, const py::object& value) {
s.session.capture_result(shapes_in(value));
s.captured_values.push_back(value);
return value;
}, py::kw_only(), py::arg("value"))
.def("clear_results", [](PySession& s) {
s.session.clear_results();
s.captured_values.clear();
})
.def_property_readonly("last_node", [](const PySession& s) -> py::object {
return s.session.last_node() ? py::cast(s.session.last_node()) : py::object(py::none());
})
.def_property_readonly("shared_lineage", [](const PySession& s) { return s.session.shared_lineage(); })
.def("_expect_value_op", [](PySession& s, const py::object& inputs, bool value_output) {
std::vector<NodePtr> nodes;
if (!inputs.is_none()) {
for (const auto& item : inputs) nodes.push_back(py::cast<NodePtr>(item));
}
s.session.expect_value_op(std::move(nodes), value_output);
}, py::arg("inputs") = py::none(), py::arg("value_output") = true,
"The next recorded operation also takes these nodes as inputs and (value_output) has one output.")
.def("_clear_value_op", [](PySession& s) { s.session.clear_value_op(); })
.def("validate_graph_ownership", [](const PySession& s, const py::object& value) {
for (const Shape& shape : shapes_in(value)) s.session.validate_graph_ownership(shape);
}, py::arg("value"))
// ---- recording from Python ----
.def("record", [](PySession& s, const std::string& op, const py::object& params, const py::object& inputs,
const py::object& outputs) -> NodePtr {
OpRecord record;
record.op = op;
record.params = Value::object();
if (!params.is_none()) {
for (const auto& item : py::cast<py::dict>(params)) {
const std::string key = py::cast<std::string>(py::str(item.first));
record.params.set(key, split_value(item.second, key, record.symbolic));
}
}
if (!inputs.is_none()) {
for (const auto& item : inputs) {
if (py::isinstance<py::tuple>(item) && py::len(item) == 2) {
record.inputs.push_back(OpInput{py::cast<Shape>(item.cast<py::tuple>()[0]), py::cast<std::string>(item.cast<py::tuple>()[1])});
} else {
record.inputs.push_back(OpInput{py::cast<Shape>(item), "input"});
}
}
}
std::vector<Shape> shapes;
if (!outputs.is_none()) {
if (py::isinstance<Shape>(outputs)) {
shapes.push_back(py::cast<Shape>(outputs));
} else {
for (const auto& item : outputs) shapes.push_back(py::cast<Shape>(item));
}
}
return s.session.record_node(record, shapes);
},
py::arg("op"), py::arg("params") = py::none(), py::kw_only(), py::arg("inputs") = py::none(),
py::arg("outputs") = py::none(),
"Record an operation: params may hold Var / Expr values (the symbolic ones make the node reactive); "
"inputs are shapes or (shape, role); outputs are the shapes it produced.")
// ---- variables ----
.def_property_readonly("vars", [](const PySession& s) {
py::tuple out(s.session.vars().size());
for (std::size_t i = 0; i < s.session.vars().size(); ++i) out[i] = py::cast(s.session.vars()[i]);
return out;
})
.def("declare_var", [](PySession& s, const py::object& var) {
if (!py::isinstance<sr::Var>(var)) throw scad::TypeError("declare_var needs a Var");
s.session.declare_var(py::cast<std::shared_ptr<const sr::Var>>(var));
}, py::arg("var"))
.def("has_var", [](const PySession& s, const std::string& name) { return s.session.has_var(name); }, py::arg("name"))
.def("parameters", [](const PySession& s) {
py::list out;
for (const sr::ParamSpec& spec : s.session.parameters()) out.append(value_to_python(spec.to_value()));
return out;
})
.def("var_value", [](const PySession& s, const std::string& name) { return s.session.var_value(name); }, py::arg("name"))
.def_property_readonly("bindings", [](const PySession& s) {
py::dict out;
for (const auto& [name, value] : s.session.bindings()) out[py::str(name)] = value;
return out;
})
.def("set_var", [](PySession& s, const std::string& name, const py::object& value) {
s.session.set_var(name, finite_real(value, "Binding '" + name + "'"));
}, py::arg("name"), py::arg("value"))
.def("set_vars", [](PySession& s, const py::dict& values) {
std::vector<std::pair<std::string, double>> list;
for (const auto& item : values) {
const std::string name = py::cast<std::string>(item.first);
list.emplace_back(name, finite_real(item.second, "Binding '" + name + "'"));
}
s.session.set_vars(list);
}, py::arg("values"))
.def("reset_var", [](PySession& s, const std::string& name) { s.session.reset_var(name); }, py::arg("name"))
.def("reset_vars", [](PySession& s) { s.session.reset_vars(); })
// ---- impact ----
.def("nodes_using", [](const PySession& s, const std::string& name) { return s.session.nodes_using(name); }, py::arg("var_name"))
.def("affected_nodes", [](const PySession& s, const py::object& names) {
if (py::isinstance<py::str>(names)) return s.session.affected_nodes(py::cast<std::string>(names));
return s.session.affected_nodes(py::cast<std::vector<std::string>>(names));
}, py::arg("var_names"))
.def("vars_affecting", [](const PySession& s, const std::string& id) { return s.session.vars_affecting(id); }, py::arg("node_id"))
// ---- recomputation ----
.def("status", [](const PySession& s, const std::string& id) { return std::string(sr::to_string(s.session.status(id))); }, py::arg("node_id"))
.def("dirty_nodes", [](const PySession& s) { return s.session.dirty_nodes(); })
.def("failure", [](const PySession& s, const std::string& id) -> py::object {
const std::exception_ptr error = s.session.failure(id);
if (!error) return py::none();
try {
std::rethrow_exception(error);
} catch (const std::exception& e) {
return py::str(e.what());
}
}, py::arg("node_id"))
.def("recompute", [](PySession& s, bool throw_on_error) {
return to_report(s.session.recompute(sr::RecomputeOptions{throw_on_error}));
}, py::kw_only(), py::arg("throw_on_error") = false)
.def("outputs", [](const PySession& s, const std::string& id) {
py::list out;
for (const Shape& shape : s.session.outputs(id)) out.append(shape_to_python(shape));
return out;
}, py::arg("node_id"))
.def("output", [](const PySession& s, const std::string& id, int slot) { return shape_to_python(s.session.output(id, slot)); },
py::arg("node_id"), py::arg("slot") = 0)
.def("current", [](const PySession& s, const py::object& shape) { return shape_to_python(s.session.current(py::cast<Shape>(shape))); },
py::arg("shape"))
.def("captured_shapes", [](const PySession& s) {
py::list out;
for (const Shape& shape : s.session.captured_shapes()) out.append(shape_to_python(shape));
return out;
})
.def_property_readonly("memo_size", [](const PySession& s) { return s.session.memo_size(); });
m.def("find_registered_node", [](const std::string& graph_id, const std::string& node_id) -> py::object {
const NodePtr node = sr::find_registered_node(graph_id, node_id);
return node ? py::cast(node) : py::object(py::none());
}, py::arg("graph_id"), py::arg("node_id"),
"The node a shared-lineage session recorded (or that register_graph_nodes added), by graph and node id.");
m.def("register_graph_nodes", [](const sr::OperationGraph& graph) {
for (const NodePtr& node : graph.nodes()) sr::register_node(node);
}, py::arg("graph"), "Make the nodes of a restored graph findable by shared-lineage sessions.");
m.def("recording_active", []() {
Session* active = Session::active_session();
return active != nullptr && current_recorder() == active;
}, "Whether a session is active and not suspended (an operation would be recorded).");
m.def("register_node", [](const NodePtr& node) { sr::register_node(node); }, py::arg("node"),
"Make one node findable by shared-lineage sessions.");
m.def("forget_graph_nodes", [](const std::string& graph_id) { sr::forget_graph_nodes(graph_id); }, py::arg("graph_id"));
m.def("get_active_session", []() -> py::object {
PySession* owner = python_session_of(Session::active_session());
return owner != nullptr ? py::cast(owner, py::return_value_policy::reference) : py::none().cast<py::object>();
});
py::class_<PySuspend>(m, "_SuspendGraphRecording")
.def("__enter__", [](py::object self) {
py::cast<PySuspend&>(self).inner.emplace();
return self;
})
.def("__exit__", [](PySuspend& s, const py::object&, const py::object&, const py::object&) { s.inner.reset(); });
m.def("suspend_graph_recording", []() { return std::make_unique<PySuspend>(); },
"Temporarily suspend automatic graph recording for internal API composition.");
py::class_<PyIsolated>(m, "_IsolatedRecording")
.def("__enter__", [](py::object self) {
py::cast<PyIsolated&>(self).inner.emplace();
return self;
})
.def("__exit__", [](PyIsolated& s, const py::object&, const py::object&, const py::object&) { s.inner.reset(); });
m.def("isolated_recording", []() { return std::make_unique<PyIsolated>(); },
"Run a nested definition build as if it were called at top level.");
m.def("record_operation_if_active", [](const std::string& op, const py::object& params, const py::object& outputs,
const py::object& input_shapes) -> py::object {
Session* session = Session::active_session();
if (session == nullptr || current_recorder() != session) return py::none();
PySession* owner = python_session_of(session);
if (owner == nullptr) return py::none();
const py::object self = py::cast(owner, py::return_value_policy::reference);
return self.attr("record")(op, params, py::arg("inputs") = input_shapes, py::arg("outputs") = outputs);
}, py::arg("op"), py::arg("params") = py::none(), py::arg("outputs") = py::none(), py::arg("input_shapes") = py::none(),
"Record an operation only when a session is active; returns the node or None.");
}
} // namespace scad::pybind::reactive
@@ -0,0 +1,165 @@
// Dimension, Unit, the registered units and UnitValidationError.
#include "bind_reactive_common.hpp"
#include <pybind11/eval.h>
#include "scad/core/error.hpp"
#include "scad/reactive/digest.hpp"
#include "scad/reactive/errors.hpp"
#include "scad/reactive/units.hpp"
namespace scad::pybind::reactive {
using scad::reactive::Dimension;
using scad::reactive::Unit;
scad::reactive::Unit unit_from(const py::object& value) {
if (py::isinstance<Unit>(value)) return py::cast<Unit>(value);
if (!py::isinstance<py::str>(value)) throw scad::TypeError("Unit must be a non-empty string or Unit");
return scad::reactive::get_unit(py::cast<std::string>(value));
}
namespace {
int exponent_of(const py::object& value, const char* what) {
if (PyBool_Check(value.ptr()) || !PyLong_Check(value.ptr())) {
throw scad::TypeError(std::string("Dimension ") + what + " exponent must be an integer");
}
return py::cast<int>(value);
}
const char* kUnitErrorSource = R"PY(
from simplecadapi._cpp.errors import SimpleCADError
class UnitValidationError(SimpleCADError):
"""Units or expression dimensions are physically inconsistent."""
operation = "units"
def __init__(self, message):
message = str(message)
guidance = {
"operation": "units",
"what_happened": message,
"possible_causes": [],
"how_to_fix": [],
"technical_details": None,
"signature": None,
"documentation_hint": None,
"measurements": [],
"evidence": [],
"repair": [],
"inventory": [],
}
super().__init__("units", guidance, message)
def __str__(self):
return self.args[0]
def __repr__(self):
return f"{type(self).__name__}({self.args[0]!r})"
)PY";
} // namespace
void bind_reactive_units(py::module_& m) {
// UnitValidationError is a Python class (a SimpleCADError subclass whose str() is the bare message).
py::dict scope;
py::exec(kUnitErrorSource, scope);
m.attr("UnitValidationError") = scope["UnitValidationError"];
py::register_exception_translator([](std::exception_ptr p) {
try {
if (p) std::rethrow_exception(p);
} catch (const scad::reactive::UnitValidationError& e) {
py::object cls = py::module_::import("simplecadapi._cpp._native").attr("UnitValidationError");
PyErr_SetObject(cls.ptr(), cls(e.guidance().what_happened).ptr());
}
});
py::class_<Dimension>(m, "Dimension")
.def(py::init([](const py::object& length, const py::object& angle) {
return Dimension{exponent_of(length, "length"), exponent_of(angle, "angle")};
}),
py::arg("length") = 0, py::arg("angle") = 0)
.def_property_readonly("length", [](const Dimension& d) { return d.length; })
.def_property_readonly("angle", [](const Dimension& d) { return d.angle; })
.def_property_readonly("name", &Dimension::name)
.def_property_readonly("symbol", &Dimension::symbol)
.def_property_readonly("is_dimensionless", &Dimension::is_dimensionless)
.def_property_readonly("is_design_dimension", &Dimension::is_design_dimension)
.def("multiply", &Dimension::multiply)
.def("divide", &Dimension::divide)
.def("power", [](const Dimension& d, const py::object& exponent) { return d.power(exponent_of(exponent, "")); })
.def("square_root", &Dimension::square_root)
.def("to_dict", [](const Dimension& d) { return value_to_python(d.to_value()); })
.def_static("from_dict", [](const py::object& data) { return Dimension::from_value(value_from_python(data)); })
.def("__eq__", [](const Dimension& a, const py::object& b) { return py::isinstance<Dimension>(b) && a == py::cast<Dimension>(b); })
.def("__hash__", [](const Dimension& d) { return std::hash<int>{}(d.length) * 31 + std::hash<int>{}(d.angle); })
.def("__repr__", [](const Dimension& d) {
return "Dimension(length=" + std::to_string(d.length) + ", angle=" + std::to_string(d.angle) + ")";
});
py::class_<Unit>(m, "Unit")
.def(py::init([](const py::object& symbol, const py::object& dimension, const py::object& scale) {
if (!py::isinstance<py::str>(symbol)) throw scad::ValueError("Unit symbol must be a non-empty string");
if (!py::isinstance<Dimension>(dimension)) throw scad::TypeError("Unit dimension must be a Dimension");
return Unit(py::cast<std::string>(symbol), py::cast<Dimension>(dimension),
real_number(scale, "Unit scale"));
}),
py::arg("symbol"), py::arg("dimension"), py::arg("scale_to_canonical"))
.def_property_readonly("symbol", &Unit::symbol)
.def_property_readonly("dimension", &Unit::dimension)
.def_property_readonly("scale_to_canonical", &Unit::scale_to_canonical)
.def("to_canonical", [](const Unit& u, const py::object& v) { return u.to_canonical(finite_real(v, "Value in " + u.symbol())); })
.def("from_canonical", [](const Unit& u, const py::object& v) { return u.from_canonical(finite_real(v, "Canonical value")); })
.def("to_dict", [](const Unit& u) { return value_to_python(u.to_value()); })
.def_static("from_dict", [](const py::object& data) { return Unit::from_value(value_from_python(data)); })
.def("__eq__", [](const Unit& a, const py::object& b) { return py::isinstance<Unit>(b) && a == py::cast<Unit>(b); })
.def("__hash__", [](const Unit& u) { return std::hash<std::string>{}(u.symbol()); })
.def("__repr__", [](const Unit& u) {
return "Unit(symbol=" + scad::reactive::py_str_repr(u.symbol()) + ", dimension=Dimension(length=" +
std::to_string(u.dimension().length) + ", angle=" + std::to_string(u.dimension().angle) +
"), scale_to_canonical=" + scad::reactive::py_float_repr(u.scale_to_canonical()) + ")";
});
namespace sr = scad::reactive;
m.attr("DIMENSIONLESS") = py::cast(sr::kDimensionless);
m.attr("LENGTH") = py::cast(sr::kLength);
m.attr("AREA") = py::cast(sr::kArea);
m.attr("VOLUME") = py::cast(sr::kVolume);
m.attr("ANGLE") = py::cast(sr::kAngle);
const struct {
const char* name;
const Unit& (*unit)();
} registered[] = {
{"MM", sr::units::mm}, {"CM", sr::units::cm}, {"M", sr::units::m},
{"INCH", sr::units::inch}, {"FOOT", sr::units::foot}, {"DEGREE", sr::units::degree},
{"RADIAN", sr::units::radian}, {"ONE", sr::units::one}, {"PERCENT", sr::units::percent},
{"SQUARE_MM", sr::units::square_mm}, {"SQUARE_CM", sr::units::square_cm}, {"SQUARE_M", sr::units::square_m},
{"SQUARE_INCH", sr::units::square_inch}, {"SQUARE_FOOT", sr::units::square_foot},
{"CUBIC_MM", sr::units::cubic_mm}, {"CUBIC_CM", sr::units::cubic_cm}, {"CUBIC_M", sr::units::cubic_m},
{"CUBIC_INCH", sr::units::cubic_inch}, {"CUBIC_FOOT", sr::units::cubic_foot},
};
for (const auto& entry : registered) m.attr(entry.name) = py::cast(entry.unit());
m.def("get_unit", [](const py::object& value) -> py::object {
if (py::isinstance<Unit>(value)) return value;
if (!py::isinstance<py::str>(value)) throw scad::TypeError("Unit must be a non-empty string or Unit");
return py::cast(sr::get_unit(py::cast<std::string>(value)));
}, py::arg("value"));
m.def("unit_to_payload", [](const py::object& unit) {
if (!py::isinstance<Unit>(unit)) throw scad::TypeError("Unit payload serialization requires a Unit");
return value_to_python(sr::unit_to_payload(py::cast<Unit>(unit)));
});
m.def("unit_from_payload", [](const py::object& payload) {
if (py::isinstance<Unit>(payload)) return py::cast<Unit>(payload);
return sr::unit_from_payload(value_from_python(payload));
});
m.def("canonical_unit_for_dimension", &sr::canonical_unit_for_dimension, py::arg("dimension"));
m.def("convert_value", [](const py::object& value, const py::object& from, const py::object& to) {
return sr::convert_value(finite_real(value, "Value"), unit_from(from), unit_from(to));
}, py::arg("value"), py::arg("from_unit"), py::arg("to_unit"));
}
} // namespace scad::pybind::reactive
+311
View File
@@ -0,0 +1,311 @@
// Python bindings for the "render" area: the software renderer (see include/scad/render/render.hpp).
#include "bindings.hpp"
#include <cmath>
#include <memory>
#include <optional>
#include <vector>
#include "scad/core/error.hpp"
#include "scad/render/render.hpp"
#include "scad/topo/shape.hpp"
namespace {
using namespace scad;
using namespace scad::render;
template <class Elem>
py::array view(const py::object& owner, const Elem* data, std::vector<py::ssize_t> shape) {
std::vector<py::ssize_t> strides(shape.size());
py::ssize_t stride = static_cast<py::ssize_t>(sizeof(Elem));
for (std::size_t i = shape.size(); i-- > 0;) {
strides[i] = stride;
stride *= shape[i];
}
py::array array(py::dtype::of<Elem>(), shape, strides, data, owner);
array.attr("setflags")(py::arg("write") = false);
return array;
}
Rgb to_rgb(const std::array<double, 3>& c) { return {static_cast<float>(c[0]), static_cast<float>(c[1]), static_cast<float>(c[2])}; }
std::vector<float> flat_points(const py::array_t<float, py::array::c_style | py::array::forcecast>& a) {
if (a.ndim() != 2 || a.shape(1) != 3) throw ValueError("expected an (n, 3) array of points");
return std::vector<float>(a.data(), a.data() + a.size());
}
Style parse_style(const std::string& s) {
if (s == "standard") return Style::Standard;
if (s == "studio") return Style::Studio;
throw ValueError("unknown render style: '" + s + "' (expected 'standard' or 'studio')");
}
MeshStyle mesh_style(const std::array<double, 3>& color, double opacity, bool studio_material, bool lit,
const std::optional<py::array_t<float, py::array::c_style | py::array::forcecast>>& face_colors) {
MeshStyle s;
s.color = to_rgb(color);
s.opacity = static_cast<float>(opacity);
s.studio_material = studio_material;
s.lit = lit;
if (face_colors) {
const auto& a = *face_colors;
if (a.ndim() != 2 || (a.shape(1) != 4 && a.shape(1) != 3)) throw ValueError("face_colors must be an (n, 4) rgba array (NaN alpha = default colour)");
const std::size_t w = static_cast<std::size_t>(a.shape(1));
for (py::ssize_t i = 0; i < a.shape(0); ++i) {
const float* r = a.data() + static_cast<std::size_t>(i) * w;
s.face_colors.push_back({r[0], r[1], r[2], w == 4 ? r[3] : 1.0f});
}
}
return s;
}
LineStyle line_style(const std::array<double, 3>& color, std::optional<double> width_px, bool ink, std::optional<double> width_world,
std::optional<double> depth_bias) {
LineStyle s;
s.color = to_rgb(color);
if (width_world) s.width_world = *width_world;
else if (ink) s.width_world = -1.0;
if (width_px) s.width_px = *width_px;
s.depth_bias = depth_bias;
return s;
}
} // namespace
void bind_render(py::module_& m) {
using FaceColors = std::optional<py::array_t<float, py::array::c_style | py::array::forcecast>>;
using Color = std::array<double, 3>;
py::class_<Scene, std::shared_ptr<Scene>>(
m, "RenderScene",
"The input of the software renderer: surface meshes (with per-face colours), line sets and point sets.")
.def(py::init<>())
.def(
"add_mesh",
[](Scene& s, const std::shared_ptr<io::Mesh>& mesh, Color color, double opacity, bool studio_material, bool lit,
const FaceColors& face_colors) { return s.add_mesh(mesh, mesh_style(color, opacity, studio_material, lit, face_colors)); },
py::arg("mesh"), py::arg("color") = Color{0.55, 0.64, 0.73}, py::arg("opacity") = 1.0, py::arg("studio_material") = false,
py::arg("lit") = true, py::arg("face_colors") = py::none(),
"Add a Mesh (the result of mesh(shape)); returns its index in the id buffer. face_colors is an (n, 4) float array indexed by\n"
"face id; a NaN alpha means 'use color'.")
.def(
"add_mesh_arrays",
[](Scene& s, const py::array_t<float, py::array::c_style | py::array::forcecast>& vertices,
const py::array_t<float, py::array::c_style | py::array::forcecast>& normals,
const py::array_t<std::uint32_t, py::array::c_style | py::array::forcecast>& triangles,
const py::array_t<std::uint32_t, py::array::c_style | py::array::forcecast>& face_ids, Color color, double opacity,
bool studio_material, bool lit, const FaceColors& face_colors) {
if (vertices.ndim() != 2 || vertices.shape(1) != 3 || normals.shape(0) != vertices.shape(0) || triangles.ndim() != 2 ||
triangles.shape(1) != 3 || face_ids.size() != triangles.shape(0))
throw ValueError("add_mesh_arrays: expected vertices (n,3), normals (n,3), triangles (m,3), face_ids (m,)");
auto mesh = std::make_shared<io::Mesh>();
mesh->vertices.assign(vertices.data(), vertices.data() + vertices.size());
mesh->normals.assign(normals.data(), normals.data() + normals.size());
mesh->triangles.assign(triangles.data(), triangles.data() + triangles.size());
mesh->face_ids.assign(face_ids.data(), face_ids.data() + face_ids.size());
for (std::uint32_t i : mesh->triangles)
if (i >= vertices.shape(0)) throw ValueError("add_mesh_arrays: triangle index out of range");
return s.add_mesh(std::move(mesh), mesh_style(color, opacity, studio_material, lit, face_colors));
},
py::arg("vertices"), py::arg("normals"), py::arg("triangles"), py::arg("face_ids"), py::arg("color") = Color{0.55, 0.64, 0.73},
py::arg("opacity") = 1.0, py::arg("studio_material") = false, py::arg("lit") = true, py::arg("face_colors") = py::none())
.def(
"add_shape",
[](Scene& s, const Shape& shape, Color color, double opacity, bool studio_material, bool lit, const FaceColors& face_colors,
double linear_deflection, double angular_deflection, bool edges, Color edge_color, bool ink,
std::optional<double> edge_width_px, std::optional<double> edge_deflection) {
const TopoDS_Shape wrapped = shape.wrapped();
io::MeshParameters mp;
mp.linear_deflection = linear_deflection;
mp.angular_deflection = angular_deflection;
mp.validate();
const MeshStyle ms = mesh_style(color, opacity, studio_material, lit, face_colors);
const LineStyle ls = line_style(edge_color, edge_width_px, ink, std::nullopt, std::nullopt);
std::shared_ptr<io::Mesh> mesh;
Polylines lines;
{
py::gil_scoped_release release;
mesh = std::make_shared<io::Mesh>(io::mesh(wrapped, mp));
if (edges) lines = edge_polylines(wrapped, edge_deflection.value_or(std::min(linear_deflection, 0.04)));
}
const int index = s.add_mesh(std::move(mesh), ms);
if (edges) s.add_lines(std::move(lines), ls);
return index;
},
py::arg("shape"), py::arg("color") = Color{0.55, 0.64, 0.73}, py::arg("opacity") = 1.0, py::arg("studio_material") = false,
py::arg("lit") = true, py::arg("face_colors") = py::none(), py::arg("linear_deflection") = io::kDefaultLinearDeflection,
py::arg("angular_deflection") = io::kDefaultAngularDeflection, py::arg("edges") = true,
py::arg("edge_color") = Color{0.16, 0.21, 0.27}, py::arg("ink") = true, py::arg("edge_width_px") = py::none(),
py::arg("edge_deflection") = py::none(),
"Tessellate `shape` and (by default) add its B-rep edges as ink. Returns the mesh index.")
.def(
"add_edges",
[](Scene& s, const Shape& shape, Color color, bool ink, std::optional<double> width_px, double deflection, int sample_count) {
const TopoDS_Shape wrapped = shape.wrapped();
Polylines lines;
{
py::gil_scoped_release release;
lines = edge_polylines(wrapped, deflection, sample_count);
}
return s.add_lines(std::move(lines), line_style(color, width_px, ink, std::nullopt, std::nullopt));
},
py::arg("shape"), py::arg("color") = Color{0.16, 0.21, 0.27}, py::arg("ink") = false, py::arg("width_px") = 4.5,
py::arg("deflection") = 0.04, py::arg("sample_count") = 0,
"Add the edges of `shape` (an edge, a wire, a solid ...) as depth-tested lines of `width_px` output pixels (or ink).")
.def(
"add_polylines",
[](Scene& s, const py::array_t<float, py::array::c_style | py::array::forcecast>& points,
const std::optional<py::array_t<std::uint32_t, py::array::c_style | py::array::forcecast>>& starts, Color color, bool ink,
std::optional<double> width_px, std::optional<double> depth_bias) {
Polylines p;
p.points = flat_points(points);
const std::uint32_t n = static_cast<std::uint32_t>(p.points.size() / 3);
if (starts) p.starts.assign(starts->data(), starts->data() + starts->size());
else p.starts = {0, n};
return s.add_lines(std::move(p), line_style(color, width_px, ink, std::nullopt, depth_bias));
},
py::arg("points"), py::arg("starts") = py::none(), py::arg("color") = Color{0.16, 0.21, 0.27}, py::arg("ink") = false,
py::arg("width_px") = 4.5, py::arg("depth_bias") = py::none())
.def(
"add_points",
[](Scene& s, const py::array_t<float, py::array::c_style | py::array::forcecast>& points, Color color, double size_px) {
PointStyle ps;
ps.color = to_rgb(color);
ps.size_px = size_px;
return s.add_points(flat_points(points), ps);
},
py::arg("points"), py::arg("color") = Color{0.78, 0.0, 0.0}, py::arg("size_px") = 15.0)
.def("bounds",
[](const Scene& s) {
const Bounds b = s.bounds();
return py::make_tuple(py::make_tuple(b.min.x, b.min.y, b.min.z), py::make_tuple(b.max.x, b.max.y, b.max.z));
})
.def_property_readonly("mesh_count", &Scene::mesh_count)
.def_property_readonly("triangle_count", &Scene::triangle_count);
py::class_<Panel>(m, "RenderPanel")
.def_readonly("x", &Panel::x)
.def_readonly("y", &Panel::y)
.def_readonly("width", &Panel::width)
.def_readonly("height", &Panel::height)
.def_readonly("label", &Panel::label)
.def_property_readonly("anchors",
[](const Panel& p) {
py::list out;
for (const AnchorResult& a : p.anchors) out.append(py::make_tuple(a.x, a.y, a.depth, a.in_view, a.visible));
return out;
},
"One (x, y, depth, in_view, visible) per requested anchor; x, y in output pixels (y down).")
.def_property_readonly("axes_tips",
[](const Panel& p) {
py::list out;
for (const auto& t : p.axes_tips) out.append(py::make_tuple(t[0], t[1]));
return out;
})
.def_property_readonly("camera",
[](const Panel& p) {
py::dict d;
auto t3 = [](const Vec3& v) { return py::make_tuple(v.x, v.y, v.z); };
d["target"] = t3(p.camera.target);
d["right"] = t3(p.camera.right);
d["up"] = t3(p.camera.up);
d["forward"] = t3(p.camera.forward);
d["half_height"] = p.camera.half_height;
d["aspect"] = p.camera.aspect;
return d;
})
.def("project",
[](const Panel& p, Vec3 point) {
const AnchorResult a = p.project(point);
return py::make_tuple(a.x, a.y, a.depth, a.in_view);
},
py::arg("point"), "(x, y, depth, in_view) of a world point in output pixels.");
py::class_<Frame, std::shared_ptr<Frame>>(m, "RenderFrame",
"A rendered image: rgba (h, w, 4) uint8, depth (h, w) float32 (+inf = background), mesh_id and\n"
"face_id (h, w) int32 (-1 = background), the panels and their projected anchors. Arrays are\n"
"read-only views of the frame's memory.")
.def_readonly("width", &Frame::width)
.def_readonly("height", &Frame::height)
.def_readonly("panels", &Frame::panels)
.def_readonly("ink_diameter", &Frame::ink_diameter)
.def_readonly("render_ms", &Frame::render_ms)
.def_readonly("resolve_ms", &Frame::resolve_ms)
.def_property_readonly("rgba", [](const py::object& self) {
const auto& f = self.cast<const Frame&>();
return view<std::uint8_t>(self, f.rgba.data(), {f.height, f.width, 4});
})
.def_property_readonly("depth", [](const py::object& self) {
const auto& f = self.cast<const Frame&>();
return view<float>(self, f.depth.data(), {f.height, f.width});
})
.def_property_readonly("mesh_id", [](const py::object& self) {
const auto& f = self.cast<const Frame&>();
return view<std::int32_t>(self, f.mesh_id.data(), {f.height, f.width});
})
.def_property_readonly("face_id", [](const py::object& self) {
const auto& f = self.cast<const Frame&>();
return view<std::int32_t>(self, f.face_id.data(), {f.height, f.width});
});
m.def(
"render_scene",
[](const Scene& scene, int width, int height, int supersample, const std::string& style,
const std::vector<std::tuple<double, double, std::string>>& views, double legend_panel_fraction,
std::optional<Vec3> view_up, double zoom, double edge_width_scale, bool show_axes, const std::vector<Vec3>& anchors,
int threads, const std::string& resolve, std::optional<Color> background_top, std::optional<Color> background_bottom,
double occlusion_tolerance) {
RenderOptions o;
o.width = width;
o.height = height;
o.supersample = supersample;
o.style = parse_style(style);
o.views.clear();
for (const auto& [el, az, label] : views) o.views.push_back({el, az, label});
o.legend_panel_fraction = legend_panel_fraction;
o.view_up = view_up;
o.zoom = zoom;
o.edge_width_scale = edge_width_scale;
o.show_axes = show_axes;
o.anchors = anchors;
o.threads = threads;
if (resolve == "lanczos") o.resolve = Resolve::Lanczos;
else if (resolve == "box") o.resolve = Resolve::Box;
else throw ValueError("resolve must be 'lanczos' or 'box'");
if (background_top) o.background_top = to_rgb(*background_top);
if (background_bottom) o.background_bottom = to_rgb(*background_bottom);
o.occlusion_tolerance = occlusion_tolerance;
Frame frame;
{
py::gil_scoped_release release;
frame = render_scene(scene, o);
}
return std::make_shared<Frame>(std::move(frame));
},
py::arg("scene"), py::arg("width") = 1400, py::arg("height") = 900, py::arg("supersample") = 2, py::arg("style") = "studio",
py::arg("views") = std::vector<std::tuple<double, double, std::string>>{{28.0, -45.0, "isometric"}},
py::arg("legend_panel_fraction") = 0.0, py::arg("view_up") = py::none(), py::arg("zoom") = 1.0,
py::arg("edge_width_scale") = 0.0019, py::arg("show_axes") = false, py::arg("anchors") = std::vector<Vec3>{},
py::arg("threads") = 0, py::arg("resolve") = "lanczos", py::arg("background_top") = py::none(),
py::arg("background_bottom") = py::none(), py::arg("occlusion_tolerance") = 0.002,
"Render `scene` into a grid of (elevation_deg, azimuth_deg, label) views (orthographic, supersampled, depth-tested).\n"
"`zoom` multiplies the SDK's 0.92 fit; a single-view screenshot with the SDK's zoom=4 default is zoom=1.");
m.def("render_view_preset", [](const std::string& name) { auto p = view_preset(name); return py::make_tuple(p.first, p.second); },
py::arg("name"), "(elevation, azimuth) of a named view ('iso', 'top', 'front_right', ...).");
m.def("render_auto_view", [](Vec3 spans) { auto p = auto_view(spans); return py::make_tuple(p.first, p.second); }, py::arg("spans"),
"The 'auto' view for a model with these x/y/z extents.");
m.def("render_edge_polylines",
[](const Shape& shape, double deflection, int sample_count) {
const Polylines p = edge_polylines(shape.wrapped(), deflection, sample_count);
py::array_t<float> pts({static_cast<py::ssize_t>(p.points.size() / 3), static_cast<py::ssize_t>(3)});
std::copy(p.points.begin(), p.points.end(), pts.mutable_data());
py::array_t<std::uint32_t> starts(static_cast<py::ssize_t>(p.starts.size()));
std::copy(p.starts.begin(), p.starts.end(), starts.mutable_data());
return py::make_tuple(pts, starts);
},
py::arg("shape"), py::arg("deflection") = 0.04, py::arg("sample_count") = 0,
"(points (n,3) float32, starts (k+1,) uint32): each unique B-rep edge of `shape` as a polyline.");
m.def("render_default_threads", &default_threads);
}
+501
View File
@@ -0,0 +1,501 @@
// Names the Python SDK exposes below its public surface that the layers staying in Python
// (build/, artifacts/, recording/serializer.py, scene/, ...) import from the lower modules:
// the non-recording assembly solver, connector resolution, and the helpers around Assembly.
// The Python package maps them into simplecadapi.product.{solver,connector,assembly}
// (simplecadapi/_native/compat.py).
#include "bind_product_args.hpp"
#include "bind_reactive_common.hpp"
#include "py_lifetime.hpp"
#include "scad/topo/diagnostic_image.hpp"
#include <BRepAdaptor_Curve.hxx>
#include <BRepAdaptor_Surface.hxx>
#include <GeomAbs_CurveType.hxx>
#include <GeomAbs_SurfaceType.hxx>
#include <TopoDS.hxx>
#include <array>
#include <cmath>
#include <set>
#include <mutex>
#include <unordered_map>
#include <vector>
#include <BRepBuilderAPI_Transform.hxx>
#include <GCPnts_TangentialDeflection.hxx>
#include <TopLoc_Location.hxx>
#include <Geom_BSplineCurve.hxx>
#include <Geom_BSplineSurface.hxx>
#include <Geom_Curve.hxx>
#include <TopAbs_ShapeEnum.hxx>
#include <TopExp_Explorer.hxx>
#include <gp_Circ.hxx>
#include <gp_Cylinder.hxx>
#include <gp_Elips.hxx>
#include <gp_Lin.hxx>
#include <gp_Sphere.hxx>
#include <gp_Torus.hxx>
#include <gp_Ax1.hxx>
#include <TopAbs_Orientation.hxx>
#include <gp_Ax3.hxx>
#include <gp_Dir.hxx>
#include <gp_Pnt.hxx>
#include <gp_Trsf.hxx>
#include "scad/kernel/curves.hpp"
#include "scad/product/resolve.hpp"
#include "scad/reactive/lineage.hpp"
#include "scad/topo/delta.hpp"
#include "scad/product/solver.hpp"
namespace {
using namespace scad;
using namespace scad::product_binding;
void bind_product_internals(py::module_& m) {
m.def("solve_assembly_constraints",
[](const py::object& assembly, const py::object& strict) {
if (!py::isinstance<sp::Assembly>(assembly)) throw TypeError("assembly must be an Assembly");
return sp::solve_assembly_constraints(assembly.cast<sp::AssemblyPtr>(), truthy(strict));
},
py::arg("assembly"), py::arg("strict") = true,
"Solve the assembly constraints without recording a graph node.");
m.def("inspect_assembly_constraints",
[](const py::object& assembly) {
return sp::inspect_assembly_constraints(typed<sp::Assembly>(assembly, "assembly must be an Assembly"));
},
py::arg("assembly"), "Residuals of every constraint and the components the grounded ones reach.");
m.def("constraint_reports_match",
[](const py::object& actual, const py::object& expected) {
return sp::constraint_reports_match(pybind::value_from_python(actual), pybind::value_from_python(expected));
},
py::arg("actual"), py::arg("expected"), "Two ConstraintReport dicts agree within the solver tolerances.");
m.def("resolve_connector",
[](const py::object& assembly, const py::object& ref) {
return sp::resolve_connector(typed<sp::Assembly>(assembly, "assembly must be an Assembly"),
typed<sp::ConnectorRef>(ref, "connector_ref must be a ConnectorRef"));
},
py::arg("assembly"), py::arg("connector_ref"));
m.def("resolve_item_connector",
[](const py::object& item, const py::object& connector_id) {
return sp::resolve_item_connector(item_of(item), text(connector_id, "connector_id"));
},
py::arg("item"), py::arg("connector_id"));
m.def("resolve_item_connector_placement",
[](const py::object& item, const py::object& connector_id) {
return sp::resolve_item_connector_placement(item_of(item), text(connector_id, "connector_id"));
},
py::arg("item"), py::arg("connector_id"));
m.def("resolve_connector_ref_placement",
[](const py::object& assembly, const py::object& ref) {
return sp::resolve_connector_ref_placement(typed<sp::Assembly>(assembly, "assembly must be an Assembly"),
typed<sp::ConnectorRef>(ref, "connector_ref must be a ConnectorRef"));
},
py::arg("assembly"), py::arg("connector_ref"));
m.def("resolve_connector_placement",
[](const py::object& connector) {
return sp::resolve_connector_placement(typed<sp::Connector>(connector, "connector must be a Connector"));
},
py::arg("connector"));
py::class_<sp::Assembly, py::smart_holder> assembly = py::reinterpret_borrow<py::class_<sp::Assembly, py::smart_holder>>(
m.attr("Assembly"));
assembly.def("_with_component_path_placement",
[](const sp::Assembly& self, const std::vector<std::string>& path, const py::object& placement) {
return self.with_component_path_placement(path, typed<sp::Placement>(placement, "placement must be a Placement"));
},
py::arg("component_path"), py::arg("placement"));
}
// The semantic state of a topology entity as plain dictionaries: what the artifact layer of
// the Python SDK (topology snapshots) reads and writes, and what no accessor handed out whole.
template <class T>
void add_state_dicts(py::module_& m, const char* name) {
py::class_<T, py::smart_holder> cls = py::reinterpret_borrow<py::class_<T, py::smart_holder>>(m.attr(name));
cls.def("_metadata_dict", [](const T& value) { return pybind::value_to_python(value.metadata()); });
cls.def("_runtime_dict", [](const T& value) { return pybind::value_to_python(value.runtime()); });
}
// BRepBndLib::AddOptimal on a trimmed torus or B-spline face costs 10-15 ms, and the geometry-interface
// fingerprint measures the same faces again every time a part is captured, restored or re-hashed. The
// box of a face depends only on its TShape and Location (not on tags or orientation), so it is memoised
// on that pair. The entry keeps the TShape alive: a freed address can never be mistaken for a new face.
kernel::BoundingBox face_bounding_box(const Shape& s) {
if (s.kind() != Kind::Face) return s.bounding_box();
struct Entry {
TopoDS_Shape keep;
kernel::BoundingBox box;
};
static std::mutex mutex;
static std::unordered_map<const void*, std::vector<Entry>> cache;
static std::size_t entries = 0;
constexpr std::size_t kMaxEntries = 8192;
const TopoDS_Shape& shape = s.wrapped();
const void* tshape = shape.TShape().get();
{
std::lock_guard<std::mutex> lock(mutex);
const auto it = cache.find(tshape);
if (it != cache.end())
for (const Entry& e : it->second)
if (e.keep.Location() == shape.Location()) return e.box;
}
const kernel::BoundingBox box = s.bounding_box();
std::lock_guard<std::mutex> lock(mutex);
if (entries >= kMaxEntries) {
cache.clear();
entries = 0;
}
cache[tshape].push_back({shape, box});
++entries;
return box;
}
void bind_shape_internals(py::module_& m) {
add_state_dicts<sp::Part>(m, "Part");
add_state_dicts<sp::Assembly>(m, "Assembly");
add_state_dicts<sp::Placement>(m, "Placement");
add_state_dicts<sp::Material>(m, "Material");
add_state_dicts<sp::Connector>(m, "Connector");
add_state_dicts<sp::ConnectorRef>(m, "ConnectorRef");
add_state_dicts<sp::GeometryRef>(m, "GeometryRef");
add_state_dicts<sp::ConnectorAnchor>(m, "ConnectorAnchor");
add_state_dicts<sp::Constraint>(m, "Constraint");
add_state_dicts<sp::ScalarLimit>(m, "ScalarLimit");
py::class_<Shape> any = py::reinterpret_borrow<py::class_<Shape>>(m.attr("AnyShape"));
any.def("_metadata_dict", [](const Shape& s) { return pybind::value_to_python(s.metadata()); });
any.def("_runtime_dict", [](const Shape& s) { return pybind::value_to_python(s.runtime()); });
any.def("_bounds", [](const Shape& s) {
const auto b = face_bounding_box(s);
return py::make_tuple(b.xmin, b.ymin, b.zmin, b.xmax, b.ymax, b.zmax);
}, "(xmin, ymin, zmin, xmax, ymax, zmax) of the shape.");
any.def("_shape_key", [](const Shape& s) {
// Identity of the geometry (TShape address, Location, Orientation): equal keys on live handles mean the
// same OCCT shape. Callers that memoise on it must hold the handle so the address cannot be reused.
const TopoDS_Shape& shape = s.wrapped();
const gp_Trsf t = shape.Location().Transformation();
return py::make_tuple(reinterpret_cast<std::uintptr_t>(shape.TShape().get()), static_cast<int>(shape.Orientation()),
t.ScaleFactor(), static_cast<int>(t.Form()), t.Value(1, 1), t.Value(1, 2), t.Value(1, 3), t.Value(1, 4),
t.Value(2, 1), t.Value(2, 2), t.Value(2, 3), t.Value(2, 4), t.Value(3, 1), t.Value(3, 2),
t.Value(3, 3), t.Value(3, 4));
}, "Identity key of the underlying OCCT shape (see the memo in artifacts' geometry interface).");
any.def("_geom_type", [](const Shape& s) -> py::object {
if (s.kind() == Kind::Face) {
switch (BRepAdaptor_Surface(TopoDS::Face(s.wrapped()), true).GetType()) {
case GeomAbs_Plane: return py::str("PLANE");
case GeomAbs_Cylinder: return py::str("CYLINDER");
case GeomAbs_Cone: return py::str("CONE");
case GeomAbs_Sphere: return py::str("SPHERE");
case GeomAbs_Torus: return py::str("TORUS");
case GeomAbs_BezierSurface: return py::str("BEZIER");
case GeomAbs_BSplineSurface: return py::str("BSPLINE");
case GeomAbs_SurfaceOfRevolution: return py::str("REVOLUTION");
case GeomAbs_SurfaceOfExtrusion: return py::str("EXTRUSION");
case GeomAbs_OffsetSurface: return py::str("OFFSET");
default: return py::str("OTHER");
}
}
if (s.kind() == Kind::Edge) {
switch (BRepAdaptor_Curve(TopoDS::Edge(s.wrapped())).GetType()) {
case GeomAbs_Line: return py::str("LINE");
case GeomAbs_Circle: return py::str("CIRCLE");
case GeomAbs_Ellipse: return py::str("ELLIPSE");
case GeomAbs_Hyperbola: return py::str("HYPERBOLA");
case GeomAbs_Parabola: return py::str("PARABOLA");
case GeomAbs_BezierCurve: return py::str("BEZIER");
case GeomAbs_BSplineCurve: return py::str("BSPLINE");
case GeomAbs_OffsetCurve: return py::str("OFFSET");
default: return py::str("OTHER");
}
}
return py::none();
}, "The geometric type of a face's surface or an edge's curve, or None.");
any.def("_polyline", [](const Shape& s, double linear, double angular) {
// The edge as the scene renders it: forward oriented, its location baked in, sampled by tangential deflection.
if (s.kind() != Kind::Edge) throw TypeError("_polyline needs an Edge");
TopoDS_Shape prepared = s.wrapped().Oriented(TopAbs_FORWARD);
const TopLoc_Location location = prepared.Location();
TopoDS_Shape unlocated = prepared.Located(TopLoc_Location(), Standard_False);
if (!location.IsIdentity()) {
BRepBuilderAPI_Transform builder(unlocated, location.Transformation(), Standard_True, Standard_False);
builder.Build();
if (!builder.IsDone()) throw ValueError("location bake failed");
unlocated = builder.Shape();
}
BRepAdaptor_Curve adaptor(TopoDS::Edge(unlocated));
GCPnts_TangentialDeflection sampler(adaptor, adaptor.FirstParameter(), adaptor.LastParameter(), angular, linear, 2, 1e-9, 1e-7);
py::list out;
for (int i = 1; i <= sampler.NbPoints(); ++i) {
const gp_Pnt p = sampler.Value(i);
out.append(py::make_tuple(p.X(), p.Y(), p.Z()));
}
return out;
}, py::arg("linear"), py::arg("angular"));
any.def("_orientation", [](const Shape& s) {
switch (s.wrapped().Orientation()) {
case TopAbs_REVERSED: return "reversed";
case TopAbs_INTERNAL: return "internal";
case TopAbs_EXTERNAL: return "external";
default: return "forward";
}
}, "The orientation of this occurrence in its container: forward, reversed, internal or external.");
any.def("_geometry", [](const Shape& s) -> py::object {
const auto point = [](const gp_Pnt& p) { return py::make_tuple(p.X(), p.Y(), p.Z()); };
const auto dir = [](const gp_Dir& d) { return py::make_tuple(d.X(), d.Y(), d.Z()); };
py::dict out;
if (s.kind() == Kind::Face) {
BRepAdaptor_Surface a(TopoDS::Face(s.wrapped()), true);
switch (a.GetType()) {
case GeomAbs_Cylinder: {
const gp_Cylinder v = a.Cylinder();
out["origin"] = point(v.Location()); out["axis"] = dir(v.Axis().Direction());
out["x_direction"] = dir(v.XAxis().Direction()); out["radius"] = v.Radius();
return out;
}
case GeomAbs_Sphere: {
const gp_Sphere v = a.Sphere();
out["center"] = point(v.Location()); out["axis"] = dir(v.Position().Direction());
out["x_direction"] = dir(v.XAxis().Direction()); out["radius"] = v.Radius();
return out;
}
case GeomAbs_Torus: {
const gp_Torus v = a.Torus();
out["center"] = point(v.Location()); out["axis"] = dir(v.Axis().Direction());
out["x_direction"] = dir(v.XAxis().Direction());
out["major_radius"] = std::max(v.MajorRadius(), v.MinorRadius());
out["minor_radius"] = std::min(v.MajorRadius(), v.MinorRadius());
return out;
}
default: return py::none();
}
}
if (s.kind() == Kind::Edge) {
BRepAdaptor_Curve a(TopoDS::Edge(s.wrapped()));
switch (a.GetType()) {
case GeomAbs_Line: {
const gp_Lin v = a.Line();
out["origin"] = point(v.Location()); out["direction"] = dir(v.Direction());
return out;
}
case GeomAbs_Circle: {
const gp_Circ v = a.Circle();
out["center"] = point(v.Location()); out["normal"] = dir(v.Axis().Direction());
out["x_direction"] = dir(v.XAxis().Direction()); out["radius"] = v.Radius();
return out;
}
case GeomAbs_Ellipse: {
const gp_Elips v = a.Ellipse();
out["center"] = point(v.Location()); out["normal"] = dir(v.Axis().Direction());
out["x_direction"] = dir(v.XAxis().Direction());
out["major_radius"] = v.MajorRadius(); out["minor_radius"] = v.MinorRadius();
return out;
}
case GeomAbs_BSplineCurve: {
const Handle(Geom_BSplineCurve) v = a.BSpline();
out["degree"] = v->Degree(); out["rational"] = static_cast<bool>(v->IsRational());
out["periodic"] = static_cast<bool>(v->IsPeriodic());
out["poles_count"] = v->NbPoles(); out["knots_count"] = v->NbKnots();
return out;
}
default: return py::none();
}
}
return py::none();
}, "The analytic parameters of a face's surface (cylinder, sphere, torus) or an edge's curve, or None.");
any.def("_topo_ref", [](const Shape& s) -> py::object {
const auto ref = reactive::topo_ref_of(s);
return ref ? pybind::value_to_python(to_value(*ref)) : py::object(py::none());
}, "The durable reference (graph, node, slot, kind, topo id) of an entity of a recorded output, or None.");
any.def("_keep_topology_owner", [](const Shape& s) { reactive::keep_topology_owner(s); },
"Before a tag node re-attributes the shape: its contents stay named by the nodes that made them.");
}
// ---------------------------------------------------------------------------
// B-spline data for the translators (kept in Python).
// ---------------------------------------------------------------------------
py::list pole_list(const Handle(Geom_BSplineCurve)& c) {
py::list out;
for (int i = 1; i <= c->NbPoles(); ++i) {
const gp_Pnt p = c->Pole(i);
out.append(py::make_tuple(p.X(), p.Y(), p.Z()));
}
return out;
}
py::dict bspline_curve_dict(const Handle(Geom_BSplineCurve)& c) {
py::dict d;
d["control_points"] = pole_list(c);
d["degree"] = c->Degree();
py::list knots, mults, weights;
for (int i = 1; i <= c->NbKnots(); ++i) {
knots.append(c->Knot(i));
mults.append(c->Multiplicity(i));
}
for (int i = 1; i <= c->NbPoles(); ++i) weights.append(c->Weight(i));
d["knots"] = knots;
d["multiplicities"] = mults;
d["weights"] = weights;
d["rational"] = static_cast<bool>(c->IsRational());
d["periodic"] = static_cast<bool>(c->IsPeriodic());
return d;
}
// loft_geometry._curve_value: a curve segment as an editable-sketch recipe.
py::dict loft_curve_value(const Handle(Geom_Curve)& curve, double first, double last) {
Handle(Geom_BSplineCurve) copy = Handle(Geom_BSplineCurve)::DownCast(curve->Copy());
if (copy.IsNull()) throw TypeError("iso-curve of a B-spline surface is not a B-spline");
copy->Segment(first, last);
py::dict d;
d["kind"] = "edge";
if (copy->Degree() == 1 && copy->NbPoles() == 2) {
const gp_Pnt a = copy->Pole(1), b = copy->Pole(2);
d["type"] = "line";
d["start"] = py::make_tuple(a.X(), a.Y(), a.Z());
d["end"] = py::make_tuple(b.X(), b.Y(), b.Z());
return d;
}
d["type"] = "spline";
py::dict data = bspline_curve_dict(copy);
d["controls"] = data["control_points"];
d["degree"] = data["degree"];
d["knots"] = data["knots"];
d["multiplicities"] = data["multiplicities"];
d["weights"] = data["weights"];
d["periodic"] = data["periodic"];
return d;
}
// loft_geometry.canonical_guided_loft over a native shape; None when no face is a B-spline surface.
py::object guided_loft_recipe(const Shape& shape) {
std::vector<BRepAdaptor_Surface> sides;
for (TopExp_Explorer ex(shape.wrapped(), TopAbs_FACE); ex.More(); ex.Next()) {
BRepAdaptor_Surface surface(TopoDS::Face(ex.Current()));
if (surface.GetType() == GeomAbs_BSplineSurface) sides.push_back(std::move(surface));
}
if (sides.empty()) return py::none();
constexpr int kStations = 9;
std::vector<py::list> profiles(kStations);
py::list guides;
std::set<std::array<double, 9>> guide_keys;
const auto rounded = [](double v) { return std::round(v * 1e8) / 1e8; };
for (const BRepAdaptor_Surface& surface : sides) {
const Handle(Geom_BSplineSurface) spline = surface.BSpline();
const double u0 = surface.FirstUParameter(), u1 = surface.LastUParameter();
const double v0 = surface.FirstVParameter(), v1 = surface.LastVParameter();
for (int index = 0; index < kStations; ++index) {
const double v = v0 + (v1 - v0) * index / (kStations - 1);
profiles[static_cast<std::size_t>(index)].append(loft_curve_value(spline->VIso(v), u0, u1));
}
const int count = surface.UDegree() == 1 ? 1 : 16;
for (int index = 0; index <= count; ++index) {
const double u = u0 + (u1 - u0) * index / count;
const Handle(Geom_Curve) curve = spline->UIso(u);
std::array<double, 9> key{};
int slot = 0;
for (const double fraction : {0.0, 0.5, 1.0}) {
const gp_Pnt p = curve->Value(v0 + (v1 - v0) * fraction);
key[static_cast<std::size_t>(slot++)] = rounded(p.X());
key[static_cast<std::size_t>(slot++)] = rounded(p.Y());
key[static_cast<std::size_t>(slot++)] = rounded(p.Z());
}
if (!guide_keys.insert(key).second) continue;
guides.append(loft_curve_value(curve, v0, v1));
}
}
py::list wires;
for (py::list& edges : profiles) {
py::dict wire;
wire["kind"] = "wire";
wire["edges"] = edges;
wires.append(wire);
}
py::dict out;
out["profiles"] = wires;
out["guides"] = guides;
return out;
}
} // namespace
// An evidence dict from the Python provider as the C++ ErrorEvidence.
ErrorEvidence evidence_of(const py::object& item) {
ErrorEvidence out;
const auto text = [&](const char* key) {
return item.contains(key) && !item[key].is_none() ? py::str(item[key]).cast<std::string>() : std::string();
};
out.kind = text("kind");
out.path = text("path");
out.view = text("view");
out.caption = text("caption");
if (item.contains("symbols") && !item["symbols"].is_none())
for (const py::handle pair : item["symbols"]) {
const py::sequence entry = py::reinterpret_borrow<py::sequence>(pair);
out.symbols.emplace_back(py::str(entry[0]).cast<std::string>(), py::str(entry[1]).cast<std::string>());
}
return out;
}
// The Python callable a C++ registry keeps: released without touching the interpreter once it has gone.
class KeptCallable {
public:
explicit KeptCallable(py::object fn) : fn_(std::move(fn)) {}
KeptCallable(const KeptCallable&) = delete;
KeptCallable& operator=(const KeptCallable&) = delete;
~KeptCallable() { scad::pybind::drop_python_reference(fn_); }
const py::object& get() const { return fn_; }
private:
py::object fn_;
};
void bind_sdk_compat(py::module_& m) {
bind_product_internals(m);
bind_shape_internals(m);
m.def("_set_diagnostic_image_provider", [](const py::object& provider) {
if (provider.is_none()) {
set_diagnostic_image_provider({});
return;
}
const auto callable = std::make_shared<KeptCallable>(provider);
set_diagnostic_image_provider([callable](const DiagnosticImage& request) -> std::optional<ErrorEvidence> {
const py::gil_scoped_acquire gil; // the operation that failed may be running without the GIL
py::list shapes;
for (const Shape& shape : request.shapes) shapes.append(scad::pybind::reactive::shape_to_python(shape));
const py::object picture = callable->get()(request.kind, request.operation, request.view, request.caption,
request.dedup_key, shapes, scad::pybind::value_to_python(request.payload));
if (picture.is_none()) return std::nullopt;
return evidence_of(picture);
});
}, py::arg("provider"),
"Install provider(kind, operation, view, caption, dedup_key, shapes, payload) -> evidence dict or None: it "
"draws the pictures a failing operation asks for. None removes it.");
m.def("_sample_edge_points", [](const Shape& edge, int samples) {
if (edge.kind() != Kind::Edge) throw TypeError("_sample_edge_points needs an Edge");
const BRepAdaptor_Curve curve(TopoDS::Edge(edge.wrapped()));
const int count = std::max(2, samples);
std::vector<std::array<double, 3>> out;
out.reserve(static_cast<std::size_t>(count));
const double first = curve.FirstParameter(), last = curve.LastParameter();
for (int i = 0; i < count; ++i) {
const gp_Pnt p = curve.Value(first + (last - first) * i / (count - 1));
out.push_back({p.X(), p.Y(), p.Z()});
}
return out;
}, py::arg("edge"), py::arg("samples") = 16, "Points along an edge, evenly in parameter.");
m.def("_guided_loft_recipe", &guided_loft_recipe, py::arg("shape"),
"Boundary profiles and guide curves of the B-spline faces of a loft (translator recipe), or None.");
m.def("_interpolated_bspline_edge", [](const std::vector<std::array<double, 3>>& points, bool periodic, double tolerance) {
std::vector<Vec3> pts;
pts.reserve(points.size());
for (const auto& p : points) pts.push_back(Vec3{p[0], p[1], p[2]});
return Edge(kernel::make_interpolated_bspline_edge(pts, periodic, tolerance));
}, py::arg("points"), py::kw_only(), py::arg("periodic") = false, py::arg("tolerance") = 1e-6,
"An interpolating B-spline edge through the points (GeomAPI_Interpolate).");
m.def("_bspline_curve_of", [](const Shape& edge) {
if (edge.kind() != Kind::Edge) throw TypeError("_bspline_curve_of needs an Edge");
BRepAdaptor_Curve adaptor(TopoDS::Edge(edge.wrapped()));
if (adaptor.GetType() != GeomAbs_BSplineCurve) throw ValueError("the edge's curve is not a B-spline");
return bspline_curve_dict(adaptor.BSpline());
}, py::arg("edge"), "Poles, degree, knots, multiplicities, weights of an edge's B-spline curve.");
}
+619
View File
@@ -0,0 +1,619 @@
// Python bindings for the semantic area: the tag data model (simplecadapi.tagging), the public
// tag operators (operators/selection.py) and the private TaggedMixin surface of shapes.
//
// The ten tag enums are real `(str, Enum)` classes, as in Python: a function that takes one accepts
// the member or its string value ("local"), and returns members. The casters below are the only
// ones for these types in the module.
#include "bindings.hpp"
#include <algorithm>
#include <type_traits>
#include "scad/core/error.hpp"
#include "scad/ql/selector.hpp"
#include "scad/semantic/finalize.hpp"
#include "scad/semantic/selection.hpp"
#include "scad/topo/tag_factories.hpp"
namespace scad::pybind {
// The Python class standing for each enum, and the facts needed to parse one.
template <class E>
struct EnumInfo;
template <> struct EnumInfo<TagScope> { static constexpr const char* name = "TagScope"; static constexpr const char* field = "tag scope"; static constexpr int count = 4; };
template <> struct EnumInfo<TopologyPropagation> { static constexpr const char* name = "TopologyPropagation"; static constexpr const char* field = "topology propagation"; static constexpr int count = 2; };
template <> struct EnumInfo<LineagePolicy> { static constexpr const char* name = "LineagePolicy"; static constexpr const char* field = "lineage policy"; static constexpr int count = 4; };
template <> struct EnumInfo<LineageDerivation> { static constexpr const char* name = "LineageDerivation"; static constexpr const char* field = "lineage derivation"; static constexpr int count = 6; };
template <> struct EnumInfo<TagAttachment> { static constexpr const char* name = "TagAttachment"; static constexpr const char* field = "attachment"; static constexpr int count = 3; };
template <> struct EnumInfo<TagProducerKind> { static constexpr const char* name = "TagProducerKind"; static constexpr const char* field = "producer kind"; static constexpr int count = 4; };
template <> struct EnumInfo<TagTargetKind> { static constexpr const char* name = "TagTargetKind"; static constexpr const char* field = "target kind"; static constexpr int count = 4; };
template <> struct EnumInfo<TagEvidenceKind> { static constexpr const char* name = "TagEvidenceKind"; static constexpr const char* field = "evidence kind"; static constexpr int count = 6; };
template <> struct EnumInfo<TagCertainty> { static constexpr const char* name = "TagCertainty"; static constexpr const char* field = "certainty"; static constexpr int count = 2; };
template <> struct EnumInfo<TagLifecycle> { static constexpr const char* name = "TagLifecycle"; static constexpr const char* field = "lifecycle"; static constexpr int count = 3; };
template <class E>
py::object& enum_class() {
static py::object* cls = new py::object; // never destroyed: static destructors run after Py_Finalize
return *cls;
}
template <class E>
E parse_enum_text(const std::string& text) {
if constexpr (std::is_same_v<E, TagScope>) {
return normalize_tag_scope(text);
} else {
std::vector<std::string> allowed;
for (int i = 0; i < EnumInfo<E>::count; ++i) {
const E candidate = static_cast<E>(i);
if (to_string(candidate) == text) return candidate;
allowed.emplace_back(to_string(candidate));
}
std::sort(allowed.begin(), allowed.end());
std::string joined;
for (const auto& item : allowed) joined += (joined.empty() ? "" : ", ") + item;
throw TagValidationError(std::string("unsupported ") + EnumInfo<E>::field + " '" + text + "'; expected one of: " + joined);
}
}
} // namespace scad::pybind
namespace scad::pybind {
// One caster for all of them. pybind11 3 has a generic caster for enums, so each type below gets
// an explicit specialization (which outranks it) that derives from this.
template <class E>
struct TagEnumCaster {
PYBIND11_TYPE_CASTER(E, ::pybind11::detail::const_name("str"));
bool load(py::handle src, bool) {
if (!src) return false;
if (py::isinstance<py::str>(src)) {
value = parse_enum_text<E>(src.cast<std::string>());
return true;
}
if (py::hasattr(src, "value") && py::isinstance<py::str>(src.attr("value"))) {
value = parse_enum_text<E>(src.attr("value").template cast<std::string>());
return true;
}
return false;
}
static py::handle cast(E v, py::return_value_policy, py::handle) {
return enum_class<E>()(std::string(to_string(v))).release();
}
};
} // namespace scad::pybind
namespace pybind11::detail {
template <> struct type_caster<scad::TagScope> : scad::pybind::TagEnumCaster<scad::TagScope> {};
template <> struct type_caster<scad::TopologyPropagation> : scad::pybind::TagEnumCaster<scad::TopologyPropagation> {};
template <> struct type_caster<scad::LineagePolicy> : scad::pybind::TagEnumCaster<scad::LineagePolicy> {};
template <> struct type_caster<scad::LineageDerivation> : scad::pybind::TagEnumCaster<scad::LineageDerivation> {};
template <> struct type_caster<scad::TagAttachment> : scad::pybind::TagEnumCaster<scad::TagAttachment> {};
template <> struct type_caster<scad::TagProducerKind> : scad::pybind::TagEnumCaster<scad::TagProducerKind> {};
template <> struct type_caster<scad::TagTargetKind> : scad::pybind::TagEnumCaster<scad::TagTargetKind> {};
template <> struct type_caster<scad::TagEvidenceKind> : scad::pybind::TagEnumCaster<scad::TagEvidenceKind> {};
template <> struct type_caster<scad::TagCertainty> : scad::pybind::TagEnumCaster<scad::TagCertainty> {};
template <> struct type_caster<scad::TagLifecycle> : scad::pybind::TagEnumCaster<scad::TagLifecycle> {};
} // namespace pybind11::detail
namespace {
using namespace scad;
using scad::pybind::value_from_python;
using scad::pybind::value_to_python;
py::object shape_to_py(const Shape& s) {
switch (s.kind()) {
case Kind::Vertex: return py::cast(Vertex(s));
case Kind::Edge: return py::cast(Edge(s));
case Kind::Wire: return py::cast(Wire(s));
case Kind::Face: return py::cast(Face(s));
case Kind::Shell: return py::cast(Shell(s));
case Kind::Solid: return py::cast(Solid(s));
case Kind::Compound: return py::cast(Compound(s));
}
return py::none();
}
template <class E>
void make_enum(py::module_& m, std::initializer_list<const char*> values) {
py::list members;
for (const char* value : values) {
std::string name = value;
for (char& c : name) c = static_cast<char>(c >= 'a' && c <= 'z' ? c - 'a' + 'A' : c);
members.append(py::make_tuple(name, value));
}
py::dict kwargs;
kwargs["type"] = py::module_::import("builtins").attr("str");
kwargs["module"] = "simplecadapi._cpp";
py::object cls = py::module_::import("enum").attr("Enum")(scad::pybind::EnumInfo<E>::name, members, **kwargs);
scad::pybind::enum_class<E>() = cls;
m.attr(scad::pybind::EnumInfo<E>::name) = cls;
}
void bind_enums(py::module_& m) {
make_enum<TagScope>(m, {"local", "inherited", "effective", "lineage"});
make_enum<TopologyPropagation>(m, {"local", "downward"});
make_enum<LineagePolicy>(m, {"none", "continuation", "continuation_fragment", "explicit"});
make_enum<LineageDerivation>(m, {"continuation", "fragment", "merge", "intersection", "boundary", "replacement"});
make_enum<TagAttachment>(m, {"local", "inherited", "effective_legacy"});
make_enum<TagProducerKind>(m, {"user_operation", "auto_rule", "imported_sidecar", "legacy_import"});
make_enum<TagTargetKind>(m, {"selection_query", "scope_root", "explicit_refs", "legacy_effective"});
make_enum<TagEvidenceKind>(m, {"user_assertion", "query_execution", "topology_change", "geometry_classification",
"imported_sidecar", "legacy_snapshot"});
make_enum<TagCertainty>(m, {"asserted", "proven"});
make_enum<TagLifecycle>(m, {"assertion", "recompute", "snapshot"});
}
// ---- the data classes ------------------------------------------------------------------------------------
// The data classes validate when they are built, like the Python dataclasses; the wire parsers hold the rules.
TagTarget checked(const TagTarget& target) { return tag_target_from_value(target.to_value()); }
TagPropagation checked(const TagPropagation& p) { return tag_propagation_from_value(p.to_value()); }
TagProducer checked(const TagProducer& p) { return tag_producer_from_value(p.to_value()); }
void bind_records(py::module_& m) {
py::class_<TagBindingScope>(m, "TagBindingScope", "Snapshot boundary in which an assignment target is evaluated.")
.def(py::init([](std::optional<std::string> node_id, int output_slot) {
if (node_id && node_id->empty()) throw TagValidationError("scope.node_id must be null or a non-empty string");
if (output_slot < 0) throw TagValidationError("scope.output_slot must be >= 0");
return TagBindingScope{std::move(node_id), output_slot};
}),
py::arg("node_id") = py::none(), py::arg("output_slot") = 0)
.def_property_readonly("node_id", [](const TagBindingScope& s) { return s.node_id; })
.def_property_readonly("output_slot", [](const TagBindingScope& s) { return s.output_slot; })
.def("to_dict", [](const TagBindingScope& s) { return value_to_python(s.to_value()); })
.def_static("from_dict", [](const py::object& data) { return tag_binding_scope_from_value(value_from_python(data)); })
.def("__eq__", [](const TagBindingScope& a, const TagBindingScope& b) { return a.to_value() == b.to_value(); })
.def("__hash__", [](const TagBindingScope& s) { return py::hash(py::make_tuple(s.node_id, s.output_slot)); })
.def("__repr__", [](const TagBindingScope& s) {
return "TagBindingScope(node_id=" + (s.node_id ? "'" + *s.node_id + "'" : std::string("None")) +
", output_slot=" + std::to_string(s.output_slot) + ")";
});
py::class_<TagProducer>(m, "TagProducer", "Identity of the operation, rule, or import that made an assertion.")
.def(py::init([](TagProducerKind kind, std::optional<std::string> node_id, std::optional<std::string> rule_id,
std::optional<std::string> rule_version) {
TagProducer p;
p.kind = kind;
p.node_id = std::move(node_id);
p.rule_id = std::move(rule_id);
p.rule_version = std::move(rule_version);
return checked(p);
}),
py::arg("kind"), py::arg("node_id") = py::none(), py::arg("rule_id") = py::none(),
py::arg("rule_version") = py::none())
.def_property_readonly("kind", [](const TagProducer& p) { return p.kind; })
.def_property_readonly("node_id", [](const TagProducer& p) { return p.node_id; })
.def_property_readonly("rule_id", [](const TagProducer& p) { return p.rule_id; })
.def_property_readonly("rule_version", [](const TagProducer& p) { return p.rule_version; })
.def("to_dict", [](const TagProducer& p) { return value_to_python(p.to_value()); })
.def_static("from_dict", [](const py::object& data) { return tag_producer_from_value(value_from_python(data)); })
.def("__eq__", [](const TagProducer& a, const TagProducer& b) { return a == b; })
.def("__repr__", [](const TagProducer& p) { return "TagProducer(" + p.to_value().dump() + ")"; });
py::class_<TagTarget>(m, "TagTarget", "Serializable assignment intent, separate from execution evidence.")
.def(py::init([](TagTargetKind kind, std::optional<std::string> query_hash, std::optional<std::string> binding_hash,
std::optional<Value> selector, std::vector<Value> refs) {
TagTarget t;
t.kind = kind;
t.query_hash = std::move(query_hash);
t.binding_hash = std::move(binding_hash);
if (selector && !selector->is_null()) {
if (!selector->is_object()) throw TagValidationError("target.selector must be an object");
t.selector = std::move(selector);
}
for (const Value& ref : refs)
if (!ref.is_object()) throw TagValidationError("target.refs must be a tuple of objects");
t.refs = std::move(refs);
return checked(t);
}),
py::arg("kind") = TagTargetKind::ScopeRoot, py::arg("query_hash") = py::none(),
py::arg("binding_hash") = py::none(), py::arg("selector") = py::none(), py::arg("refs") = py::tuple())
.def_property_readonly("kind", [](const TagTarget& t) { return t.kind; })
.def_property_readonly("query_hash", [](const TagTarget& t) { return t.query_hash; })
.def_property_readonly("binding_hash", [](const TagTarget& t) { return t.binding_hash; })
.def_property_readonly("selector", [](const TagTarget& t) { return t.selector ? value_to_python(*t.selector) : py::object(py::none()); })
.def_property_readonly("refs", [](const TagTarget& t) {
py::list refs;
for (const Value& r : t.refs) refs.append(value_to_python(r));
return py::tuple(refs);
})
.def("to_dict", [](const TagTarget& t) { return value_to_python(t.to_value()); })
.def_static("from_dict", [](const py::object& data) { return tag_target_from_value(value_from_python(data)); })
.def("__eq__", [](const TagTarget& a, const TagTarget& b) { return a.to_value() == b.to_value(); })
.def("__repr__", [](const TagTarget& t) { return "TagTarget(" + t.to_value().dump() + ")"; });
py::class_<TagPropagation>(m, "TagPropagation", "How a tag travels through topology and history.")
.def(py::init([](TopologyPropagation topology, LineagePolicy lineage, std::vector<LineageDerivation> derivations) {
TagPropagation p;
p.topology = topology;
p.lineage = lineage;
p.explicit_derivations = std::move(derivations);
return checked(p);
}),
py::arg("topology") = TopologyPropagation::Local, py::arg("lineage") = LineagePolicy::ContinuationFragment,
py::arg("explicit_derivations") = py::tuple())
.def_property_readonly("topology", [](const TagPropagation& p) { return p.topology; })
.def_property_readonly("lineage", [](const TagPropagation& p) { return p.lineage; })
.def_property_readonly("explicit_derivations", [](const TagPropagation& p) {
py::list items;
for (const auto d : p.explicit_derivations) items.append(py::cast(d));
return py::tuple(items);
})
.def("to_dict", [](const TagPropagation& p) { return value_to_python(p.to_value()); })
.def_static("from_dict", [](const py::object& data) { return tag_propagation_from_value(value_from_python(data)); })
.def("__eq__", [](const TagPropagation& a, const TagPropagation& b) { return a.to_value() == b.to_value(); })
.def("__repr__", [](const TagPropagation& p) { return "TagPropagation(" + p.to_value().dump() + ")"; });
py::class_<TagEvidence>(m, "TagEvidence", "Typed evidence payload for a binding or a lineage witness.")
.def(py::init([](TagEvidenceKind kind, std::optional<Value> data) {
TagEvidence e;
e.kind = kind;
if (data && !data->is_null()) {
if (!data->is_object()) throw TagValidationError("evidence data must be an object");
if (data->find("kind") != nullptr) throw TagValidationError("evidence data cannot redefine kind");
e.data = std::move(*data);
}
return e;
}),
py::arg("kind"), py::arg("data") = py::none())
.def_property_readonly("kind", [](const TagEvidence& e) { return e.kind; })
.def_property_readonly("data", [](const TagEvidence& e) { return value_to_python(e.data); })
.def("to_dict", [](const TagEvidence& e) { return value_to_python(e.to_value()); })
.def_static("from_dict", [](const py::object& data) { return tag_evidence_from_value(value_from_python(data)); })
.def("__eq__", [](const TagEvidence& a, const TagEvidence& b) { return a.to_value() == b.to_value(); })
.def("__repr__", [](const TagEvidence& e) { return "TagEvidence(" + e.to_value().dump() + ")"; });
py::class_<TagBinding>(m, "TagBinding", "Canonical, source-preserving Semantic Binding Schema 1.0 assignment.")
.def(py::init([](const std::string& tag, TagProducer producer, std::optional<TagBindingScope> scope,
std::optional<TagTarget> target, std::optional<TagPropagation> propagation,
std::optional<TagEvidence> evidence, TagAttachment attachment, TagCertainty certainty,
TagLifecycle lifecycle, std::optional<std::string> binding_id, const std::string& schema_version) {
TagBinding b;
try {
b.tag = normalize_tag(tag, true);
} catch (const ValueError& e) {
throw TagValidationError(e.what());
}
b.policy.mut().producer = std::move(producer);
if (scope) b.policy.mut().scope = std::move(*scope);
if (target) b.policy.mut().target = std::move(*target);
if (propagation) b.policy.mut().propagation = std::move(*propagation);
b.evidence = evidence ? std::move(*evidence) : TagEvidence{};
b.attachment = attachment;
b.certainty = certainty;
b.lifecycle = lifecycle;
b.binding_id = binding_id ? BindingId(*binding_id) : new_binding_id();
b.policy.mut().schema_version = schema_version;
b.validate();
return b;
}),
py::arg("tag"), py::arg("producer"), py::arg("scope") = py::none(), py::arg("target") = py::none(),
py::arg("propagation") = py::none(), py::arg("evidence") = py::none(),
py::arg("attachment") = TagAttachment::Local, py::arg("certainty") = TagCertainty::Asserted,
py::arg("lifecycle") = TagLifecycle::Assertion, py::arg("binding_id") = py::none(),
py::arg("schema_version") = std::string(kTagBindingSchemaVersion))
.def_property_readonly("tag", [](const TagBinding& b) { return b.tag.str(); })
.def_property_readonly("producer", [](const TagBinding& b) { return b.producer(); })
.def_property_readonly("scope", [](const TagBinding& b) { return b.scope(); })
.def_property_readonly("target", [](const TagBinding& b) { return b.target(); })
.def_property_readonly("propagation", [](const TagBinding& b) { return b.propagation(); })
.def_property_readonly("evidence", [](const TagBinding& b) { return *b.evidence; })
.def_property_readonly("attachment", [](const TagBinding& b) { return b.attachment; })
.def_property_readonly("certainty", [](const TagBinding& b) { return b.certainty; })
.def_property_readonly("lifecycle", [](const TagBinding& b) { return b.lifecycle; })
.def_property_readonly("binding_id", [](const TagBinding& b) { return b.binding_id.str(); })
.def_property_readonly("schema_version", [](const TagBinding& b) { return b.schema_version().str(); })
.def("to_dict", [](const TagBinding& b) { return value_to_python(b.to_value()); })
.def_static("from_dict", [](const py::object& data) { return tag_binding_from_value(value_from_python(data)); })
.def("__eq__", [](const TagBinding& a, const TagBinding& b) { return a == b; })
.def("__hash__", [](const TagBinding& b) { return py::hash(py::str(b.binding_id.str())); })
.def("__repr__", [](const TagBinding& b) { return "TagBinding(tag='" + b.tag.str() + "', binding_id='" + b.binding_id.str() + "')"; });
py::class_<TagLineageWitness>(m, "TagLineageWitness", "Evidence that makes a source binding visible in lineage scope.")
.def(py::init([](TagBinding binding, LineageDerivation derivation, std::string source_topo_id,
std::string target_topo_id, TagEvidence evidence, std::string coverage) {
TagLineageWitness w;
w.binding = std::move(binding);
w.derivation = derivation;
w.source_topo_id = std::move(source_topo_id);
w.target_topo_id = std::move(target_topo_id);
w.evidence = std::move(evidence);
w.coverage = std::move(coverage);
w.validate();
return w;
}),
py::arg("binding"), py::arg("derivation"), py::arg("source_topo_id"), py::arg("target_topo_id"),
py::arg("evidence"), py::arg("coverage") = "complete")
.def_property_readonly("binding", [](const TagLineageWitness& w) { return w.binding; })
.def_property_readonly("derivation", [](const TagLineageWitness& w) { return w.derivation; })
.def_property_readonly("source_topo_id", [](const TagLineageWitness& w) { return w.source_topo_id; })
.def_property_readonly("target_topo_id", [](const TagLineageWitness& w) { return w.target_topo_id; })
.def_property_readonly("evidence", [](const TagLineageWitness& w) { return *w.evidence; })
.def_property_readonly("coverage", [](const TagLineageWitness& w) { return w.coverage; })
.def("to_dict", [](const TagLineageWitness& w) { return value_to_python(w.to_value()); })
.def_static("from_dict", [](const py::object& data) { return tag_lineage_witness_from_value(value_from_python(data)); })
.def("__eq__", [](const TagLineageWitness& a, const TagLineageWitness& b) { return a == b; })
.def("__repr__", [](const TagLineageWitness& w) { return "TagLineageWitness(" + w.to_value().dump() + ")"; });
py::class_<TagPolicy>(m, "TagPolicy", "Legacy token registry hints; canonical assignments do not consult this.")
.def(py::init<>())
.def_readonly("propagate_prefixes", &TagPolicy::propagate_prefixes)
.def_readonly("propagate_exact", &TagPolicy::propagate_exact)
.def_readonly("block_prefixes", &TagPolicy::block_prefixes)
.def_readonly("block_exact", &TagPolicy::block_exact)
.def("should_propagate", &TagPolicy::should_propagate, py::arg("tag"));
py::class_<SemanticRef>(m, "SemanticRef")
.def(py::init([](std::string graph_id, std::string node_id, std::string entity_type, std::string entity_id) {
return SemanticRef{std::move(graph_id), std::move(node_id), std::move(entity_type), std::move(entity_id)};
}),
py::arg("graph_id"), py::arg("node_id"), py::arg("entity_type"), py::arg("entity_id"))
.def_readonly("graph_id", &SemanticRef::graph_id)
.def_readonly("node_id", &SemanticRef::node_id)
.def_readonly("entity_type", &SemanticRef::entity_type)
.def_readonly("entity_id", &SemanticRef::entity_id)
.def("__eq__", [](const SemanticRef& a, const SemanticRef& b) { return a == b; })
.def("__repr__", [](const SemanticRef& r) {
return "SemanticRef(graph_id='" + r.graph_id + "', node_id='" + r.node_id + "', entity_type='" + r.entity_type +
"', entity_id='" + r.entity_id + "')";
});
py::class_<SemanticDelta>(m, "SemanticDelta")
.def(py::init([](std::vector<SemanticRef> created, std::vector<SemanticRef> modified, std::vector<SemanticRef> deleted,
std::optional<Value> metadata) {
SemanticDelta d;
d.created = std::move(created);
d.modified = std::move(modified);
d.deleted = std::move(deleted);
if (metadata) d.metadata = std::move(*metadata);
return d;
}),
py::arg("created") = py::tuple(), py::arg("modified") = py::tuple(), py::arg("deleted") = py::tuple(),
py::arg("metadata") = py::none())
.def_readonly("created", &SemanticDelta::created)
.def_readonly("modified", &SemanticDelta::modified)
.def_readonly("deleted", &SemanticDelta::deleted)
.def_property_readonly("metadata", [](const SemanticDelta& d) { return value_to_python(d.metadata); });
}
// ---- the tagging namespace: factories and rules ----------------------------------------------------------------
void bind_tagging_functions(py::module_& m, py::module_& tagging) {
tagging.def(
"user_tag_binding",
[](const std::string& tag, std::optional<std::string> node_id, std::optional<std::string> scope_node_id,
int output_slot, std::optional<TagTarget> target, TopologyPropagation topology, LineagePolicy lineage,
std::vector<LineageDerivation> explicit_derivations, std::optional<TagEvidence> evidence) {
UserTagOptions o;
o.node_id = std::move(node_id);
o.scope_node_id = std::move(scope_node_id);
o.output_slot = output_slot;
o.target = std::move(target);
o.topology = topology;
o.lineage = lineage;
o.explicit_derivations = std::move(explicit_derivations);
o.evidence = std::move(evidence);
return user_tag_binding(tag, o);
},
py::arg("tag"), py::kw_only(), py::arg("node_id") = py::none(), py::arg("scope_node_id") = py::none(),
py::arg("output_slot") = 0, py::arg("target") = py::none(), py::arg("topology") = TopologyPropagation::Local,
py::arg("lineage") = LineagePolicy::ContinuationFragment, py::arg("explicit_derivations") = py::tuple(),
py::arg("evidence") = py::none());
tagging.def(
"internal_tag_binding",
[](const std::string& tag, TopologyPropagation topology, const std::string& rule_id, const std::string& rule_version,
std::optional<Value> evidence) {
InternalTagOptions o;
o.topology = topology;
o.rule_id = rule_id;
o.rule_version = rule_version;
if (evidence) o.evidence = std::move(*evidence);
return internal_tag_binding(tag, o);
},
py::arg("tag"), py::kw_only(), py::arg("topology") = TopologyPropagation::Local,
py::arg("rule_id") = "simplecad.compat.internal_annotation", py::arg("rule_version") = "1.0",
py::arg("evidence") = py::none());
tagging.def("operation_role_tag_binding", &operation_role_tag_binding, py::arg("tag"), py::kw_only(),
py::arg("operation"), py::arg("role"), py::arg("target_topo_id"), py::arg("evidence_method"));
tagging.def("projected_tag_binding", &projected_tag_binding, py::arg("source"), py::kw_only(), py::arg("operation"),
py::arg("role"), py::arg("source_topo_id"), py::arg("target_topo_id"), py::arg("evidence_method"),
py::arg("topology") = TopologyPropagation::Local);
tagging.def(
"legacy_tag_binding",
[](const std::string& tag, std::optional<std::string> diagnostic) {
return legacy_tag_binding(tag, diagnostic ? std::optional<std::string_view>(*diagnostic) : std::nullopt);
},
py::arg("tag"), py::kw_only(), py::arg("diagnostic") = py::none());
tagging.def(
"lineage_policy_allows",
[](const py::object& policy, LineageDerivation derivation) {
if (py::isinstance<TagPropagation>(policy)) return lineage_policy_allows(policy.cast<const TagPropagation&>(), derivation);
return lineage_policy_allows(policy.cast<LineagePolicy>(), derivation);
},
py::arg("policy"), py::arg("derivation"));
tagging.def("is_normalized_tag", [](const py::object& tag) { return py::isinstance<py::str>(tag) && is_normalized_tag(tag.cast<std::string>()); },
py::arg("tag"));
tagging.def(
"normalize_tag",
[](const py::object& tag, bool strict) {
if (!py::isinstance<py::str>(tag)) throw TypeError("tag must be a string");
return normalize_tag(tag.cast<std::string>(), strict);
},
py::arg("tag"), py::kw_only(), py::arg("strict") = true);
tagging.def(
"normalize_tag_scope",
[](const py::object& scope) {
if (py::isinstance<py::str>(scope)) return normalize_tag_scope(scope.cast<std::string>());
throw TypeError("tag scope must be a string or TagScope");
},
py::arg("scope"));
tagging.def("resolve_anchor_tag_candidates", &resolve_anchor_tag_candidates, py::arg("tag"));
tagging.attr("DEFAULT_TAG_POLICY") = py::cast(default_tag_policy());
tagging.attr("TAG_BINDING_SCHEMA_VERSION") = std::string(kTagBindingSchemaVersion);
py::set scopes;
for (const char* scope : {"local", "inherited", "effective", "lineage"}) scopes.add(scope);
tagging.attr("VALID_TAG_SCOPES") = py::frozenset(scopes);
// The error families are one Python class in this module: every scad::Error arrives as SimpleCADError.
py::object error = py::module_::import("simplecadapi._cpp.errors").attr("SimpleCADError");
tagging.attr("TagValidationError") = error;
tagging.attr("SemanticCapabilityError") = error;
tagging.attr("UnsupportedQueryCapabilityError") = error;
for (const char* name :
{"TagScope", "TopologyPropagation", "LineagePolicy", "LineageDerivation", "TagAttachment", "TagProducerKind",
"TagTargetKind", "TagEvidenceKind", "TagCertainty", "TagLifecycle", "TagBinding", "TagBindingScope",
"TagProducer", "TagTarget", "TagPropagation", "TagEvidence", "TagLineageWitness", "TagPolicy"})
tagging.attr(name) = m.attr(name);
// The short aliases tagging.py keeps for the model names.
for (const auto& [alias, target] : std::initializer_list<std::pair<const char*, const char*>>{
{"BindingScope", "TagBindingScope"}, {"Propagation", "TagPropagation"}, {"Lineage", "LineagePolicy"},
{"Attachment", "TagAttachment"}, {"Producer", "TagProducer"}, {"ProducerKind", "TagProducerKind"},
{"Target", "TagTarget"}, {"TargetKind", "TagTargetKind"}, {"Evidence", "TagEvidence"},
{"EvidenceKind", "TagEvidenceKind"}, {"Certainty", "TagCertainty"}, {"Lifecycle", "TagLifecycle"}})
tagging.attr(alias) = m.attr(target);
}
// ---- the public operators ---------------------------------------------------------------------------------------
TagTargets targets_from_py(const py::object& targets) {
if (py::isinstance<ql::ShapeSelector>(targets)) return TagTargets(targets.cast<const ql::ShapeSelector&>().shared());
if (py::isinstance<py::str>(targets) || py::isinstance<py::bytes>(targets) || !py::hasattr(targets, "__iter__"))
throw TypeError("targets must be a ShapeSelector or shape sequence");
std::vector<Shape> shapes;
for (const py::handle item : targets) {
if (!py::isinstance<Shape>(item)) throw TypeError("tag assignment targets must contain only shapes");
shapes.push_back(item.cast<const Shape&>());
}
return TagTargets(std::move(shapes));
}
void bind_operators(py::module_& m) {
m.def(
"apply_tag",
[](const py::object& shape, const std::string& tag) {
if (!py::isinstance<Shape>(shape)) {
static const ErrorSpec spec{"apply_tag", "Failed to attach the tag to the shape.",
{"The shape is invalid.", "The tag value is empty or malformed."},
{"Pass a valid shape object.",
"Use a normalized tag string such as 'role.mounting_surface' or 'group.fasteners'."}};
raise_harness_error(spec, TypeError("expected a SimpleCAD shape"));
}
apply_tag(shape.cast<const Shape&>(), tag);
return shape; // the same object, as in Python
},
py::arg("shape"), py::arg("tag"), "Attach a local user tag with continuation/fragment lineage policy.");
m.def(
"apply_tag_rselection",
[](const Shape& scope, const py::object& targets, const std::string& tag, TopologyPropagation topology,
LineagePolicy lineage) {
static const ErrorSpec spec{
"apply_tag_rselection",
"Failed to attach the tag to the selected shapes.",
{"The assignment scope or target selection is invalid.", "The tag value is empty or malformed.",
"The selector resolved no targets or references foreign topology."},
{"Pass a valid scope and a non-empty ShapeSelector or shape sequence.",
"Use a normalized tag string such as 'role.mounting_surface' or 'group.fasteners'.",
"Ensure every explicit target belongs to the assignment scope."}};
return shape_to_py(guarded(spec, [&] { return apply_tag_rselection(scope, targets_from_py(targets), tag, topology, lineage); }));
},
py::arg("scope"), py::arg("targets"), py::arg("tag"),
py::arg("topology_propagation") = TopologyPropagation::Local,
py::arg("lineage_policy") = LineagePolicy::ContinuationFragment,
"Return a semantic shape view with a canonical tag assignment.");
m.def(
"list_tags", [](const Shape& shape, TagScope scope) { return list_tags(shape, scope); }, py::arg("shape"),
py::arg("scope") = TagScope::Effective, "Return shape tags in deterministic sorted order for one scope.");
m.def(
"explain_tag", [](const Shape& shape, const std::string& tag, TagScope scope) { return explain_tag(shape, tag, scope); },
py::arg("shape"), py::arg("tag"), py::arg("scope") = TagScope::Effective,
"Explain every visible binding that produces a tag token.");
m.def(
"select_faces_by_tag", [](const Solid& solid, const std::string& tag, TagScope scope) { return select_faces_by_tag(solid, tag, scope); },
py::arg("solid"), py::arg("tag"), py::arg("scope") = TagScope::Effective, "Select faces by tag.");
m.def(
"select_edges_by_tag", [](const Shape& shape, const std::string& tag, TagScope scope) { return select_edges_by_tag(shape, tag, scope); },
py::arg("shape"), py::arg("tag"), py::arg("scope") = TagScope::Effective, "Select edges by tag.");
}
// ---- TaggedMixin's private surface, on every shape class --------------------------------------------------------------
void bind_shape_methods(py::module_& m) {
py::object cls = m.attr("AnyShape");
const auto method = [&cls](const char* name, auto fn, auto... extras) {
cls.attr(name) = py::cpp_function(std::move(fn), py::name(name), py::is_method(cls), extras...);
};
method("_apply_user_tag",
[](Shape& s, const std::string& tag, TopologyPropagation topology, LineagePolicy lineage,
std::optional<std::string> producer_node_id) {
UserTagOptions o;
o.node_id = std::move(producer_node_id);
o.topology = topology;
o.lineage = lineage;
TagBinding binding = user_tag_binding(normalize_tag(tag, true), o);
s.add_binding(binding);
return binding;
},
py::arg("tag"), py::kw_only(), py::arg("topology_propagation") = TopologyPropagation::Local,
py::arg("lineage_policy") = LineagePolicy::ContinuationFragment, py::arg("producer_node_id") = py::none());
method("_add_tag_binding", [](Shape& s, const TagBinding& b) { s.add_binding(b); }, py::arg("binding"));
method("_add_tag_lineage",
[](Shape& s, const TagBinding& binding, LineageDerivation derivation, const std::string& source_topo_id,
const TagEvidence& evidence, const std::string& coverage) {
s.add_tag_lineage(binding, derivation, source_topo_id, evidence, coverage);
},
py::arg("binding"), py::kw_only(), py::arg("derivation"), py::arg("source_topo_id"), py::arg("evidence"),
py::arg("coverage") = "complete");
method("_remove_tag",
[](Shape& s, const std::string& tag, const py::object& matching) {
if (py::isinstance<TagProducer>(matching))
return static_cast<int>(s.remove_tag_bindings(tag, matching.cast<const TagProducer&>()));
return static_cast<int>(s.remove_tag_bindings(tag, matching.cast<TagProducerKind>()));
},
py::arg("tag"), py::kw_only(), py::arg("matching_producer") = TagProducerKind::UserOperation);
method("_remove_tag_binding", [](Shape& s, const std::string& id) { return s.remove_tag_binding(id); }, py::arg("binding_id"));
method("_local_tag_bindings", [](const Shape& s) { return s.local_tag_bindings(); });
method("_legacy_effective_bindings", [](const Shape& s) { return s.legacy_effective_bindings(); });
method("_inherited_tag_bindings", [](const Shape& s) { return s.inherited_tag_bindings(); });
method("_lineage_tag_bindings", [](const Shape& s) { return s.lineage_tag_bindings(); });
method("_list_tag_bindings", [](const Shape& s, TagScope scope) { return s.list_tag_bindings(scope); },
py::arg("scope") = TagScope::Effective);
method("_replace_local_tag_bindings", [](Shape& s, std::vector<TagBinding> bindings) { s.replace_local_tag_bindings(std::move(bindings)); },
py::arg("bindings"));
method("_copy_tag_state_from", [](Shape& s, const Shape& source) { s.copy_tag_state_from(source); }, py::arg("source"));
method("_copy_semantic_state_from", [](Shape& s, const Shape& source) { s.copy_semantic_state_from(source); }, py::arg("source"));
method("_refresh_tag_cache", [](Shape& s, bool recursive) { s.refresh_tag_cache(recursive); }, py::kw_only(),
py::arg("recursive") = false);
const py::object property = py::module_::import("builtins").attr("property");
cls.attr("_tag_bindings") = property(py::cpp_function([](const Shape& s) { return s.local_bindings(); }));
cls.attr("_tag_lineage") = property(py::cpp_function([](const Shape& s) { return s.lineage_witnesses(); }));
cls.attr("_tags") = property(py::cpp_function([](const Shape& s) { return py::set(py::cast(s.list_tags())); }),
py::cpp_function([](Shape& s, const py::object& tags) {
if (py::isinstance<py::str>(tags) || py::isinstance<py::bytes>(tags) || !py::hasattr(tags, "__iter__"))
throw TypeError("_tags compatibility cache must be assigned an iterable");
std::vector<std::string> names;
for (const py::handle item : tags) names.push_back(item.cast<std::string>());
s.set_legacy_tags(names);
}));
}
} // namespace
void bind_semantic(py::module_& m) {
bind_enums(m);
bind_records(m);
py::module_ tagging = m.def_submodule("tagging", "The tag data model: bindings, factories, lineage rules.");
bind_tagging_functions(m, tagging);
bind_operators(m);
bind_shape_methods(m);
}
+572
View File
@@ -0,0 +1,572 @@
// Python bindings for the "sketch" area: the Sketch document, its data classes,
// the solver backend registry (duck-typed Python backends included) and the 42
// operators, under the names and signatures of simplecadapi.
#include "bindings.hpp"
#include "py_lifetime.hpp"
#include <mutex>
#include "scad/core/error.hpp"
#include "scad/sketch/native_solver.hpp"
#include "scad/sketch/operators.hpp"
namespace pybind11::detail {
// SketchTarget <- SketchRef | str
template <>
struct type_caster<scad::SketchTarget> {
PYBIND11_TYPE_CASTER(scad::SketchTarget, const_name("SketchRef | str"));
bool load(handle src, bool) {
if (isinstance<scad::SketchRef>(src)) {
value = scad::SketchTarget(src.cast<scad::SketchRef>());
return true;
}
if (isinstance<str>(src)) {
value = scad::SketchTarget(src.cast<std::string>());
return true;
}
return false;
}
static handle cast(const scad::SketchTarget& target, return_value_policy, handle) {
return target.is_ref() ? pybind11::cast(target.ref()).release() : pybind11::cast(target.path()).release();
}
};
// SketchControlPoint <- SketchRef | str | {"point_id": ...} | (x, y)
template <>
struct type_caster<scad::SketchControlPoint> {
public:
PYBIND11_TYPE_CASTER(scad::SketchControlPoint, const_name("SketchRef | str | tuple[float, float]"));
bool load(handle src, bool) {
if (isinstance<scad::SketchRef>(src)) {
value = scad::SketchControlPoint(scad::SketchTarget(src.cast<scad::SketchRef>()));
return true;
}
if (isinstance<str>(src)) {
value = scad::SketchControlPoint(src.cast<std::string>());
return true;
}
if (isinstance<dict>(src)) {
const dict mapping = reinterpret_borrow<dict>(src);
object point = mapping.contains("point_id") ? mapping["point_id"] : (mapping.contains("point") ? mapping["point"] : object());
if (!point) throw scad::ValueError("bspline control point mapping requires point_id");
value = scad::SketchControlPoint(str(point).cast<std::string>());
return true;
}
if (isinstance<sequence>(src)) {
const sequence seq = reinterpret_borrow<sequence>(src);
if (seq.size() != 2) {
throw scad::ValueError("bspline control point must contain exactly two coordinates");
}
value = scad::SketchControlPoint(seq[0].cast<double>(), seq[1].cast<double>());
return true;
}
return false;
}
};
// SketchProfileId <- int | str
template <>
struct type_caster<scad::SketchProfileId> {
PYBIND11_TYPE_CASTER(scad::SketchProfileId, const_name("int | str"));
bool load(handle src, bool) {
if (isinstance<str>(src)) {
value = scad::SketchProfileId(src.cast<std::string>());
return true;
}
if (PyLong_Check(src.ptr()) && !PyBool_Check(src.ptr())) {
value = scad::SketchProfileId(src.cast<int>());
return true;
}
return false;
}
static handle cast(const scad::SketchProfileId& id, return_value_policy, handle) {
return id.is_index() ? pybind11::cast(id.index()).release() : pybind11::cast(id.id()).release();
}
};
} // namespace pybind11::detail
namespace {
using namespace scad;
using pybind::value_from_python;
using pybind::value_to_python;
// A Python object that implements the SketchSolverBackend protocol.
class PythonBackend final : public SketchSolverBackend {
public:
explicit PythonBackend(py::object object) : object_(std::move(object)) {}
~PythonBackend() override { scad::pybind::drop_python_reference(object_); }
std::string name() const override {
const py::gil_scoped_acquire gil;
return py::str(object_.attr("name")).cast<std::string>();
}
std::string version() const override {
const py::gil_scoped_acquire gil;
return py::str(object_.attr("version")).cast<std::string>();
}
SketchSolveResult solve(const Sketch& sketch, const SketchSolverOptions& options) const override {
const py::gil_scoped_acquire gil;
py::object result = object_.attr("solve")(py::cast(sketch), py::arg("options") = py::cast(options));
return result.cast<SketchSolveResult>();
}
private:
py::object object_;
};
std::shared_ptr<SketchSolverBackend> backend_from_python(const py::object& backend) {
if (backend.is_none()) return get_default_sketch_solver_backend();
if (py::isinstance<py::str>(backend)) return get_sketch_solver_backend(backend.cast<std::string>());
if (py::isinstance<SketchSolverBackend>(backend)) return backend.cast<std::shared_ptr<SketchSolverBackend>>();
return std::make_shared<PythonBackend>(backend);
}
template <class T>
py::dict to_dict_of(const OrderedMap<T>& map, py::object (*convert)(const T&)) {
py::dict out;
for (const auto& [key, value] : map) out[py::str(key)] = convert(value);
return out;
}
template <class T>
OrderedMap<T> from_dict_of(const py::object& mapping, T (*convert)(const py::handle&)) {
OrderedMap<T> out;
if (mapping.is_none()) return out;
for (const auto& item : mapping.cast<py::dict>()) out.set(py::str(item.first).cast<std::string>(), convert(item.second));
return out;
}
py::object point_to_python(const SketchPoint2& p) { return py::make_tuple(p.first, p.second); }
py::object double_to_python(const double& v) { return py::float_(v); }
py::object value_object(const Value& v) { return value_to_python(v); }
SketchPoint2 point_from_python(const py::handle& h) {
const py::sequence seq = py::reinterpret_borrow<py::sequence>(h);
return {seq[0].cast<double>(), seq[1].cast<double>()};
}
double double_from_python(const py::handle& h) { return h.cast<double>(); }
Value value_from_handle(const py::handle& h) { return value_from_python(h); }
SketchSolveRequest request_of(bool require_fully_constrained, bool strict, double tolerance, int max_iterations) {
SketchSolveRequest request;
request.require_fully_constrained = require_fully_constrained;
request.strict = strict;
request.tolerance = tolerance;
request.max_iterations = max_iterations;
return request;
}
void bind_data_classes(py::module_& m) {
py::class_<SketchRef>(m, "SketchRef")
.def(py::init([](std::string sketch_id, std::string entity_id, std::string kind, std::string subentity) {
return SketchRef{std::move(sketch_id), std::move(entity_id), std::move(kind), std::move(subentity)};
}),
py::arg("sketch_id"), py::arg("entity_id"), py::kw_only(), py::arg("kind"), py::arg("subentity") = "geometry")
.def_readwrite("sketch_id", &SketchRef::sketch_id)
.def_readwrite("entity_id", &SketchRef::entity_id)
.def_readwrite("kind", &SketchRef::kind)
.def_readwrite("subentity", &SketchRef::subentity)
.def("to_dict", [](const SketchRef& r) { return value_to_python(r.to_value()); })
.def_static("from_dict", [](const py::object& data) { return SketchRef::from_value(value_from_python(data)); })
.def("__repr__", &SketchRef::repr)
.def("__eq__", [](const SketchRef& a, const SketchRef& b) { return a == b; })
.def("__hash__", [](const SketchRef& r) { return std::hash<std::string>{}(r.sketch_id + "|" + r.entity_id + "|" + r.kind + "|" + r.subentity); });
py::class_<SketchEntity>(m, "SketchEntity")
.def_property_readonly("entity_id", [](const SketchEntity& e) { return e.id; })
.def_readonly("kind", &SketchEntity::kind)
.def_readonly("construction", &SketchEntity::construction)
.def_property_readonly("data", [](const SketchEntity& e) { return value_to_python(e.data); })
.def("to_dict", [](const SketchEntity& e) { return value_to_python(e.to_value()); });
py::class_<SketchConstraint>(m, "SketchConstraint")
.def_property_readonly("constraint_id", [](const SketchConstraint& c) { return c.id; })
.def_readonly("kind", &SketchConstraint::kind)
.def_property_readonly("targets", [](const SketchConstraint& c) {
py::list targets;
for (const SketchRef& t : c.targets) targets.append(value_to_python(t.to_value()));
return py::tuple(targets);
})
.def_property_readonly("value", [](const SketchConstraint& c) -> py::object {
return c.value ? py::object(py::float_(c.numeric_value())) : py::none();
})
.def_readonly("driving", &SketchConstraint::driving)
.def_property_readonly("metadata", [](const SketchConstraint& c) { return value_to_python(c.metadata); })
.def("to_dict", [](const SketchConstraint& c) { return value_to_python(c.to_value()); });
py::class_<SketchConstraintDiagnostic>(m, "SketchConstraintDiagnostic")
.def(py::init([](std::optional<std::string> constraint_id, std::string severity, std::string code, std::string message,
std::optional<double> residual) {
return SketchConstraintDiagnostic{std::move(constraint_id), std::move(severity), std::move(code),
std::move(message), residual};
}),
py::arg("constraint_id"), py::arg("severity"), py::arg("code"), py::arg("message"), py::arg("residual") = py::none())
.def_readonly("constraint_id", &SketchConstraintDiagnostic::constraint_id)
.def_readonly("severity", &SketchConstraintDiagnostic::severity)
.def_readonly("code", &SketchConstraintDiagnostic::code)
.def_readonly("message", &SketchConstraintDiagnostic::message)
.def_readonly("residual", &SketchConstraintDiagnostic::residual);
py::class_<SketchSolverOptions>(m, "SketchSolverOptions")
.def(py::init([](double tolerance, int max_iterations) { return SketchSolverOptions{tolerance, max_iterations}; }),
py::arg("tolerance") = 1e-7, py::arg("max_iterations") = 80)
.def_readonly("tolerance", &SketchSolverOptions::tolerance)
.def_readonly("max_iterations", &SketchSolverOptions::max_iterations);
py::class_<SketchSolveResult>(m, "SketchSolveResult")
.def(py::init([](std::string sketch_id, std::string status, int dof, double residual_norm, int iterations,
const py::object& solved_points, const py::object& solved_scalars, const py::object& solved_entities,
const py::object& diagnostics, std::string backend, std::string backend_version,
std::optional<int> backend_status_code) {
SketchSolveResult r;
r.sketch_id = std::move(sketch_id);
r.status = std::move(status);
r.dof = dof;
r.residual_norm = residual_norm;
r.iterations = iterations;
r.solved_points = from_dict_of<SketchPoint2>(solved_points, point_from_python);
r.solved_scalars = from_dict_of<double>(solved_scalars, double_from_python);
r.solved_entities = from_dict_of<Value>(solved_entities, value_from_handle);
if (!diagnostics.is_none()) {
for (const auto& item : diagnostics) r.diagnostics.push_back(item.cast<SketchConstraintDiagnostic>());
}
r.backend = std::move(backend);
r.backend_version = std::move(backend_version);
r.backend_status_code = backend_status_code;
return r;
}),
py::arg("sketch_id"), py::arg("status"), py::arg("dof"), py::arg("residual_norm"), py::arg("iterations"),
py::arg("solved_points"), py::arg("solved_scalars"), py::arg("solved_entities") = py::none(),
py::arg("diagnostics") = py::none(), py::arg("backend") = "unknown", py::arg("backend_version") = "unknown",
py::arg("backend_status_code") = py::none())
.def_readwrite("sketch_id", &SketchSolveResult::sketch_id)
.def_readwrite("status", &SketchSolveResult::status)
.def_readwrite("dof", &SketchSolveResult::dof)
.def_readwrite("residual_norm", &SketchSolveResult::residual_norm)
.def_readwrite("iterations", &SketchSolveResult::iterations)
.def_property_readonly("solved_points", [](const SketchSolveResult& r) { return to_dict_of<SketchPoint2>(r.solved_points, point_to_python); })
.def_property_readonly("solved_scalars", [](const SketchSolveResult& r) { return to_dict_of<double>(r.solved_scalars, double_to_python); })
.def_property_readonly("solved_entities", [](const SketchSolveResult& r) { return to_dict_of<Value>(r.solved_entities, value_object); })
.def_property_readonly("diagnostics", [](const SketchSolveResult& r) { return py::tuple(py::cast(r.diagnostics)); })
.def_readwrite("backend", &SketchSolveResult::backend)
.def_readwrite("backend_version", &SketchSolveResult::backend_version)
.def_readwrite("backend_status_code", &SketchSolveResult::backend_status_code)
.def("to_dict", [](const SketchSolveResult& r) { return value_to_python(r.to_value()); });
}
void bind_backends(py::module_& m) {
py::class_<SketchSolverBackend, std::shared_ptr<SketchSolverBackend>>(m, "SketchSolverBackend")
.def_property_readonly("name", [](const SketchSolverBackend& b) { return b.name(); })
.def_property_readonly("version", [](const SketchSolverBackend& b) { return b.version(); })
.def("solve", [](const SketchSolverBackend& b, const Sketch& sketch, const SketchSolverOptions& options) {
return b.solve(sketch, options);
},
py::arg("sketch"), py::kw_only(), py::arg("options"));
m.def("register_sketch_solver_backend",
[](const py::object& backend, bool replace) {
register_sketch_solver_backend(py::isinstance<SketchSolverBackend>(backend)
? backend.cast<std::shared_ptr<SketchSolverBackend>>()
: std::make_shared<PythonBackend>(backend),
replace);
},
py::arg("backend"), py::kw_only(), py::arg("replace") = false);
m.def("get_sketch_solver_backend", [](const std::optional<std::string>& name) { return get_sketch_solver_backend(name); },
py::arg("name") = py::none());
m.def("get_default_sketch_solver_backend", [] { return get_default_sketch_solver_backend(); });
m.def("set_default_sketch_solver_backend", [](const py::object& backend) {
if (py::isinstance<py::str>(backend)) {
set_default_sketch_solver_backend(backend.cast<std::string>());
} else {
set_default_sketch_solver_backend(backend_from_python(backend));
}
}, py::arg("backend"));
// `with sketch_solver_backend(...)`: select, then restore the previous default.
struct BackendContext {
py::object backend;
std::string previous;
};
py::class_<BackendContext>(m, "_SketchSolverBackendContext")
.def("__enter__", [](BackendContext& c) {
c.previous = get_default_sketch_solver_backend()->name();
if (py::isinstance<py::str>(c.backend)) {
set_default_sketch_solver_backend(c.backend.cast<std::string>());
} else {
set_default_sketch_solver_backend(backend_from_python(c.backend));
}
return get_default_sketch_solver_backend();
})
.def("__exit__", [](BackendContext& c, const py::args&) {
set_default_sketch_solver_backend(c.previous);
return false;
});
m.def("sketch_solver_backend", [](const py::object& backend) { return BackendContext{backend, {}}; }, py::arg("backend"));
}
void bind_sketch_class(py::module_& m) {
py::class_<Sketch>(m, "Sketch")
.def(py::init([](const py::object& curves, std::optional<std::string> name, const py::object& plane,
std::optional<std::string> sketch_id) {
Sketch sketch(std::move(name), value_from_python(plane), std::move(sketch_id));
if (!curves.is_none()) {
for (const auto& curve : curves) sketch.add_curve(curve.cast<Shape>());
}
return sketch;
}),
py::arg("curves") = py::none(), py::kw_only(), py::arg("name") = py::none(), py::arg("plane") = "XY",
py::arg("sketch_id") = py::none())
.def_property_readonly("sketch_id", [](const Sketch& s) { return s.sketch_id(); })
.def_property_readonly("name", [](const Sketch& s) { return s.name(); })
.def_property_readonly("plane", [](const Sketch& s) {
py::object plane = value_to_python(s.plane());
// A plane mapping holds its frame vectors as tuples of floats.
if (py::isinstance<py::dict>(plane)) {
for (const char* key : {"origin", "x_axis", "y_axis", "z_axis"})
if (plane.contains(key) && py::isinstance<py::list>(plane[key])) plane[key] = py::tuple(plane[key]);
}
return plane;
})
.def_property_readonly("entities", [](const Sketch& s) {
py::dict out;
for (const auto& [id, entity] : s.entities()) out[py::str(id)] = entity;
return out;
})
.def_property_readonly("entity_order", [](const Sketch& s) { return s.entities().keys(); })
.def_property_readonly("constraints", [](const Sketch& s) { return s.constraints(); })
.def("add_curve", [](Sketch& s, const Shape& curve) -> Sketch& { return s.add_curve(curve); }, py::arg("curve"),
py::return_value_policy::reference_internal)
.def("curves", &Sketch::curves)
.def("closed_wires", &Sketch::closed_wires)
.def("to_faces", [](const Sketch& s) { return sketch_to_faces(s); })
.def("to_face", [](const Sketch& s, const SketchProfileId& profile, const std::vector<SketchProfileId>& inner) {
return make_face_from_sketch_rface(s, profile, inner);
},
py::arg("profile") = 0, py::kw_only(), py::arg("inner_profiles") = std::vector<SketchProfileId>{})
.def("clone", [](const Sketch& s, bool include_solve) { return s.clone(include_solve); }, py::kw_only(),
py::arg("include_solve") = true)
.def("to_dict", [](const Sketch& s) { return value_to_python(s.to_value()); })
.def_static("from_dict", [](const py::object& data) { return Sketch::from_value(value_from_python(data)); })
.def("ref", [](const Sketch& s, const std::string& entity_id, std::optional<std::string> kind, const std::string& sub) {
return s.ref(entity_id, kind, sub);
},
py::arg("entity_id"), py::kw_only(), py::arg("kind") = py::none(), py::arg("subentity") = "geometry")
.def("point_ref", &Sketch::point_ref, py::arg("path"))
.def("resolve_target", [](const Sketch& s, const SketchTarget& target, const py::object& expected) {
std::vector<std::string> kinds;
if (py::isinstance<py::str>(expected)) {
kinds.push_back(expected.cast<std::string>());
} else if (!expected.is_none()) {
for (const auto& item : expected) kinds.push_back(py::str(item).cast<std::string>());
}
return s.resolve_target(target, kinds);
},
py::arg("target"), py::kw_only(), py::arg("expected") = py::none())
.def("validate_ref", &Sketch::validate_ref, py::arg("ref"))
.def("resolve_point_id", &Sketch::resolve_point_id, py::arg("ref"))
.def("add_point", &Sketch::add_point, py::arg("point_id"), py::arg("x"), py::arg("y"))
.def("add_line", [](Sketch& s, const std::string& id, const SketchRef& a, const SketchRef& b, bool construction) -> Sketch& {
return s.add_line(id, a, b, construction);
},
py::arg("entity_id"), py::arg("start"), py::arg("end"), py::kw_only(), py::arg("construction") = false,
py::return_value_policy::reference_internal)
.def("add_circle", [](Sketch& s, const std::string& id, const SketchRef& c, const Scalar& r, bool construction) -> Sketch& {
return s.add_circle(id, c, r, construction);
},
py::arg("entity_id"), py::arg("center"), py::arg("radius"), py::kw_only(), py::arg("construction") = false,
py::return_value_policy::reference_internal)
.def("add_arc", [](Sketch& s, const std::string& id, const SketchRef& a, const SketchRef& b, const SketchRef& c, bool construction) -> Sketch& {
return s.add_arc(id, a, b, c, construction);
},
py::arg("entity_id"), py::arg("start"), py::arg("end"), py::arg("center"), py::kw_only(),
py::arg("construction") = false, py::return_value_policy::reference_internal)
.def("add_ellipse", [](Sketch& s, const std::string& id, const SketchRef& c, const SketchRef& a, const SketchRef& b, bool construction) -> Sketch& {
return s.add_ellipse(id, c, a, b, construction);
},
py::arg("entity_id"), py::arg("center"), py::arg("major_point"), py::arg("minor_point"), py::kw_only(),
py::arg("construction") = false, py::return_value_policy::reference_internal)
.def("add_bspline",
[](Sketch& s, const std::string& id, const SketchRef& start, const SketchRef& end,
const std::vector<SketchControlPoint>& control_points, int degree,
const std::optional<std::vector<Scalar>>& knots, const std::optional<std::vector<int>>& multiplicities,
const std::optional<std::vector<Scalar>>& weights, bool periodic, bool construction) -> Sketch& {
return s.add_bspline(id, start, end, control_points, degree, knots, multiplicities, weights, periodic, construction);
},
py::arg("entity_id"), py::arg("start"), py::arg("end"), py::arg("control_points"), py::arg("degree") = 3,
py::arg("knots") = py::none(), py::arg("multiplicities") = py::none(), py::arg("weights") = py::none(),
py::arg("periodic") = false, py::kw_only(), py::arg("construction") = false,
py::return_value_policy::reference_internal)
.def("add_constraint",
[](Sketch& s, const std::string& kind, const std::vector<SketchRef>& targets, const py::object& value,
std::optional<std::string> constraint_id, bool driving, const py::object& metadata) -> Sketch& {
std::optional<Scalar> scalar;
if (!value.is_none()) scalar = value.cast<Scalar>();
return s.add_constraint(kind, targets, scalar, constraint_id, driving,
metadata.is_none() ? Value::object() : value_from_python(metadata));
},
py::arg("kind"), py::arg("targets"), py::kw_only(), py::arg("value") = py::none(),
py::arg("constraint_id") = py::none(), py::arg("driving") = true, py::arg("metadata") = py::none(),
py::return_value_policy::reference_internal)
.def("solve",
[](Sketch& s, bool require_fully_constrained, bool strict, double tolerance, int max_iterations,
const py::object& backend) {
SketchSolveRequest request = request_of(require_fully_constrained, strict, tolerance, max_iterations);
request.backend = backend_from_python(backend);
return s.solve(request);
},
py::kw_only(), py::arg("require_fully_constrained") = false, py::arg("strict") = true,
py::arg("tolerance") = 1e-7, py::arg("max_iterations") = 80, py::arg("backend") = py::none())
.def("solved_result", [](Sketch& s) { return s.solved_result(); })
.def("make_wire", [](const Sketch& s, const SketchProfileId& profile) { return make_wire_from_sketch_rwire(s, profile); },
py::arg("profile") = 0)
.def("make_face", [](const Sketch& s, const SketchProfileId& profile, const std::vector<SketchProfileId>& inner) {
return make_face_from_sketch_rface(s, profile, inner);
},
py::arg("profile") = 0, py::kw_only(), py::arg("inner_profiles") = std::vector<SketchProfileId>{})
.def("get_metadata", [](const Sketch& s, const std::string& key, const Value& fallback) {
const Value* found = s.metadata().find(key);
return found != nullptr ? *found : fallback;
},
py::arg("key"), py::arg("default") = Value())
.def("set_metadata", [](Sketch& s, const std::string& key, const Value& value) { s.metadata().set(key, value); })
.def("_set_runtime", [](Sketch& s, const std::string& key, const Value& value) { s.runtime().set(key, value); })
.def("_get_runtime", [](const Sketch& s, const std::string& key, const Value& fallback) {
const Value* found = s.runtime().find(key);
return found != nullptr ? *found : fallback;
},
py::arg("key"), py::arg("default") = Value())
.def("__repr__", [](const Sketch& s) {
return "Sketch(sketch_id='" + s.sketch_id() + "', entities=" + std::to_string(s.entities().size()) +
", constraints=" + std::to_string(s.constraints().size()) + ")";
});
}
void bind_entity_operators(py::module_& m) {
m.def("make_sketch_rsketch",
[](const std::optional<std::string>& name, const py::object& plane, const std::optional<std::string>& sketch_id) {
return make_sketch_rsketch(name, value_from_python(plane), sketch_id);
},
py::arg("name") = py::none(), py::kw_only(), py::arg("plane") = "XY", py::arg("sketch_id") = py::none());
m.def("add_point_rsketch", &add_point_rsketch, py::arg("sketch"), py::arg("point_id"), py::arg("x"), py::arg("y"));
m.def("get_sketch_entity_rsketchref", &get_sketch_entity_rsketchref, py::arg("sketch"), py::arg("entity_id"));
m.def("get_sketch_point_rsketchref", &get_sketch_point_rsketchref, py::arg("sketch"), py::arg("point_path"));
m.def("add_line_rsketch", &add_line_rsketch, py::arg("sketch"), py::arg("entity_id"), py::arg("start"), py::arg("end"),
py::kw_only(), py::arg("construction") = false);
m.def("add_circle_rsketch", &add_circle_rsketch, py::arg("sketch"), py::arg("entity_id"), py::arg("center"),
py::arg("radius"), py::kw_only(), py::arg("construction") = false);
m.def("add_ellipse_rsketch", &add_ellipse_rsketch, py::arg("sketch"), py::arg("entity_id"), py::arg("center"),
py::arg("major_point"), py::arg("minor_point"), py::kw_only(), py::arg("construction") = false);
m.def("add_bspline_rsketch", &add_bspline_rsketch, py::arg("sketch"), py::arg("entity_id"), py::arg("start"),
py::arg("end"), py::arg("control_points"), py::arg("degree") = 3, py::arg("knots") = py::none(),
py::arg("multiplicities") = py::none(), py::arg("weights") = py::none(), py::arg("periodic") = false,
py::kw_only(), py::arg("construction") = false);
m.def("add_arc_rsketch", &add_arc_rsketch, py::arg("sketch"), py::arg("entity_id"), py::arg("start"), py::arg("end"),
py::arg("center"), py::kw_only(), py::arg("construction") = false);
}
// (sketch, a, b, *, constraint_id=None)
template <class F>
void def_two(py::module_& m, const char* name, F fn, const char* first = "a", const char* second = "b") {
m.def(name, fn, py::arg("sketch"), py::arg(first), py::arg(second), py::kw_only(), py::arg("constraint_id") = py::none());
}
// (sketch, target, *, constraint_id=None)
template <class F>
void def_one(py::module_& m, const char* name, F fn, const char* target) {
m.def(name, fn, py::arg("sketch"), py::arg(target), py::kw_only(), py::arg("constraint_id") = py::none());
}
// (sketch, a, b, value, *, constraint_id=None, driving=True)
template <class F>
void def_two_value(py::module_& m, const char* name, F fn) {
m.def(name, fn, py::arg("sketch"), py::arg("a"), py::arg("b"), py::arg("value"), py::kw_only(),
py::arg("constraint_id") = py::none(), py::arg("driving") = true);
}
// (sketch, target, value, *, constraint_id=None, driving=True)
template <class F>
void def_one_value(py::module_& m, const char* name, F fn, const char* target) {
m.def(name, fn, py::arg("sketch"), py::arg(target), py::arg("value"), py::kw_only(),
py::arg("constraint_id") = py::none(), py::arg("driving") = true);
}
void bind_constraint_operators(py::module_& m) {
m.def("_constrain_rsketch",
[](const Sketch& sketch, const std::string& kind, const std::vector<SketchTarget>& targets,
const std::optional<Scalar>& value, const SketchConstraintId& id, bool driving, const Value& metadata,
const py::object&) { return constrain_rsketch(sketch, kind, targets, value, id, driving, metadata); },
py::arg("sketch"), py::arg("kind"), py::arg("targets"),
py::kw_only(), py::arg("value") = py::none(), py::arg("constraint_id") = py::none(), py::arg("driving") = true,
py::arg("metadata") = py::none(), py::arg("expected") = py::none(),
"Any constraint kind by name (graph replay); `expected` is accepted and not used.");
def_two(m, "constrain_coincident_rsketch", &constrain_coincident_rsketch);
def_two(m, "constrain_connect_rsketch", &constrain_connect_rsketch);
def_two(m, "constrain_point_on_rsketch", &constrain_point_on_rsketch, "point", "entity");
def_one(m, "constrain_horizontal_rsketch", &constrain_horizontal_rsketch, "line");
def_one(m, "constrain_vertical_rsketch", &constrain_vertical_rsketch, "line");
def_two(m, "constrain_points_horizontal_rsketch", &constrain_points_horizontal_rsketch);
def_two(m, "constrain_points_vertical_rsketch", &constrain_points_vertical_rsketch);
def_two_value(m, "constrain_line_distance_rsketch", &constrain_line_distance_rsketch);
def_two(m, "constrain_normal_rsketch", &constrain_normal_rsketch);
m.def("constrain_mirror_rsketch", &constrain_mirror_rsketch, py::arg("sketch"), py::arg("a"), py::arg("axis"), py::arg("b"),
py::kw_only(), py::arg("constraint_id") = py::none());
m.def("constrain_midpoint_points_rsketch", &constrain_midpoint_points_rsketch, py::arg("sketch"), py::arg("mid"),
py::arg("a"), py::arg("b"), py::kw_only(), py::arg("constraint_id") = py::none());
def_two(m, "constrain_parallel_rsketch", &constrain_parallel_rsketch);
def_two(m, "constrain_perpendicular_rsketch", &constrain_perpendicular_rsketch);
def_two(m, "constrain_collinear_rsketch", &constrain_collinear_rsketch);
m.def("constrain_tangent_rsketch", &constrain_tangent_rsketch, py::arg("sketch"), py::arg("a"), py::arg("b"),
py::kw_only(), py::arg("at_a") = py::none(), py::arg("at_b") = py::none(), py::arg("mode") = "external",
py::arg("constraint_id") = py::none());
def_two(m, "constrain_concentric_rsketch", &constrain_concentric_rsketch);
def_two(m, "constrain_midpoint_rsketch", &constrain_midpoint_rsketch, "point", "line");
m.def("constrain_symmetric_rsketch", &constrain_symmetric_rsketch, py::arg("sketch"), py::arg("a"), py::arg("b"),
py::arg("axis"), py::kw_only(), py::arg("constraint_id") = py::none());
def_two(m, "constrain_equal_length_rsketch", &constrain_equal_length_rsketch);
def_two(m, "constrain_equal_radius_rsketch", &constrain_equal_radius_rsketch);
def_two_value(m, "constrain_distance_rsketch", &constrain_distance_rsketch);
def_two_value(m, "constrain_distance_x_rsketch", &constrain_distance_x_rsketch);
def_two_value(m, "constrain_distance_y_rsketch", &constrain_distance_y_rsketch);
def_one_value(m, "constrain_length_rsketch", &constrain_length_rsketch, "line");
def_two_value(m, "constrain_angle_rsketch", &constrain_angle_rsketch);
def_one_value(m, "constrain_radius_rsketch", &constrain_radius_rsketch, "circle");
def_one_value(m, "constrain_diameter_rsketch", &constrain_diameter_rsketch, "circle");
def_one_value(m, "constrain_major_radius_rsketch", &constrain_major_radius_rsketch, "ellipse");
def_one_value(m, "constrain_minor_radius_rsketch", &constrain_minor_radius_rsketch, "ellipse");
def_one(m, "constrain_fix_rsketch", &constrain_fix_rsketch, "target");
}
void bind_solve_operators(py::module_& m) {
m.def("inspect_sketch_rsketchresult",
[](const Sketch& sketch, bool fully, bool strict, double tolerance, int max_iterations) {
return inspect_sketch_rsketchresult(sketch, request_of(fully, strict, tolerance, max_iterations));
},
py::arg("sketch"), py::kw_only(), py::arg("require_fully_constrained") = false, py::arg("strict") = true,
py::arg("tolerance") = 1e-7, py::arg("max_iterations") = 80);
m.def("make_wire_from_sketch_rwire",
[](const Sketch& sketch, const SketchProfileId& profile, bool fully, bool strict, double tolerance, int max_iterations) {
return make_wire_from_sketch_rwire(sketch, profile, request_of(fully, strict, tolerance, max_iterations));
},
py::arg("sketch"), py::arg("profile") = 0, py::kw_only(), py::arg("require_fully_constrained") = false,
py::arg("strict") = true, py::arg("tolerance") = 1e-7, py::arg("max_iterations") = 80);
m.def("make_face_from_sketch_rface",
[](const Sketch& sketch, const SketchProfileId& profile, const std::vector<SketchProfileId>& inner, bool fully,
bool strict, double tolerance, int max_iterations) {
return make_face_from_sketch_rface(sketch, profile, inner, request_of(fully, strict, tolerance, max_iterations));
},
py::arg("sketch"), py::arg("profile") = 0, py::kw_only(), py::arg("inner_profiles") = std::vector<SketchProfileId>{},
py::arg("require_fully_constrained") = false, py::arg("strict") = true, py::arg("tolerance") = 1e-7,
py::arg("max_iterations") = 80);
}
} // namespace
void bind_sketch(py::module_& m) {
bind_data_classes(m);
bind_backends(m);
bind_sketch_class(m);
bind_entity_operators(m);
bind_constraint_operators(m);
bind_solve_operators(m);
}
+498
View File
@@ -0,0 +1,498 @@
// Python bindings for the "std" area: `simplecadapi._cpp.std` with the submodules `gear`, `bearing`,
// `chain` and `fastener`, under the names, argument names and defaults of simplecadapi.std.
//
// The factories record the operations they are built from, not themselves, so there is no
// executor to register: a recorded gear replays through the operators it was made of.
// `build_ball_bearing` (the durable-definition wrapper over the build layer) is not provided.
#include "bindings.hpp"
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "scad/core/error.hpp"
#include "scad/product/assembly.hpp"
#include "scad/product/material.hpp"
#include "scad/sketch/operators.hpp"
#include "scad/sketch/sketch.hpp"
#include "scad/std/std.hpp"
namespace {
using namespace scad;
// Runs `body` with the GIL released; an exception leaves with the GIL back.
template <class F>
auto unlocked(F&& body) {
const py::gil_scoped_release release;
return body();
}
ToothTuning tuning(double addendum_factor, double clearance_factor, double backlash) {
return {addendum_factor, clearance_factor, backlash};
}
// `isinstance(value, int) and not isinstance(value, bool)`, as the chain and nut factories test it.
bool is_plain_int(const py::object& value) { return PyLong_Check(value.ptr()) != 0 && !PyBool_Check(value.ptr()); }
// `int(value)`, for the arguments Python converts that way.
int python_int(const py::object& value) { return py::int_(value).cast<int>(); }
// `str(value)`, the way the fastener factories read their style arguments.
std::string text_of(const py::object& value) { return py::str(value).cast<std::string>(); }
py::object point_to_py(const stdlib::Point2& p) { return py::make_tuple(p.x, p.y); }
stdlib::Point2 point_from_py(const py::object& value) {
const py::sequence items = py::reinterpret_borrow<py::sequence>(value);
if (items.size() != 2) throw ValueError("a 2D point needs two coordinates");
return {items[0].cast<double>(), items[1].cast<double>()};
}
// ---- gear -----------------------------------------------------------------------------------------------------
void bind_gear_factories(py::module_& gear) {
gear.def(
"make_spur_gear_rsolid",
[](int n_teeth, double module, double pressure_angle, double gear_height, double addendum_factor,
double clearance_factor, double backlash) {
return unlocked([&] {
return make_spur_gear_rsolid(n_teeth, module, pressure_angle, gear_height,
tuning(addendum_factor, clearance_factor, backlash));
});
},
py::arg("n_teeth"), py::arg("module"), py::arg("pressure_angle") = 20.0, py::arg("gear_height") = 6.0, py::kw_only(),
py::arg("addendum_factor") = 1.0, py::arg("clearance_factor") = 0.25, py::arg("backlash") = 0.0,
"Create an involute spur gear (straight teeth, helix angle = 0).\n\n"
"n_teeth >= 3; module in mm (pitch diameter = module * n_teeth); pressure_angle in degrees;\n"
"gear_height is the thickness along Z. addendum_factor and clearance_factor are multiples of\n"
"the module; backlash is the circumferential tooth-thickness reduction at the pitch circle in mm.");
gear.def(
"make_straight_bevel_gear_rsolid",
[](int n_teeth, double module, double pitch_angle, double pressure_angle, double face_width,
double addendum_factor, double clearance_factor, double backlash) {
return unlocked([&] {
return make_straight_bevel_gear_rsolid(n_teeth, module, pitch_angle, pressure_angle, face_width,
tuning(addendum_factor, clearance_factor, backlash));
});
},
py::arg("n_teeth"), py::arg("module"), py::arg("pitch_angle") = 45.0, py::arg("pressure_angle") = 20.0,
py::arg("face_width") = 8.0, py::kw_only(), py::arg("addendum_factor") = 1.0, py::arg("clearance_factor") = 0.25,
py::arg("backlash") = 0.0,
"Create a straight bevel gear with standard metric tooth proportions.\n\n"
"The large-end section is the spur-gear involute profile; a similar small-end section sits on the\n"
"pitch cone and the two are joined with ruled tooth surfaces. face_width runs along the pitch-cone\n"
"generator. Metadata 'std.gear.straight_bevel'.");
gear.def(
"make_helical_gear_rsolid",
[](int n_teeth, double module, double pressure_angle, double helix_angle, double gear_height,
double addendum_factor, double clearance_factor, double backlash) {
return unlocked([&] {
return make_helical_gear_rsolid(n_teeth, module, pressure_angle, helix_angle, gear_height,
tuning(addendum_factor, clearance_factor, backlash));
});
},
py::arg("n_teeth"), py::arg("module"), py::arg("pressure_angle") = 20.0, py::arg("helix_angle") = 30.0,
py::arg("gear_height") = 8.0, py::kw_only(), py::arg("addendum_factor") = 1.0, py::arg("clearance_factor") = 0.25,
py::arg("backlash") = 0.0,
"Create an involute helical gear: one continuous twisted sweep along the gear axis (a zero helix\n"
"angle gives the spur gear).");
gear.def(
"make_herringbone_gear_rsolid",
[](int n_teeth, double module, double pressure_angle, double helix_angle, double gear_height,
double addendum_factor, double clearance_factor, double backlash) {
return unlocked([&] {
return make_herringbone_gear_rsolid(n_teeth, module, pressure_angle, helix_angle, gear_height,
tuning(addendum_factor, clearance_factor, backlash));
});
},
py::arg("n_teeth"), py::arg("module"), py::arg("pressure_angle") = 20.0, py::arg("helix_angle") = 32.0,
py::arg("gear_height") = 10.0, py::kw_only(), py::arg("addendum_factor") = 1.0, py::arg("clearance_factor") = 0.25,
py::arg("backlash") = 0.0,
"Create an involute herringbone (double-helical) gear: two opposite twisted halves fused at the\n"
"shared centre section.");
gear.def(
"make_spur_ring_gear_rsolid",
[](int n_teeth, double module, double pressure_angle, double gear_height, double rim_thickness, double backlash,
double addendum_factor, double clearance_factor) {
return unlocked([&] {
return make_spur_ring_gear_rsolid(n_teeth, module, pressure_angle, gear_height, rim_thickness,
tuning(addendum_factor, clearance_factor, backlash));
});
},
py::arg("n_teeth"), py::arg("module"), py::arg("pressure_angle") = 20.0, py::arg("gear_height") = 6.0,
py::arg("rim_thickness") = 3.0, py::arg("backlash") = 0.0, py::kw_only(), py::arg("addendum_factor") = 1.0,
py::arg("clearance_factor") = 0.25,
"Create an internal spur ring gear: the rim circle and the inward tooth profile form one multi-loop\n"
"face that is extruded directly. backlash is the circumferential tooth-space clearance at the pitch\n"
"circle in mm.");
gear.def(
"make_helical_ring_gear_rsolid",
[](int n_teeth, double module, double pressure_angle, double helix_angle, double gear_height, double rim_thickness,
double backlash, double addendum_factor, double clearance_factor) {
return unlocked([&] {
return make_helical_ring_gear_rsolid(n_teeth, module, pressure_angle, helix_angle, gear_height, rim_thickness,
tuning(addendum_factor, clearance_factor, backlash));
});
},
py::arg("n_teeth"), py::arg("module"), py::arg("pressure_angle") = 20.0, py::arg("helix_angle") = 25.0,
py::arg("gear_height") = 8.0, py::arg("rim_thickness") = 3.0, py::arg("backlash") = 0.0, py::kw_only(),
py::arg("addendum_factor") = 1.0, py::arg("clearance_factor") = 0.25,
"Create an internal helical ring gear: the multi-loop ring face swept with one continuous twist.");
gear.def(
"make_herringbone_ring_gear_rsolid",
[](int n_teeth, double module, double pressure_angle, double helix_angle, double gear_height, double rim_thickness,
double backlash, double addendum_factor, double clearance_factor) {
return unlocked([&] {
return make_herringbone_ring_gear_rsolid(n_teeth, module, pressure_angle, helix_angle, gear_height,
rim_thickness, tuning(addendum_factor, clearance_factor, backlash));
});
},
py::arg("n_teeth"), py::arg("module"), py::arg("pressure_angle") = 20.0, py::arg("helix_angle") = 30.0,
py::arg("gear_height") = 10.0, py::arg("rim_thickness") = 3.0, py::arg("backlash") = 0.0, py::kw_only(),
py::arg("addendum_factor") = 1.0, py::arg("clearance_factor") = 0.25,
"Create an internal herringbone ring gear: two opposite twisted halves of the ring face, fused.");
gear.def(
"make_cycloidal_disc_rsolid",
[](int n_lobes, double ring_pin_pitch_radius, double roller_radius, double eccentricity, double gear_height,
double bore_radius, int output_pin_count, double output_pin_pitch_radius, double output_pin_clearance_radius,
double output_pin_phase, int sample_count_per_lobe, double spline_tolerance, int max_control_points) {
CycloidalDiscOptions options;
options.bore_radius = bore_radius;
options.output_pin_count = output_pin_count;
options.output_pin_pitch_radius = output_pin_pitch_radius;
options.output_pin_clearance_radius = output_pin_clearance_radius;
options.output_pin_phase = output_pin_phase;
options.sample_count_per_lobe = sample_count_per_lobe;
options.spline_tolerance = spline_tolerance;
options.max_control_points = max_control_points;
return unlocked([&] {
return make_cycloidal_disc_rsolid(n_lobes, ring_pin_pitch_radius, roller_radius, eccentricity, gear_height, options);
});
},
py::arg("n_lobes"), py::arg("ring_pin_pitch_radius"), py::arg("roller_radius"), py::arg("eccentricity"),
py::arg("gear_height") = 6.0, py::kw_only(), py::arg("bore_radius") = 0.0, py::arg("output_pin_count") = 0,
py::arg("output_pin_pitch_radius") = 0.0, py::arg("output_pin_clearance_radius") = 0.0,
py::arg("output_pin_phase") = 0.0, py::arg("sample_count_per_lobe") = 33, py::arg("spline_tolerance") = 0.005,
py::arg("max_control_points") = 20,
"Create a cycloidal reducer disc for a one-tooth-difference pin ring.\n\n"
"One fitted cubic B-spline per lobe, an optional central bore and output-pin clearance holes.\n"
"output_pin_phase (degrees) is read in the unrotated disc's frame. Metadata 'std.gear.cycloidal_disc'.");
gear.def(
"make_spur_rack_rsolid",
[](double module, int n_teeth, double pressure_angle, double rack_height) {
return unlocked([&] { return make_spur_rack_rsolid(module, n_teeth, pressure_angle, rack_height); });
},
py::arg("module"), py::arg("n_teeth") = 10, py::arg("pressure_angle") = 20.0, py::arg("rack_height") = 6.0,
"Create a straight-tooth rack (tooth pitch = pi * module, thickness along Z).");
gear.def(
"make_helical_rack_rsolid",
[](double module, int n_teeth, double pressure_angle, double helix_angle, double rack_height) {
return unlocked([&] { return make_helical_rack_rsolid(module, n_teeth, pressure_angle, helix_angle, rack_height); });
},
py::arg("module"), py::arg("n_teeth") = 10, py::arg("pressure_angle") = 20.0, py::arg("helix_angle") = 25.0,
py::arg("rack_height") = 8.0, "Create a helical rack: the rack profile lofted through twisted sections.");
gear.def(
"make_herringbone_rack_rsolid",
[](double module, int n_teeth, double pressure_angle, double helix_angle, double rack_height) {
return unlocked([&] { return make_herringbone_rack_rsolid(module, n_teeth, pressure_angle, helix_angle, rack_height); });
},
py::arg("module"), py::arg("n_teeth") = 10, py::arg("pressure_angle") = 20.0, py::arg("helix_angle") = 30.0,
py::arg("rack_height") = 10.0, "Create a herringbone rack: two opposite twisted halves lofted as one.");
gear.attr("__all__") = py::make_tuple(
"make_spur_gear_rsolid", "make_straight_bevel_gear_rsolid", "make_helical_gear_rsolid", "make_herringbone_gear_rsolid",
"make_spur_ring_gear_rsolid", "make_helical_ring_gear_rsolid", "make_herringbone_ring_gear_rsolid",
"make_cycloidal_disc_rsolid", "make_spur_rack_rsolid", "make_helical_rack_rsolid", "make_herringbone_rack_rsolid");
}
// The private helpers the reference tests reach into (they read the profile sketch and the tooth numbers).
void bind_gear_internals(py::module_& gear) {
gear.def("_involute_point", [](double base_radius, double t) { return point_to_py(stdlib::involute_point(base_radius, t)); },
py::arg("base_radius"), py::arg("t"));
gear.def("_involute_t_for_radius", &stdlib::involute_t_for_radius, py::arg("base_radius"), py::arg("target_radius"));
gear.def("_rotate_xy", [](const py::object& point, double angle) { return point_to_py(stdlib::rotate_xy(point_from_py(point), angle)); },
py::arg("point"), py::arg("angle"));
gear.def(
"_root_fillet_control_points",
[](const py::object& start, const py::object& end, double start_tangent_angle, double end_tangent_angle) {
const stdlib::BSplineData data = stdlib::root_fillet_control_points(point_from_py(start), point_from_py(end),
start_tangent_angle, end_tangent_angle);
py::list poles;
for (const stdlib::Point2& pole : data.control_points) poles.append(point_to_py(pole));
return py::make_tuple(poles, data.degree, data.knots, data.multiplicities);
},
py::arg("start"), py::arg("end"), py::arg("start_tangent_angle"), py::arg("end_tangent_angle"));
gear.def(
"_compute_tooth_geometry",
[](int n_teeth, double module, double pressure_angle, std::optional<double> root_radius,
std::optional<double> tip_radius, double addendum_factor, double clearance_factor, double backlash) {
stdlib::ToothOptions options;
options.root_radius = root_radius;
options.tip_radius = tip_radius;
options.tuning = tuning(addendum_factor, clearance_factor, backlash);
const stdlib::ToothGeometry g = stdlib::compute_tooth_geometry(n_teeth, module, pressure_angle, options);
py::dict out;
out["pitch_radius"] = g.pitch_radius;
out["base_radius"] = g.base_radius;
out["tip_radius"] = g.tip_radius;
out["root_radius"] = g.root_radius;
out["tooth_angle"] = g.tooth_angle;
out["left_start"] = g.left_start;
out["right_start"] = g.right_start;
out["left_tip_angle"] = g.left_tip_angle;
out["right_tip_angle"] = g.right_tip_angle;
out["prev_right_start"] = g.prev_right_start;
out["addendum_factor"] = g.addendum_factor;
out["clearance_factor"] = g.clearance_factor;
out["backlash"] = g.backlash;
return out;
},
py::arg("n_teeth"), py::arg("module"), py::arg("pressure_angle"), py::arg("root_radius") = py::none(),
py::arg("tip_radius") = py::none(), py::arg("addendum_factor") = 1.0, py::arg("clearance_factor") = 0.25,
py::arg("backlash") = 0.0);
gear.def(
"_compute_internal_tooth_geometry",
[](int n_teeth, double module, double pressure_angle, double backlash, double addendum_factor,
double clearance_factor) {
const stdlib::InternalToothGeometry g = stdlib::compute_internal_tooth_geometry(
n_teeth, module, pressure_angle, tuning(addendum_factor, clearance_factor, backlash));
py::dict out;
out["pitch_radius"] = g.pitch_radius;
out["base_radius"] = g.base_radius;
out["tip_radius"] = g.tip_radius;
out["root_radius"] = g.root_radius;
out["flank_tip_radius"] = g.flank_tip_radius;
out["needs_tip_connectors"] = g.needs_tip_connectors;
out["tooth_angle"] = g.tooth_angle;
out["backlash"] = g.backlash;
out["backlash_half_angle"] = g.backlash_half_angle;
out["left_base_angle"] = g.left_base_angle;
out["right_base_angle"] = g.right_base_angle;
out["left_tip_angle"] = g.left_tip_angle;
out["right_tip_angle"] = g.right_tip_angle;
out["left_root_angle"] = g.left_root_angle;
out["right_root_angle"] = g.right_root_angle;
out["addendum_factor"] = g.addendum_factor;
out["clearance_factor"] = g.clearance_factor;
return out;
},
py::arg("n_teeth"), py::arg("module"), py::arg("pressure_angle"), py::arg("backlash") = 0.0,
py::arg("addendum_factor") = 1.0, py::arg("clearance_factor") = 0.25);
gear.def(
"_internal_ring_radii",
[](int n_teeth, double module, double rim_thickness, double addendum_factor, double clearance_factor) {
const stdlib::InternalRingRadii r =
stdlib::internal_ring_radii(n_teeth, module, rim_thickness, addendum_factor, clearance_factor);
return py::make_tuple(r.pitch, r.tip, r.root, r.outer);
},
py::arg("n_teeth"), py::arg("module"), py::arg("rim_thickness"), py::arg("addendum_factor") = 1.0,
py::arg("clearance_factor") = 0.25);
gear.def(
"_build_gear_profile_face",
[](int n_teeth, double module, double pressure_angle, bool return_sketch, std::optional<double> root_radius,
std::optional<double> tip_radius, double addendum_factor, double clearance_factor, double backlash,
bool build_face) -> py::object {
stdlib::ToothOptions options;
options.root_radius = root_radius;
options.tip_radius = tip_radius;
options.tuning = tuning(addendum_factor, clearance_factor, backlash);
Sketch sketch = stdlib::build_gear_profile_sketch(n_teeth, module, pressure_angle, options);
if (build_face || !return_sketch) {
Face face = make_face_from_sketch_rface(sketch, 0);
return return_sketch ? py::make_tuple(py::cast(face), py::cast(std::move(sketch))).cast<py::object>() : py::cast(face);
}
return py::make_tuple(py::none(), py::cast(std::move(sketch)));
},
py::arg("n_teeth"), py::arg("module"), py::arg("pressure_angle"), py::arg("return_sketch") = false,
py::arg("root_radius") = py::none(), py::arg("tip_radius") = py::none(), py::arg("addendum_factor") = 1.0,
py::arg("clearance_factor") = 0.25, py::arg("backlash") = 0.0, py::arg("build_face") = true);
gear.def(
"_build_internal_gear_profile_wire",
[](int n_teeth, double module, double pressure_angle, bool return_sketch, double backlash, double addendum_factor,
double clearance_factor) -> py::object {
Sketch sketch = stdlib::build_internal_gear_profile_sketch(n_teeth, module, pressure_angle,
tuning(addendum_factor, clearance_factor, backlash));
Wire wire = make_wire_from_sketch_rwire(sketch, 0);
if (!return_sketch) return py::cast(wire);
return py::make_tuple(py::cast(wire), py::cast(std::move(sketch)));
},
py::arg("n_teeth"), py::arg("module"), py::arg("pressure_angle"), py::arg("return_sketch") = false,
py::arg("backlash") = 0.0, py::arg("addendum_factor") = 1.0, py::arg("clearance_factor") = 0.25);
gear.def(
"_build_ring_gear_face",
[](int n_teeth, double module, double pressure_angle, double rim_thickness, double backlash, double addendum_factor,
double clearance_factor) {
return stdlib::build_ring_gear_face(n_teeth, module, pressure_angle, rim_thickness,
tuning(addendum_factor, clearance_factor, backlash));
},
py::arg("n_teeth"), py::arg("module"), py::arg("pressure_angle"), py::arg("rim_thickness"),
py::arg("backlash") = 0.0, py::arg("addendum_factor") = 1.0, py::arg("clearance_factor") = 0.25);
}
// ---- chain ----------------------------------------------------------------------------------------------------
void bind_chain(py::module_& chain) {
chain.def(
"make_roller_chain_sprocket_rsolid",
[](const py::object& n_teeth, double chain_pitch, double roller_diameter, double sprocket_thickness,
double bore_radius, double roller_clearance) {
if (!is_plain_int(n_teeth)) throw ValueError("n_teeth must be an integer of at least 6");
const int teeth = python_int(n_teeth);
return unlocked([&] {
return make_roller_chain_sprocket_rsolid(teeth, chain_pitch, roller_diameter, sprocket_thickness, bore_radius,
roller_clearance);
});
},
py::arg("n_teeth"), py::arg("chain_pitch"), py::arg("roller_diameter"), py::arg("sprocket_thickness"),
py::kw_only(), py::arg("bore_radius") = 0.0, py::arg("roller_clearance") = 0.15,
"Create a roller-chain sprocket from the chain engagement dimensions.\n\n"
"The pitch radius follows the regular pitch polygon; circular roller-seat cutters at every pitch point\n"
"are opened through the outside-diameter envelope p * (0.6 + cot(180 / z)). Metadata\n"
"'std.chain.roller_sprocket' keeps the tooth count, pitch, roller seats, root and outside radii.");
chain.attr("__all__") = py::make_tuple("make_roller_chain_sprocket_rsolid");
}
// ---- fastener -------------------------------------------------------------------------------------------------
void bind_fastener(py::module_& fastener) {
fastener.def(
"make_bolt_rsolid",
[](double diameter, double length, const py::object& head_style, const py::object& thread_style,
const py::object& thread_detail, const py::object& thread_form, std::optional<double> thread_pitch,
std::optional<double> thread_depth, std::optional<double> thread_length, std::optional<double> head_width,
std::optional<double> head_height, const py::object& drive_style, std::optional<double> drive_size,
std::optional<double> drive_depth, std::optional<double> underhead_fillet_radius) {
BoltOptions options;
options.head_style = text_of(head_style);
options.thread_style = text_of(thread_style);
options.thread_detail = text_of(thread_detail);
options.thread_form = text_of(thread_form);
options.thread_pitch = thread_pitch;
options.thread_depth = thread_depth;
options.thread_length = thread_length;
options.head_width = head_width;
options.head_height = head_height;
options.drive_style = text_of(drive_style);
options.drive_size = drive_size;
options.drive_depth = drive_depth;
options.underhead_fillet_radius = underhead_fillet_radius;
return unlocked([&] { return make_bolt_rsolid(diameter, length, options); });
},
py::arg("diameter"), py::arg("length"), py::arg("head_style") = "hex", py::arg("thread_style") = "auto",
py::arg("thread_detail") = "modeled", py::arg("thread_form") = "v", py::arg("thread_pitch") = py::none(),
py::arg("thread_depth") = py::none(), py::arg("thread_length") = py::none(), py::arg("head_width") = py::none(),
py::arg("head_height") = py::none(), py::arg("drive_style") = "none", py::arg("drive_size") = py::none(),
py::arg("drive_depth") = py::none(), py::arg("underhead_fillet_radius") = py::none(),
"Create a bolt along +Z with its head underside on the Z=0 plane.\n\n"
"head_style accepts hex, square, cylindrical, button and countersunk. thread_style accepts auto, full,\n"
"partial and none: auto uses a full thread through 3d length and the standard piecewise partial-thread\n"
"length above. Cosmetic threads keep a smooth major-diameter shank and record the thread intent in\n"
"metadata; modeled threads cut a helical groove.");
fastener.def(
"make_nut_rsolid",
[](double diameter, double width, double height, const py::object& nut_style, const py::object& hole_style,
const py::object& thread_detail, const py::object& thread_form, std::optional<double> thread_pitch,
std::optional<double> thread_depth, std::optional<double> hole_depth, const py::object& knurl_count) {
NutOptions options;
options.nut_style = text_of(nut_style);
options.hole_style = text_of(hole_style);
options.thread_detail = text_of(thread_detail);
options.thread_form = text_of(thread_form);
options.thread_pitch = thread_pitch;
options.thread_depth = thread_depth;
options.hole_depth = hole_depth;
// Python reads knurl_count after the dimensions are checked; an invalid count is ValueError either way.
options.knurl_count = is_plain_int(knurl_count) ? python_int(knurl_count) : -1;
return unlocked([&] { return make_nut_rsolid(diameter, width, height, options); });
},
py::arg("diameter"), py::arg("width"), py::arg("height"), py::arg("nut_style") = "hex",
py::arg("hole_style") = "through", py::arg("thread_detail") = "modeled", py::arg("thread_form") = "v",
py::arg("thread_pitch") = py::none(), py::arg("thread_depth") = py::none(), py::arg("hole_depth") = py::none(),
py::arg("knurl_count") = 24,
"Create a nut along +Z with its bottom face on the Z=0 plane.\n\n"
"nut_style accepts hex, square, round and knurled; through and blind holes are supported. Modeled thread\n"
"detail adds internal V or trapezoidal helical teeth to a major-diameter hole.");
fastener.attr("__all__") = py::make_tuple("make_bolt_rsolid", "make_nut_rsolid");
}
// ---- bearing --------------------------------------------------------------------------------------------------
void bind_bearing(py::module_& bearing) {
bearing.def(
"make_ball_bearing_rassembly",
[](double bore_diameter, double outer_diameter, double bearing_width, double ball_diameter,
const py::object& ball_count, double raceway_clearance, double edge_chamfer, std::string assembly_id,
std::optional<double> drive_angle_degrees, bool fuse_rolling_elements, double rolling_element_fuse_overlap,
const py::object& material) {
BallBearingOptions options;
if (!ball_count.is_none()) options.ball_count = python_int(ball_count);
options.raceway_clearance = raceway_clearance;
options.edge_chamfer = edge_chamfer;
options.assembly_id = std::move(assembly_id);
options.drive_angle_degrees = drive_angle_degrees;
options.fuse_rolling_elements = fuse_rolling_elements;
options.rolling_element_fuse_overlap = rolling_element_fuse_overlap;
if (!material.is_none()) {
if (!py::isinstance<product::Material>(material)) throw TypeError("material must be a Material or None");
options.material = material.cast<const product::Material&>();
}
return unlocked([&] {
return make_ball_bearing_rassembly(bore_diameter, outer_diameter, bearing_width, ball_diameter, options);
});
},
py::arg("bore_diameter"), py::arg("outer_diameter"), py::arg("bearing_width"), py::arg("ball_diameter"),
py::arg("ball_count") = py::none(), py::arg("raceway_clearance") = 0.02, py::arg("edge_chamfer") = 0.0,
py::arg("assembly_id") = "ball_bearing", py::arg("drive_angle_degrees") = py::none(),
py::arg("fuse_rolling_elements") = false, py::arg("rolling_element_fuse_overlap") = 0.01,
py::arg("material") = py::none(),
"Create a parameterized radial ball bearing assembly.\n\n"
"Separate outer_ring, inner_ring and ball_* components, an inner/outer revolute constraint and the public\n"
"connectors outer_axis / inner_axis. With fuse_rolling_elements=True the balls are embedded in the outer\n"
"ring and unioned into it (a simplified body). `material` is assigned to the generated parts.");
bearing.attr("__all__") = py::make_tuple("make_ball_bearing_rassembly");
}
} // namespace
void bind_std(py::module_& m) {
py::module_ std_module = m.def_submodule("std", "Standard parts: gears, bearings, roller-chain sprockets, fasteners.");
py::module_ gear = std_module.def_submodule("gear", "Involute gears, ring gears, racks and cycloidal discs.");
py::module_ bearing = std_module.def_submodule("bearing", "Ball bearing standard assemblies.");
py::module_ chain = std_module.def_submodule("chain", "Roller-chain sprockets.");
py::module_ fastener = std_module.def_submodule("fastener", "Parameterized bolts and nuts.");
bind_gear_factories(gear);
bind_gear_internals(gear);
bind_bearing(bearing);
bind_chain(chain);
bind_fastener(fastener);
std_module.attr("__all__") = py::make_tuple("bearing", "chain", "fastener", "gear");
// def_submodule does not register in sys.modules: do it so `import simplecadapi._cpp.std.gear` works.
py::dict modules = py::module_::import("sys").attr("modules");
const std::string root = py::str(m.attr("__name__")).cast<std::string>(); // "simplecadapi._cpp._native"
const std::string package = root.substr(0, root.rfind('.')); // "simplecadapi._cpp"
modules[py::str(package + ".std")] = std_module;
for (const char* name : {"gear", "bearing", "chain", "fastener"}) {
modules[py::str(package + ".std." + name)] = std_module.attr(name);
}
}
+287
View File
@@ -0,0 +1,287 @@
// Python bindings for the "surface" area: the surface and shell operators of
// simplecadapi.surface, under the Python SDK's names and keyword signatures.
//
// Every name is also reachable as `simplecadapi._cpp.surface.<name>` (the same object), as in
// the Python package. This is also where the units hook of the surface area is wired to the
// reactive area's dimension inference.
#include "bindings.hpp"
#include <array>
#include <optional>
#include <string>
#include <variant>
#include <vector>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <BRepBuilderAPI_MakePolygon.hxx>
#include <BRepBuilderAPI_MakeVertex.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <BRepCheck_Analyzer.hxx>
#include <GC_MakeArcOfCircle.hxx>
#include <GeomAPI_Interpolate.hxx>
#include <TColgp_HArray1OfPnt.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopoDS_Wire.hxx>
#include <gp_Circ.hxx>
#include "scad/reactive/expr.hpp"
#include "scad/reactive/units.hpp"
#include "scad/surface/hooks.hpp"
#include "scad/surface/operators.hpp"
#include "scad/surface/types.hpp"
namespace {
using namespace scad;
// expression_uses_units / infer_dimension for the surface operators' dimension checks.
ScalarUnits probe_units(const Scalar& value) {
const auto node = reactive::lift_scalar(value);
ScalarUnits units;
units.uses_units = reactive::expression_uses_units(node);
if (!units.uses_units) return units;
const std::optional<reactive::Dimension> dimension = reactive::infer_dimension(node);
if (dimension && dimension->is_dimensionless()) units.dimension = UnitDimension::Dimensionless;
else if (dimension && *dimension == reactive::kLength) units.dimension = UnitDimension::Length;
else units.dimension = UnitDimension::Other;
return units;
}
// Raw OpenCASCADE builders for the test suite: the ops_geometry operators are the real way to
// make edges and wires, but the surface tests must not wait for them.
void bind_surface_testing(py::module_& m) {
py::module_ t = m.def_submodule("_surface_testing", "edge/wire builders for the surface tests");
const auto pnt = [](const Vec3& v) { return gp_Pnt(v.x, v.y, v.z); };
t.def("line", [pnt](const Vec3& a, const Vec3& b) { return Edge(BRepBuilderAPI_MakeEdge(pnt(a), pnt(b)).Edge()); });
t.def("arc", [pnt](const Vec3& a, const Vec3& b, const Vec3& c) {
return Edge(BRepBuilderAPI_MakeEdge(GC_MakeArcOfCircle(pnt(a), pnt(b), pnt(c)).Value()).Edge());
});
t.def("spline", [pnt](const std::vector<Vec3>& points, double tolerance) {
Handle(TColgp_HArray1OfPnt) array = new TColgp_HArray1OfPnt(1, static_cast<int>(points.size()));
for (std::size_t i = 0; i < points.size(); ++i) array->SetValue(static_cast<int>(i) + 1, pnt(points[i]));
GeomAPI_Interpolate interpolation(array, false, tolerance);
interpolation.Perform();
return Edge(BRepBuilderAPI_MakeEdge(interpolation.Curve()).Edge());
}, py::arg("points"), py::arg("tolerance") = 1e-5);
t.def("wire", [](const std::vector<Edge>& edges) {
BRepBuilderAPI_MakeWire builder;
for (const Edge& e : edges) builder.Add(TopoDS::Edge(e.wrapped()));
return Wire(builder.Wire());
});
t.def("polygon", [pnt](const std::vector<Vec3>& points, bool closed) {
BRepBuilderAPI_MakePolygon builder;
for (const Vec3& p : points) builder.Add(pnt(p));
if (closed) builder.Close();
return Wire(builder.Wire());
}, py::arg("points"), py::arg("closed") = true);
t.def("rectangle", [](double width, double height, const Vec3& center) {
BRepBuilderAPI_MakePolygon builder;
for (const auto& [dx, dy] : {std::pair{-0.5, -0.5}, std::pair{0.5, -0.5}, std::pair{0.5, 0.5}, std::pair{-0.5, 0.5}})
builder.Add(gp_Pnt(center.x + dx * width, center.y + dy * height, center.z));
builder.Close();
return Wire(builder.Wire());
}, py::arg("width"), py::arg("height"), py::arg("center") = Vec3{0, 0, 0});
t.def("circle", [](const Vec3& center, double radius) {
const gp_Circ circle(gp_Ax2(gp_Pnt(center.x, center.y, center.z), gp_Dir(0, 0, 1)), radius);
return Wire(BRepBuilderAPI_MakeWire(BRepBuilderAPI_MakeEdge(circle).Edge()).Wire());
});
t.def("point", [](double x, double y, double z) { return Vertex(BRepBuilderAPI_MakeVertex(gp_Pnt(x, y, z)).Vertex()); });
t.def("is_valid", [](const Shape& shape) { return BRepCheck_Analyzer(shape.wrapped()).IsValid(); });
t.def("bbox", [](const Shape& shape) {
const auto b = shape.bounding_box();
return std::array<double, 6>{b.xmin, b.ymin, b.zmin, b.xmax, b.ymax, b.zmax};
});
}
} // namespace
void bind_surface(py::module_& m) {
using namespace scad;
set_scalar_units_probe(&probe_units);
bind_surface_testing(m);
// ---- value types ---------------------------------------------------------------------------
py::class_<SurfaceBoundary>(m, "SurfaceBoundary", "One edge constraint used by make_surface_patch_rface.")
.def(py::init([](Edge edge, const std::string& continuity, std::optional<Face> support) {
return SurfaceBoundary(std::move(edge), continuity, std::move(support));
}),
py::arg("edge"), py::arg("continuity") = "C0", py::arg("support") = py::none())
.def_property_readonly("edge", [](const SurfaceBoundary& b) { return b.edge; })
.def_property_readonly("continuity", [](const SurfaceBoundary& b) { return b.continuity; })
.def_property_readonly("support", [](const SurfaceBoundary& b) { return b.support; })
.def("as_dict", &SurfaceBoundary::as_dict);
py::class_<SurfaceFillingSettings>(m, "SurfaceFillingSettings",
"Explicit OCCT filling controls; units are model units and radians.")
.def(py::init([](double degree, double points_per_curve, double iterations, bool anisotropic, double tolerance_2d,
double tolerance_3d, double angular_tolerance, double curvature_tolerance, double max_degree,
double max_segments) {
// The SDK's dataclass does not check types: a replayed payload carries 3.0 for 3.
const auto whole = [](double v) { return static_cast<int>(v); };
SurfaceFillingSettings settings{whole(degree), whole(points_per_curve), whole(iterations), anisotropic,
tolerance_2d, tolerance_3d, angular_tolerance,
curvature_tolerance, whole(max_degree), whole(max_segments)};
settings.validate();
return settings;
}),
py::arg("degree") = 3, py::arg("points_per_curve") = 15, py::arg("iterations") = 2,
py::arg("anisotropic") = false, py::arg("tolerance_2d") = 1e-5, py::arg("tolerance_3d") = 1e-4,
py::arg("angular_tolerance") = 0.01, py::arg("curvature_tolerance") = 0.1, py::arg("max_degree") = 8,
py::arg("max_segments") = 9)
.def_readonly("degree", &SurfaceFillingSettings::degree)
.def_readonly("points_per_curve", &SurfaceFillingSettings::points_per_curve)
.def_readonly("iterations", &SurfaceFillingSettings::iterations)
.def_readonly("anisotropic", &SurfaceFillingSettings::anisotropic)
.def_readonly("tolerance_2d", &SurfaceFillingSettings::tolerance_2d)
.def_readonly("tolerance_3d", &SurfaceFillingSettings::tolerance_3d)
.def_readonly("angular_tolerance", &SurfaceFillingSettings::angular_tolerance)
.def_readonly("curvature_tolerance", &SurfaceFillingSettings::curvature_tolerance)
.def_readonly("max_degree", &SurfaceFillingSettings::max_degree)
.def_readonly("max_segments", &SurfaceFillingSettings::max_segments)
.def("as_dict", &SurfaceFillingSettings::as_dict)
.def("__eq__", [](const SurfaceFillingSettings& a, const SurfaceFillingSettings& b) { return a == b; });
// ---- operators -----------------------------------------------------------------------------
m.def(
"make_bezier_surface_rface",
[](const PointGrid& control_points, const std::optional<WeightGrid>& weights, const TagPrefix& tag_prefix) {
return make_bezier_surface_rface(control_points, weights, tag_prefix);
},
py::arg("control_points"), py::arg("weights") = py::none(), py::kw_only(), py::arg("tag_prefix") = py::none(),
"Create a trimmed Face carrying a tensor-product Bezier surface.");
m.def(
"make_cylindrical_surface_rface",
[](const Scalar& radius, const ScalarRange& u_range, const ScalarRange& v_range, const ScalarVec3& origin,
const ScalarVec3& axis, const std::optional<ScalarVec3>& x_direction, const Scalar& tolerance,
const TagPrefix& tag_prefix) {
return make_cylindrical_surface_rface(
radius, u_range, v_range,
{.origin = origin, .axis = axis, .x_direction = x_direction, .tolerance = tolerance, .tag_prefix = tag_prefix});
},
py::arg("radius"), py::arg("u_range"), py::arg("v_range"),
py::arg("origin") = ScalarVec3{0.0, 0.0, 0.0}, py::arg("axis") = ScalarVec3{0.0, 0.0, 1.0},
py::arg("x_direction") = py::none(), py::kw_only(), py::arg("tolerance") = Scalar(1e-7),
py::arg("tag_prefix") = py::none(),
"Create a finite cylindrical carrier Face over explicit U/V ranges (U in raw radians, at most one turn).");
m.def(
"fit_point_grid_rface",
[](const PointGrid& points, double tolerance, int degree_min, int degree_max,
const std::optional<std::array<double, 3>>& smoothing, const TagPrefix& tag_prefix) {
return fit_point_grid_rface(points, {.tolerance = tolerance,
.degree_min = degree_min,
.degree_max = degree_max,
.smoothing = smoothing,
.tag_prefix = tag_prefix});
},
py::arg("points"), py::kw_only(), py::arg("tolerance") = 1e-3, py::arg("degree_min") = 3,
py::arg("degree_max") = 8, py::arg("smoothing") = py::none(), py::arg("tag_prefix") = py::none(),
"Fit a B-spline Face through a rectangular 3D point grid.");
m.def(
"make_ruled_surface_rface",
[](const Edge& edge_a, const Edge& edge_b, const TagPrefix& tag_prefix) {
return make_ruled_surface_rface(edge_a, edge_b, tag_prefix);
},
py::arg("edge_a"), py::arg("edge_b"), py::kw_only(), py::arg("tag_prefix") = py::none(),
"Create a ruled Face spanning two compatible edges.");
m.def(
"make_gordon_surface_rface",
[](const std::vector<Edge>& profiles, const std::vector<Edge>& guides, double tolerance,
const TagPrefix& tag_prefix) { return make_gordon_surface_rface(profiles, guides, tolerance, tag_prefix); },
py::arg("profiles"), py::arg("guides"), py::kw_only(), py::arg("tolerance") = 1e-3,
py::arg("tag_prefix") = py::none(),
"Create a Gordon Face from intersecting profile and guide edge networks.");
m.def(
"make_surface_patch_rface",
[](const std::vector<SurfaceBoundary>& boundaries, const std::vector<Vec3>& points,
const std::optional<SurfaceFillingSettings>& settings, const std::vector<Wire>& holes,
const TagPrefix& tag_prefix) {
return make_surface_patch_rface(
boundaries, {.points = points, .settings = settings, .holes = holes, .tag_prefix = tag_prefix});
},
py::arg("boundaries"), py::kw_only(), py::arg("points") = std::vector<Vec3>{},
py::arg("settings") = py::none(), py::arg("holes") = std::vector<Wire>{}, py::arg("tag_prefix") = py::none(),
"Fill a constrained boundary network into one Face, optionally with holes.");
m.def(
"trim_surface_rface",
[](const Face& carrier, const Wire& outer, const std::vector<Wire>& holes, double tolerance,
const TagPrefix& tag_prefix) {
return trim_surface_rface(carrier, outer, {.holes = holes, .tolerance = tolerance, .tag_prefix = tag_prefix});
},
py::arg("carrier"), py::arg("outer"), py::arg("holes") = std::vector<Wire>{}, py::kw_only(),
py::arg("tolerance") = 1e-7, py::arg("tag_prefix") = py::none(),
"Trim a carrier Face to exactly one connected Face.");
m.def(
"loft_rshell",
[](const std::vector<py::object>& raw_sections, bool ruled, const TagPrefix& tag_prefix,
const std::optional<std::string>& result_tag, const std::optional<std::string>& start_wire_tag,
const std::optional<std::string>& end_wire_tag, const std::optional<std::string>& side_faces_tag) {
std::vector<LoftSection> sections;
sections.reserve(raw_sections.size());
for (const py::object& item : raw_sections) {
if (py::isinstance<Wire>(item)) sections.emplace_back(item.cast<Wire>());
else if (py::isinstance<Vertex>(item)) sections.emplace_back(item.cast<Vertex>());
else throw TypeError("loft_rshell sections must contain only Wire or Vertex objects");
}
return loft_rshell(sections, ruled,
{.tag_prefix = tag_prefix,
.result_tag = result_tag,
.start_wire_tag = start_wire_tag,
.end_wire_tag = end_wire_tag,
.side_faces_tag = side_faces_tag});
},
py::arg("sections"), py::kw_only(), py::arg("ruled") = false, py::arg("tag_prefix") = py::none(),
py::arg("result_tag") = py::none(), py::arg("start_wire_tag") = py::none(),
py::arg("end_wire_tag") = py::none(), py::arg("side_faces_tag") = py::none(),
"Create an open loft Shell with endpoint-Wire and side-Face naming.");
m.def(
"sew_faces_rshell",
[](const std::vector<Face>& faces, double tolerance, const TagPrefix& tag_prefix) {
return sew_faces_rshell(faces, tolerance, tag_prefix);
},
py::arg("faces"), py::kw_only(), py::arg("tolerance") = 1e-6, py::arg("tag_prefix") = py::none(),
"Sew faces into exactly one connected Shell.");
m.def(
"make_solid_from_shell_rsolid",
[](const Shell& shell, const TagPrefix& tag_prefix) { return make_solid_from_shell_rsolid(shell, tag_prefix); },
py::arg("shell"), py::kw_only(), py::arg("tag_prefix") = py::none(),
"Create an oriented Solid from one valid closed Shell.");
m.def(
"free_boundaries_rwirelist",
[](const Shell& shell, double tolerance) { return free_boundaries_rwirelist(shell, tolerance); },
py::arg("shell"), py::kw_only(), py::arg("tolerance") = 1e-6,
"Return unique closed and open free boundary wires of a Shell.");
m.def(
"fill_holes_rshell",
[](const Shell& shell, const std::optional<std::vector<int>>& hole_indices, double tolerance,
const std::optional<SurfaceFillingSettings>& settings, const TagPrefix& tag_prefix) {
return fill_holes_rshell(shell, {.hole_indices = hole_indices,
.tolerance = tolerance,
.settings = settings,
.tag_prefix = tag_prefix});
},
py::arg("shell"), py::arg("hole_indices") = py::none(), py::kw_only(), py::arg("tolerance") = 1e-6,
py::arg("settings") = py::none(), py::arg("tag_prefix") = py::none(),
"Fill selected closed free boundaries and return a sewn Shell.");
// simplecadapi.surface: the same objects under the namespace the Python package offers.
py::module_ ns = m.def_submodule("surface", "Surface modeling namespace (the same functions as the top level).");
for (const char* name :
{"SurfaceBoundary", "SurfaceFillingSettings", "make_bezier_surface_rface", "make_cylindrical_surface_rface",
"fit_point_grid_rface", "make_ruled_surface_rface", "make_gordon_surface_rface", "make_surface_patch_rface",
"loft_rshell", "trim_surface_rface", "sew_faces_rshell", "make_solid_from_shell_rsolid",
"free_boundaries_rwirelist", "fill_holes_rshell"})
ns.attr(name) = m.attr(name);
}
+231
View File
@@ -0,0 +1,231 @@
// Shape classes, with the method names of the Python SDK (core.py).
//
// Where the Python SDK forbids bare enumeration (get_faces() without an index
// raises, pointing at the QL selectors) this module does too; the plural
// accessors faces()/edges()/... exist as C++-port extensions so tests and
// native callers can enumerate until QL is ported.
#include "bindings.hpp"
#include <BRep_Builder.hxx>
#include <TopoDS_Compound.hxx>
#include <BRepPrimAPI_MakeBox.hxx>
#include <BRepPrimAPI_MakeCylinder.hxx>
#include "occt/occt.hpp"
#include "scad/core/error.hpp"
#include "scad/reactive/graph.hpp"
#include "scad/reactive/lineage.hpp"
#include "scad/topo/recorder.hpp"
#include "scad/topo/shape.hpp"
namespace occt = scad::pybind::occt;
namespace {
using namespace scad;
[[noreturn]] void enumeration_forbidden(const char* method, const char* kind) {
ErrorGuidance g;
g.what_happened = std::string(method) +
"() without an index no longer returns a list -- bare topology enumeration is not part of "
"the public API.";
g.possible_causes = {"Calling a plural topology getter (get_edges/get_faces/...) with no argument.",
"Porting code that enumerated topology with Python loops or len()."};
g.how_to_fix = {
"Enumerate or measure via QL: ql.edges().resolve(shape) / len(ql.faces().resolve(shape)).",
"Pick intentionally with the indexed form get_edges(index) -- indexed picks are recorded as graph "
"selection nodes.",
"Filter with QL predicates and cardinality (take/exactly) instead of post-filtering an enumerated list."};
g.signature = std::string(method) + "(index: int) -> " + kind;
g.technical_details =
"Enumeration escapes the graph: selections made by indexing a bare list carry no predicate and capture "
"kernel artifacts (e.g. periodic-face seams).";
throw Error(std::string(method) + " (no index)", std::move(g));
}
// get_faces(i) and the like: the pick is recorded as a graph selection node when it is made
// (_record_indexed_topology_selection; a recorder that cannot take it is ignored).
template <class T>
T indexed(const Shape& source, const std::vector<T>& items, const py::object& index, const char* method, const char* kind) {
if (index.is_none()) enumeration_forbidden(method, kind);
T picked = pick(items, index.cast<long>(), kind);
if (Recorder* recorder = current_recorder()) {
try {
recorder->record_selection(source, {picked}, kind);
} catch (const std::exception&) {
}
}
return picked;
}
// Methods every shape kind shares (TaggedMixin + TopoMixein).
template <class T, class Cls>
void bind_common(Cls& cls) {
cls.def_property_readonly("topo_id", [](const T& s) { return s.topo_id(); })
.def("same_topology", [](const T& a, const Shape& b) { return a.same_entity(b) || a.topo_id() == b.topo_id(); })
.def("_add_tag", [](T& s, const std::string& tag) { s.add_tag(tag); })
.def("_apply_tag", [](T& s, const std::string& tag, bool propagate) { s.apply_tag(tag, propagate); },
py::arg("tag"), py::arg("propagate") = false)
.def("_has_tag", [](const T& s, const std::string& tag, const std::string& scope) {
return s.has_tag(tag, normalize_tag_scope(scope));
}, py::arg("tag"), py::arg("scope") = "effective")
.def("_list_tags", [](const T& s, const std::string& scope) {
return s.list_tags(normalize_tag_scope(scope));
}, py::arg("scope") = "effective")
.def("_explain_tag", [](const T& s, const std::string& tag, const std::string& scope) {
return s.explain_tag(normalize_tag(tag, true), normalize_tag_scope(scope));
}, py::arg("tag"), py::arg("scope") = "effective")
.def("set_metadata", [](T& s, const std::string& key, const Value& v) { s.set_metadata(key, v); })
.def("get_metadata", [](const T& s, const std::string& key, const Value& dflt) {
Value found = s.get_metadata(key, Value());
// The SDK stamps "topo_ref" on every entity of a recorded output; here it is derived on demand.
if (found.is_null() && key == "topo_ref") {
if (auto ref = scad::reactive::topo_ref_of(s)) {
ref->topo_id = std::string(kind_name(ref->kind)) + "_" + ref->topo_id; // the SDK's text: "face_face_5"
return scad::to_value(*ref);
}
}
return found.is_null() ? dflt : found;
}, py::arg("key"), py::arg("default") = Value())
.def_property_readonly("wrapped", [](const T& s) { return occt::shape_to_python(s.wrapped()); },
"The OCCT shape (TopoDS_Solid, ...) this handle stands for: the same OpenCASCADE, no copy.")
.def("_attach_node", [](const T& s, const std::shared_ptr<const scad::reactive::OperationNode>& node) { s.set_graph_node(node); },
py::arg("node"), "The graph node this value was made by (a value restored from a pickle brings its node back).")
.def("_set_runtime", [](T& s, const std::string& key, const Value& v) { s.set_runtime(key, v); })
.def("_get_runtime", [](const T& s, const std::string& key, const Value& dflt) -> py::object {
if (key == "graph.node") { // the node object itself, as the SDK keeps it in the runtime
if (const auto node = s.graph_node())
return py::cast(std::static_pointer_cast<const scad::reactive::OperationNode>(node));
}
return scad::pybind::value_to_python(s.get_runtime(key, dflt));
}, py::arg("key"), py::arg("default") = Value())
.def("get_center", [](const T& s) { return scad::pybind::PyVec3{s.center()}; })
.def("__eq__", [](const T& a, const py::object& b) {
return py::isinstance<Shape>(b) && a.same_entity(b.cast<const Shape&>());
}, py::is_operator())
.def("__hash__", [](const T& s) { return s.entity_key(); })
.def("__repr__", [](const T& s) { return s.repr(); })
.def("__str__", [](const T& s) { return s.to_string(0); });
}
} // namespace
void bind_topo(py::module_& m) {
py::class_<Shape>(m, "AnyShape").def_property_readonly("topo_id", &Shape::topo_id);
auto vertex = py::class_<Vertex, Shape>(m, "Vertex");
vertex.def("get_coordinates", &Vertex::coordinates)
.def("get_incident_edges", &Vertex::incident_edges);
bind_common<Vertex>(vertex);
auto edge = py::class_<Edge, Shape>(m, "Edge");
edge.def("get_length", &Edge::length)
.def("get_start_vertex", &Edge::start_vertex)
.def("get_end_vertex", &Edge::end_vertex)
.def("get_incident_faces", &Edge::incident_faces)
.def("get_vertices", [](const Edge& e, const py::object& i) { return indexed(e, e.vertices(), i, "get_vertices", "vertex"); },
py::arg("index") = py::none())
.def("vertices", &Edge::vertices);
bind_common<Edge>(edge);
auto wire = py::class_<Wire, Shape>(m, "Wire");
wire.def("get_edges", [](const Wire& w, const py::object& i) { return indexed(w, w.edges(), i, "get_edges", "edge"); },
py::arg("index") = py::none())
.def("is_closed", &Wire::is_closed)
.def("edges", &Wire::edges);
bind_common<Wire>(wire);
auto face = py::class_<Face, Shape>(m, "Face");
face.def("get_area", &Face::area)
.def("get_normal_at", [](const Face& f, double u, double v) { return scad::pybind::PyVec3{f.normal_at(u, v)}; },
py::arg("u") = 0.5, py::arg("v") = 0.5)
.def("get_outer_wire", &Face::outer_wire)
.def("get_wires", [](const Face& f, const py::object& i) { return indexed(f, f.wires(), i, "get_wires", "wire"); },
py::arg("index") = py::none())
.def("get_inner_wires", [](const Face& f, const py::object& i) { return indexed(f, f.inner_wires(), i, "get_inner_wires", "wire"); },
py::arg("index") = py::none())
.def("get_edges", [](const Face& f, const py::object& i) { return indexed(f, f.edges(), i, "get_edges", "edge"); },
py::arg("index") = py::none())
.def("get_adjacent_faces", &Face::adjacent_faces)
.def("wires", &Face::wires)
.def("edges", &Face::edges);
bind_common<Face>(face);
auto shell = py::class_<Shell, Shape>(m, "Shell");
shell.def("get_area", &Shell::area)
.def("is_closed", &Shell::is_closed)
.def("get_faces", [](const Shell& s, const py::object& i) { return indexed(s, s.faces(), i, "get_faces", "face"); },
py::arg("index") = py::none())
.def("get_wires", [](const Shell& s, const py::object& i) { return indexed(s, s.wires(), i, "get_wires", "wire"); },
py::arg("index") = py::none())
.def("get_edges", [](const Shell& s, const py::object& i) { return indexed(s, s.edges(), i, "get_edges", "edge"); },
py::arg("index") = py::none())
.def("faces", &Shell::faces)
.def("edges", &Shell::edges);
bind_common<Shell>(shell);
auto solid = py::class_<Solid, Shape>(m, "Solid");
solid.def("get_volume", &Solid::volume)
.def("get_faces", [](const Solid& s, const py::object& i) { return indexed(s, s.faces(), i, "get_faces", "face"); },
py::arg("index") = py::none())
.def("get_edges", [](const Solid& s, const py::object& i) { return indexed(s, s.edges(), i, "get_edges", "edge"); },
py::arg("index") = py::none())
.def("get_edge_occurrences", [](const Solid& s, const py::object& i) { return indexed(s, s.edge_occurrences(), i, "get_edge_occurrences", "edge"); },
py::arg("index") = py::none())
.def("auto_tag_faces", &Solid::auto_tag_faces, py::arg("geometry_type") = "unknown")
.def("faces", &Solid::faces)
.def("edges", &Solid::edges);
bind_common<Solid>(solid);
auto compound = py::class_<Compound, Shape>(m, "Compound");
// A compound of shapes (duplicates and all): the shapes themselves are not copied.
compound.def(py::init([](const py::sequence& shapes) {
BRep_Builder builder;
TopoDS_Compound made;
builder.MakeCompound(made);
for (const py::handle item : shapes) builder.Add(made, item.cast<const Shape&>().wrapped());
return Compound(made);
}), py::arg("shapes"));
compound.def("get_volume", &Compound::volume)
.def("get_solids", [](const Compound& c, const py::object& i) { return indexed(c, c.solids(), i, "get_solids", "solid"); },
py::arg("index") = py::none())
.def("get_faces", [](const Compound& c, const py::object& i) { return indexed(c, c.faces(), i, "get_faces", "face"); },
py::arg("index") = py::none())
.def("get_edges", [](const Compound& c, const py::object& i) { return indexed(c, c.edges(), i, "get_edges", "edge"); },
py::arg("index") = py::none())
.def("solids", &Compound::solids)
.def("faces", &Compound::faces)
.def("edges", &Compound::edges);
bind_common<Compound>(compound);
// The Python SDK's private enumerators (`_iter_*`): its own tests and std parts use them.
// The wrapper tree the SDK builds: vertex < edge < wire < face < solid | shell < compound.
edge.def("get_children", [](const Edge& e) { return py::cast(e.vertices()); });
wire.def("get_children", [](const Wire& w) { return py::cast(w.edges()); });
face.def("get_children", [](const Face& f) { return py::cast(f.wires()); });
shell.def("get_children", [](const Shell& s) {
py::list out = py::cast(s.faces());
for (const py::handle wire : py::cast(s.wires())) out.append(wire); // its free boundaries
return out;
});
solid.def("get_children", [](const Solid& s) { return py::cast(s.faces()); });
compound.def("get_children", [](const Compound& c) { return py::cast(c.solids()); });
vertex.def("get_children", [](const Vertex&) { return py::list(); });
edge.def("_iter_vertices", &Edge::vertices);
wire.def("_iter_edges", &Wire::edges);
face.def("_iter_wires", &Face::wires)
.def("_iter_inner_wires", &Face::inner_wires)
.def("_iter_edges", &Face::edges);
shell.def("_iter_faces", &Shell::faces).def("_iter_wires", &Shell::wires).def("_iter_edges", &Shell::edges);
solid.def("_iter_faces", &Solid::faces)
.def("_iter_edges", &Solid::edges)
.def("_iter_edge_occurrences", &Solid::edge_occurrences);
compound.def("_iter_solids", &Compound::solids)
.def("_iter_faces", &Compound::faces)
.def("_iter_edges", &Compound::edges);
// Raw OCCT primitives for tests: operators are the real way to build shapes.
auto testing = m.def_submodule("_testing", "helpers for the test suite");
testing.def("box", [](double x, double y, double z) { return Solid(BRepPrimAPI_MakeBox(x, y, z).Solid()); });
testing.def("cylinder", [](double r, double h) { return Solid(BRepPrimAPI_MakeCylinder(r, h).Solid()); });
}
+158
View File
@@ -0,0 +1,158 @@
// Shared pybind11 plumbing: type casters and the per-area registration hooks.
//
// Every area registers itself from its own bind_<area>.cpp; module.cpp only
// calls the hooks below in order. A new area adds one declaration here and one
// call in module.cpp -- nothing else is shared.
#pragma once
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <memory>
#include <string>
#include "scad/core/scalar.hpp"
#include "scad/core/value.hpp"
#include "scad/core/vec.hpp"
namespace py = pybind11;
void bind_core(py::module_& m);
void bind_topo(py::module_& m);
void bind_semantic(py::module_& m);
void bind_ops_geometry(py::module_& m);
void bind_ops_features(py::module_& m);
void bind_sketch(py::module_& m);
void bind_surface(py::module_& m);
void bind_std(py::module_& m);
void bind_reactive(py::module_& m);
void bind_io(py::module_& m);
void bind_ql(py::module_& m);
void bind_render(py::module_& m);
void bind_product(py::module_& m);
void bind_sdk_compat(py::module_& m);
void bind_canonical(py::module_& m);
namespace scad::pybind {
// The Python-visible Vec3 value (what get_center()/get_normal_at() return).
// Plain tuples are accepted wherever a Vec3 is read.
struct PyVec3 {
scad::Vec3 v;
};
// Installs the exception translator (scad::Error -> simplecadapi._cpp.SimpleCADError,
// plain scad exceptions -> the matching builtin, OCCT failures -> RuntimeError).
void register_exceptions(py::module_& m);
// Python value -> scad::Value (None, bool, int, float, str, list/tuple, dict).
Value value_from_python(const py::handle& obj);
py::object value_to_python(const Value& value);
} // namespace scad::pybind
namespace pybind11::detail {
// Vec3 <-> any 3-sequence of numbers (tuple, list, numpy array); returns a tuple.
template <>
struct type_caster<scad::Vec3> {
PYBIND11_TYPE_CASTER(scad::Vec3, const_name("tuple[float, float, float]"));
bool load(handle src, bool /*convert*/) {
if (!src) return false;
// A Vec3 object (or anything with x, y, z attributes).
if (hasattr(src, "x") && hasattr(src, "y") && hasattr(src, "z") && !isinstance<sequence>(src)) {
try {
value = scad::Vec3{src.attr("x").cast<double>(), src.attr("y").cast<double>(), src.attr("z").cast<double>()};
return true;
} catch (const cast_error&) {
return false;
}
}
if (!(isinstance<sequence>(src) || isinstance<array>(src))) return false;
sequence seq = reinterpret_borrow<sequence>(src);
if (seq.size() != 3) return false;
double v[3];
for (std::size_t i = 0; i < 3; ++i) {
object item = seq[i];
try {
v[i] = item.cast<double>();
} catch (const cast_error&) {
return false;
}
}
value = scad::Vec3{v[0], v[1], v[2]};
return true;
}
static handle cast(const scad::Vec3& v, return_value_policy, handle) {
return make_tuple(v.x, v.y, v.z).release();
}
};
// Scalar <- float | int | an expression object (anything holding an ExprPtr).
// The expression types are bound in bind_reactive; until then only numbers load.
template <>
struct type_caster<scad::Scalar> {
PYBIND11_TYPE_CASTER(scad::Scalar, const_name("float | Expr"));
bool load(handle src, bool convert) {
if (!src) return false;
// An Expr/Var exposed by the reactive module.
if (object expr_type = scad_expr_type(); expr_type && !expr_type.is_none() && isinstance(src, expr_type)) {
value = scad::Scalar(src.cast<scad::ExprPtr>());
return true;
}
if (PyFloat_Check(src.ptr()) || PyLong_Check(src.ptr()) || (convert && PyNumber_Check(src.ptr()))) {
PyObject* number = PyNumber_Float(src.ptr());
if (number == nullptr) {
PyErr_Clear();
return false;
}
value = scad::Scalar(PyFloat_AsDouble(number));
Py_DECREF(number);
return true;
}
return false;
}
static handle cast(const scad::Scalar& s, return_value_policy, handle) {
if (s.symbolic()) return pybind11::cast(s.expr()).release();
return PyFloat_FromDouble(s.literal());
}
private:
// The Python class that wraps scad::ExprNode; absent until bind_reactive ran.
static object scad_expr_type() {
static object* type = new object; // never destroyed: static destructors run after Py_Finalize
if (!*type) {
try {
*type = module_::import("simplecadapi._cpp._native").attr("ExprBase");
} catch (const error_already_set&) {
return none();
}
}
return *type;
}
};
// Value <-> native Python objects.
template <>
struct type_caster<scad::Value> {
PYBIND11_TYPE_CASTER(scad::Value, const_name("Any"));
bool load(handle src, bool) {
try {
value = scad::pybind::value_from_python(src);
return true;
} catch (const std::exception&) {
return false;
}
}
static handle cast(const scad::Value& v, return_value_policy, handle) {
return scad::pybind::value_to_python(v).release();
}
};
} // namespace pybind11::detail
+149
View File
@@ -0,0 +1,149 @@
// Exception translation and Value <-> Python conversion.
#include "bindings.hpp"
#include <stdexcept>
#include <pybind11/eval.h>
#include "scad/core/error.hpp"
#include "scad/reactive/errors.hpp"
namespace scad::pybind {
namespace {
py::dict guidance_to_dict(const Error& e) {
const ErrorGuidance& g = e.guidance();
py::dict d;
d["operation"] = e.operation();
d["what_happened"] = g.what_happened;
d["possible_causes"] = g.possible_causes;
d["how_to_fix"] = g.how_to_fix;
d["technical_details"] = g.technical_details.empty() ? py::none() : py::object(py::str(g.technical_details));
d["signature"] = g.signature.empty() ? py::none() : py::object(py::str(g.signature));
d["documentation_hint"] =
g.documentation_hint.empty() ? py::none() : py::object(py::str(g.documentation_hint));
py::list measurements;
for (const auto& m : g.measurements) {
py::dict item;
item["name"] = m.name;
if (const auto* scalar = std::get_if<double>(&m.value)) item["value"] = *scalar;
else {
const auto& v = std::get<std::array<double, 3>>(m.value);
item["value"] = py::make_tuple(v[0], v[1], v[2]);
}
item["unit"] = m.unit;
measurements.append(item);
}
d["measurements"] = measurements;
py::list evidence;
for (const auto& ev : g.evidence) {
py::dict item;
item["kind"] = ev.kind;
item["path"] = ev.path;
item["view"] = ev.view;
item["caption"] = ev.caption;
py::dict symbols;
for (const auto& [k, v] : ev.symbols) symbols[py::str(k)] = v;
item["symbols"] = symbols;
evidence.append(item);
}
d["evidence"] = evidence;
d["repair"] = g.repair;
py::list inventory;
for (const auto& entry : g.inventory) {
py::dict item;
item["symbol"] = entry.symbol;
item["status"] = entry.status;
item["description"] = entry.description;
inventory.append(item);
}
d["inventory"] = inventory;
return d;
}
void set_python_error(const Exception& e) {
PyObject* type = PyExc_RuntimeError;
switch (e.py_kind()) {
case PyKind::ValueError: type = PyExc_ValueError; break;
case PyKind::TypeError: type = PyExc_TypeError; break;
case PyKind::IndexError: type = PyExc_IndexError; break;
case PyKind::KeyError: type = PyExc_KeyError; break;
case PyKind::RuntimeError: type = PyExc_RuntimeError; break;
case PyKind::NotImplementedError: type = PyExc_NotImplementedError; break;
}
PyErr_SetString(type, e.what());
}
} // namespace
void register_exceptions(py::module_&) {
py::register_exception_translator([](std::exception_ptr p) {
try {
if (p) std::rethrow_exception(p);
} catch (const Error& e) {
try {
py::object errors = py::module_::import("simplecadapi._cpp.errors");
// The message-first families are real classes in the SDK: which one this is travels with the error.
const char* family = "";
if (dynamic_cast<const UnsupportedQueryCapabilityError*>(&e) != nullptr) family = "UnsupportedQueryCapabilityError";
else if (dynamic_cast<const SemanticCapabilityError*>(&e) != nullptr) family = "SemanticCapabilityError";
else if (dynamic_cast<const TagValidationError*>(&e) != nullptr) family = "TagValidationError";
py::object exc = errors.attr("make_error")(e.operation(), guidance_to_dict(e), std::string(e.what()), family);
PyErr_SetObject(reinterpret_cast<PyObject*>(Py_TYPE(exc.ptr())), exc.ptr());
} catch (const py::error_already_set&) {
// errors.py unavailable (partial import): degrade to a plain ValueError with the same text.
PyErr_Clear();
PyErr_SetString(PyExc_ValueError, e.what());
}
} catch (const Exception& e) {
set_python_error(e);
}
// Anything else falls through to pybind11's built-in translators.
});
}
Value value_from_python(const py::handle& obj) {
if (obj.is_none()) return Value();
if (py::isinstance<py::bool_>(obj)) return Value(obj.cast<bool>());
if (py::isinstance<py::int_>(obj)) return Value(obj.cast<std::int64_t>());
if (py::isinstance<py::float_>(obj)) return Value(obj.cast<double>());
if (py::isinstance<py::str>(obj)) return Value(obj.cast<std::string>());
if (py::isinstance<py::dict>(obj)) {
Value out = Value::object();
for (const auto& item : obj.cast<py::dict>()) out.set(py::str(item.first).cast<std::string>(), value_from_python(item.second));
return out;
}
if (py::isinstance<py::sequence>(obj)) {
Value out = py::isinstance<py::tuple>(obj) ? Value::tuple() : Value::array();
for (const auto& item : obj.cast<py::sequence>()) out.push_back(value_from_python(item));
return out;
}
if (PyNumber_Check(obj.ptr())) return Value(obj.cast<double>()); // numpy scalars
throw std::invalid_argument(std::string("cannot convert Python ") +
std::string(py::str(py::type::of(obj).attr("__name__"))) + " to a Value");
}
py::object value_to_python(const Value& v) {
if (v.is_null()) return py::none();
if (v.is_bool()) return py::bool_(v.as_bool());
if (v.is_int()) return py::int_(v.as_int());
if (v.is_double()) return py::float_(v.as_double());
if (v.is_string()) return py::str(v.as_string());
if (v.is_tuple()) {
py::tuple out(v.size());
std::size_t at = 0;
for (const auto& item : v.as_array()) out[at++] = value_to_python(item);
return std::move(out);
}
if (v.is_array()) {
py::list out;
for (const auto& item : v.as_array()) out.append(value_to_python(item));
return std::move(out);
}
py::dict out;
for (const auto& [key, item] : v.as_object()) out[py::str(key)] = value_to_python(item);
return std::move(out);
}
} // namespace scad::pybind
+26
View File
@@ -0,0 +1,26 @@
#include "bindings.hpp"
#include "occt/occt.hpp"
#include "scad/core/error.hpp"
PYBIND11_MODULE(_native, m, py::mod_gil_not_used()) {
m.doc() = "SimpleCADAPI on OpenCASCADE, implemented in C++ (pybind11).";
scad::set_error_module_name("simplecadapi._cpp");
scad::pybind::register_exceptions(m);
bind_core(m);
bind_topo(m);
bind_reactive(m); // before the operator areas: they accept Scalar expressions
bind_semantic(m);
bind_io(m);
bind_ql(m);
bind_render(m);
bind_ops_geometry(m);
bind_ops_features(m);
bind_sketch(m);
bind_surface(m);
bind_std(m);
bind_product(m);
bind_canonical(m);
bind_sdk_compat(m); // names the Python layers above import from the lower modules
scad::pybind::occt::bind_occt(m); // the OCCT classes the kept Python layers use (OCP's names)
}
@@ -0,0 +1,13 @@
#include "occt.hpp"
namespace scad::pybind::occt {
void bind_occt(py::module_& m) {
py::module_ occt = m.def_submodule("_occt", "OCCT classes under their OCP names (see occt.hpp)");
bind_core(occt);
bind_query(occt);
bind_algo(occt);
bind_step(occt);
}
} // namespace scad::pybind::occt
@@ -0,0 +1,315 @@
// Construction: booleans, shape builders, primitives, fillets, transform/copy, meshing, HLR, shape upgrade.
#include <BOPAlgo_GlueEnum.hxx>
#include <BRepAlgoAPI_Algo.hxx>
#include <StlAPI_Writer.hxx>
#include <BRepAlgoAPI_BooleanOperation.hxx>
#include <BRepAlgoAPI_BuilderAlgo.hxx>
#include <BRepAlgoAPI_Common.hxx>
#include <BRepAlgoAPI_Cut.hxx>
#include <BRepAlgoAPI_Fuse.hxx>
#include <BRepAlgoAPI_Section.hxx>
#include <BRepBuilderAPI_Command.hxx>
#include <BRepBuilderAPI_Copy.hxx>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <BRepBuilderAPI_MakeFace.hxx>
#include <BRepBuilderAPI_MakeShape.hxx>
#include <BRepBuilderAPI_MakeSolid.hxx>
#include <BRepBuilderAPI_MakeVertex.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <BRepBuilderAPI_ModifyShape.hxx>
#include <BRepBuilderAPI_Transform.hxx>
#include <BRepFilletAPI_LocalOperation.hxx>
#include <BRepFilletAPI_MakeFillet.hxx>
#include <BRepMesh_IncrementalMesh.hxx>
#include <BRepPrimAPI_MakeBox.hxx>
#include <BRepPrimAPI_MakeCylinder.hxx>
#include <BRepPrimAPI_MakePrism.hxx>
#include <BRepPrimAPI_MakeSphere.hxx>
#include <BRepPrimAPI_MakeSweep.hxx>
#include <GeomAbs_Shape.hxx>
#include <Geom_Curve.hxx>
#include <Geom_Surface.hxx>
#include <HLRAlgo_Projector.hxx>
#include <HLRBRep_Algo.hxx>
#include <HLRBRep_HLRToShape.hxx>
#include <HLRBRep_InternalAlgo.hxx>
#include <ShapeUpgrade_ShapeDivide.hxx>
#include <ShapeUpgrade_ShapeDivideContinuity.hxx>
#include <TopTools_ListOfShape.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Face.hxx>
#include <TopoDS_Shell.hxx>
#include <TopoDS_Solid.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopoDS_Wire.hxx>
#include <gp_Ax2.hxx>
#include <gp_Circ.hxx>
#include <gp_Elips.hxx>
#include <gp_Lin.hxx>
#include <gp_Pln.hxx>
#include <gp_Torus.hxx>
#include <gp_Sphere.hxx>
#include <gp_Cone.hxx>
#include <gp_Cylinder.hxx>
#include <gp_Pnt.hxx>
#include <gp_Trsf.hxx>
#include <gp_Vec.hxx>
#include "occt.hpp"
namespace scad::pybind::occt {
namespace {
template <class Op>
void boolean_class(py::module_& m, const char* name) {
py::class_<Op, BRepAlgoAPI_BooleanOperation>(m, name)
.def(py::init<>())
.def(py::init<const TopoDS_Shape&, const TopoDS_Shape&>(), py::arg("S1"), py::arg("S2"));
}
} // namespace
void bind_algo(py::module_& m) {
py::enum_<BOPAlgo_GlueEnum>(m, "BOPAlgo_GlueEnum")
.value("BOPAlgo_GlueOff", BOPAlgo_GlueOff)
.value("BOPAlgo_GlueShift", BOPAlgo_GlueShift)
.value("BOPAlgo_GlueFull", BOPAlgo_GlueFull)
.export_values();
py::class_<StlAPI_Writer>(m, "StlAPI_Writer")
.def(py::init<>())
.def("Write", [](StlAPI_Writer& w, const TopoDS_Shape& shape, const std::string& path) { return w.Write(shape, path.c_str()); },
py::arg("theShape"), py::arg("theFileName"));
// ---- the builder chain: command -> make-shape -> modify-shape ---------------------------------------------
py::class_<BRepBuilderAPI_Command>(m, "BRepBuilderAPI_Command").def("IsDone", &BRepBuilderAPI_Command::IsDone);
py::class_<BRepBuilderAPI_MakeShape, BRepBuilderAPI_Command>(m, "BRepBuilderAPI_MakeShape")
.def("Build", [](BRepBuilderAPI_MakeShape& op) { op.Build(); })
.def("Shape", [](BRepBuilderAPI_MakeShape& op) { return op.Shape(); })
.def("Generated", [](BRepBuilderAPI_MakeShape& op, const TopoDS_Shape& s) { return op.Generated(s); })
.def("Modified", [](BRepBuilderAPI_MakeShape& op, const TopoDS_Shape& s) { return op.Modified(s); })
.def("IsDeleted", [](BRepBuilderAPI_MakeShape& op, const TopoDS_Shape& s) { return op.IsDeleted(s); });
py::class_<BRepBuilderAPI_ModifyShape, BRepBuilderAPI_MakeShape>(m, "BRepBuilderAPI_ModifyShape")
.def("ModifiedShape", [](BRepBuilderAPI_ModifyShape& op, const TopoDS_Shape& s) { return op.ModifiedShape(s); });
py::class_<BRepBuilderAPI_Transform, BRepBuilderAPI_ModifyShape>(m, "BRepBuilderAPI_Transform")
.def(py::init<const gp_Trsf&>())
.def(py::init<const TopoDS_Shape&, const gp_Trsf&, bool, bool>(), py::arg("S"), py::arg("T"), py::arg("Copy") = false,
py::arg("CopyMesh") = false)
.def("Perform", [](BRepBuilderAPI_Transform& t, const TopoDS_Shape& s, bool copy, bool copyMesh) { t.Perform(s, copy, copyMesh); },
py::arg("S"), py::arg("Copy") = false, py::arg("CopyMesh") = false);
py::class_<BRepBuilderAPI_Copy, BRepBuilderAPI_ModifyShape>(m, "BRepBuilderAPI_Copy")
.def(py::init<>())
.def(py::init<const TopoDS_Shape&, bool, bool>(), py::arg("S"), py::arg("copyGeom") = true, py::arg("copyMesh") = false)
.def("Perform", [](BRepBuilderAPI_Copy& c, const TopoDS_Shape& s, bool copyGeom, bool copyMesh) { c.Perform(s, copyGeom, copyMesh); },
py::arg("S"), py::arg("copyGeom") = true, py::arg("copyMesh") = false);
py::class_<BRepBuilderAPI_MakeVertex, BRepBuilderAPI_MakeShape>(m, "BRepBuilderAPI_MakeVertex")
.def(py::init<const gp_Pnt&>())
.def("Vertex", [](BRepBuilderAPI_MakeVertex& v) { return v.Vertex(); });
py::class_<BRepBuilderAPI_MakeEdge, BRepBuilderAPI_MakeShape>(m, "BRepBuilderAPI_MakeEdge")
.def(py::init<>())
.def(py::init<const TopoDS_Vertex&, const TopoDS_Vertex&>())
.def(py::init<const gp_Pnt&, const gp_Pnt&>())
.def(py::init<const gp_Lin&, double, double>())
.def(py::init<const gp_Circ&>())
.def(py::init<const gp_Circ&, double, double>())
.def(py::init<const gp_Elips&>())
.def(py::init<const gp_Elips&, double, double>())
.def(py::init<const opencascade::handle<Geom_Curve>&>())
.def(py::init<const opencascade::handle<Geom_Curve>&, double, double>())
.def(py::init<const opencascade::handle<Geom_Curve>&, const gp_Pnt&, const gp_Pnt&>())
.def(py::init<const opencascade::handle<Geom_Curve>&, const TopoDS_Vertex&, const TopoDS_Vertex&>())
.def("Edge", [](BRepBuilderAPI_MakeEdge& e) { return e.Edge(); })
.def("Vertex1", [](const BRepBuilderAPI_MakeEdge& e) { return e.Vertex1(); })
.def("Vertex2", [](const BRepBuilderAPI_MakeEdge& e) { return e.Vertex2(); })
.def("Error", [](const BRepBuilderAPI_MakeEdge& e) { return static_cast<int>(e.Error()); });
py::class_<BRepBuilderAPI_MakeWire, BRepBuilderAPI_MakeShape>(m, "BRepBuilderAPI_MakeWire")
.def(py::init<>())
.def(py::init<const TopoDS_Edge&>())
.def(py::init<const TopoDS_Edge&, const TopoDS_Edge&>())
.def(py::init<const TopoDS_Wire&>())
.def("Add", [](BRepBuilderAPI_MakeWire& w, const TopoDS_Edge& e) { w.Add(e); })
.def("Add", [](BRepBuilderAPI_MakeWire& w, const TopoDS_Wire& other) { w.Add(other); })
.def("Wire", [](BRepBuilderAPI_MakeWire& w) { return w.Wire(); })
.def("Edge", [](const BRepBuilderAPI_MakeWire& w) { return w.Edge(); })
.def("Vertex", [](const BRepBuilderAPI_MakeWire& w) { return w.Vertex(); })
.def("Error", [](const BRepBuilderAPI_MakeWire& w) { return static_cast<int>(w.Error()); });
py::class_<BRepBuilderAPI_MakeFace, BRepBuilderAPI_MakeShape>(m, "BRepBuilderAPI_MakeFace")
.def(py::init<>())
.def(py::init<const TopoDS_Face&>())
.def(py::init<const gp_Pln&>())
.def(py::init<const gp_Cylinder&, double, double, double, double>(), py::arg("C"), py::arg("UMin"), py::arg("UMax"),
py::arg("VMin"), py::arg("VMax"))
.def(py::init<const gp_Cone&, double, double, double, double>(), py::arg("C"), py::arg("UMin"), py::arg("UMax"),
py::arg("VMin"), py::arg("VMax"))
.def(py::init<const gp_Sphere&, double, double, double, double>(), py::arg("C"), py::arg("UMin"), py::arg("UMax"),
py::arg("VMin"), py::arg("VMax"))
.def(py::init<const gp_Torus&, double, double, double, double>(), py::arg("C"), py::arg("UMin"), py::arg("UMax"),
py::arg("VMin"), py::arg("VMax"))
.def(py::init<const gp_Pln&, double, double, double, double>(), py::arg("P"), py::arg("UMin"), py::arg("UMax"),
py::arg("VMin"), py::arg("VMax"))
.def(py::init<const opencascade::handle<Geom_Surface>&, double, double, double, double, double>(), py::arg("S"),
py::arg("UMin"), py::arg("UMax"), py::arg("VMin"), py::arg("VMax"), py::arg("TolDegen"))
.def(py::init<const TopoDS_Wire&, bool>(), py::arg("W"), py::arg("OnlyPlane") = false)
.def(py::init<const opencascade::handle<Geom_Surface>&, double>(), py::arg("S"), py::arg("TolDegen"))
.def(py::init<const opencascade::handle<Geom_Surface>&, const TopoDS_Wire&, bool>(), py::arg("S"), py::arg("W"),
py::arg("Inside") = true)
.def(py::init<const TopoDS_Face&, const TopoDS_Wire&>())
.def("Add", [](BRepBuilderAPI_MakeFace& f, const TopoDS_Wire& w) { f.Add(w); })
.def("Face", [](BRepBuilderAPI_MakeFace& f) { return f.Face(); })
.def("Error", [](const BRepBuilderAPI_MakeFace& f) { return static_cast<int>(f.Error()); });
py::class_<BRepBuilderAPI_MakeSolid, BRepBuilderAPI_MakeShape>(m, "BRepBuilderAPI_MakeSolid")
.def(py::init<>())
.def(py::init<const TopoDS_Shell&>())
.def(py::init<const TopoDS_Solid&>())
.def("Add", [](BRepBuilderAPI_MakeSolid& s, const TopoDS_Shell& shell) { s.Add(shell); })
.def("Solid", [](BRepBuilderAPI_MakeSolid& s) { return s.Solid(); });
// ---- booleans -----------------------------------------------------------------------------------------------
// BRepAlgoAPI_Algo (protected destructor) is not a Python class: its methods are the builder's own here.
py::class_<BRepAlgoAPI_BuilderAlgo, BRepBuilderAPI_MakeShape>(m, "BRepAlgoAPI_BuilderAlgo")
.def("SetRunParallel", [](BRepAlgoAPI_BuilderAlgo& a, bool v) { a.SetRunParallel(v); })
.def("RunParallel", [](const BRepAlgoAPI_BuilderAlgo& a) { return a.RunParallel(); })
.def("SetFuzzyValue", [](BRepAlgoAPI_BuilderAlgo& a, double v) { a.SetFuzzyValue(v); })
.def("FuzzyValue", [](const BRepAlgoAPI_BuilderAlgo& a) { return a.FuzzyValue(); })
.def("SetUseOBB", [](BRepAlgoAPI_BuilderAlgo& a, bool v) { a.SetUseOBB(v); })
.def("SetNonDestructive", [](BRepAlgoAPI_BuilderAlgo& a, bool v) { a.SetNonDestructive(v); })
.def("SetGlue", [](BRepAlgoAPI_BuilderAlgo& a, BOPAlgo_GlueEnum g) { a.SetGlue(g); })
.def("SetArguments", [](BRepAlgoAPI_BuilderAlgo& a, const TopTools_ListOfShape& l) { a.SetArguments(l); })
.def("Arguments", [](const BRepAlgoAPI_BuilderAlgo& a) { return a.Arguments(); })
.def("SetToFillHistory", [](BRepAlgoAPI_BuilderAlgo& a, bool v) { a.SetToFillHistory(v); })
.def("HasHistory", [](const BRepAlgoAPI_BuilderAlgo& a) { return a.HasHistory(); })
.def("SimplifyResult", [](BRepAlgoAPI_BuilderAlgo& a, bool unifyEdges, bool unifyFaces, double angTol) {
a.SimplifyResult(unifyEdges, unifyFaces, angTol);
}, py::arg("theUnifyEdges") = true, py::arg("theUnifyFaces") = true, py::arg("theAngularTol") = 1e-12)
.def("Build", [](BRepAlgoAPI_BuilderAlgo& a) { a.Build(); })
.def("IsDeleted", [](BRepAlgoAPI_BuilderAlgo& a, const TopoDS_Shape& s) { return a.IsDeleted(s); })
.def("Modified", [](BRepAlgoAPI_BuilderAlgo& a, const TopoDS_Shape& s) { return a.Modified(s); })
.def("Generated", [](BRepAlgoAPI_BuilderAlgo& a, const TopoDS_Shape& s) { return a.Generated(s); })
.def("HasModified", [](const BRepAlgoAPI_BuilderAlgo& a) { return a.HasModified(); })
.def("HasGenerated", [](const BRepAlgoAPI_BuilderAlgo& a) { return a.HasGenerated(); })
.def("HasDeleted", [](const BRepAlgoAPI_BuilderAlgo& a) { return a.HasDeleted(); });
py::class_<BRepAlgoAPI_BooleanOperation, BRepAlgoAPI_BuilderAlgo>(m, "BRepAlgoAPI_BooleanOperation")
.def("SetTools", [](BRepAlgoAPI_BooleanOperation& a, const TopTools_ListOfShape& l) { a.SetTools(l); })
.def("Tools", [](const BRepAlgoAPI_BooleanOperation& a) { return a.Tools(); })
.def("Shape1", [](const BRepAlgoAPI_BooleanOperation& a) { return a.Shape1(); })
.def("Shape2", [](const BRepAlgoAPI_BooleanOperation& a) { return a.Shape2(); })
.def("Build", [](BRepAlgoAPI_BooleanOperation& a) { a.Build(); });
boolean_class<BRepAlgoAPI_Common>(m, "BRepAlgoAPI_Common");
boolean_class<BRepAlgoAPI_Cut>(m, "BRepAlgoAPI_Cut");
boolean_class<BRepAlgoAPI_Fuse>(m, "BRepAlgoAPI_Fuse");
py::class_<BRepAlgoAPI_Section, BRepAlgoAPI_BooleanOperation>(m, "BRepAlgoAPI_Section")
.def(py::init<>())
.def(py::init<const TopoDS_Shape&, const TopoDS_Shape&, bool>(), py::arg("S1"), py::arg("S2"), py::arg("PerformNow") = true)
.def(py::init<const TopoDS_Shape&, const gp_Pln&, bool>(), py::arg("S1"), py::arg("Pl"), py::arg("PerformNow") = true)
.def("Build", [](BRepAlgoAPI_Section& s) { s.Build(); })
.def("Init1", [](BRepAlgoAPI_Section& s, const TopoDS_Shape& v) { s.Init1(v); })
.def("Init2", [](BRepAlgoAPI_Section& s, const TopoDS_Shape& v) { s.Init2(v); })
.def("Init1", [](BRepAlgoAPI_Section& s, const gp_Pln& v) { s.Init1(v); })
.def("Approximation", [](BRepAlgoAPI_Section& s, bool v) { s.Approximation(v); })
.def("ComputePCurveOn1", [](BRepAlgoAPI_Section& s, bool v) { s.ComputePCurveOn1(v); })
.def("ComputePCurveOn2", [](BRepAlgoAPI_Section& s, bool v) { s.ComputePCurveOn2(v); });
// ---- primitives, fillets, mesh --------------------------------------------------------------------------------
py::class_<BRepPrimAPI_MakeBox, BRepBuilderAPI_MakeShape>(m, "BRepPrimAPI_MakeBox")
.def(py::init<double, double, double>())
.def(py::init<const gp_Pnt&, double, double, double>())
.def(py::init<const gp_Pnt&, const gp_Pnt&>())
.def(py::init<const gp_Ax2&, double, double, double>())
.def("Shell", [](BRepPrimAPI_MakeBox& b) { return b.Shell(); })
.def("Solid", [](BRepPrimAPI_MakeBox& b) { return b.Solid(); });
py::class_<BRepPrimAPI_MakeCylinder, BRepBuilderAPI_MakeShape>(m, "BRepPrimAPI_MakeCylinder")
.def(py::init<double, double>())
.def(py::init<double, double, double>())
.def(py::init<const gp_Ax2&, double, double>())
.def(py::init<const gp_Ax2&, double, double, double>())
.def("Shell", [](BRepPrimAPI_MakeCylinder& c) { return c.Shell(); })
.def("Solid", [](BRepPrimAPI_MakeCylinder& c) { return c.Solid(); });
py::class_<BRepPrimAPI_MakeSphere, BRepBuilderAPI_MakeShape>(m, "BRepPrimAPI_MakeSphere")
.def(py::init<double>())
.def(py::init<const gp_Pnt&, double>())
.def(py::init<const gp_Ax2&, double>())
.def("Shell", [](BRepPrimAPI_MakeSphere& s) { return s.Shell(); })
.def("Solid", [](BRepPrimAPI_MakeSphere& s) { return s.Solid(); });
py::class_<BRepPrimAPI_MakeSweep, BRepBuilderAPI_MakeShape>(m, "BRepPrimAPI_MakeSweep")
.def("FirstShape", [](BRepPrimAPI_MakeSweep& s) { return s.FirstShape(); })
.def("LastShape", [](BRepPrimAPI_MakeSweep& s) { return s.LastShape(); });
py::class_<BRepPrimAPI_MakePrism, BRepPrimAPI_MakeSweep>(m, "BRepPrimAPI_MakePrism")
.def(py::init<const TopoDS_Shape&, const gp_Vec&, bool, bool>(), py::arg("S"), py::arg("V"), py::arg("Copy") = false,
py::arg("Canonize") = true);
py::class_<BRepFilletAPI_LocalOperation, BRepBuilderAPI_MakeShape>(m, "BRepFilletAPI_LocalOperation");
py::class_<BRepFilletAPI_MakeFillet, BRepFilletAPI_LocalOperation>(m, "BRepFilletAPI_MakeFillet")
.def(py::init<const TopoDS_Shape&>())
.def("Add", [](BRepFilletAPI_MakeFillet& f, double radius, const TopoDS_Edge& e) { f.Add(radius, e); })
.def("Add", [](BRepFilletAPI_MakeFillet& f, double r1, double r2, const TopoDS_Edge& e) { f.Add(r1, r2, e); })
.def("NbContours", [](const BRepFilletAPI_MakeFillet& f) { return f.NbContours(); })
.def("Build", [](BRepFilletAPI_MakeFillet& f) { f.Build(); });
py::class_<BRepMesh_IncrementalMesh>(m, "BRepMesh_IncrementalMesh")
.def(py::init<>())
.def(py::init<const TopoDS_Shape&, double, bool, double, bool>(), py::arg("theShape"), py::arg("theLinDeflection"),
py::arg("isRelative") = false, py::arg("theAngDeflection") = 0.5, py::arg("isInParallel") = false)
.def("Perform", [](BRepMesh_IncrementalMesh& mesh) { mesh.Perform(); })
.def("IsDone", [](const BRepMesh_IncrementalMesh& mesh) { return mesh.IsDone(); })
.def("Shape", [](const BRepMesh_IncrementalMesh& mesh) { return mesh.Shape(); })
.def("IsModified", [](const BRepMesh_IncrementalMesh& mesh) { return mesh.IsModified(); })
.def("GetStatusFlags", [](const BRepMesh_IncrementalMesh& mesh) { return mesh.GetStatusFlags(); });
// ---- hidden-line removal ------------------------------------------------------------------------------------
py::class_<HLRAlgo_Projector>(m, "HLRAlgo_Projector")
.def(py::init<>())
.def(py::init<const gp_Ax2&>())
.def(py::init<const gp_Ax2&, double>());
py::class_<HLRBRep_InternalAlgo, opencascade::handle<HLRBRep_InternalAlgo>>(m, "HLRBRep_InternalAlgo")
.def("Projector", [](HLRBRep_InternalAlgo& a, const HLRAlgo_Projector& p) { a.Projector(p); })
.def("Update", [](HLRBRep_InternalAlgo& a) { a.Update(); })
.def("Hide", [](HLRBRep_InternalAlgo& a) { a.Hide(); });
py::class_<HLRBRep_Algo, opencascade::handle<HLRBRep_Algo>, HLRBRep_InternalAlgo>(m, "HLRBRep_Algo")
.def(py::init<>())
.def("Add", [](HLRBRep_Algo& a, const TopoDS_Shape& s, int nbIso) { a.Add(s, nbIso); }, py::arg("S"), py::arg("nbIso") = 0);
py::class_<HLRBRep_HLRToShape>(m, "HLRBRep_HLRToShape")
.def(py::init<const opencascade::handle<HLRBRep_Algo>&>())
.def("VCompound", [](HLRBRep_HLRToShape& h) { return h.VCompound(); })
.def("Rg1LineVCompound", [](HLRBRep_HLRToShape& h) { return h.Rg1LineVCompound(); })
.def("RgNLineVCompound", [](HLRBRep_HLRToShape& h) { return h.RgNLineVCompound(); })
.def("OutLineVCompound", [](HLRBRep_HLRToShape& h) { return h.OutLineVCompound(); })
.def("IsoLineVCompound", [](HLRBRep_HLRToShape& h) { return h.IsoLineVCompound(); })
.def("HCompound", [](HLRBRep_HLRToShape& h) { return h.HCompound(); })
.def("Rg1LineHCompound", [](HLRBRep_HLRToShape& h) { return h.Rg1LineHCompound(); })
.def("RgNLineHCompound", [](HLRBRep_HLRToShape& h) { return h.RgNLineHCompound(); })
.def("OutLineHCompound", [](HLRBRep_HLRToShape& h) { return h.OutLineHCompound(); })
.def("IsoLineHCompound", [](HLRBRep_HLRToShape& h) { return h.IsoLineHCompound(); });
// ---- shape upgrade ------------------------------------------------------------------------------------------
py::class_<ShapeUpgrade_ShapeDivide>(m, "ShapeUpgrade_ShapeDivide")
.def("Perform", [](ShapeUpgrade_ShapeDivide& d, bool newContext) { return d.Perform(newContext); }, py::arg("newContext") = true)
.def("Result", [](const ShapeUpgrade_ShapeDivide& d) { return d.Result(); });
py::class_<ShapeUpgrade_ShapeDivideContinuity, ShapeUpgrade_ShapeDivide>(m, "ShapeUpgrade_ShapeDivideContinuity")
.def(py::init<const TopoDS_Shape&>())
.def("SetTolerance", [](ShapeUpgrade_ShapeDivideContinuity& d, double t) { d.SetTolerance(t); })
.def("SetBoundaryCriterion", [](ShapeUpgrade_ShapeDivideContinuity& d, GeomAbs_Shape c) { d.SetBoundaryCriterion(c); },
py::arg("Criterion") = GeomAbs_C1)
.def("SetPCurveCriterion", [](ShapeUpgrade_ShapeDivideContinuity& d, GeomAbs_Shape c) { d.SetPCurveCriterion(c); },
py::arg("Criterion") = GeomAbs_C1)
.def("SetSurfaceCriterion", [](ShapeUpgrade_ShapeDivideContinuity& d, GeomAbs_Shape c) { d.SetSurfaceCriterion(c); },
py::arg("Criterion") = GeomAbs_C1);
}
} // namespace scad::pybind::occt
@@ -0,0 +1,469 @@
// gp_*, the topology enums, TopLoc_Location, TopoDS_*, TopExp, TopTools_*, Precision, BRep_Tool, BRep_Builder.
#include <BRepAdaptor_Curve.hxx>
#include <BRep_Builder.hxx>
#include <BRep_Tool.hxx>
#include <Geom2d_Curve.hxx>
#include <Geom_Curve.hxx>
#include <Geom_Surface.hxx>
#include <GeomAbs_Shape.hxx>
#include <Poly_Triangulation.hxx>
#include <Precision.hxx>
#include <Standard_Version.hxx>
#include <TopAbs_Orientation.hxx>
#include <TopAbs_ShapeEnum.hxx>
#include <TopAbs_State.hxx>
#include <TopExp.hxx>
#include <TopExp_Explorer.hxx>
#include <TopLoc_Location.hxx>
#include <TopTools_FormatVersion.hxx>
#include <TopTools_IndexedMapOfShape.hxx>
#include <TopTools_ListIteratorOfListOfShape.hxx>
#include <TopTools_ListOfShape.hxx>
#include <TopoDS.hxx>
#include <TopoDS_Builder.hxx>
#include <TopoDS_CompSolid.hxx>
#include <TopoDS_Compound.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Face.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Shell.hxx>
#include <TopoDS_Solid.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopoDS_Wire.hxx>
#include <gp_Ax1.hxx>
#include <gp_Ax2.hxx>
#include <gp_Ax3.hxx>
#include <gp_Circ.hxx>
#include <gp_Cylinder.hxx>
#include <gp_Dir.hxx>
#include <gp_Elips.hxx>
#include <gp_Lin.hxx>
#include <gp_Pln.hxx>
#include <gp_Pnt.hxx>
#include <gp_Pnt2d.hxx>
#include <gp_Trsf.hxx>
#include <gp_Vec.hxx>
#include <gp_XYZ.hxx>
#include "occt.hpp"
namespace scad::pybind::occt {
namespace {
template <class T>
py::tuple coord3(const T& v) {
return py::make_tuple(v.X(), v.Y(), v.Z());
}
// A TopoDS_Shape as the Python class of its type (OCP hands the most derived class back from TopoDS.*_s casts and
// from explorers only as TopoDS_Shape; callers cast explicitly).
template <class Cls>
void shape_members(Cls& cls) {
cls.def("IsNull", &TopoDS_Shape::IsNull)
.def("Nullify", &TopoDS_Shape::Nullify)
.def("ShapeType", &TopoDS_Shape::ShapeType)
.def("Orientation", [](const TopoDS_Shape& s) { return s.Orientation(); })
.def("Orientation", [](TopoDS_Shape& s, TopAbs_Orientation o) { s.Orientation(o); })
.def("Location", [](const TopoDS_Shape& s) { return s.Location(); })
.def("Location", [](TopoDS_Shape& s, const TopLoc_Location& l, bool raise) { s.Location(l, raise); }, py::arg("Loc"),
py::arg("theRaiseExc") = true)
.def("Located", [](const TopoDS_Shape& s, const TopLoc_Location& l, bool raise) { return s.Located(l, raise); },
py::arg("theLoc"), py::arg("theRaiseExc") = true)
.def("Moved", [](const TopoDS_Shape& s, const TopLoc_Location& l, bool raise) { return s.Moved(l, raise); },
py::arg("thePosition"), py::arg("theRaiseExc") = true)
.def("Oriented", &TopoDS_Shape::Oriented)
.def("Reversed", &TopoDS_Shape::Reversed)
.def("Reverse", &TopoDS_Shape::Reverse)
.def("Complemented", &TopoDS_Shape::Complemented)
.def("Complement", &TopoDS_Shape::Complement)
.def("EmptyCopied", &TopoDS_Shape::EmptyCopied)
.def("IsSame", &TopoDS_Shape::IsSame)
.def("IsEqual", &TopoDS_Shape::IsEqual)
.def("IsPartner", &TopoDS_Shape::IsPartner)
.def("Free", [](const TopoDS_Shape& s) { return s.Free(); })
.def("Closed", [](const TopoDS_Shape& s) { return s.Closed(); })
.def("Closed", [](TopoDS_Shape& s, bool v) { s.Closed(v); })
.def("Convex", [](const TopoDS_Shape& s) { return s.Convex(); })
.def("Checked", [](const TopoDS_Shape& s) { return s.Checked(); })
.def("Infinite", [](const TopoDS_Shape& s) { return s.Infinite(); })
.def("Modified", [](const TopoDS_Shape& s) { return s.Modified(); })
.def("Orientable", [](const TopoDS_Shape& s) { return s.Orientable(); })
.def("HashCode", [](const TopoDS_Shape& s, int upper) { return static_cast<long>(std::hash<TopoDS_Shape>{}(s) % static_cast<std::size_t>(upper)); },
py::arg("theUpperBound") = 2147483647)
.def("__eq__", [](const TopoDS_Shape& a, const TopoDS_Shape& b) { return a.IsEqual(b); }, py::is_operator())
.def("__hash__", [](const TopoDS_Shape& s) { return std::hash<TopoDS_Shape>{}(s); });
}
template <class Sub>
void sub_shape(py::module_& m, const char* name) {
py::class_<Sub, TopoDS_Shape>(m, name).def(py::init<>());
}
} // namespace
void bind_core(py::module_& m) {
m.attr("OCC_VERSION_COMPLETE") = OCC_VERSION_COMPLETE; // "7.9.3": what OCP calls its version, minus its own build number
// ---- enums -------------------------------------------------------------------------------------------------
py::enum_<TopAbs_ShapeEnum>(m, "TopAbs_ShapeEnum")
.value("TopAbs_COMPOUND", TopAbs_COMPOUND)
.value("TopAbs_COMPSOLID", TopAbs_COMPSOLID)
.value("TopAbs_SOLID", TopAbs_SOLID)
.value("TopAbs_SHELL", TopAbs_SHELL)
.value("TopAbs_FACE", TopAbs_FACE)
.value("TopAbs_WIRE", TopAbs_WIRE)
.value("TopAbs_EDGE", TopAbs_EDGE)
.value("TopAbs_VERTEX", TopAbs_VERTEX)
.value("TopAbs_SHAPE", TopAbs_SHAPE)
.export_values();
py::enum_<TopAbs_Orientation>(m, "TopAbs_Orientation")
.value("TopAbs_FORWARD", TopAbs_FORWARD)
.value("TopAbs_REVERSED", TopAbs_REVERSED)
.value("TopAbs_INTERNAL", TopAbs_INTERNAL)
.value("TopAbs_EXTERNAL", TopAbs_EXTERNAL)
.export_values();
py::enum_<TopAbs_State>(m, "TopAbs_State")
.value("TopAbs_IN", TopAbs_IN)
.value("TopAbs_OUT", TopAbs_OUT)
.value("TopAbs_ON", TopAbs_ON)
.value("TopAbs_UNKNOWN", TopAbs_UNKNOWN)
.export_values();
py::enum_<GeomAbs_Shape>(m, "GeomAbs_Shape")
.value("GeomAbs_C0", GeomAbs_C0)
.value("GeomAbs_G1", GeomAbs_G1)
.value("GeomAbs_C1", GeomAbs_C1)
.value("GeomAbs_G2", GeomAbs_G2)
.value("GeomAbs_C2", GeomAbs_C2)
.value("GeomAbs_C3", GeomAbs_C3)
.value("GeomAbs_CN", GeomAbs_CN)
.export_values();
py::enum_<TopTools_FormatVersion>(m, "TopTools_FormatVersion")
.value("TopTools_FormatVersion_VERSION_1", TopTools_FormatVersion_VERSION_1)
.value("TopTools_FormatVersion_VERSION_2", TopTools_FormatVersion_VERSION_2)
.value("TopTools_FormatVersion_VERSION_3", TopTools_FormatVersion_VERSION_3)
.export_values();
// ---- gp ----------------------------------------------------------------------------------------------------
py::class_<gp_XYZ>(m, "gp_XYZ")
.def(py::init<>())
.def(py::init<double, double, double>())
.def("X", &gp_XYZ::X)
.def("Y", &gp_XYZ::Y)
.def("Z", &gp_XYZ::Z)
.def("Coord", [](const gp_XYZ& v) { return coord3(v); });
py::class_<gp_Pnt2d>(m, "gp_Pnt2d")
.def(py::init<>())
.def(py::init<double, double>())
.def("X", &gp_Pnt2d::X)
.def("Y", &gp_Pnt2d::Y)
.def("Coord", [](const gp_Pnt2d& p) { return py::make_tuple(p.X(), p.Y()); })
.def("Distance", &gp_Pnt2d::Distance);
py::class_<gp_Pnt>(m, "gp_Pnt")
.def(py::init<>())
.def(py::init<double, double, double>(), py::arg("Xp"), py::arg("Yp"), py::arg("Zp"))
.def("X", &gp_Pnt::X)
.def("Y", &gp_Pnt::Y)
.def("Z", &gp_Pnt::Z)
.def("SetX", &gp_Pnt::SetX)
.def("SetY", &gp_Pnt::SetY)
.def("SetZ", &gp_Pnt::SetZ)
.def("SetCoord", [](gp_Pnt& p, double x, double y, double z) { p.SetCoord(x, y, z); })
.def("Coord", [](const gp_Pnt& p) { return coord3(p); })
.def("XYZ", [](const gp_Pnt& p) { return p.XYZ(); })
.def("Distance", &gp_Pnt::Distance)
.def("SquareDistance", &gp_Pnt::SquareDistance)
.def("IsEqual", &gp_Pnt::IsEqual)
.def("Translate", [](gp_Pnt& p, const gp_Vec& v) { p.Translate(v); })
.def("Translated", [](const gp_Pnt& p, const gp_Vec& v) { return p.Translated(v); })
.def("Transform", &gp_Pnt::Transform)
.def("Transformed", &gp_Pnt::Transformed)
.def("__repr__", [](const gp_Pnt& p) {
return "gp_Pnt(" + std::to_string(p.X()) + ", " + std::to_string(p.Y()) + ", " + std::to_string(p.Z()) + ")";
});
py::class_<gp_Vec>(m, "gp_Vec")
.def(py::init<>())
.def(py::init<double, double, double>())
.def(py::init<const gp_Pnt&, const gp_Pnt&>())
.def(py::init<const gp_Dir&>())
.def("X", &gp_Vec::X)
.def("Y", &gp_Vec::Y)
.def("Z", &gp_Vec::Z)
.def("SetCoord", [](gp_Vec& v, double x, double y, double z) { v.SetCoord(x, y, z); })
.def("Coord", [](const gp_Vec& v) { return coord3(v); })
.def("Magnitude", &gp_Vec::Magnitude)
.def("SquareMagnitude", &gp_Vec::SquareMagnitude)
.def("Normalize", &gp_Vec::Normalize)
.def("Normalized", &gp_Vec::Normalized)
.def("Multiplied", [](const gp_Vec& v, double s) { return v.Multiplied(s); })
.def("Multiply", [](gp_Vec& v, double s) { v.Multiply(s); })
.def("Scaled", [](const gp_Vec& v, double s) { return v.Multiplied(s); })
.def("Added", [](const gp_Vec& v, const gp_Vec& o) { return v.Added(o); })
.def("Subtracted", [](const gp_Vec& v, const gp_Vec& o) { return v.Subtracted(o); })
.def("Dot", &gp_Vec::Dot)
.def("Crossed", [](const gp_Vec& v, const gp_Vec& o) { return v.Crossed(o); })
.def("Reverse", &gp_Vec::Reverse)
.def("Reversed", &gp_Vec::Reversed)
.def("Angle", &gp_Vec::Angle)
.def("IsParallel", &gp_Vec::IsParallel)
.def("Transform", &gp_Vec::Transform)
.def("Transformed", &gp_Vec::Transformed);
py::class_<gp_Dir>(m, "gp_Dir")
.def(py::init<>())
.def(py::init<double, double, double>())
.def(py::init<const gp_Vec&>())
.def("X", &gp_Dir::X)
.def("Y", &gp_Dir::Y)
.def("Z", &gp_Dir::Z)
.def("Coord", [](const gp_Dir& d) { return coord3(d); })
.def("Reverse", &gp_Dir::Reverse)
.def("Reversed", &gp_Dir::Reversed)
.def("Dot", &gp_Dir::Dot)
.def("Crossed", [](const gp_Dir& d, const gp_Dir& o) { return d.Crossed(o); })
.def("Angle", &gp_Dir::Angle)
.def("IsParallel", &gp_Dir::IsParallel)
.def("Transform", &gp_Dir::Transform)
.def("Transformed", &gp_Dir::Transformed);
py::class_<gp_Ax1>(m, "gp_Ax1")
.def(py::init<>())
.def(py::init<const gp_Pnt&, const gp_Dir&>())
.def("Location", [](const gp_Ax1& a) { return a.Location(); })
.def("Direction", [](const gp_Ax1& a) { return a.Direction(); });
py::class_<gp_Ax2>(m, "gp_Ax2")
.def(py::init<>())
.def(py::init<const gp_Pnt&, const gp_Dir&>())
.def(py::init<const gp_Pnt&, const gp_Dir&, const gp_Dir&>())
.def("Location", [](const gp_Ax2& a) { return a.Location(); })
.def("Direction", [](const gp_Ax2& a) { return a.Direction(); })
.def("XDirection", [](const gp_Ax2& a) { return a.XDirection(); })
.def("YDirection", [](const gp_Ax2& a) { return a.YDirection(); })
.def("Axis", [](const gp_Ax2& a) { return a.Axis(); });
py::class_<gp_Ax3>(m, "gp_Ax3")
.def(py::init<>())
.def(py::init<const gp_Pnt&, const gp_Dir&>())
.def(py::init<const gp_Pnt&, const gp_Dir&, const gp_Dir&>())
.def("Location", [](const gp_Ax3& a) { return a.Location(); })
.def("Direction", [](const gp_Ax3& a) { return a.Direction(); })
.def("XDirection", [](const gp_Ax3& a) { return a.XDirection(); })
.def("YDirection", [](const gp_Ax3& a) { return a.YDirection(); })
.def("Axis", [](const gp_Ax3& a) { return a.Axis(); });
py::class_<gp_Trsf>(m, "gp_Trsf")
.def(py::init<>())
.def("SetRotation", [](gp_Trsf& t, const gp_Ax1& a, double angle) { t.SetRotation(a, angle); })
.def("SetTranslation", [](gp_Trsf& t, const gp_Vec& v) { t.SetTranslation(v); })
.def("SetScale", [](gp_Trsf& t, const gp_Pnt& p, double s) { t.SetScale(p, s); })
.def("SetMirror", [](gp_Trsf& t, const gp_Ax1& a) { t.SetMirror(a); })
.def("SetValues", [](gp_Trsf& t, double a11, double a12, double a13, double a14, double a21, double a22, double a23,
double a24, double a31, double a32, double a33, double a34) {
t.SetValues(a11, a12, a13, a14, a21, a22, a23, a24, a31, a32, a33, a34);
})
.def("TranslationPart", [](const gp_Trsf& t) { return t.TranslationPart(); })
.def("Value", [](const gp_Trsf& t, int r, int c) { return t.Value(r, c); })
.def("ScaleFactor", &gp_Trsf::ScaleFactor)
.def("Inverted", &gp_Trsf::Inverted)
.def("Multiplied", [](const gp_Trsf& t, const gp_Trsf& o) { return t.Multiplied(o); })
.def("IsNegative", &gp_Trsf::IsNegative);
py::class_<gp_Pln>(m, "gp_Pln")
.def(py::init<>())
.def(py::init<const gp_Pnt&, const gp_Dir&>())
.def(py::init<const gp_Ax3&>())
.def("Axis", [](const gp_Pln& p) { return p.Axis(); })
.def("Location", [](const gp_Pln& p) { return p.Location(); })
.def("Position", [](const gp_Pln& p) { return p.Position(); })
.def("Distance", [](const gp_Pln& p, const gp_Pnt& q) { return p.Distance(q); });
py::class_<gp_Lin>(m, "gp_Lin")
.def(py::init<>())
.def(py::init<const gp_Pnt&, const gp_Dir&>())
.def("Direction", [](const gp_Lin& l) { return l.Direction(); })
.def("Location", [](const gp_Lin& l) { return l.Location(); });
py::class_<gp_Circ>(m, "gp_Circ")
.def(py::init<>())
.def(py::init<const gp_Ax2&, double>())
.def("Axis", [](const gp_Circ& c) { return c.Axis(); })
.def("Location", [](const gp_Circ& c) { return c.Location(); })
.def("Position", [](const gp_Circ& c) { return c.Position(); })
.def("Radius", &gp_Circ::Radius)
.def("XAxis", [](const gp_Circ& c) { return c.XAxis(); })
.def("YAxis", [](const gp_Circ& c) { return c.YAxis(); });
py::class_<gp_Elips>(m, "gp_Elips")
.def(py::init<>())
.def(py::init<const gp_Ax2&, double, double>())
.def("Axis", [](const gp_Elips& e) { return e.Axis(); })
.def("Location", [](const gp_Elips& e) { return e.Location(); })
.def("Position", [](const gp_Elips& e) { return e.Position(); })
.def("MajorRadius", &gp_Elips::MajorRadius)
.def("MinorRadius", &gp_Elips::MinorRadius)
.def("XAxis", [](const gp_Elips& e) { return e.XAxis(); })
.def("YAxis", [](const gp_Elips& e) { return e.YAxis(); });
py::class_<gp_Cylinder>(m, "gp_Cylinder")
.def(py::init<>())
.def(py::init<const gp_Ax3&, double>())
.def("Axis", [](const gp_Cylinder& c) { return c.Axis(); })
.def("Location", [](const gp_Cylinder& c) { return c.Location(); })
.def("Position", [](const gp_Cylinder& c) { return c.Position(); })
.def("Radius", &gp_Cylinder::Radius);
// ---- TopLoc / TopoDS ---------------------------------------------------------------------------------------
py::class_<TopLoc_Location>(m, "TopLoc_Location")
.def(py::init<>())
.def(py::init<const gp_Trsf&>())
.def("IsIdentity", &TopLoc_Location::IsIdentity)
.def("Transformation", [](const TopLoc_Location& l) { return l.Transformation(); })
.def("Inverted", &TopLoc_Location::Inverted)
.def("Multiplied", &TopLoc_Location::Multiplied)
.def("IsEqual", &TopLoc_Location::IsEqual);
py::class_<TopoDS_Shape> shape(m, "TopoDS_Shape");
shape.def(py::init<>());
shape_members(shape);
sub_shape<TopoDS_Vertex>(m, "TopoDS_Vertex");
sub_shape<TopoDS_Edge>(m, "TopoDS_Edge");
sub_shape<TopoDS_Wire>(m, "TopoDS_Wire");
sub_shape<TopoDS_Face>(m, "TopoDS_Face");
sub_shape<TopoDS_Shell>(m, "TopoDS_Shell");
sub_shape<TopoDS_Solid>(m, "TopoDS_Solid");
sub_shape<TopoDS_CompSolid>(m, "TopoDS_CompSolid");
sub_shape<TopoDS_Compound>(m, "TopoDS_Compound");
// `TopoDS.Face_s(shape)`: the shape as its own type.
struct TopoDSCasts {}; // `TopoDS` is a namespace in OCCT; OCP presents its casts as a class
py::class_<TopoDSCasts>(m, "TopoDS")
.def_static("Vertex_s", [](const TopoDS_Shape& s) { return TopoDS::Vertex(s); })
.def_static("Edge_s", [](const TopoDS_Shape& s) { return TopoDS::Edge(s); })
.def_static("Wire_s", [](const TopoDS_Shape& s) { return TopoDS::Wire(s); })
.def_static("Face_s", [](const TopoDS_Shape& s) { return TopoDS::Face(s); })
.def_static("Shell_s", [](const TopoDS_Shape& s) { return TopoDS::Shell(s); })
.def_static("Solid_s", [](const TopoDS_Shape& s) { return TopoDS::Solid(s); })
.def_static("CompSolid_s", [](const TopoDS_Shape& s) { return TopoDS::CompSolid(s); })
.def_static("Compound_s", [](const TopoDS_Shape& s) { return TopoDS::Compound(s); });
py::class_<TopoDS_Builder>(m, "TopoDS_Builder")
.def(py::init<>())
.def("MakeCompound", [](const TopoDS_Builder& b, TopoDS_Compound& c) { b.MakeCompound(c); })
.def("MakeCompSolid", [](const TopoDS_Builder& b, TopoDS_CompSolid& c) { b.MakeCompSolid(c); })
.def("MakeSolid", [](const TopoDS_Builder& b, TopoDS_Solid& s) { b.MakeSolid(s); })
.def("MakeShell", [](const TopoDS_Builder& b, TopoDS_Shell& s) { b.MakeShell(s); })
.def("MakeWire", [](const TopoDS_Builder& b, TopoDS_Wire& w) { b.MakeWire(w); })
.def("Add", [](const TopoDS_Builder& b, TopoDS_Shape& whole, const TopoDS_Shape& part) { b.Add(whole, part); })
.def("Remove", [](const TopoDS_Builder& b, TopoDS_Shape& whole, const TopoDS_Shape& part) { b.Remove(whole, part); });
// ---- TopExp / TopTools -------------------------------------------------------------------------------------
py::class_<TopTools_ListOfShape>(m, "TopTools_ListOfShape")
.def(py::init<>())
.def("Append", [](TopTools_ListOfShape& l, const TopoDS_Shape& s) { l.Append(s); })
.def("Prepend", [](TopTools_ListOfShape& l, const TopoDS_Shape& s) { l.Prepend(s); })
.def("Extent", [](const TopTools_ListOfShape& l) { return l.Extent(); })
.def("Size", [](const TopTools_ListOfShape& l) { return l.Size(); })
.def("IsEmpty", [](const TopTools_ListOfShape& l) { return l.IsEmpty(); })
.def("Clear", [](TopTools_ListOfShape& l) { l.Clear(); })
.def("First", [](const TopTools_ListOfShape& l) { return l.First(); })
.def("Last", [](const TopTools_ListOfShape& l) { return l.Last(); })
.def("__len__", [](const TopTools_ListOfShape& l) { return l.Extent(); })
.def("__iter__", [](const TopTools_ListOfShape& l) {
py::list items;
for (TopTools_ListIteratorOfListOfShape it(l); it.More(); it.Next()) items.append(it.Value());
return py::iter(items);
});
py::class_<TopTools_IndexedMapOfShape>(m, "TopTools_IndexedMapOfShape")
.def(py::init<>())
.def("Add", [](TopTools_IndexedMapOfShape& map, const TopoDS_Shape& s) { return map.Add(s); })
.def("Contains", [](const TopTools_IndexedMapOfShape& map, const TopoDS_Shape& s) { return map.Contains(s); })
.def("FindIndex", [](const TopTools_IndexedMapOfShape& map, const TopoDS_Shape& s) { return map.FindIndex(s); })
.def("FindKey", [](const TopTools_IndexedMapOfShape& map, int i) { return map.FindKey(i); })
.def("Extent", [](const TopTools_IndexedMapOfShape& map) { return map.Extent(); })
.def("Size", [](const TopTools_IndexedMapOfShape& map) { return map.Size(); })
.def("Clear", [](TopTools_IndexedMapOfShape& map) { map.Clear(); })
.def("__len__", [](const TopTools_IndexedMapOfShape& map) { return map.Extent(); });
py::class_<TopExp>(m, "TopExp")
.def_static("MapShapes_s", [](const TopoDS_Shape& s, TopAbs_ShapeEnum t, TopTools_IndexedMapOfShape& map) { TopExp::MapShapes(s, t, map); })
.def_static("MapShapes_s", [](const TopoDS_Shape& s, TopTools_IndexedMapOfShape& map) { TopExp::MapShapes(s, map); })
.def_static("FirstVertex_s", [](const TopoDS_Edge& e, bool cumOri) { return TopExp::FirstVertex(e, cumOri); }, py::arg("E"), py::arg("CumOri") = false)
.def_static("LastVertex_s", [](const TopoDS_Edge& e, bool cumOri) { return TopExp::LastVertex(e, cumOri); }, py::arg("E"), py::arg("CumOri") = false)
.def_static("Vertices_s", [](const TopoDS_Edge& e, TopoDS_Vertex& v1, TopoDS_Vertex& v2, bool cumOri) { TopExp::Vertices(e, v1, v2, cumOri); },
py::arg("E"), py::arg("Vfirst"), py::arg("Vlast"), py::arg("CumOri") = false);
py::class_<TopExp_Explorer>(m, "TopExp_Explorer")
.def(py::init<>())
.def(py::init<const TopoDS_Shape&, TopAbs_ShapeEnum, TopAbs_ShapeEnum>(), py::arg("S"), py::arg("ToFind"),
py::arg("ToAvoid") = TopAbs_SHAPE)
.def("Init", [](TopExp_Explorer& e, const TopoDS_Shape& s, TopAbs_ShapeEnum find, TopAbs_ShapeEnum avoid) { e.Init(s, find, avoid); },
py::arg("S"), py::arg("ToFind"), py::arg("ToAvoid") = TopAbs_SHAPE)
.def("More", &TopExp_Explorer::More)
.def("Next", &TopExp_Explorer::Next)
.def("Current", [](const TopExp_Explorer& e) { return e.Current(); })
.def("Value", [](const TopExp_Explorer& e) { return e.Current(); })
.def("Depth", &TopExp_Explorer::Depth)
.def("ReInit", &TopExp_Explorer::ReInit)
.def("Clear", &TopExp_Explorer::Clear);
// ---- Precision / BRep ---------------------------------------------------------------------------------------
py::class_<Precision>(m, "Precision")
.def_static("Confusion_s", []() { return Precision::Confusion(); })
.def_static("Angular_s", []() { return Precision::Angular(); })
.def_static("Approximation_s", []() { return Precision::Approximation(); })
.def_static("Intersection_s", []() { return Precision::Intersection(); })
.def_static("PConfusion_s", []() { return Precision::PConfusion(); })
.def_static("Infinite_s", []() { return Precision::Infinite(); })
.def_static("IsInfinite_s", [](double v) { return Precision::IsInfinite(v); });
py::class_<BRep_Builder, TopoDS_Builder>(m, "BRep_Builder")
.def(py::init<>())
.def("MakeEdge", [](const BRep_Builder& b, TopoDS_Edge& e) { b.MakeEdge(e); })
.def("MakeFace", [](const BRep_Builder& b, TopoDS_Face& f) { b.MakeFace(f); })
.def("MakeVertex", [](const BRep_Builder& b, TopoDS_Vertex& v) { b.MakeVertex(v); })
.def("MakeVertex", [](const BRep_Builder& b, TopoDS_Vertex& v, const gp_Pnt& p, double tol) { b.MakeVertex(v, p, tol); })
.def("Degenerated", [](const BRep_Builder& b, const TopoDS_Edge& e, bool d) { b.Degenerated(e, d); })
.def("UpdateVertex", [](const BRep_Builder& b, const TopoDS_Vertex& v, const gp_Pnt& p, double tol) { b.UpdateVertex(v, p, tol); })
.def("UpdateEdge", [](const BRep_Builder& b, const TopoDS_Edge& e, double tol) { b.UpdateEdge(e, tol); })
.def("UpdateFace", [](const BRep_Builder& b, const TopoDS_Face& f, double tol) { b.UpdateFace(f, tol); });
py::class_<BRep_Tool>(m, "BRep_Tool")
.def_static("Pnt_s", [](const TopoDS_Vertex& v) { return BRep_Tool::Pnt(v); })
.def_static("Tolerance_s", [](const TopoDS_Vertex& v) { return BRep_Tool::Tolerance(v); })
.def_static("Tolerance_s", [](const TopoDS_Edge& e) { return BRep_Tool::Tolerance(e); })
.def_static("Tolerance_s", [](const TopoDS_Face& f) { return BRep_Tool::Tolerance(f); })
.def_static("Degenerated_s", [](const TopoDS_Edge& e) { return BRep_Tool::Degenerated(e); })
.def_static("IsClosed_s", [](const TopoDS_Shape& s) { return BRep_Tool::IsClosed(s); })
.def_static("IsClosed_s", [](const TopoDS_Edge& e, const TopoDS_Face& f) { return BRep_Tool::IsClosed(e, f); })
.def_static("Range_s", [](const TopoDS_Edge& e, const TopoDS_Face& f) {
double a = 0.0, b = 0.0;
BRep_Tool::Range(e, f, a, b);
return py::make_tuple(a, b);
})
.def_static("Range_s", [](const TopoDS_Edge& e) {
double a = 0.0, b = 0.0;
BRep_Tool::Range(e, a, b);
return py::make_tuple(a, b);
})
.def_static("Surface_s", [](const TopoDS_Face& f) { return BRep_Tool::Surface(f); })
// OCP returns the curve alone: the parameter range is read with Range_s
.def_static("Curve_s", [](const TopoDS_Edge& e, double, double) {
double a = 0.0, b = 0.0;
return BRep_Tool::Curve(e, a, b);
}, py::arg("E"), py::arg("First") = 0.0, py::arg("Last") = 0.0)
.def_static("CurveOnSurface_s", [](const TopoDS_Edge& e, const TopoDS_Face& f, double, double) {
double a = 0.0, b = 0.0;
return BRep_Tool::CurveOnSurface(e, f, a, b);
}, py::arg("E"), py::arg("F"), py::arg("First") = 0.0, py::arg("Last") = 0.0)
.def_static("Continuity_s", [](const TopoDS_Edge& e, const TopoDS_Face& f1, const TopoDS_Face& f2) { return BRep_Tool::Continuity(e, f1, f2); })
.def_static("Triangulation_s", [](const TopoDS_Face& f, TopLoc_Location& loc) { return BRep_Tool::Triangulation(f, loc); })
.def_static("Triangulation_s", [](const TopoDS_Face& f, TopLoc_Location& loc, int purpose) {
return BRep_Tool::Triangulation(f, loc, static_cast<Poly_MeshPurpose>(purpose));
});
}
} // namespace scad::pybind::occt
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,785 @@
// Data exchange and documents: STEPControl_*, STEPCAFControl_*, IFSelect_*, Interface_Static, XSControl_*, XCAF*,
// TDF_*, TDocStd_*, TDataStd_*, TCollection_*, Quantity_*, the Step* data-model classes the SDK touches, BinTools, and
// the stream-taking BRepTools.Write_s / Read_s. Names and call shapes follow OCP (see OCCT_BINDINGS.md).
#include <BRepTools.hxx>
#include <BRep_Builder.hxx>
#include <BinTools.hxx>
#include <BinTools_FormatVersion.hxx>
#include <IFSelect_ReturnStatus.hxx>
#include <IFSelect_WorkSession.hxx>
#include <Interface_InterfaceModel.hxx>
#include <Interface_Static.hxx>
#include <Quantity_Color.hxx>
#include <Quantity_ColorRGBA.hxx>
#include <Quantity_TypeOfColor.hxx>
#include <STEPCAFControl_Reader.hxx>
#include <STEPCAFControl_Writer.hxx>
#include <STEPControl_Reader.hxx>
#include <STEPControl_StepModelType.hxx>
#include <STEPControl_Writer.hxx>
#include <Standard_GUID.hxx>
#include <Standard_Transient.hxx>
#include <StepBasic_ProductDefinition.hxx>
#include <StepData_StepModel.hxx>
#include <StepRepr_CharacterizedDefinition.hxx>
#include <StepRepr_DescriptiveRepresentationItem.hxx>
#include <StepRepr_HArray1OfRepresentationItem.hxx>
#include <StepRepr_ProductDefinitionShape.hxx>
#include <StepRepr_PropertyDefinition.hxx>
#include <StepRepr_PropertyDefinitionRepresentation.hxx>
#include <StepRepr_Representation.hxx>
#include <StepRepr_RepresentationContext.hxx>
#include <StepRepr_RepresentationItem.hxx>
#include <StepRepr_RepresentedDefinition.hxx>
#include <StepShape_ShapeDefinitionRepresentation.hxx>
#include <TCollection_AsciiString.hxx>
#include <TCollection_ExtendedString.hxx>
#include <TCollection_HAsciiString.hxx>
#include <TCollection_HExtendedString.hxx>
#include <TDF_Attribute.hxx>
#include <TDF_Label.hxx>
#include <TDF_LabelSequence.hxx>
#include <TDataStd_Comment.hxx>
#include <TDataStd_GenericExtString.hxx>
#include <TDataStd_Name.hxx>
#include <TDocStd_Document.hxx>
#include <TopLoc_Location.hxx>
#include <TopTools_FormatVersion.hxx>
#include <TopoDS_Shape.hxx>
#include <XCAFApp_Application.hxx>
#include <XCAFDoc_ColorTool.hxx>
#include <XCAFDoc_ColorType.hxx>
#include <XCAFDoc_DocumentTool.hxx>
#include <XCAFDoc_MaterialTool.hxx>
#include <XCAFDoc_ShapeTool.hxx>
#include <XCAFPrs.hxx>
#include <XCAFPrs_DocumentExplorer.hxx>
#include <XCAFPrs_DocumentNode.hxx>
#include <XCAFPrs_IndexedDataMapOfShapeStyle.hxx>
#include <XCAFPrs_Style.hxx>
#include <XSControl_Reader.hxx>
#include <XSControl_WorkSession.hxx>
#include <cstdint>
#include <sstream>
#include <string>
#include "occt.hpp"
namespace scad::pybind::occt {
namespace {
template <class T>
using H = opencascade::handle<T>;
// ---- Python file objects as C++ streams -----------------------------------------------------------------------
// OCP hands a Python `BytesIO` to `std::istream&` / `std::ostream&`; here the stream is drained / filled in one piece.
std::string drain(const py::object& stream) {
py::object data = stream.attr("read")();
if (py::isinstance<py::str>(data)) throw py::type_error("a binary stream (BytesIO) is required");
return py::bytes(data);
}
void fill(const py::object& stream, const std::string& data) { stream.attr("write")(py::bytes(data)); }
// `Cls.name` becomes a static method that tries the new overload first and the ones registered before it next
// (the other agent's file may already define the same name on a class created earlier).
template <class F, class... Extra>
void add_static(py::object cls, const char* name, F&& f, const Extra&... extra) {
py::object previous = py::getattr(cls, name, py::none());
py::cpp_function fn(std::forward<F>(f), py::name(name), py::scope(cls), py::sibling(previous), extra...);
cls.attr(name) = py::staticmethod(fn);
}
// UTF-8 <-> TCollection_ExtendedString (16 bit code units).
TCollection_ExtendedString to_extended(const std::string& s) { return TCollection_ExtendedString(s.c_str(), true); }
py::str from_extended(const TCollection_ExtendedString& s) {
const int n = s.Length();
if (n == 0) return py::str("");
int byteorder = -1; // little endian; flipped below on a big-endian host
const std::uint16_t probe = 1;
if (*reinterpret_cast<const unsigned char*>(&probe) == 0) byteorder = 1;
PyObject* u = PyUnicode_DecodeUTF16(reinterpret_cast<const char*>(s.ToExtString()), static_cast<Py_ssize_t>(n) * 2,
"replace", &byteorder);
if (!u) throw py::error_already_set();
return py::reinterpret_steal<py::str>(u);
}
template <class T>
bool find_attr(const TDF_Label& label, const Standard_GUID& id, H<T> out) {
H<TDF_Attribute> found;
if (!label.FindAttribute(id, found)) return false;
H<T> typed = H<T>::DownCast(found);
if (typed.IsNull()) return false;
// OCP mutates the handle in place; pybind keeps the object pointer apart from the holder, so the attribute the
// caller already holds takes over the state of the one found.
if (!out.IsNull()) out->Restore(typed);
return true;
}
} // namespace
void bind_step(py::module_& m) {
// ---- Standard_Transient: the root of the reference-counted classes below --------------------------------------
if (!py::detail::get_type_info(typeid(Standard_Transient))) {
py::class_<Standard_Transient, H<Standard_Transient>>(m, "Standard_Transient");
}
// ---- enums ---------------------------------------------------------------------------------------------------
py::enum_<IFSelect_ReturnStatus>(m, "IFSelect_ReturnStatus")
.value("IFSelect_RetVoid", IFSelect_RetVoid)
.value("IFSelect_RetDone", IFSelect_RetDone)
.value("IFSelect_RetError", IFSelect_RetError)
.value("IFSelect_RetFail", IFSelect_RetFail)
.value("IFSelect_RetStop", IFSelect_RetStop)
.export_values();
py::enum_<STEPControl_StepModelType>(m, "STEPControl_StepModelType")
.value("STEPControl_AsIs", STEPControl_AsIs)
.value("STEPControl_ManifoldSolidBrep", STEPControl_ManifoldSolidBrep)
.value("STEPControl_BrepWithVoids", STEPControl_BrepWithVoids)
.value("STEPControl_FacetedBrep", STEPControl_FacetedBrep)
.value("STEPControl_FacetedBrepAndBrepWithVoids", STEPControl_FacetedBrepAndBrepWithVoids)
.value("STEPControl_ShellBasedSurfaceModel", STEPControl_ShellBasedSurfaceModel)
.value("STEPControl_GeometricCurveSet", STEPControl_GeometricCurveSet)
.value("STEPControl_Hybrid", STEPControl_Hybrid)
.export_values();
py::enum_<Quantity_TypeOfColor>(m, "Quantity_TypeOfColor")
.value("Quantity_TOC_RGB", Quantity_TOC_RGB)
.value("Quantity_TOC_sRGB", Quantity_TOC_sRGB)
.value("Quantity_TOC_HLS", Quantity_TOC_HLS)
.value("Quantity_TOC_CIELab", Quantity_TOC_CIELab)
.value("Quantity_TOC_CIELch", Quantity_TOC_CIELch)
.export_values();
py::enum_<XCAFDoc_ColorType>(m, "XCAFDoc_ColorType")
.value("XCAFDoc_ColorGen", XCAFDoc_ColorGen)
.value("XCAFDoc_ColorSurf", XCAFDoc_ColorSurf)
.value("XCAFDoc_ColorCurv", XCAFDoc_ColorCurv)
.export_values();
py::enum_<BinTools_FormatVersion>(m, "BinTools_FormatVersion")
.value("BinTools_FormatVersion_VERSION_1", BinTools_FormatVersion_VERSION_1)
.value("BinTools_FormatVersion_VERSION_2", BinTools_FormatVersion_VERSION_2)
.value("BinTools_FormatVersion_VERSION_3", BinTools_FormatVersion_VERSION_3)
.value("BinTools_FormatVersion_VERSION_4", BinTools_FormatVersion_VERSION_4)
.export_values();
m.attr("BinTools_FormatVersion_CURRENT") = m.attr("BinTools_FormatVersion_VERSION_4");
m.attr("BinTools_FormatVersion_LOWER") = m.attr("BinTools_FormatVersion_VERSION_1");
m.attr("BinTools_FormatVersion_UPPER") = m.attr("BinTools_FormatVersion_VERSION_4");
// XCAFPrs_DocumentExplorerFlags: OCP takes plain ints.
m.attr("XCAFPrs_DocumentExplorerFlags_None") = py::int_(static_cast<int>(XCAFPrs_DocumentExplorerFlags_None));
m.attr("XCAFPrs_DocumentExplorerFlags_OnlyLeafNodes") =
py::int_(static_cast<int>(XCAFPrs_DocumentExplorerFlags_OnlyLeafNodes));
m.attr("XCAFPrs_DocumentExplorerFlags_NoStyle") = py::int_(static_cast<int>(XCAFPrs_DocumentExplorerFlags_NoStyle));
// ---- TCollection ---------------------------------------------------------------------------------------------
py::class_<TCollection_AsciiString>(m, "TCollection_AsciiString")
.def(py::init<>())
.def(py::init([](const std::string& s) { return TCollection_AsciiString(s.c_str()); }))
.def("ToCString", [](const TCollection_AsciiString& s) { return std::string(s.ToCString()); })
.def("Length", &TCollection_AsciiString::Length)
.def("IsEmpty", &TCollection_AsciiString::IsEmpty)
.def("__str__", [](const TCollection_AsciiString& s) { return std::string(s.ToCString()); })
.def("__eq__", [](const TCollection_AsciiString& a, const TCollection_AsciiString& b) { return a.IsEqual(b); },
py::is_operator())
.def("__hash__", [](const TCollection_AsciiString& s) { return std::hash<TCollection_AsciiString>{}(s); });
py::class_<TCollection_ExtendedString>(m, "TCollection_ExtendedString")
.def(py::init<>())
.def(py::init([](const std::string& s) { return to_extended(s); }))
.def("ToExtString", [](const TCollection_ExtendedString& s) { return from_extended(s); })
.def("Length", &TCollection_ExtendedString::Length)
.def("IsEmpty", &TCollection_ExtendedString::IsEmpty)
.def("__str__", [](const TCollection_ExtendedString& s) { return from_extended(s); })
.def("__eq__", [](const TCollection_ExtendedString& a, const TCollection_ExtendedString& b) { return a.IsEqual(b); },
py::is_operator());
py::class_<TCollection_HAsciiString, H<TCollection_HAsciiString>, Standard_Transient>(m, "TCollection_HAsciiString")
.def(py::init([]() { return new TCollection_HAsciiString(); }))
.def(py::init([](const std::string& s) { return new TCollection_HAsciiString(s.c_str()); }))
.def("ToCString", [](const TCollection_HAsciiString& s) { return std::string(s.ToCString()); })
.def("Length", &TCollection_HAsciiString::Length)
.def("IsEmpty", &TCollection_HAsciiString::IsEmpty)
.def("String", [](const TCollection_HAsciiString& s) { return s.String(); });
py::class_<TCollection_HExtendedString, H<TCollection_HExtendedString>, Standard_Transient>(m, "TCollection_HExtendedString")
.def(py::init([]() { return new TCollection_HExtendedString(); }))
.def(py::init([](const std::string& s) { return new TCollection_HExtendedString(to_extended(s)); }))
.def("ToExtString", [](const TCollection_HExtendedString& s) { return from_extended(s.String()); })
.def("Length", &TCollection_HExtendedString::Length)
.def("IsEmpty", &TCollection_HExtendedString::IsEmpty)
.def("String", [](const TCollection_HExtendedString& s) { return s.String(); });
// ---- Quantity ------------------------------------------------------------------------------------------------
py::class_<Quantity_Color>(m, "Quantity_Color")
.def(py::init<>())
.def(py::init<double, double, double, Quantity_TypeOfColor>(), py::arg("theC1"), py::arg("theC2"), py::arg("theC3"),
py::arg("theType"))
.def("Red", &Quantity_Color::Red)
.def("Green", &Quantity_Color::Green)
.def("Blue", &Quantity_Color::Blue)
.def("Hue", &Quantity_Color::Hue)
.def("Light", &Quantity_Color::Light)
.def("IsDifferent", &Quantity_Color::IsDifferent)
.def("IsEqual", &Quantity_Color::IsEqual)
.def("SetValues", [](Quantity_Color& c, double a, double b, double d, Quantity_TypeOfColor t) { c.SetValues(a, b, d, t); }, py::arg("theC1"), py::arg("theC2"), py::arg("theC3"), py::arg("theType"))
.def("Values",
[](const Quantity_Color& c, Quantity_TypeOfColor type) {
double a, b, d;
c.Values(a, b, d, type);
return py::make_tuple(a, b, d);
},
py::arg("theType"))
.def("__eq__", [](const Quantity_Color& a, const Quantity_Color& b) { return a.IsEqual(b); }, py::is_operator());
py::class_<Quantity_ColorRGBA>(m, "Quantity_ColorRGBA")
.def(py::init<>())
.def(py::init<const Quantity_Color&>())
.def(py::init<const Quantity_Color&, float>())
.def(py::init<float, float, float, float>())
.def("GetRGB", [](const Quantity_ColorRGBA& c) { return c.GetRGB(); })
.def("SetRGB", [](Quantity_ColorRGBA& c, const Quantity_Color& v) { c.SetRGB(v); })
.def("Alpha", &Quantity_ColorRGBA::Alpha)
.def("SetAlpha", &Quantity_ColorRGBA::SetAlpha)
.def("IsEqual", &Quantity_ColorRGBA::IsEqual)
.def("__eq__", [](const Quantity_ColorRGBA& a, const Quantity_ColorRGBA& b) { return a.IsEqual(b); }, py::is_operator());
// ---- Standard_GUID, TDF, TDataStd, TDocStd -------------------------------------------------------------------
py::class_<Standard_GUID>(m, "Standard_GUID")
.def(py::init<>())
.def(py::init([](const std::string& s) { return Standard_GUID(s.c_str()); }))
.def("ToCString",
[](const Standard_GUID& g) {
Standard_Character buf[Standard_GUID_SIZE_ALLOC];
g.ToCString(buf);
return std::string(buf);
})
.def("__str__",
[](const Standard_GUID& g) {
Standard_Character buf[Standard_GUID_SIZE_ALLOC];
g.ToCString(buf);
return std::string(buf);
})
.def("IsSame", &Standard_GUID::IsSame)
.def("__eq__", [](const Standard_GUID& a, const Standard_GUID& b) { return a == b; }, py::is_operator())
.def("__hash__", [](const Standard_GUID& g) { Standard_Character buf[Standard_GUID_SIZE_ALLOC];
g.ToCString(buf);
return std::hash<std::string>{}(std::string(buf)); });
py::class_<TDF_Attribute, H<TDF_Attribute>, Standard_Transient>(m, "TDF_Attribute")
.def("ID", [](const TDF_Attribute& a) { return a.ID(); })
.def("Label", [](const TDF_Attribute& a) { return a.Label(); })
.def("IsValid", &TDF_Attribute::IsValid);
py::class_<TDF_Label>(m, "TDF_Label")
.def(py::init<>())
.def("IsNull", &TDF_Label::IsNull)
.def("IsRoot", &TDF_Label::IsRoot)
.def("Tag", &TDF_Label::Tag)
.def("Depth", &TDF_Label::Depth)
.def("HasAttribute", &TDF_Label::HasAttribute)
.def("NbAttributes", &TDF_Label::NbAttributes)
.def("HasChild", &TDF_Label::HasChild)
.def("NbChildren", &TDF_Label::NbChildren)
.def("Father", &TDF_Label::Father)
.def("IsEqual", &TDF_Label::IsEqual)
.def("IsDifferent", &TDF_Label::IsDifferent)
.def("FindChild", &TDF_Label::FindChild, py::arg("aTag"), py::arg("create") = true)
.def("FindAttribute", &find_attr<TDataStd_Name>, py::arg("anID"), py::arg("anAttribute"))
.def("FindAttribute", &find_attr<TDataStd_Comment>, py::arg("anID"), py::arg("anAttribute"))
.def("__eq__", [](const TDF_Label& a, const TDF_Label& b) { return a.IsEqual(b); }, py::is_operator())
.def("__hash__", [](const TDF_Label& l) { return std::hash<TDF_Label>{}(l); });
py::class_<TDF_LabelSequence>(m, "TDF_LabelSequence")
.def(py::init<>())
.def("Length", &TDF_LabelSequence::Length)
.def("Size", &TDF_LabelSequence::Size)
.def("IsEmpty", &TDF_LabelSequence::IsEmpty)
.def("Clear", [](TDF_LabelSequence& s) { s.Clear(); })
.def("Append", [](TDF_LabelSequence& s, const TDF_Label& l) { s.Append(l); })
.def("Prepend", [](TDF_LabelSequence& s, const TDF_Label& l) { s.Prepend(l); })
.def("Value", [](const TDF_LabelSequence& s, int i) {
if (i < 1 || i > s.Length()) throw std::out_of_range("TDF_LabelSequence::Value");
return s.Value(i);
})
.def("First", [](const TDF_LabelSequence& s) { return s.First(); })
.def("Last", [](const TDF_LabelSequence& s) { return s.Last(); })
.def("__len__", &TDF_LabelSequence::Length);
py::class_<TDataStd_GenericExtString, H<TDataStd_GenericExtString>, TDF_Attribute>(m, "TDataStd_GenericExtString")
.def("Get", [](const TDataStd_GenericExtString& a) { return a.Get(); })
.def("SetID", [](TDataStd_GenericExtString& a, const Standard_GUID& id) { a.SetID(id); });
py::class_<TDataStd_Name, H<TDataStd_Name>, TDataStd_GenericExtString>(m, "TDataStd_Name")
.def(py::init([]() { return new TDataStd_Name(); }))
.def_static("GetID_s", []() { return TDataStd_Name::GetID(); })
.def_static("Set_s", [](const TDF_Label& l, const TCollection_ExtendedString& s) { return TDataStd_Name::Set(l, s); })
.def_static("Set_s", [](const TDF_Label& l, const Standard_GUID& g, const TCollection_ExtendedString& s) {
return TDataStd_Name::Set(l, g, s);
});
py::class_<TDataStd_Comment, H<TDataStd_Comment>, TDataStd_GenericExtString>(m, "TDataStd_Comment")
.def(py::init([]() { return new TDataStd_Comment(); }))
.def_static("GetID_s", []() { return TDataStd_Comment::GetID(); })
.def_static("Set_s", [](const TDF_Label& l, const TCollection_ExtendedString& s) { return TDataStd_Comment::Set(l, s); });
;
py::class_<TDocStd_Document, H<TDocStd_Document>, Standard_Transient>(m, "TDocStd_Document")
.def(py::init([](const TCollection_ExtendedString& format) { return new TDocStd_Document(format); }))
.def("Main", [](const TDocStd_Document& d) { return d.Main(); })
.def("IsEmpty", &TDocStd_Document::IsEmpty)
.def("IsValid", &TDocStd_Document::IsValid);
// ---- XCAF ----------------------------------------------------------------------------------------------------
py::class_<XCAFApp_Application, H<XCAFApp_Application>, Standard_Transient>(m, "XCAFApp_Application")
.def_static("GetApplication_s", []() { return XCAFApp_Application::GetApplication(); })
.def("InitDocument", [](const XCAFApp_Application& a, const H<TDocStd_Document>& d) { a.InitDocument(d); })
// OCP: NewDocument(format, doc) fills `doc`'s handle; a pybind object cannot change its pointer, so the new
// document is returned instead (the one-argument form).
.def("NewDocument", [](XCAFApp_Application& a, const TCollection_ExtendedString& format) {
H<TDocStd_Document> doc;
a.NewDocument(format, doc);
return doc;
});
py::class_<XCAFDoc_ShapeTool, H<XCAFDoc_ShapeTool>, TDF_Attribute>(m, "XCAFDoc_ShapeTool")
.def("AddShape", &XCAFDoc_ShapeTool::AddShape, py::arg("S"), py::arg("makeAssembly") = true,
py::arg("makePrototype") = true)
.def("GetFreeShapes", [](const XCAFDoc_ShapeTool& t, TDF_LabelSequence& out) { t.GetFreeShapes(out); })
.def("GetShapes", [](const XCAFDoc_ShapeTool& t, TDF_LabelSequence& out) { t.GetShapes(out); })
.def("GetOneShape", [](const XCAFDoc_ShapeTool& t) { return t.GetOneShape(); })
.def_static("GetShape_s", [](const TDF_Label& l) { return XCAFDoc_ShapeTool::GetShape(l); })
.def_static("GetShape_s", [](const TDF_Label& l, TopoDS_Shape& s) { return XCAFDoc_ShapeTool::GetShape(l, s); })
.def("AddComponent",
[](XCAFDoc_ShapeTool& t, const TDF_Label& assembly, const TDF_Label& comp, const TopLoc_Location& loc) {
return t.AddComponent(assembly, comp, loc);
})
.def("AddComponent",
[](XCAFDoc_ShapeTool& t, const TDF_Label& assembly, const TopoDS_Shape& comp, bool expand) {
return t.AddComponent(assembly, comp, expand);
},
py::arg("assembly"), py::arg("comp"), py::arg("expand") = false)
.def("UpdateAssemblies", &XCAFDoc_ShapeTool::UpdateAssemblies)
.def("ComputeShapes", &XCAFDoc_ShapeTool::ComputeShapes)
.def_static("IsFree_s", [](const TDF_Label& l) { return XCAFDoc_ShapeTool::IsFree(l); })
.def_static("IsAssembly_s", [](const TDF_Label& l) { return XCAFDoc_ShapeTool::IsAssembly(l); })
.def_static("IsComponent_s", [](const TDF_Label& l) { return XCAFDoc_ShapeTool::IsComponent(l); })
.def_static("IsSimpleShape_s", [](const TDF_Label& l) { return XCAFDoc_ShapeTool::IsSimpleShape(l); })
.def_static("IsReference_s", [](const TDF_Label& l) { return XCAFDoc_ShapeTool::IsReference(l); })
.def_static("IsShape_s", [](const TDF_Label& l) { return XCAFDoc_ShapeTool::IsShape(l); })
.def("IsTopLevel", [](const XCAFDoc_ShapeTool& t, const TDF_Label& l) { return t.IsTopLevel(l); });
py::class_<XCAFDoc_ColorTool, H<XCAFDoc_ColorTool>, TDF_Attribute>(m, "XCAFDoc_ColorTool")
.def("SetColor",
[](XCAFDoc_ColorTool& t, const TDF_Label& l, const Quantity_Color& c, XCAFDoc_ColorType type) { t.SetColor(l, c, type); })
.def("SetColor",
[](XCAFDoc_ColorTool& t, const TDF_Label& l, const Quantity_ColorRGBA& c, XCAFDoc_ColorType type) { t.SetColor(l, c, type); })
.def("SetColor",
[](XCAFDoc_ColorTool& t, const TDF_Label& l, const TDF_Label& color, XCAFDoc_ColorType type) { t.SetColor(l, color, type); })
.def("SetColor",
[](XCAFDoc_ColorTool& t, const TopoDS_Shape& s, const Quantity_Color& c, XCAFDoc_ColorType type) { return t.SetColor(s, c, type); })
.def("SetColor",
[](XCAFDoc_ColorTool& t, const TopoDS_Shape& s, const Quantity_ColorRGBA& c, XCAFDoc_ColorType type) { return t.SetColor(s, c, type); })
.def_static("GetColor_s", [](const TDF_Label& l, Quantity_Color& c) { return XCAFDoc_ColorTool::GetColor(l, c); })
.def_static("GetColor_s", [](const TDF_Label& l, Quantity_ColorRGBA& c) { return XCAFDoc_ColorTool::GetColor(l, c); })
.def_static("GetColor_s",
[](const TDF_Label& l, XCAFDoc_ColorType type, Quantity_Color& c) { return XCAFDoc_ColorTool::GetColor(l, type, c); })
.def_static("GetColor_s",
[](const TDF_Label& l, XCAFDoc_ColorType type, Quantity_ColorRGBA& c) { return XCAFDoc_ColorTool::GetColor(l, type, c); })
.def("GetColor",
[](XCAFDoc_ColorTool& t, const TopoDS_Shape& s, XCAFDoc_ColorType type, Quantity_Color& c) { return t.GetColor(s, type, c); })
.def("GetColor",
[](XCAFDoc_ColorTool& t, const TopoDS_Shape& s, XCAFDoc_ColorType type, Quantity_ColorRGBA& c) { return t.GetColor(s, type, c); })
.def("IsSet", [](XCAFDoc_ColorTool& t, const TDF_Label& l, XCAFDoc_ColorType type) { return t.IsSet(l, type); })
.def("AddColor", [](XCAFDoc_ColorTool& t, const Quantity_Color& c) { return t.AddColor(c); })
.def("AddColor", [](XCAFDoc_ColorTool& t, const Quantity_ColorRGBA& c) { return t.AddColor(c); });
py::class_<XCAFDoc_MaterialTool, H<XCAFDoc_MaterialTool>, TDF_Attribute>(m, "XCAFDoc_MaterialTool")
.def("AddMaterial",
[](XCAFDoc_MaterialTool& t, const H<TCollection_HAsciiString>& name, const H<TCollection_HAsciiString>& desc, double density,
const H<TCollection_HAsciiString>& dname, const H<TCollection_HAsciiString>& dvt) {
return t.AddMaterial(name, desc, density, dname, dvt);
})
.def("SetMaterial", [](XCAFDoc_MaterialTool& t, const TDF_Label& l, const TDF_Label& mat) { t.SetMaterial(l, mat); })
.def("SetMaterial",
[](XCAFDoc_MaterialTool& t, const TDF_Label& l, const H<TCollection_HAsciiString>& name,
const H<TCollection_HAsciiString>& desc, double density, const H<TCollection_HAsciiString>& dname,
const H<TCollection_HAsciiString>& dvt) { t.SetMaterial(l, name, desc, density, dname, dvt); });
py::class_<XCAFDoc_DocumentTool>(m, "XCAFDoc_DocumentTool")
.def_static("ShapeTool_s", [](const TDF_Label& l) { return XCAFDoc_DocumentTool::ShapeTool(l); })
.def_static("ColorTool_s", [](const TDF_Label& l) { return XCAFDoc_DocumentTool::ColorTool(l); })
.def_static("MaterialTool_s", [](const TDF_Label& l) { return XCAFDoc_DocumentTool::MaterialTool(l); });
py::class_<XCAFPrs_Style>(m, "XCAFPrs_Style")
.def(py::init<>())
.def("IsEmpty", &XCAFPrs_Style::IsEmpty)
.def("IsVisible", &XCAFPrs_Style::IsVisible)
.def("SetVisibility", &XCAFPrs_Style::SetVisibility)
.def("IsSetColorSurf", &XCAFPrs_Style::IsSetColorSurf)
.def("GetColorSurf", [](const XCAFPrs_Style& s) { return s.GetColorSurf(); })
.def("GetColorSurfRGBA", [](const XCAFPrs_Style& s) { return s.GetColorSurfRGBA(); })
.def("SetColorSurf", [](XCAFPrs_Style& s, const Quantity_Color& c) { s.SetColorSurf(c); })
.def("SetColorSurf", [](XCAFPrs_Style& s, const Quantity_ColorRGBA& c) { s.SetColorSurf(c); })
.def("UnSetColorSurf", &XCAFPrs_Style::UnSetColorSurf)
.def("IsSetColorCurv", &XCAFPrs_Style::IsSetColorCurv)
.def("GetColorCurv", [](const XCAFPrs_Style& s) { return s.GetColorCurv(); })
.def("SetColorCurv", &XCAFPrs_Style::SetColorCurv)
.def("UnSetColorCurv", &XCAFPrs_Style::UnSetColorCurv)
.def("IsEqual", &XCAFPrs_Style::IsEqual)
.def("__eq__", [](const XCAFPrs_Style& a, const XCAFPrs_Style& b) { return a.IsEqual(b); }, py::is_operator());
py::class_<XCAFPrs_IndexedDataMapOfShapeStyle>(m, "XCAFPrs_IndexedDataMapOfShapeStyle")
.def(py::init<>())
.def("Extent", &XCAFPrs_IndexedDataMapOfShapeStyle::Extent)
.def("Size", &XCAFPrs_IndexedDataMapOfShapeStyle::Size)
.def("IsEmpty", &XCAFPrs_IndexedDataMapOfShapeStyle::IsEmpty)
.def("Clear", [](XCAFPrs_IndexedDataMapOfShapeStyle& d) { d.Clear(); })
.def("Add", [](XCAFPrs_IndexedDataMapOfShapeStyle& d, const TopoDS_Shape& k, const XCAFPrs_Style& v) { return d.Add(k, v); })
.def("Contains", [](const XCAFPrs_IndexedDataMapOfShapeStyle& d, const TopoDS_Shape& k) { return d.Contains(k); })
.def("FindIndex", [](const XCAFPrs_IndexedDataMapOfShapeStyle& d, const TopoDS_Shape& k) { return d.FindIndex(k); })
.def("FindKey",
[](const XCAFPrs_IndexedDataMapOfShapeStyle& d, int i) {
if (i < 1 || i > d.Extent()) throw std::out_of_range("XCAFPrs_IndexedDataMapOfShapeStyle::FindKey");
return shape_to_python(d.FindKey(i));
})
.def("FindFromIndex",
[](const XCAFPrs_IndexedDataMapOfShapeStyle& d, int i) {
if (i < 1 || i > d.Extent()) throw std::out_of_range("XCAFPrs_IndexedDataMapOfShapeStyle::FindFromIndex");
return d.FindFromIndex(i);
})
.def("FindFromKey",
[](const XCAFPrs_IndexedDataMapOfShapeStyle& d, const TopoDS_Shape& k) {
if (!d.Contains(k)) throw std::out_of_range("XCAFPrs_IndexedDataMapOfShapeStyle::FindFromKey");
return d.FindFromKey(k);
});
py::class_<XCAFPrs_DocumentNode>(m, "XCAFPrs_DocumentNode")
.def(py::init<>())
.def_readonly("Id", &XCAFPrs_DocumentNode::Id)
.def_readonly("Label", &XCAFPrs_DocumentNode::Label)
.def_readonly("RefLabel", &XCAFPrs_DocumentNode::RefLabel)
.def_readonly("Style", &XCAFPrs_DocumentNode::Style)
.def_readonly("Location", &XCAFPrs_DocumentNode::Location)
.def_readonly("LocalTrsf", &XCAFPrs_DocumentNode::LocalTrsf)
.def_readonly("IsAssembly", &XCAFPrs_DocumentNode::IsAssembly);
py::class_<XCAFPrs_DocumentExplorer>(m, "XCAFPrs_DocumentExplorer")
.def(py::init<>())
.def(py::init([](const H<TDocStd_Document>& d, int flags, const XCAFPrs_Style& style) {
return new XCAFPrs_DocumentExplorer(d, static_cast<XCAFPrs_DocumentExplorerFlags>(flags), style);
}),
py::arg("theDocument"), py::arg("theFlags"), py::arg("theDefStyle") = XCAFPrs_Style())
.def(py::init([](const H<TDocStd_Document>& d, const TDF_LabelSequence& roots, int flags, const XCAFPrs_Style& style) {
return new XCAFPrs_DocumentExplorer(d, roots, static_cast<XCAFPrs_DocumentExplorerFlags>(flags), style);
}),
py::arg("theDocument"), py::arg("theRoots"), py::arg("theFlags"), py::arg("theDefStyle") = XCAFPrs_Style())
.def("Init",
[](XCAFPrs_DocumentExplorer& e, const H<TDocStd_Document>& d, const TDF_LabelSequence& roots, int flags,
const XCAFPrs_Style& style) { e.Init(d, roots, static_cast<XCAFPrs_DocumentExplorerFlags>(flags), style); },
py::arg("theDocument"), py::arg("theRoots"), py::arg("theFlags"), py::arg("theDefStyle") = XCAFPrs_Style())
.def("Init",
[](XCAFPrs_DocumentExplorer& e, const H<TDocStd_Document>& d, const TDF_Label& root, int flags,
const XCAFPrs_Style& style) { e.Init(d, root, static_cast<XCAFPrs_DocumentExplorerFlags>(flags), style); },
py::arg("theDocument"), py::arg("theRoot"), py::arg("theFlags"), py::arg("theDefStyle") = XCAFPrs_Style())
.def("More", &XCAFPrs_DocumentExplorer::More)
.def("Next", &XCAFPrs_DocumentExplorer::Next)
.def("CurrentDepth", &XCAFPrs_DocumentExplorer::CurrentDepth)
.def("Current", [](const XCAFPrs_DocumentExplorer& e) { return e.Current(); })
.def("Current", [](const XCAFPrs_DocumentExplorer& e, int depth) { return e.Current(depth); }, py::arg("theDepth"))
.def_static("DefineChildId_s",
[](const TDF_Label& l, const TCollection_AsciiString& parent) {
return XCAFPrs_DocumentExplorer::DefineChildId(l, parent);
})
.def_static("FindShapeFromPathId_s", [](const H<TDocStd_Document>& d, const TCollection_AsciiString& path) {
return XCAFPrs_DocumentExplorer::FindShapeFromPathId(d, path);
});
py::class_<XCAFPrs>(m, "XCAFPrs")
.def_static("CollectStyleSettings_s",
[](const TDF_Label& l, const TopLoc_Location& loc, XCAFPrs_IndexedDataMapOfShapeStyle& settings) {
XCAFPrs::CollectStyleSettings(l, loc, settings);
});
// ---- IFSelect / XSControl / Interface_Static -----------------------------------------------------------------
py::class_<Interface_InterfaceModel, H<Interface_InterfaceModel>, Standard_Transient>(m, "Interface_InterfaceModel")
.def("NbEntities", &Interface_InterfaceModel::NbEntities)
.def("Entity", [](const Interface_InterfaceModel& mo, int i) {
if (i < 1 || i > mo.NbEntities()) throw std::out_of_range("Interface_InterfaceModel::Entity");
return mo.Value(i);
})
.def("AddEntity", [](Interface_InterfaceModel& mo, const H<Standard_Transient>& e) { mo.AddEntity(e); })
.def("AddWithRefs",
[](Interface_InterfaceModel& mo, const H<Standard_Transient>& e, int level, bool listall) {
mo.AddWithRefs(e, level, listall);
},
py::arg("anent"), py::arg("level") = 0, py::arg("listall") = false)
.def("Clear", &Interface_InterfaceModel::Clear);
py::class_<StepData_StepModel, H<StepData_StepModel>, Interface_InterfaceModel>(m, "StepData_StepModel");
py::class_<IFSelect_WorkSession, H<IFSelect_WorkSession>, Standard_Transient>(m, "IFSelect_WorkSession")
.def("Model", [](const IFSelect_WorkSession& w) { return w.Model(); })
.def("HasModel", [](const IFSelect_WorkSession& w) { return !w.Model().IsNull(); });
py::class_<XSControl_WorkSession, H<XSControl_WorkSession>, IFSelect_WorkSession>(m, "XSControl_WorkSession");
py::class_<Interface_Static>(m, "Interface_Static")
.def_static("CVal_s", [](const char* name) { return Interface_Static::CVal(name); })
.def_static("SetCVal_s", [](const char* name, const char* v) { return Interface_Static::SetCVal(name, v); })
.def_static("IVal_s", [](const char* name) { return Interface_Static::IVal(name); })
.def_static("SetIVal_s", [](const char* name, int v) { return Interface_Static::SetIVal(name, v); })
.def_static("RVal_s", [](const char* name) { return Interface_Static::RVal(name); })
.def_static("SetRVal_s", [](const char* name, double v) { return Interface_Static::SetRVal(name, v); })
.def_static("IsPresent_s", [](const char* name) { return Interface_Static::IsPresent(name); })
.def_static("IsSet_s", [](const char* name, bool proper) { return Interface_Static::IsSet(name, proper); }, py::arg("name"),
py::arg("proper") = false)
.def_static("Init_s",
[](const char* family, const char* name, char type, const char* init) {
return Interface_Static::Init(family, name, type, init);
});
// ---- STEP readers / writers ----------------------------------------------------------------------------------
py::class_<XSControl_Reader>(m, "XSControl_Reader")
.def("ReadFile", [](XSControl_Reader& r, const char* f) { return r.ReadFile(f); })
.def("NbRootsForTransfer", [](XSControl_Reader& r) { return r.NbRootsForTransfer(); })
.def("TransferOneRoot", [](XSControl_Reader& r, int n) { return r.TransferOneRoot(n); }, py::arg("num") = 1)
.def("TransferOne", [](XSControl_Reader& r, int n) { return r.TransferOne(n); })
.def("TransferRoots", [](XSControl_Reader& r) { return r.TransferRoots(); })
.def("NbShapes", &XSControl_Reader::NbShapes)
.def("Shape", [](XSControl_Reader& r, int n) { return r.Shape(n); }, py::arg("num") = 1)
.def("OneShape", [](XSControl_Reader& r) { return r.OneShape(); })
.def("ClearShapes", &XSControl_Reader::ClearShapes)
.def("WS", [](const XSControl_Reader& r) { return r.WS(); })
.def("Model", [](const XSControl_Reader& r) { return r.Model(); });
py::class_<STEPControl_Reader, XSControl_Reader>(m, "STEPControl_Reader")
.def(py::init<>())
.def("ReadStream",
[](STEPControl_Reader& r, const std::string& name, const py::object& stream) {
std::istringstream in(drain(stream), std::ios::in | std::ios::binary);
return r.ReadStream(name.c_str(), in);
})
.def("StepModel", [](const STEPControl_Reader& r) { return r.StepModel(); });
py::class_<STEPControl_Writer>(m, "STEPControl_Writer")
.def(py::init<>())
.def("Transfer", [](STEPControl_Writer& w, const TopoDS_Shape& s, STEPControl_StepModelType mode,
bool compgraph) { return w.Transfer(s, mode, compgraph); },
py::arg("sh"), py::arg("mode"), py::arg("compgraph") = true)
.def("Write", [](STEPControl_Writer& w, const char* f) { return w.Write(f); })
.def("SetTolerance", &STEPControl_Writer::SetTolerance)
.def("UnsetTolerance", &STEPControl_Writer::UnsetTolerance)
.def("WS", [](const STEPControl_Writer& w) { return w.WS(); })
.def("Model", [](STEPControl_Writer& w, bool newone) { return w.Model(newone); }, py::arg("newone") = false);
py::class_<STEPCAFControl_Reader>(m, "STEPCAFControl_Reader")
.def(py::init<>())
.def("ReadFile", [](STEPCAFControl_Reader& r, const char* f) { return r.ReadFile(f); })
.def("ReadStream",
[](STEPCAFControl_Reader& r, const std::string& name, const py::object& stream) {
std::istringstream in(drain(stream), std::ios::in | std::ios::binary);
return r.ReadStream(name.c_str(), in);
})
.def("NbRootsForTransfer", [](STEPCAFControl_Reader& r) { return r.NbRootsForTransfer(); })
.def("Transfer", [](STEPCAFControl_Reader& r, const H<TDocStd_Document>& d) {
H<TDocStd_Document> doc = d;
return r.Transfer(doc);
})
.def("Perform", [](STEPCAFControl_Reader& r, const std::string& f, const H<TDocStd_Document>& d) {
H<TDocStd_Document> doc = d;
return r.Perform(f.c_str(), doc);
})
.def("ChangeReader", [](STEPCAFControl_Reader& r) -> STEPControl_Reader& { return r.ChangeReader(); },
py::return_value_policy::reference_internal)
.def("Reader", [](const STEPCAFControl_Reader& r) -> const STEPControl_Reader& { return r.Reader(); },
py::return_value_policy::reference_internal)
#define SCAD_MODE(NAME) \
.def("Set" #NAME "Mode", [](STEPCAFControl_Reader& r, bool v) { r.Set##NAME##Mode(v); }) \
.def("Get" #NAME "Mode", [](const STEPCAFControl_Reader& r) { return r.Get##NAME##Mode(); })
SCAD_MODE(Color) SCAD_MODE(Name) SCAD_MODE(Layer) SCAD_MODE(Props) SCAD_MODE(Meta) SCAD_MODE(ProductMeta)
SCAD_MODE(SHUO) SCAD_MODE(GDT) SCAD_MODE(Mat) SCAD_MODE(View)
#undef SCAD_MODE
;
py::class_<STEPCAFControl_Writer>(m, "STEPCAFControl_Writer")
.def(py::init<>())
.def("Transfer",
[](STEPCAFControl_Writer& w, const H<TDocStd_Document>& d, STEPControl_StepModelType mode) { return w.Transfer(d, mode); },
py::arg("doc"), py::arg("mode") = STEPControl_AsIs)
.def("Transfer",
[](STEPCAFControl_Writer& w, const TDF_Label& l, STEPControl_StepModelType mode) { return w.Transfer(l, mode); },
py::arg("L"), py::arg("mode") = STEPControl_AsIs)
.def("Transfer",
[](STEPCAFControl_Writer& w, const TDF_LabelSequence& l, STEPControl_StepModelType mode) { return w.Transfer(l, mode); },
py::arg("labels"), py::arg("mode") = STEPControl_AsIs)
.def("Write", [](STEPCAFControl_Writer& w, const char* f) { return w.Write(f); })
.def("Perform",
[](STEPCAFControl_Writer& w, const H<TDocStd_Document>& d, const std::string& f) { return w.Perform(d, f.c_str()); })
.def("ChangeWriter", [](STEPCAFControl_Writer& w) -> STEPControl_Writer& { return w.ChangeWriter(); },
py::return_value_policy::reference_internal)
.def("Writer", [](const STEPCAFControl_Writer& w) -> const STEPControl_Writer& { return w.Writer(); },
py::return_value_policy::reference_internal)
#define SCAD_MODE(NAME) \
.def("Set" #NAME "Mode", [](STEPCAFControl_Writer& w, bool v) { w.Set##NAME##Mode(v); }) \
.def("Get" #NAME "Mode", [](const STEPCAFControl_Writer& w) { return w.Get##NAME##Mode(); })
SCAD_MODE(Color) SCAD_MODE(Name) SCAD_MODE(Layer) SCAD_MODE(Props) SCAD_MODE(SHUO) SCAD_MODE(DimTol)
SCAD_MODE(Material)
#undef SCAD_MODE
;
// ---- Step* data model ----------------------------------------------------------------------------------------
py::class_<StepRepr_RepresentationContext, H<StepRepr_RepresentationContext>, Standard_Transient>(
m, "StepRepr_RepresentationContext");
py::class_<StepRepr_RepresentationItem, H<StepRepr_RepresentationItem>, Standard_Transient>(m, "StepRepr_RepresentationItem")
.def("Name", [](const StepRepr_RepresentationItem& i) { return i.Name(); })
.def("SetName", [](StepRepr_RepresentationItem& i, const H<TCollection_HAsciiString>& n) { i.SetName(n); });
py::class_<StepRepr_DescriptiveRepresentationItem, H<StepRepr_DescriptiveRepresentationItem>, StepRepr_RepresentationItem>(
m, "StepRepr_DescriptiveRepresentationItem")
.def(py::init([]() { return new StepRepr_DescriptiveRepresentationItem(); }))
.def("Init",
[](StepRepr_DescriptiveRepresentationItem& i, const H<TCollection_HAsciiString>& name,
const H<TCollection_HAsciiString>& description) { i.Init(name, description); })
.def("Description", [](const StepRepr_DescriptiveRepresentationItem& i) { return i.Description(); })
.def("SetDescription",
[](StepRepr_DescriptiveRepresentationItem& i, const H<TCollection_HAsciiString>& d) { i.SetDescription(d); });
py::class_<StepRepr_HArray1OfRepresentationItem, H<StepRepr_HArray1OfRepresentationItem>, Standard_Transient>(
m, "StepRepr_HArray1OfRepresentationItem")
.def(py::init([](int lo, int up) { return new StepRepr_HArray1OfRepresentationItem(lo, up); }))
.def("Length", [](const StepRepr_HArray1OfRepresentationItem& a) { return a.Length(); })
.def("Lower", [](const StepRepr_HArray1OfRepresentationItem& a) { return a.Lower(); })
.def("Upper", [](const StepRepr_HArray1OfRepresentationItem& a) { return a.Upper(); })
.def("SetValue",
[](StepRepr_HArray1OfRepresentationItem& a, int i, const H<StepRepr_RepresentationItem>& v) {
if (i < a.Lower() || i > a.Upper()) throw std::out_of_range("StepRepr_HArray1OfRepresentationItem::SetValue");
a.SetValue(i, v);
})
.def("Value", [](const StepRepr_HArray1OfRepresentationItem& a, int i) {
if (i < a.Lower() || i > a.Upper()) throw std::out_of_range("StepRepr_HArray1OfRepresentationItem::Value");
return a.Value(i);
});
py::class_<StepRepr_Representation, H<StepRepr_Representation>, Standard_Transient>(m, "StepRepr_Representation")
.def(py::init([]() { return new StepRepr_Representation(); }))
.def("Init",
[](StepRepr_Representation& r, const H<TCollection_HAsciiString>& name, const H<StepRepr_HArray1OfRepresentationItem>& items,
const H<StepRepr_RepresentationContext>& ctx) { r.Init(name, items, ctx); })
.def("Name", [](const StepRepr_Representation& r) { return r.Name(); })
.def("Items", [](const StepRepr_Representation& r) { return r.Items(); })
.def("ContextOfItems", [](const StepRepr_Representation& r) { return r.ContextOfItems(); });
py::class_<StepRepr_CharacterizedDefinition>(m, "StepRepr_CharacterizedDefinition")
.def(py::init<>())
.def("SetValue", [](StepRepr_CharacterizedDefinition& d, const H<Standard_Transient>& v) { d.SetValue(v); })
.def("Value", [](const StepRepr_CharacterizedDefinition& d) { return d.Value(); });
py::class_<StepRepr_RepresentedDefinition>(m, "StepRepr_RepresentedDefinition")
.def(py::init<>())
.def("SetValue", [](StepRepr_RepresentedDefinition& d, const H<Standard_Transient>& v) { d.SetValue(v); })
.def("Value", [](const StepRepr_RepresentedDefinition& d) { return d.Value(); });
py::class_<StepBasic_ProductDefinition, H<StepBasic_ProductDefinition>, Standard_Transient>(m, "StepBasic_ProductDefinition")
.def(py::init([]() { return new StepBasic_ProductDefinition(); }))
.def("Id", [](const StepBasic_ProductDefinition& p) { return p.Id(); })
.def("Description", [](const StepBasic_ProductDefinition& p) { return p.Description(); });
py::class_<StepRepr_PropertyDefinition, H<StepRepr_PropertyDefinition>, Standard_Transient>(m, "StepRepr_PropertyDefinition")
.def(py::init([]() { return new StepRepr_PropertyDefinition(); }))
.def("Init",
[](StepRepr_PropertyDefinition& p, const H<TCollection_HAsciiString>& name, bool has_description,
const H<TCollection_HAsciiString>& description, const StepRepr_CharacterizedDefinition& definition) {
p.Init(name, has_description, description, definition);
})
.def("Name", [](const StepRepr_PropertyDefinition& p) { return p.Name(); })
.def("Description", [](const StepRepr_PropertyDefinition& p) { return p.Description(); })
.def("HasDescription", [](const StepRepr_PropertyDefinition& p) { return p.HasDescription(); })
.def("Definition", [](const StepRepr_PropertyDefinition& p) { return p.Definition(); });
py::class_<StepRepr_ProductDefinitionShape, H<StepRepr_ProductDefinitionShape>, StepRepr_PropertyDefinition>(
m, "StepRepr_ProductDefinitionShape")
.def(py::init([]() { return new StepRepr_ProductDefinitionShape(); }));
py::class_<StepRepr_PropertyDefinitionRepresentation, H<StepRepr_PropertyDefinitionRepresentation>, Standard_Transient>(
m, "StepRepr_PropertyDefinitionRepresentation")
.def(py::init([]() { return new StepRepr_PropertyDefinitionRepresentation(); }))
.def("Init",
[](StepRepr_PropertyDefinitionRepresentation& p, const StepRepr_RepresentedDefinition& definition,
const H<StepRepr_Representation>& used) { p.Init(definition, used); })
.def("Definition", [](const StepRepr_PropertyDefinitionRepresentation& p) { return p.Definition(); })
.def("UsedRepresentation", [](const StepRepr_PropertyDefinitionRepresentation& p) { return p.UsedRepresentation(); });
py::class_<StepShape_ShapeDefinitionRepresentation, H<StepShape_ShapeDefinitionRepresentation>,
StepRepr_PropertyDefinitionRepresentation>(m, "StepShape_ShapeDefinitionRepresentation")
.def(py::init([]() { return new StepShape_ShapeDefinitionRepresentation(); }));
// ---- BinTools, and the stream-taking BRepTools statics -------------------------------------------------------
py::class_<BinTools>(m, "BinTools")
.def_static("Write_s", [](const TopoDS_Shape& s, const std::string& file) { return BinTools::Write(s, file.c_str()); },
py::arg("theShape"), py::arg("theFile"))
.def_static("Write_s",
[](const TopoDS_Shape& s, const std::string& file, bool tri, bool normals, BinTools_FormatVersion v) {
return BinTools::Write(s, file.c_str(), tri, normals, v);
},
py::arg("theShape"), py::arg("theFile"), py::arg("theWithTriangles"), py::arg("theWithNormals"),
py::arg("theVersion"))
.def_static("Write_s",
[](const TopoDS_Shape& s, const py::object& stream) {
std::ostringstream out(std::ios::out | std::ios::binary);
BinTools::Write(s, out);
fill(stream, out.str());
},
py::arg("theShape"), py::arg("theStream"))
.def_static("Write_s",
[](const TopoDS_Shape& s, const py::object& stream, bool tri, bool normals, BinTools_FormatVersion v) {
std::ostringstream out(std::ios::out | std::ios::binary);
BinTools::Write(s, out, tri, normals, v);
fill(stream, out.str());
},
py::arg("theShape"), py::arg("theStream"), py::arg("theWithTriangles"), py::arg("theWithNormals"),
py::arg("theVersion"))
.def_static("Read_s", [](TopoDS_Shape& s, const std::string& file) { return BinTools::Read(s, file.c_str()); },
py::arg("theShape"), py::arg("theFile"))
.def_static("Read_s",
[](TopoDS_Shape& s, const py::object& stream) {
std::istringstream in(drain(stream), std::ios::in | std::ios::binary);
BinTools::Read(s, in);
},
py::arg("theShape"), py::arg("theStream"));
// BRepTools belongs to the geometry/query area; its stream statics live here. Added to that class when it is
// there, overload-chained after whatever it already defines under the same name.
py::object brep_tools;
if (py::hasattr(m, "BRepTools")) {
brep_tools = m.attr("BRepTools");
} else {
brep_tools = py::class_<BRepTools>(m, "BRepTools");
}
add_static(
brep_tools, "Write_s",
[](const TopoDS_Shape& s, const py::object& stream) {
std::ostringstream out(std::ios::out | std::ios::binary);
BRepTools::Write(s, out);
fill(stream, out.str());
},
py::arg("theShape"), py::arg("theStream"));
add_static(
brep_tools, "Write_s",
[](const TopoDS_Shape& s, const py::object& stream, bool tri, bool normals, TopTools_FormatVersion v) {
std::ostringstream out(std::ios::out | std::ios::binary);
BRepTools::Write(s, out, tri, normals, v);
fill(stream, out.str());
},
py::arg("theShape"), py::arg("theStream"), py::arg("theWithTriangles"), py::arg("theWithNormals"),
py::arg("theVersion"));
add_static(
brep_tools, "Read_s",
[](TopoDS_Shape& s, const py::object& stream, const BRep_Builder& b) {
std::istringstream in(drain(stream), std::ios::in | std::ios::binary);
BRepTools::Read(s, in, b);
},
py::arg("Sh"), py::arg("S"), py::arg("B"));
}
} // namespace scad::pybind::occt
+74
View File
@@ -0,0 +1,74 @@
// The OCCT classes the Python layers above the C++ library still talk to (STEP/BREP inspection, drawing, DXF,
// translators), exposed under the names and with the call shapes of the `OCP` package -- so that code written
// against OCP runs on the OpenCASCADE this module already carries, and OCP itself is not needed.
//
// Only what those layers (and their tests) call is bound: the surface is measured, not copied. Every class lives
// in the flat submodule `simplecadapi._cpp._native._occt`; the pure-Python package `simplecadapi._cpp.occt` lays it out
// in OCP's module structure (`from simplecadapi._cpp.occt.TopoDS import TopoDS_Shape`).
//
// Calls follow OCP, not C++: out-parameters are mutated in place (`BRepAdaptor_Curve.D1(u, pnt, vec)`), a static
// method `Foo::Bar` is `Foo.Bar_s`, an enum value is both `Enum.Name` and a module-level `Name`.
#pragma once
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/functional.h>
#include <pybind11/operators.h>
#include <Standard_Handle.hxx>
namespace py = pybind11;
// OCCT's reference-counted classes (Geom_*, Poly_Triangulation, TDocStd_Document, ...) travel as opencascade::handle.
PYBIND11_DECLARE_HOLDER_TYPE(T, opencascade::handle<T>, true)
namespace pybind11::detail {
template <typename T>
struct holder_helper<opencascade::handle<T>> {
static const T* get(const opencascade::handle<T>& p) { return p.get(); }
};
} // namespace pybind11::detail
namespace scad::pybind::occt {
// Each area registers its classes on the flat submodule, in this order (a class may name one registered before it).
void bind_core(py::module_& m); // gp_*, enums, TopLoc, TopoDS_*, TopExp, TopTools_*, Precision, BRep_Tool/Builder
void bind_query(py::module_& m); // BRepAdaptor_*, BRepGProp/GProp, Bnd/BRepBndLib, classifiers, extrema, Geom_* curves/surfaces
void bind_algo(py::module_& m); // booleans, builders, primitives, fillet, transform/copy, mesh, HLR, shape upgrade
void bind_step(py::module_& m); // STEP/XCAF/TDF/TCollection/Quantity/Step*, BinTools, IO of BREP
void bind_occt(py::module_& m);
} // namespace scad::pybind::occt
#include <TopAbs_ShapeEnum.hxx>
#include <TopoDS.hxx>
#include <TopoDS_CompSolid.hxx>
#include <TopoDS_Compound.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Face.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Shell.hxx>
#include <TopoDS_Solid.hxx>
#include <TopoDS_Vertex.hxx>
#include <TopoDS_Wire.hxx>
namespace scad::pybind::occt {
// A shape as the Python class of its type (TopoDS_Solid, ...): `.wrapped` of a native shape, and what an explorer
// hands back once the caller has asked for a type.
inline py::object shape_to_python(const TopoDS_Shape& shape) {
if (shape.IsNull()) return py::cast(shape);
switch (shape.ShapeType()) {
case TopAbs_VERTEX: return py::cast(TopoDS::Vertex(shape));
case TopAbs_EDGE: return py::cast(TopoDS::Edge(shape));
case TopAbs_WIRE: return py::cast(TopoDS::Wire(shape));
case TopAbs_FACE: return py::cast(TopoDS::Face(shape));
case TopAbs_SHELL: return py::cast(TopoDS::Shell(shape));
case TopAbs_SOLID: return py::cast(TopoDS::Solid(shape));
case TopAbs_COMPSOLID: return py::cast(TopoDS::CompSolid(shape));
case TopAbs_COMPOUND: return py::cast(TopoDS::Compound(shape));
default: return py::cast(shape);
}
}
} // namespace scad::pybind::occt
+36
View File
@@ -0,0 +1,36 @@
// Holding Python objects from C++ objects that outlive the interpreter.
//
// A registry with static storage (the reactive ExecutorRegistry, the sketch solver backends, ...)
// is destroyed from exit(), AFTER Py_Finalize. Releasing a Python reference then must not touch
// the interpreter: acquiring the GIL creates a thread state (PyThreadState_New) on a finalized
// runtime and crashes the process on its way out. Use drop_python_reference() in every
// destructor that owns a py::object / py::function; at shutdown it leaks the one reference,
// which is the right thing to do for a process that is exiting.
#pragma once
#include <Python.h>
#include <pybind11/pybind11.h>
namespace scad::pybind {
inline bool python_alive() noexcept {
if (Py_IsInitialized() == 0) return false;
#if PY_VERSION_HEX >= 0x030D0000
return Py_IsFinalizing() == 0;
#else
return _Py_IsFinalizing() == 0;
#endif
}
template <class PyObj>
void drop_python_reference(PyObj& object) noexcept {
if (!python_alive()) {
object.release(); // forget the reference without decrementing it
return;
}
const pybind11::gil_scoped_acquire gil;
object = PyObj();
}
} // namespace scad::pybind