Skip to content
Merged
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
1 change: 1 addition & 0 deletions crates/doc/src/drawing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ pub mod note;
pub mod symbol;
pub mod table;
pub mod template;
pub mod thread_lines;
pub mod view;

use balloon::Balloon;
Expand Down
331 changes: 331 additions & 0 deletions crates/doc/src/drawing/thread_lines.rs

Large diffs are not rendered by default.

492 changes: 492 additions & 0 deletions crates/doc/src/drawing/thread_lines_tests.rs

Large diffs are not rendered by default.

23 changes: 22 additions & 1 deletion crates/engine/src/cmd/drawing_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ use solidcraft_doc::drawing::cutting_line::CuttingLine;
use solidcraft_doc::drawing::dimension::{Dimension, LabelKind, MAX_DECIMALS, reading_label};
use solidcraft_doc::drawing::fold::{FoldFor, FoldRefusal, FoldSide, auxiliary_side};
use solidcraft_doc::drawing::note::Note;
use solidcraft_doc::drawing::thread_lines::{ThreadPiece, ThreadStroke};
use solidcraft_doc::drawing::view::{Beside, ResolvedView, SetBy, Setting, View, ViewKind, ViewLabel, ViewPlace, check_occurrence_paths, check_pose};
use solidcraft_doc::drawing_view::{
Exploded, JointPose, Looking, MAX_POSE_JOINTS, OccurrencePaths, Pose, StudyStep, TangentEdges, ViewConfiguration, ViewDirection, ViewOverrides,
Expand Down Expand Up @@ -80,7 +81,8 @@ use crate::schema::drawing_view::{
FromResult, InspectParams, InspectResult, LabelResult, LabelSet, LineResult, LinesStatusResult, MeasureParam, MeasurementResult, MoveParams,
OutsideResult, PathSegResult, PictureResult, PieceResult, PlaceParam, PoseParam, PoseResult, ProjectedParams, ProjectionForParams,
ProjectionForResult, ScaleResult, SceneResult, SectionParams, SettingResult, SettingsResult, SnapshotParams, SnapshotResult, SourceResult,
StudyPoseParam, StudyStepResult, ToSheetResult, ViewLineParam, ViewMoveParams, ViewMoveResult, ViewResult, ViewSet,
StudyPoseParam, StudyStepResult, ThreadPieceResult, ThreadResult, ToSheetResult, ViewLineParam, ViewMoveParams, ViewMoveResult, ViewResult,
ViewSet,
};
use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Session};
Expand Down Expand Up @@ -294,6 +296,7 @@ fn snapshot(s: &mut Session, p: &Value) -> Result<Value> {
extents: extents_result(&extents, None, false),
boundary_mm: BoxResult { min: boundary.min.into(), max: boundary.max.into() },
lines: line_results(&set, &drawn),
threads: thread_results(&set, &drawn),
status: LinesStatusResult {
lines: if drawn.lines.iter().flat_map(|l| &l.pieces).any(|p| matches!(p.accuracy, CurveAccuracy::Sampled { .. })) {
"approximate"
Expand Down Expand Up @@ -508,6 +511,24 @@ fn line_results(shown: &ShownSet, drawn: &Lines) -> Vec<LineResult> {
drawn.lines.iter().map(line).collect()
}

fn thread_results(shown: &ShownSet, drawn: &Lines) -> Vec<ThreadResult> {
let thread = |t: &crate::drawing_view::ThreadLine| {
let body = shown.bodies.get(t.shown);
let piece = |p: &ThreadPiece| ThreadPieceResult {
stroke: if p.stroke == ThreadStroke::Limit { "limit" } else { "root" },
visibility: if p.visibility == Visibility::Hidden { "hidden" } else { "visible" },
path: vec![PathSegResult(p.seg)],
};
ThreadResult {
occurrence: body.map(|b| b.path.clone()).unwrap_or_default(),
body: body.map(|b| b.body.clone()).unwrap_or_default(),
reference: t.reference,
pieces: t.pieces.iter().map(piece).collect(),
}
};
drawn.threads.iter().map(thread).collect()
}

fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
let request: InspectParams = crate::schema::read(INSPECT, p)?;
let d = s.drawing(INSPECT)?;
Expand Down
115 changes: 115 additions & 0 deletions crates/engine/src/cmd/drawing_view_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4661,3 +4661,118 @@ fn a_section_views_letter_is_given() {
}
assert_eq!(letters, ["A", "B"]);
}

/// A 40 x 40 x 20 mm block from the origin with an M8 tapped hole down from the middle of its top:
/// drilled Ø6.8 16 deep, threaded 12 deep. At 1:1 the block's centre is the A3 sheet's (210, 148.5),
/// so from above the hole is round it, and from the front its top is at y = 158.5 on the sheet.
fn tapped_block() -> Session {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 20, "body_name": "Block"}));
run(&mut s, "solid.hole", json!({"position": [20, 20, 20], "direction": [0, 0, -1], "thread": "M8", "depth": 16, "thread_depth": 12}));
s
}

