添加项目文件。

This commit is contained in:
GG Z
2026-02-28 21:01:57 +08:00
parent 9fe4e5a9aa
commit 7a229067cc
175 changed files with 18060 additions and 0 deletions

66
Mstn.Toolkit/External/DimensionData.cs vendored Normal file
View File

@@ -0,0 +1,66 @@
using Bentley.DgnPlatformNET;
using Bentley.DgnPlatformNET.Elements;
using Bentley.GeometryNET;
namespace Mstn.Toolkit.External
{
class DimensionData : DimensionCreateData
{
private DimensionStyle m_dimStyle;
private DgnTextStyle m_textStyle;
private Symbology m_symbology;
private LevelId m_levelId;
private DirectionFormatter m_directionFormatter;
public DimensionData(DimensionStyle dimStyle, DgnTextStyle textStyle, Symbology symb, LevelId levelId, DirectionFormatter formatter)
{
m_dimStyle = dimStyle;
m_textStyle = textStyle;
m_symbology = symb;
m_levelId = levelId;
m_directionFormatter = formatter;
}
public override DimensionStyle GetDimensionStyle()
{
return m_dimStyle;
}
public override DgnTextStyle GetTextStyle()
{
return m_textStyle;
}
public override Symbology GetSymbology()
{
return m_symbology;
}
public override LevelId GetLevelId()
{
return m_levelId;
}
public override int GetViewNumber()
{
return 0;
}
//此函数返回的旋转矩阵与GetViewRotation返回的旋转矩阵共同定义了尺寸标注元素的方向
public override DMatrix3d GetDimensionRotation()
{
return DMatrix3d.Identity;
}
public override DMatrix3d GetViewRotation()
{
return DMatrix3d.Identity;
}
//用于从数字方向值构造字符串。
public override DirectionFormatter GetDirectionFormatter()
{
return m_directionFormatter;
}
}
}

124
Mstn.Toolkit/External/DynamicDrawTool.cs vendored Normal file
View File

@@ -0,0 +1,124 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Bentley.DgnPlatformNET;
using Bentley.DgnPlatformNET.Elements;
using Bentley.GeometryNET;
using Bentley.MstnPlatformNET;
namespace Mstn.Toolkit.External
{
public class DynamicDrawTool : DgnElementSetTool
{
private List<DPoint3d> m_pos;
private string startPrompt;
private string updatePrompt;
private Func<List<DPoint3d>, DPoint3d, Element> creation;
private int pickTimes;
private DynamicDrawTool(int toolId, int prompt) : base(toolId, prompt)
{
}
/// <summary>
/// 交互式工具的入口函数,用于声明工具并进行加载
/// </summary>
/// <param name="creation">元素创建的条件及创建元素的对象</param>
/// <param name="pickTimes">选取次数</param>
/// <param name="startPrompt"></param>
/// <param name="updatePrompt"></param>
public static void Setup(Func<List<DPoint3d>, DPoint3d, Element> creation, int pickTimes, string startPrompt, string updatePrompt)
{
DynamicDrawTool primitiveTool = new(0, 0)
{
startPrompt = startPrompt,
updatePrompt = updatePrompt,
pickTimes = pickTimes,
creation = creation
};
primitiveTool.InstallTool();//加载工具
}
protected override void OnPostInstall()//工具激活后执行
{
NotificationManager.OutputPrompt(startPrompt);//将提示语输出到提示框中
m_pos = [];//创建用于储存坐标的列表
}
/*
* 如果我们对通过参数传递进来的元素进行修改并且返回SUCCESS的话在_DoOperationForModify
* 中会用修改后的元素替换掉原来的元素当然前提是_IsModifyOriginal返回true。否则的话会直接
* 把修改后的元素重新添加到Dgn文件中。
*/
public override StatusInt OnElementModify(Element element)
{
return StatusInt.Error;
}
protected override bool OnDataButton(DgnButtonEvent ev)//点击确认键(默认为左键)后触发
{
NotificationManager.OutputPrompt(updatePrompt);//将提示语输出到提示框中
if (m_pos.Count() == 0)
{
BeginDynamics();//启动动态绘制,只启动一次
}
m_pos.Add(ev.Point);//添加捕捉点
if (pickTimes == m_pos.Count)
{
EndDynamics();//关闭动态绘制
m_pos.Add(ev.Point);//添加捕捉点
Element element = creation(m_pos, ev.Point);
element.AddToModel();//将椭圆元素写入模型
m_pos.Clear();//清空列表
NotificationManager.OutputPrompt(startPrompt);//将提示语输出到提示框中
}
return true;
}
/// <summary>
/// BeginDynamics后动态绘制时触发
/// </summary>
/// <param name="ev"></param>
protected override void OnDynamicFrame(DgnButtonEvent ev)
{
//每次增加一个点的时候,生成元素的操作都要更新,根据点数来确定生成元素的类型,不断在基础上叠加
Element element = creation(m_pos, ev.Point);
if (null == element)//若未成功生成椭圆元素
return;//返回
RedrawElems redrawElems = new()
{
DrawMode = DgnDrawMode.TempDraw,//设置绘制模式
DrawPurpose = DrawPurpose.Dynamics//设置绘制目标
};//使用元素用于动态绘制
redrawElems.SetDynamicsViewsFromActiveViewSet(Session.GetActiveViewport());//设置视角
redrawElems.DoRedraw(element);//使用元素用于动态绘制
}
protected override bool OnResetButton(DgnButtonEvent ev)//点击重置键(默认为右键)触发
{
if (m_pos.Count() == 0)//判断列表中点个数,若列表中没有坐标点则退出
{
ExitTool();//退出工具
}
else
{
EndDynamics();//停止动态捕捉
m_pos.Clear();//清空列表中的数据
NotificationManager.OutputPrompt(startPrompt);//将提示语输出到提示框中
}
return true;//返回
}
protected override void OnRestartTool()//重启工具时触发
{
Setup(creation, pickTimes, startPrompt, updatePrompt);//重新启动交互式工具
}
}
}

