brep_kernel/feature_pipeline/ports.rs
1//! PORTS — a part's declared connection points, as PART DATA rather than
2//! history features.
3//!
4//! # The block
5//!
6//! A part document carries `ports` as a sibling of `features`, beside the eCAD
7//! `symbol` and `pads` blocks:
8//!
9//! ```json
10//! "ports": [
11//! { "name": "J1", "purpose": "wiring",
12//! "points": [ { "name": "VCC", "transform": { … }, "pointRef": "Body_PZ" } ] }
13//! ]
14//! ```
15//!
16//! A port is a NAMED GROUP of connection points with one `purpose` — `pcb`,
17//! `wiring`, `piping`, or anything else a later slice invents; the kernel
18//! carries the string and never enumerates it. One part may declare several
19//! ports with different purposes (a valve with a piping port and a wiring port
20//! for its pressure sensor). None of this is a feature: there is no history
21//! row, no dialog, no icon and no schema-catalogue entry.
22//!
23//! # Addressing
24//!
25//! A connection point is addressed `[<occurrence chain>:]<port>.<point>` —
26//! `J1.VCC` in its own part, `ACOMP3:J1.VCC` once placed, `ACOMP7:ACOMP1:J1.VCC`
27//! at depth. `:` is the occurrence namespace the assembly lane already speaks
28//! (`component::namespaced`, peeled by `split_component_namespace`); `.`
29//! separates the port group from the point. The NAME is the identity — there is
30//! no second hidden id — so `:`, `.` and `/` are refused inside a port or point
31//! name (`/` because the harness routing graph keys its nodes `{address}/A`).
32//!
33//! The address is the key in [`SceneMap::ports`], so every existing consumer —
34//! `wireHarness` `from`/`to`, a spline anchor's `attachment.portRef`, a sketch
35//! on the point's frame — refers to a connection point exactly as it referred
36//! to a PORT feature id before, only with a name a user can read.
37//!
38//! # One symbol UNIT per port group
39//!
40//! A symbol pin binds to a connection point BY NAME (`part_pins.rs`). With
41//! several port groups `J1.1` and `J2.1` are both "point 1", so the name alone
42//! cannot say which. The part's SYMBOL says it instead: eCAD's `Symbol` already
43//! carries `unit_count`, KiCad's own model for a multi-unit device, and ONE
44//! SYMBOL UNIT MAPS TO ONE PORT GROUP. Pin `1` of unit 1 is `J1.1` and pin `1`
45//! of unit 2 is `J2.1`, so pin labels stay short and two identical headers on
46//! one part are ordinary rather than a collision.
47//!
48//! [`unit_map`] states the mapping:
49//!
50//! - a group may name its unit with `symbolUnit` (1-based), and that is the
51//! mapping, written down;
52//! - a document with ONE group and no `symbolUnit` anywhere maps that group to
53//! unit 1. This is the ordinary single-group part, and it declares nothing;
54//! - a document with SEVERAL groups binds only the groups that name a unit.
55//! Position is deliberately NOT a fallback here: a piping component declaring
56//! its piping port first and the wiring port of its pressure sensor second
57//! would otherwise bind the sensor's pins into the piping port. A group with
58//! no unit is not a schematic thing at all, which is exactly right for that
59//! piping port.
60//!
61//! Disagreements are REPORTED, never refused, and each names what it concerns:
62//! a unit with no group ([`UnitProblem::UnitWithoutGroup`] — its pins can bind
63//! to nothing), a `symbolUnit` past the symbol's `unit_count`, and two groups
64//! claiming one unit. `unit_count` 0 reads as 1, which is what a symbol written
65//! before units existed carries.
66//!
67//! # A placement is an OFFSET IN A SEAT
68//!
69//! A point may name geometry that places it: `pointRef` locates it,
70//! `directionRef` turns it. Those two used to REPLACE the typed placement,
71//! which made picking a reference the end of the conversation — there was
72//! nothing left to adjust, and the `transform` beside them was dead data.
73//!
74//! They now supply a SEAT ([`seat_of`]): a [`Frame`] whose origin is where the
75//! reference puts the point and whose **x_axis** is the direction it gives
76//! (x, because a point's direction is its rotation applied to +X, the
77//! convention every feature transform reads — see
78//! [`Frame::from_origin_direction`]). The point's own `transform` is then read
79//! IN that frame: `position` along the seat's three axes, `rotationEuler`
80//! composed onto its basis. So "on this face, 2 mm off it, turned 30 degrees"
81//! is one point with a reference and a small offset, and moving the face
82//! carries all of it.
83//!
84//! A point that names NOTHING has the WORLD seat — origin at the part origin,
85//! the world axes — in which an offset is an absolute placement. That is what
86//! a document written before the seat existed says, and it reads exactly as it
87//! did. A reference that seats the origin but implies no direction (a vertex,
88//! a bare scene point) keeps the world axes too.
89//!
90//! What a reference may BE is the kernel's own analytic vocabulary
91//! ([`crate::SelectionGeometry`], the same one an assembly constraint and a
92//! PMI annotation measure against): a planar face seats on its plane along its
93//! normal, a cylindrical face on its axis, a CIRCULAR edge at its CENTRE along
94//! its axis, a straight edge at its chord midpoint, a vertex
95//! (`{solid}@x,y,z`) at the vertex. A face or edge the analytic lane cannot
96//! describe falls back to the parametric midpoint and the chord this module
97//! always read.
98//!
99//! # Resolved AFTER history
100//!
101//! [`finish_history_run`] runs at the tail of every history run, after the
102//! assembly solve and before the wire-harness router. That is deliberate: a
103//! port point may reference ANY geometry in the part without a history-ordering
104//! rule, because by the time it resolves the whole part is built. The tail is
105//! authoritative: it resolves every point and overwrites whatever was there.
106//!
107//! There is ONE deviation, and it is a fixed two-phase, not an ordering rule.
108//! [`seed_history_run`] publishes, BEFORE the walk, every point whose placement
109//! is ALREADY FULLY DETERMINED — no `pointRef`, no `directionRef`, no
110//! `mapsTo`, so nothing the walk builds can move it. A SPLINE in the same
111//! document can then attach to it, and a sketch can sit on its frame, which is
112//! the whole standalone-harness workflow. A point that DOES reference geometry
113//! stays tail-only: a same-document spline attached to one reports the address
114//! `unresolved` and the harness lists it as a segment problem, by name, rather
115//! than quietly routing to a stale placement. In an assembly the question does
116//! not arise — a placed component's points arrive with the component, during
117//! the walk.
118//!
119//! # Assemblies declare DOWN
120//!
121//! An assembly declares its own ports and maps each point to a descendant's
122//! point with `mapsTo`: `J1.VCC -> ACOMP2:J5.VCC`. The mapped point takes the
123//! target's resolved placement, so the interface moves with the child. Depth is
124//! unbounded because the target is just another address.
125//!
126//! # Encapsulation
127//!
128//! A PCB assembly is a BOUNDARY: its child components are not directly
129//! wireable, and the only way to reach inside is a port the board itself
130//! declares. An ordinary mechanical assembly is TRANSPARENT — an enclosure
131//! holding a motor and a sensor does not hide them.
132//!
133//! The mark is [`document_is_boundary`]: the explicit `portBoundary` flag when
134//! the document sets one, else derived — a document carrying a `pcb` block is a
135//! board and therefore a boundary. Boundary is INDEPENDENT of `purpose`: a
136//! terminal block on a board carries wiring-purpose points and must still be
137//! declared at board level before anything may wire to it, so purpose filters
138//! what KIND of connection a point is, never whether it is reachable.
139//!
140//! The filter is applied at EXPORT, in [`export_ports`]: what a part's library
141//! entry carries is what a parent can see. A boundary part exports only the
142//! points it declares itself; a transparent part exports everything its run
143//! published, descendants included. `attach_component_ports` then namespaces
144//! whatever arrived, and arbitrary depth falls out of the address.
145
146use std::collections::{BTreeMap, BTreeSet};
147
148use serde::{Deserialize, Serialize};
149
150use crate::feature_pipeline::features::common;
151use crate::feature_pipeline::{
152 Axis, Env, FeatureResult, Frame, HistoryRequest, PortKind, PortRecord, SceneMap, ScenePoint,
153};
154use crate::{make_line, SelectionGeometry, Vec3};
155
156#[path = "ports_contact.rs"]
157mod contact;
158pub use contact::{contact_body_axis, contact_body_end, contact_body_solid, ContactAxis, ContactRule, PortContactRow};
159
160/// The id of the tail's appended result (never a history feature). The scene
161/// entities a declared point publishes ride it, so the display pipeline draws
162/// and picks a connection point exactly as it draws a feature's curves.
163pub const PORTS_FEATURE_ID: &str = "Ports";
164/// The type of the appended tail result.
165pub const PORTS_FEATURE_TYPE: &str = "PORTS";
166
167/// The part document's top-level key for its declared ports.
168pub const PORTS_BLOCK: &str = "ports";
169/// The part document's top-level key for the explicit encapsulation flag.
170pub const BOUNDARY_KEY: &str = "portBoundary";
171/// What separates a port group from a point in an address.
172pub const ADDRESS_SEPARATOR: char = '.';
173/// Characters a port or point name may not contain: the occurrence namespace
174/// separator, the address separator, and the harness graph's side separator.
175pub const RESERVED: [char; 3] = [':', '.', '/'];
176
177/// Default straight run a wire keeps from a connection point before it may bend.
178pub const DEFAULT_EXTENSION: f64 = 2.0;
179/// Default length of the drawn point line.
180pub const DEFAULT_DISPLAY_LENGTH: f64 = 6.0;
181/// The shortest drawn line — a zero-length line would publish no path.
182const MIN_DISPLAY_LENGTH: f64 = 0.1;
183
184// ===========================================================================
185// The block as a document declares it
186// ===========================================================================
187
188/// One declared port: a named group of connection points with one purpose.
189#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
190pub struct PortDeclaration {
191 /// The group name (`J1`), part-local and unique within the document.
192 #[serde(default)]
193 pub name: String,
194 /// What kind of connection these points are: `pcb`, `wiring`, `piping`, …
195 /// Free-form and deliberately not an enum — the set is extensible.
196 #[serde(default)]
197 pub purpose: String,
198 /// The SYMBOL UNIT whose pins bind into this group, 1-based. `None` means
199 /// derive it — see [`unit_map`]. A group that maps to no unit takes no
200 /// pins, which is what a piping port wants.
201 #[serde(default, rename = "symbolUnit", skip_serializing_if = "Option::is_none")]
202 pub symbol_unit: Option<u32>,
203 #[serde(default)]
204 pub points: Vec<PortPoint>,
205}
206
207/// One connection point of a declared port.
208#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
209pub struct PortPoint {
210 /// The point name (`VCC`), part-local and unique within its port.
211 #[serde(default)]
212 pub name: String,
213 /// `{ position, rotationEuler }` — the placement when no reference seats
214 /// it. The direction is the rotation applied to `+X`, exactly as every
215 /// feature transform reads. Components may be expression strings.
216 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
217 pub transform: serde_json::Value,
218 /// Optional geometry that LOCATES the point: a scene point, a plane/datum
219 /// frame origin, a face midpoint or an edge. Unresolved is reported, never
220 /// fatal — the transform placement stands.
221 #[serde(
222 default,
223 rename = "pointRef",
224 deserialize_with = "lenient_text",
225 skip_serializing_if = "Option::is_none"
226 )]
227 pub point_ref: Option<String>,
228 /// Optional geometry that sets the DIRECTION: a face normal, a frame
229 /// normal, an axis or an edge chord. A `pointRef` naming a face seats the
230 /// direction too when this is absent.
231 #[serde(
232 default,
233 rename = "directionRef",
234 deserialize_with = "lenient_text",
235 skip_serializing_if = "Option::is_none"
236 )]
237 pub direction_ref: Option<String>,
238 /// Optional: a SOLID of the part that IS this point's contact (a pin that
239 /// is a whole body). It seats what `pointRef`/`directionRef` leave empty:
240 /// the origin at the body's wire-side end, the direction along its axis,
241 /// outward ([`contact_body_axis`]). Absent reads exactly as before.
242 #[serde(
243 default,
244 rename = "contactBody",
245 deserialize_with = "lenient_text",
246 skip_serializing_if = "Option::is_none"
247 )]
248 pub contact_body: Option<String>,
249 #[serde(default, rename = "reverseDirection", skip_serializing_if = "is_false")]
250 pub reverse_direction: bool,
251 /// The straight run a wire keeps before it may bend (a spline anchor
252 /// attached here takes it as its forward/backward distance).
253 #[serde(default, deserialize_with = "lenient_number", skip_serializing_if = "Option::is_none")]
254 pub extension: Option<f64>,
255 #[serde(
256 default,
257 rename = "displayLength",
258 deserialize_with = "lenient_number",
259 skip_serializing_if = "Option::is_none"
260 )]
261 pub display_length: Option<f64>,
262 /// ASSEMBLY declaration: the descendant point this one IS, by address
263 /// (`ACOMP2:J5.VCC`). The mapped point takes the target's resolved
264 /// placement, so the interface follows the child.
265 #[serde(
266 default,
267 rename = "mapsTo",
268 deserialize_with = "lenient_text",
269 skip_serializing_if = "Option::is_none"
270 )]
271 pub maps_to: Option<String>,
272}
273
274fn is_false(value: &bool) -> bool {
275 !*value
276}
277
278/// A reference field (`pointRef`, `directionRef`, `contactBody`, `mapsTo`)
279/// read leniently. These are names, so a JSON number or boolean is read as
280/// its text (`0` -> `"0"`), and null as absent. Strict `Option<String>` let
281/// one stray scalar fail the WHOLE block: a user typed
282/// `0` into a seat field, the panel stored `"pointRef": 0.0`, every reader
283/// of the block saw no groups at all, and the part could not be qualified
284/// or re-edited. An unresolvable name is reported per point, never fatal.
285fn lenient_text<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
286where
287 D: serde::Deserializer<'de>,
288{
289 use serde_json::Value;
290 Ok(match Value::deserialize(deserializer)? {
291 Value::String(text) => Some(text),
292 Value::Number(number) => Some(match number.as_f64() {
293 // `0.0` was typed as `0`: give the name back as typed.
294 Some(value) if value.fract() == 0.0 && value.abs() < 1e15 => format!("{}", value as i64),
295 _ => number.to_string(),
296 }),
297 Value::Bool(flag) => Some(flag.to_string()),
298 // Null, or a shape no name has: absent, so the point keeps its
299 // transform placement and its group stays readable.
300 _ => None,
301 })
302}
303
304/// A length field (`extension`, `displayLength`) read leniently: a number,
305/// or text that parses as one; anything else reads as absent (the default),
306/// rather than failing the whole block as a strict `Option<f64>` did.
307fn lenient_number<'de, D>(deserializer: D) -> Result<Option<f64>, D::Error>
308where
309 D: serde::Deserializer<'de>,
310{
311 use serde_json::Value;
312 Ok(match Value::deserialize(deserializer)? {
313 Value::Number(number) => number.as_f64(),
314 Value::String(text) => text.trim().parse::<f64>().ok().filter(|value| value.is_finite()),
315 _ => None,
316 })
317}
318
319// ===========================================================================
320// Addresses
321// ===========================================================================
322
323/// The address of a point within its own part: `{port}.{point}`.
324pub fn address(port: &str, point: &str) -> String {
325 format!("{port}{ADDRESS_SEPARATOR}{point}")
326}
327
328/// Split a PART-LOCAL address into `(port, point)`. `None` when it carries no
329/// separator — a WAYPOINT feature id, for one, which is an address in its own
330/// right and belongs to no port.
331pub fn split_address(address: &str) -> Option<(&str, &str)> {
332 address.split_once(ADDRESS_SEPARATOR)
333}
334
335/// Why a name cannot be used, or `None` when it can.
336fn name_problem(kind: &str, name: &str) -> Option<String> {
337 if name.trim().is_empty() {
338 return Some(format!("a {kind} has no name"));
339 }
340 if name.contains(RESERVED) {
341 return Some(format!(
342 "{kind} '{name}' contains a reserved character (':', '.' or '/')"
343 ));
344 }
345 None
346}
347
348// ===========================================================================
349// Symbol units and port groups
350// ===========================================================================
351
352/// Something about the unit-to-group mapping that does not hold. Never fatal:
353/// what maps still binds, and this says what did not.
354#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
355#[serde(tag = "problem", rename_all = "kebab-case")]
356pub enum UnitProblem {
357 /// The symbol has this unit and no port group takes it, so its pins bind
358 /// to nothing.
359 UnitWithoutGroup { unit: u32 },
360 /// A group names a unit the symbol does not have (`0`, or past
361 /// `unit_count`).
362 UnitOutOfRange { port: String, unit: u32, units: u32 },
363 /// Two groups name one unit; the FIRST in block order keeps it.
364 UnitContested { unit: u32, ports: Vec<String> },
365}
366
367impl UnitProblem {
368 pub fn message(&self) -> String {
369 match self {
370 UnitProblem::UnitWithoutGroup { unit } => {
371 format!("symbol unit {unit} has no port group, so its pins bind to nothing")
372 }
373 UnitProblem::UnitOutOfRange { port, unit, units } => format!(
374 "port '{port}' names symbol unit {unit}, and the symbol has {units}"
375 ),
376 UnitProblem::UnitContested { unit, ports } => {
377 format!("ports {} all name symbol unit {unit}", ports.join(", "))
378 }
379 }
380 }
381}
382
383/// Which port group each symbol unit binds its pins into, and everything about
384/// the mapping that does not hold. The map is `unit (1-based) -> index into
385/// `declarations``; a unit absent from it binds no pins.
386///
387/// `unit_count` is the symbol's, and `0` reads as `1`. The rule is in this
388/// module's docs; in short, an explicit `symbolUnit` decides, one group with
389/// none takes unit 1, and several groups with none bind nothing.
390///
391/// `has_symbol` is whether the document carries a symbol at all. A 3D-only part
392/// has no units, so it reports no missing ones.
393pub fn unit_map(
394 declarations: &[PortDeclaration],
395 unit_count: u32,
396 has_symbol: bool,
397) -> (BTreeMap<u32, usize>, Vec<UnitProblem>) {
398 let units = unit_count.max(1);
399 let mut map: BTreeMap<u32, usize> = BTreeMap::new();
400 let mut problems = Vec::new();
401 let mut contested: BTreeMap<u32, Vec<String>> = BTreeMap::new();
402
403 let explicit: Vec<(usize, u32)> = declarations
404 .iter()
405 .enumerate()
406 .filter_map(|(index, group)| group.symbol_unit.map(|unit| (index, unit)))
407 .collect();
408 for (index, unit) in &explicit {
409 let port = declarations[*index].name.trim().to_string();
410 if *unit == 0 || *unit > units {
411 problems.push(UnitProblem::UnitOutOfRange { port, unit: *unit, units });
412 continue;
413 }
414 match map.get(unit) {
415 Some(first) => contested
416 .entry(*unit)
417 .or_insert_with(|| vec![declarations[*first].name.trim().to_string()])
418 .push(port),
419 None => {
420 map.insert(*unit, *index);
421 }
422 }
423 }
424 for (unit, ports) in contested {
425 problems.push(UnitProblem::UnitContested { unit, ports });
426 }
427 // The ordinary part: one group, nothing written down, unit 1.
428 if explicit.is_empty() && declarations.len() == 1 {
429 map.insert(1, 0);
430 }
431 if has_symbol {
432 for unit in 1..=units {
433 if !map.contains_key(&unit) {
434 problems.push(UnitProblem::UnitWithoutGroup { unit });
435 }
436 }
437 }
438 (map, problems)
439}
440
441// ===========================================================================
442// The tail's report
443// ===========================================================================
444
445/// A [`Frame`] as the ports REPORT carries it: four plain triples rather than
446/// [`Vec3`]s, because a report is compared and serialized (a `Vec3` carries no
447/// `PartialEq`, by choice, and this is the shape the app and the verifier
448/// read).
449#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
450pub struct PortSeat {
451 pub origin: [f64; 3],
452 /// The seat's x axis, which is the direction the reference gives — see
453 /// [`Frame::from_origin_direction`].
454 pub x: [f64; 3],
455 pub y: [f64; 3],
456 pub z: [f64; 3],
457}
458
459impl PortSeat {
460 pub fn to_frame(self) -> Frame {
461 let v = |a: [f64; 3]| Vec3::new(a[0], a[1], a[2]);
462 Frame {
463 origin: v(self.origin),
464 x_axis: v(self.x),
465 y_axis: v(self.y),
466 z_axis: v(self.z),
467 }
468 }
469}
470
471impl From<Frame> for PortSeat {
472 fn from(frame: Frame) -> Self {
473 let a = |v: Vec3| [v.x, v.y, v.z];
474 PortSeat {
475 origin: a(frame.origin),
476 x: a(frame.x_axis),
477 y: a(frame.y_axis),
478 z: a(frame.z_axis),
479 }
480 }
481}
482
483/// One resolved connection point, as the tail publishes it.
484#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
485pub struct PortPointRow {
486 /// The part-local address (`J1.VCC`) — the [`SceneMap::ports`] key.
487 pub address: String,
488 pub port: String,
489 pub point: String,
490 pub purpose: String,
491 /// The descendant address this point maps to, when it declares one.
492 #[serde(default, skip_serializing_if = "Option::is_none")]
493 pub maps_to: Option<String>,
494 /// The frame this point's `transform` was read as an offset IN
495 /// ([`seat_of`]) — the world frame for a point that names no reference.
496 ///
497 /// Report-only, and deliberately not on [`PortRecord`]: a seat is what the
498 /// last RUN made of the references, not something the document carries or
499 /// a library entry exports. The editor needs it to put a gizmo on the
500 /// point, because dragging one in world space has to be written back as an
501 /// offset in exactly this frame.
502 pub seat: PortSeat,
503 /// Where the point resolved, in world space (`record.point`).
504 pub position: [f64; 3],
505 /// The unit direction it resolved facing (`record.direction`).
506 pub direction: [f64; 3],
507 /// The contact body's axis and the end the wire took, for a point that
508 /// names one and whose body derives an axis. Absent otherwise.
509 #[serde(default, skip_serializing_if = "Option::is_none")]
510 pub contact: Option<PortContactRow>,
511 /// The point has NO wire end: its contact body derived none and it has no
512 /// other seat or offset of its own, so nothing is published for it (a
513 /// harness end there is unresolved) rather than a wire end at the part
514 /// origin. Its row stays so the point, and its problem, are still shown.
515 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
516 pub unplaced: bool,
517}
518
519/// What the ports tail resolved, and everything about the block that does not
520/// hold — a name it refused, a reference that resolved to nothing, a mapping
521/// whose target is not in the scene. Never fatal: a problem is reported and the
522/// point still publishes at whatever placement could be worked out, so nothing
523/// downstream vanishes (the same contract rule the features follow).
524#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
525pub struct PortsReport {
526 /// Whether this document encapsulates its children ([`document_is_boundary`]).
527 #[serde(default)]
528 pub boundary: bool,
529 pub points: Vec<PortPointRow>,
530 pub problems: Vec<String>,
531}
532
533// ===========================================================================
534// Encapsulation
535// ===========================================================================
536
537/// Whether a DOCUMENT hides its children behind its declared ports.
538///
539/// The explicit `portBoundary` flag decides when the document sets one. With no
540/// flag it is derived: a document carrying a `pcb` block is a board, and a
541/// board is a boundary by construction. Derivation alone could not mark a
542/// non-PCB enclosure; a flag alone would have to be set on every board by hand,
543/// which is exactly the case the user said holds "by construction".
544pub fn document_is_boundary(document: &serde_json::Value) -> bool {
545 match document.get(BOUNDARY_KEY).and_then(serde_json::Value::as_bool) {
546 Some(explicit) => explicit,
547 None => document.get("pcb").is_some_and(|block| !block.is_null()),
548 }
549}
550
551/// The same question for a parsed request (the tail's lane).
552pub fn request_is_boundary(request: &HistoryRequest) -> bool {
553 request.port_boundary.unwrap_or(request.pcb_present)
554}
555
556/// What a part's library entry carries out of its own run — the encapsulation
557/// filter, applied ONCE, here.
558///
559/// A TRANSPARENT part exports every port record its run published: its own
560/// declared points and, namespaced, every point its children brought. A
561/// BOUNDARY part exports only the points it declares itself, so a parent can
562/// reach its connectors and nothing else.
563pub fn export_ports(
564 scene_ports: &BTreeMap<String, PortRecord>,
565 declared: &[String],
566 boundary: bool,
567) -> BTreeMap<String, PortRecord> {
568 if !boundary {
569 return scene_ports.clone();
570 }
571 let declared: BTreeSet<&str> = declared.iter().map(String::as_str).collect();
572 scene_ports
573 .iter()
574 .filter(|(address, _)| declared.contains(address.as_str()))
575 .map(|(address, record)| (address.clone(), record.clone()))
576 .collect()
577}
578
579// ===========================================================================
580// Publishing one point's scene entities
581// ===========================================================================
582
583/// The drawn line for a connection point: a termination's wire leaves along the
584/// direction; a waypoint's wire passes through, so its line straddles the base
585/// point.
586pub fn port_line(record: &PortRecord) -> (Vec3, Vec3) {
587 let point = record.point;
588 let direction = record.direction;
589 let length = record.display_length;
590 match record.kind {
591 PortKind::Termination => (point, point.add(direction.scale(length))),
592 PortKind::Waypoint => (
593 point.sub(direction.scale(length * 0.5)),
594 point.add(direction.scale(length * 0.5)),
595 ),
596 }
597}
598
599/// Publish one connection point's scene entities under `address`: the record
600/// (`ports[address]`), its base point (`{address}:Base`), its axis and its
601/// frame (both `address`) and its drawn line (`{address}:PortLine`). A sketch
602/// on the frame is a connector face square to the wire.
603///
604/// The `Vec` side-channel form, for a FEATURE result (WAYPOINT, and the ACOMP
605/// that re-publishes a placed part's points).
606pub fn publish_port(
607 result: &mut crate::feature_pipeline::FeatureResult,
608 address: &str,
609 record: PortRecord,
610) -> Result<(), String> {
611 let (start, end) = port_line(&record);
612 result
613 .paths
614 .push((format!("{address}:PortLine"), vec![make_line(start, end)?]));
615 result
616 .points
617 .push((format!("{address}:Base"), ScenePoint::model(record.point)));
618 result.axes.push((
619 address.to_string(),
620 Axis { point: record.point, direction: record.direction },
621 ));
622 result.frames.push((
623 address.to_string(),
624 Frame::from_origin_normal(record.point, record.direction)?,
625 ));
626 result.ports.push((address.to_string(), record));
627 Ok(())
628}
629
630/// The same entities written straight into a scene — the ports tail and the
631/// component re-pose lane, which moves a placed part's points without
632/// re-running its feature.
633pub fn place_scene_port(
634 scene: &mut SceneMap,
635 address: &str,
636 record: PortRecord,
637) -> Result<(), String> {
638 let (start, end) = port_line(&record);
639 scene
640 .paths
641 .insert(format!("{address}:PortLine"), vec![make_line(start, end)?]);
642 scene
643 .points
644 .insert(format!("{address}:Base"), ScenePoint::model(record.point));
645 scene.axes.insert(
646 address.to_string(),
647 Axis { point: record.point, direction: record.direction },
648 );
649 scene.frames.insert(
650 address.to_string(),
651 Frame::from_origin_normal(record.point, record.direction)?,
652 );
653 scene.ports.insert(address.to_string(), record);
654 Ok(())
655}
656
657// ===========================================================================
658// The SEAT — what a reference resolves to, and the frame a placement sits in
659// ===========================================================================
660
661/// Where a reference sits, and the direction it implies when it has one.
662///
663/// The vocabulary is the kernel's own analytic one ([`SelectionGeometry`]), so
664/// a connection point seats on exactly what an assembly constraint and a PMI
665/// annotation measure against:
666///
667/// | picked | seats at | points along |
668/// |---|---|---|
669/// | a planar face | the face's boundary-AABB centre on its plane | its outward normal |
670/// | a cylindrical / conical face (a bore) | a point on its axis | its axis |
671/// | a spherical face | the centre | — |
672/// | a CIRCULAR edge (a hole rim) | the **centre** | its axis |
673/// | a straight edge | the chord midpoint | the chord |
674/// | a vertex (`{solid}@x,y,z`) | the vertex | — |
675/// | a scene point, a datum/plane frame, an axis | its own origin | its own normal / direction |
676///
677/// The scene-native names (points, frames, axes) are tried FIRST and keep the
678/// meaning they always had. Everything else goes through the analytic
679/// resolver, and a face or edge it calls unsupported (a freeform patch, a
680/// spline edge) falls back to what this module read before: a face's
681/// parametric midpoint and normal, an edge's start and chord.
682fn resolve_seat_reference(scene: &SceneMap, name: &str) -> Result<(Vec3, Option<Vec3>), String> {
683 if let Some(position) = scene.resolve_point(name) {
684 return Ok((position, None));
685 }
686 if let Some(frame) = scene.resolve_frame(name) {
687 return Ok((frame.origin, Some(frame.z_axis)));
688 }
689 if let Some(axis) = scene.resolve_axis(name) {
690 return Ok((axis.point, Some(axis.direction)));
691 }
692 match analytic_reference(scene, name) {
693 Some(Ok(geometry)) => Ok(seat_of_geometry(&geometry)),
694 Some(Err(problem)) => Err(problem),
695 None => Err(format!("'{name}' resolves to no geometry")),
696 }
697}
698
699/// [`resolve_seat_reference`]'s direction half: the same vocabulary, keeping
700/// only what implies a direction. A reference that implies none (a vertex, a
701/// sphere's centre, a bare scene point) is refused BY NAME rather than
702/// silently leaving the direction where it was.
703fn resolve_seat_direction(scene: &SceneMap, name: &str) -> Result<Vec3, String> {
704 if let Some(frame) = scene.resolve_frame(name) {
705 return Ok(frame.z_axis);
706 }
707 if let Some(axis) = scene.resolve_axis(name) {
708 return Ok(axis.direction);
709 }
710 if scene.resolve_point(name).is_some() {
711 return Err(format!("'{name}' is a point, which implies no direction"));
712 }
713 match analytic_reference(scene, name) {
714 Some(Ok(geometry)) => seat_of_geometry(&geometry)
715 .1
716 .ok_or_else(|| format!("'{name}' implies no direction")),
717 Some(Err(problem)) => Err(problem),
718 None => Err(format!("'{name}' resolves to no geometry")),
719 }
720}
721
722/// One analytic entity's seat: where it sits and the direction it implies.
723fn seat_of_geometry(geometry: &SelectionGeometry) -> (Vec3, Option<Vec3>) {
724 match geometry {
725 SelectionGeometry::Plane { origin, normal } => (*origin, Some(*normal)),
726 SelectionGeometry::Axis { origin, direction, .. } => (*origin, Some(*direction)),
727 SelectionGeometry::Sphere { center, .. } => (*center, None),
728 SelectionGeometry::Circle { center, axis, .. } => (*center, Some(*axis)),
729 SelectionGeometry::Line { origin, direction } => (*origin, Some(*direction)),
730 SelectionGeometry::Point { position } => (*position, None),
731 }
732}
733
734/// `name` as an ANALYTIC entity — a face, an edge, or a `{solid}@x,y,z` vertex
735/// reference — or `None` when the scene holds no such thing under that name.
736///
737/// `Some(Err(..))` is a name that DID resolve to topology the analytic lane
738/// cannot describe. A face or edge in that state falls back to this module's
739/// older reading rather than refusing the point: a freeform seat is worse than
740/// an analytic one and much better than none.
741fn analytic_reference(
742 scene: &SceneMap,
743 name: &str,
744) -> Option<Result<SelectionGeometry, String>> {
745 // A VERTEX carries no kernel name, so the viewport references one by its
746 // owning solid and world position — the same form PMI writes, resolved by
747 // the same helper (nearest topology vertex, snap-gated).
748 if name.contains('@') {
749 return Some(
750 crate::feature_pipeline::pmi::resolve::resolve_reference(scene, name)
751 .map_err(|error| error.to_string()),
752 );
753 }
754 if let Some(face) = scene.resolve_face(name) {
755 let analytic = crate::with_registered_solid_str(face.handle, |solid| {
756 Ok(crate::resolve_face_selection(solid, face.face_id))
757 });
758 return Some(match analytic {
759 Ok(Ok(geometry)) => Ok(geometry),
760 // Unsupported / failed: the parametric midpoint and normal, which
761 // is what a `pointRef` on a face has always meant here.
762 _ => common::face_point_normal(face).map(|(point, normal)| {
763 SelectionGeometry::Plane { origin: point, normal }
764 }),
765 });
766 }
767 if let Some(edge) = scene.resolve_edge(name) {
768 let analytic = crate::with_registered_solid_str(edge.handle, |solid| {
769 Ok(crate::resolve_edge_selection(solid, edge.edge_id))
770 });
771 return Some(match analytic {
772 Ok(Ok(geometry)) => Ok(geometry),
773 // A freeform edge: its start and chord, as before. A CLOSED one
774 // has a zero chord and refuses itself here rather than failing the
775 // whole point — which is what a circle used to do, before the
776 // analytic lane above started answering with its centre.
777 _ => common::edge_axis(edge).map(|axis| SelectionGeometry::Line {
778 origin: axis.point,
779 direction: axis.direction,
780 }),
781 });
782 }
783 None
784}
785
786/// The FRAME a connection point's placement is an offset in.
787///
788/// Its origin is where `pointRef` seats the point (the part origin when there
789/// is none) and its **x_axis** is the direction that seats it: `directionRef`
790/// when the point names one, else whatever `pointRef` implied, else +X. The
791/// point's own `transform` is then read IN this frame — `position` along its
792/// three axes, `rotationEuler` composed onto its basis — so a point seated on
793/// a face can be nudged 2 mm off it and turned 30 degrees on it without the
794/// reference being lost.
795///
796/// With NO reference at all the seat is the world frame, and a local offset in
797/// the world frame is an absolute placement: that is the case every document
798/// written before the seat existed is in, and it reads exactly as it did.
799///
800/// Problems are collected, never fatal. A reference that resolves to nothing
801/// leaves that half of the seat at its default and says so by name.
802pub fn seat_of(
803 point: &PortPoint,
804 scene: &SceneMap,
805) -> (Frame, Vec<String>) {
806 let (seat, problems, _, _) = seat_with_contact(point, scene);
807 (seat, problems)
808}
809
810/// [`seat_of`], plus what the point's contact body derived (when it names one
811/// that derives an axis). The body fills each half of the seat only where the
812/// explicit references leave it empty: origin `pointRef` -> the body's wire
813/// end -> the part origin; direction `directionRef` -> what `pointRef`
814/// implies -> the body's outward axis -> +X.
815fn seat_with_contact(
816 point: &PortPoint,
817 scene: &SceneMap,
818) -> (Frame, Vec<String>, Option<(String, ContactAxis, bool)>, Option<String>) {
819 let mut problems = Vec::new();
820 let mut origin = Vec3::new(0.0, 0.0, 0.0);
821 // `None` until a reference SUPPLIES one. A seated origin with no direction
822 // — a vertex, a bare scene point — keeps the world axes, so the point's
823 // own rotation still means what it means everywhere else in the document.
824 let mut direction: Option<Vec3> = None;
825
826 if let Some(reference) = trimmed(point.point_ref.as_deref()) {
827 match resolve_seat_reference(scene, reference) {
828 Ok((located, implied)) => {
829 origin = located;
830 if let Some(implied) = implied {
831 direction = Some(implied);
832 }
833 }
834 Err(problem) => problems.push(problem),
835 }
836 }
837 let mut given_direction = None;
838 if let Some(reference) = trimmed(point.direction_ref.as_deref()) {
839 match resolve_seat_direction(scene, reference) {
840 Ok(resolved) => {
841 direction = Some(resolved);
842 given_direction = Some(resolved);
843 }
844 Err(problem) => problems.push(problem),
845 }
846 }
847 // The contact body, below both references. `reverseDirection` on a
848 // body-seated origin takes the OTHER end (the wire still leaving outward)
849 // rather than flipping the wire back through the pin. A body with no
850 // distinct ends takes its end from the Direction, and the wire leaves
851 // along it (or against it, reversed).
852 let mut contact = None;
853 let mut body_problem = None;
854 if let Some(body) = trimmed(point.contact_body.as_deref()) {
855 let seats_origin = trimmed(point.point_ref.as_deref()).is_none();
856 match contact_body_end(scene, body, seats_origin && point.reverse_direction, given_direction) {
857 Ok(derived) => {
858 if seats_origin {
859 origin = derived.wire_end();
860 }
861 if direction.is_none() || (seats_origin && derived.rule == ContactRule::Direction) {
862 direction = Some(derived.outward());
863 }
864 contact = Some((body.to_string(), derived, seats_origin));
865 }
866 Err(problem) => {
867 if seats_origin {
868 body_problem = Some(problem.clone());
869 }
870 problems.push(problem);
871 }
872 }
873 }
874 // No direction, or one too degenerate to make a basis from: the WORLD axes
875 // at whatever origin was seated. With no references at all that is the
876 // world frame exactly, in which an offset IS an absolute placement — which
877 // is what every document written before the seat existed says.
878 let seat = match direction {
879 Some(direction) => Frame::from_origin_direction(origin, direction)
880 .unwrap_or_else(|_| Frame { origin, ..world_seat() }),
881 None => Frame { origin, ..world_seat() },
882 };
883 (seat, problems, contact, body_problem)
884}
885
886/// A local offset carried into world space by `seat`.
887pub fn seat_point(seat: &Frame, local: Vec3) -> Vec3 {
888 seat.origin
889 .add(seat.x_axis.scale(local.x))
890 .add(seat.y_axis.scale(local.y))
891 .add(seat.z_axis.scale(local.z))
892}
893
894/// A world position read back as an offset in `seat` — the inverse of
895/// [`seat_point`], which is what a gizmo drag writes. The basis is orthonormal,
896/// so the inverse is the transpose.
897pub fn unseat_point(seat: &Frame, world: Vec3) -> Vec3 {
898 unseat_vector(seat, world.sub(seat.origin))
899}
900
901/// A local DIRECTION carried into world space by `seat` (no translation).
902pub fn seat_vector(seat: &Frame, local: Vec3) -> Vec3 {
903 seat.x_axis
904 .scale(local.x)
905 .add(seat.y_axis.scale(local.y))
906 .add(seat.z_axis.scale(local.z))
907}
908
909/// A world direction read back in `seat`'s basis.
910pub fn unseat_vector(seat: &Frame, world: Vec3) -> Vec3 {
911 Vec3::new(
912 world.dot(seat.x_axis),
913 world.dot(seat.y_axis),
914 world.dot(seat.z_axis),
915 )
916}
917
918/// The world direction a point with this seat and this rotation faces: the
919/// rotation applied to +X (every feature transform's convention), carried
920/// through the seat's basis. With the world seat this is the rotated +X
921/// itself.
922pub fn seated_direction(seat: &Frame, rotation_deg: [f64; 3]) -> Vec3 {
923 let local = crate::feature_pipeline::features::datum::rotate_euler_xyz(
924 Vec3::new(1.0, 0.0, 0.0),
925 [
926 rotation_deg[0].to_radians(),
927 rotation_deg[1].to_radians(),
928 rotation_deg[2].to_radians(),
929 ],
930 );
931 seat_vector(seat, local)
932}
933
934/// A non-empty trimmed reference, or `None`.
935fn trimmed(value: Option<&str>) -> Option<&str> {
936 value.map(str::trim).filter(|text| !text.is_empty())
937}
938
939/// A `directionRef`'s unit direction, or `None` when the name resolves to
940/// nothing that implies one. The WAYPOINT feature's lane — a waypoint has no
941/// seat (it is a feature with its own transform), so it takes the direction
942/// alone and lists an unresolved name in its own report.
943pub fn resolve_direction(scene: &SceneMap, name: &str) -> Result<Option<Vec3>, String> {
944 Ok(resolve_seat_direction(scene, name).ok())
945}
946
947// ===========================================================================
948// The tail
949// ===========================================================================
950
951/// Publish, BEFORE the history walk, every declared point whose placement is
952/// already fully determined — see the module doc. Returns each published scene
953/// name with the CONTENT VERSION of the declaration behind it, so the
954/// incremental cache invalidates a feature that consumed the point when the
955/// declaration moves (without this a spline attached to a point would replay
956/// from cache at the point's old placement).
957pub fn seed_history_run(
958 request: &HistoryRequest,
959 scene: &mut SceneMap,
960 env: &Env,
961) -> Vec<(String, u64)> {
962 let mut seeded = Vec::new();
963 let mut ports_seen: BTreeSet<&str> = BTreeSet::new();
964 for declaration in &request.ports {
965 let port = declaration.name.trim();
966 if name_problem("port", port).is_some() || !ports_seen.insert(port) {
967 continue;
968 }
969 let mut points_seen: BTreeSet<&str> = BTreeSet::new();
970 for point in &declaration.points {
971 let name = point.name.trim();
972 if name_problem("point", name).is_some() || !points_seen.insert(name) {
973 continue;
974 }
975 if point.point_ref.is_some()
976 || point.direction_ref.is_some()
977 || point.maps_to.is_some()
978 || point.contact_body.is_some()
979 {
980 continue;
981 }
982 let Ok((record, _, _, _, _)) =
983 resolve_point(point, port, name, &declaration.purpose, scene, env)
984 else {
985 continue;
986 };
987 let address = address(port, name);
988 if place_scene_port(scene, &address, record).is_err() {
989 continue;
990 }
991 let version = declaration_version(port, &declaration.purpose, point);
992 for name in [
993 address.clone(),
994 format!("{address}:Base"),
995 format!("{address}:PortLine"),
996 ] {
997 seeded.push((name, version));
998 }
999 }
1000 }
1001 seeded
1002}
1003
1004/// The content version of one declared point: its port, its purpose and the
1005/// point itself. Two runs that declare the same point the same way produce the
1006/// same number, and any edit to it produces a different one.
1007fn declaration_version(port: &str, purpose: &str, point: &PortPoint) -> u64 {
1008 use std::hash::{Hash, Hasher};
1009 let mut hasher = std::collections::hash_map::DefaultHasher::new();
1010 port.hash(&mut hasher);
1011 purpose.hash(&mut hasher);
1012 serde_json::to_string(point).unwrap_or_default().hash(&mut hasher);
1013 hasher.finish()
1014}
1015
1016/// What the ports tail produced: its report, and the appended result the
1017/// display pipeline consumes.
1018#[derive(Debug, Default)]
1019pub struct PortsOutcome {
1020 pub report: Option<PortsReport>,
1021 pub result: Option<FeatureResult>,
1022}
1023
1024/// Resolve the request's `ports` block against the FINISHED scene and publish
1025/// every point. Runs after the assembly solve (so a mapped point reads its
1026/// child's posed placement) and before the wire-harness router (which routes
1027/// over what this published). Empty when the document declares no ports.
1028pub fn finish_history_run(
1029 request: &HistoryRequest,
1030 scene: &mut SceneMap,
1031 env: &Env,
1032) -> PortsOutcome {
1033 if request.ports.is_empty() {
1034 return PortsOutcome::default();
1035 }
1036 let mut result = FeatureResult::pass_through(
1037 PORTS_FEATURE_ID.to_string(),
1038 PORTS_FEATURE_TYPE.to_string(),
1039 );
1040 let mut report = PortsReport {
1041 boundary: request_is_boundary(request),
1042 ..PortsReport::default()
1043 };
1044 let mut ports_seen: BTreeSet<&str> = BTreeSet::new();
1045
1046 for declaration in &request.ports {
1047 let port = declaration.name.trim();
1048 if let Some(problem) = name_problem("port", port) {
1049 report.problems.push(problem);
1050 continue;
1051 }
1052 if !ports_seen.insert(port) {
1053 report.problems.push(format!("two ports are named '{port}'"));
1054 continue;
1055 }
1056 let mut points_seen: BTreeSet<&str> = BTreeSet::new();
1057 for point in &declaration.points {
1058 let name = point.name.trim();
1059 if let Some(problem) = name_problem(&format!("point of port '{port}'"), name) {
1060 report.problems.push(problem);
1061 continue;
1062 }
1063 if !points_seen.insert(name) {
1064 report
1065 .problems
1066 .push(format!("port '{port}' has two points named '{name}'"));
1067 continue;
1068 }
1069 let address = address(port, name);
1070 match resolve_point(point, port, name, &declaration.purpose, scene, env) {
1071 Ok((record, seat, problems, contact, unplaced)) => {
1072 report.problems.extend(problems);
1073 let (position, direction) = (record.point, record.direction);
1074 if !unplaced {
1075 if let Err(error) = publish_port(&mut result, &address, record) {
1076 report.problems.push(format!("{address}: {error}"));
1077 continue;
1078 }
1079 }
1080 report.points.push(PortPointRow {
1081 address,
1082 port: port.to_string(),
1083 point: name.to_string(),
1084 purpose: declaration.purpose.clone(),
1085 maps_to: point.maps_to.clone(),
1086 seat: seat.into(),
1087 position: [position.x, position.y, position.z],
1088 direction: [direction.x, direction.y, direction.z],
1089 contact,
1090 unplaced,
1091 });
1092 }
1093 Err(error) => report.problems.push(format!("{address}: {error}")),
1094 }
1095 }
1096 }
1097 scene.apply(&result);
1098 PortsOutcome { report: Some(report), result: Some(result) }
1099}
1100
1101/// One point's record and its seat, plus whatever about it did not hold. A
1102/// reference that resolves to nothing is a problem, never an error: the point
1103/// still publishes, at whatever placement could be worked out.
1104///
1105/// The placement rule, in one sentence: **a point's `transform` is an offset in
1106/// its seat** ([`seat_of`]) — its `position` along the seat's three axes, its
1107/// `rotationEuler` composed onto the seat's basis. A point with no reference
1108/// has the WORLD seat, where an offset is an absolute placement, so every
1109/// document written before the seat existed reads exactly as it did.
1110fn resolve_point(
1111 point: &PortPoint,
1112 port: &str,
1113 name: &str,
1114 purpose: &str,
1115 scene: &SceneMap,
1116 env: &Env,
1117) -> Result<(PortRecord, Frame, Vec<String>, Option<PortContactRow>, bool), String> {
1118 let address = address(port, name);
1119 let mut problems = Vec::new();
1120
1121 // A mapped point IS its target: the assembly declares the interface, the
1122 // descendant holds the geometry. It has no seat of its own — its placement
1123 // is the target's, and a gizmo on one would be editing the wrong document.
1124 if let Some(target) = point.maps_to.as_deref().map(str::trim).filter(|t| !t.is_empty()) {
1125 match scene.resolve_port(target) {
1126 Some(mapped) => {
1127 let seat = Frame::from_origin_direction(mapped.point, mapped.direction)
1128 .unwrap_or_else(|_| world_seat());
1129 return Ok((
1130 PortRecord {
1131 point: mapped.point,
1132 direction: mapped.direction,
1133 kind: PortKind::Termination,
1134 extension: point.extension.unwrap_or(mapped.extension).max(0.0),
1135 display_length: point
1136 .display_length
1137 .unwrap_or(mapped.display_length)
1138 .max(MIN_DISPLAY_LENGTH),
1139 port_name: port.to_string(),
1140 point_name: name.to_string(),
1141 purpose: purpose.to_string(),
1142 },
1143 seat,
1144 problems,
1145 None,
1146 false,
1147 ));
1148 }
1149 None => problems.push(format!(
1150 "{address} maps to '{target}', which is not a connection point of this document"
1151 )),
1152 }
1153 }
1154
1155 let position = common::vec3_from_value(
1156 env,
1157 point.transform.get("position"),
1158 &format!("{address}.transform.position"),
1159 [0.0, 0.0, 0.0],
1160 )?;
1161 let rotation = common::vec3_from_value(
1162 env,
1163 point.transform.get("rotationEuler"),
1164 &format!("{address}.transform.rotationEuler"),
1165 [0.0, 0.0, 0.0],
1166 )?;
1167
1168 let (seat, mut seat_problems, contact, body_problem) = seat_with_contact(point, scene);
1169 // A contact body that was to seat the origin and derived nothing must not
1170 // leave the wire end at the world origin: a point with an offset of its
1171 // own keeps it (its last explicit place), one without has no wire end
1172 // (it is reported, not published) and says why.
1173 let unplaced = body_problem.is_some() && position == [0.0, 0.0, 0.0];
1174 if let (true, Some(problem)) = (unplaced, body_problem) {
1175 if let Some(entry) = seat_problems.iter_mut().find(|entry| **entry == problem) {
1176 entry.push_str("; this point has no wire end until it is seated");
1177 }
1178 }
1179 problems.extend(
1180 seat_problems
1181 .into_iter()
1182 .map(|problem| format!("{address}: {problem}")),
1183 );
1184
1185 let base = seat_point(&seat, Vec3::new(position[0], position[1], position[2]));
1186 let mut direction = seated_direction(&seat, rotation)
1187 .normalized()
1188 .map_err(|_| "direction is a zero vector".to_string())?;
1189 // A body-seated origin already took the other end for `reverseDirection`.
1190 let reversed_by_end = contact.as_ref().is_some_and(|(_, _, seats_origin)| *seats_origin);
1191 if point.reverse_direction && !reversed_by_end {
1192 direction = direction.scale(-1.0);
1193 }
1194 let contact = contact.map(|(body, derived, seats_origin)| {
1195 let a = |v: Vec3| [v.x, v.y, v.z];
1196 PortContactRow {
1197 body,
1198 end: if derived.wire_at_plus { "+axis" } else { "-axis" }.to_string(),
1199 axis: a(derived.axis),
1200 wire_end: a(derived.wire_end()),
1201 other_end: a(derived.other_end()),
1202 seats_origin,
1203 rule: derived.rule.as_str().to_string(),
1204 }
1205 });
1206 Ok((
1207 PortRecord {
1208 point: base,
1209 direction,
1210 kind: PortKind::Termination,
1211 extension: point.extension.unwrap_or(DEFAULT_EXTENSION).max(0.0),
1212 display_length: point
1213 .display_length
1214 .unwrap_or(DEFAULT_DISPLAY_LENGTH)
1215 .max(MIN_DISPLAY_LENGTH),
1216 port_name: port.to_string(),
1217 point_name: name.to_string(),
1218 purpose: purpose.to_string(),
1219 },
1220 seat,
1221 problems,
1222 contact,
1223 unplaced,
1224 ))
1225}
1226
1227/// The seat of a point that names no reference: the world frame, in which an
1228/// offset is an absolute placement.
1229pub fn world_seat() -> Frame {
1230 Frame {
1231 origin: Vec3::new(0.0, 0.0, 0.0),
1232 x_axis: Vec3::new(1.0, 0.0, 0.0),
1233 y_axis: Vec3::new(0.0, 1.0, 0.0),
1234 z_axis: Vec3::new(0.0, 0.0, 1.0),
1235 }
1236}
1237