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
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,362 @@
/// 参数化草图绘制:几何(直线 / 圆 / 弧)、点(固定点高亮)、
/// 约束图标(H / V / ∥ / ⊥ / = / ◎ / T)、驱动尺寸标注与预览。
///
/// 所有尺寸按 `1 / zoom` 逆缩放,保持屏幕像素恒定(CAD 观感)。
library;
import 'dart:math' as math;
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:sequence_diagram/theme/tokens.dart';
import 'sketch_models.dart';
/// 草图配色(浅 / 深色主题下都可读)。
const int kSketchLineColor = 0xFF2F6FEB;
const int kSketchPointColor = 0xFF64748B;
const int kSketchFixedColor = 0xFFDC2626;
const int kSketchDimColor = 0xFF0F766E;
const int kSketchConsColor = 0xFF7C3AED;
const int kSketchSelColor = 0xFFF97316;
const int kSketchPreviewColor = 0xFF0EA5E9;
/// 草图预览信息(绘制中的橡皮筋)。
class SketchPreview {
/// 构造。
const SketchPreview({required this.pts, this.kind = SketchKind.line, this.closed = false});
/// 预览点(世界坐标)。
final List<Offset> pts;
/// 预览类型(line:折线描边;circle / arc 用第一点为圆心)。
final SketchKind kind;
/// 是否闭合描边。
final bool closed;
}
/// 绘制草图内容(调用方已完成 translate + scale)。
void paintSketch(
Canvas canvas,
SketchDoc doc,
Tokens t, {
Set<String> sel = const <String>{},
Offset? hover,
SketchPreview? preview,
Offset? snapMark,
}) {
// 逆缩放因子:通过画布变换取得真实缩放,保证线宽 / 字号恒定。
final double scale = _canvasScale(canvas);
final double s = scale <= 0 ? 1 : 1 / scale;
// ---- 几何 ----
for (final SketchEntity e in doc.entities) {
final bool selected = sel.contains(e.id);
final Paint paint = Paint()
..style = PaintingStyle.stroke
..strokeWidth = (selected ? 2.4 : 1.6) * s
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round
..color = Color(selected ? kSketchSelColor : kSketchLineColor);
switch (e.kind) {
case SketchKind.line:
final Offset? a = doc.pointById(e.p1)?.pos;
final Offset? b = doc.pointById(e.p2)?.pos;
if (a == null || b == null) break;
canvas.drawLine(a, b, paint);
case SketchKind.circle:
final Offset? c = doc.pointById(e.p1)?.pos;
if (c == null) break;
canvas.drawCircle(c, e.r, paint);
case SketchKind.arc:
final Offset? c = doc.pointById(e.p1)?.pos;
final Offset? ps = doc.pointById(e.p2)?.pos;
final Offset? pe = doc.pointById(e.p3)?.pos;
if (c == null || ps == null || pe == null) break;
final (double a1, double sweep) =
sketchArcAngles(c, ps, pe, e.ccw);
final Path path = Path()
..addArc(Rect.fromCircle(center: c, radius: e.r),
e.ccw ? a1 : a1 - sweep, sweep);
canvas.drawPath(path, paint);
}
}
// ---- 点 ----
for (final SketchPoint p in doc.points) {
final bool selected = sel.contains(p.id);
final bool hovered = hover != null && (hover - p.pos).distance < 7 * s;
final double r = (hovered ? 3.6 : 2.8) * s;
canvas.drawRect(
Rect.fromCenter(center: p.pos, width: r * 2, height: r * 2),
Paint()
..color = Color(selected
? kSketchSelColor
: (p.fixed ? kSketchFixedColor : kSketchPointColor)),
);
if (p.fixed) {
// 固定点:外圈提示锚定。
canvas.drawCircle(
p.pos,
r * 2.2,
Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1.2 * s
..color = Color(kSketchFixedColor),
);
}
}
// ---- 约束图标 ----
for (final SketchConstraint k in doc.constraints) {
if (k.internal) continue;
final List<Offset> anchors = _consAnchors(doc, k);
for (final Offset a in anchors) {
_label(canvas, _consGlyph(k.type), a, s,
color: Color(kSketchConsColor),
bg: t.panel.withValues(alpha: 0.92));
}
}
// ---- 驱动尺寸 ----
for (final SketchDim d in doc.dims) {
_dim(canvas, doc, d, t, s, sel.contains(d.id));
}
// ---- 预览 ----
final SketchPreview? pv = preview;
if (pv != null && pv.pts.isNotEmpty) {
final Paint pp = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1.8 * s
..strokeCap = StrokeCap.round
..color = Color(kSketchPreviewColor);
switch (pv.kind) {
case SketchKind.line:
if (pv.pts.length >= 2) {
final Path path = Path()..moveTo(pv.pts.first.dx, pv.pts.first.dy);
for (int i = 1; i < pv.pts.length; i++) {
path.lineTo(pv.pts[i].dx, pv.pts[i].dy);
}
if (pv.closed) path.close();
canvas.drawPath(path, pp);
}
case SketchKind.circle:
if (pv.pts.length >= 2) {
canvas.drawCircle(pv.pts.first,
(pv.pts.last - pv.pts.first).distance, pp);
}
case SketchKind.arc:
if (pv.pts.length >= 3) {
final Offset c = pv.pts.first;
final Offset ps = pv.pts[1];
final Offset pe = pv.pts.last;
final double r = (ps - c).distance;
final (double a1, double sweep) = sketchArcAngles(c, ps, pe, true);
canvas.drawPath(
Path()
..addArc(
Rect.fromCircle(center: c, radius: r), a1, sweep),
pp,
);
}
}
}
// ---- 捕捉标记 ----
final Offset? sm = snapMark;
if (sm != null) {
canvas.drawCircle(
sm,
4.5 * s,
Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1.6 * s
..color = Color(kSketchPreviewColor),
);
}
}
/// 取画布当前缩放的倒数(保持屏幕像素恒定的线宽 / 文字)。
double _canvasScale(Canvas canvas) {
final Float64List m = canvas.getTransform();
final double sx = math.sqrt(m[0] * m[0] + m[1] * m[1]);
final double sy = math.sqrt(m[4] * m[4] + m[5] * m[5]);
final double s = (sx + sy) / 2;
return s <= 0 ? 1 : s;
}
/// 约束图标锚点(每个约束可画多处)。
List<Offset> _consAnchors(SketchDoc doc, SketchConstraint k) {
Offset? midEntity(String id) {
final SketchEntity? e = doc.entityById(id);
if (e == null) return null;
if (e.kind == SketchKind.line) {
final Offset? a = doc.pointById(e.p1)?.pos;
final Offset? b = doc.pointById(e.p2)?.pos;
if (a == null || b == null) return null;
final Offset m = Offset.lerp(a, b, 0.5)!;
final Offset d = b - a;
final double len = d.distance;
if (len < 1e-6) return m;
return m + Offset(-d.dy / len, d.dx / len) * 12;
}
final Offset? c = doc.pointById(e.p1)?.pos;
if (c == null) return null;
return c + Offset(e.r * 0.35, -e.r * 0.35);
}
switch (k.type) {
case SketchConsType.horizontal:
case SketchConsType.vertical:
final Offset? m = midEntity(k.a);
return m == null ? <Offset>[] : <Offset>[m];
case SketchConsType.pointOnEntity:
final Offset? p = doc.pointById(k.a)?.pos;
return p == null ? <Offset>[] : <Offset>[p + const Offset(10, -10)];
case SketchConsType.concentric:
final Offset? c = doc.pointById(doc.entityById(k.a)?.p1)?.pos;
return c == null ? <Offset>[] : <Offset>[c + const Offset(14, -14)];
default:
final List<Offset> out = <Offset>[];
final Offset? m1 = midEntity(k.a);
if (m1 != null) out.add(m1);
return out;
}
}
String _consGlyph(SketchConsType t2) => switch (t2) {
SketchConsType.horizontal => 'H',
SketchConsType.vertical => 'V',
SketchConsType.parallel => '∥',
SketchConsType.perpendicular => '⊥',
SketchConsType.equal => '=',
SketchConsType.concentric => '◎',
SketchConsType.tangent => 'T',
SketchConsType.pointOnEntity => '⌐',
};
/// 画一条尺寸标注。
void _dim(
Canvas canvas,
SketchDoc doc,
SketchDim d,
Tokens t,
double s,
bool selected,
) {
final Offset? anchor = sketchDimAnchor(doc, d);
if (anchor == null) return;
final Color color = Color(selected ? kSketchSelColor : kSketchDimColor);
final Paint line = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1.2 * s
..color = color;
switch (d.type) {
case SketchDimType.length:
case SketchDimType.distance:
final (Offset p1, Offset p2) = d.type == SketchDimType.length
? _entityEnds(doc, d.a)
: (doc.pointById(d.a)?.pos ?? Offset.zero,
doc.pointById(d.b)?.pos ?? Offset.zero);
final Offset dir = p2 - p1;
final double len = dir.distance;
if (len < 1e-6) return;
final Offset n = Offset(-dir.dy / len, dir.dx / len);
final double off = d.type == SketchDimType.length ? 18 : -20;
final Offset a2 = p1 + n * (off * s);
final Offset b2 = p2 + n * (off * s);
canvas.drawLine(a2, b2, line);
canvas.drawLine(p1, a2 + n * 3 * s, line);
canvas.drawLine(p2, b2 + n * 3 * s, line);
_tick(canvas, a2, n, s, color);
_tick(canvas, b2, n, s, color);
case SketchDimType.radius:
final SketchEntity? e = doc.entityById(d.a);
final Offset? c = doc.pointById(e?.p1)?.pos;
if (e == null || c == null) return;
final Offset dir = const Offset(0.7071, -0.7071);
final Offset end = c + dir * e.r;
canvas.drawLine(c, end, line);
canvas.drawLine(
c,
c + dir * (e.r * 0.45),
Paint()
..strokeWidth = 3.2 * s
..color = color);
case SketchDimType.angle:
final Offset? a1 = doc.pointById(doc.entityById(d.a)?.p1)?.pos;
final Offset? a2 = doc.pointById(doc.entityById(d.a)?.p2)?.pos;
if (a1 == null || a2 == null) return;
// 简化:在第一条线的中点画一个角度弧示意。
final Offset m = Offset.lerp(a1, a2, 0.5)!;
canvas.drawCircle(
m,
10 * s,
Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1.2 * s
..color = color,
);
}
_label(canvas, sketchDimText(d), anchor, s,
color: color, bg: t.panel.withValues(alpha: 0.94), border: color);
}
(Offset, Offset) _entityEnds(SketchDoc doc, String id) {
final SketchEntity? e = doc.entityById(id);
if (e == null) return (Offset.zero, Offset.zero);
return (doc.pointById(e.p1)?.pos ?? Offset.zero,
doc.pointById(e.p2)?.pos ?? Offset.zero);
}
/// 尺寸界线端点的小斜线(CAD 风格刻度)。
void _tick(Canvas canvas, Offset p, Offset n, double s, Color color) {
canvas.drawLine(
p + Offset(-n.dy, n.dx) * 3.5 * s,
p + Offset(n.dy, -n.dx) * 3.5 * s,
Paint()
..strokeWidth = 1.2 * s
..color = color,
);
}
/// 小圆角标签(逆缩放保持屏幕字号恒定)。
void _label(
Canvas canvas,
String text,
Offset anchor,
double s, {
required Color color,
required Color bg,
Color? border,
}) {
final TextPainter tp = TextPainter(
text: TextSpan(
text: text,
style: TextStyle(
color: color,
fontSize: 10 * s,
fontWeight: FontWeight.w600,
),
),
textDirection: TextDirection.ltr,
)..layout();
final Rect r = Rect.fromCenter(
center: anchor,
width: tp.width + 8 * s,
height: tp.height + 3 * s,
);
final RRect rr = RRect.fromRectAndRadius(r, Radius.circular(4 * s));
canvas.drawRRect(rr, Paint()..color = bg);
canvas.drawRRect(
rr,
Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1 * s
..color = border ?? color.withValues(alpha: 0.45),
);
tp.paint(canvas, r.center - Offset(tp.width / 2, tp.height / 2));
}
@@ -0,0 +1,579 @@
/// 参数化草图求解器:把「约束 + 驱动尺寸 + 拖拽目标」作为残差,
/// 用 Levenberg–Marquardt(数值雅可比)最小二乘求解点坐标与半径。
///
/// 权重约定(越大越硬):
/// - 几何约束 / 驱动尺寸:30(先满足);
/// - 拖拽目标:6(尽量跟随鼠标,但不破坏约束);
/// - 正则项:0.03(把无驱动变量轻微拉回原位,避免欠约束漂移)。
library;
import 'dart:math' as math;
import 'dart:ui' show Offset;
import 'sketch_models.dart';
/// 求解结果。
class SketchSolveResult {
/// 构造。
const SketchSolveResult({
required this.doc,
required this.converged,
required this.iterations,
required this.residual,
});
/// 求解后的文档。
final SketchDoc doc;
/// 是否收敛(残差平方和 < 1e-8)。
final bool converged;
/// 实际迭代次数。
final int iterations;
/// 最终残差平方和。
final double residual;
}
/// 求解草图:返回满足(尽量)约束与尺寸的新文档。
///
/// [dragPoints]:拖拽目标(点 id → 世界坐标);[dragRadii]:拖拽半径(实体 id → 半径)。
SketchSolveResult solveSketch(
SketchDoc doc, {
Map<String, Offset> dragPoints = const <String, Offset>{},
Map<String, double> dragRadii = const <String, double>{},
int maxIter = 30,
}) {
final _VarSet vs = _VarSet(doc);
if (vs.n == 0) {
return SketchSolveResult(
doc: doc, converged: true, iterations: 0, residual: 0);
}
final _Access acc = _Access(doc, vs);
final List<_Res> res = <_Res>[];
for (final SketchConstraint k in doc.constraints) {
_addConstraint(doc, acc, k, res);
}
for (final SketchEntity e in doc.entities) {
_addArcInternal(doc, acc, e, res);
}
for (final SketchDim d in doc.dims) {
_addDim(doc, acc, d, res);
}
// ---- 拖拽目标 ----
dragPoints.forEach((String id, Offset t) {
if (doc.pointById(id) == null) return;
res.add(_Res(6, (List<double> x) {
acc.x = x;
return acc.p(id).dx - t.dx;
}));
res.add(_Res(6, (List<double> x) {
acc.x = x;
return acc.p(id).dy - t.dy;
}));
});
dragRadii.forEach((String id, double r) {
final SketchEntity? e = doc.entityById(id);
if (e == null || e.kind == SketchKind.line) return;
res.add(_Res(6, (List<double> x) {
acc.x = x;
return acc.r(id) - r;
}));
});
// ---- 正则项(soft stay) ----
final List<double> x0 = vs.x0();
for (int i = 0; i < vs.n; i++) {
final int idx = i;
res.add(_Res(0.03, (List<double> x) => x[idx] - x0[idx]));
}
final (List<double> x, bool conv, int iters, double err) =
_lm(res, x0, maxIter);
return SketchSolveResult(
doc: vs.apply(doc, x),
converged: conv,
iterations: iters,
residual: err,
);
}
/// 估算剩余自由度(变量数 − 独立约束数,粗略:约束 / 尺寸各算 1,同心算 2)。
int sketchDofCount(SketchDoc doc) {
int vars = 0;
for (final SketchPoint p in doc.points) {
if (!p.fixed) vars += 2;
}
for (final SketchEntity e in doc.entities) {
if (e.kind != SketchKind.line) vars += 1;
}
int cons = 0;
for (final SketchConstraint k in doc.constraints) {
cons += k.type == SketchConsType.concentric ? 2 : 1;
}
cons += doc.dims.length;
for (final SketchEntity e in doc.entities) {
if (e.kind == SketchKind.arc) cons += 2;
}
final int dof = vars - cons;
return dof < 0 ? 0 : dof;
}
// ===================== 残差构建 =====================
/// 几何约束残差。
void _addConstraint(
SketchDoc doc,
_Access acc,
SketchConstraint k,
List<_Res> res,
) {
if (k.type == SketchConsType.horizontal ||
k.type == SketchConsType.vertical) {
final SketchEntity? e = doc.entityById(k.a);
if (e == null || e.kind != SketchKind.line) return;
if (doc.pointById(e.p1) == null || doc.pointById(e.p2) == null) return;
final bool horiz = k.type == SketchConsType.horizontal;
res.add(_Res(30, (List<double> x) {
acc.x = x;
return horiz
? acc.p(e.p2).dy - acc.p(e.p1).dy
: acc.p(e.p2).dx - acc.p(e.p1).dx;
}));
return;
}
if (k.type == SketchConsType.parallel ||
k.type == SketchConsType.perpendicular) {
final SketchEntity? e1 = doc.entityById(k.a);
final SketchEntity? e2 = doc.entityById(k.b);
if (e1 == null ||
e2 == null ||
e1.kind != SketchKind.line ||
e2.kind != SketchKind.line) {
return;
}
final bool par = k.type == SketchConsType.parallel;
res.add(_Res(30, (List<double> x) {
acc.x = x;
final Offset d1 = acc.p(e1.p2) - acc.p(e1.p1);
final Offset d2 = acc.p(e2.p2) - acc.p(e2.p1);
final double l1 = d1.distance;
final double l2 = d2.distance;
if (l1 < 1e-9 || l2 < 1e-9) return 0;
return par
? (d1.dx * d2.dy - d1.dy * d2.dx) / (l1 * l2)
: (d1.dx * d2.dx + d1.dy * d2.dy) / (l1 * l2);
}));
return;
}
if (k.type == SketchConsType.equal) {
final SketchEntity? e1 = doc.entityById(k.a);
final SketchEntity? e2 = doc.entityById(k.b);
if (e1 == null || e2 == null) return;
res.add(_Res(30, (List<double> x) {
acc.x = x;
if (e1.kind == SketchKind.line && e2.kind == SketchKind.line) {
return (acc.p(e1.p2) - acc.p(e1.p1)).distance -
(acc.p(e2.p2) - acc.p(e2.p1)).distance;
}
return acc.r(e1.id) - acc.r(e2.id);
}));
return;
}
if (k.type == SketchConsType.concentric) {
final SketchEntity? e1 = doc.entityById(k.a);
final SketchEntity? e2 = doc.entityById(k.b);
if (e1 == null ||
e2 == null ||
e1.kind == SketchKind.line ||
e2.kind == SketchKind.line) {
return;
}
res.add(_Res(30, (List<double> x) {
acc.x = x;
return acc.p(e1.p1).dx - acc.p(e2.p1).dx;
}));
res.add(_Res(30, (List<double> x) {
acc.x = x;
return acc.p(e1.p1).dy - acc.p(e2.p1).dy;
}));
return;
}
if (k.type == SketchConsType.tangent) {
final SketchEntity? e1 = doc.entityById(k.a);
final SketchEntity? e2 = doc.entityById(k.b);
if (e1 == null || e2 == null) return;
final SketchEntity? line = e1.kind == SketchKind.line
? e1
: (e2.kind == SketchKind.line ? e2 : null);
final SketchEntity? circle = e1.kind != SketchKind.line
? e1
: (e2.kind != SketchKind.line ? e2 : null);
if (line != null && circle != null) {
res.add(_Res(30, (List<double> x) {
acc.x = x;
final Offset a = acc.p(line.p1);
final Offset d = acc.p(line.p2) - a;
final double len = d.distance;
if (len < 1e-9) return 0;
final Offset c = acc.p(circle.p1);
final double dist =
((c - a).dx * d.dy - (c - a).dy * d.dx).abs() / len;
return dist - acc.r(circle.id);
}));
} else if (e1.kind != SketchKind.line && e2.kind != SketchKind.line) {
res.add(_Res(30, (List<double> x) {
acc.x = x;
return (acc.p(e1.p1) - acc.p(e2.p1)).distance -
(acc.r(e1.id) + acc.r(e2.id));
}));
}
return;
}
if (k.type == SketchConsType.pointOnEntity) {
final SketchPoint? pt = doc.pointById(k.a);
final SketchEntity? e = doc.entityById(k.b);
if (pt == null || e == null) return;
if (e.kind == SketchKind.line) {
res.add(_Res(30, (List<double> x) {
acc.x = x;
final Offset a = acc.p(e.p1);
final Offset d = acc.p(e.p2) - a;
final double len = d.distance;
if (len < 1e-9) return 0;
final Offset pp = acc.p(pt.id);
return ((pp - a).dx * d.dy - (pp - a).dy * d.dx) / len;
}));
} else {
res.add(_Res(30, (List<double> x) {
acc.x = x;
return (acc.p(pt.id) - acc.p(e.p1)).distance - acc.r(e.id);
}));
}
}
}
/// 圆弧内部约束:端点落在圆上。
void _addArcInternal(
SketchDoc doc,
_Access acc,
SketchEntity e,
List<_Res> res,
) {
if (e.kind != SketchKind.arc) return;
if (doc.pointById(e.p1) == null ||
doc.pointById(e.p2) == null ||
doc.pointById(e.p3) == null) {
return;
}
res.add(_Res(30, (List<double> x) {
acc.x = x;
return (acc.p(e.p2) - acc.p(e.p1)).distance - acc.r(e.id);
}));
res.add(_Res(30, (List<double> x) {
acc.x = x;
return (acc.p(e.p3) - acc.p(e.p1)).distance - acc.r(e.id);
}));
}
/// 驱动尺寸残差。
void _addDim(SketchDoc doc, _Access acc, SketchDim d, List<_Res> res) {
if (d.type == SketchDimType.length) {
final SketchEntity? e = doc.entityById(d.a);
if (e == null || e.kind != SketchKind.line) return;
res.add(_Res(30, (List<double> x) {
acc.x = x;
return (acc.p(e.p2) - acc.p(e.p1)).distance - d.value;
}));
return;
}
if (d.type == SketchDimType.radius) {
final SketchEntity? e = doc.entityById(d.a);
if (e == null || e.kind == SketchKind.line) return;
res.add(_Res(30, (List<double> x) {
acc.x = x;
return acc.r(e.id) - d.value;
}));
return;
}
if (d.type == SketchDimType.angle) {
final SketchEntity? e1 = doc.entityById(d.a);
final SketchEntity? e2 = doc.entityById(d.b);
if (e1 == null ||
e2 == null ||
e1.kind != SketchKind.line ||
e2.kind != SketchKind.line) {
return;
}
final double cosTarget =
math.cos(d.value.clamp(0.01, 179.99) * math.pi / 180);
res.add(_Res(30, (List<double> x) {
acc.x = x;
final Offset d1 = acc.p(e1.p2) - acc.p(e1.p1);
final Offset d2 = acc.p(e2.p2) - acc.p(e2.p1);
final double l1 = d1.distance;
final double l2 = d2.distance;
if (l1 < 1e-9 || l2 < 1e-9) return 0;
return (d1.dx * d2.dx + d1.dy * d2.dy) / (l1 * l2) - cosTarget;
}));
return;
}
if (d.type == SketchDimType.distance) {
if (doc.pointById(d.a) == null || doc.pointById(d.b) == null) return;
res.add(_Res(30, (List<double> x) {
acc.x = x;
return (acc.p(d.b) - acc.p(d.a)).distance - d.value;
}));
}
}
// ===================== 求解内部实现 =====================
/// 残差项:函数 + 权重。
class _Res {
const _Res(this.weight, this.f);
/// 权重。
final double weight;
/// 残差函数(输入变量向量)。
final double Function(List<double> x) f;
}
/// 变量集:点坐标(未固定的点)与半径(圆 / 弧)。
class _VarSet {
_VarSet(this.doc) {
for (final SketchPoint p in doc.points) {
if (p.fixed) continue;
_pointIndex[p.id] = _n;
_n += 2;
}
for (final SketchEntity e in doc.entities) {
if (e.kind == SketchKind.line) continue;
_radiusIndex[e.id] = _n;
_n += 1;
}
}
/// 源文档。
final SketchDoc doc;
/// 变量总数。
int _n = 0;
/// 点 → 变量下标(x, y)。
final Map<String, int> _pointIndex = <String, int>{};
/// 实体 → 半径变量下标。
final Map<String, int> _radiusIndex = <String, int>{};
/// 变量总数。
int get n => _n;
/// 初始变量向量。
List<double> x0() {
final List<double> x = List<double>.filled(_n, 0);
for (final SketchPoint p in doc.points) {
final int? i = _pointIndex[p.id];
if (i == null) continue;
x[i] = p.x;
x[i + 1] = p.y;
}
for (final SketchEntity e in doc.entities) {
final int? i = _radiusIndex[e.id];
if (i == null) continue;
x[i] = e.r;
}
return x;
}
/// 把变量向量写回文档。
SketchDoc apply(SketchDoc source, List<double> x) {
final List<SketchPoint> pts = <SketchPoint>[
for (final SketchPoint p in source.points)
_pointIndex.containsKey(p.id)
? p.copyWith(
x: x[_pointIndex[p.id]!],
y: x[_pointIndex[p.id]! + 1],
)
: p,
];
final List<SketchEntity> ents = <SketchEntity>[
for (final SketchEntity e in source.entities)
_radiusIndex.containsKey(e.id)
? e.copyWith(r: math.max(0.5, x[_radiusIndex[e.id]!]))
: e,
];
return source.copyWith(points: pts, entities: ents);
}
}
/// 访问器:把变量向量映射为点坐标 / 半径(未参与求解的取文档原值)。
class _Access {
_Access(this.doc, this.vs);
final SketchDoc doc;
final _VarSet vs;
/// 当前变量向量。
late List<double> x;
/// 取点坐标。
Offset p(String id) {
final int? i = vs._pointIndex[id];
if (i != null) return Offset(x[i], x[i + 1]);
final SketchPoint? pt = doc.pointById(id);
return pt == null ? Offset.zero : pt.pos;
}
/// 取半径。
double r(String id) {
final int? i = vs._radiusIndex[id];
if (i != null) return x[i];
return doc.entityById(id)?.r ?? 0;
}
}
/// Levenberg–Marquardt:返回(解, 是否收敛, 迭代数, 残差平方和)。
(List<double>, bool, int, double) _lm(
List<_Res> res,
List<double> x0,
int maxIter,
) {
final int n = x0.length;
final List<double> x = List<double>.of(x0);
double err(List<double> v) {
double s = 0;
for (final _Res r in res) {
final double e = r.weight * r.f(v);
s += e * e;
}
return s;
}
double e0 = err(x);
double lambda = 1e-4;
int iters = 0;
const double convTol = 1e-10;
for (int it = 0; it < maxIter; it++) {
if (e0 < convTol) break;
iters = it + 1;
final List<double> rv = List<double>.generate(
res.length, (int i) => res[i].weight * res[i].f(x));
final List<List<double>> jac = List<List<double>>.generate(
res.length,
(int _) => List<double>.filled(n, 0),
);
for (int j = 0; j < n; j++) {
final double h = 1e-5 * (1 + x[j].abs());
final double old = x[j];
x[j] = old + h;
for (int i = 0; i < res.length; i++) {
jac[i][j] = (res[i].weight * res[i].f(x) - rv[i]) / h;
}
x[j] = old;
}
final List<List<double>> a =
List<List<double>>.generate(n, (int _) => List<double>.filled(n, 0));
final List<double> g = List<double>.filled(n, 0);
for (int i = 0; i < res.length; i++) {
final List<double> ji = jac[i];
final double ri = rv[i];
for (int p = 0; p < n; p++) {
final double vp = ji[p];
if (vp == 0) continue;
g[p] -= vp * ri;
for (int q = p; q < n; q++) {
a[p][q] += vp * ji[q];
}
}
}
for (int p = 0; p < n; p++) {
for (int q = 0; q < p; q++) {
a[p][q] = a[q][p];
}
}
bool accepted = false;
for (int t = 0; t < 8; t++) {
// 单位阵阻尼(标准 LM):秩缺陷方向的 diag(A) 元极小,
// 若按 diag(A) 阻尼会产生病态大跳步,这里统一按标量阻尼。
final List<List<double>> ad = List<List<double>>.generate(
n,
(int p) => List<double>.generate(
n,
(int q) => a[p][q] + (p == q ? lambda : 0.0),
),
);
final List<double>? d = _solveLinear(ad, g);
if (d == null) {
lambda *= 8;
if (lambda > 1e9) break;
continue;
}
final List<double> x2 =
List<double>.generate(n, (int p) => x[p] + d[p]);
final double e2 = err(x2);
if (e2 < e0) {
for (int p = 0; p < n; p++) {
x[p] = x2[p];
}
e0 = e2;
lambda = math.max(lambda / 4, 1e-9);
accepted = true;
break;
}
lambda *= 6;
if (lambda > 1e9) break;
}
if (!accepted) break;
}
return (x, e0 < 1e-8, iters, e0);
}
/// 高斯消元(部分主元);奇异返回 null。
List<double>? _solveLinear(List<List<double>> m, List<double> b) {
final int n = b.length;
final List<List<double>> a = <List<double>>[
for (int i = 0; i < n; i++) <double>[...m[i], b[i]],
];
for (int col = 0; col < n; col++) {
int piv = col;
double best = a[col][col].abs();
for (int r = col + 1; r < n; r++) {
final double v = a[r][col].abs();
if (v > best) {
best = v;
piv = r;
}
}
if (best < 1e-12) return null;
if (piv != col) {
final List<double> tmp = a[piv];
a[piv] = a[col];
a[col] = tmp;
}
final double d = a[col][col];
for (int r = col + 1; r < n; r++) {
final double f = a[r][col] / d;
if (f == 0) continue;
for (int ccol = col; ccol <= n; ccol++) {
a[r][ccol] -= f * a[col][ccol];
}
}
}
final List<double> x = List<double>.filled(n, 0);
for (int i = n - 1; i >= 0; i--) {
double s = a[i][n];
for (int j = i + 1; j < n; j++) {
s -= a[i][j] * x[j];
}
final double d = a[i][i];
if (d.abs() < 1e-12) return null;
x[i] = s / d;
}
return x;
}