/// Every segment of `v`'s thread pieces of `stroke` at `visibility`, on the sheet.
fn thread_segs(v: &Value, stroke: &str, visibility: &str) -> Vec<Value> {
let pieces = v["threads"].as_array().into_iter().flatten().flat_map(|t| t["pieces"].as_array().into_iter().flatten());
let wanted = pieces.filter(|p| p["stroke"] == stroke && p["visibility"] == visibility);
wanted.flat_map(|p| p["path"].as_array().into_iter().flatten().cloned()).collect()
}

/// A line segment's ends, top first.
fn top_first(seg: &Value) -> (Vec2, Vec2) {
let (a, b) = (point(&seg["a"]), point(&seg["b"]));
if a.y >= b.y { (a, b) } else { (b, a) }
}

/// From above, the M8 tapped hole draws its root as a thin three-quarter arc of radius 4.0 round
/// the hole's centre, from 90° round to 360°, so its gap is the upper right quadrant: the Ø6.8 drill
/// is the circle the view draws already.
#[test]
fn a_tapped_holes_root_is_a_three_quarter_arc_seen_from_above() {
let mut s = tapped_block();
let v = snap(&mut s, json!({"view": "top", "scale": "1:1"}));
let schema = output_schema_for::<SnapshotResult>();
assert!(conforms(schema.as_value(), schema.as_value(), &v), "{v}");
let roots = thread_segs(&v, "root", "visible");
assert_eq!(roots.len(), 1, "{v}");
let arc = &roots[0];
assert_eq!(arc["type"], "arc", "{arc}");
assert!(point(&arc["center"]).dist(Vec2::new(210.0, 148.5)) < 1e-6, "{arc}");
let (radius, start, sweep) = (arc["radius"].as_f64().unwrap(), arc["start"].as_f64().unwrap(), arc["sweep"].as_f64().unwrap());
assert!(
(radius - 4.0).abs() < 1e-6 && (start - std::f64::consts::FRAC_PI_2).abs() < 1e-6 && (sweep - 3.0 * std::f64::consts::FRAC_PI_2).abs() < 1e-6,
"{arc}"
);
assert!(thread_segs(&v, "limit", "visible").is_empty() && thread_segs(&v, "limit", "hidden").is_empty(), "end on, no limit line: {v}");
assert!(arcs(&v, "visible").iter().any(|(c, r, ..)| c.dist(Vec2::new(210.0, 148.5)) < 1e-6 && (r - 3.4).abs() < 1e-6), "the drill: {v}");
}

/// From the front, with hidden lines drawn, the hole's thread is hidden: two dashed root lines 8.0
/// apart, each 12.0 long down from the top, and a limit line 8.0 long across at 12 deep, where the
/// thread stops in its 16 mm hole. With hidden lines left out, the thread draws nothing.
#[test]
fn a_tapped_holes_thread_is_hidden_from_the_side() {
let mut s = tapped_block();
let v = snap(&mut s, json!({"scale": "1:1", "visual_style": "visible_hidden"}));
let mut roots: Vec<(Vec2, Vec2)> = thread_segs(&v, "root", "hidden").iter().map(top_first).collect();
roots.sort_by(|p, q| p.0.x.total_cmp(&q.0.x));
assert_eq!(roots.len(), 2, "{v}");
for ((top, bottom), x) in roots.iter().zip([206.0, 214.0]) {
assert!(top.dist(Vec2::new(x, 158.5)) < 1e-6 && bottom.dist(Vec2::new(x, 146.5)) < 1e-6, "{top:?} {bottom:?} {v}");
}
let limits: Vec<(Vec2, Vec2)> = thread_segs(&v, "limit", "hidden").iter().map(top_first).collect();
assert_eq!(limits.len(), 1, "{v}");
let (a, b) = limits[0];
assert!(
(a.dist(b) - 8.0).abs() < 1e-6 && (a.y - 146.5).abs() < 1e-6 && (b.y - 146.5).abs() < 1e-6 && ((a.x + b.x) / 2.0 - 210.0).abs() < 1e-6,
"{v}"
);
assert!(thread_segs(&v, "root", "visible").is_empty() && thread_segs(&v, "limit", "visible").is_empty(), "{v}");
let v = snap(&mut s, json!({"scale": "1:1"}));
assert_eq!(v["threads"], json!([]), "{v}");
}

/// A tapped block drawn from the mesh (a mesh cube stands in front of its lower right corner, clear
/// of the hole) still draws its thread: two hidden root lines 8.0 apart, each 12.0 long, and a limit
/// line 8.0 long across their lower ends. The thread lines pair with the mesh's crest lines as with
/// exact ones.
#[test]
fn a_tapped_block_drawn_from_the_mesh_draws_its_thread() {
let mut s = tapped_block();
with_mesh_cube(&mut s, [30.0, -30.0, -10.0], "tapped");
let v = snap(&mut s, json!({"scale": "1:1", "visual_style": "visible_hidden"}));
assert_eq!(v["status"]["provenance"], "mesh_projection", "{v}");
let mut roots: Vec<(Vec2, Vec2)> = thread_segs(&v, "root", "hidden").iter().map(top_first).collect();
roots.sort_by(|p, q| p.0.x.total_cmp(&q.0.x));
assert_eq!(roots.len(), 2, "{v}");
let (left, right) = (roots[0], roots[1]);
assert!((right.0.x - left.0.x - 8.0).abs() < 1e-6 && (left.0.y - right.0.y).abs() < 1e-6, "{roots:?}");
assert!(roots.iter().all(|(top, bottom)| (top.x - bottom.x).abs() < 1e-6 && (top.y - bottom.y - 12.0).abs() < 1e-6), "{roots:?}");
let limits: Vec<(Vec2, Vec2)> = thread_segs(&v, "limit", "hidden").iter().map(top_first).collect();
assert_eq!(limits.len(), 1, "{v}");
let (a, b) = limits[0];
assert!((a.dist(b) - 8.0).abs() < 1e-6 && (a.y - left.1.y).abs() < 1e-6 && (b.y - left.1.y).abs() < 1e-6, "{limits:?} {roots:?}");
}

