1use std::collections::HashMap;
9use std::f64::consts::PI;
10
11use serde_json::Value;
12
13use super::doc::{id_key, point_index, SketchConstraint, SketchDiagnostics, SketchDoc, SketchPoint};
14use super::PlaneFrame;
15use crate::style::SketchColors;
16
17pub const OVERLAY_DIM_LEADERS: &str = "sketch-dim-leaders";
20
21#[derive(Clone, Debug)]
23pub struct DimLabel {
24 pub id: Value,
26 pub text: String,
28 pub world: [f64; 3],
30 pub value: Option<f64>,
32 pub value_expr: Option<String>,
34 pub mode: &'static str,
36 pub conflicting: bool,
40}
41
42struct DimGeometry {
44 segments: Vec<([f64; 2], [f64; 2])>,
46 label_uv: [f64; 2],
48 text: String,
49 value: Option<f64>,
50 value_expr: Option<String>,
51 mode: &'static str,
52}
53
54fn is_radial_dimension(c: &SketchConstraint) -> bool {
57 if c.ctype() != Some("⟺") || c.points().len() < 2 {
58 return false;
59 }
60 matches!(
61 c.raw.get("displayStyle").and_then(Value::as_str),
62 Some("radius") | Some("diameter")
63 )
64}
65
66fn saved_offset(dim_offsets: &serde_json::Map<String, Value>, id: &Value) -> Option<[f64; 2]> {
69 let entry = dim_offsets.get(&id_key(id))?;
70 let du = entry.get("du").and_then(Value::as_f64);
71 let dv = entry.get("dv").and_then(Value::as_f64);
72 match (du, dv) {
73 (Some(du), Some(dv)) if du.is_finite() && dv.is_finite() => Some([du, dv]),
74 (Some(du), None) if du.is_finite() => Some([du, 0.0]),
76 (None, Some(dv)) if dv.is_finite() => Some([0.0, dv]),
77 _ => None,
78 }
79}
80
81fn linear_endpoints(
87 c: &SketchConstraint,
88 by_id: &HashMap<String, &SketchPoint>,
89) -> Option<([f64; 2], [f64; 2], [f64; 2])> {
90 let get = |id: &Value| by_id.get(&id_key(id)).copied();
91 let pts = c.points();
92 match c.ctype() {
93 Some("⟺") if pts.len() >= 2 && !is_radial_dimension(c) => {
94 let p0 = get(&pts[0])?;
95 let p1 = get(&pts[1])?;
96 let a = [p0.x, p0.y];
97 Some((a, [p1.x, p1.y], a))
98 }
99 Some("↥") if pts.len() >= 3 => {
100 let a = get(&pts[0])?;
101 let b = get(&pts[1])?;
102 let cpt = get(&pts[2])?;
103 let dx = b.x - a.x;
104 let dy = b.y - a.y;
105 let len_sq = dx * dx + dy * dy;
106 if !(len_sq > 1e-12) {
107 return Some(([a.x, a.y], [cpt.x, cpt.y], [a.x, a.y]));
108 }
109 let t_raw = ((cpt.x - a.x) * dx + (cpt.y - a.y) * dy) / len_sq;
110 let t_raw = if t_raw.is_finite() { t_raw } else { 0.0 };
111 let t_seg = t_raw.clamp(0.0, 1.0);
112 Some((
113 [a.x + t_raw * dx, a.y + t_raw * dy],
114 [cpt.x, cpt.y],
115 [a.x + t_seg * dx, a.y + t_seg * dy],
116 ))
117 }
118 _ => None,
119 }
120}
121
122pub(super) fn screen_fit(wpp: f64, entity: f64, frac: f64, min_px: f64, max_px: f64, fallback: f64) -> f64 {
129 if !(wpp > 0.0) || !wpp.is_finite() {
130 return fallback;
131 }
132 let (lo, hi) = (wpp * min_px, wpp * max_px);
133 if !(entity > 0.0) || !entity.is_finite() {
134 return hi;
135 }
136 (entity * frac).clamp(lo, hi)
137}
138
139fn radial_default_offset(pc: [f64; 2], pr: [f64; 2], wpp: f64) -> [f64; 2] {
143 let vx = pr[0] - pc[0];
144 let vy = pr[1] - pc[1];
145 let l = vx.hypot(vy);
146 let (rx, ry) = if l > 1e-9 { (vx / l, vy / l) } else { (1.0, 0.0) };
147 let (nx, ny) = (-ry, rx);
148 let floor = if wpp > 0.0 && wpp.is_finite() { wpp * 12.0 } else { 0.2 };
149 let base = (l * 0.35).max(floor);
150 [
151 vx + rx * base + nx * base * 0.35,
152 vy + ry * base + ny * base * 0.35,
153 ]
154}
155
156fn push_arrow(
159 segments: &mut Vec<([f64; 2], [f64; 2])>,
160 tip: [f64; 2],
161 dx: f64,
162 dy: f64,
163 ah: f64,
164 s: f64,
165) {
166 let len = dx.hypot(dy);
167 if !(len > 1e-9) {
168 return;
169 }
170 let (tx, ty) = (dx / len, dy / len);
171 let (wx, wy) = (-ty, tx);
172 let a = [tip[0] + tx * ah + wx * ah * s, tip[1] + ty * ah + wy * ah * s];
173 let b = [tip[0] + tx * ah - wx * ah * s, tip[1] + ty * ah - wy * ah * s];
174 segments.push((tip, a));
175 segments.push((tip, b));
176}
177
178fn dim_geometry(
181 c: &SketchConstraint,
182 by_id: &HashMap<String, &SketchPoint>,
183 dim_offsets: &serde_json::Map<String, Value>,
184 wpp: f64,
185) -> Option<DimGeometry> {
186 let ctype = c.ctype()?;
187 let id = c.raw.get("id")?;
188 let value = c
189 .raw
190 .get("value")
191 .and_then(Value::as_f64)
192 .filter(|v| v.is_finite());
193 let value_expr = c
194 .raw
195 .get("valueExpr")
196 .and_then(Value::as_str)
197 .filter(|s| !s.is_empty())
198 .map(str::to_string);
199
200 let arrow_head = |measured: f64| screen_fit(wpp, measured, 0.2, 2.5, 6.0, 0.06);
203 let arrow_s = 0.6;
204
205 if is_radial_dimension(c) {
206 let pts = c.points();
208 let pc = by_id.get(&id_key(&pts[0])).copied()?;
209 let pr = by_id.get(&id_key(&pts[1])).copied()?;
210 let center = [pc.x, pc.y];
211 let radius = (pr.x - pc.x).hypot(pr.y - pc.y);
212 if !(radius > 1e-9) {
213 return None;
214 }
215 let diameter = c.raw.get("displayStyle").and_then(Value::as_str) == Some("diameter");
216 let ah = arrow_head(radius);
217 let off = saved_offset(dim_offsets, id).unwrap_or_else(|| radial_default_offset(center, [pr.x, pr.y], wpp));
218 let label_uv = [center[0] + off[0], center[1] + off[1]];
219
220 let (mut dx, mut dy) = (label_uv[0] - center[0], label_uv[1] - center[1]);
222 let mut l = dx.hypot(dy);
223 if !(l > 1e-9) {
224 dx = pr.x - pc.x;
225 dy = pr.y - pc.y;
226 l = dx.hypot(dy).max(1e-9);
227 }
228 let (ux, uy) = (dx / l, dy / l);
229 let near = [center[0] + ux * radius, center[1] + uy * radius];
230 let far = [center[0] - ux * radius, center[1] - uy * radius];
231
232 let mut segments = Vec::new();
233 if diameter {
234 segments.push((far, near));
235 segments.push((near, label_uv));
236 push_arrow(&mut segments, near, -ux, -uy, ah, arrow_s);
238 push_arrow(&mut segments, far, ux, uy, ah, arrow_s);
239 } else {
240 segments.push((center, near));
241 segments.push((near, label_uv));
242 push_arrow(&mut segments, near, -ux, -uy, ah, arrow_s);
243 }
244
245 let safe = value.unwrap_or(0.0);
246 let (text, mode) = if diameter {
247 (format!("⌀{:.3}", 2.0 * safe), "diameter")
248 } else {
249 (format!("R{safe:.3}"), "radius")
250 };
251 return Some(DimGeometry {
252 segments,
253 label_uv,
254 text,
255 value,
256 value_expr,
257 mode,
258 });
259 }
260
261 if ctype == "⟺" || ctype == "↥" {
262 let (a, b, anchor_a) = linear_endpoints(c, by_id)?;
264 let (dx, dy) = (b[0] - a[0], b[1] - a[1]);
265 let len = dx.hypot(dy).max(1e-9);
266 let (tx, ty) = (dx / len, dy / len);
267 let (nx, ny) = (-ty, tx);
268 let ah = arrow_head(len);
269 let base = screen_fit(wpp, len, 0.8, 12.0, 20.0, 0.1);
272 let mid = [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0];
273 let off = saved_offset(dim_offsets, id).unwrap_or([nx * base, ny * base]);
275 let label_uv = [mid[0] + off[0], mid[1] + off[1]];
276 let off_n = off[0] * nx + off[1] * ny;
280 let ou = nx * off_n;
281 let ov = ny * off_n;
282
283 let a_off = [a[0] + ou, a[1] + ov];
284 let b_off = [b[0] + ou, b[1] + ov];
285 let mut segments = vec![
286 (a_off, b_off), (anchor_a, a_off), (b, b_off), ];
290 push_arrow(&mut segments, a_off, tx, ty, ah, arrow_s);
292 push_arrow(&mut segments, b_off, -tx, -ty, ah, arrow_s);
293
294 let t_lbl = (label_uv[0] - a_off[0]) * tx + (label_uv[1] - a_off[1]) * ty;
300 let foot = {
301 let t = t_lbl.clamp(0.0, len);
302 [a_off[0] + tx * t, a_off[1] + ty * t]
303 };
304 if (label_uv[0] - foot[0]).hypot(label_uv[1] - foot[1]) > wpp * 2.0 {
305 segments.push((foot, label_uv));
306 }
307
308 let text = format!("{:.3}", value.unwrap_or(0.0));
309 return Some(DimGeometry {
310 segments,
311 label_uv,
312 text,
313 value,
314 value_expr,
315 mode: "distance",
316 });
317 }
318
319 if ctype == "∠" && c.points().len() >= 4 {
320 let pts = c.points();
322 let get = |i: usize| by_id.get(&id_key(&pts[i])).copied();
323 let (p0, p1, p2, p3) = (get(0)?, get(1)?, get(2)?, get(3)?);
324 let inter = line_intersection([p0.x, p0.y], [p1.x, p1.y], [p2.x, p2.y], [p3.x, p3.y]);
325 let (d1x, d1y) = (p1.x - p0.x, p1.y - p0.y);
326 let (d2x, d2y) = (p3.x - p2.x, p3.y - p2.y);
327 if (d1x * d1x + d1y * d1y) < 1e-12 || (d2x * d2x + d2y * d2y) < 1e-12 {
328 return None;
329 }
330 let a0 = d1y.atan2(d1x);
331 let a1 = d2y.atan2(d2x);
332 let mut signed = a1 - a0;
333 while signed <= -PI {
334 signed += 2.0 * PI;
335 }
336 while signed > PI {
337 signed -= 2.0 * PI;
338 }
339 let default_deg = (a1 - a0).to_degrees().rem_euclid(360.0);
340 let mut target_deg = match value {
341 Some(v) => {
342 let abs = v.abs();
343 let mut t = abs % 360.0;
344 if t < 1e-6 && abs > 0.0 {
345 t = 360.0;
346 }
347 t
348 }
349 None => default_deg,
350 };
351 if target_deg < 1e-6 {
352 target_deg = 1e-6;
353 }
354 let mut dir_sign = if signed == 0.0 { 1.0 } else { signed.signum() };
355 if target_deg > 180.0 && target_deg < 360.0 - 1e-6 {
356 dir_sign = -dir_sign;
357 }
358 let mut d = target_deg.to_radians() * dir_sign;
359 let two_pi = 2.0 * PI;
360 if d.abs() > two_pi {
361 d = d.signum() * (two_pi - 1e-6);
362 }
363
364 let shorter = d1x.hypot(d1y).min(d2x.hypot(d2y));
367 let base_r = screen_fit(wpp, shorter, 0.6, 10.0, 24.0, 0.3);
368 let ah = arrow_head(base_r);
369 let off = saved_offset(dim_offsets, id).unwrap_or([0.0, 0.0]);
370 let r = base_r + off[0].hypot(off[1]);
371 let (cx, cy) = (inter[0], inter[1]);
372
373 let mut a_start = a0;
375 if off[0] != 0.0 || off[1] != 0.0 {
376 let label_ang = off[1].atan2(off[0]);
377 let norm = |a: f64| {
378 let t = two_pi;
379 let m = a % t;
380 if m < 0.0 {
381 m + t
382 } else {
383 m
384 }
385 };
386 let ang_diff = |a: f64, b: f64| {
387 let mut x = norm(a - b);
388 if x > PI {
389 x = two_pi - x;
390 }
391 x.abs()
392 };
393 let bisector = a_start + d * 0.5;
394 let bisector_opp = bisector + PI;
395 if ang_diff(label_ang, bisector_opp) + 1e-6 < ang_diff(label_ang, bisector) {
396 a_start += PI;
397 }
398 }
399
400 let segs = 48usize;
402 let mut segments = Vec::with_capacity(segs + 4);
403 let mut prev = [cx + a_start.cos() * r, cy + a_start.sin() * r];
404 for i in 1..=segs {
405 let t = a_start + d * (i as f64 / segs as f64);
406 let cur = [cx + t.cos() * r, cy + t.sin() * r];
407 segments.push((prev, cur));
408 prev = cur;
409 }
410 let dir_start = if d >= 0.0 { 1.0 } else { -1.0 };
412 let add_arc_arrow = |segments: &mut Vec<([f64; 2], [f64; 2])>, t: f64, dir: f64| {
413 let tip = [cx + t.cos() * r, cy + t.sin() * r];
414 let (tx, ty) = (-t.sin() * dir, t.cos() * dir);
415 push_arrow(segments, tip, tx, ty, ah, arrow_s);
416 };
417 add_arc_arrow(&mut segments, a_start, dir_start);
418 add_arc_arrow(&mut segments, a_start + d, -dir_start);
419
420 let mid_ang = a_start + d * 0.5;
422 let label_uv = [cx + mid_ang.cos() * r, cy + mid_ang.sin() * r];
423
424 let text = format!("{:.1}°", value.unwrap_or(default_deg));
427 return Some(DimGeometry {
428 segments,
429 label_uv,
430 text,
431 value,
432 value_expr,
433 mode: "angle",
434 });
435 }
436
437 None
438}
439
440pub(super) fn line_intersection(a: [f64; 2], b: [f64; 2], c: [f64; 2], d: [f64; 2]) -> [f64; 2] {
443 let r = [b[0] - a[0], b[1] - a[1]];
444 let s = [d[0] - c[0], d[1] - c[1]];
445 let rxs = r[0] * s[1] - r[1] * s[0];
446 if rxs.abs() < 1e-12 {
447 return a;
448 }
449 let t = ((c[0] - a[0]) * s[1] - (c[1] - a[1]) * s[0]) / rxs;
450 [a[0] + t * r[0], a[1] + t * r[1]]
451}
452
453pub fn constraint_dim_segments(
459 c: &SketchConstraint,
460 doc: &SketchDoc,
461 dim_offsets: &serde_json::Map<String, Value>,
462 world_per_pixel: f64,
463) -> Option<Vec<([f64; 2], [f64; 2])>> {
464 let by_id = point_index(doc);
465 dim_geometry(c, &by_id, dim_offsets, world_per_pixel).map(|g| g.segments)
466}
467
468pub fn dimension_leaders_buffers(
472 doc: &SketchDoc,
473 diag: &SketchDiagnostics,
474 plane: &PlaneFrame,
475 dim_offsets: &serde_json::Map<String, Value>,
476 world_per_pixel: f64,
477 colors: &SketchColors,
478) -> (Vec<f32>, Vec<f32>) {
479 dimension_leaders_buffers_with_state(
480 doc,
481 diag,
482 plane,
483 dim_offsets,
484 world_per_pixel,
485 colors,
486 None,
487 &[],
488 )
489}
490
491pub fn dimension_leaders_buffers_with_state(
496 doc: &SketchDoc,
497 diag: &SketchDiagnostics,
498 plane: &PlaneFrame,
499 dim_offsets: &serde_json::Map<String, Value>,
500 world_per_pixel: f64,
501 colors: &SketchColors,
502 hovered: Option<&Value>,
503 selection: &[Value],
504) -> (Vec<f32>, Vec<f32>) {
505 let by_id = point_index(doc);
506 let mut positions: Vec<f32> = Vec::new();
507 let mut color_buf: Vec<f32> = Vec::new();
508 for c in &doc.constraints {
509 let Some(geom) = dim_geometry(c, &by_id, dim_offsets, world_per_pixel) else {
510 continue;
511 };
512 let color = match c.raw.get("id") {
515 Some(id) => super::tessellate::interaction_color(
516 colors,
517 super::constraint_base_color(colors, diag, id),
518 hovered,
519 selection,
520 "constraint",
521 id,
522 ),
523 None => colors.constraint,
524 };
525 let rgb = crate::color::hex_to_srgb_f32(color);
526 for (a, b) in geom.segments {
527 let wa = plane.to_world(a[0], a[1]);
528 let wb = plane.to_world(b[0], b[1]);
529 positions.extend_from_slice(&[
530 wa[0] as f32,
531 wa[1] as f32,
532 wa[2] as f32,
533 wb[0] as f32,
534 wb[1] as f32,
535 wb[2] as f32,
536 ]);
537 color_buf.extend_from_slice(&[rgb[0], rgb[1], rgb[2], rgb[0], rgb[1], rgb[2]]);
538 }
539 }
540 (positions, color_buf)
541}
542
543pub fn dimension_leaders_overlay_json(
546 doc: &SketchDoc,
547 diag: &SketchDiagnostics,
548 plane: &PlaneFrame,
549 dim_offsets: &serde_json::Map<String, Value>,
550 world_per_pixel: f64,
551 colors: &SketchColors,
552) -> String {
553 dimension_leaders_overlay_json_with_state(
554 doc,
555 diag,
556 plane,
557 dim_offsets,
558 world_per_pixel,
559 colors,
560 None,
561 &[],
562 )
563}
564
565pub fn dimension_leaders_overlay_json_with_state(
568 doc: &SketchDoc,
569 diag: &SketchDiagnostics,
570 plane: &PlaneFrame,
571 dim_offsets: &serde_json::Map<String, Value>,
572 world_per_pixel: f64,
573 colors: &SketchColors,
574 hovered: Option<&Value>,
575 selection: &[Value],
576) -> String {
577 let (positions, color_buf) = dimension_leaders_buffers_with_state(
578 doc,
579 diag,
580 plane,
581 dim_offsets,
582 world_per_pixel,
583 colors,
584 hovered,
585 selection,
586 );
587 serde_json::json!({
588 "groups": [
589 {
590 "name": OVERLAY_DIM_LEADERS,
591 "renderOrder": 10003,
592 "lines": { "positions": positions, "colors": color_buf },
593 }
594 ]
595 })
596 .to_string()
597}
598
599pub fn dimension_labels(
602 doc: &SketchDoc,
603 diag: &SketchDiagnostics,
604 plane: &PlaneFrame,
605 dim_offsets: &serde_json::Map<String, Value>,
606 world_per_pixel: f64,
607) -> Vec<DimLabel> {
608 let by_id = point_index(doc);
609 let mut out = Vec::new();
610 for c in &doc.constraints {
611 let Some(geom) = dim_geometry(c, &by_id, dim_offsets, world_per_pixel) else {
612 continue;
613 };
614 let Some(id) = c.raw.get("id").cloned() else {
615 continue;
616 };
617 out.push(DimLabel {
618 conflicting: diag.constraint_conflicting(&id),
619 id,
620 text: geom.text,
621 world: plane.to_world(geom.label_uv[0], geom.label_uv[1]),
622 value: geom.value,
623 value_expr: geom.value_expr,
624 mode: geom.mode,
625 });
626 }
627 out
628}
629
630pub fn dimension_anchor_uv(
635 c: &SketchConstraint,
636 doc: &SketchDoc,
637) -> Option<[f64; 2]> {
638 let by_id = point_index(doc);
639 let get = |id: &Value| by_id.get(&id_key(id)).copied();
640 if is_radial_dimension(c) {
641 let pc = get(&c.points()[0])?;
642 return Some([pc.x, pc.y]);
643 }
644 match c.ctype() {
645 Some("⟺") | Some("↥") => {
646 let (a, b, _) = linear_endpoints(c, &by_id)?;
647 Some([(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0])
648 }
649 Some("∠") if c.points().len() >= 4 => {
650 let pts = c.points();
651 let g = |i: usize| get(&pts[i]);
652 let (p0, p1, p2, p3) = (g(0)?, g(1)?, g(2)?, g(3)?);
653 Some(line_intersection(
654 [p0.x, p0.y],
655 [p1.x, p1.y],
656 [p2.x, p2.y],
657 [p3.x, p3.y],
658 ))
659 }
660 _ => None,
661 }
662}
663