23#include <wrl/client.h>
26#include <d3dcompiler.h>
32using Microsoft::WRL::ComPtr;
61static std::string_view
CompileShader(std::string_view source, std::string_view func, std::string_view profile, ComPtr<ID3DBlob> &code)
63 ComPtr<ID3DBlob> error;
65 HRESULT result =
_D3DCompile(source.data(), source.length(),
66 nullptr,
nullptr,
nullptr,
67 func.data(), profile.data(), D3DCOMPILE_ENABLE_STRICTNESS, 0, &code, &error);
71 return "Shader compile error";
85static std::string_view
CreateVertexShader(ID3D11Device *device, std::string_view source, ComPtr<ID3D11VertexShader> &shader)
87 ComPtr<ID3DBlob> code;
89 std::string_view msg =
CompileShader(source,
"vs_main",
"vs_4_0", code);
90 if (!msg.empty())
return msg;
92 HRESULT result = device->CreateVertexShader(code->GetBufferPointer(), code->GetBufferSize(),
nullptr, &shader);
93 if (FAILED(result))
return "Failed to create vertex shader";
106static std::string_view
CreatePixelShader(ID3D11Device *device, std::string_view source, ComPtr<ID3D11PixelShader> &shader)
108 ComPtr<ID3DBlob> code;
110 std::string_view msg =
CompileShader(source,
"ps_main",
"ps_4_0", code);
111 if (!msg.empty())
return msg;
113 HRESULT result = device->CreatePixelShader(code->GetBufferPointer(), code->GetBufferSize(),
nullptr, &shader);
114 if (FAILED(result))
return "Failed to create pixel shader";
129 std::optional<std::string_view>
Start(
const StringList ¶m)
override;
131 void Stop()
override;
151 return "win32-d3d11";
179 void Paint()
override;
217 std::string_view
Resize(
int w,
int h);
230 return std::make_unique<VideoDriver_Win32D3D11>();
248 D3D_FEATURE_LEVEL feature_level = D3D_FEATURE_LEVEL_10_0;
249 UINT device_flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_SINGLETHREADED;
253 device_flags, &feature_level, 1, D3D11_SDK_VERSION,
256 if (FAILED(result))
return "Failed to create D3D11 device";
259 if (!err.empty())
return err;
262 if (!err.empty())
return err;
265 if (!err.empty())
return err;
268 if (!err.empty())
return err;
271 if (!err.empty())
return err;
273 D3D11_BUFFER_DESC cbuffer_desc{
275 .Usage = D3D11_USAGE_IMMUTABLE,
276 .BindFlags = D3D11_BIND_CONSTANT_BUFFER,
279 .StructureByteStride = 0
283 .sprite = { 0.0f, 0.0f, 1.0f, 1.0f },
284 .screen = { 1.0f, 1.0f },
291 D3D11_SUBRESOURCE_DATA data{
292 .pSysMem = &constant,
293 .SysMemPitch =
sizeof(constant),
294 .SysMemSlicePitch = 0
298 if (FAILED(result))
return "Failed to constant buffer";
300 D3D11_TEXTURE1D_DESC desc{
304 .Format = DXGI_FORMAT_B8G8R8A8_UNORM,
305 .Usage = D3D11_USAGE_DEFAULT,
306 .BindFlags = D3D11_BIND_SHADER_RESOURCE,
307 .CPUAccessFlags = D3D11_CPU_ACCESS_WRITE,
312 if (FAILED(result))
return "Failed to create texture";
314 result =
device->CreateShaderResourceView(this->
pal_texture.Get(),
nullptr, &this->pal_texture_srv);
315 if (FAILED(result))
return "Failed to resource view";
317 D3D11_SAMPLER_DESC sampler_desc{};
318 sampler_desc.Filter = D3D11_FILTER_MIN_MAG_MIP_POINT;
319 sampler_desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
320 sampler_desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
321 sampler_desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
322 sampler_desc.ComparisonFunc = D3D11_COMPARISON_NEVER;
323 sampler_desc.MaxLOD = D3D11_FLOAT32_MAX;
326 if (FAILED(result))
return "Failed to create sampler state";
342 D3D11_TEXTURE2D_DESC desc{
343 .Width =
static_cast<UINT
>(w),
344 .
Height =
static_cast<UINT
>(h),
347 .Format = (bpp == 8) ? DXGI_FORMAT_R8_UNORM : DXGI_FORMAT_B8G8R8A8_UNORM,
348 .SampleDesc = { .Count = 1, .Quality = 0 },
349 .Usage = D3D11_USAGE_DEFAULT,
350 .BindFlags = D3D11_BIND_SHADER_RESOURCE,
356 if (FAILED(result))
return "Failed to create texture";
359 desc.Usage = D3D11_USAGE_STAGING;
360 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
363 if (FAILED(result))
return "Failed to create texture";
365 desc.Format = DXGI_FORMAT_R8_UNORM;
369 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
370 desc.Usage = D3D11_USAGE_DEFAULT;
371 desc.CPUAccessFlags = 0;
374 if (FAILED(result))
return "Failed to create texture";
377 desc.Usage = D3D11_USAGE_STAGING;
378 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
381 if (FAILED(result))
return "Failed to create texture";
386 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
387 desc.Usage = D3D11_USAGE_IMMUTABLE;
388 desc.CPUAccessFlags = 0;
391 D3D11_SUBRESOURCE_DATA data{
394 .SysMemSlicePitch = 0
398 if (FAILED(result))
return "Failed to create texture";
403 result =
device->CreateShaderResourceView(this->
vid_texture.Get(),
nullptr, &this->vid_texture_srv);
404 if (FAILED(result))
return "Failed to create resource view";
406 result =
device->CreateShaderResourceView(this->
anim_texture.Get(),
nullptr, &this->anim_texture_srv);
407 if (FAILED(result))
return "Failed to create resource view";
412 _screen.dst_ptr =
nullptr;
421 if (
_d3d11.HasError())
return "Failed to load d3d11 library";
424 if (
_d3d11.HasError())
return "Failed to import D3D11CreateDevice function";
426 for (
int ver = D3D_COMPILER_VERSION; ver >= 40; ver--) {
427 std::string dllname = fmt::format(
"d3dcompiler_{}.dll", ver);
432 if (
_d3dcompiler->HasError())
return "Failed to load d3dcompiler library";
435 if (
_d3dcompiler->HasError())
return "Failed to import D3DCompile function";
437 std::string_view err =
InitD3D();
438 if (!err.empty())
return err;
449 if (_screen.dst_ptr ==
nullptr)
return "D3D11 setup failed";
451 ComPtr<IDXGIDevice> dxgiDevice;
454 ComPtr<IDXGIAdapter> adapter;
456 if (SUCCEEDED(dxgiDevice->GetAdapter(adapter.GetAddressOf()))) {
457 DXGI_ADAPTER_DESC desc{};
458 adapter->GetDesc(&desc);
460 char driver_name_utf8[1024];
494 ComPtr<IDXGIDevice> dxgi_device;
495 HRESULT result =
device.As(&dxgi_device);
496 if (FAILED(result))
return "Failed to get DXGI device";
498 ComPtr<IDXGIAdapter> dxgi_adapter;
499 result = dxgi_device->GetAdapter(&dxgi_adapter);
500 if (FAILED(result))
return "Failed to get DXGI adapter";
502 ComPtr<IDXGIFactory> dxgi_factory;
503 result = dxgi_adapter->GetParent(IID_PPV_ARGS(&dxgi_factory));
504 if (FAILED(result))
return "Failed to get DXGI factory";
506 ComPtr<IDXGIFactory2> dxgi_factory2;
507 dxgi_factory.As(&dxgi_factory2);
509 ComPtr<IDXGIFactory4> dxgi_factory4;
510 dxgi_factory.As(&dxgi_factory4);
512 ComPtr<IDXGIFactory5> dxgi_factory5;
513 dxgi_factory.As(&dxgi_factory5);
515 BOOL allow_tearing = FALSE;
517 dxgi_factory5->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allow_tearing,
sizeof(allow_tearing));
520 DXGI_SWAP_EFFECT swap_effect;
524 swap_effect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
525 }
else if (dxgi_factory2) {
527 swap_effect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
529 swap_effect = DXGI_SWAP_EFFECT_DISCARD;
530 allow_tearing = FALSE;
536 swap_effect = DXGI_SWAP_EFFECT_DISCARD;
540 this->
dxgi_flags = allow_tearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;
544 DXGI_SWAP_CHAIN_DESC swap_desc{};
546 swap_desc.BufferDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
547 swap_desc.SampleDesc.Count = 1;
548 swap_desc.SampleDesc.Quality = 0;
549 swap_desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
550 swap_desc.BufferCount = 2;
551 swap_desc.OutputWindow = this->
main_wnd;
552 swap_desc.Windowed = TRUE;
553 swap_desc.SwapEffect = swap_effect;
556 result = dxgi_factory->CreateSwapChain(
device.Get(), &swap_desc, &this->swap_chain);
557 if (FAILED(result))
return "Failed to create swap chain";
560 result = dxgi_factory->MakeWindowAssociation(this->
main_wnd, DXGI_MWA_NO_ALT_ENTER);
561 if (FAILED(result))
return "Failed to set DXGI window settings";
580 DXGI_MODE_DESC mode{};
581 mode.Width =
static_cast<UINT
>(w);
582 mode.Height =
static_cast<UINT
>(h);
583 mode.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
585 return SUCCEEDED(this->
swap_chain->ResizeTarget(&mode));
590 HRESULT result = this->
swap_chain->SetFullscreenState(full_screen,
nullptr);
591 if (FAILED(result))
return false;
593 _fullscreen = full_screen;
611 if (!force && w == _screen.width && h == _screen.height)
return false;
613 this->
width = w = std::max(w, 64);
614 this->
height = h = std::max(h, 64);
619 std::string_view err =
Resize(w, h);
634 HRESULT result = this->
swap_chain->ResizeBuffers(2, w, h, DXGI_FORMAT_B8G8R8A8_UNORM, this->
dxgi_flags);
635 if (FAILED(result)) {
643 ComPtr<ID3D11Texture2D> framebuffer;
644 HRESULT result = this->
swap_chain->GetBuffer(0, IID_PPV_ARGS(&framebuffer));
645 if (FAILED(result)) {
650 result =
device->CreateRenderTargetView(framebuffer.Get(),
nullptr, &this->rendertarget);
651 if (FAILED(result)) {
663 D3D11_MAPPED_SUBRESOURCE mapped;
665 this->
anim_buffer =
static_cast<uint8_t *
>(mapped.pData);
669 D3D11_MAPPED_SUBRESOURCE mapped;
673 _screen.pitch = mapped.RowPitch / bpp * 8;
685 .left =
static_cast<UINT
>(this->
dirty_rect.left),
686 .top =
static_cast<UINT
>(this->
dirty_rect.top),
688 .right =
static_cast<UINT
>(this->
dirty_rect.right),
689 .bottom =
static_cast<UINT
>(this->
dirty_rect.bottom),
701 .left =
static_cast<UINT
>(this->
dirty_rect.left),
702 .top =
static_cast<UINT
>(this->
dirty_rect.top),
704 .right =
static_cast<UINT
>(this->
dirty_rect.right),
705 .bottom =
static_cast<UINT
>(this->
dirty_rect.bottom),
713 _screen.dst_ptr =
nullptr;
751 FLOAT background_color[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
759 ID3D11ShaderResourceView *resources[4] = {
nullptr };
774 device_ctx->PSSetShaderResources(0, 4, resources);
776 D3D11_VIEWPORT viewport = { 0.0f, 0.0f,
static_cast<float>(_screen.width),
static_cast<float>(_screen.height), 0.0f, 1.0f };
779 device_ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
How all blitters should look like.
virtual uint8_t GetScreenDepth()=0
Get the screen depth this blitter works for.
virtual Blitter::PaletteAnimation UsePaletteAnimation()=0
Check if the blitter uses palette animation at all.
virtual void PaletteAnimate(const Palette &palette)=0
Called when the 8bpp palette is changed; you should redraw all pixels on the screen that are equal to...
@ Blitter
The blitter takes care of the palette animation.
DriverFactoryBase(Driver::Type type, int priority, std::string_view name, std::string_view description)
Construct a new DriverFactory.
A driver for communicating with the user.
The factory for Windows' D3D11 video driver.
FVideoDriver_Win32D3D11()
Constructor for the D3D11 video driver factory.
std::unique_ptr< Driver > CreateInstance() const override
Create an instance of this driver-class.
bool UsesHardwareAcceleration() const override
Does the driver use hardware acceleration (video-drivers only).
int height
Height in pixels of our display surface.
VideoDriver_Win32Base(bool uses_hardware_acceleration=false, bool supports_animation_buffer=false)
Create the video driver.
void Stop() override
Stop this driver.
HWND main_wnd
Handle to system window.
bool fullscreen
Whether to use (true) fullscreen mode.
bool MakeWindow(bool full_screen, bool resize=true)
Instantiate a new window.
int width
Width in pixels of our display surface.
Palette local_palette
Current palette to use for drawing.
void ClientSizeChanged(int w, int h, bool force=false)
Indicate to the driver the client-size might have changed.
Rect dirty_rect
Region of the screen that needs redrawing.
UINT dxgi_flags
DXGI swap chain flags.
ComPtr< ID3D11VertexShader > vertex_shader
Vertex shader for sprite rendering.
ComPtr< ID3D11PixelShader > sprite_blend_shader
Pixel shader for sprite blending.
std::string_view Resize(int w, int h)
Resizes the D3D11 textures to the given width and height.
bool UseSystemCursor() override
Get whether the mouse cursor is drawn by the video driver.
ComPtr< ID3D11ShaderResourceView > pal_texture_srv
Shader resource view for palette texture.
bool AllocateBackingStore(int w, int h, bool force=false) override
(Re-)create the backing store.
ComPtr< ID3D11ShaderResourceView > vid_texture_srv
Shader resource view for video texture.
ComPtr< ID3D11Texture2D > vid_texture
Video texture for the back buffer.
void * GetVideoPointer() override
Get a pointer to the video buffer.
ComPtr< ID3D11RenderTargetView > rendertarget
D3D11 render target view for the back buffer.
bool dxgi_force_resize_buffer
Flag indicating whether to force resize the swap chain buffer.
ComPtr< ID3D11SamplerState > texture_sampler
Sampler state for texture sampling.
ComPtr< ID3D11Texture2D > anim_texture_staging
Staging texture for animation texture.
bool dxgi_fullscreen
Flag indicating whether we're in fullscreen mode.
ComPtr< IDXGISwapChain > swap_chain
DXGI swap chain.
VideoDriver_Win32D3D11()
Constructor for the D3D11 video driver.
ComPtr< ID3D11Texture2D > anim_texture
Animation texture for palette animation.
ComPtr< ID3D11PixelShader > rgb_mask_blend_shader
Pixel shader for RGB mask blending.
ComPtr< ID3D11Device > device
D3D11 device.
bool HasEfficient8Bpp() const override
Has this video driver an efficient code path for palette animated 8-bpp sprites?
ComPtr< ID3D11Texture1D > pal_texture
Palette texture for palette animation.
void Stop() override
Stop this driver.
void ReleaseVideoPointer() override
Hand video buffer back to the painting backend.
ComPtr< ID3D11Buffer > constant_buffer
Constant buffer.
ComPtr< ID3D11DeviceContext > device_ctx
D3D11 device context.
std::string_view InitD3D()
Check for the needed D3D11 functionality and allocate all resources.
ComPtr< ID3D11PixelShader > palette_shader
Pixel shader for palette animation.
void PaletteChanged(HWND) override
Palette of the window has changed.
void Paint() override
Paint the window.
std::string_view GetInfoString() const override
Get some information about the selected driver/backend to be shown to the user.
ComPtr< ID3D11PixelShader > direct_shader
Pixel shader for direct rendering.
std::string_view GetName() const override
Get the name of this driver.
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
bool MinimiseRestoreWithToggleFullscreen() const override
Whether minimising and restoring fullscreen windows uses ToggleFullscreen.
ComPtr< ID3D11Texture2D > vid_texture_staging
Staging texture for video texture.
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
std::optional< std::string_view > Start(const StringList ¶m) override
Start this driver.
ComPtr< ID3D11ShaderResourceView > anim_texture_srv
Shader resource view for animation texture.
void DestroySwapchain()
Destroys the DXGI swap chain and releases all associated resources.
std::string driver_info
Information string about selected driver.
uint8_t GetFullscreenBpp() override
Colour depth to use for fullscreen display modes.
bool AfterBlitterChange() override
Callback invoked after the blitter was changed.
std::string_view CreateSwapchain()
Creates a DXGI swap chain for the current window.
int anim_pitch
Pitch of the animation buffer if supported/used.
uint8_t * anim_buffer
The animation buffer if supported/used.
bool is_game_threaded
Whether the game is allowed to use threads; cleared in the driver implementation constructors if requ...
static LibraryLoader _d3d11("d3d11.dll")
LibraryLoader instance for the D3D11 DLL.
static std::unique_ptr< LibraryLoader > _d3dcompiler
Pointer to a LibraryLoader instance for the D3DCompiler DLL.
static pD3DCompile _D3DCompile
Pointer to the D3DCompile function.
static PFN_D3D11_CREATE_DEVICE _D3D11CreateDevice
Pointer to the D3D11CreateDevice function.
static std::string_view CompileShader(std::string_view source, std::string_view func, std::string_view profile, ComPtr< ID3DBlob > &code)
Compiles an HLSL shader from source code.
static std::string_view CreatePixelShader(ID3D11Device *device, std::string_view source, ComPtr< ID3D11PixelShader > &shader)
Creates a pixel shader from HLSL source code.
bool _window_maximize
Declared in win32_v.cpp.
static FVideoDriver_Win32D3D11 iFVideoDriver_Win32D3D11
Factory instance for the D3D11 video driver.
static std::string_view CreateVertexShader(ID3D11Device *device, std::string_view source, ComPtr< ID3D11VertexShader > &shader)
Creates a vertex shader from HLSL source code.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
@ Driver
Driver message facility.
@ Critical
Critical, user should know about this.
@ Error
Error, but we are recovering.
bool GetDriverParamBool(const StringList &parm, std::string_view name)
Get a boolean parameter the list of parameters.
Error reporting related functions.
Factory to 'query' all available blitters.
Types for recording game performance data.
@ Video
Speed of painting drawn video buffer.
bool IsEmptyRect(const Rect &r)
Check if a rectangle is empty.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
static const char _frag_shader_palette_hlsl[]
HLSL pixel shader that reads the fragment colour from a 32bpp texture.
static const char _frag_shader_direct_hlsl[]
HLSL pixel shader that reads the fragment colour from a 32bpp texture.
static const char _vertex_shader_sprite_hlsl[]
HLSL vertex shader that positions a sprite on screen.
static const char _frag_shader_rgb_mask_blend_hlsl[]
HLSL pixel shader that performs a palette lookup to read the colour from an 8bpp texture.
static const char _frag_shader_sprite_blend_hlsl[]
HLSL pixel shader that performs a palette lookup to read the colour from a sprite texture.
Functions/types related to loading libraries dynamically.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
std::vector< std::string > StringList
Type for a list of strings.
Structure for an HLSL constant buffer containing the sprite position, screen size,...
BOOL rgb
Flag indicating whether RGB mode is enabled.
BOOL crash
Flag indicating whether crash mode is enabled.
FLOAT sprite[4]
Sprite position.
FLOAT screen[2]
Screen size.
int16_t Height
Fixed point type for heights.
bool _video_vsync
Whether we should use vsync (only if active video driver supports HW acceleration).
std::string_view convert_from_fs(const std::wstring_view src, std::span< char > dst_buf)
Convert to OpenTTD's encoding from that of the environment in UNICODE.
Declarations of functions for MS windows systems.
Base of the Windows video driver.
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Window functions not directly related to making/drawing windows.