forked from ITotalJustice/sys-tune
-
Notifications
You must be signed in to change notification settings - Fork 1
/
tesla.hpp
3659 lines (3000 loc) · 138 KB
/
tesla.hpp
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) 2020 werwolv
*
* This file is part of libtesla.
*
* libtesla 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, either version 2 of the License, or
* (at your option) any later version.
*
* libtesla 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. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with libtesla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <switch.h>
#include <stdlib.h>
#include <strings.h>
#include <math.h>
#include <algorithm>
#include <cstring>
#include <cwctype>
#include <string>
#include <functional>
#include <type_traits>
#include <mutex>
#include <memory>
#include <chrono>
#include <list>
#include <stack>
#include <map>
#include <filesystem>
// Define this makro before including tesla.hpp in your main file. If you intend
// to use the tesla.hpp header in more than one source file, only define it once!
// #define TESLA_INIT_IMPL
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-function"
#ifdef TESLA_INIT_IMPL
#define STB_TRUETYPE_IMPLEMENTATION
#endif
#include "stb_truetype.h"
#pragma GCC diagnostic pop
#define ELEMENT_BOUNDS(elem) elem->getX(), elem->getY(), elem->getWidth(), elem->getHeight()
#define ASSERT_EXIT(x) if (R_FAILED(x)) std::exit(1)
#define ASSERT_FATAL(x) if (Result res = x; R_FAILED(res)) fatalThrow(res)
#define PACKED __attribute__((packed))
#define ALWAYS_INLINE inline __attribute__((always_inline))
/// Evaluates an expression that returns a result, and returns the result if it would fail.
#define TSL_R_TRY(resultExpr) \
({ \
const auto result = resultExpr; \
if (R_FAILED(result)) { \
return result; \
} \
})
using namespace std::literals::string_literals;
using namespace std::literals::chrono_literals;
namespace tsl {
// Constants
namespace cfg {
constexpr u32 ScreenWidth = 1920; ///< Width of the Screen
constexpr u32 ScreenHeight = 1080; ///< Height of the Screen
extern u16 LayerWidth; ///< Width of the Tesla layer
extern u16 LayerHeight; ///< Height of the Tesla layer
extern u16 LayerPosX; ///< X position of the Tesla layer
extern u16 LayerPosY; ///< Y position of the Tesla layer
extern u16 FramebufferWidth; ///< Width of the framebuffer
extern u16 FramebufferHeight; ///< Height of the framebuffer
extern u64 launchCombo; ///< Overlay activation key combo
}
/**
* @brief RGBA4444 Color structure
*/
struct Color {
union {
struct {
u16 r: 4, g: 4, b: 4, a: 4;
} PACKED;
u16 rgba;
};
constexpr inline Color(u16 raw): rgba(raw) {}
constexpr inline Color(u8 r, u8 g, u8 b, u8 a): r(r), g(g), b(b), a(a) {}
};
namespace style {
constexpr u32 ListItemDefaultHeight = 70; ///< Standard list item height
constexpr u32 TrackBarDefaultHeight = 90; ///< Standard track bar height
constexpr u8 ListItemHighlightSaturation = 6; ///< Maximum saturation of Listitem highlights
constexpr u8 ListItemHighlightLength = 22; ///< Maximum length of Listitem highlights
namespace color {
constexpr Color ColorFrameBackground = { 0x0, 0x0, 0x0, 0xD }; ///< Overlay frame background color
constexpr Color ColorTransparent = { 0x0, 0x0, 0x0, 0x0 }; ///< Transparent color
constexpr Color ColorHighlight = { 0x0, 0xF, 0xD, 0xF }; ///< Greenish highlight color
constexpr Color ColorFrame = { 0x7, 0x7, 0x7, 0xF }; ///< Outer boarder color
constexpr Color ColorHandle = { 0x5, 0x5, 0x5, 0xF }; ///< Track bar handle color
constexpr Color ColorText = { 0xF, 0xF, 0xF, 0xF }; ///< Standard text color
constexpr Color ColorDescription = { 0xA, 0xA, 0xA, 0xF }; ///< Description text color
constexpr Color ColorHeaderBar = { 0xC, 0xC, 0xC, 0xF }; ///< Category header rectangle color
constexpr Color ColorClickAnimation = { 0x0, 0x2, 0x2, 0xF }; ///< Element click animation color
}
}
// Declarations
/**
* @brief Direction in which focus moved before landing on
* the currently focused element
*/
enum class FocusDirection {
None, ///< Focus was placed on the element programatically without user input
Up, ///< Focus moved upwards
Down, ///< Focus moved downwards
Left, ///< Focus moved from left to rigth
Right ///< Focus moved from right to left
};
/**
* @brief Current input controll mode
*
*/
enum class InputMode {
Controller, ///< Input from controller
Touch, ///< Touch input
TouchScroll ///< Moving/scrolling touch input
};
class Overlay;
namespace elm { class Element; }
namespace impl {
/**
* @brief Overlay launch parameters
*/
enum class LaunchFlags : u8 {
None = 0, ///< Do nothing special at launch
CloseOnExit = BIT(0) ///< Close the overlay the last Gui gets poped from the stack
};
[[maybe_unused]] static constexpr LaunchFlags operator|(LaunchFlags lhs, LaunchFlags rhs) {
return static_cast<LaunchFlags>(u8(lhs) | u8(rhs));
}
/**
* @brief Combo key mapping
*/
struct KeyInfo {
u64 key;
const char* name;
const char* glyph;
};
/**
* @brief Combo key mappings
*
* Ordered as they should be displayed
*/
constexpr std::array<KeyInfo, 18> KEYS_INFO = {{
{ HidNpadButton_L, "L", "\uE0A4" }, { HidNpadButton_R, "R", "\uE0A5" },
{ HidNpadButton_ZL, "ZL", "\uE0A6" }, { HidNpadButton_ZR, "ZR", "\uE0A7" },
{ HidNpadButton_AnySL, "SL", "\uE0A8" }, { HidNpadButton_AnySR, "SR", "\uE0A9" },
{ HidNpadButton_Left, "DLEFT", "\uE07B" }, { HidNpadButton_Up, "DUP", "\uE079" }, { HidNpadButton_Right, "DRIGHT", "\uE07C" }, { HidNpadButton_Down, "DDOWN", "\uE07A" },
{ HidNpadButton_A, "A", "\uE0A0" }, { HidNpadButton_B, "B", "\uE0A1" }, { HidNpadButton_X, "X", "\uE0A2" }, { HidNpadButton_Y, "Y", "\uE0A3" },
{ HidNpadButton_StickL, "LS", "\uE08A" }, { HidNpadButton_StickR, "RS", "\uE08B" },
{ HidNpadButton_Minus, "MINUS", "\uE0B6" }, { HidNpadButton_Plus, "PLUS", "\uE0B5" }
}};
}
[[maybe_unused]] static void goBack();
[[maybe_unused]] static void setNextOverlay(const std::string& ovlPath, std::string args = "");
template<typename TOverlay, impl::LaunchFlags launchFlags = impl::LaunchFlags::CloseOnExit>
int loop(int argc, char** argv);
// Helpers
namespace hlp {
/**
* @brief Wrapper for service initialization
*
* @param f wrapped function
*/
template<typename F>
static inline void doWithSmSession(F f) {
smInitialize();
f();
smExit();
}
/**
* @brief Wrapper for sd card access using stdio
* @note Consider using raw fs calls instead as they are faster and need less space
*
* @param f wrapped function
*/
template<typename F>
static inline void doWithSDCardHandle(F f) {
fsdevMountSdmc();
f();
fsdevUnmountDevice("sdmc");
}
/**
* @brief Guard that will execute a passed function at the end of the current scope
*
* @param f wrapped function
*/
template<typename F>
class ScopeGuard {
ScopeGuard(const ScopeGuard&) = delete;
ScopeGuard& operator=(const ScopeGuard&) = delete;
private:
F f;
bool canceled = false;
public:
ALWAYS_INLINE ScopeGuard(F f) : f(std::move(f)) { }
ALWAYS_INLINE ~ScopeGuard() { if (!canceled) { f(); } }
void dismiss() { canceled = true; }
};
/**
* @brief libnx hid:sys shim that gives or takes away frocus to or from the process with the given aruid
*
* @param enable Give focus or take focus
* @param aruid Aruid of the process to focus/unfocus
* @return Result Result
*/
static Result hidsysEnableAppletToGetInput(bool enable, u64 aruid) {
const struct {
u8 permitInput;
u64 appletResourceUserId;
} in = { enable != 0, aruid };
return serviceDispatchIn(hidsysGetServiceSession(), 503, in);
}
static Result viAddToLayerStack(ViLayer *layer, ViLayerStack stack) {
const struct {
u32 stack;
u64 layerId;
} in = { stack, layer->layer_id };
return serviceDispatchIn(viGetSession_IManagerDisplayService(), 6000, in);
}
/**
* @brief Toggles focus between the Tesla overlay and the rest of the system
*
* @param enabled Focus Tesla?
*/
static void requestForeground(bool enabled) {
u64 applicationAruid = 0, appletAruid = 0;
for (u64 programId = 0x0100000000001000UL; programId < 0x0100000000001020UL; programId++) {
pmdmntGetProcessId(&appletAruid, programId);
if (appletAruid != 0)
hidsysEnableAppletToGetInput(!enabled, appletAruid);
}
pmdmntGetApplicationProcessId(&applicationAruid);
hidsysEnableAppletToGetInput(!enabled, applicationAruid);
hidsysEnableAppletToGetInput(true, 0);
}
/**
* @brief Splits a string at the given delimeters
*
* @param str String to split
* @param delim Delimeter
* @return Vector containing the split tokens
*/
static std::vector<std::string> split(const std::string& str, char delim = ' ') {
std::vector<std::string> out;
std::size_t current, previous = 0;
current = str.find(delim);
while (current != std::string::npos) {
out.push_back(str.substr(previous, current - previous));
previous = current + 1;
current = str.find(delim, previous);
}
out.push_back(str.substr(previous, current - previous));
return out;
}
namespace ini {
/**
* @brief Ini file type
*/
using IniData = std::map<std::string, std::map<std::string, std::string>>;
/**
* @brief Tesla config file
*/
static const char* CONFIG_FILE = "/config/tesla/config.ini";
/**
* @brief Parses a ini string
*
* @param str String to parse
* @return Parsed data
*/
static IniData parseIni(const std::string &str) {
IniData iniData;
auto lines = split(str, '\n');
std::string lastHeader = "";
for (auto& line : lines) {
line.erase(std::remove_if(line.begin(), line.end(), ::isspace), line.end());
if (line[0] == '[' && line[line.size() - 1] == ']') {
lastHeader = line.substr(1, line.size() - 2);
iniData.emplace(lastHeader, std::map<std::string, std::string>{});
}
else if (auto keyValuePair = split(line, '='); keyValuePair.size() == 2) {
iniData[lastHeader].emplace(keyValuePair[0], keyValuePair[1]);
}
}
return iniData;
}
/**
* @brief Unparses ini data into a string
*
* @param iniData Ini data
* @return Ini string
*/
static std::string unparseIni(IniData const &iniData) {
std::string string;
bool addSectionGap = false;
for (auto §ion : iniData) {
if (addSectionGap)
string += "\n";
string += "["s + section.first + "]\n"s;
for (auto &keyValue : section.second) {
string += keyValue.first + "="s + keyValue.second + "\n"s;
}
}
return string;
}
/**
* @brief Read Tesla settings file
*
* @return Settings data
*/
static IniData readOverlaySettings() {
/* Open Sd card filesystem. */
FsFileSystem fsSdmc;
if (R_FAILED(fsOpenSdCardFileSystem(&fsSdmc)))
return {};
hlp::ScopeGuard fsGuard([&] { fsFsClose(&fsSdmc); });
/* Open config file. */
FsFile fileConfig;
if (R_FAILED(fsFsOpenFile(&fsSdmc, CONFIG_FILE, FsOpenMode_Read, &fileConfig)))
return {};
hlp::ScopeGuard fileGuard([&] { fsFileClose(&fileConfig); });
/* Get config file size. */
s64 configFileSize;
if (R_FAILED(fsFileGetSize(&fileConfig, &configFileSize)))
return {};
/* Read and parse config file. */
std::string configFileData(configFileSize, '\0');
u64 readSize;
Result rc = fsFileRead(&fileConfig, 0, configFileData.data(), configFileSize, FsReadOption_None, &readSize);
if (R_FAILED(rc) || readSize != static_cast<u64>(configFileSize))
return {};
return parseIni(configFileData);
}
/**
* @brief Replace Tesla settings file with new data
*
* @param iniData new data
*/
static void writeOverlaySettings(IniData const &iniData) {
/* Open Sd card filesystem. */
FsFileSystem fsSdmc;
if (R_FAILED(fsOpenSdCardFileSystem(&fsSdmc)))
return;
hlp::ScopeGuard fsGuard([&] { fsFsClose(&fsSdmc); });
/* Open config file. */
FsFile fileConfig;
if (R_FAILED(fsFsOpenFile(&fsSdmc, CONFIG_FILE, FsOpenMode_Write, &fileConfig)))
return;
hlp::ScopeGuard fileGuard([&] { fsFileClose(&fileConfig); });
std::string iniString = unparseIni(iniData);
fsFileWrite(&fileConfig, 0, iniString.c_str(), iniString.length(), FsWriteOption_Flush);
}
/**
* @brief Merge and save changes into Tesla settings file
*
* @param changes setting values to add or update
*/
static void updateOverlaySettings(IniData const &changes) {
hlp::ini::IniData iniData = hlp::ini::readOverlaySettings();
for (auto §ion : changes) {
for (auto &keyValue : section.second) {
iniData[section.first][keyValue.first] = keyValue.second;
}
}
writeOverlaySettings(iniData);
}
}
/**
* @brief Decodes a key string into it's key code
*
* @param value Key string
* @return Key code
*/
static u64 stringToKeyCode(const std::string &value) {
for (auto &keyInfo : impl::KEYS_INFO) {
if (strcasecmp(value.c_str(), keyInfo.name) == 0)
return keyInfo.key;
}
return 0;
}
/**
* @brief Decodes a combo string into key codes
*
* @param value Combo string
* @return Key codes
*/
static u64 comboStringToKeys(const std::string &value) {
u64 keyCombo = 0x00;
for (std::string key : hlp::split(value, '+')) {
keyCombo |= hlp::stringToKeyCode(key);
}
return keyCombo;
}
/**
* @brief Encodes key codes into a combo string
*
* @param keys Key codes
* @return Combo string
*/
static std::string keysToComboString(u64 keys) {
std::string str;
for (auto &keyInfo : impl::KEYS_INFO) {
if (keys & keyInfo.key) {
if (!str.empty())
str.append("+");
str.append(keyInfo.name);
}
}
return str;
}
}
// Renderer
namespace gfx {
extern "C" u64 __nx_vi_layer_id;
struct ScissoringConfig {
s32 x, y, w, h;
};
/**
* @brief Manages the Tesla layer and draws raw data to the screen
*/
class Renderer final {
public:
Renderer& operator=(Renderer&) = delete;
friend class tsl::Overlay;
/**
* @brief Handles opacity of drawn colors for fadeout. Pass all colors through this function in order to apply opacity properly
*
* @param c Original color
* @return Color with applied opacity
*/
static Color a(const Color &c) {
return (c.rgba & 0x0FFF) | (static_cast<u8>(c.a * Renderer::s_opacity) << 12);
}
/**
* @brief Enables scissoring, discarding of any draw outside the given boundaries
*
* @param x x pos
* @param y y pos
* @param w Width
* @param h Height
*/
inline void enableScissoring(s32 x, s32 y, s32 w, s32 h) {
this->m_scissoringStack.emplace(x, y, w, h);
}
/**
* @brief Disables scissoring
*/
inline void disableScissoring() {
this->m_scissoringStack.pop();
}
// Drawing functions
/**
* @brief Draw a single pixel onto the screen
*
* @param x X pos
* @param y Y pos
* @param color Color
*/
inline void setPixel(s32 x, s32 y, Color color) {
if (x < 0 || y < 0 || x >= cfg::FramebufferWidth || y >= cfg::FramebufferHeight)
return;
u32 offset = this->getPixelOffset(x, y);
if (offset != UINT32_MAX)
static_cast<Color*>(this->getCurrentFramebuffer())[offset] = color;
}
/**
* @brief Blends two colors
*
* @param src Source color
* @param dst Destination color
* @param alpha Opacity
* @return Blended color
*/
inline u8 blendColor(u8 src, u8 dst, u8 alpha) {
u8 oneMinusAlpha = 0x0F - alpha;
return (dst * alpha + src * oneMinusAlpha) / double(0xF);
}
/**
* @brief Draws a single source blended pixel onto the screen
*
* @param x X pos
* @param y Y pos
* @param color Color
*/
inline void setPixelBlendSrc(s32 x, s32 y, Color color) {
if (x < 0 || y < 0 || x >= cfg::FramebufferWidth || y >= cfg::FramebufferHeight)
return;
u32 offset = this->getPixelOffset(x, y);
if (offset == UINT32_MAX)
return;
Color src((static_cast<u16*>(this->getCurrentFramebuffer()))[offset]);
Color dst(color);
Color end(0);
end.r = this->blendColor(src.r, dst.r, dst.a);
end.g = this->blendColor(src.g, dst.g, dst.a);
end.b = this->blendColor(src.b, dst.b, dst.a);
end.a = src.a;
this->setPixel(x, y, end);
}
/**
* @brief Draws a single destination blended pixel onto the screen
*
* @param x X pos
* @param y Y pos
* @param color Color
*/
inline void setPixelBlendDst(s32 x, s32 y, Color color) {
if (x < 0 || y < 0 || x >= cfg::FramebufferWidth || y >= cfg::FramebufferHeight)
return;
u32 offset = this->getPixelOffset(x, y);
if (offset == UINT32_MAX)
return;
Color src((static_cast<u16*>(this->getCurrentFramebuffer()))[offset]);
Color dst(color);
Color end(0);
end.r = this->blendColor(src.r, dst.r, dst.a);
end.g = this->blendColor(src.g, dst.g, dst.a);
end.b = this->blendColor(src.b, dst.b, dst.a);
end.a = std::min(dst.a + src.a, 0xF);
this->setPixel(x, y, end);
}
/**
* @brief Draws a rectangle of given sizes
*
* @param x X pos
* @param y Y pos
* @param w Width
* @param h Height
* @param color Color
*/
inline void drawRect(s32 x, s32 y, s32 w, s32 h, Color color) {
for (s32 x1 = x; x1 < (x + w); x1++)
for (s32 y1 = y; y1 < (y + h); y1++)
this->setPixelBlendDst(x1, y1, color);
}
void drawCircle(s32 centerX, s32 centerY, u16 radius, bool filled, Color color) {
s32 x = radius;
s32 y = 0;
s32 radiusError = 0;
s32 xChange = 1 - (radius << 1);
s32 yChange = 0;
while (x >= y) {
if(filled) {
for (s32 i = centerX - x; i <= centerX + x; i++) {
s32 y0 = centerY + y;
s32 y1 = centerY - y;
s32 x0 = i;
this->setPixelBlendDst(x0, y0, color);
this->setPixelBlendDst(x0, y1, color);
}
for (s32 i = centerX - y; i <= centerX + y; i++) {
s32 y0 = centerY + x;
s32 y1 = centerY - x;
s32 x0 = i;
this->setPixelBlendDst(x0, y0, color);
this->setPixelBlendDst(x0, y1, color);
}
y++;
radiusError += yChange;
yChange += 2;
if (((radiusError << 1) + xChange) > 0) {
x--;
radiusError += xChange;
xChange += 2;
}
} else {
this->setPixelBlendDst(centerX + x, centerY + y, color);
this->setPixelBlendDst(centerX + y, centerY + x, color);
this->setPixelBlendDst(centerX - y, centerY + x, color);
this->setPixelBlendDst(centerX - x, centerY + y, color);
this->setPixelBlendDst(centerX - x, centerY - y, color);
this->setPixelBlendDst(centerX - y, centerY - x, color);
this->setPixelBlendDst(centerX + y, centerY - x, color);
this->setPixelBlendDst(centerX + x, centerY - y, color);
if(radiusError <= 0) {
y++;
radiusError += 2 * y + 1;
} else {
x--;
radiusError -= 2 * x + 1;
}
}
}
}
/**
* @brief Draws a RGBA8888 bitmap from memory
*
* @param x X start position
* @param y Y start position
* @param w Bitmap width
* @param h Bitmap height
* @param bmp Pointer to bitmap data
*/
void drawBitmap(s32 x, s32 y, s32 w, s32 h, const u8 *bmp) {
for (s32 y1 = 0; y1 < h; y1++) {
for (s32 x1 = 0; x1 < w; x1++) {
const Color color = { static_cast<u8>(bmp[0] >> 4), static_cast<u8>(bmp[1] >> 4), static_cast<u8>(bmp[2] >> 4), static_cast<u8>(bmp[3] >> 4) };
setPixelBlendSrc(x + x1, y + y1, a(color));
bmp += 4;
}
}
}
/**
* @brief Fills the entire layer with a given color
*
* @param color Color
*/
inline void fillScreen(Color color) {
std::fill_n(static_cast<Color*>(this->getCurrentFramebuffer()), this->getFramebufferSize() / sizeof(Color), color);
}
/**
* @brief Clears the layer (With transparency)
*
*/
inline void clearScreen() {
this->fillScreen({ 0x00, 0x00, 0x00, 0x00 });
}
/**
* @brief Draws a string
*
* @param string String to draw
* @param monospace Draw string in monospace font
* @param x X pos
* @param y Y pos
* @param fontSize Height of the text drawn in pixels
* @param color Text color. Use transparent color to skip drawing and only get the string's dimensions
* @return Dimensions of drawn string
*/
std::pair<u32, u32> drawString(const char* string, bool monospace, s32 x, s32 y, double fontSize, Color color, ssize_t maxWidth = 0) {
s32 maxX = x;
s32 currX = x;
s32 currY = y;
struct Glyph {
stbtt_fontinfo *currFont;
double currFontSize;
int bounds[4];
int xAdvance;
u8 *glyphBmp;
int width, height;
};
static std::unordered_map<u64, Glyph> s_glyphCache;
do {
if (maxWidth > 0 && maxWidth < (currX - x))
break;
u32 currCharacter;
ssize_t codepointWidth = decode_utf8(&currCharacter, reinterpret_cast<const u8*>(string));
if (codepointWidth <= 0)
break;
string += codepointWidth;
if (currCharacter == '\n') {
maxX = std::max(currX, maxX);
currX = x;
currY += fontSize;
continue;
}
u64 key = (static_cast<u64>(currCharacter) << 32) | static_cast<u64>(monospace) << 31 | static_cast<u64>(std::bit_cast<u64>(fontSize));
Glyph *glyph = nullptr;
auto it = s_glyphCache.find(key);
if (it == s_glyphCache.end()) {
/* Cache glyph */
glyph = &s_glyphCache.emplace(key, Glyph()).first->second;
if (stbtt_FindGlyphIndex(&this->m_extFont, currCharacter))
glyph->currFont = &this->m_extFont;
else if(this->m_hasLocalFont && stbtt_FindGlyphIndex(&this->m_stdFont, currCharacter)==0)
glyph->currFont = &this->m_localFont;
else
glyph->currFont = &this->m_stdFont;
glyph->currFontSize = stbtt_ScaleForPixelHeight(glyph->currFont, fontSize);
stbtt_GetCodepointBitmapBoxSubpixel(glyph->currFont, currCharacter, glyph->currFontSize, glyph->currFontSize,
0, 0, &glyph->bounds[0], &glyph->bounds[1], &glyph->bounds[2], &glyph->bounds[3]);
int yAdvance = 0;
stbtt_GetCodepointHMetrics(glyph->currFont, monospace ? 'W' : currCharacter, &glyph->xAdvance, &yAdvance);
glyph->glyphBmp = stbtt_GetCodepointBitmap(glyph->currFont, glyph->currFontSize, glyph->currFontSize, currCharacter, &glyph->width, &glyph->height, nullptr, nullptr);
} else {
/* Use cached glyph */
glyph = &it->second;
}
if (glyph->glyphBmp != nullptr && !std::iswspace(currCharacter) && fontSize > 0 && color.a != 0x0) {
auto x = currX + glyph->bounds[0];
auto y = currY + glyph->bounds[1];
for (s32 bmpY = 0; bmpY < glyph->height; bmpY++) {
for (s32 bmpX = 0; bmpX < glyph->width; bmpX++) {
auto bmpColor = glyph->glyphBmp[glyph->width * bmpY + bmpX] >> 4;
if (bmpColor == 0xF) {
this->setPixel(x + bmpX, y + bmpY, color);
} else if (bmpColor != 0x0) {
Color tmpColor = color;
tmpColor.a = bmpColor * (double(tmpColor.a) / 0xF);
this->setPixelBlendDst(x + bmpX, y + bmpY, tmpColor);
}
}
}
}
currX += static_cast<s32>(glyph->xAdvance * glyph->currFontSize);
} while (*string != '\0');
maxX = std::max(currX, maxX);
return { maxX - x, currY - y };
}
/**
* @brief Limit a strings length and end it with "…"
*
* @param string String to truncate
* @param maxLength Maximum length of string
*/
std::string limitStringLength(std::string string, bool monospace, double fontSize, s32 maxLength) {
if (string.size() < 2)
return string;
s32 currX = 0;
ssize_t strPos = 0;
ssize_t codepointWidth;
do {
u32 currCharacter;
codepointWidth = decode_utf8(&currCharacter, reinterpret_cast<const u8*>(&string[strPos]));
if (codepointWidth <= 0)
break;
strPos += codepointWidth;
stbtt_fontinfo *currFont = nullptr;
if (stbtt_FindGlyphIndex(&this->m_extFont, currCharacter))
currFont = &this->m_extFont;
else if(this->m_hasLocalFont && stbtt_FindGlyphIndex(&this->m_stdFont, currCharacter)==0)
currFont = &this->m_localFont;
else
currFont = &this->m_stdFont;
double currFontSize = stbtt_ScaleForPixelHeight(currFont, fontSize);
int xAdvance = 0, yAdvance = 0;
stbtt_GetCodepointHMetrics(currFont, monospace ? 'W' : currCharacter, &xAdvance, &yAdvance);
currX += static_cast<s32>(xAdvance * currFontSize);
} while (string[strPos] != '\0' && string[strPos] != '\n' && currX < maxLength);
string = string.substr(0, strPos - codepointWidth) + "…";
string.shrink_to_fit();
return string;
}
private:
Renderer() {}
/**
* @brief Gets the renderer instance
*
* @return Renderer
*/
static Renderer& get() {
static Renderer renderer;
return renderer;
}
/**
* @brief Sets the opacity of the layer
*
* @param opacity Opacity
*/
static void setOpacity(double opacity) {
opacity = std::clamp(opacity, (double)0.0, (double)1.0);
Renderer::s_opacity = opacity;
}
bool m_initialized = false;
ViDisplay m_display;
ViLayer m_layer;
Event m_vsyncEvent;
NWindow m_window;
Framebuffer m_framebuffer;
void *m_currentFramebuffer = nullptr;
std::stack<ScissoringConfig> m_scissoringStack;
stbtt_fontinfo m_stdFont, m_localFont, m_extFont;
bool m_hasLocalFont = false;
static inline double s_opacity = 1.0F;
/**
* @brief Get the current framebuffer address
*
* @return Framebuffer address
*/
inline void* getCurrentFramebuffer() {
return this->m_currentFramebuffer;
}
/**
* @brief Get the next framebuffer address
*
* @return Next framebuffer address
*/
inline void* getNextFramebuffer() {
return static_cast<u8*>(this->m_framebuffer.buf) + this->getNextFramebufferSlot() * this->getFramebufferSize();
}
/**
* @brief Get the framebuffer size
*
* @return Framebuffer size
*/
inline size_t getFramebufferSize() {
return this->m_framebuffer.fb_size;
}
/**
* @brief Get the number of framebuffers in use
*
* @return Number of framebuffers
*/
inline size_t getFramebufferCount() {
return this->m_framebuffer.num_fbs;
}
/**
* @brief Get the currently used framebuffer's slot
*
* @return Slot
*/
inline u8 getCurrentFramebufferSlot() {
return this->m_window.cur_slot;
}
/**
* @brief Get the next framebuffer's slot
*
* @return Next slot
*/
inline u8 getNextFramebufferSlot() {
return (this->getCurrentFramebufferSlot() + 1) % this->getFramebufferCount();
}
/**
* @brief Waits for the vsync event
*
*/
inline void waitForVSync() {
eventWait(&this->m_vsyncEvent, UINT64_MAX);
}
/**