67 Commits

Author SHA1 Message Date
afe30a5dbd Add Drawlist
- Add Pool iterator support
- Add Pool Expandability
- Add Pool::Push
- Add Lithium Maths API
- Remove InitPools
- update spirv-helper
2026-03-19 22:06:58 +01:00
e6cd8b7d24 Merge branch 'dev-0.7-rewrite' of ssh://dev.npid7.de:222/tobid7/palladium into dev-0.7-rewrite 2026-03-19 16:26:07 +01:00
66602a79e0 Replace spirv-helper stuff with a library that combines everything 2026-03-19 15:54:01 +01:00
a28b7318d2 Add the shaders 2026-03-19 09:22:46 +01:00
71563e8979 Add pdsg (palladium spirv-generator)
- remove glslang from pd-system
- use spirv blobs instead of glsl 460
- Use Legacy shaders for OpenGL2 backend
- add devnotes
2026-03-18 21:21:00 +01:00
7d89ab1c47 Add SpirvHelper (Shader cross compilation)
- Make OpenGL2 and OpenGL3 use the same base shaders (using SpirvHelper)
- Add Transpose func to Mat4
2026-03-18 15:17:48 +01:00
186fce803e Add missing sources 2026-03-18 11:37:44 +01:00
66412ca8e0 Full 3ds support and fix dx9 2026-03-18 11:34:36 +01:00
e04046720b Work at 3ds support and backend upgrades
- Track textures (not sure if this is done tbh)
- Add lithium formatters and move TextureID, TextureFormat and TextureFilter to lithium
- Only include gl-helper if any glDriver is included
- Add Li::Rect for UV stuff
- Add Li::Texture as Info holder (still thinking of making them to ptrs
- Add Check if textures are still loaded on exit
2026-03-18 09:31:47 +01:00
d4c59e5b61 Add backends
- Renamed GfxOpenGL to GfxOPenGL2
- Added GfxOpenGL3 backend for OpenGL 3.3+
- Added WIP DirectX9 backend
- Added structure for Citro3D
- Added linear Allocator
2026-03-17 16:47:19 +01:00
fe9194b907 More work to drivers
- Add gfx_test
- add texture loading to GfxOpenGL
- add full submit code
- add debug logging
- add construct and destroy functionality to Pool
- add command functionality
- add vertex and index pools to lithium (static and not threadsafe yet)
- Update GfxDriver Matrix with SetViewPort
- Add glfw (only dependency of gfx_test) maybe later required for input driver
2026-03-16 17:33:46 +01:00
4924d86bc0 # Work at gfx driver system
- Update pool to use template allocator directly instead of std::vector
- Add a GfxDriver config Template to be able to modify settings like allocators / Types for specific Drivers
- Add glad
2026-03-16 15:19:12 +01:00
41b612ec0a 0.7.0 rewrite dev
- remove everyting
- keep core
-rename bit_utils to bits
- add formatter for  color
- add float getters to color
- start with new drivers api
2026-03-16 06:37:51 +01:00
ff1b574276 [pd-ui7] add getters for ui7 menu pos and size 2026-03-13 20:55:40 +01:00
1b47ed843f [pd-drivers]: Ad more debug values
[pd-3ds]: Use new debug values
[pd-lithium]: Add functionality to DrawList::Optimize
[pd-ui7]: Add setters for Menu pos ans size
2026-03-12 20:18:27 +01:00
02d2200edd Fix Render discard issue [pd-3ds]
- Clip Rects do now not discard when they move out of screen (cause the maths ends in < 0 which is not working with u32)
- Fixing ui7 crash wehn im input was nullptr
2026-03-10 18:57:29 +01:00
97efca5173 Merge branch 'stable' of https://github.com/tobid7/palladium into stable 2026-03-09 20:47:53 +01:00
68cc809555 Fix Drawlist::Clear / Add HashID / FNV Type traits 2026-03-09 20:46:41 +01:00
ca490df915 Add U8Iterator and Pool base class 2026-03-05 20:24:47 +01:00
da0f7320c8 Add stuff for cmake find_package
- Add build* to gitignore
- Fix year in license file
- other changes are result of clang-format
2026-03-01 21:41:53 +01:00
8ee7006d2c Export OS correctly 2026-01-30 20:19:13 +01:00
683c226ce0 Fix MSVC dll building 2026-01-29 20:17:04 +01:00
1ec06a26cc Fix GL Scissor in Desktop Backend 2026-01-28 07:40:34 +01:00
21b45f5855 WIP: Add CLipRects to UI7 Layouts
- Added Scissor Support to Font Rendering
2026-01-28 07:11:56 +01:00
090656b30c Fix close sym input logic 2026-01-27 08:06:52 +01:00
e8072a064c WIP Backend System Redesign Step 1
- Created 1 Context for Backend Management and Sharing
- Made every class that used a static Backend require the Context or specific Backend
- Bring Back 3ds support
2026-01-26 20:46:27 +01:00
892f8ce0c4 Update License Header Text 2026-01-25 21:12:16 +01:00
c373b15bab remove drivers pd_p_api header 2026-01-25 21:00:50 +01:00
fb46f4d36a Let's just use 1 PD_API header 2026-01-25 20:57:14 +01:00
337c016824 Unfiy all sub projects back into 1 libpalladium 2026-01-25 20:44:52 +01:00
d2806b2061 Add Nee Backend Structure
Use TexAddress instead of Texture::Ref in Cmds
Add a .clang-format??
2026-01-25 00:04:40 +01:00
da79db223f Add MacOS support as well as OpenGL 3.3 support 2026-01-24 23:08:03 +01:00
b2c7c1fdbf UI7 Add Containers to Layout
- Hotfix in CommandPool
- Add UI7 ItemRowHeight (Universal Item Size/Height)
- Add Containers to Layout
- Add ColorEdit to Menu
- Switch Back to COlorEdit in UI7::StyleEditor
- Add DrawList Layer Sorting to UI7 (Not working as expected)
- STart Work at ColorEdit container
2026-01-24 11:58:41 +01:00
4a73e8c8da UI7 hotfix
- Fix Image has No Size
- Fix DragData PathRect Positioning
2026-01-24 09:27:21 +01:00
641fc27e55 Auto Menu Sizing 2026-01-23 16:11:09 +01:00
b8c25d6901 Add a Drag Slider to UI7 2026-01-23 15:45:25 +01:00
931e02aefb Move CmdPool code to a source file 2026-01-22 19:25:01 +01:00
0db4953125 Reimplement list sorting and Fix UI7 Layers 2026-01-22 16:34:46 +01:00
2b7d25cf06 Update
- Added DestroyTex to 3ds backend
- Added Size() -> ivec2 to PD::Image
- Added CmdPool Copy as well as DrawList Copy (Static rendering)
- Added == ooperator for Rect
- Added UI7 Frame Rounding
- Fix UI7 Image usage withour size or uv
- Added New way to use BeginMenu
2026-01-18 19:25:50 +01:00
0ef6d34435 Refactor the Command / DrawList System
Use Command Pool instead of always allocating.
This gives us e big performance diffrence on the 3ds
Fixed IDS of ui7 for now
2026-01-16 12:13:48 +01:00
eb5d5f9974 backend updates
pd-3ds:
Add support for RGB565 textures
pd-desktop:
Add support for A8 textures
Add glfw callback chain to not break other libs using the same callback
2026-01-05 14:37:57 +01:00
3575a6787d hotfix 2025-12-28 21:38:41 +01:00
7fc7a2ecb9 QoL Changes
fix timetrace last diff
2025-12-27 23:35:23 +01:00
03f65e069f Add TextMapSystem WIP 2025-12-24 18:17:58 +01:00
c618c616fe Fix UI7 Crash by safe deleting the elements 2025-12-24 15:05:05 +01:00
ac281dc7a9 Update
- Add data getter to DrawList
- Add NoOOS (Out Of screen Rendering) flag to text renderer (requires a textbox)
- UI7 Label Wrapping (optinal and beta)
2025-12-23 19:20:31 +01:00
0cb5de882f Fixes and function additions
- Fixed Text pos at NoCollapse flag
- Fix Button Input Api (HandleScrolling after layout Update)
- Add getter for IO and Current Menu
- Add AdObject func wrappers to Menu
2025-12-20 19:25:20 +01:00
b3d621a847 Add LayerOptimisation / QoL change 2025-12-19 21:08:32 +01:00
4ad00cd2be pd-3ds: Add sysfont loader
- add support for Alpha only textures in rendering
2025-12-19 21:07:57 +01:00
1e35dbd743 ReAdd text shorting 2025-12-18 21:51:48 +01:00
803fa5cdb5 Remove custom standard lib
Why?? cause it was russian roulette with pointer access stuff etc
2025-12-17 10:02:05 +01:00
66d3825481 bknd-3ds: implement libpicasso to load shader 2025-12-17 09:25:36 +01:00
6c38aa6f21 Adding and fixing stuff
- Fix HexChar2Int
- Remove some devisions in tween engine
- Add PathAdd function for x, y seperated instead of fvec2
- Readd text wrapping (rd7-palladium maybe)
2025-12-15 22:16:19 +01:00
f19c947fc3 Road to 0.6.0
- readd the c++ linear allocator for 3ds
- start switching from PD::Vec to std::vector
- Add Color::Hex as constexpr for compiletime color converts
- Add FNV Hasing functions
- Make UI7 ids be able to be generated at compile time
- Added a Throw Function (for whatever)
- Added HexCHar2Int (replaces the lookup table)
- Made u128 fully constexpr
2025-12-10 19:02:54 +01:00
91754558f7 Fix the floating color bug :) 2025-12-06 22:30:37 +01:00
8328181a2a Merge branch 'devel050' of https://dev.npid7.de/tobid7/palladium into devel050 2025-10-24 09:18:29 +02:00
be230bef6b lithium: Fix text Spacing 2025-10-22 20:58:02 +02:00
c2bff368d4 lithium: Fix text Spacing 2025-10-21 08:55:51 +02:00
0ecf559fbb # Small Update
- Start some work on scrolling
2025-10-18 17:00:35 +02:00
3823f08bab Update Font System
- Add support for splitting glyphs over multiple textures
- Fix some casts in wrong places (like casting a float to float?)
- Add a break if stb truetype fails
- Fix a typo in FontRenderer Shaddow part (used .x twice)
- Use L' ' for the wstring chars

- TODO: Fix the space of tabs / space chars (currently hardcoded)

- WARNING
  - Spaces are broken (idk why)
