Files
envi-code/SourceCode/Code2026/cad_mcp_aec/aec_mcp_shape_tools.cpp
T
company-desktop 693d3ed934 feat: add_aec_shape 覆盖 PL_DTYG 对话框上的全部几何体
之前只做了 7 种基本体 + 放样体;这次补齐剩下的 5 种,对话框(DTYGDlg)上
能点出来的造型现在都能用 MCP 建:

- extrude 拉伸体:profile 落在过 position、法向 direction 的平面上,沿该法向拉 height
  (命令 CreateExtrude:路径线从轮廓包围盒中心出发)
- revolve 旋转体:profile=[[r,h],...](r=到轴距离、h=沿轴坐标)+ axis_start/axis_end
  + angle(度,缺省 360),内部 CreateRevolve2
- sweep 扫掠体:profile + path=[[u,v],...],u 沿轮廓平面 X、v 沿 direction(前进方向),
  起点即轮廓中心;内部 CreateSweep(region, polyline)
- cut 切割:profile + depth(缺省取母体最大尺寸),往 -direction 拉刀,永远按减料
- weir 异形堰:base_curve 给圆/圆弧 handle(命令也只能选 CIRCLE/ARC)+ weir_width/
  thickness/height1/height2/type/start_distance,移植 makeRegion4Arc + CreateLoft

关键坑(扫掠体一开始怎么都失败就是因为它):
AcDbPolyline 的 2D 坐标是 OCS 坐标,直接 setNormal(vtZ) 摆放是错的——法向不是 Z 时
OCS 的 X/Y 轴会跟着转(AcGe arbitrary axis 规则),给的 [x,y] 就不再是那个位置。
改成用 AcGeMatrix3d::setToAlignCoordSys 把 XY 平面上的曲线搬到 WCS(PlaceOnFrame),
轮廓/路径/放样截面统一走这条路。

其他细节:
- 切割(kCut)强制减料,与命令 bSub=true 一致;刀长缺省用母体包围盒最大边(getMaxLength)
- 异形堰命令里的循环条件 while (UPEQUAL_ZERO(dist - m_dL - dSp)) 像是把"不等于"写成
  "约等于",实际只生成一段;工具按"生成一段"实现,排一圈请自己循环换 start_distance
- update_aec_shape 只对 7 种基本体生效(尺寸存在 AcDbX3dSolid 里),曲线类明确拒绝改造
- 三点定弧不再依赖 KTCADUtilityEx::FormatArc,直接用 AcGeCircArc3d 推 AcDbArc

实测(空图,R230 Debug):摆了 13 个异形构筑物,13 种几何体各建一个
(box/cylinder/cone/pyramid/sphere/drum/wedge/loft/extrude/revolve/sweep/cut/weir,
其中 cut 是在 box 上切掉一半),14 次 add_aec_shape 全部 ok。
2026-10-30 21:38:21 +08:00

