【问题标题】:What is the best way for a mesh class structure in Delphi?Delphi中网格类结构的最佳方法是什么?
【发布时间】:2014-03-05 18:01:28
【问题描述】:

我想在 Delphi XE5 中创建一个三角网格结构。

主 TMyMesh 类具有通用 TObjectLists 来保存顶点、面等的列表。

假设我必须为网格的每个面计算一些东西。我可以让 TMyMesh 类处理这个:

TMyVertex=class(TComponent)
  Vertex: TPoint3D;
  //other fields and methods
end;

TMyTriangleFace=class(TComponent)
  Vertices: Array [0..2] of Integer;
  //other fields and methods
end;

TMyMesh=class(TComponent)
  ListOfVertices: TObjectList<TMyVertex>;
  ListOfTriangleFaces: TObjectList<TMyTriangleFace>;
  procedure CreateListOfTriangleFaces;
  procedure DoSomethingWithTheFace(const FaceNumber: Integer);
  procedure DoSomethingWithAllFaces;
end;

procedure TMyMesh.CreateListOfTriangleFaces;
begin
  for i := 0 to NumberOfTriangleFaces-1 do
  begin
    ListOfTriangleFaces.Add(TMyTraingleFace.Add(nil));
  end;
end;

procedure TMyMesh.DoSomethingWithTheFace(const AFaceNumber: Integer);
begin
  AVertex:=ListOfVertices[ListOfFaces[AFaceNumber].Vertices[0]];
  //do something
end;

procedure TMyMesh.DoSomethingWithAllFaces;
begin
  for i := 0 to ListOfFaces.Count-1 do
  begin
    DoSomethingWithTheFace(i);
  end;
end;

或者我可以将它委托给 TMyTriangleFace 类:

TMyVertex=class(TComponent)
  Vertex: TPoint3D;
  //other fields and methods
end;

TMyTriangleFace=class(TComponent)
  Vertices: Array [0..2] of Integer;
  procedure DoSomethingWithTheFace;
  //other fields and methods
end;

TMyMesh=class(TComponent)
  ListOfVertices: TObjectList<TMyVertex>;
  ListOfTriangleFaces: TObjectList<TMyTriangleFace>;
  procedure CreateListOfTriangleFaces;
  procedure DoSomethingWithAllFaces;
end;

procedure TMyTriangleFace.DoSomethingWithTheFace;
begin
  AVertex:=TMyMesh(Owner).ListOfVertices[Vertices[0]];
  //do something
end;

procedure TMyMesh.CreateListOfTriangleFaces;
begin
  for i := 0 to NumberOfTriangleFaces-1 do
  begin
    ListOfTriangleFaces.Add(TMyTraingleFace.Add(Self));
  end;
end;

procedure TMyMesh.DoSomethingWithAllFaces;
begin
  for i := 0 to ListOfFaces.Count-1 do
  begin
    ListOfTriangleFaces[i].DoSomethingWithTheFace;
  end;
end;

在这种情况下,我需要让 TMyTriangleFace 类访问 ListOfVertices。我可以通过在过程 CreateListOfTriangleFaces 中将 TMyMesh 作为所有者传递来做到这一点。

在我的理解中,第二部分应该是更好的代码(得墨忒耳法则)。但是作为所有者传递 TMyMesh 可能不是那么好。

执行此操作的最佳做​​法是什么?也许这两种解决方案都朝着错误的方向发展,还有更好的解决方案?

非常感谢!

【问题讨论】:

  • 您希望尽可能多地使用值。将所有东西都变成组件将导致令人震惊的性能。
  • 这个问题似乎跑题了,因为它要求进行代码审查。这个问题最好在 Code Review 堆栈交换站点提出。
  • 在我看来不像代码审查。当然有大量的代码示例,但本质上它是关于 OOP 方法与数据存储的。如果 OOP 应该是细粒度或更简单的方法是有益的。

标签: delphi decoupling law-of-demeter


【解决方案1】:

为每个顶点和三角形创建一个新对象是非常低效的,因为所有额外的初始化开销和单独的内存分配。由于内存中的数据稀疏(与 Delphi 创建的对象标头交错?)和函数调用,访问也会效率低下。

作为 David cmets,将所有内容放在一个 TMyMesh 类中,并将顶点和索引作为记录数组会更快。

【讨论】:

猜你喜欢
  • 2015-03-08
  • 1970-01-01
  • 2022-08-23
  • 2015-02-28
  • 2012-11-17
  • 1970-01-01
  • 2020-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多