2025-08-28 21:06:19 +02:00
decae031ae Small Fix
- Make target compile definitions private (cause its only for them

this fixes errors when using in projects that have c source files
2025-08-23 20:02:33 +02:00
da87c0f7c2 # Hotfix
- 3ds backend
   -probably i forgot to apply the changes of moving Gfx backends to the PD namespace to the 3ds backend :/
2025-08-15 22:14:33 +02:00
310b44caf5 # Changes -> 0.5.1
- 3ds
  - Remove Gfx values that are present in Backend Tamplate
  - Move to default Palladium Namespace
  - Set the Input Flags
- Desktop
  - Move to PD Namespace
  - Comment out old keyboard stuff
  - HidDriver needs a rewrite but is functional enough
- Core
  - Add u128 class (only used in input driver so far
- Drivers (Core)
  - Move Gfx to PD namespace
  - Move Vertex/Index Pos and Projection Mtx to Gfx template
  - Add Keyboard support with u128 to Hid
  - Add a Update func if no hiddriver is specified (to prevent crashes when requestign inputs)
- Image
   - Add RGBA -> BGRA support (used in windows bitmaps iirc)
- Lithium
  - Add Vertex/Index counters to drawlist
  - Add a LoadTTF from Mem func and let the loadfile func use PD::IO::LoadFile2Mem (looks cleaner)
  - Add LoadDefaultFont (which loads one of the integrated fonts if the PD_LI_INCLUDE_FONTS flag was passed on palaldium build) !!! Note that there are no fonts integrated yet due to i dont know how to handle licensing...
- UI7
  - Add MouseLeft support to Input handler
  - Use xy coords of the Viewport to create Menus inside it
  - Get num of Vertices/Indices out of FinalDrawList
  - Add some Palladium Info to metrics Menu
  - Readd Compiler string
- pdfm
  - New tool that creates fonts.cpp/fonts.hpp
2025-08-14 20:37:55 +02:00
87910b57de # Changes
3ds Backend:
  - switch to shaderProgramUse
Desktop Backend
  - Add Pre Alpha Text Input and Keyboard Support
  - Move Shader Attrib Setup into a function and callit every time we need a set up vbo
  - Move to Mat4 api
Core:
  - Add fquat support
  - Add LoadFile2Str
  - Move Mat4 Lib from Project     n73 to Palladium
  - Add full supprot for vec cross types
  - Add Normalize, Distance and Dot to all
  - Add Cross to vec3
Drivers:
  - Add a SetViewPort func to GFX
  - Add Keyboard keys and Flasg to Hid
Image:
  - Add Vertical Flipping
  - Add Horizontal flipping
UI7:
  - Fix Critical Bug in IO Viewport handler
  - Fix library list (error on MinGW for some reason)
Lazyvec:
  - Split into multiple source files
  - Generate new functions (see core updates)
2025-07-23 23:21:34 +02:00
31a0c3656f # Changes
- Remove () from vec formatter
 -Add Merge function to DrawList to Move Data into the Current DrawList
- Fix stupid bug in Rect.hpp which caused some problems in line rendering
- Remove some unused UI7 Flags
- io: Allocate FinalDrawList and add GetViewPort func
- Readd TreeNodes to Menu
- Add ABout/Style and Metrics Menu to Context
- Add some Variables for cliprects in ui7 container.hpp
- Add InputHandler functionality to DynObj
- Fix Menu Layout Render Order
- Add Better Menu Sorting to Context
# ppam
- Use stringview instead of hardcoded const char*
# Todos
- Work on the Lithium 3D System
- Fix UI7 Menu Order to Pop new Menus into the front instead of the background
- Add Scrolling support to menu (or integrate it into layout maybe)
2025-07-01 21:43:35 +02:00
01fb149e71 Update glfw 2025-06-22 21:05:24 +02:00
57634cbf4b # Rewrite 5
- Move Libraries Source into pd directory and give them all their own CMakeLists.txt
- Partial rewrite core (color, autogenerated vec), lithium (now uses UNIQUE PTR for Commands), UI7
- Use MenuV2 as new standart in UI7
- Implementz ViewPort Pre alpha to UI7
- Add Line Drawing to DrawList (not Working)
- Implement a Complete new drievrs API (static Drivers)
- NO SUPPORT FOR SHARED LIBRARY BUILDS IN VERSION 5 YET
- Add Tools to Autogenerate Headers and Stuff
2025-06-22 21:05:09 +02:00
223 changed files with 32114 additions and 60064 deletions

334
.clang-format Normal file
View File

@@ -0,0 +1,334 @@
---
Language: Cpp
AccessModifierOffset: -1
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: true
AlignConsecutiveBitFields:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveDeclarations:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: true
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveMacros:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveShortCaseStatements:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCaseArrows: false
AlignCaseColons: false
AlignConsecutiveTableGenBreakingDAGArgColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenCondOperatorColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenDefinitionColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionDeclarations: false
AlignFunctionPointers: false
PadOperators: false
AlignEscapedNewlines: Left
AlignOperands: Align
AlignTrailingComments:
Kind: Always
OverEmptyLines: 0
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowBreakBeforeNoexceptSpecifier: Never
AllowShortBlocksOnASingleLine: Never
AllowShortCaseExpressionOnASingleLine: true
AllowShortCaseLabelsOnASingleLine: false
AllowShortCompoundRequirementOnASingleLine: true
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: WithoutElse
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: true
AllowShortNamespacesOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AttributeMacros:
- __capability
- absl_nonnull
- absl_nullable
- absl_nullability_unknown
BinPackArguments: true
BinPackLongBracedList: true
BinPackParameters: BinPack
BitFieldColonSpacing: Both
BracedInitializerIndentWidth: -1
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterExternBlock: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakAdjacentStringLiterals: true
BreakAfterAttributes: Leave
BreakAfterJavaFieldAnnotations: false
BreakAfterReturnType: None
BreakArrays: true
BreakBeforeBinaryOperators: None
BreakBeforeConceptDeclarations: Always
BreakBeforeBraces: Attach
BreakBeforeInlineASMColon: OnlyMultiline
BreakBeforeTemplateCloser: false
BreakBeforeTernaryOperators: true
BreakBinaryOperations: Never
BreakConstructorInitializers: BeforeColon
BreakFunctionDefinitionParameters: false
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
BreakTemplateDeclarations: Yes
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
EnumTrailingComma: Leave
ExperimentalAutoDetectBinPacking: false
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^<ext/.*\.h>'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^<.*\.h>'
Priority: 1
SortPriority: 0
CaseSensitive: false
- Regex: '^<.*'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
Priority: 3
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '([-_](test|unittest))?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseBlocks: false
IndentCaseLabels: true
IndentExportBlock: true
IndentExternBlock: AfterExternBlock
IndentGotoLabels: true
IndentPPDirectives: None
IndentRequiresClause: true
IndentWidth: 2
IndentWrappedFunctionNames: false
InsertBraces: false
InsertNewlineAtEOF: false
InsertTrailingCommas: None
IntegerLiteralSeparator:
Binary: 0
BinaryMinDigits: 0
Decimal: 0
DecimalMinDigits: 0
Hex: 0
HexMinDigits: 0
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLines:
AtEndOfFile: false
AtStartOfBlock: false
AtStartOfFile: true
KeepFormFeed: false
LambdaBodyIndentation: Signature
LineEnding: DeriveLF
MacroBlockBegin: ''
MacroBlockEnd: ''
MainIncludeChar: Quote
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
ObjCBinPackProtocolList: Never
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
OneLineFormatOffRegex: ''
PackConstructorInitializers: NextLine
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakBeforeMemberAccess: 150
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakScopeResolution: 500
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyIndentedWhitespace: 0
PenaltyReturnTypeOnItsOwnLine: 200
PointerAlignment: Left
PPIndentWidth: -1
QualifierAlignment: Leave
RawStringFormats:
- Language: Cpp
Delimiters:
- cc
- CC
- cpp
- Cpp
- CPP
- 'c++'
- 'C++'
CanonicalDelimiter: ''
BasedOnStyle: google
- Language: TextProto
Delimiters:
- pb
- PB
- proto
- PROTO
EnclosingFunctions:
- EqualsProto
- EquivToProto
- PARSE_PARTIAL_TEXT_PROTO
- PARSE_TEST_PROTO
- PARSE_TEXT_PROTO
- ParseTextOrDie
- ParseTextProtoOrDie
- ParseTestProto
- ParsePartialTestProto
CanonicalDelimiter: pb
BasedOnStyle: google
ReferenceAlignment: Pointer
ReflowComments: Always
RemoveBracesLLVM: false
RemoveEmptyLinesInUnwrappedLines: false
RemoveParentheses: Leave
RemoveSemicolon: false
RequiresClausePosition: OwnLine
RequiresExpressionIndentation: OuterScope
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SkipMacroDefinitionBody: false
SortIncludes:
Enabled: true
IgnoreCase: false
SortJavaStaticImport: Before
SortUsingDeclarations: LexicographicNumeric
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterOperatorKeyword: false
SpaceAfterTemplateKeyword: true
SpaceAroundPointerQualifiers: Default
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeJsonColon: false
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterForeachMacros: true
AfterFunctionDefinitionName: false
AfterFunctionDeclarationName: false
AfterIfMacros: true
AfterNot: false
AfterOverloadedOperator: false
AfterPlacementOperator: true
AfterRequiresInClause: false
AfterRequiresInExpression: false
BeforeNonEmptyParentheses: false
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: false
SpacesBeforeTrailingComments: 2
SpacesInAngles: Never
SpacesInContainerLiterals: true
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParens: Never
SpacesInParensOptions:
ExceptDoubleParentheses: false
InCStyleCasts: false
InConditionalStatements: false
InEmptyParentheses: false
Other: false
SpacesInSquareBrackets: false
Standard: Auto
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TableGenBreakInsideDAGArg: DontBreak
TabWidth: 8
UseTab: Never
VerilogBreakBetweenInstancePorts: true
WhitespaceSensitiveMacros:
- BOOST_PP_STRINGIZE
- CF_SWIFT_NAME
- NS_SWIFT_NAME
- PP_STRINGIZE
- STRINGIZE
WrapNamespaceBodyWithEmptyLines: Leave
...

5
.clangd Normal file
View File

@@ -0,0 +1,5 @@
CompileFlags:
Add: []
Completion:
HeaderInsertion: Never

1
.gitattributes vendored Normal file
View File

@@ -0,0 +1 @@
vendor/* linguist-vendored

4
.gitignore vendored Normal file → Executable file
View File

@@ -1 +1,3 @@
build/
build*/
.cache
.vscode

13
.gitmodules vendored
View File

@@ -1,3 +1,12 @@
[submodule "backends/desktop/glfw"]
path = backends/desktop/glfw
[submodule "vendor/stb"]
path = vendor/stb
url = https://github.com/nothings/stb.git
[submodule "vendor/glfw"]
path = vendor/glfw
url = https://github.com/glfw/glfw.git
[submodule "vendor/libpicasso"]
path = vendor/libpicasso
url = https://github.com/tobid7/libpicasso
[submodule "vendor/spirv-helper"]
path = vendor/spirv-helper
url = https://github.com/tobid7/spirv-helper.git

View File

@@ -1,37 +0,0 @@
{
"configurations": [
{
"name": "3DS | Windows",
"includePath": [
"${workspaceFolder}/**",
"C:/devkitpro/libctru/include/**",
"C:/devkitpro/devkitARM/include/**",
"C:/devkitpro/devkitARM/arm-none-eabi/include/**",
"C:/devkitpro/portlibs/3ds/include/**"
],
"defines": [
"BUILD_CTR",
"__3DS__"
],
"compilerPath": "C:/devkitPro/devkitARM/bin/arm-none-eabi-g++.exe",
"intelliSenseMode": "gcc-arm",
"cStandard": "c11",
"cppStandard": "c++20"
},
{
"name": "3DS | Linux",
"includePath": [
"${workspaceFolder}/**",
"/opt/devkitpro/libctru/include/**",
"/opt/devkitpro/portlibs/3ds/include/**"
],
"defines": [
"BUILD_CTR"
],
"cStandard": "c17",
"cppStandard": "gnu++20",
"intelliSenseMode": "gcc-arm"
}
],
"version": 4
}

21
.vscode/launch.json vendored
View File

@@ -1,21 +0,0 @@
{
"configurations": [
{
"name": "3DS GDB",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceFolder}/build/test.elf",
"miDebuggerServerAddress": "localhost:4003",
"miDebuggerPath": "C:\\devkitPro\\devkitARM\\bin\\arm-none-eabi-gdb.exe",
"cwd": "${workspaceFolder}",
"externalConsole": true,
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
]
}

120
.vscode/settings.json vendored
View File

@@ -1,120 +0,0 @@
{
"files.associations": {
"array": "cpp",
"*.tcc": "cpp",
"cctype": "cpp",
"clocale": "cpp",
"cmath": "cpp",
"cstdarg": "cpp",
"cstddef": "cpp",
"cstdint": "cpp",
"cstdio": "cpp",
"cstdlib": "cpp",
"cwchar": "cpp",
"cwctype": "cpp",
"unordered_map": "cpp",
"vector": "cpp",
"exception": "cpp",
"algorithm": "cpp",
"functional": "cpp",
"iterator": "cpp",
"memory": "cpp",
"numeric": "cpp",
"type_traits": "cpp",
"fstream": "cpp",
"initializer_list": "cpp",
"iosfwd": "cpp",
"iostream": "cpp",
"istream": "cpp",
"limits": "cpp",
"new": "cpp",
"optional": "cpp",
"ostream": "cpp",
"sstream": "cpp",
"stdexcept": "cpp",
"streambuf": "cpp",
"string": "cpp",
"string_view": "cpp",
"system_error": "cpp",
"tuple": "cpp",
"typeinfo": "cpp",
"utility": "cpp",
"atomic": "cpp",
"bit": "cpp",
"bitset": "cpp",
"chrono": "cpp",
"codecvt": "cpp",
"condition_variable": "cpp",
"cstring": "cpp",
"ctime": "cpp",
"deque": "cpp",
"forward_list": "cpp",
"map": "cpp",
"iomanip": "cpp",
"memory_resource": "cpp",
"ratio": "cpp",
"regex": "cpp",
"shared_mutex": "cpp",
"valarray": "cpp",
"random": "cpp",
"cuchar": "cpp",
"compare": "cpp",
"concepts": "cpp",
"numbers": "cpp",
"filesystem": "cpp",
"xstring": "cpp",
"charconv": "cpp",
"format": "cpp",
"ios": "cpp",
"list": "cpp",
"locale": "cpp",
"mutex": "cpp",
"stack": "cpp",
"stop_token": "cpp",
"thread": "cpp",
"xfacet": "cpp",
"xhash": "cpp",
"xiosbase": "cpp",
"xlocale": "cpp",
"xlocbuf": "cpp",
"xlocinfo": "cpp",
"xlocmes": "cpp",
"xlocmon": "cpp",
"xlocnum": "cpp",
"xloctime": "cpp",
"xmemory": "cpp",
"xstddef": "cpp",
"xtr1common": "cpp",
"xtree": "cpp",
"xutility": "cpp",
"queue": "cpp",
"semaphore": "cpp",
"hash_map": "cpp",
"set": "cpp",
"unordered_set": "cpp",
"source_location": "cpp",
"future": "cpp",
"cfenv": "cpp",
"cinttypes": "cpp",
"typeindex": "cpp",
"variant": "cpp",
"ranges": "cpp",
"span": "cpp",
"coroutine": "cpp",
"__bit_reference": "cpp",
"__config": "cpp",
"__debug": "cpp",
"__errc": "cpp",
"__hash_table": "cpp",
"__locale": "cpp",
"__mutex_base": "cpp",
"__node_handle": "cpp",
"__split_buffer": "cpp",
"__threading_support": "cpp",
"__tree": "cpp",
"__verbose_abort": "cpp",
"complex": "cpp",
"any": "cpp",
"text_encoding": "cpp"
}
}

269
CMakeLists.txt Normal file → Executable file
View File

@@ -1,158 +1,141 @@
cmake_minimum_required(VERSION 3.18)
cmake_minimum_required(VERSION 3.22)
### Helper Function to Build Librarys without have always
### These includes and definition defines
function(add_pd_lib TARGET_NAME)
set(opts "BUILD_SHARED")
set(one_val_args "")
set(multi_val_args SRC_FILES DEPENDS)
cmake_parse_arguments(ARG "${opts}" "${one_val_args}" "${multi_val_args}" ${ARGN})
string(REPLACE "-" "_" FLAG_NAME_T ${TARGET_NAME})
string(TOUPPER ${FLAG_NAME_T} FLAG_NAME_F)
if(ARG_BUILD_SHARED)
add_library(${TARGET_NAME} SHARED ${ARG_SRC_FILES})
target_compile_definitions(${TARGET_NAME} PUBLIC -D${FLAG_NAME_F}_BUILD_SHARED=1)
message("Building SHARED library: ${FLAG_NAME_F}_BUILD_SHARED=1")
else()
add_library(${TARGET_NAME} STATIC ${ARG_SRC_FILES})
target_compile_definitions(${TARGET_NAME} PUBLIC -D${FLAG_NAME_F}_BUILD_SHARED=0)
message("Building STATIC library: ${FLAG_NAME_F}_BUILD_SHARED=0")
endif()
target_include_directories(${TARGET_NAME} PUBLIC
include
${DEVKITPRO}/portlibs/3ds/include
backends)
target_compile_definitions(${TARGET_NAME} PUBLIC
-D_GNU_SOURCE=1
-DPALLADIUM_VERSION="${PROJECT_VERSION}"
-DPALLADIUM_GIT_COMMIT="${GIT_SHORT_HASH}"
-DPALLADIUM_GIT_BRANCH="${GIT_BRANCH}"
-DBUILD_CTR=1)
### For the libs that depend on another
if(ARG_DEPENDS)
target_link_libraries(${TARGET_NAME} PUBLIC ${ARG_DEPENDS})
endif()
install(TARGETS ${TARGET_NAME})
endfunction()
## Get Current Git Commit Value
execute_process(
COMMAND git rev-parse --short HEAD
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
OUTPUT_VARIABLE GIT_SHORT_HASH
OUTPUT_STRIP_TRAILING_WHITESPACE
)
## Get Current Git Branch
execute_process(
COMMAND git rev-parse --abbrev-ref HEAD
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
OUTPUT_VARIABLE GIT_BRANCH
OUTPUT_STRIP_TRAILING_WHITESPACE
)
include(GNUInstallDirs)
# Set Project
project(palladium LANGUAGES C CXX VERSION 0.4.0)
project(palladium LANGUAGES C CXX VERSION 0.7.0)
# Required to add this Variable
set(PD_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/include)
include(cmake/palladium.cmake)
option(PD_BUILD_TESTS "Sets if TestApp and TestBench get build" OFF)
option(PD_BUILD_SHARED "Build Shared Libraries" OFF)
option(PD_BUILD_SHARED "Build Shared Library" OFF)
option(PD_BUILD_TOOLS "Build Palladium Tools" OFF)
message("Var: ${PD_BUILD_SHARED}")
# Enable Compile Command Export
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# Force C++ 20
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
# Set Special C and CXX flags for 3ds
if(${CMAKE_SYSTEM_NAME} STREQUAL "Nintendo3DS")
add_compile_options(-Wno-psabi)
endif()
if(${PD_BUILD_TOOLS})
add_subdirectory(tools)
endif()
add_subdirectory(vendor)
# # Include Library Source
set(PD_SOURCES
# Common
source/common.cpp
# Core
source/core/bits.cpp
source/core/color.cpp
source/core/io.cpp
source/core/mat.cpp
source/core/strings.cpp
source/core/timer.cpp
source/core/timetrace.cpp
# Drivers
source/drivers/os.cpp
source/drivers/gfx.cpp
# Lithium
source/lithium/pools.cpp
source/lithium/math.cpp
source/lithium/drawlist.cpp
)
if(${PD_BUILD_SHARED})
message(ERROR "3DS Only supports Static libraries")
endif()
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wno-psabi -O2")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_C_FLAGS} -fno-rtti -fno-exceptions")
endif()
#include_directories(include)
## Core Source Code
set(CORE_SRC
source/core/common.cpp
source/core/bit_util.cpp
source/core/color.cpp
source/core/io.cpp
source/core/hid_driver.cpp
source/core/mat.cpp
source/core/strings.cpp
source/core/sys.cpp
source/core/timer.cpp
source/core/timetrace.cpp)
## Image Source Code
set(IMAGE_SRC
source/image/image.cpp
source/image/img_blur.cpp
source/image/img_convert.cpp)
## External Source Code
set(EXTERNAL_SRC
source/external/stb.cpp)
## Lithiu, Source Code
set(LI_SRC
source/lithium/font.cpp
source/lithium/drawlist.cpp
source/lithium/renderer.cpp)
## Net Source Code
set(NET_SRC
source/net/socket.cpp)
## UI7 Source Code
set(UI7_SRC
source/ui7/drawlist.cpp
source/ui7/io.cpp
source/ui7/layout.cpp
source/ui7/menu.cpp
source/ui7/remenu.cpp
source/ui7/theme.cpp
source/ui7/ui7.cpp
source/ui7/container/container.cpp
source/ui7/container/button.cpp
source/ui7/container/checkbox.cpp
source/ui7/container/coloredit.cpp
source/ui7/container/dragdata.cpp
source/ui7/container/dynobj.cpp
source/ui7/container/image.cpp
source/ui7/container/label.cpp)
#### Creating the Libraries ####
if(PD_BUILD_SHARED)
add_pd_lib(pd-core BUILD_SHARED TRUE SRC_FILES ${CORE_SRC})
add_pd_lib(pd-image BUILD_SHARED TRUE SRC_FILES ${IMAGE_SRC} DEPENDS pd-core)
add_pd_lib(pd-external SRC_FILES ${EXTERNAL_SRC})
add_pd_lib(pd-lithium BUILD_SHARED TRUE SRC_FILES ${LI_SRC} DEPENDS pd-core)
add_pd_lib(pd-net BUILD_SHARED TRUE SRC_FILES ${NET_SRC} DEPENDS pd-core)
add_pd_lib(pd-ui7 BUILD_SHARED TRUE SRC_FILES ${UI7_SRC} DEPENDS pd-core pd-lithium)
add_library(palladium SHARED ${PD_SOURCES})
target_compile_definitions(palladium PRIVATE PD_BUILD_SHARED)
else()
add_pd_lib(pd-core SRC_FILES ${CORE_SRC})
add_pd_lib(pd-image SRC_FILES ${IMAGE_SRC} DEPENDS pd-core)
add_pd_lib(pd-external SRC_FILES ${EXTERNAL_SRC})
add_pd_lib(pd-lithium SRC_FILES ${LI_SRC} DEPENDS pd-core)
add_pd_lib(pd-net SRC_FILES ${NET_SRC} DEPENDS pd-core)
add_pd_lib(pd-ui7 SRC_FILES ${UI7_SRC} DEPENDS pd-core pd-lithium)
add_library(palladium STATIC ${PD_SOURCES})
target_compile_definitions(palladium PUBLIC PD_BUILD_STATIC)
endif()
add_library(palladium INTERFACE)
target_link_libraries(palladium INTERFACE
pd-core pd-image pd-external pd-lithium pd-net pd-ui7
target_compile_definitions(palladium PUBLIC PD_DEBUG)
target_compile_options(palladium
PUBLIC $<$<CXX_COMPILER_ID:GNU,Clang>:
-fmacro-prefix-map=${CMAKE_CURRENT_SOURCE_DIR}/source=source
-fmacro-prefix-map=${CMAKE_CURRENT_SOURCE_DIR}/include=include
>
)
add_dependencies(palladium
pd-core pd-image pd-external pd-lithium pd-net pd-ui7
add_library(palladium::palladium ALIAS palladium)
target_include_directories(palladium
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
install(DIRECTORY include DESTINATION ".")
target_compile_options(palladium
PRIVATE
$<$<AND:$<CONFIG:Debug>,$<CXX_COMPILER_ID:GNU,Clang>>:-O0 -g>
$<$<AND:$<CONFIG:Release>,$<CXX_COMPILER_ID:GNU,Clang>>:-O3>
$<$<AND:$<CONFIG:Debug>,$<CXX_COMPILER_ID:MSVC>>:/Od /Zi>
$<$<AND:$<CONFIG:Release>,$<CXX_COMPILER_ID:MSVC>>:/O2>
)
install(
TARGETS palladium
EXPORT palladiumTargets
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)
install(
DIRECTORY include/
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(EXPORT palladiumTargets
FILE palladiumTargets.cmake
NAMESPACE palladium::
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/palladium
)
include(CMakePackageConfigHelpers)
configure_package_config_file(
cmake/palladiumConfig.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/palladiumConfig.cmake
INSTALL_DESTINATION
${CMAKE_INSTALL_LIBDIR}/cmake/palladium
)
write_basic_package_version_file(
${CMAKE_CURRENT_BINARY_DIR}/palladiumConfigVersion.cmake
VERSION
${PROJECT_VERSION}
COMPATIBILITY
SameMajorVersion
)
install(
FILES
${CMAKE_CURRENT_BINARY_DIR}/palladiumConfig.cmake
${CMAKE_CURRENT_BINARY_DIR}/palladiumConfigVersion.cmake
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/palladium
)
find_program(CLANG_FORMAT clang-format)
file(GLOB_RECURSE PD_FMTFILES
CONFIGURE_DEPENDS
${CMAKE_CURRENT_SOURCE_DIR}/source/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/include/*.hpp
${CMAKE_CURRENT_SOURCE_DIR}/backends/source/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/backends/include/*.hpp
${CMAKE_CURRENT_SOURCE_DIR}/tests/core/source/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/tests/gfx/source/*.cpp
)
add_custom_target(pd-clang-format
COMMAND ${CLANG_FORMAT} --style=file -i ${PD_FMTFILES}
COMMENT "Formatting Project Sources"
)
add_subdirectory(backends)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/tests)

2
LICENSE Normal file → Executable file
View File

@@ -1,6 +1,6 @@
MIT License
Copyright (c) 2024 - 2025 tobid7
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

16
README.md Normal file → Executable file
View File

@@ -23,27 +23,11 @@ make
make install
```
## Libraries
| Name | Last Updated | Platform | Depends |
|---|---|---|---|
| pd-core | 0.3.3 | multi | none |
| pd-external | 0.1.0 | multi | none |
| pd-image | 0.3.3 | multi | pd-core |
| pd-lib3ds | 0.2.4 | 3ds | pd-core, pd-drivers |
| pd-net | 0.2.4 | 3ds | pd-core, pd-lib3ds |
| pd-lithium | 0.3.3 | multi | pd-core |
| pd-sound | 0.2.4 | 3ds | pd-core, mpg123 |
| pd-overlays | 0.2.4 | 3ds | pd-core, pd-image, pd-lib3ds, pd-lithium, pd-ui7 |
| pd-ui7 | 0.3.3 | multi | pd-core, pd-lithium |
| pd-app | 0.2.4 | 3ds | pd-core, pd-image, pd-lib3ds, pd-lithium |
## Credits
| Icon | Username | Description |
|---|---|---|
| <img src="https://github.com/tobid7.png" alt="https://github.com/tobid7" width="48"/> | [tobid7](https://github.com/tobid7) | main dev of RenderD7, Palladium |
| <img src="https://github.com/devkitpro.png" alt="https://github.com/devkitpro" width="48"/> | [devkitpro](https://github.com/devkitpro) | devkitarm, picasso, libctru and citro3d |
| <img src="https://github.com/Universal-Team.png" alt="https://github.com/Universal-Team" width="48"/> | [Universal-Team](https://github.com/Universal-Team) | Inspiration for Lang System, Cia Installer Code |
| <img src="https://github.com/nothings.png" alt="https://github.com/nothings" width="48"/> | [nothings](https://github.com/nothings) | stb_image(_write) and stb_truetype |
| <img src="https://github.com/nlohmann.png" alt="https://github.com/nlohmann" width="48"/> | [nlohmann](https://github.com/nlohmann) | for json.hpp |

View File

@@ -1,18 +0,0 @@
cmake_minimum_required(VERSION 3.22)
# Make sure to use 3ds toolschain for 3ds build :)
if(NOT DEFINED CMAKE_TOOLCHAIN_FILE)
if(DEFINED ENV{DEVKITPRO})
set(CMAKE_TOOLCHAIN_FILE "$ENV{DEVKITPRO}/cmake/3DS.cmake" CACHE PATH "toolchain file")
else()
message(FATAL_ERROR "Please define DEVKITPRO to point to your SDK path!")
endif()
endif()
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -Wno-psabi -O3")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${CMAKE_C_FLAGS} -fno-rtti -fno-exceptions")
add_library(pd-backend-3ds STATIC
source/li_backend_c3d.cpp
source/pd_hid_3ds.cpp)
target_include_directories(pd-backend-3ds PUBLIC include)
target_link_libraries(pd-backend-3ds PUBLIC palladium)

View File

@@ -1,84 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#include <3ds.h>
#include <citro3d.h>
#include <pd/core/core.hpp>
#include <pd/lithium/backend.hpp>
namespace PD {
template <typename T>
class LinearAlloc : public Allocator<T> {
public:
LinearAlloc() = default;
~LinearAlloc() = default;
/** Never forget the sizeof(T) again (most painful bug i created) */
T* Allocate(size_t n) override { return (T*)linearAlloc(n * sizeof(T)); }
void Deallocate(T* ptr) { linearFree(ptr); }
};
namespace LI {
class Backend_C3D : public PD::LI::Backend {
public:
Backend_C3D() : LI::Backend("Citro3D") {}
~Backend_C3D() {}
PD_SMART_CTOR(Backend_C3D)
void Init() override;
void Deinit() override;
void NewFrame() override;
void BindTexture(PD::LI::TexAddress addr) override;
void RenderDrawData(const PD::Vec<PD::LI::Command::Ref>& Commands) override;
PD::LI::Texture::Ref LoadTexture(
const std::vector<PD::u8>& pixels, int w, int h,
PD::LI::Texture::Type type = PD::LI::Texture::Type::RGBA32,
PD::LI::Texture::Filter filter =
PD::LI::Texture::Filter::LINEAR) override;
private:
Vec<Vertex, LinearAlloc<Vertex>> VertexBuffer;
Vec<u16, LinearAlloc<u16>> IndexBuffer;
size_t CurrentVertex = 0;
size_t CurrentIndex = 0;
Mat4 Projection;
int pLocProjection = 0;
DVLB_s* ShaderCode;
shaderProgram_s Shader;
C3D_AttrInfo ShaderInfo;
// For Stats
PD::u32 num_vtx = 0;
PD::u32 num_idx = 0;
};
} // namespace LI
} // namespace PD

View File

@@ -1,117 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <3ds.h>
#include <arpa/inet.h>
#include <malloc.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <pd/net/backend.hpp>
namespace PD {
class NetBackend3DS : public Net::Backend {
public:
NetBackend3DS() : Net::Backend("3DS") {}
~NetBackend3DS() = default;
PD_SMART_CTOR(NetBackend3DS)
bool Init() override {
pSocBuffer = (uint32_t*)memalign(pSocAlign, pSocBufferSize);
Result ret = 0;
if (pSocBuffer == NULL) {
return false;
}
if ((ret = socInit(pSocBuffer, pSocBufferSize)) != 0) {
return false;
}
return true;
}
void Deinit() override { socExit(); }
int NewSocket() override { return socket(AF_INET, SOCK_STREAM, 0); }
void Close(int sock_id) override { close(sock_id); }
int GetInvalidRef() const override { return -1; }
bool Bind(int sock_id, u16 port) {
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
return bind(sock_id, (sockaddr*)&addr, sizeof(addr)) != -1;
}
bool Listen(int sock_id, int backlog = 5) {
return listen(sock_id, backlog) != -1;
}
bool WaitForRead(int sock_id, int timeout_ms) override {
fd_set set;
FD_ZERO(&set);
FD_SET(sock_id, &set);
timeval timeout{};
timeout.tv_sec = timeout_ms / 1000;
timeout.tv_usec = (timeout_ms % 1000) * 1000;
int result = select(sock_id + 1, &set, nullptr, nullptr, &timeout);
return (result > 0 && FD_ISSET(sock_id, &set));
}
bool Accept(int sock_id, Net::Socket::Ref client) {
int client_soc = accept(sock_id, nullptr, nullptr);
if (client_soc == -1) {
return false;
}
client->pSocket = client_soc;
return true;
}
bool Connect(int sock_id, const std::string& ip, u16 port) {
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
inet_pton(AF_INET, ip.c_str(), &addr.sin_addr);
return connect(sock_id, (sockaddr*)&addr, sizeof(addr)) != -1;
}
int Send(int sock_id, const std::string& data) {
return send(sock_id, data.c_str(), static_cast<int>(data.size()), 0);
}
int Receive(int sock_id, std::string& data, int size = 1024) {
char* tmp = new char[size];
int res = recv(sock_id, tmp, size, 0);
if (res > 0) {
data.assign(tmp, res);
}
delete[] tmp;
return res;
}
private:
/** using libctru u32 here */
const uint32_t pSocAlign = 0x1000;
const uint32_t pSocBufferSize = 0x100000;
uint32_t* pSocBuffer = nullptr;
};
} // namespace PD

View File

@@ -1,231 +0,0 @@
#include <li_backend_c3d.hpp>
/// @brief Shader Code (Unused as i dont want to use libpicasso here (yet))
const char* LIShaderCTR = R"(
; LI7 Shader
; Constants
.constf myconst(0.0, 1.0, 0.00392156862745, 0.0)
.alias ones myconst.yyyy ; Vector full of ones
; Uniforms
.fvec projection[4]
; Outputs
.out out_position position
.out out_color color
.out out_uv texcoord0
; Inputs
.alias in_xy v0
.alias in_uvc v1
.alias in_col v2
.entry vmain
.proc vmain
mov r0.xy, in_xy.xy
mov r0.w, ones
dp4 out_position.x, projection[0], r0
dp4 out_position.y, projection[1], r0
dp4 out_position.z, projection[2], r0
dp4 out_position.w, projection[3], r0
mov out_uv, in_uvc.xy
mul r1, myconst.zzzz, in_col
mov out_color, r1
end
.end
)";
// clang-format off
unsigned char li_shader[] = {
0x44, 0x56, 0x4c, 0x42, 0x1, 0x0, 0x0, 0x0, 0xa4, 0x0, 0x0, 0x0, 0x44, 0x56, 0x4c, 0x50, 0x0, 0x0, 0x0, 0x0, 0x28, 0x0, 0x0, 0x0, 0xa, 0x0, 0x0, 0x0, 0x50, 0x0, 0x0, 0x0, 0x9, 0x0, 0x0, 0x0, 0x98, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4e, 0x1, 0xf0, 0x7, 0x4e, 0x2, 0x8, 0x2, 0x8, 0x3, 0x18, 0x2, 0x8, 0x4, 0x28, 0x2, 0x8, 0x5, 0x38, 0x2, 0x8, 0x6, 0x10, 0x40, 0x4c, 0x7, 0xf1, 0x27, 0x22, 0x8, 0x10, 0x21, 0x4c, 0x0, 0x0, 0x0, 0x88, 0xac, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xa1, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x68, 0xc3, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x64, 0xc3, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x62, 0xc3, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x61, 0xc3, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0xaf, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x4f, 0xd5, 0x6, 0x0, 0x0, 0x0, 0x0, 0x0, 0x6f, 0x3, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x44, 0x56, 0x4c, 0x45, 0x2, 0x10, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xa, 0x0, 0x0, 0x0, 0x0, 0x0, 0x7, 0x0, 0x0, 0x0, 0x0, 0x0, 0x40, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x54, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x54, 0x0, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0, 0x6c, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x74, 0x0, 0x0, 0x0, 0xb, 0x0, 0x0, 0x0, 0x2, 0x0, 0x5f, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3f, 0x0, 0x1, 0x1, 0x37, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xf, 0x0, 0x0, 0x0, 0x2, 0x0, 0x1, 0x0, 0xf, 0x0, 0x0, 0x0, 0x3, 0x0, 0x2, 0x0, 0xf, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x10, 0x0, 0x13, 0x0, 0x70, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x0, 0x0,
};
// clang-format on
size_t li_shader_size = 0x124;
namespace PD {
namespace LI {
GPU_TEXCOLOR GetTexFmt(Texture::Type type) {
if (type == Texture::RGBA32)
return GPU_RGBA8;
else if (type == Texture::RGB24)
return GPU_RGB8;
else if (type == Texture::A8)
return GPU_A8;
return GPU_RGBA8; // Default
}
int GetBPP(Texture::Type type) {
if (type == Texture::RGBA32)
return 4;
else if (type == Texture::RGB24)
return 3;
else if (type == Texture::A8)
return 1;
return 0; // Error
}
void Backend_C3D::Init() {
std::cout << "[BACKEND_C3D]: Setting up Buffers" << std::endl;
VertexBuffer.Resize(4 * 8192);
IndexBuffer.Resize(6 * 8192);
Flags |= LIBackendFlags_FlipUV_Y;
std::cout << "[BACKEND_C3D]: Loading shader..." << std::endl;
ShaderCode = DVLB_ParseFile((uint32_t*)li_shader, li_shader_size);
shaderProgramInit(&Shader);
shaderProgramSetVsh(&Shader, &ShaderCode->DVLE[0]);
pLocProjection =
shaderInstanceGetUniformLocation(Shader.vertexShader, "projection");
std::cout << "[BACKEND_C3D]: Setting up Attr Info" << std::endl;
AttrInfo_Init(&ShaderInfo);
AttrInfo_AddLoader(&ShaderInfo, 0, GPU_FLOAT, 2);
AttrInfo_AddLoader(&ShaderInfo, 1, GPU_FLOAT, 2);
AttrInfo_AddLoader(&ShaderInfo, 2, GPU_UNSIGNED_BYTE, 4);
std::cout << "[BACKEND_C3D]: Backend init done!" << std::endl;
}
void Backend_C3D::Deinit() {
shaderProgramFree(&Shader);
DVLB_Free(ShaderCode);
}
void Backend_C3D::NewFrame() {
C3D_BindProgram(&Shader);
C3D_SetAttrInfo(&ShaderInfo);
CurrentIndex = 0;
CurrentVertex = 0;
FrameCounter++;
VertexCounter = num_vtx;
IndexCounter = num_idx;
num_vtx = 0;
num_idx = 0;
}
void Backend_C3D::BindTexture(PD::LI::TexAddress addr) {
C3D_TexBind(0, reinterpret_cast<C3D_Tex*>(addr));
}
void Backend_C3D::RenderDrawData(
const PD::Vec<PD::LI::Command::Ref>& Commands) {
C3D_BindProgram(&Shader);
C3D_SetAttrInfo(&ShaderInfo);
C3D_Mtx proj;
Mtx_OrthoTilt(&proj, 0.f, ViewPort.x, ViewPort.y, 0.f, 1.f, -1.f, false);
C3D_FVUnifMtx4x4(GPU_VERTEX_SHADER, pLocProjection, &proj);
C3D_DepthTest(false, GPU_GREATER, GPU_WRITE_ALL);
C3D_TexEnv* env = C3D_GetTexEnv(0);
C3D_TexEnvInit(env);
C3D_TexEnvSrc(env, C3D_Both, GPU_TEXTURE0);
C3D_TexEnvFunc(env, C3D_Both, GPU_MODULATE);
size_t index = 0;
while (index < Commands.Size()) {
PD::LI::Texture::Ref Tex = Commands[index]->Tex;
if (!Tex) {
index++;
continue;
}
bool ScissorEnabled = Commands[index]->ScissorEnabled;
ivec4 ScissorRect = Commands[index]->ScissorRect;
size_t StartIndex = CurrentIndex;
while (index < Commands.Size() && Commands[index]->Tex == Tex &&
Commands[index]->ScissorEnabled == ScissorEnabled &&
Commands[index]->ScissorRect == ScissorRect) {
auto c = Commands[index];
for (size_t i = 0; i < c->IndexBuffer.Size(); i++) {
num_idx++;
IndexBuffer[CurrentIndex++] = CurrentVertex + c->IndexBuffer.At(i);
}
for (size_t i = 0; i < c->VertexBuffer.Size(); i++) {
num_vtx++;
VertexBuffer[CurrentVertex++] = c->VertexBuffer.At(i);
}
index++;
}
if (ScissorEnabled) {
// Figure out this setup was pain
C3D_SetScissor(GPU_SCISSOR_NORMAL,
ViewPort.y - (ScissorRect.y + ScissorRect.w),
ViewPort.x - (ScissorRect.x + ScissorRect.z),
ViewPort.y - ScissorRect.y, ViewPort.x - ScissorRect.x);
} else {
C3D_SetScissor(GPU_SCISSOR_DISABLE, 0, 0, 0, 0);
}
BindTexture(Tex->Address);
auto bufInfo = C3D_GetBufInfo();
BufInfo_Init(bufInfo);
BufInfo_Add(bufInfo, VertexBuffer.Data(), sizeof(Vertex), 3, 0x210);
C3D_DrawElements(GPU_TRIANGLES, CurrentIndex - StartIndex,
C3D_UNSIGNED_SHORT, IndexBuffer.Data() + StartIndex);
}
C3D_DepthTest(true, GPU_GREATER, GPU_WRITE_ALL);
}
PD::LI::Texture::Ref Backend_C3D::LoadTexture(const std::vector<PD::u8>& pixels,
int w, int h,
PD::LI::Texture::Type type,
PD::LI::Texture::Filter filter) {
std::cout << "Loading Tex " << std::format("[{}, {}]", w, h) << std::endl;
if (w > 1024 || h > 1024) {
return nullptr;
}
// Don't check here as check done before
PD::LI::Texture::Ref res = PD::LI::Texture::New();
int bpp = GetBPP(type);
ivec2 tex_size(w, h);
// Pow2
if (!PD::BitUtil::IsSingleBit(w)) {
tex_size.x = PD::BitUtil::GetPow2((unsigned int)w);
}
if (!PD::BitUtil::IsSingleBit(h)) {
tex_size.y = PD::BitUtil::GetPow2((unsigned int)h);
}
res->Size.x = w;
res->Size.y = h;
res->UV = fvec4(0.f, 1.f, ((float)w / (float)tex_size.x),
1.0 - ((float)h / (float)tex_size.y));
// Texture Setup
auto fltr = (filter == Texture::NEAREST ? GPU_NEAREST : GPU_LINEAR);
auto tex_fmt = GetTexFmt(type);
auto tex = new C3D_Tex;
C3D_TexInit(tex, (u16)tex_size.x, (u16)tex_size.y, tex_fmt);
C3D_TexSetFilter(tex, fltr, fltr);
// Using std::fill_n instead cause i hate this error lines
// under the memset func in my editor
std::fill_n((PD::u8*)tex->data, tex->size, 0);
// memset(tex->data, 0, tex->size);s
/// Probably Remove this if statement in future
/// This are the things confirmed as working
if (bpp == 3 || bpp == 4 || bpp == 1) {
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
int dst_pos = ((((y >> 3) * ((int)tex_size.x >> 3) + (x >> 3)) << 6) +
((x & 1) | ((y & 1) << 1) | ((x & 2) << 1) |
((y & 2) << 2) | ((x & 4) << 2) | ((y & 4) << 3))) *
bpp;
int src_pos = (y * w + x) * bpp;
/// Best idea i had
for (int i = 0; i < bpp; i++) {
((u8*)tex->data)[dst_pos + bpp - 1 - i] = pixels[src_pos + i];
}
}
}
C3D_TexFlush(tex);
}
tex->border = 0x00000000;
C3D_TexSetWrap(tex, GPU_REPEAT, GPU_REPEAT);
res->Address = (TexAddress)tex;
std::cout << std::format("Tex {:#08x} Addr {:#08X}", (TexAddress)res.get(),
res->Address)
<< std::endl;
return res;
}
} // namespace LI
} // namespace PD

View File

@@ -1,60 +0,0 @@
#include <3ds.h>
#include <pd_hid_3ds.hpp>
namespace PD {
Hid3DS::Hid3DS() : Hid("3DS") {
binds[KEY_A] = A;
binds[KEY_B] = B;
binds[KEY_X] = X;
binds[KEY_Y] = Y;
binds[KEY_START] = Start;
binds[KEY_SELECT] = Select;
binds[KEY_L] = L;
binds[KEY_R] = R;
binds[KEY_DUP] = DUp;
binds[KEY_DDOWN] = DDown;
binds[KEY_DLEFT] = DLeft;
binds[KEY_DRIGHT] = DRight;
binds[KEY_CPAD_UP] = CPUp;
binds[KEY_CPAD_DOWN] = CPDown;
binds[KEY_CPAD_LEFT] = CPLeft;
binds[KEY_CPAD_RIGHT] = CPRight;
binds[KEY_CSTICK_UP] = CSUp;
binds[KEY_CSTICK_DOWN] = CSDown;
binds[KEY_CSTICK_LEFT] = CSLeft;
binds[KEY_CSTICK_RIGHT] = CSRight;
binds[KEY_ZL] = ZL;
binds[KEY_ZR] = ZR;
binds[KEY_TOUCH] = Touch;
}
void Hid3DS::Update() {
hidScanInput();
for (int i = 0; i < 2; i++) {
key_events[i][Event_Down] = 0;
key_events[i][Event_Held] = 0;
key_events[i][Event_Up] = 0;
}
u32 kd = hidKeysDown();
u32 kh = hidKeysHeld();
u32 ku = hidKeysUp();
for (auto &b : binds) {
if (b.first & kd) {
key_events[0][Event_Down] |= b.second;
}
if (b.first & kh) {
key_events[0][Event_Held] |= b.second;
}
if (b.first & ku) {
key_events[0][Event_Up] |= b.second;
}
}
if (locked) {
SwappyTable();
}
touchPosition t;
hidTouchRead(&t);
touch[1] = touch[0]; // Cycle touch pos
touch[0] = fvec2(t.px, t.py);
}
} // namespace PD

83
backends/CMakeLists.txt Normal file
View File

@@ -0,0 +1,83 @@
cmake_minimum_required(VERSION 3.22)
project(pd-system)
option(PD_ENABLE_OPENGL2 "Enable OpenGL 2.1 (On Supported Hardware)" ON)
option(PD_ENABLE_OPENGL3 "Enable OpenGL 3.3 (On Supported Hardware)" ON)
option(PD_ENABLE_DIRECTX9 "Enable DirectX9 Support" ON)
option(PD_ENABLE_CITRO3D "Enable Citro3D Support (3DS)" OFF)
option(PD_ENABLE_VULKAN "Not implemented yet" OFF)
if(NOT WIN32) # cause we are not on windows...
set(PD_ENABLE_DIRECTX9 OFF)
endif()
if(${CMAKE_SYSTEM_NAME} STREQUAL "Nintendo3DS")
set(PD_ENABLE_OPENGL2 OFF)
set(PD_ENABLE_OPENGL3 OFF)
set(PD_ENABLE_VULKAN OFF)
set(PD_ENABLE_CITRO3D ON)
endif()
add_library(pd-system STATIC
${CMAKE_CURRENT_SOURCE_DIR}/source/gl-helper.cpp
${CMAKE_CURRENT_SOURCE_DIR}/source/gfx_opengl2.cpp
${CMAKE_CURRENT_SOURCE_DIR}/source/gfx_opengl3.cpp
${CMAKE_CURRENT_SOURCE_DIR}/source/gfx_directx9.cpp
${CMAKE_CURRENT_SOURCE_DIR}/source/gfx_citro3d.cpp
)
target_include_directories(pd-system
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
target_compile_options(palladium
PUBLIC $<$<CXX_COMPILER_ID:GNU,Clang>:
-fmacro-prefix-map=${CMAKE_CURRENT_SOURCE_DIR}/source=source
-fmacro-prefix-map=${CMAKE_CURRENT_SOURCE_DIR}/include=include
>
)
target_compile_definitions(pd-system
PUBLIC
$<$<BOOL:${PD_ENABLE_OPENGL2}>:PD_ENABLE_OPENGL2>
$<$<BOOL:${PD_ENABLE_OPENGL3}>:PD_ENABLE_OPENGL3>
$<$<BOOL:${PD_ENABLE_VULKAN}>:PD_ENABLE_VULKAN>
$<$<BOOL:${PD_ENABLE_DIRECTX9}>:PD_ENABLE_DIRECTX9>
$<$<BOOL:${PD_ENABLE_CITRO3D}>:PD_ENABLE_CITRO3D>
)
# Palladium
target_link_libraries(pd-system PUBLIC palladium::palladium)
# glad (if we have any OpenGL version included)
if(PD_ENABLE_OPENGL2 OR PD_ENABLE_OPENGL3)
target_link_libraries(pd-system
PUBLIC glad
)
endif()
# DirectX9
if(PD_ENABLE_DIRECTX9)
target_link_libraries(pd-system
PUBLIC
d3d9
d3dcompiler
)
endif()
if(${CMAKE_SYSTEM_NAME} STREQUAL "Nintendo3DS")
target_link_libraries(pd-system
PUBLIC
pica::pica
citro3d
ctru
)
else()
target_link_libraries(pd-system
PUBLIC
spirv-helper
)
endif()

24
backends/README.md Normal file
View File

@@ -0,0 +1,24 @@
# Backends
- [Graphics](#graphics)
- [OpenGL2](#opengl2-legacy)
- [OpenGL3](#opengl3-modern-opengl)
- [DirectX9](#directx9-could-potentially-cover-more-then-opengl2)
- [Citro3D](#citro3d-3ds)
## Graphics
### OpenGL2 (Legacy)
> [!NOTE]
> As SPIRV to GLSL 120 translation doesn't work, your'e forced to write separate shaders for this backend
### OpenGL3+ (Modern OpenGL)
### DirectX9 (Could potentially cover more than OpenGL2)
### Citro3D (3DS)
> [!NOTE]
> This backend requires shaders as binary file, directly in the code or as string for libpicasso
> The Fragment Stage is special and is still wip

View File

@@ -1,27 +0,0 @@
cmake_minimum_required(VERSION 3.22)
if(WIN32)
set(EXTRA_LIBS ws2_32)
else()
set(EXTRA_LIBS)
endif()
add_subdirectory(glfw)
add_subdirectory(glad)
# if(PD_BUILD_SHARED)
# add_library(pd-backend-desktop SHARED
# source/li_backend_gl2.cpp
# source/pd_hid_glfw.cpp)
# target_compile_definitions(pd-backend-desktop PUBLIC
# -DPD_BKND_DESKTOP_BUILD_SHARED=1)
# else()
add_library(pd-backend-desktop STATIC
source/li_backend_gl2.cpp
source/pd_hid_glfw.cpp)
#endif()
target_compile_definitions(pd-backend-desktop PUBLIC
-DPD_BKND_DESKTOP_STATIC=1)
target_include_directories(pd-backend-desktop PUBLIC include)
target_link_libraries(pd-backend-desktop PUBLIC glad glfw palladium ${EXTRA_LIBS})

View File

@@ -1,4 +0,0 @@
cmake_minimum_required(VERSION 3.22)
add_library(glad source/glad.c)
target_include_directories(glad PUBLIC include)

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,46 +0,0 @@
#include <glad/glad.h>
/** SEPARATOR */
#include <GLFW/glfw3.h>
/** SEPARATOR */
#include <pd/core/core.hpp>
#include <pd/lithium/backend.hpp>
#include <pd_p_bknd_api.hpp>
namespace PD {
namespace LI {
class PD_BKND_DESKTOP_API Backend_GL2 : public PD::LI::Backend {
public:
Backend_GL2() : LI::Backend("OpenGL2") {}
~Backend_GL2() {}
PD_SMART_CTOR(Backend_GL2)
void Init() override;
void Deinit() override;
void NewFrame() override;
void BindTexture(PD::LI::TexAddress addr) override;
void RenderDrawData(const PD::Vec<PD::LI::Command::Ref>& Commands) override;
PD::LI::Texture::Ref LoadTexture(
const std::vector<PD::u8>& pixels, int w, int h,
PD::LI::Texture::Type type = PD::LI::Texture::Type::RGBA32,
PD::LI::Texture::Filter filter =
PD::LI::Texture::Filter::LINEAR) override;
private:
PD::Vec<PD::LI::Vertex> VertexBuffer;
PD::Vec<PD::u16> IndexBuffer;
size_t CurrentVertex = 0;
size_t CurrentIndex = 0;
GLuint Shader;
GLuint pLocProjection;
GLuint pLocTex;
Mat4 Projection;
GLuint VBO, IBO;
// For Stats
PD::u32 num_vtx = 0;
PD::u32 num_idx = 0;
};
} // namespace LI
} // namespace PD

View File

@@ -1,132 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#ifdef _MSVC
#pragma comment(lib, "ws2_32.lib")
#endif
#else
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#endif
#include <pd/net/backend.hpp>
namespace PD {
class NetBackendDesktop : public PD::Net::Backend {
public:
#ifdef _WIN32
NetBackendDesktop() : Net::Backend("Desktop (Windows)") {
#else
NetBackendDesktop() : Net::Backend("Desktop (Unix)") {
#endif
}
~NetBackendDesktop() = default;
PD_SMART_CTOR(NetBackendDesktop)
bool Init() override {
#ifdef _WIN32
WSADATA wsa_data;
return (WSAStartup(MAKEWORD(2, 2), &wsa_data) == 0);
#else
return true;
#endif
}
void Deinit() override {
#ifdef _WIN32
WSACleanup();
#endif
}
int NewSocket() override { return socket(AF_INET, SOCK_STREAM, 0); }
void Close(int sock_id) override {
#ifdef _WIN32
closesocket(sock_id);
#else
close(sock_id);
#endif
}
int GetInvalidRef() const override {
#ifdef _WIN32
return INVALID_SOCKET;
#else
return -1;
#endif
}
bool Bind(int sock_id, u16 port) override {
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY;
return bind(sock_id, (sockaddr*)&addr, sizeof(addr)) != -1;
}
bool Listen(int sock_id, int backlog = 5) override {
return listen(sock_id, backlog) != -1;
}
bool WaitForRead(int sock_id, int timeout_ms) override {
fd_set set;
FD_ZERO(&set);
FD_SET(sock_id, &set);
timeval timeout{};
timeout.tv_sec = timeout_ms / 1000;
timeout.tv_usec = (timeout_ms % 1000) * 1000;
int result = select(sock_id + 1, &set, nullptr, nullptr, &timeout);
return (result > 0 && FD_ISSET(sock_id, &set));
}
bool Accept(int sock_id, Net::Socket::Ref client) override {
int client_soc = accept(sock_id, nullptr, nullptr);
if (client_soc == GetInvalidRef()) {
return false;
}
client->pSocket = client_soc;
return true;
}
bool Connect(int sock_id, const std::string& ip, u16 port) override {
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
inet_pton(AF_INET, ip.c_str(), &addr.sin_addr);
return connect(sock_id, (sockaddr*)&addr, sizeof(addr)) != -1;
}
int Send(int sock_id, const std::string& data) override {
return send(sock_id, data.c_str(), static_cast<int>(data.size()), 0);
}
int Receive(int sock_id, std::string& data, int size = 1024) override {
char* tmp = new char[size];
int res = recv(sock_id, tmp, size, 0);
if (res > 0) {
data.assign(tmp, res);
}
delete[] tmp;
return res;
}
};
} // namespace PD

View File

@@ -1,58 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#ifdef PD_BKND_DESKTOP_STATIC
#if defined(__3DS__) // 3ds Specific
#error "Desktop backend is not supported on the 3ds!"
#endif
#define PD_BKND_DESKTOP_API
#else
#ifdef _WIN32 // Windows (MSVC Tested)
#ifdef PD_BKND_DESKTOP_BUILD_SHARED
#define PD_BKND_DESKTOP_API __declspec(dllexport)
#else
#define PD_BKND_DESKTOP_API __declspec(dllimport)
#endif
#elif defined(__APPLE__) // macOS (untested yet)
#ifdef PD_BKND_DESKTOP_BUILD_SHARED
#define PD_BKND_DESKTOP_API __attribute__((visibility("default")))
#else
#define PD_BKND_DESKTOP_API
#endif
#elif defined(__linux__) // Linux (untested yet)
#ifdef PD_BKND_DESKTOP_BUILD_SHARED
#define PD_BKND_DESKTOP_API __attribute__((visibility("default")))
#else
#define PD_BKND_DESKTOP_API
#endif
#elif defined(__3DS__) // 3ds Specific
#error "Desktop backend is not supported on the 3ds!"
#else
#define PD_BKND_DESKTOP_API
#endif
#endif

View File

@@ -1,230 +0,0 @@
#include <li_backend_gl2.hpp>
const char* vertex_shader = R"(
#version 120
attribute vec2 pos;
attribute vec2 uv;
attribute vec4 color;
varying vec2 oUV;
varying vec4 oColor;
// Probably forgot about this matric and
// searched hours for why the rendering isn't working :/
uniform mat4 projection;
void main() {
gl_Position = projection*vec4(pos, 0.0, 1.0);
oUV = uv;
oColor = color;
}
)";
const char* frag_shader = R"(
#version 120
varying vec2 oUV;
varying vec4 oColor;
uniform sampler2D tex;
void main() {
vec4 tc = texture2D(tex, oUV);
gl_FragColor = tc*oColor;
}
)";
GLuint compileShader(const std::string& source,
GLenum type) {
GLuint shader = glCreateShader(type);
const char* src = source.c_str();
glShaderSource(shader, 1, &src, nullptr);
glCompileShader(shader);
GLint success;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success) {
char infoLog[512];
glGetShaderInfoLog(shader, 512, nullptr, infoLog);
std::cerr << "Shader Compilation Error: " << infoLog << std::endl;
}
return shader;
}
GLuint
createShaderProgram(const std::string& vertexShaderSource,
const std::string& fragmentShaderSource) {
GLuint vertexShader = compileShader(vertexShaderSource, GL_VERTEX_SHADER);
GLuint fragmentShader =
compileShader(fragmentShaderSource, GL_FRAGMENT_SHADER);
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
GLint success;
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
char infoLog[512];
glGetProgramInfoLog(shaderProgram, 512, nullptr, infoLog);
std::cerr << "Shader Program Linking Error: " << infoLog << std::endl;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return shaderProgram;
}
namespace PD {
namespace LI {
PD_BKND_DESKTOP_API void Backend_GL2::Init() {
VertexBuffer.Resize(4 * 8192);
IndexBuffer.Resize(6 * 8192);
Shader = createShaderProgram(vertex_shader, frag_shader);
glUseProgram(Shader);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
GLint _pos = glGetAttribLocation(Shader, "pos");
GLint _uv = glGetAttribLocation(Shader, "uv");
GLint _color = glGetAttribLocation(Shader, "color");
glVertexAttribPointer(_pos, 2, GL_FLOAT, GL_FALSE, sizeof(PD::LI::Vertex),
(void*)offsetof(PD::LI::Vertex, Pos));
glEnableVertexAttribArray(_pos);
glVertexAttribPointer(_uv, 2, GL_FLOAT, GL_FALSE, sizeof(PD::LI::Vertex),
(void*)offsetof(PD::LI::Vertex, UV));
glEnableVertexAttribArray(_uv);
glVertexAttribPointer(_color, 4, GL_UNSIGNED_BYTE, GL_TRUE,
sizeof(PD::LI::Vertex),
(void*)offsetof(PD::LI::Vertex, Color));
glEnableVertexAttribArray(_color);
glGenBuffers(1, &IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
pLocTex = glGetUniformLocation(Shader, "tex");
pLocProjection = glGetUniformLocation(Shader, "projection");
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
PD_BKND_DESKTOP_API void Backend_GL2::Deinit() {
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &IBO);
}
PD_BKND_DESKTOP_API void Backend_GL2::NewFrame() {
glViewport(0, 0, ViewPort.x, ViewPort.y);
glClearColor(ClearColor.x, ClearColor.y, ClearColor.z, ClearColor.w);
glClear(GL_COLOR_BUFFER_BIT);
Projection.Ortho(0.f, ViewPort.x, ViewPort.y, 0.f, -1.f, 1.f);
glUniformMatrix4fv(pLocProjection, 1, GL_TRUE, Projection.m);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
CurrentIndex = 0;
CurrentVertex = 0;
FrameCounter++;
VertexCounter = num_vtx;
IndexCounter = num_idx;
num_vtx = 0;
num_idx = 0;
}
PD_BKND_DESKTOP_API void Backend_GL2::BindTexture(PD::LI::TexAddress addr) {
// Actually not using the Address as Address
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, (GLuint)addr);
glUniform1i(pLocTex, 0);
}
PD_BKND_DESKTOP_API void Backend_GL2::RenderDrawData(
const PD::Vec<PD::LI::Command::Ref>& Commands) {
glUseProgram(Shader);
size_t index = 0;
while (index < Commands.Size()) {
PD::LI::Texture::Ref Tex = Commands[index]->Tex;
if (!Tex) {
index++;
continue;
}
size_t StartIndex = CurrentIndex;
bool ScissorEnabled = Commands[index]->ScissorEnabled;
ivec4 ScissorRect = Commands[index]->ScissorRect;
while (index < Commands.Size() && Commands[index]->Tex == Tex &&
Commands[index]->ScissorEnabled == ScissorEnabled &&
Commands[index]->ScissorRect == ScissorRect) {
auto c = Commands[index];
for (size_t i = 0; i < c->IndexBuffer.Size(); i++) {
num_idx++;
IndexBuffer[CurrentIndex++] = CurrentVertex + c->IndexBuffer.At(i);
}
for (size_t i = 0; i < c->VertexBuffer.Size(); i++) {
num_vtx++;
VertexBuffer[CurrentVertex++] = c->VertexBuffer.At(i);
}
index++;
}
if (ScissorEnabled) {
glScissor(ScissorRect.x, ViewPort.y - (ScissorRect.y + ScissorRect.w),
ScissorRect.z, ScissorRect.w);
glEnable(GL_SCISSOR_TEST);
} else {
glDisable(GL_SCISSOR_TEST);
}
BindTexture(Tex->Address);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, CurrentVertex * sizeof(PD::LI::Vertex),
&VertexBuffer[0], GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, CurrentIndex * sizeof(PD::u16),
&IndexBuffer[0], GL_DYNAMIC_DRAW);
glDrawElements(GL_TRIANGLES, CurrentIndex - StartIndex, GL_UNSIGNED_SHORT,
(void*)(StartIndex * sizeof(PD::u16)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
BindTexture(0);
}
}
PD_BKND_DESKTOP_API PD::LI::Texture::Ref Backend_GL2::LoadTexture(
const std::vector<PD::u8>& pixels, int w, int h, PD::LI::Texture::Type type,
PD::LI::Texture::Filter filter) {
GLuint texID;
glGenTextures(1, &texID);
glBindTexture(GL_TEXTURE_2D, texID);
// Set base format (Always using RGBA as base)
GLenum fmt = GL_RGBA;
if (type == PD::LI::Texture::Type::RGB24) {
fmt = GL_RGB;
} else if (type == PD::LI::Texture::Type::A8) {
fmt = GL_ALPHA;
}
glTexImage2D(GL_TEXTURE_2D, 0, fmt, w, h, 0, fmt, GL_UNSIGNED_BYTE,
pixels.data());
if (filter == PD::LI::Texture::Filter::LINEAR) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
} else if (filter == PD::LI::Texture::Filter::NEAREST) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
glBindTexture(GL_TEXTURE_2D, 0);
auto res = PD::LI::Texture::New(texID, PD::ivec2(w, h));
return res;
}
} // namespace LI
} // namespace PD

View File

@@ -1,33 +0,0 @@
#include <pd_hid_glfw.hpp>
namespace PD {
PD_BKND_DESKTOP_API HidGLFW::HidGLFW(GLFWwindow* win) : Hid("GLFW") {
Window = win;
binds[GLFW_MOUSE_BUTTON_LEFT] = Touch;
}
PD_BKND_DESKTOP_API void HidGLFW::Update() {
for (int i = 0; i < 2; i++) {
key_events[i][Event_Down] = 0;
key_events[i][Event_Held] = 0;
key_events[i][Event_Up] = 0;
}
int state = glfwGetMouseButton(Window, GLFW_MOUSE_BUTTON_LEFT);
if (state == GLFW_PRESS) {
if (PrevState == GLFW_RELEASE) {
key_events[0][Event_Down] |= Touch;
}
key_events[0][Event_Held] |= Touch;
} else if (state == GLFW_RELEASE && PrevState == GLFW_PRESS) {
key_events[0][Event_Up] |= Touch;
}
PrevState = state;
if (locked) {
SwappyTable();
}
double x, y;
glfwGetCursorPos(Window, &x, &y);
touch[1] = touch[0]; // Cycle touch pos
touch[0] = fvec2(x, y);
}
} // namespace PD

View File

@@ -0,0 +1,67 @@
#pragma once
#ifdef __3DS__
#include <3ds.h>
#endif
#include <limits>
#include <memory>
#include <stdexcept>
// Custom C++ Allocator class to interface with libctru linear heap memory
// based on this guide:
// https://johnfarrier.com/custom-allocators-in-c-high-performance-memory-management/
namespace PD {
template <typename T>
class LinearAllocator {
public:
using value_type = T;
LinearAllocator() noexcept = default;
template <typename U>
constexpr LinearAllocator(const LinearAllocator<U>&) noexcept {}
T* allocate(std::size_t n) {
if (n > max_size()) {
throw std::runtime_error("[PD] LinearAllocator: Bad alloc!");
}
#ifdef __3DS__
return static_cast<T*>(linearAlloc(n * sizeof(T)));
#else
return static_cast<T*>(malloc(n * sizeof(T)));
#endif
}
#ifdef __3DS__
void deallocate(T* p, std::size_t) noexcept { linearFree(p); }
#else
void deallocate(T* p, std::size_t) noexcept { free(p); }
#endif
template <class U, class... Args>
void construct(U* p, Args&&... args) {
::new ((void*)p) U(std::forward<Args>(args)...);
}
template <class U>
void destroy(U* p) {
p->~U();
}
friend bool operator==(const LinearAllocator, const LinearAllocator) {
return true;
}
friend bool operator!=(const LinearAllocator, const LinearAllocator) {
return false;
}
#ifdef __3DS__
// Use linearSpace free as max_size to not allocate out of bounds
// or to b eable to see a crash report screen.
size_t max_size() const noexcept { return linearSpaceFree(); }
#else
size_t max_size() const noexcept {
return std::numeric_limits<size_t>::max();
}
#endif
};
} // namespace PD

View File

@@ -0,0 +1,39 @@
#pragma once
#include <pd/drivers/gfx.hpp>
#include <pd_system/ctr-linear-allocator.hpp>
namespace PD {
struct GfxCitro3DConfig {
// Vertex Allocator
template <typename T>
using VertexAlloc = LinearAllocator<T>;
// Index Allocator
template <typename T>
using IndexAlloc = LinearAllocator<T>;
static constexpr size_t NumVertices = 32768; // 8192*4
static constexpr size_t NumIndices = 49152; // 8192*6
};
class GfxCitro3D : public GfxDriverBase<GfxCitro3DConfig> {
public:
GfxCitro3D() : GfxDriverBase("Citro3D") {}
~GfxCitro3D() {}
void SysInit() override;
void SysDeinit() override;
void Submit(size_t count, size_t start) override;
void BindTexture(TextureID id) override;
void SysReset() override;
Li::Texture LoadTexture(
const std::vector<PD::u8>& pixels, int w, int h,
TextureFormat type = TextureFormat::RGBA32,
TextureFilter filter = TextureFilter::Linear) override;
void DeleteTexture(const Li::Texture& tex) override;
private:
struct Impl;
Impl* impl = nullptr;
};
} // namespace PD

View File

@@ -0,0 +1,40 @@
#pragma once
#include <pd/drivers/gfx.hpp>
namespace PD {
struct GfxDirectX9Config {
// Vertex Allocator
template <typename T>
using VertexAlloc = std::allocator<T>;
// Index Allocator
template <typename T>
using IndexAlloc = std::allocator<T>;
static constexpr size_t NumVertices = 32768; // 8192*4
static constexpr size_t NumIndices = 49152; // 8192*6
};
class GfxDirectX9 : public GfxDriverBase<GfxDirectX9Config> {
public:
GfxDirectX9(void* device = nullptr)
: GfxDriverBase("DirectX9"), pDevice(device) {}
~GfxDirectX9() {}
void SysInit() override;
void SysDeinit() override;
void Submit(size_t count, size_t start) override;
void BindTexture(TextureID id) override;
void SysReset() override;
Li::Texture LoadTexture(
const std::vector<PD::u8>& pixels, int w, int h,
TextureFormat type = TextureFormat::RGBA32,
TextureFilter filter = TextureFilter::Linear) override;
void DeleteTexture(const Li::Texture& tex) override;
private:
struct Impl;
Impl* impl = nullptr;
void* pDevice = nullptr;
};
} // namespace PD

View File

@@ -0,0 +1,45 @@
#pragma once
#include <pd/drivers/gfx.hpp>
namespace PD {
struct GfxOpenGL2Config {
// Vertex Allocator
template <typename T>
using VertexAlloc = std::allocator<T>;
// Index Allocator
template <typename T>
using IndexAlloc = std::allocator<T>;
static constexpr size_t NumVertices = 32768; // 8192*4
static constexpr size_t NumIndices = 49152; // 8192*6
};
class GfxOpenGL2 : public GfxDriverBase<GfxOpenGL2Config> {
public:
GfxOpenGL2() : GfxDriverBase("OpenGL2") {}
~GfxOpenGL2() {}
void SysInit() override;
void SysDeinit() override;
void Submit(size_t count, size_t start) override;
void BindTexture(TextureID id) override;
void SysReset() override;
Li::Texture LoadTexture(
const std::vector<PD::u8>& pixels, int w, int h,
TextureFormat type = TextureFormat::RGBA32,
TextureFilter filter = TextureFilter::Linear) override;
void DeleteTexture(const Li::Texture& tex) override;
private:
void pSetupShaderAttribs(u32 shader);
u32 pShader = 0;
u32 VBO = 0;
u32 IBO = 0;
int pLocTex = 0;
int pLocAlfa = 0;
int pLocProjection = 0;
static const char* pVertCode;
static const char* pFragCode;
};
} // namespace PD

View File

@@ -0,0 +1,43 @@
#pragma once
#include <pd/drivers/gfx.hpp>
namespace PD {
struct GfxOpenGL3Config {
// Vertex Allocator
template <typename T>
using VertexAlloc = std::allocator<T>;
// Index Allocator
template <typename T>
using IndexAlloc = std::allocator<T>;
static constexpr size_t NumVertices = 32768; // 8192*4
static constexpr size_t NumIndices = 49152; // 8192*6
};
class GfxOpenGL3 : public GfxDriverBase<GfxOpenGL3Config> {
public:
GfxOpenGL3() : GfxDriverBase("OpenGL3") {}
~GfxOpenGL3() {}
void SysInit() override;
void SysDeinit() override;
void Submit(size_t count, size_t start) override;
void BindTexture(TextureID id) override;
void SysReset() override;
Li::Texture LoadTexture(
const std::vector<PD::u8>& pixels, int w, int h,
TextureFormat type = TextureFormat::RGBA32,
TextureFilter filter = TextureFilter::Linear) override;
void DeleteTexture(const Li::Texture& tex) override;
private:
u32 pShader = 0;
u32 VBO = 0;
u32 IBO = 0;
u32 VAO = 0;
int pLocTex = 0;
int pLocAlfa = 0;
int pLocProjection = 0;
};
} // namespace PD

View File

@@ -0,0 +1,7 @@
#pragma once
#include <pd/common.hpp>
namespace PD {
u32 CreateShaderProgram(const char* vert, const char* frag);
}

View File

@@ -0,0 +1,17 @@
#pragma once
namespace PD {
/**
* Shader blobs
* Required for OpenGL3, and maybe later for vulkan
* Shaders can be found in /tools/pdsg/shaders
*/
namespace Shaders {
// clang-format off
const unsigned int VertexShader[] = { 0x7230203, 0x10000, 0x8000B, 0x2B, 0x0, 0x20011, 0x1, 0x6000B, 0x1, 0x4C534C47, 0x6474732E, 0x3035342E, 0x0, 0x3000E, 0x0, 0x1, 0xB000F, 0x0, 0x4, 0x6E69616D, 0x0, 0xD, 0x19, 0x24, 0x25, 0x27, 0x29, 0x30003, 0x2, 0x1CC, 0x40005, 0x4, 0x6E69616D, 0x0, 0x60005, 0xB, 0x505F6C67, 0x65567265, 0x78657472, 0x0, 0x60006, 0xB, 0x0, 0x505F6C67, 0x7469736F, 0x6E6F69, 0x70006, 0xB, 0x1, 0x505F6C67, 0x746E696F, 0x657A6953, 0x0, 0x70006, 0xB, 0x2, 0x435F6C67, 0x4470696C, 0x61747369, 0x65636E, 0x70006, 0xB, 0x3, 0x435F6C67, 0x446C6C75, 0x61747369, 0x65636E, 0x30005, 0xD, 0x0, 0x30005, 0x11, 0x4F4255, 0x60006, 0x11, 0x0, 0x6A6F7270, 0x69746365, 0x6E6F, 0x30005, 0x13, 0x6F6275, 0x30005, 0x19, 0x736F70, 0x30005, 0x24, 0x56556F, 0x30005, 0x25, 0x7675, 0x40005, 0x27, 0x6C6F436F, 0x726F, 0x40005, 0x29, 0x6F6C6F63, 0x72, 0x30047, 0xB, 0x2, 0x50048, 0xB, 0x0, 0xB, 0x0, 0x50048, 0xB, 0x1, 0xB, 0x1, 0x50048, 0xB, 0x2, 0xB, 0x3, 0x50048, 0xB, 0x3, 0xB, 0x4, 0x30047, 0x11, 0x2, 0x40048, 0x11, 0x0, 0x5, 0x50048, 0x11, 0x0, 0x7, 0x10, 0x50048, 0x11, 0x0, 0x23, 0x0, 0x40047, 0x13, 0x21, 0x0, 0x40047, 0x13, 0x22, 0x0, 0x40047, 0x19, 0x1E, 0x0, 0x40047, 0x24, 0x1E, 0x0, 0x40047, 0x25, 0x1E, 0x1, 0x40047, 0x27, 0x1E, 0x1, 0x40047, 0x29, 0x1E, 0x2, 0x20013, 0x2, 0x30021, 0x3, 0x2, 0x30016, 0x6, 0x20, 0x40017, 0x7, 0x6, 0x4, 0x40015, 0x8, 0x20, 0x0, 0x4002B, 0x8, 0x9, 0x1, 0x4001C, 0xA, 0x6, 0x9, 0x6001E, 0xB, 0x7, 0x6, 0xA, 0xA, 0x40020, 0xC, 0x3, 0xB, 0x4003B, 0xC, 0xD, 0x3, 0x40015, 0xE, 0x20, 0x1, 0x4002B, 0xE, 0xF, 0x0, 0x40018, 0x10, 0x7, 0x4, 0x3001E, 0x11, 0x10, 0x40020, 0x12, 0x2, 0x11, 0x4003B, 0x12, 0x13, 0x2, 0x40020, 0x14, 0x2, 0x10, 0x40017, 0x17, 0x6, 0x2, 0x40020, 0x18, 0x1, 0x17, 0x4003B, 0x18, 0x19, 0x1, 0x4002B, 0x6, 0x1B, 0x0, 0x4002B, 0x6, 0x1C, 0x3F800000, 0x40020, 0x21, 0x3, 0x7, 0x40020, 0x23, 0x3, 0x17, 0x4003B, 0x23, 0x24, 0x3, 0x4003B, 0x18, 0x25, 0x1, 0x4003B, 0x21, 0x27, 0x3, 0x40020, 0x28, 0x1, 0x7, 0x4003B, 0x28, 0x29, 0x1, 0x50036, 0x2, 0x4, 0x0, 0x3, 0x200F8, 0x5, 0x50041, 0x14, 0x15, 0x13, 0xF, 0x4003D, 0x10, 0x16, 0x15, 0x4003D, 0x17, 0x1A, 0x19, 0x50051, 0x6, 0x1D, 0x1A, 0x0, 0x50051, 0x6, 0x1E, 0x1A, 0x1, 0x70050, 0x7, 0x1F, 0x1D, 0x1E, 0x1B, 0x1C, 0x50091, 0x7, 0x20, 0x16, 0x1F, 0x50041, 0x21, 0x22, 0xD, 0xF, 0x3003E, 0x22, 0x20, 0x4003D, 0x17, 0x26, 0x25, 0x3003E, 0x24, 0x26, 0x4003D, 0x7, 0x2A, 0x29, 0x3003E, 0x27, 0x2A, 0x100FD, 0x10038, };
// clang-format on
// clang-format off
const unsigned int FragmentShader[] = { 0x7230203, 0x10000, 0x8000B, 0x39, 0x0, 0x20011, 0x1, 0x6000B, 0x1, 0x4C534C47, 0x6474732E, 0x3035342E, 0x0, 0x3000E, 0x0, 0x1, 0x8000F, 0x0, 0x4, 0x6E69616D, 0x0, 0x11, 0x22, 0x24, 0x30003, 0x2, 0x1CC, 0x40005, 0x4, 0x6E69616D, 0x0, 0x30005, 0x9, 0x6374, 0x30005, 0xD, 0x786574, 0x30005, 0x11, 0x56556F, 0x50005, 0x16, 0x68737550, 0x61746144, 0x0, 0x50006, 0x16, 0x0, 0x61666C61, 0x0, 0x40005, 0x18, 0x68737570, 0x0, 0x50005, 0x22, 0x67617246, 0x6F6C6F43, 0x72, 0x40005, 0x24, 0x6C6F436F, 0x726F, 0x40047, 0xD, 0x21, 0x0, 0x40047, 0xD, 0x22, 0x0, 0x40047, 0x11, 0x1E, 0x0, 0x30047, 0x16, 0x2, 0x50048, 0x16, 0x0, 0x23, 0x0, 0x40047, 0x24, 0x1E, 0x1, 0x20013, 0x2, 0x30021, 0x3, 0x2, 0x30016, 0x6, 0x20, 0x40017, 0x7, 0x6, 0x4, 0x40020, 0x8, 0x7, 0x7, 0x90019, 0xA, 0x6, 0x1, 0x0, 0x0, 0x0, 0x1, 0x0, 0x3001B, 0xB, 0xA, 0x40020, 0xC, 0x0, 0xB, 0x4003B, 0xC, 0xD, 0x0, 0x40017, 0xF, 0x6, 0x2, 0x40020, 0x10, 0x1, 0xF, 0x4003B, 0x10, 0x11, 0x1, 0x4002B, 0x6, 0x13, 0x0, 0x40015, 0x15, 0x20, 0x1, 0x3001E, 0x16, 0x15, 0x40020, 0x17, 0x9, 0x16, 0x4003B, 0x17, 0x18, 0x9, 0x4002B, 0x15, 0x19, 0x0, 0x40020, 0x1A, 0x9, 0x15, 0x20014, 0x1D, 0x40020, 0x21, 0x3, 0x7, 0x4003B, 0x21, 0x22, 0x3, 0x40020, 0x23, 0x1, 0x7, 0x4003B, 0x23, 0x24, 0x1, 0x40017, 0x25, 0x6, 0x3, 0x40015, 0x28, 0x20, 0x0, 0x4002B, 0x28, 0x29, 0x3, 0x40020, 0x2A, 0x7, 0x6, 0x40020, 0x2D, 0x1, 0x6, 0x50036, 0x2, 0x4, 0x0, 0x3, 0x200F8, 0x5, 0x4003B, 0x8, 0x9, 0x7, 0x4003D, 0xB, 0xE, 0xD, 0x4003D, 0xF, 0x12, 0x11, 0x70058, 0x7, 0x14, 0xE, 0x12, 0x2, 0x13, 0x3003E, 0x9, 0x14, 0x50041, 0x1A, 0x1B, 0x18, 0x19, 0x4003D, 0x15, 0x1C, 0x1B, 0x500AB, 0x1D, 0x1E, 0x1C, 0x19, 0x300F7, 0x20, 0x0, 0x400FA, 0x1E, 0x1F, 0x35, 0x200F8, 0x1F, 0x4003D, 0x7, 0x26, 0x24, 0x8004F, 0x25, 0x27, 0x26, 0x26, 0x0, 0x1, 0x2, 0x50041, 0x2A, 0x2B, 0x9, 0x29, 0x4003D, 0x6, 0x2C, 0x2B, 0x50041, 0x2D, 0x2E, 0x24, 0x29, 0x4003D, 0x6, 0x2F, 0x2E, 0x50085, 0x6, 0x30, 0x2C, 0x2F, 0x50051, 0x6, 0x31, 0x27, 0x0, 0x50051, 0x6, 0x32, 0x27, 0x1, 0x50051, 0x6, 0x33, 0x27, 0x2, 0x70050, 0x7, 0x34, 0x31, 0x32, 0x33, 0x30, 0x3003E, 0x22, 0x34, 0x200F9, 0x20, 0x200F8, 0x35, 0x4003D, 0x7, 0x36, 0x9, 0x4003D, 0x7, 0x37, 0x24, 0x50085, 0x7, 0x38, 0x36, 0x37, 0x3003E, 0x22, 0x38, 0x200F9, 0x20, 0x200F8, 0x20, 0x100FD, 0x10038, };
// clang-format on
} // namespace Shaders
} // namespace PD

View File

@@ -0,0 +1,6 @@
#pragma once
#include <pd_system/gfx_citro3d.hpp>
#include <pd_system/gfx_directx9.hpp>
#include <pd_system/gfx_opengl2.hpp>
#include <pd_system/gfx_opengl3.hpp>

View File

@@ -0,0 +1,254 @@
// Well yes, i finally try it
#include <pd/core/core.hpp>
#include <pd/lithium/formatters.hpp>
#include <pd_system/gfx_citro3d.hpp>
#if defined(PD_ENABLE_CITRO3D) && defined(__3DS__)
#include <3ds.h>
#include <citro3d.h>
#include <pd/drivers/drivers.hpp>
#include <pica.hpp>
namespace PD {
const char* LIShaderCTR = R"(
; LI7 Shader
; Constants
.constf myconst(0.0, 1.0, 0.00392156862745, 0.0)
.alias ones myconst.yyyy ; Vector full of ones
; Uniforms
.fvec projection[4]
; Outputs
.out out_position position
.out out_color color
.out out_uv texcoord0
; Inputs
.alias in_xy v0
.alias in_uvc v1
.alias in_col v2
.entry vmain
.proc vmain
mov r0.xy, in_xy.xy
mov r0.w, ones
dp4 out_position.x, projection[0], r0
dp4 out_position.y, projection[1], r0
dp4 out_position.z, projection[2], r0
dp4 out_position.w, projection[3], r0
mov out_uv, in_uvc.xy
mul r1, myconst.zzzz, in_col
mov out_color, r1
end
.end
)";
struct GfxCitro3D::Impl {
C3D_AttrInfo pAttr;
shaderProgram_s pShader;
DVLB_s* pCode;
int uLocProjection = 0;
C3D_Tex* CurrentTex = nullptr;
std::vector<u8> pShaderRaw;
GPU_TEXCOLOR TextureTranslateFormat(TextureFormat fmt) {
switch (fmt) {
case PD::TextureFormat::A8:
return GPU_A8;
case PD::TextureFormat::RGB24:
return GPU_RGB8;
case PD::TextureFormat::RGBA32:
return GPU_RGBA8;
default:
return GPU_RGBA8;
}
}
int TextureFormat2Bpp(TextureFormat fmt) {
switch (fmt) {
case PD::TextureFormat::A8:
return 1;
case PD::TextureFormat::RGB24:
return 3;
case PD::TextureFormat::RGBA32:
return 4;
default:
return 0;
}
}
void SetupPixelStage() {
shaderProgramUse(&pShader);
C3D_BindProgram(&pShader);
C3D_SetAttrInfo(&pAttr);
C3D_DepthTest(false, GPU_GREATER, GPU_WRITE_ALL);
if (!CurrentTex) return;
C3D_TexEnv* env = C3D_GetTexEnv(0);
C3D_TexEnvInit(env);
switch (CurrentTex->fmt) {
case GPU_A4:
case GPU_A8:
case GPU_L4:
case GPU_L8:
C3D_TexEnvSrc(env, C3D_Alpha, GPU_TEXTURE0);
C3D_TexEnvFunc(env, C3D_RGB, GPU_REPLACE);
C3D_TexEnvFunc(env, C3D_Alpha, GPU_MODULATE);
break;
case GPU_RGB565:
C3D_TexEnvSrc(env, C3D_Alpha, GPU_TEXTURE0);
C3D_TexEnvFunc(env, C3D_RGB, GPU_MODULATE);
C3D_TexEnvFunc(env, C3D_Alpha, GPU_REPLACE);
break;
default:
C3D_TexEnvSrc(env, C3D_Both, GPU_TEXTURE0);
C3D_TexEnvFunc(env, C3D_Both, GPU_MODULATE);
break;
}
}
};
void GfxCitro3D::SysInit() {
if (impl) return;
PDLOG("GfxCitro3D::SysInit();");
impl = new Impl();
impl->pShaderRaw = Pica::AssembleCode(LIShaderCTR);
impl->pCode = DVLB_ParseFile((uint32_t*)impl->pShaderRaw.data(),
impl->pShaderRaw.size());
shaderProgramInit(&impl->pShader);
shaderProgramSetVsh(&impl->pShader, &impl->pCode->DVLE[0]);
impl->uLocProjection = shaderInstanceGetUniformLocation(
impl->pShader.vertexShader, "projection");
AttrInfo_Init(&impl->pAttr);
AttrInfo_AddLoader(&impl->pAttr, 0, GPU_FLOAT, 2);
AttrInfo_AddLoader(&impl->pAttr, 1, GPU_FLOAT, 2);
AttrInfo_AddLoader(&impl->pAttr, 2, GPU_UNSIGNED_BYTE, 4);
}
void GfxCitro3D::SysDeinit() {
if (!impl) return;
shaderProgramFree(&impl->pShader);
DVLB_Free(impl->pCode);
delete impl;
impl = nullptr;
PDLOG("GfxCitro3D::SysDeinit()");
}
void GfxCitro3D::Submit(size_t count, size_t start) {
if (!impl) return;
BindTexture(CurrentTex);
impl->SetupPixelStage(); // needs to be called after
C3D_Mtx proj;
Mtx_OrthoTilt(&proj, 0.f, ViewPort.x, ViewPort.y, 0.f, 1.f, -1.f, false);
C3D_FVUnifMtx4x4(GPU_VERTEX_SHADER, impl->uLocProjection, &proj);
// C3D_FVUnifMtx4x4(GPU_VERTEX_SHADER, impl->uLocProjection,
// (C3D_Mtx*)&Projection);
auto buf = C3D_GetBufInfo();
BufInfo_Init(buf);
BufInfo_Add(buf, GetVertexBufPtr(0), sizeof(Li::Vertex), 3, 0x210);
C3D_DrawElements(GPU_TRIANGLES, count, C3D_UNSIGNED_SHORT,
GetIndexBufPtr(start));
impl->CurrentTex = nullptr;
}
void GfxCitro3D::BindTexture(TextureID id) {
if (!impl || !id) return;
impl->CurrentTex = (C3D_Tex*)id;
C3D_TexBind(0, (C3D_Tex*)id);
}
void GfxCitro3D::SysReset() {
if (!impl) return;
C3D_CullFace(GPU_CULL_NONE);
}
Li::Texture GfxCitro3D::LoadTexture(const std::vector<PD::u8>& pixels, int w,
int h, TextureFormat type,
TextureFilter filter) {
if (!impl || w > 1024 || h > 1024) return Li::Texture();
// Don't check here as check done before
PD::Li::Texture res;
int bpp = impl->TextureFormat2Bpp(type);
ivec2 tex_size(w, h);
// Pow2
if (!PD::Bits::IsSingleBit(w)) {
tex_size.x = PD::Bits::GetPow2((unsigned int)w);
}
if (!PD::Bits::IsSingleBit(h)) {
tex_size.y = PD::Bits::GetPow2((unsigned int)h);
}
res.SetSize(w, h);
res.SetUV(0.f, 1.f, ((float)w / (float)tex_size.x),
1.0 - ((float)h / (float)tex_size.y));
// Texture Setup
auto fltr = (filter == TextureFilter::Linear ? GPU_NEAREST : GPU_LINEAR);
auto tex_fmt = impl->TextureTranslateFormat(type);
auto tex = new C3D_Tex;
C3D_TexInit(tex, (u16)tex_size.x, (u16)tex_size.y, tex_fmt);
C3D_TexSetFilter(tex, fltr, fltr);
std::memset((PD::u8*)tex->data, 0x0, tex->size);
/// Probably Remove this if statement in future
/// This are the things confirmed as working
if (bpp == 3 || bpp == 4 || bpp == 1) {
for (int x = 0; x < w; x++) {
for (int y = 0; y < h; y++) {
int dst_pos = ((((y >> 3) * ((int)tex_size.x >> 3) + (x >> 3)) << 6) +
((x & 1) | ((y & 1) << 1) | ((x & 2) << 1) |
((y & 2) << 2) | ((x & 4) << 2) | ((y & 4) << 3))) *
bpp;
int src_pos = (y * w + x) * bpp;
/// Best idea i had
for (int i = 0; i < bpp; i++) {
((u8*)tex->data)[dst_pos + bpp - 1 - i] = pixels[src_pos + i];
}
}
}
C3D_TexFlush(tex);
}
tex->border = 0x00000000;
C3D_TexSetWrap(tex, GPU_REPEAT, GPU_REPEAT);
res.SetID((TextureID)tex);
RegisterTexture(res);
PDLOG("GfxCitro3D::LoadTexture -> {{ {} }}, [{}, {}]", res, type, filter);
return res;
}
void GfxCitro3D::DeleteTexture(const Li::Texture& tex) {
if (!tex.GetID()) return;
UnregisterTexture(tex);
C3D_Tex* t = reinterpret_cast<C3D_Tex*>(tex.GetID());
C3D_TexDelete(t);
delete t;
}
} // namespace PD
#else
namespace PD {
void GfxCitro3D::SysInit() {
PDLOG(
"GfxCitro3D::SysInit: Citro3D Driver is not included in "
"palladium-system");
}
void GfxCitro3D::SysDeinit() {}
void GfxCitro3D::Submit(size_t count, size_t start) {}
void GfxCitro3D::BindTexture(TextureID id) {}
void GfxCitro3D::SysReset() {}
Li::Texture GfxCitro3D::LoadTexture(const std::vector<PD::u8>& pixels, int w,
int h, TextureFormat type,
TextureFilter filter) {
return Li::Texture();
}
void GfxCitro3D::DeleteTexture(const Li::Texture& tex) {}
} // namespace PD
#endif

View File

@@ -0,0 +1,273 @@
// Well yes, i finally try it
#include <pd/lithium/formatters.hpp>
#include <pd_system/gfx_directx9.hpp>
// Sicher ist sicher
#if defined(PD_ENABLE_DIRECTX9) && defined(_WIN32)
#include <d3d9.h>
#include <d3dcompiler.h>
#include <pd/drivers/drivers.hpp>
namespace PD {
static const char* g_vsCode = R"(
float4x4 projection;
struct VS_IN {
float2 pos : POSITION0;
float2 uv : TEXCOORD0;
float4 col : COLOR0;
};
struct VS_OUT {
float4 pos : POSITION0;
float2 uv : TEXCOORD0;
float4 col : COLOR0;
};
VS_OUT main(VS_IN input) {
VS_OUT o;
o.pos = mul(projection, float4(input.pos, 0.0, 1.0));
o.uv = input.uv;
o.col = input.col;
return o;
}
)";
static const char* g_psCode = R"(
sampler2D tex : register(s0);
float alfa;
struct PS_IN {
float2 uv : TEXCOORD0;
float4 col : COLOR0;
};
float4 main(PS_IN input) : COLOR0 {
float4 tc = tex2D(tex, input.uv);
if (alfa > 0.5)
return float4(input.col.rgb, tc.a * input.col.a);
else
return tc * input.col;
}
)";
struct GfxDirectX9::Impl {
IDirect3DDevice9* Device = nullptr;
IDirect3DVertexBuffer9* VBO = nullptr;
IDirect3DIndexBuffer9* IBO = nullptr;
IDirect3DVertexDeclaration9* Decl = nullptr;
IDirect3DVertexShader9* VS = nullptr;
IDirect3DPixelShader9* FS = nullptr;
IDirect3DTexture9* CurrentTex = nullptr;
};
void GfxDirectX9::SysInit() {
if (impl) return;
PDLOG("GfxDirectX9::SysInit();");
impl = new Impl();
impl->Device = (IDirect3DDevice9*)pDevice;
if (impl->Device) {
D3DVERTEXELEMENT9 elements[]{
{0, 0, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_POSITION,
0},
{0, 8, D3DDECLTYPE_FLOAT2, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_TEXCOORD,
0},
{0, 16, D3DDECLTYPE_D3DCOLOR, D3DDECLMETHOD_DEFAULT, D3DDECLUSAGE_COLOR,
0},
D3DDECL_END()};
impl->Device->CreateVertexDeclaration(elements, &impl->Decl);
impl->Device->CreateVertexBuffer(
GfxDirectX9Config::NumVertices * sizeof(PD::Li::Vertex),
D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, 0, D3DPOOL_DEFAULT, &impl->VBO,
nullptr);
impl->Device->CreateIndexBuffer(GfxDirectX9Config::NumIndices * sizeof(u16),
D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY,
D3DFMT_INDEX16, D3DPOOL_DEFAULT, &impl->IBO,
nullptr);
ID3DBlob* vsBlob = nullptr;
ID3DBlob* errBlob = nullptr;
HRESULT hr = D3DCompile(g_vsCode, strlen(g_vsCode), nullptr, nullptr,
nullptr, "main", "vs_2_0", 0, 0, &vsBlob, &errBlob);
if (FAILED(hr)) {
PDLOG("Vertex Shader compile error: {}",
errBlob ? (char*)errBlob->GetBufferPointer() : "");
} else {
impl->Device->CreateVertexShader((DWORD*)vsBlob->GetBufferPointer(),
&impl->VS);
}
if (vsBlob) vsBlob->Release();
if (errBlob) errBlob->Release();
ID3DBlob* psBlob = nullptr;
errBlob = nullptr;
hr = D3DCompile(g_psCode, strlen(g_psCode), nullptr, nullptr, nullptr,
"main", "ps_2_0", 0, 0, &psBlob, &errBlob);
if (FAILED(hr)) {
PDLOG("Pixel Shader compile error: {}",
errBlob ? (char*)errBlob->GetBufferPointer() : "");
} else {
impl->Device->CreatePixelShader((DWORD*)psBlob->GetBufferPointer(),
&impl->FS);
}
if (psBlob) psBlob->Release();
if (errBlob) errBlob->Release();
} else {
PDLOG(
"GfxDirectX9::SysInit Error: pDevice is not set!\nYOu need to include "
"your D3D9 Device as "
"folowing:\nPD::Gfx::UseDriver<PD::GfxDirectX9>(D3D9Device);");
}
}
void GfxDirectX9::SysDeinit() {
if (!impl || !impl->Device) return;
if (impl->VBO) impl->VBO->Release();
if (impl->IBO) impl->IBO->Release();
if (impl->Decl) impl->Decl->Release();
if (impl->VS) impl->VS->Release();
if (impl->FS) impl->FS->Release();
delete impl;
impl = nullptr;
PDLOG("GfxDirectX9::SysDeinit()");
}
void GfxDirectX9::Submit(size_t count, size_t start) {
if (!impl || !impl->Device || !impl->VBO || !impl->IBO) return;
BindTexture(CurrentTex);
impl->Device->SetVertexShaderConstantF(
0, reinterpret_cast<const float*>(&Projection), 4);
void* vptr;
impl->VBO->Lock(0, 0, &vptr, D3DLOCK_DISCARD);
memcpy(vptr, GetVertexBufPtr(0), CurrentVertex * sizeof(PD::Li::Vertex));
impl->VBO->Unlock();
void* iptr;
impl->IBO->Lock(0, 0, &iptr, D3DLOCK_DISCARD);
memcpy(iptr, GetIndexBufPtr(0), CurrentIndex * sizeof(u16));
impl->IBO->Unlock();
impl->Device->SetStreamSource(0, impl->VBO, 0, sizeof(PD::Li::Vertex));
impl->Device->SetIndices(impl->IBO);
impl->Device->SetVertexDeclaration(impl->Decl);
impl->Device->SetVertexShader(impl->VS);
impl->Device->SetPixelShader(impl->FS);
impl->Device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, CurrentVertex,
start, count / 3);
}
void GfxDirectX9::BindTexture(TextureID id) {
if (!impl || !impl->Device) return;
impl->CurrentTex = (IDirect3DTexture9*)id;
impl->Device->SetTexture(0, impl->CurrentTex);
bool a8 = false;
if (impl->CurrentTex) {
D3DSURFACE_DESC desc;
impl->CurrentTex->GetLevelDesc(0, &desc);
a8 = (desc.Format == D3DFMT_A8);
}
float v = a8 ? 1.0f : 0.0f;
impl->Device->SetPixelShaderConstantF(0, &v, 1);
}
void GfxDirectX9::SysReset() {
if (!impl || !impl->Device) return;
impl->Device->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
impl->Device->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
impl->Device->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
}
Li::Texture GfxDirectX9::LoadTexture(const std::vector<PD::u8>& pixels, int w,
int h, TextureFormat type,
TextureFilter filter) {
if (!impl || !impl->Device) return Li::Texture();
IDirect3DTexture9* tex = nullptr;
D3DFORMAT fmt = D3DFMT_A8R8G8B8;
if (type == TextureFormat::RGB24)
fmt = D3DFMT_X8R8G8B8;
else if (type == TextureFormat::A8)
fmt = D3DFMT_A8;
HRESULT hr = impl->Device->CreateTexture(w, h, 1, 0, fmt, D3DPOOL_MANAGED,
&tex, nullptr);
if (FAILED(hr) || !tex) return Li::Texture();
D3DLOCKED_RECT rect;
tex->LockRect(0, &rect, nullptr, 0);
if (type == TextureFormat::RGB24) {
u8* dstRow = reinterpret_cast<u8*>(rect.pBits);
for (int y = 0; y < h; ++y) {
u32* dst = reinterpret_cast<u32*>(dstRow);
for (int x = 0; x < w; ++x) {
u8 r = pixels[(y * w + x) * 3 + 0];
u8 g = pixels[(y * w + x) * 3 + 1];
u8 b = pixels[(y * w + x) * 3 + 2];
dst[x] = (0xFF << 24) | (r << 16) | (g << 8) | b;
}
dstRow += rect.Pitch;
}
} else if (type == TextureFormat::RGBA32) {
u8* dstRow = reinterpret_cast<u8*>(rect.pBits);
for (int y = 0; y < h; ++y) {
u32* dst = reinterpret_cast<u32*>(dstRow);
for (int x = 0; x < w; ++x) {
u8 r = pixels[(y * w + x) * 4 + 0];
u8 g = pixels[(y * w + x) * 4 + 1];
u8 b = pixels[(y * w + x) * 4 + 2];
u8 a = pixels[(y * w + x) * 4 + 3];
dst[x] = (a << 24) | (r << 16) | (g << 8) | b;
}
dstRow += rect.Pitch;
}
} else if (type == TextureFormat::A8) {
u8* dstRow = reinterpret_cast<u8*>(rect.pBits);
for (int y = 0; y < h; ++y) {
memcpy(dstRow, &pixels[y * w], w);
dstRow += rect.Pitch;
}
}
tex->UnlockRect(0);
Li::Texture res;
res.SetID((TextureID)tex);
res.SetSize(w, h);
res.SetUV(0.f, 0.f, 1.f, 1.f);
RegisterTexture(res);
PDLOG("GfxDirectX9::LoadTexture -> {{ {} }}, [{}, {}]", res, type, filter);
return res;
}
void GfxDirectX9::DeleteTexture(const Li::Texture& tex) {
if (!tex.GetID()) return;
UnregisterTexture(tex);
IDirect3DTexture9* t = (IDirect3DTexture9*)tex.GetID();
t->Release();
}
} // namespace PD
#else
namespace PD {
void GfxDirectX9::SysInit() {
PDLOG(
"GfxDirectX9::SysInit: DirectX9 Driver is not included in "
"palladium-system");
}
void GfxDirectX9::SysDeinit() {}
void GfxDirectX9::Submit(size_t count, size_t start) {}
void GfxDirectX9::BindTexture(TextureID id) {}
void GfxDirectX9::SysReset() {}
Li::Texture GfxDirectX9::LoadTexture(const std::vector<PD::u8>& pixels, int w,
int h, TextureFormat type,
TextureFilter filter) {
return Li::Texture();
}
void GfxDirectX9::DeleteTexture(const Li::Texture& tex) {}
} // namespace PD
#endif

View File

@@ -0,0 +1,191 @@
#include <pd/lithium/formatters.hpp>
#include <pd_system/gfx_opengl2.hpp>
#if defined(PD_ENABLE_OPENGL2)
#include <glad/glad.h>
#include <pd/drivers/drivers.hpp>
#include <pd_system/gl-helper.hpp>
namespace PD {
const char* GfxOpenGL2::pVertCode = R"(
#version 120
attribute vec2 pos;
attribute vec2 uv;
attribute vec4 color;
varying vec2 oUV;
varying vec4 oColor;
// Probably forgot about this matrix and
// searched hours for why the rendering isn't working :/
uniform mat4 projection;
void main() {
gl_Position = projection*vec4(pos, 0.0, 1.0);
oUV = uv;
oColor = color;
}
)";
const char* GfxOpenGL2::pFragCode = R"(
#version 120
varying vec2 oUV;
varying vec4 oColor;
uniform sampler2D tex;
uniform bool alfa;
void main() {
vec4 tc = texture2D(tex, oUV);
if (alfa) {
gl_FragColor = vec4(oColor.rgb, tc.a * oColor.a);
} else {
gl_FragColor = tc * oColor;
}
}
)";
void GfxOpenGL2::pSetupShaderAttribs(u32 shader) {
GLint _pos = glGetAttribLocation(shader, "pos");
GLint _uv = glGetAttribLocation(shader, "uv");
GLint _color = glGetAttribLocation(shader, "color");
glVertexAttribPointer(_pos, 2, GL_FLOAT, GL_FALSE, sizeof(PD::Li::Vertex),
(void*)offsetof(PD::Li::Vertex, pos));
glEnableVertexAttribArray(_pos);
glVertexAttribPointer(_uv, 2, GL_FLOAT, GL_FALSE, sizeof(PD::Li::Vertex),
(void*)offsetof(PD::Li::Vertex, uv));
glEnableVertexAttribArray(_uv);
glVertexAttribPointer(_color, 4, GL_UNSIGNED_BYTE, GL_TRUE,
sizeof(PD::Li::Vertex),
(void*)offsetof(PD::Li::Vertex, color));
glEnableVertexAttribArray(_color);
}
void GfxOpenGL2::SysInit() {
pShader = CreateShaderProgram(pVertCode, pFragCode);
glUseProgram(pShader);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glGenBuffers(1, &IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
pSetupShaderAttribs(pShader);
pLocTex = glGetUniformLocation(pShader, "tex");
pLocAlfa = glGetUniformLocation(pShader, "alfa");
pLocProjection = glGetUniformLocation(pShader, "projection");
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
PDLOG(
"GfxOpenGL2::SysInit():\n pShader = {}\n pLocTex = {}\n pLocAlfa = "
"{}\n pLocProjection = {}\n VBO = {}\n IBO = {}",
pShader, pLocTex, pLocAlfa, pLocProjection, VBO, IBO);
}
void GfxOpenGL2::SysDeinit() {
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &IBO);
PDLOG("GfxOpenGL2::SysDeinit()");
}
void GfxOpenGL2::Submit(size_t count, size_t start) {
BindTexture(CurrentTex);
glUseProgram(pShader);
glUniformMatrix4fv(pLocProjection, 1, GL_FALSE, Projection.m.data());
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, CurrentVertex * sizeof(PD::Li::Vertex),
GetVertexBufPtr(0), GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, CurrentIndex * sizeof(PD::u16),
GetIndexBufPtr(0), GL_DYNAMIC_DRAW);
pSetupShaderAttribs(pShader);
GLint ibo = 0;
glGetIntegerv(GL_ELEMENT_ARRAY_BUFFER_BINDING, &ibo);
glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_SHORT,
reinterpret_cast<void*>(start * sizeof(u16)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
BindTexture(0);
}
void GfxOpenGL2::BindTexture(TextureID id) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, (GLuint)id);
glUniform1i(pLocTex, 0);
GLint fmt = 0;
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
glUniform1i(pLocAlfa, fmt == GL_ALPHA);
}
void GfxOpenGL2::SysReset() {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
Li::Texture GfxOpenGL2::LoadTexture(const std::vector<PD::u8>& pixels, int w,
int h, TextureFormat type,
TextureFilter filter) {
GLuint texID;
glGenTextures(1, &texID);
glBindTexture(GL_TEXTURE_2D, texID);
// Set base format (Always using RGBA as base)
GLenum fmt = GL_RGBA;
if (type == TextureFormat::RGB24) {
fmt = GL_RGB;
} else if (type == TextureFormat::A8) {
fmt = GL_ALPHA;
}
glTexImage2D(GL_TEXTURE_2D, 0, fmt, w, h, 0, fmt, GL_UNSIGNED_BYTE,
pixels.data());
if (filter == TextureFilter::Linear) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
} else if (filter == TextureFilter::Nearest) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
glBindTexture(GL_TEXTURE_2D, 0);
Li::Texture res;
res.SetID(texID);
res.SetSize(w, h);
res.SetUV(0.f, 0.f, 1.f, 1.f);
RegisterTexture(res);
PDLOG("GfxOpenGL2::LoadTexture -> {{ {} }}, [{}, {}]", res, type, filter);
return res;
}
void GfxOpenGL2::DeleteTexture(const Li::Texture& tex) {
UnregisterTexture(tex);
GLuint tex_ = tex.GetID();
glDeleteTextures(1, &tex_);
}
} // namespace PD
#else
namespace PD {
void GfxOpenGL2::SysInit() {
PDLOG(
"GfxOpenGL2::SysInit: OpenGL2 Driver is not included in "
"palladium-system");
}
void GfxOpenGL2::SysDeinit() {}
void GfxOpenGL2::Submit(size_t count, size_t start) {}
void GfxOpenGL2::BindTexture(TextureID id) {}
void GfxOpenGL2::SysReset() {}
Li::Texture GfxOpenGL2::LoadTexture(const std::vector<PD::u8>& pixels, int w,
int h, TextureFormat type,
TextureFilter filter) {
return Li::Texture();
}
void GfxOpenGL2::DeleteTexture(const Li::Texture& tex) {}
void GfxOpenGL2::pSetupShaderAttribs(u32 shader) {}
} // namespace PD
#endif

