refactor(ql,std,semantic,sketch,surface,reactive,topo): split the remaining long functions

cardinality_failure, ShapeSelector::from_value, build_gear_profile_sketch,
apply_tracking_tags, Shape::to_string, assemble_solution, Sketch::add_bspline,
make_cylindrical_surface_rface, geo_selector_score, make_geo_exact_selector.
Behaviour is unchanged: validation and OCCT call order are kept; float sums
keep their operation order. Verified with the 14 ctest targets, the 471
Python tests in tests/python and the old ql, gear, sketch, surface,
tagging, serialization and inspect suites.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
NiJingzhe
2026-10-29 17:25:52 +08:00
parent 954ec58da0
commit eeb312c5d6
10 changed files with 693 additions and 450 deletions
+45 -24
View File
@@ -217,8 +217,8 @@ std::vector<ErrorEvidence> collect_evidence(const EvidenceRequest& request) {
}
// ---- the cardinality message
// ---------------------------------------------------------------------------------------------- One letter per kind,
// so error text and rendered evidence can say "F3" and "E7" unambiguously.
//
// One letter per kind, so error text and rendered evidence can say "F3" and "E7" unambiguously.
std::string symbol_prefix(const std::string& target_kind) {
if (target_kind == "face")
return "F";
@@ -237,40 +237,39 @@ std::string symbol_prefix(const std::string& target_kind) {
return text::upper(std::string_view(target_kind).substr(0, 1));
}
[[noreturn]] void cardinality_failure(const std::string& target_kind, const std::vector<Shape>& matched,
std::int64_t expected, const std::string& mode, const Scope& scope) {
const std::vector<Shape> candidates = detail::scope_items(scope, target_kind);
const std::string prefix = symbol_prefix(target_kind);
const IdentitySet matched_set(matched.begin(), matched.end());
const auto matched_count = static_cast<std::int64_t>(matched.size());
// Symbols follow the candidate enumeration, so hits and near misses share one naming for the scope.
// Inventory rows for the hits and (at most 8) near misses, and which candidates were hits.
struct CardinalityInventory {
std::vector<InventoryEntry> inventory;
std::vector<char> is_hit(candidates.size(), 0);
std::vector<char> is_hit;
};
// Symbols follow the candidate enumeration, so hits and near misses share one naming for the scope.
CardinalityInventory cardinality_inventory(const std::vector<Shape>& candidates, const IdentitySet& matched_set,
const std::string& prefix) {
CardinalityInventory out;
out.is_hit.assign(candidates.size(), 0);
std::size_t near_misses_listed = 0;
for (std::size_t i = 0; i < candidates.size(); ++i) {
const bool hit = matched_set.contains(candidates[i]);
if (hit) {
is_hit[i] = 1;
out.is_hit[i] = 1;
} else {
if (near_misses_listed >= 8)
continue;
++near_misses_listed;
}
inventory.push_back(
out.inventory.push_back(
{prefix + std::to_string(i + 1), hit ? "hit" : "near_miss", entity_geometry_summary(candidates[i])});
}
return out;
}
const std::vector<std::vector<std::size_t>> groups = target_kind == "face" && matched.size() > 1
? face_logical_groups(matched)
: std::vector<std::vector<std::size_t>>{};
std::vector<ErrorMeasurement> measurements = {
{"matched_count", static_cast<double>(matched.size()), ""},
{"candidate_count", static_cast<double>(candidates.size()), ""},
{"expected_count", static_cast<double>(expected), ""},
};
// What to try: group hints for seam-split faces, then too-many / too-few advice.
std::vector<std::string> cardinality_repair(const std::vector<Shape>& candidates, const std::vector<Shape>& matched,
const std::vector<std::vector<std::size_t>>& groups,
const std::vector<char>& is_hit, const std::string& prefix,
std::int64_t expected) {
const auto matched_count = static_cast<std::int64_t>(matched.size());
std::unordered_map<Shape, std::size_t, IdentityHash, IdentityEqual> candidate_index;
for (std::size_t i = 0; i < candidates.size(); ++i)
candidate_index[candidates[i]] = i;
@@ -306,6 +305,28 @@ std::string symbol_prefix(const std::string& target_kind) {
"Booleans and fillets re-split topology; re-derive the selector from the newest shape instead of "
"reusing one resolved earlier.");
}
return repair;
}
[[noreturn]] void cardinality_failure(const std::string& target_kind, const std::vector<Shape>& matched,
std::int64_t expected, const std::string& mode, const Scope& scope) {
const std::vector<Shape> candidates = detail::scope_items(scope, target_kind);
const std::string prefix = symbol_prefix(target_kind);
const IdentitySet matched_set(matched.begin(), matched.end());
CardinalityInventory listed = cardinality_inventory(candidates, matched_set, prefix);
const std::vector<std::vector<std::size_t>> groups = target_kind == "face" && matched.size() > 1
? face_logical_groups(matched)
: std::vector<std::vector<std::size_t>>{};
std::vector<ErrorMeasurement> measurements = {
{"matched_count", static_cast<double>(matched.size()), ""},
{"candidate_count", static_cast<double>(candidates.size()), ""},
{"expected_count", static_cast<double>(expected), ""},
};
std::vector<std::string> repair = cardinality_repair(candidates, matched, groups, listed.is_hit, prefix, expected);
std::vector<Shape> near_misses;
for (const Shape& candidate : candidates) {
@@ -342,7 +363,7 @@ std::string symbol_prefix(const std::string& target_kind) {
guidance.measurements = std::move(measurements);
guidance.evidence = collect_evidence(request);
guidance.repair = std::move(repair);
guidance.inventory = std::move(inventory);
guidance.inventory = std::move(listed.inventory);
throw Error(operation, std::move(guidance));
}
+102 -63
View File
@@ -351,58 +351,112 @@ Value ShapeSelector::to_value() const {
return out;
}
namespace {
// The payload member `name`, or nullptr when it is absent or null.
const Value* present_member(const Value& data, std::string_view name) {
const Value* found = data.find(name);
return found != nullptr && !found->is_null() ? found : nullptr;
}
std::string required_target_kind(const Value& data) {
const Value* found = data.find("target_kind");
if (found == nullptr)
missing_key("target_kind");
return string_of(*found);
}
struct ParsedSetOperation {
std::string op;
std::vector<ShapeSelector> operands;
};
// {"op": "intersection", "operands": [...]}: at least two operands of the selector's own target kind.
ParsedSetOperation parse_set_operation(const Value& raw, const Value& data) {
if (!raw.is_object())
throw ValueError("selector set_operation must be an object");
if (!has_exactly(raw, {"op", "operands"}))
throw ValueError("selector set_operation has invalid fields");
ParsedSetOperation out;
out.op = text::lower(text::strip(string_of(*raw.find("op"))));
if (out.op != "intersection")
throw ValueError("unsupported selector set operation: " + out.op);
const Value& raw_operands = *raw.find("operands");
if (!raw_operands.is_array() || raw_operands.size() < 2)
throw ValueError("selector intersection requires at least two operands");
out.operands = selectors_from(raw_operands);
const std::string kind = required_target_kind(data);
if (std::any_of(out.operands.begin(), out.operands.end(),
[&](const ShapeSelector& s) { return s.target_kind() != kind; }))
throw ValueError("selector intersection operands must match target_kind");
return out;
}
struct ParsedIncidentFaces {
std::vector<ShapeSelector> selectors;
bool distinct = false;
};
// {"selectors": [...], "distinct": bool}: only valid on edge selectors, and the selectors must select faces.
ParsedIncidentFaces parse_incident_faces(const Value& raw, const Value& data) {
if (!raw.is_object() || !has_exactly(raw, {"selectors", "distinct"}))
throw ValueError("selector incident_faces has invalid fields");
const Value* kind = data.find("target_kind");
if (kind == nullptr || text::lower(string_of(*kind)) != "edge")
throw ValueError("incident_faces is only valid for edge selectors");
const Value& raw_selectors = *raw.find("selectors");
if (!raw_selectors.is_array() || raw_selectors.size() == 0)
throw ValueError("incident_faces requires one or more selectors");
ParsedIncidentFaces out;
out.selectors = selectors_from(raw_selectors);
if (std::any_of(out.selectors.begin(), out.selectors.end(),
[](const ShapeSelector& s) { return s.target_kind() != "face"; }))
throw ValueError("incident_faces selectors must select faces");
out.distinct = truthy(*raw.find("distinct"));
return out;
}
// The ordering keys: the "order_keys" list when present, else the single "order_key" with "order_desc".
// A list without a single key also sets the single key to its last entry (`order_key`).
std::vector<std::pair<Key, bool>> parse_order_keys(const Value& data, std::optional<Key>& order_key) {
std::vector<std::pair<Key, bool>> order_keys;
const Value* raw_keys = data.find("order_keys");
if (raw_keys != nullptr && raw_keys->is_array()) {
for (const Value& item : raw_keys->as_array()) {
const Value* key_object = item.is_object() ? object_member(item, "key") : nullptr;
if (key_object == nullptr)
throw ValueError("selector order_keys entries must contain a key object");
const Value* desc = item.find("desc");
order_keys.emplace_back(Key::from_value(*key_object), desc != nullptr && truthy(*desc));
}
if (!order_key && !order_keys.empty())
order_key = order_keys.back().first;
} else if (order_key) {
const Value* desc = data.find("order_desc");
order_keys.emplace_back(*order_key, desc != nullptr && truthy(*desc));
}
return order_keys;
}
} // namespace
ShapeSelector ShapeSelector::from_value(const Value& data) {
if (!data.is_object())
throw ValueError("selector payload must be an object");
auto impl = std::make_shared<Impl>();
Impl& m = *impl;
const auto target_kind = [&]() -> std::string {
const Value* found = data.find("target_kind");
if (found == nullptr)
missing_key("target_kind");
return string_of(*found);
};
const auto present = [&](std::string_view name) -> const Value* {
const Value* found = data.find(name);
return found != nullptr && !found->is_null() ? found : nullptr;
};
if (const Value* raw = present("set_operation")) {
if (!raw->is_object())
throw ValueError("selector set_operation must be an object");
if (!has_exactly(*raw, {"op", "operands"}))
throw ValueError("selector set_operation has invalid fields");
std::string op_name = text::lower(text::strip(string_of(*raw->find("op"))));
if (op_name != "intersection")
throw ValueError("unsupported selector set operation: " + op_name);
const Value& raw_operands = *raw->find("operands");
if (!raw_operands.is_array() || raw_operands.size() < 2)
throw ValueError("selector intersection requires at least two operands");
m.operands = selectors_from(raw_operands);
const std::string kind = target_kind();
if (std::any_of(m.operands.begin(), m.operands.end(),
[&](const ShapeSelector& s) { return s.target_kind() != kind; }))
throw ValueError("selector intersection operands must match target_kind");
m.set_operation = std::move(op_name);
if (const Value* raw = present_member(data, "set_operation")) {
ParsedSetOperation parsed = parse_set_operation(*raw, data);
m.operands = std::move(parsed.operands);
m.set_operation = std::move(parsed.op);
}
if (const Value* raw = present("incident_faces")) {
if (!raw->is_object() || !has_exactly(*raw, {"selectors", "distinct"}))
throw ValueError("selector incident_faces has invalid fields");
const Value* kind = data.find("target_kind");
if (kind == nullptr || text::lower(string_of(*kind)) != "edge")
throw ValueError("incident_faces is only valid for edge selectors");
const Value& raw_selectors = *raw->find("selectors");
if (!raw_selectors.is_array() || raw_selectors.size() == 0)
throw ValueError("incident_faces requires one or more selectors");
m.incident_face_selectors = selectors_from(raw_selectors);
if (std::any_of(m.incident_face_selectors.begin(), m.incident_face_selectors.end(),
[](const ShapeSelector& s) { return s.target_kind() != "face"; }))
throw ValueError("incident_faces selectors must select faces");
m.incident_faces_distinct = truthy(*raw->find("distinct"));
if (const Value* raw = present_member(data, "incident_faces")) {
ParsedIncidentFaces parsed = parse_incident_faces(*raw, data);
m.incident_face_selectors = std::move(parsed.selectors);
m.incident_faces_distinct = parsed.distinct;
}
if (const Value* raw = present("incident_face_cardinality")) {
if (const Value* raw = present_member(data, "incident_face_cardinality")) {
if (!raw->is_object() || !has_exactly(*raw, {"exactly"}))
throw ValueError("incident_face_cardinality only supports exactly");
m.incident_face_cardinality = integer_of(*raw->find("exactly"));
@@ -416,27 +470,12 @@ ShapeSelector ShapeSelector::from_value(const Value& data) {
m.predicate = Predicate::from_value(*raw);
if (const Value* raw = object_member(data, "order_key"))
m.order_key = Key::from_value(*raw);
m.order_keys = parse_order_keys(data, m.order_key);
const Value* raw_keys = data.find("order_keys");
if (raw_keys != nullptr && raw_keys->is_array()) {
for (const Value& item : raw_keys->as_array()) {
const Value* key_object = item.is_object() ? object_member(item, "key") : nullptr;
if (key_object == nullptr)
throw ValueError("selector order_keys entries must contain a key object");
const Value* desc = item.find("desc");
m.order_keys.emplace_back(Key::from_value(*key_object), desc != nullptr && truthy(*desc));
}
if (!m.order_key && !m.order_keys.empty())
m.order_key = m.order_keys.back().first;
} else if (m.order_key) {
const Value* desc = data.find("order_desc");
m.order_keys.emplace_back(*m.order_key, desc != nullptr && truthy(*desc));
}
m.target_kind = target_kind();
m.target_kind = required_target_kind(data);
if (const Value* desc = data.find("order_desc"))
m.order_desc = truthy(*desc);
if (const Value* limit = present("limit"))
if (const Value* limit = present_member(data, "limit"))
m.limit_count = integer_of(*limit);
if (const Value* raw = data.find("cardinality")) {
if (!raw->is_object())
@@ -444,7 +483,7 @@ ShapeSelector ShapeSelector::from_value(const Value& data) {
for (const auto& [name, count] : raw->as_object())
m.cardinality.emplace_back(name, integer_of(count));
}
if (const Value* raw = present("source_node_id")) {
if (const Value* raw = present_member(data, "source_node_id")) {
m.source_node_id = string_of(*raw);
const Value* slot = data.find("source_output_slot");
m.source_output_slot = slot != nullptr ? static_cast<int>(integer_of(*slot)) : 0;
+32 -18
View File
@@ -186,18 +186,10 @@ Value make_selector_hint(const Shape& shape) {
return hint;
}
Value make_geo_exact_selector(const Shape& shape, const Shape* source) {
Value selector = Value::object();
selector.set("mode", "geo_exact");
selector.set("kind", shape_kind_token(shape));
Value geo = shape.get_metadata("geo", Value::object());
if (geo.is_null())
geo = Value::object();
if (shape.kind() == Kind::Edge && source != nullptr) {
if (const auto index = wrapper_edge_index(*source, shape))
geo.set("edge_index", *index);
}
selector.set("metadata_geo", std::move(geo));
namespace {
// A face loaded from a BREP region snapshot also names its snapshot and source face id.
void add_brep_region_ref(Value& selector, const Shape& shape) {
if (shape.kind() == Kind::Face) {
const Value provenance = shape.get_metadata("provenance");
if (provenance.is_object()) {
@@ -211,13 +203,10 @@ Value make_geo_exact_selector(const Shape& shape, const Shape* source) {
}
}
}
try {
selector.set("bbox", bbox_payload(shape));
} catch (const std::exception&) {
}
if (const auto geom = shape_geom_type(shape))
selector.set("geom_type", *geom);
}
// The kind-specific measurements that make up the exact selector (compared by geo_selector_score).
void add_kind_measurements(Value& selector, const Shape& shape) {
switch (shape.kind()) {
case Kind::Vertex:
selector.set("coordinates", vec_list(shape.as<Vertex>().coordinates()));
@@ -266,6 +255,31 @@ Value make_geo_exact_selector(const Shape& shape, const Shape* source) {
break;
}
}
}
} // namespace
Value make_geo_exact_selector(const Shape& shape, const Shape* source) {
Value selector = Value::object();
selector.set("mode", "geo_exact");
selector.set("kind", shape_kind_token(shape));
Value geo = shape.get_metadata("geo", Value::object());
if (geo.is_null())
geo = Value::object();
if (shape.kind() == Kind::Edge && source != nullptr) {
if (const auto index = wrapper_edge_index(*source, shape))
geo.set("edge_index", *index);
}
selector.set("metadata_geo", std::move(geo));
add_brep_region_ref(selector, shape);
try {
selector.set("bbox", bbox_payload(shape));
} catch (const std::exception&) {
}
if (const auto geom = shape_geom_type(shape))
selector.set("geom_type", *geom);
add_kind_measurements(selector, shape);
return selector;
}
+25 -12
View File
@@ -60,12 +60,9 @@ double number_or(const Value* value, double fallback) {
return value != nullptr && value->is_number() ? value->as_double() : fallback;
}
// _geo_selector_score: how far `shape` is from what the selector describes (0 = the same).
double geo_selector_score(const Shape& shape, const Value& selector) {
const Value* kind = selector.find("kind");
if (kind == nullptr || !kind->is_string() || kind->as_string() != kind_name(shape.kind()))
return 1e12;
// Distance of the shape's bounding box corners from the selector's "bbox" (0 when it declares none;
// 1e6 when the box is malformed).
double bbox_distance(const Shape& shape, const Value& selector) {
double score = 0.0;
if (const Value* bbox = selector.find("bbox"); bbox != nullptr && bbox->is_object()) {
const Value* lo = bbox->find("min");
@@ -78,12 +75,12 @@ double geo_selector_score(const Shape& shape, const Value& selector) {
Vec3{box.xmax, box.ymax, box.zmax}.distance(vec_of(hi));
}
}
score *= 10.0;
if (const Value* expected = selector.find("geom_type"); expected != nullptr && expected->is_string()) {
const auto actual = shape_geom_type(shape);
if (actual && *actual != expected->as_string())
score += 1e6;
}
return score;
}
// Adds the per-kind terms to `score`, in the order the Python scorer adds them (float sums are order-sensitive).
// A missing center/coordinates/normal costs 1e6.
double add_kind_terms(double score, const Shape& shape, const Value& selector) {
const auto center_term = [&](double weight) {
return has_vec(selector.find("center")) ? shape.center().distance(vec_of(selector.find("center"))) * weight : 1e6;
};
@@ -145,6 +142,22 @@ double geo_selector_score(const Shape& shape, const Value& selector) {
return score;
}
// _geo_selector_score: how far `shape` is from what the selector describes (0 = the same).
double geo_selector_score(const Shape& shape, const Value& selector) {
const Value* kind = selector.find("kind");
if (kind == nullptr || !kind->is_string() || kind->as_string() != kind_name(shape.kind()))
return 1e12;
double score = bbox_distance(shape, selector);
score *= 10.0;
if (const Value* expected = selector.find("geom_type"); expected != nullptr && expected->is_string()) {
const auto actual = shape_geom_type(shape);
if (actual && *actual != expected->as_string())
score += 1e6;
}
return add_kind_terms(score, shape, selector);
}
} // namespace
TopAbs_ShapeEnum topabs_of(Kind kind) {
+65 -39
View File
@@ -523,21 +523,13 @@ DeltaEntries entries_from_delta(const TopoDelta& delta) {
return result;
}
Shape apply_tracking_tags(Shape result, const TopoDelta& delta, const DeltaEntries& given_entries,
const TrackingContext& context) {
const DeltaEntries entries = given_entries.empty() ? entries_from_delta(delta) : given_entries;
const std::string& op = context.op;
namespace {
TopologyIndex source_faces, source_edges;
for (const Shape& source : context.sources) {
for (const Shape& face : faces_of(source))
source_faces.add(face);
for (const Shape& edge : edges_of(source))
source_edges.add(edge);
}
using SourceTargets = std::map<std::string, std::set<std::string>>;
// Which result faces a source edge's projected tags may land on: only a one-to-one story is told.
std::map<std::string, std::set<std::string>> topology_source_targets;
// Which result faces a source edge's projected tags may land on: only a one-to-one story is told.
SourceTargets topology_source_targets_of(const DeltaEntries& entries) {
SourceTargets topology_source_targets;
for (const auto& [target_id, entry] : entries) {
if (upper(py_str(entry.find("kind") != nullptr ? *entry.find("kind") : Value(""))) != "FACE")
continue;
@@ -548,7 +540,13 @@ Shape apply_tracking_tags(Shape result, const TopoDelta& delta, const DeltaEntri
topology_source_targets[py_str(*source_id)].insert(target_id);
}
}
return topology_source_targets;
}
// Sets the track, role bindings, lineage coverage and projected source tags on every result face.
void tag_result_faces(Shape& result, const DeltaEntries& entries, const std::string& op,
const TopologyIndex& source_faces, const TopologyIndex& source_edges,
const SourceTargets& topology_source_targets) {
for (Shape& face : faces_of(result)) {
const std::string topo_id = topology_key(face);
const auto entry = matching_entry(entries, topo_id, Kind::Face);
@@ -569,12 +567,35 @@ Shape apply_tracking_tags(Shape result, const TopoDelta& delta, const DeltaEntri
if (!source_edges.empty() && proven)
project_source_bindings(face, *entry, source_edges, op, false, topology_source_targets);
}
}
std::set<std::string> section_ids;
for (const TopoRef& ref : delta.section_edges)
if (ref.kind == Kind::Edge)
section_ids.insert(ref.topo_id);
// An edge the kernel reported only as a section edge: its track is a generated, proven intersection.
void mark_section_edge_without_witness(Value& track) {
Value section_witness = object({{"kind", "topology_change"},
{"topo_kind", "EDGE"},
{"source_kind", Value()},
{"event", "generated"},
{"origin_role", Value()},
{"input_topo_id", Value()},
{"derivation", "intersection"},
{"coverage", "complete"},
{"status", "proven"},
{"evidence_kind", "kernel_section_edges"},
{"section", true}});
Value witnesses = Value::array();
witnesses.push_back(std::move(section_witness));
Value generated = Value::array();
generated.push_back("generated");
track.set("coverage", "complete");
track.set("status", "proven");
track.set("event", "generated");
track.set("events", std::move(generated));
track.set("witnesses", std::move(witnesses));
}
// Same for edges; section edges (from the boolean's section result) get a track even without an entry.
void tag_result_edges(Shape& result, const DeltaEntries& entries, const std::string& op,
const std::set<std::string>& section_ids, const TopologyIndex& source_edges) {
for (Shape& edge : edges_of(result)) {
const std::string topo_id = topology_key(edge);
const auto entry = matching_entry(entries, topo_id, Kind::Edge);
@@ -588,28 +609,8 @@ Shape apply_tracking_tags(Shape result, const TopoDelta& delta, const DeltaEntri
if (section_ids.count(topo_id) != 0) {
track.set("section", true);
track.set("derivation", "intersection");
if (!entry) {
Value section_witness = object({{"kind", "topology_change"},
{"topo_kind", "EDGE"},
{"source_kind", Value()},
{"event", "generated"},
{"origin_role", Value()},
{"input_topo_id", Value()},
{"derivation", "intersection"},
{"coverage", "complete"},
{"status", "proven"},
{"evidence_kind", "kernel_section_edges"},
{"section", true}});
Value witnesses = Value::array();
witnesses.push_back(std::move(section_witness));
Value generated = Value::array();
generated.push_back("generated");
track.set("coverage", "complete");
track.set("status", "proven");
track.set("event", "generated");
track.set("events", std::move(generated));
track.set("witnesses", std::move(witnesses));
}
if (!entry)
mark_section_edge_without_witness(track);
}
edge.set_metadata_deferred("track", track);
apply_operation_role_bindings(edge, track, op);
@@ -617,6 +618,31 @@ Shape apply_tracking_tags(Shape result, const TopoDelta& delta, const DeltaEntri
if (entry && !source_edges.empty() && py_str(*track.find("status")) == "proven")
carry_source_lineage(edge, *entry, source_edges, op);
}
}
} // namespace
Shape apply_tracking_tags(Shape result, const TopoDelta& delta, const DeltaEntries& given_entries,
const TrackingContext& context) {
const DeltaEntries entries = given_entries.empty() ? entries_from_delta(delta) : given_entries;
const std::string& op = context.op;
TopologyIndex source_faces, source_edges;
for (const Shape& source : context.sources) {
for (const Shape& face : faces_of(source))
source_faces.add(face);
for (const Shape& edge : edges_of(source))
source_edges.add(edge);
}
const SourceTargets topology_source_targets = topology_source_targets_of(entries);
tag_result_faces(result, entries, op, source_faces, source_edges, topology_source_targets);
std::set<std::string> section_ids;
for (const TopoRef& ref : delta.section_edges)
if (ref.kind == Kind::Edge)
section_ids.insert(ref.topo_id);
tag_result_edges(result, entries, op, section_ids, source_edges);
return result;
}
+62 -43
View File
@@ -385,6 +385,64 @@ Sketch& Sketch::add_ellipse(const std::string& entity_id, const SketchRef& cente
return *this;
}
namespace {
// A non-periodic spline starts and ends at its start/end points: a pole given as a ref must be that
// point, a literal pole is overwritten with its coordinates.
void pin_end_poles(std::vector<Value>& poles, const std::string& start_id, const std::string& end_id,
const SketchPoint2& start_point, const SketchPoint2& end_point) {
const auto literal = [](const SketchPoint2& p) { return Value(Value::Array{Value(p.first), Value(p.second)}); };
if (poles.front().is_object()) {
if (poles.front().find("point_id")->as_string() != start_id) {
throw ValueError("The first B-spline control-point ref must match start");
}
} else {
poles.front() = literal(start_point);
}
if (poles.back().is_object()) {
if (poles.back().find("point_id")->as_string() != end_id) {
throw ValueError("The last B-spline control-point ref must match end");
}
} else {
poles.back() = literal(end_point);
}
}
// The stored form of a B-spline: normalized poles, full knot vector with multiplicities, weights or null.
SketchEntity make_bspline_entity(const std::string& entity_id, bool construction, const std::string& start_id,
const std::string& end_id, const std::vector<Value>& poles, int degree,
const BSplineKnots& resolved_knots,
const std::optional<std::vector<double>>& resolved_weights, bool periodic) {
SketchEntity entity;
entity.id = entity_id;
entity.kind = std::string(kBSplineKind);
entity.construction = construction;
entity.data.set("start", start_id);
entity.data.set("end", end_id);
entity.data.set("control_points", Value(Value::Array(poles.begin(), poles.end())));
entity.data.set("degree", degree);
Value::Array knot_values;
for (const double knot : resolved_knots.knots)
knot_values.emplace_back(knot);
entity.data.set("knots", Value(std::move(knot_values)));
Value::Array multiplicity_values;
for (const int mult : resolved_knots.multiplicities)
multiplicity_values.emplace_back(mult);
entity.data.set("multiplicities", Value(std::move(multiplicity_values)));
if (resolved_weights) {
Value::Array weight_values;
for (const double weight : *resolved_weights)
weight_values.emplace_back(weight);
entity.data.set("weights", Value(std::move(weight_values)));
} else {
entity.data.set("weights", Value());
}
entity.data.set("periodic", periodic);
return entity;
}
} // namespace
Sketch& Sketch::add_bspline(const std::string& entity_id, const SketchRef& start, const SketchRef& end,
const std::vector<SketchControlPoint>& control_points, int degree,
const std::optional<std::vector<Scalar>>& knots,
@@ -432,50 +490,11 @@ Sketch& Sketch::add_bspline(const std::string& entity_id, const SketchRef& start
const SketchPoint2 start_point = entity_xy(start_id);
const SketchPoint2 end_point = entity_xy(end_id);
const auto literal = [](const SketchPoint2& p) { return Value(Value::Array{Value(p.first), Value(p.second)}); };
if (!periodic) {
if (poles.front().is_object()) {
if (poles.front().find("point_id")->as_string() != start_id) {
throw ValueError("The first B-spline control-point ref must match start");
}
} else {
poles.front() = literal(start_point);
}
if (poles.back().is_object()) {
if (poles.back().find("point_id")->as_string() != end_id) {
throw ValueError("The last B-spline control-point ref must match end");
}
} else {
poles.back() = literal(end_point);
}
}
if (!periodic)
pin_end_poles(poles, start_id, end_id, start_point, end_point);
SketchEntity entity;
entity.id = entity_id;
entity.kind = std::string(kBSplineKind);
entity.construction = construction;
entity.data.set("start", start_id);
entity.data.set("end", end_id);
entity.data.set("control_points", Value(Value::Array(poles.begin(), poles.end())));
entity.data.set("degree", degree);
Value::Array knot_values;
for (const double knot : resolved_knots.knots)
knot_values.emplace_back(knot);
entity.data.set("knots", Value(std::move(knot_values)));
Value::Array multiplicity_values;
for (const int mult : resolved_knots.multiplicities)
multiplicity_values.emplace_back(mult);
entity.data.set("multiplicities", Value(std::move(multiplicity_values)));
if (resolved_weights) {
Value::Array weight_values;
for (const double weight : *resolved_weights)
weight_values.emplace_back(weight);
entity.data.set("weights", Value(std::move(weight_values)));
} else {
entity.data.set("weights", Value());
}
entity.data.set("periodic", periodic);
add_entity(std::move(entity));
add_entity(make_bspline_entity(entity_id, construction, start_id, end_id, poles, degree, resolved_knots,
resolved_weights, periodic));
return *this;
}
+74 -58
View File
@@ -105,10 +105,12 @@ double bspline_length(const SolvedGeometry& solved, const SketchEntity& entity)
} // namespace
SolvedGeometry assemble_solution(const Model& model, const std::vector<double>& x) {
const Reader read{model, x};
namespace {
// Point and radius values read from the solver vector: points first (entities, then spline poles),
// then circle and arc radii (an arc's radius is its centre-to-start distance).
void read_points_and_radii(const Model& model, const Reader& read, SolvedGeometry& out) {
const Sketch& sketch = model.sketch;
SolvedGeometry out;
for (const auto& [id, entity] : sketch.entities()) {
if (entity.kind == kPointKind)
@@ -134,63 +136,77 @@ SolvedGeometry assemble_solution(const Model& model, const std::vector<double>&
out.scalars.set("arc:" + id + ":radius", radius);
out.scalars.set("arc:" + id + ":diameter", 2.0 * radius);
}
}
for (const auto& [id, entity] : sketch.entities()) {
Value solved = Value::object();
solved.set("kind", entity.kind);
if (entity.kind == kPointKind) {
solved.set("point", point_value(out.points.at(id)));
} else if (entity.kind == kLineKind) {
const SketchPoint2 start = out.points.at(entity.point_id("start"));
const SketchPoint2 end = out.points.at(entity.point_id("end"));
solved.set("start", point_value(start));
solved.set("end", point_value(end));
solved.set("length", distance(start, end));
} else if (entity.kind == kCircleKind) {
const double radius = out.scalars.at("circle:" + id + ":radius");
solved.set("center", point_value(out.points.at(entity.point_id("center"))));
solved.set("radius", radius);
solved.set("diameter", 2.0 * radius);
} else if (entity.kind == kArcKind) {
const SketchPoint2 center = out.points.at(entity.point_id("center"));
const SketchPoint2 start = out.points.at(entity.point_id("start"));
const SketchPoint2 end = out.points.at(entity.point_id("end"));
const double radius = out.scalars.at("arc:" + id + ":radius");
const double sweep = sweep_of(center, start, end);
solved.set("center", point_value(center));
solved.set("start", point_value(start));
solved.set("end", point_value(end));
solved.set("radius", radius);
solved.set("sweep", sweep);
solved.set("length", radius * sweep);
} else if (entity.kind == kEllipseKind) {
const SketchPoint2 center = out.points.at(entity.point_id("center"));
const SketchPoint2 major = out.points.at(entity.point_id("major"));
const SketchPoint2 minor = out.points.at(entity.point_id("minor"));
solved.set("center", point_value(center));
solved.set("major_point", point_value(major));
solved.set("minor_point", point_value(minor));
solved.set("major_radius", distance(center, major));
solved.set("minor_radius", distance(center, minor));
solved.set("angle", std::atan2(major.second - center.second, major.first - center.first) * 180.0 / kPi);
} else if (entity.kind == kBSplineKind) {
const SplineModel& spline = model.splines.at(id);
Value::Array poles;
for (std::size_t i = 0; i < spline.poles.size(); ++i) {
poles.push_back(point_value(out.points.at("bspline:" + id + ":pole:" + std::to_string(i))));
}
solved.set("degree", spline.definition.degree);
solved.set("control_points", Value(std::move(poles)));
solved.set("knots", *entity.data.find("knots"));
solved.set("multiplicities", *entity.data.find("multiplicities"));
solved.set("weights", *entity.data.find("weights"));
solved.set("periodic", spline.definition.periodic);
solved.set("segment_count", static_cast<int>(spline.segments.size()));
solved.set("solver_representation", spline.cubic_bezier ? "cubic_bezier" : "fixed_shape");
} else {
continue;
// The solved description of one entity (what inspection reports), or nullopt for kinds it does not describe.
std::optional<Value> solved_entity_value(const Model& model, const std::string& id, const SketchEntity& entity,
const SolvedGeometry& out) {
Value solved = Value::object();
solved.set("kind", entity.kind);
if (entity.kind == kPointKind) {
solved.set("point", point_value(out.points.at(id)));
} else if (entity.kind == kLineKind) {
const SketchPoint2 start = out.points.at(entity.point_id("start"));
const SketchPoint2 end = out.points.at(entity.point_id("end"));
solved.set("start", point_value(start));
solved.set("end", point_value(end));
solved.set("length", distance(start, end));
} else if (entity.kind == kCircleKind) {
const double radius = out.scalars.at("circle:" + id + ":radius");
solved.set("center", point_value(out.points.at(entity.point_id("center"))));
solved.set("radius", radius);
solved.set("diameter", 2.0 * radius);
} else if (entity.kind == kArcKind) {
const SketchPoint2 center = out.points.at(entity.point_id("center"));
const SketchPoint2 start = out.points.at(entity.point_id("start"));
const SketchPoint2 end = out.points.at(entity.point_id("end"));
const double radius = out.scalars.at("arc:" + id + ":radius");
const double sweep = sweep_of(center, start, end);
solved.set("center", point_value(center));
solved.set("start", point_value(start));
solved.set("end", point_value(end));
solved.set("radius", radius);
solved.set("sweep", sweep);
solved.set("length", radius * sweep);
} else if (entity.kind == kEllipseKind) {
const SketchPoint2 center = out.points.at(entity.point_id("center"));
const SketchPoint2 major = out.points.at(entity.point_id("major"));
const SketchPoint2 minor = out.points.at(entity.point_id("minor"));
solved.set("center", point_value(center));
solved.set("major_point", point_value(major));
solved.set("minor_point", point_value(minor));
solved.set("major_radius", distance(center, major));
solved.set("minor_radius", distance(center, minor));
solved.set("angle", std::atan2(major.second - center.second, major.first - center.first) * 180.0 / kPi);
} else if (entity.kind == kBSplineKind) {
const SplineModel& spline = model.splines.at(id);
Value::Array poles;
for (std::size_t i = 0; i < spline.poles.size(); ++i) {
poles.push_back(point_value(out.points.at("bspline:" + id + ":pole:" + std::to_string(i))));
}
out.entities.set(id, std::move(solved));
solved.set("degree", spline.definition.degree);
solved.set("control_points", Value(std::move(poles)));
solved.set("knots", *entity.data.find("knots"));
solved.set("multiplicities", *entity.data.find("multiplicities"));
solved.set("weights", *entity.data.find("weights"));
solved.set("periodic", spline.definition.periodic);
solved.set("segment_count", static_cast<int>(spline.segments.size()));
solved.set("solver_representation", spline.cubic_bezier ? "cubic_bezier" : "fixed_shape");
} else {
return std::nullopt;
}
return solved;
}
} // namespace
SolvedGeometry assemble_solution(const Model& model, const std::vector<double>& x) {
const Reader read{model, x};
SolvedGeometry out;
read_points_and_radii(model, read, out);
for (const auto& [id, entity] : model.sketch.entities()) {
if (std::optional<Value> solved = solved_entity_value(model, id, entity, out))
out.entities.set(id, std::move(*solved));
}
return out;
}
+86 -50
View File
@@ -56,6 +56,87 @@ void add_construction_circles(SketchBuilder& sketch, const char* first, double f
// External gear
// ---------------------------------------------------------------------------
namespace {
// The six points of one external tooth: root start/end, flank base start/end, tip start/end.
struct ToothPoints {
Point2 rs, re, bs, be, ts, te;
};
// The outline of an external gear as one point set and one edge ring, ready for the sketch.
struct ExternalGearPlan {
const ToothGeometry& geo;
int n_teeth;
double tooth_angle;
bool needs_root_connectors; // the root circle lies inside the base circle: flanks start with a root fillet
const BSplineData& canonical;
const std::vector<double>& reversed_knots;
const std::vector<int>& reversed_multiplicities;
const std::optional<BSplineData>& left_fillet;
const std::optional<BSplineData>& right_fillet;
};
// Edges share the tooth points instead of carrying hundreds of coincidence constraints.
void add_tooth_points(SketchBuilder& sketch, const std::vector<ToothPoints>& teeth) {
for (std::size_t i = 0; i < teeth.size(); ++i) {
const int tooth = static_cast<int>(i);
add_point(sketch, tooth, "rs", teeth[i].rs);
add_point(sketch, tooth, "re", teeth[i].re);
add_point(sketch, tooth, "bs", teeth[i].bs);
add_point(sketch, tooth, "be", teeth[i].be);
add_point(sketch, tooth, "ts", teeth[i].ts);
add_point(sketch, tooth, "te", teeth[i].te);
}
}
// Per tooth: root arc, [left root fillet], left flank, tip arc, right flank (mirrored + reversed
// from the canonical one), [right root fillet]; each is the canonical curve rotated by the tooth turn.
void add_tooth_edges(SketchBuilder& sketch, const ExternalGearPlan& plan) {
const ToothGeometry& geo = plan.geo;
const int n_teeth = plan.n_teeth;
const bool needs_root_connectors = plan.needs_root_connectors;
const BSplineData& canonical = plan.canonical;
for (int i = 0; i < n_teeth; ++i) {
const std::string rs = tooth_point(i, "rs");
const std::string re = tooth_point(i, "re");
const std::string bs = needs_root_connectors ? tooth_point(i, "bs") : re;
const std::string be = tooth_point(i, "be");
const std::string ts = tooth_point(i, "ts");
const std::string te = tooth_point(i, "te");
const std::string next_rs = tooth_point((i + 1) % n_teeth, "rs");
const std::string right_flank_end = needs_root_connectors ? be : next_rs;
const double turn = plan.tooth_angle * i;
sketch.arc(numbered("arc_root_", i), rs, re, "center");
if (needs_root_connectors) {
BSplineData fillet = *plan.left_fillet;
fillet.control_points = transform_bspline_control_points(fillet.control_points, turn);
sketch.bspline(numbered("fillet_left_", i), re, tooth_point(i, "bs"), fillet);
}
BSplineData left = canonical;
left.control_points = transform_bspline_control_points(canonical.control_points, geo.left_start + turn);
sketch.bspline(numbered("bspline_left_", i), bs, ts, left);
sketch.arc(numbered("arc_tip_", i), ts, te, "center");
BSplineData right = canonical;
right.control_points = transform_bspline_control_points(canonical.control_points, geo.right_start + turn,
/*mirror=*/true, /*reverse=*/true);
right.knots = plan.reversed_knots;
right.multiplicities = plan.reversed_multiplicities;
sketch.bspline(numbered("bspline_right_", i), te, right_flank_end, right);
if (needs_root_connectors) {
BSplineData fillet = *plan.right_fillet;
fillet.control_points = transform_bspline_control_points(fillet.control_points, turn);
sketch.bspline(numbered("fillet_right_", i), be, next_rs, fillet);
}
}
}
} // namespace
Sketch build_gear_profile_sketch(int n_teeth, double module, double pressure_angle, const ToothOptions& options) {
const ToothGeometry geo = compute_tooth_geometry(n_teeth, module, pressure_angle, options);
const double root_radius = geo.root_radius;
@@ -81,9 +162,6 @@ Sketch build_gear_profile_sketch(int n_teeth, double module, double pressure_ang
add_construction_circles(sketch, "root_circle", root_radius, "pitch_circle", geo.pitch_radius, "tip_circle",
tip_radius);
struct ToothPoints {
Point2 rs, re, bs, be, ts, te;
};
std::vector<ToothPoints> teeth;
teeth.reserve(static_cast<std::size_t>(n_teeth));
for (int i = 0; i < n_teeth; ++i) {
@@ -101,54 +179,12 @@ Sketch build_gear_profile_sketch(int n_teeth, double module, double pressure_ang
geo.right_start + kPi, root_right_angle + kPi / 2.0);
}
// Edges share these points instead of carrying hundreds of coincidence constraints.
for (int i = 0; i < n_teeth; ++i) {
const ToothPoints& t = teeth[static_cast<std::size_t>(i)];
add_point(sketch, i, "rs", t.rs);
add_point(sketch, i, "re", t.re);
add_point(sketch, i, "bs", t.bs);
add_point(sketch, i, "be", t.be);
add_point(sketch, i, "ts", t.ts);
add_point(sketch, i, "te", t.te);
}
add_tooth_points(sketch, teeth);
for (int i = 0; i < n_teeth; ++i) {
const std::string rs = tooth_point(i, "rs");
const std::string re = tooth_point(i, "re");
const std::string bs = needs_root_connectors ? tooth_point(i, "bs") : re;
const std::string be = tooth_point(i, "be");
const std::string ts = tooth_point(i, "ts");
const std::string te = tooth_point(i, "te");
const std::string next_rs = tooth_point((i + 1) % n_teeth, "rs");
const std::string right_flank_end = needs_root_connectors ? be : next_rs;
const double turn = tooth_angle * i;
sketch.arc(numbered("arc_root_", i), rs, re, "center");
if (needs_root_connectors) {
BSplineData fillet = *left_fillet;
fillet.control_points = transform_bspline_control_points(fillet.control_points, turn);
sketch.bspline(numbered("fillet_left_", i), re, tooth_point(i, "bs"), fillet);
}
BSplineData left = canonical;
left.control_points = transform_bspline_control_points(canonical.control_points, geo.left_start + turn);
sketch.bspline(numbered("bspline_left_", i), bs, ts, left);
sketch.arc(numbered("arc_tip_", i), ts, te, "center");
BSplineData right = canonical;
right.control_points = transform_bspline_control_points(canonical.control_points, geo.right_start + turn,
/*mirror=*/true, /*reverse=*/true);
right.knots = reversed_knots;
right.multiplicities = reversed_multiplicities;
sketch.bspline(numbered("bspline_right_", i), te, right_flank_end, right);
if (needs_root_connectors) {
BSplineData fillet = *right_fillet;
fillet.control_points = transform_bspline_control_points(fillet.control_points, turn);
sketch.bspline(numbered("fillet_right_", i), be, next_rs, fillet);
}
}
const ExternalGearPlan plan{
geo, n_teeth, tooth_angle, needs_root_connectors, canonical, reversed_knots, reversed_multiplicities,
left_fillet, right_fillet};
add_tooth_edges(sketch, plan);
return sketch.take();
}
+100 -65
View File
@@ -124,6 +124,98 @@ TopoDS_Face cylindrical_face(double radius, const std::pair<double, double>& u,
return face;
}
void check_cylinder_dimensions(const Scalar& radius, const ScalarRange& u_range, const ScalarRange& v_range,
const CylindricalSurfaceOptions& options) {
require_dimension(radius, UnitDimension::Length, "radius must use model length units");
for (const Scalar* value : {&u_range.first, &u_range.second})
require_dimension(*value, UnitDimension::Dimensionless,
"u_range must use unitless raw radians; unit-aware angle values evaluate in degrees");
for (const Scalar* value : {&v_range.first, &v_range.second})
require_dimension(*value, UnitDimension::Length, "v_range must use model length units");
require_dimension(options.tolerance, UnitDimension::Length, "tolerance must use model length units");
}
struct CylinderRanges {
double radius, tolerance;
std::pair<double, double> u, v;
};
// Finite, positive radius and tolerance; increasing U (at most one revolution) and V ranges.
CylinderRanges checked_cylinder_ranges(const Scalar& radius, const ScalarRange& u_range, const ScalarRange& v_range,
const CylindricalSurfaceOptions& options) {
const double radius_value = radius.value();
const std::pair<double, double> u{u_range.first.value(), u_range.second.value()};
const std::pair<double, double> v{v_range.first.value(), v_range.second.value()};
const double tolerance_value = options.tolerance.value();
if (!std::isfinite(radius_value) || radius_value <= 0.0)
throw ValueError("radius must be a positive finite value");
if (!std::isfinite(u.first) || !std::isfinite(u.second))
throw ValueError("u_range must contain two finite values");
if (!std::isfinite(v.first) || !std::isfinite(v.second))
throw ValueError("v_range must contain two finite values");
const double u_span = u.second - u.first;
const double v_span = v.second - v.first;
// OCCT limits: a U span of at most 2*pi + Precision::Angular() (one revolution plus kernel angular slack).
if (u_span <= Precision::PConfusion() || u_span > 2.0 * kPi + Precision::Angular())
throw ValueError("u_range must be increasing and span at most one revolution");
if (v_span <= Precision::Confusion())
throw ValueError("v_range must be increasing beyond kernel confusion");
if (!std::isfinite(tolerance_value) || tolerance_value <= 0.0)
throw ValueError("tolerance must be a positive finite value");
return {radius_value, tolerance_value, u, v};
}
struct CylinderFrame {
Vec3 origin, axis, x_direction;
};
// The surface frame: finite, non-zero, non-parallel axis and x direction (default X from the axis).
CylinderFrame checked_cylinder_frame(const CylindricalSurfaceOptions& options) {
const Vec3 origin = evaluated(options.origin);
const Vec3 axis = evaluated(options.axis);
// A non-finite axis has no default X; the finite check below reports it.
const Vec3 x_direction = options.x_direction ? evaluated(*options.x_direction)
: axis.is_finite() ? default_plane_x_direction(axis)
: axis;
if (!origin.is_finite() || !axis.is_finite() || !x_direction.is_finite())
throw ValueError("origin, axis, and x_direction must be finite 3D values");
const double axis_norm = axis.norm();
const double x_norm = x_direction.norm();
if (axis_norm <= tol::kDegenerateNorm || x_norm <= tol::kDegenerateNorm)
throw ValueError("axis and x_direction must be non-zero");
if (std::abs(axis.dot(x_direction)) / (axis_norm * x_norm) >= 1.0 - tol::kParallelCosineGap)
throw ValueError("axis and x_direction must not be parallel");
return {origin, axis, x_direction};
}
// The recorded params and symbolic scalars of the operation (values as given, before the workplane transform).
void record_cylinder_args(const Scalar& radius, const ScalarRange& u_range, const ScalarRange& v_range,
const CylindricalSurfaceOptions& options, const CylinderRanges& r, const CylinderFrame& f,
Value& params, SymbolicArgs& symbolic) {
params = Value::object();
params.set("radius", r.radius);
params.set("u_range", Value(Value::Array{r.u.first, r.u.second}));
params.set("v_range", Value(Value::Array{r.v.first, r.v.second}));
params.set("origin", vec_value(f.origin));
params.set("axis", vec_value(f.axis));
params.set("x_direction", options.x_direction ? vec_value(f.x_direction) : Value());
params.set("tolerance", r.tolerance);
params.set("tag_prefix", to_value(options.tag_prefix));
note_symbolic(symbolic, "radius", radius);
note_symbolic(symbolic, "u_range[0]", u_range.first);
note_symbolic(symbolic, "u_range[1]", u_range.second);
note_symbolic(symbolic, "v_range[0]", v_range.first);
note_symbolic(symbolic, "v_range[1]", v_range.second);
for (std::size_t i = 0; i < 3; ++i) {
const std::string index = "[" + std::to_string(i) + "]";
note_symbolic(symbolic, "origin" + index, options.origin[i]);
note_symbolic(symbolic, "axis" + index, options.axis[i]);
if (options.x_direction)
note_symbolic(symbolic, "x_direction" + index, (*options.x_direction)[i]);
}
note_symbolic(symbolic, "tolerance", options.tolerance);
}
} // namespace
Face make_cylindrical_surface_rface(const Scalar& radius, const ScalarRange& u_range, const ScalarRange& v_range,
@@ -137,75 +229,18 @@ Face make_cylindrical_surface_rface(const Scalar& radius, const ScalarRange& u_r
"Pass increasing finite U bounds as unitless raw radians.",
"Keep the U span at or below one revolution and provide non-parallel axis directions."}};
return operator_scope(kSpec, [&] {
require_dimension(radius, UnitDimension::Length, "radius must use model length units");
for (const Scalar* value : {&u_range.first, &u_range.second})
require_dimension(*value, UnitDimension::Dimensionless,
"u_range must use unitless raw radians; unit-aware angle values evaluate in degrees");
for (const Scalar* value : {&v_range.first, &v_range.second})
require_dimension(*value, UnitDimension::Length, "v_range must use model length units");
require_dimension(options.tolerance, UnitDimension::Length, "tolerance must use model length units");
const double radius_value = radius.value();
const std::pair<double, double> u{u_range.first.value(), u_range.second.value()};
const std::pair<double, double> v{v_range.first.value(), v_range.second.value()};
const double tolerance_value = options.tolerance.value();
if (!std::isfinite(radius_value) || radius_value <= 0.0)
throw ValueError("radius must be a positive finite value");
if (!std::isfinite(u.first) || !std::isfinite(u.second))
throw ValueError("u_range must contain two finite values");
if (!std::isfinite(v.first) || !std::isfinite(v.second))
throw ValueError("v_range must contain two finite values");
const double u_span = u.second - u.first;
const double v_span = v.second - v.first;
if (u_span <= Precision::PConfusion() || u_span > 2.0 * kPi + Precision::Angular())
throw ValueError("u_range must be increasing and span at most one revolution");
if (v_span <= Precision::Confusion())
throw ValueError("v_range must be increasing beyond kernel confusion");
if (!std::isfinite(tolerance_value) || tolerance_value <= 0.0)
throw ValueError("tolerance must be a positive finite value");
const Vec3 origin = evaluated(options.origin);
const Vec3 axis = evaluated(options.axis);
// A non-finite axis has no default X; the finite check below reports it.
const Vec3 x_direction = options.x_direction ? evaluated(*options.x_direction)
: axis.is_finite() ? default_plane_x_direction(axis)
: axis;
if (!origin.is_finite() || !axis.is_finite() || !x_direction.is_finite())
throw ValueError("origin, axis, and x_direction must be finite 3D values");
const double axis_norm = axis.norm();
const double x_norm = x_direction.norm();
if (axis_norm <= tol::kDegenerateNorm || x_norm <= tol::kDegenerateNorm)
throw ValueError("axis and x_direction must be non-zero");
if (std::abs(axis.dot(x_direction)) / (axis_norm * x_norm) >= 1.0 - tol::kParallelCosineGap)
throw ValueError("axis and x_direction must not be parallel");
check_cylinder_dimensions(radius, u_range, v_range, options);
const CylinderRanges r = checked_cylinder_ranges(radius, u_range, v_range, options);
const CylinderFrame f = checked_cylinder_frame(options);
const CoordinateSystem& cs = current_cs();
const TopoDS_Face face = cylindrical_face(radius_value, u, v, cs.transform_point(origin), cs.transform_vector(axis),
cs.transform_vector(x_direction), tolerance_value);
const TopoDS_Face face =
cylindrical_face(r.radius, r.u, r.v, cs.transform_point(f.origin), cs.transform_vector(f.axis),
cs.transform_vector(f.x_direction), r.tolerance);
Value params = Value::object();
params.set("radius", radius_value);
params.set("u_range", Value(Value::Array{u.first, u.second}));
params.set("v_range", Value(Value::Array{v.first, v.second}));
params.set("origin", vec_value(origin));
params.set("axis", vec_value(axis));
params.set("x_direction", options.x_direction ? vec_value(x_direction) : Value());
params.set("tolerance", tolerance_value);
params.set("tag_prefix", to_value(options.tag_prefix));
Value params;
SymbolicArgs symbolic;
note_symbolic(symbolic, "radius", radius);
note_symbolic(symbolic, "u_range[0]", u_range.first);
note_symbolic(symbolic, "u_range[1]", u_range.second);
note_symbolic(symbolic, "v_range[0]", v_range.first);
note_symbolic(symbolic, "v_range[1]", v_range.second);
for (std::size_t i = 0; i < 3; ++i) {
const std::string index = "[" + std::to_string(i) + "]";
note_symbolic(symbolic, "origin" + index, options.origin[i]);
note_symbolic(symbolic, "axis" + index, options.axis[i]);
if (options.x_direction)
note_symbolic(symbolic, "x_direction" + index, (*options.x_direction)[i]);
}
note_symbolic(symbolic, "tolerance", options.tolerance);
record_cylinder_args(radius, u_range, v_range, options, r, f, params, symbolic);
return finalize_surface_output(Face(face), FaceOutput{.record = {.op = "make_cylindrical_surface_rface",
.params = std::move(params),
.symbolic = std::move(symbolic)},
+102 -78
View File
@@ -121,96 +121,120 @@ std::string Shape::repr() const {
return "Shape()";
}
namespace {
// Each helper appends the multi-line description of one kind (the layout of the Python __str__).
void describe_vertex(std::string& out, const Shape& shape, const std::string& pad) {
const Vec3 c = Vertex(shape).coordinates();
append(out, pad + "Vertex:");
append(out, pad + " coordinates: [" + f3(c.x) + ", " + f3(c.y) + ", " + f3(c.z) + "]");
}
void describe_edge(std::string& out, const Shape& shape, const std::string& pad) {
const Edge e(shape);
append(out, pad + "Edge:");
append(out, pad + " length: " + f3(e.length()));
try {
const Vec3 a = e.start_vertex().coordinates(), b = e.end_vertex().coordinates();
append(out, pad + " vertices:");
append(out, pad + " start: (" + g6(a.x) + ", " + g6(a.y) + ", " + g6(a.z) + ")");
append(out, pad + " end: (" + g6(b.x) + ", " + g6(b.y) + ", " + g6(b.z) + ")");
} catch (const std::exception&) {
append(out, pad + " vertices: [unable to retrieve, usually a closed edge]");
}
}
void describe_wire(std::string& out, const Shape& shape, const std::string& pad, int indent) {
const Wire w(shape);
const auto edges = w.edges();
append(out, pad + "Wire:");
append(out, pad + " edge_count: " + std::to_string(edges.size()));
append(out, pad + std::string(" closed: ") + (w.is_closed() ? "True" : "False"));
if (!edges.empty()) {
append(out, pad + " edges:");
for (std::size_t i = 0; i < edges.size(); ++i) {
append(out, pad + " edge_" + std::to_string(i) + ":");
append(out, edges[i].to_string(indent + 3));
}
}
}
// Normal and wires may fail to evaluate on degenerate faces; each failure prints "[unable to retrieve]".
void describe_face(std::string& out, const Shape& shape, const std::string& pad, int indent) {
const Face f(shape);
append(out, pad + "Face:");
append(out, pad + " area: " + f3(f.area()) + ", center: " + vec_repr(f.center()));
try {
const Vec3 n = f.normal_at();
append(out, pad + " normal: [" + f3(n.x) + ", " + f3(n.y) + ", " + f3(n.z) + "]");
} catch (const std::exception&) {
append(out, pad + " normal: [unable to retrieve]");
}
try {
append(out, pad + " outer_wire:");
append(out, f.outer_wire().to_string(indent + 2));
} catch (const std::exception&) {
append(out, pad + " outer_wire: [unable to retrieve]");
}
try {
for (const Wire& inner : f.inner_wires()) {
append(out, pad + " inner_wire:");
append(out, inner.to_string(indent + 2));
}
} catch (const std::exception&) {
append(out, pad + " inner_wires: [unable to retrieve]");
}
}
void describe_solid(std::string& out, const Shape& shape, const std::string& pad, int indent) {
const Solid s(shape);
const auto faces = s.faces();
append(out, pad + "Solid:");
append(out, pad + " volume: " + f3(s.volume()));
append(out, pad + " face_count: " + std::to_string(faces.size()));
append(out, pad + " edge_count: " + std::to_string(s.edges().size()));
if (!faces.empty()) {
append(out, pad + " faces:");
for (std::size_t i = 0; i < faces.size(); ++i) {
append(out, pad + " face_" + std::to_string(i) + ":");
append(out, faces[i].to_string(indent + 3));
}
}
}
void describe_compound(std::string& out, const Shape& shape, const std::string& pad) {
const Compound c(shape);
append(out, pad + "Compound:");
append(out, pad + " solid_count: " + std::to_string(c.solids().size()));
append(out, pad + " volume: " + f3(c.volume()));
}
} // namespace
std::string Shape::to_string(int indent) const {
const std::string pad = spaces(indent);
std::string out;
switch (kind()) {
case Kind::Vertex: {
const Vec3 c = Vertex(*this).coordinates();
append(out, pad + "Vertex:");
append(out, pad + " coordinates: [" + f3(c.x) + ", " + f3(c.y) + ", " + f3(c.z) + "]");
case Kind::Vertex:
describe_vertex(out, *this, pad);
break;
}
case Kind::Edge: {
const Edge e(*this);
append(out, pad + "Edge:");
append(out, pad + " length: " + f3(e.length()));
try {
const Vec3 a = e.start_vertex().coordinates(), b = e.end_vertex().coordinates();
append(out, pad + " vertices:");
append(out, pad + " start: (" + g6(a.x) + ", " + g6(a.y) + ", " + g6(a.z) + ")");
append(out, pad + " end: (" + g6(b.x) + ", " + g6(b.y) + ", " + g6(b.z) + ")");
} catch (const std::exception&) {
append(out, pad + " vertices: [unable to retrieve, usually a closed edge]");
}
case Kind::Edge:
describe_edge(out, *this, pad);
break;
}
case Kind::Wire: {
const Wire w(*this);
const auto edges = w.edges();
append(out, pad + "Wire:");
append(out, pad + " edge_count: " + std::to_string(edges.size()));
append(out, pad + std::string(" closed: ") + (w.is_closed() ? "True" : "False"));
if (!edges.empty()) {
append(out, pad + " edges:");
for (std::size_t i = 0; i < edges.size(); ++i) {
append(out, pad + " edge_" + std::to_string(i) + ":");
append(out, edges[i].to_string(indent + 3));
}
}
case Kind::Wire:
describe_wire(out, *this, pad, indent);
break;
}
case Kind::Face: {
const Face f(*this);
append(out, pad + "Face:");
append(out, pad + " area: " + f3(f.area()) + ", center: " + vec_repr(f.center()));
try {
const Vec3 n = f.normal_at();
append(out, pad + " normal: [" + f3(n.x) + ", " + f3(n.y) + ", " + f3(n.z) + "]");
} catch (const std::exception&) {
append(out, pad + " normal: [unable to retrieve]");
}
try {
append(out, pad + " outer_wire:");
append(out, f.outer_wire().to_string(indent + 2));
} catch (const std::exception&) {
append(out, pad + " outer_wire: [unable to retrieve]");
}
try {
for (const Wire& inner : f.inner_wires()) {
append(out, pad + " inner_wire:");
append(out, inner.to_string(indent + 2));
}
} catch (const std::exception&) {
append(out, pad + " inner_wires: [unable to retrieve]");
}
case Kind::Face:
describe_face(out, *this, pad, indent);
break;
}
case Kind::Shell:
return repr();
case Kind::Solid: {
const Solid s(*this);
const auto faces = s.faces();
append(out, pad + "Solid:");
append(out, pad + " volume: " + f3(s.volume()));
append(out, pad + " face_count: " + std::to_string(faces.size()));
append(out, pad + " edge_count: " + std::to_string(s.edges().size()));
if (!faces.empty()) {
append(out, pad + " faces:");
for (std::size_t i = 0; i < faces.size(); ++i) {
append(out, pad + " face_" + std::to_string(i) + ":");
append(out, faces[i].to_string(indent + 3));
}
}
case Kind::Solid:
describe_solid(out, *this, pad, indent);
break;
}
case Kind::Compound: {
const Compound c(*this);
append(out, pad + "Compound:");
append(out, pad + " solid_count: " + std::to_string(c.solids().size()));
append(out, pad + " volume: " + f3(c.volume()));
case Kind::Compound:
describe_compound(out, *this, pad);
break;
}
}
append(out, tags_and_metadata(*this, indent + 1));
return out;