Files
EasyDesignCollection/lib/modules/architecture/sketch/sketch_solver.dart
T
admin 0a3f2c5cc6 v1.3.13: 模块化注册架构 + PDS流程设计套件更名 + 依赖/圆周交互修复
- 模块化:EdcModule 契约 + registry + 模块独立目录;发布包增加 modules/registry.json
- 更名:PDS流程设计套件 / ProcessDesignSuite;同步构建、发布脚本与文档
- 时序图:依赖偏移以时间显示/编辑;紧贴依赖隐藏箭头并在接缝显示标签;动作条磁吸
- 圆周:依赖标签沿圆弧方向、环间空隙;动作旋转磁吸增强;短弧标签优先动作名
- 清理:release 移至源码同级(本地不入库);tool 合并到 tools;发布说明迁移 docs/release-notes
2026-11-22 10:02:54 +08:00

580 lines
16 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/// 参数化草图求解器:把「约束 + 驱动尺寸 + 拖拽目标」作为残差,
/// 用 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;
}