View File

@@ -0,0 +1,160 @@
#include <pd/lithium/formatters.hpp>
#include <pd_system/gfx_opengl3.hpp>
#if defined(PD_ENABLE_OPENGL3)
#include <glad/glad.h>
#include <pd/drivers/drivers.hpp>
#include <pd_system/gl-helper.hpp>
#include <pd_system/shaders.hpp>
#include <spirv-helper.hpp>
namespace PD {
void GfxOpenGL3::SysInit() {
std::string vcode = SpirvHelper::SPV2GLSL(
std::vector<unsigned int>(
Shaders::VertexShader,
Shaders::VertexShader +
(sizeof(Shaders::VertexShader) / sizeof(unsigned int))),
330, false);
std::string fcode = SpirvHelper::SPV2GLSL(
std::vector<unsigned int>(
Shaders::FragmentShader,
Shaders::FragmentShader +
(sizeof(Shaders::FragmentShader) / sizeof(unsigned int))),
330, false);
PDLOG("Vertex: \n{}", vcode);
PDLOG("Fragment: \n{}", fcode);
pShader = CreateShaderProgram(vcode.c_str(), fcode.c_str());
glUseProgram(pShader);
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(PD::Li::Vertex),
(void*)offsetof(PD::Li::Vertex, pos));
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(PD::Li::Vertex),
(void*)offsetof(PD::Li::Vertex, uv));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(PD::Li::Vertex),
(void*)offsetof(PD::Li::Vertex, color));
glGenBuffers(1, &IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
pLocTex = glGetUniformLocation(pShader, "tex");
pLocAlfa = glGetUniformLocation(pShader, "push.alfa");
pLocProjection = glGetUniformLocation(pShader, "ubo.projection");
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
PDLOG(
"GfxOpenGL3::SysInit():\n pShader = {}\n pLocTex = {}\n pLocAlfa = "
"{}\n pLocProjection = {}\n VBO = {}\n IBO = {}, VAO = {}",
pShader, pLocTex, pLocAlfa, pLocProjection, VBO, IBO, VAO);
}
void GfxOpenGL3::SysDeinit() {
glDeleteBuffers(1, &VBO);
glDeleteBuffers(1, &IBO);
glDeleteVertexArrays(1, &VAO);
PDLOG("GfxOpenGL3::SysDeinit()");
}
void GfxOpenGL3::Submit(size_t count, size_t start) {
BindTexture(CurrentTex);
glUseProgram(pShader);
glUniformMatrix4fv(pLocProjection, 1, GL_FALSE, Projection.m.data());
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, CurrentVertex * sizeof(PD::Li::Vertex),
GetVertexBufPtr(0), GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, CurrentIndex * sizeof(u16),
GetIndexBufPtr(0), GL_DYNAMIC_DRAW);
glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_SHORT,
reinterpret_cast<void*>(start * sizeof(u16)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
BindTexture(0);
}
void GfxOpenGL3::BindTexture(TextureID id) {
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, (GLuint)id);
glUniform1i(pLocTex, 0);
GLint fmt = 0;
glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &fmt);
glUniform1i(pLocAlfa, fmt == GL_ALPHA);
}
void GfxOpenGL3::SysReset() {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}
Li::Texture GfxOpenGL3::LoadTexture(const std::vector<PD::u8>& pixels, int w,
int h, TextureFormat type,
TextureFilter filter) {
GLuint texID;
glGenTextures(1, &texID);
glBindTexture(GL_TEXTURE_2D, texID);
// Set base format (Always using RGBA as base)
GLenum fmt = GL_RGBA;
if (type == TextureFormat::RGB24) {
fmt = GL_RGB;
} else if (type == TextureFormat::A8) {
fmt = GL_ALPHA;
}
glTexImage2D(GL_TEXTURE_2D, 0, fmt, w, h, 0, fmt, GL_UNSIGNED_BYTE,
pixels.data());
if (filter == TextureFilter::Linear) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
} else if (filter == TextureFilter::Nearest) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
glBindTexture(GL_TEXTURE_2D, 0);
Li::Texture res;
res.SetID(texID);
res.SetSize(w, h);
res.SetUV(0.f, 0.f, 1.f, 1.f);
RegisterTexture(res);
PDLOG("GfxOpenGL3::LoadTexture -> {{ {} }}, [{}, {}]", res, type, filter);
return res;
}
void GfxOpenGL3::DeleteTexture(const Li::Texture& tex) {
UnregisterTexture(tex);
GLuint tex_ = tex.GetID();
glDeleteTextures(1, &tex_);
}
} // namespace PD
#else
namespace PD {
void GfxOpenGL3::SysInit() {
PDLOG(
"GfxOpenGL3::SysInit: OpenGL3 Driver is not included in "
"palladium-system");
}
void GfxOpenGL3::SysDeinit() {}
void GfxOpenGL3::Submit(size_t count, size_t start) {}
void GfxOpenGL3::BindTexture(TextureID id) {}
void GfxOpenGL3::SysReset() {}
Li::Texture GfxOpenGL3::LoadTexture(const std::vector<PD::u8>& pixels, int w,
int h, TextureFormat type,
TextureFilter filter) {
return Li::Texture();
}
void GfxOpenGL3::DeleteTexture(const Li::Texture& tex) {}
} // namespace PD
#endif

View File

@@ -0,0 +1,48 @@
#if defined(PD_ENABLE_OPENGL2) || defined(PD_ENABLE_OPENGL3)
#include <glad/glad.h>
#include <iostream>
#include <pd_system/gl-helper.hpp>
namespace PD {
GLuint compileShader(const char* src, GLenum type) {
GLuint shader = glCreateShader(type);
glShaderSource(shader, 1, &src, nullptr);
glCompileShader(shader);
GLint success;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success) {
char infoLog[512];
glGetShaderInfoLog(shader, 512, nullptr, infoLog);
std::cerr << "Shader Compilation Error: " << infoLog << std::endl;
}
return shader;
}
u32 CreateShaderProgram(const char* vert, const char* frag) {
GLuint vertexShader = compileShader(vert, GL_VERTEX_SHADER);
GLuint fragmentShader = compileShader(frag, GL_FRAGMENT_SHADER);
GLuint shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
GLint success;
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
char infoLog[512];
glGetProgramInfoLog(shaderProgram, 512, nullptr, infoLog);
std::cerr << "Shader Program Linking Error: " << infoLog << std::endl;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
if (success) PDLOG("Shader [{}] compiled sucessfully", shaderProgram);
return shaderProgram;
}
} // namespace PD
#endif

34
cmake/palladium.cmake Executable file
View File

@@ -0,0 +1,34 @@
cmake_minimum_required(VERSION 3.22)
## Utilitys of Palladium Library
### RULES ###
# Force C++ 20
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
# Enable Compile Command Export
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
### GIT HELPER ###
function(pd_git_get_hash ret)
execute_process(
COMMAND git rev-parse --short HEAD
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
OUTPUT_VARIABLE _ret
OUTPUT_STRIP_TRAILING_WHITESPACE
)
set(${ret} "${_ret}" PARENT_SCOPE)
endfunction()
function(pd_git_get_branch ret)
execute_process(
COMMAND git rev-parse --abbrev-ref HEAD
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
OUTPUT_VARIABLE _ret
OUTPUT_STRIP_TRAILING_WHITESPACE
)
set(${ret} "${_ret}" PARENT_SCOPE)
endfunction()

View File

@@ -0,0 +1,6 @@
@PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/palladiumTargets.cmake")
if(NOT TARGET palladium::pd-desktop AND PALLADIUM_FIND_DESKTOP)
find_dependency(palladium::pd-desktop OPTIONAL)
endif()

View File

@@ -1,16 +0,0 @@
window.MathJax = {
tex: {
inlineMath: [["\\(", "\\)"]],
displayMath: [["\\[", "\\]"]],
processEscapes: true,
processEnvironments: true
},
options: {
ignoreHtmlClass: ".*|",
processHtmlClass: "arithmatex"
}
};
document$.subscribe(() => {
MathJax.typesetPromise()
})

View File

@@ -1,6 +0,0 @@
document$.subscribe(function() {
var tables = document.querySelectorAll("article table:not([class])")
tables.forEach(function(table) {
new Tablesort(table)
})
})

View File

@@ -1,22 +0,0 @@
<div class="md-copyright">
{% if config.copyright %}
<div class="md-copyright__highlight">
{{ config.copyright }}
</div>
{% endif %}
{% if not config.extra.generator == false %}
&copy; 2024 -
<script>document.write(new Date().getFullYear());</script>
<a href="https://github.com/tobid7">
tobid7
</a>
- Kassel, Germany | Made with
<a href="https://doxide.org" target="_blank" rel="noopener">
Doxide
</a>
and
<a href="https://squidfunk.github.io/mkdocs-material/" target="_blank" rel="noopener">
Material for MkDocs
</a>
{% endif %}
</div>

View File

