Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/doc/src/construct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ pub(crate) fn as_line(pts: &[Vec3]) -> Option<(Vec3, Vec3)> {
}

/// A polyline on a circle: (centre, unit normal, radius).
fn as_circle(pts: &[Vec3]) -> Option<(Vec3, Vec3, f64)> {
pub(crate) fn as_circle(pts: &[Vec3]) -> Option<(Vec3, Vec3, f64)> {
let n = pts.len();
if n < 4 {
return None;
Expand Down
159 changes: 123 additions & 36 deletions crates/doc/src/drawing/dimension.rs

Large diffs are not rendered by default.

68 changes: 66 additions & 2 deletions crates/doc/src/drawing/dimension_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const BODY: &str = "Box";
const FEATURE: u64 = 7;

fn corner(edges: &[&str]) -> ModelPoint {
ModelPoint { body: BODY.into(), origin_feature: FEATURE, edges: edges.iter().map(|e| e.to_string()).collect(), path: Vec::new() }
ModelPoint { body: BODY.into(), origin_feature: FEATURE, edges: edges.iter().map(|e| e.to_string()).collect(), centre: false, path: Vec::new() }
}

fn edge(name: &str) -> ModelEdge {
Expand Down Expand Up @@ -159,6 +159,18 @@ fn the_dimensions_rules_are_kept_on_reading() {
};
let meet = rule(&linear_id, "a corner is where 2 to 16 named edges meet");
assert_eq!([edges(0), edges(1), edges(2), edges(16), edges(17)], [meet.clone(), meet.clone(), "read".into(), "read".into(), meet]);
// A centre is of one named circle or arc, and saves as `centre`.
let centred = |n: usize| {
let mut v = file(&d);
let b = &mut dim(&mut v, &linear_id)["kind"]["linear"]["b"];
b["centre"] = json!(true);
b["edges"] = json!((0..n).map(|i| format!("F3:e{i}")).collect::<Vec<_>>());
let read = Drawing::from_json(&v.to_string()).map_err(|e| e.to_string())?;
Ok::<_, String>(dim(&mut file(&read), &linear_id)["kind"]["linear"]["b"].clone())
};
let one = Err(rule(&linear_id, "a centre is of one named circle or arc"));
assert_eq!([centred(0), centred(2)], [one.clone(), one]);
assert_eq!(centred(1), Ok(json!({"body": "Box", "origin_feature": 7, "edges": ["F3:e0"], "centre": true})));
// The feature that made the body, and the occurrence path.
let feature = rule(&length_id, "a reference names the feature that made its body");
assert_eq!(refused(&d, |v| dim(v, &length_id)["kind"]["length"]["edge"]["origin_feature"] = json!(0)), feature);
Expand Down Expand Up @@ -206,7 +218,7 @@ fn the_dimensions_rules_are_kept_on_reading() {
|v, id| dim(v, id)["kind"]["linear"]["tolerance"] = json!(0.1),
|v, id| dim(v, id)["kind"]["linear"]["a"]["point"] = json!([0.0, 0.0, 0.0]),
|v, id| dim(v, id)["text"] = json!({"at": [1.0, 2.0], "angle": 3.0}),
|v, id| dim(v, id)["kind"] = json!({"chain": {}}),
|v, id| dim(v, id)["kind"] = json!({"baseline": {}}),
];
for (i, edit) in unknown.into_iter().enumerate() {
assert!(refused(&d, |v| edit(v, &linear_id)).starts_with("damaged drawing: "), "{i}");
Expand Down Expand Up @@ -271,6 +283,58 @@ fn a_radial_dimension_saves_its_edge_and_whether_it_is_a_diameter() {
assert!(refused(&d, |v| dim(v, &radial_id)["kind"]["radial"]["reading"] = json!("true")).starts_with("damaged drawing: "));
}

/// A chain saves its points in order and its direction, and keeps its rules on reading: 3 to
/// [`MAX_CHAIN_POINTS`] points, each with a point's rules, a direction to measure along that isn't
/// zero, no reading (it reads projected) and no text instead of its members' numbers.
#[test]
fn a_chain_saves_its_points_in_order_and_keeps_its_rules() {
let (mut d, _) = measured();
let (view, id) = (d.views[0].id, d.allocate_id(&mut IdSource::seeded(SEED + 1)).unwrap());
let hole = |n: u64| {
let rim = format!("F{n}:hole|F1:front");
ModelPoint { centre: true, ..corner(&[rim.as_str()]) }
};
let points = vec![corner(&["F1:front|F1:bottom", "F1:front|F1:left"]), hole(3), hole(4), hole(5)];
let kind = DimensionKind::Chain { points, direction: LinearDirection::Horizontal };
d.add_dimensions([Arc::new(Dimension {
id,
view,
kind,
offset_mm: 8.0,
text: TextPlace::Centred,
decimals: 1,
override_text: None,
last_good: None,
})]);
d.validate().unwrap();
let chain_id = ids::encode(id);
let mut v = file(&d);
let first = json!({"body": "Box", "origin_feature": 7, "edges": ["F1:front|F1:bottom", "F1:front|F1:left"]});
let centre = |n: u64| json!({"body": "Box", "origin_feature": 7, "edges": [format!("F{n}:hole|F1:front")], "centre": true});
let saved = json!({"chain": {"points": [first, centre(3), centre(4), centre(5)], "direction": "horizontal"}});
assert_eq!(dim(&mut v, &chain_id)["kind"], saved);
assert_eq!(Drawing::from_json(&v.to_string()).unwrap(), d);
let rule = |rule: &str| format!("damaged drawing: dimension {chain_id}: {rule}");
let count = |n: usize| {
refused(&d, |v| {
let points = &mut dim(v, &chain_id)["kind"]["chain"]["points"];
let one = points[1].clone();
*points = json!(vec![one; n]);
})
};
let three_to = rule(&format!("a chain has 3 to {MAX_CHAIN_POINTS} points"));
let counts = [count(0), count(2), count(3), count(MAX_CHAIN_POINTS), count(MAX_CHAIN_POINTS + 1)];
assert_eq!(counts, [three_to.clone(), three_to.clone(), "read".into(), "read".into(), three_to]);
let two_edges = refused(&d, |v| dim(v, &chain_id)["kind"]["chain"]["points"][2]["edges"] = json!(["F3:a", "F3:b"]));
assert_eq!(two_edges, rule("a centre is of one named circle or arc"));
let zero = refused(&d, |v| dim(v, &chain_id)["kind"]["chain"]["direction"] = json!({"along": [0.0, 0.0]}));
assert_eq!(zero, rule("the direction to measure along is zero or not finite"));
let instead = refused(&d, |v| dim(v, &chain_id)["override_text"] = json!("60"));
assert_eq!(instead, rule("a chain shows its members' numbers, never a text instead"));
let reading = refused(&d, |v| dim(v, &chain_id)["kind"]["chain"]["reading"] = json!("projected"));
assert!(reading.starts_with("damaged drawing: "), "{reading}");
}

/// A direction along a picked line saves as its plane coordinates and reads back as the same
/// direction: what W19a measures along.
#[test]
Expand Down
10 changes: 5 additions & 5 deletions crates/doc/src/drawing/format/pending/dimensions.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Drawings save their dimensions (`dimensions`, #4896 W19b): each on one of the drawing's views,
//! measuring named corners or edges of the view's model (a linear distance, an edge's length, an
//! angle, or a circle's or an arc's radius or diameter), with how far its line sits from them and
//! where its text sits on paper, its decimals and any text shown instead of its number. An older
//! drawing has no dimensions. The last release refuses a drawing saved with them, as a newer
//! format.
//! measuring named corners, circles' and arcs' centres, or edges of the view's model (a linear
//! distance, an edge's length, an angle, a circle's or an arc's radius or diameter, or a chain of
//! distances along one line), with how far its line sits from them and where its text sits on
//! paper, its decimals and any text shown instead of its number. An older drawing has no
//! dimensions. The last release refuses a drawing saved with them, as a newer format.
8 changes: 7 additions & 1 deletion crates/doc/src/drawing_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,13 @@ fn plate() -> Drawing {
let iso = ViewKind::Base { source: plate_id, view: ViewDirection::Named(NamedView::IsoFrontRight) };
let full_size = ViewOverrides { scale: Some("1:1".parse().unwrap()), tangent_edges: Some(TangentEdges::Show), ..ViewOverrides::default() };
add(&mut d, bolt_sheet, iso, ViewPlace::At([105.0, 148.5]), full_size, 5.0);
let corner = |edges: [&str; 2]| ModelPoint { body: "Plate".into(), origin_feature: 1, edges: edges.map(String::from).to_vec(), path: Vec::new() };
let corner = |edges: [&str; 2]| ModelPoint {
body: "Plate".into(),
origin_feature: 1,
edges: edges.map(String::from).to_vec(),
centre: false,
path: Vec::new(),
};
let edge = |name: &str| ModelEdge { body: "Plate".into(), origin_feature: 1, name: name.into(), path: vec![3, 7] };
let measures = [
DimensionKind::Linear {
Expand Down
39 changes: 28 additions & 11 deletions crates/engine/src/cmd/drawing_dimension.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ use std::sync::Arc;

use serde_json::Value;
use solidcraft_doc::drawing::Drawing;
use solidcraft_doc::drawing::dimension::{Candidate, Dimension, DimensionKind, Status, TextPlace};
use solidcraft_doc::drawing::dimension::{Candidate, Dimension, DimensionKind, Status, TextPlace, check_chain_length};
use solidcraft_doc::ids;
use solidcraft_geom::Vec3;
use solidcraft_geom::drawing_measure::{LinearDirection, Reading};

use super::CommandSpec;
use crate::params::bad;
use crate::schema::drawing_dimension::{
AddParams, CandidateResult, CornerParam, DimensionResult, DimensionSet, EdgeParam, EditParams, EditResult, InspectParams, KindParam,
AddParams, CandidateResult, CornerParam, DimensionResult, DimensionSet, EdgeParam, EditParams, EditResult, InspectParams, KindParam, MemberResult,
};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
Expand Down Expand Up @@ -45,12 +45,14 @@ pub static COMMANDS: &[CommandSpec] = &[
.params(
"view: a saved view's id; kind: {linear: {a, b: corners, direction?: aligned (default), horizontal, vertical or {along: [x, y]}, \
reading?: projected (default) or true}}, {length: {edge, direction?, reading?}}, {angle: {a, b: straight edges, reading?, \
other_side?}} or {radial: {edge: a circle or an arc the view sees face on, diameter?: by default for a whole circle or \
half a turn or more}}; an edge is a point on it [x, y, z] in the design's frame, {point} or {body, index}, and a corner a point, \
{point} or {edges: [2 to 16 edges]}, each with path?: the occurrences its body is placed through, from the top; offset_mm?: \
the dimension line's distance on paper (default 10); text?: centred (default) or {at: [x, y]} from the view's centre; \
decimals?: 0..6 (default 2); override_text? → what drawing.dimension.inspect answers for it. Saved by the edges' names, \
never the points picked; one the view can't measure is refused. One undo step; no model is evaluated.",
other_side?}}, {radial: {edge: a circle or an arc the view sees face on, diameter?: by default for a whole circle or \
half a turn or more}} or {chain: {points: [3 to 64 corners, in order along one line], direction?: as a linear one's, \
aligned being first to last}}; an edge is a point on it [x, y, z] in the design's frame, {point} or {body, index}, and a \
corner a point, {point}, {edges: [2 to 16 edges]} or {centre: an edge that is a circle or an arc}, each with path?: the \
occurrences its body is placed through, from the top; offset_mm?: the dimension line's distance on paper (default 10); \
text?: centred (default) or {at: [x, y]} from the view's centre; decimals?: 0..6 (default 2); override_text? (not a \
chain's) → what drawing.dimension.inspect answers for it. Saved by the edges' names, never the points picked; one the \
view can't measure is refused. One undo step; no model is evaluated.",
),
CommandSpec::new(EDIT, "Edit Drawing Dimension", crate::checked!("drawing.dimension.edit", edit))
.icon("dimension")
Expand All @@ -61,7 +63,7 @@ pub static COMMANDS: &[CommandSpec] = &[
.params(
"dimension: its id; set: {offset_mm?, text?: centred or {at: [x, y]}, decimals?: 0..6, override_text?: text, or null to show \
the number again; direction?, reading?: a linear or length dimension's, reading? and other_side?: an angle's, diameter?: a \
radial dimension's} → \
radial dimension's, direction?: a chain's} → \
{dimension, changed: [fields]}. What it measures stays: to measure something else, add a new one. One undo step, none \
when nothing changes; no model is evaluated.",
),
Expand All @@ -74,8 +76,9 @@ pub static COMMANDS: &[CommandSpec] = &[
.output(output_schema_for::<DimensionResult>)
.params(
"dimension: its id → {dimension, view, record: as saved, status: ok, overridden, ambiguous, suppressed, lost or unmeasurable, \
why?, value? (model mm, or degrees for an angle), foreshortened?, text?, last_good? (the value it last read, kept when \
the design is saved, when it has none now), exact, candidates?: [{edge: {body, index}} or {corner: [x, y, z]}]}. Read-only; no model is \
why?, value? (model mm, or degrees for an angle; a chain's overall), foreshortened?, text? (none for a chain), \
members?: a chain's [{value, text}] from its first point, last_good? (the value it last read, kept when the design \
is saved, when it has none now), exact, candidates?: [{edge: {body, index}} or {corner: [x, y, z]}]}. Read-only; no model is \
evaluated.",
),
];
Expand Down Expand Up @@ -105,6 +108,12 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
DimensionKind::Angle { a: edge(&a)?, b: edge(&b)?, reading: reading.unwrap_or(Reading::Projected), other_side }
}
KindParam::Radial { edge: e, diameter } => DimensionKind::Radial { edge: edge(&e)?, diameter: diameter.unwrap_or(false) },
KindParam::Chain { points, direction } => {
// Counted before any point is looked up.
check_chain_length(points.len()).map_err(|why| bad(ADD, why.to_string()))?;
let points = points.iter().map(corner).collect::<Result<_>>()?;
DimensionKind::Chain { points, direction: direction.unwrap_or(LinearDirection::Aligned) }
}
};
let id = record.allocate_id(&mut s.ids).map_err(|e| bad(ADD, e.to_string()))?;
let mut dimension = Dimension {
Expand Down Expand Up @@ -193,6 +202,12 @@ fn change(d: &mut Drawing, id: u64, set: &DimensionSet) -> Result<Vec<String>> {
}
*diameter = set.diameter.unwrap_or(*diameter);
}
DimensionKind::Chain { direction, .. } => {
if set.reading.is_some() || set.other_side.is_some() {
return Err(bad(EDIT, "a chain has only `direction`: it reads as the view shows it"));
}
*direction = set.direction.unwrap_or(*direction);
}
}
Ok(changed_fields(&before, dimension))
}
Expand All @@ -205,6 +220,7 @@ fn kind_settings(kind: &DimensionKind) -> (Option<LinearDirection>, Option<Readi
}
DimensionKind::Angle { reading, other_side, .. } => (None, Some(*reading), *other_side, false),
DimensionKind::Radial { diameter, .. } => (None, None, false, *diameter),
DimensionKind::Chain { direction, .. } => (Some(*direction), None, false, false),
}
}

Expand Down Expand Up @@ -255,6 +271,7 @@ fn answer(s: &mut Session, cmd: &str, id: u64) -> Result<Value> {
value: r.measured.map(|m| shown(m.value)),
foreshortened: r.measured.map(|m| m.foreshortened),
text: r.text,
members: r.members.into_iter().map(|m| MemberResult { value: m.measured.value, text: m.text }).collect(),
last_good: last_good.map(shown),
exact: r.exact,
candidates,
Expand Down
Loading