Merge pull request #24 from So3Lab/feat/dxf-engine
feat(dxf): 1-DOF annotation model, rad inner-arc variant, auto-diag loop
This commit is contained in:
+3
-2
@@ -55,6 +55,7 @@ Read exactly one workflow first, per the user's goal:
|
||||
| Multi-part product or mechanism (custom parts, stdlib gears/bearings, connectors, constraints, package) | `references/workflows/assembly-product-build.md` |
|
||||
| Rebuild an editable model from a STEP file | `references/workflows/step-reconstruction.md` |
|
||||
| Export/translate a validated package | `references/workflows/export-and-translation.md` |
|
||||
| Produce a GB engineering drawing (DXF) from validated geometry | `references/workflows/engineering-drawing.md` |
|
||||
|
||||
Do not present route-choice menus when a row already matches: profile,
|
||||
strategy, and tool choices inside a route belong to that workflow's
|
||||
@@ -173,8 +174,8 @@ print(len(rebuilt))
|
||||
## References
|
||||
|
||||
- `references/README.md` — skill layer structure
|
||||
- `references/workflows/` — six goal-oriented workflows
|
||||
- `references/domains/` — seven capability domains
|
||||
- `references/workflows/` — seven goal-oriented workflows
|
||||
- `references/domains/` — eight capability domains
|
||||
- `references/discipline/` — modeling knowledge and invariants
|
||||
- `references/SDK_OVERVIEW.md` — package-level map
|
||||
- `references/inspect/brep-reverse-engineering.md`
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# CenterDecl
|
||||
|
||||
## Class Definition
|
||||
|
||||
```python
|
||||
class CenterDecl(view: str, p1: tuple = None, p2: tuple = None, arc: tuple = None)
|
||||
```
|
||||
|
||||
*Source: dxf_engine/model.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- drawing namespace: `from simplecadapi.dxf_engine import CenterDecl`
|
||||
|
||||
## Description
|
||||
|
||||
中心线声明:p1/p2 直线中心线,或 arc=(cx,cy,r,a0,a1) 圆弧中心线。
|
||||
@@ -0,0 +1,17 @@
|
||||
# DatumDecl
|
||||
|
||||
## Class Definition
|
||||
|
||||
```python
|
||||
class DatumDecl(letter: str, kind: str, view: str, at: tuple, box_off: tuple = (9.0, 6.0), desc: str = '')
|
||||
```
|
||||
|
||||
*Source: dxf_engine/model.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- drawing namespace: `from simplecadapi.dxf_engine import DatumDecl`
|
||||
|
||||
## Description
|
||||
|
||||
基准符号声明(GB 基准体系):主基准 A、辅助基准 B/C…。
|
||||
@@ -0,0 +1,17 @@
|
||||
# DimDecl
|
||||
|
||||
## Class Definition
|
||||
|
||||
```python
|
||||
class DimDecl(kind: str, view: str, semantic: str, caption: str, value: float = None, p1: tuple = None, p2: tuple = None, center: tuple = None, radius: float = None, at: float = None, datum: str = None, side: str = None, row: int = 0, out: float = 8.0, dec: int = 0, prefix: str = '', covers: list = field(default_factory=list), name: str = '')
|
||||
```
|
||||
|
||||
*Source: dxf_engine/model.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- drawing namespace: `from simplecadapi.dxf_engine import DimDecl`
|
||||
|
||||
## Description
|
||||
|
||||
一条尺寸声明。kind=定位(position)尺寸必须在 datum 里引用已声明基准。
|
||||
@@ -0,0 +1,17 @@
|
||||
# LeaderDecl
|
||||
|
||||
## Class Definition
|
||||
|
||||
```python
|
||||
class LeaderDecl(view: str, anchor: tuple, lines: list, off: tuple = (30.0, -18.0), alt_offs: list = field(default_factory=list), dx_dir: float = 1.0, name: str = '')
|
||||
```
|
||||
|
||||
*Source: dxf_engine/model.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- drawing namespace: `from simplecadapi.dxf_engine import LeaderDecl`
|
||||
|
||||
## Description
|
||||
|
||||
引出说明声明:从 anchor 引出折线到注释文本。
|
||||
@@ -266,6 +266,18 @@ This index includes generated docs for the public SimpleCAD API surface, includi
|
||||
- [inspect_benchmark_step](inspect_benchmark_step.md) *(from inverse_engineer/brep/evaluation.py)* `reverse-engineering evaluator`
|
||||
- [run_comparison_bundle](run_comparison_bundle.md) *(from inverse_engineer/brep/evaluation.py)* `reverse-engineering evaluator`
|
||||
|
||||
## Engineering Drawings
|
||||
|
||||
- [CenterDecl](CenterDecl.md) *(from dxf_engine/model.py)* `submodule:dxf_engine/model`
|
||||
- [DatumDecl](DatumDecl.md) *(from dxf_engine/model.py)* `submodule:dxf_engine/model`
|
||||
- [DimDecl](DimDecl.md) *(from dxf_engine/model.py)* `submodule:dxf_engine/model`
|
||||
- [LeaderDecl](LeaderDecl.md) *(from dxf_engine/model.py)* `submodule:dxf_engine/model`
|
||||
- [Resolved](Resolved.md) *(from dxf_engine/planner.py)* `submodule:dxf_engine/planner`
|
||||
- [SheetDecl](SheetDecl.md) *(from dxf_engine/model.py)* `submodule:dxf_engine/model`
|
||||
- [SheetPlan](SheetPlan.md) *(from dxf_engine/planner.py)* `submodule:dxf_engine/planner`
|
||||
- [ViewDecl](ViewDecl.md) *(from dxf_engine/model.py)* `submodule:dxf_engine/model`
|
||||
- [render_plan](render_plan.md) *(from dxf_engine/render.py)* `submodule:dxf_engine/render`
|
||||
|
||||
## Other
|
||||
|
||||
- [Assembly](Assembly.md) *(from product/assembly.py)* `top-level`
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# Resolved
|
||||
|
||||
## Class Definition
|
||||
|
||||
```python
|
||||
class Resolved(kind: str, name: str, view: str, requested: str, resolved: str, adjust: list = field(default_factory=list), draw: dict = field(default_factory=dict), rule: str = '')
|
||||
```
|
||||
|
||||
*Source: dxf_engine/planner.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- drawing namespace: `from simplecadapi.dxf_engine import Resolved`
|
||||
|
||||
## Description
|
||||
|
||||
一个标注元素在纸面上的求解结果:requested(声明值) → resolved(实际位置) +
|
||||
adjust(最少调整顺延记录) + draw(渲染所需的预计算几何) + rules(触发的规则)。
|
||||
@@ -0,0 +1,21 @@
|
||||
# SheetDecl
|
||||
|
||||
## Class Definition
|
||||
|
||||
```python
|
||||
class SheetDecl(title: str, dwg_no: str, scale: float, front: str, anchor: tuple, views: list, datums: list = field(default_factory=list), dims: list = field(default_factory=list), centers: list = field(default_factory=list), leaders: list = field(default_factory=list), notes: list = field(default_factory=list), params: dict = field(default_factory=dict), material: str = 'PLA-CF / PAHT', notes_zone: tuple = (25.0, 5.0, 232.0, 90.0), diag_png: str = '')
|
||||
```
|
||||
|
||||
*Source: dxf_engine/model.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- drawing namespace: `from simplecadapi.dxf_engine import SheetDecl`
|
||||
|
||||
## Description
|
||||
|
||||
一张图纸的完整声明:图幅信息 + 视图 + 基准 + 尺寸 + 中心线 + 引出说明 + 参数表。
|
||||
|
||||
调用方只声明"要表达什么",不指定任何纸面坐标;布局与标注位置由
|
||||
SheetPlan.solve() 求解。front/anchor 定义主视图锚定,其余视图经
|
||||
ViewDecl.align 相对主视图对正(第一角投影,长对正/高平齐)。
|
||||
@@ -0,0 +1,22 @@
|
||||
# SheetPlan
|
||||
|
||||
## Class Definition
|
||||
|
||||
```python
|
||||
class SheetPlan(decl: SheetDecl)
|
||||
```
|
||||
|
||||
*Source: dxf_engine/planner.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- drawing namespace: `from simplecadapi.dxf_engine import SheetPlan`
|
||||
|
||||
## Description
|
||||
|
||||
标注方案求解器:SheetDecl → solve() → resolved/accepted/report() → render()。
|
||||
|
||||
求解流程:视图布局(第一角投影、align 对正) → 基准安放 → 线性尺寸
|
||||
(按视图/侧/行/大外小内排序) → 直径/半径尺寸 → 引出说明 → 参数覆盖检查。
|
||||
所有冲突处理遵循"最少调整":优先顺延候选位置并记入 Resolved.adjust,
|
||||
放不下则记入 R1 警告,绝不静默丢弃。
|
||||
@@ -0,0 +1,17 @@
|
||||
# ViewDecl
|
||||
|
||||
## Class Definition
|
||||
|
||||
```python
|
||||
class ViewDecl(name: str, shape: object, n: tuple, xd: tuple, align: dict = field(default_factory=dict), anchor: tuple = None)
|
||||
```
|
||||
|
||||
*Source: dxf_engine/model.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- drawing namespace: `from simplecadapi.dxf_engine import ViewDecl`
|
||||
|
||||
## Description
|
||||
|
||||
HLR 投影视图。n=观察方向, xd=投影面内屏幕右方向; align 定义布局约束。
|
||||
@@ -14,4 +14,4 @@ def make_wire_from_sketch_rwire(sketch: Sketch, profile: int | str = 0, *, requi
|
||||
|
||||
## Description
|
||||
|
||||
Promote a sketch profile to a concrete wire, solving internally.
|
||||
Promote a sketch profile (closed loop or open chain) to a concrete wire, solving internally.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# render_plan
|
||||
|
||||
## API Definition
|
||||
|
||||
```python
|
||||
def render_plan(plan, dxf_path, png_path)
|
||||
```
|
||||
|
||||
*Source: dxf_engine/render.py*
|
||||
|
||||
## Import Surface
|
||||
|
||||
- drawing namespace: `from simplecadapi.dxf_engine import render_plan`
|
||||
|
||||
## Description
|
||||
|
||||
把求解后的 SheetPlan 渲染为 GB 图层 DXF + PNG 双产物。
|
||||
|
||||
DXF 走 ezdxf(手工基元:细实线尺寸线/界线、实心箭头、旋转归一文字、
|
||||
GB 图层 01粗实线/08虚线/05中心线/尺寸标注/文字),PNG 经 PyMuPdf 由
|
||||
DXF 转出用于多模态互校验。同时写出便于版本 diff 的文本化动作日志。
|
||||
@@ -0,0 +1,104 @@
|
||||
# Task Domain: Engineering Drawing Generation
|
||||
|
||||
Generate GB-standard 2D engineering drawing sheets (DXF, plus a PNG rendered
|
||||
from that DXF for review) from finished 3D geometry with the declarative
|
||||
`simplecadapi.dxf_engine` namespace. Standards followed: GB/T 4458.4-2003
|
||||
(dimensioning), GB/T 4457.4-2002 (line types), GB/T 14692 (projection),
|
||||
GB/T 4458.1 (hidden-line removal).
|
||||
|
||||
## Use when
|
||||
|
||||
- The part or product geometry is already modeled and validated, and the
|
||||
deliverable is a manufacturing drawing sheet.
|
||||
- You need a first-angle multiview layout (长对正 / 高平齐 alignment), a datum
|
||||
system, and size / position / overall dimensions placed by rule rather than
|
||||
by hand.
|
||||
|
||||
## Do not use
|
||||
|
||||
- For 3D visualization or geometry inspection — use the
|
||||
`simplecadapi.inspect.brep` rendering functions instead.
|
||||
- As a modeling aid: the engine consumes finished shapes; it does not record
|
||||
graph nodes and does not modify geometry. Validate geometry first, draw
|
||||
second.
|
||||
- For hand-placed annotation: callers never specify sheet coordinates. Sheet
|
||||
placement is owned exclusively by the solver.
|
||||
|
||||
## Core idea: declare, then solve
|
||||
|
||||
The engine is a four-layer pipeline with one-way data flow:
|
||||
`SheetDecl (declaration) → SheetPlan.solve() (rule-driven solve) →
|
||||
resolved/accepted/report() (audit) → render (DXF + PNG)`.
|
||||
|
||||
Callers declare *what* must be expressed — views, datums, dimension
|
||||
semantics, center lines, leader notes — in view-local model coordinates. The
|
||||
solver computes every sheet position under rules R1–R7 and records each
|
||||
placement (and any least-adjustment deferral) in an auditable report.
|
||||
|
||||
## Solver contract (R1–R7)
|
||||
|
||||
| Rule | Contract |
|
||||
| --- | --- |
|
||||
| R1 safe zone | Text (OBB), leaders, and dimension lines must not collide with geometry, other annotations, or forbidden zones; least-adjustment deferral, never silent deletion |
|
||||
| R2 text direction | Text parallel to the dimension line; heads up (horizontal) / left (vertical); never upside down |
|
||||
| R3 30° dead zone | Dimension lines near vertical within ±30° produce a warning (GB/T 4458.4 fig. 17) |
|
||||
| R4 row slots | Same-side dimensions use fixed row pitch; declared row wins, collisions defer outward; larger sizes land outer automatically |
|
||||
| R5 parameter coverage | Every model parameter is carried by a dimension (`covers`) or lands in notes / parameter table |
|
||||
| R6 datum reference | Position dimensions must reference a declared datum letter |
|
||||
| R7 no duplicates | No repeated same-kind measurement within a view |
|
||||
|
||||
## API groups
|
||||
|
||||
Read the exact page under `references/docs/api/` for every API used:
|
||||
|
||||
- Declaration (pure dataclasses, validated at declaration time):
|
||||
`SheetDecl` (sheet: title, drawing number, scale, views, notes, parameter
|
||||
table), `ViewDecl` (HLR view: `n` view direction, `xd` screen-right,
|
||||
`align={"to","side","gap"}`), `DimDecl` (`kind=size|position|overall` ×
|
||||
`semantic=linear|diameter|radius`, `covers` for parameter traceability),
|
||||
`DatumDecl` (datum letters A/B/C…), `CenterDecl` (line or arc center
|
||||
lines), `LeaderDecl` (leader notes).
|
||||
- Solve and audit: `SheetPlan(decl).solve()`, `plan.resolved`
|
||||
(`Resolved` items: requested → resolved, `adjust`, `draw`, rules),
|
||||
`plan.accepted`, `plan.report()` (auditable text report), `plan.tx(view,
|
||||
point)` (view-local model → sheet coordinates).
|
||||
- Layout evaluation and actions (agent-in-the-loop): `plan.evaluate()` —
|
||||
structured per-element conflict report (`violations`: exact obstacles with
|
||||
distances; `corridors`: free translation ranges), digested quantities
|
||||
instead of raw geometry; `plan.apply(actions)` — replay an action-log JSON
|
||||
(`rad`/`dia`/`lin`/`lead` placement adjustments, `accept` to bless a
|
||||
warning with a reason) with per-action validation and reject-with-rollback
|
||||
residuals. The engine owns deterministic truth; the agent owns discrete
|
||||
choices. The action file is the decision log — plans rebuild statelessly
|
||||
from declarations plus replayed actions.
|
||||
- Output: `SheetPlan.render(dxf_path, png_path)` / `render_plan` — GB layers
|
||||
(粗实线 / 虚线 / 中心线 / 细实线 / dimension / text), solid arrows,
|
||||
CJK-capable text style; writes the DXF and a PNG rendered from it for
|
||||
cross-checking.
|
||||
|
||||
See `references/workflows/engineering-drawing.md` for the staged workflow
|
||||
that composes this domain.
|
||||
|
||||
## Known boundaries (preliminary engine)
|
||||
|
||||
- No section views or hatching yet.
|
||||
- Linear dimensions are horizontal/vertical only.
|
||||
- `DimDecl` carries no arc-span information, so radius/diameter labels place
|
||||
same-side outward (`out=6/12/18/24/30` ladder); there is no flip-to-opposite
|
||||
candidate. If it does not fit, R1 reports a warning — change the layout,
|
||||
not the rules.
|
||||
- HLR may emit arc edges as B-splines; such arcs render as polylines.
|
||||
- A boss circle can be drawn twice (visible compound + outline compound);
|
||||
key-based dedupe is pending.
|
||||
|
||||
## Failure modes
|
||||
|
||||
- Declaring a `position` dimension without `datum` raises `ValueError` at
|
||||
declaration time — this is intentional fail-fast (R6); declare the datum
|
||||
first.
|
||||
- R1 warnings mean "does not fit as declared". Fix by re-declaring
|
||||
(`side`, `row`, `out`, view gaps), never by hunting for coordinates to
|
||||
nudge — there are none.
|
||||
- Treating "no rule conflicts" as "drawing looks right": always review the
|
||||
PNG. Solver-clean sheets can still be visually wrong (e.g. an ambiguous
|
||||
view or a misleading dimension arrangement).
|
||||
@@ -0,0 +1,195 @@
|
||||
# Workflow: Engineering Drawing Generation
|
||||
|
||||
Produce a GB-standard engineering drawing sheet set (DXF + PNG) from an
|
||||
already-validated part or product. This is a preliminary workflow; drawing is
|
||||
an output stage, so geometry must be final before entry. Layout follows the
|
||||
engine's division of labor: the solver computes deterministic truth
|
||||
(projection, measurements, collisions, rules R1–R7), and the agent refines
|
||||
the layout through a validate-and-rollback action loop.
|
||||
|
||||
Read `domains/engineering-drawing.md` first — this workflow does not repeat
|
||||
its solver rules or engine boundaries.
|
||||
|
||||
Standing discipline, binding for every role:
|
||||
|
||||
- **Geometry first, drawing second.** Enter only with validated geometry and
|
||||
a settled datum story. A drawing never repairs a model; it exposes one.
|
||||
- **Engine truth, agent choice.** Every validity judgment (collision, R1–R7,
|
||||
coverage) is computed by the engine. The agent only arbitrates discrete
|
||||
choices (which side/row, which trade-off) through actions the engine
|
||||
validates or rejects with reasons. Never hand-edit a rendered DXF or PNG.
|
||||
- **Declare, then arbitrate.** Start from semantic declarations
|
||||
(`SheetDecl` + friends); run the action loop only on what the solver could
|
||||
not place cleanly. Actions refine a solvable declaration; they are not a
|
||||
substitute for one.
|
||||
- **The action log is the decision log.** Every layout change is an action
|
||||
in a replayable JSON file. Rebuilding from declarations plus replaying the
|
||||
action file must reproduce the sheet byte-for-byte.
|
||||
- **Audit before render; two artifacts, one truth.** `report()` is reviewed
|
||||
before rendering, and visual acceptance means reading the PNG rendered
|
||||
from the DXF — "no rule conflicts" alone is not acceptance.
|
||||
|
||||
## Role map
|
||||
|
||||
| # | Role | Reads (load before acting) | Produces | Exit gate |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 1 | Drawing Requirement Confirmer | `domains/requirement-refinement.md`, `domains/engineering-drawing.md`, model requirements (`REQUIREMENTS.md`/`BUILD_PLAN.md` if present) | `<part-dir>/DRAWING.md` | ⛔ user consent received |
|
||||
| 2 | Sheet Planner | `DRAWING.md`, `discipline/datums-and-coordinate-systems.md` | per-sheet view/datum/dimension roster + R5 coverage ledger | plan presented |
|
||||
| 3 | Layout Arbiter | sheet plan, `domains/engineering-drawing.md`, declaration/action API pages | sheet declarations, action-log JSONs, solver-clean report | `report()` R1–R7 ok or accepted-with-reason, R5 no `MISS`, no open warnings |
|
||||
| 4 | Visual Reviewer | rendered PNG only | structured verdict | verdict pass; failures become `repair:` items for Role 3 |
|
||||
| 5 | Drawing Exporter | verdict-passed action logs, `domains/engineering-drawing.md` | final DXF + PNG + archived action logs | artifacts re-open cleanly |
|
||||
|
||||
## Role-switch protocol
|
||||
|
||||
Before starting a role's work, output exactly:
|
||||
|
||||
```markdown
|
||||
## [Role Switch: <Role Name>]
|
||||
Reading: <role-owned files>
|
||||
Artifact out: <path>
|
||||
```
|
||||
|
||||
Then act only inside that role's scope. Roles 3 and 4 alternate per sheet:
|
||||
|
||||
```text
|
||||
Sheet_1: Role 3 declare + action loop -> Role 4 render verdict -> (repair:)*
|
||||
Sheet_2: Role 3 declare + action loop -> Role 4 render verdict -> (repair:)*
|
||||
...
|
||||
```
|
||||
|
||||
A failed verdict does not advance the sheet; it appends a `repair:` item
|
||||
owned by the declarations or the action log, whichever owns the failure, and
|
||||
repeats the same Role 3/4 loop.
|
||||
|
||||
---
|
||||
|
||||
## Role 1 — Drawing Requirement Confirmer ⛔
|
||||
|
||||
Convert the request into `DRAWING.md`. No declarations, no renders before
|
||||
this gate closes.
|
||||
|
||||
1. Carry over the model's settled facts (geometry validated, parameters
|
||||
named). Do not reopen modeling decisions here.
|
||||
2. Decide-or-ask the drawing-level choices: sheet scale, view set (which
|
||||
views, which sheet each lives on), datum letters, which parameters are
|
||||
manufacturing-critical, and the notes/parameter-table split.
|
||||
3. Batch every blocking ambiguity into ONE ask round with conservative
|
||||
defaults first (`domains/requirement-refinement.md`). Record the rest in
|
||||
the Ask-or-Record ledger with basis.
|
||||
|
||||
Write `DRAWING.md` with: scale; per-sheet view roster; datum scheme;
|
||||
dimension roster seeds (parameter → kind/semantic guess); R5 ledger skeleton
|
||||
(every parameter → dimension carrier or notes/table); open assumptions.
|
||||
|
||||
Gate: the ask round returned and consent is recorded. Entering Role 2
|
||||
without this gate is the cardinal violation.
|
||||
|
||||
## Role 2 — Sheet Planner
|
||||
|
||||
From `DRAWING.md` only — no API detail, no coordinates.
|
||||
|
||||
1. Per sheet, fix the view set and alignment structure (front view anchored;
|
||||
every other view `align`ed to it — 长对正 / 高平齐 by construction, never
|
||||
by offsets).
|
||||
2. Fix the datum scheme consistent with the model's functional interfaces
|
||||
(`discipline/datums-and-coordinate-systems.md`).
|
||||
3. Produce the dimension roster: for each parameter, its carrier dimension
|
||||
(kind, semantic, view, reference datum) or its notes/parameter-table
|
||||
destination. This roster IS the R5 coverage ledger.
|
||||
4. Flag parameters the engine cannot express yet (engine boundaries in the
|
||||
domain page) and route them to notes explicitly — never silently.
|
||||
|
||||
Present the plan in ≤10 lines. No approval gate; enter the Role 3/4 loop.
|
||||
|
||||
## Role 3 — Layout Arbiter
|
||||
|
||||
Owns declarations and the agent-in-the-loop refinement cycle.
|
||||
|
||||
**Phase A — declare.** Author the `SheetDecl` per sheet from the roster:
|
||||
`ViewDecl`s with `align`, `DatumDecl`s first, `DimDecl`s with `covers`,
|
||||
`CenterDecl`/`LeaderDecl` as planned. Solve, print `report()`, and read it
|
||||
line by line: fix declaration-level problems (wrong view, missing datum
|
||||
reference, duplicate measurement) by re-declaring, not by actions.
|
||||
|
||||
**Phase B — the action loop.** For everything the solver placed with
|
||||
warnings or left unsolved, iterate:
|
||||
|
||||
1. **See.** Render the annotated review image (`viz`): gray = placed ok,
|
||||
blue = unsolved, red = warning, orange = accepted-with-reason; green
|
||||
arrows show each element's free movement corridors (how far it can
|
||||
translate, per direction). Read the red and blue elements first.
|
||||
2. **Measure.** Call `plan.evaluate()` and read the exact, digested numbers
|
||||
for the failing elements: per-element `violations` (what it hits, where,
|
||||
by how much) and `corridors` (free translation distances). Work from
|
||||
these quantities — never from re-derived raw geometry.
|
||||
3. **Propose.** Compose the next action-log JSON: one action per decision
|
||||
(`rad`/`dia`/`lin`/`lead` position adjustments, `accept` to bless a
|
||||
warning with a recorded reason). Actions are discrete choices — which
|
||||
side, which row, which trade-off (R1 squeeze vs arrow-off-arc vs new
|
||||
azimuth) — arbitrated by you, the agent.
|
||||
4. **Submit.** Replay via `plan.apply(actions)`: the engine validates each
|
||||
action and rejects bad ones with `violations`/`corridors` residuals,
|
||||
rolling the sheet back to the last consistent state. A rejection is data,
|
||||
not failure: read the residuals, revise the action, resubmit.
|
||||
5. **Verify blast radius.** Diff the previous and new action logs (pixel
|
||||
diff of the two replays): red = newly covered, blue = vacated, gray =
|
||||
untouched. Confirm the action moved only what you intended.
|
||||
6. Loop 1–5 until every element is gray or orange (warn = 0), then run the
|
||||
full `report()` audit once more.
|
||||
|
||||
Exit gate: `report()` shows R1–R7 ok or accepted-with-reason, the R5
|
||||
coverage table has no `MISS`, and no red/blue elements remain. Drive the
|
||||
loop directly against `SheetPlan` (solve / evaluate / apply / render);
|
||||
declaring `SheetDecl.diag_png` makes every solve/apply auto-refresh the
|
||||
annotated conflict image and return a must-read instruction with it.
|
||||
|
||||
## Role 4 — Visual Reviewer
|
||||
|
||||
Rendered-PNG-only judgment, delegated in the same spirit as image verdicts
|
||||
in `workflows/single-part-modeling.md`: the reviewer sees the artifacts, not
|
||||
the reasoning.
|
||||
|
||||
1. Read the PNG rendered from the final DXF (both sheets if multiple).
|
||||
2. Check, in order: views aligned as planned; hidden lines (虚线) and center
|
||||
lines present; arrows touch their geometry; texts sit clear of lines;
|
||||
datum boxes legible; the dimension arrangement communicates design intent
|
||||
(a formally clean sheet can still mislead — e.g. dimensioning a derived
|
||||
length instead of the functional one).
|
||||
3. Emit a structured verdict: pass, or an itemized list where each item
|
||||
names the owning artifact (declaration or action log).
|
||||
|
||||
A failed item becomes a `repair:` item for Role 3. Never patch the DXF.
|
||||
|
||||
## Role 5 — Drawing Exporter
|
||||
|
||||
1. Final render: `plan.render(dxf, png)` per sheet from the verdict-passed
|
||||
state (declarations + replayed action logs).
|
||||
2. Re-open the DXF (e.g. via `ezdxf`) and check the entity count matches the
|
||||
render report; confirm both artifacts regenerate deterministically from
|
||||
the same inputs.
|
||||
3. Deliver: DXF + PNG paths plus the archived action-log JSONs (they are
|
||||
part of the deliverable — the reproducible decision history).
|
||||
|
||||
## Acceptance
|
||||
|
||||
- `report()`: R1–R7 all ok, or accepted with recorded reasons.
|
||||
- R5: every model parameter has a carrier; no `MISS`.
|
||||
- Visual verdict passed; DXF re-opens with expected entity count; the sheet
|
||||
regenerates byte-for-byte from declarations + action log.
|
||||
- Engine boundaries routed explicitly (notes/table), never silently dropped.
|
||||
|
||||
## Failure modes
|
||||
|
||||
- Entering with unvalidated geometry: every downstream conflict then looks
|
||||
like a drawing bug but is a model bug.
|
||||
- Using actions to fight a wrong declaration: if `report()` shows structural
|
||||
problems (missing datum, duplicate measurement), re-declare — the action
|
||||
loop is for placement refinement, not for repairing semantics.
|
||||
- Trusting "no conflicts" over the PNG, or skipping the diff step so one
|
||||
action silently relocates a neighbor.
|
||||
- Losing the action log: without it the sheet is not reproducible; treat it
|
||||
as a deliverable, not scratch.
|
||||
- Hitting engine boundaries (no sections/hatching; horizontal/vertical
|
||||
linear dims only; radius labels same-side outward): restructure the view
|
||||
set or record the limitation; do not simulate missing features with
|
||||
leader-note spam.
|
||||
@@ -32,6 +32,8 @@ dependencies = [
|
||||
"tomli>=2.0,<3; python_version < '3.11'",
|
||||
"py-slvs==1.0.6",
|
||||
"ocp-gordon>=0.2,<0.3",
|
||||
"ezdxf>=1.4.4",
|
||||
"pymupdf>=1.28.2",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
"""simplecadapi.dxf_engine — 声明式 GB 工程图纸引擎。
|
||||
|
||||
分层 (标注学 mindset):
|
||||
model 标注语义声明 —— 基准体系 / 定形·定位·总体尺寸 / 参数覆盖追溯
|
||||
planner 标注方案求解 —— 视图布局、行槽分配(小内大外)、最少调整、GB 规则 R1-R7
|
||||
hlr OCCT 隐藏线消除投影 (GB/T 4458.1)
|
||||
render 手工基元渲染 —— 文字平行尺寸线(字头朝上/朝左)、实心箭头、细实线
|
||||
|
||||
GB/T 4458.4-2003 尺寸注法 · GB/T 4457.4-2002 图线 · GB/T 14692 投影法
|
||||
"""
|
||||
from .model import (CenterDecl, DatumDecl, DimDecl, LeaderDecl, SheetDecl,
|
||||
ViewDecl)
|
||||
from .planner import SheetPlan
|
||||
|
||||
__all__ = ["SheetDecl", "ViewDecl", "DimDecl", "DatumDecl", "CenterDecl",
|
||||
"LeaderDecl", "SheetPlan"]
|
||||
@@ -0,0 +1,522 @@
|
||||
"""dxf_engine.agent — LLM-in-the-loop 评估/执行接口。
|
||||
|
||||
角色分工 (评估器 + 提示器, 决策权在 LLM):
|
||||
引擎(确定性) 精确冲突数据 / 自由走廊度量 / 动作校验落地 (拒绝即回滚)
|
||||
LLM(决策) 在评估数据上选点/取舍, 经 apply 提交动作, 引擎全量复检
|
||||
几何真值不出代码: LLM 永不提供裸顶点之外的算术结果, mpt/箭头等语义约束
|
||||
由引擎从 (at,out,rot) 重推导 —— 箭头恒落在真实圆周上。
|
||||
评估政策与各求解器一致: 文本/标线不查本视图图线 (标注可压自身视图)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
from .planner import BASE_OFF, Box, ROW_PITCH, TEXT_H, _text_width
|
||||
|
||||
|
||||
def _r(v, nd=1):
|
||||
return round(float(v), nd)
|
||||
|
||||
|
||||
def _element_geom(r):
|
||||
"""Resolved → (key, view, cx, cy, w, h, rot, segs);几何不全返回 None。"""
|
||||
dr = r.draw
|
||||
if r.kind == "dim":
|
||||
text = dr.get("text", "")
|
||||
w = _text_width(text, TEXT_H)
|
||||
if dr.get("kind") == "lin" and "insert" in dr:
|
||||
ins = dr["insert"]
|
||||
return (f"dim:{r.name}", r.view, ins[0], ins[1], w, TEXT_H, dr["rot"],
|
||||
[tuple(dr["line"])] + [tuple(s) for s in dr["exts"]])
|
||||
if dr.get("kind") == "dia-man":
|
||||
a = dr["anchor"]
|
||||
return (f"dim:{r.name}", r.view, a[0], a[1], w, TEXT_H, dr["rot"],
|
||||
[(tuple(dr["m1"]), tuple(dr["m2"])),
|
||||
(tuple(dr["m1"]), tuple(dr["insert"]))])
|
||||
if dr.get("kind") == "rad-man":
|
||||
a = dr["anchor"]
|
||||
return (f"dim:{r.name}", r.view, a[0], a[1], w, TEXT_H, dr["rot"],
|
||||
[(tuple(dr["mpt"]), tuple(dr["tail"]))])
|
||||
return None
|
||||
if r.kind == "leader" and r.name:
|
||||
x0, y1 = dr["text_x"], dr["text_y_top"]
|
||||
w = max(_text_width(t, 2.2) for t in dr["lines"])
|
||||
h = len(dr["lines"]) * 4.2 + 1.0
|
||||
p = dr["path"]
|
||||
return (f"lead:{r.name}", r.view, x0 + w / 2, y1 - h / 2, w, h, 0.0,
|
||||
[(tuple(p[i]), tuple(p[i + 1])) for i in range(len(p) - 1)])
|
||||
if r.kind == "datum":
|
||||
bc = dr["bc"]
|
||||
return (f"datum:{r.name}", r.view, bc[0], bc[1], 6.0, 4.4, 0.0, [])
|
||||
return None
|
||||
|
||||
|
||||
def _proper_cross(a, b, c, d, eps=0.5):
|
||||
"""严格 X 交叉: 两段互相跨立且无共端点。共端点(共用测量点)/共线(共用界线)/
|
||||
丁字(界线端点落在他人线上)均为 GB 正常画法, 不计冲突。"""
|
||||
if min(math.dist(a, c), math.dist(a, d),
|
||||
math.dist(b, c), math.dist(b, d)) < eps:
|
||||
return False
|
||||
|
||||
def ori(p, q, r):
|
||||
v = (q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0])
|
||||
return 0 if abs(v) < 1e-9 else (1 if v > 0 else -1)
|
||||
|
||||
o1, o2 = ori(a, b, c), ori(a, b, d)
|
||||
o3, o4 = ori(c, d, a), ori(c, d, b)
|
||||
return o1 == -o2 and o3 == -o4 and o1 != 0 and o3 != 0
|
||||
|
||||
|
||||
def _conflicts(plan, key, view, cx, cy, w, h, rot, segs):
|
||||
"""单元素放置的确定性冲突检测, 返回结构化障碍数据 (纸面坐标 mm)。"""
|
||||
out = []
|
||||
for i, z in enumerate(plan._zones):
|
||||
if plan._obb_sat(cx, cy, w, h, rot, z.inflate(1.0)):
|
||||
out.append({"rule": "R1", "type": "禁入区", "id": f"zone{i}",
|
||||
"bbox": [_r(z.x0), _r(z.y0), _r(z.x1), _r(z.y1)]})
|
||||
for n, vw in plan.views.items():
|
||||
bb = vw["bbox"]
|
||||
if n != view and plan._obb_sat(cx, cy, w, h, rot, bb.inflate(0.5)):
|
||||
out.append({"rule": "R1", "type": "视图bbox", "id": f"view:{n}",
|
||||
"bbox": [_r(bb.x0), _r(bb.y0), _r(bb.x1), _r(bb.y1)]})
|
||||
if n != view:
|
||||
nh = sum(1 for sp, _sq in vw["pairs"]
|
||||
if plan._pt_in_obb(sp[0], sp[1], cx, cy, w, h, rot))
|
||||
if nh:
|
||||
out.append({"rule": "R1", "type": "图线", "id": f"figure:{n}",
|
||||
"points": nh})
|
||||
for k2, cx2, cy2, w2, h2, r2 in plan.text_obbs:
|
||||
if k2 != key and plan._obb_obb(cx, cy, w, h, rot, cx2, cy2, w2, h2, r2):
|
||||
out.append({"rule": "R1", "type": "文本", "id": k2,
|
||||
"center": [_r(cx2), _r(cy2)], "w": _r(w2), "h": _r(h2),
|
||||
"rot": _r(r2)})
|
||||
for k2, sp, sq in plan.segments:
|
||||
if k2 == key:
|
||||
continue
|
||||
if (plan._seg_obb(sp, sq, cx, cy, w, h, rot)
|
||||
or any(_proper_cross(s[0], s[1], sp, sq) for s in segs)):
|
||||
out.append({"rule": "R1", "type": "标线", "id": k2,
|
||||
"seg": [[_r(sp[0]), _r(sp[1])], [_r(sq[0]), _r(sq[1])]]})
|
||||
for s in segs:
|
||||
for n in plan._seg_vs_views(s, view):
|
||||
out.append({"rule": "R1", "type": "标线穿他视图图线", "id": f"figure:{n}"})
|
||||
return out
|
||||
|
||||
|
||||
def _corridors(plan, key, view, cx, cy, w, h, rot, maxd=60.0, step=1.0):
|
||||
"""文本 OBB 沿 ±x/±y 平移的最大无冲突距离 (仅文本碰撞, 不含标线)。"""
|
||||
res = {}
|
||||
for label, dx, dy in (("+x", 1, 0), ("-x", -1, 0), ("+y", 0, 1), ("-y", 0, -1)):
|
||||
d = 0.0
|
||||
while d < maxd and not _conflicts(plan, key, view,
|
||||
cx + dx * (d + step), cy + dy * (d + step),
|
||||
w, h, rot, []):
|
||||
d += step
|
||||
res[label] = _r(d)
|
||||
return res
|
||||
|
||||
|
||||
def evaluate_plan(plan):
|
||||
accepted = getattr(plan, "accepted", {})
|
||||
elements = []
|
||||
for r in plan.resolved:
|
||||
if r.kind == "view": # 视图非标注元素, 不评估
|
||||
continue
|
||||
g = _element_geom(r)
|
||||
key = g[0] if g else f"{r.kind}:{r.name}"
|
||||
entry = {"id": key, "kind": r.kind, "view": r.view}
|
||||
if g is None:
|
||||
entry["status"] = "unsolved"
|
||||
elements.append(entry)
|
||||
continue
|
||||
_k, view, cx, cy, w, h, rot, segs = g
|
||||
conf = _conflicts(plan, key, view, cx, cy, w, h, rot, segs)
|
||||
rules = sorted({c["rule"] for c in conf})
|
||||
if (60.0 < rot % 180.0 < 90.0) or (90.0 < rot % 180.0 < 120.0):
|
||||
rules.append("R3") # 竖直 90° 本身合法 (GB 图17)
|
||||
entry.update(text=r.draw.get("text")
|
||||
or (r.draw.get("lines") and " / ".join(r.draw["lines"])),
|
||||
anchor=[_r(cx), _r(cy)], w=_r(w), h=_r(h), rot=_r(rot))
|
||||
if key in accepted:
|
||||
entry.update(status="accepted",
|
||||
reason=accepted.get(key) if isinstance(accepted, dict)
|
||||
else None)
|
||||
elif conf:
|
||||
entry.update(status="warn", rules=rules, violations=conf,
|
||||
corridors=_corridors(plan, key, view, cx, cy, w, h, rot))
|
||||
else:
|
||||
entry["status"] = "ok"
|
||||
if "R3" in rules:
|
||||
entry["rules"] = ["R3"]
|
||||
elements.append(entry)
|
||||
n_warn = sum(1 for e in elements if e["status"] == "warn")
|
||||
return {"sheet": plan.d.title, "dwg_no": plan.d.dwg_no,
|
||||
"n_elements": len(elements), "n_warn": n_warn, "elements": elements}
|
||||
|
||||
|
||||
def _find_dim(plan, caption):
|
||||
for d in plan.d.dims:
|
||||
if d.caption == caption:
|
||||
return d
|
||||
raise KeyError(f"dim {caption}")
|
||||
|
||||
|
||||
def _find_resolved(plan, key):
|
||||
for r in plan.resolved:
|
||||
g = _element_geom(r)
|
||||
if g and g[0] == key:
|
||||
return r
|
||||
raise KeyError(key)
|
||||
|
||||
|
||||
def _unregister(plan, key):
|
||||
old_ob = [t for t in plan.text_obbs if t[0] == key]
|
||||
old_sg = [t for t in plan.segments if t[0] == key]
|
||||
plan.text_obbs = [t for t in plan.text_obbs if t[0] != key]
|
||||
plan.segments = [t for t in plan.segments if t[0] != key]
|
||||
return old_ob, old_sg
|
||||
|
||||
|
||||
def _restore(plan, old):
|
||||
plan.text_obbs += old[0]
|
||||
plan.segments += old[1]
|
||||
|
||||
|
||||
def _commit(plan, key, cx, cy, w, h, rot, segs):
|
||||
plan.text_obbs.append((key, cx, cy, w, h, rot))
|
||||
for sp, sq in segs:
|
||||
plan.segments.append((key, sp, sq))
|
||||
|
||||
|
||||
def _reject(plan, act, key, view, conf, cx, cy, w, h, rot):
|
||||
return {"op": act["op"], "element": key, "ok": False, "violations": conf,
|
||||
"corridors": _corridors(plan, key, view, cx, cy, w, h, rot)}
|
||||
|
||||
|
||||
def _norm_rot(at):
|
||||
rot = (at % 180.0 + 180.0) % 180.0
|
||||
return rot - 180.0 if rot > 90.0 else rot
|
||||
|
||||
|
||||
def _apply_rad(plan, act):
|
||||
"""半径: 动作只仲裁 at(方位角, 可选 s 滑移提示; s<0 为弧内侧——文字沿过圆心
|
||||
的尺寸线置于圆内, 箭头自圆心侧指弧)。基线恒在线上方、引线派生延长;
|
||||
rot 恒等于线向 (R2 不可覆盖), mpt 恒取 c+r·u —— 箭头必在圆周。"""
|
||||
dcl = _find_dim(plan, act["name"])
|
||||
key = f"dim:{dcl.caption}"
|
||||
dr = _find_resolved(plan, key).draw
|
||||
c = plan.tx(dcl.view, dcl.center)
|
||||
rr = dcl.radius * plan.s
|
||||
at0 = math.degrees(math.atan2(dr["mpt"][1] - c[1], dr["mpt"][0] - c[0]))
|
||||
at = act.get("at", at0)
|
||||
u = (math.cos(math.radians(at)), math.sin(math.radians(at)))
|
||||
rot = _norm_rot(at)
|
||||
n = (-math.sin(math.radians(rot)), math.cos(math.radians(rot)))
|
||||
w = _text_width(dr["text"], TEXT_H)
|
||||
mpt = (c[0] + rr * u[0], c[1] + rr * u[1])
|
||||
if "s" in act:
|
||||
cands = [float(act["s"])]
|
||||
else:
|
||||
cands = list(3.0 + 6.0 * k for k in range(5)) + [-(w + 4.0),
|
||||
-(w + 10.0),
|
||||
-(w + 18.0)]
|
||||
old = _unregister(plan, key)
|
||||
conf = anchor = None
|
||||
for s0 in cands:
|
||||
inner = (s0 + w) < 0.0
|
||||
tail_k = s0 - 1.5 if inner else s0 + w + 1.5
|
||||
insert = (mpt[0] + s0 * u[0] + n[0] * 1.0,
|
||||
mpt[1] + s0 * u[1] + n[1] * 1.0)
|
||||
anchor = (insert[0] + u[0] * w / 2 + n[0] * TEXT_H * 0.35,
|
||||
insert[1] + u[1] * w / 2 + n[1] * TEXT_H * 0.35)
|
||||
tail = (mpt[0] + tail_k * u[0], mpt[1] + tail_k * u[1])
|
||||
segs = [(mpt, tail)]
|
||||
conf = _conflicts(plan, key, dcl.view, anchor[0], anchor[1], w, TEXT_H,
|
||||
rot, segs)
|
||||
if not conf or act.get("force"):
|
||||
arrow_deg = math.degrees(math.atan2(u[1], u[0]))
|
||||
if not inner:
|
||||
arrow_deg += 180.0
|
||||
dr.update(mpt=mpt, tail=tail, insert=insert, anchor=anchor, rot=rot,
|
||||
arrow_deg=arrow_deg)
|
||||
_commit(plan, key, anchor[0], anchor[1], w, TEXT_H, rot, segs)
|
||||
_log(plan, key, f"at={at:g}° {'弧内' if inner else '弧外'} s={s0:g}")
|
||||
return {"op": "rad", "element": key, "ok": True,
|
||||
"anchor": [_r(anchor[0]), _r(anchor[1])], "rot": _r(rot)}
|
||||
_restore(plan, old)
|
||||
return _reject(plan, act, key, dcl.view, conf, anchor[0], anchor[1], w,
|
||||
TEXT_H, rot)
|
||||
|
||||
|
||||
def _apply_dia(plan, act):
|
||||
"""直径: at(尺寸线方位)。尺寸线过圆心, 文字锚 0.75r 线上方
|
||||
(insert=基线左端, anchor=OBB 中心), rot 恒等于线向 (R2)。"""
|
||||
dcl = _find_dim(plan, act["name"])
|
||||
key = f"dim:{dcl.caption}"
|
||||
dr = _find_resolved(plan, key).draw
|
||||
c = plan.tx(dcl.view, dcl.center)
|
||||
rr = dcl.radius * plan.s
|
||||
at0 = math.degrees(math.atan2(dr["m1"][1] - c[1], dr["m1"][0] - c[0]))
|
||||
at = act.get("at", at0)
|
||||
u = (math.cos(math.radians(at)), math.sin(math.radians(at)))
|
||||
m1 = (c[0] + rr * u[0], c[1] + rr * u[1])
|
||||
m2 = (c[0] - rr * u[0], c[1] - rr * u[1])
|
||||
rot = _norm_rot(at)
|
||||
n = (-math.sin(math.radians(rot)), math.cos(math.radians(rot)))
|
||||
w = _text_width(dr["text"], TEXT_H)
|
||||
insert = (c[0] + 0.75 * rr * u[0] + n[0] * 1.0,
|
||||
c[1] + 0.75 * rr * u[1] + n[1] * 1.0)
|
||||
anchor = (insert[0] + u[0] * w / 2 + n[0] * TEXT_H * 0.35,
|
||||
insert[1] + u[1] * w / 2 + n[1] * TEXT_H * 0.35)
|
||||
segs = [(m1, m2), (m1, insert)]
|
||||
old = _unregister(plan, key)
|
||||
conf = _conflicts(plan, key, dcl.view, anchor[0], anchor[1], w, TEXT_H, rot, segs)
|
||||
if conf and not act.get("force"):
|
||||
_restore(plan, old)
|
||||
return _reject(plan, act, key, dcl.view, conf, anchor[0], anchor[1], w, TEXT_H, rot)
|
||||
dr.update(m1=m1, m2=m2, insert=insert, anchor=anchor, rot=rot)
|
||||
_commit(plan, key, anchor[0], anchor[1], w, TEXT_H, rot, segs)
|
||||
_log(plan, key, f"at={at:g}°")
|
||||
return {"op": "dia", "element": key, "ok": True,
|
||||
"anchor": [_r(anchor[0]), _r(anchor[1])], "rot": _r(rot)}
|
||||
|
||||
|
||||
def _apply_lin(plan, act):
|
||||
"""线性: side/row 结构位 + slide 沿线 1-DOF。几何与 solver 共用
|
||||
_lin_geometry 派生 (文字滑出测量段时尺寸线自动侧延长), 不存在自由文本位。"""
|
||||
dcl = _find_dim(plan, act["name"])
|
||||
key = f"dim:{dcl.caption}"
|
||||
dr = _find_resolved(plan, key).draw
|
||||
p1, p2 = plan.tx(dcl.view, dcl.p1), plan.tx(dcl.view, dcl.p2)
|
||||
vertical = abs(p2[1] - p1[1]) >= abs(p2[0] - p1[0])
|
||||
side = act.get("side", dcl.side or ("right" if vertical else "bottom"))
|
||||
row = act.get("row", dcl.row)
|
||||
slide = float(act.get("slide", 0.0))
|
||||
g = plan._lin_geometry(dcl, side, row, slide, dr["text"])
|
||||
w = _text_width(dr["text"], TEXT_H)
|
||||
segs = [g["line"]] + g["exts"]
|
||||
old = _unregister(plan, key)
|
||||
conf = _conflicts(plan, key, dcl.view, g["center"][0], g["center"][1],
|
||||
w, TEXT_H, g["rot"], segs)
|
||||
if conf and not act.get("force"):
|
||||
_restore(plan, old)
|
||||
return _reject(plan, act, key, dcl.view, conf, g["center"][0],
|
||||
g["center"][1], w, TEXT_H, g["rot"])
|
||||
dr.update(kind="lin", line=g["line"], arrows=g["arrows"], exts=g["exts"],
|
||||
insert=g["insert"], rot=g["rot"])
|
||||
_commit(plan, key, g["center"][0], g["center"][1], w, TEXT_H, g["rot"], segs)
|
||||
_log(plan, key, f"{side} row{row} slide{slide:+g}"
|
||||
+ (" 线延长" if g["extended"] else ""))
|
||||
return {"op": "lin", "element": key, "ok": True,
|
||||
"anchor": [_r(g["center"][0]), _r(g["center"][1])],
|
||||
"rot": _r(g["rot"])}
|
||||
|
||||
|
||||
def _apply_lead(plan, act):
|
||||
"""引出: off=[dx,dy] 文本框相对锚点偏移 (纸面 mm)。路径随框重推。"""
|
||||
dcl = next((d for d in plan.d.leaders
|
||||
if (d.name or d.lines[0][:12]) == act["name"]), None)
|
||||
if dcl is None:
|
||||
raise KeyError(f"leader {act['name']}")
|
||||
key = f"lead:{dcl.name}"
|
||||
dr = _find_resolved(plan, key).draw
|
||||
a = plan.tx(dcl.view, dcl.anchor)
|
||||
w = max(_text_width(t, 2.2) for t in dcl.lines)
|
||||
h = len(dcl.lines) * 4.2 + 1.0
|
||||
off = act.get("off", [dr["text_x"] - a[0], dr["text_y_top"] - a[1]])
|
||||
tx0, ty0 = a[0] + off[0], a[1] + off[1]
|
||||
box = Box(tx0, ty0 - h, tx0 + w, ty0)
|
||||
# 肘点取框顶上方: 多行文本时框中部肘线会划过第二行字高带
|
||||
elb_y = ty0 + 0.8
|
||||
near_x = (box.x0 - 1.2) if dcl.dx_dir < 0 else (box.x1 + 1.2)
|
||||
path = [a, (a[0], elb_y), (near_x, elb_y)]
|
||||
segs = [(path[i], path[i + 1]) for i in range(len(path) - 1)]
|
||||
old = _unregister(plan, key)
|
||||
conf = _conflicts(plan, key, dcl.view, tx0 + w / 2, ty0 - h / 2, w, h, 0.0, segs)
|
||||
if conf and not act.get("force"):
|
||||
_restore(plan, old)
|
||||
return _reject(plan, act, key, dcl.view, conf, tx0 + w / 2, ty0 - h / 2, w, h, 0.0)
|
||||
dr.update(anchor=a, path=path, text_x=tx0, text_y_top=ty0)
|
||||
_commit(plan, key, tx0 + w / 2, ty0 - h / 2, w, h, 0.0, segs)
|
||||
_log(plan, key, f"off=({off[0]:g},{off[1]:g})")
|
||||
return {"op": "lead", "element": key, "ok": True,
|
||||
"anchor": [_r(tx0 + w / 2), _r(ty0 - h / 2)]}
|
||||
|
||||
|
||||
def _apply_accept(plan, act):
|
||||
"""接受某元素的现存冲突并记录理由 —— 显式取舍, 非静默放行。"""
|
||||
if not hasattr(plan, "accepted"):
|
||||
plan.accepted = {}
|
||||
plan.accepted[act["name"]] = act.get("reason", "")
|
||||
plan.rule_log.append(("R1", "accepted",
|
||||
f"{act['name']}: {act.get('reason', '')}"))
|
||||
return {"op": "accept", "element": act["name"], "ok": True}
|
||||
|
||||
|
||||
def _log(plan, key, desc):
|
||||
r = _find_resolved(plan, key)
|
||||
r.resolved = f"agent {desc}"
|
||||
r.adjust.append(f"agent: {desc}")
|
||||
plan.adjust_count += 1
|
||||
|
||||
|
||||
def _cjk_font_path():
|
||||
"""matplotlib 用 CJK 字体全路径 (与 render._cjk_font_name 同一候选序)。"""
|
||||
import glob
|
||||
import os
|
||||
|
||||
want = ("pingfang", "songti", "stheiti", "hiragino", "simsun", "simhei",
|
||||
"msyh", "arial unicode")
|
||||
pats = ["/System/Library/Fonts/PingFang*", "/System/Library/Fonts/Supplemental/*",
|
||||
"/System/Library/Fonts/*", "/Library/Fonts/*.ttf",
|
||||
"C:/Windows/Fonts/sim*.tt?", "C:/Windows/Fonts/msyh*"]
|
||||
for pat in pats:
|
||||
for f in sorted(glob.glob(pat)):
|
||||
low = os.path.basename(f).lower()
|
||||
if any(w in low for w in want) and low.endswith((".ttf", ".ttc", ".otf")):
|
||||
return f
|
||||
return None
|
||||
|
||||
|
||||
def annotate_plan(plan, png_path, ev=None, crop_warn=True):
|
||||
"""冲突可视化: 元素 OBB 打标 + 障碍叠加 (browser-use DOM 打标的制图版)。
|
||||
|
||||
徽标 [N] 对应 evaluate() 输出 elements[N] 的 id, 供 LLM 图文对齐:
|
||||
灰边=ok / 红边红底=warn / 橙=accepted; 蓝=障碍 (bbox 虚线框, 标线实线);
|
||||
黑点线=视图 bbox, 灰细线=视图图线。统一纸面坐标 (mm)。
|
||||
crop_warn=True 时对每个 warn 元素另存局部放大图 `<stem>__<id>.png`
|
||||
(视野 = 元素 OBB ∪ 障碍范围 外扩)。"""
|
||||
from pathlib import Path
|
||||
|
||||
ev = ev or evaluate_plan(plan)
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.patches import Polygon, Rectangle
|
||||
|
||||
from .planner import SheetPlan
|
||||
|
||||
fp = _cjk_font_path()
|
||||
if fp:
|
||||
from matplotlib import font_manager
|
||||
font_manager.fontManager.addfont(fp)
|
||||
plt.rcParams["font.family"] = font_manager.FontProperties(fname=fp).get_name()
|
||||
plt.rcParams["axes.unicode_minus"] = False
|
||||
|
||||
png_path = Path(png_path)
|
||||
fig, ax = plt.subplots(figsize=(16.5, 11.7), dpi=150)
|
||||
|
||||
def draw():
|
||||
for n, vw in plan.views.items():
|
||||
for (x1, y1), (x2, y2) in vw["pairs"]:
|
||||
ax.plot([x1, x2], [y1, y2], color="#999999", lw=0.5, zorder=1)
|
||||
bb = vw["bbox"]
|
||||
ax.add_patch(Rectangle((bb.x0, bb.y0), bb.x1 - bb.x0, bb.y1 - bb.y0,
|
||||
fill=False, ls=":", ec="#444444", lw=0.6,
|
||||
zorder=1))
|
||||
style = {"ok": ("#bbbbbb", None), "unsolved": ("#8888ff", None),
|
||||
"warn": ("#dd0022", "#ff000018"),
|
||||
"accepted": ("#ee8800", "#ff990018")}
|
||||
dirs = {"+x": (1, 0), "-x": (-1, 0), "+y": (0, 1), "-y": (0, -1)}
|
||||
for i, e in enumerate(ev["elements"]):
|
||||
if e.get("anchor") is None:
|
||||
continue
|
||||
cx, cy, w, h, rot = *e["anchor"], e["w"], e["h"], e["rot"]
|
||||
ec, fc = style.get(e["status"], style["ok"])
|
||||
ax.add_patch(Polygon(SheetPlan._obb_corners(cx, cy, w, h, rot),
|
||||
closed=True, fill=fc is not None,
|
||||
facecolor=fc or "none", edgecolor=ec, lw=1.4,
|
||||
zorder=3))
|
||||
ax.text(cx, cy + h / 2 + 1.5, f"[{i}] {e['id']}", color=ec,
|
||||
fontsize=6, ha="center", zorder=4)
|
||||
if e["status"] == "accepted" and e.get("reason"):
|
||||
ax.text(cx, cy - h / 2 - 1.5, "✓ " + e["reason"][:44],
|
||||
color="#ee8800", fontsize=5.2, ha="center", va="top",
|
||||
zorder=4)
|
||||
for v in e.get("violations", []):
|
||||
if "bbox" in v:
|
||||
x0, y0, x1, y1 = v["bbox"]
|
||||
ax.add_patch(Rectangle((x0, y0), x1 - x0, y1 - y0,
|
||||
fill=False, ls="--", ec="#0066ff",
|
||||
lw=1.0, zorder=2))
|
||||
elif "seg" in v:
|
||||
(sx0, sy0), (sx1, sy1) = v["seg"]
|
||||
ax.plot([sx0, sx1], [sy0, sy1], color="#0066ff", lw=1.6,
|
||||
zorder=2)
|
||||
for lbl, d in (e.get("corridors") or {}).items():
|
||||
if d <= 0:
|
||||
continue # 无自由度不画
|
||||
dx, dy = dirs[lbl]
|
||||
ax.annotate("", xy=(cx + dx * d, cy + dy * d), xytext=(cx, cy),
|
||||
arrowprops=dict(arrowstyle="->", color="#009944",
|
||||
lw=0.9), zorder=2)
|
||||
ax.text(cx + dx * d * 0.55, cy + dy * d * 0.55,
|
||||
f"{lbl}{d:g}", color="#009944", fontsize=5.5,
|
||||
ha="center", zorder=4)
|
||||
|
||||
draw()
|
||||
ax.set_aspect("equal")
|
||||
ax.autoscale()
|
||||
ax.set_title(f"{plan.d.title} · 冲突标注: 红=warn 橙=accepted 蓝=障碍 "
|
||||
f"黑点线=视图bbox")
|
||||
ax.set_axis_off()
|
||||
fig.tight_layout()
|
||||
fig.savefig(png_path)
|
||||
|
||||
if crop_warn:
|
||||
dirs = {"+x": (1, 0), "-x": (-1, 0), "+y": (0, 1), "-y": (0, -1)}
|
||||
for e in ev["elements"]:
|
||||
if e["status"] != "warn":
|
||||
continue
|
||||
cx, cy = e["anchor"]
|
||||
xs, ys = [cx], [cy]
|
||||
for v in e.get("violations", []):
|
||||
if "bbox" in v:
|
||||
xs += [v["bbox"][0], v["bbox"][2]]
|
||||
ys += [v["bbox"][1], v["bbox"][3]]
|
||||
elif "seg" in v:
|
||||
xs += [p[0] for p in v["seg"]]
|
||||
ys += [p[1] for p in v["seg"]]
|
||||
for lbl, d in (e.get("corridors") or {}).items():
|
||||
if d > 0: # 走廊箭头纳入视野
|
||||
dx, dy = dirs[lbl]
|
||||
dd = min(d, 25.0)
|
||||
xs.append(cx + dx * dd)
|
||||
ys.append(cy + dy * dd)
|
||||
m = max(15.0, (max(xs) - min(xs)) * 0.35, (max(ys) - min(ys)) * 0.35)
|
||||
ax.set_xlim(min(xs) - m, max(xs) + m)
|
||||
ax.set_ylim(min(ys) - m, max(ys) + m)
|
||||
safe = e["id"].replace("/", "_").replace(":", "_")
|
||||
fig.savefig(png_path.with_name(f"{png_path.stem}__{safe}.png"))
|
||||
plt.close(fig)
|
||||
return ev
|
||||
|
||||
|
||||
_OPS = {"rad": _apply_rad, "dia": _apply_dia, "lin": _apply_lin,
|
||||
"lead": _apply_lead, "accept": _apply_accept}
|
||||
|
||||
|
||||
def apply_actions(plan, actions):
|
||||
results = []
|
||||
for act in actions:
|
||||
fn = _OPS.get(act.get("op"))
|
||||
if fn is None:
|
||||
results.append({"op": act.get("op"), "ok": False,
|
||||
"error": f"未知 op {act.get('op')!r}"})
|
||||
continue
|
||||
try:
|
||||
results.append(fn(plan, act))
|
||||
except KeyError as e:
|
||||
results.append({"op": act.get("op"), "ok": False, "error": str(e)})
|
||||
out = {"results": results, "eval": evaluate_plan(plan)}
|
||||
# agent-in-the-loop: 每次 apply 自动刷新诊断图, 返回文本要求调用方先读图
|
||||
if getattr(plan.d, "diag_png", ""):
|
||||
try:
|
||||
annotate_plan(plan, plan.d.diag_png, out["eval"])
|
||||
out["diag"] = plan.d.diag_png
|
||||
out["instruction"] = ("诊断图已刷新, 提交下一组动作前必读: "
|
||||
"灰=ok 红=warn(先读红) 蓝=障碍 "
|
||||
"绿箭头=元素可滑移方向与距离")
|
||||
except Exception as e: # 诊断失败不阻塞动作结果
|
||||
out["diag_error"] = str(e)
|
||||
return out
|
||||
@@ -0,0 +1,82 @@
|
||||
"""dxf_engine.hlr — OCCT 隐藏线消除投影 (GB/T 4458.1 视图画法)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
from OCP.BRepAdaptor import BRepAdaptor_Curve
|
||||
from OCP.GCPnts import GCPnts_QuasiUniformDeflection
|
||||
from OCP.GeomAbs import GeomAbs_Circle, GeomAbs_Line
|
||||
from OCP.HLRAlgo import HLRAlgo_Projector
|
||||
from OCP.HLRBRep import HLRBRep_Algo, HLRBRep_HLRToShape
|
||||
from OCP.TopAbs import TopAbs_EDGE
|
||||
from OCP.TopExp import TopExp_Explorer
|
||||
from OCP.TopoDS import TopoDS
|
||||
from OCP.gp import gp_Ax2, gp_Dir, gp_Pnt
|
||||
|
||||
DEG = 180.0 / math.pi
|
||||
|
||||
|
||||
def hlr_project(shape, view_dir, x_dir):
|
||||
"""单方向隐藏线消除。返回 (visible_edges, hidden_edges)。
|
||||
|
||||
view_dir: 观察方向朝向物体的轴向; x_dir: 投影面内屏幕右方向。
|
||||
相切过渡线 (Rg1/RgN) 不取 —— 工程图不画光滑缝。
|
||||
"""
|
||||
algo = HLRBRep_Algo()
|
||||
algo.Add(shape)
|
||||
algo.Projector(HLRAlgo_Projector(
|
||||
gp_Ax2(gp_Pnt(0, 0, 0), gp_Dir(*view_dir), gp_Dir(*x_dir))))
|
||||
algo.Update()
|
||||
algo.Hide()
|
||||
hlr = HLRBRep_HLRToShape(algo)
|
||||
|
||||
def _edges(compound):
|
||||
out = []
|
||||
if compound.IsNull():
|
||||
return out
|
||||
exp = TopExp_Explorer(compound, TopAbs_EDGE)
|
||||
while exp.More():
|
||||
out.append(TopoDS.Edge_s(exp.Current()))
|
||||
exp.Next()
|
||||
return out
|
||||
|
||||
return (_edges(hlr.VCompound()) + _edges(hlr.OutLineVCompound()),
|
||||
_edges(hlr.HCompound()) + _edges(hlr.OutLineHCompound()))
|
||||
|
||||
|
||||
def discretize_edge(edge, deflection=0.04):
|
||||
"""边 -> (adaptor, 采样点列)。"""
|
||||
ad = BRepAdaptor_Curve(edge)
|
||||
t0, t1 = ad.FirstParameter(), ad.LastParameter()
|
||||
disc = GCPnts_QuasiUniformDeflection(ad, deflection, t0, t1)
|
||||
pts = []
|
||||
if disc.IsDone():
|
||||
for i in range(1, disc.NbPoints() + 1):
|
||||
p = disc.Value(i)
|
||||
pts.append((p.X(), p.Y()))
|
||||
else:
|
||||
for t in (t0, 0.5 * (t0 + t1), t1):
|
||||
p = ad.Value(t)
|
||||
pts.append((p.X(), p.Y()))
|
||||
dedup = [pts[0]]
|
||||
for q in pts[1:]:
|
||||
if math.dist(q, dedup[-1]) > 1e-6:
|
||||
dedup.append(q)
|
||||
return ad, dedup
|
||||
|
||||
|
||||
def arc_angles(ad, cxy, t0, t1):
|
||||
"""DXF 逆时针弧起止角; 采样中点落在弧段内的角度序为准。"""
|
||||
cx, cy = cxy
|
||||
p0, pm, p1 = ad.Value(t0), ad.Value(t0 + (t1 - t0) * 0.499999), ad.Value(t1)
|
||||
a0 = math.atan2(p0.Y() - cy, p0.X() - cx) * DEG
|
||||
am = math.atan2(pm.Y() - cy, pm.X() - cx) * DEG
|
||||
a1 = math.atan2(p1.Y() - cy, p1.X() - cx) * DEG
|
||||
norm = lambda a: a % 360.0
|
||||
|
||||
def in_arc(beg, end, mid):
|
||||
beg, end, mid = norm(beg), norm(end), norm(mid)
|
||||
return beg <= mid <= end if beg <= end else (mid >= beg or mid <= end)
|
||||
|
||||
a0n, a1n = norm(a0), norm(a1)
|
||||
return (a0n, a1n) if in_arc(a0n, a1n, norm(am)) else (a1n, a0n)
|
||||
@@ -0,0 +1,108 @@
|
||||
"""dxf_engine.model — 标注声明模型。
|
||||
|
||||
标注学分层 (GB/T 4458.4, GB/T 16675.1):
|
||||
基准体系 DatumDecl —— 主基准/辅助基准, 定位尺寸的出发点
|
||||
尺寸语义 DimDecl.kind —— size(定形) / position(定位, 须引用基准) / overall(总体)
|
||||
几何语义 DimDecl.semantic —— linear / diameter / radius
|
||||
参数追溯 covers —— 该尺寸承载哪些模型参数 (参数覆盖追溯 R5)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
@dataclass
|
||||
class ViewDecl:
|
||||
"""HLR 投影视图。n=观察方向, xd=投影面内屏幕右方向; align 定义布局约束。"""
|
||||
name: str
|
||||
shape: object
|
||||
n: tuple
|
||||
xd: tuple
|
||||
align: dict = field(default_factory=dict) # {"to","side","gap"} side: below|right
|
||||
anchor: tuple = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class DimDecl:
|
||||
"""一条尺寸声明。kind=定位(position)尺寸必须在 datum 里引用已声明基准。"""
|
||||
kind: str # size | position | overall
|
||||
view: str
|
||||
semantic: str # linear | diameter | radius
|
||||
caption: str # 参数名 (进入文本 "值 (caption)")
|
||||
value: float = None
|
||||
p1: tuple = None # linear 测量点 (视图局部模型坐标)
|
||||
p2: tuple = None
|
||||
center: tuple = None # dia/rad 圆心
|
||||
radius: float = None
|
||||
at: float = None # dia/rad 方位角
|
||||
datum: str = None # position/size 引用的基准字母
|
||||
side: str = None # bottom/right/left/top
|
||||
row: int = 0 # 期望行 (同侧行距, 碰撞顺延)
|
||||
out: float = 8.0 # dia/rad 文本外伸
|
||||
dec: int = 0
|
||||
prefix: str = ""
|
||||
covers: list = field(default_factory=list) # 承载的模型参数名
|
||||
name: str = ""
|
||||
|
||||
def __post_init__(self):
|
||||
if self.semantic == "linear" and self.kind == "position" and not self.datum:
|
||||
raise ValueError(f"定位尺寸 {self.caption or self.name} 未声明基准")
|
||||
if self.covers and self.caption not in self.covers:
|
||||
self.covers = [self.caption] + list(self.covers)
|
||||
|
||||
|
||||
@dataclass
|
||||
class DatumDecl:
|
||||
"""基准符号声明(GB 基准体系):主基准 A、辅助基准 B/C…。"""
|
||||
letter: str # A(主) B C...
|
||||
kind: str # axis | plane
|
||||
view: str
|
||||
at: tuple # 视图局部模型坐标
|
||||
box_off: tuple = (9.0, 6.0)
|
||||
desc: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class CenterDecl:
|
||||
"""中心线声明:p1/p2 直线中心线,或 arc=(cx,cy,r,a0,a1) 圆弧中心线。"""
|
||||
view: str
|
||||
p1: tuple = None
|
||||
p2: tuple = None
|
||||
arc: tuple = None # (cx, cy, r, a0, a1) 视图局部模型坐标
|
||||
|
||||
|
||||
@dataclass
|
||||
class LeaderDecl:
|
||||
"""引出说明声明:从 anchor 引出折线到注释文本。"""
|
||||
view: str
|
||||
anchor: tuple
|
||||
lines: list
|
||||
off: tuple = (30.0, -18.0)
|
||||
alt_offs: list = field(default_factory=list)
|
||||
dx_dir: float = 1.0
|
||||
name: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class SheetDecl:
|
||||
"""一张图纸的完整声明:图幅信息 + 视图 + 基准 + 尺寸 + 中心线 + 引出说明 + 参数表。
|
||||
|
||||
调用方只声明"要表达什么",不指定任何纸面坐标;布局与标注位置由
|
||||
SheetPlan.solve() 求解。front/anchor 定义主视图锚定,其余视图经
|
||||
ViewDecl.align 相对主视图对正(第一角投影,长对正/高平齐)。
|
||||
"""
|
||||
title: str
|
||||
dwg_no: str
|
||||
scale: float
|
||||
front: str
|
||||
anchor: tuple
|
||||
views: list
|
||||
datums: list = field(default_factory=list)
|
||||
dims: list = field(default_factory=list)
|
||||
centers: list = field(default_factory=list)
|
||||
leaders: list = field(default_factory=list)
|
||||
notes: list = field(default_factory=list)
|
||||
params: dict = field(default_factory=dict)
|
||||
material: str = "PLA-CF / PAHT"
|
||||
notes_zone: tuple = (25.0, 5.0, 232.0, 90.0) # x0,y0,x1,y1 (正序)
|
||||
diag_png: str = "" # 声明后 solve()/apply() 自动刷新冲突诊断图 (agent-in-the-loop)
|
||||
@@ -0,0 +1,769 @@
|
||||
"""dxf_engine.planner — 标注方案求解器。
|
||||
|
||||
标注学 mindset (GB/T 4458.4-2003 / GB/T 16675.1 / GB/T 14691):
|
||||
R1 安全区 文本(OBB)/引线/尺寸线 与 图线/其他标注/禁入区 不冲突 (最少调整)
|
||||
R2 字向 文字平行于尺寸线; 字头朝上(水平)/朝左(竖直); 不倒置
|
||||
R3 30°禁用区 倾斜尺寸线靠近铅垂 ±30° 时给警告 (图17; 竖直 90° 本身合法)
|
||||
R4 行槽 同侧尺寸行距 ROW_PITCH, 声明行优先, 碰撞顺延; 大尺寸在外 (自动)
|
||||
R5 参数覆盖 每个模型参数: 被图形尺寸承载(covers/caption) 或 进入技术要求/参数表
|
||||
R6 基准引用 position 尺寸必须声明 datum; datum 字母必须已声明
|
||||
R7 不重复 同视图同类测量不重复
|
||||
|
||||
旋转文字碰撞用 OBB(分离轴判定), 不用粗糙 AABB。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from .hlr import DEG, arc_angles, discretize_edge, hlr_project
|
||||
from .model import (CenterDecl, DatumDecl, DimDecl, LeaderDecl, SheetDecl,
|
||||
ViewDecl)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Box:
|
||||
x0: float
|
||||
y0: float
|
||||
x1: float
|
||||
y1: float
|
||||
|
||||
def overlaps(self, b: "Box") -> bool:
|
||||
return not (self.x1 < b.x0 or self.x0 > b.x1 or
|
||||
self.y1 < b.y0 or self.y0 > b.y1)
|
||||
|
||||
def inflate(self, d: float) -> "Box":
|
||||
return Box(self.x0 - d, self.y0 - d, self.x1 + d, self.y1 + d)
|
||||
|
||||
|
||||
def _text_width(text, h=3.5):
|
||||
return sum(h * (1.0 if ord(ch) > 0x2E80 else 0.62) for ch in text)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Resolved:
|
||||
"""一个标注元素在纸面上的求解结果:requested(声明值) → resolved(实际位置) +
|
||||
adjust(最少调整顺延记录) + draw(渲染所需的预计算几何) + rules(触发的规则)。"""
|
||||
kind: str
|
||||
name: str
|
||||
view: str
|
||||
requested: str
|
||||
resolved: str
|
||||
adjust: list = field(default_factory=list)
|
||||
draw: dict = field(default_factory=dict)
|
||||
rule: str = ""
|
||||
|
||||
|
||||
DIM_TXT, DIM_ASZ, DIM_EXO, DIM_EXE, DIM_GAP = 3.5, 3.0, 0.75, 2.0, 0.8
|
||||
TEXT_H = DIM_TXT
|
||||
ROW_PITCH, BASE_OFF = 11.0, 8.0
|
||||
|
||||
|
||||
class SheetPlan:
|
||||
"""标注方案求解器:SheetDecl → solve() → resolved/accepted/report() → render()。
|
||||
|
||||
求解流程:视图布局(第一角投影、align 对正) → 基准安放 → 线性尺寸
|
||||
(按视图/侧/行/大外小内排序) → 直径/半径尺寸 → 引出说明 → 参数覆盖检查。
|
||||
所有冲突处理遵循"最少调整":优先顺延候选位置并记入 Resolved.adjust,
|
||||
放不下则记入 R1 警告,绝不静默丢弃。
|
||||
"""
|
||||
|
||||
def __init__(self, decl: SheetDecl):
|
||||
self.d = decl
|
||||
self.s = decl.scale
|
||||
self.views: dict[str, dict] = {}
|
||||
self.resolved: list[Resolved] = []
|
||||
self.text_obbs: list[tuple[str, float, float, float, float, float]] = []
|
||||
self.segments: list[tuple[str, tuple, tuple]] = []
|
||||
self.datum_pos: dict[str, tuple] = {}
|
||||
self.adjust_count = 0
|
||||
self.rule_log: list[tuple[str, str, str]] = []
|
||||
self.coverage: list[tuple[str, str]] = []
|
||||
self._zones: list[Box] = []
|
||||
|
||||
# ---------- 几何基元 ----------
|
||||
def tx(self, view, p):
|
||||
"""视图局部模型坐标 → 纸面坐标(含图纸比例)。"""
|
||||
vw = self.views[view]
|
||||
return (vw["ox"] + p[0] * self.s, vw["oy"] + p[1] * self.s)
|
||||
|
||||
def _prime(self):
|
||||
self._zones = [Box(*self.d.notes_zone), Box(235.0, 5.0, 415.0, 61.0)]
|
||||
|
||||
@staticmethod
|
||||
def _obb_corners(cx, cy, w, h, rot_deg):
|
||||
rr = math.radians(rot_deg)
|
||||
ca, sa = math.cos(rr), math.sin(rr)
|
||||
hw, hh = w / 2.0, h / 2.0
|
||||
return [(cx + ca * sx + sa * sy - sa * 0 - 0, cy + sa * sx - ca * sy)
|
||||
for sx, sy in ((hw, hh), (-hw, hh), (-hw, -hh), (hw, -hh))]
|
||||
|
||||
@staticmethod
|
||||
def _obb_sat(cx, cy, w, h, rot_deg, box: Box) -> bool:
|
||||
"""旋转矩形(OBB) 与 轴对齐盒 分离轴判定。"""
|
||||
rr = math.radians(rot_deg)
|
||||
ca, sa = math.cos(rr), math.sin(rr)
|
||||
axes = ((1.0, 0.0), (0.0, 1.0), (ca, sa), (-sa, ca))
|
||||
corners = SheetPlan._obb_corners(cx, cy, w, h, rot_deg)
|
||||
bxc = [(box.x0, box.y0), (box.x1, box.y0), (box.x1, box.y1), (box.x0, box.y1)]
|
||||
for ax, ay in axes:
|
||||
ovals = [ (x * ax + y * ay) for x, y in corners ]
|
||||
bvals = [ (x * ax + y * ay) for x, y in bxc ]
|
||||
if max(ovals) < min(bvals) or min(ovals) > max(bvals):
|
||||
return False
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _pt_in_obb(px, py, cx, cy, w, h, rot_deg, pad=0.6):
|
||||
rr = math.radians(rot_deg)
|
||||
ca, sa = math.cos(rr), math.sin(rr)
|
||||
dx, dy = px - cx, py - cy
|
||||
lu, lv = dx * ca + dy * sa, -dx * sa + dy * ca
|
||||
return (abs(lu) <= w / 2 + pad) and (abs(lv) <= h / 2 + pad)
|
||||
|
||||
@staticmethod
|
||||
def _obb_obb(cx1, cy1, w1, h1, r1, cx2, cy2, w2, h2, r2):
|
||||
"""两旋转矩形分离轴判定。"""
|
||||
corners1 = SheetPlan._obb_corners(cx1, cy1, w1, h1, r1)
|
||||
corners2 = SheetPlan._obb_corners(cx2, cy2, w2, h2, r2)
|
||||
rr1, rr2 = math.radians(r1), math.radians(r2)
|
||||
axes = [(math.cos(rr1), math.sin(rr1)), (-math.sin(rr1), math.cos(rr1)),
|
||||
(math.cos(rr2), math.sin(rr2)), (-math.sin(rr2), math.cos(rr2)),
|
||||
(1.0, 0.0), (0.0, 1.0)]
|
||||
for ax, ay in axes:
|
||||
v1 = [x * ax + y * ay for x, y in corners1]
|
||||
v2 = [x * ax + y * ay for x, y in corners2]
|
||||
if max(v1) < min(v2) or min(v1) > max(v2):
|
||||
return False
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def _seg_obb(p, q, cx, cy, w, h, rot_deg):
|
||||
n = max(2, int(math.dist(p, q) / 1.5))
|
||||
for i in range(n + 1):
|
||||
t = i / n
|
||||
x = p[0] + (q[0] - p[0]) * t
|
||||
y = p[1] + (q[1] - p[1]) * t
|
||||
if SheetPlan._pt_in_obb(x, y, cx, cy, w, h, rot_deg):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _text_clear(self, key, cx, cy, w, h, rot, skip_view=None) -> list[str]:
|
||||
why = []
|
||||
for z in self._zones:
|
||||
if self._obb_sat(cx, cy, w, h, rot, z.inflate(1.0)):
|
||||
why.append("禁入区")
|
||||
for n, vw in self.views.items():
|
||||
if n != skip_view:
|
||||
if self._obb_sat(cx, cy, w, h, rot, vw["bbox"].inflate(0.5)):
|
||||
why.append(f"视图{n}")
|
||||
for sp, sq in vw["pairs"]:
|
||||
if self._pt_in_obb(sp[0], sp[1], cx, cy, w, h, rot):
|
||||
why.append(f"图线{n}")
|
||||
break
|
||||
for k2, cx2, cy2, w2, h2, r2 in self.text_obbs:
|
||||
if k2 != key and self._obb_obb(cx, cy, w, h, rot,
|
||||
cx2, cy2, w2, h2, r2):
|
||||
why.append(f"文本{k2}")
|
||||
for k2, sp, sq in self.segments:
|
||||
if k2 != key and self._seg_obb(sp, sq, cx, cy, w, h, rot):
|
||||
why.append(f"标线{k2}")
|
||||
return why
|
||||
|
||||
@staticmethod
|
||||
def _seg_hits_box(p, q, box: Box, step=1.5):
|
||||
b = box.inflate(0.6)
|
||||
n = max(2, int(math.dist(p, q) / step))
|
||||
for i in range(n + 1):
|
||||
t = i / n
|
||||
x = p[0] + (q[0] - p[0]) * t
|
||||
y = p[1] + (q[1] - p[1]) * t
|
||||
if b.x0 <= x <= b.x1 and b.y0 <= y <= b.y1:
|
||||
return True
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _seg_cross(p1, q1, p2, q2):
|
||||
l1 = math.dist(p1, q1)
|
||||
n = max(2, int(l1 / 2.0))
|
||||
for i in range(n + 1):
|
||||
t = i / n
|
||||
x = p1[0] + (q1[0] - p1[0]) * t
|
||||
y = p1[1] + (q1[1] - p1[1]) * t
|
||||
b = Box(x - 0.4, y - 0.4, x + 0.4, y + 0.4)
|
||||
if SheetPlan._seg_hits_box(p2, q2, b, step=1.5):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _seg_vs_views(self, seg, skip_view):
|
||||
hits = []
|
||||
for n, vw in self.views.items():
|
||||
if n == skip_view:
|
||||
continue
|
||||
bb = vw["bbox"]
|
||||
if not (min(seg[0][0], seg[1][0]) <= bb.x1 and
|
||||
max(seg[0][0], seg[1][0]) >= bb.x0 and
|
||||
min(seg[0][1], seg[1][1]) <= bb.y1 and
|
||||
max(seg[0][1], seg[1][1]) >= bb.y0):
|
||||
continue
|
||||
for a, b in vw["pairs"]:
|
||||
if self._seg_cross(seg[0], seg[1], a, b):
|
||||
hits.append(n)
|
||||
break
|
||||
return hits
|
||||
|
||||
def _reg_seg(self, key, p, q):
|
||||
self.segments.append((key, p, q))
|
||||
|
||||
# ---------- 视图 ----------
|
||||
def _solve_views(self):
|
||||
by_name = {v.name: v for v in self.d.views}
|
||||
order = [self.d.front] + [v.name for v in self.d.views
|
||||
if v.name != self.d.front]
|
||||
for name in order:
|
||||
v = by_name[name]
|
||||
vis, hid = hlr_project(v.shape, v.n, v.xd)
|
||||
edges, xs, ys = [], [], []
|
||||
for e in vis + hid:
|
||||
ad, pts = discretize_edge(e)
|
||||
if len(pts) >= 2:
|
||||
edges.append((ad, pts, e in vis))
|
||||
xs += [p[0] for p in pts]
|
||||
ys += [p[1] for p in pts]
|
||||
if name == self.d.front:
|
||||
ox, oy = v.anchor
|
||||
how = "声明锚点"
|
||||
else:
|
||||
base = self.views[v.align["to"]]
|
||||
bb = base["bbox"]
|
||||
if v.align["side"] == "below":
|
||||
ox, oy = base["ox"], bb.y0 - v.align["gap"]
|
||||
how = f"长对正 gap{v.align['gap']:g}"
|
||||
else:
|
||||
ox, oy = bb.x1 + v.align["gap"], base["oy"]
|
||||
how = f"高平齐 gap{v.align['gap']:g}"
|
||||
bbox = Box(ox + min(xs) * self.s, oy + min(ys) * self.s,
|
||||
ox + max(xs) * self.s, oy + max(ys) * self.s)
|
||||
pairs = []
|
||||
for ad, pts, _vis in edges:
|
||||
sh = [(p[0] * self.s + ox, p[1] * self.s + oy) for p in pts]
|
||||
pairs.extend(zip(sh, sh[1:]))
|
||||
self.views[name] = {"ox": ox, "oy": oy, "bbox": bbox,
|
||||
"edges": edges, "pairs": pairs, "how": how}
|
||||
self.resolved.append(Resolved(
|
||||
"view", name, name, f"anchor={v.anchor}", f"({ox:.1f},{oy:.1f})",
|
||||
[], {"how": how}))
|
||||
|
||||
# ---------- 文字平行基元 ----------
|
||||
@staticmethod
|
||||
def _text_frame(mid, line_angle_deg, above=1.0, h=TEXT_H, w=0.0):
|
||||
"""文字平行于尺寸线: 旋转归一(不倒置), 基线偏移到'上方'侧
|
||||
(GB 字头朝上/朝左)。返回 (insert, rot, center, aabb)。"""
|
||||
rot = line_angle_deg % 180.0
|
||||
if rot > 90.0:
|
||||
rot -= 180.0
|
||||
rr = math.radians(rot)
|
||||
n = (-math.sin(rr), math.cos(rr))
|
||||
insert = (mid[0] + n[0] * above, mid[1] + n[1] * above)
|
||||
half_h = h * 0.35 # 基线到字形视觉中心
|
||||
cx, cy = mid[0] + n[0] * (above + half_h), mid[1] + n[1] * (above + half_h)
|
||||
ca, sa = math.cos(rr), math.sin(rr)
|
||||
ex = abs(ca) * w / 2 + abs(sa) * h / 2
|
||||
ey = abs(sa) * w / 2 + abs(ca) * h / 2
|
||||
return (insert, rot, (cx, cy), Box(cx - ex, cy - ey, cx + ex, cy + ey))
|
||||
|
||||
def _arrow(self, msp, tip, direction_deg):
|
||||
pass # 渲染阶段实现 (render.py)
|
||||
|
||||
# ---------- 尺寸求解 ----------
|
||||
def _solve_dim(self, dcl: DimDecl):
|
||||
key = f"dim:{dcl.caption}"
|
||||
if dcl.semantic == "linear":
|
||||
self._solve_linear(dcl, self.views[dcl.view], key)
|
||||
elif dcl.semantic == "diameter":
|
||||
self._solve_diameter(dcl, self.views[dcl.view], key)
|
||||
elif dcl.semantic == "radius":
|
||||
self._solve_radius(dcl, self.views[dcl.view], key)
|
||||
|
||||
def _lin_geometry(self, dcl, side, row, slide, text):
|
||||
"""线性尺寸几何派生 (solver 与 agent 动作共用, 一处派生一处真值):
|
||||
尺寸线在视图 bbox 外第 row 行 (side 侧); 文字只有沿尺寸线方向的
|
||||
1 自由度 (slide, 相对测量中点的纸面偏移); 文字滑出测量段时尺寸线
|
||||
**自动侧延长**覆盖全文 (箭头仍指测量点)。"""
|
||||
vw = self.views[dcl.view]
|
||||
bb = vw["bbox"]
|
||||
p1, p2 = self.tx(dcl.view, dcl.p1), self.tx(dcl.view, dcl.p2)
|
||||
dx, dy = p2[0] - p1[0], p2[1] - p1[1]
|
||||
vertical = abs(dy) >= abs(dx)
|
||||
if vertical and p1[1] > p2[1]:
|
||||
p1, p2 = p2, p1 # 方向归一: 自下而上 (字头朝左)
|
||||
if not vertical and p1[0] > p2[0]:
|
||||
p1, p2 = p2, p1
|
||||
w = _text_width(text, TEXT_H)
|
||||
if vertical:
|
||||
xl = (bb.x1 + BASE_OFF + row * ROW_PITCH if side == "right"
|
||||
else bb.x0 - BASE_OFF - row * ROW_PITCH)
|
||||
ymid = (p1[1] + p2[1]) / 2 + slide
|
||||
# insert=基线**下端** (文字沿 +y 向上展开, 与渲染 set_placement 一致);
|
||||
# OBB 中心 = insert + u·(w/2) + n·(0.35h), u=(0,1), n=(-1,0)
|
||||
insert = (xl - 1.0, ymid - w / 2)
|
||||
rot, center = 90.0, (xl - 1.0 - TEXT_H * 0.35, ymid)
|
||||
lo = min(p1[1], insert[1] - 2.0) # 文字滑出 → 侧延长
|
||||
hi = max(p2[1], insert[1] + w + 2.0)
|
||||
line = ((xl, lo), (xl, hi))
|
||||
arrows = ((xl, p1[1]), (xl, p2[1]))
|
||||
exts = [((p1[0], p1[1]), (xl, p1[1])), ((p2[0], p2[1]), (xl, p2[1]))]
|
||||
else:
|
||||
yl = (bb.y0 - BASE_OFF - row * ROW_PITCH if side == "bottom"
|
||||
else bb.y1 + BASE_OFF + row * ROW_PITCH)
|
||||
xmid = (p1[0] + p2[0]) / 2 + slide
|
||||
# insert=基线**左端** (文字沿 +x 展开, 与渲染一致)
|
||||
insert = (xmid - w / 2, yl + 1.0)
|
||||
rot, center = 0.0, (xmid, yl + 1.0 + TEXT_H * 0.35)
|
||||
lo = min(p1[0], insert[0] - 2.0)
|
||||
hi = max(p2[0], insert[0] + w + 2.0)
|
||||
line = ((lo, yl), (hi, yl))
|
||||
arrows = ((p1[0], yl), (p2[0], yl))
|
||||
exts = [((p1[0], p1[1]), (p1[0], yl)), ((p2[0], p2[1]), (p2[0], yl))]
|
||||
return {"kind": "lin", "line": line, "arrows": arrows, "exts": exts,
|
||||
"insert": insert, "rot": rot, "center": center, "text": text,
|
||||
"slide": slide,
|
||||
"extended": (lo < (p1[1] if vertical else p1[0]) - 0.01 or
|
||||
hi > (p2[1] if vertical else p2[0]) + 0.01)}
|
||||
|
||||
def _solve_linear(self, dcl, vw, key):
|
||||
p1, p2 = self.tx(dcl.view, dcl.p1), self.tx(dcl.view, dcl.p2)
|
||||
dx, dy = p2[0] - p1[0], p2[1] - p1[1]
|
||||
vertical = abs(dy) >= abs(dx)
|
||||
side = dcl.side or ("right" if vertical else "bottom")
|
||||
value = dcl.value if dcl.value is not None else math.dist(p1, p2) / self.s
|
||||
vs = f"{value:.{dcl.dec}f}"
|
||||
if "." in vs:
|
||||
vs = vs.rstrip("0").rstrip(".")
|
||||
text = f"{dcl.prefix}{vs} ({dcl.caption})"
|
||||
w = _text_width(text, TEXT_H)
|
||||
span = abs(dy) if vertical else abs(dx)
|
||||
if span >= w + 2.0:
|
||||
# 中点居首 (零位移); 冲突时先滑移 (最小调整), 后顺延行
|
||||
slides = (0.0, w / 2 + 2.0, -(w / 2 + 2.0), w + 6.0, -(w + 6.0))
|
||||
else:
|
||||
# 测量段容不下文字: 直接界外放置 + 尺寸线侧延长 (派生)
|
||||
off = span / 2 + w / 2 + 2.0
|
||||
slides = (off, -off)
|
||||
adjust = []
|
||||
for n_try in range(0, 7):
|
||||
row_i = dcl.row + n_try
|
||||
for slide in slides:
|
||||
g = self._lin_geometry(dcl, side, row_i, slide, text)
|
||||
why = self._text_clear(key, g["center"][0], g["center"][1],
|
||||
w, TEXT_H, g["rot"],
|
||||
skip_view=dcl.view)
|
||||
# 尺寸线/界线允许压中心线; 但不压他视图图线
|
||||
seg_bad = []
|
||||
for seg in [g["line"]] + g["exts"]:
|
||||
seg_bad += self._seg_vs_views(seg, dcl.view)
|
||||
if seg_bad:
|
||||
why.append(f"线穿视图{'+'.join(seg_bad)}")
|
||||
if not why:
|
||||
notes = []
|
||||
if n_try:
|
||||
notes.append(f"R1 行顺延 row{row_i}")
|
||||
if slide:
|
||||
notes.append(f"文字沿线滑移 {slide:+g}")
|
||||
if g["extended"]:
|
||||
notes.append("尺寸线侧延长")
|
||||
adjust += notes
|
||||
self.adjust_count += len(notes)
|
||||
self.text_obbs.append((key, g["center"][0], g["center"][1],
|
||||
w, TEXT_H, g["rot"]))
|
||||
for sg in [g["line"]] + g["exts"]:
|
||||
self._reg_seg(key, *sg)
|
||||
res = f"{side} row{row_i}"
|
||||
if slide or g["extended"]:
|
||||
res += f" slide{slide:+g}" + (" 延长" if g["extended"] else "")
|
||||
self.resolved.append(Resolved(
|
||||
"dim", dcl.caption, dcl.view,
|
||||
f"{side} row{dcl.row}", res, adjust,
|
||||
{k: g[k] for k in ("kind", "line", "arrows", "exts",
|
||||
"insert", "rot", "text",
|
||||
"extended")},
|
||||
"R2/R4"))
|
||||
return
|
||||
adjust.append(f"R1 冲突@row{row_i}({why[0] if why else '线穿视图'})")
|
||||
self.adjust_count += 1
|
||||
self.resolved.append(Resolved(
|
||||
"dim", dcl.caption, dcl.view, f"{side} row{dcl.row}",
|
||||
f"{side} row{dcl.row}", adjust, {"kind": "lin", "text": text},
|
||||
"R1/R4"))
|
||||
|
||||
def _solve_diameter(self, dcl, vw, key):
|
||||
"""直径标注 (GB/T 4458.4 图10): 尺寸线过圆心, 双箭头贴圆; at 定向后
|
||||
文字沿直径线 1-DOF (缺省 0.75r 处, 冲突时换位候选), 基线恒在线上方;
|
||||
m1/m2 恒在圆周。"""
|
||||
s = self.s
|
||||
c = self.tx(dcl.view, dcl.center)
|
||||
r = dcl.radius * s
|
||||
u = (math.cos(math.radians(dcl.at)), math.sin(math.radians(dcl.at)))
|
||||
value = dcl.value if dcl.value is not None else 2 * dcl.radius
|
||||
vs = f"{value:.{dcl.dec}f}"
|
||||
if "." in vs:
|
||||
vs = vs.rstrip("0").rstrip(".")
|
||||
text = f"⌀{vs} ({dcl.caption})"
|
||||
w = _text_width(text, TEXT_H)
|
||||
m1 = (c[0] + r * u[0], c[1] + r * u[1])
|
||||
m2 = (c[0] - r * u[0], c[1] - r * u[1])
|
||||
line = (m1, m2)
|
||||
rot = (dcl.at % 180.0 + 180.0) % 180.0
|
||||
if rot > 90.0:
|
||||
rot -= 180.0
|
||||
rr = math.radians(rot)
|
||||
n = (-math.sin(rr), math.cos(rr))
|
||||
w2 = _text_width(text, TEXT_H)
|
||||
|
||||
def _anchor_at(uu):
|
||||
"""文字基线左端 (0.75r 处线上方) 与 OBB 中心。"""
|
||||
ins = (c[0] + 0.75 * r * uu[0] + n[0] * 1.0,
|
||||
c[1] + 0.75 * r * uu[1] + n[1] * 1.0)
|
||||
ctr = (ins[0] + uu[0] * w2 / 2 + n[0] * TEXT_H * 0.35,
|
||||
ins[1] + uu[1] * w2 / 2 + n[1] * TEXT_H * 0.35)
|
||||
return ins, ctr
|
||||
|
||||
insert, anchor = _anchor_at(u)
|
||||
why = self._text_clear(key, anchor[0], anchor[1], w2, TEXT_H, rot,
|
||||
skip_view=dcl.view)
|
||||
adjust = []
|
||||
if why:
|
||||
for k in range(1, 4):
|
||||
aa = dcl.at + 180.0 * (k % 2) + (12.0 * ((k + 1) // 2)) * (
|
||||
1 if k <= 2 else -1)
|
||||
uu = (math.cos(math.radians(aa)), math.sin(math.radians(aa)))
|
||||
a2, c2 = _anchor_at(uu)
|
||||
rrot = (aa % 180.0 + 180.0) % 180.0
|
||||
rrot = rrot - 180.0 if rrot > 90.0 else rrot
|
||||
if not self._text_clear(key, c2[0], c2[1], w2, TEXT_H, rrot,
|
||||
skip_view=dcl.view):
|
||||
insert, anchor, u = a2, c2, uu
|
||||
rot = rrot
|
||||
adjust.append(f"换位 {aa:g}°")
|
||||
self.adjust_count += 1
|
||||
break
|
||||
else:
|
||||
adjust.append("R1 警告: 文本留于原位")
|
||||
self.adjust_count += 1
|
||||
self.text_obbs.append((key, anchor[0], anchor[1], w2, TEXT_H, rot))
|
||||
for sg in (line, (m1, insert)):
|
||||
self._reg_seg(key, *sg)
|
||||
draw = {"kind": "dia-man", "m1": m1, "m2": m2, "insert": insert,
|
||||
"anchor": anchor, "text": text, "rot": rot}
|
||||
self.resolved.append(Resolved("dim", dcl.caption, dcl.view,
|
||||
f"at {dcl.at:g}°", f"rot {rot:g}° 75%r",
|
||||
adjust, draw, "R2/R5"))
|
||||
|
||||
# ---------- 引出 ----------
|
||||
def _solve_leaders(self):
|
||||
for dcl in self.d.leaders:
|
||||
a = self.tx(dcl.view, dcl.anchor)
|
||||
w = max(_text_width(t, 2.2) for t in dcl.lines)
|
||||
h = len(dcl.lines) * 4.2 + 1.0
|
||||
bbv = self.views[dcl.view]["bbox"]
|
||||
side = -1.0 if (a[0] - bbv.x0) < (bbv.x1 - a[0]) else 1.0
|
||||
cands = [dcl.off] + list(dcl.alt_offs)
|
||||
for k in range(1, 6):
|
||||
cands.append((dcl.off[0] + side * (18.0 * k),
|
||||
dcl.off[1] - 8.0 * k))
|
||||
final = None
|
||||
adjust = []
|
||||
for ci, off in enumerate(cands):
|
||||
tx0 = a[0] + off[0]
|
||||
ty0 = a[1] + off[1]
|
||||
box = Box(tx0, ty0 - h, tx0 + w, ty0)
|
||||
# 肘点取框顶上方: 多行文本时框中部肘线会划过第二行字高带
|
||||
elb_y = ty0 + 0.8
|
||||
near_x = (box.x0 - 1.2) if dcl.dx_dir < 0 else (box.x1 + 1.2)
|
||||
path = [a, (a[0], elb_y), (near_x, elb_y)]
|
||||
why = []
|
||||
for z in self._zones:
|
||||
if box.overlaps(z.inflate(1.0)):
|
||||
why.append("禁入区")
|
||||
if any(box.overlaps(v["bbox"]) for n, v in self.views.items()
|
||||
if n != dcl.view):
|
||||
why.append("压他视图bbox")
|
||||
for sp, sq in zip(path, path[1:]):
|
||||
vh = self._seg_vs_views((sp, sq), dcl.view)
|
||||
if vh:
|
||||
mid = ((sp[0] + sq[0]) / 2, (sp[1] + sq[1]) / 2)
|
||||
if math.dist(a, mid) > 15.0:
|
||||
why.append(f"引线穿{'+'.join(vh)}")
|
||||
|
||||
for kk, cx2, cy2, w2, h2, r2 in self.text_obbs:
|
||||
if f"lead:{dcl.name}" != kk and self._obb_obb(
|
||||
tx0, ty0 - h / 2, w, h, 0.0,
|
||||
cx2, cy2, w2, h2, r2):
|
||||
why.append(f"文本{kk}")
|
||||
for i in range(len(path) - 1):
|
||||
seg = (path[i], path[i + 1])
|
||||
for k2, cx2, cy2, w2, h2, r2 in self.text_obbs:
|
||||
if self._seg_obb(seg[0], seg[1], cx2, cy2, w2, h2, r2):
|
||||
why.append(f"引线压文本{k2}")
|
||||
for i in range(len(path) - 1):
|
||||
seg = (path[i], path[i + 1])
|
||||
for k2, sp2, sq2 in self.segments:
|
||||
if k2 != f"lead:{dcl.name}" and \
|
||||
self._seg_cross(*seg, sp2, sq2):
|
||||
why.append(f"标线{k2}")
|
||||
if not why:
|
||||
final = (off, box, path)
|
||||
if ci:
|
||||
adjust.append(f"换位×{ci}")
|
||||
self.adjust_count += 1
|
||||
break
|
||||
if final is None:
|
||||
off = dcl.off
|
||||
box = Box(a[0] + off[0], a[1] + off[1] - h,
|
||||
a[0] + off[0] + w, a[1] + off[1])
|
||||
path = [a, (a[0] + dcl.dx_dir * 12.0, box.y1 + 0.8),
|
||||
(box.x0 - 1.2 if dcl.dx_dir < 0 else box.x1 + 1.2,
|
||||
box.y1 + 0.8)]
|
||||
adjust.append("未找到空位 (警告)")
|
||||
self.adjust_count += 1
|
||||
else:
|
||||
off, box, path = final
|
||||
self.text_obbs.append((f"lead:{dcl.name}",
|
||||
(box.x0 + box.x1) / 2,
|
||||
(box.y0 + box.y1) / 2, w, h, 0.0))
|
||||
for i in range(len(path) - 1):
|
||||
self._reg_seg(f"lead:{dcl.name}", path[i], path[i + 1])
|
||||
self.resolved.append(Resolved(
|
||||
"leader", dcl.name or dcl.lines[0][:12], dcl.view,
|
||||
f"off={dcl.off}", f"off={tuple(round(v, 1) for v in off)}",
|
||||
adjust, {"anchor": a, "path": path, "lines": dcl.lines,
|
||||
"text_x": box.x0, "text_y_top": box.y1}))
|
||||
|
||||
# ---------- 覆盖 / 规则 ----------
|
||||
def _solve_coverage_rules(self):
|
||||
P = self.d.params
|
||||
for k in P:
|
||||
where = None
|
||||
for r in self.resolved:
|
||||
if r.kind != "dim":
|
||||
continue
|
||||
txt = r.draw.get("text", "")
|
||||
for dcl in self.d.dims:
|
||||
if dcl.caption == r.name and (
|
||||
k in dcl.covers or k == dcl.caption or
|
||||
f"({k})" in txt):
|
||||
where = f"{txt}@{r.view}"
|
||||
break
|
||||
if where:
|
||||
break
|
||||
if where is None:
|
||||
for i, nt in enumerate(self.d.notes):
|
||||
if k in nt:
|
||||
where = f"notes[{i + 1}]"
|
||||
break
|
||||
if where is None:
|
||||
where = "参数表" # 图纸右下参数表逐项列出, 视为已覆盖
|
||||
self.coverage.append((k, where))
|
||||
self.rule_log.append(("R5", "ok", f"{k}: {where}"))
|
||||
letters = {d.letter for d in self.d.datums}
|
||||
for dcl in self.d.dims:
|
||||
if dcl.datum and dcl.datum not in letters:
|
||||
self.rule_log.append(("R6", "fail",
|
||||
f"{dcl.caption} 引用未声明基准 {dcl.datum}"))
|
||||
for r in self.resolved:
|
||||
if r.kind == "dim" and "rot" in r.draw:
|
||||
rot = abs(r.draw["rot"]) % 180.0
|
||||
if (60.0 < rot < 90.0) or (90.0 < rot < 120.0):
|
||||
self.rule_log.append(("R3", "warn",
|
||||
f"{r.name}: 文字旋回 {rot:g}° "
|
||||
"近铅垂禁用区"))
|
||||
|
||||
# ---------- 总规划 ----------
|
||||
def solve(self):
|
||||
"""执行完整求解并返回 self。求解后经 resolved/accepted/report() 审计,
|
||||
再由 render() 出图。重复调用会重置重新求解。"""
|
||||
self._prime()
|
||||
self._solve_views()
|
||||
self._solve_datums()
|
||||
lin = sorted([x for x in self.d.dims if x.semantic == "linear"],
|
||||
key=lambda x: (x.view, x.side or "",
|
||||
x.row, -abs(x.value or 0)))
|
||||
for dcl in lin:
|
||||
self._solve_dim(dcl)
|
||||
for dcl in [x for x in self.d.dims if x.semantic != "linear"]:
|
||||
self._solve_dim(dcl)
|
||||
self._solve_leaders()
|
||||
self._solve_coverage_rules()
|
||||
self._auto_diag()
|
||||
return self
|
||||
|
||||
def _auto_diag(self):
|
||||
"""diag_png 声明后: 每次 solve()/apply() 自动刷新冲突诊断图。
|
||||
视觉反馈是 agent-in-the-loop 的一等通道 —— 调用方读图决策, 引擎只供真值。"""
|
||||
if not getattr(self.d, "diag_png", ""):
|
||||
return
|
||||
try:
|
||||
from .agent import annotate_plan, evaluate_plan
|
||||
annotate_plan(self, self.d.diag_png, evaluate_plan(self))
|
||||
except Exception as e: # 诊断失败不阻塞求解, 如实入日志
|
||||
self.rule_log.append(("R1", "warn", f"诊断图渲染失败: {e}"))
|
||||
|
||||
def _solve_datums(self):
|
||||
for dcl in self.d.datums:
|
||||
at = self.tx(dcl.view, dcl.at)
|
||||
bc = (at[0] + dcl.box_off[0], at[1] + dcl.box_off[1])
|
||||
box = Box(bc[0] - 3, bc[1] - 2.2, bc[0] + 3, bc[1] + 2.2)
|
||||
self.datum_pos[dcl.letter] = at
|
||||
why = self._text_clear(f"datum:{dcl.letter}", bc[0], bc[1],
|
||||
6.0, 4.4, 0.0, skip_view=dcl.view)
|
||||
adjust = []
|
||||
if why:
|
||||
bc = (bc[0], bc[1] - 6.0)
|
||||
adjust.append("下移避让")
|
||||
self.text_obbs.append((f"datum:{dcl.letter}",
|
||||
bc[0], bc[1], 6.0, 4.4, 0.0))
|
||||
self.resolved.append(Resolved(
|
||||
"datum", dcl.letter, dcl.view, f"at {dcl.at}",
|
||||
f"box@({bc[0]:.1f},{bc[1]:.1f})", adjust,
|
||||
{"at": at, "bc": bc, "kind": dcl.kind, "desc": dcl.desc},
|
||||
"R6"))
|
||||
|
||||
def report(self) -> str:
|
||||
"""输出可审计的求解报告:基准体系、每个元素的 requested→resolved 与调整、
|
||||
参数覆盖 (R5) 表、规则检查 (R1-R7) 结果。生成图纸后必须审阅。"""
|
||||
lines = [f"── 标注方案报告 · {self.d.title} ({self.d.dwg_no}, "
|
||||
f"比例 {self.d.scale:g}:1) ──"]
|
||||
lines.append("基准体系: " + "; ".join(
|
||||
f"{d.letter}={d.desc or d.kind}" for d in self.d.datums))
|
||||
for r in self.resolved:
|
||||
flag = " · ".join(r.adjust) if r.adjust else "ok"
|
||||
lines.append(f"{r.kind:<7} {r.name:<14} [{r.view:<5}] "
|
||||
f"{r.requested:<22} → {r.resolved:<26} [{flag}]")
|
||||
lines.append("── 参数覆盖 (R5) ──")
|
||||
for k, where in self.coverage:
|
||||
mark = "ok" if where != "未覆盖!" else "MISS"
|
||||
lines.append(f" {k:<18} → {where:<26} [{mark}]")
|
||||
lines.append("── 规则检查 ──")
|
||||
seen = {}
|
||||
for rl, st, dt in self.rule_log:
|
||||
seen.setdefault(rl, []).append((st, dt))
|
||||
for rl in ("R1", "R2", "R3", "R4", "R5", "R6", "R7"):
|
||||
entries = seen.get(rl)
|
||||
if not entries:
|
||||
lines.append(f" {rl}: ok")
|
||||
elif all(st == "ok" for st, _ in entries):
|
||||
lines.append(f" {rl}: ok ({len(entries)})")
|
||||
else:
|
||||
bad = [dt for st, dt in entries if st != "ok"]
|
||||
lines.append(f" {rl}: 警告 {len(bad)} 项: " + "; ".join(bad[:4]))
|
||||
lines.append(f"调整合计: {self.adjust_count}")
|
||||
if getattr(self.d, "diag_png", ""):
|
||||
lines.append(f"诊断图 DIAG: {self.d.diag_png}")
|
||||
lines.append(" ↑ 每次 solve/apply 自动刷新; 下一步决策前必读 —— "
|
||||
"灰=ok 红=warn(先读红) 蓝=障碍 绿箭头=元素可滑移方向与距离")
|
||||
return "\n".join(lines)
|
||||
|
||||
def render(self, dxf_path, png_path):
|
||||
"""按求解结果渲染 DXF + PNG 双产物(委托 render_plan)。"""
|
||||
from .render import render_plan
|
||||
return render_plan(self, dxf_path, png_path)
|
||||
|
||||
# ---------- LLM-in-the-loop 评估/执行 (agent.py 承载) ----------
|
||||
def evaluate(self):
|
||||
"""结构化冲突报告: 每元素 violations(精确障碍数据)+corridors(自由走廊)。"""
|
||||
from .agent import evaluate_plan
|
||||
return evaluate_plan(self)
|
||||
|
||||
def apply(self, actions):
|
||||
"""执行 LLM 动作序列 (rad/dia/lin/lead/accept), 逐条校验, 拒绝即回滚。"""
|
||||
from .agent import apply_actions
|
||||
return apply_actions(self, actions)
|
||||
|
||||
def _solve_radius(self, dcl, vw, key):
|
||||
"""半径标注 (GB/T 4458.4): 声明只给 at(方位角)。定角后文字仅剩沿引线方向
|
||||
的单一自由度 (起点 s, 引擎按候选搜索), 基线恒在线上方 1mm (法向 n),
|
||||
引线长度 = s+字宽+余量 **派生** —— 文字滑出箭头段时线自动侧延长盖住全文;
|
||||
mpt 恒在圆周 (箭头贴弧), rot 恒等于线向 (R2, 不可声明/覆盖)。"""
|
||||
s = self.s
|
||||
c = self.tx(dcl.view, dcl.center)
|
||||
r = dcl.radius * s
|
||||
u = (math.cos(math.radians(dcl.at)), math.sin(math.radians(dcl.at)))
|
||||
value = dcl.value if dcl.value is not None else dcl.radius
|
||||
text = f"R{value:g} ({dcl.caption})"
|
||||
w = _text_width(text, TEXT_H)
|
||||
rot = (dcl.at % 180.0 + 180.0) % 180.0
|
||||
if rot > 90.0:
|
||||
rot -= 180.0 # 正立化
|
||||
rr = math.radians(rot)
|
||||
n = (-math.sin(rr), math.cos(rr))
|
||||
mpt = (c[0] + r * u[0], c[1] + r * u[1]) # 弧上箭头点
|
||||
adjust = []
|
||||
chosen = None
|
||||
# 候选序: 弧外侧引出 (3,9,...) → 弧内侧 (s<0, 文字沿过圆心的尺寸线置于
|
||||
# 圆内, 箭头自圆心侧指向圆弧) —— GB/T 4458.4 半径尺寸线可过圆心。
|
||||
# 内侧候选递进加深: 圆心近障碍时浅位仍探出, 需过心更远的深位。
|
||||
cands = (tuple(3.0 + 6.0 * k for k in range(5))
|
||||
+ (-(w + 4.0), -(w + 10.0), -(w + 18.0)))
|
||||
for s0 in cands: # 文字起点 (1-DOF)
|
||||
inner = (s0 + w) < 0.0 # 内侧: 文字整段在圆内
|
||||
tail_k = s0 - 1.5 if inner else s0 + w + 1.5 # 引线派生长度
|
||||
insert = (mpt[0] + s0 * u[0] + n[0] * 1.0, # 基线左端: 线上方 1mm
|
||||
mpt[1] + s0 * u[1] + n[1] * 1.0)
|
||||
anchor = (insert[0] + u[0] * w / 2 + n[0] * TEXT_H * 0.35,
|
||||
insert[1] + u[1] * w / 2 + n[1] * TEXT_H * 0.35)
|
||||
tail = (mpt[0] + tail_k * u[0], mpt[1] + tail_k * u[1])
|
||||
why = []
|
||||
for z in self._zones:
|
||||
if self._obb_sat(anchor[0], anchor[1], w, TEXT_H, rot,
|
||||
z.inflate(1.0)):
|
||||
why.append("禁入区")
|
||||
for n_v, vwb in self.views.items():
|
||||
if n_v != dcl.view and self._obb_sat(
|
||||
anchor[0], anchor[1], w, TEXT_H, rot,
|
||||
vwb["bbox"].inflate(0.5)):
|
||||
why.append(f"视图{n_v}")
|
||||
for kk, cx2, cy2, w2, h2, r2 in self.text_obbs:
|
||||
if kk != key and self._obb_obb(anchor[0], anchor[1], w, TEXT_H,
|
||||
rot, cx2, cy2, w2, h2, r2):
|
||||
why.append(f"文本{kk.split(':')[-1]}")
|
||||
for k2, sp2, sq2 in self.segments:
|
||||
if k2.startswith("cl:") or k2 == key:
|
||||
continue # 与中心线相交属正常
|
||||
if (self._seg_cross(mpt, tail, sp2, sq2)
|
||||
or self._seg_obb(sp2, sq2, anchor[0], anchor[1],
|
||||
w, TEXT_H, rot)):
|
||||
why.append(f"标线{k2}")
|
||||
if not why:
|
||||
chosen = (s0, tail, insert, anchor, inner)
|
||||
if s0 != 3.0:
|
||||
where = "弧内" if inner else "弧外"
|
||||
adjust.append(f"文字滑移 {where} s={s0:g}")
|
||||
self.adjust_count += 1
|
||||
break
|
||||
adjust.append(f"R1 冲突@{s0:g}({why[0]})")
|
||||
if chosen is None:
|
||||
s0, inner = 15.0, False
|
||||
tail_k = s0 + w + 1.5
|
||||
insert = (mpt[0] + s0 * u[0] + n[0] * 1.0,
|
||||
mpt[1] + s0 * u[1] + n[1] * 1.0)
|
||||
anchor = (insert[0] + u[0] * w / 2 + n[0] * TEXT_H * 0.35,
|
||||
insert[1] + u[1] * w / 2 + n[1] * TEXT_H * 0.35)
|
||||
tail = (mpt[0] + tail_k * u[0], mpt[1] + tail_k * u[1])
|
||||
chosen = (s0, tail, insert, anchor, inner)
|
||||
adjust.append("R1 未找到理想位 (警告)")
|
||||
self.adjust_count += 1
|
||||
s0, tail, insert, anchor, inner = chosen
|
||||
self.text_obbs.append((key, anchor[0], anchor[1], w, TEXT_H, rot))
|
||||
self._reg_seg(key, mpt, tail)
|
||||
# 外侧: 箭头自外指向圆弧; 内侧: 箭头自圆心侧指向圆弧
|
||||
arrow_deg = math.degrees(math.atan2(u[1], u[0]))
|
||||
if not inner:
|
||||
arrow_deg += 180.0
|
||||
draw = {"kind": "rad-man", "mpt": mpt, "tail": tail, "insert": insert,
|
||||
"anchor": anchor, "text": text, "rot": rot,
|
||||
"arrow_deg": arrow_deg}
|
||||
self.resolved.append(Resolved("dim", dcl.caption, dcl.view,
|
||||
f"at {dcl.at:g}°",
|
||||
f"{'弧内' if inner else '弧外'} s={s0:g}",
|
||||
adjust, draw, "R2/R5"))
|
||||
@@ -0,0 +1,301 @@
|
||||
"""dxf_engine.render — 手工基元渲染: 图线/箭头/旋转文字 → DXF + PNG。
|
||||
|
||||
GB/T 4458.4 基元:
|
||||
尺寸线/尺寸界线 细实线
|
||||
轮廓线 粗实线 (b=0.5)
|
||||
虚线/中心线 细虚线 / 细点画线
|
||||
箭头 实心三角 (长约 6b)
|
||||
文字 平行于尺寸线, 字头朝上/朝左 (旋转归一)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import time
|
||||
|
||||
import ezdxf
|
||||
from OCP.GeomAbs import GeomAbs_Circle, GeomAbs_Line
|
||||
from pathlib import Path
|
||||
|
||||
from .planner import TEXT_H
|
||||
|
||||
_LAYERS = [
|
||||
("01粗实线", 7, "Continuous", 50),
|
||||
("08虚线", 3, "DASHED_GB", 25),
|
||||
("05中心线", 1, "CENTER_GB", 25),
|
||||
("01细实线", 7, "Continuous", 25),
|
||||
("尺寸标注", 7, "Continuous", 25),
|
||||
("文字", 7, "Continuous", 25),
|
||||
]
|
||||
|
||||
|
||||
def _cjk_font_name() -> str:
|
||||
import glob
|
||||
import os
|
||||
|
||||
pats = ["/System/Library/Fonts/*PingFang*", "/System/Library/Fonts/Supplemental/*",
|
||||
"/System/Library/Fonts/*", "/Library/Fonts/*.ttf",
|
||||
"C:/Windows/Fonts/sim*.tt?", "C:/Windows/Fonts/msyh*"]
|
||||
want = ("pingfang", "songti", "stheiti", "hiragino", "simsun", "simhei",
|
||||
"msyh", "arial unicode")
|
||||
seen = []
|
||||
for pat in pats:
|
||||
for f in glob.glob(pat):
|
||||
low = os.path.basename(f).lower()
|
||||
seen.append(low)
|
||||
if any(w in low for w in want) and low.endswith((".ttf", ".ttc", ".otf")):
|
||||
return low
|
||||
return next(iter(seen), "txt")
|
||||
|
||||
|
||||
def _arrow(msp, tip, direction_deg, layer="尺寸标注", length=3.0, width=1.15):
|
||||
a = math.radians(direction_deg)
|
||||
ux, uy = math.cos(a), math.sin(a)
|
||||
px, py = -uy, ux
|
||||
b1 = (tip[0] - ux * length + px * width / 2,
|
||||
tip[1] - uy * length + py * width / 2)
|
||||
b2 = (tip[0] - ux * length - px * width / 2,
|
||||
tip[1] - uy * length - py * width / 2)
|
||||
msp.add_solid([tip, b1, b2], dxfattribs={"layer": layer})
|
||||
|
||||
|
||||
def _seg(msp, p, q, layer):
|
||||
msp.add_line(p, q, dxfattribs={"layer": layer})
|
||||
|
||||
|
||||
def _poly(msp, pts, layer, closed=False):
|
||||
msp.add_lwpolyline(list(pts), format="xy",
|
||||
dxfattribs={"layer": layer, "closed": closed})
|
||||
|
||||
|
||||
def _draw_view_edges(msp, plan, view):
|
||||
from .hlr import arc_angles
|
||||
ox, oy, s = view["ox"], view["oy"], plan.s
|
||||
for ad, pts, visible in view["edges"]:
|
||||
if len(pts) < 2:
|
||||
continue
|
||||
layer = "01粗实线" if visible else "08虚线"
|
||||
g = ad.GetType()
|
||||
if g == GeomAbs_Line:
|
||||
(x0, y0), (x1, y1) = pts[0], pts[-1]
|
||||
msp.add_line((x0 * s + ox, y0 * s + oy), (x1 * s + ox, y1 * s + oy),
|
||||
dxfattribs={"layer": layer})
|
||||
elif g == GeomAbs_Circle:
|
||||
circ = ad.Circle()
|
||||
c = circ.Location()
|
||||
cx, cy, rr = c.X(), c.Y(), circ.Radius()
|
||||
if abs(circ.Axis().Direction().Z()) < 0.999:
|
||||
_poly(msp, [(p[0] * s + ox, p[1] * s + oy) for p in pts], layer)
|
||||
else:
|
||||
q0 = ad.Value(ad.FirstParameter())
|
||||
q1 = ad.Value(ad.LastParameter())
|
||||
closed = math.hypot(q0.X() - q1.X(), q0.Y() - q1.Y()) < 1e-6
|
||||
if closed:
|
||||
msp.add_circle((cx * s + ox, cy * s + oy), rr * s,
|
||||
dxfattribs={"layer": layer})
|
||||
else:
|
||||
a0, a1 = arc_angles(ad, (cx, cy),
|
||||
ad.FirstParameter(), ad.LastParameter())
|
||||
msp.add_arc((cx * s + ox, cy * s + oy), rr * s, a0, a1,
|
||||
dxfattribs={"layer": layer})
|
||||
else:
|
||||
_poly(msp, [(p[0] * s + ox, p[1] * s + oy) for p in pts], layer)
|
||||
|
||||
|
||||
def _rot_text(msp, text, insert, rot, layer="文字", h=TEXT_H, style="CJK"):
|
||||
msp.add_text(text, dxfattribs={"layer": layer, "style": style,
|
||||
"height": h, "rotation": rot}
|
||||
).set_placement(insert)
|
||||
|
||||
|
||||
def _render_dim(msp, r):
|
||||
dr = r.draw
|
||||
if not dr.get("text"):
|
||||
return
|
||||
if dr["kind"] == "lin":
|
||||
for sp, sq in dr["exts"]:
|
||||
_seg(msp, sp, sq, "尺寸标注")
|
||||
_seg(msp, dr["line"][0], dr["line"][1], "尺寸标注")
|
||||
for tip, ddeg in ((dr["arrows"][0], dr["rot"] + 180.0),
|
||||
(dr["arrows"][1], dr["rot"])):
|
||||
_arrow(msp, tip, ddeg)
|
||||
_rot_text(msp, dr["text"], dr["insert"], dr["rot"], layer="文字")
|
||||
elif dr["kind"] == "dia-man":
|
||||
m1, m2 = dr["m1"], dr["m2"]
|
||||
_seg(msp, m1, m2, "尺寸标注")
|
||||
for tip, ref in ((m1, m2), (m2, m1)):
|
||||
dv = (ref[0] - tip[0], ref[1] - tip[1])
|
||||
ln = math.hypot(*dv)
|
||||
_arrow(msp, tip, math.degrees(math.atan2(dv[1], dv[0])))
|
||||
_rot_text(msp, dr["text"], dr["insert"], dr["rot"], layer="文字")
|
||||
elif dr["kind"] == "rad-man":
|
||||
_seg(msp, dr["mpt"], dr["tail"], "尺寸标注")
|
||||
_arrow(msp, dr["mpt"], dr["arrow_deg"])
|
||||
_rot_text(msp, dr["text"], dr["insert"], dr["rot"], layer="文字")
|
||||
|
||||
|
||||
def _render_leader(msp, r):
|
||||
dr = r.draw
|
||||
a, path, lines = dr["anchor"], dr["path"], dr["lines"]
|
||||
for i in range(len(path) - 1):
|
||||
_seg(msp, path[i], path[i + 1], "尺寸标注")
|
||||
arrow_at = path[0] if r.adjust else path[0]
|
||||
dv = (path[1][0] - path[0][0], path[1][1] - path[0][1])
|
||||
ln = math.hypot(*dv) or 1.0
|
||||
tip = (path[0][0] + dv[0] / ln * 2.2, path[0][1] + dv[1] / ln * 2.2)
|
||||
_arrow(msp, tip, math.degrees(math.atan2(-dv[1], -dv[0])))
|
||||
ty = dr["text_y_top"] - 2.4
|
||||
for line in lines:
|
||||
msp.add_text(line, dxfattribs={"layer": "文字", "style": "CJK",
|
||||
"height": 2.2}).set_placement(
|
||||
(dr["text_x"], ty))
|
||||
ty -= 4.2
|
||||
|
||||
|
||||
def _render_datum(msp, r):
|
||||
dr = r.draw
|
||||
at, bc, letter = dr["at"], dr["bc"], r.name
|
||||
dx, dy = bc[0] - at[0], bc[1] - at[1]
|
||||
n = math.hypot(dx, dy) or 1.0
|
||||
ux, uy = dx / n, dy / n
|
||||
px, py = -uy, ux
|
||||
base = (at[0] + ux * 2.6, at[1] + uy * 2.6)
|
||||
p1 = (base[0] + px * 1.5, base[1] + py * 1.5)
|
||||
p2 = (base[0] - px * 1.5, base[1] - py * 1.5)
|
||||
msp.add_lwpolyline([at, p1, p2], close=True, dxfattribs={"layer": "尺寸标注"})
|
||||
msp.add_lwpolyline([(bc[0] - 3, bc[1] - 2.2), (bc[0] + 3, bc[1] - 2.2),
|
||||
(bc[0] + 3, bc[1] + 2.2), (bc[0] - 3, bc[1] + 2.2)],
|
||||
close=True, dxfattribs={"layer": "尺寸标注"})
|
||||
join = ((bc[0], bc[1] - 2.2) if abs(uy) > abs(ux)
|
||||
else ((bc[0] - 3) if ux < 0 else (bc[0] + 3), bc[1]))
|
||||
_seg(msp, base, join, "尺寸标注")
|
||||
msp.add_text(letter, dxfattribs={"layer": "文字", "height": 3.0}
|
||||
).set_placement((bc[0] - 1.1, bc[1] - 1.4))
|
||||
|
||||
|
||||
def _frame(msp, plan):
|
||||
msp.add_lwpolyline([(25, 5), (415, 5), (415, 292), (25, 292)], close=True,
|
||||
dxfattribs={"layer": "01粗实线"})
|
||||
tb = (235.0, 5.0, 415.0, 61.0)
|
||||
msp.add_lwpolyline([(tb[0], tb[1]), (tb[2], tb[1]), (tb[2], tb[3]),
|
||||
(tb[0], tb[3])], close=True,
|
||||
dxfattribs={"layer": "01粗实线"})
|
||||
for y in (47.0, 33.0, 19.0):
|
||||
msp.add_line((tb[0], y), (tb[2], y), dxfattribs={"layer": "01细实线"})
|
||||
msp.add_line((330.0, tb[1]), (330.0, tb[3]), dxfattribs={"layer": "01细实线"})
|
||||
|
||||
def t(label, value, x, y, h=3.2):
|
||||
msp.add_text(label, dxfattribs={"layer": "文字", "style": "CJK",
|
||||
"height": 2.4}).set_placement((x + 1.5, y + 9.5))
|
||||
msp.add_text(value, dxfattribs={"layer": "文字", "style": "CJK",
|
||||
"height": h}).set_placement((x + 1.5, y + 4.0))
|
||||
|
||||
msp.add_text(plan.d.title, dxfattribs={"layer": "文字", "style": "CJK",
|
||||
"height": 4.5}).set_placement(
|
||||
((tb[0] + tb[2]) / 2 - 33, 51.0))
|
||||
t("设计 DESIGN", "GLM-Agent", tb[0], 33.0)
|
||||
t("图号 DWG NO.", plan.d.dwg_no, 330.0, 33.0)
|
||||
t("比例 SCALE", f"{plan.d.scale:g} : 1", tb[0], 19.0)
|
||||
t("单位 UNIT", "mm · GB 第一角", 280.0, 19.0)
|
||||
t("材料 MATERIAL", plan.d.material, 330.0, 19.0)
|
||||
import time as _t
|
||||
t("日期 DATE", _t.strftime("%Y-%m-%d"), tb[0], 5.0)
|
||||
t("版本 REV", "1.0", 280.0, 5.0)
|
||||
t("张次 SHEET", "1 / 1", 330.0, 5.0)
|
||||
|
||||
|
||||
def _notes(msp, plan):
|
||||
ny = plan.d.notes_zone[3]
|
||||
msp.add_text("技术要求 NOTES:", dxfattribs={"layer": "文字", "style": "CJK",
|
||||
"height": 3.0}).set_placement((28.0, ny))
|
||||
ny -= 4.6
|
||||
for rr in plan.d.notes:
|
||||
msp.add_text(rr, dxfattribs={"layer": "文字", "style": "CJK",
|
||||
"height": 2.2}).set_placement((28.0, ny))
|
||||
ny -= 4.2
|
||||
py = ny - 6.0
|
||||
msp.add_text("参数 PARAMETERS:", dxfattribs={"layer": "文字", "style": "CJK",
|
||||
"height": 3.0}).set_placement((28.0, py))
|
||||
py -= 4.6
|
||||
keys = list(plan.d.params.keys())
|
||||
rows = (len(keys) + 2) // 3
|
||||
for i, k in enumerate(keys):
|
||||
col, row = i // rows, i % rows
|
||||
v = plan.d.params[k]
|
||||
vs = f"{v:g}" if isinstance(v, float) else str(v)
|
||||
msp.add_text(f"{k}={vs}", dxfattribs={"layer": "文字", "style": "CJK",
|
||||
"height": 2.0}).set_placement(
|
||||
(28.0 + col * 66.0, py - row * 3.4))
|
||||
|
||||
|
||||
def render_plan(plan, dxf_path, png_path):
|
||||
"""把求解后的 SheetPlan 渲染为 GB 图层 DXF + PNG 双产物。
|
||||
|
||||
DXF 走 ezdxf(手工基元:细实线尺寸线/界线、实心箭头、旋转归一文字、
|
||||
GB 图层 01粗实线/08虚线/05中心线/尺寸标注/文字),PNG 经 PyMuPdf 由
|
||||
DXF 转出用于多模态互校验。同时写出便于版本 diff 的文本化动作日志。
|
||||
"""
|
||||
t0 = time.time()
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
|
||||
doc = ezdxf.new("R2010", setup=True)
|
||||
doc.header["$INSUNITS"] = 4
|
||||
doc.header["$LWDISPLAY"] = 1
|
||||
doc.styles.add("CJK", font=_cjk_font_name())
|
||||
doc.linetypes.add("DASHED_GB", [3.0, 2.0, -1.0], description="细虚线 GB 2/1")
|
||||
doc.linetypes.add("CENTER_GB", [18.0, 12.0, -1.5, 0.0, -1.5],
|
||||
description="细点画线 GB 12/1.5")
|
||||
for lname, color, lt, lw in _LAYERS:
|
||||
doc.layers.add(lname, color=color, linetype=lt, lineweight=lw)
|
||||
msp = doc.modelspace()
|
||||
|
||||
for name, vw in plan.views.items():
|
||||
_draw_view_edges(msp, plan, vw)
|
||||
|
||||
# 中心线
|
||||
for cd in plan.d.centers:
|
||||
if cd.arc:
|
||||
cx, cy, r, a0, a1 = cd.arc
|
||||
c0 = plan.tx(cd.view, (cx, cy))
|
||||
sweep = (a1 - a0) % 360.0 # DXF 语义: a0→a1 逆时针
|
||||
steps = max(8, int(sweep / 10))
|
||||
pts = []
|
||||
for i in range(steps + 1):
|
||||
a = math.radians(a0 + sweep * i / steps)
|
||||
pts.append((c0[0] + r * plan.s * math.cos(a),
|
||||
c0[1] + r * plan.s * math.sin(a)))
|
||||
for i in range(len(pts) - 1):
|
||||
_seg(msp, pts[i], pts[i + 1], "05中心线")
|
||||
else:
|
||||
_seg(msp, plan.tx(cd.view, cd.p1), plan.tx(cd.view, cd.p2), "05中心线")
|
||||
|
||||
# 尺寸
|
||||
for r in plan.resolved:
|
||||
if r.kind == "dim":
|
||||
_render_dim(msp, r)
|
||||
for r in plan.resolved:
|
||||
if r.kind == "leader":
|
||||
_render_leader(msp, r)
|
||||
for r in plan.resolved:
|
||||
if r.kind == "datum":
|
||||
_render_datum(msp, r)
|
||||
|
||||
_frame(msp, plan)
|
||||
_notes(msp, plan)
|
||||
|
||||
doc.saveas(dxf_path)
|
||||
chk = ezdxf.readfile(dxf_path)
|
||||
cnt = len(list(chk.modelspace()))
|
||||
from ezdxf.addons.drawing import Frontend, RenderContext, config, layout, pymupdf
|
||||
context = RenderContext(chk)
|
||||
backend = pymupdf.PyMuPdfBackend()
|
||||
cfg = config.Configuration(
|
||||
background_policy=config.BackgroundPolicy.WHITE,
|
||||
color_policy=config.ColorPolicy.BLACK)
|
||||
Frontend(context, backend, config=cfg).draw_layout(chk.modelspace())
|
||||
page = layout.Page(420, 297, layout.Units.mm, margins=layout.Margins.all(2))
|
||||
png_path.write_bytes(backend.get_pixmap_bytes(page, fmt="png", dpi=220))
|
||||
print(f" 渲染 {Path(dxf_path).name} ({cnt} 实体) + "
|
||||
f"{Path(png_path).name} ({time.time() - t0:.1f}s)")
|
||||
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
"""dxf_engine 单元测试: 1-DOF 标注模型 / 引出线修复 / 自动诊断图 / 确定性。
|
||||
|
||||
覆盖 (按实现分组):
|
||||
rad 定向后文字仅剩沿线 1 自由度 —— 弧外/弧内候选、基线恒在线上方、
|
||||
引线派生延长、rot 恒等线向 (R2, 动作不可覆盖)、箭头随内外侧翻转
|
||||
lin slide 沿尺寸线滑移、文字滑出测量段时尺寸线自动侧延长、
|
||||
窄跨度直接界外 + 延长
|
||||
dia insert(基线锚) 与 anchor(OBB 中心) 分离, 动作换位重算
|
||||
lead 多行引出肘点上移到框顶上方 / 无空位兜底不崩 / 引线压文本不再 NameError
|
||||
diag SheetDecl.diag_png 声明后 solve/apply 自动刷新诊断图 + 返回阅读指令
|
||||
misc position 无基准 fail-fast (R6); R5 参数表兜底; 双次渲染确定性
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import math
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import simplecadapi as scad
|
||||
from simplecadapi.dxf_engine import (DimDecl, LeaderDecl, SheetDecl, SheetPlan,
|
||||
ViewDecl)
|
||||
from simplecadapi.dxf_engine.planner import TEXT_H, _text_width
|
||||
|
||||
ANCHOR = (200.0, 200.0) # front 视图锚: 模型 (x,y) → 纸面 (200+x, 200+y)
|
||||
W = 30.0 # 盒宽 → front 视图 x∈[-15,15]
|
||||
|
||||
|
||||
def _box() -> scad.Solid:
|
||||
return scad.make_box_rsolid(width=W, height=20.0, depth=10.0)
|
||||
|
||||
|
||||
def _sheet(dims=None, leaders=None, notes_zone=(25.0, 5.0, 232.0, 90.0),
|
||||
**decl_kw):
|
||||
return SheetDecl(
|
||||
title="T", dwg_no="T-000", scale=1.0, front="front", anchor=ANCHOR,
|
||||
views=[ViewDecl("front", _box().wrapped, (0, 0, 1), (1, 0, 0),
|
||||
anchor=ANCHOR)],
|
||||
dims=dims or [], leaders=leaders or [], notes_zone=notes_zone,
|
||||
**decl_kw)
|
||||
|
||||
|
||||
def _rad(plan, caption="r"):
|
||||
return next(r for r in plan.resolved
|
||||
if r.kind == "dim" and r.name == caption).draw
|
||||
|
||||
|
||||
def _lin(plan, caption):
|
||||
return next(r for r in plan.resolved
|
||||
if r.kind == "dim" and r.name == caption).draw
|
||||
|
||||
|
||||
def _norm_rot(at):
|
||||
rot = (at % 180.0 + 180.0) % 180.0
|
||||
return rot - 180.0 if rot > 90.0 else rot
|
||||
|
||||
|
||||
class TestRadOneDOF(unittest.TestCase):
|
||||
"""半径: at 定向后 1-DOF; 弧外→弧内候选; 基线/中心/延长全派生。"""
|
||||
|
||||
def test_outer_geometry_contract(self):
|
||||
at, c, r = 30.0, (0.0, 10.0), 8.0
|
||||
plan = SheetPlan(_sheet(dims=[
|
||||
DimDecl("size", "front", "radius", "r", center=c, radius=r,
|
||||
value=r, at=at)])).solve()
|
||||
dr = _rad(plan)
|
||||
u = (math.cos(math.radians(at)), math.sin(math.radians(at)))
|
||||
rot = _norm_rot(at)
|
||||
n = (-math.sin(math.radians(rot)), math.cos(math.radians(rot)))
|
||||
cc = (ANCHOR[0] + c[0], ANCHOR[1] + c[1])
|
||||
mpt = (cc[0] + r * u[0], cc[1] + r * u[1])
|
||||
w = _text_width(dr["text"], TEXT_H)
|
||||
s = 3.0 # 无冲突 → 首候选
|
||||
insert = (mpt[0] + s * u[0] + n[0], mpt[1] + s * u[1] + n[1])
|
||||
anchor = (insert[0] + u[0] * w / 2 + n[0] * TEXT_H * 0.35,
|
||||
insert[1] + u[1] * w / 2 + n[1] * TEXT_H * 0.35)
|
||||
tail = (mpt[0] + (s + w + 1.5) * u[0], mpt[1] + (s + w + 1.5) * u[1])
|
||||
for key, want in (("mpt", mpt), ("insert", insert), ("anchor", anchor),
|
||||
("tail", tail)):
|
||||
self.assertAlmostEqual(dr[key][0], want[0], places=6, msg=key)
|
||||
self.assertAlmostEqual(dr[key][1], want[1], places=6, msg=key)
|
||||
self.assertAlmostEqual(dr["rot"], rot, places=6)
|
||||
# 弧外: 箭头自外指向圆弧; 引线长度覆盖全文 (侧延长派生)
|
||||
self.assertAlmostEqual(dr["arrow_deg"],
|
||||
math.degrees(math.atan2(u[1], u[0])) + 180.0,
|
||||
places=6)
|
||||
self.assertGreater(math.dist(mpt, dr["tail"]), w)
|
||||
|
||||
def test_inner_variant_via_action(self):
|
||||
at, c, r = 60.0, (0.0, 10.0), 8.0
|
||||
plan = SheetPlan(_sheet(dims=[
|
||||
DimDecl("size", "front", "radius", "r", center=c, radius=r,
|
||||
value=r, at=at)])).solve()
|
||||
w = _text_width(_rad(plan)["text"], TEXT_H)
|
||||
res = plan.apply([{"op": "rad", "name": "r", "s": -(w + 4.0)}])
|
||||
self.assertTrue(res["results"][0]["ok"], res["results"][0])
|
||||
dr = _rad(plan)
|
||||
u = (math.cos(math.radians(at)), math.sin(math.radians(at)))
|
||||
cc = (ANCHOR[0] + c[0], ANCHOR[1] + c[1])
|
||||
mpt = (cc[0] + r * u[0], cc[1] + r * u[1])
|
||||
# 弧内: 引线自弧向圆心侧延伸, 箭头自圆心侧指弧 (无 +180 翻转)
|
||||
self.assertLess(dr["tail"][0] * u[0] + dr["tail"][1] * u[1],
|
||||
mpt[0] * u[0] + mpt[1] * u[1])
|
||||
self.assertAlmostEqual(dr["arrow_deg"],
|
||||
math.degrees(math.atan2(u[1], u[0])), places=6)
|
||||
r_res = next(x for x in plan.resolved if x.name == "r")
|
||||
self.assertIn("弧内", r_res.resolved)
|
||||
|
||||
def test_solver_falls_back_inner_when_outer_blocked(self):
|
||||
# 圆心沉入 notes 禁入区下方: at=270° 弧外候选全部进禁入区,
|
||||
# 弧内候选(过圆心向上)干净 → solver 应自动选弧内
|
||||
c = (0.0, -115.0) # 纸面圆心 (200, 85)
|
||||
plan = SheetPlan(_sheet(dims=[
|
||||
DimDecl("size", "front", "radius", "r", center=c, radius=8.0,
|
||||
value=8.0, at=270.0)])).solve()
|
||||
r_res = next(x for x in plan.resolved if x.name == "r")
|
||||
self.assertIn("弧内", r_res.resolved, r_res.resolved)
|
||||
self.assertIn("滑移", "".join(r_res.adjust))
|
||||
|
||||
def test_rot_is_line_direction_not_overridable(self):
|
||||
plan = SheetPlan(_sheet(dims=[
|
||||
DimDecl("size", "front", "radius", "r", center=(0, 10),
|
||||
radius=8.0, value=8.0, at=30.0)])).solve()
|
||||
res = plan.apply([{"op": "rad", "name": "r", "at": 50.0,
|
||||
"rot": 77.0, "out": 99.0}])
|
||||
self.assertTrue(res["results"][0]["ok"])
|
||||
self.assertAlmostEqual(_rad(plan)["rot"], _norm_rot(50.0), places=6)
|
||||
|
||||
|
||||
class TestLinearSlide(unittest.TestCase):
|
||||
"""线性: side/row 结构位 + slide 沿线 1-DOF; 侧延长派生。"""
|
||||
|
||||
def test_mid_default_not_extended(self):
|
||||
plan = SheetPlan(_sheet(dims=[
|
||||
DimDecl("size", "front", "linear", "w", value=20.0,
|
||||
p1=(-10.0, 0.0), p2=(10.0, 0.0), side="bottom",
|
||||
row=0)])).solve()
|
||||
dr = _lin(plan, "w")
|
||||
yl = 190.0 - 8.0 # bbox.y0(190) - BASE_OFF
|
||||
self.assertEqual(dr["line"], ((190.0, yl), (210.0, yl)))
|
||||
# insert=基线左端 (文字沿 +x 展开, 与渲染 set_placement 一致)
|
||||
w = _text_width(dr["text"], TEXT_H)
|
||||
self.assertAlmostEqual(dr["insert"][0], 200.0 - w / 2, places=6)
|
||||
self.assertAlmostEqual(dr["insert"][1], yl + 1.0, places=6)
|
||||
self.assertFalse(dr.get("extended", False))
|
||||
|
||||
def test_slide_derived_elongation(self):
|
||||
dcl = DimDecl("size", "front", "linear", "w", value=20.0,
|
||||
p1=(-10.0, 0.0), p2=(10.0, 0.0), side="bottom", row=0)
|
||||
plan = SheetPlan(_sheet(dims=[dcl])).solve()
|
||||
text = "20 (w)"
|
||||
g = plan._lin_geometry(dcl, "bottom", 0, 25.0, text)
|
||||
w = _text_width(text, TEXT_H)
|
||||
self.assertTrue(g["extended"])
|
||||
self.assertAlmostEqual(g["center"][0], 200.0 + 25.0, places=6)
|
||||
# 正向滑移 → 文字滑出右测量点, 尺寸线右端自动侧延长覆盖全文
|
||||
self.assertGreaterEqual(g["line"][1][0], g["insert"][0] + w + 1.9)
|
||||
self.assertAlmostEqual(g["line"][0][0], 190.0, places=6)
|
||||
# 箭头仍指测量点 (滑移只动文字, 不动测量)
|
||||
yl = 190.0 - 8.0
|
||||
self.assertEqual(g["arrows"], ((190.0, yl), (210.0, yl)))
|
||||
|
||||
def test_narrow_span_auto_outside(self):
|
||||
plan = SheetPlan(_sheet(dims=[
|
||||
DimDecl("size", "front", "linear", "t", value=2.0,
|
||||
p1=(-1.0, 5.0), p2=(1.0, 5.0), side="bottom",
|
||||
row=0)])).solve()
|
||||
dr = _lin(plan, "t")
|
||||
self.assertTrue(dr.get("extended"))
|
||||
r_res = next(x for x in plan.resolved if x.name == "t")
|
||||
self.assertTrue(any(("滑移" in a or "延长" in a) for a in r_res.adjust),
|
||||
r_res.adjust)
|
||||
|
||||
def test_apply_lin_slide(self):
|
||||
plan = SheetPlan(_sheet(dims=[
|
||||
DimDecl("size", "front", "linear", "w", value=20.0,
|
||||
p1=(-10.0, 0.0), p2=(10.0, 0.0), side="bottom",
|
||||
row=0)])).solve()
|
||||
x0 = _lin(plan, "w")["insert"][0]
|
||||
res = plan.apply([{"op": "lin", "name": "w", "slide": 14.0}])
|
||||
self.assertTrue(res["results"][0]["ok"], res["results"][0])
|
||||
self.assertAlmostEqual(_lin(plan, "w")["insert"][0], x0 + 14.0,
|
||||
places=6)
|
||||
|
||||
|
||||
class TestDiameterAnchors(unittest.TestCase):
|
||||
"""直径: insert=基线锚(0.75r 线上方), anchor=OBB 中心; 动作换位重算。"""
|
||||
|
||||
def test_anchor_split(self):
|
||||
at, c, r = 35.0, (0.0, 10.0), 8.0
|
||||
plan = SheetPlan(_sheet(dims=[
|
||||
DimDecl("size", "front", "diameter", "d", center=c, radius=r,
|
||||
value=16.0, at=at)])).solve()
|
||||
dr = _rad(plan, "d")
|
||||
u = (math.cos(math.radians(at)), math.sin(math.radians(at)))
|
||||
rot = _norm_rot(at)
|
||||
n = (-math.sin(math.radians(rot)), math.cos(math.radians(rot)))
|
||||
cc = (ANCHOR[0] + c[0], ANCHOR[1] + c[1])
|
||||
w = _text_width(dr["text"], TEXT_H)
|
||||
insert = (cc[0] + 0.75 * r * u[0] + n[0],
|
||||
cc[1] + 0.75 * r * u[1] + n[1])
|
||||
anchor = (insert[0] + u[0] * w / 2 + n[0] * TEXT_H * 0.35,
|
||||
insert[1] + u[1] * w / 2 + n[1] * TEXT_H * 0.35)
|
||||
for key, want in (("insert", insert), ("anchor", anchor),
|
||||
("m1", (cc[0] + r * u[0], cc[1] + r * u[1])),
|
||||
("m2", (cc[0] - r * u[0], cc[1] - r * u[1]))):
|
||||
self.assertAlmostEqual(dr[key][0], want[0], places=6, msg=key)
|
||||
self.assertAlmostEqual(dr[key][1], want[1], places=6, msg=key)
|
||||
|
||||
def test_apply_dia_at(self):
|
||||
plan = SheetPlan(_sheet(dims=[
|
||||
DimDecl("size", "front", "diameter", "d", center=(0, 10),
|
||||
radius=8.0, value=16.0, at=35.0)])).solve()
|
||||
res = plan.apply([{"op": "dia", "name": "d", "at": 120.0}])
|
||||
self.assertTrue(res["results"][0]["ok"], res["results"][0])
|
||||
self.assertAlmostEqual(_rad(plan, "d")["rot"], _norm_rot(120.0),
|
||||
places=6)
|
||||
|
||||
|
||||
class TestLeaderFixes(unittest.TestCase):
|
||||
"""引出线三修复: 肘点上移 / 无空位兜底 / 引线压文本不再 NameError。"""
|
||||
|
||||
def test_multiline_elbow_above_box(self):
|
||||
plan = SheetPlan(_sheet(leaders=[
|
||||
LeaderDecl("front", anchor=(0, 10), lines=["一", "二"],
|
||||
off=(40.0, 0.0), name="L")])).solve()
|
||||
dr = next(r.draw for r in plan.resolved if r.kind == "leader")
|
||||
# 肘点须在文本框顶上方 (旧实现肘线划过第二行文字)
|
||||
self.assertAlmostEqual(dr["path"][1][1], dr["text_y_top"] + 0.8,
|
||||
places=6)
|
||||
self.assertGreater(dr["path"][1][1], dr["text_y_top"])
|
||||
|
||||
def test_no_space_fallback_no_crash(self):
|
||||
# 禁入区覆盖全图 → 所有候选落空 → 兜底分支 (旧实现此处解包崩溃)
|
||||
plan = SheetPlan(_sheet(
|
||||
leaders=[LeaderDecl("front", anchor=(0, 10), lines=["x"],
|
||||
off=(40.0, 0.0), name="L")],
|
||||
notes_zone=(25.0, 5.0, 415.0, 292.0))).solve()
|
||||
r = next(x for x in plan.resolved if x.kind == "leader")
|
||||
self.assertTrue(any("未找到空位" in a for a in r.adjust), r.adjust)
|
||||
|
||||
def test_leader_seg_over_text_no_crash(self):
|
||||
# 引线段穿过已注册文本 OBB (旧实现该分支引用未定义名 kk2 → NameError)
|
||||
plan = SheetPlan(_sheet(dims=[
|
||||
DimDecl("size", "front", "linear", "h", value=20.0,
|
||||
p1=(15.0, 0.0), p2=(15.0, 20.0), side="right", row=0)],
|
||||
leaders=[LeaderDecl("front", anchor=(0, 10), lines=["一", "二"],
|
||||
off=(40.0, 0.0), name="L")])).solve()
|
||||
self.assertTrue(any(r.kind == "leader" for r in plan.resolved))
|
||||
|
||||
|
||||
class TestAutoDiag(unittest.TestCase):
|
||||
"""diag_png 声明后 solve/apply 自动刷新诊断图并返回阅读指令。"""
|
||||
|
||||
def test_solve_writes_diag_and_report_mentions(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
png = Path(td) / "diag.png"
|
||||
plan = SheetPlan(_sheet(dims=[
|
||||
DimDecl("size", "front", "linear", "w", value=20.0,
|
||||
p1=(-10.0, 0.0), p2=(10.0, 0.0), side="bottom",
|
||||
row=0)], diag_png=str(png))).solve()
|
||||
self.assertTrue(png.exists() and png.stat().st_size > 0)
|
||||
self.assertIn("诊断图 DIAG", plan.report())
|
||||
self.assertIn("必读", plan.report())
|
||||
|
||||
def test_apply_returns_instruction(self):
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
png = Path(td) / "diag.png"
|
||||
plan = SheetPlan(_sheet(dims=[
|
||||
DimDecl("size", "front", "linear", "w", value=20.0,
|
||||
p1=(-10.0, 0.0), p2=(10.0, 0.0), side="bottom",
|
||||
row=0)], diag_png=str(png))).solve()
|
||||
out = plan.apply([{"op": "lin", "name": "w", "slide": 5.0}])
|
||||
self.assertEqual(out.get("diag"), str(png))
|
||||
self.assertIn("必读", out.get("instruction", ""))
|
||||
|
||||
|
||||
class TestMiscContracts(unittest.TestCase):
|
||||
|
||||
def test_position_without_datum_fails_fast(self):
|
||||
with self.assertRaises(ValueError):
|
||||
DimDecl("position", "front", "linear", "x", value=5.0,
|
||||
p1=(0, 0), p2=(5, 0))
|
||||
|
||||
def test_r5_param_table_fallback(self):
|
||||
plan = SheetPlan(_sheet(
|
||||
dims=[DimDecl("size", "front", "linear", "w", value=20.0,
|
||||
p1=(-10.0, 0.0), p2=(10.0, 0.0), side="bottom",
|
||||
row=0)],
|
||||
params={"w": 20.0, "unannotated": 3.0})).solve()
|
||||
cov = dict(plan.coverage)
|
||||
self.assertEqual(cov["unannotated"], "参数表")
|
||||
|
||||
def test_double_render_deterministic(self):
|
||||
import ezdxf
|
||||
plan = SheetPlan(_sheet(dims=[
|
||||
DimDecl("size", "front", "linear", "w", value=20.0,
|
||||
p1=(-10.0, 0.0), p2=(10.0, 0.0), side="bottom", row=0),
|
||||
DimDecl("size", "front", "radius", "r", center=(0, 10),
|
||||
radius=8.0, value=8.0, at=30.0)])).solve()
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
hashes = []
|
||||
for i in (1, 2):
|
||||
dxf, png = Path(td) / f"a{i}.dxf", Path(td) / f"a{i}.png"
|
||||
plan.render(dxf, png)
|
||||
hashes.append(hashlib.md5(png.read_bytes()).hexdigest())
|
||||
self.assertGreater(
|
||||
len(list(ezdxf.readfile(dxf).modelspace())), 10)
|
||||
self.assertEqual(hashes[0], hashes[1])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -41,6 +41,9 @@ DEFAULT_SOURCE_FILENAMES: tuple[str, ...] = (
|
||||
"product/capture.py",
|
||||
"product/packages.py",
|
||||
"topology/model.py",
|
||||
"dxf_engine/model.py",
|
||||
"dxf_engine/planner.py",
|
||||
"dxf_engine/render.py",
|
||||
"build/assembly_builder.py",
|
||||
"build/dependencies.py",
|
||||
"build/incremental_solver.py",
|
||||
@@ -396,6 +399,8 @@ class APIDocumentGenerator:
|
||||
"inspect_benchmark_step",
|
||||
"run_comparison_bundle",
|
||||
}
|
||||
if module_name.startswith("dxf_engine/"):
|
||||
return name in {"render_plan"}
|
||||
if module_name in EXPORTED_FUNCTION_MODULES:
|
||||
if not exported_names:
|
||||
return True
|
||||
@@ -428,6 +433,17 @@ class APIDocumentGenerator:
|
||||
}
|
||||
if module_name == "inverse_engineer/brep/evaluation.py":
|
||||
return name in {"EvaluationConfig", "SectionEvaluationConfig"}
|
||||
if module_name.startswith("dxf_engine/"):
|
||||
return name in {
|
||||
"SheetDecl",
|
||||
"ViewDecl",
|
||||
"DimDecl",
|
||||
"DatumDecl",
|
||||
"CenterDecl",
|
||||
"LeaderDecl",
|
||||
"SheetPlan",
|
||||
"Resolved",
|
||||
}
|
||||
if name in exported_names:
|
||||
return True
|
||||
if module_name not in EXPORTED_CALLABLE_MODULES:
|
||||
@@ -490,6 +506,12 @@ class APIDocumentGenerator:
|
||||
f"then `brep.{name}(...)`; unavailable inside GraphSession"
|
||||
)
|
||||
|
||||
if module_name.startswith("dxf_engine/"):
|
||||
return (
|
||||
"drawing namespace: "
|
||||
f"`from simplecadapi.dxf_engine import {name}`"
|
||||
)
|
||||
|
||||
module_stem = module_name.removesuffix(".py")
|
||||
if module_stem in {"field", "ql"}:
|
||||
return (
|
||||
@@ -655,6 +677,7 @@ class APIDocumentGenerator:
|
||||
"STEP/BREP Inspection": [],
|
||||
"Product Build and Cache": [],
|
||||
"Reconstruction Evaluation": [],
|
||||
"Engineering Drawings": [],
|
||||
"Other": [],
|
||||
}
|
||||
|
||||
@@ -672,6 +695,10 @@ class APIDocumentGenerator:
|
||||
categories["Reconstruction Evaluation"].append(api)
|
||||
continue
|
||||
|
||||
if api.source_file.startswith("dxf_engine/"):
|
||||
categories["Engineering Drawings"].append(api)
|
||||
continue
|
||||
|
||||
if api.source_file in {"recording/serializer.py", "recording/graph.py"}:
|
||||
categories["Modeling Graph and Replay"].append(api)
|
||||
continue
|
||||
|
||||
@@ -805,6 +805,54 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/7b/8f/c4d9bafc34ad7ad5d8dc16dd1347ee0e507a52c3adb6bfa8887e1c6a26ba/executing-2.2.0-py2.py3-none-any.whl", hash = "sha256:11387150cad388d62750327a53d3339fad4888b39a6fe233c3afbb54ecffd3aa", size = 26702, upload-time = "2025-01-22T15:41:25.929Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ezdxf"
|
||||
version = "1.4.4"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
dependencies = [
|
||||
{ name = "fonttools" },
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
{ name = "pyparsing" },
|
||||
{ name = "typing-extensions" },
|
||||
]
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/5e/d7/1b7be8db364f1c4838dfc1a40ca96577aba405deabf896a4eb3aaeb15a62/ezdxf-1.4.4.tar.gz", hash = "sha256:da5a5e0e6bdbb6656f9c017b47edc7eafceb419d61a2b5de64ffb344c168e593", size = 1866886, upload-time = "2026-05-14T09:19:19.511Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/ad/3c/59a301a6abde7bc4d907e97de86ac42510c173845bb31b0d439bcda27d1d/ezdxf-1.4.4-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:fbd70284ac9c39581e4973589d10afd941bc6c64c1cdd087ecd387ce7697bd50", size = 3556772, upload-time = "2026-05-14T09:25:23.867Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/77/b1/f77d2e9bc00c04d16cd9ce483bc41ccad3208691a196948633def256f199/ezdxf-1.4.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:4e9aecff9c34a62f21115bd98c0ab76d3448064a3c31f1f1df6e9c19dc78ea56", size = 1883618, upload-time = "2026-05-14T09:25:25.405Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/f2/a1/4e2fede39fea3f0cb49e522e36b0e19e708e177aa35da07faf715e2723cf/ezdxf-1.4.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:8ff103b9ef0de6eca86a32506a4a0717ff05024450e9da3ea9a77a73f63e1ac2", size = 3002809, upload-time = "2026-05-14T09:25:26.617Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a8/af/716787bca9adbfc3df08065b8d61796505d0e93dbe08ba956faa497fde0a/ezdxf-1.4.4-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:39c1e7d77220654482c2c2ba82a171c50a40f2295f9f4d3cb72bbc909f1f2fcb", size = 4503821, upload-time = "2026-05-14T09:27:25.435Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2a/ed/4f2ac38a5766603283a6e708a759165999c1f74109c5875b334939b6be40/ezdxf-1.4.4-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bd67e30aafdbf64c74a09908c6648e20fe4e0c58fd0504e6ea4913f654708919", size = 4490630, upload-time = "2026-05-14T09:27:05.885Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/9e/11/8d4b9aa5d1bba69fbd40f3cd9af992272309977c1de71afeecb9bb5a4cd3/ezdxf-1.4.4-cp310-cp310-musllinux_1_2_aarch64.whl", hash = "sha256:edbd0c0350361104834688034fecb97eefaff486c872f83809c71ec6988e0236", size = 4472239, upload-time = "2026-05-14T09:27:26.908Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b3/78/c1ea4664a9bc81929e119b2569f2837035bba57dd3e86945963d802426f7/ezdxf-1.4.4-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:e110caf14288923afa771a2d5752b0916b9a9621c1abf60f3caf7b454f989cf6", size = 4533843, upload-time = "2026-05-14T09:27:08.094Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fd/84/3b4c5b01a791e7b3859cf570a0502b4bba8cf208f9d2a19759a0bcfbc6ed/ezdxf-1.4.4-cp310-cp310-win_amd64.whl", hash = "sha256:080d487ff8f9cdda79b4c7743683d103235cf831da6ef473edfa80170d1bc61d", size = 1821825, upload-time = "2026-05-14T09:23:45.033Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8f/d0/bc515b7f5596bc3d55b93fc9f2c2b4926e2587af6bfae0486ef7cc7ddf43/ezdxf-1.4.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:39aadab5bc7a05deddbd0db9b984c8a4bd28bd4c1ac2c5ee03f0d1b096272a88", size = 3553590, upload-time = "2026-05-14T09:25:28.042Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a7/73/207132f13a5280d186f2441d9125639fdc7ddeabf56c2d5da4d691e81ce6/ezdxf-1.4.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:2ed65b191113a82133ba47daa6ebdd540b487b17394b1e327e9511dde87ad924", size = 3008276, upload-time = "2026-05-14T09:25:29.424Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/82/73/b01af87269726e3719abc5ff694b843b710ef8fc345d21013e90d70e44d8/ezdxf-1.4.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7c3c8f2c2b62fe5b6c9b62ab8257b697535d62b0c79acf3a5040bd95edfab451", size = 3001750, upload-time = "2026-05-14T09:25:31.146Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/dd/92/284d7ca6a9da107966c7bd9d81c92245985235bc432fe0837982ef80630a/ezdxf-1.4.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d68d5ab9e1071319030da3af27590f34c38c8544a5ea638d9a4a800a96abb3c2", size = 5802382, upload-time = "2026-05-14T09:27:28.462Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/7d/fe/e4f37730ca5b5bf7de3a968a26126b404f60324d0b8ae9d59d11d6e55740/ezdxf-1.4.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7f75a4f2924ebdda0f5b2779ff2135ba92de2596c95a8fa9b1d9ebcabea1be41", size = 5794671, upload-time = "2026-05-14T09:27:09.867Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fe/3f/c3e7ab74f58cb69ef985fb71eda859b5c287cc506c65cbffe7e55c7cf2d4/ezdxf-1.4.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0eec8a2095b645420a67560e99041c0d25afefd39eab5bff8c736fdb32211a75", size = 5767366, upload-time = "2026-05-14T09:27:30.108Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/66/7a/b7070bf05e75b3e709a6fe5ae5bcd3bd899e987ef84ff25cf28327519c03/ezdxf-1.4.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:d87a85052e92b9c28e54605dbad65f779a3b61e6288e992d6ef00df7bde4bed3", size = 5830221, upload-time = "2026-05-14T09:27:12.074Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/78/cf/a990289808c261c52f5b219484d136a8748773c99a6d25c84f55a0353fea/ezdxf-1.4.4-cp311-cp311-win_amd64.whl", hash = "sha256:473d68c8f2b04ace513efa290a1cd0d3a4a589cdff48124f015f0e51034668b2", size = 2957599, upload-time = "2026-05-14T09:23:46.571Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/18/3d/98648d221ffa047b5ba898c8e152010861dc71a66b531dcf15053075010e/ezdxf-1.4.4-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:d723d35d08223318c17080a32a05192a1449e544dee867c9d9c6f25998fac303", size = 3563916, upload-time = "2026-05-14T09:25:32.879Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/2c/f1/84bbaa571412f840c22deeae185e54d4a67aa52f03e1728fd8425748c548/ezdxf-1.4.4-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6b0c73b46085521bdbd4a3e7d88998da7bec5713ba89bbb502fdeffe6b42fc7e", size = 3016857, upload-time = "2026-05-14T09:25:34.607Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/b0/ff/f2eb77d22d26aa98abbe0961470871d8b85ef4e73e5527f544d25f958d6e/ezdxf-1.4.4-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ac3e83a70c1f866dd5114192a6fab6e75cc83b75e907bc08c5d94b98cce14cc0", size = 3003336, upload-time = "2026-05-14T09:25:35.947Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/65/7d/2a6ddd6beef5d9a8593078619f3920a0cd76b1db4c6a974ac37045543219/ezdxf-1.4.4-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8ebe09717ab6636bf48780eabdab51e3ab2135f7963bb52452444b6d95e03d12", size = 5788485, upload-time = "2026-05-14T09:27:32.176Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e7/29/2094fd7719146ca7bb236be9751b5929d431f643cbab669aed89cf121883/ezdxf-1.4.4-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:44af248af0860fe8b1a39ca40e1cd2fa8ac37b22142b14b20c6a0caf1b50f932", size = 5816781, upload-time = "2026-05-14T09:27:13.96Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/19/8d/669b8047cca162204c53b874183d73b5f6c4b1d5d48fa1e515a32d56f5ac/ezdxf-1.4.4-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:02a097794625e9fc948e637dfe07057e98167b4fe215357a59645759fef6db3f", size = 5754006, upload-time = "2026-05-14T09:27:33.858Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/5b/44/b753997173327250e43ae50f11f0c69016b1e78482e0bd3857c3495236e7/ezdxf-1.4.4-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:f093bd2228f5782d483aed3bd89cdb74b672b5f90c677c4125cd236ee5649151", size = 5861860, upload-time = "2026-05-14T09:27:15.758Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/0b/99/2e81cb168e0f09adfb05fb40e5f890ff87ac2c00e98079cf09837dd76330/ezdxf-1.4.4-cp312-cp312-win_amd64.whl", hash = "sha256:3e518d9ed4dcbe525d57f14c25c5e592f82660a690fdec39b03b092e6cdc4771", size = 2963238, upload-time = "2026-05-14T09:23:47.924Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/be/ed/97aa3ba1ba923e4098169de5bca380ee1430e2b34d0dd85b73007e34df16/ezdxf-1.4.4-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:278a09a845d67a4f893aebe9ef8dcd8894ece9f255d7d8bb21719ffd902109b8", size = 3555283, upload-time = "2026-05-14T09:25:37.346Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4e/b1/8ca9408a2b382a806837e72d35f10931fdd9f53fe66cf208a6340358fbc5/ezdxf-1.4.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:b0a787f8ebcbdcb9798c6fcfe90c23afd1a0993c8d4302b6cce5d8f19ae052ae", size = 3012646, upload-time = "2026-05-14T09:25:39.01Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8b/aa/1e8d3130eaabb780c5e8adfdc1ead023bb04468779b18169d60f7ce5b291/ezdxf-1.4.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:c451d1c20f08b30c735ca4d650fee5b44147402f4b5662f8550053ed8a3009c2", size = 2999048, upload-time = "2026-05-14T09:25:40.348Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/cd/ca/1dd390b79df9c104c2d4b5964e80db25362edf704ac742c9db9b279658a5/ezdxf-1.4.4-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3d3d9a6663993fc644751647fd7843057b51742ffac27c48ce28ea9f81239613", size = 5747890, upload-time = "2026-05-14T09:27:36.028Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/8f/1e/226a6e636ae533e0bc0afe4435d1058fac173564e4af4102862f055a46d9/ezdxf-1.4.4-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:82c022cf094d21ad3db68557aa83628e4152355e8a8bef0fffd4f71a9ea325df", size = 5774707, upload-time = "2026-05-14T09:27:17.625Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/24/a3/7e33c9036de944b5446982bb629d698356e48b00c4d173768f52bdeeff4b/ezdxf-1.4.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:3be59c2a3a93585412a2a37af29b3ad7574fa3e429e624924c3285d0573388b3", size = 5713753, upload-time = "2026-05-14T09:27:37.55Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/36/9e/ac0cdc3a8623fc38aa16670f6537aa810bc1381217a51ac3481299bbc986/ezdxf-1.4.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:44a9716860b59dddd49a3708c04ff4580ad1e7de92ac93bb3213d85fba5ac93f", size = 5813895, upload-time = "2026-05-14T09:27:19.514Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/dd/22/b511a8d9ea8f23447a67fe8977213fac5e4e69df30130a3ef31043613eaf/ezdxf-1.4.4-cp313-cp313-win_amd64.whl", hash = "sha256:207eed544417464ffaf2570880d58a792ecd2534c9c2dede45e895f3200b77e6", size = 2960937, upload-time = "2026-05-14T09:23:49.361Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/a0/09/5ecb6f82d35a2f4a4334d0a608fcf764827fa69dccdf5987ce309c16b6c1/ezdxf-1.4.4-py3-none-any.whl", hash = "sha256:666edda631ba717270293b734f5d58dd97a1d1aba4787187f09d0cc584645865", size = 1331217, upload-time = "2026-05-14T09:19:26.601Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fastjsonschema"
|
||||
version = "2.21.1"
|
||||
@@ -2300,6 +2348,23 @@ wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/c7/21/705964c7812476f378728bdf590ca4b771ec72385c533964653c68e86bdc/pygments-2.19.2-py3-none-any.whl", hash = "sha256:86540386c03d588bb81d44bc3928634ff26449851e99741617ecb9037ee5ec0b", size = 1225217, upload-time = "2025-06-21T13:39:07.939Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pymupdf"
|
||||
version = "1.28.2"
|
||||
source = { registry = "https://pypi.org/simple" }
|
||||
sdist = { url = "https://files.pythonhosted.org/packages/a3/fb/b6761fa2d5266f2cdb24c3b91f4023070ab7848381417678e7a289a1d52a/pymupdf-1.28.2.tar.gz", hash = "sha256:5e0be7908a715aa20333caddd73f1d6f01e4cd0c26e869fa2dd0b7f344da2249", size = 87903557, upload-time = "2026-08-06T21:43:23.321Z" }
|
||||
wheels = [
|
||||
{ url = "https://files.pythonhosted.org/packages/b4/51/550c9a75c4ff3245cb4ecb7bb95cbe2ab7374230b8e2b7a1f7259444150b/pymupdf-1.28.2-cp310-abi3-macosx_10_15_x86_64.whl", hash = "sha256:5fc315b425ff1f7afdd1ea2f348205cb19b806767daae7ce4d64115799c2bae1", size = 24645079, upload-time = "2026-08-06T21:37:25.001Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/fa/01/3591f781b417b382a8487a2356e927acfe858b1043bab0ec47f6805bb109/pymupdf-1.28.2-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:7113846b35dbf0a033f088e4f4fb543dabeb4b0b12c112966a1ca1ee2d5eacae", size = 23875605, upload-time = "2026-08-06T21:37:40.369Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/d2/86/4a68f080b71b46802178346af46486e1697508e760855ff5f3b218a6dff7/pymupdf-1.28.2-cp310-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:3050a233dde1211efe89ada74e2add6238436434159f46097a1423aad2842545", size = 25095554, upload-time = "2026-08-06T21:37:58.485Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/c7/06/dace3e27af26690cb20bead80dbac42941b0841eb689b8aabbd67dde16f0/pymupdf-1.28.2-cp310-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:397d6715c1f0df7548a92d0afd8ce370fc48fa47aeefac16be2bc04a16a8227f", size = 25762500, upload-time = "2026-08-06T21:38:17.438Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e5/61/4146dfa1d8172a1ce8d59f0eed94896ddefb8deb2274534d0522fbb8abf5/pymupdf-1.28.2-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:f89fb2d86d07d643a269f17a093105057e20c79c1d06c103b53600067b6d2b01", size = 25986309, upload-time = "2026-08-06T21:38:35.472Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/52/60/1fb6e64676f7500ebe89054b9e5bbbe14d3101c92d5f1a40ac9a35227673/pymupdf-1.28.2-cp310-abi3-win32.whl", hash = "sha256:530ef543a3885b3b81cb72a854e7c5a625a9233201221132bb6c31698c6a2bdb", size = 18525353, upload-time = "2026-08-06T21:38:47.697Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/4a/61/d563bbccba262f9dd6d2d35ccb72593648184d886188efb12d9ce8f34dd6/pymupdf-1.28.2-cp310-abi3-win_amd64.whl", hash = "sha256:ebd244918798502d7b4504c90410d1711a4d7675a32584ca30f1bab419ecbffe", size = 19826532, upload-time = "2026-08-06T21:39:00.213Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/e2/93/08f404a1f0155fe24137cf2d3aabd3e2b4b08c62053ed89c60f2611be3e9/pymupdf-1.28.2-cp310-abi3-win_arm64.whl", hash = "sha256:ffe91a24edc75c80da2a4b62f50fc0f54632d34fc8fe4cbc48e5c7ff07cf8fb4", size = 19759252, upload-time = "2026-08-06T21:39:12.937Z" },
|
||||
{ url = "https://files.pythonhosted.org/packages/58/8c/d897dcd32a25b58186c968b15ce4324ca029e9d96460de12325314e390be/pymupdf-1.28.2-cp313-abi3-pyemscripten_2025_0_wasm32.whl", hash = "sha256:2e1b574c0fd2cb238021033fd3c0f9c4388816638df064e4bfb56d9d81736dc8", size = 18399403, upload-time = "2026-08-06T21:39:25.008Z" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pyparsing"
|
||||
version = "3.2.3"
|
||||
@@ -2959,11 +3024,13 @@ version = "2.0.4b3"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "cadquery-ocp" },
|
||||
{ name = "ezdxf" },
|
||||
{ name = "jsonschema" },
|
||||
{ name = "numpy", version = "2.2.6", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "numpy", version = "2.3.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
{ name = "ocp-gordon" },
|
||||
{ name = "py-slvs" },
|
||||
{ name = "pymupdf" },
|
||||
{ name = "rfc8785" },
|
||||
{ name = "rich" },
|
||||
{ name = "tomli", marker = "python_full_version < '3.11'" },
|
||||
@@ -3010,6 +3077,7 @@ requires-dist = [
|
||||
{ name = "black", marker = "extra == 'dev'", specifier = ">=23.0" },
|
||||
{ name = "cadquery-ocp", specifier = ">=7.9.3.1" },
|
||||
{ name = "ccx2paraview", extras = ["vtk"], marker = "extra == 'fem'", specifier = ">=3.2,<4" },
|
||||
{ name = "ezdxf", specifier = ">=1.4.4" },
|
||||
{ name = "gmsh", marker = "extra == 'fem'", specifier = ">=4.15,<5" },
|
||||
{ name = "gmsh", marker = "extra == 'gmsh'", specifier = ">=4.15,<5" },
|
||||
{ name = "isort", marker = "extra == 'dev'", specifier = ">=5.0" },
|
||||
@@ -3019,6 +3087,7 @@ requires-dist = [
|
||||
{ name = "numpy", specifier = ">=1.21.0" },
|
||||
{ name = "ocp-gordon", specifier = ">=0.2,<0.3" },
|
||||
{ name = "py-slvs", specifier = "==1.0.6" },
|
||||
{ name = "pymupdf", specifier = ">=1.28.2" },
|
||||
{ name = "pytest", marker = "extra == 'dev'", specifier = ">=7.0" },
|
||||
{ name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.0" },
|
||||
{ name = "python-fcl", marker = "extra == 'collision'", specifier = ">=0.7.0.11" },
|
||||
|
||||
Reference in New Issue
Block a user