/// 手绘识别:把一笔自由曲线识别成标准图形(直线 / 箭头 / 矩形 / 圆角矩形 / /// 圆 / 椭圆 / 三角形 / 菱形 / 六边形)。 /// /// 设计目标:像 iOS 手写便签那样——随手画个大概,松手后自动「扶正」成标准 /// 图形;识别不了的笔迹保留为墨迹(不丢内容)。 /// /// 算法概览(纯几何、无依赖、可单测): /// 1. 清洗 & 重采样成均匀点列; /// 2. 首尾距离判定「闭合 / 开放」; /// 3. 开放笔迹:直线拟合(含水平 / 垂直吸附)→ 箭头(箭杆直线 + 尖端折返); /// 4. 闭合笔迹:径向椭圆残差 + Douglas-Peucker 顶点化简 + 折点合并, /// 按顶点数分流(3 三角 / 4 矩形或菱形 / 6 六边形 / ≥7 或残差小 → 椭圆)。 library; import 'dart:math' as math; import 'dart:ui' show Offset, Rect; import 'arch_models.dart'; /// 识别结果:标准图形类型 + 规范化几何。 class ArchRecognition { /// 构造识别结果。 const ArchRecognition({ required this.type, required this.rect, this.radius = 0, this.dir = 0, this.a, this.b, this.arrow = false, this.pts, }); /// 图形类型(含 [ArchShapeType.line] 直线 / 箭头)。 final ArchShapeType type; /// 规范化后的外接矩形。 final Rect rect; /// 圆角半径([ArchShapeType.roundRect])。 final double radius; /// 三角形朝向:0 上 / 1 右 / 2 下 / 3 左。 final int dir; /// 直线起点。 final Offset? a; /// 直线终点。 final Offset? b; /// 是否为箭头(仅 [ArchShapeType.line])。 final bool arrow; /// 折线 / 曲线的通过点([ArchShapeType.polyline] / [ArchShapeType.curve])。 final List? pts; } /// 识别一笔手绘:成功返回标准图形,失败返回 null(调用方保留墨迹)。 ArchRecognition? recognizeArchStroke(List raw) { final List pts = _clean(raw); if (pts.length < 5) return null; final double len = _polyLength(pts); if (len < 18) return null; final Rect bb = _bounds(pts); if (math.max(bb.width, bb.height) < 14) return null; final double diag = math.sqrt(bb.width * bb.width + bb.height * bb.height); // 单笔「圆柱」:柱体 + 顶盖两圈轮廓,路径长度显著大于外接矩形周长。 final double gap = (pts.last - pts.first).distance; final double hullPer = 2 * (bb.width + bb.height); if (hullPer > 40 && len > hullPer * 1.38) { final List> parts = _splitOnJumps(pts, diag); if (parts.length == 2) { final ArchRecognition? cyl = _cylinderFromParts(parts[0], parts[1]) ?? _cylinderFromParts(parts[1], parts[0]); if (cyl != null) return cyl; } // 无内部跳变(顶盖起点与柱体起点重合)时:接近闭合即视为圆柱。 if (gap <= 0.45 * diag) { return ArchRecognition(type: ArchShapeType.cylinder, rect: bb); } } final bool closed = gap <= math.max(16, 0.22 * diag); if (closed) { if (math.min(bb.width, bb.height) < 10) return null; return _classifyClosed(pts, bb, diag); } return _classifyOpen(pts, len); } /// 多笔合并识别(如:两笔画出的矩形、先画柱体再画顶盖的圆柱)。 /// /// 按端点最近邻串接各笔后走单笔识别管线;接缝过大(两笔相距太远)时放弃。 ArchRecognition? recognizeArchStrokes(List> strokes) { final List> parts = >[ for (final List s in strokes) if (_clean(s).length >= 4) _clean(s), ]; if (parts.isEmpty) return null; if (parts.length == 1) return recognizeArchStroke(parts.first); if (parts.length > 2) return null; final List a = parts[0]; final List b = parts[1]; final double g1 = (a.last - b.first).distance; final double g2 = (a.last - b.last).distance; final double g3 = (a.first - b.first).distance; final double g4 = (a.first - b.last).distance; List merged; double gap; if (g1 <= g2 && g1 <= g3 && g1 <= g4) { merged = [...a, ...b]; gap = g1; } else if (g2 <= g3 && g2 <= g4) { merged = [...a, ...b.reversed]; gap = g2; } else if (g3 <= g4) { merged = [...a.reversed, ...b]; gap = g3; } else { merged = [...a.reversed, ...b.reversed]; gap = g4; } final Rect bb = _bounds(merged); final double diag = math.sqrt(bb.width * bb.width + bb.height * bb.height); if (gap > math.max(26.0, 0.30 * diag)) return null; return recognizeArchStroke(merged); } /// 两个「部件」识别结果组合成圆柱(顶盖椭圆 + 柱体矩形,形状层面快速判定)。 ArchRecognition? archCylinderFromRecognitions( ArchRecognition body, ArchRecognition lid, ) { final bool bodyIsRect = body.type == ArchShapeType.rect || body.type == ArchShapeType.roundRect; final bool lidIsEllipse = lid.type == ArchShapeType.ellipse || lid.type == ArchShapeType.circle; if (!bodyIsRect || !lidIsEllipse) return null; final Rect br = body.rect; final Rect lr = lid.rect; final bool geomOk = (lr.center.dx - br.center.dx).abs() <= math.max(14, br.width * 0.20) && (lr.width - br.width).abs() <= math.max(18, br.width * 0.38) && lr.center.dy <= br.top + lr.height * 0.9 && lr.bottom >= br.top - lr.height * 0.6; if (!geomOk) return null; return ArchRecognition( type: ArchShapeType.cylinder, rect: Rect.fromLTRB( math.min(lr.left, br.left), math.min(lr.top, br.top), math.max(lr.right, br.right), math.max(lr.bottom, br.bottom), ), ); } /// 按跳变(相邻点距离过大)把一笔拆成多段(单笔圆柱的柱体 + 顶盖)。 List> _splitOnJumps(List pts, double diag) { final double thr = math.max(14.0, 0.18 * diag); final List> parts = >[]; List cur = [pts.first]; for (int i = 1; i < pts.length; i++) { if ((pts[i] - pts[i - 1]).distance > thr) { if (cur.length >= 4) parts.add(cur); cur = [pts[i]]; } else { cur.add(pts[i]); } } if (cur.length >= 4) parts.add(cur); return parts; } /// 圆柱顶盖(扁椭圆)识别:放宽椭圆残差阈值(扁椭圆曲率大、抖动残差偏高), /// 只要「近椭圆」即可作为顶盖。 ArchRecognition? _recognizeLid(List lidPts) { final Rect lb = _bounds(lidPts); if (math.min(lb.width, lb.height) < 10) return null; final List pts = _resample(lidPts, 72); final double res90 = _percentile(_ellipseResiduals(pts, lb), 0.90); if (res90 <= 0.24) return _ellipseFrom(lb); return null; } /// 两段轮廓组合成圆柱:一段是柱体(矩形类),一段是顶盖(椭圆类)。 ArchRecognition? _cylinderFromParts(List bodyPts, List lidPts) { final Rect bb = _bounds(bodyPts); final double bd = math.sqrt(bb.width * bb.width + bb.height * bb.height); final Rect lb = _bounds(lidPts); final double ld = math.sqrt(lb.width * lb.width + lb.height * lb.height); final double gapB = (bodyPts.last - bodyPts.first).distance; final double gapL = (lidPts.last - lidPts.first).distance; if (math.min(bb.width, bb.height) < 12 || math.min(lb.width, lb.height) < 10) { return null; } if (gapB > math.max(20, 0.35 * bd) || gapL > math.max(20, 0.35 * ld)) { return null; } final ArchRecognition? lid = _recognizeLid(lidPts); if (lid == null || (lid.type != ArchShapeType.ellipse && lid.type != ArchShapeType.circle)) { return null; } final ArchRecognition? body = _classifyClosed(bodyPts, bb, bd); final bool bodyRect = body != null && (body.type == ArchShapeType.rect || body.type == ArchShapeType.roundRect); if (!bodyRect && !_hasTwoSideEdges(bodyPts, bb)) return null; final Rect lr = lid.rect; final bool geomOk = (lr.center.dx - bb.center.dx).abs() <= math.max(14, bb.width * 0.20) && (lr.width - bb.width).abs() <= math.max(18, bb.width * 0.38) && lr.center.dy <= bb.top + lr.height * 0.9 && lr.bottom >= bb.top - lr.height * 0.6; if (!geomOk) return null; return ArchRecognition( type: ArchShapeType.cylinder, rect: Rect.fromLTRB( math.min(lr.left, bb.left), math.min(lr.top, bb.top), math.max(lr.right, bb.right), math.max(lr.bottom, bb.bottom), ), ); } /// 柱体结构判定:左右两侧各有一条较长的竖直侧边(圆柱轮廓的必要条件)。 bool _hasTwoSideEdges(List bodyPts, Rect bb) { final double eps = math.max(3.0, 0.04 * math.min(bb.width, bb.height)); double lMin = double.infinity, lMax = -double.infinity; double rMin = double.infinity, rMax = -double.infinity; for (final Offset p in bodyPts) { if ((p.dx - bb.left).abs() <= eps) { if (p.dy < lMin) lMin = p.dy; if (p.dy > lMax) lMax = p.dy; } if ((p.dx - bb.right).abs() <= eps) { if (p.dy < rMin) rMin = p.dy; if (p.dy > rMax) rMax = p.dy; } } final double lSpan = lMax - lMin; final double rSpan = rMax - rMin; return lSpan >= bb.height * 0.4 && rSpan >= bb.height * 0.4; } /// 把识别结果转成标准图形(画布提交 / 示例场景共用)。 ArchShape archShapeFromRecognition( ArchRecognition r, { required String id, required int color, String text = '', }) { if (r.type == ArchShapeType.line) { final Offset a = r.a ?? Offset.zero; final Offset b = r.b ?? Offset.zero; return ArchShape( id: id, type: ArchShapeType.line, rect: Rect.fromPoints(a, b), a: a, b: b, arrow: r.arrow, fill: 0, stroke: color, sw: 2.4, text: text, ); } if (r.type == ArchShapeType.polyline || r.type == ArchShapeType.curve) { final List pts = r.pts ?? const []; return ArchShape( id: id, type: r.type, rect: r.rect, fill: 0, stroke: color, sw: 2.4, text: text, pts: pts, ); } return ArchShape( id: id, type: r.type, rect: r.rect, radius: r.radius, dir: r.dir, fill: archFillOf(color), stroke: color, sw: 1.8, text: text, ); } // ===================== 开放笔迹:直线 / 箭头 ===================== /// 开放笔迹分类:先试直线(含水平/垂直吸附),再试箭头。 ArchRecognition? _classifyOpen(List pts, double len) { final Offset a = pts.first; final Offset b = pts.last; final double chord = (b - a).distance; // 1) 直线:路径基本沿首尾弦推进,且最大偏距很小。 if (chord >= 0.72 * len) { final double dev = _maxDeviation(pts, a, b); if (dev <= math.max(4.0, 0.075 * chord)) { return _line(a, b, arrow: false); } } // 2) 箭头:离起点最远的点为箭尖;箭杆近似直线;尖端之后有明显折返 // (手绘箭头的头部是一笔折返的「>」)。 int tip = 0; double best = -1; for (int i = 0; i < pts.length; i++) { final double d = (pts[i] - a).distance; if (d > best) { best = d; tip = i; } } if (tip >= 2 && pts.length - 1 - tip >= 2) { final Offset t = pts[tip]; final double shaft = best; if (shaft >= 0.5 * len && shaft >= 14) { final double shaftDev = _maxDeviation(pts.sublist(0, tip + 1), a, t); if (shaftDev <= math.max(4.0, 0.065 * shaft)) { final double headLen = len - _polyLength(pts.sublist(0, tip + 1)); if (headLen <= 0.45 * len && headLen >= math.max(5.0, 0.035 * len)) { final Offset u = (t - a) / shaft; double minProj = shaft; for (int i = tip + 1; i < pts.length; i++) { final double pr = _dot(pts[i] - a, u); if (pr < minProj) minProj = pr; } if (minProj <= shaft - math.max(5.0, 0.065 * len)) { return _line(a, t, arrow: true); } } } } } // 3) 折线 / 曲线:既不是直线也不是箭头。 return _classifyPolyOrCurve(pts, len); } /// 折线 / 曲线分流: /// - 有集中的尖折点(折点转角大)→ 折线(近轴段自动扶正); /// - 平缓弯曲 → 曲线(样条通过点)。 ArchRecognition? _classifyPolyOrCurve(List pts, double len) { final Rect bb = _bounds(pts); final double diag = math.max(1, math.sqrt(bb.width * bb.width + bb.height * bb.height)); final List idx = _rdpIndices(pts, math.max(3.0, 0.03 * diag)); final List merged = _mergeOpen(pts, idx, 24); final List v = [for (final int i in merged) pts[i]]; if (v.length < 2) return null; final double chord = (v.last - v.first).distance; if (v.length == 2) { // 轻微弯曲的笔迹:保留弧度成为曲线(不弯曲的早走直线分支了)。 if (len >= chord * 1.015 && len <= chord * 2.2) { return ArchRecognition( type: ArchShapeType.curve, rect: _bounds(v), pts: v, ); } return null; } double maxTurn = 0; for (int i = 1; i < v.length - 1; i++) { maxTurn = math.max(maxTurn, _turnDeg(v[i - 1], v[i], v[i + 1])); } // 优先级:直线 > 曲线 > 折线。只有「折点犀利 + 每段足够直」才判为折线; // 否则一律归为曲线(曲线识别优先)。 if (maxTurn >= 55 && v.length <= 9 && _segmentsStraight(pts, v)) { final List snapped = _snapAxisSegments(v, 12); return ArchRecognition( type: ArchShapeType.polyline, rect: _bounds(snapped), pts: snapped, ); } // 平缓弯曲 → 曲线:用更粗的简化取「通过点」,保留动势。 final List idx2 = _rdpIndices(pts, math.max(5.0, 0.07 * diag)); final List cv = [for (final int i in idx2) pts[i]]; if (cv.length < 3) return null; return ArchRecognition( type: ArchShapeType.curve, rect: _bounds(cv), pts: cv, ); } /// 判断折点之间的每一段是否足够「直」: /// 直线段 → 折线候选;带明显弧度的段 → 归为曲线(曲线优先)。 bool _segmentsStraight(List pts, List v) { if (v.length < 2) return false; final List idx = []; for (final Offset t in v) { int bestI = 0; double bestD = double.infinity; for (int i = 0; i < pts.length; i++) { final double d = (pts[i] - t).distance; if (d < bestD) { bestD = d; bestI = i; } } idx.add(bestI); } for (int i = 1; i < idx.length; i++) { if (idx[i] <= idx[i - 1]) return false; } for (int s = 0; s < idx.length - 1; s++) { final Offset a = pts[idx[s]]; final Offset b = pts[idx[s + 1]]; final double segLen = (b - a).distance; if (segLen < 6) continue; double maxDev = 0; for (int i = idx[s] + 1; i < idx[s + 1]; i++) { final double d = archDistToSegment(pts[i], a, b); if (d > maxDev) maxDev = d; } if (maxDev > math.max(3.5, segLen * 0.055)) return false; } return true; } /// 把一段手画轨迹简化为折线顶点(连线轨迹识别用): /// RDP 抽稀 + 共线合并 + 近轴段扶正(±12° 吸附为水平 / 垂直)。 List simplifyArchPolyline(List pts) { final List clean = _clean(pts); if (clean.length < 2) return clean; final Rect b = _bounds(clean); final double diag = math.sqrt(b.width * b.width + b.height * b.height); final List idx = _rdpIndices(clean, math.max(4.0, 0.035 * diag)); final List merged = _mergeOpen(clean, idx, 24); final List v = [for (final int i in merged) clean[i]]; if (v.length < 2) return [clean.first, clean.last]; return _snapAxisSegments(v, 12); } /// 合并共线折点(开放折线:只处理内部顶点)。 List _mergeOpen(List pts, List idx, double tolDeg) { final List cur = List.of(idx); bool changed = true; while (changed && cur.length > 2) { changed = false; for (int i = 1; i < cur.length - 1; i++) { if (_turnDeg(pts[cur[i - 1]], pts[cur[i]], pts[cur[i + 1]]) < tolDeg) { cur.removeAt(i); changed = true; break; } } } return cur; } /// 近水平 / 垂直的折线段扶正(±[tolDeg] 内吸附为水平 / 垂直)。 List _snapAxisSegments(List v, double tolDeg) { final List out = List.of(v); for (int i = 0; i < out.length - 1; i++) { final Offset d = out[i + 1] - out[i]; if (d.distance < 0.001) continue; final double ang = math.atan2(d.dy, d.dx) * 180 / math.pi; double m = ang % 180; if (m > 90) m -= 180; final double devH = m.abs(); final double devV = 90 - m.abs(); if (devH <= tolDeg) { final double y = (out[i].dy + out[i + 1].dy) / 2; out[i] = Offset(out[i].dx, y); out[i + 1] = Offset(out[i + 1].dx, y); } else if (devV <= tolDeg) { final double x = (out[i].dx + out[i + 1].dx) / 2; out[i] = Offset(x, out[i].dy); out[i + 1] = Offset(x, out[i + 1].dy); } } return out; } /// 云判定:统计闭合曲线上的「凹口」段数(鼓包相接处方向反转)。 /// /// 矩形 / 圆角矩形 / 椭圆边界全程同向(凸),凹口数为 0; /// 云由多个鼓包拼接而成,凹口 ≥ 3。 int _concaveRunCount(List pts) { final int total = pts.length; if (total < 24) return 0; final int k = math.max(2, total ~/ 20); final List turns = []; for (int i = 0; i < total; i++) { final Offset a = pts[(i + k) % total] - pts[i]; final Offset b = pts[(i + 2 * k) % total] - pts[(i + k) % total]; final double la = a.distance; final double lb = b.distance; if (la < 0.001 || lb < 0.001) { turns.add(0); continue; } double s = (a.dx * b.dy - a.dy * b.dx) / (la * lb); s = s.clamp(-1.0, 1.0); turns.add(math.asin(s) * 180 / math.pi); } double totalTurn = 0; for (final double v in turns) { totalTurn += v; } final double dir = totalTurn >= 0 ? 1 : -1; int runs = 0; bool inRun = false; for (int i = 0; i < total * 2; i++) { final bool concave = turns[i % total] * dir < -10.0; if (concave && !inRun) { runs++; inRun = true; } else if (!concave) { inRun = false; } } return (runs / 2).round(); } /// 构造直线识别结果;方向接近水平 / 垂直(±8°)时吸附到正轴。 ArchRecognition _line(Offset a, Offset b, {required bool arrow}) { Offset aa = a; Offset bb = b; final Offset d = b - a; if (d.distance > 0.001) { final double ang = math.atan2(d.dy, d.dx) * 180 / math.pi; double m = ang % 180; if (m > 90) m -= 180; // 归一化到 (-90, 90]:0 = 水平,±90 = 垂直 final double devH = m.abs(); final double devV = 90 - m.abs(); if (devH <= 8) { final double y = (a.dy + b.dy) / 2; aa = Offset(a.dx, y); bb = Offset(b.dx, y); } else if (devV <= 8) { final double x = (a.dx + b.dx) / 2; aa = Offset(x, a.dy); bb = Offset(x, b.dy); } } return ArchRecognition( type: ArchShapeType.line, rect: Rect.fromPoints(aa, bb), a: aa, b: bb, arrow: arrow, ); } // ===================== 闭合笔迹:多边形 / 椭圆 ===================== /// 闭合笔迹分类:顶点数 + 椭圆残差(分位)+ 贴边率。 ArchRecognition? _classifyClosed(List raw, Rect bb, double diag) { final List pts = _resample(raw, 72); final double res90 = _percentile(_ellipseResiduals(pts, bb), 0.90); final List poly = _rdpIndices(pts, math.max(2.2, 0.016 * diag), closed: true); final List merged = _mergeCollinear( pts, poly, 13, math.max(3.0, 0.075 * diag), ); final int n = merged.length; // 顶点很少(光滑闭合曲线)→ 椭圆残差小则是圆 / 椭圆。 if (n <= 2) { return res90 <= 0.15 ? _ellipseFrom(bb) : null; } if (n >= 7) { if (res90 <= 0.15) return _ellipseFrom(bb); // 云:边界上有多个「凹口」(鼓包相接处);矩形类边界全凸、椭圆已排除。 if (_concaveRunCount(pts) >= 3) { return ArchRecognition(type: ArchShapeType.cloud, rect: bb); } // 大圆角矩形会被化简出很多顶点:贴边率高 → 按矩形(含圆角)处理。 if (_sideFit(pts, bb) >= 0.5) return _quadFromRect(pts, bb); return null; } if (n == 6) { if (res90 <= 0.15) return _ellipseFrom(bb); // 起笔 / 收笔接缝可能带来 1–2 个多余顶点,先尝试合并回四边形。 final List? quad = _tryMergeToQuad(pts, merged, 13); if (quad != null && _sideFit(pts, bb) >= 0.45) { return _quad(pts, bb, quad); } return ArchRecognition(type: ArchShapeType.hexagon, rect: bb); } if (n == 5) { final List? quad = _tryMergeToQuad(pts, merged, 13); if (quad != null && _sideFit(pts, bb) >= 0.45) { return _quad(pts, bb, quad); } // 五边形等暂无对应标准图形:保留墨迹。 return null; } if (n == 3) return _triangle(pts, bb, merged); return _quad(pts, bb, merged); } /// 由外接矩形构造椭圆 / 圆(长短边接近时归一为圆)。 ArchRecognition _ellipseFrom(Rect bb) { final double w = bb.width; final double h = bb.height; if (w > 0 && h > 0 && (w - h).abs() <= 0.18 * math.max(w, h)) { final double d = (w + h) / 2; return ArchRecognition( type: ArchShapeType.circle, rect: Rect.fromCenter(center: bb.center, width: d, height: d), ); } return ArchRecognition(type: ArchShapeType.ellipse, rect: bb); } /// 四顶点:按边方向判别矩形(含圆角矩形)与菱形。 ArchRecognition? _quad(List pts, Rect bb, List merged) { final List v = [for (final int i in merged) pts[i]]; double axisScore = 0; double diagScore = 0; for (int i = 0; i < 4; i++) { final Offset e = v[(i + 1) % 4] - v[i]; if (e.distance < 0.5) return null; final double ang = math.atan2(e.dy, e.dx) * 180 / math.pi; double m = ang % 90; if (m < 0) m += 90; final double b = math.min(m, 90 - m); // 与最近坐标轴的夹角(0..45) axisScore += b; diagScore += 45 - b; } if (axisScore > diagScore) { return ArchRecognition(type: ArchShapeType.diamond, rect: bb); } return _quadFromRect(pts, bb); } /// 矩形系列:估计圆角半径(外接矩形四角到笔迹的最小距离 / 0.414), /// 明显圆角 → 圆角矩形。 ArchRecognition _quadFromRect(List pts, Rect bb) { final double minSide = math.min(bb.width, bb.height); final double r = _cornerRadiusFromBbox(pts, bb); if (r > math.max(9, 0.075 * minSide)) { return ArchRecognition( type: ArchShapeType.roundRect, rect: bb, radius: math.min(r, 0.45 * minSide), ); } return ArchRecognition(type: ArchShapeType.rect, rect: bb); } /// 三角形:最长边为底,把顶点吸附到外接矩形的对应边上(正三角 / 直角靠边)。 ArchRecognition? _triangle(List pts, Rect bb, List merged) { final List v = [for (final int i in merged) pts[i]]; double bestLen = -1; int baseI = 0; for (int i = 0; i < 3; i++) { final double d = (v[(i + 1) % 3] - v[i]).distance; if (d > bestLen) { bestLen = d; baseI = i; } } final Offset b0 = v[baseI]; final Offset b1 = v[(baseI + 1) % 3]; final Offset apex = v[(baseI + 2) % 3]; final Offset baseMid = (b0 + b1) / 2; final bool horiz = (b1.dx - b0.dx).abs() >= (b1.dy - b0.dy).abs(); if (horiz) { final bool up = apex.dy < baseMid.dy; final double baseY = up ? bb.bottom : bb.top; final double apexY = up ? bb.top : bb.bottom; return ArchRecognition( type: ArchShapeType.triangle, rect: Rect.fromLTRB( bb.left, math.min(apexY, baseY), bb.right, math.max(apexY, baseY), ), dir: up ? 0 : 2, ); } final bool left = apex.dx < baseMid.dx; final double baseX = left ? bb.right : bb.left; final double apexX = left ? bb.left : bb.right; return ArchRecognition( type: ArchShapeType.triangle, rect: Rect.fromLTRB( math.min(apexX, baseX), bb.top, math.max(apexX, baseX), bb.bottom, ), dir: left ? 3 : 1, ); } // ===================== 几何工具 ===================== /// 椭圆残差列表:以 [bb] 为「拟合椭圆」,逐点计算归一化偏差。 List _ellipseResiduals(List pts, Rect bb) { final double rx = bb.width / 2; final double ry = bb.height / 2; if (rx < 1 || ry < 1 || pts.isEmpty) return [1]; final List out = []; for (final Offset p in pts) { final double nx = (p.dx - bb.center.dx) / rx; final double ny = (p.dy - bb.center.dy) / ry; out.add((math.sqrt(nx * nx + ny * ny) - 1).abs()); } return out; } /// 分位数([q] 0..1)。 double _percentile(List values, double q) { if (values.isEmpty) return 1; final List s = List.of(values)..sort(); final int idx = ((s.length - 1) * q).round().clamp(0, s.length - 1); return s[idx]; } /// 贴边率:笔迹点贴近外接矩形四条边的比例 /// (区分「有直边的矩形」与「全曲线的椭圆」)。 double _sideFit(List pts, Rect bb) { if (pts.isEmpty) return 0; final double eps = math.max(4.0, 0.05 * math.min(bb.width, bb.height)); int hit = 0; for (final Offset p in pts) { final double d = math.min( math.min((p.dy - bb.top).abs(), (p.dy - bb.bottom).abs()), math.min((p.dx - bb.left).abs(), (p.dx - bb.right).abs()), ); if (d <= eps) hit++; } return hit / pts.length; } /// 估计圆角半径:外接矩形四个角到笔迹的最小距离 / (√2−1) /// (90° 圆角弧线到尖角的距离恰为 0.414r),再减去手抖带来的基础偏差。 double _cornerRadiusFromBbox(List pts, Rect bb) { final List corners = [ bb.topLeft, bb.topRight, bb.bottomRight, bb.bottomLeft, ]; double sum = 0; for (final Offset c in corners) { double dmin = double.infinity; for (final Offset p in pts) { final double d = (p - c).distance; if (d < dmin) dmin = d; } sum += dmin; } return math.max(0, (sum / 4) / 0.4142 - 3.5); } /// 四边形的「与坐标轴 / 对角线贴合度」:各边到最近轴(0° / 90°)或 /// 对角线(45°)的平均偏差(度)。越小越像矩形 / 菱形。 double _quadDeviation(List pts, List quad) { final List v = [for (final int i in quad) pts[i]]; double axis = 0; double diag = 0; for (int i = 0; i < 4; i++) { final Offset e = v[(i + 1) % 4] - v[i]; if (e.distance < 0.5) return double.infinity; final double ang = math.atan2(e.dy, e.dx) * 180 / math.pi; double m = ang % 90; if (m < 0) m += 90; final double b = math.min(m, 90 - m); axis += b; diag += 45 - b; } return math.min(axis, diag) / 4; } /// 尝试把 5 / 6 个顶点合并成四边形(起笔 / 收笔接缝可能多出顶点): /// 暴力尝试删除 1–2 个顶点,取「最像四边形」的组合;偏差超限返回 null。 List? _tryMergeToQuad(List pts, List merged, double maxDev) { final int n = merged.length; if (n == 4) return merged; if (n < 4 || n > 6) return null; double best = maxDev; List? bestSet; if (n == 5) { for (int i = 0; i < 5; i++) { final List r = List.of(merged)..removeAt(i); final double d = _quadDeviation(pts, r); if (d < best) { best = d; bestSet = r; } } } else { for (int i = 0; i < 6; i++) { for (int j = i + 1; j < 6; j++) { final List r = List.of(merged) ..removeAt(j) ..removeAt(i); final double d = _quadDeviation(pts, r); if (d < best) { best = d; bestSet = r; } } } } return bestSet; } /// 最大偏距:所有点到直线 a–b 的距离最大值。 double _maxDeviation(List pts, Offset a, Offset b) { double m = 0; for (final Offset p in pts) { final double d = archDistToSegment(p, a, b); if (d > m) m = d; } return m; } /// 去掉间距过近的重复点。 List _clean(List raw) { final List out = []; for (final Offset p in raw) { if (out.isEmpty || (p - out.last).distance > 0.6) out.add(p); } return out; } /// 折线总长。 double _polyLength(List pts) { double s = 0; for (int i = 1; i < pts.length; i++) { s += (pts[i] - pts[i - 1]).distance; } return s; } /// 外接矩形。 Rect _bounds(List pts) { 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; } return Rect.fromLTRB(l, t, r, b); } /// 重采样成 [n] 个均匀点(按弧长)。 List _resample(List pts, int n) { final double len = _polyLength(pts); if (len <= 0.0001 || pts.length < 2) return List.of(pts); final double step = len / (n - 1); final List out = [pts.first]; double need = step; Offset prev = pts.first; for (int i = 1; i < pts.length && out.length < n; i++) { Offset cur = pts[i]; double segLen = (cur - prev).distance; while (segLen >= need && segLen > 0.0001 && out.length < n) { final Offset np = prev + (cur - prev) * (need / segLen); out.add(np); prev = np; segLen = (cur - prev).distance; need = step; } need -= segLen; prev = cur; } while (out.length < n) { out.add(pts.last); } return out; } /// Douglas-Peucker 顶点索引([closed] 时把首点视为终点,去掉重复)。 List _rdpIndices(List pts, double eps, {bool closed = false}) { final List work = closed ? [...pts, pts.first] : pts; final List keep = List.filled(work.length, false); keep[0] = true; keep[work.length - 1] = true; final List> stack = >[ [0, work.length - 1], ]; while (stack.isNotEmpty) { final List seg = stack.removeLast(); final int s = seg[0]; final int e = seg[1]; double maxD = 0; int idx = -1; for (int i = s + 1; i < e; i++) { final double d = archDistToSegment(work[i], work[s], work[e]); if (d > maxD) { maxD = d; idx = i; } } if (idx >= 0 && maxD > eps) { keep[idx] = true; stack.add([s, idx]); stack.add([idx, e]); } } final List out = []; for (int i = 0; i < work.length; i++) { if (keep[i]) out.add(i); } if (closed && out.isNotEmpty && out.last == work.length - 1) { out.removeLast(); } return out; } /// 合并近似共线的折点(也合并过短的边),直到稳定;最少保留 3 个顶点。 List _mergeCollinear( List pts, List idx, double tolDeg, double minSeg, ) { final List cur = List.of(idx); bool changed = true; while (changed && cur.length > 3) { changed = false; final int n = cur.length; for (int i = 0; i < n; i++) { final Offset p = pts[cur[(i - 1 + n) % n]]; final Offset v = pts[cur[i]]; final Offset q = pts[cur[(i + 1) % n]]; final double turn = _turnDeg(p, v, q); final bool tiny = (v - p).distance < minSeg || (q - v).distance < minSeg; if (turn < tolDeg || tiny) { cur.removeAt(i); changed = true; break; } } } return cur; } /// 折点转向角(度):0 = 直线方向,90 = 直角折点。 double _turnDeg(Offset p, Offset v, Offset q) { final Offset a = v - p; final Offset b = q - v; final double la = a.distance; final double lb = b.distance; if (la < 0.001 || lb < 0.001) return 0; final double c = (_dot(a, b) / (la * lb)).clamp(-1.0, 1.0); return math.acos(c) * 180 / math.pi; } /// 点积(dart:ui 的 Offset 无 dot,自带实现)。 double _dot(Offset a, Offset b) => a.dx * b.dx + a.dy * b.dy;