Skip to content
On this page

自定义实体

在 mxcad 中,我们支持用户自定义实体,可以根据具体的需求来创建和管理自定义实体。我们可以通过从自定义实体类 McDbCustomEntity() 中继承实体的名称、属性、方法等,也可结合自身需求对自定义实体类中的属性或方法进行重写。下面以自定义一条直线为例:

  1. 通过重写 dwgInFields() 函数读取自定义实体数据,dwgOutFields() 函数写入自定义实体数据(在从文件读取实体或把实体写入文件时,复制实体等地方都会调用这两个函数)。

  2. getGripPoints() 方法是在点击这个渲染好的图形时提供一个操作点位,即返回自定义的编辑夹点,并在点击操作点移动的回调函数moveGripPointsAt() 中处理夹点编辑结果。

  3. 动态绘制 worldDraw() 方法能够绘制自定义实体的显示效果。

  4. 每次触发动态绘制worldDraw,就会将原本的实例对象删掉(同时也会删除渲染的three.js物体对象),通过create方法重新创建实例。

点击 McDbCustomEntity 查看详细属性和方法说明。

ts
import { IMcDbDwgFiler, McDbCustomEntity, McDbLine, McGePoint3d, McGePoint3dArray, MxCADUiPrPoint, MxCADWorldDraw, MxCpp } from "mxcad";
import { MxFun } from "mxdraw";

class McDbTestLineCustomEntity extends McDbCustomEntity {

  private pt1: McGePoint3d = new McGePoint3d();
  private pt2: McGePoint3d = new McGePoint3d();

  constructor(imp?: any) {
    super(imp);
  }

  public create(imp: any) {
    return new McDbTestLineCustomEntity(imp)
  }

  public getTypeName(): string {
    return "McDbTestLineCustomEntity";
  }

  public dwgInFields(filter: IMcDbDwgFiler): boolean {
    this.pt1 = filter.readPoint("pt1").val;
    this.pt2 = filter.readPoint("pt2").val;
    return true;
  }

  public dwgOutFields(filter: IMcDbDwgFiler): boolean {
    filter.writePoint("pt1", this.pt1);
    filter.writePoint("pt2", this.pt2);
    return true;
  }

  public moveGripPointsAt(iIndex: number, dXOffset: number, dYOffset: number, dZOffset: number) {
    this.assertWrite();
    if (iIndex == 0) {
      this.pt1.x += dXOffset;
      this.pt1.y += dYOffset;
      this.pt1.z += dZOffset;
    }
    else if (iIndex == 1) {
      this.pt2.x += dXOffset;
      this.pt2.y += dYOffset;
      this.pt2.z += dZOffset;
    }
  };

  public getGripPoints(): McGePoint3dArray {
    let ret = new McGePoint3dArray()
    ret.append(this.pt1);
    ret.append(this.pt2);
    return ret;
  };

  public worldDraw(draw: MxCADWorldDraw): void {
    let tmpline = new McDbLine(this.pt1, this.pt2);
    draw.drawEntity(tmpline);
  }

  public setPoint1(pt1: McGePoint3d) {
    this.assertWrite();
    this.pt1 = pt1.clone();
  }

  public setPoint2(pt2: McGePoint3d) {
    this.assertWrite();
    this.pt2 = pt2.clone();
  }

  public getPoint1() {
    return this.pt1;
  }

  public getPoint2() {
    return this.pt2;
  }
}

async function MxTest_DrawCustomEntity() {
  let mxcad = MxCpp.getCurrentMxCAD();
  const getPoint = new MxCADUiPrPoint();
  getPoint.setMessage("\n指定一点:");
  let pt1 = (await getPoint.go());
  if (!pt1) return;

  getPoint.setBasePt(pt1);
  getPoint.setUseBasePt(true);

  getPoint.setMessage("\n指定二点:");
  let pt2 = (await getPoint.go());
  if (!pt2) return;

  let myline = new McDbTestLineCustomEntity();
  new McDbTestLineCustomEntity().rxInit();
  myline.setPoint1(pt1);
  myline.setPoint2(pt2);
  mxcad.drawEntity(myline);
}

MxTest_DrawCustomEntity()