HDRI(Stage2~3)



ここ2日くらい、HDRIの実装を目指してAIにコードを書いてもらっていた。最初は例によってChatGPTに書いてもらってそれでうまくいかないときはGenemiに聞いたりしていた。それでもうまくいかないときは最終手段としてClaudに聞いた。なんで最終手段かというとChatGPTとGenemiはいつでも使えるけどClaludは時間制限なのかコード制限なのかそれともほかの要因なのかわからないけど無料版はここまでです、と言われてしまうのと普段あまり使ったことがないので面倒な気がして今までほとんど使ったことがなかった。でも今日はGenemiに聞いても解決できそうになかったのであえてClaudにコードを見てもらった。デバッグ力はChatGPTはあんまり無くて、Genemiは高かったけど、今回Claudを使ってみたらClaudのほうがデバッグ力が高いと感じた。Genemiはログインしないと画像を見てもらうことができないけどGmailにアカウントを作るのは電話番号がいるのでスマホの充電がないときはめんどくさくてログインする気が起きないので画像を見てもらうことができない。でもClaudは電話番号とかいらないのでログインするのがめんどくさくない。何より画像を見てもらえる上にChatGPTだと3枚が限界だけど今日Claudを使ったら10枚くらい見てもらってもまだいけそうな感じだった。そのうえデバッグ力も合わさって多分Claudが最強かもしれない。ただ今日はここまでです、みたいに言われてしまうのでやはり普段は使わないでおこうと思う。というわけで感想はここまでにしてHDRIの実装の話に戻る。今までコードを書いてなかったけど万一、今のコードが消えた場合を考えてそろそろコードをnoteに貼り付けておこうと思う。
main.cpp
// ============================================================
// main.cpp
// DX11 + glTF Viewer
// Blender-like Orbit Camera
// ============================================================
#define _CRT_SECURE_NO_WARNINGS
#define TINYGLTF_IMPLEMENTATION #define STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION
#include "tiny_gltf.h"
#include <windows.h> #include <d3d11.h> #include <d3dcompiler.h> #include <DirectXMath.h>
#include <vector> #include <string> #include <algorithm> #include <WICTextureLoader.h> #include <DDSTextureLoader.h>
#pragma comment(lib, "d3d11.lib") #pragma comment(lib, "d3dcompiler.lib")
using namespace DirectX;
// ============================================================
// Vertex
// ============================================================
struct Vertex
{
XMFLOAT3 position;
XMFLOAT3 normal;
XMFLOAT2 uv;
XMFLOAT4 tangent; //
};
// ============================================================
// Constant Buffer
// ============================================================
struct ConstantBuffer
{
XMMATRIX world;
XMMATRIX view;
XMMATRIX projection;
XMFLOAT3 cameraPos;
float paddiing;
float metallic;
float roughness;
float padding2[2]; //
};
// ============================================================
// Mesh
// ============================================================
struct Material
{
ID3D11ShaderResourceView* baseColor = nullptr;
ID3D11ShaderResourceView* normal = nullptr;
ID3D11ShaderResourceView* mr = nullptr; // metallic-roughness
ID3D11ShaderResourceView* occlusion = nullptr;
float metallicFactor = 0.0f; //
float roughnessFactor = 1.0f; //
};
struct Mesh
{
ID3D11Buffer* vb = nullptr;
ID3D11Buffer* ib = nullptr;
UINT indexCount = 0;
Material material; //
};
// ============================================================
// Node
// ============================================================
struct Node
{
int mesh = -1;
std::vector<int> children;
XMFLOAT3 translation = { 0,0,0 };
XMFLOAT4 rotation = { 0,0,0,1 };
XMFLOAT3 scale = { 1,1,1 };
XMMATRIX localMatrix = XMMatrixIdentity();
XMMATRIX worldMatrix = XMMatrixIdentity();
};
// ============================================================
// Globals
// ============================================================
HWND g_hWnd = nullptr;
ID3D11Device* g_device = nullptr;
ID3D11DeviceContext* g_context = nullptr;
IDXGISwapChain* g_swapChain = nullptr;
ID3D11RenderTargetView* g_rtv = nullptr;
ID3D11Texture2D* g_depthTexture = nullptr;
ID3D11DepthStencilView* g_dsv = nullptr;
ID3D11RasterizerState* g_rs = nullptr;
ID3D11RasterizerState* g_rsNone = nullptr;
ID3D11VertexShader* g_vs = nullptr;
ID3D11PixelShader* g_ps = nullptr;
ID3D11InputLayout* g_inputLayout = nullptr;
ID3D11Buffer* g_constantBuffer = nullptr;
ID3D11SamplerState* g_samplerBaseColor = nullptr;
ID3D11SamplerState* g_samplerLinear = nullptr;
ID3D11DepthStencilState* g_dsDefault = nullptr; //
ID3D11ShaderResourceView* g_dummyMR = nullptr; //
// ============================================================
// Skybox 用
// ============================================================
ID3D11Buffer* g_skyboxVB = nullptr;
ID3D11Buffer* g_skyboxIB = nullptr;
ID3D11InputLayout* g_skyboxInputLayout = nullptr;
ID3D11VertexShader* g_skyboxVS = nullptr;
ID3D11PixelShader* g_skyboxPS = nullptr;
ID3D11ShaderResourceView* g_skyboxSRV = nullptr;
std::vector<Mesh> g_meshes;
std::vector<Node> g_nodes;
std::vector<int> g_rootNodes;
// ============================================================
// Camera
// ============================================================
float g_yaw = 0.0f;
float g_pitch = 0.3f;
float g_distance = 5.0f;
XMFLOAT3 g_target = { 0.0f, 1.0f, 0.0f };
POINT g_prevMouse{};
bool g_leftDragging = false;
bool g_middleDragging = false;
// ============================================================
// Window Proc
// ============================================================
LRESULT CALLBACK WindowProc(
HWND hWnd,
UINT msg,
WPARAM wp,
LPARAM lp)
{
switch (msg)
{
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
}
// ========================================================
// Left Mouse
// Orbit
// ========================================================
case WM_LBUTTONDOWN:
{
g_leftDragging = true;
GetCursorPos(&g_prevMouse);
SetCapture(hWnd);
return 0;
}
case WM_LBUTTONUP:
{
g_leftDragging = false;
ReleaseCapture();
return 0;
}
// ========================================================
// Middle Mouse
// Pan
// ========================================================
case WM_MBUTTONDOWN:
{
g_middleDragging = true;
GetCursorPos(&g_prevMouse);
SetCapture(hWnd);
return 0;
}
case WM_MBUTTONUP:
{
g_middleDragging = false;
ReleaseCapture();
return 0;
}
// ========================================================
// Mouse Move
// ========================================================
case WM_MOUSEMOVE:
{
// ====================================================
// Orbit
// ====================================================
if (g_leftDragging)
{
POINT cur;
GetCursorPos(&cur);
float dx =
(cur.x - g_prevMouse.x) * 0.005f;
float dy =
(cur.y - g_prevMouse.y) * 0.005f;
g_yaw += dx;
g_pitch += dy;
if (g_pitch > 1.5f)
g_pitch = 1.5f;
if (g_pitch < -1.5f)
g_pitch = -1.5f;
g_prevMouse = cur;
}
// ====================================================
// Pan
// ====================================================
if (g_middleDragging)
{
POINT cur;
GetCursorPos(&cur);
float speed =
g_distance * 0.002f;
float dx =
(cur.x - g_prevMouse.x) * speed;
float dy =
(cur.y - g_prevMouse.y) * speed;
XMVECTOR forward =
XMVector3Normalize(
XMVectorSet(
cosf(g_pitch) * sinf(g_yaw),
sinf(g_pitch),
cosf(g_pitch) * cosf(g_yaw),
0.0f));
XMVECTOR worldUp =
XMVectorSet(0, 1, 0, 0);
XMVECTOR right =
XMVector3Normalize(
XMVector3Cross(
worldUp,
forward));
XMVECTOR up =
XMVector3Normalize(
XMVector3Cross(
forward,
right));
XMVECTOR move =
(-right * dx) + (up * dy);
XMVECTOR target =
XMLoadFloat3(&g_target);
target += move;
XMStoreFloat3(
&g_target,
target);
g_prevMouse = cur;
}
return 0;
}
// ========================================================
// Mouse Wheel
// Zoom
// ========================================================
case WM_MOUSEWHEEL:
{
short delta =
GET_WHEEL_DELTA_WPARAM(wp);
g_distance -= delta * 0.001f;
if (g_distance < 1.0f)
g_distance = 1.0f;
if (g_distance > 100.0f)
g_distance = 100.0f;
return 0;
}
}
return DefWindowProc(
hWnd,
msg,
wp,
lp);
}
// ============================================================
const unsigned char* GetBufferData(
const tinygltf::Model& model,
const tinygltf::Accessor& accessor,
int index)
{
const tinygltf::BufferView& bufferView =
model.bufferViews[accessor.bufferView];
const tinygltf::Buffer& buffer =
model.buffers[bufferView.buffer];
size_t stride =
accessor.ByteStride(bufferView);
if (stride == 0)
{
int componentSize =
tinygltf::GetComponentSizeInBytes(
accessor.componentType);
int componentCount =
tinygltf::GetNumComponentsInType(
accessor.type);
stride =
componentSize * componentCount;
}
return &buffer.data[
bufferView.byteOffset +
accessor.byteOffset +
stride * index];
}
// ============================================================
bool IsColorTexture(const tinygltf::Material& mat, int texIndex)
{
return true; //
}
bool CreateTextureFromImage(
ID3D11Device* device,
const tinygltf::Image& img,
ID3D11ShaderResourceView** outSRV,
bool isSRGB)
{
if (img.image.empty())
return false;
D3D11_TEXTURE2D_DESC desc = {};
desc.Width = img.width;
desc.Height = img.height;
desc.MipLevels = 1;
desc.ArraySize = 1;
if (isSRGB)
{
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
}
else
{
desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
}
desc.SampleDesc.Count = 1;
desc.Usage =
D3D11_USAGE_DEFAULT;
desc.BindFlags =
D3D11_BIND_SHADER_RESOURCE;
D3D11_SUBRESOURCE_DATA initData = {};
initData.pSysMem =
img.image.data();
initData.SysMemPitch =
img.width * 4;
ID3D11Texture2D* tex = nullptr;
if (FAILED(device->CreateTexture2D(
&desc,
&initData,
&tex)))
{
return false;
}
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
srvDesc.Format = desc.Format;
srvDesc.ViewDimension =
D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = 1;
if (FAILED(device->CreateShaderResourceView(
tex,
&srvDesc,
outSRV)))
{
tex->Release();
return false;
}
tex->Release();
return true;
}
// ============================================================
bool LoadShaders()
{
ID3DBlob* vsBlob = nullptr;
ID3DBlob* psBlob = nullptr;
if (FAILED(D3DCompileFromFile(
L"VertexShader.hlsl",
nullptr,
nullptr,
"main",
"vs_5_0",
0,
0,
&vsBlob,
nullptr)))
{
return false;
}
if (FAILED(D3DCompileFromFile(
L"PixelShader.hlsl",
nullptr,
nullptr,
"main",
"ps_5_0",
0,
0,
&psBlob,
nullptr)))
{
return false;
}
g_device->CreateVertexShader(
vsBlob->GetBufferPointer(),
vsBlob->GetBufferSize(),
nullptr,
&g_vs);
g_device->CreatePixelShader(
psBlob->GetBufferPointer(),
psBlob->GetBufferSize(),
nullptr,
&g_ps);
D3D11_INPUT_ELEMENT_DESC layout[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 24, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TANGENT", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 32, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
g_device->CreateInputLayout(
layout,
ARRAYSIZE(layout),
vsBlob->GetBufferPointer(),
vsBlob->GetBufferSize(),
&g_inputLayout);
vsBlob->Release();
psBlob->Release();
return true;
}
// ============================================================
void UpdateNodeWorld(
int nodeIndex,
const XMMATRIX& parent)
{
Node& node = g_nodes[nodeIndex];
node.worldMatrix =
node.localMatrix * parent;
for (int child : node.children)
{
UpdateNodeWorld(
child,
node.worldMatrix);
}
}
void CreateSkybox()
{
struct SkyboxVertex
{
DirectX::XMFLOAT3 position;
};
SkyboxVertex vertices[] =
{
{ DirectX::XMFLOAT3(-1.0f, 1.0f, -1.0f) },
{ DirectX::XMFLOAT3(1.0f, 1.0f, -1.0f) },
{ DirectX::XMFLOAT3(1.0f, -1.0f, -1.0f) },
{ DirectX::XMFLOAT3(-1.0f, -1.0f, -1.0f) },
{ DirectX::XMFLOAT3(-1.0f, 1.0f, 1.0f) },
{ DirectX::XMFLOAT3(1.0f, 1.0f, 1.0f) },
{ DirectX::XMFLOAT3(1.0f, -1.0f, 1.0f) },
{ DirectX::XMFLOAT3(-1.0f, -1.0f, 1.0f) },
};
unsigned int indices[] =
{
0,1,2, 0,2,3,
4,6,5, 4,7,6,
4,5,1, 4,1,0,
3,2,6, 3,6,7,
4,0,3, 4,3,7,
1,5,6, 1,6,2
};
D3D11_BUFFER_DESC vbDesc = {};
vbDesc.ByteWidth = sizeof(vertices);
vbDesc.Usage = D3D11_USAGE_DEFAULT;
vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
D3D11_SUBRESOURCE_DATA vbData = {};
vbData.pSysMem = vertices;
g_device->CreateBuffer(&vbDesc, &vbData, &g_skyboxVB);
D3D11_BUFFER_DESC ibDesc = {};
ibDesc.ByteWidth = sizeof(indices);
ibDesc.Usage = D3D11_USAGE_DEFAULT;
ibDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
D3D11_SUBRESOURCE_DATA ibData = {};
ibData.pSysMem = indices;
g_device->CreateBuffer(&ibDesc, &ibData, &g_skyboxIB);
}
bool LoadSkyboxShaders()
{
ID3DBlob* vsBlob = nullptr;
ID3DBlob* psBlob = nullptr;
if (FAILED(D3DCompileFromFile(L"SkyboxVS.hlsl", nullptr, nullptr, "main", "vs_5_0", 0, 0, &vsBlob, nullptr)))
return false;
if (FAILED(D3DCompileFromFile(L"SkyboxPS.hlsl", nullptr, nullptr, "main", "ps_5_0", 0, 0, &psBlob, nullptr)))
return false;
g_device->CreateVertexShader(vsBlob->GetBufferPointer(), vsBlob->GetBufferSize(), nullptr, &g_skyboxVS);
g_device->CreatePixelShader(psBlob->GetBufferPointer(), psBlob->GetBufferSize(), nullptr, &g_skyboxPS);
D3D11_INPUT_ELEMENT_DESC layout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }
};
g_device->CreateInputLayout(layout, ARRAYSIZE(layout), vsBlob->GetBufferPointer(), vsBlob->GetBufferSize(), &g_skyboxInputLayout);
vsBlob->Release();
psBlob->Release();
return true;
}
void DrawSkybox(const XMMATRIX& view, const XMMATRIX& projection)
{
D3D11_DEPTH_STENCIL_DESC dsDesc = {};
dsDesc.DepthEnable = TRUE;
dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ZERO;
dsDesc.DepthFunc = D3D11_COMPARISON_LESS_EQUAL; //
ID3D11DepthStencilState* dsState = nullptr;
g_device->CreateDepthStencilState(&dsDesc, &dsState);
g_context->OMSetDepthStencilState(dsState, 0);
g_context->RSSetState(g_rsNone);
UINT stride = sizeof(XMFLOAT3);
UINT offset = 0;
g_context->IASetVertexBuffers(0, 1, &g_skyboxVB, &stride, &offset);
g_context->IASetIndexBuffer(g_skyboxIB, DXGI_FORMAT_R32_UINT, 0);
g_context->IASetInputLayout(g_skyboxInputLayout);
g_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
g_context->VSSetShader(g_skyboxVS, nullptr, 0);
g_context->PSSetShader(g_skyboxPS, nullptr, 0);
g_context->PSSetShaderResources(0, 1, &g_skyboxSRV);
g_context->PSSetSamplers(0, 1, &g_samplerLinear);
struct CameraBuffer {
XMMATRIX world;
XMMATRIX view;
XMMATRIX projection;
} cb;
XMMATRIX viewNoTrans = view;
viewNoTrans.r[3] = XMVectorSet(0, 0, 0, 1);
cb.world = XMMatrixIdentity();
cb.view = XMMatrixTranspose(viewNoTrans);
cb.projection = XMMatrixTranspose(projection);
g_context->UpdateSubresource(g_constantBuffer, 0, nullptr, &cb, 0, 0);
g_context->VSSetConstantBuffers(0, 1, &g_constantBuffer);
//
g_context->DrawIndexed(36, 0, 0);
//
g_context->RSSetState(g_rs); //
g_context->OMSetDepthStencilState(nullptr, 0);
dsState->Release();
}
bool LoadSkyboxTexture(const wchar_t* filename)
{
HRESULT hr = DirectX::CreateDDSTextureFromFile(
g_device,
filename,
nullptr,
&g_skyboxSRV
);
return SUCCEEDED(hr);
}
// ============================================================
bool LoadGLTF(const char* path)
{
tinygltf::TinyGLTF loader;
tinygltf::Model model;
std::string err, warn;
std::string ext = path;
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
bool result = false;
if (ext.find(".glb") != std::string::npos)
{
result = loader.LoadBinaryFromFile(&model, &err, &warn, path);
}
else
{
result = loader.LoadASCIIFromFile(&model, &err, &warn, path);
}
if (!result)
return false;
// ========================================================
// Meshes
// ========================================================
for (const auto& mesh : model.meshes)
{
for (const auto& primitive : mesh.primitives)
{
std::vector<Vertex> vertices;
std::vector<unsigned int> indices;
const auto& posAcc =
model.accessors.at(primitive.attributes.at("POSITION"));
const auto& normAcc =
model.accessors.at(primitive.attributes.at("NORMAL"));
const auto& uvAcc =
model.accessors.at(primitive.attributes.at("TEXCOORD_0"));
const auto& idxAcc =
model.accessors.at(primitive.indices);
//
auto itTan = primitive.attributes.find("TANGENT");
bool hasTangent = (itTan != primitive.attributes.end());
const tinygltf::Accessor* tanAcc = nullptr;
if (hasTangent)
{
tanAcc = &model.accessors[itTan->second];
}
for (size_t i = 0; i < posAcc.count; i++)
{
Vertex v{};
const float* pos =
reinterpret_cast<const float*>(
GetBufferData(model, posAcc, (int)i));
const float* norm =
reinterpret_cast<const float*>(
GetBufferData(model, normAcc, (int)i));
if (i < 5)
{
printf("N[%d] = %f %f %f\n", i, norm[0], norm[1], norm[2]);
}
const float* uv =
reinterpret_cast<const float*>(
GetBufferData(model, uvAcc, (int)i));
v.position = { pos[0], pos[1], -pos[2] };
v.normal = { norm[0], norm[1], -norm[2] };
v.uv = { uv[0], uv[1] };
// =========================
// Tangent
// =========================
if (hasTangent && tanAcc)
{
const float* tan =
reinterpret_cast<const float*>(
GetBufferData(model, *tanAcc, (int)i));
v.tangent =
{
tan[0],
tan[1],
-tan[2],
tan[3]
};
}
else
{
v.tangent = { 1, 0, 0, 1 };
}
vertices.push_back(v);
}
// ====================================================
// Indices
// ====================================================
const auto& indexView =
model.bufferViews[idxAcc.bufferView];
const auto& indexBuffer =
model.buffers[indexView.buffer];
const unsigned char* data =
&indexBuffer.data[indexView.byteOffset + idxAcc.byteOffset];
if (idxAcc.componentType == TINYGLTF_COMPONENT_TYPE_UNSIGNED_SHORT)
{
const unsigned short* src =
reinterpret_cast<const unsigned short*>(data);
for (size_t i = 0; i < idxAcc.count; i += 3)
{
indices.push_back(src[i + 0]);
indices.push_back(src[i + 2]);
indices.push_back(src[i + 1]);
}
}
// ====================================================
// Mesh
// ====================================================
Mesh dxMesh;
// VB
D3D11_BUFFER_DESC vbDesc = {};
vbDesc.ByteWidth = UINT(sizeof(Vertex) * vertices.size());
vbDesc.Usage = D3D11_USAGE_DEFAULT;
vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
D3D11_SUBRESOURCE_DATA vbData = {};
vbData.pSysMem = vertices.data();
g_device->CreateBuffer(&vbDesc, &vbData, &dxMesh.vb);
// IB
D3D11_BUFFER_DESC ibDesc = {};
ibDesc.ByteWidth = UINT(sizeof(unsigned int) * indices.size());
ibDesc.Usage = D3D11_USAGE_DEFAULT;
ibDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
D3D11_SUBRESOURCE_DATA ibData = {};
ibData.pSysMem = indices.data();
g_device->CreateBuffer(&ibDesc, &ibData, &dxMesh.ib);
dxMesh.indexCount = (UINT)indices.size();
// ====================================================
// Material
// ====================================================
if (primitive.material >= 0)
{
const tinygltf::Material& mat =
model.materials[primitive.material];
// ---------------------
// BaseColor
// ---------------------
int baseColorIndex =
mat.pbrMetallicRoughness.baseColorTexture.index;
if (baseColorIndex >= 0)
{
const auto& tex = model.textures[baseColorIndex];
const auto& img = model.images[tex.source];
CreateTextureFromImage(
g_device,
img,
&dxMesh.material.baseColor,
true);
}
// ---------------------
// Normal
// ---------------------
int normalIndex = mat.normalTexture.index;
if (normalIndex >= 0)
{
const auto& tex = model.textures[normalIndex];
const auto& img = model.images[tex.source];
CreateTextureFromImage(
g_device,
img,
&dxMesh.material.normal,
false);
}
// ---------------------
// Metallic-Roughness
// ---------------------
int mrIndex =
mat.pbrMetallicRoughness.metallicRoughnessTexture.index;
if (mrIndex >= 0)
{
printf("MR texture found: index %d\n", mrIndex);
const auto& tex = model.textures[mrIndex];
const auto& img = model.images[tex.source];
CreateTextureFromImage(
g_device,
img,
&dxMesh.material.mr,
false);
}
else {
// スカラー値を読む
dxMesh.material.metallicFactor = (float)mat.pbrMetallicRoughness.metallicFactor;
dxMesh.material.roughnessFactor = (float)mat.pbrMetallicRoughness.roughnessFactor;
printf("metallic=%.2f roughness=%.2f\n",
dxMesh.material.metallicFactor,
dxMesh.material.roughnessFactor);
}
}
g_meshes.push_back(dxMesh);
}
}
// ========================================================
// Nodes
// ========================================================
for (const auto& srcNode : model.nodes)
{
Node node;
node.mesh = srcNode.mesh;
node.children = srcNode.children;
if (srcNode.translation.size() == 3)
{
node.translation =
{
(float)srcNode.translation[0],
(float)srcNode.translation[1],
(float)-srcNode.translation[2]
};
}
// ❗ rotation
if (srcNode.rotation.size() == 4)
{
node.rotation =
{
(float)srcNode.rotation[0],
(float)srcNode.rotation[1],
(float)srcNode.rotation[2],
(float)srcNode.rotation[3]
};
}
if (srcNode.scale.size() == 3)
{
node.scale =
{
(float)srcNode.scale[0],
(float)srcNode.scale[1],
(float)srcNode.scale[2]
};
}
XMMATRIX T = XMMatrixTranslation(
node.translation.x,
node.translation.y,
node.translation.z);
XMMATRIX R = XMMatrixRotationQuaternion(
XMLoadFloat4(&node.rotation));
XMMATRIX S = XMMatrixScaling(
node.scale.x,
node.scale.y,
node.scale.z);
node.localMatrix = S * R * T;
g_nodes.push_back(node);
}
const tinygltf::Scene& scene =
model.scenes[model.defaultScene];
for (int rootNode : scene.nodes)
{
g_rootNodes.push_back(rootNode);
UpdateNodeWorld(rootNode, XMMatrixIdentity());
}
return true;
}
// ============================================================
bool InitD3D(HWND hwnd)
{
DXGI_SWAP_CHAIN_DESC scd = {};
scd.BufferCount = 1;
scd.BufferDesc.Width = 1280;
scd.BufferDesc.Height = 720;
scd.BufferDesc.Format =
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB;
scd.BufferUsage =
DXGI_USAGE_RENDER_TARGET_OUTPUT;
scd.OutputWindow = hwnd;
scd.SampleDesc.Count = 1;
scd.Windowed = TRUE;
if (FAILED(D3D11CreateDeviceAndSwapChain(
nullptr,
D3D_DRIVER_TYPE_HARDWARE,
nullptr,
0,
nullptr,
0,
D3D11_SDK_VERSION,
&scd,
&g_swapChain,
&g_device,
nullptr,
&g_context)))
{
return false;
}
ID3D11Texture2D* backBuffer = nullptr;
g_swapChain->GetBuffer(
0,
__uuidof(ID3D11Texture2D),
(void**)&backBuffer);
g_device->CreateRenderTargetView(
backBuffer,
nullptr,
&g_rtv);
backBuffer->Release();
// Depth
D3D11_TEXTURE2D_DESC depthDesc = {};
depthDesc.Width = 1280;
depthDesc.Height = 720;
depthDesc.MipLevels = 1;
depthDesc.ArraySize = 1;
depthDesc.Format =
DXGI_FORMAT_D24_UNORM_S8_UINT;
depthDesc.SampleDesc.Count = 1;
depthDesc.BindFlags =
D3D11_BIND_DEPTH_STENCIL;
g_device->CreateTexture2D(
&depthDesc,
nullptr,
&g_depthTexture);
g_device->CreateDepthStencilView(
g_depthTexture,
nullptr,
&g_dsv);
g_context->OMSetRenderTargets(
1,
&g_rtv,
g_dsv);
// Viewport
D3D11_VIEWPORT vp = {};
vp.Width = 1280.0f;
vp.Height = 720.0f;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
g_context->RSSetViewports(
1,
&vp);
// Rasterizer
D3D11_RASTERIZER_DESC rsDesc = {};
rsDesc.FillMode =
D3D11_FILL_SOLID;
rsDesc.CullMode =
D3D11_CULL_BACK;
rsDesc.DepthClipEnable =
TRUE;
g_device->CreateRasterizerState(
&rsDesc,
&g_rs);
D3D11_RASTERIZER_DESC rsDescNone = {};
rsDescNone.FillMode = D3D11_FILL_SOLID;
rsDescNone.CullMode = D3D11_CULL_NONE;
rsDescNone.DepthClipEnable = TRUE;
g_device->CreateRasterizerState(&rsDescNone, &g_rsNone);
D3D11_DEPTH_STENCIL_DESC dsDesc = {};
dsDesc.DepthEnable = TRUE;
dsDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
dsDesc.DepthFunc = D3D11_COMPARISON_LESS; //
g_device->CreateDepthStencilState(&dsDesc, &g_dsDefault);
g_context->RSSetState(g_rs);
// Sampler
D3D11_SAMPLER_DESC sampDesc = {};
sampDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
g_device->CreateSamplerState(&sampDesc, &g_samplerBaseColor);
// main.cpp 内 InitD3D 関数の中
D3D11_SAMPLER_DESC sampDesc2 = {};
sampDesc2.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
sampDesc2.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc2.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc2.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
sampDesc2.MipLODBias = 0.0f;
sampDesc2.MaxAnisotropy = 1;
sampDesc2.ComparisonFunc = D3D11_COMPARISON_NEVER;
sampDesc2.MinLOD = -D3D11_FLOAT32_MAX; // 非常に小さい値
sampDesc2.MaxLOD = D3D11_FLOAT32_MAX; // 非常に大きい値(重要!)
g_device->CreateSamplerState(&sampDesc2, &g_samplerLinear);
g_device->CreateSamplerState(
&sampDesc2,
&g_samplerLinear);
// ダミーMRテクスチャ作成
ID3D11ShaderResourceView* g_dummyMR = nullptr;
D3D11_TEXTURE2D_DESC dummyDesc = {};
dummyDesc.Width = 1;
dummyDesc.Height = 1;
dummyDesc.MipLevels = 1;
dummyDesc.ArraySize = 1;
dummyDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
dummyDesc.SampleDesc.Count = 1;
dummyDesc.Usage = D3D11_USAGE_DEFAULT;
dummyDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
uint32_t white = 0xFFFFFFFF;
D3D11_SUBRESOURCE_DATA dummyData = {};
dummyData.pSysMem = &white;
dummyData.SysMemPitch = 4;
ID3D11Texture2D* dummyTex = nullptr;
g_device->CreateTexture2D(&dummyDesc, &dummyData, &dummyTex);
g_device->CreateShaderResourceView(dummyTex, nullptr, &g_dummyMR);
dummyTex->Release();
return true;
}
// ============================================================
void CreateConstantBuffer()
{
D3D11_BUFFER_DESC desc = {};
desc.ByteWidth =
sizeof(ConstantBuffer);
desc.Usage =
D3D11_USAGE_DEFAULT;
desc.BindFlags =
D3D11_BIND_CONSTANT_BUFFER;
g_device->CreateBuffer(
&desc,
nullptr,
&g_constantBuffer);
}
// ============================================================
void DrawNode(
int nodeIndex,
const XMMATRIX& view,
const XMMATRIX& projection,
const XMVECTOR& eye)
{
Node& node =
g_nodes[nodeIndex];
if (node.mesh >= 0 &&
node.mesh < (int)g_meshes.size())
{
Mesh& mesh =
g_meshes[node.mesh];
UINT stride =
sizeof(Vertex);
UINT offset = 0;
g_context->IASetVertexBuffers(
0,
1,
&mesh.vb,
&stride,
&offset);
g_context->IASetIndexBuffer(
mesh.ib,
DXGI_FORMAT_R32_UINT,
0);
ConstantBuffer cb;
cb.world =
XMMatrixTranspose(
node.worldMatrix);
cb.view =
XMMatrixTranspose(view);
cb.projection =
XMMatrixTranspose(projection);
XMStoreFloat3(&cb.cameraPos, eye);
cb.metallic = mesh.material.metallicFactor; //
cb.roughness = mesh.material.roughnessFactor; //
XMStoreFloat3(&cb.cameraPos, eye);
g_context->UpdateSubresource(
g_constantBuffer,
0,
nullptr,
&cb,
0,
0);
g_context->VSSetConstantBuffers(
0,
1,
&g_constantBuffer);
//
ID3D11ShaderResourceView* nullSRV[3] = { nullptr, nullptr, nullptr };
g_context->PSSetShaderResources(0, 3, nullSRV);
//
ID3D11ShaderResourceView* srvs[3] =
{
mesh.material.baseColor,
mesh.material.normal,
mesh.material.mr ? mesh.material.mr : g_dummyMR
};
g_context->PSSetShaderResources(
0,
3,
srvs
);
g_context->PSSetSamplers(0, 1, &g_samplerBaseColor);
g_context->PSSetSamplers(1, 1, &g_samplerLinear);
g_context->DrawIndexed(
mesh.indexCount,
0,
0);
}
for (int child : node.children)
{
DrawNode(
child,
view,
projection,
eye);
}
}
// ============================================================
void Render()
{
float clearColor[4] = { 0.05f, 0.05f, 0.1f, 1.0f };
g_context->ClearRenderTargetView(g_rtv, clearColor);
g_context->ClearDepthStencilView(g_dsv, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
XMVECTOR target = XMLoadFloat3(&g_target);
XMVECTOR baseDir = XMVectorSet(0, 0, -1, 0);
XMMATRIX rot = XMMatrixRotationRollPitchYaw(g_pitch, g_yaw, 0.0f);
XMVECTOR rotatedDir = XMVector3TransformNormal(baseDir, rot);
XMVECTOR eye = target + rotatedDir * g_distance;
XMMATRIX view = XMMatrixLookAtLH(eye, target, XMVectorSet(0, 1, 0, 0));
XMMATRIX projection = XMMatrixPerspectiveFovLH(XMConvertToRadians(45.0f), 1280.0f / 720.0f, 0.1f, 1000.0f);
DrawSkybox(view, projection);
g_context->PSSetShaderResources(3, 1, &g_skyboxSRV);
g_context->IASetInputLayout(g_inputLayout);
g_context->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
g_context->VSSetShader(g_vs, nullptr, 0);
g_context->PSSetShader(g_ps, nullptr, 0);
g_context->OMSetDepthStencilState(g_dsDefault, 0);
g_context->RSSetState(g_rs);
for (int root : g_rootNodes)
{
DrawNode(root, view, projection, eye);
}
g_swapChain->Present(1, 0);
}
// ============================================================
int WINAPI WinMain(
HINSTANCE hInstance,
HINSTANCE,
LPSTR,
int)
{
AllocConsole();
FILE* fp;
freopen_s(&fp, "CONOUT$", "w", stdout);
WNDCLASS wc = {};
wc.lpfnWndProc =
WindowProc;
wc.hInstance =
hInstance;
wc.lpszClassName =
L"DX11Window";
RegisterClass(&wc);
g_hWnd = CreateWindowEx(
0,
L"DX11Window",
L"DX11 glTF Viewer",
WS_OVERLAPPEDWINDOW,
100,
100,
1280,
720,
nullptr,
nullptr,
hInstance,
nullptr);
ShowWindow(
g_hWnd,
SW_SHOW);
if (!InitD3D(g_hWnd))
return -1;
if (!LoadShaders())
return -1;
CreateConstantBuffer();
CreateSkybox();
if (!LoadSkyboxShaders())
return -1;
if (!LoadSkyboxTexture(L"skybox.dds"))
return -1;
ID3D11Resource* res = nullptr;
g_skyboxSRV->GetResource(&res);
ID3D11Texture2D* tex = nullptr;
res->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&tex);
D3D11_TEXTURE2D_DESC desc;
tex->GetDesc(&desc);
printf("mipLevels = %d\n", desc.MipLevels);
tex->Release();
res->Release();
if (!LoadGLTF("model.glb"))
return -1;
MSG msg = {};
while (msg.message != WM_QUIT)
{
if (PeekMessage(
&msg,
nullptr,
0,
0,
PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
Render();
}
}
return 0;
}VertexShader.hlsl
cbuffer ConstantBuffer : register(b0)
{
matrix world;
matrix view;
matrix projection;
};
struct VS_INPUT
{
float3 position : POSITION;
float3 normal : NORMAL;
float2 uv : TEXCOORD;
float4 tangent : TANGENT; //
};
struct PS_INPUT
{
float4 position : SV_POSITION;
float3 normal : NORMAL;
float2 uv : TEXCOORD;
float3 worldPos : TEXCOORD1;
float4 tangent : TANGENT; //
};
PS_INPUT main(VS_INPUT input)
{
PS_INPUT output;
float4 worldPos =
mul(float4(input.position, 1.0f), world);
float4 viewPos =
mul(worldPos, view);
output.position =
mul(viewPos, projection);
output.worldPos =
worldPos.xyz;
output.normal =
normalize(mul(input.normal, (float3x3) world));
float3 T =
normalize(mul(input.tangent.xyz, (float3x3) world));
output.tangent =
float4(T, input.tangent.w);
output.uv =
input.uv;
return output;
}PixelShader.hlsl
// ============================================================
// PixelShader.hlsl (Normal Mapなし対応版)
// ============================================================
Texture2D baseColorTex : register(t0);
Texture2D mrTex : register(t2);
TextureCube envMap : register(t3);
SamplerState sampBaseColor : register(s0);
SamplerState sampLinear : register(s1);
cbuffer ConstantBuffer : register(b0)
{
matrix world;
matrix view;
matrix projection;
float3 cameraPos;
float padding;
float metallicFactor;
float roughnessFactor;
float2 padding2;
};
struct PS_INPUT
{
float4 position : SV_POSITION;
float3 normal : NORMAL;
float2 uv : TEXCOORD;
float3 worldPos : TEXCOORD1;
float4 tangent : TANGENT;
};
float4 main(PS_INPUT input) : SV_TARGET
{
// ------------------------
// ベースカラー(albedo)
// ------------------------
float3 albedo = baseColorTex.Sample(sampBaseColor, input.uv).rgb;
// ------------------------
// Metallic / Roughness
// ------------------------
float4 mrSample = mrTex.Sample(sampLinear, input.uv);
float roughness = mrSample.g * roughnessFactor;
float metallic = mrSample.b * metallicFactor;
// ------------------------
// カメラと反射方向
// ------------------------
float3 N = normalize(input.normal);
float3 V = normalize(cameraPos - input.worldPos);
float3 R = reflect(-V, N);
// ------------------------
// 環境光の強さ
// ------------------------
float envScaleDiffuse = 0.01;
float envScaleSpecular = 0.01;
// ------------------------
// ディフューズ
// ------------------------
// ディフューズのベースを環境光のみにする
float3 diffuse = float3(0.0, 0.0, 0.0); // albedo の固定分を削除
float3 irradiance = envMap.SampleLevel(sampLinear, N, 8.0).rgb;
diffuse += irradiance * envScaleDiffuse * (1.0 - metallic);
// ------------------------
// スペキュラー
// ------------------------
float mip = roughness * 8.0;
float3 envSpec = envMap.SampleLevel(sampLinear, R, mip).rgb;
float3 F0 = lerp(float3(0.028, 0.028, 0.028), albedo, metallic);
float3 specular = envSpec * F0 * envScaleSpecular * roughness;
// ------------------------
// ディレクショナルライト
// ------------------------
float3 lightDir = normalize(float3(-0.3, 0.5, 2.0)); // Z をプラスに
float3 lightColor = float3(1.0, 0.95, 0.8); // 太陽光の色
float lightIntensity = 3.0;
float NdotL = saturate(dot(N, lightDir));
float3 directLight = albedo * lightColor * NdotL * lightIntensity;
// ------------------------
// アンビエント(暗部の底上げ)
// ------------------------
float3 ambient = albedo * 0.15;
// ------------------------
// 合成
// ------------------------
float3 color = ambient + directLight + diffuse + specular;
color = color / (color + 1.0);
return float4(color, 1.0);
//return float4(N * 0.5 + 0.5, 1.0); // 法線を色として表示
}SkyboxVS.hlsl
// SkyboxVS.hlsl
cbuffer ConstantBuffer : register(b0)
{
matrix dummyWorld; // メイン側と構造を合わせるためのダミー
matrix view;
matrix projection;
};
struct VS_INPUT
{
float3 position : POSITION;
};
struct PS_INPUT
{
float4 position : SV_POSITION;
float3 texcoord : TEXCOORD0;
};
PS_INPUT main(VS_INPUT input)
{
PS_INPUT output;
float4 pos = float4(input.position, 1.0f);
// ビュー行列から平行移動を除去
pos = mul(pos, view);
output.position = mul(pos, projection);
output.texcoord = input.position;
return output;
}SkyboxPS.hlsl
TextureCube skyboxTex : register(t0);
SamplerState sampLinear : register(s0);
struct PS_INPUT
{
float4 position : SV_POSITION;
float3 texcoord : TEXCOORD0;
};
float4 main(PS_INPUT input) : SV_TARGET
{
return skyboxTex.Sample(sampLinear, input.texcoord);
}という感じでかなり長いコード(1500行)なので写経する気が起こらないから何も理解せずにこのまま進んでいこうと思う。次はフォルダ構成。
フォルダ構成


使うフォルダはこのVisual Studio -> Project1 -> Project1フォルダだけでこのフォルダにはmain.cpp, VertexShader.hlsl, といったコード群とblenderでエクスポートしたglTFファイル(.glb)とか、tinygltf のファイルとか、.ddsファイルとかが入っている。要するにこのフォルダしか使わない。実行ファイルが入っているフォルダはVisual Studio -> Project1 -> Project1, ではなくVisual Studio -> Project1 -> X64 -> Debug, フォルダにある。でもここは使わないので関係ない。つまりVisual Studio -> Project1 -> Project1、以外使わないからほかのフォルダは無視してもいい。


という感じでフォルダ構成を説明したので次はblenderで作ったモデルを.glTF(.glb)でエクスポートするやり方を説明する。







これで .glb ファイルができた。次はglTFをロードするためにtiny_gltfというローダーをダウンロードする。
tiny_gltf
GitHubのtiny_gltfのページに飛んで緑色の「code」というボタンをクリックして「Download Zip」を選ぶとダウンロードできる。ダウンロードしたら解凍する。


という感じで .glbファイルと tiny_gltf の作業が終わったのであとは.ddsファイルを作ればいいだけになった。なので次は .ddsファイルの作り方について説明する。
Poly Haven
まず Poly Haven というサイトから .hdr ファイルをダウンロードする。画像は何でもいいけど今回はこれにした。
Poly Haven

1K, 2K, 4K, 8K, 16k, 32K, などがあったり、また HDR のほかに EXR というのがあるけど EXR のほうが高画質らしいけどゲームは HDR で十分らしいので 4K, HDR, を選択してダウンロードする。4K以外でもいいと思うけどよくわからないのでとりあえず今回は4Kにする。
HDRI to CubeMap
次にこのサイトに飛んで先ほど入手した .hdrファイルを変換する。変換しないと次に使うNVIDIA Texture Tools Exporter というソフトが Cube Map として認識してくれないので このサイトで変換する。


次は NVIDIA Texture Tools Exporter を ダウンロードする。ブラウザでNVIDIA Texture Tools Exporter と検索して出てきたサイトからダウンロードする。
NVIDIA Texture Tools Exporter

NVIDIA Texture Tools Exporter のサイトに飛んだらDownload というボタンがあるのでクリックする。そうするとメールアドレスを求められるので適当なメールアドレスを入力した後アカウント作成画面になるので適当に入力する。そうするとダウンロードできる。ダウンロードしたらインストールする。インストールが終わったら起動する。そうするとこんな画面になる。



変換が終わったら.ddsファイルをVisual Studioのプロジェクトフォルダに入れる。

.dds ファイルの変換が終わったらプロジェクトフォルダに入れて完了。これですべてのファイルが集まったので次はVisual Studio でコードを書く。なのでVisual Studio を起動する。起動したら新しいプロジェクトの作成を選んで検索バーにC++と入力してからからのプロジェクトを選ぶ。次へを押したらこんな画面になる。









ピクセルシェーダーはシェーダーモデルをピクセルシェーダーにする。


次に画面右にあるソリューションエクスプローラーの中にあるProject5の上にマウスカーソルを乗せて右クリック->プロパティ->構成プロパティ->リンカー->システム->サブシステムをデフォルトのコンソールからWindowsに変える。


そのほうがいいのでここは$(ProjectDir)のままでいい。
リンカー->システム->サブシステムをWindowsに変えたらまたProject5の上にマウスカーソルを乗せて右クリック->Nugetパッケージの管理を選ぶ。


これですべての設定が終わった。ただVisual Studio 2026 はこれで終了だけどVisual Studio 2022を使う場合はコードをデフォルトではシフトJISで保存してあるのでそれをUTF-8(署名なし)で保存しなおす。画面右側にあるソリューションエクスプローラーの中にあるVertexShader.hlslをクリックして画面左上のファイル->名前を付けてVertexShader.hlslを保存を選択する。


これでVisual Studio 2022の設定のほうも終わったのでコードをコピペする作業をする。この記事にあるmain.cpp, VertexShader.hlsl, PixelShader.hlsl, SkyboxVS.hlsl, SkyboxPS.hlsl の5つのコードをそれぞれ貼り付ける。
if (!LoadGLTF("model.glb"))
return -1;あとglbファイルの名前はコード中でmodel.glbとして探しているのでもし違う名前(model1.glbみたいな)がついていたらmodel.glbに改名する必要がある。
if (!LoadSkyboxTexture(L"skybox.dds"))
return -1;同様にddsファイルもskybox.ddsとして探しているので名前をskybox.ddsに改名する必要がある。




実行したらちゃんと表示された。ただお尻のあたりに白飛びがあるのでコードとしてはまだ修正の余地がある。とにかくこれでHDRIの実装ができたのでStage2はクリアしたから次はStage3に進むことができるようになった。