// ============================================================================ // aec_mcp_pipehanger_tools.cpp // cad_mcp_aec 的"管道托架/支座"工具(工作计划第 6 项) // list_aec_pipe_hangers / add_aec_pipe_hanger / update_aec_pipe_hanger // 实体:AecDbPipeHanger(图集 03S42 那一套托架/支座) // // 5 个命令(PipeHanger/PipeHangerCmd.cpp 注册,实现在 PipeHanger/command.cpp): // PL_DGTJ 单管托架(mode 0) / PL_SGTJ 双管托架(1) / PL_LGTJ 立管托架(2) / // PL_PGZZ 平管支座(3) / PL_WGZZ 弯管支座(4) // 做法一样: // CGZDJDlg(ShowType(mode) 选分类、再选型号)-> GetHolderData(name, mpData, pms路径) // -> new AecDbPipeHanger -> AddVar(&mpData) -> LoadPmsFile(pms) -> Insert(pt, dRot) // 沿方向按 hf(层高,m)摆 nRows 个;弯管支座多一步 SetElbow(arc, OD) // // 数据在 <安装目录>/Support/Holder: // Holder.txt 型号清单,每行 "中文名称/.jpg" // .pms 建模脚本(EX / PCP / PCP6 … 指令) // .csv 参数表(首行 "序号,DN,保温类型,L1,L2,hf,A,L,t,Q…") // .jpg 预览图 // ============================================================================ #include "StdAfx.h" #include "KTCad.h" #include "aec_mcp_common.h" #include "mcp_plugin_api.h" #include "AecDbPipeHanger.h" #include "AecDbObjXDataMap.h" #include "CoreTools.h" #include "KTSetting.h" using namespace aec_mcp; namespace { const TCHAR* kPmsKey = _T("MCP_PMS_PATH"); // 自己记一份 pms 路径,update 要用 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; } bool ModeOfKind(const std::wstring& sKind, int& nMode) { if (sKind == L"single") { nMode = 0; return true; } // 单管托架 if (sKind == L"double") { nMode = 1; return true; } // 双管托架 if (sKind == L"vertical") { nMode = 2; return true; } // 立管托架 if (sKind == L"horizontal") { nMode = 3; return true; } // 平管支座 if (sKind == L"bend") { nMode = 4; return true; } // 弯管支座 return false; } bool HolderDir(CString& sDir) { CString sPs; if (!KTSetting::GetKTPsPath(sPs) || sPs.IsEmpty()) return false; sDir = sPs; if (sDir[sDir.GetLength() - 1] != _T('\\')) sDir += _T("\\"); sDir += _T("Support\\Holder\\"); return true; } // Holder.txt 每行 "中文名称/.jpg" bool ReadHolderList(int nMode, std::vector >& arItems, CString& sDir, std::wstring& err) { if (!HolderDir(sDir)) { err = L"取不到安装目录(KTSetting::GetKTPsPath 失败)"; return false; } CString sFile; sFile.Format(_T("%sHolder%d.txt"), (LPCTSTR)sDir, nMode); CStdioFile file; if (!file.Open(sFile, CFile::modeRead | CFile::typeText)) { err = L"打不开型号清单:" + std::wstring((LPCTSTR)sFile); return false; } CString sLn; while (file.ReadString(sLn)) { sLn.Trim(); if (sLn.IsEmpty()) continue; const int nPos = sLn.ReverseFind(_T('/')); if (nPos <= 0) continue; arItems.push_back(std::make_pair(sLn.Left(nPos), sLn.Mid(nPos + 1))); } file.Close(); if (arItems.empty()) { err = L"型号清单是空的:" + std::wstring((LPCTSTR)sFile); return false; } return true; } // "64.jpg" -> "64" CString StemOfJpg(const CString& sJpg) { CString s = sJpg; const int nDot = s.ReverseFind(_T('.')); if (nDot > 0) s = s.Left(nDot); return s; } CString SplitField(const CString& sLn, int& nStart, int nIdx, std::vector* pCols) { int nComma = sLn.Find(_T(','), nStart); if (nComma < 0) nComma = sLn.GetLength(); CString s = sLn.Mid(nStart, nComma - nStart); s.Trim(); nStart = nComma + 1; return s; } // 读 csv:列名 + 第 nRow 行(1 基,无表头)里"能转成数字"的列 bool ReadCsvRow(const CString& sCsvPath, int nRow, std::vector >& arVars, std::vector* pCols, int* pRowCount, std::wstring& err) { CStdioFile file; if (!file.Open(sCsvPath, CFile::modeRead | CFile::typeText)) { err = L"打不开参数表:" + std::wstring((LPCTSTR)sCsvPath); return false; } CString sLn; if (!file.ReadString(sLn)) { file.Close(); err = L"参数表是空的"; return false; } std::vector arCols; { int nStart = 0; while (nStart <= sLn.GetLength()) arCols.push_back(SplitField(sLn, nStart, 0, NULL)); } if (pCols != NULL) *pCols = arCols; int nCur = 0; bool bFound = false; while (file.ReadString(sLn)) { sLn.Trim(); if (sLn.IsEmpty()) continue; ++nCur; if (nCur == nRow) { int nStart = 0, nIdx = 0; while (nStart <= sLn.GetLength() && nIdx < (int)arCols.size()) { const CString sVal = SplitField(sLn, nStart, nIdx, NULL); if (!sVal.IsEmpty() && (_istdigit((unsigned short)sVal[0]) || sVal[0] == _T('-') || sVal[0] == _T('+'))) arVars.push_back(std::make_pair(arCols[nIdx], _ttof((LPCTSTR)sVal))); ++nIdx; } bFound = true; } } file.Close(); if (pRowCount != NULL) *pRowCount = nCur; if (!bFound) { err = L"参数表里没有第 " + std::to_wstring(nRow) + L" 行"; return false; } return !arVars.empty(); } void MergeVars(AecDbObjXDataMap* pMap, const nlohmann::json& vars) { if (pMap == NULL || !vars.is_object()) return; for (nlohmann::json::const_iterator it = vars.begin(); it != vars.end(); ++it) { if (!it.value().is_number()) continue; const std::wstring sKey = utf8ToWstr(it.key()); pMap->SetAt(sKey.c_str(), it.value().get()); } } nlohmann::json VarsToJson(AecDbObjXDataMap* pMap) { nlohmann::json o = nlohmann::json::object(); if (pMap == NULL) return o; AecDbObjXDataMap::It it = pMap->Begin(); CString sKey; AecXData xd; int nGuard = 0; while (pMap->GetNext(it, sKey, xd) && nGuard++ < 500) { if (xd.nVt == VT_R8) o[acharToUtf8((LPCTSTR)sKey)] = xd.dVal[0]; else if (xd.nVt == VT_I4) o[acharToUtf8((LPCTSTR)sKey)] = (double)xd.nVal; } return o; } } // --------------------------------------------------------------------------- // list_aec_pipe_hangers —— 列出型号 // --------------------------------------------------------------------------- class ToolListPipeHangers : public mcp_Tool { public: std::string private_name() const override { return "list_aec_pipe_hangers"; } std::string private_description() const override { return "列出管道托架/支座的图集型号(数据在 <安装目录>/Support/Holder)。\n" "kind: single 单管托架(PL_DGTJ) / double 双管托架(PL_SGTJ) / vertical 立管托架(PL_LGTJ) /\n" " horizontal 平管支座(PL_PGZZ) / bend 弯管支座(PL_WGZZ)。\n" "返回型号名、pms 文件名、csv 列名、数据行数,供 add_aec_pipe_hanger 用。"; } nlohmann::json private_input_schema() const override { return nlohmann::json::parse(R"({ "type": "object", "properties": { "kind": { "type": "string", "enum": [ "single", "double", "vertical", "horizontal", "bend" ], "description": "分类,缺省 single" } } })"); } nlohmann::json Execute(const nlohmann::json& args) override { if (workingDb() == NULL) return errJson(kErrNoDocument, L"没有活动图纸"); DocLock lock; if (!lock.isLocked()) return errJson(kErrInternal, L"拿不到图纸写锁(有别的命令在跑?)"); int nMode = 0; if (!ModeOfKind(wstrOr(args, "kind", L"single"), nMode)) return errJson(kErrBadParam, L"kind 只支持 single / double / vertical / horizontal / bend"); std::vector > arItems; CString sDir; std::wstring err; if (!ReadHolderList(nMode, arItems, sDir, err)) return errJson(kErrNotFound, err); nlohmann::json arOut = nlohmann::json::array(); for (size_t i = 0; i < arItems.size(); ++i) { const CString sStem = StemOfJpg(arItems[i].second); nlohmann::json o; o["index"] = (int)i; o["name"] = acharToUtf8((LPCTSTR)arItems[i].first); o["pms"] = acharToUtf8((LPCTSTR)(sStem + _T(".pms"))); CString sCsv; sCsv.Format(_T("%s%s.csv"), (LPCTSTR)sDir, (LPCTSTR)sStem); std::vector > arVars; std::vector arCols; int nRows = 0; std::wstring sErr2; if (ReadCsvRow(sCsv, 1, arVars, &arCols, &nRows, sErr2)) { nlohmann::json arC = nlohmann::json::array(); for (size_t k = 0; k < arCols.size(); ++k) arC.push_back(acharToUtf8((LPCTSTR)arCols[k])); o["columns"] = arC; o["rows"] = nRows; nlohmann::json arFirst = nlohmann::json::object(); for (size_t k = 0; k < arVars.size(); ++k) arFirst[acharToUtf8((LPCTSTR)arVars[k].first)] = arVars[k].second; o["first_row"] = arFirst; } else { o["columns_error"] = acharToUtf8(sErr2.c_str()); } arOut.push_back(o); } nlohmann::json body; body["ok"] = true; body["kind"] = acharToUtf8(wstrOr(args, "kind", L"single").c_str()); body["dir"] = acharToUtf8((LPCTSTR)sDir); body["count"] = (int)arOut.size(); body["items"] = arOut; return okJson(body); } }; EXPORT_MCP_TOOL(ToolListPipeHangers, ListAecPipeHangersTool) // --------------------------------------------------------------------------- // add_aec_pipe_hanger —— 插入托架/支座 // --------------------------------------------------------------------------- class ToolAddPipeHanger : public mcp_Tool { public: std::string private_name() const override { return "add_aec_pipe_hanger"; } std::string private_description() const override { return "插入管道托架/支座(AecDbPipeHanger,图集 03S42):用 list_aec_pipe_hangers 拿型号,\n" "再给 kind + index(或 pms 文件名)+ 插入点 + 旋转角;参数默认取该型号 csv 的第 csv_row 行,\n" "也可用 vars 覆盖单个参数(如 {\\\"L1\\\":600})。rows/row_spacing 可以沿方向摆一串(命令里也是这么做的)。\n" "弯管支座(kind=bend)还要给 elbow(圆弧 handle)和 elbow_od。图层 LAY_SUPPORT。"; } nlohmann::json private_input_schema() const override { return nlohmann::json::parse(R"({ "type": "object", "properties": { "kind": { "type": "string", "enum": [ "single", "double", "vertical", "horizontal", "bend" ], "description": "分类,缺省 single" }, "index": { "type": "integer", "description": "型号在清单里的序号(list_aec_pipe_hangers 返回的 index)" }, "name": { "type": "string", "description": "或者给型号名称(清单里的 name)" }, "pms": { "type": "string", "description": "或者直接给 pms 文件名(如 64.pms)" }, "csv_row": { "type": "integer", "description": "参数取 csv 的第几行(1 基,缺省 1)" }, "vars": { "type": "object", "description": "覆盖参数,如 {\"L1\":600,\"t\":5}" }, "position": { "type": "array", "items": { "type": "number" }, "description": "插入点 [x,y,z]" }, "rotation_deg": { "type": "number", "description": "旋转角(度),缺省 0" }, "rows": { "type": "integer", "description": "沿方向摆几个(命令里由长度/hf 算),缺省 1" }, "row_spacing": { "type": "number", "description": "每个之间的间距(图纸单位),缺省取 hf*1000" }, "direction": { "type": "array", "items": { "type": "number" }, "description": "摆列方向 [x,y,z],缺省 +X" }, "elbow": { "type": "string", "description": "弯管支座用:弯头的圆弧 handle" }, "elbow_od": { "type": "number", "description": "弯管支座用:管外径" }, "layer": { "type": "string", "description": "图层,缺省 LAY_SUPPORT" }, "color": { "type": "integer" } }, "required": [ "position" ] })"); } nlohmann::json Execute(const nlohmann::json& args) override { if (workingDb() == NULL) return errJson(kErrNoDocument, L"没有活动图纸"); DocLock lock; if (!lock.isLocked()) return errJson(kErrInternal, L"拿不到图纸写锁(有别的命令在跑?)"); AcGePoint3d ptIns(0.0, 0.0, 0.0); if (!readPoint(args, "position", ptIns)) return errJson(kErrBadParam, L"需要 position(插入点)"); int nMode = 0; if (!ModeOfKind(wstrOr(args, "kind", L"single"), nMode)) return errJson(kErrBadParam, L"kind 只支持 single / double / vertical / horizontal / bend"); std::vector > arItems; CString sDir; std::wstring err; if (!ReadHolderList(nMode, arItems, sDir, err)) return errJson(kErrNotFound, err); // 定位型号:index > name > pms CString sStem; if (hasKey(args, "index")) { const int n = intOr(args, "index", -1); if (n < 0 || n >= (int)arItems.size()) return errJson(kErrBadParam, L"index 超范围(0~" + std::to_wstring(arItems.size() - 1) + L")"); sStem = StemOfJpg(arItems[n].second); } else if (hasKey(args, "name")) { const std::wstring sName = wstrOr(args, "name", L""); for (size_t i = 0; i < arItems.size(); ++i) { if (std::wstring((LPCTSTR)arItems[i].first) == sName) { sStem = StemOfJpg(arItems[i].second); break; } } if (sStem.IsEmpty()) return errJson(kErrNotFound, L"清单里没有这个型号名:" + sName); } else if (hasKey(args, "pms")) { CString sPms = CString(wstrOr(args, "pms", L"").c_str()); const int nDot = sPms.ReverseFind(_T('.')); sStem = (nDot > 0) ? sPms.Left(nDot) : sPms; } else { return errJson(kErrBadParam, L"要给 index / name / pms 之一来指定型号"); } CString sPmsPath; sPmsPath.Format(_T("%s%s.pms"), (LPCTSTR)sDir, (LPCTSTR)sStem); if (GetFileAttributes(sPmsPath) == INVALID_FILE_ATTRIBUTES) return errJson(kErrNotFound, L"pms 文件不存在:" + utf8ToWstr(acharToUtf8((LPCTSTR)sPmsPath))); // 参数:csv 那行 + vars 覆盖 CString sCsvPath; sCsvPath.Format(_T("%s%s.csv"), (LPCTSTR)sDir, (LPCTSTR)sStem); std::vector > arVars; std::wstring sErr2; ReadCsvRow(sCsvPath, intOr(args, "csv_row", 1), arVars, NULL, NULL, sErr2); AecDbObjXDataMap mpData; for (size_t i = 0; i < arVars.size(); ++i) mpData.SetAt((LPCTSTR)arVars[i].first, arVars[i].second); if (hasKey(args, "vars")) MergeVars(&mpData, args["vars"]); // 摆列参数(命令里:hf 是层高 m,沿方向摆 nRows 个) double dhf = 1.5; mpData.GetAt(_T("hf"), dhf); double dSpacing = numOr(args, "row_spacing", 0.0); if (dSpacing <= 0.0) dSpacing = dhf * 1000.0; int nRows = intOr(args, "rows", 1); if (nRows < 1) nRows = 1; AcGePoint3d ptDir(0.0, 0.0, 0.0); AcGeVector3d vtDir = AcGeVector3d::kXAxis; if (readPoint(args, "direction", ptDir) && ptDir.asVector().length() > 1e-9) vtDir = ptDir.asVector(); vtDir.normalize(); const double dRot = CoreTools::A2R(numOr(args, "rotation_deg", 0.0)); // 弯管支座:需要圆弧 + 外径 AcDbArc* pElbow = NULL; if (nMode == 4) { if (!hasKey(args, "elbow")) return errJson(kErrBadParam, L"弯管支座需要 elbow(圆弧 handle)"); const std::wstring sElbow = wstrOr(args, "elbow", L""); AcDbEntity* pEnt = openByHandle(acharToUtf8(sElbow.c_str()), AcDb::kForRead); pElbow = (pEnt != NULL) ? AcDbArc::cast(pEnt) : NULL; if (pElbow == NULL) { if (pEnt != NULL) pEnt->close(); return errJson(kErrWrongType, L"elbow 必须是圆弧(ARC):" + sElbow); } } std::wstring sLay = hasKey(args, "layer") ? wstrOr(args, "layer", L"") : L""; if (sLay.empty()) sLay = L"LAY_SUPPORT"; AcDbObjectId idLay = KTSetting::InitLayer(sLay.c_str()); nlohmann::json arHandles = nlohmann::json::array(); AcGePoint3d ptCur = ptIns; for (int i = 0; i < nRows; ++i) { AecDbPipeHanger* pHg = new AecDbPipeHanger(); if (!idLay.isNull()) pHg->setLayer(idLay); if (hasKey(args, "color")) pHg->setColorIndex((Adesk::UInt16)intOr(args, "color", 256)); pHg->AddVar(&mpData); pHg->LoadPmsFile(sPmsPath); if (pElbow != NULL) pHg->SetElbow(pElbow, numOr(args, "elbow_od", 0.0)); pHg->GetSpecialtyData()->SetAt(kPmsKey, (LPCTSTR)sPmsPath); if (!pHg->Insert(ptCur, dRot)) { delete pHg; if (pElbow != NULL) pElbow->close(); return errJson(kErrInternal, L"Insert 失败(pms 脚本或参数不对)"); } AcDbObjectId idNew; if (addToSpace(pHg, &idNew) != Acad::eOk) { delete pHg; continue; } touchEntity(pHg); pHg->close(); arHandles.push_back(HandleOfId(idNew)); ptCur += vtDir * dSpacing; } if (pElbow != NULL) pElbow->close(); nlohmann::json body; body["ok"] = !arHandles.empty(); body["type"] = "pipe_hanger"; body["pms"] = acharToUtf8((LPCTSTR)sPmsPath); body["count"] = (int)arHandles.size(); body["handles"] = arHandles; if (!arHandles.empty()) body["handle"] = arHandles[0]; body["vars"] = VarsToJson(&mpData); return okJson(body); } }; EXPORT_MCP_TOOL(ToolAddPipeHanger, AddAecPipeHangerTool) // --------------------------------------------------------------------------- // update_aec_pipe_hanger —— 改参数(重建几何) // --------------------------------------------------------------------------- class ToolUpdatePipeHanger : public mcp_Tool { public: std::string private_name() const override { return "update_aec_pipe_hanger"; } std::string private_description() const override { return "改管道托架/支座(AecDbPipeHanger)的参数:给 vars 覆盖(如 {\"L1\":600})," "或给 rotation_deg 改旋转角。实体是按 pms 脚本现场生成的,改参数等于按新参数重建几何" "(位置沿用原来的)。pms 路径是创建时记下的,换型号请删了重建。"; } nlohmann::json private_input_schema() const override { return nlohmann::json::parse(R"({ "type": "object", "properties": { "handle": { "type": "string", "description": "托架/支座实体 handle" }, "vars": { "type": "object", "description": "要覆盖的参数" }, "rotation_deg": { "type": "number", "description": "新的旋转角(度)" }, "color": { "type": "integer" } }, "required": [ "handle" ] })"); } nlohmann::json Execute(const nlohmann::json& args) override { if (workingDb() == NULL) return errJson(kErrNoDocument, L"没有活动图纸"); DocLock lock; if (!lock.isLocked()) return errJson(kErrInternal, L"拿不到图纸写锁(有别的命令在跑?)"); if (!hasKey(args, "handle")) return errJson(kErrBadParam, L"缺少 handle"); const std::string sHandle = args["handle"].get(); AcDbEntity* pEnt = openByHandle(sHandle, AcDb::kForWrite); if (pEnt == NULL) return errJson(kErrNotFound, L"按 handle 打不开实体:" + utf8ToWstr(sHandle)); AecDbPipeHanger* pHg = AecDbPipeHanger::cast(pEnt); if (pHg == NULL) { const std::string sCls = classNameOf(pEnt); pEnt->close(); return errJson(kErrWrongType, L"实体 " + utf8ToWstr(sCls) + L" 不是管道托架/支座(AecDbPipeHanger)"); } CString sPms; if (!pHg->GetSpecialtyData()->GetAt(kPmsKey, sPms) || sPms.IsEmpty()) { pEnt->close(); return errJson(kErrBadParam, L"这个实体不是用 add_aec_pipe_hanger 建的(没有记 pms 路径),改不了"); } // 现有参数 + 覆盖 AecDbObjXDataMap xData; pHg->GetVar(xData); if (hasKey(args, "vars")) MergeVars(&xData, args["vars"]); const AcGePoint3d ptPos = pHg->position(); const double dRot = hasKey(args, "rotation_deg") ? CoreTools::A2R(numOr(args, "rotation_deg", 0.0)) : pHg->rotation(); pHg->AddVar(&xData); pHg->LoadPmsFile((LPCTSTR)sPms); if (!pHg->Insert(ptPos, dRot)) { pEnt->close(); return errJson(kErrInternal, L"按新参数重建失败(pms 脚本或参数不对)"); } if (hasKey(args, "color")) pHg->setColorIndex((Adesk::UInt16)intOr(args, "color", 256)); touchEntity(pHg); nlohmann::json body; body["ok"] = true; body["type"] = "pipe_hanger"; body["handle"] = sHandle; body["pms"] = acharToUtf8((LPCTSTR)sPms); body["position"] = { ptPos.x, ptPos.y, ptPos.z }; body["vars"] = VarsToJson(&xData); pEnt->close(); return okJson(body); } }; EXPORT_MCP_TOOL(ToolUpdatePipeHanger, UpdateAecPipeHangerTool)