Compare commits
116 Commits
win_build
...
55bbfe2966
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
55bbfe2966 | ||
|
|
55aa2217cf | ||
|
|
a029c416d5 | ||
|
|
e588364b08 | ||
|
|
baa923342b | ||
|
|
523306dcc3 | ||
|
|
d802d3d066 | ||
|
|
0547ee347d | ||
|
|
55350a9a3b | ||
|
|
25a246f3ff | ||
|
|
0ee43d2f48 | ||
|
|
c7ae2c6c14 | ||
|
|
ec3022d43e | ||
|
|
e00c02e176 | ||
|
|
9b4b852872 | ||
|
|
a42d7c578d | ||
|
|
2f1c285a93 | ||
|
|
30eecc366e | ||
|
|
69d08e5310 | ||
|
|
434f808095 | ||
|
|
9c1ec01ce0 | ||
|
|
193310f704 | ||
|
|
fc15b132f2 | ||
|
|
a2c77966b8 | ||
|
|
d1cb6dbac7 | ||
|
|
3c2b636ea8 | ||
|
|
cfe48661d8 | ||
|
|
b94b18993d | ||
|
|
b2e9c1b55e | ||
|
|
057842ca7b | ||
|
|
370fc98588 | ||
|
|
6d040cb61f | ||
|
|
f979005208 | ||
|
|
a4e44e6cb8 | ||
|
|
836731b971 | ||
|
|
5209e054e5 | ||
|
|
5d35a3e92d | ||
|
|
3a8dce8996 | ||
|
|
b25d006b9e | ||
|
|
e117e85e7f | ||
|
|
935c74864c | ||
|
|
fdda4fe9f0 | ||
|
|
43f7432cb0 | ||
|
|
e5f5fea992 | ||
|
|
f982c3b55f | ||
|
|
bc65b05854 | ||
|
|
3064af65aa | ||
|
|
256cd7a431 | ||
|
|
f574f604d3 | ||
|
|
b4fcd56f10 | ||
|
|
2f346c11c3 | ||
|
|
df6d323e42 | ||
|
|
1ce793c6e8 | ||
|
|
d3af793092 | ||
|
|
4b3a4c53e8 | ||
|
|
370df129a8 | ||
|
|
08b4b10113 | ||
|
|
250f0963c8 | ||
|
|
3d34b68133 | ||
|
|
2f80129dce | ||
|
|
8a9aa8ee5e | ||
|
|
536618d7a7 | ||
|
|
038ea4f9c2 | ||
|
|
e1fa58e11a | ||
|
|
69e319a730 | ||
|
|
783200733a | ||
|
|
582e3e1adc | ||
|
|
81f7de05fb | ||
|
|
4e950c15a5 | ||
|
|
11fbcbbb10 | ||
|
|
71e6bdb904 | ||
|
|
f5304d045d | ||
|
|
d924e7dbca | ||
|
|
4a9498a520 | ||
|
|
f458468644 | ||
|
|
75eeac06df | ||
|
|
326094caf3 | ||
|
|
8a49c12909 | ||
|
|
47977d9979 | ||
|
|
92b36a8943 | ||
|
|
0e17c84eb9 | ||
|
|
a022c3321e | ||
|
|
8e00c1fed3 | ||
|
|
1defbe8a00 | ||
|
|
02a2ba2818 | ||
|
|
ec64c05bf0 | ||
|
|
427d3878c3 | ||
|
|
0f89ca9020 | ||
|
|
e25ce9604d | ||
|
|
6ce349e976 | ||
|
|
1779fde397 | ||
|
|
b6d24da982 | ||
|
|
c42a6b647e | ||
|
|
7eee6a5c54 | ||
|
|
2dd44ab169 | ||
|
|
5cd3a68e6d | ||
|
|
86d52edfd7 | ||
|
|
1b0edb664c | ||
|
|
76f10725ec | ||
|
|
e6fc4e881c | ||
|
|
ea316ab997 | ||
|
|
9b08c057e0 | ||
|
|
ec57ce7418 | ||
|
|
c55e76a4ba | ||
|
|
1941c4c29a | ||
|
|
e31a45b229 | ||
|
|
33813c135f | ||
|
|
70a9e6a80f | ||
|
|
4419e9bac9 | ||
|
|
82eb2e2539 | ||
|
|
f9b76687b3 | ||
|
|
1aebe47acf | ||
|
|
bf7c1ab2a7 | ||
|
|
9913d5b938 | ||
|
|
83d18443c3 | ||
|
|
bdac14c6cb |
297
.clang-format
Normal file
297
.clang-format
Normal file
@@ -0,0 +1,297 @@
|
||||
---
|
||||
Language: Cpp
|
||||
AccessModifierOffset: -2
|
||||
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: Right
|
||||
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: Never
|
||||
AllowShortLambdasOnASingleLine: All
|
||||
AllowShortLoopsOnASingleLine: false
|
||||
AllowShortNamespacesOnASingleLine: false
|
||||
AlwaysBreakAfterDefinitionReturnType: None
|
||||
AlwaysBreakBeforeMultilineStrings: false
|
||||
AttributeMacros:
|
||||
- __capability
|
||||
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: MultiLine
|
||||
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: Preserve
|
||||
IncludeCategories:
|
||||
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
|
||||
Priority: 2
|
||||
SortPriority: 0
|
||||
CaseSensitive: false
|
||||
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
|
||||
Priority: 3
|
||||
SortPriority: 0
|
||||
CaseSensitive: false
|
||||
- Regex: '.*'
|
||||
Priority: 1
|
||||
SortPriority: 0
|
||||
CaseSensitive: false
|
||||
IncludeIsMainRegex: '(Test)?$'
|
||||
IncludeIsMainSourceRegex: ''
|
||||
IndentAccessModifiers: false
|
||||
IndentCaseBlocks: false
|
||||
IndentCaseLabels: false
|
||||
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: true
|
||||
AtStartOfFile: true
|
||||
KeepFormFeed: false
|
||||
LambdaBodyIndentation: Signature
|
||||
LineEnding: DeriveLF
|
||||
MacroBlockBegin: ''
|
||||
MacroBlockEnd: ''
|
||||
MainIncludeChar: Quote
|
||||
MaxEmptyLinesToKeep: 1
|
||||
NamespaceIndentation: None
|
||||
ObjCBinPackProtocolList: Auto
|
||||
ObjCBlockIndentWidth: 2
|
||||
ObjCBreakBeforeNestedBlockParam: true
|
||||
ObjCSpaceAfterProperty: false
|
||||
ObjCSpaceBeforeProtocolList: true
|
||||
OneLineFormatOffRegex: ''
|
||||
PackConstructorInitializers: BinPack
|
||||
PenaltyBreakAssignment: 2
|
||||
PenaltyBreakBeforeFirstCallParameter: 19
|
||||
PenaltyBreakBeforeMemberAccess: 150
|
||||
PenaltyBreakComment: 300
|
||||
PenaltyBreakFirstLessLess: 120
|
||||
PenaltyBreakOpenParenthesis: 0
|
||||
PenaltyBreakScopeResolution: 500
|
||||
PenaltyBreakString: 1000
|
||||
PenaltyBreakTemplateDeclaration: 10
|
||||
PenaltyExcessCharacter: 1000000
|
||||
PenaltyIndentedWhitespace: 0
|
||||
PenaltyReturnTypeOnItsOwnLine: 60
|
||||
PointerAlignment: Right
|
||||
PPIndentWidth: -1
|
||||
QualifierAlignment: Leave
|
||||
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: 1
|
||||
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: Latest
|
||||
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
|
||||
...
|
||||
|
||||
26
.clang-uml
Normal file
26
.clang-uml
Normal file
@@ -0,0 +1,26 @@
|
||||
# When configuring with cmake, use:
|
||||
# cmake -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DCMAKE_BUILD_TYPE=Debug
|
||||
compilation_database_dir: build
|
||||
|
||||
# Path to system header needs to be specified,
|
||||
# you will probably need to modify this
|
||||
add_compile_flags:
|
||||
- '-I/usr/lib/clang/21/include'
|
||||
|
||||
output_directory: docs/diagrams
|
||||
diagrams:
|
||||
class_diagram:
|
||||
type: class
|
||||
glob:
|
||||
- cpp/src/**/*.cpp
|
||||
- cpp/src/**/*.hpp
|
||||
include_diagram:
|
||||
type: include
|
||||
glob:
|
||||
- cpp/src/**/*.cpp
|
||||
# Include also external system headers
|
||||
#generate_system_headers: true
|
||||
include:
|
||||
# Include only files belonging to these paths
|
||||
paths:
|
||||
- cpp/src
|
||||
12
.gitignore
vendored
12
.gitignore
vendored
@@ -1,4 +1,8 @@
|
||||
tags
|
||||
python/.ipynb_checkpoints
|
||||
cpp/test
|
||||
cpp/pathfinding
|
||||
tags
|
||||
python/.ipynb_checkpoints
|
||||
cpp/build
|
||||
cpp/pathfinding
|
||||
.aider*
|
||||
build
|
||||
.vscode
|
||||
docs/diagrams/*puml
|
||||
|
||||
9
.gitmodules
vendored
9
.gitmodules
vendored
@@ -1,9 +0,0 @@
|
||||
[submodule "vs/SDL"]
|
||||
path = vs/SDL
|
||||
url = https://github.com/libsdl-org/SDL.git
|
||||
[submodule "vs/glew"]
|
||||
path = vs/glew
|
||||
url = gitea@gitea.veleslabs.org:jan.mrna/glew.git
|
||||
[submodule "vs/SDL_image"]
|
||||
path = vs/SDL_image
|
||||
url = https://github.com/libsdl-org/SDL_image.git
|
||||
203
CMakeLists.txt
Normal file
203
CMakeLists.txt
Normal file
@@ -0,0 +1,203 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
|
||||
# Vcpkg integration for Windows
|
||||
if(WIN32)
|
||||
# Try to find vcpkg automatically
|
||||
if(DEFINED ENV{VCPKG_ROOT})
|
||||
set(CMAKE_TOOLCHAIN_FILE "$ENV{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"
|
||||
CACHE STRING "Vcpkg toolchain file")
|
||||
message(STATUS "Using vcpkg from: $ENV{VCPKG_ROOT}")
|
||||
elseif(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake")
|
||||
set(CMAKE_TOOLCHAIN_FILE "${CMAKE_CURRENT_SOURCE_DIR}/vcpkg/scripts/buildsystems/vcpkg.cmake"
|
||||
CACHE STRING "Vcpkg toolchain file")
|
||||
message(STATUS "Using local vcpkg installation")
|
||||
else()
|
||||
message(WARNING "vcpkg not found. Please set VCPKG_ROOT environment variable or install vcpkg locally.")
|
||||
message(STATUS "To install dependencies with vcpkg:")
|
||||
message(STATUS " vcpkg install sdl3 sdl3-image glew opengl gtest")
|
||||
endif()
|
||||
endif()
|
||||
|
||||
project(PathfindingDemo)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 23)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
# Platform-specific package finding
|
||||
if(WIN32)
|
||||
# Windows: Use vcpkg-compatible find_package with CONFIG
|
||||
find_package(SDL3 CONFIG REQUIRED)
|
||||
find_package(SDL3_image CONFIG REQUIRED)
|
||||
find_package(OpenGL REQUIRED)
|
||||
find_package(GLEW REQUIRED)
|
||||
find_package(GTest CONFIG REQUIRED)
|
||||
|
||||
# Set vcpkg target names for consistent linking
|
||||
set(SDL3_TARGET SDL3::SDL3)
|
||||
set(SDL3_IMAGE_TARGET $<IF:$<TARGET_EXISTS:SDL3_image::SDL3_image-shared>,SDL3_image::SDL3_image-shared,SDL3_image::SDL3_image-static>)
|
||||
set(GLEW_TARGET GLEW::GLEW)
|
||||
else()
|
||||
# Linux/Unix: Use pkg-config
|
||||
find_package(PkgConfig REQUIRED)
|
||||
pkg_check_modules(SDL3 REQUIRED sdl3)
|
||||
pkg_check_modules(SDL3_image REQUIRED sdl3-image)
|
||||
find_package(OpenGL REQUIRED)
|
||||
find_package(GLEW REQUIRED)
|
||||
find_package(GTest REQUIRED)
|
||||
|
||||
# Set target names for Unix systems
|
||||
set(SDL3_TARGET ${SDL3_LIBRARIES})
|
||||
set(SDL3_IMAGE_TARGET ${SDL3_image_LIBRARIES})
|
||||
set(GLEW_TARGET GLEW::GLEW)
|
||||
|
||||
# Enable clang-tidy
|
||||
set(CMAKE_CXX_CLANG_TIDY "clang-tidy")
|
||||
endif()
|
||||
|
||||
# Include directories
|
||||
include_directories(cpp/src)
|
||||
|
||||
# Source files for the main executable
|
||||
set(MAIN_SOURCES
|
||||
cpp/src/main.cpp
|
||||
cpp/src/camera.cpp
|
||||
cpp/src/entities.cpp
|
||||
cpp/src/gameloop.cpp
|
||||
cpp/src/map.cpp
|
||||
cpp/src/pathfinder/base.cpp
|
||||
cpp/src/pathfinder/bfs.cpp
|
||||
cpp/src/pathfinder/dijkstra.cpp
|
||||
cpp/src/pathfinder/gbfs.cpp
|
||||
cpp/src/pathfinder/utils.cpp
|
||||
cpp/src/pathfindingdemo.cpp
|
||||
cpp/src/sprite.cpp
|
||||
cpp/src/tile.cpp
|
||||
cpp/src/user_input.cpp
|
||||
cpp/src/window.cpp
|
||||
)
|
||||
|
||||
# Header files (for IDE support)
|
||||
set(HEADERS
|
||||
cpp/src/array.hpp
|
||||
cpp/src/camera.hpp
|
||||
cpp/src/entities.hpp
|
||||
cpp/src/gameloop.hpp
|
||||
cpp/src/log.hpp
|
||||
cpp/src/map.hpp
|
||||
cpp/src/math.hpp
|
||||
cpp/src/pathfinder/base.hpp
|
||||
cpp/src/pathfinder/bfs.hpp
|
||||
cpp/src/pathfinder/dijkstra.hpp
|
||||
cpp/src/pathfinder/gbfs.hpp
|
||||
cpp/src/pathfinder/utils.hpp
|
||||
cpp/src/pathfindingdemo.hpp
|
||||
cpp/src/sprite.hpp
|
||||
cpp/src/tile.hpp
|
||||
cpp/src/user_input.hpp
|
||||
cpp/src/window.hpp
|
||||
)
|
||||
|
||||
# Create main executable
|
||||
add_executable(pathfinding_demo ${MAIN_SOURCES} ${HEADERS})
|
||||
|
||||
# Platform-specific linking
|
||||
if(WIN32)
|
||||
# Windows: Use vcpkg targets
|
||||
target_link_libraries(pathfinding_demo
|
||||
${SDL3_TARGET}
|
||||
${SDL3_IMAGE_TARGET}
|
||||
OpenGL::GL
|
||||
${GLEW_TARGET}
|
||||
)
|
||||
|
||||
# Add compile flags for Windows (vcpkg handles most of this automatically)
|
||||
if(MSVC)
|
||||
if(SDL3_CFLAGS_OTHER)
|
||||
target_compile_options(pathfinding_demo PRIVATE ${SDL3_CFLAGS_OTHER})
|
||||
endif()
|
||||
endif()
|
||||
else()
|
||||
# Unix/Linux: Use pkg-config variables
|
||||
target_link_libraries(pathfinding_demo
|
||||
${SDL3_TARGET}
|
||||
${SDL3_IMAGE_TARGET}
|
||||
OpenGL::GL
|
||||
${GLEW_TARGET}
|
||||
)
|
||||
|
||||
# Add compile flags for Unix/Linux
|
||||
target_compile_options(pathfinding_demo PRIVATE ${SDL3_CFLAGS_OTHER})
|
||||
endif()
|
||||
|
||||
|
||||
# Copy resources after build
|
||||
add_custom_command(TARGET pathfinding_demo POST_BUILD
|
||||
COMMAND ${CMAKE_COMMAND} -E copy_directory
|
||||
${CMAKE_SOURCE_DIR}/cpp/resources
|
||||
$<TARGET_FILE_DIR:pathfinding_demo>/resources
|
||||
)
|
||||
|
||||
# Unit tests executable
|
||||
add_executable(unit_tests
|
||||
cpp/test/test.cpp
|
||||
)
|
||||
if(WIN32)
|
||||
target_link_libraries(unit_tests GTest::gtest GTest::gtest_main GTest::gmock GTest::gmock_main)
|
||||
else()
|
||||
target_link_libraries(unit_tests GTest::gtest GTest::gtest_main)
|
||||
endif()
|
||||
|
||||
# Performance tests executable
|
||||
add_executable(performance_tests
|
||||
cpp/test/collision_performance.cpp
|
||||
)
|
||||
if(WIN32)
|
||||
target_link_libraries(performance_tests GTest::gtest GTest::gtest_main GTest::gmock GTest::gmock_main)
|
||||
else()
|
||||
target_link_libraries(performance_tests GTest::gtest GTest::gtest_main)
|
||||
endif()
|
||||
|
||||
# Enable testing
|
||||
enable_testing()
|
||||
add_test(NAME unit_tests COMMAND unit_tests)
|
||||
add_test(NAME performance_tests COMMAND performance_tests)
|
||||
|
||||
# Compiler-specific options with MSVC support
|
||||
if(MSVC)
|
||||
# MSVC-specific flags: disable permissive mode, enable high warning level
|
||||
target_compile_options(pathfinding_demo PRIVATE /W4 /permissive-)
|
||||
target_compile_options(unit_tests PRIVATE /W4 /permissive-)
|
||||
target_compile_options(performance_tests PRIVATE /W4 /permissive-)
|
||||
|
||||
# Additional MSVC flags for C++23 and modern standards
|
||||
target_compile_options(pathfinding_demo PRIVATE /Zc:__cplusplus /Zc:preprocessor)
|
||||
target_compile_options(unit_tests PRIVATE /Zc:__cplusplus /Zc:preprocessor)
|
||||
target_compile_options(performance_tests PRIVATE /Zc:__cplusplus /Zc:preprocessor)
|
||||
elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" OR CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
|
||||
# GCC/Clang flags
|
||||
target_compile_options(pathfinding_demo PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(unit_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
target_compile_options(performance_tests PRIVATE -Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
|
||||
# Platform-specific build configurations
|
||||
if(MSVC)
|
||||
# MSVC flags
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "/Od /Zi /RTC1")
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "/O2 /DNDEBUG")
|
||||
set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "/O2 /Zi /DNDEBUG")
|
||||
set(CMAKE_CXX_FLAGS_MINSIZEREL "/O1 /DNDEBUG")
|
||||
else()
|
||||
# GCC/Clang flags with extended debugging symbols
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "-ggdb3 -O0")
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "-O3 -DNDEBUG")
|
||||
# Formatting target (clang only)
|
||||
add_custom_target(format
|
||||
COMMAND clang-format -i ${MAIN_SOURCES} ${HEADERS}
|
||||
)
|
||||
endif()
|
||||
|
||||
|
||||
list(TRANSFORM MAIN_SOURCES PREPEND "${CMAKE_SOURCE_DIR}/")
|
||||
list(TRANSFORM HEADERS PREPEND "${CMAKE_SOURCE_DIR}/")
|
||||
|
||||
13
CMakePresets.json
Normal file
13
CMakePresets.json
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": 2,
|
||||
"configurePresets": [
|
||||
{
|
||||
"name": "vcpkg",
|
||||
"generator": "Ninja",
|
||||
"binaryDir": "${sourceDir}/build",
|
||||
"cacheVariables": {
|
||||
"CMAKE_TOOLCHAIN_FILE": "$env{VCPKG_ROOT}/scripts/buildsystems/vcpkg.cmake"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
121
README.md
121
README.md
@@ -2,13 +2,17 @@
|
||||
|
||||
This is a demo of pathfinding on a 2D grid. It consists of 2 main parts:
|
||||
|
||||
* python notes and implementation
|
||||
* jupyter notebook file
|
||||
* standalone python script
|
||||
* C++ demo - **work in progress**
|
||||
* Notes and Python implementation
|
||||
* jupyter notebook file: [`python/pathfinding_demo.ipynb`](./python/pathfinding_demo.ipynb)
|
||||
* standalone python script: [`./python/pathfinding_demo.py`](./python/pathfinding_demo.py)
|
||||
* C++ interactive demo: [`cpp`](./cpp/)
|
||||
|
||||
## Python
|
||||
|
||||
Plots a path from one end of the map to the other. Black tiles represent low-cost path, white tiles have high-cost.
|
||||
|
||||

|
||||
|
||||
### Standalone script
|
||||
|
||||
Run `python pathfinding_demo.py`. Requires numpy and matplotlib to be installed.
|
||||
@@ -17,37 +21,84 @@ Run `python pathfinding_demo.py`. Requires numpy and matplotlib to be installed.
|
||||
|
||||
Contains the same demo as the standalone script and some notes. Since Github supports Jupyter Notebooks now, you can go [directly to the file](./python/pathfinding_demo.ipynb).
|
||||
|
||||
Alternatively (or if you want to edit the file), you can use the [Jupyeter Lab on the official website](https://jupyter.org/try-jupyter/lab/):
|
||||
## C++
|
||||
|
||||
* click the icon "Upload files" (on the top of left sidebar)
|
||||
* select pathfinding_demo.ipynb
|
||||
* file should be now visible in the left sidebar. Double-click it and confirm default kernel selection
|
||||
* run all the cells one by one (play button on the top) or run all of at once using menu "Run -> Run All Cells"
|
||||
Interactive demo of entities moving on a simple map with terrains of varying cost. Draw left-mouse button over entities to select them, right-mouse button to send them to selected destination. Simple collision checks are implemented.
|
||||
|
||||
## TODO
|
||||
Uses some C++20 features. Latest generated architecture drawing is available in [`docs/diagrams/class_diagram.svg`](./docs/diagrams/class_diagram.svg)
|
||||
|
||||

|
||||
|
||||
### Windows
|
||||
|
||||
#### Dependencies
|
||||
|
||||
* `vcpkg` needs to be installed and `VCPKG_ROOT` set. See the [installation instructions](https://learn.microsoft.com/en-us/vcpkg/get_started/get-started?pivots=shell-powershell).
|
||||
* Visual Studio with Desktop development with C++ workload (or MSVC Build Tools)
|
||||
|
||||
#### Build
|
||||
|
||||
Run "Developer Command Prompt for VS 20xx":
|
||||
|
||||
```cmd
|
||||
cmake --preset=vcpkg
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
Run the `pathfinding.exe` binary in the `build` folder.
|
||||
|
||||
### Linux
|
||||
|
||||
#### Dependencies
|
||||
|
||||
* SDL3
|
||||
* SDL3-image
|
||||
* GLEW
|
||||
* gtest
|
||||
|
||||
e.g. on Archlinux:
|
||||
|
||||
```
|
||||
pacman -S glew sdl3 sdl3_image gtest
|
||||
```
|
||||
|
||||
Optional dependencies for generating class and include diagrams:
|
||||
|
||||
* plantuml
|
||||
* [clang-uml](https://github.com/bkryza/clang-uml)
|
||||
|
||||
clang-uml needs to be either installed from [AUR](https://aur.archlinux.org/packages/clang-uml) or built manually
|
||||
|
||||
#### Build
|
||||
|
||||
```bash
|
||||
cmake -B build
|
||||
cmake --build build -j 16
|
||||
```
|
||||
|
||||
Optionally you can also use options:
|
||||
|
||||
* `-DCMAKE_EXPORT_COMPILE_COMMANDS=ON` to enable compile database export (needed for class diagram generation)
|
||||
* `-DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++` to use clang
|
||||
|
||||
```
|
||||
cmake -B build -DCMAKE_EXPORT_COMPILE_COMMANDS=O -DCMAKE_C_COMPILER=clang -DCMAKE_CXX_COMPILER=clang++
|
||||
```
|
||||
|
||||
Run the `pathfinding` binary in the `build` folder.
|
||||
|
||||
#### Generate architecture diagrams
|
||||
|
||||
Build with `-DCMAKE_EXPORT_COMPILE_COMMANDS=ON`. Then in the root folder run:
|
||||
|
||||
```
|
||||
clang-uml
|
||||
plantuml -tsvg docs/diagrams/*.puml
|
||||
```
|
||||
|
||||
The resulting svg files are located in [docs/diagrams/](./docs/diagrams/).
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
Entity sprite comes from the Bomberman game, taken from [archive.org](https://archive.org/details/bombermansprites/Custom%20Edited%20-%20Bomberman%20Customs%20-%20Bomberman%20Super%20Bomberman%202-Style.png)
|
||||
|
||||
- [x] python
|
||||
- [x] get jupyter lab running
|
||||
- [x] drawing utility
|
||||
- [x] interface for pathfinding
|
||||
- [x] research methods
|
||||
- [x] implement methods
|
||||
- [x] DFS
|
||||
- [x] BFS
|
||||
- [x] Dijsktra
|
||||
- [x] GBFS
|
||||
- [x] A*
|
||||
- [x] performance measurement: time/visited nodes
|
||||
- [x] finalize the script and copy back to the jupyter notebook
|
||||
- [x] finish text on the page
|
||||
- [x] create a dedicated python script
|
||||
- [ ] C++
|
||||
- [x] re-use 2D game engine
|
||||
- [x] add tiles (with cost) to map
|
||||
- [x] conversion functions from tile coords to world coords
|
||||
- [x] drawing tiles
|
||||
- [x] add "terrain tiles" with different costs
|
||||
- [x] add mouse-click action
|
||||
- [ ] add direct movement (through mouse click action, no pathfinding)
|
||||
- [ ] implement pathfinding
|
||||
- [ ] windows build?
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
all: test pathfinding
|
||||
# TODO add extra warnings
|
||||
# TODO linter?
|
||||
|
||||
pathfinding: src/main.cpp src/array.hpp
|
||||
g++ -Wall -ggdb3 -lSDL3 -lSDL3_image -std=c++23 -lGLEW -lGL -o pathfinding src/main.cpp
|
||||
|
||||
test: src/test.cpp src/array.hpp
|
||||
g++ -Wall -Wextra -Wpedantic -ggdb3 -std=c++23 -lgtest -o test src/test.cpp
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 10 KiB After Width: | Height: | Size: 3.9 KiB |
@@ -4,7 +4,7 @@
|
||||
#include <stack>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace array { // TODO rename to container or something
|
||||
namespace array {
|
||||
|
||||
template <typename U>
|
||||
concept Deletable = requires(U u) {
|
||||
@@ -148,7 +148,6 @@ public:
|
||||
|
||||
private:
|
||||
pair_t *m_Pool = nullptr;
|
||||
// TODO use unique_ptr
|
||||
std::stack<size_t> m_FreeIdx;
|
||||
|
||||
size_t m_Capacity = 0;
|
||||
|
||||
35
cpp/src/camera.cpp
Normal file
35
cpp/src/camera.cpp
Normal file
@@ -0,0 +1,35 @@
|
||||
#include "camera.hpp"
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
// for now only pass-through placeholder functions,
|
||||
// since we draw the whole map
|
||||
|
||||
void Camera::Pan(const WorldPos &delta) { m_Pan += (delta / m_Zoom); }
|
||||
|
||||
void Camera::Zoom(float delta) {
|
||||
constexpr float ZOOM_SCALE = 0.1f;
|
||||
m_Zoom += delta * ZOOM_SCALE;
|
||||
LOG_DEBUG("Zoom: ", m_Zoom);
|
||||
}
|
||||
|
||||
WindowPos Camera::WorldToWindow(WorldPos world) const {
|
||||
const auto &v = world + m_Pan;
|
||||
return WindowPos{v[0], v[1]} * m_Zoom;
|
||||
}
|
||||
|
||||
WorldPos Camera::WindowToWorld(WindowPos window) const {
|
||||
window /= m_Zoom;
|
||||
return WorldPos{window[0], window[1]} - m_Pan;
|
||||
}
|
||||
|
||||
WindowSize Camera::WorldToWindowSize(WorldSize world) const {
|
||||
const auto &v = world;
|
||||
// no zoom yet, just pass-through
|
||||
return WindowSize{v[0], v[1]} * m_Zoom;
|
||||
}
|
||||
|
||||
WorldSize Camera::WindowToWorldSize(WindowSize window) const {
|
||||
window /= m_Zoom;
|
||||
return WorldSize{window[0], window[1]};
|
||||
}
|
||||
33
cpp/src/camera.hpp
Normal file
33
cpp/src/camera.hpp
Normal file
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include "math.hpp"
|
||||
|
||||
class Camera {
|
||||
public:
|
||||
void Pan(const WorldPos &delta);
|
||||
void Zoom(float delta);
|
||||
|
||||
WorldPos GetPan() const { return m_Pan; }
|
||||
float GetZoom() const { return m_Zoom; }
|
||||
|
||||
WindowPos WorldToWindow(WorldPos) const;
|
||||
WorldPos WindowToWorld(WindowPos) const;
|
||||
WindowSize WorldToWindowSize(WorldSize) const;
|
||||
WorldSize WindowToWorldSize(WindowSize) const;
|
||||
|
||||
template <typename T>
|
||||
requires std::floating_point<T>
|
||||
T WindowToWorldSize(T window_size) const {
|
||||
return window_size / static_cast<T>(m_Zoom);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
requires std::floating_point<T>
|
||||
T WorldToWindowSize(T world_size) const {
|
||||
return world_size * static_cast<T>(m_Zoom);
|
||||
}
|
||||
|
||||
private:
|
||||
float m_Zoom = 1.0f;
|
||||
WorldPos m_Pan;
|
||||
};
|
||||
104
cpp/src/entities.cpp
Normal file
104
cpp/src/entities.cpp
Normal file
@@ -0,0 +1,104 @@
|
||||
#include <memory>
|
||||
|
||||
#include "entities.hpp"
|
||||
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
#include "sprite.hpp"
|
||||
|
||||
Entity::Entity(WorldPos position) : m_Position(position) {
|
||||
LOG_DEBUG("spawning entity at position ", position);
|
||||
}
|
||||
|
||||
std::ostream &operator<<(std::ostream &os, const Entity &obj) {
|
||||
static constexpr std::array<std::string_view,
|
||||
static_cast<size_t>(Entity::Type::COUNT)>
|
||||
type_name{"NONE", "PLAYER", "TILE"};
|
||||
size_t idx = static_cast<size_t>(obj.GetType());
|
||||
assert(idx < type_name.size());
|
||||
os << type_name[idx];
|
||||
return os;
|
||||
}
|
||||
|
||||
void Entity::ZeroActualVelocityInDirection(WorldPos direction) {
|
||||
// Vectors e1, e2 form the basis for a local coord system,
|
||||
// where e1 is formed by the direction where we want to zero-out
|
||||
// the velocity, and e2 is the orthogonal vector.
|
||||
// Scalars q1, q2 are coordinates for e1, e2 basis.
|
||||
WorldPos e1 = direction.GetNormalized();
|
||||
WorldPos e2 = e1.GetOrthogonal();
|
||||
|
||||
// q1 * e1 + q2 * e2 = v, from this follows:
|
||||
auto &v = GetActualVelocity();
|
||||
float q2 =
|
||||
(v.y() * e1.x() - v.x() * e1.y()) / (e2.y() * e1.x() - e2.x() * e1.y());
|
||||
float q1 = (v.x() - q2 * e2.x()) / e1.x();
|
||||
|
||||
// We then zero-out the q1, but only if it's positive - meaning
|
||||
// it is aiming in the direction of "direction", not out.
|
||||
// (otherwise we're not able to move out from collision with
|
||||
// another object)
|
||||
if (q1 > 0.0f) {
|
||||
SetActualVelocity(q2 * e2);
|
||||
}
|
||||
}
|
||||
|
||||
void Entity::Update(float time_delta) {
|
||||
m_Position += m_ActualVelocity * time_delta;
|
||||
}
|
||||
|
||||
std::optional<WorldPos> Entity::GetMoveTarget() {
|
||||
auto &path = GetPath();
|
||||
if (path.empty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
WorldPos current_pos = GetPosition();
|
||||
WorldPos next_pos = path.front();
|
||||
|
||||
if (current_pos.DistanceTo(next_pos) > 1.0) {
|
||||
// target not reached yet
|
||||
return next_pos;
|
||||
}
|
||||
// target reached, pop it
|
||||
// m_MoveQueue.pop();
|
||||
path.erase(path.begin());
|
||||
// return nothing - if there's next point in the queue,
|
||||
// we'll get it in the next iteration
|
||||
return {};
|
||||
}
|
||||
|
||||
bool Entity::CollidesWith(const Entity &other) const {
|
||||
const auto &A = *this;
|
||||
const auto &B = other;
|
||||
|
||||
auto position_A = A.GetPosition();
|
||||
auto position_B = B.GetPosition();
|
||||
auto distance_sq = position_A.DistanceSquared(position_B);
|
||||
auto collision_distance_sq =
|
||||
A.GetCollisionRadiusSquared() + B.GetCollisionRadiusSquared() +
|
||||
2 * A.GetCollisionRadius() * B.GetCollisionRadius();
|
||||
if (distance_sq < collision_distance_sq) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Player::Player() {
|
||||
LOG_DEBUG(".");
|
||||
if (m_Sprite == nullptr) {
|
||||
LoadResources();
|
||||
}
|
||||
}
|
||||
|
||||
Sprite &Player::GetSprite() {
|
||||
assert(m_Sprite != nullptr);
|
||||
return *m_Sprite;
|
||||
}
|
||||
|
||||
void Player::LoadResources() {
|
||||
m_Sprite =
|
||||
std::make_unique<Sprite>("resources/player.png", WorldPos{19.0f, 23.0f});
|
||||
}
|
||||
|
||||
std::unique_ptr<Sprite> Player::m_Sprite;
|
||||
102
cpp/src/entities.hpp
Normal file
102
cpp/src/entities.hpp
Normal file
@@ -0,0 +1,102 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
#include "pathfinder/base.hpp"
|
||||
#include "sprite.hpp"
|
||||
|
||||
class Entity {
|
||||
public:
|
||||
enum class Type : std::uint8_t {
|
||||
NONE,
|
||||
PLAYER,
|
||||
TILE,
|
||||
COUNT // must be last
|
||||
};
|
||||
|
||||
Entity(WorldPos position = {0.0f, 0.0f});
|
||||
Entity(const Entity &) = delete;
|
||||
Entity &operator=(const Entity &) = delete;
|
||||
Entity(Entity &&) = delete;
|
||||
Entity &operator=(Entity &&) = delete;
|
||||
|
||||
friend std::ostream &operator<<(std::ostream &os, const Entity &obj);
|
||||
|
||||
virtual Sprite &GetSprite() = 0;
|
||||
virtual constexpr float GetCollisionRadius() const = 0;
|
||||
virtual constexpr Type GetType() const = 0;
|
||||
virtual bool IsMovable() const = 0;
|
||||
virtual bool IsCollidable() const = 0;
|
||||
|
||||
virtual void Update(float time_delta);
|
||||
|
||||
virtual constexpr float GetCollisionRadiusSquared() const {
|
||||
return GetCollisionRadius() * GetCollisionRadius();
|
||||
}
|
||||
|
||||
void SetFlagExpired() { m_FlagExpired = true; }
|
||||
bool IsFlaggedExpired() const { return m_FlagExpired; }
|
||||
|
||||
const WorldPos &GetPosition() const { return m_Position; }
|
||||
void SetPosition(WorldPos new_pos) { m_Position = new_pos; }
|
||||
|
||||
const WorldPos &GetActualVelocity() const { return m_ActualVelocity; }
|
||||
const WorldPos &GetRequestedVelocity() const { return m_RequestedVelocity; }
|
||||
void SetActualVelocity(const WorldPos &new_velocity) {
|
||||
m_ActualVelocity = new_velocity;
|
||||
}
|
||||
void SetRequestedVelocity(const WorldPos &new_velocity) {
|
||||
m_RequestedVelocity = new_velocity;
|
||||
}
|
||||
|
||||
void ZeroActualVelocityInDirection(WorldPos direction);
|
||||
|
||||
const pathfinder::Path &GetPath() const { return m_Path; }
|
||||
pathfinder::Path &GetPath() { return m_Path; }
|
||||
void SetPath(pathfinder::Path &path) { m_Path = path; }
|
||||
std::optional<WorldPos> GetMoveTarget();
|
||||
|
||||
bool CollidesWith(const Entity &other) const;
|
||||
|
||||
bool IsCollisionBoxVisible() const { return m_CollisionBoxVisible; }
|
||||
|
||||
void Select() { m_Selected = true; }
|
||||
void Deselect() { m_Selected = false; }
|
||||
bool IsSelected() const { return m_Selected; }
|
||||
|
||||
protected:
|
||||
WorldPos m_Position;
|
||||
WorldPos m_ActualVelocity;
|
||||
WorldPos m_RequestedVelocity;
|
||||
pathfinder::Path m_Path;
|
||||
|
||||
private:
|
||||
bool m_FlagExpired = false;
|
||||
bool m_CollisionBoxVisible = true;
|
||||
bool m_Selected = false;
|
||||
};
|
||||
|
||||
class Player final : public Entity {
|
||||
public:
|
||||
Player();
|
||||
|
||||
Sprite &GetSprite() override;
|
||||
|
||||
constexpr Entity::Type GetType() const override {
|
||||
return Entity::Type::PLAYER;
|
||||
}
|
||||
constexpr float GetCollisionRadius() const override { return 25.0f; }
|
||||
bool IsMovable() const override { return true; }
|
||||
bool IsCollidable() const override { return true; }
|
||||
|
||||
private:
|
||||
void LoadResources();
|
||||
static std::unique_ptr<Sprite> m_Sprite;
|
||||
};
|
||||
78
cpp/src/gameloop.cpp
Normal file
78
cpp/src/gameloop.cpp
Normal file
@@ -0,0 +1,78 @@
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
|
||||
#include "gameloop.hpp"
|
||||
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
#include "pathfinder/base.hpp"
|
||||
#include "pathfindingdemo.hpp"
|
||||
#include "user_input.hpp"
|
||||
#include "window.hpp"
|
||||
|
||||
void GameLoop::Draw() {
|
||||
// draw the map (terrain tiles)
|
||||
const Map &map = m_Game->GetMap();
|
||||
const auto &tiles = map.GetMapTiles();
|
||||
for (size_t row = 0; row < tiles.size(); row++) {
|
||||
for (size_t col = 0; col < tiles[row].size(); col++) {
|
||||
const auto &camera = m_Game->GetCamera();
|
||||
const auto &position = camera.WorldToWindow(map.TileEdgeToWorld(
|
||||
TilePos{static_cast<int32_t>(row), static_cast<int32_t>(col)}));
|
||||
const auto &size = camera.WorldToWindowSize(map.GetTileSize());
|
||||
// LOG_DEBUG("Drawing rect (", row, ", ", col, ")");
|
||||
m_Window->DrawFilledRect(position, size, tiles[row][col]->R,
|
||||
tiles[row][col]->G, tiles[row][col]->B,
|
||||
tiles[row][col]->A);
|
||||
}
|
||||
}
|
||||
|
||||
// draw the path, if it exists
|
||||
|
||||
for (const auto &entity : m_Game->GetEntities()) {
|
||||
WorldPos start_pos = entity->GetPosition();
|
||||
for (const auto &next_pos : entity->GetPath()) {
|
||||
const auto &camera = m_Game->GetCamera();
|
||||
m_Window->DrawLine(camera.WorldToWindow(start_pos),
|
||||
camera.WorldToWindow(next_pos));
|
||||
start_pos = next_pos;
|
||||
}
|
||||
}
|
||||
|
||||
// draw all the entities (player etc)
|
||||
for (auto &entity : m_Game->GetEntities()) {
|
||||
const auto &camera = m_Game->GetCamera();
|
||||
auto entity_pos = camera.WorldToWindow(entity->GetPosition());
|
||||
m_Window->DrawSprite(entity_pos, entity->GetSprite(), camera.GetZoom());
|
||||
if (entity->IsCollisionBoxVisible()) {
|
||||
float collision_radius =
|
||||
camera.WorldToWindowSize(entity->GetCollisionRadius());
|
||||
m_Window->DrawCircle(entity_pos, collision_radius, 255, 0, 0);
|
||||
}
|
||||
if (entity->IsSelected()) {
|
||||
float collision_radius =
|
||||
camera.WorldToWindowSize(entity->GetCollisionRadius());
|
||||
m_Window->DrawCircle(entity_pos, collision_radius, 0, 255, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// draw the selection box, if present
|
||||
if (m_Game->IsSelectionBoxActive()) {
|
||||
const auto &[corner_pos, size] = m_Game->GetSelectionBoxPosSize();
|
||||
m_Window->DrawRect(corner_pos, size, 200, 20, 20);
|
||||
}
|
||||
}
|
||||
|
||||
void GameLoop::Run() {
|
||||
LOG_INFO("Running the game");
|
||||
while (!m_Game->IsExitRequested()) {
|
||||
m_Game->HandleActions(m_UserInput->GetActions());
|
||||
m_Game->UpdateWorld();
|
||||
|
||||
m_Window->ClearWindow();
|
||||
Draw();
|
||||
m_Window->Flush();
|
||||
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(30));
|
||||
}
|
||||
}
|
||||
33
cpp/src/gameloop.hpp
Normal file
33
cpp/src/gameloop.hpp
Normal file
@@ -0,0 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "pathfindingdemo.hpp"
|
||||
#include "user_input.hpp"
|
||||
#include "window.hpp"
|
||||
|
||||
class GameLoop {
|
||||
public:
|
||||
GameLoop() = default;
|
||||
~GameLoop() = default;
|
||||
|
||||
GameLoop(const GameLoop &) = delete;
|
||||
GameLoop(GameLoop &&) = delete;
|
||||
GameLoop &operator=(const GameLoop &) = delete;
|
||||
GameLoop &operator=(GameLoop &&) = delete;
|
||||
|
||||
void Run();
|
||||
|
||||
void SetGame(std::unique_ptr<PathFindingDemo> x) { m_Game = std::move(x); }
|
||||
void SetWindow(std::unique_ptr<Window> x) { m_Window = std::move(x); }
|
||||
void SetUserInput(std::unique_ptr<UserInput> x) {
|
||||
m_UserInput = std::move(x);
|
||||
}
|
||||
|
||||
private:
|
||||
void Draw();
|
||||
|
||||
std::unique_ptr<PathFindingDemo> m_Game;
|
||||
std::unique_ptr<Window> m_Window;
|
||||
std::unique_ptr<UserInput> m_UserInput;
|
||||
};
|
||||
@@ -3,11 +3,11 @@
|
||||
#include <iostream>
|
||||
|
||||
#if defined(__GNUC__) || defined(__clang__)
|
||||
# define PRETTY_FUNC __PRETTY_FUNCTION__
|
||||
#define PRETTY_FUNC __PRETTY_FUNCTION__
|
||||
#elif defined(_MSC_VER)
|
||||
# define PRETTY_FUNC __FUNCTION__
|
||||
#define PRETTY_FUNC __FUNCTION__
|
||||
#else
|
||||
# define PRETTY_FUNC __func__
|
||||
#define PRETTY_FUNC __func__
|
||||
#endif
|
||||
|
||||
#define LOG_CRITICAL(...) Log::critical(PRETTY_FUNC, ": ", __VA_ARGS__)
|
||||
|
||||
791
cpp/src/main.cpp
791
cpp/src/main.cpp
@@ -1,785 +1,18 @@
|
||||
#include <cassert>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <expected>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
#include "array.hpp"
|
||||
#include "gameloop.hpp"
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
#include "pathfindingdemo.hpp"
|
||||
#include "user_input.hpp"
|
||||
#include "window.hpp"
|
||||
#include <memory>
|
||||
|
||||
//
|
||||
// Utils
|
||||
//
|
||||
|
||||
//
|
||||
// Math stuff
|
||||
//
|
||||
|
||||
// Forward declarations
|
||||
class Sprite;
|
||||
class Sound;
|
||||
class UserAction;
|
||||
|
||||
//
|
||||
// UI stuff. This is the part directly dependent on the SDL
|
||||
//
|
||||
|
||||
// containers
|
||||
|
||||
#include <GL/glew.h>
|
||||
#include <SDL3/SDL.h>
|
||||
#include <SDL3_image/SDL_image.h>
|
||||
|
||||
class Sound {
|
||||
public:
|
||||
Sound() { LOG_DEBUG("."); }
|
||||
Sound(const Sound &x) { LOG_DEBUG("."); }
|
||||
Sound(Sound &&x) noexcept { LOG_DEBUG("."); }
|
||||
~Sound() { LOG_DEBUG("."); }
|
||||
};
|
||||
|
||||
class AudioOutput {
|
||||
public:
|
||||
AudioOutput() { LOG_DEBUG("."); }
|
||||
AudioOutput(const AudioOutput &x) = delete;
|
||||
AudioOutput(AudioOutput &&x) = delete;
|
||||
~AudioOutput() { LOG_DEBUG("."); }
|
||||
|
||||
std::expected<void, std::string> Init() {
|
||||
LOG_INFO("Initialing audio output");
|
||||
return {};
|
||||
}
|
||||
|
||||
void PlaySound(Sound &s);
|
||||
};
|
||||
|
||||
class Sprite {
|
||||
public:
|
||||
Sprite() : m_Texture(nullptr, SDL_DestroyTexture) {}
|
||||
Sprite(std::string path, Vec2D<float> center) : Sprite() {
|
||||
LoadImage(path, center);
|
||||
}
|
||||
int m_R = 0;
|
||||
int m_G = 0;
|
||||
int m_B = 0;
|
||||
int m_A = 0;
|
||||
Sprite(const Sprite &x) = delete;
|
||||
Sprite(Sprite &&x) = delete;
|
||||
~Sprite() { LOG_DEBUG("."); }
|
||||
void LoadImage(std::string path, Vec2D<float> image_center = {0.0, 0.0}) {
|
||||
LOG_INFO("Loading image ", path);
|
||||
assert(m_Renderer != nullptr);
|
||||
|
||||
auto surface = std::unique_ptr<SDL_Surface, decltype(&SDL_DestroySurface)>(
|
||||
IMG_Load(path.c_str()), SDL_DestroySurface);
|
||||
|
||||
if (surface == nullptr) {
|
||||
LOG_ERROR("IMG_Load failed to load ", path);
|
||||
throw std::runtime_error("Failed to load resources");
|
||||
}
|
||||
|
||||
m_Texture = std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)>(
|
||||
SDL_CreateTextureFromSurface(m_Renderer.get(), surface.get()),
|
||||
SDL_DestroyTexture);
|
||||
if (m_Texture == nullptr) {
|
||||
LOG_ERROR("SDL_CreateTextureFromSurface failed");
|
||||
throw std::runtime_error("Failed to load resources");
|
||||
}
|
||||
float w, h;
|
||||
SDL_GetTextureSize(m_Texture.get(), &w, &h);
|
||||
m_Size = {w, h};
|
||||
m_ImageCenter = image_center;
|
||||
}
|
||||
|
||||
// Renderer is shared for all class instances - we need it in order
|
||||
// to create textures from images
|
||||
static void SetRenderer(std::shared_ptr<SDL_Renderer> renderer) {
|
||||
m_Renderer = renderer;
|
||||
}
|
||||
|
||||
// GetTexture cannot return pointer to const, as SDL_RenderTexture modifies it
|
||||
SDL_Texture *GetTexture() { return m_Texture.get(); }
|
||||
|
||||
Vec2D<float> GetSize() const { return m_Size; }
|
||||
Vec2D<float> GetCenter() const { return m_ImageCenter; }
|
||||
|
||||
private:
|
||||
static std::shared_ptr<SDL_Renderer> m_Renderer;
|
||||
std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)> m_Texture;
|
||||
Vec2D<float> m_Size;
|
||||
Vec2D<float> m_ImageCenter;
|
||||
float m_TextureWidth = 0;
|
||||
float m_TextureHeight = 0;
|
||||
};
|
||||
std::shared_ptr<SDL_Renderer> Sprite::m_Renderer = nullptr;
|
||||
|
||||
// User interface classes
|
||||
|
||||
class Window {
|
||||
public:
|
||||
Window(const Window &x) = delete;
|
||||
Window(Window &&x) = delete;
|
||||
Window(int width, int height) : m_Width(width), m_Height(height) {
|
||||
LOG_DEBUG(".");
|
||||
}
|
||||
|
||||
std::expected<void, std::string> Init() {
|
||||
LOG_DEBUG(".");
|
||||
|
||||
if (SDL_Init(SDL_INIT_VIDEO) == false) {
|
||||
return std::unexpected(std::string("SDL could not initialize! Error: ") +
|
||||
SDL_GetError());
|
||||
}
|
||||
m_Window = SDL_CreateWindow("SDL2 Window", m_Width, m_Height,
|
||||
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
|
||||
if (m_Window == nullptr) {
|
||||
std::atexit(SDL_Quit);
|
||||
return std::unexpected(
|
||||
std::string("Window could not be created! Error: ") + SDL_GetError());
|
||||
}
|
||||
|
||||
m_Context = SDL_GL_CreateContext(m_Window);
|
||||
if (m_Context == nullptr) {
|
||||
SDL_DestroyWindow(m_Window);
|
||||
std::atexit(SDL_Quit);
|
||||
return std::unexpected(
|
||||
std::string("GL context could not be created! Error: ") +
|
||||
SDL_GetError());
|
||||
}
|
||||
|
||||
if (glewInit() != GLEW_OK) {
|
||||
SDL_GL_DestroyContext(m_Context);
|
||||
SDL_DestroyWindow(m_Window);
|
||||
std::atexit(SDL_Quit);
|
||||
return std::unexpected("GLEW init failed!");
|
||||
}
|
||||
|
||||
// Resize();
|
||||
|
||||
m_Renderer = std::shared_ptr<SDL_Renderer>(
|
||||
SDL_CreateRenderer(m_Window, NULL), SDL_DestroyRenderer);
|
||||
if (m_Renderer == nullptr) {
|
||||
SDL_DestroyWindow(m_Window);
|
||||
std::atexit(SDL_Quit);
|
||||
return std::unexpected(
|
||||
std::string("Renderer could not be created! Error: ") +
|
||||
SDL_GetError());
|
||||
}
|
||||
|
||||
// Set renderer to the Sprite class
|
||||
Sprite::SetRenderer(m_Renderer);
|
||||
|
||||
// TODO this needs to be tied to map size
|
||||
SDL_SetRenderScale(m_Renderer.get(), 1.0f, 1.0f);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
~Window() {
|
||||
// SDL_DestroyRenderer(m_Renderer); // handled by shared_ptr
|
||||
SDL_GL_DestroyContext(m_Context);
|
||||
SDL_DestroyWindow(m_Window);
|
||||
std::atexit(SDL_Quit);
|
||||
LOG_DEBUG(".");
|
||||
}
|
||||
|
||||
void DrawSprite(const Vec2D<float> &position, Sprite &s) {
|
||||
Vec2D<float> size = s.GetSize();
|
||||
Vec2D<float> img_center = s.GetCenter();
|
||||
SDL_FRect rect = {position.x - img_center.x, position.y - img_center.y,
|
||||
size.x, size.y};
|
||||
SDL_RenderTexture(m_Renderer.get(), s.GetTexture(), nullptr, &rect);
|
||||
}
|
||||
|
||||
void DrawRect(const Vec2D<float> &position, const Vec2D<float> size,
|
||||
uint8_t R, uint8_t G, uint8_t B, uint8_t A) {
|
||||
SDL_FRect rect = {position.x, position.y,
|
||||
size.x, size.y};
|
||||
SDL_SetRenderDrawColor(m_Renderer.get(), R, G, B, A);
|
||||
SDL_RenderFillRect(m_Renderer.get(), &rect);
|
||||
}
|
||||
|
||||
void ClearWindow() {
|
||||
SDL_SetRenderDrawColor(m_Renderer.get(), 50, 50, 50, 255);
|
||||
SDL_RenderClear(m_Renderer.get());
|
||||
}
|
||||
|
||||
void Flush() { SDL_RenderPresent(m_Renderer.get()); }
|
||||
|
||||
void DrawCircle(const Vec2D<float> &position, float radius) {
|
||||
int cx = static_cast<int>(position.x);
|
||||
int cy = static_cast<int>(position.y);
|
||||
SDL_SetRenderDrawColor(m_Renderer.get(), 255, 0, 0, 255);
|
||||
for (int i = 0; i < 360; ++i) {
|
||||
double a = i * M_PI / 180.0;
|
||||
SDL_RenderPoint(m_Renderer.get(),
|
||||
cx + static_cast<int>(std::round(radius * std::cos(a))),
|
||||
cy + static_cast<int>(std::round(radius * std::sin(a))));
|
||||
}
|
||||
}
|
||||
|
||||
std::shared_ptr<SDL_Renderer> m_Renderer = nullptr;
|
||||
SDL_Window *m_Window;
|
||||
SDL_GLContext m_Context;
|
||||
|
||||
private:
|
||||
uint32_t m_Width;
|
||||
uint32_t m_Height;
|
||||
};
|
||||
|
||||
class UserAction {
|
||||
public:
|
||||
enum class Type { NONE, EXIT, MOVE, CROUCH, STAND, FIRE, MOVE_TARGET};
|
||||
|
||||
UserAction() = default;
|
||||
|
||||
UserAction(Type t) : type(t) {}
|
||||
|
||||
UserAction(Type t, char key) : type(t), Argument{.key = key} {}
|
||||
|
||||
UserAction(Type t, Vec2D<float> v) : type(t), Argument{.position = v} {}
|
||||
|
||||
~UserAction() = default;
|
||||
|
||||
Type type;
|
||||
|
||||
union {
|
||||
Vec2D<float> position;
|
||||
char key;
|
||||
} Argument;
|
||||
};
|
||||
|
||||
class UserInput {
|
||||
public:
|
||||
UserInput()
|
||||
: // pre-alloc some space
|
||||
m_Actions(10) {
|
||||
LOG_DEBUG(".");
|
||||
};
|
||||
|
||||
UserInput(const UserInput &x) = delete;
|
||||
UserInput(UserInput &&x) = delete;
|
||||
~UserInput() { LOG_DEBUG("."); };
|
||||
|
||||
std::expected<void, std::string> Init() { return {}; }
|
||||
|
||||
const std::vector<UserAction> &GetActions() {
|
||||
m_Actions.clear();
|
||||
static Vec2D<float> move_direction = {0.0f, 0.0f};
|
||||
static bool send_move_action = false;
|
||||
SDL_Event event;
|
||||
|
||||
while (SDL_PollEvent(&event)) {
|
||||
if (event.type == SDL_EVENT_KEY_DOWN || event.type == SDL_EVENT_KEY_UP) {
|
||||
bool key_down = event.type == SDL_EVENT_KEY_DOWN ? true : false;
|
||||
SDL_KeyboardEvent kbd_event = event.key;
|
||||
if (kbd_event.repeat) {
|
||||
// SDL repeats KEY_DOWN if key is held down, we ignore that
|
||||
continue;
|
||||
}
|
||||
LOG_DEBUG("Key '", static_cast<char>(kbd_event.key),
|
||||
key_down ? "' down" : "' up");
|
||||
|
||||
switch (kbd_event.key) {
|
||||
case 'q':
|
||||
m_Actions.emplace_back(UserAction::Type::EXIT);
|
||||
// further processing of inputs is not needed
|
||||
return m_Actions;
|
||||
case 'w':
|
||||
case 's':
|
||||
case 'a':
|
||||
case 'd':
|
||||
case SDLK_UP:
|
||||
case SDLK_DOWN:
|
||||
case SDLK_LEFT:
|
||||
case SDLK_RIGHT: {
|
||||
static std::map<char, Vec2D<float>> move_base{
|
||||
{'w', {0.0, 1.0}},
|
||||
{'s', {0.0, -1.0}},
|
||||
{'a', {1.0, 0.0}},
|
||||
{'d', {-1.0, 0.0}},
|
||||
{static_cast<char>(SDLK_UP), {0.0, 1.0}},
|
||||
{static_cast<char>(SDLK_DOWN), {0.0, -1.0}},
|
||||
{static_cast<char>(SDLK_LEFT), {1.0, 0.0}},
|
||||
{static_cast<char>(SDLK_RIGHT), {-1.0, 0.0}},
|
||||
};
|
||||
|
||||
float direction = key_down ? -1.0f : 1.0f;
|
||||
send_move_action = true;
|
||||
move_direction += move_base[kbd_event.key] * direction;
|
||||
break;
|
||||
}
|
||||
case SDLK_SPACE:
|
||||
if (key_down)
|
||||
m_Actions.emplace_back(UserAction::Type::FIRE);
|
||||
break;
|
||||
default:
|
||||
LOG_INFO("Key '", static_cast<char>(kbd_event.key), "' not mapped");
|
||||
break;
|
||||
}
|
||||
} else if (event.type == SDL_EVENT_MOUSE_BUTTON_DOWN) {
|
||||
SDL_MouseButtonEvent mouse_event = event.button;
|
||||
LOG_DEBUG("Mouse down: ", mouse_event.x, ", ", mouse_event.y);
|
||||
m_Actions.emplace_back(UserAction::Type::MOVE_TARGET,
|
||||
Vec2D<float>{mouse_event.x, mouse_event.y});
|
||||
} else {
|
||||
// TODO uncomment, for now too much noise
|
||||
// LOG_WARNING("Action not processed");
|
||||
}
|
||||
}
|
||||
if (send_move_action) {
|
||||
m_Actions.emplace_back(UserAction::Type::MOVE,
|
||||
move_direction.normalized());
|
||||
send_move_action = false;
|
||||
}
|
||||
return m_Actions;
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<UserAction> m_Actions;
|
||||
};
|
||||
|
||||
//
|
||||
// Game classes
|
||||
//
|
||||
|
||||
class Entity {
|
||||
public:
|
||||
enum class Type : std::uint8_t {
|
||||
NONE,
|
||||
PLAYER,
|
||||
WALL,
|
||||
TILE,
|
||||
COUNT // must be last
|
||||
};
|
||||
|
||||
Entity(Vec2D<float> position = {0.0f, 0.0f}) : m_Position(position) {
|
||||
LOG_DEBUG("spawning entity at position ", position);
|
||||
}
|
||||
|
||||
friend std::ostream &operator<<(std::ostream &os, const Entity &obj) {
|
||||
static constexpr std::array<std::string_view,
|
||||
static_cast<size_t>(Entity::Type::COUNT)>
|
||||
type_name{"NONE", "PLAYER", "WALL", "TILE"};
|
||||
size_t idx = static_cast<size_t>(obj.GetType());
|
||||
assert(idx < type_name.size());
|
||||
os << type_name[idx];
|
||||
return os;
|
||||
}
|
||||
|
||||
virtual Sprite &GetSprite() = 0;
|
||||
virtual constexpr float GetCollisionRadius() const = 0;
|
||||
virtual constexpr float GetCollisionRadiusSquared() {
|
||||
return GetCollisionRadius() * GetCollisionRadius();
|
||||
}
|
||||
|
||||
virtual constexpr Type GetType() const = 0;
|
||||
void SetFlagExpired() { m_FlagExpired = true; }
|
||||
bool IsFlaggedExpired() { return m_FlagExpired; }
|
||||
|
||||
const Vec2D<float> &GetPosition() const { return m_Position; }
|
||||
void SetPosition(Vec2D<float> new_pos) { m_Position = new_pos; }
|
||||
|
||||
const Vec2D<float> &GetActualVelocity() const { return m_ActualVelocity; }
|
||||
const Vec2D<float> &GetRequestedVelocity() const {
|
||||
return m_RequestedVelocity;
|
||||
}
|
||||
void SetActualVelocity(const Vec2D<float> &new_velocity) {
|
||||
m_ActualVelocity = new_velocity;
|
||||
}
|
||||
void SetRequestedVelocity(const Vec2D<float> &new_velocity) {
|
||||
m_RequestedVelocity = new_velocity;
|
||||
}
|
||||
|
||||
void ZeroActualVelocityInDirection(Vec2D<float> direction) {
|
||||
// Vectors e1, e2 form the basis for a local coord system,
|
||||
// where e1 is formed by the direction where we want to zero-out
|
||||
// the velocity, and e2 is the orthogonal vector.
|
||||
// Scalars q1, q2 are coordinates for e1, e2 basis.
|
||||
Vec2D<float> e1 = direction.normalized();
|
||||
Vec2D<float> e2 = e1.orthogonal();
|
||||
|
||||
// q1 * e1 + q2 * e2 = v, from this follows:
|
||||
auto &v = GetActualVelocity();
|
||||
float q2 = (v.y * e1.x - v.x * e1.y) / (e2.y * e1.x - e2.x * e1.y);
|
||||
float q1 = (v.x - q2 * e2.x) / e1.x;
|
||||
|
||||
// We then zero-out the q1, but only if it's positive - meaning
|
||||
// it is aiming in the direction of "direction", not out.
|
||||
// (otherwise we're not able to move out from collision with
|
||||
// another object)
|
||||
if (q1 > 0.0f) {
|
||||
SetActualVelocity(q2 * e2);
|
||||
}
|
||||
}
|
||||
|
||||
virtual void Update(float time_delta) {
|
||||
m_Position += m_ActualVelocity * time_delta;
|
||||
}
|
||||
|
||||
virtual bool IsMovable() const = 0;
|
||||
virtual bool IsCollidable() const = 0;
|
||||
|
||||
protected:
|
||||
Vec2D<float> m_Position;
|
||||
Vec2D<float> m_ActualVelocity;
|
||||
Vec2D<float> m_RequestedVelocity;
|
||||
|
||||
private:
|
||||
bool m_FlagExpired = false;
|
||||
static constexpr float m_CollisionRadiusSq = 1000.0f;
|
||||
};
|
||||
|
||||
class Wall final : public Entity {
|
||||
public:
|
||||
Wall(Vec2D<float> pos = {0.0f, 0.0f}) : Entity(pos) {
|
||||
LOG_DEBUG(".");
|
||||
if (m_Sprite == nullptr) {
|
||||
LoadResources();
|
||||
}
|
||||
}
|
||||
Wall(const Wall &x) = delete;
|
||||
Wall(Wall &&x) = delete;
|
||||
|
||||
Sprite &GetSprite() override {
|
||||
assert(m_Sprite != nullptr);
|
||||
return *m_Sprite;
|
||||
}
|
||||
constexpr Entity::Type GetType() const override { return Entity::Type::WALL; }
|
||||
constexpr float GetCollisionRadius() const override { return 50.0f; }
|
||||
bool IsMovable() const override { return false; }
|
||||
bool IsCollidable() const override { return true; }
|
||||
|
||||
private:
|
||||
void LoadResources() {
|
||||
m_Sprite = std::make_unique<Sprite>("resources/wall.png",
|
||||
Vec2D<float>{50.0f, 50.0f});
|
||||
}
|
||||
static std::unique_ptr<Sprite> m_Sprite;
|
||||
};
|
||||
std::unique_ptr<Sprite> Wall::m_Sprite;
|
||||
|
||||
class Player final : public Entity {
|
||||
public:
|
||||
Player() {
|
||||
LOG_DEBUG(".");
|
||||
if (m_Sprite == nullptr) {
|
||||
LoadResources();
|
||||
}
|
||||
}
|
||||
Player(const Player &x) = delete;
|
||||
Player(Player &&x) = delete;
|
||||
|
||||
Sprite &GetSprite() override {
|
||||
assert(m_Sprite != nullptr);
|
||||
return *m_Sprite;
|
||||
}
|
||||
|
||||
constexpr Entity::Type GetType() const override {
|
||||
return Entity::Type::PLAYER;
|
||||
}
|
||||
constexpr float GetCollisionRadius() const override { return 50.0f; }
|
||||
bool IsMovable() const override { return true; }
|
||||
bool IsCollidable() const override { return true; }
|
||||
|
||||
private:
|
||||
void LoadResources() {
|
||||
m_Sprite = std::make_unique<Sprite>("resources/player.png",
|
||||
Vec2D<float>{38.0f, 46.0f});
|
||||
}
|
||||
static std::unique_ptr<Sprite> m_Sprite;
|
||||
};
|
||||
|
||||
std::unique_ptr<Sprite> Player::m_Sprite;
|
||||
|
||||
using Collision = std::pair<std::shared_ptr<Entity>, std::shared_ptr<Entity>>;
|
||||
|
||||
struct Tile {
|
||||
float cost;
|
||||
uint8_t R, G, B, A;
|
||||
};
|
||||
|
||||
static const std::map<std::string_view, Tile> tile_types = {
|
||||
{"Grass", {1.0, 0, 200, 0, 255}},
|
||||
{"Mud", {2.0, 100, 100, 100, 255}},
|
||||
{"Road", {0.5, 200, 200, 200, 255}},
|
||||
{"Water", {10.0, 0, 50, 200, 255}},
|
||||
};
|
||||
|
||||
using TilePos = Vec2D<int>;
|
||||
using WorldPos = Vec2D<float>;
|
||||
|
||||
class Map {
|
||||
|
||||
// TODO using = ... for tile vector
|
||||
|
||||
public:
|
||||
static constexpr float TILE_SIZE = 100.0f; // tile size in world
|
||||
|
||||
Map(int width, int height) : m_Width(width), m_Height(height) {
|
||||
bool sw = true;
|
||||
LOG_DEBUG("width = ", width, " height = ", height);
|
||||
m_Tiles = std::vector<std::vector<const Tile *>>{};
|
||||
for (int i = 0; i < m_Width; i++) {
|
||||
m_Tiles.push_back(std::vector<const Tile *>{});
|
||||
for (int j = 0; j < m_Height; j++) {
|
||||
if (sw)
|
||||
m_Tiles[i].push_back(&tile_types.at("Grass"));
|
||||
else
|
||||
m_Tiles[i].push_back(&tile_types.at("Water"));
|
||||
sw = !sw;
|
||||
}
|
||||
sw = !sw;
|
||||
}
|
||||
}
|
||||
Map() : Map(0, 0) {}
|
||||
|
||||
const std::vector<std::vector<const Tile *>> &GetMapTiles() const {
|
||||
return m_Tiles;
|
||||
}
|
||||
|
||||
WorldPos TileToWorld(TilePos p) const {
|
||||
return WorldPos{p.x * TILE_SIZE, p.y * TILE_SIZE};
|
||||
}
|
||||
|
||||
TilePos WorldToTile(WorldPos p) const {
|
||||
return TilePos{p.x / TILE_SIZE, p.y / TILE_SIZE};
|
||||
}
|
||||
|
||||
Vec2D<float> GetTileSize() const {
|
||||
return Vec2D<float>{TILE_SIZE, TILE_SIZE};
|
||||
}
|
||||
|
||||
private:
|
||||
// std::vector<std::vector<const Tile*>> m_Tiles;
|
||||
std::vector<std::vector<const Tile *>> m_Tiles;
|
||||
int m_Width = 0;
|
||||
int m_Height = 0;
|
||||
};
|
||||
|
||||
class PathFindingDemo {
|
||||
public:
|
||||
PathFindingDemo(int width, int height)
|
||||
: m_Width(width), m_Height(height), // TODO delete width, height
|
||||
m_Map(width, height) {
|
||||
LOG_DEBUG(".");
|
||||
}
|
||||
|
||||
~PathFindingDemo() { LOG_DEBUG("."); }
|
||||
|
||||
PathFindingDemo(const PathFindingDemo &m) = delete;
|
||||
PathFindingDemo(PathFindingDemo &&m) = delete;
|
||||
|
||||
void AddEntity(std::shared_ptr<Entity> e) {
|
||||
// TODO emplace_back
|
||||
m_Entities.push_back(e);
|
||||
}
|
||||
|
||||
void CreateMap() {
|
||||
m_Entities.clear();
|
||||
m_Player = std::make_shared<Player>();
|
||||
m_Player->SetPosition(Vec2D<float>{200.0f, 200.0f});
|
||||
m_Entities.push_back(m_Player);
|
||||
}
|
||||
|
||||
std::shared_ptr<Player> GetPlayer() { return m_Player; }
|
||||
|
||||
Vec2D<float> GetRandomPosition() const { return Vec2D<float>{0.0, 0.0}; }
|
||||
|
||||
std::vector<std::shared_ptr<Entity>> &GetEntities() { return m_Entities; }
|
||||
|
||||
void UpdateEntities() {
|
||||
float time_delta = 1.0f;
|
||||
|
||||
// Remove entities marked as expired and handle expiry logic (e.g. bomb
|
||||
// exploding); for all other entities, reset the actual velocity to the
|
||||
// requested; actual velocity will be updated later with collisions
|
||||
for (auto &entity : m_Entities) {
|
||||
if (entity->IsFlaggedExpired()) {
|
||||
ExpiryGameLogic(*entity);
|
||||
auto it = std::find(m_Entities.begin(), m_Entities.end(), entity);
|
||||
if (it != m_Entities.end()) {
|
||||
std::swap(*it, m_Entities.back());
|
||||
m_Entities.pop_back();
|
||||
}
|
||||
} else {
|
||||
// Actual velocity might be changed later by collisions
|
||||
entity->SetActualVelocity(entity->GetRequestedVelocity());
|
||||
}
|
||||
}
|
||||
|
||||
// Handle collisions:
|
||||
// - update actual velocity for colliding objects
|
||||
// - handle collision logic
|
||||
auto &collisions = GetEntityCollisions();
|
||||
// LOG_DEBUG("number of collisions: ", collisions.size());
|
||||
for (auto &collision : collisions) {
|
||||
Entity &A = *std::get<0>(collision);
|
||||
Entity &B = *std::get<1>(collision);
|
||||
if (!A.IsMovable())
|
||||
continue;
|
||||
// modify actual speed
|
||||
// LOG_DEBUG("Collision: A is ", A, ", B is ", B);
|
||||
Vec2D<float> AB = B.GetPosition() - A.GetPosition();
|
||||
A.ZeroActualVelocityInDirection(AB);
|
||||
// handle logic
|
||||
CollisionGameLogic(A, B);
|
||||
}
|
||||
|
||||
// Update entities: this advances animations,
|
||||
// internal timers, and updates positions (with velocity
|
||||
// modified by the collision handling)
|
||||
for (auto &entity : m_Entities) {
|
||||
entity->Update(time_delta);
|
||||
}
|
||||
}
|
||||
|
||||
void CollisionGameLogic(Entity &A, Entity &B) {
|
||||
// not used for path finding demo
|
||||
}
|
||||
|
||||
void ExpiryGameLogic(Entity &entity) {
|
||||
// not used for path finding demo
|
||||
}
|
||||
|
||||
const std::vector<Collision> &GetEntityCollisions() {
|
||||
static std::vector<Collision> m_Collisions;
|
||||
|
||||
m_Collisions.clear();
|
||||
for (const auto &entity_A : m_Entities) {
|
||||
for (const auto &entity_B : m_Entities) {
|
||||
if (entity_A == entity_B)
|
||||
continue;
|
||||
if (!entity_A->IsCollidable() || !entity_B->IsCollidable())
|
||||
continue;
|
||||
// check distance of player to given entity
|
||||
auto position_A = entity_A->GetPosition();
|
||||
auto position_B = entity_B->GetPosition();
|
||||
auto distance_sq = position_A.distance_squared(position_B);
|
||||
auto collision_distance_sq =
|
||||
entity_A->GetCollisionRadiusSquared() +
|
||||
entity_B->GetCollisionRadiusSquared() +
|
||||
2 * entity_A->GetCollisionRadius() * entity_B->GetCollisionRadius();
|
||||
// TODO use vector instructions
|
||||
if (distance_sq < collision_distance_sq) {
|
||||
m_Collisions.emplace_back(Collision(entity_A, entity_B));
|
||||
}
|
||||
}
|
||||
}
|
||||
return m_Collisions;
|
||||
}
|
||||
|
||||
void HandleActions(const std::vector<UserAction> &actions) {
|
||||
for (const auto &action : actions) {
|
||||
if (action.type == UserAction::Type::EXIT) {
|
||||
LOG_INFO("Exit requested");
|
||||
m_ExitRequested = true;
|
||||
} else if (action.type == UserAction::Type::FIRE) {
|
||||
LOG_INFO("Fire");
|
||||
// AddEntity(m_Player->CreateBomb());
|
||||
} else if (action.type == UserAction::Type::MOVE) {
|
||||
LOG_INFO("Move direction ", action.Argument.position);
|
||||
m_Player->SetRequestedVelocity(action.Argument.position * 4.0f);
|
||||
} else if (action.type == UserAction::Type::MOVE_TARGET) {
|
||||
TilePos p = m_Map.WorldToTile(action.Argument.position);
|
||||
LOG_INFO("Move target: ", action.Argument.position, ", tile pos: ", p);
|
||||
// TODO move
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const Map &GetMap() const { return m_Map; }
|
||||
|
||||
bool IsCollisionBoxVisible() const { return m_DrawCollisionBox; }
|
||||
bool IsExitRequested() const { return m_ExitRequested; }
|
||||
|
||||
private:
|
||||
int m_Width;
|
||||
int m_Height;
|
||||
bool m_ExitRequested = false;
|
||||
bool m_DrawCollisionBox = true;
|
||||
std::vector<std::shared_ptr<Entity>> m_Entities;
|
||||
std::shared_ptr<Player> m_Player;
|
||||
Map m_Map;
|
||||
};
|
||||
|
||||
// GameLoop class handles user input and audio/video output,
|
||||
// client side only. No game logic should be handled here.
|
||||
|
||||
class GameLoop {
|
||||
public:
|
||||
GameLoop() = default;
|
||||
|
||||
void Run() {
|
||||
LOG_INFO("Running the game");
|
||||
while (!m_Game->IsExitRequested()) {
|
||||
m_Game->HandleActions(m_UserInput->GetActions());
|
||||
m_Game->UpdateEntities();
|
||||
|
||||
m_Window->ClearWindow();
|
||||
|
||||
// draw the map (terrain tiles)
|
||||
const Map &map = m_Game->GetMap();
|
||||
const auto &tiles = map.GetMapTiles();
|
||||
for (int row = 0; row < tiles.size(); row++) {
|
||||
for (int col = 0; col < tiles[row].size(); col++) {
|
||||
// LOG_DEBUG("Drawing rect (", row, ", ", col, ")");
|
||||
m_Window->DrawRect(
|
||||
map.TileToWorld(TilePos{row, col}),
|
||||
map.GetTileSize(), tiles[row][col]->R, tiles[row][col]->G,
|
||||
tiles[row][col]->B, tiles[row][col]->A);
|
||||
}
|
||||
}
|
||||
|
||||
// draw all the entities (player etc)
|
||||
for (auto &entity : m_Game->GetEntities()) {
|
||||
m_Window->DrawSprite(entity->GetPosition(), entity->GetSprite());
|
||||
if (m_Game->IsCollisionBoxVisible()) {
|
||||
m_Window->DrawCircle(entity->GetPosition(),
|
||||
entity->GetCollisionRadius());
|
||||
}
|
||||
}
|
||||
|
||||
m_Window->Flush();
|
||||
// TODO measure fps
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(30));
|
||||
}
|
||||
}
|
||||
|
||||
inline void SetGame(std::unique_ptr<PathFindingDemo> x) {
|
||||
m_Game = std::move(x);
|
||||
}
|
||||
inline void SetWindow(std::unique_ptr<Window> x) { m_Window = std::move(x); }
|
||||
inline void SetUserInput(std::unique_ptr<UserInput> x) {
|
||||
m_UserInput = std::move(x);
|
||||
}
|
||||
inline void SetAudioOutput(std::unique_ptr<AudioOutput> x) {
|
||||
m_AudioOutput = std::move(x);
|
||||
}
|
||||
|
||||
private:
|
||||
std::unique_ptr<PathFindingDemo> m_Game;
|
||||
std::unique_ptr<Window> m_Window;
|
||||
std::unique_ptr<UserInput> m_UserInput;
|
||||
std::unique_ptr<AudioOutput> m_AudioOutput;
|
||||
};
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int main() {
|
||||
constexpr int error = -1;
|
||||
|
||||
/*
|
||||
* Initialize the input/output system
|
||||
*/
|
||||
|
||||
auto window = std::make_unique<Window>(640, 480); // the holy resolution
|
||||
// auto window_init = window->Init();
|
||||
auto window = std::make_unique<Window>(640, 480);
|
||||
if (auto initialized = window->Init(); !initialized) {
|
||||
LOG_ERROR(initialized.error());
|
||||
return error;
|
||||
@@ -791,23 +24,17 @@ int main(int argc, char **argv) {
|
||||
return error;
|
||||
}
|
||||
|
||||
auto audio_output = std::make_unique<AudioOutput>();
|
||||
if (auto initialized = audio_output->Init(); !initialized) {
|
||||
LOG_ERROR(initialized.error());
|
||||
return error;
|
||||
}
|
||||
|
||||
/*
|
||||
* Initialize the map and run the pathfinding demo
|
||||
*/
|
||||
|
||||
auto demo = std::make_unique<PathFindingDemo>(10, 10);
|
||||
auto demo = std::make_unique<PathFindingDemo>(100, 100);
|
||||
demo->CreateMap();
|
||||
|
||||
auto game_loop = GameLoop{};
|
||||
game_loop.SetWindow(std::move(window));
|
||||
game_loop.SetUserInput(std::move(user_input));
|
||||
game_loop.SetAudioOutput(std::move(audio_output));
|
||||
game_loop.SetGame(std::move(demo));
|
||||
game_loop.Run();
|
||||
return 0;
|
||||
}
|
||||
|
||||
136
cpp/src/map.cpp
Normal file
136
cpp/src/map.cpp
Normal file
@@ -0,0 +1,136 @@
|
||||
#include <cassert>
|
||||
#include <vector>
|
||||
|
||||
#include "log.hpp"
|
||||
#include "map.hpp"
|
||||
#include "tile.hpp"
|
||||
|
||||
Map::Map(int rows, int cols) : m_Cols(cols), m_Rows(rows) {
|
||||
LOG_DEBUG("cols = ", cols, " rows = ", rows);
|
||||
m_Tiles = std::vector<std::vector<const Tile *>>{};
|
||||
for (size_t row = 0; row < m_Rows; row++) {
|
||||
m_Tiles.push_back(std::vector<const Tile *>{});
|
||||
for (size_t col = 0; col < m_Cols; col++) {
|
||||
m_Tiles[row].push_back(&tile_types.at(TileType::GRASS));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
WorldPos Map::TileToWorld(TilePos p) const {
|
||||
return WorldPos{(p.x() + 0.5f) * TILE_SIZE, (p.y() + 0.5f) * TILE_SIZE};
|
||||
}
|
||||
|
||||
WorldPos Map::TileEdgeToWorld(TilePos p) const {
|
||||
return WorldPos{p.x() * TILE_SIZE, p.y() * TILE_SIZE};
|
||||
}
|
||||
|
||||
TilePos Map::WorldToTile(WorldPos p) const {
|
||||
return TilePos{static_cast<int32_t>(p.x() / TILE_SIZE),
|
||||
static_cast<int32_t>(p.y() / TILE_SIZE)};
|
||||
}
|
||||
|
||||
WorldSize Map::GetTileSize() const { return WorldSize{TILE_SIZE, TILE_SIZE}; }
|
||||
|
||||
const Tile *Map::GetTileAt(TilePos p) const {
|
||||
assert(IsTilePosValid(p));
|
||||
size_t row = p.x();
|
||||
size_t col = p.y();
|
||||
|
||||
return m_Tiles[row][col];
|
||||
}
|
||||
|
||||
const Tile *Map::GetTileAt(WorldPos p) const {
|
||||
return GetTileAt(WorldToTile(p));
|
||||
}
|
||||
|
||||
bool Map::IsTilePosValid(TilePos p) const {
|
||||
if (p.x() < 0 || p.y() < 0)
|
||||
return false;
|
||||
size_t row = static_cast<size_t>(p.x());
|
||||
size_t col = static_cast<size_t>(p.y());
|
||||
|
||||
return row < m_Tiles.size() && col < m_Tiles[0].size();
|
||||
}
|
||||
|
||||
std::vector<TilePos> Map::GetNeighbors(TilePos center) const {
|
||||
std::vector<TilePos> neighbours;
|
||||
neighbours.reserve(4);
|
||||
|
||||
std::array<TilePos, 4> candidates = {
|
||||
center + TilePos{1, 0},
|
||||
center + TilePos{-1, 0},
|
||||
center + TilePos{0, 1},
|
||||
center + TilePos{0, -1},
|
||||
};
|
||||
|
||||
for (const auto &c : candidates) {
|
||||
if (IsTilePosValid(c))
|
||||
neighbours.push_back(c);
|
||||
}
|
||||
return neighbours;
|
||||
}
|
||||
|
||||
void Map::PaintCircle(TilePos center, unsigned radius, TileType tile_type) {
|
||||
// get rectangle that wraps the circle
|
||||
TilePos corner1 = TilePos{center.x() - static_cast<int32_t>(radius),
|
||||
center.y() - static_cast<int32_t>(radius)};
|
||||
TilePos corner2 = TilePos{center.x() + static_cast<int32_t>(radius),
|
||||
center.y() + static_cast<int32_t>(radius)};
|
||||
// iterate through all valid points, setting the type
|
||||
const unsigned radius_squared = radius * radius;
|
||||
for (int x = corner1.x(); x < corner2.x(); x++) {
|
||||
for (int y = corner1.y(); y < corner2.y(); y++) {
|
||||
TilePos current_tile = {x, y};
|
||||
unsigned distance_squared = static_cast<unsigned>(
|
||||
center.DistanceTo(current_tile) * center.DistanceTo(current_tile));
|
||||
if (IsTilePosValid(current_tile) && distance_squared < radius_squared) {
|
||||
// y is row, x is col
|
||||
m_Tiles[y][x] = &tile_types.at(tile_type);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Map::PaintLine(TilePos start_tile, TilePos stop_tile, double width,
|
||||
TileType tile_type) {
|
||||
const vec<double, 2> start{static_cast<double>(start_tile.x()),
|
||||
static_cast<double>(start_tile.y())};
|
||||
const vec<double, 2> stop{static_cast<double>(stop_tile.x()),
|
||||
static_cast<double>(stop_tile.y())};
|
||||
const double line_length = start.DistanceTo(stop);
|
||||
const vec<double, 2> step = (stop - start) / line_length;
|
||||
const vec<double, 2> ortho = step.GetOrthogonal();
|
||||
LOG_DEBUG("step = ", step, " ortho = ", ortho);
|
||||
|
||||
// NOLINTNEXTLINE(clang-analyzer-security.FloatLoopCounter)
|
||||
for (double t = 0; t < line_length; t += 1.0) {
|
||||
// NOLINTNEXTLINE(clang-analyzer-security.FloatLoopCounter)
|
||||
for (double ortho_t = 0; ortho_t < width; ortho_t += 0.1) {
|
||||
auto tile_pos = start + step * t + ortho * ortho_t;
|
||||
TilePos tile_pos_int{static_cast<int32_t>(tile_pos.x()),
|
||||
static_cast<int32_t>(tile_pos.y())};
|
||||
if (IsTilePosValid(tile_pos_int)) {
|
||||
size_t row = static_cast<size_t>(tile_pos.x());
|
||||
size_t col = static_cast<size_t>(tile_pos.y());
|
||||
m_Tiles[row][col] = &tile_types.at(tile_type);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void Map::PaintRectangle(TilePos first_corner, TilePos second_corner,
|
||||
TileType tile_type) {
|
||||
std::initializer_list<int> xvals = {first_corner.x(), second_corner.x()};
|
||||
std::initializer_list<int> yvals = {first_corner.y(), second_corner.y()};
|
||||
for (int x = std::min(xvals); x < std::max(xvals); x++) {
|
||||
for (int y = std::min(yvals); y < std::max(yvals); y++) {
|
||||
TilePos tile_pos{x, y};
|
||||
LOG_DEBUG("tile_pos = ", tile_pos);
|
||||
if (IsTilePosValid(tile_pos)) {
|
||||
size_t row = static_cast<size_t>(tile_pos.x());
|
||||
size_t col = static_cast<size_t>(tile_pos.y());
|
||||
m_Tiles[row][col] = &tile_types.at(tile_type);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
52
cpp/src/map.hpp
Normal file
52
cpp/src/map.hpp
Normal file
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "math.hpp"
|
||||
#include "tile.hpp"
|
||||
|
||||
using TileGrid = std::vector<std::vector<const Tile *>>;
|
||||
|
||||
class Map {
|
||||
public:
|
||||
static constexpr float TILE_SIZE = 10.0f; // tile size in world
|
||||
|
||||
Map(int rows, int cols);
|
||||
Map() : Map(0, 0) {}
|
||||
|
||||
Map(const Map &) = delete;
|
||||
Map(Map &&) = delete;
|
||||
Map &operator=(const Map &) = delete;
|
||||
Map &operator=(Map &&) = delete;
|
||||
|
||||
const TileGrid &GetMapTiles() const { return m_Tiles; }
|
||||
|
||||
// coordinate conversion functions
|
||||
WorldPos TileToWorld(TilePos p) const;
|
||||
WorldPos TileEdgeToWorld(TilePos p) const;
|
||||
TilePos WorldToTile(WorldPos p) const;
|
||||
|
||||
WorldSize GetTileSize() const;
|
||||
const Tile *GetTileAt(TilePos p) const;
|
||||
const Tile *GetTileAt(WorldPos p) const;
|
||||
|
||||
bool IsTilePosValid(TilePos p) const;
|
||||
|
||||
// methods for drawing on the map
|
||||
void PaintCircle(TilePos center, unsigned radius, TileType tile_type);
|
||||
void PaintLine(TilePos start, TilePos stop, double width, TileType tile_type);
|
||||
void PaintRectangle(TilePos first_corner, TilePos second_corner,
|
||||
TileType tile_type);
|
||||
|
||||
std::vector<TilePos> GetNeighbors(TilePos center) const;
|
||||
float GetCost(TilePos pos) const { return GetTileAt(pos)->cost; }
|
||||
|
||||
template <typename T> double GetTileVelocityCoeff(T p) const {
|
||||
return 1.0 / GetTileAt(p)->cost;
|
||||
}
|
||||
|
||||
private:
|
||||
TileGrid m_Tiles;
|
||||
size_t m_Cols = 0;
|
||||
size_t m_Rows = 0;
|
||||
};
|
||||
516
cpp/src/math.hpp
516
cpp/src/math.hpp
@@ -1,93 +1,455 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <concepts>
|
||||
#include <functional>
|
||||
#include <initializer_list>
|
||||
#include <iostream>
|
||||
|
||||
#ifdef _WIN32
|
||||
#include <numbers>
|
||||
#define M_PI std::numbers::pi
|
||||
#endif
|
||||
#include <numeric>
|
||||
#include <ranges>
|
||||
#include <utility>
|
||||
|
||||
template <typename T> struct Vec2D {
|
||||
public:
|
||||
Vec2D() = default;
|
||||
~Vec2D() = default;
|
||||
|
||||
Vec2D &operator+=(const Vec2D &other) {
|
||||
x += other.x;
|
||||
y += other.y;
|
||||
return *this;
|
||||
}
|
||||
|
||||
friend Vec2D operator+(const Vec2D &a, const Vec2D &b) {
|
||||
return Vec2D{a.x + b.x, a.y + b.y};
|
||||
}
|
||||
|
||||
friend Vec2D operator-(const Vec2D &a, const Vec2D &b) {
|
||||
return Vec2D{a.x - b.x, a.y - b.y};
|
||||
}
|
||||
|
||||
friend Vec2D operator*(float k, const Vec2D &v) {
|
||||
return Vec2D{k * v.x, k * v.y};
|
||||
}
|
||||
|
||||
Vec2D operator*(float b) const { return Vec2D{b * x, b * y}; }
|
||||
|
||||
T distance_squared(const Vec2D &other) const {
|
||||
T dx = x - other.x;
|
||||
T dy = y - other.y;
|
||||
return dx * dx + dy * dy;
|
||||
}
|
||||
|
||||
T distance(const Vec2D &other) const
|
||||
requires std::floating_point<T>
|
||||
{
|
||||
return sqrt(distance_squared(other));
|
||||
}
|
||||
|
||||
void normalize()
|
||||
requires std::floating_point<T>
|
||||
{
|
||||
auto length = sqrt(x * x + y * y);
|
||||
if (length < 1e-6) {
|
||||
x = y = 0;
|
||||
template <typename T>
|
||||
requires std::floating_point<T>
|
||||
static inline bool equalEpsilon(const T &a, const T &b) {
|
||||
constexpr auto epsilon = []() {
|
||||
if constexpr (std::is_same_v<T, float>) {
|
||||
return T{1e-5};
|
||||
} else {
|
||||
x /= length;
|
||||
y /= length;
|
||||
return T{1e-12}; // double, long double
|
||||
}
|
||||
}();
|
||||
if (a == b) {
|
||||
// handle special cases: bit equality, Inf...
|
||||
return true;
|
||||
}
|
||||
return std::abs(a - b) < epsilon;
|
||||
}
|
||||
|
||||
struct Any {};
|
||||
|
||||
template <typename T, size_t N, typename Tag = Any> class vec {
|
||||
|
||||
// Friend declaration for move constructor from different tag types
|
||||
template <typename U, size_t M, typename OtherTag> friend class vec;
|
||||
|
||||
public:
|
||||
vec() : m_Array{} {}
|
||||
|
||||
template <typename... ArgsT>
|
||||
requires(std::same_as<ArgsT, T> && ...) && (sizeof...(ArgsT) == N)
|
||||
vec(ArgsT... args) : m_Array{args...} {}
|
||||
|
||||
vec(std::array<T, N> array) : m_Array{array} {}
|
||||
|
||||
template <typename OtherTag>
|
||||
vec(vec<T, N, OtherTag> &&other) : m_Array{std::move(other.m_Array)} {}
|
||||
|
||||
//
|
||||
// Access to elements & data
|
||||
//
|
||||
|
||||
const T &operator[](size_t index) const {
|
||||
// we leave run-time checks to the underlying std::array
|
||||
return m_Array[index];
|
||||
}
|
||||
|
||||
T &operator[](size_t index) {
|
||||
// we leave run-time checks to the underlying std::array
|
||||
return m_Array[index];
|
||||
}
|
||||
|
||||
friend std::ostream &operator<<(std::ostream &os, const vec &obj) {
|
||||
os << "( ";
|
||||
for (const auto &element : obj.m_Array) {
|
||||
os << element << " ";
|
||||
}
|
||||
os << ")";
|
||||
return os;
|
||||
}
|
||||
|
||||
std::array<T, N> &Data() { return m_Array; }
|
||||
|
||||
//
|
||||
// binary operators
|
||||
//
|
||||
|
||||
friend bool operator==(const vec &a, const vec &b)
|
||||
requires(std::is_integral_v<T>)
|
||||
{
|
||||
return std::ranges::equal(a.m_Array, b.m_Array);
|
||||
}
|
||||
|
||||
friend bool operator==(const vec &a, const vec &b)
|
||||
requires(std::is_floating_point_v<T>)
|
||||
{
|
||||
for (const auto &[u, v] : std::views::zip(a.m_Array, b.m_Array)) {
|
||||
if (!equalEpsilon(u, v)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
friend bool operator!=(const vec &a, const vec &b) { return !(a == b); }
|
||||
|
||||
friend vec operator+(const vec &a, const vec &b) {
|
||||
vec<T, N, Tag> c;
|
||||
std::ranges::transform(a.m_Array, b.m_Array, c.m_Array.begin(),
|
||||
std::plus{});
|
||||
return c;
|
||||
}
|
||||
|
||||
friend vec operator+(const vec &a, T b) {
|
||||
vec<T, N, Tag> c;
|
||||
std::ranges::transform(a.m_Array, std::views::repeat(b), c.m_Array.begin(),
|
||||
std::plus{});
|
||||
return c;
|
||||
}
|
||||
|
||||
friend vec operator-(const vec &a, const vec &b) {
|
||||
vec<T, N, Tag> c;
|
||||
std::ranges::transform(a.m_Array, b.m_Array, c.m_Array.begin(),
|
||||
std::minus{});
|
||||
return c;
|
||||
}
|
||||
|
||||
friend vec operator-(const vec &a, T b) {
|
||||
vec<T, N, Tag> c;
|
||||
std::ranges::transform(a.m_Array, std::views::repeat(b), c.m_Array.begin(),
|
||||
std::minus{});
|
||||
return c;
|
||||
}
|
||||
|
||||
friend vec operator*(const vec &a, const T &scalar) {
|
||||
vec<T, N, Tag> c;
|
||||
std::ranges::transform(a.m_Array, std::views::repeat(scalar),
|
||||
c.m_Array.begin(), std::multiplies{});
|
||||
return c;
|
||||
}
|
||||
|
||||
friend vec operator*(const T &scalar, const vec &a) { return a * scalar; }
|
||||
|
||||
friend vec operator/(const vec &a, const T &scalar) {
|
||||
vec<T, N, Tag> c;
|
||||
std::ranges::transform(a.m_Array, std::views::repeat(scalar),
|
||||
c.m_Array.begin(), std::divides{});
|
||||
return c;
|
||||
}
|
||||
|
||||
friend vec operator/(const vec &a, const vec &b) {
|
||||
vec<T, N, Tag> c;
|
||||
std::ranges::transform(a.m_Array, b.m_Array, c.m_Array.begin(),
|
||||
std::divides{});
|
||||
return c;
|
||||
}
|
||||
|
||||
//
|
||||
// compound-assignment operators
|
||||
//
|
||||
|
||||
vec &operator+=(const vec &b) {
|
||||
vec &a = *this;
|
||||
std::ranges::transform(a.m_Array, b.m_Array, a.m_Array.begin(),
|
||||
std::plus{});
|
||||
return a;
|
||||
}
|
||||
|
||||
vec &operator-=(const vec &b) {
|
||||
vec &a = *this;
|
||||
std::ranges::transform(a.m_Array, b.m_Array, a.m_Array.begin(),
|
||||
std::minus{});
|
||||
return a;
|
||||
}
|
||||
|
||||
vec &operator/=(float scalar) {
|
||||
vec &a = *this;
|
||||
auto b = std::views::repeat(scalar);
|
||||
std::ranges::transform(a.m_Array, b, a.m_Array.begin(), std::divides{});
|
||||
return a;
|
||||
}
|
||||
|
||||
//
|
||||
// Utility functions
|
||||
//
|
||||
|
||||
T LengthSquared() const {
|
||||
return std::transform_reduce(m_Array.begin(), m_Array.end(), T{},
|
||||
std::plus{}, [](T x) { return x * x; });
|
||||
}
|
||||
|
||||
T Length() const { return std::sqrt(LengthSquared()); }
|
||||
|
||||
T DistanceTo(const vec &b) const {
|
||||
const vec &a = *this;
|
||||
return (a - b).Length();
|
||||
}
|
||||
|
||||
T DistanceSquared(const vec &b) const {
|
||||
const vec &a = *this;
|
||||
return (a - b).LengthSquared();
|
||||
}
|
||||
|
||||
//
|
||||
// In-place vector operations
|
||||
//
|
||||
|
||||
void Normalize() {
|
||||
T length = Length();
|
||||
if (equalEpsilon(length, T{0}))
|
||||
return;
|
||||
std::ranges::transform(m_Array, std::views::repeat(length), m_Array.begin(),
|
||||
std::divides{});
|
||||
}
|
||||
|
||||
//
|
||||
// Methods returning new object
|
||||
//
|
||||
|
||||
vec GetNormalized() const {
|
||||
vec tmp = *this;
|
||||
tmp.Normalize();
|
||||
return tmp;
|
||||
}
|
||||
|
||||
vec GetOrthogonal() const
|
||||
requires(N == 2)
|
||||
{
|
||||
vec tmp = *this;
|
||||
|
||||
std::swap(tmp.m_Array[0], tmp.m_Array[1]);
|
||||
tmp.m_Array[0] *= -1;
|
||||
|
||||
return tmp;
|
||||
}
|
||||
|
||||
static T DotProduct(const vec &a, const vec &b) {
|
||||
return std::inner_product(a.m_Array.begin(), a.m_Array.end(),
|
||||
b.m_Array.begin(), T{}, std::plus{},
|
||||
std::multiplies{});
|
||||
}
|
||||
|
||||
T DotProduct(const vec &b) const {
|
||||
const auto &a = *this;
|
||||
return DotProduct(a, b);
|
||||
}
|
||||
|
||||
//
|
||||
// Helpers
|
||||
//
|
||||
|
||||
const T &x() const
|
||||
requires(N >= 1)
|
||||
{
|
||||
return m_Array[0];
|
||||
}
|
||||
|
||||
T &x()
|
||||
requires(N >= 1)
|
||||
{
|
||||
return m_Array[0];
|
||||
}
|
||||
|
||||
const T &y() const
|
||||
requires(N >= 2)
|
||||
{
|
||||
return m_Array[1];
|
||||
}
|
||||
|
||||
T &y()
|
||||
requires(N >= 2)
|
||||
{
|
||||
return m_Array[1];
|
||||
}
|
||||
|
||||
const T &z() const
|
||||
requires(N >= 3)
|
||||
{
|
||||
return m_Array[2];
|
||||
}
|
||||
|
||||
T &z()
|
||||
requires(N >= 3)
|
||||
{
|
||||
return m_Array[2];
|
||||
}
|
||||
|
||||
template <typename TargetTag> vec<T, N, TargetTag> ChangeTag() const & {
|
||||
return vec<T, N, TargetTag>(m_Array);
|
||||
}
|
||||
|
||||
template <typename TargetTag> vec<T, N, TargetTag> ChangeTag() && {
|
||||
return vec<T, N, TargetTag>(std::move(*this));
|
||||
}
|
||||
|
||||
// Structured binding support for N == 2
|
||||
template <size_t I>
|
||||
const T &get() const
|
||||
requires(N == 2 && I < 2)
|
||||
{
|
||||
return m_Array[I];
|
||||
}
|
||||
|
||||
template <size_t I>
|
||||
T &get()
|
||||
requires(N == 2 && I < 2)
|
||||
{
|
||||
return m_Array[I];
|
||||
}
|
||||
|
||||
private:
|
||||
std::array<T, N> m_Array;
|
||||
};
|
||||
|
||||
//
|
||||
// Aliases
|
||||
//
|
||||
|
||||
using vec2 = vec<float, 2>;
|
||||
using vec3 = vec<float, 3>;
|
||||
using vec4 = vec<float, 4>;
|
||||
using dvec2 = vec<double, 2>;
|
||||
using dvec3 = vec<double, 3>;
|
||||
using dvec4 = vec<double, 4>;
|
||||
using ivec2 = vec<std::int32_t, 2>;
|
||||
using ivec3 = vec<std::int32_t, 3>;
|
||||
using ivec4 = vec<std::int32_t, 4>;
|
||||
using uvec2 = vec<std::uint32_t, 2>;
|
||||
using uvec3 = vec<std::uint32_t, 3>;
|
||||
using uvec4 = vec<std::uint32_t, 4>;
|
||||
|
||||
// tags for differentiating between domains
|
||||
struct WorldPosTag {};
|
||||
struct WorldSizeTag {};
|
||||
struct WindowPosTag {};
|
||||
struct WindowSizeTag {};
|
||||
struct TilePosTag {};
|
||||
struct TileSizeTag {};
|
||||
|
||||
// types for each domain
|
||||
using WorldPos = vec<float, 2, WorldPosTag>;
|
||||
using WindowPos = vec<float, 2, WindowPosTag>;
|
||||
using TilePos = vec<int32_t, 2, TilePosTag>;
|
||||
// Size
|
||||
using WorldSize = vec<float, 2, WorldSizeTag>;
|
||||
using WindowSize = vec<float, 2, WindowSizeTag>;
|
||||
using TileSize = vec<int32_t, 2, TileSizeTag>;
|
||||
|
||||
//
|
||||
// Utils
|
||||
//
|
||||
|
||||
struct TilePosHash {
|
||||
std::size_t operator()(const TilePos &p) const noexcept {
|
||||
std::size_t h1 = std::hash<int>{}(p.x());
|
||||
std::size_t h2 = std::hash<int>{}(p.y());
|
||||
return h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h1 >> 2));
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
// Matrix
|
||||
//
|
||||
|
||||
// Collumn major square matrix
|
||||
template <typename T, size_t N, typename Tag = Any> class Matrix {
|
||||
|
||||
using vec_type = vec<T, N, Tag>;
|
||||
|
||||
public:
|
||||
Matrix() = default;
|
||||
|
||||
// Initialization using flat array of N*N elements
|
||||
template <typename Tarr, size_t M>
|
||||
requires(M == N * N && std::same_as<Tarr, T>)
|
||||
Matrix(std::array<Tarr, M> array) : m_Array{} {
|
||||
std::size_t idx = 0;
|
||||
for (auto col : array | std::views::chunk(N)) {
|
||||
std::ranges::copy(col, m_Array[idx++].Data().begin());
|
||||
}
|
||||
}
|
||||
|
||||
Vec2D normalized()
|
||||
requires std::floating_point<T>
|
||||
{
|
||||
Vec2D v(*this);
|
||||
v.normalize();
|
||||
return v;
|
||||
}
|
||||
const vec_type &operator[](size_t index) const { return m_Array[index]; }
|
||||
vec_type &operator[](size_t index) { return m_Array[index]; }
|
||||
|
||||
Vec2D orthogonal()
|
||||
{
|
||||
Vec2D v(*this);
|
||||
|
||||
std::swap(v.x, v.y);
|
||||
v.x = -v.x;
|
||||
return v;
|
||||
}
|
||||
|
||||
template <typename U> Vec2D(std::initializer_list<U> list) {
|
||||
assert(list.size() == 2);
|
||||
auto first_element = *list.begin();
|
||||
auto second_element = *(list.begin() + 1);
|
||||
x = static_cast<T>(first_element);
|
||||
y = static_cast<T>(second_element);
|
||||
}
|
||||
|
||||
T x, y;
|
||||
|
||||
friend std::ostream &operator<<(std::ostream &os, const Vec2D &obj) {
|
||||
os << "( " << obj.x << ", " << obj.y << ")";
|
||||
friend std::ostream &operator<<(std::ostream &os, const Matrix &obj) {
|
||||
os << "( ";
|
||||
for (const auto &element : obj.m_Array) {
|
||||
os << element << " ";
|
||||
}
|
||||
os << ")";
|
||||
return os;
|
||||
}
|
||||
|
||||
friend Matrix operator+(const Matrix &A, const Matrix &B) {
|
||||
Matrix C;
|
||||
std::ranges::transform(A.m_Array, B.m_Array, C.m_Array.begin(),
|
||||
std::plus{});
|
||||
return C;
|
||||
}
|
||||
|
||||
friend Matrix operator-(const Matrix &A, const Matrix &B) {
|
||||
Matrix C;
|
||||
std::ranges::transform(A.m_Array, B.m_Array, C.m_Array.begin(),
|
||||
std::minus{});
|
||||
return C;
|
||||
}
|
||||
|
||||
friend Matrix operator*(const Matrix &A, const Matrix &B) {
|
||||
Matrix C;
|
||||
|
||||
for (size_t i = 0; i < N; i++) {
|
||||
for (size_t j = 0; j < N; j++) {
|
||||
T sum = 0;
|
||||
for (size_t k = 0; k < N; ++k)
|
||||
sum += A[i][k] * B[k][j];
|
||||
C[i][j] = sum;
|
||||
}
|
||||
}
|
||||
return C;
|
||||
}
|
||||
|
||||
friend vec_type operator*(const Matrix &A, const vec_type &b) {
|
||||
// we assume that b is row vector
|
||||
vec_type c;
|
||||
for (size_t i = 0; i < N; i++) {
|
||||
c[i] = b.DotProduct(A[i]);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
static constexpr Matrix Eye() {
|
||||
Matrix E;
|
||||
for (size_t i = 0; i < N; i++) {
|
||||
E[i][i] = T{1};
|
||||
}
|
||||
return E;
|
||||
}
|
||||
|
||||
private:
|
||||
std::array<vec_type, N> m_Array;
|
||||
};
|
||||
|
||||
// Structured binding support for vec<T, 2, Tag>
|
||||
namespace std {
|
||||
template <typename T, typename Tag>
|
||||
struct tuple_size<vec<T, 2, Tag>> : integral_constant<size_t, 2> {};
|
||||
|
||||
template <size_t I, typename T, typename Tag>
|
||||
struct tuple_element<I, vec<T, 2, Tag>> {
|
||||
using type = T;
|
||||
};
|
||||
} // namespace std
|
||||
|
||||
// ADL-based get for structured bindings
|
||||
template <size_t I, typename T, typename Tag>
|
||||
const T &get(const vec<T, 2, Tag> &v) {
|
||||
return v.template get<I>();
|
||||
}
|
||||
|
||||
template <size_t I, typename T, typename Tag> T &get(vec<T, 2, Tag> &v) {
|
||||
return v.template get<I>();
|
||||
}
|
||||
|
||||
0
cpp/src/pathfinder/astar.cpp
Normal file
0
cpp/src/pathfinder/astar.cpp
Normal file
0
cpp/src/pathfinder/astar.hpp
Normal file
0
cpp/src/pathfinder/astar.hpp
Normal file
23
cpp/src/pathfinder/base.cpp
Normal file
23
cpp/src/pathfinder/base.cpp
Normal file
@@ -0,0 +1,23 @@
|
||||
#include <cassert>
|
||||
#include <memory>
|
||||
#include <queue>
|
||||
|
||||
#include "pathfinder/base.hpp"
|
||||
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
namespace pathfinder {
|
||||
|
||||
PathFinderBase::PathFinderBase(const Map *map) : m_Map(map) {}
|
||||
|
||||
// LinearPathFinder also lives here, since it is too small to get it's
|
||||
// own implementation file
|
||||
Path LinearPathFinder::CalculatePath(
|
||||
WorldPos, WorldPos end) // first argument (start pos) not used
|
||||
{
|
||||
auto path = Path{end};
|
||||
return path;
|
||||
}
|
||||
|
||||
} // namespace pathfinder
|
||||
50
cpp/src/pathfinder/base.hpp
Normal file
50
cpp/src/pathfinder/base.hpp
Normal file
@@ -0,0 +1,50 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "map.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
namespace pathfinder {
|
||||
|
||||
using Path = std::vector<WorldPos>;
|
||||
|
||||
enum class PathFinderType {
|
||||
LINEAR = 1,
|
||||
BFS,
|
||||
DIJKSTRA,
|
||||
GBFS,
|
||||
COUNT,
|
||||
};
|
||||
|
||||
class PathFinderBase {
|
||||
public:
|
||||
PathFinderBase(const Map *m);
|
||||
virtual ~PathFinderBase() = default;
|
||||
|
||||
PathFinderBase(const PathFinderBase &) = delete;
|
||||
PathFinderBase(PathFinderBase &&) = delete;
|
||||
PathFinderBase &operator=(const PathFinderBase &) = delete;
|
||||
PathFinderBase &operator=(PathFinderBase &&) = delete;
|
||||
|
||||
virtual const std::string_view &GetName() const = 0;
|
||||
virtual Path CalculatePath(WorldPos start, WorldPos end) = 0;
|
||||
|
||||
protected:
|
||||
const Map *m_Map;
|
||||
};
|
||||
|
||||
class LinearPathFinder final : public PathFinderBase {
|
||||
|
||||
public:
|
||||
LinearPathFinder(const Map *m) : PathFinderBase(m) {}
|
||||
Path CalculatePath(WorldPos start, WorldPos end) override;
|
||||
const std::string_view &GetName() const override { return m_Name; }
|
||||
|
||||
private:
|
||||
const std::string_view m_Name = "Linear Path";
|
||||
};
|
||||
|
||||
} // namespace pathfinder
|
||||
67
cpp/src/pathfinder/bfs.cpp
Normal file
67
cpp/src/pathfinder/bfs.cpp
Normal file
@@ -0,0 +1,67 @@
|
||||
#include <queue>
|
||||
|
||||
#include "bfs.hpp"
|
||||
|
||||
#include "base.hpp"
|
||||
#include "map.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
namespace pathfinder {
|
||||
|
||||
Path BFS::CalculatePath(WorldPos start_world, WorldPos end_world) {
|
||||
if (m_Map == nullptr)
|
||||
return {};
|
||||
|
||||
const TilePos start = m_Map->WorldToTile(start_world);
|
||||
const TilePos end = m_Map->WorldToTile(end_world);
|
||||
|
||||
if (!m_Map->IsTilePosValid(start) || !m_Map->IsTilePosValid(end))
|
||||
return {};
|
||||
if (start == end) {
|
||||
return {};
|
||||
}
|
||||
// clear previous run
|
||||
m_CameFrom.clear();
|
||||
m_Distance.clear();
|
||||
|
||||
std::queue<TilePos> frontier;
|
||||
frontier.push(start);
|
||||
m_CameFrom[start] = start;
|
||||
m_Distance[start] = 0.0f;
|
||||
|
||||
// ---------------- build flow-field ----------------
|
||||
bool early_exit = false;
|
||||
while (!frontier.empty() && !early_exit) {
|
||||
TilePos current = frontier.front();
|
||||
frontier.pop();
|
||||
|
||||
for (TilePos next : m_Map->GetNeighbors(current)) {
|
||||
if (m_CameFrom.find(next) == m_CameFrom.end()) { // not visited
|
||||
frontier.push(next);
|
||||
m_Distance[next] = m_Distance[current] + 1.0f;
|
||||
m_CameFrom[next] = current;
|
||||
|
||||
if (next == end) { // early exit
|
||||
early_exit = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --------------- reconstruct path -----------------
|
||||
if (m_CameFrom.find(end) == m_CameFrom.end())
|
||||
return {}; // end not reached
|
||||
|
||||
Path path;
|
||||
TilePos cur = end;
|
||||
path.push_back(m_Map->TileToWorld(cur));
|
||||
while (cur != start) {
|
||||
cur = m_CameFrom[cur];
|
||||
path.push_back(m_Map->TileToWorld(cur));
|
||||
}
|
||||
std::reverse(path.begin(), path.end());
|
||||
return path;
|
||||
}
|
||||
|
||||
} // namespace pathfinder
|
||||
25
cpp/src/pathfinder/bfs.hpp
Normal file
25
cpp/src/pathfinder/bfs.hpp
Normal file
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "base.hpp"
|
||||
|
||||
#include "math.hpp"
|
||||
|
||||
namespace pathfinder {
|
||||
|
||||
class BFS final : public PathFinderBase {
|
||||
|
||||
public:
|
||||
BFS(const Map *m) : PathFinderBase(m) {}
|
||||
Path CalculatePath(WorldPos start, WorldPos end) override;
|
||||
const std::string_view &GetName() const override { return m_Name; }
|
||||
|
||||
private:
|
||||
const std::string_view m_Name = "Breadth First Search";
|
||||
std::unordered_map<TilePos, double, TilePosHash> m_Distance;
|
||||
std::unordered_map<TilePos, TilePos, TilePosHash> m_CameFrom;
|
||||
};
|
||||
|
||||
} // namespace pathfinder
|
||||
71
cpp/src/pathfinder/dijkstra.cpp
Normal file
71
cpp/src/pathfinder/dijkstra.cpp
Normal file
@@ -0,0 +1,71 @@
|
||||
#include <queue>
|
||||
|
||||
#include "dijkstra.hpp"
|
||||
|
||||
#include "base.hpp"
|
||||
#include "map.hpp"
|
||||
#include "math.hpp"
|
||||
#include "utils.hpp"
|
||||
|
||||
namespace pathfinder {
|
||||
|
||||
Path Dijkstra::CalculatePath(WorldPos start_world, WorldPos end_world) {
|
||||
using QueueEntry = utils::QueueEntry;
|
||||
|
||||
if (!m_Map)
|
||||
return {};
|
||||
|
||||
const TilePos start = m_Map->WorldToTile(start_world);
|
||||
const TilePos end = m_Map->WorldToTile(end_world);
|
||||
|
||||
if (!m_Map->IsTilePosValid(start) || !m_Map->IsTilePosValid(end))
|
||||
return {};
|
||||
if (start == end)
|
||||
return {};
|
||||
|
||||
// clear previous run
|
||||
m_CameFrom.clear();
|
||||
m_Cost.clear();
|
||||
|
||||
std::priority_queue<QueueEntry, std::vector<QueueEntry>, std::greater<>>
|
||||
frontier;
|
||||
frontier.push({0.0f, start});
|
||||
m_CameFrom[start] = start; // sentinel
|
||||
m_Cost[start] = 0.0f;
|
||||
|
||||
while (!frontier.empty()) {
|
||||
const QueueEntry current = frontier.top();
|
||||
frontier.pop();
|
||||
|
||||
if (current.tile == end) // early exit
|
||||
break;
|
||||
|
||||
for (TilePos next : m_Map->GetNeighbors(current.tile)) {
|
||||
// cost of moving to neighbour (uniform 1.0 matches original BFS)
|
||||
const float newCost = m_Cost[current.tile] + m_Map->GetCost(next);
|
||||
|
||||
if (!m_Cost.count(next) || newCost < m_Cost[next]) {
|
||||
m_Cost[next] = newCost;
|
||||
m_CameFrom[next] = current.tile;
|
||||
frontier.push({newCost, next});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reconstruct path
|
||||
if (!m_CameFrom.count(end))
|
||||
return {}; // goal never reached
|
||||
|
||||
Path path;
|
||||
TilePos cur = end;
|
||||
path.push_back(m_Map->TileToWorld(cur));
|
||||
|
||||
while (cur != start) {
|
||||
cur = m_CameFrom[cur];
|
||||
path.push_back(m_Map->TileToWorld(cur));
|
||||
}
|
||||
std::reverse(path.begin(), path.end());
|
||||
return path;
|
||||
}
|
||||
|
||||
} // namespace pathfinder
|
||||
26
cpp/src/pathfinder/dijkstra.hpp
Normal file
26
cpp/src/pathfinder/dijkstra.hpp
Normal file
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "base.hpp"
|
||||
|
||||
#include "map.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
namespace pathfinder {
|
||||
|
||||
class Dijkstra final : public PathFinderBase {
|
||||
|
||||
public:
|
||||
Dijkstra(const Map *m) : PathFinderBase(m) {}
|
||||
Path CalculatePath(WorldPos start, WorldPos end) override;
|
||||
const std::string_view &GetName() const override { return m_Name; }
|
||||
|
||||
private:
|
||||
const std::string_view m_Name = "Dijkstra's Algorithm";
|
||||
std::unordered_map<TilePos, double, TilePosHash> m_Cost;
|
||||
std::unordered_map<TilePos, TilePos, TilePosHash> m_CameFrom;
|
||||
};
|
||||
|
||||
} // namespace pathfinder
|
||||
69
cpp/src/pathfinder/gbfs.cpp
Normal file
69
cpp/src/pathfinder/gbfs.cpp
Normal file
@@ -0,0 +1,69 @@
|
||||
#include <queue>
|
||||
|
||||
#include "gbfs.hpp"
|
||||
|
||||
#include "base.hpp"
|
||||
#include "map.hpp"
|
||||
#include "math.hpp"
|
||||
#include "pathfinder/utils.hpp"
|
||||
|
||||
namespace pathfinder {
|
||||
|
||||
float GBFS::Heuristic(const TilePos &a, const TilePos &b) {
|
||||
return static_cast<float>(std::abs(a.x() - b.x()) + std::abs(a.y() - b.y()));
|
||||
}
|
||||
|
||||
Path GBFS::CalculatePath(WorldPos start_world, WorldPos end_world) {
|
||||
using QueueEntry = pathfinder::utils::QueueEntry;
|
||||
|
||||
if (!m_Map)
|
||||
return {};
|
||||
|
||||
const TilePos start = m_Map->WorldToTile(start_world);
|
||||
const TilePos end = m_Map->WorldToTile(end_world);
|
||||
|
||||
if (!m_Map->IsTilePosValid(start) || !m_Map->IsTilePosValid(end))
|
||||
return {};
|
||||
if (start == end)
|
||||
return {};
|
||||
|
||||
m_CameFrom.clear();
|
||||
|
||||
std::priority_queue<QueueEntry, std::vector<QueueEntry>, std::greater<>>
|
||||
frontier;
|
||||
frontier.push({Heuristic(start, end), start});
|
||||
m_CameFrom[start] = start; // sentinel
|
||||
|
||||
while (!frontier.empty()) {
|
||||
const QueueEntry current = frontier.top();
|
||||
frontier.pop();
|
||||
|
||||
if (current.tile == end) // early exit
|
||||
break;
|
||||
|
||||
for (TilePos next : m_Map->GetNeighbors(current.tile)) {
|
||||
if (!m_CameFrom.count(next)) // not visited
|
||||
{
|
||||
m_CameFrom[next] = current.tile;
|
||||
frontier.push({Heuristic(end, next), next});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// reconstruct path
|
||||
if (!m_CameFrom.count(end))
|
||||
return {}; // goal never reached
|
||||
|
||||
Path path;
|
||||
TilePos cur = end;
|
||||
path.push_back(m_Map->TileToWorld(cur));
|
||||
|
||||
while (cur != start) {
|
||||
cur = m_CameFrom[cur];
|
||||
path.push_back(m_Map->TileToWorld(cur));
|
||||
}
|
||||
std::reverse(path.begin(), path.end());
|
||||
return path;
|
||||
}
|
||||
|
||||
} // namespace pathfinder
|
||||
26
cpp/src/pathfinder/gbfs.hpp
Normal file
26
cpp/src/pathfinder/gbfs.hpp
Normal file
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "base.hpp"
|
||||
|
||||
#include "map.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
namespace pathfinder {
|
||||
|
||||
class GBFS final : public PathFinderBase {
|
||||
|
||||
public:
|
||||
GBFS(const Map *m) : PathFinderBase(m) {}
|
||||
Path CalculatePath(WorldPos start, WorldPos end) override;
|
||||
const std::string_view &GetName() const override { return m_Name; }
|
||||
|
||||
private:
|
||||
static float Heuristic(const TilePos &a, const TilePos &b);
|
||||
const std::string_view m_Name = "Greedy Best First Search";
|
||||
std::unordered_map<TilePos, TilePos, TilePosHash> m_CameFrom;
|
||||
};
|
||||
|
||||
} // namespace pathfinder
|
||||
0
cpp/src/pathfinder/linear.cpp
Normal file
0
cpp/src/pathfinder/linear.cpp
Normal file
0
cpp/src/pathfinder/linear.hpp
Normal file
0
cpp/src/pathfinder/linear.hpp
Normal file
35
cpp/src/pathfinder/utils.cpp
Normal file
35
cpp/src/pathfinder/utils.cpp
Normal file
@@ -0,0 +1,35 @@
|
||||
#include <memory>
|
||||
|
||||
#include "utils.hpp"
|
||||
|
||||
#include "base.hpp"
|
||||
#include "log.hpp"
|
||||
#include "map.hpp"
|
||||
#include "math.hpp"
|
||||
#include "pathfinder/bfs.hpp"
|
||||
#include "pathfinder/dijkstra.hpp"
|
||||
#include "pathfinder/gbfs.hpp"
|
||||
|
||||
namespace pathfinder {
|
||||
namespace utils {
|
||||
|
||||
std::unique_ptr<PathFinderBase> create(PathFinderType type, const Map *map) {
|
||||
using namespace pathfinder;
|
||||
switch (type) {
|
||||
case PathFinderType::LINEAR:
|
||||
return std::make_unique<LinearPathFinder>(map);
|
||||
case PathFinderType::BFS:
|
||||
return std::make_unique<BFS>(map);
|
||||
case PathFinderType::DIJKSTRA:
|
||||
return std::make_unique<Dijkstra>(map);
|
||||
case PathFinderType::GBFS:
|
||||
return std::make_unique<GBFS>(map);
|
||||
case PathFinderType::COUNT:
|
||||
LOG_WARNING("Incorrect pathfinder type");
|
||||
return nullptr;
|
||||
};
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
} // namespace utils
|
||||
} // namespace pathfinder
|
||||
25
cpp/src/pathfinder/utils.hpp
Normal file
25
cpp/src/pathfinder/utils.hpp
Normal file
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
|
||||
#include "pathfinder/base.hpp"
|
||||
|
||||
#include "map.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
namespace pathfinder {
|
||||
namespace utils {
|
||||
|
||||
struct QueueEntry {
|
||||
float cost;
|
||||
TilePos tile;
|
||||
|
||||
// min-heap -> smallest cost on top
|
||||
bool operator>(const QueueEntry &o) const noexcept { return cost > o.cost; }
|
||||
};
|
||||
|
||||
std::unique_ptr<pathfinder::PathFinderBase>
|
||||
create(pathfinder::PathFinderType type, const Map *map);
|
||||
|
||||
} // namespace utils
|
||||
} // namespace pathfinder
|
||||
215
cpp/src/pathfindingdemo.cpp
Normal file
215
cpp/src/pathfindingdemo.cpp
Normal file
@@ -0,0 +1,215 @@
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <vector>
|
||||
|
||||
#include "pathfindingdemo.hpp"
|
||||
|
||||
#include "entities.hpp"
|
||||
#include "log.hpp"
|
||||
#include "map.hpp"
|
||||
#include "pathfinder/base.hpp"
|
||||
#include "pathfinder/utils.hpp"
|
||||
#include "tile.hpp"
|
||||
#include "user_input.hpp"
|
||||
|
||||
PathFindingDemo::PathFindingDemo(int width, int height) : m_Map(width, height) {
|
||||
LOG_DEBUG(".");
|
||||
// set default pathfinder method
|
||||
m_PathFinder = pathfinder::utils::create(pathfinder::PathFinderType::DIJKSTRA,
|
||||
(const Map *)&m_Map);
|
||||
}
|
||||
|
||||
PathFindingDemo::~PathFindingDemo() { LOG_DEBUG("."); }
|
||||
|
||||
void PathFindingDemo::AddEntity(std::shared_ptr<Entity> e) {
|
||||
m_Entities.push_back(e);
|
||||
}
|
||||
|
||||
void PathFindingDemo::CreateMap() {
|
||||
// lake
|
||||
m_Map.PaintCircle(TilePos{50, 50}, 10, TileType::WATER);
|
||||
m_Map.PaintCircle(TilePos{75, 100}, 50, TileType::WATER);
|
||||
// river
|
||||
m_Map.PaintLine(TilePos{0, 0}, TilePos{100, 100}, 3.0, TileType::WATER);
|
||||
// road
|
||||
m_Map.PaintLine(TilePos{17, 6}, TilePos{100, 6}, 5.0, TileType::ROAD);
|
||||
m_Map.PaintLine(TilePos{10, 17}, TilePos{10, 100}, 5.0, TileType::ROAD);
|
||||
m_Map.PaintLine(TilePos{20, 10}, TilePos{10, 20}, 5.0, TileType::ROAD);
|
||||
// bridges
|
||||
m_Map.PaintLine(TilePos{50, 75}, TilePos{70, 75}, 5.0, TileType::WOOD);
|
||||
m_Map.PaintLine(TilePos{95, 26}, TilePos{95, 60}, 5.0, TileType::WOOD);
|
||||
// island
|
||||
m_Map.PaintRectangle(TilePos{70, 60}, TilePos{100, 100}, TileType::GRASS);
|
||||
// walls
|
||||
m_Map.PaintLine(TilePos{71, 60}, TilePos{90, 60}, 1.0, TileType::WALL);
|
||||
m_Map.PaintLine(TilePos{77, 67}, TilePos{100, 67}, 1.0, TileType::WALL);
|
||||
m_Map.PaintLine(TilePos{71, 60}, TilePos{71, 75}, 1.0, TileType::WALL);
|
||||
m_Map.PaintLine(TilePos{72, 73}, TilePos{95, 73}, 1.0, TileType::WALL);
|
||||
m_Map.PaintLine(TilePos{95, 73}, TilePos{95, 90}, 1.0, TileType::WALL);
|
||||
m_Map.PaintLine(TilePos{71, 81}, TilePos{71, 100}, 1.0, TileType::WALL);
|
||||
m_Map.PaintLine(TilePos{72, 81}, TilePos{90, 81}, 1.0, TileType::WALL);
|
||||
m_Map.PaintLine(TilePos{89, 87}, TilePos{89, 100}, 1.0, TileType::WALL);
|
||||
m_Map.PaintLine(TilePos{84, 81}, TilePos{84, 96}, 1.0, TileType::WALL);
|
||||
m_Map.PaintLine(TilePos{78, 87}, TilePos{78, 100}, 1.0, TileType::WALL);
|
||||
|
||||
// add some controllable entities
|
||||
m_Entities.clear();
|
||||
auto player = std::make_shared<Player>();
|
||||
player->SetPosition(m_Map.TileToWorld(TilePos{25, 20}));
|
||||
AddEntity(player);
|
||||
|
||||
auto player2 = std::make_shared<Player>();
|
||||
player2->SetPosition(m_Map.TileToWorld(TilePos{50, 20}));
|
||||
AddEntity(player2);
|
||||
}
|
||||
|
||||
WorldPos PathFindingDemo::GetRandomPosition() const {
|
||||
return WorldPos{0.0f, 0.0f}; // totally random!
|
||||
}
|
||||
|
||||
const std::vector<Collision> &PathFindingDemo::GetEntityCollisions() {
|
||||
static std::vector<Collision> m_Collisions;
|
||||
m_Collisions.clear();
|
||||
|
||||
for (const auto &entity_A : m_Entities) {
|
||||
for (const auto &entity_B : m_Entities) {
|
||||
if (entity_A == entity_B)
|
||||
continue;
|
||||
if (!entity_A->IsCollidable() || !entity_B->IsCollidable())
|
||||
continue;
|
||||
if (entity_A->CollidesWith(*entity_B)) {
|
||||
// handle collision logic
|
||||
m_Collisions.emplace_back(Collision(entity_A, entity_B));
|
||||
}
|
||||
}
|
||||
}
|
||||
return m_Collisions;
|
||||
}
|
||||
|
||||
// Update entity positions, handle collisions
|
||||
void PathFindingDemo::UpdateWorld() {
|
||||
|
||||
float time_delta = 1.0f;
|
||||
|
||||
for (auto &entity : m_Entities) {
|
||||
// calculate the velocity
|
||||
auto current_pos = entity->GetPosition();
|
||||
double tile_velocity_coeff = m_Map.GetTileVelocityCoeff(current_pos);
|
||||
auto next_pos = entity->GetMoveTarget();
|
||||
WorldPos velocity = WorldPos{};
|
||||
if (next_pos) {
|
||||
velocity = next_pos.value() - current_pos;
|
||||
velocity.Normalize();
|
||||
// LOG_DEBUG("I want to move to: ", next_pos.value(),
|
||||
// ", velocity: ", velocity);
|
||||
}
|
||||
entity->SetActualVelocity(velocity * tile_velocity_coeff);
|
||||
|
||||
for (const auto &collision : GetEntityCollisions()) {
|
||||
auto weak_A = std::get<0>(collision);
|
||||
auto weak_B = std::get<1>(collision);
|
||||
auto A = weak_A.lock();
|
||||
auto B = weak_B.lock();
|
||||
if (A == nullptr || B == nullptr) {
|
||||
continue;
|
||||
}
|
||||
if (!A->IsMovable())
|
||||
continue;
|
||||
// modify actual speed
|
||||
// LOG_DEBUG("Collision: A is ", A, ", B is ", B);
|
||||
auto AB = B->GetPosition() - A->GetPosition();
|
||||
A->ZeroActualVelocityInDirection(AB);
|
||||
}
|
||||
|
||||
// update the position
|
||||
entity->Update(time_delta);
|
||||
}
|
||||
}
|
||||
|
||||
void PathFindingDemo::HandleActions(const std::vector<UserAction> &actions) {
|
||||
for (const auto &action : actions) {
|
||||
if (action.type == UserAction::Type::EXIT) {
|
||||
LOG_INFO("Exit requested");
|
||||
m_ExitRequested = true;
|
||||
} else if (action.type == UserAction::Type::SET_MOVE_TARGET) {
|
||||
WorldPos target_pos =
|
||||
m_Camera.WindowToWorld(std::get<WindowPos>(action.Argument));
|
||||
for (auto &selected_entity : m_SelectedEntities) {
|
||||
LOG_INFO("Calculating path to target: ", target_pos);
|
||||
if (auto sp = selected_entity.lock()) {
|
||||
auto path =
|
||||
m_PathFinder->CalculatePath(sp->GetPosition(), target_pos);
|
||||
sp->SetPath(path);
|
||||
LOG_INFO("Done, path node count: ", path.size());
|
||||
} else {
|
||||
LOG_INFO("Cannot calculate path for destroyed entity "
|
||||
"(weak_ptr.lock() failed)");
|
||||
}
|
||||
}
|
||||
} else if (action.type == UserAction::Type::SELECT_PATHFINDER) {
|
||||
using namespace pathfinder;
|
||||
PathFinderType type =
|
||||
static_cast<PathFinderType>(std::get<int32_t>(action.Argument));
|
||||
m_PathFinder = pathfinder::utils::create(type, (const Map *)&m_Map);
|
||||
LOG_INFO("Switched to path finding method: ", m_PathFinder->GetName());
|
||||
} else if (action.type == UserAction::Type::CAMERA_PAN) {
|
||||
const auto &window_pan = std::get<WindowPos>(action.Argument);
|
||||
WorldPos world_pan{window_pan.x(), window_pan.y()};
|
||||
m_Camera.Pan(world_pan);
|
||||
LOG_INFO("Camera pan delta: ", world_pan);
|
||||
} else if (action.type == UserAction::Type::CAMERA_ZOOM) {
|
||||
m_Camera.Zoom(std::get<float>(action.Argument));
|
||||
LOG_INFO("Camera zoom: ", std::get<float>(action.Argument));
|
||||
} else if (action.type == UserAction::Type::SELECTION_START) {
|
||||
m_SelectionBox.active = true;
|
||||
m_SelectionBox.start = std::get<WindowPos>(action.Argument);
|
||||
m_SelectionBox.end = std::get<WindowPos>(action.Argument);
|
||||
} else if (action.type == UserAction::Type::SELECTION_END) {
|
||||
m_SelectionBox.end = std::get<WindowPos>(action.Argument);
|
||||
m_SelectionBox.active = false;
|
||||
auto diff = m_SelectionBox.end - m_SelectionBox.start;
|
||||
// here we explicitly change the vector type from WindowPos to WindowSize
|
||||
m_SelectionBox.size = diff.ChangeTag<WindowSizeTag>();
|
||||
WorldPos start = m_Camera.WindowToWorld(m_SelectionBox.start);
|
||||
WorldPos end = m_Camera.WindowToWorld(m_SelectionBox.end);
|
||||
SelectEntitiesInRectangle(start, end);
|
||||
} else if (action.type == UserAction::Type::SELECTION_CHANGE) {
|
||||
m_SelectionBox.end = std::get<WindowPos>(action.Argument);
|
||||
auto diff = m_SelectionBox.end - m_SelectionBox.start;
|
||||
m_SelectionBox.size = diff.ChangeTag<WindowSizeTag>();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
void PathFindingDemo::DeselectEntities() {
|
||||
std::for_each(m_SelectedEntities.begin(), m_SelectedEntities.end(),
|
||||
[](auto &x) {
|
||||
if (auto entity = x.lock())
|
||||
entity->Deselect();
|
||||
});
|
||||
m_SelectedEntities.clear();
|
||||
}
|
||||
|
||||
void PathFindingDemo::SelectEntitiesInRectangle(WorldPos A, WorldPos B) {
|
||||
DeselectEntities();
|
||||
auto [x_min, x_max] = std::minmax(A.x(), B.x());
|
||||
auto [y_min, y_max] = std::minmax(A.y(), B.y());
|
||||
for (const auto &entity : m_Entities) {
|
||||
const auto &pos = entity->GetPosition();
|
||||
bool x_in_range = x_min < pos.x() && pos.x() < x_max;
|
||||
bool y_in_range = y_min < pos.y() && pos.y() < y_max;
|
||||
if (x_in_range && y_in_range) {
|
||||
m_SelectedEntities.push_back(std::weak_ptr(entity));
|
||||
entity->Select();
|
||||
}
|
||||
}
|
||||
LOG_INFO("Selected ", m_SelectedEntities.size(), " entities");
|
||||
}
|
||||
|
||||
std::pair<WindowPos, WindowSize> PathFindingDemo::GetSelectionBoxPosSize() {
|
||||
const auto &pos = m_SelectionBox.start;
|
||||
WindowPos size_pos = m_SelectionBox.end - m_SelectionBox.start;
|
||||
WindowSize size = size_pos.ChangeTag<WindowSizeTag>();
|
||||
return std::pair(pos, size);
|
||||
}
|
||||
62
cpp/src/pathfindingdemo.hpp
Normal file
62
cpp/src/pathfindingdemo.hpp
Normal file
@@ -0,0 +1,62 @@
|
||||
#pragma once
|
||||
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <queue>
|
||||
#include <vector>
|
||||
|
||||
#include "camera.hpp"
|
||||
#include "entities.hpp"
|
||||
#include "log.hpp"
|
||||
#include "map.hpp"
|
||||
#include "pathfinder/base.hpp"
|
||||
#include "user_input.hpp"
|
||||
|
||||
using Collision = std::pair<std::weak_ptr<Entity>, std::weak_ptr<Entity>>;
|
||||
|
||||
struct SelectionBox {
|
||||
WindowPos start, end;
|
||||
WindowSize size;
|
||||
bool active;
|
||||
};
|
||||
|
||||
class PathFindingDemo {
|
||||
public:
|
||||
PathFindingDemo(int width, int height);
|
||||
~PathFindingDemo();
|
||||
|
||||
PathFindingDemo(const PathFindingDemo &m) = delete;
|
||||
PathFindingDemo(PathFindingDemo &&m) = delete;
|
||||
PathFindingDemo &operator=(const PathFindingDemo &) = delete;
|
||||
PathFindingDemo &operator=(PathFindingDemo &&) = delete;
|
||||
|
||||
std::vector<std::shared_ptr<Entity>> &GetEntities() { return m_Entities; }
|
||||
const Map &GetMap() const { return m_Map; }
|
||||
const Camera &GetCamera() const { return m_Camera; }
|
||||
bool IsExitRequested() const { return m_ExitRequested; }
|
||||
|
||||
void AddEntity(std::shared_ptr<Entity> e);
|
||||
void CreateMap();
|
||||
void UpdateWorld();
|
||||
void HandleActions(const std::vector<UserAction> &actions);
|
||||
WorldPos GetRandomPosition() const;
|
||||
|
||||
void SelectEntitiesInRectangle(WorldPos A, WorldPos B);
|
||||
void DeselectEntities();
|
||||
bool IsSelectionBoxActive() const { return m_SelectionBox.active; }
|
||||
std::pair<WindowPos, WindowSize> GetSelectionBoxPosSize();
|
||||
std::vector<std::weak_ptr<Entity>> GetSelectedEntities() {
|
||||
return m_SelectedEntities;
|
||||
}
|
||||
|
||||
private:
|
||||
const std::vector<Collision> &GetEntityCollisions();
|
||||
|
||||
bool m_ExitRequested = false;
|
||||
Map m_Map;
|
||||
Camera m_Camera;
|
||||
std::vector<std::shared_ptr<Entity>> m_Entities;
|
||||
std::unique_ptr<pathfinder::PathFinderBase> m_PathFinder;
|
||||
std::vector<std::weak_ptr<Entity>> m_SelectedEntities;
|
||||
SelectionBox m_SelectionBox;
|
||||
};
|
||||
203
cpp/src/positional_container.hpp
Normal file
203
cpp/src/positional_container.hpp
Normal file
@@ -0,0 +1,203 @@
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <iterator>
|
||||
#include <memory>
|
||||
#include <vector>
|
||||
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
template <typename T>
|
||||
concept HasPosition = requires(T t, WorldPos pos) {
|
||||
{ t.GetPosition() } -> std::convertible_to<WorldPos>;
|
||||
t.SetPosition(pos);
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
requires HasPosition<T>
|
||||
|
||||
class IPositionalContainer {
|
||||
public:
|
||||
virtual ~IPositionalContainer() = default;
|
||||
virtual bool Add(std::shared_ptr<T> t) = 0;
|
||||
virtual std::vector<std::weak_ptr<T>> Get(const WorldPos &p,
|
||||
float radius) = 0;
|
||||
virtual void UpdateAll() = 0;
|
||||
virtual void Update(std::shared_ptr<T> item) = 0;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class IColliderContainer : public IPositionalContainer<T> {
|
||||
public:
|
||||
virtual std::vector<std::weak_ptr<T>> GetCollisions() = 0;
|
||||
};
|
||||
|
||||
template <typename T> class SimpleContainer : IPositionalContainer<T> {
|
||||
public:
|
||||
bool Add(std::shared_ptr<T> t) override {
|
||||
m_Items.push_back(t);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::weak_ptr<T>> Get(const WorldPos ¢er,
|
||||
float radius) override {
|
||||
std::vector<std::weak_ptr<T>> matched_items;
|
||||
for (const auto &item : m_Items) {
|
||||
if (center.DistanceTo(item->GetPosition()) < radius) {
|
||||
matched_items.push_back(item);
|
||||
}
|
||||
}
|
||||
return matched_items;
|
||||
}
|
||||
|
||||
// no update needed here, as we have no smart lookup scheme
|
||||
void UpdateAll() override {}
|
||||
void Update(std::shared_ptr<T>) override {}
|
||||
|
||||
private:
|
||||
std::vector<std::shared_ptr<T>> m_Items;
|
||||
};
|
||||
|
||||
template <class T> class PositionalContainer : IPositionalContainer<T> {
|
||||
public:
|
||||
PositionalContainer(const WorldSize &size, size_t chunks)
|
||||
: m_GridSize{size}, m_GridStep{size / chunks}, m_ChunksPerAxis{chunks} {
|
||||
LOG_INFO("Size: ", m_GridSize, " step: ", m_GridStep);
|
||||
m_Grid.reserve(chunks);
|
||||
for (size_t i = 0; i < chunks; i++) {
|
||||
m_Grid.emplace_back(chunks);
|
||||
for (size_t j = 0; j < chunks; j++) {
|
||||
m_Grid[i][j].reserve(16);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// calling Add on object that is already in the container is UB
|
||||
bool Add(std::shared_ptr<T> item) override {
|
||||
const auto &world_pos = item->GetPosition();
|
||||
if (!CheckBounds(world_pos)) {
|
||||
return false;
|
||||
}
|
||||
m_Items.push_back(item);
|
||||
auto coords = GetCoords(world_pos);
|
||||
m_Grid[coords.x()][coords.y()].push_back(item);
|
||||
m_ReverseGridLookup[item] = coords;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<std::weak_ptr<T>> Get(const WorldPos ¢er,
|
||||
float radius) override {
|
||||
vector_wptr output_vec{};
|
||||
|
||||
Get(output_vec, center, radius);
|
||||
|
||||
return output_vec;
|
||||
}
|
||||
|
||||
void Get(std::vector<std::weak_ptr<T>> &output_vec, const WorldPos &corner,
|
||||
const WorldSize &size) {
|
||||
const WorldSize half_size = size / 2.0f;
|
||||
const WorldPos center = corner + half_size.ChangeTag<WorldPos>();
|
||||
float radius = half_size.x();
|
||||
Get(output_vec, center, radius);
|
||||
}
|
||||
|
||||
void Get(std::vector<std::weak_ptr<T>> &output_vec, const WorldPos ¢er,
|
||||
float radius) {
|
||||
output_vec.clear();
|
||||
const WorldPos corner_1 = center + radius;
|
||||
const WorldPos corner_2 = center - radius;
|
||||
|
||||
const auto A = GetCoords(corner_1);
|
||||
const auto B = GetCoords(corner_2);
|
||||
|
||||
auto [x_min_f, x_max_f] = std::minmax(A.x(), B.x());
|
||||
auto [y_min_f, y_max_f] = std::minmax(A.y(), B.y());
|
||||
|
||||
size_t x_min = static_cast<size_t>(std::floor(x_min_f));
|
||||
size_t x_max = static_cast<size_t>(std::ceil(x_max_f));
|
||||
size_t y_min = static_cast<size_t>(std::floor(y_min_f));
|
||||
size_t y_max = static_cast<size_t>(std::ceil(y_max_f));
|
||||
|
||||
for (size_t x = x_min; x <= x_max; x++) {
|
||||
for (size_t y = y_min; y <= y_max; y++) {
|
||||
if (!CheckBounds(x, y)) {
|
||||
continue;
|
||||
}
|
||||
for (auto item_wptr : m_Grid[x][y]) {
|
||||
if (auto shared = item_wptr.lock()) {
|
||||
if (center.DistanceTo(shared->GetPosition()) < radius) {
|
||||
output_vec.push_back(item_wptr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void UpdateAll() override {
|
||||
for (auto ptr : m_Items) {
|
||||
Update(ptr);
|
||||
}
|
||||
}
|
||||
void Update(std::shared_ptr<T> item) override {
|
||||
coord_type current_coords = GetCoords(item->GetPosition());
|
||||
coord_type last_known_coords = m_ReverseGridLookup[item];
|
||||
if (current_coords == last_known_coords) {
|
||||
return;
|
||||
}
|
||||
vector_wptr &vec = m_Grid[last_known_coords.x()][last_known_coords.y()];
|
||||
// remove the old weak ptr from the map
|
||||
vec.erase(std::remove_if(vec.begin(), vec.end(),
|
||||
[&](const std::weak_ptr<T> &w) {
|
||||
return !w.owner_before(item) &&
|
||||
!item.owner_before(w);
|
||||
}),
|
||||
vec.end());
|
||||
// add new weak ptr to the map
|
||||
m_Grid[current_coords.x()][current_coords.y()].push_back(item);
|
||||
}
|
||||
|
||||
private:
|
||||
using coord_type = vec<size_t, 2>;
|
||||
using vector_wptr = std::vector<std::weak_ptr<T>>;
|
||||
using grid_type = std::vector<std::vector<vector_wptr>>;
|
||||
|
||||
coord_type GetCoords(const WorldPos &wp) {
|
||||
auto coord_float = wp / m_GridStep.ChangeTag<WorldPos>();
|
||||
return coord_type{static_cast<size_t>(coord_float.x()),
|
||||
static_cast<size_t>(coord_float.y())};
|
||||
}
|
||||
|
||||
bool CheckBounds(size_t x, size_t y) const {
|
||||
bool x_in_bounds = x < m_Grid.size();
|
||||
bool y_in_bounds = y < m_Grid.size();
|
||||
return x_in_bounds && y_in_bounds;
|
||||
}
|
||||
|
||||
bool CheckBounds(const WorldPos &pos) const {
|
||||
auto [x, y] = pos;
|
||||
bool x_in_bounds = 0.0f < x && x < m_GridSize.x();
|
||||
bool y_in_bounds = 0.0f < y && y < m_GridSize.y();
|
||||
return x_in_bounds && y_in_bounds;
|
||||
}
|
||||
|
||||
WorldSize m_GridSize;
|
||||
WorldSize m_GridStep;
|
||||
size_t m_ChunksPerAxis;
|
||||
std::vector<std::shared_ptr<T>> m_Items;
|
||||
grid_type m_Grid;
|
||||
|
||||
// normal lookup: WorldPos -> coord_type -> vector_wptr -> std::shared_ptr<T>
|
||||
// reverse lookup: std::shared_ptr<T> -> vector_wptr -> coord_type
|
||||
// we need the reverse lookup because T.GetPosition() may change and we need
|
||||
// to delete the old weak_ptr from vector_wptr (without iterating through all
|
||||
// of them). Also it might be useful to have T -> location lookup Note: hash
|
||||
// of std::shared_ptr<T> may give us trouble if we free the memory and new one
|
||||
// points to the same location, maybe it would be better to hash the object
|
||||
// itself? NOTE how about using counting bloom filter for this?
|
||||
std::unordered_map<std::shared_ptr<T>, coord_type> m_ReverseGridLookup;
|
||||
};
|
||||
52
cpp/src/sprite.cpp
Normal file
52
cpp/src/sprite.cpp
Normal file
@@ -0,0 +1,52 @@
|
||||
#include "sprite.hpp"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
#include <SDL3_image/SDL_image.h>
|
||||
#include <cassert>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
Sprite::Sprite() : m_Texture(nullptr, SDL_DestroyTexture) {}
|
||||
|
||||
Sprite::Sprite(std::string path, WorldPos center) : Sprite() {
|
||||
LoadImage(path, center);
|
||||
}
|
||||
|
||||
Sprite::~Sprite() { LOG_DEBUG("."); }
|
||||
|
||||
void Sprite::LoadImage(std::string path, WorldPos image_center) {
|
||||
LOG_INFO("Loading image ", path);
|
||||
assert(m_Renderer != nullptr);
|
||||
|
||||
auto surface = std::unique_ptr<SDL_Surface, decltype(&SDL_DestroySurface)>(
|
||||
IMG_Load(path.c_str()), SDL_DestroySurface);
|
||||
|
||||
if (surface == nullptr) {
|
||||
LOG_ERROR("IMG_Load failed: ", SDL_GetError());
|
||||
throw std::runtime_error("Failed to load resources");
|
||||
}
|
||||
|
||||
m_Texture = std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)>(
|
||||
SDL_CreateTextureFromSurface(m_Renderer.get(), surface.get()),
|
||||
SDL_DestroyTexture);
|
||||
if (m_Texture == nullptr) {
|
||||
LOG_ERROR("SDL_CreateTextureFromSurface failed");
|
||||
throw std::runtime_error("Failed to load resources");
|
||||
}
|
||||
float w, h;
|
||||
SDL_GetTextureSize(m_Texture.get(), &w, &h);
|
||||
m_Size = {w, h};
|
||||
m_ImageCenter = image_center;
|
||||
}
|
||||
|
||||
// Renderer is shared for all class instances - we need it in order
|
||||
// to create textures from images
|
||||
void Sprite::SetRenderer(std::shared_ptr<SDL_Renderer> renderer) {
|
||||
m_Renderer = renderer;
|
||||
}
|
||||
|
||||
std::shared_ptr<SDL_Renderer> Sprite::m_Renderer = nullptr;
|
||||
40
cpp/src/sprite.hpp
Normal file
40
cpp/src/sprite.hpp
Normal file
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
#include <SDL3_image/SDL_image.h>
|
||||
#include <cassert>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
class Sprite {
|
||||
public:
|
||||
Sprite();
|
||||
~Sprite();
|
||||
explicit Sprite(std::string path, WorldPos center = WorldPos{});
|
||||
|
||||
Sprite(const Sprite &) = delete;
|
||||
Sprite &operator=(const Sprite &) = delete;
|
||||
Sprite(Sprite &&) = delete;
|
||||
Sprite &operator=(Sprite &&) = delete;
|
||||
|
||||
static void SetRenderer(std::shared_ptr<SDL_Renderer> renderer);
|
||||
|
||||
// GetTexture cannot return pointer to const, as SDL_RenderTexture modifies it
|
||||
SDL_Texture *GetTexture() { return m_Texture.get(); }
|
||||
WorldSize GetSize() const { return m_Size; }
|
||||
WorldPos GetCenter() const { return m_ImageCenter; }
|
||||
|
||||
void LoadImage(std::string path, WorldPos image_center = WorldPos{});
|
||||
|
||||
private:
|
||||
static std::shared_ptr<SDL_Renderer> m_Renderer;
|
||||
std::unique_ptr<SDL_Texture, decltype(&SDL_DestroyTexture)> m_Texture;
|
||||
WorldSize m_Size;
|
||||
WorldPos m_ImageCenter;
|
||||
float m_TextureWidth = 0;
|
||||
float m_TextureHeight = 0;
|
||||
};
|
||||
158
cpp/src/test.cpp
158
cpp/src/test.cpp
@@ -1,158 +0,0 @@
|
||||
#include <cassert>
|
||||
#include <cmath>
|
||||
#include <concepts>
|
||||
#include <gtest/gtest.h>
|
||||
#include <sstream>
|
||||
#include <unordered_set>
|
||||
|
||||
#include "array.hpp"
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
// Vec2D Tests
|
||||
TEST(Vec2D, DefaultConstruction) {
|
||||
Vec2D<int> v;
|
||||
// Default values are uninitialized, but we can test basic functionality
|
||||
v.x = 0;
|
||||
v.y = 0;
|
||||
ASSERT_EQ(v.x, 0);
|
||||
ASSERT_EQ(v.y, 0);
|
||||
}
|
||||
|
||||
TEST(Vec2D, InitializerListConstruction) {
|
||||
Vec2D<int> v{3, 4};
|
||||
ASSERT_EQ(v.x, 3);
|
||||
ASSERT_EQ(v.y, 4);
|
||||
|
||||
Vec2D<float> vf{1.5f, 2.5f};
|
||||
ASSERT_FLOAT_EQ(vf.x, 1.5f);
|
||||
ASSERT_FLOAT_EQ(vf.y, 2.5f);
|
||||
|
||||
// Test type conversion
|
||||
Vec2D<float> vd{1, 2}; // int to float
|
||||
ASSERT_FLOAT_EQ(vd.x, 1.0f);
|
||||
ASSERT_FLOAT_EQ(vd.y, 2.0f);
|
||||
}
|
||||
|
||||
TEST(Vec2D, Addition) {
|
||||
Vec2D<int> a{1, 2};
|
||||
Vec2D<int> b{3, 4};
|
||||
|
||||
Vec2D<int> c = a + b;
|
||||
ASSERT_EQ(c.x, 4);
|
||||
ASSERT_EQ(c.y, 6);
|
||||
|
||||
// Test that original vectors are unchanged
|
||||
ASSERT_EQ(a.x, 1);
|
||||
ASSERT_EQ(a.y, 2);
|
||||
ASSERT_EQ(b.x, 3);
|
||||
ASSERT_EQ(b.y, 4);
|
||||
}
|
||||
|
||||
TEST(Vec2D, AdditionAssignment) {
|
||||
Vec2D<int> a{1, 2};
|
||||
Vec2D<int> b{3, 4};
|
||||
|
||||
a += b;
|
||||
ASSERT_EQ(a.x, 4);
|
||||
ASSERT_EQ(a.y, 6);
|
||||
|
||||
// Test that b is unchanged
|
||||
ASSERT_EQ(b.x, 3);
|
||||
ASSERT_EQ(b.y, 4);
|
||||
}
|
||||
|
||||
TEST(Vec2D, ScalarMultiplication) {
|
||||
Vec2D<int> v{2, 3};
|
||||
|
||||
Vec2D<int> result = v * 2.0f;
|
||||
ASSERT_EQ(result.x, 4);
|
||||
ASSERT_EQ(result.y, 6);
|
||||
|
||||
// Test with float vector
|
||||
Vec2D<float> vf{1.5f, 2.5f};
|
||||
Vec2D<float> resultf = vf * 2.0f;
|
||||
ASSERT_FLOAT_EQ(resultf.x, 3.0f);
|
||||
ASSERT_FLOAT_EQ(resultf.y, 5.0f);
|
||||
}
|
||||
|
||||
TEST(Vec2D, Normalization) {
|
||||
Vec2D<float> v{3.0f, 4.0f}; // Length = 5
|
||||
|
||||
v.normalize();
|
||||
ASSERT_FLOAT_EQ(v.x, 0.6f);
|
||||
ASSERT_FLOAT_EQ(v.y, 0.8f);
|
||||
|
||||
// Check that length is approximately 1
|
||||
float length = sqrt(v.x * v.x + v.y * v.y);
|
||||
ASSERT_NEAR(length, 1.0f, 1e-6f);
|
||||
}
|
||||
|
||||
TEST(Vec2D, NormalizedCopy) {
|
||||
Vec2D<float> v{3.0f, 4.0f};
|
||||
Vec2D<float> normalized = v.normalized();
|
||||
|
||||
// Original should be unchanged
|
||||
ASSERT_FLOAT_EQ(v.x, 3.0f);
|
||||
ASSERT_FLOAT_EQ(v.y, 4.0f);
|
||||
|
||||
// Normalized copy should be unit length
|
||||
ASSERT_FLOAT_EQ(normalized.x, 0.6f);
|
||||
ASSERT_FLOAT_EQ(normalized.y, 0.8f);
|
||||
|
||||
float length =
|
||||
sqrt(normalized.x * normalized.x + normalized.y * normalized.y);
|
||||
ASSERT_NEAR(length, 1.0f, 1e-6f);
|
||||
}
|
||||
|
||||
TEST(Vec2D, ZeroVectorNormalization) {
|
||||
Vec2D<float> v{0.0f, 0.0f};
|
||||
|
||||
v.normalize();
|
||||
ASSERT_FLOAT_EQ(v.x, 0.0f);
|
||||
ASSERT_FLOAT_EQ(v.y, 0.0f);
|
||||
|
||||
// Test normalized() as well
|
||||
Vec2D<float> v2{0.0f, 0.0f};
|
||||
Vec2D<float> normalized = v2.normalized();
|
||||
ASSERT_FLOAT_EQ(normalized.x, 0.0f);
|
||||
ASSERT_FLOAT_EQ(normalized.y, 0.0f);
|
||||
}
|
||||
|
||||
TEST(Vec2D, VerySmallVectorNormalization) {
|
||||
Vec2D<float> v{1e-7f, 1e-7f}; // Very small vector
|
||||
|
||||
v.normalize();
|
||||
// Should be treated as zero vector
|
||||
ASSERT_FLOAT_EQ(v.x, 0.0f);
|
||||
ASSERT_FLOAT_EQ(v.y, 0.0f);
|
||||
}
|
||||
|
||||
TEST(Vec2D, OutputOperator) {
|
||||
Vec2D<int> v{42, 24};
|
||||
|
||||
std::ostringstream oss;
|
||||
oss << v;
|
||||
ASSERT_EQ(oss.str(), "( 42, 24)");
|
||||
}
|
||||
|
||||
TEST(Vec2D, ChainedOperations) {
|
||||
Vec2D<float> a{1.0f, 2.0f};
|
||||
Vec2D<float> b{3.0f, 4.0f};
|
||||
|
||||
// Test chaining: (a + b) * 2.0f
|
||||
Vec2D<float> result = (a + b) * 2.0f;
|
||||
ASSERT_FLOAT_EQ(result.x, 8.0f);
|
||||
ASSERT_FLOAT_EQ(result.y, 12.0f);
|
||||
|
||||
// Test chaining with assignment
|
||||
a += b;
|
||||
a = a * 0.5f;
|
||||
ASSERT_FLOAT_EQ(a.x, 2.0f);
|
||||
ASSERT_FLOAT_EQ(a.y, 3.0f);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
::testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
14
cpp/src/tile.cpp
Normal file
14
cpp/src/tile.cpp
Normal file
@@ -0,0 +1,14 @@
|
||||
#include <array>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "tile.hpp"
|
||||
|
||||
// we could use array here, but this is more explicit,
|
||||
// and we don't access tile_types that often, so it should be ok
|
||||
const std::unordered_map<TileType, Tile> tile_types = {
|
||||
{TileType::GRASS, Tile{1.0, 0, 200, 0, 255}},
|
||||
{TileType::WOOD, Tile{1.0, 132, 68, 0, 255}},
|
||||
{TileType::ROAD, Tile{0.5, 20, 20, 20, 255}},
|
||||
{TileType::WATER, Tile{10.0, 0, 50, 200, 255}},
|
||||
{TileType::WALL, Tile{1000.0, 144, 33, 0, 255}},
|
||||
};
|
||||
22
cpp/src/tile.hpp
Normal file
22
cpp/src/tile.hpp
Normal file
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
|
||||
struct Tile {
|
||||
float cost;
|
||||
uint8_t R, G, B, A;
|
||||
};
|
||||
|
||||
enum class TileType {
|
||||
GRASS,
|
||||
WOOD,
|
||||
ROAD,
|
||||
WATER,
|
||||
WALL,
|
||||
};
|
||||
|
||||
extern const std::unordered_map<TileType, Tile> tile_types;
|
||||
124
cpp/src/user_input.cpp
Normal file
124
cpp/src/user_input.cpp
Normal file
@@ -0,0 +1,124 @@
|
||||
#include <SDL3/SDL.h>
|
||||
#include <expected>
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
#include "user_input.hpp"
|
||||
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
UserInput::UserInput()
|
||||
: // pre-alloc some space
|
||||
m_Actions(10) {
|
||||
LOG_DEBUG(".");
|
||||
};
|
||||
|
||||
UserInput::~UserInput() { LOG_DEBUG("."); };
|
||||
|
||||
std::expected<void, std::string> UserInput::Init() { return {}; }
|
||||
|
||||
void UserInput::GetActions_mouse(const SDL_Event &event) {
|
||||
static bool mouse_pan = false;
|
||||
|
||||
SDL_MouseButtonEvent mouse_event = event.button;
|
||||
MouseButton button = static_cast<MouseButton>(mouse_event.button);
|
||||
|
||||
if (event.type == SDL_EVENT_MOUSE_BUTTON_DOWN) {
|
||||
if (button == MouseButton::LEFT) {
|
||||
LOG_DEBUG("Selection start at ", mouse_event.x, ", ", mouse_event.y);
|
||||
m_SelectionActive = true;
|
||||
m_Actions.emplace_back(UserAction::Type::SELECTION_START,
|
||||
WindowPos{mouse_event.x, mouse_event.y});
|
||||
} else if (button == MouseButton::RIGHT) {
|
||||
LOG_DEBUG("Set move target to: ", mouse_event.x, ", ", mouse_event.y);
|
||||
m_Actions.emplace_back(UserAction::Type::SET_MOVE_TARGET,
|
||||
WindowPos{mouse_event.x, mouse_event.y});
|
||||
} else if (button == MouseButton::MIDDLE) {
|
||||
mouse_pan = true;
|
||||
}
|
||||
} else if (event.type == SDL_EVENT_MOUSE_BUTTON_UP) {
|
||||
if (button == MouseButton::LEFT) {
|
||||
LOG_DEBUG("Selection end at ", mouse_event.x, ", ", mouse_event.y);
|
||||
m_SelectionActive = false;
|
||||
m_Actions.emplace_back(UserAction::Type::SELECTION_END,
|
||||
WindowPos{mouse_event.x, mouse_event.y});
|
||||
}
|
||||
if (button == MouseButton::MIDDLE) {
|
||||
mouse_pan = false;
|
||||
}
|
||||
} else if (event.type == SDL_EVENT_MOUSE_MOTION) {
|
||||
SDL_MouseMotionEvent motion_event = event.motion;
|
||||
if (mouse_pan) {
|
||||
m_Actions.emplace_back(UserAction::Type::CAMERA_PAN,
|
||||
WindowPos{motion_event.xrel, motion_event.yrel});
|
||||
}
|
||||
if (m_SelectionActive) {
|
||||
m_Actions.emplace_back(UserAction::Type::SELECTION_CHANGE,
|
||||
WindowPos{mouse_event.x, mouse_event.y});
|
||||
}
|
||||
} else if (event.type == SDL_EVENT_MOUSE_WHEEL) {
|
||||
SDL_MouseWheelEvent mouse_wheel = event.wheel;
|
||||
m_Actions.emplace_back(UserAction::Type::CAMERA_ZOOM, mouse_wheel.y);
|
||||
}
|
||||
}
|
||||
|
||||
void UserInput::GetActions_keyboard(const SDL_Event &event) {
|
||||
bool key_down = event.type == SDL_EVENT_KEY_DOWN ? true : false;
|
||||
SDL_KeyboardEvent kbd_event = event.key;
|
||||
if (kbd_event.repeat) {
|
||||
// SDL repeats KEY_DOWN if key is held down, we ignore that
|
||||
return;
|
||||
}
|
||||
LOG_DEBUG("Key '", static_cast<char>(kbd_event.key),
|
||||
key_down ? "' down" : "' up");
|
||||
|
||||
switch (kbd_event.key) {
|
||||
case 'q':
|
||||
m_Actions.emplace_back(UserAction::Type::EXIT);
|
||||
return;
|
||||
case '1':
|
||||
case '2':
|
||||
case '3':
|
||||
case '4':
|
||||
if (key_down) {
|
||||
int selection = kbd_event.key - '0';
|
||||
m_Actions.emplace_back(UserAction::Type::SELECT_PATHFINDER, selection);
|
||||
LOG_INFO("Pathfinder selected: ", selection);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
LOG_INFO("Key '", static_cast<char>(kbd_event.key), "' not mapped");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const std::vector<UserAction> &UserInput::GetActions() {
|
||||
|
||||
static std::unordered_set<uint32_t> mouse_events = {
|
||||
SDL_EVENT_MOUSE_MOTION, SDL_EVENT_MOUSE_BUTTON_DOWN,
|
||||
SDL_EVENT_MOUSE_BUTTON_UP, SDL_EVENT_MOUSE_WHEEL,
|
||||
SDL_EVENT_MOUSE_ADDED, SDL_EVENT_MOUSE_REMOVED,
|
||||
};
|
||||
|
||||
static std::unordered_set<uint32_t> keyboard_events = {
|
||||
SDL_EVENT_KEY_DOWN,
|
||||
SDL_EVENT_KEY_UP,
|
||||
};
|
||||
|
||||
SDL_Event event;
|
||||
m_Actions.clear();
|
||||
|
||||
while (SDL_PollEvent(&event)) {
|
||||
if (keyboard_events.contains(event.type)) {
|
||||
GetActions_keyboard(event);
|
||||
} else if (mouse_events.contains(event.type)) {
|
||||
GetActions_mouse(event);
|
||||
} else {
|
||||
LOG_WARNING("Action not processed");
|
||||
}
|
||||
}
|
||||
return m_Actions;
|
||||
}
|
||||
60
cpp/src/user_input.hpp
Normal file
60
cpp/src/user_input.hpp
Normal file
@@ -0,0 +1,60 @@
|
||||
#pragma once
|
||||
|
||||
#include <expected>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
|
||||
// Seems like SDL doesn't have named constants for mouse button
|
||||
enum class MouseButton { LEFT = 1, MIDDLE, RIGHT };
|
||||
|
||||
class UserAction {
|
||||
public:
|
||||
enum class Type {
|
||||
NONE,
|
||||
EXIT,
|
||||
SET_MOVE_TARGET,
|
||||
SELECT_PATHFINDER,
|
||||
CAMERA_PAN,
|
||||
CAMERA_ZOOM,
|
||||
SELECTION_START,
|
||||
SELECTION_CHANGE,
|
||||
SELECTION_END
|
||||
};
|
||||
|
||||
UserAction() : type(Type::NONE), Argument{0} {}
|
||||
UserAction(Type t) : type(t), Argument{0} {}
|
||||
UserAction(Type t, char key) : type(t), Argument{key} {}
|
||||
UserAction(Type t, WindowPos v) : type(t), Argument{v} {}
|
||||
UserAction(Type t, int32_t arg) : type(t), Argument{arg} {}
|
||||
UserAction(Type t, float arg) : type(t), Argument{arg} {}
|
||||
~UserAction() = default;
|
||||
|
||||
Type type;
|
||||
|
||||
std::variant<WindowPos, char, int32_t, float> Argument;
|
||||
};
|
||||
|
||||
class UserInput {
|
||||
public:
|
||||
UserInput();
|
||||
~UserInput();
|
||||
|
||||
UserInput(const UserInput &x) = delete;
|
||||
UserInput(UserInput &&x) = delete;
|
||||
UserInput &operator=(const UserInput &) = delete;
|
||||
UserInput &operator=(UserInput &&) = delete;
|
||||
|
||||
std::expected<void, std::string> Init();
|
||||
|
||||
const std::vector<UserAction> &GetActions();
|
||||
|
||||
private:
|
||||
std::vector<UserAction> m_Actions;
|
||||
bool m_SelectionActive = false;
|
||||
|
||||
void GetActions_keyboard(const SDL_Event &);
|
||||
void GetActions_mouse(const SDL_Event &);
|
||||
};
|
||||
123
cpp/src/window.cpp
Normal file
123
cpp/src/window.cpp
Normal file
@@ -0,0 +1,123 @@
|
||||
#include <GL/glew.h>
|
||||
#include <SDL3/SDL.h>
|
||||
#include <SDL3/SDL_opengl.h>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "window.hpp"
|
||||
|
||||
#include "log.hpp"
|
||||
#include "math.hpp"
|
||||
#include "sprite.hpp"
|
||||
|
||||
Window::Window(int width, int height) : m_Width(width), m_Height(height) {
|
||||
LOG_DEBUG(".");
|
||||
}
|
||||
|
||||
std::expected<void, std::string> Window::Init() {
|
||||
LOG_DEBUG(".");
|
||||
|
||||
if (SDL_Init(SDL_INIT_VIDEO) == false) {
|
||||
return std::unexpected(std::string("SDL could not initialize! Error: ") +
|
||||
SDL_GetError());
|
||||
}
|
||||
m_Window = SDL_CreateWindow("SDL2 Window", m_Width, m_Height,
|
||||
SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
|
||||
if (m_Window == nullptr) {
|
||||
std::atexit(SDL_Quit);
|
||||
return std::unexpected(std::string("Window could not be created! Error: ") +
|
||||
SDL_GetError());
|
||||
}
|
||||
|
||||
m_Context = SDL_GL_CreateContext(m_Window);
|
||||
if (m_Context == nullptr) {
|
||||
SDL_DestroyWindow(m_Window);
|
||||
std::atexit(SDL_Quit);
|
||||
return std::unexpected(
|
||||
std::string("GL context could not be created! Error: ") +
|
||||
SDL_GetError());
|
||||
}
|
||||
|
||||
if (glewInit() != GLEW_OK) {
|
||||
SDL_GL_DestroyContext(m_Context);
|
||||
SDL_DestroyWindow(m_Window);
|
||||
std::atexit(SDL_Quit);
|
||||
return std::unexpected("GLEW init failed!");
|
||||
}
|
||||
|
||||
// Resize();
|
||||
|
||||
m_Renderer = std::shared_ptr<SDL_Renderer>(SDL_CreateRenderer(m_Window, NULL),
|
||||
SDL_DestroyRenderer);
|
||||
if (m_Renderer == nullptr) {
|
||||
SDL_DestroyWindow(m_Window);
|
||||
std::atexit(SDL_Quit);
|
||||
return std::unexpected(
|
||||
std::string("Renderer could not be created! Error: ") + SDL_GetError());
|
||||
}
|
||||
|
||||
// Set renderer to the Sprite class
|
||||
Sprite::SetRenderer(m_Renderer);
|
||||
|
||||
SDL_SetRenderScale(m_Renderer.get(), 1.0f, 1.0f);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
Window::~Window() {
|
||||
// SDL_DestroyRenderer(m_Renderer); // handled by shared_ptr
|
||||
SDL_GL_DestroyContext(m_Context);
|
||||
SDL_DestroyWindow(m_Window);
|
||||
std::atexit(SDL_Quit);
|
||||
LOG_DEBUG(".");
|
||||
}
|
||||
|
||||
void Window::DrawSprite(const WindowPos &position, Sprite &s, float scale) {
|
||||
WorldSize size = s.GetSize() * scale;
|
||||
WorldPos img_center = s.GetCenter() * scale;
|
||||
SDL_FRect rect = {position.x() - img_center.x(),
|
||||
position.y() - img_center.y(), size.x(), size.y()};
|
||||
SDL_RenderTexture(m_Renderer.get(), s.GetTexture(), nullptr, &rect);
|
||||
}
|
||||
|
||||
void Window::DrawFilledRect(const WindowPos &position, const WindowSize size,
|
||||
uint8_t R, uint8_t G, uint8_t B, uint8_t A) {
|
||||
SDL_FRect rect = {position.x(), position.y(), size.x(), size.y()};
|
||||
SDL_SetRenderDrawColor(m_Renderer.get(), R, G, B, A);
|
||||
SDL_RenderFillRect(m_Renderer.get(), &rect);
|
||||
}
|
||||
|
||||
void Window::DrawRect(const WindowPos &position, const WindowSize size,
|
||||
uint8_t R, uint8_t G, uint8_t B) {
|
||||
SDL_FRect rect = {position.x(), position.y(), size.x(), size.y()};
|
||||
SDL_SetRenderDrawColor(m_Renderer.get(), R, G, B, 255);
|
||||
SDL_RenderRect(m_Renderer.get(), &rect);
|
||||
}
|
||||
|
||||
void Window::ClearWindow() {
|
||||
SDL_SetRenderDrawColor(m_Renderer.get(), 50, 50, 50, 255);
|
||||
SDL_RenderClear(m_Renderer.get());
|
||||
}
|
||||
|
||||
void Window::Flush() { SDL_RenderPresent(m_Renderer.get()); }
|
||||
|
||||
void Window::DrawCircle(const WindowPos &position, float radius, uint8_t R,
|
||||
uint8_t G, uint8_t B) {
|
||||
int cx = static_cast<int>(position.x());
|
||||
int cy = static_cast<int>(position.y());
|
||||
SDL_SetRenderDrawColor(m_Renderer.get(), R, G, B, 255);
|
||||
for (int i = 0; i < 360; ++i) {
|
||||
double a = i * std::numbers::pi / 180.0;
|
||||
SDL_RenderPoint(m_Renderer.get(),
|
||||
cx + static_cast<int>(std::round(radius * std::cos(a))),
|
||||
cy + static_cast<int>(std::round(radius * std::sin(a))));
|
||||
}
|
||||
}
|
||||
|
||||
void Window::DrawLine(const WindowPos &A, const WindowPos &B) {
|
||||
SDL_SetRenderDrawColor(m_Renderer.get(), 255, 0, 0, 255);
|
||||
SDL_RenderLine(m_Renderer.get(), A.x(), A.y(), B.x(), B.y());
|
||||
}
|
||||
42
cpp/src/window.hpp
Normal file
42
cpp/src/window.hpp
Normal file
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
|
||||
#include <GL/glew.h>
|
||||
#include <SDL3/SDL.h>
|
||||
#include <SDL3/SDL_opengl.h>
|
||||
#include <cmath>
|
||||
#include <expected>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "math.hpp"
|
||||
#include "sprite.hpp"
|
||||
|
||||
class Window {
|
||||
public:
|
||||
Window(int width, int height);
|
||||
~Window();
|
||||
|
||||
Window(const Window &x) = delete;
|
||||
Window(Window &&x) = delete;
|
||||
Window &operator=(const Window &) = delete;
|
||||
Window &operator=(Window &&) = delete;
|
||||
|
||||
std::expected<void, std::string> Init();
|
||||
void DrawSprite(const WindowPos &position, Sprite &s, float scale = 1.0f);
|
||||
void DrawFilledRect(const WindowPos &position, const WindowSize size,
|
||||
uint8_t R, uint8_t G, uint8_t B, uint8_t A);
|
||||
void DrawRect(const WindowPos &position, const WindowSize size, uint8_t R,
|
||||
uint8_t G, uint8_t B);
|
||||
void ClearWindow();
|
||||
void Flush();
|
||||
void DrawCircle(const WindowPos &position, float radius, uint8_t R, uint8_t G,
|
||||
uint8_t B);
|
||||
void DrawLine(const WindowPos &A, const WindowPos &B);
|
||||
|
||||
private:
|
||||
uint32_t m_Width;
|
||||
uint32_t m_Height;
|
||||
std::shared_ptr<SDL_Renderer> m_Renderer = nullptr;
|
||||
SDL_Window *m_Window;
|
||||
SDL_GLContext m_Context;
|
||||
};
|
||||
251
cpp/test/collision_performance.cpp
Normal file
251
cpp/test/collision_performance.cpp
Normal file
@@ -0,0 +1,251 @@
|
||||
#include <gtest/gtest.h>
|
||||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <random>
|
||||
#include <algorithm>
|
||||
#include <set>
|
||||
|
||||
#include "positional_container.hpp"
|
||||
|
||||
/**
|
||||
* @file collision_performance.cpp
|
||||
* @brief Performance tests for collision detection systems
|
||||
*
|
||||
* This file contains performance benchmarks and tests for various
|
||||
* collision detection algorithms and optimizations.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Helper class to measure and print execution time
|
||||
*/
|
||||
class PerformanceTimer {
|
||||
public:
|
||||
using Clock = std::chrono::high_resolution_clock;
|
||||
using TimePoint = std::chrono::time_point<Clock>;
|
||||
using Duration = std::chrono::duration<double, std::milli>;
|
||||
|
||||
PerformanceTimer(const std::string& name) : name_(name) {
|
||||
start_ = Clock::now();
|
||||
}
|
||||
|
||||
~PerformanceTimer() {
|
||||
auto end = Clock::now();
|
||||
Duration duration = end - start_;
|
||||
std::cout << std::fixed << std::setprecision(3)
|
||||
<< "[PERF] " << name_ << ": "
|
||||
<< duration.count() << " ms" << std::endl;
|
||||
}
|
||||
|
||||
double elapsed_ms() const {
|
||||
auto end = Clock::now();
|
||||
Duration duration = end - start_;
|
||||
return duration.count();
|
||||
}
|
||||
|
||||
private:
|
||||
std::string name_;
|
||||
TimePoint start_;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Run a function multiple times and measure average execution time
|
||||
* @param name Name of the test for output
|
||||
* @param iterations Number of iterations to run
|
||||
* @param func Function to benchmark
|
||||
*/
|
||||
template<typename Func>
|
||||
void benchmark_function(const std::string& name, int iterations, Func func) {
|
||||
auto start = PerformanceTimer::Clock::now();
|
||||
|
||||
for (int i = 0; i < iterations; ++i) {
|
||||
func();
|
||||
}
|
||||
|
||||
auto end = PerformanceTimer::Clock::now();
|
||||
PerformanceTimer::Duration total_duration = end - start;
|
||||
double avg_duration = total_duration.count() / iterations;
|
||||
|
||||
std::cout << std::fixed << std::setprecision(6)
|
||||
<< "[BENCHMARK] " << name << ":\n"
|
||||
<< " Total: " << total_duration.count() << " ms\n"
|
||||
<< " Iterations: " << iterations << "\n"
|
||||
<< " Average: " << avg_duration << " ms\n"
|
||||
<< " Throughput: " << (iterations / (total_duration.count() / 1000.0))
|
||||
<< " ops/sec" << std::endl;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Simple dummy class that conforms to HasPosition concept
|
||||
* Used for testing PositionalContainer without heavy dependencies
|
||||
*/
|
||||
class Dummy {
|
||||
public:
|
||||
Dummy() : m_Position{0.0f, 0.0f}, m_Id(next_id++) {}
|
||||
Dummy(float x, float y) : m_Position{x, y}, m_Id(next_id++) {}
|
||||
Dummy(WorldPos pos) : m_Position(pos), m_Id(next_id++) {}
|
||||
|
||||
WorldPos GetPosition() const { return m_Position; }
|
||||
void SetPosition(WorldPos pos) { m_Position = pos; }
|
||||
int GetId() const { return m_Id; }
|
||||
|
||||
private:
|
||||
WorldPos m_Position;
|
||||
int m_Id;
|
||||
static int next_id;
|
||||
};
|
||||
|
||||
int Dummy::next_id = 0;
|
||||
|
||||
/**
|
||||
* @brief Helper function to generate random float in range [min, max]
|
||||
*/
|
||||
float random_float(std::mt19937& gen, float min, float max) {
|
||||
std::uniform_real_distribution<float> dist(min, max);
|
||||
return dist(gen);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Compare two sets of weak_ptrs by comparing the IDs of the objects they point to
|
||||
*/
|
||||
bool compare_results(const std::vector<std::weak_ptr<Dummy>>& a,
|
||||
const std::vector<std::weak_ptr<Dummy>>& b) {
|
||||
std::set<int> ids_a, ids_b;
|
||||
|
||||
for (const auto& weak : a) {
|
||||
if (auto shared = weak.lock()) {
|
||||
ids_a.insert(shared->GetId());
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto& weak : b) {
|
||||
if (auto shared = weak.lock()) {
|
||||
ids_b.insert(shared->GetId());
|
||||
}
|
||||
}
|
||||
|
||||
return ids_a == ids_b;
|
||||
}
|
||||
|
||||
TEST(CollisionPerformance, CompareContainers) {
|
||||
std::cout << "\n=== Collision Performance Comparison ===\n" << std::endl;
|
||||
|
||||
// Configuration
|
||||
const int NUM_OBJECTS = 1000;
|
||||
const int NUM_LOOKUPS = 100;
|
||||
const float WORLD_SIZE = 1000.0f;
|
||||
const float LOOKUP_RADIUS = 50.0f;
|
||||
const size_t CHUNKS = 20;
|
||||
|
||||
// Random number generator
|
||||
std::random_device rd;
|
||||
std::mt19937 gen(rd());
|
||||
|
||||
// Create containers
|
||||
PositionalContainer<Dummy> pos_cont{WorldSize{WORLD_SIZE, WORLD_SIZE}, CHUNKS};
|
||||
SimpleContainer<Dummy> simp_cont;
|
||||
|
||||
// Create and add dummy objects with random positions
|
||||
std::vector<std::shared_ptr<Dummy>> objects;
|
||||
objects.reserve(NUM_OBJECTS);
|
||||
|
||||
std::cout << "Creating " << NUM_OBJECTS << " objects with random positions..." << std::endl;
|
||||
for (int i = 0; i < NUM_OBJECTS; ++i) {
|
||||
float x = random_float(gen, 10.0f, WORLD_SIZE - 10.0f);
|
||||
float y = random_float(gen, 10.0f, WORLD_SIZE - 10.0f);
|
||||
auto obj = std::make_shared<Dummy>(x, y);
|
||||
objects.push_back(obj);
|
||||
pos_cont.Add(obj);
|
||||
simp_cont.Add(obj);
|
||||
}
|
||||
std::cout << "Objects created and added to containers." << std::endl;
|
||||
|
||||
// Generate random lookup positions
|
||||
std::vector<WorldPos> lookup_positions;
|
||||
lookup_positions.reserve(NUM_LOOKUPS);
|
||||
for (int i = 0; i < NUM_LOOKUPS; ++i) {
|
||||
float x = random_float(gen, 0.0f, WORLD_SIZE);
|
||||
float y = random_float(gen, 0.0f, WORLD_SIZE);
|
||||
lookup_positions.push_back(WorldPos{x, y});
|
||||
}
|
||||
|
||||
// Benchmark SimpleContainer
|
||||
double simple_total_time = 0.0;
|
||||
std::vector<std::vector<std::weak_ptr<Dummy>>> simple_results;
|
||||
simple_results.reserve(NUM_LOOKUPS);
|
||||
|
||||
std::cout << "\nBenchmarking SimpleContainer with " << NUM_LOOKUPS << " lookups..." << std::endl;
|
||||
for (const auto& pos : lookup_positions) {
|
||||
auto start = PerformanceTimer::Clock::now();
|
||||
auto result = simp_cont.Get(pos, LOOKUP_RADIUS);
|
||||
auto end = PerformanceTimer::Clock::now();
|
||||
|
||||
PerformanceTimer::Duration duration = end - start;
|
||||
simple_total_time += duration.count();
|
||||
simple_results.push_back(result);
|
||||
}
|
||||
|
||||
double simple_avg_time = simple_total_time / NUM_LOOKUPS;
|
||||
std::cout << std::fixed << std::setprecision(6)
|
||||
<< "[BENCHMARK] SimpleContainer:\n"
|
||||
<< " Total time: " << simple_total_time << " ms\n"
|
||||
<< " Average time per lookup: " << simple_avg_time << " ms\n"
|
||||
<< " Throughput: " << (NUM_LOOKUPS / (simple_total_time / 1000.0))
|
||||
<< " lookups/sec" << std::endl;
|
||||
|
||||
// Benchmark PositionalContainer
|
||||
double positional_total_time = 0.0;
|
||||
std::vector<std::vector<std::weak_ptr<Dummy>>> positional_results;
|
||||
positional_results.reserve(NUM_LOOKUPS);
|
||||
|
||||
std::cout << "\nBenchmarking PositionalContainer with " << NUM_LOOKUPS << " lookups..." << std::endl;
|
||||
for (const auto& pos : lookup_positions) {
|
||||
auto start = PerformanceTimer::Clock::now();
|
||||
auto result = pos_cont.Get(pos, LOOKUP_RADIUS);
|
||||
auto end = PerformanceTimer::Clock::now();
|
||||
|
||||
PerformanceTimer::Duration duration = end - start;
|
||||
positional_total_time += duration.count();
|
||||
positional_results.push_back(result);
|
||||
}
|
||||
|
||||
double positional_avg_time = positional_total_time / NUM_LOOKUPS;
|
||||
std::cout << std::fixed << std::setprecision(6)
|
||||
<< "[BENCHMARK] PositionalContainer:\n"
|
||||
<< " Total time: " << positional_total_time << " ms\n"
|
||||
<< " Average time per lookup: " << positional_avg_time << " ms\n"
|
||||
<< " Throughput: " << (NUM_LOOKUPS / (positional_total_time / 1000.0))
|
||||
<< " lookups/sec" << std::endl;
|
||||
|
||||
// Verify results match
|
||||
std::cout << "\nVerifying results correctness..." << std::endl;
|
||||
int mismatches = 0;
|
||||
for (size_t i = 0; i < NUM_LOOKUPS; ++i) {
|
||||
if (!compare_results(simple_results[i], positional_results[i])) {
|
||||
mismatches++;
|
||||
std::cout << "Mismatch at lookup " << i
|
||||
<< " (pos: " << lookup_positions[i] << ")" << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
if (mismatches == 0) {
|
||||
std::cout << "✓ All " << NUM_LOOKUPS << " lookups produced identical results!" << std::endl;
|
||||
} else {
|
||||
std::cout << "✗ Found " << mismatches << " mismatches out of "
|
||||
<< NUM_LOOKUPS << " lookups" << std::endl;
|
||||
}
|
||||
|
||||
// Performance comparison
|
||||
std::cout << "\n=== Performance Summary ===\n";
|
||||
double speedup = simple_avg_time / positional_avg_time;
|
||||
std::cout << std::fixed << std::setprecision(2)
|
||||
<< "PositionalContainer is " << speedup << "x "
|
||||
<< (speedup > 1.0 ? "faster" : "slower")
|
||||
<< " than SimpleContainer" << std::endl;
|
||||
|
||||
std::cout << "\n======================================\n" << std::endl;
|
||||
|
||||
// Assertions
|
||||
EXPECT_EQ(mismatches, 0) << "Results should match between containers";
|
||||
EXPECT_GT(speedup, 1.0) << "PositionalContainer should be faster than SimpleContainer";
|
||||
}
|
||||
1190
cpp/test/test.cpp
Normal file
1190
cpp/test/test.cpp
Normal file
File diff suppressed because it is too large
Load Diff
1
docs/diagrams/class_diagram.svg
Normal file
1
docs/diagrams/class_diagram.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 406 KiB |
1
docs/diagrams/include_diagram.svg
Normal file
1
docs/diagrams/include_diagram.svg
Normal file
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 93 KiB |
BIN
docs/img/py_screenshot.png
Normal file
BIN
docs/img/py_screenshot.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 30 KiB |
BIN
docs/img/screenshot_1.png
Normal file
BIN
docs/img/screenshot_1.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 6.9 KiB |
File diff suppressed because one or more lines are too long
@@ -56,7 +56,8 @@ class Map:
|
||||
x_center, y_center = center_point
|
||||
for x in range(-1,2):
|
||||
for y in range(-1,2):
|
||||
if x == 0 and y == 0:
|
||||
diagonal = x == y # includes center 0,0
|
||||
if diagonal:
|
||||
continue
|
||||
p = Point2D((x + x_center, y + y_center))
|
||||
if self.IsPointValid(p):
|
||||
@@ -304,10 +305,6 @@ class GBFS(PathFinderBase):
|
||||
|
||||
@staticmethod
|
||||
def heuristic(a: Point2D, b: Point2D) -> float:
|
||||
# for now we use Manhattan distance, although
|
||||
# it is probably not entirely correct, given that
|
||||
# we can also move diagonally in the grid
|
||||
# TODO a problem for future me
|
||||
x_a, y_a = a
|
||||
x_b, y_b = b
|
||||
return abs(x_a - x_b) + abs(y_a - y_b)
|
||||
@@ -348,10 +345,6 @@ class A_star(PathFinderBase):
|
||||
|
||||
@staticmethod
|
||||
def heuristic(a: Point2D, b: Point2D) -> float:
|
||||
# for now we use Manhattan distance, although
|
||||
# it is probably not entirely correct, given that
|
||||
# we can also move diagonally in the grid
|
||||
# TODO a problem for future me
|
||||
x_a, y_a = a
|
||||
x_b, y_b = b
|
||||
return abs(x_a - x_b) + abs(y_a - y_b)
|
||||
|
||||
9
scripts/pre-commit.sample
Normal file
9
scripts/pre-commit.sample
Normal file
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
|
||||
# Copy this file to .git/hooks
|
||||
|
||||
# Run clang-format before commiting
|
||||
files=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(cpp|hpp)$')
|
||||
[ -z "$files" ] && exit 0
|
||||
clang-format -i $files
|
||||
git add $files
|
||||
14
vcpkg-configuration.json
Normal file
14
vcpkg-configuration.json
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"default-registry": {
|
||||
"kind": "git",
|
||||
"baseline": "b2c74683ecfd6a8e7d27ffb0df077f66a9339509",
|
||||
"repository": "https://github.com/microsoft/vcpkg"
|
||||
},
|
||||
"registries": [
|
||||
{
|
||||
"kind": "artifact",
|
||||
"location": "https://github.com/microsoft/vcpkg-ce-catalog/archive/refs/heads/main.zip",
|
||||
"name": "microsoft"
|
||||
}
|
||||
]
|
||||
}
|
||||
12
vcpkg.json
Normal file
12
vcpkg.json
Normal file
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"dependencies": [
|
||||
"glew",
|
||||
"opengl",
|
||||
"sdl3",
|
||||
{
|
||||
"name": "sdl3-image",
|
||||
"features": [ "png" ]
|
||||
},
|
||||
"gtest"
|
||||
]
|
||||
}
|
||||
1
vs/SDL
1
vs/SDL
Submodule vs/SDL deleted from 3e9e22f17d
Submodule vs/SDL_image deleted from eeae8a64df
1
vs/glew
1
vs/glew
Submodule vs/glew deleted from 02505d6cc1
@@ -1,61 +0,0 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.9.34622.214
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "pathfinding_demo", "pathfinding_demo.vcxproj", "{E14D159C-08E1-46E4-BD63-6157EDBC70DC}"
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SDL3", "..\SDL\VisualC\SDL\SDL.vcxproj", "{81CE8DAF-EBB2-4761-8E45-B71ABCCA8C68}"
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "glew_static", "..\glew\build\vc15\glew_static.vcxproj", "{664E6F0D-6784-4760-9565-D54F8EB1EDF4}"
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "SDL3_image", "..\SDL_image\VisualC\SDL_image.vcxproj", "{2BD5534E-00E2-4BEA-AC96-D9A92EA24696}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{E14D159C-08E1-46E4-BD63-6157EDBC70DC}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{E14D159C-08E1-46E4-BD63-6157EDBC70DC}.Debug|x64.Build.0 = Debug|x64
|
||||
{E14D159C-08E1-46E4-BD63-6157EDBC70DC}.Debug|x86.ActiveCfg = Debug|Win32
|
||||
{E14D159C-08E1-46E4-BD63-6157EDBC70DC}.Debug|x86.Build.0 = Debug|Win32
|
||||
{E14D159C-08E1-46E4-BD63-6157EDBC70DC}.Release|x64.ActiveCfg = Release|x64
|
||||
{E14D159C-08E1-46E4-BD63-6157EDBC70DC}.Release|x64.Build.0 = Release|x64
|
||||
{E14D159C-08E1-46E4-BD63-6157EDBC70DC}.Release|x86.ActiveCfg = Release|Win32
|
||||
{E14D159C-08E1-46E4-BD63-6157EDBC70DC}.Release|x86.Build.0 = Release|Win32
|
||||
{81CE8DAF-EBB2-4761-8E45-B71ABCCA8C68}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{81CE8DAF-EBB2-4761-8E45-B71ABCCA8C68}.Debug|x64.Build.0 = Debug|x64
|
||||
{81CE8DAF-EBB2-4761-8E45-B71ABCCA8C68}.Debug|x86.ActiveCfg = Debug|Win32
|
||||
{81CE8DAF-EBB2-4761-8E45-B71ABCCA8C68}.Debug|x86.Build.0 = Debug|Win32
|
||||
{81CE8DAF-EBB2-4761-8E45-B71ABCCA8C68}.Release|x64.ActiveCfg = Release|x64
|
||||
{81CE8DAF-EBB2-4761-8E45-B71ABCCA8C68}.Release|x64.Build.0 = Release|x64
|
||||
{81CE8DAF-EBB2-4761-8E45-B71ABCCA8C68}.Release|x86.ActiveCfg = Release|Win32
|
||||
{81CE8DAF-EBB2-4761-8E45-B71ABCCA8C68}.Release|x86.Build.0 = Release|Win32
|
||||
{664E6F0D-6784-4760-9565-D54F8EB1EDF4}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{664E6F0D-6784-4760-9565-D54F8EB1EDF4}.Debug|x64.Build.0 = Debug|x64
|
||||
{664E6F0D-6784-4760-9565-D54F8EB1EDF4}.Debug|x86.ActiveCfg = Debug|Win32
|
||||
{664E6F0D-6784-4760-9565-D54F8EB1EDF4}.Debug|x86.Build.0 = Debug|Win32
|
||||
{664E6F0D-6784-4760-9565-D54F8EB1EDF4}.Release|x64.ActiveCfg = Release|x64
|
||||
{664E6F0D-6784-4760-9565-D54F8EB1EDF4}.Release|x64.Build.0 = Release|x64
|
||||
{664E6F0D-6784-4760-9565-D54F8EB1EDF4}.Release|x86.ActiveCfg = Release|Win32
|
||||
{664E6F0D-6784-4760-9565-D54F8EB1EDF4}.Release|x86.Build.0 = Release|Win32
|
||||
{2BD5534E-00E2-4BEA-AC96-D9A92EA24696}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{2BD5534E-00E2-4BEA-AC96-D9A92EA24696}.Debug|x64.Build.0 = Debug|x64
|
||||
{2BD5534E-00E2-4BEA-AC96-D9A92EA24696}.Debug|x86.ActiveCfg = Debug|Win32
|
||||
{2BD5534E-00E2-4BEA-AC96-D9A92EA24696}.Debug|x86.Build.0 = Debug|Win32
|
||||
{2BD5534E-00E2-4BEA-AC96-D9A92EA24696}.Release|x64.ActiveCfg = Release|x64
|
||||
{2BD5534E-00E2-4BEA-AC96-D9A92EA24696}.Release|x64.Build.0 = Release|x64
|
||||
{2BD5534E-00E2-4BEA-AC96-D9A92EA24696}.Release|x86.ActiveCfg = Release|Win32
|
||||
{2BD5534E-00E2-4BEA-AC96-D9A92EA24696}.Release|x86.Build.0 = Release|Win32
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {7CCA451E-D4BA-48B4-AAD0-8AC02333FD9D}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -1,167 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup Label="ProjectConfigurations">
|
||||
<ProjectConfiguration Include="Debug|Win32">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|Win32">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>Win32</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Debug|x64">
|
||||
<Configuration>Debug</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
<ProjectConfiguration Include="Release|x64">
|
||||
<Configuration>Release</Configuration>
|
||||
<Platform>x64</Platform>
|
||||
</ProjectConfiguration>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\..\cpp\src\main.cpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\..\cpp\src\array.hpp" />
|
||||
<ClInclude Include="..\..\cpp\src\log.hpp" />
|
||||
<ClInclude Include="..\..\cpp\src\math.hpp" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\glew\build\vc15\glew_static.vcxproj">
|
||||
<Project>{664e6f0d-6784-4760-9565-d54f8eb1edf4}</Project>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\SDL\VisualC\SDL\SDL.vcxproj">
|
||||
<Project>{81ce8daf-ebb2-4761-8e45-b71abcca8c68}</Project>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\SDL_image\VisualC\SDL_image.vcxproj">
|
||||
<Project>{2bd5534e-00e2-4bea-ac96-d9a92ea24696}</Project>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<PropertyGroup Label="Globals">
|
||||
<VCProjectVersion>17.0</VCProjectVersion>
|
||||
<Keyword>Win32Proj</Keyword>
|
||||
<ProjectGuid>{e14d159c-08e1-46e4-bd63-6157edbc70dc}</ProjectGuid>
|
||||
<RootNamespace>pathfindingdemo</RootNamespace>
|
||||
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>true</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
|
||||
<ConfigurationType>Application</ConfigurationType>
|
||||
<UseDebugLibraries>false</UseDebugLibraries>
|
||||
<PlatformToolset>v143</PlatformToolset>
|
||||
<WholeProgramOptimization>true</WholeProgramOptimization>
|
||||
<CharacterSet>Unicode</CharacterSet>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
|
||||
<ImportGroup Label="ExtensionSettings">
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="Shared">
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
|
||||
</ImportGroup>
|
||||
<PropertyGroup Label="UserMacros" />
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>GLEW_STATIC</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<LanguageStandard>stdcpplatest</LanguageStandard>
|
||||
<AdditionalIncludeDirectories>..\glew\include;..\SDL\include;..\SDL_image\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalLibraryDirectories>..\glew\lib\Debug\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
|
||||
<AdditionalDependencies>opengl32.lib;glu32.lib;glew32sd.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>GLEW_STATIC</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<LanguageStandard>stdcpplatest</LanguageStandard>
|
||||
<AdditionalIncludeDirectories>..\glew\include;..\SDL\include;..\SDL_image\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalLibraryDirectories>..\glew\lib\Debug\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
|
||||
<AdditionalDependencies>opengl32.lib;glu32.lib;glew32sd.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>GLEW_STATIC</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<LanguageStandard>stdcpplatest</LanguageStandard>
|
||||
<AdditionalIncludeDirectories>..\glew\include;..\SDL\include;..\SDL_image\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalLibraryDirectories>..\glew\lib\Debug\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
|
||||
<AdditionalDependencies>opengl32.lib;glu32.lib;glew32sd.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<ClCompile>
|
||||
<WarningLevel>Level3</WarningLevel>
|
||||
<FunctionLevelLinking>true</FunctionLevelLinking>
|
||||
<IntrinsicFunctions>true</IntrinsicFunctions>
|
||||
<SDLCheck>true</SDLCheck>
|
||||
<PreprocessorDefinitions>GLEW_STATIC</PreprocessorDefinitions>
|
||||
<ConformanceMode>true</ConformanceMode>
|
||||
<LanguageStandard>stdcpplatest</LanguageStandard>
|
||||
<AdditionalIncludeDirectories>..\glew\include;..\SDL\include;..\SDL_image\include;..\;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
|
||||
</ClCompile>
|
||||
<Link>
|
||||
<SubSystem>Console</SubSystem>
|
||||
<EnableCOMDATFolding>true</EnableCOMDATFolding>
|
||||
<OptimizeReferences>true</OptimizeReferences>
|
||||
<GenerateDebugInformation>true</GenerateDebugInformation>
|
||||
<AdditionalLibraryDirectories>..\glew\lib\Debug\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
|
||||
<AdditionalDependencies>opengl32.lib;glu32.lib;glew32sd.lib;%(AdditionalDependencies)</AdditionalDependencies>
|
||||
</Link>
|
||||
</ItemDefinitionGroup>
|
||||
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
|
||||
<ImportGroup Label="ExtensionTargets">
|
||||
</ImportGroup>
|
||||
</Project>
|
||||
@@ -1,33 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<ItemGroup>
|
||||
<Filter Include="Source Files">
|
||||
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
|
||||
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
|
||||
</Filter>
|
||||
<Filter Include="Header Files">
|
||||
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
|
||||
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
|
||||
</Filter>
|
||||
<Filter Include="Resource Files">
|
||||
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
|
||||
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
|
||||
</Filter>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClCompile Include="..\..\cpp\src\main.cpp">
|
||||
<Filter>Source Files</Filter>
|
||||
</ClCompile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ClInclude Include="..\..\cpp\src\array.hpp">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="..\..\cpp\src\log.hpp">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
<ClInclude Include="..\..\cpp\src\math.hpp">
|
||||
<Filter>Header Files</Filter>
|
||||
</ClInclude>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,19 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
|
||||
<LocalDebuggerWorkingDirectory>$(ProjectDir)\..\..\cpp</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
|
||||
<LocalDebuggerWorkingDirectory>$(ProjectDir)\..\..\cpp</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
|
||||
<LocalDebuggerWorkingDirectory>$(ProjectDir)\..\..\cpp</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
|
||||
<LocalDebuggerWorkingDirectory>$(ProjectDir)\..\..\cpp</LocalDebuggerWorkingDirectory>
|
||||
<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
Reference in New Issue
Block a user