/// An M8 shaft threaded 10 mm down from its top, seen from the side: its root lines are thin and
/// seen, at the minor radius a modelled M8 is cut to (4 - 5H/8 for H = 1.25 √3 / 2), 10 long; a
/// limit line goes across where the thread stops, and none at the free end, where the shaft's own
/// edge is drawn.
#[test]
fn a_shafts_thread_is_seen_from_the_side() {
let mut s = Session::default();
run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 20, "body_name": "Shaft"}));
run(&mut s, "solid.thread", json!({"face": [4, 0, 10], "designation": "M8", "length": 10, "from": [4, 0, 20]}));
let v = snap(&mut s, json!({"scale": "1:1"}));
let minor = 4.0 - 5.0 * (1.25 * 3f64.sqrt() / 2.0) / 8.0;
let mut roots: Vec<(Vec2, Vec2)> = thread_segs(&v, "root", "visible").iter().map(top_first).collect();
roots.sort_by(|p, q| p.0.x.total_cmp(&q.0.x));
assert_eq!(roots.len(), 2, "{v}");
for ((top, bottom), x) in roots.iter().zip([210.0 - minor, 210.0 + minor]) {
assert!(top.dist(Vec2::new(x, 158.5)) < 1e-6 && bottom.dist(Vec2::new(x, 148.5)) < 1e-6, "{top:?} {bottom:?} {v}");
}
let limits: Vec<(Vec2, Vec2)> = thread_segs(&v, "limit", "visible").iter().map(top_first).collect();
assert_eq!(limits.len(), 1, "{v}");
assert!((limits[0].0.y - 148.5).abs() < 1e-6 && (limits[0].0.dist(limits[0].1) - 8.0).abs() < 1e-6, "{v}");
}
15 changes: 10 additions & 5 deletions crates/engine/src/drawing_scene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ use solidcraft_doc::drawing::note::{Anchor, Note};
use solidcraft_doc::drawing::view::{FlatOf, ResolvedView, View};
use solidcraft_doc::drawing::{Drawing, Sheet, Updates};
use solidcraft_doc::drawing_view::TangentEdges;
use solidcraft_doc::{DocError, Document, ModelState, ids};
use solidcraft_doc::{DocError, Document, ModelState, ThreadInfo, ids};
use solidcraft_geom::cell::{Part, Projection};
use solidcraft_geom::drawing_view::ViewFrame;
use solidcraft_geom::hlr::Source;
Expand Down Expand Up @@ -695,7 +695,7 @@ fn draw(
let pictures = picture_items(id, &view_parts(&set, styles), rect);
// The pictures go under the strokes, so the owners start with one empty entry for each.
let owner = |at: usize| lines.lines.get(at).map(|line| (line.shown, line.source));
let items = std::iter::repeat_n(None, pictures.len()).chain(drew.into_iter().map(owner)).collect();
let items = std::iter::repeat_n(None, pictures.len()).chain(drew.into_iter().map(|at| at.and_then(owner))).collect();
group.items.splice(0..0, pictures);
if group.records() > MAX_RECORDS {
return none(Status::Failed(format!("its lines are more than a paper scene's {MAX_RECORDS} records: choose a smaller scale")));
Expand Down Expand Up @@ -1411,19 +1411,24 @@ pub struct Cache {
}

/// What a view's lines show: each body of the world state by the occurrences that place it, its
/// definition's body name, whether it is a reference, and its geometry where it stands. A world state
/// definition's body name, whether it is a reference, its geometry where it stands, and its cosmetic
/// threads (which change no geometry, yet draw lines of their own). A world state
/// with the same draws the same lines, so an appearance, or an edit taken back, draws nothing. It
/// keys the whole set, not a view's own bodies: which bodies share a mesh, so the lines' last bits,
/// hangs on all of them ([`crate::mesh_lines`]).
#[derive(Debug, PartialEq)]
pub(crate) struct SourceKey(Vec<(Vec<u64>, String, bool, u64)>);
pub(crate) struct SourceKey(Vec<(Vec<u64>, String, bool, u64, Vec<ThreadInfo>)>);

impl SourceKey {
/// None when there is nothing to show, or a body's geometry has no key: a view drawn from it
/// always draws again.
fn of(shown: &std::result::Result<ShownSet, Unmeasured>) -> Option<Arc<SourceKey>> {
let set = shown.as_ref().ok()?;
let body = |one: &Shown| Some((one.path.clone(), one.body.clone(), one.reference, set.body(one)?.geometry_key()?));
let body = |one: &Shown| {
let body = set.body(one)?;
let threads = set.state.threads.iter().filter(|t| t.body == body.name).cloned().collect();
Some((one.path.clone(), one.body.clone(), one.reference, body.geometry_key()?, threads))
};
set.bodies.iter().map(body).collect::<Option<Vec<_>>>().map(|bodies| Arc::new(SourceKey(bodies)))
}
}
Expand Down
73 changes: 73 additions & 0 deletions crates/engine/src/drawing_scene_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3677,3 +3677,76 @@ fn a_rule_change_draws_the_flat_view_again() {
settled(&mut s, sheet);
assert!(extract(&mut s, sheet).unwrap().stale.is_empty());
}

/// [`front_and_top`]'s block with a hole drilled Ø6.8 16 deep down from the middle of its top, and an
/// M8 cosmetic thread 12 deep in it (the feature `Tap`): a thread of its own, so editing it changes
/// no geometry.
fn tapped_front_and_top() -> (Session, u64, [u64; 2]) {
let mut s = Session::default();
run(&mut s, "solid.box", json!({"length": 100, "width": 50, "height": 20, "body_name": "Block"}));
run(&mut s, "solid.hole", json!({"position": [50, 25, 20], "direction": [0, 0, -1], "diameter": 6.8, "depth": 16}));
run(&mut s, "solid.thread", json!({"face": [53.4, 25, 15], "designation": "M8", "length": 12, "from": [53.4, 25, 20], "name": "Tap"}));
front_and_top_of(s)
}

/// The arcs of `group`'s strokes of `radius` (paper millimetres).
fn arcs_of(group: &Group, radius: f64) -> usize {
let segs = group.items.iter().filter_map(|item| match item {
Item::Stroke { path, .. } => Some(path),
_ => None,
});
segs.flatten().filter(|seg| matches!(seg, Seg2::Arc { radius: r, .. } if (r - radius).abs() < 1e-9)).count()
}

/// A sheet's view draws a cosmetic thread's lines as its snapshot does: from the front, hidden
/// (two root lines and the limit line, dashed); from above, the root's three-quarter arc, radius 2
/// on paper at 1:2. Changing only the thread's depth draws the front view again, with its limit line
/// moved, though the block's geometry is the same.
#[test]
fn a_views_threads_draw_as_its_snapshot_does_and_follow_the_thread() {
let (mut s, sheet, [front, top]) = tapped_front_and_top();
run(&mut s, "drawing.view.edit", json!({"view": ids::encode(front), "set": {"visual_style": "visible_hidden"}}));
let scene = settled(&mut s, sheet).scene;
let group = |scene: &Scene, id: u64| scene.groups.iter().find(|g| g.object == id).unwrap().clone();
let ours = group(&scene, front);
assert_eq!(arcs_of(&group(&scene, top), 2.0), 1, "{:?}", group(&scene, top));
let dashed = ours.items.iter().filter(|item| matches!(item, Item::Stroke { pattern: Some(_), .. })).count();
// The drill's two sides and its floor, its cone's two sides, and the thread's three lines.
assert!(dashed >= 6, "{ours:?}");
let drawing = ids::encode(s.open_drawing.unwrap());
run(&mut s, "drawing.close", json!({}));
let p = json!({"view": "front", "scale": "1:2", "position_mm": [150, 150], "scene": true, "visual_style": "visible_hidden"});
let v = run(&mut s, "drawing.view.snapshot", p);
let snapped: Scene = serde_json::from_value(v["scene"].clone()).unwrap();
assert!(same_within(&ours, &snapped.groups[0], 1e-9), "{ours:?} {:?}", snapped.groups[0]);
assert_eq!(v["threads"].as_array().map(Vec::len), Some(1), "{v}");
let geometry = s.world_state().unwrap().bodies[0].geometry_key();
run(&mut s, "timeline.edit", json!({"feature": "Tap", "set": {"length": "8"}}));
assert_eq!(s.world_state().unwrap().bodies[0].geometry_key(), geometry, "a cosmetic thread changes no geometry");
run(&mut s, "drawing.open", json!({"drawing": drawing}));
let moved = group(&settled(&mut s, sheet).scene, front);
assert_ne!(bytes_of(&moved), bytes_of(&ours), "the limit line moves with the thread");
run(&mut s, "drawing.close", json!({}));
let v = run(
&mut s,
"drawing.view.snapshot",
json!({"view": "front", "scale": "1:2", "position_mm": [150, 150], "scene": true, "visual_style": "visible_hidden"}),
);
let snapped: Scene = serde_json::from_value(v["scene"].clone()).unwrap();
assert!(same_within(&moved, &snapped.groups[0], 1e-9), "{moved:?} {:?}", snapped.groups[0]);
}

/// Two placements of a tapped plate each draw their own thread: two root arcs from above.
#[test]
fn each_placement_of_a_tapped_part_draws_its_thread() {
let mut s = Session::default();
let plate = run(&mut s, "component.create", json!({"name": "Plate"}));
run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10, "body_name": "PlateBody"}));
run(&mut s, "solid.hole", json!({"position": [20, 20, 10], "direction": [0, 0, -1], "thread": "M8", "depth": 8}));
run(&mut s, "component.activate", json!({"component": 0}));
run(&mut s, "occurrence.copy", json!({"component": plate["component"], "translate": [60, 0, 0]}));
let (mut s, sheet, [_, top]) = front_and_top_of(s);
let scene = settled(&mut s, sheet).scene;
let top = scene.groups.iter().find(|g| g.object == top).unwrap();
assert_eq!(arcs_of(top, 2.0), 2, "{top:?}");
}
7 changes: 6 additions & 1 deletion crates/engine/src/drawing_view.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,12 @@ use crate::{Result, Session};
mod exact;
#[path = "drawing_view_lines.rs"]
mod lines;
#[path = "drawing_view_threads.rs"]
mod threads;

pub use exact::{Fallback, PreparedBodies};
pub use lines::{CHORD_MM, CHORD_RANGE, LineRequest, Lines, MIN_MODEL_CHORD_MM, Made, Piece, Stats, ViewLine, lines, paper_group, paper_lines};
pub use threads::ThreadLine;

#[path = "drawing_view_flat.rs"]
mod flat;
Expand Down Expand Up @@ -151,7 +154,9 @@ impl Styles {
/// Leaves out a shaded part's own lines: its picture draws it, and it still hides what lies
/// behind it.
pub fn leave_shaded_to_pictures(&self, lines: &mut Lines) {
lines.lines.retain(|l| !(if l.reference { self.reference } else { self.display }).is_shaded());
let shaded = |reference: bool| (if reference { self.reference } else { self.display }).is_shaded();
lines.lines.retain(|l| !shaded(l.reference));
lines.threads.retain(|t| !shaded(t.reference));
}
}

Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/drawing_view_exact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ fn clipped(path: &[Seg2], area: &Aabb2, chord: f64) -> Vec<(Vec<Seg2>, bool)> {
}
ends = q.dist(b) <= EPS;
}
let near = |radius: f64| 2.0 * chord + radius * 1e-9;
let near = |radius: f64| super::lines::near(chord, radius);
for (points, starts) in kept {
let part = match seg {
Seg2::Arc { .. } => on_arc(seg, &points, false, near, 0.0).map(|(arc, _)| vec![arc]),
Expand Down
Loading
Loading