-
Notifications
You must be signed in to change notification settings - Fork 8.4k
/
Copy pathBackendD3D.cpp
2274 lines (1972 loc) · 94.7 KB
/
BackendD3D.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include "BackendD3D.h"
#include <til/unicode.h>
#include <custom_shader_ps.h>
#include <custom_shader_vs.h>
#include <shader_ps.h>
#include <shader_vs.h>
#include "BuiltinGlyphs.h"
#include "dwrite.h"
#include "wic.h"
#include "../../types/inc/ColorFix.hpp"
#if ATLAS_DEBUG_SHOW_DIRTY || ATLAS_DEBUG_COLORIZE_GLYPH_ATLAS
#include "colorbrewer.h"
#endif
TIL_FAST_MATH_BEGIN
#pragma warning(disable : 4100) // '...': unreferenced formal parameter
#pragma warning(disable : 26440) // Function '...' can be declared 'noexcept'(f.6).
// This code packs various data into smaller-than-int types to save both CPU and GPU memory. This warning would force
// us to add dozens upon dozens of gsl::narrow_cast<>s throughout the file which is more annoying than helpful.
#pragma warning(disable : 4242) // '=': conversion from '...' to '...', possible loss of data
#pragma warning(disable : 4244) // 'initializing': conversion from '...' to '...', possible loss of data
#pragma warning(disable : 4267) // 'argument': conversion from '...' to '...', possible loss of data
#pragma warning(disable : 4838) // conversion from '...' to '...' requires a narrowing conversion
#pragma warning(disable : 26472) // Don't use a static_cast for arithmetic conversions. Use brace initialization, gsl::narrow_cast or gsl::narrow (type.1).
// Disable a bunch of warnings which get in the way of writing performant code.
#pragma warning(disable : 26429) // Symbol 'data' is never tested for nullness, it can be marked as not_null (f.23).
#pragma warning(disable : 26446) // Prefer to use gsl::at() instead of unchecked subscript operator (bounds.4).
#pragma warning(disable : 26459) // You called an STL function '...' with a raw pointer parameter at position '...' that may be unsafe [...].
#pragma warning(disable : 26481) // Don't use pointer arithmetic. Use span instead (bounds.1).
#pragma warning(disable : 26482) // Only index into arrays using constant expressions (bounds.2).
// Initializing large arrays can be very costly compared to how cheap some of these functions are.
#define ALLOW_UNINITIALIZED_BEGIN _Pragma("warning(push)") _Pragma("warning(disable : 26494)")
#define ALLOW_UNINITIALIZED_END _Pragma("warning(pop)")
using namespace Microsoft::Console::Render::Atlas;
static constexpr D2D1_MATRIX_3X2_F identityTransform{ .m11 = 1, .m22 = 1 };
static constexpr D2D1_COLOR_F whiteColor{ 1, 1, 1, 1 };
static u64 queryPerfFreq() noexcept
{
LARGE_INTEGER li;
QueryPerformanceFrequency(&li);
return std::bit_cast<u64>(li.QuadPart);
}
static u64 queryPerfCount() noexcept
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return std::bit_cast<u64>(li.QuadPart);
}
BackendD3D::BackendD3D(const RenderingPayload& p)
{
THROW_IF_FAILED(p.device->CreateVertexShader(&shader_vs[0], sizeof(shader_vs), nullptr, _vertexShader.addressof()));
THROW_IF_FAILED(p.device->CreatePixelShader(&shader_ps[0], sizeof(shader_ps), nullptr, _pixelShader.addressof()));
{
static constexpr D3D11_INPUT_ELEMENT_DESC layout[]{
{ "SV_Position", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "shadingType", 0, DXGI_FORMAT_R16_UINT, 1, offsetof(QuadInstance, shadingType), D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "renditionScale", 0, DXGI_FORMAT_R8G8_UINT, 1, offsetof(QuadInstance, renditionScale), D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "position", 0, DXGI_FORMAT_R16G16_SINT, 1, offsetof(QuadInstance, position), D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "size", 0, DXGI_FORMAT_R16G16_UINT, 1, offsetof(QuadInstance, size), D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "texcoord", 0, DXGI_FORMAT_R16G16_UINT, 1, offsetof(QuadInstance, texcoord), D3D11_INPUT_PER_INSTANCE_DATA, 1 },
{ "color", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 1, offsetof(QuadInstance, color), D3D11_INPUT_PER_INSTANCE_DATA, 1 },
};
THROW_IF_FAILED(p.device->CreateInputLayout(&layout[0], std::size(layout), &shader_vs[0], sizeof(shader_vs), _inputLayout.addressof()));
}
{
static constexpr f32x2 vertices[]{
{ 0, 0 },
{ 1, 0 },
{ 1, 1 },
{ 0, 1 },
};
static constexpr D3D11_SUBRESOURCE_DATA initialData{ &vertices[0] };
D3D11_BUFFER_DESC desc{};
desc.ByteWidth = sizeof(vertices);
desc.Usage = D3D11_USAGE_IMMUTABLE;
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
THROW_IF_FAILED(p.device->CreateBuffer(&desc, &initialData, _vertexBuffer.addressof()));
}
{
static constexpr u16 indices[]{
0, // { 0, 0 }
1, // { 1, 0 }
2, // { 1, 1 }
2, // { 1, 1 }
3, // { 0, 1 }
0, // { 0, 0 }
};
static constexpr D3D11_SUBRESOURCE_DATA initialData{ &indices[0] };
D3D11_BUFFER_DESC desc{};
desc.ByteWidth = sizeof(indices);
desc.Usage = D3D11_USAGE_IMMUTABLE;
desc.BindFlags = D3D11_BIND_INDEX_BUFFER;
THROW_IF_FAILED(p.device->CreateBuffer(&desc, &initialData, _indexBuffer.addressof()));
}
{
static constexpr D3D11_BUFFER_DESC desc{
.ByteWidth = sizeof(VSConstBuffer),
.Usage = D3D11_USAGE_DEFAULT,
.BindFlags = D3D11_BIND_CONSTANT_BUFFER,
};
THROW_IF_FAILED(p.device->CreateBuffer(&desc, nullptr, _vsConstantBuffer.addressof()));
}
{
static constexpr D3D11_BUFFER_DESC desc{
.ByteWidth = sizeof(PSConstBuffer),
.Usage = D3D11_USAGE_DEFAULT,
.BindFlags = D3D11_BIND_CONSTANT_BUFFER,
};
THROW_IF_FAILED(p.device->CreateBuffer(&desc, nullptr, _psConstantBuffer.addressof()));
}
{
// The final step of the ClearType blending algorithm is a lerp() between the premultiplied alpha
// background color and straight alpha foreground color given the 3 RGB weights in alphaCorrected:
// lerp(background, foreground, weights)
// Which is equivalent to:
// background * (1 - weights) + foreground * weights
//
// This COULD be implemented using dual source color blending like so:
// .SrcBlend = D3D11_BLEND_SRC1_COLOR
// .DestBlend = D3D11_BLEND_INV_SRC1_COLOR
// .BlendOp = D3D11_BLEND_OP_ADD
// Because:
// background * (1 - weights) + foreground * weights
// ^ ^ ^ ^ ^
// Dest INV_SRC1_COLOR | Src SRC1_COLOR
// OP_ADD
//
// BUT we need simultaneous support for regular "source over" alpha blending
// (SHADING_TYPE_PASSTHROUGH) like this:
// background * (1 - alpha) + foreground
//
// This is why we set:
// .SrcBlend = D3D11_BLEND_ONE
//
// --> We need to multiply the foreground with the weights ourselves.
static constexpr D3D11_BLEND_DESC desc{
.RenderTarget = { {
.BlendEnable = TRUE,
.SrcBlend = D3D11_BLEND_ONE,
.DestBlend = D3D11_BLEND_INV_SRC1_COLOR,
.BlendOp = D3D11_BLEND_OP_ADD,
.SrcBlendAlpha = D3D11_BLEND_ONE,
.DestBlendAlpha = D3D11_BLEND_INV_SRC1_ALPHA,
.BlendOpAlpha = D3D11_BLEND_OP_ADD,
.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL,
} },
};
THROW_IF_FAILED(p.device->CreateBlendState(&desc, _blendState.addressof()));
}
#if ATLAS_DEBUG_SHADER_HOT_RELOAD
_sourceDirectory = std::filesystem::path{ __FILE__ }.parent_path();
_sourceCodeWatcher = wil::make_folder_change_reader_nothrow(_sourceDirectory.c_str(), false, wil::FolderChangeEvents::FileName | wil::FolderChangeEvents::LastWriteTime, [this](wil::FolderChangeEvent, PCWSTR path) {
if (til::ends_with(path, L".hlsl"))
{
auto expected = INT64_MAX;
const auto invalidationTime = std::chrono::steady_clock::now() + std::chrono::milliseconds(100);
_sourceCodeInvalidationTime.compare_exchange_strong(expected, invalidationTime.time_since_epoch().count(), std::memory_order_relaxed);
}
});
#endif
}
#pragma warning(suppress : 26432) // If you define or delete any default operation in the type '...', define or delete them all (c.21).
BackendD3D::~BackendD3D()
{
// In case an exception is thrown for some reason between BeginDraw() and EndDraw()
// we still technically need to call EndDraw() before releasing any resources.
if (_d2dBeganDrawing)
{
#pragma warning(suppress : 26447) // The function is declared 'noexcept' but calls function '...' which may throw exceptions (f.6).
LOG_IF_FAILED(_d2dRenderTarget->EndDraw());
}
}
void BackendD3D::ReleaseResources() noexcept
{
_renderTargetView.reset();
_customRenderTargetView.reset();
// Ensure _handleSettingsUpdate() is called so that _renderTarget gets recreated.
_generation = {};
}
void BackendD3D::Render(RenderingPayload& p)
{
if (_generation != p.s.generation())
{
_handleSettingsUpdate(p);
}
_debugUpdateShaders(p);
// After a Present() the render target becomes unbound.
p.deviceContext->OMSetRenderTargets(1, _customRenderTargetView ? _customRenderTargetView.addressof() : _renderTargetView.addressof(), nullptr);
// Invalidating the render target helps with spotting invalid quad instances and Present1() bugs.
#if ATLAS_DEBUG_SHOW_DIRTY || ATLAS_DEBUG_DUMP_RENDER_TARGET
{
static constexpr f32 clearColor[4]{};
p.deviceContext->ClearView(_renderTargetView.get(), &clearColor[0], nullptr, 0);
}
#endif
_drawBackground(p);
_drawCursorBackground(p);
_drawText(p);
_drawSelection(p);
_debugShowDirty(p);
_flushQuads(p);
if (_customPixelShader)
{
_executeCustomShader(p);
}
_debugDumpRenderTarget(p);
}
bool BackendD3D::RequiresContinuousRedraw() noexcept
{
return _requiresContinuousRedraw;
}
void BackendD3D::_handleSettingsUpdate(const RenderingPayload& p)
{
if (!_renderTargetView)
{
wil::com_ptr<ID3D11Texture2D> buffer;
THROW_IF_FAILED(p.swapChain.swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), reinterpret_cast<void**>(buffer.addressof())));
THROW_IF_FAILED(p.device->CreateRenderTargetView(buffer.get(), nullptr, _renderTargetView.put()));
}
const auto fontChanged = _fontGeneration != p.s->font.generation();
const auto miscChanged = _miscGeneration != p.s->misc.generation();
const auto cellCountChanged = _viewportCellCount != p.s->viewportCellCount;
if (fontChanged)
{
_updateFontDependents(p);
}
if (miscChanged)
{
_recreateCustomShader(p);
}
if (cellCountChanged)
{
_recreateBackgroundColorBitmap(p);
}
// Similar to _renderTargetView above, we might have to recreate the _customRenderTargetView whenever _swapChainManager
// resets it. We only do it after calling _recreateCustomShader however, since that sets the _customPixelShader.
if (_customPixelShader && !_customRenderTargetView)
{
_recreateCustomRenderTargetView(p);
}
_recreateConstBuffer(p);
_setupDeviceContextState(p);
_generation = p.s.generation();
_fontGeneration = p.s->font.generation();
_miscGeneration = p.s->misc.generation();
_targetSize = p.s->targetSize;
_viewportCellCount = p.s->viewportCellCount;
}
void BackendD3D::_updateFontDependents(const RenderingPayload& p)
{
const auto& font = *p.s->font;
// Curlyline is drawn with a desired height relative to the font size. The
// baseline of curlyline is at the middle of singly underline. When there's
// limited space to draw a curlyline, we apply a limit on the peak height.
{
const int cellHeight = font.cellSize.y;
const int duTop = font.doubleUnderline[0].position;
const int duBottom = font.doubleUnderline[1].position;
const int duHeight = font.doubleUnderline[0].height;
// This gives it the same position and height as our double-underline. There's no particular reason for that, apart from
// it being simple to implement and robust against more peculiar fonts with unusually large/small descenders, etc.
// We still need to ensure though that it doesn't clip out of the cellHeight at the bottom, which is why `position` has a min().
const auto height = std::max(3, duBottom + duHeight - duTop);
const auto position = std::min(duTop, cellHeight - height - duHeight);
_curlyLineHalfHeight = height * 0.5f;
_curlyUnderline.position = gsl::narrow_cast<u16>(position);
_curlyUnderline.height = gsl::narrow_cast<u16>(height);
}
DWrite_GetRenderParams(p.dwriteFactory.get(), &_gamma, &_cleartypeEnhancedContrast, &_grayscaleEnhancedContrast, _textRenderingParams.put());
// Clearing the atlas requires BeginDraw(), which is expensive. Defer this until we need Direct2D anyways.
_fontChangedResetGlyphAtlas = true;
_textShadingType = font.antialiasingMode == AntialiasingMode::ClearType ? ShadingType::TextClearType : ShadingType::TextGrayscale;
// _ligatureOverhangTriggerLeft/Right are essentially thresholds for a glyph's width at
// which point we consider it wider than allowed and "this looks like a coding ligature".
// See _drawTextOverlapSplit for more information about what this does.
{
// No ligatures -> No thresholds.
auto ligaturesDisabled = false;
for (const auto& feature : font.fontFeatures)
{
if (feature.nameTag == DWRITE_FONT_FEATURE_TAG_STANDARD_LIGATURES)
{
ligaturesDisabled = !feature.parameter;
break;
}
}
if (ligaturesDisabled)
{
_ligatureOverhangTriggerLeft = til::CoordTypeMin;
_ligatureOverhangTriggerRight = til::CoordTypeMax;
}
else
{
const auto halfCellWidth = font.cellSize.x / 2;
_ligatureOverhangTriggerLeft = -halfCellWidth;
_ligatureOverhangTriggerRight = font.advanceWidth + halfCellWidth;
}
}
if (_d2dRenderTarget)
{
_d2dRenderTargetUpdateFontSettings(p);
}
_softFontBitmap.reset();
}
void BackendD3D::_d2dRenderTargetUpdateFontSettings(const RenderingPayload& p) const noexcept
{
const auto& font = *p.s->font;
_d2dRenderTarget->SetDpi(font.dpi, font.dpi);
_d2dRenderTarget->SetTextAntialiasMode(static_cast<D2D1_TEXT_ANTIALIAS_MODE>(font.antialiasingMode));
}
void BackendD3D::_recreateCustomShader(const RenderingPayload& p)
{
_customRenderTargetView.reset();
_customOffscreenTexture.reset();
_customOffscreenTextureView.reset();
_customVertexShader.reset();
_customPixelShader.reset();
_customShaderConstantBuffer.reset();
_customShaderSamplerState.reset();
_customShaderTexture.reset();
_customShaderTextureView.reset();
_requiresContinuousRedraw = false;
if (!p.s->misc->customPixelShaderPath.empty())
{
const char* target = nullptr;
switch (p.device->GetFeatureLevel())
{
case D3D_FEATURE_LEVEL_10_0:
target = "ps_4_0";
break;
case D3D_FEATURE_LEVEL_10_1:
target = "ps_4_1";
break;
default:
target = "ps_5_0";
break;
}
static constexpr auto flags =
D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR
#ifdef NDEBUG
| D3DCOMPILE_OPTIMIZATION_LEVEL3;
#else
// Only enable strictness and warnings in DEBUG mode
// as these settings makes it very difficult to develop
// shaders as windows terminal is not telling the user
// what's wrong, windows terminal just fails.
// Keep it in DEBUG mode to catch errors in shaders
// shipped with windows terminal
| D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_WARNINGS_ARE_ERRORS | D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION;
#endif
wil::com_ptr<ID3DBlob> error;
wil::com_ptr<ID3DBlob> blob;
const auto hr = D3DCompileFromFile(
/* pFileName */ p.s->misc->customPixelShaderPath.c_str(),
/* pDefines */ nullptr,
/* pInclude */ D3D_COMPILE_STANDARD_FILE_INCLUDE,
/* pEntrypoint */ "main",
/* pTarget */ target,
/* Flags1 */ flags,
/* Flags2 */ 0,
/* ppCode */ blob.addressof(),
/* ppErrorMsgs */ error.addressof());
if (SUCCEEDED(hr))
{
THROW_IF_FAILED(p.device->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, _customPixelShader.addressof()));
// Try to determine whether the shader uses the Time variable
wil::com_ptr<ID3D11ShaderReflection> reflector;
if (SUCCEEDED_LOG(D3DReflect(blob->GetBufferPointer(), blob->GetBufferSize(), IID_PPV_ARGS(reflector.addressof()))))
{
// Depending on the version of the d3dcompiler_*.dll, the next two functions either return nullptr
// on failure or an instance of CInvalidSRConstantBuffer or CInvalidSRVariable respectively,
// which cause GetDesc() to return E_FAIL. In other words, we have to assume that any failure in the
// next few lines indicates that the cbuffer is entirely unused (--> _requiresContinuousRedraw=false).
if (ID3D11ShaderReflectionConstantBuffer* constantBufferReflector = reflector->GetConstantBufferByIndex(0)) // shader buffer
{
if (ID3D11ShaderReflectionVariable* variableReflector = constantBufferReflector->GetVariableByIndex(0)) // time
{
D3D11_SHADER_VARIABLE_DESC variableDescriptor;
if (SUCCEEDED(variableReflector->GetDesc(&variableDescriptor)))
{
// only if time is used
_requiresContinuousRedraw = WI_IsFlagSet(variableDescriptor.uFlags, D3D_SVF_USED);
}
}
}
}
else
{
// Unless we can determine otherwise, assume this shader requires evaluation every frame
_requiresContinuousRedraw = true;
}
}
else
{
if (error)
{
LOG_HR_MSG(hr, "%.*hs", static_cast<int>(error->GetBufferSize()), static_cast<char*>(error->GetBufferPointer()));
}
else
{
LOG_HR(hr);
}
if (p.warningCallback)
{
p.warningCallback(D2DERR_SHADER_COMPILE_FAILED, p.s->misc->customPixelShaderPath);
}
}
if (!p.s->misc->customPixelShaderImagePath.empty())
{
try
{
WIC::LoadTextureFromFile(p.device.get(), p.s->misc->customPixelShaderImagePath.c_str(), _customShaderTexture.addressof(), _customShaderTextureView.addressof());
}
catch (...)
{
LOG_CAUGHT_EXCEPTION();
_customPixelShader.reset();
if (p.warningCallback)
{
p.warningCallback(D2DERR_SHADER_COMPILE_FAILED, p.s->misc->customPixelShaderImagePath);
}
}
}
}
else if (p.s->misc->useRetroTerminalEffect)
{
THROW_IF_FAILED(p.device->CreatePixelShader(&custom_shader_ps[0], sizeof(custom_shader_ps), nullptr, _customPixelShader.put()));
}
if (_customPixelShader)
{
THROW_IF_FAILED(p.device->CreateVertexShader(&custom_shader_vs[0], sizeof(custom_shader_vs), nullptr, _customVertexShader.put()));
{
static constexpr D3D11_BUFFER_DESC desc{
.ByteWidth = sizeof(CustomConstBuffer),
.Usage = D3D11_USAGE_DYNAMIC,
.BindFlags = D3D11_BIND_CONSTANT_BUFFER,
.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE,
};
THROW_IF_FAILED(p.device->CreateBuffer(&desc, nullptr, _customShaderConstantBuffer.put()));
}
{
static constexpr D3D11_SAMPLER_DESC desc{
.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR,
.AddressU = D3D11_TEXTURE_ADDRESS_BORDER,
.AddressV = D3D11_TEXTURE_ADDRESS_BORDER,
.AddressW = D3D11_TEXTURE_ADDRESS_BORDER,
.MaxAnisotropy = 1,
.ComparisonFunc = D3D11_COMPARISON_ALWAYS,
.MaxLOD = D3D11_FLOAT32_MAX,
};
THROW_IF_FAILED(p.device->CreateSamplerState(&desc, _customShaderSamplerState.put()));
}
// Since floats are imprecise we need to constrain the time value into a range that can be accurately represented.
// Assuming a monitor refresh rate of 1000 Hz, we can still easily represent 1000 seconds accurately (roughly 16 minutes).
// 10000 seconds would already result in a 50% error. So to avoid this, we use queryPerfCount() modulo _customShaderPerfTickMod.
// The use of a power of 10 is intentional, because shaders are often periodic and this makes any decimal multiplier up to 3 fractional
// digits not break the periodicity. For instance, with a wraparound of 1000 seconds sin(1.234*x) is still perfectly periodic.
const auto freq = queryPerfFreq();
_customShaderPerfTickMod = freq * 1000;
_customShaderSecsPerPerfTick = 1.0f / freq;
}
}
void BackendD3D::_recreateCustomRenderTargetView(const RenderingPayload& p)
{
// Avoid memory usage spikes by releasing memory first.
_customOffscreenTexture.reset();
_customOffscreenTextureView.reset();
const D3D11_TEXTURE2D_DESC desc{
.Width = p.s->targetSize.x,
.Height = p.s->targetSize.y,
.MipLevels = 1,
.ArraySize = 1,
.Format = DXGI_FORMAT_B8G8R8A8_UNORM,
.SampleDesc = { 1, 0 },
.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET,
};
THROW_IF_FAILED(p.device->CreateTexture2D(&desc, nullptr, _customOffscreenTexture.addressof()));
THROW_IF_FAILED(p.device->CreateShaderResourceView(_customOffscreenTexture.get(), nullptr, _customOffscreenTextureView.addressof()));
THROW_IF_FAILED(p.device->CreateRenderTargetView(_customOffscreenTexture.get(), nullptr, _customRenderTargetView.addressof()));
}
void BackendD3D::_recreateBackgroundColorBitmap(const RenderingPayload& p)
{
// Avoid memory usage spikes by releasing memory first.
_backgroundBitmap.reset();
_backgroundBitmapView.reset();
const D3D11_TEXTURE2D_DESC desc{
.Width = p.s->viewportCellCount.x,
.Height = p.s->viewportCellCount.y,
.MipLevels = 1,
.ArraySize = 1,
.Format = DXGI_FORMAT_R8G8B8A8_UNORM,
.SampleDesc = { 1, 0 },
.Usage = D3D11_USAGE_DYNAMIC,
.BindFlags = D3D11_BIND_SHADER_RESOURCE,
.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE,
};
THROW_IF_FAILED(p.device->CreateTexture2D(&desc, nullptr, _backgroundBitmap.addressof()));
THROW_IF_FAILED(p.device->CreateShaderResourceView(_backgroundBitmap.get(), nullptr, _backgroundBitmapView.addressof()));
_backgroundBitmapGeneration = {};
}
void BackendD3D::_recreateConstBuffer(const RenderingPayload& p) const
{
{
VSConstBuffer data{};
data.positionScale = { 2.0f / p.s->targetSize.x, -2.0f / p.s->targetSize.y };
p.deviceContext->UpdateSubresource(_vsConstantBuffer.get(), 0, nullptr, &data, 0, 0);
}
{
PSConstBuffer data{};
data.backgroundColor = colorFromU32Premultiply<f32x4>(p.s->misc->backgroundColor);
data.backgroundCellSize = { static_cast<f32>(p.s->font->cellSize.x), static_cast<f32>(p.s->font->cellSize.y) };
data.backgroundCellCount = { static_cast<f32>(p.s->viewportCellCount.x), static_cast<f32>(p.s->viewportCellCount.y) };
DWrite_GetGammaRatios(_gamma, data.gammaRatios);
data.enhancedContrast = p.s->font->antialiasingMode == AntialiasingMode::ClearType ? _cleartypeEnhancedContrast : _grayscaleEnhancedContrast;
data.underlineWidth = p.s->font->underline.height;
data.doubleUnderlineWidth = p.s->font->doubleUnderline[0].height;
data.curlyLineHalfHeight = _curlyLineHalfHeight;
data.shadedGlyphDotSize = std::max(1.0f, std::roundf(std::max(p.s->font->cellSize.x / 16.0f, p.s->font->cellSize.y / 32.0f)));
p.deviceContext->UpdateSubresource(_psConstantBuffer.get(), 0, nullptr, &data, 0, 0);
}
}
void BackendD3D::_setupDeviceContextState(const RenderingPayload& p)
{
// IA: Input Assembler
ID3D11Buffer* vertexBuffers[]{ _vertexBuffer.get(), _instanceBuffer.get() };
static constexpr UINT strides[]{ sizeof(f32x2), sizeof(QuadInstance) };
static constexpr UINT offsets[]{ 0, 0 };
p.deviceContext->IASetIndexBuffer(_indexBuffer.get(), DXGI_FORMAT_R16_UINT, 0);
p.deviceContext->IASetInputLayout(_inputLayout.get());
p.deviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
p.deviceContext->IASetVertexBuffers(0, 2, &vertexBuffers[0], &strides[0], &offsets[0]);
// VS: Vertex Shader
p.deviceContext->VSSetShader(_vertexShader.get(), nullptr, 0);
p.deviceContext->VSSetConstantBuffers(0, 1, _vsConstantBuffer.addressof());
// RS: Rasterizer Stage
D3D11_VIEWPORT viewport{};
viewport.Width = static_cast<f32>(p.s->targetSize.x);
viewport.Height = static_cast<f32>(p.s->targetSize.y);
p.deviceContext->RSSetViewports(1, &viewport);
// PS: Pixel Shader
ID3D11ShaderResourceView* resources[]{ _backgroundBitmapView.get(), _glyphAtlasView.get() };
p.deviceContext->PSSetShader(_pixelShader.get(), nullptr, 0);
p.deviceContext->PSSetConstantBuffers(0, 1, _psConstantBuffer.addressof());
p.deviceContext->PSSetShaderResources(0, 2, &resources[0]);
// OM: Output Merger
p.deviceContext->OMSetBlendState(_blendState.get(), nullptr, 0xffffffff);
p.deviceContext->OMSetRenderTargets(1, _customRenderTargetView ? _customRenderTargetView.addressof() : _renderTargetView.addressof(), nullptr);
}
void BackendD3D::_debugUpdateShaders(const RenderingPayload& p) noexcept
{
#if ATLAS_DEBUG_SHADER_HOT_RELOAD
try
{
const auto invalidationTime = _sourceCodeInvalidationTime.load(std::memory_order_relaxed);
if (invalidationTime == INT64_MAX || invalidationTime > std::chrono::steady_clock::now().time_since_epoch().count())
{
return;
}
_sourceCodeInvalidationTime.store(INT64_MAX, std::memory_order_relaxed);
static constexpr auto flags =
D3DCOMPILE_PACK_MATRIX_COLUMN_MAJOR | D3DCOMPILE_ENABLE_STRICTNESS | D3DCOMPILE_WARNINGS_ARE_ERRORS
#ifndef NDEBUG
| D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION
#endif
;
static const auto compile = [](const std::filesystem::path& path, const char* target) {
wil::com_ptr<ID3DBlob> error;
wil::com_ptr<ID3DBlob> blob;
const auto hr = D3DCompileFromFile(
/* pFileName */ path.c_str(),
/* pDefines */ nullptr,
/* pInclude */ D3D_COMPILE_STANDARD_FILE_INCLUDE,
/* pEntrypoint */ "main",
/* pTarget */ target,
/* Flags1 */ flags,
/* Flags2 */ 0,
/* ppCode */ blob.addressof(),
/* ppErrorMsgs */ error.addressof());
if (error)
{
std::thread t{ [error = std::move(error)]() noexcept {
MessageBoxA(nullptr, static_cast<const char*>(error->GetBufferPointer()), "Compilation error", MB_ICONERROR | MB_OK);
} };
t.detach();
}
THROW_IF_FAILED(hr);
return blob;
};
struct FileVS
{
std::wstring_view filename;
wil::com_ptr<ID3D11VertexShader> BackendD3D::*target;
};
struct FilePS
{
std::wstring_view filename;
wil::com_ptr<ID3D11PixelShader> BackendD3D::*target;
};
static constexpr std::array filesVS{
FileVS{ L"shader_vs.hlsl", &BackendD3D::_vertexShader },
};
static constexpr std::array filesPS{
FilePS{ L"shader_ps.hlsl", &BackendD3D::_pixelShader },
};
std::array<wil::com_ptr<ID3D11VertexShader>, filesVS.size()> compiledVS;
std::array<wil::com_ptr<ID3D11PixelShader>, filesPS.size()> compiledPS;
// Compile our files before moving them into `this` below to ensure we're
// always in a consistent state where all shaders are seemingly valid.
for (size_t i = 0; i < filesVS.size(); ++i)
{
const auto blob = compile(_sourceDirectory / filesVS[i].filename, "vs_4_0");
THROW_IF_FAILED(p.device->CreateVertexShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, compiledVS[i].addressof()));
}
for (size_t i = 0; i < filesPS.size(); ++i)
{
const auto blob = compile(_sourceDirectory / filesPS[i].filename, "ps_4_0");
THROW_IF_FAILED(p.device->CreatePixelShader(blob->GetBufferPointer(), blob->GetBufferSize(), nullptr, compiledPS[i].addressof()));
}
for (size_t i = 0; i < filesVS.size(); ++i)
{
this->*filesVS[i].target = std::move(compiledVS[i]);
}
for (size_t i = 0; i < filesPS.size(); ++i)
{
this->*filesPS[i].target = std::move(compiledPS[i]);
}
_setupDeviceContextState(p);
}
CATCH_LOG()
#endif
}
void BackendD3D::_d2dBeginDrawing() noexcept
{
if (!_d2dBeganDrawing)
{
_d2dRenderTarget->BeginDraw();
_d2dBeganDrawing = true;
}
}
void BackendD3D::_d2dEndDrawing()
{
if (_d2dBeganDrawing)
{
THROW_IF_FAILED(_d2dRenderTarget->EndDraw());
_d2dBeganDrawing = false;
}
}
void BackendD3D::_resetGlyphAtlas(const RenderingPayload& p)
{
// The index returned by _BitScanReverse is undefined when the input is 0. We can simultaneously guard
// against that and avoid unreasonably small textures, by clamping the min. texture size to `minArea`.
// `minArea` results in a 64kB RGBA texture which is the min. alignment for placed memory.
static constexpr u32 minArea = 128 * 128;
static constexpr u32 maxArea = D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION * D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION;
const auto cellArea = static_cast<u32>(p.s->font->cellSize.x) * p.s->font->cellSize.y;
const auto targetArea = static_cast<u32>(p.s->targetSize.x) * p.s->targetSize.y;
const auto minAreaByFont = cellArea * 95; // Covers all printable ASCII characters
const auto minAreaByGrowth = static_cast<u32>(_rectPacker.width) * _rectPacker.height * 2;
// It's hard to say what the max. size of the cache should be. Optimally I think we should use as much
// memory as is available, but the rendering code in this project is a big mess and so integrating
// memory pressure feedback (RegisterVideoMemoryBudgetChangeNotificationEvent) is rather difficult.
// As an alternative I'm using 1.25x the size of the swap chain. The 1.25x is there to avoid situations, where
// we're locked into a state, where on every render pass we're starting with a half full atlas, drawing once,
// filling it with the remaining half and drawing again, requiring two rendering passes on each frame.
const auto maxAreaByFont = targetArea + targetArea / 4;
auto area = std::min(maxAreaByFont, std::max(minAreaByFont, minAreaByGrowth));
area = clamp(area, minArea, maxArea);
// This block of code calculates the size of a power-of-2 texture that has an area larger than the given `area`.
// For instance, for an area of 985x1946 = 1916810 it would result in a u/v of 2048x1024 (area = 2097152).
// This has 2 benefits: GPUs like power-of-2 textures and it ensures that we don't resize the texture
// every time you resize the window by a pixel. Instead it only grows/shrinks by a factor of 2.
unsigned long index;
_BitScanReverse(&index, area - 1);
const auto u = static_cast<u16>(1u << ((index + 2) / 2));
const auto v = static_cast<u16>(1u << ((index + 1) / 2));
if (u != _rectPacker.width || v != _rectPacker.height)
{
_resizeGlyphAtlas(p, u, v);
}
stbrp_init_target(&_rectPacker, u, v, _rectPackerData.data(), _rectPackerData.size());
// This is a little imperfect, because it only releases the memory of the glyph mappings, not the memory held by
// any DirectWrite fonts. On the other side, the amount of fonts on a system is always finite, where "finite"
// is pretty low, relatively speaking. Additionally this allows us to cache the boxGlyphs map indefinitely.
// It's not great, but it's not terrible.
for (auto& slot : _glyphAtlasMap.container())
{
for (auto& glyphs : slot.glyphs)
{
glyphs.clear();
}
}
for (auto& glyphs : _builtinGlyphs.glyphs)
{
glyphs.clear();
}
_d2dBeginDrawing();
_d2dRenderTarget->Clear();
_fontChangedResetGlyphAtlas = false;
}
void BackendD3D::_resizeGlyphAtlas(const RenderingPayload& p, const u16 u, const u16 v)
{
_d2dRenderTarget.reset();
_d2dRenderTarget4.reset();
_glyphAtlas.reset();
_glyphAtlasView.reset();
{
const D3D11_TEXTURE2D_DESC desc{
.Width = u,
.Height = v,
.MipLevels = 1,
.ArraySize = 1,
.Format = DXGI_FORMAT_B8G8R8A8_UNORM,
.SampleDesc = { 1, 0 },
.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET,
};
THROW_IF_FAILED(p.device->CreateTexture2D(&desc, nullptr, _glyphAtlas.addressof()));
THROW_IF_FAILED(p.device->CreateShaderResourceView(_glyphAtlas.get(), nullptr, _glyphAtlasView.addressof()));
}
{
const auto surface = _glyphAtlas.query<IDXGISurface>();
static constexpr D2D1_RENDER_TARGET_PROPERTIES props{
.type = D2D1_RENDER_TARGET_TYPE_DEFAULT,
.pixelFormat = { DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED },
};
// ID2D1RenderTarget and ID2D1DeviceContext are the same and I'm tired of pretending they're not.
THROW_IF_FAILED(p.d2dFactory->CreateDxgiSurfaceRenderTarget(surface.get(), &props, reinterpret_cast<ID2D1RenderTarget**>(_d2dRenderTarget.addressof())));
_d2dRenderTarget.try_query_to(_d2dRenderTarget4.addressof());
_d2dRenderTarget->SetUnitMode(D2D1_UNIT_MODE_PIXELS);
// Ensure that D2D uses the exact same gamma as our shader uses.
_d2dRenderTarget->SetTextRenderingParams(_textRenderingParams.get());
_d2dRenderTargetUpdateFontSettings(p);
}
// We have our own glyph cache so Direct2D's cache doesn't help much.
// This saves us 1MB of RAM, which is not much, but also not nothing.
if (_d2dRenderTarget4)
{
wil::com_ptr<ID2D1Device> device;
_d2dRenderTarget4->GetDevice(device.addressof());
device->SetMaximumTextureMemory(0);
if (const auto device4 = device.try_query<ID2D1Device4>())
{
device4->SetMaximumColorGlyphCacheMemory(0);
}
}
{
THROW_IF_FAILED(_d2dRenderTarget->CreateSolidColorBrush(&whiteColor, nullptr, _emojiBrush.put()));
THROW_IF_FAILED(_d2dRenderTarget->CreateSolidColorBrush(&whiteColor, nullptr, _brush.put()));
}
ID3D11ShaderResourceView* resources[]{ _backgroundBitmapView.get(), _glyphAtlasView.get() };
p.deviceContext->PSSetShaderResources(0, 2, &resources[0]);
_rectPackerData = Buffer<stbrp_node>{ u };
}
BackendD3D::QuadInstance& BackendD3D::_getLastQuad() noexcept
{
assert(_instancesCount != 0);
return _instances[_instancesCount - 1];
}
// NOTE: Up to 5M calls per second -> no std::vector, no std::unordered_map.
// This function is an easy >100x faster than std::vector, can be
// inlined and reduces overall (!) renderer CPU usage by 5%.
BackendD3D::QuadInstance& BackendD3D::_appendQuad()
{
if (_instancesCount >= _instances.size())
{
_bumpInstancesSize();
}
return _instances[_instancesCount++];
}
void BackendD3D::_bumpInstancesSize()
{
auto newSize = std::max(_instancesCount, _instances.size() * 2);
newSize = std::max(size_t{ 256 }, newSize);
Expects(newSize > _instances.size());
// Our render loop heavily relies on memcpy() which is up to between 1.5x (Intel)
// and 40x (AMD) faster for allocations with an alignment of 32 or greater.
auto newInstances = Buffer<QuadInstance, 32>{ newSize };
std::copy_n(_instances.data(), _instances.size(), newInstances.data());
_instances = std::move(newInstances);
}
void BackendD3D::_flushQuads(const RenderingPayload& p)
{
if (!_instancesCount)
{
return;
}
if (!_cursorRects.empty())
{
_drawCursorForeground();
}
// TODO: Shrink instances buffer
if (_instancesCount > _instanceBufferCapacity)
{
_recreateInstanceBuffers(p);
}
{
D3D11_MAPPED_SUBRESOURCE mapped{};
THROW_IF_FAILED(p.deviceContext->Map(_instanceBuffer.get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped));
memcpy(mapped.pData, _instances.data(), _instancesCount * sizeof(QuadInstance));
p.deviceContext->Unmap(_instanceBuffer.get(), 0);
}
// I found 4 approaches to drawing lots of quads quickly. There are probably even more.
// They can often be found in discussions about "particle" or "point sprite" rendering in game development.
// * Compute Shader: My understanding is that at the time of writing games are moving over to bucketing
// particles into "tiles" on the screen and drawing them with a compute shader. While this improves
// performance, it doesn't mix well with our goal of allowing arbitrary overlaps between glyphs.
// Additionally none of the next 3 approaches use any significant amount of GPU time in the first place.
// * Geometry Shader: Geometry shaders can generate vertices on the fly, which would neatly replace our need
// for an index buffer. However, many sources claim they're significantly slower than the following approaches.
// * DrawIndexed & DrawInstanced: Again, many sources claim that GPU instancing (Draw(Indexed)Instanced) performs
// poorly for small meshes, and instead indexed vertices with a SRV (shader resource view) should be used.
// The popular "Vertex Shader Tricks" talk from Bill Bilodeau at GDC 2014 suggests this approach, explains
// how it works (you divide the `SV_VertexID` by 4 and index into the SRV that contains the per-instance data;
// it's basically manual instancing inside the vertex shader) and shows how it outperforms regular instancing.
// However on my own limited test hardware (built around ~2020), I found that for at least our use case,
// GPU instancing matches the performance of using a custom buffer. In fact on my Nvidia GPU in particular,
// instancing with ~10k instances appears to be about 50% faster and so DrawInstanced was chosen.
// Instead I found that packing instance data as tightly as possible made the biggest performance difference,
// and packing 16 bit integers with ID3D11InputLayout is quite a bit more convenient too.
p.deviceContext->DrawIndexedInstanced(6, static_cast<UINT>(_instancesCount), 0, 0, 0);
_instancesCount = 0;
}
void BackendD3D::_recreateInstanceBuffers(const RenderingPayload& p)
{
// We use the viewport size of the terminal as the initial estimate for the amount of instances we'll see.
const auto minCapacity = static_cast<size_t>(p.s->viewportCellCount.x) * p.s->viewportCellCount.y;
auto newCapacity = std::max(_instancesCount, minCapacity);
auto newSize = newCapacity * sizeof(QuadInstance);
// Round up to multiples of 64kB to avoid reallocating too often.
// 64kB is the minimum alignment for committed resources in D3D12.
newSize = alignForward<size_t>(newSize, 64 * 1024);
newCapacity = newSize / sizeof(QuadInstance);
_instanceBuffer.reset();
{
const D3D11_BUFFER_DESC desc{
.ByteWidth = gsl::narrow<UINT>(newSize),
.Usage = D3D11_USAGE_DYNAMIC,
.BindFlags = D3D11_BIND_VERTEX_BUFFER,
.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE,
.StructureByteStride = sizeof(QuadInstance),
};
THROW_IF_FAILED(p.device->CreateBuffer(&desc, nullptr, _instanceBuffer.addressof()));
}
// IA: Input Assembler
ID3D11Buffer* vertexBuffers[]{ _vertexBuffer.get(), _instanceBuffer.get() };
static constexpr UINT strides[]{ sizeof(f32x2), sizeof(QuadInstance) };
static constexpr UINT offsets[]{ 0, 0 };
p.deviceContext->IASetVertexBuffers(0, 2, &vertexBuffers[0], &strides[0], &offsets[0]);
_instanceBufferCapacity = newCapacity;
}
void BackendD3D::_drawBackground(const RenderingPayload& p)
{
// Not uploading the bitmap halves (!) the GPU load for any given frame on 2023 hardware.
if (_backgroundBitmapGeneration != p.colorBitmapGenerations[0])
{
_uploadBackgroundBitmap(p);
}
_appendQuad() = {
.shadingType = static_cast<u16>(ShadingType::Background),
.size = p.s->targetSize,
};
}
void BackendD3D::_uploadBackgroundBitmap(const RenderingPayload& p)
{
D3D11_MAPPED_SUBRESOURCE mapped{};
THROW_IF_FAILED(p.deviceContext->Map(_backgroundBitmap.get(), 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped));
auto src = std::bit_cast<const char*>(p.backgroundBitmap.data());
const auto srcEnd = std::bit_cast<const char*>(p.backgroundBitmap.data() + p.backgroundBitmap.size());
const auto srcStride = p.colorBitmapRowStride * sizeof(u32);
auto dst = static_cast<char*>(mapped.pData);
while (src < srcEnd)