Compare commits

..
9 Commits
Author SHA1 Message Date
david 97192e1587 Add input layout
Add matrix buffer
Convert camera to D3D11
2026-11-27 16:08:22 +01:00
david 85d8830b84 Changed D3D api to D3D11
Changed mesh to D3D11
Changed material to D3D11 (WIP)
2026-11-23 15:57:28 +01:00
david 024a283898 Add D3D11 project 2026-11-23 13:32:53 +01:00
david abf85aa6f7 Add material definition 2026-11-23 13:32:41 +01:00
david 7ef5efa341 Add texture loading
Add uv mapping
Add lighting
2026-11-20 16:05:33 +01:00
david 439871d63f Add transformations
Add input
Add time
Add vertex colors
2026-11-16 15:56:44 +01:00
david 948c5e067e Add Vertex
Add triangle & quad examples
2026-11-09 15:50:23 +01:00
david 4f91b8081d Add D3D 2026-11-09 15:50:06 +01:00
david 6fb23f7099 Fix ShowMessage 2026-11-09 15:49:51 +01:00
46 changed files with 3042 additions and 12 deletions
+31
View File
@@ -0,0 +1,31 @@
#include "Camera.h"
UINT Camera::init(UINT width, UINT height)
{
// view matrix
XMVECTOR position = XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f);
XMVECTOR forward = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
XMMATRIX lookTo = XMMatrixLookToLH(position, forward, up);
XMStoreFloat4x4(&_viewMatrix, lookTo);
// projection matrix
float fov = XMConvertToRadians(60.0f);
float aspectRatio = static_cast<float>(width) / static_cast<float>(height);
float nearClippingPlane = 0.3f;
float farClippingPlane = 100.0f;
XMMATRIX perspective = XMMatrixPerspectiveFovLH(fov, aspectRatio, nearClippingPlane, farClippingPlane);
XMStoreFloat4x4(&_projectionMatrix, perspective);
return 0;
}
void Camera::update(FLOAT dt)
{
}
void Camera::deInit()
{
}
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include <DirectXMath.h>
#include <Windows.h>
using namespace DirectX;
class Camera
{
public:
UINT init(UINT width, UINT height);
void update(FLOAT dt);
void deInit();
const XMFLOAT4X4& getViewMatrix() const { return _viewMatrix; }
const XMFLOAT4X4& getProjectionMatrix() const { return _projectionMatrix; }
private:
XMFLOAT4X4 _viewMatrix = {};
XMFLOAT4X4 _projectionMatrix = {};
};
+225
View File
@@ -0,0 +1,225 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|ARM64">
<Configuration>Debug</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|ARM64">
<Configuration>Release</Configuration>
<Platform>ARM64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{E0259873-82A0-4B75-9F14-B153FCFBC827}</ProjectGuid>
<RootNamespace>D3D9</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_WINDOWS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="Camera.cpp" />
<ClCompile Include="Direct3D.cpp" />
<ClCompile Include="Light.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="Material.cpp" />
<ClCompile Include="Mesh.cpp" />
<ClCompile Include="Time.cpp" />
<ClCompile Include="Utilities.cpp" />
<ClCompile Include="WICTextureLoader9.cpp" />
<ClCompile Include="Window.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="Camera.h" />
<ClInclude Include="Direct3D.h" />
<ClInclude Include="Light.h" />
<ClInclude Include="Material.h" />
<ClInclude Include="Mesh.h" />
<ClInclude Include="Time.h" />
<ClInclude Include="Utilities.h" />
<ClInclude Include="Vertex.h" />
<ClInclude Include="WICTextureLoader9.h" />
<ClInclude Include="Window.h" />
</ItemGroup>
<ItemGroup>
<FxCompile Include="PixelShader.hlsl">
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Pixel</ShaderType>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">%(Filename).cso</ObjectFileOutput>
</FxCompile>
<FxCompile Include="VertexShader.hlsl">
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Vertex</ShaderType>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">%(Filename).cso</ObjectFileOutput>
</FxCompile>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
+89
View File
@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="Camera.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Direct3D.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Light.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="main.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Material.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Mesh.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Time.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Utilities.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="Window.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="WICTextureLoader9.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Camera.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Direct3D.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Light.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Material.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Mesh.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Time.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Utilities.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Window.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Vertex.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="WICTextureLoader9.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<FxCompile Include="VertexShader.hlsl">
<Filter>Resource Files</Filter>
</FxCompile>
<FxCompile Include="PixelShader.hlsl">
<Filter>Resource Files</Filter>
</FxCompile>
</ItemGroup>
</Project>
+102
View File
@@ -0,0 +1,102 @@
#include "Direct3D.h"
#include "Utilities.h"
INT Direct3D::init(HWND hWnd, UINT width, UINT height, BOOL isFullscreen)
{
HRESULT hr = {};
// 1. define presentation parameters
DXGI_SWAP_CHAIN_DESC swapChainDesc = {};
swapChainDesc.OutputWindow = hWnd; // target window
swapChainDesc.Windowed = !isFullscreen; // window mode yes or no
swapChainDesc.BufferCount = 1;
swapChainDesc.BufferDesc.Width = width;
swapChainDesc.BufferDesc.Height = height;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // how to use/access the back buffer
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
swapChainDesc.SampleDesc.Count = 1; // at least set to one
// 2. create Direct3D device, device context & swap chain
D3D_FEATURE_LEVEL supportedFeatureLevels[] =
{
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
};
D3D_FEATURE_LEVEL chosenFeatureLevel = {};
hr = D3D11CreateDeviceAndSwapChain(
nullptr, // graphic card adapter
D3D_DRIVER_TYPE_HARDWARE, // hardware or software rendering
nullptr, // software rendering module
0, // optional flags
supportedFeatureLevels, std::size(supportedFeatureLevels), // supported D3D api versions
D3D11_SDK_VERSION,
&swapChainDesc, &_pDXGISwapChain, &_pD3DDevice, &chosenFeatureLevel, &_pD3DDeviceContext
);
CheckFailed(hr, 200);
// 3. create render target view
ID3D11Texture2D* pBackBuffer = nullptr;
hr = _pDXGISwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
CheckFailed(hr, 220);
hr = _pD3DDevice->CreateRenderTargetView(pBackBuffer, nullptr, &_pRenderTargetView);
CheckFailed(hr, 225);
safeRelease(pBackBuffer);
// 4. create rasterizer state
//d3d.getDevice()->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
//d3d.getDevice()->SetRenderState(D3DRS_LIGHTING, TRUE);
//d3d.getDevice()->SetRenderState(D3DRS_SPECULARENABLE, TRUE);
//d3d.getDevice()->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL);
//d3d.getDevice()->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL);
//d3d.getDevice()->SetRenderState(D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_MATERIAL);
//d3d.getDevice()->SetRenderState(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL);
// 5. create depth stencil view & state
// 6. define view port
D3D11_VIEWPORT viewPort = {};
viewPort.Width = width;
viewPort.Height = height;
viewPort.MinDepth = 0.0f;
viewPort.MaxDepth = 1.0f;
// 7. setup render pipeline
_pD3DDeviceContext->RSSetViewports(1, &viewPort);
_pD3DDeviceContext->OMSetRenderTargets(1, &_pRenderTargetView, nullptr);
return 0;
}
void Direct3D::beginScene()
{
// clear buffers
FLOAT backgroundColor[] = { 0.0f, 0.0f, 0.0f, 1.0f };
_pD3DDeviceContext->ClearRenderTargetView(_pRenderTargetView, backgroundColor);
}
void Direct3D::endScene()
{
// present frame
_pDXGISwapChain->Present(
0, // 0 -> vsync deactivated, 1,2,3,4 -> vsync activated with x frames
0 // optional flags
);
}
void Direct3D::deInit()
{
safeRelease(_pDepthStencilState);
safeRelease(_pDepthStencilView);
safeRelease(_pRasterizerState);
safeRelease(_pRenderTargetView);
safeRelease(_pDXGISwapChain);
safeRelease(_pD3DDeviceContext);
safeRelease(_pD3DDevice);
}
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include <d3d11.h>
#pragma comment(lib, "d3d11.lib")
class Direct3D
{
public:
INT init(HWND hWnd, UINT width, UINT height, BOOL isFullscreen);
void beginScene();
void endScene();
void deInit();
ID3D11Device* getDevice() const { return _pD3DDevice; }
ID3D11DeviceContext* getDeviceContext() const { return _pD3DDeviceContext; }
private:
ID3D11Device* _pD3DDevice = nullptr; // create other api objects, e.g. buffer
ID3D11DeviceContext* _pD3DDeviceContext = nullptr; // customize render pipeline, e.g. set buffer or make draw calls
IDXGISwapChain* _pDXGISwapChain = nullptr; // holds references to front and back buffer and swap them
ID3D11RenderTargetView* _pRenderTargetView = nullptr; // back buffer
ID3D11RasterizerState* _pRasterizerState = nullptr; // customize rasterizer stage
ID3D11DepthStencilView* _pDepthStencilView = nullptr; // depth & stencil buffer
ID3D11DepthStencilState* _pDepthStencilState = nullptr; // customize depth stencil buffering
};
+22
View File
@@ -0,0 +1,22 @@
#include "Light.h"
UINT Light::init(D3DLIGHT9& lightData)
{
_lightData = lightData;
return 0;
}
void Light::update(FLOAT dt)
{
}
void Light::render(IDirect3DDevice9* pD3DDevice)
{
pD3DDevice->SetLight(0, &_lightData);
pD3DDevice->LightEnable(0, TRUE);
}
void Light::deInit()
{
}
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include <d3d9.h>
class Light
{
public:
UINT init(D3DLIGHT9& lightData);
void update(FLOAT dt);
void render(IDirect3DDevice9* pD3DDevice);
void deInit();
private:
D3DLIGHT9 _lightData = {};
};
+191
View File
@@ -0,0 +1,191 @@
#include "Material.h"
#include "Utilities.h"
//#include "WICTextureLoader9.h"
UINT Material::init(ID3D11Device* pD3DDevice, LPCTSTR textureFileName)
{
//HRESULT hr = DirectX::CreateWICTextureFromFile(pD3DDevice, textureFileName, &_pTexture, 0, DirectX::WIC_LOADER_MIP_AUTOGEN);
//CheckFailed(hr, 600);
UINT error = 0;
error = createVertexShader(pD3DDevice);
CheckError(error);
error = createPixelShader(pD3DDevice);
CheckError(error);
error = createMatrixBuffer(pD3DDevice);
CheckError(error);
return 0;
}
void Material::render(ID3D11DeviceContext* pD3DDeviceContext)
{
//// set texture
//pD3DDevice->SetTexture(0, _pTexture);
//// set sampler state
//pD3DDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_BORDER);
//pD3DDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_BORDER);
//pD3DDevice->SetSamplerState(0, D3DSAMP_BORDERCOLOR, D3DCOLOR_XRGB(100, 0, 100));
//pD3DDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
//pD3DDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
//pD3DDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
//pD3DDevice->SetSamplerState(0, D3DSAMP_MAXMIPLEVEL, 0);
//// set material
//D3DMATERIAL9 material = {};
//material.Ambient = { 1.0f, 1.0f, 1.0f, 1.0f };
//material.Diffuse = { 1.0f, 1.0f, 1.0f, 1.0f };
//material.Specular = { 1.0f, 1.0f, 1.0f, 1.0f };
//material.Power = 100.0f;
//material.Emissive = { 1.0f, 0.0f, 0.0f, 1.0f };
//pD3DDevice->SetMaterial(&material);
// set shader
pD3DDeviceContext->VSSetShader(_pVertexShader, nullptr, 0);
pD3DDeviceContext->PSSetShader(_pPixelShader, nullptr, 0);
// set input layout
pD3DDeviceContext->IASetInputLayout(_pInputLayout);
// set matrix buffer
pD3DDeviceContext->VSSetConstantBuffers(0, 1, &_pMatrixBuffer);
}
void Material::deInit()
{
safeRelease(_pInputLayout);
safeRelease(_pPixelShader);
safeRelease(_pVertexShader);
}
UINT Material::setMatrices(ID3D11DeviceContext* pD3DDeviceContext,
const XMFLOAT4X4& worldMatrix, const XMFLOAT4X4& viewMatrix, const XMFLOAT4X4& projectionMatrix)
{
// 1. load matrix data
XMMATRIX w = XMLoadFloat4x4(&worldMatrix);
XMMATRIX v = XMLoadFloat4x4(&viewMatrix);
XMMATRIX p = XMLoadFloat4x4(&projectionMatrix);
// 2. map matrix buffer
D3D11_MAPPED_SUBRESOURCE data = {};
HRESULT hr = pD3DDeviceContext->Map(_pMatrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &data);
CheckFailed(hr, 665);
// 3. set data
MatrixBuffer* pMatrixBuffer = static_cast<MatrixBuffer*>(data.pData);
XMStoreFloat4x4(&pMatrixBuffer->WorldViewProjectionMatrix, XMMatrixTranspose(w * v * p));
// 4. unmap matrix buffer
pD3DDeviceContext->Unmap(_pMatrixBuffer, 0);
return 0;
}
UINT Material::createVertexShader(ID3D11Device* pD3DDevice)
{
HRESULT hr = {};
ID3DBlob* pCompiledShaderCode = nullptr;
// two options to get compiled shader code
// option 1: compile at runtime
//hr = D3DCompileFromFile(
// L"VertexShader.hlsl", // shader filename
// nullptr, nullptr, // shared shader code
// "main", // shader entry function
// "vs_4_0", // shader type & model (version)
// 0, 0, // optional flags
// &pCompiledShaderCode,
// nullptr // optional blob for compiler error messages
//);
// option 2: load compiled code from file
hr = D3DReadFileToBlob(L"VertexShader.cso", &pCompiledShaderCode);
CheckFailed(hr, 600);
hr = pD3DDevice->CreateVertexShader(
pCompiledShaderCode->GetBufferPointer(), pCompiledShaderCode->GetBufferSize(), // compiled shader code
nullptr, // shared code code
&_pVertexShader
);
CheckFailed(hr, 605);
UINT error = createInputLayout(pD3DDevice, pCompiledShaderCode);
CheckError(error);
safeRelease(pCompiledShaderCode);
return 0;
}
UINT Material::createPixelShader(ID3D11Device* pD3DDevice)
{
HRESULT hr = {};
ID3DBlob* pCompiledShaderCode = nullptr;
hr = D3DReadFileToBlob(L"PixelShader.cso", &pCompiledShaderCode);
CheckFailed(hr, 620);
hr = pD3DDevice->CreatePixelShader(
pCompiledShaderCode->GetBufferPointer(), pCompiledShaderCode->GetBufferSize(), // compiled shader code
nullptr, // shared code code
&_pPixelShader
);
CheckFailed(hr, 625);
return 0;
}
UINT Material::createInputLayout(ID3D11Device* pD3DDevice, ID3DBlob* pCompiledVertexShader)
{
// https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-semantics
D3D11_INPUT_ELEMENT_DESC inputs[4] = {};
// position
inputs[0].SemanticName = "POSITION";
inputs[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
// normal
inputs[1].SemanticName = "NORMAL";
inputs[1].Format = DXGI_FORMAT_R32G32B32_FLOAT;
inputs[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
// uv
inputs[2].SemanticName = "TEXCOORD";
inputs[2].Format = DXGI_FORMAT_R32G32_FLOAT;
inputs[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
// color
inputs[3].SemanticName = "COLOR";
inputs[3].Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
inputs[3].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
HRESULT hr = pD3DDevice->CreateInputLayout(
inputs, std::size(inputs), // array of element descriptions & size of array
pCompiledVertexShader->GetBufferPointer(), pCompiledVertexShader->GetBufferSize(), // check vertex compatability with vertex shader
&_pInputLayout
);
CheckFailed(hr, 640);
return 0;
}
UINT Material::createMatrixBuffer(ID3D11Device* pD3DDevice)
{
D3D11_BUFFER_DESC desc = {};
desc.ByteWidth = sizeof(MatrixBuffer);
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
desc.Usage = D3D11_USAGE_DYNAMIC;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; // has to be set if D3D11_USAGE_DYNAMIC or D3D11_USAGE_STAGING is used
HRESULT hr = pD3DDevice->CreateBuffer(&desc, nullptr, &_pMatrixBuffer);
CheckFailed(hr, 660);
return 0;
}
+39
View File
@@ -0,0 +1,39 @@
#pragma once
#include <d3d11.h>
#include <d3dcompiler.h>
#include <DirectXMath.h>
#pragma comment(lib, "d3dcompiler.lib")
using namespace DirectX;
class Material
{
public:
UINT init(ID3D11Device* pD3DDevice, LPCTSTR textureFileName);
void render(ID3D11DeviceContext* pD3DDeviceContext);
void deInit();
UINT setMatrices(ID3D11DeviceContext* pD3DDeviceContext,
const XMFLOAT4X4& worldMatrix, const XMFLOAT4X4& viewMatrix, const XMFLOAT4X4& projectionMatrix);
private:
UINT createVertexShader(ID3D11Device* pD3DDevice);
UINT createPixelShader(ID3D11Device* pD3DDevice);
UINT createInputLayout(ID3D11Device* pD3DDevice, ID3DBlob* pCompiledVertexShader);
UINT createMatrixBuffer(ID3D11Device* pD3DDevice);
ID3D11VertexShader* _pVertexShader = nullptr;
ID3D11PixelShader* _pPixelShader = nullptr;
ID3D11InputLayout* _pInputLayout = nullptr;
//IDirect3DTexture9* _pTexture = nullptr;
struct MatrixBuffer
{
XMFLOAT4X4 WorldViewProjectionMatrix;
};
ID3D11Buffer* _pMatrixBuffer = nullptr;
};
+121
View File
@@ -0,0 +1,121 @@
#include "Mesh.h"
#include "Utilities.h"
#include "Vertex.h"
UINT Mesh::init(ID3D11Device* pD3DDevice)
{
UINT error = 0;
error = createVertexBuffer(pD3DDevice);
CheckError(error);
error = createIndexBuffer(pD3DDevice);
CheckError(error);
XMStoreFloat4x4(&_worldMatrix, XMMatrixIdentity());
return 0;
}
void Mesh::update(FLOAT dt)
{
static float x = 0.0f;
static float y = 0.0f;
static float z = 0.0f;
static float rotY = 0.0f;
static float rotZ = 0.0f;
rotY += 0.5f * dt;
rotZ += 0.0f * dt;
float move = 1.0f * dt;
if (GetAsyncKeyState(VK_LEFT) & 0x8000) x -= move;
if (GetAsyncKeyState(VK_RIGHT) & 0x8000) x += move;
if (GetAsyncKeyState(VK_DOWN) & 0x8000) y -= move;
if (GetAsyncKeyState(VK_UP) & 0x8000) y += move;
if ((GetAsyncKeyState(VK_SUBTRACT) & 0x8000) || (GetAsyncKeyState('Q') & 0x8000)) z -= move;
if ((GetAsyncKeyState(VK_ADD) & 0x8000) || (GetAsyncKeyState('E') & 0x8000)) z += move;
XMMATRIX translation = XMMatrixTranslation(x, y, z);
XMMATRIX rotation = XMMatrixRotationRollPitchYaw(0.0f, rotY, rotZ);
XMMATRIX scale = XMMatrixScaling(1.0f, 1.0f, 1.0f);
XMStoreFloat4x4(&_worldMatrix, scale * rotation * translation);
}
void Mesh::render(ID3D11DeviceContext* pD3DDeviceContext)
{
// setup pipeline
UINT offset = 0;
pD3DDeviceContext->IASetVertexBuffers(
0, // which vertex buffer should be set (Startslot)
1, &_pVertexBuffer, // buffers to set
&_vertexStride, // vertex size for each buffer
&offset // offset for each buffer
);
pD3DDeviceContext->IASetIndexBuffer(_pIndexBuffer, DXGI_FORMAT_R16_UINT, 0);
pD3DDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// draw call
pD3DDeviceContext->DrawIndexed(_indexCount, 0, 0);
}
void Mesh::deInit()
{
safeRelease(_pIndexBuffer);
safeRelease(_pVertexBuffer);
}
UINT Mesh::createVertexBuffer(ID3D11Device* pD3DDevice)
{
// define values
Vertex vertices[] =
{
Vertex(-0.5f, 0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f),
Vertex(0.5f, 0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f),
Vertex(0.5f, -0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f),
Vertex(-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f),
};
_vertexCount = std::size(vertices);
_vertexStride = sizeof(Vertex);
// describe & create vertex buffer
D3D11_BUFFER_DESC desc = {};
desc.ByteWidth = _vertexCount * _vertexStride; // total size of content
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; // buffer type
desc.Usage = D3D11_USAGE_IMMUTABLE; // https://learn.microsoft.com/en-us/windows/win32/api/d3d11/ne-d3d11-d3d11_usage
D3D11_SUBRESOURCE_DATA data = {};
data.pSysMem = vertices;
HRESULT hr = pD3DDevice->CreateBuffer(&desc, &data, &_pVertexBuffer);
CheckFailed(hr, 300);
return 0;
}
UINT Mesh::createIndexBuffer(ID3D11Device* pD3DDevice)
{
unsigned short indices[] =
{
0, 1, 2,
0, 2, 3
};
_indexCount = std::size(indices);
D3D11_BUFFER_DESC desc = {};
desc.ByteWidth = _indexCount * sizeof(unsigned short); // total size of content
desc.BindFlags = D3D11_BIND_INDEX_BUFFER; // buffer type
desc.Usage = D3D11_USAGE_IMMUTABLE; // https://learn.microsoft.com/en-us/windows/win32/api/d3d11/ne-d3d11-d3d11_usage
D3D11_SUBRESOURCE_DATA data = {};
data.pSysMem = indices;
HRESULT hr = pD3DDevice->CreateBuffer(&desc, &data, &_pIndexBuffer);
CheckFailed(hr, 320);
return 0;
}
+30
View File
@@ -0,0 +1,30 @@
#pragma once
#include <d3d11.h>
#include <DirectXMath.h>
using namespace DirectX;
class Mesh
{
public:
UINT init(ID3D11Device* pD3DDevice);
void update(FLOAT dt);
void render(ID3D11DeviceContext* pD3DDeviceContext);
void deInit();
const XMFLOAT4X4& getWorldMatrix() const { return _worldMatrix; }
private:
UINT createVertexBuffer(ID3D11Device* pD3DDevice);
UINT createIndexBuffer(ID3D11Device* pD3DDevice);
ID3D11Buffer* _pVertexBuffer = nullptr; // dumps mesh vertices
ID3D11Buffer* _pIndexBuffer = nullptr; // dumps mesh indices
UINT _vertexCount = 0; // amount of vertices
UINT _vertexStride = 0; // size of one vertex in bytes
UINT _indexCount = 0; // amount of indices
XMFLOAT4X4 _worldMatrix = {};
};
Binary file not shown.
+4
View File
@@ -0,0 +1,4 @@
float4 main() : SV_TARGET
{
return float4(1.0f, .0f, 1.0f, 1.0f);
}
+28
View File
@@ -0,0 +1,28 @@
#include "Time.h"
#include <string>
UINT Time::init()
{
_lastFrame = CLOCK::now();
return 0;
}
void Time::update()
{
TIMEPOINT now = CLOCK::now();
SECONDS diff = now - _lastFrame;
_deltaTime = diff.count();
_lastFrame = now;
#if _DEBUG && UNICODE
wstring output = L"fps: " + to_wstring(1.0f / _deltaTime) + L"\n";
OutputDebugString(output.c_str());
#endif // _DEBUG && UNICODE
}
void Time::deInit()
{
}
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include <Windows.h>
#include <chrono>
using namespace std;
typedef chrono::steady_clock CLOCK;
typedef chrono::duration<FLOAT> SECONDS;
typedef CLOCK::time_point TIMEPOINT;
class Time
{
public:
UINT init();
void update();
void deInit();
FLOAT getDeltaTime() const { return _deltaTime; }
private:
FLOAT _deltaTime = 0.0f;
TIMEPOINT _lastFrame = {};
};
+16
View File
@@ -0,0 +1,16 @@
#include "Utilities.h"
void ShowError(UINT error)
{
#if _DEBUG
LPCTSTR msg = TEXT("Application quit with an error: ");
#if UNICODE
std::wstring str = std::wstring(msg) + std::to_wstring(error);
msg = str.c_str();
#else // UNICODE
std::string str = std::string(msg) + std::to_string(error);
msg = str.c_str();
#endif // UNICODE
MessageBox(nullptr, msg, TEXT("Error"), MB_OK);
#endif // DEBUG
}
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#include <Windows.h>
#include <string>
void ShowError(UINT error);
#define CheckError(x) if (x != 0) \
{ \
ShowError(x); \
return x; \
}
#define CheckFailed(hr, x) if (FAILED(hr)) \
{ \
ShowError(x); \
return x; \
}
template<typename T>
void safeRelease(T*& obj)
{
if (obj != nullptr)
{
obj->Release();
obj = nullptr;
}
}
+24
View File
@@ -0,0 +1,24 @@
#pragma once
#include <DirectXMath.h>
using namespace DirectX;
struct Vertex
{
XMFLOAT3 position;
XMFLOAT3 normal;
XMFLOAT2 uv;
XMFLOAT4 color;
Vertex() : position(0.0f, 0.0f, 0.0f), color(1.0f, 1.0f, 1.0f, 1.0f), uv(0.0f, 0.0f), normal(0.0f, 0.0f, 0.0f) {}
Vertex(float x, float y, float z) : position(x, y, z), color(1.0f, 1.0f, 1.0f, 1.0f), uv(0.0f, 0.0f), normal(0.0f, 0.0f, 0.0f) {}
Vertex(float x, float y, float z, UINT r, UINT g, UINT b) :
position(x, y, z), color(1.0f, 1.0f, 1.0f, 1.0f), uv(0.0f, 0.0f), normal(0.0f, 0.0f, 0.0f) {}
Vertex(float x, float y, float z, float u, float v) :
position(x, y, z), color(1.0f, 1.0f, 1.0f, 1.0f), uv(u, v), normal(0.0f, 0.0f, 0.0f) {}
Vertex(float x, float y, float z, float nx, float ny, float nz, float u, float v) :
position(x, y, z), color(1.0f, 1.0f, 1.0f, 1.0f), uv(u, v), normal(nx, ny, nz) {}
};
Binary file not shown.
+9
View File
@@ -0,0 +1,9 @@
cbuffer MatrixBuffer
{
float4x4 WorldViewProjectionMatrix;
};
float4 main( float4 pos : POSITION ) : SV_POSITION
{
return mul(pos, WorldViewProjectionMatrix);
}
+637
View File
@@ -0,0 +1,637 @@
//--------------------------------------------------------------------------------------
// File: WICTextureLoader9.cpp
//
// Function for loading a WIC image and creating a Direct3D runtime texture for it
//
// Note: Assumes application has already called CoInitializeEx
//
// Note these functions are useful for images created as simple 2D textures. For
// more complex resources, DDSTextureLoader is an excellent light-weight runtime loader.
// For a full-featured DDS file reader, writer, and texture processing pipeline see
// the 'Texconv' sample and the 'DirectXTex' library.
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// https://go.microsoft.com/fwlink/?LinkId=248926
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
// We could load multi-frame images (TIFF/GIF) into a texture array.
// For now, we just load the first frame (note: DirectXTex supports multi-frame images)
#include "WICTextureLoader9.h"
#include <d3d9types.h>
#include <algorithm>
#include <cassert>
#include <cfloat>
#include <cmath>
#include <cstring>
#include <iterator>
#include <memory>
#include <wincodec.h>
#include <wrl/client.h>
#ifdef _MSC_VER
// Off by default warnings
#pragma warning(disable : 4619 4616 4061 4623 4626 5027)
// C4619/4616 #pragma warning warnings
// C4061 enumerator 'x' in switch of enum 'y' is not explicitly handled by a case label
// C4623 default constructor was implicitly defined as deleted
// C4626 assignment operator was implicitly defined as deleted
// C5027 move assignment operator was implicitly defined as deleted
#endif
#ifdef __clang__
#pragma clang diagnostic ignored "-Wcovered-switch-default"
#pragma clang diagnostic ignored "-Wswitch-enum"
#endif
using namespace DirectX;
using Microsoft::WRL::ComPtr;
namespace
{
//-------------------------------------------------------------------------------------
// WIC Pixel Format Translation Data
//-------------------------------------------------------------------------------------
struct WICTranslate
{
const GUID& wic;
D3DFORMAT format;
constexpr WICTranslate(const GUID& wg, D3DFORMAT fmt) noexcept
: wic(wg),
format(fmt)
{
}
};
constexpr WICTranslate g_WICFormats[] = {
// clang-format off
{ GUID_WICPixelFormat128bppRGBAFloat, D3DFMT_A32B32G32R32F },
{ GUID_WICPixelFormat64bppRGBAHalf, D3DFMT_A16B16G16R16F },
{ GUID_WICPixelFormat64bppRGBA, D3DFMT_A16B16G16R16 },
{ GUID_WICPixelFormat32bppBGRA, D3DFMT_A8R8G8B8 },
{ GUID_WICPixelFormat32bppRGBA1010102, D3DFMT_A2B10G10R10 },
{ GUID_WICPixelFormat16bppBGRA5551, D3DFMT_A1R5G5B5 },
{ GUID_WICPixelFormat16bppBGR555, D3DFMT_X1R5G5B5 },
{ GUID_WICPixelFormat16bppBGR565, D3DFMT_R5G6B5 },
{ GUID_WICPixelFormat32bppGrayFloat, D3DFMT_R32F },
{ GUID_WICPixelFormat16bppGrayHalf, D3DFMT_R16F },
{ GUID_WICPixelFormat16bppGray, D3DFMT_L16 },
{ GUID_WICPixelFormat8bppGray, D3DFMT_L8 },
{ GUID_WICPixelFormat8bppAlpha, D3DFMT_A8 },
// clang-format on
};
//-------------------------------------------------------------------------------------
// WIC Pixel Format nearest conversion table
//-------------------------------------------------------------------------------------
struct WICConvert
{
const GUID& source;
const GUID& target;
constexpr WICConvert(const GUID& src, const GUID& tgt) noexcept
: source(src),
target(tgt)
{
}
};
constexpr WICConvert g_WICConvert[] = {
// clang-format off
// Note target GUID in this conversion table must be one of those directly supported formats (above).
{ GUID_WICPixelFormatBlackWhite, GUID_WICPixelFormat8bppGray }, // D3DFMT_L8
{ GUID_WICPixelFormat1bppIndexed, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat2bppIndexed, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat4bppIndexed, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat8bppIndexed, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat2bppGray, GUID_WICPixelFormat8bppGray }, // D3DFMT_L8
{ GUID_WICPixelFormat4bppGray, GUID_WICPixelFormat8bppGray }, // D3DFMT_L8
{ GUID_WICPixelFormat16bppGrayFixedPoint, GUID_WICPixelFormat16bppGrayHalf }, // D3DFMT_R16F
{ GUID_WICPixelFormat32bppGrayFixedPoint, GUID_WICPixelFormat32bppGrayFloat }, // D3DFMT_R32F
{ GUID_WICPixelFormat32bppBGR101010, GUID_WICPixelFormat32bppRGBA1010102 }, // D3DFMT_A2B10G10R10
{ GUID_WICPixelFormat24bppBGR, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat24bppRGB, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat32bppBGR, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat32bppRGBA, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat32bppPBGRA, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat32bppPRGBA, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat48bppRGB, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat48bppBGR, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat64bppBGRA, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat64bppPRGBA, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat64bppPBGRA, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat48bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat48bppBGRFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat64bppRGBAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat64bppBGRAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat64bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat64bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat48bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat128bppPRGBAFloat, GUID_WICPixelFormat128bppRGBAFloat }, // D3DFMT_A32B32G32R32F
{ GUID_WICPixelFormat128bppRGBFloat, GUID_WICPixelFormat128bppRGBAFloat }, // D3DFMT_A32B32G32R32F
{ GUID_WICPixelFormat128bppRGBAFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // D3DFMT_A32B32G32R32F
{ GUID_WICPixelFormat128bppRGBFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // D3DFMT_A32B32G32R32F
{ GUID_WICPixelFormat32bppRGBE, GUID_WICPixelFormat128bppRGBAFloat }, // D3DFMT_A32B32G32R32F
{ GUID_WICPixelFormat32bppCMYK, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat64bppCMYK, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat40bppCMYKAlpha, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat80bppCMYKAlpha, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat32bppRGB, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat64bppRGB, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat64bppPRGBAHalf, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat96bppRGBFloat, GUID_WICPixelFormat128bppRGBAFloat }, // D3DFMT_A32B32G32R32F
// We don't support n-channel formats
// clang-format on
};
//--------------------------------------------------------------------------------------
BOOL WINAPI InitializeWICFactory(PINIT_ONCE, PVOID, PVOID* ifactory) noexcept
{
HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory2, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory2), ifactory);
if (SUCCEEDED(hr))
{
// WIC2 is available on Windows 10, Windows 8.x, and Windows 7 SP1 with KB 2670838 installed
return TRUE;
}
else
{
hr = CoCreateInstance(CLSID_WICImagingFactory1, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory), ifactory);
return SUCCEEDED(hr) ? TRUE : FALSE;
}
}
IWICImagingFactory* GetWIC() noexcept
{
static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT;
IWICImagingFactory* factory = nullptr;
if (!InitOnceExecuteOnce(&s_initOnce, InitializeWICFactory, nullptr, reinterpret_cast<LPVOID*>(&factory)))
{
return nullptr;
}
return factory;
}
//---------------------------------------------------------------------------------
D3DFORMAT WICToD3D9(const GUID& guid) noexcept
{
for (size_t i = 0; i < std::size(g_WICFormats); ++i)
{
if (memcmp(&g_WICFormats[i].wic, &guid, sizeof(GUID)) == 0)
return g_WICFormats[i].format;
}
return D3DFMT_UNKNOWN;
}
//---------------------------------------------------------------------------------
void FitPowerOf2(UINT origx, UINT origy, UINT& targetx, UINT& targety, size_t maxsize)
{
const float origAR = float(origx) / float(origy);
if (origx > origy)
{
size_t x;
for (x = maxsize; x > 1; x >>= 1)
{
if (x <= targetx)
break;
}
targetx = UINT(x);
float bestScore = FLT_MAX;
for (size_t y = maxsize; y > 0; y >>= 1)
{
const float score = fabsf((float(x) / float(y)) - origAR);
if (score < bestScore)
{
bestScore = score;
targety = UINT(y);
}
}
}
else
{
size_t y;
for (y = maxsize; y > 1; y >>= 1)
{
if (y <= targety)
break;
}
targety = UINT(y);
float bestScore = FLT_MAX;
for (size_t x = maxsize; x > 0; x >>= 1)
{
const float score = fabsf((float(x) / float(y)) - origAR);
if (score < bestScore)
{
bestScore = score;
targetx = UINT(x);
}
}
}
}
//---------------------------------------------------------------------------------
HRESULT CreateTextureFromWIC(_In_ LPDIRECT3DDEVICE9 device,
_In_ IWICBitmapFrameDecode* frame,
_In_ size_t maxsize,
_In_ DWORD usage,
_In_ D3DPOOL pool,
_In_ WIC_LOADER_FLAGS loadFlags,
_Outptr_ LPDIRECT3DTEXTURE9* texture) noexcept
{
UINT width, height;
HRESULT hr = frame->GetSize(&width, &height);
if (FAILED(hr))
return hr;
if (maxsize > UINT32_MAX)
return E_INVALIDARG;
assert(width > 0 && height > 0);
if (!maxsize)
{
maxsize = 4096u /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/;
}
assert(maxsize > 0);
UINT twidth = width;
UINT theight = height;
if (loadFlags & WIC_LOADER_FIT_POW2)
{
FitPowerOf2(width, height, twidth, theight, maxsize);
}
else if (width > maxsize || height > maxsize)
{
const float ar = static_cast<float>(height) / static_cast<float>(width);
if (width > height)
{
twidth = static_cast<UINT>(maxsize);
theight = std::max<UINT>(1, static_cast<UINT>(static_cast<float>(maxsize) * ar));
}
else
{
theight = static_cast<UINT>(maxsize);
twidth = std::max<UINT>(1, static_cast<UINT>(static_cast<float>(maxsize) / ar));
}
assert(twidth <= maxsize && theight <= maxsize);
}
if (loadFlags & WIC_LOADER_MAKE_SQUARE)
{
twidth = std::max<UINT>(twidth, theight);
theight = twidth;
}
// Determine format
WICPixelFormatGUID pixelFormat;
hr = frame->GetPixelFormat(&pixelFormat);
if (FAILED(hr))
return hr;
WICPixelFormatGUID convertGUID;
memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &pixelFormat, sizeof(GUID));
D3DFORMAT format = WICToD3D9(pixelFormat);
if (format == D3DFMT_UNKNOWN)
{
for (size_t i = 0; i < std::size(g_WICConvert); ++i)
{
if (memcmp(&g_WICConvert[i].source, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0)
{
memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &g_WICConvert[i].target, sizeof(GUID));
format = WICToD3D9(g_WICConvert[i].target);
assert(format != D3DFMT_UNKNOWN);
break;
}
}
if (format == D3DFMT_UNKNOWN)
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
}
if (loadFlags & WIC_LOADER_FORCE_RGBA32)
{
memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &GUID_WICPixelFormat32bppBGRA, sizeof(GUID));
format = D3DFMT_A8R8G8B8;
}
// Create texture
if (loadFlags & WIC_LOADER_MIP_AUTOGEN)
usage |= D3DUSAGE_AUTOGENMIPMAP;
ComPtr<IDirect3DTexture9> pTexture;
hr = device->CreateTexture(twidth, theight, 1u, usage, format, pool, pTexture.GetAddressOf(), nullptr);
if (FAILED(hr))
return hr;
// Create staging texture memory
ComPtr<IDirect3DTexture9> pStagingTexture;
if (pool == D3DPOOL_DEFAULT)
{
hr = device->CreateTexture(twidth, theight, 1u, 0u, format, D3DPOOL_SYSTEMMEM, pStagingTexture.GetAddressOf(), nullptr);
if (FAILED(hr))
return hr;
}
else
{
pStagingTexture = pTexture;
}
D3DLOCKED_RECT LockedRect = {};
hr = pStagingTexture->LockRect(0, &LockedRect, nullptr, 0);
if (FAILED(hr))
return hr;
const uint64_t numBytes = uint64_t(LockedRect.Pitch) * uint64_t(theight);
pStagingTexture->UnlockRect(0);
if (numBytes > UINT32_MAX)
{
return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW);
}
// Load image data
if (memcmp(&convertGUID, &pixelFormat, sizeof(GUID)) == 0 && twidth == width && theight == height)
{
// No format conversion or resize needed
hr = pStagingTexture->LockRect(0, &LockedRect, nullptr, 0);
if (FAILED(hr))
return hr;
hr = frame->CopyPixels(nullptr,
static_cast<UINT>(LockedRect.Pitch),
static_cast<UINT>(numBytes),
static_cast<BYTE*>(LockedRect.pBits));
pStagingTexture->UnlockRect(0);
if (FAILED(hr))
return hr;
}
else if (twidth != width || theight != height)
{
// Resize
auto pWIC = GetWIC();
if (!pWIC)
return E_NOINTERFACE;
ComPtr<IWICBitmapScaler> scaler;
hr = pWIC->CreateBitmapScaler(scaler.GetAddressOf());
if (FAILED(hr))
return hr;
hr = scaler->Initialize(frame, twidth, theight, WICBitmapInterpolationModeFant);
if (FAILED(hr))
return hr;
WICPixelFormatGUID pfScaler;
hr = scaler->GetPixelFormat(&pfScaler);
if (FAILED(hr))
return hr;
if (memcmp(&convertGUID, &pfScaler, sizeof(GUID)) == 0)
{
// No format conversion needed
hr = pStagingTexture->LockRect(0, &LockedRect, nullptr, 0);
if (FAILED(hr))
return hr;
hr = scaler->CopyPixels(nullptr,
static_cast<UINT>(LockedRect.Pitch),
static_cast<UINT>(numBytes),
static_cast<BYTE*>(LockedRect.pBits));
pStagingTexture->UnlockRect(0);
if (FAILED(hr))
return hr;
}
else
{
ComPtr<IWICFormatConverter> FC;
hr = pWIC->CreateFormatConverter(FC.GetAddressOf());
if (FAILED(hr))
return hr;
BOOL canConvert = FALSE;
hr = FC->CanConvert(pfScaler, convertGUID, &canConvert);
if (FAILED(hr) || !canConvert)
{
return E_UNEXPECTED;
}
hr = FC->Initialize(scaler.Get(),
convertGUID,
WICBitmapDitherTypeErrorDiffusion,
nullptr,
0,
WICBitmapPaletteTypeMedianCut);
if (FAILED(hr))
return hr;
hr = pStagingTexture->LockRect(0, &LockedRect, nullptr, 0);
if (FAILED(hr))
return hr;
hr = FC->CopyPixels(nullptr,
static_cast<UINT>(LockedRect.Pitch),
static_cast<UINT>(numBytes),
static_cast<BYTE*>(LockedRect.pBits));
pStagingTexture->UnlockRect(0);
if (FAILED(hr))
return hr;
}
}
else
{
// Format conversion but no resize
auto pWIC = GetWIC();
if (!pWIC)
return E_NOINTERFACE;
ComPtr<IWICFormatConverter> FC;
hr = pWIC->CreateFormatConverter(FC.GetAddressOf());
if (FAILED(hr))
return hr;
BOOL canConvert = FALSE;
hr = FC->CanConvert(pixelFormat, convertGUID, &canConvert);
if (FAILED(hr) || !canConvert)
{
return E_UNEXPECTED;
}
hr = FC->Initialize(frame, convertGUID, WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeMedianCut);
if (FAILED(hr))
return hr;
hr = pStagingTexture->LockRect(0, &LockedRect, nullptr, 0);
if (FAILED(hr))
return hr;
hr = FC->CopyPixels(nullptr,
static_cast<UINT>(LockedRect.Pitch),
static_cast<UINT>(numBytes),
static_cast<BYTE*>(LockedRect.pBits));
pStagingTexture->UnlockRect(0);
if (FAILED(hr))
return hr;
}
if (pool == D3DPOOL_DEFAULT)
{
hr = device->UpdateTexture(pStagingTexture.Get(), pTexture.Get());
if (FAILED(hr))
return hr;
}
*texture = pTexture.Detach();
return S_OK;
}
} // anonymous namespace
//--------------------------------------------------------------------------------------
_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromMemory(LPDIRECT3DDEVICE9 d3dDevice,
const uint8_t* wicData,
size_t wicDataSize,
LPDIRECT3DTEXTURE9* texture,
size_t maxsize,
WIC_LOADER_FLAGS loadFlags) noexcept
{
return CreateWICTextureFromMemoryEx(d3dDevice, wicData, wicDataSize, maxsize, 0u, D3DPOOL_DEFAULT, loadFlags, texture);
}
_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromMemoryEx(LPDIRECT3DDEVICE9 d3dDevice,
const uint8_t* wicData,
size_t wicDataSize,
_In_ size_t maxsize,
_In_ DWORD usage,
_In_ D3DPOOL pool,
_In_ WIC_LOADER_FLAGS loadFlags,
LPDIRECT3DTEXTURE9* texture) noexcept
{
if (texture)
{
*texture = nullptr;
}
if (!d3dDevice || !wicData || !wicDataSize || !texture)
return E_INVALIDARG;
if (!wicDataSize)
return E_FAIL;
if (wicDataSize > UINT32_MAX)
return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE);
auto pWIC = GetWIC();
if (!pWIC)
return E_NOINTERFACE;
// Create input stream for memory
ComPtr<IWICStream> stream;
HRESULT hr = pWIC->CreateStream(stream.GetAddressOf());
if (FAILED(hr))
return hr;
hr = stream->InitializeFromMemory(const_cast<uint8_t*>(wicData), static_cast<DWORD>(wicDataSize));
if (FAILED(hr))
return hr;
// Initialize WIC
ComPtr<IWICBitmapDecoder> decoder;
hr = pWIC->CreateDecoderFromStream(stream.Get(), nullptr, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf());
if (FAILED(hr))
return hr;
ComPtr<IWICBitmapFrameDecode> frame;
hr = decoder->GetFrame(0, frame.GetAddressOf());
if (FAILED(hr))
return hr;
return CreateTextureFromWIC(d3dDevice, frame.Get(), maxsize, usage, pool, loadFlags, texture);
}
//--------------------------------------------------------------------------------------
_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromFile(LPDIRECT3DDEVICE9 d3dDevice,
const wchar_t* fileName,
LPDIRECT3DTEXTURE9* texture,
size_t maxsize,
WIC_LOADER_FLAGS loadFlags) noexcept
{
return CreateWICTextureFromFileEx(d3dDevice, fileName, maxsize, 0u, D3DPOOL_DEFAULT, loadFlags, texture);
}
_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromFileEx(LPDIRECT3DDEVICE9 d3dDevice,
const wchar_t* fileName,
size_t maxsize,
DWORD usage,
D3DPOOL pool,
WIC_LOADER_FLAGS loadFlags,
LPDIRECT3DTEXTURE9* texture) noexcept
{
if (texture)
{
*texture = nullptr;
}
if (!d3dDevice || !fileName || !texture)
return E_INVALIDARG;
auto pWIC = GetWIC();
if (!pWIC)
return E_NOINTERFACE;
// Initialize WIC
ComPtr<IWICBitmapDecoder> decoder;
HRESULT hr = pWIC->CreateDecoderFromFilename(fileName, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf());
if (FAILED(hr))
return hr;
ComPtr<IWICBitmapFrameDecode> frame;
hr = decoder->GetFrame(0, frame.GetAddressOf());
if (FAILED(hr))
return hr;
return CreateTextureFromWIC(d3dDevice, frame.Get(), maxsize, usage, pool, loadFlags, texture);
}
+89
View File
@@ -0,0 +1,89 @@
//--------------------------------------------------------------------------------------
// File: WICTextureLoader9.h
//
// Function for loading a WIC image and creating a Direct3D runtime texture for it
// (auto-generating mipmaps if possible)
//
// Note: Assumes application has already called CoInitializeEx
//
// Note these functions are useful for images created as simple 2D textures. For
// more complex resources, DDSTextureLoader is an excellent light-weight runtime loader.
// For a full-featured DDS file reader, writer, and texture processing pipeline see
// the 'Texconv' sample and the 'DirectXTex' library.
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// https://go.microsoft.com/fwlink/?LinkId=248926
//--------------------------------------------------------------------------------------
#pragma once
#ifndef DIRECT3D_VERSION
#define DIRECT3D_VERSION 0x900
#endif
#include <d3d9.h>
#pragma comment(lib, "windowscodecs.lib")
#include <cstddef>
#include <cstdint>
namespace DirectX
{
#ifndef WIC_LOADER_FLAGS_DEFINED
#define WIC_LOADER_FLAGS_DEFINED
enum WIC_LOADER_FLAGS : uint32_t
{
WIC_LOADER_DEFAULT = 0,
WIC_LOADER_MIP_AUTOGEN = 0x8,
WIC_LOADER_FIT_POW2 = 0x20,
WIC_LOADER_MAKE_SQUARE = 0x40,
WIC_LOADER_FORCE_RGBA32 = 0x80,
};
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-dynamic-exception-spec"
#pragma clang diagnostic ignored "-Wextra-semi-stmt"
#endif
DEFINE_ENUM_FLAG_OPERATORS(WIC_LOADER_FLAGS);
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif
// Standard version
HRESULT CreateWICTextureFromMemory(_In_ LPDIRECT3DDEVICE9 d3dDevice,
_In_reads_bytes_(wicDataSize) const uint8_t* wicData,
_In_ size_t wicDataSize,
_Outptr_ LPDIRECT3DTEXTURE9* texture,
_In_ size_t maxsize = 0,
_In_ WIC_LOADER_FLAGS loadFlags = WIC_LOADER_DEFAULT) noexcept;
HRESULT CreateWICTextureFromFile(_In_ LPDIRECT3DDEVICE9 d3dDevice,
_In_z_ const wchar_t* fileName,
_Outptr_ LPDIRECT3DTEXTURE9* texture,
_In_ size_t maxsize = 0,
_In_ WIC_LOADER_FLAGS loadFlags = WIC_LOADER_DEFAULT) noexcept;
// Extended version
HRESULT CreateWICTextureFromMemoryEx(_In_ LPDIRECT3DDEVICE9 d3dDevice,
_In_reads_bytes_(wicDataSize) const uint8_t* wicData,
_In_ size_t wicDataSize,
_In_ size_t maxsize,
_In_ DWORD usage,
_In_ D3DPOOL pool,
_In_ WIC_LOADER_FLAGS loadFlags,
_Outptr_ LPDIRECT3DTEXTURE9* texture) noexcept;
HRESULT CreateWICTextureFromFileEx(_In_ LPDIRECT3DDEVICE9 d3dDevice,
_In_z_ const wchar_t* fileName,
_In_ size_t maxsize,
_In_ DWORD usage,
_In_ D3DPOOL pool,
_In_ WIC_LOADER_FLAGS loadFlags,
_Outptr_ LPDIRECT3DTEXTURE9* texture) noexcept;
} // namespace DirectX
+89
View File
@@ -0,0 +1,89 @@
#include "Window.h"
INT Window::init(HINSTANCE hInstance, UINT width, UINT height)
{
// 1. describe window class
WNDCLASS wc = {};
wc.hInstance = hInstance;
wc.lpszClassName = TEXT("D3D11"); // class name
wc.lpfnWndProc = WindowProc; // callback function for windows to communicate with our application
wc.hbrBackground = CreateSolidBrush(RGB(0, 255, 0));
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
wc.hIcon = LoadIcon(nullptr, IDI_APPLICATION);
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // technical behaviour
// 2. register window class
if (!RegisterClass(&wc)) return 100;
// 3. adjust window size (optional)
DWORD style = {};
style = WS_OVERLAPPEDWINDOW; // window with border & title
//style = WS_POPUP; // window without any decorations
RECT rect = { 100, 100, 100 + width, 100 + height }; // left-top corner, right-bottom corner
AdjustWindowRect(&rect, style, FALSE);
// 4. create window instance
_hWnd = CreateWindow(
wc.lpszClassName, // class name of window class to be instantiated
wc.lpszClassName, // window title
style, // visual style
rect.left, rect.top, // window position (left-top corner)
rect.right - rect.left, rect.bottom - rect.top, // window size
nullptr, // handle to a parent window
nullptr, // handle to a menu instance
hInstance,
nullptr // pointer to optional parameter
);
if (_hWnd == nullptr) return 110;
// 5. show window
ShowWindow(_hWnd, SW_SHOW);
SetFocus(_hWnd);
return 0;
}
BOOL Window::run()
{
// 6. run window
// GetMessage - synchronous call which holds until a new message arrives
// PeekMessage - get last message from message queue or nothing if no one is available
// TranslateMessage - translates keyboard input
// DispatchMessage - send message to WindowProc
MSG msg = {};
if (PeekMessage(&msg, nullptr, 0, UINT_MAX, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return msg.message != WM_QUIT;
}
void Window::deInit()
{
}
LRESULT WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CLOSE:
DestroyWindow(hWnd);
return 0;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
case WM_KEYDOWN:
if (wParam == VK_ESCAPE) DestroyWindow(hWnd);
return 0;
default:
break;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include <Windows.h>
class Window
{
public:
INT init(HINSTANCE hInstance, UINT width, UINT height);
BOOL run();
void deInit();
HWND getWindowHandle() const { return _hWnd; }
private:
HWND _hWnd = nullptr; // handle to window instance
};
LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+104
View File
@@ -0,0 +1,104 @@
#include <Windows.h>
#include "Window.h"
#include "Direct3D.h"
#include "Mesh.h"
#include "Material.h"
#include "Camera.h"
#include "Time.h"
#include "Light.h"
#include "Utilities.h"
int WINAPI WinMain(
HINSTANCE hInstance, // handle to instance of application
HINSTANCE hPrevInstance, // deprecated
PSTR szCmdLine, // command line
int nCmdShow // how should the window be opened (minimized, maximized or normal)
)
{
// some constant values
const UINT width = 1024;
const UINT height = 768;
const BOOL isFullscreen = FALSE;
UINT error = 0; // error code for identifying errors
// 1. create window
Window window = {};
error = window.init(hInstance, width, height);
CheckError(error);
// 2. create connection to Direct3D
Direct3D d3d = {};
error = d3d.init(window.getWindowHandle(), width, height, isFullscreen);
CheckError(error);
// 3. create a mesh
Mesh mesh = {};
error = mesh.init(d3d.getDevice());
CheckError(error);
// 4. create a camera
Camera camera = {};
error = camera.init(width, height);
CheckError(error);
// 5. create time
Time time = {};
error = time.init();
CheckError(error);
// 6. create a material
Material material = {};
error = material.init(d3d.getDevice(), TEXT("wall.jpg"));
CheckError(error);
//// 7. create light source
//Light light = {};
//D3DLIGHT9 lightData = {};
//lightData.Type = D3DLIGHT_POINT;
//lightData.Direction = { -1.0f, -1.0f, 1.0f };
//lightData.Position = { 1.0f, 1.0f, -1.0f };
//lightData.Diffuse = { 0.7f, 0.7f, 0.7f };
//lightData.Specular = { 1.0f, 1.0f, 1.0f };
//lightData.Range = 100.0f;
//lightData.Attenuation0 = 1.0f;
//lightData.Attenuation1 = 0.2f;
//lightData.Attenuation2 = 0.1f;
//error = light.init(lightData);
//CheckError(error);
// 8. run application
while (window.run())
{
// 8.1. update objects
time.update();
mesh.update(time.getDeltaTime());
camera.update(time.getDeltaTime());
//light.update(time.getDeltaTime());
material.setMatrices(
d3d.getDeviceContext(), mesh.getWorldMatrix(), camera.getViewMatrix(), camera.getProjectionMatrix());
// 8.2. render objects
d3d.beginScene();
//light.render(d3d.getDevice());
material.render(d3d.getDeviceContext());
mesh.render(d3d.getDeviceContext());
d3d.endScene();
}
// 9. tidy up
//light.deInit();
material.deInit();
time.deInit();
//camera.deInit();
mesh.deInit();
d3d.deInit();
window.deInit();
return 0;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 213 KiB

+27 -1
View File
@@ -1,7 +1,33 @@
#include "Camera.h"
UINT Camera::init(UINT width, UINT height)
#include <DirectXMath.h>
using namespace DirectX;
UINT Camera::init(IDirect3DDevice9* pD3DDevice, UINT width, UINT height)
{
// view matrix
XMVECTOR position = XMVectorSet(0.0f, 0.0f, -1.0f, 0.0f);
XMVECTOR forward = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
XMMATRIX lookTo = XMMatrixLookToLH(position, forward, up);
XMFLOAT4X4 v;
XMStoreFloat4x4(&v, lookTo);
_viewMatrix = *reinterpret_cast<D3DMATRIX*>(&v);
// projection matrix
float fov = XMConvertToRadians(60.0f);
float aspectRatio = static_cast<float>(width) / static_cast<float>(height);
float nearClippingPlane = 0.3f;
float farClippingPlane = 100.0f;
XMMATRIX perspective = XMMatrixPerspectiveFovLH(fov, aspectRatio, nearClippingPlane, farClippingPlane);
XMStoreFloat4x4(reinterpret_cast<XMFLOAT4X4*>(&_projectionMatrix), perspective);
pD3DDevice->SetTransform(D3DTS_VIEW, &_viewMatrix);
pD3DDevice->SetTransform(D3DTS_PROJECTION, &_projectionMatrix);
return 0;
}
+1 -1
View File
@@ -4,7 +4,7 @@
class Camera
{
public:
UINT init(UINT width, UINT height);
UINT init(IDirect3DDevice9* pD3DDevice, UINT width, UINT height);
void update(FLOAT dt);
void deInit();
+3
View File
@@ -184,6 +184,7 @@
<ClCompile Include="Mesh.cpp" />
<ClCompile Include="Time.cpp" />
<ClCompile Include="Utilities.cpp" />
<ClCompile Include="WICTextureLoader9.cpp" />
<ClCompile Include="Window.cpp" />
</ItemGroup>
<ItemGroup>
@@ -194,6 +195,8 @@
<ClInclude Include="Mesh.h" />
<ClInclude Include="Time.h" />
<ClInclude Include="Utilities.h" />
<ClInclude Include="Vertex.h" />
<ClInclude Include="WICTextureLoader9.h" />
<ClInclude Include="Window.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
+9
View File
@@ -42,6 +42,9 @@
<ClCompile Include="Window.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="WICTextureLoader9.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="Camera.h">
@@ -68,5 +71,11 @@
<ClInclude Include="Window.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="Vertex.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="WICTextureLoader9.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
</Project>
+38
View File
@@ -1,28 +1,66 @@
#include "Direct3D.h"
#include "Utilities.h"
INT Direct3D::init(HWND hWnd, UINT width, UINT height, BOOL isFullscreen)
{
HRESULT hr = {};
// 1. create connection to Direct3D API
IDirect3D9* pD3D = Direct3DCreate9(D3D_SDK_VERSION);
if (pD3D == nullptr) return 200;
// 2. check compatibility
D3DCAPS9 caps = {};
UINT adapter = D3DADAPTER_DEFAULT; // graphic card index, 0 -> primary
D3DDEVTYPE devType = D3DDEVTYPE_HAL; // hardware or software renderer, here hardware
hr = pD3D->GetDeviceCaps(adapter, devType, &caps);
CheckFailed(hr, 210);
DWORD vertexProcessing = D3DCREATE_SOFTWARE_VERTEXPROCESSING; // fallback if hardware processing is not available
if (caps.VertexProcessingCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
vertexProcessing = D3DCREATE_HARDWARE_VERTEXPROCESSING; // hardware processing is available
// 3. define presentation parameters
D3DPRESENT_PARAMETERS pp = {};
pp.hDeviceWindow = hWnd; // target window
pp.Windowed = !isFullscreen; // window mode yes or no
pp.BackBufferCount = 1;
pp.BackBufferWidth = width;
pp.BackBufferHeight = height;
pp.BackBufferFormat = D3DFMT_A8R8G8B8; // 4 channels, each channel 8bit
pp.SwapEffect = D3DSWAPEFFECT_DISCARD; // what happens with the front buffer after a swap
// 4. create Direct3D device
hr = pD3D->CreateDevice(adapter, devType, hWnd, vertexProcessing, &pp, &_pD3DDevice);
CheckFailed(hr, 220);
// 5. tidy up
safeRelease(pD3D);
return 0;
}
void Direct3D::beginScene()
{
_pD3DDevice->BeginScene();
// clear buffers
_pD3DDevice->Clear(
0, nullptr, // clear regions, here clear everything
D3DCLEAR_TARGET, // which buffers to clear
D3DCOLOR_XRGB(100, 100, 100), 1.0f, 0xffffffff // clear values
);
}
void Direct3D::endScene()
{
_pD3DDevice->EndScene();
// present frame
_pD3DDevice->Present(nullptr, nullptr, nullptr, nullptr);
}
void Direct3D::deInit()
{
safeRelease(_pD3DDevice);
}
+5 -1
View File
@@ -1,7 +1,9 @@
#include "Light.h"
UINT Light::init()
UINT Light::init(D3DLIGHT9& lightData)
{
_lightData = lightData;
return 0;
}
@@ -11,6 +13,8 @@ void Light::update(FLOAT dt)
void Light::render(IDirect3DDevice9* pD3DDevice)
{
pD3DDevice->SetLight(0, &_lightData);
pD3DDevice->LightEnable(0, TRUE);
}
void Light::deInit()
+4 -1
View File
@@ -4,9 +4,12 @@
class Light
{
public:
UINT init();
UINT init(D3DLIGHT9& lightData);
void update(FLOAT dt);
void render(IDirect3DDevice9* pD3DDevice);
void deInit();
private:
D3DLIGHT9 _lightData = {};
};
+26
View File
@@ -1,13 +1,39 @@
#include "Material.h"
#include "Utilities.h"
#include "WICTextureLoader9.h"
UINT Material::init(IDirect3DDevice9* pD3DDevice, LPCTSTR textureFileName)
{
HRESULT hr = DirectX::CreateWICTextureFromFile(pD3DDevice, textureFileName, &_pTexture, 0, DirectX::WIC_LOADER_MIP_AUTOGEN);
CheckFailed(hr, 600);
return 0;
}
void Material::render(IDirect3DDevice9* pD3DDevice)
{
// set texture
pD3DDevice->SetTexture(0, _pTexture);
// set sampler state
pD3DDevice->SetSamplerState(0, D3DSAMP_ADDRESSU, D3DTADDRESS_BORDER);
pD3DDevice->SetSamplerState(0, D3DSAMP_ADDRESSV, D3DTADDRESS_BORDER);
pD3DDevice->SetSamplerState(0, D3DSAMP_BORDERCOLOR, D3DCOLOR_XRGB(100, 0, 100));
pD3DDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR);
pD3DDevice->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR);
pD3DDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
pD3DDevice->SetSamplerState(0, D3DSAMP_MAXMIPLEVEL, 0);
// set material
D3DMATERIAL9 material = {};
material.Ambient = { 1.0f, 1.0f, 1.0f, 1.0f };
material.Diffuse = { 1.0f, 1.0f, 1.0f, 1.0f };
material.Specular = { 1.0f, 1.0f, 1.0f, 1.0f };
material.Power = 100.0f;
material.Emissive = { 1.0f, 0.0f, 0.0f, 1.0f };
pD3DDevice->SetMaterial(&material);
}
void Material::deInit()
+1 -1
View File
@@ -9,6 +9,6 @@ public:
void deInit();
private:
IDirect3DTexture9* _texture = {};
IDirect3DTexture9* _pTexture = {};
};
+123
View File
@@ -1,5 +1,10 @@
#include "Mesh.h"
#include "Utilities.h"
#include "Vertex.h"
#include <DirectXMath.h>
using namespace DirectX;
UINT Mesh::init(IDirect3DDevice9* pD3DDevice)
{
@@ -11,15 +16,57 @@ UINT Mesh::init(IDirect3DDevice9* pD3DDevice)
error = createIndexBuffer(pD3DDevice);
CheckError(error);
XMMATRIX identity = XMMatrixIdentity();
XMFLOAT4X4 w;
XMStoreFloat4x4(&w, identity);
_worldMatrix = *reinterpret_cast<D3DMATRIX*>(&w);
return 0;
}
void Mesh::update(FLOAT dt)
{
static float x = 0.0f;
static float y = 0.0f;
static float z = 0.0f;
static float rotY = 0.0f;
static float rotZ = 0.0f;
rotY += 0.5f * dt;
rotZ += 0.0f * dt;
float move = 1.0f * dt;
if (GetAsyncKeyState(VK_LEFT) & 0x8000) x -= move;
if (GetAsyncKeyState(VK_RIGHT) & 0x8000) x += move;
if (GetAsyncKeyState(VK_DOWN) & 0x8000) y -= move;
if (GetAsyncKeyState(VK_UP) & 0x8000) y += move;
if ((GetAsyncKeyState(VK_SUBTRACT) & 0x8000) || (GetAsyncKeyState('Q') & 0x8000)) z -= move;
if ((GetAsyncKeyState(VK_ADD) & 0x8000) || (GetAsyncKeyState('E') & 0x8000)) z += move;
XMMATRIX translation = XMMatrixTranslation(x, y, z);
XMMATRIX rotation = XMMatrixRotationRollPitchYaw(0.0f, rotY, rotZ);
XMMATRIX scale = XMMatrixScaling(1.0f, 1.0f, 1.0f);
XMStoreFloat4x4(reinterpret_cast<XMFLOAT4X4*>(&_worldMatrix), scale * rotation * translation);
}
void Mesh::render(IDirect3DDevice9* pD3DDevice)
{
// setup pipeline
pD3DDevice->SetStreamSource(0, _pVertexBuffer, 0, _vertexStride);
pD3DDevice->SetIndices(_pIndexBuffer);
pD3DDevice->SetFVF(FVF);
pD3DDevice->SetTransform(D3DTS_WORLD, &_worldMatrix);
// draw call
pD3DDevice->DrawIndexedPrimitive(
D3DPT_TRIANGLELIST, // primitive type
0, 0, // vertex buffer offsets
_vertexCount,
0, // index buffer offset
_indexCount / 3 // primitive count
);
}
void Mesh::deInit()
@@ -30,10 +77,86 @@ void Mesh::deInit()
UINT Mesh::createVertexBuffer(IDirect3DDevice9* pD3DDevice)
{
// define values
_vertexCount = 4;
_vertexStride = sizeof(Vertex);
// describe & create vertex buffer
HRESULT hr = pD3DDevice->CreateVertexBuffer(
_vertexCount * _vertexStride, // total size of content
D3DUSAGE_WRITEONLY, // read and/or write access
FVF, // FVF - Flexible Vertex Format -> vertex structure
D3DPOOL_MANAGED, // memmory management
&_pVertexBuffer,
nullptr // deprecated, always nullptr
);
CheckFailed(hr, 300);
// populate vertex buffer
Vertex* pVertices = nullptr;
hr = _pVertexBuffer->Lock(
0, 0, // offset & size to lock, here everything
reinterpret_cast<void**>(&pVertices),
0 // optional flags
);
CheckFailed(hr, 310);
// triangle
//pVertices[0] = Vertex(0.0f, 1.0f, 0.0f);
//pVertices[1] = Vertex(1.0f, -1.0f, 0.0f);
//pVertices[2] = Vertex(-1.0f, -1.0f, 0.0f);
// quad
//pVertices[0] = Vertex(-0.5f, 0.5f, 0.0f);
//pVertices[1] = Vertex(0.5f, 0.5f, 0.0f);
//pVertices[2] = Vertex(0.5f, -0.5f, 0.0f);
//pVertices[3] = Vertex(-0.5f, -0.5f, 0.0f);
// quad with color
//pVertices[0] = Vertex(-0.5f, 0.5f, 0.0f, 255, 0, 0);
//pVertices[1] = Vertex(0.5f, 0.5f, 0.0f, 0, 255, 0);
//pVertices[2] = Vertex(0.5f, -0.5f, 0.0f, 255, 0, 255);
//pVertices[3] = Vertex(-0.5f, -0.5f, 0.0f, 0, 0, 255);
// quad with uvs & normals
pVertices[0] = Vertex(-0.5f, 0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f);
pVertices[1] = Vertex(0.5f, 0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f);
pVertices[2] = Vertex(0.5f, -0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f);
pVertices[3] = Vertex(-0.5f, -0.5f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f);
hr = _pVertexBuffer->Unlock();
CheckFailed(hr, 320);
pVertices = nullptr;
return 0;
}
UINT Mesh::createIndexBuffer(IDirect3DDevice9* pD3DDevice)
{
_indexCount = 6;
HRESULT hr = pD3DDevice->CreateIndexBuffer(_indexCount * sizeof(unsigned short),
D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_MANAGED, &_pIndexBuffer, nullptr);
CheckFailed(hr, 330);
unsigned short* pIndices = nullptr;
hr = _pIndexBuffer->Lock(0, 0, reinterpret_cast<void**>(&pIndices), 0);
CheckFailed(hr, 340);
// triangle
//pIndices[0] = 0;
//pIndices[1] = 1;
//pIndices[2] = 2;
// quad
pIndices[0] = 0; pIndices[1] = 1; pIndices[2] = 2;
pIndices[3] = 0; pIndices[4] = 2; pIndices[5] = 3;
hr = _pIndexBuffer->Unlock();
CheckFailed(hr, 350);
pIndices = nullptr;
return 0;
}
+14
View File
@@ -1,12 +1,26 @@
#include "Time.h"
#include <string>
UINT Time::init()
{
_lastFrame = CLOCK::now();
return 0;
}
void Time::update()
{
TIMEPOINT now = CLOCK::now();
SECONDS diff = now - _lastFrame;
_deltaTime = diff.count();
_lastFrame = now;
#if _DEBUG && UNICODE
wstring output = L"fps: " + to_wstring(1.0f / _deltaTime) + L"\n";
OutputDebugString(output.c_str());
#endif // _DEBUG && UNICODE
}
void Time::deInit()
+5
View File
@@ -4,6 +4,10 @@
using namespace std;
typedef chrono::steady_clock CLOCK;
typedef chrono::duration<FLOAT> SECONDS;
typedef CLOCK::time_point TIMEPOINT;
class Time
{
public:
@@ -15,5 +19,6 @@ public:
private:
FLOAT _deltaTime = 0.0f;
TIMEPOINT _lastFrame = {};
};
+4 -2
View File
@@ -5,9 +5,11 @@ void ShowError(UINT error)
#if _DEBUG
LPCTSTR msg = TEXT("Application quit with an error: ");
#if UNICODE
msg = (std::wstring(msg) + std::to_wstring(error)).c_str();
std::wstring str = std::wstring(msg) + std::to_wstring(error);
msg = str.c_str();
#else // UNICODE
msg = (std::string(msg) + std::to_string(error)).c_str();
std::string str = std::string(msg) + std::to_string(error);
msg = str.c_str();
#endif // UNICODE
MessageBox(nullptr, msg, TEXT("Error"), MB_OK);
#endif // DEBUG
+36
View File
@@ -0,0 +1,36 @@
#pragma once
#include <d3d9.h>
#define FVF D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 | D3DFVF_NORMAL
struct Vertex
{
// position
float x;
float y;
float z;
// normal
float nx;
float ny;
float nz;
// color
D3DCOLOR color;
// texture coordinates
float u;
float v;
Vertex() : x(0.0f), y(0.0f), z(0.0f), color(0xffffffff), u(0.0f), v(0.0f), nx(0.0f), ny(0.0f), nz(0.0f) {}
Vertex(float x, float y, float z) : x(x), y(y), z(z), color(0xffffffff), u(0.0f), v(0.0f), nx(0.0f), ny(0.0f), nz(0.0f) {}
Vertex(float x, float y, float z, UINT r, UINT g, UINT b) :
x(x), y(y), z(z), color(D3DCOLOR_XRGB(r, g, b)), u(0.0f), v(0.0f), nx(0.0f), ny(0.0f), nz(0.0f) {}
Vertex(float x, float y, float z, float u, float v) :
x(x), y(y), z(z), color(0xffffffff), u(u), v(v), nx(0.0f), ny(0.0f), nz(0.0f) {}
Vertex(float x, float y, float z, float nx, float ny, float nz, float u, float v) :
x(x), y(y), z(z), color(0xffffffff), u(u), v(v), nx(nx), ny(ny), nz(nz) {}
};
+637
View File
@@ -0,0 +1,637 @@
//--------------------------------------------------------------------------------------
// File: WICTextureLoader9.cpp
//
// Function for loading a WIC image and creating a Direct3D runtime texture for it
//
// Note: Assumes application has already called CoInitializeEx
//
// Note these functions are useful for images created as simple 2D textures. For
// more complex resources, DDSTextureLoader is an excellent light-weight runtime loader.
// For a full-featured DDS file reader, writer, and texture processing pipeline see
// the 'Texconv' sample and the 'DirectXTex' library.
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// https://go.microsoft.com/fwlink/?LinkId=248926
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
// We could load multi-frame images (TIFF/GIF) into a texture array.
// For now, we just load the first frame (note: DirectXTex supports multi-frame images)
#include "WICTextureLoader9.h"
#include <d3d9types.h>
#include <algorithm>
#include <cassert>
#include <cfloat>
#include <cmath>
#include <cstring>
#include <iterator>
#include <memory>
#include <wincodec.h>
#include <wrl/client.h>
#ifdef _MSC_VER
// Off by default warnings
#pragma warning(disable : 4619 4616 4061 4623 4626 5027)
// C4619/4616 #pragma warning warnings
// C4061 enumerator 'x' in switch of enum 'y' is not explicitly handled by a case label
// C4623 default constructor was implicitly defined as deleted
// C4626 assignment operator was implicitly defined as deleted
// C5027 move assignment operator was implicitly defined as deleted
#endif
#ifdef __clang__
#pragma clang diagnostic ignored "-Wcovered-switch-default"
#pragma clang diagnostic ignored "-Wswitch-enum"
#endif
using namespace DirectX;
using Microsoft::WRL::ComPtr;
namespace
{
//-------------------------------------------------------------------------------------
// WIC Pixel Format Translation Data
//-------------------------------------------------------------------------------------
struct WICTranslate
{
const GUID& wic;
D3DFORMAT format;
constexpr WICTranslate(const GUID& wg, D3DFORMAT fmt) noexcept
: wic(wg),
format(fmt)
{
}
};
constexpr WICTranslate g_WICFormats[] = {
// clang-format off
{ GUID_WICPixelFormat128bppRGBAFloat, D3DFMT_A32B32G32R32F },
{ GUID_WICPixelFormat64bppRGBAHalf, D3DFMT_A16B16G16R16F },
{ GUID_WICPixelFormat64bppRGBA, D3DFMT_A16B16G16R16 },
{ GUID_WICPixelFormat32bppBGRA, D3DFMT_A8R8G8B8 },
{ GUID_WICPixelFormat32bppRGBA1010102, D3DFMT_A2B10G10R10 },
{ GUID_WICPixelFormat16bppBGRA5551, D3DFMT_A1R5G5B5 },
{ GUID_WICPixelFormat16bppBGR555, D3DFMT_X1R5G5B5 },
{ GUID_WICPixelFormat16bppBGR565, D3DFMT_R5G6B5 },
{ GUID_WICPixelFormat32bppGrayFloat, D3DFMT_R32F },
{ GUID_WICPixelFormat16bppGrayHalf, D3DFMT_R16F },
{ GUID_WICPixelFormat16bppGray, D3DFMT_L16 },
{ GUID_WICPixelFormat8bppGray, D3DFMT_L8 },
{ GUID_WICPixelFormat8bppAlpha, D3DFMT_A8 },
// clang-format on
};
//-------------------------------------------------------------------------------------
// WIC Pixel Format nearest conversion table
//-------------------------------------------------------------------------------------
struct WICConvert
{
const GUID& source;
const GUID& target;
constexpr WICConvert(const GUID& src, const GUID& tgt) noexcept
: source(src),
target(tgt)
{
}
};
constexpr WICConvert g_WICConvert[] = {
// clang-format off
// Note target GUID in this conversion table must be one of those directly supported formats (above).
{ GUID_WICPixelFormatBlackWhite, GUID_WICPixelFormat8bppGray }, // D3DFMT_L8
{ GUID_WICPixelFormat1bppIndexed, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat2bppIndexed, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat4bppIndexed, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat8bppIndexed, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat2bppGray, GUID_WICPixelFormat8bppGray }, // D3DFMT_L8
{ GUID_WICPixelFormat4bppGray, GUID_WICPixelFormat8bppGray }, // D3DFMT_L8
{ GUID_WICPixelFormat16bppGrayFixedPoint, GUID_WICPixelFormat16bppGrayHalf }, // D3DFMT_R16F
{ GUID_WICPixelFormat32bppGrayFixedPoint, GUID_WICPixelFormat32bppGrayFloat }, // D3DFMT_R32F
{ GUID_WICPixelFormat32bppBGR101010, GUID_WICPixelFormat32bppRGBA1010102 }, // D3DFMT_A2B10G10R10
{ GUID_WICPixelFormat24bppBGR, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat24bppRGB, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat32bppBGR, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat32bppRGBA, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat32bppPBGRA, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat32bppPRGBA, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat48bppRGB, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat48bppBGR, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat64bppBGRA, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat64bppPRGBA, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat64bppPBGRA, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat48bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat48bppBGRFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat64bppRGBAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat64bppBGRAFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat64bppRGBFixedPoint, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat64bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat48bppRGBHalf, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat128bppPRGBAFloat, GUID_WICPixelFormat128bppRGBAFloat }, // D3DFMT_A32B32G32R32F
{ GUID_WICPixelFormat128bppRGBFloat, GUID_WICPixelFormat128bppRGBAFloat }, // D3DFMT_A32B32G32R32F
{ GUID_WICPixelFormat128bppRGBAFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // D3DFMT_A32B32G32R32F
{ GUID_WICPixelFormat128bppRGBFixedPoint, GUID_WICPixelFormat128bppRGBAFloat }, // D3DFMT_A32B32G32R32F
{ GUID_WICPixelFormat32bppRGBE, GUID_WICPixelFormat128bppRGBAFloat }, // D3DFMT_A32B32G32R32F
{ GUID_WICPixelFormat32bppCMYK, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat64bppCMYK, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat40bppCMYKAlpha, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat80bppCMYKAlpha, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat32bppRGB, GUID_WICPixelFormat32bppBGRA }, // D3DFMT_A8R8G8B8
{ GUID_WICPixelFormat64bppRGB, GUID_WICPixelFormat64bppRGBA }, // D3DFMT_A16B16G16R16
{ GUID_WICPixelFormat64bppPRGBAHalf, GUID_WICPixelFormat64bppRGBAHalf }, // D3DFMT_A16B16G16R16F
{ GUID_WICPixelFormat96bppRGBFloat, GUID_WICPixelFormat128bppRGBAFloat }, // D3DFMT_A32B32G32R32F
// We don't support n-channel formats
// clang-format on
};
//--------------------------------------------------------------------------------------
BOOL WINAPI InitializeWICFactory(PINIT_ONCE, PVOID, PVOID* ifactory) noexcept
{
HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory2, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory2), ifactory);
if (SUCCEEDED(hr))
{
// WIC2 is available on Windows 10, Windows 8.x, and Windows 7 SP1 with KB 2670838 installed
return TRUE;
}
else
{
hr = CoCreateInstance(CLSID_WICImagingFactory1, nullptr, CLSCTX_INPROC_SERVER, __uuidof(IWICImagingFactory), ifactory);
return SUCCEEDED(hr) ? TRUE : FALSE;
}
}
IWICImagingFactory* GetWIC() noexcept
{
static INIT_ONCE s_initOnce = INIT_ONCE_STATIC_INIT;
IWICImagingFactory* factory = nullptr;
if (!InitOnceExecuteOnce(&s_initOnce, InitializeWICFactory, nullptr, reinterpret_cast<LPVOID*>(&factory)))
{
return nullptr;
}
return factory;
}
//---------------------------------------------------------------------------------
D3DFORMAT WICToD3D9(const GUID& guid) noexcept
{
for (size_t i = 0; i < std::size(g_WICFormats); ++i)
{
if (memcmp(&g_WICFormats[i].wic, &guid, sizeof(GUID)) == 0)
return g_WICFormats[i].format;
}
return D3DFMT_UNKNOWN;
}
//---------------------------------------------------------------------------------
void FitPowerOf2(UINT origx, UINT origy, UINT& targetx, UINT& targety, size_t maxsize)
{
const float origAR = float(origx) / float(origy);
if (origx > origy)
{
size_t x;
for (x = maxsize; x > 1; x >>= 1)
{
if (x <= targetx)
break;
}
targetx = UINT(x);
float bestScore = FLT_MAX;
for (size_t y = maxsize; y > 0; y >>= 1)
{
const float score = fabsf((float(x) / float(y)) - origAR);
if (score < bestScore)
{
bestScore = score;
targety = UINT(y);
}
}
}
else
{
size_t y;
for (y = maxsize; y > 1; y >>= 1)
{
if (y <= targety)
break;
}
targety = UINT(y);
float bestScore = FLT_MAX;
for (size_t x = maxsize; x > 0; x >>= 1)
{
const float score = fabsf((float(x) / float(y)) - origAR);
if (score < bestScore)
{
bestScore = score;
targetx = UINT(x);
}
}
}
}
//---------------------------------------------------------------------------------
HRESULT CreateTextureFromWIC(_In_ LPDIRECT3DDEVICE9 device,
_In_ IWICBitmapFrameDecode* frame,
_In_ size_t maxsize,
_In_ DWORD usage,
_In_ D3DPOOL pool,
_In_ WIC_LOADER_FLAGS loadFlags,
_Outptr_ LPDIRECT3DTEXTURE9* texture) noexcept
{
UINT width, height;
HRESULT hr = frame->GetSize(&width, &height);
if (FAILED(hr))
return hr;
if (maxsize > UINT32_MAX)
return E_INVALIDARG;
assert(width > 0 && height > 0);
if (!maxsize)
{
maxsize = 4096u /*D3D_FL9_3_REQ_TEXTURE2D_U_OR_V_DIMENSION*/;
}
assert(maxsize > 0);
UINT twidth = width;
UINT theight = height;
if (loadFlags & WIC_LOADER_FIT_POW2)
{
FitPowerOf2(width, height, twidth, theight, maxsize);
}
else if (width > maxsize || height > maxsize)
{
const float ar = static_cast<float>(height) / static_cast<float>(width);
if (width > height)
{
twidth = static_cast<UINT>(maxsize);
theight = std::max<UINT>(1, static_cast<UINT>(static_cast<float>(maxsize) * ar));
}
else
{
theight = static_cast<UINT>(maxsize);
twidth = std::max<UINT>(1, static_cast<UINT>(static_cast<float>(maxsize) / ar));
}
assert(twidth <= maxsize && theight <= maxsize);
}
if (loadFlags & WIC_LOADER_MAKE_SQUARE)
{
twidth = std::max<UINT>(twidth, theight);
theight = twidth;
}
// Determine format
WICPixelFormatGUID pixelFormat;
hr = frame->GetPixelFormat(&pixelFormat);
if (FAILED(hr))
return hr;
WICPixelFormatGUID convertGUID;
memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &pixelFormat, sizeof(GUID));
D3DFORMAT format = WICToD3D9(pixelFormat);
if (format == D3DFMT_UNKNOWN)
{
for (size_t i = 0; i < std::size(g_WICConvert); ++i)
{
if (memcmp(&g_WICConvert[i].source, &pixelFormat, sizeof(WICPixelFormatGUID)) == 0)
{
memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &g_WICConvert[i].target, sizeof(GUID));
format = WICToD3D9(g_WICConvert[i].target);
assert(format != D3DFMT_UNKNOWN);
break;
}
}
if (format == D3DFMT_UNKNOWN)
return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED);
}
if (loadFlags & WIC_LOADER_FORCE_RGBA32)
{
memcpy_s(&convertGUID, sizeof(WICPixelFormatGUID), &GUID_WICPixelFormat32bppBGRA, sizeof(GUID));
format = D3DFMT_A8R8G8B8;
}
// Create texture
if (loadFlags & WIC_LOADER_MIP_AUTOGEN)
usage |= D3DUSAGE_AUTOGENMIPMAP;
ComPtr<IDirect3DTexture9> pTexture;
hr = device->CreateTexture(twidth, theight, 1u, usage, format, pool, pTexture.GetAddressOf(), nullptr);
if (FAILED(hr))
return hr;
// Create staging texture memory
ComPtr<IDirect3DTexture9> pStagingTexture;
if (pool == D3DPOOL_DEFAULT)
{
hr = device->CreateTexture(twidth, theight, 1u, 0u, format, D3DPOOL_SYSTEMMEM, pStagingTexture.GetAddressOf(), nullptr);
if (FAILED(hr))
return hr;
}
else
{
pStagingTexture = pTexture;
}
D3DLOCKED_RECT LockedRect = {};
hr = pStagingTexture->LockRect(0, &LockedRect, nullptr, 0);
if (FAILED(hr))
return hr;
const uint64_t numBytes = uint64_t(LockedRect.Pitch) * uint64_t(theight);
pStagingTexture->UnlockRect(0);
if (numBytes > UINT32_MAX)
{
return HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW);
}
// Load image data
if (memcmp(&convertGUID, &pixelFormat, sizeof(GUID)) == 0 && twidth == width && theight == height)
{
// No format conversion or resize needed
hr = pStagingTexture->LockRect(0, &LockedRect, nullptr, 0);
if (FAILED(hr))
return hr;
hr = frame->CopyPixels(nullptr,
static_cast<UINT>(LockedRect.Pitch),
static_cast<UINT>(numBytes),
static_cast<BYTE*>(LockedRect.pBits));
pStagingTexture->UnlockRect(0);
if (FAILED(hr))
return hr;
}
else if (twidth != width || theight != height)
{
// Resize
auto pWIC = GetWIC();
if (!pWIC)
return E_NOINTERFACE;
ComPtr<IWICBitmapScaler> scaler;
hr = pWIC->CreateBitmapScaler(scaler.GetAddressOf());
if (FAILED(hr))
return hr;
hr = scaler->Initialize(frame, twidth, theight, WICBitmapInterpolationModeFant);
if (FAILED(hr))
return hr;
WICPixelFormatGUID pfScaler;
hr = scaler->GetPixelFormat(&pfScaler);
if (FAILED(hr))
return hr;
if (memcmp(&convertGUID, &pfScaler, sizeof(GUID)) == 0)
{
// No format conversion needed
hr = pStagingTexture->LockRect(0, &LockedRect, nullptr, 0);
if (FAILED(hr))
return hr;
hr = scaler->CopyPixels(nullptr,
static_cast<UINT>(LockedRect.Pitch),
static_cast<UINT>(numBytes),
static_cast<BYTE*>(LockedRect.pBits));
pStagingTexture->UnlockRect(0);
if (FAILED(hr))
return hr;
}
else
{
ComPtr<IWICFormatConverter> FC;
hr = pWIC->CreateFormatConverter(FC.GetAddressOf());
if (FAILED(hr))
return hr;
BOOL canConvert = FALSE;
hr = FC->CanConvert(pfScaler, convertGUID, &canConvert);
if (FAILED(hr) || !canConvert)
{
return E_UNEXPECTED;
}
hr = FC->Initialize(scaler.Get(),
convertGUID,
WICBitmapDitherTypeErrorDiffusion,
nullptr,
0,
WICBitmapPaletteTypeMedianCut);
if (FAILED(hr))
return hr;
hr = pStagingTexture->LockRect(0, &LockedRect, nullptr, 0);
if (FAILED(hr))
return hr;
hr = FC->CopyPixels(nullptr,
static_cast<UINT>(LockedRect.Pitch),
static_cast<UINT>(numBytes),
static_cast<BYTE*>(LockedRect.pBits));
pStagingTexture->UnlockRect(0);
if (FAILED(hr))
return hr;
}
}
else
{
// Format conversion but no resize
auto pWIC = GetWIC();
if (!pWIC)
return E_NOINTERFACE;
ComPtr<IWICFormatConverter> FC;
hr = pWIC->CreateFormatConverter(FC.GetAddressOf());
if (FAILED(hr))
return hr;
BOOL canConvert = FALSE;
hr = FC->CanConvert(pixelFormat, convertGUID, &canConvert);
if (FAILED(hr) || !canConvert)
{
return E_UNEXPECTED;
}
hr = FC->Initialize(frame, convertGUID, WICBitmapDitherTypeErrorDiffusion, nullptr, 0, WICBitmapPaletteTypeMedianCut);
if (FAILED(hr))
return hr;
hr = pStagingTexture->LockRect(0, &LockedRect, nullptr, 0);
if (FAILED(hr))
return hr;
hr = FC->CopyPixels(nullptr,
static_cast<UINT>(LockedRect.Pitch),
static_cast<UINT>(numBytes),
static_cast<BYTE*>(LockedRect.pBits));
pStagingTexture->UnlockRect(0);
if (FAILED(hr))
return hr;
}
if (pool == D3DPOOL_DEFAULT)
{
hr = device->UpdateTexture(pStagingTexture.Get(), pTexture.Get());
if (FAILED(hr))
return hr;
}
*texture = pTexture.Detach();
return S_OK;
}
} // anonymous namespace
//--------------------------------------------------------------------------------------
_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromMemory(LPDIRECT3DDEVICE9 d3dDevice,
const uint8_t* wicData,
size_t wicDataSize,
LPDIRECT3DTEXTURE9* texture,
size_t maxsize,
WIC_LOADER_FLAGS loadFlags) noexcept
{
return CreateWICTextureFromMemoryEx(d3dDevice, wicData, wicDataSize, maxsize, 0u, D3DPOOL_DEFAULT, loadFlags, texture);
}
_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromMemoryEx(LPDIRECT3DDEVICE9 d3dDevice,
const uint8_t* wicData,
size_t wicDataSize,
_In_ size_t maxsize,
_In_ DWORD usage,
_In_ D3DPOOL pool,
_In_ WIC_LOADER_FLAGS loadFlags,
LPDIRECT3DTEXTURE9* texture) noexcept
{
if (texture)
{
*texture = nullptr;
}
if (!d3dDevice || !wicData || !wicDataSize || !texture)
return E_INVALIDARG;
if (!wicDataSize)
return E_FAIL;
if (wicDataSize > UINT32_MAX)
return HRESULT_FROM_WIN32(ERROR_FILE_TOO_LARGE);
auto pWIC = GetWIC();
if (!pWIC)
return E_NOINTERFACE;
// Create input stream for memory
ComPtr<IWICStream> stream;
HRESULT hr = pWIC->CreateStream(stream.GetAddressOf());
if (FAILED(hr))
return hr;
hr = stream->InitializeFromMemory(const_cast<uint8_t*>(wicData), static_cast<DWORD>(wicDataSize));
if (FAILED(hr))
return hr;
// Initialize WIC
ComPtr<IWICBitmapDecoder> decoder;
hr = pWIC->CreateDecoderFromStream(stream.Get(), nullptr, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf());
if (FAILED(hr))
return hr;
ComPtr<IWICBitmapFrameDecode> frame;
hr = decoder->GetFrame(0, frame.GetAddressOf());
if (FAILED(hr))
return hr;
return CreateTextureFromWIC(d3dDevice, frame.Get(), maxsize, usage, pool, loadFlags, texture);
}
//--------------------------------------------------------------------------------------
_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromFile(LPDIRECT3DDEVICE9 d3dDevice,
const wchar_t* fileName,
LPDIRECT3DTEXTURE9* texture,
size_t maxsize,
WIC_LOADER_FLAGS loadFlags) noexcept
{
return CreateWICTextureFromFileEx(d3dDevice, fileName, maxsize, 0u, D3DPOOL_DEFAULT, loadFlags, texture);
}
_Use_decl_annotations_ HRESULT DirectX::CreateWICTextureFromFileEx(LPDIRECT3DDEVICE9 d3dDevice,
const wchar_t* fileName,
size_t maxsize,
DWORD usage,
D3DPOOL pool,
WIC_LOADER_FLAGS loadFlags,
LPDIRECT3DTEXTURE9* texture) noexcept
{
if (texture)
{
*texture = nullptr;
}
if (!d3dDevice || !fileName || !texture)
return E_INVALIDARG;
auto pWIC = GetWIC();
if (!pWIC)
return E_NOINTERFACE;
// Initialize WIC
ComPtr<IWICBitmapDecoder> decoder;
HRESULT hr = pWIC->CreateDecoderFromFilename(fileName, nullptr, GENERIC_READ, WICDecodeMetadataCacheOnDemand, decoder.GetAddressOf());
if (FAILED(hr))
return hr;
ComPtr<IWICBitmapFrameDecode> frame;
hr = decoder->GetFrame(0, frame.GetAddressOf());
if (FAILED(hr))
return hr;
return CreateTextureFromWIC(d3dDevice, frame.Get(), maxsize, usage, pool, loadFlags, texture);
}
+89
View File
@@ -0,0 +1,89 @@
//--------------------------------------------------------------------------------------
// File: WICTextureLoader9.h
//
// Function for loading a WIC image and creating a Direct3D runtime texture for it
// (auto-generating mipmaps if possible)
//
// Note: Assumes application has already called CoInitializeEx
//
// Note these functions are useful for images created as simple 2D textures. For
// more complex resources, DDSTextureLoader is an excellent light-weight runtime loader.
// For a full-featured DDS file reader, writer, and texture processing pipeline see
// the 'Texconv' sample and the 'DirectXTex' library.
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// https://go.microsoft.com/fwlink/?LinkId=248926
//--------------------------------------------------------------------------------------
#pragma once
#ifndef DIRECT3D_VERSION
#define DIRECT3D_VERSION 0x900
#endif
#include <d3d9.h>
#pragma comment(lib, "windowscodecs.lib")
#include <cstddef>
#include <cstdint>
namespace DirectX
{
#ifndef WIC_LOADER_FLAGS_DEFINED
#define WIC_LOADER_FLAGS_DEFINED
enum WIC_LOADER_FLAGS : uint32_t
{
WIC_LOADER_DEFAULT = 0,
WIC_LOADER_MIP_AUTOGEN = 0x8,
WIC_LOADER_FIT_POW2 = 0x20,
WIC_LOADER_MAKE_SQUARE = 0x40,
WIC_LOADER_FORCE_RGBA32 = 0x80,
};
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-dynamic-exception-spec"
#pragma clang diagnostic ignored "-Wextra-semi-stmt"
#endif
DEFINE_ENUM_FLAG_OPERATORS(WIC_LOADER_FLAGS);
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif
// Standard version
HRESULT CreateWICTextureFromMemory(_In_ LPDIRECT3DDEVICE9 d3dDevice,
_In_reads_bytes_(wicDataSize) const uint8_t* wicData,
_In_ size_t wicDataSize,
_Outptr_ LPDIRECT3DTEXTURE9* texture,
_In_ size_t maxsize = 0,
_In_ WIC_LOADER_FLAGS loadFlags = WIC_LOADER_DEFAULT) noexcept;
HRESULT CreateWICTextureFromFile(_In_ LPDIRECT3DDEVICE9 d3dDevice,
_In_z_ const wchar_t* fileName,
_Outptr_ LPDIRECT3DTEXTURE9* texture,
_In_ size_t maxsize = 0,
_In_ WIC_LOADER_FLAGS loadFlags = WIC_LOADER_DEFAULT) noexcept;
// Extended version
HRESULT CreateWICTextureFromMemoryEx(_In_ LPDIRECT3DDEVICE9 d3dDevice,
_In_reads_bytes_(wicDataSize) const uint8_t* wicData,
_In_ size_t wicDataSize,
_In_ size_t maxsize,
_In_ DWORD usage,
_In_ D3DPOOL pool,
_In_ WIC_LOADER_FLAGS loadFlags,
_Outptr_ LPDIRECT3DTEXTURE9* texture) noexcept;
HRESULT CreateWICTextureFromFileEx(_In_ LPDIRECT3DDEVICE9 d3dDevice,
_In_z_ const wchar_t* fileName,
_In_ size_t maxsize,
_In_ DWORD usage,
_In_ D3DPOOL pool,
_In_ WIC_LOADER_FLAGS loadFlags,
_Outptr_ LPDIRECT3DTEXTURE9* texture) noexcept;
} // namespace DirectX
+25 -4
View File
@@ -16,8 +16,8 @@ int WINAPI WinMain(
)
{
// some constant values
const UINT width = 640;
const UINT height = 480;
const UINT width = 1024;
const UINT height = 768;
const BOOL isFullscreen = FALSE;
UINT error = 0; // error code for identifying errors
@@ -32,6 +32,15 @@ int WINAPI WinMain(
error = d3d.init(window.getWindowHandle(), width, height, isFullscreen);
CheckError(error);
d3d.getDevice()->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
d3d.getDevice()->SetRenderState(D3DRS_LIGHTING, TRUE);
d3d.getDevice()->SetRenderState(D3DRS_SPECULARENABLE, TRUE);
d3d.getDevice()->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL);
d3d.getDevice()->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL);
d3d.getDevice()->SetRenderState(D3DRS_AMBIENTMATERIALSOURCE, D3DMCS_MATERIAL);
d3d.getDevice()->SetRenderState(D3DRS_EMISSIVEMATERIALSOURCE, D3DMCS_MATERIAL);
// 3. create a mesh
Mesh mesh = {};
error = mesh.init(d3d.getDevice());
@@ -39,7 +48,7 @@ int WINAPI WinMain(
// 4. create a camera
Camera camera = {};
error = camera.init(width, height);
error = camera.init(d3d.getDevice(), width, height);
CheckError(error);
// 5. create time
@@ -54,7 +63,19 @@ int WINAPI WinMain(
// 7. create light source
Light light = {};
error = light.init();
D3DLIGHT9 lightData = {};
lightData.Type = D3DLIGHT_POINT;
lightData.Direction = { -1.0f, -1.0f, 1.0f };
lightData.Position = { 1.0f, 1.0f, -1.0f };
lightData.Diffuse = { 0.7f, 0.7f, 0.7f };
lightData.Specular = { 1.0f, 1.0f, 1.0f };
lightData.Range = 100.0f;
lightData.Attenuation0 = 1.0f;
lightData.Attenuation1 = 0.2f;
lightData.Attenuation2 = 0.1f;
error = light.init(lightData);
CheckError(error);
// 8. run application
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 213 KiB

+15 -1
View File
@@ -1,10 +1,12 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36414.22 d17.14
VisualStudioVersion = 17.14.36414.22
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "D3D9", "D3D9\D3D9.vcxproj", "{0A0FC4EF-7B17-42CF-9AC6-B54B176258A5}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "D3D11", "D3D11\D3D11.vcxproj", "{E0259873-82A0-4B75-9F14-B153FCFBC827}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|ARM64 = Debug|ARM64
@@ -27,6 +29,18 @@ Global
{0A0FC4EF-7B17-42CF-9AC6-B54B176258A5}.Release|x64.Build.0 = Release|x64
{0A0FC4EF-7B17-42CF-9AC6-B54B176258A5}.Release|x86.ActiveCfg = Release|Win32
{0A0FC4EF-7B17-42CF-9AC6-B54B176258A5}.Release|x86.Build.0 = Release|Win32
{E0259873-82A0-4B75-9F14-B153FCFBC827}.Debug|ARM64.ActiveCfg = Debug|ARM64
{E0259873-82A0-4B75-9F14-B153FCFBC827}.Debug|ARM64.Build.0 = Debug|ARM64
{E0259873-82A0-4B75-9F14-B153FCFBC827}.Debug|x64.ActiveCfg = Debug|x64
{E0259873-82A0-4B75-9F14-B153FCFBC827}.Debug|x64.Build.0 = Debug|x64
{E0259873-82A0-4B75-9F14-B153FCFBC827}.Debug|x86.ActiveCfg = Debug|Win32
{E0259873-82A0-4B75-9F14-B153FCFBC827}.Debug|x86.Build.0 = Debug|Win32
{E0259873-82A0-4B75-9F14-B153FCFBC827}.Release|ARM64.ActiveCfg = Release|ARM64
{E0259873-82A0-4B75-9F14-B153FCFBC827}.Release|ARM64.Build.0 = Release|ARM64
{E0259873-82A0-4B75-9F14-B153FCFBC827}.Release|x64.ActiveCfg = Release|x64
{E0259873-82A0-4B75-9F14-B153FCFBC827}.Release|x64.Build.0 = Release|x64
{E0259873-82A0-4B75-9F14-B153FCFBC827}.Release|x86.ActiveCfg = Release|Win32
{E0259873-82A0-4B75-9F14-B153FCFBC827}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE