-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathImGui.cpp
More file actions
1528 lines (1320 loc) · 61.2 KB
/
ImGui.cpp
File metadata and controls
1528 lines (1320 loc) · 61.2 KB
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
#include <iostream>
#include <map>
#include <ranges>
#include <vector>
#include <utility>
#include <locale>
#include <codecvt>
#include "nbl/system/CStdoutLogger.h"
#include "nbl/ext/ImGui/ImGui.h"
#include "nbl/ext/ImGui/builtin/hlsl/common.hlsl"
#include "imgui/imgui.h"
#include "imgui/imgui_internal.h"
#include "imgui/misc/cpp/imgui_stdlib.h"
#ifdef NBL_EMBED_BUILTIN_RESOURCES
#include "nbl/ext/ImGui/builtin/CArchive.h"
#endif
using namespace nbl::video;
using namespace nbl::core;
using namespace nbl::asset;
using namespace nbl::system;
using namespace nbl::ui;
using namespace nbl::hlsl;
namespace nbl::ext::imgui
{
static constexpr SPushConstantRange PushConstantRanges[] =
{
{
.stageFlags = IShader::E_SHADER_STAGE::ESS_VERTEX | IShader::E_SHADER_STAGE::ESS_FRAGMENT,
.offset = 0,
.size = sizeof(PushConstants)
}
};
smart_refctd_ptr<IGPUPipelineLayout> UI::createDefaultPipelineLayout(ILogicalDevice* const device, const SResourceParameters::SBindingInfo texturesInfo, const SResourceParameters::SBindingInfo samplersInfo, uint32_t texturesCount)
{
if (!device)
return nullptr;
if (texturesInfo.bindingIx == samplersInfo.bindingIx)
return nullptr;
if (!texturesCount)
return nullptr;
smart_refctd_ptr<IGPUSampler> fontAtlasUISampler, userTexturesSampler;
using binding_flags_t = IGPUDescriptorSetLayout::SBinding::E_CREATE_FLAGS;
{
IGPUSampler::SParams params;
params.AnisotropicFilter = 1u;
params.TextureWrapU = ISampler::E_TEXTURE_CLAMP::ETC_REPEAT;
params.TextureWrapV = ISampler::E_TEXTURE_CLAMP::ETC_REPEAT;
params.TextureWrapW = ISampler::E_TEXTURE_CLAMP::ETC_REPEAT;
fontAtlasUISampler = device->createSampler(params);
fontAtlasUISampler->setObjectDebugName("Nabla default ImGUI font UI sampler");
}
{
IGPUSampler::SParams params;
params.MinLod = 0.f;
params.MaxLod = 0.f;
params.TextureWrapU = ISampler::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
params.TextureWrapV = ISampler::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
params.TextureWrapW = ISampler::E_TEXTURE_CLAMP::ETC_CLAMP_TO_EDGE;
userTexturesSampler = device->createSampler(params);
userTexturesSampler->setObjectDebugName("Nabla default ImGUI user texture sampler");
}
//! note we use immutable separate samplers and they are part of the descriptor set layout
std::array<smart_refctd_ptr<IGPUSampler>, (uint32_t)DefaultSamplerIx::COUNT> immutableSamplers;
immutableSamplers[(uint32_t)DefaultSamplerIx::FONT_ATLAS] = smart_refctd_ptr(fontAtlasUISampler);
immutableSamplers[(uint32_t)DefaultSamplerIx::USER] = smart_refctd_ptr(userTexturesSampler);
auto textureBinding = IGPUDescriptorSetLayout::SBinding
{
.binding = texturesInfo.bindingIx,
.type = IDescriptor::E_TYPE::ET_SAMPLED_IMAGE,
.createFlags = SResourceParameters::TexturesRequiredCreateFlags,
.stageFlags = SResourceParameters::RequiredShaderStageFlags,
.count = texturesCount
};
auto samplersBinding = IGPUDescriptorSetLayout::SBinding
{
.binding = samplersInfo.bindingIx,
.type = IDescriptor::E_TYPE::ET_SAMPLER,
.createFlags = SResourceParameters::SamplersRequiredCreateFlags,
.stageFlags = SResourceParameters::RequiredShaderStageFlags,
.count = immutableSamplers.size(),
.immutableSamplers = immutableSamplers.data()
};
auto layouts = std::to_array<smart_refctd_ptr<IGPUDescriptorSetLayout>>({ nullptr, nullptr, nullptr, nullptr });
if (texturesInfo.setIx == samplersInfo.setIx)
layouts[texturesInfo.setIx] = device->createDescriptorSetLayout({ {textureBinding, samplersBinding} });
else
{
layouts[texturesInfo.setIx] = device->createDescriptorSetLayout({ {textureBinding} });
layouts[samplersInfo.setIx] = device->createDescriptorSetLayout({ {samplersBinding} });
}
if (!layouts[texturesInfo.setIx])
return nullptr;
if (!layouts[samplersInfo.setIx])
return nullptr;
return device->createPipelineLayout(PushConstantRanges, std::move(layouts[0u]), std::move(layouts[1u]), std::move(layouts[2u]), std::move(layouts[3u]));
}
// note we use archive entry explicitly for temporary compiler include search path & asset cwd to use keys directly
constexpr std::string_view NBL_ARCHIVE_ENTRY = _ARCHIVE_ENTRY_KEY_;
const smart_refctd_ptr<IFileArchive> UI::mount(smart_refctd_ptr<ILogger> logger, ISystem* system, const std::string_view archiveAlias)
{
assert(system);
if(!system)
return nullptr;
// extension should mount everything for you, regardless if content goes from virtual filesystem
// or disk directly - and you should never rely on application framework to expose extension data
#ifdef NBL_EMBED_BUILTIN_RESOURCES
auto archive = make_smart_refctd_ptr<builtin::CArchive>(smart_refctd_ptr(logger));
system->mount(smart_refctd_ptr(archive), archiveAlias.data());
#else
auto NBL_EXTENSION_MOUNT_DIRECTORY_ENTRY = (path(_ARCHIVE_ABSOLUTE_ENTRY_PATH_) / NBL_ARCHIVE_ENTRY).make_preferred();
auto archive = make_smart_refctd_ptr<nbl::system::CMountDirectoryArchive>(std::move(NBL_EXTENSION_MOUNT_DIRECTORY_ENTRY), smart_refctd_ptr(logger), system);
system->mount(smart_refctd_ptr(archive), archiveAlias.data());
#endif
return smart_refctd_ptr(archive);
}
core::smart_refctd_ptr<video::IGPUGraphicsPipeline> UI::createPipeline(SCreationParameters& creationParams)
{
auto pipelineLayout = smart_refctd_ptr<IGPUPipelineLayout>(creationParams.pipelineLayout);
if (!pipelineLayout)
{
creationParams.utilities->getLogger()->log("Could not create pipeline layout!", ILogger::ELL_ERROR);
return nullptr;
}
struct
{
smart_refctd_ptr<IShader> vertex, fragment;
} shaders;
if (creationParams.spirv.has_value())
{
// TODO: since prebuild is experminetal currently I don't validate anything
auto& spirv = creationParams.spirv.value();
shaders.vertex = spirv.vertex;
shaders.fragment = spirv.fragment;
}
else
{
//! proxy the system, we will touch it gently
auto system = smart_refctd_ptr<ISystem>(creationParams.assetManager->getSystem());
auto* set = creationParams.assetManager->getCompilerSet();
auto compiler = set->getShaderCompiler(IShader::E_CONTENT_TYPE::ECT_HLSL);
auto includeFinder = make_smart_refctd_ptr<IShaderCompiler::CIncludeFinder>(smart_refctd_ptr(system));
auto includeLoader = includeFinder->getDefaultFileSystemLoader();
includeFinder->addSearchPath(NBL_ARCHIVE_ENTRY.data(), includeLoader);
auto createShader = [&]<StringLiteral key, IShader::E_SHADER_STAGE stage>() -> smart_refctd_ptr<IShader>
{
IAssetLoader::SAssetLoadParams params = {};
params.logger = creationParams.utilities->getLogger();
params.workingDirectory = NBL_ARCHIVE_ENTRY.data();
auto bundle = creationParams.assetManager->getAsset(key.value, params);
const auto assets = bundle.getContents();
if (assets.empty())
{
creationParams.utilities->getLogger()->log("Could not load \"%s\" shader!", ILogger::ELL_ERROR, key.value);
return nullptr;
}
const auto shader = IAsset::castDown<IShader>(assets[0]);
CHLSLCompiler::SOptions options = {};
options.stage = stage;
options.preprocessorOptions.sourceIdentifier = key.value;
options.preprocessorOptions.logger = creationParams.utilities->getLogger();
options.preprocessorOptions.includeFinder = includeFinder.get();
auto compileToSPIRV = [&]() -> smart_refctd_ptr<IShader>
{
auto toOptions = []<uint32_t N>(const std::array<std::string_view, N>&in) // options must be alive till compileToSPIRV ends
{
const auto required = CHLSLCompiler::getRequiredArguments();
std::array<std::string, required.size() + N> options;
std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
for (uint32_t i = 0; i < required.size(); ++i)
options[i] = converter.to_bytes(required[i]); // meh
uint32_t offset = required.size();
for (const auto& opt : in)
options[offset++] = std::string(opt);
return options;
};
const std::string_view code(reinterpret_cast<const char*>(shader->getContent()->getPointer()), shader->getContent()->getSize());
if constexpr (stage == IShader::E_SHADER_STAGE::ESS_VERTEX)
{
const auto VERTEX_COMPILE_OPTIONS = toOptions(std::to_array<std::string_view>({ "-T", "vs_6_7", "-E", "VSMain", "-O3" }));
options.dxcOptions = VERTEX_COMPILE_OPTIONS;
return compiler->compileToSPIRV(code.data(), options); // we good here - no code patching
}
else if (stage == IShader::E_SHADER_STAGE::ESS_FRAGMENT)
{
const auto FRAGMENT_COMPILE_OPTIONS = toOptions(std::to_array<std::string_view>({ "-T", "ps_6_7", "-E", "PSMain", "-O3" }));
options.dxcOptions = FRAGMENT_COMPILE_OPTIONS;
std::stringstream stream;
// TODO: Use the `ConstevalBindingInfo`
stream << "// -> this code has been autogenerated with Nabla ImGUI extension\n"
<< "#define NBL_TEXTURES_BINDING_IX " << creationParams.resources.texturesInfo.bindingIx << "\n"
<< "#define NBL_SAMPLER_STATES_BINDING_IX " << creationParams.resources.samplersInfo.bindingIx << "\n"
<< "#define NBL_TEXTURES_SET_IX " << creationParams.resources.texturesInfo.setIx << "\n"
<< "#define NBL_SAMPLER_STATES_SET_IX " << creationParams.resources.samplersInfo.setIx << "\n"
<< "#define NBL_TEXTURES_COUNT " << creationParams.resources.texturesCount << "\n"
<< "#define NBL_SAMPLERS_COUNT " << creationParams.resources.samplersCount << "\n"
<< "// <-\n\n";
const auto newCode = stream.str() + std::string(code);
return compiler->compileToSPIRV(newCode.c_str(), options); // but here we do patch the code with additional define directives for which values are taken from the creation parameters
}
else
{
static_assert(stage != IShader::E_SHADER_STAGE::ESS_UNKNOWN, "Unknown shader stage!");
return nullptr;
}
};
auto spirv = compileToSPIRV();
if (!spirv)
{
creationParams.utilities->getLogger()->log("Could not compile \"%s\" shader!", ILogger::ELL_ERROR, key.value);
return nullptr;
}
auto gpu = creationParams.utilities->getLogicalDevice()->compileShader({.source = spirv.get(),});
if (!gpu)
creationParams.utilities->getLogger()->log("Could not create GPU shader for \"%s\"!", ILogger::ELL_ERROR, key.value);
return gpu;
};
if (!system->areBuiltinsMounted())
{
creationParams.utilities->getLogger()->log("Nabla builtins are not mounted!", ILogger::ELL_ERROR);
return nullptr;
}
//! but we should never assume user will mount our internal data since its the extension and not user's job to do it so we do to compile our extension sources
if(!system->isDirectory(path(NBL_ARCHIVE_ENTRY.data())))
mount(smart_refctd_ptr<ILogger>(creationParams.utilities->getLogger()), system.get(), NBL_ARCHIVE_ENTRY);
shaders.vertex = createShader.template operator() < NBL_CORE_UNIQUE_STRING_LITERAL_TYPE("vertex.hlsl"), IShader::E_SHADER_STAGE::ESS_VERTEX > ();
shaders.fragment = createShader.template operator() < NBL_CORE_UNIQUE_STRING_LITERAL_TYPE("fragment.hlsl"), IShader::E_SHADER_STAGE::ESS_FRAGMENT > ();
}
if (!shaders.vertex)
{
creationParams.utilities->getLogger()->log("Failed to create vertex shader!", ILogger::ELL_ERROR);
return nullptr;
}
if (!shaders.fragment)
{
creationParams.utilities->getLogger()->log("Failed to create fragment shader!", ILogger::ELL_ERROR);
return nullptr;
}
SVertexInputParams vertexInputParams{};
{
vertexInputParams.enabledBindingFlags = 0b1u;
vertexInputParams.enabledAttribFlags = 0b111u;
vertexInputParams.bindings[0].inputRate = SVertexInputBindingParams::EVIR_PER_VERTEX;
vertexInputParams.bindings[0].stride = sizeof(ImDrawVert);
auto& position = vertexInputParams.attributes[0];
position.format = EF_R32G32_SFLOAT;
position.relativeOffset = offsetof(ImDrawVert, pos);
position.binding = 0u;
auto& uv = vertexInputParams.attributes[1];
uv.format = EF_R32G32_SFLOAT;
uv.relativeOffset = offsetof(ImDrawVert, uv);
uv.binding = 0u;
auto& color = vertexInputParams.attributes[2];
color.format = EF_R8G8B8A8_UNORM;
color.relativeOffset = offsetof(ImDrawVert, col);
color.binding = 0u;
}
SBlendParams blendParams{};
{
blendParams.logicOp = ELO_NO_OP;
auto& param = blendParams.blendParams[0];
// color blending factors (for RGB)
param.srcColorFactor = EBF_SRC_ALPHA;
param.dstColorFactor = EBF_ONE_MINUS_SRC_ALPHA;
param.colorBlendOp = EBO_ADD;
// alpha blending factors (for A)
param.srcAlphaFactor = EBF_ONE;
param.dstAlphaFactor = EBF_ONE_MINUS_SRC_ALPHA;
param.alphaBlendOp = EBO_ADD;
// Write all components (R, G, B, A)
param.colorWriteMask = (1u << 0u) | (1u << 1u) | (1u << 2u) | (1u << 3u);
}
SRasterizationParams rasterizationParams{};
{
rasterizationParams.faceCullingMode = EFCM_NONE;
rasterizationParams.depthWriteEnable = false;
rasterizationParams.depthBoundsTestEnable = false;
rasterizationParams.depthCompareOp = ECO_ALWAYS;
rasterizationParams.viewportCount = creationParams.viewportCount;
}
SPrimitiveAssemblyParams primitiveAssemblyParams{};
{
primitiveAssemblyParams.primitiveType = EPT_TRIANGLE_LIST;
}
core::smart_refctd_ptr<video::IGPUGraphicsPipeline> pipeline;
{
IGPUGraphicsPipeline::SCreationParams params[1];
{
auto& param = params[0u];
param.vertexShader = { .shader = shaders.vertex.get(), .entryPoint = "VSMain" };
param.fragmentShader = { .shader = shaders.fragment.get(), .entryPoint = "PSMain" };
param.layout = pipelineLayout.get();
param.renderpass = creationParams.renderpass.get();
param.cached = { .vertexInput = vertexInputParams, .primitiveAssembly = primitiveAssemblyParams, .rasterization = rasterizationParams, .blend = blendParams, .subpassIx = creationParams.subpassIx };
};
if (!creationParams.utilities->getLogicalDevice()->createGraphicsPipelines(creationParams.pipelineCache.get(), params, &pipeline))
{
creationParams.utilities->getLogger()->log("Could not create pipeline!", ILogger::ELL_ERROR);
return nullptr;
}
}
return pipeline;
}
smart_refctd_ptr<IGPUImageView> UI::createFontAtlasTexture(const SCreationParameters& creationParams, void* const imFontAtlas)
{
video::IQueue* queue = creationParams.transfer;
system::logger_opt_ptr logger = creationParams.utilities->getLogger();
auto* device = creationParams.utilities->getLogicalDevice();
auto* const fontAtlas = reinterpret_cast<ImFontAtlas*>(imFontAtlas);
// intialize command buffers
constexpr auto TransfersInFlight = 2;
std::array<smart_refctd_ptr<nbl::video::IGPUCommandBuffer>,TransfersInFlight> commandBuffers;
{
using pool_flags_t = IGPUCommandPool::CREATE_FLAGS;
auto pool = device->createCommandPool(queue->getFamilyIndex(), pool_flags_t::RESET_COMMAND_BUFFER_BIT | pool_flags_t::TRANSIENT_BIT);
if (!pool)
{
logger.log("Could not create command pool!", ILogger::ELL_ERROR);
return nullptr;
}
if (!pool->createCommandBuffers(IGPUCommandPool::BUFFER_LEVEL::PRIMARY, { commandBuffers.data(),TransfersInFlight }, core::smart_refctd_ptr<system::ILogger>(logger.get())))
{
logger.log("Could not create transistent command buffers!", ILogger::ELL_ERROR);
return nullptr;
}
}
constexpr auto NBL_FORMAT_FONT = EF_R8G8B8A8_UNORM;
// CCustomAllocatorCPUBuffer is kinda crap and doesn't support stateful allocators
uint8_t* pixels = nullptr;
auto freeMemory = core::makeRAIIExiter([&fontAtlas]()->void
{
fontAtlas->ClearTexData(); // calls free on pixel blocks
}
);
// make buffer with image contents
core::smart_refctd_ptr<ICPUImage> cpuImage;
{
int32_t width, height;
fontAtlas->GetTexDataAsRGBA32(&pixels, &width, &height);
if (!pixels)
return nullptr;
if (width<=0 || height<=0)
return nullptr;
const asset::VkExtent3D extent = {static_cast<uint32_t>(width),static_cast<uint32_t>(height),1u};
// create image
using usage_flags_t = ICPUImage::E_USAGE_FLAGS;
cpuImage = asset::ICPUImage::create({
.type = IImage::ET_2D,
.samples = IImage::ESCF_1_BIT,
.format = NBL_FORMAT_FONT,
.extent = extent,
.mipLevels = 1u,
.arrayLayers = 1u,
.flags = IImage::E_CREATE_FLAGS::ECF_NONE,
.usage = usage_flags_t::EUF_SAMPLED_BIT // transfer should get patched in by having regions
});
if (!cpuImage)
{
logger.log("Could not create font ICPUImage!", ILogger::ELL_ERROR);
return nullptr;
}
// set its contents
{
const size_t image_size = getTexelOrBlockBytesize(NBL_FORMAT_FONT)*width*height;
auto buffer = ICPUBuffer::create({ { image_size }, pixels, core::getNullMemoryResource(), alignof(uint32_t) }, adopt_memory);
auto regions = make_refctd_dynamic_array<smart_refctd_dynamic_array<ICPUImage::SBufferCopy>>(1ull);
{
auto region = regions->begin();
region->bufferOffset = 0ull;
region->bufferRowLength = width;
region->bufferImageHeight = 0u;
region->imageSubresource = {
.aspectMask = IImage::EAF_COLOR_BIT,
.mipLevel = 0u,
.baseArrayLayer = 0u,
.layerCount = 1u
};
region->imageOffset = { 0u, 0u, 0u };
region->imageExtent = extent;
}
if (!cpuImage->setBufferAndRegions(std::move(buffer),std::move(regions)))
{
logger.log("Could not set font ICPUImage contents!",ILogger::ELL_ERROR);
return nullptr;
}
cpuImage->setContentHash(cpuImage->computeContentHash());
}
// note its by default but you can still change it at runtime, both the texture & sampler id
SImResourceInfo defaultInfo;
defaultInfo.textureID = FontAtlasTexId;
defaultInfo.samplerIx = FontAtlasSamplerId;
fontAtlas->SetTexID(defaultInfo);
}
// convert the CPU Image into a GPU image
core::smart_refctd_ptr<IGPUImage> gpuImage;
core::smart_refctd_ptr<ISemaphore> imgFillSemaphore = device->createSemaphore(0);
{
std::array<IQueue::SSubmitInfo::SCommandBufferInfo,TransfersInFlight> commandBufferInfos;
for (uint32_t i=0u; i<TransfersInFlight; ++i)
{
commandBuffers[i]->setObjectDebugName(("ImGUI Font Upload Command Buffer #"+std::to_string(i)).c_str());
commandBufferInfos[i].cmdbuf = commandBuffers[i].get();
}
// as per the `SIntendedSubmitInfo` one commandbuffer must be begun
if (!commandBuffers[0]->begin(IGPUCommandBuffer::USAGE::ONE_TIME_SUBMIT_BIT))
{
logger.log("Could not begin command buffer \"%s\"",ILogger::ELL_ERROR,commandBuffers[0]->getObjectDebugName());
return nullptr;
}
imgFillSemaphore->setObjectDebugName("ImGUI Font Image Fill Semaphore");
auto converter = CAssetConverter::create({.device=device});
{
// We don't want to generate mip-maps for these images (YET), to ensure that we must override the default callbacks.
struct SInputs final : CAssetConverter::SInputs
{
inline uint8_t getMipLevelCount(const size_t groupCopyID, const ICPUImage* image, const CAssetConverter::patch_t<asset::ICPUImage>& patch) const override
{
return image->getCreationParameters().mipLevels;
}
inline uint16_t needToRecomputeMips(const size_t groupCopyID, const ICPUImage* image, const CAssetConverter::patch_t<asset::ICPUImage>& patch) const override
{
return 0b0u;
}
} inputs = {};
std::get<CAssetConverter::SInputs::asset_span_t<ICPUImage>>(inputs.assets) = { &cpuImage.get(),1 };
inputs.logger = logger;
auto reservation = converter->reserve(inputs);
gpuImage = reservation.getGPUObjects<ICPUImage>().front().value;
// now convert
SIntendedSubmitInfo transfer = {};
{
transfer.queue = queue;
transfer.waitSemaphores = {};
transfer.scratchCommandBuffers = commandBufferInfos;
transfer.scratchSemaphore =
{
.semaphore = imgFillSemaphore.get(),
.value = 0u,
.stageMask = PIPELINE_STAGE_FLAGS::ALL_TRANSFER_BITS
};
}
// TODO: FIXME ImGUI needs to know what Queue will have ownership of the image AFTER its uploaded (need to know the family of the graphics queue)
// right now, the transfer queue will stay the owner after upload
CAssetConverter::SConvertParams params = {};
params.transfer = &transfer;
params.utilities = creationParams.utilities.get();
auto result = reservation.convert(params);
// block immediately
if (result.copy()!=IQueue::RESULT::SUCCESS)
{
logger.log("Failed to record or submit conversion of ImGUI Font Image");
return nullptr;
}
}
}
// create the view
IGPUImageView::SCreationParams params;
params.format = gpuImage->getCreationParameters().format;
params.viewType = IImageView<IGPUImage>::ET_2D;
params.image = std::move(gpuImage);
return device->createImageView(std::move(params));
}
void UI::handleMouseEvents(const SUpdateParameters& params) const
{
auto& io = ImGui::GetIO();
io.AddMousePosEvent(params.mousePosition.x, params.mousePosition.y);
for (const auto& e : params.mouseEvents)
{
switch (e.type)
{
case SMouseEvent::EET_CLICK:
{
ImGuiMouseButton_ button = ImGuiMouseButton_COUNT;
if (e.clickEvent.mouseButton == EMB_LEFT_BUTTON)
button = ImGuiMouseButton_Left;
else if (e.clickEvent.mouseButton == EMB_RIGHT_BUTTON)
button = ImGuiMouseButton_Right;
else if (e.clickEvent.mouseButton == EMB_MIDDLE_BUTTON)
button = ImGuiMouseButton_Middle;
if (button == ImGuiMouseButton_COUNT)
continue;
if (e.clickEvent.action == SMouseEvent::SClickEvent::EA_PRESSED)
io.AddMouseButtonEvent(button, true);
else if (e.clickEvent.action == SMouseEvent::SClickEvent::EA_RELEASED)
io.AddMouseButtonEvent(button, false);
} break;
case SMouseEvent::EET_SCROLL:
{
_NBL_STATIC_INLINE_CONSTEXPR auto scalar = 0.02f;
const auto wheel = float32_t2(e.scrollEvent.horizontalScroll, e.scrollEvent.verticalScroll) * scalar;
io.AddMouseWheelEvent(wheel.x, wheel.y);
} break;
case SMouseEvent::EET_MOVEMENT:
default:
break;
}
}
}
struct NBL_TO_IMGUI_KEY_BIND
{
ImGuiKey target;
char physicalSmall;
char physicalBig;
};
// maps Nabla keys to IMGUIs
constexpr std::array<NBL_TO_IMGUI_KEY_BIND, EKC_COUNT> createKeyMap()
{
std::array<NBL_TO_IMGUI_KEY_BIND, EKC_COUNT> map = { { NBL_TO_IMGUI_KEY_BIND{ImGuiKey_None, '0', '0'} } };
#define NBL_REGISTER_KEY(__NBL_KEY__, __IMGUI_KEY__) \
map[__NBL_KEY__] = NBL_TO_IMGUI_KEY_BIND{__IMGUI_KEY__, keyCodeToChar(__NBL_KEY__, false), keyCodeToChar(__NBL_KEY__, true)};
NBL_REGISTER_KEY(EKC_BACKSPACE, ImGuiKey_Backspace);
NBL_REGISTER_KEY(EKC_TAB, ImGuiKey_Tab);
NBL_REGISTER_KEY(EKC_ENTER, ImGuiKey_Enter);
NBL_REGISTER_KEY(EKC_LEFT_SHIFT, ImGuiKey_LeftShift);
NBL_REGISTER_KEY(EKC_RIGHT_SHIFT, ImGuiKey_RightShift);
NBL_REGISTER_KEY(EKC_LEFT_CONTROL, ImGuiKey_LeftCtrl);
NBL_REGISTER_KEY(EKC_RIGHT_CONTROL, ImGuiKey_RightCtrl);
NBL_REGISTER_KEY(EKC_LEFT_ALT, ImGuiKey_LeftAlt);
NBL_REGISTER_KEY(EKC_RIGHT_ALT, ImGuiKey_RightAlt);
NBL_REGISTER_KEY(EKC_PAUSE, ImGuiKey_Pause);
NBL_REGISTER_KEY(EKC_CAPS_LOCK, ImGuiKey_CapsLock);
NBL_REGISTER_KEY(EKC_ESCAPE, ImGuiKey_Escape);
NBL_REGISTER_KEY(EKC_SPACE, ImGuiKey_Space);
NBL_REGISTER_KEY(EKC_PAGE_UP, ImGuiKey_PageUp);
NBL_REGISTER_KEY(EKC_PAGE_DOWN, ImGuiKey_PageDown);
NBL_REGISTER_KEY(EKC_END, ImGuiKey_End);
NBL_REGISTER_KEY(EKC_HOME, ImGuiKey_Home);
NBL_REGISTER_KEY(EKC_LEFT_ARROW, ImGuiKey_LeftArrow);
NBL_REGISTER_KEY(EKC_RIGHT_ARROW, ImGuiKey_RightArrow);
NBL_REGISTER_KEY(EKC_DOWN_ARROW, ImGuiKey_DownArrow);
NBL_REGISTER_KEY(EKC_UP_ARROW, ImGuiKey_UpArrow);
NBL_REGISTER_KEY(EKC_PRINT_SCREEN, ImGuiKey_PrintScreen);
NBL_REGISTER_KEY(EKC_INSERT, ImGuiKey_Insert);
NBL_REGISTER_KEY(EKC_DELETE, ImGuiKey_Delete);
NBL_REGISTER_KEY(EKC_APPS, ImGuiKey_Menu);
NBL_REGISTER_KEY(EKC_COMMA, ImGuiKey_Comma);
NBL_REGISTER_KEY(EKC_PERIOD, ImGuiKey_Period);
NBL_REGISTER_KEY(EKC_SEMICOLON, ImGuiKey_Semicolon);
NBL_REGISTER_KEY(EKC_OPEN_BRACKET, ImGuiKey_LeftBracket);
NBL_REGISTER_KEY(EKC_CLOSE_BRACKET, ImGuiKey_RightBracket);
NBL_REGISTER_KEY(EKC_BACKSLASH, ImGuiKey_Backslash);
NBL_REGISTER_KEY(EKC_APOSTROPHE, ImGuiKey_Apostrophe);
NBL_REGISTER_KEY(EKC_ADD, ImGuiKey_KeypadAdd);
NBL_REGISTER_KEY(EKC_SUBTRACT, ImGuiKey_KeypadSubtract);
NBL_REGISTER_KEY(EKC_MULTIPLY, ImGuiKey_KeypadMultiply);
NBL_REGISTER_KEY(EKC_DIVIDE, ImGuiKey_KeypadDivide);
NBL_REGISTER_KEY(EKC_0, ImGuiKey_0);
NBL_REGISTER_KEY(EKC_1, ImGuiKey_1);
NBL_REGISTER_KEY(EKC_2, ImGuiKey_2);
NBL_REGISTER_KEY(EKC_3, ImGuiKey_3);
NBL_REGISTER_KEY(EKC_4, ImGuiKey_4);
NBL_REGISTER_KEY(EKC_5, ImGuiKey_5);
NBL_REGISTER_KEY(EKC_6, ImGuiKey_6);
NBL_REGISTER_KEY(EKC_7, ImGuiKey_7);
NBL_REGISTER_KEY(EKC_8, ImGuiKey_8);
NBL_REGISTER_KEY(EKC_9, ImGuiKey_9);
NBL_REGISTER_KEY(EKC_A, ImGuiKey_A);
NBL_REGISTER_KEY(EKC_B, ImGuiKey_B);
NBL_REGISTER_KEY(EKC_C, ImGuiKey_C);
NBL_REGISTER_KEY(EKC_D, ImGuiKey_D);
NBL_REGISTER_KEY(EKC_E, ImGuiKey_E);
NBL_REGISTER_KEY(EKC_F, ImGuiKey_F);
NBL_REGISTER_KEY(EKC_G, ImGuiKey_G);
NBL_REGISTER_KEY(EKC_H, ImGuiKey_H);
NBL_REGISTER_KEY(EKC_I, ImGuiKey_I);
NBL_REGISTER_KEY(EKC_J, ImGuiKey_J);
NBL_REGISTER_KEY(EKC_K, ImGuiKey_K);
NBL_REGISTER_KEY(EKC_L, ImGuiKey_L);
NBL_REGISTER_KEY(EKC_M, ImGuiKey_M);
NBL_REGISTER_KEY(EKC_N, ImGuiKey_N);
NBL_REGISTER_KEY(EKC_O, ImGuiKey_O);
NBL_REGISTER_KEY(EKC_P, ImGuiKey_P);
NBL_REGISTER_KEY(EKC_Q, ImGuiKey_Q);
NBL_REGISTER_KEY(EKC_R, ImGuiKey_R);
NBL_REGISTER_KEY(EKC_S, ImGuiKey_S);
NBL_REGISTER_KEY(EKC_T, ImGuiKey_T);
NBL_REGISTER_KEY(EKC_U, ImGuiKey_U);
NBL_REGISTER_KEY(EKC_V, ImGuiKey_V);
NBL_REGISTER_KEY(EKC_W, ImGuiKey_W);
NBL_REGISTER_KEY(EKC_X, ImGuiKey_X);
NBL_REGISTER_KEY(EKC_Y, ImGuiKey_Y);
NBL_REGISTER_KEY(EKC_Z, ImGuiKey_Z);
NBL_REGISTER_KEY(EKC_NUMPAD_0, ImGuiKey_Keypad0);
NBL_REGISTER_KEY(EKC_NUMPAD_1, ImGuiKey_Keypad1);
NBL_REGISTER_KEY(EKC_NUMPAD_2, ImGuiKey_Keypad2);
NBL_REGISTER_KEY(EKC_NUMPAD_3, ImGuiKey_Keypad3);
NBL_REGISTER_KEY(EKC_NUMPAD_4, ImGuiKey_Keypad4);
NBL_REGISTER_KEY(EKC_NUMPAD_5, ImGuiKey_Keypad5);
NBL_REGISTER_KEY(EKC_NUMPAD_6, ImGuiKey_Keypad6);
NBL_REGISTER_KEY(EKC_NUMPAD_7, ImGuiKey_Keypad7);
NBL_REGISTER_KEY(EKC_NUMPAD_8, ImGuiKey_Keypad8);
NBL_REGISTER_KEY(EKC_NUMPAD_9, ImGuiKey_Keypad9);
NBL_REGISTER_KEY(EKC_F1, ImGuiKey_F1);
NBL_REGISTER_KEY(EKC_F2, ImGuiKey_F2);
NBL_REGISTER_KEY(EKC_F3, ImGuiKey_F3);
NBL_REGISTER_KEY(EKC_F4, ImGuiKey_F4);
NBL_REGISTER_KEY(EKC_F5, ImGuiKey_F5);
NBL_REGISTER_KEY(EKC_F6, ImGuiKey_F6);
NBL_REGISTER_KEY(EKC_F7, ImGuiKey_F7);
NBL_REGISTER_KEY(EKC_F8, ImGuiKey_F8);
NBL_REGISTER_KEY(EKC_F9, ImGuiKey_F9);
NBL_REGISTER_KEY(EKC_F10, ImGuiKey_F10);
NBL_REGISTER_KEY(EKC_F11, ImGuiKey_F11);
NBL_REGISTER_KEY(EKC_F12, ImGuiKey_F12);
NBL_REGISTER_KEY(EKC_F13, ImGuiKey_F13);
NBL_REGISTER_KEY(EKC_F14, ImGuiKey_F14);
NBL_REGISTER_KEY(EKC_F15, ImGuiKey_F15);
NBL_REGISTER_KEY(EKC_F16, ImGuiKey_F16);
NBL_REGISTER_KEY(EKC_F17, ImGuiKey_F17);
NBL_REGISTER_KEY(EKC_F18, ImGuiKey_F18);
NBL_REGISTER_KEY(EKC_F19, ImGuiKey_F19);
NBL_REGISTER_KEY(EKC_F20, ImGuiKey_F20);
NBL_REGISTER_KEY(EKC_F21, ImGuiKey_F21);
NBL_REGISTER_KEY(EKC_F22, ImGuiKey_F22);
NBL_REGISTER_KEY(EKC_F23, ImGuiKey_F23);
NBL_REGISTER_KEY(EKC_F24, ImGuiKey_F24);
NBL_REGISTER_KEY(EKC_NUM_LOCK, ImGuiKey_NumLock);
NBL_REGISTER_KEY(EKC_SCROLL_LOCK, ImGuiKey_ScrollLock);
NBL_REGISTER_KEY(EKC_VOLUME_MUTE, ImGuiKey_None);
NBL_REGISTER_KEY(EKC_VOLUME_UP, ImGuiKey_None);
NBL_REGISTER_KEY(EKC_VOLUME_DOWN, ImGuiKey_None);
return map;
}
void UI::handleKeyEvents(const SUpdateParameters& params) const
{
auto& io = ImGui::GetIO();
_NBL_STATIC_INLINE_CONSTEXPR auto keyMap = createKeyMap();
const bool useBigLetters = [&]() // TODO: we can later improve it to check for CAPS, etc
{
for (const auto& e : params.keyboardEvents)
if (e.keyCode == EKC_LEFT_SHIFT && e.action == SKeyboardEvent::ECA_PRESSED)
return true;
return false;
}();
for (const auto& e : params.keyboardEvents)
{
const auto& bind = keyMap[e.keyCode];
const auto& iCharacter = useBigLetters ? bind.physicalBig : bind.physicalSmall;
if(bind.target == ImGuiKey_None)
m_cachedCreationParams.utilities->getLogger()->log(std::string("Requested physical Nabla key \"") + iCharacter + std::string("\" has yet no mapping to IMGUI key!"), ILogger::ELL_ERROR);
else
if (e.action == SKeyboardEvent::ECA_PRESSED)
{
io.AddKeyEvent(bind.target, true);
io.AddInputCharacter(iCharacter);
}
else if (e.action == SKeyboardEvent::ECA_RELEASED)
io.AddKeyEvent(bind.target, false);
}
}
bool UI::validateCreationParameters(SCreationParameters& creationParams)
{
system::logger_opt_ptr logger = creationParams.utilities->getLogger();
auto validateResourcesInfo = [&]() -> bool
{
auto* pipelineLayout = creationParams.pipelineLayout.get();
if (pipelineLayout) // provided? we will validate your pipeline layout to check if you declared required UI resources
{
auto validateResource = [&]<IDescriptor::E_TYPE descriptorType>(const IGPUDescriptorSetLayout* const descriptorSetLayout)
{
static_assert(descriptorType != IDescriptor::E_TYPE::ET_COMBINED_IMAGE_SAMPLER, "Explicitly not supported.");
constexpr std::string_view typeLiteral = descriptorType == IDescriptor::E_TYPE::ET_SAMPLED_IMAGE ? "ET_SAMPLED_IMAGE" : "ET_SAMPLER",
ixLiteral = descriptorType == IDescriptor::E_TYPE::ET_SAMPLED_IMAGE ? "texturesBindingIx" : "samplersBindingIx";
// we need to check if there is at least single "descriptorType" resource, if so we can validate the resource further
auto anyBindingCount = [logger, &creationParams = creationParams, &log = std::as_const(typeLiteral)](const IDescriptorSetLayoutBase::CBindingRedirect* redirect, bool logError = true) -> bool
{
bool ok = redirect->getBindingCount();
if (!ok && logError)
{
logger.log("Provided descriptor set layout has no bindings for IDescriptor::E_TYPE::%s, you are required to provide at least single default ImGUI Font Atlas texture resource & corresponsing sampler resource!", ILogger::ELL_ERROR, log.data());
return false;
}
return ok;
};
if (!descriptorSetLayout)
{
logger.log("Provided descriptor set layout for IDescriptor::E_TYPE::%s is nullptr!", ILogger::ELL_ERROR, typeLiteral.data());
return false;
}
using redirect_t = IDescriptorSetLayoutBase::CBindingRedirect;
const redirect_t* redirect = &descriptorSetLayout->getDescriptorRedirect(descriptorType);
if constexpr (descriptorType == IDescriptor::E_TYPE::ET_SAMPLED_IMAGE)
{
if (!anyBindingCount(redirect))
return false;
}
else
{
if (!anyBindingCount(redirect, false))
{
redirect = &descriptorSetLayout->getImmutableSamplerRedirect(); // we must give it another try & request to look for immutable samplers
if (!anyBindingCount(redirect))
return false;
}
}
const redirect_t::binding_number_t requestedBinding(descriptorType == IDescriptor::E_TYPE::ET_SAMPLED_IMAGE ? creationParams.resources.texturesInfo.bindingIx : creationParams.resources.samplersInfo.bindingIx);
const auto storageIndex = redirect->findBindingStorageIndex(requestedBinding);
if (!storageIndex)
{
logger.log("No IDescriptor::E_TYPE::%s binding exists for requested `creationParams.resources.%s=%d` in the Provided descriptor set layout!", ILogger::ELL_ERROR, typeLiteral.data(), ixLiteral.data(), requestedBinding.data);
return false;
}
const auto creation = redirect->getCreateFlags(storageIndex);
if (!creation.hasFlags(descriptorType == IDescriptor::E_TYPE::ET_SAMPLED_IMAGE ? creationParams.resources.TexturesRequiredCreateFlags : creationParams.resources.SamplersRequiredCreateFlags))
{
logger.log("Provided descriptor set layout has IDescriptor::E_TYPE::%s binding for requested `creationParams.resources.%s` index but doesn't meet create flags requirements!", ILogger::ELL_ERROR, typeLiteral.data(), ixLiteral.data());
return false;
}
const auto stage = redirect->getStageFlags(storageIndex);
if (!stage.hasFlags(creationParams.resources.RequiredShaderStageFlags))
{
logger.log("Provided descriptor set layout has IDescriptor::E_TYPE::%s binding for requested `creationParams.resources.%s` index but doesn't meet stage flags requirements!", ILogger::ELL_ERROR, typeLiteral.data(), ixLiteral.data());
return false;
}
const auto count = redirect->getCount(storageIndex);
if (!count)
{
logger.log("Provided descriptor set layout has IDescriptor::E_TYPE::%s binding for requested `creationParams.resources.%s` index but the binding resource count == 0u!", ILogger::ELL_ERROR, typeLiteral.data(), ixLiteral.data());
return false;
}
if constexpr (descriptorType == IDescriptor::E_TYPE::ET_SAMPLED_IMAGE)
creationParams.resources.texturesCount = count;
else
creationParams.resources.samplersCount = count;
return true;
};
const auto& layouts = pipelineLayout->getDescriptorSetLayouts();
const bool ok = validateResource.template operator() < IDescriptor::E_TYPE::ET_SAMPLED_IMAGE > (layouts[creationParams.resources.texturesInfo.setIx]) && validateResource.template operator() < IDescriptor::E_TYPE::ET_SAMPLER > (layouts[creationParams.resources.samplersInfo.setIx]);
if (!ok)
return false;
}
return true;
};
const auto validation = std::to_array
({
std::make_pair(bool(creationParams.assetManager), "Invalid `creationParams.assetManager` is nullptr!"),
std::make_pair(bool(creationParams.assetManager->getSystem()), "Invalid `creationParams.assetManager->getSystem()` is nullptr!"),
std::make_pair(bool(creationParams.utilities), "Invalid `creationParams.utilities` is nullptr!"),
std::make_pair(bool(creationParams.transfer), "Invalid `creationParams.transfer` is nullptr!"),
std::make_pair(bool(creationParams.renderpass), "Invalid `creationParams.renderpass` is nullptr!"),
(creationParams.assetManager && creationParams.utilities && creationParams.transfer && creationParams.renderpass) ? std::make_pair(bool(creationParams.utilities->getLogicalDevice()->getPhysicalDevice()->getQueueFamilyProperties()[creationParams.transfer->getFamilyIndex()].queueFlags.hasFlags(IQueue::FAMILY_FLAGS::TRANSFER_BIT)), "Invalid `creationParams.transfer` is not capable of transfer operations!") : std::make_pair(false, "Pass valid required UI::S_CREATION_PARAMETERS!"),
std::make_pair(bool(creationParams.resources.texturesInfo.setIx <= 3u), "Invalid `creationParams.resources.textures` is outside { 0u, 1u, 2u, 3u } set!"),
std::make_pair(bool(creationParams.resources.samplersInfo.setIx <= 3u), "Invalid `creationParams.resources.samplers` is outside { 0u, 1u, 2u, 3u } set!"),
std::make_pair(bool(creationParams.resources.texturesInfo.bindingIx != creationParams.resources.samplersInfo.bindingIx), "Invalid `creationParams.resources.textures.bindingIx` is equal to `creationParams.resources.samplers.bindingIx`!"),
std::make_pair(bool(validateResourcesInfo()), "Invalid `creationParams.resources` content!")
});
for (const auto& [ok, error] : validation)
if (!ok)
{
logger.log(error, ILogger::ELL_ERROR);
return false;
}
return true;
}
core::smart_refctd_ptr<UI> UI::create(SCreationParameters&& creationParams, void* const imSharedFontAtlas)
{
auto* const logger = creationParams.utilities->getLogger();
if (!validateCreationParameters(creationParams))
{
logger->log("Failed creation parameters validation!", ILogger::ELL_ERROR);
return nullptr;
}
auto pipeline = createPipeline(creationParams);
if (!pipeline)
{
logger->log("Failed pipeline creation!", ILogger::ELL_ERROR);
return nullptr;
}
if (!createMDIBuffer(creationParams))
{
logger->log("Failed at mdi buffer creation!", ILogger::ELL_ERROR);
return nullptr;
}
// note that imgui context allows you to share atlas at creation time so we do too,
// hence you can have *custom* default font texture we will create a image view from
// + obvsly ownership of the atlas is yours then
auto* const inAtlas = reinterpret_cast<ImFontAtlas*>(imSharedFontAtlas);
const bool isFontAtlasShared = inAtlas;
auto* imFontAtlas = isFontAtlasShared ? inAtlas : IM_NEW(ImFontAtlas)();
auto fontView = createFontAtlasTexture(creationParams,imFontAtlas);
if (!fontView)
{
if (!isFontAtlasShared) // carefully here
IM_DELETE(imFontAtlas); // if that was supposed to be ours then on fail we kill it
logger->log("Failed default font image view creation!", ILogger::ELL_ERROR);
return nullptr;
}
// Dear ImGui context
IMGUI_CHECKVERSION();
// now create imgui context only if we created default image view to default font atlas image,
// we benefit from sharing font atlas with the context & allow to decidewho owns the atlas
// - the UI extension instance or user (because it comes from outside)
ImGuiContext* context = ImGui::CreateContext(imFontAtlas);
if (!context)
{
logger->log("Failed to create ImGUI context!", ILogger::ELL_ERROR);
return nullptr;
}
// note that you can still change im font atlas at runtime but if the atlas belongs to us
// then we must track the pointer since we own it and must free it at destruction
void* const trackedAtlasPointer = !isFontAtlasShared ? imFontAtlas : nullptr;
return core::smart_refctd_ptr<UI>(new UI(std::move(creationParams), pipeline, fontView, trackedAtlasPointer, context), core::dont_grab);
}
UI::UI(SCreationParameters&& creationParams, core::smart_refctd_ptr<video::IGPUGraphicsPipeline> pipeline, core::smart_refctd_ptr<video::IGPUImageView> defaultFont, void* const imFontAtlas, void* const imContext)
: m_cachedCreationParams(std::move(creationParams)), m_pipeline(std::move(pipeline)), m_fontAtlasTexture(std::move(defaultFont)), m_imFontAtlasBackPointer(imFontAtlas), m_imContextBackPointer(imContext)
{
auto& io = ImGui::GetIO();
// using AddKeyEvent() - it's new way of handling ImGUI events our backends supports
io.BackendUsingLegacyKeyArrays = 0;
}
UI::~UI()
{
// I assume somebody has not killed ImGUI context & atlas but if so then we do nothing
auto* const context = reinterpret_cast<ImGuiContext*>(m_imContextBackPointer);
ImGuiContext* const previousContext = ImGui::GetCurrentContext();
if (context && previousContext != context)
ImGui::SetCurrentContext(context);
// we must call it to unlock atlas from potential "render" state before we kill it (obvsly if its ours!)
if (m_imFontAtlasBackPointer && context && context->WithinFrameScope)
ImGui::EndFrame();
// context belongs to the instance, we must free it
if (context)
ImGui::DestroyContext(context);
if (previousContext && previousContext != context)
ImGui::SetCurrentContext(previousContext);
// and if we own the atlas we must free it as well, if user passed its own at creation time then its "shared" - at this point m_imFontAtlasBackPointer is nullptr and we don't free anything
if (m_imFontAtlasBackPointer)
IM_DELETE(reinterpret_cast<ImFontAtlas*>(m_imFontAtlasBackPointer));
}
bool UI::createMDIBuffer(SCreationParameters& creationParams)
{
constexpr static uint32_t minStreamingBufferAllocationSize = 128u, maxStreamingBufferAllocationAlignment = 4096u, mdiBufferDefaultSize = /* 2MB */ 1024u * 1024u * 2u;
auto getRequiredAccessFlags = [&](const bitflag<IDeviceMemoryAllocation::E_MEMORY_PROPERTY_FLAGS>& properties)
{
bitflag<IDeviceMemoryAllocation::E_MAPPING_CPU_ACCESS_FLAGS> flags (IDeviceMemoryAllocation::EMCAF_NO_MAPPING_ACCESS);
if (properties.hasFlags(IDeviceMemoryAllocation::EMPF_HOST_READABLE_BIT))
flags |= IDeviceMemoryAllocation::EMCAF_READ;
if (properties.hasFlags(IDeviceMemoryAllocation::EMPF_HOST_WRITABLE_BIT))
flags |= IDeviceMemoryAllocation::EMCAF_WRITE;
return flags;
};
auto* device = creationParams.utilities->getLogicalDevice();
const auto* physDev = device->getPhysicalDevice();
const auto upStreamingBits = physDev->getUpStreamingMemoryTypeBits();
const auto hostVisibleBits = physDev->getHostVisibleMemoryTypeBits();
bool usedFallback = false;
if (!creationParams.streamingBuffer)
{
IGPUBuffer::SCreationParams mdiCreationParams = {};
mdiCreationParams.usage = SCachedCreationParams::RequiredUsageFlags;
mdiCreationParams.size = mdiBufferDefaultSize;
auto buffer = device->createBuffer(std::move(mdiCreationParams));