首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

DirectX 11 遊戲開發實戰:HLSL 著色器、常數緩衝區與光照實現

     編輯:C++ 入門

著色器語言本質

HLSL 本質是面向 GPU 的 C 方言,:POSITION 等語義標記對應硬件寄存器,操作著色器即操作 GPU 寄存器。

效果文件 Cube.fx 核心結構

cbuffer ConstantBuffer : register(b0) {
    float4 lightDirections[4];
    float4 lightColors[4];
    float4 ambientColor;
    float4 diffuseColor;
    // ... 矩陣變換參數
};

struct VS_INPUT { float4 Pos : POSITION; float3 Normal : NORMAL; float2 Tex : TEXCOORD; };
struct PS_INPUT { float4 Pos : SV_POSITION; float3 Normal : NORMAL; float2 Tex : TEXCOORD; };

PS_INPUT VS_Main(VS_INPUT input) { /* 頂點變換 */ }
float4 PS_Main(PS_INPUT input) : SV_TARGET {
    // 光照計算:環境光 + 多方向光漫反射 + 紋理採樣
    float3 color = ambientColor;
    for (int i=0; i<4; ++i)
        color += saturate(dot(lightDirections[i], input.Normal)) * lightColors[i];
    return texDiffuse.Sample(sampLinear, input.Tex) * color;
}

C++ 端常數緩衝區更新

struct CB_NEVER_CHANGES { XMFLOAT4 lightDir[4]; XMFLOAT4 lightColor[4]; };
CB_NEVER_CHANGES cb1;
cb1.lightDir[0] = XMFLOAT4(-0.5f, 0.5f, -0.5f, 0.0f);
// ... 填充其餘數據
context->UpdateSubresource(_constantBuffer, 0, nullptr, &cb1, 0, 0);

一一對應原則:C++ 結構體佈局必須與 HLSL cbuffer 完全一致(對齊、順序、類型)。

專案配置要點

  • VS2012 新建 Win32 空項目 → Property Manager 導入 Microsoft.Cpp.Win32.user 統一屬性表
  • Cube.fx 屬性 → General → Item Type = "Does not participate in build",避免 HLSL 編譯器尋找 main 入口報錯
  • 核心樣板文件(DX11Base.h/cpp, Main.cpp, Helper.h)可復用於新專案

學習建議

  1. 核心三板斧:光照、紋理、座標變換 —— 官方 SDK 文檔講解詳盡
  2. C++ 進階推薦《C++ Primer》,細節極致
  3. 向量/矩陣數學是必修課,好在不難
  4. 最大技巧:善用復制貼上與樣板復用,理解後重組

源碼下載

置頂博客 x01.Lab.Download 提供完整工程源碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved