OpenTTD Source 20261112-master-gbcbec5e63f
d3d11_v.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "../stdafx.h"
11#include "../openttd.h"
12#include "../error_func.h"
13#include "../os/windows/win32.h"
16#include "../window_func.h"
17#include "../framerate_type.h"
18#include "../library_loader.h"
20#include "win32_v.h"
21#include <windows.h>
22#include <objbase.h>
23#include <wrl/client.h>
24#include <dxgi1_5.h>
25#include <d3d11.h>
26#include <d3dcompiler.h>
27
28#include "../safeguards.h"
29
30extern bool _window_maximize;
31
32using Microsoft::WRL::ComPtr;
33
38 FLOAT sprite[4];
39 FLOAT screen[2];
40 FLOAT zoom;
41 BOOL rgb;
42 BOOL crash;
43 FLOAT pad[3];
44};
45
46static LibraryLoader _d3d11("d3d11.dll");
47static std::unique_ptr<LibraryLoader> _d3dcompiler;
48
49static PFN_D3D11_CREATE_DEVICE _D3D11CreateDevice;
50static pD3DCompile _D3DCompile;
51
61static std::string_view CompileShader(std::string_view source, std::string_view func, std::string_view profile, ComPtr<ID3DBlob> &code)
62{
63 ComPtr<ID3DBlob> error;
64
65 HRESULT result = _D3DCompile(source.data(), source.length(),
66 nullptr, nullptr, nullptr,
67 func.data(), profile.data(), D3DCOMPILE_ENABLE_STRICTNESS, 0, &code, &error);
68
69 if (FAILED(result)) {
70 if (error != nullptr) Debug(Facility::Driver, Severity::Error, "{}", static_cast<char *>(error->GetBufferPointer()));
71 return "Shader compile error";
72 }
73
74 return {};
75}
76
85static std::string_view CreateVertexShader(ID3D11Device *device, std::string_view source, ComPtr<ID3D11VertexShader> &shader)
86{
87 ComPtr<ID3DBlob> code;
88
89 std::string_view msg = CompileShader(source, "vs_main", "vs_4_0", code);
90 if (!msg.empty()) return msg;
91
92 HRESULT result = device->CreateVertexShader(code->GetBufferPointer(), code->GetBufferSize(), nullptr, &shader);
93 if (FAILED(result)) return "Failed to create vertex shader";
94
95 return {};
96}
97
106static std::string_view CreatePixelShader(ID3D11Device *device, std::string_view source, ComPtr<ID3D11PixelShader> &shader)
107{
108 ComPtr<ID3DBlob> code;
109
110 std::string_view msg = CompileShader(source, "ps_main", "ps_4_0", code);
111 if (!msg.empty()) return msg;
112
113 HRESULT result = device->CreatePixelShader(code->GetBufferPointer(), code->GetBufferSize(), nullptr, &shader);
114 if (FAILED(result)) return "Failed to create pixel shader";
115
116 return {};
117}
118
121public:
128
129 std::optional<std::string_view> Start(const StringList &param) override;
130
131 void Stop() override;
132
133 bool ChangeResolution(int w, int h) override;
134
135 bool ToggleFullscreen(bool fullscreen) override;
136
137 bool AfterBlitterChange() override;
138
139 bool HasEfficient8Bpp() const override
140 {
141 return true;
142 }
143
144 bool UseSystemCursor() override
145 {
146 return false;
147 }
148
149 std::string_view GetName() const override
150 {
151 return "win32-d3d11";
152 }
153
154 std::string_view GetInfoString() const override
155 {
156 return this->driver_info;
157 }
158
159protected:
160 ComPtr<IDXGISwapChain> swap_chain;
161 ComPtr<ID3D11RenderTargetView> rendertarget;
162
164 bool dxgi_fullscreen = false;
165 UINT dxgi_flags = 0;
166
167 std::string driver_info;
168
170 {
171 return true;
172 }
173
174 uint8_t GetFullscreenBpp() override
175 {
176 return 32; // D3D11 is always 32 bpp.
177 }
178
179 void Paint() override;
180
181 bool AllocateBackingStore(int w, int h, bool force = false) override;
182 void *GetVideoPointer() override;
183 void ReleaseVideoPointer() override;
184 void PaletteChanged(HWND) override
185 {
186 }
187
188 std::string_view CreateSwapchain();
189 void DestroySwapchain();
190
191private:
192 ComPtr<ID3D11Device> device;
193 ComPtr<ID3D11DeviceContext> device_ctx;
194
195 ComPtr<ID3D11VertexShader> vertex_shader;
196 ComPtr<ID3D11PixelShader> direct_shader;
197 ComPtr<ID3D11PixelShader> palette_shader;
198 ComPtr<ID3D11PixelShader> rgb_mask_blend_shader;
199 ComPtr<ID3D11PixelShader> sprite_blend_shader;
200
201 ComPtr<ID3D11Buffer> constant_buffer;
202
203 ComPtr<ID3D11Texture2D> vid_texture;
204 ComPtr<ID3D11Texture2D> vid_texture_staging;
205 ComPtr<ID3D11ShaderResourceView> vid_texture_srv;
206
207 ComPtr<ID3D11Texture2D> anim_texture;
208 ComPtr<ID3D11Texture2D> anim_texture_staging;
209 ComPtr<ID3D11ShaderResourceView> anim_texture_srv;
210
211 ComPtr<ID3D11Texture1D> pal_texture;
212 ComPtr<ID3D11ShaderResourceView> pal_texture_srv;
213
214 ComPtr<ID3D11SamplerState> texture_sampler;
215
216 std::string_view InitD3D();
217 std::string_view Resize(int w, int h);
218};
219
222public:
224 FVideoDriver_Win32D3D11() : DriverFactoryBase(Driver::Type::Video, 10, "win32-d3d11", "Win32 D3D11 Video Driver")
225 {
226 }
227
228 std::unique_ptr<Driver> CreateInstance() const override
229 {
230 return std::make_unique<VideoDriver_Win32D3D11>();
231 }
232
233protected:
234 bool UsesHardwareAcceleration() const override
235 {
236 return true;
237 }
238};
239
241
247{
248 D3D_FEATURE_LEVEL feature_level = D3D_FEATURE_LEVEL_10_0;
249 UINT device_flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_SINGLETHREADED;
250 //device_flags |= D3D11_CREATE_DEVICE_DEBUG; /* Uncomment to create device with debug layer. */
251
252 HRESULT result = _D3D11CreateDevice(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr,
253 device_flags, &feature_level, 1, D3D11_SDK_VERSION,
254 &this->device, nullptr, &this->device_ctx);
255
256 if (FAILED(result)) return "Failed to create D3D11 device";
257
258 std::string_view err = CreateVertexShader(this->device.Get(), _vertex_shader_sprite_hlsl, this->vertex_shader);
259 if (!err.empty()) return err;
260
261 err = CreatePixelShader(this->device.Get(), _frag_shader_direct_hlsl, this->direct_shader);
262 if (!err.empty()) return err;
263
264 err = CreatePixelShader(this->device.Get(), _frag_shader_palette_hlsl, this->palette_shader);
265 if (!err.empty()) return err;
266
267 err = CreatePixelShader(this->device.Get(), _frag_shader_rgb_mask_blend_hlsl, this->rgb_mask_blend_shader);
268 if (!err.empty()) return err;
269
270 err = CreatePixelShader(this->device.Get(), _frag_shader_sprite_blend_hlsl, this->sprite_blend_shader);
271 if (!err.empty()) return err;
272
273 D3D11_BUFFER_DESC cbuffer_desc{
274 .ByteWidth = sizeof(HlslConstantBuffer),
275 .Usage = D3D11_USAGE_IMMUTABLE,
276 .BindFlags = D3D11_BIND_CONSTANT_BUFFER,
277 .CPUAccessFlags = 0,
278 .MiscFlags = 0,
279 .StructureByteStride = 0
280 };
281
282 HlslConstantBuffer constant{
283 .sprite = { 0.0f, 0.0f, 1.0f, 1.0f },
284 .screen = { 1.0f, 1.0f },
285 .zoom = 0.0f,
286 .rgb = TRUE,
287 .crash = FALSE,
288 .pad = 0
289 };
290
291 D3D11_SUBRESOURCE_DATA data{
292 .pSysMem = &constant,
293 .SysMemPitch = sizeof(constant),
294 .SysMemSlicePitch = 0
295 };
296
297 result = device->CreateBuffer(&cbuffer_desc, &data, &this->constant_buffer);
298 if (FAILED(result)) return "Failed to constant buffer";
299
300 D3D11_TEXTURE1D_DESC desc{
301 .Width = 256,
302 .MipLevels = 1,
303 .ArraySize = 1,
304 .Format = DXGI_FORMAT_B8G8R8A8_UNORM,
305 .Usage = D3D11_USAGE_DEFAULT,
306 .BindFlags = D3D11_BIND_SHADER_RESOURCE,
307 .CPUAccessFlags = D3D11_CPU_ACCESS_WRITE,
308 .MiscFlags = 0
309 };
310
311 result = device->CreateTexture1D(&desc, nullptr, &this->pal_texture);
312 if (FAILED(result)) return "Failed to create texture";
313
314 result = device->CreateShaderResourceView(this->pal_texture.Get(), nullptr, &this->pal_texture_srv);
315 if (FAILED(result)) return "Failed to resource view";
316
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;
324
325 result = device->CreateSamplerState(&sampler_desc, &texture_sampler);
326 if (FAILED(result)) return "Failed to create sampler state";
327
328 return {};
329}
330
338std::string_view VideoDriver_Win32D3D11::Resize(int w, int h)
339{
341
342 D3D11_TEXTURE2D_DESC desc{
343 .Width = static_cast<UINT>(w),
344 .Height = static_cast<UINT>(h),
345 .MipLevels = 1,
346 .ArraySize = 1,
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,
351 .CPUAccessFlags = 0,
352 .MiscFlags = 0
353 };
354
355 HRESULT result = device->CreateTexture2D(&desc, nullptr, &this->vid_texture);
356 if (FAILED(result)) return "Failed to create texture";
357
358 desc.BindFlags = 0;
359 desc.Usage = D3D11_USAGE_STAGING;
360 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
361
362 result = device->CreateTexture2D(&desc, nullptr, &this->vid_texture_staging);
363 if (FAILED(result)) return "Failed to create texture";
364
365 desc.Format = DXGI_FORMAT_R8_UNORM;
366
367 /* Does this blitter need a separate animation buffer? */
368 if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
369 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
370 desc.Usage = D3D11_USAGE_DEFAULT;
371 desc.CPUAccessFlags = 0;
372
373 result = device->CreateTexture2D(&desc, nullptr, &this->anim_texture);
374 if (FAILED(result)) return "Failed to create texture";
375
376 desc.BindFlags = 0;
377 desc.Usage = D3D11_USAGE_STAGING;
378 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
379
380 result = device->CreateTexture2D(&desc, nullptr, &this->anim_texture_staging);
381 if (FAILED(result)) return "Failed to create texture";
382 } else {
383 /* Allocate dummy texture that always reads as 0 == no remap. */
384 desc.Width = 1;
385 desc.Height = 1;
386 desc.BindFlags = D3D11_BIND_SHADER_RESOURCE;
387 desc.Usage = D3D11_USAGE_IMMUTABLE;
388 desc.CPUAccessFlags = 0;
389
390 byte dummy = 0;
391 D3D11_SUBRESOURCE_DATA data{
392 .pSysMem = &dummy,
393 .SysMemPitch = 1,
394 .SysMemSlicePitch = 0
395 };
396
397 result = device->CreateTexture2D(&desc, &data, &this->anim_texture);
398 if (FAILED(result)) return "Failed to create texture";
399
400 this->anim_texture_staging.Reset();
401 }
402
403 result = device->CreateShaderResourceView(this->vid_texture.Get(), nullptr, &this->vid_texture_srv);
404 if (FAILED(result)) return "Failed to create resource view";
405
406 result = device->CreateShaderResourceView(this->anim_texture.Get(), nullptr, &this->anim_texture_srv);
407 if (FAILED(result)) return "Failed to create resource view";
408
409 /* Set new viewport. */
410 _screen.height = h;
411 _screen.width = w;
412 _screen.dst_ptr = nullptr;
413
414 return {};
415}
416
417std::optional<std::string_view> VideoDriver_Win32D3D11::Start(const StringList& param)
418{
419 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 0) return "Only real blitters supported";
420
421 if (_d3d11.HasError()) return "Failed to load d3d11 library";
422
423 _D3D11CreateDevice = static_cast<PFN_D3D11_CREATE_DEVICE>(_d3d11.GetFunction("D3D11CreateDevice"));
424 if (_d3d11.HasError()) return "Failed to import D3D11CreateDevice function";
425
426 for (int ver = D3D_COMPILER_VERSION; ver >= 40; ver--) {
427 std::string dllname = fmt::format("d3dcompiler_{}.dll", ver);
428 _d3dcompiler = make_unique<LibraryLoader>(dllname);
429 if (!_d3dcompiler->HasError()) break;
430 }
431
432 if (_d3dcompiler->HasError()) return "Failed to load d3dcompiler library";
433
434 _D3DCompile = static_cast<pD3DCompile>(_d3dcompiler->GetFunction("D3DCompile"));
435 if (_d3dcompiler->HasError()) return "Failed to import D3DCompile function";
436
437 std::string_view err = InitD3D();
438 if (!err.empty()) return err;
439
440 this->Initialize();
441
442 /* Don't use legacy MakeWindow fullscreen handling, handle this later in ToggleFullscreen.
443 * Set dxgi_fullscreen there as a hint to CreateSwapchain to allow it to select optimal DXGI swap effect. */
444 bool fs = this->dxgi_fullscreen = _fullscreen;
445 this->MakeWindow(false);
446
447 this->ClientSizeChanged(this->width, this->height, true);
448
449 if (_screen.dst_ptr == nullptr) return "D3D11 setup failed";
450
451 ComPtr<IDXGIDevice> dxgiDevice;
452 device.As(&dxgiDevice);
453
454 ComPtr<IDXGIAdapter> adapter;
455
456 if (SUCCEEDED(dxgiDevice->GetAdapter(adapter.GetAddressOf()))) {
457 DXGI_ADAPTER_DESC desc{};
458 adapter->GetDesc(&desc);
459
460 char driver_name_utf8[1024];
461 convert_from_fs(desc.Description, driver_name_utf8);
462 this->driver_info = fmt::format("{} ({})", this->GetName(), driver_name_utf8);
463 } else {
464 this->driver_info = fmt::format("{} (unknown device)", this->GetName());
465 }
466
467 if (fs) this->ToggleFullscreen(true);
468
469 /* Main loop expects to start with the buffer unmapped. */
470 this->ReleaseVideoPointer();
471
473
474 this->is_game_threaded = !GetDriverParamBool(param, "no_threads") && !GetDriverParamBool(param, "no_thread");
475
476 return std::nullopt;
477}
478
480{
481 this->DestroySwapchain();
482 _D3D11CreateDevice = nullptr;
483 _D3DCompile = nullptr;
485}
486
493{
494 ComPtr<IDXGIDevice> dxgi_device;
495 HRESULT result = device.As(&dxgi_device);
496 if (FAILED(result)) return "Failed to get DXGI device";
497
498 ComPtr<IDXGIAdapter> dxgi_adapter;
499 result = dxgi_device->GetAdapter(&dxgi_adapter);
500 if (FAILED(result)) return "Failed to get DXGI adapter";
501
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";
505
506 ComPtr<IDXGIFactory2> dxgi_factory2;
507 dxgi_factory.As(&dxgi_factory2);
508
509 ComPtr<IDXGIFactory4> dxgi_factory4;
510 dxgi_factory.As(&dxgi_factory4);
511
512 ComPtr<IDXGIFactory5> dxgi_factory5;
513 dxgi_factory.As(&dxgi_factory5);
514
515 BOOL allow_tearing = FALSE;
516 if (dxgi_factory5) {
517 dxgi_factory5->CheckFeatureSupport(DXGI_FEATURE_PRESENT_ALLOW_TEARING, &allow_tearing, sizeof(allow_tearing));
518 }
519
520 DXGI_SWAP_EFFECT swap_effect;
521
522 if (dxgi_factory4) {
523 /* DXGI_SWAP_EFFECT_FLIP_DISCARD supported since Windows 10/DXGI 1.4 */
524 swap_effect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
525 } else if (dxgi_factory2) {
526 /* DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL supported since Windows 8/DXGI 1.2 */
527 swap_effect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
528 } else {
529 swap_effect = DXGI_SWAP_EFFECT_DISCARD;
530 allow_tearing = FALSE;
531 }
532
533 if (!allow_tearing && !this->dxgi_fullscreen && !_video_vsync) {
534 /* If non-fullscreen window without vsync is requested and DXGI_FEATURE_PRESENT_ALLOW_TEARING is not present
535 * always use bitblt model, otherwise window might be always vsynced. */
536 swap_effect = DXGI_SWAP_EFFECT_DISCARD;
537 }
538
539 /* Add DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH here to allow changing fullscreen resolution. */
540 this->dxgi_flags = allow_tearing ? DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING : 0;
541
542 this->dxgi_fullscreen = false;
543
544 DXGI_SWAP_CHAIN_DESC swap_desc{};
545
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; // Documentation recommends to always create windowed swapchain and only set it to fullscreen later.
553 swap_desc.SwapEffect = swap_effect;
554 swap_desc.Flags = this->dxgi_flags;
555
556 result = dxgi_factory->CreateSwapChain(device.Get(), &swap_desc, &this->swap_chain);
557 if (FAILED(result)) return "Failed to create swap chain";
558
559 /* We don't want DXGI to intercept Alt-enter and switch to fullscreen mode by itself. */
560 result = dxgi_factory->MakeWindowAssociation(this->main_wnd, DXGI_MWA_NO_ALT_ENTER);
561 if (FAILED(result)) return "Failed to set DXGI window settings";
562
563 return {};
564}
565
570{
571 this->rendertarget.Reset();
572 if (this->swap_chain && this->dxgi_fullscreen) this->swap_chain->SetFullscreenState(false, nullptr);
573 this->swap_chain.Reset();
574}
575
577{
578 if (_window_maximize) ShowWindow(this->main_wnd, SW_SHOWNORMAL);
579
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;
584
585 return SUCCEEDED(this->swap_chain->ResizeTarget(&mode));
586}
587
589{
590 HRESULT result = this->swap_chain->SetFullscreenState(full_screen, nullptr);
591 if (FAILED(result)) return false;
592
593 _fullscreen = full_screen;
594 this->fullscreen = full_screen;
595 this->dxgi_fullscreen = full_screen;
596 this->dxgi_force_resize_buffer = true;
597 InvalidateWindowClassesData(WindowClass::GameOptions, 3);
598
599 return true;
600}
601
603{
604 assert(BlitterFactory::GetCurrentBlitter()->GetScreenDepth() != 0);
605 this->ClientSizeChanged(this->width, this->height, true);
606 return true;
607}
608
610{
611 if (!force && w == _screen.width && h == _screen.height) return false;
612
613 this->width = w = std::max(w, 64);
614 this->height = h = std::max(h, 64);
615
616 if (_screen.dst_ptr != nullptr) this->ReleaseVideoPointer();
617
618 this->dirty_rect = {};
619 std::string_view err = Resize(w, h);
620 if (!err.empty()) {
622 return false;
623 }
624
625 this->rendertarget.Reset();
626
627 if (!this->swap_chain) {
628 err = this->CreateSwapchain();
629 if (!err.empty()) {
631 return false;
632 }
633 } else {
634 HRESULT result = this->swap_chain->ResizeBuffers(2, w, h, DXGI_FORMAT_B8G8R8A8_UNORM, this->dxgi_flags);
635 if (FAILED(result)) {
636 Debug(Facility::Driver, Severity::Critical, "Failed to resize buffers");
637 return false;
638 }
639 }
640
641 this->dxgi_force_resize_buffer = false;
642
643 ComPtr<ID3D11Texture2D> framebuffer;
644 HRESULT result = this->swap_chain->GetBuffer(0, IID_PPV_ARGS(&framebuffer));
645 if (FAILED(result)) {
646 Debug(Facility::Driver, Severity::Critical, "Failed to get framebuffer");
647 return false;
648 }
649
650 result = device->CreateRenderTargetView(framebuffer.Get(), nullptr, &this->rendertarget);
651 if (FAILED(result)) {
652 Debug(Facility::Driver, Severity::Critical, "Failed to create render target view");
653 return false;
654 }
655
656 _screen.dst_ptr = this->GetVideoPointer();
657 return true;
658}
659
661{
662 if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
663 D3D11_MAPPED_SUBRESOURCE mapped;
664 device_ctx->Map(anim_texture_staging.Get(), 0, D3D11_MAP_READ_WRITE, 0, &mapped);
665 this->anim_buffer = static_cast<uint8_t *>(mapped.pData);
666 this->anim_pitch = mapped.RowPitch;
667 }
668
669 D3D11_MAPPED_SUBRESOURCE mapped;
670 device_ctx->Map(vid_texture_staging.Get(), 0, D3D11_MAP_READ_WRITE, 0, &mapped);
671
673 _screen.pitch = mapped.RowPitch / bpp * 8;
674
675 return mapped.pData;
676}
677
679{
680 if (this->anim_buffer != nullptr) {
681 device_ctx->Unmap(anim_texture_staging.Get(), 0);
682
683 if (!IsEmptyRect(this->dirty_rect)) {
684 D3D11_BOX box{
685 .left = static_cast<UINT>(this->dirty_rect.left),
686 .top = static_cast<UINT>(this->dirty_rect.top),
687 .front = 0,
688 .right = static_cast<UINT>(this->dirty_rect.right),
689 .bottom = static_cast<UINT>(this->dirty_rect.bottom),
690 .back = 1
691 };
692
693 device_ctx->CopySubresourceRegion(anim_texture.Get(), 0, this->dirty_rect.left, this->dirty_rect.top, 0, anim_texture_staging.Get(), 0, &box);
694 }
695 }
696
697 device_ctx->Unmap(vid_texture_staging.Get(), 0);
698
699 if (!IsEmptyRect(this->dirty_rect)) {
700 D3D11_BOX box{
701 .left = static_cast<UINT>(this->dirty_rect.left),
702 .top = static_cast<UINT>(this->dirty_rect.top),
703 .front = 0,
704 .right = static_cast<UINT>(this->dirty_rect.right),
705 .bottom = static_cast<UINT>(this->dirty_rect.bottom),
706 .back = 1
707 };
708
709 device_ctx->CopySubresourceRegion(vid_texture.Get(), 0, this->dirty_rect.left, this->dirty_rect.top, 0, vid_texture_staging.Get(), 0, &box);
710 }
711
712 this->dirty_rect = {};
713 _screen.dst_ptr = nullptr;
714 this->anim_buffer = nullptr;
715 this->anim_pitch = 0;
716}
717
719{
721
722 if (this->dxgi_force_resize_buffer) {
723 this->AllocateBackingStore(this->width, this->height, true);
725 }
726
727 if (local_palette.count_dirty != 0) {
729
730 /* Always push a changed palette to D3D11. */
731 assert(local_palette.first_dirty + local_palette.count_dirty <= 256);
732
733 D3D11_BOX box{
734 .left = static_cast<UINT>(local_palette.first_dirty),
735 .top = 0,
736 .front = 0,
737 .right = static_cast<UINT>(local_palette.first_dirty + local_palette.count_dirty),
738 .bottom = 1,
739 .back = 1
740 };
741
742 device_ctx->UpdateSubresource(pal_texture.Get(), 0, &box, local_palette.palette + local_palette.first_dirty, 256, 0);
743
746 }
747
748 local_palette.count_dirty = 0;
749 }
750
751 FLOAT background_color[4] = { 0.0f, 0.0f, 0.0f, 1.0f };
752 device_ctx->ClearRenderTargetView(rendertarget.Get(), background_color);
753 device_ctx->OMSetRenderTargets(1, rendertarget.GetAddressOf(), nullptr);
754
755 device_ctx->VSSetShader(vertex_shader.Get(), nullptr, 0);
756 device_ctx->VSSetConstantBuffers(0, 1, constant_buffer.GetAddressOf());
757 device_ctx->PSSetConstantBuffers(0, 1, constant_buffer.GetAddressOf());
758
759 ID3D11ShaderResourceView *resources[4] = { nullptr };
760 resources[0] = this->vid_texture_srv.Get();
761 resources[1] = this->pal_texture_srv.Get();
762 if (BlitterFactory::GetCurrentBlitter()->NeedsAnimationBuffer()) {
763 resources[2] = this->anim_texture_srv.Get();
764 device_ctx->PSSetShader(this->rgb_mask_blend_shader.Get(), nullptr, 0);
765 } else {
766 if (BlitterFactory::GetCurrentBlitter()->GetScreenDepth() == 8) {
767 device_ctx->PSSetShader(this->palette_shader.Get(), nullptr, 0);
768 } else {
769 device_ctx->PSSetShader(this->direct_shader.Get(), nullptr, 0);
770 }
771 }
772
773 device_ctx->PSSetSamplers(0, 1, texture_sampler.GetAddressOf());
774 device_ctx->PSSetShaderResources(0, 4, resources);
775
776 D3D11_VIEWPORT viewport = { 0.0f, 0.0f, static_cast<float>(_screen.width), static_cast<float>(_screen.height), 0.0f, 1.0f };
777 device_ctx->RSSetViewports(1, &viewport);
778
779 device_ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
780 device_ctx->Draw(4, 0);
781
782 device_ctx->ClearState();
783
784 UINT swap_flags = (!_video_vsync && !this->dxgi_fullscreen && (this->dxgi_flags & DXGI_SWAP_CHAIN_FLAG_ALLOW_TEARING)) ? DXGI_PRESENT_ALLOW_TEARING : 0;
785 this->swap_chain->Present(_video_vsync ? 1 : 0, swap_flags);
786}
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:139
How all blitters should look like.
Definition base.hpp:28
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.
Definition base.hpp:52
DriverFactoryBase(Driver::Type type, int priority, std::string_view name, std::string_view description)
Construct a new DriverFactory.
Definition driver.cpp:246
A driver for communicating with the user.
Definition driver.h:21
The factory for Windows' D3D11 video driver.
Definition d3d11_v.cpp:221
FVideoDriver_Win32D3D11()
Constructor for the D3D11 video driver factory.
Definition d3d11_v.cpp:224
std::unique_ptr< Driver > CreateInstance() const override
Create an instance of this driver-class.
Definition d3d11_v.cpp:228
bool UsesHardwareAcceleration() const override
Does the driver use hardware acceleration (video-drivers only).
Definition d3d11_v.cpp:234
RAII class for measuring simple elements of performance.
int height
Height in pixels of our display surface.
Definition win32_v.h:49
VideoDriver_Win32Base(bool uses_hardware_acceleration=false, bool supports_animation_buffer=false)
Create the video driver.
Definition win32_v.h:24
void Stop() override
Stop this driver.
Definition win32_v.cpp:1027
HWND main_wnd
Handle to system window.
Definition win32_v.h:44
bool fullscreen
Whether to use (true) fullscreen mode.
Definition win32_v.h:45
bool MakeWindow(bool full_screen, bool resize=true)
Instantiate a new window.
Definition win32_v.cpp:150
int width
Width in pixels of our display surface.
Definition win32_v.h:48
Palette local_palette
Current palette to use for drawing.
Definition win32_v.h:54
void ClientSizeChanged(int w, int h, bool force=false)
Indicate to the driver the client-size might have changed.
Definition win32_v.cpp:1103
Rect dirty_rect
Region of the screen that needs redrawing.
Definition win32_v.h:47
UINT dxgi_flags
DXGI swap chain flags.
Definition d3d11_v.cpp:165
ComPtr< ID3D11VertexShader > vertex_shader
Vertex shader for sprite rendering.
Definition d3d11_v.cpp:195
ComPtr< ID3D11PixelShader > sprite_blend_shader
Pixel shader for sprite blending.
Definition d3d11_v.cpp:199
std::string_view Resize(int w, int h)
Resizes the D3D11 textures to the given width and height.
Definition d3d11_v.cpp:338
bool UseSystemCursor() override
Get whether the mouse cursor is drawn by the video driver.
Definition d3d11_v.cpp:144
ComPtr< ID3D11ShaderResourceView > pal_texture_srv
Shader resource view for palette texture.
Definition d3d11_v.cpp:212
bool AllocateBackingStore(int w, int h, bool force=false) override
(Re-)create the backing store.
Definition d3d11_v.cpp:609
ComPtr< ID3D11ShaderResourceView > vid_texture_srv
Shader resource view for video texture.
Definition d3d11_v.cpp:205
ComPtr< ID3D11Texture2D > vid_texture
Video texture for the back buffer.
Definition d3d11_v.cpp:203
void * GetVideoPointer() override
Get a pointer to the video buffer.
Definition d3d11_v.cpp:660
ComPtr< ID3D11RenderTargetView > rendertarget
D3D11 render target view for the back buffer.
Definition d3d11_v.cpp:161
bool dxgi_force_resize_buffer
Flag indicating whether to force resize the swap chain buffer.
Definition d3d11_v.cpp:163
ComPtr< ID3D11SamplerState > texture_sampler
Sampler state for texture sampling.
Definition d3d11_v.cpp:214
ComPtr< ID3D11Texture2D > anim_texture_staging
Staging texture for animation texture.
Definition d3d11_v.cpp:208
bool dxgi_fullscreen
Flag indicating whether we're in fullscreen mode.
Definition d3d11_v.cpp:164
ComPtr< IDXGISwapChain > swap_chain
DXGI swap chain.
Definition d3d11_v.cpp:160
VideoDriver_Win32D3D11()
Constructor for the D3D11 video driver.
Definition d3d11_v.cpp:125
ComPtr< ID3D11Texture2D > anim_texture
Animation texture for palette animation.
Definition d3d11_v.cpp:207
ComPtr< ID3D11PixelShader > rgb_mask_blend_shader
Pixel shader for RGB mask blending.
Definition d3d11_v.cpp:198
ComPtr< ID3D11Device > device
D3D11 device.
Definition d3d11_v.cpp:192
bool HasEfficient8Bpp() const override
Has this video driver an efficient code path for palette animated 8-bpp sprites?
Definition d3d11_v.cpp:139
ComPtr< ID3D11Texture1D > pal_texture
Palette texture for palette animation.
Definition d3d11_v.cpp:211
void Stop() override
Stop this driver.
Definition d3d11_v.cpp:479
void ReleaseVideoPointer() override
Hand video buffer back to the painting backend.
Definition d3d11_v.cpp:678
ComPtr< ID3D11Buffer > constant_buffer
Constant buffer.
Definition d3d11_v.cpp:201
ComPtr< ID3D11DeviceContext > device_ctx
D3D11 device context.
Definition d3d11_v.cpp:193
std::string_view InitD3D()
Check for the needed D3D11 functionality and allocate all resources.
Definition d3d11_v.cpp:246
ComPtr< ID3D11PixelShader > palette_shader
Pixel shader for palette animation.
Definition d3d11_v.cpp:197
void PaletteChanged(HWND) override
Palette of the window has changed.
Definition d3d11_v.cpp:184
void Paint() override
Paint the window.
Definition d3d11_v.cpp:718
std::string_view GetInfoString() const override
Get some information about the selected driver/backend to be shown to the user.
Definition d3d11_v.cpp:154
ComPtr< ID3D11PixelShader > direct_shader
Pixel shader for direct rendering.
Definition d3d11_v.cpp:196
std::string_view GetName() const override
Get the name of this driver.
Definition d3d11_v.cpp:149
bool ChangeResolution(int w, int h) override
Change the resolution of the window.
Definition d3d11_v.cpp:576
bool MinimiseRestoreWithToggleFullscreen() const override
Whether minimising and restoring fullscreen windows uses ToggleFullscreen.
Definition d3d11_v.cpp:169
ComPtr< ID3D11Texture2D > vid_texture_staging
Staging texture for video texture.
Definition d3d11_v.cpp:204
bool ToggleFullscreen(bool fullscreen) override
Change the full screen setting.
Definition d3d11_v.cpp:588
std::optional< std::string_view > Start(const StringList &param) override
Start this driver.
Definition d3d11_v.cpp:417
ComPtr< ID3D11ShaderResourceView > anim_texture_srv
Shader resource view for animation texture.
Definition d3d11_v.cpp:209
void DestroySwapchain()
Destroys the DXGI swap chain and releases all associated resources.
Definition d3d11_v.cpp:569
std::string driver_info
Information string about selected driver.
Definition d3d11_v.cpp:167
uint8_t GetFullscreenBpp() override
Colour depth to use for fullscreen display modes.
Definition d3d11_v.cpp:174
bool AfterBlitterChange() override
Callback invoked after the blitter was changed.
Definition d3d11_v.cpp:602
std::string_view CreateSwapchain()
Creates a DXGI swap chain for the current window.
Definition d3d11_v.cpp:492
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.
Definition d3d11_v.cpp:47
static pD3DCompile _D3DCompile
Pointer to the D3DCompile function.
Definition d3d11_v.cpp:50
static PFN_D3D11_CREATE_DEVICE _D3D11CreateDevice
Pointer to the D3D11CreateDevice function.
Definition d3d11_v.cpp:49
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.
Definition d3d11_v.cpp:61
static std::string_view CreatePixelShader(ID3D11Device *device, std::string_view source, ComPtr< ID3D11PixelShader > &shader)
Creates a pixel shader from HLSL source code.
Definition d3d11_v.cpp:106
bool _window_maximize
Declared in win32_v.cpp.
Definition win32_v.cpp:58
static FVideoDriver_Win32D3D11 iFVideoDriver_Win32D3D11
Factory instance for the D3D11 video driver.
Definition d3d11_v.cpp:240
static std::string_view CreateVertexShader(ID3D11Device *device, std::string_view source, ComPtr< ID3D11VertexShader > &shader)
Creates a vertex shader from HLSL source code.
Definition d3d11_v.cpp:85
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Driver
Driver message facility.
Definition debug_type.h:29
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
@ Error
Error, but we are recovering.
Definition debug_type.h:16
bool GetDriverParamBool(const StringList &parm, std::string_view name)
Get a boolean parameter the list of parameters.
Definition driver.cpp:67
Error reporting related functions.
Factory to 'query' all available blitters.
Types for recording game performance data.
@ Video
Speed of painting drawn video buffer.
Geometry functions.
bool IsEmptyRect(const Rect &r)
Check if a rectangle is empty.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1548
HLSL shader programs.
static const char _frag_shader_palette_hlsl[]
HLSL pixel shader that reads the fragment colour from a 32bpp texture.
Definition hlsl_shader.h:75
static const char _frag_shader_direct_hlsl[]
HLSL pixel shader that reads the fragment colour from a 32bpp texture.
Definition hlsl_shader.h:57
static const char _vertex_shader_sprite_hlsl[]
HLSL vertex shader that positions a sprite on screen.
Definition hlsl_shader.h:26
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.
Some generic types.
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.
Definition string_type.h:61
Structure for an HLSL constant buffer containing the sprite position, screen size,...
Definition d3d11_v.cpp:37
BOOL rgb
Flag indicating whether RGB mode is enabled.
Definition d3d11_v.cpp:41
FLOAT zoom
Zoom level.
Definition d3d11_v.cpp:40
BOOL crash
Flag indicating whether crash mode is enabled.
Definition d3d11_v.cpp:42
FLOAT sprite[4]
Sprite position.
Definition d3d11_v.cpp:38
FLOAT pad[3]
Padding.
Definition d3d11_v.cpp:43
FLOAT screen[2]
Screen size.
Definition d3d11_v.cpp:39
int16_t Height
Fixed point type for heights.
Definition tgp.cpp:152
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.
Definition win32.cpp:407
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...
Definition window.cpp:3395
Window functions not directly related to making/drawing windows.