@@ -1,58 +0,0 @@
:root {
--md-admonition-icon--variable: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20.41 3c1.39 2.71 1.94 5.84 1.59 9-.2 3.16-1.3 6.29-3.17 9l-1.53-1c1.61-2.43 2.55-5.2 2.7-8 .34-2.8-.11-5.57-1.3-8l1.71-1M5.17 3 6.7 4C5.09 6.43 4.15 9.2 4 12c-.34 2.8.12 5.57 1.3 8l-1.69 1c-1.4-2.71-1.96-5.83-1.61-9 .2-3.16 1.3-6.29 3.17-9m6.91 7.68 2.32-3.23h2.53l-3.78 5 2.2 4.92h-2.26L11.71 14l-2.43 3.33H6.76l3.9-5.12-2.13-4.76h2.27l1.28 3.23Z"/></svg>');
--md-admonition-icon--function: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.6 5.29c-1.1-.1-2.07.71-2.17 1.82L13.18 10H16v2h-3l-.44 5.07a3.986 3.986 0 0 1-4.33 3.63 4.007 4.007 0 0 1-3.06-1.87l1.5-1.5c.24.74.9 1.31 1.73 1.38 1.1.1 2.07-.71 2.17-1.82L11 12H8v-2h3.17l.27-3.07c.19-2.2 2.13-3.83 4.33-3.63 1.31.11 2.41.84 3.06 1.87l-1.5 1.5c-.24-.74-.9-1.31-1.73-1.38Z"/></svg>');
--md-admonition-icon--typedef: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M 13.43 7.11 L 13.18 10 H 17 V 12 H 13 L 12.56 17.07 A 1 1 0 0 0 15.287 17.261 L 17.028 17.48 A 1 1 0 0 1 10.57 16.89 L 11 12 H 8 V 10 H 11.17 L 11.44 6.93 Z"/></svg>');
--md-admonition-icon--concept: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M3.75 3.5a.25.25 0 0 0-.25.25v2.062a.75.75 0 1 1-1.5 0V3.75C2 2.783 2.783 2 3.75 2h2.062a.75.75 0 1 1 0 1.5Zm13.688-.75a.75.75 0 0 1 .75-.75h2.062c.966 0 1.75.783 1.75 1.75v2.062a.75.75 0 1 1-1.5 0V3.75a.25.25 0 0 0-.25-.25h-2.062a.75.75 0 0 1-.75-.75ZM2.75 17.438a.75.75 0 0 1 .75.75v2.062c0 .138.112.25.25.25h2.062a.75.75 0 1 1 0 1.5H3.75A1.75 1.75 0 0 1 2 20.25v-2.062a.75.75 0 0 1 .75-.75Zm18.5 0a.75.75 0 0 1 .75.75v2.062A1.75 1.75 0 0 1 20.25 22h-2.062a.75.75 0 1 1 0-1.5h2.062a.25.25 0 0 0 .25-.25v-2.062a.75.75 0 0 1 .75-.75Zm-18.5-8.25a.75.75 0 0 1 .75.75v4.124a.75.75 0 1 1-1.5 0V9.938a.75.75 0 0 1 .75-.75ZM9.188 2.75a.75.75 0 0 1 .75-.75h4.124a.75.75 0 1 1 0 1.5H9.938a.75.75 0 0 1-.75-.75Zm0 18.5a.75.75 0 0 1 .75-.75h4.124a.75.75 0 1 1 0 1.5H9.938a.75.75 0 0 1-.75-.75ZM21.25 9.188a.75.75 0 0 1 .75.75v4.124a.75.75 0 1 1-1.5 0V9.938a.75.75 0 0 1 .75-.75ZM3.75 8.25a.75.75 0 0 1 .75-.75h2a.75.75 0 0 1 0 1.5h-2a.75.75 0 0 1-.75-.75Zm5.5 0A.75.75 0 0 1 10 7.5h2A.75.75 0 0 1 12 9h-2a.75.75 0 0 1-.75-.75Zm-1-4.5A.75.75 0 0 1 9 4.5v2a.75.75 0 0 1-1.5 0v-2a.75.75 0 0 1 .75-.75Zm0 5.5A.75.75 0 0 1 9 10v2a.75.75 0 0 1-1.5 0v-2a.75.75 0 0 1 .75-.75Zm0 4.75a.75.75 0 0 1 .75.75v4a.75.75 0 0 1-1.5 0v-4a.75.75 0 0 1 .75-.75ZM14 8.25a.75.75 0 0 1 .75-.75h4a.75.75 0 0 1 0 1.5h-4a.75.75 0 0 1-.75-.75Z"/></svg>');
--md-admonition-icon--macro: url('data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="m5.41 21 .71-4h-4l.35-2h4l1.06-6h-4l.35-2h4l.71-4h2l-.71 4h6l.71-4h2l-.71 4h4l-.35 2h-4l-1.06 6h4l-.35 2h-4l-.71 4h-2l.71-4h-6l-.71 4h-2M9.53 9l-1.06 6h6l1.06-6h-6Z"/></svg>');
}
.md-typeset .admonition.variable, .md-typeset details.variable,
.md-typeset .admonition.function, .md-typeset details.function,
.md-typeset .admonition.typedef, .md-typeset details.typedef,
.md-typeset .admonition.concept, .md-typeset details.concept,
.md-typeset .admonition.macro, .md-typeset details.macro {
border-color: var(--md-default-fg-color--lighter);
}
.md-typeset .variable > .admonition-title, .md-typeset .variable > summary,
.md-typeset .function > .admonition-title, .md-typeset .function > summary,
.md-typeset .typedef > .admonition-title, .md-typeset .typedef > summary,
.md-typeset .concept > .admonition-title, .md-typeset .concept > summary,
.md-typeset .macro > .admonition-title, .md-typeset .macro > summary {
background-color: var(--md-default-bg-color);
}
.md-typeset .variable > .admonition-title::before,
.md-typeset .variable > summary::before {
background-color: var(--md-default-fg-color--light);
-webkit-mask-image: var(--md-admonition-icon--variable);
mask-image: var(--md-admonition-icon--variable);
}
.md-typeset .function > .admonition-title::before,
.md-typeset .function > summary::before {
background-color: var(--md-default-fg-color--light);
-webkit-mask-image: var(--md-admonition-icon--function);
mask-image: var(--md-admonition-icon--function);
}
.md-typeset .typedef > .admonition-title::before,
.md-typeset .typedef > summary::before {
background-color: var(--md-default-fg-color--light);
-webkit-mask-image: var(--md-admonition-icon--typedef);
mask-image: var(--md-admonition-icon--typedef);
}
.md-typeset .concept > .admonition-title::before,
.md-typeset .concept > summary::before {
background-color: var(--md-default-fg-color--light);
-webkit-mask-image: var(--md-admonition-icon--concept);
mask-image: var(--md-admonition-icon--concept);
}
.md-typeset .macro > .admonition-title::before,
.md-typeset .macro > summary::before {
background-color: var(--md-default-fg-color--light);
-webkit-mask-image: var(--md-admonition-icon--macro);
mask-image: var(--md-admonition-icon--macro);
}

View File

@@ -1,15 +0,0 @@
title: Palladium
description:
files:
- "include/*.hpp"
- "include/pd/app/*.hpp"
- "include/pd/core/*.hpp"
- "include/pd/drivers/*.hpp"
- "include/pd/image/*.hpp"
- "include/pd/lib3ds/*.hpp"
- "include/pd/lithium/*.hpp"
- "include/pd/net/*.hpp"
- "include/pd/overlays/*.hpp"
- "include/pd/sound/*.hpp"
- "include/pd/ui7/*.hpp"
- "include/pd/ui7/container/*.hpp"

15
include/pd/core/sl/sl.hpp → include/palladium Normal file → Executable file
View File

@@ -2,8 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -22,12 +21,8 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
*/
#include <pd/core/sl/allocator.hpp>
#include <pd/core/sl/hashmap.hpp>
#include <pd/core/sl/list.hpp>
#include <pd/core/sl/pair.hpp>
#include <pd/core/sl/stack.hpp>
#include <pd/core/sl/tools.hpp>
#include <pd/core/sl/vector.hpp>
#include <pd/core/core.hpp>
#include <pd/drivers/drivers.hpp>
#include <pd/lithium/lithium.hpp>

View File

@@ -1,51 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
// Core
#include <pd/core/core.hpp>
// Image
#include <pd/image/image.hpp>
#include <pd/image/img_blur.hpp>
#include <pd/image/img_convert.hpp>
#include <pd/ui7/ui7.hpp>
// Net
#include <pd/net/backend.hpp>
#include <pd/net/socket.hpp>
/// Setup these as non Namespaced access by default
#ifndef PD_MATH_NAMESPACED
using fvec2 = PD::fvec2;
using fvec3 = PD::fvec3;
using fvec4 = PD::fvec4;
using dvec2 = PD::dvec2;
using dvec3 = PD::dvec3;
using dvec4 = PD::dvec4;
using ivec2 = PD::ivec2;
using ivec3 = PD::ivec3;
using ivec4 = PD::ivec4;
#endif
// namespace Palladium = PD;

View File

