You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Direct3D中适配自定义像素顶点坐标实现2D渲染?

自定义顶点坐标适配Direct3D渲染的修改方案

默认情况下

Direct3D 假设视口裁剪空间的X范围为-1.0到1.0,Y范围为1.0到-1.0。

我希望进行2D渲染,提供的顶点缓冲区数据需满足像素左上角为整数坐标(即像素中心位于(*.5, *.5))。对于1280x720的视口,希望X范围为0到1280,Y范围为0到720。

Direct3D光栅化规则示意图

当前Hello Triangle示例的顶点坐标如下:

Vertex triangleVertices[] =
{
    { { 0.0f, 0.25f, 0.0f }, color1 },
    { { 0.25f, -0.25f, 0.0f }, color2 },
    { { -0.25f, -0.25f, 0.0f }, color3 }
};

若使用如下自定义顶点坐标,需要进行哪些修改才能得到与示例相同的渲染结果?

Vertex triangleVertices[] =
{
    { { width/2 + 0.00f * width/2, height/2 + 0.25f * height/2, 0.0f }, color1 },
    { { width/2 + 0.25f * width/2, height/2 - 0.25f * height/2, 0.0f }, color2 },
    { { width/2 - 0.25f * width/2, height/2 - 0.25f * height/2, 0.0f }, color3 }
};

Direct3D 9中可通过变换管线实现类似坐标转换,但当前版本的实现逻辑已有变化。


必要修改步骤

  1. 修正顶点坐标的像素对齐偏移
    自定义坐标以像素左上角为整数原点,而Direct3D裁剪空间对应像素中心位置,因此需要给每个顶点的X、Y坐标减去0.5f,将坐标基准从像素左上角切换到像素中心,匹配原示例的光栅化逻辑。修改后的顶点代码如下:

    Vertex triangleVertices[] =
    {
        { { width/2 + 0.00f * width/2 - 0.5f, height/2 + 0.25f * height/2 - 0.5f, 0.0f }, color1 },
        { { width/2 + 0.25f * width/2 - 0.5f, height/2 - 0.25f * height/2 - 0.5f, 0.0f }, color2 },
        { { width/2 - 0.25f * width/2 - 0.5f, height/2 - 0.25f * height/2 - 0.5f, 0.0f }, color3 }
    };
    
  2. 替换为适配窗口空间的正交投影矩阵
    原示例使用默认裁剪空间,自定义坐标是0到width、0到height的窗口空间,需要通过正交投影矩阵将窗口坐标转换为Direct3D要求的裁剪空间。该矩阵需实现:

    • X轴:0 → -1,width → 1
    • Y轴:0 → 1,height → -1(匹配Direct3D的Y轴向下翻转特性)
      行优先格式的投影矩阵示例:
    float projMatrix[] = {
        2.0f / width, 0.0f, 0.0f, 0.0f,
        0.0f, -2.0f / height, 0.0f, 0.0f,
        0.0f, 0.0f, 1.0f, 0.0f,
        -1.0f, 1.0f, 0.0f, 1.0f
    };
    

    将此矩阵设置为顶点着色器的投影参数,替换原示例的默认变换矩阵。

  3. 确认光栅化状态无额外偏移
    检查光栅化阶段的配置(如D3D11_RASTERIZER_DESC),确保DepthBias、SlopeScaledDepthBias均设为0,禁用任何额外的坐标偏移逻辑,避免干扰顶点位置的映射。

内容的提问来源于stack exchange,提问作者Tom Huntington

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 07:30:11