1402 lines
51 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_shape_tools.cpp
// cad_mcp_aec 的"造型"工具:对应菜单命令
// * PL_DTYG —— 向墙/板/梁/柱/堰/异形构筑物(AecDbBDPipeBase 派生)里加几何体
// * PL_YXGZ —— 新建一个空的异形构筑物(AecDbMultiPartEntity)再加几何体
//
// 命令的做法(Pool3dCmd/DTYGDlg.cpp):
// 每一种造型都是 AcDbX3dSolid,用 Create(prim, 中心, vtZ, n, 尺寸...) 造出来,
// 然后包一层 AecDbX3dPart(DTYG_TYPE 记中文造型名、BIM 数据记名称/颜色/统计类型),
// 再 host->AddX3dPart(pPart, kBoolUnite / kBoolSubtract) —— 并/差就是这么来的。
// 修改时命令是"重建 solid":pPart->RemoveAt(0) + AddX3dSolid(新的)。
// 本工具改成整块部件重建(host->RemoveX3dPart(guid) + AddX3dPart(新 part, mode)),
// 这样连"并/差"模式、名称、位置都能一起改。
//
// 尺寸都用**图纸单位**,与命令的对话框一致。
// shortcut: 只支持能直接用 AcDbX3dSolid::Create 造出来的基本体
// (立方体/圆柱/圆台/四方台/球体/球台/楔形体);拉伸体、旋转体、放样体、扫掠体、
// 环体、切割、异形堰要选曲线/面域,需要的话再单独加。
// ============================================================================
#include "StdAfx.h"
#include "KTCad.h"
#include "aec_mcp_common.h"
#include "mcp_plugin_api.h"
#include "AecDbBDPipeBase.h"
#include "AecDbMultiPartEntity.h"
#include "AecDbX3dPart.h"
#include "AecDbObjXDataMap.h"
#include "AcDbX3dSolid.h"
#include "CoreTools.h"
#include "KTSetting.h"
using namespace aec_mcp;
namespace
{
// id -> 句柄字符串(刚入库的对象用)
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;
}
// 方向:give direction 就用,否则 Z
AcGeVector3d DirOf(const nlohmann::json& a)
{
AcGePoint3d ptDir;
AcGeVector3d vt = AcGeVector3d::kZAxis;
if (readPoint(a, "direction", ptDir))
{
AcGeVector3d vtGiven = ptDir.asVector();
if (vtGiven.length() > 1e-9)
vt = vtGiven;
}
vt.normalize();
return vt;
}
// 与 vtZ 垂直的一组轴(命令用当前 UCS 的 X/Y;工具里按 vtZ 推,避免依赖 UCS)
void AxesOf(const AcGeVector3d& vtZ, AcGeVector3d& vtX, AcGeVector3d& vtY)
{
vtX = AcGeVector3d::kZAxis.crossProduct(vtZ);
if (vtX.length() < 1e-9)
vtX = AcGeVector3d::kXAxis;
vtX.normalize();
vtY = vtZ.crossProduct(vtX).normalize();
}
// ---------------------------------------------------------------- 造型表
// 造型的建体方式:基本体直接 Create,其余各自一套(见 BuildShapeSolid)
enum ShapeKind
{
kPrim = 0, // AcDbX3dSolid::Create(prim, ...)
kLoft,
kExtrude,
kRevolve,
kSweep,
kCut,
kWeir,
};
struct ShapeSpec
{
const wchar_t* pszKey; // 工具参数 shape 的取值
const wchar_t* pszName; // DTYG_TYPE / 部件名(与命令 getName() 一致)
AcDbX3dSolid::Primitive ePrim;
int nKind; // ShapeKind
int nParams;
const char* aszParam[6]; // 参数名,顺序与 Create 一致
};
// 参数顺序全部照抄命令里各 makeSolid() 的 Create(...),顺序错了尺寸就串位。
const ShapeSpec g_shapes[] =
{
{ L"box", L"立方体", AcDbX3dSolid::kBox, kPrim, 3, { "length", "width", "height" } },
{ L"cylinder", L"圆柱", AcDbX3dSolid::kCylinder, kPrim, 2, { "radius", "height" } },
{ L"cone", L"圆台", AcDbX3dSolid::kCone, kPrim, 3, { "radius_bottom", "radius_top", "height" } },
{ L"pyramid", L"四方台", AcDbX3dSolid::kPyramid, kPrim, 6, { "top_length", "top_width", "bottom_length", "bottom_width", "height", "x_offset" } },
{ L"sphere", L"球体", AcDbX3dSolid::kSpere, kPrim, 1, { "radius" } },
{ L"drum", L"球台", AcDbX3dSolid::kDrum, kPrim, 5, { "radius", "len1", "len2", "start_angle", "end_angle" } },
{ L"wedge", L"楔形体", AcDbX3dSolid::kWedge, kPrim, 3, { "a", "b", "thickness" } },
// 下面这几种没有固定尺寸参数,靠 profile / sections / axis / path 描述
{ L"loft", L"放样体", AcDbX3dSolid::kLoft, kLoft, 0, { } },
{ L"extrude", L"拉伸体", AcDbX3dSolid::kExtrude, kExtrude, 0, { } },
{ L"revolve", L"旋转体", AcDbX3dSolid::kRevolve, kRevolve, 0, { } },
{ L"sweep", L"扫掠体", AcDbX3dSolid::kSweep, kSweep, 0, { } },
{ L"cut", L"切割", AcDbX3dSolid::kSliceSolid, kCut, 0, { } },
{ L"weir", L"异形堰", AcDbX3dSolid::kRevolve2, kWeir, 0, { } },
};
const ShapeSpec* FindShape(const std::wstring& sKey)
{
for (int i = 0; i < _countof(g_shapes); ++i)
{
if (sKey == g_shapes[i].pszKey)
return &g_shapes[i];
}
return NULL;
}
const ShapeSpec* FindShapeByName(const CString& sName)
{
for (int i = 0; i < _countof(g_shapes); ++i)
{
if (sName == g_shapes[i].pszName)
return &g_shapes[i];
}
return NULL;
}
// 造型名字 -> 参数数组(缺省全 0)
void InitParams(double* p)
{
for (int i = 0; i < 6; ++i)
p[i] = 0.0;
}
// Create() 用的中心点偏移:命令里 ptOrg 是"插入点",各造型把自己挪到中心
double CenterOffset(const ShapeSpec& sp, const double* p)
{
switch (sp.ePrim)
{
case AcDbX3dSolid::kBox:
case AcDbX3dSolid::kCylinder:
case AcDbX3dSolid::kCone: return 0.5 * p[sp.nParams - 1]; // 最后一个都是高
case AcDbX3dSolid::kSpere: return p[0];
case AcDbX3dSolid::kDrum: return p[2]; // len2
default: return 0.0; // pyramid / wedge 以插入点为原点
}
}
AcDbX3dSolid* BuildSolid(const ShapeSpec& sp, const double* p, const AcGePoint3d& ptIns,
const AcGeVector3d& vtZ, std::wstring& err)
{
const AcGePoint3d ptCen = ptIns + vtZ * CenterOffset(sp, p);
AcDbX3dSolid* pSolid = new AcDbX3dSolid();
bool bOk = false;
switch (sp.nParams)
{
case 1: bOk = pSolid->Create(sp.ePrim, ptCen, vtZ, 1, p[0]); break;
case 2: bOk = pSolid->Create(sp.ePrim, ptCen, vtZ, 2, p[0], p[1]); break;
case 3: bOk = pSolid->Create(sp.ePrim, ptCen, vtZ, 3, p[0], p[1], p[2]); break;
case 5: bOk = pSolid->Create(sp.ePrim, ptCen, vtZ, 5, p[0], p[1], p[2], p[3], p[4]); break;
case 6: bOk = pSolid->Create(sp.ePrim, ptCen, vtZ, 6, p[0], p[1], p[2], p[3], p[4], p[5]); break;
default: break;
}
if (!bOk)
{
delete pSolid; pSolid = NULL;
err = std::wstring(L"造型几何创建失败:") + sp.pszName + L"(检查尺寸是否都 > 0)";
return NULL;
}
return pSolid;
}
// 把在 XY 平面上造好的 2D 曲线搬到"原点 ptOrg + 三轴 x/y/z"的坐标系上。
// 之前直接给 AcDbPolyline 设 normal 是错的:normal 不是 Z 时 OCS 轴会转,
// 二维坐标就不再是你给的那两个数了(扫掠体就是这么失败的)。
void PlaceOnFrame(AcDbEntity* pEnt, const AcGePoint3d& ptOrg,
const AcGeVector3d& vtX, const AcGeVector3d& vtY, const AcGeVector3d& vtZ)
{
if (pEnt == NULL) return;
AcGeMatrix3d mat;
mat.setToAlignCoordSys(AcGePoint3d::kOrigin, AcGeVector3d::kXAxis, AcGeVector3d::kYAxis, AcGeVector3d::kZAxis,
ptOrg, vtX, vtY, vtZ);
pEnt->transformBy(mat);
}
// 三点定弧(命令用 KTCADUtilityEx::FormatArc,这里直接用 AcGeCircArc3d 推)
AcDbArc* ArcBy3Point(const AcGePoint3d& pt1, const AcGePoint3d& pt2, const AcGePoint3d& pt3)
{
AcGeCircArc3d geArc(pt1, pt2, pt3);
if (geArc.radius() < 1e-9) return NULL;
return new AcDbArc(geArc.center(), geArc.normal(), geArc.radius(), geArc.startAng(), geArc.endAng());
}
// ---------------------------------------------------------------- 轮廓
// 2D 轮廓 -> 面域:{points:[[x,y],...]} 或 {diameter: d},
// 落在"过 ptIns、法向 vtZ"的平面上,dElev 是沿法向的额外抬高。
// shortcut: points 按 OCS 的 x/y 解释,法向不是 Z 时平面原点与预期可能差一点,
// 需要精确摆放就用 revolve/extrude 的 3D 写法或先画好轮廓再引用。
AcDbRegion* BuildProfileRegion(const nlohmann::json& sec, const AcGePoint3d& ptIns,
const AcGeVector3d& vtZ, double dElev, std::wstring& err)
{
const AcGePoint3d ptSec = ptIns + vtZ * dElev;
AcGeVector3d vtX, vtY;
AxesOf(vtZ, vtX, vtY);
AcDbRegion* pReg = NULL;
if (sec.contains("diameter") && sec["diameter"].is_number())
{
const double dD = sec["diameter"].get<double>();
if (dD <= 0.0) { err = L"轮廓 diameter 必须 > 0"; return NULL; }
AcDbCircle cir(AcGePoint3d::kOrigin, AcGeVector3d::kZAxis, 0.5 * dD);
PlaceOnFrame(&cir, ptSec, vtX, vtY, vtZ);
pReg = CoreTools::createRegion(&cir);
}
else if (sec.contains("points") && sec["points"].is_array() && sec["points"].size() >= 3)
{
AcDbPolyline pl((int)sec["points"].size());
int nIdx = 0;
for (size_t j = 0; j < sec["points"].size(); ++j)
{
const nlohmann::json& pt = sec["points"][j];
if (!pt.is_array() || pt.size() < 2) continue;
pl.addVertexAt(nIdx++, AcGePoint2d(pt[0].get<double>(), pt[1].get<double>()), 0.0, 0.0, 0.0);
}
if (nIdx >= 3)
{
pl.setClosed(true);
PlaceOnFrame(&pl, ptSec, vtX, vtY, vtZ);
pReg = CoreTools::createRegion(&pl);
}
}
if (pReg == NULL && err.empty())
err = L"轮廓生成面域失败:需要 points(至少 3 点、能闭合)或 diameter";
return pReg;
}
// 一串 3D 点连成的闭合折线 -> 面域(任意平面都行,revolve 用这个)
AcDbRegion* BuildRegionFrom3dLoop(const AcGePoint3dArray& pts, std::wstring& err)
{
if (pts.length() < 3) { err = L"轮廓点少于 3 个"; return NULL; }
AcDbVoidPtrArray lnPtrs;
for (int i = 0; i < pts.length(); ++i)
lnPtrs.append(new AcDbLine(pts[i], pts[(i + 1) % pts.length()]));
AcDbRegion* pReg = CoreTools::createRegion(lnPtrs);
for (int i = 0; i < lnPtrs.length(); ++i)
delete (AcDbLine*)lnPtrs[i];
if (pReg == NULL && err.empty()) err = L"3D 轮廓闭合失败(点不共面?)";
return pReg;
}
// 面域质心(拉伸/切割的路径线从这里出发,与命令 getCenterOfReg 一致)
AcGePoint3d RegionCenter(AcDbRegion* pReg)
{
if (pReg == NULL) return AcGePoint3d(0.0, 0.0, 0.0);
AcDbExtents ext;
if (pReg->getGeomExtents(ext) != Acad::eOk) return AcGePoint3d(0.0, 0.0, 0.0);
return AcGePoint3d(0.5 * (ext.minPoint().x + ext.maxPoint().x),
0.5 * (ext.minPoint().y + ext.maxPoint().y),
0.5 * (ext.minPoint().z + ext.maxPoint().z));
}
// ---------------------------------------------------------------- 拉伸体
// 命令 CreateExtrude:轮廓沿自身法向拉 dH,路径线从轮廓质心出发。
AcDbX3dSolid* BuildExtrudeSolid(const nlohmann::json& a, const AcGePoint3d& ptIns,
const AcGeVector3d& vtZ, std::wstring& err)
{
if (!hasKey(a, "profile")) { err = L"拉伸体需要 profile{points|diameter}"; return NULL; }
const double dH = numOr(a, "height", 0.0);
if (fabs(dH) < 1e-9) { err = L"拉伸体需要 height(拉伸高度,可以为负)"; return NULL; }
AcDbRegion* pReg = BuildProfileRegion(a["profile"], ptIns, vtZ, 0.0, err);
if (pReg == NULL) return NULL;
const AcGePoint3d ptCen = RegionCenter(pReg);
AcDbX3dSolid* pSolid = new AcDbX3dSolid();
const bool bOk = pSolid->CreateExtrude(pReg, AcDbLine(ptCen, ptCen + vtZ * dH));
delete pReg;
if (!bOk)
{
delete pSolid;
err = L"CreateExtrude 失败";
return NULL;
}
return pSolid;
}
// ---------------------------------------------------------------- 旋转体
// 命令 CreateRevolve:轮廓绕一条直线转 2π(CreateRevolve2)。
// profile 用 [r,h] 两点式:r = 到轴的距离、h = 沿轴的坐标,轴由 axis_start/axis_end 给。
AcDbX3dSolid* BuildRevolveSolid(const nlohmann::json& a, std::wstring& err)
{
AcGePoint3d ptAxisS(0.0, 0.0, 0.0), ptAxisE(0.0, 0.0, 1.0);
readPoint(a, "axis_start", ptAxisS);
readPoint(a, "axis_end", ptAxisE);
AcGeVector3d vtAxis = ptAxisE - ptAxisS;
if (vtAxis.length() < 1e-9) { err = L"旋转体需要 axis_start / axis_end(两点不能重合)"; return NULL; }
vtAxis.normalize();
// 径向:优先取 direction 里与轴垂直的分量,否则随便找一个垂直方向
AcGeVector3d vtRad = DirOf(a);
vtRad -= vtAxis * vtRad.dotProduct(vtAxis);
if (vtRad.length() < 1e-9)
{
vtRad = AcGeVector3d::kXAxis - vtAxis * vtAxis.x;
if (vtRad.length() < 1e-9)
vtRad = AcGeVector3d::kYAxis - vtAxis * vtAxis.y;
}
vtRad.normalize();
if (!hasKey(a, "profile") || !a["profile"].is_array() || a["profile"].size() < 3)
{
err = L"旋转体需要 profile:[[r,h],...](r=到轴距离、h=沿轴坐标),至少 3 点";
return NULL;
}
AcGePoint3dArray pts;
for (size_t i = 0; i < a["profile"].size(); ++i)
{
const nlohmann::json& pr = a["profile"][i];
if (!pr.is_array() || pr.size() < 2) continue;
pts.append(ptAxisS + vtRad * pr[0].get<double>() + vtAxis * pr[1].get<double>());
}
AcDbRegion* pReg = BuildRegionFrom3dLoop(pts, err);
if (pReg == NULL) return NULL;
const double dAngle = numOr(a, "angle", 360.0);
AcDbX3dSolid* pSolid = new AcDbX3dSolid();
const bool bOk = pSolid->CreateRevolve2(pReg, ptAxisS, vtAxis,
CoreTools::A2R(dAngle), 0.0);
delete pReg;
if (!bOk)
{
delete pSolid;
err = L"CreateRevolve2 失败(轮廓不能与轴相交/穿过)";
return NULL;
}
return pSolid;
}
// ---------------------------------------------------------------- 扫掠体
// 命令 CreateSweep:轮廓 + 一条路径多段线。
// path 用 [[x,y],...],与该轮廓同一个 OCS 平面。
AcDbX3dSolid* BuildSweepSolid(const nlohmann::json& a, const AcGePoint3d& ptIns,
const AcGeVector3d& vtZ, std::wstring& err)
{
if (!hasKey(a, "profile")) { err = L"扫掠体需要 profile{points|diameter}"; return NULL; }
if (!hasKey(a, "path") || !a["path"].is_array() || a["path"].size() < 2)
{
err = L"扫掠体需要 path:[[x,y],...](至少 2 点,与轮廓同一 OCS 平面)";
return NULL;
}
AcDbRegion* pReg = BuildProfileRegion(a["profile"], ptIns, vtZ, 0.0, err);
if (pReg == NULL) return NULL;
// 路径所在的平面必须"立"在轮廓平面上:坐标 (u,v),u 沿 vtX、v 沿 vtZ(v 就是扫掠前进方向)
AcGeVector3d vtX, vtY;
AxesOf(vtZ, vtX, vtY);
const AcGeVector3d vtThird = vtX.crossProduct(vtZ).normalize();
AcDbPolyline plPath;
int nIdx = 0;
for (size_t i = 0; i < a["path"].size(); ++i)
{
const nlohmann::json& pt = a["path"][i];
if (!pt.is_array() || pt.size() < 2) continue;
plPath.addVertexAt(nIdx++, AcGePoint2d(pt[0].get<double>(), pt[1].get<double>()), 0.0, 0.0, 0.0);
}
PlaceOnFrame(&plPath, ptIns, vtX, vtZ, vtThird);
if (nIdx < 2)
{
delete pReg;
err = L"扫掠体 path 至少要 2 个点";
return NULL;
}
AcDbX3dSolid* pSolid = new AcDbX3dSolid();
const bool bOk = pSolid->CreateSweep(pReg, &plPath);
delete pReg;
if (!bOk)
{
delete pSolid;
err = L"CreateSweep 失败(路径要穿过轮廓平面、且是平面曲线)";
return NULL;
}
return pSolid;
}
// ---------------------------------------------------------------- 切割
// 命令 CreateCut:把轮廓沿 -Z 拉出 maxLen 的柱体当"刀"(永远是减料)。
AcDbX3dSolid* BuildCutSolid(const nlohmann::json& a, const AcGePoint3d& ptIns,
const AcGeVector3d& vtZ, double dHostMax, std::wstring& err)
{
if (!hasKey(a, "profile")) { err = L"切割需要 profile{points|diameter}(切割轮廓)"; return NULL; }
double dDepth = numOr(a, "depth", 0.0);
if (dDepth <= 0.0) dDepth = dHostMax; // 缺省跟命令一样取母体最大尺寸
if (dDepth <= 0.0) { err = L"切割需要 depth(母体尺寸也取不到)"; return NULL; }
AcDbRegion* pReg = BuildProfileRegion(a["profile"], ptIns, vtZ, 0.0, err);
if (pReg == NULL) return NULL;
const AcGePoint3d ptCen = RegionCenter(pReg);
AcDbX3dSolid* pSolid = new AcDbX3dSolid();
const bool bOk = pSolid->CreateExtrude(pReg, AcDbLine(ptCen, ptCen - vtZ * dDepth));
delete pReg;
if (!bOk)
{
delete pSolid;
err = L"切割体的 CreateExtrude 失败";
return NULL;
}
return pSolid;
}
// ------------------------------------------------ 异形堰(沿圆/弧排布的堰体)
// 移植自 CYiXingYanDlg::makeRegion4Arc / makeXSolid4Arc:
// 基准线上取 [dStart, dStart+弧长] 的一段,向圆心方向偏 dT 生成上下两个截面再放样。
AcDbRegion* WeirRegionAt(double dStart, AcDbCurve* pCurve, double dL, double dT,
const AcGePoint3d& ptCen, double dR, std::wstring& err)
{
if (dR <= 1e-6 || dL <= 1e-6) { err = L"基准线半径/堰宽太小"; return NULL; }
const double alpha = asin((std::min)(0.999, (dL * 0.5) / dR));
const double l = dT / cos(alpha);
const double dEnd = dStart + dR * alpha * 2.0;
AcGePoint3d ptStart1, ptMid1, ptEnd1, ptStart2, ptMid2, ptEnd2;
if (pCurve->getPointAtDist(dStart, ptStart1) != Acad::eOk ||
pCurve->getPointAtDist((dEnd + dStart) * 0.5, ptMid1) != Acad::eOk ||
pCurve->getPointAtDist(dEnd, ptEnd1) != Acad::eOk)
{
err = L"基准线取点失败(start_distance 超出基线长度?)";
return NULL;
}
AcGeVector3d vt = ptCen - ptMid1;
vt.normalize();
ptMid2 = ptMid1 + vt * dT;
ptStart2 = ptStart1 + vt * l;
ptEnd2 = ptEnd1 + vt * l;
// 命令里留 0.1 的缝,避免上下两条弧完全重合时面域失败
const double dScale = 0.1;
ptStart1 -= vt * dScale;
ptMid1 -= vt * dScale;
ptEnd1 -= vt * dScale;
AcDbArc* pArc1 = ArcBy3Point(ptStart1, ptMid1, ptEnd1);
ptStart2 += vt * dScale;
ptMid2 += vt * dScale;
ptEnd2 += vt * dScale;
AcDbArc* pArc2 = ArcBy3Point(ptStart2, ptMid2, ptEnd2);
if (pArc1 == NULL || pArc2 == NULL)
{
delete pArc1; delete pArc2;
err = L"基准线三点定弧失败";
return NULL;
}
AcDbLine ln1(ptStart1, ptStart2);
AcDbLine ln2(ptEnd1, ptEnd2);
AcDbVoidPtrArray ptrs;
ptrs.append(pArc1);
ptrs.append(pArc2);
ptrs.append(&ln1);
ptrs.append(&ln2);
AcDbRegion* pReg = CoreTools::createRegion(ptrs);
delete pArc1;
delete pArc2;
if (pReg == NULL) err = L"堰体截面(弧形面域)生成失败";
return pReg;
}
// 异形堰:基准线必须是圆或弧(命令也只能选 CIRCLE/ARC)
AcDbX3dSolid* BuildWeirSolid(const nlohmann::json& a, AcDbEntity* pBaseCurve,
double dStartDist, std::wstring& err)
{
AcDbCurve* pCurve = (pBaseCurve != NULL) ? AcDbCurve::cast(pBaseCurve) : NULL;
if (pCurve == NULL) { err = L"异形堰需要 base_curve:圆或圆弧的 handle"; return NULL; }
AcGePoint3d ptCen(0.0, 0.0, 0.0);
double dR = 0.0;
if (AcDbCircle* pCir = AcDbCircle::cast(pBaseCurve))
{
ptCen = pCir->center();
dR = pCir->radius();
}
else if (AcDbArc* pArc = AcDbArc::cast(pBaseCurve))
{
ptCen = pArc->center();
dR = pArc->radius();
}
else
{
err = L"异形堰的 base_curve 只支持圆或圆弧(命令里也只能选 CIRCLE/ARC)";
return NULL;
}
const int nType = intOr(a, "weir_type", 0); // 0=三角(上宽下窄) 1=方形(上下同宽)
const double dL = numOr(a, "weir_width", 0.0); // m_dL 堰宽(沿基线)
const double dT = numOr(a, "weir_thickness", 0.0); // m_dT 堰厚(径向)
const double dH1 = numOr(a, "weir_height1", 0.0); // m_dH1 上段高
const double dH2 = numOr(a, "weir_height2", 0.0); // m_dH2 下段高
if (dL <= 0.0 || dT <= 0.0 || dH1 <= 0.0)
{
err = L"异形堰需要 weir_width / weir_thickness / weir_height1,且都 > 0";
return NULL;
}
AcDbRegion* pReg1 = WeirRegionAt(dStartDist, pCurve, dL, dT, ptCen, dR, err);
if (pReg1 == NULL) return NULL;
AcGeMatrix3d mat;
if (nType == 0 || nType == 1)
{
mat.setToTranslation(-AcGeVector3d::kZAxis * dH1);
pReg1->transformBy(mat);
}
AcDbRegion* pReg2 = NULL;
if (nType == 1)
{
pReg2 = (AcDbRegion*)pReg1->clone();
mat.setToTranslation(-AcGeVector3d::kZAxis * (dH1 + dH2));
pReg2->transformBy(mat);
}
else
{
// 三角堰:下截面在更远处,且只有 10 宽(与命令一致)
const double a1 = asin((std::min)(0.999, (dL * 0.5) / dR));
const double dArcLen1 = a1 * dR;
const double dL2 = 10.0;
const double a2 = asin((std::min)(0.999, dL2 * 0.5 / dR));
const double dArcLen2 = a2 * dR;
pReg2 = WeirRegionAt(dStartDist + (dArcLen1 - dArcLen2), pCurve, dL2, dT, ptCen, dR, err);
if (pReg2 == NULL)
{
delete pReg1;
return NULL;
}
mat.setToTranslation(-AcGeVector3d::kZAxis * (dH1 + dH2));
pReg2->transformBy(mat);
}
AcArray<AcDbRegion*> regs;
regs.append(pReg1);
regs.append(pReg2);
AcDbX3dSolid* pSolid = new AcDbX3dSolid();
if (!pSolid->CreateLoft(regs))
{
delete pSolid;
pSolid = NULL;
err = L"堰体 CreateLoft 失败(两截面法向不一致?)";
}
delete pReg1;
delete pReg2;
return pSolid;
}
// 放样体(loft):命令 CreateLoft 是"一级一级选闭合轮廓 + 给层高",
// 工具里换成一次给 sections:[ {diameter, elevation} 或 {points:[[x,y],...], elevation} ]
// 每级沿 direction 抬 elevation,轮廓用 OCS(x/y 就是给定坐标)。
// shortcut: 放样体不支持 update(AcDbX3dSolid 只存尺寸不存截面),要改就删了重建。
AcDbX3dSolid* BuildLoftSolid(const nlohmann::json& a, const AcGePoint3d& ptIns,
const AcGeVector3d& vtZ, std::wstring& err)
{
if (!hasKey(a, "sections") || !a["sections"].is_array() || a["sections"].size() < 2)
{
err = L"放样体需要 sections:至少两级截面,每级 {diameter} 或 {points:[[x,y],...]},可选 elevation";
return NULL;
}
AcArray<AcDbRegion*> regs;
for (size_t i = 0; i < a["sections"].size(); ++i)
{
const nlohmann::json& sec = a["sections"][i];
const double dEl = sec.contains("elevation") ? sec["elevation"].get<double>() : 0.0;
AcGePoint3d ptSec = ptIns + vtZ * dEl;
AcGePoint3d ptSec2 = ptSec;
AcDbRegion* pReg = BuildProfileRegion(sec, ptIns, vtZ, dEl, err);
(void)ptSec2;
if (pReg == NULL)
{
err = L"第 " + std::to_wstring(i + 1) + L" 级截面生成失败(要不闭合,要不 points 太少)";
break;
}
regs.append(pReg);
}
AcDbX3dSolid* pSolid = NULL;
if (err.empty() && regs.length() >= 2)
{
pSolid = new AcDbX3dSolid();
if (!pSolid->CreateLoft(regs))
{
delete pSolid;
pSolid = NULL;
err = L"CreateLoft 失败(各级截面得共面于同一法向、并且层高不为 0)";
}
}
else if (err.empty())
{
err = L"放样体至少需要 2 级有效截面";
}
for (int i = 0; i < regs.length(); ++i)
{
delete regs[i];
}
return pSolid;
}
// ---------------------------------------------------------------- 总分派
AcDbX3dSolid* BuildShapeSolid(const ShapeSpec& sp, const nlohmann::json& a, AecDbBDPipeBase* pHost,
double dHostMax, const AcGePoint3d& ptIns, const AcGeVector3d& vtZ, std::wstring& err)
{
switch (sp.nKind)
{
case kLoft: return BuildLoftSolid(a, ptIns, vtZ, err);
case kExtrude: return BuildExtrudeSolid(a, ptIns, vtZ, err);
case kRevolve: return BuildRevolveSolid(a, err);
case kSweep: return BuildSweepSolid(a, ptIns, vtZ, err);
case kCut: return BuildCutSolid(a, ptIns, vtZ, dHostMax, err);
case kWeir:
{
// 基准线:给 handle(圆/圆弧),命令里是拾取
if (!hasKey(a, "base_curve"))
{
err = L"异形堰需要 base_curve:圆或圆弧实体的 handle";
return NULL;
}
const std::string sId = a["base_curve"].get<std::string>();
AcDbEntity* pBase = openByHandle(sId, AcDb::kForRead);
if (pBase == NULL)
{
err = L"按 handle 打不开基准线:" + utf8ToWstr(sId);
return NULL;
}
AcDbX3dSolid* pSolid = BuildWeirSolid(a, pBase, numOr(a, "start_distance", 0.0), err);
pBase->close();
return pSolid;
}
default: break;
}
return NULL;
}
// 部件:DTYG_TYPE + BIM 数据(名称/颜色/统计类型)+ 单个 solid,与命令一致
AecDbX3dPart* MakePart(const ShapeSpec& sp, AcDbX3dSolid* pSolid, const std::wstring& sName,
int nColor, const AcGePoint3d& ptIns,
const AcGeVector3d& vtX, const AcGeVector3d& vtY, const AcGeVector3d& vtZ)
{
AecDbX3dPart* pPart = new AecDbX3dPart();
pPart->GetSpecialtyData()->SetAt(_T("DTYG_TYPE"), sp.pszName);
// solid 的 org 是**中心**,工具的 position 是**插入点**,两个都留着免得回调时错位
pPart->GetSpecialtyData()->SetAt(_T("DTYG_INS"), ptIns);
pPart->SetName(sName.c_str());
CString sClr;
if (nColor == 0) sClr = _T("ByBlock");
else if (nColor == 256) sClr = _T("ByLayer");
else sClr.Format(_T("%d"), nColor);
SH_BIM_BLOCK bims;
bims.push_back(std::make_pair(CString(_T("名称")), CString(sName.c_str())));
bims.push_back(std::make_pair(CString(_T("颜色")), sClr));
bims.push_back(std::make_pair(CString(_T("统计类型")), CString(_T("其它"))));
pPart->setBimDatas(bims);
pPart->AddX3dSolid(pSolid);
pPart->SetOrgPoint(pSolid->GetCentoridPoint());
pPart->SetAxis(0, vtX);
pPart->SetAxis(1, vtY);
pPart->SetAxis(2, vtZ);
return pPart;
}
// 母体:墙/板/梁/柱/堰/异形构筑物 都是 AecDbBDPipeBase 派生
AecDbBDPipeBase* OpenHost(const nlohmann::json& args, AcDbEntity*& pOut, std::wstring& err)
{
pOut = NULL;
if (!hasKey(args, "host"))
{
err = L"缺少 host(母体实体的 handle:墙/板/梁/柱/堰/异形构筑物)";
return NULL;
}
const std::string sHost = args["host"].get<std::string>();
pOut = openByHandle(sHost, AcDb::kForWrite);
if (pOut == NULL)
{
err = L"按 handle 打不开母体:" + utf8ToWstr(sHost);
return NULL;
}
AecDbBDPipeBase* pHost = AecDbBDPipeBase::cast(pOut);
if (pHost == NULL)
{
const std::string sCls = classNameOf(pOut);
err = L"handle " + utf8ToWstr(sHost) + L" 是 " + utf8ToWstr(sCls) +
L",不是可加造型的实体(需要 AecDbBDPipeBase 派生:墙/板/梁/柱/堰/异形构筑物)";
pOut->close();
pOut = NULL;
}
return pHost;
}
// 造型的插入点:优先用记下的 DTYG_INS,老数据(命令建的)按中心反推
AcGePoint3d InsertPointOf(AecDbX3dPart* pPart, const ShapeSpec& sp, const double* p,
const AcGePoint3d& ptCenter, const AcGeVector3d& vtZ)
{
AcGePoint3d ptIns(0.0, 0.0, 0.0);
if (!pPart->GetSpecialtyData()->GetAt(_T("DTYG_INS"), ptIns))
ptIns = ptCenter - vtZ * CenterOffset(sp, p);
return ptIns;
}
std::string ModeToStr(int nOper)
{
return (nOper == AcDb::kBoolSubtract) ? "subtract" : "unite";
}
nlohmann::json ParamsToJson(const ShapeSpec& sp, const double* p)
{
nlohmann::json o = nlohmann::json::object();
for (int i = 0; i < sp.nParams; ++i)
o[sp.aszParam[i]] = p[i];
return o;
}
nlohmann::json PartToJson(AecDbBDPipeBase* pHost, int nIndex)
{
AecDbX3dPart* pPart = pHost->GetX3dPart(nIndex);
if (pPart == NULL) return nlohmann::json();
nlohmann::json o;
CString sType;
pPart->GetSpecialtyData()->GetAt(_T("DTYG_TYPE"), sType);
CString sName;
pPart->GetName(sName);
o["guid"] = acharToUtf8(pPart->GetGUID());
o["name"] = acharToUtf8((LPCTSTR)sName);
o["type"] = acharToUtf8((LPCTSTR)sType);
o["mode"] = ModeToStr(pPart->GetBoolOperFor());
const ShapeSpec* sp = FindShapeByName(sType);
if (sp != NULL) o["shape"] = acharToUtf8(sp->pszKey);
if (pPart->GetX3dSolidCount() > 0)
{
AcDbX3dSolid* pSolid = pPart->GetX3dSolid(0);
if (pSolid != NULL)
{
const AcGePoint3d ptCenter = pSolid->GetOrgPoint();
AcGeVector3d vtZ = pSolid->GetvtZ();
if (vtZ.length() < 1e-9) vtZ = AcGeVector3d::kZAxis; // 放样体没存 vtZ
o["direction"] = { vtZ.x, vtZ.y, vtZ.z };
if (sp != NULL)
{
AcArray<double> ar;
double p[6] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
if (pSolid->GetSolidData(sp->ePrim, ar))
{
for (int i = 0; i < sp->nParams && i < ar.length(); ++i)
p[i] = ar[i];
o["params"] = ParamsToJson(*sp, p);
}
const AcGePoint3d ptIns = InsertPointOf(pPart, *sp, p, ptCenter, vtZ);
o["position"] = { ptIns.x, ptIns.y, ptIns.z };
}
else
{
o["position"] = { ptCenter.x, ptCenter.y, ptCenter.z };
}
}
}
return o;
}
}
// ---------------------------------------------------------------------------
// add_aec_multipart —— 新建异形构筑物(PL_YXGZ)
// ---------------------------------------------------------------------------
class ToolAddMultiPart : public mcp_Tool
{
public:
std::string private_name() const override { return "add_aec_multipart"; }
std::string private_description() const override
{
return "新建一个空的异形构筑物(AecDbMultiPartEntity,菜单 PL_YXGZ),"
"之后用 add_aec_shape 往里加几何体。命令里截面是个半径 1mm 的占位圆、基准线是 1mm 的竖线,"
"真正的形体全靠后加的造型,这里保持一致。position 是安放点(图纸单位),图层缺省 LAY_YGDT。"
"返回新实体的 handle。";
}
nlohmann::json private_input_schema() const override
{
return nlohmann::json::parse(R"({
"type": "object",
"properties": {
"position": { "type": "array", "items": { "type": "number" },
"description": "安放点 [x,y] 或 [x,y,z],缺省原点" },
"direction": { "type": "array", "items": { "type": "number" },
"description": "竖向 [x,y,z],缺省 [0,0,1]" },
"layer": { "type": "string", "description": "图层,缺省 LAY_YGDT" }
}
})");
}
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 pt(0.0, 0.0, 0.0);
readPoint(args, "position", pt);
const AcGeVector3d vtZ = DirOf(args);
AecDbMultiPartEntity* pEnt = new AecDbMultiPartEntity();
// 截面与基准线:与命令一致,1mm 占位
const double l = 0.001, h = 0.001;
AcDbCircle cir(pt, AcGeVector3d::kZAxis, l);
AcDbLine line(pt, pt + vtZ * h);
pEnt->SetBaseCurve(&line);
AcDbRegion* pReg = CoreTools::createRegion(&cir);
if (pReg == NULL)
{
delete pEnt;
return errJson(kErrInternal, L"占位截面(1mm 圆)生成失败");
}
pEnt->SetSection(pReg, pt);
delete pReg; pReg = NULL;
AcGeVector3d vtX, vtY;
AxesOf(vtZ, vtX, vtY);
pEnt->SetOrg(pt);
pEnt->SetXDir(vtX);
pEnt->SetYDir(vtY);
pEnt->SetZDir(vtZ);
std::wstring sLay = hasKey(args, "layer") ? wstrOr(args, "layer", L"") : L"";
if (sLay.empty()) sLay = L"LAY_YGDT";
AcDbObjectId idLay = KTSetting::InitLayer(sLay.c_str());
if (!idLay.isNull()) pEnt->setLayer(idLay);
AcDbObjectId idNew;
Acad::ErrorStatus es = addToSpace(pEnt, &idNew);
if (es != Acad::eOk)
{
delete pEnt;
return errJson(kErrInternal, std::wstring(L"加入模型空间失败,err=") + std::to_wstring((int)es));
}
touchEntity(pEnt);
pEnt->close();
nlohmann::json body;
body["ok"] = true;
body["type"] = "multipart";
body["handle"] = HandleOfId(idNew);
body["position"] = { pt.x, pt.y, pt.z };
return okJson(body);
}
};
EXPORT_MCP_TOOL(ToolAddMultiPart, AddAecMultiPartTool)
// ---------------------------------------------------------------------------
// add_aec_shape —— 向已有实体加造型(PL_DTYG)
// ---------------------------------------------------------------------------
class ToolAddShape : public mcp_Tool
{
public:
std::string private_name() const override { return "add_aec_shape"; }
std::string private_description() const override
{
return "向墙/板/梁/柱/堰/异形构筑物(AecDbBDPipeBase 派生)里加一个几何体(菜单 PL_DTYG 造型设计)。"
"造型种类见 shape,尺寸参数见各 shape 说明,全部图纸单位;mode=unite 加料 / subtract 挖料。"
"position 是造型的插入点(立方体/圆柱/圆台/球台是底面中心,球体是球底,四方台/楔形体以该点为原点)。"
"命令里同一个实体上可以叠很多造型,这里一次加一个,返回 part_guid;改/删/查分别用 "
"update_aec_shape / delete_aec_shape / list_aec_shapes。"
"支持 7 种基本体 + 放样体”(shape=loft,用 sections 给多级截面,命令里是一级一级选轮廓 + 层高)。"
"拉伸/旋转/扫掠/环/切割/异形堰没做。放样体只能新增,不能 update(截面没存在实体里)。";
}
nlohmann::json private_input_schema() const override
{
return nlohmann::json::parse(R"({
"type": "object",
"properties": {
"host": { "type": "string", "description": "母体 handle(墙/板/梁/柱/堰/异形构筑物)" },
"shape": { "type": "string",
"enum": [ "box", "cylinder", "cone", "pyramid", "sphere", "drum", "wedge",
"loft", "extrude", "revolve", "sweep", "cut", "weir" ],
"description": "loft 放样体(用 sections);box 立方体 length,width,height;cylinder 圆柱 radius,height;cone 圆台 radius_bottom,radius_top,height;pyramid 四方台 top_length,top_width,bottom_length,bottom_width,height,x_offset;sphere 球体 radius;drum 球台 radius,len1,len2,start_angle,end_angle(度);wedge 楔形体 a,b,thickness" },
"position": { "type": "array", "items": { "type": "number" }, "description": "插入点 [x,y,z],缺省母体中心" },
"direction": { "type": "array", "items": { "type": "number" }, "description": "造型竖向 [x,y,z],缺省 [0,0,1]" },
"mode": { "type": "string", "enum": [ "unite", "subtract" ], "description": "并/差,缺省 unite" },
"name": { "type": "string", "description": "部件名,缺省用造型中文名" },
"color": { "type": "integer", "description": "ACI 颜色号,256=ByLayer(缺省)" },
"length": { "type": "number" }, "width": { "type": "number" }, "height": { "type": "number" },
"radius": { "type": "number" }, "radius_bottom": { "type": "number" }, "radius_top": { "type": "number" },
"top_length": { "type": "number" }, "top_width": { "type": "number" },
"bottom_length": { "type": "number" }, "bottom_width": { "type": "number" },
"x_offset": { "type": "number" },
"len1": { "type": "number" }, "len2": { "type": "number" },
"start_angle": { "type": "number" }, "end_angle": { "type": "number" },
"a": { "type": "number" }, "b": { "type": "number" }, "thickness": { "type": "number" },
"profile": { "description": "extrude/sweep/cut 的轮廓:{points:[[x,y],...]} 或 {diameter},落在过 position、法向 direction 的平面上;revolve 用 [[r,h],...](r=到轴距离、h=沿轴坐标)",
"type": [ "object", "array" ],
"properties": {
"diameter": { "type": "number" },
"points": { "type": "array", "items": { "type": "array", "items": { "type": "number" } } } } },
"path": { "type": "array", "items": { "type": "array", "items": { "type": "number" } },
"description": "sweep 的路径 [[x,y],...](与轮廓同一 OCS 平面,至少 2 点)" },
"axis_start": { "type": "array", "items": { "type": "number" }, "description": "revolve 的轴起点" },
"axis_end": { "type": "array", "items": { "type": "number" }, "description": "revolve 的轴终点" },
"angle": { "type": "number", "description": "revolve 的旋转角(度),缺省 360" },
"base_curve": { "type": "string", "description": "weir 的基准线 handle(圆或圆弧实体)" },
"start_distance": { "type": "number", "description": "weir 起始位置(沿基准线的弧长),缺省 0" },
"weir_type": { "type": "integer", "description": "weir 类型:0=三角堰(上宽下窄)、1=方形堰" },
"weir_width": { "type": "number", "description": "weir 堰宽(沿基线)" },
"weir_thickness": { "type": "number", "description": "weir 堰厚(径向)" },
"weir_height1": { "type": "number", "description": "weir 上段高" },
"weir_height2": { "type": "number", "description": "weir 下段高" },
"sections": { "type": "array", "description": "loft 的各级截面(至少 2 级,自下而上)", "items": {
"type": "object",
"properties": {
"diameter": { "type": "number", "description": "圆形截面直径" },
"points": { "type": "array", "items": { "type": "array", "items": { "type": "number" } },
"description": "多边形截面点串 [[x,y],...](自动闭合,坐标相对 position)" },
"elevation": { "type": "number", "description": "该级沿 direction 的标高,缺省 0" }
}
} }
},
"required": [ "host", "shape" ]
})");
}
nlohmann::json Execute(const nlohmann::json& args) override
{
if (workingDb() == NULL) return errJson(kErrNoDocument, L"没有活动图纸");
DocLock lock;
if (!lock.isLocked()) return errJson(kErrInternal, L"拿不到图纸写锁(有别的命令在跑?)");
std::wstring err;
AcDbEntity* pOut = NULL;
AecDbBDPipeBase* pHost = OpenHost(args, pOut, err);
if (pHost == NULL) return errJson(kErrWrongType, err);
const ShapeSpec* sp = FindShape(wstrOr(args, "shape", L""));
if (sp == NULL)
{
pHost->close();
return errJson(kErrBadParam, L"shape 只支持 box / cylinder / cone / pyramid / sphere / drum / wedge / "
L"loft / extrude / revolve / sweep / cut / weir");
}
const bool bSpecial = (sp->nKind != kPrim);
double p[6];
InitParams(p);
bool bMissing = false;
for (int i = 0; !bSpecial && i < sp->nParams; ++i)
{
p[i] = numOr(args, sp->aszParam[i], 0.0);
if (sp->aszParam[i] == std::string("x_offset") ||
sp->aszParam[i] == std::string("len1") ||
sp->aszParam[i] == std::string("start_angle"))
continue; // 这几个允许 0
if (sp->ePrim == AcDbX3dSolid::kDrum &&
(sp->aszParam[i] == std::string("start_angle") || sp->aszParam[i] == std::string("end_angle")))
{
p[i] = CoreTools::A2R(p[i]); // 度 -> 弧度,与命令一致
continue;
}
if (p[i] <= 0.0) bMissing = true;
}
if (bMissing)
{
pHost->close();
return errJson(kErrBadParam, std::wstring(L"造型 ") + sp->pszName + L" 的尺寸参数没给全或 <= 0");
}
// 插入点:没给就用母体位置/包围盒中心
AcGePoint3d ptIns(0.0, 0.0, 0.0);
if (!readPoint(args, "position", ptIns))
{
ptIns = pHost->GetPosition();
AcGePoint3d ptMin, ptMax;
if (entityBBox(pHost, ptMin, ptMax))
ptIns = AcGePoint3d(0.5 * (ptMin.x + ptMax.x), 0.5 * (ptMin.y + ptMax.y), 0.5 * (ptMin.z + ptMax.z));
}
const AcGeVector3d vtZ = DirOf(args);
AcGeVector3d vtX, vtY;
AxesOf(vtZ, vtX, vtY);
// 切割缺省刀长取母体最大尺寸(命令 getMaxLength)
double dHostMax = 0.0;
{
AcGePoint3d ptMin, ptMax;
if (entityBBox(pHost, ptMin, ptMax))
dHostMax = (std::max)((std::max)(ptMax.x - ptMin.x, ptMax.y - ptMin.y), ptMax.z - ptMin.z);
}
AcDbX3dSolid* pSolid = bSpecial
? BuildShapeSolid(*sp, args, pHost, dHostMax, ptIns, vtZ, err)
: BuildSolid(*sp, p, ptIns, vtZ, err);
if (pSolid == NULL)
{
pHost->close();
return errJson(kErrBadParam, err);
}
// 切割在命令里永远是减料
const bool bSub = (sp->nKind == kCut) || (wstrOr(args, "mode", L"unite") == L"subtract");
std::wstring sName = hasKey(args, "name") ? wstrOr(args, "name", L"") : std::wstring();
if (sName.empty()) sName = sp->pszName;
AecDbX3dPart* pPart = MakePart(*sp, pSolid, sName, intOr(args, "color", 256), ptIns, vtX, vtY, vtZ);
const CString sGuid = pPart->GetGUID();
pHost->AddX3dPart(pPart, bSub ? AcDb::kBoolSubtract : AcDb::kBoolUnite);
pHost->ReCreateDraw3d(); // 3D 缓存要重建,命令里是 regen
touchEntity(pHost);
pHost->close();
nlohmann::json body;
body["ok"] = true;
body["part_guid"] = acharToUtf8(sGuid);
body["shape"] = acharToUtf8(sp->pszKey);
body["type"] = acharToUtf8(sp->pszName);
body["name"] = acharToUtf8((LPCTSTR)CString(sName.c_str()));
body["mode"] = bSub ? "subtract" : "unite";
body["params"] = ParamsToJson(*sp, p);
body["position"] = { ptIns.x, ptIns.y, ptIns.z };
return okJson(body);
}
};
EXPORT_MCP_TOOL(ToolAddShape, AddAecShapeTool)
// ---------------------------------------------------------------------------
// list_aec_shapes —— 列出实体上已有的造型
// ---------------------------------------------------------------------------
class ToolListShapes : public mcp_Tool
{
public:
std::string private_name() const override { return "list_aec_shapes"; }
std::string private_description() const override
{
return "列出一个实体上的所有造型部件(PL_DTYG 加的几何体):guid、名称、造型种类、并/差、"
"插入点、方向与尺寸参数,供 update_aec_shape / delete_aec_shape 用。";
}
nlohmann::json private_input_schema() const override
{
return nlohmann::json::parse(R"({
"type": "object",
"properties": { "host": { "type": "string", "description": "实体 handle" } },
"required": [ "host" ]
})");
}
nlohmann::json Execute(const nlohmann::json& args) override
{
if (workingDb() == NULL) return errJson(kErrNoDocument, L"没有活动图纸");
DocLock lock;
if (!lock.isLocked()) return errJson(kErrInternal, L"拿不到图纸写锁(有别的命令在跑?)");
std::wstring err;
AcDbEntity* pOut = NULL;
AecDbBDPipeBase* pHost = OpenHost(args, pOut, err);
if (pHost == NULL) return errJson(kErrWrongType, err);
nlohmann::json arItems = nlohmann::json::array();
const int nCount = pHost->GetX3dPartCount();
for (int i = 0; i < nCount; ++i)
{
nlohmann::json o = PartToJson(pHost, i);
if (!o.is_null()) arItems.push_back(o);
}
pHost->close();
nlohmann::json body;
body["ok"] = true;
body["count"] = (int)arItems.size();
body["shapes"] = arItems;
return okJson(body);
}
};
EXPORT_MCP_TOOL(ToolListShapes, ListAecShapesTool)
// ---------------------------------------------------------------------------
// update_aec_shape —— 改造型(尺寸/位置/方向/并差/名字/颜色)
// ---------------------------------------------------------------------------
class ToolUpdateShape : public mcp_Tool
{
public:
std::string private_name() const override { return "update_aec_shape"; }
std::string private_description() const override
{
return "修改实体上的某个造型:给新的尺寸/插入点/方向/并差模式/名字/颜色,没给的沿用原来的。"
"实现是整块部件重建(等价于命令里的\"重建 solid\"),位置和并差模式也能改。"
"造型种类(shape)也能换,但必须还是基本体那 7 种。";
}
nlohmann::json private_input_schema() const override
{
return nlohmann::json::parse(R"({
"type": "object",
"properties": {
"host": { "type": "string", "description": "实体 handle" },
"part_guid": { "type": "string", "description": "造型部件的 guid(list_aec_shapes 里拿)" },
"shape": { "type": "string",
"enum": [ "box", "cylinder", "cone", "pyramid", "sphere", "drum", "wedge" ],
"description": "换造型种类(可选)" },
"position": { "type": "array", "items": { "type": "number" }, "description": "新插入点" },
"direction": { "type": "array", "items": { "type": "number" }, "description": "新方向" },
"mode": { "type": "string", "enum": [ "unite", "subtract" ] },
"name": { "type": "string" },
"color": { "type": "integer" },
"length": { "type": "number" }, "width": { "type": "number" }, "height": { "type": "number" },
"radius": { "type": "number" }, "radius_bottom": { "type": "number" }, "radius_top": { "type": "number" },
"top_length": { "type": "number" }, "top_width": { "type": "number" },
"bottom_length": { "type": "number" }, "bottom_width": { "type": "number" },
"x_offset": { "type": "number" },
"len1": { "type": "number" }, "len2": { "type": "number" },
"start_angle": { "type": "number" }, "end_angle": { "type": "number" },
"a": { "type": "number" }, "b": { "type": "number" }, "thickness": { "type": "number" }
},
"required": [ "host", "part_guid" ]
})");
}
nlohmann::json Execute(const nlohmann::json& args) override
{
if (workingDb() == NULL) return errJson(kErrNoDocument, L"没有活动图纸");
DocLock lock;
if (!lock.isLocked()) return errJson(kErrInternal, L"拿不到图纸写锁(有别的命令在跑?)");
std::wstring err;
AcDbEntity* pOut = NULL;
AecDbBDPipeBase* pHost = OpenHost(args, pOut, err);
if (pHost == NULL) return errJson(kErrWrongType, err);
const std::string sGuid = args["part_guid"].get<std::string>();
AecDbX3dPart* pOld = pHost->GetX3dPart(utf8ToWstr(sGuid).c_str());
if (pOld == NULL)
{
pHost->close();
return errJson(kErrNotFound, L"母体上找不到这个造型部件:" + utf8ToWstr(sGuid));
}
if (pOld->GetX3dSolidCount() != 1)
{
pHost->close();
return errJson(kErrBadParam, L"这个部件不是单 solid 造型(solid 数 != 1),不支持修改");
}
// 先把旧部件的信息全读出来(后面重建会把它删掉)
CString sTypeOld;
pOld->GetSpecialtyData()->GetAt(_T("DTYG_TYPE"), sTypeOld);
const ShapeSpec* spOld = FindShapeByName(sTypeOld);
CString sName;
pOld->GetName(sName);
const std::wstring sNameOld = acharToUtf8((LPCTSTR)sName).empty() ? std::wstring() : utf8ToWstr(acharToUtf8((LPCTSTR)sName));
int nOper = pOld->GetBoolOperFor();
AcGeVector3d vtXA(0.0, 0.0, 0.0), vtYA(0.0, 0.0, 0.0), vtZA(0.0, 0.0, 1.0);
pOld->GetAxis(0, vtXA);
pOld->GetAxis(1, vtYA);
pOld->GetAxis(2, vtZA);
AcDbX3dSolid* pOldSolid = pOld->GetX3dSolid(0);
if (pOldSolid == NULL)
{
pHost->close();
return errJson(kErrInternal, L"旧造型取不到 solid");
}
const AcGePoint3d ptCenter = pOldSolid->GetOrgPoint();
AcGeVector3d vtZ = pOldSolid->GetvtZ();
AcGePoint3d ptIns = ptCenter;
if (spOld != NULL && spOld->ePrim == AcDbX3dSolid::kLoft)
{
pHost->close();
return errJson(kErrBadParam, L"放样体不支持改造(截面数据没存在实体里),请 delete_aec_shape 后重建");
}
// 旧尺寸:按旧种类的参数顺序读出来
double p[6];
InitParams(p);
if (spOld != NULL)
{
AcArray<double> ar;
if (pOldSolid->GetSolidData(spOld->ePrim, ar))
{
for (int i = 0; i < spOld->nParams && i < ar.length(); ++i)
p[i] = ar[i];
}
}
if (FindShapeByName(sTypeOld) != NULL)
ptIns = InsertPointOf(pOld, *FindShapeByName(sTypeOld), p, ptCenter, vtZ);
// 新种类:没给就沿用旧的
const ShapeSpec* spNew = spOld;
if (hasKey(args, "shape") && wstrOr(args, "shape", L"") == L"loft")
{
pHost->close();
return errJson(kErrBadParam, L"造型种类不能改成放样体(改造型按尺寸重建,放样体没有尺寸),请新增一个");
}
if (hasKey(args, "shape"))
{
spNew = FindShape(wstrOr(args, "shape", L""));
if (spNew == NULL)
{
pHost->close();
return errJson(kErrBadParam, L"shape 只支持 box / cylinder / cone / pyramid / sphere / drum / wedge");
}
if (spNew != spOld)
{
// 换了种类,旧尺寸不能沿用,必须全给
double pNewIn[6];
InitParams(pNewIn);
bool bMissing = false;
for (int i = 0; i < spNew->nParams; ++i)
{
if (!hasKey(args, spNew->aszParam[i])) { bMissing = true; break; }
}
if (bMissing)
{
pHost->close();
return errJson(kErrBadParam, std::wstring(L"换成 ") + spNew->pszName + L" 需要把它的尺寸参数一起给全");
}
InitParams(p);
}
}
if (spNew == NULL)
{
pHost->close();
return errJson(kErrBadParam, L"这个部件的造型种类不认识(DTYG_TYPE 不是基本体),没法按参数重建");
}
// 覆盖尺寸
for (int i = 0; i < spNew->nParams; ++i)
{
if (!hasKey(args, spNew->aszParam[i]))
continue;
double dVal = numOr(args, spNew->aszParam[i], p[i]);
if (spNew->ePrim == AcDbX3dSolid::kDrum &&
(std::string(spNew->aszParam[i]) == "start_angle" || std::string(spNew->aszParam[i]) == "end_angle"))
dVal = CoreTools::A2R(dVal);
p[i] = dVal;
}
readPoint(args, "position", ptIns);
if (hasKey(args, "direction"))
vtZ = DirOf(args);
if (wstrOr(args, "mode", L"").compare(0, 1, L"s") == 0) nOper = AcDb::kBoolSubtract;
else if (hasKey(args, "mode")) nOper = AcDb::kBoolUnite;
std::wstring sNameNew = hasKey(args, "name") ? wstrOr(args, "name", L"") : sNameOld;
if (sNameNew.empty()) sNameNew = spNew->pszName;
// 旧颜色:从 BIM 数据里读(没有就 ByLayer)
int nColor = intOr(args, "color", 256);
if (!hasKey(args, "color"))
{
SH_BIM_BLOCK bims;
pOld->getBimDatas(bims);
for (size_t i = 0; i < bims.size(); ++i)
{
if (bims[i].first != _T("颜色"))
continue;
const CString sClr = bims[i].second;
if (sClr == _T("ByLayer")) nColor = 256;
else if (sClr == _T("ByBlock")) nColor = 0;
else nColor = _ttoi(sClr);
}
}
AcDbX3dSolid* pSolid = BuildSolid(*spNew, p, ptIns, vtZ, err);
if (pSolid == NULL)
{
pHost->close();
return errJson(kErrBadParam, err);
}
AcGeVector3d vtX, vtY;
AxesOf(vtZ, vtX, vtY);
// 重建:删旧部件 -> 加新部件(并/差模式随之改变)
pHost->RemoveX3dPart(utf8ToWstr(sGuid).c_str());
AecDbX3dPart* pNewPart = MakePart(*spNew, pSolid, sNameNew, nColor, ptIns, vtX, vtY, vtZ);
const CString sGuidNew = pNewPart->GetGUID();
pHost->AddX3dPart(pNewPart, nOper);
pHost->ReCreateDraw3d(); // 3D 缓存要重建,命令里是 regen
touchEntity(pHost);
pHost->close();
nlohmann::json body;
body["ok"] = true;
body["part_guid"] = acharToUtf8(sGuidNew);
body["old_guid"] = sGuid;
body["shape"] = acharToUtf8(spNew->pszKey);
body["type"] = acharToUtf8(spNew->pszName);
body["name"] = acharToUtf8(CString(sNameNew.c_str()));
body["mode"] = ModeToStr(nOper);
body["params"] = ParamsToJson(*spNew, p);
body["position"] = { ptIns.x, ptIns.y, ptIns.z };
return okJson(body);
}
};
EXPORT_MCP_TOOL(ToolUpdateShape, UpdateAecShapeTool)
// ---------------------------------------------------------------------------
// delete_aec_shape —— 删造型
// ---------------------------------------------------------------------------
class ToolDeleteShape : public mcp_Tool
{
public:
std::string private_name() const override { return "delete_aec_shape"; }
std::string private_description() const override
{
return "删掉实体上的一个造型部件(按 guid)。不传 part_guid 就删掉该实体上所有造型。";
}
nlohmann::json private_input_schema() const override
{
return nlohmann::json::parse(R"({
"type": "object",
"properties": {
"host": { "type": "string", "description": "实体 handle" },
"part_guid": { "type": "string", "description": "造型部件 guid;不给则删全部造型" }
},
"required": [ "host" ]
})");
}
nlohmann::json Execute(const nlohmann::json& args) override
{
if (workingDb() == NULL) return errJson(kErrNoDocument, L"没有活动图纸");
DocLock lock;
if (!lock.isLocked()) return errJson(kErrInternal, L"拿不到图纸写锁(有别的命令在跑?)");
std::wstring err;
AcDbEntity* pOut = NULL;
AecDbBDPipeBase* pHost = OpenHost(args, pOut, err);
if (pHost == NULL) return errJson(kErrWrongType, err);
nlohmann::json body;
body["ok"] = true;
if (hasKey(args, "part_guid"))
{
const std::wstring sGuid = utf8ToWstr(args["part_guid"].get<std::string>());
if (!pHost->RemoveX3dPart(sGuid.c_str()))
{
pHost->close();
return errJson(kErrNotFound, L"母体上找不到这个造型部件:" + sGuid);
}
body["removed"] = 1;
}
else
{
const int nCount = pHost->GetX3dPartCount();
pHost->RemoveAllX3dPart();
body["removed"] = nCount;
}
pHost->ReCreateDraw3d(); // 3D 缓存要重建,命令里是 regen
touchEntity(pHost);
pHost->close();
return okJson(body);
}
};
EXPORT_MCP_TOOL(ToolDeleteShape, DeleteAecShapeTool)