@@ -2,7 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -23,28 +23,41 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <GLFW/glfw3.h>
#include <pd/core/hid_driver.hpp>
#include <pd_p_bknd_api.hpp>
#include <array>
#include <chrono>
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <exception>
#include <format>
#include <fstream>
#include <numbers>
#include <pd/pd_p_api.hpp>
#include <string>
#include <unordered_map>
#include <vector>
namespace PD {
class PD_BKND_DESKTOP_API HidGLFW : public Hid {
public:
/**
* Constructor to setup Key binds
*/
HidGLFW(GLFWwindow* win);
~HidGLFW() = default;
PD_SMART_CTOR(HidGLFW)
/**
* Overrideing the Update Function for Input Checking etc
*/
void Update() override;
private:
GLFWwindow* Window;
int PrevState;
};
[[noreturn]] inline void Throw(const std::string& msg) {
throw std::runtime_error(msg);
}
using u8 = unsigned char;
using u16 = unsigned short;
using u32 = unsigned int;
using u64 = unsigned long long;
using ptr = uintptr_t;
PD_API void Log(const std::string& txt);
template <typename... Args>
void Log(std::format_string<Args...> fmt, Args&&... args) {
std::string msg = std::format(fmt, std::forward<Args>(args)...);
Log(msg);
}
} // namespace PD
#ifdef PD_DEBUG
#define PDLOG(fmt, ...) \
PD::Log("[{}:{}]: " fmt, __FILE__, __LINE__, ##__VA_ARGS__)
#else
#define PDLOG(fmt, ...)
#endif

View File

@@ -2,8 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -24,24 +23,21 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
#include <pd/common.hpp>
namespace PD {
/**
* Binary Utillity Functions
*/
namespace BitUtil {
namespace Bits {
/**
* Check if a 32 Bit number only set a sigle bit to 1
* @param v 32 bit unsigned int
* @return true if its a single bit number
*/
PD_CORE_API bool IsSingleBit(u32 v);
PD_API bool IsSingleBit(u32 v);
/**
* Get the Next Power of two Number
* @param v Current Number
* @return Next Number thats a Pow of 2
*/
PD_CORE_API u32 GetPow2(u32 v);
} // namespace BitUtil
PD_API u32 GetPow2(u32 v);
} // namespace Bits
} // namespace PD

197
include/pd/core/color.hpp Normal file → Executable file
View File

@@ -2,8 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -24,45 +23,26 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
#include <pd/common.hpp>
#include <pd/core/strings.hpp>
namespace PD {
/**
* Color class
*
* - Supports hex input starting with a # and 6 or 8 digits
* - Supports rgb(a) 8Bit unsigned number input
* - Supports rgb(a) float input from 0.0 to 1.0
* - Supports 32Bit input color
* @note Safetey checks are disabled for maximum performance
*/
class PD_CORE_API Color {
private:
/** Red Value */
u8 m_r;
/** Green Value */
u8 m_g;
/** Blue Value */
u8 m_b;
/** Alpha Value */
u8 m_a;
class PD_API Color {
public:
/**
* Default Constructor (all variables are set to 0)
*/
// Color() : m_r(0), m_g(0), m_b(0), m_a(0) {}
constexpr Color() : m_r(0), m_g(0), m_b(0), m_a(0) {}
constexpr Color() : r(0), g(0), b(0), a(0) {}
constexpr ~Color() {}
/**
* Constructor for 32Bit Color Input
* @param color 32Bit Color value
*/
constexpr Color(u32 color) {
m_a = (color >> 24) & 0xff;
m_b = (color >> 16) & 0xff;
m_g = (color >> 8) & 0xff;
m_r = color & 0xff;
constexpr Color(u32 clr) {
a = (clr >> 24) & 0xff;
b = (clr >> 16) & 0xff;
g = (clr >> 8) & 0xff;
r = clr & 0xff;
}
/**
* Constructor for 8Bit Input
@@ -71,12 +51,7 @@ class PD_CORE_API Color {
* @param b Blue Value
* @param a Optional Alpha Value (Defaults to 255)
*/
constexpr Color(int r, int g, int b, int a = 255) {
m_r = r;
m_g = g;
m_b = b;
m_a = a;
}
constexpr Color(int r, int g, int b, int a = 255) : r(r), g(g), b(b), a(a) {}
/**
* Constructor for float Input
* @param r Red Value
@@ -85,28 +60,40 @@ class PD_CORE_API Color {
* @param a Optional Alpha Value (Defaults to 1.0f)
* @note There is no Check if the number is between 0.0 and 1.0
*/
constexpr Color(float r, float g, float b, float a = 1.f) {
m_r = static_cast<u8>(255.f * r);
m_g = static_cast<u8>(255.f * g);
m_b = static_cast<u8>(255.f * b);
m_a = static_cast<u8>(255.f * a);
}
constexpr Color(float r, float g, float b, float a = 1.f)
: r(static_cast<u8>(255.f * r)),
g(static_cast<u8>(255.f * g)),
b(static_cast<u8>(255.f * b)),
a(static_cast<u8>(255.f * a)) {}
/**
* Constructor for Hex Input
* Constructor for Hex Input (is abel to run at compile time xD)
* @param hex Hex String in `#ffffff` or `#ffffffff` format
*/
Color(const std::string& hex) { Hex(hex); }
/**
* Unused Deconstructor
*/
// ~Color() {}
constexpr Color(const std::string_view& hex) { Hex(hex); }
/**
* Create Color Object by Hex String
* Create Color Object by Hex String (at compile time btw)
* @param hex Hex String in `#ffffff` or `#ffffffff` format
* @return Color class itself
*/
Color& Hex(const std::string& hex);
constexpr Color& Hex(const std::string_view& hex) {
if (!(hex.length() == 7 || hex.length() == 9)) {
PD::Throw("[PD] Color: hex string is not rgb or rgba!");
}
r = PD::Strings::HexChar2Int(hex[1]) * 16 +
PD::Strings::HexChar2Int(hex[2]);
g = PD::Strings::HexChar2Int(hex[3]) * 16 +
PD::Strings::HexChar2Int(hex[4]);
b = PD::Strings::HexChar2Int(hex[5]) * 16 +
PD::Strings::HexChar2Int(hex[6]);
if (hex.length() == 9) {
a = PD::Strings::HexChar2Int(hex[7]) * 16 +
PD::Strings::HexChar2Int(hex[8]);
} else {
a = 255;
}
return *this;
}
/**
* Convert this Color Object to Hex string
* @param rgba [default false] sets if 8 or 6 digit color should be returned
@@ -114,118 +101,54 @@ class PD_CORE_API Color {
*/
std::string Hex(bool rgba = false) const;
/**
* Setter for Red
* @param v value
* @return Color class reference
*/
Color& r(u8 v) {
m_r = v;
return *this;
}
/**
* Getter for Red
* @return Red Value
*/
u8 r() const { return m_r; }
/**
* Setter for Green
* @param v value
* @return Color class reference
*/
Color& g(u8 v) {
m_g = v;
return *this;
}
/**
* Getter for Green
* @return Green Value
*/
u8 g() const { return m_g; }
/**
* Setter for Blue
* @param v value
* @return Color class reference
*/
Color& b(u8 v) {
m_b = v;
return *this;
}
/**
* Getter for Blue
* @return Blue Value
*/
u8 b() const { return m_b; }
/**
* Setter for Alpha
* @param v value
* @return Color class reference
*/
Color& a(u8 v) {
m_a = v;
return *this;
}
/**
* Getter for Alpha
* @return Alpha Value
*/
u8 a() const { return m_a; }
/**
* Fade from Current to another Color
* @param color Color to fade to
* @param p Amount (supports -1.0 to 1.0 for use of sine)
* @return Class Reference
*/
Color& Fade(const Color& color, float p) {
m_a = static_cast<u8>((color.a() - m_a) * ((p + 1.f) / 2));
m_b = static_cast<u8>((color.b() - m_b) * ((p + 1.f) / 2));
m_g = static_cast<u8>((color.g() - m_g) * ((p + 1.f) / 2));
m_r = static_cast<u8>((color.r() - m_r) * ((p + 1.f) / 2));
constexpr Color& Fade(const Color& color, float p) {
a = static_cast<u8>((color.a - a) * ((p + 1.f) / 2));
b = static_cast<u8>((color.b - b) * ((p + 1.f) / 2));
g = static_cast<u8>((color.g - g) * ((p + 1.f) / 2));
r = static_cast<u8>((color.r - r) * ((p + 1.f) / 2));
return *this;
}
/**
* Get 32Bit Color Value
* @return 32Bit Color Value
* @return 32Bit Color Value (ABGR iirc)
*/
u32 Get() const { return (m_a << 24) | (m_b << 16) | (m_g << 8) | m_r; }
constexpr u32 Get() const { return (a << 24) | (b << 16) | (g << 8) | r; }
/**
* Get The Luminance of the Color
* @return luminance (from 0.0 to 1.0)
*/
float Luminance() const {
constexpr float Luminance() const {
// For Reference https://en.wikipedia.org/wiki/HSL_and_HSV#Lightness
return (0.3 * (m_r / 255.f) + 0.59 * (m_g / 255.f) + 0.11 * (m_b / 255.f));
return (0.3 * (r / 255.f) + 0.59 * (g / 255.f) + 0.11 * (b / 255.f));
}
/**
* Check if the Color is Light or Dark
* @return true if light
*/
bool IsLight() const { return (Luminance() >= 0.5); }
constexpr bool IsLight() const { return (Luminance() >= 0.5); }
/**
* Operator to cast Color to 32Bit Value
* @return 32Bit Color Value
*/
operator u32() const { return Get(); }
constexpr operator u32() const { return Get(); }
const float rf() const { return static_cast<float>(r) / 255.f; }
const float gf() const { return static_cast<float>(g) / 255.f; }
const float bf() const { return static_cast<float>(b) / 255.f; }
const float af() const { return static_cast<float>(a) / 255.f; }
/** Public Access Data section */
u8 r;
u8 g;
u8 b;
u8 a;
};
namespace Colors {
constexpr Color White = Color(1.f, 1.f, 1.f, 1.f);
constexpr Color Black = Color(0.f, 0.f, 0.f, 1.f);
constexpr Color Red = Color(1.f, 0.f, 0.f, 1.f);
constexpr Color Green = Color(0.f, 1.f, 0.f, 1.f);
constexpr Color Blue = Color(0.f, 0.f, 1.f, 1.f);
constexpr Color Yellow = Color(1.f, 1.f, 0.f, 1.f);
constexpr Color Cyan = Color(0.f, 1.f, 1.f, 1.f);
constexpr Color Magenta = Color(1.f, 0.f, 1.f, 1.f);
constexpr Color Gray = Color(0.5f, 0.5f, 0.5f, 1.f);
constexpr Color LightGray = Color(0.75f, 0.75f, 0.75f, 1.f);
constexpr Color DarkGray = Color(0.25f, 0.25f, 0.25f, 1.f);
constexpr Color Orange = Color(1.f, 0.65f, 0.f, 1.f);
constexpr Color Pink = Color(1.f, 0.75f, 0.8f, 1.f);
constexpr Color Brown = Color(0.6f, 0.4f, 0.2f, 1.f);
constexpr Color Purple = Color(0.5f, 0.f, 0.5f, 1.f);
constexpr Color Teal = Color(0.f, 0.5f, 0.5f, 1.f);
constexpr Color Transparent = Color(0.f, 0.f, 0.f, 0.f);
} // namespace Colors
} // namespace PD

View File

@@ -1,131 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <chrono>
#include <cinttypes>
#include <cmath>
#include <filesystem> // Requires C++ 17 or later
#include <format> // Requires C++ 20 or later
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
// Platform API
#include <pd/core/pd_p_api.hpp>
// Legacy Smart Pointer
#define PD_SMART_CTOR(x) \
using Ref = std::shared_ptr<x>; \
template <typename... args> \
static Ref New(args&&... cargs) { \
return std::make_shared<x>(std::forward<args>(cargs)...); \
}
namespace PD {
/**
* SmartCtor (std::shared_ptr) Template class for Smart Pointers
*
* - Just add : public PD::SmartCtor<YourClass> to your class
* @tparam T Your Class
*/
template <typename T>
class SmartCtor {
public:
/** Reference alias for std::shared_ptr<Type> */
using Ref = std::shared_ptr<T>;
/**
* static Function to Create a New Reference
* @param args Additional Arguments (Depends on your classes Constructors)
* @return New Reference Object
*/
template <typename... Args>
static Ref New(Args&&... args) {
return std::make_shared<T>(std::forward<Args>(args)...);
}
};
/**
* Wrapper for SmartCtor<Type>::New(Args)
* @tparam T Class Type
* @param args Arguments
* @return Type Reference (SmartPointer)
*/
template <typename T, typename... Args>
SmartCtor<T>::Ref New(Args&&... args) {
return SmartCtor<T>::New(std::forward<Args>(args)...);
}
// Defines
/** alias for 64 Bit unsigned integer */
using u64 = unsigned long long;
/** alias for 32 Bit unsigned integer */
using u32 = unsigned int;
/** alias for 16 Bit unsigned integer */
using u16 = unsigned short;
/** alias for 8 Bit unsigned integer */
using u8 = unsigned char;
/**
* LinInfo Compile Information
*/
namespace LibInfo {
/**
* Get the Compiler Name and Version the lib got Compiled with
* @return Compiler Name / Version
*/
PD_CORE_API const std::string CompiledWith();
/**
* Get the C++ Version used to compile the lib
* @return C++ Version (__cplusplus)
*/
PD_CORE_API const std::string CxxVersion();
/**
* Get the Buildtime of the Library
* @return Build Time
*/
PD_CORE_API const std::string BuildTime();
/**
* Get the Library Version
* @return Library Version String
*/
PD_CORE_API const std::string Version();
/**
* Get the Git Commit the Lib got compiled in
* @return Git Commit 7digit short hash
*/
PD_CORE_API const std::string Commit();
/**
* Get the Git Branch which was active when compiling the lib
* @return Git Branch
*/
PD_CORE_API const std::string Branch();
} // namespace LibInfo
} // namespace PD

17
include/pd/core/core.hpp Normal file → Executable file
View File

@@ -2,8 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -22,18 +21,20 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
*/
#include <pd/core/bit_util.hpp>
#include <pd/core/bits.hpp>
#include <pd/core/color.hpp>
#include <pd/core/common.hpp>
#include <pd/core/hid_driver.hpp>
#include <pd/core/fnv.hpp>
#include <pd/core/formatters.hpp>
#include <pd/core/fquat.hpp>
#include <pd/core/hashid.hpp>
#include <pd/core/io.hpp>
#include <pd/core/mat.hpp>
#include <pd/core/sl/sl.hpp>
#include <pd/core/pool.hpp>
#include <pd/core/strings.hpp>
#include <pd/core/sys.hpp>
#include <pd/core/timer.hpp>
#include <pd/core/timetrace.hpp>
#include <pd/core/tween.hpp>
#include <pd/core/u128.hpp>
#include <pd/core/vec.hpp>

70
include/pd/core/fnv.hpp Normal file
View File

@@ -0,0 +1,70 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/common.hpp>
namespace PD {
/**
* FNV-1a 32Bit hasing function
* https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
*/
constexpr u32 FNV1A32(std::string_view str) {
u32 ret = 0x811c9dc5; // Offset basis
for (auto& it : str) {
ret ^= it;
ret *= 0x01000193; // Prime
}
return ret;
}
/**
* FNV-1a 64Bit hasing function
* https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
*/
constexpr u64 FNV1A64(std::string_view str) {
u64 ret = 0xcbf29ce484222325; // Offset basis
for (auto& it : str) {
ret ^= it;
ret *= 0x00000100000001b3; // Prime
}
return ret;
}
namespace Detail {
template <typename T>
struct FNV1A {};
template <>
struct FNV1A<u32> {
static constexpr u32 Hash(std::string_view str) { return FNV1A32(str); }
static constexpr u32 Hash(const std::string& str) { return FNV1A32(str); }
};
template <>
struct FNV1A<u64> {
static constexpr u64 Hash(std::string_view str) { return FNV1A64(str); }
static constexpr u64 Hash(const std::string& str) { return FNV1A64(str); }
};
} // namespace Detail
} // namespace PD

View File

@@ -0,0 +1,98 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/color.hpp>
template <>
struct std::formatter<PD::Color> : std::formatter<std::string> {
enum class ColorFmt {
Hex,
Rgbf,
Rgb,
Rgba,
Rgbaf,
};
ColorFmt mode = ColorFmt::Hex;
constexpr auto parse(std::format_parse_context& ctx) {
auto it = ctx.begin();
auto end = ctx.end();
if (it == end || *it == '}') return it;
if (check(it, end, 5, "rgbaf")) {
mode = ColorFmt::Rgbaf;
it += 5;
} else if (check(it, end, 4, "rgba")) {
mode = ColorFmt::Rgba;
it += 4;
} else if (check(it, end, 4, "rgbf")) {
mode = ColorFmt::Rgbf;
it += 4;
} else if (check(it, end, 3, "rgb")) {
mode = ColorFmt::Rgb;
it += 3;
} else if (check(it, end, 3, "hex")) {
mode = ColorFmt::Hex;
it += 3;
} else {
throw std::format_error("invalid format for PD::Color");
}
if (it == end || *it != '}')
throw std::format_error("invalid format for PD::Color");
return it;
}
template <typename FormatContext>
auto format(const PD::Color& value, FormatContext& ctx) const {
switch (mode) {
case ColorFmt::Hex:
return std::format_to(ctx.out(), "#{:02X}{:02X}{:02X}{:02X}", value.r,
value.g, value.b, value.a);
case ColorFmt::Rgb:
return std::format_to(ctx.out(), "{}, {}, {}", value.r, value.g,
value.b);
case ColorFmt::Rgba:
return std::format_to(ctx.out(), "{}, {}, {}, {}", value.r, value.g,
value.b, value.a);
case ColorFmt::Rgbf:
return std::format_to(ctx.out(), "{}, {}, {}", value.rf(), value.gf(),
value.bf());
case ColorFmt::Rgbaf:
return std::format_to(ctx.out(), "{}, {}, {}, {}", value.rf(),
value.gf(), value.bf(), value.af());
default:
return ctx.out();
}
}
constexpr bool check(std::format_parse_context::const_iterator it,
std::format_parse_context::const_iterator end,
size_t len, const char* what) {
return (end - it >= static_cast<std::ptrdiff_t>(len) &&
std::string_view(&*it, len) == what); // msvc things...
}
};

View File

@@ -2,8 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -22,30 +21,35 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
*/
#include <pd/core/common.hpp>
// This file is based on fvec4
#include <pd/common.hpp>
#include <pd/core/vec4.hpp>
namespace PD {
/**
* Custom Allocator for Custom Vec and probably other stuff in future
*/
template <typename T>
class Allocator {
public:
Allocator() = default;
~Allocator() = default;
class fquat : public fvec4 {
constexpr fquat() : fvec4(0.f, 0.f, 0.f, 1.f) {}
constexpr fquat(float x, float y, float z, float w) : fvec4(x, y, z, w) {}
constexpr fquat(const fvec4& v) : fvec4(v) {}
virtual T* Allocate(size_t n) { return new T[n]; }
virtual T* AllocateRaw(size_t n) {
return reinterpret_cast<T*>(::operator new(sizeof(T) * n));
static fquat Identity() { return fquat(0.f, 0.f, 0.f, 1.f); }
constexpr fquat Conjugate() const { return fquat(-x, -y, -z, w); }
fquat Inverse() const {
float len = SqLen();
if (len == 0.0f) {
return fquat();
}
virtual void DeallocateRaw(T* ptr) { operator delete(ptr); }
virtual void Deallocate(T* ptr) { delete[] ptr; }
template <typename... Args>
void Construct(T* ptr, Args&&... args) {
new (ptr) T(std::forward<Args>(args)...);
return Conjugate() / len;
}
fquat operator*(const fquat& v) const {
return fquat(w * v.x + x * v.w + y * v.z - z * v.y,
w * v.y - x * v.z + y * v.w + z * v.x,
w * v.z + x * v.y - y * v.x + z * v.w,
w * v.w - x * v.x - y * v.y - z * v.z);
}
void Destroy(T* ptr) { ptr->~T(); }
};
} // namespace PD

View File

@@ -0,0 +1,50 @@
#pragma once
#include <pd/core/fnv.hpp>
#include <pd/core/strings.hpp>
namespace PD {
template <typename T>
class HashID {
public:
using __Type = T;
constexpr HashID() {};
constexpr HashID(T id) { pID = id; }
HashID(const std::string& name) {
pID = Detail::FNV1A<T>::Hash(name);
#ifdef PD_HASHID_KEEP_STR
pName = name;
#endif
}
constexpr HashID(const char* name) {
pID = Detail::FNV1A<T>::Hash(std::string_view(name));
#ifdef PD_HASHID_KEEP_STR
pName = name;
#endif
}
~HashID() {}
constexpr T Get() { return pID; }
std::string GetName() const {
#ifdef PD_HASHID_KEEP_STR
return pName;
#else
return std::format("hash({:#08x})", pID);
#endif
}
operator T() const { return pID; }
// operator std::string() const { return GetName(); }
private:
T pID;
#ifdef PD_HASHID_KEEP_STR
str pName;
#endif
};
using HashID32 = HashID<u32>;
using HashID64 = HashID<u64>;
} // namespace PD

View File

@@ -1,175 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
#include <pd/core/vec.hpp>
namespace PD {
/** Input Driver Template class */
class PD_CORE_API Hid : public SmartCtor<Hid> {
public:
/** Key [Controller] */
enum Key : u32 {
No = 0, ///< No Key
A = 1 << 0, ///< A
B = 1 << 1, ///< B
X = 1 << 2, ///< X
Y = 1 << 3, ///< Y
Start = 1 << 4, ///< Start
Select = 1 << 5, ///< Select
L = 1 << 6, ///< L
R = 1 << 7, ///< R
DUp = 1 << 8, ///< Dpad Up
DDown = 1 << 9, ///< Dpad down
DLeft = 1 << 10, ///< Dpad left
DRight = 1 << 11, ///< Dpad right
CPUp = 1 << 12, ///< Cpad up
CPDown = 1 << 13, ///< cpad down
CPLeft = 1 << 14, ///< cpad left
CPRight = 1 << 15, ///< Cpad right
CSUp = 1 << 16, ///< Cstick up
CSDown = 1 << 17, ///< cstick down
CSLeft = 1 << 18, ///< cstick left
CSRight = 1 << 19, ///< cstick right
ZL = 1 << 20, ///< ZL
ZR = 1 << 21, ///< ZR
Touch = 1 << 22, ///< Touch
Up = DUp | CPUp, ///< DPad or CPad Up
Down = DDown | CPDown, ///< DPad or CPad Down
Left = DLeft | CPLeft, ///< DPad or CPad Left
Right = DRight | CPRight, ///< DPad or CPad Right
};
/** Event */
enum Event {
Event_Down, ///< Key Pressed
Event_Held, ///< Key Held
Event_Up, ///< Key released
};
Hid(const std::string& name = "NullBackend") : pName(name) {}
~Hid() = default;
/**
* Get TOuch Position
* @return touch pos
*/
fvec2 TouchPos() const { return touch[0]; }
/**
* Get Last Touch Position (from last frame)
* @return touch pos
*/
fvec2 TouchPosLast() const { return touch[1]; }
/**
* Check for a Button Event
* @param e Event Type
* @param keys Keys to check for
* @return if key(s) doing the requiested event
*/
bool IsEvent(Event e, Key keys);
/**
* Check for Key Press Event
* @param keys set of keys
* @return true if key is pressed
*/
bool IsDown(Key keys) const { return key_events[0].at(Event_Down) & keys; }
/**
* Check for Key Held Event
* @param keys set of keys
* @return true if key is held
*/
bool IsHeld(Key keys) const { return key_events[0].at(Event_Held) & keys; }
/**
* Check for Key Release Event
* @param keys set of keys
* @return true if key is released
*/
bool IsUp(Key keys) const { return key_events[0].at(Event_Up) & keys; }
/**
* Sett all keyevents to 0
*/
void Clear() {
for (int i = 0; i < 2; i++) {
key_events[i][Event_Down] = 0;
key_events[i][Event_Up] = 0;
key_events[i][Event_Held] = 0;
}
}
/**
* Lock input driver
* @param v lock or not lock
*/
void Lock(bool v) {
if (v != locked) {
SwappyTable();
}
locked = v;
}
/**
* Check if Driver is locked
* @return true if locked
*/
bool Locked() const { return locked; }
/**
* Lock Input Driver
*/
void Lock() {
if (!locked) {
SwappyTable();
}
locked = true;
}
/**
* Unlock Input Driver
*/
void Unlock() {
if (locked) {
SwappyTable();
}
locked = false;
}
/**
* Template Update Function for a device specific driver
*/
virtual void Update() {}
/** Backend Identification Name */
const std::string pName;
protected:
/** Key binds map */
std::unordered_map<u32, u32> binds;
/** Function to swap around the Table */
void SwappyTable();
/** Using 2 Touch positions for current and last frame */
fvec2 touch[2];
/** locked state */
bool locked = false;
/** Key event tables */
std::unordered_map<Event, u32> key_events[2];
};
} // namespace PD

34
include/pd/core/io.hpp Normal file → Executable file
View File

@@ -2,7 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -23,50 +23,40 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
#include <pd/common.hpp>
namespace PD {
/**
* Set of File Functions
*/
namespace IO {
enum RleFmt {
Default = 0,
_16 = 1 << 0,
_32 = 1 << 1,
_64 = 1 << 2,
};
/**
* Load a File into an 8Bit Memory Buffer
* @param path Path to the File
* @return 8Bit FileBuffer
*/
PD_CORE_API std::vector<u8> LoadFile2Mem(const std::string& path);
PD_API std::vector<u8> LoadFile2Mem(const std::string& path);
/**
* Load a File into a std::string
* @param path Path to the File
* @return std::string file content
*/
PD_API std::string LoadFile2Str(const std::string& path);
/**
* Hash a 8Bit Memory Buffer
* @param data 8Bit input Buffer
* @return 32Bit Hash
*/
PD_CORE_API u32 HashMemory(const std::vector<u8>& data);
PD_API u32 HashMemory(const std::vector<u8>& data);
/**
* Function to decrompress RLE buffer
* @param data Data buffer to decompress
*/
PD_CORE_API void DecompressRLE(std::vector<u8>& data);
/**
* Function to decrompress Extended RLE Buffer
* @param data Data buffer to decompress
*/
PD_CORE_API void DecompressRLE_Ex(std::vector<u8>& data);
PD_API void DecompressRLE(std::vector<u8>& data);
/**
* Function to compress data with RLE Algorithm
* @param data Data buf
*/
PD_CORE_API void CompressRLE(std::vector<u8>& data);
/**
* Extended RLE Compress function (slower cause searches best format)
* @param data Data buf
*/
PD_CORE_API void CompressRLE_Ex(std::vector<u8>& data);
PD_API void CompressRLE(std::vector<u8>& data);
} // namespace IO
} // namespace PD

132
include/pd/core/mat.hpp Normal file → Executable file
View File

@@ -2,8 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -24,18 +23,129 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
#include <pd/common.hpp>
#include <pd/core/vec3.hpp>
namespace PD {
class PD_CORE_API Mat4 {
public:
Mat4() { Zeros(); }
~Mat4() = default;
namespace Numbers {
constexpr float Tau = std::numbers::pi * 2.f;
}
constexpr float Radians(float v) { return v * (Numbers::Tau / 360.0f); }
/**
* Minimal Mtx4 Lib that precomputes
* basic stuff stuff at compiletime
*
* This Lib includes Patches for work with Citro3D as well
*
* @note That this is not a full Matrix Library
*/
void Zeros();
void Ortho(float left, float right, float bottom, float top, float near,
float far);
struct PD_API Mat4 {
std::array<float, 16> m;
constexpr Mat4() : m{} {}
constexpr static Mat4 Diagonal(float x, float y, float z, float w) {
Mat4 ret;
ret(0, 0) = x;
ret(1, 1) = y;
ret(2, 2) = z;
ret(3, 3) = w;
return ret;
}
constexpr static Mat4 Identity() { return Diagonal(1, 1, 1, 1); }
float m[16];
constexpr float* Ptr() { return m.data(); }
constexpr const float* Ptr() const { return m.data(); }
constexpr float& operator()(int row, int col) {
#ifdef __3DS__
// 3ds is full reverse order iirc
return m[row * 4 + (3 - col)];
#else
return m[col * 4 + row];
#endif
}
constexpr float operator()(int row, int col) const {
#ifdef __3DS__
// 3ds is full reverse order iirc
return m[row * 4 + (3 - col)];
#else
return m[col * 4 + row];
#endif
}
constexpr Mat4 operator*(const Mat4& v) const {
Mat4 ret;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
float t = 0.f;
for (int k = 0; k < 4; k++) {
t += (*this)(i, k) * v(k, j);
}
ret(i, j) = t;
}
}
return ret;
}
constexpr Mat4& operator*=(const Mat4& v) {
*this = *this * v;
return *this;
}
constexpr static Mat4 Translate(float x, float y, float z) {
Mat4 ret = Identity();
ret(0, 3) = x;
ret(1, 3) = y;
ret(2, 3) = z;
return ret;
}
constexpr static Mat4 Scale(float x, float y, float z) {
Mat4 ret;
ret(0, 0) = x;
ret(1, 1) = y;
ret(2, 2) = z;
ret(3, 3) = 1.f;
return ret;
}
constexpr Mat4 Transpose() const {
Mat4 ret;
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
ret(i, j) = (*this)(j, i);
}
}
return ret;
}
constexpr static Mat4 Ortho(float l, float r, float b, float t, float n,
float f) {
Mat4 ret;
#ifdef __3DS__ // Patch to rotate the Matrix correctly
ret(0, 1) = 2.f / (t - b);
ret(0, 3) = (b + t) / (b - t);
ret(1, 0) = 2.f / (l - r);
ret(1, 3) = (l + r) / (r - l);
ret(2, 2) = 1.f / (n - f);
ret(2, 3) = 0.5f * (n + f) / (n - f) - 0.5f;
#else
ret(0, 0) = 2.0f / (r - l);
ret(0, 3) = -(r + l) / (r - l);
ret(1, 1) = 2.0f / (t - b);
ret(1, 3) = -(t + b) / (t - b);
ret(2, 2) = -2.0f / (f - n);
ret(2, 3) = -(f + n) / (f - n);
#endif
ret(3, 3) = 1.f;
return ret;
}
static Mat4 Rotate(fvec3 axis, float a);
static Mat4 RotateX(float a);
static Mat4 RotateY(float a);
static Mat4 RotateZ(float a);
static Mat4 Perspective(float fov, float aspect, float n, float f);
static Mat4 LookAt(const fvec3& pos, const fvec3& center, const fvec3& up);
};
} // namespace PD

View File

@@ -1,50 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifdef _WIN32 // Windows (MSVC Tested)
#ifdef PD_CORE_BUILD_SHARED
#define PD_CORE_API __declspec(dllexport)
#else
#define PD_CORE_API __declspec(dllimport)
#endif
#elif defined(__APPLE__) // macOS (untested yet)
#ifdef PD_CORE_BUILD_SHARED
#define PD_CORE_API __attribute__((visibility("default")))
#else
#define PD_CORE_API
#endif
#elif defined(__linux__) // Linux (untested yet)
#ifdef PD_CORE_BUILD_SHARED
#define PD_CORE_API __attribute__((visibility("default")))
#else
#define PD_CORE_API
#endif
#elif defined(__3DS__) // 3ds Specific
// Only Static supported
#define PD_CORE_API
#else
#define PD_CORE_API
#endif

98
include/pd/core/pool.hpp Normal file
View File

@@ -0,0 +1,98 @@
#pragma once
#include <memory>
#include <pd/common.hpp>
namespace PD {
template <typename T, typename Alloc = std::allocator<T>>
class Pool {
public:
using value_type = T;
using iterator = T*;
using const_iterator = const T*;
Pool() = default;
~Pool() {
if (pData) {
pAlloc.deallocate(pData, pCap);
pData = nullptr;
}
}
static Pool* Create(size_t size) { return new Pool(size); }
void Init(size_t size) {
pPos = 0;
pCap = size;
pData = pAlloc.allocate(size);
for (size_t i = 0; i < pCap; i++) {
std::allocator_traits<Alloc>::construct(pAlloc, &pData[i]);
}
PDLOG("Pool::Init({})", size);
}
Pool(const Pool&) = delete;
Pool(Pool&&) = delete;
Pool& operator=(const Pool&) = delete;
Pool& operator=(Pool&&) = delete;
T* Allocate(size_t num = 1) {
ExpandIf(num);
T* ret = &pData[pPos];
pPos += num;
return ret;
}
void Push(const T& elem) {
T* e = Allocate(1);
*e = elem;
}
void ExpandIf(size_t req) {
if ((pPos + req) <= pCap) return;
size_t ncap = std::max(pCap * 2, pPos + req);
T* nu = pAlloc.allocate(ncap);
if (pData) {
for (size_t i = 0; i < pPos; i++) {
std::allocator_traits<Alloc>::construct(
pAlloc, &nu[i], std::move_if_noexcept(pData[i]));
}
pAlloc.deallocate(pData, pCap);
}
for (size_t i = pPos; i < ncap; i++) {
std::allocator_traits<Alloc>::construct(pAlloc, &nu[i]);
}
PDLOG("Pool::ExpandIf({}): {} -> {}", req, pCap, ncap);
pData = nu;
pCap = ncap;
}
void Reset() {
for (size_t i = 0; i < pCap; i++) {
std::allocator_traits<Alloc>::destroy(pAlloc, &pData[i]);
}
pPos = 0;
for (size_t i = 0; i < pCap; i++) {
std::allocator_traits<Alloc>::construct(pAlloc, &pData[i]);
}
}
size_t size() const { return pPos; }
size_t capacity() const { return pCap; }
T& at(size_t idx) { return pData[idx]; }
const T& at(size_t idx) const { return pData[idx]; }
iterator begin() { return pData; }
iterator end() { return pData + pPos; }
const_iterator begin() const { return pData; }
const_iterator end() const { return pData + pPos; }
T& operator[](size_t idx) { return at(idx); }
const T& operator[](size_t idx) const { return at(idx); }
private:
Pool(size_t size) : pCap(size), pPos(0) { pData = pAlloc.allocate(size); }
size_t pCap = 0;
size_t pPos = 0;
Alloc pAlloc;
T* pData = nullptr;
};
} // namespace PD

View File

@@ -1,71 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
#include <pd/core/sl/list.hpp>
#include <pd/core/sl/pair.hpp>
namespace PD {
template <typename K, typename V, size_t bucket_count = 10>
class HashMap {
public:
HashMap() {}
~HashMap() {}
void Insert(const K& k, const V& v) {
size_t idx = Hash(k);
auto& bukket = pBuckets[idx];
for (auto& it : bukket) {
if (it.First == k) {
it.Second = v;
return;
}
}
bukket.PushBack(Pair(k, v));
}
bool Contains(const K& k) const {
size_t idx = Hash(k);
auto& bukket = pBuckets[idx];
for (auto& it : bukket) {
if (it.First == k) {
return true;
}
}
return false;
}
void Clear() {
for (size_t i = 0; i < bucket_count; i++) {
pBuckets[i].Clear();
}
}
size_t Hash(const K& k) const { return std::hash<K>{}(k) % bucket_count; }
PD::List<PD::Pair<K, V>> pBuckets[bucket_count];
};
} // namespace PD

View File

@@ -1,210 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
namespace PD {
template <typename T>
class List {
public:
List() {}
~List() {}
struct Node {
Node(const T& v) : Data(v) {}
T Data;
Node* Prev = nullptr;
Node* Next = nullptr;
};
class Iterator {
public:
Iterator(Node* n) : pNode(n) {}
T& operator*() { return pNode->Data; }
Iterator& operator++() {
pNode = pNode->Next;
return *this;
}
bool operator!=(const Iterator& o) const { return pNode != o.pNode; }
Node* pNode = nullptr;
};
void PushFront(const T& val) {
Node* node = new Node(val);
// node->Data = val;
node->Prev = nullptr;
node->Next = pHead;
if (pHead) {
pHead->Prev = node;
}
pHead = node;
if (!pTail) {
pTail = node;
}
pSize++;
}
void PushBack(const T& val) {
Node* node = new Node(val);
// node->Data = val;
node->Prev = pTail;
node->Next = nullptr;
if (pTail) {
pTail->Next = node;
}
pTail = node;
if (!pHead) {
pHead = node;
}
pSize++;
}
void PopFront() {
if (!pHead) {
return;
}
Node* t = pHead;
pHead = pHead->Next;
if (pHead) {
pHead->Prev = nullptr;
} else {
pTail = nullptr;
}
delete t;
pSize--;
}
void PopBack() {
if (!pTail) {
return;
}
Node* t = pTail;
pTail = pTail->Prev;
if (pTail) {
pTail->Next = nullptr;
} else {
pHead = nullptr;
}
delete t;
pSize--;
}
void Clear() {
while (pHead) {
PopFront();
}
}
void Remove(const T& v) {
Node* s = pHead;
while (s) {
if (s->Data == v) {
if (s->Prev) {
s->Prev->Next = s->Next;
} else {
pHead = s->Next;
}
if (s->Next) {
s->Next->Prev = s->Prev;
} else {
pTail = s->Prev;
}
delete s;
pSize--;
return;
}
s = s->Next;
}
}
void Reverse() {
Node* cur = pHead;
while (cur) {
Node* temp = cur->Prev;
cur->Prev = cur->Next;
cur->Next = temp;
cur = cur->Prev;
}
Node* temp = pHead;
pHead = pTail;
pTail = temp;
}
T& Front() {
if (pHead) {
return pHead->Data;
}
// Need a List Empty Error Here (exceptions are disabled on 3ds)
exit(1);
}
const T& Front() const {
if (pHead) {
return pHead->Data;
}
// Need a List Empty Error Here (exceptions are disabled on 3ds)
exit(1);
}
T& Back() {
if (pTail) {
return pTail->Data;
}
// Need a List Empty Error Here (exceptions are disabled on 3ds)
exit(1);
}
const T& Back() const {
if (pTail) {
return pTail->Data;
}
// Need a List Empty Error Here (exceptions are disabled on 3ds)
exit(1);
}
size_t Size() const { return pSize; }
Iterator begin() { return Iterator(pHead); }
Iterator end() { return Iterator(nullptr); }
private:
Node* Find(const T& v) const {
Node* t = pHead;
while (t) {
if (t->Data == v) {
return t;
}
t = t->Next;
}
return nullptr;
}
Node* pHead = nullptr;
Node* pTail = nullptr;
size_t pSize = 0;
};
} // namespace PD

View File

@@ -1,41 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
namespace PD {
template <typename T1, typename T2>
class Pair {
public:
Pair() = default;
Pair(const T1& f, const T2& s) : First(f), Second(s) {}
Pair(T1&& f, T2&& s) : First(std::move(f)), Second(std::move(s)) {}
~Pair() = default;
T1 First;
T2 Second;
};
} // namespace PD

View File

@@ -1,70 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
#include <pd/core/sl/vector.hpp>
namespace PD {
/**
* Custom Stack class (caus std::stack ofsten lead to memory coruption)
*/
template <typename T, typename Alloc = Allocator<T>>
class Stack {
public:
Stack() = default;
explicit Stack(size_t cap) : pVec(cap) {}
void Push(const T& val) { pVec.Add(val); }
void Pop() {
if (pVec.Size() == 0) {
exit(1);
}
pVec.PopBack();
}
T& Top() {
if (pVec.Size() == 0) {
exit(1);
}
return pVec[pVec.Size() - 1];
}
const T& Top() const {
if (pVec.Size() == 0) {
exit(1);
}
return pVec[pVec.Size() - 1];
}
bool IsEmpty() const { return pVec.Size() == 0; }
size_t Size() const { return pVec.Size(); }
void Clear() { pVec.Clear(); }
private:
Vec<T, Alloc> pVec;
};
} // namespace PD

View File

@@ -1,165 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
#include <pd/core/sl/allocator.hpp>
namespace PD {
/**
* Open Access Vector class (Alternative to std::vector)
*/
template <typename T, typename Alloc = Allocator<T>>
class Vec {
public:
Vec() {
pData = pAllocator.Allocate(2);
pCap = 2;
Clear();
pPos = 0;
};
Vec(const size_t& Size) {
pData = pAllocator.Allocate(Size + 2);
pCap = Size + 2;
Clear();
pPos = Size;
}
Vec(const size_t& Size, const T& v) {
pData = pAllocator.Allocate(Size + 2);
pCap = Size + 2;
Clear();
pPos = Size;
std::fill_n(pData, Size, v);
}
Vec(const T* s, const T* e) {
pData = pAllocator.Allocate(2);
pCap = 2;
Clear();
pPos = 0;
Resize(e - s);
std::copy_n(s, e - s, pData);
}
Vec(const Vec& v) {
pCap = v.pCap;
pPos = v.pPos;
pData = pAllocator.Allocate(pCap);
for (size_t i = 0; i < pPos; i++) {
pData[i] = v.pData[i];
}
}
~Vec() { pAllocator.Deallocate(pData); }
void Add(const T& v) {
if (pPos >= pCap) {
Reserve(pCap * 2);
}
pData[pPos++] = v;
}
void PopBack() {
if (pPos == 0) return;
pPos--;
}
T Pop() {
if (pPos == 0) {
// Todo: LOG
exit(1);
}
return pData[pPos--];
}
T& At(const size_t& Idx) {
if (Idx >= pPos) {
// Log
exit(1);
}
return pData[Idx];
}
const T& At(const size_t& Idx) const {
if (Idx >= pPos) {
// Log
exit(1);
}
return pData[Idx];
}
T& operator[](const size_t& Idx) { return At(Idx); }
const T& operator[](const size_t& Idx) const { return At(Idx); }
void operator+=(T v) { Add(v); }
T* Begin() { return pData; }
const T* Begin() const { return pData; }
T* End() { return pData + pPos; }
const T* End() const { return pData + pPos; }
// Support: `for(auto& it : Vec)` //
T* begin() { return pData; }
const T* begin() const { return pData; }
T* end() { return pData + pPos; }
const T* end() const { return pData + pPos; }
T* Data() { return pData; }
T* Data() const { return pData; }
size_t Size() const { return pPos; }
size_t Capacity() const { return pCap; }
void Clear() {
// Avoid memset to support std::string for now
// probably revert this decision based if it lacks performance
// or make it a setting
std::fill(pData, pData + pCap, T());
pPos = 0;
}
void Reserve(const size_t& Size) {
if (Size <= pCap) return;
T* tmp = pAllocator.Allocate(Size);
std::fill(tmp, tmp + Size, T());
std::copy(pData, pData + pCap, tmp);
pAllocator.Deallocate(pData);
pData = tmp;
pCap = Size;
}
void Resize(size_t Size) {
if (Size < pPos) {
pPos = Size;
} else if (Size > pCap) {
Reserve(Size);
}
std::fill(pData + pPos, pData + Size, T());
pPos = Size;
}
// Allocator
Alloc pAllocator;
// Data Reference Pointer
T* pData;
// Capacity
size_t pCap;
// Current Position (Size)
size_t pPos;
};
} // namespace PD

View File

@@ -2,7 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -23,20 +23,27 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
#include <pd/common.hpp>
namespace PD {
/**
* Set of String Utillity Functions
*/
namespace Strings {
constexpr int HexChar2Int(char c) {
/** Imagine man hat ne lookup table dafür verwendet :/ */
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return 10 + (c - 'a');
if (c >= 'A' && c <= 'F') return 10 + (c - 'A');
return -1; // Error
}
/**
* Check if a String ends with a specific extension
* @param str Input string
* @param exts List of Extensions to check for
* @return true if one of the extensions is found in the String
*/
PD_CORE_API bool StringEndsWith(const std::string& str,
PD_API bool StringEndsWith(const std::string& str,
const std::vector<std::string>& exts);
/**
* Function to Create a wstring of a string
@@ -44,39 +51,39 @@ PD_CORE_API bool StringEndsWith(const std::string& str,
* @return Result wstring
* @note Returns Empty if it has an error
*/
PD_CORE_API std::wstring MakeWstring(const std::string& s);
PD_API std::wstring MakeWstring(const std::string& s);
/**
* Generate a Formatted String by an Nanoseconds Input
* @param nanos Nanoseconds Input
* @return Result String
*/
PD_CORE_API const std::string FormatNanos(unsigned long long nanos);
PD_API const std::string FormatNanos(unsigned long long nanos);
/**
* Generate a Formatted String by an Milliseconds Input
* @param millis Milliseconds Input
* @return Result String
*/
PD_CORE_API const std::string FormatMillis(unsigned long long millis);
PD_API const std::string FormatMillis(unsigned long long millis);
/**
* Create a formatted String by an input bytes value
* @param bytes value in bytes
* @result Formatted String for example `2.5MB`
*/
PD_CORE_API const std::string FormatBytes(unsigned long long bytes);
PD_API const std::string FormatBytes(unsigned long long bytes);
/**
* Extract the Filename out of a Path
* @param path Path to extract from
* @param saperators Path Split Chars
* @return extracted filename
*/
PD_CORE_API const std::string GetFileName(
const std::string& path, const std::string& saperators = "/\\");
PD_API const std::string GetFileName(const std::string& path,
const std::string& saperators = "/\\");
/**
* Remove Extension from a Path / Filename
* @param path Input Path
* @return Path without Extension
*/
PD_CORE_API const std::string PathRemoveExtension(const std::string& path);
PD_API const std::string PathRemoveExtension(const std::string& path);
/**
* Function to Convert a Type to a hex value
* @tparam T Type
@@ -85,39 +92,79 @@ PD_CORE_API const std::string PathRemoveExtension(const std::string& path);
*/
template <typename T>
inline const std::string ToHex(const T& v) {
std::stringstream s;
s << "0x" << std::setfill('0') << std::setw(sizeof(v) * 2) << std::hex << v;
return s.str();
return std::format("{0:0{1}X}", v, sizeof(v) * 2);
}
/**
* Generate a Hash out of a string
* @param s String to hash
* @return 32Bit Hash
*/
PD_CORE_API u32 FastHash(const std::string& s);
PD_API u32 FastHash(const std::string& s);
/**
* Function to Generate a Compiler Name and Version String
* Based on their Macros
* @return CompilerName: Version
*/
inline const std::string GetCompilerVersion() {
/// As the function looks like this Project is meant to
/// Be ported to other systems as well
std::stringstream res;
inline const char* GetCompilerVersion() {
/// As the function looks like this Project is meant to
/// Be ported to other systems as well
#define __mks(x) #x
#define mkstring(x) __mks(x)
#ifdef __clang__ // Check clang first
res << "Clang: " << __clang_major__ << ".";
res << __clang_minor__ << ".";
res << __clang_patchlevel__;
return "Clang: " mkstring(__clang_major__) "." mkstring(
__clang_minor__) "." mkstring(__clang_patchlevel__);
#elif __GNUC__
res << "GCC: " << __GNUC__;
res << "." << __GNUC_MINOR__ << ".";
res << __GNUC_PATCHLEVEL__;
return "GCC: " mkstring(__GNUC__) "." mkstring(__GNUC_MINOR__) "." mkstring(
__GNUC_PATCHLEVEL__);
#elif _MSC_VER
res << "MSVC: " << _MSC_VER;
return "MSVC; " mkstring(_MSC_VER);
#else
res << "Unknown Compiler";
return "Unknown Compiler";
#endif
return res.str();
}
} // namespace Strings
class U8Iterator {
public:
explicit U8Iterator(const char* s) : ptr(reinterpret_cast<const u8*>(s)) {}
~U8Iterator() = default;
bool Decode32(u32& ret) {
if (ptr == nullptr || *ptr == 0) return false;
u8 c = *ptr;
if (c < 0x80) {
ret = c;
ptr += 1;
} else if ((c >> 5) == 0x6) {
ret = ((c & 0x1F) << 6) | (ptr[1] & 0x3F);
ptr += 2;
} else if ((c >> 4) == 0xE) {
ret = ((c & 0x0F) << 12) | ((ptr[1] & 0x3F) << 6) | (ptr[2] & 0x3F);
ptr += 3;
} else {
ret = ((c & 0x07) << 18) | ((ptr[1] & 0x3F) << 12) |
((ptr[2] & 0x3F) << 6) | (ptr[3] & 0x3F);
ptr += 4;
}
return true;
}
bool PeekNext32(u32& ret) {
// if ((ptr + 1) == 0 || *(ptr + 1) == 0) return false;
u8 c = *ptr;
if (c < 0x80) {
ret = c;
} else if ((c >> 5) == 0x6) {
ret = ((c & 0x1F) << 6) | (ptr[1] & 0x3F);
} else if ((c >> 4) == 0xE) {
ret = ((c & 0x0F) << 12) | ((ptr[1] & 0x3F) << 6) | (ptr[2] & 0x3F);
} else {
ret = ((c & 0x07) << 18) | ((ptr[1] & 0x3F) << 12) |
((ptr[2] & 0x3F) << 6) | (ptr[3] & 0x3F);
}
return true;
}
private:
const u8* ptr = nullptr;
};
} // namespace PD

View File

@@ -1,66 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
#include <pd/core/timetrace.hpp>
namespace PD {
/**
* Namespace containing functions for get Millis and Get Nanos
*/
namespace Sys {
/**
* alias for the TimeTrace Traces Map
*/
using TraceMap = std::map<std::string, TT::Res::Ref>;
/**
* Get Current Time in Milliseconds
* @return 64Bit value of millis
*/
PD_CORE_API u64 GetTime();
/**
* Get Current Time in Nanoseconds
* @return 64Bit value of nanos
*/
PD_CORE_API u64 GetNanoTime();
/**
* Get a TimeTrace Reference by its string ID
* @param id trace name
* @return Trace reference or nullptr if not found
*/
PD_CORE_API TT::Res::Ref& GetTraceRef(const std::string& id);
/**
* Check if a Trace with the name exists
* @param id tracename to search
* @return true if exist
*/
PD_CORE_API bool TraceExist(const std::string& id);
/**
* Get TraceMap Reference
* @return edidable Reference to the TraceMap
*/
PD_CORE_API TraceMap& GetTraceMap();
} // namespace Sys
} // namespace PD

15
include/pd/core/timer.hpp Normal file → Executable file
View File

@@ -2,7 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -23,14 +23,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
#include <pd/core/sys.hpp>
#include <pd/common.hpp>
namespace PD {
/**
* Timer class
*/
class PD_CORE_API Timer : public SmartCtor<Timer> {
class PD_API Timer {
public:
/**
* Constructor
@@ -41,6 +40,7 @@ class PD_CORE_API Timer : public SmartCtor<Timer> {
* Unused Deconstructor
*/
~Timer() {}
/**
* Resume Timer if Paused
*/
@@ -73,12 +73,11 @@ class PD_CORE_API Timer : public SmartCtor<Timer> {
*/
double GetSeconds();
private:
/** Start of the Timer */
u64 start;
u64 pStart;
/** Current Time */
u64 now;
u64 pNow;
/** Is Running */
bool is_running = false;
bool pIsRunning = false;
};
} // namespace PD

View File

@@ -2,7 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -23,13 +23,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
#include <pd/common.hpp>
namespace PD {
/**
* Class to calculate Maximum/Minimum and Average Timings
*/
class TimeStats : public SmartCtor<TimeStats> {
class TimeStats {
public:
/**
* Constructor taking a lengh for the List
@@ -100,12 +100,12 @@ class TimeStats : public SmartCtor<TimeStats> {
* Get Data Buffer
* @return data bufer (not edidable)
*/
const std::vector<u64> &GetData() { return val; }
const std::vector<u64>& GetData() { return val; }
/**
* Access an element in the list [not edidable]
* @return value to access
*/
const u64 &operator[](int i) { return val[smart_idx(i)]; }
const u64& operator[](int i) { return val[smart_idx(i)]; }
/**
* Get List Lengh
* @return Lengh
@@ -146,17 +146,17 @@ namespace TT {
/**
* Data Structure for a TimeTrace Result
*/
class Res : public SmartCtor<Res> {
class Res {
public:
/** Constructore that Inits a protocol at size of 60 frames */
Res() { protocol = TimeStats::New(60); }
Res() : start(0), end(0), protocol(60) {}
~Res() = default;
/**
* Setter for the ID (Name)
* @param v ID of the Trace
*/
void SetID(const std::string &v) { id = v; }
void SetID(const std::string& v) { id = v; }
/**
* Getter for the traces ID
* @return Trace ID
@@ -178,7 +178,8 @@ class Res : public SmartCtor<Res> {
*/
void SetEnd(u64 v) {
end = v;
protocol->Add(GetLastDiff());
diff = end - start;
protocol.Add(GetLastDiff());
}
/**
* Getter for the End Time
@@ -190,12 +191,12 @@ class Res : public SmartCtor<Res> {
* Get Last Diffrence between end and start
* @return end - start
*/
u64 GetLastDiff() { return end - start; }
u64 GetLastDiff() { return diff; }
/**
* Get Protcol Reference
* @return Protocol Ref
*/
TimeStats::Ref GetProtocol() { return protocol; }
TimeStats& GetProtocol() { return protocol; }
private:
/** Trace ID */
@@ -204,19 +205,21 @@ class Res : public SmartCtor<Res> {
u64 start;
/** End Time */
u64 end;
/** Last Diff */
u64 diff;
/** Protocol */
TimeStats::Ref protocol;
TimeStats protocol;
};
/**
* Begin a Trace
* @param id Name of the Trace
*/
PD_CORE_API void Beg(const std::string &id);
PD_API void Beg(const std::string& id);
/**
* End a Trace
* @param id Name of the Trace
*/
PD_CORE_API void End(const std::string &id);
PD_API void End(const std::string& id);
/**
* Collect Start end end of the trace by tracking
* when the Scope object goes out of scope
@@ -238,18 +241,18 @@ class Scope {
* Constructor requiring a Name for the Trace
* @param id Name of the Trace
*/
Scope(const std::string &id) {
this->id = id;
Scope(const std::string& id) {
this->ID = id;
Beg(id);
}
/**
* Deconstructor getting the end time when going out of scope
*/
~Scope() { End(id); }
~Scope() { End(ID); }
private:
/** Trace Name/ID */
std::string id;
std::string ID;
};
} // namespace TT
} // namespace PD

26
include/pd/core/tween.hpp Normal file → Executable file
View File

@@ -2,7 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -23,7 +23,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
#include <pd/common.hpp>
#ifndef M_PI
#define M_PI 3.14159265358979323846
@@ -60,7 +60,7 @@ class Tween {
* @param delta deltatime
*/
void Update(float delta) {
time += delta / 1000.f;
time += delta * 0.001f;
if (time > tend) {
finished = true;
time = tend;
@@ -162,10 +162,10 @@ class Tween {
return -(end - start) * t * (t - 2) + start;
break;
case EaseInOutQuad:
t = time / (tend / 2);
if (t < 1) return (end - start) / 2 * t * t + start;
t = time / (tend * 0.5f);
if (t < 1) return (end - start) * 0.5f * t * t + start;
t--;
return -(end - start) / 2 * (t * (t - 2) - 1) + start;
return -(end - start) * 0.5f * (t * (t - 2) - 1) + start;
break;
case EaseInCubic:
t = time / tend;
@@ -177,20 +177,20 @@ class Tween {
return (end - start) * (t * t * t + 1) + start;
break;
// case EaseInOutCubic:
// t = time / (tend / 2);
// if (t < 1) return (end - start) / 2 * t * t * t + start;
// t = time / (tend *0.5f);
// if (t < 1) return (end - start) *0.5f * t * t * t + start;
// t--;
// return (end - start) / 2 * (t * t * t * 2) + start;
// return (end - start) *0.5f * (t * t * t * 2) + start;
// break;
case EaseInSine:
return -(end - start) * cos(time / tend * (M_PI / 2)) + (end - start) +
start;
return -(end - start) * cos(time / tend * (M_PI * 0.5f)) +
(end - start) + start;
break;
case EaseOutSine:
return (end - start) * sin(time / tend * (M_PI / 2)) + start;
return (end - start) * sin(time / tend * (M_PI * 0.5f)) + start;
break;
case EaseInOutSine:
return -(end - start) / 2 * (cos(M_PI * time / tend) - 1) + start;
return -(end - start) * 0.5f * (cos(M_PI * time / tend) - 1) + start;
break;
default: // Linear

127
include/pd/core/u128.hpp Normal file
View File

@@ -0,0 +1,127 @@
#pragma once
#include <pd/common.hpp>
namespace PD {
/**
* 128 Bit support for all platforms probably
* only used for flag checks in Keyboard/Mouse Input driver
*/
class u128 {
public:
u64 pLow = 0;
u64 pHigh = 0;
constexpr u128() : pLow(0), pHigh(0) {}
constexpr u128(u64 l, u64 h = 0) : pLow(l), pHigh(h) {}
/**
* Best way so far to create flags that go over 63
* like `1 << 65` is just `u128::Flag(65)`
*/
constexpr static u128 Flag(u32 i) {
if (i < 64) {
return u128(1ULL << i, 0);
} else if (i < 128) {
return u128(0, 1ULL << (i - 64));
}
return u128();
}
constexpr u128 operator+(const u128& v) const {
u128 ret;
ret.pLow = pLow + v.pLow;
ret.pHigh = pHigh + v.pHigh + (ret.pLow < pLow);
return ret;
}
constexpr u128 operator&(const u128& v) const {
return u128(pLow & v.pLow, pHigh & v.pHigh);
}
constexpr u128 operator<<(u32 s) const {
if (s == 0) {
return *this;
}
if (s >= 128) {
return u128();
}
if (s >= 64) {
return u128(0, pLow << (s - 64));
}
return u128(pLow << s, (pHigh << s) | (pLow >> (64 - s)));
}
constexpr u128 operator>>(u32 s) const {
if (s == 0) {
return *this;
}
if (s >= 128) {
return u128();
}
if (s >= 64) {
return u128(pHigh >> (s - 64), 0);
}
return u128((pLow >> s) | (pHigh << (64 - s)), pHigh >> s);
}
constexpr u128& operator|=(const u128& v) {
pLow |= v.pLow;
pHigh |= v.pHigh;
return *this;
}
constexpr u128 operator|(const u128& v) const {
return u128(pLow | v.pLow, pHigh | v.pHigh);
}
constexpr u128& operator&=(const u128& v) {
pLow &= v.pLow;
pHigh &= v.pHigh;
return *this;
}
constexpr u128 operator~() const { return u128(~pLow, ~pHigh); }
/**
* Old why to make if checks possible
* Problem was that a operator& is required
* with u128 as result
*/
// bool operator&(const u128& v) const {
// return pLow & v.pLow || pHigh & v.pHigh;
// }
constexpr bool operator==(const u128& v) const {
return pLow == v.pLow && pHigh == v.pHigh;
}
/**
* Use explicit here to make sure it is only for checking and not for
* some error leading implicit bool assignments...
*/
constexpr explicit operator bool() const { return pLow != 0 || pHigh != 0; }
/** Deprecated way to handle `flag & SomeFlag` */
constexpr bool Has(const u128& v) const {
return pLow & v.pLow || pHigh & v.pHigh;
}
constexpr bool operator!=(const u128& v) const { return !(*this == v); }
};
} // namespace PD
namespace std {
/**
* Provide c++ STL support for unordered map to u128
*/
template <>
struct hash<PD::u128> {
size_t operator()(const PD::u128& k) const {
// just combine hashes of the parts usign simple xor op
size_t h0 = std::hash<PD::u64>{}(k.pLow);
size_t h1 = std::hash<PD::u64>{}(k.pHigh);
return h0 ^ (h1 << 1);
}
};
} // namespace std

33
include/pd/core/vec.hpp Normal file → Executable file
View File

@@ -2,7 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -23,6 +23,37 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/common.hpp>
#include <pd/core/vec2.hpp>
#include <pd/core/vec3.hpp>
#include <pd/core/vec4.hpp>
/** Define Formatters for C++ 20 */
/**
* WHY DOES MSVC ALWAYS NEED THESE EXTRA THINGS
*/
template <typename T, typename CharT>
struct std::formatter<PD::vec2<T>, CharT> : std::formatter<T, CharT> {
template <typename FormatContext>
auto format(const PD::vec2<T>& v, FormatContext& ctx) const {
return std::format_to(ctx.out(), "{}, {}", v.x, v.y);
}
};
template <typename T, typename CharT>
struct std::formatter<PD::vec3<T>, CharT> : std::formatter<T, CharT> {
template <typename FormatContext>
auto format(const PD::vec3<T>& v, FormatContext& ctx) const {
return std::format_to(ctx.out(), "{}, {}, {}", v.x, v.y, v.z);
}
};
template <typename T, typename CharT>
struct std::formatter<PD::vec4<T>, CharT> : std::formatter<T, CharT> {
template <typename FormatContext>
auto format(const PD::vec4<T>& v, FormatContext& ctx) const {
return std::format_to(ctx.out(), "{}, {}, {}, {}", v.x, v.y, v.z, v.w);
}
};

190
include/pd/core/vec2.hpp Normal file → Executable file
View File

@@ -2,7 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -23,113 +23,175 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
// This file is generated by lazyvec 2.0.0
#include <pd/common.hpp>
namespace PD {
template <typename T>
class vec2 {
public:
// SECTION: Constructors //
T x;
T y;
vec2() = default;
vec2(T v) {
x = v;
y = v;
}
vec2(T x, T y) {
this->x = x;
this->y = y;
// Constructors
constexpr vec2() : x(0), y(0) {}
template <typename T1>
constexpr vec2(T1 v) {
x = (T)v;
y = (T)v;
}
vec2(const vec2<T> &v) {
x = v.x;
y = v.y;
template <typename T1>
constexpr vec2(const vec2<T1>& v) {
x = (T)v.x;
y = (T)v.y;
}
// SECTION: Operators //
constexpr explicit vec2(T x, T y) : x(x), y(y) {}
// ADD //
// Operations
vec2 &operator+=(T v) {
x += v;
y += v;
template <typename T1>
vec2<T>& operator+=(T1 v) {
x += (T)v;
y += (T)v;
return *this;
}
vec2 &operator+=(const vec2 &v) {
x += v.x;
y += v.y;
template <typename T1>
vec2<T>& operator+=(const vec2<T1>& v) {
x += (T)v.x;
y += (T)v.y;
return *this;
}
vec2 operator+(T v) const { return vec2(x + v, y + v); }
vec2 operator+(vec2 v) const { return vec2(x + v.x, y + v.y); }
// SUB //
template <typename T1>
vec2<T> operator+(T1 v) const {
return vec2<T>(x + (T)v, y + (T)v);
}
vec2 &operator-=(T v) {
x -= v;
y -= v;
template <typename T1>
vec2<T> operator+(const vec2<T1>& v) const {
return vec2<T>(x + (T)v.x, y + (T)v.y);
}
template <typename T1>
vec2<T>& operator-=(T1 v) {
x -= (T)v;
y -= (T)v;
return *this;
}
vec2 &operator-=(const vec2 &v) {
x -= v.x;
y -= v.y;
template <typename T1>
vec2<T>& operator-=(const vec2<T1>& v) {
x -= (T)v.x;
y -= (T)v.y;
return *this;
}
vec2 operator-(T v) const { return vec2(x - v, y - v); }
vec2 operator-(vec2 v) const { return vec2(x - v.x, y - v.y); }
// MUL //
template <typename T1>
vec2<T> operator-(T1 v) const {
return vec2<T>(x - (T)v, y - (T)v);
}
vec2 &operator*=(T v) {
x *= v;
y *= v;
template <typename T1>
vec2<T> operator-(const vec2<T1>& v) const {
return vec2<T>(x - (T)v.x, y - (T)v.y);
}
template <typename T1>
vec2<T>& operator*=(T1 v) {
x *= (T)v;
y *= (T)v;
return *this;
}
vec2 &operator*=(const vec2 &v) {
x *= v.x;
y *= v.y;
template <typename T1>
vec2<T>& operator*=(const vec2<T1>& v) {
x *= (T)v.x;
y *= (T)v.y;
return *this;
}
vec2 operator*(T v) const { return vec2(x * v, y * v); }
vec2 operator*(vec2 v) const { return vec2(x * v.x, y * v.y); }
// DIV //
template <typename T1>
vec2<T> operator*(T1 v) const {
return vec2<T>(x * (T)v, y * (T)v);
}
vec2 &operator/=(T v) {
x /= v;
y /= v;
template <typename T1>
vec2<T> operator*(const vec2<T1>& v) const {
return vec2<T>(x * (T)v.x, y * (T)v.y);
}
template <typename T1>
vec2<T>& operator/=(T1 v) {
x /= (T)v;
y /= (T)v;
return *this;
}
vec2 &operator/=(const vec2 &v) {
x /= v.x;
y /= v.y;
template <typename T1>
vec2<T>& operator/=(const vec2<T1>& v) {
x /= (T)v.x;
y /= (T)v.y;
return *this;
}
vec2 operator/(T v) const { return vec2(x / v, y / v); }
vec2 operator/(vec2 v) const { return vec2(x / v.x, y / v.y); }
// Make Negative //
template <typename T1>
vec2<T> operator/(T1 v) const {
return vec2<T>(x / (T)v, y / (T)v);
}
template <typename T1>
vec2<T> operator/(const vec2<T1>& v) const {
return vec2<T>(x / (T)v.x, y / (T)v.y);
}
// Generic Operations
vec2 operator-() const { return vec2(-x, -y); }
template <typename T1>
bool operator==(const vec2<T1>& v) const {
return x == (T)v.x && y == (T)v.y;
}
template <typename T1>
bool operator!=(const vec2<T1>& v) const {
return !(*this == v);
}
bool operator==(const vec2 &v) const { return x == v.x && y == v.y; }
bool operator!=(const vec2 &v) const { return !(*this == v); }
// Functions
// SECTION: Additional Functions //
double Len() const { return std::sqrt(SqLen()); }
double SqLen() const { return x * x + y * y; }
float Len() const { return sqrt(SqLen()); }
float SqLen() const { return x * x + y * y; }
void Swap() {
template <typename T1>
double Distance(const vec2<T1>& v) const {
return (*this - v).Len();
}
vec2<T> Normalize() const {
double l = Len();
if (l == 0) {
return *this;
}
return *this / (T)l;
}
template <typename T1>
T Dot(const vec2<T1>& v) const {
return x * (T)v.x + y * (T)v.y;
}
// Swap Functions
void SwapXY() {
T t = x;
x = y;
y = t;
}
// SECTION: DATA //
T x = 0;
T y = 0;
};
using dvec2 = vec2<double>;
using fvec2 = vec2<float>;
using ivec2 = vec2<int>;
using dvec2 = vec2<double>;
} // namespace PD

245
include/pd/core/vec3.hpp Normal file → Executable file
View File

@@ -2,7 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -23,138 +23,213 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
// This file is generated by lazyvec 2.0.0
#include <pd/common.hpp>
// Extended includes (rename if you use other filenames/paths)
#include <pd/core/vec2.hpp>
namespace PD {
template <typename T>
class vec3 {
public:
// SECTION: Constructors //
T x;
T y;
T z;
vec3() = default;
vec3(T v) {
x = v;
y = v;
z = v;
}
vec3(T x, T y, T z) {
this->x = x;
this->y = y;
this->z = z;
// Constructors
constexpr vec3() : x(0), y(0), z(0) {}
template <typename T1>
constexpr vec3(T1 v) {
x = (T)v;
y = (T)v;
z = (T)v;
}
vec3(const vec3 &v) {
x = v.x;
y = v.y;
z = v.z;
template <typename T1>
constexpr vec3(const vec3<T1>& v) {
x = (T)v.x;
y = (T)v.y;
z = (T)v.z;
}
// SECTION: Operators //
constexpr explicit vec3(T x, T y, T z) : x(x), y(y), z(z) {}
// ADD //
// Extended Constructors
template <typename T1>
constexpr explicit vec3(const vec2<T1>& xy, T1 z) {
{
x = (T)xy.x;
y = (T)xy.y;
this->z = (T)z;
}
}
vec3 &operator+=(T v) {
x += v;
y += v;
z += v;
// Operations
template <typename T1>
vec3<T>& operator+=(T1 v) {
x += (T)v;
y += (T)v;
z += (T)v;
return *this;
}
vec3 &operator+=(const vec3 &v) {
x += v.x;
y += v.y;
z += v.z;
template <typename T1>
vec3<T>& operator+=(const vec3<T1>& v) {
x += (T)v.x;
y += (T)v.y;
z += (T)v.z;
return *this;
}
vec3 operator+(T v) const { return vec3(x + v, y + v, z + v); }
vec3 operator+(vec3 v) const { return vec3(x + v.x, y + v.y, z + v.z); }
// SUB //
template <typename T1>
vec3<T> operator+(T1 v) const {
return vec3<T>(x + (T)v, y + (T)v, z + (T)v);
}
vec3 &operator-=(T v) {
x -= v;
y -= v;
z -= v;
template <typename T1>
vec3<T> operator+(const vec3<T1>& v) const {
return vec3<T>(x + (T)v.x, y + (T)v.y, z + (T)v.z);
}
template <typename T1>
vec3<T>& operator-=(T1 v) {
x -= (T)v;
y -= (T)v;
z -= (T)v;
return *this;
}
vec3 &operator-=(const vec3 &v) {
x -= v.x;
y -= v.y;
z -= v.z;
template <typename T1>
vec3<T>& operator-=(const vec3<T1>& v) {
x -= (T)v.x;
y -= (T)v.y;
z -= (T)v.z;
return *this;
}
vec3 operator-(T v) const { return vec3(x - v, y - v, z - v); }
vec3 operator-(vec3 v) const { return vec3(x - v.x, y - v.y, z - v.z); }
// MUL //
template <typename T1>
vec3<T> operator-(T1 v) const {
return vec3<T>(x - (T)v, y - (T)v, z - (T)v);
}
vec3 &operator*=(T v) {
x *= v;
y *= v;
z *= v;
template <typename T1>
vec3<T> operator-(const vec3<T1>& v) const {
return vec3<T>(x - (T)v.x, y - (T)v.y, z - (T)v.z);
}
template <typename T1>
vec3<T>& operator*=(T1 v) {
x *= (T)v;
y *= (T)v;
z *= (T)v;
return *this;
}
vec3 &operator*=(const vec3 &v) {
x *= v.x;
y *= v.y;
z *= v.z;
template <typename T1>
vec3<T>& operator*=(const vec3<T1>& v) {
x *= (T)v.x;
y *= (T)v.y;
z *= (T)v.z;
return *this;
}
vec3 operator*(T v) const { return vec3(x * v, y * v, z * v); }
vec3 operator*(vec3 v) const { return vec3(x * v.x, y * v.y, z * v.z); }
// DIV //
template <typename T1>
vec3<T> operator*(T1 v) const {
return vec3<T>(x * (T)v, y * (T)v, z * (T)v);
}
vec3 &operator/=(T v) {
x /= v;
y /= v;
z /= v;
template <typename T1>
vec3<T> operator*(const vec3<T1>& v) const {
return vec3<T>(x * (T)v.x, y * (T)v.y, z * (T)v.z);
}
template <typename T1>
vec3<T>& operator/=(T1 v) {
x /= (T)v;
y /= (T)v;
z /= (T)v;
return *this;
}
vec3 &operator/=(const vec3 &v) {
x /= v.x;
y /= v.y;
z /= v.z;
template <typename T1>
vec3<T>& operator/=(const vec3<T1>& v) {
x /= (T)v.x;
y /= (T)v.y;
z /= (T)v.z;
return *this;
}
vec3 operator/(T v) const { return vec3(x / v, y / v, z / v); }
vec3 operator/(vec3 v) const { return vec3(x / v.x, y / v.y, z / v.z); }
// Make Negative //
template <typename T1>
vec3<T> operator/(T1 v) const {
return vec3<T>(x / (T)v, y / (T)v, z / (T)v);
}
template <typename T1>
vec3<T> operator/(const vec3<T1>& v) const {
return vec3<T>(x / (T)v.x, y / (T)v.y, z / (T)v.z);
}
// Generic Operations
vec3 operator-() const { return vec3(-x, -y, -z); }
bool operator==(const vec3 &v) const {
return x == v.x && y == v.y && z == v.z;
template <typename T1>
bool operator==(const vec3<T1>& v) const {
return x == (T)v.x && y == (T)v.y && z == (T)v.z;
}
template <typename T1>
bool operator!=(const vec3<T1>& v) const {
return !(*this == v);
}
bool operator!=(const vec3 &v) const { return !(*this == v); }
// SECTION: Additional Functions //
// Functions
float Len() const { return sqrt(SqLen()); }
float SqLen() const { return x * x + y * y + z * z; }
double Len() const { return std::sqrt(SqLen()); }
double SqLen() const { return x * x + y * y + z * z; }
template <typename T1>
double Distance(const vec3<T1>& v) const {
return (*this - v).Len();
}
vec3<T> Normalize() const {
double l = Len();
if (l == 0) {
return *this;
}
return *this / (T)l;
}
template <typename T1>
T Dot(const vec3<T1>& v) const {
return x * (T)v.x + y * (T)v.y + z * (T)v.z;
}
template <typename T1>
vec3<T> Cross(const vec3<T1>& v) const {
return vec3<T>(y * v.z - z * v.y, z * v.x - x * v.z, x * v.y - y * v.x);
}
// Swap Functions
void SwapXY() {
T t = x;
x = y;
y = t;
}
void SwapYZ() {
T t = z;
z = y;
y = t;
}
void SwapXZ() {
T t = z;
z = x;
x = t;
T t = x;
x = z;
z = t;
}
void SwapYZ() {
T t = y;
y = z;
z = t;
}
// SECTION: DATA //
T x = 0;
T y = 0;
T z = 0;
};
using dvec3 = vec3<double>;
using fvec3 = vec3<float>;
using ivec3 = vec3<int>;
using dvec3 = vec3<double>;
} // namespace PD

297
include/pd/core/vec4.hpp Normal file → Executable file
View File

@@ -2,7 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -23,171 +23,246 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/common.hpp>
// This file is generated by lazyvec 2.0.0
#include <pd/common.hpp>
// Extended includes (rename if you use other filenames/paths)
#include <pd/core/vec2.hpp>
#include <pd/core/vec3.hpp>
namespace PD {
template <typename T>
class vec4 {
public:
// SECTION: Constructors //
T x;
T y;
T z;
T w;
vec4() = default;
vec4(T v) {
x = v;
y = v;
z = v;
w = v;
}
vec4(T x, T y, T z, T w) {
this->x = x;
this->y = y;
this->z = z;
this->w = w;
// Constructors
constexpr vec4() : x(0), y(0), z(0), w(0) {}
template <typename T1>
constexpr vec4(T1 v) {
x = (T)v;
y = (T)v;
z = (T)v;
w = (T)v;
}
vec4(const vec4 &v) {
x = v.x;
y = v.y;
z = v.z;
w = v.w;
template <typename T1>
constexpr vec4(const vec4<T1>& v) {
x = (T)v.x;
y = (T)v.y;
z = (T)v.z;
w = (T)v.w;
}
vec4(const vec2<T> &xy, const vec2<T> &zw) {
x = xy.x;
y = xy.y;
z = zw.x;
w = zw.y;
constexpr explicit vec4(T x, T y, T z, T w) : x(x), y(y), z(z), w(w) {}
// Extended Constructors
template <typename T1>
constexpr explicit vec4(const vec2<T1>& xy, const vec2<T1>& zw) {
{
x = (T)xy.x;
y = (T)xy.y;
z = (T)zw.x;
w = (T)zw.y;
}
}
// SECTION: Operators //
template <typename T1>
constexpr explicit vec4(const vec3<T1>& xyz, T1 w) {
{
x = (T)xyz.x;
y = (T)xyz.y;
z = (T)xyz.z;
this->w = (T)w;
}
}
// ADD //
// Operations
vec4 &operator+=(T v) {
x += v;
y += v;
z += v;
w += v;
template <typename T1>
vec4<T>& operator+=(T1 v) {
x += (T)v;
y += (T)v;
z += (T)v;
w += (T)v;
return *this;
}
vec4 &operator+=(const vec4<T> &v) {
x += v.x;
y += v.y;
z += v.z;
w += v.w;
template <typename T1>
vec4<T>& operator+=(const vec4<T1>& v) {
x += (T)v.x;
y += (T)v.y;
z += (T)v.z;
w += (T)v.w;
return *this;
}
vec4 operator+(T v) const { return vec4<T>(x + v, y + v, z + v, w + v); }
vec4 operator+(vec4 v) const {
return vec4(x + v.x, y + v.y, z + v.z, w + v.w);
template <typename T1>
vec4<T> operator+(T1 v) const {
return vec4<T>(x + (T)v, y + (T)v, z + (T)v, w + (T)v);
}
// SUB //
template <typename T1>
vec4<T> operator+(const vec4<T1>& v) const {
return vec4<T>(x + (T)v.x, y + (T)v.y, z + (T)v.z, w + (T)v.w);
}
vec4 &operator-=(T v) {
x -= v;
y -= v;
z -= v;
w -= v;
template <typename T1>
vec4<T>& operator-=(T1 v) {
x -= (T)v;
y -= (T)v;
z -= (T)v;
w -= (T)v;
return *this;
}
vec4 &operator-=(const vec4 &v) {
x -= v.x;
y -= v.y;
z -= v.z;
w -= v.w;
template <typename T1>
vec4<T>& operator-=(const vec4<T1>& v) {
x -= (T)v.x;
y -= (T)v.y;
z -= (T)v.z;
w -= (T)v.w;
return *this;
}
vec4 operator-(T v) const { return vec4(x - v, y - v, z - v, w - v); }
vec4 operator-(vec4 v) const {
return vec4(x - v.x, y - v.y, z - v.z, w - v.w);
template <typename T1>
vec4<T> operator-(T1 v) const {
return vec4<T>(x - (T)v, y - (T)v, z - (T)v, w - (T)v);
}
// MUL //
template <typename T1>
vec4<T> operator-(const vec4<T1>& v) const {
return vec4<T>(x - (T)v.x, y - (T)v.y, z - (T)v.z, w - (T)v.w);
}
vec4 &operator*=(T v) {
x *= v;
y *= v;
z *= v;
w *= v;
template <typename T1>
vec4<T>& operator*=(T1 v) {
x *= (T)v;
y *= (T)v;
z *= (T)v;
w *= (T)v;
return *this;
}
vec4 &operator*=(const vec4 &v) {
x *= v.x;
y *= v.y;
z *= v.z;
w *= v.w;
template <typename T1>
vec4<T>& operator*=(const vec4<T1>& v) {
x *= (T)v.x;
y *= (T)v.y;
z *= (T)v.z;
w *= (T)v.w;
return *this;
}
vec4 operator*(T v) const { return vec4(x * v, y * v, z * v, w * v); }
vec4 operator*(vec4 v) const {
return vec4(x * v.x, y * v.y, z * v.z, w * v.w);
template <typename T1>
vec4<T> operator*(T1 v) const {
return vec4<T>(x * (T)v, y * (T)v, z * (T)v, w * (T)v);
}
// DIV //
template <typename T1>
vec4<T> operator*(const vec4<T1>& v) const {
return vec4<T>(x * (T)v.x, y * (T)v.y, z * (T)v.z, w * (T)v.w);
}
vec4 &operator/=(T v) {
x /= v;
y /= v;
z /= v;
w /= v;
template <typename T1>
vec4<T>& operator/=(T1 v) {
x /= (T)v;
y /= (T)v;
z /= (T)v;
w /= (T)v;
return *this;
}
vec4 &operator/=(const vec4 &v) {
x /= v.x;
y /= v.y;
z /= v.z;
w /= v.w;
template <typename T1>
vec4<T>& operator/=(const vec4<T1>& v) {
x /= (T)v.x;
y /= (T)v.y;
z /= (T)v.z;
w /= (T)v.w;
return *this;
}
vec4 operator/(T v) const { return vec4(x / v, y / v, z / v, w / v); }
vec4 operator/(vec4 v) const {
return vec4(x / v.x, y / v.y, z / v.z, w / v.w);
template <typename T1>
vec4<T> operator/(T1 v) const {
return vec4<T>(x / (T)v, y / (T)v, z / (T)v, w / (T)v);
}
// Make Negative //
template <typename T1>
vec4<T> operator/(const vec4<T1>& v) const {
return vec4<T>(x / (T)v.x, y / (T)v.y, z / (T)v.z, w / (T)v.w);
}
// Generic Operations
vec4 operator-() const { return vec4(-x, -y, -z, -w); }
bool operator==(const vec4 &v) const {
return x == v.x && y == v.y && z == v.z && w == v.w;
template <typename T1>
bool operator==(const vec4<T1>& v) const {
return x == (T)v.x && y == (T)v.y && z == (T)v.z && w == (T)v.w;
}
template <typename T1>
bool operator!=(const vec4<T1>& v) const {
return !(*this == v);
}
bool operator!=(const vec4 &v) const { return !(*this == v); }
// SECTION: Additional Functions //
// Functions
float Len() const { return sqrt(SqLen()); }
float SqLen() const { return x * x + y * y + z * z + w * w; }
double Len() const { return std::sqrt(SqLen()); }
double SqLen() const { return x * x + y * y + z * z + w * w; }
template <typename T1>
double Distance(const vec4<T1>& v) const {
return (*this - v).Len();
}
vec4<T> Normalize() const {
double l = Len();
if (l == 0) {
return *this;
}
return *this / (T)l;
}
template <typename T1>
T Dot(const vec4<T1>& v) const {
return x * (T)v.x + y * (T)v.y + z * (T)v.z + w * (T)v.w;
}
// Swap Functions
void SwapXY() {
T t = x;
x = y;
y = t;
}
void SwapYZ() {
T t = z;
z = y;
y = t;
}
void SwapXZ() {
T t = z;
z = x;
x = t;
}
// Adding ZW (to lazy to add all of those yet)
void SwapZW() {
T t = w;
w = z;
T t = x;
x = z;
z = t;
}
// SECTION: DATA //
T x = 0;
T y = 0;
T z = 0;
T w = 0;
void SwapXW() {
T t = x;
x = w;
w = t;
}
void SwapYZ() {
T t = y;
y = z;
z = t;
}
void SwapYW() {
T t = y;
y = w;
w = t;
}
void SwapZW() {
T t = z;
z = w;
w = t;
}
};
using dvec4 = vec4<double>;
using fvec4 = vec4<float>;
using ivec4 = vec4<int>;
using dvec4 = vec4<double>;
} // namespace PD

4
include/pd/drivers/drivers.hpp Executable file
View File

@@ -0,0 +1,4 @@
#pragma once
#include <pd/drivers/gfx.hpp>
#include <pd/drivers/os.hpp>

172
include/pd/drivers/gfx.hpp Executable file
View File

@@ -0,0 +1,172 @@
#pragma once
#include <pd/core/mat.hpp>
#include <pd/drivers/interface.hpp>
#include <pd/lithium/command.hpp>
#include <pd/lithium/texture.hpp>
using LiBackendFlags = PD::u32;
enum LiBackendFlags_ {
LiBackendFlags_None = 0,
LiBackendFlags_FlipUV_Y = 1 << 0, // Essential for font loading
};
namespace PD {
// Pre interface class
class PD_API GfxDriver : public DriverInterface {
public:
GfxDriver(std::string_view name);
virtual ~GfxDriver();
virtual void Init() {}
virtual void Deinit() { SysDeinit(); }
void SetViewPort(const ivec2& size);
void SetViewPort(int x, int y);
virtual void BindTexture(TextureID id) {}
void Reset();
virtual Li::Texture LoadTexture(
const std::vector<PD::u8>& pixels, int w, int h,
TextureFormat type = TextureFormat::RGBA32,
TextureFilter filter = TextureFilter::Linear) {
return Li::Texture();
}
virtual void DeleteTexture(const Li::Texture& tex) {}
virtual void Draw(const Pool<Li::Command>& commands) {}
Li::Texture::Ptr GetWhiteTexture() { return &pWhite; }
protected:
virtual void SysDeinit() {}
virtual void SysInit() {}
virtual void SysReset() {}
virtual void Submit(size_t count, size_t start) {}
virtual void ResetPools() = 0;
void RegisterTexture(const Li::Texture& tex);
void UnregisterTexture(const Li::Texture& tex);
// Counters
size_t CountDrawcalls = 0;
size_t CountCommands = 0;
size_t CountVertices = 0;
size_t CountIndices = 0;
size_t CurrentIndex = 0;
size_t CurrentVertex = 0;
TextureID CurrentTex = 0;
Mat4 Projection;
ivec2 ViewPort;
std::unordered_map<TextureID, Li::Texture> pTextureRegestry;
Li::Texture pWhite;
};
struct DefaultGfxConfig {
// Vertex Allocator
template <typename T>
using VertexAlloc = std::allocator<T>;
// Index Allocator
template <typename T>
using IndexAlloc = std::allocator<T>;
static constexpr size_t NumVertices = 32768; // 8192*4
static constexpr size_t NumIndices = 49152; // 8192*6
};
template <typename Config = DefaultGfxConfig>
class GfxDriverBase : public GfxDriver {
public:
using VtxPool =
Pool<Li::Vertex, typename Config::template VertexAlloc<Li::Vertex>>;
using IdxPool = Pool<u16, typename Config::template VertexAlloc<u16>>;
GfxDriverBase(std::string_view name = "Default") : GfxDriver(name) {}
virtual ~GfxDriverBase() {}
void Init() override {
// pVtxPool.Init(Config::NumVertices);
// pIdxPool.Init(Config::NumIndices);
SysInit();
std::vector<u8> img(16 * 16 * 4, 0xff);
pWhite = LoadTexture(img, 16, 16);
}
void Draw(const Pool<Li::Command>& commands) override {
CountCommands += commands.size();
size_t index = 0;
while (index < commands.size()) {
CurrentTex = commands[index].Tex;
if (!CurrentTex) {
CurrentTex = pWhite.GetID();
}
size_t startidx = CurrentIndex;
while (index < commands.size() &&
(CurrentTex == commands[index].Tex ||
(CurrentTex == pWhite.GetID() && commands[index].Tex == 0))) {
const auto& c = commands[index];
CountVertices += c.VertexCount;
CountIndices += c.IndexCount;
auto pIdx = pIdxPool.Allocate(c.IndexCount);
auto pVtx = pVtxPool.Allocate(c.VertexCount);
for (size_t i = 0; i < c.IndexCount; i++) {
pIdx[i] = CurrentVertex + c.FirstIndex[i];
}
CurrentIndex += c.IndexCount;
CurrentVertex += c.VertexCount;
for (size_t i = 0; i < c.VertexCount; i++) {
pVtx[i] = c.FirstVertex[i];
}
index++;
}
Submit(CurrentIndex - startidx, startidx);
}
}
protected:
u16* GetIndexBufPtr(size_t start) { return &pIdxPool[start]; }
Li::Vertex* GetVertexBufPtr(size_t start) { return &pVtxPool[start]; }
void ResetPools() override {
pVtxPool.Reset();
pIdxPool.Reset();
}
private:
VtxPool pVtxPool;
IdxPool pIdxPool;
};
class PD_API Gfx {
public:
Gfx() = default;
~Gfx() = default;
template <typename T, typename... Args>
static void UseDriver(Args&&... args) {
// assert(driver == nullptr && "OS Driver already set");
driver = std::make_unique<T>(std::forward<Args>(args)...);
}
static void Init() { driver->Init(); }
static void Deinit() { driver->Deinit(); }
static void SetViewPort(const ivec2& vp) { driver->SetViewPort(vp); }
static void SetViewPort(int w, int h) { driver->SetViewPort(w, h); }
static void Reset() { driver->Reset(); }
static void Draw(const Pool<Li::Command>& commands) {
driver->Draw(commands);
}
static Li::Texture LoadTexture(const std::vector<PD::u8>& pixels, int w,
int h,
TextureFormat type = TextureFormat::RGBA32,
TextureFilter filter = TextureFilter::Linear) {
return driver->LoadTexture(pixels, w, h, type, filter);
}
static void DeleteTexture(const Li::Texture& tex) {
driver->DeleteTexture(tex);
}
static Li::Texture::Ptr GetWhiteTexture() {
return driver->GetWhiteTexture();
}
static const char* GetDriverName() { return driver->GetName(); }
private:
static std::unique_ptr<GfxDriver> driver;
};
} // namespace PD

View File

@@ -0,0 +1,16 @@
#pragma once
#include <pd/common.hpp>
namespace PD {
class DriverInterface {
public:
DriverInterface(const std::string_view& name) : pName(name) {}
virtual ~DriverInterface() {}
const char* GetName() const { return pName.data(); }
private:
std::string_view pName;
};
} // namespace PD

32
include/pd/drivers/os.hpp Executable file
View File

@@ -0,0 +1,32 @@
#pragma once
#include <pd/drivers/interface.hpp>
namespace PD {
class PD_API OsDriver : public DriverInterface {
public:
OsDriver(std::string_view name = "Default") : DriverInterface(name) {}
virtual ~OsDriver() {}
virtual u64 GetTime() const;
virtual u64 GetTimeNano() const;
};
class PD_API Os {
public:
Os() = default;
~Os() = default;
template <typename T, typename... Args>
static void UseDriver(Args&&... args) {
// assert(driver == nullptr && "OS Driver already set");
driver = std::make_unique<T>(std::forward<Args>(args)...);
}
static u64 GetTime() { return driver->GetTime(); }
static u64 GetTimeNano() { return driver->GetTimeNano(); }
private:
static std::unique_ptr<OsDriver> driver;
};
} // namespace PD

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -1,82 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/core.hpp>
#include <pd/image/pd_p_api.hpp>
namespace PD {
class PD_IMAGE_API Image : public SmartCtor<Image> {
public:
enum Format {
RGBA, // bpp == 4
RGB, // bpp == 3
RGB565, // bpp == 2 (not supported in laoding)
BGR, // bpp == 3
ABGR // bpp == 4
};
Image() = default;
Image(const std::string& path) { this->Load(path); }
Image(const std::vector<u8>& buf) { this->Load(buf); }
Image(const std::vector<u8>& buf, int w, int h, int bpp = 4) {
this->Copy(buf, w, h, bpp);
}
~Image() = default;
void Load(const std::string& path);
void Load(const std::vector<u8>& buf);
void Copy(const std::vector<u8>& buf, int w, int h, int bpp = 4);
std::vector<PD::u8>& GetBuffer() { return pBuffer; }
std::vector<PD::u8> GetBuffer() const { return pBuffer; }
int Width() const { return pWidth; }
int Height() const { return pHeight; }
Format Fmt() const { return pFmt; }
u8& operator[](int idx) { return pBuffer[idx]; }
u8 operator[](int idx) const { return pBuffer[idx]; }
// Probably these make th eabove ones useless
operator std::vector<PD::u8>&() { return pBuffer; }
operator std::vector<PD::u8>() const { return pBuffer; }
static void Convert(Image::Ref img, Image::Format dst);
static void ReTile(Image::Ref img,
std::function<u32(int x, int y, int w)> src,
std::function<u32(int x, int y, int w)> dst);
static int Fmt2Bpp(Format fmt);
std::vector<PD::u8> pBuffer;
int pWidth;
int pHeight;
Format pFmt = Format::RGBA;
private:
/** Leftover variable used for stbi_load */
int fmt = 0;
};
} // namespace PD

View File

@@ -1,72 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/core.hpp>
#include <pd/image/pd_p_api.hpp>
namespace PD {
/**
* Namepace containing functions to blur images
*/
namespace ImgBlur {
/**
* Function to create Gaussian Kernel List
* @param radius Rasius to use
* @param si sigma value to use
* @return list of kernel values
*/
PD_IMAGE_API std::vector<float> GaussianKernel(int radius, float si);
/**
* Gaussian Blur for basic Image Buffer
* @param buf Image Buffer (unsigned char)
* @param w width of the image
* @param h width of the image
* @param radius Blur radius
* @param si Blur sigma
* @param idxfn Indexing function
*/
PD_IMAGE_API void GaussianBlur(
std::vector<u8> &buf, int w, int h, float radius, float si,
std::function<int(int, int, int)> idxfn = [](int x, int y, int w) -> int {
return y * w + x;
});
/**
* Advanced func to access memory directly
* @param buf Referenvce to the buffer
* @param w width of the image
* @param h width of the image
* @param bpp Bytes per Pixels (RGB[A], RGB565, etc)
* @param radius Blur radius
* @param si Blur sigma
* @param idxfn Indexing function
*/
PD_IMAGE_API void GaussianBlur(
void *buf, int w, int h, int bpp, float radius, float si,
std::function<int(int, int, int)> idxfn = [](int x, int y, int w) -> int {
return y * w + x;
});
} // namespace ImgBlur
} // namespace PD

View File

@@ -1,82 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/core.hpp>
#include <pd/image/image.hpp>
#include <pd/image/pd_p_api.hpp>
namespace PD {
/**
* Namespace containing function to convert images
*/
namespace ImgConvert {
/**
* Convert RGB24 to RGBA32 by adding a 4th alpha value set to 255
* to every pixel
* @param out Result List
* @param in Input Buffer List (rgb24)
* @param w width of the image
* @param h height of the image
*/
PD_IMAGE_API
void RGB24toRGBA32(std::vector<PD::u8> &out, const std::vector<u8> &in,
const int &w, const int &h);
PD_IMAGE_API
void RGB32toRGBA24(std::vector<u8> &out, const std::vector<u8> &in,
const int &w, const int &h);
/**
* Reverse 32 (RGBA -> ABGR || ABGR -> RGBA)
* @param buf Buffer to convert
* @param w width
* @param h height
*/
PD_IMAGE_API void Reverse32(std::vector<u8> &buf, const int &w, const int &h);
PD_IMAGE_API void ReverseBuf(std::vector<u8> &buf, size_t bpp, int w, int h);
/**
* Convert RGB24 to RGBA32 by adding a 4th alpha value set to 255
* to every pixel
* @param out Result List
* @param in Input Buffer List (rgb24)
* @param w width of the image
* @param h height of the image
*/
PD_IMAGE_API
void RGB24toRGBA32(PD::Vec<u8> &out, const PD::Vec<u8> &in, const int &w,
const int &h);
PD_IMAGE_API
void RGB32toRGBA24(PD::Vec<u8> &out, const PD::Vec<u8> &in, const int &w,
const int &h);
/**
* Reverse 32 (RGBA -> ABGR || ABGR -> RGBA)
* @param buf Buffer to convert
* @param w width
* @param h height
*/
PD_IMAGE_API void Reverse32(PD::Vec<u8> &buf, const int &w, const int &h);
PD_IMAGE_API void ReverseBuf(PD::Vec<u8> &buf, size_t bpp, int w, int h);
} // namespace ImgConvert
} // namespace PD

View File

@@ -1,52 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#ifdef _WIN32 // Windows (MSVC Tested)
#ifdef PD_IMAGE_BUILD_SHARED
#define PD_IMAGE_API __declspec(dllexport)
#else
#define PD_IMAGE_API __declspec(dllimport)
#endif
#elif defined(__APPLE__) // macOS (untested yet)
#ifdef PD_IMAGE_BUILD_SHARED
#define PD_IMAGE_API __attribute__((visibility("default")))
#else
#define PD_IMAGE_API
#endif
#elif defined(__linux__) // Linux (untested yet)
#ifdef PD_IMAGE_BUILD_SHARED
#define PD_IMAGE_API __attribute__((visibility("default")))
#else
#define PD_IMAGE_API
#endif
#elif defined(__3DS__) // 3ds Specific
// Only Static supported
#define PD_IMAGE_API
#else
#define PD_IMAGE_API
#endif

View File

@@ -0,0 +1,25 @@
#pragma once
#include <pd/core/core.hpp>
#include <pd/lithium/texture.hpp>
namespace PD {
namespace Li {
enum class AtlasState {
Invalid,
ReqCreate,
ReqUpdate,
ReqDestroy,
};
class Atlas {
public:
Atlas() {}
~Atlas() {}
private:
AtlasState pState = AtlasState::Invalid;
TextureID pID;
};
} // namespace Li
} // namespace PD

View File

@@ -1,76 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/core.hpp>
#include <pd/lithium/command.hpp>
#include <pd/lithium/rect.hpp>
#include <pd/lithium/texture.hpp>
using LIBackendFlags = PD::u32;
enum LIBackendFlags_ {
LIBackendFlags_None = 0,
LIBackendFlags_FlipUV_Y = 1 << 0, // Essential for Font Loading
};
namespace PD {
namespace LI {
class Backend {
public:
Backend(const std::string& name = "NullBackend") : pName(name) {}
~Backend() = default;
// Using Legacy SmartCTOR API here
PD_SMART_CTOR(Backend)
virtual void Init() {}
virtual void Deinit() {}
virtual void NewFrame() {}
virtual void BindTexture(TexAddress addr) {}
virtual void RenderDrawData(const Vec<Command::Ref>& Commands) {}
virtual Texture::Ref LoadTexture(
const std::vector<PD::u8>& pixels, int w, int h,
Texture::Type type = Texture::Type::RGBA32,
Texture::Filter filter = Texture::Filter::LINEAR) {
// Texture loading not supported (when this func not get override)
return nullptr;
}
/** Backend identification name */
const std::string pName = "NullBackend";
LIBackendFlags Flags = 0;
ivec2 ViewPort;
fvec4 ClearColor;
// Optional Index Counter
int IndexCounter = 0;
// Optional Vertex Counter
int VertexCounter = 0;
// Optional Frame Counter
int FrameCounter = 0;
};
} // namespace LI
} // namespace PD

View File

@@ -1,62 +1,61 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/core.hpp>
// #include <pd/lithium/flags.hpp>
#include <pd/lithium/texture.hpp>
#include <cstddef>
#include <pd/core/pool.hpp>
#include <pd/lithium/pools.hpp>
#include <pd/lithium/vertex.hpp>
namespace PD {
namespace LI {
/**
* Lithium Draw Command (containing a list of vertex and index data
* only for this specific command itself)
*/
class Command : public SmartCtor<Command> {
namespace Li {
class Command {
public:
Command() = default;
~Command() = default;
Command() { Reset(); }
~Command() {}
Command& AppendIndex(u16 idx) {
IndexBuffer.Add(VertexBuffer.Size() + idx);
void Reserve(size_t vtx, size_t idx) {
if (!FirstVertex)
FirstVertex = AllocateVertices(vtx);
else
AllocateVertices(vtx);
if (!FirstIndex)
FirstIndex = AllocateIndices(idx);
else
AllocateIndices(idx);
}
void Reset() {
Layer = 0;
Tex = 0;
FirstIndex = nullptr;
FirstVertex = nullptr;
IndexCount = 0;
VertexCount = 0;
}
Command& Add(const Vertex& vtx) {
FirstVertex[VertexCount++] = vtx;
return *this;
}
Command& Add(u16 idx) {
FirstIndex[IndexCount++] = VertexCount + idx;
return *this;
}
Command& Add(u16 a, u16 b, u16 c) {
FirstIndex[IndexCount++] = VertexCount + a;
FirstIndex[IndexCount++] = VertexCount + b;
FirstIndex[IndexCount++] = VertexCount + c;
return *this;
}
Command& AppendVertex(const Vertex& v) {
VertexBuffer.Add(v);
return *this;
}
Vec<Vertex> VertexBuffer;
Vec<u16> IndexBuffer;
ivec4 ScissorRect;
bool ScissorEnabled = false;
int Layer;
int Index;
Texture::Ref Tex;
int Layer = 0;
ptr Tex = 0;
Vertex* FirstVertex = nullptr;
u16* FirstIndex = nullptr;
size_t VertexCount = 0;
size_t IndexCount = 0;
// Todo: implement
size_t VertexCountMax = 0;
size_t IndexCountMax = 0;
};
} // namespace LI
} // namespace Li
} // namespace PD

View File

@@ -1,145 +1,116 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/lithium/command.hpp>
#include <pd/lithium/font.hpp>
#include <pd/lithium/pd_p_api.hpp>
#include <pd/lithium/texture.hpp>
using LiPathRectFlags = PD::u32;
enum LiPathRectFlags_ : PD::u32 {
LiPathRectFlags_None = 0,
LiPathRectFlags_KeepTopLeft = 1 << 0,
LiPathRectFlags_KeepTopRight = 1 << 1,
LiPathRectFlags_KeepBotRight = 1 << 2,
LiPathRectFlags_KeepBotLeft = 1 << 3,
LiPathRectFlags_KeepTop =
LiPathRectFlags_KeepTopLeft | LiPathRectFlags_KeepTopRight,
LiPathRectFlags_KeepBot =
LiPathRectFlags_KeepBotLeft | LiPathRectFlags_KeepBotRight,
LiPathRectFlags_KeepLeft =
LiPathRectFlags_KeepTopLeft | LiPathRectFlags_KeepBotLeft,
LiPathRectFlags_KeepRight =
LiPathRectFlags_KeepTopRight | LiPathRectFlags_KeepBotRight,
};
using LiDrawFlags = PD::u32;
enum LiDrawFlags_ : PD::u32 {
LiDrawFlags_None = 0,
LiDrawFlags_Close = 1 << 0,
};
using LiTextFlags = PD::u32;
enum LiTextFlags_ : PD::u32 {
LiTextFlags_None = 0, ///< Do nothing
LiTextFlags_AlignRight = 1 << 0, ///< Align Right of position
LiTextFlags_AlignMid = 1 << 1, ///< Align in the middle of pos and box
LiTextFlags_Shaddow = 1 << 2, ///< Draws the text twice to create shaddow
LiTextFlags_Wrap = 1 << 3, ///< Wrap Text: May be runs better with TMS
LiTextFlags_Short = 1 << 4, ///< Short Text: May be runs better with TMS
LiTextFlags_Scroll = 1 << 5, ///< Not implemented [scoll text if to long]
LiTextFlags_NoOOS = 1 << 6, ///< No Out of Screen Rendering
};
namespace PD {
namespace LI {
class PD_LITHIUM_API DrawList : public SmartCtor<DrawList> {
namespace Li {
class PD_API Drawlist {
public:
DrawList(Texture::Ref solid) {
WhitePixel = solid;
CurrentTex = solid;
}
~DrawList() {}
Drawlist();
~Drawlist();
Command::Ref PreGenerateCmd();
void AddCommand(Command::Ref v) { pDrawList.Add(v); }
void Clear() { pDrawList.Clear(); }
/** Baisc */
void SetFont(Font::Ref font) { pCurrentFont = font; }
void SetFontScale(float scale) { pFontScale = scale; }
void Merge(Drawlist& other);
void Copy(Drawlist& other);
void Optimize();
void Clear();
void DrawSolid() { CurrentTex = WhitePixel; }
void DrawTexture(Texture::Ref tex) { CurrentTex = tex; }
/** Command Allocation */
Command& NewCommand();
// SECTION: Draw API //
/** Path API */
void PathAdd(const fvec2& point) { pPath.Push(point); }
void PathAdd(float x, float y) { pPath.Push(fvec2(x, y)); }
void PathClear() { pPath.Reset(); }
/**
* @brief Reserve memory for the next PathAdd uses
* @note As path will autoexpant and keep the size this func is
* only for special use cases
*/
void PathReserve(size_t num) { pPath.ExpandIf(num); }
void PathStroke(u32 color, int t = 1, LiDrawFlags flags = LiDrawFlags_None);
void PathFill(u32 color);
void PathArcToN(const fvec2& c, float r, float amin, float amax, int s);
void PathFastArcToN(const fvec2& c, float r, float amin, float amax, int s);
void PathRect(const fvec2& tl, const fvec2& br, float r = 0.f);
void PathRectEx(const fvec2& tl, const fvec2& br, float r = 0.f,
LiPathRectFlags flags = LiPathRectFlags_None);
void DrawRect(const fvec2& pos, const fvec2& size, u32 color,
int thickness = 1);
/** Texture Handling */
void BindTexture(const Texture& tex);
void UnbindTexture() { pCurrentTexture = Texture(); }
/** Data geters */
const Pool<Command>& Data() const { return pCommands; }
operator const Pool<Command>&() const { return pCommands; }
/** Drawing functions */
void DrawRect(const fvec2& pos, const fvec2& size, u32 color, int t = 1);
void DrawRectFilled(const fvec2& pos, const fvec2& size, u32 color);
void DrawTriangle(const fvec2& a, const fvec2& b, const fvec2& c, u32 color,
int thickness = 1);
int t = 1);
void DrawTriangleFilled(const fvec2& a, const fvec2& b, const fvec2& c,
u32 color);
void DrawCircle(const fvec2& center, float rad, u32 color, int num_segments,
int thickness = 1);
int t = 1);
void DrawCircleFilled(const fvec2& center, float rad, u32 color,
int num_segments);
void DrawText(const fvec2& p, const std::string& text, u32 color);
void DrawText(const fvec2& p, const char* text, u32 color);
void DrawTextEx(const fvec2& p, const char* text, u32 color,
LiTextFlags flags, const fvec2& box = fvec2(0.f));
/**
* Take list of points and display it as a line on screen
* @param points List of Positions
* @param clr Color of the Line
* @param flags Additional Flags (Close for go back to starting point)
* @param thickness Thickness of the Line
*/
void DrawPolyLine(const Vec<fvec2>& points, u32 clr, u32 flags = 0,
int thickness = 1);
/**
* Take a List ofpoints and display it as Filled Shape
* @note Keep in mind to setup the list of points clockwise
* @param points List of Points
* @param clr Color of the shape
*/
void DrawConvexPolyFilled(const Vec<fvec2>& points, u32 clr);
void DrawPolyLine(const Pool<fvec2>& points, u32 color,
LiDrawFlags flags = LiDrawFlags_None, int t = 1);
void DrawConvexPolyFilled(const Pool<fvec2>& points, u32 color);
// SECTION: PATH API //
void PrimQuad(Command& cmd, const Rect& quad, const Rect& uv, u32 color);
void PrimTriangle(Command& cmd, const fvec2& a, const fvec2& b,
const fvec2& c, u32 color);
/**
* Function to reserve Memory to prevent overhead on
* pusing a lot of points with PathNext
* @param num_points Number of Positions you want to add
*/
void PathReserve(size_t num_points) {
pPath.Reserve(pPath.Size() + num_points);
}
/**
* Clear current Path
* @note PathStroke and PathFill will automatically clear
*/
void PathClear() { pPath.Clear(); }
/**
* Add a Point to the Path
* @note Keep in mind that this function is used for
* setting the starting point
* @param v Position to add
*/
void PathAdd(const fvec2& v) { pPath.Add(v); }
/**
* Path Stroke Create Line from point to point
* @note For Primitives like Rect or Triangle mak sure to use
* UI7DrawFlags_Close to add a line back to the starting point
* @param clr Color od the line
* @param thickness Thickness of the line
* @param flags Additional Drawflags
*/
void PathStroke(u32 clr, int thickness = 1, u32 flags = 0) {
DrawPolyLine(pPath, clr, flags, thickness);
pPath.Clear();
}
/**
* Fill a Path with a Color
* @note **IMPORTANT: ** Paths need to be setup clockwise
* to be rendered correctly
* @param clr Fill Color
*/
void PathFill(u32 clr) {
DrawConvexPolyFilled(pPath, clr);
pPath.Clear();
}
void PathArcToN(const fvec2& c, float radius, float a_min, float a_max,
int segments);
/// @brief Create a Path Rect (uses to Positions instead of Pos/Size)
/// @param a Top Left Position
/// @param b Bottom Right Position
/// @param rounding rounding
/// @param flags DrawFlags (for special rounding rules)
void PathRect(fvec2 a, fvec2 b, float rounding = 0.f, u32 flags = 0);
int Layer = 0;
float pFontScale = 0.7f;
Font::Ref pCurrentFont = nullptr;
Texture::Ref CurrentTex = nullptr;
Texture::Ref WhitePixel = nullptr;
PD::Vec<Command::Ref> pDrawList;
PD::Vec<fvec2> pPath;
private:
Texture pCurrentTexture;
Pool<Command> pCommands;
Pool<fvec2> pPath;
Pool<Vertex> pVertices;
Pool<u16> pIndices;
};
} // namespace LI
} // namespace Li
} // namespace PD

View File

@@ -1,95 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <pd/core/core.hpp>
#include <pd/lithium/backend.hpp>
#include <pd/lithium/pd_p_api.hpp>
#include <pd/lithium/rect.hpp>
#include <pd/lithium/texture.hpp>
using LITextFlags = PD::u32;
enum LITextFlags_ {
LITextFlags_None = 0, ///< Do nothing
LITextFlags_AlignRight = 1 << 0, ///< Align Right of position
LITextFlags_AlignMid = 1 << 1, ///< Align in the middle of pos and box
LITextFlags_Shaddow = 1 << 2, ///< Draws the text twice to create shaddow
LITextFlags_Wrap = 1 << 3, ///< Wrap Text: May be runs better with TMS
LITextFlags_Short = 1 << 4, ///< Short Text: May be runs better with TMS
LITextFlags_Scroll = 1 << 5, ///< Not implemented [scoll text if to long]
};
namespace PD {
namespace LI {
/** Font Loader for Lithium */
class PD_LITHIUM_API Font : public SmartCtor<Font> {
public:
/** Codepoint Data holder */
struct Codepoint {
u32 pCodepoint = 0;
fvec4 SimpleUV;
Texture::Ref Tex;
fvec2 Size;
float Offset = 0.f;
bool pInvalid = false;
};
Font(Backend::Ref backend) { pBackend = backend; };
~Font() = default;
/**
* Load a TTF File
* @param path Path to the TTF file
* @param px_height Pixelheight of the codepoints (limit by 64)
*/
void LoadTTF(const std::string& path, int px_height = 32);
/**
* Getter for Codepoint reference
* @return codepoint dataholder reference
*/
Codepoint& GetCodepoint(u32 c);
/**
* Get Text Bounding Box
*/
fvec2 GetTextBounds(const std::string& text, float scale);
/**
* Extended Draw Text Function that vreates a Command List
*/
void CmdTextEx(Vec<Command::Ref>& cmds, const fvec2& pos, u32 color,
float scale, const std::string& text, LITextFlags flags = 0,
const fvec2& box = 0);
/** Pixelheight */
int PixelHeight;
int DefaultPixelHeight = 24;
private:
/** List of textures (codepoints are using) */
std::vector<Texture::Ref> Textures;
/** 32Bit Codepoint Dataholder Reference Map */
std::map<u32, Codepoint> CodeMap;
Backend::Ref pBackend = nullptr;
};
} // namespace LI
} // namespace PD

View File

@@ -0,0 +1,109 @@
#pragma once
#include <pd/lithium/atlas.hpp>
#include <pd/lithium/rect.hpp>
#include <pd/lithium/texture.hpp>
#include <pd/lithium/vertex.hpp>
template <>
struct std::formatter<PD::TextureFilter> {
constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
template <typename FormatContext>
auto format(const PD::TextureFilter& value, FormatContext& ctx) const {
std::string_view ret = "Unknown";
switch (value) {
case PD::TextureFilter::Linear:
ret = "Linear";
break;
case PD::TextureFilter::Nearest:
ret = "Nearest";
break;
}
return std::format_to(ctx.out(), "{}", ret);
}
};
template <>
struct std::formatter<PD::TextureFormat> {
constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
template <typename FormatContext>
auto format(const PD::TextureFormat& value, FormatContext& ctx) const {
std::string_view ret = "Unknown";
switch (value) {
case PD::TextureFormat::RGBA32:
ret = "RGBA32";
break;
case PD::TextureFormat::RGB24:
ret = "RGB24";
break;
case PD::TextureFormat::A8:
ret = "A8";
break;
}
return std::format_to(ctx.out(), "{}", ret);
}
};
template <>
struct std::formatter<PD::Li::Rect> : std::formatter<std::string> {
constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
template <typename FormatContext>
auto format(const PD::Li::Rect& value, FormatContext& ctx) const {
// {l, t, r, t, l, b, r, b}
return std::format_to(ctx.out(), "{}, {}, {}, {}, {}, {}, {}, {}",
value.Top.x, value.Top.y, value.Top.z, value.Top.w,
value.Bot.x, value.Bot.y, value.Bot.z, value.Bot.w);
}
};
template <>
struct std::formatter<PD::Li::Texture> : std::formatter<std::string> {
constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
template <typename FormatContext>
auto format(const PD::Li::Texture& value, FormatContext& ctx) const {
// {ID, [w, h], [l, t, r, t, l, b, r, b]}
return std::format_to(ctx.out(), "{}, [{}], [{}]", value.GetID(),
value.GetSize(), value.GetUV());
}
};
template <>
struct std::formatter<PD::Li::Vertex> : std::formatter<std::string> {
constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
template <typename FormatContext>
auto format(const PD::Li::Vertex& value, FormatContext& ctx) const {
// { [x, y], [u, v], colorhex }
return std::format_to(ctx.out(), "[{}], [{}], #{:08X}", value.pos, value.uv,
value.color);
}
};
template <>
struct std::formatter<PD::Li::AtlasState> : std::formatter<std::string> {
constexpr auto parse(std::format_parse_context& ctx) { return ctx.begin(); }
template <typename FormatContext>
auto format(const PD::Li::AtlasState& value, FormatContext& ctx) const {
std::string_view ret = "Unknown";
switch (value) {
case PD::Li::AtlasState::Invalid:
ret = "Invalid";
break;
case PD::Li::AtlasState::ReqCreate:
ret = "RequestCreate";
break;
case PD::Li::AtlasState::ReqUpdate:
ret = "RequestUpdate";
break;
case PD::Li::AtlasState::ReqDestroy:
ret = "RequestDestroy";
break;
}
return std::format_to(ctx.out(), "{}", ret);
}
};

View File

@@ -0,0 +1,7 @@
#pragma once
#include <pd/lithium/command.hpp>
#include <pd/lithium/drawlist.hpp>
#include <pd/lithium/math.hpp>
#include <pd/lithium/pools.hpp>
#include <pd/lithium/vertex.hpp>

View File

@@ -0,0 +1,18 @@
#pragma once
#include <pd/core/core.hpp>
#include <pd/lithium/rect.hpp>
namespace PD {
namespace Li {
namespace Math {
PD_API bool InBounds(const fvec2& pos, const fvec2& size, const fvec4& rect);
PD_API bool InBounds(const fvec2& pos, const fvec4& rect);
PD_API bool InBounds(const fvec2& a, const fvec2& b, const fvec2& c,
const fvec4& rect);
PD_API void RotateCorner(fvec2& pos, float sinus, float cosinus);
PD_API Rect PrimRect(const fvec2& pos, const fvec2& size, float angle = 0.f);
PD_API Rect PrimLine(const fvec2& a, const fvec2& b, int t = 1);
} // namespace Math
} // namespace Li
} // namespace PD

View File

@@ -1,52 +0,0 @@
#pragma once
/*
MIT License
Copyright (c) 2024 - 2025 tobid7
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#pragma once
#ifdef _WIN32 // Windows (MSVC Tested)
#ifdef PD_LITHIUM_BUILD_SHARED
#define PD_LITHIUM_API __declspec(dllexport)
#else
#define PD_LITHIUM_API __declspec(dllimport)
#endif
#elif defined(__APPLE__) // macOS (untested yet)
#ifdef PD_LITHIUM_BUILD_SHARED
#define PD_LITHIUM_API __attribute__((visibility("default")))
#else
#define PD_LITHIUM_API
#endif
#elif defined(__linux__) // Linux (untested yet)
#ifdef PD_LITHIUM_BUILD_SHARED
#define PD_LITHIUM_API __attribute__((visibility("default")))
#else
#define PD_LITHIUM_API
#endif
#elif defined(__3DS__) // 3ds Specific
// Only Static supported
#define PD_LITHIUM_API
#else
#define PD_LITHIUM_API
#endif

View File

@@ -0,0 +1,12 @@
#pragma once
#include <cstddef>
#include <pd/lithium/vertex.hpp>
namespace PD {
namespace Li {
PD_API Vertex* AllocateVertices(size_t count);
PD_API u16* AllocateIndices(size_t count);
PD_API void ResetPools();
} // namespace Li
} // namespace PD

View File

@@ -2,7 +2,7 @@
/*
MIT License
Copyright (c) 2024 - 2025 René Amthor (tobid7)
Copyright (c) 2024 - 2026 René Amthor (tobid7)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
@@ -26,24 +26,20 @@ SOFTWARE.
#include <pd/core/core.hpp>
namespace PD {
namespace LI {
/**
* Container that holds position of a rectangle's corners.
*/
namespace Li {
class Rect {
public:
Rect() = default;
Rect() : Top(0), Bot(0) {}
~Rect() = default;
/**
* Constructor that initializes the rectangle using top and bottom positions.
* @param t Top left and right corner positions.
* @param b Bottom left and right corner positions.
*/
Rect(const fvec4& t, const fvec4& b) {
top = t;
bot = b;
Top = t;
Bot = b;
}
/**
* Constructor that initializes the rectangle using individual corner
* positions.
@@ -53,8 +49,8 @@ class Rect {
* @param br Bottom right corner position.
*/
Rect(const fvec2& tl, const fvec2& tr, const fvec2& bl, const fvec2& br) {
top = fvec4(tl, tr);
bot = fvec4(bl, br);
Top = fvec4(tl, tr);
Bot = fvec4(bl, br);
}
/**
@@ -66,67 +62,30 @@ class Rect {
* @param uv Vec4 UV map.
*/
Rect(const fvec4& uv) {
top = vec4(uv.x, uv.y, uv.z, uv.y);
bot = vec4(uv.x, uv.w, uv.z, uv.w);
}
~Rect() = default;
/**
* Get the top left and right corner positions.
* @return Top positions.
*/
fvec4 Top() const { return top; }
/**
* Get the bottom left and right corner positions.
* @return Bottom positions.
*/
fvec4 Bot() const { return bot; }
/**
* Set the top left and right corner positions.
* @param v New top positions.
* @return Reference to the updated Rect.
*/
Rect& Top(const fvec4& v) {
top = v;
return *this;
}
/**
* Set the bottom left and right corner positions.
* @param v New bottom positions.
* @return Reference to the updated Rect.
*/
Rect& Bot(const fvec4& v) {
bot = v;
return *this;
Top = vec4(uv.x, uv.y, uv.z, uv.y);
Bot = vec4(uv.x, uv.w, uv.z, uv.w);
}
/**
* Get the top-left corner position.
* @return Top-left position as vec2.
*/
fvec2 TopLeft() const { return vec2(top.x, top.y); }
fvec2 TopLeft() const { return fvec2(Top.x, Top.y); }
/**
* Get the top-right corner position.
* @return Top-right position as vec2.
*/
fvec2 TopRight() const { return vec2(top.z, top.w); }
fvec2 TopRight() const { return fvec2(Top.z, Top.w); }
/**
* Get the bottom-left corner position.
* @return Bottom-left position as vec2.
*/
fvec2 BotLeft() const { return vec2(bot.x, bot.y); }
fvec2 BotLeft() const { return fvec2(Bot.x, Bot.y); }
/**
* Get the bottom-right corner position.
* @return Bottom-right position as vec2.
*/
fvec2 BotRight() const { return vec2(bot.z, bot.w); }
fvec2 BotRight() const { return fvec2(Bot.z, Bot.w); }
/**
* Set the top-left corner position.
@@ -134,8 +93,8 @@ class Rect {
* @return Reference to the updated Rect.
*/
Rect& TopLeft(const fvec2& v) {
top.x = v.x;
top.y = v.y;
Top.x = v.x;
Top.y = v.y;
return *this;
}
@@ -145,8 +104,8 @@ class Rect {
* @return Reference to the updated Rect.
*/
Rect& TopRight(const fvec2& v) {
top.z = v.x;
top.w = v.y;
Top.z = v.x;
Top.w = v.y;
return *this;
}
@@ -156,8 +115,8 @@ class Rect {
* @return Reference to the updated Rect.
*/
Rect& BotLeft(const fvec2& v) {
bot.x = v.x;
bot.y = v.y;
Bot.x = v.x;
Bot.y = v.y;
return *this;
}
@@ -167,26 +126,24 @@ class Rect {
* @return Reference to the updated Rect.
*/
Rect& BotRight(const fvec2& v) {
bot.z = v.x;
bot.w = v.y;
Bot.z = v.x;
Bot.w = v.y;
return *this;
}
/**
* Swap X and Y coordinates for all corners.
*
* - Used in SpiteSheet for the rotated images.
*/
bool operator==(const Rect& r) const { return Top == r.Top && Bot == r.Bot; }
void SwapVec2XY() {
top.SwapXY();
top.SwapZW();
bot.SwapXY();
bot.SwapZW();
Top.SwapXY();
Top.SwapZW();
Bot.SwapXY();
Bot.SwapZW();
}
private:
fvec4 top; ///< Top left and right corner positions.
fvec4 bot; ///< Bottom left and right corner positions.
/** Data Section */
fvec4 Top;
fvec4 Bot;
};
} // namespace LI
} // namespace Li
} // namespace PD

Some files were not shown because too many files have changed in this diff Show More