View File

@@ -0,0 +1,67 @@
using System.Collections.Generic;
using Bentley.DgnPlatformNET;
using Bentley.DgnPlatformNET.Elements;
using Bentley.GeometryNET;
namespace Mstn.Toolkit.External
{
public class PolyfaceProcessor : ElementGraphicsProcessor
{
private readonly IList<PolyfaceHeader> outputPolyface;
private readonly FacetOptions options;
private DTransform3d currentTransform;
public PolyfaceProcessor(ref IList<PolyfaceHeader> outputPolyface, FacetOptions options)
{
this.outputPolyface = outputPolyface;
currentTransform = DTransform3d.Identity;
this.options = options;
}
public override FacetOptions GetFacetOptions()
{
return options;
}
public override bool ProcessAsBody(bool isCurved)
{
return false;
}
public override bool ProcessAsFacets(bool isPolyface)
{
return true;
}
public override BentleyStatus ProcessFacets(PolyfaceHeader meshData, bool filled = false)
{
if (meshData.FacetCount == 0)
{
return BentleyStatus.Error;
}
PolyfaceHeader header = PolyfaceHeader.New();
header.CopyFrom(meshData);
header.TwoSided = true;
header.Transform(ref currentTransform, false);
outputPolyface.Add(header);
return BentleyStatus.Success;
}
public void Process(Element element)
{
ElementGraphicsOutput.Process(element, this);
}
public override void AnnounceTransform(DTransform3d transform)
{
currentTransform = transform != null ? transform : DTransform3d.Identity;
}
public override void AnnounceIdentityTransform()
{
currentTransform = DTransform3d.Identity;
}
}
}

33
Mstn.Toolkit/External/RelayCommand.cs vendored Normal file
View File

