v1.3.13: 模块化注册架构 + PDS流程设计套件更名 + 依赖/圆周交互修复

- 模块化:EdcModule 契约 + registry + 模块独立目录;发布包增加 modules/registry.json
- 更名:PDS流程设计套件 / ProcessDesignSuite;同步构建、发布脚本与文档
- 时序图:依赖偏移以时间显示/编辑;紧贴依赖隐藏箭头并在接缝显示标签;动作条磁吸
- 圆周:依赖标签沿圆弧方向、环间空隙;动作旋转磁吸增强;短弧标签优先动作名
- 清理:release 移至源码同级(本地不入库);tool 合并到 tools;发布说明迁移 docs/release-notes
This commit is contained in:
2026-11-22 10:02:48 +08:00
parent afc4dc6dd7
commit 0a3f2c5cc6
105 changed files with 6309 additions and 3577 deletions
@@ -0,0 +1,268 @@
/// 架构图 DXF 导出(AutoCAD R12 ASCII,AC1009):
/// 可直接在 AutoCAD / DraftSight / ZWCAD 等 CAD 软件中打开继续编辑。
///
/// 约定:
/// - 图形几何统一采样为 POLYLINE/VERTEX(圆用 CIRCLE、直线用 LINE);
/// - 文字用 TEXT(多行拆多条),连线标签同;
/// - 图层按架构图图层写入 TABLES→LAYER(颜色近似为 ACI 色号);
/// - Y 轴取反(CAD 绿轴向上,画布向下)。
library;
import 'dart:math' as math;
import 'dart:ui';
import 'package:sequence_diagram/modules/architecture/library/symbol_library.dart';
import 'arch_models.dart';
import 'arch_painter.dart';
/// 构造架构图 DXF 文本。
String buildArchDxf({required ArchDoc doc}) {
final StringBuffer sb = StringBuffer();
sb.write('0\nSECTION\n2\nHEADER\n9\n\$ACADVER\n1\nAC1009\n0\nENDSEC\n');
// TABLES → LAYER
sb.write('0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nLAYER\n70\n'
'${doc.layers.length}\n');
for (final ArchLayer l in doc.layers) {
sb.write('0\nLAYER\n2\n${_name(l.name)}\n70\n0\n62\n${_aci(l.color)}\n'
'6\nCONTINUOUS\n');
}
sb.write('0\nENDTAB\n0\nENDSEC\n');
// ENTITIES
sb.write('0\nSECTION\n2\nENTITIES\n');
for (final ArchConnector c in doc.connectors) {
if (!doc.isLayerVisible(c.layerId)) continue;
_connector(sb, doc, c);
}
for (final ArchShape s in doc.shapes) {
if (!doc.isLayerVisible(s.layerId)) continue;
_shape(sb, doc, s);
}
for (final ArchStroke s in doc.strokes) {
if (!doc.isLayerVisible(s.layerId)) continue;
_polyline(sb, _layerName(doc, s.layerId), s.pts, false);
}
sb.write('0\nENDSEC\n0\nEOF\n');
return sb.toString();
}
// ===================== 图形 =====================
void _shape(StringBuffer sb, ArchDoc doc, ArchShape s) {
final String layer = _layerName(doc, s.layerId);
switch (s.type) {
case ArchShapeType.line:
final Offset a = s.a ?? s.rect.topLeft;
final Offset b = s.b ?? s.rect.bottomRight;
_line(sb, layer, a, b);
if (s.arrow) _solidArrow(sb, layer, a, b);
break;
case ArchShapeType.circle:
_circle(sb, layer, s.rect.center, s.rect.width / 2);
break;
case ArchShapeType.text:
break;
case ArchShapeType.rect:
_polyline(
sb,
layer,
<Offset>[
s.rect.topLeft,
s.rect.topRight,
s.rect.bottomRight,
s.rect.bottomLeft,
],
true,
);
break;
case ArchShapeType.polyline:
_polyline(sb, layer, s.pts, false);
break;
case ArchShapeType.curve:
_samplePath(sb, layer, archSplinePath(s.pts), closed: false);
break;
case ArchShapeType.roundRect:
case ArchShapeType.ellipse:
case ArchShapeType.triangle:
case ArchShapeType.diamond:
case ArchShapeType.cylinder:
case ArchShapeType.cloud:
case ArchShapeType.hexagon:
case ArchShapeType.server:
case ArchShapeType.client:
case ArchShapeType.mobile:
case ArchShapeType.firewall:
case ArchShapeType.netSwitch:
case ArchShapeType.queue:
_samplePath(sb, layer, archShapePath(s), closed: true);
break;
case ArchShapeType.symbol:
final LibSymbol? sym = SymbolCache.byId(s.symbolId);
final Path symPath = (sym == null || s.symbolId.isEmpty)
? archShapePath(s)
: buildSymbolPath(sym, s.rect);
_samplePathEach(sb, layer, symPath);
break;
}
if (s.text.isNotEmpty) {
final double size = s.type == ArchShapeType.text
? (s.rect.height * 0.72).clamp(10.0, 120.0).toDouble()
: 12.5;
Offset center = s.rect.center;
if (s.type == ArchShapeType.cloud) {
center = center.translate(0, s.rect.height * 0.12);
}
_text(sb, layer, s.text, center, size);
}
}
void _connector(StringBuffer sb, ArchDoc doc, ArchConnector c) {
final String layer = _layerName(doc, c.layerId);
final ArchConnGeometry g = archConnectorGeometry(doc, c);
_polyline(sb, layer, g.pts, false);
if (g.pts.length >= 2) {
_solidArrow(sb, layer, g.pts[g.pts.length - 2], g.end);
}
if (c.label.isNotEmpty) {
_text(sb, layer, c.label, g.label, 10.5);
}
}
// ===================== 实体 =====================
void _polyline(StringBuffer sb, String layer, List<Offset> pts, bool closed) {
if (pts.length < 2) return;
sb.write('0\nPOLYLINE\n8\n$layer\n66\n1\n70\n${closed ? 1 : 0}\n');
for (final Offset p in pts) {
sb.write('0\nVERTEX\n8\n$layer\n10\n${_n(p.dx)}\n20\n${_n(-p.dy)}\n'
'30\n0\n');
}
sb.write('0\nSEQEND\n8\n$layer\n');
}
void _circle(StringBuffer sb, String layer, Offset c, double r) {
sb.write('0\nCIRCLE\n8\n$layer\n10\n${_n(c.dx)}\n20\n${_n(-c.dy)}\n30\n0\n'
'40\n${_n(r)}\n');
}
void _line(StringBuffer sb, String layer, Offset a, Offset b) {
sb.write('0\nLINE\n8\n$layer\n10\n${_n(a.dx)}\n20\n${_n(-a.dy)}\n30\n0\n'
'11\n${_n(b.dx)}\n21\n${_n(-b.dy)}\n31\n0\n');
}
void _solidArrow(StringBuffer sb, String layer, Offset from, Offset to) {
final Offset d = to - from;
final double len = d.distance;
if (len < 1) return;
final Offset u = d / len;
final Offset n = Offset(-u.dy, u.dx);
const double hl = 11;
const double hw = 5.5;
final Offset p1 = to - u * hl + n * hw;
final Offset p2 = to - u * hl - n * hw;
sb.write('0\nSOLID\n8\n$layer\n'
'10\n${_n(to.dx)}\n20\n${_n(-to.dy)}\n30\n0\n'
'11\n${_n(p1.dx)}\n21\n${_n(-p1.dy)}\n31\n0\n'
'12\n${_n(p2.dx)}\n22\n${_n(-p2.dy)}\n32\n0\n'
'13\n${_n(p2.dx)}\n23\n${_n(-p2.dy)}\n33\n0\n');
}
void _text(StringBuffer sb, String layer, String text, Offset center, double size) {
final List<String> lines = text.split('\n');
final double lh = size * 1.25;
final double y0 = center.dy - (lines.length - 1) * lh / 2;
for (int i = 0; i < lines.length; i++) {
final double yy = y0 + i * lh;
sb.write('0\nTEXT\n8\n$layer\n'
'10\n${_n(center.dx)}\n20\n${_n(-yy)}\n30\n0\n'
'40\n${_n(size)}\n1\n${_esc(lines[i])}\n'
'72\n1\n73\n2\n'
'11\n${_n(center.dx)}\n21\n${_n(-yy)}\n31\n0\n');
}
}
/// 沿路径按固定步长采样为折线(圆弧近似)。
void _samplePath(StringBuffer sb, String layer, Path path,
{required bool closed}) {
final List<Offset> pts = <Offset>[];
for (final PathMetric m in path.computeMetrics()) {
final int count = math.max(4, (m.length / 6).ceil());
for (int i = 0; i <= count; i++) {
final Tangent? t = m.getTangentForOffset(m.length * i / count);
if (t != null) pts.add(t.position);
}
}
if (pts.length > 1 && (pts.first - pts.last).distance < 0.5) {
pts.removeLast();
}
_polyline(sb, layer, pts, closed);
}
/// 每条子路径各自输出一条折线(图元库符号:多段线互不相连,不能合并)。
void _samplePathEach(StringBuffer sb, String layer, Path path) {
for (final PathMetric m in path.computeMetrics()) {
final int count = math.max(2, (m.length / 6).ceil());
final List<Offset> pts = <Offset>[];
for (int i = 0; i <= count; i++) {
final Tangent? t = m.getTangentForOffset(m.length * i / count);
if (t != null) pts.add(t.position);
}
if (pts.length > 1 && (pts.first - pts.last).distance < 0.5) {
pts.removeLast();
}
_polyline(sb, layer, pts, m.isClosed);
}
}
// ===================== 工具 =====================
String _layerName(ArchDoc doc, String layerId) =>
_name(doc.layerById(layerId).name);
/// 图层 / 实体名安全化(DXF 名称不允许空格等特殊字符)。
String _name(String raw) {
final String n = raw.replaceAll(RegExp(r'[^\w\u4e00-\u9fa5\-]'), '_');
return n.isEmpty ? 'LAYER' : n;
}
/// 颜色近似为 AutoCAD 颜色号(R12 兼容)。
int _aci(int argb) {
const List<(int, int)> table = <(int, int)>[
(0xFF4CC9F0, 4),
(0xFF34D399, 3),
(0xFFFFD166, 2),
(0xFFFF8A5C, 30),
(0xFFF472B6, 6),
(0xFFA78BFA, 200),
(0xFF38BDF8, 5),
(0xFF94A3B8, 8),
(0xFF7C8DA6, 8),
];
final int r = (argb >> 16) & 0xFF;
final int g = (argb >> 8) & 0xFF;
final int b = argb & 0xFF;
int best = 7;
double bestD = double.infinity;
for (final (int rgb, int aci) in table) {
final int rr = (rgb >> 16) & 0xFF;
final int gg = (rgb >> 8) & 0xFF;
final int bb = rgb & 0xFF;
final double d = ((r - rr) * (r - rr) +
(g - gg) * (g - gg) +
(b - bb) * (b - bb))
.toDouble();
if (d < bestD) {
bestD = d;
best = aci;
}
}
return best;
}
String _n(double v) {
if ((v - v.roundToDouble()).abs() < 0.005) return v.round().toString();
return v.toStringAsFixed(2);
}
String _esc(String s) => s.replaceAll('\n', ' ').replaceAll('\r', ' ');
@@ -0,0 +1,607 @@
/// 架构图导出:SVG(矢量,可直接进文档 / 二次编辑)与 PNG(3840×2160 位图)。
///
/// 与其他导出保持同一约定:
/// - 导出始终使用**纯白背景**([exportTokens]),与屏幕主题无关;
/// - PNG 画布固定 1920×1080 逻辑尺寸 × 2 倍像素;
/// - 不导出网格点阵与选中框,只导出设计内容。
library;
import 'dart:math' as math;
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:sequence_diagram/export/export_geometry.dart';
import 'package:sequence_diagram/modules/architecture/library/symbol_library.dart';
import 'package:sequence_diagram/theme/tokens.dart';
import 'arch_models.dart';
import 'arch_painter.dart';
// ===================== PNG =====================
/// 渲染架构图 PNG(3840×2160 位图)并返回字节。
Future<Uint8List> renderArchPng({
required ArchDoc doc,
required Tokens baseTokens,
required String projectName,
}) async {
final Tokens et = exportTokens(baseTokens);
final ui.PictureRecorder recorder = ui.PictureRecorder();
final Canvas canvas = Canvas(recorder);
const double w = 1920;
const double h = 1080;
canvas.scale(kExportPixelRatio);
canvas.drawRect(
const Rect.fromLTWH(0, 0, w, h),
Paint()..color = Colors.white,
);
// 标题与副标题(固定左上角)。
_text(canvas, '架构图设计', const Offset(48, 36),
color: et.text, size: 34, weight: FontWeight.w700);
_text(canvas, 'PDS流程设计套件 · Process Design Suite · 手绘识别架构图', const Offset(48, 88),
color: et.sub, size: 16, weight: FontWeight.w400);
// 内容适配(白底令牌 + 关闭网格点阵)。
final Rect b = doc.contentBounds().inflate(40);
final ExportFit fit = _contentFit(b, kExportContentArea);
canvas.save();
canvas.translate(fit.tx, fit.ty);
ArchPainter(
doc: doc.copyWith(zoom: fit.scale, panX: 0, panY: 0, gridSize: 0),
t: et,
).paint(canvas, const Size(w, h));
canvas.restore();
_text(
canvas,
'PDS流程设计套件 · 架构图设计 · $projectName · 元件 ${doc.shapes.length} · 连线 '
'${doc.connectors.length} · 墨迹 ${doc.strokes.length}',
Offset(48, h - 38),
color: et.sub,
size: 15,
weight: FontWeight.w400,
);
final ui.Image image = await recorder.endRecording().toImage(
(w * kExportPixelRatio).toInt(),
(h * kExportPixelRatio).toInt(),
);
final ByteData? data = await image.toByteData(format: ui.ImageByteFormat.png);
return data!.buffer.asUint8List();
}
/// 内容适配:等比缩放并居中到 [area]。
ExportFit _contentFit(Rect bounds, Rect area) {
if (bounds.width <= 1 || bounds.height <= 1) {
return const ExportFit(1, 0, 0);
}
final double s = math
.min(area.width / bounds.width, area.height / bounds.height)
.clamp(0.1, 1.6)
.toDouble();
final double tx =
area.left + (area.width - bounds.width * s) / 2 - bounds.left * s;
final double ty =
area.top + (area.height - bounds.height * s) / 2 - bounds.top * s;
return ExportFit(s, tx, ty);
}
/// 用统一字体绘制单行文本。
void _text(
Canvas canvas,
String s,
Offset at, {
required Color color,
required double size,
required FontWeight weight,
}) {
final TextPainter tp = TextPainter(
text: TextSpan(
text: s,
style: TextStyle(
color: color,
fontSize: size,
fontWeight: weight,
fontFamily: 'Microsoft YaHei UI',
fontFamilyFallback: const <String>[
'Microsoft YaHei',
'Noto Sans SC',
'sans-serif',
],
),
),
textDirection: TextDirection.ltr,
)..layout();
tp.paint(canvas, Offset(at.dx, at.dy - tp.height / 2));
}
// ===================== SVG =====================
/// 构造架构图 SVG 文本(viewBox = 内容范围 + 留白;纯白背景)。
String buildArchSvg({required ArchDoc doc, required Tokens baseTokens}) {
final Tokens t = exportTokens(baseTokens);
final Rect b = doc.contentBounds().inflate(40);
final double w = math.max(b.width, 200);
final double h = math.max(b.height, 160);
final StringBuffer sb = StringBuffer();
sb.writeln('<?xml version="1.0" encoding="UTF-8"?>');
sb.writeln(
'<svg xmlns="http://www.w3.org/2000/svg" width="${w.round()}" height="${h.round()}" '
'viewBox="${_n(b.left)} ${_n(b.top)} ${_n(w)} ${_n(h)}">');
sb.writeln('<rect x="${_n(b.left)}" y="${_n(b.top)}" width="${_n(w)}" height="${_n(h)}" fill="#ffffff"/>');
// 连线(底层)。
for (final ArchConnector c in doc.connectors) {
if (!doc.isLayerVisible(c.layerId)) continue;
_svgConnector(sb, doc, c);
}
// 图形。
for (final ArchShape s in doc.shapes) {
if (!doc.isLayerVisible(s.layerId)) continue;
_svgShape(sb, s, t);
}
// 手绘墨迹。
for (final ArchStroke s in doc.strokes) {
if (!doc.isLayerVisible(s.layerId)) continue;
sb.writeln(
'<path d="${_smoothD(s.pts)}" fill="none" stroke="${_hex(s.color)}" stroke-width="${_n(s.w)}" '
'stroke-linecap="round" stroke-linejoin="round"/>');
}
sb.writeln('</svg>');
return sb.toString();
}
/// 连线(含正交折线、虚线、箭头与标签)。
void _svgConnector(StringBuffer sb, ArchDoc doc, ArchConnector c) {
final ArchConnGeometry g = archConnectorGeometry(doc, c);
final String d = _polyD(g.pts);
final String color = _hex(c.color);
final String dash = c.dash ? ' stroke-dasharray="8 6"' : '';
sb.writeln(
'<path d="$d" fill="none" stroke="$color" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"$dash/>');
// 箭头(终点方向)。
if (g.pts.length >= 2) {
final Offset a = g.pts[g.pts.length - 2];
final Offset b2 = g.end;
final Offset dv = b2 - a;
final double len = dv.distance;
if (len > 1) {
final Offset u = dv / len;
final Offset n = Offset(-u.dy, u.dx);
const double hl = 11;
const double hw = 5.5;
final Offset p1 = b2 - u * hl + n * hw;
final Offset p2 = b2 - u * hl - n * hw;
sb.writeln(
'<polygon points="${_n(b2.dx)},${_n(b2.dy)} ${_n(p1.dx)},${_n(p1.dy)} ${_n(p2.dx)},${_n(p2.dy)}" fill="$color"/>');
}
}
// 标签(白底片 + 文本)。
if (c.label.isNotEmpty) {
final double lw = math.max(20, c.label.length * 10.5 + 10);
final Rect bg = Rect.fromCenter(center: g.label, width: lw, height: 18);
sb.writeln(
'<rect x="${_n(bg.left)}" y="${_n(bg.top)}" width="${_n(bg.width)}" height="${_n(bg.height)}" rx="5" '
'fill="#ffffff" stroke="#c9d6e5" stroke-width="1"/>');
sb.writeln(
'<text x="${_n(g.label.dx)}" y="${_n(g.label.dy)}" text-anchor="middle" dominant-baseline="central" '
'font-family="Microsoft YaHei UI" font-size="10.5" fill="${_hex(0xFF334155)}">${_esc(c.label)}</text>');
}
}
/// 单个标准图形。
void _svgShape(StringBuffer sb, ArchShape s, Tokens t) {
final String fill = _hex(s.fill);
final String fillOp = _op(s.fill);
final String stroke = _hex(s.stroke);
final String sw = _n(s.sw);
final Rect r = s.rect;
switch (s.type) {
case ArchShapeType.rect:
sb.writeln(
'<rect x="${_n(r.left)}" y="${_n(r.top)}" width="${_n(r.width)}" height="${_n(r.height)}" '
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
break;
case ArchShapeType.roundRect:
final double rad = math.min(s.radius, math.min(r.width, r.height) * 0.45);
sb.writeln(
'<rect x="${_n(r.left)}" y="${_n(r.top)}" width="${_n(r.width)}" height="${_n(r.height)}" rx="${_n(rad)}" '
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
break;
case ArchShapeType.ellipse:
case ArchShapeType.circle:
sb.writeln(
'<ellipse cx="${_n(r.center.dx)}" cy="${_n(r.center.dy)}" rx="${_n(r.width / 2)}" ry="${_n(r.height / 2)}" '
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
break;
case ArchShapeType.triangle:
sb.writeln(
'<polygon points="${_points(archTrianglePoints(s))}" fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
break;
case ArchShapeType.diamond:
sb.writeln(
'<polygon points="${_points(archDiamondPoints(r))}" fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
break;
case ArchShapeType.hexagon:
sb.writeln(
'<polygon points="${_points(archHexagonPoints(r))}" fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
break;
case ArchShapeType.cylinder:
final double ry = math.min(r.height * 0.20, r.width * 0.32);
final double l = r.left;
final double rt = r.right;
final double tp = r.top;
final double bt = r.bottom;
// 柱体(含底部弧)。
sb.writeln(
'<path d="M ${_n(l)} ${_n(tp + ry)} L ${_n(l)} ${_n(bt - ry)} '
'A ${_n(r.width / 2)} ${_n(ry)} 0 0 0 ${_n(rt)} ${_n(bt - ry)} '
'L ${_n(rt)} ${_n(tp + ry)} Z" '
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
// 顶盖(稍亮)。
final double lidOp =
math.min(1.0, (_opValue(s.fill) + 0.10));
sb.writeln(
'<ellipse cx="${_n(r.center.dx)}" cy="${_n(tp + ry)}" rx="${_n(r.width / 2)}" ry="${_n(ry)}" '
'fill="$fill" fill-opacity="${lidOp.toStringAsFixed(3)}" stroke="$stroke" stroke-width="$sw"/>');
break;
case ArchShapeType.cloud:
// 双层绘制:第一层带描边,第二层纯填充覆盖内部接缝 → 外轮廓保持描边。
final List<Offset> circles = <Offset>[
Offset(r.left + r.width * 0.24, r.top + r.height * 0.62),
Offset(r.left + r.width * 0.42, r.top + r.height * 0.40),
Offset(r.left + r.width * 0.64, r.top + r.height * 0.34),
Offset(r.left + r.width * 0.82, r.top + r.height * 0.58),
];
final List<double> radii = <double>[
r.height * 0.26,
r.height * 0.30,
r.height * 0.28,
r.height * 0.24,
];
final Rect base = Rect.fromLTRB(
r.left + r.width * 0.06,
r.top + r.height * 0.55,
r.right - r.width * 0.06,
r.top + r.height * 0.86,
);
for (int pass = 0; pass < 2; pass++) {
final bool strokePass = pass == 0;
for (int i = 0; i < circles.length; i++) {
sb.writeln(
'<circle cx="${_n(circles[i].dx)}" cy="${_n(circles[i].dy)}" r="${_n(radii[i])}" '
'fill="$fill" fill-opacity="$fillOp"'
'${strokePass ? ' stroke="$stroke" stroke-width="$sw"' : ''}/>');
}
sb.writeln(
'<rect x="${_n(base.left)}" y="${_n(base.top)}" width="${_n(base.width)}" height="${_n(base.height)}" '
'rx="${_n(r.height * 0.22)}" fill="$fill" fill-opacity="$fillOp"'
'${strokePass ? ' stroke="$stroke" stroke-width="$sw"' : ''}/>');
}
break;
case ArchShapeType.server:
case ArchShapeType.client:
case ArchShapeType.mobile:
case ArchShapeType.firewall:
case ArchShapeType.netSwitch:
case ArchShapeType.queue:
_svgItShape(sb, s, r, fill, fillOp, stroke, sw);
break;
case ArchShapeType.symbol:
_svgSymbol(sb, s, r, fill, fillOp, stroke, sw);
break;
case ArchShapeType.text:
break;
case ArchShapeType.line:
final Offset a = s.a ?? r.topLeft;
final Offset b2 = s.b ?? r.bottomRight;
sb.writeln(
'<line x1="${_n(a.dx)}" y1="${_n(a.dy)}" x2="${_n(b2.dx)}" y2="${_n(b2.dy)}" '
'stroke="$stroke" stroke-width="${_n(s.sw)}" stroke-linecap="round"/>');
if (s.arrow) {
_svgArrow(sb, a, b2, stroke);
}
break;
case ArchShapeType.polyline:
if (s.pts.length >= 2) {
sb.writeln(
'<polyline points="${_points(s.pts)}" fill="none" stroke="$stroke" stroke-width="${_n(s.sw)}" '
'stroke-linecap="round" stroke-linejoin="round"/>');
}
break;
case ArchShapeType.curve:
if (s.pts.length >= 2) {
sb.writeln(
'<path d="${_splineD(s.pts)}" fill="none" stroke="$stroke" stroke-width="${_n(s.sw)}" '
'stroke-linecap="round" stroke-linejoin="round"/>');
}
break;
}
// 图内文字。
if (s.text.isNotEmpty) {
final String tc = s.type == ArchShapeType.text
? _hex(s.stroke)
: _hex(0xFF1B2740);
double size = 12.5;
if (s.type == ArchShapeType.text) {
size = (s.rect.height * 0.72).clamp(10.0, 120.0).toDouble();
}
Offset center = s.rect.center;
if (s.type == ArchShapeType.cloud) {
center = center.translate(0, s.rect.height * 0.12);
} else if (s.type == ArchShapeType.cylinder) {
center = center.translate(
0,
math.min(s.rect.height * 0.20, s.rect.width * 0.32) * 0.8);
} else if (s.type == ArchShapeType.client) {
center = Offset(s.rect.center.dx, s.rect.top + s.rect.height * 0.32);
} else if (s.type == ArchShapeType.netSwitch) {
center = Offset(s.rect.center.dx, s.rect.top + s.rect.height * 0.30);
}
_svgMultilineText(sb, s.text, center.dx, center.dy, tc, size);
}
}
/// IT 图形(服务器 / PC / 移动端 / 防火墙 / 交换机 / 队列)的 SVG 绘制。
void _svgItShape(StringBuffer sb, ArchShape s, Rect r, String fill,
String fillOp, String stroke, String sw) {
final double rad = switch (s.type) {
ArchShapeType.server => math.min(12.0, math.min(r.width, r.height) * 0.12),
ArchShapeType.client => math.min(10.0, r.height * 0.08),
ArchShapeType.mobile => math.min(16.0, r.width * 0.22),
ArchShapeType.firewall => math.min(6.0, r.height * 0.10),
ArchShapeType.netSwitch => math.min(10.0, r.height * 0.20),
ArchShapeType.queue => r.height * 0.5,
_ => 0.0,
};
sb.writeln(
'<rect x="${_n(r.left)}" y="${_n(r.top)}" width="${_n(r.width)}" height="${_n(r.height)}" rx="${_n(rad)}" '
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
final String inner =
'stroke="$stroke" stroke-width="${_n(math.max(1, s.sw * 0.7))}" stroke-linecap="round"';
void hline(double y, double x0, double x1) {
sb.writeln('<line x1="${_n(x0)}" y1="${_n(y)}" x2="${_n(x1)}" y2="${_n(y)}" $inner/>');
}
void dot(double x, double y, double radius) {
sb.writeln(
'<circle cx="${_n(x)}" cy="${_n(y)}" r="${_n(radius)}" fill="$stroke" fill-opacity="0.85"/>');
}
switch (s.type) {
case ArchShapeType.server:
for (int i = 1; i <= 3; i++) {
final double y = r.top + r.height * i / 4;
hline(y, r.left + r.width * 0.10, r.right - r.width * 0.10);
}
for (int i = 0; i < 4; i++) {
dot(r.left + r.width * 0.16, r.top + r.height * (i + 0.5) / 4,
math.min(2.4, r.width * 0.035));
}
case ArchShapeType.client:
final Rect screen =
Rect.fromLTWH(r.left, r.top, r.width, r.height * 0.72);
sb.writeln(
'<rect x="${_n(screen.left)}" y="${_n(screen.top)}" width="${_n(screen.width)}" height="${_n(screen.height)}" rx="${_n(math.min(8, screen.height * 0.12))}" fill="none" stroke="$stroke" stroke-width="$sw"/>');
sb.writeln(
'<line x1="${_n(r.center.dx)}" y1="${_n(screen.bottom)}" x2="${_n(r.center.dx)}" y2="${_n(r.bottom - r.height * 0.10)}" $inner/>');
hline(r.bottom - r.height * 0.08, r.center.dx - r.width * 0.18,
r.center.dx + r.width * 0.18);
case ArchShapeType.mobile:
hline(r.top + r.height * 0.055, r.center.dx - r.width * 0.14,
r.center.dx + r.width * 0.14);
hline(r.bottom - r.height * 0.05, r.center.dx - r.width * 0.12,
r.center.dx + r.width * 0.12);
case ArchShapeType.firewall:
for (int i = 1; i < 3; i++) {
hline(r.top + r.height * i / 3, r.left, r.right);
}
for (int i = 0; i < 3; i++) {
final double y0 = r.top + r.height * i / 3;
final double y1 = r.top + r.height * (i + 1) / 3;
final double offset = i.isEven ? 0.5 : 0.25;
for (double fx = offset; fx < 0.95; fx += 0.5) {
final double x = r.left + r.width * fx;
sb.writeln(
'<line x1="${_n(x)}" y1="${_n(y0)}" x2="${_n(x)}" y2="${_n(y1)}" $inner/>');
}
}
case ArchShapeType.netSwitch:
final double size = math.min(r.height * 0.20, 8.0);
for (int i = 0; i < 6; i++) {
final double x = r.left + r.width * (0.10 + i * 0.135);
sb.writeln(
'<rect x="${_n(x)}" y="${_n(r.bottom - r.height * 0.42)}" width="${_n(size * 1.4)}" height="${_n(size)}" rx="1.5" fill="$stroke" fill-opacity="0.85"/>');
}
case ArchShapeType.queue:
final double h = r.height * 0.30;
for (int i = 0; i < 3; i++) {
final double x = r.left + r.width * (0.30 + i * 0.18);
sb.writeln(
'<path d="M ${_n(x - h * 0.35)} ${_n(r.center.dy - h * 0.5)} L ${_n(x + h * 0.35)} ${_n(r.center.dy)} L ${_n(x - h * 0.35)} ${_n(r.center.dy + h * 0.5)}" fill="none" $inner/>');
}
default:
break;
}
}
/// 图元库符号的 SVG 绘制(按 100×100 归一化基元映射到矩形)。
void _svgSymbol(StringBuffer sb, ArchShape s, Rect r, String fill,
String fillOp, String stroke, String sw) {
final LibSymbol? sym = SymbolCache.byId(s.symbolId);
if (sym == null || s.symbolId.isEmpty) {
sb.writeln(
'<rect x="${_n(r.left)}" y="${_n(r.top)}" width="${_n(r.width)}" height="${_n(r.height)}" rx="6" '
'fill="none" stroke="$stroke" stroke-width="$sw" stroke-dasharray="4 3"/>');
return;
}
Offset p2(double x, double y) => symPt(x, y, r);
final double rad = (r.width + r.height) / 2 / 100;
for (final SymPrim p in sym.prims) {
switch (p.kind) {
case SymPrimKind.text:
if (p.pts.length < 2 || p.label.isEmpty) break;
final Offset tl = p2(p.pts[0], p.pts[1]);
final double size =
(r.height * 0.14).clamp(7.0, 18.0).toDouble();
sb.writeln(
'<text x="${_n(tl.dx)}" y="${_n(tl.dy)}" font-family="Microsoft YaHei UI" font-size="${_n(size)}" '
'font-weight="600" fill="$stroke">${_esc(p.label)}</text>');
case SymPrimKind.line:
if (p.pts.length < 4) break;
final Offset a = p2(p.pts[0], p.pts[1]);
final Offset b = p2(p.pts[2], p.pts[3]);
sb.writeln(
'<line x1="${_n(a.dx)}" y1="${_n(a.dy)}" x2="${_n(b.dx)}" y2="${_n(b.dy)}" '
'stroke="$stroke" stroke-width="$sw" stroke-linecap="round"/>');
case SymPrimKind.polyline:
if (p.pts.length < 4) break;
final List<Offset> pts = <Offset>[
for (int i = 0; i + 1 < p.pts.length; i += 2) p2(p.pts[i], p.pts[i + 1]),
];
sb.writeln(
'<polyline points="${_points(pts)}" fill="none" stroke="$stroke" stroke-width="$sw" '
'stroke-linecap="round" stroke-linejoin="round"/>');
case SymPrimKind.circle:
if (p.pts.length < 2) break;
final Offset c = p2(p.pts[0], p.pts[1]);
final double rr = p.r * rad;
sb.writeln(
'<circle cx="${_n(c.dx)}" cy="${_n(c.dy)}" r="${_n(rr)}" '
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
case SymPrimKind.rect:
if (p.pts.length < 4) break;
final Offset tl = p2(p.pts[0], p.pts[1]);
sb.writeln(
'<rect x="${_n(tl.dx)}" y="${_n(tl.dy)}" width="${_n(p.pts[2] / 100 * r.width)}" height="${_n(p.pts[3] / 100 * r.height)}" '
'fill="$fill" fill-opacity="$fillOp" stroke="$stroke" stroke-width="$sw"/>');
case SymPrimKind.arc:
if (p.pts.length < 2) break;
final Offset c = p2(p.pts[0], p.pts[1]);
final double rr = p.r * rad;
final double a0 = p.startDeg * math.pi / 180;
final double a1 = (p.startDeg + p.sweepDeg) * math.pi / 180;
final Offset s0 =
c + Offset(math.cos(a0) * rr, math.sin(a0) * rr);
final Offset s1 =
c + Offset(math.cos(a1) * rr, math.sin(a1) * rr);
final int large = p.sweepDeg.abs() > 180 ? 1 : 0;
final int sweep = p.sweepDeg >= 0 ? 1 : 0;
sb.writeln(
'<path d="M ${_n(s0.dx)} ${_n(s0.dy)} A ${_n(rr)} ${_n(rr)} 0 $large $sweep ${_n(s1.dx)} ${_n(s1.dy)}" '
'fill="none" stroke="$stroke" stroke-width="$sw" stroke-linecap="round"/>');
}
}
}
/// 箭头头部(line 图形用)。
void _svgArrow(StringBuffer sb, Offset a, Offset b, String color) {
final Offset dv = b - a;
final double len = dv.distance;
if (len < 1) return;
final Offset u = dv / len;
final Offset n = Offset(-u.dy, u.dx);
const double hl = 11;
const double hw = 5.5;
final Offset p1 = b - u * hl + n * hw;
final Offset p2 = b - u * hl - n * hw;
sb.writeln(
'<polygon points="${_n(b.dx)},${_n(b.dy)} ${_n(p1.dx)},${_n(p1.dy)} ${_n(p2.dx)},${_n(p2.dy)}" fill="$color"/>');
}
/// 多行居中文本(每行一个 tspan)。
void _svgMultilineText(
StringBuffer sb, String text, double cx, double cy, String color, double size) {
final List<String> lines = text.split('\n');
final double lineH = size * 1.25;
final double startY = cy - (lines.length - 1) * lineH / 2;
sb.writeln(
'<text text-anchor="middle" dominant-baseline="central" font-family="Microsoft YaHei UI" '
'font-size="${_n(size)}" font-weight="600" fill="$color">');
for (int i = 0; i < lines.length; i++) {
sb.writeln(
'<tspan x="${_n(cx)}" y="${_n(startY + i * lineH)}">${_esc(lines[i])}</tspan>');
}
sb.writeln('</text>');
}
// ===================== 工具 =====================
/// 数字格式化(最多 2 位小数、去掉多余 0)。
String _n(double v) {
if ((v - v.roundToDouble()).abs() < 0.005) return v.round().toString();
return v.toStringAsFixed(2);
}
/// ARGB → `#rrggbb`。
String _hex(int argb) {
final int rgb = argb & 0xFFFFFF;
return '#${rgb.toRadixString(16).padLeft(6, '0')}';
}
/// ARGB → 不透明度字符串。
String _op(int argb) => _opValue(argb).toStringAsFixed(3);
/// ARGB → 不透明度值(0..1)。
double _opValue(int argb) => ((argb >> 24) & 0xFF) / 255;
/// 点列表 → polygon points。
String _points(List<Offset> pts) =>
pts.map((Offset p) => '${_n(p.dx)},${_n(p.dy)}').join(' ');
/// 折线 d。
String _polyD(List<Offset> pts) {
if (pts.isEmpty) return '';
final StringBuffer sb = StringBuffer('M ${_n(pts.first.dx)} ${_n(pts.first.dy)}');
for (int i = 1; i < pts.length; i++) {
sb.write(' L ${_n(pts[i].dx)} ${_n(pts[i].dy)}');
}
return sb.toString();
}
/// 样条 d(Catmull-Rom → 三次贝塞尔,与画布绘制一致)。
String _splineD(List<Offset> pts) {
if (pts.isEmpty) return '';
final StringBuffer sb = StringBuffer('M ${_n(pts.first.dx)} ${_n(pts.first.dy)}');
if (pts.length == 2) {
sb.write(' L ${_n(pts[1].dx)} ${_n(pts[1].dy)}');
return sb.toString();
}
for (int i = 0; i < pts.length - 1; i++) {
final Offset p0 = i == 0 ? pts[i] : pts[i - 1];
final Offset p1 = pts[i];
final Offset p2 = pts[i + 1];
final Offset p3 = i + 2 < pts.length ? pts[i + 2] : pts[i + 1];
final Offset c1 = p1 + (p2 - p0) / 6;
final Offset c2 = p2 - (p3 - p1) / 6;
sb.write(
' C ${_n(c1.dx)} ${_n(c1.dy)} ${_n(c2.dx)} ${_n(c2.dy)} ${_n(p2.dx)} ${_n(p2.dy)}');
}
return sb.toString();
}
/// 平滑墨迹 d(与画布 `archSmoothPath` 一致的二次贝塞尔)。
String _smoothD(List<Offset> pts) {
if (pts.isEmpty) return '';
final StringBuffer sb = StringBuffer('M ${_n(pts.first.dx)} ${_n(pts.first.dy)}');
if (pts.length == 2) {
sb.write(' L ${_n(pts[1].dx)} ${_n(pts[1].dy)}');
return sb.toString();
}
for (int i = 1; i < pts.length - 1; i++) {
final Offset mid = (pts[i] + pts[i + 1]) / 2;
sb.write(' Q ${_n(pts[i].dx)} ${_n(pts[i].dy)} ${_n(mid.dx)} ${_n(mid.dy)}');
}
sb.write(' L ${_n(pts.last.dx)} ${_n(pts.last.dy)}');
return sb.toString();
}
/// XML 文本转义。
String _esc(String s) => s
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;');
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,971 @@
/// 手绘识别:把一笔自由曲线识别成标准图形(直线 / 箭头 / 矩形 / 圆角矩形 /
/// 圆 / 椭圆 / 三角形 / 菱形 / 六边形)。
///
/// 设计目标:像 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<Offset>? pts;
}
/// 识别一笔手绘:成功返回标准图形,失败返回 null(调用方保留墨迹)。
ArchRecognition? recognizeArchStroke(List<Offset> raw) {
final List<Offset> 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<List<Offset>> 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<List<Offset>> strokes) {
final List<List<Offset>> parts = <List<Offset>>[
for (final List<Offset> 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<Offset> a = parts[0];
final List<Offset> 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<Offset> merged;
double gap;
if (g1 <= g2 && g1 <= g3 && g1 <= g4) {
merged = <Offset>[...a, ...b];
gap = g1;
} else if (g2 <= g3 && g2 <= g4) {
merged = <Offset>[...a, ...b.reversed];
gap = g2;
} else if (g3 <= g4) {
merged = <Offset>[...a.reversed, ...b];
gap = g3;
} else {
merged = <Offset>[...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<List<Offset>> _splitOnJumps(List<Offset> pts, double diag) {
final double thr = math.max(14.0, 0.18 * diag);
final List<List<Offset>> parts = <List<Offset>>[];
List<Offset> cur = <Offset>[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 = <Offset>[pts[i]];
} else {
cur.add(pts[i]);
}
}
if (cur.length >= 4) parts.add(cur);
return parts;
}
/// 圆柱顶盖(扁椭圆)识别:放宽椭圆残差阈值(扁椭圆曲率大、抖动残差偏高),
/// 只要「近椭圆」即可作为顶盖。
ArchRecognition? _recognizeLid(List<Offset> lidPts) {
final Rect lb = _bounds(lidPts);
if (math.min(lb.width, lb.height) < 10) return null;
final List<Offset> 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<Offset> bodyPts, List<Offset> 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<Offset> 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<Offset> pts = r.pts ?? const <Offset>[];
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<Offset> 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<Offset> 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<int> idx =
_rdpIndices(pts, math.max(3.0, 0.03 * diag));
final List<int> merged = _mergeOpen(pts, idx, 24);
final List<Offset> v = <Offset>[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<Offset> snapped = _snapAxisSegments(v, 12);
return ArchRecognition(
type: ArchShapeType.polyline,
rect: _bounds(snapped),
pts: snapped,
);
}
// 平缓弯曲 → 曲线:用更粗的简化取「通过点」,保留动势。
final List<int> idx2 = _rdpIndices(pts, math.max(5.0, 0.07 * diag));
final List<Offset> cv = <Offset>[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<Offset> pts, List<Offset> v) {
if (v.length < 2) return false;
final List<int> idx = <int>[];
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<Offset> simplifyArchPolyline(List<Offset> pts) {
final List<Offset> 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<int> idx = _rdpIndices(clean, math.max(4.0, 0.035 * diag));
final List<int> merged = _mergeOpen(clean, idx, 24);
final List<Offset> v = <Offset>[for (final int i in merged) clean[i]];
if (v.length < 2) return <Offset>[clean.first, clean.last];
return _snapAxisSegments(v, 12);
}
/// 合并共线折点(开放折线:只处理内部顶点)。
List<int> _mergeOpen(List<Offset> pts, List<int> idx, double tolDeg) {
final List<int> cur = List<int>.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<Offset> _snapAxisSegments(List<Offset> v, double tolDeg) {
final List<Offset> out = List<Offset>.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<Offset> pts) {
final int total = pts.length;
if (total < 24) return 0;
final int k = math.max(2, total ~/ 20);
final List<double> turns = <double>[];
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<Offset> raw, Rect bb, double diag) {
final List<Offset> pts = _resample(raw, 72);
final double res90 = _percentile(_ellipseResiduals(pts, bb), 0.90);
final List<int> poly =
_rdpIndices(pts, math.max(2.2, 0.016 * diag), closed: true);
final List<int> 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<int>? 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<int>? 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<Offset> pts, Rect bb, List<int> merged) {
final List<Offset> v = <Offset>[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<Offset> 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<Offset> pts, Rect bb, List<int> merged) {
final List<Offset> v = <Offset>[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<double> _ellipseResiduals(List<Offset> pts, Rect bb) {
final double rx = bb.width / 2;
final double ry = bb.height / 2;
if (rx < 1 || ry < 1 || pts.isEmpty) return <double>[1];
final List<double> out = <double>[];
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<double> values, double q) {
if (values.isEmpty) return 1;
final List<double> s = List<double>.of(values)..sort();
final int idx = ((s.length - 1) * q).round().clamp(0, s.length - 1);
return s[idx];
}
/// 贴边率:笔迹点贴近外接矩形四条边的比例
/// (区分「有直边的矩形」与「全曲线的椭圆」)。
double _sideFit(List<Offset> 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<Offset> pts, Rect bb) {
final List<Offset> corners = <Offset>[
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<Offset> pts, List<int> quad) {
final List<Offset> v = <Offset>[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<int>? _tryMergeToQuad(List<Offset> pts, List<int> merged, double maxDev) {
final int n = merged.length;
if (n == 4) return merged;
if (n < 4 || n > 6) return null;
double best = maxDev;
List<int>? bestSet;
if (n == 5) {
for (int i = 0; i < 5; i++) {
final List<int> r = List<int>.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<int> r = List<int>.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<Offset> 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<Offset> _clean(List<Offset> raw) {
final List<Offset> out = <Offset>[];
for (final Offset p in raw) {
if (out.isEmpty || (p - out.last).distance > 0.6) out.add(p);
}
return out;
}
/// 折线总长。
double _polyLength(List<Offset> pts) {
double s = 0;
for (int i = 1; i < pts.length; i++) {
s += (pts[i] - pts[i - 1]).distance;
}
return s;
}
/// 外接矩形。
Rect _bounds(List<Offset> 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<Offset> _resample(List<Offset> pts, int n) {
final double len = _polyLength(pts);
if (len <= 0.0001 || pts.length < 2) return List<Offset>.of(pts);
final double step = len / (n - 1);
final List<Offset> out = <Offset>[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<int> _rdpIndices(List<Offset> pts, double eps, {bool closed = false}) {
final List<Offset> work =
closed ? <Offset>[...pts, pts.first] : pts;
final List<bool> keep = List<bool>.filled(work.length, false);
keep[0] = true;
keep[work.length - 1] = true;
final List<List<int>> stack = <List<int>>[
<int>[0, work.length - 1],
];
while (stack.isNotEmpty) {
final List<int> 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(<int>[s, idx]);
stack.add(<int>[idx, e]);
}
}
final List<int> out = <int>[];
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<int> _mergeCollinear(
List<Offset> pts,
List<int> idx,
double tolDeg,
double minSeg,
) {
final List<int> cur = List<int>.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;
@@ -0,0 +1,361 @@
/// 架构图示例场景:自动化产线系统架构(手绘稿 / 完成图两种状态),
/// 以及「手绘识别对照表」的素材(用于演示与截图)。
///
/// 「手绘稿」= 把每个标准图形的轮廓采样成带抖动的单笔墨迹 + 箭头墨迹;
/// 「完成图」= 识别后的标准图形 + 吸附连线 + 标签文字。
/// 两个场景共用同一套几何,保证演示「画 → 识别 → 成图」的完整链路。
library;
import 'dart:math' as math;
import 'dart:ui';
import 'arch_models.dart';
import 'arch_painter.dart';
/// 示例场景种类。
enum ArchDemoKind {
/// 手绘稿(全部为墨迹,等待识别)。
ink,
/// 完成图(标准图形 + 连线 + 文字)。
done,
}
/// 示例场景中的一个图形定义。
class ArchDemoEntry {
/// 构造图形定义。
const ArchDemoEntry(
this.id,
this.type,
this.rect,
this.color,
this.text, {
this.radius = 0,
this.dir = 0,
});
/// 图形 id。
final String id;
/// 图形类型。
final ArchShapeType type;
/// 外接矩形(世界坐标)。
final Rect rect;
/// 主题色。
final int color;
/// 图内文字。
final String text;
/// 圆角半径(圆角矩形)。
final double radius;
/// 朝向(三角形)。
final int dir;
}
/// 示例场景中的一条连线定义。
class ArchDemoConn {
/// 构造连线定义。
const ArchDemoConn(
this.from,
this.to,
this.label, {
this.dash = false,
this.route = ArchRoute.straight,
});
/// 起点图形 id。
final String from;
/// 终点图形 id。
final String to;
/// 连线标签。
final String label;
/// 是否虚线。
final bool dash;
/// 走线方式(直线 / 正交折线)。
final ArchRoute route;
}
/// 示例图形清单(两个场景共用)。
List<ArchDemoEntry> archDemoEntries() => <ArchDemoEntry>[
const ArchDemoEntry('S1', ArchShapeType.cloud,
Rect.fromLTWH(620, 20, 250, 120), 0xFF94A3B8, '云平台 · 远程运维'),
const ArchDemoEntry('S2', ArchShapeType.rect,
Rect.fromLTWH(600, 186, 290, 78), 0xFF38BDF8, '组态上位机 (Windows)'),
const ArchDemoEntry('S3', ArchShapeType.roundRect,
Rect.fromLTWH(628, 310, 234, 66), 0xFFA78BFA, '工业交换机',
radius: 16),
const ArchDemoEntry('S4', ArchShapeType.rect,
Rect.fromLTWH(595, 424, 300, 84), 0xFF4CC9F0, 'PLC 主站\n(EtherCAT)'),
const ArchDemoEntry('S5', ArchShapeType.rect,
Rect.fromLTWH(120, 438, 190, 76), 0xFF34D399, '视觉相机\nGigE'),
const ArchDemoEntry('S6', ArchShapeType.roundRect,
Rect.fromLTWH(1030, 438, 190, 76), 0xFFF472B6, 'IO 模块',
radius: 14),
const ArchDemoEntry('S7', ArchShapeType.rect,
Rect.fromLTWH(540, 560, 240, 76), 0xFFFFD166, '伺服驱动器'),
const ArchDemoEntry('S8', ArchShapeType.ellipse,
Rect.fromLTWH(505, 706, 150, 96), 0xFF38BDF8, '伺服电机'),
const ArchDemoEntry('S9', ArchShapeType.ellipse,
Rect.fromLTWH(820, 706, 180, 96), 0xFF34D399, '气缸 / 传感器'),
const ArchDemoEntry('S10', ArchShapeType.cylinder,
Rect.fromLTWH(140, 690, 150, 130), 0xFFFF8A5C, '历史数据库'),
];
/// 示例连线清单。
List<ArchDemoConn> archDemoConns() => <ArchDemoConn>[
const ArchDemoConn('S1', 'S2', '光纤 / 5G', dash: true),
const ArchDemoConn('S2', 'S3', 'Profinet'),
const ArchDemoConn('S3', 'S4', 'Profinet'),
const ArchDemoConn('S4', 'S5', 'GigE', route: ArchRoute.ortho),
const ArchDemoConn('S4', 'S7', 'EtherCAT'),
const ArchDemoConn('S4', 'S6', 'EtherCAT'),
const ArchDemoConn('S7', 'S8', '动力线'),
const ArchDemoConn('S6', 'S9', '24V IO / 气路'),
const ArchDemoConn('S4', 'S10', 'OPC UA', route: ArchRoute.ortho),
];
/// 由定义构造标准图形。
ArchShape _shapeOf(ArchDemoEntry e) => ArchShape(
id: e.id,
type: e.type,
rect: e.rect,
radius: e.radius,
dir: e.dir,
fill: archFillOf(e.color),
stroke: e.color,
sw: 1.8,
text: e.text,
);
/// 手绘稿场景:所有图形与连线的「原始墨迹」。
ArchDoc archDemoInkScene() {
final List<ArchStroke> strokes = <ArchStroke>[];
final Map<String, ArchShape> byId = <String, ArchShape>{};
int seed = 7;
const int inkColor = 0xFF64748B;
for (final ArchDemoEntry e in archDemoEntries()) {
byId[e.id] = _shapeOf(e);
final Path path = archShapePath(byId[e.id]!);
final List<Offset> pts =
archInkOutline(path, seed: seed++, jitter: 1.7, gapFrac: 0.07);
if (pts.length > 4) {
strokes.add(ArchStroke(
id: 'K${strokes.length + 1}',
pts: pts,
color: inkColor,
));
}
}
for (final ArchDemoConn c in archDemoConns()) {
final ArchShape f = byId[c.from]!;
final ArchShape t = byId[c.to]!;
final Offset a = archBorderPoint(f, t.rect.center);
final Offset b = archBorderPoint(t, f.rect.center);
final List<Offset> pts = _inkArrow(a, b, seed: seed++);
if (pts.length > 6) {
strokes.add(ArchStroke(
id: 'K${strokes.length + 1}',
pts: pts,
color: inkColor,
));
}
}
return ArchDoc(strokes: strokes);
}
/// 完成图场景:标准图形 + 吸附连线 + 标题。
ArchDoc archDemoDoneScene() {
final List<ArchShape> shapes = <ArchShape>[
const ArchShape(
id: 'T0',
type: ArchShapeType.text,
rect: Rect.fromLTWH(120, 40, 430, 40),
fill: 0,
stroke: 0xFF64748B,
sw: 0,
text: '自动化产线 · 系统架构(示例)',
),
for (final ArchDemoEntry e in archDemoEntries()) _shapeOf(e),
];
final Map<String, ArchShape> byId = <String, ArchShape>{
for (final ArchShape s in shapes) s.id: s,
};
final List<ArchConnector> conns = <ArchConnector>[];
for (final ArchDemoConn c in archDemoConns()) {
final ArchShape f = byId[c.from]!;
final ArchShape t = byId[c.to]!;
conns.add(ArchConnector(
id: 'C${conns.length + 1}',
fromId: c.from,
from: f.rect.center,
toId: c.to,
to: t.rect.center,
label: c.label,
dash: c.dash,
route: c.route,
));
}
return ArchDoc(shapes: shapes, connectors: conns);
}
/// 「手绘识别对照表」素材:一组(标签, 手绘墨迹),供演示 / 截图逐个识别。
List<(String, List<Offset>)> archRecognitionSheet() {
final List<(String, List<Offset>)> out = <(String, List<Offset>)>[];
int seed = 101;
void addStroke(String label, List<Offset> pts) {
out.add((label, pts));
}
void addOutline(String label, ArchShape proto) {
addStroke(
label,
archInkOutline(archShapePath(proto), seed: seed++, jitter: 1.8, gapFrac: 0.07),
);
}
ArchShape proto(ArchShapeType type, Rect r, {double radius = 0}) => ArchShape(
id: 'x',
type: type,
rect: r,
radius: radius,
fill: 0,
stroke: 0xFF64748B,
sw: 1.8,
);
addStroke('直线', _inkLine(const Offset(24, 128), const Offset(196, 66), seed: seed++));
addStroke('箭头', _inkArrow(const Offset(24, 132), const Offset(196, 60), seed: seed++));
addOutline('矩形', proto(ArchShapeType.rect, const Rect.fromLTWH(34, 30, 152, 104)));
addOutline('圆角矩形',
proto(ArchShapeType.roundRect, const Rect.fromLTWH(34, 30, 152, 104), radius: 22));
addOutline('圆形', proto(ArchShapeType.circle, const Rect.fromLTWH(46, 26, 128, 128)));
addOutline('椭圆', proto(ArchShapeType.ellipse, const Rect.fromLTWH(30, 42, 160, 92)));
addOutline('三角形', proto(ArchShapeType.triangle, const Rect.fromLTWH(44, 26, 140, 118)));
addOutline('菱形', proto(ArchShapeType.diamond, const Rect.fromLTWH(30, 32, 160, 108)));
addStroke(
'折线',
archInkOutline(
Path()
..moveTo(26, 30)
..lineTo(26, 96)
..lineTo(118, 96)
..lineTo(118, 142)
..lineTo(196, 142),
seed: seed++,
jitter: 1.5,
gapFrac: 0,
),
);
addStroke(
'曲线',
archInkOutline(
Path()
..moveTo(24, 122)
..cubicTo(62, 36, 138, 150, 198, 62),
seed: seed++,
jitter: 1.7,
gapFrac: 0,
),
);
return out;
}
// ===================== 墨迹采样 =====================
/// 沿路径采样成一段带抖动的「手绘墨迹」([gapFrac] 为收笔缺口占比)。
List<Offset> archInkOutline(
Path path, {
required int seed,
double jitter = 1.7,
double gapFrac = 0.07,
}) {
final List<PathMetric> metrics = path.computeMetrics().toList();
double total = 0;
for (final PathMetric m in metrics) {
total += m.length;
}
if (total < 10) return <Offset>[];
final math.Random rnd = math.Random(seed);
final List<Offset> out = <Offset>[];
final double stop = total * (1 - gapFrac);
final double step = math.max(3.0, total / 260);
double walked = 0;
for (final PathMetric m in metrics) {
double d = 0;
while (d < m.length && walked < stop) {
final Tangent? tan = m.getTangentForOffset(d);
if (tan != null) {
final Offset dir = tan.vector;
final Offset nrm = Offset(-dir.dy, dir.dx);
final double j = (rnd.nextDouble() * 2 - 1) * jitter +
math.sin(d * 0.045 + seed) * jitter * 0.6;
out.add(tan.position + nrm * j);
}
d += step;
walked += step;
}
if (walked >= stop) break;
}
return out;
}
/// 采样一段直线墨迹。
List<Offset> _inkLine(Offset a, Offset b, {int seed = 1, double jitter = 1.2}) {
final math.Random rnd = math.Random(seed);
final List<Offset> out = <Offset>[];
final Offset d = b - a;
final double len = d.distance;
if (len < 4) return out;
final Offset u = d / len;
final Offset n = Offset(-u.dy, u.dx);
for (double t = 0; t <= len - 3; t += 6) {
out.add(a + u * t + n * ((rnd.nextDouble() * 2 - 1) * jitter));
}
out.add(b);
return out;
}
/// 采样一段单笔箭头墨迹:箭杆 + 尖端折返的「>」形头部。
List<Offset> _inkArrow(Offset a, Offset b, {int seed = 1, double jitter = 1.2}) {
final math.Random rnd = math.Random(seed);
final List<Offset> out = <Offset>[];
final Offset d = b - a;
final double len = d.distance;
if (len < 36) return out;
final Offset u = d / len;
final Offset n = Offset(-u.dy, u.dx);
// 箭杆
for (double t = 0; t <= len - 4; t += 7) {
out.add(a + u * t + n * ((rnd.nextDouble() * 2 - 1) * jitter));
}
// 头部:尖端 → 左后 → 右后(同一笔完成)
final double hs = math.min(40, len * 0.18);
final Offset p1 = b + _rot(u, 155) * hs;
final Offset p2 = b + _rot(u, -155) * hs;
final Offset mid = (p1 + p2) / 2;
const int seg = 4;
for (int i = 1; i <= seg; i++) {
out.add(Offset.lerp(b, p1, i / seg)! + n * ((rnd.nextDouble() * 2 - 1) * jitter * 0.5));
}
for (int i = 1; i <= seg; i++) {
out.add(i <= 2
? Offset.lerp(p1, mid, i / 2)!
: Offset.lerp(mid, p2, (i - 2) / (seg - 2))!);
}
return out;
}
/// 向量旋转(度)。
Offset _rot(Offset v, double deg) {
final double r = deg * math.pi / 180;
return Offset(v.dx * math.cos(r) - v.dy * math.sin(r),
v.dx * math.sin(r) + v.dy * math.cos(r));
}
@@ -0,0 +1,201 @@
/// 手绘识别 · 图元库匹配。
///
/// 把笔迹(可多笔,顺序无关)与图元库每个符号的轮廓做「归一化双向
/// 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<List<Offset>> strokes,
List<LibSymbol> catalog, {
double maxScore = kArchSymbolMaxScore,
double margin = kArchSymbolMargin,
int inputSamples = 96,
int refSamples = 128,
}) {
// 每笔独立重采样(避免笔与笔之间产生"跳线"污染),按各笔长度分配采样数。
final List<List<Offset>> parts = <List<Offset>>[];
final List<double> lens = <double>[];
double total = 0;
for (final List<Offset> 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<Offset> pts = <Offset>[];
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<double> scales = <double>[0.7, 0.85, 1.0, 1.2, 1.45];
final List<List<Offset>> scaled = <List<Offset>>[
for (final double s in scales)
<Offset>[for (final Offset p in input.pts) p * s],
];
ArchSymbolMatch? best;
double second = double.infinity;
for (final LibSymbol sym in catalog) {
final List<Offset> 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<Offset> 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<Offset> pts;
final double extent;
static _Np of(List<Offset> pts) {
if (pts.isEmpty) return const _Np(<Offset>[], 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<Offset>.filled(pts.length, Offset.zero), 0);
final Offset c = Offset((l + r) / 2, (t + b) / 2);
return _Np(<Offset>[
for (final Offset p in pts)
Offset((p.dx - c.dx) / ext, (p.dy - c.dy) / ext),
], ext);
}
}
/// 按弧长均匀重采样折线到 [n] 个点。
List<Offset> _resample(List<Offset> pts, int n) {
if (pts.length <= 1) return List<Offset>.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 <Offset>[pts.first];
final List<Offset> out = <Offset>[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<Offset> _sampleSymbol(LibSymbol sym, int n) {
final Path path = buildSymbolPath(sym, const Rect.fromLTWH(0, 0, 100, 100));
final List<PathMetric> metrics = path.computeMetrics().toList();
double total = 0;
for (final PathMetric m in metrics) {
total += m.length;
}
if (total < 1e-6) return const <Offset>[];
final List<Offset> out = <Offset>[];
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<Offset> a, List<Offset> 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<Offset> 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);
}