diff --git a/.clang-format b/.clang-format new file mode 100644 index 000000000..350fd097b --- /dev/null +++ b/.clang-format @@ -0,0 +1,6 @@ +--- +BasedOnStyle: Google +--- +Language: Cpp +UseTab: Never +ColumnLimit: 0 diff --git a/.clang-tidy b/.clang-tidy new file mode 100644 index 000000000..b8f76c6d4 --- /dev/null +++ b/.clang-tidy @@ -0,0 +1,6 @@ +Checks: "*,-fuchsia-*,-google-*,-zircon-*,-abseil-*,-modernize-use-trailing-return-type,-llvm-*,-llvmlibc-*" +WarningsAsErrors: "*" +HeaderFilterRegex: "" +FormatStyle: none +CheckOptions: + - key: altera-struct-pack-align.No diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 82278d72f..14117b86d 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -24,7 +24,7 @@ If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - OS: [e.g. mac/linux/windows] - - Version [e.g. 1.2.12] + - Version [e.g. 1.2.13] **Additional context** Add any other context about the problem here. diff --git a/CMakeLists.txt b/CMakeLists.txt index f1e27290d..96cc0eb57 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,5 +1,5 @@ cmake_minimum_required(VERSION 3.10.0) -project(Griddly VERSION 1.2.12) +project(Griddly VERSION 1.2.13) set(BINARY ${CMAKE_PROJECT_NAME}) @@ -34,6 +34,8 @@ set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) # Don't use e.g. GNU extension (like -std=gnu++11) for portability set(CMAKE_CXX_EXTENSIONS OFF) +# Relevant cmake files are in this folder +set(CMAKE_CONFIG_FOLDER ${CMAKE_SOURCE_DIR}/cmake) # GLM add_subdirectory("libs/glm") @@ -48,6 +50,14 @@ set(YAML_CPP_BUILD_CONTRIB OFF CACHE BOOL "disable yaml contrib") set(YAML_BUILD_SHARED_LIBS OFF CACHE BOOL "disable shared libs") add_subdirectory("libs/yaml-cpp") +#enable clang-format and clang-tidy project wide +include(${CMAKE_CONFIG_FOLDER}/settings/Clang-cxx-dev-tools.cmake) + +# standard compiler warnings +add_library(project_warnings INTERFACE) +include(${CMAKE_CONFIG_FOLDER}/settings/CompilerWarnings.cmake) +set_project_warnings(project_warnings) + find_package(Vulkan REQUIRED FATAL_ERROR) set(VULKAN_SHADER_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src/Griddly/Core/Observers/Vulkan/resources/shaders) @@ -84,7 +94,7 @@ set(STB_DIR "libs/stb") include_directories(${STB_DIR}) add_library(${BINARY} STATIC ${GRIDDLY_SOURCES}) -target_link_libraries(${BINARY} PRIVATE Vulkan::Vulkan yaml-cpp glm) +target_link_libraries(${BINARY} PRIVATE project_warnings Vulkan::Vulkan yaml-cpp glm) # Add the pybind11 module set(PYTHON_MODULE python_griddly) @@ -99,7 +109,7 @@ if(MSVC) endif() set_target_properties(${PYTHON_MODULE} PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${BIN_OUTPUT_DIR}) -target_link_libraries(${PYTHON_MODULE} PRIVATE ${BINARY} Vulkan::Vulkan yaml-cpp glm) +target_link_libraries(${PYTHON_MODULE} PRIVATE ${BINARY} project_warnings Vulkan::Vulkan yaml-cpp glm ) set(CPACK_PROJECT_NAME ${PROJECT_NAME}) set(CPACK_PROJECT_VERSION ${PROJECT_VERSION}) @@ -110,5 +120,5 @@ include(CTest) enable_testing() if(BUILD_TESTING) - add_subdirectory (tests) + add_subdirectory(tests) endif() diff --git a/bindings/python.cpp b/bindings/python.cpp index 92f98ecc9..c07ed6652 100644 --- a/bindings/python.cpp +++ b/bindings/python.cpp @@ -12,7 +12,7 @@ namespace griddly { PYBIND11_MODULE(python_griddly, m) { m.doc() = "Griddly python bindings"; - m.attr("version") = "1.2.12"; + m.attr("version") = "1.2.13"; #ifndef NDEBUG spdlog::set_level(spdlog::level::debug); diff --git a/cmake/settings/Clang-cxx-dev-tools.cmake b/cmake/settings/Clang-cxx-dev-tools.cmake new file mode 100644 index 000000000..98db85df6 --- /dev/null +++ b/cmake/settings/Clang-cxx-dev-tools.cmake @@ -0,0 +1,20 @@ +file(GLOB_RECURSE + ALL_CXX_SOURCE_FILES + src/*.[ch]pp + src/*.h + tests/*.[ch]pp + tests/*.h +) + +# Adding clang-format target if executable is found +message(STATUS "finding clang format") +find_program(CLANG_FORMAT "clang-format") +if(CLANG_FORMAT) + add_custom_target( + clang-format + COMMAND ${CLANG_FORMAT} + -i + -style=file + ${ALL_CXX_SOURCE_FILES} +) +endif() \ No newline at end of file diff --git a/cmake/settings/CompilerWarnings.cmake b/cmake/settings/CompilerWarnings.cmake new file mode 100644 index 000000000..e538da9d7 --- /dev/null +++ b/cmake/settings/CompilerWarnings.cmake @@ -0,0 +1,87 @@ +function(set_project_warnings project_name) + + set(MSVC_WARNINGS + /W4 # Baseline reasonable warnings + /w14242 # 'identifier': conversion from 'type1' to 'type1', possible loss + # of data + /w14254 # 'operator': conversion from 'type1:field_bits' to + # 'type2:field_bits', possible loss of data + /w14263 # 'function': member function does not override any base class + # virtual member function + /w14265 # 'classname': class has virtual functions, but destructor is not + # virtual instances of this class may not be destructed correctly + /w14287 # 'operator': unsigned/negative constant mismatch + /we4289 # nonstandard extension used: 'variable': loop control variable + # declared in the for-loop is used outside the for-loop scope + /w14296 # 'operator': expression is always 'boolean_value' + /w14311 # 'variable': pointer truncation from 'type1' to 'type2' + /w14545 # expression before comma evaluates to a function which is missing + # an argument list + /w14546 # function call before comma missing argument list + /w14547 # 'operator': operator before comma has no effect; expected + # operator with side-effect + /w14549 # 'operator': operator before comma has no effect; did you intend + # 'operator'? + /w14555 # expression has no effect; expected expression with side- effect + /w14619 # pragma warning: there is no warning number 'number' + /w14640 # Enable warning on thread un-safe static member initialization + /w14826 # Conversion from 'type1' to 'type_2' is sign-extended. This may + # cause unexpected runtime behavior. + /w14905 # wide string literal cast to 'LPSTR' + /w14906 # string literal cast to 'LPWSTR' + /w14928 # illegal copy-initialization; more than one user-defined + # conversion has been implicitly applied + /permissive- # standards conformance mode for MSVC compiler. + ) + + set(CLANG_WARNINGS + -Wall + -Wextra # reasonable and standard + -Wshadow # warn the user if a variable declaration shadows one from a + # parent context + -Wnon-virtual-dtor # warn the user if a class with virtual functions has a + # non-virtual destructor. This helps catch hard to + # track down memory errors + -Wold-style-cast # warn for c-style casts + -Wcast-align # warn for potential performance problem casts + -Wunused # warn on anything being unused + -Woverloaded-virtual # warn if you overload (not override) a virtual + # function + -Wpedantic # warn if non-standard C++ is used + -Wconversion # warn on type conversions that may lose data + #-Wsign-conversion # warn on sign conversions + -Wnull-dereference # warn if a null dereference is detected + -Wdouble-promotion # warn if float is implicit promoted to double + -Wformat=2 # warn on security issues around functions that format output + # (ie printf) + ) + + if (WARNINGS_AS_ERRORS) + set(CLANG_WARNINGS ${CLANG_WARNINGS} -Werror) + set(MSVC_WARNINGS ${MSVC_WARNINGS} /WX) + endif() + + set(GCC_WARNINGS + ${CLANG_WARNINGS} + -Wmisleading-indentation # warn if indentation implies blocks where blocks + # do not exist + -Wduplicated-cond # warn if if / else chain has duplicated conditions + -Wduplicated-branches # warn if if / else branches have duplicated code + -Wlogical-op # warn about logical operations being used where bitwise were + # probably wanted + -Wuseless-cast # warn if you perform a cast to the same type + ) + + if(MSVC) + set(PROJECT_WARNINGS ${MSVC_WARNINGS}) + elseif(CMAKE_CXX_COMPILER_ID MATCHES ".*Clang") + set(PROJECT_WARNINGS ${CLANG_WARNINGS}) + elseif(CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + set(PROJECT_WARNINGS ${GCC_WARNINGS}) + else() + message(AUTHOR_WARNING "No compiler warnings set for '${CMAKE_CXX_COMPILER_ID}' compiler.") + endif() + + target_compile_options(${project_name} INTERFACE ${PROJECT_WARNINGS}) + +endfunction() \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py index cfab91a0b..a05d722fe 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -22,7 +22,7 @@ author = 'Chris Bamford' # The full version, including alpha/beta/rc tags -release = '1.2.12' +release = '1.2.13' # -- General configuration --------------------------------------------------- diff --git a/python/examples/clone_environments/clone_environments.py b/python/examples/clone_environments/clone_environments.py index b1dd2d4a4..9e3a7ce9b 100644 --- a/python/examples/clone_environments/clone_environments.py +++ b/python/examples/clone_environments/clone_environments.py @@ -1,4 +1,5 @@ import gym +import griddly import numpy as np env = gym.make('GDY-Sokoban-v0') diff --git a/python/griddly/GymWrapper.py b/python/griddly/GymWrapper.py index f3fb359b0..4bd3a2edf 100644 --- a/python/griddly/GymWrapper.py +++ b/python/griddly/GymWrapper.py @@ -144,11 +144,16 @@ def step(self, action): else: raise ValueError(f'The supplied action is in the wrong format for this environment.\n\n' f'A valid example: {self.action_space.sample()}') - - for p in range(self.player_count): - # Copy only if the environment is done (it will reset itself) - # This is because the underlying data will be released - self._player_last_observation[p] = np.array(self._players[p].observe(), copy=False) + # In the case where the environment is cloned, but no step has happened to replace the last obs, + # we can do that here + if len(self._player_last_observation) == 0: + for p in range(self.player_count): + self._player_last_observation.append(np.array(self._players[p].observe(), copy=False)) + else: + for p in range(self.player_count): + # Copy only if the environment is done (it will reset itself) + # This is because the underlying data will be released + self._player_last_observation[p] = np.array(self._players[p].observe(), copy=False) obs = self._player_last_observation[0] if self.player_count == 1 else self._player_last_observation @@ -169,6 +174,9 @@ def reset(self, level_id=None, level_string=None, global_observations=False): self.initialize_spaces() + for p in range(self.player_count): + self._player_last_observation.append(np.array(self._players[p].observe(), copy=False)) + if global_observations: self._global_last_observation = np.array(self.game.observe(), copy=False) @@ -203,9 +211,6 @@ def initialize_spaces(self): self.action_space = self._create_action_space() - for p in range(self.player_count): - self._player_last_observation.append(np.array(self._players[p].observe(), copy=False)) - def render(self, mode='human', observer=0): if observer == 'global': @@ -223,6 +228,12 @@ def render(self, mode='human', observer=0): return ascii_string else: + # In the case where the environment is cloned, but no step has happened to replace the last obs, + # we can do that here + if len(self._player_last_observation) == 0: + for p in range(self.player_count): + self._player_last_observation.append(np.array(self._players[p].observe(), copy=False)) + observation = self._player_last_observation[observer] if self._player_observer_type[observer] == gd.ObserverType.VECTOR: observation = self._vector2rgb.convert(observation) @@ -261,6 +272,8 @@ def close(self): self._renderWindow = {} + self.game.release() + def __del__(self): self.close() diff --git a/python/setup.py b/python/setup.py index 194cae74b..e18fbdc75 100644 --- a/python/setup.py +++ b/python/setup.py @@ -71,7 +71,7 @@ def griddly_package_data(config='Debug'): setup( name='griddly', - version="1.2.12", + version="1.2.13", author_email="chrisbam4d@gmail.com", description="Griddly Python Libraries", long_description=long_description, diff --git a/src/Griddly/Core/AStarPathFinder.cpp b/src/Griddly/Core/AStarPathFinder.cpp index 491ce9085..d9c59b5ef 100644 --- a/src/Griddly/Core/AStarPathFinder.cpp +++ b/src/Griddly/Core/AStarPathFinder.cpp @@ -1,11 +1,13 @@ #include "AStarPathFinder.hpp" -#include + #include + +#include #include -#include "Grid.hpp" -#include "GDY/Objects/Object.hpp" #include "GDY/Actions/Action.hpp" +#include "GDY/Objects/Object.hpp" +#include "Grid.hpp" namespace griddly { @@ -14,7 +16,7 @@ AStarPathFinder::AStarPathFinder(std::shared_ptr grid, std::set currentBestNode) { - if(currentBestNode->parent->parent == nullptr) { + if (currentBestNode->parent->parent == nullptr) { return {currentBestNode->actionId}; } else { spdlog::debug("Reconstructing path: [{0},{1}]->[{2},{3}] actionId: {4}", currentBestNode->parent->location.x, currentBestNode->parent->location.y, currentBestNode->location.x, currentBestNode->location.y, currentBestNode->parent->actionId); @@ -24,38 +26,36 @@ SearchOutput AStarPathFinder::reconstructPath(std::shared_ptr cur } SearchOutput AStarPathFinder::search(glm::ivec2 startLocation, glm::ivec2 endLocation, glm::ivec2 startOrientationVector, uint32_t maxDepth) { - std::priority_queue, std::vector>, SortAStarPathNodes> orderedBestNodes; std::unordered_map> nodes; auto startNode = std::make_shared(AStarPathNode(startLocation, startOrientationVector)); - startNode->scoreFromStart = glm::distance((glm::vec2)endLocation, (glm::vec2)startLocation); + startNode->scoreFromStart = glm::distance(static_cast(endLocation), static_cast(startLocation)); startNode->scoreToGoal = 0; orderedBestNodes.push(startNode); - while(!orderedBestNodes.empty()) { - + while (!orderedBestNodes.empty()) { auto currentBestNode = orderedBestNodes.top(); orderedBestNodes.pop(); spdlog::debug("Current best node at location: [{0},{1}]. score: {2}, action: {3}", currentBestNode->location.x, currentBestNode->location.y, currentBestNode->scoreFromStart, currentBestNode->actionId); - if(currentBestNode->location == endLocation) { + if (currentBestNode->location == endLocation) { return reconstructPath(currentBestNode); } auto rotationMatrix = DiscreteOrientation(currentBestNode->orientationVector).getRotationMatrix(); - for(auto& inputMapping : actionInputs_.inputMappings) { + for (auto& inputMapping : actionInputs_.inputMappings) { const auto actionId = inputMapping.first; const auto mapping = inputMapping.second; - const auto vectorToDest = actionInputs_.relative ? mapping.vectorToDest * rotationMatrix: mapping.vectorToDest; + const auto vectorToDest = actionInputs_.relative ? mapping.vectorToDest * rotationMatrix : mapping.vectorToDest; const auto nextLocation = currentBestNode->location + vectorToDest; - const auto nextOrientation = actionInputs_.relative ? mapping.orientationVector * rotationMatrix: mapping.orientationVector; + const auto nextOrientation = actionInputs_.relative ? mapping.orientationVector * rotationMatrix : mapping.orientationVector; - if(nextLocation.y < 0 || nextLocation.y >= grid_->getHeight() || nextLocation.x < 0 || nextLocation.x >= grid_->getWidth()) { + if (nextLocation.y < 0 || nextLocation.y >= grid_->getHeight() || nextLocation.x < 0 || nextLocation.x >= grid_->getWidth()) { continue; } @@ -64,27 +64,27 @@ SearchOutput AStarPathFinder::search(glm::ivec2 startLocation, glm::ivec2 endLoc bool passable = true; for (const auto& object : objectsAtNextLocation) { auto objectName = object.second->getObjectName(); - if(impassableObjects_.find(objectName) != impassableObjects_.end()) { + if (impassableObjects_.find(objectName) != impassableObjects_.end()) { passable = false; break; } } - if(passable) { + if (passable) { std::shared_ptr neighbourNode; auto nodeKey = glm::ivec4(nextLocation, nextOrientation); - if(nodes.find(nodeKey) != nodes.end()) { + if (nodes.find(nodeKey) != nodes.end()) { neighbourNode = nodes.at(nodeKey); } else { neighbourNode = std::make_shared(AStarPathNode(nextLocation, nextOrientation)); nodes[nodeKey] = neighbourNode; } - auto nextScoreToGoal = currentBestNode->scoreToGoal + glm::length((glm::vec2)mapping.vectorToDest); + auto nextScoreToGoal = currentBestNode->scoreToGoal + glm::length(static_cast(mapping.vectorToDest)); - if(nextScoreToGoal < neighbourNode->scoreToGoal) { + if (nextScoreToGoal < neighbourNode->scoreToGoal) { // We have found a better path // Set the action from the current best node to this node @@ -93,20 +93,16 @@ SearchOutput AStarPathFinder::search(glm::ivec2 startLocation, glm::ivec2 endLoc // Calculate the scores neighbourNode->scoreToGoal = nextScoreToGoal; - neighbourNode->scoreFromStart = nextScoreToGoal + glm::distance((glm::vec2)endLocation, (glm::vec2)nextLocation); + neighbourNode->scoreFromStart = nextScoreToGoal + glm::distance(static_cast(endLocation), static_cast(nextLocation)); spdlog::debug("New scores for location: [{0},{1}], scoreToGoal: {2}, scoreFromStart: {3}, action: {4}", nextLocation.x, nextLocation.y, neighbourNode->scoreToGoal, neighbourNode->scoreFromStart, actionId); orderedBestNodes.push(neighbourNode); - } } - } } return SearchOutput(); - } - } // namespace griddly \ No newline at end of file diff --git a/src/Griddly/Core/AStarPathFinder.hpp b/src/Griddly/Core/AStarPathFinder.hpp index 09afe96b7..45d15fa28 100644 --- a/src/Griddly/Core/AStarPathFinder.hpp +++ b/src/Griddly/Core/AStarPathFinder.hpp @@ -1,21 +1,19 @@ #pragma once -#include "PathFinder.hpp" -#include "Grid.hpp" -#include "Util/util.hpp" #include "AStarPathNode.hpp" #include "GDY/Actions/Action.hpp" +#include "Grid.hpp" +#include "PathFinder.hpp" +#include "Util/util.hpp" namespace griddly { - struct SortAStarPathNodes { - bool operator()(std::shared_ptr a, std::shared_ptr b){ + bool operator()(std::shared_ptr a, std::shared_ptr b) { return a->scoreFromStart > b->scoreFromStart; }; }; - class AStarPathFinder : public PathFinder { public: AStarPathFinder(std::shared_ptr grid, std::set impassableObjects, ActionInputsDefinition actionInputs); @@ -24,10 +22,9 @@ class AStarPathFinder : public PathFinder { virtual SearchOutput search(glm::ivec2 startLocation, glm::ivec2 endLocation, glm::ivec2 startOrientationVector, uint32_t maxDepth) override; - private: - const std::string targetAction_; - const ActionInputsDefinition actionInputs_; - + private: + const std::string targetAction_; + const ActionInputsDefinition actionInputs_; }; } // namespace griddly diff --git a/src/Griddly/Core/AStarPathNode.hpp b/src/Griddly/Core/AStarPathNode.hpp index e6758471a..94e083101 100644 --- a/src/Griddly/Core/AStarPathNode.hpp +++ b/src/Griddly/Core/AStarPathNode.hpp @@ -1,15 +1,14 @@ #pragma once #include -#include #include +#include namespace griddly { class AStarPathNode { public: - - AStarPathNode(glm::ivec2 nodeLocation, glm::ivec2 nodeOrientationVector) - : location(nodeLocation), orientationVector(nodeOrientationVector) { + AStarPathNode(glm::ivec2 nodeLocation, glm::ivec2 nodeOrientationVector) + : location(nodeLocation), orientationVector(nodeOrientationVector) { } float scoreFromStart = std::numeric_limits::max(); diff --git a/src/Griddly/Core/CollisionDetector.hpp b/src/Griddly/Core/CollisionDetector.hpp index f957e5c60..1136faaac 100644 --- a/src/Griddly/Core/CollisionDetector.hpp +++ b/src/Griddly/Core/CollisionDetector.hpp @@ -1,16 +1,14 @@ #pragma once +#include #include -#include #include - -#include +#include namespace griddly { class Object; - struct SearchResult { std::unordered_set> objectSet; std::vector> closestObjects; @@ -19,6 +17,7 @@ struct SearchResult { class CollisionDetector { public: CollisionDetector(uint32_t gridWidth, uint32_t gridHeight, uint32_t range); + virtual ~CollisionDetector() = default; virtual bool upsert(std::shared_ptr object) = 0; @@ -28,7 +27,7 @@ class CollisionDetector { protected: const uint32_t range_; - const uint32_t gridWidth_; + const uint32_t gridWidth_; const uint32_t gridHeight_; }; diff --git a/src/Griddly/Core/CollisionDetectorFactory.cpp b/src/Griddly/Core/CollisionDetectorFactory.cpp index 684227f74..0b0cc7e47 100644 --- a/src/Griddly/Core/CollisionDetectorFactory.cpp +++ b/src/Griddly/Core/CollisionDetectorFactory.cpp @@ -1,18 +1,18 @@ #include "CollisionDetectorFactory.hpp" + #include "SpatialHashCollisionDetector.hpp" namespace griddly { std::shared_ptr CollisionDetectorFactory::newCollisionDetector(uint32_t gridWidth, uint32_t gridHeight, ActionTriggerDefinition actionTriggerDefinition) { - // Calculate bucket size auto minDim = gridWidth > gridHeight ? gridWidth : gridHeight; uint32_t cellSize = 10; - + if (minDim >= 100) { cellSize = (uint32_t)std::floor(std::sqrt((double)minDim)); } return std::shared_ptr(new SpatialHashCollisionDetector(gridWidth, gridHeight, cellSize, actionTriggerDefinition.range, actionTriggerDefinition.triggerType)); } -} \ No newline at end of file +} // namespace griddly \ No newline at end of file diff --git a/src/Griddly/Core/CollisionDetectorFactory.hpp b/src/Griddly/Core/CollisionDetectorFactory.hpp index 537047dee..112cc5f82 100644 --- a/src/Griddly/Core/CollisionDetectorFactory.hpp +++ b/src/Griddly/Core/CollisionDetectorFactory.hpp @@ -1,6 +1,7 @@ #pragma once #include + #include "CollisionDetector.hpp" namespace griddly { @@ -9,6 +10,7 @@ struct ActionTriggerDefinition; class CollisionDetectorFactory { public: + virtual ~CollisionDetectorFactory() = default; virtual std::shared_ptr newCollisionDetector(uint32_t gridHeight, uint32_t gridWidth, ActionTriggerDefinition actionTriggerDefinition); }; diff --git a/src/Griddly/Core/DelayedActionQueueItem.hpp b/src/Griddly/Core/DelayedActionQueueItem.hpp index e174b29f0..a5ed07447 100644 --- a/src/Griddly/Core/DelayedActionQueueItem.hpp +++ b/src/Griddly/Core/DelayedActionQueueItem.hpp @@ -7,8 +7,8 @@ namespace griddly { class DelayedActionQueueItem { public: - DelayedActionQueueItem(uint32_t playerId, uint32_t priority, std::shared_ptr action) - : playerId(playerId), priority(priority), action(action) { + DelayedActionQueueItem(uint32_t _playerId, uint32_t _priority, std::shared_ptr _action) + : playerId(_playerId), priority(_priority), action(_action) { } bool operator==(const DelayedActionQueueItem& other) const { return priority == other.priority; @@ -21,7 +21,7 @@ class DelayedActionQueueItem { bool operator<(const DelayedActionQueueItem& other) const { return priority > other.priority; } - + uint32_t playerId; uint32_t priority; std::shared_ptr action; diff --git a/src/Griddly/Core/GDY/Actions/Action.cpp b/src/Griddly/Core/GDY/Actions/Action.cpp index c762c9d44..10c5a707d 100644 --- a/src/Griddly/Core/GDY/Actions/Action.cpp +++ b/src/Griddly/Core/GDY/Actions/Action.cpp @@ -13,8 +13,6 @@ Action::Action(std::shared_ptr grid, std::string actionName, uint32_t play metaData_(metaData) { } -Action::~Action() {} - std::string Action::getDescription() const { auto sourceLocation = getSourceLocation(); auto destinationLocation = getDestinationLocation(); @@ -47,11 +45,13 @@ void Action::init(std::shared_ptr sourceObject, std::shared_ptr void Action::init(std::shared_ptr sourceObject, glm::ivec2 vectorToDest, glm::ivec2 orientationVector, bool relativeToSource) { sourceObject_ = sourceObject; + spdlog::debug("Getting rotation matrix from source"); auto rotationMatrix = sourceObject_->getObjectOrientation().getRotationMatrix(); vectorToDest_ = relativeToSource ? vectorToDest * rotationMatrix : vectorToDest; orientationVector_ = relativeToSource ? orientationVector * rotationMatrix : orientationVector; + spdlog::debug("SRC_OBJ_DST_VEC"); actionMode_ = ActionMode::SRC_OBJ_DST_VEC; } @@ -64,6 +64,8 @@ std::shared_ptr Action::getSourceObject() const { return srcObject; } + spdlog::debug("getting default object"); + return grid_->getPlayerDefaultObject(playerId_); } } @@ -89,6 +91,8 @@ std::shared_ptr Action::getDestinationObject() const { return grid_->getPlayerDefaultObject(playerId_); } } + + return nullptr; } glm::ivec2 Action::getSourceLocation() const { @@ -100,6 +104,8 @@ glm::ivec2 Action::getSourceLocation() const { case ActionMode::SRC_OBJ_DST_VEC: return sourceObject_->getLocation(); } + + return {}; } glm::ivec2 Action::getDestinationLocation() const { @@ -112,6 +118,8 @@ glm::ivec2 Action::getDestinationLocation() const { case ActionMode::SRC_OBJ_DST_VEC: return sourceObject_->getLocation() + vectorToDest_; } + + return {}; } glm::ivec2 Action::getVectorToDest() const { diff --git a/src/Griddly/Core/GDY/Actions/Action.hpp b/src/Griddly/Core/GDY/Actions/Action.hpp index 51db04153..1c6f83773 100644 --- a/src/Griddly/Core/GDY/Actions/Action.hpp +++ b/src/Griddly/Core/GDY/Actions/Action.hpp @@ -23,11 +23,11 @@ struct InputMapping { glm::ivec2 vectorToDest{}; glm::ivec2 orientationVector{}; std::string description; - std::unordered_map metaData; + std::unordered_map metaData{}; }; struct ActionInputsDefinition { - std::unordered_map inputMappings; + std::unordered_map inputMappings{}; bool relative = false; bool internal = false; bool mapToGrid = false; @@ -73,7 +73,7 @@ class Action { virtual int32_t getMetaData(std::string variableName) const; - ~Action(); + virtual ~Action() = default; protected: std::shared_ptr sourceObject_ = nullptr; diff --git a/src/Griddly/Core/GDY/Actions/Direction.hpp b/src/Griddly/Core/GDY/Actions/Direction.hpp index 345a2cb0f..d216aa521 100644 --- a/src/Griddly/Core/GDY/Actions/Direction.hpp +++ b/src/Griddly/Core/GDY/Actions/Direction.hpp @@ -20,7 +20,7 @@ class DiscreteOrientation { unitVector_ = {0, 0}; direction_ = Direction::NONE; } - + DiscreteOrientation(glm::ivec2 vector) { unitVector_ = vector; @@ -72,7 +72,7 @@ class DiscreteOrientation { case Direction::DOWN: return glm::pi(); case Direction::LEFT: - return 3 * glm::pi() / 2.0; + return 3.0f * glm::pi() / 2.0f; default: return 0.0f; } @@ -85,7 +85,7 @@ class DiscreteOrientation { std::string getName() { switch (direction_) { case Direction::NONE: - return "NONE"; + return "NONE"; case Direction::UP: return "UP"; case Direction::RIGHT: @@ -106,6 +106,7 @@ class DiscreteOrientation { glm::imat2x2 getRotationMatrix() { switch (direction_) { + default: case Direction::NONE: case Direction::UP: return {{1, 0}, {0, 1}}; diff --git a/src/Griddly/Core/GDY/GDYFactory.cpp b/src/Griddly/Core/GDY/GDYFactory.cpp index ccdb970bc..02aafb63e 100644 --- a/src/Griddly/Core/GDY/GDYFactory.cpp +++ b/src/Griddly/Core/GDY/GDYFactory.cpp @@ -27,9 +27,6 @@ GDYFactory::GDYFactory(std::shared_ptr objectGenerator, std::sh #endif } -GDYFactory::~GDYFactory() { -} - void GDYFactory::initializeFromFile(std::string filename) { spdlog::info("Loading GDY file: {0}", filename); std::ifstream gdyFile; @@ -164,12 +161,12 @@ void GDYFactory::parseBlockObserverConfig(YAML::Node observerConfigNode) { } } -glm::ivec2 GDYFactory::parseTileSize(YAML::Node observerConfigNode) { - glm::ivec2 tileSize{}; +glm::uvec2 GDYFactory::parseTileSize(YAML::Node observerConfigNode) { + glm::uvec2 tileSize{}; if (observerConfigNode["TileSize"].IsDefined()) { auto tileSizeNode = observerConfigNode["TileSize"]; if (tileSizeNode.IsScalar()) { - tileSize = glm::ivec2(tileSizeNode.as()); + tileSize = glm::uvec2(tileSizeNode.as()); } else if (tileSizeNode.IsSequence()) { tileSize.x = tileSizeNode[0].as(); tileSize.y = tileSizeNode[1].as(); @@ -208,8 +205,8 @@ void GDYFactory::parsePlayerDefinition(YAML::Node playerNode) { if (observerNode.IsDefined()) { auto observerGridWidth = observerNode["Width"].as(0); auto observerGridHeight = observerNode["Height"].as(0); - auto observerGridOffsetX = observerNode["OffsetX"].as(0); - auto observerGridOffsetY = observerNode["OffsetY"].as(0); + auto observerGridOffsetX = observerNode["OffsetX"].as(0); + auto observerGridOffsetY = observerNode["OffsetY"].as(0); auto trackAvatar = observerNode["TrackAvatar"].as(false); auto rotateWithAvatar = observerNode["RotateWithAvatar"].as(false); auto highlightPlayers = observerNode["HighlightPlayers"].as(true); @@ -260,8 +257,8 @@ bool GDYFactory::parseTerminationConditionV2(TerminationState state, YAML::Node auto reward = rewardNode.as(0); auto opposingReward = opposingRewardNode.as(0); - for (std::size_t c = 0; c < conditionNode.size(); c++) { - auto commandIt = validateCommandPairNode(conditionNode[c]); + for (std::size_t i = 0; i < conditionNode.size(); i++) { + auto commandIt = validateCommandPairNode(conditionNode[i]); auto commandName = commandIt->first.as(); auto commandArguments = singleOrListNodeToList(commandIt->second); @@ -398,8 +395,8 @@ void GDYFactory::parseIsometricObserverDefinition(std::string objectName, uint32 auto tileOffsetNode = isometricSpriteNode["Offset"]; if (tileOffsetNode.IsDefined() && tileOffsetNode.IsSequence()) { - spriteDefinition.offset.x = tileOffsetNode[0].as(0); - spriteDefinition.offset.y = tileOffsetNode[1].as(0); + spriteDefinition.offset.x = tileOffsetNode[0].as(0); + spriteDefinition.offset.y = tileOffsetNode[1].as(0); } auto tilingMode = isometricSpriteNode["TilingMode"]; @@ -847,7 +844,7 @@ std::shared_ptr GDYFactory::getLevelGenerator(uint32_t level) co spdlog::error(error); throw std::invalid_argument(error); } - return mapLevelGenerators_[(uint32_t)level]; + return mapLevelGenerators_[static_cast(level)]; } std::shared_ptr GDYFactory::getLevelGenerator(std::string levelString) const { @@ -904,7 +901,7 @@ std::string GDYFactory::getAvatarObject() const { } uint32_t GDYFactory::getLevelCount() const { - return mapLevelGenerators_.size(); + return static_cast(mapLevelGenerators_.size()); } std::string GDYFactory::getName() const { diff --git a/src/Griddly/Core/GDY/GDYFactory.hpp b/src/Griddly/Core/GDY/GDYFactory.hpp index 7c4f01c5d..967f56b86 100644 --- a/src/Griddly/Core/GDY/GDYFactory.hpp +++ b/src/Griddly/Core/GDY/GDYFactory.hpp @@ -21,7 +21,7 @@ namespace griddly { class GDYFactory { public: GDYFactory(std::shared_ptr objectGenerator, std::shared_ptr terminationGenerator, ResourceConfig resourceConfig); - ~GDYFactory(); + virtual ~GDYFactory() = default; static ActionBehaviourDefinition makeBehaviourDefinition(ActionBehaviourType behaviourType, std::string objectName, @@ -95,7 +95,7 @@ class GDYFactory { void parseBlockObserverConfig(YAML::Node observerConfigNode); void parseVectorObserverConfig(YAML::Node observerConfigNode); - glm::ivec2 parseTileSize(YAML::Node observerConfigNode); + glm::uvec2 parseTileSize(YAML::Node observerConfigNode); void parseBlockObserverDefinitions(std::string objectName, YAML::Node blockNode); void parseBlockObserverDefinition(std::string objectName, uint32_t renderTileId, YAML::Node blockNode); diff --git a/src/Griddly/Core/GDY/Objects/Object.cpp b/src/Griddly/Core/GDY/Objects/Object.cpp index 6d7aa39cb..aa4d3de2e 100644 --- a/src/Griddly/Core/GDY/Objects/Object.cpp +++ b/src/Griddly/Core/GDY/Objects/Object.cpp @@ -2,12 +2,12 @@ #include +#include "../../AStarPathFinder.hpp" #include "../../Grid.hpp" +#include "../../SpatialHashCollisionDetector.hpp" #include "../../Util/util.hpp" #include "../Actions/Action.hpp" #include "ObjectGenerator.hpp" -#include "../../AStarPathFinder.hpp" -#include "../../SpatialHashCollisionDetector.hpp" namespace griddly { @@ -23,8 +23,6 @@ Object::Object(std::string objectName, char mapCharacter, uint32_t playerId, uin availableVariables_ = availableVariables; } -Object::~Object() {} - void Object::init(glm::ivec2 location) { init(location, DiscreteOrientation(Direction::NONE)); } @@ -39,7 +37,7 @@ void Object::init(glm::ivec2 location, DiscreteOrientation orientation) { glm::ivec2 Object::getLocation() const { glm::ivec2 location(*x_, *y_); return location; -}; +} std::string Object::getDescription() const { return fmt::format("{0}@[{1}, {2}]", objectName_, *x_, *y_); @@ -367,13 +365,12 @@ BehaviourFunction Object::instantiateBehaviour(std::string commandName, Behaviou } if (commandName == "exec") { - auto actionName = getCommandArgument(commandArguments, "Action", ""); auto delay = getCommandArgument(commandArguments, "Delay", 0); auto randomize = getCommandArgument(commandArguments, "Randomize", false); auto actionId = getCommandArgument(commandArguments, "ActionId", 0); auto executor = getCommandArgument(commandArguments, "Executor", "action"); - auto searchNode = getCommandArgument(commandArguments, "Search", YAML::Node(YAML::NodeType::Undefined)); + auto searchNode = getCommandArgument(commandArguments, "Search", YAML::Node(YAML::NodeType::Undefined)); PathFinderConfig pathFinderConfig = configurePathFinder(searchNode, actionName); @@ -386,19 +383,19 @@ BehaviourFunction Object::instantiateBehaviour(std::string commandName, Behaviou fallbackInputMapping.orientationVector = action->getOrientationVector(); SingleInputMapping inputMapping; - if(pathFinderConfig.pathFinder != nullptr) { + if (pathFinderConfig.pathFinder != nullptr) { spdlog::debug("Executing action based on PathFinder"); auto endLocation = pathFinderConfig.endLocation; if (pathFinderConfig.collisionDetector != nullptr) { auto searchResult = pathFinderConfig.collisionDetector->search(getLocation()); - if (searchResult.objectSet.empty()) { + if (searchResult.objectSet.empty()) { spdlog::debug("Cannot find target object for pathfinding!"); return {}; } endLocation = searchResult.closestObjects.at(0)->getLocation(); - } + } spdlog::debug("Searching for path from [{0},{1}] to [{2},{3}] using action {4}", getLocation().x, getLocation().y, endLocation.x, endLocation.y, actionName); @@ -412,7 +409,7 @@ BehaviourFunction Object::instantiateBehaviour(std::string commandName, Behaviou inputMapping.vectorToDest = inputMapping.destinationLocation - getLocation(); } - auto execAsPlayerId = 0; + uint32_t execAsPlayerId = 0; switch (actionExecutor) { case ActionExecutor::ACTION_PLAYER_ID: execAsPlayerId = action->getOriginatingPlayerId(); @@ -665,7 +662,7 @@ std::vector> Object::getInitialActions(std::shared_ptr C Object::getCommandArgument(BehaviourCommandArguments commandArguments, std::string commandArgumentKey, C defaultValue) { auto commandArgumentIt = commandArguments.find(commandArgumentKey); - if(commandArgumentIt == commandArguments.end()) { + if (commandArgumentIt == commandArguments.end()) { return defaultValue; } @@ -675,13 +672,11 @@ C Object::getCommandArgument(BehaviourCommandArguments commandArguments, std::st PathFinderConfig Object::configurePathFinder(YAML::Node searchNode, std::string actionName) { PathFinderConfig config; if (searchNode.IsDefined()) { - spdlog::debug("Configuring path finder for action {0}", actionName); - - auto targetObjectNameNode = searchNode["TargetObjectName"]; - if(targetObjectNameNode.IsDefined()) { + auto targetObjectNameNode = searchNode["TargetObjectName"]; + if (targetObjectNameNode.IsDefined()) { auto targetObjectName = targetObjectNameNode.as(); spdlog::debug("Path finder target object: {0}", targetObjectName); @@ -693,13 +688,13 @@ PathFinderConfig Object::configurePathFinder(YAML::Node searchNode, std::string config.collisionDetector = std::shared_ptr(new SpatialHashCollisionDetector(grid_->getWidth(), grid_->getHeight(), 10, range, TriggerType::RANGE_BOX_AREA)); - if(config.collisionDetector != nullptr) { + if (config.collisionDetector != nullptr) { grid_->addCollisionDetector({targetObjectName}, actionName + generateRandomString(5), config.collisionDetector); } } - + auto impassableObjectsList = singleOrListNodeToList(searchNode["ImpassableObjects"]); - + std::set impassableObjectsSet(impassableObjectsList.begin(), impassableObjectsList.end()); auto actionInputDefinitions = objectGenerator_->getActionInputDefinitions(); auto actionInputDefinitionIt = actionInputDefinitions.find(actionName); @@ -711,7 +706,6 @@ PathFinderConfig Object::configurePathFinder(YAML::Node searchNode, std::string auto targetEndLocation = singleOrListNodeToList(searchNode["TargetLocation"]); config.endLocation = glm::ivec2(targetEndLocation[0], targetEndLocation[1]); } - } return config; diff --git a/src/Griddly/Core/GDY/Objects/Object.hpp b/src/Griddly/Core/GDY/Objects/Object.hpp index 67a934684..2584055cc 100644 --- a/src/Griddly/Core/GDY/Objects/Object.hpp +++ b/src/Griddly/Core/GDY/Objects/Object.hpp @@ -11,9 +11,8 @@ #include #include "../Actions/Direction.hpp" -#include "ObjectVariable.hpp" #include "../YAMLUtils.hpp" - +#include "ObjectVariable.hpp" #define BehaviourCommandArguments std::unordered_map #define BehaviourFunction std::function)> @@ -56,7 +55,7 @@ struct SingleInputMapping { struct BehaviourResult { bool abortAction = false; - std::unordered_map rewards; + std::unordered_map rewards{}; }; enum class ActionExecutor { @@ -65,10 +64,10 @@ enum class ActionExecutor { }; struct PathFinderConfig { - std::shared_ptr pathFinder = nullptr; - std::shared_ptr collisionDetector = nullptr; - glm::ivec2 endLocation{0,0}; - uint32_t maxSearchDepth = 100; + std::shared_ptr pathFinder = nullptr; + std::shared_ptr collisionDetector = nullptr; + glm::ivec2 endLocation{0, 0}; + uint32_t maxSearchDepth = 100; }; class Object : public std::enable_shared_from_this { @@ -121,7 +120,7 @@ class Object : public std::enable_shared_from_this { Object(std::string objectName, char mapCharacter, uint32_t playerId, uint32_t zIdx, std::unordered_map> availableVariables, std::shared_ptr objectGenerator, std::shared_ptr grid); - ~Object(); + virtual ~Object() = default; private: // Have to be shared pointers because they are used as variables @@ -166,7 +165,7 @@ class Object : public std::enable_shared_from_this { SingleInputMapping getInputMapping(std::string actionName, uint32_t actionId, bool randomize, InputMapping fallback); PathFinderConfig configurePathFinder(YAML::Node searchNode, std::string actionName); - + template static C getCommandArgument(BehaviourCommandArguments commandArguments, std::string commandArgumentKey, C defaultValue); diff --git a/src/Griddly/Core/GDY/Objects/ObjectGenerator.cpp b/src/Griddly/Core/GDY/Objects/ObjectGenerator.cpp index cf788e7de..c8af91f2d 100644 --- a/src/Griddly/Core/GDY/Objects/ObjectGenerator.cpp +++ b/src/Griddly/Core/GDY/Objects/ObjectGenerator.cpp @@ -26,9 +26,6 @@ ObjectGenerator::ObjectGenerator() { objectDefinitions_.insert({"_boundary", std::make_shared(boundaryObjectDefinition)}); } -ObjectGenerator::~ObjectGenerator() { -} - void ObjectGenerator::defineNewObject(std::string objectName, char mapCharacter, uint32_t zIdx, std::unordered_map variableDefinitions) { spdlog::debug("Defining new object {0}", objectName); diff --git a/src/Griddly/Core/GDY/Objects/ObjectGenerator.hpp b/src/Griddly/Core/GDY/Objects/ObjectGenerator.hpp index 988fd635b..2dd8e6be8 100644 --- a/src/Griddly/Core/GDY/Objects/ObjectGenerator.hpp +++ b/src/Griddly/Core/GDY/Objects/ObjectGenerator.hpp @@ -3,8 +3,8 @@ #include #include -#include "Object.hpp" #include "../Actions/Action.hpp" +#include "Object.hpp" namespace griddly { @@ -40,11 +40,11 @@ class ObjectGenerator : public std::enable_shared_from_this { public: ObjectGenerator(); - ~ObjectGenerator(); + virtual ~ObjectGenerator() = default; virtual void defineNewObject(std::string objectName, char mapCharacter, uint32_t zIdx, std::unordered_map variableDefinitions); virtual void defineActionBehaviour(std::string objectName, ActionBehaviourDefinition behaviourDefinition); - virtual void addInitialAction(std::string objectName, std::string actionName, uint32_t actionId, uint32_t delay, bool randomize=false); + virtual void addInitialAction(std::string objectName, std::string actionName, uint32_t actionId, uint32_t delay, bool randomize = false); virtual std::shared_ptr newInstance(std::string objectName, uint32_t playerId, std::shared_ptr grid); virtual std::shared_ptr cloneInstance(std::shared_ptr toClone, std::shared_ptr grid); diff --git a/src/Griddly/Core/GDY/TerminationGenerator.cpp b/src/Griddly/Core/GDY/TerminationGenerator.cpp index 4f197e4ba..08213c607 100644 --- a/src/Griddly/Core/GDY/TerminationGenerator.cpp +++ b/src/Griddly/Core/GDY/TerminationGenerator.cpp @@ -1,13 +1,13 @@ #include "TerminationGenerator.hpp" -#include "TerminationHandler.hpp" -#include "../Players/Player.hpp" #include +#include "../Players/Player.hpp" +#include "TerminationHandler.hpp" + namespace griddly { void TerminationGenerator::defineTerminationCondition(TerminationState state, std::string commandName, int32_t reward, int32_t opposingReward, std::vector commandArguments) { - spdlog::debug("Adding termination condition definition {0} [{1}, {2}]", commandName, commandArguments[0], commandArguments[1]); TerminationConditionDefinition tcd; tcd.commandName = commandName; @@ -19,10 +19,9 @@ void TerminationGenerator::defineTerminationCondition(TerminationState state, st } std::shared_ptr TerminationGenerator::newInstance(std::shared_ptr grid, std::vector> players) { - auto terminationHandler = std::shared_ptr(new TerminationHandler(grid, players)); - for(auto terminationConditionDefinition: terminationConditionDefinitions_) { + for (auto terminationConditionDefinition : terminationConditionDefinitions_) { terminationHandler->addTerminationCondition(terminationConditionDefinition); } diff --git a/src/Griddly/Core/GDY/TerminationGenerator.hpp b/src/Griddly/Core/GDY/TerminationGenerator.hpp index 9bd0c2744..5a3513e6b 100644 --- a/src/Griddly/Core/GDY/TerminationGenerator.hpp +++ b/src/Griddly/Core/GDY/TerminationGenerator.hpp @@ -16,6 +16,8 @@ class TerminationGenerator { virtual void defineTerminationCondition(TerminationState state, std::string commandName, int32_t reward, int32_t opposingReward, std::vector commandArguments); virtual std::shared_ptr newInstance(std::shared_ptr grid, std::vector> players); + virtual ~TerminationGenerator() = default; + private: std::vector terminationConditionDefinitions_; }; diff --git a/src/Griddly/Core/GDY/TerminationHandler.cpp b/src/Griddly/Core/GDY/TerminationHandler.cpp index 463fec8cb..a45ee42c9 100644 --- a/src/Griddly/Core/GDY/TerminationHandler.cpp +++ b/src/Griddly/Core/GDY/TerminationHandler.cpp @@ -24,9 +24,6 @@ TerminationHandler::TerminationHandler(std::shared_ptr grid, std::vector> variablePointers) { spdlog::debug("Adding termination condition={0} for player {1}", commandName, playerId); @@ -70,7 +67,7 @@ TerminationFunction TerminationHandler::instantiateTerminationCondition(Terminat playerTerminationRewards[pid] = state == TerminationState::NONE ? 0 : reward; } else { playerTerminationStates[pid] = oppositeState; - playerTerminationRewards[pid] = oppositeState == TerminationState::NONE ? 0 :opposingReward; + playerTerminationRewards[pid] = oppositeState == TerminationState::NONE ? 0 : opposingReward; } } @@ -101,11 +98,10 @@ void TerminationHandler::resolveTerminationConditions(TerminationState state, st } } - for (auto resolvedTerminationCondition : conditionArguments) { auto playerId = resolvedTerminationCondition.first; auto resolvedVariables = resolvedTerminationCondition.second; - if(conditionArguments.size() > 1 && playerId == 0) { + if (conditionArguments.size() > 1 && playerId == 0) { continue; } terminationFunctions_.push_back(instantiateTerminationCondition(state, commandName, playerId, reward, opposingReward, resolvedVariables)); diff --git a/src/Griddly/Core/GDY/TerminationHandler.hpp b/src/Griddly/Core/GDY/TerminationHandler.hpp index b5a135aff..7d08ffc91 100644 --- a/src/Griddly/Core/GDY/TerminationHandler.hpp +++ b/src/Griddly/Core/GDY/TerminationHandler.hpp @@ -15,7 +15,7 @@ class Player; enum class TerminationState { WIN, LOSE, - NONE // There does not have to be a winner or loser, just terminate + NONE // There does not have to be a winner or loser, just terminate }; struct TerminationResult { @@ -35,7 +35,7 @@ struct TerminationConditionDefinition { class TerminationHandler { public: TerminationHandler(std::shared_ptr grid, std::vector> players); - ~TerminationHandler(); + virtual ~TerminationHandler() = default; virtual TerminationResult isTerminated(); virtual void addTerminationCondition(TerminationConditionDefinition terminationConditionDefinition); diff --git a/src/Griddly/Core/GDY/YAMLUtils.hpp b/src/Griddly/Core/GDY/YAMLUtils.hpp index 8e9879156..a4ae9dd21 100644 --- a/src/Griddly/Core/GDY/YAMLUtils.hpp +++ b/src/Griddly/Core/GDY/YAMLUtils.hpp @@ -34,4 +34,4 @@ inline BehaviourCommandArguments singleOrListNodeToCommandArguments(YAML::Node s return map; } -} \ No newline at end of file +} // namespace griddly \ No newline at end of file diff --git a/src/Griddly/Core/GameProcess.cpp b/src/Griddly/Core/GameProcess.cpp index caae433ea..97d4f9f2b 100644 --- a/src/Griddly/Core/GameProcess.cpp +++ b/src/Griddly/Core/GameProcess.cpp @@ -114,7 +114,7 @@ void GameProcess::init(bool isCloned) { if (playerAvatarObjects.size() > 0) { auto playerId = p->getId(); - if(playerAvatarObjects.find(playerId) == playerAvatarObjects.end()) { + if (playerAvatarObjects.find(playerId) == playerAvatarObjects.end()) { std::string errorMessage = fmt::format("Cannot find avatar for player {0}. Make sure an avatar for this player is defined in the level_string e.g 'A{0}'", playerId); spdlog::error(errorMessage); throw std::invalid_argument(errorMessage); @@ -144,7 +144,7 @@ void GameProcess::resetObservers() { } } - if(observer_ != nullptr) { + if (observer_ != nullptr) { observer_->reset(); } } @@ -167,7 +167,7 @@ void GameProcess::reset() { resetObservers(); spdlog::debug("Resetting Termination Handler."); - terminationHandler_ = std::shared_ptr(gdyFactory_->createTerminationHandler(grid_, players_)); + terminationHandler_ = gdyFactory_->createTerminationHandler(grid_, players_); requiresReset_ = false; spdlog::debug("Reset Complete."); @@ -205,7 +205,7 @@ std::string GameProcess::getProcessName() const { } uint32_t GameProcess::getNumPlayers() const { - return players_.size(); + return static_cast(players_.size()); } uint8_t* GameProcess::observe() const { @@ -277,7 +277,7 @@ std::vector GameProcess::getAvailableActionIdsAtLocation(glm::ivec2 lo for (auto inputMapping : actionInputDefinition.inputMappings) { auto actionId = inputMapping.first; auto mapping = inputMapping.second; - + auto metaData = mapping.metaData; // Create an fake action to test for availability (and not duplicate a bunch of code) @@ -294,7 +294,6 @@ std::vector GameProcess::getAvailableActionIdsAtLocation(glm::ivec2 lo } void GameProcess::generateStateHash(StateInfo& stateInfo) const { - // Hash global variables for (auto variableIt : stateInfo.globalVariables) { hash_combine(stateInfo.hash, variableIt.first); @@ -306,14 +305,14 @@ void GameProcess::generateStateHash(StateInfo& stateInfo) const { // Hash ordered object list std::sort(stateInfo.objectInfo.begin(), stateInfo.objectInfo.end(), SortObjectInfo()); - for(auto o : stateInfo.objectInfo) { + for (auto o : stateInfo.objectInfo) { hash_combine(stateInfo.hash, o.name); hash_combine(stateInfo.hash, o.location); hash_combine(stateInfo.hash, o.orientation.getUnitVector()); hash_combine(stateInfo.hash, o.playerId); // Hash the object variables - for(auto variableIt : o.variables) { + for (auto variableIt : o.variables) { hash_combine(stateInfo.hash, variableIt.first); hash_combine(stateInfo.hash, variableIt.second); } diff --git a/src/Griddly/Core/GameProcess.hpp b/src/Griddly/Core/GameProcess.hpp index 8a5b1579f..24df5e1b6 100644 --- a/src/Griddly/Core/GameProcess.hpp +++ b/src/Griddly/Core/GameProcess.hpp @@ -22,16 +22,15 @@ struct ObjectInfo { std::map variables; glm::ivec2 location; DiscreteOrientation orientation; - uint8_t playerId; - + uint32_t playerId; }; struct SortObjectInfo { inline bool operator()(const ObjectInfo& a, const ObjectInfo& b) { - auto loca = 10000*a.location.x + a.location.y; - auto locb = 10000*b.location.x + b.location.y; - - if(loca == locb) { + auto loca = 10000 * a.location.x + a.location.y; + auto locb = 10000 * b.location.x + b.location.y; + + if (loca == locb) { return a.name < b.name; } else { return loca < locb; @@ -128,4 +127,4 @@ class GameProcess : public std::enable_shared_from_this { void resetObservers(); ObserverConfig getObserverConfig(ObserverType observerType) const; }; -} // namespace griddly \ No newline at end of file +} // namespace griddly diff --git a/src/Griddly/Core/Grid.cpp b/src/Griddly/Core/Grid.cpp index 40dee59ab..23b2cdf5b 100644 --- a/src/Griddly/Core/Grid.cpp +++ b/src/Griddly/Core/Grid.cpp @@ -486,8 +486,7 @@ void Grid::addActionProbability(std::string actionName, float probability) { } void Grid::addCollisionDetector(std::vector objectNames, std::string actionName, std::shared_ptr collisionDetector) { - - for(auto objectName : objectNames) { + for (auto objectName : objectNames) { collisionObjectActionNames_[objectName].insert(actionName); } diff --git a/src/Griddly/Core/Grid.hpp b/src/Griddly/Core/Grid.hpp index b9c4c6ae7..746e83921 100644 --- a/src/Griddly/Core/Grid.hpp +++ b/src/Griddly/Core/Grid.hpp @@ -8,11 +8,11 @@ #include #include +#include "CollisionDetectorFactory.hpp" #include "GDY/Actions/Action.hpp" #include "GDY/Objects/Object.hpp" #include "LevelGenerators/LevelGenerator.hpp" #include "Util/util.hpp" -#include "CollisionDetectorFactory.hpp" #define GLM_ENABLE_EXPERIMENTAL #include @@ -64,7 +64,7 @@ class Grid : public std::enable_shared_from_this { public: Grid(); Grid(std::shared_ptr collisionDetectorFactory); - ~Grid(); + virtual ~Grid(); virtual void setPlayerCount(uint32_t playerCount); virtual void resetMap(uint32_t height, uint32_t width); @@ -100,7 +100,7 @@ class Grid : public std::enable_shared_from_this { virtual void initObject(std::string objectName, std::vector objectVariableNames); - virtual void addObject(glm::ivec2 location, std::shared_ptr object, bool applyInitialActions = true, std::shared_ptr originatingAction=nullptr); + virtual void addObject(glm::ivec2 location, std::shared_ptr object, bool applyInitialActions = true, std::shared_ptr originatingAction = nullptr); virtual bool removeObject(std::shared_ptr object); diff --git a/src/Griddly/Core/LevelGenerators/LevelGenerator.cpp b/src/Griddly/Core/LevelGenerators/LevelGenerator.cpp index d738fc5d5..b33dbe714 100644 --- a/src/Griddly/Core/LevelGenerators/LevelGenerator.cpp +++ b/src/Griddly/Core/LevelGenerators/LevelGenerator.cpp @@ -1,7 +1,7 @@ #include "LevelGenerator.hpp" namespace griddly { - LevelGenerator::~LevelGenerator() { - } +LevelGenerator::~LevelGenerator() { +} } // namespace griddly \ No newline at end of file diff --git a/src/Griddly/Core/LevelGenerators/MapGenerator.cpp b/src/Griddly/Core/LevelGenerators/MapGenerator.cpp index f3dd10b77..81c291cff 100644 --- a/src/Griddly/Core/LevelGenerators/MapGenerator.cpp +++ b/src/Griddly/Core/LevelGenerators/MapGenerator.cpp @@ -15,8 +15,7 @@ MapGenerator::MapGenerator(uint32_t playerCount, std::shared_ptr grid) { grid->resetMap(width_, height_); @@ -43,7 +42,7 @@ void MapGenerator::reset(std::shared_ptr grid) { grid->addActionTrigger(actionTriggerDefinitionIt.first, actionTriggerDefinitionIt.second); } - for(auto& actionProbability : objectGenerator_->getActionProbabilities()) { + for (auto& actionProbability : objectGenerator_->getActionProbabilities()) { grid->addActionProbability(actionProbability.first, actionProbability.second); } @@ -52,7 +51,6 @@ void MapGenerator::reset(std::shared_ptr grid) { auto location = item.first; for (auto& objectData : gridObjectData) { - auto objectName = objectData.objectName; auto playerId = objectData.playerId; @@ -61,7 +59,6 @@ void MapGenerator::reset(std::shared_ptr grid) { grid->addObject(location, object); } } - } void MapGenerator::initializeFromFile(std::string filename) { diff --git a/src/Griddly/Core/LevelGenerators/MapGenerator.hpp b/src/Griddly/Core/LevelGenerators/MapGenerator.hpp index 09c19d986..110c9c9ba 100644 --- a/src/Griddly/Core/LevelGenerators/MapGenerator.hpp +++ b/src/Griddly/Core/LevelGenerators/MapGenerator.hpp @@ -1,8 +1,8 @@ #pragma once #include -#include "LevelGenerator.hpp" #include "../GDY/Objects/ObjectGenerator.hpp" +#include "LevelGenerator.hpp" #define GLM_ENABLE_EXPERIMENTAL #include @@ -10,9 +10,9 @@ namespace griddly { struct GridInitInfo { - std::string objectName; - int32_t playerId; - int32_t zIdx; + std::string objectName; + int32_t playerId; + int32_t zIdx; }; enum class MapReaderState { @@ -32,7 +32,7 @@ class MapGenerator : public LevelGenerator { virtual void reset(std::shared_ptr grid) override; private: - uint32_t width_ = 0; + uint32_t width_ = 0; uint32_t height_ = 0; const uint32_t playerCount_; std::unordered_map> mapDescription_; diff --git a/src/Griddly/Core/Observers/ASCIIObserver.hpp b/src/Griddly/Core/Observers/ASCIIObserver.hpp index dbc3c3966..0a84ed1c5 100644 --- a/src/Griddly/Core/Observers/ASCIIObserver.hpp +++ b/src/Griddly/Core/Observers/ASCIIObserver.hpp @@ -20,7 +20,7 @@ class ASCIIObserver : public Observer { void print(std::shared_ptr observation) override; protected: - void renderLocation(glm::ivec2 objectLocation, glm::ivec2 outputLocation, bool resetLocation=false) const; + void renderLocation(glm::ivec2 objectLocation, glm::ivec2 outputLocation, bool resetLocation = false) const; private: std::shared_ptr observation_; diff --git a/src/Griddly/Core/Observers/BlockObserver.cpp b/src/Griddly/Core/Observers/BlockObserver.cpp index a9b5f3d76..da3f100a0 100644 --- a/src/Griddly/Core/Observers/BlockObserver.cpp +++ b/src/Griddly/Core/Observers/BlockObserver.cpp @@ -13,12 +13,12 @@ BlockObserver::~BlockObserver() { } ObserverType BlockObserver::getObserverType() const { - return ObserverType::BLOCK_2D; + return ObserverType::BLOCK_2D; } void BlockObserver::lazyInit() { VulkanObserver::lazyInit(); - + device_->initRenderMode(vk::RenderMode::SHAPES); for (auto blockDef : blockDefinitions_) { @@ -32,7 +32,6 @@ void BlockObserver::lazyInit() { blockConfigs_.insert({objectName, {col, shapeBuffer, definition.scale, definition.outlineScale}}); } - } void BlockObserver::renderLocation(vk::VulkanRenderContext& ctx, glm::ivec2 objectLocation, glm::ivec2 outputLocation, glm::ivec2 tileOffset, DiscreteOrientation orientation) const { @@ -43,7 +42,7 @@ void BlockObserver::renderLocation(vk::VulkanRenderContext& ctx, glm::ivec2 obje auto object = objectIt.second; auto tileName = object->getObjectRenderTileName(); float objectRotationRad; - + if (object == avatarObject_ && observerConfig_.rotateWithAvatar) { objectRotationRad = 0.0; } else { @@ -63,7 +62,6 @@ void BlockObserver::renderLocation(vk::VulkanRenderContext& ctx, glm::ivec2 obje glm::mat4 model = glm::scale(glm::translate(glm::mat4(1.0f), position), {blockConfig.scale * tileSize.x, blockConfig.scale * tileSize.y, 1.0}); auto orientedModel = glm::rotate(model, objectRotationRad, glm::vec3(0.0, 0.0, 1.0)); - if (observerConfig_.highlightPlayers && observerConfig_.playerCount > 1 && objectPlayerId > 0) { auto playerId = observerConfig_.playerId; @@ -72,16 +70,13 @@ void BlockObserver::renderLocation(vk::VulkanRenderContext& ctx, glm::ivec2 obje if (playerId == objectPlayerId) { outlineColor = glm::vec4(0.0, 1.0, 0.0, 1.0); } else { - outlineColor = globalObserverPlayerColors_[objectPlayerId-1]; + outlineColor = globalObserverPlayerColors_[objectPlayerId - 1]; } device_->drawShapeWithOutline(ctx, blockConfig.shapeBuffer, orientedModel, shapeColor, outlineColor); } else { device_->drawShape(ctx, blockConfig.shapeBuffer, orientedModel, shapeColor); - } - - } } diff --git a/src/Griddly/Core/Observers/IsometricSpriteObserver.cpp b/src/Griddly/Core/Observers/IsometricSpriteObserver.cpp index 3b2606db3..f5f163fa9 100644 --- a/src/Griddly/Core/Observers/IsometricSpriteObserver.cpp +++ b/src/Griddly/Core/Observers/IsometricSpriteObserver.cpp @@ -50,19 +50,19 @@ std::vector IsometricSpriteObserver::calculateDirtyRectangles(std::uno glm::vec2 isometricLocation = isometricOutputLocation(location, noOffset); VkOffset2D offset = { - std::max(0, (int32_t)isometricLocation.x - (tileSize.x / 2) - 2), - std::max(0, (int32_t)isometricLocation.y - (tileSize.y / 2) - 2)}; + std::max(0, static_cast(isometricLocation.x) - (tileSize.x / 2) - 2), + std::max(0, static_cast(isometricLocation.y) - (tileSize.y / 2) - 2)}; // Because we make the dirty rectangles slightly larger than the sprites, must check boundaries do not go beyond // the render image surface - auto extentWidth = (uint32_t)tileSize.x + 4; - auto boundaryX = (int32_t)extentWidth + offset.x - (int32_t)pixelWidth_; + auto extentWidth = static_cast(tileSize.x) + 4; + auto boundaryX = static_cast(extentWidth) + offset.x - static_cast(pixelWidth_); if (boundaryX > 0) { extentWidth -= boundaryX; } - auto extentHeight = (uint32_t)tileSize.y + 4; - auto boundaryY = (int32_t)extentHeight + offset.y - (int32_t)pixelHeight_; + auto extentHeight = static_cast(tileSize.y) + 4; + auto boundaryY = static_cast(extentHeight) + offset.y - static_cast(pixelHeight_); if (boundaryY > 0) { extentHeight -= boundaryY; } @@ -93,8 +93,6 @@ void IsometricSpriteObserver::renderLocation(vk::VulkanRenderContext& ctx, glm:: auto tilingMode = spriteDefinition.tilingMode; auto isIsoFloor = tilingMode == TilingMode::ISO_FLOOR; - float outlineScale = spriteDefinition.outlineScale; - uint32_t spriteArrayLayer = device_->getSpriteArrayLayer(tileName); // Just a hack to keep depth between 0 and 1 diff --git a/src/Griddly/Core/Observers/IsometricSpriteObserver.hpp b/src/Griddly/Core/Observers/IsometricSpriteObserver.hpp index ce9fef069..ed722f0c2 100644 --- a/src/Griddly/Core/Observers/IsometricSpriteObserver.hpp +++ b/src/Griddly/Core/Observers/IsometricSpriteObserver.hpp @@ -24,7 +24,6 @@ class IsometricSpriteObserver : public SpriteObserver { private: glm::vec2 isoOriginOffset_; - }; } // namespace griddly \ No newline at end of file diff --git a/src/Griddly/Core/Observers/Observer.cpp b/src/Griddly/Core/Observers/Observer.cpp index 862b3dfc3..d3690de70 100644 --- a/src/Griddly/Core/Observers/Observer.cpp +++ b/src/Griddly/Core/Observers/Observer.cpp @@ -8,7 +8,6 @@ Observer::Observer(std::shared_ptr grid) : grid_(grid) { } void Observer::init(ObserverConfig observerConfig) { - spdlog::debug("Initializing observer."); if (observerState_ != ObserverState::NONE) { @@ -29,7 +28,7 @@ void Observer::reset() { spdlog::debug("Observation Shape ({0}, {1}, {2})", observationShape_[0], observationShape_[1], observationShape_[2]); // if the observer is "READY", then it has already been initialized once, so keep it in the ready state, we're just resetting it. - observerState_ = observerState_ == ObserverState::READY? ObserverState::READY: ObserverState::RESET; + observerState_ = observerState_ == ObserverState::READY ? ObserverState::READY : ObserverState::RESET; } void Observer::setAvatar(std::shared_ptr avatarObject) { @@ -60,28 +59,28 @@ PartialObservableGrid Observer::getAvatarObservableGrid(glm::ivec2 avatarLocatio switch (avatarOrientation) { case Direction::NONE: case Direction::UP: - partiallyObservableGrid.left = (int32_t)avatarLocation.x - (int32_t)observerConfig_.gridXOffset - (gridWidth_ - 1) / 2; - partiallyObservableGrid.right = (int32_t)avatarLocation.x - (int32_t)observerConfig_.gridXOffset + (gridWidth_ - 1) / 2; - partiallyObservableGrid.bottom = (int32_t)avatarLocation.y - (int32_t)observerConfig_.gridYOffset - (gridHeight_ - 1) / 2; - partiallyObservableGrid.top = (int32_t)avatarLocation.y - (int32_t)observerConfig_.gridYOffset + (gridHeight_ - 1) / 2; + partiallyObservableGrid.left = avatarLocation.x - observerConfig_.gridXOffset - (gridWidth_ - 1) / 2; + partiallyObservableGrid.right = avatarLocation.x - observerConfig_.gridXOffset + (gridWidth_ - 1) / 2; + partiallyObservableGrid.bottom = avatarLocation.y - observerConfig_.gridYOffset - (gridHeight_ - 1) / 2; + partiallyObservableGrid.top = avatarLocation.y - observerConfig_.gridYOffset + (gridHeight_ - 1) / 2; break; case Direction::RIGHT: - partiallyObservableGrid.left = (int32_t)avatarLocation.x + (int32_t)observerConfig_.gridYOffset - (gridHeight_ - 1) / 2; - partiallyObservableGrid.right = (int32_t)avatarLocation.x + (int32_t)observerConfig_.gridYOffset + (gridHeight_ - 1) / 2; - partiallyObservableGrid.bottom = (int32_t)avatarLocation.y + (int32_t)observerConfig_.gridXOffset - (gridWidth_ - 1) / 2; - partiallyObservableGrid.top = (int32_t)avatarLocation.y + (int32_t)observerConfig_.gridXOffset + (gridWidth_ - 1) / 2; + partiallyObservableGrid.left = avatarLocation.x + observerConfig_.gridYOffset - (gridHeight_ - 1) / 2; + partiallyObservableGrid.right = avatarLocation.x + observerConfig_.gridYOffset + (gridHeight_ - 1) / 2; + partiallyObservableGrid.bottom = avatarLocation.y + observerConfig_.gridXOffset - (gridWidth_ - 1) / 2; + partiallyObservableGrid.top = avatarLocation.y + observerConfig_.gridXOffset + (gridWidth_ - 1) / 2; break; case Direction::DOWN: - partiallyObservableGrid.left = (int32_t)avatarLocation.x + (int32_t)observerConfig_.gridXOffset - (gridWidth_ - 1) / 2; - partiallyObservableGrid.right = (int32_t)avatarLocation.x + (int32_t)observerConfig_.gridXOffset + (gridWidth_ - 1) / 2; - partiallyObservableGrid.bottom = (int32_t)avatarLocation.y + (int32_t)observerConfig_.gridYOffset - (gridHeight_ - 1) / 2; - partiallyObservableGrid.top = (int32_t)avatarLocation.y + (int32_t)observerConfig_.gridYOffset + (gridHeight_ - 1) / 2; + partiallyObservableGrid.left = avatarLocation.x + observerConfig_.gridXOffset - (gridWidth_ - 1) / 2; + partiallyObservableGrid.right = avatarLocation.x + observerConfig_.gridXOffset + (gridWidth_ - 1) / 2; + partiallyObservableGrid.bottom = avatarLocation.y + observerConfig_.gridYOffset - (gridHeight_ - 1) / 2; + partiallyObservableGrid.top = avatarLocation.y + observerConfig_.gridYOffset + (gridHeight_ - 1) / 2; break; case Direction::LEFT: - partiallyObservableGrid.left = (int32_t)avatarLocation.x - (int32_t)observerConfig_.gridYOffset - (gridHeight_ - 1) / 2; - partiallyObservableGrid.right = (int32_t)avatarLocation.x - (int32_t)observerConfig_.gridYOffset + (gridHeight_ - 1) / 2; - partiallyObservableGrid.bottom = (int32_t)avatarLocation.y - (int32_t)observerConfig_.gridXOffset - (gridWidth_ - 1) / 2; - partiallyObservableGrid.top = (int32_t)avatarLocation.y - (int32_t)observerConfig_.gridXOffset + (gridWidth_ - 1) / 2; + partiallyObservableGrid.left = avatarLocation.x - observerConfig_.gridYOffset - (gridHeight_ - 1) / 2; + partiallyObservableGrid.right = avatarLocation.x - observerConfig_.gridYOffset + (gridHeight_ - 1) / 2; + partiallyObservableGrid.bottom = avatarLocation.y - observerConfig_.gridXOffset - (gridWidth_ - 1) / 2; + partiallyObservableGrid.top = avatarLocation.y - observerConfig_.gridXOffset + (gridWidth_ - 1) / 2; break; } diff --git a/src/Griddly/Core/Observers/Observer.hpp b/src/Griddly/Core/Observers/Observer.hpp index f03af2a3d..e34eede1b 100644 --- a/src/Griddly/Core/Observers/Observer.hpp +++ b/src/Griddly/Core/Observers/Observer.hpp @@ -16,7 +16,6 @@ struct ObserverConfig { uint32_t playerCount = 1; glm::ivec2 tileSize = {24, 24}; - // Config for VECTOR observers only bool includeVariables = false; bool includeRotation = false; @@ -48,7 +47,10 @@ enum class ObserverType { NONE, ASCII }; enum class ObserverState { - NONE, INITIALISED, RESET, READY + NONE, + INITIALISED, + RESET, + READY }; class Observer { @@ -61,7 +63,7 @@ class Observer { */ virtual uint8_t* update() = 0; virtual void reset(); - + virtual std::vector getShape() const; virtual std::vector getStrides() const; diff --git a/src/Griddly/Core/Observers/SpriteObserver.cpp b/src/Griddly/Core/Observers/SpriteObserver.cpp index 7e19a25fd..39f121c27 100644 --- a/src/Griddly/Core/Observers/SpriteObserver.cpp +++ b/src/Griddly/Core/Observers/SpriteObserver.cpp @@ -36,7 +36,7 @@ vk::SpriteData SpriteObserver::loadImage(std::string imageFilename) { stbi_uc* pixels = stbi_load(absoluteFilePath.c_str(), &width, &height, &channels, STBI_rgb_alpha); if (!pixels) { - throw std::runtime_error(fmt::format("Failed to load texture image {0}.",imageFilename)); + throw std::runtime_error(fmt::format("Failed to load texture image {0}.", imageFilename)); } int outputWidth = observerConfig_.tileSize.x; diff --git a/src/Griddly/Core/Observers/VectorObserver.cpp b/src/Griddly/Core/Observers/VectorObserver.cpp index 5ecf1becc..55accaa94 100644 --- a/src/Griddly/Core/Observers/VectorObserver.cpp +++ b/src/Griddly/Core/Observers/VectorObserver.cpp @@ -36,26 +36,26 @@ void VectorObserver::resetShape() { gridBoundary_.x = grid_->getWidth(); gridBoundary_.y = grid_->getHeight(); - observationChannels_ = grid_->getObjectIds().size(); + observationChannels_ = static_cast(grid_->getObjectIds().size()); // Always in order objects, player, orientation, variables. if (observerConfig_.includePlayerId) { channelsBeforePlayerCount_ = observationChannels_; observationChannels_ += observerConfig_.playerCount + 1; // additional one-hot for "no-player" - spdlog::debug("Adding {0} playerId channels at: {1}", observationChannels_-channelsBeforePlayerCount_, channelsBeforePlayerCount_); + spdlog::debug("Adding {0} playerId channels at: {1}", observationChannels_ - channelsBeforePlayerCount_, channelsBeforePlayerCount_); } if (observerConfig_.includeRotation) { channelsBeforeRotation_ = observationChannels_; observationChannels_ += 4; - spdlog::debug("Adding {0} rotation channels at: {1}", observationChannels_-channelsBeforeRotation_, channelsBeforeRotation_); + spdlog::debug("Adding {0} rotation channels at: {1}", observationChannels_ - channelsBeforeRotation_, channelsBeforeRotation_); } if (observerConfig_.includeVariables) { channelsBeforeVariables_ = observationChannels_; - observationChannels_ += grid_->getObjectVariableIds().size(); - spdlog::debug("Adding {0} variable channels at: {1}", observationChannels_-channelsBeforeVariables_, channelsBeforeVariables_); + observationChannels_ += static_cast(grid_->getObjectVariableIds().size()); + spdlog::debug("Adding {0} variable channels at: {1}", observationChannels_ - channelsBeforeVariables_, channelsBeforeVariables_); } observationShape_ = {observationChannels_, gridWidth_, gridHeight_}; @@ -111,12 +111,16 @@ void VectorObserver::renderLocation(glm::ivec2 objectLocation, glm::ivec2 output case Direction::UP: case Direction::NONE: directionIdx = 0; + break; case Direction::RIGHT: directionIdx = 1; + break; case Direction::DOWN: directionIdx = 2; + break; case Direction::LEFT: directionIdx = 3; + break; } auto orientationMemPtr = memPtr + channelsBeforeRotation_ + directionIdx; *orientationMemPtr = 1; @@ -134,8 +138,7 @@ void VectorObserver::renderLocation(glm::ivec2 objectLocation, glm::ivec2 output auto variableMemPtr = memPtr + channelsBeforeVariables_ + variableIdx; *variableMemPtr = variableValue; - - } + } } } @@ -146,13 +149,12 @@ void VectorObserver::renderLocation(glm::ivec2 objectLocation, glm::ivec2 output uint8_t* VectorObserver::update() { spdlog::debug("Vector renderer updating."); - + if (observerState_ != ObserverState::READY) { throw std::runtime_error("Observer not ready, must be initialized and reset before update() can be called."); } if (trackAvatar_) { - spdlog::debug("Tracking Avatar."); auto avatarLocation = avatarObject_->getLocation(); diff --git a/src/Griddly/Core/Observers/VectorObserver.hpp b/src/Griddly/Core/Observers/VectorObserver.hpp index 9378e47ee..781e17576 100644 --- a/src/Griddly/Core/Observers/VectorObserver.hpp +++ b/src/Griddly/Core/Observers/VectorObserver.hpp @@ -20,7 +20,7 @@ class VectorObserver : public Observer { void print(std::shared_ptr observation) override; protected: - void renderLocation(glm::ivec2 objectLocation, glm::ivec2 outputLocation, bool resetLocation=false) const; + void renderLocation(glm::ivec2 objectLocation, glm::ivec2 outputLocation, bool resetLocation = false) const; private: std::shared_ptr observation_; diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanConfiguration.hpp b/src/Griddly/Core/Observers/Vulkan/VulkanConfiguration.hpp index 21f2dd2d1..afd69e1d5 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanConfiguration.hpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanConfiguration.hpp @@ -9,4 +9,4 @@ struct VulkanConfiguration { uint32_t engineVersion = VK_MAKE_VERSION(0, 0, 0); uint32_t apiVersion = VK_API_VERSION_1_0; }; -} \ No newline at end of file +} // namespace vk \ No newline at end of file diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanDevice.cpp b/src/Griddly/Core/Observers/Vulkan/VulkanDevice.cpp index 8356c10cf..57c8d0c08 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanDevice.cpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanDevice.cpp @@ -194,7 +194,7 @@ std::vector VulkanDevice::resetRenderSurface(uint32_t pixelWidth, uint break; } - spdlog::debug("Render Surface Strides ({0}, {1}, {2}).", imageStrides[0],imageStrides[1],imageStrides[2]); + spdlog::debug("Render Surface Strides ({0}, {1}, {2}).", imageStrides[0], imageStrides[1], imageStrides[2]); return imageStrides; } diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanDevice.hpp b/src/Griddly/Core/Observers/Vulkan/VulkanDevice.hpp index cfe9d5575..899c56cef 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanDevice.hpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanDevice.hpp @@ -17,8 +17,8 @@ class VulkanPhysicalDeviceInfo; class VulkanQueueFamilyIndices; enum DeviceSelectionOrder { - DRIVER_ENUMERATION, // the order that the devices are returned from the driver (default) - PCI_BUS_ID // order by the PCI bus Id ascending + DRIVER_ENUMERATION, // the order that the devices are returned from the driver (default) + PCI_BUS_ID // order by the PCI bus Id ascending }; struct DeviceSelection { @@ -106,7 +106,7 @@ class VulkanDevice { void drawShapeWithOutline(VulkanRenderContext& renderContext, ShapeBuffer shapeBuffer, glm::mat4 model, glm::vec4 color, glm::vec4 outlineColor); uint32_t getSpriteArrayLayer(std::string spriteName); - void drawSprite(VulkanRenderContext& renderContext, uint32_t arrayLayer, glm::mat4 model, glm::vec4 color, glm::vec4 outlineColor={0,0,0,0}); + void drawSprite(VulkanRenderContext& renderContext, uint32_t arrayLayer, glm::mat4 model, glm::vec4 color, glm::vec4 outlineColor = {0, 0, 0, 0}); void drawBackgroundTiling(VulkanRenderContext& renderContext, uint32_t arrayLayer); uint8_t* endRender(VulkanRenderContext& renderContext, std::vector dirtyRectangles); diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanInitializers.hpp b/src/Griddly/Core/Observers/Vulkan/VulkanInitializers.hpp index 8f0fa40dd..2d2e04a74 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanInitializers.hpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanInitializers.hpp @@ -133,7 +133,7 @@ inline VkMemoryBarrier memoryBarrier() { return memoryBarrier; } -inline VkImageCreateInfo imageCreateInfo(uint32_t width, uint32_t height, uint32_t arrayLayers, VkFormat& format, VkImageTiling& tiling, VkImageUsageFlags usageFlags, VkImageLayout initialLayout=VK_IMAGE_LAYOUT_UNDEFINED) { +inline VkImageCreateInfo imageCreateInfo(uint32_t width, uint32_t height, uint32_t arrayLayers, VkFormat& format, VkImageTiling& tiling, VkImageUsageFlags usageFlags, VkImageLayout initialLayout = VK_IMAGE_LAYOUT_UNDEFINED) { VkImageCreateInfo imageCreateInfo{}; imageCreateInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanInstance.hpp b/src/Griddly/Core/Observers/Vulkan/VulkanInstance.hpp index 14a593f84..b7cbbd046 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanInstance.hpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanInstance.hpp @@ -1,5 +1,6 @@ #pragma once #include + #include #include "VulkanConfiguration.hpp" diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanObserver.cpp b/src/Griddly/Core/Observers/Vulkan/VulkanObserver.cpp index 7945e4a00..0563a47ae 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanObserver.cpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanObserver.cpp @@ -25,15 +25,14 @@ VulkanObserver::~VulkanObserver() { * This a) allows significantly more enviroments to be loaded (if only one of them is being used to create videos) and b) */ void VulkanObserver::lazyInit() { - if (observerState_ != ObserverState::RESET) { throw std::runtime_error("Cannot initialize Vulkan Observer when it is not in RESET state."); } spdlog::debug("Vulkan lazy initialization...."); - + gridBoundary_ = glm::ivec2(grid_->getWidth(), grid_->getHeight()); - + auto imagePath = resourceConfig_.imagePath; auto shaderPath = resourceConfig_.shaderPath; @@ -53,7 +52,7 @@ void VulkanObserver::lazyInit() { void VulkanObserver::reset() { Observer::reset(); - if(observerState_ == ObserverState::READY) { + if (observerState_ == ObserverState::READY) { resetRenderSurface(); } } @@ -62,26 +61,20 @@ uint8_t* VulkanObserver::update() { if (observerState_ == ObserverState::RESET) { lazyInit(); resetRenderSurface(); - } else if(observerState_ != ObserverState::READY) { + } else if (observerState_ != ObserverState::READY) { throw std::runtime_error("Observer is not in READY state, cannot render"); } - + auto ctx = device_->beginRender(); render(ctx); - std::vector dirtyRectangles; - // Optimize this in the future, partial observation is slower for the moment if (avatarObject_ != nullptr) { - std::vector dirtyRectangles = { - {{0, 0}, - {pixelWidth_, pixelHeight_}}}; - - return device_->endRender(ctx, dirtyRectangles); + return device_->endRender(ctx, std::vector{{{0, 0}, {pixelWidth_, pixelHeight_}}}); } - dirtyRectangles = calculateDirtyRectangles(grid_->getUpdatedLocations(observerConfig_.playerId)); + auto dirtyRectangles = calculateDirtyRectangles(grid_->getUpdatedLocations(observerConfig_.playerId)); grid_->purgeUpdatedLocations(observerConfig_.playerId); diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanObserver.hpp b/src/Griddly/Core/Observers/Vulkan/VulkanObserver.hpp index be9687058..04ecaa629 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanObserver.hpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanObserver.hpp @@ -33,10 +33,10 @@ class VulkanObserver : public Observer { protected: virtual void render(vk::VulkanRenderContext& ctx) const = 0; - + void resetRenderSurface(); virtual std::vector calculateDirtyRectangles(std::unordered_set updatedLocations) const = 0; - + std::unique_ptr device_; ResourceConfig resourceConfig_; diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanPhysicalDeviceInfo.hpp b/src/Griddly/Core/Observers/Vulkan/VulkanPhysicalDeviceInfo.hpp index da65e572f..150c4365e 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanPhysicalDeviceInfo.hpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanPhysicalDeviceInfo.hpp @@ -1,15 +1,17 @@ #include + #include + #include "VulkanQueueFamilyIndices.hpp" namespace vk { struct VulkanPhysicalDeviceInfo { - VkPhysicalDevice physicalDevice; - std::string deviceName; - bool isGpu; - bool isSupported; - uint8_t gpuIdx; - uint8_t pciBusId; - VulkanQueueFamilyIndices queueFamilyIndices; + VkPhysicalDevice physicalDevice; + std::string deviceName; + bool isGpu; + bool isSupported; + uint8_t gpuIdx; + uint8_t pciBusId; + VulkanQueueFamilyIndices queueFamilyIndices; }; } // namespace vk \ No newline at end of file diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanQueueFamilyIndices.hpp b/src/Griddly/Core/Observers/Vulkan/VulkanQueueFamilyIndices.hpp index 8d0405451..fe62d43f6 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanQueueFamilyIndices.hpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanQueueFamilyIndices.hpp @@ -3,8 +3,8 @@ #include namespace vk { - struct VulkanQueueFamilyIndices { - uint32_t graphicsIndices = UINT32_MAX; - uint32_t computeIndices = UINT32_MAX; - }; -} \ No newline at end of file +struct VulkanQueueFamilyIndices { + uint32_t graphicsIndices = UINT32_MAX; + uint32_t computeIndices = UINT32_MAX; +}; +} // namespace vk \ No newline at end of file diff --git a/src/Griddly/Core/Observers/Vulkan/VulkanUtil.hpp b/src/Griddly/Core/Observers/Vulkan/VulkanUtil.hpp index c784ad74b..25cae83e6 100644 --- a/src/Griddly/Core/Observers/Vulkan/VulkanUtil.hpp +++ b/src/Griddly/Core/Observers/Vulkan/VulkanUtil.hpp @@ -1,13 +1,14 @@ #pragma once #include #include + #include #include namespace vk { inline void vk_check(VkResult res) { #ifndef NDEBUG - if(res != VK_SUCCESS) { + if (res != VK_SUCCESS) { spdlog::error("BAD VK Result{0}", res); } assert(("Vulkan command did not execute correctly", res == VK_SUCCESS)); diff --git a/src/Griddly/Core/Observers/VulkanGridObserver.cpp b/src/Griddly/Core/Observers/VulkanGridObserver.cpp index aaf20a366..fab87a96b 100644 --- a/src/Griddly/Core/Observers/VulkanGridObserver.cpp +++ b/src/Griddly/Core/Observers/VulkanGridObserver.cpp @@ -16,7 +16,6 @@ VulkanGridObserver::~VulkanGridObserver() { } void VulkanGridObserver::resetShape() { - spdlog::debug("Resetting grid observer shape."); gridWidth_ = observerConfig_.overrideGridWidth > 0 ? observerConfig_.overrideGridWidth : grid_->getWidth(); @@ -64,13 +63,12 @@ std::vector VulkanGridObserver::calculateDirtyRectangles(std::unordere } VkOffset2D offset = { - std::max(0, (int32_t)location.x * tileSize.x), - std::max(0, (int32_t)location.y * tileSize.y)}; + std::max(0, location.x * tileSize.x), + std::max(0, location.y * tileSize.y)}; VkExtent2D extent = { - (uint32_t)tileSize.x, - (uint32_t)tileSize.y - }; + static_cast(tileSize.x), + static_cast(tileSize.y)}; dirtyRectangles.push_back({offset, extent}); } @@ -80,7 +78,7 @@ std::vector VulkanGridObserver::calculateDirtyRectangles(std::unordere void VulkanGridObserver::render(vk::VulkanRenderContext& ctx) const { auto tileSize = observerConfig_.tileSize; - auto tileOffset = (glm::vec2)tileSize / 2.0f; + auto tileOffset = static_cast(tileSize) / 2.0f; // Just change the viewport of the renderer to point at the correct place if (avatarObject_ != nullptr) { auto avatarLocation = avatarObject_->getLocation(); diff --git a/src/Griddly/Core/Observers/VulkanGridObserver.hpp b/src/Griddly/Core/Observers/VulkanGridObserver.hpp index 7af6e0999..8d0871fa7 100644 --- a/src/Griddly/Core/Observers/VulkanGridObserver.hpp +++ b/src/Griddly/Core/Observers/VulkanGridObserver.hpp @@ -13,7 +13,6 @@ class VulkanGridObserver : public VulkanObserver { void init(ObserverConfig observerConfig) override; - protected: virtual void renderLocation(vk::VulkanRenderContext& ctx, glm::ivec2 objectLocation, glm::ivec2 outputLocation, glm::ivec2 tileOffset, DiscreteOrientation renderOrientation) const = 0; virtual void render(vk::VulkanRenderContext& ctx) const; diff --git a/src/Griddly/Core/PathFinder.cpp b/src/Griddly/Core/PathFinder.cpp index 5751eec96..059a493f5 100644 --- a/src/Griddly/Core/PathFinder.cpp +++ b/src/Griddly/Core/PathFinder.cpp @@ -1,11 +1,10 @@ #include "PathFinder.hpp" + #include "Grid.hpp" namespace griddly { -PathFinder::PathFinder(std::shared_ptr grid, std::set impassableObjects) : - grid_(grid), impassableObjects_(impassableObjects) -{ +PathFinder::PathFinder(std::shared_ptr grid, std::set impassableObjects) : grid_(grid), impassableObjects_(impassableObjects) { } } // namespace griddly \ No newline at end of file diff --git a/src/Griddly/Core/PathFinder.hpp b/src/Griddly/Core/PathFinder.hpp index fc7310139..d2fed4fe8 100644 --- a/src/Griddly/Core/PathFinder.hpp +++ b/src/Griddly/Core/PathFinder.hpp @@ -16,6 +16,7 @@ struct SearchOutput { class PathFinder { public: PathFinder(std::shared_ptr grid, std::set impassableObjects); + virtual ~PathFinder() = default; virtual SearchOutput search(glm::ivec2 startLocation, glm::ivec2 endLocation, glm::ivec2 startOrientationVector, uint32_t maxDepth) = 0; diff --git a/src/Griddly/Core/Players/Player.hpp b/src/Griddly/Core/Players/Player.hpp index 48b2a559b..18c426621 100644 --- a/src/Griddly/Core/Players/Player.hpp +++ b/src/Griddly/Core/Players/Player.hpp @@ -16,8 +16,8 @@ struct ActionResult; struct PlayerObserverDefinition { uint32_t gridWidth = 0; uint32_t gridHeight = 0; - uint32_t gridXOffset = 0; - uint32_t gridYOffset = 0; + int32_t gridXOffset = 0; + int32_t gridYOffset = 0; bool trackAvatar = false; bool rotateWithAvatar = false; uint32_t playerCount; @@ -28,7 +28,7 @@ class Player { public: Player(uint32_t id, std::string playerName, std::shared_ptr observer); - virtual ActionResult performActions(std::vector> actions, bool updateTicks=true); + virtual ActionResult performActions(std::vector> actions, bool updateTicks = true); virtual void init(ObserverConfig observerConfig, bool trackAvatar, std::shared_ptr gameProcess); virtual void reset(); diff --git a/src/Griddly/Core/SpatialHashCollisionDetector.cpp b/src/Griddly/Core/SpatialHashCollisionDetector.cpp index 497bcff6e..91683aaa5 100644 --- a/src/Griddly/Core/SpatialHashCollisionDetector.cpp +++ b/src/Griddly/Core/SpatialHashCollisionDetector.cpp @@ -1,6 +1,7 @@ -#include #include "SpatialHashCollisionDetector.hpp" +#include + namespace griddly { SpatialHashCollisionDetector::SpatialHashCollisionDetector(uint32_t gridWidth, uint32_t gridHeight, uint32_t cellSize, uint32_t range, TriggerType triggerType) @@ -41,19 +42,18 @@ bool SpatialHashCollisionDetector::remove(std::shared_ptr object) { } SearchResult SpatialHashCollisionDetector::search(glm::ivec2 location) { - auto top = std::min(gridHeight_, location.y + range_); - auto bottom = std::max(0, location.y - (int32_t)range_); - + auto bottom = std::max(0, location.y - static_cast(range_)); + auto right = std::min(gridWidth_, location.x + range_); - auto left = std::max(0, location.x - (int32_t)range_); + auto left = std::max(0, location.x - static_cast(range_)); auto bottomLeft = calculateHash(glm::ivec2(left, bottom)); auto topRight = calculateHash(glm::ivec2(right, top)); std::vector hashes; - for(uint32_t hashy = bottomLeft.y; hashy <= topRight.y; hashy++) { - for(uint32_t hashx = bottomLeft.x; hashx <= topRight.x; hashx++) { + for (uint32_t hashy = bottomLeft.y; hashy <= topRight.y; hashy++) { + for (uint32_t hashx = bottomLeft.x; hashx <= topRight.x; hashx++) { hashes.push_back({hashx, hashy}); } } @@ -77,8 +77,7 @@ SearchResult SpatialHashCollisionDetector::search(glm::ivec2 location) { closestObjects.push_back(object); } } - } - break; + } break; case TriggerType::RANGE_BOX_AREA: { for (auto object : objectSet) { auto collisionLocation = object->getLocation(); @@ -88,11 +87,10 @@ SearchResult SpatialHashCollisionDetector::search(glm::ivec2 location) { closestObjects.push_back(object); } } - } - break; + } break; case TriggerType::NONE: - throw std::invalid_argument("Misconfigured collision detector!, specify 'RANGE_BOX_BOUNDARY' or 'RANGE_BOX_AREA' in configuration"); - break; + throw std::invalid_argument("Misconfigured collision detector!, specify 'RANGE_BOX_BOUNDARY' or 'RANGE_BOX_AREA' in configuration"); + break; } } diff --git a/src/Griddly/Core/TurnBasedGameProcess.cpp b/src/Griddly/Core/TurnBasedGameProcess.cpp index c19c1b5c2..11a3d3f44 100644 --- a/src/Griddly/Core/TurnBasedGameProcess.cpp +++ b/src/Griddly/Core/TurnBasedGameProcess.cpp @@ -76,7 +76,7 @@ std::shared_ptr TurnBasedGameProcess::clone() { // Firstly create a new grid std::shared_ptr clonedGrid = std::shared_ptr(new Grid()); - clonedGrid->setPlayerCount(players_.size()); + clonedGrid->setPlayerCount(static_cast(players_.size())); auto gridHeight = grid_->getHeight(); auto gridWidth = grid_->getWidth(); @@ -116,16 +116,21 @@ std::shared_ptr TurnBasedGameProcess::clone() { clonedGrid->initObject(objectName, objectVariableNames); } + std::unordered_map, std::shared_ptr> clonedObjectMapping; + // Adding player default objects for (auto playerId = 0; playerId < players_.size() + 1; playerId++) { auto defaultObject = objectGenerator->newInstance("_empty", playerId, clonedGrid); clonedGrid->addPlayerDefaultObject(defaultObject); + + auto defaultObjectToCopy = grid_->getPlayerDefaultObject(playerId); + + clonedObjectMapping[defaultObjectToCopy] = defaultObject; } // Clone Objects spdlog::debug("Cloning objects..."); auto& objectsToCopy = grid_->getObjects(); - std::unordered_map, std::shared_ptr> clonedObjectMapping; for (const auto& toCopy : objectsToCopy) { auto clonedObject = objectGenerator->cloneInstance(toCopy, clonedGrid); clonedGrid->addObject(toCopy->getLocation(), clonedObject, false); @@ -154,17 +159,23 @@ std::shared_ptr TurnBasedGameProcess::clone() { auto orientationVector = actionToCopy->getOrientationVector(); auto sourceObjectMapping = actionToCopy->getSourceObject(); auto originatingPlayerId = actionToCopy->getOriginatingPlayerId(); + spdlog::debug("Copying action {0}", actionToCopy->getActionName()); - auto clonedActionSourceObject = clonedObjectMapping[sourceObjectMapping]; + auto clonedActionSourceObjectIt = clonedObjectMapping.find(sourceObjectMapping); - // Clone the action - auto clonedAction = std::shared_ptr(new Action(clonedGrid, actionName, originatingPlayerId, remainingTicks)); + if (clonedActionSourceObjectIt != clonedObjectMapping.end()) { + // Clone the action + auto clonedAction = std::shared_ptr(new Action(clonedGrid, actionName, originatingPlayerId, remainingTicks)); - // The orientation and vector to dest are already modified from the first action in respect - // to if this is a relative action, so relative is set to false here - clonedAction->init(clonedActionSourceObject, vectorToDest, orientationVector, false); + // The orientation and vector to dest are already modified from the first action in respect + // to if this is a relative action, so relative is set to false here + clonedAction->init(clonedActionSourceObjectIt->second, vectorToDest, orientationVector, false); - clonedGrid->performActions(playerId, {clonedAction}); + spdlog::debug("applying cloned action {0}", clonedAction->getActionName()); + clonedGrid->performActions(playerId, {clonedAction}); + } else { + spdlog::debug("Action cannot be cloned as it is invalid in original environment."); + } } spdlog::debug("Cloning game process..."); diff --git a/src/Griddly/Core/TurnBasedGameProcess.hpp b/src/Griddly/Core/TurnBasedGameProcess.hpp index 376f75916..8a9ce922e 100644 --- a/src/Griddly/Core/TurnBasedGameProcess.hpp +++ b/src/Griddly/Core/TurnBasedGameProcess.hpp @@ -14,7 +14,7 @@ class TurnBasedGameProcess : public GameProcess { TurnBasedGameProcess(ObserverType globalObserverType, std::shared_ptr gdyFactory, std::shared_ptr grid); ~TurnBasedGameProcess(); - virtual ActionResult performActions(uint32_t playerId, std::vector> actions, bool updateTicks=true) override; + virtual ActionResult performActions(uint32_t playerId, std::vector> actions, bool updateTicks = true) override; virtual std::string getProcessName() const override; diff --git a/src/Griddly/Core/Util/util.hpp b/src/Griddly/Core/Util/util.hpp index a7489c461..658642765 100644 --- a/src/Griddly/Core/Util/util.hpp +++ b/src/Griddly/Core/Util/util.hpp @@ -24,30 +24,30 @@ inline std::vector split(const std::string& s, char delim) { return elems; } -template, class P = std::less > -struct VectorPriorityQueue : std::priority_queue { - using std::priority_queue::priority_queue; - typename C::iterator begin() { return std::priority_queue::c.begin(); } - typename C::iterator end() { return std::priority_queue::c.end(); } +template , class P = std::less > +struct VectorPriorityQueue : std::priority_queue { + using std::priority_queue::priority_queue; + typename C::iterator begin() { return std::priority_queue::c.begin(); } + typename C::iterator end() { return std::priority_queue::c.end(); } }; inline void accumulateRewards(std::unordered_map& acc, std::unordered_map& values) { - for(auto valueIt : values) { + for (auto valueIt : values) { acc[valueIt.first] += valueIt.second; } } inline std::string generateRandomString(const int len) { - static const char alphanum[] = - "0123456789" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz"; - std::string tmp_s; - tmp_s.reserve(len); - - for (int i = 0; i < len; ++i) { - tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)]; - } - - return tmp_s; -} \ No newline at end of file + static const char alphanum[] = + "0123456789" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz"; + std::string tmp_s; + tmp_s.reserve(len); + + for (int i = 0; i < len; ++i) { + tmp_s += alphanum[rand() % (sizeof(alphanum) - 1)]; + } + + return tmp_s; +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 71fd42ec4..82d622aad 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -25,4 +25,4 @@ target_include_directories ( # Link against our built libraries -target_link_libraries(${BINARY} PUBLIC ${CMAKE_PROJECT_NAME} Vulkan::Vulkan yaml-cpp glm gmock_main) \ No newline at end of file +target_link_libraries(${BINARY} PUBLIC ${CMAKE_PROJECT_NAME} project_warnings Vulkan::Vulkan yaml-cpp glm gmock_main) \ No newline at end of file diff --git a/tests/src/Griddly/Core/AStarPathFinderTest.cpp b/tests/src/Griddly/Core/AStarPathFinderTest.cpp index 7c3da8453..6d49f5ac8 100644 --- a/tests/src/Griddly/Core/AStarPathFinderTest.cpp +++ b/tests/src/Griddly/Core/AStarPathFinderTest.cpp @@ -135,7 +135,7 @@ TEST(AStarPathFinderTest, searchRotationActions) { EXPECT_CALL(*mockGridPtr, getHeight).WillRepeatedly(Return(6)); EXPECT_CALL(*mockGridPtr, getWidth).WillRepeatedly(Return(6)); - auto up = pathFinder->search({0, 0}, {0, 5}, {1, 0}, 100); // Agent can rotate either way here to reach the goal. So to stop flakey tests, we rotate the agent so shortest path is specific. + auto up = pathFinder->search({0, 0}, {0, 5}, {1, 0}, 100); // Agent can rotate either way here to reach the goal. So to stop flakey tests, we rotate the agent so shortest path is specific. auto right = pathFinder->search({0, 0}, {5, 0}, {0, 0}, 100); auto down = pathFinder->search({0, 5}, {0, 0}, {0, 0}, 100); auto left = pathFinder->search({5, 0}, {0, 0}, {0, 0}, 100); @@ -146,4 +146,4 @@ TEST(AStarPathFinderTest, searchRotationActions) { ASSERT_EQ(left.actionId, 1); } -} // namespace griddly \ No newline at end of file +} // namespace griddly \ No newline at end of file diff --git a/tests/src/Griddly/Core/GDY/Objects/ObjectTest.cpp b/tests/src/Griddly/Core/GDY/Objects/ObjectTest.cpp index d0af6f930..a4ff3b237 100644 --- a/tests/src/Griddly/Core/GDY/Objects/ObjectTest.cpp +++ b/tests/src/Griddly/Core/GDY/Objects/ObjectTest.cpp @@ -13,12 +13,12 @@ using ::testing::_; using ::testing::ElementsAre; -using ::testing::UnorderedElementsAre; using ::testing::Eq; using ::testing::Invoke; using ::testing::Mock; using ::testing::Return; using ::testing::ReturnRef; +using ::testing::UnorderedElementsAre; namespace griddly { @@ -434,7 +434,7 @@ TEST(ObjectTest, command_reward) { } TEST(ObjectTest, command_reward_variable) { - auto srcObjectPtr = setupObject(1, "srcObject", {{"ten", _V(10)}}); + auto srcObjectPtr = setupObject(1, "srcObject", {{"ten", _V(10)}}); auto dstObjectPtr = setupObject(3, "dstObject", {{"minusten", _V(-10)}}); auto mockActionPtr = setupAction("action", srcObjectPtr, dstObjectPtr); @@ -447,7 +447,6 @@ TEST(ObjectTest, command_reward_variable) { verifyMocks(mockActionPtr); } - TEST(ObjectTest, command_reward_default_to_action_player_id) { auto srcObjectPtr = setupObject(0, "srcObject", {}); auto dstObjectPtr = setupObject(0, "dstObject", {}); @@ -1019,7 +1018,7 @@ TEST(ObjectTest, command_exec_search) { //* - exec: //* Action: exec_action //* Delay: 20 - //* Search: + //* Search: //* MaxDepth: 100 //* TargetObjectName: search_object //* Dst: @@ -1027,7 +1026,7 @@ TEST(ObjectTest, command_exec_search) { //* Commands: //* - exec: //* Action: exec_action - //* Search: + //* Search: //* TargetLocation: [6, 7] //* auto mockObjectGenerator = std::shared_ptr(new MockObjectGenerator()); @@ -1041,7 +1040,7 @@ TEST(ObjectTest, command_exec_search) { auto searchObjectPtr = setupObject(1, "search_object", glm::ivec2(5, 0), DiscreteOrientation(), {}, mockGridPtr, mockObjectGenerator); std::map> noObjects = {}; std::map> searchObjectList = {{0, searchObjectPtr}}; - + ON_CALL(*mockGridPtr, getObjectsAt(_)).WillByDefault(ReturnRef(noObjects)); EXPECT_CALL(*mockGridPtr, getObjectsAt(_)).WillRepeatedly(ReturnRef(noObjects)); EXPECT_CALL(*mockGridPtr, getObjectsAt(Eq(glm::ivec2(5, 0)))).WillRepeatedly(ReturnRef(searchObjectList)); @@ -1058,7 +1057,6 @@ TEST(ObjectTest, command_exec_search) { false}}}; auto invokeCollisionDetector = [this, searchObjectPtr](std::vector objectNames, std::string actionName, std::shared_ptr collisionDetector) -> void { - ASSERT_EQ(objectNames, std::vector({"search_object"})); collisionDetector->upsert(searchObjectPtr); }; @@ -1553,42 +1551,32 @@ TEST(ObjectTest, isValidActionDestinationLocationOutsideGrid) { } TEST(ObjectTest, getInitialActions) { - auto mockObjectGenerator = std::shared_ptr(new MockObjectGenerator()); std::string objectName = "objectName"; std::vector initialActionDefinitions = { - { - "action1Name", - 1, - 0, - false, - 1.0, - }, - { - "action2Name", - 1, - 0, - true, - 1.0, - } - }; - - std::unordered_map mockActionInputDefinitions = { { - "action1Name", - { - {{1, {{1,1}, {1,1}, "description1"}}} - } + "action1Name", + 1, + 0, + false, + 1.0, }, - { "action2Name", - { - {{2, {{2,2}, {2,2}, "description2"}}} - } - } - }; - + { + "action2Name", + 1, + 0, + true, + 1.0, + }}; + + std::unordered_map mockActionInputDefinitions = { + {"action1Name", + {{{1, {{1, 1}, {1, 1}, "description1"}}}}}, + {"action2Name", + {{{2, {{2, 2}, {2, 2}, "description2"}}}}}}; + EXPECT_CALL(*mockObjectGenerator, getActionInputDefinitions()).WillRepeatedly(Return(mockActionInputDefinitions)); auto object = std::shared_ptr(new Object(objectName, 'S', 0, 0, {}, mockObjectGenerator, nullptr)); @@ -1606,7 +1594,6 @@ TEST(ObjectTest, getInitialActions) { ASSERT_EQ(actions[1]->getOrientationVector(), glm::ivec2(2, 2)); EXPECT_TRUE(Mock::VerifyAndClearExpectations(mockObjectGenerator.get())); - } TEST(ObjectTest, getInitialActionsWithOriginatingAction) { @@ -1621,49 +1608,39 @@ TEST(ObjectTest, getInitialActionsWithOriginatingAction) { .WillRepeatedly(Return(originatingActionName)); EXPECT_CALL(*mockActionPtr, getSourceLocation()) - .WillRepeatedly(Return(glm::ivec2{3,3})); + .WillRepeatedly(Return(glm::ivec2{3, 3})); EXPECT_CALL(*mockActionPtr, getDestinationLocation()) - .WillRepeatedly(Return(glm::ivec2{4,4})); + .WillRepeatedly(Return(glm::ivec2{4, 4})); EXPECT_CALL(*mockActionPtr, getVectorToDest()) - .WillRepeatedly(Return(glm::ivec2{3,1})); + .WillRepeatedly(Return(glm::ivec2{3, 1})); EXPECT_CALL(*mockActionPtr, getOrientationVector()) - .WillRepeatedly(Return(glm::ivec2{1,5})); - + .WillRepeatedly(Return(glm::ivec2{1, 5})); std::vector initialActionDefinitions = { - { - "action1Name", - 0, - 0, - false, - 1.0, - }, - { - "action2Name", - 1, - 0, - true, - 1.0, - } - }; - - std::unordered_map mockActionInputDefinitions = { { - "action1Name", - { - {} - } + "action1Name", + 0, + 0, + false, + 1.0, }, - { "action2Name", - { - {{2, {{2,2}, {2,2}, "description2"}}} - } - } - }; - + { + "action2Name", + 1, + 0, + true, + 1.0, + }}; + + std::unordered_map mockActionInputDefinitions = { + {"action1Name", + {{}}}, + {"action2Name", + {{{2, {{2, 2}, {2, 2}, "description2"}}}}}}; + EXPECT_CALL(*mockObjectGenerator, getActionInputDefinitions()).WillRepeatedly(Return(mockActionInputDefinitions)); auto object = std::shared_ptr(new Object(objectName, 'S', 0, 0, {}, mockObjectGenerator, nullptr)); diff --git a/tests/src/Griddly/Core/GameProcessTest.cpp b/tests/src/Griddly/Core/GameProcessTest.cpp index 6cebfecc9..916f277f7 100644 --- a/tests/src/Griddly/Core/GameProcessTest.cpp +++ b/tests/src/Griddly/Core/GameProcessTest.cpp @@ -3,8 +3,8 @@ #include "Griddly/Core/TestUtils/common.hpp" #include "Griddly/Core/TurnBasedGameProcess.cpp" #include "Mocks/Griddly/Core/GDY/MockGDYFactory.hpp" -#include "Mocks/Griddly/Core/GDY/Objects/MockObjectGenerator.hpp" #include "Mocks/Griddly/Core/GDY/MockTerminationHandler.hpp" +#include "Mocks/Griddly/Core/GDY/Objects/MockObjectGenerator.hpp" #include "Mocks/Griddly/Core/LevelGenerators/MockLevelGenerator.hpp" #include "Mocks/Griddly/Core/MockGrid.hpp" #include "Mocks/Griddly/Core/Observers/MockObserver.hpp" @@ -772,7 +772,7 @@ TEST(GameProcessTest, performActionsDelayedReward) { ASSERT_EQ(gameProcessPtr->getAccumulatedRewards(1), 19); ASSERT_EQ(gameProcessPtr->getAccumulatedRewards(2), 3); ASSERT_EQ(gameProcessPtr->getAccumulatedRewards(5), 3); - + EXPECT_TRUE(Mock::VerifyAndClearExpectations(mockGridPtr.get())); EXPECT_TRUE(Mock::VerifyAndClearExpectations(mockPlayerPtr.get())); EXPECT_TRUE(Mock::VerifyAndClearExpectations(mockObserverPtr.get())); @@ -970,63 +970,61 @@ TEST(GameProcessTest, getState) { } TEST(GameProcessTest, clone) { - auto mockGridPtr = std::shared_ptr(new MockGrid()); - auto mockLevelGeneratorPtr = std::shared_ptr(new MockLevelGenerator()); - auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); - auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); - - auto globalVar = _V(5); - auto playerVar = _V(6); - - auto mockObject1 = mockObject("object1", 'a', 0, 0, {0, 1}, DiscreteOrientation(), {}, {{"global_var", globalVar}, {"test_param1", _V(20)}}); - auto mockObject2 = mockObject("object2", 'b', 1, 0, {4, 6}, DiscreteOrientation(), {}, {{"global_var", globalVar}, {"test_param2", _V(5)}}); - auto mockObject3 = mockObject("object3", 'c', 1, 0, {20, 13}, DiscreteOrientation(), {}, {{"global_var", globalVar}, {"test_param3", _V(12)}}); + auto mockGridPtr = std::shared_ptr(new MockGrid()); + auto mockLevelGeneratorPtr = std::shared_ptr(new MockLevelGenerator()); + auto mockObjectGeneratorPtr = std::shared_ptr(new MockObjectGenerator()); + auto mockGDYFactoryPtr = std::shared_ptr(new MockGDYFactory()); - auto clonedMockObject1 = mockObject("object1", 'a', 0, 0, {0, 1}, DiscreteOrientation(), {}, {{"global_var", globalVar}, {"test_param1", _V(20)}}); - auto clonedMockObject2 = mockObject("object2", 'b', 1, 0, {4, 6}, DiscreteOrientation(), {}, {{"global_var", globalVar}, {"test_param2", _V(5)}}); - auto clonedMockObject3 = mockObject("object3", 'c', 1, 0, {20, 13}, DiscreteOrientation(), {}, {{"global_var", globalVar}, {"test_param3", _V(12)}}); + auto globalVar = _V(5); + auto playerVar = _V(6); - auto mockPlayerDefaultObject = mockObject("_empty", ' ', 1, 0, {-1, -1}, DiscreteOrientation(), {}, {}); + auto mockObject1 = mockObject("object1", 'a', 0, 0, {0, 1}, DiscreteOrientation(), {}, {{"global_var", globalVar}, {"test_param1", _V(20)}}); + auto mockObject2 = mockObject("object2", 'b', 1, 0, {4, 6}, DiscreteOrientation(), {}, {{"global_var", globalVar}, {"test_param2", _V(5)}}); + auto mockObject3 = mockObject("object3", 'c', 1, 0, {20, 13}, DiscreteOrientation(), {}, {{"global_var", globalVar}, {"test_param3", _V(12)}}); - auto objects = std::unordered_set>{mockObject1, mockObject2, mockObject3}; + auto clonedMockObject1 = mockObject("object1", 'a', 0, 0, {0, 1}, DiscreteOrientation(), {}, {{"global_var", globalVar}, {"test_param1", _V(20)}}); + auto clonedMockObject2 = mockObject("object2", 'b', 1, 0, {4, 6}, DiscreteOrientation(), {}, {{"global_var", globalVar}, {"test_param2", _V(5)}}); + auto clonedMockObject3 = mockObject("object3", 'c', 1, 0, {20, 13}, DiscreteOrientation(), {}, {{"global_var", globalVar}, {"test_param3", _V(12)}}); - auto globalVariables = std::unordered_map>>{ - {"global_var", {{0, globalVar}}}, - {"player_var", {{1, playerVar}}}}; + auto mockPlayerDefaultObject = mockObject("_empty", ' ', 1, 0, {-1, -1}, DiscreteOrientation(), {}, {}); - EXPECT_CALL(*mockGridPtr, getWidth()).WillRepeatedly(Return(100)); - EXPECT_CALL(*mockGridPtr, getHeight()).WillRepeatedly(Return(100)); + auto objects = std::unordered_set>{mockObject1, mockObject2, mockObject3}; - EXPECT_CALL(*mockGridPtr, getObjects()) - .WillRepeatedly(ReturnRef(objects)); + auto globalVariables = std::unordered_map>>{ + {"global_var", {{0, globalVar}}}, + {"player_var", {{1, playerVar}}}}; - EXPECT_CALL(*mockGridPtr, getTickCount()) - .WillRepeatedly(Return(_V(10))); + EXPECT_CALL(*mockGridPtr, getWidth()).WillRepeatedly(Return(100)); + EXPECT_CALL(*mockGridPtr, getHeight()).WillRepeatedly(Return(100)); - EXPECT_CALL(*mockGridPtr, getGlobalVariables()) - .WillRepeatedly(ReturnRef(globalVariables)); + EXPECT_CALL(*mockGridPtr, getObjects()) + .WillRepeatedly(ReturnRef(objects)); - std::unordered_map> mockObjectDefinitions = { - {"object1", std::make_shared(ObjectDefinition{"object1", 'a'})}, - {"object2", std::make_shared(ObjectDefinition{"object2", 'b'})}, - {"object3", std::make_shared(ObjectDefinition{"object3", 'c'})}, - }; + EXPECT_CALL(*mockGridPtr, getTickCount()) + .WillRepeatedly(Return(_V(10))); - EXPECT_CALL(*mockObjectGeneratorPtr, getObjectDefinitions()).WillRepeatedly(Return(mockObjectDefinitions)); - EXPECT_CALL(*mockObjectGeneratorPtr, cloneInstance(Eq(mockObject1), _)).WillRepeatedly(Return(clonedMockObject1)); - EXPECT_CALL(*mockObjectGeneratorPtr, cloneInstance(Eq(mockObject2), _)).WillRepeatedly(Return(clonedMockObject2)); - EXPECT_CALL(*mockObjectGeneratorPtr, cloneInstance(Eq(mockObject3), _)).WillRepeatedly(Return(clonedMockObject3)); - EXPECT_CALL(*mockObjectGeneratorPtr, newInstance(Eq("_empty"), _, _)).WillRepeatedly(Return(mockPlayerDefaultObject)); + EXPECT_CALL(*mockGridPtr, getGlobalVariables()) + .WillRepeatedly(ReturnRef(globalVariables)); + std::unordered_map> mockObjectDefinitions = { + {"object1", std::make_shared(ObjectDefinition{"object1", 'a'})}, + {"object2", std::make_shared(ObjectDefinition{"object2", 'b'})}, + {"object3", std::make_shared(ObjectDefinition{"object3", 'c'})}, + }; - EXPECT_CALL(*mockGDYFactoryPtr, getObjectGenerator()).WillRepeatedly(Return(mockObjectGeneratorPtr)); + EXPECT_CALL(*mockObjectGeneratorPtr, getObjectDefinitions()).WillRepeatedly(Return(mockObjectDefinitions)); + EXPECT_CALL(*mockObjectGeneratorPtr, cloneInstance(Eq(mockObject1), _)).WillRepeatedly(Return(clonedMockObject1)); + EXPECT_CALL(*mockObjectGeneratorPtr, cloneInstance(Eq(mockObject2), _)).WillRepeatedly(Return(clonedMockObject2)); + EXPECT_CALL(*mockObjectGeneratorPtr, cloneInstance(Eq(mockObject3), _)).WillRepeatedly(Return(clonedMockObject3)); + EXPECT_CALL(*mockObjectGeneratorPtr, newInstance(Eq("_empty"), _, _)).WillRepeatedly(Return(mockPlayerDefaultObject)); + EXPECT_CALL(*mockGDYFactoryPtr, getObjectGenerator()).WillRepeatedly(Return(mockObjectGeneratorPtr)); - auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr)); + auto gameProcessPtr = std::shared_ptr(new TurnBasedGameProcess(ObserverType::NONE, mockGDYFactoryPtr, mockGridPtr)); - for(int i = 0; i<100; i++) { - auto clonedPtr = gameProcessPtr->clone(); - } + for (int i = 0; i < 100; i++) { + auto clonedPtr = gameProcessPtr->clone(); + } } } // namespace griddly \ No newline at end of file diff --git a/tests/src/Griddly/Core/GridTest.cpp b/tests/src/Griddly/Core/GridTest.cpp index b33186c55..23c347f83 100644 --- a/tests/src/Griddly/Core/GridTest.cpp +++ b/tests/src/Griddly/Core/GridTest.cpp @@ -8,6 +8,7 @@ #include "gmock/gmock.h" #include "gtest/gtest.h" +using ::testing::_; using ::testing::ContainerEq; using ::testing::ElementsAre; using ::testing::ElementsAreArray; @@ -15,7 +16,6 @@ using ::testing::Eq; using ::testing::Mock; using ::testing::Return; using ::testing::UnorderedElementsAre; -using ::testing::_; namespace griddly { @@ -885,7 +885,6 @@ TEST(GridTest, performActionTriggeredByCollision) { grid->addActionTrigger(actionName1, {{"object_1", "object_2", "object_3"}, {"object_1", "object_2", "object_3"}, TriggerType::RANGE_BOX_AREA, 2}); grid->addActionProbability(actionName1, 1.0); - auto mockObjectPtr1 = mockObject("object_1", '?', 1, 0, {1, 1}); auto mockObjectPtr2 = mockObject("object_2", '?', 1, 0, {2, 2}); auto mockObjectPtr3 = mockObject("object_3", '?', 1, 0, {3, 3}); @@ -916,13 +915,13 @@ TEST(GridTest, performActionTriggeredByCollision) { grid->addObject({3, 3}, mockObjectPtr3); EXPECT_CALL(*mockCollisionDetectorPtr1, search(Eq(glm::ivec2{1, 1}))) - .WillOnce(Return(SearchResult{{mockObjectPtr1, mockObjectPtr2, mockObjectPtr3},{}})); + .WillOnce(Return(SearchResult{{mockObjectPtr1, mockObjectPtr2, mockObjectPtr3}, {}})); EXPECT_CALL(*mockCollisionDetectorPtr1, search(Eq(glm::ivec2{2, 2}))) - .WillOnce(Return(SearchResult{{mockObjectPtr1, mockObjectPtr2, mockObjectPtr3},{}})); + .WillOnce(Return(SearchResult{{mockObjectPtr1, mockObjectPtr2, mockObjectPtr3}, {}})); EXPECT_CALL(*mockCollisionDetectorPtr1, search(Eq(glm::ivec2{3, 3}))) - .WillOnce(Return(SearchResult{{mockObjectPtr1, mockObjectPtr2, mockObjectPtr3},{}})); + .WillOnce(Return(SearchResult{{mockObjectPtr1, mockObjectPtr2, mockObjectPtr3}, {}})); auto rewards = grid->update(); @@ -930,8 +929,6 @@ TEST(GridTest, performActionTriggeredByCollision) { ASSERT_EQ(rewards[1], 4); ASSERT_EQ(rewards[2], 8); ASSERT_EQ(rewards[3], 12); - - } } // namespace griddly \ No newline at end of file diff --git a/tests/src/Griddly/Core/Observers/ASCIIObserverTest.cpp b/tests/src/Griddly/Core/Observers/ASCIIObserverTest.cpp index 2fca76b52..898731f07 100644 --- a/tests/src/Griddly/Core/Observers/ASCIIObserverTest.cpp +++ b/tests/src/Griddly/Core/Observers/ASCIIObserverTest.cpp @@ -487,11 +487,11 @@ TEST(ASCIIObserverTest, multiPlayer_Outline_Player1) { config.includePlayerId = true; uint8_t expectedData[5][5][4] = { - {{'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'A','1',' ',' '}, {'B','1',' ',' '}, {'C','1',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'A','2',' ',' '}, {'B','2',' ',' '}, {'C','2',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'A','3',' ',' '}, {'B','3',' ',' '}, {'C','3',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}}}; + {{'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'A', '1', ' ', ' '}, {'B', '1', ' ', ' '}, {'C', '1', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'A', '2', ' ', ' '}, {'B', '2', ' ', ' '}, {'C', '2', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'A', '3', ' ', ' '}, {'B', '3', ' ', ' '}, {'C', '3', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}}}; runASCIIObserverRTSTest(config, {4, 5, 5}, {1, 4, 4 * 5}, expectedData[0][0]); } @@ -504,11 +504,11 @@ TEST(ASCIIObserverTest, multiPlayer_Outline_Player2) { config.includePlayerId = true; uint8_t expectedData[5][5][4] = { - {{'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'A','2',' ',' '}, {'B','2',' ',' '}, {'C','2',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'A','1',' ',' '}, {'B','1',' ',' '}, {'C','1',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'A','3',' ',' '}, {'B','3',' ',' '}, {'C','3',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}}}; + {{'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'A', '2', ' ', ' '}, {'B', '2', ' ', ' '}, {'C', '2', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'A', '1', ' ', ' '}, {'B', '1', ' ', ' '}, {'C', '1', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'A', '3', ' ', ' '}, {'B', '3', ' ', ' '}, {'C', '3', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}}}; runASCIIObserverRTSTest(config, {4, 5, 5}, {1, 4, 4 * 5}, expectedData[0][0]); } @@ -521,11 +521,11 @@ TEST(ASCIIObserverTest, multiPlayer_Outline_Player3) { config.includePlayerId = true; uint8_t expectedData[5][5][4] = { - {{'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'A','2',' ',' '}, {'B','2',' ',' '}, {'C','2',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'A','3',' ',' '}, {'B','3',' ',' '}, {'C','3',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'A','1',' ',' '}, {'B','1',' ',' '}, {'C','1',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}}}; + {{'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'A', '2', ' ', ' '}, {'B', '2', ' ', ' '}, {'C', '2', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'A', '3', ' ', ' '}, {'B', '3', ' ', ' '}, {'C', '3', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'A', '1', ' ', ' '}, {'B', '1', ' ', ' '}, {'C', '1', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}}}; runASCIIObserverRTSTest(config, {4, 5, 5}, {1, 4, 4 * 5}, expectedData[0][0]); } @@ -538,11 +538,11 @@ TEST(ASCIIObserverTest, multiPlayer_Outline_Global) { config.includePlayerId = true; uint8_t expectedData[5][5][4] = { - {{'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'A','1',' ',' '}, {'B','1',' ',' '}, {'C','1',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'A','2',' ',' '}, {'B','2',' ',' '}, {'C','2',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'A','3',' ',' '}, {'B','3',' ',' '}, {'C','3',' ',' '}, {'W',' ',' ',' '}}, - {{'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}, {'W',' ',' ',' '}}}; + {{'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'A', '1', ' ', ' '}, {'B', '1', ' ', ' '}, {'C', '1', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'A', '2', ' ', ' '}, {'B', '2', ' ', ' '}, {'C', '2', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'A', '3', ' ', ' '}, {'B', '3', ' ', ' '}, {'C', '3', ' ', ' '}, {'W', ' ', ' ', ' '}}, + {{'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}, {'W', ' ', ' ', ' '}}}; runASCIIObserverRTSTest(config, {4, 5, 5}, {1, 4, 4 * 5}, expectedData[0][0]); } diff --git a/tests/src/Griddly/Core/Observers/BlockObserverTest.cpp b/tests/src/Griddly/Core/Observers/BlockObserverTest.cpp index 49b38fe64..85311f675 100644 --- a/tests/src/Griddly/Core/Observers/BlockObserverTest.cpp +++ b/tests/src/Griddly/Core/Observers/BlockObserverTest.cpp @@ -508,24 +508,22 @@ TEST(BlockObserverTest, reset) { blockObserver->init(observerConfig); - std::vector expectedObservationShape = {3, 100, 100}; + std::vector expectedObservationShape = {3, 100, 100}; std::vector expectedObservationStride = {1, 4, 4 * 100}; auto expectedImageData = loadExpectedImage("tests/resources/observer/block/defaultObserverConfig.png"); // Reset and update 100 times to make sure reset is stable - for(int x = 0; x<100; x++) { + for (int x = 0; x < 100; x++) { blockObserver->reset(); auto updateObservation = blockObserver->update(); - ASSERT_EQ(blockObserver->getShape(), expectedObservationShape); ASSERT_EQ(blockObserver->getStrides()[0], expectedObservationStride[0]); ASSERT_EQ(blockObserver->getStrides()[1], expectedObservationStride[1]); ASSERT_THAT(expectedImageData.get(), ObservationResultMatcher(blockObserver->getShape(), blockObserver->getStrides(), updateObservation)); - } size_t dataLength = 4 * blockObserver->getShape()[1] * blockObserver->getShape()[2]; @@ -533,6 +531,4 @@ TEST(BlockObserverTest, reset) { testEnvironment.verifyAndClearExpectations(); } - - } // namespace griddly \ No newline at end of file diff --git a/tests/src/Griddly/Core/Observers/ObserverRTSTestData.hpp b/tests/src/Griddly/Core/Observers/ObserverRTSTestData.hpp index 529062426..eb7a9d8e8 100644 --- a/tests/src/Griddly/Core/Observers/ObserverRTSTestData.hpp +++ b/tests/src/Griddly/Core/Observers/ObserverRTSTestData.hpp @@ -27,18 +27,18 @@ class ObserverRTSTestData { // 1 A3 B1 C2 1 // 1 1 1 1 1 - if(observerConfig.includeVariables) { - mockObjectWallPtr = mockObject("W", 'W', 0, 0, {0,0}, DiscreteOrientation(), {}, {}); - mockObjectA1Ptr = mockObject("A", 'A', 1, 0, {0,0}, DiscreteOrientation(), {}, {{"V1", _V(1)}, {"_ignored", _V(10)}}); - mockObjectA2Ptr = mockObject("A", 'A', 2, 0, {0,0}, DiscreteOrientation(), {}, {{"V2", _V(2)}, {"_ignored", _V(10)}}); - mockObjectA3Ptr = mockObject("A", 'A', 3, 0, {0,0}, DiscreteOrientation(), {}, {{"V3", _V(3)}, {"_ignored", _V(10)}}); - mockObjectB1Ptr = mockObject("B", 'B', 1, 0, {0,0}, DiscreteOrientation(), {}, {{"V1", _V(4)}, {"_ignored", _V(10)}}); - mockObjectB2Ptr = mockObject("B", 'B', 2, 0, {0,0}, DiscreteOrientation(), {}, {{"V2", _V(5)}, {"_ignored", _V(10)}}); - mockObjectB3Ptr = mockObject("B", 'B', 3, 0, {0,0}, DiscreteOrientation(), {}, {{"V3", _V(6)}, {"_ignored", _V(10)}}); - mockObjectC1Ptr = mockObject("C", 'C', 1, 0, {0,0}, DiscreteOrientation(), {}, {{"V1", _V(7)}, {"_ignored", _V(10)}}); - mockObjectC2Ptr = mockObject("C", 'C', 2, 0, {0,0}, DiscreteOrientation(), {}, {{"V2", _V(8)}, {"_ignored", _V(10)}}); - mockObjectC3Ptr = mockObject("C", 'C', 3, 0, {0,0}, DiscreteOrientation(), {}, {{"V3", _V(9)}, {"_ignored", _V(10)}}); - } else { + if (observerConfig.includeVariables) { + mockObjectWallPtr = mockObject("W", 'W', 0, 0, {0, 0}, DiscreteOrientation(), {}, {}); + mockObjectA1Ptr = mockObject("A", 'A', 1, 0, {0, 0}, DiscreteOrientation(), {}, {{"V1", _V(1)}, {"_ignored", _V(10)}}); + mockObjectA2Ptr = mockObject("A", 'A', 2, 0, {0, 0}, DiscreteOrientation(), {}, {{"V2", _V(2)}, {"_ignored", _V(10)}}); + mockObjectA3Ptr = mockObject("A", 'A', 3, 0, {0, 0}, DiscreteOrientation(), {}, {{"V3", _V(3)}, {"_ignored", _V(10)}}); + mockObjectB1Ptr = mockObject("B", 'B', 1, 0, {0, 0}, DiscreteOrientation(), {}, {{"V1", _V(4)}, {"_ignored", _V(10)}}); + mockObjectB2Ptr = mockObject("B", 'B', 2, 0, {0, 0}, DiscreteOrientation(), {}, {{"V2", _V(5)}, {"_ignored", _V(10)}}); + mockObjectB3Ptr = mockObject("B", 'B', 3, 0, {0, 0}, DiscreteOrientation(), {}, {{"V3", _V(6)}, {"_ignored", _V(10)}}); + mockObjectC1Ptr = mockObject("C", 'C', 1, 0, {0, 0}, DiscreteOrientation(), {}, {{"V1", _V(7)}, {"_ignored", _V(10)}}); + mockObjectC2Ptr = mockObject("C", 'C', 2, 0, {0, 0}, DiscreteOrientation(), {}, {{"V2", _V(8)}, {"_ignored", _V(10)}}); + mockObjectC3Ptr = mockObject("C", 'C', 3, 0, {0, 0}, DiscreteOrientation(), {}, {{"V3", _V(9)}, {"_ignored", _V(10)}}); + } else { mockObjectWallPtr = mockObject("W", 'W', 0); mockObjectA1Ptr = mockObject("A", 'A', 1); mockObjectA2Ptr = mockObject("A", 'A', 2); @@ -51,8 +51,6 @@ class ObserverRTSTestData { mockObjectC3Ptr = mockObject("C", 'C', 3); } - - mockRTSObjects = std::unordered_set>{ mockObjectWallPtr, mockObjectA1Ptr, @@ -131,23 +129,20 @@ class ObserverRTSTestData { return nullptr; } })); - } std::shared_ptr mockGridPtr; const std::unordered_map mockSinglePlayerObjectIds = { - {"W", 3}, - {"A", 0}, - {"B", 1}, - {"C", 2} - }; + {"W", 3}, + {"A", 0}, + {"B", 1}, + {"C", 2}}; const std::unordered_map mockObjectVariableIds = { - {"V1", 0}, - {"V2", 1}, - {"V3", 2} - }; + {"V1", 0}, + {"V2", 1}, + {"V3", 2}}; std::shared_ptr mockObjectWallPtr; std::shared_ptr mockObjectA1Ptr; @@ -196,4 +191,4 @@ class ObserverRTSTestData { } }; -} \ No newline at end of file +} // namespace griddly \ No newline at end of file diff --git a/tests/src/Griddly/Core/Observers/ObserverTestData.hpp b/tests/src/Griddly/Core/Observers/ObserverTestData.hpp index eed80024d..fee99b0ff 100644 --- a/tests/src/Griddly/Core/Observers/ObserverTestData.hpp +++ b/tests/src/Griddly/Core/Observers/ObserverTestData.hpp @@ -3,6 +3,7 @@ #include "gtest/gtest.h" using ::testing::AnyNumber; +using ::testing::AtLeast; using ::testing::ElementsAre; using ::testing::ElementsAreArray; using ::testing::Eq; @@ -11,7 +12,6 @@ using ::testing::Mock; using ::testing::Pair; using ::testing::Return; using ::testing::ReturnRef; -using ::testing::AtLeast; namespace griddly { @@ -76,8 +76,7 @@ class ObserverTestData { })); EXPECT_CALL(*mockGridPtr, getObject).WillRepeatedly(Invoke([this](glm::ivec2 location) -> const std::shared_ptr { - - if(mockSinglePlayerGridData.find(location) == mockSinglePlayerGridData.end()) { + if (mockSinglePlayerGridData.find(location) == mockSinglePlayerGridData.end()) { return nullptr; } @@ -104,11 +103,10 @@ class ObserverTestData { std::unordered_map mockSinglePlayerGridData; const std::unordered_map mockSinglePlayerObjectIds = { - {"avatar", 3}, - {"mo1", 0}, - {"mo2", 1}, - {"mo3", 2} - }; + {"avatar", 3}, + {"mo1", 0}, + {"mo2", 1}, + {"mo3", 2}}; const std::unordered_set mockSinglePlayerUpdatedLocations = { {0, 0}, diff --git a/tests/src/Griddly/Core/Observers/SpriteObserverTest.cpp b/tests/src/Griddly/Core/Observers/SpriteObserverTest.cpp index 08bb47388..c9ac99011 100644 --- a/tests/src/Griddly/Core/Observers/SpriteObserverTest.cpp +++ b/tests/src/Griddly/Core/Observers/SpriteObserverTest.cpp @@ -97,7 +97,7 @@ void runSpriteObserverRTSTest(ObserverConfig observerConfig, spriteObserver->reset(); auto updateObservation = spriteObserver->update(); - + ASSERT_EQ(spriteObserver->getTileSize(), glm::ivec2(50, 50)); ASSERT_EQ(spriteObserver->getShape(), expectedObservationShape); ASSERT_EQ(spriteObserver->getStrides()[0], expectedObservationStride[0]); @@ -513,7 +513,6 @@ TEST(SpriteObserverTest, multiPlayer_Outline_Global) { runSpriteObserverRTSTest(config, {3, 250, 250}, {1, 4, 4 * 250}, "tests/resources/observer/sprite/multiPlayer_Outline_Global.png"); } - TEST(SpriteObserverTest, reset) { ResourceConfig resourceConfig = {"resources/images", "resources/shaders"}; ObserverConfig observerConfig; @@ -527,24 +526,22 @@ TEST(SpriteObserverTest, reset) { spriteObserver->init(observerConfig); - std::vector expectedObservationShape = {3, 120, 120}; + std::vector expectedObservationShape = {3, 120, 120}; std::vector expectedObservationStride = {1, 4, 4 * 100}; auto expectedImageData = loadExpectedImage("tests/resources/observer/sprite/defaultObserverConfig.png"); // Reset and update 100 times to make sure reset is stable - for(int x = 0; x<100; x++) { + for (int x = 0; x < 100; x++) { spriteObserver->reset(); auto updateObservation = spriteObserver->update(); - ASSERT_EQ(spriteObserver->getShape(), expectedObservationShape); ASSERT_EQ(spriteObserver->getStrides()[0], expectedObservationStride[0]); ASSERT_EQ(spriteObserver->getStrides()[1], expectedObservationStride[1]); ASSERT_THAT(expectedImageData.get(), ObservationResultMatcher(spriteObserver->getShape(), spriteObserver->getStrides(), updateObservation)); - } size_t dataLength = 4 * spriteObserver->getShape()[1] * spriteObserver->getShape()[2]; @@ -552,7 +549,4 @@ TEST(SpriteObserverTest, reset) { testEnvironment.verifyAndClearExpectations(); } - - - } // namespace griddly \ No newline at end of file diff --git a/tests/src/Griddly/Core/Observers/VectorObserverTest.cpp b/tests/src/Griddly/Core/Observers/VectorObserverTest.cpp index 78fa01481..0e4e196d6 100644 --- a/tests/src/Griddly/Core/Observers/VectorObserverTest.cpp +++ b/tests/src/Griddly/Core/Observers/VectorObserverTest.cpp @@ -73,7 +73,6 @@ void runVectorObserverRTSTest(ObserverConfig observerConfig, ASSERT_EQ(vectorObserver->getStrides()[0], expectedObservationStride[0]); ASSERT_EQ(vectorObserver->getStrides()[1], expectedObservationStride[1]); - size_t dataLength = vectorObserver->getShape()[0] * vectorObserver->getShape()[1] * vectorObserver->getShape()[2]; auto updateObservationPointer = std::vector(updateObservation, updateObservation + dataLength); @@ -511,7 +510,6 @@ TEST(VectorObserverTest, multiPlayer_Outline_Player2) { {{0, 0, 0, 1, 1, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 0, 1}, {0, 1, 0, 0, 0, 0, 0, 1}, {0, 0, 1, 0, 0, 0, 0, 1}, {0, 0, 0, 1, 1, 0, 0, 0}}, {{0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}}}; - runVectorObserverRTSTest(config, {8, 5, 5}, {1, 8, 8 * 5}, expectedData[0][0]); } @@ -538,14 +536,14 @@ TEST(VectorObserverTest, multiPlayer_Outline_Global) { config.playerCount = 3; config.includePlayerId = true; - + uint8_t expectedData[5][5][8] = { {{0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}}, {{0, 0, 0, 1, 1, 0, 0, 0}, {1, 0, 0, 0, 0, 1, 0, 0}, {0, 1, 0, 0, 0, 1, 0, 0}, {0, 0, 1, 0, 0, 1, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}}, {{0, 0, 0, 1, 1, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 1, 0}, {0, 1, 0, 0, 0, 0, 1, 0}, {0, 0, 1, 0, 0, 0, 1, 0}, {0, 0, 0, 1, 1, 0, 0, 0}}, {{0, 0, 0, 1, 1, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 0, 1}, {0, 1, 0, 0, 0, 0, 0, 1}, {0, 0, 1, 0, 0, 0, 0, 1}, {0, 0, 0, 1, 1, 0, 0, 0}}, {{0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0}}}; - + runVectorObserverRTSTest(config, {8, 5, 5}, {1, 8, 8 * 5}, expectedData[0][0]); } @@ -556,14 +554,14 @@ TEST(VectorObserverTest, multiPlayer_PlusVariables_Player1) { config.includePlayerId = true; config.includeVariables = true; - + uint8_t expectedData[5][5][11] = { {{0, 0, 0, 1, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}}, {{0, 0, 0, 1, 1, 0, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0}, {0, 1, 0, 0, 0, 1, 0, 0, 4, 0, 0}, {0, 0, 1, 0, 0, 1, 0, 0, 7, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}}, {{0, 0, 0, 1, 1, 0, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 1, 0, 0, 2, 0}, {0, 1, 0, 0, 0, 0, 1, 0, 0, 5, 0}, {0, 0, 1, 0, 0, 0, 1, 0, 0, 8, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}}, {{0, 0, 0, 1, 1, 0, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 3}, {0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 6}, {0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 9}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}}, {{0, 0, 0, 1, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}}}; - + runVectorObserverRTSTest(config, {11, 5, 5}, {1, 11, 11 * 5}, expectedData[0][0]); } @@ -574,14 +572,14 @@ TEST(VectorObserverTest, multiPlayer_PlusVariables_Player2) { config.includePlayerId = true; config.includeVariables = true; - + uint8_t expectedData[5][5][11] = { {{0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}}, {{0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0}, {0, 1, 0, 0, 0, 0, 1, 0, 4, 0, 0}, {0, 0, 1, 0, 0, 0, 1, 0, 7, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}}, {{0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0}, {0, 1, 0, 0, 0, 1, 0, 0, 0, 5, 0}, {0, 0, 1, 0, 0, 1, 0, 0, 0, 8, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}}, {{0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 3}, {0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 6}, {0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 9}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}}, {{0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}}}; - + runVectorObserverRTSTest(config, {11, 5, 5}, {1, 11, 11 * 5}, expectedData[0][0]); } diff --git a/tests/src/Griddly/Core/Players/PlayerTest.cpp b/tests/src/Griddly/Core/Players/PlayerTest.cpp index 90cf965ae..78287fb10 100644 --- a/tests/src/Griddly/Core/Players/PlayerTest.cpp +++ b/tests/src/Griddly/Core/Players/PlayerTest.cpp @@ -1,18 +1,16 @@ -#include "gmock/gmock.h" -#include "gtest/gtest.h" - +#include "Griddly/Core/Players/Player.hpp" #include "Mocks/Griddly/Core/GDY/Actions/MockAction.hpp" #include "Mocks/Griddly/Core/MockGameProcess.hpp" -#include "Mocks/Griddly/Core/Observers/MockObserver.hpp" #include "Mocks/Griddly/Core/MockGrid.hpp" - -#include "Griddly/Core/Players/Player.hpp" +#include "Mocks/Griddly/Core/Observers/MockObserver.hpp" +#include "gmock/gmock.h" +#include "gtest/gtest.h" using ::testing::ByMove; +using ::testing::ElementsAre; using ::testing::Eq; using ::testing::Mock; using ::testing::Return; -using ::testing::ElementsAre; namespace griddly { @@ -31,7 +29,7 @@ TEST(PlayerTest, getIdAndName) { TEST(PlayerTest, performActions) { auto mockActionPtr = std::shared_ptr(new MockAction()); auto mockGameProcessPtr = std::shared_ptr(new MockGameProcess()); - + int playerId = 0; std::string name = "PlayerName"; auto player = std::shared_ptr(new Player(playerId, name, nullptr)); @@ -58,7 +56,7 @@ TEST(PlayerTest, performActions) { TEST(PlayerTest, performActions_terminated) { auto mockActionPtr = std::shared_ptr(new MockAction()); auto mockGameProcessPtr = std::shared_ptr(new MockGameProcess()); - + int playerId = 1; std::string name = "PlayerName"; auto player = std::shared_ptr(new Player(playerId, name, nullptr)); diff --git a/tests/src/Griddly/Core/TestUtils/common.hpp b/tests/src/Griddly/Core/TestUtils/common.hpp index 85aaf2b85..d512477cd 100644 --- a/tests/src/Griddly/Core/TestUtils/common.hpp +++ b/tests/src/Griddly/Core/TestUtils/common.hpp @@ -15,7 +15,7 @@ using ::testing::Return; namespace griddly { -std::shared_ptr static mockObject(std::string objectName = "object", char mapCharacter='?', uint32_t playerId = 1, uint32_t zidx = 0, glm::ivec2 location = {0, 0}, DiscreteOrientation orientation = DiscreteOrientation(), std::unordered_set availableActionNames = {}, std::unordered_map> availableVariables = {}) { +std::shared_ptr static mockObject(std::string objectName = "object", char mapCharacter = '?', uint32_t playerId = 1, uint32_t zidx = 0, glm::ivec2 location = {0, 0}, DiscreteOrientation orientation = DiscreteOrientation(), std::unordered_set availableActionNames = {}, std::unordered_map> availableVariables = {}) { auto mockObjectPtr = std::shared_ptr(new MockObject()); EXPECT_CALL(*mockObjectPtr, getPlayerId()).WillRepeatedly(Return(playerId)); diff --git a/tests/src/Mocks/Griddly/Core/GDY/MockGDYFactory.hpp b/tests/src/Mocks/Griddly/Core/GDY/MockGDYFactory.hpp index 5f1183887..3f09d92bc 100644 --- a/tests/src/Mocks/Griddly/Core/GDY/MockGDYFactory.hpp +++ b/tests/src/Mocks/Griddly/Core/GDY/MockGDYFactory.hpp @@ -7,9 +7,8 @@ namespace griddly { class MockGDYFactory : public GDYFactory { public: - MockGDYFactory() - : GDYFactory(nullptr, nullptr, {}) {} + : GDYFactory(nullptr, nullptr, {}) {} MOCK_METHOD(std::shared_ptr, getTerminationGenerator, (), (const)); MOCK_METHOD(std::shared_ptr, getLevelGenerator, (uint32_t), (const)); @@ -34,4 +33,4 @@ class MockGDYFactory : public GDYFactory { MOCK_METHOD(uint32_t, getPlayerCount, (), (const)); MOCK_METHOD(PlayerObserverDefinition, getPlayerObserverDefinition, (), (const)); }; -} \ No newline at end of file +} // namespace griddly \ No newline at end of file diff --git a/tests/src/Mocks/Griddly/Core/MockCollisionDetectorFactory.hpp b/tests/src/Mocks/Griddly/Core/MockCollisionDetectorFactory.hpp index 38bca4f26..468358dd1 100644 --- a/tests/src/Mocks/Griddly/Core/MockCollisionDetectorFactory.hpp +++ b/tests/src/Mocks/Griddly/Core/MockCollisionDetectorFactory.hpp @@ -9,4 +9,4 @@ class MockCollisionDetectorFactory : public CollisionDetectorFactory { MOCK_METHOD(std::shared_ptr, newCollisionDetector, (uint32_t gridHeight, uint32_t gridWidth, ActionTriggerDefinition actionTriggerDefinition), ()); }; -} \ No newline at end of file +} // namespace griddly \ No newline at end of file diff --git a/tests/src/Mocks/Griddly/Core/MockGameProcess.hpp b/tests/src/Mocks/Griddly/Core/MockGameProcess.hpp index 69fc40849..a20c57c6e 100644 --- a/tests/src/Mocks/Griddly/Core/MockGameProcess.hpp +++ b/tests/src/Mocks/Griddly/Core/MockGameProcess.hpp @@ -1,7 +1,7 @@ #pragma once #include -#include "Griddly/Core/GameProcess.hpp" +#include "Griddly/Core/GameProcess.hpp" #include "gmock/gmock.h" namespace griddly { diff --git a/tests/src/Mocks/Griddly/Core/Players/MockPlayer.hpp b/tests/src/Mocks/Griddly/Core/Players/MockPlayer.hpp index 3b8a7d325..c8e4a063f 100644 --- a/tests/src/Mocks/Griddly/Core/Players/MockPlayer.hpp +++ b/tests/src/Mocks/Griddly/Core/Players/MockPlayer.hpp @@ -1,7 +1,7 @@ #pragma once -#include "Griddly/Core/Players/Player.hpp" #include "Griddly/Core/GameProcess.hpp" +#include "Griddly/Core/Players/Player.hpp" #include "gmock/gmock.h" namespace griddly { diff --git a/tests/src/main.cpp b/tests/src/main.cpp index b42b72163..1659be89e 100644 --- a/tests/src/main.cpp +++ b/tests/src/main.cpp @@ -1,6 +1,6 @@ #include "gtest/gtest.h" int main(int argc, char **argv) { - ::testing::InitGoogleTest(&argc, argv); - return RUN_ALL_TESTS(); + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); } \ No newline at end of file