Compare commits

...
15 Commits
Author SHA1 Message Date
david e430508772 add recordings for 03122025 2025-12-03 15:52:07 +01:00
david 0e73ed0ee3 add d3d11 project 2025-12-03 15:50:25 +01:00
david 770c3f790b add light 2025-11-19 13:50:33 +01:00
david 4910894bef add texture mapping 2025-11-12 15:08:57 +01:00
david a39f37ac4e add wall texture
add WICTextureLoader
add uv coordinates
2025-11-12 14:09:20 +01:00
david 6470789977 add vertex color
add time calculation
2025-11-12 13:49:37 +01:00
david 589d0933f4 add input
add time
2025-09-24 15:37:58 +02:00
david 10d4f9fd1b add transformation 2025-09-24 13:35:00 +02:00
david 5322f857d3 add adjust window rect 2025-09-24 13:10:15 +02:00
david 53cf8b96a3 add world matrix
add view matrix
add projection matrix
2025-09-17 16:08:23 +02:00
david e5451c10fc add mesh examples 2025-09-17 14:20:46 +02:00
david 7aa8e8e79c add mesh creation (WIP) 2025-09-10 16:08:11 +02:00
david 3bda921efb add direct3D 2025-09-10 15:24:32 +02:00
david ed7b1816e9 add window message queue 2025-09-10 13:34:42 +02:00
david f98cacdde3 add window (WIP) 2025-09-03 16:10:19 +02:00
60 changed files with 3985 additions and 12 deletions
+28
View File
@@ -0,0 +1,28 @@
#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);
XMStoreFloat4x4(&_viewMatrix, XMMatrixLookToLH(position, forward, up));
// projection matrix
XMMATRIX perspectiveMatrix = XMMatrixPerspectiveFovLH(
XM_PI * 0.3333333f, // field of view in radians, here 60 degrees
static_cast<FLOAT>(width) / static_cast<FLOAT>(height), // aspect ratio
0.3f, 10.0f // near & far clipping planes
);
XMStoreFloat4x4(&_projectionMatrix, perspectiveMatrix);
return 0;
}
void Camera::update(FLOAT dt)
{
}
void Camera::deInit()
{
}
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include <d3d11.h>
#include <DirectXMath.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; }
const XMFLOAT3 getCameraPosition() const { return XMFLOAT3(_viewMatrix._14, _viewMatrix._24, _viewMatrix._34); }
private:
XMFLOAT4X4 _viewMatrix = {};
XMFLOAT4X4 _projectionMatrix = {};
};
Binary file not shown.
+19
View File
@@ -0,0 +1,19 @@
struct PixelInput
{
float4 position : SV_POSITION;
float4 color : COLOR;
};
float4 main(PixelInput INPUT) : SV_TARGET
{
//return float4(1.0f, 1.0f, 1.0f, 1.0f); // solid color
return INPUT.color; // vertex color
//return INPUT.color * 0.5f; // darker vertex color
//return INPUT.color * 2.0f; // lighter vertex color
//float4 color = INPUT.color;
//color.r = 0.0f; // no red channel
//color = 1 - color;
//return color;
}
Binary file not shown.
+26
View File
@@ -0,0 +1,26 @@
cbuffer MatrixBuffer
{
matrix WorldViewProjectionMatrix;
};
struct VertexInput
{
float4 position : POSITION;
float4 color : COLOR;
};
struct VertexOutput
{
float4 position : SV_POSITION;
float4 color : COLOR;
};
VertexOutput main(VertexInput INPUT)
{
VertexOutput OUTPUT;
OUTPUT.position = mul(INPUT.position, WorldViewProjectionMatrix);
OUTPUT.color = INPUT.color;
return OUTPUT;
}
+297
View File
@@ -0,0 +1,297 @@
<?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>{C46808CF-936B-4F98-81C2-1E10D9F1822F}</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>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<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>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<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>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<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="WICTextureLoader11.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="WICTextureLoader11.h" />
<ClInclude Include="Window.h" />
</ItemGroup>
<ItemGroup>
<FxCompile Include="ColorPixelShader.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|Win32'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|x64'">%(Filename).cso</ObjectFileOutput>
</FxCompile>
<FxCompile Include="ColorVertexShader.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|Win32'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|x64'">%(Filename).cso</ObjectFileOutput>
</FxCompile>
<FxCompile Include="LightingPixelShader.hlsl">
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Pixel</ShaderType>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|x64'">%(Filename).cso</ObjectFileOutput>
</FxCompile>
<FxCompile Include="LightingVertexShader.hlsl">
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Vertex</ShaderType>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|x64'">%(Filename).cso</ObjectFileOutput>
</FxCompile>
<FxCompile Include="TexturePixelShader.hlsl">
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Pixel</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Pixel</ShaderType>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|x64'">%(Filename).cso</ObjectFileOutput>
</FxCompile>
<FxCompile Include="TextureVertexShader.hlsl">
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">Vertex</ShaderType>
<ShaderType Condition="'$(Configuration)|$(Platform)'=='Release|x64'">Vertex</ShaderType>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">%(Filename).cso</ObjectFileOutput>
<ObjectFileOutput Condition="'$(Configuration)|$(Platform)'=='Release|x64'">%(Filename).cso</ObjectFileOutput>
</FxCompile>
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
+101
View File
@@ -0,0 +1,101 @@
<?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="WICTextureLoader11.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="WICTextureLoader11.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<FxCompile Include="ColorVertexShader.hlsl">
<Filter>Resource Files</Filter>
</FxCompile>
<FxCompile Include="ColorPixelShader.hlsl">
<Filter>Resource Files</Filter>
</FxCompile>
<FxCompile Include="TexturePixelShader.hlsl">
<Filter>Resource Files</Filter>
</FxCompile>
<FxCompile Include="TextureVertexShader.hlsl">
<Filter>Resource Files</Filter>
</FxCompile>
<FxCompile Include="LightingPixelShader.hlsl">
<Filter>Resource Files</Filter>
</FxCompile>
<FxCompile Include="LightingVertexShader.hlsl">
<Filter>Resource Files</Filter>
</FxCompile>
</ItemGroup>
</Project>
+94
View File
@@ -0,0 +1,94 @@
#include "Direct3D.h"
#include "Utilities.h"
INT Direct3D::init(HWND hWnd, UINT width, UINT height, BOOL isFullscreen)
{
HRESULT hr = {};
// 1. define swap chain description
DXGI_SWAP_CHAIN_DESC swapChainDesc = {};
swapChainDesc.OutputWindow = hWnd; // target window instance handle
swapChainDesc.Windowed = !isFullscreen; // windowed or fullscreen
swapChainDesc.BufferCount = 1; // amount of backbuffers, minimum 1
swapChainDesc.BufferDesc.Width = width;
swapChainDesc.BufferDesc.Height = height;
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; // pixel format, here 4 channels (red, green, blue, alpha) with 8bit depth each and unsigned normalized floating points
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; // which technique is used to render to back buffer
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // what happens to front buffer after swap
swapChainDesc.SampleDesc.Count = 1; // have to be at least one
// 2. create Direct3D device, device context & swap chain
D3D_FEATURE_LEVEL featureLevels[] = {
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0
};
D3D_FEATURE_LEVEL chosenFeatureLevel = {};
hr = D3D11CreateDeviceAndSwapChain(
nullptr, // graphic card, nullptr -> default adapter
D3D_DRIVER_TYPE_HARDWARE, // rendering with hard- or software renderer
nullptr, // software renderer module reference
0, // optional flags
featureLevels, std::size(featureLevels), // which api features are supported
D3D11_SDK_VERSION, &swapChainDesc, &_pDXGISwapChain, &_pD3DDevice, &chosenFeatureLevel, &_pD3DDeviceContext);
CheckFailed(hr, 20);
// 3. create render target
ID3D11Texture2D* pBackBuffer = nullptr;
hr = _pDXGISwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
CheckFailed(hr, 22);
hr = _pD3DDevice->CreateRenderTargetView(pBackBuffer, nullptr, &_pD3DRenderTargetView);
CheckFailed(hr, 24);
safeRelease(pBackBuffer);
// 4. create depth stencil buffer
// 5. create rasterizer state
//d3d.getDevice()->SetRenderState(D3DRS_LIGHTING, TRUE);
//d3d.getDevice()->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
//d3d.getDevice()->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
//d3d.getDevice()->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE, D3DMCS_MATERIAL);
//d3d.getDevice()->SetRenderState(D3DRS_SPECULARMATERIALSOURCE, D3DMCS_MATERIAL);
//d3d.getDevice()->SetRenderState(D3DRS_SPECULARENABLE, TRUE);
// 6. describe viewport
D3D11_VIEWPORT viewport = {};
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
viewport.Width = width;
viewport.Height = height;
// 7. setup render pipeline (device context)
_pD3DDeviceContext->OMSetRenderTargets(1, &_pD3DRenderTargetView, nullptr);
_pD3DDeviceContext->RSSetViewports(1, &viewport);
return 0;
}
void Direct3D::beginScene(FLOAT r, FLOAT g, FLOAT b)
{
// clear back buffer with a solid color
FLOAT backgroundColor[] = { r, g, b, 1.0f };
_pD3DDeviceContext->ClearRenderTargetView(_pD3DRenderTargetView, backgroundColor);
}
void Direct3D::endScene()
{
_pDXGISwapChain->Present(
0, // sync interval, 0,1,2,3,4 -> (de-)active vsync setting and how often should be synced
0 // optional flags
);
}
void Direct3D::deInit()
{
safeRelease(_pD3DRenderTargetView);
safeRelease(_pDXGISwapChain);
safeRelease(_pD3DDeviceContext);
safeRelease(_pD3DDevice);
}
+23
View File
@@ -0,0 +1,23 @@
#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(FLOAT r, FLOAT g, FLOAT b);
void endScene();
void deInit();
ID3D11Device* getDevice() const { return _pD3DDevice; }
ID3D11DeviceContext* getDeviceContext() const { return _pD3DDeviceContext; }
private:
ID3D11Device* _pD3DDevice = nullptr; // needed for creating all objects, e.g. buffer, textures, etc., used in init phase
ID3D11DeviceContext* _pD3DDeviceContext = nullptr; // access to render pipeline, e.g. set matrices or draw command, used in run phase
IDXGISwapChain* _pDXGISwapChain = nullptr; // holds references to front & back buffer & swaps them
ID3D11RenderTargetView* _pD3DRenderTargetView = nullptr; // target device context is rendering to
};
+33
View File
@@ -0,0 +1,33 @@
#include "Light.h"
#include "Utilities.h"
UINT Light::init(ID3D11Device* pD3DDevice, LightBuffer& lightData)
{
D3D11_BUFFER_DESC desc = {};
desc.ByteWidth = sizeof(LightBuffer);
desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
desc.Usage = D3D11_USAGE_IMMUTABLE; // no light update possible
//desc.Usage = D3D11_USAGE_DYNAMIC; // light update possible
D3D11_SUBRESOURCE_DATA initialData = {};
initialData.pSysMem = &lightData;
HRESULT hr = pD3DDevice->CreateBuffer(&desc, &initialData, &_pLightBuffer);
CheckFailed(hr, 70);
return 0;
}
void Light::update(FLOAT dt)
{
}
void Light::render(ID3D11DeviceContext* pD3DDeviceContext)
{
pD3DDeviceContext->PSSetConstantBuffers(0, 1, &_pLightBuffer);
}
void Light::deInit()
{
safeRelease(_pLightBuffer);
}
+28
View File
@@ -0,0 +1,28 @@
#pragma once
#include <d3d11.h>
#include <DirectXMath.h>
using namespace DirectX;
class Light
{
public:
struct LightBuffer
{
XMFLOAT3 LightVector;
FLOAT LightIntensity;
XMFLOAT4 DiffuseColor;
XMFLOAT4 SpecularColor;
XMFLOAT3 CameraPosition;
FLOAT Phong;
};
UINT init(ID3D11Device* pD3DDevice, LightBuffer& lightData);
void update(FLOAT dt);
void render(ID3D11DeviceContext* pD3DDeviceContext);
void deInit();
private:
ID3D11Buffer* _pLightBuffer = nullptr;
};
Binary file not shown.
+45
View File
@@ -0,0 +1,45 @@
Texture2D MainTexture;
SamplerState MainSampler;
cbuffer LightBuffer // has to be always 16 byte aligned
{
float3 LightVector;
float LightIntensity;
float4 DiffuseColor;
float4 SpecularColor;
float3 CameraPosition;
float Phong;
};
struct PixelInput
{
float4 position : SV_POSITION;
float3 positionWorld : POSITION1;
float3 normal : NORMAL;
float2 uv : TEXCOORD;
};
float4 main(PixelInput INPUT) : SV_TARGET
{
float4 texColor = MainTexture.Sample(MainSampler, INPUT.uv);
float4 ambientColor = float4(0.2f, 0.2f, 0.2f, 1.0f);
float4 diffuseColor = DiffuseColor;
float4 specularColor = SpecularColor;
float4 emissionColor = float4(0.0f, 0.0f, 0.0f, 1.0f);
float3 lightVector = normalize(-LightVector);
float3 normalVector = normalize(INPUT.normal);
// diffuse color
float diffuse = dot(lightVector, normalVector); // diffuse intensity
diffuseColor *= diffuse * LightIntensity;
// specular color
float3 reflectVector = normalize(reflect(-lightVector, normalVector));
//float3 reflectVector = 2 * normalVector * diffuse - lightVector;
float3 viewVector = normalize(CameraPosition - INPUT.positionWorld);
float specular = pow(max(dot(reflectVector, viewVector), 0), Phong);
specularColor *= specular * LightIntensity;
return saturate(saturate(texColor * saturate(ambientColor + diffuseColor) + specularColor) + emissionColor);
}
Binary file not shown.
+33
View File
@@ -0,0 +1,33 @@
cbuffer MatrixBuffer
{
matrix WorldViewProjectionMatrix;
matrix WorldMatrix;
//float4 TilingOffset;
};
struct VertexInput
{
float4 position : POSITION;
float3 normal : NORMAL;
float2 uv : TEXCOORD;
};
struct VertexOutput
{
float4 position : SV_POSITION;
float3 positionWorld : POSITION1;
float3 normal : NORMAL;
float2 uv : TEXCOORD;
};
VertexOutput main(VertexInput INPUT)
{
VertexOutput OUTPUT;
OUTPUT.position = mul(INPUT.position, WorldViewProjectionMatrix);
OUTPUT.positionWorld = mul(INPUT.position, WorldMatrix);
OUTPUT.normal = mul(INPUT.normal, (float3x3)WorldMatrix);
OUTPUT.uv = INPUT.uv * float2(1.0f, 1.0f) + float2(0.0f, 0.0f); // uv * tiling + offset
return OUTPUT;
}
+194
View File
@@ -0,0 +1,194 @@
#include "Material.h"
#include "Utilities.h"
#include "WICTextureLoader11.h"
using namespace DirectX;
UINT Material::init(ID3D11Device* pD3DDevice, LPCTSTR textureFileName)
{
UINT error = 0;
error = createVertexShader(pD3DDevice);
CheckError(error);
error = createPixelShader(pD3DDevice);
CheckError(error);
error = createMatrixBuffer(pD3DDevice);
CheckError(error);
error = createTextureAndSamplerState(pD3DDevice, textureFileName);
CheckError(error);
return 0;
}
void Material::render(ID3D11DeviceContext* pD3DDeviceContext)
{
// set shader stages
pD3DDeviceContext->VSSetShader(_pVertexShader, nullptr, 0);
pD3DDeviceContext->PSSetShader(_pPixelShader, nullptr, 0);
// set input layout
pD3DDeviceContext->IASetInputLayout(_pInputLayout);
// set shader resources
pD3DDeviceContext->VSSetConstantBuffers(0, 1, &_pMatrixBuffer);
// set texture
pD3DDeviceContext->PSSetShaderResources(0, 1, &_pTexture);
// set sampler state
pD3DDeviceContext->PSSetSamplers(0, 1, &_pSamplerState);
}
void Material::deInit()
{
safeRelease(_pSamplerState);
safeRelease(_pTexture);
safeRelease(_pMatrixBuffer);
safeRelease(_pInputLayout);
safeRelease(_pPixelShader);
safeRelease(_pVertexShader);
}
void Material::setMatrixBuffer(ID3D11DeviceContext* pD3DDeviceContext, const XMFLOAT4X4& worldMatrix, const XMFLOAT4X4& viewMatrix, const XMFLOAT4X4& projectionMatrix)
{
// unpack matrix data
XMMATRIX w = XMLoadFloat4x4(&worldMatrix);
XMMATRIX v = XMLoadFloat4x4(&viewMatrix);
XMMATRIX p = XMLoadFloat4x4(&projectionMatrix);
XMMATRIX wvp = w * v * p;
// set matrix data
D3D11_MAPPED_SUBRESOURCE bufferData = {};
HRESULT hr = pD3DDeviceContext->Map(_pMatrixBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &bufferData);
if (FAILED(hr)) return;
MatrixBuffer* matrixBuffer = static_cast<MatrixBuffer*>(bufferData.pData);
XMStoreFloat4x4(static_cast<XMFLOAT4X4*>(&matrixBuffer->WorldViewProjectionMatrix), XMMatrixTranspose(wvp));
XMStoreFloat4x4(static_cast<XMFLOAT4X4*>(&matrixBuffer->WorldMatrix), XMMatrixTranspose(w));
pD3DDeviceContext->Unmap(_pMatrixBuffer, 0);
}
UINT Material::createVertexShader(ID3D11Device* pD3DDevice)
{
HRESULT hr = {};
ID3DBlob* pCompiledShaderCode = nullptr;
// part 1 get compiled shader code
// option 1: load high level shader code & compile
//hr = D3DCompileFromFile(
// L"ColorVertexShader.hlsl", // shader file name
// nullptr, // optional macro defines
// nullptr, // pre compiled included shader code
// "main", // shader entry point (start function)
// "vs_4_0", // shader type & version
// 0, 0, // optional flags
// &pCompiledShaderCode, // compiled shader code memory
// nullptr // error messages
//);
// option 2: load compiled shader code
//hr = D3DReadFileToBlob(L"ColorVertexShader.cso", &pCompiledShaderCode);
//hr = D3DReadFileToBlob(L"TextureVertexShader.cso", &pCompiledShaderCode);
hr = D3DReadFileToBlob(L"LightingVertexShader.cso", &pCompiledShaderCode);
CheckFailed(hr, 60);
// part 2 create vertex shader object
hr = pD3DDevice->CreateVertexShader(pCompiledShaderCode->GetBufferPointer(), pCompiledShaderCode->GetBufferSize(), nullptr, &_pVertexShader);
CheckFailed(hr, 62);
UINT error = createInputLayout(pD3DDevice, pCompiledShaderCode);
CheckError(error);
safeRelease(pCompiledShaderCode);
return 0;
}
UINT Material::createPixelShader(ID3D11Device* pD3DDevice)
{
HRESULT hr = {};
ID3DBlob* pCompiledShaderCode = nullptr;
//hr = D3DReadFileToBlob(L"ColorPixelShader.cso", &pCompiledShaderCode);
//hr = D3DReadFileToBlob(L"TexturePixelShader.cso", &pCompiledShaderCode);
hr = D3DReadFileToBlob(L"LightingPixelShader.cso", &pCompiledShaderCode);
CheckFailed(hr, 64);
hr = pD3DDevice->CreatePixelShader(pCompiledShaderCode->GetBufferPointer(), pCompiledShaderCode->GetBufferSize(), nullptr, &_pPixelShader);
CheckFailed(hr, 66);
safeRelease(pCompiledShaderCode);
return 0;
}
UINT Material::createInputLayout(ID3D11Device* pD3DDevice, ID3DBlob* pCompiledVertexShaderCode)
{
// https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-semantics
D3D11_INPUT_ELEMENT_DESC elements[4] = {};
// position
elements[0].SemanticName = "POSITION";
elements[0].Format = DXGI_FORMAT_R32G32B32_FLOAT;
// normal
elements[1].SemanticName = "NORMAL";
elements[1].Format = DXGI_FORMAT_R32G32B32_FLOAT;
elements[1].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
// uv
elements[2].SemanticName = "TEXCOORD";
elements[2].Format = DXGI_FORMAT_R32G32_FLOAT;
elements[2].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
// color
elements[3].SemanticName = "COLOR";
elements[3].Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
elements[3].AlignedByteOffset = D3D11_APPEND_ALIGNED_ELEMENT;
HRESULT hr = pD3DDevice->CreateInputLayout(elements, std::size(elements), pCompiledVertexShaderCode->GetBufferPointer(), pCompiledVertexShaderCode->GetBufferSize(), &_pInputLayout);
CheckFailed(hr, 68);
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;
HRESULT hr = pD3DDevice->CreateBuffer(&desc, nullptr, &_pMatrixBuffer);
CheckFailed(hr, 61);
return 0;
}
UINT Material::createTextureAndSamplerState(ID3D11Device* pD3DDevice, LPCTSTR textureFileName)
{
// load texture
HRESULT hr = CreateWICTextureFromFile(pD3DDevice, textureFileName, nullptr, &_pTexture);
CheckFailed(hr, 63);
// create sampler state
D3D11_SAMPLER_DESC samplerDesc = {};
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; // CAUTION: has to be set always
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
hr = pD3DDevice->CreateSamplerState(&samplerDesc, &_pSamplerState);
CheckFailed(hr, 65);
return 0;
}
+40
View File
@@ -0,0 +1,40 @@
#pragma once
#include <d3d11.h>
#include <d3dcompiler.h>
#include <DirectXMath.h>
using namespace DirectX;
#pragma comment(lib, "d3dcompiler.lib")
class Material
{
public:
UINT init(ID3D11Device* pD3DDevice, LPCTSTR textureFileName);
void render(ID3D11DeviceContext* pD3DDeviceContext);
void deInit();
void setMatrixBuffer(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* pCompiledVertexShaderCode);
UINT createMatrixBuffer(ID3D11Device* pD3DDevice);
UINT createTextureAndSamplerState(ID3D11Device* pD3DDevice, LPCTSTR textureFileName);
ID3D11VertexShader* _pVertexShader = nullptr;
ID3D11PixelShader* _pPixelShader = nullptr;
ID3D11InputLayout* _pInputLayout = nullptr; // byte structure of vertex
struct MatrixBuffer
{
XMFLOAT4X4 WorldViewProjectionMatrix;
XMFLOAT4X4 WorldMatrix;
};
ID3D11Buffer* _pMatrixBuffer = nullptr;
ID3D11ShaderResourceView* _pTexture = {};
ID3D11SamplerState* _pSamplerState = {};
};
+129
View File
@@ -0,0 +1,129 @@
#include "Mesh.h"
#include "Utilities.h"
#include "Vertex.h"
#include <DirectXMath.h>
using namespace DirectX;
UINT Mesh::init(ID3D11Device* pD3DDevice)
{
UINT error = 0;
error = createVertexBuffer(pD3DDevice);
CheckError(error);
error = createIndexBuffer(pD3DDevice);
CheckError(error);
// create world matrix
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 rot = 0.0f;
rot += 1.0f * dt;
FLOAT move = 1.0f * dt;
if ((GetAsyncKeyState(VK_LEFT) & 0x8000) || (GetAsyncKeyState('A') & 0x8000)) x -= move;
if ((GetAsyncKeyState(VK_RIGHT) & 0x8000) || (GetAsyncKeyState('D') & 0x8000)) x += move;
if ((GetAsyncKeyState(VK_UP) & 0x8000) || (GetAsyncKeyState('W') & 0x8000)) y += move;
if ((GetAsyncKeyState(VK_DOWN) & 0x8000) || (GetAsyncKeyState('S') & 0x8000)) y -= move;
if ((GetAsyncKeyState(VK_ADD) & 0x8000) || (GetAsyncKeyState('Q') & 0x8000)) z -= move;
if ((GetAsyncKeyState(VK_SUBTRACT) & 0x8000) || (GetAsyncKeyState('E') & 0x8000)) z += move;
XMMATRIX translation = XMMatrixTranslation(x, y, z);
XMMATRIX rotation = XMMatrixRotationRollPitchYaw(rot, 0.0f, rot);
XMMATRIX scale = XMMatrixScaling(1.0f, 1.0f, 1.0f);
XMVECTOR det = XMMatrixDeterminant(translation);
XMStoreFloat4x4(&_worldMatrix, scale * rotation * translation);
}
void Mesh::render(ID3D11DeviceContext* pD3DDeviceContext)
{
// set data
static UINT offset = 0;
pD3DDeviceContext->IASetVertexBuffers(0, 1, &_pVertexBuffer, &_vertexStride, &offset);
pD3DDeviceContext->IASetIndexBuffer(_pIndexBuffer, DXGI_FORMAT_R16_UINT, 0);
pD3DDeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
// draw
pD3DDeviceContext->DrawIndexed(_indexCount, 0, 0);
}
void Mesh::deInit()
{
safeRelease(_pIndexBuffer);
safeRelease(_pVertexBuffer);
}
UINT Mesh::createVertexBuffer(ID3D11Device* pD3DDevice)
{
// describe vertex buffer content
//// quad with color
//Vertex vertices[] = { Vertex(-0.5f, 0.5f, 0.0f, 255, 0, 0),
//Vertex(0.5f, 0.5f, 0.0f, 0, 255, 0),
//Vertex(0.5f, -0.5f, 0.0f, 255, 0, 255),
//Vertex(-0.5f, -0.5f, 0.0f, 0, 0, 255) };
// quad with uv & normal
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)
};
// general data
_vertexCount = std::size(vertices);
_vertexStride = sizeof(Vertex);
// create vertex buffer object
D3D11_BUFFER_DESC desc = {};
desc.ByteWidth = _vertexCount * _vertexStride; // size of vertex buffer in bytes
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
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, 30);
return 0;
}
UINT Mesh::createIndexBuffer(ID3D11Device* pD3DDevice)
{
// describe index buffer content
WORD indices[] = {
0,1,2,
0,2,3
};
// general data
_indexCount = std::size(indices);
// create index buffer object
D3D11_BUFFER_DESC desc = {};
desc.ByteWidth = _indexCount * sizeof(WORD); // size of index buffer in bytes
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
desc.Usage = D3D11_USAGE_IMMUTABLE;
D3D11_SUBRESOURCE_DATA data = {};
data.pSysMem = indices;
HRESULT hr = pD3DDevice->CreateBuffer(&desc, &data, &_pIndexBuffer);
CheckFailed(hr, 32);
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.
+13
View File
@@ -0,0 +1,13 @@
Texture2D MainTexture;
SamplerState MainSampler;
struct PixelInput
{
float4 position : SV_POSITION;
float2 uv : TEXCOORD;
};
float4 main(PixelInput INPUT) : SV_TARGET
{
return MainTexture.Sample(MainSampler, INPUT.uv);
}
Binary file not shown.
+27
View File
@@ -0,0 +1,27 @@
cbuffer MatrixBuffer
{
matrix WorldViewProjectionMatrix;
//float4 TilingOffset;
};
struct VertexInput
{
float4 position : POSITION;
float2 uv : TEXCOORD;
};
struct VertexOutput
{
float4 position : SV_POSITION;
float2 uv : TEXCOORD;
};
VertexOutput main(VertexInput INPUT)
{
VertexOutput OUTPUT;
OUTPUT.position = mul(INPUT.position, WorldViewProjectionMatrix);
OUTPUT.uv = INPUT.uv * float2(1.0f, 1.0f) + float2(0.0f, 0.0f); // uv * tiling + offset
return OUTPUT;
}
+34
View File
@@ -0,0 +1,34 @@
#include "Time.h"
#include <string>
UINT Time::init()
{
_lastTime = CLOCK::now();
return 0;
}
void Time::update()
{
TIME_POINT now = CLOCK::now();
SECONDS diff = now - _lastTime;
_deltaTime = diff.count();
_lastTime = now;
#ifdef _DEBUG
#ifdef UNICODE
wstring output = L"fps: " + to_wstring(1 / _deltaTime) + L"\n";
OutputDebugString(output.c_str());
#else // !UNICODE
string output = "fps: " + to_string(1 / _deltaTime) + "\n";
OutputDebugString(output.c_str());
#endif // UNICODE
#endif // DEBUG
}
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 CLOCK::time_point TIME_POINT;
typedef chrono::duration<FLOAT> SECONDS;
class Time
{
public:
UINT init();
void update();
void deInit();
FLOAT getDeltaTime() const { return _deltaTime; }
private:
FLOAT _deltaTime = 0.0f;
TIME_POINT _lastTime = {};
};
+14
View File
@@ -0,0 +1,14 @@
#include "Utilities.h"
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();
#else // UNICODE
msg = (std::string(msg) + std::to_string(error)).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;
}
}
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include <d3d11.h>
#include <DirectXMath.h>
using namespace DirectX;
struct Vertex
{
XMFLOAT3 position;
XMFLOAT3 normal;
XMFLOAT2 uv;
XMFLOAT4 color;
Vertex() : position(0.0f, 0.0f, 0.0f), normal(0.0f, 0.0f, 0.0f), uv(0.0f, 0.0f), color(1.0f, 1.0f, 1.0f, 1.0f) {}
Vertex(FLOAT x, FLOAT y, FLOAT z) : position(x, y, z), normal(0.0f, 0.0f, 0.0f), uv(0.0f, 0.0f), color(1.0f, 1.0f, 1.0f, 1.0f) {}
Vertex(FLOAT x, FLOAT y, FLOAT z, UINT r, UINT g, UINT b)
: position(x, y, z), normal(0.0f, 0.0f, 0.0f), uv(0.0f, 0.0f), color(r / 255.0f, g / 255.0f, b / 255.0f, 1.0f) {}
Vertex(FLOAT x, FLOAT y, FLOAT z, FLOAT u, FLOAT v) : position(x, y, z), normal(0.0f, 0.0f, 0.0f), uv(u, v), color(1.0f, 1.0f, 1.0f, 1.0f) {}
Vertex(FLOAT x, FLOAT y, FLOAT z, FLOAT nx, FLOAT ny, FLOAT nz, FLOAT u, FLOAT v) : position(x, y, z), normal(nx, ny, nz), uv(u, v), color(1.0f, 1.0f, 1.0f, 1.0f) {}
};
File diff suppressed because it is too large Load Diff
+148
View File
@@ -0,0 +1,148 @@
//--------------------------------------------------------------------------------------
// File: WICTextureLoader11.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
//
// Warning: CreateWICTexture* functions are not thread-safe if given a d3dContext instance for
// auto-gen mipmap support.
//
// 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.
//
// http://go.microsoft.com/fwlink/?LinkId=248926
// http://go.microsoft.com/fwlink/?LinkId=248929
//--------------------------------------------------------------------------------------
#pragma once
#include <d3d11_1.h>
#pragma comment(lib,"dxguid.lib")
#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_FORCE_SRGB = 0x1,
WIC_LOADER_IGNORE_SRGB = 0x2,
WIC_LOADER_SRGB_DEFAULT = 0x4,
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"
#endif
DEFINE_ENUM_FLAG_OPERATORS(WIC_LOADER_FLAGS)
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#endif
// Standard version
HRESULT CreateWICTextureFromMemory(
_In_ ID3D11Device* d3dDevice,
_In_reads_bytes_(wicDataSize) const uint8_t* wicData,
_In_ size_t wicDataSize,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0) noexcept;
HRESULT CreateWICTextureFromFile(
_In_ ID3D11Device* d3dDevice,
_In_z_ const wchar_t* szFileName,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0) noexcept;
// Standard version with optional auto-gen mipmap support
HRESULT CreateWICTextureFromMemory(
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
_In_reads_bytes_(wicDataSize) const uint8_t* wicData,
_In_ size_t wicDataSize,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0) noexcept;
HRESULT CreateWICTextureFromFile(
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
_In_z_ const wchar_t* szFileName,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView,
_In_ size_t maxsize = 0) noexcept;
// Extended version
HRESULT CreateWICTextureFromMemoryEx(
_In_ ID3D11Device* d3dDevice,
_In_reads_bytes_(wicDataSize) const uint8_t* wicData,
_In_ size_t wicDataSize,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ WIC_LOADER_FLAGS loadFlags,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept;
HRESULT CreateWICTextureFromFileEx(
_In_ ID3D11Device* d3dDevice,
_In_z_ const wchar_t* szFileName,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ WIC_LOADER_FLAGS loadFlags,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept;
// Extended version with optional auto-gen mipmap support
HRESULT CreateWICTextureFromMemoryEx(
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
_In_reads_bytes_(wicDataSize) const uint8_t* wicData,
_In_ size_t wicDataSize,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ WIC_LOADER_FLAGS loadFlags,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept;
HRESULT CreateWICTextureFromFileEx(
_In_ ID3D11Device* d3dDevice,
_In_opt_ ID3D11DeviceContext* d3dContext,
_In_z_ const wchar_t* szFileName,
_In_ size_t maxsize,
_In_ D3D11_USAGE usage,
_In_ unsigned int bindFlags,
_In_ unsigned int cpuAccessFlags,
_In_ unsigned int miscFlags,
_In_ WIC_LOADER_FLAGS loadFlags,
_Outptr_opt_ ID3D11Resource** texture,
_Outptr_opt_ ID3D11ShaderResourceView** textureView) noexcept;
}
+99
View File
@@ -0,0 +1,99 @@
#include "Window.h"
INT Window::init(HINSTANCE hInstance, UINT width, UINT height)
{
// 1. describe window class
WNDCLASS wc = {};
wc.hInstance = hInstance; // application instance
wc.lpszClassName = TEXT("D3D11"); // name of window class
wc.lpfnWndProc = WindowProc; // message queue handler function
wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // behaviour style and not visual style
wc.hbrBackground = CreateSolidBrush(RGB(255,0,0)); // set window background color
wc.hCursor = LoadCursor(nullptr, IDC_ARROW); // set window cursor
wc.hIcon = LoadIcon(nullptr, IDI_APPLICATION); // set window icon
// 2. register window class
if (!RegisterClass(&wc)) return 10;
// 3. adjust window size (optional)
DWORD style = WS_POPUP;
RECT rect = { 100, 100, width + 100, height + 100 }; // left-top corner, right-bottom corner
AdjustWindowRect(&rect, style, FALSE);
// 4. create window instance
_hWnd = CreateWindow(
wc.lpszClassName, // name of window class
wc.lpszClassName, // window title
style, // visual window style
rect.left, rect.top, // window position
rect.right - rect.left, rect.bottom - rect.top, // window size
nullptr, // parent window handle
nullptr, // menu instance handle
hInstance, // application instance
nullptr // optional parameter
);
if (_hWnd == nullptr) return 12;
// 5. show window
ShowWindow(_hWnd, SW_SHOW);
SetFocus(_hWnd);
return 0;
}
BOOL Window::run()
{
// 6. run window
// message queue
// GetMessage - event based message method, return something if a new a message occur
// PeekMessage - returns a boolean, to signale if a message is available or not
// TranslateMessage - translate hardware keyboard codes (scan code) into virtual key table
// DispatchMessage - send message to WindowProc
// https://learn.microsoft.com/en-us/windows/win32/winmsg/messages-and-message-queues
MSG msg = {};
if (PeekMessage(&msg, nullptr, 0, UINT_MAX, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
Sleep(10);
return msg.message != WM_QUIT;
}
void Window::deInit()
{
}
LRESULT WindowProc(
HWND hWnd, // handle to window instance
UINT msg, // message id
WPARAM wParam, // main paramater
LPARAM lParam // additional parameters
)
{
switch (msg)
{
case WM_CLOSE:
DestroyWindow(hWnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
case WM_KEYDOWN:
if (wParam == VK_ESCAPE) DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return 0;
}
+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);
+115
View File
@@ -0,0 +1,115 @@
#include <Windows.h>
#include <random>
#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 = 640;
const UINT height = 480;
const BOOL isFullscreen = FALSE;
const INT r = 0;
const INT g = 0;
const INT b = 0;
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 = {};
Light::LightBuffer lightData = {};
//directional light
lightData.LightVector = { 1.0f, -1.0f, 1.0f };
//lightData.Type = D3DLIGHT_POINT;
//lightData.Position = { 0.0f, 0.0f, -1.0f };
//lightData.Range = 10.0f;
//lightData.Falloff = 1.0f;
//lightData.Attenuation0 = 1.0f;
//lightData.Attenuation1 = 0.2f;
//lightData.Attenuation2 = 0.1f;
lightData.DiffuseColor = { 1.0f, 1.0f, 1.0f, 1.0f };
lightData.SpecularColor = { 1.0f, 0.0f, 1.0f, 1.0f };
lightData.LightIntensity = 1.0f;
lightData.Phong = 8.0f;
lightData.CameraPosition = { 0.0f, 0.0f, -1.0f };
error = light.init(d3d.getDevice(), lightData);
CheckError(error);
// 8. run application
// random colors
//std::default_random_engine e;
//std::uniform_real_distribution<FLOAT> d(0.0f, 1.0f);
while (window.run())
{
// 8.1. update objects
time.update();
mesh.update(time.getDeltaTime());
camera.update(time.getDeltaTime());
light.update(time.getDeltaTime());
// 8.2. render objects
//d3d.beginScene(d(e), d(e), d(e));
d3d.beginScene(r, g, b);
light.render(d3d.getDeviceContext());
material.setMatrixBuffer(d3d.getDeviceContext(), mesh.getWorldMatrix(), camera.getViewMatrix(), camera.getProjectionMatrix());
material.render(d3d.getDeviceContext());
mesh.render(d3d.getDeviceContext());
d3d.endScene();
}
// 9. tidy up
light.deInit();
time.deInit();
camera.deInit();
material.deInit();
mesh.deInit();
d3d.deInit();
window.deInit();
return 0;
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 213 KiB

+24 -1
View File
@@ -1,12 +1,35 @@
#include "Camera.h"
#include <DirectXMath.h>
using namespace DirectX;
UINT Camera::init(UINT width, UINT height)
{
// view matrix
XMVECTOR position = XMVectorSet(0.0f, 0.0f, -2.0f, 0.0f); // camera position
XMVECTOR forward = XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f); // camera forward vector
XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f); // camera up vector
XMMATRIX viewMatrix = XMMatrixLookToLH(position, forward, up);
XMStoreFloat4x4(reinterpret_cast<XMFLOAT4X4*>(&_viewMatrix), viewMatrix);
// projection matrix
FLOAT fov = XM_PI * 0.3333333f; // field of view
FLOAT aspectRatio = static_cast<FLOAT>(width) / static_cast<FLOAT>(height); // CAUTION: UINT / UINT => UINT
FLOAT nearClippingPlane = 0.3f;
FLOAT farClippingPlane = 100.0f;
XMMATRIX projectionMatrix = XMMatrixPerspectiveFovLH(fov, aspectRatio, nearClippingPlane, farClippingPlane);
XMStoreFloat4x4(reinterpret_cast<XMFLOAT4X4*>(&_projectionMatrix), projectionMatrix);
return 0;
}
void Camera::update(FLOAT dt)
void Camera::update(FLOAT dt, IDirect3DDevice9* pD3DDevice)
{
pD3DDevice->SetTransform(D3DTS_VIEW, &_viewMatrix);
pD3DDevice->SetTransform(D3DTS_PROJECTION, &_projectionMatrix);
}
void Camera::deInit()
+1 -1
View File
@@ -5,7 +5,7 @@ class Camera
{
public:
UINT init(UINT width, UINT height);
void update(FLOAT dt);
void update(FLOAT dt, IDirect3DDevice9* pD3DDevice);
void deInit();
private:
+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>
+51
View File
@@ -1,28 +1,79 @@
#include "Direct3D.h"
#include "Utilities.h"
#include <random>
INT Direct3D::init(HWND hWnd, UINT width, UINT height, BOOL isFullscreen)
{
// 1. create connection to Direct3D API
IDirect3D9* pD3D = Direct3DCreate9(D3D_SDK_VERSION);
if (pD3D == nullptr) return 200;
// 2. check compatibility
UINT adapter = D3DADAPTER_DEFAULT; // graphic card index
D3DDEVTYPE devType = D3DDEVTYPE_HAL; // hardware type, hardware or software renderer
D3DCAPS9 caps = {};
HRESULT hr = pD3D->GetDeviceCaps(adapter, devType, &caps);
CheckFailed(hr, 210);
// support for fixed functiuon pipeline
DWORD vertexProcessing = D3DCREATE_SOFTWARE_VERTEXPROCESSING; // fallback
if (caps.VertexProcessingCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
{
// hardware support for fixed function pipeline
vertexProcessing = D3DCREATE_HARDWARE_VERTEXPROCESSING;
}
// 3. define presentation parameters
D3DPRESENT_PARAMETERS d3dpp = {};
d3dpp.hDeviceWindow = hWnd; // target window to draw into
d3dpp.Windowed = !isFullscreen; // fullscreen window?
d3dpp.BackBufferCount = 1; // at least 1
d3dpp.BackBufferWidth = width;
d3dpp.BackBufferHeight = height;
d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8; // back buffer pixel format
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; // what happen to front buffer after swap
// 4. create Direct3D device
hr = pD3D->CreateDevice(
adapter, // graphic adapter index
devType, // hardware device type
hWnd, // target window handle
vertexProcessing, // optional flags, here important for fixed function pipeline support
&d3dpp, &_pD3DDevice
);
CheckFailed(hr, 220);
// 5. tidy up
safeRelease(pD3D);
return 0;
}
void Direct3D::beginScene()
{
_pD3DDevice->BeginScene(); // draw calls only after this call
// clear back buffer
static std::default_random_engine e;
static std::uniform_int_distribution<UINT> d(0, 255);
_pD3DDevice->Clear(
0, nullptr, // clear specific areas only
D3DCLEAR_TARGET, // what to clear
D3DCOLOR_XRGB(255, 255, 255), 1.0f, 0xFFFFFFFF // how to clear
);
}
void Direct3D::endScene()
{
_pD3DDevice->EndScene(); // draw calls only before this call
// swap front with back buffer
_pD3DDevice->Present(nullptr, nullptr, nullptr, nullptr);
}
void Direct3D::deInit()
{
safeRelease(_pD3DDevice);
}
+2 -1
View File
@@ -14,6 +14,7 @@ public:
IDirect3DDevice9* getDevice() const { return _pD3DDevice; }
private:
IDirect3DDevice9* _pD3DDevice = nullptr; // our interface for api communication
// COM - Component Object Model
IDirect3DDevice9* _pD3DDevice = nullptr; // our interface for graphic card communication
};
+6 -1
View File
@@ -1,7 +1,10 @@
#include "Light.h"
UINT Light::init()
UINT Light::init(D3DLIGHT9& lightData, UINT id)
{
_lightData = lightData;
_id = id;
return 0;
}
@@ -11,6 +14,8 @@ void Light::update(FLOAT dt)
void Light::render(IDirect3DDevice9* pD3DDevice)
{
pD3DDevice->SetLight(_id, &_lightData);
pD3DDevice->LightEnable(_id, TRUE);
}
void Light::deInit()
+5 -1
View File
@@ -4,9 +4,13 @@
class Light
{
public:
UINT init();
UINT init(D3DLIGHT9& lightData, UINT id = 0);
void update(FLOAT dt);
void render(IDirect3DDevice9* pD3DDevice);
void deInit();
private:
D3DLIGHT9 _lightData = {};
UINT _id = 0;
};
+27 -1
View File
@@ -1,13 +1,39 @@
#include "Material.h"
#include "Utilities.h"
UINT Material::init(IDirect3DDevice9* pD3DDevice, LPCTSTR textureFileName)
#include "WICTextureLoader9.h"
using namespace DirectX;
UINT Material::init(IDirect3DDevice9* pD3DDevice, LPCWSTR textureFileName)
{
// load texture
HRESULT hr = CreateWICTextureFromFile(pD3DDevice, textureFileName, &_pTexture, 0, WIC_LOADER_MIP_AUTOGEN);
CheckFailed(hr, 600);
// 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.Emissive = { 0.0f, 0.0f, 0.0f, 1.0f };
material.Power = 1024.0f;
pD3DDevice->SetMaterial(&material);
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_BORDERCOLOR, D3DCOLOR_XRGB(255, 0, 255));
pD3DDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_POINT);
pD3DDevice->SetSamplerState(0, D3DSAMP_MAXMIPLEVEL, 0);
}
void Material::deInit()
+2 -2
View File
@@ -4,11 +4,11 @@
class Material
{
public:
UINT init(IDirect3DDevice9* pD3DDevice, LPCTSTR textureFileName);
UINT init(IDirect3DDevice9* pD3DDevice, LPCWSTR textureFileName);
void render(IDirect3DDevice9* pD3DDevice);
void deInit();
private:
IDirect3DTexture9* _texture = {};
IDirect3DTexture9* _pTexture = {};
};
+183
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,59 @@ UINT Mesh::init(IDirect3DDevice9* pD3DDevice)
error = createIndexBuffer(pD3DDevice);
CheckError(error);
// identity matrix
XMMATRIX identityMatrix = XMMatrixIdentity();
XMFLOAT4X4 worldMatrix;
XMStoreFloat4x4(&worldMatrix, identityMatrix);
D3DMATRIX* pWorldMatrix = reinterpret_cast<D3DMATRIX*>(&worldMatrix);
_worldMatrix = *pWorldMatrix;
return 0;
}
void Mesh::update(FLOAT dt)
{
static FLOAT x = 0.0f;
static FLOAT y = 0.0f;
static FLOAT z = 0.0f;
static FLOAT pitch = 0.0f;
static FLOAT yaw = 0.0f;
static FLOAT roll = 0.0f;
static FLOAT scale = 1.0f;
//yaw += 1.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('Q') & 0x8000) z -= move;
if (GetAsyncKeyState('E') & 0x8000) z += move;
XMMATRIX translationMatrix = XMMatrixTranslation(x, y, z);
XMMATRIX rotationMatrix = XMMatrixRotationRollPitchYaw(pitch, yaw, roll);
XMMATRIX scaleMatrix = XMMatrixScaling(scale, scale, scale);
XMStoreFloat4x4(reinterpret_cast<XMFLOAT4X4*>(&_worldMatrix), scaleMatrix * rotationMatrix * translationMatrix);
}
void Mesh::render(IDirect3DDevice9* pD3DDevice)
{
// 1. set mesh data
pD3DDevice->SetStreamSource(0, _pVertexBuffer, 0, _vertexStride);
pD3DDevice->SetFVF(FVF);
pD3DDevice->SetIndices(_pIndexBuffer);
pD3DDevice->SetTransform(D3DTS_WORLD, &_worldMatrix);
// 2. draw call
//pD3DDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, _vertexCount / 3);
//pD3DDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, _vertexCount - 2);
//pD3DDevice->DrawPrimitive(D3DPT_TRIANGLEFAN, 0, _vertexCount - 2);
pD3DDevice->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, _vertexCount, 0, _indexCount / 3);
}
void Mesh::deInit()
@@ -30,10 +79,144 @@ void Mesh::deInit()
UINT Mesh::createVertexBuffer(IDirect3DDevice9* pD3DDevice)
{
// 1. define mesh structure
_vertexCount = 8;
_vertexStride = sizeof(Vertex);
// 2. create vertex buffer WITHOUT data
HRESULT hr = pD3DDevice->CreateVertexBuffer(
_vertexCount * _vertexStride, // vertex buffer byte length
D3DUSAGE_WRITEONLY, // vertex buffer access mode
FVF, // FVF - Flexible Vertex Format
D3DPOOL_MANAGED, // video memory management
&_pVertexBuffer,
nullptr // not used anymore
);
CheckFailed(hr, 300);
// 3. fill vertex buffer with data
Vertex* pVertices = nullptr;
hr = _pVertexBuffer->Lock(0, 0, reinterpret_cast<void**>(&pVertices), 0);
CheckFailed(hr, 310);
// triangle
//pVertices[0] = Vertex(0.0f, 0.5f, 0.0f);
//pVertices[1] = Vertex(0.5f, -0.5f, 0.0f);
//pVertices[2] = Vertex(-0.5f, -0.5f, 0.0f);
// quad with trianglelist WITHOUT index buffer
//// triangle 1
//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);
//// triangle 2
//pVertices[3] = Vertex(-0.5f, 0.5f, 0.0f);
//pVertices[4] = Vertex(0.5f, -0.5f, 0.0f);
//pVertices[5] = Vertex(-0.5f, -0.5f, 0.0f);
// quad with trianglestrip
//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 trianglefan
//// quad with trianglelist & index buffer
// uv & normal
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);
//// cube with color
//// front
//pVertices[0] = Vertex(-0.5f, 0.5f, -0.5f, 255, 0, 0);
//pVertices[1] = Vertex(0.5f, 0.5f, -0.5f, 0, 255, 0);
//pVertices[2] = Vertex(0.5f, -0.5f, -0.5f, 0, 0, 255);
//pVertices[3] = Vertex(-0.5f, -0.5f, -0.5f, 255, 0, 255);
//// back
//pVertices[4] = Vertex(0.5f, 0.5f, 0.5f, 255, 255, 0);
//pVertices[5] = Vertex(-0.5f, 0.5f, 0.5f, 0, 255, 255);
//pVertices[6] = Vertex(-0.5f, -0.5f, 0.5f, 0, 0, 0);
//pVertices[7] = Vertex(0.5f, -0.5f, 0.5f, 200, 200, 200);
// cube with uv
//// front
//pVertices[0] = Vertex(-0.5f, 0.5f, -0.5f, 0.0f, 0.0f);
//pVertices[1] = Vertex(0.5f, 0.5f, -0.5f, 1.0f, 0.0f);
//pVertices[2] = Vertex(0.5f, -0.5f, -0.5f, 1.0f, 1.0f);
//pVertices[3] = Vertex(-0.5f, -0.5f, -0.5f, 0.0f, 1.0f);
//// back
//pVertices[4] = Vertex(0.5f, 0.5f, 0.5f, 0.0f, 0.0f);
//pVertices[5] = Vertex(-0.5f, 0.5f, 0.5f, 1.0f, 0.0f);
//pVertices[6] = Vertex(-0.5f, -0.5f, 0.5f, 1.0f, 1.0f);
//pVertices[7] = Vertex(0.5f, -0.5f, 0.5f, 0.0f, 1.0f);
hr = _pVertexBuffer->Unlock();
CheckFailed(hr, 320);
pVertices = nullptr;
return 0;
}
UINT Mesh::createIndexBuffer(IDirect3DDevice9* pD3DDevice)
{
_indexCount = 36; // triangle * 3
HRESULT hr = pD3DDevice->CreateIndexBuffer(
_indexCount * sizeof(WORD),
D3DUSAGE_WRITEONLY,
D3DFMT_INDEX16,
D3DPOOL_MANAGED,
&_pIndexBuffer,
nullptr
);
CheckFailed(hr, 330);
WORD* pIndices = nullptr;
hr = _pIndexBuffer->Lock(0, 0, reinterpret_cast<void**>(&pIndices), 0);
CheckFailed(hr, 340);
//// quad
//// triangle 1
//pIndices[0] = 0; pIndices[1] = 1; pIndices[2] = 2;
//// triangle 2
//pIndices[3] = 0; pIndices[4] = 2; pIndices[5] = 3;
// cube
// front
pIndices[0] = 0; pIndices[1] = 1; pIndices[2] = 2;
pIndices[3] = 0; pIndices[4] = 2; pIndices[5] = 3;
// back
pIndices[6] = 4; pIndices[7] = 5; pIndices[8] = 6;
pIndices[9] = 4; pIndices[10] = 6; pIndices[11] = 7;
// left
pIndices[12] = 5; pIndices[13] = 0; pIndices[14] = 3;
pIndices[15] = 5; pIndices[16] = 3; pIndices[17] = 6;
// right
pIndices[18] = 1; pIndices[19] = 4; pIndices[20] = 7;
pIndices[21] = 1; pIndices[22] = 7; pIndices[23] = 2;
// top
pIndices[24] = 5; pIndices[25] = 4; pIndices[26] = 1;
pIndices[27] = 5; pIndices[28] = 1; pIndices[29] = 0;
// bottom
pIndices[30] = 3; pIndices[31] = 2; pIndices[32] = 7;
pIndices[33] = 3; pIndices[34] = 7; pIndices[35] = 6;
hr = _pIndexBuffer->Unlock();
CheckFailed(hr, 350);
pIndices = nullptr;
return 0;
}
+19
View File
@@ -1,12 +1,31 @@
#include "Time.h"
#if _DEBUG
#include <string>
#endif // _DEBUG
UINT Time::init()
{
_lastFrame = CLOCK::now();
return 0;
}
void Time::update()
{
TIMEPOINT now = CLOCK::now();
SECONDS diff = now - _lastFrame;
_lastFrame = now;
_deltaTime = diff.count();
#ifdef _DEBUG
#ifdef UNICODE
wstring output = L"fps: " + to_wstring(1 / _deltaTime) + L"\n";
OutputDebugString(output.c_str());
#else // !UNICODE
string output = "fps: " + to_string(1 / _deltaTime) + "\n";
OutputDebugString(output.c_str());
#endif // UNICODE
#endif // DEBUG
}
void Time::deInit()
+5
View File
@@ -4,6 +4,10 @@
using namespace std;
typedef chrono::steady_clock CLOCK;
typedef CLOCK::time_point TIMEPOINT;
typedef chrono::duration<FLOAT> SECONDS;
class Time
{
public:
@@ -15,5 +19,6 @@ public:
private:
FLOAT _deltaTime = 0.0f;
TIMEPOINT _lastFrame = {};
};
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#include <d3d9.h>
#define FVF D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 | D3DFVF_NORMAL
struct Vertex
{
FLOAT x;
FLOAT y;
FLOAT z;
FLOAT nx;
FLOAT ny;
FLOAT nz;
D3DCOLOR color;
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) {}
};
+650
View File
@@ -0,0 +1,650 @@
//--------------------------------------------------------------------------------------
// 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.
//
// http://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[] =
{
{ 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 },
};
//-------------------------------------------------------------------------------------
// 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[] =
{
// 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
};
//--------------------------------------------------------------------------------------
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);
}
+93
View File
@@ -0,0 +1,93 @@
//--------------------------------------------------------------------------------------
// 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.
//
// http://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;
}
+63 -1
View File
@@ -1,16 +1,47 @@
#include "Window.h"
// https://learn.microsoft.com/en-us/windows/win32/learnwin32/creating-a-window
INT Window::init(HINSTANCE hInstance, UINT width, UINT height)
{
// 1. describe window class
WNDCLASS wc = {};
wc.hInstance = hInstance;
wc.lpszClassName = TEXT("D3D9"); // 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 border or title
RECT rect = { 100, 100, width + 100, height + 100 }; // left top right bottom
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 parent window
nullptr, // handle to menu instance
hInstance,
nullptr // pointer to optional parameter
);
if (_hWnd == nullptr) return 110;
// 5. show window
ShowWindow(_hWnd, SW_SHOW);
SetFocus(_hWnd);
return 0;
}
@@ -18,10 +49,41 @@ INT Window::init(HINSTANCE hInstance, UINT width, UINT height)
BOOL Window::run()
{
// 6. run window
// GetMessage - syncronous call which holds until a new message arrived
// PeekMessage - get last message from message queue or nothing if there is no message
// TranslateMessage - translates keyboard input
// DispatchMessage - send message to WindowProcedure
MSG msg = {};
if (PeekMessage(&msg, nullptr, 0, UINT_MAX, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return 0;
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);
break;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
+1
View File
@@ -14,3 +14,4 @@ private:
HWND _hWnd = nullptr; // handle to window instance
};
LRESULT CALLBACK WindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
+23 -2
View File
@@ -32,6 +32,13 @@ int WINAPI WinMain(
error = d3d.init(window.getWindowHandle(), width, height, isFullscreen);
CheckError(error);
// set render states
d3d.getDevice()->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
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);
// 3. create a mesh
Mesh mesh = {};
error = mesh.init(d3d.getDevice());
@@ -54,16 +61,30 @@ int WINAPI WinMain(
// 7. create light source
Light light = {};
error = light.init();
D3DLIGHT9 lightData = {};
lightData.Type = D3DLIGHT_DIRECTIONAL;
lightData.Direction = { 0.0f, 0.0f, 1.0f };
lightData.Diffuse = { 0.5f, 0.5f, 0.5f, 1.0f };
lightData.Specular = { 1.0f, 1.0f, 1.0f, 1.0f };
lightData.Ambient = { 0.2f, 0.2f, 0.2f, 1.0f };
error = light.init(lightData);
CheckError(error);
// 8. run application
while (window.run())
{
if (GetAsyncKeyState(VK_F1) & 0x8000) d3d.getDevice()->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
if (GetAsyncKeyState(VK_F2) & 0x8000) d3d.getDevice()->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
if (GetAsyncKeyState(VK_F3) & 0x8000) d3d.getDevice()->SetRenderState(D3DRS_FILLMODE, D3DFILL_POINT);
if (GetAsyncKeyState(VK_F4) & 0x8000) d3d.getDevice()->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
if (GetAsyncKeyState(VK_F5) & 0x8000) d3d.getDevice()->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW);
if (GetAsyncKeyState(VK_F6) & 0x8000) d3d.getDevice()->SetRenderState(D3DRS_CULLMODE, D3DCULL_CCW);
// 8.1. update objects
time.update();
mesh.update(time.getDeltaTime());
camera.update(time.getDeltaTime());
camera.update(time.getDeltaTime(), d3d.getDevice());
light.update(time.getDeltaTime());
// 8.2. render objects
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", "{C46808CF-936B-4F98-81C2-1E10D9F1822F}"
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
{C46808CF-936B-4F98-81C2-1E10D9F1822F}.Debug|ARM64.ActiveCfg = Debug|ARM64
{C46808CF-936B-4F98-81C2-1E10D9F1822F}.Debug|ARM64.Build.0 = Debug|ARM64
{C46808CF-936B-4F98-81C2-1E10D9F1822F}.Debug|x64.ActiveCfg = Debug|x64
{C46808CF-936B-4F98-81C2-1E10D9F1822F}.Debug|x64.Build.0 = Debug|x64
{C46808CF-936B-4F98-81C2-1E10D9F1822F}.Debug|x86.ActiveCfg = Debug|Win32
{C46808CF-936B-4F98-81C2-1E10D9F1822F}.Debug|x86.Build.0 = Debug|Win32
{C46808CF-936B-4F98-81C2-1E10D9F1822F}.Release|ARM64.ActiveCfg = Release|ARM64
{C46808CF-936B-4F98-81C2-1E10D9F1822F}.Release|ARM64.Build.0 = Release|ARM64
{C46808CF-936B-4F98-81C2-1E10D9F1822F}.Release|x64.ActiveCfg = Release|x64
{C46808CF-936B-4F98-81C2-1E10D9F1822F}.Release|x64.Build.0 = Release|x64
{C46808CF-936B-4F98-81C2-1E10D9F1822F}.Release|x86.ActiveCfg = Release|Win32
{C46808CF-936B-4F98-81C2-1E10D9F1822F}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.