/// 手绘识别 · 图元库匹配。 /// /// 把笔迹(可多笔,顺序无关)与图元库每个符号的轮廓做「归一化双向 /// chamfer 距离」匹配,返回最相似的图元。 /// /// 与内置识别的关系:内置识别(矩形 / 圆 / 箭头 / 折线…)优先且保持不变; /// **内置识别不了的笔迹再走本匹配器**——因此「图元库可扩展」等价于 /// 「能手绘识别的图形可扩展」:用户导入 / 自建的图元也能被画出来识别。 library; import 'dart:math' as math; import 'dart:ui' show Offset, Path, PathMetric, Rect, Tangent; import 'package:sequence_diagram/modules/architecture/library/symbol_library.dart'; /// 图元匹配结果。 class ArchSymbolMatch { /// 构造。 const ArchSymbolMatch({required this.symbol, required this.score}); /// 命中的图元。 final LibSymbol symbol; /// 双向 chamfer 平均距离(归一化坐标 0..1,越小越像)。 final double score; } /// 识别阈值(归一化单位):匹配分数大于该值视为「都不像」。 /// /// 标定依据(合成笔迹回归):真命中 0.006–0.03(接地 0.006 / 灯 0.013 / /// 自定义图元≈0.01),乱涂 / 斜线等假命中 ≥0.07;取 0.06 保守稳妥。 const double kArchSymbolMaxScore = 0.06; /// 最佳与次佳的分数差下限:相差太小说明特征不明显,宁可不错认。 /// (灯 vs 电机 这类相似图形差约 0.010;取 0.008 兼顾召回与精度。) const double kArchSymbolMargin = 0.008; /// 识别笔迹(多笔按点集合并)。 ArchSymbolMatch? recognizeArchSymbol( List> strokes, List catalog, { double maxScore = kArchSymbolMaxScore, double margin = kArchSymbolMargin, int inputSamples = 96, int refSamples = 128, }) { // 每笔独立重采样(避免笔与笔之间产生"跳线"污染),按各笔长度分配采样数。 final List> parts = >[]; final List lens = []; double total = 0; for (final List s in strokes) { if (s.length < 2) continue; double len = 0; for (int i = 1; i < s.length; i++) { len += (s[i] - s[i - 1]).distance; } if (len < 1e-6) continue; parts.add(s); lens.add(len); total += len; } if (parts.isEmpty || total < 1e-6 || catalog.isEmpty) return null; final List pts = []; for (int i = 0; i < parts.length; i++) { final int count = math.max(4, (inputSamples * lens[i] / total).round()); pts.addAll(_resample(parts[i], count)); } if (pts.length < 4) return null; final _Np input = _Np.of(pts); if (input.extent < 1e-6) return null; // 多尺度:手绘大小 / 完整度与图元不完全一致(少画一笔、比例不同都要容忍), // 对输入做几档缩放,取最像的一档。 const List scales = [0.7, 0.85, 1.0, 1.2, 1.45]; final List> scaled = >[ for (final double s in scales) [for (final Offset p in input.pts) p * s], ]; ArchSymbolMatch? best; double second = double.infinity; for (final LibSymbol sym in catalog) { final List refPts = _sampleSymbol(sym, refSamples); if (refPts.length < 4) continue; final _Np ref = _Np.of(refPts); if (ref.extent < 1e-6) continue; double score = double.infinity; for (final List sp in scaled) { final double sc = _chamfer(sp, ref.pts); if (sc < score) score = sc; } if (best == null || score < best.score) { second = best?.score ?? second; best = ArchSymbolMatch(symbol: sym, score: score); } else if (score < second) { second = score; } } if (best == null) return null; if (best.score > maxScore) return null; if (second.isFinite && second - best.score < margin) return null; return best; } // ===================== 内部实现 ===================== /// 归一化点集:中心化 + 按最大边缩放(对平移 / 缩放不敏感)。 class _Np { const _Np(this.pts, this.extent); final List pts; final double extent; static _Np of(List pts) { if (pts.isEmpty) return const _Np([], 0); double l = pts.first.dx, r = l, t = pts.first.dy, b = t; for (final Offset p in pts) { if (p.dx < l) l = p.dx; if (p.dx > r) r = p.dx; if (p.dy < t) t = p.dy; if (p.dy > b) b = p.dy; } final double ext = math.max(r - l, b - t); if (ext < 1e-6) return _Np(List.filled(pts.length, Offset.zero), 0); final Offset c = Offset((l + r) / 2, (t + b) / 2); return _Np([ for (final Offset p in pts) Offset((p.dx - c.dx) / ext, (p.dy - c.dy) / ext), ], ext); } } /// 按弧长均匀重采样折线到 [n] 个点。 List _resample(List pts, int n) { if (pts.length <= 1) return List.of(pts); double total = 0; for (int i = 1; i < pts.length; i++) { total += (pts[i] - pts[i - 1]).distance; } if (total < 1e-6) return [pts.first]; final List out = [pts.first]; int seg = 0; double acc = 0; double segLen = (pts[1] - pts[0]).distance; for (int i = 1; i < n; i++) { final double target = total * i / (n - 1); while (acc + segLen < target && seg < pts.length - 2) { acc += segLen; seg++; segLen = (pts[seg + 1] - pts[seg]).distance; } final double rest = target - acc; final double t = segLen <= 1e-9 ? 0 : (rest / segLen).clamp(0.0, 1.0); out.add(Offset.lerp(pts[seg], pts[seg + 1], t)!); } return out; } /// 采样图元轮廓(在 100×100 归一化盒内按各子路径长度分配采样点)。 List _sampleSymbol(LibSymbol sym, int n) { final Path path = buildSymbolPath(sym, const Rect.fromLTWH(0, 0, 100, 100)); final List metrics = path.computeMetrics().toList(); double total = 0; for (final PathMetric m in metrics) { total += m.length; } if (total < 1e-6) return const []; final List out = []; for (final PathMetric m in metrics) { final int count = math.max(2, (n * m.length / total).round()); for (int i = 0; i <= count; i++) { final Tangent? t = m.getTangentForOffset(m.length * i / count); if (t != null) out.add(t.position); } } return out; } /// 双向 chamfer 平均距离。 double _chamfer(List a, List b) { double d1 = 0; for (final Offset p in a) { d1 += _nearest(p, b); } d1 /= a.length; double d2 = 0; for (final Offset p in b) { d2 += _nearest(p, a); } d2 /= b.length; return (d1 + d2) / 2; } double _nearest(Offset p, List pts) { double best = double.infinity; for (final Offset q in pts) { final double d = (p - q).distanceSquared; if (d < best) best = d; } return math.sqrt(best); }