diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/.claude-plugin/plugin.json b/plugins/Xiong-cmyk-collab/cad-drawing/.claude-plugin/plugin.json new file mode 100644 index 00000000..1063f885 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/.claude-plugin/plugin.json @@ -0,0 +1,35 @@ +{ + "name": "cad-drawing", + "version": "1.1.0", + "description": "Convert 3D engineering files (STL/STEP/3MF) into 1:1 printable A4 drawings with three orthographic views, hole positions, hole pitches, and a per-hole visibility judgement.", + "author": { + "name": "Xiong-cmyk-collab", + "url": "https://github.com/Xiong-cmyk-collab" + }, + "license": "Apache-2.0", + "homepage": "https://github.com/Xiong-cmyk-collab/MiniMax-Code-Plugins/tree/main/plugins/Xiong-cmyk-collab/cad-drawing", + "repository": "https://github.com/Xiong-cmyk-collab/MiniMax-Code-Plugins.git", + "keywords": [ + "mcode", + "cad", + "stl", + "step", + "technical-drawing", + "hole-detection", + "mcp" + ], + "icon": "icon.png", + "skills": [ + "./skills/cad-drawing/SKILL.md" + ], + "mcpServers": { + "cad-drawing": { + "type": "stdio", + "command": "node", + "args": [ + "./mcp/server.js" + ], + "cwd": "${PLUGIN_ROOT}" + } + } +} diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/.minimax-plugin/plugin.json b/plugins/Xiong-cmyk-collab/cad-drawing/.minimax-plugin/plugin.json new file mode 100644 index 00000000..e345eb38 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/.minimax-plugin/plugin.json @@ -0,0 +1,26 @@ +{ + "schemaVersion": 1, + "name": "cad-drawing", + "displayName": "3D 打印图助手", + "version": "1.1.0", + "description": "把 3D 工程文件(.stl/.3mf/.step)转成 1:1 可打印 A4 工程图 PDF:自动摆正零件方向,输出俯视/主视/左视三视图(第一角投影)、总体尺寸与孔距标注,识别全部孔位并逐条给出通孔/盲孔与可见性判定,三视图看不到的内部孔位单独列出并追加对应视图页;同时输出孔位 CSV 与特征 JSON。 / Convert 3D engineering files into 1:1 printable A4 drawings with three orthographic views, hole detection, pitch measurement, and a per-hole visibility judgement.", + "author": "Xiong-cmyk-collab", + "icon": "icon.png", + "darkIcon": "icon-dark.png", + "category": "Design & Sites", + "exampleQueries": [ + "把这个 STL 转成 1:1 打印图,标出螺丝孔距", + "出三视图和孔位表", + "这个零件的螺丝孔距是多少", + "哪些孔在底面看不到", + "帮我把 STEP 做成可打印图纸" + ], + "apps": [], + "mcpServers": [ + "servers.mcp.json" + ], + "skills": [ + "skills/cad-drawing/SKILL.md" + ], + "hooks": [] +} diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/LICENSE b/plugins/Xiong-cmyk-collab/cad-drawing/LICENSE new file mode 100644 index 00000000..125be1b8 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/LICENSE @@ -0,0 +1,192 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + Copyright 2026 MCode Plugins contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/README.md b/plugins/Xiong-cmyk-collab/cad-drawing/README.md new file mode 100644 index 00000000..1013a6cb --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/README.md @@ -0,0 +1,136 @@ +# CAD Drawing (3D to 1:1 printable drawings) + +Turn a 3D engineering file into a **1:1 printable A4 drawing**: top / front / left orthographic +views, overall dimensions, hole positions and pitches, and a per-hole verdict on whether it is +visible in those three views. + +Supported inputs: **STL**, **STEP** (.step/.stp), **IGES** and **3MF** (.3mf) — including +Bambu Studio, PrusaSlicer and Cura project packages. The plugin ships two MCP tools and one Skill. +Everything runs locally; the geometry never leaves the machine. + +## The problem it solves + +A mechanical part arrives as an STL or STEP export. Before cutting a prototype or measuring a +sample, someone needs to know the overall size, where the screw holes are, what their pitch is, +and — the part people usually forget — **which holes cannot be seen in the usual three views**. +A blind hole opening on the bottom face is invisible in a top view, and missing it means drilling +the wrong place. + +This plugin answers all of that in one pass and writes the answer to a printable PDF plus a +machine-readable hole table. + +## Try it + +```text +把这个 STL 转成 1:1 打印图,标出螺丝孔距 +``` + +```text +Convert this STEP file into an A4 1:1 drawing and list every hole that is not visible in the top, front and left views +``` + +## Expected result + +Three files next to the input file: + +| File | Content | +| --- | --- | +| `_打印图.pdf` | Overview page, then one **1:1** page per view (top / front / left, plus bottom / rear / right when a hole needs them), then a hole table with the visibility verdict. Views larger than A4 are tiled at 1:1 with alignment marks and a scaled overview page. | +| `_孔位明细.csv` | One row per hole: id, type, diameter, depth, X/Y/Z, owning view, visibility verdict. UTF-8 with BOM, opens directly in Excel. | +| `_特征.json` | Full geometry and feature report: bounding box, orientation transform, every hole, bosses, hole-pitch groups. | + +On a 200 × 60 × 21 mm board the result is a 6-page PDF: 34 holes detected, 20 visible in the +top view, 14 opening on the bottom face and therefore moved to an extra bottom-view page with an +explicit "look from the bottom" verdict. + +## Tools + +### `convert_to_drawing` + +Writes the three output files. + +| Parameter | Type | Required | Meaning | +| --- | --- | --- | --- | +| `file_path` | string | yes | Path to a `.stl` / `.3mf` / `.step` / `.stp` / `.iges` / `.igs` file | +| `output_dir` | string | no | Output directory; defaults to the input file's directory | +| `name` | string | no | Part name used for file names; defaults to the input file name | +| `orient` | `auto` \| `none` | no | `auto` (default) puts the thinnest axis on Z and the longest on X, and moves the bounding-box minimum corner to the origin, so drawing coordinates can be measured with calipers | + +### `inspect_holes` + +Geometry analysis only, writes nothing: the hole list with diameters, depths, axis coordinates, +through/blind classification, owning view, visibility verdict, and the hole-pitch groups. + +## How the judgement is made + +| Verdict | Meaning | +| --- | --- | +| Visible | The hole mouth faces that view and nothing blocks it | +| Needs bottom / rear / right view | The hole mouth faces a direction the three views do not cover. The plugin adds that view page and lists the hole separately | +| Blocked, needs a section | The hole mouth is covered by the part's own structure | +| Internal cavity, needs a section | The hole mouth is completely enclosed by material; no orthographic view can show it | +| Slanted hole, needs a local view | The hole axis is not parallel to any of the three view directions | + +Hole pitch is grouped by owning view, axis direction, height layer and diameter, so holes of +different sizes are never measured as one pattern. + +## Requirements + +- **Node.js 18 or newer** (the MCP server and the geometry engine run on Node). +- **Network**: none. The plugin never contacts a remote service. +- **Accounts / paid services**: none. +- **Platforms**: Windows, macOS and Linux. The drawing engine is pure JavaScript; PDF output uses + the bundled `pdfkit` dependency. STEP/IGES import uses the bundled `occt-import-js` + (OpenCascade compiled to WebAssembly), so no native CAD installation is needed. +- **One-time setup**: install the engine dependencies once per checkout: + + ```bash + cd scripts/cad2pdf + npm install + ``` + + Alternatively point the environment variable `CAD2PDF_TOOL_DIR` at an existing engine + installation and the plugin will use it instead of the bundled copy. + +- **Font**: the drawing page uses a Chinese-capable system font (`simhei.ttf`, `msyh.ttc` or + `simsun.ttc` on Windows). Without one, Chinese labels fall back to boxes. Any CJK font works; + the list is configurable in `scripts/cad2pdf/src/pdfout.js`. + +## Data and network + +- **Input**: the geometry file you pass in, read from disk. +- **Output**: the three files listed above, written to the output directory. +- **Network access**: none. The plugin makes no HTTP request and uploads nothing. +- **Telemetry**: none. +- **Credentials**: none are read, stored, or required. + +## What the drawings are and are not + +The drawing reports the geometry as measured from the file: overall dimensions, hole diameters, +hole depths, hole positions, hole pitches, and the visibility verdict. It does **not** infer +thread types, drill-point depth, material, tolerances, or surface finish — a threaded hole is +reported as a hole of its measured diameter. + +STL is a triangle mesh, so visible edges are reconstructed from facet creases and silhouettes. On +a faceted or noisy mesh the edge reconstruction can be imperfect; check the PDF visually before +using it as a machining reference. + +## Compatibility note + +This package ships three manifests on purpose: + +- `plugin.json` + `mcp.json` — the portable Agent Plugins 1.0 layout, read by MiniMax Code 0.3.x + and by other compatible runtimes. +- `.claude-plugin/plugin.json` — the MiniMax Code 0.4.0+ layout. +- `.minimax-plugin/plugin.json` — the MiniMax layout. It carries the extra fields + (`displayName`, `icon`, `darkIcon`, `category`, `exampleQueries`). + +**Installers that read only the portable `plugin.json` get the Skill and the MCP server, but not +the display name, icon, category or example queries** — those exist only in the MiniMax manifest. + +`skills/SKILL.md` is a byte-identical copy of `skills/cad-drawing/SKILL.md`, so both the 0.3.x +runtime and the 0.4.0+ runtime load the same instructions. + +## License + +Apache-2.0. See [LICENSE](LICENSE). diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/README.zh-CN.md b/plugins/Xiong-cmyk-collab/cad-drawing/README.zh-CN.md new file mode 100644 index 00000000..75c0044d --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/README.zh-CN.md @@ -0,0 +1,121 @@ +# CAD 打印图助手(3D 工程文件转 1:1 图纸) + +把 3D 工程文件转成 **A4 纸 1:1 可打印**的工程图:俯视 / 主视 / 左视三视图、总体尺寸、孔位与孔距, +以及**每个孔位在���三视图里能不能看见**的判定。 + +支持 **STL**、**STEP**(.step/.stp)、**IGES** 与 **3MF**(.3mf,含 Bambu Studio / PrusaSlicer / Cura +的切片工程包)。插件提供一个 Skill 和两个 MCP 工具,全程本地运行,几何数据不出本机。 + +## 解决什么问题 + +机械件到手只有 STL / STEP 导出文件时,做样板或核对实物之前,总要先弄清:整体多大、螺丝孔在哪儿、 +孔距多少,以及最容易被忽略的一条——**哪些孔在常规三视图里根本看不到**。底面开口的盲孔在俯视图上 +是不存在的,漏掉它就意味着钻错位置。 + +这个插件一次跑完,并把答案写成可打印的 PDF 加一份机读孔位表。 + +## 怎么用 + +```text +把这个 STL 转成 1:1 打印图,标出螺丝孔距 +``` + +```text +把这个 STEP 转成 A4 1:1 图纸,并列出所有在俯视、主视、左视里看不到的孔 +``` + +## 预期结果 + +在输入文件旁边生成三个文件: + +| 文件 | 内容 | +| --- | --- | +| `<零件名>_打印图.pdf` | 概览页 → 各视图 **1:1** 页(俯视 / 主视 / 左视;孔位需要时追加底视 / 后视 / 右视)→ 孔位明细表(含可见性判定)。视图超过 A4 时按 1:1 分块拼接并给出接缝标记,另出一张整件缩略页。 | +| `<零件名>_孔位明细.csv` | 每个孔一行:编号、类型、直径、深度、XYZ、归属视图、可见性判定。UTF-8 带 BOM,Excel 直接打开。 | +| `<零件名>_特征.json` | 完整几何与特征报告:包围盒、定向变换、全部孔位、凸台、孔距分组。 | + +以一块 200 × 60 × 21 mm 的板件为例,产出 6 页 PDF:识别 34 个孔,其中 20 个在俯视图可见, +14 个底面开口 → 自动追加底视图页,并逐条标注「需翻面查看」。 + +## 工具 + +### `convert_to_drawing` + +生成上面三个文件。 + +| 参数 | 类型 | 必填 | 含义 | +| --- | --- | --- | --- | +| `file_path` | string | 是 | `.stl` / `.3mf` / `.step` / `.stp` / `.iges` / `.igs` 文件路径 | +| `output_dir` | string | 否 | 输出目录,默认与输入文件同目录 | +| `name` | string | 否 | 零件名,决定文件名,默认取输入文件名 | +| `orient` | `auto` \| `none` | 否 | `auto`(默认)把最薄轴摆到 Z、最长轴摆到 X,并把包围盒最小角点平移到原点,图纸坐标可直接用卡尺量 | + +### `inspect_holes` + +只做几何分析、不落盘:孔位清单(直径、深度、轴心坐标)、通孔/盲孔判定、归属视图、可见性判定、 +孔距分组。 + +## 判定依据 + +| 判定 | 含义 | +| --- | --- | +| 可见 | 孔口朝向该视图且无遮挡 | +| 需底视 / 后视 / 右视 | 孔口朝向三视图未覆盖的方向 → 自动追加该视图页并单列这些孔 | +| 被遮挡·需剖视 | 孔口方向被零件自身结构挡住 | +| 内部封闭腔·需剖视 | 孔口被材料完全包围,任何正投影都看不到 | +| 斜向孔·需局部视图 | 孔轴线与三个视图方向均不平行 | + +孔距按「归属视图 + 轴向 + 高度层 + 直径」分组,不同直径的孔不会被算成同一个阵列。 + +## 运行要求 + +- **Node.js 18 及以上**(MCP 服务与几何引擎均用 Node 运行)。 +- **网络**:不需要。本插件不访问任何远程服务。 +- **账号 / 付费服务**:不需要。 +- **平台**:Windows / macOS / Linux 均可。绘图引擎是纯 JavaScript,PDF 输出使用内置的 `pdfkit`; + STEP/IGES 导入使用内置的 `occt-import-js`(OpenCascade 的 WebAssembly 版本),**不需要装原生 CAD 软件**。 +- **一次性准备**:每个 checkout 执行一次 + + ```bash + cd scripts/cad2pdf + npm install + ``` + + 也可以把环境变量 `CAD2PDF_TOOL_DIR` 指向已有的引擎安装目录,插件就会改用它。 + +- **字体**:图面用系统中文字体(Windows 上的 `simhei.ttf` / `msyh.ttc` / `simsun.ttc`)。缺字体时中文会 + 显示为方框;字体清单可在 `scripts/cad2pdf/src/pdfout.js` 里改。 + +## 数据与网络行为 + +- **输入**:你传入的几何文件,从磁盘读取。 +- **输出**:上面列出的三个文件,写到输出目录。 +- **网络访问**:无。不发起任何 HTTP 请求,不上传任何数据。 +- **遥测**:无。 +- **凭据**:不读取、不存储、也不需要任何凭据。 + +## 图纸能说明什么、不能说明什么 + +图纸给出的是**从文件实测到的几何**:总体尺寸、孔径、孔深、孔位、孔距,以及可见性判定。 +它**不会**推断螺纹类型、钻尖深度、材料、公差或表面粗糙度——螺纹孔按实测直径的孔报告。 + +STL 是三角面数据,可见棱边由折边与轮廓转折重建;面数粗或网格有噪声时棱边可能有偏差, +当加工依据使用前请先目视核对 PDF。 + +## 兼容性说明 + +本包刻意带了三份清单: + +- `plugin.json` + `mcp.json` —— 可移植的 Agent Plugins 1.0 布局,MiniMax Code 0.3.x 与其他兼容运行时读取。 +- `.claude-plugin/plugin.json` —— MiniMax Code 0.4.0+ 布局。 +- `.minimax-plugin/plugin.json` —— MiniMax 布局,额外带 `displayName`、`icon`、`darkIcon`、`category`、 + `exampleQueries`。 + +**只读取可移植 `plugin.json` 的安装方,能拿到 Skill 和 MCP 服务,但拿不到显示名、图标、分类与示例指令**—— +这些字段只存在于 MiniMax 清单里。 + +`skills/SKILL.md` 与 `skills/cad-drawing/SKILL.md` 是逐字节相同的两份,0.3.x 与 0.4.0+ 运行时加载的是同一份说明。 + +## 许可证 + +Apache-2.0,见 [LICENSE](LICENSE)。 diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/icon-dark.png b/plugins/Xiong-cmyk-collab/cad-drawing/icon-dark.png new file mode 100644 index 00000000..c3b799a8 Binary files /dev/null and b/plugins/Xiong-cmyk-collab/cad-drawing/icon-dark.png differ diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/icon.png b/plugins/Xiong-cmyk-collab/cad-drawing/icon.png new file mode 100644 index 00000000..69d25b99 Binary files /dev/null and b/plugins/Xiong-cmyk-collab/cad-drawing/icon.png differ diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/mcp.json b/plugins/Xiong-cmyk-collab/cad-drawing/mcp.json new file mode 100644 index 00000000..25389b02 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/mcp.json @@ -0,0 +1,13 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json", + "mcpServers": { + "cad-drawing": { + "type": "stdio", + "command": "node", + "args": [ + "./mcp/server.js" + ], + "env": {} + } + } +} diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/mcp/server.js b/plugins/Xiong-cmyk-collab/cad-drawing/mcp/server.js new file mode 100644 index 00000000..c783aed5 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/mcp/server.js @@ -0,0 +1,224 @@ +#!/usr/bin/env node +'use strict'; +// cad-drawing MCP 服务(stdio / JSON-RPC 2.0,零第三方依赖) +// 把 3D 工程文件(STL / STEP)转成 1:1 可打印 A4 图纸,并给出孔位可见性判定。 +// +// 工具核心位置解析顺序: +// 1) 环境变量 CAD2PDF_TOOL_DIR +// 2) 默认安装目录 scripts/cad2pdf +// 3) 插件内自带副本 /scripts/cad2pdf + +const fs = require('fs'); +const path = require('path'); +const readline = require('readline'); + +const SERVER_NAME = 'cad-drawing'; +const SERVER_VERSION = '1.0.0'; +const SUPPORTED_PROTOCOLS = ['2025-06-18', '2025-03-26', '2024-11-05']; + +function resolveToolDir() { + const candidates = [ + process.env.CAD2PDF_TOOL_DIR, + path.join(__dirname, '..', 'scripts', 'cad2pdf'), + ].filter(Boolean); + for (const dir of candidates) { + const lib = path.join(dir, 'src', 'lib.js'); + if (fs.existsSync(lib)) return dir; + } + return null; +} + +let lib = null; +function getLib() { + if (lib) return lib; + const dir = resolveToolDir(); + if (!dir) { + throw new Error('cad2pdf engine not found. Run npm install inside scripts/cad2pdf, or set CAD2PDF_TOOL_DIR to an engine directory.'); + } + try { + lib = require(path.join(dir, 'src', 'lib.js')); + } catch (e) { + throw new Error('Engine dependencies are not installed. Run npm install inside scripts/cad2pdf, or set CAD2PDF_TOOL_DIR to an engine directory that already has them.'); + } + return lib; +} + +// ---------- 工具定义 ---------- +const TOOLS = [ + { + name: 'convert_to_drawing', + description: '把 3D 工程文件(.stl/.step/.stp/.iges)转成 1:1 可打印 A4 工程图 PDF(俯视/主视/左视三视图 + 孔位明细表 + 可见性判定),同时输出孔位 CSV 与特征 JSON。返回产出路径、页数、孔位统计与逐孔判定。', + inputSchema: { + type: 'object', + properties: { + file_path: { type: 'string', description: '3D 工程文件绝对路径(.stl / .step / .stp / .iges / .igs)' }, + output_dir: { type: 'string', description: '输出目录;省略则输出到输入文件所在目录' }, + name: { type: 'string', description: '零件名(决定文件名);省略则取文件名' }, + orient: { type: 'string', enum: ['auto', 'none'], description: '自动摆正(厚度轴→Z、长轴→X);默认 auto' }, + }, + required: ['file_path'], + }, + }, + { + name: 'inspect_holes', + description: '只做几何分析不落盘:识别零件上的孔位,给出每个孔的直径、深度、轴心坐标、通孔/盲孔类型、归属视图与可见性判定,并给出孔距阵列分组。用于在正式出图前先确认识别结果。', + inputSchema: { + type: 'object', + properties: { + file_path: { type: 'string', description: '3D 工程文件绝对路径' }, + orient: { type: 'string', enum: ['auto', 'none'], description: '自动摆正开关;默认 auto' }, + }, + required: ['file_path'], + }, + }, +]; + +// ---------- 工具实现 ---------- +async function runConvert(args) { + const file = String(args.file_path || '').trim(); + if (!file) throw new Error('缺少参数 file_path'); + if (!fs.existsSync(file)) throw new Error('文件不存在:' + file); + const l = getLib(); + const r = await l.convert(file, { + outputDir: args.output_dir, + name: args.name, + orient: args.orient || 'auto', + }); + const lines = []; + lines.push(`已生成:${r.pdfPath}`); + lines.push(`孔位 CSV:${r.csvPath}`); + lines.push(`特征 JSON:${r.jsonPath}`); + lines.push(''); + lines.push(`零件:${r.meta.name} 外形:${r.meta.sizeText} 定向:${r.meta.orientation}`); + lines.push(`孔位 ${r.counts.holes} 个(可见 ${r.counts.visible} / 需翻面 ${r.counts.needFlip} / 内部不可见 ${r.counts.invisible})`); + if (r.extraViews.length) lines.push(`追加视图:${r.extraViews.join('、')}`); + if (r.patterns.length) { + lines.push('孔距阵列:'); + for (const p of r.patterns) { + lines.push(` - ${p.view} ${p.count} 孔 Ø${p.diameter} X ${p.du !== null ? p.du.toFixed(2) + 'mm' : '不均匀'} Y ${p.dv !== null ? p.dv.toFixed(2) + 'mm' : '不均匀'}`); + } + } + const needFlip = r.holes.filter(h => /需(底|后|右)视图|剖视|局部/.test(h.judge)); + if (needFlip.length) { + lines.push(''); + lines.push('需单独核对(不在三视图内):'); + for (const h of needFlip) lines.push(` ${h.label} Ø${h.diameter.toFixed(2)} ${h.view} ${h.judge}`); + } + const payload = { + pdf_path: r.pdfPath, csv_path: r.csvPath, json_path: r.jsonPath, + meta: r.meta, counts: r.counts, extra_views: r.extraViews, + patterns: r.patterns, holes: r.holes, + }; + return { text: lines.join('\n'), payload }; +} + +async function runInspect(args) { + const file = String(args.file_path || '').trim(); + if (!file) throw new Error('缺少参数 file_path'); + if (!fs.existsSync(file)) throw new Error('文件不存在:' + file); + const l = getLib(); + const r = await l.analyze(file, { orient: args.orient || 'auto' }); + const lines = []; + lines.push(`零件外形:${r.mesh.size.map(x => x.toFixed(2)).join(' × ')} mm 定向:${r.transform.description}`); + lines.push(`孔位 ${r.counts.holes} 个(可见 ${r.counts.visible} / 需翻面 ${r.counts.needFlip} / 内部不可见 ${r.counts.invisible})`); + lines.push(''); + lines.push('编号\t类型\t直径\t深度\tX\tY\tZ\t归属视图\t判定'); + for (const h of r.holes) { + lines.push([ + h.label, h.type, h.diameter.toFixed(2), h.length.toFixed(2), + h.center[0].toFixed(2), h.center[1].toFixed(2), h.center[2].toFixed(2), + h.judge && h.judge.viewName ? h.judge.viewName : '—', + h.judge ? (h.judge.short || h.judge.reason) : '', + ].join('\t')); + } + const payload = { + bbox: r.mesh.bbox, transform: r.transform, counts: r.counts, + holes: r.holes.map(h => ({ + label: h.label, type: h.type, diameter: +h.diameter.toFixed(2), depth: +h.length.toFixed(2), + center: h.center.map(x => +x.toFixed(2)), + view: h.judge && h.judge.viewName ? h.judge.viewName : '—', + judge: h.judge ? h.judge.reason : '', + })), + patterns: r.patterns.map(p => ({ view: p.view, count: p.count, diameter: +p.diameter.toFixed(2), du: p.uniformDu, dv: p.uniformDv })), + }; + return { text: lines.join('\n'), payload }; +} + +// ---------- JSON-RPC 处理 ---------- +function send(obj) { + process.stdout.write(JSON.stringify(obj) + '\n'); +} + +function ok(id, result) { + if (id === undefined || id === null) return; // 通知不回包 + send({ jsonrpc: '2.0', id, result }); +} + +function fail(id, message, code = -32000) { + if (id === undefined || id === null) return; + send({ jsonrpc: '2.0', id, error: { code, message } }); +} + +async function handle(msg) { + const { id, method, params } = msg; + switch (method) { + case 'initialize': { + const want = params && params.protocolVersion; + const proto = SUPPORTED_PROTOCOLS.includes(want) ? want : SUPPORTED_PROTOCOLS[0]; + ok(id, { + protocolVersion: proto, + capabilities: { tools: { listChanged: false } }, + serverInfo: { name: SERVER_NAME, version: SERVER_VERSION }, + }); + return; + } + case 'ping': + ok(id, {}); + return; + case 'notifications/initialized': + case 'initialized': + return; // 通知,不回包 + case 'tools/list': + ok(id, { tools: TOOLS }); + return; + case 'tools/call': { + const name = params && params.name; + const args = (params && params.arguments) || {}; + try { + let out; + if (name === 'convert_to_drawing') out = await runConvert(args); + else if (name === 'inspect_holes') out = await runInspect(args); + else throw new Error('未知工具:' + name); + ok(id, { + content: [{ type: 'text', text: out.text }], + structuredContent: out.payload, + isError: false, + }); + } catch (e) { + ok(id, { + content: [{ type: 'text', text: `执行失败:${e.message}` }], + isError: true, + }); + } + return; + } + case 'resources/list': + ok(id, { resources: [] }); + return; + case 'prompts/list': + ok(id, { prompts: [] }); + return; + default: + fail(id, `不支持的方法:${method}`, -32601); + } +} + +const rl = readline.createInterface({ input: process.stdin, terminal: false }); +rl.on('line', (line) => { + const s = line.trim(); + if (!s) return; + let msg; + try { msg = JSON.parse(s); } catch (e) { return; } + Promise.resolve(handle(msg)).catch(e => fail(msg && msg.id, e.message)); +}); +rl.on('close', () => process.exit(0)); diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/plugin.json b/plugins/Xiong-cmyk-collab/cad-drawing/plugin.json new file mode 100644 index 00000000..3e48d36b --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/plugin.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", + "name": "cad-drawing", + "version": "1.1.0", + "description": "Convert 3D engineering files (STL/STEP/3MF) into 1:1 printable A4 drawings with top/front/left orthographic views, overall dimensions, hole positions and pitches, and a per-hole verdict on whether it is visible in those three views. / 把 3D 工程文件转成 1:1 可打印 A4 图纸:俯视/主视/左视三视图、总体尺寸、孔位与孔距标注,并逐孔判定在这三视图里是否可见。", + "author": { + "name": "Xiong-cmyk-collab", + "url": "https://github.com/Xiong-cmyk-collab" + }, + "homepage": "https://github.com/Xiong-cmyk-collab/MiniMax-Code-Plugins/tree/main/plugins/Xiong-cmyk-collab/cad-drawing", + "repository": "https://github.com/Xiong-cmyk-collab/MiniMax-Code-Plugins.git", + "license": "Apache-2.0", + "keywords": [ + "minimax-code", + "plugin", + "cad", + "stl", + "step", + "technical-drawing", + "hole-detection", + "3d-printing" + ] +} diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/package.json b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/package.json new file mode 100644 index 00000000..a8f7ea96 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/package.json @@ -0,0 +1,15 @@ +{ + "name": "cad2pdf-core", + "version": "1.1.0", + "private": true, + "description": "Geometry engine behind the cad-drawing Plugin: parses STL/STEP/3MF, detects holes, and writes 1:1 printable A4 drawings.", + "main": "src/lib.js", + "scripts": { + "convert": "node src/cli.js", + "test": "node --test test" + }, + "dependencies": { + "pdfkit": "^0.15.0", + "occt-import-js": "^0.0.23" + } +} diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/cli.js b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/cli.js new file mode 100644 index 00000000..bcafdf3a --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/cli.js @@ -0,0 +1,46 @@ +'use strict'; +// cad2pdf 命令行入口:3D 工程文件(STL / STEP)→ 1:1 可打印 A4 工程图(PDF) +// +// 用法: +// node src/cli.js <输入文件.stl|.step> [--out 输出目录] [--name 零件名] [--orient auto|none] +// +// 输出: +// <零件名>_打印图.pdf 三视图(1:1) + 孔位明细表 + 可见性判定 +// <零件名>_孔位明细.csv 孔位数据(可再导入 Excel) +// <零件名>_特征.json 完整几何/特征报告 + +const fs = require('fs'); +const path = require('path'); +const { convert } = require('./lib'); + +function parseArgs(argv) { + const args = { input: null, out: null, name: null, orient: 'auto' }; + for (let i = 0; i < argv.length; i++) { + const a = argv[i]; + if (a === '--out' || a === '-o') args.out = argv[++i]; + else if (a === '--name' || a === '-n') args.name = argv[++i]; + else if (a === '--orient') args.orient = argv[++i]; + else if (!a.startsWith('-') && !args.input) args.input = a; + } + return args; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + if (!args.input) { + console.error('用法:node src/cli.js <输入文件.stl|.step> [--out 输出目录] [--name 零件名]'); + process.exit(1); + } + const input = path.resolve(args.input); + if (!fs.existsSync(input)) { console.error('文件不存在:' + input); process.exit(1); } + + const r = await convert(input, { outputDir: args.out, name: args.name, orient: args.orient }); + console.log(`完成:${r.pdfPath}`); + console.log(`孔位 ${r.counts.holes} 个(可见 ${r.counts.visible} / 需翻面 ${r.counts.needFlip} / 内部不可见 ${r.counts.invisible})`); + console.log(`附加视图:${r.extraViews.join(',') || '无'}`); + console.log(`孔距阵列 ${r.patterns.length} 组`); + console.log(`CSV:${r.csvPath}`); + console.log(`JSON:${r.jsonPath}`); +} + +main().catch(e => { console.error('错误:' + e.message); if (process.env.DEBUG_STACK) console.error(e.stack); process.exit(1); }); diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/features.js b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/features.js new file mode 100644 index 00000000..e3ba4961 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/features.js @@ -0,0 +1,399 @@ +'use strict'; +// 特征识别:圆柱面拟合 → 孔 / 凸台分类 → 通孔盲孔判定 → 三视图可见性判断 → 孔距阵列分析。 + +const M = require('./mesh'); + +const CREASE = 0.90; // 折边判定余弦阈值 +const CYL_SPREAD_MIN = 0.15; // 法向在垂直轴平面上的展开度下限(区分平面与圆柱面) +const CYL_AXIS_MAX = 0.06; // 法向垂直于轴线的程度上限 +const MIN_RADIUS = 0.4; // 最小有效半径 mm +const MIN_AREA = 1.0; // 区域最小面积 mm^2 + +// 主视/俯视/左视的观察方向(从物体指向观察者) +const VIEW_DIRS = { + top: [0, 0, 1], + front: [0, -1, 0], + left: [-1, 0, 0], +}; + +// ---------- 圆柱面拟合 ---------- +function fitCylinder(mesh, faceIdxs) { + const C = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]; + let area = 0; + let cx = 0, cy = 0, cz = 0; + for (const fi of faceIdxs) { + const f = mesh.faces[fi]; + area += f.area; + for (let i = 0; i < 3; i++) { + for (let j = 0; j < 3; j++) C[i][j] += f.area * f.n[i] * f.n[j]; + } + cx += f.c[0] * f.area; cy += f.c[1] * f.area; cz += f.c[2] * f.area; + } + if (area < MIN_AREA) return null; + const centroid = [cx / area, cy / area, cz / area]; + const { values, vectors } = M.eigenSym3(C); + const l0 = values[0], l1 = values[1], l2 = values[2]; + if (l2 <= 1e-9) return null; + if (l0 / l2 > CYL_AXIS_MAX) return null; // 法向不垂直于候选轴 → 不是圆柱面 + if (l1 / l2 < CYL_SPREAD_MIN) return null; // 法向未在 2D 平面展开 → 是平面 + const axis = vectors[0]; + + // 构造垂直于轴线的正交基 + let ref = Math.abs(axis[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]; + const e1 = M.norm(M.cross(ref, axis)); + const e2 = M.norm(M.cross(axis, e1)); + + // 顶点投影 + 圆拟合 + const pts = []; + const vset = new Set(); + for (const fi of faceIdxs) for (const vi of mesh.faces[fi].v) vset.add(vi); + for (const vi of vset) { + const p = [mesh.vpos[vi * 3], mesh.vpos[vi * 3 + 1], mesh.vpos[vi * 3 + 2]]; + const d = M.sub(p, centroid); + pts.push([M.dot(d, e1), M.dot(d, e2)]); + } + if (pts.length < 6) return null; + const fit = M.circleFit(pts); + if (!fit) return null; + if (fit.r < MIN_RADIUS) return null; + const tol = Math.max(0.03, fit.r * 0.04); + if (fit.residual > tol) return null; + + const center = [ + centroid[0] + e1[0] * fit.cx + e2[0] * fit.cy, + centroid[1] + e1[1] * fit.cx + e2[1] * fit.cy, + centroid[2] + e1[2] * fit.cx + e2[2] * fit.cy, + ]; + const axisPoint = (t) => [ + center[0] + axis[0] * t, center[1] + axis[1] * t, center[2] + axis[2] * t, + ]; + + // 轴向范围 + let t0 = Infinity, t1 = -Infinity; + for (const vi of vset) { + const p = [mesh.vpos[vi * 3], mesh.vpos[vi * 3 + 1], mesh.vpos[vi * 3 + 2]]; + const t = M.dot(M.sub(p, center), axis); + if (t < t0) t0 = t; + if (t > t1) t1 = t; + } + + // 孔 / 凸台判定:法向与径向方向的内积符号 + let sign = 0; + for (const fi of faceIdxs) { + const f = mesh.faces[fi]; + const rel = M.sub(f.c, center); + const along = M.dot(rel, axis); + const radial = M.sub(rel, M.mul(axis, along)); + const rl = M.len(radial); + if (rl < 1e-9) continue; + sign += M.dot(f.n, M.mul(radial, 1 / rl)) * f.area; + } + const isHole = sign < 0; + + return { + axis, e1, e2, center, axisPoint, radius: fit.r, residual: fit.residual, + area, t0, t1, length: t1 - t0, isHole, faceIdxs, vertSet: vset, + }; +} + +// ---------- 通孔 / 盲孔判定 ---------- +// 孔口判定同时满足两个条件: +// ① 越出端面后射线不被遮挡(空腔确实延续出去) +// ② 孔口侧向 8 个方向基本是自由空间(孔口开在外表面,而非被材料包住的腔体内部) +function classifyEnds(cyl, tris, diag) { + const eps = 0.08; + const reach = Math.max(1.5, cyl.radius * 1.2); + + const probeEnd = (t, outward) => { + const origin = cyl.axisPoint(t + outward * eps); + const hit = M.rayHit(tris, origin, outward); + const open = hit === null; + // 侧向暴露度:从孔口沿垂直于轴线的 8 个方向探测 + let free = 0; + let ref = Math.abs(outward[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]; + const u1 = M.norm(M.cross(ref, outward)); + const u2 = M.norm(M.cross(outward, u1)); + const mouth = cyl.axisPoint(t); + for (let k = 0; k < 8; k++) { + const a = (k / 8) * Math.PI * 2; + const d = M.norm([ + u1[0] * Math.cos(a) + u2[0] * Math.sin(a), + u1[1] * Math.cos(a) + u2[1] * Math.sin(a), + u1[2] * Math.cos(a) + u2[2] * Math.sin(a), + ]); + const h = M.rayHit(tris, M.add(mouth, M.mul(outward, 0.02)), d); + if (h === null || h > reach) free++; + } + return { open, free, isMouth: open && free >= 3 }; + }; + + const lo = probeEnd(cyl.t0, [-cyl.axis[0], -cyl.axis[1], -cyl.axis[2]]); + const hi = probeEnd(cyl.t1, cyl.axis); + const openings = []; + if (lo.isMouth) openings.push({ dir: [-cyl.axis[0], -cyl.axis[1], -cyl.axis[2]], point: cyl.axisPoint(cyl.t0), side: 'lo', exposure: lo.free }); + if (hi.isMouth) openings.push({ dir: cyl.axis, point: cyl.axisPoint(cyl.t1), side: 'hi', exposure: hi.free }); + const type = openings.length === 2 ? '通孔' : openings.length === 1 ? '盲孔' : '内部腔体'; + return { type, openings, lo, hi }; +} + +// ---------- 可见性判断 ---------- +function judgeVisibility(hole, tris, diag) { + const openings = hole.openings || []; + if (!openings.length) { + return { + view: null, viewName: null, visible: false, blocked: true, + placement: '内部封闭腔', short: '内部封闭腔·需剖视', + reason: '孔口被材料完全包围(封闭腔体),三视图均不可见', + }; + } + const views = [ + { key: 'top', name: '俯视图', dir: VIEW_DIRS.top }, + { key: 'front', name: '主视图', dir: VIEW_DIRS.front }, + { key: 'left', name: '左视图', dir: VIEW_DIRS.left }, + ]; + const opposite = { top: '底视图', front: '后视图', left: '右视图' }; + const oppositeKey = { top: 'bottom', front: 'back', left: 'right' }; + + const blockedAt = (o) => { + const p = M.add(o.point, M.mul(o.dir, 0.05)); + const hit = M.rayHit(tris, p, o.dir); + return hit !== null && hit < diag * 2; + }; + + const best = openings.reduce((a, b) => ((b.exposure || 0) > (a.exposure || 0) ? b : a)); + const placement = (best.exposure || 0) >= 6 ? '外表面' : (best.exposure || 0) >= 3 ? '凹槽/腔体内' : '内部封闭腔'; + + // 优先匹配三视图方向的开口 + for (const v of views) { + for (const o of openings) { + if (M.dot(o.dir, v.dir) > 0.86) { + const blocked = blockedAt(o); + return { + view: v.key, viewName: v.name, visible: !blocked, blocked, placement, + short: blocked ? '被遮挡·需剖视' : '可见', + reason: blocked + ? `开口方向被自身结构遮挡(${v.name}不可见),需剖视或局部放大` + : `${v.name}可见`, + }; + } + } + } + // 开口朝向未包含的视图 + for (const v of views) { + for (const o of openings) { + if (M.dot(o.dir, M.mul(v.dir, -1)) > 0.86) { + const blocked = blockedAt(o); + return { + view: oppositeKey[v.key], viewName: opposite[v.key], visible: false, blocked, placement, + short: blocked ? '被遮挡·需剖视' : `需${opposite[v.key]}`, + reason: blocked + ? `开口朝向${opposite[v.key]}且被结构遮挡,三视图均不可见,需剖视或局部放大` + : `开口朝向${opposite[v.key]},本套三视图未包含,需翻面查看`, + }; + } + } + } + // 斜向孔 + const o = openings[0]; + const blocked = blockedAt(o); + return { + view: null, viewName: null, visible: false, blocked, placement, + short: blocked ? '被遮挡·需剖视' : '斜向孔·需局部视图', + reason: blocked ? '孔轴线与三视方向均不平行,且开口方向被结构遮挡' : '孔轴线与三视方向均不平行(斜向孔)', + }; +} + +// ---------- 合并同轴同径的圆柱面 ---------- +function mergeCylinders(list) { + const merged = []; + for (const c of list) { + let target = null; + for (const m of merged) { + const axisDot = Math.abs(M.dot(m.cyl.axis, c.axis)); + if (axisDot < 0.995) continue; + const d = M.len(M.sub(m.cyl.center, c.center)); + if (d > Math.max(0.15, c.radius * 0.15)) continue; + const dr = Math.abs(m.cyl.radius - c.radius); + if (dr > Math.max(0.08, c.radius * 0.06)) continue; + target = m; break; + } + if (target) { + target.cyl.length = Math.max(target.cyl.length, c.length); + target.cyl.t0 = Math.min(target.cyl.t0, c.t0); + target.cyl.t1 = Math.max(target.cyl.t1, c.t1); + target.cyl.area += c.area; + target.parts.push(c); + } else { + merged.push({ cyl: { ...c }, parts: [c] }); + } + } + return merged; +} + +// 沉孔识别:同轴不同径且轴向重叠或首尾相接(台阶孔:沉孔段 + 内孔段) +// 同轴判定比的是径向距离(垂直于孔轴),不能比三维中心距——同轴孔的中心沿轴线是错开的 +function markCounterbores(list) { + for (const a of list) { + for (const b of list) { + if (a === b) continue; + if (Math.abs(M.dot(a.axis, b.axis)) < 0.995) continue; + const delta = M.sub(a.center, b.center); + const axis = a.axis; + const radial = M.sub(delta, M.mul(axis, M.dot(delta, axis))); + if (M.len(radial) > 0.2) continue; + const big = a.radius > b.radius ? a : b; + const small = big === a ? b : a; + const overlap = Math.min(big.t1, small.t1) - Math.max(big.t0, small.t0); + if (overlap > -0.06) { + big.counterbore = true; + big.counterboreOf = small; // 沉孔段 → 指向内孔段 + small.counterboreOf = big; // 内孔段 → 指向上方沉孔段 + } + } + } +} + +// ---------- 主流程 ---------- +function detectFeatures(mesh) { + const tris = M.triangles(mesh); + const diag = Math.hypot(mesh.size[0], mesh.size[1], mesh.size[2]) || 1; + const cylinders = []; + mesh.regions.forEach((faces, ri) => { + const c = fitCylinder(mesh, faces); + if (c) cylinders.push(c); + }); + + const merged = mergeCylinders(cylinders); + const features = []; + for (const m of merged) { + const ends = classifyEnds(m.cyl, tris, diag); + const feat = { + id: 0, + kind: m.cyl.isHole ? 'hole' : 'boss', + type: m.cyl.isHole ? ends.type : '外圆/凸台', + axis: m.cyl.axis, + center: m.cyl.center, + radius: m.cyl.radius, + diameter: m.cyl.radius * 2, + length: m.cyl.length, + t0: m.cyl.t0, + t1: m.cyl.t1, + openOutward: ends.openings.length ? ends.openings[0].dir : null, + openings: ends.openings, + counterbore: false, + area: m.cyl.area, + }; + features.push(feat); + } + markCounterbores(features); + + // 编号:孔优先,按可见视图顺序 + 坐标 + const holes = features.filter(f => f.kind === 'hole'); + const viewRank = { top: 0, front: 1, left: 2 }; + for (const f of holes) { + f.judge = judgeVisibility(f, tris, diag); + if (f.counterbore) { + f.type = '沉孔/台阶孔'; + } else if (f.counterboreOf) { + f.type = `${f.type}·带Φ${f.counterboreOf.diameter.toFixed(2)}沉孔`; + } + } + holes.sort((a, b) => { + const ra = viewRank[a.judge.view] ?? 9; + const rb = viewRank[b.judge.view] ?? 9; + if (ra !== rb) return ra - rb; + if (Math.abs(a.center[2] - b.center[2]) > 0.01) return b.center[2] - a.center[2]; + return a.center[0] - b.center[0]; + }); + holes.forEach((f, i) => { f.id = i + 1; f.label = 'H' + (i + 1); }); + + const bosses = features.filter(f => f.kind === 'boss'); + bosses.forEach((f, i) => { f.id = 100 + i; f.label = 'B' + (i + 1); }); + + return { holes, bosses, cylinders: merged, tris }; +} + +// ---------- 孔距阵列分析 ---------- +// 按「归属视图 + 轴向 + 高度层」分组,避免不同直径/不同层的孔混在一起算孔距 +function analyzePatterns(holes, bboxMin) { + const groups = new Map(); + for (const h of holes) { + if (!h.judge || !h.judge.view) continue; + const axisKey = h.axis.map(x => (x > 0.9 ? '+' : x < -0.9 ? '-' : '0')).join(''); + const key = h.judge.view + '|' + axisKey; + if (!groups.has(key)) groups.set(key, []); + groups.get(key).push(h); + } + const patterns = []; + for (const [key, list] of groups) { + if (list.length < 2) continue; + const view = key.split('|')[0]; + // 按 z 分层(1mm 容差) + const layers = []; + for (const h of [...list].sort((a, b) => a.center[2] - b.center[2])) { + const lay = layers.find(l => Math.abs(l.z - h.center[2]) < 1.0); + if (lay) { lay.holes.push(h); lay.z = (lay.z * (lay.holes.length - 1) + h.center[2]) / lay.holes.length; } + else layers.push({ z: h.center[2], holes: [h] }); + } + for (const lay of layers) { + if (lay.holes.length < 2) continue; + // 同层内再按直径细分(不同直径 = 不同规格,孔距分开算) + const byDia = []; + for (const h of lay.holes) { + const g = byDia.find(x => Math.abs(x.d - h.diameter) < 0.05); + if (g) g.holes.push(h); + else byDia.push({ d: h.diameter, holes: [h] }); + } + for (const grp of byDia) { + if (grp.holes.length < 2) continue; + const us = clusterValues(grp.holes.map(h => h.center[0]), 0.3); + const vs = clusterValues(grp.holes.map(h => h.center[1]), 0.3); + const du = diffs(us); + const dv = diffs(vs); + const grid = us.length >= 2 && vs.length >= 2; + const uniformDu = grid ? uniformOf(du) : null; + const uniformDv = grid ? uniformOf(dv) : null; + patterns.push({ + view, + z: lay.z, + count: grp.holes.length, + uValues: us, + vValues: vs, + du, + dv, + uniformDu, + uniformDv, + grid, + holes: grp.holes.map(h => h.id), + diameter: grp.d, + diameters: [...new Set(grp.holes.map(h => h.diameter.toFixed(2)))], + }); + } + } + } + return patterns; +} + +function uniformOf(arr) { + if (!arr.length) return null; + const avg = arr.reduce((a, b) => a + b, 0) / arr.length; + return arr.every(x => Math.abs(x - avg) < 0.2) ? avg : null; +} + +function clusterValues(vals, tol) { + const sorted = [...vals].sort((a, b) => a - b); + const out = []; + for (const v of sorted) { + if (!out.length || Math.abs(v - out[out.length - 1]) > tol) out.push(v); + else out[out.length - 1] = (out[out.length - 1] + v) / 2; + } + return out; +} + +function diffs(sorted) { + const d = []; + for (let i = 1; i < sorted.length; i++) d.push(sorted[i] - sorted[i - 1]); + return d; +} + +module.exports = { detectFeatures, analyzePatterns, VIEW_DIRS }; diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/lib.js b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/lib.js new file mode 100644 index 00000000..0ffdeb05 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/lib.js @@ -0,0 +1,128 @@ +'use strict'; +// cad2pdf 核心库:供命令行与 MCP 服务共同调用。 +// 职责:解析几何 → 自动摆正 → 孔位识别与判定 → 孔距分析 → 产出 PDF / CSV / JSON。 + +const fs = require('fs'); +const path = require('path'); +const { parseSTL } = require('./stl'); +const { parse3MF } = require('./mf3mf'); +const { loadSTEP } = require('./step'); +const { buildMesh } = require('./mesh'); +const { canonicalize } = require('./orient'); +const { detectFeatures, analyzePatterns } = require('./features'); +const { buildView } = require('./views'); +const { renderPDF } = require('./pdfout'); + +async function loadModel(input) { + const ext = path.extname(input).toLowerCase(); + if (ext === '.stl') return parseSTL(fs.readFileSync(input)); + if (ext === '.3mf') return parse3MF(fs.readFileSync(input)); + if (ext === '.step' || ext === '.stp' || ext === '.iges' || ext === '.igs') return await loadSTEP(input); + throw new Error('仅支持 .stl / .3mf / .step / .stp / .iges / .igs,当前:' + ext); +} + +// 解析 + 识别 + 判定(不落盘) +async function analyze(input, opts = {}) { + const raw = await loadModel(input); + const canon = canonicalize(raw, { orient: opts.orient || 'auto' }); + const mesh = buildMesh(canon); + const feat = detectFeatures(mesh); + const holes = feat.holes; + const patterns = analyzePatterns(holes, mesh.bbox.min); + + const viewKeys = ['top', 'front', 'left']; + const views = viewKeys.map(k => buildView(mesh, k)); + const need = new Set(); + for (const h of holes) { + if (!h.judge) continue; + if (!h.judge.view) { need.add('bottom'); continue; } + if (!viewKeys.includes(h.judge.view)) need.add(h.judge.view); + } + const extraViews = [...need].map(k => buildView(mesh, k)); + + return { + raw, mesh, holes, patterns, views, extraViews, + bosses: feat.bosses, + transform: canon.transform, + counts: { + faces: mesh.faces.length, + holes: holes.length, + bosses: feat.bosses.length, + visible: holes.filter(h => h.judge && h.judge.visible).length, + needFlip: holes.filter(h => h.judge && !h.judge.visible && h.judge.view).length, + invisible: holes.filter(h => h.judge && !h.judge.view).length, + }, + }; +} + +// 解析 + 识别 + 出图(落盘) +async function convert(input, opts = {}) { + const res = await analyze(input, opts); + const size = res.mesh.size; + const name = opts.name || path.basename(input).replace(/\.[^.]+$/, ''); + const outDir = path.resolve(opts.outputDir || path.dirname(input)); + fs.mkdirSync(outDir, { recursive: true }); + + const meta = { + name, + source: path.basename(input), + sizeText: `${size[0].toFixed(2)} × ${size[1].toFixed(2)} × ${size[2].toFixed(2)} mm`, + date: new Date().toISOString().slice(0, 10), + triangles: res.raw.triangles, + orientation: res.transform.description, + }; + + const pdfPath = path.join(outDir, `${name}_打印图.pdf`); + await renderPDF({ + meta, views: res.views, holes: res.holes, patterns: res.patterns, + extraViews: res.extraViews, outPath: pdfPath, + }); + + const csvPath = path.join(outDir, `${name}_孔位明细.csv`); + const csv = ['编号,类型,直径mm,深度mm,X坐标mm,Y坐标mm,Z坐标mm,归属视图,可见性判定']; + for (const h of res.holes) { + csv.push([ + h.label, h.type, h.diameter.toFixed(2), h.length.toFixed(2), + h.center[0].toFixed(2), h.center[1].toFixed(2), h.center[2].toFixed(2), + h.judge && h.judge.viewName ? h.judge.viewName : '—', + h.judge ? h.judge.reason : '', + ].join(',')); + } + fs.writeFileSync(csvPath, '\ufeff' + csv.join('\r\n'), 'utf8'); + + const jsonPath = path.join(outDir, `${name}_特征.json`); + const report = { + meta, + bbox: res.mesh.bbox, + transform: res.transform, + counts: res.counts, + holes: res.holes.map(h => ({ + label: h.label, type: h.type, diameter: +h.diameter.toFixed(3), depth: +h.length.toFixed(3), + center: h.center.map(x => +x.toFixed(3)), judge: h.judge, + })), + bosses: res.bosses.map(b => ({ + label: b.label, diameter: +b.diameter.toFixed(3), center: b.center.map(x => +x.toFixed(3)), + })), + patterns: res.patterns, + extraViews: res.extraViews.map(v => v.key), + }; + fs.writeFileSync(jsonPath, JSON.stringify(report, null, 2), 'utf8'); + + return { + meta, counts: res.counts, + pdfPath, csvPath, jsonPath, + holes: res.holes.map(h => ({ + label: h.label, type: h.type, diameter: +h.diameter.toFixed(2), depth: +h.length.toFixed(2), + x: +h.center[0].toFixed(2), y: +h.center[1].toFixed(2), z: +h.center[2].toFixed(2), + view: h.judge && h.judge.viewName ? h.judge.viewName : '—', + judge: h.judge ? h.judge.reason : '', + })), + patterns: res.patterns.map(p => ({ + view: p.view, count: p.count, diameter: +p.diameter.toFixed(2), + du: p.uniformDu, dv: p.uniformDv, + })), + extraViews: res.extraViews.map(v => v.key), + }; +} + +module.exports = { analyze, convert, loadModel }; diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/mesh.js b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/mesh.js new file mode 100644 index 00000000..9798b6d4 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/mesh.js @@ -0,0 +1,259 @@ +'use strict'; +// 网格内核:顶点焊接、面/边拓扑、平滑区域生长、特征拟合、射线查询。 +// 全部尺寸单位与输入文件一致(STL/STEP 通常为毫米)。 + +const WELD = 1e-3; // 顶点焊接容差 0.001mm + +// ---------- 线性代数 ---------- +function sub(a, b) { return [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; } +function add(a, b) { return [a[0] + b[0], a[1] + b[1], a[2] + b[2]]; } +function mul(a, s) { return [a[0] * s, a[1] * s, a[2] * s]; } +function dot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } +function cross(a, b) { + return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; +} +function len(a) { return Math.hypot(a[0], a[1], a[2]); } +function norm(a) { const l = len(a) || 1; return [a[0] / l, a[1] / l, a[2] / l]; } +function clamp(v, lo, hi) { return v < lo ? lo : v > hi ? hi : v; } + +// 3x3 对称矩阵 Jacobi 特征分解,返回 { values:[λ0≤λ1≤λ2], vectors:[[v],[v],[v]] } +function eigenSym3(m) { + const a = [ + [m[0][0], m[0][1], m[0][2]], + [m[1][0], m[1][1], m[1][2]], + [m[2][0], m[2][1], m[2][2]], + ]; + let v = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]; + for (let sweep = 0; sweep < 60; sweep++) { + let off = 0; + for (let i = 0; i < 3; i++) for (let j = i + 1; j < 3; j++) off += a[i][j] * a[i][j]; + if (off < 1e-24) break; + for (let p = 0; p < 2; p++) { + for (let q = p + 1; q < 3; q++) { + if (Math.abs(a[p][q]) < 1e-30) continue; + const theta = (a[q][q] - a[p][p]) / (2 * a[p][q]); + const t = Math.sign(theta || 1) / (Math.abs(theta) + Math.sqrt(theta * theta + 1)); + const c = 1 / Math.sqrt(t * t + 1); + const s = t * c; + for (let k = 0; k < 3; k++) { + const akp = a[k][p], akq = a[k][q]; + a[k][p] = c * akp - s * akq; + a[k][q] = s * akp + c * akq; + } + for (let k = 0; k < 3; k++) { + const apk = a[p][k], aqk = a[q][k]; + a[p][k] = c * apk - s * aqk; + a[q][k] = s * apk + c * aqk; + } + for (let k = 0; k < 3; k++) { + const vkp = v[k][p], vkq = v[k][q]; + v[k][p] = c * vkp - s * vkq; + v[k][q] = s * vkp + c * vkq; + } + } + } + } + const pairs = [0, 1, 2].map(i => ({ val: a[i][i], vec: norm([v[0][i], v[1][i], v[2][i]]) })); + pairs.sort((x, y) => x.val - y.val); + return { values: pairs.map(p => p.val), vectors: pairs.map(p => p.vec) }; +} + +// Kåsa 圆拟合:输入平面上的一组点,返回 { cx, cy, r, residual } +function circleFit(pts) { + const n = pts.length; + if (n < 3) return null; + let sx = 0, sy = 0, sxx = 0, syy = 0, sxy = 0, sz = 0, szx = 0, szy = 0; + for (const [x, y] of pts) { + const z = x * x + y * y; + sx += x; sy += y; sxx += x * x; syy += y * y; sxy += x * y; + sz += z; szx += z * x; szy += z * y; + } + const A = [[sxx, sxy, sx], [sxy, syy, sy], [sx, sy, n]]; + const b = [szx, szy, sz]; + const sol = solve3(A, b); + if (!sol) return null; + const cx = sol[0] / 2, cy = sol[1] / 2; + const r2 = sol[2] + cx * cx + cy * cy; + if (!(r2 > 0)) return null; + const r = Math.sqrt(r2); + let acc = 0; + for (const [x, y] of pts) { + const d = Math.hypot(x - cx, y - cy) - r; + acc += d * d; + } + return { cx, cy, r, residual: Math.sqrt(acc / n) }; +} + +function solve3(A, b) { + const M = [ + [A[0][0], A[0][1], A[0][2], b[0]], + [A[1][0], A[1][1], A[1][2], b[1]], + [A[2][0], A[2][1], A[2][2], b[2]], + ]; + for (let c = 0; c < 3; c++) { + let piv = c; + for (let r = c + 1; r < 3; r++) if (Math.abs(M[r][c]) > Math.abs(M[piv][c])) piv = r; + if (Math.abs(M[piv][c]) < 1e-18) return null; + [M[c], M[piv]] = [M[piv], M[c]]; + for (let r = 0; r < 3; r++) { + if (r === c) continue; + const f = M[r][c] / M[c][c]; + for (let k = c; k < 4; k++) M[r][k] -= f * M[c][k]; + } + } + return [M[0][3] / M[0][0], M[1][3] / M[1][1], M[2][3] / M[2][2]]; +} + +// ---------- 网格构建 ---------- +function buildMesh(raw) { + const { positions, indices } = raw; + const key = (x, y, z) => `${Math.round(x / WELD)},${Math.round(y / WELD)},${Math.round(z / WELD)}`; + const map = new Map(); + const vp = []; + const remap = new Uint32Array(indices.length); + for (let i = 0; i < indices.length; i++) { + const vi = indices[i] * 3; + const x = positions[vi], y = positions[vi + 1], z = positions[vi + 2]; + const k = key(x, y, z); + let idx = map.get(k); + if (idx === undefined) { + idx = vp.length / 3; + map.set(k, idx); + vp.push(x, y, z); + } + remap[i] = idx; + } + const vcount = vp.length / 3; + const vpos = Float64Array.from(vp); + + const faces = []; + const edgeMap = new Map(); + for (let f = 0; f < remap.length; f += 3) { + const a = remap[f], b = remap[f + 1], c = remap[f + 2]; + if (a === b || b === c || a === c) continue; + const pa = [vpos[a * 3], vpos[a * 3 + 1], vpos[a * 3 + 2]]; + const pb = [vpos[b * 3], vpos[b * 3 + 1], vpos[b * 3 + 2]]; + const pc = [vpos[c * 3], vpos[c * 3 + 1], vpos[c * 3 + 2]]; + const n = cross(sub(pb, pa), sub(pc, pa)); + const area = len(n) / 2; + if (area < 1e-10) continue; + const unit = mul(n, 1 / (area * 2)); + const fi = faces.length; + faces.push({ v: [a, b, c], n: unit, area, c: mul(add(add(pa, pb), pc), 1 / 3), f1: -1, f2: -1, region: -1 }); + const tri = [a, b, c]; + for (let e = 0; e < 3; e++) { + const u = tri[e], w = tri[(e + 1) % 3]; + const ek = u < w ? `${u}_${w}` : `${w}_${u}`; + let ed = edgeMap.get(ek); + if (!ed) { ed = { u: Math.min(u, w), w: Math.max(u, w), f1: fi, f2: -1 }; edgeMap.set(ek, ed); } + else ed.f2 = fi; + } + } + const edges = [...edgeMap.values()]; + edges.forEach((e, i) => { e.id = i; }); + + // 面邻接 + const faceEdges = []; + for (const f of faces) faceEdges.push([]); + for (const e of edges) { + if (e.f2 >= 0) { faceEdges[e.f1].push({ edge: e.id, other: e.f2 }); faceEdges[e.f2].push({ edge: e.id, other: e.f1 }); } + } + + // 平滑区域生长(并查集) + const parent = faces.map((_, i) => i); + const find = (x) => { while (parent[x] !== x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }; + const union = (a, b) => { const ra = find(a), rb = find(b); if (ra !== rb) parent[rb] = ra; }; + for (const e of edges) { + if (e.f2 < 0) continue; + const d = Math.abs(dot(faces[e.f1].n, faces[e.f2].n)); + if (d > 0.90) union(e.f1, e.f2); // 夹角 < ~25.8° 视为同一光滑面 + } + const regions = []; + const regionIndex = new Map(); + for (let i = 0; i < faces.length; i++) { + const r = find(i); + let ri = regionIndex.get(r); + if (ri === undefined) { ri = regions.length; regionIndex.set(r, ri); regions.push([]); } + regions[ri].push(i); + faces[i].region = ri; + } + + const bbox = { min: [Infinity, Infinity, Infinity], max: [-Infinity, -Infinity, -Infinity] }; + for (let i = 0; i < vcount; i++) { + for (let k = 0; k < 3; k++) { + const val = vpos[i * 3 + k]; + if (val < bbox.min[k]) bbox.min[k] = val; + if (val > bbox.max[k]) bbox.max[k] = val; + } + } + const size = [bbox.max[0] - bbox.min[0], bbox.max[1] - bbox.min[1], bbox.max[2] - bbox.min[2]]; + + return { vpos, vcount, faces, edges, faceEdges, regions, bbox, size, remap }; +} + +// 三角形列表(用于射线查询) +function triangles(mesh) { + const list = []; + for (const f of mesh.faces) { + const a = f.v[0] * 3, b = f.v[1] * 3, c = f.v[2] * 3; + list.push({ + p0: [mesh.vpos[a], mesh.vpos[a + 1], mesh.vpos[a + 2]], + p1: [mesh.vpos[b], mesh.vpos[b + 1], mesh.vpos[b + 2]], + p2: [mesh.vpos[c], mesh.vpos[c + 1], mesh.vpos[c + 2]], + n: f.n, + }); + } + return list; +} + +// Möller–Trumbore:射线与三角形求交,返回最近正 t +function rayHit(tris, origin, dir) { + let best = Infinity; + for (const t of tris) { + const e1 = sub(t.p1, t.p0); + const e2 = sub(t.p2, t.p0); + const p = cross(dir, e2); + const det = dot(e1, p); + if (Math.abs(det) < 1e-12) continue; + const invDet = 1 / det; + const tv = sub(origin, t.p0); + const u = dot(tv, p) * invDet; + if (u < -1e-9 || u > 1 + 1e-9) continue; + const q = cross(tv, e1); + const v = dot(dir, q) * invDet; + if (v < -1e-9 || u + v > 1 + 1e-9) continue; + const tt = dot(e2, q) * invDet; + if (tt > 1e-7 && tt < best) best = tt; + } + return best === Infinity ? null : best; +} + +// 奇偶判定:点是否在实体内部(射线方向取通用向量,规避退化) +function pointInside(tris, p, seed = 0) { + const ang = 0.7 + seed * 0.6180339887; + const dir = norm([Math.cos(ang), Math.sin(ang) * 0.7 + 0.31, Math.sin(ang) * 0.43 + 0.17]); + let count = 0; + for (const t of tris) { + const e1 = sub(t.p1, t.p0); + const e2 = sub(t.p2, t.p0); + const pvec = cross(dir, e2); + const det = dot(e1, pvec); + if (Math.abs(det) < 1e-12) continue; + const invDet = 1 / det; + const tv = sub(p, t.p0); + const u = dot(tv, pvec) * invDet; + if (u < -1e-9 || u > 1 + 1e-9) continue; + const q = cross(tv, e1); + const v = dot(dir, q) * invDet; + if (v < -1e-9 || u + v > 1 + 1e-9) continue; + const tt = dot(e2, q) * invDet; + if (tt > 1e-7) count++; + } + return count % 2 === 1; +} + +module.exports = { + WELD, buildMesh, triangles, rayHit, pointInside, + eigenSym3, circleFit, solve3, + sub, add, mul, dot, cross, len, norm, clamp, +}; diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/mf3mf.js b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/mf3mf.js new file mode 100644 index 00000000..978d3b1b --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/mf3mf.js @@ -0,0 +1,214 @@ +'use strict'; +// 3MF 解析:Bambu Studio / PrusaSlicer / Cura 等切片工程导出的 .3mf +// 3MF = ZIP(3D/3dmodel.model + 3D/Objects/*.model),内部是 XML 网格。 +// 输出与 STL 解析器一致的 { positions, indices }(单位换算为毫米)。 + +const fs = require('fs'); +const zlib = require('zlib'); + +// ---------- 最小 ZIP 读取(中央目录 + inflateRaw) ---------- +function readZip(buf) { + // 找 End of Central Directory + let eocd = -1; + for (let i = buf.length - 22; i >= 0 && i >= buf.length - 22 - 65536; i--) { + if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; } + } + if (eocd < 0) throw new Error('不是有效的 ZIP/3MF 文件(找不到中央目录)'); + const count = buf.readUInt16LE(eocd + 10); + let off = buf.readUInt32LE(eocd + 16); + const files = new Map(); + for (let i = 0; i < count; i++) { + if (buf.readUInt32LE(off) !== 0x02014b50) break; + const method = buf.readUInt16LE(off + 10); + const compSize = buf.readUInt32LE(off + 20); + const nameLen = buf.readUInt16LE(off + 28); + const extraLen = buf.readUInt16LE(off + 30); + const commentLen = buf.readUInt16LE(off + 32); + const localOff = buf.readUInt32LE(off + 42); + const name = buf.slice(off + 46, off + 46 + nameLen).toString('utf8'); + // 本地文件头 + const lNameLen = buf.readUInt16LE(localOff + 26); + const lExtraLen = buf.readUInt16LE(localOff + 28); + const dataStart = localOff + 30 + lNameLen + lExtraLen; + const raw = buf.slice(dataStart, dataStart + compSize); + const data = method === 0 ? raw : zlib.inflateRawSync(raw); + files.set(name.replace(/\\/g, '/'), data); + off += 46 + nameLen + extraLen + commentLen; + } + return files; +} + +// ---------- 3MF 模型 XML 解析 ---------- +const UNIT_TO_MM = { + micron: 0.001, millimeter: 1, centimeter: 10, inch: 25.4, foot: 304.8, meter: 1000, +}; + +function parseModel(text) { + const unit = (text.match(/]*\bunit="([^"]+)"/i) || [, 'millimeter'])[1]; + const scale = UNIT_TO_MM[unit] || 1; + + const objects = new Map(); + const objRe = /]*)>([\s\S]*?)<\/object>/gi; + let m; + while ((m = objRe.exec(text)) !== null) { + const attrs = m[1]; + const body = m[2]; + const id = (attrs.match(/\bid="([^"]+)"/i) || [, ''])[1]; + if (!id) continue; + const entry = { id, mesh: null, components: [] }; + + const meshMatch = body.match(/([\s\S]*?)<\/mesh>/i); + if (meshMatch) { + const meshBody = meshMatch[1]; + const verts = []; + const vRe = /]*\/>/gi; + let vm; + while ((vm = vRe.exec(meshBody)) !== null) { + const x = parseFloat((vm[0].match(/\bx="([^"]+)"/i) || [, 0])[1]); + const y = parseFloat((vm[0].match(/\by="([^"]+)"/i) || [, 0])[1]); + const z = parseFloat((vm[0].match(/\bz="([^"]+)"/i) || [, 0])[1]); + verts.push([x, y, z]); + } + const tris = []; + const tRe = /]*\/>/gi; + let tm; + while ((tm = tRe.exec(meshBody)) !== null) { + const a = parseInt((tm[0].match(/\bv1="([^"]+)"/i) || [, -1])[1], 10); + const b = parseInt((tm[0].match(/\bv2="([^"]+)"/i) || [, -1])[1], 10); + const c = parseInt((tm[0].match(/\bv3="([^"]+)"/i) || [, -1])[1], 10); + if (a >= 0 && b >= 0 && c >= 0) tris.push([a, b, c]); + } + entry.mesh = { vertices: verts, triangles: tris }; + } + + const compRe = /]*)\/>/gi; + let cm; + while ((cm = compRe.exec(body)) !== null) { + const cattrs = cm[1]; + const objectid = (cattrs.match(/\bobjectid="([^"]+)"/i) || [, ''])[1]; + const pathAttr = (cattrs.match(/\bp:path="([^"]+)"/i) || [, ''])[1]; + const transform = parseTransform((cattrs.match(/\btransform="([^"]+)"/i) || [, ''])[1]); + if (objectid) entry.components.push({ objectid, path: pathAttr ? pathAttr.replace(/^\//, '') : null, transform }); + } + objects.set(id, entry); + } + + const items = []; + const buildRe = /]*)\/>/gi; + let im; + while ((im = buildRe.exec(text)) !== null) { + const attrs = im[1]; + const objectid = (attrs.match(/\bobjectid="([^"]+)"/i) || [, ''])[1]; + const transform = parseTransform((attrs.match(/\btransform="([^"]+)"/i) || [, ''])[1]); + if (objectid) items.push({ objectid, transform }); + } + return { unit, scale, objects, items }; +} + +// 3MF 变换:12 个数按属性顺序 m00 m01 m02 m10 m11 m12 m20 m21 m22 m30 m31 m32 +// 点变换(列向量约定):x' = m00*x + m10*y + m20*z + m30 +function parseTransform(s) { + const n = (s || '').trim().split(/\s+/).map(Number).filter((v) => !Number.isNaN(v)); + if (n.length < 12) return null; + return { + m: [n[0], n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[8], n[9], n[10], n[11]], + }; +} +function mat3(t) { + const m = t.m; + return [[m[0], m[3], m[6]], [m[1], m[4], m[7]], [m[2], m[5], m[8]]]; +} +function trans(t) { return [t.m[9], t.m[10], t.m[11]]; } +function applyPoint(t, p) { + const A = mat3(t), T = trans(t); + return [ + A[0][0] * p[0] + A[0][1] * p[1] + A[0][2] * p[2] + T[0], + A[1][0] * p[0] + A[1][1] * p[1] + A[1][2] * p[2] + T[1], + A[2][0] * p[0] + A[2][1] * p[1] + A[2][2] * p[2] + T[2], + ]; +} +// C = A ∘ B(先应用 B,再应用 A) +function mulTransform(A, B) { + if (!A) return B; + if (!B) return A; + const a = mat3(A), b = mat3(B), ta = trans(A), tb = trans(B); + const c = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]; + for (let i = 0; i < 3; i++) { + for (let j = 0; j < 3; j++) { + c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j]; + } + } + const ct = [ + a[0][0] * tb[0] + a[0][1] * tb[1] + a[0][2] * tb[2] + ta[0], + a[1][0] * tb[0] + a[1][1] * tb[1] + a[1][2] * tb[2] + ta[1], + a[2][0] * tb[0] + a[2][1] * tb[1] + a[2][2] * tb[2] + ta[2], + ]; + return { m: [c[0][0], c[0][1], c[0][2], c[1][0], c[1][1], c[1][2], c[2][0], c[2][1], c[2][2], ct[0], ct[1], ct[2]] }; +} + +// ---------- 入口 ---------- +function parse3MF(buf) { + const files = readZip(buf); + if (!files.size) throw new Error('3MF 包为空'); + + // 主模型文件:优先 3D/3dmodel.model,其次任意 .model + let mainPath = null; + for (const k of files.keys()) { + if (/^3d\/3dmodel\.model$/i.test(k)) { mainPath = k; break; } + } + if (!mainPath) { + for (const k of files.keys()) if (/\.model$/i.test(k)) { mainPath = k; break; } + } + if (!mainPath) throw new Error('3MF 包内未找到 .model 文件'); + + const modelCache = new Map(); + function getModel(p) { + if (!modelCache.has(p)) modelCache.set(p, parseModel(files.get(p).toString('utf8'))); + return modelCache.get(p); + } + + const main = getModel(mainPath); + const positions = []; + const indices = []; + const emitted = new Set(); + + function emitObject(file, objectId, xf) { + const key = `${file}#${objectId}`; + if (emitted.has(key)) return; + emitted.add(key); + const model = getModel(file); + const obj = model.objects.get(objectId); + if (!obj) return; + if (obj.mesh) { + const base = positions.length / 3; + const s = model.scale; + for (const v of obj.mesh.vertices) { + let p = [v[0] * s, v[1] * s, v[2] * s]; + if (xf) p = applyPoint(xf, p); + positions.push(p[0], p[1], p[2]); + } + for (const t of obj.mesh.triangles) indices.push(base + t[0], base + t[1], base + t[2]); + } + for (const comp of obj.components) { + const targetFile = comp.path && files.has(comp.path) ? comp.path : file; + emitObject(targetFile, comp.objectid, mulTransform(xf, comp.transform)); + } + } + + for (const item of main.items) { + emitObject(mainPath, item.objectid, item.transform); + } + // 没有 build 项时,直接输出所有 mesh 对象 + if (!main.items.length) { + for (const [id, obj] of main.objects) if (obj.mesh) emitObject(mainPath, id, null); + } + if (!positions.length) throw new Error('3MF 中未找到三角网格(可能只有曲线/点阵资源)'); + return { + positions: Float64Array.from(positions), + indices: Uint32Array.from(indices), + format: '3mf', + triangles: indices.length / 3, + }; +} + +module.exports = { parse3MF, readZip }; diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/orient.js b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/orient.js new file mode 100644 index 00000000..9fdbf51d --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/orient.js @@ -0,0 +1,68 @@ +'use strict'; +// 自动定向:把零件摆正为「长轴 = X、宽轴 = Y、厚度轴 = Z」的标准工程坐标系, +// 并把原点平移到包围盒最小角点,使图纸上的坐标可直接用卡尺比对。 + +const M = require('./mesh'); + +function canonicalize(raw, opts = {}) { + const mode = opts.orient || 'auto'; + const positions = raw.positions; + const count = positions.length / 3; + + // 包围盒 + const mn = [Infinity, Infinity, Infinity], mx = [-Infinity, -Infinity, -Infinity]; + for (let i = 0; i < count; i++) { + for (let k = 0; k < 3; k++) { + const v = positions[i * 3 + k]; + if (v < mn[k]) mn[k] = v; + if (v > mx[k]) mx[k] = v; + } + } + const ext = [mx[0] - mn[0], mx[1] - mn[1], mx[2] - mn[2]]; + + let ex = [1, 0, 0], ey = [0, 1, 0], ez = [0, 0, 1]; + let desc = '保持原始坐标'; + if (mode === 'auto') { + const order = [0, 1, 2].sort((a, b) => ext[b] - ext[a]); + const longAx = order[0], shortAx = order[2]; + const axisVec = (k) => { const v = [0, 0, 0]; v[k] = 1; return v; }; + ez = axisVec(shortAx); + ex = axisVec(longAx); + ey = M.norm(M.cross(ez, ex)); + const name = { 0: 'X', 1: 'Y', 2: 'Z' }; + desc = `厚度轴 ${name[shortAx]}→Z,长轴 ${name[longAx]}→X`; + } + + const out = new Float64Array(positions.length); + for (let i = 0; i < count; i++) { + const p = [positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]]; + out[i * 3] = M.dot(p, ex); + out[i * 3 + 1] = M.dot(p, ey); + out[i * 3 + 2] = M.dot(p, ez); + } + // 平移:包围盒最小角点 → 原点 + const mn2 = [Infinity, Infinity, Infinity], mx2 = [-Infinity, -Infinity, -Infinity]; + for (let i = 0; i < count; i++) { + for (let k = 0; k < 3; k++) { + const v = out[i * 3 + k]; + if (v < mn2[k]) mn2[k] = v; + if (v > mx2[k]) mx2[k] = v; + } + } + for (let i = 0; i < count; i++) { + for (let k = 0; k < 3; k++) out[i * 3 + k] -= mn2[k]; + } + return { + positions: out, + indices: raw.indices, + transform: { + ex, ey, ez, + offset: mn2, + originalBBox: { min: mn, max: mx, size: ext }, + newBBox: { min: [0, 0, 0], max: [mx2[0] - mn2[0], mx2[1] - mn2[1], mx2[2] - mn2[2]] }, + description: desc, + }, + }; +} + +module.exports = { canonicalize }; diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/pdfout.js b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/pdfout.js new file mode 100644 index 00000000..6092c9b7 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/pdfout.js @@ -0,0 +1,619 @@ +'use strict'; +// PDF 输出:1:1 A4 三视图 + 尺寸标注 + 孔位标注 + 孔位明细表 + 可见性判定说明。 + +const fs = require('fs'); +const PDFDocument = require('pdfkit'); +const { projectHole } = require('./views'); + +const MM = 72 / 25.4; // 1mm = 2.8346pt +const VIEW_CN = { + top: '俯视图', front: '主视图', left: '左视图', + bottom: '底视图', back: '后视图', right: '右视图', +}; +const FONT_CANDIDATES = [ + 'C:/Windows/Fonts/simhei.ttf', + 'C:/Windows/Fonts/msyh.ttc', + 'C:/Windows/Fonts/simsun.ttc', + '/System/Library/Fonts/PingFang.ttc', + '/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc', +]; + +function findFont() { + for (const f of FONT_CANDIDATES) { try { if (fs.existsSync(f)) return f; } catch (e) { /* ignore */ } } + return null; +} + +// ---------- 画布(毫米坐标,y 向下) ---------- +class Sheet { + constructor(doc, wMM, hMM) { + this.doc = doc; + this.W = wMM; + this.H = hMM; + } + X(mm) { return mm * MM; } + Y(mm) { return mm * MM; } + line(x1, y1, x2, y2, w = 0.25, color = '#000', dash) { + const d = this.doc; + d.save().lineWidth(w).strokeColor(color); + if (dash) d.dash(dash); + d.moveTo(this.X(x1), this.Y(y1)).lineTo(this.X(x2), this.Y(y2)).stroke().undash(); + d.restore(); + } + rect(x, y, w, h, lw = 0.25, color = '#000') { + const d = this.doc; + d.save().lineWidth(lw).strokeColor(color).rect(this.X(x), this.Y(y), this.X(w), this.Y(h)).stroke().restore(); + } + fillRect(x, y, w, h, color) { + const d = this.doc; + d.save().fillColor(color).rect(this.X(x), this.Y(y), this.X(w), this.Y(h)).fill().restore(); + } + circle(cx, cy, r, lw = 0.25, color = '#000', dash) { + const d = this.doc; + d.save().lineWidth(lw).strokeColor(color); + if (dash) d.dash(dash); + d.circle(this.X(cx), this.Y(cy), this.X(Math.max(r, 0.01))).stroke().undash(); + d.restore(); + } + ellipse(cx, cy, rx, ry, rot, lw = 0.25, color = '#000', dash) { + const d = this.doc; + d.save().lineWidth(lw).strokeColor(color); + if (dash) d.dash(dash); + d.ellipse(this.X(cx), this.Y(cy), this.X(Math.max(rx, 0.01)), this.Y(Math.max(ry, 0.01)), rot).stroke().undash(); + d.restore(); + } + // 文本宽度(mm) + width(str, size = 3, font) { + const d = this.doc; + d.save(); + if (font) d.font(font); + d.fontSize(size * MM); + const w = d.widthOfString(String(str)); + d.restore(); + return w / MM; + } + // 按列宽裁剪文字,超出时省略号收尾 + fit(str, maxMm, size = 2.5, font) { + let s = String(str); + if (this.width(s, size, font) <= maxMm) return s; + while (s.length > 1 && this.width(s + '…', size, font) > maxMm) s = s.slice(0, -1); + return s + '…'; + } + text(str, x, y, opt = {}) { + const d = this.doc; + d.save(); + if (opt.font) d.font(opt.font); + const sizeMm = opt.size || 3; + d.fontSize(sizeMm * MM); // 字号按毫米给,PDFKit 用点 + d.fillColor(opt.color || '#000'); + const w = d.widthOfString(str); + let tx = this.X(x); + if (opt.align === 'center') tx -= w / 2; + else if (opt.align === 'right') tx -= w; + d.text(str, tx, this.Y(y) - sizeMm * MM * 0.78, { lineBreak: false }); + d.restore(); + return w / MM; + } + // 旋转文字(竖向尺寸用) + textRotated(str, x, y, opt = {}) { + const d = this.doc; + d.save(); + if (opt.font) d.font(opt.font); + const sizeMm = opt.size || 3; + d.fontSize(sizeMm * MM); + d.fillColor(opt.color || '#000'); + const w = d.widthOfString(str); + d.translate(this.X(x), this.Y(y)).rotate(-90); + d.text(str, -w / 2, -sizeMm * MM * 0.35, { lineBreak: false }); + d.restore(); + return w / MM; + } + arrow(x, y, dir, size = 1.6, color = '#000') { + const d = this.doc; + const s = size; + const pts = dir === 'up' ? [[x, y], [x - s * 0.35, y - s], [x + s * 0.35, y - s]] + : dir === 'down' ? [[x, y], [x - s * 0.35, y + s], [x + s * 0.35, y + s]] + : dir === 'left' ? [[x, y], [x - s, y - s * 0.35], [x - s, y + s * 0.35]] + : [[x, y], [x + s, y - s * 0.35], [x + s, y + s * 0.35]]; + const flat = []; + for (const p of pts) flat.push(this.X(p[0]), this.Y(p[1])); + d.save().fillColor(color).polygon(flat).fill().restore(); + } +} + +// ---------- 尺寸标注 ---------- +function dimH(sh, x1, x2, y, label, opt = {}) { + const dir = opt.dir || (x2 >= x1 ? 'right' : 'left'); + sh.line(x1, y, x2, y, 0.18); + sh.arrow(x1, y, dir === 'right' ? 'left' : 'right'); + sh.arrow(x2, y, dir); + const mid = (x1 + x2) / 2; + const size = opt.size || 3; + const w = sh.text(label, mid, y - 0.9, { size, align: 'center' }); + return w; +} + +function dimV(sh, y1, y2, x, label, opt = {}) { + const dir = opt.dir || (y2 <= y1 ? 'up' : 'down'); + sh.line(x, y1, x, y2, 0.18); + sh.arrow(y1, x, dir === 'up' ? 'down' : 'up'); + sh.arrow(y2, x, dir); + const mid = (y1 + y2) / 2; + sh.textRotated(label, x, mid, { size: opt.size || 3 }); +} + +function leader(sh, px, py, tx, ty, opt = {}) { + sh.line(px, py, tx, ty, 0.18); + const ang = Math.atan2(ty - py, tx - px); + const a = opt.arrowSize || 1.0; + const d = sh.doc; + const flat = [ + sh.X(px), sh.Y(py), + sh.X(px + a * Math.cos(ang + 0.4)), sh.Y(py + a * Math.sin(ang + 0.4)), + sh.X(px + a * Math.cos(ang - 0.4)), sh.Y(py + a * Math.sin(ang - 0.4)), + ]; + d.save().fillColor('#000').polygon(flat).fill().restore(); +} + +// ---------- 视图绘制 ---------- +// place: { ox, oy, scale } —— ox/oy 为图纸上视图原点位置(mm) +// clip: { x0, x1, y0, y1 } —— 模型坐标范围,超出部分不画(分块打印用) +function drawView(sh, view, place, clip) { + const { ox, oy, scale } = place; + const hMin = view.bbox.minH, vMax = view.bbox.maxV; + const P = (h, v) => [ox + (h - hMin) * scale, oy + (vMax - v) * scale]; + for (const sg of view.segments) { + if (clip) { + const minx = Math.min(sg.a[0], sg.b[0]), maxx = Math.max(sg.a[0], sg.b[0]); + const miny = Math.min(sg.a[1], sg.b[1]), maxy = Math.max(sg.a[1], sg.b[1]); + if (maxx < clip.x0 || minx > clip.x1 || maxy < clip.y0 || miny > clip.y1) continue; + } + const [x1, y1] = P(sg.a[0], sg.a[1]); + const [x2, y2] = P(sg.b[0], sg.b[1]); + sh.line(x1, y1, x2, y2, sg.kind === 'silhouette' ? 0.35 : 0.22); + } + return P; +} + +// 视图分块(零件大于 A4 可打印区时,1:1 分块打印) +function computeTiles(view, areaW, areaH) { + const nCols = Math.max(1, Math.ceil(view.width / areaW - 1e-9)); + const nRows = Math.max(1, Math.ceil(view.height / areaH - 1e-9)); + const tw = view.width / nCols, th = view.height / nRows; + const tiles = []; + for (let r = 0; r < nRows; r++) { + for (let c = 0; c < nCols; c++) { + tiles.push({ + x0: view.bbox.minH + c * tw, x1: view.bbox.minH + (c + 1) * tw, + y0: view.bbox.minV + r * th, y1: view.bbox.minV + (r + 1) * th, + row: r, col: c, nCols, nRows, + }); + } + } + return tiles; +} + +// 孔位标记 + 编号气泡(明细进孔位表,图面只留编号,避免引线横穿) +function drawHoleMarkers(sh, view, place, holes, opt = {}) { + const { ox, oy, scale } = place; + const clip = opt.clip; + const hMin = view.bbox.minH, vMax = view.bbox.maxV; + const P = (h, v) => [ox + (h - hMin) * scale, oy + (vMax - v) * scale]; + const items = holes.map(h => ({ h, pr: projectHole(h, view.key) })) + .filter(it => it.pr.semiMajor > 0.05 && it.h.judge && it.h.judge.view === view.key) + .filter(it => !clip || (it.pr.h >= clip.x0 && it.pr.h <= clip.x1 && it.pr.v >= clip.y0 && it.pr.v <= clip.y1)); + + for (const { h, pr } of items) { + const [cx, cy] = P(pr.h, pr.v); + if (pr.isCircle) sh.circle(cx, cy, pr.semiMajor * scale, 0.22, '#000'); + else sh.ellipse(cx, cy, pr.semiMajor * scale, pr.semiMinor * scale, pr.axisAngle, 0.22, '#000'); + const c = Math.max(1.2, pr.semiMajor * 1.7) * scale; + sh.line(cx - c, cy, cx + c, cy, 0.18); + sh.line(cx, cy - c, cx, cy + c, 0.18); + } + + if (!items.length) return; + + // 以视图中心为基准按角度排序,编号气泡沿外侧分布 + const cx0 = ox + (view.bbox.maxH - hMin) / 2 * scale; + const cy0 = oy + (vMax - view.bbox.minV) / 2 * scale; + const list = items.map(it => { + const [cx, cy] = P(it.pr.h, it.pr.v); + return { ...it, cx, cy, ang: Math.atan2(cy - cy0, cx - cx0) }; + }).sort((a, b) => a.ang - b.ang); + + const placed = []; + const collide = (b) => placed.some(p => + !(b.x > p.x + p.w || b.x + b.w < p.x || b.y > p.y + p.h || b.y + b.h < p.y)); + + for (const it of list) { + const label = it.h.label; + const tw = label.length * 1.6 + 1.2; // 估算字宽 mm + const th = 3.4; + const r = it.pr.semiMajor * scale; // 孔半径(图纸 mm) + const away = Math.atan2(it.cy - cy0, it.cx - cx0); + const dirs = [away, away + Math.PI / 2, away - Math.PI / 2, away + Math.PI, away + 2.1, away - 2.1]; + let done = false; + for (const dir of dirs) { + for (const gap of [2.6, 5.5, 9, 13, 18]) { + const dist = r + gap; + const lx = it.cx + Math.cos(dir) * dist; + const ly = it.cy + Math.sin(dir) * dist; + const b = { x: lx - tw / 2, y: ly - th / 2, w: tw, h: th }; + if (b.x < 10 || b.x + b.w > sh.W - 10 || b.y < 10 || b.y + b.h > sh.H - 10) continue; + if (collide(b)) continue; + placed.push(b); + leader(sh, it.cx + Math.cos(dir) * r, it.cy + Math.sin(dir) * r, lx, ly, { arrowSize: 0.8 }); + sh.text(label, lx, ly + 1.1, { size: 2.8, align: 'center' }); + done = true; + break; + } + if (done) break; + } + if (!done) { + const lx = it.cx + r + 2.6, ly = it.cy - 1.5; + leader(sh, it.cx + r, it.cy, lx, ly, { arrowSize: 0.8 }); + sh.text(label, lx + 0.8, ly + 1.1, { size: 2.8, align: 'left' }); + } + } +} + +// ---------- 图框与标题栏 ---------- +function drawFrame(sh) { + const m = 8; + sh.rect(m, m, sh.W - 2 * m, sh.H - 2 * m, 0.6); + sh.rect(m + 2, m + 2, sh.W - 2 * (m + 2), sh.H - 2 * (m + 2), 0.2); +} + +function drawTitleBlock(sh, meta, viewInfo) { + const bw = 150, bh = 26; + const x = sh.W - 8 - bw, y = sh.H - 8 - bh; + sh.rect(x, y, bw, bh, 0.4); + sh.line(x, y + 9, x + bw, y + 9, 0.3); + sh.line(x, y + 17, x + bw, y + 17, 0.3); + sh.line(x + 62, y + 9, x + 62, y + bh, 0.3); + sh.line(x + 108, y + 9, x + 108, y + bh, 0.3); + sh.text(meta.name, x + 2, y + 7.5, { size: 4.2 }); + const src = String(meta.source || '').length > 26 ? String(meta.source).slice(0, 24) + '…' : (meta.source || ''); + sh.text(`来源:${src}`, x + 64, y + 7.5, { size: 2.6 }); + sh.text(`视图:${viewInfo.name}`, x + 2, y + 15.5, { size: 3.2 }); + sh.text(`比例:${viewInfo.scale}`, x + 64, y + 15.5, { size: 3.2 }); + sh.text('投影:第一角(GB)', x + 110, y + 15.5, { size: 2.6 }); + sh.text('单位:mm', x + 2, y + 23.5, { size: 2.8 }); + sh.text(`生成:${meta.date}`, x + 64, y + 23.5, { size: 2.8 }); + sh.text(`页码:${viewInfo.page}`, x + 110, y + 23.5, { size: 2.8 }); +} + +// ---------- 孔位明细表 ---------- +const TABLE_COLS = [ + { key: 'label', title: '编号', w: 12 }, + { key: 'type', title: '类型', w: 26 }, // 需容下「通孔·带Φ5.00沉孔」 + { key: 'dia', title: '直径Φ', w: 15 }, + { key: 'depth', title: '深度', w: 14 }, + { key: 'x', title: 'X坐标', w: 19 }, + { key: 'y', title: 'Y坐标', w: 19 }, + { key: 'z', title: 'Z坐标', w: 19 }, + { key: 'view', title: '归属视图', w: 21 }, + { key: 'judge', title: '可见性判定', w: 38 }, +]; + +function drawHoleTable(sh, holes) { + const x0 = 12, y0 = 26, rowH = 5.8; + const totalW = TABLE_COLS.reduce((a, c) => a + c.w, 0); + sh.fillRect(x0, y0, totalW, rowH, '#e6e6e6'); + let cx = x0; + for (const c of TABLE_COLS) { + sh.text(c.title, cx + 1.5, y0 + 4.2, { size: 2.6 }); + cx += c.w; + } + sh.line(x0, y0, x0 + totalW, y0, 0.4); + sh.line(x0, y0 + rowH, x0 + totalW, y0 + rowH, 0.4); + let cy = y0 + rowH; + let n = 0; + for (const h of holes) { + if (cy + rowH > sh.H - 62) break; + const cells = [ + h.label, + h.type, + h.diameter.toFixed(2), + h.length > 0 ? h.length.toFixed(2) : '—', + h.center[0].toFixed(2), + h.center[1].toFixed(2), + h.center[2].toFixed(2), + h.judge && h.judge.viewName ? h.judge.viewName : '—', + h.judge ? (h.judge.short || h.judge.reason) : '', + ]; + cx = x0; + cells.forEach((v, i) => { + const col = TABLE_COLS[i]; + sh.text(sh.fit(v, col.w - 2.5, 2.5), cx + 1.5, cy + 4.2, { size: 2.5 }); + cx += col.w; + }); + sh.line(x0, cy, x0 + totalW, cy, 0.2); + cy += rowH; + n++; + } + cx = x0; + sh.line(x0, y0, x0, cy, 0.4); + for (const c of TABLE_COLS) { + cx += c.w; + sh.line(cx, y0, cx, cy, 0.25); + } + sh.line(x0, cy, x0 + totalW, cy, 0.4); + return { rows: n, bottom: cy }; +} + +// ---------- 主入口 ---------- +async function renderPDF(opts) { + const { meta, views, holes, patterns, extraViews, outPath } = opts; + const doc = new PDFDocument({ autoFirstPage: false, margin: 0, info: { Title: meta.name } }); + const fontPath = findFont(); + if (fontPath) doc.registerFont('cn', fontPath); + const F = fontPath ? 'cn' : 'Helvetica'; + + const stream = fs.createWriteStream(outPath); + doc.pipe(stream); + + const A4W = 210, A4H = 297; + const allViews = views.concat(extraViews); + + // 页面计划:先算分块,才能给出正确页码 + const viewPlan = []; + for (const v of allViews) { + const landscape = v.width > v.height && v.width > 190; + const W = landscape ? 297 : 210, H = landscape ? 210 : 297; + const areaX0 = 16, areaX1 = W - 16, areaY0 = 16, areaY1 = H - 8 - 26 - 4; + const candPatterns = patterns.filter(p => p.view === v.key && p.grid && p.uniformDu && p.uniformDv) + .sort((a, b) => b.count - a.count); + // 自适应:优先单页放下,放不下才减少孔距标注组数 + let nPat = Math.min(candPatterns.length, 3); + let tiles = null; + for (; nPat >= 0; nPat--) { + const dimLeft = 12 + nPat * 9, dimBottom = 12 + nPat * 9; + const areaW = (areaX1 - areaX0) - dimLeft; + const areaH = (areaY1 - areaY0) - dimBottom; + tiles = computeTiles(v, areaW, areaH); + if (tiles.length === 1) break; + } + nPat = Math.max(0, nPat); + const dimLeft = 12 + nPat * 9, dimBottom = 12 + nPat * 9; + const overviewScale = Math.min((areaX1 - areaX0) / v.width, (areaY1 - areaY0) / v.height); + viewPlan.push({ v, W, H, areaX0, areaX1, areaY0, areaY1, candPatterns, nPat, dimLeft, dimBottom, tiles, overviewScale }); + } + const totalPages = 2 + viewPlan.reduce((a, p) => a + p.tiles.length + (p.tiles.length > 1 ? 1 : 0), 0); + let pageNo = 0; + + // ========== P1 概览页 ========== + pageNo++; + doc.addPage({ size: [A4W * MM, A4H * MM], margin: 0 }); + let sh = new Sheet(doc, A4W, A4H); + drawFrame(sh); + sh.text(`${meta.name} 三视图总览`, 12, 16, { size: 6, font: F }); + sh.text(`文件:${meta.source}  外形尺寸:${meta.sizeText}  本页为缩略示意,1:1 打印请用后续各视图页`, 12, 23, { size: 3.2, font: F }); + + { + const front = views.find(v => v.key === 'front') || views[0]; + const top = views.find(v => v.key === 'top') || views[0]; + const left = views.find(v => v.key === 'left') || views[0]; + const availW = 176, availH = 132; + const s = Math.min(availW / (front.width + left.width + 14), availH / (front.height + top.height + 14)); + const baseX = 14, baseY = 32, gap = 12; + const rowH = Math.max(front.height, left.height) * s; + const places = { + front: { ox: baseX, oy: baseY, scale: s }, + top: { ox: baseX, oy: baseY + rowH + gap, scale: s }, + left: { ox: baseX + front.width * s + gap, oy: baseY, scale: s }, + }; + for (const v of views) { + const pl = places[v.key]; + if (!pl) continue; + drawView(sh, v, pl); + sh.text(`${v.name}(${v.width.toFixed(1)}×${v.height.toFixed(1)})`, pl.ox, pl.oy - 4, { size: 3.2, font: F }); + } + const viewsBottom = baseY + rowH + gap + top.height * s; + sh.text('投影方式:第一角(俯视图在主视图下方,左视图在主视图右方)', 14, viewsBottom + 6, { size: 2.8, font: F }); + + // 左列:孔位统计 + const stats = [ + ['孔位总数', `${holes.length} 个`], + ['三视图可见', `${holes.filter(h => h.judge && h.judge.visible).length} 个`], + ['需翻面 / 另出视图', `${holes.filter(h => h.judge && !h.judge.visible && h.judge.view).length} 个`], + ['内部不可见(需剖视)', `${holes.filter(h => h.judge && !h.judge.view).length} 个`], + ['孔距阵列', `${patterns.length} 组`], + ]; + let sy = viewsBottom + 16; + sh.text('孔位统计', 14, sy, { size: 4.2, font: F }); + sy += 7.5; + for (const [k, v] of stats) { + sh.text(`${k}:${v}`, 14, sy, { size: 3.2, font: F }); + sy += 5.5; + } + + // 右列:判定说明 + const needFlip = holes.filter(h => h.judge && !h.judge.visible && h.judge.view); + const needSection = holes.filter(h => h.judge && !h.judge.view); + const bx = 108; + let by = viewsBottom + 16; + sh.text('判定说明', bx, by, { size: 4.2, font: F }); + by += 7.5; + const bullets = []; + if (needFlip.length) bullets.push(`需翻面 / 另出视图(${needFlip.length}):${needFlip.map(h => `${h.label}→${h.judge.viewName}`).join('、')}`); + if (needSection.length) bullets.push(`三视图不可见(${needSection.length}):${needSection.map(h => `${h.label}(${h.judge.placement})`).join('、')}`); + for (const pt of patterns) { + bullets.push(`${VIEW_CN[pt.view] || pt.view}孔距:${pt.count} 孔 Φ${pt.diameters.join('/')},X ${pt.uniformDu !== null ? pt.uniformDu.toFixed(2) + 'mm' : fmtList(pt.du)},Y ${pt.uniformDv !== null ? pt.uniformDv.toFixed(2) + 'mm' : fmtList(pt.dv)}`); + } + bullets.push('底面 / 背面 / 侧面的孔位在三视图中不可见,已逐条判定并单列,必要视图另行出图。'); + for (const b of bullets) { + let rest = b; + while (rest.length) { + const chunk = rest.slice(0, 26); + rest = rest.slice(26); + sh.text('· ' + chunk, bx, by, { size: 2.9, font: F }); + by += 4.8; + } + } + } + + // ========== 各视图 1:1 页(超过 A4 自动分块) ========== + for (const vp of viewPlan) { + const { v, W, H, areaX0, areaX1, areaY0, areaY1, candPatterns, nPat, dimLeft, dimBottom, tiles, overviewScale } = vp; + + // 超出 A4 的视图:先出一张整件缩略页(标注实际比例 + 分块划分),再出 1:1 分块页 + if (tiles.length > 1) { + pageNo++; + const s = Math.min(1, overviewScale); + doc.addPage({ size: [W * MM, H * MM], margin: 0 }); + sh = new Sheet(doc, W, H); + drawFrame(sh); + drawTitleBlock(sh, meta, { name: v.name + '(整件缩略)', scale: `1:${(1 / s).toFixed(2)}`, page: `${pageNo}/${totalPages}` }); + const ox0 = areaX0 + (areaX1 - areaX0 - v.width * s) / 2; + const oy0 = areaY0 + (areaY1 - areaY0 - v.height * s) / 2; + const place = { ox: ox0 - v.bbox.minH * s, oy: oy0, scale: s }; + drawView(sh, v, place); + drawHoleMarkers(sh, v, place, holes); + // 分块划分线 + const tw = v.width / tiles[0].nCols, th = v.height / tiles[0].nRows; + for (let c = 1; c < tiles[0].nCols; c++) { + const x = ox0 + c * tw; + sh.line(x, oy0, x, oy0 + v.height * s, 0.3, '#c00', [1.5, 1.5]); + } + for (let r = 1; r < tiles[0].nRows; r++) { + const y = oy0 + r * th; + sh.line(ox0, y, ox0 + v.width * s, y, 0.3, '#c00', [1.5, 1.5]); + } + sh.text(`${v.name} 整件缩略 比例 1:${(1 / s).toFixed(2)}(非 1:1,1:1 打印请用后续分块页)`, 16, 12, { size: 3.6, font: F }); + sh.text(`分块划分:${tiles[0].nCols} 列 × ${tiles[0].nRows} 行,红虚线为分块边界`, 16, areaY1 + 4, { size: 3, font: F }); + } + + for (const tile of tiles) { + pageNo++; + doc.addPage({ size: [W * MM, H * MM], margin: 0 }); + sh = new Sheet(doc, W, H); + drawFrame(sh); + const tileIdx = tile.row * tile.nCols + tile.col + 1; + const tileNote = tiles.length > 1 ? `(分块 ${tileIdx}/${tiles.length})` : ''; + drawTitleBlock(sh, meta, { name: v.name + tileNote, scale: '1:1', page: `${pageNo}/${totalPages}` }); + + const scale = 1; + // 单块时在可用区域内居中;多块时保持左上对齐,保证各块之间能拼接 + const areaW = (areaX1 - areaX0) - dimLeft; + const areaH = (areaY1 - areaY0) - dimBottom; + const extraX = tiles.length > 1 ? 0 : Math.max(0, (areaW - (tile.x1 - tile.x0) * scale) / 2); + const extraY = tiles.length > 1 ? 0 : Math.max(0, (areaH - (tile.y1 - tile.y0) * scale) / 2); + const ox = areaX0 + dimLeft + extraX - (tile.x0 - v.bbox.minH) * scale; + const oy = areaY0 + extraY - (v.bbox.maxV - tile.y1) * scale; + const place = { ox, oy, scale }; + const clip = { x0: tile.x0, x1: tile.x1, y0: tile.y0, y1: tile.y1 }; + + drawView(sh, v, place, clip); + drawHoleMarkers(sh, v, place, holes, { clip }); + + sh.text( + `${v.name} 比例 1:1 (图纸横向 ${v.hAxis} / 纵向 ${v.vAxis})` + + (tiles.length > 1 ? ` 分块 ${tileIdx}/${tiles.length} 本块 ${(tile.x1 - tile.x0).toFixed(1)}×${(tile.y1 - tile.y0).toFixed(1)}mm` : ''), + 16, 12, { size: 3.6, font: F }); + + const P = (h, v2) => [ox + (h - v.bbox.minH) * scale, oy + (v.bbox.maxV - v2) * scale]; + const tl = P(tile.x0, tile.y1); + const br = P(tile.x1, tile.y0); + + // 总体尺寸:宽度标在最后一行,高度标在最左列 + if (tile.row === tile.nRows - 1) { + const dimY = br[1] + 10; + dimH(sh, tl[0], br[0], dimY, tiles.length > 1 ? `${(tile.x1 - tile.x0).toFixed(2)}` : `${v.width.toFixed(2)}`); + sh.line(tl[0], br[1], tl[0], dimY + 1, 0.18); + sh.line(br[0], br[1], br[0], dimY + 1, 0.18); + } + if (tile.col === 0) { + const dimX = tl[0] - 10; + dimV(sh, tl[1], br[1], dimX, tiles.length > 1 ? `${(tile.y1 - tile.y0).toFixed(2)}` : `${v.height.toFixed(2)}`); + sh.line(dimX - 1, tl[1], tl[0], tl[1], 0.18); + sh.line(dimX - 1, br[1], tl[0], br[1], 0.18); + } + + // 孔距标注:仅当整组孔位落在同一块内,且标注空间足够 + candPatterns.slice(0, nPat).forEach((pt, idx) => { + const list = pt.holes.map(id => holes.find(h => h.id === id)).filter(Boolean); + const us = [...new Set(list.map(h => h.center[0]))].sort((a, b) => a - b); + const vs = [...new Set(list.map(h => h.center[1]))].sort((a, b) => a - b); + if (us.length < 2 || vs.length < 2) return; + if (us[0] < tile.x0 || us[us.length - 1] > tile.x1 || vs[0] < tile.y0 || vs[vs.length - 1] > tile.y1) return; + const sy2 = br[1] + 19 + idx * 9; + const sx2 = tl[0] - 19 - idx * 9; + if (sy2 + 3 > areaY1 || sx2 - 3 < areaX0) return; + const p0 = P(us[0], vs[0]); + const p1 = P(us[us.length - 1], vs[0]); + const p2 = P(us[0], vs[vs.length - 1]); + dimH(sh, p0[0], p1[0], sy2, `孔距 ${pt.uniformDu.toFixed(2)}`, { size: 2.8 }); + sh.line(p0[0], p0[1], p0[0], sy2 + 1, 0.15); + sh.line(p1[0], p1[1], p1[0], sy2 + 1, 0.15); + dimV(sh, p2[1], p0[1], sx2, `孔距 ${pt.uniformDv.toFixed(2)}`, { size: 2.8 }); + sh.line(p2[0], p2[1], sx2 - 1, p2[1], 0.15); + sh.line(p0[0], p0[1], sx2 - 1, p0[1], 0.15); + }); + + // 分块接缝标记:相邻块用同位置十字线对接 + if (tiles.length > 1) { + const mid = (a, b) => (a + b) / 2; + if (tile.col > 0) { + const x = tl[0]; + sh.line(x, areaY0 - 3, x, areaY0, 0.35); + sh.line(x - 2, areaY0 - 1.5, x + 2, areaY0 - 1.5, 0.35); + } + if (tile.col < tile.nCols - 1) { + const x = br[0]; + sh.line(x, areaY0 - 3, x, areaY0, 0.35); + sh.line(x - 2, areaY0 - 1.5, x + 2, areaY0 - 1.5, 0.35); + } + if (tile.row > 0) { + const y = tl[1]; + sh.line(areaX0 - 3, y, areaX0, y, 0.35); + sh.line(areaX0 - 1.5, y - 2, areaX0 - 1.5, y + 2, 0.35); + } + if (tile.row < tile.nRows - 1) { + const y = br[1]; + sh.line(areaX0 - 3, y, areaX0, y, 0.35); + sh.line(areaX0 - 1.5, y - 2, areaX0 - 1.5, y + 2, 0.35); + } + } + } + } + + // ========== 孔位明细表 + 判定说明 ========== + pageNo++; + doc.addPage({ size: [A4W * MM, A4H * MM], margin: 0 }); + sh = new Sheet(doc, A4W, A4H); + drawFrame(sh); + sh.text(`${meta.name} 孔位明细表(含可见性判定)`, 12, 14, { size: 5.5, font: F }); + sh.text('坐标基准:包围盒最小角点为原点;X/Y/Z 为孔轴线中心坐标;深度为圆柱段轴向长度;孔位编号在各视图页一致。', 12, 20, { size: 2.9, font: F }); + const t = drawHoleTable(sh, holes); + + let yy = t.bottom + 9; + if (yy < sh.H - 60) { + const needFlip = holes.filter(h => h.judge && !h.judge.visible && h.judge.view); + const needSection = holes.filter(h => h.judge && !h.judge.view); + sh.text('判定说明(完整说明见首页)', 12, yy, { size: 3.8, font: F }); + yy += 6.5; + const bullets = []; + if (needFlip.length) bullets.push(`需翻面 / 另出视图的孔位(${needFlip.length} 个):${needFlip.map(h => `${h.label}(${h.judge.viewName})`).join('、')} —— 已按对应视图单独出图`); + if (needSection.length) bullets.push(`三视图完全不可见的内部孔位(${needSection.length} 个):${needSection.map(h => `${h.label}(${h.judge.placement})`).join('、')} —— 建议补剖视图`); + for (const b of bullets) { + let rest = b; + while (rest.length) { + const chunk = rest.slice(0, 58); + rest = rest.slice(58); + sh.text('· ' + chunk, 12, yy, { size: 3, font: F }); + yy += 5; + } + } + } + + doc.end(); + return new Promise((resolve, reject) => { + stream.on('finish', () => resolve(outPath)); + stream.on('error', reject); + }); +} + +function fmtList(a) { return a.length ? a.map(x => x.toFixed(2)).join('/') + ' mm' : '—'; } + +module.exports = { renderPDF, findFont }; diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/step.js b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/step.js new file mode 100644 index 00000000..36ef23ca --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/step.js @@ -0,0 +1,62 @@ +'use strict'; +// STEP 加载器:用 occt-import-js(OpenCascade WASM)把 STEP/IGES 转成三角网格。 +// 该库为可选依赖:缺失时给出明确提示,不影响 STL 路径。 + +const fs = require('fs'); +const path = require('path'); + +let occtPromise = null; +function getOcct() { + if (!occtPromise) { + occtPromise = (async () => { + const mod = require('occt-import-js'); + const factory = mod.default || mod; + return await factory(); + })(); + } + return occtPromise; +} + +async function loadSTEP(filePath) { + let occt; + try { + occt = await getOcct(); + } catch (e) { + throw new Error('STEP 解析需要可选依赖 occt-import-js,请在项目目录执行:npm install occt-import-js'); + } + const buf = new Uint8Array(fs.readFileSync(filePath)); + const ext = path.extname(filePath).toLowerCase(); + let result; + if (ext === '.step' || ext === '.stp') result = occt.ReadStepFile(buf, null); + else if (ext === '.iges' || ext === '.igs') result = occt.ReadIgesFile(buf, null); + else throw new Error('不支持的扩展名:' + ext); + + const positions = []; + const indices = []; + let offset = 0; + for (const mesh of result.meshes || []) { + const posAttr = mesh.attributes && mesh.attributes.position; + const idxAttr = mesh.index; + // occt-import-js 的属性是 { array: Float32Array } 包装,也兼容裸数组 + const pos = posAttr && (posAttr.array || posAttr); + const idx = idxAttr && (idxAttr.array || idxAttr); + if (!pos || !idx) continue; + for (let i = 0; i < pos.length; i += 3) { + positions.push(pos[i], pos[i + 1], pos[i + 2]); + } + for (let i = 0; i < idx.length; i++) indices.push(idx[i] + offset); + offset += pos.length / 3; + } + if (!positions.length) { + throw new Error('STEP 文件未解析出三角面(该文件可能是纯曲面/线框模型,无实体可三角化)'); + } + return { + positions: Float64Array.from(positions), + indices: Uint32Array.from(indices), + format: 'step', + triangles: indices.length / 3, + brepFaces: (result.brep_faces || []).length, + }; +} + +module.exports = { loadSTEP }; diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/stl.js b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/stl.js new file mode 100644 index 00000000..c5b7b09e --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/stl.js @@ -0,0 +1,57 @@ +'use strict'; +// STL 解析器:支持二进制与 ASCII 两种格式。 +// 输出统一为 { positions: Float64Array(3n), indices: Uint32Array(3m) }。 + +function parseSTL(buf) { + const isAscii = looksAscii(buf); + if (isAscii) return parseAscii(buf.toString('ascii')); + return parseBinary(buf); +} + +function looksAscii(buf) { + if (buf.length < 84) return true; + const head = buf.slice(0, 5).toString('ascii').toLowerCase(); + if (head !== 'solid') return false; + // 二进制 STL 也可能以 "solid" 开头:用 80 字节后的面数做一致性校验 + const count = buf.readUInt32LE(80); + if (count === 0) return false; + const expected = 84 + count * 50; + if (expected === buf.length) return false; + return buf.slice(5, 64).toString('ascii').toLowerCase().includes('facet'); +} + +function parseBinary(buf) { + const count = buf.readUInt32LE(80); + const positions = new Float64Array(count * 9); + const indices = new Uint32Array(count * 3); + let off = 84; + for (let f = 0; f < count; f++) { + const base = f * 9; + for (let v = 0; v < 3; v++) { + const o = off + 12 + v * 12; + positions[base + v * 3] = buf.readFloatLE(o); + positions[base + v * 3 + 1] = buf.readFloatLE(o + 4); + positions[base + v * 3 + 2] = buf.readFloatLE(o + 8); + } + indices[f * 3] = f * 3; + indices[f * 3 + 1] = f * 3 + 1; + indices[f * 3 + 2] = f * 3 + 2; + off += 50; + } + return { positions, indices, format: 'binary', triangles: count }; +} + +function parseAscii(text) { + const verts = []; + const indices = []; + const re = /vertex\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)\s+([-+0-9.eE]+)/g; + let m; + while ((m = re.exec(text)) !== null) { + verts.push(parseFloat(m[1]), parseFloat(m[2]), parseFloat(m[3])); + } + const n = verts.length / 3; + for (let i = 0; i + 2 < n; i += 3) indices.push(i, i + 1, i + 2); + return { positions: Float64Array.from(verts), indices: Uint32Array.from(indices), format: 'ascii', triangles: n / 3 }; +} + +module.exports = { parseSTL }; diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/views.js b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/views.js new file mode 100644 index 00000000..aabb8938 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/src/views.js @@ -0,0 +1,104 @@ +'use strict'; +// 视图构建:正交投影 + 可见棱边提取。 +// 采用第一角投影(GB 惯例):俯视图在主视图下方,左视图在主视图右方。 +// 主视图:h = +X, v = +Z 观察者在 -Y +// 俯视图:h = +X, v = +Y 观察者在 +Z +// 左视图:h = -Y, v = +Z 观察者在 -X + +const M = require('./mesh'); + +const CREASE_COS = 0.90; // 折边阈值(夹角 > 25.8°) + +const VIEW_DEFS = { + top: { key: 'top', name: '俯视图', en: 'TOP VIEW', dir: [0, 0, 1], hp: (p) => p[0], vp: (p) => p[1], hVec: [1, 0, 0], vVec: [0, 1, 0], hAxis: 'X', vAxis: 'Y' }, + front: { key: 'front', name: '主视图', en: 'FRONT VIEW', dir: [0, -1, 0], hp: (p) => p[0], vp: (p) => p[2], hVec: [1, 0, 0], vVec: [0, 0, 1], hAxis: 'X', vAxis: 'Z' }, + left: { key: 'left', name: '左视图', en: 'LEFT VIEW', dir: [-1, 0, 0], hp: (p) => -p[1], vp: (p) => p[2], hVec: [0, -1, 0], vVec: [0, 0, 1], hAxis: 'Y(反向)', vAxis: 'Z' }, + bottom: { key: 'bottom', name: '底视图', en: 'BOTTOM VIEW', dir: [0, 0, -1], hp: (p) => p[0], vp: (p) => -p[1], hVec: [1, 0, 0], vVec: [0, -1, 0], hAxis: 'X', vAxis: 'Y' }, + back: { key: 'back', name: '后视图', en: 'REAR VIEW', dir: [0, 1, 0], hp: (p) => -p[0], vp: (p) => p[2], hVec: [-1, 0, 0], vVec: [0, 0, 1], hAxis: 'X(反向)', vAxis: 'Z' }, + right: { key: 'right', name: '右视图', en: 'RIGHT VIEW', dir: [1, 0, 0], hp: (p) => p[1], vp: (p) => p[2], hVec: [0, 1, 0], vVec: [0, 0, 1], hAxis: 'Y', vAxis: 'Z' }, +}; + +function buildView(mesh, viewKey) { + const def = VIEW_DEFS[viewKey]; + const dir = def.dir; + const hp = def.hp, vp = def.vp; + + const proj = (vi) => { + const p = [mesh.vpos[vi * 3], mesh.vpos[vi * 3 + 1], mesh.vpos[vi * 3 + 2]]; + return [hp(p), vp(p)]; + }; + + const segments = []; + let minH = Infinity, maxH = -Infinity, minV = Infinity, maxV = -Infinity; + const touch = (x, y) => { + if (x < minH) minH = x; + if (x > maxH) maxH = x; + if (y < minV) minV = y; + if (y > maxV) maxV = y; + }; + + for (const e of mesh.edges) { + const a = proj(e.u), b = proj(e.w); + const f1 = mesh.faces[e.f1]; + const front1 = M.dot(f1.n, dir) > 1e-6; + let draw = false; + let kind = 'edge'; + if (e.f2 >= 0) { + const f2 = mesh.faces[e.f2]; + const front2 = M.dot(f2.n, dir) > 1e-6; + const crease = Math.abs(M.dot(f1.n, f2.n)) < CREASE_COS; + const silhouette = front1 !== front2; + if ((crease || silhouette) && (front1 || front2)) { + draw = true; + kind = crease ? 'crease' : 'silhouette'; + } + } else { + // 开放边界边:仅在该面朝向观察者时绘制 + draw = front1; + kind = 'boundary'; + } + if (!draw) continue; + if (Math.abs(a[0] - b[0]) < 1e-9 && Math.abs(a[1] - b[1]) < 1e-9) continue; + segments.push({ a, b, kind }); + touch(a[0], a[1]); touch(b[0], b[1]); + } + + // 整体投影轮廓(用于确定视图外框,不绘制) + for (let i = 0; i < mesh.vcount; i++) { + const p = [mesh.vpos[i * 3], mesh.vpos[i * 3 + 1], mesh.vpos[i * 3 + 2]]; + const x = hp(p), y = vp(p); + touch(x, y); + } + + return { + key: viewKey, name: def.name, en: def.en, dir, hAxis: def.hAxis, vAxis: def.vAxis, + segments, bbox: { minH, maxH, minV, maxV }, + width: maxH - minH, height: maxV - minV, + }; +} + +// 孔位在指定视图中的投影:圆柱正投影为椭圆 +// 垂直于投影轴的半轴 = R;沿投影轴的半轴 = R * |cos(轴, 视线)| +// 视线与孔轴平行时退化为半径 R 的圆。 +function projectHole(hole, viewKey) { + const def = VIEW_DEFS[viewKey]; + const p = hole.center; + const h = def.hp(p), v = def.vp(p); + const ax = hole.axis; + const dir = def.dir; + const c = Math.abs(M.dot(ax, dir)); + const semiMajor = hole.radius; // 垂直于投影轴 + const semiMinor = hole.radius * c; // 沿投影轴 + // 投影后的轴方向(在视图平面内) + const hv = def.hVec, vv = def.vVec; + const ah = M.dot(ax, hv), av = M.dot(ax, vv); + const al = Math.hypot(ah, av); + return { + h, v, r: hole.radius, semiMajor, semiMinor, + axisAngle: al > 1e-9 ? Math.atan2(av, ah) : 0, + isCircle: c > 0.995, + visible: hole.judge ? hole.judge.view === viewKey : false, + }; +} + +module.exports = { buildView, projectHole, VIEW_DEFS }; diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/test/engine.test.cjs b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/test/engine.test.cjs new file mode 100644 index 00000000..6dd3adc2 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/test/engine.test.cjs @@ -0,0 +1,135 @@ +'use strict'; +// cad-drawing 引擎测试:几何解析、孔位识别、通盲判定、可见性判定、孔距分组。 +// 运行:node --test scripts/cad2pdf/test +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const { parseSTL } = require('../src/stl'); +const { buildMesh } = require('../src/mesh'); +const { canonicalize } = require('../src/orient'); +const { detectFeatures, analyzePatterns } = require('../src/features'); + +// ---- 构造测试几何:带一个通孔的板(外廓取多边形近似矩形,内孔为圆) ---- +function buildPlateWithHole({ + sizeX = 100, sizeY = 60, sizeZ = 10, holeR = 10, holeX = 50, holeY = 30, segments = 48, +} = {}) { + const positions = []; + const indices = []; + const push = (x, y, z) => { positions.push(x, y, z); return positions.length / 3 - 1; }; + + const outer = []; + const inner = []; + for (let i = 0; i < segments; i++) { + const a = (i / segments) * Math.PI * 2; + const dx = Math.cos(a), dy = Math.sin(a); + // 外廓:沿该方向射到矩形边界 + const tx = dx > 0 ? (sizeX / 2) / dx : dx < 0 ? (-sizeX / 2) / dx : Infinity; + const ty = dy > 0 ? (sizeY / 2) / dy : dy < 0 ? (-sizeY / 2) / dy : Infinity; + const t = Math.min(tx, ty); + outer.push([holeX + dx * t, holeY + dy * t]); + inner.push([holeX + dx * holeR, holeY + dy * holeR]); + } + + const zTop = sizeZ, zBot = 0; + const oT = outer.map(([x, y]) => push(x, y, zTop)); + const iT = inner.map(([x, y]) => push(x, y, zTop)); + const oB = outer.map(([x, y]) => push(x, y, zBot)); + const iB = inner.map(([x, y]) => push(x, y, zBot)); + + const quad = (a, b, c, d) => { indices.push(a, b, c, a, c, d); }; + for (let i = 0; i < segments; i++) { + const j = (i + 1) % segments; + quad(oT[i], oT[j], iT[j], iT[i]); // 顶面(环形) + quad(iB[i], iB[j], oB[j], oB[i]); // 底面(环形) + quad(oB[i], oB[j], oT[j], oT[i]); // 外侧壁 + quad(iT[i], iT[j], iB[j], iB[i]); // 孔壁(法向朝内) + } + return { positions: Float64Array.from(positions), indices: Uint32Array.from(indices) }; +} + +function toBinarySTL(raw) { + const count = raw.indices.length / 3; + const buf = Buffer.alloc(84 + count * 50); + buf.writeUInt32LE(count, 80); + for (let f = 0; f < count; f++) { + const base = 84 + f * 50; + const p = [0, 1, 2].map(k => { + const vi = raw.indices[f * 3 + k] * 3; + return [raw.positions[vi], raw.positions[vi + 1], raw.positions[vi + 2]]; + }); + const u = [p[1][0] - p[0][0], p[1][1] - p[0][1], p[1][2] - p[0][2]]; + const v = [p[2][0] - p[0][0], p[2][1] - p[0][1], p[2][2] - p[0][2]]; + const n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + const nl = Math.hypot(...n) || 1; + for (let k = 0; k < 3; k++) buf.writeFloatLE(n[k] / nl, base + k * 4); + for (let k = 0; k < 3; k++) { + for (let c = 0; c < 3; c++) buf.writeFloatLE(p[k][c], base + 12 + (k * 3 + c) * 4); + } + buf.writeUInt16LE(0, base + 48); + } + return buf; +} + +test('二进制 STL 可被解析,面数与包围盒正确', () => { + const raw = buildPlateWithHole(); + const parsed = parseSTL(toBinarySTL(raw)); + assert.equal(parsed.triangles, raw.indices.length / 3); + const mesh = buildMesh(parsed); + const size = mesh.size; + assert.ok(Math.abs(size[0] - 100) < 1e-6, `X 尺寸 ${size[0]}`); + assert.ok(Math.abs(size[1] - 60) < 1e-6, `Y 尺寸 ${size[1]}`); + assert.ok(Math.abs(size[2] - 10) < 1e-6, `Z 尺寸 ${size[2]}`); +}); + +test('自动摆正后厚度轴落在 Z、原点归零', () => { + const raw = buildPlateWithHole(); + const canon = canonicalize(raw); + const mesh = buildMesh(canon); + assert.ok(mesh.bbox.min.every(v => Math.abs(v) < 1e-6), '包围盒最小角点归零'); + assert.ok(Math.abs(mesh.size[2] - 10) < 1e-6, '最薄轴映射到 Z'); +}); + +test('识别出唯一的通孔,直径与中心正确,且俯视图可见', () => { + const raw = buildPlateWithHole({ holeR: 10 }); + const mesh = buildMesh(canonicalize(raw)); + const { holes } = detectFeatures(mesh); + assert.equal(holes.length, 1, `只应识别 1 个孔,实际 ${holes.length}`); + const h = holes[0]; + assert.ok(Math.abs(h.diameter - 20) < 0.3, `孔径 ${h.diameter}`); + assert.ok(Math.abs(h.center[0] - 50) < 0.3, `孔心 X ${h.center[0]}`); + assert.ok(Math.abs(h.center[1] - 30) < 0.3, `孔心 Y ${h.center[1]}`); + assert.ok(Math.abs(h.center[2] - 5) < 0.5, `孔心 Z ${h.center[2]}`); + assert.equal(h.type, '通孔', `孔类型 ${h.type}`); + assert.equal(h.judge.view, 'top', `归属视图 ${h.judge.view}`); + assert.equal(h.judge.visible, true); +}); + +test('孔距分组把同一阵列识别为均匀矩形', () => { + const raw = buildPlateWithHole({ holeR: 5 }); + const mesh = buildMesh(canonicalize(raw)); + const { holes } = detectFeatures(mesh); + const patterns = analyzePatterns(holes, mesh.bbox.min); + assert.ok(patterns.length >= 0, '孔距分析不抛错'); + for (const p of patterns) { + assert.ok(p.count >= 1 && p.view, '分组含视图与孔数'); + } +}); + +test('STEP 之外:ASCII STL 同样可解析', () => { + const raw = buildPlateWithHole({ segments: 12 }); + const lines = ['solid test']; + for (let f = 0; f < raw.indices.length / 3; f++) { + lines.push('facet normal 0 0 0', 'outer loop'); + for (let k = 0; k < 3; k++) { + const vi = raw.indices[f * 3 + k] * 3; + lines.push(`vertex ${raw.positions[vi]} ${raw.positions[vi + 1]} ${raw.positions[vi + 2]}`); + } + lines.push('endloop', 'endfacet'); + } + lines.push('endsolid test'); + const parsed = parseSTL(Buffer.from(lines.join('\n'), 'ascii')); + assert.equal(parsed.triangles, raw.indices.length / 3); +}); diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/tools/pdf2png.py b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/tools/pdf2png.py new file mode 100644 index 00000000..97377235 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/scripts/cad2pdf/tools/pdf2png.py @@ -0,0 +1,17 @@ +import sys, os +import pypdfium2 as pdfium + +src = sys.argv[1] +outdir = sys.argv[2] if len(sys.argv) > 2 else os.path.dirname(src) +scale = float(sys.argv[3]) if len(sys.argv) > 3 else 2.0 +os.makedirs(outdir, exist_ok=True) +pdf = pdfium.PdfDocument(src) +base = os.path.splitext(os.path.basename(src))[0] +for i in range(len(pdf)): + page = pdf[i] + bitmap = page.render(scale=scale) + img = bitmap.to_pil() + out = os.path.join(outdir, f"{base}_p{i+1}.png") + img.save(out) + print(out, img.size) +print("pages:", len(pdf)) diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/servers.mcp.json b/plugins/Xiong-cmyk-collab/cad-drawing/servers.mcp.json new file mode 100644 index 00000000..c0e07e66 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/servers.mcp.json @@ -0,0 +1,15 @@ +{ + "schemaVersion": 1, + "mcpServers": { + "cad-drawing": { + "type": "stdio", + "command": "node", + "args": [ + "./mcp/server.js" + ], + "env": {}, + "description": "3D 工程文件转 1:1 可打印 A4 图纸:孔位识别、通盲判定、孔距分析、可见性判定", + "timeout": 180000 + } + } +} diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/skills/SKILL.md b/plugins/Xiong-cmyk-collab/cad-drawing/skills/SKILL.md new file mode 100644 index 00000000..89eddaff --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/skills/SKILL.md @@ -0,0 +1,96 @@ +--- +name: cad-drawing +description: "把 3D 工程文件(STL / STEP)转成 1:1 可打印 A4 工程图,并给出每个孔位的可见性判定。Trigger: STL 转图纸, STEP 转 PDF, 3D 文件出图, 1:1 打印图, 三视图, 俯视图正视图侧视图, 孔位表, 螺丝孔距, 孔位判定, 打样图纸, cad-drawing" +--- + +# 3D 打印图助手 + +把 3D 工程文件(.stl / .3mf / .step / .stp / .iges)转成 **A4 纸 1:1 可打印**的工程图 PDF,并给出**每个孔位的可见性判定**。 + +## 何时用 + +用户发来 STL / STEP / 3MF 文件,想要: +- 打印出来量尺寸、做样板、核对实物 +- 知道螺丝孔在哪儿、孔距多少 +- 知道哪些孔在常规三视图里**看不到**(底面 / 背面 / 腔体内),需要单独核对 + +## 主路径:直接调 MCP 工具 + +工具已在本插件内注册,**优先用工具,不要手搓脚本**: + +| 工具 | 用途 | 必填参数 | +| --- | --- | --- | +| `convert_to_drawing` | 出图:生成 PDF + 孔位 CSV + 特征 JSON | `file_path` | +| `inspect_holes` | 只分析不落盘:孔位清单与判定、孔距分组 | `file_path` | + +可选参数:`output_dir`(输出目录,默认输入文件所在目录)、`name`(零件名,默认取文件名)、`orient`(`auto` 自动摆正 / `none` 保持原始坐标)。 + +典型流程: +1. 先 `inspect_holes` 看识别结果对不对(尤其孔位数量与判定) +2. 再 `convert_to_drawing` 正式出图 +3. 渲染 PDF 逐页目视验收(见「验收」) +4. 回报产出路径 + 页数 + 孔位统计 + 需单独核对的孔位 + +## 备用路径:命令行 + +MCP 不可用时,直接跑工具: + +``` +node scripts/cad2pdf/src/cli.js <输入文件> --out <输出目录> [--name 零件名] +``` + +工具目录位置解析顺序:环境变量 `CAD2PDF_TOOL_DIR` → 插件内自带副本 `scripts/cad2pdf`。 + +## 产出结构 + +| 文件 | 内容 | +| --- | --- | +| `<零件名>_打印图.pdf` | 概览页 + 各视图 1:1 页(尺寸/孔距标注)+ 孔位明细表页 | +| `<零件名>_孔位明细.csv` | 一孔一行 9 列(编号/类型/直径/深度/XYZ/归属视图/判定) | +| `<零件名>_特征.json` | 包围盒、定向变换、全孔位明细、凸台、孔距分组 | + +页面构成:概览页(零件信息 + 三视图缩略 + 孔位统计 + 判定说明)→ 各视图 1:1 页 → 孔位明细表页。视图超出 A4 可打印区时,按 1:1 分块拼接并额外出一张整件缩略页(显式标注实际比例)。 + +## 判定口径 + +| 判定 | 含义 | 处理 | +| --- | --- | --- | +| 可见 | 孔口朝向该视图且无遮挡 | 图面画编号气泡 | +| 需底视图 / 需后视图 / 需右视图 | 孔口朝向未包含的方向 | 追加该视图页,明细表单列 | +| 被遮挡·需剖视 | 开口被自身结构挡住 | 明细表标注,建议补剖视 | +| 内部封闭腔·需剖视 | 孔口被材料完全包围 | 三视图均不可见,必须单列 | +| 斜向孔·需局部视图 | 轴线与三视图均不平行 | 标注并提示补局部视图 | + +## 硬规则 + +- 视图页必须 1:1;缩略页必须写明实际比例,不得当 1:1 交付 +- 三视图齐全:俯视 / 主视 / 左视(第一角投影:俯视图在下、左视图在右) +- 图面只标编号气泡,明细进表格,不要把引线拉满图 +- 不同直径的孔不得混算孔距 +- 数字全部来自几何实测,不得臆断螺纹、牙型、钻尖深度 +- 未识别到孔位时如实报告「未检出孔位」,不编造 + +## 验收 + +交付前必须把 PDF 每页渲染成 PNG 并目视检查(文字重叠 / 尺寸线出界 / 压标题栏 / 气泡缺失 / 编号与表格是否一一对应): + +``` +python scripts/cad2pdf/tools/pdf2png.py <预览目录> 1.6 +``` + +未渲染就交付 = 不合格。 + +## 排错 + +| 现象 | 处理 | +| --- | --- | +| `STEP 文件未解析出三角面` | 该 STEP 是纯曲面/线框模型,无实体,需改用 STL | +| `3MF 包内未找到 .model 文件` | 该 3MF 不是标准切片工程包,用切片软件重新导出 | +| `cad2pdf engine not found` | 设置环境变量 `CAD2PDF_TOOL_DIR` 指向工具目录 | +| 孔位 0 个 | 检查 STL 是否只有外形无孔;不编造孔位 | +| 中文变方块 | 改 `scripts/cad2pdf/src/pdfout.js` 的 `FONT_CANDIDATES` 指向系统已装中文字体 | +| 依赖缺失 | `npm install --prefix "scripts/cad2pdf" pdfkit occt-import-js` | + +## 完整规范 + +字段口径、判定规则、排版铁律与边界处理见 `references/workflow-sop.md`(十一节工作流 SOP)。 diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/skills/cad-drawing/SKILL.md b/plugins/Xiong-cmyk-collab/cad-drawing/skills/cad-drawing/SKILL.md new file mode 100644 index 00000000..89eddaff --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/skills/cad-drawing/SKILL.md @@ -0,0 +1,96 @@ +--- +name: cad-drawing +description: "把 3D 工程文件(STL / STEP)转成 1:1 可打印 A4 工程图,并给出每个孔位的可见性判定。Trigger: STL 转图纸, STEP 转 PDF, 3D 文件出图, 1:1 打印图, 三视图, 俯视图正视图侧视图, 孔位表, 螺丝孔距, 孔位判定, 打样图纸, cad-drawing" +--- + +# 3D 打印图助手 + +把 3D 工程文件(.stl / .3mf / .step / .stp / .iges)转成 **A4 纸 1:1 可打印**的工程图 PDF,并给出**每个孔位的可见性判定**。 + +## 何时用 + +用户发来 STL / STEP / 3MF 文件,想要: +- 打印出来量尺寸、做样板、核对实物 +- 知道螺丝孔在哪儿、孔距多少 +- 知道哪些孔在常规三视图里**看不到**(底面 / 背面 / 腔体内),需要单独核对 + +## 主路径:直接调 MCP 工具 + +工具已在本插件内注册,**优先用工具,不要手搓脚本**: + +| 工具 | 用途 | 必填参数 | +| --- | --- | --- | +| `convert_to_drawing` | 出图:生成 PDF + 孔位 CSV + 特征 JSON | `file_path` | +| `inspect_holes` | 只分析不落盘:孔位清单与判定、孔距分组 | `file_path` | + +可选参数:`output_dir`(输出目录,默认输入文件所在目录)、`name`(零件名,默认取文件名)、`orient`(`auto` 自动摆正 / `none` 保持原始坐标)。 + +典型流程: +1. 先 `inspect_holes` 看识别结果对不对(尤其孔位数量与判定) +2. 再 `convert_to_drawing` 正式出图 +3. 渲染 PDF 逐页目视验收(见「验收」) +4. 回报产出路径 + 页数 + 孔位统计 + 需单独核对的孔位 + +## 备用路径:命令行 + +MCP 不可用时,直接跑工具: + +``` +node scripts/cad2pdf/src/cli.js <输入文件> --out <输出目录> [--name 零件名] +``` + +工具目录位置解析顺序:环境变量 `CAD2PDF_TOOL_DIR` → 插件内自带副本 `scripts/cad2pdf`。 + +## 产出结构 + +| 文件 | 内容 | +| --- | --- | +| `<零件名>_打印图.pdf` | 概览页 + 各视图 1:1 页(尺寸/孔距标注)+ 孔位明细表页 | +| `<零件名>_孔位明细.csv` | 一孔一行 9 列(编号/类型/直径/深度/XYZ/归属视图/判定) | +| `<零件名>_特征.json` | 包围盒、定向变换、全孔位明细、凸台、孔距分组 | + +页面构成:概览页(零件信息 + 三视图缩略 + 孔位统计 + 判定说明)→ 各视图 1:1 页 → 孔位明细表页。视图超出 A4 可打印区时,按 1:1 分块拼接并额外出一张整件缩略页(显式标注实际比例)。 + +## 判定口径 + +| 判定 | 含义 | 处理 | +| --- | --- | --- | +| 可见 | 孔口朝向该视图且无遮挡 | 图面画编号气泡 | +| 需底视图 / 需后视图 / 需右视图 | 孔口朝向未包含的方向 | 追加该视图页,明细表单列 | +| 被遮挡·需剖视 | 开口被自身结构挡住 | 明细表标注,建议补剖视 | +| 内部封闭腔·需剖视 | 孔口被材料完全包围 | 三视图均不可见,必须单列 | +| 斜向孔·需局部视图 | 轴线与三视图均不平行 | 标注并提示补局部视图 | + +## 硬规则 + +- 视图页必须 1:1;缩略页必须写明实际比例,不得当 1:1 交付 +- 三视图齐全:俯视 / 主视 / 左视(第一角投影:俯视图在下、左视图在右) +- 图面只标编号气泡,明细进表格,不要把引线拉满图 +- 不同直径的孔不得混算孔距 +- 数字全部来自几何实测,不得臆断螺纹、牙型、钻尖深度 +- 未识别到孔位时如实报告「未检出孔位」,不编造 + +## 验收 + +交付前必须把 PDF 每页渲染成 PNG 并目视检查(文字重叠 / 尺寸线出界 / 压标题栏 / 气泡缺失 / 编号与表格是否一一对应): + +``` +python scripts/cad2pdf/tools/pdf2png.py <预览目录> 1.6 +``` + +未渲染就交付 = 不合格。 + +## 排错 + +| 现象 | 处理 | +| --- | --- | +| `STEP 文件未解析出三角面` | 该 STEP 是纯曲面/线框模型,无实体,需改用 STL | +| `3MF 包内未找到 .model 文件` | 该 3MF 不是标准切片工程包,用切片软件重新导出 | +| `cad2pdf engine not found` | 设置环境变量 `CAD2PDF_TOOL_DIR` 指向工具目录 | +| 孔位 0 个 | 检查 STL 是否只有外形无孔;不编造孔位 | +| 中文变方块 | 改 `scripts/cad2pdf/src/pdfout.js` 的 `FONT_CANDIDATES` 指向系统已装中文字体 | +| 依赖缺失 | `npm install --prefix "scripts/cad2pdf" pdfkit occt-import-js` | + +## 完整规范 + +字段口径、判定规则、排版铁律与边界处理见 `references/workflow-sop.md`(十一节工作流 SOP)。 diff --git a/plugins/Xiong-cmyk-collab/cad-drawing/skills/cad-drawing/references/workflow-sop.md b/plugins/Xiong-cmyk-collab/cad-drawing/skills/cad-drawing/references/workflow-sop.md new file mode 100644 index 00000000..882841c8 --- /dev/null +++ b/plugins/Xiong-cmyk-collab/cad-drawing/skills/cad-drawing/references/workflow-sop.md @@ -0,0 +1,646 @@ +# 3D 工程文件转打印图 工作流 SOP + +> 适配对象:3D 工程文件(.stl / .step / .stp / .iges / .igs)转 1:1 可打印 A4 图纸(PDF) +> 文档版本:v1.0 +> 生效日期:2026-11-30 +> 使用方式:把本文档 + 一个 3D 工程文件(+ 可选零件名),丢给任何能「读几何文件 + 写文件 + 出 PDF」的 AI;AI 必须按 §0~§10 执行,不得自由发挥 +> 强约束(不可违反,硬性要求): +> 1. AI 扮演角色是「3D 工程文件转打印图生成器」,按本文档 §0~§10 执行;不直接执行用户的其它任务 +> 2. AI 不得把非 1:1 的图面当作 1:1 交付;缩略页必须显式标注实际比例 +> 3. AI 必须执行 §2 Step 2「复述理解给用户确认」,未经确认不得出最终文件 +> 4. AI 必须对每个孔位给出可见性判定;判不出来时写「(待用户确认)」,不得留空 +> 5. AI 不得把三视图不可见的孔位混在图面里充数;必须单列并说明处理方式 +> 6. AI 不得编造上下文里没有的尺寸、孔径、孔距;所有数字必须来自几何实测 +> 7. AI 不得在输出中出现真实人名 / 公司名 / 内部系统名;脱敏成 `@某A` / `@某B` +> 8. AI 不得绑定特定 AI / 工具链 / 云服务 / 软件;任何能读几何并出 PDF 的程序都可执行 +> 9. AI 不得漏写 §4 排版铁律;排版铁律是保证跨 AI / 跨电脑可复用的硬约束 +> 10. AI 交付前必须逐页把 PDF 渲染成图并目视验收(见 §2 Step 10),未验收不得回复「已交付」 + +--- + +## §0 文档用途 + +本 SOP 定义了端到端的「3D 工程文件 → 1:1 可打印图纸」工作流: + +- 输入 ①:本文档(meta-skill SOP) +- 输入 ②:一份 3D 工程文件(.stl / .step / .stp / .iges / .igs),单位通常为毫米 +- 输入 ③(可选):零件名、图纸口径参数(投影法、比例策略、分块策略) +- 输出:三件套 + - `<零件名>_打印图.pdf`:概览页 + 各视图 1:1 页 + 孔位明细表页(含可见性判定) + - `<零件名>_孔位明细.csv`:孔位数据表(带 BOM,可直接用 Excel 打开) + - `<零件名>_特征.json`:完整几何与特征报告(供复核与二次开发) + +AI 在执行转换时,不得自由发挥版面、字段命名、判定口径,必须严格遵守本文档定义的字段、块状结构、排版铁律、措辞规范。 + +--- + +## §1 输入与输出定义 + +### 1.1 输入清单表 + +| 输入 | 是否必填 | 说明 | +| --- | --- | --- | +| 本工作流 md | 必填 | AI 必须先通读 | +| 3D 工程文件 | 必填 | .stl / .step / .stp / .iges / .igs;含三角面或 B-rep 实体 | +| 零件名 | 可选 | 未指定时取文件名(去扩展名) | +| 图纸口径 | 可选 | 投影法 / 比例策略 / 分块策略;缺省见 §6 | + +### 1.2 输入质量容忍度 + +- STL 为二进制或 ASCII 均可;ASCII 需容忍顶点顺序错乱、缺面、重复面 → 重复面按位置去重,缺面不影响出图但需在特征报告中记录 +- STEP 若为纯曲面 / 线框模型(无实体)→ 无法三角化,按 §8 报错,不产出空文件 +- 装配体(多实体)→ 全部实体合并为一件整体出图,但孔位编号连续 +- 单位非毫米(如英寸)→ 尺寸数值按原样出图并在概览页标注单位来源(待用户确认是否换算) +- 网格非水密(存在开口边)→ 仍可出图,但棱边判定精度下降,需在交付说明中提示 + +### 1.3 输出清单 + +- 格式:PDF(主)+ CSV(孔位数据)+ JSON(特征报告) +- 文件名:`<零件名>_打印图.pdf` / `<零件名>_孔位明细.csv` / `<零件名>_特征.json` +- 字符编码:UTF-8(CSV 带 BOM,保证 Excel 中文不乱码) +- 行尾:Windows CRLF +- 不使用 Emoji 装饰字段标题 +- 输出路径:`<由调用方传入,默认 D:\Ai\生成skill\>`(待用户确认);目录不存在时 AI 必须先创建 +- 包含内容:概览页(零件信息 + 三视图缩略 + 孔位统计 + 判定说明)、各视图 1:1 页(尺寸标注 + 孔位编号)、孔位明细表页(全孔位数据 + 可见性判定) + +### 1.4 适用范围 + +✅ 适用: + +- 机械零件 / 结构件 / 板类件的尺寸确认与打印核对 +- 输入 1 份 3D 工程文件,需产出可 1:1 打印的图纸 +- 需要明确「哪些孔位在常规三视图里看不到」的场合 + +⚠️ 部分适用: + +- 装配体(含多个独立零件)→ 合并出图,孔位编号连续,必要时补充「本图含 N 个实体」说明 +- 曲面 / 自由曲面为主的零件 → 棱边由折边推断,曲线轮廓需人工复核 + +❌ 不适用(直接告诉用户): + +- 纯点云 / 扫描网格(无可靠拓扑)→ 只能出轮廓示意,不能出尺寸图 +- 需要出加工工艺图 / 公差标注 / 形位公差 → 本 SOP 只出几何尺寸与孔位,不含工艺信息 + +--- + +## §2 工作流主流程(强约束) + +### Step 1:接收并校验输入文件 + +必做动作: + +1. 确认文件存在、可读,扩展名在支持列表内 +2. 读取几何,统计三角面数、实体数、包围盒尺寸 +3. 确认单位来源;非毫米时在概览页标注「单位按原文件,1:1 依据待用户确认」 +4. 预检:STEP 无实体、STL 零面 → 直接按 §8 报错退出 + +输出:几何对象 + 基础统计(面数 / 实体数 / 包围盒) + +--- + +### ⭐ Step 2:复述理解给用户确认(强约束,不可跳过) + +必做动作: + +- 复述 6 项:识别到的输入 / 输入→处理→输出循环 / 关键字段清单 / 排版铁律 / 图纸长什么样 / 没识别清楚的地方 +- 至少确认 3 个口径项:投影法、比例策略、大件处理策略 +- 用 ask_user 让用户选 A / B / C(A = 口径正确,直接出图;B = 有偏差,用户补充;C = 重来) + +禁止: + +- ❌ 跳过本步直接出图 +- ❌ 用「已自动确认」等字样绕过本步 +- ❌ 未经确认擅自生成最终 PDF + +输出:用户确认过的图纸口径(投影法 / 比例策略 / 分块策略 / 孔位表字段) + +--- + +### Step 3:解析几何并自动摆正 + +必做动作: + +1. 顶点按位置去重焊接(容差 0.001mm),建立面表与边表 +2. 自动定向:取包围盒最小延伸轴为厚度轴 → 映射到 Z;最长轴 → 映射到 X;构成右手系 +3. 原点平移:包围盒最小角点归零,使图纸坐标可用卡尺直接比对 +4. 在概览页记录本次定向动作(如「厚度轴 Y→Z,长轴 Z→X」) + +输出:定向后的网格 + 变换记录(写入特征 JSON) + +--- + +### Step 4:识别孔位与凸台 + +必做动作: + +1. 按面法线夹角做区域生长,把平滑曲面聚成区域 +2. 对每个区域做圆柱拟合:法向必须垂直于候选轴(残差比 < 6%)且在轴向平面展开(展开度 > 15%),否则判为非圆柱 +3. 圆拟合半径残差必须 < max(0.03mm, 4% 半径) +4. 用法向与径向的内积符号区分「孔(凹)」与「凸台 / 外圆(凸)」 +5. 同轴同径的区域合并为一个特征;同轴不同径且轴向重叠 → 标记为沉孔 / 台阶孔 + +输出:孔位特征表(轴线、直径、轴向范围、孔/凸台标记) + +--- + +### Step 5:判定通孔 / 盲孔与孔口暴露度 + +必做动作: + +1. 对每个轴向端点做「越界探测」:沿轴向外侧的射线是否被材料挡住 +2. 做「侧向暴露度」探测:孔口法向 8 个方向各投一条射线,统计自由方向数 +3. 端点判定:越界不被挡且侧向自由方向 ≥ 3 → 该端为孔口 +4. 两端皆孔口 → 通孔;仅一端 → 盲孔(记开口朝向);两端皆非 → 内部腔体 +5. 暴露度 ≥ 6 → 外表面;3~5 → 凹槽 / 腔体内;< 3 → 内部封闭腔 + +输出:每个孔的类型 + 孔口朝向 + 暴露度 + 位置判定 + +--- + +### Step 6:三视图可见性判定与内部孔位单列 + +必做动作: + +1. 建立标准三视图方向:俯视(+Z)、主视(−Y)、左视(−X),第一角投影 +2. 孔口朝向与某视图方向夹角余弦 > 0.86 → 该视图可见 +3. 孔口朝向反向视图 → 判「需底视图 / 需后视图 / 需右视图」,必须追加对应视图页 +4. 孔口朝向与三视图均不平行 → 判「斜向孔·需局部视图」 +5. 沿孔口朝外做遮挡射线,被自身结构挡住 → 判「被遮挡·需剖视」 +6. 汇总「需翻面 / 需剖视 / 内部不可见」清单,在概览页与明细表页双处列明 + +输出:每个孔的归属视图 + 可见性判定(长判定 + 短判定)+ 需单独出图的视图清单 + +--- + +### Step 7:孔距阵列分析 + +必做动作: + +1. 按「归属视图 + 轴向 + 高度层(1mm 容差)」分组 +2. 同层内再按直径细分(直径差 < 0.05mm 视为同组),不同直径不得混算孔距 +3. 每组取 X、Y 方向的去重位置序列,算相邻间距 +4. 两向间距各自离散度 < 0.2mm → 判为均匀矩形阵列,给出统一孔距;否则给出全部差值 +5. 单孔组、斜向孔组不参与阵列判定,但孔位仍进明细表 + +输出:孔距分组表(孔数、直径、X 孔距、Y 孔距、均匀与否) + +--- + +### Step 8:生成 1:1 图纸 PDF + +必做动作: + +1. 概览页:零件信息 + 三视图缩略(第一角布局)+ 孔位统计 + 判定说明 +2. 各视图页:轮廓按 1:1 落图(图纸 mm = 模型 mm),总体宽高各标注一条尺寸 +3. 孔位在所属视图页画中心十字 + 编号气泡;气泡编号与明细表一致 +4. 均匀阵列的孔距在图上标注(X 向在图下方,Y 向在图左侧),每组一行,不与总体尺寸打架 +5. 视图超过 A4 可打印区 → 分块 1:1 拼接,接缝画对位十字;并额外出一张整件缩略页,红虚线标分块边界,显式标注实际比例 +6. 孔位明细表页:全孔位逐行列出 + 可见性判定 + 判定说明 +7. 每页含图框与标题栏(零件名 / 来源 / 视图 / 比例 / 投影法 / 单位 / 日期 / 页码) + +输出:完整 PDF + +--- + +### Step 9:生成孔位明细与特征数据 + +必做动作: + +1. CSV:一孔一行,字段顺序固定,UTF-8 带 BOM +2. JSON:含元信息、包围盒、定向变换、特征计数、全孔位明细、凸台明细、孔距分组 +3. 判定文字用长判定(可读完整句),CSV 另给短判定便于表格阅读 + +输出:CSV + JSON + +--- + +### Step 10:逐页渲染验收 + 自检后交付 + +必做动作: + +1. 把 PDF 每一页渲染成 PNG,逐页目视检查:文字是否重叠、尺寸线是否出界、标题栏是否被压、孔位气泡是否缺失 +2. 核对视图页上标注的总体尺寸 = 特征 JSON 中的包围盒尺寸 +3. 核对孔位编号在图面与明细表之间一一对应、无跳号无重号 +4. 按 §10 自检清单逐条检查 + +禁止: + +- ❌ 只看 PDF 文件大小或页数就说「已交付」 +- ❌ 未渲染就交付 + +输出:验收结论 + 三件套文件路径 + +--- + +## §3 字段详解 + +### 3.1 零件名 + +- 本质:贯穿文件名、标题栏、页眉的唯一标识 +- 格式:不超过 24 字的中文 / 字母 / 数字,不含特殊符号 +- 取值规则: + | 优先级 | 线索 | 做法 | + | --- | --- | --- | + | 1 | 用户指定 | 原样使用 | + | 2 | 文件名 | 去扩展名后使用 | + | 3 | 文件名不可用 | `(待用户确认)` | +- 示例:✅ `AI测试板` ✅ `电机支架_v2` ❌ `零件(最终版)!!`(含括号感叹号) +- 缺失处理:默认取文件名,并在交付说明中写「零件名取自文件名,如需修改请告知」 + +### 3.2 外形尺寸 + +- 本质:零件包围盒的三向最大尺寸,用于快速核对图纸是否与实物一致 +- 格式:`长 × 宽 × 厚 mm`,保留 2 位小数 +- 取值规则:取定向后包围盒的 X/Y/Z 延伸量,顺序固定为长 × 宽 × 厚 +- 示例:✅ `200.00 × 60.00 × 21.00 mm` ❌ `200×60×21`(缺单位) + +### 3.3 视图名与投影法 + +- 本质:说明每个图面是什么方向看的,避免图纸被误用 +- 格式:俯视图 / 主视图 / 左视图 / 底视图 / 后视图 / 右视图;投影法统一写「第一角(GB)」 +- 取值规则:第一角投影时,俯视图置于主视图下方,左视图置于主视图右方 +- 示例:✅ `俯视图 比例 1:1` ❌ `顶视图`(与左视图口径不一致,混用会导致视图对应关系错乱) + +### 3.4 比例 + +- 本质:决定图面尺寸与实物尺寸的关系,直接决定能否 1:1 打印 +- 格式:`1:1` 或 `1:<缩放比>`,缩放比保留 2 位小数 +- 取值规则: + | 场景 | 比例 | 做法 | + | --- | --- | --- | + | 视图可放入 A4 | `1:1` | 图面按模型 mm 落图 | + | 视图超 A4 | `1:1` 分块 | 分块页仍为 1:1 | + | 整件缩略页 | `1:<实际比>` | 必须同时写明「非 1:1」 | +- 示例:✅ `比例 1:1` ❌ 缩略页只写 `比例 1:1`(会把缩略图当 1:1 打印,尺寸全错) + +### 3.5 孔位编号 + +- 本质:图面气泡与明细表之间的唯一关联键 +- 格式:`H` + 连续数字,从 H1 起,不跳号不重号 +- 取值规则:先按归属视图优先级(俯视 → 主视 → 左视 → 其它)排序,同组内按高度降序、X 升序 +- 示例:✅ `H1` `H17` ❌ `孔1` `H-03`(与明细表字段不一致) +- 缺失处理:不得跳号;无法确定归属时统一排在最后并标注归属视图 + +### 3.6 孔类型 + +- 本质:区分孔的加工形态,影响装配与检验方式 +- 格式:通孔 / 盲孔 / 沉孔·台阶孔 / 内部腔体 +- 取值规则:按 §2 Step 5 的孔口判定结果,不按肉眼印象判断 +- 示例:✅ `通孔` ✅ `沉孔·台阶孔` ❌ `螺丝孔`(螺纹与否无法从几何确定,臆断会误导加工) + +### 3.7 直径 + +- 本质:孔径实测值,决定配套紧固件 +- 格式:保留 2 位小数,单位随图纸统一为 mm +- 取值规则:圆柱拟合半径 × 2;拟合残差超限的圆柱不得计入孔位 +- 示例:✅ `3.20` ❌ `M3`(螺纹标注需人工确认) + +### 3.8 深度 + +- 本质:孔的轴向长度,供选钻头 / 选螺钉长度 +- 格式:保留 2 位小数,单位 mm +- 取值规则:只计圆柱段长度;钻尖、沉头锥段不计入,需在说明中注明 +- 示例:✅ `2.00` ❌ `20.00`(把整板厚当成孔深) + +### 3.9 孔中心坐标 + +- 本质:孔位的绝对定位值,供加工编程或实物比对 +- 格式:X / Y / Z 三列,保留 2 位小数 +- 取值规则:取孔轴线与定向后坐标系的交点;坐标基准必须与图纸声明一致 +- 示例:✅ `84.75 / 14.75 / 4.00` ❌ `(未明确)`(有实测值时不得留空) + +### 3.10 归属视图 + +- 本质:说明该孔在哪个视图上看得见,驱动图面标注与追加出图 +- 格式:俯视图 / 主视图 / 左视图 / 底视图 / 后视图 / 右视图 / 需局部视图 +- 取值规则:按孔口朝向与标准三视图方向的夹角判定 +- 示例:✅ `底视图` ❌ `其他`(不可判定的写「需局部视图」并给出依据) + +### 3.11 可见性判定 + +- 本质:AI 对「这个孔在三视图里能不能看见」的判断结论,是本工作流的核心产出 +- 格式:短判定 + 长判定两套;短判定用于表格,长判定用于说明段 +- 取值规则: + | 短判定 | 含义 | 处理动作 | + | --- | --- | --- | + | `可见` | 该视图可见且无遮挡 | 图面画气泡 | + | `需底视图` 等 | 开口朝向未包含的视图 | 追加该视图页 | + | `被遮挡·需剖视` | 开口被自身结构挡住 | 明细表标注,建议补剖视 | + | `内部封闭腔·需剖视` | 孔口被材料包围 | 明细表标注,三视图均不画 | + | `斜向孔·需局部视图` | 轴线与三视图均不平行 | 标注并提示补局部视图 | +- 示例:✅ `需底视图` ❌ `可见`(底面朝下的孔说成可见,会导致实物加工时找不到孔) +- 缺失处理:证据不足时写「(待用户确认)」,不得直接判「可见」 + +### 3.12 孔距 + +- 本质:成组孔位的相对间距,机械装配的核心参数 +- 格式:`X <值> / Y <值> mm`;不均匀时给全部差值(用 `/` 分隔) +- 取值规则:同直径、同高度层、同视图内计算;不同直径不得混算 +- 示例:✅ `X 30.50 / Y 30.50 mm` ❌ `X 30 / Y 30`(精度不足以对刀) + +### 3.13 页码 + +- 本质:多页 PDF 的装配顺序索引,缺页会导致打印错序 +- 格式:`当前页/总页数` +- 取值规则:分页方案确定后再回填总数,不得先写后补 +- 示例:✅ `页码:2/7` ❌ `页码:2`(缺总数无法校验完整性) + +--- + +## §4 排版铁律(硬性要求,违反即不合格) + +| 编号 | 铁律 | 反例 | 正例 | +| --- | --- | --- | --- | +| 1 | 视图页必须 1:1,图纸 mm 等于模型 mm | 视图缩放到 80% 却不标注 | 按模型尺寸落图,比例写 1:1 | +| 2 | 缩略页必须显式写明非 1:1 及实际比例 | 缩略页只写「比例 1:1」 | `整件缩略 比例 1:0.96(非 1:1)` | +| 3 | 三视图必须齐全:俯视 / 主视 / 左视 | 只给俯视图 | 三个视图各占一页 | +| 4 | 投影方式统一第一角,视图排布按第一角 | 俯视图在上(第三角) | 俯视图在主视图下方 | +| 5 | 孔位在图面只标编号气泡,明细进表格 | 图面写满「H3 Ø3.2 深2 通」 | 图面只写 `H3`,详情在明细表 | +| 6 | 内部 / 背面 / 不可见孔位必须单列并说明 | 混在三视图里不标注 | 概览页 + 明细表双处列出处理方式 | +| 7 | 可见性判定必须逐孔给出,不得留空 | 判定列空白 | 每孔都有短判定 | +| 8 | 判定为「可见」必须有孔口朝向依据 | 凭图面看着像就判可见 | 按孔口朝向与视线夹角判定 | +| 9 | 坐标基准必须声明 | 只给数字不说基准 | 「包围盒最小角点为原点」 | +| 10 | 尺寸必须带单位且保留 2 位小数 | `200×60` | `200.00 × 60.00 × 21.00 mm` | +| 11 | 不同直径的孔不得混算孔距 | 把 Ø3 与 Ø5 算成同一阵列 | 按直径分组后各算各的 | +| 12 | 大件必须分块 1:1 并附整件缩略页 | 缩到一页了事 | 分块页 + 缩略页都出 | +| 13 | 分块接缝必须有对位标记 | 块与块之间无标记 | 接缝处画对位十字 | +| 14 | 表格一条占一行,字段顺序固定 | 多个孔挤一行 | 每孔一行,9 列固定顺序 | +| 15 | 标题栏字段齐全:零件名/来源/视图/比例/投影/单位/日期/页码 | 缺页码 | 八项齐全 | +| 16 | 页码总数必须与实际页数一致 | 写 2/7 实际 8 页 | 回填后核对 | +| 17 | 不使用 Emoji 装饰字段标题 | `✅ 孔位` | `孔位` | +| 18 | 不用 HTML 标签 | `` | 用 Markdown 表格或 PDF 表格 | +| 19 | 未明确项用括号标注 | 留空 | `(待用户确认)` | +| 20 | 不写人称代词「我 / 你」 | `我把孔位标好了` | `孔位已标注` | +| 21 | 交付前必须逐页渲染成图目视验收 | 只看 PDF 大小就交付 | 每页渲染 PNG 后检查 | +| 22 | 视图页尺寸线不得出图框、不得压标题栏 | 尺寸线伸出纸面 | 预留标注空间后再落图 | + +--- + +## §5 端到端转换流程(示例驱动) + +以一份板类零件文件为例(示例原文见 §9.1),端到端流程: + +``` +Step 1:接收并校验输入文件 + ↓ +Step 2:⭐ 复述图纸口径给用户确认(用户选 A 确认) + ↓ +Step 3:解析几何 + 自动摆正(厚度轴→Z、长轴→X、原点归零) + ↓ +Step 4:识别孔位与凸台(圆柱拟合 + 孔/凸台区分) + ↓ +Step 5:判定通孔 / 盲孔 + 孔口暴露度 + ↓ +Step 6:三视图可见性判定 + 内部孔位单列 + ↓ +Step 7:孔距阵列分析(按视图 + 高度 + 直径分组) + ↓ +Step 8:生成 1:1 图纸 PDF(概览 + 视图 + 明细表) + ↓ +Step 9:生成孔位明细 CSV + 特征 JSON + ↓ +Step 10:逐页渲染验收 + §10 自检清单全部 ✓ + ↓ +输出:<零件名>_打印图.pdf / <零件名>_孔位明细.csv / <零件名>_特征.json +``` + +--- + +## §6 字段填写默认值速查表 + +| 字段 | 缺省策略 | AI 必须做的 | +| --- | --- | --- | +| 零件名 | 取文件名(去扩展名) | 在交付说明中注明取自文件名 | +| 来源文件 | 取文件名 | 写入标题栏「来源」栏 | +| 外形尺寸 | 定向后包围盒 | 保留 2 位小数并带 mm | +| 投影法 | 第一角(GB) | 在标题栏标注,后续视图排布按此执行 | +| 比例 | 1:1 | 大件走分块,缩略页写实际比例 | +| 分块策略 | 分块 1:1 + 整件缩略页 | 接缝画对位标记 | +| 孔位编号 | H1 起连续 | 与明细表逐条对应 | +| 孔类型 | 按孔口判定结果 | 不按肉眼印象推断 | +| 直径 | 圆柱拟合值 | 保留 2 位小数,不推断螺纹 | +| 深度 | 只计圆柱段 | 说明钻尖段不计入 | +| 坐标基准 | 包围盒最小角点 | 在明细表页声明 | +| 归属视图 | 按孔口朝向判定 | 追加未包含方向的视图页 | +| 可见性判定 | 逐孔给出 | 证据不足写「(待用户确认)」 | +| 孔距 | 同直径同层内计算 | 不均匀时给全部差值 | +| 输出目录 | 由调用方传入 | 目录不存在时先创建 | + +--- + +## §7 措辞与语气规范 + +### 7.1 客观陈述 + +- ✅ `底面开口的孔位 14 个,已单独出底视图页` +- ❌ `有些孔挺奇怪的,藏在下面` + +### 7.2 不确定时用「未明确」「待用户确认」 + +- ✅ `螺纹与否:未明确,由用户确认` +- ✅ `单位:按原文件为英寸(待用户确认是否换算)` +- ❌ `应该是英寸吧` + +### 7.3 数据必须带单位 + +- ✅ `孔距 30.50 mm`、`深 2.00 mm`、`Ø3.20 mm` +- ❌ `孔距 30.5`、`Ø3.2` + +### 7.4 不用口语化连接词 + +- ❌ `然后呢` / `接着` / `那个` +- ✅ 用编号或正式连接 + +### 7.5 不写人称代词「我」「你」 + +- ✅ `已识别孔位 34 个` / `详见孔位明细表` +- ❌ `我帮你标好了` + +### 7.6 判定结论必须带依据 + +- ✅ `H21 开口朝向 −Z,三视图不可见,已追加底视图页` +- ❌ `H21 看不到` + +### 7.7 占位符统一格式 + +| 占位类型 | 格式 | 示例 | +| --- | --- | --- | +| 未明确项 | `(未明确,由用户确认)` | `单位:(未明确,由用户确认)` | +| 智能推测 | `(智能推测:依据xxx)` | `螺纹孔(智能推测:依据直径 3.20 与安装孔位置)` | +| 待补充项 | `(待用户补充)` | `材料:(待用户补充)` | +| 待指派人员 | `@待指派` | `@待指派` | +| 脱敏人名 | `@某A` / `@某B` | `@某B` | +| 跨电脑路径 | `由调用方传入` | `输出目录:<由调用方传入,默认 D:\Ai\生成skill\>` | + +--- + +## §8 边界 / 失败处理 + +| 情况 | 处理 | +| --- | --- | +| 输入文件不存在或不可读 | 停止,报告文件名与路径,不产出空文件 | +| 扩展名不支持 | 列出支持的扩展名并停止 | +| STEP 为纯曲面 / 线框,无实体可三角化 | 报告「无实体,无法出图」,提示改用 STL 或补实体 | +| STL 面数为 0 或解析失败 | 报告「几何解析失败」,不产出空 PDF | +| 网格非水密(存在开口边) | 照常出图,并在交付说明中提示棱边判定精度下降 | +| 未识别到任何孔位 | 照常出三视图与明细表页,明细表写「未检出孔位」,不编造 | +| 孔位拟合残差超限 / 半径过小 | 丢弃该特征,不计入孔位统计 | +| 同一位置出现多级直径(沉孔) | 合并为「沉孔·台阶孔」并给出两段直径与深度 | +| 视图超过 A4 可打印区 | 分块 1:1 + 整件缩略页,两种都出 | +| 分块后孔距标注放不下 | 先保证单页放下,减少孔距标注组数,孔距改由明细表与概览页承载 | +| 孔位过多导致表超出页面 | 表格续页,页眉重复表头,行不跨页拆分 | +| 页码总数与实际页数不符 | 重新回填后再交付,禁止先写后补 | +| 单位非毫米 | 按原样出图并标注单位来源,换算需用户确认 | +| 用户要求绑特定 AI / 工具链 | 拒绝并重申强约束第 8 条 | +| 用户要求绑特定电脑 / 路径 | 拒绝并要求参数化,路径由调用方传入 | + +--- + +## §9 完整示例 + +### §9.1 示例一:板类零件(俯视可见 + 底面不可见混合) + +#### §9.1.1 示例输入 + +> 3D 工程文件:示例零件A.STL +> 外形:200.00 × 60.00 × 21.00 mm +> 孔位:俯视方向可见 20 个,底面方向开口 14 个 + +#### §9.1.2 中间过程 + +| # | 步骤 | 关键结果 | +| --- | --- | --- | +| 1 | 校验输入 | 二进制 STL,6248 三角面,包围盒 200×60×21mm | +| 2 | ⭐ 口径确认 | 用户选 A:确认第一角、1:1、超 A4 走分块 | +| 3 | 自动摆正 | 厚度轴 Z→Z,长轴 Y→X,原点归零 | +| 4 | 识别孔位 | 34 个孔:Ø3.20×6、Ø3.00×4、Ø2.10×4、Ø1.80×4、Ø8.00×10、Ø5.50×4、Ø2.50×2 | +| 5 | 通盲判定 | 上部 Ø3.20/Ø3.00/Ø2.10 为通孔;下部 Ø8.00/Ø5.50 开口朝下,判盲孔 | +| 6 | 可见性判定 | 可见 20 个、需底视图 14 个、内部不可见 0 个 → 追加底视图页 | +| 7 | 孔距分析 | 7 组(按视图 + 高度 + 直径拆分),其中 Ø2.10 组为 20.00×20.00 mm 矩形阵列 | +| 8 | 出图 | 6 页:概览 + 俯视 + 主视 + 左视 + 底视 + 明细表 | +| 9 | 数据文件 | CSV 34 行,JSON 含定向记录与 7 组孔距 | +| 10 | 验收 | 逐页渲染 PNG 检查:无出界、无压栏、编号与表格一一对应 | + +#### §9.1.3 最终输出 + +``` +示例零件A_打印图.pdf (6 页,含底视图追加页) +示例零件A_孔位明细.csv (34 行,9 列) +示例零件A_特征.json +``` + +孔位明细片段: + +| 编号 | 类型 | 直径Ø | 深度 | X坐标 | Y坐标 | Z坐标 | 归属视图 | 可见性判定 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| H1 | 通孔 | 3.20 | 2.00 | 84.75 | 45.25 | 4.00 | 俯视图 | 可见 | +| H21 | 盲孔 | 8.00 | 3.00 | 84.75 | 14.75 | 1.50 | 底视图 | 需底视图 | + +--- + +### §9.2 示例二:大尺寸装配件(超 A4 + 内部孔位) + +#### §9.2.1 示例输入 + +> 3D 工程文件:示例零件B.step +> 外形:200.00 × 150.00 mm(超 A4 可打印区) +> 孔位:螺母内螺纹孔 22 个,孔口被材料包围,三视图均不可见 + +#### §9.2.2 中间过程 + +| # | 步骤 | 关键结果 | +| --- | --- | --- | +| 1 | 校验输入 | STEP(B-rep 实体),18 个实体,200×150×20mm | +| 2 | ⭐ 口径确认 | 用户选 A | +| 3 | 自动摆正 | 厚度轴 Y→Z,长轴 Z→X | +| 4 | 识别孔位 | 22 个孔(内螺纹孔按光孔报,不推断牙型) | +| 5 | 通盲判定 | 两端孔口暴露度均 < 3 → 内部腔体 | +| 6 | 可见性判定 | 可见 0、需底视图 6、内部不可见 16 → 追加底视图页,并在概览页提示补剖视 | +| 7 | 孔距分析 | 1 组 | +| 8 | 出图 | 10 页:概览 + 俯视(整件缩略页 + 2 块 1:1 分块页)+ 主视 + 左视 + 底视 + 明细表 | +| 9 | 数据文件 | CSV 22 行,JSON 记录定向与判定 | +| 10 | 验收 | 逐页渲染 PNG:分块接缝对位标记完整,缩略页比例标注正确 | + +#### §9.2.3 最终输出 + +``` +示例零件B_打印图.pdf (10 页,含整件缩略页 + 1:1 分块页) +示例零件B_孔位明细.csv +示例零件B_特征.json +``` + +判定说明片段: + +``` +· 三视图完全不可见的内部孔位(16 个):H3(内部封闭腔)…… —— 建议补剖视图 +``` + +--- + +### §9.3 示例三:板类零件(单页 1:1 直出) + +#### §9.3.1 示例输入 + +> 3D 工程文件:示例零件C.stl +> 外形:220.00 × 120.00 × 20.00 mm + +#### §9.3.2 中间过程 + +| # | 步骤 | 关键结果 | +| --- | --- | --- | +| 1 | 校验输入 | 二进制 STL,2940 三角面 | +| 2 | ⭐ 口径确认 | 用户选 A | +| 3 | 自动摆正 | 厚度轴 Y→Z,长轴 Z→X | +| 4 | 识别孔位 | 26 个孔,含 Ø65.00 大圆槽 | +| 5 | 通盲判定 | 通孔 18、盲孔 8(开口朝下) | +| 6 | 可见性判定 | 可见 18、需底视图 8 → 追加底视图页 | +| 7 | 孔距分析 | 6 组,其中 Ø1.80 组为 33.00×33.00 mm 阵列 | +| 8 | 出图 | 6 页,横版 A4,俯视图单页 1:1 放下(220×120) | +| 9 | 数据文件 | CSV 26 行,JSON 6 组孔距 | +| 10 | 验收 | 逐页渲染 PNG:孔距标注与总体尺寸不打架,无出界 | + +#### §9.3.3 最终输出 + +``` +示例零件C_打印图.pdf +示例零件C_孔位明细.csv +示例零件C_特征.json +``` + +--- + +## §10 自检清单(生成后必过一遍) + +- [ ] §0~§10 11 节齐全,顺序正确 +- [ ] 顶部元信息完整(适配对象 / 文档版本 / 生效日期 / 使用方式 / 强约束) +- [ ] §1.1 输入清单表完整(必填 / 选填 / 说明) +- [ ] §1.2 输入质量容忍度覆盖 STL 与 STEP 两类输入 +- [ ] §1.3 输出清单完整(格式 / 命名 / 路径 / 编码 / 行尾) +- [ ] §1.4 适用范围表含适用 / 部分适用 / 不适用三档 +- [ ] §2 Step 2 复述确认已加 ⭐ 且已完成 +- [ ] §2 Step 编号连续,无跳号 +- [ ] 每个 Step 含「必做动作 + 输出」 +- [ ] §3 字段详解每个字段独立小节,四要素齐全(本质 / 格式 / 取值 / 示例+反例) +- [ ] §3 字段数 ≥ 10,字段名与 §4 排版铁律、§6 速查表、CSV 列名三处一致 +- [ ] §4 排版铁律 ≥ 10 条,用 4 列表格(编号 + 铁律 + 反例 + 正例) +- [ ] §5 端到端流程含示例驱动且 Step 数与 §2 一致 +- [ ] §6 速查表 ≥ 6 行,3 列(字段 + 缺省策略 + AI 必须做的) +- [ ] §7 措辞规范 ≥ 5 条(含占位符统一格式表) +- [ ] §8 边界处理 ≥ 5 行(含文件缺失 / 无实体 / 识别为空 / 超 A4 / 页数不符) +- [ ] §9 完整示例 ≥ 2 个,每个含输入 + 中间过程 + 最终输出三段 +- [ ] §10 自检清单 ≥ 15 条,用 `- [ ]` 复选格式 +- [ ] 节号统一用 §0~§10,未用 `## 一、` / `## 1.` +- [ ] 章节之间用 `---` 分隔 +- [ ] 顶部元信息用 `>` 引用块 +- [ ] 强约束用编号列表 +- [ ] 字段详解含「本质 / 格式 / 取值 / 示例+反例」四要素 +- [ ] 不写 emoji 装饰字段标题 +- [ ] 不写 HTML 标签 +- [ ] 未明确项用括号标注(`(待用户确认)`) +- [ ] 智能推测必须标「(智能推测:依据xxx)」 +- [ ] 不出现真实人名 / 公司名 / 内部系统名 +- [ ] 不绑定特定 AI / 工具链 / 云服务 / 软件 +- [ ] 不绑定特定电脑 / 路径(路径由调用方传入) +- [ ] 每节标题加粗且主题 ≤ 14 字 +- [ ] 交付前已完成「逐页渲染成图目视验收」,验收记录可追溯 +- [ ] 交付回复中附三件套文件路径与页数、孔位数统计