Files
envi-code/SourceCode/Code2026/cad_mcp_aec/aec_mcp_valve_tools.cpp
T
company-desktop d6614a44d5 feat: 阀门插入——参数化阀门 + 定制阀门(两种都做成 MCP 工具)
一、参数化阀门(P3_CR* 19 个命令)
命令链:P3_CRZF -> initParamPipeValveJsonData("闸阀") -> PL_wValveEx("闸阀",…,false)
-> startForPipeValve(...) -> 里面 dlg.DoModal()(弹"参数化设计"对话框)-> start2Ptr。
产品自己是 LoadLibrary + GetProcAddress 调 pool3dcmd.arx 导出的 startForPipeValve,
所以我们也照做,但用新增的无界面版 startForPipeValveNoUI(不 DoModal)。

Pool3dCmd 里两处小改造(不改原命令行为):
1. 把 startForPipeValve 里"DoModal 之前"的准备逻辑抽成 PreparePipeValveDlg(..., bSilent),
   有界面/无界面共用;bSilent=true 时不弹 AfxMessageBox(MCP 里弹框会卡死调用方)。
2. 把"点确定"里填 m_datas/m_Bims 的那段抽成 CParaDesignDlg::BuildDatas(),
   无界面版在 start2Ptr 之前也调一次 —— VALVE::start2Ptr 里 getDatasByDlg 读的就是 m_datas,
   不填直接返回 NULL(这是第一版失败的真因)。

二、定制阀门(PL_CR* 20+ 命令)
不搬代码:照命令的做法查 sys/Aec3DMep.db -> aec_class(类别) -> aec_package(name like %DN<n>%)
-> select package 的 blob 落成临时 .equ -> AecDbEwEquipment::ReadFromFile。
注意 Aec_Class.Class 存的是多级路径(如 "管路附件\闸阀"),要用
class='<类别>' or class like '%\<类别>' 匹配末级,用等号查不到(第一版就栽在这)。

三、共同部分
SetInsert(pt, vtDir)(给 pipe 时位置投影到管轴、朝向取管轴)+ 图层 LAY_PIPE_OUTSIDE
+ 专业数据记 KEY_ASSOIC(所在管线) 与 PIPE_SYS(跟管线)。

工程改动:cad_mcp_aec 的 cmakelists 补链 sqliteserver(CUIISQLiteServer 要用,
CoreCommand 链了但不传递);源文件里先 #include "uiiado.h" 定义 TGADOSRV_API。

实测(R230 Debug,空图,DN100 给水管):
- 参数化闸阀 -> 31F
- 定制闸阀 -> 320,库里取到 Z45X(RVHX)弹性座封楔式闸阀DN100
工具总数 95 -> 97(本插件 67 -> 69),R230/Z2026 都编过。

限制:还没做插入时的"断管+法兰对接"(命令里的 InsertValAtInfPos 约 150 行),
阀门只是摆在管线上的位置与方向,管段不会自动断开。
2026-10-31 12:54:13 +08:00

436 lines
18 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// ============================================================================
// aec_mcp_valve_tools.cpp
// cad_mcp_aec 的阀门插入工具(工作计划第 6 项)
// * add_aec_valve 参数化阀门(P3_CR* 那 19 个命令:闸阀/球阀/截止阀…)
// * add_aec_custom_valve 定制阀门(PL_CR* 那 20+ 个命令:从设备库取预制件)
//
// 一、参数化阀门
// 命令链:P3_CRZF 等 → initParamPipeValveJsonData("闸阀") → PL_wValveEx("闸阀", …, false)
// → getEquiment(bByDB=false) → startForPipeValve(...) → 里面 dlg.DoModal()(弹"参数化设计"对话框)
// → dlg.m_pCurObj->start2Ptr(dlg) 生成 AecDbEwEquipment。
// 产品自己的 startForPipeValve 是 pool3dcmd.arx 用 __declspec(dllexport) 导出的,
// PipelineCmd 就是 LoadLibrary + GetProcAddress 调它。我们照做,但用的是本次新增的
// **无界面版 startForPipeValveNoUI**(不 DoModal,按 DN/PN + idx 直接建模),
// 否则 MCP 一调就卡在模态框上。
//
// 二、定制阀门
// 命令链:PL_CRZF → PL_wValveEx(VALVE_CRZF) → getEquiment(bByDB=true)
// → CEquipmentLibraryDlg::selectCustomValve(类别, DN) → 在 sys\Aec3DMep.db 里
// 按 aec_class.class=<类别> + aec_package.name like '%DN<dn>%' 找包,
// select package 的 blob 落成临时 .equ 文件 → new AecDbEwEquipment; ReadFromFile(tmp)。
// 这些 SQL 很浅,这里直接照做(不弹选型对话框)。
//
// 两者最后都是:SetInsert(pt, vtDir) + 图层 LAY_PIPE_OUTSIDE + 入库,
// 并在专业数据里记 KEY_ASSOIC(所在管线)与 PIPE_SYS(管网系统)。
// shortcut: 还没做插入时"断管 + 法兰对接"那套(命令里是 InsertValAtInfPos,150 行),
// 阀门现在只是摆在管线上的位置与方向,管段不会自动断开。
// ============================================================================
#include "StdAfx.h"
#include "KTCad.h"
#include "aec_mcp_common.h"
#include "mcp_plugin_api.h"
#include "AecDbEwEquipment.h"
#include "AecDbEwPipe.h"
#include "AecDbObjXDataMap.h"
#include "CoreTools.h"
#include "FilePath.h"
#include "KTSetting.h"
#include "uiiado.h" // 先定义 TGADOSRV_API(sqlite server 的头要用)
#include "UIISQLiteServer.h"
using namespace aec_mcp;
namespace
{
std::string HandleOfId(const AcDbObjectId& id)
{
if (id.isNull()) return std::string();
AcDbObject* pObj = NULL;
if (Acad::eOk != acdbOpenObject(pObj, id, AcDb::kForRead)) return std::string();
const std::string s = handleOf(pObj);
pObj->close();
return s;
}
// 插入点与方向:给了 pipe 就投影到管轴、方向取管轴;否则用 position/direction
bool ResolveInsert(AcDbEntity* pPipe, const nlohmann::json& a, AcGePoint3d& ptIns, AcGeVector3d& vtDir,
std::wstring& err)
{
if (!readPoint(a, "position", ptIns))
return false;
if (pPipe != NULL)
{
AcDbCurve* pCrv = AcDbCurve::cast(pPipe);
if (pCrv == NULL) { err = L"pipe 不是曲线"; return false; }
AcGePoint3d ptSta(0.0, 0.0, 0.0), ptEnd(0.0, 0.0, 0.0);
pCrv->getStartPoint(ptSta);
pCrv->getEndPoint(ptEnd);
AcGeVector3d vtAxis = ptEnd - ptSta;
const double dLen2 = vtAxis.dotProduct(vtAxis);
if (dLen2 > 1e-18)
{
double t = (ptIns - ptSta).dotProduct(vtAxis) / dLen2;
if (t < 0.0) t = 0.0;
if (t > 1.0) t = 1.0;
ptIns = ptSta + vtAxis * t; // 落到管轴上
vtDir = vtAxis;
vtDir.normalize();
return true;
}
}
AcGePoint3d ptDir(0.0, 0.0, 0.0);
if (readPoint(a, "direction", ptDir) && ptDir.asVector().length() > 1e-9)
{
vtDir = ptDir.asVector();
vtDir.normalize();
return true;
}
err = L"没给 pipe 时必须给 direction(阀门朝向)";
return false;
}
// 收尾:图层 + 管网系统 + 母体管线 + 入库
bool PlaceEquipment(AecDbEwEquipment* pEqu, AcDbEntity* pPipe, const AcGePoint3d& ptIns,
const AcGeVector3d& vtDir, const nlohmann::json& a, std::wstring& err)
{
if (pEqu == NULL) { err = L"生成阀门实体失败"; return false; }
pEqu->SetInsert(ptIns, vtDir);
if (!hasKey(a, "layer"))
pEqu->setLayer(KTSetting::InitLayer(LAY_PIPE_OUTSIDE));
if (pPipe != NULL)
{
pEqu->GetSpecialtyData()->SetAt(KEY_ASSOIC, pPipe->objectId());
// 管网系统跟着管线走
AecDbEwPipe* pP = AecDbEwPipe::cast(pPipe);
if (pP != NULL)
{
const AecDbObjXDataMap* pXPipe = pP->GetSpecialtyData(AcDb::kForRead);
CString sSys;
if (pXPipe != NULL && pXPipe->GetAt(PIPE_SYS, sSys) && !sSys.IsEmpty())
pEqu->GetSpecialtyData()->SetAt(PIPE_SYS, sSys);
}
}
if (hasKey(a, "system"))
pEqu->GetSpecialtyData()->SetAt(PIPE_SYS, wstrOr(a, "system", L"").c_str());
return true;
}
}
// ---------------------------------------------------------------------------
// add_aec_valve —— 参数化阀门(调 pool3dcmd.arx 的无界面导出)
// ---------------------------------------------------------------------------
class ToolAddValve : public mcp_Tool
{
public:
std::string private_name() const override { return "add_aec_valve"; }
std::string private_description() const override
{
return "在管线上插入**参数化阀门**(对应菜单 参数阀门 P3_CRZF 闸阀 / P3_CRQF 球阀 / P3_CRJZF 截止阀 / "
"P3_CRDF 蝶阀 / P3_CRZHF 止回阀 / P3_CRPQF 排气阀 / P3_CRDXZF 刀型闸阀 / P3_CRZSF 柱塞阀 / "
"P3_CRFQF 浮球阀 / P3_CRTJF 调节阀 / P3_CRSLKZF 水力控制阀 / P3_CRJYF 浆液阀 / P3_CRPNF 排泥阀 / "
"P3_CRDCF 电磁阀 / P3_GDBC 补偿器 / P3_CRSSJT 伸缩接头 / P3_CRCLJT 传力接头 / P3_CRXJJT 橡胶接头)。\n"
"实现:调用 pool3dcmd.arx 本次新增的无界面导出 startForPipeValveNoUI"
"(参数取自 <安装目录>/sys 里的 valvesize.json,与命令同一套),不弹对话框。\n"
"给 pipe(管线 handle)+ position(沿管的位置,会投影到管轴),阀门朝向自动取管轴;"
"dn_mm 公称直径、pn 压力等级、has_flange 是否带法兰、idx 同类型多个规格时选第几个。"
"图层缺省 LAY_PIPE_OUTSIDE。";
}
nlohmann::json private_input_schema() const override
{
return nlohmann::json::parse(R"({
"type": "object",
"properties": {
"kind": { "type": "string",
"description": "阀门类型名,与 valvesize.json 里的一致:闸阀/刀型闸阀/截止阀/球阀/止回阀/蝶阀/排气阀/柱塞阀/浮球阀/调节阀/水力控制阀/浆液阀/排泥阀/电磁阀/补偿器/伸缩接头/传力接头/橡胶接头" },
"pipe": { "type": "string", "description": "所在管线的 handle(给了就把 position 投影到管轴、朝向取管轴)" },
"position": { "type": "array", "items": { "type": "number" }, "description": "插入位置 [x,y,z](在管线附近即可)" },
"direction": { "type": "array", "items": { "type": "number" }, "description": "没给 pipe 时用它当阀门朝向" },
"dn_mm": { "type": "number", "description": "公称直径 DN(毫米)" },
"pn": { "type": "number", "description": "压力等级(MPa),缺省 1.0" },
"has_flange": { "type": "boolean", "description": "是否带法兰,缺省否" },
"idx": { "type": "integer", "description": "同类型有多个规格时选第几个(0 起),缺省 0" },
"system": { "type": "string", "description": "管网系统名(缺省跟管线)" },
"layer": { "type": "string", "description": "图层,缺省 LAY_PIPE_OUTSIDE" },
"color": { "type": "integer" }
},
"required": [ "kind", "position", "dn_mm" ]
})");
}
nlohmann::json Execute(const nlohmann::json& args) override
{
if (workingDb() == NULL) return errJson(kErrNoDocument, L"没有活动图纸");
DocLock lock;
if (!lock.isLocked()) return errJson(kErrInternal, L"拿不到图纸写锁(有别的命令在跑?)");
const std::wstring sKind = wstrOr(args, "kind", L"");
if (sKind.empty()) return errJson(kErrBadParam, L"需要 kind(阀门类型名)");
const double dDn = numOr(args, "dn_mm", 0.0);
if (dDn <= 0.0) return errJson(kErrBadParam, L"需要 dn_mm > 0");
// 所在管线
AcDbEntity* pPipe = NULL;
if (hasKey(args, "pipe"))
{
const std::wstring sPipe = wstrOr(args, "pipe", L"");
pPipe = openByHandle(acharToUtf8(sPipe.c_str()), AcDb::kForRead);
if (pPipe == NULL)
return errJson(kErrNotFound, L"按 handle 打不开管线:" + sPipe);
}
AcGePoint3d ptIns(0.0, 0.0, 0.0);
AcGeVector3d vtDir(0.0, 0.0, 1.0);
std::wstring err;
if (!ResolveInsert(pPipe, args, ptIns, vtDir, err))
{
if (pPipe != NULL) pPipe->close();
return errJson(kErrBadParam, err);
}
// 调 pool3dcmd.arx 导出的无界面版
typedef AcDbEntity*(_cdecl *FnStartValve)(LPCTSTR, LPCTSTR, const double&, const double&,
bool&, const int&, const AecDbObjXDataMap*);
AecDbEwEquipment* pEqu = NULL;
{
HINSTANCE hMod = ::LoadLibrary(FilePath::GetArxDir() + _T("\\pool3dcmd.arx"));
if (hMod == NULL)
{
if (pPipe != NULL) pPipe->close();
return errJson(kErrInternal, L"加载 pool3dcmd.arx 失败");
}
FnStartValve pfn = (FnStartValve)::GetProcAddress(hMod, "startForPipeValveNoUI");
if (pfn == NULL)
{
::FreeLibrary(hMod);
if (pPipe != NULL) pPipe->close();
return errJson(kErrInternal, L"pool3dcmd.arx 里没有 startForPipeValveNoUI(版本太旧?)");
}
bool bHasFlange = hasKey(args, "has_flange") ? (intOr(args, "has_flange", 0) != 0) : false;
CString sTitle;
sTitle.Format(_T("插入%s"), sKind.c_str());
AcDbEntity* pEnt = pfn(sKind.c_str(), (LPCTSTR)sTitle, dDn, numOr(args, "pn", 1.0),
bHasFlange, intOr(args, "idx", 0), NULL);
::FreeLibrary(hMod);
pEqu = AecDbEwEquipment::cast(pEnt);
if (pEqu == NULL)
{
if (pEnt != NULL) { pEnt->close(); delete pEnt; }
if (pPipe != NULL) pPipe->close();
return errJson(kErrBadParam, std::wstring(L"生成参数化阀门失败:类型名要说 valvesize.json 里的名字(") +
sKind + L");也可能是该类型没有对应 DN 的尺寸");
}
}
if (!PlaceEquipment(pEqu, pPipe, ptIns, vtDir, args, err))
{
delete pEqu;
if (pPipe != NULL) pPipe->close();
return errJson(kErrInternal, err);
}
if (hasKey(args, "color")) pEqu->setColorIndex((Adesk::UInt16)intOr(args, "color", 256));
if (hasKey(args, "layer"))
{
AcDbObjectId idLay = KTSetting::InitLayer(wstrOr(args, "layer", L"").c_str());
if (!idLay.isNull()) pEqu->setLayer(idLay);
}
AcDbObjectId idNew;
Acad::ErrorStatus es = addToSpace(pEqu, &idNew);
if (es != Acad::eOk)
{
delete pEqu;
if (pPipe != NULL) pPipe->close();
return errJson(kErrInternal, std::wstring(L"加入模型空间失败,err=") + std::to_wstring((int)es));
}
touchEntity(pEqu);
pEqu->close();
if (pPipe != NULL) pPipe->close();
nlohmann::json body;
body["ok"] = true;
body["type"] = "valve";
body["mode"] = "parametric";
body["kind"] = acharToUtf8(sKind.c_str());
body["position"] = { ptIns.x, ptIns.y, ptIns.z };
body["direction"] = { vtDir.x, vtDir.y, vtDir.z };
body["handle"] = HandleOfId(idNew);
return okJson(body);
}
};
EXPORT_MCP_TOOL(ToolAddValve, AddAecValveTool)
// ---------------------------------------------------------------------------
// add_aec_custom_valve —— 定制阀门(从 sys\Aec3DMep.db 取预制件)
// ---------------------------------------------------------------------------
class ToolAddCustomValve : public mcp_Tool
{
public:
std::string private_name() const override { return "add_aec_custom_valve"; }
std::string private_description() const override
{
return "在管线上插入**定制阀门**(对应菜单 定制阀门 PL_CRZF 闸阀 / PL_CJZF 截止阀 / PL_AQFM 球阀 / "
"PL_CRDF 碟阀 / PL_CZHF 止回阀 / PL_CRJF 角阀 / PL_CAQF 安全阀 等)。\n"
"实现:查 <安装目录>/sys/Aec3DMep.db 里的设备库(aec_class.class = 类别,"
"aec_package.name like '%DN<dn>%'),把 package blob 落成临时 .equ 文件,"
"再 AecDbEwEquipment::ReadFromFile 生成实体 —— 与命令 selectCustomValve 取的是同一份数据,"
"但不弹选型对话框。\n"
"给 category(类别名)+ dn_mm + pipe/position,朝向自动取管轴。图层缺省 LAY_PIPE_OUTSIDE。";
}
nlohmann::json private_input_schema() const override
{
return nlohmann::json::parse(R"({
"type": "object",
"properties": {
"category": { "type": "string", "description": "设备库里的类别名(aec_class.class),如 闸阀/截止阀/球阀/碟阀/止回阀" },
"dn_mm": { "type": "number", "description": "公称直径 DN(毫米),用来匹配库里 name 含 DN<dn> 的包" },
"pipe": { "type": "string", "description": "所在管线的 handle(给了就把 position 投影到管轴、朝向取管轴)" },
"position": { "type": "array", "items": { "type": "number" }, "description": "插入位置 [x,y,z]" },
"direction": { "type": "array", "items": { "type": "number" }, "description": "没给 pipe 时用它当朝向" },
"system": { "type": "string", "description": "管网系统名(缺省跟管线)" },
"layer": { "type": "string", "description": "图层,缺省 LAY_PIPE_OUTSIDE" },
"color": { "type": "integer" }
},
"required": [ "category", "position", "dn_mm" ]
})");
}
nlohmann::json Execute(const nlohmann::json& args) override
{
if (workingDb() == NULL) return errJson(kErrNoDocument, L"没有活动图纸");
DocLock lock;
if (!lock.isLocked()) return errJson(kErrInternal, L"拿不到图纸写锁(有别的命令在跑?)");
const std::wstring sCat = wstrOr(args, "category", L"");
if (sCat.empty()) return errJson(kErrBadParam, L"需要 category(设备库类别名,如 闸阀)");
const double dDn = numOr(args, "dn_mm", 0.0);
if (dDn <= 0.0) return errJson(kErrBadParam, L"需要 dn_mm > 0");
AcDbEntity* pPipe = NULL;
if (hasKey(args, "pipe"))
{
const std::wstring sPipe = wstrOr(args, "pipe", L"");
pPipe = openByHandle(acharToUtf8(sPipe.c_str()), AcDb::kForRead);
if (pPipe == NULL) return errJson(kErrNotFound, L"按 handle 打不开管线:" + sPipe);
}
AcGePoint3d ptIns(0.0, 0.0, 0.0);
AcGeVector3d vtDir(0.0, 0.0, 1.0);
std::wstring err;
if (!ResolveInsert(pPipe, args, ptIns, vtDir, err))
{
if (pPipe != NULL) pPipe->close();
return errJson(kErrBadParam, err);
}
// 查库:类别 -> aec_class.id -> aec_package(blob)
CUIISQLiteServer db;
CString sDb = FilePath::GetSysDir() + _T("\\Aec3DMep.db");
if (!db.InitADOServer((LPCTSTR)sDb))
{
if (pPipe != NULL) pPipe->close();
return errJson(kErrNotFound, L"打不开设备库:" + utf8ToWstr(acharToUtf8((LPCTSTR)sDb)));
}
CString sDnKey;
sDnKey.Format(_T("DN%d"), (int)(dDn + 0.5));
CString sSql;
// 库里 aec_class.class 存的是**多级路径**(如 "管路附件\闸阀"),
// 所以用 like '%<类别>' 匹配末级,而不是等号
sSql.Format(_T("select id,name from aec_package where idclass in")
_T(" (select id from aec_class where class='%s' or class like '%%\%s')")
_T(" and name like '%%%s%%'"),
(LPCTSTR)sCat.c_str(), (LPCTSTR)sCat.c_str(), (LPCTSTR)sDnKey);
std::map<CString, CString> hits;
if (db.GetSelData((LPCTSTR)sSql, hits) <= 0 || hits.empty())
{
if (pPipe != NULL) pPipe->close();
return errJson(kErrNotFound, std::wstring(L"设备库里没找到:类别=") + sCat + L",DN=" + (LPCTSTR)sDnKey);
}
const CString sId = hits.begin()->first;
const CString sName = hits.begin()->second;
// blob -> 临时 .equ 文件
CString sTmp;
sTmp.Format(_T("%s\\mcp_valve_%d.equ"), (LPCTSTR)FilePath::getSystemTemporaryFolder(), (int)GetTickCount());
CString sBlobSql;
sBlobSql.Format(_T("select package from aec_package where ID='%s'"), (LPCTSTR)sId);
if (db.GetSelBlob((LPCTSTR)sBlobSql, (LPCTSTR)sTmp) <= 0)
{
if (pPipe != NULL) pPipe->close();
return errJson(kErrInternal, L"从设备库导出 package 失败(id=" + utf8ToWstr(acharToUtf8((LPCTSTR)sId)) + L")");
}
AecDbEwEquipment* pEqu = new AecDbEwEquipment();
const BOOL bRead = pEqu->ReadFromFile((LPCTSTR)sTmp);
::DeleteFile((LPCTSTR)sTmp);
if (!bRead)
{
delete pEqu;
if (pPipe != NULL) pPipe->close();
return errJson(kErrInternal, L"ReadFromFile 失败(设备库里的 .equ 数据读不出来)");
}
pEqu->GetSpecialtyData()->SetAt(KEY_ID, (LPCTSTR)sId);
pEqu->GetSpecialtyData()->SetAt(KEY_NAME, (LPCTSTR)sName);
pEqu->SetDashLayer(KTSetting::InitLayer(LAY_FITN_DASH));
pEqu->SetCenterLayer(KTSetting::InitLayer(LAY_FITN_CENTER));
if (!PlaceEquipment(pEqu, pPipe, ptIns, vtDir, args, err))
{
delete pEqu;
if (pPipe != NULL) pPipe->close();
return errJson(kErrInternal, err);
}
if (hasKey(args, "color")) pEqu->setColorIndex((Adesk::UInt16)intOr(args, "color", 256));
if (hasKey(args, "layer"))
{
AcDbObjectId idLay = KTSetting::InitLayer(wstrOr(args, "layer", L"").c_str());
if (!idLay.isNull()) pEqu->setLayer(idLay);
}
AcDbObjectId idNew;
Acad::ErrorStatus es = addToSpace(pEqu, &idNew);
if (es != Acad::eOk)
{
delete pEqu;
if (pPipe != NULL) pPipe->close();
return errJson(kErrInternal, std::wstring(L"加入模型空间失败,err=") + std::to_wstring((int)es));
}
touchEntity(pEqu);
pEqu->close();
if (pPipe != NULL) pPipe->close();
nlohmann::json body;
body["ok"] = true;
body["type"] = "valve";
body["mode"] = "custom";
body["category"] = acharToUtf8((LPCTSTR)sCat.c_str());
body["dn"] = (int)(dDn + 0.5);
body["library_id"] = acharToUtf8((LPCTSTR)sId);
body["library_name"] = acharToUtf8((LPCTSTR)sName);
body["position"] = { ptIns.x, ptIns.y, ptIns.z };
body["direction"] = { vtDir.x, vtDir.y, vtDir.z };
body["handle"] = HandleOfId(idNew);
return okJson(body);
}
};
EXPORT_MCP_TOOL(ToolAddCustomValve, AddAecCustomValveTool)