@@ -0,0 +1,33 @@
using System;
using System.Windows.Input;
namespace Mstn.Toolkit.External
{
public class RelayCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Func<object, bool> _canExecute;
public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
{
_execute = execute ?? throw new ArgumentNullException(nameof(execute));
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
}

View File

@@ -0,0 +1,474 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Bentley.DgnPlatformNET;
using Bentley.DgnPlatformNET.Elements;
using Bentley.GeometryNET;
using Bentley.MstnPlatformNET;
using Mstn.Toolkit.Extensions;
namespace Mstn.Toolkit.External
{
internal class SelectionExtensions
{
/// <summary>
/// 围栅(临时组合)
/// </summary>
/// <remarks>只在当前操作期内有效关闭DGN后再打开将不复存在命名围栅则可以保存下来</remarks>
/// <param name="unparsed"></param>
public static void CreateFenceByElement(string unparsed)//Case:FenceClipByElement
{
DgnModelRef dgnModelRef = Session.Instance.GetActiveDgnModelRef();//获得当前的模型空间/参照空间 注DgnModelRef是一个基类DgnModel和DgnAttachment都派生于这个基类
DgnModel dgnModel = Session.Instance.GetActiveDgnModel();//获得当前激活的模型控件
Viewport view = Session.GetActiveViewport();//获得当前视图信息
double uorPerMas = Session.Instance.GetActiveDgnModel().GetModelInfo().UorPerMaster;//分辨率单位转换为主单位
#region Create complex shape element
DPoint3d p1 = new(-10 * uorPerMas, 0, 0);//声明线串元素端点
DPoint3d p2 = new(-10 * uorPerMas, 260 * uorPerMas, 0);
DPoint3d p3 = new(110 * uorPerMas, 260 * uorPerMas, 0);
DPoint3d p4 = new(110 * uorPerMas, 110 * uorPerMas, 0);
DPoint3d[] pos = { p1, p2, p3, p4 };//声明端点集
LineStringElement lineString = new(dgnModel, null, pos);//声明线串元素
DPoint3d centerPo = new(0, 100 * uorPerMas, 0);//声明弧元素的圆心
ArcElement arc = new(
dgnModel,
null,
centerPo,
110 * uorPerMas,
110 * uorPerMas,
DMatrix3d.Identity,
0,
-Angle.PI.Radians / 2);//声明弧元素
ComplexShapeElement complexShape = new(dgnModel, null);//声明复杂形元素
complexShape.AddComponentElement(lineString);//将子构件添加到复杂元素中
complexShape.AddComponentElement(arc);
complexShape.AddComponentComplete();//子构件添加完成
#endregion
if (StatusInt.Success == FenceManager.DefineByElement(complexShape, view))//使用元素围成的区域声明围栅
{
FenceParameters fenceParams = new(dgnModelRef, DTransform3d.Identity);//声明围栅信息
FenceManager.InitFromActiveFence(fenceParams, false, false, FenceClipMode.None);
/*
* 使用围栅信息初始化围栅
* fenceParameters围栅信息
* overlap若需囊括部分包含的元素则输入true
* doClip若需修剪操作则输入true
* allowClipFlag若需要在原始元素上剪切则输入FenceClipMode.Original若需要在新声明的元素上剪切则输入FenceClipMode.Copy
*/
ElementAgenda eAgenda = new();//声明元素容器
DgnModelRef[] modelRefList = new DgnModelRef[1];//设置需要声明围栅的模型空间
modelRefList[0] = dgnModelRef;//设置模型空间
FenceManager.BuildAgenda(fenceParams, eAgenda, modelRefList, false, false, false);
/*
* 使用围栅信息获得符合要求的元素集
* fenceParameters围栅信息
* elementAgenda符合要求的元素集
* modelRefList声明围栅的模型空间
* modifyOrig是否修改原始元素
* allowLocked是否允许锁定元素
* callAsynch是否需要调用异步
*/
string result = "Result:\n";//声明字符串
for (uint i = 0; i < eAgenda.GetCount(); i++)//遍历元素容器中的元素
{
Element element = eAgenda.GetEntry(i);//获得元素容器中的元素
result = result + "ElementId = " + element.ElementId + '\n';//将元素ID写入模型
}
result = result + "Total count: " + eAgenda.GetCount();//输出元素个数
MessageBox.Show(result);//将字符串输出到对话框中
}
}
public static void ClipElementByFence(string unparsed)//Case:FenceClipByPoints
{
DgnModelRef dgnModelRef = Session.Instance.GetActiveDgnModelRef();//获得当前的模型空间/参照空间 注DgnModelRef是一个基类DgnModel和DgnAttachment都派生于这个基类
DgnModel dgnModel = Session.Instance.GetActiveDgnModel();//获得当前激活的模型控件
Viewport view = Session.GetActiveViewport();//获得当前视图信息
double uorPerMas = Session.Instance.GetActiveDgnModel().GetModelInfo().UorPerMaster;//分辨率单位转换为主单位
DPoint3d p1 = new(-10 * uorPerMas, 0, -130 * uorPerMas);//声明围栅坐标点
DPoint3d p2 = new(-10 * uorPerMas, 0, 200 * uorPerMas);
DPoint3d p3 = new(50 * uorPerMas, 0, 200 * uorPerMas);
DPoint3d p4 = new(50 * uorPerMas, 0, -130 * uorPerMas);
DPoint3d[] pos = { p1, p2, p3, p4 };//使用端点声明端点集
ShapeElement shape = new(dgnModel, null, pos);//声明形元素
if (StatusInt.Success == FenceManager.DefineByElement(shape, view))//使用图形建立围栅
{
FenceParameters fenceParams = new(dgnModelRef, DTransform3d.Identity);//声明围栅信息
FenceManager.InitFromActiveFence(fenceParams, true, true, FenceClipMode.Copy);//使用围栅信息初始化围栅
ElementAgenda eAgenda = new();//声明元素容器
DgnModelRef[] modelRefList = new DgnModelRef[1];//设置需要声明围栅的模型空间
modelRefList[0] = dgnModelRef;//设置模型空间
FenceManager.BuildAgenda(fenceParams, eAgenda, modelRefList, false, false, false);//使用围栅信息获得符合要求的元素集
for (uint i = 0; i < eAgenda.GetCount(); i++)//遍历元素容器中的元素
{
ElementAgenda insideElems = new();//声明元素容器
ElementAgenda outsideElems = new();//声明元素容器
Element element = eAgenda.GetEntry(i);//获得元素容器中的元素
FenceManager.ClipElement(fenceParams, insideElems, outsideElems, element, FenceClipFlags.Optimized);//对围栅内的元素进行剪切
for (uint j = 0; j < outsideElems.GetCount(); j++)//遍历围栅切割后生成的外围元素
{
using (ElementCopyContext copyContext = new(dgnModelRef))//复制元素
{
Element elemToCopy = outsideElems.GetEntry(j);//获得切割后生成的外围元素
copyContext.DoCopy(elemToCopy);//将元素复制到指定模型中
}
}
}
}
}
//参考文章https://communities.bentley.com/communities/other_communities/bdn_other_communities/b/bdn-blog/posts/mesh
public static void BreakElementIntoPolyface(string unparsed)//Case:BreakSolidExample
{
DgnModel dgnModel = Session.Instance.GetActiveDgnModel();//获取当前的模型空间
double uorPerMas = Session.Instance.GetActiveDgnModel().GetModelInfo().UorPerMaster;//分辨率单位转换为主单位
#region Create Solid
#region Create profile
DPoint3d p1 = new(-uorPerMas, uorPerMas, 0);//声明体元素端点
DPoint3d p2 = new(uorPerMas, uorPerMas, 0);
DPoint3d p3 = new(uorPerMas, -uorPerMas, 0);
DPoint3d p4 = new(-uorPerMas, -uorPerMas, 0);
DPoint3d[] pos = { p1, p2, p3, p4 };//将面元素端点添加到面元素端点数组中
ShapeElement shape = new(dgnModel, null, pos);//声明形元素
#endregion
DPoint3d origin = DPoint3d.Zero;//声明拉伸基点
DVector3d extrudeVector = new(uorPerMas, uorPerMas, 10 * uorPerMas);//声明拉伸向量
SurfaceOrSolidElement solid = SurfaceOrSolidElement.CreateProjectionElement(
dgnModel,
null,
shape,
origin,
extrudeVector,
DTransform3d.Identity,
true);//声明实体元素
solid.AddToModel();//将拉伸体写入模型
#endregion
IList<PolyfaceHeader> polyfaces = [];//声明多面体几何列表
FacetOptions facetOptions = new();//曲面属性,用于设置生成曲面或曲线弦的属性声明
facetOptions.SetDefaults();//属性设置为默认
PolyfaceProcessor polyfaceProcessor = new(ref polyfaces, facetOptions);//声明用于分解多面体几何的处理器
polyfaceProcessor.Process(solid); //将需要分解的元素输入处理器中
for (int i = 0; i < polyfaces.Count; i++)//遍历元素中分解后的多面体几何
{
List<uint> colorIndex = [];//声明颜色索引
foreach (DPoint3d po in polyfaces[i].Point)//为了获得该多面体几何的端点个数,对端点进行遍历
{
if (po.Z < 5 * uorPerMas)//Z坐标小于5为红色否则则为蓝色
{
colorIndex.Add(0x00ff0000);//红色
}
else
{
colorIndex.Add(0x000000ff);//蓝色
}
//关于16进制颜色对照请参考http://each.sinaapp.com/tools/color.html 格式为0x00+(去掉#)16进制颜色
}
polyfaces[i].IntColor = colorIndex;//设置多面体几何的颜色索引值
polyfaces[i].ActivateVectorsForIndexing(polyfaces[i]);//设置为激活状态,以便携带所有的数据及索引信息
MeshHeaderElement meshElem = new(dgnModel, null, polyfaces[i]);//使用修改后的多面体几何建立网格元素
TransformInfo trans = new(DTransform3d.FromTranslation(new DPoint3d(5 * uorPerMas, 0, 0)));//声明变换信息
meshElem.ApplyTransform(trans);//对网格元素应用变换
meshElem.AddToModel();//将网格元素写入模型
}
}
public static void BreakElementIntoCurves(string unparsed)//Case:BreakSolidExample
{
DgnModel dgnModel = Session.Instance.GetActiveDgnModel();//获取当前的模型空间
double uorPerMas = Session.Instance.GetActiveDgnModel().GetModelInfo().UorPerMaster;//分辨率单位转换为主单位
#region Create Solid
#region Create profile
DPoint3d p1 = new(-uorPerMas, uorPerMas, 0);//声明体元素端点
DPoint3d p2 = new(uorPerMas, uorPerMas, 0);
DPoint3d p3 = new(uorPerMas, -uorPerMas, 0);
DPoint3d p4 = new(-uorPerMas, -uorPerMas, 0);
DPoint3d[] pos = { p1, p2, p3, p4 };//将面元素端点添加到面元素端点数组中
ShapeElement shape = new(dgnModel, null, pos);//声明形元素
#endregion
DPoint3d origin = DPoint3d.Zero;//声明拉伸基点
DVector3d extrudeVector = new(uorPerMas, uorPerMas, 10 * uorPerMas);//声明拉伸向量
SurfaceOrSolidElement solid = SurfaceOrSolidElement.CreateProjectionElement(
dgnModel,
null,
shape,
origin,
extrudeVector,
DTransform3d.Identity,
true);//声明实体元素
solid.AddToModel();//将拉伸体写入模型
#endregion
IList<CurveVector> curves = [];//声明多面体几何列表
CurveProcessor curveProcessor = new(ref curves);//声明用于分解曲线几何的处理器
curveProcessor.Process(solid); //将需要分解的元素输入处理器中
List<CurveVector> curvesList = [];//声明几何图元列表
for (int i = 0; i < curves.Count; i++)//遍历元素中分解后的曲线几何
{
Element subElem = DraftingElementSchema.ToElement(dgnModel, curves[i], null);//将几何转换成对应的元素
subElem.AddToModel();//将元素写入模型
if (subElem.ElementType == MSElementType.LineString)//判断转换后的元素是否为线串
{
ComplexShapeElement complexShape = new(dgnModel, null);//声明复杂形元素因为对于线串元素不一定为闭合有可能无法围城封闭图形故使用建立shape的形式闭合几何图形
complexShape.AddComponentElement(subElem);//将线串元素添加到shape元素中
complexShape.AddComponentComplete();//添加元素完成
CurveVector shapeCurve = complexShape.GetCurveVector();//获得shape的封闭图形
CurveVector curveWithFillets = shapeCurve.CloneWithFillets(0.1 * uorPerMas);//对获得的几何图元做倒角处理
curvesList.Add(curveWithFillets);//将几何图元添加到列表中
}
}
BentleyStatus result = Create.BodyFromLoft(
out SolidKernelEntity entityOut,
curvesList.ToArray(),
curvesList.Count,
curvesList.ToArray(),
0,
dgnModel,
false,
false);//声明扫掠体
Convert1.BodyToElement(out Element solidElem, entityOut, null, dgnModel);//将实体转换为元素
solidElem.AddToModel();//将元素写入模型空间
}
#region PracticeWork
public static void CmdPracticeWork(string unparsed)
{
DgnFile dgnFile = Session.Instance.GetActiveDgnFile();//获得当前激活的文件
DgnModel dgnModel = Session.Instance.GetActiveDgnModel();//获取当前的模型空间
double uorPerMeter = Session.Instance.GetActiveDgnModel().GetModelInfo().UorPerMeter;//分辨率单位转换为米
#region Create beam
#region Create profile
double H = 700 * uorPerMeter / 1000;
double H1 = 125 * uorPerMeter / 1000, H2 = 125 * uorPerMeter / 1000;
double H3 = 275 * uorPerMeter / 1000;
double H4 = 75 * uorPerMeter / 1000, B4 = 75 * uorPerMeter / 1000;
double H5 = 100 * uorPerMeter / 1000;
double B3 = 125 * uorPerMeter / 1000;
double B1 = 400 * uorPerMeter / 1000;
double B2 = 300 * uorPerMeter / 1000;
double B = 150 * uorPerMeter / 1000;
DPoint3d p1 = new(-1 * 0.5 * B1, 0, 0);//声明体元素端点
DPoint3d p2 = new(-1 * 0.5 * B1, 0, H2);
DPoint3d p3 = new(-0.5 * B, 0, H2 + H5);
DPoint3d p4 = new(-0.5 * B, 0, H2 + H5 + H3);
DPoint3d p5 = new(-0.5 * B2, 0, H2 + H5 + H3 + H4);
DPoint3d p6 = new(-0.5 * B2, 0, H);
DPoint3d p7 = new(0.5 * B2, 0, H);
DPoint3d p8 = new(0.5 * B2, 0, H2 + H5 + H3 + H4);
DPoint3d p9 = new(0.5 * B, 0, H2 + H5 + H3);
DPoint3d p10 = new(0.5 * B, 0, H2 + H5);
DPoint3d p11 = new(0.5 * B1, 0, H2);
DPoint3d p12 = new(0.5 * B1, 0, 0);
DPoint3d[] pos = { p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12 };//将面元素端点添加到面元素端点数组中
ShapeElement shape = new(dgnModel, null, pos);//声明形元素
#endregion
DPoint3d origin = DPoint3d.Zero;//声明拉伸基点
DVector3d extrudeVector = new(0, 12 * uorPerMeter, 0);//声明拉伸向量
SurfaceOrSolidElement beamSolid = SurfaceOrSolidElement.CreateProjectionElement(
dgnModel,
null,
shape,
origin,
extrudeVector,
DTransform3d.Identity,
true);//使用投影的方式声明拉伸体元素
#endregion
#region Create dimension
DPoint3d d1 = new(-0.5 * B1, 0, -50 * uorPerMeter / 1000);//声明标注点
DPoint3d d2 = new(0.5 * B1, 0, -50 * uorPerMeter / 1000);//声明标注点
DPoint3d[] dimensionPos1 = { d1, d2 };//声明标注点数组
DMatrix3d dMatrix1 = new(-1, 0, 0, 0, 0, 1, 0, -1, 0);//声明变换矩阵
DimensionElement dimEle1 = CreateDimensionElement(dgnFile, dgnModel, dimensionPos1, string.Empty, dMatrix1);//声明标注元素
dimEle1.AddToModel();//将标注元素写入模型
DPoint3d d3 = new(-0.5 * B1, 0, -10 * uorPerMeter / 1000);
DPoint3d d4 = new(-0.5 * B, 0, -10 * uorPerMeter / 1000);
DPoint3d d5 = new(0.5 * B, 0, -10 * uorPerMeter / 1000);
DPoint3d d6 = new(0.5 * B1, 0, -10 * uorPerMeter / 1000);
DPoint3d[] dimensionPos2 = { d3, d4, d5, d6 };
DimensionElement dimEle2 = CreateDimensionElement(dgnFile, dgnModel, dimensionPos2, string.Empty, dMatrix1);
dimEle2.AddToModel();//将标注元素写入模型
DMatrix3d dMatrix2 = DMatrix3d.FromRows(new DVector3d(0, 1, 0), new DVector3d(-1, 0, 0), new DVector3d(0, 0, 1));
DMatrix3d dMatrix = DMatrix3d.Multiply(dMatrix1, dMatrix2);
DPoint3d d7 = new(-0.5 * B1 - 50 * uorPerMeter / 1000, 0, 0);
DPoint3d d8 = new(-0.5 * B1 - 50 * uorPerMeter / 1000, 0, H);
DPoint3d[] dimensionPos3 = { d7, d8 };
DimensionElement dimEle3 = CreateDimensionElement(dgnFile, dgnModel, dimensionPos3, string.Empty, dMatrix);
dimEle3.AddToModel();//将标注元素写入模型
DPoint3d d9 = new(-0.5 * B1 - 10 * uorPerMeter / 1000, 0, 0);
DPoint3d d10 = new(-0.5 * B1 - 10 * uorPerMeter / 1000, 0, H2);
DPoint3d d11 = new(-0.5 * B1 - 10 * uorPerMeter / 1000, 0, H2 + H5);
DPoint3d d12 = new(-0.5 * B1 - 10 * uorPerMeter / 1000, 0, H2 + H5 + H3);
DPoint3d d13 = new(-0.5 * B1 - 10 * uorPerMeter / 1000, 0, H2 + H5 + H3 + H4);
DPoint3d d14 = new(-0.5 * B1 - 10 * uorPerMeter / 1000, 0, H);
DPoint3d[] dimensionPos4 = { d9, d10, d11, d12, d13, d14 };
DimensionElement dimEle4 = CreateDimensionElement(dgnFile, dgnModel, dimensionPos4, string.Empty, dMatrix);
dimEle4.AddToModel();//将标注元素写入模型
#endregion
#region Create column
EllipseElement ellipse = new(
dgnModel,
null,
DPoint3d.Zero,
350 * uorPerMeter / 1000,
350 * uorPerMeter / 1000,
DMatrix3d.Identity);
DVector3d columnVector = new(0, 0, 3 * uorPerMeter);//声明拉伸向量
SurfaceOrSolidElement columnSolid = SurfaceOrSolidElement.CreateProjectionElement(
dgnModel,
null,
ellipse,
DPoint3d.Zero,
columnVector,
DTransform3d.Identity,
true);//使用投影的方式声明拉伸体元素
DTransform3d dTransform3D = DTransform3d.FromTranslation(new DPoint3d(0, 12 * uorPerMeter, -1 * uorPerMeter));//声明变换几何,执行元素平移操作
TransformInfo trans = new(dTransform3D);//声明变换信息
columnSolid.ApplyTransform(trans);//对拉伸圆柱体施加变换信息
#endregion
#region BooleanSubtract
Convert1.ElementToBody(out SolidKernelEntity entity1, beamSolid, true, false, false);//将实体转成SolidKernelEntity
Convert1.ElementToBody(out SolidKernelEntity entity2, columnSolid, true, false, false);//将圆台实体元素转成SolidKernelEntity
SolidKernelEntity[] entities = { entity2 };//声明实核实体集
Modify.BooleanSubtract(ref entity1, ref entities, entities.Count());//用实核实体集中的实体与实体进行布尔减运算
Convert1.BodyToElement(out Element resultElem, entity1, null, dgnModel);//将结果转换为元素
#endregion
#region Attach material
MaterialId id = FindMaterial(dgnFile, dgnModel);
AttachMaterialToElement(id, resultElem);
AttachMaterialToElement(id, columnSolid);
#endregion
}
private static void AttachMaterialToElement(MaterialId id, Element elem)
{
if (id != null)
{
MaterialPropertiesExtension propertiesExtension = MaterialPropertiesExtension.GetAsMaterialPropertiesExtension(
(DisplayableElement)elem);//为拉伸实体元素设置材料属性
propertiesExtension.AddMaterialAttachment(id);//添加嵌入的材料信息
propertiesExtension.StoresAttachmentInfo(id);//保存拉伸实体元素的材料信息
propertiesExtension.AddToModel();//将拉伸实体写入模型
}
}
private static MaterialId FindMaterial(DgnFile dgnFile, DgnModel dgnModel)
{
MaterialTable matTbl = new(dgnFile)
{
Name = "MyMaterialTable"//声明材料表名称
};//声明材料表
PaletteInfo[] palInfo = MaterialManager.GetPalettesInSearchPath("MS_MATERIAL");//从MS_MATERIAL的环境变量声明路径下读取材料图表
if (palInfo.Length < 1)//判断是否获取到材料图表
{
MessageCenter.Instance.ShowInfoMessage("Can't get palette", null, true);//输出错误信息
return null;//返回
}
for (int i = 0; i < palInfo.Count(); i++)//遍历材料图表
{
if (palInfo[i].Name == "Concrete&Pavers")//判断材料图表是否名为Concrete&Pavers
{
matTbl.AddPalette(palInfo[i]);//添加材料图表至材料表
break;//跳出循环
}
else if (i == palInfo.Count() - 1)//若未找到名为lightwidgets的材料图表
{
MessageCenter.Instance
.ShowErrorMessage(
"Can't find material lib named lightwidgets, please check",
"Can't find material lib named lightwidgets, please check",
true);//输出错误信息
}
}
MaterialManager.SetActiveTable(matTbl, dgnModel);//设置当前材料表为激活图表
MaterialManager.SaveTable(matTbl);//保存材料表
MaterialId id = new("Concrete_1");//查找名为Concrete_1的材料
return id;
}
#endregion
/*
* 参考论坛帖子:
* https://communities.bentley.com/communities/other_communities/chinafirst/f/microstation-projectwise/158653/ms-ce-c
* https://communities.bentley.com/communities/other_communities/chinafirst/f/microstation-projectwise/200717/thread/601140#601140
* https://communities.bentley.com/communities/other_communities/chinafirst/f/microstation-projectwise/221336/abd-ce-c/678991#678991
*/
private static DimensionElement CreateDimensionElement(
DgnFile dgnFile,
DgnModel dgnModel,
DPoint3d[] pos,
string text,
DMatrix3d dMatrix)
{
//获取当前dgn文件中名字为"DimStyle"的标注样式,尺寸标注元素的外貌由上百个属性控制,而标注样式是一组预先设置好的属性
//获取了预先订制好的标注样式之后还可以调用DimensionStyle下的各种SetXXX成员函数修改设置的属性
DimensionStyle dimStyle = new("DimStyle", dgnFile);//声明标注样式
dimStyle.SetBooleanProp(true, DimStyleProp.Placement_UseStyleAnnotationScale_BOOLINT);//设置标注样式
dimStyle.SetDoubleProp(1, DimStyleProp.Placement_AnnotationScale_DOUBLE);
dimStyle.SetBooleanProp(true, DimStyleProp.Text_OverrideHeight_BOOLINT);
dimStyle.SetDistanceProp(200, DimStyleProp.Text_Height_DISTANCE, dgnModel);
dimStyle.SetBooleanProp(true, DimStyleProp.Text_OverrideWidth_BOOLINT);
dimStyle.SetDistanceProp(200, DimStyleProp.Text_Width_DISTANCE, dgnModel);
dimStyle.SetBooleanProp(true, DimStyleProp.General_UseMinLeader_BOOLINT);
dimStyle.SetDoubleProp(0.01, DimStyleProp.Terminator_MinLeader_DOUBLE);
dimStyle.SetBooleanProp(true, DimStyleProp.Value_AngleMeasure_BOOLINT);
dimStyle.SetAccuracyProp((byte)AnglePrecision.Use1Place, DimStyleProp.Value_AnglePrecision_INTEGER);
int alignInt = (int)DimStyleProp_General_Alignment.True;
StatusInt status = dimStyle.SetIntegerProp(alignInt, DimStyleProp.General_Alignment_INTEGER);
dimStyle.GetIntegerProp(out int valueOut, DimStyleProp.General_Alignment_INTEGER);
DgnTextStyle textStyle = new("TestStyle", dgnFile);//设置文字样式
LevelId lvlId = Settings.GetLevelIdFromName("Default");//设置图层
DimensionData callbacks = new(dimStyle, textStyle, new Symbology(), lvlId, null);//尺寸标注元素的构造函数会调用DimensionCreateData的各个成员函数去获取声明尺寸标注元素需要的各种参数
DimensionElement dimEle = new(dgnModel, callbacks, DimensionType.SizeStroke);//声明标注元素
if (dimEle.IsValid)//判断标注元素是否有效
{
for (int i = 0; i < pos.Count(); i++)
{
dimEle.InsertPoint(pos[i], null, dimStyle, -1);//对标注元素设置插入点
}
dimEle.SetHeight(500);//设置尺寸标注元素的高度
dimEle.SetRotationMatrix(dMatrix);//设置变换信息
}
return dimEle;
}
}
}

273
Mstn.Toolkit/External/UserPickTool.cs vendored Normal file
View File

@@ -0,0 +1,273 @@
using System;
using Bentley.DgnPlatformNET;
using Bentley.DgnPlatformNET.Elements;
using static Bentley.DgnPlatformNET.DgnElementSetTool;
namespace Mstn.Toolkit.External
{
public class UserPickTool : DgnElementSetTool
{
private Func<Element, bool> allowElement;
private string prompt;
private Action<ElementAgenda> operations;
private UserPickTool(int toolId, int promptId) : base(toolId, promptId)
{
}
public static void Setup(Func<Element, bool> allowElement, Action<ElementAgenda> operations, string prompt = "请选择元素")
{
UserPickTool tool = new(0, 0)
{
prompt = prompt,
allowElement = allowElement,
operations = operations,
};
tool.InstallTool();
}
/// <summary>
/// 判断是否要启用框选或者划选
/// </summary>
/// <returns></returns>
protected override UsesDragSelect AllowDragSelect()
{
return UsesDragSelect.Box;
}
///// <summary>
///// 筛选拾取的元素
///// </summary>
///// <returns></returns>
//protected override bool FilterAgendaEntries()
//{
// for (uint i = 0; i < ElementAgenda.GetCount(); i++)
// {
// var elem = ElementAgenda.GetEntry(i);
// return allowElement(elem);
// }
// return false;
// //return base.FilterAgendaEntries();
//}
///// <summary>
///// 通过点选、围栅还是选择集来填充ElementAgenda
///// </summary>
///// <returns></returns>
//protected override ElementSource GetElementSource()
//{
// return base.GetElementSource();
//}
/// <summary>
/// 获取偏好选择方式
/// </summary>
/// <returns></returns>
protected override ElementSource GetPreferredElementSource()
{
switch (AllowFence())
{
case UsesFence.Check:
if (UseActiveFence() && FenceManager.IsFenceActive)
{
return ElementSource.Fence;
}
break;
case UsesFence.Required:
return ElementSource.Fence;
case UsesFence.None:
break;
default:
break;
}
switch (AllowSelection())
{
case UsesSelection.Check:
if (SelectionSetManager.IsActive())
{
return ElementSource.SelectionSet;
}
break;
case UsesSelection.Required:
return ElementSource.SelectionSet;
case UsesSelection.None:
break;
default:
break;
}
return ElementSource.Pick;
}
/// <summary>
/// 判断是否需要用户再点击左键才开始处理元素
/// </summary>
/// <returns></returns>
protected override bool NeedAcceptPoint()
{
return false;
}
///// <summary>
/////
///// </summary>
///// <param name="ev"></param>
///// <param name="newSearch">是否重新搜索</param>
///// <remarks>newSearch=false:表明用户最后拾取的元素不是想要的调用RemoveAgendaElement移除并继续往后定位其他元素</remarks>
//protected override void LocateOneElement(DgnButtonEvent ev, bool newSearch)
//{
// base.LocateOneElement(ev, newSearch);
//}
///// <summary>
///// 对ElementAgenda中的元素进行修改筛选
///// </summary>
//protected override void ModifyAgendaEntries()
//{
// base.ModifyAgendaEntries();
//}
///// <summary>
///// 点击确认键(默认为左键)后触发,判断是否需要拾取元素
///// </summary>
///// <param name="ev"></param>
///// <returns></returns>
//protected override bool OnDataButton(DgnButtonEvent ev)//
//{
// //var promptId = "OnDataButton";
// NotificationManager.OutputPrompt(prompt);//将提示语输出到提示框中
// if (ElementSource.Pick == GetElementSource())
// {
// //光标变为点选状态
// BeginPickElements();
// }
// else if (ElementSource.SelectionSet == GetElementSource())
// {
// //是否需要用户输入额外的确认点才开始处理选择集元素/判断是否需要用户再点击左键才开始处理元素
// if (NeedPointForSelection())
// {
// }
// else
// {
// BuildAgenda(ev);
// ProcessAgenda(ev);
// OnModifyComplete(ev);
// }
// if (!NeedPointForDynamics())
// {
// if (ElementSource.Pick != GetElementSource())
// {
// BuildAgenda(ev);
// }
// }
// }
// return true;
//}
/// <summary>
/// 修改完毕,对选择集中的元素进行处理
/// </summary>
/// <param name="ev"></param>
/// <returns></returns>
protected override bool OnModifyComplete(DgnButtonEvent ev)
{
operations(ElementAgenda);
//for (uint i = 0; i < ElementAgenda.GetCount(); i++)
//{
// var elem = ElementAgenda.GetEntry(i);
// operation(elem);
//}
NotificationManager.OutputPrompt("完成");//将提示语输出到提示框中
return base.OnModifyComplete(ev);
}
/// <summary>
/// 工具激活后执行
/// </summary>
protected override void OnPostInstall()
{
//var promptId = "OnPostInstall";
//NotificationManager.OutputPrompt(promptId);//将提示语输出到提示框中
NotificationManager.OutputPrompt(prompt);
//var dgnModel = Session.Instance.GetActiveDgnModel();//获得当前的模型空间
base.OnPostInstall();
}
/// <summary>
/// 光标定位到某个元素时调用,判断是否支持该元素,能否被选中
/// </summary>
/// <param name="path"></param>
/// <param name="cantAcceptReason">光标在上方时,进行提醒,为什么不能被选中</param>
/// <returns></returns>
protected override bool OnPostLocate(HitPath path, out string cantAcceptReason)
{
var elem = path.GetCursorElement();
var b = allowElement(elem);
cantAcceptReason = b ? path.GetCursorElement().Description : "元素不适用此功能";
return b;
}
/// <summary>
/// 点击重置键(默认为右键)触发
/// </summary>
/// <param name="ev"></param>
/// <returns></returns>
protected override bool OnResetButton(DgnButtonEvent ev)//
{
ExitTool();//退出工具
return true;//返回
}
///// <summary>
///// 重启工具时触发
///// </summary>
protected override void OnRestartTool()
{
Setup(allowElement, operations, prompt);
}
///// <summary>
///// 设置选择方式
///// </summary>
///// <param name="source"></param>
//protected override void SetElementSource(ElementSource source)
//{
// switch (source)
// {
// case ElementSource.Pick:
// break;
// case ElementSource.Fence:
// break;
// case ElementSource.SelectionSet:
// break;
// default:
// break;
// }
//}
/// <summary>
/// 是否需要继续进行选择
/// </summary>
/// <param name="ev"></param>
/// <returns></returns>
protected override bool WantAdditionalLocate(DgnButtonEvent ev)
{
if (ev == null)//若没有选择到元素
{
return true;
}
if (ev.IsControlKey)//若检测到按动Ctrl行为
{
return true;
}
if (ElementAgenda.GetCount() == 0)//若选择集中没有元素
{
return true;
}
return false;
}
/*
* 如果我们对通过参数传递进来的元素进行修改并且返回SUCCESS的话在_DoOperationForModify
* 中会用修改后的元素替换掉原来的元素当然前提是_IsModifyOriginal返回true。否则的话会直接
* 把修改后的元素重新添加到Dgn文件中。
*/
public override StatusInt OnElementModify(Element element)
{
return StatusInt.Error;
}
}
}