Skip to main content
 首页 » 编程设计

c#之重写 VertexPositionTexture 以使用整数向量

2024年02月20日13qlqwjy

我目前正在从事一个涉及使用 VertexPositionTextures 设置大量顶点数据的项目。这最终会占用大量内存,虽然我可以就当前内存中的内容以及可以卸载到硬盘驱动器的内容进行一些优化,但我想以各种可能的方式进行优化。

那么我的问题是:有没有一种方法可以重写 VertexPositionTexture 结构,使其使用我的自定义 IntVector 类来使用更少的空间?这是否也需要修改 DrawPrimitives 和 DrawUserPrimitives?

我问这个是因为我没有使用纹理图集,所以我的 UV 坐标总是 (0,0),(0,1),(1,0),(1,1) float ,我的顶点位置也可以很容易地用整数表示。

请您参考如下方法:

是的,您可以这样做。您只需定义自定义顶点格式,XNA 将完成其余的工作。

要记住的最重要的事情是,您只能使用可用的 VertexElementFormat ( MSDN ) 中的元素 - 注意 HalfVector 格式是在 Reach 配置文件 ( info ) 中不可用。

您可能不需要创建自己的矢量类型,因为 XNA 已经在 Microsoft.Xna.Framework.Graphics.PackedVector 中提供了所有可用格式的实现( MSDN ) 或在主库中。如果您确实想创建自己的类型,它需要是一个以相同方式打包的 struct(或您的顶点中的松散字段)。

最后,值得指出的是,没有 32 位的 int 数据类型。而且也没有任何好处,因为 float(Single)在 32 位时大小相同。 (有些 GPU 以单精度运行,因此您无论如何都无法保持额外的精度。)


所以我们从一个 VertexPositionTexture 开始,它包含一个 Vector3 位置(96 位)和一个 Vector2 纹理坐标(64 位)共 160 位。

让我们把它变成一个自定义的 IntVertexPositionTexture,它包含一个 Short4 位置(64 位)和一个 NormalizedShort2 纹理坐标(32 位)总共 96 位(大小减少 40%)。

(如果您在 2D 中工作,您可以使用 Short2 而不是 Short4 并保存另外 32 位。没有 Short3 .)

这是此顶点类型的代码,实际上只是了解 API 期望的情况:

struct IntVertexPositionTexture : IVertexType 
{ 
    public Short4 Position; 
    public NormalizedShort2 TextureCoordinate; 
 
    public IntVertexPositionTexture(Short4 position, NormalizedShort2 textureCoordinate) 
    { 
        this.Position = position; 
        this.TextureCoordinate = textureCoordinate; 
    } 
 
    public static readonly VertexDeclaration VertexDeclaration = new VertexDeclaration(new VertexElement[] 
    { 
        new VertexElement(0, VertexElementFormat.Short4, VertexElementUsage.Position, 0), 
        new VertexElement(8, VertexElementFormat.NormalizedShort2, VertexElementUsage.TextureCoordinate, 0), 
    }); 
 
    VertexDeclaration IVertexType.VertexDeclaration 
    { 
        get { return IntVertexPositionTexture.VertexDeclaration; } 
    } 
} 

创建自定义顶点类型时,重要的是确保字段与您在 VertexDeclaration ( MSDN ) 中指定的顺序和布局相匹配。如何创建 VertexDeclaration 应该是不言自明的 - 只需看看 MSDN page for VertexElement's constructor .每个字段的偏移量以字节为单位指定。

elementUsage 和 usageIndex 匹配 vertex shader semantics在 HLSL 中。因此,在这种自定义格式中,我们有 POSITION0 和 TEXCOORD0。

IVertexType 的使用是可选的,因为您也可以将 VertexDeclaration 直接传递给(例如)VertexBuffer 构造函数。


如果您想制作一种与我提供的格式不同的顶点格式,那应该是您需要的所有信息。有关更多信息,请访问 blog post by Shawn Hargreaves其中详细介绍了 API。