Table of Contents

绘制顶点

高级 程序员

加载场景时,Stride 会通过实体系统自动处理显示场景所需的绘制调用。本页介绍手动绘制。

图元

Stride 提供以下内置图元:

  • Plane(平面)
  • Cube(立方体)
  • Sphere(球体)
  • Geosphere(几何球体)
  • Cylinder(圆柱体)
  • Torus(圆环)
  • Teapot(茶壶)

它们不会随 @'Stride.Graphics.GraphicsDevice' 一起自动创建,因此你必须实例化它们。你可以通过 @'Stride.Graphics.GeometricPrimitives.GeometricPrimitive' 类来完成。

**代码:**创建并使用图元

// 创建
var myCube = GeometricPrimitive.Cube.New(GraphicsDevice);
var myTorus = GeometricPrimitive.Torus.New(GraphicsDevice);
 
// ...
 
// 在屏幕上绘制一个
myCube.Draw(CommandList, EffectInstance);

它们没有关联的效果,因此用户在绘制时必须提供 @'Stride.Rendering.EffectInstance'。有关加载效果的信息,请参阅效果与着色器。

自定义绘制

除了内置图元之外,任何几何体都可以通过创建自定义顶点缓冲区来绘制。要创建顶点缓冲区,首先需要定义一个 @'Stride.Graphics.VertexDeclaration'。顶点声明描述每个顶点的元素及其布局。 详情请参阅 @'Stride.Graphics.VertexElement' 参考页。

接下来,可以从顶点数组创建顶点缓冲区。顶点的数据类型必须与 @'Stride.Graphics.VertexDeclaration' 匹配。

有了顶点缓冲区和声明后,就可以创建 @'Stride.Graphics.VertexBufferBinding'。

**代码:**创建顶点缓冲区

// 创建包含位置和纹理坐标的顶点布局
var layout = new VertexDeclaration(VertexElement.Position<Vector3>(), VertexElement.TextureCoordinate<Vector2>()); 
 
// 从顶点数组创建顶点缓冲区
var vertices = new VertexPositionTexture[vertexCount];
var vertexBuffer = Buffer.Vertex.New(GraphicsDevice, vertices);
 
// 创建顶点缓冲区绑定
var vertexBufferBinding = new VertexBufferBinding(vertexBuffer, layout, vertexCount);

要绘制新创建的顶点缓冲区,必须先将其绑定到管线。顶点布局和要绘制的 @'Stride.Graphics.PrimitiveType' 必须包含在管线状态对象中。缓冲区本身可以动态设置。

之后,顶点就可以通过 @'Stride.Graphics.CommandList.Draw(System.Int32,System.Int32)' 渲染了。

**代码:**绑定并绘制顶点缓冲区

// 设置管线状态
pipelineStateDescription.InputElements = vertexBufferBinding.Layout.CreateInputElements();
pipelineStateDescription.PrimitiveType = PrimitiveType.TriangleStrip;
 
// 创建并设置 PipelineState 对象
// ...

// 将顶点缓冲区绑定到管线
commandList.SetVertexBuffers(0, vertexBuffer, 0, vertexBufferBinding.Stride);
 
// 绘制顶点
commandList.Draw(vertexCount);

也可以绘制索引化的几何体。要使用索引缓冲区,首先像顶点缓冲区一样创建它并绑定到管线。 然后可以使用 @'Stride.Graphics.CommandList.DrawIndexed(System.Int32,System.Int32,System.Int32)' 进行绘制。

**代码:**绘制索引顶点

// 创建索引缓冲区
var indices = new short[indexCount];
var is32Bits = false;
var indexBuffer = Buffer.Index.New(GraphicsDevice, indices);
 
// 设置 VAO
commandList.SetIndexBuffer(indexBuffer, 0, is32Bits);

// 绘制索引顶点
commandList.DrawIndexed(indexBuffer.ElementCount);