diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 8a81def7..fc44885d 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -13,7 +13,7 @@ jobs: continue-on-error: true strategy: matrix: - os: [ windows-2022, ubuntu-20.04, macos-11 ] + os: [ windows-2022, ubuntu-22.04, macos-13 ] steps: - uses: actions/checkout@v3 @@ -25,9 +25,11 @@ jobs: with: vs-version: '[17,18)' msbuild-architecture: x64 - - name: Install libssl (Mac Only) - if: ${{ matrix.os == 'macos-11' }} - run: brew install openssl@3 + - name: Install libssl and switch to XCode 15.2 (Mac Only) + if: ${{ matrix.os == 'macos-13' }} + run: | + brew install openssl@3 + sudo xcode-select -s /Applications/Xcode_15.2.app/Contents/Developer - name: cmake uses: lukka/run-cmake@v10 with: diff --git a/CMakeLists.txt b/CMakeLists.txt index 74408df8..0f2b1bb7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,8 +1,11 @@ -cmake_minimum_required(VERSION 3.18) +cmake_minimum_required(VERSION 3.25) project(Darkflame) include(CTest) set(CMAKE_CXX_STANDARD 20) +set(CXX_STANDARD_REQUIRED ON) +set(CMAKE_POLICY_DEFAULT_CMP0063 NEW) # Set CMAKE visibility policy to NEW on project and subprojects +set(CMAKE_CXX_VISIBILITY_PRESET hidden) # Set C++ symbol visibility to default to hidden set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") # Read variables from file @@ -76,6 +79,7 @@ endif() # Our output dir set(CMAKE_BINARY_DIR ${PROJECT_BINARY_DIR}) +#set(CMAKE_INCLUDE_CURRENT_DIR_IN_INTERFACE ON) # unfortunately, forces all libraries to be built in series, which will slow down the build process # TODO make this not have to override the build type directories set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_BINARY_DIR}) @@ -89,6 +93,8 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) +find_package(MariaDB) + # Create a /resServer directory make_directory(${CMAKE_BINARY_DIR}/resServer) @@ -178,7 +184,7 @@ file(ARCHIVE_EXTRACT INPUT ${PROJECT_BINARY_DIR}/navmeshes.zip DESTINATION ${PRO file(REMOVE ${PROJECT_BINARY_DIR}/navmeshes.zip) # Copy vanity files on first build -set(VANITY_FILES "CREDITS.md" "INFO.md" "TESTAMENT.md" "NPC.xml") +set(VANITY_FILES "CREDITS.md" "INFO.md" "TESTAMENT.md" "root.xml" "dev-tribute.xml" "atm.xml" "demo.xml") foreach(file ${VANITY_FILES}) configure_file("${CMAKE_SOURCE_DIR}/vanity/${file}" "${CMAKE_BINARY_DIR}/vanity/${file}" COPYONLY) @@ -201,88 +207,47 @@ foreach(file ${SQL_FILES}) configure_file(${CMAKE_SOURCE_DIR}/migrations/cdserver/${file} ${PROJECT_BINARY_DIR}/migrations/cdserver/${file}) endforeach() +# Add system specfic includes for Apple, Windows and Other Unix OS' (including Linux) +if (APPLE) + include_directories("/usr/local/include/") +endif() + +# Load all of our third party directories +add_subdirectory(thirdparty SYSTEM) + # Create our list of include directories -set(INCLUDED_DIRECTORIES - "dCommon" - "dCommon/dClient" - "dCommon/dEnums" - - "dChatFilter" - - "dGame" - "dGame/dBehaviors" - "dGame/dComponents" - "dGame/dGameMessages" - "dGame/dInventory" - "dGame/dMission" - "dGame/dEntity" - "dGame/dPropertyBehaviors" - "dGame/dPropertyBehaviors/ControlBehaviorMessages" - "dGame/dUtilities" - +include_directories( "dPhysics" "dNavigation" - "dNavigation/dTerrain" - - "dZoneManager" - - "dDatabase" - "dDatabase/CDClientDatabase" - "dDatabase/CDClientDatabase/CDClientTables" - "dDatabase/GameDatabase" - "dDatabase/GameDatabase/ITables" - "dDatabase/GameDatabase/MySQL" - "dDatabase/GameDatabase/MySQL/Tables" "dNet" - "thirdparty/magic_enum/include/magic_enum" - "thirdparty/raknet/Source" - "thirdparty/tinyxml2" - "thirdparty/recastnavigation" - "thirdparty/SQLite" - "thirdparty/cpplinq" - "thirdparty/cpp-httplib" - "tests" "tests/dCommonTests" "tests/dGameTests" "tests/dGameTests/dComponentsTests" + + SYSTEM "thirdparty/magic_enum/include/magic_enum" + SYSTEM "thirdparty/raknet/Source" + SYSTEM "thirdparty/tinyxml2" + SYSTEM "thirdparty/recastnavigation" + SYSTEM "thirdparty/SQLite" + SYSTEM "thirdparty/cpplinq" + SYSTEM "thirdparty/cpp-httplib" + SYSTEM "thirdparty/MD5" ) # Add system specfic includes for Apple, Windows and Other Unix OS' (including Linux) +# TODO: Should probably not do this. if(APPLE) include_directories("/usr/local/include/") endif() -# Actually include the directories from our list -foreach(dir ${INCLUDED_DIRECTORIES}) - include_directories(${PROJECT_SOURCE_DIR}/${dir}) -endforeach() - -if(NOT WIN32) - include_directories("${PROJECT_SOURCE_DIR}/thirdparty/libbcrypt/include/bcrypt") -endif() - -include_directories("${PROJECT_SOURCE_DIR}/thirdparty/libbcrypt/include") - # Add linking directories: -link_directories(${PROJECT_BINARY_DIR}) - -# Load all of our third party directories -add_subdirectory(thirdparty) - -# Glob together all headers that need to be precompiled -file( - GLOB HEADERS_DDATABASE - LIST_DIRECTORIES false - ${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase/*.h - ${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase/CDClientTables/*.h - ${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase/ITables/*.h - ${PROJECT_SOURCE_DIR}/thirdparty/SQLite/*.h -) - +if (UNIX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wold-style-cast -Werror") # Warning flags +endif() file( GLOB HEADERS_DZONEMANAGER LIST_DIRECTORIES false @@ -317,7 +282,7 @@ add_subdirectory(dPhysics) add_subdirectory(dServer) # Create a list of common libraries shared between all binaries -set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "raknet" "mariadbConnCpp" "magic_enum") +set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "raknet" "MariaDB::ConnCpp" "magic_enum") # Add platform specific common libraries if(UNIX) @@ -339,12 +304,6 @@ target_precompile_headers( ${HEADERS_DZONEMANAGER} ) -# Need to specify to use the CXX compiler language here or else we get errors including . -target_precompile_headers( - dDatabase PRIVATE - "$<$:${HEADERS_DDATABASE}>" -) - target_precompile_headers( dCommon PRIVATE ${HEADERS_DCOMMON} diff --git a/CMakePresets.json b/CMakePresets.json index f8170755..2feabc53 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -14,13 +14,13 @@ "generator": "Unix Makefiles" }, { - "name": "ci-ubuntu-20.04", + "name": "ci-ubuntu-22.04", "displayName": "CI configure step for Ubuntu", "description": "Same as default, Used in GitHub actions workflow", "inherits": "default" }, { - "name": "ci-macos-11", + "name": "ci-macos-13", "displayName": "CI configure step for MacOS", "description": "Same as default, Used in GitHub actions workflow", "inherits": "default" @@ -67,15 +67,15 @@ "jobs": 2 }, { - "name": "ci-ubuntu-20.04", - "configurePreset": "ci-ubuntu-20.04", + "name": "ci-ubuntu-22.04", + "configurePreset": "ci-ubuntu-22.04", "displayName": "Linux CI Build", "description": "This preset is used by the CI build on linux", "jobs": 2 }, { - "name": "ci-macos-11", - "configurePreset": "ci-macos-11", + "name": "ci-macos-13", + "configurePreset": "ci-macos-13", "displayName": "MacOS CI Build", "description": "This preset is used by the CI build on MacOS", "jobs": 2 @@ -83,8 +83,8 @@ ], "testPresets": [ { - "name": "ci-ubuntu-20.04", - "configurePreset": "ci-ubuntu-20.04", + "name": "ci-ubuntu-22.04", + "configurePreset": "ci-ubuntu-22.04", "displayName": "CI Tests on Linux", "description": "Runs all tests on a linux configuration", "execution": { @@ -95,8 +95,8 @@ } }, { - "name": "ci-macos-11", - "configurePreset": "ci-macos-11", + "name": "ci-macos-13", + "configurePreset": "ci-macos-13", "displayName": "CI Tests on MacOS", "description": "Runs all tests on a Mac configuration", "execution": { diff --git a/Dockerfile b/Dockerfile index c1316a60..efb82b42 100644 --- a/Dockerfile +++ b/Dockerfile @@ -23,8 +23,7 @@ RUN --mount=type=cache,id=build-apt-cache,target=/var/cache/apt \ rm -rf /var/lib/apt/lists/* # Grab libraries and load them -COPY --from=build /app/build/mariadbcpp/src/mariadb_connector_cpp-build/libmariadbcpp.so /usr/local/lib/ -COPY --from=build /app/build/mariadbcpp/src/mariadb_connector_cpp-build/libmariadb/libmariadb/libmariadb.so.3 /usr/local/lib +COPY --from=build /app/build/mariadbcpp/libmariadbcpp.so /usr/local/lib/ RUN ldconfig # Server bins diff --git a/README.md b/README.md index 1d998511..a0dffaad 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,7 @@ git clone --recursive https://github.com/DarkflameUniverse/DarkflameServer ### Windows packages Ensure that you have either the [MSVC C++ compiler](https://visualstudio.microsoft.com/vs/features/cplusplus/) (recommended) or the [Clang compiler](https://github.com/llvm/llvm-project/releases/) installed. -You'll also need to download and install [CMake](https://cmake.org/download/) (version **CMake version 3.18** or later!). +You'll also need to download and install [CMake](https://cmake.org/download/) (version **CMake version 3.25** or later!). ### MacOS packages Ensure you have [brew](https://brew.sh) installed. @@ -356,6 +356,10 @@ The Darkflame Server is automatically built and published as a Docker Container ## Compose +> [!WARNING] +> It seems that Docker Desktop on Windows with the WSL 2 backend has some issues with MariaDB (c.f. [mariadb-docker#331](https://github.com/MariaDB/mariadb-docker/issues/331)) triggered by NexusDashboard +> migrations, so this setup may not work for you. If that is the case, please tell us about your setup in [NexusDashboard#92](https://github.com/DarkflameUniverse/NexusDashboard/issues/92). + You can use the `docker-compose` tool to [setup a MariaDB database](#database-setup), run the Darkflame Server and manage it with [Nexus Dashboard](https://github.com/DarkflameUniverse/NexusDashboard) all at once. For that: diff --git a/cmake/FindGoogleTest.cmake b/cmake/FindGoogleTest.cmake new file mode 100644 index 00000000..69d16247 --- /dev/null +++ b/cmake/FindGoogleTest.cmake @@ -0,0 +1,17 @@ +include(FetchContent) + +message(STATUS "Fetching gtest...") + +FetchContent_Declare( + googletest + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG release-1.12.1 +) + +# For Windows: Prevent overriding the parent project's compiler/linker settings +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) + +FetchContent_MakeAvailable(GoogleTest) + +message(STATUS "gtest fetched and is now ready.") +set(GoogleTest_FOUND TRUE) diff --git a/thirdparty/CMakeMariaDBLists.txt b/cmake/FindMariaDB.cmake similarity index 58% rename from thirdparty/CMakeMariaDBLists.txt rename to cmake/FindMariaDB.cmake index d7a17f28..d3f89931 100644 --- a/thirdparty/CMakeMariaDBLists.txt +++ b/cmake/FindMariaDB.cmake @@ -23,14 +23,14 @@ if(WIN32 AND NOT MARIADB_BUILD_SOURCE) set(MARIADB_CONNECTOR_CPP_MSI "mariadb-connector-cpp-${MARIADB_CONNECTOR_CPP_VERSION}-win64.msi") if(NOT EXISTS "${MARIADB_MSI_DIR}/${MARIADB_CONNECTOR_C_MSI}" ) - message("Downloading mariadb connector/c") + message(STATUS "Downloading mariadb connector/c") file(DOWNLOAD https://dlm.mariadb.com/${MARIADB_CONNECTOR_C_BUCKET}/Connectors/c/connector-c-${MARIADB_CONNECTOR_C_VERSION}/${MARIADB_CONNECTOR_C_MSI} "${MARIADB_MSI_DIR}/${MARIADB_CONNECTOR_C_MSI}" EXPECTED_HASH MD5=${MARIADB_CONNECTOR_C_MD5}) endif() if(NOT EXISTS "${MARIADB_MSI_DIR}/${MARIADB_CONNECTOR_CPP_MSI}" ) - message("Downloading mariadb connector/c++") + message(STATUS "Downloading mariadb connector/c++") file(DOWNLOAD https://dlm.mariadb.com/${MARIADB_CONNECTOR_CPP_BUCKET}/Connectors/cpp/connector-cpp-${MARIADB_CONNECTOR_CPP_VERSION}/${MARIADB_CONNECTOR_CPP_MSI} "${MARIADB_MSI_DIR}/${MARIADB_CONNECTOR_CPP_MSI}" EXPECTED_HASH MD5=${MARIADB_CONNECTOR_CPP_MD5}) @@ -43,27 +43,28 @@ if(WIN32 AND NOT MARIADB_BUILD_SOURCE) file(TO_NATIVE_PATH "${MARIADB_MSI_DIR}/${MARIADB_CONNECTOR_C_MSI}" MSI_DIR) execute_process(COMMAND msiexec /a ${MSI_DIR} /qn TARGETDIR=${MSIEXEC_TARGETDIR}) endif() + set(MARIADBC_SHARED_LIBRARY_LOCATION "${MARIADB_C_CONNECTOR_DIR}/lib/libmariadb.dll") if(NOT EXISTS "${MARIADB_CPP_CONNECTOR_DIR}") file(TO_NATIVE_PATH "${MARIADB_MSI_DIR}/${MARIADB_CONNECTOR_CPP_MSI}" MSI_DIR) execute_process(COMMAND msiexec /a ${MSI_DIR} /qn TARGETDIR=${MSIEXEC_TARGETDIR}) endif() - set(MARIADB_SHARED_LIBRARY_LOCATION "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.dll") + set(MARIADBCPP_SHARED_LIBRARY_LOCATION "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.dll") set(MARIADB_IMPLIB_LOCATION "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.lib") set(MARIADB_INCLUDE_DIR "${MARIADB_CPP_CONNECTOR_DIR}/include/mariadb") add_custom_target(mariadb_connector_cpp) add_custom_command(TARGET mariadb_connector_cpp POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different - "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.dll" - "${MARIADB_C_CONNECTOR_DIR}/lib/libmariadb.dll" + "${MARIADBCPP_SHARED_LIBRARY_LOCATION}" + "${MARIADBC_SHARED_LIBRARY_LOCATION}" "${PROJECT_BINARY_DIR}") # MariaDB uses plugins that the database needs to load, the prebuilt binaries by default will try to find the libraries in system directories, # so set this define and the servers will set the MARIADB_PLUGIN_DIR environment variable to the appropriate directory. # Plugin directory is determined at dll load time (this will happen before main()) so we need to delay the dll load so that we can set the environment variable - add_link_options(/DELAYLOAD:${MARIADB_SHARED_LIBRARY_LOCATION}) + add_link_options(/DELAYLOAD:${MARIADBCPP_SHARED_LIBRARY_LOCATION}) add_compile_definitions(MARIADB_PLUGIN_DIR_OVERRIDE="${MARIADB_CPP_CONNECTOR_DIR}/plugin") else() # Build from source @@ -85,77 +86,61 @@ else() # Build from source -DCMAKE_CXX_FLAGS=-D_GLIBCXX_USE_CXX11_ABI=0) endif() + set(MARIADBCPP_INSTALL_DIR ${PROJECT_BINARY_DIR}/prefix) + set(MARIADBCPP_LIBRARY_DIR ${PROJECT_BINARY_DIR}/mariadbcpp) + set(MARIADBCPP_PLUGIN_DIR ${MARIADBCPP_LIBRARY_DIR}/plugin) + set(MARIADBCPP_SOURCE_DIR ${PROJECT_SOURCE_DIR}/thirdparty/mariadb-connector-cpp) + set(MARIADB_INCLUDE_DIR "${MARIADBCPP_SOURCE_DIR}/include") ExternalProject_Add(mariadb_connector_cpp - SOURCE_DIR ${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp - CMAKE_ARGS -Wno-dev - -DCMAKE_BUILD_RPATH_USE_ORIGIN=${CMAKE_BUILD_RPATH_USE_ORIGIN} - -DCMAKE_INSTALL_PREFIX=./mariadbcpp # Points the connector to the correct plugin directory - -DINSTALL_PLUGINDIR=plugin - ${MARIADB_EXTRA_CMAKE_ARGS} - PREFIX "${PROJECT_BINARY_DIR}/mariadbcpp" - BUILD_COMMAND cmake --build . --config RelWithDebInfo -j${MARIADB_CONNECTOR_COMPILE_JOBS} - INSTALL_COMMAND "") - - ExternalProject_Get_Property(mariadb_connector_cpp BINARY_DIR) + PREFIX "${PROJECT_BINARY_DIR}/thirdparty/mariadb-connector-cpp" + SOURCE_DIR ${MARIADBCPP_SOURCE_DIR} + INSTALL_DIR ${MARIADBCPP_INSTALL_DIR} + CMAKE_ARGS -Wno-dev + -DWITH_UNIT_TESTS=OFF + -DMARIADB_LINK_DYNAMIC=OFF + -DCMAKE_BUILD_RPATH_USE_ORIGIN=${CMAKE_BUILD_RPATH_USE_ORIGIN} + -DCMAKE_INSTALL_PREFIX= + -DINSTALL_LIBDIR=${MARIADBCPP_LIBRARY_DIR} + -DINSTALL_PLUGINDIR=${MARIADBCPP_PLUGIN_DIR} + ${MARIADB_EXTRA_CMAKE_ARGS} + BUILD_ALWAYS true + ) if(WIN32) set(MARIADB_SHARED_LIBRARY_NAME mariadbcpp.dll) set(MARIADB_PLUGIN_SUFFIX .dll) - set(MARIADB_IMPLIB_LOCATION "${BINARY_DIR}/RelWithDebInfo/mariadbcpp.lib") + set(MARIADB_IMPLIB_LOCATION "${MARIADBCPP_LIBRARY_DIR}/mariadbcpp.lib") # When built from source windows only seems to check same folder as exe instead specified folder, so use # environment variable to force it add_link_options(/DELAYLOAD:mariadbcpp.dll) - add_compile_definitions(MARIADB_PLUGIN_DIR_OVERRIDE="${PROJECT_BINARY_DIR}/mariadbcpp/plugin") + add_compile_definitions(MARIADB_PLUGIN_DIR_OVERRIDE="${MARIADBCPP_PLUGIN_DIR}") else() set(MARIADB_SHARED_LIBRARY_NAME libmariadbcpp${CMAKE_SHARED_LIBRARY_SUFFIX}) - set(MARIADB_PLUGIN_SUFFIX .so) + set(MARIADB_PLUGIN_SUFFIX ${CMAKE_SHARED_LIBRARY_SUFFIX}) endif() - get_property(isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) - if(isMultiConfig) - set(MARIADB_SHARED_LIBRARY_LOCATION "${BINARY_DIR}/RelWithDebInfo/${MARIADB_SHARED_LIBRARY_NAME}") - set(MARIADB_SHARED_LIBRARY_COPY_LOCATION "${PROJECT_BINARY_DIR}/$") - set(MARIADB_PLUGINS_LOCATION "${BINARY_DIR}/libmariadb/RelWithDebInfo") - else() - set(MARIADB_SHARED_LIBRARY_LOCATION "${BINARY_DIR}/${MARIADB_SHARED_LIBRARY_NAME}") - set(MARIADB_SHARED_LIBRARY_COPY_LOCATION "${PROJECT_BINARY_DIR}") - set(MARIADB_PLUGINS_LOCATION "${BINARY_DIR}/libmariadb") + set(MARIADBCPP_SHARED_LIBRARY_LOCATION "${MARIADBCPP_LIBRARY_DIR}/${MARIADB_SHARED_LIBRARY_NAME}") + if(WIN32) + set(MARIADBC_SHARED_LIBRARY_LOCATION "${MARIADBCPP_LIBRARY_DIR}/libmariadb.lib") endif() - - set(MARIADB_INCLUDE_DIR "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/include/") - - add_custom_command(TARGET mariadb_connector_cpp POST_BUILD - COMMAND ${CMAKE_COMMAND} -E make_directory - ${BINARY_DIR}/mariadbcpp/plugin - ${MARIADB_SHARED_LIBRARY_COPY_LOCATION} - - COMMAND ${CMAKE_COMMAND} -E copy_if_different - ${MARIADB_SHARED_LIBRARY_LOCATION} - ${MARIADB_SHARED_LIBRARY_COPY_LOCATION} - - COMMAND ${CMAKE_COMMAND} -E copy_if_different - ${MARIADB_PLUGINS_LOCATION}/caching_sha2_password${MARIADB_PLUGIN_SUFFIX} - ${MARIADB_PLUGINS_LOCATION}/client_ed25519${MARIADB_PLUGIN_SUFFIX} - ${MARIADB_PLUGINS_LOCATION}/dialog${MARIADB_PLUGIN_SUFFIX} - ${MARIADB_PLUGINS_LOCATION}/mysql_clear_password${MARIADB_PLUGIN_SUFFIX} - ${MARIADB_PLUGINS_LOCATION}/sha256_password${MARIADB_PLUGIN_SUFFIX} - ${BINARY_DIR}/mariadbcpp/plugin) -endif() - -# Remove the CMakeLists.txt file from the tests folder for the maria-db-connector so we dont compile the tests. -if(EXISTS "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/test/CMakeLists.txt") - file(REMOVE "${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/test/CMakeLists.txt") endif() # Create mariadb connector library object -add_library(mariadbConnCpp SHARED IMPORTED GLOBAL) -set_property(TARGET mariadbConnCpp PROPERTY IMPORTED_LOCATION ${MARIADB_SHARED_LIBRARY_LOCATION}) +add_library(MariaDB::ConnCpp SHARED IMPORTED GLOBAL) +add_dependencies(MariaDB::ConnCpp mariadb_connector_cpp) +set_target_properties(MariaDB::ConnCpp PROPERTIES + IMPORTED_LOCATION "${MARIADBCPP_SHARED_LIBRARY_LOCATION}") if(WIN32) - set_property(TARGET mariadbConnCpp PROPERTY IMPORTED_IMPLIB ${MARIADB_IMPLIB_LOCATION}) + set_target_properties(MariaDB::ConnCpp PROPERTIES + IMPORTED_IMPLIB "${MARIADB_IMPLIB_LOCATION}") +elseif(APPLE) + set_target_properties(MariaDB::ConnCpp PROPERTIES + IMPORTED_SONAME "libmariadbcpp") endif() # Add directories to include lists -target_include_directories(mariadbConnCpp INTERFACE ${MARIADB_INCLUDE_DIR}) -add_dependencies(mariadbConnCpp mariadb_connector_cpp) +target_include_directories(MariaDB::ConnCpp SYSTEM INTERFACE ${MARIADB_INCLUDE_DIR}) + +set(MariaDB_FOUND TRUE) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index 5593f0e1..476e1a68 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -82,11 +82,11 @@ int main(int argc, char** argv) { Game::randomEngine = std::mt19937(time(0)); //It's safe to pass 'localhost' here, as the IP is only used as the external IP. - uint32_t maxClients = 999; - uint32_t ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default. std::string ourIP = "localhost"; - GeneralUtils::TryParse(Game::config->GetValue("max_clients"), maxClients); - GeneralUtils::TryParse(Game::config->GetValue("auth_server_port"), ourPort); + const uint32_t maxClients = GeneralUtils::TryParse(Game::config->GetValue("max_clients")).value_or(999); + + //LU client is hardcoded to use this for auth port, so I'm making it the default. + const uint32_t ourPort = GeneralUtils::TryParse(Game::config->GetValue("auth_server_port")).value_or(1001); const auto externalIPString = Game::config->GetValue("external_ip"); if (!externalIPString.empty()) ourIP = externalIPString; diff --git a/dChatServer/CMakeLists.txt b/dChatServer/CMakeLists.txt index cc4cee1f..c7eea041 100644 --- a/dChatServer/CMakeLists.txt +++ b/dChatServer/CMakeLists.txt @@ -5,10 +5,12 @@ set(DCHATSERVER_SOURCES ) add_executable(ChatServer "ChatServer.cpp") -add_library(dChatServer ${DCHATSERVER_SOURCES}) -target_include_directories(dChatServer PRIVATE ${PROJECT_SOURCE_DIR}/dServer) +target_include_directories(ChatServer PRIVATE "${PROJECT_SOURCE_DIR}/dChatFilter") add_compile_definitions(ChatServer PRIVATE PROJECT_VERSION="\"${PROJECT_VERSION}\"") +add_library(dChatServer ${DCHATSERVER_SOURCES}) +target_include_directories(dChatServer PRIVATE "${PROJECT_SOURCE_DIR}/dServer") + target_link_libraries(dChatServer ${COMMON_LIBRARIES} dChatFilter) target_link_libraries(ChatServer ${COMMON_LIBRARIES} dChatFilter dChatServer dServer) diff --git a/dChatServer/ChatIgnoreList.cpp b/dChatServer/ChatIgnoreList.cpp index 697e9d1e..6dfbd7fc 100644 --- a/dChatServer/ChatIgnoreList.cpp +++ b/dChatServer/ChatIgnoreList.cpp @@ -59,7 +59,7 @@ void ChatIgnoreList::GetIgnoreList(Packet* packet) { bitStream.Write(LUWString(ignoredPlayer.playerName, 36)); } - Game::server->Send(&bitStream, packet->systemAddress, false); + Game::server->Send(bitStream, packet->systemAddress, false); } void ChatIgnoreList::AddIgnore(Packet* packet) { @@ -131,7 +131,7 @@ void ChatIgnoreList::AddIgnore(Packet* packet) { bitStream.Write(playerNameSend); bitStream.Write(ignoredPlayerId); - Game::server->Send(&bitStream, packet->systemAddress, false); + Game::server->Send(bitStream, packet->systemAddress, false); } void ChatIgnoreList::RemoveIgnore(Packet* packet) { @@ -167,5 +167,5 @@ void ChatIgnoreList::RemoveIgnore(Packet* packet) { LUWString playerNameSend(removedIgnoreStr, 33); bitStream.Write(playerNameSend); - Game::server->Send(&bitStream, packet->systemAddress, false); + Game::server->Send(bitStream, packet->systemAddress, false); } diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index db12e7d2..ad2b17c7 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -98,18 +98,15 @@ int main(int argc, char** argv) { masterPort = masterInfo->port; } //It's safe to pass 'localhost' here, as the IP is only used as the external IP. - uint32_t maxClients = 999; - uint32_t ourPort = 1501; std::string ourIP = "localhost"; - GeneralUtils::TryParse(Game::config->GetValue("max_clients"), maxClients); - GeneralUtils::TryParse(Game::config->GetValue("chat_server_port"), ourPort); + const uint32_t maxClients = GeneralUtils::TryParse(Game::config->GetValue("max_clients")).value_or(999); + const uint32_t ourPort = GeneralUtils::TryParse(Game::config->GetValue("chat_server_port")).value_or(2005); const auto externalIPString = Game::config->GetValue("external_ip"); if (!externalIPString.empty()) ourIP = externalIPString; Game::server = new dServer(ourIP, ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config, &Game::lastSignal); - bool dontGenerateDCF = false; - GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf"), dontGenerateDCF); + const bool dontGenerateDCF = GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf")).value_or(false); Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", dontGenerateDCF); Game::randomEngine = std::mt19937(time(0)); @@ -210,7 +207,6 @@ void HandlePacket(Packet* packet) { // verif internal Game::playerContainer.CreateTeamServer(packet); break; - case eChatMessageType::GET_FRIENDS_LIST: ChatPacketHandler::HandleFriendlistRequest(packet); break; diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index 83a198b1..e449fcde 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -14,16 +14,10 @@ #include "dConfig.h" void PlayerContainer::Initialize() { - GeneralUtils::TryParse(Game::config->GetValue("max_number_of_best_friends"), m_MaxNumberOfBestFriends); - GeneralUtils::TryParse(Game::config->GetValue("max_number_of_friends"), m_MaxNumberOfFriends); -} - -PlayerContainer::~PlayerContainer() { - m_Players.clear(); -} - -PlayerData::PlayerData() { - gmLevel == eGameMasterLevel::CIVILIAN; + m_MaxNumberOfBestFriends = + GeneralUtils::TryParse(Game::config->GetValue("max_number_of_best_friends")).value_or(m_MaxNumberOfBestFriends); + m_MaxNumberOfFriends = + GeneralUtils::TryParse(Game::config->GetValue("max_number_of_friends")).value_or(m_MaxNumberOfFriends); } TeamData::TeamData() { @@ -158,7 +152,7 @@ void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) { bitStream.Write(player); bitStream.Write(time); - Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); + Game::server->Send(bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); } TeamData* PlayerContainer::CreateLocalTeam(std::vector members) { @@ -369,7 +363,7 @@ void PlayerContainer::UpdateTeamsOnWorld(TeamData* team, bool deleteTeam) { } } - Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); + Game::server->Send(bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); } std::u16string PlayerContainer::GetName(LWOOBJID playerID) { diff --git a/dChatServer/PlayerContainer.h b/dChatServer/PlayerContainer.h index 0e360eaa..053766b3 100644 --- a/dChatServer/PlayerContainer.h +++ b/dChatServer/PlayerContainer.h @@ -10,7 +10,7 @@ enum class eGameMasterLevel : uint8_t; struct IgnoreData { - IgnoreData(const std::string& name, const LWOOBJID& id) : playerName(name), playerId(id) {} + IgnoreData(const std::string& name, const LWOOBJID& id) : playerName{ name }, playerId{ id } {} inline bool operator==(const std::string& other) const noexcept { return playerName == other; } @@ -24,7 +24,6 @@ struct IgnoreData { }; struct PlayerData { - PlayerData(); operator bool() const noexcept { return playerID != LWOOBJID_EMPTY; } @@ -45,7 +44,7 @@ struct PlayerData { std::string playerName; std::vector friends; std::vector ignoredPlayers; - eGameMasterLevel gmLevel; + eGameMasterLevel gmLevel = static_cast(0); // CIVILLIAN bool isFTP = false; }; @@ -61,8 +60,6 @@ struct TeamData { class PlayerContainer { public: - ~PlayerContainer(); - void Initialize(); void InsertPlayer(Packet* packet); void RemovePlayer(Packet* packet); diff --git a/dCommon/AMFDeserialize.cpp b/dCommon/AMFDeserialize.cpp index 648d1ed1..130ebc4a 100644 --- a/dCommon/AMFDeserialize.cpp +++ b/dCommon/AMFDeserialize.cpp @@ -9,12 +9,11 @@ * AMF3 Deserializer written by EmosewaMC */ -AMFBaseValue* AMFDeserialize::Read(RakNet::BitStream* inStream) { - if (!inStream) return nullptr; +AMFBaseValue* AMFDeserialize::Read(RakNet::BitStream& inStream) { AMFBaseValue* returnValue = nullptr; // Read in the value type from the bitStream eAmf marker; - inStream->Read(marker); + inStream.Read(marker); // Based on the typing, create the value associated with that and return the base value class switch (marker) { case eAmf::Undefined: { @@ -79,13 +78,13 @@ AMFBaseValue* AMFDeserialize::Read(RakNet::BitStream* inStream) { return returnValue; } -uint32_t AMFDeserialize::ReadU29(RakNet::BitStream* inStream) { +uint32_t AMFDeserialize::ReadU29(RakNet::BitStream& inStream) { bool byteFlag = true; uint32_t actualNumber{}; uint8_t numberOfBytesRead{}; while (byteFlag && numberOfBytesRead < 4) { uint8_t byte{}; - inStream->Read(byte); + inStream.Read(byte); // Parse the byte if (numberOfBytesRead < 3) { byteFlag = byte & static_cast(1 << 7); @@ -101,7 +100,7 @@ uint32_t AMFDeserialize::ReadU29(RakNet::BitStream* inStream) { return actualNumber; } -const std::string AMFDeserialize::ReadString(RakNet::BitStream* inStream) { +const std::string AMFDeserialize::ReadString(RakNet::BitStream& inStream) { auto length = ReadU29(inStream); // Check if this is a reference bool isReference = length % 2 == 1; @@ -109,7 +108,7 @@ const std::string AMFDeserialize::ReadString(RakNet::BitStream* inStream) { length = length >> 1; if (isReference) { std::string value(length, 0); - inStream->Read(&value[0], length); + inStream.Read(&value[0], length); // Empty strings are never sent by reference if (!value.empty()) accessedElements.push_back(value); return value; @@ -119,20 +118,20 @@ const std::string AMFDeserialize::ReadString(RakNet::BitStream* inStream) { } } -AMFBaseValue* AMFDeserialize::ReadAmfDouble(RakNet::BitStream* inStream) { +AMFBaseValue* AMFDeserialize::ReadAmfDouble(RakNet::BitStream& inStream) { double value; - inStream->Read(value); + inStream.Read(value); return new AMFDoubleValue(value); } -AMFBaseValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream* inStream) { +AMFBaseValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream& inStream) { auto arrayValue = new AMFArrayValue(); // Read size of dense array - auto sizeOfDenseArray = (ReadU29(inStream) >> 1); + const auto sizeOfDenseArray = (ReadU29(inStream) >> 1); // Then read associative portion while (true) { - auto key = ReadString(inStream); + const auto key = ReadString(inStream); // No more associative values when we encounter an empty string key if (key.size() == 0) break; arrayValue->Insert(key, Read(inStream)); @@ -144,10 +143,10 @@ AMFBaseValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream* inStream) { return arrayValue; } -AMFBaseValue* AMFDeserialize::ReadAmfString(RakNet::BitStream* inStream) { +AMFBaseValue* AMFDeserialize::ReadAmfString(RakNet::BitStream& inStream) { return new AMFStringValue(ReadString(inStream)); } -AMFBaseValue* AMFDeserialize::ReadAmfInteger(RakNet::BitStream* inStream) { +AMFBaseValue* AMFDeserialize::ReadAmfInteger(RakNet::BitStream& inStream) { return new AMFIntValue(ReadU29(inStream)); } diff --git a/dCommon/AMFDeserialize.h b/dCommon/AMFDeserialize.h index 5e2729eb..e204976d 100644 --- a/dCommon/AMFDeserialize.h +++ b/dCommon/AMFDeserialize.h @@ -15,7 +15,7 @@ public: * @param inStream inStream to read value from. * @return Returns an AMFValue with all the information from the bitStream in it. */ - AMFBaseValue* Read(RakNet::BitStream* inStream); + AMFBaseValue* Read(RakNet::BitStream& inStream); private: /** * @brief Private method to read a U29 integer from a bitstream @@ -23,7 +23,7 @@ private: * @param inStream bitstream to read data from * @return The number as an unsigned 29 bit integer */ - uint32_t ReadU29(RakNet::BitStream* inStream); + static uint32_t ReadU29(RakNet::BitStream& inStream); /** * @brief Reads a string from a bitstream @@ -31,7 +31,7 @@ private: * @param inStream bitStream to read data from * @return The read string */ - const std::string ReadString(RakNet::BitStream* inStream); + const std::string ReadString(RakNet::BitStream& inStream); /** * @brief Read an AMFDouble value from a bitStream @@ -39,7 +39,7 @@ private: * @param inStream bitStream to read data from * @return Double value represented as an AMFValue */ - AMFBaseValue* ReadAmfDouble(RakNet::BitStream* inStream); + AMFBaseValue* ReadAmfDouble(RakNet::BitStream& inStream); /** * @brief Read an AMFArray from a bitStream @@ -47,7 +47,7 @@ private: * @param inStream bitStream to read data from * @return Array value represented as an AMFValue */ - AMFBaseValue* ReadAmfArray(RakNet::BitStream* inStream); + AMFBaseValue* ReadAmfArray(RakNet::BitStream& inStream); /** * @brief Read an AMFString from a bitStream @@ -55,7 +55,7 @@ private: * @param inStream bitStream to read data from * @return String value represented as an AMFValue */ - AMFBaseValue* ReadAmfString(RakNet::BitStream* inStream); + AMFBaseValue* ReadAmfString(RakNet::BitStream& inStream); /** * @brief Read an AMFInteger from a bitStream @@ -63,7 +63,7 @@ private: * @param inStream bitStream to read data from * @return Integer value represented as an AMFValue */ - AMFBaseValue* ReadAmfInteger(RakNet::BitStream* inStream); + AMFBaseValue* ReadAmfInteger(RakNet::BitStream& inStream); /** * List of strings read so far saved to be read by reference. diff --git a/dCommon/Amf3.h b/dCommon/Amf3.h index 967313c7..9fe728c0 100644 --- a/dCommon/Amf3.h +++ b/dCommon/Amf3.h @@ -31,54 +31,70 @@ enum class eAmf : uint8_t { class AMFBaseValue { public: - virtual eAmf GetValueType() { return eAmf::Undefined; }; - AMFBaseValue() {}; - virtual ~AMFBaseValue() {}; + [[nodiscard]] constexpr virtual eAmf GetValueType() const noexcept { return eAmf::Undefined; } + constexpr AMFBaseValue() noexcept = default; + constexpr virtual ~AMFBaseValue() noexcept = default; }; -template +// AMFValue template class instantiations +template class AMFValue : public AMFBaseValue { public: - AMFValue() {}; - AMFValue(ValueType value) { SetValue(value); }; - virtual ~AMFValue() override {}; + AMFValue() = default; + AMFValue(const ValueType value) : m_Data{ value } {} - eAmf GetValueType() override { return eAmf::Undefined; }; + virtual ~AMFValue() override = default; + + [[nodiscard]] constexpr eAmf GetValueType() const noexcept override; + + [[nodiscard]] const ValueType& GetValue() const { return m_Data; } + + void SetValue(const ValueType value) { m_Data = value; } - const ValueType& GetValue() { return data; }; - void SetValue(ValueType value) { data = value; }; protected: - ValueType data; + ValueType m_Data; }; +// Explicit template class instantiations +template class AMFValue; +template class AMFValue; +template class AMFValue; +template class AMFValue; +template class AMFValue; +template class AMFValue; + +// AMFValue template class member function instantiations +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Null; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return m_Data ? eAmf::True : eAmf::False; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Integer; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Integer; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::String; } +template <> [[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Double; } + +template +[[nodiscard]] constexpr eAmf AMFValue::GetValueType() const noexcept { return eAmf::Undefined; } + // As a string this is much easier to write and read from a BitStream. -template<> +template <> class AMFValue : public AMFBaseValue { public: - AMFValue() {}; - AMFValue(const char* value) { SetValue(std::string(value)); }; - virtual ~AMFValue() override {}; + AMFValue() = default; + AMFValue(const char* value) { m_Data = value; } + virtual ~AMFValue() override = default; - eAmf GetValueType() override { return eAmf::String; }; + [[nodiscard]] constexpr eAmf GetValueType() const noexcept override { return eAmf::String; } - const std::string& GetValue() { return data; }; - void SetValue(std::string value) { data = value; }; + [[nodiscard]] const std::string& GetValue() const { return m_Data; } + void SetValue(const std::string& value) { m_Data = value; } protected: - std::string data; + std::string m_Data; }; -typedef AMFValue AMFNullValue; -typedef AMFValue AMFBoolValue; -typedef AMFValue AMFIntValue; -typedef AMFValue AMFStringValue; -typedef AMFValue AMFDoubleValue; - -template<> inline eAmf AMFValue::GetValueType() { return eAmf::Null; }; -template<> inline eAmf AMFValue::GetValueType() { return this->data ? eAmf::True : eAmf::False; }; -template<> inline eAmf AMFValue::GetValueType() { return eAmf::Integer; }; -template<> inline eAmf AMFValue::GetValueType() { return eAmf::Integer; }; -template<> inline eAmf AMFValue::GetValueType() { return eAmf::String; }; -template<> inline eAmf AMFValue::GetValueType() { return eAmf::Double; }; +using AMFNullValue = AMFValue; +using AMFBoolValue = AMFValue; +using AMFIntValue = AMFValue; +using AMFStringValue = AMFValue; +using AMFDoubleValue = AMFValue; /** * The AMFArrayValue object holds 2 types of lists: @@ -89,15 +105,14 @@ template<> inline eAmf AMFValue::GetValueType() { return eAmf::Double; } * and are not to be deleted by a caller. */ class AMFArrayValue : public AMFBaseValue { - - typedef std::unordered_map AMFAssociative; - typedef std::vector AMFDense; + using AMFAssociative = std::unordered_map; + using AMFDense = std::vector; public: - eAmf GetValueType() override { return eAmf::Array; }; + [[nodiscard]] constexpr eAmf GetValueType() const noexcept override { return eAmf::Array; } ~AMFArrayValue() override { - for (auto valueToDelete : GetDense()) { + for (const auto* valueToDelete : GetDense()) { if (valueToDelete) { delete valueToDelete; valueToDelete = nullptr; @@ -109,17 +124,17 @@ public: valueToDelete.second = nullptr; } } - }; + } /** * Returns the Associative portion of the object */ - inline AMFAssociative& GetAssociative() { return this->associative; }; + [[nodiscard]] inline const AMFAssociative& GetAssociative() const noexcept { return m_Associative; } /** * Returns the dense portion of the object */ - inline AMFDense& GetDense() { return this->dense; }; + [[nodiscard]] inline const AMFDense& GetDense() const noexcept { return m_Dense; } /** * Inserts an AMFValue into the associative portion with the given key. @@ -135,48 +150,48 @@ public: * @return The inserted element if the type matched, * or nullptr if a key existed and was not the same type */ - template - std::pair*, bool> Insert(const std::string& key, ValueType value) { - auto element = associative.find(key); + template + [[maybe_unused]] std::pair*, bool> Insert(const std::string& key, const ValueType value) { + const auto element = m_Associative.find(key); AMFValue* val = nullptr; bool found = true; - if (element == associative.end()) { + if (element == m_Associative.cend()) { val = new AMFValue(value); - associative.insert(std::make_pair(key, val)); + m_Associative.emplace(key, val); } else { val = dynamic_cast*>(element->second); found = false; } return std::make_pair(val, found); - }; + } // Associates an array with a string key - std::pair Insert(const std::string& key) { - auto element = associative.find(key); + [[maybe_unused]] std::pair Insert(const std::string& key) { + const auto element = m_Associative.find(key); AMFArrayValue* val = nullptr; bool found = true; - if (element == associative.end()) { + if (element == m_Associative.cend()) { val = new AMFArrayValue(); - associative.insert(std::make_pair(key, val)); + m_Associative.emplace(key, val); } else { val = dynamic_cast(element->second); found = false; } return std::make_pair(val, found); - }; + } // Associates an array with an integer key - std::pair Insert(const uint32_t& index) { + [[maybe_unused]] std::pair Insert(const size_t index) { AMFArrayValue* val = nullptr; bool inserted = false; - if (index >= dense.size()) { - dense.resize(index + 1); + if (index >= m_Dense.size()) { + m_Dense.resize(index + 1); val = new AMFArrayValue(); - dense.at(index) = val; + m_Dense.at(index) = val; inserted = true; } - return std::make_pair(dynamic_cast(dense.at(index)), inserted); - }; + return std::make_pair(dynamic_cast(m_Dense.at(index)), inserted); + } /** * @brief Inserts an AMFValue into the AMFArray key'd by index. @@ -188,18 +203,18 @@ public: * @return The inserted element, or nullptr if the type did not match * what was at the index. */ - template - std::pair*, bool> Insert(const uint32_t& index, ValueType value) { + template + [[maybe_unused]] std::pair*, bool> Insert(const size_t index, const ValueType value) { AMFValue* val = nullptr; bool inserted = false; - if (index >= this->dense.size()) { - this->dense.resize(index + 1); + if (index >= m_Dense.size()) { + m_Dense.resize(index + 1); val = new AMFValue(value); - this->dense.at(index) = val; + m_Dense.at(index) = val; inserted = true; } - return std::make_pair(dynamic_cast*>(this->dense.at(index)), inserted); - }; + return std::make_pair(dynamic_cast*>(m_Dense.at(index)), inserted); + } /** * Inserts an AMFValue into the associative portion with the given key. @@ -210,15 +225,15 @@ public: * @param key The key to associate with the value * @param value The value to insert */ - void Insert(const std::string& key, AMFBaseValue* value) { - auto element = associative.find(key); - if (element != associative.end() && element->second) { + void Insert(const std::string& key, AMFBaseValue* const value) { + const auto element = m_Associative.find(key); + if (element != m_Associative.cend() && element->second) { delete element->second; element->second = value; } else { - associative.insert(std::make_pair(key, value)); + m_Associative.emplace(key, value); } - }; + } /** * Inserts an AMFValue into the associative portion with the given index. @@ -229,15 +244,15 @@ public: * @param key The key to associate with the value * @param value The value to insert */ - void Insert(const uint32_t index, AMFBaseValue* value) { - if (index < dense.size()) { - AMFDense::iterator itr = dense.begin() + index; - if (*itr) delete dense.at(index); + void Insert(const size_t index, AMFBaseValue* const value) { + if (index < m_Dense.size()) { + const AMFDense::const_iterator itr = m_Dense.cbegin() + index; + if (*itr) delete m_Dense.at(index); } else { - dense.resize(index + 1); + m_Dense.resize(index + 1); } - dense.at(index) = value; - }; + m_Dense.at(index) = value; + } /** * Pushes an AMFValue into the back of the dense portion. @@ -249,10 +264,10 @@ public: * * @return The inserted pointer, or nullptr should the key already be in use. */ - template - inline AMFValue* Push(ValueType value) { - return Insert(this->dense.size(), value).first; - }; + template + [[maybe_unused]] inline AMFValue* Push(const ValueType value) { + return Insert(m_Dense.size(), value).first; + } /** * Removes the key from the associative portion @@ -261,52 +276,49 @@ public: * * @param key The key to remove from the associative portion */ - void Remove(const std::string& key, bool deleteValue = true) { - AMFAssociative::iterator it = this->associative.find(key); - if (it != this->associative.end()) { + void Remove(const std::string& key, const bool deleteValue = true) { + const AMFAssociative::const_iterator it = m_Associative.find(key); + if (it != m_Associative.cend()) { if (deleteValue) delete it->second; - this->associative.erase(it); + m_Associative.erase(it); } } /** * Pops the last element in the dense portion, deleting it in the process. */ - void Remove(const uint32_t index) { - if (!this->dense.empty() && index < this->dense.size()) { - auto itr = this->dense.begin() + index; + void Remove(const size_t index) { + if (!m_Dense.empty() && index < m_Dense.size()) { + const auto itr = m_Dense.cbegin() + index; if (*itr) delete (*itr); - this->dense.erase(itr); + m_Dense.erase(itr); } } void Pop() { - if (!this->dense.empty()) Remove(this->dense.size() - 1); + if (!m_Dense.empty()) Remove(m_Dense.size() - 1); } - AMFArrayValue* GetArray(const std::string& key) { - AMFAssociative::const_iterator it = this->associative.find(key); - if (it != this->associative.end()) { - return dynamic_cast(it->second); - } - return nullptr; - }; + [[nodiscard]] AMFArrayValue* GetArray(const std::string& key) const { + const AMFAssociative::const_iterator it = m_Associative.find(key); + return it != m_Associative.cend() ? dynamic_cast(it->second) : nullptr; + } - AMFArrayValue* GetArray(const uint32_t index) { - return index >= this->dense.size() ? nullptr : dynamic_cast(this->dense.at(index)); - }; + [[nodiscard]] AMFArrayValue* GetArray(const size_t index) const { + return index < m_Dense.size() ? dynamic_cast(m_Dense.at(index)) : nullptr; + } - inline AMFArrayValue* InsertArray(const std::string& key) { + [[maybe_unused]] inline AMFArrayValue* InsertArray(const std::string& key) { return static_cast(Insert(key).first); - }; + } - inline AMFArrayValue* InsertArray(const uint32_t index) { + [[maybe_unused]] inline AMFArrayValue* InsertArray(const size_t index) { return static_cast(Insert(index).first); - }; + } - inline AMFArrayValue* PushArray() { - return static_cast(Insert(this->dense.size()).first); - }; + [[maybe_unused]] inline AMFArrayValue* PushArray() { + return static_cast(Insert(m_Dense.size()).first); + } /** * Gets an AMFValue by the key from the associative portion and converts it @@ -318,18 +330,18 @@ public: * @return The AMFValue */ template - AMFValue* Get(const std::string& key) const { - AMFAssociative::const_iterator it = this->associative.find(key); - return it != this->associative.end() ? + [[nodiscard]] AMFValue* Get(const std::string& key) const { + const AMFAssociative::const_iterator it = m_Associative.find(key); + return it != m_Associative.cend() ? dynamic_cast*>(it->second) : nullptr; - }; + } // Get from the array but dont cast it - AMFBaseValue* Get(const std::string& key) const { - AMFAssociative::const_iterator it = this->associative.find(key); - return it != this->associative.end() ? it->second : nullptr; - }; + [[nodiscard]] AMFBaseValue* Get(const std::string& key) const { + const AMFAssociative::const_iterator it = m_Associative.find(key); + return it != m_Associative.cend() ? it->second : nullptr; + } /** * @brief Get an AMFValue object at a position in the dense portion. @@ -341,27 +353,28 @@ public: * @return The casted object, or nullptr. */ template - AMFValue* Get(uint32_t index) const { - return index < this->dense.size() ? - dynamic_cast*>(this->dense.at(index)) : + [[nodiscard]] AMFValue* Get(const size_t index) const { + return index < m_Dense.size() ? + dynamic_cast*>(m_Dense.at(index)) : nullptr; - }; + } // Get from the dense but dont cast it - AMFBaseValue* Get(const uint32_t index) const { - return index < this->dense.size() ? this->dense.at(index) : nullptr; - }; + [[nodiscard]] AMFBaseValue* Get(const size_t index) const { + return index < m_Dense.size() ? m_Dense.at(index) : nullptr; + } + private: /** * The associative portion. These values are key'd with strings to an AMFValue. */ - AMFAssociative associative; + AMFAssociative m_Associative; /** * The dense portion. These AMFValue's are stored one after * another with the most recent addition being at the back. */ - AMFDense dense; + AMFDense m_Dense; }; #endif //!__AMF3__H__ diff --git a/dCommon/AmfSerialize.cpp b/dCommon/AmfSerialize.cpp index 3072b8e1..e11ae1de 100644 --- a/dCommon/AmfSerialize.cpp +++ b/dCommon/AmfSerialize.cpp @@ -53,7 +53,7 @@ void RakNet::BitStream::Write(AMFBaseValue& value) { * A private function to write an value to a RakNet::BitStream * RakNet writes in the correct byte order - do not reverse this. */ -void WriteUInt29(RakNet::BitStream* bs, uint32_t v) { +void WriteUInt29(RakNet::BitStream& bs, uint32_t v) { unsigned char b4 = static_cast(v); if (v < 0x00200000) { b4 = b4 & 0x7F; @@ -65,10 +65,10 @@ void WriteUInt29(RakNet::BitStream* bs, uint32_t v) { unsigned char b2; v = v >> 7; b2 = static_cast(v) | 0x80; - bs->Write(b2); + bs.Write(b2); } - bs->Write(b3); + bs.Write(b3); } } else { unsigned char b1; @@ -82,19 +82,19 @@ void WriteUInt29(RakNet::BitStream* bs, uint32_t v) { v = v >> 7; b1 = static_cast(v) | 0x80; - bs->Write(b1); - bs->Write(b2); - bs->Write(b3); + bs.Write(b1); + bs.Write(b2); + bs.Write(b3); } - bs->Write(b4); + bs.Write(b4); } /** * Writes a flag number to a RakNet::BitStream * RakNet writes in the correct byte order - do not reverse this. */ -void WriteFlagNumber(RakNet::BitStream* bs, uint32_t v) { +void WriteFlagNumber(RakNet::BitStream& bs, uint32_t v) { v = (v << 1) | 0x01; WriteUInt29(bs, v); } @@ -104,9 +104,9 @@ void WriteFlagNumber(RakNet::BitStream* bs, uint32_t v) { * * RakNet writes in the correct byte order - do not reverse this. */ -void WriteAMFString(RakNet::BitStream* bs, const std::string& str) { +void WriteAMFString(RakNet::BitStream& bs, const std::string& str) { WriteFlagNumber(bs, static_cast(str.size())); - bs->Write(str.c_str(), static_cast(str.size())); + bs.Write(str.c_str(), static_cast(str.size())); } /** @@ -114,8 +114,8 @@ void WriteAMFString(RakNet::BitStream* bs, const std::string& str) { * * RakNet writes in the correct byte order - do not reverse this. */ -void WriteAMFU16(RakNet::BitStream* bs, uint16_t value) { - bs->Write(value); +void WriteAMFU16(RakNet::BitStream& bs, uint16_t value) { + bs.Write(value); } /** @@ -123,8 +123,8 @@ void WriteAMFU16(RakNet::BitStream* bs, uint16_t value) { * * RakNet writes in the correct byte order - do not reverse this. */ -void WriteAMFU32(RakNet::BitStream* bs, uint32_t value) { - bs->Write(value); +void WriteAMFU32(RakNet::BitStream& bs, uint32_t value) { + bs.Write(value); } /** @@ -132,40 +132,40 @@ void WriteAMFU32(RakNet::BitStream* bs, uint32_t value) { * * RakNet writes in the correct byte order - do not reverse this. */ -void WriteAMFU64(RakNet::BitStream* bs, uint64_t value) { - bs->Write(value); +void WriteAMFU64(RakNet::BitStream& bs, uint64_t value) { + bs.Write(value); } // Writes an AMFIntegerValue to BitStream template<> void RakNet::BitStream::Write(AMFIntValue& value) { - WriteUInt29(this, value.GetValue()); + WriteUInt29(*this, value.GetValue()); } // Writes an AMFDoubleValue to BitStream template<> void RakNet::BitStream::Write(AMFDoubleValue& value) { double d = value.GetValue(); - WriteAMFU64(this, *reinterpret_cast(&d)); + WriteAMFU64(*this, *reinterpret_cast(&d)); } // Writes an AMFStringValue to BitStream template<> void RakNet::BitStream::Write(AMFStringValue& value) { - WriteAMFString(this, value.GetValue()); + WriteAMFString(*this, value.GetValue()); } // Writes an AMFArrayValue to BitStream template<> void RakNet::BitStream::Write(AMFArrayValue& value) { uint32_t denseSize = value.GetDense().size(); - WriteFlagNumber(this, denseSize); + WriteFlagNumber(*this, denseSize); auto it = value.GetAssociative().begin(); auto end = value.GetAssociative().end(); while (it != end) { - WriteAMFString(this, it->first); + WriteAMFString(*this, it->first); this->Write(*it->second); it++; } diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index 5300a4f2..d020ff72 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -8,11 +8,9 @@ set(DCOMMON_SOURCES "Game.cpp" "GeneralUtils.cpp" "LDFFormat.cpp" - "MD5.cpp" "Metrics.cpp" "NiPoint3.cpp" "NiQuaternion.cpp" - "SHA512.cpp" "Demangler.cpp" "ZCompression.cpp" "BrickByBrickFix.cpp" @@ -20,17 +18,27 @@ set(DCOMMON_SOURCES "FdbToSqlite.cpp" ) +# Workaround for compiler bug where the optimized code could result in a memcpy of 0 bytes, even though that isnt possible. +# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=97185 +if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + set_source_files_properties("FdbToSqlite.cpp" PROPERTIES COMPILE_FLAGS "-Wno-stringop-overflow") +endif() + add_subdirectory(dClient) foreach(file ${DCOMMON_DCLIENT_SOURCES}) set(DCOMMON_SOURCES ${DCOMMON_SOURCES} "dClient/${file}") endforeach() -include_directories(${PROJECT_SOURCE_DIR}/dCommon/) - add_library(dCommon STATIC ${DCOMMON_SOURCES}) - -target_link_libraries(dCommon bcrypt dDatabase tinyxml2) +target_include_directories(dCommon + PUBLIC "." "dClient" "dEnums" + PRIVATE + "${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase" + "${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase/ITables" + "${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase" + "${PROJECT_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/include" +) if (UNIX) find_package(ZLIB REQUIRED) @@ -61,4 +69,6 @@ else () ) endif () -target_link_libraries(dCommon ZLIB::ZLIB) +target_link_libraries(dCommon + PRIVATE ZLIB::ZLIB bcrypt tinyxml2 + INTERFACE dDatabase) diff --git a/dCommon/GeneralUtils.cpp b/dCommon/GeneralUtils.cpp index b45165fa..27ebfb2c 100644 --- a/dCommon/GeneralUtils.cpp +++ b/dCommon/GeneralUtils.cpp @@ -278,14 +278,14 @@ std::vector GeneralUtils::SplitString(const std::string& str, char return vector; } -std::u16string GeneralUtils::ReadWString(RakNet::BitStream* inStream) { +std::u16string GeneralUtils::ReadWString(RakNet::BitStream& inStream) { uint32_t length; - inStream->Read(length); + inStream.Read(length); std::u16string string; for (auto i = 0; i < length; i++) { uint16_t c; - inStream->Read(c); + inStream.Read(c); string.push_back(c); } @@ -294,32 +294,50 @@ std::u16string GeneralUtils::ReadWString(RakNet::BitStream* inStream) { std::vector GeneralUtils::GetSqlFileNamesFromFolder(const std::string& folder) { // Because we dont know how large the initial number before the first _ is we need to make it a map like so. - std::map filenames{}; + std::map filenames{}; for (auto& t : std::filesystem::directory_iterator(folder)) { - auto filename = t.path().filename().string(); - auto index = std::stoi(GeneralUtils::SplitString(filename, '_').at(0)); - filenames.insert(std::make_pair(index, filename)); + auto filename = t.path().filename().string(); + auto index = std::stoi(GeneralUtils::SplitString(filename, '_').at(0)); + filenames.insert(std::make_pair(index, filename)); } // Now sort the map by the oldest migration. std::vector sortedFiles{}; - auto fileIterator = filenames.begin(); - std::map::iterator oldest = filenames.begin(); - while (!filenames.empty()) { + auto fileIterator = filenames.begin(); + std::map::iterator oldest = filenames.begin(); + while (!filenames.empty()) { if (fileIterator == filenames.end()) { - sortedFiles.push_back(oldest->second); - filenames.erase(oldest); - fileIterator = filenames.begin(); - oldest = filenames.begin(); - continue; + sortedFiles.push_back(oldest->second); + filenames.erase(oldest); + fileIterator = filenames.begin(); + oldest = filenames.begin(); + continue; } - if (oldest->first > fileIterator->first) oldest = fileIterator; - fileIterator++; + if (oldest->first > fileIterator->first) oldest = fileIterator; + fileIterator++; } return sortedFiles; } -bool GeneralUtils::TryParse(const std::string& x, const std::string& y, const std::string& z, NiPoint3& dst) { - return TryParse(x.c_str(), dst.x) && TryParse(y.c_str(), dst.y) && TryParse(z.c_str(), dst.z); +#ifdef DARKFLAME_PLATFORM_MACOS + +// MacOS floating-point parse function specializations +namespace GeneralUtils::details { + template <> + [[nodiscard]] float _parse(const std::string_view str, size_t& parseNum) { + return std::stof(std::string{ str }, &parseNum); + } + + template <> + [[nodiscard]] double _parse(const std::string_view str, size_t& parseNum) { + return std::stod(std::string{ str }, &parseNum); + } + + template <> + [[nodiscard]] long double _parse(const std::string_view str, size_t& parseNum) { + return std::stold(std::string{ str }, &parseNum); + } } + +#endif diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index 37291ab8..c3422b05 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -1,17 +1,20 @@ #pragma once // C++ -#include +#include +#include #include -#include +#include #include -#include +#include +#include #include #include #include #include "BitStream.h" #include "NiPoint3.h" +#include "dPlatforms.h" #include "Game.h" #include "Logger.h" @@ -113,7 +116,7 @@ namespace GeneralUtils { bool ReplaceInString(std::string& str, const std::string& from, const std::string& to); - std::u16string ReadWString(RakNet::BitStream* inStream); + std::u16string ReadWString(RakNet::BitStream& inStream); std::vector SplitString(std::wstring& str, wchar_t delimiter); @@ -123,90 +126,111 @@ namespace GeneralUtils { std::vector GetSqlFileNamesFromFolder(const std::string& folder); + // Concept constraining to enum types template - T Parse(const char* value); + concept Enum = std::is_enum_v; - template <> - inline bool Parse(const char* value) { - return std::stoi(value); + // Concept constraining to numeric types + template + concept Numeric = std::integral || Enum || std::floating_point; + + // Concept trickery to enable parsing underlying numeric types + template + struct numeric_parse { using type = T; }; + + // If an enum, present an alias to its underlying type for parsing + template requires Enum + struct numeric_parse { using type = std::underlying_type_t; }; + + // If a boolean, present an alias to an intermediate integral type for parsing + template requires std::same_as + struct numeric_parse { using type = uint32_t; }; + + // Shorthand type alias + template + using numeric_parse_t = numeric_parse::type; + + /** + * For numeric values: Parses a string_view and returns an optional variable depending on the result. + * @param str The string_view to be evaluated + * @returns An std::optional containing the desired value if it is equivalent to the string + */ + template + [[nodiscard]] std::optional TryParse(const std::string_view str) { + numeric_parse_t result; + + const char* const strEnd = str.data() + str.size(); + const auto [parseEnd, ec] = std::from_chars(str.data(), strEnd, result); + const bool isParsed = parseEnd == strEnd && ec == std::errc{}; + + return isParsed ? static_cast(result) : std::optional{}; } - template <> - inline int32_t Parse(const char* value) { - return std::stoi(value); +#ifdef DARKFLAME_PLATFORM_MACOS + + // MacOS floating-point parse helper function specializations + namespace details { + template + [[nodiscard]] T _parse(const std::string_view str, size_t& parseNum); } - template <> - inline int64_t Parse(const char* value) { - return std::stoll(value); + /** + * For floating-point values: Parses a string_view and returns an optional variable depending on the result. + * Note that this function overload is only included for MacOS, as from_chars will fulfill its purpose otherwise. + * @param str The string_view to be evaluated + * @returns An std::optional containing the desired value if it is equivalent to the string + */ + template + [[nodiscard]] std::optional TryParse(const std::string_view str) noexcept + try { + size_t parseNum; + const T result = details::_parse(str, parseNum); + const bool isParsed = str.length() == parseNum; + + return isParsed ? result : std::optional{}; + } catch (...) { + return std::nullopt; } - template <> - inline float Parse(const char* value) { - return std::stof(value); +#endif + + /** + * The TryParse overload for handling NiPoint3 by passing 3 seperate string references + * @param strX The string representing the X coordinate + * @param strY The string representing the Y coordinate + * @param strZ The string representing the Z coordinate + * @returns An std::optional containing the desired NiPoint3 if it can be constructed from the string parameters + */ + template + [[nodiscard]] std::optional TryParse(const std::string& strX, const std::string& strY, const std::string& strZ) { + const auto x = TryParse(strX); + if (!x) return std::nullopt; + + const auto y = TryParse(strY); + if (!y) return std::nullopt; + + const auto z = TryParse(strZ); + return z ? std::make_optional(x.value(), y.value(), z.value()) : std::nullopt; } - template <> - inline double Parse(const char* value) { - return std::stod(value); - } - - template <> - inline uint16_t Parse(const char* value) { - return std::stoul(value); - } - - template <> - inline uint32_t Parse(const char* value) { - return std::stoul(value); - } - - template <> - inline uint64_t Parse(const char* value) { - return std::stoull(value); - } - - template <> - inline eInventoryType Parse(const char* value) { - return static_cast(std::stoul(value)); - } - - template <> - inline eReplicaComponentType Parse(const char* value) { - return static_cast(std::stoul(value)); + /** + * The TryParse overload for handling NiPoint3 by passingn a reference to a vector of three strings + * @param str The string vector representing the X, Y, and Xcoordinates + * @returns An std::optional containing the desired NiPoint3 if it can be constructed from the string parameters + */ + template + [[nodiscard]] std::optional TryParse(const std::vector& str) { + return (str.size() == 3) ? TryParse(str[0], str[1], str[2]) : std::nullopt; } template - bool TryParse(const char* value, T& dst) { - try { - dst = Parse(value); - - return true; - } catch (...) { - return false; - } - } - - template - T Parse(const std::string& value) { - return Parse(value.c_str()); - } - - template - bool TryParse(const std::string& value, T& dst) { - return TryParse(value.c_str(), dst); - } - - bool TryParse(const std::string& x, const std::string& y, const std::string& z, NiPoint3& dst); - - template std::u16string to_u16string(T value) { return GeneralUtils::ASCIIToUTF16(std::to_string(value)); } // From boost::hash_combine template - void hash_combine(std::size_t& s, const T& v) { + constexpr void hash_combine(std::size_t& s, const T& v) { std::hash h; s ^= h(v) + 0x9e3779b9 + (s << 6) + (s >> 2); } @@ -239,11 +263,9 @@ namespace GeneralUtils { * @param entry Enum entry to cast * @returns The enum entry's value in its underlying type */ - template - inline constexpr typename std::underlying_type_t CastUnderlyingType(const eType entry) { - static_assert(std::is_enum_v, "Not an enum"); - - return static_cast>(entry); + template + constexpr std::underlying_type_t ToUnderlying(const eType entry) noexcept { + return static_cast>(entry); } // on Windows we need to undef these or else they conflict with our numeric limits calls diff --git a/dCommon/LDFFormat.cpp b/dCommon/LDFFormat.cpp index 67f6a630..da28ae6e 100644 --- a/dCommon/LDFFormat.cpp +++ b/dCommon/LDFFormat.cpp @@ -61,33 +61,33 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } case LDF_TYPE_S32: { - int32_t data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid int32 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } case LDF_TYPE_FLOAT: { - float data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid float value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } case LDF_TYPE_DOUBLE: { - double data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid double value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } @@ -100,10 +100,12 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } else if (ldfTypeAndValue.second == "false") { data = 0; } else { - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto dataOptional = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!dataOptional) { LOG("Warning: Attempted to process invalid uint32 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } + data = dataOptional.value(); } returnValue = new LDFData(key, data); @@ -118,10 +120,12 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } else if (ldfTypeAndValue.second == "false") { data = false; } else { - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto dataOptional = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!dataOptional) { LOG("Warning: Attempted to process invalid bool value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } + data = dataOptional.value(); } returnValue = new LDFData(key, data); @@ -129,22 +133,22 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } case LDF_TYPE_U64: { - uint64_t data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid uint64 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } case LDF_TYPE_OBJID: { - LWOOBJID data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid LWOOBJID value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } diff --git a/dCommon/LDFFormat.h b/dCommon/LDFFormat.h index 7bcc91a2..2cd9156c 100644 --- a/dCommon/LDFFormat.h +++ b/dCommon/LDFFormat.h @@ -31,7 +31,7 @@ public: virtual ~LDFBaseData() {} - virtual void WriteToPacket(RakNet::BitStream* packet) = 0; + virtual void WriteToPacket(RakNet::BitStream& packet) = 0; virtual const std::u16string& GetKey() = 0; @@ -62,17 +62,17 @@ private: T value; //! Writes the key to the packet - void WriteKey(RakNet::BitStream* packet) { - packet->Write(this->key.length() * sizeof(uint16_t)); + void WriteKey(RakNet::BitStream& packet) { + packet.Write(this->key.length() * sizeof(uint16_t)); for (uint32_t i = 0; i < this->key.length(); ++i) { - packet->Write(this->key[i]); + packet.Write(this->key[i]); } } //! Writes the value to the packet - void WriteValue(RakNet::BitStream* packet) { - packet->Write(this->GetValueType()); - packet->Write(this->value); + void WriteValue(RakNet::BitStream& packet) { + packet.Write(this->GetValueType()); + packet.Write(this->value); } public: @@ -108,7 +108,7 @@ public: /*! \param packet The packet */ - void WriteToPacket(RakNet::BitStream* packet) override { + void WriteToPacket(RakNet::BitStream& packet) override { this->WriteKey(packet); this->WriteValue(packet); } @@ -162,7 +162,7 @@ public: return new LDFData(key, value); } - inline static T Default = {}; + inline static const T Default = {}; }; // LDF Types @@ -178,31 +178,31 @@ template<> inline eLDFType LDFData::GetValueType(void) { return LDF // The specialized version for std::u16string (UTF-16) template<> -inline void LDFData::WriteValue(RakNet::BitStream* packet) { - packet->Write(this->GetValueType()); +inline void LDFData::WriteValue(RakNet::BitStream& packet) { + packet.Write(this->GetValueType()); - packet->Write(this->value.length()); + packet.Write(this->value.length()); for (uint32_t i = 0; i < this->value.length(); ++i) { - packet->Write(this->value[i]); + packet.Write(this->value[i]); } } // The specialized version for bool template<> -inline void LDFData::WriteValue(RakNet::BitStream* packet) { - packet->Write(this->GetValueType()); +inline void LDFData::WriteValue(RakNet::BitStream& packet) { + packet.Write(this->GetValueType()); - packet->Write(this->value); + packet.Write(this->value); } // The specialized version for std::string (UTF-8) template<> -inline void LDFData::WriteValue(RakNet::BitStream* packet) { - packet->Write(this->GetValueType()); +inline void LDFData::WriteValue(RakNet::BitStream& packet) { + packet.Write(this->GetValueType()); - packet->Write(this->value.length()); + packet.Write(this->value.length()); for (uint32_t i = 0; i < this->value.length(); ++i) { - packet->Write(this->value[i]); + packet.Write(this->value[i]); } } diff --git a/dCommon/NiPoint3.cpp b/dCommon/NiPoint3.cpp index 3394deb7..b8546fdd 100644 --- a/dCommon/NiPoint3.cpp +++ b/dCommon/NiPoint3.cpp @@ -1,210 +1,24 @@ #include "NiPoint3.h" -#include "NiQuaternion.h" // C++ #include -// Static Variables -const NiPoint3 NiPoint3::ZERO(0.0f, 0.0f, 0.0f); -const NiPoint3 NiPoint3::UNIT_X(1.0f, 0.0f, 0.0f); -const NiPoint3 NiPoint3::UNIT_Y(0.0f, 1.0f, 0.0f); -const NiPoint3 NiPoint3::UNIT_Z(0.0f, 0.0f, 1.0f); -const NiPoint3 NiPoint3::UNIT_ALL(1.0f, 1.0f, 1.0f); - -//! Initializer -NiPoint3::NiPoint3(void) { - this->x = 0; - this->y = 0; - this->z = 0; -} - -//! Initializer -NiPoint3::NiPoint3(float x, float y, float z) { - this->x = x; - this->y = y; - this->z = z; -} - -//! Copy Constructor -NiPoint3::NiPoint3(const NiPoint3& point) { - this->x = point.x; - this->y = point.y; - this->z = point.z; -} - -//! Destructor -NiPoint3::~NiPoint3(void) {} - -// MARK: Getters / Setters - -//! Gets the X coordinate -float NiPoint3::GetX(void) const { - return this->x; -} - -//! Sets the X coordinate -void NiPoint3::SetX(float x) { - this->x = x; -} - -//! Gets the Y coordinate -float NiPoint3::GetY(void) const { - return this->y; -} - -//! Sets the Y coordinate -void NiPoint3::SetY(float y) { - this->y = y; -} - -//! Gets the Z coordinate -float NiPoint3::GetZ(void) const { - return this->z; -} - -//! Sets the Z coordinate -void NiPoint3::SetZ(float z) { - this->z = z; -} - -// MARK: Functions +// MARK: Member Functions //! Gets the length of the vector -float NiPoint3::Length(void) const { - return sqrt(x * x + y * y + z * z); -} - -//! Gets the squared length of a vector -float NiPoint3::SquaredLength(void) const { - return (x * x + y * y + z * z); -} - -//! Returns the dot product of the vector dotted with another vector -float NiPoint3::DotProduct(const Vector3& vec) const { - return ((this->x * vec.x) + (this->y * vec.y) + (this->z * vec.z)); -} - -//! Returns the cross product of the vector crossed with another vector -Vector3 NiPoint3::CrossProduct(const Vector3& vec) const { - return Vector3(((this->y * vec.z) - (this->z * vec.y)), - ((this->z * vec.x) - (this->x * vec.z)), - ((this->x * vec.y) - (this->y * vec.x))); +float NiPoint3::Length() const { + return std::sqrt(x * x + y * y + z * z); } //! Unitize the vector -NiPoint3 NiPoint3::Unitize(void) const { +NiPoint3 NiPoint3::Unitize() const { float length = this->Length(); - return length != 0 ? *this / length : NiPoint3::ZERO; + return length != 0 ? *this / length : NiPoint3Constant::ZERO; } - -// MARK: Operators - -//! Operator to check for equality -bool NiPoint3::operator==(const NiPoint3& point) const { - return point.x == this->x && point.y == this->y && point.z == this->z; -} - -//! Operator to check for inequality -bool NiPoint3::operator!=(const NiPoint3& point) const { - return !(*this == point); -} - -//! Operator for subscripting -float& NiPoint3::operator[](int i) { - float* base = &x; - return base[i]; -} - -//! Operator for subscripting -const float& NiPoint3::operator[](int i) const { - const float* base = &x; - return base[i]; -} - -//! Operator for addition of vectors -NiPoint3 NiPoint3::operator+(const NiPoint3& point) const { - return NiPoint3(this->x + point.x, this->y + point.y, this->z + point.z); -} - -//! Operator for addition of vectors -NiPoint3& NiPoint3::operator+=(const NiPoint3& point) { - this->x += point.x; - this->y += point.y; - this->z += point.z; - return *this; -} - -NiPoint3& NiPoint3::operator*=(const float scalar) { - this->x *= scalar; - this->y *= scalar; - this->z *= scalar; - return *this; -} - -//! Operator for subtraction of vectors -NiPoint3 NiPoint3::operator-(const NiPoint3& point) const { - return NiPoint3(this->x - point.x, this->y - point.y, this->z - point.z); -} - -//! Operator for addition of a scalar on all vector components -NiPoint3 NiPoint3::operator+(float fScalar) const { - return NiPoint3(this->x + fScalar, this->y + fScalar, this->z + fScalar); -} - -//! Operator for subtraction of a scalar on all vector components -NiPoint3 NiPoint3::operator-(float fScalar) const { - return NiPoint3(this->x - fScalar, this->y - fScalar, this->z - fScalar); -} - -//! Operator for scalar multiplication of a vector -NiPoint3 NiPoint3::operator*(float fScalar) const { - return NiPoint3(this->x * fScalar, this->y * fScalar, this->z * fScalar); -} - -//! Operator for scalar division of a vector -NiPoint3 NiPoint3::operator/(float fScalar) const { - float retX = this->x != 0 ? this->x / fScalar : 0; - float retY = this->y != 0 ? this->y / fScalar : 0; - float retZ = this->z != 0 ? this->z / fScalar : 0; - return NiPoint3(retX, retY, retZ); -} - - // MARK: Helper Functions -//! Checks to see if the point (or vector) is with an Axis-Aligned Bounding Box -bool NiPoint3::IsWithinAxisAlignedBox(const NiPoint3& minPoint, const NiPoint3& maxPoint) { - if (this->x < minPoint.x) return false; - if (this->x > maxPoint.x) return false; - if (this->y < minPoint.y) return false; - if (this->y > maxPoint.y) return false; - - return (this->z < maxPoint.z && this->z > minPoint.z); -} - -//! Checks to see if the point (or vector) is within a sphere -bool NiPoint3::IsWithinSpehere(const NiPoint3& sphereCenter, float radius) { - Vector3 diffVec = Vector3(x - sphereCenter.GetX(), y - sphereCenter.GetY(), z - sphereCenter.GetZ()); - return (diffVec.SquaredLength() <= (radius * radius)); -} - -NiPoint3 NiPoint3::ClosestPointOnLine(const NiPoint3& a, const NiPoint3& b, const NiPoint3& p) { - if (a == b) return a; - - const auto pa = p - a; - const auto ab = b - a; - - const auto t = pa.DotProduct(ab) / ab.SquaredLength(); - - if (t <= 0.0f) return a; - - if (t >= 1.0f) return b; - - return a + ab * t; -} - float NiPoint3::Angle(const NiPoint3& a, const NiPoint3& b) { const auto dot = a.DotProduct(b); const auto lenA = a.SquaredLength(); @@ -220,15 +34,7 @@ float NiPoint3::Distance(const NiPoint3& a, const NiPoint3& b) { return std::sqrt(dx * dx + dy * dy + dz * dz); } -float NiPoint3::DistanceSquared(const NiPoint3& a, const NiPoint3& b) { - const auto dx = a.x - b.x; - const auto dy = a.y - b.y; - const auto dz = a.z - b.z; - - return dx * dx + dy * dy + dz * dz; -} - -NiPoint3 NiPoint3::MoveTowards(const NiPoint3& current, const NiPoint3& target, float maxDistanceDelta) { +NiPoint3 NiPoint3::MoveTowards(const NiPoint3& current, const NiPoint3& target, const float maxDistanceDelta) { float dx = target.x - current.x; float dy = target.y - current.y; float dz = target.z - current.z; @@ -249,29 +55,3 @@ NiPoint3 NiPoint3::MoveTowards(const NiPoint3& current, const NiPoint3& target, float length = std::sqrt(lengthSquared); return NiPoint3(current.x + dx / length * maxDistanceDelta, current.y + dy / length * maxDistanceDelta, current.z + dz / length * maxDistanceDelta); } - -//This code is yoinked from the MS XNA code, so it should be right, even if it's horrible. -NiPoint3 NiPoint3::RotateByQuaternion(const NiQuaternion& rotation) { - Vector3 vector; - float num12 = rotation.x + rotation.x; - float num2 = rotation.y + rotation.y; - float num = rotation.z + rotation.z; - float num11 = rotation.w * num12; - float num10 = rotation.w * num2; - float num9 = rotation.w * num; - float num8 = rotation.x * num12; - float num7 = rotation.x * num2; - float num6 = rotation.x * num; - float num5 = rotation.y * num2; - float num4 = rotation.y * num; - float num3 = rotation.z * num; - - NiPoint3 value = *this; - float num15 = ((value.x * ((1.0f - num5) - num3)) + (value.y * (num7 - num9))) + (value.z * (num6 + num10)); - float num14 = ((value.x * (num7 + num9)) + (value.y * ((1.0f - num8) - num3))) + (value.z * (num4 - num11)); - float num13 = ((value.x * (num6 - num10)) + (value.y * (num4 + num11))) + (value.z * ((1.0f - num8) - num5)); - vector.x = num15; - vector.y = num14; - vector.z = num13; - return vector; -} diff --git a/dCommon/NiPoint3.h b/dCommon/NiPoint3.h index 44c3c383..00d09083 100644 --- a/dCommon/NiPoint3.h +++ b/dCommon/NiPoint3.h @@ -1,4 +1,5 @@ -#pragma once +#ifndef __NIPOINT3_H__ +#define __NIPOINT3_H__ /*! \file NiPoint3.hpp @@ -12,13 +13,13 @@ typedef NiPoint3 Vector3; //!< The Vector3 class is technically the NiPoin //! A custom class the defines a point in space class NiPoint3 { public: - float x; //!< The x position - float y; //!< The y position - float z; //!< The z position + float x{ 0 }; //!< The x position + float y{ 0 }; //!< The y position + float z{ 0 }; //!< The z position //! Initializer - NiPoint3(void); + constexpr NiPoint3() = default; //! Initializer /*! @@ -26,23 +27,21 @@ public: \param y The y coordinate \param z The z coordinate */ - NiPoint3(float x, float y, float z); + constexpr NiPoint3(const float x, const float y, const float z) noexcept + : x{ x } + , y{ y } + , z{ z } { + } //! Copy Constructor /*! \param point The point to copy */ - NiPoint3(const NiPoint3& point); - - //! Destructor - ~NiPoint3(void); - - // MARK: Constants - static const NiPoint3 ZERO; //!< Point(0, 0, 0) - static const NiPoint3 UNIT_X; //!< Point(1, 0, 0) - static const NiPoint3 UNIT_Y; //!< Point(0, 1, 0) - static const NiPoint3 UNIT_Z; //!< Point(0, 0, 1) - static const NiPoint3 UNIT_ALL; //!< Point(1, 1, 1) + constexpr NiPoint3(const NiPoint3& point) noexcept + : x{ point.x } + , y{ point.y } + , z{ point.z } { + } // MARK: Getters / Setters @@ -50,38 +49,37 @@ public: /*! \return The x coordinate */ - float GetX(void) const; + [[nodiscard]] constexpr float GetX() const noexcept; //! Sets the X coordinate /*! \param x The x coordinate */ - void SetX(float x); + constexpr void SetX(const float x) noexcept; //! Gets the Y coordinate /*! \return The y coordinate */ - float GetY(void) const; + [[nodiscard]] constexpr float GetY() const noexcept; //! Sets the Y coordinate /*! \param y The y coordinate */ - void SetY(float y); + constexpr void SetY(const float y) noexcept; //! Gets the Z coordinate /*! \return The z coordinate */ - float GetZ(void) const; + [[nodiscard]] constexpr float GetZ() const noexcept; //! Sets the Z coordinate /*! \param z The z coordinate */ - void SetZ(float z); - + constexpr void SetZ(const float z) noexcept; // MARK: Member Functions @@ -89,72 +87,70 @@ public: /*! \return The scalar length of the vector */ - float Length(void) const; + [[nodiscard]] float Length() const; //! Gets the squared length of a vector /*! \return The squared length of a vector */ - float SquaredLength(void) const; + [[nodiscard]] constexpr float SquaredLength() const noexcept; //! Returns the dot product of the vector dotted with another vector /*! \param vec The second vector \return The dot product of the two vectors */ - float DotProduct(const Vector3& vec) const; + [[nodiscard]] constexpr float DotProduct(const Vector3& vec) const noexcept; //! Returns the cross product of the vector crossed with another vector /*! \param vec The second vector \return The cross product of the two vectors */ - Vector3 CrossProduct(const Vector3& vec) const; + [[nodiscard]] constexpr Vector3 CrossProduct(const Vector3& vec) const noexcept; //! Unitize the vector /*! \returns The current vector */ - NiPoint3 Unitize(void) const; - + [[nodiscard]] NiPoint3 Unitize() const; // MARK: Operators //! Operator to check for equality - bool operator==(const NiPoint3& point) const; + constexpr bool operator==(const NiPoint3& point) const noexcept; //! Operator to check for inequality - bool operator!=(const NiPoint3& point) const; + constexpr bool operator!=(const NiPoint3& point) const noexcept; //! Operator for subscripting - float& operator[](int i); + constexpr float& operator[](const int i) noexcept; //! Operator for subscripting - const float& operator[](int i) const; + constexpr const float& operator[](const int i) const noexcept; //! Operator for addition of vectors - NiPoint3 operator+(const NiPoint3& point) const; + constexpr NiPoint3 operator+(const NiPoint3& point) const noexcept; //! Operator for addition of vectors - NiPoint3& operator+=(const NiPoint3& point); + constexpr NiPoint3& operator+=(const NiPoint3& point) noexcept; - NiPoint3& operator*=(const float scalar); + constexpr NiPoint3& operator*=(const float scalar) noexcept; //! Operator for subtraction of vectors - NiPoint3 operator-(const NiPoint3& point) const; + constexpr NiPoint3 operator-(const NiPoint3& point) const noexcept; //! Operator for addition of a scalar on all vector components - NiPoint3 operator+(float fScalar) const; + constexpr NiPoint3 operator+(const float fScalar) const noexcept; //! Operator for subtraction of a scalar on all vector components - NiPoint3 operator-(float fScalar) const; + constexpr NiPoint3 operator-(const float fScalar) const noexcept; //! Operator for scalar multiplication of a vector - NiPoint3 operator*(float fScalar) const; + constexpr NiPoint3 operator*(const float fScalar) const noexcept; //! Operator for scalar division of a vector - NiPoint3 operator/(float fScalar) const; - + constexpr NiPoint3 operator/(const float fScalar) const noexcept; // MARK: Helper Functions @@ -164,14 +160,14 @@ public: \param maxPoint The maximum point of the bounding box \return Whether or not this point lies within the box */ - bool IsWithinAxisAlignedBox(const NiPoint3& minPoint, const NiPoint3& maxPoint); + [[nodiscard]] constexpr bool IsWithinAxisAlignedBox(const NiPoint3& minPoint, const NiPoint3& maxPoint) noexcept; //! Checks to see if the point (or vector) is within a sphere /*! \param sphereCenter The sphere center \param radius The radius */ - bool IsWithinSpehere(const NiPoint3& sphereCenter, float radius); + [[nodiscard]] constexpr bool IsWithinSphere(const NiPoint3& sphereCenter, const float radius) noexcept; /*! \param a Start of line @@ -179,15 +175,30 @@ public: \param p Refrence point \return The point of line AB which is closest to P */ - static NiPoint3 ClosestPointOnLine(const NiPoint3& a, const NiPoint3& b, const NiPoint3& p); + [[nodiscard]] static constexpr NiPoint3 ClosestPointOnLine(const NiPoint3& a, const NiPoint3& b, const NiPoint3& p) noexcept; - static float Angle(const NiPoint3& a, const NiPoint3& b); + [[nodiscard]] static float Angle(const NiPoint3& a, const NiPoint3& b); - static float Distance(const NiPoint3& a, const NiPoint3& b); + [[nodiscard]] static float Distance(const NiPoint3& a, const NiPoint3& b); - static float DistanceSquared(const NiPoint3& a, const NiPoint3& b); + [[nodiscard]] static constexpr float DistanceSquared(const NiPoint3& a, const NiPoint3& b) noexcept; - static NiPoint3 MoveTowards(const NiPoint3& current, const NiPoint3& target, float maxDistanceDelta); + [[nodiscard]] static NiPoint3 MoveTowards(const NiPoint3& current, const NiPoint3& target, const float maxDistanceDelta); - NiPoint3 RotateByQuaternion(const NiQuaternion& rotation); + //This code is yoinked from the MS XNA code, so it should be right, even if it's horrible. + [[nodiscard]] constexpr NiPoint3 RotateByQuaternion(const NiQuaternion& rotation) noexcept; }; + +// Static Variables +namespace NiPoint3Constant { + constexpr NiPoint3 ZERO(0.0f, 0.0f, 0.0f); + constexpr NiPoint3 UNIT_X(1.0f, 0.0f, 0.0f); + constexpr NiPoint3 UNIT_Y(0.0f, 1.0f, 0.0f); + constexpr NiPoint3 UNIT_Z(0.0f, 0.0f, 1.0f); + constexpr NiPoint3 UNIT_ALL(1.0f, 1.0f, 1.0f); +} + +// .inl file needed for code organization and to circumvent circular dependency issues +#include "NiPoint3.inl" + +#endif // !__NIPOINT3_H__ diff --git a/dCommon/NiPoint3.inl b/dCommon/NiPoint3.inl new file mode 100644 index 00000000..48aa3ae1 --- /dev/null +++ b/dCommon/NiPoint3.inl @@ -0,0 +1,196 @@ +#pragma once +#ifndef __NIPOINT3_H__ +#error "This should only be included inline in NiPoint3.h: Do not include directly!" +#endif + +#include "NiQuaternion.h" + +// MARK: Getters / Setters + +//! Gets the X coordinate +constexpr float NiPoint3::GetX() const noexcept { + return this->x; +} + +//! Sets the X coordinate +constexpr void NiPoint3::SetX(const float x) noexcept { + this->x = x; +} + +//! Gets the Y coordinate +constexpr float NiPoint3::GetY() const noexcept { + return this->y; +} + +//! Sets the Y coordinate +constexpr void NiPoint3::SetY(const float y) noexcept { + this->y = y; +} + +//! Gets the Z coordinate +constexpr float NiPoint3::GetZ() const noexcept { + return this->z; +} + +//! Sets the Z coordinate +constexpr void NiPoint3::SetZ(const float z) noexcept { + this->z = z; +} + +// MARK: Member Functions + +//! Gets the squared length of a vector +constexpr float NiPoint3::SquaredLength() const noexcept { + return (x * x + y * y + z * z); +} + +//! Returns the dot product of the vector dotted with another vector +constexpr float NiPoint3::DotProduct(const Vector3& vec) const noexcept { + return ((this->x * vec.x) + (this->y * vec.y) + (this->z * vec.z)); +} + +//! Returns the cross product of the vector crossed with another vector +constexpr Vector3 NiPoint3::CrossProduct(const Vector3& vec) const noexcept { + return Vector3(((this->y * vec.z) - (this->z * vec.y)), + ((this->z * vec.x) - (this->x * vec.z)), + ((this->x * vec.y) - (this->y * vec.x))); +} + +// MARK: Operators + +//! Operator to check for equality +constexpr bool NiPoint3::operator==(const NiPoint3& point) const noexcept { + return point.x == this->x && point.y == this->y && point.z == this->z; +} + +//! Operator to check for inequality +constexpr bool NiPoint3::operator!=(const NiPoint3& point) const noexcept { + return !(*this == point); +} + +//! Operator for subscripting +constexpr float& NiPoint3::operator[](const int i) noexcept { + float* base = &x; + return base[i]; +} + +//! Operator for subscripting +constexpr const float& NiPoint3::operator[](const int i) const noexcept { + const float* base = &x; + return base[i]; +} + +//! Operator for addition of vectors +constexpr NiPoint3 NiPoint3::operator+(const NiPoint3& point) const noexcept { + return NiPoint3(this->x + point.x, this->y + point.y, this->z + point.z); +} + +//! Operator for addition of vectors +constexpr NiPoint3& NiPoint3::operator+=(const NiPoint3& point) noexcept { + this->x += point.x; + this->y += point.y; + this->z += point.z; + return *this; +} + +constexpr NiPoint3& NiPoint3::operator*=(const float scalar) noexcept { + this->x *= scalar; + this->y *= scalar; + this->z *= scalar; + return *this; +} + +//! Operator for subtraction of vectors +constexpr NiPoint3 NiPoint3::operator-(const NiPoint3& point) const noexcept { + return NiPoint3(this->x - point.x, this->y - point.y, this->z - point.z); +} + +//! Operator for addition of a scalar on all vector components +constexpr NiPoint3 NiPoint3::operator+(const float fScalar) const noexcept { + return NiPoint3(this->x + fScalar, this->y + fScalar, this->z + fScalar); +} + +//! Operator for subtraction of a scalar on all vector components +constexpr NiPoint3 NiPoint3::operator-(const float fScalar) const noexcept { + return NiPoint3(this->x - fScalar, this->y - fScalar, this->z - fScalar); +} + +//! Operator for scalar multiplication of a vector +constexpr NiPoint3 NiPoint3::operator*(const float fScalar) const noexcept { + return NiPoint3(this->x * fScalar, this->y * fScalar, this->z * fScalar); +} + +//! Operator for scalar division of a vector +constexpr NiPoint3 NiPoint3::operator/(const float fScalar) const noexcept { + float retX = this->x != 0 ? this->x / fScalar : 0; + float retY = this->y != 0 ? this->y / fScalar : 0; + float retZ = this->z != 0 ? this->z / fScalar : 0; + return NiPoint3(retX, retY, retZ); +} + +// MARK: Helper Functions + +//! Checks to see if the point (or vector) is with an Axis-Aligned Bounding Box +constexpr bool NiPoint3::IsWithinAxisAlignedBox(const NiPoint3& minPoint, const NiPoint3& maxPoint) noexcept { + if (this->x < minPoint.x) return false; + if (this->x > maxPoint.x) return false; + if (this->y < minPoint.y) return false; + if (this->y > maxPoint.y) return false; + + return (this->z < maxPoint.z && this->z > minPoint.z); +} + +//! Checks to see if the point (or vector) is within a sphere +constexpr bool NiPoint3::IsWithinSphere(const NiPoint3& sphereCenter, const float radius) noexcept { + Vector3 diffVec = Vector3(x - sphereCenter.GetX(), y - sphereCenter.GetY(), z - sphereCenter.GetZ()); + return (diffVec.SquaredLength() <= (radius * radius)); +} + +constexpr NiPoint3 NiPoint3::ClosestPointOnLine(const NiPoint3& a, const NiPoint3& b, const NiPoint3& p) noexcept { + if (a == b) return a; + + const auto pa = p - a; + const auto ab = b - a; + + const auto t = pa.DotProduct(ab) / ab.SquaredLength(); + + if (t <= 0.0f) return a; + + if (t >= 1.0f) return b; + + return a + ab * t; +} + +constexpr float NiPoint3::DistanceSquared(const NiPoint3& a, const NiPoint3& b) noexcept { + const auto dx = a.x - b.x; + const auto dy = a.y - b.y; + const auto dz = a.z - b.z; + + return dx * dx + dy * dy + dz * dz; +} + +//This code is yoinked from the MS XNA code, so it should be right, even if it's horrible. +constexpr NiPoint3 NiPoint3::RotateByQuaternion(const NiQuaternion& rotation) noexcept { + Vector3 vector; + float num12 = rotation.x + rotation.x; + float num2 = rotation.y + rotation.y; + float num = rotation.z + rotation.z; + float num11 = rotation.w * num12; + float num10 = rotation.w * num2; + float num9 = rotation.w * num; + float num8 = rotation.x * num12; + float num7 = rotation.x * num2; + float num6 = rotation.x * num; + float num5 = rotation.y * num2; + float num4 = rotation.y * num; + float num3 = rotation.z * num; + + NiPoint3 value = *this; + float num15 = ((value.x * ((1.0f - num5) - num3)) + (value.y * (num7 - num9))) + (value.z * (num6 + num10)); + float num14 = ((value.x * (num7 + num9)) + (value.y * ((1.0f - num8) - num3))) + (value.z * (num4 - num11)); + float num13 = ((value.x * (num6 - num10)) + (value.y * (num4 + num11))) + (value.z * ((1.0f - num8) - num5)); + vector.x = num15; + vector.y = num14; + vector.z = num13; + return vector; +} diff --git a/dCommon/NiQuaternion.cpp b/dCommon/NiQuaternion.cpp index 33c5c976..b12d3991 100644 --- a/dCommon/NiQuaternion.cpp +++ b/dCommon/NiQuaternion.cpp @@ -3,89 +3,8 @@ // C++ #include -// Static Variables -const NiQuaternion NiQuaternion::IDENTITY(1, 0, 0, 0); - -//! The initializer -NiQuaternion::NiQuaternion(void) { - this->w = 1; - this->x = 0; - this->y = 0; - this->z = 0; -} - -//! The initializer -NiQuaternion::NiQuaternion(float w, float x, float y, float z) { - this->w = w; - this->x = x; - this->y = y; - this->z = z; -} - -//! Destructor -NiQuaternion::~NiQuaternion(void) {} - - -// MARK: Setters / Getters - -//! Gets the W coordinate -float NiQuaternion::GetW(void) const { - return this->w; -} - -//! Sets the W coordinate -void NiQuaternion::SetW(float w) { - this->w = w; -} - -//! Gets the X coordinate -float NiQuaternion::GetX(void) const { - return this->x; -} - -//! Sets the X coordinate -void NiQuaternion::SetX(float x) { - this->x = x; -} - -//! Gets the Y coordinate -float NiQuaternion::GetY(void) const { - return this->y; -} - -//! Sets the Y coordinate -void NiQuaternion::SetY(float y) { - this->y = y; -} - -//! Gets the Z coordinate -float NiQuaternion::GetZ(void) const { - return this->z; -} - -//! Sets the Z coordinate -void NiQuaternion::SetZ(float z) { - this->z = z; -} - - // MARK: Member Functions -//! Returns the forward vector from the quaternion -Vector3 NiQuaternion::GetForwardVector(void) const { - return Vector3(2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)); -} - -//! Returns the up vector from the quaternion -Vector3 NiQuaternion::GetUpVector(void) const { - return Vector3(2 * (x * y - w * z), 1 - 2 * (x * x + z * z), 2 * (y * z + w * x)); -} - -//! Returns the right vector from the quaternion -Vector3 NiQuaternion::GetRightVector(void) const { - return Vector3(1 - 2 * (y * y + z * z), 2 * (x * y + w * z), 2 * (x * z - w * y)); -} - Vector3 NiQuaternion::GetEulerAngles() const { Vector3 angles; @@ -111,22 +30,9 @@ Vector3 NiQuaternion::GetEulerAngles() const { return angles; } -// MARK: Operators - -//! Operator to check for equality -bool NiQuaternion::operator==(const NiQuaternion& rot) const { - return rot.x == this->x && rot.y == this->y && rot.z == this->z && rot.w == this->w; -} - -//! Operator to check for inequality -bool NiQuaternion::operator!=(const NiQuaternion& rot) const { - return !(*this == rot); -} - - // MARK: Helper Functions -//! Look from a specific point in space to another point in space +//! Look from a specific point in space to another point in space (Y-locked) NiQuaternion NiQuaternion::LookAt(const NiPoint3& sourcePoint, const NiPoint3& destPoint) { //To make sure we don't orient around the X/Z axis: NiPoint3 source = sourcePoint; @@ -136,7 +42,7 @@ NiQuaternion NiQuaternion::LookAt(const NiPoint3& sourcePoint, const NiPoint3& d NiPoint3 forwardVector = NiPoint3(dest - source).Unitize(); - NiPoint3 posZ = NiPoint3::UNIT_Z; + NiPoint3 posZ = NiPoint3Constant::UNIT_Z; NiPoint3 vecA = posZ.CrossProduct(forwardVector).Unitize(); float dot = posZ.DotProduct(forwardVector); @@ -148,10 +54,11 @@ NiQuaternion NiQuaternion::LookAt(const NiPoint3& sourcePoint, const NiPoint3& d return NiQuaternion::CreateFromAxisAngle(vecA, rotAngle); } +//! Look from a specific point in space to another point in space NiQuaternion NiQuaternion::LookAtUnlocked(const NiPoint3& sourcePoint, const NiPoint3& destPoint) { NiPoint3 forwardVector = NiPoint3(destPoint - sourcePoint).Unitize(); - NiPoint3 posZ = NiPoint3::UNIT_Z; + NiPoint3 posZ = NiPoint3Constant::UNIT_Z; NiPoint3 vecA = posZ.CrossProduct(forwardVector).Unitize(); float dot = posZ.DotProduct(forwardVector); diff --git a/dCommon/NiQuaternion.h b/dCommon/NiQuaternion.h index b7d60f4e..482b86fa 100644 --- a/dCommon/NiQuaternion.h +++ b/dCommon/NiQuaternion.h @@ -1,4 +1,5 @@ -#pragma once +#ifndef __NIQUATERNION_H__ +#define __NIQUATERNION_H__ // Custom Classes #include "NiPoint3.h" @@ -14,14 +15,14 @@ typedef NiQuaternion Quaternion; //!< A typedef for a shorthand version o //! A class that defines a rotation in space class NiQuaternion { public: - float w; //!< The w coordinate - float x; //!< The x coordinate - float y; //!< The y coordinate - float z; //!< The z coordinate + float w{ 1 }; //!< The w coordinate + float x{ 0 }; //!< The x coordinate + float y{ 0 }; //!< The y coordinate + float z{ 0 }; //!< The z coordinate //! The initializer - NiQuaternion(void); + constexpr NiQuaternion() = default; //! The initializer /*! @@ -30,13 +31,12 @@ public: \param y The y coordinate \param z The z coordinate */ - NiQuaternion(float w, float x, float y, float z); - - //! Destructor - ~NiQuaternion(void); - - // MARK: Constants - static const NiQuaternion IDENTITY; //!< Quaternion(1, 0, 0, 0) + constexpr NiQuaternion(const float w, const float x, const float y, const float z) noexcept + : w{ w } + , x{ x } + , y{ y } + , z{ z } { + } // MARK: Setters / Getters @@ -44,50 +44,49 @@ public: /*! \return The w coordinate */ - float GetW(void) const; + [[nodiscard]] constexpr float GetW() const noexcept; //! Sets the W coordinate /*! \param w The w coordinate */ - void SetW(float w); + constexpr void SetW(const float w) noexcept; //! Gets the X coordinate /*! \return The x coordinate */ - float GetX(void) const; + [[nodiscard]] constexpr float GetX() const noexcept; //! Sets the X coordinate /*! \param x The x coordinate */ - void SetX(float x); + constexpr void SetX(const float x) noexcept; //! Gets the Y coordinate /*! \return The y coordinate */ - float GetY(void) const; + [[nodiscard]] constexpr float GetY() const noexcept; //! Sets the Y coordinate /*! \param y The y coordinate */ - void SetY(float y); + constexpr void SetY(const float y) noexcept; //! Gets the Z coordinate /*! \return The z coordinate */ - float GetZ(void) const; + [[nodiscard]] constexpr float GetZ() const noexcept; //! Sets the Z coordinate /*! \param z The z coordinate */ - void SetZ(float z); - + constexpr void SetZ(const float z) noexcept; // MARK: Member Functions @@ -95,31 +94,29 @@ public: /*! \return The forward vector of the quaternion */ - Vector3 GetForwardVector(void) const; + [[nodiscard]] constexpr Vector3 GetForwardVector() const noexcept; //! Returns the up vector from the quaternion /*! \return The up vector fo the quaternion */ - Vector3 GetUpVector(void) const; + [[nodiscard]] constexpr Vector3 GetUpVector() const noexcept; //! Returns the right vector from the quaternion /*! \return The right vector of the quaternion */ - Vector3 GetRightVector(void) const; - - Vector3 GetEulerAngles() const; + [[nodiscard]] constexpr Vector3 GetRightVector() const noexcept; + [[nodiscard]] Vector3 GetEulerAngles() const; // MARK: Operators //! Operator to check for equality - bool operator==(const NiQuaternion& rot) const; + constexpr bool operator==(const NiQuaternion& rot) const noexcept; //! Operator to check for inequality - bool operator!=(const NiQuaternion& rot) const; - + constexpr bool operator!=(const NiQuaternion& rot) const noexcept; // MARK: Helper Functions @@ -129,7 +126,7 @@ public: \param destPoint The destination location \return The Quaternion with the rotation towards the destination */ - static NiQuaternion LookAt(const NiPoint3& sourcePoint, const NiPoint3& destPoint); + [[nodiscard]] static NiQuaternion LookAt(const NiPoint3& sourcePoint, const NiPoint3& destPoint); //! Look from a specific point in space to another point in space /*! @@ -137,7 +134,7 @@ public: \param destPoint The destination location \return The Quaternion with the rotation towards the destination */ - static NiQuaternion LookAtUnlocked(const NiPoint3& sourcePoint, const NiPoint3& destPoint); + [[nodiscard]] static NiQuaternion LookAtUnlocked(const NiPoint3& sourcePoint, const NiPoint3& destPoint); //! Creates a Quaternion from a specific axis and angle relative to that axis /*! @@ -145,7 +142,17 @@ public: \param angle The angle relative to this axis \return A quaternion created from the axis and angle */ - static NiQuaternion CreateFromAxisAngle(const Vector3& axis, float angle); + [[nodiscard]] static NiQuaternion CreateFromAxisAngle(const Vector3& axis, float angle); - static NiQuaternion FromEulerAngles(const NiPoint3& eulerAngles); + [[nodiscard]] static NiQuaternion FromEulerAngles(const NiPoint3& eulerAngles); }; + +// Static Variables +namespace NiQuaternionConstant { + constexpr NiQuaternion IDENTITY(1, 0, 0, 0); +} + +// Include constexpr and inline function definitions in a seperate file for readability +#include "NiQuaternion.inl" + +#endif // !__NIQUATERNION_H__ diff --git a/dCommon/NiQuaternion.inl b/dCommon/NiQuaternion.inl new file mode 100644 index 00000000..9ed84ffc --- /dev/null +++ b/dCommon/NiQuaternion.inl @@ -0,0 +1,75 @@ +#pragma once +#ifndef __NIQUATERNION_H__ +#error "This should only be included inline in NiQuaternion.h: Do not include directly!" +#endif + +// MARK: Setters / Getters + +//! Gets the W coordinate +constexpr float NiQuaternion::GetW() const noexcept { + return this->w; +} + +//! Sets the W coordinate +constexpr void NiQuaternion::SetW(const float w) noexcept { + this->w = w; +} + +//! Gets the X coordinate +constexpr float NiQuaternion::GetX() const noexcept { + return this->x; +} + +//! Sets the X coordinate +constexpr void NiQuaternion::SetX(const float x) noexcept { + this->x = x; +} + +//! Gets the Y coordinate +constexpr float NiQuaternion::GetY() const noexcept { + return this->y; +} + +//! Sets the Y coordinate +constexpr void NiQuaternion::SetY(const float y) noexcept { + this->y = y; +} + +//! Gets the Z coordinate +constexpr float NiQuaternion::GetZ() const noexcept { + return this->z; +} + +//! Sets the Z coordinate +constexpr void NiQuaternion::SetZ(const float z) noexcept { + this->z = z; +} + +// MARK: Member Functions + +//! Returns the forward vector from the quaternion +constexpr Vector3 NiQuaternion::GetForwardVector() const noexcept { + return Vector3(2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)); +} + +//! Returns the up vector from the quaternion +constexpr Vector3 NiQuaternion::GetUpVector() const noexcept { + return Vector3(2 * (x * y - w * z), 1 - 2 * (x * x + z * z), 2 * (y * z + w * x)); +} + +//! Returns the right vector from the quaternion +constexpr Vector3 NiQuaternion::GetRightVector() const noexcept { + return Vector3(1 - 2 * (y * y + z * z), 2 * (x * y + w * z), 2 * (x * z - w * y)); +} + +// MARK: Operators + +//! Operator to check for equality +constexpr bool NiQuaternion::operator==(const NiQuaternion& rot) const noexcept { + return rot.x == this->x && rot.y == this->y && rot.z == this->z && rot.w == this->w; +} + +//! Operator to check for inequality +constexpr bool NiQuaternion::operator!=(const NiQuaternion& rot) const noexcept { + return !(*this == rot); +} diff --git a/dCommon/PositionUpdate.h b/dCommon/PositionUpdate.h index 1b84e371..f28c682d 100644 --- a/dCommon/PositionUpdate.h +++ b/dCommon/PositionUpdate.h @@ -6,43 +6,29 @@ struct RemoteInputInfo { - RemoteInputInfo() { - m_RemoteInputX = 0; - m_RemoteInputY = 0; - m_IsPowersliding = false; - m_IsModified = false; - } - - void operator=(const RemoteInputInfo& other) { - m_RemoteInputX = other.m_RemoteInputX; - m_RemoteInputY = other.m_RemoteInputY; - m_IsPowersliding = other.m_IsPowersliding; - m_IsModified = other.m_IsModified; - } - bool operator==(const RemoteInputInfo& other) { return m_RemoteInputX == other.m_RemoteInputX && m_RemoteInputY == other.m_RemoteInputY && m_IsPowersliding == other.m_IsPowersliding && m_IsModified == other.m_IsModified; } - float m_RemoteInputX; - float m_RemoteInputY; - bool m_IsPowersliding; - bool m_IsModified; + float m_RemoteInputX = 0; + float m_RemoteInputY = 0; + bool m_IsPowersliding = false; + bool m_IsModified = false; }; struct LocalSpaceInfo { LWOOBJID objectId = LWOOBJID_EMPTY; - NiPoint3 position = NiPoint3::ZERO; - NiPoint3 linearVelocity = NiPoint3::ZERO; + NiPoint3 position = NiPoint3Constant::ZERO; + NiPoint3 linearVelocity = NiPoint3Constant::ZERO; }; struct PositionUpdate { - NiPoint3 position = NiPoint3::ZERO; - NiQuaternion rotation = NiQuaternion::IDENTITY; + NiPoint3 position = NiPoint3Constant::ZERO; + NiQuaternion rotation = NiQuaternionConstant::IDENTITY; bool onGround = false; bool onRail = false; - NiPoint3 velocity = NiPoint3::ZERO; - NiPoint3 angularVelocity = NiPoint3::ZERO; + NiPoint3 velocity = NiPoint3Constant::ZERO; + NiPoint3 angularVelocity = NiPoint3Constant::ZERO; LocalSpaceInfo localSpaceInfo; RemoteInputInfo remoteInputInfo; }; diff --git a/dCommon/SHA512.cpp b/dCommon/SHA512.cpp deleted file mode 100644 index e3c2d9f7..00000000 --- a/dCommon/SHA512.cpp +++ /dev/null @@ -1,154 +0,0 @@ -// Source: http://www.zedwood.com/article/cpp-sha512-function - -#include "SHA512.h" - -#include -#include - -const unsigned long long SHA512::sha512_k[80] = //ULL = uint64 -{ 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, - 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, - 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, - 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, - 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, - 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, - 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, - 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, - 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, - 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, - 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, - 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, - 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, - 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, - 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, - 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, - 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, - 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, - 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, - 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, - 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, - 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, - 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, - 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, - 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, - 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, - 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, - 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, - 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, - 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, - 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, - 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, - 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, - 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, - 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, - 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, - 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, - 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, - 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, - 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL }; - -void SHA512::transform(const unsigned char* message, unsigned int block_nb) { - uint64 w[80]; - uint64 wv[8]; - uint64 t1, t2; - const unsigned char* sub_block; - int i, j; - for (i = 0; i < (int)block_nb; i++) { - sub_block = message + (i << 7); - for (j = 0; j < 16; j++) { - SHA2_PACK64(&sub_block[j << 3], &w[j]); - } - for (j = 16; j < 80; j++) { - w[j] = SHA512_F4(w[j - 2]) + w[j - 7] + SHA512_F3(w[j - 15]) + w[j - 16]; - } - for (j = 0; j < 8; j++) { - wv[j] = m_h[j]; - } - for (j = 0; j < 80; j++) { - t1 = wv[7] + SHA512_F2(wv[4]) + SHA2_CH(wv[4], wv[5], wv[6]) - + sha512_k[j] + w[j]; - t2 = SHA512_F1(wv[0]) + SHA2_MAJ(wv[0], wv[1], wv[2]); - wv[7] = wv[6]; - wv[6] = wv[5]; - wv[5] = wv[4]; - wv[4] = wv[3] + t1; - wv[3] = wv[2]; - wv[2] = wv[1]; - wv[1] = wv[0]; - wv[0] = t1 + t2; - } - for (j = 0; j < 8; j++) { - m_h[j] += wv[j]; - } - - } -} - -void SHA512::init() { - m_h[0] = 0x6a09e667f3bcc908ULL; - m_h[1] = 0xbb67ae8584caa73bULL; - m_h[2] = 0x3c6ef372fe94f82bULL; - m_h[3] = 0xa54ff53a5f1d36f1ULL; - m_h[4] = 0x510e527fade682d1ULL; - m_h[5] = 0x9b05688c2b3e6c1fULL; - m_h[6] = 0x1f83d9abfb41bd6bULL; - m_h[7] = 0x5be0cd19137e2179ULL; - m_len = 0; - m_tot_len = 0; -} - -void SHA512::update(const unsigned char* message, unsigned int len) { - unsigned int block_nb; - unsigned int new_len, rem_len, tmp_len; - const unsigned char* shifted_message; - tmp_len = SHA384_512_BLOCK_SIZE - m_len; - rem_len = len < tmp_len ? len : tmp_len; - memcpy(&m_block[m_len], message, rem_len); - if (m_len + len < SHA384_512_BLOCK_SIZE) { - m_len += len; - return; - } - new_len = len - rem_len; - block_nb = new_len / SHA384_512_BLOCK_SIZE; - shifted_message = message + rem_len; - transform(m_block, 1); - transform(shifted_message, block_nb); - rem_len = new_len % SHA384_512_BLOCK_SIZE; - memcpy(m_block, &shifted_message[block_nb << 7], rem_len); - m_len = rem_len; - m_tot_len += (block_nb + 1) << 7; -} - -void SHA512::final(unsigned char* digest) { - unsigned int block_nb; - unsigned int pm_len; - unsigned int len_b; - int i; - block_nb = 1 + ((SHA384_512_BLOCK_SIZE - 17) - < (m_len % SHA384_512_BLOCK_SIZE)); - len_b = (m_tot_len + m_len) << 3; - pm_len = block_nb << 7; - memset(m_block + m_len, 0, pm_len - m_len); - m_block[m_len] = 0x80; - SHA2_UNPACK32(len_b, m_block + pm_len - 4); - transform(m_block, block_nb); - for (i = 0; i < 8; i++) { - SHA2_UNPACK64(m_h[i], &digest[i << 3]); - } -} - -std::string sha512(std::string input) { - unsigned char digest[SHA512::DIGEST_SIZE]; - memset(digest, 0, SHA512::DIGEST_SIZE); - class SHA512 ctx; - ctx.init(); - ctx.update((unsigned char*)input.c_str(), input.length()); - ctx.final(digest); - - char buf[2 * SHA512::DIGEST_SIZE + 1]; - buf[2 * SHA512::DIGEST_SIZE] = 0; - for (int i = 0; i < SHA512::DIGEST_SIZE; i++) - sprintf(buf + i * 2, "%02x", digest[i]); - - return std::string(buf); -} diff --git a/dCommon/SHA512.h b/dCommon/SHA512.h deleted file mode 100644 index 512fa645..00000000 --- a/dCommon/SHA512.h +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once - -// C++ -#include - -class SHA512 { -protected: - typedef unsigned char uint8; - typedef unsigned int uint32; - typedef unsigned long long uint64; - - const static uint64 sha512_k[]; - static const unsigned int SHA384_512_BLOCK_SIZE = (1024 / 8); - -public: - void init(); - void update(const unsigned char* message, unsigned int len); - void final(unsigned char* digest); - static const unsigned int DIGEST_SIZE = (512 / 8); - -protected: - void transform(const unsigned char* message, unsigned int block_nb); - unsigned int m_tot_len; - unsigned int m_len; - unsigned char m_block[2 * SHA384_512_BLOCK_SIZE]; - uint64 m_h[8]; -}; - -std::string sha512(std::string input); - -#define SHA2_SHFR(x, n) (x >> n) -#define SHA2_ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n))) -#define SHA2_ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n))) -#define SHA2_CH(x, y, z) ((x & y) ^ (~x & z)) -#define SHA2_MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z)) -#define SHA512_F1(x) (SHA2_ROTR(x, 28) ^ SHA2_ROTR(x, 34) ^ SHA2_ROTR(x, 39)) -#define SHA512_F2(x) (SHA2_ROTR(x, 14) ^ SHA2_ROTR(x, 18) ^ SHA2_ROTR(x, 41)) -#define SHA512_F3(x) (SHA2_ROTR(x, 1) ^ SHA2_ROTR(x, 8) ^ SHA2_SHFR(x, 7)) -#define SHA512_F4(x) (SHA2_ROTR(x, 19) ^ SHA2_ROTR(x, 61) ^ SHA2_SHFR(x, 6)) -#define SHA2_UNPACK32(x, str) \ -{ \ -*((str) + 3) = (uint8) ((x) ); \ -*((str) + 2) = (uint8) ((x) >> 8); \ -*((str) + 1) = (uint8) ((x) >> 16); \ -*((str) + 0) = (uint8) ((x) >> 24); \ -} -#define SHA2_UNPACK64(x, str) \ -{ \ -*((str) + 7) = (uint8) ((x) ); \ -*((str) + 6) = (uint8) ((x) >> 8); \ -*((str) + 5) = (uint8) ((x) >> 16); \ -*((str) + 4) = (uint8) ((x) >> 24); \ -*((str) + 3) = (uint8) ((x) >> 32); \ -*((str) + 2) = (uint8) ((x) >> 40); \ -*((str) + 1) = (uint8) ((x) >> 48); \ -*((str) + 0) = (uint8) ((x) >> 56); \ -} -#define SHA2_PACK64(str, x) \ -{ \ -*(x) = ((uint64) *((str) + 7) ) \ -| ((uint64) *((str) + 6) << 8) \ -| ((uint64) *((str) + 5) << 16) \ -| ((uint64) *((str) + 4) << 24) \ -| ((uint64) *((str) + 3) << 32) \ -| ((uint64) *((str) + 2) << 40) \ -| ((uint64) *((str) + 1) << 48) \ -| ((uint64) *((str) + 0) << 56); \ -} diff --git a/dCommon/dClient/CMakeLists.txt b/dCommon/dClient/CMakeLists.txt index 69bb1712..017a22a5 100644 --- a/dCommon/dClient/CMakeLists.txt +++ b/dCommon/dClient/CMakeLists.txt @@ -1,6 +1,6 @@ set(DCOMMON_DCLIENT_SOURCES + "AssetManager.cpp" "PackIndex.cpp" "Pack.cpp" - "AssetManager.cpp" PARENT_SCOPE ) diff --git a/dCommon/dClient/ClientVersion.h b/dCommon/dClient/ClientVersion.h new file mode 100644 index 00000000..393103ab --- /dev/null +++ b/dCommon/dClient/ClientVersion.h @@ -0,0 +1,12 @@ +#ifndef __CLIENTVERSION_H__ +#define __CLIENTVERSION_H__ + +#include + +namespace ClientVersion { + constexpr uint16_t major = 1; + constexpr uint16_t current = 10; + constexpr uint16_t minor = 64; +} + +#endif // !__CLIENTVERSION_H__ diff --git a/dCommon/dEnums/StringifiedEnum.h b/dCommon/dEnums/StringifiedEnum.h index 16eafdca..1816d705 100644 --- a/dCommon/dEnums/StringifiedEnum.h +++ b/dCommon/dEnums/StringifiedEnum.h @@ -9,15 +9,15 @@ namespace StringifiedEnum { const std::string_view ToString(const T e) { static_assert(std::is_enum_v, "Not an enum"); // Check type - constexpr auto sv = &magic_enum::enum_entries(); + constexpr auto& sv = magic_enum::enum_entries(); const auto it = std::lower_bound( - sv->begin(), sv->end(), e, + sv.begin(), sv.end(), e, [&](const std::pair& lhs, const T rhs) { return lhs.first < rhs; } ); std::string_view output; - if (it != sv->end() && it->first == e) { + if (it != sv.end() && it->first == e) { output = it->second; } else { output = "UNKNOWN"; diff --git a/dCommon/dEnums/dCommonVars.h b/dCommon/dEnums/dCommonVars.h index f4f8fdfb..7cdbfdb6 100644 --- a/dCommon/dEnums/dCommonVars.h +++ b/dCommon/dEnums/dCommonVars.h @@ -34,91 +34,89 @@ constexpr uint32_t lowFrameDelta = FRAMES_TO_MS(lowFramerate); #define CINSTREAM RakNet::BitStream inStream(packet->data, packet->length, false); #define CINSTREAM_SKIP_HEADER CINSTREAM if (inStream.GetNumberOfUnreadBits() >= BYTES_TO_BITS(HEADER_SIZE)) inStream.IgnoreBytes(HEADER_SIZE); else inStream.IgnoreBits(inStream.GetNumberOfUnreadBits()); #define CMSGHEADER BitStreamUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::GAME_MSG); -#define SEND_PACKET Game::server->Send(&bitStream, sysAddr, false); -#define SEND_PACKET_BROADCAST Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); +#define SEND_PACKET Game::server->Send(bitStream, sysAddr, false); +#define SEND_PACKET_BROADCAST Game::server->Send(bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); //=========== TYPEDEFS ========== -typedef int32_t LOT; //!< A LOT -typedef int64_t LWOOBJID; //!< An object ID (should be unsigned actually but ok) -typedef int32_t TSkillID; //!< A skill ID -typedef uint32_t LWOCLONEID; //!< Used for Clone IDs -typedef uint16_t LWOMAPID; //!< Used for Map IDs -typedef uint16_t LWOINSTANCEID; //!< Used for Instance IDs -typedef uint32_t PROPERTYCLONELIST; //!< Used for Property Clone IDs -typedef uint32_t StripId; +using LOT = int32_t; //!< A LOT +using LWOOBJID = int64_t; //!< An object ID (should be unsigned actually but ok) +using TSkillID = int32_t; //!< A skill ID +using LWOCLONEID = uint32_t; //!< Used for Clone IDs +using LWOMAPID = uint16_t; //!< Used for Map IDs +using LWOINSTANCEID = uint16_t; //!< Used for Instance IDs +using PROPERTYCLONELIST = uint32_t; //!< Used for Property Clone IDs +using StripId = uint32_t; -const LWOOBJID LWOOBJID_EMPTY = 0; //!< An empty object ID -const LOT LOT_NULL = -1; //!< A null LOT -const int32_t LOOTTYPE_NONE = 0; //!< No loot type available -const float SECONDARY_PRIORITY = 1.0f; //!< Secondary Priority -const uint32_t INVENTORY_MAX = 9999999; //!< The Maximum Inventory Size -const uint32_t LWOCLONEID_INVALID = -1; //!< Invalid LWOCLONEID -const uint16_t LWOINSTANCEID_INVALID = -1; //!< Invalid LWOINSTANCEID -const uint16_t LWOMAPID_INVALID = -1; //!< Invalid LWOMAPID -const uint64_t LWOZONEID_INVALID = 0; //!< Invalid LWOZONEID +constexpr LWOOBJID LWOOBJID_EMPTY = 0; //!< An empty object ID +constexpr LOT LOT_NULL = -1; //!< A null LOT +constexpr int32_t LOOTTYPE_NONE = 0; //!< No loot type available +constexpr float SECONDARY_PRIORITY = 1.0f; //!< Secondary Priority +constexpr uint32_t INVENTORY_MAX = 9999999; //!< The Maximum Inventory Size +constexpr LWOCLONEID LWOCLONEID_INVALID = -1; //!< Invalid LWOCLONEID +constexpr LWOINSTANCEID LWOINSTANCEID_INVALID = -1; //!< Invalid LWOINSTANCEID +constexpr LWOMAPID LWOMAPID_INVALID = -1; //!< Invalid LWOMAPID +constexpr uint64_t LWOZONEID_INVALID = 0; //!< Invalid LWOZONEID -const float PI = 3.14159f; +constexpr float PI = 3.14159f; //============ STRUCTS ============== struct LWOSCENEID { public: - LWOSCENEID() { m_sceneID = -1; m_layerID = 0; } - LWOSCENEID(int sceneID) { m_sceneID = sceneID; m_layerID = 0; } - LWOSCENEID(int sceneID, unsigned int layerID) { m_sceneID = sceneID; m_layerID = layerID; } + constexpr LWOSCENEID() noexcept { m_sceneID = -1; m_layerID = 0; } + constexpr LWOSCENEID(int32_t sceneID) noexcept { m_sceneID = sceneID; m_layerID = 0; } + constexpr LWOSCENEID(int32_t sceneID, uint32_t layerID) noexcept { m_sceneID = sceneID; m_layerID = layerID; } - LWOSCENEID& operator=(const LWOSCENEID& rhs) { m_sceneID = rhs.m_sceneID; m_layerID = rhs.m_layerID; return *this; } - LWOSCENEID& operator=(const int rhs) { m_sceneID = rhs; m_layerID = 0; return *this; } + constexpr LWOSCENEID& operator=(const LWOSCENEID& rhs) noexcept { m_sceneID = rhs.m_sceneID; m_layerID = rhs.m_layerID; return *this; } + constexpr LWOSCENEID& operator=(const int32_t rhs) noexcept { m_sceneID = rhs; m_layerID = 0; return *this; } - bool operator<(const LWOSCENEID& rhs) const { return (m_sceneID < rhs.m_sceneID || (m_sceneID == rhs.m_sceneID && m_layerID < rhs.m_layerID)); } - bool operator<(const int rhs) const { return m_sceneID < rhs; } + constexpr bool operator<(const LWOSCENEID& rhs) const noexcept { return (m_sceneID < rhs.m_sceneID || (m_sceneID == rhs.m_sceneID && m_layerID < rhs.m_layerID)); } + constexpr bool operator<(const int32_t rhs) const noexcept { return m_sceneID < rhs; } - bool operator==(const LWOSCENEID& rhs) const { return (m_sceneID == rhs.m_sceneID && m_layerID == rhs.m_layerID); } - bool operator==(const int rhs) const { return m_sceneID == rhs; } + constexpr bool operator==(const LWOSCENEID& rhs) const noexcept { return (m_sceneID == rhs.m_sceneID && m_layerID == rhs.m_layerID); } + constexpr bool operator==(const int32_t rhs) const noexcept { return m_sceneID == rhs; } - const int GetSceneID() const { return m_sceneID; } - const unsigned int GetLayerID() const { return m_layerID; } + constexpr int32_t GetSceneID() const noexcept { return m_sceneID; } + constexpr uint32_t GetLayerID() const noexcept { return m_layerID; } - void SetSceneID(const int sceneID) { m_sceneID = sceneID; } - void SetLayerID(const unsigned int layerID) { m_layerID = layerID; } + constexpr void SetSceneID(const int32_t sceneID) noexcept { m_sceneID = sceneID; } + constexpr void SetLayerID(const uint32_t layerID) noexcept { m_layerID = layerID; } private: - int m_sceneID; - unsigned int m_layerID; + int32_t m_sceneID; + uint32_t m_layerID; }; struct LWOZONEID { public: - const LWOMAPID& GetMapID() const { return m_MapID; } - const LWOINSTANCEID& GetInstanceID() const { return m_InstanceID; } - const LWOCLONEID& GetCloneID() const { return m_CloneID; } + constexpr const LWOMAPID& GetMapID() const noexcept { return m_MapID; } + constexpr const LWOINSTANCEID& GetInstanceID() const noexcept { return m_InstanceID; } + constexpr const LWOCLONEID& GetCloneID() const noexcept { return m_CloneID; } //In order: def constr, constr, assign op - LWOZONEID() { m_MapID = LWOMAPID_INVALID; m_InstanceID = LWOINSTANCEID_INVALID; m_CloneID = LWOCLONEID_INVALID; } - LWOZONEID(const LWOMAPID& mapID, const LWOINSTANCEID& instanceID, const LWOCLONEID& cloneID) { m_MapID = mapID; m_InstanceID = instanceID; m_CloneID = cloneID; } - LWOZONEID(const LWOZONEID& replacement) { *this = replacement; } + constexpr LWOZONEID() noexcept = default; + constexpr LWOZONEID(const LWOMAPID& mapID, const LWOINSTANCEID& instanceID, const LWOCLONEID& cloneID) noexcept { m_MapID = mapID; m_InstanceID = instanceID; m_CloneID = cloneID; } + constexpr LWOZONEID(const LWOZONEID& replacement) noexcept { *this = replacement; } private: - LWOMAPID m_MapID; //1000 for VE, 1100 for AG, etc... - LWOINSTANCEID m_InstanceID; //Instances host the same world, but on a different dWorld process. - LWOCLONEID m_CloneID; //To differentiate between "your property" and "my property". Always 0 for non-prop worlds. + LWOMAPID m_MapID = LWOMAPID_INVALID; //1000 for VE, 1100 for AG, etc... + LWOINSTANCEID m_InstanceID = LWOINSTANCEID_INVALID; //Instances host the same world, but on a different dWorld process. + LWOCLONEID m_CloneID = LWOCLONEID_INVALID; //To differentiate between "your property" and "my property". Always 0 for non-prop worlds. }; -const LWOSCENEID LWOSCENEID_INVALID = -1; +constexpr LWOSCENEID LWOSCENEID_INVALID = -1; struct LWONameValue { uint32_t length = 0; //!< The length of the name std::u16string name; //!< The name - LWONameValue(void) {} + LWONameValue() = default; LWONameValue(const std::u16string& name) { this->name = name; this->length = static_cast(name.length()); } - - ~LWONameValue(void) {} }; struct FriendData { diff --git a/dCommon/dEnums/eReplicaComponentType.h b/dCommon/dEnums/eReplicaComponentType.h index 83acbf89..2b991dfb 100644 --- a/dCommon/dEnums/eReplicaComponentType.h +++ b/dCommon/dEnums/eReplicaComponentType.h @@ -106,7 +106,7 @@ enum class eReplicaComponentType : uint32_t { INTERACTION_MANAGER, DONATION_VENDOR, COMBAT_MEDIATOR, - COMMENDATION_VENDOR, + ACHIEVEMENT_VENDOR, GATE_RUSH_CONTROL, RAIL_ACTIVATOR, ROLLER, diff --git a/dCommon/dEnums/eVendorTransactionResult.h b/dCommon/dEnums/eVendorTransactionResult.h new file mode 100644 index 00000000..e61ee0ee --- /dev/null +++ b/dCommon/dEnums/eVendorTransactionResult.h @@ -0,0 +1,15 @@ +#ifndef __EVENDORTRANSACTIONRESULT__ +#define __EVENDORTRANSACTIONRESULT__ + +#include + +enum class eVendorTransactionResult : uint32_t { + SELL_SUCCESS = 0, + SELL_FAIL, + PURCHASE_SUCCESS, + PURCHASE_FAIL, + DONATION_FAIL, + DONATION_FULL +}; + +#endif // !__EVENDORTRANSACTIONRESULT__ diff --git a/dCommon/dEnums/eWaypointCommandType.h b/dCommon/dEnums/eWaypointCommandType.h new file mode 100644 index 00000000..308f3764 --- /dev/null +++ b/dCommon/dEnums/eWaypointCommandType.h @@ -0,0 +1,59 @@ + +#ifndef __EWAYPOINTCOMMANDTYPES__H__ +#define __EWAYPOINTCOMMANDTYPES__H__ + +#include + +enum class eWaypointCommandType : uint32_t { + INVALID, + BOUNCE, + STOP, + GROUP_EMOTE, + SET_VARIABLE, + CAST_SKILL, + EQUIP_INVENTORY, + UNEQUIP_INVENTORY, + DELAY, + EMOTE, + TELEPORT, + PATH_SPEED, + REMOVE_NPC, + CHANGE_WAYPOINT, + DELETE_SELF, + KILL_SELF, + SPAWN_OBJECT, + PLAY_SOUND, +}; + +class WaypointCommandType { +public: + static eWaypointCommandType StringToWaypointCommandType(std::string commandString) { + const std::map WaypointCommandTypeMap = { + {"bounce", eWaypointCommandType::BOUNCE}, + {"stop", eWaypointCommandType::STOP}, + {"groupemote", eWaypointCommandType::GROUP_EMOTE}, + {"setvar", eWaypointCommandType::SET_VARIABLE}, + {"castskill", eWaypointCommandType::CAST_SKILL}, + {"eqInvent", eWaypointCommandType::EQUIP_INVENTORY}, + {"unInvent", eWaypointCommandType::UNEQUIP_INVENTORY}, + {"delay", eWaypointCommandType::DELAY}, + {"femote", eWaypointCommandType::EMOTE}, + {"emote", eWaypointCommandType::EMOTE}, + {"teleport", eWaypointCommandType::TELEPORT}, + {"pathspeed", eWaypointCommandType::PATH_SPEED}, + {"removeNPC", eWaypointCommandType::REMOVE_NPC}, + {"changeWP", eWaypointCommandType::CHANGE_WAYPOINT}, + {"DeleteSelf", eWaypointCommandType::DELETE_SELF}, + {"killself", eWaypointCommandType::KILL_SELF}, + {"removeself", eWaypointCommandType::DELETE_SELF}, + {"spawnOBJ", eWaypointCommandType::SPAWN_OBJECT}, + {"playSound", eWaypointCommandType::PLAY_SOUND}, + }; + + auto intermed = WaypointCommandTypeMap.find(commandString); + return (intermed != WaypointCommandTypeMap.end()) ? intermed->second : eWaypointCommandType::INVALID; + }; +}; + + +#endif //!__EWAYPOINTCOMMANDTYPES__H__ diff --git a/dDatabase/CDClientDatabase/CDClientManager.cpp b/dDatabase/CDClientDatabase/CDClientManager.cpp index f270d849..0e05c0b8 100644 --- a/dDatabase/CDClientDatabase/CDClientManager.cpp +++ b/dDatabase/CDClientDatabase/CDClientManager.cpp @@ -39,6 +39,7 @@ #include "CDFeatureGatingTable.h" #include "CDRailActivatorComponent.h" #include "CDRewardCodesTable.h" +#include "CDPetComponentTable.h" #include @@ -61,6 +62,55 @@ public: } }; +// Using a macro to reduce repetitive code and issues from copy and paste. +// As a note, ## in a macro is used to concatenate two tokens together. + +#define SPECIALIZE_TABLE_STORAGE(table) \ + template<> typename table::StorageType& CDClientManager::GetEntriesMutable() { return table##Entries; }; + +#define DEFINE_TABLE_STORAGE(table) namespace { table::StorageType table##Entries; }; SPECIALIZE_TABLE_STORAGE(table) + +DEFINE_TABLE_STORAGE(CDActivityRewardsTable); +DEFINE_TABLE_STORAGE(CDActivitiesTable); +DEFINE_TABLE_STORAGE(CDAnimationsTable); +DEFINE_TABLE_STORAGE(CDBehaviorParameterTable); +DEFINE_TABLE_STORAGE(CDBehaviorTemplateTable); +DEFINE_TABLE_STORAGE(CDBrickIDTableTable); +DEFINE_TABLE_STORAGE(CDComponentsRegistryTable); +DEFINE_TABLE_STORAGE(CDCurrencyTableTable); +DEFINE_TABLE_STORAGE(CDDestructibleComponentTable); +DEFINE_TABLE_STORAGE(CDEmoteTableTable); +DEFINE_TABLE_STORAGE(CDFeatureGatingTable); +DEFINE_TABLE_STORAGE(CDInventoryComponentTable); +DEFINE_TABLE_STORAGE(CDItemComponentTable); +DEFINE_TABLE_STORAGE(CDItemSetSkillsTable); +DEFINE_TABLE_STORAGE(CDItemSetsTable); +DEFINE_TABLE_STORAGE(CDLevelProgressionLookupTable); +DEFINE_TABLE_STORAGE(CDLootMatrixTable); +DEFINE_TABLE_STORAGE(CDLootTableTable); +DEFINE_TABLE_STORAGE(CDMissionEmailTable); +DEFINE_TABLE_STORAGE(CDMissionNPCComponentTable); +DEFINE_TABLE_STORAGE(CDMissionTasksTable); +DEFINE_TABLE_STORAGE(CDMissionsTable); +DEFINE_TABLE_STORAGE(CDMovementAIComponentTable); +DEFINE_TABLE_STORAGE(CDObjectSkillsTable); +DEFINE_TABLE_STORAGE(CDObjectsTable); +DEFINE_TABLE_STORAGE(CDPhysicsComponentTable); +DEFINE_TABLE_STORAGE(CDPackageComponentTable); +DEFINE_TABLE_STORAGE(CDPetComponentTable); +DEFINE_TABLE_STORAGE(CDProximityMonitorComponentTable); +DEFINE_TABLE_STORAGE(CDPropertyEntranceComponentTable); +DEFINE_TABLE_STORAGE(CDPropertyTemplateTable); +DEFINE_TABLE_STORAGE(CDRailActivatorComponentTable); +DEFINE_TABLE_STORAGE(CDRarityTableTable); +DEFINE_TABLE_STORAGE(CDRebuildComponentTable); +DEFINE_TABLE_STORAGE(CDRewardCodesTable); +DEFINE_TABLE_STORAGE(CDRewardsTable); +DEFINE_TABLE_STORAGE(CDScriptComponentTable); +DEFINE_TABLE_STORAGE(CDSkillBehaviorTable); +DEFINE_TABLE_STORAGE(CDVendorComponentTable); +DEFINE_TABLE_STORAGE(CDZoneTableTable); + void CDClientManager::LoadValuesFromDatabase() { if (!CDClientDatabase::isConnected) throw CDClientConnectionException(); diff --git a/dDatabase/CDClientDatabase/CDClientManager.h b/dDatabase/CDClientDatabase/CDClientManager.h index ae628a36..c1c4443d 100644 --- a/dDatabase/CDClientDatabase/CDClientManager.h +++ b/dDatabase/CDClientDatabase/CDClientManager.h @@ -1,18 +1,12 @@ -#pragma once - -#include "CDTable.h" - -#include "Singleton.h" +#ifndef __CDCLIENTMANAGER__H__ +#define __CDCLIENTMANAGER__H__ #define UNUSED_TABLE(v) /** * Initialize the CDClient tables so they are all loaded into memory. */ -class CDClientManager : public Singleton { -public: - CDClientManager() = default; - +namespace CDClientManager { void LoadValuesFromDatabase(); void LoadValuesFromDefaults(); @@ -23,7 +17,28 @@ public: * @return A pointer to the requested table. */ template - T* GetTable() { - return &T::Instance(); - } + T* GetTable(); + + /** + * Fetch a table from CDClient + * Note: Calling this function without a template specialization in CDClientManager.cpp will cause a linker error. + * + * @tparam Table type to fetch + * @return A pointer to the requested table. + */ + template + typename T::StorageType& GetEntriesMutable(); }; + + +// These are included after the CDClientManager namespace declaration as CDTable as of Jan 29 2024 relies on CDClientManager in Templated code. +#include "CDTable.h" + +#include "Singleton.h" + +template +T* CDClientManager::GetTable() { + return &T::Instance(); +}; + +#endif //!__CDCLIENTMANAGER__H__ diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp index 998c4095..19111490 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp @@ -1,5 +1,6 @@ #include "CDActivitiesTable.h" + void CDActivitiesTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; @@ -13,7 +14,8 @@ void CDActivitiesTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Activities"); @@ -39,7 +41,7 @@ void CDActivitiesTable::LoadValuesFromDatabase() { entry.noTeamLootOnDeath = tableData.getIntField("noTeamLootOnDeath", -1); entry.optionalPercentage = tableData.getFloatField("optionalPercentage", -1.0f); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -48,7 +50,7 @@ void CDActivitiesTable::LoadValuesFromDatabase() { std::vector CDActivitiesTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h index 75fc602e..3e1d4c37 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h @@ -25,15 +25,10 @@ struct CDActivities { float optionalPercentage; }; -class CDActivitiesTable : public CDTable { -private: - std::vector entries; - +class CDActivitiesTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const { return this->entries; } }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp index 7795a177..abe0c50c 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp @@ -1,5 +1,6 @@ #include "CDActivityRewardsTable.h" + void CDActivityRewardsTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -14,7 +15,8 @@ void CDActivityRewardsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ActivityRewards"); @@ -28,7 +30,7 @@ void CDActivityRewardsTable::LoadValuesFromDatabase() { entry.ChallengeRating = tableData.getIntField("ChallengeRating", -1); entry.description = tableData.getStringField("description", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -37,7 +39,7 @@ void CDActivityRewardsTable::LoadValuesFromDatabase() { std::vector CDActivityRewardsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h index 40ab17e7..8d07a718 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h @@ -13,15 +13,9 @@ struct CDActivityRewards { std::string description; //!< The description }; -class CDActivityRewardsTable : public CDTable { -private: - std::vector entries; - +class CDActivityRewardsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - std::vector GetEntries() const; - }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp index 7244ddee..cf461fc9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp @@ -5,6 +5,7 @@ void CDAnimationsTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Animations"); + auto& animations = GetEntriesMutable(); while (!tableData.eof()) { std::string animation_type = tableData.getStringField("animation_type", ""); DluAssert(!animation_type.empty()); @@ -24,7 +25,7 @@ void CDAnimationsTable::LoadValuesFromDatabase() { UNUSED_COLUMN(entry.priority = tableData.getFloatField("priority", 0.0f);) UNUSED_COLUMN(entry.blendTime = tableData.getFloatField("blendTime", 0.0f);) - this->animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); + animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); tableData.nextRow(); } @@ -35,6 +36,7 @@ bool CDAnimationsTable::CacheData(CppSQLite3Statement& queryToCache) { auto tableData = queryToCache.execQuery(); // If we received a bad lookup, cache it anyways so we do not run the query again. if (tableData.eof()) return false; + auto& animations = GetEntriesMutable(); do { std::string animation_type = tableData.getStringField("animation_type", ""); @@ -55,7 +57,7 @@ bool CDAnimationsTable::CacheData(CppSQLite3Statement& queryToCache) { UNUSED_COLUMN(entry.priority = tableData.getFloatField("priority", 0.0f);) UNUSED_COLUMN(entry.blendTime = tableData.getFloatField("blendTime", 0.0f);) - this->animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); + animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); tableData.nextRow(); } while (!tableData.eof()); @@ -68,15 +70,17 @@ void CDAnimationsTable::CacheAnimations(const CDAnimationKey animationKey) { auto query = CDClientDatabase::CreatePreppedStmt("SELECT * FROM Animations WHERE animationGroupID = ? and animation_type = ?"); query.bind(1, static_cast(animationKey.second)); query.bind(2, animationKey.first.c_str()); + auto& animations = GetEntriesMutable(); // If we received a bad lookup, cache it anyways so we do not run the query again. if (!CacheData(query)) { - this->animations[animationKey]; + animations[animationKey]; } } void CDAnimationsTable::CacheAnimationGroup(AnimationGroupID animationGroupID) { - auto animationEntryCached = this->animations.find(CDAnimationKey("", animationGroupID)); - if (animationEntryCached != this->animations.end()) { + auto& animations = GetEntriesMutable(); + auto animationEntryCached = animations.find(CDAnimationKey("", animationGroupID)); + if (animationEntryCached != animations.end()) { return; } @@ -85,28 +89,29 @@ void CDAnimationsTable::CacheAnimationGroup(AnimationGroupID animationGroupID) { // Cache the query so we don't run the query again. CacheData(query); - this->animations[CDAnimationKey("", animationGroupID)]; + animations[CDAnimationKey("", animationGroupID)]; } -CDAnimationLookupResult CDAnimationsTable::GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID) { +std::optional CDAnimationsTable::GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID) { + auto& animations = GetEntriesMutable(); CDAnimationKey animationKey(animationType, animationGroupID); - auto animationEntryCached = this->animations.find(animationKey); - if (animationEntryCached == this->animations.end()) { + auto animationEntryCached = animations.find(animationKey); + if (animationEntryCached == animations.end()) { this->CacheAnimations(animationKey); } - auto animationEntry = this->animations.find(animationKey); + auto animationEntry = animations.find(animationKey); // If we have only one animation, return it regardless of the chance to play. if (animationEntry->second.size() == 1) { - return CDAnimationLookupResult(animationEntry->second.front()); + return animationEntry->second.front(); } auto randomAnimation = GeneralUtils::GenerateRandomNumber(0, 1); for (auto& animationEntry : animationEntry->second) { randomAnimation -= animationEntry.chance_to_play; // This is how the client gets the random animation. - if (animationEntry.animation_name != previousAnimationName && randomAnimation <= 0.0f) return CDAnimationLookupResult(animationEntry); + if (animationEntry.animation_name != previousAnimationName && randomAnimation <= 0.0f) return animationEntry; } - return CDAnimationLookupResult(); + return std::nullopt; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h index 1b6280ca..643ef98f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h @@ -2,6 +2,11 @@ #include "CDTable.h" #include +#include + +typedef int32_t AnimationGroupID; +typedef std::string AnimationID; +typedef std::pair CDAnimationKey; struct CDAnimation { // uint32_t animationGroupID; @@ -20,12 +25,7 @@ struct CDAnimation { UNUSED_COLUMN(float blendTime;) //!< The blend time }; -typedef LookupResult CDAnimationLookupResult; - -class CDAnimationsTable : public CDTable { - typedef int32_t AnimationGroupID; - typedef std::string AnimationID; - typedef std::pair CDAnimationKey; +class CDAnimationsTable : public CDTable>> { public: void LoadValuesFromDatabase(); /** @@ -38,7 +38,7 @@ public: * @param animationGroupID The animationGroupID to lookup * @return CDAnimationLookupResult */ - [[nodiscard]] CDAnimationLookupResult GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID); + [[nodiscard]] std::optional GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID); /** * Cache a full AnimationGroup by its ID. @@ -58,10 +58,4 @@ private: * @return false */ bool CacheData(CppSQLite3Statement& queryToCache); - - /** - * Each animation is key'd by its animationName and its animationGroupID. Each - * animation has a possible list of animations. This is because there can be animations have a percent chance to play so one is selected at random. - */ - std::map> animations; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp index 708bec4c..57187c7c 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp @@ -1,6 +1,10 @@ #include "CDBehaviorParameterTable.h" #include "GeneralUtils.h" +namespace { + std::unordered_map m_ParametersList; +}; + uint64_t GetKey(const uint32_t behaviorID, const uint32_t parameterID) { uint64_t key = behaviorID; key <<= 31U; @@ -11,6 +15,7 @@ uint64_t GetKey(const uint32_t behaviorID, const uint32_t parameterID) { void CDBehaviorParameterTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorParameter"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { uint32_t behaviorID = tableData.getIntField("behaviorID", -1); auto candidateStringToAdd = std::string(tableData.getStringField("parameterID", "")); @@ -24,7 +29,7 @@ void CDBehaviorParameterTable::LoadValuesFromDatabase() { uint64_t hash = GetKey(behaviorID, parameterId); float value = tableData.getFloatField("value", -1.0f); - m_Entries.insert(std::make_pair(hash, value)); + entries.insert(std::make_pair(hash, value)); tableData.nextRow(); } @@ -32,22 +37,24 @@ void CDBehaviorParameterTable::LoadValuesFromDatabase() { } float CDBehaviorParameterTable::GetValue(const uint32_t behaviorID, const std::string& name, const float defaultValue) { - auto parameterID = this->m_ParametersList.find(name); - if (parameterID == this->m_ParametersList.end()) return defaultValue; + auto parameterID = m_ParametersList.find(name); + if (parameterID == m_ParametersList.end()) return defaultValue; auto hash = GetKey(behaviorID, parameterID->second); // Search for specific parameter - auto it = m_Entries.find(hash); - return it != m_Entries.end() ? it->second : defaultValue; + auto& entries = GetEntriesMutable(); + auto it = entries.find(hash); + return it != entries.end() ? it->second : defaultValue; } std::map CDBehaviorParameterTable::GetParametersByBehaviorID(uint32_t behaviorID) { + auto& entries = GetEntriesMutable(); uint64_t hashBase = behaviorID; std::map returnInfo; for (auto& [parameterString, parameterId] : m_ParametersList) { uint64_t hash = GetKey(hashBase, parameterId); - auto infoCandidate = m_Entries.find(hash); - if (infoCandidate != m_Entries.end()) { + auto infoCandidate = entries.find(hash); + if (infoCandidate != entries.end()) { returnInfo.insert(std::make_pair(parameterString, infoCandidate->second)); } } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h index 3daa3aa3..ba6ad6c1 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h @@ -5,12 +5,10 @@ #include #include -class CDBehaviorParameterTable : public CDTable { -private: - typedef uint64_t BehaviorParameterHash; - typedef float BehaviorParameterValue; - std::unordered_map m_Entries; - std::unordered_map m_ParametersList; +typedef uint64_t BehaviorParameterHash; +typedef float BehaviorParameterValue; + +class CDBehaviorParameterTable : public CDTable> { public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp index a67398a9..983156e3 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp @@ -1,5 +1,9 @@ #include "CDBehaviorTemplateTable.h" +namespace { + std::unordered_set m_EffectHandles; +}; + void CDBehaviorTemplateTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -13,11 +17,9 @@ void CDBehaviorTemplateTable::LoadValuesFromDatabase() { tableSize.finalize(); - // Reserve the size - this->entries.reserve(size); - // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorTemplate"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDBehaviorTemplate entry; entry.behaviorID = tableData.getIntField("behaviorID", -1); @@ -31,30 +33,17 @@ void CDBehaviorTemplateTable::LoadValuesFromDatabase() { entry.effectHandle = m_EffectHandles.insert(candidateToAdd).first; } - this->entries.push_back(entry); - this->entriesMappedByBehaviorID.insert(std::make_pair(entry.behaviorID, entry)); + entries.insert(std::make_pair(entry.behaviorID, entry)); tableData.nextRow(); } tableData.finalize(); } -std::vector CDBehaviorTemplateTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; -} - -const std::vector& CDBehaviorTemplateTable::GetEntries() const { - return this->entries; -} - const CDBehaviorTemplate CDBehaviorTemplateTable::GetByBehaviorID(uint32_t behaviorID) { - auto entry = this->entriesMappedByBehaviorID.find(behaviorID); - if (entry == this->entriesMappedByBehaviorID.end()) { + auto& entries = GetEntriesMutable(); + auto entry = entries.find(behaviorID); + if (entry == entries.end()) { CDBehaviorTemplate entryToReturn; entryToReturn.behaviorID = 0; entryToReturn.effectHandle = m_EffectHandles.end(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h index cbc494a2..367f5f0a 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h @@ -12,19 +12,9 @@ struct CDBehaviorTemplate { std::unordered_set::iterator effectHandle; //!< The effect handle }; - -class CDBehaviorTemplateTable : public CDTable { -private: - std::vector entries; - std::unordered_map entriesMappedByBehaviorID; - std::unordered_set m_EffectHandles; +class CDBehaviorTemplateTable : public CDTable> { public: void LoadValuesFromDatabase(); - // Queries the table with a custom "where" clause - std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; - const CDBehaviorTemplate GetByBehaviorID(uint32_t behaviorID); }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp index abc917b5..c2714396 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp @@ -14,7 +14,8 @@ void CDBrickIDTableTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BrickIDTable"); @@ -23,7 +24,7 @@ void CDBrickIDTableTable::LoadValuesFromDatabase() { entry.NDObjectID = tableData.getIntField("NDObjectID", -1); entry.LEGOBrickID = tableData.getIntField("LEGOBrickID", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -31,15 +32,9 @@ void CDBrickIDTableTable::LoadValuesFromDatabase() { } std::vector CDBrickIDTableTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDBrickIDTableTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h index 1a9f9a94..9a2c2523 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h @@ -16,14 +16,9 @@ struct CDBrickIDTable { //! BrickIDTable table -class CDBrickIDTableTable : public CDTable { -private: - std::vector entries; - +class CDBrickIDTableTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp index 3cf7ac62..4944c13b 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp @@ -4,14 +4,15 @@ void CDComponentsRegistryTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ComponentsRegistry"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDComponentsRegistry entry; entry.id = tableData.getIntField("id", -1); entry.component_type = static_cast(tableData.getIntField("component_type", 0)); entry.component_id = tableData.getIntField("component_id", -1); - this->mappedEntries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); - this->mappedEntries.insert_or_assign(entry.id, 0); + entries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); + entries.insert_or_assign(entry.id, 0); tableData.nextRow(); } @@ -20,10 +21,11 @@ void CDComponentsRegistryTable::LoadValuesFromDatabase() { } int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, eReplicaComponentType componentType, int32_t defaultValue) { - auto exists = mappedEntries.find(id); - if (exists != mappedEntries.end()) { - auto iter = mappedEntries.find(static_cast(componentType) << 32 | static_cast(id)); - return iter == mappedEntries.end() ? defaultValue : iter->second; + auto& entries = GetEntriesMutable(); + auto exists = entries.find(id); + if (exists != entries.end()) { + auto iter = entries.find(static_cast(componentType) << 32 | static_cast(id)); + return iter == entries.end() ? defaultValue : iter->second; } // Now get the data. Get all components of this entity so we dont do a query for each component @@ -38,14 +40,14 @@ int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, eReplicaComponent entry.component_type = static_cast(tableData.getIntField("component_type", 0)); entry.component_id = tableData.getIntField("component_id", -1); - this->mappedEntries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); + entries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); tableData.nextRow(); } - mappedEntries.insert_or_assign(id, 0); + entries.insert_or_assign(id, 0); - auto iter = this->mappedEntries.find(static_cast(componentType) << 32 | static_cast(id)); + auto iter = entries.find(static_cast(componentType) << 32 | static_cast(id)); - return iter == this->mappedEntries.end() ? defaultValue : iter->second; + return iter == entries.end() ? defaultValue : iter->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h index 45da7614..2165f907 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h @@ -13,10 +13,7 @@ struct CDComponentsRegistry { }; -class CDComponentsRegistryTable : public CDTable { -private: - std::unordered_map mappedEntries; //id, component_type, component_id - +class CDComponentsRegistryTable : public CDTable> { public: void LoadValuesFromDatabase(); int32_t GetByIDAndType(uint32_t id, eReplicaComponentType componentType, int32_t defaultValue = 0); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp index deb2b168..19ac7da0 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp @@ -15,7 +15,8 @@ void CDCurrencyTableTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM CurrencyTable"); @@ -27,7 +28,7 @@ void CDCurrencyTableTable::LoadValuesFromDatabase() { entry.maxvalue = tableData.getIntField("maxvalue", -1); entry.id = tableData.getIntField("id", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -35,15 +36,9 @@ void CDCurrencyTableTable::LoadValuesFromDatabase() { } std::vector CDCurrencyTableTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDCurrencyTableTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h index 9c68c277..1cd6c142 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h @@ -18,14 +18,9 @@ struct CDCurrencyTable { }; //! CurrencyTable table -class CDCurrencyTableTable : public CDTable { -private: - std::vector entries; - +class CDCurrencyTableTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp index 4939a50e..b1a6f699 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp @@ -13,7 +13,8 @@ void CDDestructibleComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM DestructibleComponent"); @@ -34,7 +35,7 @@ void CDDestructibleComponentTable::LoadValuesFromDatabase() { entry.isSmashable = tableData.getIntField("isSmashable", -1) == 1 ? true : false; entry.difficultyLevel = tableData.getIntField("difficultyLevel", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -42,15 +43,9 @@ void CDDestructibleComponentTable::LoadValuesFromDatabase() { } std::vector CDDestructibleComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDDestructibleComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h index 0871d9ea..3319907b 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h @@ -20,14 +20,9 @@ struct CDDestructibleComponent { int32_t difficultyLevel; //!< ??? }; -class CDDestructibleComponentTable : public CDTable { -private: - std::vector entries; - +class CDDestructibleComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp index a7f39705..28052819 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp @@ -2,6 +2,7 @@ void CDEmoteTableTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Emotes"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDEmoteTable entry; entry.ID = tableData.getIntField("id", -1); @@ -21,6 +22,7 @@ void CDEmoteTableTable::LoadValuesFromDatabase() { } CDEmoteTable* CDEmoteTableTable::GetEmote(int32_t id) { + auto& entries = GetEntriesMutable(); auto itr = entries.find(id); return itr != entries.end() ? &itr->second : nullptr; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h index 360cfc38..ff0b28d1 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h @@ -26,10 +26,7 @@ struct CDEmoteTable { std::string gateVersion; }; -class CDEmoteTableTable : public CDTable { -private: - std::map entries; - +class CDEmoteTableTable : public CDTable> { public: void LoadValuesFromDatabase(); // Returns an emote by ID diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp index 1a146bf1..407efff7 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp @@ -14,7 +14,8 @@ void CDFeatureGatingTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM FeatureGating"); @@ -26,7 +27,7 @@ void CDFeatureGatingTable::LoadValuesFromDatabase() { entry.minor = tableData.getIntField("minor", -1); entry.description = tableData.getStringField("description", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -35,7 +36,8 @@ void CDFeatureGatingTable::LoadValuesFromDatabase() { std::vector CDFeatureGatingTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + auto& entries = GetEntriesMutable(); + std::vector data = cpplinq::from(entries) >> cpplinq::where(predicate) >> cpplinq::to_vector(); @@ -43,6 +45,7 @@ std::vector CDFeatureGatingTable::Query(std::function= entry) { return true; @@ -51,8 +54,3 @@ bool CDFeatureGatingTable::FeatureUnlocked(const CDFeatureGating& feature) const return false; } - -const std::vector& CDFeatureGatingTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h index 5df202e3..65f33395 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h @@ -17,10 +17,7 @@ struct CDFeatureGating { } }; -class CDFeatureGatingTable : public CDTable { -private: - std::vector entries; - +class CDFeatureGatingTable : public CDTable> { public: void LoadValuesFromDatabase(); @@ -28,6 +25,4 @@ public: std::vector Query(std::function predicate); bool FeatureUnlocked(const CDFeatureGating& feature) const; - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp index 1a21a899..8cf3d8da 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp @@ -14,7 +14,8 @@ void CDInventoryComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM InventoryComponent"); @@ -25,7 +26,7 @@ void CDInventoryComponentTable::LoadValuesFromDatabase() { entry.count = tableData.getIntField("count", -1); entry.equip = tableData.getIntField("equip", -1) == 1 ? true : false; - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -33,15 +34,9 @@ void CDInventoryComponentTable::LoadValuesFromDatabase() { } std::vector CDInventoryComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDInventoryComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h index 1f5a525d..361e1a90 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h @@ -10,14 +10,9 @@ struct CDInventoryComponent { bool equip; //!< Whether or not to equip the item }; -class CDInventoryComponentTable : public CDTable { -private: - std::vector entries; - +class CDInventoryComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp index 9f7609e9..0d8b1ad9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp @@ -17,6 +17,7 @@ void CDItemComponentTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDItemComponent entry; entry.id = tableData.getIntField("id", -1); @@ -62,7 +63,7 @@ void CDItemComponentTable::LoadValuesFromDatabase() { entry.forgeType = tableData.getIntField("forgeType", -1); entry.SellMultiplier = tableData.getFloatField("SellMultiplier", -1.0f); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -70,8 +71,9 @@ void CDItemComponentTable::LoadValuesFromDatabase() { } const CDItemComponent& CDItemComponentTable::GetItemComponentByID(uint32_t skillID) { - const auto& it = this->entries.find(skillID); - if (it != this->entries.end()) { + auto& entries = GetEntriesMutable(); + const auto& it = entries.find(skillID); + if (it != entries.end()) { return it->second; } @@ -129,12 +131,12 @@ const CDItemComponent& CDItemComponentTable::GetItemComponentByID(uint32_t skill entry.forgeType = tableData.getIntField("forgeType", -1); entry.SellMultiplier = tableData.getFloatField("SellMultiplier", -1.0f); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } - const auto& it2 = this->entries.find(skillID); - if (it2 != this->entries.end()) { + const auto& it2 = entries.find(skillID); + if (it2 != entries.end()) { return it2->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h index 014c9801..60a3e412 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h @@ -49,10 +49,7 @@ struct CDItemComponent { float SellMultiplier; //!< Something to do with early vendors perhaps (but replaced) }; -class CDItemComponentTable : public CDTable { -private: - std::map entries; - +class CDItemComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); static std::map ParseCraftingCurrencies(const CDItemComponent& itemComponent); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp index 0376bad4..79bd69ae 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp @@ -14,7 +14,8 @@ void CDItemSetSkillsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSetSkills"); @@ -24,7 +25,7 @@ void CDItemSetSkillsTable::LoadValuesFromDatabase() { entry.SkillID = tableData.getIntField("SkillID", -1); entry.SkillCastType = tableData.getIntField("SkillCastType", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -32,22 +33,17 @@ void CDItemSetSkillsTable::LoadValuesFromDatabase() { } std::vector CDItemSetSkillsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } -const std::vector& CDItemSetSkillsTable::GetEntries() const { - return this->entries; -} - std::vector CDItemSetSkillsTable::GetBySkillID(uint32_t SkillSetID) { std::vector toReturn; - for (CDItemSetSkills entry : this->entries) { + for (const auto& entry : GetEntries()) { if (entry.SkillSetID == SkillSetID) toReturn.push_back(entry); if (entry.SkillSetID > SkillSetID) return toReturn; //stop seeking in the db if it's not needed. } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h index ee5fda05..78e708ae 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h @@ -9,16 +9,11 @@ struct CDItemSetSkills { uint32_t SkillCastType; //!< The skill cast type }; -class CDItemSetSkillsTable : public CDTable { -private: - std::vector entries; - +class CDItemSetSkillsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - const std::vector& GetEntries() const; - std::vector GetBySkillID(uint32_t SkillSetID); }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp index f3859ae2..77b3b1e7 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp @@ -14,7 +14,8 @@ void CDItemSetsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSets"); @@ -36,7 +37,7 @@ void CDItemSetsTable::LoadValuesFromDatabase() { entry.kitID = tableData.getIntField("kitID", -1); entry.priority = tableData.getFloatField("priority", -1.0f); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -45,14 +46,9 @@ void CDItemSetsTable::LoadValuesFromDatabase() { std::vector CDItemSetsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDItemSetsTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h index 77cc0c35..45b91590 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h @@ -21,15 +21,10 @@ struct CDItemSets { float priority; //!< The priority }; -class CDItemSetsTable : public CDTable { -private: - std::vector entries; - +class CDItemSetsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp index 930f3a85..284cf484 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp @@ -14,7 +14,8 @@ void CDLevelProgressionLookupTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LevelProgressionLookup"); @@ -24,7 +25,7 @@ void CDLevelProgressionLookupTable::LoadValuesFromDatabase() { entry.requiredUScore = tableData.getIntField("requiredUScore", -1); entry.BehaviorEffect = tableData.getStringField("BehaviorEffect", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -33,14 +34,9 @@ void CDLevelProgressionLookupTable::LoadValuesFromDatabase() { std::vector CDLevelProgressionLookupTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDLevelProgressionLookupTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h index fa1bb4cc..050d910e 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h @@ -9,15 +9,10 @@ struct CDLevelProgressionLookup { std::string BehaviorEffect; //!< The behavior effect attached to this }; -class CDLevelProgressionLookupTable : public CDTable { -private: - std::vector entries; - +class CDLevelProgressionLookupTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp index 36bebb69..cd8ae5c4 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp @@ -25,7 +25,8 @@ void CDLootMatrixTable::LoadValuesFromDatabase() { } // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootMatrix"); @@ -33,14 +34,15 @@ void CDLootMatrixTable::LoadValuesFromDatabase() { CDLootMatrix entry; uint32_t lootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); - this->entries[lootMatrixIndex].push_back(ReadRow(tableData)); + entries[lootMatrixIndex].push_back(ReadRow(tableData)); tableData.nextRow(); } } const LootMatrixEntries& CDLootMatrixTable::GetMatrix(uint32_t matrixId) { - auto itr = this->entries.find(matrixId); - if (itr != this->entries.end()) { + auto& entries = GetEntriesMutable(); + auto itr = entries.find(matrixId); + if (itr != entries.end()) { return itr->second; } @@ -49,10 +51,10 @@ const LootMatrixEntries& CDLootMatrixTable::GetMatrix(uint32_t matrixId) { auto tableData = query.execQuery(); while (!tableData.eof()) { - this->entries[matrixId].push_back(ReadRow(tableData)); + entries[matrixId].push_back(ReadRow(tableData)); tableData.nextRow(); } - return this->entries[matrixId]; + return entries[matrixId]; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h index c7157e07..b0ce7e0f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h @@ -16,7 +16,7 @@ struct CDLootMatrix { typedef uint32_t LootMatrixIndex; typedef std::vector LootMatrixEntries; -class CDLootMatrixTable : public CDTable { +class CDLootMatrixTable : public CDTable> { public: void LoadValuesFromDatabase(); @@ -24,6 +24,5 @@ public: const LootMatrixEntries& GetMatrix(uint32_t matrixId); private: CDLootMatrix ReadRow(CppSQLite3Query& tableData) const; - std::unordered_map entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp index a90f8108..0781897f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp @@ -6,8 +6,8 @@ // Sort the tables by their rarity so the highest rarity items are first. void SortTable(LootTableEntries& table) { - auto* componentsRegistryTable = CDClientManager::Instance().GetTable(); - auto* itemComponentTable = CDClientManager::Instance().GetTable(); + auto* componentsRegistryTable = CDClientManager::GetTable(); + auto* itemComponentTable = CDClientManager::GetTable(); // We modify the table in place so the outer loop keeps track of what is sorted // and the inner loop finds the highest rarity item and swaps it with the current position // of the outer loop. @@ -49,7 +49,8 @@ void CDLootTableTable::LoadValuesFromDatabase() { } // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootTable"); @@ -57,17 +58,18 @@ void CDLootTableTable::LoadValuesFromDatabase() { CDLootTable entry; uint32_t lootTableIndex = tableData.getIntField("LootTableIndex", -1); - this->entries[lootTableIndex].push_back(ReadRow(tableData)); + entries[lootTableIndex].emplace_back(ReadRow(tableData)); tableData.nextRow(); } - for (auto& [id, table] : this->entries) { + for (auto& [id, table] : entries) { SortTable(table); } } -const LootTableEntries& CDLootTableTable::GetTable(uint32_t tableId) { - auto itr = this->entries.find(tableId); - if (itr != this->entries.end()) { +const LootTableEntries& CDLootTableTable::GetTable(const uint32_t tableId) { + auto& entries = GetEntriesMutable(); + auto itr = entries.find(tableId); + if (itr != entries.end()) { return itr->second; } @@ -77,10 +79,10 @@ const LootTableEntries& CDLootTableTable::GetTable(uint32_t tableId) { while (!tableData.eof()) { CDLootTable entry; - this->entries[tableId].push_back(ReadRow(tableData)); + entries[tableId].emplace_back(ReadRow(tableData)); tableData.nextRow(); } - SortTable(this->entries[tableId]); + SortTable(entries[tableId]); - return this->entries[tableId]; + return entries[tableId]; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h index e432d621..c88ba03c 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h @@ -3,6 +3,8 @@ // Custom Classes #include "CDTable.h" +#include + struct CDLootTable { uint32_t itemid; //!< The LOT of the item uint32_t LootTableIndex; //!< The Loot Table Index @@ -13,14 +15,12 @@ struct CDLootTable { typedef uint32_t LootTableIndex; typedef std::vector LootTableEntries; -class CDLootTableTable : public CDTable { +class CDLootTableTable : public CDTable> { private: CDLootTable ReadRow(CppSQLite3Query& tableData) const; - std::unordered_map entries; public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause - const LootTableEntries& GetTable(uint32_t tableId); + const LootTableEntries& GetTable(const uint32_t tableId); }; - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp index c7e884c2..5acaa906 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp @@ -1,7 +1,7 @@ #include "CDMissionEmailTable.h" -void CDMissionEmailTable::LoadValuesFromDatabase() { +void CDMissionEmailTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionEmail"); @@ -14,12 +14,13 @@ void CDMissionEmailTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionEmail"); while (!tableData.eof()) { - CDMissionEmail entry; + auto& entry = entries.emplace_back(); entry.ID = tableData.getIntField("ID", -1); entry.messageType = tableData.getIntField("messageType", -1); entry.notificationGroup = tableData.getIntField("notificationGroup", -1); @@ -29,24 +30,15 @@ void CDMissionEmailTable::LoadValuesFromDatabase() { entry.locStatus = tableData.getIntField("locStatus", -1); entry.gate_version = tableData.getStringField("gate_version", ""); - this->entries.push_back(entry); tableData.nextRow(); } - - tableData.finalize(); } //! Queries the table with a custom "where" clause std::vector CDMissionEmailTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDMissionEmailTable::GetEntries() const { - return this->entries; -} diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h index 06c15e71..ea48b423 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h @@ -3,6 +3,8 @@ // Custom Classes #include "CDTable.h" +#include + struct CDMissionEmail { uint32_t ID; uint32_t messageType; @@ -15,14 +17,9 @@ struct CDMissionEmail { }; -class CDMissionEmailTable : public CDTable { -private: - std::vector entries; - +class CDMissionEmailTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp index 87d2bd61..e475a998 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp @@ -14,37 +14,29 @@ void CDMissionNPCComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionNPCComponent"); while (!tableData.eof()) { - CDMissionNPCComponent entry; + auto& entry = entries.emplace_back(); entry.id = tableData.getIntField("id", -1); entry.missionID = tableData.getIntField("missionID", -1); entry.offersMission = tableData.getIntField("offersMission", -1) == 1 ? true : false; entry.acceptsMission = tableData.getIntField("acceptsMission", -1) == 1 ? true : false; entry.gate_version = tableData.getStringField("gate_version", ""); - this->entries.push_back(entry); tableData.nextRow(); } - - tableData.finalize(); } //! Queries the table with a custom "where" clause std::vector CDMissionNPCComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDMissionNPCComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h index 8c4b790d..dde81251 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h @@ -3,6 +3,8 @@ // Custom Classes #include "CDTable.h" +#include + struct CDMissionNPCComponent { uint32_t id; //!< The ID uint32_t missionID; //!< The Mission ID @@ -11,17 +13,9 @@ struct CDMissionNPCComponent { std::string gate_version; //!< The gate version }; -class CDMissionNPCComponentTable : public CDTable { -private: - std::vector entries; - +class CDMissionNPCComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - // Gets all the entries in the table - const std::vector& GetEntries() const; - }; - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp index b2cb9e21..b9584032 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp @@ -14,12 +14,13 @@ void CDMissionTasksTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionTasks"); while (!tableData.eof()) { - CDMissionTasks entry; + auto& entry = entries.emplace_back(); entry.id = tableData.getIntField("id", -1); UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1)); entry.taskType = tableData.getIntField("taskType", -1); @@ -34,26 +35,24 @@ void CDMissionTasksTable::LoadValuesFromDatabase() { UNUSED(entry.localize = tableData.getIntField("localize", -1) == 1 ? true : false); UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); - this->entries.push_back(entry); tableData.nextRow(); } - - tableData.finalize(); } std::vector CDMissionTasksTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } -std::vector CDMissionTasksTable::GetByMissionID(uint32_t missionID) { +std::vector CDMissionTasksTable::GetByMissionID(const uint32_t missionID) { std::vector tasks; - for (auto& entry : this->entries) { + // TODO: this should not be linear(?) and also shouldnt need to be a pointer + for (auto& entry : GetEntriesMutable()) { if (entry.id == missionID) { tasks.push_back(&entry); } @@ -62,7 +61,6 @@ std::vector CDMissionTasksTable::GetByMissionID(uint32_t missio return tasks; } -const std::vector& CDMissionTasksTable::GetEntries() const { - return this->entries; +const typename CDMissionTasksTable::StorageType& CDMissionTasksTable::GetEntries() const { + return CDTable::GetEntries(); } - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h index 420dbfbe..60a21073 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h @@ -3,6 +3,8 @@ // Custom Classes #include "CDTable.h" +#include + struct CDMissionTasks { uint32_t id; //!< The Mission ID that the task belongs to UNUSED(uint32_t locStatus); //!< ??? @@ -19,17 +21,15 @@ struct CDMissionTasks { UNUSED(std::string gate_version); //!< ??? }; -class CDMissionTasksTable : public CDTable { -private: - std::vector entries; - +class CDMissionTasksTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - std::vector GetByMissionID(uint32_t missionID); + std::vector GetByMissionID(const uint32_t missionID); - const std::vector& GetEntries() const; + // TODO: Remove this and replace it with a proper lookup function. + const CDTable::StorageType& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp index bc9eb76c..c98254ea 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp @@ -16,12 +16,13 @@ void CDMissionsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Missions"); while (!tableData.eof()) { - CDMissions entry; + auto& entry = entries.emplace_back(); entry.id = tableData.getIntField("id", -1); entry.defined_type = tableData.getStringField("defined_type", ""); entry.defined_subtype = tableData.getStringField("defined_subtype", ""); @@ -75,10 +76,8 @@ void CDMissionsTable::LoadValuesFromDatabase() { UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1)); entry.reward_bankinventory = tableData.getIntField("reward_bankinventory", -1); - this->entries.push_back(entry); tableData.nextRow(); } - tableData.finalize(); Default.id = -1; @@ -86,19 +85,15 @@ void CDMissionsTable::LoadValuesFromDatabase() { std::vector CDMissionsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } -const std::vector& CDMissionsTable::GetEntries(void) const { - return this->entries; -} - const CDMissions* CDMissionsTable::GetPtrByMissionID(uint32_t missionID) const { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.id == missionID) { return const_cast(&entry); } @@ -108,7 +103,7 @@ const CDMissions* CDMissionsTable::GetPtrByMissionID(uint32_t missionID) const { } const CDMissions& CDMissionsTable::GetByMissionID(uint32_t missionID, bool& found) const { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.id == missionID) { found = true; @@ -121,3 +116,12 @@ const CDMissions& CDMissionsTable::GetByMissionID(uint32_t missionID, bool& foun return Default; } +const std::set CDMissionsTable::GetMissionsForReward(LOT lot) { + std::set toReturn {}; + for (const auto& entry : GetEntries()) { + if (lot == entry.reward_item1 || lot == entry.reward_item2 || lot == entry.reward_item3 || lot == entry.reward_item4) { + toReturn.insert(entry.id); + } + } + return toReturn; +} diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h index de4b21c3..c5ae0e88 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h @@ -60,22 +60,18 @@ struct CDMissions { int32_t reward_bankinventory; //!< The amount of bank space this mission rewards }; -class CDMissionsTable : public CDTable { -private: - std::vector entries; - +class CDMissionsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - // Gets all the entries in the table - const std::vector& GetEntries() const; - const CDMissions* GetPtrByMissionID(uint32_t missionID) const; const CDMissions& GetByMissionID(uint32_t missionID, bool& found) const; + const std::set GetMissionsForReward(LOT lot); + + static CDMissions Default; }; - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp index be1c3d96..cec27bb9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp @@ -14,12 +14,13 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MovementAIComponent"); while (!tableData.eof()) { - CDMovementAIComponent entry; + auto& entry = entries.emplace_back(); entry.id = tableData.getIntField("id", -1); entry.MovementType = tableData.getStringField("MovementType", ""); entry.WanderChance = tableData.getFloatField("WanderChance", -1.0f); @@ -29,23 +30,15 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() { entry.WanderRadius = tableData.getFloatField("WanderRadius", -1.0f); entry.attachedPath = tableData.getStringField("attachedPath", ""); - this->entries.push_back(entry); tableData.nextRow(); } - - tableData.finalize(); } std::vector CDMovementAIComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDMovementAIComponentTable::GetEntries(void) const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h index 8b415f3a..6671d945 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h @@ -3,6 +3,8 @@ // Custom Classes #include "CDTable.h" +#include + struct CDMovementAIComponent { uint32_t id; std::string MovementType; @@ -14,15 +16,9 @@ struct CDMovementAIComponent { std::string attachedPath; }; -class CDMovementAIComponentTable : public CDTable { -private: - std::vector entries; - +class CDMovementAIComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - // Gets all the entries in the table - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp index 958c6cc8..a07446b5 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp @@ -14,33 +14,27 @@ void CDObjectSkillsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ObjectSkills"); while (!tableData.eof()) { - CDObjectSkills entry; + auto &entry = entries.emplace_back(); entry.objectTemplate = tableData.getIntField("objectTemplate", -1); entry.skillID = tableData.getIntField("skillID", -1); entry.castOnType = tableData.getIntField("castOnType", -1); entry.AICombatWeight = tableData.getIntField("AICombatWeight", -1); - this->entries.push_back(entry); tableData.nextRow(); } - - tableData.finalize(); } std::vector CDObjectSkillsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDObjectSkillsTable::GetEntries() const { - return this->entries; -} diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h index 0b88fb6f..731f6657 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h @@ -3,6 +3,8 @@ // Custom Classes #include "CDTable.h" +#include + struct CDObjectSkills { uint32_t objectTemplate; //!< The LOT of the item uint32_t skillID; //!< The Skill ID of the object @@ -10,17 +12,10 @@ struct CDObjectSkills { uint32_t AICombatWeight; //!< ??? }; -class CDObjectSkillsTable : public CDTable { -private: - std::vector entries; - +class CDObjectSkillsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - // Gets all the entries in the table - const std::vector& GetEntries() const; - }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp index 3282e14c..738a13ac 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp @@ -1,5 +1,9 @@ #include "CDObjectsTable.h" +namespace { + CDObjects ObjDefault; +}; + void CDObjectsTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; @@ -14,9 +18,12 @@ void CDObjectsTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Objects"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { - CDObjects entry; - entry.id = tableData.getIntField("id", -1); + const uint32_t lot = tableData.getIntField("id", 0); + + auto& entry = entries[lot]; + entry.id = lot; entry.name = tableData.getStringField("name", ""); UNUSED_COLUMN(entry.placeable = tableData.getIntField("placeable", -1);) entry.type = tableData.getStringField("type", ""); @@ -31,34 +38,34 @@ void CDObjectsTable::LoadValuesFromDatabase() { UNUSED_COLUMN(entry.gate_version = tableData.getStringField("gate_version", "");) UNUSED_COLUMN(entry.HQ_valid = tableData.getIntField("HQ_valid", -1);) - this->entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } - tableData.finalize(); - - m_default.id = 0; + ObjDefault.id = 0; } -const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) { - const auto& it = this->entries.find(LOT); - if (it != this->entries.end()) { +const CDObjects& CDObjectsTable::GetByID(const uint32_t lot) { + auto& entries = GetEntriesMutable(); + const auto& it = entries.find(lot); + if (it != entries.end()) { return it->second; } auto query = CDClientDatabase::CreatePreppedStmt("SELECT * FROM Objects WHERE id = ?;"); - query.bind(1, static_cast(LOT)); + query.bind(1, static_cast(lot)); auto tableData = query.execQuery(); if (tableData.eof()) { - this->entries.insert(std::make_pair(LOT, m_default)); - return m_default; + entries.emplace(lot, ObjDefault); + return ObjDefault; } // Now get the data while (!tableData.eof()) { - CDObjects entry; - entry.id = tableData.getIntField("id", -1); + const uint32_t lot = tableData.getIntField("id", 0); + + auto& entry = entries[lot]; + entry.id = lot; entry.name = tableData.getStringField("name", ""); UNUSED(entry.placeable = tableData.getIntField("placeable", -1)); entry.type = tableData.getStringField("type", ""); @@ -73,17 +80,15 @@ const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) { UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); UNUSED(entry.HQ_valid = tableData.getIntField("HQ_valid", -1)); - this->entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } tableData.finalize(); - const auto& it2 = entries.find(LOT); + const auto& it2 = entries.find(lot); if (it2 != entries.end()) { return it2->second; } - return m_default; + return ObjDefault; } - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h index 2ef47727..13bb90fa 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h @@ -3,6 +3,8 @@ // Custom Classes #include "CDTable.h" +#include + struct CDObjects { uint32_t id; //!< The LOT of the object std::string name; //!< The internal name of the object @@ -20,14 +22,10 @@ struct CDObjects { UNUSED(uint32_t HQ_valid); //!< Probably used for the Nexus HQ database on LEGOUniverse.com }; -class CDObjectsTable : public CDTable { -private: - std::map entries; - CDObjects m_default; - +class CDObjectsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Gets an entry by ID - const CDObjects& GetByID(uint32_t LOT); + const CDObjects& GetByID(const uint32_t lot); }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp index 8038c779..a18ae8d9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp @@ -13,18 +13,17 @@ void CDPackageComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); - // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PackageComponent"); while (!tableData.eof()) { - CDPackageComponent entry; + auto& entry = entries.emplace_back(); entry.id = tableData.getIntField("id", -1); entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); entry.packageType = tableData.getIntField("packageType", -1); - this->entries.push_back(entry); tableData.nextRow(); } @@ -34,15 +33,9 @@ void CDPackageComponentTable::LoadValuesFromDatabase() { //! Queries the table with a custom "where" clause std::vector CDPackageComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDPackageComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h index cc8b0636..7d73fe8f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h @@ -3,20 +3,17 @@ // Custom Classes #include "CDTable.h" +#include + struct CDPackageComponent { uint32_t id; uint32_t LootMatrixIndex; uint32_t packageType; }; -class CDPackageComponentTable : public CDTable { -private: - std::vector entries; - +class CDPackageComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp index c3dd5d50..f3371ecb 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp @@ -23,10 +23,12 @@ namespace { void CDPetComponentTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PetComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { const uint32_t componentID = tableData.getIntField("id", defaultEntry.id); - auto& entry = m_Entries[componentID]; + auto& entry = entries[componentID]; + entry.id = componentID; UNUSED_COLUMN(entry.minTameUpdateTime = tableData.getFloatField("minTameUpdateTime", defaultEntry.minTameUpdateTime)); UNUSED_COLUMN(entry.maxTameUpdateTime = tableData.getFloatField("maxTameUpdateTime", defaultEntry.maxTameUpdateTime)); @@ -48,12 +50,13 @@ void CDPetComponentTable::LoadValuesFromDatabase() { } void CDPetComponentTable::LoadValuesFromDefaults() { - m_Entries.insert(std::make_pair(defaultEntry.id, defaultEntry)); + GetEntriesMutable().insert(std::make_pair(defaultEntry.id, defaultEntry)); } CDPetComponent& CDPetComponentTable::GetByID(const uint32_t componentID) { - auto itr = m_Entries.find(componentID); - if (itr == m_Entries.end()) { + auto& entries = GetEntriesMutable(); + auto itr = entries.find(componentID); + if (itr == entries.end()) { LOG("Unable to load pet component (ID %i) values from database! Using default values instead.", componentID); return defaultEntry; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h index fa54e457..42890253 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h @@ -21,7 +21,7 @@ struct CDPetComponent { UNUSED_COLUMN(std::string buffIDs;) }; -class CDPetComponentTable : public CDTable { +class CDPetComponentTable : public CDTable> { public: /** @@ -39,7 +39,4 @@ public: * @returns A reference to the corresponding table, or the default if one could not be found */ CDPetComponent& GetByID(const uint32_t componentID); - -private: - std::map m_Entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp index ebc5327b..050312b1 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp @@ -2,34 +2,35 @@ void CDPhysicsComponentTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PhysicsComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { - CDPhysicsComponent entry; - entry.id = tableData.getIntField("id", -1); + const uint32_t componentID = tableData.getIntField("id", -1); + + auto& entry = entries[componentID]; + entry.id = componentID; entry.bStatic = tableData.getIntField("static", -1) != 0; entry.physicsAsset = tableData.getStringField("physics_asset", ""); - UNUSED(entry->jump = tableData.getIntField("jump", -1) != 0); - UNUSED(entry->doublejump = tableData.getIntField("doublejump", -1) != 0); - entry.speed = tableData.getFloatField("speed", -1); - UNUSED(entry->rotSpeed = tableData.getFloatField("rotSpeed", -1)); - entry.playerHeight = tableData.getFloatField("playerHeight"); - entry.playerRadius = tableData.getFloatField("playerRadius"); + UNUSED_COLUMN(entry.jump = tableData.getIntField("jump", -1) != 0;) + UNUSED_COLUMN(entry.doubleJump = tableData.getIntField("doublejump", -1) != 0;) + entry.speed = static_cast(tableData.getFloatField("speed", -1)); + UNUSED_COLUMN(entry.rotSpeed = tableData.getFloatField("rotSpeed", -1);) + entry.playerHeight = static_cast(tableData.getFloatField("playerHeight")); + entry.playerRadius = static_cast(tableData.getFloatField("playerRadius")); entry.pcShapeType = tableData.getIntField("pcShapeType"); entry.collisionGroup = tableData.getIntField("collisionGroup"); - UNUSED(entry->airSpeed = tableData.getFloatField("airSpeed")); - UNUSED(entry->boundaryAsset = tableData.getStringField("boundaryAsset")); - UNUSED(entry->jumpAirSpeed = tableData.getFloatField("jumpAirSpeed")); - UNUSED(entry->friction = tableData.getFloatField("friction")); - UNUSED(entry->gravityVolumeAsset = tableData.getStringField("gravityVolumeAsset")); + UNUSED_COLUMN(entry.airSpeed = tableData.getFloatField("airSpeed");) + UNUSED_COLUMN(entry.boundaryAsset = tableData.getStringField("boundaryAsset");) + UNUSED_COLUMN(entry.jumpAirSpeed = tableData.getFloatField("jumpAirSpeed");) + UNUSED_COLUMN(entry.friction = tableData.getFloatField("friction");) + UNUSED_COLUMN(entry.gravityVolumeAsset = tableData.getStringField("gravityVolumeAsset");) - m_entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } - - tableData.finalize(); } -CDPhysicsComponent* CDPhysicsComponentTable::GetByID(uint32_t componentID) { - auto itr = m_entries.find(componentID); - return itr != m_entries.end() ? &itr->second : nullptr; +CDPhysicsComponent* CDPhysicsComponentTable::GetByID(const uint32_t componentID) { + auto& entries = GetEntriesMutable(); + auto itr = entries.find(componentID); + return itr != entries.end() ? &itr->second : nullptr; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h index 5ed33cc9..b783a826 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h @@ -1,5 +1,6 @@ #pragma once #include "CDTable.h" +#include #include struct CDPhysicsComponent { @@ -7,7 +8,7 @@ struct CDPhysicsComponent { bool bStatic; std::string physicsAsset; UNUSED(bool jump); - UNUSED(bool doublejump); + UNUSED(bool doubleJump); float speed; UNUSED(float rotSpeed); float playerHeight; @@ -21,13 +22,10 @@ struct CDPhysicsComponent { UNUSED(std::string gravityVolumeAsset); }; -class CDPhysicsComponentTable : public CDTable { +class CDPhysicsComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); static const std::string GetTableName() { return "PhysicsComponent"; }; - CDPhysicsComponent* GetByID(uint32_t componentID); - -private: - std::map m_entries; + CDPhysicsComponent* GetByID(const uint32_t componentID); }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp index c1532c86..dfb591d1 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp @@ -1,5 +1,9 @@ #include "CDPropertyEntranceComponentTable.h" +namespace { + CDPropertyEntranceComponent defaultEntry{}; +}; + void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -12,7 +16,8 @@ void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyEntranceComponent;"); while (!tableData.eof()) { @@ -24,7 +29,7 @@ void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { tableData.getStringField("groupType", "") }; - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -32,11 +37,10 @@ void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { } CDPropertyEntranceComponent CDPropertyEntranceComponentTable::GetByID(uint32_t id) { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.id == id) return entry; } return defaultEntry; } - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h index 5c7d0965..f687b881 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h @@ -9,15 +9,9 @@ struct CDPropertyEntranceComponent { std::string groupType; }; -class CDPropertyEntranceComponentTable : public CDTable { +class CDPropertyEntranceComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause CDPropertyEntranceComponent GetByID(uint32_t id); - - // Gets all the entries in the table - [[nodiscard]] const std::vector& GetEntries() const { return entries; } -private: - std::vector entries{}; - CDPropertyEntranceComponent defaultEntry{}; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp index 4a1d666e..4046b6fa 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp @@ -1,5 +1,9 @@ #include "CDPropertyTemplateTable.h" +namespace { + CDPropertyTemplate defaultEntry{}; +}; + void CDPropertyTemplateTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -12,7 +16,8 @@ void CDPropertyTemplateTable::LoadValuesFromDatabase() { tableSize.finalize(); - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyTemplate;"); while (!tableData.eof()) { @@ -23,7 +28,7 @@ void CDPropertyTemplateTable::LoadValuesFromDatabase() { tableData.getStringField("spawnName", "") }; - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -31,7 +36,7 @@ void CDPropertyTemplateTable::LoadValuesFromDatabase() { } CDPropertyTemplate CDPropertyTemplateTable::GetByMapID(uint32_t mapID) { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.mapID == mapID) return entry; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h index 7261bdf9..e0c6c485 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h @@ -8,13 +8,9 @@ struct CDPropertyTemplate { std::string spawnName; }; -class CDPropertyTemplateTable : public CDTable { +class CDPropertyTemplateTable : public CDTable> { public: void LoadValuesFromDatabase(); - static const std::string GetTableName() { return "PropertyTemplate"; }; CDPropertyTemplate GetByMapID(uint32_t mapID); -private: - std::vector entries{}; - CDPropertyTemplate defaultEntry{}; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp index 6edd00b2..279d6408 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp @@ -14,7 +14,8 @@ void CDProximityMonitorComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ProximityMonitorComponent"); @@ -25,7 +26,7 @@ void CDProximityMonitorComponentTable::LoadValuesFromDatabase() { entry.LoadOnClient = tableData.getIntField("LoadOnClient", -1); entry.LoadOnServer = tableData.getIntField("LoadOnServer", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -34,14 +35,9 @@ void CDProximityMonitorComponentTable::LoadValuesFromDatabase() { std::vector CDProximityMonitorComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDProximityMonitorComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h index 861c900e..af2c385e 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h @@ -10,14 +10,9 @@ struct CDProximityMonitorComponent { bool LoadOnServer; }; -class CDProximityMonitorComponentTable : public CDTable { -private: - std::vector entries; - +class CDProximityMonitorComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); //! Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp index 34ec5826..72a26beb 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp @@ -3,6 +3,7 @@ void CDRailActivatorComponentTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RailActivatorComponent;"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDRailActivatorComponent entry; @@ -36,7 +37,7 @@ void CDRailActivatorComponentTable::LoadValuesFromDatabase() { entry.showNameBillboard = tableData.getIntField("ShowNameBillboard", 0); - m_Entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -44,7 +45,7 @@ void CDRailActivatorComponentTable::LoadValuesFromDatabase() { } CDRailActivatorComponent CDRailActivatorComponentTable::GetEntryByID(int32_t id) const { - for (const auto& entry : m_Entries) { + for (const auto& entry : GetEntries()) { if (entry.id == id) return entry; } @@ -52,10 +53,6 @@ CDRailActivatorComponent CDRailActivatorComponentTable::GetEntryByID(int32_t id) return {}; } -const std::vector& CDRailActivatorComponentTable::GetEntries() const { - return m_Entries; -} - std::pair CDRailActivatorComponentTable::EffectPairFromString(std::string& str) { const auto split = GeneralUtils::SplitString(str, ':'); if (split.size() == 2) { diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h index d06b2d36..d9a94d37 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h @@ -20,13 +20,10 @@ struct CDRailActivatorComponent { bool showNameBillboard; }; -class CDRailActivatorComponentTable : public CDTable { +class CDRailActivatorComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); - static const std::string GetTableName() { return "RailActivatorComponent"; }; [[nodiscard]] CDRailActivatorComponent GetEntryByID(int32_t id) const; - [[nodiscard]] const std::vector& GetEntries() const; private: static std::pair EffectPairFromString(std::string& str); - std::vector m_Entries{}; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp index 6f086e34..def27339 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp @@ -14,7 +14,8 @@ void CDRarityTableTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RarityTable order by randmax desc;"); @@ -30,5 +31,5 @@ void CDRarityTableTable::LoadValuesFromDatabase() { } const std::vector& CDRarityTableTable::GetRarityTable(uint32_t id) { - return entries[id]; + return GetEntriesMutable()[id]; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h index 1248350b..006ac986 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h @@ -6,15 +6,13 @@ struct CDRarityTable { float randmax; uint32_t rarity; + + typedef uint32_t Index; }; typedef std::vector RarityTable; -class CDRarityTableTable : public CDTable { -private: - typedef uint32_t RarityTableIndex; - std::unordered_map> entries; - +class CDRarityTableTable : public CDTable>> { public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp index 30534936..8a07db88 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp @@ -14,7 +14,8 @@ void CDRebuildComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RebuildComponent"); @@ -31,7 +32,7 @@ void CDRebuildComponentTable::LoadValuesFromDatabase() { entry.post_imagination_cost = tableData.getIntField("post_imagination_cost", -1); entry.time_before_smash = tableData.getFloatField("time_before_smash", -1.0f); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -40,14 +41,9 @@ void CDRebuildComponentTable::LoadValuesFromDatabase() { std::vector CDRebuildComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDRebuildComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h index aed71905..0eeb62ae 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h @@ -16,15 +16,10 @@ struct CDRebuildComponent { float time_before_smash; //!< The time before smash }; -class CDRebuildComponentTable : public CDTable { -private: - std::vector entries; - +class CDRebuildComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp index 4dab9ee9..8ade60a9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp @@ -14,7 +14,8 @@ void CDRewardCodesTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RewardCodes"); @@ -26,20 +27,20 @@ void CDRewardCodesTable::LoadValuesFromDatabase() { UNUSED_COLUMN(entry.locStatus = tableData.getIntField("locStatus", -1)); UNUSED_COLUMN(entry.gate_version = tableData.getStringField("gate_version", "")); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } } LOT CDRewardCodesTable::GetAttachmentLOT(uint32_t rewardCodeId) const { - for (auto const &entry : this->entries){ + for (auto const &entry : GetEntries()){ if (rewardCodeId == entry.id) return entry.attachmentLOT; } return LOT_NULL; } uint32_t CDRewardCodesTable::GetCodeID(std::string code) const { - for (auto const &entry : this->entries){ + for (auto const &entry : GetEntries()){ if (code == entry.code) return entry.id; } return -1; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h index 1010a572..aa64c3bb 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h @@ -13,13 +13,9 @@ struct CDRewardCode { }; -class CDRewardCodesTable : public CDTable { -private: - std::vector entries; - +class CDRewardCodesTable : public CDTable> { public: void LoadValuesFromDatabase(); - const std::vector& GetEntries() const; LOT GetAttachmentLOT(uint32_t rewardCodeId) const; uint32_t GetCodeID(std::string code) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp index 27c2344a..4539e417 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp @@ -2,6 +2,7 @@ void CDRewardsTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Rewards"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDRewards entry; entry.id = tableData.getIntField("id", -1); @@ -11,7 +12,7 @@ void CDRewardsTable::LoadValuesFromDatabase() { entry.value = tableData.getIntField("value", -1); entry.count = tableData.getIntField("count", -1); - m_entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -20,7 +21,7 @@ void CDRewardsTable::LoadValuesFromDatabase() { std::vector CDRewardsTable::GetByLevelID(uint32_t levelID) { std::vector result{}; - for (const auto& e : m_entries) { + for (const auto& e : GetEntries()) { if (e.second.levelID == levelID) result.push_back(e.second); } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h index 9c24397b..cec787cf 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h @@ -11,13 +11,9 @@ struct CDRewards { int32_t count; }; -class CDRewardsTable : public CDTable { +class CDRewardsTable : public CDTable> { public: void LoadValuesFromDatabase(); - static const std::string GetTableName() { return "Rewards"; }; std::vector GetByLevelID(uint32_t levelID); - -private: - std::map m_entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp index a2fe0514..02e3e29c 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp @@ -1,5 +1,9 @@ #include "CDScriptComponentTable.h" +namespace { + CDScriptComponent m_ToReturnWhenNoneFound; +}; + void CDScriptComponentTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -15,13 +19,14 @@ void CDScriptComponentTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ScriptComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDScriptComponent entry; entry.id = tableData.getIntField("id", -1); entry.script_name = tableData.getStringField("script_name", ""); entry.client_script_name = tableData.getStringField("client_script_name", ""); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -29,8 +34,9 @@ void CDScriptComponentTable::LoadValuesFromDatabase() { } const CDScriptComponent& CDScriptComponentTable::GetByID(uint32_t id) { - std::map::iterator it = this->entries.find(id); - if (it != this->entries.end()) { + auto& entries = GetEntries(); + auto it = entries.find(id); + if (it != entries.end()) { return it->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h index 56296776..96c1b5a5 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h @@ -9,11 +9,7 @@ struct CDScriptComponent { std::string client_script_name; //!< The client script name }; -class CDScriptComponentTable : public CDTable { -private: - std::map entries; - CDScriptComponent m_ToReturnWhenNoneFound; - +class CDScriptComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Gets an entry by scriptID diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp index 51ed7de3..0df67884 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp @@ -1,8 +1,10 @@ #include "CDSkillBehaviorTable.h" -void CDSkillBehaviorTable::LoadValuesFromDatabase() { - m_empty = CDSkillBehavior(); +namespace { + CDSkillBehavior m_empty = CDSkillBehavior(); +}; +void CDSkillBehaviorTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM SkillBehavior"); @@ -14,8 +16,7 @@ void CDSkillBehaviorTable::LoadValuesFromDatabase() { tableSize.finalize(); - // Reserve the size - //this->entries.reserve(size); + auto& entries = GetEntriesMutable(); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM SkillBehavior"); @@ -41,7 +42,7 @@ void CDSkillBehaviorTable::LoadValuesFromDatabase() { UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); UNUSED(entry.cancelType = tableData.getIntField("cancelType", -1)); - this->entries.insert(std::make_pair(entry.skillID, entry)); + entries.insert(std::make_pair(entry.skillID, entry)); //this->entries.push_back(entry); tableData.nextRow(); } @@ -50,8 +51,9 @@ void CDSkillBehaviorTable::LoadValuesFromDatabase() { } const CDSkillBehavior& CDSkillBehaviorTable::GetSkillByID(uint32_t skillID) { - std::map::iterator it = this->entries.find(skillID); - if (it != this->entries.end()) { + auto& entries = GetEntries(); + auto it = entries.find(skillID); + if (it != entries.end()) { return it->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h index 0c970be6..19225d19 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h @@ -25,11 +25,7 @@ struct CDSkillBehavior { UNUSED(uint32_t cancelType); //!< The cancel type (?) }; -class CDSkillBehaviorTable : public CDTable { -private: - std::map entries; - CDSkillBehavior m_empty; - +class CDSkillBehaviorTable : public CDTable> { public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDTable.h index ab965127..4e896dbb 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDTable.h @@ -1,6 +1,7 @@ #pragma once #include "CDClientDatabase.h" +#include "CDClientManager.h" #include "Singleton.h" #include "DluAssert.h" @@ -27,22 +28,23 @@ #define UNUSED_ENTRY(v, x) #pragma warning (disable : 4244) //Disable double to float conversion warnings -#pragma warning (disable : 4715) //Disable "not all control paths return a value" +// #pragma warning (disable : 4715) //Disable "not all control paths return a value" -template +template class CDTable : public Singleton
{ +public: + typedef Storage StorageType; + protected: virtual ~CDTable() = default; -}; -template -class LookupResult { - typedef std::pair DataType; -public: - LookupResult() { m_data.first = T(); m_data.second = false; }; - LookupResult(T& data) { m_data.first = data; m_data.second = true; }; - inline const T& Data() { return m_data.first; }; - inline const bool& FoundData() { return m_data.second; }; -private: - DataType m_data; + // If you need these for a specific table, override it such that there is a public variant. + [[nodiscard]] StorageType& GetEntriesMutable() const { + return CDClientManager::GetEntriesMutable
(); + } + + // If you need these for a specific table, override it such that there is a public variant. + [[nodiscard]] const StorageType& GetEntries() const { + return GetEntriesMutable(); + } }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp index 990d0b32..f639a7e3 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp @@ -14,7 +14,8 @@ void CDVendorComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM VendorComponent"); @@ -26,7 +27,7 @@ void CDVendorComponentTable::LoadValuesFromDatabase() { entry.refreshTimeSeconds = tableData.getFloatField("refreshTimeSeconds", -1.0f); entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -36,15 +37,9 @@ void CDVendorComponentTable::LoadValuesFromDatabase() { //! Queries the table with a custom "where" clause std::vector CDVendorComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDVendorComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h index 133ce78f..cbed2d13 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h @@ -11,15 +11,10 @@ struct CDVendorComponent { uint32_t LootMatrixIndex; //!< LootMatrixIndex of the vendor's items }; -class CDVendorComponentTable : public CDTable { -private: - std::vector entries; - +class CDVendorComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp index b599c37f..6aaeb854 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp @@ -15,6 +15,7 @@ void CDZoneTableTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ZoneTable"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDZoneTable entry; entry.zoneID = tableData.getIntField("zoneID", -1); @@ -45,7 +46,7 @@ void CDZoneTableTable::LoadValuesFromDatabase() { UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); entry.mountsAllowed = tableData.getIntField("mountsAllowed", -1) == 1 ? true : false; - this->m_Entries.insert(std::make_pair(entry.zoneID, entry)); + entries.insert(std::make_pair(entry.zoneID, entry)); tableData.nextRow(); } @@ -54,6 +55,7 @@ void CDZoneTableTable::LoadValuesFromDatabase() { //! Queries the table with a zoneID to find. const CDZoneTable* CDZoneTableTable::Query(uint32_t zoneID) { + auto& m_Entries = GetEntries(); const auto& iter = m_Entries.find(zoneID); if (iter != m_Entries.end()) { diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h index 5f5970ae..b1e8b1ba 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h @@ -33,10 +33,7 @@ struct CDZoneTable { bool mountsAllowed; //!< Whether or not mounts are allowed }; -class CDZoneTableTable : public CDTable { -private: - std::map m_Entries; - +class CDZoneTableTable : public CDTable> { public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CMakeLists.txt b/dDatabase/CDClientDatabase/CMakeLists.txt index 2645c215..13d59ffb 100644 --- a/dDatabase/CDClientDatabase/CMakeLists.txt +++ b/dDatabase/CDClientDatabase/CMakeLists.txt @@ -9,4 +9,28 @@ foreach(file ${DDATABASE_CDCLIENTDATABASE_CDCLIENTTABLES_SOURCES}) set(DDATABASE_CDCLIENTDATABASE_SOURCES ${DDATABASE_CDCLIENTDATABASE_SOURCES} "CDClientTables/${file}") endforeach() -set(DDATABASE_CDCLIENTDATABASE_SOURCES ${DDATABASE_CDCLIENTDATABASE_SOURCES} PARENT_SCOPE) +add_library(dDatabaseCDClient STATIC ${DDATABASE_CDCLIENTDATABASE_SOURCES}) +target_include_directories(dDatabaseCDClient PUBLIC "." + "CDClientTables" + "${PROJECT_SOURCE_DIR}/dCommon" + "${PROJECT_SOURCE_DIR}/dCommon/dEnums" +) +target_link_libraries(dDatabaseCDClient PRIVATE sqlite3) + +if (${CDCLIENT_CACHE_ALL}) + add_compile_definitions(dDatabaseCDClient PRIVATE CDCLIENT_CACHE_ALL=${CDCLIENT_CACHE_ALL}) +endif() + +file( + GLOB HEADERS_DDATABASE_CDCLIENT + LIST_DIRECTORIES false + ${PROJECT_SOURCE_DIR}/thirdparty/SQLite/*.h + CDClientTables/*.h + *.h +) + +# Need to specify to use the CXX compiler language here or else we get errors including . +target_precompile_headers( + dDatabaseCDClient PRIVATE + "$<$:${HEADERS_DDATABASE_CDCLIENT}>" +) diff --git a/dDatabase/CMakeLists.txt b/dDatabase/CMakeLists.txt index f0fe54b4..004bdc14 100644 --- a/dDatabase/CMakeLists.txt +++ b/dDatabase/CMakeLists.txt @@ -1,20 +1,7 @@ -set(DDATABASE_SOURCES) - add_subdirectory(CDClientDatabase) - -foreach(file ${DDATABASE_CDCLIENTDATABASE_SOURCES}) - set(DDATABASE_SOURCES ${DDATABASE_SOURCES} "CDClientDatabase/${file}") -endforeach() - add_subdirectory(GameDatabase) -foreach(file ${DDATABASE_GAMEDATABASE_SOURCES}) - set(DDATABASE_SOURCES ${DDATABASE_SOURCES} "GameDatabase/${file}") -endforeach() - -add_library(dDatabase STATIC ${DDATABASE_SOURCES}) -target_link_libraries(dDatabase sqlite3 mariadbConnCpp) - -if (${CDCLIENT_CACHE_ALL}) - add_compile_definitions(dDatabase CDCLIENT_CACHE_ALL=${CDCLIENT_CACHE_ALL}) -endif() +add_library(dDatabase STATIC "MigrationRunner.cpp") +target_include_directories(dDatabase PUBLIC ".") +target_link_libraries(dDatabase + PUBLIC dDatabaseCDClient dDatabaseGame) diff --git a/dDatabase/GameDatabase/CMakeLists.txt b/dDatabase/GameDatabase/CMakeLists.txt index c32007bb..09ca7251 100644 --- a/dDatabase/GameDatabase/CMakeLists.txt +++ b/dDatabase/GameDatabase/CMakeLists.txt @@ -1,6 +1,5 @@ set(DDATABASE_GAMEDATABASE_SOURCES "Database.cpp" - "MigrationRunner.cpp" ) add_subdirectory(MySQL) @@ -9,4 +8,25 @@ foreach(file ${DDATABSE_DATABSES_MYSQL_SOURCES}) set(DDATABASE_GAMEDATABASE_SOURCES ${DDATABASE_GAMEDATABASE_SOURCES} "MySQL/${file}") endforeach() -set(DDATABASE_GAMEDATABASE_SOURCES ${DDATABASE_GAMEDATABASE_SOURCES} PARENT_SCOPE) +add_library(dDatabaseGame STATIC ${DDATABASE_GAMEDATABASE_SOURCES}) +target_include_directories(dDatabaseGame PUBLIC "." + "ITables" PRIVATE "MySQL" + "${PROJECT_SOURCE_DIR}/dCommon" + "${PROJECT_SOURCE_DIR}/dCommon/dEnums" +) +target_link_libraries(dDatabaseGame + PUBLIC MariaDB::ConnCpp + INTERFACE dCommon) + +# Glob together all headers that need to be precompiled +file( + GLOB HEADERS_DDATABASE_GAME + LIST_DIRECTORIES false + ITables/*.h +) + +# Need to specify to use the CXX compiler language here or else we get errors including . +target_precompile_headers( + dDatabaseGame PRIVATE + "$<$:${HEADERS_DDATABASE_GAME}>" +) diff --git a/dDatabase/GameDatabase/ITables/IAccounts.h b/dDatabase/GameDatabase/ITables/IAccounts.h index 1b1f85a7..3f27dda6 100644 --- a/dDatabase/GameDatabase/ITables/IAccounts.h +++ b/dDatabase/GameDatabase/ITables/IAccounts.h @@ -3,6 +3,7 @@ #include #include +#include #include enum class eGameMasterLevel : uint8_t; diff --git a/dDatabase/GameDatabase/MigrationRunner.cpp b/dDatabase/MigrationRunner.cpp similarity index 100% rename from dDatabase/GameDatabase/MigrationRunner.cpp rename to dDatabase/MigrationRunner.cpp diff --git a/dDatabase/GameDatabase/MigrationRunner.h b/dDatabase/MigrationRunner.h similarity index 100% rename from dDatabase/GameDatabase/MigrationRunner.h rename to dDatabase/MigrationRunner.h diff --git a/dGame/CMakeLists.txt b/dGame/CMakeLists.txt index 4d9a3e50..26eb859a 100644 --- a/dGame/CMakeLists.txt +++ b/dGame/CMakeLists.txt @@ -2,7 +2,6 @@ set(DGAME_SOURCES "Character.cpp" "Entity.cpp" "EntityManager.cpp" "LeaderboardManager.cpp" - "Player.cpp" "PlayerManager.cpp" "TeamManager.cpp" "TradingManager.cpp" @@ -14,11 +13,25 @@ include_directories( ${PROJECT_SOURCE_DIR}/dGame ) -add_library(dGameBase ${DGAME_SOURCES}) +add_library(dGameBase OBJECT ${DGAME_SOURCES}) target_precompile_headers(dGameBase PRIVATE ${HEADERS_DGAME}) -target_link_libraries(dGameBase - PUBLIC dDatabase dPhysics - INTERFACE dComponents dEntity) +target_include_directories(dGameBase PUBLIC "." "dEntity" + PRIVATE "dComponents" "dGameMessages" "dBehaviors" "dMission" "dUtilities" "dInventory" + $ + "${PROJECT_SOURCE_DIR}/dCommon" + "${PROJECT_SOURCE_DIR}/dCommon/dEnums" + "${PROJECT_SOURCE_DIR}/dCommon/dClient" + # dDatabase + "${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase" + "${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase/CDClientTables" + "${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase" + "${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase/ITables" + "${PROJECT_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/include" + # dPhysics + "${PROJECT_SOURCE_DIR}/thirdparty/recastnavigation/Recast/Include" + "${PROJECT_SOURCE_DIR}/thirdparty/recastnavigation/Detour/Include" + "${PROJECT_SOURCE_DIR}/dZoneManager" +) add_subdirectory(dBehaviors) add_subdirectory(dComponents) @@ -29,7 +42,26 @@ add_subdirectory(dMission) add_subdirectory(dPropertyBehaviors) add_subdirectory(dUtilities) -add_library(dGame INTERFACE) -target_link_libraries(dGame INTERFACE - dGameBase dBehaviors dComponents dEntity dGameMessages dInventory dMission dPropertyBehaviors dUtilities dScripts +add_library(dGame STATIC + $ + $ + $ + $ + $ + $ + $ + $ + $ +) +target_link_libraries(dGame INTERFACE dNet) +target_include_directories(dGame INTERFACE + $ + $ + $ + $ + $ + $ + $ + $ + $ ) diff --git a/dGame/Character.cpp b/dGame/Character.cpp index ee04710a..eab7583f 100644 --- a/dGame/Character.cpp +++ b/dGame/Character.cpp @@ -451,7 +451,7 @@ void Character::LoadXmlRespawnCheckpoints() { auto* r = points->FirstChildElement("r"); while (r != nullptr) { int32_t map = 0; - NiPoint3 point = NiPoint3::ZERO; + NiPoint3 point = NiPoint3Constant::ZERO; r->QueryAttribute("w", &map); r->QueryAttribute("x", &point.x); @@ -513,7 +513,7 @@ void Character::SetRespawnPoint(LWOMAPID map, const NiPoint3& point) { const NiPoint3& Character::GetRespawnPoint(LWOMAPID map) const { const auto& pair = m_WorldRespawnCheckpoints.find(map); - if (pair == m_WorldRespawnCheckpoints.end()) return NiPoint3::ZERO; + if (pair == m_WorldRespawnCheckpoints.end()) return NiPoint3Constant::ZERO; return pair->second; } diff --git a/dGame/Character.h b/dGame/Character.h index 6c8ead30..b994fb61 100644 --- a/dGame/Character.h +++ b/dGame/Character.h @@ -457,6 +457,8 @@ public: void SetBillboardVisible(bool visible); + User* GetParentUser() const { return m_ParentUser; } + private: void UpdateInfoFromDatabase(); /** diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 3c76a97c..109edfc8 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -15,7 +15,6 @@ #include "Spawner.h" #include "UserManager.h" #include "dpWorld.h" -#include "Player.h" #include "LUTriggers.h" #include "User.h" #include "EntityTimer.h" @@ -26,6 +25,7 @@ #include "eObjectBits.h" #include "PositionUpdate.h" #include "eChatMessageType.h" +#include "PlayerManager.h" //Component includes: #include "Component.h" @@ -82,6 +82,7 @@ #include "CollectibleComponent.h" #include "ItemComponent.h" #include "GhostComponent.h" +#include "AchievementVendorComponent.h" // Table includes #include "CDComponentsRegistryTable.h" @@ -95,7 +96,7 @@ #include "CDSkillBehaviorTable.h" #include "CDZoneTableTable.h" -Entity::Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity) { +Entity::Entity(const LWOOBJID& objectID, EntityInfo info, User* parentUser, Entity* parentEntity) { m_ObjectID = objectID; m_TemplateID = info.lot; m_ParentEntity = parentEntity; @@ -124,9 +125,40 @@ Entity::Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity) m_SpawnerNodeID = info.spawnerNodeID; if (info.lot != 1) m_PlayerIsReadyForUpdates = true; + if (parentUser) { + m_Character = parentUser->GetLastUsedChar(); + parentUser->SetLoggedInChar(objectID); + m_GMLevel = m_Character->GetGMLevel(); + + m_Character->SetEntity(this); + + PlayerManager::AddPlayer(this); + } } Entity::~Entity() { + if (IsPlayer()) { + LOG("Deleted player"); + + // Make sure the player exists first. Remove afterwards to prevent the OnPlayerExist functions from not being able to find the player. + if (!PlayerManager::RemovePlayer(this)) { + LOG("Unable to find player to remove from manager."); + return; + } + + auto* zoneControl = Game::entityManager->GetZoneControlEntity(); + if (zoneControl) { + zoneControl->GetScript()->OnPlayerExit(zoneControl, this); + } + + std::vector scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); + for (Entity* scriptEntity : scriptedActs) { + if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds + scriptEntity->GetScript()->OnPlayerExit(scriptEntity, this); + } + } + } + if (m_Character) { m_Character->SaveXMLToDatabase(); } @@ -182,7 +214,7 @@ void Entity::Initialize() { } // Get the registry table - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); /** * Special case for BBB models. They have components not corresponding to the registry. @@ -212,7 +244,7 @@ void Entity::Initialize() { * Not all components are implemented. Some are represented by a nullptr, as they hold no data. */ - if (GetParentUser()) { + if (m_Character && m_Character->GetParentUser()) { AddComponent()->LoadFromXml(m_Character->GetXMLDoc()); } @@ -336,7 +368,7 @@ void Entity::Initialize() { if (quickBuildComponentID > 0) componentID = quickBuildComponentID; if (buffComponentID > 0) componentID = buffComponentID; - CDDestructibleComponentTable* destCompTable = CDClientManager::Instance().GetTable(); + CDDestructibleComponentTable* destCompTable = CDClientManager::GetTable(); std::vector destCompData = destCompTable->Query([=](CDDestructibleComponent entry) { return (entry.id == componentID); }); bool isSmashable = GetVarAs(u"is_smashable") != 0; @@ -371,7 +403,7 @@ void Entity::Initialize() { uint32_t npcMinLevel = destCompData[0].level; uint32_t currencyIndex = destCompData[0].CurrencyIndex; - CDCurrencyTableTable* currencyTable = CDClientManager::Instance().GetTable(); + CDCurrencyTableTable* currencyTable = CDClientManager::GetTable(); std::vector currencyValues = currencyTable->Query([=](CDCurrencyTable entry) { return (entry.currencyIndex == currencyIndex && entry.npcminlevel == npcMinLevel); }); if (currencyValues.size() > 0) { @@ -419,10 +451,10 @@ void Entity::Initialize() { if (!setFaction.empty()) { // TODO also split on space here however we do not have a general util for splitting on multiple characters yet. std::vector factionsToAdd = GeneralUtils::SplitString(setFaction, ';'); - int32_t factionToAdd; for (const auto faction : factionsToAdd) { - if (GeneralUtils::TryParse(faction, factionToAdd)) { - comp->AddFaction(factionToAdd, true); + const auto factionToAdd = GeneralUtils::TryParse(faction); + if (factionToAdd) { + comp->AddFaction(factionToAdd.value(), true); } } } @@ -437,7 +469,8 @@ void Entity::Initialize() { AddComponent(); - AddComponent(m_Character)->LoadFromXml(m_Character->GetXMLDoc()); + auto& systemAddress = m_Character->GetParentUser() ? m_Character->GetParentUser()->GetSystemAddress() : UNASSIGNED_SYSTEM_ADDRESS; + AddComponent(m_Character, systemAddress)->LoadFromXml(m_Character->GetXMLDoc()); AddComponent(); } @@ -455,7 +488,7 @@ void Entity::Initialize() { * This is a bit of a mess */ - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable(); + CDScriptComponentTable* scriptCompTable = CDClientManager::GetTable(); int32_t scriptComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::SCRIPT, -1); std::string scriptName = ""; @@ -504,7 +537,7 @@ void Entity::Initialize() { // ZoneControl script if (m_TemplateID == 2365) { - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); const auto zoneID = Game::zoneManager->GetZoneID(); const CDZoneTable* zoneData = zoneTable->Query(zoneID.GetMapID()); @@ -527,7 +560,7 @@ void Entity::Initialize() { if (int componentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::QUICK_BUILD) > 0) { auto* quickBuildComponent = AddComponent(); - CDRebuildComponentTable* rebCompTable = CDClientManager::Instance().GetTable(); + CDRebuildComponentTable* rebCompTable = CDClientManager::GetTable(); std::vector rebCompData = rebCompTable->Query([=](CDRebuildComponent entry) { return (entry.id == quickBuildComponentID); }); if (rebCompData.size() > 0) { @@ -581,6 +614,8 @@ void Entity::Initialize() { AddComponent(); } else if ((compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::DONATION_VENDOR, -1) != -1)) { AddComponent(); + } else if ((compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::ACHIEVEMENT_VENDOR, -1) != -1)) { + AddComponent(); } if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROPERTY_VENDOR, -1) != -1) { @@ -651,7 +686,7 @@ void Entity::Initialize() { int movementAIID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::MOVEMENT_AI); if (movementAIID > 0) { - CDMovementAIComponentTable* moveAITable = CDClientManager::Instance().GetTable(); + CDMovementAIComponentTable* moveAITable = CDClientManager::GetTable(); std::vector moveAIComp = moveAITable->Query([=](CDMovementAIComponent entry) {return (entry.id == movementAIID); }); if (moveAIComp.size() > 0) { @@ -715,7 +750,7 @@ void Entity::Initialize() { int proximityMonitorID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROXIMITY_MONITOR); if (proximityMonitorID > 0) { - CDProximityMonitorComponentTable* proxCompTable = CDClientManager::Instance().GetTable(); + CDProximityMonitorComponentTable* proxCompTable = CDClientManager::GetTable(); std::vector proxCompData = proxCompTable->Query([=](CDProximityMonitorComponent entry) { return (entry.id == proximityMonitorID); }); if (proxCompData.size() > 0) { std::vector proximityStr = GeneralUtils::SplitString(proxCompData[0].Proximities, ','); @@ -725,9 +760,7 @@ void Entity::Initialize() { // Hacky way to trigger these when the object has had a chance to get constructed AddCallbackTimer(0, [this]() { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnStartup(this); - } + this->GetScript()->OnStartup(this); }); if (!m_Character && Game::entityManager->GetGhostingEnabled()) { @@ -788,14 +821,6 @@ bool Entity::operator!=(const Entity& other) const { return other.m_ObjectID != m_ObjectID; } -User* Entity::GetParentUser() const { - if (!IsPlayer()) { - return nullptr; - } - - return static_cast(this)->GetParentUser(); -} - Component* Entity::GetComponent(eReplicaComponentType componentID) const { const auto& index = m_Components.find(componentID); @@ -810,17 +835,6 @@ bool Entity::HasComponent(const eReplicaComponentType componentId) const { return m_Components.find(componentId) != m_Components.end(); } -std::vector Entity::GetScriptComponents() { - std::vector comps; - for (std::pair p : m_Components) { - if (p.first == eReplicaComponentType::SCRIPT) { - comps.push_back(static_cast(p.second)); - } - } - - return comps; -} - void Entity::Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName) { if (notificationName == "HitOrHealResult" || notificationName == "Hit") { auto* destroyableComponent = GetComponent(); @@ -850,17 +864,12 @@ void Entity::SetProximityRadius(dpEntity* entity, std::string name) { void Entity::SetGMLevel(eGameMasterLevel value) { m_GMLevel = value; - if (GetParentUser()) { - Character* character = GetParentUser()->GetLastUsedChar(); + if (m_Character) m_Character->SetGMLevel(value); - if (character) { - character->SetGMLevel(value); - } - } + auto* characterComponent = GetComponent(); + if (!characterComponent) return; - CharacterComponent* character = GetComponent(); - if (!character) return; - character->SetGMLevel(value); + characterComponent->SetGMLevel(value); GameMessages::SendGMLevelBroadcast(m_ObjectID, value); @@ -875,34 +884,34 @@ void Entity::SetGMLevel(eGameMasterLevel value) { } } -void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacketType packetType) { +void Entity::WriteBaseReplicaData(RakNet::BitStream& outBitStream, eReplicaPacketType packetType) { if (packetType == eReplicaPacketType::CONSTRUCTION) { - outBitStream->Write(m_ObjectID); - outBitStream->Write(m_TemplateID); + outBitStream.Write(m_ObjectID); + outBitStream.Write(m_TemplateID); if (IsPlayer()) { std::string name = m_Character != nullptr ? m_Character->GetName() : "Invalid"; - outBitStream->Write(uint8_t(name.size())); + outBitStream.Write(uint8_t(name.size())); for (size_t i = 0; i < name.size(); ++i) { - outBitStream->Write(name[i]); + outBitStream.Write(name[i]); } } else { const auto& name = GetVar(u"npcName"); - outBitStream->Write(uint8_t(name.size())); + outBitStream.Write(uint8_t(name.size())); for (size_t i = 0; i < name.size(); ++i) { - outBitStream->Write(name[i]); + outBitStream.Write(name[i]); } } - outBitStream->Write(0); //Time since created on server + outBitStream.Write(0); //Time since created on server const auto& syncLDF = GetVar>(u"syncLDF"); // Only sync for models. if (m_Settings.size() > 0 && (GetComponent() && !GetComponent())) { - outBitStream->Write1(); //ldf data + outBitStream.Write1(); //ldf data RakNet::BitStream settingStream; int32_t numberOfValidKeys = m_Settings.size(); @@ -919,13 +928,13 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke for (LDFBaseData* data : m_Settings) { if (data && data->GetValueType() != eLDFType::LDF_TYPE_UNKNOWN) { - data->WriteToPacket(&settingStream); + data->WriteToPacket(settingStream); } } - outBitStream->Write(settingStream.GetNumberOfBytesUsed() + 1); - outBitStream->Write(0); //no compression used - outBitStream->Write(settingStream); + outBitStream.Write(settingStream.GetNumberOfBytesUsed() + 1); + outBitStream.Write(0); //no compression used + outBitStream.Write(settingStream); } else if (!syncLDF.empty()) { std::vector ldfData; @@ -933,79 +942,79 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke ldfData.push_back(GetVarData(data)); } - outBitStream->Write1(); //ldf data + outBitStream.Write1(); //ldf data RakNet::BitStream settingStream; settingStream.Write(ldfData.size()); for (LDFBaseData* data : ldfData) { if (data) { - data->WriteToPacket(&settingStream); + data->WriteToPacket(settingStream); } } - outBitStream->Write(settingStream.GetNumberOfBytesUsed() + 1); - outBitStream->Write(0); //no compression used - outBitStream->Write(settingStream); + outBitStream.Write(settingStream.GetNumberOfBytesUsed() + 1); + outBitStream.Write(0); //no compression used + outBitStream.Write(settingStream); } else { - outBitStream->Write0(); //No ldf data + outBitStream.Write0(); //No ldf data } TriggerComponent* triggerComponent; if (TryGetComponent(eReplicaComponentType::TRIGGER, triggerComponent)) { // has trigger component, check to see if we have events to handle auto* trigger = triggerComponent->GetTrigger(); - outBitStream->Write(trigger && trigger->events.size() > 0); + outBitStream.Write(trigger && trigger->events.size() > 0); } else { // no trigger componenet, so definitely no triggers - outBitStream->Write0(); + outBitStream.Write0(); } if (m_ParentEntity != nullptr || m_SpawnerID != 0) { - outBitStream->Write1(); - if (m_ParentEntity != nullptr) outBitStream->Write(GeneralUtils::SetBit(m_ParentEntity->GetObjectID(), static_cast(eObjectBits::CLIENT))); - else if (m_Spawner != nullptr && m_Spawner->m_Info.isNetwork) outBitStream->Write(m_SpawnerID); - else outBitStream->Write(GeneralUtils::SetBit(m_SpawnerID, static_cast(eObjectBits::CLIENT))); - } else outBitStream->Write0(); + outBitStream.Write1(); + if (m_ParentEntity != nullptr) outBitStream.Write(GeneralUtils::SetBit(m_ParentEntity->GetObjectID(), static_cast(eObjectBits::CLIENT))); + else if (m_Spawner != nullptr && m_Spawner->m_Info.isNetwork) outBitStream.Write(m_SpawnerID); + else outBitStream.Write(GeneralUtils::SetBit(m_SpawnerID, static_cast(eObjectBits::CLIENT))); + } else outBitStream.Write0(); - outBitStream->Write(m_HasSpawnerNodeID); - if (m_HasSpawnerNodeID) outBitStream->Write(m_SpawnerNodeID); + outBitStream.Write(m_HasSpawnerNodeID); + if (m_HasSpawnerNodeID) outBitStream.Write(m_SpawnerNodeID); - //outBitStream->Write0(); //Spawner node id + //outBitStream.Write0(); //Spawner node id - if (m_Scale == 1.0f || m_Scale == 0.0f) outBitStream->Write0(); + if (m_Scale == 1.0f || m_Scale == 0.0f) outBitStream.Write0(); else { - outBitStream->Write1(); - outBitStream->Write(m_Scale); + outBitStream.Write1(); + outBitStream.Write(m_Scale); } - outBitStream->Write0(); //ObjectWorldState + outBitStream.Write0(); //ObjectWorldState if (m_GMLevel != eGameMasterLevel::CIVILIAN) { - outBitStream->Write1(); - outBitStream->Write(m_GMLevel); - } else outBitStream->Write0(); //No GM Level + outBitStream.Write1(); + outBitStream.Write(m_GMLevel); + } else outBitStream.Write0(); //No GM Level } // Only serialize parent / child info should the info be dirty (changed) or if this is the construction of the entity. - outBitStream->Write(m_IsParentChildDirty || packetType == eReplicaPacketType::CONSTRUCTION); + outBitStream.Write(m_IsParentChildDirty || packetType == eReplicaPacketType::CONSTRUCTION); if (m_IsParentChildDirty || packetType == eReplicaPacketType::CONSTRUCTION) { m_IsParentChildDirty = false; - outBitStream->Write(m_ParentEntity != nullptr); + outBitStream.Write(m_ParentEntity != nullptr); if (m_ParentEntity) { - outBitStream->Write(m_ParentEntity->GetObjectID()); - outBitStream->Write0(); + outBitStream.Write(m_ParentEntity->GetObjectID()); + outBitStream.Write0(); } - outBitStream->Write(m_ChildEntities.size() > 0); + outBitStream.Write(m_ChildEntities.size() > 0); if (m_ChildEntities.size() > 0) { - outBitStream->Write(m_ChildEntities.size()); + outBitStream.Write(m_ChildEntities.size()); for (Entity* child : m_ChildEntities) { - outBitStream->Write(child->GetObjectID()); + outBitStream.Write(child->GetObjectID()); } } } } -void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType packetType) { +void Entity::WriteComponents(RakNet::BitStream& outBitStream, eReplicaPacketType packetType) { /** * This has to be done in a specific order. @@ -1093,7 +1102,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType possessorComponent->Serialize(outBitStream, bIsInitialUpdate); } else { // Should never happen, but just to be safe - outBitStream->Write0(); + outBitStream.Write0(); } LevelProgressionComponent* levelProgressionComponent; @@ -1101,7 +1110,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType levelProgressionComponent->Serialize(outBitStream, bIsInitialUpdate); } else { // Should never happen, but just to be safe - outBitStream->Write0(); + outBitStream.Write0(); } PlayerForcedMovementComponent* playerForcedMovementComponent; @@ -1109,7 +1118,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType playerForcedMovementComponent->Serialize(outBitStream, bIsInitialUpdate); } else { // Should never happen, but just to be safe - outBitStream->Write0(); + outBitStream.Write0(); } characterComponent->Serialize(outBitStream, bIsInitialUpdate); @@ -1170,6 +1179,11 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType donationVendorComponent->Serialize(outBitStream, bIsInitialUpdate); } + AchievementVendorComponent* achievementVendorComponent; + if (TryGetComponent(eReplicaComponentType::ACHIEVEMENT_VENDOR, achievementVendorComponent)) { + achievementVendorComponent->Serialize(outBitStream, bIsInitialUpdate); + } + BouncerComponent* bouncerComponent; if (TryGetComponent(eReplicaComponentType::BOUNCER, bouncerComponent)) { bouncerComponent->Serialize(outBitStream, bIsInitialUpdate); @@ -1221,7 +1235,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType // BBB Component, unused currently // Need to to write0 so that is serialized correctly // TODO: Implement BBB Component - outBitStream->Write0(); + outBitStream.Write0(); } void Entity::UpdateXMLDoc(tinyxml2::XMLDocument* doc) { @@ -1249,9 +1263,7 @@ void Entity::Update(const float deltaTime) { // Remove the timer from the list of timers first so that scripts and events can remove timers without causing iterator invalidation auto timerName = timer.GetName(); m_Timers.erase(m_Timers.begin() + timerPosition); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnTimerDone(this, timerName); - } + GetScript()->OnTimerDone(this, timerName); TriggerEvent(eTriggerEventType::TIMER_DONE, this); } else { @@ -1297,9 +1309,7 @@ void Entity::Update(const float deltaTime) { Wake(); } - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnUpdate(this); - } + GetScript()->OnUpdate(this); for (const auto& pair : m_Components) { if (pair.second == nullptr) continue; @@ -1316,9 +1326,7 @@ void Entity::OnCollisionProximity(LWOOBJID otherEntity, const std::string& proxN Entity* other = Game::entityManager->GetEntity(otherEntity); if (!other) return; - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnProximityUpdate(this, other, proxName, status); - } + GetScript()->OnProximityUpdate(this, other, proxName, status); RocketLaunchpadControlComponent* rocketComp = GetComponent(); if (!rocketComp) return; @@ -1330,9 +1338,7 @@ void Entity::OnCollisionPhantom(const LWOOBJID otherEntity) { auto* other = Game::entityManager->GetEntity(otherEntity); if (!other) return; - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnCollisionPhantom(this, other); - } + GetScript()->OnCollisionPhantom(this, other); for (const auto& callback : m_PhantomCollisionCallbacks) { callback(other); @@ -1357,17 +1363,11 @@ void Entity::OnCollisionPhantom(const LWOOBJID otherEntity) { } if (!other->GetIsDead()) { - auto* combat = GetComponent(); - - if (combat != nullptr) { + if (GetComponent() != nullptr) { const auto index = std::find(m_TargetsInPhantom.begin(), m_TargetsInPhantom.end(), otherEntity); if (index != m_TargetsInPhantom.end()) return; - const auto valid = combat->IsEnemy(otherEntity); - - if (!valid) return; - m_TargetsInPhantom.push_back(otherEntity); } } @@ -1377,9 +1377,7 @@ void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) { auto* other = Game::entityManager->GetEntity(otherEntity); if (!other) return; - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnOffCollisionPhantom(this, other); - } + GetScript()->OnOffCollisionPhantom(this, other); TriggerEvent(eTriggerEventType::EXIT, other); @@ -1396,46 +1394,32 @@ void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) { } void Entity::OnFireEventServerSide(Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnFireEventServerSide(this, sender, args, param1, param2, param3); - } + GetScript()->OnFireEventServerSide(this, sender, args, param1, param2, param3); } void Entity::OnActivityStateChangeRequest(LWOOBJID senderID, int32_t value1, int32_t value2, const std::u16string& stringValue) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnActivityStateChangeRequest(this, senderID, value1, value2, stringValue); - } + GetScript()->OnActivityStateChangeRequest(this, senderID, value1, value2, stringValue); } void Entity::OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName, float_t pathTime, float_t totalTime, int32_t waypoint) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnCinematicUpdate(self, sender, event, pathName, pathTime, totalTime, waypoint); - } + GetScript()->OnCinematicUpdate(self, sender, event, pathName, pathTime, totalTime, waypoint); } void Entity::NotifyObject(Entity* sender, const std::string& name, int32_t param1, int32_t param2) { GameMessages::SendNotifyObject(GetObjectID(), sender->GetObjectID(), GeneralUtils::ASCIIToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnNotifyObject(this, sender, name, param1, param2); - } + GetScript()->OnNotifyObject(this, sender, name, param1, param2); } void Entity::OnEmoteReceived(const int32_t emote, Entity* target) { - for (auto* script : CppScripts::GetEntityScripts(this)) { - script->OnEmoteReceived(this, emote, target); - } + GetScript()->OnEmoteReceived(this, emote, target); } void Entity::OnUse(Entity* originator) { TriggerEvent(eTriggerEventType::INTERACT, originator); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnUse(this, originator); - } - - // component base class when + GetScript()->OnUse(this, originator); for (const auto& pair : m_Components) { if (pair.second == nullptr) continue; @@ -1445,82 +1429,63 @@ void Entity::OnUse(Entity* originator) { } void Entity::OnHitOrHealResult(Entity* attacker, int32_t damage) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnHitOrHealResult(this, attacker, damage); - } + GetScript()->OnHitOrHealResult(this, attacker, damage); } void Entity::OnHit(Entity* attacker) { TriggerEvent(eTriggerEventType::HIT, attacker); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnHit(this, attacker); - } + GetScript()->OnHit(this, attacker); } void Entity::OnZonePropertyEditBegin() { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnZonePropertyEditBegin(this); - } + GetScript()->OnZonePropertyEditBegin(this); } void Entity::OnZonePropertyEditEnd() { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnZonePropertyEditEnd(this); - } + GetScript()->OnZonePropertyEditEnd(this); } void Entity::OnZonePropertyModelEquipped() { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnZonePropertyModelEquipped(this); - } + GetScript()->OnZonePropertyModelEquipped(this); } void Entity::OnZonePropertyModelPlaced(Entity* player) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnZonePropertyModelPlaced(this, player); - } + GetScript()->OnZonePropertyModelPlaced(this, player); } void Entity::OnZonePropertyModelPickedUp(Entity* player) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnZonePropertyModelPickedUp(this, player); - } + GetScript()->OnZonePropertyModelPickedUp(this, player); } void Entity::OnZonePropertyModelRemoved(Entity* player) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnZonePropertyModelRemoved(this, player); - } + GetScript()->OnZonePropertyModelRemoved(this, player); } void Entity::OnZonePropertyModelRemovedWhileEquipped(Entity* player) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnZonePropertyModelRemovedWhileEquipped(this, player); - } + GetScript()->OnZonePropertyModelRemovedWhileEquipped(this, player); } void Entity::OnZonePropertyModelRotated(Entity* player) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnZonePropertyModelRotated(this, player); - } + GetScript()->OnZonePropertyModelRotated(this, player); } void Entity::OnMessageBoxResponse(Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnMessageBoxResponse(this, sender, button, identifier, userData); - } + GetScript()->OnMessageBoxResponse(this, sender, button, identifier, userData); } void Entity::OnChoiceBoxResponse(Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnChoiceBoxResponse(this, sender, button, buttonIdentifier, identifier); - } + GetScript()->OnChoiceBoxResponse(this, sender, button, buttonIdentifier, identifier); } void Entity::RequestActivityExit(Entity* sender, LWOOBJID player, bool canceled) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnRequestActivityExit(sender, player, canceled); - } + GetScript()->OnRequestActivityExit(sender, player, canceled); +} + +CppScripts::Script* const Entity::GetScript() { + auto* scriptComponent = GetComponent(); + auto* script = scriptComponent ? scriptComponent->GetScript() : CppScripts::GetInvalidScript(); + DluAssert(script != nullptr); + return script; } void Entity::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType) { @@ -1553,9 +1518,7 @@ void Entity::Kill(Entity* murderer, const eKillType killType) { //OMAI WA MOU, SHINDERIU - for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { - script->OnDie(this, murderer); - } + GetScript()->OnDie(this, murderer); if (m_Spawner != nullptr) { m_Spawner->NotifyOfEntityDeath(m_ObjectID); @@ -1636,18 +1599,23 @@ bool Entity::GetIsDead() const { void Entity::AddLootItem(const Loot::Info& info) { if (!IsPlayer()) return; - auto& droppedLoot = static_cast(this)->GetDroppedLoot(); + + auto* characterComponent = GetComponent(); + if (!characterComponent) return; + + auto& droppedLoot = characterComponent->GetDroppedLoot(); droppedLoot.insert(std::make_pair(info.id, info)); } void Entity::PickupItem(const LWOOBJID& objectID) { if (!IsPlayer()) return; InventoryComponent* inv = GetComponent(); - if (!inv) return; + auto* characterComponent = GetComponent(); + if (!inv || !characterComponent) return; - CDObjectsTable* objectsTable = CDClientManager::Instance().GetTable(); + CDObjectsTable* objectsTable = CDClientManager::GetTable(); - auto& droppedLoot = static_cast(this)->GetDroppedLoot(); + auto& droppedLoot = characterComponent->GetDroppedLoot(); for (const auto& p : droppedLoot) { if (p.first == objectID) { @@ -1658,13 +1626,13 @@ void Entity::PickupItem(const LWOOBJID& objectID) { const CDObjects& object = objectsTable->GetByID(p.second.lot); if (object.id != 0 && object.type == "Powerup") { - CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable(); + CDObjectSkillsTable* skillsTable = CDClientManager::GetTable(); std::vector skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == p.second.lot); }); for (CDObjectSkills skill : skills) { - CDSkillBehaviorTable* skillBehTable = CDClientManager::Instance().GetTable(); - CDSkillBehavior behaviorData = skillBehTable->GetSkillByID(skill.skillID); + CDSkillBehaviorTable* skillBehTable = CDClientManager::GetTable(); - SkillComponent::HandleUnmanaged(behaviorData.behaviorID, GetObjectID()); + auto* skillComponent = GetComponent(); + if (skillComponent) skillComponent->CastSkill(skill.skillID, GetObjectID(), GetObjectID()); auto* missionComponent = GetComponent(); @@ -1683,22 +1651,28 @@ void Entity::PickupItem(const LWOOBJID& objectID) { bool Entity::CanPickupCoins(uint64_t count) { if (!IsPlayer()) return false; - auto* player = static_cast(this); - auto droppedCoins = player->GetDroppedCoins(); + + auto* characterComponent = GetComponent(); + if (!characterComponent) return false; + + auto droppedCoins = characterComponent->GetDroppedCoins(); if (count > droppedCoins) { return false; } else { - player->SetDroppedCoins(droppedCoins - count); + characterComponent->SetDroppedCoins(droppedCoins - count); return true; } } void Entity::RegisterCoinDrop(uint64_t count) { if (!IsPlayer()) return; - auto* player = static_cast(this); - auto droppedCoins = player->GetDroppedCoins(); + + auto* characterComponent = GetComponent(); + if (!characterComponent) return; + + auto droppedCoins = characterComponent->GetDroppedCoins(); droppedCoins += count; - player->SetDroppedCoins(droppedCoins); + characterComponent->SetDroppedCoins(droppedCoins); } void Entity::AddChild(Entity* child) { @@ -1863,7 +1837,7 @@ const NiPoint3& Entity::GetPosition() const { return vehicel->GetPosition(); } - return NiPoint3::ZERO; + return NiPoint3Constant::ZERO; } const NiQuaternion& Entity::GetRotation() const { @@ -1891,7 +1865,7 @@ const NiQuaternion& Entity::GetRotation() const { return vehicel->GetRotation(); } - return NiQuaternion::IDENTITY; + return NiQuaternionConstant::IDENTITY; } void Entity::SetPosition(const NiPoint3& position) { @@ -1992,25 +1966,21 @@ void Entity::SetNetworkId(const uint16_t id) { m_NetworkID = id; } -std::vector& Entity::GetTargetsInPhantom() { - std::vector valid; - +std::vector Entity::GetTargetsInPhantom() { // Clean up invalid targets, like disconnected players - for (auto i = 0u; i < m_TargetsInPhantom.size(); ++i) { - const auto id = m_TargetsInPhantom.at(i); + m_TargetsInPhantom.erase(std::remove_if(m_TargetsInPhantom.begin(), m_TargetsInPhantom.end(), [](const LWOOBJID id) { + return !Game::entityManager->GetEntity(id); + }), m_TargetsInPhantom.end()); - auto* entity = Game::entityManager->GetEntity(id); + std::vector enemies; + for (const auto id : m_TargetsInPhantom) { + auto* combat = GetComponent(); + if (!combat || !combat->IsEnemy(id)) continue; - if (entity == nullptr) { - continue; - } - - valid.push_back(id); + enemies.push_back(id); } - m_TargetsInPhantom = valid; - - return m_TargetsInPhantom; + return enemies; } void Entity::SendNetworkVar(const std::string& data, const SystemAddress& sysAddr) { @@ -2096,9 +2066,7 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) { havokVehiclePhysicsComponent->SetIsOnGround(update.onGround); havokVehiclePhysicsComponent->SetIsOnRail(update.onRail); havokVehiclePhysicsComponent->SetVelocity(update.velocity); - havokVehiclePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3::ZERO); havokVehiclePhysicsComponent->SetAngularVelocity(update.angularVelocity); - havokVehiclePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3::ZERO); havokVehiclePhysicsComponent->SetRemoteInputInfo(update.remoteInputInfo); } else { // Need to get the mount's controllable physics @@ -2109,17 +2077,15 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) { possessedControllablePhysicsComponent->SetIsOnGround(update.onGround); possessedControllablePhysicsComponent->SetIsOnRail(update.onRail); possessedControllablePhysicsComponent->SetVelocity(update.velocity); - possessedControllablePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3::ZERO); possessedControllablePhysicsComponent->SetAngularVelocity(update.angularVelocity); - possessedControllablePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3::ZERO); } Game::entityManager->SerializeEntity(possassableEntity); } } if (!updateChar) { - update.velocity = NiPoint3::ZERO; - update.angularVelocity = NiPoint3::ZERO; + update.velocity = NiPoint3Constant::ZERO; + update.angularVelocity = NiPoint3Constant::ZERO; } // Handle statistics @@ -2133,9 +2099,7 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) { controllablePhysicsComponent->SetIsOnGround(update.onGround); controllablePhysicsComponent->SetIsOnRail(update.onRail); controllablePhysicsComponent->SetVelocity(update.velocity); - controllablePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3::ZERO); controllablePhysicsComponent->SetAngularVelocity(update.angularVelocity); - controllablePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3::ZERO); auto* ghostComponent = GetComponent(); if (ghostComponent) ghostComponent->SetGhostReferencePoint(update.position); @@ -2143,3 +2107,27 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) { if (updateChar) Game::entityManager->SerializeEntity(this); } + +const SystemAddress& Entity::GetSystemAddress() const { + auto* characterComponent = GetComponent(); + return characterComponent ? characterComponent->GetSystemAddress() : UNASSIGNED_SYSTEM_ADDRESS; +} + +const NiPoint3& Entity::GetRespawnPosition() const { + auto* characterComponent = GetComponent(); + return characterComponent ? characterComponent->GetRespawnPosition() : NiPoint3Constant::ZERO; +} + +const NiQuaternion& Entity::GetRespawnRotation() const { + auto* characterComponent = GetComponent(); + return characterComponent ? characterComponent->GetRespawnRotation() : NiQuaternionConstant::IDENTITY; +} + +void Entity::SetRespawnPos(const NiPoint3& position) { + auto* characterComponent = GetComponent(); + if (characterComponent) characterComponent->SetRespawnPos(position); +} +void Entity::SetRespawnRot(const NiQuaternion& rotation) { + auto* characterComponent = GetComponent(); + if (characterComponent) characterComponent->SetRespawnRot(rotation); +} diff --git a/dGame/Entity.h b/dGame/Entity.h index 36621d5c..740d7c92 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -47,10 +47,10 @@ namespace CppScripts { */ class Entity { public: - explicit Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity = nullptr); - virtual ~Entity(); + explicit Entity(const LWOOBJID& objectID, EntityInfo info, User* parentUser = nullptr, Entity* parentEntity = nullptr); + ~Entity(); - virtual void Initialize(); + void Initialize(); bool operator==(const Entity& other) const; bool operator!=(const Entity& other) const; @@ -104,9 +104,7 @@ public: const NiQuaternion& GetRotation() const; - virtual User* GetParentUser() const; - - virtual const SystemAddress& GetSystemAddress() const { return UNASSIGNED_SYSTEM_ADDRESS; }; + const SystemAddress& GetSystemAddress() const; /** * Setters @@ -128,11 +126,9 @@ public: void SetRotation(const NiQuaternion& rotation); - virtual void SetRespawnPos(const NiPoint3& position) {} + void SetRespawnPos(const NiPoint3& position); - virtual void SetRespawnRot(const NiQuaternion& rotation) {} - - virtual void SetSystemAddress(const SystemAddress& value) {}; + void SetRespawnRot(const NiQuaternion& rotation); /** * Component management @@ -150,7 +146,8 @@ public: void AddComponent(eReplicaComponentType componentId, Component* component); - std::vector GetScriptComponents(); + // This is expceted to never return nullptr, an assert checks this. + CppScripts::Script* const GetScript(); void Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName); void Unsubscribe(LWOOBJID scriptObjId, const std::string& notificationName); @@ -175,8 +172,8 @@ public: std::unordered_map& GetComponents() { return m_Components; } // TODO: Remove - void WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacketType packetType); - void WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType packetType); + void WriteBaseReplicaData(RakNet::BitStream& outBitStream, eReplicaPacketType packetType); + void WriteComponents(RakNet::BitStream& outBitStream, eReplicaPacketType packetType); void UpdateXMLDoc(tinyxml2::XMLDocument* doc); void Update(float deltaTime); @@ -229,8 +226,8 @@ public: void TriggerEvent(eTriggerEventType event, Entity* optionalTarget = nullptr); void ScheduleDestructionAfterUpdate() { m_ShouldDestroyAfterUpdate = true; } - virtual const NiPoint3& GetRespawnPosition() const { return NiPoint3::ZERO; } - virtual const NiQuaternion& GetRespawnRotation() const { return NiQuaternion::IDENTITY; } + const NiPoint3& GetRespawnPosition() const; + const NiQuaternion& GetRespawnRotation() const; void Sleep(); void Wake(); @@ -293,12 +290,15 @@ public: /* * Collision */ - std::vector& GetTargetsInPhantom(); + std::vector GetTargetsInPhantom(); Entity* GetScheduledKiller() { return m_ScheduleKiller; } void ProcessPositionUpdate(PositionUpdate& update); + // Scale will only be communicated to the client when the construction packet is sent + void SetScale(const float scale) { m_Scale = scale; }; + protected: LWOOBJID m_ObjectID; @@ -399,14 +399,8 @@ const T& Entity::GetVar(const std::u16string& name) const { template T Entity::GetVarAs(const std::u16string& name) const { const auto data = GetVarAsString(name); - - T value; - - if (!GeneralUtils::TryParse(data, value)) { - return LDFData::Default; - } - - return value; + + return GeneralUtils::TryParse(data).value_or(LDFData::Default); } template diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index 10655d25..c95af3d7 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -7,7 +7,6 @@ #include "GeneralUtils.h" #include "dServer.h" #include "Spawner.h" -#include "Player.h" #include "SkillComponent.h" #include "SwitchComponent.h" #include "UserManager.h" @@ -25,6 +24,7 @@ #include "eReplicaPacketType.h" #include "PlayerManager.h" #include "GhostComponent.h" +#include // Configure which zones have ghosting disabled, mostly small worlds. std::vector EntityManager::m_GhostingExcludedZones = { @@ -118,14 +118,7 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE info.id = id; - Entity* entity; - - // Check if the entitty if a player, in case use the extended player entity class - if (user != nullptr) { - entity = new Player(id, info, user, parentEntity); - } else { - entity = new Entity(id, info, parentEntity); - } + Entity* entity = new Entity(id, info, user, parentEntity); // Initialize the entity entity->Initialize(); @@ -173,8 +166,8 @@ void EntityManager::DestroyEntity(Entity* entity) { } void EntityManager::SerializeEntities() { - for (int32_t i = 0; i < m_EntitiesToSerialize.size(); i++) { - const LWOOBJID toSerialize = m_EntitiesToSerialize.at(i); + for (size_t i = 0; i < m_EntitiesToSerialize.size(); i++) { + const LWOOBJID toSerialize = m_EntitiesToSerialize[i]; auto* entity = GetEntity(toSerialize); if (!entity) continue; @@ -185,26 +178,26 @@ void EntityManager::SerializeEntities() { stream.Write(ID_REPLICA_MANAGER_SERIALIZE); stream.Write(entity->GetNetworkId()); - entity->WriteBaseReplicaData(&stream, eReplicaPacketType::SERIALIZATION); - entity->WriteComponents(&stream, eReplicaPacketType::SERIALIZATION); + entity->WriteBaseReplicaData(stream, eReplicaPacketType::SERIALIZATION); + entity->WriteComponents(stream, eReplicaPacketType::SERIALIZATION); if (entity->GetIsGhostingCandidate()) { for (auto* player : PlayerManager::GetAllPlayers()) { auto* ghostComponent = player->GetComponent(); if (ghostComponent && ghostComponent->IsObserved(toSerialize)) { - Game::server->Send(&stream, player->GetSystemAddress(), false); + Game::server->Send(stream, player->GetSystemAddress(), false); } } } else { - Game::server->Send(&stream, UNASSIGNED_SYSTEM_ADDRESS, true); + Game::server->Send(stream, UNASSIGNED_SYSTEM_ADDRESS, true); } } m_EntitiesToSerialize.clear(); } void EntityManager::KillEntities() { - for (int32_t i = 0; i < m_EntitiesToKill.size(); i++) { - const LWOOBJID toKill = m_EntitiesToKill.at(i); + for (size_t i = 0; i < m_EntitiesToKill.size(); i++) { + const LWOOBJID toKill = m_EntitiesToKill[i]; auto* entity = GetEntity(toKill); if (!entity) { @@ -222,8 +215,8 @@ void EntityManager::KillEntities() { } void EntityManager::DeleteEntities() { - for (int32_t i = 0; i < m_EntitiesToDelete.size(); i++) { - const LWOOBJID toDelete = m_EntitiesToDelete.at(i); + for (size_t i = 0; i < m_EntitiesToDelete.size(); i++) { + const LWOOBJID toDelete = m_EntitiesToDelete[i]; auto entityToDelete = GetEntity(toDelete); if (entityToDelete) { // Get all this info first before we delete the player. @@ -246,8 +239,8 @@ void EntityManager::DeleteEntities() { } void EntityManager::UpdateEntities(const float deltaTime) { - for (const auto& e : m_Entities) { - e.second->Update(deltaTime); + for (auto* entity : m_Entities | std::views::values) { + entity->Update(deltaTime); } SerializeEntities(); @@ -267,10 +260,10 @@ Entity* EntityManager::GetEntity(const LWOOBJID& objectId) const { std::vector EntityManager::GetEntitiesInGroup(const std::string& group) { std::vector entitiesInGroup; - for (const auto& entity : m_Entities) { - for (const auto& entityGroup : entity.second->GetGroups()) { + for (auto* entity : m_Entities | std::views::values) { + for (const auto& entityGroup : entity->GetGroups()) { if (entityGroup == group) { - entitiesInGroup.push_back(entity.second); + entitiesInGroup.push_back(entity); } } } @@ -280,10 +273,12 @@ std::vector EntityManager::GetEntitiesInGroup(const std::string& group) std::vector EntityManager::GetEntitiesByComponent(const eReplicaComponentType componentType) const { std::vector withComp; - for (const auto& entity : m_Entities) { - if (componentType != eReplicaComponentType::INVALID && !entity.second->HasComponent(componentType)) continue; + if (componentType != eReplicaComponentType::INVALID) { + for (auto* entity : m_Entities | std::views::values) { + if (!entity->HasComponent(componentType)) continue; - withComp.push_back(entity.second); + withComp.push_back(entity); + } } return withComp; } @@ -291,19 +286,19 @@ std::vector EntityManager::GetEntitiesByComponent(const eReplicaCompone std::vector EntityManager::GetEntitiesByLOT(const LOT& lot) const { std::vector entities; - for (const auto& entity : m_Entities) { - if (entity.second->GetLOT() == lot) - entities.push_back(entity.second); + for (auto* entity : m_Entities | std::views::values) { + if (entity->GetLOT() == lot) entities.push_back(entity); } return entities; } -std::vector EntityManager::GetEntitiesByProximity(NiPoint3 reference, float radius) const{ - std::vector entities = {}; - if (radius > 1000.0f) return entities; - for (const auto& entity : m_Entities) { - if (NiPoint3::Distance(reference, entity.second->GetPosition()) <= radius) entities.push_back(entity.second); +std::vector EntityManager::GetEntitiesByProximity(NiPoint3 reference, float radius) const { + std::vector entities; + if (radius <= 1000.0f) { // The client has a 1000 unit limit on this same logic, so we'll use the same limit + for (auto* entity : m_Entities | std::views::values) { + if (NiPoint3::Distance(reference, entity->GetPosition()) <= radius) entities.push_back(entity); + } } return entities; } @@ -317,12 +312,8 @@ Entity* EntityManager::GetSpawnPointEntity(const std::string& spawnName) const { // Lookup the spawn point entity in the map const auto& spawnPoint = m_SpawnPoints.find(spawnName); - if (spawnPoint == m_SpawnPoints.end()) { - return nullptr; - } - // Check if the spawn point entity is valid just in case - return GetEntity(spawnPoint->second); + return spawnPoint == m_SpawnPoints.end() ? nullptr : GetEntity(spawnPoint->second); } const std::unordered_map& EntityManager::GetSpawnPointEntities() const { @@ -348,40 +339,36 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr entity->SetNetworkId(networkId); } - const auto checkGhosting = entity->GetIsGhostingCandidate(); - - if (checkGhosting) { - const auto& iter = std::find(m_EntitiesToGhost.begin(), m_EntitiesToGhost.end(), entity); - - if (iter == m_EntitiesToGhost.end()) { + if (entity->GetIsGhostingCandidate()) { + if (std::find(m_EntitiesToGhost.begin(), m_EntitiesToGhost.end(), entity) == m_EntitiesToGhost.end()) { m_EntitiesToGhost.push_back(entity); } - } - if (checkGhosting && sysAddr == UNASSIGNED_SYSTEM_ADDRESS) { - CheckGhosting(entity); + if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) { + CheckGhosting(entity); - return; + return; + } } m_SerializationCounter++; RakNet::BitStream stream; - stream.Write(ID_REPLICA_MANAGER_CONSTRUCTION); + stream.Write(ID_REPLICA_MANAGER_CONSTRUCTION); stream.Write(true); - stream.Write(entity->GetNetworkId()); + stream.Write(entity->GetNetworkId()); - entity->WriteBaseReplicaData(&stream, eReplicaPacketType::CONSTRUCTION); - entity->WriteComponents(&stream, eReplicaPacketType::CONSTRUCTION); + entity->WriteBaseReplicaData(stream, eReplicaPacketType::CONSTRUCTION); + entity->WriteComponents(stream, eReplicaPacketType::CONSTRUCTION); if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) { if (skipChecks) { - Game::server->Send(&stream, UNASSIGNED_SYSTEM_ADDRESS, true); + Game::server->Send(stream, UNASSIGNED_SYSTEM_ADDRESS, true); } else { for (auto* player : PlayerManager::GetAllPlayers()) { if (player->GetPlayerReadyForUpdates()) { - Game::server->Send(&stream, player->GetSystemAddress(), false); + Game::server->Send(stream, player->GetSystemAddress(), false); } else { auto* ghostComponent = player->GetComponent(); if (ghostComponent) ghostComponent->AddLimboConstruction(entity->GetObjectID()); @@ -389,7 +376,7 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr } } } else { - Game::server->Send(&stream, sysAddr, false); + Game::server->Send(stream, sysAddr, false); } if (entity->IsPlayer()) { @@ -403,9 +390,9 @@ void EntityManager::ConstructAllEntities(const SystemAddress& sysAddr) { //ZoneControl is special: ConstructEntity(m_ZoneControlEntity, sysAddr); - for (const auto& e : m_Entities) { - if (e.second && (e.second->GetSpawnerID() != 0 || e.second->GetLOT() == 1) && !e.second->GetIsGhostingCandidate()) { - ConstructEntity(e.second, sysAddr); + for (auto* entity : m_Entities | std::views::values) { + if (entity && (entity->GetSpawnerID() != 0 || entity->GetLOT() == 1) && !entity->GetIsGhostingCandidate()) { + ConstructEntity(entity, sysAddr); } } @@ -417,10 +404,10 @@ void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr) RakNet::BitStream stream; - stream.Write(ID_REPLICA_MANAGER_DESTRUCTION); - stream.Write(entity->GetNetworkId()); + stream.Write(ID_REPLICA_MANAGER_DESTRUCTION); + stream.Write(entity->GetNetworkId()); - Game::server->Send(&stream, sysAddr, sysAddr == UNASSIGNED_SYSTEM_ADDRESS); + Game::server->Send(stream, sysAddr, sysAddr == UNASSIGNED_SYSTEM_ADDRESS); for (auto* player : PlayerManager::GetAllPlayers()) { if (!player->GetPlayerReadyForUpdates()) { @@ -431,16 +418,22 @@ void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr) } void EntityManager::SerializeEntity(Entity* entity) { - if (!entity || entity->GetNetworkId() == 0) return; + if (!entity) return; + + EntityManager::SerializeEntity(*entity); +} - if (std::find(m_EntitiesToSerialize.begin(), m_EntitiesToSerialize.end(), entity->GetObjectID()) == m_EntitiesToSerialize.end()) { - m_EntitiesToSerialize.push_back(entity->GetObjectID()); +void EntityManager::SerializeEntity(const Entity& entity) { + if (entity.GetNetworkId() == 0) return; + + if (std::find(m_EntitiesToSerialize.cbegin(), m_EntitiesToSerialize.cend(), entity.GetObjectID()) == m_EntitiesToSerialize.cend()) { + m_EntitiesToSerialize.push_back(entity.GetObjectID()); } } void EntityManager::DestructAllEntities(const SystemAddress& sysAddr) { - for (const auto& e : m_Entities) { - DestructEntity(e.second, sysAddr); + for (auto* entity : m_Entities | std::views::values) { + DestructEntity(entity, sysAddr); } } @@ -448,22 +441,12 @@ void EntityManager::SetGhostDistanceMax(float value) { m_GhostDistanceMaxSquared = value * value; } -float EntityManager::GetGhostDistanceMax() const { - return std::sqrt(m_GhostDistanceMaxSquared); -} - void EntityManager::SetGhostDistanceMin(float value) { m_GhostDistanceMinSqaured = value * value; } -float EntityManager::GetGhostDistanceMin() const { - return std::sqrt(m_GhostDistanceMinSqaured); -} - void EntityManager::QueueGhostUpdate(LWOOBJID playerID) { - const auto& iter = std::find(m_PlayersToUpdateGhosting.begin(), m_PlayersToUpdateGhosting.end(), playerID); - - if (iter == m_PlayersToUpdateGhosting.end()) { + if (std::find(m_PlayersToUpdateGhosting.begin(), m_PlayersToUpdateGhosting.end(), playerID) == m_PlayersToUpdateGhosting.end()) { m_PlayersToUpdateGhosting.push_back(playerID); } } @@ -482,27 +465,21 @@ void EntityManager::UpdateGhosting() { m_PlayersToUpdateGhosting.clear(); } -void EntityManager::UpdateGhosting(Player* player) { - if (player == nullptr) { - return; - } +void EntityManager::UpdateGhosting(Entity* player) { + if (!player) return; auto* missionComponent = player->GetComponent(); auto* ghostComponent = player->GetComponent(); - if (missionComponent == nullptr || !ghostComponent) { - return; - } + if (!missionComponent || !ghostComponent) return; const auto& referencePoint = ghostComponent->GetGhostReferencePoint(); const auto isOverride = ghostComponent->GetGhostOverride(); for (auto* entity : m_EntitiesToGhost) { - const auto isAudioEmitter = entity->GetLOT() == 6368; - const auto& entityPoint = entity->GetPosition(); - const int32_t id = entity->GetObjectID(); + const auto id = entity->GetObjectID(); const auto observed = ghostComponent->IsObserved(id); @@ -511,6 +488,7 @@ void EntityManager::UpdateGhosting(Player* player) { auto ghostingDistanceMax = m_GhostDistanceMaxSquared; auto ghostingDistanceMin = m_GhostDistanceMinSqaured; + const auto isAudioEmitter = entity->GetLOT() == 6368; // https://explorer.lu/objects/6368 if (isAudioEmitter) { ghostingDistanceMax = ghostingDistanceMin; } @@ -549,30 +527,25 @@ void EntityManager::CheckGhosting(Entity* entity) { const auto& referencePoint = entity->GetPosition(); - auto ghostingDistanceMax = m_GhostDistanceMaxSquared; - auto ghostingDistanceMin = m_GhostDistanceMinSqaured; - - const auto isAudioEmitter = entity->GetLOT() == 6368; - for (auto* player : PlayerManager::GetAllPlayers()) { auto* ghostComponent = player->GetComponent(); if (!ghostComponent) continue; const auto& entityPoint = ghostComponent->GetGhostReferencePoint(); - const int32_t id = entity->GetObjectID(); + const auto id = entity->GetObjectID(); const auto observed = ghostComponent->IsObserved(id); const auto distance = NiPoint3::DistanceSquared(referencePoint, entityPoint); - if (observed && distance > ghostingDistanceMax) { + if (observed && distance > m_GhostDistanceMaxSquared) { ghostComponent->GhostEntity(id); DestructEntity(entity, player->GetSystemAddress()); entity->SetObservers(entity->GetObservers() - 1); - } else if (!observed && ghostingDistanceMin > distance) { + } else if (!observed && m_GhostDistanceMinSqaured > distance) { ghostComponent->ObserveEntity(id); ConstructEntity(entity, player->GetSystemAddress()); @@ -582,7 +555,7 @@ void EntityManager::CheckGhosting(Entity* entity) { } } -Entity* EntityManager::GetGhostCandidate(int32_t id) { +Entity* EntityManager::GetGhostCandidate(LWOOBJID id) const { for (auto* entity : m_EntitiesToGhost) { if (entity->GetObjectID() == id) { return entity; @@ -608,26 +581,22 @@ void EntityManager::ScheduleForKill(Entity* entity) { const auto objectId = entity->GetObjectID(); - if (std::count(m_EntitiesToKill.begin(), m_EntitiesToKill.end(), objectId)) { - return; + if (std::find(m_EntitiesToKill.begin(), m_EntitiesToKill.end(), objectId) == m_EntitiesToKill.end()) { + m_EntitiesToKill.push_back(objectId); } - - m_EntitiesToKill.push_back(objectId); } void EntityManager::ScheduleForDeletion(LWOOBJID entity) { - if (std::count(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity)) { - return; + if (std::find(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity) == m_EntitiesToDelete.end()) { + m_EntitiesToDelete.push_back(entity); } - - m_EntitiesToDelete.push_back(entity); } void EntityManager::FireEventServerSide(Entity* origin, std::string args) { - for (std::pair e : m_Entities) { - if (e.second) { - e.second->OnFireEventServerSide(origin, args); + for (const auto entity : m_Entities | std::views::values) { + if (entity) { + entity->OnFireEventServerSide(origin, args); } } } diff --git a/dGame/EntityManager.h b/dGame/EntityManager.h index 33d7aaff..fdbb1a55 100644 --- a/dGame/EntityManager.h +++ b/dGame/EntityManager.h @@ -45,19 +45,18 @@ public: void ConstructEntity(Entity* entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, bool skipChecks = false); void DestructEntity(Entity* entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); void SerializeEntity(Entity* entity); + void SerializeEntity(const Entity& entity); void ConstructAllEntities(const SystemAddress& sysAddr); void DestructAllEntities(const SystemAddress& sysAddr); void SetGhostDistanceMax(float value); - float GetGhostDistanceMax() const; void SetGhostDistanceMin(float value); - float GetGhostDistanceMin() const; void QueueGhostUpdate(LWOOBJID playerID); void UpdateGhosting(); - void UpdateGhosting(Player* player); + void UpdateGhosting(Entity* player); void CheckGhosting(Entity* entity); - Entity* GetGhostCandidate(int32_t id); + Entity* GetGhostCandidate(LWOOBJID id) const; bool GetGhostingEnabled() const; void ScheduleForKill(Entity* entity); diff --git a/dGame/LeaderboardManager.cpp b/dGame/LeaderboardManager.cpp index 1fd49d26..347bd68e 100644 --- a/dGame/LeaderboardManager.cpp +++ b/dGame/LeaderboardManager.cpp @@ -43,9 +43,9 @@ inline void WriteLeaderboardRow(std::ostringstream& leaderboard, const uint32_t& leaderboard << "\nResult[0].Row[" << index << "]." << data->GetString(); } -void Leaderboard::Serialize(RakNet::BitStream* bitStream) const { - bitStream->Write(gameID); - bitStream->Write(infoType); +void Leaderboard::Serialize(RakNet::BitStream& bitStream) const { + bitStream.Write(gameID); + bitStream.Write(infoType); std::ostringstream leaderboard; @@ -64,12 +64,12 @@ void Leaderboard::Serialize(RakNet::BitStream* bitStream) const { // Serialize the thing to a BitStream uint32_t leaderboardSize = leaderboard.tellp(); - bitStream->Write(leaderboardSize); + bitStream.Write(leaderboardSize); // Doing this all in 1 call so there is no possbility of a dangling pointer. - bitStream->WriteAlignedBytes(reinterpret_cast(GeneralUtils::ASCIIToUTF16(leaderboard.str()).c_str()), leaderboardSize * sizeof(char16_t)); - if (leaderboardSize > 0) bitStream->Write(0); - bitStream->Write0(); - bitStream->Write0(); + bitStream.WriteAlignedBytes(reinterpret_cast(GeneralUtils::ASCIIToUTF16(leaderboard.str()).c_str()), leaderboardSize * sizeof(char16_t)); + if (leaderboardSize > 0) bitStream.Write(0); + bitStream.Write0(); + bitStream.Write0(); } void Leaderboard::QueryToLdf(std::unique_ptr& rows) { @@ -402,7 +402,7 @@ Leaderboard::Type LeaderboardManager::GetLeaderboardType(const GameID gameID) { auto lookup = leaderboardCache.find(gameID); if (lookup != leaderboardCache.end()) return lookup->second; - auto* activitiesTable = CDClientManager::Instance().GetTable(); + auto* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([gameID](const CDActivities& entry) { return entry.ActivityID == gameID; }); diff --git a/dGame/LeaderboardManager.h b/dGame/LeaderboardManager.h index e2ce3f97..527ae02d 100644 --- a/dGame/LeaderboardManager.h +++ b/dGame/LeaderboardManager.h @@ -6,7 +6,6 @@ #include #include -#include "Singleton.h" #include "dCommonVars.h" #include "LDFFormat.h" @@ -89,7 +88,7 @@ public: * * Expensive! Leaderboards are very string intensive so be wary of performatnce calling this method. */ - void Serialize(RakNet::BitStream* bitStream) const; + void Serialize(RakNet::BitStream& bitStream) const; /** * Builds the leaderboard from the database based on the associated gameID diff --git a/dGame/Player.cpp b/dGame/Player.cpp deleted file mode 100644 index 8f414b43..00000000 --- a/dGame/Player.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include "Player.h" - -#include - -#include "Character.h" -#include "UserManager.h" -#include "EntityManager.h" -#include "Game.h" -#include "Logger.h" -#include "dZoneManager.h" -#include "User.h" -#include "CppScripts.h" -#include "Loot.h" -#include "eReplicaComponentType.h" -#include "PlayerManager.h" - -void Player::SetRespawnPos(const NiPoint3& position) { - if (!m_Character) return; - - m_respawnPos = position; - - m_Character->SetRespawnPoint(Game::zoneManager->GetZone()->GetWorldID(), position); - -} - -void Player::SetRespawnRot(const NiQuaternion& rotation) { - m_respawnRot = rotation; -} - -void Player::SetSystemAddress(const SystemAddress& value) { - m_SystemAddress = value; -} - -Player::Player(const LWOOBJID& objectID, const EntityInfo info, User* user, Entity* parentEntity) : Entity(objectID, info, parentEntity) { - m_ParentUser = user; - m_Character = m_ParentUser->GetLastUsedChar(); - m_ParentUser->SetLoggedInChar(objectID); - m_GMLevel = m_Character->GetGMLevel(); - m_SystemAddress = m_ParentUser->GetSystemAddress(); - m_DroppedCoins = 0; - - m_Character->SetEntity(this); - - PlayerManager::AddPlayer(this); -} - -Player::~Player() { - LOG("Deleted player"); - - // Make sure the player exists first. Remove afterwards to prevent the OnPlayerExist functions from not being able to find the player. - if (!PlayerManager::RemovePlayer(this)) { - LOG("Unable to find player to remove from manager."); - return; - } - - if (IsPlayer()) { - Entity* zoneControl = Game::entityManager->GetZoneControlEntity(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { - script->OnPlayerExit(zoneControl, this); - } - - std::vector scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); - for (Entity* scriptEntity : scriptedActs) { - if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds - for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { - script->OnPlayerExit(scriptEntity, this); - } - } - } - } -} diff --git a/dGame/Player.h b/dGame/Player.h deleted file mode 100644 index dd8efd9c..00000000 --- a/dGame/Player.h +++ /dev/null @@ -1,62 +0,0 @@ -#pragma once - -#include "Entity.h" - -/** - * Extended Entity for player data and behavior. - * - * Contains properties only a player entity would require, like associated SystemAddress and User. - * - * Keeps track of which entities are observed by this user for ghosting. - */ -class Player final : public Entity -{ -public: - explicit Player(const LWOOBJID& objectID, EntityInfo info, User* user, Entity* parentEntity = nullptr); - - /** - * Getters - */ - - User* GetParentUser() const override { return m_ParentUser; }; - - const SystemAddress& GetSystemAddress() const override { return m_SystemAddress; }; - - const NiPoint3& GetRespawnPosition() const override { return m_respawnPos; }; - - const NiQuaternion& GetRespawnRotation() const override { return m_respawnRot; }; - - std::map& GetDroppedLoot() { return m_DroppedLoot; }; - - uint64_t GetDroppedCoins() const { return m_DroppedCoins; }; - - /** - * Setters - */ - - void SetDroppedCoins(const uint64_t value) { m_DroppedCoins = value; }; - - void SetSystemAddress(const SystemAddress& value) override; - - void SetRespawnPos(const NiPoint3& position) override; - - void SetRespawnRot(const NiQuaternion& rotation) override; - - /** - * Ghosting - */ - - ~Player() override; -private: - SystemAddress m_SystemAddress; - - NiPoint3 m_respawnPos; - - NiQuaternion m_respawnRot; - - User* m_ParentUser; - - std::map m_DroppedLoot; - - uint64_t m_DroppedCoins; -}; diff --git a/dGame/PlayerManager.cpp b/dGame/PlayerManager.cpp index e3017f05..61e2568d 100644 --- a/dGame/PlayerManager.cpp +++ b/dGame/PlayerManager.cpp @@ -1,20 +1,19 @@ #include "PlayerManager.h" #include "Character.h" -#include "Player.h" #include "User.h" #include "UserManager.h" #include "eReplicaComponentType.h" namespace { - std::vector m_Players; + std::vector m_Players; }; -const std::vector& PlayerManager::GetAllPlayers() { +const std::vector& PlayerManager::GetAllPlayers() { return m_Players; } -void PlayerManager::AddPlayer(Player* player) { +void PlayerManager::AddPlayer(Entity* player) { const auto& iter = std::find(m_Players.begin(), m_Players.end(), player); if (iter == m_Players.end()) { @@ -22,7 +21,7 @@ void PlayerManager::AddPlayer(Player* player) { } } -bool PlayerManager::RemovePlayer(Player* player) { +bool PlayerManager::RemovePlayer(Entity* player) { const auto iter = std::find(m_Players.begin(), m_Players.end(), player); const bool toReturn = iter != m_Players.end(); @@ -33,21 +32,21 @@ bool PlayerManager::RemovePlayer(Player* player) { return toReturn; } -Player* PlayerManager::GetPlayer(const SystemAddress& sysAddr) { +Entity* PlayerManager::GetPlayer(const SystemAddress& sysAddr) { auto* entity = UserManager::Instance()->GetUser(sysAddr)->GetLastUsedChar()->GetEntity(); - return static_cast(entity); + return entity; } -Player* PlayerManager::GetPlayer(const std::string& name) { +Entity* PlayerManager::GetPlayer(const std::string& name) { const auto characters = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::CHARACTER); - Player* player = nullptr; + Entity* player = nullptr; for (auto* character : characters) { if (!character->IsPlayer()) continue; if (GeneralUtils::CaseInsensitiveStringCompare(name, character->GetCharacter()->GetName())) { - player = dynamic_cast(character); + player = character; break; } } @@ -55,8 +54,8 @@ Player* PlayerManager::GetPlayer(const std::string& name) { return player; } -Player* PlayerManager::GetPlayer(LWOOBJID playerID) { - Player* playerToReturn = nullptr; +Entity* PlayerManager::GetPlayer(LWOOBJID playerID) { + Entity* playerToReturn = nullptr; for (auto* player : m_Players) { if (player->GetObjectID() == playerID) { playerToReturn = player; diff --git a/dGame/PlayerManager.h b/dGame/PlayerManager.h index bb54f83b..7f6be5ba 100644 --- a/dGame/PlayerManager.h +++ b/dGame/PlayerManager.h @@ -5,21 +5,21 @@ #include -class Player; +class Entity; struct SystemAddress; namespace PlayerManager { - void AddPlayer(Player* player); + void AddPlayer(Entity* player); - bool RemovePlayer(Player* player); + bool RemovePlayer(Entity* player); - Player* GetPlayer(const SystemAddress& sysAddr); + Entity* GetPlayer(const SystemAddress& sysAddr); - Player* GetPlayer(const std::string& name); + Entity* GetPlayer(const std::string& name); - Player* GetPlayer(LWOOBJID playerID); + Entity* GetPlayer(LWOOBJID playerID); - const std::vector& GetAllPlayers(); + const std::vector& GetAllPlayers(); }; #endif //!__PLAYERMANAGER__H__ diff --git a/dGame/TradingManager.cpp b/dGame/TradingManager.cpp index 3d9a209c..c7143354 100644 --- a/dGame/TradingManager.cpp +++ b/dGame/TradingManager.cpp @@ -104,7 +104,7 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) { } Complete(); - TradingManager::Instance()->CancelTrade(m_TradeId); + TradingManager::Instance()->CancelTrade(LWOOBJID_EMPTY, m_TradeId, false); } } @@ -178,14 +178,14 @@ void Trade::Complete() { return; } -void Trade::Cancel() { +void Trade::Cancel(const LWOOBJID canceller) { auto* entityA = GetParticipantAEntity(); auto* entityB = GetParticipantBEntity(); if (entityA == nullptr || entityB == nullptr) return; - GameMessages::SendServerTradeCancel(entityA->GetObjectID(), entityA->GetSystemAddress()); - GameMessages::SendServerTradeCancel(entityB->GetObjectID(), entityB->GetSystemAddress()); + if (entityA->GetObjectID() != canceller || canceller == LWOOBJID_EMPTY) GameMessages::SendServerTradeCancel(entityA->GetObjectID(), entityA->GetSystemAddress()); + if (entityB->GetObjectID() != canceller || canceller == LWOOBJID_EMPTY) GameMessages::SendServerTradeCancel(entityB->GetObjectID(), entityB->GetSystemAddress()); } void Trade::SendUpdateToOther(LWOOBJID participant) { @@ -262,11 +262,13 @@ Trade* TradingManager::GetPlayerTrade(LWOOBJID playerId) const { return nullptr; } -void TradingManager::CancelTrade(LWOOBJID tradeId) { +void TradingManager::CancelTrade(const LWOOBJID canceller, LWOOBJID tradeId, const bool sendCancelMessage) { auto* trade = GetTrade(tradeId); if (trade == nullptr) return; + if (sendCancelMessage) trade->Cancel(canceller); + delete trade; trades.erase(tradeId); diff --git a/dGame/TradingManager.h b/dGame/TradingManager.h index ec0d332f..fa55aa9d 100644 --- a/dGame/TradingManager.h +++ b/dGame/TradingManager.h @@ -30,7 +30,7 @@ public: void SetAccepted(LWOOBJID participant, bool value); void Complete(); - void Cancel(); + void Cancel(const LWOOBJID canceller); void SendUpdateToOther(LWOOBJID participant); @@ -66,7 +66,7 @@ public: Trade* GetTrade(LWOOBJID tradeId) const; Trade* GetPlayerTrade(LWOOBJID playerId) const; - void CancelTrade(LWOOBJID tradeId); + void CancelTrade(const LWOOBJID canceller, LWOOBJID tradeId, const bool sendCancelMessage = true); Trade* NewTrade(LWOOBJID participantA, LWOOBJID participantB); private: diff --git a/dGame/UserManager.cpp b/dGame/UserManager.cpp index 97ceced1..930e1a29 100644 --- a/dGame/UserManager.cpp +++ b/dGame/UserManager.cpp @@ -301,6 +301,7 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) const auto name = LUWStringName.GetAsString(); std::string predefinedName = GetPredefinedName(firstNameIndex, middleNameIndex, lastNameIndex); + LOT shirtLOT = FindCharShirtID(shirtColor, shirtStyle); LOT pantsLOT = FindCharPantsID(pantsColor); @@ -323,7 +324,7 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) } //Now that the name is ok, we can get an objectID from Master: - ObjectIDManager::RequestPersistentID([=, this](uint32_t objectID) { + ObjectIDManager::RequestPersistentID([=, this](uint32_t objectID) mutable { if (Database::Get()->GetCharacterInfo(objectID)) { LOG("Character object id unavailable, check object_id_tracker!"); WorldPackets::SendCharacterCreationResponse(sysAddr, eCharacterCreationResponse::OBJECT_ID_UNAVAILABLE); @@ -366,6 +367,14 @@ void UserManager::CreateCharacter(const SystemAddress& sysAddr, Packet* packet) bool nameOk = IsNamePreapproved(name); if (!nameOk && u->GetMaxGMLevel() > eGameMasterLevel::FORUM_MODERATOR) nameOk = true; + // If predefined name is invalid, change it to be their object id + // that way more than one player can create characters if the predefined name files are not provided + if (predefinedName == "INVALID") { + std::stringstream nameObjID; + nameObjID << "minifig" << objectID; + predefinedName = nameObjID.str(); + } + std::string_view nameToAssign = !name.empty() && nameOk ? name : predefinedName; std::string pendingName = !name.empty() && !nameOk ? name : ""; @@ -451,7 +460,7 @@ void UserManager::RenameCharacter(const SystemAddress& sysAddr, Packet* packet) "User %i tried to rename a character that it does not own!", u->GetAccountID()); - std::find_if(u->GetCharacters().begin(), u->GetCharacters().end(), [&](Character* c) { + auto unusedItr = std::find_if(u->GetCharacters().begin(), u->GetCharacters().end(), [&](Character* c) { if (c->GetID() == charID) { character = c; return true; diff --git a/dGame/dBehaviors/AirMovementBehavior.cpp b/dGame/dBehaviors/AirMovementBehavior.cpp index 8a3f894c..46d18680 100644 --- a/dGame/dBehaviors/AirMovementBehavior.cpp +++ b/dGame/dBehaviors/AirMovementBehavior.cpp @@ -5,35 +5,35 @@ #include "Game.h" #include "Logger.h" -void AirMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void AirMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { uint32_t handle{}; - if (!bitStream->Read(handle)) { - LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(handle)) { + LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; } context->RegisterSyncBehavior(handle, this, branch, this->m_Timeout); } -void AirMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void AirMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { const auto handle = context->GetUniqueSkillId(); - bitStream->Write(handle); + bitStream.Write(handle); } -void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { uint32_t behaviorId{}; - if (!bitStream->Read(behaviorId)) { - LOG("Unable to read behaviorId from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(behaviorId)) { + LOG("Unable to read behaviorId from bitStream, aborting Sync! %i", bitStream.GetNumberOfUnreadBits()); return; } LWOOBJID target{}; - if (!bitStream->Read(target)) { - LOG("Unable to read target from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(target)) { + LOG("Unable to read target from bitStream, aborting Sync! %i", bitStream.GetNumberOfUnreadBits()); return; } diff --git a/dGame/dBehaviors/AirMovementBehavior.h b/dGame/dBehaviors/AirMovementBehavior.h index 9d51ef03..0edb1a76 100644 --- a/dGame/dBehaviors/AirMovementBehavior.h +++ b/dGame/dBehaviors/AirMovementBehavior.h @@ -6,11 +6,11 @@ class AirMovementBehavior final : public Behavior public: explicit AirMovementBehavior(const uint32_t behavior_id) : Behavior(behavior_id) {} - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; private: diff --git a/dGame/dBehaviors/AndBehavior.cpp b/dGame/dBehaviors/AndBehavior.cpp index 57493248..ad986e37 100644 --- a/dGame/dBehaviors/AndBehavior.cpp +++ b/dGame/dBehaviors/AndBehavior.cpp @@ -3,13 +3,13 @@ #include "Game.h" #include "Logger.h" -void AndBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void AndBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { for (auto* behavior : this->m_behaviors) { behavior->Handle(context, bitStream, branch); } } -void AndBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void AndBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { for (auto* behavior : this->m_behaviors) { behavior->Calculate(context, bitStream, branch); } diff --git a/dGame/dBehaviors/AndBehavior.h b/dGame/dBehaviors/AndBehavior.h index 0ef7c0fd..76bd3956 100644 --- a/dGame/dBehaviors/AndBehavior.h +++ b/dGame/dBehaviors/AndBehavior.h @@ -15,9 +15,9 @@ public: explicit AndBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/ApplyBuffBehavior.cpp b/dGame/dBehaviors/ApplyBuffBehavior.cpp index 26b3da84..9ee48375 100644 --- a/dGame/dBehaviors/ApplyBuffBehavior.cpp +++ b/dGame/dBehaviors/ApplyBuffBehavior.cpp @@ -5,7 +5,7 @@ #include "BuffComponent.h" -void ApplyBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ApplyBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* entity = Game::entityManager->GetEntity(branch.target == LWOOBJID_EMPTY ? context->originator : branch.target); if (entity == nullptr) return; @@ -30,7 +30,7 @@ void ApplyBuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext b buffComponent->RemoveBuff(m_BuffId); } -void ApplyBuffBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ApplyBuffBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } diff --git a/dGame/dBehaviors/ApplyBuffBehavior.h b/dGame/dBehaviors/ApplyBuffBehavior.h index e01a238e..4acc6550 100644 --- a/dGame/dBehaviors/ApplyBuffBehavior.h +++ b/dGame/dBehaviors/ApplyBuffBehavior.h @@ -24,11 +24,11 @@ public: explicit ApplyBuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; private: diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.cpp b/dGame/dBehaviors/AreaOfEffectBehavior.cpp index 2a7e9754..ce41785f 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.cpp +++ b/dGame/dBehaviors/AreaOfEffectBehavior.cpp @@ -12,11 +12,11 @@ #include "Game.h" #include "Logger.h" -void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { uint32_t targetCount{}; - if (!bitStream->Read(targetCount)) { - LOG("Unable to read targetCount from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(targetCount)) { + LOG("Unable to read targetCount from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; } @@ -40,7 +40,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* b for (auto i = 0u; i < targetCount; ++i) { LWOOBJID target{}; - if (!bitStream->Read(target)) { + if (!bitStream.Read(target)) { LOG("failed to read in target %i from bitStream, aborting target Handle!", i); }; targets.push_back(target); @@ -54,7 +54,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* b PlayFx(u"cast", context->originator); } -void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* caster = Game::entityManager->GetEntity(context->caster); if (!caster) return; @@ -83,7 +83,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream // resize if we have more than max targets allows if (targets.size() > this->m_maxTargets) targets.resize(this->m_maxTargets); - bitStream->Write(targets.size()); + bitStream.Write(targets.size()); if (targets.size() == 0) { PlayFx(u"miss", context->originator); @@ -92,7 +92,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream context->foundTarget = true; // write all the targets to the bitstream for (auto* target : targets) { - bitStream->Write(target->GetObjectID()); + bitStream.Write(target->GetObjectID()); } // then cast all the actions diff --git a/dGame/dBehaviors/AreaOfEffectBehavior.h b/dGame/dBehaviors/AreaOfEffectBehavior.h index f0fbb18d..5ce20003 100644 --- a/dGame/dBehaviors/AreaOfEffectBehavior.h +++ b/dGame/dBehaviors/AreaOfEffectBehavior.h @@ -6,8 +6,8 @@ class AreaOfEffectBehavior final : public Behavior { public: explicit AreaOfEffectBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; private: Behavior* m_action; diff --git a/dGame/dBehaviors/AttackDelayBehavior.cpp b/dGame/dBehaviors/AttackDelayBehavior.cpp index 1bf1048a..105a1327 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.cpp +++ b/dGame/dBehaviors/AttackDelayBehavior.cpp @@ -4,11 +4,11 @@ #include "Game.h" #include "Logger.h" -void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { uint32_t handle{}; - if (!bitStream->Read(handle)) { - LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(handle)) { + LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; @@ -17,10 +17,10 @@ void AttackDelayBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi } } -void AttackDelayBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void AttackDelayBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { const auto handle = context->GetUniqueSkillId(); - bitStream->Write(handle); + bitStream.Write(handle); context->foundTarget = true; @@ -31,11 +31,11 @@ void AttackDelayBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* } } -void AttackDelayBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void AttackDelayBehavior::Sync(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { this->m_action->Handle(context, bitStream, branch); } -void AttackDelayBehavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void AttackDelayBehavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { PlayFx(u"cast", context->originator); this->m_action->Calculate(context, bitStream, branch); diff --git a/dGame/dBehaviors/AttackDelayBehavior.h b/dGame/dBehaviors/AttackDelayBehavior.h index 64271ba5..173b0a0d 100644 --- a/dGame/dBehaviors/AttackDelayBehavior.h +++ b/dGame/dBehaviors/AttackDelayBehavior.h @@ -19,13 +19,13 @@ public: explicit AttackDelayBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void SyncCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/BasicAttackBehavior.cpp b/dGame/dBehaviors/BasicAttackBehavior.cpp index 914e67a5..3d45d9a7 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.cpp +++ b/dGame/dBehaviors/BasicAttackBehavior.cpp @@ -9,7 +9,7 @@ #include "BehaviorContext.h" #include "eBasicAttackSuccessTypes.h" -void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { if (context->unmanaged) { auto* entity = Game::entityManager->GetEntity(branch.target); @@ -30,22 +30,22 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi return; } - bitStream->AlignReadToByteBoundary(); + bitStream.AlignReadToByteBoundary(); uint16_t allocatedBits{}; - if (!bitStream->Read(allocatedBits) || allocatedBits == 0) { + if (!bitStream.Read(allocatedBits) || allocatedBits == 0) { LOG_DEBUG("No allocated bits"); return; } LOG_DEBUG("Number of allocated bits %i", allocatedBits); - const auto baseAddress = bitStream->GetReadOffset(); + const auto baseAddress = bitStream.GetReadOffset(); DoHandleBehavior(context, bitStream, branch); - bitStream->SetReadOffset(baseAddress + allocatedBits); + bitStream.SetReadOffset(baseAddress + allocatedBits); } -void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* targetEntity = Game::entityManager->GetEntity(branch.target); if (!targetEntity) { LOG("Target targetEntity %llu not found.", branch.target); @@ -62,7 +62,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit bool isImmune{}; bool isSuccess{}; - if (!bitStream->Read(isBlocked)) { + if (!bitStream.Read(isBlocked)) { LOG("Unable to read isBlocked"); return; } @@ -74,7 +74,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit return; } - if (!bitStream->Read(isImmune)) { + if (!bitStream.Read(isImmune)) { LOG("Unable to read isImmune"); return; } @@ -85,20 +85,20 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit return; } - if (!bitStream->Read(isSuccess)) { + if (!bitStream.Read(isSuccess)) { LOG("failed to read success from bitstream"); return; } if (isSuccess) { uint32_t armorDamageDealt{}; - if (!bitStream->Read(armorDamageDealt)) { + if (!bitStream.Read(armorDamageDealt)) { LOG("Unable to read armorDamageDealt"); return; } uint32_t healthDamageDealt{}; - if (!bitStream->Read(healthDamageDealt)) { + if (!bitStream.Read(healthDamageDealt)) { LOG("Unable to read healthDamageDealt"); return; } @@ -111,7 +111,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit } bool died{}; - if (!bitStream->Read(died)) { + if (!bitStream.Read(died)) { LOG("Unable to read died"); return; } @@ -122,7 +122,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit } uint8_t successState{}; - if (!bitStream->Read(successState)) { + if (!bitStream.Read(successState)) { LOG("Unable to read success state"); return; } @@ -144,26 +144,26 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit } } -void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - bitStream->AlignWriteToByteBoundary(); +void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { + bitStream.AlignWriteToByteBoundary(); - const auto allocatedAddress = bitStream->GetWriteOffset(); + const auto allocatedAddress = bitStream.GetWriteOffset(); - bitStream->Write(0); + bitStream.Write(0); - const auto startAddress = bitStream->GetWriteOffset(); + const auto startAddress = bitStream.GetWriteOffset(); DoBehaviorCalculation(context, bitStream, branch); - const auto endAddress = bitStream->GetWriteOffset(); + const auto endAddress = bitStream.GetWriteOffset(); const uint16_t allocate = endAddress - startAddress; - bitStream->SetWriteOffset(allocatedAddress); - bitStream->Write(allocate); - bitStream->SetWriteOffset(startAddress + allocate); + bitStream.SetWriteOffset(allocatedAddress); + bitStream.Write(allocate); + bitStream.SetWriteOffset(startAddress + allocate); } -void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* targetEntity = Game::entityManager->GetEntity(branch.target); if (!targetEntity) { LOG("Target entity %llu is null!", branch.target); @@ -178,7 +178,7 @@ void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet const bool isBlocking = destroyableComponent->GetAttacksToBlock() > 0; - bitStream->Write(isBlocking); + bitStream.Write(isBlocking); if (isBlocking) { destroyableComponent->SetAttacksToBlock(destroyableComponent->GetAttacksToBlock() - 1); @@ -188,7 +188,7 @@ void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet } const bool isImmune = destroyableComponent->IsImmune() || destroyableComponent->IsCooldownImmune(); - bitStream->Write(isImmune); + bitStream.Write(isImmune); if (isImmune) { LOG_DEBUG("Target targetEntity %llu is immune!", branch.target); @@ -210,7 +210,7 @@ void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet const uint32_t healthDamageDealt = previousHealth - destroyableComponent->GetHealth(); isSuccess = armorDamageDealt > 0 || healthDamageDealt > 0 || (armorDamageDealt + healthDamageDealt) > 0; - bitStream->Write(isSuccess); + bitStream.Write(isSuccess); //Handle player damage cooldown if (isSuccess && targetEntity->IsPlayer() && !this->m_DontApplyImmune) { @@ -225,12 +225,12 @@ void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet successState = this->m_OnFailArmor->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY ? eBasicAttackSuccessTypes::FAILIMMUNE : eBasicAttackSuccessTypes::FAILARMOR; } - bitStream->Write(armorDamageDealt); - bitStream->Write(healthDamageDealt); - bitStream->Write(targetEntity->GetIsDead()); + bitStream.Write(armorDamageDealt); + bitStream.Write(healthDamageDealt); + bitStream.Write(targetEntity->GetIsDead()); } - bitStream->Write(successState); + bitStream.Write(successState); switch (static_cast(successState)) { case eBasicAttackSuccessTypes::SUCCESS: diff --git a/dGame/dBehaviors/BasicAttackBehavior.h b/dGame/dBehaviors/BasicAttackBehavior.h index 6525c343..3cde23fd 100644 --- a/dGame/dBehaviors/BasicAttackBehavior.h +++ b/dGame/dBehaviors/BasicAttackBehavior.h @@ -12,7 +12,7 @@ public: * is then offset to after the allocated bits for this stream. * */ - void DoHandleBehavior(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch); + void DoHandleBehavior(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch); /** * @brief Handles a client initialized Basic Attack Behavior cast to be deserialized and verified on the server. @@ -22,14 +22,14 @@ public: * and will fail gracefully if an overread is detected. * @param branch The context of this specific branch of the Skill Behavior. Changes based on which branch you are going down. */ - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; /** * @brief Writes a 16bit short to the bitStream and when the actual behavior calculation finishes with all of its branches, the number * of bits used is then written to where the 16bit short initially was. * */ - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; /** * @brief Calculates a server initialized Basic Attack Behavior cast to be serialized to the client @@ -38,7 +38,7 @@ public: * @param bitStream The bitStream to serialize to. * @param branch The context of this specific branch of the Skill Behavior. Changes based on which branch you are going down. */ - void DoBehaviorCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch); + void DoBehaviorCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch); /** * @brief Loads this Behaviors parameters from the database. For this behavior specifically: diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index c70b34c7..36607a66 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -82,7 +82,7 @@ CDBehaviorParameterTable* Behavior::BehaviorParameterTable = nullptr; Behavior* Behavior::GetBehavior(const uint32_t behaviorId) { if (BehaviorParameterTable == nullptr) { - BehaviorParameterTable = CDClientManager::Instance().GetTable(); + BehaviorParameterTable = CDClientManager::GetTable(); } const auto pair = Cache.find(behaviorId); @@ -297,7 +297,7 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) { } BehaviorTemplates Behavior::GetBehaviorTemplate(const uint32_t behaviorId) { - auto behaviorTemplateTable = CDClientManager::Instance().GetTable(); + auto behaviorTemplateTable = CDClientManager::GetTable(); BehaviorTemplates templateID = BehaviorTemplates::BEHAVIOR_EMPTY; // Find behavior template by its behavior id. Default to 0. @@ -405,7 +405,7 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID } Behavior::Behavior(const uint32_t behaviorId) { - auto behaviorTemplateTable = CDClientManager::Instance().GetTable(); + auto behaviorTemplateTable = CDClientManager::GetTable(); CDBehaviorTemplate templateInDatabase{}; @@ -448,7 +448,7 @@ Behavior::Behavior(const uint32_t behaviorId) { float Behavior::GetFloat(const std::string& name, const float defaultValue) const { // Get the behavior parameter entry and return its value. - if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance().GetTable(); + if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::GetTable(); return BehaviorParameterTable->GetValue(this->m_behaviorId, name, defaultValue); } @@ -476,7 +476,7 @@ Behavior* Behavior::GetAction(float value) const { std::map Behavior::GetParameterNames() const { std::map templatesInDatabase; // Find behavior template by its behavior id. - if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance().GetTable(); + if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::GetTable(); if (BehaviorParameterTable) { templatesInDatabase = BehaviorParameterTable->GetParametersByBehaviorID(this->m_behaviorId); } @@ -487,10 +487,10 @@ std::map Behavior::GetParameterNames() const { void Behavior::Load() { } -void Behavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void Behavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { } -void Behavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void Behavior::Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { } void Behavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) { @@ -502,10 +502,10 @@ void Behavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWO void Behavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { } -void Behavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void Behavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { } -void Behavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void Behavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { } Behavior::~Behavior() { diff --git a/dGame/dBehaviors/Behavior.h b/dGame/dBehaviors/Behavior.h index ca1c23e5..af7fd206 100644 --- a/dGame/dBehaviors/Behavior.h +++ b/dGame/dBehaviors/Behavior.h @@ -68,9 +68,9 @@ public: virtual void Load(); // Player side - virtual void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch); + virtual void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch); - virtual void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch); + virtual void Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch); virtual void UnCast(BehaviorContext* context, BehaviorBranchContext branch); @@ -79,9 +79,9 @@ public: virtual void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second); // Npc side - virtual void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch); + virtual void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch); - virtual void SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch); + virtual void SyncCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch); /* * Creations/destruction diff --git a/dGame/dBehaviors/BehaviorContext.cpp b/dGame/dBehaviors/BehaviorContext.cpp index e4f3011c..5ca335b1 100644 --- a/dGame/dBehaviors/BehaviorContext.cpp +++ b/dGame/dBehaviors/BehaviorContext.cpp @@ -105,7 +105,7 @@ void BehaviorContext::ExecuteUpdates() { this->scheduledUpdates.clear(); } -void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream* bitStream) { +void BehaviorContext::SyncBehavior(const uint32_t syncId, RakNet::BitStream& bitStream) { BehaviorSyncEntry entry; auto found = false; @@ -243,27 +243,25 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) { echo.uiBehaviorHandle = entry.handle; echo.uiSkillHandle = this->skillUId; - auto* bitStream = new RakNet::BitStream(); + RakNet::BitStream bitStream{}; // Calculate sync entry.behavior->SyncCalculation(this, bitStream, entry.branchContext); if (!clientInitalized) { - echo.sBitStream.assign(reinterpret_cast(bitStream->GetData()), bitStream->GetNumberOfBytesUsed()); + echo.sBitStream.assign(reinterpret_cast(bitStream.GetData()), bitStream.GetNumberOfBytesUsed()); // Write message RakNet::BitStream message; BitStreamUtils::WriteHeader(message, eConnectionType::CLIENT, eClientMessageType::GAME_MSG); message.Write(this->originator); - echo.Serialize(&message); + echo.Serialize(message); - Game::server->Send(&message, UNASSIGNED_SYSTEM_ADDRESS, true); + Game::server->Send(message, UNASSIGNED_SYSTEM_ADDRESS, true); } ExecuteUpdates(); - - delete bitStream; } std::vector valid; diff --git a/dGame/dBehaviors/BehaviorContext.h b/dGame/dBehaviors/BehaviorContext.h index 333dc9a8..3e6c0b1d 100644 --- a/dGame/dBehaviors/BehaviorContext.h +++ b/dGame/dBehaviors/BehaviorContext.h @@ -93,7 +93,7 @@ struct BehaviorContext void ExecuteUpdates(); - void SyncBehavior(uint32_t syncId, RakNet::BitStream* bitStream); + void SyncBehavior(uint32_t syncId, RakNet::BitStream& bitStream); void Update(float deltaTime); diff --git a/dGame/dBehaviors/BlockBehavior.cpp b/dGame/dBehaviors/BlockBehavior.cpp index 88c6bb0b..0d3e164b 100644 --- a/dGame/dBehaviors/BlockBehavior.cpp +++ b/dGame/dBehaviors/BlockBehavior.cpp @@ -7,7 +7,7 @@ #include "Logger.h" #include "DestroyableComponent.h" -void BlockBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void BlockBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { const auto target = context->originator; auto* entity = Game::entityManager->GetEntity(target); @@ -33,7 +33,7 @@ void BlockBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea } } -void BlockBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void BlockBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } diff --git a/dGame/dBehaviors/BlockBehavior.h b/dGame/dBehaviors/BlockBehavior.h index e0d639ed..9f4d696d 100644 --- a/dGame/dBehaviors/BlockBehavior.h +++ b/dGame/dBehaviors/BlockBehavior.h @@ -13,9 +13,9 @@ public: explicit BlockBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/BuffBehavior.cpp b/dGame/dBehaviors/BuffBehavior.cpp index 7ac8b352..e20bf820 100644 --- a/dGame/dBehaviors/BuffBehavior.cpp +++ b/dGame/dBehaviors/BuffBehavior.cpp @@ -7,7 +7,7 @@ #include "Logger.h" #include "DestroyableComponent.h" -void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void BuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator; auto* entity = Game::entityManager->GetEntity(target); diff --git a/dGame/dBehaviors/BuffBehavior.h b/dGame/dBehaviors/BuffBehavior.h index b7c805b3..d057758a 100644 --- a/dGame/dBehaviors/BuffBehavior.h +++ b/dGame/dBehaviors/BuffBehavior.h @@ -16,7 +16,7 @@ public: explicit BuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/CMakeLists.txt b/dGame/dBehaviors/CMakeLists.txt index c8cb0be0..f00ba7e2 100644 --- a/dGame/dBehaviors/CMakeLists.txt +++ b/dGame/dBehaviors/CMakeLists.txt @@ -21,7 +21,6 @@ set(DGAME_DBEHAVIORS_SOURCES "AirMovementBehavior.cpp" "DamageReductionBehavior.cpp" "DarkInspirationBehavior.cpp" "DurationBehavior.cpp" - "EmptyBehavior.cpp" "EndBehavior.cpp" "FallSpeedBehavior.cpp" "ForceMovementBehavior.cpp" @@ -56,7 +55,15 @@ set(DGAME_DBEHAVIORS_SOURCES "AirMovementBehavior.cpp" "VentureVisionBehavior.cpp" "VerifyBehavior.cpp") -add_library(dBehaviors STATIC ${DGAME_DBEHAVIORS_SOURCES}) -target_link_libraries(dBehaviors PUBLIC dPhysics) -target_include_directories(dBehaviors PUBLIC ".") +add_library(dBehaviors OBJECT ${DGAME_DBEHAVIORS_SOURCES}) +target_link_libraries(dBehaviors PUBLIC dDatabaseCDClient dPhysics) +target_include_directories(dBehaviors PUBLIC "." + "${PROJECT_SOURCE_DIR}/dGame/dGameMessages" # via BehaviorContext.h + PRIVATE + "${PROJECT_SOURCE_DIR}/dGame/dComponents" # direct BuffComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dUtilities" # Preconditions.h via QuickBuildComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dEntity" # via dZoneManager.h, Spawner.h + "${PROJECT_SOURCE_DIR}/dGame/dInventory" # via CharacterComponent.h + "${PROJECT_SOURCE_DIR}/dZoneManager" # via BasicAttackBehavior.cpp +) target_precompile_headers(dBehaviors REUSE_FROM dGameBase) diff --git a/dGame/dBehaviors/CarBoostBehavior.cpp b/dGame/dBehaviors/CarBoostBehavior.cpp index eb22cb09..fdbcba71 100644 --- a/dGame/dBehaviors/CarBoostBehavior.cpp +++ b/dGame/dBehaviors/CarBoostBehavior.cpp @@ -8,7 +8,7 @@ #include "Logger.h" #include "PossessableComponent.h" -void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void CarBoostBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { GameMessages::SendVehicleAddPassiveBoostAction(branch.target, UNASSIGNED_SYSTEM_ADDRESS); auto* entity = Game::entityManager->GetEntity(context->originator); diff --git a/dGame/dBehaviors/CarBoostBehavior.h b/dGame/dBehaviors/CarBoostBehavior.h index 3f4265b9..5e629421 100644 --- a/dGame/dBehaviors/CarBoostBehavior.h +++ b/dGame/dBehaviors/CarBoostBehavior.h @@ -17,7 +17,7 @@ public: explicit CarBoostBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/ChainBehavior.cpp b/dGame/dBehaviors/ChainBehavior.cpp index 4a20c151..feb27988 100644 --- a/dGame/dBehaviors/ChainBehavior.cpp +++ b/dGame/dBehaviors/ChainBehavior.cpp @@ -3,11 +3,11 @@ #include "Game.h" #include "Logger.h" -void ChainBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void ChainBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { uint32_t chainIndex{}; - if (!bitStream->Read(chainIndex)) { - LOG("Unable to read chainIndex from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(chainIndex)) { + LOG("Unable to read chainIndex from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; } @@ -16,12 +16,12 @@ void ChainBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea if (chainIndex < this->m_behaviors.size()) { this->m_behaviors.at(chainIndex)->Handle(context, bitStream, branch); } else { - LOG("chainIndex out of bounds, aborting handle of chain %i bits unread %i", chainIndex, bitStream->GetNumberOfUnreadBits()); + LOG("chainIndex out of bounds, aborting handle of chain %i bits unread %i", chainIndex, bitStream.GetNumberOfUnreadBits()); } } -void ChainBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { - bitStream->Write(1); +void ChainBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { + bitStream.Write(1); this->m_behaviors.at(0)->Calculate(context, bitStream, branch); } diff --git a/dGame/dBehaviors/ChainBehavior.h b/dGame/dBehaviors/ChainBehavior.h index c31d5358..174326df 100644 --- a/dGame/dBehaviors/ChainBehavior.h +++ b/dGame/dBehaviors/ChainBehavior.h @@ -16,9 +16,9 @@ public: explicit ChainBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/ChangeIdleFlagsBehavior.cpp b/dGame/dBehaviors/ChangeIdleFlagsBehavior.cpp index 06a79fa7..b7c6b80a 100644 --- a/dGame/dBehaviors/ChangeIdleFlagsBehavior.cpp +++ b/dGame/dBehaviors/ChangeIdleFlagsBehavior.cpp @@ -3,7 +3,7 @@ #include "BehaviorContext.h" #include "BehaviorBranchContext.h" -void ChangeIdleFlagsBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ChangeIdleFlagsBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator; if (!target) return; @@ -16,7 +16,7 @@ void ChangeIdleFlagsBehavior::Handle(BehaviorContext* context, RakNet::BitStream } } -void ChangeIdleFlagsBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ChangeIdleFlagsBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } diff --git a/dGame/dBehaviors/ChangeIdleFlagsBehavior.h b/dGame/dBehaviors/ChangeIdleFlagsBehavior.h index 91f802f4..e40af3cc 100644 --- a/dGame/dBehaviors/ChangeIdleFlagsBehavior.h +++ b/dGame/dBehaviors/ChangeIdleFlagsBehavior.h @@ -11,8 +11,8 @@ public: */ explicit ChangeIdleFlagsBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void Load() override; diff --git a/dGame/dBehaviors/ChangeOrientationBehavior.cpp b/dGame/dBehaviors/ChangeOrientationBehavior.cpp index 445c76df..f8a34fb8 100644 --- a/dGame/dBehaviors/ChangeOrientationBehavior.cpp +++ b/dGame/dBehaviors/ChangeOrientationBehavior.cpp @@ -3,7 +3,7 @@ #include "BehaviorContext.h" #include "EntityManager.h" -void ChangeOrientationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ChangeOrientationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { Entity* sourceEntity; if (this->m_orientCaster) sourceEntity = Game::entityManager->GetEntity(context->originator); else sourceEntity = Game::entityManager->GetEntity(branch.target); diff --git a/dGame/dBehaviors/ChangeOrientationBehavior.h b/dGame/dBehaviors/ChangeOrientationBehavior.h index 22c92bb8..62c47d5c 100644 --- a/dGame/dBehaviors/ChangeOrientationBehavior.h +++ b/dGame/dBehaviors/ChangeOrientationBehavior.h @@ -5,7 +5,7 @@ class ChangeOrientationBehavior final : public Behavior { public: explicit ChangeOrientationBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; private: bool m_orientCaster; diff --git a/dGame/dBehaviors/ChargeUpBehavior.cpp b/dGame/dBehaviors/ChargeUpBehavior.cpp index cf737e19..dd6293db 100644 --- a/dGame/dBehaviors/ChargeUpBehavior.cpp +++ b/dGame/dBehaviors/ChargeUpBehavior.cpp @@ -4,10 +4,10 @@ #include "Game.h" #include "Logger.h" -void ChargeUpBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void ChargeUpBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { uint32_t handle{}; - if (!bitStream->Read(handle)) { + if (!bitStream.Read(handle)) { LOG("Unable to read handle from bitStream, aborting Handle! variable_type"); return; }; @@ -15,10 +15,10 @@ void ChargeUpBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt context->RegisterSyncBehavior(handle, this, branch, this->m_MaxDuration); } -void ChargeUpBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ChargeUpBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { } -void ChargeUpBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void ChargeUpBehavior::Sync(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { this->m_action->Handle(context, bitStream, branch); } diff --git a/dGame/dBehaviors/ChargeUpBehavior.h b/dGame/dBehaviors/ChargeUpBehavior.h index ceb40f6c..2ded1eb6 100644 --- a/dGame/dBehaviors/ChargeUpBehavior.h +++ b/dGame/dBehaviors/ChargeUpBehavior.h @@ -6,11 +6,11 @@ class ChargeUpBehavior final : public Behavior public: explicit ChargeUpBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; private: diff --git a/dGame/dBehaviors/ClearTargetBehavior.cpp b/dGame/dBehaviors/ClearTargetBehavior.cpp index ec0c0db6..40ae9b01 100644 --- a/dGame/dBehaviors/ClearTargetBehavior.cpp +++ b/dGame/dBehaviors/ClearTargetBehavior.cpp @@ -3,13 +3,13 @@ #include "BehaviorContext.h" -void ClearTargetBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ClearTargetBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { branch.target = LWOOBJID_EMPTY; this->m_action->Handle(context, bitStream, branch); } -void ClearTargetBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ClearTargetBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { branch.target = LWOOBJID_EMPTY; this->m_action->Calculate(context, bitStream, branch); diff --git a/dGame/dBehaviors/ClearTargetBehavior.h b/dGame/dBehaviors/ClearTargetBehavior.h index 0ed57fb4..d950c8f5 100644 --- a/dGame/dBehaviors/ClearTargetBehavior.h +++ b/dGame/dBehaviors/ClearTargetBehavior.h @@ -14,9 +14,9 @@ public: explicit ClearTargetBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/ConsumeItemBehavior.cpp b/dGame/dBehaviors/ConsumeItemBehavior.cpp index c3b76fcb..440a641b 100644 --- a/dGame/dBehaviors/ConsumeItemBehavior.cpp +++ b/dGame/dBehaviors/ConsumeItemBehavior.cpp @@ -3,7 +3,7 @@ #include "BehaviorBranchContext.h" #include "InventoryComponent.h" -void ConsumeItemBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ConsumeItemBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto action_to_cast = m_ActionNotConsumed; if (this->m_ConsumeLOT != -1) { auto caster = Game::entityManager->GetEntity(context->caster); @@ -19,7 +19,7 @@ void ConsumeItemBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi if(action_to_cast) action_to_cast->Handle(context, bitStream, branch); } -void ConsumeItemBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ConsumeItemBehavior::Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } diff --git a/dGame/dBehaviors/ConsumeItemBehavior.h b/dGame/dBehaviors/ConsumeItemBehavior.h index f3eeb330..c2fe357c 100644 --- a/dGame/dBehaviors/ConsumeItemBehavior.h +++ b/dGame/dBehaviors/ConsumeItemBehavior.h @@ -5,8 +5,8 @@ class ConsumeItemBehavior final : public Behavior { public: explicit ConsumeItemBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; + void Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; private: diff --git a/dGame/dBehaviors/DamageAbsorptionBehavior.cpp b/dGame/dBehaviors/DamageAbsorptionBehavior.cpp index 880550e3..f657c8fd 100644 --- a/dGame/dBehaviors/DamageAbsorptionBehavior.cpp +++ b/dGame/dBehaviors/DamageAbsorptionBehavior.cpp @@ -7,7 +7,7 @@ #include "Logger.h" #include "DestroyableComponent.h" -void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { auto* target = Game::entityManager->GetEntity(branch.target); if (target == nullptr) { @@ -29,7 +29,7 @@ void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStrea context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void DamageAbsorptionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void DamageAbsorptionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } diff --git a/dGame/dBehaviors/DamageAbsorptionBehavior.h b/dGame/dBehaviors/DamageAbsorptionBehavior.h index 1b865e87..6e26bda1 100644 --- a/dGame/dBehaviors/DamageAbsorptionBehavior.h +++ b/dGame/dBehaviors/DamageAbsorptionBehavior.h @@ -13,9 +13,9 @@ public: explicit DamageAbsorptionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; diff --git a/dGame/dBehaviors/DamageReductionBehavior.cpp b/dGame/dBehaviors/DamageReductionBehavior.cpp index bf32360e..62b70a52 100644 --- a/dGame/dBehaviors/DamageReductionBehavior.cpp +++ b/dGame/dBehaviors/DamageReductionBehavior.cpp @@ -7,7 +7,7 @@ #include "Logger.h" #include "DestroyableComponent.h" -void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { auto* target = Game::entityManager->GetEntity(branch.target); if (target == nullptr) { @@ -27,7 +27,7 @@ void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void DamageReductionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void DamageReductionBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } diff --git a/dGame/dBehaviors/DamageReductionBehavior.h b/dGame/dBehaviors/DamageReductionBehavior.h index bddd31fb..7a9aa4f5 100644 --- a/dGame/dBehaviors/DamageReductionBehavior.h +++ b/dGame/dBehaviors/DamageReductionBehavior.h @@ -13,9 +13,9 @@ public: explicit DamageReductionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; diff --git a/dGame/dBehaviors/DarkInspirationBehavior.cpp b/dGame/dBehaviors/DarkInspirationBehavior.cpp index 27a7c634..367f9d5a 100644 --- a/dGame/dBehaviors/DarkInspirationBehavior.cpp +++ b/dGame/dBehaviors/DarkInspirationBehavior.cpp @@ -6,7 +6,7 @@ #include "EntityManager.h" #include "BehaviorContext.h" -void DarkInspirationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void DarkInspirationBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { auto* target = Game::entityManager->GetEntity(branch.target); if (target == nullptr) { @@ -25,7 +25,7 @@ void DarkInspirationBehavior::Handle(BehaviorContext* context, RakNet::BitStream } } -void DarkInspirationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void DarkInspirationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* target = Game::entityManager->GetEntity(branch.target); if (target == nullptr) { diff --git a/dGame/dBehaviors/DarkInspirationBehavior.h b/dGame/dBehaviors/DarkInspirationBehavior.h index f8298742..5fe02c5e 100644 --- a/dGame/dBehaviors/DarkInspirationBehavior.h +++ b/dGame/dBehaviors/DarkInspirationBehavior.h @@ -11,9 +11,9 @@ public: explicit DarkInspirationBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; private: diff --git a/dGame/dBehaviors/DurationBehavior.cpp b/dGame/dBehaviors/DurationBehavior.cpp index c0bc5585..3544dc52 100644 --- a/dGame/dBehaviors/DurationBehavior.cpp +++ b/dGame/dBehaviors/DurationBehavior.cpp @@ -2,13 +2,13 @@ #include "BehaviorBranchContext.h" #include "BehaviorContext.h" -void DurationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void DurationBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { branch.duration = this->m_duration; this->m_action->Handle(context, bitStream, branch); } -void DurationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void DurationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { branch.duration = this->m_duration; this->m_action->Calculate(context, bitStream, branch); diff --git a/dGame/dBehaviors/DurationBehavior.h b/dGame/dBehaviors/DurationBehavior.h index 164754b1..5ea6abb9 100644 --- a/dGame/dBehaviors/DurationBehavior.h +++ b/dGame/dBehaviors/DurationBehavior.h @@ -11,9 +11,9 @@ public: explicit DurationBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; private: diff --git a/dGame/dBehaviors/EmptyBehavior.cpp b/dGame/dBehaviors/EmptyBehavior.cpp deleted file mode 100644 index 8828f5de..00000000 --- a/dGame/dBehaviors/EmptyBehavior.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#include "EmptyBehavior.h" - diff --git a/dGame/dBehaviors/EndBehavior.cpp b/dGame/dBehaviors/EndBehavior.cpp index c67f3215..804a31b7 100644 --- a/dGame/dBehaviors/EndBehavior.cpp +++ b/dGame/dBehaviors/EndBehavior.cpp @@ -3,11 +3,11 @@ #include "BehaviorContext.h" #include "BehaviorBranchContext.h" -void EndBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void EndBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { context->InvokeEnd(this->m_startBehavior); } -void EndBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void EndBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { context->InvokeEnd(this->m_startBehavior); } diff --git a/dGame/dBehaviors/EndBehavior.h b/dGame/dBehaviors/EndBehavior.h index e1c06068..26a6f2d5 100644 --- a/dGame/dBehaviors/EndBehavior.h +++ b/dGame/dBehaviors/EndBehavior.h @@ -13,9 +13,9 @@ public: explicit EndBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/FallSpeedBehavior.cpp b/dGame/dBehaviors/FallSpeedBehavior.cpp index dfbdec2a..9a376cec 100644 --- a/dGame/dBehaviors/FallSpeedBehavior.cpp +++ b/dGame/dBehaviors/FallSpeedBehavior.cpp @@ -5,7 +5,7 @@ #include "BehaviorBranchContext.h" -void FallSpeedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void FallSpeedBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { // make sure required parameter has non-default value if (m_PercentSlowed == 0.0f) return; auto* target = Game::entityManager->GetEntity(branch.target); @@ -23,7 +23,7 @@ void FallSpeedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS } } -void FallSpeedBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void FallSpeedBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } diff --git a/dGame/dBehaviors/FallSpeedBehavior.h b/dGame/dBehaviors/FallSpeedBehavior.h index 01f0143f..f53c17e2 100644 --- a/dGame/dBehaviors/FallSpeedBehavior.h +++ b/dGame/dBehaviors/FallSpeedBehavior.h @@ -6,8 +6,8 @@ class FallSpeedBehavior final : public Behavior public: explicit FallSpeedBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/ForceMovementBehavior.cpp b/dGame/dBehaviors/ForceMovementBehavior.cpp index 2ba3f2e1..83c6fabc 100644 --- a/dGame/dBehaviors/ForceMovementBehavior.cpp +++ b/dGame/dBehaviors/ForceMovementBehavior.cpp @@ -6,29 +6,29 @@ #include "Game.h" #include "Logger.h" -void ForceMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void ForceMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { if (this->m_hitAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitEnemyAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitFactionAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { return; } uint32_t handle{}; - if (!bitStream->Read(handle)) { - LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(handle)) { + LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; } context->RegisterSyncBehavior(handle, this, branch, this->m_Duration); } -void ForceMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ForceMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { uint32_t next{}; - if (!bitStream->Read(next)) { - LOG("Unable to read target from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(next)) { + LOG("Unable to read target from bitStream, aborting Sync! %i", bitStream.GetNumberOfUnreadBits()); return; } LWOOBJID target{}; - if (!bitStream->Read(target)) { - LOG("Unable to read target from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(target)) { + LOG("Unable to read target from bitStream, aborting Sync! %i", bitStream.GetNumberOfUnreadBits()); return; } @@ -37,7 +37,7 @@ void ForceMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bi behavior->Handle(context, bitStream, branch); } -void ForceMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ForceMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { if (this->m_hitAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitEnemyAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitFactionAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { return; } @@ -56,7 +56,7 @@ void ForceMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStrea } const auto skillHandle = context->GetUniqueSkillId(); - bitStream->Write(skillHandle); + bitStream.Write(skillHandle); context->SyncCalculation(skillHandle, this->m_Duration, this, branch); } @@ -71,7 +71,7 @@ void ForceMovementBehavior::Load() { this->m_Yaw = GetFloat("yaw"); } -void ForceMovementBehavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ForceMovementBehavior::SyncCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* casterEntity = Game::entityManager->GetEntity(context->caster); if (casterEntity != nullptr) { auto* controllablePhysicsComponent = casterEntity->GetComponent(); diff --git a/dGame/dBehaviors/ForceMovementBehavior.h b/dGame/dBehaviors/ForceMovementBehavior.h index 8d5fd9f4..ffcea0f4 100644 --- a/dGame/dBehaviors/ForceMovementBehavior.h +++ b/dGame/dBehaviors/ForceMovementBehavior.h @@ -22,13 +22,13 @@ public: explicit ForceMovementBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void SyncCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void SyncCalculation(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/HealBehavior.cpp b/dGame/dBehaviors/HealBehavior.cpp index 3eb4928c..e2553671 100644 --- a/dGame/dBehaviors/HealBehavior.cpp +++ b/dGame/dBehaviors/HealBehavior.cpp @@ -7,7 +7,7 @@ #include "eReplicaComponentType.h" -void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { +void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bit_stream, const BehaviorBranchContext branch) { auto* entity = Game::entityManager->GetEntity(branch.target); if (entity == nullptr) { @@ -28,7 +28,7 @@ void HealBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_strea } -void HealBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { +void HealBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, const BehaviorBranchContext branch) { Handle(context, bit_stream, branch); } diff --git a/dGame/dBehaviors/HealBehavior.h b/dGame/dBehaviors/HealBehavior.h index e967135a..9ce678a4 100644 --- a/dGame/dBehaviors/HealBehavior.h +++ b/dGame/dBehaviors/HealBehavior.h @@ -13,9 +13,9 @@ public: explicit HealBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/ImaginationBehavior.cpp b/dGame/dBehaviors/ImaginationBehavior.cpp index c57fd0c7..be426e44 100644 --- a/dGame/dBehaviors/ImaginationBehavior.cpp +++ b/dGame/dBehaviors/ImaginationBehavior.cpp @@ -6,7 +6,7 @@ #include "Logger.h" -void ImaginationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { +void ImaginationBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bit_stream, const BehaviorBranchContext branch) { auto* entity = Game::entityManager->GetEntity(branch.target); if (entity == nullptr) { @@ -23,7 +23,7 @@ void ImaginationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi } -void ImaginationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { +void ImaginationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, const BehaviorBranchContext branch) { Handle(context, bit_stream, branch); } diff --git a/dGame/dBehaviors/ImaginationBehavior.h b/dGame/dBehaviors/ImaginationBehavior.h index a35c2ddd..ccebccc2 100644 --- a/dGame/dBehaviors/ImaginationBehavior.h +++ b/dGame/dBehaviors/ImaginationBehavior.h @@ -13,9 +13,9 @@ public: explicit ImaginationBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/ImmunityBehavior.cpp b/dGame/dBehaviors/ImmunityBehavior.cpp index 9824c479..77d43834 100644 --- a/dGame/dBehaviors/ImmunityBehavior.cpp +++ b/dGame/dBehaviors/ImmunityBehavior.cpp @@ -9,7 +9,7 @@ #include "ControllablePhysicsComponent.h" #include "eStateChangeType.h" -void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { auto* target = Game::entityManager->GetEntity(branch.target); if (!target) { @@ -51,7 +51,7 @@ void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt context->RegisterTimerBehavior(this, branch, target->GetObjectID()); } -void ImmunityBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ImmunityBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } diff --git a/dGame/dBehaviors/ImmunityBehavior.h b/dGame/dBehaviors/ImmunityBehavior.h index 02cc0fae..d2f28b95 100644 --- a/dGame/dBehaviors/ImmunityBehavior.h +++ b/dGame/dBehaviors/ImmunityBehavior.h @@ -11,9 +11,9 @@ public: explicit ImmunityBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; diff --git a/dGame/dBehaviors/InterruptBehavior.cpp b/dGame/dBehaviors/InterruptBehavior.cpp index bd3f0c4a..0b23c34d 100644 --- a/dGame/dBehaviors/InterruptBehavior.cpp +++ b/dGame/dBehaviors/InterruptBehavior.cpp @@ -7,12 +7,12 @@ #include "SkillComponent.h" -void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { if (branch.target != context->originator) { bool unknown = false; - if (!bitStream->Read(unknown)) { - LOG("Unable to read unknown1 from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(unknown)) { + LOG("Unable to read unknown1 from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; @@ -22,8 +22,8 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS if (!this->m_interruptBlock) { bool unknown = false; - if (!bitStream->Read(unknown)) { - LOG("Unable to read unknown2 from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(unknown)) { + LOG("Unable to read unknown2 from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; @@ -34,8 +34,8 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS { bool unknown = false; - if (!bitStream->Read(unknown)) { - LOG("Unable to read unknown3 from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(unknown)) { + LOG("Unable to read unknown3 from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; } @@ -54,16 +54,16 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS } -void InterruptBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void InterruptBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { if (branch.target != context->originator) { - bitStream->Write(false); + bitStream.Write(false); } if (!this->m_interruptBlock) { - bitStream->Write(false); + bitStream.Write(false); } - bitStream->Write(false); + bitStream.Write(false); if (branch.target == context->originator) return; diff --git a/dGame/dBehaviors/InterruptBehavior.h b/dGame/dBehaviors/InterruptBehavior.h index 9ba272c7..440bc559 100644 --- a/dGame/dBehaviors/InterruptBehavior.h +++ b/dGame/dBehaviors/InterruptBehavior.h @@ -15,9 +15,9 @@ public: explicit InterruptBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/JetPackBehavior.cpp b/dGame/dBehaviors/JetPackBehavior.cpp index 7fcd78b0..8cfb87da 100644 --- a/dGame/dBehaviors/JetPackBehavior.cpp +++ b/dGame/dBehaviors/JetPackBehavior.cpp @@ -5,7 +5,7 @@ #include "Character.h" -void JetPackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { +void JetPackBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bit_stream, const BehaviorBranchContext branch) { auto* entity = Game::entityManager->GetEntity(branch.target); GameMessages::SendSetJetPackMode(entity, true, this->m_BypassChecks, this->m_EnableHover, this->m_effectId, this->m_Airspeed, this->m_MaxAirspeed, this->m_VerticalVelocity, this->m_WarningEffectID); @@ -33,7 +33,7 @@ void JetPackBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext bra } } -void JetPackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { +void JetPackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, const BehaviorBranchContext branch) { Handle(context, bit_stream, branch); } diff --git a/dGame/dBehaviors/JetPackBehavior.h b/dGame/dBehaviors/JetPackBehavior.h index 0cc6c399..bc82d5d2 100644 --- a/dGame/dBehaviors/JetPackBehavior.h +++ b/dGame/dBehaviors/JetPackBehavior.h @@ -18,11 +18,11 @@ public: explicit JetPackBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/KnockbackBehavior.cpp b/dGame/dBehaviors/KnockbackBehavior.cpp index d0f86597..4d7bf2ea 100644 --- a/dGame/dBehaviors/KnockbackBehavior.cpp +++ b/dGame/dBehaviors/KnockbackBehavior.cpp @@ -9,16 +9,16 @@ #include "Game.h" #include "Logger.h" -void KnockbackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void KnockbackBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { bool unknown{}; - if (!bitStream->Read(unknown)) { - LOG("Unable to read unknown from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(unknown)) { + LOG("Unable to read unknown from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; } -void KnockbackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void KnockbackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { bool blocked = false; auto* target = Game::entityManager->GetEntity(branch.target); @@ -31,7 +31,7 @@ void KnockbackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* b } } - bitStream->Write(blocked); + bitStream.Write(blocked); } void KnockbackBehavior::Load() { diff --git a/dGame/dBehaviors/KnockbackBehavior.h b/dGame/dBehaviors/KnockbackBehavior.h index c952bb41..89777a6d 100644 --- a/dGame/dBehaviors/KnockbackBehavior.h +++ b/dGame/dBehaviors/KnockbackBehavior.h @@ -17,9 +17,9 @@ public: explicit KnockbackBehavior(const uint32_t behaviorID) : Behavior(behaviorID) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/LootBuffBehavior.cpp b/dGame/dBehaviors/LootBuffBehavior.cpp index c7a6b36a..65b73422 100644 --- a/dGame/dBehaviors/LootBuffBehavior.cpp +++ b/dGame/dBehaviors/LootBuffBehavior.cpp @@ -1,6 +1,6 @@ #include "LootBuffBehavior.h" -void LootBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void LootBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto target = Game::entityManager->GetEntity(context->caster); if (!target) return; @@ -14,7 +14,7 @@ void LootBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt } -void LootBuffBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void LootBuffBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } diff --git a/dGame/dBehaviors/LootBuffBehavior.h b/dGame/dBehaviors/LootBuffBehavior.h index b6f700ca..dba82d75 100644 --- a/dGame/dBehaviors/LootBuffBehavior.h +++ b/dGame/dBehaviors/LootBuffBehavior.h @@ -20,9 +20,9 @@ public: explicit LootBuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/MovementSwitchBehavior.cpp b/dGame/dBehaviors/MovementSwitchBehavior.cpp index cddeeea9..cc2d7b34 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.cpp +++ b/dGame/dBehaviors/MovementSwitchBehavior.cpp @@ -3,9 +3,9 @@ #include "Game.h" #include "Logger.h" -void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { uint32_t movementType{}; - if (!bitStream->Read(movementType)) { + if (!bitStream.Read(movementType)) { if (this->m_groundAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_jumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_fallingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && @@ -15,7 +15,7 @@ void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* this->m_movingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { return; } - LOG("Unable to read movementType from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + LOG("Unable to read movementType from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; diff --git a/dGame/dBehaviors/MovementSwitchBehavior.h b/dGame/dBehaviors/MovementSwitchBehavior.h index e6ff96f6..75b13b54 100644 --- a/dGame/dBehaviors/MovementSwitchBehavior.h +++ b/dGame/dBehaviors/MovementSwitchBehavior.h @@ -36,7 +36,7 @@ public: explicit MovementSwitchBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/NpcCombatSkillBehavior.cpp b/dGame/dBehaviors/NpcCombatSkillBehavior.cpp index 5a8d03cf..69a6ea9d 100644 --- a/dGame/dBehaviors/NpcCombatSkillBehavior.cpp +++ b/dGame/dBehaviors/NpcCombatSkillBehavior.cpp @@ -3,7 +3,7 @@ #include "BehaviorContext.h" -void NpcCombatSkillBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { +void NpcCombatSkillBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) { context->skillTime = this->m_npcSkillTime; for (auto* behavior : this->m_behaviors) { diff --git a/dGame/dBehaviors/NpcCombatSkillBehavior.h b/dGame/dBehaviors/NpcCombatSkillBehavior.h index 19ff3483..07826f48 100644 --- a/dGame/dBehaviors/NpcCombatSkillBehavior.h +++ b/dGame/dBehaviors/NpcCombatSkillBehavior.h @@ -15,7 +15,7 @@ public: explicit NpcCombatSkillBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - void Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/OverTimeBehavior.cpp b/dGame/dBehaviors/OverTimeBehavior.cpp index bdef2eb6..5a42993f 100644 --- a/dGame/dBehaviors/OverTimeBehavior.cpp +++ b/dGame/dBehaviors/OverTimeBehavior.cpp @@ -11,7 +11,7 @@ #include "CDSkillBehaviorTable.h" -void OverTimeBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void OverTimeBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { const auto originator = context->originator; auto* entity = Game::entityManager->GetEntity(originator); @@ -33,7 +33,7 @@ void OverTimeBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt } } -void OverTimeBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void OverTimeBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { } @@ -41,7 +41,7 @@ void OverTimeBehavior::Load() { m_Action = GetInt("action"); // Since m_Action is a skillID and not a behavior, get is correlated behaviorID. - CDSkillBehaviorTable* skillTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillTable = CDClientManager::GetTable(); m_ActionBehaviorId = skillTable->GetSkillByID(m_Action).behaviorID; m_Delay = GetFloat("delay"); diff --git a/dGame/dBehaviors/OverTimeBehavior.h b/dGame/dBehaviors/OverTimeBehavior.h index 73a07865..78d9388b 100644 --- a/dGame/dBehaviors/OverTimeBehavior.h +++ b/dGame/dBehaviors/OverTimeBehavior.h @@ -16,9 +16,9 @@ public: explicit OverTimeBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/PlayEffectBehavior.cpp b/dGame/dBehaviors/PlayEffectBehavior.cpp index acd606a9..451c52de 100644 --- a/dGame/dBehaviors/PlayEffectBehavior.cpp +++ b/dGame/dBehaviors/PlayEffectBehavior.cpp @@ -3,7 +3,7 @@ #include "BehaviorContext.h" #include "BehaviorBranchContext.h" -void PlayEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void PlayEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { // On managed behaviors this is handled by the client if (!context->unmanaged) return; @@ -13,7 +13,7 @@ void PlayEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit PlayFx(u"", target); } -void PlayEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void PlayEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { const auto& target = branch.target == LWOOBJID_EMPTY ? context->originator : branch.target; //PlayFx(u"", target); diff --git a/dGame/dBehaviors/PlayEffectBehavior.h b/dGame/dBehaviors/PlayEffectBehavior.h index 5ef49161..c112579b 100644 --- a/dGame/dBehaviors/PlayEffectBehavior.h +++ b/dGame/dBehaviors/PlayEffectBehavior.h @@ -10,9 +10,9 @@ public: explicit PlayEffectBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.cpp b/dGame/dBehaviors/ProjectileAttackBehavior.cpp index 732ff186..3e5118f7 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.cpp +++ b/dGame/dBehaviors/ProjectileAttackBehavior.cpp @@ -8,11 +8,11 @@ #include "ObjectIDManager.h" #include "eObjectBits.h" -void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { LWOOBJID target{}; - if (!bitStream->Read(target)) { - LOG("Unable to read target from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(target)) { + LOG("Unable to read target from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; @@ -33,9 +33,9 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea } if (m_useMouseposit && !branch.isSync) { - NiPoint3 targetPosition = NiPoint3::ZERO; - if (!bitStream->Read(targetPosition)) { - LOG("Unable to read targetPosition from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + NiPoint3 targetPosition = NiPoint3Constant::ZERO; + if (!bitStream.Read(targetPosition)) { + LOG("Unable to read targetPosition from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; } @@ -45,8 +45,8 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea for (auto i = 0u; i < this->m_projectileCount; ++i) { LWOOBJID projectileId{}; - if (!bitStream->Read(projectileId)) { - LOG("Unable to read projectileId from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(projectileId)) { + LOG("Unable to read projectileId from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; @@ -58,8 +58,8 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea } } -void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { - bitStream->Write(branch.target); +void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { + bitStream.Write(branch.target); auto* entity = Game::entityManager->GetEntity(context->originator); @@ -110,7 +110,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt GeneralUtils::SetBit(id, eObjectBits::SPAWNED); - bitStream->Write(id); + bitStream.Write(id); auto eulerAngles = rotation.GetEulerAngles(); diff --git a/dGame/dBehaviors/ProjectileAttackBehavior.h b/dGame/dBehaviors/ProjectileAttackBehavior.h index b307e66c..fee3a5c2 100644 --- a/dGame/dBehaviors/ProjectileAttackBehavior.h +++ b/dGame/dBehaviors/ProjectileAttackBehavior.h @@ -32,9 +32,9 @@ public: explicit ProjectileAttackBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/PropertyTeleportBehavior.cpp b/dGame/dBehaviors/PropertyTeleportBehavior.cpp index 939568f6..7e9ecee0 100644 --- a/dGame/dBehaviors/PropertyTeleportBehavior.cpp +++ b/dGame/dBehaviors/PropertyTeleportBehavior.cpp @@ -11,7 +11,7 @@ #include "ZoneInstanceManager.h" #include "dZoneManager.h" -void PropertyTeleportBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void PropertyTeleportBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* caster = Game::entityManager->GetEntity(context->caster); if (!caster) return; diff --git a/dGame/dBehaviors/PropertyTeleportBehavior.h b/dGame/dBehaviors/PropertyTeleportBehavior.h index 74eed03b..7dbec84c 100644 --- a/dGame/dBehaviors/PropertyTeleportBehavior.h +++ b/dGame/dBehaviors/PropertyTeleportBehavior.h @@ -11,7 +11,7 @@ public: explicit PropertyTeleportBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/PullToPointBehavior.cpp b/dGame/dBehaviors/PullToPointBehavior.cpp index e18443f7..f776298f 100644 --- a/dGame/dBehaviors/PullToPointBehavior.cpp +++ b/dGame/dBehaviors/PullToPointBehavior.cpp @@ -5,7 +5,7 @@ #include "EntityManager.h" #include "MovementAIComponent.h" -void PullToPointBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void PullToPointBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* entity = Game::entityManager->GetEntity(context->originator); auto* target = Game::entityManager->GetEntity(branch.target); @@ -25,7 +25,7 @@ void PullToPointBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi movement->PullToPoint(position); } -void PullToPointBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void PullToPointBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } diff --git a/dGame/dBehaviors/PullToPointBehavior.h b/dGame/dBehaviors/PullToPointBehavior.h index d448ad8d..83c8a944 100644 --- a/dGame/dBehaviors/PullToPointBehavior.h +++ b/dGame/dBehaviors/PullToPointBehavior.h @@ -12,9 +12,9 @@ public: explicit PullToPointBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/RemoveBuffBehavior.cpp b/dGame/dBehaviors/RemoveBuffBehavior.cpp index c6d2c9c9..ec2c15d4 100644 --- a/dGame/dBehaviors/RemoveBuffBehavior.cpp +++ b/dGame/dBehaviors/RemoveBuffBehavior.cpp @@ -5,7 +5,7 @@ #include "EntityManager.h" #include "BuffComponent.h" -void RemoveBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void RemoveBuffBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* entity = Game::entityManager->GetEntity(context->caster); if (!entity) return; diff --git a/dGame/dBehaviors/RemoveBuffBehavior.h b/dGame/dBehaviors/RemoveBuffBehavior.h index f2d8547b..5e08ea7f 100644 --- a/dGame/dBehaviors/RemoveBuffBehavior.h +++ b/dGame/dBehaviors/RemoveBuffBehavior.h @@ -12,7 +12,7 @@ public: explicit RemoveBuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; diff --git a/dGame/dBehaviors/RepairBehavior.cpp b/dGame/dBehaviors/RepairBehavior.cpp index d0ce3fe8..95b8ed89 100644 --- a/dGame/dBehaviors/RepairBehavior.cpp +++ b/dGame/dBehaviors/RepairBehavior.cpp @@ -7,7 +7,7 @@ #include "Game.h" #include "eReplicaComponentType.h" -void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { +void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bit_stream, const BehaviorBranchContext branch) { auto* entity = Game::entityManager->GetEntity(branch.target); if (entity == nullptr) { @@ -27,7 +27,7 @@ void RepairBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_str destroyable->Repair(this->m_armor); } -void RepairBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, const BehaviorBranchContext branch) { +void RepairBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, const BehaviorBranchContext branch) { Handle(context, bit_stream, branch); } diff --git a/dGame/dBehaviors/RepairBehavior.h b/dGame/dBehaviors/RepairBehavior.h index 8d2f14e4..61b96543 100644 --- a/dGame/dBehaviors/RepairBehavior.h +++ b/dGame/dBehaviors/RepairBehavior.h @@ -13,9 +13,9 @@ public: explicit RepairBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/SkillCastFailedBehavior.cpp b/dGame/dBehaviors/SkillCastFailedBehavior.cpp index a663e709..a9babe61 100644 --- a/dGame/dBehaviors/SkillCastFailedBehavior.cpp +++ b/dGame/dBehaviors/SkillCastFailedBehavior.cpp @@ -3,11 +3,11 @@ #include "BehaviorContext.h" #include "BehaviorBranchContext.h" -void SkillCastFailedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void SkillCastFailedBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { context->failed = true; } -void SkillCastFailedBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void SkillCastFailedBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { context->failed = true; } diff --git a/dGame/dBehaviors/SkillCastFailedBehavior.h b/dGame/dBehaviors/SkillCastFailedBehavior.h index 5359cb42..5ccb12b2 100644 --- a/dGame/dBehaviors/SkillCastFailedBehavior.h +++ b/dGame/dBehaviors/SkillCastFailedBehavior.h @@ -11,9 +11,9 @@ public: explicit SkillCastFailedBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/SkillEventBehavior.cpp b/dGame/dBehaviors/SkillEventBehavior.cpp index 4205c28b..2de801a2 100644 --- a/dGame/dBehaviors/SkillEventBehavior.cpp +++ b/dGame/dBehaviors/SkillEventBehavior.cpp @@ -3,26 +3,23 @@ #include "BehaviorContext.h" #include "EntityManager.h" #include "CppScripts.h" +#include "Entity.h" -void SkillEventBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void SkillEventBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* target = Game::entityManager->GetEntity(branch.target); auto* caster = Game::entityManager->GetEntity(context->originator); if (caster != nullptr && target != nullptr && this->m_effectHandle != nullptr && !this->m_effectHandle->empty()) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(target)) { - script->OnSkillEventFired(target, caster, *this->m_effectHandle); - } + target->GetScript()->OnSkillEventFired(target, caster, *this->m_effectHandle); } } void -SkillEventBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +SkillEventBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* target = Game::entityManager->GetEntity(branch.target); auto* caster = Game::entityManager->GetEntity(context->originator); if (caster != nullptr && target != nullptr && this->m_effectHandle != nullptr && !this->m_effectHandle->empty()) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(target)) { - script->OnSkillEventFired(target, caster, *this->m_effectHandle); - } + target->GetScript()->OnSkillEventFired(target, caster, *this->m_effectHandle); } } diff --git a/dGame/dBehaviors/SkillEventBehavior.h b/dGame/dBehaviors/SkillEventBehavior.h index 540f6d4a..6a334d90 100644 --- a/dGame/dBehaviors/SkillEventBehavior.h +++ b/dGame/dBehaviors/SkillEventBehavior.h @@ -9,7 +9,7 @@ public: explicit SkillEventBehavior(const uint32_t behaviorID) : Behavior(behaviorID) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; }; diff --git a/dGame/dBehaviors/SpawnBehavior.cpp b/dGame/dBehaviors/SpawnBehavior.cpp index dd45fb1b..e033d368 100644 --- a/dGame/dBehaviors/SpawnBehavior.cpp +++ b/dGame/dBehaviors/SpawnBehavior.cpp @@ -11,7 +11,7 @@ #include "EntityInfo.h" #include "eReplicaComponentType.h" -void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* origin = Game::entityManager->GetEntity(context->originator); if (origin == nullptr) { @@ -74,7 +74,7 @@ void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea }); } -void SpawnBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void SpawnBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } diff --git a/dGame/dBehaviors/SpawnBehavior.h b/dGame/dBehaviors/SpawnBehavior.h index 875e0a2b..fad57604 100644 --- a/dGame/dBehaviors/SpawnBehavior.h +++ b/dGame/dBehaviors/SpawnBehavior.h @@ -13,9 +13,9 @@ public: explicit SpawnBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; diff --git a/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp b/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp index 514ae27a..a76ce980 100644 --- a/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp +++ b/dGame/dBehaviors/SpawnQuickbuildBehavior.cpp @@ -3,7 +3,7 @@ #include "BehaviorBranchContext.h" #include "BehaviorContext.h" -void SpawnQuickbuildBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void SpawnQuickbuildBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { } void SpawnQuickbuildBehavior::Load() { diff --git a/dGame/dBehaviors/SpawnQuickbuildBehavior.h b/dGame/dBehaviors/SpawnQuickbuildBehavior.h index 653c60e8..a5700cc5 100644 --- a/dGame/dBehaviors/SpawnQuickbuildBehavior.h +++ b/dGame/dBehaviors/SpawnQuickbuildBehavior.h @@ -11,7 +11,7 @@ public: explicit SpawnQuickbuildBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/SpeedBehavior.cpp b/dGame/dBehaviors/SpeedBehavior.cpp index f21fda7e..c9c99bed 100644 --- a/dGame/dBehaviors/SpeedBehavior.cpp +++ b/dGame/dBehaviors/SpeedBehavior.cpp @@ -6,7 +6,7 @@ #include "Logger.h" -void SpeedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void SpeedBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { if (m_AffectsCaster) branch.target = context->caster; auto* target = Game::entityManager->GetEntity(branch.target); @@ -25,7 +25,7 @@ void SpeedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea } } -void SpeedBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void SpeedBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { Handle(context, bitStream, branch); } diff --git a/dGame/dBehaviors/SpeedBehavior.h b/dGame/dBehaviors/SpeedBehavior.h index 88b85820..f122fde7 100644 --- a/dGame/dBehaviors/SpeedBehavior.h +++ b/dGame/dBehaviors/SpeedBehavior.h @@ -11,9 +11,9 @@ public: explicit SpeedBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/StartBehavior.cpp b/dGame/dBehaviors/StartBehavior.cpp index 2bcaf325..cb23e31f 100644 --- a/dGame/dBehaviors/StartBehavior.cpp +++ b/dGame/dBehaviors/StartBehavior.cpp @@ -1,13 +1,13 @@ #include "StartBehavior.h" #include "BehaviorBranchContext.h" -void StartBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { +void StartBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) { branch.start = this->m_behaviorId; this->m_action->Handle(context, bit_stream, branch); } -void StartBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { +void StartBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) { branch.start = this->m_behaviorId; this->m_action->Calculate(context, bit_stream, branch); diff --git a/dGame/dBehaviors/StartBehavior.h b/dGame/dBehaviors/StartBehavior.h index 384fe64a..7d708d0a 100644 --- a/dGame/dBehaviors/StartBehavior.h +++ b/dGame/dBehaviors/StartBehavior.h @@ -13,9 +13,9 @@ public: explicit StartBehavior(const uint32_t behaviorID) : Behavior(behaviorID) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/StunBehavior.cpp b/dGame/dBehaviors/StunBehavior.cpp index 02144f69..bec6f409 100644 --- a/dGame/dBehaviors/StunBehavior.cpp +++ b/dGame/dBehaviors/StunBehavior.cpp @@ -10,14 +10,14 @@ #include "eReplicaComponentType.h" -void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { if (this->m_stunCaster || branch.target == context->originator) { return; } bool blocked{}; - if (!bitStream->Read(blocked)) { - LOG("Unable to read blocked from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(blocked)) { + LOG("Unable to read blocked from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; @@ -42,7 +42,7 @@ void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream combatAiComponent->Stun(branch.duration); } -void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { if (this->m_stunCaster || branch.target == context->originator) { auto* self = Game::entityManager->GetEntity(context->originator); @@ -79,7 +79,7 @@ void StunBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStr } } - bitStream->Write(blocked); + bitStream.Write(blocked); if (target == nullptr) { LOG("Failed to find target (%llu)!", branch.target); diff --git a/dGame/dBehaviors/StunBehavior.h b/dGame/dBehaviors/StunBehavior.h index f4851b47..18ca31f4 100644 --- a/dGame/dBehaviors/StunBehavior.h +++ b/dGame/dBehaviors/StunBehavior.h @@ -12,9 +12,9 @@ public: explicit StunBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/SwitchBehavior.cpp b/dGame/dBehaviors/SwitchBehavior.cpp index db04650d..88f2d85a 100644 --- a/dGame/dBehaviors/SwitchBehavior.cpp +++ b/dGame/dBehaviors/SwitchBehavior.cpp @@ -6,12 +6,12 @@ #include "BehaviorContext.h" #include "BuffComponent.h" -void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { +void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) { auto state = true; if (this->m_imagination > 0 || !this->m_isEnemyFaction) { - if (!bitStream->Read(state)) { - LOG("Unable to read state from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(state)) { + LOG("Unable to read state from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; } @@ -37,7 +37,7 @@ void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre } } -void SwitchBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void SwitchBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto state = true; if (this->m_imagination > 0 || !this->m_isEnemyFaction) { @@ -53,7 +53,7 @@ void SwitchBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS } } - bitStream->Write(state); + bitStream.Write(state); } if (state) { diff --git a/dGame/dBehaviors/SwitchBehavior.h b/dGame/dBehaviors/SwitchBehavior.h index 5e40d659..b7fcb653 100644 --- a/dGame/dBehaviors/SwitchBehavior.h +++ b/dGame/dBehaviors/SwitchBehavior.h @@ -21,9 +21,9 @@ public: explicit SwitchBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/SwitchMultipleBehavior.cpp b/dGame/dBehaviors/SwitchMultipleBehavior.cpp index faaa0d23..92c9a8de 100644 --- a/dGame/dBehaviors/SwitchMultipleBehavior.cpp +++ b/dGame/dBehaviors/SwitchMultipleBehavior.cpp @@ -9,11 +9,11 @@ #include "EntityManager.h" -void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { float value{}; - if (!bitStream->Read(value)) { - LOG("Unable to read value from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(value)) { + LOG("Unable to read value from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; @@ -32,7 +32,7 @@ void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* behavior->Handle(context, bitStream, branch); } -void SwitchMultipleBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void SwitchMultipleBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { // TODO } diff --git a/dGame/dBehaviors/SwitchMultipleBehavior.h b/dGame/dBehaviors/SwitchMultipleBehavior.h index 1e3dfe64..9f9754b8 100644 --- a/dGame/dBehaviors/SwitchMultipleBehavior.h +++ b/dGame/dBehaviors/SwitchMultipleBehavior.h @@ -15,9 +15,9 @@ public: explicit SwitchMultipleBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/TacArcBehavior.cpp b/dGame/dBehaviors/TacArcBehavior.cpp index 0cea8213..cb3430c8 100644 --- a/dGame/dBehaviors/TacArcBehavior.cpp +++ b/dGame/dBehaviors/TacArcBehavior.cpp @@ -11,7 +11,7 @@ #include -void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { std::vector targets = {}; if (this->m_usePickedTarget && branch.target != LWOOBJID_EMPTY) { @@ -28,16 +28,16 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre } bool hasTargets = false; - if (!bitStream->Read(hasTargets)) { - LOG("Unable to read hasTargets from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(hasTargets)) { + LOG("Unable to read hasTargets from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; if (this->m_checkEnv) { bool blocked = false; - if (!bitStream->Read(blocked)) { - LOG("Unable to read blocked from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(blocked)) { + LOG("Unable to read blocked from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; @@ -49,8 +49,8 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre if (hasTargets) { uint32_t count = 0; - if (!bitStream->Read(count)) { - LOG("Unable to read count from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(count)) { + LOG("Unable to read count from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; @@ -62,8 +62,8 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre for (auto i = 0u; i < count; i++) { LWOOBJID id{}; - if (!bitStream->Read(id)) { - LOG("Unable to read id from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); + if (!bitStream.Read(id)) { + LOG("Unable to read id from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits()); return; }; @@ -82,7 +82,7 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre } else this->m_missAction->Handle(context, bitStream, branch); } -void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* self = Game::entityManager->GetEntity(context->originator); if (self == nullptr) { LOG("Invalid self for (%llu)!", context->originator); @@ -155,11 +155,11 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS }); const auto hit = !targets.empty(); - bitStream->Write(hit); + bitStream.Write(hit); if (this->m_checkEnv) { const auto blocked = false; // TODO - bitStream->Write(blocked); + bitStream.Write(blocked); } if (hit) { @@ -168,9 +168,9 @@ void TacArcBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS context->foundTarget = true; // We want to continue with this behavior const auto count = static_cast(targets.size()); - bitStream->Write(count); + bitStream.Write(count); for (auto* target : targets) { - bitStream->Write(target->GetObjectID()); + bitStream.Write(target->GetObjectID()); } for (auto* target : targets) { diff --git a/dGame/dBehaviors/TacArcBehavior.h b/dGame/dBehaviors/TacArcBehavior.h index d9345272..b331e6fc 100644 --- a/dGame/dBehaviors/TacArcBehavior.h +++ b/dGame/dBehaviors/TacArcBehavior.h @@ -7,8 +7,8 @@ class TacArcBehavior final : public Behavior { public: explicit TacArcBehavior(const uint32_t behavior_id) : Behavior(behavior_id) {} - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; private: float m_maxRange; diff --git a/dGame/dBehaviors/TargetCasterBehavior.cpp b/dGame/dBehaviors/TargetCasterBehavior.cpp index ff9cfc03..1e2f82f0 100644 --- a/dGame/dBehaviors/TargetCasterBehavior.cpp +++ b/dGame/dBehaviors/TargetCasterBehavior.cpp @@ -3,7 +3,7 @@ #include "BehaviorContext.h" -void TargetCasterBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { +void TargetCasterBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) { branch.target = context->caster; this->m_action->Handle(context, bit_stream, branch); @@ -13,7 +13,7 @@ void TargetCasterBehavior::UnCast(BehaviorContext* context, BehaviorBranchContex this->m_action->UnCast(context, branch); } -void TargetCasterBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { +void TargetCasterBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) { branch.target = context->caster; this->m_action->Calculate(context, bit_stream, branch); diff --git a/dGame/dBehaviors/TargetCasterBehavior.h b/dGame/dBehaviors/TargetCasterBehavior.h index 387d2732..2713a1ce 100644 --- a/dGame/dBehaviors/TargetCasterBehavior.h +++ b/dGame/dBehaviors/TargetCasterBehavior.h @@ -13,11 +13,11 @@ public: explicit TargetCasterBehavior(const uint32_t behavior_id) : Behavior(behavior_id) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bit_stream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/TauntBehavior.cpp b/dGame/dBehaviors/TauntBehavior.cpp index 2e9f2168..43117ee3 100644 --- a/dGame/dBehaviors/TauntBehavior.cpp +++ b/dGame/dBehaviors/TauntBehavior.cpp @@ -6,7 +6,7 @@ #include "Logger.h" -void TauntBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void TauntBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* target = Game::entityManager->GetEntity(branch.target); if (target == nullptr) { @@ -22,7 +22,7 @@ void TauntBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea } } -void TauntBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void TauntBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* target = Game::entityManager->GetEntity(branch.target); if (target == nullptr) { diff --git a/dGame/dBehaviors/TauntBehavior.h b/dGame/dBehaviors/TauntBehavior.h index 3ae7db9d..b5b3196e 100644 --- a/dGame/dBehaviors/TauntBehavior.h +++ b/dGame/dBehaviors/TauntBehavior.h @@ -14,9 +14,9 @@ public: explicit TauntBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dBehaviors/VentureVisionBehavior.cpp b/dGame/dBehaviors/VentureVisionBehavior.cpp index 397bdebf..3aa3aac7 100644 --- a/dGame/dBehaviors/VentureVisionBehavior.cpp +++ b/dGame/dBehaviors/VentureVisionBehavior.cpp @@ -3,7 +3,7 @@ #include "CharacterComponent.h" #include "BehaviorContext.h" -void VentureVisionBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void VentureVisionBehavior::Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { const auto targetEntity = Game::entityManager->GetEntity(branch.target); diff --git a/dGame/dBehaviors/VentureVisionBehavior.h b/dGame/dBehaviors/VentureVisionBehavior.h index 72758949..ee89dae9 100644 --- a/dGame/dBehaviors/VentureVisionBehavior.h +++ b/dGame/dBehaviors/VentureVisionBehavior.h @@ -28,7 +28,7 @@ public: explicit VentureVisionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Handle(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override; diff --git a/dGame/dBehaviors/VerifyBehavior.cpp b/dGame/dBehaviors/VerifyBehavior.cpp index 2056f146..c7ede52f 100644 --- a/dGame/dBehaviors/VerifyBehavior.cpp +++ b/dGame/dBehaviors/VerifyBehavior.cpp @@ -7,7 +7,7 @@ #include "Logger.h" -void VerifyBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { +void VerifyBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) { auto* entity = Game::entityManager->GetEntity(branch.target); auto success = true; @@ -33,12 +33,12 @@ void VerifyBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitS } if (branch.target != LWOOBJID_EMPTY && branch.target != context->originator) { - bitStream->Write(success); + bitStream.Write(success); if (success) { - bitStream->Write(1); - bitStream->Write0(); - bitStream->Write0(); + bitStream.Write(1); + bitStream.Write0(); + bitStream.Write0(); } } diff --git a/dGame/dBehaviors/VerifyBehavior.h b/dGame/dBehaviors/VerifyBehavior.h index a91ff7cf..ed32111d 100644 --- a/dGame/dBehaviors/VerifyBehavior.h +++ b/dGame/dBehaviors/VerifyBehavior.h @@ -19,7 +19,7 @@ public: explicit VerifyBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { } - void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; + void Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override; void Load() override; }; diff --git a/dGame/dComponents/AchievementVendorComponent.cpp b/dGame/dComponents/AchievementVendorComponent.cpp new file mode 100644 index 00000000..006a2b6f --- /dev/null +++ b/dGame/dComponents/AchievementVendorComponent.cpp @@ -0,0 +1,81 @@ +#include "AchievementVendorComponent.h" +#include "MissionComponent.h" +#include "InventoryComponent.h" +#include "eMissionState.h" +#include "CDComponentsRegistryTable.h" +#include "CDItemComponentTable.h" +#include "eVendorTransactionResult.h" +#include "CheatDetection.h" +#include "UserManager.h" +#include "CDMissionsTable.h" + +AchievementVendorComponent::AchievementVendorComponent(Entity* parent) : VendorComponent(parent) { + RefreshInventory(true); +}; + +bool AchievementVendorComponent::SellsItem(Entity* buyer, const LOT lot) { + auto* missionComponent = buyer->GetComponent(); + if (!missionComponent) return false; + + if (m_PlayerPurchasableItems[buyer->GetObjectID()].contains(lot)) { + return true; + } + + CDMissionsTable* missionsTable = CDClientManager::GetTable(); + const auto missions = missionsTable->GetMissionsForReward(lot); + for (const auto mission : missions) { + if (missionComponent->GetMissionState(mission) == eMissionState::COMPLETE) { + m_PlayerPurchasableItems[buyer->GetObjectID()].insert(lot); + return true; + } + } + return false; +} + +void AchievementVendorComponent::Buy(Entity* buyer, LOT lot, uint32_t count) { + // get the item Comp from the item LOT + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + int itemCompID = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::ITEM); + CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); + uint32_t costLOT = itemComp.commendationLOT; + + if (costLOT == -1 || !SellsItem(buyer, lot)) { + auto* user = UserManager::Instance()->GetUser(buyer->GetSystemAddress()); + CheatDetection::ReportCheat(user, buyer->GetSystemAddress(), "Attempted to buy item %i from achievement vendor %i that is not purchasable", lot, m_Parent->GetLOT()); + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + + auto* inventoryComponent = buyer->GetComponent(); + if (!inventoryComponent) { + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + + if (costLOT == 13763) { // Faction Token Proxy + auto* missionComponent = buyer->GetComponent(); + if (!missionComponent) return; + + if (missionComponent->GetMissionState(545) == eMissionState::COMPLETE) costLOT = 8318; // "Assembly Token" + if (missionComponent->GetMissionState(556) == eMissionState::COMPLETE) costLOT = 8321; // "Venture League Token" + if (missionComponent->GetMissionState(567) == eMissionState::COMPLETE) costLOT = 8319; // "Sentinels Token" + if (missionComponent->GetMissionState(578) == eMissionState::COMPLETE) costLOT = 8320; // "Paradox Token" + } + + const uint32_t altCurrencyCost = itemComp.commendationCost * count; + if (inventoryComponent->GetLotCount(costLOT) < altCurrencyCost) { + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + + inventoryComponent->RemoveItem(costLOT, altCurrencyCost); + inventoryComponent->AddItem(lot, count, eLootSourceType::VENDOR); + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_SUCCESS); + +} + +void AchievementVendorComponent::RefreshInventory(bool isCreation) { + SetHasStandardCostItems(true); + Game::entityManager->SerializeEntity(m_Parent); +} diff --git a/dGame/dComponents/AchievementVendorComponent.h b/dGame/dComponents/AchievementVendorComponent.h new file mode 100644 index 00000000..ba6c7c2a --- /dev/null +++ b/dGame/dComponents/AchievementVendorComponent.h @@ -0,0 +1,25 @@ +#ifndef __ACHIEVEMENTVENDORCOMPONENT__H__ +#define __ACHIEVEMENTVENDORCOMPONENT__H__ + +#include "VendorComponent.h" +#include "eReplicaComponentType.h" +#include +#include + +class Entity; + +class AchievementVendorComponent final : public VendorComponent { +public: + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::ACHIEVEMENT_VENDOR; + AchievementVendorComponent(Entity* parent); + + void RefreshInventory(bool isCreation = false) override; + bool SellsItem(Entity* buyer, const LOT lot); + void Buy(Entity* buyer, LOT lot, uint32_t count); + +private: + std::map> m_PlayerPurchasableItems; +}; + + +#endif //!__ACHIEVEMENTVENDORCOMPONENT__H__ diff --git a/dGame/dComponents/ActivityComponent.cpp b/dGame/dComponents/ActivityComponent.cpp index e0cd7895..818d36b5 100644 --- a/dGame/dComponents/ActivityComponent.cpp +++ b/dGame/dComponents/ActivityComponent.cpp @@ -10,7 +10,6 @@ #include "WorldPackets.h" #include "EntityManager.h" #include "ChatPackets.h" -#include "Player.h" #include "BitStreamUtils.h" #include "dServer.h" #include "GeneralUtils.h" @@ -46,7 +45,7 @@ ActivityComponent::ActivityComponent(Entity* parent, int32_t activityID) : Compo if (destroyableComponent) { // First lookup the loot matrix id for this component id. - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance().GetTable(); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([=](CDActivityRewards entry) {return (entry.LootMatrixIndex == destroyableComponent->GetLootMatrixID()); }); uint32_t startingLMI = 0; @@ -70,7 +69,7 @@ ActivityComponent::ActivityComponent(Entity* parent, int32_t activityID) : Compo } } void ActivityComponent::LoadActivityData(const int32_t activityId) { - CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable(); + CDActivitiesTable* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([activityId](CDActivities entry) {return (entry.ActivityID == activityId); }); bool soloRacing = Game::config->GetValue("solo_racing") == "1"; @@ -83,21 +82,22 @@ void ActivityComponent::LoadActivityData(const int32_t activityId) { if (m_ActivityInfo.instanceMapID == -1) { const auto& transferOverride = m_Parent->GetVarAsString(u"transferZoneID"); if (!transferOverride.empty()) { - GeneralUtils::TryParse(transferOverride, m_ActivityInfo.instanceMapID); + m_ActivityInfo.instanceMapID = + GeneralUtils::TryParse(transferOverride).value_or(m_ActivityInfo.instanceMapID); } } } } -void ActivityComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - outBitStream->Write(m_DirtyActivityInfo); +void ActivityComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + outBitStream.Write(m_DirtyActivityInfo); if (m_DirtyActivityInfo) { - outBitStream->Write(m_ActivityPlayers.size()); + outBitStream.Write(m_ActivityPlayers.size()); if (!m_ActivityPlayers.empty()) { for (const auto& activityPlayer : m_ActivityPlayers) { - outBitStream->Write(activityPlayer->playerID); + outBitStream.Write(activityPlayer->playerID); for (const auto& activityValue : activityPlayer->values) { - outBitStream->Write(activityValue); + outBitStream.Write(activityValue); } } } @@ -106,7 +106,7 @@ void ActivityComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIniti } void ActivityComponent::ReloadConfig() { - CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable(); + CDActivitiesTable* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([this](CDActivities entry) {return (entry.ActivityID == m_ActivityID); }); for (auto activity : activities) { auto mapID = m_ActivityInfo.instanceMapID; @@ -545,14 +545,14 @@ void ActivityInstance::RewardParticipant(Entity* participant) { } // First, get the activity data - auto* activityRewardsTable = CDClientManager::Instance().GetTable(); + auto* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([this](CDActivityRewards entry) { return (entry.objectTemplate == m_ActivityInfo.ActivityID); }); if (!activityRewards.empty()) { uint32_t minCoins = 0; uint32_t maxCoins = 0; - auto* currencyTableTable = CDClientManager::Instance().GetTable(); + auto* currencyTableTable = CDClientManager::GetTable(); std::vector currencyTable = currencyTableTable->Query([=](CDCurrencyTable entry) { return (entry.currencyIndex == activityRewards[0].CurrencyIndex && entry.npcminlevel == 1); }); if (!currencyTable.empty()) { diff --git a/dGame/dComponents/ActivityComponent.h b/dGame/dComponents/ActivityComponent.h index de63b343..296c6ccc 100644 --- a/dGame/dComponents/ActivityComponent.h +++ b/dGame/dComponents/ActivityComponent.h @@ -155,7 +155,7 @@ public: void LoadActivityData(const int32_t activityId); void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * Makes some entity join the minigame, if it's a lobbied one, the entity will be placed in the lobby diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 9cc92c26..d40cf73e 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -25,6 +25,7 @@ #include "Metrics.hpp" #include "CDComponentsRegistryTable.h" #include "CDPhysicsComponentTable.h" +#include "dNavMesh.h" BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id): Component(parent) { m_Target = LWOOBJID_EMPTY; @@ -106,10 +107,10 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id): int32_t collisionGroup = (COLLISION_GROUP_DYNAMIC | COLLISION_GROUP_ENEMY); - CDComponentsRegistryTable* componentRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentRegistryTable = CDClientManager::GetTable(); auto componentID = componentRegistryTable->GetByIDAndType(parent->GetLOT(), eReplicaComponentType::CONTROLLABLE_PHYSICS); - CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance().GetTable(); + CDPhysicsComponentTable* physicsComponentTable = CDClientManager::GetTable(); if (physicsComponentTable != nullptr) { auto* info = physicsComponentTable->GetByID(componentID); @@ -128,17 +129,17 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id): m_dpEntity->SetPosition(m_Parent->GetPosition()); m_dpEntityEnemy->SetPosition(m_Parent->GetPosition()); - dpWorld::Instance().AddEntity(m_dpEntity); - dpWorld::Instance().AddEntity(m_dpEntityEnemy); + dpWorld::AddEntity(m_dpEntity); + dpWorld::AddEntity(m_dpEntityEnemy); } BaseCombatAIComponent::~BaseCombatAIComponent() { if (m_dpEntity) - dpWorld::Instance().RemoveEntity(m_dpEntity); + dpWorld::RemoveEntity(m_dpEntity); if (m_dpEntityEnemy) - dpWorld::Instance().RemoveEntity(m_dpEntityEnemy); + dpWorld::RemoveEntity(m_dpEntityEnemy); } void BaseCombatAIComponent::Update(const float deltaTime) { @@ -184,7 +185,7 @@ void BaseCombatAIComponent::Update(const float deltaTime) { bool stunnedThisFrame = m_Stunned; CalculateCombat(deltaTime); // Putting this here for now - if (m_StartPosition == NiPoint3::ZERO) { + if (m_StartPosition == NiPoint3Constant::ZERO) { m_StartPosition = m_Parent->GetPosition(); } @@ -519,11 +520,11 @@ bool BaseCombatAIComponent::IsMech() { } -void BaseCombatAIComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - outBitStream->Write(m_DirtyStateOrTarget || bIsInitialUpdate); +void BaseCombatAIComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + outBitStream.Write(m_DirtyStateOrTarget || bIsInitialUpdate); if (m_DirtyStateOrTarget || bIsInitialUpdate) { - outBitStream->Write(m_State); - outBitStream->Write(m_Target); + outBitStream.Write(m_State); + outBitStream.Write(m_Target); m_DirtyStateOrTarget = false; } } @@ -653,8 +654,8 @@ void BaseCombatAIComponent::Wander() { auto destination = m_StartPosition + delta; - if (dpWorld::Instance().IsLoaded()) { - destination.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(destination); + if (dpWorld::IsLoaded()) { + destination.y = dpWorld::GetNavMesh()->GetHeightAtPoint(destination); } if (Vector3::DistanceSquared(destination, m_MovementAI->GetParent()->GetPosition()) < 2 * 2) { diff --git a/dGame/dComponents/BaseCombatAIComponent.h b/dGame/dComponents/BaseCombatAIComponent.h index 8ae04611..89985d64 100644 --- a/dGame/dComponents/BaseCombatAIComponent.h +++ b/dGame/dComponents/BaseCombatAIComponent.h @@ -45,15 +45,15 @@ struct AiSkillEntry /** * Handles the AI of entities, making them wander, tether and attack their enemies */ -class BaseCombatAIComponent : public Component { +class BaseCombatAIComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::BASE_COMBAT_AI; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::BASE_COMBAT_AI; BaseCombatAIComponent(Entity* parentEntity, uint32_t id); ~BaseCombatAIComponent() override; void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * Get the current behavioral state of the enemy diff --git a/dGame/dComponents/BouncerComponent.cpp b/dGame/dComponents/BouncerComponent.cpp index 78ee3637..d1c63bf4 100644 --- a/dGame/dComponents/BouncerComponent.cpp +++ b/dGame/dComponents/BouncerComponent.cpp @@ -22,10 +22,10 @@ BouncerComponent::BouncerComponent(Entity* parent) : Component(parent) { BouncerComponent::~BouncerComponent() { } -void BouncerComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - outBitStream->Write(m_PetEnabled); +void BouncerComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + outBitStream.Write(m_PetEnabled); if (m_PetEnabled) { - outBitStream->Write(m_PetBouncerEnabled); + outBitStream.Write(m_PetBouncerEnabled); } } diff --git a/dGame/dComponents/BouncerComponent.h b/dGame/dComponents/BouncerComponent.h index cb3d8df3..441ba58e 100644 --- a/dGame/dComponents/BouncerComponent.h +++ b/dGame/dComponents/BouncerComponent.h @@ -10,14 +10,14 @@ /** * Attached to bouncer entities, allowing other entities to bounce off of it */ -class BouncerComponent : public Component { +class BouncerComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::BOUNCER; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::BOUNCER; BouncerComponent(Entity* parentEntity); ~BouncerComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; Entity* GetParentEntity() const; diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index 10ac4ebb..8b76e423 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -32,24 +32,24 @@ BuffComponent::BuffComponent(Entity* parent) : Component(parent) { BuffComponent::~BuffComponent() { } -void BuffComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void BuffComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { if (!bIsInitialUpdate) return; - outBitStream->Write(!m_Buffs.empty()); + outBitStream.Write(!m_Buffs.empty()); if (!m_Buffs.empty()) { - outBitStream->Write(m_Buffs.size()); + outBitStream.Write(m_Buffs.size()); for (const auto& [id, buff] : m_Buffs) { - outBitStream->Write(id); - outBitStream->Write(buff.time != 0.0f); - if (buff.time != 0.0f) outBitStream->Write(buff.time * 1000.0f); - outBitStream->Write(buff.cancelOnDeath); - outBitStream->Write(buff.cancelOnZone); - outBitStream->Write(buff.cancelOnDamaged); - outBitStream->Write(buff.cancelOnRemoveBuff); - outBitStream->Write(buff.cancelOnUi); - outBitStream->Write(buff.cancelOnLogout); - outBitStream->Write(buff.cancelOnUnequip); - outBitStream->Write0(); // Cancel on Damage Absorb Ran Out. Generally false from what I can tell + outBitStream.Write(id); + outBitStream.Write(buff.time != 0.0f); + if (buff.time != 0.0f) outBitStream.Write(buff.time * 1000.0f); + outBitStream.Write(buff.cancelOnDeath); + outBitStream.Write(buff.cancelOnZone); + outBitStream.Write(buff.cancelOnDamaged); + outBitStream.Write(buff.cancelOnRemoveBuff); + outBitStream.Write(buff.cancelOnUi); + outBitStream.Write(buff.cancelOnLogout); + outBitStream.Write(buff.cancelOnUnequip); + outBitStream.Write0(); // Cancel on Damage Absorb Ran Out. Generally false from what I can tell auto* team = TeamManager::Instance()->GetTeam(buff.source); bool addedByTeammate = false; @@ -57,15 +57,15 @@ void BuffComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUp addedByTeammate = std::count(team->members.begin(), team->members.end(), m_Parent->GetObjectID()) > 0; } - outBitStream->Write(addedByTeammate); // Added by teammate. If source is in the same team as the target, this is true. Otherwise, false. - outBitStream->Write(buff.applyOnTeammates); - if (addedByTeammate) outBitStream->Write(buff.source); + outBitStream.Write(addedByTeammate); // Added by teammate. If source is in the same team as the target, this is true. Otherwise, false. + outBitStream.Write(buff.applyOnTeammates); + if (addedByTeammate) outBitStream.Write(buff.source); - outBitStream->Write(buff.refCount); + outBitStream.Write(buff.refCount); } } - outBitStream->Write0(); // something to do with immunity buffs? + outBitStream.Write0(); // something to do with immunity buffs? } void BuffComponent::Update(float deltaTime) { @@ -164,7 +164,7 @@ void BuffComponent::ApplyBuff(const int32_t id, const float duration, const LWOO const auto& parameters = GetBuffParameters(id); for (const auto& parameter : parameters) { if (parameter.name == "overtime") { - auto* behaviorTemplateTable = CDClientManager::Instance().GetTable(); + auto* behaviorTemplateTable = CDClientManager::GetTable(); behaviorID = behaviorTemplateTable->GetSkillByID(parameter.values[0]).behaviorID; stacks = static_cast(parameter.values[1]); @@ -208,9 +208,8 @@ void BuffComponent::ApplyBuff(const int32_t id, const float duration, const LWOO void BuffComponent::RemoveBuff(int32_t id, bool fromUnEquip, bool removeImmunity, bool ignoreRefCount) { const auto& iter = m_Buffs.find(id); - if (iter == m_Buffs.end()) { - return; - } + // If the buff is already scheduled to be removed, don't do it again + if (iter == m_Buffs.end() || m_BuffsToRemove.contains(id)) return; if (!ignoreRefCount && !iter->second.cancelOnRemoveBuff) { iter->second.refCount--; @@ -222,7 +221,7 @@ void BuffComponent::RemoveBuff(int32_t id, bool fromUnEquip, bool removeImmunity GameMessages::SendRemoveBuff(m_Parent, fromUnEquip, removeImmunity, id); - m_BuffsToRemove.push_back(id); + m_BuffsToRemove.insert(id); RemoveBuffEffect(id); } diff --git a/dGame/dComponents/BuffComponent.h b/dGame/dComponents/BuffComponent.h index 7f7b44d8..df3c6a78 100644 --- a/dGame/dComponents/BuffComponent.h +++ b/dGame/dComponents/BuffComponent.h @@ -47,9 +47,9 @@ struct Buff { /** * Allows for the application of buffs to the parent entity, altering health, armor and imagination. */ -class BuffComponent : public Component { +class BuffComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::BUFF; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::BUFF; explicit BuffComponent(Entity* parent); @@ -61,7 +61,7 @@ public: void UpdateXml(tinyxml2::XMLDocument* doc) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; void Update(float deltaTime) override; @@ -141,7 +141,7 @@ private: std::map m_Buffs; // Buffs to remove at the end of the update frame. - std::vector m_BuffsToRemove; + std::set m_BuffsToRemove; /** * Parameters (=effects) for each buff diff --git a/dGame/dComponents/BuildBorderComponent.cpp b/dGame/dComponents/BuildBorderComponent.cpp index 9e392e69..066a8c74 100644 --- a/dGame/dComponents/BuildBorderComponent.cpp +++ b/dGame/dComponents/BuildBorderComponent.cpp @@ -56,7 +56,7 @@ void BuildBorderComponent::OnUse(Entity* originator) { 4, 0, -1, - NiPoint3::ZERO, + NiPoint3Constant::ZERO, 0 ); } else { diff --git a/dGame/dComponents/BuildBorderComponent.h b/dGame/dComponents/BuildBorderComponent.h index 985c0388..a59ac363 100644 --- a/dGame/dComponents/BuildBorderComponent.h +++ b/dGame/dComponents/BuildBorderComponent.h @@ -14,9 +14,9 @@ /** * Component for the build border, allowing the user to start building when interacting with it */ -class BuildBorderComponent : public Component { +class BuildBorderComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::BUILD_BORDER; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::BUILD_BORDER; BuildBorderComponent(Entity* parent); ~BuildBorderComponent() override; diff --git a/dGame/dComponents/CMakeLists.txt b/dGame/dComponents/CMakeLists.txt index 59c49ce9..c60e135f 100644 --- a/dGame/dComponents/CMakeLists.txt +++ b/dGame/dComponents/CMakeLists.txt @@ -1,4 +1,5 @@ set(DGAME_DCOMPONENTS_SOURCES + "AchievementVendorComponent.cpp" "ActivityComponent.cpp" "BaseCombatAIComponent.cpp" "BouncerComponent.cpp" @@ -27,7 +28,6 @@ set(DGAME_DCOMPONENTS_SOURCES "PlayerForcedMovementComponent.cpp" "PossessableComponent.cpp" "PossessorComponent.cpp" - "PropertyComponent.cpp" "PropertyEntranceComponent.cpp" "PropertyManagementComponent.cpp" "PropertyVendorComponent.cpp" @@ -48,11 +48,35 @@ set(DGAME_DCOMPONENTS_SOURCES "HavokVehiclePhysicsComponent.cpp" "VendorComponent.cpp" "MiniGameControlComponent.cpp" + "ScriptComponent.cpp" ) -add_library(dComponents STATIC ${DGAME_DCOMPONENTS_SOURCES}) -target_include_directories(dComponents PRIVATE ${PROJECT_SOURCE_DIR}/dScripts/02_server/Map/General) # PetDigServer.h +add_library(dComponents OBJECT ${DGAME_DCOMPONENTS_SOURCES}) +target_include_directories(dComponents PUBLIC "." + "${PROJECT_SOURCE_DIR}/dGame/dPropertyBehaviors" # via ModelComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dPropertyBehaviors/ControlBehaviorMessages" + "${PROJECT_SOURCE_DIR}/dGame/dMission" # via MissionComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dBehaviors" # via InventoryComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dInventory" # via InventoryComponent.h + PRIVATE + "${PROJECT_SOURCE_DIR}/dCommon" + "${PROJECT_SOURCE_DIR}/dCommon/dEnums" + "${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase" + "${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase/CDClientTables" + "${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase" + "${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase/ITables" + "${PROJECT_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/include" + # dPhysics (via dpWorld.h) + "${PROJECT_SOURCE_DIR}/thirdparty/recastnavigation/Recast/Include" + "${PROJECT_SOURCE_DIR}/thirdparty/recastnavigation/Detour/Include" + + "${PROJECT_SOURCE_DIR}/dScripts/02_server/Map/General" # PetDigServer.h + "${PROJECT_SOURCE_DIR}/dGame/dGameMessages" # direct + "${PROJECT_SOURCE_DIR}/dGame/dUtilities" # direct Loot.h + "${PROJECT_SOURCE_DIR}/dGame/dEntity" # via dZoneManager/Spawner.h + "${PROJECT_SOURCE_DIR}/dZoneManager" # via BouncerComponent.cpp, ActivityComponent.cpp + "${PROJECT_SOURCE_DIR}/dChatFilter" # via PetComponent.cpp +) target_precompile_headers(dComponents REUSE_FROM dGameBase) -target_link_libraries(dComponents - PUBLIC dPhysics dDatabase - INTERFACE dUtilities dCommon dBehaviors dChatFilter dMission dInventory) + +target_link_libraries(dComponents INTERFACE dBehaviors) diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 70eec0cf..3eafd924 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -24,7 +24,7 @@ #include "WorldPackets.h" #include -CharacterComponent::CharacterComponent(Entity* parent, Character* character) : Component(parent) { +CharacterComponent::CharacterComponent(Entity* parent, Character* character, const SystemAddress& systemAddress) : Component(parent) { m_Character = character; m_IsRacing = false; @@ -46,6 +46,7 @@ CharacterComponent::CharacterComponent(Entity* parent, Character* character) : C m_CurrentActivity = eGameActivity::NONE; m_CountryCode = 0; m_LastUpdateTimestamp = std::time(nullptr); + m_SystemAddress = systemAddress; } bool CharacterComponent::LandingAnimDisabled(int zoneID) { @@ -77,94 +78,94 @@ bool CharacterComponent::LandingAnimDisabled(int zoneID) { CharacterComponent::~CharacterComponent() { } -void CharacterComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void CharacterComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { if (bIsInitialUpdate) { - outBitStream->Write(m_ClaimCodes[0] != 0); - if (m_ClaimCodes[0] != 0) outBitStream->Write(m_ClaimCodes[0]); - outBitStream->Write(m_ClaimCodes[1] != 0); - if (m_ClaimCodes[1] != 0) outBitStream->Write(m_ClaimCodes[1]); - outBitStream->Write(m_ClaimCodes[2] != 0); - if (m_ClaimCodes[2] != 0) outBitStream->Write(m_ClaimCodes[2]); - outBitStream->Write(m_ClaimCodes[3] != 0); - if (m_ClaimCodes[3] != 0) outBitStream->Write(m_ClaimCodes[3]); + outBitStream.Write(m_ClaimCodes[0] != 0); + if (m_ClaimCodes[0] != 0) outBitStream.Write(m_ClaimCodes[0]); + outBitStream.Write(m_ClaimCodes[1] != 0); + if (m_ClaimCodes[1] != 0) outBitStream.Write(m_ClaimCodes[1]); + outBitStream.Write(m_ClaimCodes[2] != 0); + if (m_ClaimCodes[2] != 0) outBitStream.Write(m_ClaimCodes[2]); + outBitStream.Write(m_ClaimCodes[3] != 0); + if (m_ClaimCodes[3] != 0) outBitStream.Write(m_ClaimCodes[3]); - outBitStream->Write(m_Character->GetHairColor()); - outBitStream->Write(m_Character->GetHairStyle()); - outBitStream->Write(0); //Default "head" - outBitStream->Write(m_Character->GetShirtColor()); - outBitStream->Write(m_Character->GetPantsColor()); - outBitStream->Write(m_Character->GetShirtStyle()); - outBitStream->Write(0); //Default "head color" - outBitStream->Write(m_Character->GetEyebrows()); - outBitStream->Write(m_Character->GetEyes()); - outBitStream->Write(m_Character->GetMouth()); - outBitStream->Write(0); //AccountID, trying out if 0 works. - outBitStream->Write(m_Character->GetLastLogin()); //Last login - outBitStream->Write(0); //"prop mod last display time" - outBitStream->Write(m_Uscore); //u-score - outBitStream->Write0(); //Not free-to-play (disabled in DLU) + outBitStream.Write(m_Character->GetHairColor()); + outBitStream.Write(m_Character->GetHairStyle()); + outBitStream.Write(0); //Default "head" + outBitStream.Write(m_Character->GetShirtColor()); + outBitStream.Write(m_Character->GetPantsColor()); + outBitStream.Write(m_Character->GetShirtStyle()); + outBitStream.Write(0); //Default "head color" + outBitStream.Write(m_Character->GetEyebrows()); + outBitStream.Write(m_Character->GetEyes()); + outBitStream.Write(m_Character->GetMouth()); + outBitStream.Write(0); //AccountID, trying out if 0 works. + outBitStream.Write(m_Character->GetLastLogin()); //Last login + outBitStream.Write(0); //"prop mod last display time" + outBitStream.Write(m_Uscore); //u-score + outBitStream.Write0(); //Not free-to-play (disabled in DLU) //Stats: - outBitStream->Write(m_CurrencyCollected); - outBitStream->Write(m_BricksCollected); - outBitStream->Write(m_SmashablesSmashed); - outBitStream->Write(m_QuickBuildsCompleted); - outBitStream->Write(m_EnemiesSmashed); - outBitStream->Write(m_RocketsUsed); - outBitStream->Write(m_MissionsCompleted); - outBitStream->Write(m_PetsTamed); - outBitStream->Write(m_ImaginationPowerUpsCollected); - outBitStream->Write(m_LifePowerUpsCollected); - outBitStream->Write(m_ArmorPowerUpsCollected); - outBitStream->Write(m_MetersTraveled); - outBitStream->Write(m_TimesSmashed); - outBitStream->Write(m_TotalDamageTaken); - outBitStream->Write(m_TotalDamageHealed); - outBitStream->Write(m_TotalArmorRepaired); - outBitStream->Write(m_TotalImaginationRestored); - outBitStream->Write(m_TotalImaginationUsed); - outBitStream->Write(m_DistanceDriven); - outBitStream->Write(m_TimeAirborneInCar); - outBitStream->Write(m_RacingImaginationPowerUpsCollected); - outBitStream->Write(m_RacingImaginationCratesSmashed); - outBitStream->Write(m_RacingCarBoostsActivated); - outBitStream->Write(m_RacingTimesWrecked); - outBitStream->Write(m_RacingSmashablesSmashed); - outBitStream->Write(m_RacesFinished); - outBitStream->Write(m_FirstPlaceRaceFinishes); + outBitStream.Write(m_CurrencyCollected); + outBitStream.Write(m_BricksCollected); + outBitStream.Write(m_SmashablesSmashed); + outBitStream.Write(m_QuickBuildsCompleted); + outBitStream.Write(m_EnemiesSmashed); + outBitStream.Write(m_RocketsUsed); + outBitStream.Write(m_MissionsCompleted); + outBitStream.Write(m_PetsTamed); + outBitStream.Write(m_ImaginationPowerUpsCollected); + outBitStream.Write(m_LifePowerUpsCollected); + outBitStream.Write(m_ArmorPowerUpsCollected); + outBitStream.Write(m_MetersTraveled); + outBitStream.Write(m_TimesSmashed); + outBitStream.Write(m_TotalDamageTaken); + outBitStream.Write(m_TotalDamageHealed); + outBitStream.Write(m_TotalArmorRepaired); + outBitStream.Write(m_TotalImaginationRestored); + outBitStream.Write(m_TotalImaginationUsed); + outBitStream.Write(m_DistanceDriven); + outBitStream.Write(m_TimeAirborneInCar); + outBitStream.Write(m_RacingImaginationPowerUpsCollected); + outBitStream.Write(m_RacingImaginationCratesSmashed); + outBitStream.Write(m_RacingCarBoostsActivated); + outBitStream.Write(m_RacingTimesWrecked); + outBitStream.Write(m_RacingSmashablesSmashed); + outBitStream.Write(m_RacesFinished); + outBitStream.Write(m_FirstPlaceRaceFinishes); - outBitStream->Write0(); - outBitStream->Write(m_IsLanding); + outBitStream.Write0(); + outBitStream.Write(m_IsLanding); if (m_IsLanding) { - outBitStream->Write(m_LastRocketConfig.size()); + outBitStream.Write(m_LastRocketConfig.size()); for (uint16_t character : m_LastRocketConfig) { - outBitStream->Write(character); + outBitStream.Write(character); } } } - outBitStream->Write(m_DirtyGMInfo); + outBitStream.Write(m_DirtyGMInfo); if (m_DirtyGMInfo) { - outBitStream->Write(m_PvpEnabled); - outBitStream->Write(m_IsGM); - outBitStream->Write(m_GMLevel); - outBitStream->Write(m_EditorEnabled); - outBitStream->Write(m_EditorLevel); + outBitStream.Write(m_PvpEnabled); + outBitStream.Write(m_IsGM); + outBitStream.Write(m_GMLevel); + outBitStream.Write(m_EditorEnabled); + outBitStream.Write(m_EditorLevel); } - outBitStream->Write(m_DirtyCurrentActivity); - if (m_DirtyCurrentActivity) outBitStream->Write(m_CurrentActivity); + outBitStream.Write(m_DirtyCurrentActivity); + if (m_DirtyCurrentActivity) outBitStream.Write(m_CurrentActivity); - outBitStream->Write(m_DirtySocialInfo); + outBitStream.Write(m_DirtySocialInfo); if (m_DirtySocialInfo) { - outBitStream->Write(m_GuildID); - outBitStream->Write(m_GuildName.size()); + outBitStream.Write(m_GuildID); + outBitStream.Write(m_GuildName.size()); if (!m_GuildName.empty()) - outBitStream->WriteBits(reinterpret_cast(m_GuildName.c_str()), static_cast(m_GuildName.size()) * sizeof(wchar_t) * 8); + outBitStream.WriteBits(reinterpret_cast(m_GuildName.c_str()), static_cast(m_GuildName.size()) * sizeof(wchar_t) * 8); - outBitStream->Write(m_IsLEGOClubMember); - outBitStream->Write(m_CountryCode); + outBitStream.Write(m_IsLEGOClubMember); + outBitStream.Write(m_CountryCode); } } @@ -762,14 +763,14 @@ void CharacterComponent::UpdateClientMinimap(bool showFaction, std::string ventu } void CharacterComponent::AwardClaimCodes() { - if (!m_Parent) return; - auto* user = m_Parent->GetParentUser(); + if (!m_Parent || !m_Parent->GetCharacter()) return; + auto* user = m_Parent->GetCharacter()->GetParentUser(); if (!user) return; auto rewardCodes = Database::Get()->GetRewardCodesByAccountID(user->GetAccountID()); if (rewardCodes.empty()) return; - auto* cdrewardCodes = CDClientManager::Instance().GetTable(); + auto* cdrewardCodes = CDClientManager::GetTable(); for (auto const rewardCode : rewardCodes) { LOG_DEBUG("Processing RewardCode %i", rewardCode); const uint32_t rewardCodeIndex = rewardCode >> 6; @@ -817,3 +818,20 @@ void CharacterComponent::SendToZone(LWOMAPID zoneId, LWOCLONEID cloneId) const { Game::entityManager->DestructEntity(entity); }); } + +const SystemAddress& CharacterComponent::GetSystemAddress() const { + return m_SystemAddress; +} + +void CharacterComponent::SetRespawnPos(const NiPoint3& position) { + if (!m_Character) return; + + m_respawnPos = position; + + m_Character->SetRespawnPoint(Game::zoneManager->GetZone()->GetWorldID(), position); + +} + +void CharacterComponent::SetRespawnRot(const NiQuaternion& rotation) { + m_respawnRot = rotation; +} diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index fae99dcb..aa5c2e29 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -5,15 +5,17 @@ #include "RakNetTypes.h" #include "Character.h" #include "Component.h" -#include "Item.h" #include #include "CDMissionsTable.h" #include "tinyxml2.h" #include "eReplicaComponentType.h" #include +#include "Loot.h" enum class eGameActivity : uint32_t; +class Item; + /** * The statistics that can be achieved per zone */ @@ -61,17 +63,17 @@ enum StatisticID { /** * Represents a character, including their rockets and stats */ -class CharacterComponent : public Component { +class CharacterComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::CHARACTER; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::CHARACTER; - CharacterComponent(Entity* parent, Character* character); + CharacterComponent(Entity* parent, Character* character, const SystemAddress& systemAddress); ~CharacterComponent() override; void LoadFromXml(tinyxml2::XMLDocument* doc) override; void UpdateXml(tinyxml2::XMLDocument* doc) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * Updates the rocket configuration using a LOT string separated by commas @@ -289,6 +291,22 @@ public: */ void SendToZone(LWOMAPID zoneId, LWOCLONEID cloneId = 0) const; + const SystemAddress& GetSystemAddress() const; + + const NiPoint3& GetRespawnPosition() const { return m_respawnPos; }; + + void SetRespawnPos(const NiPoint3& position); + + const NiQuaternion& GetRespawnRotation() const { return m_respawnRot; }; + + void SetRespawnRot(const NiQuaternion& rotation); + + std::map& GetDroppedLoot() { return m_DroppedLoot; }; + + uint64_t GetDroppedCoins() const { return m_DroppedCoins; }; + + void SetDroppedCoins(const uint64_t value) { m_DroppedCoins = value; }; + /** * Character info regarding this character, including clothing styles, etc. */ @@ -579,6 +597,16 @@ private: std::array m_ClaimCodes{}; void AwardClaimCodes(); + + SystemAddress m_SystemAddress; + + NiPoint3 m_respawnPos; + + NiQuaternion m_respawnRot; + + std::map m_DroppedLoot; + + uint64_t m_DroppedCoins = 0; }; #endif // CHARACTERCOMPONENT_H diff --git a/dGame/dComponents/CollectibleComponent.cpp b/dGame/dComponents/CollectibleComponent.cpp index 99fcc681..f6ba25b2 100644 --- a/dGame/dComponents/CollectibleComponent.cpp +++ b/dGame/dComponents/CollectibleComponent.cpp @@ -1,5 +1,5 @@ #include "CollectibleComponent.h" -void CollectibleComponent::Serialize(RakNet::BitStream* outBitStream, bool isConstruction) { - outBitStream->Write(GetCollectibleId()); +void CollectibleComponent::Serialize(RakNet::BitStream& outBitStream, bool isConstruction) { + outBitStream.Write(GetCollectibleId()); } diff --git a/dGame/dComponents/CollectibleComponent.h b/dGame/dComponents/CollectibleComponent.h index 3ff71c6f..5ecfb97e 100644 --- a/dGame/dComponents/CollectibleComponent.h +++ b/dGame/dComponents/CollectibleComponent.h @@ -4,13 +4,13 @@ #include "Component.h" #include "eReplicaComponentType.h" -class CollectibleComponent : public Component { +class CollectibleComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::COLLECTIBLE; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::COLLECTIBLE; CollectibleComponent(Entity* parentEntity, int32_t collectibleId) : Component(parentEntity), m_CollectibleId(collectibleId) {} int16_t GetCollectibleId() const { return m_CollectibleId; } - void Serialize(RakNet::BitStream* outBitStream, bool isConstruction) override; + void Serialize(RakNet::BitStream& outBitStream, bool isConstruction) override; private: int16_t m_CollectibleId = 0; }; diff --git a/dGame/dComponents/Component.cpp b/dGame/dComponents/Component.cpp index 1136456c..705c44a7 100644 --- a/dGame/dComponents/Component.cpp +++ b/dGame/dComponents/Component.cpp @@ -29,6 +29,6 @@ void Component::LoadFromXml(tinyxml2::XMLDocument* doc) { } -void Component::Serialize(RakNet::BitStream* outBitStream, bool isConstruction) { +void Component::Serialize(RakNet::BitStream& outBitStream, bool isConstruction) { } diff --git a/dGame/dComponents/Component.h b/dGame/dComponents/Component.h index d1ad0860..062924f7 100644 --- a/dGame/dComponents/Component.h +++ b/dGame/dComponents/Component.h @@ -7,8 +7,7 @@ class Entity; /** * Component base class, provides methods for game loop updates, usage events and loading and saving to XML. */ -class Component -{ +class Component { public: Component(Entity* parent); virtual ~Component(); @@ -43,7 +42,7 @@ public: */ virtual void LoadFromXml(tinyxml2::XMLDocument* doc); - virtual void Serialize(RakNet::BitStream* outBitStream, bool isConstruction); + virtual void Serialize(RakNet::BitStream& outBitStream, bool isConstruction); protected: diff --git a/dGame/dComponents/ControllablePhysicsComponent.cpp b/dGame/dComponents/ControllablePhysicsComponent.cpp index dd981f66..dccbe915 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.cpp +++ b/dGame/dComponents/ControllablePhysicsComponent.cpp @@ -21,14 +21,11 @@ ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Phy m_InJetpackMode = false; m_IsOnGround = true; m_IsOnRail = false; - m_DirtyVelocity = true; - m_DirtyAngularVelocity = true; m_dpEntity = nullptr; m_Static = false; m_SpeedMultiplier = 1; m_GravityScale = 1; m_DirtyCheats = false; - m_IgnoreMultipliers = false; m_DirtyEquippedItemInfo = true; m_PickupRadius = 0.0f; @@ -57,13 +54,13 @@ ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Phy float radius = 1.5f; m_dpEntity = new dpEntity(m_Parent->GetObjectID(), radius, false); m_dpEntity->SetCollisionGroup(COLLISION_GROUP_DYNAMIC | COLLISION_GROUP_FRIENDLY); - dpWorld::Instance().AddEntity(m_dpEntity); + dpWorld::AddEntity(m_dpEntity); } } ControllablePhysicsComponent::~ControllablePhysicsComponent() { if (m_dpEntity) { - dpWorld::Instance().RemoveEntity(m_dpEntity); + dpWorld::RemoveEntity(m_dpEntity); } } @@ -71,90 +68,93 @@ void ControllablePhysicsComponent::Update(float deltaTime) { } -void ControllablePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void ControllablePhysicsComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { //If this is a creation, then we assume the position is dirty, even when it isn't. //This is because new clients will still need to receive the position. //if (bIsInitialUpdate) m_DirtyPosition = true; if (bIsInitialUpdate) { - outBitStream->Write(m_InJetpackMode); + outBitStream.Write(m_InJetpackMode); if (m_InJetpackMode) { - outBitStream->Write(m_JetpackEffectID); - outBitStream->Write(m_JetpackFlying); - outBitStream->Write(m_JetpackBypassChecks); + outBitStream.Write(m_JetpackEffectID); + outBitStream.Write(m_JetpackFlying); + outBitStream.Write(m_JetpackBypassChecks); } - outBitStream->Write1(); // always write these on construction - outBitStream->Write(m_ImmuneToStunMoveCount); - outBitStream->Write(m_ImmuneToStunJumpCount); - outBitStream->Write(m_ImmuneToStunTurnCount); - outBitStream->Write(m_ImmuneToStunAttackCount); - outBitStream->Write(m_ImmuneToStunUseItemCount); - outBitStream->Write(m_ImmuneToStunEquipCount); - outBitStream->Write(m_ImmuneToStunInteractCount); + outBitStream.Write1(); // always write these on construction + outBitStream.Write(m_ImmuneToStunMoveCount); + outBitStream.Write(m_ImmuneToStunJumpCount); + outBitStream.Write(m_ImmuneToStunTurnCount); + outBitStream.Write(m_ImmuneToStunAttackCount); + outBitStream.Write(m_ImmuneToStunUseItemCount); + outBitStream.Write(m_ImmuneToStunEquipCount); + outBitStream.Write(m_ImmuneToStunInteractCount); } - if (m_IgnoreMultipliers) m_DirtyCheats = false; + outBitStream.Write(m_DirtyCheats || bIsInitialUpdate); + if (m_DirtyCheats || bIsInitialUpdate) { + outBitStream.Write(m_GravityScale); + outBitStream.Write(m_SpeedMultiplier); - outBitStream->Write(m_DirtyCheats); - if (m_DirtyCheats) { - outBitStream->Write(m_GravityScale); - outBitStream->Write(m_SpeedMultiplier); - - m_DirtyCheats = false; + if (!bIsInitialUpdate) m_DirtyCheats = false; } - outBitStream->Write(m_DirtyEquippedItemInfo); - if (m_DirtyEquippedItemInfo) { - outBitStream->Write(m_PickupRadius); - outBitStream->Write(m_InJetpackMode); - m_DirtyEquippedItemInfo = false; + outBitStream.Write(m_DirtyEquippedItemInfo || bIsInitialUpdate); + if (m_DirtyEquippedItemInfo || bIsInitialUpdate) { + outBitStream.Write(m_PickupRadius); + outBitStream.Write(m_InJetpackMode); + + if (!bIsInitialUpdate) m_DirtyEquippedItemInfo = false; } - outBitStream->Write(m_DirtyBubble); - if (m_DirtyBubble) { - outBitStream->Write(m_IsInBubble); + outBitStream.Write(m_DirtyBubble || bIsInitialUpdate); + if (m_DirtyBubble || bIsInitialUpdate) { + outBitStream.Write(m_IsInBubble); if (m_IsInBubble) { - outBitStream->Write(m_BubbleType); - outBitStream->Write(m_SpecialAnims); + outBitStream.Write(m_BubbleType); + outBitStream.Write(m_SpecialAnims); } - m_DirtyBubble = false; + + if (!bIsInitialUpdate) m_DirtyBubble = false; } - outBitStream->Write(m_DirtyPosition || bIsInitialUpdate); + outBitStream.Write(m_DirtyPosition || bIsInitialUpdate); if (m_DirtyPosition || bIsInitialUpdate) { - outBitStream->Write(m_Position.x); - outBitStream->Write(m_Position.y); - outBitStream->Write(m_Position.z); + outBitStream.Write(m_Position.x); + outBitStream.Write(m_Position.y); + outBitStream.Write(m_Position.z); - outBitStream->Write(m_Rotation.x); - outBitStream->Write(m_Rotation.y); - outBitStream->Write(m_Rotation.z); - outBitStream->Write(m_Rotation.w); + outBitStream.Write(m_Rotation.x); + outBitStream.Write(m_Rotation.y); + outBitStream.Write(m_Rotation.z); + outBitStream.Write(m_Rotation.w); - outBitStream->Write(m_IsOnGround); - outBitStream->Write(m_IsOnRail); + outBitStream.Write(m_IsOnGround); + outBitStream.Write(m_IsOnRail); - outBitStream->Write(m_DirtyVelocity); - if (m_DirtyVelocity) { - outBitStream->Write(m_Velocity.x); - outBitStream->Write(m_Velocity.y); - outBitStream->Write(m_Velocity.z); + bool isNotZero = m_Velocity != NiPoint3Constant::ZERO; + outBitStream.Write(isNotZero); + if (isNotZero) { + outBitStream.Write(m_Velocity.x); + outBitStream.Write(m_Velocity.y); + outBitStream.Write(m_Velocity.z); } - outBitStream->Write(m_DirtyAngularVelocity); - if (m_DirtyAngularVelocity) { - outBitStream->Write(m_AngularVelocity.x); - outBitStream->Write(m_AngularVelocity.y); - outBitStream->Write(m_AngularVelocity.z); + isNotZero = m_AngularVelocity != NiPoint3Constant::ZERO; + outBitStream.Write(isNotZero); + if (isNotZero) { + outBitStream.Write(m_AngularVelocity.x); + outBitStream.Write(m_AngularVelocity.y); + outBitStream.Write(m_AngularVelocity.z); } - outBitStream->Write0(); - } + outBitStream.Write0(); // local_space_info, always zero for now. - if (!bIsInitialUpdate) { - outBitStream->Write(m_IsTeleporting); - m_IsTeleporting = false; + if (!bIsInitialUpdate) { + m_DirtyPosition = false; + outBitStream.Write(m_IsTeleporting); + m_IsTeleporting = false; + } } } @@ -211,33 +211,29 @@ void ControllablePhysicsComponent::SetRotation(const NiQuaternion& rot) { } void ControllablePhysicsComponent::SetVelocity(const NiPoint3& vel) { - if (m_Static) { - return; - } + if (m_Static || m_Velocity == vel) return; m_Velocity = vel; m_DirtyPosition = true; - m_DirtyVelocity = true; if (m_dpEntity) m_dpEntity->SetVelocity(vel); } void ControllablePhysicsComponent::SetAngularVelocity(const NiPoint3& vel) { - if (m_Static) { - return; - } + if (m_Static || m_AngularVelocity == vel) return; m_AngularVelocity = vel; m_DirtyPosition = true; - m_DirtyAngularVelocity = true; } void ControllablePhysicsComponent::SetIsOnGround(bool val) { + if (m_IsOnGround == val) return; m_DirtyPosition = true; m_IsOnGround = val; } void ControllablePhysicsComponent::SetIsOnRail(bool val) { + if (m_IsOnRail == val) return; m_DirtyPosition = true; m_IsOnRail = val; } @@ -245,15 +241,6 @@ void ControllablePhysicsComponent::SetIsOnRail(bool val) { void ControllablePhysicsComponent::SetDirtyPosition(bool val) { m_DirtyPosition = val; } - -void ControllablePhysicsComponent::SetDirtyVelocity(bool val) { - m_DirtyVelocity = val; -} - -void ControllablePhysicsComponent::SetDirtyAngularVelocity(bool val) { - m_DirtyAngularVelocity = val; -} - void ControllablePhysicsComponent::AddPickupRadiusScale(float value) { m_ActivePickupRadiusScales.push_back(value); if (value > m_PickupRadius) { @@ -309,7 +296,7 @@ void ControllablePhysicsComponent::RemoveSpeedboost(float value) { Game::entityManager->SerializeEntity(m_Parent); } -void ControllablePhysicsComponent::ActivateBubbleBuff(eBubbleType bubbleType, bool specialAnims){ +void ControllablePhysicsComponent::ActivateBubbleBuff(eBubbleType bubbleType, bool specialAnims) { if (m_IsInBubble) { LOG("Already in bubble"); return; @@ -321,7 +308,7 @@ void ControllablePhysicsComponent::ActivateBubbleBuff(eBubbleType bubbleType, bo Game::entityManager->SerializeEntity(m_Parent); } -void ControllablePhysicsComponent::DeactivateBubbleBuff(){ +void ControllablePhysicsComponent::DeactivateBubbleBuff() { m_DirtyBubble = true; m_IsInBubble = false; Game::entityManager->SerializeEntity(m_Parent); @@ -336,9 +323,9 @@ void ControllablePhysicsComponent::SetStunImmunity( const bool bImmuneToStunJump, const bool bImmuneToStunMove, const bool bImmuneToStunTurn, - const bool bImmuneToStunUseItem){ + const bool bImmuneToStunUseItem) { - if (state == eStateChangeType::POP){ + if (state == eStateChangeType::POP) { if (bImmuneToStunAttack && m_ImmuneToStunAttackCount > 0) m_ImmuneToStunAttackCount -= 1; if (bImmuneToStunEquip && m_ImmuneToStunEquipCount > 0) m_ImmuneToStunEquipCount -= 1; if (bImmuneToStunInteract && m_ImmuneToStunInteractCount > 0) m_ImmuneToStunInteractCount -= 1; diff --git a/dGame/dComponents/ControllablePhysicsComponent.h b/dGame/dComponents/ControllablePhysicsComponent.h index e5c3f890..8834128a 100644 --- a/dGame/dComponents/ControllablePhysicsComponent.h +++ b/dGame/dComponents/ControllablePhysicsComponent.h @@ -21,13 +21,13 @@ enum class eStateChangeType : uint32_t; */ class ControllablePhysicsComponent : public PhysicsComponent { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::CONTROLLABLE_PHYSICS; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::CONTROLLABLE_PHYSICS; ControllablePhysicsComponent(Entity* entity); ~ControllablePhysicsComponent() override; void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; void LoadFromXml(tinyxml2::XMLDocument* doc) override; void UpdateXml(tinyxml2::XMLDocument* doc) override; @@ -104,18 +104,6 @@ public: */ void SetDirtyPosition(bool val); - /** - * Mark the velocity as dirty, forcing a serializtion update next tick - * @param val whether or not the velocity is dirty - */ - void SetDirtyVelocity(bool val); - - /** - * Mark the angular velocity as dirty, forcing a serialization update next tick - * @param val whether or not the angular velocity is dirty - */ - void SetDirtyAngularVelocity(bool val); - /** * Sets whether or not the entity is currently wearing a jetpack * @param val whether or not the entity is currently wearing a jetpack @@ -186,18 +174,6 @@ public: */ const float GetGravityScale() const { return m_GravityScale; } - /** - * Sets the ignore multipliers value, allowing you to skip the serialization of speed and gravity multipliers - * @param value whether or not to ignore multipliers - */ - void SetIgnoreMultipliers(bool value) { m_IgnoreMultipliers = value; } - - /** - * Returns the current ignore multipliers value - * @return the current ignore multipliers value - */ - const bool GetIgnoreMultipliers() const { return m_IgnoreMultipliers; } - /** * Can make an entity static, making it unable to move around * @param value whether or not the entity is static @@ -310,21 +286,11 @@ private: */ dpEntity* m_dpEntity; - /** - * Whether or not the velocity is dirty, forcing a serialization of the velocity - */ - bool m_DirtyVelocity; - /** * The current velocity of the entity */ NiPoint3 m_Velocity; - /** - * Whether or not the angular velocity is dirty, forcing a serialization - */ - bool m_DirtyAngularVelocity; - /** * The current angular velocity of the entity */ @@ -375,11 +341,6 @@ private: */ bool m_DirtyCheats; - /** - * Makes it so that the speed multiplier and gravity scale are no longer serialized if false - */ - bool m_IgnoreMultipliers; - /** * Whether this entity is static, making it unable to move */ diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 64dca4f1..1b9b3285 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -81,7 +81,7 @@ DestroyableComponent::~DestroyableComponent() { } void DestroyableComponent::Reinitialize(LOT templateID) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); int32_t buffComponentID = compRegistryTable->GetByIDAndType(templateID, eReplicaComponentType::BUFF); int32_t collectibleComponentID = compRegistryTable->GetByIDAndType(templateID, eReplicaComponentType::COLLECTIBLE); @@ -92,7 +92,7 @@ void DestroyableComponent::Reinitialize(LOT templateID) { if (quickBuildComponentID > 0) componentID = quickBuildComponentID; if (buffComponentID > 0) componentID = buffComponentID; - CDDestructibleComponentTable* destCompTable = CDClientManager::Instance().GetTable(); + CDDestructibleComponentTable* destCompTable = CDClientManager::GetTable(); std::vector destCompData = destCompTable->Query([=](CDDestructibleComponent entry) { return (entry.id == componentID); }); if (componentID > 0) { @@ -122,61 +122,61 @@ void DestroyableComponent::Reinitialize(LOT templateID) { } } -void DestroyableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void DestroyableComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { if (bIsInitialUpdate) { - outBitStream->Write1(); // always write these on construction - outBitStream->Write(m_ImmuneToBasicAttackCount); - outBitStream->Write(m_ImmuneToDamageOverTimeCount); - outBitStream->Write(m_ImmuneToKnockbackCount); - outBitStream->Write(m_ImmuneToInterruptCount); - outBitStream->Write(m_ImmuneToSpeedCount); - outBitStream->Write(m_ImmuneToImaginationGainCount); - outBitStream->Write(m_ImmuneToImaginationLossCount); - outBitStream->Write(m_ImmuneToQuickbuildInterruptCount); - outBitStream->Write(m_ImmuneToPullToPointCount); + outBitStream.Write1(); // always write these on construction + outBitStream.Write(m_ImmuneToBasicAttackCount); + outBitStream.Write(m_ImmuneToDamageOverTimeCount); + outBitStream.Write(m_ImmuneToKnockbackCount); + outBitStream.Write(m_ImmuneToInterruptCount); + outBitStream.Write(m_ImmuneToSpeedCount); + outBitStream.Write(m_ImmuneToImaginationGainCount); + outBitStream.Write(m_ImmuneToImaginationLossCount); + outBitStream.Write(m_ImmuneToQuickbuildInterruptCount); + outBitStream.Write(m_ImmuneToPullToPointCount); } - outBitStream->Write(m_DirtyHealth || bIsInitialUpdate); + outBitStream.Write(m_DirtyHealth || bIsInitialUpdate); if (m_DirtyHealth || bIsInitialUpdate) { - outBitStream->Write(m_iHealth); - outBitStream->Write(m_fMaxHealth); - outBitStream->Write(m_iArmor); - outBitStream->Write(m_fMaxArmor); - outBitStream->Write(m_iImagination); - outBitStream->Write(m_fMaxImagination); + outBitStream.Write(m_iHealth); + outBitStream.Write(m_fMaxHealth); + outBitStream.Write(m_iArmor); + outBitStream.Write(m_fMaxArmor); + outBitStream.Write(m_iImagination); + outBitStream.Write(m_fMaxImagination); - outBitStream->Write(m_DamageToAbsorb); - outBitStream->Write(IsImmune()); - outBitStream->Write(m_IsGMImmune); - outBitStream->Write(m_IsShielded); + outBitStream.Write(m_DamageToAbsorb); + outBitStream.Write(IsImmune()); + outBitStream.Write(m_IsGMImmune); + outBitStream.Write(m_IsShielded); - outBitStream->Write(m_fMaxHealth); - outBitStream->Write(m_fMaxArmor); - outBitStream->Write(m_fMaxImagination); + outBitStream.Write(m_fMaxHealth); + outBitStream.Write(m_fMaxArmor); + outBitStream.Write(m_fMaxImagination); - outBitStream->Write(m_FactionIDs.size()); + outBitStream.Write(m_FactionIDs.size()); for (size_t i = 0; i < m_FactionIDs.size(); ++i) { - outBitStream->Write(m_FactionIDs[i]); + outBitStream.Write(m_FactionIDs[i]); } - outBitStream->Write(m_IsSmashable); + outBitStream.Write(m_IsSmashable); if (bIsInitialUpdate) { - outBitStream->Write(m_IsDead); - outBitStream->Write(m_IsSmashed); + outBitStream.Write(m_IsDead); + outBitStream.Write(m_IsSmashed); if (m_IsSmashable) { - outBitStream->Write(m_IsModuleAssembly); - outBitStream->Write(m_ExplodeFactor != 1.0f); - if (m_ExplodeFactor != 1.0f) outBitStream->Write(m_ExplodeFactor); + outBitStream.Write(m_IsModuleAssembly); + outBitStream.Write(m_ExplodeFactor != 1.0f); + if (m_ExplodeFactor != 1.0f) outBitStream.Write(m_ExplodeFactor); } } m_DirtyHealth = false; } - outBitStream->Write(m_DirtyThreatList || bIsInitialUpdate); + outBitStream.Write(m_DirtyThreatList || bIsInitialUpdate); if (m_DirtyThreatList || bIsInitialUpdate) { - outBitStream->Write(m_HasThreats); + outBitStream.Write(m_HasThreats); m_DirtyThreatList = false; } } @@ -251,13 +251,14 @@ void DestroyableComponent::SetMaxHealth(float value, bool playAnim) { if (playAnim) { // Now update the player bar - if (!m_Parent->GetParentUser()) return; + auto* characterComponent = m_Parent->GetComponent(); + if (!characterComponent) return; AMFArrayValue args; args.Insert("amount", std::to_string(difference)); args.Insert("type", "health"); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", args); + GameMessages::SendUIMessageServerToSingleClient(m_Parent, characterComponent->GetSystemAddress(), "MaxPlayerBarUpdate", args); } Game::entityManager->SerializeEntity(m_Parent); @@ -292,13 +293,14 @@ void DestroyableComponent::SetMaxArmor(float value, bool playAnim) { if (playAnim) { // Now update the player bar - if (!m_Parent->GetParentUser()) return; + auto* characterComponent = m_Parent->GetComponent(); + if (!characterComponent) return; AMFArrayValue args; args.Insert("amount", std::to_string(value)); args.Insert("type", "armor"); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", args); + GameMessages::SendUIMessageServerToSingleClient(m_Parent, characterComponent->GetSystemAddress(), "MaxPlayerBarUpdate", args); } Game::entityManager->SerializeEntity(m_Parent); @@ -332,13 +334,14 @@ void DestroyableComponent::SetMaxImagination(float value, bool playAnim) { if (playAnim) { // Now update the player bar - if (!m_Parent->GetParentUser()) return; + auto* characterComponent = m_Parent->GetComponent(); + if (!characterComponent) return; AMFArrayValue args; args.Insert("amount", std::to_string(difference)); args.Insert("type", "imagination"); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", args); + GameMessages::SendUIMessageServerToSingleClient(m_Parent, characterComponent->GetSystemAddress(), "MaxPlayerBarUpdate", args); } Game::entityManager->SerializeEntity(m_Parent); } @@ -782,16 +785,12 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType } Entity* zoneControl = Game::entityManager->GetZoneControlEntity(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { - script->OnPlayerDied(zoneControl, m_Parent); - } + if (zoneControl) zoneControl->GetScript()->OnPlayerDied(zoneControl, m_Parent); std::vector scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); for (Entity* scriptEntity : scriptedActs) { if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds - for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { - script->OnPlayerDied(scriptEntity, m_Parent); - } + scriptEntity->GetScript()->OnPlayerDied(scriptEntity, m_Parent); } } } diff --git a/dGame/dComponents/DestroyableComponent.h b/dGame/dComponents/DestroyableComponent.h index b81ab9f3..85a4f941 100644 --- a/dGame/dComponents/DestroyableComponent.h +++ b/dGame/dComponents/DestroyableComponent.h @@ -17,15 +17,15 @@ enum class eStateChangeType : uint32_t; * Represents the stats of an entity, for example its health, imagination and armor. Also handles factions, which * indicate which enemies this entity has. */ -class DestroyableComponent : public Component { +class DestroyableComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::DESTROYABLE; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::DESTROYABLE; DestroyableComponent(Entity* parentEntity); ~DestroyableComponent() override; void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; void LoadFromXml(tinyxml2::XMLDocument* doc) override; void UpdateXml(tinyxml2::XMLDocument* doc) override; diff --git a/dGame/dComponents/DonationVendorComponent.cpp b/dGame/dComponents/DonationVendorComponent.cpp index 6abc959a..7fb06a90 100644 --- a/dGame/dComponents/DonationVendorComponent.cpp +++ b/dGame/dComponents/DonationVendorComponent.cpp @@ -36,13 +36,13 @@ void DonationVendorComponent::SubmitDonation(uint32_t count) { m_DirtyDonationVendor = true; } -void DonationVendorComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void DonationVendorComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { VendorComponent::Serialize(outBitStream, bIsInitialUpdate); - outBitStream->Write(bIsInitialUpdate || m_DirtyDonationVendor); + outBitStream.Write(bIsInitialUpdate || m_DirtyDonationVendor); if (bIsInitialUpdate || m_DirtyDonationVendor) { - outBitStream->Write(m_PercentComplete); - outBitStream->Write(m_TotalDonated); - outBitStream->Write(m_TotalRemaining); + outBitStream.Write(m_PercentComplete); + outBitStream.Write(m_TotalDonated); + outBitStream.Write(m_TotalRemaining); if (!bIsInitialUpdate) m_DirtyDonationVendor = false; } } diff --git a/dGame/dComponents/DonationVendorComponent.h b/dGame/dComponents/DonationVendorComponent.h index d1743118..af1eb829 100644 --- a/dGame/dComponents/DonationVendorComponent.h +++ b/dGame/dComponents/DonationVendorComponent.h @@ -8,9 +8,9 @@ class Entity; class DonationVendorComponent final : public VendorComponent { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::DONATION_VENDOR; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::DONATION_VENDOR; DonationVendorComponent(Entity* parent); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; uint32_t GetActivityID() {return m_ActivityId;}; void SubmitDonation(uint32_t count); diff --git a/dGame/dComponents/GhostComponent.cpp b/dGame/dComponents/GhostComponent.cpp index 2978c912..3aea329a 100644 --- a/dGame/dComponents/GhostComponent.cpp +++ b/dGame/dComponents/GhostComponent.cpp @@ -1,14 +1,14 @@ #include "GhostComponent.h" GhostComponent::GhostComponent(Entity* parent) : Component(parent) { - m_GhostReferencePoint = NiPoint3::ZERO; - m_GhostOverridePoint = NiPoint3::ZERO; + m_GhostReferencePoint = NiPoint3Constant::ZERO; + m_GhostOverridePoint = NiPoint3Constant::ZERO; m_GhostOverride = false; } GhostComponent::~GhostComponent() { for (auto& observedEntity : m_ObservedEntities) { - if (observedEntity == 0) continue; + if (observedEntity == LWOOBJID_EMPTY) continue; auto* entity = Game::entityManager->GetGhostCandidate(observedEntity); if (!entity) continue; @@ -44,14 +44,14 @@ void GhostComponent::ConstructLimboEntities() { m_LimboConstructions.clear(); } -void GhostComponent::ObserveEntity(int32_t id) { +void GhostComponent::ObserveEntity(LWOOBJID id) { m_ObservedEntities.insert(id); } -bool GhostComponent::IsObserved(int32_t id) { +bool GhostComponent::IsObserved(LWOOBJID id) { return m_ObservedEntities.contains(id); } -void GhostComponent::GhostEntity(int32_t id) { +void GhostComponent::GhostEntity(LWOOBJID id) { m_ObservedEntities.erase(id); } diff --git a/dGame/dComponents/GhostComponent.h b/dGame/dComponents/GhostComponent.h index 5ae308a4..de0fb886 100644 --- a/dGame/dComponents/GhostComponent.h +++ b/dGame/dComponents/GhostComponent.h @@ -7,7 +7,7 @@ class NiPoint3; -class GhostComponent : public Component { +class GhostComponent final : public Component { public: static inline const eReplicaComponentType ComponentType = eReplicaComponentType::GHOST; GhostComponent(Entity* parent); @@ -33,18 +33,18 @@ public: void ConstructLimboEntities(); - void ObserveEntity(const int32_t id); + void ObserveEntity(const LWOOBJID id); - bool IsObserved(const int32_t id); + bool IsObserved(const LWOOBJID id); - void GhostEntity(const int32_t id); + void GhostEntity(const LWOOBJID id); private: NiPoint3 m_GhostReferencePoint; NiPoint3 m_GhostOverridePoint; - std::unordered_set m_ObservedEntities; + std::unordered_set m_ObservedEntities; std::unordered_set m_LimboConstructions; diff --git a/dGame/dComponents/HavokVehiclePhysicsComponent.cpp b/dGame/dComponents/HavokVehiclePhysicsComponent.cpp index 62e49a56..635830cc 100644 --- a/dGame/dComponents/HavokVehiclePhysicsComponent.cpp +++ b/dGame/dComponents/HavokVehiclePhysicsComponent.cpp @@ -2,13 +2,11 @@ #include "EntityManager.h" HavokVehiclePhysicsComponent::HavokVehiclePhysicsComponent(Entity* parent) : PhysicsComponent(parent) { - m_Velocity = NiPoint3::ZERO; - m_AngularVelocity = NiPoint3::ZERO; + m_Velocity = NiPoint3Constant::ZERO; + m_AngularVelocity = NiPoint3Constant::ZERO; m_IsOnGround = true; m_IsOnRail = false; m_DirtyPosition = true; - m_DirtyVelocity = true; - m_DirtyAngularVelocity = true; m_EndBehavior = GeneralUtils::GenerateRandomNumber(0, 7); } @@ -37,85 +35,66 @@ void HavokVehiclePhysicsComponent::SetIsOnRail(bool val) { } void HavokVehiclePhysicsComponent::SetRemoteInputInfo(const RemoteInputInfo& remoteInputInfo) { - if (m_RemoteInputInfo == remoteInputInfo) return; + if (remoteInputInfo == m_RemoteInputInfo) return; this->m_RemoteInputInfo = remoteInputInfo; - m_DirtyRemoteInput = true; + m_DirtyPosition = true; } -void HavokVehiclePhysicsComponent::SetDirtyVelocity(bool val) { - m_DirtyVelocity = val; -} - -void HavokVehiclePhysicsComponent::SetDirtyAngularVelocity(bool val) { - m_DirtyAngularVelocity = val; -} - -void HavokVehiclePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - outBitStream->Write(bIsInitialUpdate || m_DirtyPosition); +void HavokVehiclePhysicsComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + outBitStream.Write(bIsInitialUpdate || m_DirtyPosition); if (bIsInitialUpdate || m_DirtyPosition) { m_DirtyPosition = false; - outBitStream->Write(m_Position.x); - outBitStream->Write(m_Position.y); - outBitStream->Write(m_Position.z); + outBitStream.Write(m_Position.x); + outBitStream.Write(m_Position.y); + outBitStream.Write(m_Position.z); - outBitStream->Write(m_Rotation.x); - outBitStream->Write(m_Rotation.y); - outBitStream->Write(m_Rotation.z); - outBitStream->Write(m_Rotation.w); + outBitStream.Write(m_Rotation.x); + outBitStream.Write(m_Rotation.y); + outBitStream.Write(m_Rotation.z); + outBitStream.Write(m_Rotation.w); - outBitStream->Write(m_IsOnGround); - outBitStream->Write(m_IsOnRail); + outBitStream.Write(m_IsOnGround); + outBitStream.Write(m_IsOnRail); - outBitStream->Write(bIsInitialUpdate || m_DirtyVelocity); - - if (bIsInitialUpdate || m_DirtyVelocity) { - outBitStream->Write(m_Velocity.x); - outBitStream->Write(m_Velocity.y); - outBitStream->Write(m_Velocity.z); - m_DirtyVelocity = false; + bool isNotZero = m_Velocity != NiPoint3Constant::ZERO; + outBitStream.Write(isNotZero); + if (isNotZero) { + outBitStream.Write(m_Velocity.x); + outBitStream.Write(m_Velocity.y); + outBitStream.Write(m_Velocity.z); } - outBitStream->Write(bIsInitialUpdate || m_DirtyAngularVelocity); - - if (bIsInitialUpdate || m_DirtyAngularVelocity) { - outBitStream->Write(m_AngularVelocity.x); - outBitStream->Write(m_AngularVelocity.y); - outBitStream->Write(m_AngularVelocity.z); - m_DirtyAngularVelocity = false; + isNotZero = m_AngularVelocity != NiPoint3Constant::ZERO; + outBitStream.Write(isNotZero); + if (isNotZero) { + outBitStream.Write(m_AngularVelocity.x); + outBitStream.Write(m_AngularVelocity.y); + outBitStream.Write(m_AngularVelocity.z); } - outBitStream->Write0(); // local_space_info. TODO: Implement this + outBitStream.Write0(); // local_space_info. TODO: Implement this - outBitStream->Write(m_DirtyRemoteInput || bIsInitialUpdate); // remote_input_info - if (m_DirtyRemoteInput || bIsInitialUpdate) { - outBitStream->Write(m_RemoteInputInfo.m_RemoteInputX); - outBitStream->Write(m_RemoteInputInfo.m_RemoteInputY); - outBitStream->Write(m_RemoteInputInfo.m_IsPowersliding); - outBitStream->Write(m_RemoteInputInfo.m_IsModified); - m_DirtyRemoteInput = false; - } + // This structure only has this bool flag set to false if a ptr to the peVehicle is null, which we don't have + // therefore, this will always be 1, even if all the values in the structure are 0. + outBitStream.Write1(); // has remote_input_info + outBitStream.Write(m_RemoteInputInfo.m_RemoteInputX); + outBitStream.Write(m_RemoteInputInfo.m_RemoteInputY); + outBitStream.Write(m_RemoteInputInfo.m_IsPowersliding); + outBitStream.Write(m_RemoteInputInfo.m_IsModified); - outBitStream->Write(125.0f); // remote_input_ping TODO: Figure out how this should be calculated as it seems to be constant through the whole race. + + outBitStream.Write(125.0f); // remote_input_ping TODO: Figure out how this should be calculated as it seems to be constant through the whole race. if (!bIsInitialUpdate) { - outBitStream->Write0(); + outBitStream.Write0(); } } if (bIsInitialUpdate) { - outBitStream->Write(m_EndBehavior); - outBitStream->Write1(); // is input locked? + outBitStream.Write(m_EndBehavior); + outBitStream.Write1(); // is input locked? } - outBitStream->Write0(); -} - -void HavokVehiclePhysicsComponent::Update(float deltaTime) { - if (m_SoftUpdate > 5) { - Game::entityManager->SerializeEntity(m_Parent); - m_SoftUpdate = 0; - } else { - m_SoftUpdate += deltaTime; - } + outBitStream.Write0(); } diff --git a/dGame/dComponents/HavokVehiclePhysicsComponent.h b/dGame/dComponents/HavokVehiclePhysicsComponent.h index ba46f093..83eb82fe 100644 --- a/dGame/dComponents/HavokVehiclePhysicsComponent.h +++ b/dGame/dComponents/HavokVehiclePhysicsComponent.h @@ -11,13 +11,11 @@ */ class HavokVehiclePhysicsComponent : public PhysicsComponent { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::HAVOK_VEHICLE_PHYSICS; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::HAVOK_VEHICLE_PHYSICS; HavokVehiclePhysicsComponent(Entity* parentEntity); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; - - void Update(float deltaTime) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * Sets the velocity @@ -67,22 +65,16 @@ public: */ const bool GetIsOnRail() const { return m_IsOnRail; } - void SetDirtyPosition(bool val); - void SetDirtyVelocity(bool val); - void SetDirtyAngularVelocity(bool val); void SetRemoteInputInfo(const RemoteInputInfo&); private: - bool m_DirtyVelocity; NiPoint3 m_Velocity; - - bool m_DirtyAngularVelocity; NiPoint3 m_AngularVelocity; + bool m_IsOnGround; bool m_IsOnRail; float m_SoftUpdate = 0; uint32_t m_EndBehavior; RemoteInputInfo m_RemoteInputInfo; - bool m_DirtyRemoteInput; }; diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 23d5c163..161d7b91 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -14,7 +14,6 @@ #include "Character.h" #include "EntityManager.h" #include "ItemSet.h" -#include "Player.h" #include "PetComponent.h" #include "PossessorComponent.h" #include "PossessableComponent.h" @@ -56,10 +55,10 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do return; } - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); const auto componentId = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::INVENTORY); - auto* inventoryComponentTable = CDClientManager::Instance().GetTable(); + auto* inventoryComponentTable = CDClientManager::GetTable(); auto items = inventoryComponentTable->Query([=](const CDInventoryComponent entry) { return entry.id == componentId; }); auto slot = 0u; @@ -695,11 +694,11 @@ void InventoryComponent::UpdateXml(tinyxml2::XMLDocument* document) { } } -void InventoryComponent::Serialize(RakNet::BitStream* outBitStream, const bool bIsInitialUpdate) { +void InventoryComponent::Serialize(RakNet::BitStream& outBitStream, const bool bIsInitialUpdate) { if (bIsInitialUpdate || m_Dirty) { - outBitStream->Write(true); + outBitStream.Write(true); - outBitStream->Write(m_Equipped.size()); + outBitStream.Write(m_Equipped.size()); for (const auto& pair : m_Equipped) { const auto item = pair.second; @@ -708,21 +707,21 @@ void InventoryComponent::Serialize(RakNet::BitStream* outBitStream, const bool b AddItemSkills(item.lot); } - outBitStream->Write(item.id); - outBitStream->Write(item.lot); + outBitStream.Write(item.id); + outBitStream.Write(item.lot); - outBitStream->Write0(); + outBitStream.Write0(); - outBitStream->Write(item.count > 0); - if (item.count > 0) outBitStream->Write(item.count); + outBitStream.Write(item.count > 0); + if (item.count > 0) outBitStream.Write(item.count); - outBitStream->Write(item.slot != 0); - if (item.slot != 0) outBitStream->Write(item.slot); + outBitStream.Write(item.slot != 0); + if (item.slot != 0) outBitStream.Write(item.slot); - outBitStream->Write0(); + outBitStream.Write0(); bool flag = !item.config.empty(); - outBitStream->Write(flag); + outBitStream.Write(flag); if (flag) { RakNet::BitStream ldfStream; ldfStream.Write(item.config.size()); // Key count @@ -731,26 +730,26 @@ void InventoryComponent::Serialize(RakNet::BitStream* outBitStream, const bool b std::string newRocketStr = data->GetValueAsString() + ";"; GeneralUtils::ReplaceInString(newRocketStr, "+", ";"); LDFData* ldf_data = new LDFData(u"assemblyPartLOTs", GeneralUtils::ASCIIToUTF16(newRocketStr)); - ldf_data->WriteToPacket(&ldfStream); + ldf_data->WriteToPacket(ldfStream); delete ldf_data; } else { - data->WriteToPacket(&ldfStream); + data->WriteToPacket(ldfStream); } } - outBitStream->Write(ldfStream.GetNumberOfBytesUsed() + 1); - outBitStream->Write(0); // Don't compress - outBitStream->Write(ldfStream); + outBitStream.Write(ldfStream.GetNumberOfBytesUsed() + 1); + outBitStream.Write(0); // Don't compress + outBitStream.Write(ldfStream); } - outBitStream->Write1(); + outBitStream.Write1(); } m_Dirty = false; } else { - outBitStream->Write(false); + outBitStream.Write(false); } - outBitStream->Write(false); + outBitStream.Write(false); } void InventoryComponent::Update(float deltaTime) { @@ -910,11 +909,11 @@ void InventoryComponent::UnEquipItem(Item* item) { void InventoryComponent::EquipScripts(Item* equippedItem) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); if (!compRegistryTable) return; int32_t scriptComponentID = compRegistryTable->GetByIDAndType(equippedItem->GetLot(), eReplicaComponentType::SCRIPT, -1); if (scriptComponentID > -1) { - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable(); + CDScriptComponentTable* scriptCompTable = CDClientManager::GetTable(); CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); auto* itemScript = CppScripts::GetScript(m_Parent, scriptCompData.script_name); if (!itemScript) { @@ -925,11 +924,11 @@ void InventoryComponent::EquipScripts(Item* equippedItem) { } void InventoryComponent::UnequipScripts(Item* unequippedItem) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); if (!compRegistryTable) return; int32_t scriptComponentID = compRegistryTable->GetByIDAndType(unequippedItem->GetLot(), eReplicaComponentType::SCRIPT, -1); if (scriptComponentID > -1) { - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable(); + CDScriptComponentTable* scriptCompTable = CDClientManager::GetTable(); CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); auto* itemScript = CppScripts::GetScript(m_Parent, scriptCompData.script_name); if (!itemScript) { @@ -1223,7 +1222,7 @@ void InventoryComponent::SpawnPet(Item* item) { EntityInfo info{}; info.lot = item->GetLot(); info.pos = m_Parent->GetPosition(); - info.rot = NiQuaternion::IDENTITY; + info.rot = NiQuaternionConstant::IDENTITY; info.spawnerID = m_Parent->GetObjectID(); auto* pet = Game::entityManager->CreateEntity(info); @@ -1281,7 +1280,7 @@ bool InventoryComponent::IsTransferInventory(eInventoryType type) { } uint32_t InventoryComponent::FindSkill(const LOT lot) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto results = table->Query([=](const CDObjectSkills& entry) { return entry.objectTemplate == static_cast(lot); @@ -1299,8 +1298,8 @@ uint32_t InventoryComponent::FindSkill(const LOT lot) { std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip) const { std::vector buffs; if (item == nullptr) return buffs; - auto* table = CDClientManager::Instance().GetTable(); - auto* behaviors = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); + auto* behaviors = CDClientManager::GetTable(); const auto results = table->Query([=](const CDObjectSkills& entry) { return entry.objectTemplate == static_cast(item->GetLot()); diff --git a/dGame/dComponents/InventoryComponent.h b/dGame/dComponents/InventoryComponent.h index f4d38d43..8f58a523 100644 --- a/dGame/dComponents/InventoryComponent.h +++ b/dGame/dComponents/InventoryComponent.h @@ -35,14 +35,13 @@ enum class eItemType : int32_t; * of different types, each type representing a different group of items, see `eInventoryType` for a list of * inventories. */ -class InventoryComponent : public Component -{ +class InventoryComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::INVENTORY; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::INVENTORY; explicit InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document = nullptr); void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; void LoadXml(tinyxml2::XMLDocument* document); void UpdateXml(tinyxml2::XMLDocument* document) override; diff --git a/dGame/dComponents/ItemComponent.cpp b/dGame/dComponents/ItemComponent.cpp index dc413b17..799cd935 100644 --- a/dGame/dComponents/ItemComponent.cpp +++ b/dGame/dComponents/ItemComponent.cpp @@ -1,5 +1,5 @@ #include "ItemComponent.h" -void ItemComponent::Serialize(RakNet::BitStream* outBitStream, bool isConstruction) { - outBitStream->Write0(); +void ItemComponent::Serialize(RakNet::BitStream& outBitStream, bool isConstruction) { + outBitStream.Write0(); } diff --git a/dGame/dComponents/ItemComponent.h b/dGame/dComponents/ItemComponent.h index 3af6a91e..1a02ad11 100644 --- a/dGame/dComponents/ItemComponent.h +++ b/dGame/dComponents/ItemComponent.h @@ -4,13 +4,13 @@ #include "Component.h" #include "eReplicaComponentType.h" -class ItemComponent : public Component { +class ItemComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::ITEM; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::ITEM; ItemComponent(Entity* entity) : Component(entity) {} - void Serialize(RakNet::BitStream* bitStream, bool isConstruction) override; + void Serialize(RakNet::BitStream& bitStream, bool isConstruction) override; }; #endif //!__ITEMCOMPONENT__H__ diff --git a/dGame/dComponents/LUPExhibitComponent.cpp b/dGame/dComponents/LUPExhibitComponent.cpp index a312617d..00a8cf03 100644 --- a/dGame/dComponents/LUPExhibitComponent.cpp +++ b/dGame/dComponents/LUPExhibitComponent.cpp @@ -15,10 +15,10 @@ void LUPExhibitComponent::NextLUPExhibit() { Game::entityManager->SerializeEntity(m_Parent); } -void LUPExhibitComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - outBitStream->Write(m_DirtyLUPExhibit); +void LUPExhibitComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + outBitStream.Write(m_DirtyLUPExhibit); if (m_DirtyLUPExhibit) { - outBitStream->Write(m_LUPExhibits[m_LUPExhibitIndex % m_LUPExhibits.size()]); + outBitStream.Write(m_LUPExhibits[m_LUPExhibitIndex % m_LUPExhibits.size()]); if (!bIsInitialUpdate) m_DirtyLUPExhibit = false; } } diff --git a/dGame/dComponents/LUPExhibitComponent.h b/dGame/dComponents/LUPExhibitComponent.h index 47b13a17..8fd6d7ee 100644 --- a/dGame/dComponents/LUPExhibitComponent.h +++ b/dGame/dComponents/LUPExhibitComponent.h @@ -11,14 +11,14 @@ * Component that handles the LOT that is shown in the LUP exhibit in the LUP world. Works by setting a timer and * switching the LOTs around that we'd like to display. */ -class LUPExhibitComponent : public Component +class LUPExhibitComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::LUP_EXHIBIT; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::LUP_EXHIBIT; LUPExhibitComponent(Entity* parent) : Component(parent) {}; void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; void NextLUPExhibit(); private: float m_UpdateTimer = 0.0f; diff --git a/dGame/dComponents/LevelProgressionComponent.cpp b/dGame/dComponents/LevelProgressionComponent.cpp index 3a18b19c..2d3d5144 100644 --- a/dGame/dComponents/LevelProgressionComponent.cpp +++ b/dGame/dComponents/LevelProgressionComponent.cpp @@ -37,14 +37,14 @@ void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { m_CharacterVersion = static_cast(characterVersion); } -void LevelProgressionComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - outBitStream->Write(bIsInitialUpdate || m_DirtyLevelInfo); - if (bIsInitialUpdate || m_DirtyLevelInfo) outBitStream->Write(m_Level); +void LevelProgressionComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + outBitStream.Write(bIsInitialUpdate || m_DirtyLevelInfo); + if (bIsInitialUpdate || m_DirtyLevelInfo) outBitStream.Write(m_Level); m_DirtyLevelInfo = false; } void LevelProgressionComponent::HandleLevelUp() { - auto* rewardsTable = CDClientManager::Instance().GetTable(); + auto* rewardsTable = CDClientManager::GetTable(); const auto& rewards = rewardsTable->GetByLevelID(m_Level); bool rewardingItem = rewards.size() > 0; diff --git a/dGame/dComponents/LevelProgressionComponent.h b/dGame/dComponents/LevelProgressionComponent.h index 09ccec34..a27039f3 100644 --- a/dGame/dComponents/LevelProgressionComponent.h +++ b/dGame/dComponents/LevelProgressionComponent.h @@ -11,9 +11,9 @@ * */ -class LevelProgressionComponent : public Component { +class LevelProgressionComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::LEVEL_PROGRESSION; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::LEVEL_PROGRESSION; /** * Constructor for this component @@ -21,7 +21,7 @@ public: */ LevelProgressionComponent(Entity* parent); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * Save data from this componennt to character XML diff --git a/dGame/dComponents/MiniGameControlComponent.cpp b/dGame/dComponents/MiniGameControlComponent.cpp index fdd56a2c..088ee354 100644 --- a/dGame/dComponents/MiniGameControlComponent.cpp +++ b/dGame/dComponents/MiniGameControlComponent.cpp @@ -1,5 +1,5 @@ #include "MiniGameControlComponent.h" -void MiniGameControlComponent::Serialize(RakNet::BitStream* outBitStream, bool isConstruction) { - outBitStream->Write(0x40000000); +void MiniGameControlComponent::Serialize(RakNet::BitStream& outBitStream, bool isConstruction) { + outBitStream.Write(0x40000000); } diff --git a/dGame/dComponents/MiniGameControlComponent.h b/dGame/dComponents/MiniGameControlComponent.h index 06a9c24e..2cd9ac6a 100644 --- a/dGame/dComponents/MiniGameControlComponent.h +++ b/dGame/dComponents/MiniGameControlComponent.h @@ -6,10 +6,10 @@ class MiniGameControlComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::MINI_GAME_CONTROL; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::MINI_GAME_CONTROL; MiniGameControlComponent(Entity* parent) : Component(parent) {} - void Serialize(RakNet::BitStream* outBitStream, bool isConstruction); + void Serialize(RakNet::BitStream& outBitStream, bool isConstruction); }; #endif //!__MINIGAMECONTROLCOMPONENT__H__ diff --git a/dGame/dComponents/MinigameComponent.cpp b/dGame/dComponents/MinigameComponent.cpp index 6bcb985e..2174cd8a 100644 --- a/dGame/dComponents/MinigameComponent.cpp +++ b/dGame/dComponents/MinigameComponent.cpp @@ -1,5 +1,5 @@ #include "MinigameComponent.h" -void MinigameComponent::Serialize(RakNet::BitStream* outBitStream, bool isConstruction) { - outBitStream->Write(0x40000000); +void MinigameComponent::Serialize(RakNet::BitStream& outBitStream, bool isConstruction) { + outBitStream.Write(0x40000000); } diff --git a/dGame/dComponents/MissionComponent.cpp b/dGame/dComponents/MissionComponent.cpp index 7219589a..151fcf2f 100644 --- a/dGame/dComponents/MissionComponent.cpp +++ b/dGame/dComponents/MissionComponent.cpp @@ -266,7 +266,7 @@ void MissionComponent::ForceProgressValue(uint32_t missionId, uint32_t taskType, } bool MissionComponent::GetMissionInfo(uint32_t missionId, CDMissions& result) { - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionsTable = CDClientManager::GetTable(); const auto missions = missionsTable->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); @@ -320,8 +320,8 @@ const std::vector MissionComponent::LookForAchievements(eMissionTaskTy return acceptedAchievements; #else - auto* missionTasksTable = CDClientManager::Instance().GetTable(); - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionTasksTable = CDClientManager::GetTable(); + auto* missionsTable = CDClientManager::GetTable(); auto tasks = missionTasksTable->Query([=](const CDMissionTasks& entry) { return entry.taskType == static_cast(type); @@ -407,8 +407,8 @@ const std::vector& MissionComponent::QueryAchievements(eMissionTaskTyp } // Find relevent tables - auto* missionTasksTable = CDClientManager::Instance().GetTable(); - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionTasksTable = CDClientManager::GetTable(); + auto* missionsTable = CDClientManager::GetTable(); std::vector result; diff --git a/dGame/dComponents/MissionComponent.h b/dGame/dComponents/MissionComponent.h index d53db64e..866f1650 100644 --- a/dGame/dComponents/MissionComponent.h +++ b/dGame/dComponents/MissionComponent.h @@ -24,14 +24,13 @@ class AchievementCacheKey; * The mission inventory of an entity. Tracks mission state for each mission that can be accepted and allows for * progression of each of the mission task types (see eMissionTaskType). */ -class MissionComponent : public Component -{ +class MissionComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::MISSION; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::MISSION; explicit MissionComponent(Entity* parent); ~MissionComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags); + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate, unsigned int& flags); void LoadFromXml(tinyxml2::XMLDocument* doc) override; void UpdateXml(tinyxml2::XMLDocument* doc) override; diff --git a/dGame/dComponents/MissionOfferComponent.cpp b/dGame/dComponents/MissionOfferComponent.cpp index 25d4a739..7f26ed72 100644 --- a/dGame/dComponents/MissionOfferComponent.cpp +++ b/dGame/dComponents/MissionOfferComponent.cpp @@ -40,7 +40,7 @@ bool OfferedMission::GetAcceptsMission() const { //------------------------ MissionOfferComponent below ------------------------ MissionOfferComponent::MissionOfferComponent(Entity* parent, const LOT parentLot) : Component(parent) { - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); auto value = compRegistryTable->GetByIDAndType(parentLot, eReplicaComponentType::MISSION_OFFER, -1); @@ -48,7 +48,7 @@ MissionOfferComponent::MissionOfferComponent(Entity* parent, const LOT parentLot const uint32_t componentId = value; // Now lookup the missions in the MissionNPCComponent table - auto* missionNpcComponentTable = CDClientManager::Instance().GetTable(); + auto* missionNpcComponentTable = CDClientManager::GetTable(); auto missions = missionNpcComponentTable->Query([=](const CDMissionNPCComponent& entry) { return entry.id == static_cast(componentId); diff --git a/dGame/dComponents/MissionOfferComponent.h b/dGame/dComponents/MissionOfferComponent.h index 0f0d23ba..d842a92e 100644 --- a/dGame/dComponents/MissionOfferComponent.h +++ b/dGame/dComponents/MissionOfferComponent.h @@ -59,9 +59,9 @@ private: /** * Allows entities to offer missions to other entities, depending on their mission inventory progression. */ -class MissionOfferComponent : public Component { +class MissionOfferComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::MISSION_OFFER; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::MISSION_OFFER; MissionOfferComponent(Entity* parent, LOT parentLot); diff --git a/dGame/dComponents/ModelComponent.cpp b/dGame/dComponents/ModelComponent.cpp index 3f8858c0..75f2a019 100644 --- a/dGame/dComponents/ModelComponent.cpp +++ b/dGame/dComponents/ModelComponent.cpp @@ -14,26 +14,26 @@ ModelComponent::ModelComponent(Entity* parent) : Component(parent) { m_userModelID = m_Parent->GetVarAs(u"userModelID"); } -void ModelComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void ModelComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { // ItemComponent Serialization. Pets do not get this serialization. if (!m_Parent->HasComponent(eReplicaComponentType::PET)) { - outBitStream->Write1(); - outBitStream->Write(m_userModelID != LWOOBJID_EMPTY ? m_userModelID : m_Parent->GetObjectID()); - outBitStream->Write(0); - outBitStream->Write0(); + outBitStream.Write1(); + outBitStream.Write(m_userModelID != LWOOBJID_EMPTY ? m_userModelID : m_Parent->GetObjectID()); + outBitStream.Write(0); + outBitStream.Write0(); } //actual model component: - outBitStream->Write1(); // Yes we are writing model info - outBitStream->Write0(); // Is pickable - outBitStream->Write(2); // Physics type - outBitStream->Write(m_OriginalPosition); // Original position - outBitStream->Write(m_OriginalRotation); // Original rotation + outBitStream.Write1(); // Yes we are writing model info + outBitStream.Write0(); // Is pickable + outBitStream.Write(2); // Physics type + outBitStream.Write(m_OriginalPosition); // Original position + outBitStream.Write(m_OriginalRotation); // Original rotation - outBitStream->Write1(); // We are writing behavior info - outBitStream->Write(0); // Number of behaviors - outBitStream->Write1(); // Is this model paused - if (bIsInitialUpdate) outBitStream->Write0(); // We are not writing model editing info + outBitStream.Write1(); // We are writing behavior info + outBitStream.Write(0); // Number of behaviors + outBitStream.Write1(); // Is this model paused + if (bIsInitialUpdate) outBitStream.Write0(); // We are not writing model editing info } void ModelComponent::UpdatePendingBehaviorId(const int32_t newId) { diff --git a/dGame/dComponents/ModelComponent.h b/dGame/dComponents/ModelComponent.h index a36328be..dc6810eb 100644 --- a/dGame/dComponents/ModelComponent.h +++ b/dGame/dComponents/ModelComponent.h @@ -22,13 +22,13 @@ class MoveToInventoryMessage; /** * Component that represents entities that are a model, e.g. collectible models and BBB models. */ -class ModelComponent : public Component { +class ModelComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::MODEL; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::MODEL; ModelComponent(Entity* parent); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * Returns the original position of the model @@ -61,7 +61,7 @@ public: * @param args the arguments of the message to be deserialized */ template - void HandleControlBehaviorsMsg(AMFArrayValue* args) { + void HandleControlBehaviorsMsg(const AMFArrayValue& args) { static_assert(std::is_base_of_v, "Msg must be a BehaviorMessageBase"); Msg msg(args); for (auto& behavior : m_Behaviors) { diff --git a/dGame/dComponents/ModuleAssemblyComponent.cpp b/dGame/dComponents/ModuleAssemblyComponent.cpp index 5b7042df..e217d9b7 100644 --- a/dGame/dComponents/ModuleAssemblyComponent.cpp +++ b/dGame/dComponents/ModuleAssemblyComponent.cpp @@ -46,20 +46,20 @@ const std::u16string& ModuleAssemblyComponent::GetAssemblyPartsLOTs() const { return m_AssemblyPartsLOTs; } -void ModuleAssemblyComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void ModuleAssemblyComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { if (bIsInitialUpdate) { - outBitStream->Write1(); + outBitStream.Write1(); - outBitStream->Write(m_SubKey != LWOOBJID_EMPTY); + outBitStream.Write(m_SubKey != LWOOBJID_EMPTY); if (m_SubKey != LWOOBJID_EMPTY) { - outBitStream->Write(m_SubKey); + outBitStream.Write(m_SubKey); } - outBitStream->Write(m_UseOptionalParts); + outBitStream.Write(m_UseOptionalParts); - outBitStream->Write(m_AssemblyPartsLOTs.size()); + outBitStream.Write(m_AssemblyPartsLOTs.size()); for (char16_t character : m_AssemblyPartsLOTs) { - outBitStream->Write(character); + outBitStream.Write(character); } } } diff --git a/dGame/dComponents/ModuleAssemblyComponent.h b/dGame/dComponents/ModuleAssemblyComponent.h index 9e7301fe..7e050ec7 100644 --- a/dGame/dComponents/ModuleAssemblyComponent.h +++ b/dGame/dComponents/ModuleAssemblyComponent.h @@ -10,14 +10,14 @@ * same as having said items in your inventory (the subkey for this component) this component is the one that * renders the entity into the world. */ -class ModuleAssemblyComponent : public Component { +class ModuleAssemblyComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::MODULE_ASSEMBLY; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::MODULE_ASSEMBLY; ModuleAssemblyComponent(Entity* parent); ~ModuleAssemblyComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; void Update(float deltaTime) override; /** diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index 1966638d..8377031a 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -16,6 +16,8 @@ #include "CDComponentsRegistryTable.h" #include "CDPhysicsComponentTable.h" +#include "dNavMesh.h" + namespace { /** * Cache of all lots and their respective speeds @@ -41,7 +43,7 @@ MovementAIComponent::MovementAIComponent(Entity* parent, MovementAIInfo info) : m_NextWaypoint = m_Parent->GetPosition(); m_Acceleration = 0.4f; m_PullingToPoint = false; - m_PullPoint = NiPoint3::ZERO; + m_PullPoint = NiPoint3Constant::ZERO; m_HaltDistance = 0; m_TimeToTravel = 0; m_TimeTravelled = 0; @@ -86,7 +88,7 @@ void MovementAIComponent::Update(const float deltaTime) { SetPosition(source); - NiPoint3 velocity = NiPoint3::ZERO; + NiPoint3 velocity = NiPoint3Constant::ZERO; if (m_Acceleration > 0 && m_BaseSpeed > 0 && AdvanceWaypointIndex()) // Do we have another waypoint to seek? { @@ -169,8 +171,8 @@ NiPoint3 MovementAIComponent::ApproximateLocation() const { auto approximation = source + ((destination - source) * percentageToWaypoint); - if (dpWorld::Instance().IsLoaded()) { - approximation.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(approximation); + if (dpWorld::IsLoaded()) { + approximation.y = dpWorld::GetNavMesh()->GetHeightAtPoint(approximation); } return approximation; @@ -181,8 +183,8 @@ bool MovementAIComponent::Warp(const NiPoint3& point) { NiPoint3 destination = point; - if (dpWorld::Instance().IsLoaded()) { - destination.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(point); + if (dpWorld::IsLoaded()) { + destination.y = dpWorld::GetNavMesh()->GetHeightAtPoint(point); if (std::abs(destination.y - point.y) > 3) { return false; @@ -201,7 +203,7 @@ void MovementAIComponent::Stop() { SetPosition(ApproximateLocation()); - SetVelocity(NiPoint3::ZERO); + SetVelocity(NiPoint3Constant::ZERO); m_TimeToTravel = 0; m_TimeTravelled = 0; @@ -242,8 +244,8 @@ float MovementAIComponent::GetBaseSpeed(LOT lot) { return it->second; } - CDComponentsRegistryTable* componentRegistryTable = CDClientManager::Instance().GetTable(); - CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentRegistryTable = CDClientManager::GetTable(); + CDPhysicsComponentTable* physicsComponentTable = CDClientManager::GetTable(); int32_t componentID; CDPhysicsComponent* physicsComponent = nullptr; @@ -302,8 +304,8 @@ void MovementAIComponent::SetDestination(const NiPoint3& destination) { } std::vector computedPath; - if (dpWorld::Instance().IsLoaded()) { - computedPath = dpWorld::Instance().GetNavMesh()->GetPath(m_Parent->GetPosition(), destination, m_Info.wanderSpeed); + if (dpWorld::IsLoaded()) { + computedPath = dpWorld::GetNavMesh()->GetPath(m_Parent->GetPosition(), destination, m_Info.wanderSpeed); } // Somehow failed @@ -328,8 +330,8 @@ void MovementAIComponent::SetDestination(const NiPoint3& destination) { // Simply path for (auto& point : computedPath) { - if (dpWorld::Instance().IsLoaded()) { - point.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(point); + if (dpWorld::IsLoaded()) { + point.y = dpWorld::GetNavMesh()->GetHeightAtPoint(point); } m_InterpolatedWaypoints.push_back(point); diff --git a/dGame/dComponents/MovementAIComponent.h b/dGame/dComponents/MovementAIComponent.h index 0ae71dc6..852f7001 100644 --- a/dGame/dComponents/MovementAIComponent.h +++ b/dGame/dComponents/MovementAIComponent.h @@ -55,9 +55,9 @@ struct MovementAIInfo { * Component that handles the movement settings of an entity. Not to be confused with the BaseCombatAI component that * actually handles attackig and following enemy entities. */ -class MovementAIComponent : public Component { +class MovementAIComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::MOVEMENT_AI; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::MOVEMENT_AI; MovementAIComponent(Entity* parentEntity, MovementAIInfo info); diff --git a/dGame/dComponents/MovingPlatformComponent.cpp b/dGame/dComponents/MovingPlatformComponent.cpp index 366bebd3..77acbb8d 100644 --- a/dGame/dComponents/MovingPlatformComponent.cpp +++ b/dGame/dComponents/MovingPlatformComponent.cpp @@ -32,25 +32,25 @@ MoverSubComponent::MoverSubComponent(const NiPoint3& startPos) { MoverSubComponent::~MoverSubComponent() = default; -void MoverSubComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - outBitStream->Write(true); +void MoverSubComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + outBitStream.Write(true); - outBitStream->Write(mState); - outBitStream->Write(mDesiredWaypointIndex); - outBitStream->Write(mShouldStopAtDesiredWaypoint); - outBitStream->Write(mInReverse); + outBitStream.Write(mState); + outBitStream.Write(mDesiredWaypointIndex); + outBitStream.Write(mShouldStopAtDesiredWaypoint); + outBitStream.Write(mInReverse); - outBitStream->Write(mPercentBetweenPoints); + outBitStream.Write(mPercentBetweenPoints); - outBitStream->Write(mPosition.x); - outBitStream->Write(mPosition.y); - outBitStream->Write(mPosition.z); + outBitStream.Write(mPosition.x); + outBitStream.Write(mPosition.y); + outBitStream.Write(mPosition.z); - outBitStream->Write(mCurrentWaypointIndex); - outBitStream->Write(mNextWaypointIndex); + outBitStream.Write(mCurrentWaypointIndex); + outBitStream.Write(mNextWaypointIndex); - outBitStream->Write(mIdleTimeElapsed); - outBitStream->Write(0.0f); // Move time elapsed + outBitStream.Write(mIdleTimeElapsed); + outBitStream.Write(0.0f); // Move time elapsed } //------------- MovingPlatformComponent below -------------- @@ -71,43 +71,43 @@ MovingPlatformComponent::~MovingPlatformComponent() { delete static_cast(m_MoverSubComponent); } -void MovingPlatformComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void MovingPlatformComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { // Here we don't serialize the moving platform to let the client simulate the movement if (!m_Serialize) { - outBitStream->Write(false); - outBitStream->Write(false); + outBitStream.Write(false); + outBitStream.Write(false); return; } - outBitStream->Write(true); + outBitStream.Write(true); auto hasPath = !m_PathingStopped && !m_PathName.empty(); - outBitStream->Write(hasPath); + outBitStream.Write(hasPath); if (hasPath) { // Is on rail - outBitStream->Write1(); + outBitStream.Write1(); - outBitStream->Write(m_PathName.size()); + outBitStream.Write(m_PathName.size()); for (const auto& c : m_PathName) { - outBitStream->Write(c); + outBitStream.Write(c); } // Starting point - outBitStream->Write(0); + outBitStream.Write(0); // Reverse - outBitStream->Write(false); + outBitStream.Write(false); } const auto hasPlatform = m_MoverSubComponent != nullptr; - outBitStream->Write(hasPlatform); + outBitStream.Write(hasPlatform); if (hasPlatform) { auto* mover = static_cast(m_MoverSubComponent); - outBitStream->Write(m_MoverSubComponentType); + outBitStream.Write(m_MoverSubComponentType); if (m_MoverSubComponentType == eMoverSubComponentType::simpleMover) { // TODO @@ -162,7 +162,7 @@ void MovingPlatformComponent::StartPathing() { const auto& nextWaypoint = m_Path->pathWaypoints[subComponent->mNextWaypointIndex]; subComponent->mPosition = currentWaypoint.position; - subComponent->mSpeed = currentWaypoint.movingPlatform.speed; + subComponent->mSpeed = currentWaypoint.speed; subComponent->mWaitTime = currentWaypoint.movingPlatform.wait; targetPosition = nextWaypoint.position; @@ -183,9 +183,7 @@ void MovingPlatformComponent::StartPathing() { const auto travelNext = subComponent->mWaitTime + travelTime; m_Parent->AddCallbackTimer(travelTime, [subComponent, this] { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnWaypointReached(m_Parent, subComponent->mNextWaypointIndex); - } + this->m_Parent->GetScript()->OnWaypointReached(m_Parent, subComponent->mNextWaypointIndex); }); m_Parent->AddCallbackTimer(travelNext, [this] { @@ -213,7 +211,7 @@ void MovingPlatformComponent::ContinuePathing() { const auto& nextWaypoint = m_Path->pathWaypoints[subComponent->mNextWaypointIndex]; subComponent->mPosition = currentWaypoint.position; - subComponent->mSpeed = currentWaypoint.movingPlatform.speed; + subComponent->mSpeed = currentWaypoint.speed; subComponent->mWaitTime = currentWaypoint.movingPlatform.wait; // + 2; pathSize = m_Path->pathWaypoints.size() - 1; @@ -295,9 +293,7 @@ void MovingPlatformComponent::ContinuePathing() { const auto travelNext = subComponent->mWaitTime + travelTime; m_Parent->AddCallbackTimer(travelTime, [subComponent, this] { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnWaypointReached(m_Parent, subComponent->mNextWaypointIndex); - } + this->m_Parent->GetScript()->OnWaypointReached(m_Parent, subComponent->mNextWaypointIndex); }); m_Parent->AddCallbackTimer(travelNext, [this] { diff --git a/dGame/dComponents/MovingPlatformComponent.h b/dGame/dComponents/MovingPlatformComponent.h index bb5821d4..c4fbf308 100644 --- a/dGame/dComponents/MovingPlatformComponent.h +++ b/dGame/dComponents/MovingPlatformComponent.h @@ -38,7 +38,7 @@ public: MoverSubComponent(const NiPoint3& startPos); ~MoverSubComponent(); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate); + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate); /** * The state the platform is currently in @@ -104,14 +104,14 @@ public: * don't at all do what you expect them to as we don't instruct the client of changes made here. * ^^^ Trivia: This made the red blocks platform and property platforms a pain to implement. */ -class MovingPlatformComponent : public Component { +class MovingPlatformComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::MOVING_PLATFORM; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::MOVING_PLATFORM; MovingPlatformComponent(Entity* parent, const std::string& pathName); ~MovingPlatformComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * Stops all pathing, called when an entity starts a quick build associated with this platform diff --git a/dGame/dComponents/MultiZoneEntranceComponent.h b/dGame/dComponents/MultiZoneEntranceComponent.h index c65dc0fe..8928be27 100644 --- a/dGame/dComponents/MultiZoneEntranceComponent.h +++ b/dGame/dComponents/MultiZoneEntranceComponent.h @@ -8,9 +8,9 @@ * Component that handles the LUP/WBL rocket launchpad that can be interacted with to travel to WBL worlds. * */ -class MultiZoneEntranceComponent : public Component { +class MultiZoneEntranceComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::MULTI_ZONE_ENTRANCE; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::MULTI_ZONE_ENTRANCE; /** * Constructor for this component, builds the m_LUPWorlds vector diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index bddfd009..a6bb00fb 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -30,6 +30,7 @@ #include "eObjectBits.h" #include "eGameMasterLevel.h" #include "eMissionState.h" +#include "dNavMesh.h" std::unordered_map PetComponent::buildCache{}; std::unordered_map PetComponent::currentActivities{}; @@ -70,7 +71,7 @@ std::map PetComponent::petFlags = { }; PetComponent::PetComponent(Entity* parentEntity, uint32_t componentId) : Component{ parentEntity } { - m_PetInfo = CDClientManager::Instance().GetTable()->GetByID(componentId); // TODO: Make reference when safe + m_PetInfo = CDClientManager::GetTable()->GetByID(componentId); // TODO: Make reference when safe m_ComponentId = componentId; m_Interaction = LWOOBJID_EMPTY; @@ -83,7 +84,7 @@ PetComponent::PetComponent(Entity* parentEntity, uint32_t componentId) : Compone m_DatabaseId = LWOOBJID_EMPTY; m_Status = 67108866; // Tamable m_Ability = ePetAbilityType::Invalid; - m_StartPosition = NiPoint3::ZERO; + m_StartPosition = NiPoint3Constant::ZERO; m_MovementAI = nullptr; m_TresureTime = 0; m_Preconditions = nullptr; @@ -95,42 +96,42 @@ PetComponent::PetComponent(Entity* parentEntity, uint32_t componentId) : Compone } } -void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void PetComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { const bool tamed = m_Owner != LWOOBJID_EMPTY; - outBitStream->Write1(); // Always serialize as dirty for now + outBitStream.Write1(); // Always serialize as dirty for now - outBitStream->Write(m_Status); - outBitStream->Write(tamed ? m_Ability : ePetAbilityType::Invalid); // Something with the overhead icon? + outBitStream.Write(m_Status); + outBitStream.Write(tamed ? m_Ability : ePetAbilityType::Invalid); // Something with the overhead icon? const bool interacting = m_Interaction != LWOOBJID_EMPTY; - outBitStream->Write(interacting); + outBitStream.Write(interacting); if (interacting) { - outBitStream->Write(m_Interaction); + outBitStream.Write(m_Interaction); } - outBitStream->Write(tamed); + outBitStream.Write(tamed); if (tamed) { - outBitStream->Write(m_Owner); + outBitStream.Write(m_Owner); } if (bIsInitialUpdate) { - outBitStream->Write(tamed); + outBitStream.Write(tamed); if (tamed) { - outBitStream->Write(m_ModerationStatus); + outBitStream.Write(m_ModerationStatus); const auto nameData = GeneralUtils::UTF8ToUTF16(m_Name); const auto ownerNameData = GeneralUtils::UTF8ToUTF16(m_OwnerName); - outBitStream->Write(nameData.size()); + outBitStream.Write(nameData.size()); for (const auto c : nameData) { - outBitStream->Write(c); + outBitStream.Write(c); } - outBitStream->Write(ownerNameData.size()); + outBitStream.Write(ownerNameData.size()); for (const auto c : ownerNameData) { - outBitStream->Write(c); + outBitStream.Write(c); } } } @@ -250,17 +251,17 @@ void PetComponent::OnUse(Entity* originator) { NiPoint3 forward = NiQuaternion::LookAt(m_Parent->GetPosition(), originator->GetPosition()).GetForwardVector(); forward.y = 0; - if (dpWorld::Instance().IsLoaded()) { + if (dpWorld::IsLoaded()) { NiPoint3 attempt = petPosition + forward * interactionDistance; - float y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(attempt); + float y = dpWorld::GetNavMesh()->GetHeightAtPoint(attempt); while (std::abs(y - petPosition.y) > 4 && interactionDistance > 10) { const NiPoint3 forward = m_Parent->GetRotation().GetForwardVector(); attempt = originatorPosition + forward * interactionDistance; - y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(attempt); + y = dpWorld::GetNavMesh()->GetHeightAtPoint(attempt); interactionDistance -= 0.5f; } @@ -305,13 +306,11 @@ void PetComponent::OnUse(Entity* originator) { currentActivities.insert_or_assign(m_Tamer, m_Parent->GetObjectID()); // Notify the start of a pet taming minigame - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, originator, ePetTamingNotifyType::BEGIN); - } + m_Parent->GetScript()->OnNotifyPetTamingMinigame(m_Parent, originator, ePetTamingNotifyType::BEGIN); } void PetComponent::Update(float deltaTime) { - if (m_StartPosition == NiPoint3::ZERO) { + if (m_StartPosition == NiPoint3Constant::ZERO) { m_StartPosition = m_Parent->GetPosition(); } @@ -446,7 +445,7 @@ void PetComponent::Update(float deltaTime) { if (distance < 5 * 5) { m_Interaction = closestTresure->GetObjectID(); - Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 1, 202, true); + Command(NiPoint3Constant::ZERO, LWOOBJID_EMPTY, 1, 202, true); m_TresureTime = 2; } else if (distance < 10 * 10) { @@ -530,7 +529,7 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) { EntityInfo info{}; info.lot = cached->second.puzzleModelLot; info.pos = position; - info.rot = NiQuaternion::IDENTITY; + info.rot = NiQuaternionConstant::IDENTITY; info.spawnerID = tamer->GetObjectID(); auto* modelEntity = Game::entityManager->CreateEntity(info); @@ -590,9 +589,9 @@ void PetComponent::NotifyTamingBuildSuccess(NiPoint3 position) { LWOOBJID_EMPTY, false, ePetTamingNotifyType::NAMINGPET, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, + NiPoint3Constant::ZERO, + NiPoint3Constant::ZERO, + NiQuaternionConstant::IDENTITY, UNASSIGNED_SYSTEM_ADDRESS ); @@ -670,9 +669,9 @@ void PetComponent::RequestSetPetName(std::u16string name) { m_Tamer, false, ePetTamingNotifyType::SUCCESS, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, + NiPoint3Constant::ZERO, + NiPoint3Constant::ZERO, + NiQuaternionConstant::IDENTITY, UNASSIGNED_SYSTEM_ADDRESS ); @@ -689,9 +688,7 @@ void PetComponent::RequestSetPetName(std::u16string name) { m_Tamer = LWOOBJID_EMPTY; // Notify the end of a pet taming minigame - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, tamer, ePetTamingNotifyType::SUCCESS); - } + m_Parent->GetScript()->OnNotifyPetTamingMinigame(m_Parent, tamer, ePetTamingNotifyType::SUCCESS); } void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) { @@ -711,9 +708,9 @@ void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) { m_Tamer, false, ePetTamingNotifyType::QUIT, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, + NiPoint3Constant::ZERO, + NiPoint3Constant::ZERO, + NiQuaternionConstant::IDENTITY, UNASSIGNED_SYSTEM_ADDRESS ); @@ -730,9 +727,7 @@ void PetComponent::ClientExitTamingMinigame(bool voluntaryExit) { Game::entityManager->SerializeEntity(m_Parent); // Notify the end of a pet taming minigame - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, tamer, ePetTamingNotifyType::QUIT); - } + m_Parent->GetScript()->OnNotifyPetTamingMinigame(m_Parent, tamer, ePetTamingNotifyType::QUIT); } void PetComponent::StartTimer() { @@ -762,9 +757,9 @@ void PetComponent::ClientFailTamingMinigame() { m_Tamer, false, ePetTamingNotifyType::FAILED, - NiPoint3::ZERO, - NiPoint3::ZERO, - NiQuaternion::IDENTITY, + NiPoint3Constant::ZERO, + NiPoint3Constant::ZERO, + NiQuaternionConstant::IDENTITY, UNASSIGNED_SYSTEM_ADDRESS ); @@ -781,9 +776,7 @@ void PetComponent::ClientFailTamingMinigame() { Game::entityManager->SerializeEntity(m_Parent); // Notify the end of a pet taming minigame - for (CppScripts::Script* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnNotifyPetTamingMinigame(m_Parent, tamer, ePetTamingNotifyType::FAILED); - } + m_Parent->GetScript()->OnNotifyPetTamingMinigame(m_Parent, tamer, ePetTamingNotifyType::FAILED); } void PetComponent::Wander() { @@ -812,8 +805,8 @@ void PetComponent::Wander() { auto destination = m_StartPosition + delta; - if (dpWorld::Instance().IsLoaded()) { - destination.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(destination); + if (dpWorld::IsLoaded()) { + destination.y = dpWorld::GetNavMesh()->GetHeightAtPoint(destination); } if (Vector3::DistanceSquared(destination, m_MovementAI->GetParent()->GetPosition()) < 2 * 2) { diff --git a/dGame/dComponents/PetComponent.h b/dGame/dComponents/PetComponent.h index 24ee157b..f4198cae 100644 --- a/dGame/dComponents/PetComponent.h +++ b/dGame/dComponents/PetComponent.h @@ -13,15 +13,15 @@ * Represents an entity that is a pet. This pet can be tamed and consequently follows the tamer around, allowing it * to dig for treasure and activate pet bouncers. */ -class PetComponent : public Component +class PetComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::PET; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::PET; explicit PetComponent(Entity* parentEntity, uint32_t componentId); ~PetComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; void Update(float deltaTime) override; /** @@ -353,7 +353,6 @@ private: /** * Pet information loaded from the CDClientDatabase - * TODO: Switch to a reference when safe to do so */ CDPetComponent m_PetInfo; }; diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index 6248bfe9..276184b1 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -143,10 +143,10 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : PhysicsCompon */ if (!m_HasCreatedPhysics) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::PHANTOM_PHYSICS); - CDPhysicsComponentTable* physComp = CDClientManager::Instance().GetTable(); + CDPhysicsComponentTable* physComp = CDClientManager::GetTable(); if (physComp == nullptr) return; @@ -156,89 +156,48 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : PhysicsCompon //temp test if (info->physicsAsset == "miscellaneous\\misc_phys_10x1x5.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 10.0f, 5.0f, 1.0f); - - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - - dpWorld::Instance().AddEntity(m_dpEntity); } else if (info->physicsAsset == "miscellaneous\\misc_phys_640x640.hkx") { - // Move this down by 13.521004 units so it is still effectively at the same height as before - m_Position = m_Position - NiPoint3::UNIT_Y * 13.521004f; // TODO Fix physics simulation to do simulation at high velocities due to bullet through paper problem... m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 1638.4f, 13.521004f * 2.0f, 1638.4f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - - dpWorld::Instance().AddEntity(m_dpEntity); + // Move this down by 13.521004 units so it is still effectively at the same height as before + m_Position = m_Position - NiPoint3Constant::UNIT_Y * 13.521004f; } else if (info->physicsAsset == "env\\trigger_wall_tall.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 10.0f, 25.0f, 1.0f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - dpWorld::Instance().AddEntity(m_dpEntity); } else if (info->physicsAsset == "env\\env_gen_placeholderphysics.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 20.0f, 20.0f, 20.0f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - dpWorld::Instance().AddEntity(m_dpEntity); } else if (info->physicsAsset == "env\\POI_trigger_wall.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 1.0f, 12.5f, 20.0f); // Not sure what the real size is - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - dpWorld::Instance().AddEntity(m_dpEntity); } else if (info->physicsAsset == "env\\NG_NinjaGo\\env_ng_gen_gate_chamber_puzzle_ceiling_tile_falling_phantom.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 18.0f, 5.0f, 15.0f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position + m_Rotation.GetForwardVector() * 7.5f); - dpWorld::Instance().AddEntity(m_dpEntity); + m_Position += m_Rotation.GetForwardVector() * 7.5f; } else if (info->physicsAsset == "env\\NG_NinjaGo\\ng_flamejet_brick_phantom.HKX") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 1.0f, 1.0f, 12.0f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position + m_Rotation.GetForwardVector() * 6.0f); - dpWorld::Instance().AddEntity(m_dpEntity); + m_Position += m_Rotation.GetForwardVector() * 6.0f; } else if (info->physicsAsset == "env\\Ring_Trigger.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 6.0f, 6.0f, 6.0f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - dpWorld::Instance().AddEntity(m_dpEntity); } else if (info->physicsAsset == "env\\vfx_propertyImaginationBall.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 4.5f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - dpWorld::Instance().AddEntity(m_dpEntity); } else if (info->physicsAsset == "env\\env_won_fv_gas-blocking-volume.hkx") { m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 390.496826f, 111.467964f, 600.821534f, true); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); m_Position.y -= (111.467964f * m_Scale) / 2; - m_dpEntity->SetPosition(m_Position); - dpWorld::Instance().AddEntity(m_dpEntity); } else { - //LOG("This one is supposed to have %s", info->physicsAsset.c_str()); + // LOG_DEBUG("This one is supposed to have %s", info->physicsAsset.c_str()); //add fallback cube: m_dpEntity = new dpEntity(m_Parent->GetObjectID(), 2.0f, 2.0f, 2.0f); - m_dpEntity->SetScale(m_Scale); - m_dpEntity->SetRotation(m_Rotation); - m_dpEntity->SetPosition(m_Position); - dpWorld::Instance().AddEntity(m_dpEntity); } - + + m_dpEntity->SetScale(m_Scale); + m_dpEntity->SetRotation(m_Rotation); + m_dpEntity->SetPosition(m_Position); + dpWorld::AddEntity(m_dpEntity); } } PhantomPhysicsComponent::~PhantomPhysicsComponent() { if (m_dpEntity) { - dpWorld::Instance().RemoveEntity(m_dpEntity); + dpWorld::RemoveEntity(m_dpEntity); } } @@ -260,10 +219,10 @@ void PhantomPhysicsComponent::CreatePhysics() { y = m_Parent->GetVar(u"primitiveModelValueY"); z = m_Parent->GetVar(u"primitiveModelValueZ"); } else { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::PHANTOM_PHYSICS); - CDPhysicsComponentTable* physComp = CDClientManager::Instance().GetTable(); + CDPhysicsComponentTable* physComp = CDClientManager::GetTable(); if (physComp == nullptr) return; @@ -300,35 +259,35 @@ void PhantomPhysicsComponent::CreatePhysics() { m_dpEntity->SetPosition({ m_Position.x, m_Position.y - (height / 2), m_Position.z }); - dpWorld::Instance().AddEntity(m_dpEntity); + dpWorld::AddEntity(m_dpEntity); m_HasCreatedPhysics = true; } -void PhantomPhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void PhantomPhysicsComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { PhysicsComponent::Serialize(outBitStream, bIsInitialUpdate); - outBitStream->Write(m_EffectInfoDirty || bIsInitialUpdate); + outBitStream.Write(m_EffectInfoDirty || bIsInitialUpdate); if (m_EffectInfoDirty || bIsInitialUpdate) { - outBitStream->Write(m_IsPhysicsEffectActive); + outBitStream.Write(m_IsPhysicsEffectActive); if (m_IsPhysicsEffectActive) { - outBitStream->Write(m_EffectType); - outBitStream->Write(m_DirectionalMultiplier); + outBitStream.Write(m_EffectType); + outBitStream.Write(m_DirectionalMultiplier); // forgive me father for i have sinned - outBitStream->Write0(); - //outBitStream->Write(m_MinMax); + outBitStream.Write0(); + //outBitStream.Write(m_MinMax); //if (m_MinMax) { - //outBitStream->Write(m_Min); - //outBitStream->Write(m_Max); + //outBitStream.Write(m_Min); + //outBitStream.Write(m_Max); //} - outBitStream->Write(m_IsDirectional); + outBitStream.Write(m_IsDirectional); if (m_IsDirectional) { - outBitStream->Write(m_Direction.x); - outBitStream->Write(m_Direction.y); - outBitStream->Write(m_Direction.z); + outBitStream.Write(m_Direction.x); + outBitStream.Write(m_Direction.y); + outBitStream.Write(m_Direction.z); } } diff --git a/dGame/dComponents/PhantomPhysicsComponent.h b/dGame/dComponents/PhantomPhysicsComponent.h index 5fcee004..1aae9527 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.h +++ b/dGame/dComponents/PhantomPhysicsComponent.h @@ -25,14 +25,14 @@ enum class ePhysicsEffectType : uint32_t ; * trigger gameplay events, for example the bus in Avant Gardens that moves around when the player touches its physics * body. Optionally this object can also have effects, like the fans in AG. */ -class PhantomPhysicsComponent : public PhysicsComponent { +class PhantomPhysicsComponent final : public PhysicsComponent { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::PHANTOM_PHYSICS; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::PHANTOM_PHYSICS; PhantomPhysicsComponent(Entity* parent); ~PhantomPhysicsComponent() override; void Update(float deltaTime) override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * Creates the physics shape for this entity based on LDF data diff --git a/dGame/dComponents/PhysicsComponent.cpp b/dGame/dComponents/PhysicsComponent.cpp index a66c422a..3a84c4ce 100644 --- a/dGame/dComponents/PhysicsComponent.cpp +++ b/dGame/dComponents/PhysicsComponent.cpp @@ -1,21 +1,21 @@ #include "PhysicsComponent.h" PhysicsComponent::PhysicsComponent(Entity* parent) : Component(parent) { - m_Position = NiPoint3::ZERO; - m_Rotation = NiQuaternion::IDENTITY; + m_Position = NiPoint3Constant::ZERO; + m_Rotation = NiQuaternionConstant::IDENTITY; m_DirtyPosition = false; } -void PhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - outBitStream->Write(bIsInitialUpdate || m_DirtyPosition); +void PhysicsComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + outBitStream.Write(bIsInitialUpdate || m_DirtyPosition); if (bIsInitialUpdate || m_DirtyPosition) { - outBitStream->Write(m_Position.x); - outBitStream->Write(m_Position.y); - outBitStream->Write(m_Position.z); - outBitStream->Write(m_Rotation.x); - outBitStream->Write(m_Rotation.y); - outBitStream->Write(m_Rotation.z); - outBitStream->Write(m_Rotation.w); + outBitStream.Write(m_Position.x); + outBitStream.Write(m_Position.y); + outBitStream.Write(m_Position.z); + outBitStream.Write(m_Rotation.x); + outBitStream.Write(m_Rotation.y); + outBitStream.Write(m_Rotation.z); + outBitStream.Write(m_Rotation.w); if (!bIsInitialUpdate) m_DirtyPosition = false; } } diff --git a/dGame/dComponents/PhysicsComponent.h b/dGame/dComponents/PhysicsComponent.h index c1a7f34a..71f52e54 100644 --- a/dGame/dComponents/PhysicsComponent.h +++ b/dGame/dComponents/PhysicsComponent.h @@ -14,7 +14,7 @@ public: PhysicsComponent(Entity* parent); virtual ~PhysicsComponent() = default; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; const NiPoint3& GetPosition() const { return m_Position; } virtual void SetPosition(const NiPoint3& pos) { if (m_Position == pos) return; m_Position = pos; m_DirtyPosition = true; } diff --git a/dGame/dComponents/PlayerForcedMovementComponent.cpp b/dGame/dComponents/PlayerForcedMovementComponent.cpp index d511ad78..0aea882c 100644 --- a/dGame/dComponents/PlayerForcedMovementComponent.cpp +++ b/dGame/dComponents/PlayerForcedMovementComponent.cpp @@ -6,11 +6,11 @@ PlayerForcedMovementComponent::PlayerForcedMovementComponent(Entity* parent) : C PlayerForcedMovementComponent::~PlayerForcedMovementComponent() {} -void PlayerForcedMovementComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - outBitStream->Write(m_DirtyInfo || bIsInitialUpdate); +void PlayerForcedMovementComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + outBitStream.Write(m_DirtyInfo || bIsInitialUpdate); if (m_DirtyInfo || bIsInitialUpdate) { - outBitStream->Write(m_PlayerOnRail); - outBitStream->Write(m_ShowBillboard); + outBitStream.Write(m_PlayerOnRail); + outBitStream.Write(m_ShowBillboard); } m_DirtyInfo = false; } diff --git a/dGame/dComponents/PlayerForcedMovementComponent.h b/dGame/dComponents/PlayerForcedMovementComponent.h index 810b727c..f184ede2 100644 --- a/dGame/dComponents/PlayerForcedMovementComponent.h +++ b/dGame/dComponents/PlayerForcedMovementComponent.h @@ -8,9 +8,9 @@ * Component that handles player forced movement * */ -class PlayerForcedMovementComponent : public Component { +class PlayerForcedMovementComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::PLAYER_FORCED_MOVEMENT; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::PLAYER_FORCED_MOVEMENT; /** * Constructor for this component @@ -19,7 +19,7 @@ public: PlayerForcedMovementComponent(Entity* parent); ~PlayerForcedMovementComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * @brief Set the Player On Rail object diff --git a/dGame/dComponents/PossessableComponent.cpp b/dGame/dComponents/PossessableComponent.cpp index 509b1a07..ae5b05b3 100644 --- a/dGame/dComponents/PossessableComponent.cpp +++ b/dGame/dComponents/PossessableComponent.cpp @@ -27,17 +27,17 @@ PossessableComponent::PossessableComponent(Entity* parent, uint32_t componentId) result.finalize(); } -void PossessableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - outBitStream->Write(m_DirtyPossessable || bIsInitialUpdate); +void PossessableComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + outBitStream.Write(m_DirtyPossessable || bIsInitialUpdate); if (m_DirtyPossessable || bIsInitialUpdate) { m_DirtyPossessable = false; // reset flag - outBitStream->Write(m_Possessor != LWOOBJID_EMPTY); - if (m_Possessor != LWOOBJID_EMPTY) outBitStream->Write(m_Possessor); + outBitStream.Write(m_Possessor != LWOOBJID_EMPTY); + if (m_Possessor != LWOOBJID_EMPTY) outBitStream.Write(m_Possessor); - outBitStream->Write(m_AnimationFlag != eAnimationFlags::IDLE_NONE); - if (m_AnimationFlag != eAnimationFlags::IDLE_NONE) outBitStream->Write(m_AnimationFlag); + outBitStream.Write(m_AnimationFlag != eAnimationFlags::IDLE_NONE); + if (m_AnimationFlag != eAnimationFlags::IDLE_NONE) outBitStream.Write(m_AnimationFlag); - outBitStream->Write(m_ImmediatelyDepossess); + outBitStream.Write(m_ImmediatelyDepossess); m_ImmediatelyDepossess = false; // reset flag } } diff --git a/dGame/dComponents/PossessableComponent.h b/dGame/dComponents/PossessableComponent.h index 9a767ba9..6f1968a5 100644 --- a/dGame/dComponents/PossessableComponent.h +++ b/dGame/dComponents/PossessableComponent.h @@ -12,13 +12,13 @@ * Represents an entity that can be controlled by some other entity, generally used by cars to indicate that some * player is controlling it. */ -class PossessableComponent : public Component { +class PossessableComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::POSSESSABLE; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::POSSESSABLE; PossessableComponent(Entity* parentEntity, uint32_t componentId); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * @brief mounts the Entity diff --git a/dGame/dComponents/PossessorComponent.cpp b/dGame/dComponents/PossessorComponent.cpp index 0cb64956..46ccbffb 100644 --- a/dGame/dComponents/PossessorComponent.cpp +++ b/dGame/dComponents/PossessorComponent.cpp @@ -26,15 +26,15 @@ PossessorComponent::~PossessorComponent() { } } -void PossessorComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - outBitStream->Write(m_DirtyPossesor || bIsInitialUpdate); +void PossessorComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + outBitStream.Write(m_DirtyPossesor || bIsInitialUpdate); if (m_DirtyPossesor || bIsInitialUpdate) { m_DirtyPossesor = false; - outBitStream->Write(m_Possessable != LWOOBJID_EMPTY); + outBitStream.Write(m_Possessable != LWOOBJID_EMPTY); if (m_Possessable != LWOOBJID_EMPTY) { - outBitStream->Write(m_Possessable); + outBitStream.Write(m_Possessable); } - outBitStream->Write(m_PossessableType); + outBitStream.Write(m_PossessableType); } } diff --git a/dGame/dComponents/PossessorComponent.h b/dGame/dComponents/PossessorComponent.h index c225766b..3fa6153d 100644 --- a/dGame/dComponents/PossessorComponent.h +++ b/dGame/dComponents/PossessorComponent.h @@ -16,14 +16,14 @@ enum class ePossessionType : uint8_t { /** * Represents an entity that can posess other entities. Generally used by players to drive a car. */ -class PossessorComponent : public Component { +class PossessorComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::POSSESSOR; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::POSSESSOR; PossessorComponent(Entity* parent); ~PossessorComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * @brief Mounts the entity diff --git a/dGame/dComponents/PropertyComponent.cpp b/dGame/dComponents/PropertyComponent.cpp deleted file mode 100644 index 4f8df40c..00000000 --- a/dGame/dComponents/PropertyComponent.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include "PropertyComponent.h" -#include "GameMessages.h" -#include "dZoneManager.h" - -PropertyComponent::PropertyComponent(Entity* parent) : Component(parent) { - m_PropertyName = parent->GetVar(u"propertyName"); - m_PropertyState = new PropertyState(); -} - -PropertyComponent::~PropertyComponent() = default; - diff --git a/dGame/dComponents/PropertyComponent.h b/dGame/dComponents/PropertyComponent.h index 135a1d26..1085aac4 100644 --- a/dGame/dComponents/PropertyComponent.h +++ b/dGame/dComponents/PropertyComponent.h @@ -1,34 +1,22 @@ /* * Darkflame Universe - * Copyright 2018 + * Copyright 2024 */ #ifndef PROPERTYCOMPONENT_H #define PROPERTYCOMPONENT_H -#include "BitStream.h" #include "Entity.h" #include "Component.h" #include "eReplicaComponentType.h" -struct PropertyState { - LWOOBJID ownerID; - LWOOBJID propertyID; - bool rented; -}; - /** * This component is unused and has no functionality */ -class PropertyComponent : public Component { +class PropertyComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::PROPERTY; - explicit PropertyComponent(Entity* parentEntity); - ~PropertyComponent() override; - [[nodiscard]] PropertyState* GetPropertyState() const { return m_PropertyState; }; -private: - PropertyState* m_PropertyState; - std::string m_PropertyName; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::PROPERTY; + explicit PropertyComponent(Entity* const parentEntity) noexcept : Component{ parentEntity } {} }; -#endif // PROPERTYCOMPONENT_H +#endif // !PROPERTYCOMPONENT_H diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index 2bb6ea30..ab3bb5da 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -18,7 +18,7 @@ PropertyEntranceComponent::PropertyEntranceComponent(Entity* parent, uint32_t componentID) : Component(parent) { this->propertyQueries = {}; - auto table = CDClientManager::Instance().GetTable(); + auto table = CDClientManager::GetTable(); const auto& entry = table->GetByID(componentID); this->m_MapID = entry.mapID; diff --git a/dGame/dComponents/PropertyEntranceComponent.h b/dGame/dComponents/PropertyEntranceComponent.h index ef8f9810..510bb489 100644 --- a/dGame/dComponents/PropertyEntranceComponent.h +++ b/dGame/dComponents/PropertyEntranceComponent.h @@ -11,10 +11,10 @@ /** * Represents the launch pad that's used to select and browse properties */ -class PropertyEntranceComponent : public Component { +class PropertyEntranceComponent final : public Component { public: explicit PropertyEntranceComponent(Entity* parent, uint32_t componentID); - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::PROPERTY_ENTRANCE; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::PROPERTY_ENTRANCE; /** * Handles an OnUse request for some other entity, rendering the property browse menu diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index dff1e5da..2acc6a5d 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -14,7 +14,6 @@ #include "Item.h" #include "Database.h" #include "ObjectIDManager.h" -#include "Player.h" #include "RocketLaunchpadControlComponent.h" #include "PropertyEntranceComponent.h" #include "InventoryComponent.h" @@ -177,8 +176,6 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) { auto* entity = Game::entityManager->GetEntity(playerId); - auto* user = entity->GetParentUser(); - auto character = entity->GetCharacter(); if (!character) return false; @@ -217,9 +214,7 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) { Database::Get()->InsertNewProperty(info, templateId, worldId); auto* zoneControlObject = Game::zoneManager->GetZoneControlObject(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControlObject)) { - script->OnZonePropertyRented(zoneControlObject, entity); - } + if (zoneControlObject) zoneControlObject->GetScript()->OnZonePropertyRented(zoneControlObject, entity); return true; } @@ -297,7 +292,7 @@ void PropertyManagementComponent::UpdateModelPosition(const LWOOBJID id, const N const auto modelLOT = item->GetLot(); - if (rotation != NiQuaternion::IDENTITY) { + if (rotation != NiQuaternionConstant::IDENTITY) { rotation = { rotation.w, rotation.z, rotation.y, rotation.x }; } @@ -481,7 +476,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet GameMessages::SendGetModelsOnProperty(entity->GetObjectID(), GetModels(), UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), NiPoint3::ZERO, LWOOBJID_EMPTY, 16, NiQuaternion::IDENTITY); + GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), NiPoint3Constant::ZERO, LWOOBJID_EMPTY, 16, NiQuaternionConstant::IDENTITY); if (spawner != nullptr) { Game::zoneManager->RemoveSpawner(spawner->m_Info.spawnerID); @@ -534,7 +529,7 @@ void PropertyManagementComponent::DeleteModel(const LWOOBJID id, const int delet GameMessages::SendGetModelsOnProperty(entity->GetObjectID(), GetModels(), UNASSIGNED_SYSTEM_ADDRESS); - GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), NiPoint3::ZERO, LWOOBJID_EMPTY, 16, NiQuaternion::IDENTITY); + GameMessages::SendPlaceModelResponse(entity->GetObjectID(), entity->GetSystemAddress(), NiPoint3Constant::ZERO, LWOOBJID_EMPTY, 16, NiQuaternionConstant::IDENTITY); if (spawner != nullptr) { Game::zoneManager->RemoveSpawner(spawner->m_Info.spawnerID); diff --git a/dGame/dComponents/PropertyManagementComponent.h b/dGame/dComponents/PropertyManagementComponent.h index d38437c4..6a9ed09d 100644 --- a/dGame/dComponents/PropertyManagementComponent.h +++ b/dGame/dComponents/PropertyManagementComponent.h @@ -8,8 +8,7 @@ /** * Information regarding which players may visit this property */ -enum class PropertyPrivacyOption -{ +enum class PropertyPrivacyOption { /** * Default, only you can visit your property */ @@ -29,10 +28,9 @@ enum class PropertyPrivacyOption /** * Main component that handles interactions with a property, generally the plaques you see on properties. */ -class PropertyManagementComponent : public Component -{ +class PropertyManagementComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::PROPERTY_MANAGEMENT; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::PROPERTY_MANAGEMENT; PropertyManagementComponent(Entity* parent); static PropertyManagementComponent* Instance(); diff --git a/dGame/dComponents/PropertyVendorComponent.h b/dGame/dComponents/PropertyVendorComponent.h index 0e6c6521..fee8af9c 100644 --- a/dGame/dComponents/PropertyVendorComponent.h +++ b/dGame/dComponents/PropertyVendorComponent.h @@ -7,10 +7,9 @@ /** * The property guard that stands on a property before it's claimed, allows entities to attempt claiming this property. */ -class PropertyVendorComponent : public Component -{ +class PropertyVendorComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::PROPERTY_VENDOR; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::PROPERTY_VENDOR; explicit PropertyVendorComponent(Entity* parent); /** diff --git a/dGame/dComponents/ProximityMonitorComponent.cpp b/dGame/dComponents/ProximityMonitorComponent.cpp index acc93fde..fbac8ddb 100644 --- a/dGame/dComponents/ProximityMonitorComponent.cpp +++ b/dGame/dComponents/ProximityMonitorComponent.cpp @@ -18,7 +18,7 @@ ProximityMonitorComponent::~ProximityMonitorComponent() { for (const auto& en : m_ProximitiesData) { if (!en.second) continue; - dpWorld::Instance().RemoveEntity(en.second); + dpWorld::RemoveEntity(en.second); } m_ProximitiesData.clear(); @@ -28,12 +28,12 @@ void ProximityMonitorComponent::SetProximityRadius(float proxRadius, const std:: dpEntity* en = new dpEntity(m_Parent->GetObjectID(), proxRadius); en->SetPosition(m_Parent->GetPosition()); - dpWorld::Instance().AddEntity(en); + dpWorld::AddEntity(en); m_ProximitiesData.insert(std::make_pair(name, en)); } void ProximityMonitorComponent::SetProximityRadius(dpEntity* entity, const std::string& name) { - dpWorld::Instance().AddEntity(entity); + dpWorld::AddEntity(entity); entity->SetPosition(m_Parent->GetPosition()); m_ProximitiesData.insert(std::make_pair(name, entity)); } diff --git a/dGame/dComponents/ProximityMonitorComponent.h b/dGame/dComponents/ProximityMonitorComponent.h index 90ba7d54..512b2848 100644 --- a/dGame/dComponents/ProximityMonitorComponent.h +++ b/dGame/dComponents/ProximityMonitorComponent.h @@ -17,9 +17,9 @@ * Utility component for detecting how close entities are to named proximities for this entity. Allows you to store * proximity checks for multiple ojects. */ -class ProximityMonitorComponent : public Component { +class ProximityMonitorComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::PROXIMITY_MONITOR; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::PROXIMITY_MONITOR; ProximityMonitorComponent(Entity* parentEntity, int smallRadius = -1, int largeRadius = -1); ~ProximityMonitorComponent() override; diff --git a/dGame/dComponents/QuickBuildComponent.cpp b/dGame/dComponents/QuickBuildComponent.cpp index b8aec2bd..e3aed82d 100644 --- a/dGame/dComponents/QuickBuildComponent.cpp +++ b/dGame/dComponents/QuickBuildComponent.cpp @@ -23,7 +23,7 @@ #include "CppScripts.h" -QuickBuildComponent::QuickBuildComponent(Entity* entity) : Component(entity) { +QuickBuildComponent::QuickBuildComponent(Entity* const entity) : Component{ entity } { std::u16string checkPreconditions = entity->GetVar(u"CheckPrecondition"); if (!checkPreconditions.empty()) { @@ -33,10 +33,9 @@ QuickBuildComponent::QuickBuildComponent(Entity* entity) : Component(entity) { // Should a setting that has the build activator position exist, fetch that setting here and parse it for position. // It is assumed that the user who sets this setting uses the correct character delimiter (character 31 or in hex 0x1F) auto positionAsVector = GeneralUtils::SplitString(m_Parent->GetVarAsString(u"rebuild_activators"), 0x1F); - if (positionAsVector.size() == 3 && - GeneralUtils::TryParse(positionAsVector[0], m_ActivatorPosition.x) && - GeneralUtils::TryParse(positionAsVector[1], m_ActivatorPosition.y) && - GeneralUtils::TryParse(positionAsVector[2], m_ActivatorPosition.z)) { + const auto activatorPositionValid = GeneralUtils::TryParse(positionAsVector); + if (positionAsVector.size() == 3 && activatorPositionValid) { + m_ActivatorPosition = activatorPositionValid.value(); } else { LOG("Failed to find activator position for lot %i. Defaulting to parents position.", m_Parent->GetLOT()); m_ActivatorPosition = m_Parent->GetPosition(); @@ -56,55 +55,55 @@ QuickBuildComponent::~QuickBuildComponent() { DespawnActivator(); } -void QuickBuildComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void QuickBuildComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { if (m_Parent->GetComponent(eReplicaComponentType::DESTROYABLE) == nullptr) { if (bIsInitialUpdate) { - outBitStream->Write(false); + outBitStream.Write(false); } - outBitStream->Write(false); + outBitStream.Write(false); - outBitStream->Write(false); + outBitStream.Write(false); } // If build state is completed and we've already serialized once in the completed state, // don't serializing this component anymore as this will cause the build to jump again. // If state changes, serialization will begin again. if (!m_StateDirty && m_State == eQuickBuildState::COMPLETED) { - outBitStream->Write0(); - outBitStream->Write0(); + outBitStream.Write0(); + outBitStream.Write0(); return; } // BEGIN Scripted Activity - outBitStream->Write1(); + outBitStream.Write1(); Entity* builder = GetBuilder(); if (builder) { - outBitStream->Write(1); - outBitStream->Write(builder->GetObjectID()); + outBitStream.Write(1); + outBitStream.Write(builder->GetObjectID()); for (int i = 0; i < 10; i++) { - outBitStream->Write(0.0f); + outBitStream.Write(0.0f); } } else { - outBitStream->Write(0); + outBitStream.Write(0); } // END Scripted Activity - outBitStream->Write1(); + outBitStream.Write1(); - outBitStream->Write(m_State); + outBitStream.Write(m_State); - outBitStream->Write(m_ShowResetEffect); - outBitStream->Write(m_Activator != nullptr); + outBitStream.Write(m_ShowResetEffect); + outBitStream.Write(m_Activator != nullptr); - outBitStream->Write(m_Timer); - outBitStream->Write(m_TimerIncomplete); + outBitStream.Write(m_Timer); + outBitStream.Write(m_TimerIncomplete); if (bIsInitialUpdate) { - outBitStream->Write(false); - outBitStream->Write(m_ActivatorPosition); - outBitStream->Write(m_RepositionPlayer); + outBitStream.Write(false); + outBitStream.Write(m_ActivatorPosition); + outBitStream.Write(m_RepositionPlayer); } m_StateDirty = false; } @@ -253,13 +252,13 @@ void QuickBuildComponent::OnUse(Entity* originator) { } void QuickBuildComponent::SpawnActivator() { - if (!m_SelfActivator || m_ActivatorPosition != NiPoint3::ZERO) { + if (!m_SelfActivator || m_ActivatorPosition != NiPoint3Constant::ZERO) { if (!m_Activator) { EntityInfo info; info.lot = 6604; info.spawnerID = m_Parent->GetObjectID(); - info.pos = m_ActivatorPosition == NiPoint3::ZERO ? m_Parent->GetPosition() : m_ActivatorPosition; + info.pos = m_ActivatorPosition == NiPoint3Constant::ZERO ? m_Parent->GetPosition() : m_ActivatorPosition; m_Activator = Game::entityManager->CreateEntity(info, nullptr, m_Parent); if (m_Activator) { @@ -284,73 +283,73 @@ void QuickBuildComponent::DespawnActivator() { } } -Entity* QuickBuildComponent::GetActivator() { +Entity* QuickBuildComponent::GetActivator() const { return Game::entityManager->GetEntity(m_ActivatorId); } -NiPoint3 QuickBuildComponent::GetActivatorPosition() { +NiPoint3 QuickBuildComponent::GetActivatorPosition() const noexcept { return m_ActivatorPosition; } -float QuickBuildComponent::GetResetTime() { +float QuickBuildComponent::GetResetTime() const noexcept { return m_ResetTime; } -float QuickBuildComponent::GetCompleteTime() { +float QuickBuildComponent::GetCompleteTime() const noexcept { return m_CompleteTime; } -int QuickBuildComponent::GetTakeImagination() { +int32_t QuickBuildComponent::GetTakeImagination() const noexcept { return m_TakeImagination; } -bool QuickBuildComponent::GetInterruptible() { +bool QuickBuildComponent::GetInterruptible() const noexcept { return m_Interruptible; } -bool QuickBuildComponent::GetSelfActivator() { +bool QuickBuildComponent::GetSelfActivator() const noexcept { return m_SelfActivator; } -std::vector QuickBuildComponent::GetCustomModules() { +std::vector QuickBuildComponent::GetCustomModules() const noexcept { return m_CustomModules; } -int QuickBuildComponent::GetActivityId() { +int32_t QuickBuildComponent::GetActivityId() const noexcept { return m_ActivityId; } -int QuickBuildComponent::GetPostImaginationCost() { +int32_t QuickBuildComponent::GetPostImaginationCost() const noexcept { return m_PostImaginationCost; } -float QuickBuildComponent::GetTimeBeforeSmash() { +float QuickBuildComponent::GetTimeBeforeSmash() const noexcept { return m_TimeBeforeSmash; } -eQuickBuildState QuickBuildComponent::GetState() { +eQuickBuildState QuickBuildComponent::GetState() const noexcept { return m_State; } Entity* QuickBuildComponent::GetBuilder() const { - auto* builder = Game::entityManager->GetEntity(m_Builder); + auto* const builder = Game::entityManager->GetEntity(m_Builder); return builder; } -bool QuickBuildComponent::GetRepositionPlayer() const { +bool QuickBuildComponent::GetRepositionPlayer() const noexcept { return m_RepositionPlayer; } -void QuickBuildComponent::SetActivatorPosition(NiPoint3 value) { +void QuickBuildComponent::SetActivatorPosition(const NiPoint3& value) noexcept { m_ActivatorPosition = value; } -void QuickBuildComponent::SetResetTime(float value) { +void QuickBuildComponent::SetResetTime(const float value) noexcept { m_ResetTime = value; } -void QuickBuildComponent::SetCompleteTime(float value) { +void QuickBuildComponent::SetCompleteTime(const float value) noexcept { if (value < 0) { m_CompleteTime = 4.5f; } else { @@ -358,31 +357,31 @@ void QuickBuildComponent::SetCompleteTime(float value) { } } -void QuickBuildComponent::SetTakeImagination(int value) { +void QuickBuildComponent::SetTakeImagination(const int32_t value) noexcept { m_TakeImagination = value; } -void QuickBuildComponent::SetInterruptible(bool value) { +void QuickBuildComponent::SetInterruptible(const bool value) noexcept { m_Interruptible = value; } -void QuickBuildComponent::SetSelfActivator(bool value) { +void QuickBuildComponent::SetSelfActivator(const bool value) noexcept { m_SelfActivator = value; } -void QuickBuildComponent::SetCustomModules(std::vector value) { +void QuickBuildComponent::SetCustomModules(const std::vector& value) noexcept { m_CustomModules = value; } -void QuickBuildComponent::SetActivityId(int value) { +void QuickBuildComponent::SetActivityId(const int32_t value) noexcept { m_ActivityId = value; } -void QuickBuildComponent::SetPostImaginationCost(int value) { +void QuickBuildComponent::SetPostImaginationCost(const int32_t value) noexcept { m_PostImaginationCost = value; } -void QuickBuildComponent::SetTimeBeforeSmash(float value) { +void QuickBuildComponent::SetTimeBeforeSmash(const float value) noexcept { if (value < 0) { m_TimeBeforeSmash = 10.0f; } else { @@ -390,11 +389,11 @@ void QuickBuildComponent::SetTimeBeforeSmash(float value) { } } -void QuickBuildComponent::SetRepositionPlayer(bool value) { +void QuickBuildComponent::SetRepositionPlayer(const bool value) noexcept { m_RepositionPlayer = value; } -void QuickBuildComponent::StartQuickBuild(Entity* user) { +void QuickBuildComponent::StartQuickBuild(Entity* const user) { if (m_State == eQuickBuildState::OPEN || m_State == eQuickBuildState::COMPLETED || m_State == eQuickBuildState::INCOMPLETE) { m_Builder = user->GetObjectID(); @@ -415,22 +414,18 @@ void QuickBuildComponent::StartQuickBuild(Entity* user) { movingPlatform->OnQuickBuildInitilized(); } - for (auto* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnQuickBuildStart(m_Parent, user); - } + auto* script = m_Parent->GetScript(); + script->OnQuickBuildStart(m_Parent, user); // Notify scripts and possible subscribers - for (auto* script : CppScripts::GetEntityScripts(m_Parent)) - script->OnQuickBuildNotifyState(m_Parent, m_State); + script->OnQuickBuildNotifyState(m_Parent, m_State); for (const auto& cb : m_QuickBuildStateCallbacks) cb(m_State); } } -void QuickBuildComponent::CompleteQuickBuild(Entity* user) { - if (user == nullptr) { - return; - } +void QuickBuildComponent::CompleteQuickBuild(Entity* const user) { + if (!user) return; auto* characterComponent = user->GetComponent(); if (characterComponent != nullptr) { @@ -488,10 +483,9 @@ void QuickBuildComponent::CompleteQuickBuild(Entity* user) { } // Notify scripts - for (auto* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnQuickBuildComplete(m_Parent, user); - script->OnQuickBuildNotifyState(m_Parent, m_State); - } + auto* script = m_Parent->GetScript(); + script->OnQuickBuildComplete(m_Parent, user); + script->OnQuickBuildNotifyState(m_Parent, m_State); // Notify subscribers for (const auto& callback : m_QuickBuildStateCallbacks) @@ -519,7 +513,7 @@ void QuickBuildComponent::CompleteQuickBuild(Entity* user) { RenderComponent::PlayAnimation(user, u"rebuild-celebrate", 1.09f); } -void QuickBuildComponent::ResetQuickBuild(bool failed) { +void QuickBuildComponent::ResetQuickBuild(const bool failed) { Entity* builder = GetBuilder(); if (m_State == eQuickBuildState::BUILDING && builder) { @@ -542,8 +536,7 @@ void QuickBuildComponent::ResetQuickBuild(bool failed) { Game::entityManager->SerializeEntity(m_Parent); // Notify scripts and possible subscribers - for (auto* script : CppScripts::GetEntityScripts(m_Parent)) - script->OnQuickBuildNotifyState(m_Parent, m_State); + m_Parent->GetScript()->OnQuickBuildNotifyState(m_Parent, m_State); for (const auto& cb : m_QuickBuildStateCallbacks) cb(m_State); @@ -554,7 +547,7 @@ void QuickBuildComponent::ResetQuickBuild(bool failed) { } } -void QuickBuildComponent::CancelQuickBuild(Entity* entity, eQuickBuildFailReason failReason, bool skipChecks) { +void QuickBuildComponent::CancelQuickBuild(Entity* const entity, const eQuickBuildFailReason failReason, const bool skipChecks) { if (m_State != eQuickBuildState::COMPLETED || skipChecks) { m_Builder = LWOOBJID_EMPTY; @@ -574,17 +567,14 @@ void QuickBuildComponent::CancelQuickBuild(Entity* entity, eQuickBuildFailReason m_StateDirty = true; // Notify scripts and possible subscribers - for (auto* script : CppScripts::GetEntityScripts(m_Parent)) - script->OnQuickBuildNotifyState(m_Parent, m_State); + m_Parent->GetScript()->OnQuickBuildNotifyState(m_Parent, m_State); for (const auto& cb : m_QuickBuildStateCallbacks) cb(m_State); Game::entityManager->SerializeEntity(m_Parent); } - if (entity == nullptr) { - return; - } + if (!entity) return; CharacterComponent* characterComponent = entity->GetComponent(); if (characterComponent) { diff --git a/dGame/dComponents/QuickBuildComponent.h b/dGame/dComponents/QuickBuildComponent.h index f1106a61..1cab8660 100644 --- a/dGame/dComponents/QuickBuildComponent.h +++ b/dGame/dComponents/QuickBuildComponent.h @@ -20,14 +20,14 @@ enum class eQuickBuildFailReason : uint32_t; * consists of an activator that shows a popup and then the actual entity that the bricks are built into. Note * that quick builds are also scripted activities so this shared some logic with the ScriptedActivityComponent. */ -class QuickBuildComponent : public Component { +class QuickBuildComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::QUICK_BUILD; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::QUICK_BUILD; - QuickBuildComponent(Entity* entity); + QuickBuildComponent(Entity* const entity); ~QuickBuildComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; void Update(float deltaTime) override; /** @@ -50,148 +50,148 @@ public: * Returns the entity that acts as the activator for this quickbuild * @return the entity that acts as the activator for this quickbuild */ - Entity* GetActivator(); + [[nodiscard]] Entity* GetActivator() const; /** * Returns the spawn position of the activator for this quickbuild, if any * @return the spawn position of the activator for this quickbuild, if any */ - NiPoint3 GetActivatorPosition(); + [[nodiscard]] NiPoint3 GetActivatorPosition() const noexcept; /** * Sets the spawn position for the activator of this quickbuild * @param value the spawn position to set for the activator */ - void SetActivatorPosition(NiPoint3 value); + void SetActivatorPosition(const NiPoint3& value) noexcept; /** * Returns the time it takes for the quickbuild to reset after being built * @return the time it takes for the quickbuild to reset after being built */ - float GetResetTime(); + [[nodiscard]] float GetResetTime() const noexcept; /** * Sets the time it takes for the quickbuild to reset after being built * @param value the reset time to set */ - void SetResetTime(float value); + void SetResetTime(const float value) noexcept; /** * Returns the time it takes to complete the quickbuild * @return the time it takes to complete the quickbuild */ - float GetCompleteTime(); + [[nodiscard]] float GetCompleteTime() const noexcept; /** * Sets the time it takes to complete the quickbuild * @param value the completion time to set */ - void SetCompleteTime(float value); + void SetCompleteTime(const float value) noexcept; /** * Returns the imagination that's taken when completing the quickbuild * @return the imagination that's taken when completing the quickbuild */ - int GetTakeImagination(); + [[nodiscard]] int32_t GetTakeImagination() const noexcept; /** * Sets the imagination that's taken when completing the quickbuild * @param value the imagination deduction to set */ - void SetTakeImagination(int value); + void SetTakeImagination(const int32_t value) noexcept; /** * Returns if the quickbuild can be interrupted, currently unused * @return if the quickbuild can be interrupted */ - bool GetInterruptible(); + [[nodiscard]] bool GetInterruptible() const noexcept; /** * Sets whether or not the quickbuild can be interrupted, currently unused * @param value true if the quickbuild may be interrupted, false otherwise */ - void SetInterruptible(bool value); + void SetInterruptible(const bool value) noexcept; /** * Returns whether or not this entity contains a built-in activator * @return whether or not this entity contains a built-in activator */ - bool GetSelfActivator(); + [[nodiscard]] bool GetSelfActivator() const noexcept; /** * Sets whether or not this entity contains a built-in activator. If set to false this will spawn activators on * each new quickbuild. * @param value whether or not this entity contains a built-in activator */ - void SetSelfActivator(bool value); + void SetSelfActivator(const bool value) noexcept; /** * Currently unused */ - std::vector GetCustomModules(); + [[nodiscard]] std::vector GetCustomModules() const noexcept; /** * Currently unused */ - void SetCustomModules(std::vector value); + void SetCustomModules(const std::vector& value) noexcept; /** * Returns the activity ID for participating in this quickbuild * @return the activity ID for participating in this quickbuild */ - int GetActivityId(); + [[nodiscard]] int32_t GetActivityId() const noexcept; /** * Sets the activity ID for participating in this quickbuild * @param value the activity ID to set */ - void SetActivityId(int value); + void SetActivityId(const int32_t value) noexcept; /** * Currently unused */ - int GetPostImaginationCost(); + [[nodiscard]] int32_t GetPostImaginationCost() const noexcept; /** * Currently unused */ - void SetPostImaginationCost(int value); + void SetPostImaginationCost(const int32_t value) noexcept; /** * Returns the time it takes for an incomplete quickbuild to be smashed automatically * @return the time it takes for an incomplete quickbuild to be smashed automatically */ - float GetTimeBeforeSmash(); + [[nodiscard]] float GetTimeBeforeSmash() const noexcept; /** * Sets the time it takes for an incomplete quickbuild to be smashed automatically * @param value the time to set */ - void SetTimeBeforeSmash(float value); + void SetTimeBeforeSmash(const float value) noexcept; /** * Returns the current quickbuild state * @return the current quickbuild state */ - eQuickBuildState GetState(); + [[nodiscard]] eQuickBuildState GetState() const noexcept; /** * Returns the player that is currently building this quickbuild * @return the player that is currently building this quickbuild */ - Entity* GetBuilder() const; + [[nodiscard]] Entity* GetBuilder() const; /** * Returns whether or not the player is repositioned when initiating the quickbuild * @return whether or not the player is repositioned when initiating the quickbuild */ - bool GetRepositionPlayer() const; + [[nodiscard]] bool GetRepositionPlayer() const noexcept; /** * Sets whether or not the player is repositioned when initiating the quickbuild * @param value whether or not the player is repositioned when initiating the quickbuild */ - void SetRepositionPlayer(bool value); + void SetRepositionPlayer(const bool value) noexcept; /** * Adds a callback that is called when the quickbuild is completed @@ -209,7 +209,7 @@ public: * Resets the quickbuild * @param failed whether or not the player failed to complete the quickbuild, triggers an extra animation */ - void ResetQuickBuild(bool failed); + void ResetQuickBuild(const bool failed); /** * Cancels the quickbuild if it wasn't completed @@ -217,7 +217,7 @@ public: * @param failReason the reason the quickbuild was cancelled * @param skipChecks whether or not to skip the check for the quickbuild not being completed */ - void CancelQuickBuild(Entity* builder, eQuickBuildFailReason failReason, bool skipChecks = false); + void CancelQuickBuild(Entity* const builder, const eQuickBuildFailReason failReason, const bool skipChecks = false); private: /** * Whether or not the quickbuild state has been changed since we last serialized it. @@ -242,7 +242,7 @@ private: /** * The position that the quickbuild activator is spawned at */ - NiPoint3 m_ActivatorPosition = NiPoint3::ZERO; + NiPoint3 m_ActivatorPosition = NiPoint3Constant::ZERO; /** * The entity that represents the quickbuild activator @@ -287,7 +287,7 @@ private: /** * The imagination that's deducted when completing the quickbuild */ - int m_TakeImagination = 0; + int32_t m_TakeImagination = 0; /** * Currently unused @@ -302,17 +302,17 @@ private: /** * Currently unused */ - std::vector m_CustomModules{}; + std::vector m_CustomModules{}; /** * The activity ID that players partake in when doing this quickbuild */ - int m_ActivityId = 0; + int32_t m_ActivityId = 0; /** * Currently unused */ - int m_PostImaginationCost = 0; + int32_t m_PostImaginationCost = 0; /** * The time it takes for the quickbuild to reset when it's not completed yet @@ -327,7 +327,7 @@ private: /** * The amount of imagination that was drained when building this quickbuild */ - int m_DrainedImagination = 0; + int32_t m_DrainedImagination = 0; /** * Whether to reposition the player or not when building @@ -337,7 +337,7 @@ private: /** * Currently unused */ - float m_SoftTimer = 0; + int32_t m_SoftTimer = 0; /** * The ID of the entity that's currently building the quickbuild @@ -353,13 +353,13 @@ private: * Starts the quickbuild for a certain entity * @param user the entity to start the quickbuild */ - void StartQuickBuild(Entity* user); + void StartQuickBuild(Entity* const user); /** * Completes the quickbuild for an entity, dropping loot and despawning the activator * @param user the entity that completed the quickbuild */ - void CompleteQuickBuild(Entity* user); + void CompleteQuickBuild(Entity* const user); }; #endif // QUICKBUILDCOMPONENT_H diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index 5e3d81f4..d7e01f94 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -12,7 +12,6 @@ #include "Item.h" #include "MissionComponent.h" #include "ModuleAssemblyComponent.h" -#include "Player.h" #include "PossessableComponent.h" #include "PossessorComponent.h" #include "eRacingTaskParam.h" @@ -54,7 +53,7 @@ RacingControlComponent::RacingControlComponent(Entity* parent) if (Game::zoneManager->CheckIfAccessibleZone((worldID / 10) * 10)) m_MainWorld = (worldID / 10) * 10; m_ActivityID = 42; - CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable(); + CDActivitiesTable* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([=](CDActivities entry) {return (entry.instanceMapID == worldID); }); for (CDActivities activity : activities) m_ActivityID = activity.ActivityID; } @@ -119,8 +118,8 @@ void RacingControlComponent::LoadPlayerVehicle(Entity* player, GeneralUtils::UTF16ToWTF8(m_PathName)); auto spawnPointEntities = Game::entityManager->GetEntitiesByLOT(4843); - auto startPosition = NiPoint3::ZERO; - auto startRotation = NiQuaternion::IDENTITY; + auto startPosition = NiPoint3Constant::ZERO; + auto startRotation = NiQuaternionConstant::IDENTITY; const std::string placementAsString = std::to_string(positionNumber); for (auto entity : spawnPointEntities) { if (!entity) continue; @@ -434,83 +433,83 @@ void RacingControlComponent::HandleMessageBoxResponse(Entity* player, int32_t bu } } -void RacingControlComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void RacingControlComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { // BEGIN Scripted Activity - outBitStream->Write1(); + outBitStream.Write1(); - outBitStream->Write(m_RacingPlayers.size()); + outBitStream.Write(m_RacingPlayers.size()); for (const auto& player : m_RacingPlayers) { - outBitStream->Write(player.playerID); + outBitStream.Write(player.playerID); - outBitStream->Write(player.data[0]); - if (player.finished != 0) outBitStream->Write(player.raceTime); - else outBitStream->Write(player.data[1]); - if (player.finished != 0) outBitStream->Write(player.bestLapTime); - else outBitStream->Write(player.data[2]); - if (player.finished == 1) outBitStream->Write(1.0f); - else outBitStream->Write(player.data[3]); - outBitStream->Write(player.data[4]); - outBitStream->Write(player.data[5]); - outBitStream->Write(player.data[6]); - outBitStream->Write(player.data[7]); - outBitStream->Write(player.data[8]); - outBitStream->Write(player.data[9]); + outBitStream.Write(player.data[0]); + if (player.finished != 0) outBitStream.Write(player.raceTime); + else outBitStream.Write(player.data[1]); + if (player.finished != 0) outBitStream.Write(player.bestLapTime); + else outBitStream.Write(player.data[2]); + if (player.finished == 1) outBitStream.Write(1.0f); + else outBitStream.Write(player.data[3]); + outBitStream.Write(player.data[4]); + outBitStream.Write(player.data[5]); + outBitStream.Write(player.data[6]); + outBitStream.Write(player.data[7]); + outBitStream.Write(player.data[8]); + outBitStream.Write(player.data[9]); } // END Scripted Activity - outBitStream->Write1(); - outBitStream->Write(m_RacingPlayers.size()); + outBitStream.Write1(); + outBitStream.Write(m_RacingPlayers.size()); - outBitStream->Write(!m_AllPlayersReady); + outBitStream.Write(!m_AllPlayersReady); if (!m_AllPlayersReady) { int32_t numReady = 0; for (const auto& player : m_RacingPlayers) { - outBitStream->Write1(); // Has more player data - outBitStream->Write(player.playerID); - outBitStream->Write(player.vehicleID); - outBitStream->Write(player.playerIndex); - outBitStream->Write(player.playerLoaded); + outBitStream.Write1(); // Has more player data + outBitStream.Write(player.playerID); + outBitStream.Write(player.vehicleID); + outBitStream.Write(player.playerIndex); + outBitStream.Write(player.playerLoaded); if (player.playerLoaded) numReady++; } - outBitStream->Write0(); // No more data + outBitStream.Write0(); // No more data if (numReady == m_RacingPlayers.size()) m_AllPlayersReady = true; } - outBitStream->Write(!m_RacingPlayers.empty()); + outBitStream.Write(!m_RacingPlayers.empty()); if (!m_RacingPlayers.empty()) { for (const auto& player : m_RacingPlayers) { if (player.finished == 0) continue; - outBitStream->Write1(); // Has more date + outBitStream.Write1(); // Has more date - outBitStream->Write(player.playerID); - outBitStream->Write(player.finished); + outBitStream.Write(player.playerID); + outBitStream.Write(player.finished); } - outBitStream->Write0(); // No more data + outBitStream.Write0(); // No more data } - outBitStream->Write(bIsInitialUpdate); + outBitStream.Write(bIsInitialUpdate); if (bIsInitialUpdate) { - outBitStream->Write(m_RemainingLaps); - outBitStream->Write(m_PathName.size()); + outBitStream.Write(m_RemainingLaps); + outBitStream.Write(m_PathName.size()); for (const auto character : m_PathName) { - outBitStream->Write(character); + outBitStream.Write(character); } } - outBitStream->Write(!m_RacingPlayers.empty()); + outBitStream.Write(!m_RacingPlayers.empty()); if (!m_RacingPlayers.empty()) { for (const auto& player : m_RacingPlayers) { if (player.finished == 0) continue; - outBitStream->Write1(); // Has more data - outBitStream->Write(player.playerID); - outBitStream->Write(player.bestLapTime); - outBitStream->Write(player.raceTime); + outBitStream.Write1(); // Has more data + outBitStream.Write(player.playerID); + outBitStream.Write(player.bestLapTime); + outBitStream.Write(player.raceTime); } - outBitStream->Write0(); // No more data + outBitStream.Write0(); // No more data } } @@ -818,7 +817,7 @@ void RacingControlComponent::Update(float deltaTime) { // Some offset up to make they don't fall through the terrain on a // respawn, seems to fix itself to the track anyhow - player.respawnPosition = position + NiPoint3::UNIT_Y * 5; + player.respawnPosition = position + NiPoint3Constant::UNIT_Y * 5; player.respawnRotation = vehicle->GetRotation(); player.respawnIndex = respawnIndex; diff --git a/dGame/dComponents/RacingControlComponent.h b/dGame/dComponents/RacingControlComponent.h index 47341aae..790459e3 100644 --- a/dGame/dComponents/RacingControlComponent.h +++ b/dGame/dComponents/RacingControlComponent.h @@ -103,14 +103,14 @@ struct RacingPlayerInfo { /** * Component that's attached to a manager entity in each race zone that loads player vehicles, keep scores, etc. */ -class RacingControlComponent : public Component { +class RacingControlComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::RACING_CONTROL; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::RACING_CONTROL; RacingControlComponent(Entity* parentEntity); ~RacingControlComponent(); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; void Update(float deltaTime) override; /** diff --git a/dGame/dComponents/RacingSoundTriggerComponent.h b/dGame/dComponents/RacingSoundTriggerComponent.h index 0f79c67f..140bbe20 100644 --- a/dGame/dComponents/RacingSoundTriggerComponent.h +++ b/dGame/dComponents/RacingSoundTriggerComponent.h @@ -8,7 +8,7 @@ class Entity; class RacingSoundTriggerComponent : public SoundTriggerComponent { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::RACING_SOUND_TRIGGER; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::RACING_SOUND_TRIGGER; RacingSoundTriggerComponent(Entity* parent) : SoundTriggerComponent(parent){}; }; diff --git a/dGame/dComponents/RacingStatsComponent.h b/dGame/dComponents/RacingStatsComponent.h index 9349ce49..ad1b35bf 100644 --- a/dGame/dComponents/RacingStatsComponent.h +++ b/dGame/dComponents/RacingStatsComponent.h @@ -6,7 +6,7 @@ class RacingStatsComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::RACING_STATS; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::RACING_STATS; RacingStatsComponent(Entity* parent) : Component(parent) {} }; diff --git a/dGame/dComponents/RailActivatorComponent.cpp b/dGame/dComponents/RailActivatorComponent.cpp index e0eb035a..f269da49 100644 --- a/dGame/dComponents/RailActivatorComponent.cpp +++ b/dGame/dComponents/RailActivatorComponent.cpp @@ -13,7 +13,7 @@ RailActivatorComponent::RailActivatorComponent(Entity* parent, int32_t componentID) : Component(parent) { m_ComponentID = componentID; - const auto tableData = CDClientManager::Instance().GetTable()->GetEntryByID(componentID);; + const auto tableData = CDClientManager::GetTable()->GetEntryByID(componentID);; m_Path = parent->GetVar(u"rail_path"); m_PathDirection = parent->GetVar(u"rail_path_direction"); diff --git a/dGame/dComponents/RailActivatorComponent.h b/dGame/dComponents/RailActivatorComponent.h index 28b25073..015f36b7 100644 --- a/dGame/dComponents/RailActivatorComponent.h +++ b/dGame/dComponents/RailActivatorComponent.h @@ -15,7 +15,7 @@ public: explicit RailActivatorComponent(Entity* parent, int32_t componentID); ~RailActivatorComponent() override; - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::RAIL_ACTIVATOR; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::RAIL_ACTIVATOR; /** * Handles the OnUse event from some entity, initiates the rail movement diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index 4d8ff667..2067ef2a 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -1,7 +1,9 @@ #include "RenderComponent.h" +#include #include #include +#include #include #include "Entity.h" @@ -14,8 +16,7 @@ std::unordered_map RenderComponent::m_DurationCache{}; -RenderComponent::RenderComponent(Entity* parent, int32_t componentId): Component(parent) { - m_Effects = std::vector(); +RenderComponent::RenderComponent(Entity* const parentEntity, const int32_t componentId) : Component{ parentEntity } { m_LastAnimationName = ""; if (componentId == -1) return; @@ -26,116 +27,69 @@ RenderComponent::RenderComponent(Entity* parent, int32_t componentId): Component if (!result.eof()) { auto animationGroupIDs = std::string(result.getStringField("animationGroupIDs", "")); if (!animationGroupIDs.empty()) { - auto* animationsTable = CDClientManager::Instance().GetTable(); + auto* animationsTable = CDClientManager::GetTable(); auto groupIdsSplit = GeneralUtils::SplitString(animationGroupIDs, ','); for (auto& groupId : groupIdsSplit) { - int32_t groupIdInt; - if (!GeneralUtils::TryParse(groupId, groupIdInt)) { + const auto groupIdInt = GeneralUtils::TryParse(groupId); + + if (!groupIdInt) { LOG("bad animation group Id %s", groupId.c_str()); continue; } - m_animationGroupIds.push_back(groupIdInt); - animationsTable->CacheAnimationGroup(groupIdInt); + + m_animationGroupIds.push_back(groupIdInt.value()); + animationsTable->CacheAnimationGroup(groupIdInt.value()); } } } result.finalize(); } -RenderComponent::~RenderComponent() { - for (Effect* eff : m_Effects) { - if (eff) { - delete eff; - eff = nullptr; - } - } - - m_Effects.clear(); -} - -void RenderComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void RenderComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { if (!bIsInitialUpdate) return; - outBitStream->Write(m_Effects.size()); + outBitStream.Write(m_Effects.size()); - for (Effect* eff : m_Effects) { - // we still need to write 0 as the size for name if it is a nullptr - if (!eff) { - outBitStream->Write(0); - continue; - } - - outBitStream->Write(eff->name.size()); + for (auto& eff : m_Effects) { + outBitStream.Write(eff.name.size()); // if there is no name, then we don't write anything else - if (eff->name.empty()) continue; + if (eff.name.empty()) continue; - for (const auto& value : eff->name) outBitStream->Write(value); + for (const auto& value : eff.name) outBitStream.Write(value); - outBitStream->Write(eff->effectID); + outBitStream.Write(eff.effectID); - outBitStream->Write(eff->type.size()); - for (const auto& value : eff->type) outBitStream->Write(value); + outBitStream.Write(eff.type.size()); + for (const auto& value : eff.type) outBitStream.Write(value); - outBitStream->Write(eff->priority); - outBitStream->Write(eff->secondary); + outBitStream.Write(eff.priority); + outBitStream.Write(eff.secondary); } } -Effect* RenderComponent::AddEffect(const int32_t effectId, const std::string& name, const std::u16string& type, const float priority) { - auto* eff = new Effect(); - - eff->effectID = effectId; - eff->name = name; - eff->type = type; - eff->priority = priority; - m_Effects.push_back(eff); - - return eff; +Effect& RenderComponent::AddEffect(const int32_t effectId, const std::string& name, const std::u16string& type, const float priority) { + return m_Effects.emplace_back(effectId, name, type, priority); } void RenderComponent::RemoveEffect(const std::string& name) { - uint32_t index = -1; + if (m_Effects.empty()) return; - for (auto i = 0u; i < m_Effects.size(); ++i) { - auto* eff = m_Effects[i]; + const auto effectToRemove = std::ranges::find_if(m_Effects, [&name](auto&& effect) { return effect.name == name; }); + if (effectToRemove == m_Effects.end()) return; // Return early if effect is not present - if (eff->name == name) { - index = i; - - delete eff; - - break; - } - } - - if (index == -1) { - return; - } - - m_Effects.erase(m_Effects.begin() + index); + const auto lastEffect = m_Effects.rbegin(); + *effectToRemove = std::move(*lastEffect); // Move-overwrite + m_Effects.pop_back(); } -void RenderComponent::Update(const float deltaTime) { - std::vector dead; +void RenderComponent::Update(const float deltaTime) { + for (auto& effect : m_Effects) { + if (effect.time == 0) continue; // Skip persistent effects - for (auto* effect : m_Effects) { - if (effect->time == 0) { - continue; // Skip persistent effects - } + const auto result = effect.time - deltaTime; + if (result <= 0) continue; - const auto result = effect->time - deltaTime; - - if (result <= 0) { - dead.push_back(effect); - - continue; - } - - effect->time = result; - } - - for (auto* effect : dead) { - // StopEffect(effect->name); + effect.time = result; } } @@ -144,12 +98,12 @@ void RenderComponent::PlayEffect(const int32_t effectId, const std::u16string& e GameMessages::SendPlayFXEffect(m_Parent, effectId, effectType, name, secondary, priority, scale, serialize); - auto* effect = AddEffect(effectId, name, effectType, priority); + auto& effect = AddEffect(effectId, name, effectType, priority); const auto& pair = m_DurationCache.find(effectId); if (pair != m_DurationCache.end()) { - effect->time = pair->second; + effect.time = pair->second; return; } @@ -168,16 +122,16 @@ void RenderComponent::PlayEffect(const int32_t effectId, const std::u16string& e m_DurationCache[effectId] = 0; - effect->time = 0; // Persistent effect + effect.time = 0; // Persistent effect return; } - effect->time = static_cast(result.getFloatField(0)); + effect.time = static_cast(result.getFloatField(0)); result.finalize(); - m_DurationCache[effectId] = effect->time; + m_DurationCache[effectId] = effect.time; } void RenderComponent::StopEffect(const std::string& name, const bool killImmediate) { @@ -186,11 +140,6 @@ void RenderComponent::StopEffect(const std::string& name, const bool killImmedia RemoveEffect(name); } -std::vector& RenderComponent::GetEffects() { - return m_Effects; -} - - float RenderComponent::PlayAnimation(Entity* self, const std::u16string& animation, float priority, float scale) { if (!self) return 0.0f; return RenderComponent::PlayAnimation(self, GeneralUtils::UTF16ToWTF8(animation), priority, scale); @@ -218,13 +167,12 @@ float RenderComponent::DoAnimation(Entity* self, const std::string& animation, b auto* renderComponent = self->GetComponent(); if (!renderComponent) return returnlength; - auto* animationsTable = CDClientManager::Instance().GetTable(); + auto* animationsTable = CDClientManager::GetTable(); for (auto& groupId : renderComponent->m_animationGroupIds) { auto animationGroup = animationsTable->GetAnimation(animation, renderComponent->GetLastAnimationName(), groupId); - if (animationGroup.FoundData()) { - auto data = animationGroup.Data(); - renderComponent->SetLastAnimationName(data.animation_name); - returnlength = data.animation_length; + if (animationGroup) { + renderComponent->SetLastAnimationName(animationGroup->animation_name); + returnlength = animationGroup->animation_length; } } if (sendAnimation) GameMessages::SendPlayAnimation(self, GeneralUtils::ASCIIToUTF16(animation), priority, scale); diff --git a/dGame/dComponents/RenderComponent.h b/dGame/dComponents/RenderComponent.h index 74f39625..e2bbcff5 100644 --- a/dGame/dComponents/RenderComponent.h +++ b/dGame/dComponents/RenderComponent.h @@ -17,7 +17,12 @@ class Entity; * here. */ struct Effect { - Effect() { priority = 1.0f; } + explicit Effect(const int32_t effectID, const std::string& name, const std::u16string& type, const float priority = 1.0f) noexcept + : effectID{ effectID } + , name{ name } + , type{ type } + , priority{ priority } { + } /** * The ID of the effect @@ -54,14 +59,13 @@ struct Effect { * Determines that a component should be visibly rendered into the world, most entities have this. This component * also handles effects that play for entities. */ -class RenderComponent : public Component { +class RenderComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::RENDER; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::RENDER; - RenderComponent(Entity* entity, int32_t componentId = -1); - ~RenderComponent() override; + RenderComponent(Entity* const parentEntity, const int32_t componentId = -1); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; void Update(float deltaTime) override; /** @@ -72,7 +76,7 @@ public: * @param priority the priority of the effect * @return if successful, the effect that was created */ - Effect* AddEffect(int32_t effectId, const std::string& name, const std::u16string& type, const float priority); + [[maybe_unused]] Effect& AddEffect(const int32_t effectId, const std::string& name, const std::u16string& type, const float priority); /** * Removes an effect for this entity @@ -99,12 +103,6 @@ public: */ void StopEffect(const std::string& name, bool killImmediate = true); - /** - * Returns the list of currently active effects - * @return - */ - std::vector& GetEffects(); - /** * Verifies that an animation can be played on this entity by checking * if it has the animation assigned to its group. If it does, the animation is echo'd @@ -125,10 +123,10 @@ public: static float PlayAnimation(Entity* self, const std::u16string& animation, float priority = 0.0f, float scale = 1.0f); static float PlayAnimation(Entity* self, const std::string& animation, float priority = 0.0f, float scale = 1.0f); - static float GetAnimationTime(Entity* self, const std::string& animation); - static float GetAnimationTime(Entity* self, const std::u16string& animation); + [[nodiscard]] static float GetAnimationTime(Entity* self, const std::string& animation); + [[nodiscard]] static float GetAnimationTime(Entity* self, const std::u16string& animation); - const std::string& GetLastAnimationName() const { return m_LastAnimationName; }; + [[nodiscard]] const std::string& GetLastAnimationName() const { return m_LastAnimationName; }; void SetLastAnimationName(const std::string& name) { m_LastAnimationName = name; }; private: @@ -136,7 +134,7 @@ private: /** * List of currently active effects */ - std::vector m_Effects; + std::vector m_Effects; std::vector m_animationGroupIds; diff --git a/dGame/dComponents/RigidbodyPhantomPhysicsComponent.cpp b/dGame/dComponents/RigidbodyPhantomPhysicsComponent.cpp index 414ce2e8..30faa688 100644 --- a/dGame/dComponents/RigidbodyPhantomPhysicsComponent.cpp +++ b/dGame/dComponents/RigidbodyPhantomPhysicsComponent.cpp @@ -11,6 +11,6 @@ RigidbodyPhantomPhysicsComponent::RigidbodyPhantomPhysicsComponent(Entity* paren m_Rotation = m_Parent->GetDefaultRotation(); } -void RigidbodyPhantomPhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void RigidbodyPhantomPhysicsComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { PhysicsComponent::Serialize(outBitStream, bIsInitialUpdate); } diff --git a/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h b/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h index bc60c38e..09820f8e 100644 --- a/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h +++ b/dGame/dComponents/RigidbodyPhantomPhysicsComponent.h @@ -19,11 +19,11 @@ */ class RigidbodyPhantomPhysicsComponent : public PhysicsComponent { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::RIGID_BODY_PHANTOM_PHYSICS; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::RIGID_BODY_PHANTOM_PHYSICS; RigidbodyPhantomPhysicsComponent(Entity* parent); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; }; #endif // __RIGIDBODYPHANTOMPHYSICS_H__ diff --git a/dGame/dComponents/RocketLaunchpadControlComponent.cpp b/dGame/dComponents/RocketLaunchpadControlComponent.cpp index 5a385546..2bc4deec 100644 --- a/dGame/dComponents/RocketLaunchpadControlComponent.cpp +++ b/dGame/dComponents/RocketLaunchpadControlComponent.cpp @@ -139,7 +139,7 @@ void RocketLaunchpadControlComponent::TellMasterToPrepZone(int zoneID) { CBITSTREAM; BitStreamUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::PREP_ZONE); bitStream.Write(zoneID); - Game::server->SendToMaster(&bitStream); + Game::server->SendToMaster(bitStream); } diff --git a/dGame/dComponents/RocketLaunchpadControlComponent.h b/dGame/dComponents/RocketLaunchpadControlComponent.h index 06d97cd3..03d2f141 100644 --- a/dGame/dComponents/RocketLaunchpadControlComponent.h +++ b/dGame/dComponents/RocketLaunchpadControlComponent.h @@ -16,9 +16,9 @@ class PreconditionExpression; /** * Component that handles rocket launchpads that can be interacted with to travel to other worlds. */ -class RocketLaunchpadControlComponent : public Component { +class RocketLaunchpadControlComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::ROCKET_LAUNCH; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::ROCKET_LAUNCH; RocketLaunchpadControlComponent(Entity* parent, int rocketId); ~RocketLaunchpadControlComponent() override; diff --git a/dScripts/ScriptComponent.cpp b/dGame/dComponents/ScriptComponent.cpp similarity index 78% rename from dScripts/ScriptComponent.cpp rename to dGame/dComponents/ScriptComponent.cpp index 7c44ded3..d6bff5b5 100644 --- a/dScripts/ScriptComponent.cpp +++ b/dGame/dComponents/ScriptComponent.cpp @@ -17,11 +17,11 @@ ScriptComponent::~ScriptComponent() { } -void ScriptComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void ScriptComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { if (bIsInitialUpdate) { const auto& networkSettings = m_Parent->GetNetworkSettings(); auto hasNetworkSettings = !networkSettings.empty(); - outBitStream->Write(hasNetworkSettings); + outBitStream.Write(hasNetworkSettings); if (hasNetworkSettings) { @@ -31,17 +31,17 @@ void ScriptComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitial ldfData.Write(networkSettings.size()); for (auto* networkSetting : networkSettings) { - networkSetting->WriteToPacket(&ldfData); + networkSetting->WriteToPacket(ldfData); } // Finally write everything to the stream - outBitStream->Write(ldfData.GetNumberOfBytesUsed()); - outBitStream->Write(ldfData); + outBitStream.Write(ldfData.GetNumberOfBytesUsed()); + outBitStream.Write(ldfData); } } } -CppScripts::Script* ScriptComponent::GetScript() { +CppScripts::Script* const ScriptComponent::GetScript() { return m_Script; } diff --git a/dScripts/ScriptComponent.h b/dGame/dComponents/ScriptComponent.h similarity index 84% rename from dScripts/ScriptComponent.h rename to dGame/dComponents/ScriptComponent.h index cabbf8bf..adc7cc8b 100644 --- a/dScripts/ScriptComponent.h +++ b/dGame/dComponents/ScriptComponent.h @@ -17,20 +17,20 @@ class Entity; * Handles the loading and execution of server side scripts on entities, scripts were originally written in Lua, * here they're written in C++ */ -class ScriptComponent : public Component { +class ScriptComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::SCRIPT; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::SCRIPT; ScriptComponent(Entity* parent, std::string scriptName, bool serialized, bool client = false); ~ScriptComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * Returns the script that's attached to this entity * @return the script that's attached to this entity */ - CppScripts::Script* GetScript(); + CppScripts::Script* const GetScript(); /** * Sets whether the entity should be serialized, unused diff --git a/dGame/dComponents/ScriptedActivityComponent.h b/dGame/dComponents/ScriptedActivityComponent.h index 79a9593d..308a0a86 100644 --- a/dGame/dComponents/ScriptedActivityComponent.h +++ b/dGame/dComponents/ScriptedActivityComponent.h @@ -6,9 +6,9 @@ class Entity; -class ScriptedActivityComponent : public ActivityComponent { +class ScriptedActivityComponent final : public ActivityComponent { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::SCRIPTED_ACTIVITY; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::SCRIPTED_ACTIVITY; ScriptedActivityComponent(Entity* parent, int activityID) : ActivityComponent(parent, activityID){}; }; diff --git a/dGame/dComponents/ShootingGalleryComponent.cpp b/dGame/dComponents/ShootingGalleryComponent.cpp index 45cd9342..20665a01 100644 --- a/dGame/dComponents/ShootingGalleryComponent.cpp +++ b/dGame/dComponents/ShootingGalleryComponent.cpp @@ -17,50 +17,50 @@ void ShootingGalleryComponent::SetDynamicParams(const DynamicShootingGalleryPara Game::entityManager->SerializeEntity(m_Parent); } -void ShootingGalleryComponent::Serialize(RakNet::BitStream* outBitStream, bool isInitialUpdate) { +void ShootingGalleryComponent::Serialize(RakNet::BitStream& outBitStream, bool isInitialUpdate) { // Start ScriptedActivityComponent - outBitStream->Write(true); + outBitStream.Write(true); if (m_CurrentPlayerID == LWOOBJID_EMPTY) { - outBitStream->Write(0); + outBitStream.Write(0); } else { - outBitStream->Write(1); - outBitStream->Write(m_CurrentPlayerID); + outBitStream.Write(1); + outBitStream.Write(m_CurrentPlayerID); for (size_t i = 0; i < 10; i++) { - outBitStream->Write(0.0f); + outBitStream.Write(0.0f); } } // End ScriptedActivityComponent if (isInitialUpdate) { - outBitStream->Write(m_StaticParams.cameraPosition.GetX()); - outBitStream->Write(m_StaticParams.cameraPosition.GetY()); - outBitStream->Write(m_StaticParams.cameraPosition.GetZ()); + outBitStream.Write(m_StaticParams.cameraPosition.GetX()); + outBitStream.Write(m_StaticParams.cameraPosition.GetY()); + outBitStream.Write(m_StaticParams.cameraPosition.GetZ()); - outBitStream->Write(m_StaticParams.cameraLookatPosition.GetX()); - outBitStream->Write(m_StaticParams.cameraLookatPosition.GetY()); - outBitStream->Write(m_StaticParams.cameraLookatPosition.GetZ()); + outBitStream.Write(m_StaticParams.cameraLookatPosition.GetX()); + outBitStream.Write(m_StaticParams.cameraLookatPosition.GetY()); + outBitStream.Write(m_StaticParams.cameraLookatPosition.GetZ()); } - outBitStream->Write(m_Dirty || isInitialUpdate); + outBitStream.Write(m_Dirty || isInitialUpdate); if (m_Dirty || isInitialUpdate) { - outBitStream->Write(m_DynamicParams.cannonVelocity); - outBitStream->Write(m_DynamicParams.cannonRefireRate); - outBitStream->Write(m_DynamicParams.cannonMinDistance); + outBitStream.Write(m_DynamicParams.cannonVelocity); + outBitStream.Write(m_DynamicParams.cannonRefireRate); + outBitStream.Write(m_DynamicParams.cannonMinDistance); - outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetX()); - outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetY()); - outBitStream->Write(m_DynamicParams.cameraBarrelOffset.GetZ()); + outBitStream.Write(m_DynamicParams.cameraBarrelOffset.GetX()); + outBitStream.Write(m_DynamicParams.cameraBarrelOffset.GetY()); + outBitStream.Write(m_DynamicParams.cameraBarrelOffset.GetZ()); - outBitStream->Write(m_DynamicParams.cannonAngle); + outBitStream.Write(m_DynamicParams.cannonAngle); - outBitStream->Write(m_DynamicParams.facing.GetX()); - outBitStream->Write(m_DynamicParams.facing.GetY()); - outBitStream->Write(m_DynamicParams.facing.GetZ()); + outBitStream.Write(m_DynamicParams.facing.GetX()); + outBitStream.Write(m_DynamicParams.facing.GetY()); + outBitStream.Write(m_DynamicParams.facing.GetZ()); - outBitStream->Write(m_CurrentPlayerID); - outBitStream->Write(m_DynamicParams.cannonTimeout); - outBitStream->Write(m_DynamicParams.cannonFOV); + outBitStream.Write(m_CurrentPlayerID); + outBitStream.Write(m_DynamicParams.cannonTimeout); + outBitStream.Write(m_DynamicParams.cannonFOV); if (!isInitialUpdate) m_Dirty = false; } } diff --git a/dGame/dComponents/ShootingGalleryComponent.h b/dGame/dComponents/ShootingGalleryComponent.h index 4024e99a..9382d87e 100644 --- a/dGame/dComponents/ShootingGalleryComponent.h +++ b/dGame/dComponents/ShootingGalleryComponent.h @@ -71,13 +71,13 @@ struct StaticShootingGalleryParams { * A very ancient component that was used to guide shooting galleries, it's still kind of used but a lot of logic is * also in the related scripts. */ -class ShootingGalleryComponent : public Component { +class ShootingGalleryComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::SHOOTING_GALLERY; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::SHOOTING_GALLERY; explicit ShootingGalleryComponent(Entity* parent); ~ShootingGalleryComponent(); - void Serialize(RakNet::BitStream* outBitStream, bool isInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool isInitialUpdate) override; /** * Returns the static params for the shooting gallery diff --git a/dGame/dComponents/SimplePhysicsComponent.cpp b/dGame/dComponents/SimplePhysicsComponent.cpp index 3d8165dd..3b52395e 100644 --- a/dGame/dComponents/SimplePhysicsComponent.cpp +++ b/dGame/dComponents/SimplePhysicsComponent.cpp @@ -32,26 +32,26 @@ SimplePhysicsComponent::SimplePhysicsComponent(Entity* parent, uint32_t componen SimplePhysicsComponent::~SimplePhysicsComponent() { } -void SimplePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { +void SimplePhysicsComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { if (bIsInitialUpdate) { - outBitStream->Write(m_ClimbableType != eClimbableType::CLIMBABLE_TYPE_NOT); - outBitStream->Write(m_ClimbableType); + outBitStream.Write(m_ClimbableType != eClimbableType::CLIMBABLE_TYPE_NOT); + outBitStream.Write(m_ClimbableType); } - outBitStream->Write(m_DirtyVelocity || bIsInitialUpdate); + outBitStream.Write(m_DirtyVelocity || bIsInitialUpdate); if (m_DirtyVelocity || bIsInitialUpdate) { - outBitStream->Write(m_Velocity); - outBitStream->Write(m_AngularVelocity); + outBitStream.Write(m_Velocity); + outBitStream.Write(m_AngularVelocity); m_DirtyVelocity = false; } // Physics motion state if (m_PhysicsMotionState != 0) { - outBitStream->Write1(); - outBitStream->Write(m_PhysicsMotionState); + outBitStream.Write1(); + outBitStream.Write(m_PhysicsMotionState); } else { - outBitStream->Write0(); + outBitStream.Write0(); } PhysicsComponent::Serialize(outBitStream, bIsInitialUpdate); } diff --git a/dGame/dComponents/SimplePhysicsComponent.h b/dGame/dComponents/SimplePhysicsComponent.h index 752fef0b..c6ef52a0 100644 --- a/dGame/dComponents/SimplePhysicsComponent.h +++ b/dGame/dComponents/SimplePhysicsComponent.h @@ -28,12 +28,12 @@ enum class eClimbableType : int32_t { */ class SimplePhysicsComponent : public PhysicsComponent { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::SIMPLE_PHYSICS; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::SIMPLE_PHYSICS; SimplePhysicsComponent(Entity* parent, uint32_t componentID); ~SimplePhysicsComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * Returns the velocity of this entity @@ -87,12 +87,12 @@ private: /** * The current velocity of the entity */ - NiPoint3 m_Velocity = NiPoint3::ZERO; + NiPoint3 m_Velocity = NiPoint3Constant::ZERO; /** * The current angular velocity of the entity */ - NiPoint3 m_AngularVelocity = NiPoint3::ZERO; + NiPoint3 m_AngularVelocity = NiPoint3Constant::ZERO; /** * Whether or not the velocity has changed diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index b65c7d21..2e6edacd 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -31,7 +31,7 @@ ProjectileSyncEntry::ProjectileSyncEntry() { std::unordered_map SkillComponent::m_skillBehaviorCache = {}; -bool SkillComponent::CastPlayerSkill(const uint32_t behaviorId, const uint32_t skillUid, RakNet::BitStream* bitStream, const LWOOBJID target, uint32_t skillID) { +bool SkillComponent::CastPlayerSkill(const uint32_t behaviorId, const uint32_t skillUid, RakNet::BitStream& bitStream, const LWOOBJID target, uint32_t skillID) { auto* context = new BehaviorContext(this->m_Parent->GetObjectID()); context->caster = m_Parent->GetObjectID(); @@ -51,7 +51,7 @@ bool SkillComponent::CastPlayerSkill(const uint32_t behaviorId, const uint32_t s return !context->failed; } -void SkillComponent::SyncPlayerSkill(const uint32_t skillUid, const uint32_t syncId, RakNet::BitStream* bitStream) { +void SkillComponent::SyncPlayerSkill(const uint32_t skillUid, const uint32_t syncId, RakNet::BitStream& bitStream) { const auto index = this->m_managedBehaviors.find(skillUid); if (index == this->m_managedBehaviors.end()) { @@ -66,7 +66,7 @@ void SkillComponent::SyncPlayerSkill(const uint32_t skillUid, const uint32_t syn } -void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::BitStream* bitStream, const LWOOBJID target) { +void SkillComponent::SyncPlayerProjectile(const LWOOBJID projectileId, RakNet::BitStream& bitStream, const LWOOBJID target) { auto index = -1; for (auto i = 0u; i < this->m_managedProjectiles.size(); ++i) { @@ -234,7 +234,7 @@ bool SkillComponent::CastSkill(const uint32_t skillId, LWOOBJID target, const LW // if it's not in the cache look it up and cache it if (pair == m_skillBehaviorCache.end()) { - auto skillTable = CDClientManager::Instance().GetTable(); + auto skillTable = CDClientManager::GetTable(); behaviorId = skillTable->GetSkillByID(skillId).behaviorID; m_skillBehaviorCache.insert_or_assign(skillId, behaviorId); } else { @@ -252,7 +252,7 @@ bool SkillComponent::CastSkill(const uint32_t skillId, LWOOBJID target, const LW SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, const uint32_t behaviorId, const LWOOBJID target, const bool ignoreTarget, const bool clientInitalized, const LWOOBJID originatorOverride) { - auto* bitStream = new RakNet::BitStream(); + RakNet::BitStream bitStream{}; auto* behavior = Behavior::CreateBehavior(behaviorId); @@ -268,12 +268,9 @@ SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, c behavior->Calculate(context, bitStream, { target, 0 }); - for (auto* script : CppScripts::GetEntityScripts(m_Parent)) { - script->OnSkillCast(m_Parent, skillId); - } + m_Parent->GetScript()->OnSkillCast(m_Parent, skillId); if (!context->foundTarget) { - delete bitStream; delete context; // Invalid attack @@ -299,22 +296,20 @@ SkillExecutionResult SkillComponent::CalculateBehavior(const uint32_t skillId, c } //start.optionalTargetID = target; - start.sBitStream.assign(reinterpret_cast(bitStream->GetData()), bitStream->GetNumberOfBytesUsed()); + start.sBitStream.assign(reinterpret_cast(bitStream.GetData()), bitStream.GetNumberOfBytesUsed()); // Write message RakNet::BitStream message; BitStreamUtils::WriteHeader(message, eConnectionType::CLIENT, eClientMessageType::GAME_MSG); message.Write(this->m_Parent->GetObjectID()); - start.Serialize(&message); + start.Serialize(message); - Game::server->Send(&message, UNASSIGNED_SYSTEM_ADDRESS, true); + Game::server->Send(message, UNASSIGNED_SYSTEM_ADDRESS, true); } context->ExecuteUpdates(); - delete bitStream; - // Valid attack return { true, context->skillTime }; } @@ -424,13 +419,13 @@ void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) auto* behavior = Behavior::CreateBehavior(behaviorId); - auto* bitStream = new RakNet::BitStream(); + RakNet::BitStream bitStream{}; behavior->Calculate(entry.context, bitStream, entry.branchContext); DoClientProjectileImpact projectileImpact; - projectileImpact.sBitStream.assign(reinterpret_cast(bitStream->GetData()), bitStream->GetNumberOfBytesUsed()); + projectileImpact.sBitStream.assign(reinterpret_cast(bitStream.GetData()), bitStream.GetNumberOfBytesUsed()); projectileImpact.i64OwnerID = this->m_Parent->GetObjectID(); projectileImpact.i64OrgID = entry.id; projectileImpact.i64TargetID = entry.branchContext.target; @@ -439,42 +434,34 @@ void SkillComponent::SyncProjectileCalculation(const ProjectileSyncEntry& entry) BitStreamUtils::WriteHeader(message, eConnectionType::CLIENT, eClientMessageType::GAME_MSG); message.Write(this->m_Parent->GetObjectID()); - projectileImpact.Serialize(&message); + projectileImpact.Serialize(message); - Game::server->Send(&message, UNASSIGNED_SYSTEM_ADDRESS, true); + Game::server->Send(message, UNASSIGNED_SYSTEM_ADDRESS, true); entry.context->ExecuteUpdates(); - - delete bitStream; } void SkillComponent::HandleUnmanaged(const uint32_t behaviorId, const LWOOBJID target, LWOOBJID source) { - auto* context = new BehaviorContext(source); + BehaviorContext context{ source }; - context->unmanaged = true; - context->caster = target; + context.unmanaged = true; + context.caster = target; auto* behavior = Behavior::CreateBehavior(behaviorId); - auto* bitStream = new RakNet::BitStream(); + RakNet::BitStream bitStream{}; - behavior->Handle(context, bitStream, { target }); - - delete bitStream; - - delete context; + behavior->Handle(&context, bitStream, { target }); } void SkillComponent::HandleUnCast(const uint32_t behaviorId, const LWOOBJID target) { - auto* context = new BehaviorContext(target); + BehaviorContext context{ target }; - context->caster = target; + context.caster = target; auto* behavior = Behavior::CreateBehavior(behaviorId); - behavior->UnCast(context, { target }); - - delete context; + behavior->UnCast(&context, { target }); } SkillComponent::SkillComponent(Entity* parent): Component(parent) { @@ -485,8 +472,8 @@ SkillComponent::~SkillComponent() { Reset(); } -void SkillComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - if (bIsInitialUpdate) outBitStream->Write0(); +void SkillComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + if (bIsInitialUpdate) outBitStream.Write0(); } /// diff --git a/dGame/dComponents/SkillComponent.h b/dGame/dComponents/SkillComponent.h index 2d8628ef..2acae5d7 100644 --- a/dGame/dComponents/SkillComponent.h +++ b/dGame/dComponents/SkillComponent.h @@ -1,6 +1,6 @@ /* * Darkflame Universe - * Copyright 2018 + * Copyright 2024 */ #ifndef SKILLCOMPONENT_H @@ -55,16 +55,16 @@ struct SkillExecutionResult { * * Skills are a built up by a tree of behaviors. See dGame/dBehaviors/ for a list of behaviors. * - * This system is very conveluted and still has a lot of unknowns. + * This system is very convoluted and still has a lot of unknowns. */ -class SkillComponent : public Component { +class SkillComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::SKILL; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::SKILL; explicit SkillComponent(Entity* parent); ~SkillComponent() override; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * Computes skill updates. Invokes CalculateUpdate. @@ -93,7 +93,7 @@ public: * @param bitStream the bitSteam given by the client to determine the behavior path * @param target the explicit target of the skill */ - bool CastPlayerSkill(uint32_t behaviorId, uint32_t skillUid, RakNet::BitStream* bitStream, LWOOBJID target, uint32_t skillID = 0); + bool CastPlayerSkill(uint32_t behaviorId, uint32_t skillUid, RakNet::BitStream& bitStream, LWOOBJID target, uint32_t skillID = 0); /** * Continues a player skill. Should only be called when the server receives a sync message from the client. @@ -101,7 +101,7 @@ public: * @param syncId the unique sync ID of the skill given by the client * @param bitStream the bitSteam given by the client to determine the behavior path */ - void SyncPlayerSkill(uint32_t skillUid, uint32_t syncId, RakNet::BitStream* bitStream); + void SyncPlayerSkill(uint32_t skillUid, uint32_t syncId, RakNet::BitStream& bitStream); /** * Continues a player projectile calculation. Should only be called when the server receives a projectile sync message from the client. @@ -109,7 +109,7 @@ public: * @param bitStream the bitSteam given by the client to determine the behavior path * @param target the explicit target of the target */ - void SyncPlayerProjectile(LWOOBJID projectileId, RakNet::BitStream* bitStream, LWOOBJID target); + void SyncPlayerProjectile(LWOOBJID projectileId, RakNet::BitStream& bitStream, LWOOBJID target); /** * Registers a player projectile. Should only be called when the server is computing a player projectile. diff --git a/dGame/dComponents/SoundTriggerComponent.cpp b/dGame/dComponents/SoundTriggerComponent.cpp index 34d2441c..878ce848 100644 --- a/dGame/dComponents/SoundTriggerComponent.cpp +++ b/dGame/dComponents/SoundTriggerComponent.cpp @@ -2,28 +2,28 @@ #include "Game.h" #include "Logger.h" -void MusicCue::Serialize(RakNet::BitStream* outBitStream){ - outBitStream->Write(name.size()); - outBitStream->Write(name.c_str(), name.size()); - outBitStream->Write(result); - outBitStream->Write(boredomTime); +void MusicCue::Serialize(RakNet::BitStream& outBitStream){ + outBitStream.Write(name.size()); + outBitStream.Write(name.c_str(), name.size()); + outBitStream.Write(result); + outBitStream.Write(boredomTime); } -void MusicParameter::Serialize(RakNet::BitStream* outBitStream){ - outBitStream->Write(name.size()); - outBitStream->Write(name.c_str(), name.size()); - outBitStream->Write(value); +void MusicParameter::Serialize(RakNet::BitStream& outBitStream){ + outBitStream.Write(name.size()); + outBitStream.Write(name.c_str(), name.size()); + outBitStream.Write(value); } -void GUIDResults::Serialize(RakNet::BitStream* outBitStream){ +void GUIDResults::Serialize(RakNet::BitStream& outBitStream){ guid.Serialize(outBitStream); - outBitStream->Write(result); + outBitStream.Write(result); } -void MixerProgram::Serialize(RakNet::BitStream* outBitStream){ - outBitStream->Write(name.size()); - outBitStream->Write(name.c_str(), name.size()); - outBitStream->Write(result); +void MixerProgram::Serialize(RakNet::BitStream& outBitStream){ + outBitStream.Write(name.size()); + outBitStream.Write(name.c_str(), name.size()); + outBitStream.Write(result); } SoundTriggerComponent::SoundTriggerComponent(Entity* parent) : Component(parent) { @@ -55,30 +55,30 @@ SoundTriggerComponent::SoundTriggerComponent(Entity* parent) : Component(parent) if (!mixerName.empty()) this->m_MixerPrograms.push_back(MixerProgram(mixerName)); } -void SoundTriggerComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - outBitStream->Write(this->m_Dirty || bIsInitialUpdate); +void SoundTriggerComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + outBitStream.Write(this->m_Dirty || bIsInitialUpdate); if (this->m_Dirty || bIsInitialUpdate) { - outBitStream->Write(this->m_MusicCues.size()); + outBitStream.Write(this->m_MusicCues.size()); for (auto& musicCue : this->m_MusicCues) { musicCue.Serialize(outBitStream); } - outBitStream->Write(this->m_MusicParameters.size()); + outBitStream.Write(this->m_MusicParameters.size()); for (auto& musicParam : this->m_MusicParameters) { musicParam.Serialize(outBitStream); } - outBitStream->Write(this->m_2DAmbientSounds.size()); + outBitStream.Write(this->m_2DAmbientSounds.size()); for (auto twoDAmbientSound : this->m_2DAmbientSounds) { twoDAmbientSound.Serialize(outBitStream); } - outBitStream->Write(this->m_3DAmbientSounds.size()); + outBitStream.Write(this->m_3DAmbientSounds.size()); for (auto threeDAmbientSound : this->m_3DAmbientSounds) { threeDAmbientSound.Serialize(outBitStream); } - outBitStream->Write(this->m_MixerPrograms.size()); + outBitStream.Write(this->m_MixerPrograms.size()); for (auto& mixerProgram : this->m_MixerPrograms) { mixerProgram.Serialize(outBitStream); } diff --git a/dGame/dComponents/SoundTriggerComponent.h b/dGame/dComponents/SoundTriggerComponent.h index 56c71770..2851aff1 100644 --- a/dGame/dComponents/SoundTriggerComponent.h +++ b/dGame/dComponents/SoundTriggerComponent.h @@ -1,4 +1,5 @@ #pragma once + #include "dCommonVars.h" #include "Entity.h" #include "GUID.h" @@ -16,7 +17,7 @@ struct MusicCue { this->boredomTime = boredomTime; }; - void Serialize(RakNet::BitStream* outBitStream); + void Serialize(RakNet::BitStream& outBitStream); }; struct MusicParameter { @@ -28,7 +29,7 @@ struct MusicParameter { this->value = value; } - void Serialize(RakNet::BitStream* outBitStream); + void Serialize(RakNet::BitStream& outBitStream); }; struct GUIDResults{ @@ -40,10 +41,10 @@ struct GUIDResults{ this->result = result; } - void Serialize(RakNet::BitStream* outBitStream); + void Serialize(RakNet::BitStream& outBitStream); }; -struct MixerProgram{ +struct MixerProgram { std::string name; uint32_t result; @@ -52,25 +53,25 @@ struct MixerProgram{ this->result = result; } - void Serialize(RakNet::BitStream* outBitStream); + void Serialize(RakNet::BitStream& outBitStream); }; class SoundTriggerComponent : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::SOUND_TRIGGER; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::SOUND_TRIGGER; explicit SoundTriggerComponent(Entity* parent); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; void ActivateMusicCue(const std::string& name, float bordemTime = -1.0); void DeactivateMusicCue(const std::string& name); private: - std::vector m_MusicCues = {}; - std::vector m_MusicParameters = {}; - std::vector m_2DAmbientSounds = {}; - std::vector m_3DAmbientSounds = {}; - std::vector m_MixerPrograms = {}; + std::vector m_MusicCues; + std::vector m_MusicParameters; + std::vector m_2DAmbientSounds; + std::vector m_3DAmbientSounds; + std::vector m_MixerPrograms; bool m_Dirty = false; }; diff --git a/dGame/dComponents/SwitchComponent.cpp b/dGame/dComponents/SwitchComponent.cpp index 25f18a4d..e6ad6d00 100644 --- a/dGame/dComponents/SwitchComponent.cpp +++ b/dGame/dComponents/SwitchComponent.cpp @@ -21,8 +21,8 @@ SwitchComponent::~SwitchComponent() { } } -void SwitchComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - outBitStream->Write(m_Active); +void SwitchComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + outBitStream.Write(m_Active); } void SwitchComponent::SetActive(bool active) { diff --git a/dGame/dComponents/SwitchComponent.h b/dGame/dComponents/SwitchComponent.h index 7f2c3498..862e5719 100644 --- a/dGame/dComponents/SwitchComponent.h +++ b/dGame/dComponents/SwitchComponent.h @@ -14,9 +14,9 @@ /** * A component for switches in game, including pet triggered switches. */ -class SwitchComponent : public Component { +class SwitchComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::SWITCH; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::SWITCH; SwitchComponent(Entity* parent); ~SwitchComponent() override; @@ -25,7 +25,7 @@ public: Entity* GetParentEntity() const; - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; /** * Sets whether the switch is on or off. diff --git a/dGame/dComponents/TriggerComponent.cpp b/dGame/dComponents/TriggerComponent.cpp index 6d7ce3dd..a9d00b15 100644 --- a/dGame/dComponents/TriggerComponent.cpp +++ b/dGame/dComponents/TriggerComponent.cpp @@ -9,23 +9,22 @@ #include "ControllablePhysicsComponent.h" #include "MissionComponent.h" #include "PhantomPhysicsComponent.h" -#include "Player.h" #include "QuickBuildComponent.h" #include "SkillComponent.h" #include "eEndBehavior.h" #include "PlayerManager.h" +#include "Game.h" +#include "EntityManager.h" +#include "MovementAIComponent.h" - -TriggerComponent::TriggerComponent(Entity* parent, const std::string triggerInfo): Component(parent) { +TriggerComponent::TriggerComponent(Entity* parent, const std::string triggerInfo) : Component(parent) { m_Parent = parent; m_Trigger = nullptr; std::vector tokens = GeneralUtils::SplitString(triggerInfo, ':'); - uint32_t sceneID; - GeneralUtils::TryParse(tokens.at(0), sceneID); - uint32_t triggerID; - GeneralUtils::TryParse(tokens.at(1), triggerID); + const auto sceneID = GeneralUtils::TryParse(tokens.at(0)).value_or(0); + const auto triggerID = GeneralUtils::TryParse(tokens.at(1)).value_or(0); m_Trigger = Game::zoneManager->GetZone()->GetTrigger(sceneID, triggerID); @@ -45,7 +44,7 @@ void TriggerComponent::TriggerEvent(eTriggerEventType event, Entity* optionalTar } void TriggerComponent::HandleTriggerCommand(LUTriggers::Command* command, Entity* optionalTarget) { - auto argArray = GeneralUtils::SplitString(command->args, ','); + auto argArray = GeneralUtils::SplitString(command->args, ','); // determine targets std::vector targetEntities = GatherTargets(command, optionalTarget); @@ -57,107 +56,119 @@ void TriggerComponent::HandleTriggerCommand(LUTriggers::Command* command, Entity if (!targetEntity) continue; switch (command->id) { - case eTriggerCommandType::ZONE_PLAYER: break; - case eTriggerCommandType::FIRE_EVENT: - HandleFireEvent(targetEntity, command->args); - break; - case eTriggerCommandType::DESTROY_OBJ: - HandleDestroyObject(targetEntity, command->args); - break; - case eTriggerCommandType::TOGGLE_TRIGGER: - HandleToggleTrigger(targetEntity, command->args); - break; - case eTriggerCommandType::RESET_REBUILD: - HandleResetRebuild(targetEntity, command->args); - break; - case eTriggerCommandType::SET_PATH: break; - case eTriggerCommandType::SET_PICK_TYPE: break; - case eTriggerCommandType::MOVE_OBJECT: - HandleMoveObject(targetEntity, argArray); - break; - case eTriggerCommandType::ROTATE_OBJECT: - HandleRotateObject(targetEntity, argArray); - break; - case eTriggerCommandType::PUSH_OBJECT: - HandlePushObject(targetEntity, argArray); - break; - case eTriggerCommandType::REPEL_OBJECT: - HandleRepelObject(targetEntity, command->args); - break; - case eTriggerCommandType::SET_TIMER: - HandleSetTimer(targetEntity, argArray); - break; - case eTriggerCommandType::CANCEL_TIMER: - HandleCancelTimer(targetEntity, command->args); - break; - case eTriggerCommandType::PLAY_CINEMATIC: - HandlePlayCinematic(targetEntity, argArray); - break; - case eTriggerCommandType::TOGGLE_BBB: - HandleToggleBBB(targetEntity, command->args); - break; - case eTriggerCommandType::UPDATE_MISSION: - HandleUpdateMission(targetEntity, argArray); - break; - case eTriggerCommandType::SET_BOUNCER_STATE: break; - case eTriggerCommandType::BOUNCE_ALL_ON_BOUNCER: break; - case eTriggerCommandType::TURN_AROUND_ON_PATH: break; - case eTriggerCommandType::GO_FORWARD_ON_PATH: break; - case eTriggerCommandType::GO_BACKWARD_ON_PATH: break; - case eTriggerCommandType::STOP_PATHING: break; - case eTriggerCommandType::START_PATHING: break; - case eTriggerCommandType::LOCK_OR_UNLOCK_CONTROLS: break; - case eTriggerCommandType::PLAY_EFFECT: - HandlePlayEffect(targetEntity, argArray); - break; - case eTriggerCommandType::STOP_EFFECT: - GameMessages::SendStopFXEffect(targetEntity, true, command->args); - break; - case eTriggerCommandType::CAST_SKILL: - HandleCastSkill(targetEntity, command->args); - break; - case eTriggerCommandType::DISPLAY_ZONE_SUMMARY: - GameMessages::SendDisplayZoneSummary(targetEntity->GetObjectID(), targetEntity->GetSystemAddress(), false, command->args == "1", m_Parent->GetObjectID()); - break; - case eTriggerCommandType::SET_PHYSICS_VOLUME_EFFECT: - HandleSetPhysicsVolumeEffect(targetEntity, argArray); - break; - case eTriggerCommandType::SET_PHYSICS_VOLUME_STATUS: - HandleSetPhysicsVolumeStatus(targetEntity, command->args); - break; - case eTriggerCommandType::SET_MODEL_TO_BUILD: break; - case eTriggerCommandType::SPAWN_MODEL_BRICKS: break; - case eTriggerCommandType::ACTIVATE_SPAWNER_NETWORK: - HandleActivateSpawnerNetwork(command->args); - break; - case eTriggerCommandType::DEACTIVATE_SPAWNER_NETWORK: - HandleDeactivateSpawnerNetwork(command->args); - break; - case eTriggerCommandType::RESET_SPAWNER_NETWORK: - HandleResetSpawnerNetwork(command->args); - break; - case eTriggerCommandType::DESTROY_SPAWNER_NETWORK_OBJECTS: - HandleDestroySpawnerNetworkObjects(command->args); - break; - case eTriggerCommandType::GO_TO_WAYPOINT: break; - case eTriggerCommandType::ACTIVATE_PHYSICS: - HandleActivatePhysics(targetEntity, command->args); - break; + case eTriggerCommandType::ZONE_PLAYER: break; + case eTriggerCommandType::FIRE_EVENT: + HandleFireEvent(targetEntity, command->args); + break; + case eTriggerCommandType::DESTROY_OBJ: + HandleDestroyObject(targetEntity, command->args); + break; + case eTriggerCommandType::TOGGLE_TRIGGER: + HandleToggleTrigger(targetEntity, command->args); + break; + case eTriggerCommandType::RESET_REBUILD: + HandleResetRebuild(targetEntity, command->args); + break; + case eTriggerCommandType::SET_PATH: + HandleSetPath(targetEntity, argArray); + break; + case eTriggerCommandType::SET_PICK_TYPE: break; + case eTriggerCommandType::MOVE_OBJECT: + HandleMoveObject(targetEntity, argArray); + break; + case eTriggerCommandType::ROTATE_OBJECT: + HandleRotateObject(targetEntity, argArray); + break; + case eTriggerCommandType::PUSH_OBJECT: + HandlePushObject(targetEntity, argArray); + break; + case eTriggerCommandType::REPEL_OBJECT: + HandleRepelObject(targetEntity, command->args); + break; + case eTriggerCommandType::SET_TIMER: + HandleSetTimer(targetEntity, argArray); + break; + case eTriggerCommandType::CANCEL_TIMER: + HandleCancelTimer(targetEntity, command->args); + break; + case eTriggerCommandType::PLAY_CINEMATIC: + HandlePlayCinematic(targetEntity, argArray); + break; + case eTriggerCommandType::TOGGLE_BBB: + HandleToggleBBB(targetEntity, command->args); + break; + case eTriggerCommandType::UPDATE_MISSION: + HandleUpdateMission(targetEntity, argArray); + break; + case eTriggerCommandType::SET_BOUNCER_STATE: break; + case eTriggerCommandType::BOUNCE_ALL_ON_BOUNCER: break; + case eTriggerCommandType::TURN_AROUND_ON_PATH: + HandleTurnAroundOnPath(targetEntity); + break; + case eTriggerCommandType::GO_FORWARD_ON_PATH: + HandleGoForwardOnPath(targetEntity); + break; + case eTriggerCommandType::GO_BACKWARD_ON_PATH: + HandleGoBackwardOnPath(targetEntity); + break; + case eTriggerCommandType::STOP_PATHING: + HandleStopPathing(targetEntity); + break; + case eTriggerCommandType::START_PATHING: + HandleStartPathing(targetEntity); + break; + case eTriggerCommandType::LOCK_OR_UNLOCK_CONTROLS: break; + case eTriggerCommandType::PLAY_EFFECT: + HandlePlayEffect(targetEntity, argArray); + break; + case eTriggerCommandType::STOP_EFFECT: + GameMessages::SendStopFXEffect(targetEntity, true, command->args); + break; + case eTriggerCommandType::CAST_SKILL: + HandleCastSkill(targetEntity, command->args); + break; + case eTriggerCommandType::DISPLAY_ZONE_SUMMARY: + GameMessages::SendDisplayZoneSummary(targetEntity->GetObjectID(), targetEntity->GetSystemAddress(), false, command->args == "1", m_Parent->GetObjectID()); + break; + case eTriggerCommandType::SET_PHYSICS_VOLUME_EFFECT: + HandleSetPhysicsVolumeEffect(targetEntity, argArray); + break; + case eTriggerCommandType::SET_PHYSICS_VOLUME_STATUS: + HandleSetPhysicsVolumeStatus(targetEntity, command->args); + break; + case eTriggerCommandType::SET_MODEL_TO_BUILD: break; + case eTriggerCommandType::SPAWN_MODEL_BRICKS: break; + case eTriggerCommandType::ACTIVATE_SPAWNER_NETWORK: + HandleActivateSpawnerNetwork(command->args); + break; + case eTriggerCommandType::DEACTIVATE_SPAWNER_NETWORK: + HandleDeactivateSpawnerNetwork(command->args); + break; + case eTriggerCommandType::RESET_SPAWNER_NETWORK: + HandleResetSpawnerNetwork(command->args); + break; + case eTriggerCommandType::DESTROY_SPAWNER_NETWORK_OBJECTS: + HandleDestroySpawnerNetworkObjects(command->args); + break; + case eTriggerCommandType::GO_TO_WAYPOINT: break; + case eTriggerCommandType::ACTIVATE_PHYSICS: + HandleActivatePhysics(targetEntity, command->args); + break; // DEPRECATED BLOCK START - case eTriggerCommandType::ACTIVATE_MUSIC_CUE: break; - case eTriggerCommandType::DEACTIVATE_MUSIC_CUE: break; - case eTriggerCommandType::FLASH_MUSIC_CUE: break; - case eTriggerCommandType::SET_MUSIC_PARAMETER: break; - case eTriggerCommandType::PLAY_2D_AMBIENT_SOUND: break; - case eTriggerCommandType::STOP_2D_AMBIENT_SOUND: break; - case eTriggerCommandType::PLAY_3D_AMBIENT_SOUND: break; - case eTriggerCommandType::STOP_3D_AMBIENT_SOUND: break; - case eTriggerCommandType::ACTIVATE_MIXER_PROGRAM: break; - case eTriggerCommandType::DEACTIVATE_MIXER_PROGRAM: break; + case eTriggerCommandType::ACTIVATE_MUSIC_CUE: break; + case eTriggerCommandType::DEACTIVATE_MUSIC_CUE: break; + case eTriggerCommandType::FLASH_MUSIC_CUE: break; + case eTriggerCommandType::SET_MUSIC_PARAMETER: break; + case eTriggerCommandType::PLAY_2D_AMBIENT_SOUND: break; + case eTriggerCommandType::STOP_2D_AMBIENT_SOUND: break; + case eTriggerCommandType::PLAY_3D_AMBIENT_SOUND: break; + case eTriggerCommandType::STOP_3D_AMBIENT_SOUND: break; + case eTriggerCommandType::ACTIVATE_MIXER_PROGRAM: break; + case eTriggerCommandType::DEACTIVATE_MIXER_PROGRAM: break; // DEPRECATED BLOCK END - default: - LOG_DEBUG("Event %i was not handled!", command->id); - break; + default: + LOG_DEBUG("Event %i was not handled!", command->id); + break; } } } @@ -166,37 +177,39 @@ std::vector TriggerComponent::GatherTargets(LUTriggers::Command* comman std::vector entities = {}; if (command->target == "self") entities.push_back(m_Parent); - else if (command->target == "zone") { /*TODO*/ } - else if (command->target == "target" && optionalTarget) entities.push_back(optionalTarget); - else if (command->target == "targetTeam" && optionalTarget) { + else if (command->target == "zone") { + /*TODO*/ + } else if (command->target == "target" && optionalTarget) { + entities.push_back(optionalTarget); + } else if (command->target == "targetTeam" && optionalTarget) { auto* team = TeamManager::Instance()->GetTeam(optionalTarget->GetObjectID()); for (const auto memberId : team->members) { auto* member = Game::entityManager->GetEntity(memberId); if (member) entities.push_back(member); } - } else if (command->target == "objGroup") entities = Game::entityManager->GetEntitiesInGroup(command->targetName); - else if (command->target == "allPlayers") { + } else if (command->target == "objGroup") { + entities = Game::entityManager->GetEntitiesInGroup(command->targetName); + } else if (command->target == "allPlayers") { for (auto* player : PlayerManager::GetAllPlayers()) { entities.push_back(player); } - } else if (command->target == "allNPCs") { /*UNUSED*/ } + } else if (command->target == "allNPCs") { + /*UNUSED*/ + } return entities; } void TriggerComponent::HandleFireEvent(Entity* targetEntity, std::string args) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(targetEntity)) { - script->OnFireEventServerSide(targetEntity, m_Parent, args, 0, 0, 0); - } + targetEntity->GetScript()->OnFireEventServerSide(targetEntity, m_Parent, args, 0, 0, 0); } -void TriggerComponent::HandleDestroyObject(Entity* targetEntity, std::string args){ - uint32_t killType; - GeneralUtils::TryParse(args, killType); - targetEntity->Smash(m_Parent->GetObjectID(), static_cast(killType)); +void TriggerComponent::HandleDestroyObject(Entity* targetEntity, std::string args) { + const eKillType killType = GeneralUtils::TryParse(args).value_or(eKillType::VIOLENT); + targetEntity->Smash(m_Parent->GetObjectID(), killType); } -void TriggerComponent::HandleToggleTrigger(Entity* targetEntity, std::string args){ +void TriggerComponent::HandleToggleTrigger(Entity* targetEntity, std::string args) { auto* triggerComponent = targetEntity->GetComponent(); if (!triggerComponent) { LOG_DEBUG("Trigger component not found!"); @@ -205,7 +218,7 @@ void TriggerComponent::HandleToggleTrigger(Entity* targetEntity, std::string arg triggerComponent->SetTriggerEnabled(args == "1"); } -void TriggerComponent::HandleResetRebuild(Entity* targetEntity, std::string args){ +void TriggerComponent::HandleResetRebuild(Entity* targetEntity, std::string args) { auto* quickBuildComponent = targetEntity->GetComponent(); if (!quickBuildComponent) { LOG_DEBUG("Rebuild component not found!"); @@ -214,28 +227,26 @@ void TriggerComponent::HandleResetRebuild(Entity* targetEntity, std::string args quickBuildComponent->ResetQuickBuild(args == "1"); } -void TriggerComponent::HandleMoveObject(Entity* targetEntity, std::vector argArray){ +void TriggerComponent::HandleMoveObject(Entity* targetEntity, std::vector argArray) { if (argArray.size() <= 2) return; - auto position = targetEntity->GetPosition(); - NiPoint3 offset = NiPoint3::ZERO; - GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), offset); + NiPoint3 position = targetEntity->GetPosition(); + const NiPoint3 offset = GeneralUtils::TryParse(argArray).value_or(NiPoint3Constant::ZERO); position += offset; targetEntity->SetPosition(position); } -void TriggerComponent::HandleRotateObject(Entity* targetEntity, std::vector argArray){ +void TriggerComponent::HandleRotateObject(Entity* targetEntity, std::vector argArray) { if (argArray.size() <= 2) return; - NiPoint3 vector = NiPoint3::ZERO; - GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), vector); + const NiPoint3 vector = GeneralUtils::TryParse(argArray).value_or(NiPoint3Constant::ZERO); NiQuaternion rotation = NiQuaternion::FromEulerAngles(vector); targetEntity->SetRotation(rotation); } -void TriggerComponent::HandlePushObject(Entity* targetEntity, std::vector argArray){ +void TriggerComponent::HandlePushObject(Entity* targetEntity, std::vector argArray) { if (argArray.size() < 3) return; auto* phantomPhysicsComponent = m_Parent->GetComponent(); @@ -246,22 +257,21 @@ void TriggerComponent::HandlePushObject(Entity* targetEntity, std::vectorSetPhysicsEffectActive(true); phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::PUSH); phantomPhysicsComponent->SetDirectionalMultiplier(1); - NiPoint3 direction = NiPoint3::ZERO; - GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), direction); + const NiPoint3 direction = GeneralUtils::TryParse(argArray).value_or(NiPoint3Constant::ZERO); phantomPhysicsComponent->SetDirection(direction); Game::entityManager->SerializeEntity(m_Parent); } -void TriggerComponent::HandleRepelObject(Entity* targetEntity, std::string args){ +void TriggerComponent::HandleRepelObject(Entity* targetEntity, std::string args) { auto* phantomPhysicsComponent = m_Parent->GetComponent(); if (!phantomPhysicsComponent) { LOG_DEBUG("Phantom Physics component not found!"); return; } - float forceMultiplier; - GeneralUtils::TryParse(args, forceMultiplier); + const float forceMultiplier = GeneralUtils::TryParse(args).value_or(1.0f); + phantomPhysicsComponent->SetPhysicsEffectActive(true); phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::REPULSE); phantomPhysicsComponent->SetDirectionalMultiplier(forceMultiplier); @@ -278,17 +288,16 @@ void TriggerComponent::HandleRepelObject(Entity* targetEntity, std::string args) Game::entityManager->SerializeEntity(m_Parent); } -void TriggerComponent::HandleSetTimer(Entity* targetEntity, std::vector argArray){ +void TriggerComponent::HandleSetTimer(Entity* targetEntity, std::vector argArray) { if (argArray.size() != 2) { - LOG_DEBUG("Not ehought variables!"); + LOG_DEBUG("Not enough variables!"); return; } - float time = 0.0; - GeneralUtils::TryParse(argArray.at(1), time); + const float time = GeneralUtils::TryParse(argArray.at(1)).value_or(0.0f); m_Parent->AddTimer(argArray.at(0), time); } -void TriggerComponent::HandleCancelTimer(Entity* targetEntity, std::string args){ +void TriggerComponent::HandleCancelTimer(Entity* targetEntity, std::string args) { m_Parent->CancelTimer(args); } @@ -300,7 +309,7 @@ void TriggerComponent::HandlePlayCinematic(Entity* targetEntity, std::vector= 2) { - GeneralUtils::TryParse(argArray.at(1), leadIn); + leadIn = GeneralUtils::TryParse(argArray.at(1)).value_or(leadIn); if (argArray.size() >= 3 && argArray.at(2) == "wait") { wait = eEndBehavior::WAIT; if (argArray.size() >= 4 && argArray.at(3) == "unlock") { @@ -336,7 +345,7 @@ void TriggerComponent::HandleUpdateMission(Entity* targetEntity, std::vectorGetComponent(); - if (!missionComponent){ + if (!missionComponent) { LOG_DEBUG("Mission component not found!"); return; } @@ -345,22 +354,25 @@ void TriggerComponent::HandleUpdateMission(Entity* targetEntity, std::vector argArray) { if (argArray.size() < 3) return; - int32_t effectID = 0; - if (!GeneralUtils::TryParse(argArray.at(1), effectID)) return; + const auto effectID = GeneralUtils::TryParse(argArray.at(1)); + if (!effectID) return; std::u16string effectType = GeneralUtils::UTF8ToUTF16(argArray.at(2)); + float priority = 1; - if (argArray.size() == 4) GeneralUtils::TryParse(argArray.at(3), priority); - GameMessages::SendPlayFXEffect(targetEntity, effectID, effectType, argArray.at(0), LWOOBJID_EMPTY, priority); + if (argArray.size() == 4) { + priority = GeneralUtils::TryParse(argArray.at(3)).value_or(priority); + } + + GameMessages::SendPlayFXEffect(targetEntity, effectID.value(), effectType, argArray.at(0), LWOOBJID_EMPTY, priority); } -void TriggerComponent::HandleCastSkill(Entity* targetEntity, std::string args){ +void TriggerComponent::HandleCastSkill(Entity* targetEntity, std::string args) { auto* skillComponent = targetEntity->GetComponent(); if (!skillComponent) { LOG_DEBUG("Skill component not found!"); return; } - uint32_t skillId; - GeneralUtils::TryParse(args, skillId); + const uint32_t skillId = GeneralUtils::TryParse(args).value_or(0); skillComponent->CastSkill(skillId, targetEntity->GetObjectID()); } @@ -382,17 +394,16 @@ void TriggerComponent::HandleSetPhysicsVolumeEffect(Entity* targetEntity, std::v phantomPhysicsComponent->SetEffectType(effectType); phantomPhysicsComponent->SetDirectionalMultiplier(std::stof(argArray.at(1))); if (argArray.size() > 4) { - NiPoint3 direction = NiPoint3::ZERO; - GeneralUtils::TryParse(argArray.at(2), argArray.at(3), argArray.at(4), direction); + const NiPoint3 direction = + GeneralUtils::TryParse(argArray.at(2), argArray.at(3), argArray.at(4)).value_or(NiPoint3Constant::ZERO); + phantomPhysicsComponent->SetDirection(direction); } if (argArray.size() > 5) { - uint32_t min; - GeneralUtils::TryParse(argArray.at(6), min); + const uint32_t min = GeneralUtils::TryParse(argArray.at(6)).value_or(0); phantomPhysicsComponent->SetMin(min); - uint32_t max; - GeneralUtils::TryParse(argArray.at(7), max); + const uint32_t max = GeneralUtils::TryParse(argArray.at(7)).value_or(0); phantomPhysicsComponent->SetMax(max); } @@ -409,25 +420,25 @@ void TriggerComponent::HandleSetPhysicsVolumeStatus(Entity* targetEntity, std::s Game::entityManager->SerializeEntity(targetEntity); } -void TriggerComponent::HandleActivateSpawnerNetwork(std::string args){ +void TriggerComponent::HandleActivateSpawnerNetwork(std::string args) { for (auto* spawner : Game::zoneManager->GetSpawnersByName(args)) { if (spawner) spawner->Activate(); } } -void TriggerComponent::HandleDeactivateSpawnerNetwork(std::string args){ +void TriggerComponent::HandleDeactivateSpawnerNetwork(std::string args) { for (auto* spawner : Game::zoneManager->GetSpawnersByName(args)) { if (spawner) spawner->Deactivate(); } } -void TriggerComponent::HandleResetSpawnerNetwork(std::string args){ +void TriggerComponent::HandleResetSpawnerNetwork(std::string args) { for (auto* spawner : Game::zoneManager->GetSpawnersByName(args)) { if (spawner) spawner->Reset(); } } -void TriggerComponent::HandleDestroySpawnerNetworkObjects(std::string args){ +void TriggerComponent::HandleDestroySpawnerNetworkObjects(std::string args) { for (auto* spawner : Game::zoneManager->GetSpawnersByName(args)) { if (spawner) spawner->DestroyAllEntities(); } @@ -436,9 +447,50 @@ void TriggerComponent::HandleDestroySpawnerNetworkObjects(std::string args){ void TriggerComponent::HandleActivatePhysics(Entity* targetEntity, std::string args) { if (args == "true") { // TODO add physics entity if there isn't one - } else if (args == "false"){ + } else if (args == "false") { // TODO remove Phsyics entity if there is one } else { LOG_DEBUG("Invalid argument for ActivatePhysics Trigger: %s", args.c_str()); } } + +void TriggerComponent::HandleSetPath(Entity* targetEntity, std::vector argArray) { + auto* movementAIComponent = targetEntity->GetComponent(); + if (!movementAIComponent) return; + // movementAIComponent->SetupPath(argArray.at(0)); + if (argArray.size() >= 2) { + auto index = GeneralUtils::TryParse(argArray.at(1)); + if (!index) return; + // movementAIComponent->SetPathStartingWaypointIndex(index.value()); + } + if (argArray.size() >= 3 && argArray.at(2) == "1") { + // movementAIComponent->ReversePath(); + } +} + +void TriggerComponent::HandleTurnAroundOnPath(Entity* targetEntity) { + auto* movementAIComponent = targetEntity->GetComponent(); + // if (movementAIComponent) movementAIComponent->ReversePath(); +} + +void TriggerComponent::HandleGoForwardOnPath(Entity* targetEntity) { + auto* movementAIComponent = targetEntity->GetComponent(); + if (!movementAIComponent) return; + // if (movementAIComponent->GetIsInReverse()) movementAIComponent->ReversePath(); +} + +void TriggerComponent::HandleGoBackwardOnPath(Entity* targetEntity) { + auto* movementAIComponent = targetEntity->GetComponent(); + if (!movementAIComponent) return; + // if (!movementAIComponent->GetIsInReverse()) movementAIComponent->ReversePath(); +} + +void TriggerComponent::HandleStopPathing(Entity* targetEntity) { + auto* movementAIComponent = targetEntity->GetComponent(); + // if (movementAIComponent) movementAIComponent->Pause(); +} + +void TriggerComponent::HandleStartPathing(Entity* targetEntity) { + auto* movementAIComponent = targetEntity->GetComponent(); + // if (movementAIComponent) movementAIComponent->Resume(); +} diff --git a/dGame/dComponents/TriggerComponent.h b/dGame/dComponents/TriggerComponent.h index 90ecc52c..94a7682e 100644 --- a/dGame/dComponents/TriggerComponent.h +++ b/dGame/dComponents/TriggerComponent.h @@ -5,9 +5,9 @@ #include "LUTriggers.h" #include "eReplicaComponentType.h" -class TriggerComponent : public Component { +class TriggerComponent final : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::TRIGGER; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::TRIGGER; explicit TriggerComponent(Entity* parent, const std::string triggerInfo); @@ -44,6 +44,12 @@ private: void HandleResetSpawnerNetwork(std::string args); void HandleDestroySpawnerNetworkObjects(std::string args); void HandleActivatePhysics(Entity* targetEntity, std::string args); + void HandleTurnAroundOnPath(Entity* targetEntity); + void HandleGoForwardOnPath(Entity* targetEntity); + void HandleGoBackwardOnPath(Entity* targetEntity); + void HandleStopPathing(Entity* targetEntity); + void HandleStartPathing(Entity* targetEntity); + void HandleSetPath(Entity* targetEntity, std::vector argArray); LUTriggers::Trigger* m_Trigger; }; diff --git a/dGame/dComponents/VendorComponent.cpp b/dGame/dComponents/VendorComponent.cpp index dfea33df..abe11ea5 100644 --- a/dGame/dComponents/VendorComponent.cpp +++ b/dGame/dComponents/VendorComponent.cpp @@ -8,6 +8,11 @@ #include "CDLootMatrixTable.h" #include "CDLootTableTable.h" #include "CDItemComponentTable.h" +#include "InventoryComponent.h" +#include "Character.h" +#include "eVendorTransactionResult.h" +#include "UserManager.h" +#include "CheatDetection.h" VendorComponent::VendorComponent(Entity* parent) : Component(parent) { m_HasStandardCostItems = false; @@ -16,11 +21,11 @@ VendorComponent::VendorComponent(Entity* parent) : Component(parent) { RefreshInventory(true); } -void VendorComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) { - outBitStream->Write(bIsInitialUpdate || m_DirtyVendor); +void VendorComponent::Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) { + outBitStream.Write(bIsInitialUpdate || m_DirtyVendor); if (bIsInitialUpdate || m_DirtyVendor) { - outBitStream->Write(m_HasStandardCostItems); - outBitStream->Write(m_HasMultiCostItems); + outBitStream.Write(m_HasStandardCostItems); + outBitStream.Write(m_HasMultiCostItems); if (!bIsInitialUpdate) m_DirtyVendor = false; } } @@ -35,36 +40,34 @@ void VendorComponent::RefreshInventory(bool isCreation) { SetHasMultiCostItems(false); m_Inventory.clear(); - // Custom code for Max vanity NPC and Mr.Ree cameras - if(isCreation && m_Parent->GetLOT() == 9749 && Game::server->GetZoneID() == 1201) { - SetupMaxCustomVendor(); + // Custom code for Vanity Vendor Invetory Override + if(m_Parent->HasVar(u"vendorInvOverride")) { + std::vector items = GeneralUtils::SplitString(m_Parent->GetVarAsString(u"vendorInvOverride"), ','); + uint32_t sortPriority = -1; + for (auto& itemString : items) { + itemString.erase(remove_if(itemString.begin(), itemString.end(), isspace), itemString.end()); + auto item = GeneralUtils::TryParse(itemString); + if (!item) continue; + if (SetupItem(item.value())) { + sortPriority++; + m_Inventory.push_back(SoldItem(item.value(), sortPriority)); + } + } return; } - auto* lootMatrixTable = CDClientManager::Instance().GetTable(); + auto* lootMatrixTable = CDClientManager::GetTable(); const auto& lootMatrices = lootMatrixTable->GetMatrix(m_LootMatrixID); if (lootMatrices.empty()) return; - auto* lootTableTable = CDClientManager::Instance().GetTable(); - auto* itemComponentTable = CDClientManager::Instance().GetTable(); - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* lootTableTable = CDClientManager::GetTable(); for (const auto& lootMatrix : lootMatrices) { auto vendorItems = lootTableTable->GetTable(lootMatrix.LootTableIndex); if (lootMatrix.maxToDrop == 0 || lootMatrix.minToDrop == 0) { for (const auto& item : vendorItems) { - if (!m_HasStandardCostItems || !m_HasMultiCostItems) { - auto itemComponentID = compRegistryTable->GetByIDAndType(item.itemid, eReplicaComponentType::ITEM, -1); - if (itemComponentID == -1) { - LOG("Attempted to add item %i with ItemComponent ID -1 to vendor %i inventory. Not adding item!", itemComponentID, m_Parent->GetLOT()); - continue; - } - auto itemComponent = itemComponentTable->GetItemComponentByID(itemComponentID); - if (!m_HasStandardCostItems && itemComponent.baseValue != -1) SetHasStandardCostItems(true); - if (!m_HasMultiCostItems && !itemComponent.currencyCosts.empty()) SetHasMultiCostItems(true); - } - m_Inventory.push_back(SoldItem(item.itemid, item.sortPriority)); + if (SetupItem(item.itemid)) m_Inventory.push_back(SoldItem(item.itemid, item.sortPriority)); } } else { auto randomCount = GeneralUtils::GenerateRandomNumber(lootMatrix.minToDrop, lootMatrix.maxToDrop); @@ -74,17 +77,7 @@ void VendorComponent::RefreshInventory(bool isCreation) { auto randomItemIndex = GeneralUtils::GenerateRandomNumber(0, vendorItems.size() - 1); const auto& randomItem = vendorItems.at(randomItemIndex); vendorItems.erase(vendorItems.begin() + randomItemIndex); - if (!m_HasStandardCostItems || !m_HasMultiCostItems) { - auto itemComponentID = compRegistryTable->GetByIDAndType(randomItem.itemid, eReplicaComponentType::ITEM, -1); - if (itemComponentID == -1) { - LOG("Attempted to add item %i with ItemComponent ID -1 to vendor %i inventory. Not adding item!", itemComponentID, m_Parent->GetLOT()); - continue; - } - auto itemComponent = itemComponentTable->GetItemComponentByID(itemComponentID); - if (!m_HasStandardCostItems && itemComponent.baseValue != -1) SetHasStandardCostItems(true); - if (!m_HasMultiCostItems && !itemComponent.currencyCosts.empty()) SetHasMultiCostItems(true); - } - m_Inventory.push_back(SoldItem(randomItem.itemid, randomItem.sortPriority)); + if (SetupItem(randomItem.itemid)) m_Inventory.push_back(SoldItem(randomItem.itemid, randomItem.sortPriority)); } } } @@ -101,10 +94,10 @@ void VendorComponent::RefreshInventory(bool isCreation) { } void VendorComponent::SetupConstants() { - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); int componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::VENDOR); - auto* vendorComponentTable = CDClientManager::Instance().GetTable(); + auto* vendorComponentTable = CDClientManager::GetTable(); std::vector vendorComps = vendorComponentTable->Query([=](CDVendorComponent entry) { return (entry.id == componentID); }); if (vendorComps.empty()) return; auto vendorData = vendorComps.at(0); @@ -121,15 +114,6 @@ bool VendorComponent::SellsItem(const LOT item) const { }) > 0; } - -void VendorComponent::SetupMaxCustomVendor(){ - SetHasStandardCostItems(true); - m_Inventory.push_back(SoldItem(11909, 0)); // Top hat w frog - m_Inventory.push_back(SoldItem(7785, 0)); // Flash bulb - m_Inventory.push_back(SoldItem(12764, 0)); // Big fountain soda - m_Inventory.push_back(SoldItem(12241, 0)); // Hot cocoa (from fb) -} - void VendorComponent::HandleMrReeCameras(){ if (m_Parent->GetLOT() == 13569) { SetHasStandardCostItems(true); @@ -151,3 +135,80 @@ void VendorComponent::HandleMrReeCameras(){ m_Inventory.push_back(SoldItem(camera, 0)); } } + + +void VendorComponent::Buy(Entity* buyer, LOT lot, uint32_t count) { + + if (!SellsItem(lot)) { + auto* user = UserManager::Instance()->GetUser(buyer->GetSystemAddress()); + CheatDetection::ReportCheat(user, buyer->GetSystemAddress(), "Attempted to buy item %i from achievement vendor %i that is not purchasable", lot, m_Parent->GetLOT()); + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + + auto* inventoryComponent = buyer->GetComponent(); + if (!inventoryComponent) { + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + int itemCompID = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::ITEM); + CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); + + // Extra currency that needs to be deducted in case of crafting + auto craftingCurrencies = CDItemComponentTable::ParseCraftingCurrencies(itemComp); + for (const auto& [crafintCurrencyLOT, crafintCurrencyCount]: craftingCurrencies) { + if (inventoryComponent->GetLotCount(crafintCurrencyLOT) < (crafintCurrencyCount * count)) { + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + } + for (const auto& [crafintCurrencyLOT, crafintCurrencyCount]: craftingCurrencies) { + inventoryComponent->RemoveItem(crafintCurrencyLOT, crafintCurrencyCount * count); + } + + + float buyScalar = GetBuyScalar(); + const auto coinCost = static_cast(std::floor((itemComp.baseValue * buyScalar) * count)); + + Character* character = buyer->GetCharacter(); + if (!character || character->GetCoins() < coinCost) { + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + + if (Inventory::IsValidItem(itemComp.currencyLOT)) { + const uint32_t altCurrencyCost = std::floor(itemComp.altCurrencyCost * buyScalar) * count; + if (inventoryComponent->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) { + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_FAIL); + return; + } + inventoryComponent->RemoveItem(itemComp.currencyLOT, altCurrencyCost); + } + + character->SetCoins(character->GetCoins() - (coinCost), eLootSourceType::VENDOR); + inventoryComponent->AddItem(lot, count, eLootSourceType::VENDOR); + GameMessages::SendVendorTransactionResult(buyer, buyer->GetSystemAddress(), eVendorTransactionResult::PURCHASE_SUCCESS); +} + +bool VendorComponent::SetupItem(LOT item) { + + auto* itemComponentTable = CDClientManager::GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); + + auto itemComponentID = compRegistryTable->GetByIDAndType(item, eReplicaComponentType::ITEM, -1); + if (itemComponentID == -1) { + LOG("Attempted to add item %i with ItemComponent ID -1 to vendor %i inventory. Not adding item!", itemComponentID, m_Parent->GetLOT()); + return false; + } + + if (!m_HasStandardCostItems || !m_HasMultiCostItems) { + auto itemComponent = itemComponentTable->GetItemComponentByID(itemComponentID); + if (!m_HasStandardCostItems && itemComponent.baseValue != -1) SetHasStandardCostItems(true); + if (!m_HasMultiCostItems && !itemComponent.currencyCosts.empty()) SetHasMultiCostItems(true); + } + + return true; +} + diff --git a/dGame/dComponents/VendorComponent.h b/dGame/dComponents/VendorComponent.h index 7924a928..432f1801 100644 --- a/dGame/dComponents/VendorComponent.h +++ b/dGame/dComponents/VendorComponent.h @@ -20,13 +20,13 @@ struct SoldItem { class VendorComponent : public Component { public: - inline static const eReplicaComponentType ComponentType = eReplicaComponentType::VENDOR; + static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::VENDOR; VendorComponent(Entity* parent); - void Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate) override; + void Serialize(RakNet::BitStream& outBitStream, bool bIsInitialUpdate) override; void OnUse(Entity* originator) override; - void RefreshInventory(bool isCreation = false); + virtual void RefreshInventory(bool isCreation = false); void SetupConstants(); bool SellsItem(const LOT item) const; float GetBuyScalar() const { return m_BuyScalar; } @@ -47,10 +47,11 @@ public: m_DirtyVendor = true; } + void Buy(Entity* buyer, LOT lot, uint32_t count); private: - void SetupMaxCustomVendor(); void HandleMrReeCameras(); + bool SetupItem(LOT item); float m_BuyScalar = 0.0f; float m_SellScalar = 0.0f; float m_RefreshTimeSeconds = 0.0f; diff --git a/dGame/dEntity/CMakeLists.txt b/dGame/dEntity/CMakeLists.txt index d7d96e14..2a418fb9 100644 --- a/dGame/dEntity/CMakeLists.txt +++ b/dGame/dEntity/CMakeLists.txt @@ -2,6 +2,6 @@ set(DGAME_DENTITY_SOURCES "EntityCallbackTimer.cpp" "EntityTimer.cpp") -add_library(dEntity STATIC ${DGAME_DENTITY_SOURCES}) +add_library(dEntity OBJECT ${DGAME_DENTITY_SOURCES}) target_include_directories(dEntity PUBLIC ".") target_precompile_headers(dEntity REUSE_FROM dGameBase) diff --git a/dGame/dGameMessages/CMakeLists.txt b/dGame/dGameMessages/CMakeLists.txt index 7373633c..0f28dea4 100644 --- a/dGame/dGameMessages/CMakeLists.txt +++ b/dGame/dGameMessages/CMakeLists.txt @@ -4,6 +4,20 @@ set(DGAME_DGAMEMESSAGES_SOURCES "PropertyDataMessage.cpp" "PropertySelectQueryProperty.cpp") -add_library(dGameMessages STATIC ${DGAME_DGAMEMESSAGES_SOURCES}) -target_link_libraries(dGameMessages PUBLIC dDatabase) +add_library(dGameMessages OBJECT ${DGAME_DGAMEMESSAGES_SOURCES}) +target_link_libraries(dGameMessages + PUBLIC dDatabase + INTERFACE dGameBase # TradingManager +) +target_include_directories(dGameMessages PUBLIC "." + PRIVATE + "${PROJECT_SOURCE_DIR}/dGame/dComponents" # direct MissionComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dUtilities" # direct SlashCommandHandler.h + "${PROJECT_SOURCE_DIR}/dGame/dPropertyBehaviors" # direct ControlBehaviors.h + "${PROJECT_SOURCE_DIR}/dGame/dMission" # via MissionComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dBehaviors" # via InventoryComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dInventory" # via InventoryComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dEntity" # via dZoneManager/Spawner.h + "${PROJECT_SOURCE_DIR}/dZoneManager" # via GameMessages.cpp, GameMessageHandler.cpp +) target_precompile_headers(dGameMessages REUSE_FROM dGameBase) diff --git a/dGame/dGameMessages/DoClientProjectileImpact.h b/dGame/dGameMessages/DoClientProjectileImpact.h index 6b381aa5..b8e3b528 100644 --- a/dGame/dGameMessages/DoClientProjectileImpact.h +++ b/dGame/dGameMessages/DoClientProjectileImpact.h @@ -19,51 +19,51 @@ public: sBitStream = _sBitStream; } - DoClientProjectileImpact(RakNet::BitStream* stream) : DoClientProjectileImpact() { + DoClientProjectileImpact(RakNet::BitStream& stream) : DoClientProjectileImpact() { Deserialize(stream); } ~DoClientProjectileImpact() { } - void Serialize(RakNet::BitStream* stream) { - stream->Write(eGameMessageType::DO_CLIENT_PROJECTILE_IMPACT); + void Serialize(RakNet::BitStream& stream) { + stream.Write(eGameMessageType::DO_CLIENT_PROJECTILE_IMPACT); - stream->Write(i64OrgID != LWOOBJID_EMPTY); - if (i64OrgID != LWOOBJID_EMPTY) stream->Write(i64OrgID); + stream.Write(i64OrgID != LWOOBJID_EMPTY); + if (i64OrgID != LWOOBJID_EMPTY) stream.Write(i64OrgID); - stream->Write(i64OwnerID != LWOOBJID_EMPTY); - if (i64OwnerID != LWOOBJID_EMPTY) stream->Write(i64OwnerID); + stream.Write(i64OwnerID != LWOOBJID_EMPTY); + if (i64OwnerID != LWOOBJID_EMPTY) stream.Write(i64OwnerID); - stream->Write(i64TargetID != LWOOBJID_EMPTY); - if (i64TargetID != LWOOBJID_EMPTY) stream->Write(i64TargetID); + stream.Write(i64TargetID != LWOOBJID_EMPTY); + if (i64TargetID != LWOOBJID_EMPTY) stream.Write(i64TargetID); uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); + stream.Write(sBitStreamLength); for (uint32_t k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); + stream.Write(sBitStream[k]); } } - bool Deserialize(RakNet::BitStream* stream) { + bool Deserialize(RakNet::BitStream& stream) { bool i64OrgIDIsDefault{}; - stream->Read(i64OrgIDIsDefault); - if (i64OrgIDIsDefault != 0) stream->Read(i64OrgID); + stream.Read(i64OrgIDIsDefault); + if (i64OrgIDIsDefault != 0) stream.Read(i64OrgID); bool i64OwnerIDIsDefault{}; - stream->Read(i64OwnerIDIsDefault); - if (i64OwnerIDIsDefault != 0) stream->Read(i64OwnerID); + stream.Read(i64OwnerIDIsDefault); + if (i64OwnerIDIsDefault != 0) stream.Read(i64OwnerID); bool i64TargetIDIsDefault{}; - stream->Read(i64TargetIDIsDefault); - if (i64TargetIDIsDefault != 0) stream->Read(i64TargetID); + stream.Read(i64TargetIDIsDefault); + if (i64TargetIDIsDefault != 0) stream.Read(i64TargetID); uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); + stream.Read(sBitStreamLength); for (uint32_t k = 0; k < sBitStreamLength; k++) { unsigned char character; - stream->Read(character); + stream.Read(character); sBitStream.push_back(character); } diff --git a/dGame/dGameMessages/EchoStartSkill.h b/dGame/dGameMessages/EchoStartSkill.h index f5dee816..dfb79021 100644 --- a/dGame/dGameMessages/EchoStartSkill.h +++ b/dGame/dGameMessages/EchoStartSkill.h @@ -13,13 +13,13 @@ public: bUsedMouse = false; fCasterLatency = 0.0f; iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; + lastClickedPosit = NiPoint3Constant::ZERO; optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; + originatorRot = NiQuaternionConstant::IDENTITY; uiSkillHandle = 0; } - EchoStartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, float _fCasterLatency = 0.0f, int32_t _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternion::IDENTITY, uint32_t _uiSkillHandle = 0) { + EchoStartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, float _fCasterLatency = 0.0f, int32_t _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3Constant::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternionConstant::IDENTITY, uint32_t _uiSkillHandle = 0) { bUsedMouse = _bUsedMouse; fCasterLatency = _fCasterLatency; iCastType = _iCastType; @@ -32,85 +32,85 @@ public: uiSkillHandle = _uiSkillHandle; } - EchoStartSkill(RakNet::BitStream* stream) : EchoStartSkill() { + EchoStartSkill(RakNet::BitStream& stream) : EchoStartSkill() { Deserialize(stream); } ~EchoStartSkill() { } - void Serialize(RakNet::BitStream* stream) { - stream->Write(eGameMessageType::ECHO_START_SKILL); + void Serialize(RakNet::BitStream& stream) { + stream.Write(eGameMessageType::ECHO_START_SKILL); - stream->Write(bUsedMouse); + stream.Write(bUsedMouse); - stream->Write(fCasterLatency != 0.0f); - if (fCasterLatency != 0.0f) stream->Write(fCasterLatency); + stream.Write(fCasterLatency != 0.0f); + if (fCasterLatency != 0.0f) stream.Write(fCasterLatency); - stream->Write(iCastType != 0); - if (iCastType != 0) stream->Write(iCastType); + stream.Write(iCastType != 0); + if (iCastType != 0) stream.Write(iCastType); - stream->Write(lastClickedPosit != NiPoint3::ZERO); - if (lastClickedPosit != NiPoint3::ZERO) stream->Write(lastClickedPosit); + stream.Write(lastClickedPosit != NiPoint3Constant::ZERO); + if (lastClickedPosit != NiPoint3Constant::ZERO) stream.Write(lastClickedPosit); - stream->Write(optionalOriginatorID); + stream.Write(optionalOriginatorID); - stream->Write(optionalTargetID != LWOOBJID_EMPTY); - if (optionalTargetID != LWOOBJID_EMPTY) stream->Write(optionalTargetID); + stream.Write(optionalTargetID != LWOOBJID_EMPTY); + if (optionalTargetID != LWOOBJID_EMPTY) stream.Write(optionalTargetID); - stream->Write(originatorRot != NiQuaternion::IDENTITY); - if (originatorRot != NiQuaternion::IDENTITY) stream->Write(originatorRot); + stream.Write(originatorRot != NiQuaternionConstant::IDENTITY); + if (originatorRot != NiQuaternionConstant::IDENTITY) stream.Write(originatorRot); uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); + stream.Write(sBitStreamLength); for (uint32_t k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); + stream.Write(sBitStream[k]); } - stream->Write(skillID); + stream.Write(skillID); - stream->Write(uiSkillHandle != 0); - if (uiSkillHandle != 0) stream->Write(uiSkillHandle); + stream.Write(uiSkillHandle != 0); + if (uiSkillHandle != 0) stream.Write(uiSkillHandle); } - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bUsedMouse); + bool Deserialize(RakNet::BitStream& stream) { + stream.Read(bUsedMouse); bool fCasterLatencyIsDefault{}; - stream->Read(fCasterLatencyIsDefault); - if (fCasterLatencyIsDefault != 0) stream->Read(fCasterLatency); + stream.Read(fCasterLatencyIsDefault); + if (fCasterLatencyIsDefault != 0) stream.Read(fCasterLatency); bool iCastTypeIsDefault{}; - stream->Read(iCastTypeIsDefault); - if (iCastTypeIsDefault != 0) stream->Read(iCastType); + stream.Read(iCastTypeIsDefault); + if (iCastTypeIsDefault != 0) stream.Read(iCastType); bool lastClickedPositIsDefault{}; - stream->Read(lastClickedPositIsDefault); - if (lastClickedPositIsDefault != 0) stream->Read(lastClickedPosit); + stream.Read(lastClickedPositIsDefault); + if (lastClickedPositIsDefault != 0) stream.Read(lastClickedPosit); - stream->Read(optionalOriginatorID); + stream.Read(optionalOriginatorID); bool optionalTargetIDIsDefault{}; - stream->Read(optionalTargetIDIsDefault); - if (optionalTargetIDIsDefault != 0) stream->Read(optionalTargetID); + stream.Read(optionalTargetIDIsDefault); + if (optionalTargetIDIsDefault != 0) stream.Read(optionalTargetID); bool originatorRotIsDefault{}; - stream->Read(originatorRotIsDefault); - if (originatorRotIsDefault != 0) stream->Read(originatorRot); + stream.Read(originatorRotIsDefault); + if (originatorRotIsDefault != 0) stream.Read(originatorRot); uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); + stream.Read(sBitStreamLength); for (uint32_t k = 0; k < sBitStreamLength; k++) { unsigned char character; - stream->Read(character); + stream.Read(character); sBitStream.push_back(character); } - stream->Read(skillID); + stream.Read(skillID); bool uiSkillHandleIsDefault{}; - stream->Read(uiSkillHandleIsDefault); - if (uiSkillHandleIsDefault != 0) stream->Read(uiSkillHandle); + stream.Read(uiSkillHandleIsDefault); + if (uiSkillHandleIsDefault != 0) stream.Read(uiSkillHandle); return true; } diff --git a/dGame/dGameMessages/EchoSyncSkill.h b/dGame/dGameMessages/EchoSyncSkill.h index ab5a3f2b..f65daab7 100644 --- a/dGame/dGameMessages/EchoSyncSkill.h +++ b/dGame/dGameMessages/EchoSyncSkill.h @@ -21,40 +21,40 @@ public: uiSkillHandle = _uiSkillHandle; } - EchoSyncSkill(RakNet::BitStream* stream) : EchoSyncSkill() { + EchoSyncSkill(RakNet::BitStream& stream) : EchoSyncSkill() { Deserialize(stream); } ~EchoSyncSkill() { } - void Serialize(RakNet::BitStream* stream) { - stream->Write(eGameMessageType::ECHO_SYNC_SKILL); + void Serialize(RakNet::BitStream& stream) { + stream.Write(eGameMessageType::ECHO_SYNC_SKILL); - stream->Write(bDone); + stream.Write(bDone); uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); + stream.Write(sBitStreamLength); for (uint32_t k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); + stream.Write(sBitStream[k]); } - stream->Write(uiBehaviorHandle); - stream->Write(uiSkillHandle); + stream.Write(uiBehaviorHandle); + stream.Write(uiSkillHandle); } - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bDone); + bool Deserialize(RakNet::BitStream& stream) { + stream.Read(bDone); uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); + stream.Read(sBitStreamLength); for (unsigned int k = 0; k < sBitStreamLength; k++) { unsigned char character; - stream->Read(character); + stream.Read(character); sBitStream.push_back(character); } - stream->Read(uiBehaviorHandle); - stream->Read(uiSkillHandle); + stream.Read(uiBehaviorHandle); + stream.Read(uiSkillHandle); return true; } diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index fa11c086..d2432e36 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -18,7 +18,6 @@ #include "Character.h" #include "ControllablePhysicsComponent.h" #include "dZoneManager.h" -#include "Player.h" #include "CppScripts.h" #include "CDClientDatabase.h" @@ -40,7 +39,7 @@ #include "GhostComponent.h" #include "StringifiedEnum.h" -void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, eGameMessageType messageID) { +void GameMessageHandler::HandleMessage(RakNet::BitStream& inStream, const SystemAddress& sysAddr, LWOOBJID objectID, eGameMessageType messageID) { CBITSTREAM; @@ -137,16 +136,14 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System } Entity* zoneControl = Game::entityManager->GetZoneControlEntity(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { - script->OnPlayerLoaded(zoneControl, entity); + if (zoneControl) { + zoneControl->GetScript()->OnPlayerLoaded(zoneControl, entity); } std::vector scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPT); for (Entity* scriptEntity : scriptedActs) { if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds - for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { - script->OnPlayerLoaded(scriptEntity, entity); - } + scriptEntity->GetScript()->OnPlayerLoaded(scriptEntity, entity); } } @@ -270,11 +267,9 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System auto* skill_component = entity->GetComponent(); if (skill_component != nullptr) { - auto* bs = new RakNet::BitStream(reinterpret_cast(const_cast(message.sBitStream.c_str())), message.sBitStream.size(), false); + auto bs = RakNet::BitStream(reinterpret_cast(&message.sBitStream[0]), message.sBitStream.size(), false); skill_component->SyncPlayerProjectile(message.i64LocalID, bs, message.i64TargetID); - - delete bs; } break; @@ -291,13 +286,13 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System comp->Progress(eMissionTaskType::USE_SKILL, startSkill.skillID); } - CDSkillBehaviorTable* skillTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillTable = CDClientManager::GetTable(); unsigned int behaviorId = skillTable->GetSkillByID(startSkill.skillID).behaviorID; bool success = false; if (behaviorId > 0) { - RakNet::BitStream* bs = new RakNet::BitStream(reinterpret_cast(const_cast(startSkill.sBitStream.c_str())), startSkill.sBitStream.size(), false); + auto bs = RakNet::BitStream(reinterpret_cast(&startSkill.sBitStream[0]), startSkill.sBitStream.size(), false); auto* skillComponent = entity->GetComponent(); @@ -307,8 +302,6 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System DestroyableComponent* destComp = entity->GetComponent(); destComp->SetImagination(destComp->GetImagination() - skillTable->GetSkillByID(startSkill.skillID).imaginationcost); } - - delete bs; } if (Game::server->GetZoneID() == 1302) { @@ -332,9 +325,9 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System echoStartSkill.sBitStream = startSkill.sBitStream; echoStartSkill.skillID = startSkill.skillID; echoStartSkill.uiSkillHandle = startSkill.uiSkillHandle; - echoStartSkill.Serialize(&bitStreamLocal); + echoStartSkill.Serialize(bitStreamLocal); - Game::server->Send(&bitStreamLocal, entity->GetSystemAddress(), true); + Game::server->Send(bitStreamLocal, entity->GetSystemAddress(), true); } } break; @@ -354,13 +347,11 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System } if (usr != nullptr) { - RakNet::BitStream* bs = new RakNet::BitStream(reinterpret_cast(const_cast(sync.sBitStream.c_str())), sync.sBitStream.size(), false); + auto bs = RakNet::BitStream(reinterpret_cast(&sync.sBitStream[0]), sync.sBitStream.size(), false); auto* skillComponent = entity->GetComponent(); skillComponent->SyncPlayerSkill(sync.uiSkillHandle, sync.uiBehaviorHandle, bs); - - delete bs; } EchoSyncSkill echo = EchoSyncSkill(); @@ -369,9 +360,9 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System echo.uiBehaviorHandle = sync.uiBehaviorHandle; echo.uiSkillHandle = sync.uiSkillHandle; - echo.Serialize(&bitStreamLocal); + echo.Serialize(bitStreamLocal); - Game::server->Send(&bitStreamLocal, sysAddr, true); + Game::server->Send(bitStreamLocal, sysAddr, true); } break; case eGameMessageType::REQUEST_SMASH_PLAYER: diff --git a/dGame/dGameMessages/GameMessageHandler.h b/dGame/dGameMessages/GameMessageHandler.h index aed3d496..2fefd008 100644 --- a/dGame/dGameMessages/GameMessageHandler.h +++ b/dGame/dGameMessages/GameMessageHandler.h @@ -22,7 +22,7 @@ #include "eGameMessageType.h" namespace GameMessageHandler { - void HandleMessage(RakNet::BitStream* inStream, const SystemAddress& sysAddr, LWOOBJID objectID, eGameMessageType messageID); + void HandleMessage(RakNet::BitStream& inStream, const SystemAddress& sysAddr, LWOOBJID objectID, eGameMessageType messageID); }; #endif // GAMEMESSAGEHANDLER_H diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 595444e9..c144675b 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -20,7 +20,6 @@ #include "WorldPackets.h" #include "Item.h" #include "ZCompression.h" -#include "Player.h" #include "dConfig.h" #include "TeamManager.h" #include "ChatPackets.h" @@ -79,6 +78,7 @@ #include "LevelProgressionComponent.h" #include "DonationVendorComponent.h" #include "GhostComponent.h" +#include "AchievementVendorComponent.h" // Message includes: #include "dZoneManager.h" @@ -98,6 +98,7 @@ #include "ePetAbilityType.h" #include "ActivityManager.h" #include "PlayerManager.h" +#include "eVendorTransactionResult.h" #include "CDComponentsRegistryTable.h" #include "CDObjectsTable.h" @@ -321,8 +322,8 @@ void GameMessages::SendPlayNDAudioEmitter(Entity* entity, const SystemAddress& s bitStream.Write(entity->GetObjectID()); bitStream.Write(eGameMessageType::PLAY_ND_AUDIO_EMITTER); - bitStream.Write0(); - bitStream.Write0(); + bitStream.Write0(); // callback message data {lwoobjid} + bitStream.Write0(); // audio emitterid {uint32_t} uint32_t length = audioGUID.size(); bitStream.Write(length); @@ -330,9 +331,9 @@ void GameMessages::SendPlayNDAudioEmitter(Entity* entity, const SystemAddress& s bitStream.Write(audioGUID[k]); } - bitStream.Write(0); - bitStream.Write0(); - bitStream.Write0(); + bitStream.Write(0); // size of NDAudioMetaEventName (then print the string like the guid) + bitStream.Write0(); // result {bool} + bitStream.Write0(); // m_TargetObjectIDForNDAudioCallbackMessages {lwoobjid} SEND_PACKET_BROADCAST; } @@ -385,8 +386,8 @@ void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAd float fIdleTimeElapsed = 0.0f; float fMoveTimeElapsed = 0.0f; float fPercentBetweenPoints = 0.0f; - NiPoint3 ptUnexpectedLocation = NiPoint3::ZERO; - NiQuaternion qUnexpectedRotation = NiQuaternion::IDENTITY; + NiPoint3 ptUnexpectedLocation = NiPoint3Constant::ZERO; + NiQuaternion qUnexpectedRotation = NiQuaternionConstant::IDENTITY; bitStream.Write(bReverse); bitStream.Write(bStopAtDesiredWaypoint); @@ -403,8 +404,8 @@ void GameMessages::SendPlatformResync(Entity* entity, const SystemAddress& sysAd bitStream.Write(ptUnexpectedLocation.y); bitStream.Write(ptUnexpectedLocation.z); - bitStream.Write(qUnexpectedRotation != NiQuaternion::IDENTITY); - if (qUnexpectedRotation != NiQuaternion::IDENTITY) { + bitStream.Write(qUnexpectedRotation != NiQuaternionConstant::IDENTITY); + if (qUnexpectedRotation != NiQuaternionConstant::IDENTITY) { bitStream.Write(qUnexpectedRotation.x); bitStream.Write(qUnexpectedRotation.y); bitStream.Write(qUnexpectedRotation.z); @@ -625,6 +626,25 @@ void GameMessages::SendUIMessageServerToSingleClient(Entity* entity, const Syste SEND_PACKET; } +void GameMessages::SendUIMessageServerToSingleClient(const std::string& message, AMFBaseValue& args, const SystemAddress& sysAddr) { + CBITSTREAM; + CMSGHEADER; + + LWOOBJID empty = 0; + bitStream.Write(empty); + bitStream.Write(eGameMessageType::UI_MESSAGE_SERVER_TO_ALL_CLIENTS); // This is intentional to allow the server to send a ui message to a client via their system address. + + bitStream.Write(args); + uint32_t strMessageNameLength = message.size(); + bitStream.Write(strMessageNameLength); + + for (uint32_t k = 0; k < strMessageNameLength; k++) { + bitStream.Write(message[k]); + } + + SEND_PACKET; +} + void GameMessages::SendUIMessageServerToAllClients(const std::string& message, AMFBaseValue& args) { CBITSTREAM; CMSGHEADER; @@ -751,7 +771,7 @@ void GameMessages::SendSetCurrency(Entity* entity, int64_t currency, int lootTyp bitStream.Write(lootType != LOOTTYPE_NONE); if (lootType != LOOTTYPE_NONE) bitStream.Write(lootType); - bitStream.Write(NiPoint3::ZERO); + bitStream.Write(NiPoint3Constant::ZERO); bitStream.Write(sourceLOT != LOT_NULL); if (sourceLOT != LOT_NULL) bitStream.Write(sourceLOT); @@ -1060,7 +1080,7 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, entity->RegisterCoinDrop(currency); } - if (spawnPos != NiPoint3::ZERO) { + if (spawnPos != NiPoint3Constant::ZERO) { bUsePosition = true; //Calculate where the loot will go: @@ -1082,8 +1102,8 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, bitStream.Write(bUsePosition); - bitStream.Write(finalPosition != NiPoint3::ZERO); - if (finalPosition != NiPoint3::ZERO) bitStream.Write(finalPosition); + bitStream.Write(finalPosition != NiPoint3Constant::ZERO); + if (finalPosition != NiPoint3Constant::ZERO) bitStream.Write(finalPosition); bitStream.Write(currency); bitStream.Write(item); @@ -1091,14 +1111,14 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, bitStream.Write(owner); bitStream.Write(sourceID); - bitStream.Write(spawnPos != NiPoint3::ZERO); - if (spawnPos != NiPoint3::ZERO) bitStream.Write(spawnPos); + bitStream.Write(spawnPos != NiPoint3Constant::ZERO); + if (spawnPos != NiPoint3Constant::ZERO) bitStream.Write(spawnPos); auto* team = TeamManager::Instance()->GetTeam(owner); // Currency and powerups should not sync if (team != nullptr && currency == 0) { - CDObjectsTable* objectsTable = CDClientManager::Instance().GetTable(); + CDObjectsTable* objectsTable = CDClientManager::GetTable(); const CDObjects& object = objectsTable->GetByID(item); @@ -1151,7 +1171,7 @@ void GameMessages::SendPlayerReachedRespawnCheckpoint(Entity* entity, const NiPo bitStream.Write(position.y); bitStream.Write(position.z); - const bool bIsNotIdentity = rotation != NiQuaternion::IDENTITY; + const bool bIsNotIdentity = rotation != NiQuaternionConstant::IDENTITY; bitStream.Write(bIsNotIdentity); if (bIsNotIdentity) { @@ -1305,15 +1325,14 @@ void GameMessages::SendVendorStatusUpdate(Entity* entity, const SystemAddress& s SEND_PACKET; } -void GameMessages::SendVendorTransactionResult(Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::SendVendorTransactionResult(Entity* entity, const SystemAddress& sysAddr, eVendorTransactionResult result) { CBITSTREAM; CMSGHEADER; - int iResult = 0x02; // success, seems to be the only relevant one bitStream.Write(entity->GetObjectID()); bitStream.Write(eGameMessageType::VENDOR_TRANSACTION_RESULT); - bitStream.Write(iResult); + bitStream.Write(result); SEND_PACKET; } @@ -1625,17 +1644,17 @@ void GameMessages::SendNotifyClientShootingGalleryScore(LWOOBJID objectId, const } -void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleUpdateShootingGalleryRotation(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { float angle = 0.0f; - NiPoint3 facing = NiPoint3::ZERO; - NiPoint3 muzzlePos = NiPoint3::ZERO; - inStream->Read(angle); - inStream->Read(facing); - inStream->Read(muzzlePos); + NiPoint3 facing = NiPoint3Constant::ZERO; + NiPoint3 muzzlePos = NiPoint3Constant::ZERO; + inStream.Read(angle); + inStream.Read(facing); + inStream.Read(muzzlePos); } -void GameMessages::HandleActivitySummaryLeaderboardData(RakNet::BitStream* instream, Entity* entity, +void GameMessages::HandleActivitySummaryLeaderboardData(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { LOG("We got mail!"); } @@ -1647,48 +1666,48 @@ void GameMessages::SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, bitStream.Write(objectID); bitStream.Write(eGameMessageType::SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA); - leaderboard->Serialize(&bitStream); + leaderboard->Serialize(bitStream); SEND_PACKET; } -void GameMessages::HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { int32_t gameID = 0; - if (inStream->ReadBit()) inStream->Read(gameID); + if (inStream.ReadBit()) inStream.Read(gameID); Leaderboard::InfoType queryType = Leaderboard::InfoType::MyStanding; - if (inStream->ReadBit()) inStream->Read(queryType); + if (inStream.ReadBit()) inStream.Read(queryType); int32_t resultsEnd = 10; - if (inStream->ReadBit()) inStream->Read(resultsEnd); + if (inStream.ReadBit()) inStream.Read(resultsEnd); int32_t resultsStart = 0; - if (inStream->ReadBit()) inStream->Read(resultsStart); + if (inStream.ReadBit()) inStream.Read(resultsStart); LWOOBJID target{}; - inStream->Read(target); + inStream.Read(target); - bool weekly = inStream->ReadBit(); + bool weekly = inStream.ReadBit(); LeaderboardManager::SendLeaderboard(gameID, queryType, weekly, entity->GetObjectID(), entity->GetObjectID(), resultsStart, resultsEnd); } -void GameMessages::HandleActivityStateChangeRequest(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleActivityStateChangeRequest(RakNet::BitStream& inStream, Entity* entity) { LWOOBJID objectID; - inStream->Read(objectID); + inStream.Read(objectID); int32_t value1; - inStream->Read(value1); + inStream.Read(value1); int32_t value2; - inStream->Read(value2); + inStream.Read(value2); uint32_t stringValueLength; - inStream->Read(stringValueLength); + inStream.Read(stringValueLength); std::u16string stringValue; for (uint32_t i = 0; i < stringValueLength; ++i) { uint16_t character; - inStream->Read(character); + inStream.Read(character); stringValue.push_back(character); } @@ -2084,8 +2103,8 @@ void GameMessages::SendPlaceModelResponse(LWOOBJID objectId, const SystemAddress bitStream.Write(objectId); bitStream.Write(eGameMessageType::PLACE_MODEL_RESPONSE); - bitStream.Write(position != NiPoint3::ZERO); - if (position != NiPoint3::ZERO) { + bitStream.Write(position != NiPoint3Constant::ZERO); + if (position != NiPoint3Constant::ZERO) { bitStream.Write(position); } @@ -2099,8 +2118,8 @@ void GameMessages::SendPlaceModelResponse(LWOOBJID objectId, const SystemAddress bitStream.Write(response); } - bitStream.Write(rotation != NiQuaternion::IDENTITY); - if (rotation != NiQuaternion::IDENTITY) { + bitStream.Write(rotation != NiQuaternionConstant::IDENTITY); + if (rotation != NiQuaternionConstant::IDENTITY) { bitStream.Write(response); } @@ -2141,17 +2160,17 @@ void GameMessages::SendUGCEquipPostDeleteBasedOnEditMode(LWOOBJID objectId, cons SEND_PACKET; } -void GameMessages::HandleSetPropertyAccess(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleSetPropertyAccess(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { uint8_t accessType{}; int32_t renew{}; bool accessTypeIsDefault{}; - inStream->Read(accessTypeIsDefault); - if (accessTypeIsDefault != 0) inStream->Read(accessType); + inStream.Read(accessTypeIsDefault); + if (accessTypeIsDefault != 0) inStream.Read(accessType); bool renewIsDefault{}; - inStream->Read(renewIsDefault); - if (renewIsDefault != 0) inStream->Read(renew); + inStream.Read(renewIsDefault); + if (renewIsDefault != 0) inStream.Read(renew); LOG("Set privacy option to: %i", accessType); @@ -2160,11 +2179,11 @@ void GameMessages::HandleSetPropertyAccess(RakNet::BitStream* inStream, Entity* PropertyManagementComponent::Instance()->SetPrivacyOption(static_cast(accessType)); } -void GameMessages::HandleUnUseModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleUnUseModel(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { bool unknown{}; LWOOBJID objIdToAddToInventory{}; - inStream->Read(unknown); - inStream->Read(objIdToAddToInventory); + inStream.Read(unknown); + inStream.Read(objIdToAddToInventory); auto* inventoryComponent = entity->GetComponent(); if (inventoryComponent) { auto* inventory = inventoryComponent->GetInventory(eInventoryType::MODELS_IN_BBB); @@ -2186,7 +2205,7 @@ void GameMessages::HandleUnUseModel(RakNet::BitStream* inStream, Entity* entity, } } -void GameMessages::HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { bool isProperty{}; LWOOBJID objectId{}; LWOOBJID playerId{}; @@ -2196,29 +2215,29 @@ void GameMessages::HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream* uint32_t descriptionLength{}; std::u16string description{}; - inStream->Read(isProperty); - inStream->Read(objectId); - inStream->Read(playerId); - inStream->Read(worldId); + inStream.Read(isProperty); + inStream.Read(objectId); + inStream.Read(playerId); + inStream.Read(worldId); - inStream->Read(descriptionLength); + inStream.Read(descriptionLength); for (uint32_t i = 0; i < descriptionLength; ++i) { uint16_t character; - inStream->Read(character); + inStream.Read(character); description.push_back(character); } - inStream->Read(nameLength); + inStream.Read(nameLength); for (uint32_t i = 0; i < nameLength; ++i) { uint16_t character; - inStream->Read(character); + inStream.Read(character); name.push_back(character); } PropertyManagementComponent::Instance()->UpdatePropertyDetails(GeneralUtils::UTF16ToWTF8(name), GeneralUtils::UTF16ToWTF8(description)); } -void GameMessages::HandleQueryPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleQueryPropertyData(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { LOG("Entity (%i) requesting data", entity->GetLOT()); /* @@ -2246,32 +2265,32 @@ void GameMessages::HandleQueryPropertyData(RakNet::BitStream* inStream, Entity* } } -void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleSetBuildMode(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { bool start{}; int32_t distanceType = -1; bool modePaused{}; int modeValue = 1; LWOOBJID playerId{}; - NiPoint3 startPosition = NiPoint3::ZERO; + NiPoint3 startPosition = NiPoint3Constant::ZERO; - inStream->Read(start); + inStream.Read(start); - if (inStream->ReadBit()) - inStream->Read(distanceType); + if (inStream.ReadBit()) + inStream.Read(distanceType); - inStream->Read(modePaused); + inStream.Read(modePaused); - if (inStream->ReadBit()) - inStream->Read(modeValue); + if (inStream.ReadBit()) + inStream.Read(modeValue); - inStream->Read(playerId); + inStream.Read(playerId); - if (inStream->ReadBit()) - inStream->Read(startPosition); + if (inStream.ReadBit()) + inStream.Read(startPosition); auto* player = Game::entityManager->GetEntity(playerId); - if (startPosition == NiPoint3::ZERO) { + if (startPosition == NiPoint3Constant::ZERO) { startPosition = player->GetPosition(); } @@ -2282,7 +2301,7 @@ void GameMessages::HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entit SendSetBuildModeConfirmed(entity->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS, start, false, modePaused, modeValue, playerId, startPosition); } -void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { if (!entity->HasComponent(eReplicaComponentType::PROPERTY_MANAGEMENT)) { return; } @@ -2298,16 +2317,16 @@ void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Enti NiPoint3 targetPosition{}; int32_t targetType{}; - inStream->Read(firstTime); - inStream->Read(success); - inStream->Read(sourceBag); - inStream->Read(sourceId); - inStream->Read(sourceLot); - inStream->Read(sourceType); - inStream->Read(targetId); - inStream->Read(targetLot); - inStream->Read(targetPosition); - inStream->Read(targetType); + inStream.Read(firstTime); + inStream.Read(success); + inStream.Read(sourceBag); + inStream.Read(sourceId); + inStream.Read(sourceLot); + inStream.Read(sourceType); + inStream.Read(targetId); + inStream.Read(targetLot); + inStream.Read(targetPosition); + inStream.Read(targetType); if (sourceType == 1) { sourceType = 4; @@ -2336,19 +2355,19 @@ void GameMessages::HandleStartBuildingWithItem(RakNet::BitStream* inStream, Enti ); } -void GameMessages::HandlePropertyEditorBegin(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandlePropertyEditorBegin(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { PropertyManagementComponent::Instance()->OnStartBuilding(); Game::zoneManager->GetZoneControlObject()->OnZonePropertyEditBegin(); } -void GameMessages::HandlePropertyEditorEnd(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandlePropertyEditorEnd(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { PropertyManagementComponent::Instance()->OnFinishBuilding(); Game::zoneManager->GetZoneControlObject()->OnZonePropertyEditEnd(); } -void GameMessages::HandlePropertyContentsFromClient(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandlePropertyContentsFromClient(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { User* user = UserManager::Instance()->GetUser(sysAddr); Entity* player = Game::entityManager->GetEntity(user->GetLoggedInChar()); @@ -2356,52 +2375,52 @@ void GameMessages::HandlePropertyContentsFromClient(RakNet::BitStream* inStream, SendGetModelsOnProperty(player->GetObjectID(), PropertyManagementComponent::Instance()->GetModels(), UNASSIGNED_SYSTEM_ADDRESS); } -void GameMessages::HandlePropertyModelEquipped(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandlePropertyModelEquipped(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { Game::zoneManager->GetZoneControlObject()->OnZonePropertyModelEquipped(); } -void GameMessages::HandlePlacePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandlePlacePropertyModel(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID model; - inStream->Read(model); + inStream.Read(model); - PropertyManagementComponent::Instance()->UpdateModelPosition(model, NiPoint3::ZERO, NiQuaternion::IDENTITY); + PropertyManagementComponent::Instance()->UpdateModelPosition(model, NiPoint3Constant::ZERO, NiQuaternionConstant::IDENTITY); } -void GameMessages::HandleUpdatePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleUpdatePropertyModel(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID model; NiPoint3 position; - NiQuaternion rotation = NiQuaternion::IDENTITY; + NiQuaternion rotation = NiQuaternionConstant::IDENTITY; - inStream->Read(model); - inStream->Read(position); + inStream.Read(model); + inStream.Read(position); - if (inStream->ReadBit()) { - inStream->Read(rotation); + if (inStream.ReadBit()) { + inStream.Read(rotation); } PropertyManagementComponent::Instance()->UpdateModelPosition(model, position, rotation); } -void GameMessages::HandleDeletePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleDeletePropertyModel(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID model = LWOOBJID_EMPTY; int deleteReason = 0; - if (inStream->ReadBit()) { - inStream->Read(model); + if (inStream.ReadBit()) { + inStream.Read(model); } - if (inStream->ReadBit()) { - inStream->Read(deleteReason); + if (inStream.ReadBit()) { + inStream.Read(deleteReason); } PropertyManagementComponent::Instance()->DeleteModel(model, deleteReason); } -void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleBBBLoadItemRequest(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID previousItemID = LWOOBJID_EMPTY; - inStream->Read(previousItemID); + inStream.Read(previousItemID); LOG("Load item request for: %lld", previousItemID); LWOOBJID newId = previousItemID; @@ -2468,28 +2487,29 @@ void GameMessages::SendUnSmash(Entity* entity, LWOOBJID builderID, float duratio SEND_PACKET_BROADCAST; } -void GameMessages::HandleControlBehaviors(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleControlBehaviors(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { AMFDeserialize reader; - std::unique_ptr amfArguments(reader.Read(inStream)); + std::unique_ptr amfArguments{ static_cast(reader.Read(inStream)) }; if (amfArguments->GetValueType() != eAmf::Array) return; uint32_t commandLength{}; - inStream->Read(commandLength); + inStream.Read(commandLength); std::string command; - for (uint32_t i = 0; i < commandLength; i++) { + command.reserve(commandLength); + for (uint32_t i = 0; i < commandLength; ++i) { unsigned char character; - inStream->Read(character); + inStream.Read(character); command.push_back(character); } - auto owner = PropertyManagementComponent::Instance()->GetOwner(); + auto* const owner = PropertyManagementComponent::Instance()->GetOwner(); if (!owner) return; - ControlBehaviors::Instance().ProcessCommand(entity, sysAddr, static_cast(amfArguments.get()), command, owner); + ControlBehaviors::Instance().ProcessCommand(entity, *amfArguments, command, owner); } -void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleBBBSaveRequest(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { /* ___ ___ /\ /\___ _ __ ___ / __\ ___ / \_ __ __ _ __ _ ___ _ __ ___ @@ -2520,18 +2540,18 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent */ LWOOBJID localId; - inStream->Read(localId); + inStream.Read(localId); uint32_t sd0Size; - inStream->Read(sd0Size); + inStream.Read(sd0Size); std::shared_ptr sd0Data(new char[sd0Size]); if (sd0Data == nullptr) return; - inStream->ReadAlignedBytes(reinterpret_cast(sd0Data.get()), sd0Size); + inStream.ReadAlignedBytes(reinterpret_cast(sd0Data.get()), sd0Size); uint32_t timeTaken; - inStream->Read(timeTaken); + inStream.Read(timeTaken); /* Disabled this, as it's kinda silly to do this roundabout way of storing plaintext lxfml, then recompressing @@ -2565,6 +2585,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //We need to get a new ID for our model first: ObjectIDManager::RequestPersistentID([=](uint32_t newID) { + if (!entity || !entity->GetCharacter() || !entity->GetCharacter()->GetParentUser()) return; LWOOBJID newIDL = newID; GeneralUtils::SetBit(newIDL, eObjectBits::CHARACTER); GeneralUtils::SetBit(newIDL, eObjectBits::PERSISTENT); @@ -2587,13 +2608,13 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //Insert into ugc: std::string str(sd0Data.get(), sd0Size); std::istringstream sd0DataStream(str); - Database::Get()->InsertNewUgcModel(sd0DataStream, blueprintIDSmall, entity->GetParentUser()->GetAccountID(), entity->GetCharacter()->GetID()); + Database::Get()->InsertNewUgcModel(sd0DataStream, blueprintIDSmall, entity->GetCharacter()->GetParentUser()->GetAccountID(), entity->GetCharacter()->GetID()); //Insert into the db as a BBB model: IPropertyContents::Model model; model.id = newIDL; model.ugcId = blueprintIDSmall; - model.position = NiPoint3::ZERO; + model.position = NiPoint3Constant::ZERO; model.rotation = NiQuaternion(0.0f, 0.0f, 0.0f, 0.0f); model.lot = 14; Database::Get()->InsertNewPropertyModel(propertyId, model, "Objects_14_name"); @@ -2667,7 +2688,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent }); } -void GameMessages::HandlePropertyEntranceSync(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandlePropertyEntranceSync(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { bool includeNullAddress{}; bool includeNullDescription{}; bool playerOwn{}; @@ -2679,19 +2700,19 @@ void GameMessages::HandlePropertyEntranceSync(RakNet::BitStream* inStream, Entit uint32_t filterTextLength{}; std::string filterText{}; - inStream->Read(includeNullAddress); - inStream->Read(includeNullDescription); - inStream->Read(playerOwn); - inStream->Read(updateUi); - inStream->Read(numResults); - inStream->Read(reputation); - inStream->Read(sortMethod); - inStream->Read(startIndex); - inStream->Read(filterTextLength); + inStream.Read(includeNullAddress); + inStream.Read(includeNullDescription); + inStream.Read(playerOwn); + inStream.Read(updateUi); + inStream.Read(numResults); + inStream.Read(reputation); + inStream.Read(sortMethod); + inStream.Read(startIndex); + inStream.Read(filterTextLength); for (auto i = 0u; i < filterTextLength; i++) { char c; - inStream->Read(c); + inStream.Read(c); filterText.push_back(c); } @@ -2715,12 +2736,12 @@ void GameMessages::HandlePropertyEntranceSync(RakNet::BitStream* inStream, Entit ); } -void GameMessages::HandleEnterProperty(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleEnterProperty(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { uint32_t index{}; bool returnToZone{}; - inStream->Read(index); - inStream->Read(returnToZone); + inStream.Read(index); + inStream.Read(returnToZone); auto* player = PlayerManager::GetPlayer(sysAddr); @@ -2736,10 +2757,10 @@ void GameMessages::HandleEnterProperty(RakNet::BitStream* inStream, Entity* enti } } -void GameMessages::HandleSetConsumableItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleSetConsumableItem(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { LOT lot; - inStream->Read(lot); + inStream.Read(lot); auto* inventory = entity->GetComponent(); @@ -2811,43 +2832,43 @@ void GameMessages::SendEndCinematic(LWOOBJID objectId, std::u16string pathName, SEND_PACKET; } -void GameMessages::HandleCinematicUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleCinematicUpdate(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { eCinematicEvent event; - if (!inStream->ReadBit()) { + if (!inStream.ReadBit()) { event = eCinematicEvent::STARTED; } else { - inStream->Read(event); + inStream.Read(event); } float_t overallTime; - if (!inStream->ReadBit()) { + if (!inStream.ReadBit()) { overallTime = -1.0f; } else { - inStream->Read(overallTime); + inStream.Read(overallTime); } uint32_t pathNameLength; - inStream->Read(pathNameLength); + inStream.Read(pathNameLength); std::u16string pathName; for (size_t i = 0; i < pathNameLength; i++) { char16_t character; - inStream->Read(character); + inStream.Read(character); pathName.push_back(character); } float_t pathTime; - if (!inStream->ReadBit()) { + if (!inStream.ReadBit()) { pathTime = -1.0f; } else { - inStream->Read(pathTime); + inStream.Read(pathTime); } int32_t waypoint; - if (!inStream->ReadBit()) { + if (!inStream.ReadBit()) { waypoint = -1; } else { - inStream->Read(waypoint); + inStream.Read(waypoint); } std::vector scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPT); @@ -3068,23 +3089,23 @@ void GameMessages::SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std SEND_PACKET; } -void GameMessages::HandleVerifyAck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleVerifyAck(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { bool bDifferent; std::string sBitStream; uint32_t uiHandle = 0; - bDifferent = inStream->ReadBit(); + bDifferent = inStream.ReadBit(); uint32_t sBitStreamLength = 0; - inStream->Read(sBitStreamLength); + inStream.Read(sBitStreamLength); for (uint64_t k = 0; k < sBitStreamLength; k++) { uint8_t character; - inStream->Read(character); + inStream.Read(character); sBitStream.push_back(character); } - if (inStream->ReadBit()) { - inStream->Read(uiHandle); + if (inStream.ReadBit()) { + inStream.Read(uiHandle); } } @@ -3211,7 +3232,7 @@ void GameMessages::SendServerTradeUpdate(LWOOBJID objectId, uint64_t coins, cons SEND_PACKET; } -void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleClientTradeRequest(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { // Check if the player has restricted trade access auto* character = entity->GetCharacter(); @@ -3225,10 +3246,10 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* return; } - bool bNeedInvitePopUp = inStream->ReadBit(); + bool bNeedInvitePopUp = inStream.ReadBit(); LWOOBJID i64Invitee; - inStream->Read(i64Invitee); + inStream.Read(i64Invitee); auto* invitee = Game::entityManager->GetEntity(i64Invitee); @@ -3251,7 +3272,7 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* if (trade != nullptr) { if (!trade->IsParticipant(i64Invitee)) { - TradingManager::Instance()->CancelTrade(trade->GetTradeId()); + TradingManager::Instance()->CancelTrade(entity->GetObjectID(), trade->GetTradeId()); TradingManager::Instance()->NewTrade(entity->GetObjectID(), i64Invitee); } @@ -3269,18 +3290,18 @@ void GameMessages::HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* } } -void GameMessages::HandleClientTradeCancel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleClientTradeCancel(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { auto* trade = TradingManager::Instance()->GetPlayerTrade(entity->GetObjectID()); if (trade == nullptr) return; LOG("Trade canceled from (%llu)", entity->GetObjectID()); - TradingManager::Instance()->CancelTrade(trade->GetTradeId()); + TradingManager::Instance()->CancelTrade(entity->GetObjectID(), trade->GetTradeId()); } -void GameMessages::HandleClientTradeAccept(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - bool bFirst = inStream->ReadBit(); +void GameMessages::HandleClientTradeAccept(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { + bool bFirst = inStream.ReadBit(); LOG("Trade accepted from (%llu) -> (%d)", entity->GetObjectID(), bFirst); @@ -3291,12 +3312,12 @@ void GameMessages::HandleClientTradeAccept(RakNet::BitStream* inStream, Entity* trade->SetAccepted(entity->GetObjectID(), bFirst); } -void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleClientTradeUpdate(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { uint64_t currency; uint32_t itemCount; - inStream->Read(currency); - inStream->Read(itemCount); + inStream.Read(currency); + inStream.Read(itemCount); LOG("Trade update from (%llu) -> (%llu), (%i)", entity->GetObjectID(), currency, itemCount); @@ -3306,8 +3327,8 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* LWOOBJID itemId; LWOOBJID itemId2; - inStream->Read(itemId); - inStream->Read(itemId2); + inStream.Read(itemId); + inStream.Read(itemId2); LOT lot = 0; LWOOBJID unknown1 = 0; @@ -3317,32 +3338,32 @@ void GameMessages::HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* uint32_t ldfSize = 0; bool unknown4; - inStream->Read(lot); - if (inStream->ReadBit()) { - inStream->Read(unknown1); + inStream.Read(lot); + if (inStream.ReadBit()) { + inStream.Read(unknown1); } - if (inStream->ReadBit()) { - inStream->Read(unknown2); + if (inStream.ReadBit()) { + inStream.Read(unknown2); } - if (inStream->ReadBit()) { - inStream->Read(slot); + if (inStream.ReadBit()) { + inStream.Read(slot); } - if (inStream->ReadBit()) { - inStream->Read(unknown3); + if (inStream.ReadBit()) { + inStream.Read(unknown3); } - if (inStream->ReadBit()) // No + if (inStream.ReadBit()) // No { - inStream->Read(ldfSize); - bool compressed = inStream->ReadBit(); + inStream.Read(ldfSize); + bool compressed = inStream.ReadBit(); if (compressed) { uint32_t ldfCompressedSize = 0; - inStream->Read(ldfCompressedSize); - inStream->IgnoreBytes(ldfCompressedSize); + inStream.Read(ldfCompressedSize); + inStream.IgnoreBytes(ldfCompressedSize); } else { - inStream->IgnoreBytes(ldfSize); + inStream.IgnoreBytes(ldfSize); } } - unknown4 = inStream->ReadBit(); + unknown4 = inStream.ReadBit(); items.push_back({ itemId, lot, unknown2 }); @@ -3374,7 +3395,7 @@ void GameMessages::SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId bitStream.Write(petsDestPos); bitStream.Write(telePos); - const bool hasDefault = teleRot != NiQuaternion::IDENTITY; + const bool hasDefault = teleRot != NiQuaternionConstant::IDENTITY; bitStream.Write(hasDefault); if (hasDefault) bitStream.Write(teleRot); @@ -3637,8 +3658,8 @@ void GameMessages::SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatu } -void GameMessages::HandleClientExitTamingMinigame(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - bool bVoluntaryExit = inStream->ReadBit(); +void GameMessages::HandleClientExitTamingMinigame(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { + bool bVoluntaryExit = inStream.ReadBit(); auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); @@ -3649,7 +3670,7 @@ void GameMessages::HandleClientExitTamingMinigame(RakNet::BitStream* inStream, E petComponent->ClientExitTamingMinigame(bVoluntaryExit); } -void GameMessages::HandleStartServerPetMinigameTimer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleStartServerPetMinigameTimer(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); if (petComponent == nullptr) { @@ -3659,24 +3680,24 @@ void GameMessages::HandleStartServerPetMinigameTimer(RakNet::BitStream* inStream petComponent->StartTimer(); } -void GameMessages::HandlePetTamingTryBuild(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandlePetTamingTryBuild(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { uint32_t brickCount; std::vector bricks; bool clientFailed; - inStream->Read(brickCount); + inStream.Read(brickCount); bricks.reserve(brickCount); for (uint32_t i = 0; i < brickCount; i++) { Brick brick; - inStream->Read(brick); + inStream.Read(brick); bricks.push_back(brick); } - clientFailed = inStream->ReadBit(); + clientFailed = inStream.ReadBit(); auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); @@ -3687,10 +3708,10 @@ void GameMessages::HandlePetTamingTryBuild(RakNet::BitStream* inStream, Entity* petComponent->TryBuild(bricks.size(), clientFailed); } -void GameMessages::HandleNotifyTamingBuildSuccess(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleNotifyTamingBuildSuccess(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { NiPoint3 position; - inStream->Read(position); + inStream.Read(position); auto* petComponent = PetComponent::GetTamingPet(entity->GetObjectID()); @@ -3701,15 +3722,15 @@ void GameMessages::HandleNotifyTamingBuildSuccess(RakNet::BitStream* inStream, E petComponent->NotifyTamingBuildSuccess(position); } -void GameMessages::HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleRequestSetPetName(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { uint32_t nameLength; std::u16string name; - inStream->Read(nameLength); + inStream.Read(nameLength); for (size_t i = 0; i < nameLength; i++) { char16_t character; - inStream->Read(character); + inStream.Read(character); name.push_back(character); } @@ -3726,18 +3747,18 @@ void GameMessages::HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* petComponent->RequestSetPetName(name); } -void GameMessages::HandleCommandPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleCommandPet(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { NiPoint3 genericPosInfo; LWOOBJID objIdSource; int32_t iPetCommandType; int32_t iTypeID; bool overrideObey; - inStream->Read(genericPosInfo); - inStream->Read(objIdSource); - inStream->Read(iPetCommandType); - inStream->Read(iTypeID); - overrideObey = inStream->ReadBit(); + inStream.Read(genericPosInfo); + inStream.Read(objIdSource); + inStream.Read(iPetCommandType); + inStream.Read(iTypeID); + overrideObey = inStream.ReadBit(); auto* petComponent = entity->GetComponent(); @@ -3748,10 +3769,10 @@ void GameMessages::HandleCommandPet(RakNet::BitStream* inStream, Entity* entity, petComponent->Command(genericPosInfo, objIdSource, iPetCommandType, iTypeID, overrideObey); } -void GameMessages::HandleDespawnPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleDespawnPet(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { bool bDeletePet; - bDeletePet = inStream->ReadBit(); + bDeletePet = inStream.ReadBit(); auto* petComponent = PetComponent::GetActivePet(entity->GetObjectID()); @@ -3766,26 +3787,26 @@ void GameMessages::HandleDespawnPet(RakNet::BitStream* inStream, Entity* entity, } } -void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleMessageBoxResponse(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { int32_t iButton; uint32_t identifierLength; std::u16string identifier; uint32_t userDataLength; std::u16string userData; - inStream->Read(iButton); + inStream.Read(iButton); - inStream->Read(identifierLength); + inStream.Read(identifierLength); for (size_t i = 0; i < identifierLength; i++) { char16_t character; - inStream->Read(character); + inStream.Read(character); identifier.push_back(character); } - inStream->Read(userDataLength); + inStream.Read(userDataLength); for (size_t i = 0; i < userDataLength; i++) { char16_t character; - inStream->Read(character); + inStream.Read(character); userData.push_back(character); } @@ -3822,26 +3843,26 @@ void GameMessages::HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* } } -void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleChoiceBoxRespond(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { int32_t iButton; uint32_t buttonIdentifierLength; std::u16string buttonIdentifier; uint32_t identifierLength; std::u16string identifier; - inStream->Read(buttonIdentifierLength); + inStream.Read(buttonIdentifierLength); for (size_t i = 0; i < buttonIdentifierLength; i++) { char16_t character; - inStream->Read(character); + inStream.Read(character); buttonIdentifier.push_back(character); } - inStream->Read(iButton); + inStream.Read(iButton); - inStream->Read(identifierLength); + inStream.Read(identifierLength); for (size_t i = 0; i < identifierLength; i++) { char16_t character; - inStream->Read(character); + inStream.Read(character); identifier.push_back(character); } @@ -3970,10 +3991,10 @@ void GameMessages::SendSetMountInventoryID(Entity* entity, const LWOOBJID& objec } -void GameMessages::HandleDismountComplete(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleDismountComplete(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { // Get the objectID from the bitstream LWOOBJID objectId{}; - inStream->Read(objectId); + inStream.Read(objectId); // If we aren't possessing somethings, the don't do anything if (objectId != LWOOBJID_EMPTY) { @@ -4012,17 +4033,17 @@ void GameMessages::HandleDismountComplete(RakNet::BitStream* inStream, Entity* e } -void GameMessages::HandleAcknowledgePossession(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleAcknowledgePossession(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { Game::entityManager->SerializeEntity(entity); LWOOBJID objectId{}; - inStream->Read(objectId); + inStream.Read(objectId); auto* mount = Game::entityManager->GetEntity(objectId); if (mount) Game::entityManager->SerializeEntity(mount); } //Racing -void GameMessages::HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleModuleAssemblyQueryData(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { auto* moduleAssemblyComponent = entity->GetComponent(); LOG("Got Query from %i", entity->GetLOT()); @@ -4035,23 +4056,23 @@ void GameMessages::HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, En } -void GameMessages::HandleModularAssemblyNIFCompleted(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleModularAssemblyNIFCompleted(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID objectID; - inStream->Read(objectID); + inStream.Read(objectID); } -void GameMessages::HandleVehicleSetWheelLockState(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - bool bExtraFriction = inStream->ReadBit(); - bool bLocked = inStream->ReadBit(); +void GameMessages::HandleVehicleSetWheelLockState(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { + bool bExtraFriction = inStream.ReadBit(); + bool bLocked = inStream.ReadBit(); } -void GameMessages::HandleRacingClientReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleRacingClientReady(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID playerID; - inStream->Read(playerID); + inStream.Read(playerID); auto* player = Game::entityManager->GetEntity(playerID); @@ -4069,7 +4090,7 @@ void GameMessages::HandleRacingClientReady(RakNet::BitStream* inStream, Entity* } -void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleRequestDie(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { bool bClientDeath; bool bSpawnLoot; std::u16string deathType; @@ -4080,31 +4101,31 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, LWOOBJID killerID; LWOOBJID lootOwnerID = LWOOBJID_EMPTY; - bClientDeath = inStream->ReadBit(); - bSpawnLoot = inStream->ReadBit(); + bClientDeath = inStream.ReadBit(); + bSpawnLoot = inStream.ReadBit(); uint32_t deathTypeLength = 0; - inStream->Read(deathTypeLength); + inStream.Read(deathTypeLength); for (size_t i = 0; i < deathTypeLength; i++) { char16_t character; - inStream->Read(character); + inStream.Read(character); deathType.push_back(character); } - inStream->Read(directionRelativeAngleXZ); - inStream->Read(directionRelativeAngleY); - inStream->Read(directionRelativeForce); + inStream.Read(directionRelativeAngleXZ); + inStream.Read(directionRelativeAngleY); + inStream.Read(directionRelativeForce); - if (inStream->ReadBit()) { - inStream->Read(killType); + if (inStream.ReadBit()) { + inStream.Read(killType); } - inStream->Read(killerID); + inStream.Read(killerID); - if (inStream->ReadBit()) { - inStream->Read(lootOwnerID); + if (inStream.ReadBit()) { + inStream.Read(lootOwnerID); } auto* zoneController = Game::zoneManager->GetZoneControlObject(); @@ -4135,20 +4156,20 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, } -void GameMessages::HandleVehicleNotifyServerAddPassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleVehicleNotifyServerAddPassiveBoostAction(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { //SendVehicleAddPassiveBoostAction(entity->GetObjectID(), sysAddr); } -void GameMessages::HandleVehicleNotifyServerRemovePassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleVehicleNotifyServerRemovePassiveBoostAction(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { //SendVehicleRemovePassiveBoostAction(entity->GetObjectID(), sysAddr); } -void GameMessages::HandleRacingPlayerInfoResetFinished(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleRacingPlayerInfoResetFinished(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID playerID; - inStream->Read(playerID); + inStream.Read(playerID); auto* player = Game::entityManager->GetEntity(playerID); @@ -4179,10 +4200,10 @@ void GameMessages::SendUpdateReputation(const LWOOBJID objectId, const int64_t r SEND_PACKET; } -void GameMessages::HandleUpdatePropertyPerformanceCost(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleUpdatePropertyPerformanceCost(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { float performanceCost = 0.0f; - if (inStream->ReadBit()) inStream->Read(performanceCost); + if (inStream.ReadBit()) inStream.Read(performanceCost); if (performanceCost == 0.0f) return; @@ -4195,16 +4216,16 @@ void GameMessages::HandleUpdatePropertyPerformanceCost(RakNet::BitStream* inStre Database::Get()->UpdatePerformanceCost(zone->GetZoneID(), performanceCost); } -void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleVehicleNotifyHitImaginationServer(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID pickupObjID = LWOOBJID_EMPTY; LWOOBJID pickupSpawnerID = LWOOBJID_EMPTY; int32_t pickupSpawnerIndex = -1; - NiPoint3 vehiclePosition = NiPoint3::ZERO; + NiPoint3 vehiclePosition = NiPoint3Constant::ZERO; - if (inStream->ReadBit()) inStream->Read(pickupObjID); - if (inStream->ReadBit()) inStream->Read(pickupSpawnerID); - if (inStream->ReadBit()) inStream->Read(pickupSpawnerIndex); - if (inStream->ReadBit()) inStream->Read(vehiclePosition); + if (inStream.ReadBit()) inStream.Read(pickupObjID); + if (inStream.ReadBit()) inStream.Read(pickupSpawnerID); + if (inStream.ReadBit()) inStream.Read(pickupSpawnerIndex); + if (inStream.ReadBit()) inStream.Read(vehiclePosition); auto* pickup = Game::entityManager->GetEntity(pickupObjID); @@ -4526,7 +4547,7 @@ void GameMessages::SendAddBuff(LWOOBJID& objectID, const LWOOBJID& casterID, uin // NT -void GameMessages::HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { bool bAllowPartial{}; int32_t destSlot = -1; int32_t iStackCount = 1; @@ -4537,15 +4558,15 @@ void GameMessages::HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* LWOOBJID subkey = LWOOBJID_EMPTY; LOT itemLOT = 0; - bAllowPartial = inStream->ReadBit(); - if (inStream->ReadBit()) inStream->Read(destSlot); - if (inStream->ReadBit()) inStream->Read(iStackCount); - if (inStream->ReadBit()) inStream->Read(invTypeDst); - if (inStream->ReadBit()) inStream->Read(invTypeSrc); - if (inStream->ReadBit()) inStream->Read(itemID); - showFlyingLoot = inStream->ReadBit(); - if (inStream->ReadBit()) inStream->Read(subkey); - if (inStream->ReadBit()) inStream->Read(itemLOT); + bAllowPartial = inStream.ReadBit(); + if (inStream.ReadBit()) inStream.Read(destSlot); + if (inStream.ReadBit()) inStream.Read(iStackCount); + if (inStream.ReadBit()) inStream.Read(invTypeDst); + if (inStream.ReadBit()) inStream.Read(invTypeSrc); + if (inStream.ReadBit()) inStream.Read(itemID); + showFlyingLoot = inStream.ReadBit(); + if (inStream.ReadBit()) inStream.Read(subkey); + if (inStream.ReadBit()) inStream.Read(itemLOT); if (invTypeDst == invTypeSrc) { return; @@ -4598,10 +4619,10 @@ void GameMessages::SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditi //------------------------------------------------------------------- Handlers ------------------------------------------------------------------ //----------------------------------------------------------------------------------------------------------------------------------------------- -void GameMessages::HandleToggleGhostReferenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleToggleGhostReferenceOverride(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { bool bOverride = false; - inStream->Read(bOverride); + inStream.Read(bOverride); auto* player = PlayerManager::GetPlayer(sysAddr); @@ -4614,10 +4635,10 @@ void GameMessages::HandleToggleGhostReferenceOverride(RakNet::BitStream* inStrea } -void GameMessages::HandleSetGhostReferencePosition(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleSetGhostReferencePosition(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { NiPoint3 position; - inStream->Read(position); + inStream.Read(position); auto* player = PlayerManager::GetPlayer(sysAddr); @@ -4630,119 +4651,52 @@ void GameMessages::HandleSetGhostReferencePosition(RakNet::BitStream* inStream, } -void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleBuyFromVendor(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { bool bConfirmed{}; // This doesn't appear to do anything. Further research is needed. bool countIsDefault{}; int count = 1; LOT item; - inStream->Read(bConfirmed); - inStream->Read(countIsDefault); - if (countIsDefault) inStream->Read(count); - inStream->Read(item); + inStream.Read(bConfirmed); + inStream.Read(countIsDefault); + if (countIsDefault) inStream.Read(count); + inStream.Read(item); User* user = UserManager::Instance()->GetUser(sysAddr); if (!user) return; Entity* player = Game::entityManager->GetEntity(user->GetLoggedInChar()); if (!player) return; + + // handle buying normal items + auto* vendorComponent = entity->GetComponent(); + if (vendorComponent) { + vendorComponent->Buy(player, item, count); + return; + } - auto* propertyVendorComponent = static_cast(entity->GetComponent(eReplicaComponentType::PROPERTY_VENDOR)); + // handle buying achievement items + auto* achievementVendorComponent = entity->GetComponent(); + if (achievementVendorComponent) { + achievementVendorComponent->Buy(player, item, count); + return; + } - if (propertyVendorComponent != nullptr) { + // Handle buying properties + auto* propertyVendorComponent = entity->GetComponent(); + if (propertyVendorComponent) { propertyVendorComponent->OnBuyFromVendor(player, bConfirmed, item, count); - return; } - - const auto isCommendationVendor = entity->GetLOT() == 13806; - - auto* vend = entity->GetComponent(); - if (!vend && !isCommendationVendor) return; - - auto* inv = player->GetComponent(); - if (!inv) return; - - if (!isCommendationVendor && !vend->SellsItem(item)) { - LOG("User %llu %s tried to buy an item %i from a vendor when they do not sell said item", player->GetObjectID(), user->GetUsername().c_str(), item); - return; - } - - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); - - int itemCompID = compRegistryTable->GetByIDAndType(item, eReplicaComponentType::ITEM); - CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); - - Character* character = player->GetCharacter(); - if (!character) return; - - // Extra currency that needs to be deducted in case of crafting - auto craftingCurrencies = CDItemComponentTable::ParseCraftingCurrencies(itemComp); - for (const auto& craftingCurrency : craftingCurrencies) { - inv->RemoveItem(craftingCurrency.first, craftingCurrency.second * count); - } - - if (isCommendationVendor) { - if (itemComp.commendationLOT != 13763) { - return; - } - - auto* missionComponent = player->GetComponent(); - - if (missionComponent == nullptr) { - return; - } - - LOT tokenId = -1; - - if (missionComponent->GetMissionState(545) == eMissionState::COMPLETE) tokenId = 8318; // "Assembly Token" - if (missionComponent->GetMissionState(556) == eMissionState::COMPLETE) tokenId = 8321; // "Venture League Token" - if (missionComponent->GetMissionState(567) == eMissionState::COMPLETE) tokenId = 8319; // "Sentinels Token" - if (missionComponent->GetMissionState(578) == eMissionState::COMPLETE) tokenId = 8320; // "Paradox Token" - - const uint32_t altCurrencyCost = itemComp.commendationCost * count; - - if (inv->GetLotCount(tokenId) < altCurrencyCost) { - return; - } - - inv->RemoveItem(tokenId, altCurrencyCost); - - inv->AddItem(item, count, eLootSourceType::VENDOR); - } else { - float buyScalar = vend->GetBuyScalar(); - - const auto coinCost = static_cast(std::floor((itemComp.baseValue * buyScalar) * count)); - - if (character->GetCoins() < coinCost) { - return; - } - - if (Inventory::IsValidItem(itemComp.currencyLOT)) { - const uint32_t altCurrencyCost = std::floor(itemComp.altCurrencyCost * buyScalar) * count; - - if (inv->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) { - return; - } - - inv->RemoveItem(itemComp.currencyLOT, altCurrencyCost); - } - - character->SetCoins(character->GetCoins() - (coinCost), eLootSourceType::VENDOR); - inv->AddItem(item, count, eLootSourceType::VENDOR); - } - - GameMessages::SendVendorTransactionResult(entity, sysAddr); } -void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleSellToVendor(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { bool countIsDefault{}; int count = 1; LWOOBJID iObjID; - inStream->Read(countIsDefault); - if (countIsDefault) inStream->Read(count); - inStream->Read(iObjID); + inStream.Read(countIsDefault); + if (countIsDefault) inStream.Read(count); + inStream.Read(iObjID); User* user = UserManager::Instance()->GetUser(sysAddr); if (!user) return; @@ -4759,14 +4713,17 @@ void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entit Item* item = inv->FindItemById(iObjID); if (!item) return; - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); // Items with a base value of 0 or max int are special items that should not be sold if they're not sub items - if (itemComp.baseValue == 0 || itemComp.baseValue == UINT_MAX) return; + if (itemComp.baseValue == 0 || itemComp.baseValue == UINT_MAX) { + GameMessages::SendVendorTransactionResult(entity, sysAddr, eVendorTransactionResult::SELL_FAIL); + return; + } float sellScalar = vend->GetSellScalar(); if (Inventory::IsValidItem(itemComp.currencyLOT)) { @@ -4774,23 +4731,21 @@ void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entit inv->AddItem(itemComp.currencyLOT, std::floor(altCurrency), eLootSourceType::VENDOR); // Return alt currencies like faction tokens. } - //inv->RemoveItem(count, -1, iObjID); inv->MoveItemToInventory(item, eInventoryType::VENDOR_BUYBACK, count, true, false, true); character->SetCoins(std::floor(character->GetCoins() + (static_cast(itemComp.baseValue * sellScalar) * count)), eLootSourceType::VENDOR); - //Game::entityManager->SerializeEntity(player); // so inventory updates - GameMessages::SendVendorTransactionResult(entity, sysAddr); + GameMessages::SendVendorTransactionResult(entity, sysAddr, eVendorTransactionResult::SELL_SUCCESS); } -void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleBuybackFromVendor(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { bool confirmed = false; bool countIsDefault{}; int count = 1; LWOOBJID iObjID; - inStream->Read(confirmed); - inStream->Read(countIsDefault); - if (countIsDefault) inStream->Read(count); - inStream->Read(iObjID); + inStream.Read(confirmed); + inStream.Read(countIsDefault); + if (countIsDefault) inStream.Read(count); + inStream.Read(iObjID); //if (!confirmed) return; they always built in this confirmed garbage... but never used it? @@ -4809,8 +4764,8 @@ void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* Item* item = inv->FindItemById(iObjID); if (!item) return; - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); @@ -4820,16 +4775,16 @@ void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* const auto cost = static_cast(std::floor(((itemComp.baseValue * sellScalar) * count))); if (character->GetCoins() < cost) { + GameMessages::SendVendorTransactionResult(entity, sysAddr, eVendorTransactionResult::PURCHASE_FAIL); return; } if (Inventory::IsValidItem(itemComp.currencyLOT)) { const uint32_t altCurrencyCost = std::floor(itemComp.altCurrencyCost * sellScalar) * count; - if (inv->GetLotCount(itemComp.currencyLOT) < altCurrencyCost) { + GameMessages::SendVendorTransactionResult(entity, sysAddr, eVendorTransactionResult::PURCHASE_FAIL); return; } - inv->RemoveItem(itemComp.currencyLOT, altCurrencyCost); } @@ -4837,19 +4792,19 @@ void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* inv->MoveItemToInventory(item, Inventory::FindInventoryTypeForLot(item->GetLot()), count, true, false); character->SetCoins(character->GetCoins() - cost, eLootSourceType::VENDOR); //Game::entityManager->SerializeEntity(player); // so inventory updates - GameMessages::SendVendorTransactionResult(entity, sysAddr); + GameMessages::SendVendorTransactionResult(entity, sysAddr, eVendorTransactionResult::PURCHASE_SUCCESS); } -void GameMessages::HandleParseChatMessage(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleParseChatMessage(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { std::u16string wsString; int iClientState; - inStream->Read(iClientState); + inStream.Read(iClientState); uint32_t wsStringLength; - inStream->Read(wsStringLength); + inStream.Read(wsStringLength); for (uint32_t i = 0; i < wsStringLength; ++i) { uint16_t character; - inStream->Read(character); + inStream.Read(character); wsString.push_back(character); } @@ -4858,7 +4813,7 @@ void GameMessages::HandleParseChatMessage(RakNet::BitStream* inStream, Entity* e } } -void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleFireEventServerSide(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { uint32_t argsLength{}; std::u16string args{}; bool param1IsDefault{}; @@ -4869,19 +4824,19 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity int param3 = -1; LWOOBJID senderID{}; - inStream->Read(argsLength); + inStream.Read(argsLength); for (uint32_t i = 0; i < argsLength; ++i) { uint16_t character; - inStream->Read(character); + inStream.Read(character); args.push_back(character); } - inStream->Read(param1IsDefault); - if (param1IsDefault) inStream->Read(param1); - inStream->Read(param2IsDefault); - if (param2IsDefault) inStream->Read(param2); - inStream->Read(param3IsDefault); - if (param3IsDefault) inStream->Read(param3); - inStream->Read(senderID); + inStream.Read(param1IsDefault); + if (param1IsDefault) inStream.Read(param1); + inStream.Read(param2IsDefault); + if (param2IsDefault) inStream.Read(param2); + inStream.Read(param3IsDefault); + if (param3IsDefault) inStream.Read(param3); + inStream.Read(senderID); auto* sender = Game::entityManager->GetEntity(senderID); auto* player = PlayerManager::GetPlayer(sysAddr); @@ -4942,17 +4897,17 @@ void GameMessages::HandleFireEventServerSide(RakNet::BitStream* inStream, Entity entity->OnFireEventServerSide(sender, GeneralUtils::UTF16ToWTF8(args), param1, param2, param3); } -void GameMessages::HandleRequestPlatformResync(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleRequestPlatformResync(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { if (entity->GetLOT() == 6267 || entity->GetLOT() == 16141) return; GameMessages::SendPlatformResync(entity, sysAddr); } -void GameMessages::HandleQuickBuildCancel(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleQuickBuildCancel(RakNet::BitStream& inStream, Entity* entity) { bool bEarlyRelease; LWOOBJID userID; - inStream->Read(bEarlyRelease); - inStream->Read(userID); + inStream.Read(bEarlyRelease); + inStream.Read(userID); auto* quickBuildComponent = static_cast(entity->GetComponent(eReplicaComponentType::QUICK_BUILD));; if (!quickBuildComponent) return; @@ -4960,18 +4915,18 @@ void GameMessages::HandleQuickBuildCancel(RakNet::BitStream* inStream, Entity* e quickBuildComponent->CancelQuickBuild(Game::entityManager->GetEntity(userID), eQuickBuildFailReason::CANCELED_EARLY); } -void GameMessages::HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleRequestUse(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { bool bIsMultiInteractUse = false; unsigned int multiInteractID; int multiInteractType; bool secondary; LWOOBJID objectID; - inStream->Read(bIsMultiInteractUse); - inStream->Read(multiInteractID); - inStream->Read(multiInteractType); - inStream->Read(objectID); - inStream->Read(secondary); + inStream.Read(bIsMultiInteractUse); + inStream.Read(multiInteractID); + inStream.Read(multiInteractType); + inStream.Read(objectID); + inStream.Read(secondary); Entity* interactedObject = Game::entityManager->GetEntity(objectID); @@ -5008,12 +4963,12 @@ void GameMessages::HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, missionComponent->Progress(eMissionTaskType::INTERACT, interactedObject->GetLOT(), interactedObject->GetObjectID()); } -void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandlePlayEmote(RakNet::BitStream& inStream, Entity* entity) { int emoteID; LWOOBJID targetID; - inStream->Read(emoteID); - inStream->Read(targetID); + inStream.Read(emoteID); + inStream.Read(targetID); LOG_DEBUG("Emote (%i) (%llu)", emoteID, targetID); @@ -5022,7 +4977,7 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) if (emoteID == 0) return; std::string sAnimationName = "deaded"; //Default name in case we fail to get the emote - CDEmoteTableTable* emotes = CDClientManager::Instance().GetTable(); + CDEmoteTableTable* emotes = CDClientManager::GetTable(); if (emotes) { CDEmoteTable* emote = emotes->GetEmote(emoteID); if (emote) sAnimationName = emote->animationName; @@ -5057,10 +5012,10 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) } } -void GameMessages::HandleModularBuildConvertModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleModularBuildConvertModel(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { LWOOBJID modelID; - inStream->Read(modelID); + inStream.Read(modelID); User* user = UserManager::Instance()->GetUser(sysAddr); if (!user) return; @@ -5084,34 +5039,29 @@ void GameMessages::HandleModularBuildConvertModel(RakNet::BitStream* inStream, E item->SetCount(item->GetCount() - 1, false, false, true, eLootSourceType::QUICKBUILD); } -void GameMessages::HandleSetFlag(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleSetFlag(RakNet::BitStream& inStream, Entity* entity) { bool bFlag{}; int32_t iFlagID{}; - inStream->Read(bFlag); - inStream->Read(iFlagID); + inStream.Read(bFlag); + inStream.Read(iFlagID); - auto user = entity->GetParentUser(); - if (user) { - auto character = user->GetLastUsedChar(); - if (!character) return; - - character->SetPlayerFlag(iFlagID, bFlag); - } + auto character = entity->GetCharacter(); + if (character) character->SetPlayerFlag(iFlagID, bFlag); } -void GameMessages::HandleRespondToMission(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleRespondToMission(RakNet::BitStream& inStream, Entity* entity) { int missionID{}; LWOOBJID playerID{}; LWOOBJID receiverID{}; bool isDefaultReward{}; LOT reward = LOT_NULL; - inStream->Read(missionID); - inStream->Read(playerID); - inStream->Read(receiverID); - inStream->Read(isDefaultReward); - if (isDefaultReward) inStream->Read(reward); + inStream.Read(missionID); + inStream.Read(playerID); + inStream.Read(receiverID); + inStream.Read(isDefaultReward); + if (isDefaultReward) inStream.Read(reward); MissionComponent* missionComponent = static_cast(entity->GetComponent(eReplicaComponentType::MISSION)); if (!missionComponent) { @@ -5133,27 +5083,23 @@ void GameMessages::HandleRespondToMission(RakNet::BitStream* inStream, Entity* e return; } - for (CppScripts::Script* script : CppScripts::GetEntityScripts(offerer)) { - script->OnRespondToMission(offerer, missionID, Game::entityManager->GetEntity(playerID), reward); - } + offerer->GetScript()->OnRespondToMission(offerer, missionID, Game::entityManager->GetEntity(playerID), reward); } -void GameMessages::HandleMissionDialogOK(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleMissionDialogOK(RakNet::BitStream& inStream, Entity* entity) { bool bIsComplete{}; eMissionState iMissionState{}; int missionID{}; LWOOBJID responder{}; Entity* player = nullptr; - inStream->Read(bIsComplete); - inStream->Read(iMissionState); - inStream->Read(missionID); - inStream->Read(responder); + inStream.Read(bIsComplete); + inStream.Read(iMissionState); + inStream.Read(missionID); + inStream.Read(responder); player = Game::entityManager->GetEntity(responder); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(entity)) { - script->OnMissionDialogueOK(entity, player, missionID, iMissionState); - } + if (entity) entity->GetScript()->OnMissionDialogueOK(entity, player, missionID, iMissionState); // Get the player's mission component MissionComponent* missionComponent = static_cast(player->GetComponent(eReplicaComponentType::MISSION)); @@ -5177,14 +5123,14 @@ void GameMessages::HandleMissionDialogOK(RakNet::BitStream* inStream, Entity* en }); } -void GameMessages::HandleRequestLinkedMission(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleRequestLinkedMission(RakNet::BitStream& inStream, Entity* entity) { LWOOBJID playerId{}; int missionId{}; bool bMissionOffered{}; - inStream->Read(playerId); - inStream->Read(missionId); - inStream->Read(bMissionOffered); + inStream.Read(playerId); + inStream.Read(missionId); + inStream.Read(bMissionOffered); auto* player = Game::entityManager->GetEntity(playerId); @@ -5195,9 +5141,9 @@ void GameMessages::HandleRequestLinkedMission(RakNet::BitStream* inStream, Entit } } -void GameMessages::HandleHasBeenCollected(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleHasBeenCollected(RakNet::BitStream& inStream, Entity* entity) { LWOOBJID playerID; - inStream->Read(playerID); + inStream.Read(playerID); Entity* player = Game::entityManager->GetEntity(playerID); if (!player || !entity || entity->GetCollectibleID() == 0) return; @@ -5208,7 +5154,7 @@ void GameMessages::HandleHasBeenCollected(RakNet::BitStream* inStream, Entity* e } } -void GameMessages::HandleNotifyServerLevelProcessingComplete(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleNotifyServerLevelProcessingComplete(RakNet::BitStream& inStream, Entity* entity) { auto* levelComp = entity->GetComponent(); if (!levelComp) return; auto* character = entity->GetComponent(); @@ -5247,9 +5193,9 @@ void GameMessages::HandleNotifyServerLevelProcessingComplete(RakNet::BitStream* GameMessages::SendBroadcastTextToChatbox(entity, UNASSIGNED_SYSTEM_ADDRESS, attrs, wsText); } -void GameMessages::HandlePickupCurrency(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandlePickupCurrency(RakNet::BitStream& inStream, Entity* entity) { unsigned int currency; - inStream->Read(currency); + inStream.Read(currency); if (currency == 0) return; @@ -5259,7 +5205,7 @@ void GameMessages::HandlePickupCurrency(RakNet::BitStream* inStream, Entity* ent } } -void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleRequestDie(RakNet::BitStream& inStream, Entity* entity) { LWOOBJID killerID; LWOOBJID lootOwnerID; bool bDieAccepted = false; @@ -5272,38 +5218,38 @@ void GameMessages::HandleRequestDie(RakNet::BitStream* inStream, Entity* entity) bool bSpawnLoot = true; float coinSpawnTime = -1.0f; - inStream->Read(bClientDeath); - inStream->Read(bDieAccepted); - inStream->Read(bSpawnLoot); + inStream.Read(bClientDeath); + inStream.Read(bDieAccepted); + inStream.Read(bSpawnLoot); bool coinSpawnTimeIsDefault{}; - inStream->Read(coinSpawnTimeIsDefault); - if (coinSpawnTimeIsDefault != 0) inStream->Read(coinSpawnTime); + inStream.Read(coinSpawnTimeIsDefault); + if (coinSpawnTimeIsDefault != 0) inStream.Read(coinSpawnTime); /*uint32_t deathTypeLength = deathType.size(); - inStream->Read(deathTypeLength); + inStream.Read(deathTypeLength); for (uint32_t k = 0; k < deathTypeLength; k++) { - inStream->Read(deathType[k]); + inStream.Read(deathType[k]); }*/ - inStream->Read(directionRelative_AngleXZ); - inStream->Read(directionRelative_AngleY); - inStream->Read(directionRelative_Force); + inStream.Read(directionRelative_AngleXZ); + inStream.Read(directionRelative_AngleY); + inStream.Read(directionRelative_Force); bool killTypeIsDefault{}; - inStream->Read(killTypeIsDefault); - if (killTypeIsDefault != 0) inStream->Read(killType); + inStream.Read(killTypeIsDefault); + if (killTypeIsDefault != 0) inStream.Read(killType); - inStream->Read(lootOwnerID); - inStream->Read(killerID); + inStream.Read(lootOwnerID); + inStream.Read(killerID); } -void GameMessages::HandleEquipItem(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleEquipItem(RakNet::BitStream& inStream, Entity* entity) { bool immediate; LWOOBJID objectID; - inStream->Read(immediate); - inStream->Read(immediate); //twice? - inStream->Read(objectID); + inStream.Read(immediate); + inStream.Read(immediate); //twice? + inStream.Read(objectID); InventoryComponent* inv = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; @@ -5316,13 +5262,13 @@ void GameMessages::HandleEquipItem(RakNet::BitStream* inStream, Entity* entity) Game::entityManager->SerializeEntity(entity); } -void GameMessages::HandleUnequipItem(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleUnequipItem(RakNet::BitStream& inStream, Entity* entity) { bool immediate; LWOOBJID objectID; - inStream->Read(immediate); - inStream->Read(immediate); - inStream->Read(immediate); - inStream->Read(objectID); + inStream.Read(immediate); + inStream.Read(immediate); + inStream.Read(immediate); + inStream.Read(objectID); InventoryComponent* inv = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; @@ -5336,7 +5282,7 @@ void GameMessages::HandleUnequipItem(RakNet::BitStream* inStream, Entity* entity Game::entityManager->SerializeEntity(entity); } -void GameMessages::HandleRemoveItemFromInventory(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleRemoveItemFromInventory(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { // this is used for a lot more than just inventory trashing (trades, vendors, etc.) but for now since it's just used for that, that's all im going to implement bool bConfirmed = false; bool bDeleteItem = true; @@ -5364,40 +5310,40 @@ void GameMessages::HandleRemoveItemFromInventory(RakNet::BitStream* inStream, En bool iTradeIDIsDefault = false; LWOOBJID iTradeID = LWOOBJID_EMPTY; - inStream->Read(bConfirmed); - inStream->Read(bDeleteItem); - inStream->Read(bOutSuccess); - inStream->Read(eInvTypeIsDefault); - if (eInvTypeIsDefault) inStream->Read(eInvType); - inStream->Read(eLootTypeSourceIsDefault); - if (eLootTypeSourceIsDefault) inStream->Read(eLootTypeSource); - inStream->Read(extraInfo.length); + inStream.Read(bConfirmed); + inStream.Read(bDeleteItem); + inStream.Read(bOutSuccess); + inStream.Read(eInvTypeIsDefault); + if (eInvTypeIsDefault) inStream.Read(eInvType); + inStream.Read(eLootTypeSourceIsDefault); + if (eLootTypeSourceIsDefault) inStream.Read(eLootTypeSource); + inStream.Read(extraInfo.length); if (extraInfo.length > 0) { for (uint32_t i = 0; i < extraInfo.length; ++i) { uint16_t character; - inStream->Read(character); + inStream.Read(character); extraInfo.name.push_back(character); } uint16_t nullTerm; - inStream->Read(nullTerm); + inStream.Read(nullTerm); } - inStream->Read(forceDeletion); - inStream->Read(iLootTypeSourceIsDefault); - if (iLootTypeSourceIsDefault) inStream->Read(iLootTypeSource); - inStream->Read(iObjIDIsDefault); - if (iObjIDIsDefault) inStream->Read(iObjID); - inStream->Read(iObjTemplateIsDefault); - if (iObjTemplateIsDefault) inStream->Read(iObjTemplate); - inStream->Read(iRequestingObjIDIsDefault); - if (iRequestingObjIDIsDefault) inStream->Read(iRequestingObjID); - inStream->Read(iStackCountIsDefault); - if (iStackCountIsDefault) inStream->Read(iStackCount); - inStream->Read(iStackRemainingIsDefault); - if (iStackRemainingIsDefault) inStream->Read(iStackRemaining); - inStream->Read(iSubkeyIsDefault); - if (iSubkeyIsDefault) inStream->Read(iSubkey); - inStream->Read(iTradeIDIsDefault); - if (iTradeIDIsDefault) inStream->Read(iTradeID); + inStream.Read(forceDeletion); + inStream.Read(iLootTypeSourceIsDefault); + if (iLootTypeSourceIsDefault) inStream.Read(iLootTypeSource); + inStream.Read(iObjIDIsDefault); + if (iObjIDIsDefault) inStream.Read(iObjID); + inStream.Read(iObjTemplateIsDefault); + if (iObjTemplateIsDefault) inStream.Read(iObjTemplate); + inStream.Read(iRequestingObjIDIsDefault); + if (iRequestingObjIDIsDefault) inStream.Read(iRequestingObjID); + inStream.Read(iStackCountIsDefault); + if (iStackCountIsDefault) inStream.Read(iStackCount); + inStream.Read(iStackRemainingIsDefault); + if (iStackRemainingIsDefault) inStream.Read(iStackRemaining); + inStream.Read(iSubkeyIsDefault); + if (iSubkeyIsDefault) inStream.Read(iSubkey); + inStream.Read(iTradeIDIsDefault); + if (iTradeIDIsDefault) inStream.Read(iTradeID); InventoryComponent* inv = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; @@ -5438,19 +5384,19 @@ void GameMessages::SendSetGravityScale(const LWOOBJID& target, const float effec SEND_PACKET; } -void GameMessages::HandleMoveItemInInventory(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleMoveItemInInventory(RakNet::BitStream& inStream, Entity* entity) { bool destInvTypeIsDefault = false; int32_t destInvType = eInventoryType::INVALID; LWOOBJID iObjID; int inventoryType; int responseCode; int slot; - inStream->Read(destInvTypeIsDefault); - if (destInvTypeIsDefault) { inStream->Read(destInvType); } - inStream->Read(iObjID); - inStream->Read(inventoryType); - inStream->Read(responseCode); - inStream->Read(slot); + inStream.Read(destInvTypeIsDefault); + if (destInvTypeIsDefault) { inStream.Read(destInvType); } + inStream.Read(iObjID); + inStream.Read(inventoryType); + inStream.Read(responseCode); + inStream.Read(slot); InventoryComponent* inv = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; @@ -5465,7 +5411,7 @@ void GameMessages::HandleMoveItemInInventory(RakNet::BitStream* inStream, Entity Game::entityManager->SerializeEntity(entity); } -void GameMessages::HandleMoveItemBetweenInventoryTypes(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleMoveItemBetweenInventoryTypes(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { eInventoryType inventoryTypeA; eInventoryType inventoryTypeB; LWOOBJID objectID; @@ -5475,14 +5421,14 @@ void GameMessages::HandleMoveItemBetweenInventoryTypes(RakNet::BitStream* inStre bool templateIDIsDefault = false; LOT templateID = LOT_NULL; - inStream->Read(inventoryTypeA); - inStream->Read(inventoryTypeB); - inStream->Read(objectID); - inStream->Read(showFlyingLoot); - inStream->Read(stackCountIsDefault); - if (stackCountIsDefault) inStream->Read(stackCount); - inStream->Read(templateIDIsDefault); - if (templateIDIsDefault) inStream->Read(templateID); + inStream.Read(inventoryTypeA); + inStream.Read(inventoryTypeB); + inStream.Read(objectID); + inStream.Read(showFlyingLoot); + inStream.Read(stackCountIsDefault); + if (stackCountIsDefault) inStream.Read(stackCount); + inStream.Read(templateIDIsDefault); + if (templateIDIsDefault) inStream.Read(templateID); auto inv = entity->GetComponent(); if (!inv) return; @@ -5511,10 +5457,10 @@ void GameMessages::HandleMoveItemBetweenInventoryTypes(RakNet::BitStream* inStre Game::entityManager->SerializeEntity(entity); } -void GameMessages::HandleBuildModeSet(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleBuildModeSet(RakNet::BitStream& inStream, Entity* entity) { bool bStart = false; - inStream->Read(bStart); + inStream.Read(bStart); // there's more here but we don't need it (for now?) LOG("Set build mode to (%d) for (%llu)", bStart, entity->GetObjectID()); @@ -5524,7 +5470,7 @@ void GameMessages::HandleBuildModeSet(RakNet::BitStream* inStream, Entity* entit } } -void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleModularBuildFinish(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { User* user = UserManager::Instance()->GetUser(sysAddr); if (!user) return; Entity* character = Game::entityManager->GetEntity(user->GetLoggedInChar()); @@ -5535,7 +5481,7 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* uint8_t count; // 3 for rockets, 7 for cars - inStream->Read(count); + inStream.Read(count); auto* temp = inv->GetInventory(TEMP_MODELS); std::vector modList; @@ -5546,7 +5492,7 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* for (uint32_t k = 0; k < count; k++) { uint32_t mod; - inStream->Read(mod); + inStream.Read(mod); modList.push_back(mod); auto modToStr = GeneralUtils::to_u16string(mod); modules += u"1:" + (modToStr); @@ -5606,9 +5552,7 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* ScriptComponent* script = static_cast(entity->GetComponent(eReplicaComponentType::SCRIPT)); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(entity)) { - script->OnModularBuildExit(entity, character, count >= 3, modList); - } + entity->GetScript()->OnModularBuildExit(entity, character, count >= 3, modList); // Move remaining temp models back to models std::vector items; @@ -5624,7 +5568,7 @@ void GameMessages::HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* } } -void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { User* user = UserManager::Instance()->GetUser(sysAddr); if (!user) return; Entity* character = Game::entityManager->GetEntity(user->GetLoggedInChar()); @@ -5659,18 +5603,18 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti LOT oldItemLOT = 0; int oldItemTYPE = 0; - inStream->Read(newSourceBAG); - inStream->Read(newSourceID); - inStream->Read(newSourceLOT); - inStream->Read(newSourceTYPE); - inStream->Read(newTargetID); - inStream->Read(newTargetLOT); - inStream->Read(newTargetTYPE); - inStream->Read(newTargetPOS); - inStream->Read(oldItemBAG); - inStream->Read(oldItemID); - inStream->Read(oldItemLOT); - inStream->Read(oldItemTYPE); + inStream.Read(newSourceBAG); + inStream.Read(newSourceID); + inStream.Read(newSourceLOT); + inStream.Read(newSourceTYPE); + inStream.Read(newTargetID); + inStream.Read(newTargetLOT); + inStream.Read(newTargetTYPE); + inStream.Read(newTargetPOS); + inStream.Read(oldItemBAG); + inStream.Read(oldItemID); + inStream.Read(oldItemLOT); + inStream.Read(oldItemTYPE); /* LOG("GameMessages", @@ -5735,7 +5679,7 @@ void GameMessages::HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Enti } } -void GameMessages::HandleModularBuildMoveAndEquip(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleModularBuildMoveAndEquip(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { User* user = UserManager::Instance()->GetUser(sysAddr); if (!user) return; Entity* character = Game::entityManager->GetEntity(user->GetLoggedInChar()); @@ -5745,7 +5689,7 @@ void GameMessages::HandleModularBuildMoveAndEquip(RakNet::BitStream* inStream, E LOT templateID; - inStream->Read(templateID); + inStream.Read(templateID); InventoryComponent* inv = static_cast(character->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; @@ -5759,11 +5703,11 @@ void GameMessages::HandleModularBuildMoveAndEquip(RakNet::BitStream* inStream, E inv->MoveItemToInventory(item, eInventoryType::MODELS, 1, false, true); } -void GameMessages::HandlePickupItem(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandlePickupItem(RakNet::BitStream& inStream, Entity* entity) { LWOOBJID lootObjectID; LWOOBJID playerID; - inStream->Read(lootObjectID); - inStream->Read(playerID); + inStream.Read(lootObjectID); + inStream.Read(playerID); entity->PickupItem(lootObjectID); @@ -5780,31 +5724,29 @@ void GameMessages::HandlePickupItem(RakNet::BitStream* inStream, Entity* entity) } } -void GameMessages::HandleResurrect(RakNet::BitStream* inStream, Entity* entity) { - bool immediate = inStream->ReadBit(); +void GameMessages::HandleResurrect(RakNet::BitStream& inStream, Entity* entity) { + bool immediate = inStream.ReadBit(); Entity* zoneControl = Game::entityManager->GetZoneControlEntity(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { - script->OnPlayerResurrected(zoneControl, entity); + if (zoneControl) { + zoneControl->GetScript()->OnPlayerResurrected(zoneControl, entity); } std::vector scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); for (Entity* scriptEntity : scriptedActs) { if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds - for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { - script->OnPlayerResurrected(scriptEntity, entity); - } + scriptEntity->GetScript()->OnPlayerResurrected(scriptEntity, entity); } } } -void GameMessages::HandlePushEquippedItemsState(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandlePushEquippedItemsState(RakNet::BitStream& inStream, Entity* entity) { InventoryComponent* inv = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; inv->PushEquippedItems(); } -void GameMessages::HandlePopEquippedItemsState(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandlePopEquippedItemsState(RakNet::BitStream& inStream, Entity* entity) { InventoryComponent* inv = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); if (!inv) return; inv->PopEquippedItems(); @@ -5812,10 +5754,10 @@ void GameMessages::HandlePopEquippedItemsState(RakNet::BitStream* inStream, Enti } -void GameMessages::HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleClientItemConsumed(RakNet::BitStream& inStream, Entity* entity) { LWOOBJID itemConsumed; - inStream->Read(itemConsumed); + inStream.Read(itemConsumed); auto* inventory = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); @@ -5838,10 +5780,10 @@ void GameMessages::HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* } -void GameMessages::HandleUseNonEquipmentItem(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleUseNonEquipmentItem(RakNet::BitStream& inStream, Entity* entity) { LWOOBJID itemConsumed; - inStream->Read(itemConsumed); + inStream.Read(itemConsumed); auto* inv = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); @@ -5852,7 +5794,7 @@ void GameMessages::HandleUseNonEquipmentItem(RakNet::BitStream* inStream, Entity if (item) item->UseNonEquip(item); } -void GameMessages::HandleMatchRequest(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleMatchRequest(RakNet::BitStream& inStream, Entity* entity) { LWOOBJID activator; //std::map additionalPlayers; uint32_t playerChoicesLen; @@ -5860,19 +5802,19 @@ void GameMessages::HandleMatchRequest(RakNet::BitStream* inStream, Entity* entit int type; int value; - inStream->Read(activator); - inStream->Read(playerChoicesLen); + inStream.Read(activator); + inStream.Read(playerChoicesLen); for (uint32_t i = 0; i < playerChoicesLen; ++i) { uint16_t character; - inStream->Read(character); + inStream.Read(character); playerChoices.push_back(character); } if (playerChoicesLen > 0) { uint16_t nullTerm; - inStream->Read(nullTerm); + inStream.Read(nullTerm); } - inStream->Read(type); - inStream->Read(value); + inStream.Read(type); + inStream.Read(value); std::vector scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); if (type == 0) { // join @@ -5898,11 +5840,11 @@ void GameMessages::HandleMatchRequest(RakNet::BitStream* inStream, Entity* entit } } -void GameMessages::HandleGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleGetHotPropertyData(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { SendGetHotPropertyData(inStream, entity, sysAddr); } -void GameMessages::SendGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::SendGetHotPropertyData(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { CBITSTREAM; CMSGHEADER; /** @@ -5943,17 +5885,17 @@ void GameMessages::SendGetHotPropertyData(RakNet::BitStream* inStream, Entity* e SEND_PACKET*/ } -void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleReportBug(RakNet::BitStream& inStream, Entity* entity) { //Definitely not stolen from autogenerated code, no sir: IBugReports::Info reportInfo; //Reading: uint32_t messageLength; - inStream->Read(messageLength); + inStream.Read(messageLength); for (uint32_t i = 0; i < (messageLength); ++i) { uint16_t character; - inStream->Read(character); + inStream.Read(character); reportInfo.body.push_back(static_cast(character)); } @@ -5961,26 +5903,26 @@ void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) if (character) reportInfo.characterId = character->GetID(); uint32_t clientVersionLength; - inStream->Read(clientVersionLength); + inStream.Read(clientVersionLength); for (unsigned int k = 0; k < clientVersionLength; k++) { unsigned char character; - inStream->Read(character); + inStream.Read(character); reportInfo.clientVersion.push_back(character); } uint32_t nOtherPlayerIDLength; - inStream->Read(nOtherPlayerIDLength); + inStream.Read(nOtherPlayerIDLength); for (unsigned int k = 0; k < nOtherPlayerIDLength; k++) { unsigned char character; - inStream->Read(character); + inStream.Read(character); reportInfo.otherPlayer.push_back(character); } uint32_t selectionLength; - inStream->Read(selectionLength); + inStream.Read(selectionLength); for (unsigned int k = 0; k < selectionLength; k++) { unsigned char character; - inStream->Read(character); + inStream.Read(character); reportInfo.selection.push_back(character); } @@ -5988,7 +5930,7 @@ void GameMessages::HandleReportBug(RakNet::BitStream* inStream, Entity* entity) } void -GameMessages::HandleClientRailMovementReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +GameMessages::HandleClientRailMovementReady(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { const auto possibleRails = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::RAIL_ACTIVATOR); for (const auto* possibleRail : possibleRails) { const auto* rail = possibleRail->GetComponent(); @@ -5998,8 +5940,8 @@ GameMessages::HandleClientRailMovementReady(RakNet::BitStream* inStream, Entity* } } -void GameMessages::HandleCancelRailMovement(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { - const auto immediate = inStream->ReadBit(); +void GameMessages::HandleCancelRailMovement(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { + const auto immediate = inStream.ReadBit(); const auto possibleRails = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::RAIL_ACTIVATOR); for (const auto* possibleRail : possibleRails) { @@ -6010,43 +5952,41 @@ void GameMessages::HandleCancelRailMovement(RakNet::BitStream* inStream, Entity* } } -void GameMessages::HandlePlayerRailArrivedNotification(RakNet::BitStream* inStream, Entity* entity, +void GameMessages::HandlePlayerRailArrivedNotification(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { uint32_t pathNameLength; - inStream->Read(pathNameLength); + inStream.Read(pathNameLength); std::u16string pathName; for (auto k = 0; k < pathNameLength; k++) { uint16_t c; - inStream->Read(c); + inStream.Read(c); pathName.push_back(c); } int32_t waypointNumber; - inStream->Read(waypointNumber); + inStream.Read(waypointNumber); const auto possibleRails = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::RAIL_ACTIVATOR); for (auto* possibleRail : possibleRails) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(possibleRail)) { - script->OnPlayerRailArrived(possibleRail, entity, pathName, waypointNumber); - } + if (possibleRail) possibleRail->GetScript()->OnPlayerRailArrived(possibleRail, entity, pathName, waypointNumber); } } -void GameMessages::HandleModifyPlayerZoneStatistic(RakNet::BitStream* inStream, Entity* entity) { - const auto set = inStream->ReadBit(); +void GameMessages::HandleModifyPlayerZoneStatistic(RakNet::BitStream& inStream, Entity* entity) { + const auto set = inStream.ReadBit(); const auto statisticsName = GeneralUtils::ReadWString(inStream); int32_t value; - if (inStream->ReadBit()) { - inStream->Read(value); + if (inStream.ReadBit()) { + inStream.Read(value); } else { value = 0; } LWOMAPID zone; - if (inStream->ReadBit()) { - inStream->Read(zone); + if (inStream.ReadBit()) { + inStream.Read(zone); } else { zone = LWOMAPID_INVALID; } @@ -6058,13 +5998,13 @@ void GameMessages::HandleModifyPlayerZoneStatistic(RakNet::BitStream* inStream, } } -void GameMessages::HandleUpdatePlayerStatistic(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleUpdatePlayerStatistic(RakNet::BitStream& inStream, Entity* entity) { int32_t updateID; - inStream->Read(updateID); + inStream.Read(updateID); int64_t updateValue; - if (inStream->ReadBit()) { - inStream->Read(updateValue); + if (inStream.ReadBit()) { + inStream.Read(updateValue); } else { updateValue = 1; } @@ -6075,14 +6015,14 @@ void GameMessages::HandleUpdatePlayerStatistic(RakNet::BitStream* inStream, Enti } } -void GameMessages::HandleDeactivateBubbleBuff(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleDeactivateBubbleBuff(RakNet::BitStream& inStream, Entity* entity) { auto controllablePhysicsComponent = entity->GetComponent(); if (controllablePhysicsComponent) controllablePhysicsComponent->DeactivateBubbleBuff(); } -void GameMessages::HandleActivateBubbleBuff(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleActivateBubbleBuff(RakNet::BitStream& inStream, Entity* entity) { bool specialAnimations; - if (!inStream->Read(specialAnimations)) return; + if (!inStream.Read(specialAnimations)) return; std::u16string type = GeneralUtils::ReadWString(inStream); auto bubbleType = eBubbleType::DEFAULT; @@ -6115,9 +6055,9 @@ void GameMessages::SendDeactivateBubbleBuffFromServer(LWOOBJID objectId, const S SEND_PACKET; } -void GameMessages::HandleZoneSummaryDismissed(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleZoneSummaryDismissed(RakNet::BitStream& inStream, Entity* entity) { LWOOBJID player_id; - inStream->Read(player_id); + inStream.Read(player_id); auto target = Game::entityManager->GetEntity(player_id); entity->TriggerEvent(eTriggerEventType::ZONE_SUMMARY_DISMISSED, target); }; @@ -6151,25 +6091,25 @@ void GameMessages::SendShowBillboardInteractIcon(const SystemAddress& sysAddr, L else SEND_PACKET } -void GameMessages::HandleRequestActivityExit(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleRequestActivityExit(RakNet::BitStream& inStream, Entity* entity) { bool canceled = false; - inStream->Read(canceled); + inStream.Read(canceled); if (!canceled) return; LWOOBJID player_id = LWOOBJID_EMPTY; - inStream->Read(player_id); + inStream.Read(player_id); auto player = Game::entityManager->GetEntity(player_id); if (!entity || !player) return; entity->RequestActivityExit(entity, player_id, canceled); } -void GameMessages::HandleAddDonationItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleAddDonationItem(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { uint32_t count = 1; bool hasCount = false; - inStream->Read(hasCount); - if (hasCount) inStream->Read(count); + inStream.Read(hasCount); + if (hasCount) inStream.Read(count); LWOOBJID itemId = LWOOBJID_EMPTY; - inStream->Read(itemId); + inStream.Read(itemId); if (!itemId) return; auto* donationVendorComponent = entity->GetComponent(); @@ -6193,15 +6133,15 @@ void GameMessages::HandleAddDonationItem(RakNet::BitStream* inStream, Entity* en inventoryComponent->MoveItemToInventory(item, eInventoryType::DONATION, count, true, false, true); } -void GameMessages::HandleRemoveDonationItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr) { +void GameMessages::HandleRemoveDonationItem(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr) { bool confirmed = false; - inStream->Read(confirmed); + inStream.Read(confirmed); uint32_t count = 1; bool hasCount = false; - inStream->Read(hasCount); - if (hasCount) inStream->Read(count); + inStream.Read(hasCount); + if (hasCount) inStream.Read(count); LWOOBJID itemId = LWOOBJID_EMPTY; - inStream->Read(itemId); + inStream.Read(itemId); if (!itemId) return; User* user = UserManager::Instance()->GetUser(sysAddr); @@ -6218,7 +6158,7 @@ void GameMessages::HandleRemoveDonationItem(RakNet::BitStream* inStream, Entity* inventoryComponent->MoveItemToInventory(item, eInventoryType::BRICKS, count, true, false, true); } -void GameMessages::HandleConfirmDonationOnPlayer(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleConfirmDonationOnPlayer(RakNet::BitStream& inStream, Entity* entity) { auto* inventoryComponent = entity->GetComponent(); if (!inventoryComponent) return; auto* missionComponent = entity->GetComponent(); @@ -6250,7 +6190,7 @@ void GameMessages::HandleConfirmDonationOnPlayer(RakNet::BitStream* inStream, En characterComponent->SetCurrentInteracting(LWOOBJID_EMPTY); } -void GameMessages::HandleCancelDonationOnPlayer(RakNet::BitStream* inStream, Entity* entity) { +void GameMessages::HandleCancelDonationOnPlayer(RakNet::BitStream& inStream, Entity* entity) { auto* inventoryComponent = entity->GetComponent(); if (!inventoryComponent) return; auto* inventory = inventoryComponent->GetInventory(eInventoryType::DONATION); diff --git a/dGame/dGameMessages/GameMessages.h b/dGame/dGameMessages/GameMessages.h index 9c8d183e..96bbf7c3 100644 --- a/dGame/dGameMessages/GameMessages.h +++ b/dGame/dGameMessages/GameMessages.h @@ -38,6 +38,7 @@ enum class eUseItemResponse : uint32_t; enum class eQuickBuildFailReason : uint32_t; enum class eQuickBuildState : uint32_t; enum class BehaviorSlot : int32_t; +enum class eVendorTransactionResult : uint32_t; namespace GameMessages { class PropertyDataMessage; @@ -55,14 +56,14 @@ namespace GameMessages { const SystemAddress& sysAddr, bool bFirstTime = true, const LWOOBJID& buildAreaID = LWOOBJID_EMPTY, - NiPoint3 buildStartPOS = NiPoint3::ZERO, + NiPoint3 buildStartPOS = NiPoint3Constant::ZERO, int sourceBAG = 0, const LWOOBJID& sourceID = LWOOBJID_EMPTY, LOT sourceLOT = 0, int sourceTYPE = 8, const LWOOBJID& targetID = 0, LOT targetLOT = 0, - NiPoint3 targetPOS = NiPoint3::ZERO, + NiPoint3 targetPOS = NiPoint3Constant::ZERO, int targetTYPE = 0 ); @@ -92,6 +93,9 @@ namespace GameMessages { void SendModifyLEGOScore(Entity* entity, const SystemAddress& sysAddr, int64_t score, eLootSourceType sourceType); void SendUIMessageServerToSingleClient(Entity* entity, const SystemAddress& sysAddr, const std::string& message, AMFBaseValue& args); + + // Specify sysAddr if you need to send a flash message to a client who you dont know the objectID of. + void SendUIMessageServerToSingleClient(const std::string& message, AMFBaseValue& args, const SystemAddress& sysAddr); void SendUIMessageServerToAllClients(const std::string& message, AMFBaseValue& args); void SendPlayEmbeddedEffectOnAllClientsNearObject(Entity* entity, std::u16string effectName, const LWOOBJID& fromObjectID, float radius); @@ -119,7 +123,7 @@ namespace GameMessages { void SendStop2DAmbientSound(Entity* entity, bool force, std::string audioGUID, bool result = false); void SendPlay2DAmbientSound(Entity* entity, std::string audioGUID, bool result = false); void SendSetNetworkScriptVar(Entity* entity, const SystemAddress& sysAddr, std::string data); - void SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, LOT item, int currency, NiPoint3 spawnPos = NiPoint3::ZERO, int count = 1); + void SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, LOT item, int currency, NiPoint3 spawnPos = NiPoint3Constant::ZERO, int count = 1); void SendSetPlayerControlScheme(Entity* entity, eControlScheme controlScheme); void SendPlayerReachedRespawnCheckpoint(Entity* entity, const NiPoint3& position, const NiQuaternion& rotation); @@ -132,7 +136,7 @@ namespace GameMessages { void SendVendorOpenWindow(Entity* entity, const SystemAddress& sysAddr); void SendVendorStatusUpdate(Entity* entity, const SystemAddress& sysAddr, bool bUpdateOnly = false); - void SendVendorTransactionResult(Entity* entity, const SystemAddress& sysAddr); + void SendVendorTransactionResult(Entity* entity, const SystemAddress& sysAddr, eVendorTransactionResult result); void SendRemoveItemFromInventory(Entity* entity, const SystemAddress& sysAddr, LWOOBJID iObjID, LOT templateID, int inventoryType, uint32_t stackCount, uint32_t stackRemaining); void SendConsumeClientItem(Entity* entity, bool bSuccess, LWOOBJID item); @@ -142,7 +146,7 @@ namespace GameMessages { void SendMatchResponse(Entity* entity, const SystemAddress& sysAddr, int response); void SendMatchUpdate(Entity* entity, const SystemAddress& sysAddr, std::string data, eMatchUpdate type); - void HandleUnUseModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleUnUseModel(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); void SendStartCelebrationEffect(Entity* entity, const SystemAddress& sysAddr, int celebrationID); // https://lcdruniverse.org/lu_packets/lu_packets/world/gm/client/struct.SetResurrectRestoreValues.html @@ -179,7 +183,7 @@ namespace GameMessages { * @param entity The Entity that sent the message * @param sysAddr The SystemAddress that sent the message */ - void HandleControlBehaviors(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleControlBehaviors(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); // Rails stuff void SendSetRailMovement(const LWOOBJID& objectID, bool pathGoForward, std::u16string pathName, uint32_t pathStart, @@ -193,9 +197,9 @@ namespace GameMessages { bool collisionEnabled = true, bool useDB = true, int32_t railComponentID = -1, LWOOBJID railActivatorObjectID = LWOOBJID_EMPTY); - void HandleClientRailMovementReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleCancelRailMovement(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandlePlayerRailArrivedNotification(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleClientRailMovementReady(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleCancelRailMovement(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandlePlayerRailArrivedNotification(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); void SendNotifyClientObject(const LWOOBJID& objectID, std::u16string name, int param1 = 0, int param2 = 0, const LWOOBJID& paramObj = LWOOBJID_EMPTY, std::string paramStr = "", const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); void SendNotifyClientZoneObject(const LWOOBJID& objectID, const std::u16string& name, int param1, int param2, const LWOOBJID& paramObj, const std::string& paramStr, const SystemAddress& sysAddr); @@ -236,7 +240,7 @@ namespace GameMessages { void SendLockNodeRotation(Entity* entity, std::string nodeName); - void SendSetBuildModeConfirmed(LWOOBJID objectId, const SystemAddress& sysAddr, bool start, bool warnVisitors, bool modePaused, int32_t modeValue, LWOOBJID playerId, NiPoint3 startPos = NiPoint3::ZERO); + void SendSetBuildModeConfirmed(LWOOBJID objectId, const SystemAddress& sysAddr, bool start, bool warnVisitors, bool modePaused, int32_t modeValue, LWOOBJID playerId, NiPoint3 startPos = NiPoint3Constant::ZERO); void SendGetModelsOnProperty(LWOOBJID objectId, std::map models, const SystemAddress& sysAddr); @@ -248,39 +252,39 @@ namespace GameMessages { void SendUGCEquipPostDeleteBasedOnEditMode(LWOOBJID objectId, const SystemAddress& sysAddr, LWOOBJID inventoryItem, int itemTotal); - void HandleSetPropertyAccess(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleSetPropertyAccess(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleUpdatePropertyOrModelForFilterCheck(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleQueryPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleQueryPropertyData(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleSetBuildMode(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleSetBuildMode(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleStartBuildingWithItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleStartBuildingWithItem(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandlePropertyEditorBegin(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandlePropertyEditorBegin(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandlePropertyEditorEnd(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandlePropertyEditorEnd(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandlePropertyContentsFromClient(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandlePropertyContentsFromClient(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandlePropertyModelEquipped(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandlePropertyModelEquipped(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandlePlacePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandlePlacePropertyModel(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleUpdatePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleUpdatePropertyModel(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleDeletePropertyModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleDeletePropertyModel(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleBBBLoadItemRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleBBBLoadItemRequest(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleBBBSaveRequest(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandlePropertyEntranceSync(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandlePropertyEntranceSync(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleEnterProperty(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleEnterProperty(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleSetConsumableItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleSetConsumableItem(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); void SendPlayCinematic(LWOOBJID objectId, std::u16string pathName, const SystemAddress& sysAddr, bool allowGhostUpdates = true, bool bCloseMultiInteract = true, bool bSendServerNotify = false, bool bUseControlledObjectForAudioListener = false, @@ -289,7 +293,7 @@ namespace GameMessages { void SendEndCinematic(LWOOBJID objectID, std::u16string pathName, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, float leadOut = -1.0f, bool leavePlayerLocked = false); - void HandleCinematicUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleCinematicUpdate(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); void SendSetStunned(LWOOBJID objectId, eStateChangeType stateChangeType, const SystemAddress& sysAddr, LWOOBJID originator = LWOOBJID_EMPTY, bool bCantAttack = false, bool bCantEquip = false, @@ -341,7 +345,7 @@ namespace GameMessages { void SendNotifyObject(LWOOBJID objectId, LWOOBJID objIDSender, std::u16string name, const SystemAddress& sysAddr, int param1 = 0, int param2 = 0); - void HandleVerifyAck(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleVerifyAck(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); void SendTeamPickupItem(LWOOBJID objectId, LWOOBJID lootID, LWOOBJID lootOwnerID, const SystemAddress& sysAddr); @@ -358,13 +362,13 @@ namespace GameMessages { void SendServerTradeUpdate(LWOOBJID objectId, uint64_t coins, const std::vector& items, const SystemAddress& sysAddr); - void HandleClientTradeRequest(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleClientTradeRequest(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleClientTradeCancel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleClientTradeCancel(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleClientTradeAccept(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleClientTradeAccept(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleClientTradeUpdate(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleClientTradeUpdate(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); //Pets: void SendNotifyPetTamingMinigame(LWOOBJID objectId, LWOOBJID petId, LWOOBJID playerTamingId, bool bForceTeleport, ePetTamingNotifyType notifyType, NiPoint3 petsDestPos, NiPoint3 telePos, NiQuaternion teleRot, const SystemAddress& sysAddr); @@ -399,23 +403,23 @@ namespace GameMessages { void SendPetNameChanged(LWOOBJID objectId, int32_t moderationStatus, std::u16string name, std::u16string ownerName, const SystemAddress& sysAddr); - void HandleClientExitTamingMinigame(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleClientExitTamingMinigame(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleStartServerPetMinigameTimer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleStartServerPetMinigameTimer(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandlePetTamingTryBuild(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandlePetTamingTryBuild(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleNotifyTamingBuildSuccess(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleNotifyTamingBuildSuccess(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleRequestSetPetName(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleRequestSetPetName(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleCommandPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleCommandPet(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleDespawnPet(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleDespawnPet(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleMessageBoxResponse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleMessageBoxResponse(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleChoiceBoxRespond(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleChoiceBoxRespond(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); void SendDisplayZoneSummary(LWOOBJID objectId, const SystemAddress& sysAddr, bool isPropertyMap = false, bool isZoneStart = false, LWOOBJID sender = LWOOBJID_EMPTY); @@ -452,7 +456,7 @@ namespace GameMessages { * @param entity The Entity that is dismounting * @param sysAddr the system address to send game message responses to */ - void HandleDismountComplete(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleDismountComplete(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); /** * @brief Handle acknowledging that the client possessed something @@ -461,7 +465,7 @@ namespace GameMessages { * @param entity The Entity that is possessing * @param sysAddr the system address to send game message responses to */ - void HandleAcknowledgePossession(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleAcknowledgePossession(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); /** * @brief A request from a client to get the hot properties that would appear on the news feed @@ -471,7 +475,7 @@ namespace GameMessages { * @param entity The Entity that sent the request * @param sysAddr The SystemAddress of the Entity that sent the request */ - void HandleGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleGetHotPropertyData(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); /** * @brief A request from a client to get the hot properties that would appear on the news feed @@ -493,26 +497,26 @@ namespace GameMessages { * @param entity The Entity that sent the request * @param sysAddr The SystemAddress of the Entity that sent the request */ - void SendGetHotPropertyData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void SendGetHotPropertyData(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); //Racing: - void HandleModuleAssemblyQueryData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleModuleAssemblyQueryData(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleModularAssemblyNIFCompleted(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleModularAssemblyNIFCompleted(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleVehicleSetWheelLockState(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleVehicleSetWheelLockState(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleRacingClientReady(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleRacingClientReady(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleRequestDie(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleRequestDie(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleVehicleNotifyServerAddPassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleVehicleNotifyServerAddPassiveBoostAction(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleVehicleNotifyServerRemovePassiveBoostAction(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleVehicleNotifyServerRemovePassiveBoostAction(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleRacingPlayerInfoResetFinished(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleRacingPlayerInfoResetFinished(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleVehicleNotifyHitImaginationServer(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleVehicleNotifyHitImaginationServer(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); void SendModuleAssemblyDBDataForClient(LWOOBJID objectId, LWOOBJID assemblyID, const std::u16string& data, const SystemAddress& sysAddr); @@ -552,7 +556,7 @@ namespace GameMessages { bool bUseLeaderboards ); - void HandleUpdatePropertyPerformanceCost(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleUpdatePropertyPerformanceCost(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); void SendNotifyClientShootingGalleryScore(LWOOBJID objectId, const SystemAddress& sysAddr, float addTime, @@ -561,20 +565,20 @@ namespace GameMessages { NiPoint3 targetPos ); - void HandleUpdateShootingGalleryRotation(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleUpdateShootingGalleryRotation(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); void SendUpdateReputation(const LWOOBJID objectId, const int64_t reputation, const SystemAddress& sysAddr); // Leaderboards void SendActivitySummaryLeaderboardData(const LWOOBJID& objectID, const Leaderboard* leaderboard, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); - void HandleActivitySummaryLeaderboardData(RakNet::BitStream* instream, Entity* entity, const SystemAddress& sysAddr); + void HandleActivitySummaryLeaderboardData(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); void SendRequestActivitySummaryLeaderboardData(const LWOOBJID& objectID, const LWOOBJID& targetID, const SystemAddress& sysAddr, const int32_t& gameID = 0, const int32_t& queryType = 1, const int32_t& resultsEnd = 10, const int32_t& resultsStart = 0, bool weekly = false); - void HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleActivityStateChangeRequest(RakNet::BitStream* inStream, Entity* entity); + void HandleRequestActivitySummaryLeaderboardData(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleActivityStateChangeRequest(RakNet::BitStream& inStream, Entity* entity); void SendVehicleAddPassiveBoostAction(LWOOBJID objectId, const SystemAddress& sysAddr); @@ -584,82 +588,82 @@ namespace GameMessages { //NT: - void HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleRequestMoveItemBetweenInventoryTypes(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); void SendShowActivityCountdown(LWOOBJID objectId, bool bPlayAdditionalSound, bool bPlayCountdownSound, std::u16string sndName, int32_t stateToPlaySoundOn, const SystemAddress& sysAddr); //Handlers: - void HandleToggleGhostReferenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleSetGhostReferencePosition(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleToggleGhostReferenceOverride(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleSetGhostReferencePosition(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); void SendSetNamebillboardState(const SystemAddress& sysAddr, LWOOBJID objectId); void SendShowBillboardInteractIcon(const SystemAddress& sysAddr, LWOOBJID objectId); - void HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleSellToVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleParseChatMessage(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleToggleGhostReffrenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleSetGhostReffrenceOverride(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleFireEventServerSide(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleRequestPlatformResync(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleQuickBuildCancel(RakNet::BitStream* inStream, Entity* entity); - void HandleRequestUse(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity); - void HandleModularBuildConvertModel(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleSetFlag(RakNet::BitStream* inStream, Entity* entity); - void HandleRespondToMission(RakNet::BitStream* inStream, Entity* entity); - void HandleMissionDialogOK(RakNet::BitStream* inStream, Entity* entity); - void HandleRequestLinkedMission(RakNet::BitStream* inStream, Entity* entity); - void HandleHasBeenCollected(RakNet::BitStream* inStream, Entity* entity); - void HandleNotifyServerLevelProcessingComplete(RakNet::BitStream* inStream, Entity* entity); - void HandlePickupCurrency(RakNet::BitStream* inStream, Entity* entity); - void HandleRequestDie(RakNet::BitStream* inStream, Entity* entity); - void HandleEquipItem(RakNet::BitStream* inStream, Entity* entity); - void HandleUnequipItem(RakNet::BitStream* inStream, Entity* entity); - void HandleRemoveItemFromInventory(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleMoveItemInInventory(RakNet::BitStream* inStream, Entity* entity); - void HandleMoveItemBetweenInventoryTypes(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleBuildModeSet(RakNet::BitStream* inStream, Entity* entity); - void HandleModularBuildFinish(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleDoneArrangingWithItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleModularBuildMoveAndEquip(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandlePickupItem(RakNet::BitStream* inStream, Entity* entity); - void HandleResurrect(RakNet::BitStream* inStream, Entity* entity); - void HandleModifyPlayerZoneStatistic(RakNet::BitStream* inStream, Entity* entity); - void HandleUpdatePlayerStatistic(RakNet::BitStream* inStream, Entity* entity); + void HandleBuyFromVendor(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleSellToVendor(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleBuybackFromVendor(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleParseChatMessage(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleToggleGhostReffrenceOverride(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleSetGhostReffrenceOverride(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleFireEventServerSide(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleRequestPlatformResync(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleQuickBuildCancel(RakNet::BitStream& inStream, Entity* entity); + void HandleRequestUse(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandlePlayEmote(RakNet::BitStream& inStream, Entity* entity); + void HandleModularBuildConvertModel(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleSetFlag(RakNet::BitStream& inStream, Entity* entity); + void HandleRespondToMission(RakNet::BitStream& inStream, Entity* entity); + void HandleMissionDialogOK(RakNet::BitStream& inStream, Entity* entity); + void HandleRequestLinkedMission(RakNet::BitStream& inStream, Entity* entity); + void HandleHasBeenCollected(RakNet::BitStream& inStream, Entity* entity); + void HandleNotifyServerLevelProcessingComplete(RakNet::BitStream& inStream, Entity* entity); + void HandlePickupCurrency(RakNet::BitStream& inStream, Entity* entity); + void HandleRequestDie(RakNet::BitStream& inStream, Entity* entity); + void HandleEquipItem(RakNet::BitStream& inStream, Entity* entity); + void HandleUnequipItem(RakNet::BitStream& inStream, Entity* entity); + void HandleRemoveItemFromInventory(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleMoveItemInInventory(RakNet::BitStream& inStream, Entity* entity); + void HandleMoveItemBetweenInventoryTypes(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleBuildModeSet(RakNet::BitStream& inStream, Entity* entity); + void HandleModularBuildFinish(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleDoneArrangingWithItem(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleModularBuildMoveAndEquip(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandlePickupItem(RakNet::BitStream& inStream, Entity* entity); + void HandleResurrect(RakNet::BitStream& inStream, Entity* entity); + void HandleModifyPlayerZoneStatistic(RakNet::BitStream& inStream, Entity* entity); + void HandleUpdatePlayerStatistic(RakNet::BitStream& inStream, Entity* entity); - void HandlePushEquippedItemsState(RakNet::BitStream* inStream, Entity* entity); + void HandlePushEquippedItemsState(RakNet::BitStream& inStream, Entity* entity); - void HandlePopEquippedItemsState(RakNet::BitStream* inStream, Entity* entity); + void HandlePopEquippedItemsState(RakNet::BitStream& inStream, Entity* entity); - void HandleClientItemConsumed(RakNet::BitStream* inStream, Entity* entity); + void HandleClientItemConsumed(RakNet::BitStream& inStream, Entity* entity); - void HandleUseNonEquipmentItem(RakNet::BitStream* inStream, Entity* entity); + void HandleUseNonEquipmentItem(RakNet::BitStream& inStream, Entity* entity); - void HandleMatchRequest(RakNet::BitStream* inStream, Entity* entity); + void HandleMatchRequest(RakNet::BitStream& inStream, Entity* entity); - void HandleReportBug(RakNet::BitStream* inStream, Entity* entity); + void HandleReportBug(RakNet::BitStream& inStream, Entity* entity); void SendRemoveBuff(Entity* entity, bool fromUnEquip, bool removeImmunity, uint32_t buffId); // bubble - void HandleDeactivateBubbleBuff(RakNet::BitStream* inStream, Entity* entity); + void HandleDeactivateBubbleBuff(RakNet::BitStream& inStream, Entity* entity); - void HandleActivateBubbleBuff(RakNet::BitStream* inStream, Entity* entity); + void HandleActivateBubbleBuff(RakNet::BitStream& inStream, Entity* entity); void SendActivateBubbleBuffFromServer(LWOOBJID objectId, const SystemAddress& sysAddr); void SendDeactivateBubbleBuffFromServer(LWOOBJID objectId, const SystemAddress& sysAddr); - void HandleZoneSummaryDismissed(RakNet::BitStream* inStream, Entity* entity); - void HandleRequestActivityExit(RakNet::BitStream* inStream, Entity* entity); + void HandleZoneSummaryDismissed(RakNet::BitStream& inStream, Entity* entity); + void HandleRequestActivityExit(RakNet::BitStream& inStream, Entity* entity); // Donation vendor - void HandleAddDonationItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleRemoveDonationItem(RakNet::BitStream* inStream, Entity* entity, const SystemAddress& sysAddr); - void HandleConfirmDonationOnPlayer(RakNet::BitStream* inStream, Entity* entity); - void HandleCancelDonationOnPlayer(RakNet::BitStream* inStream, Entity* entity); + void HandleAddDonationItem(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleRemoveDonationItem(RakNet::BitStream& inStream, Entity* entity, const SystemAddress& sysAddr); + void HandleConfirmDonationOnPlayer(RakNet::BitStream& inStream, Entity* entity); + void HandleCancelDonationOnPlayer(RakNet::BitStream& inStream, Entity* entity); }; #endif // GAMEMESSAGES_H diff --git a/dGame/dGameMessages/PropertyDataMessage.cpp b/dGame/dGameMessages/PropertyDataMessage.cpp index 29bc8ea9..ab7fe9c3 100644 --- a/dGame/dGameMessages/PropertyDataMessage.cpp +++ b/dGame/dGameMessages/PropertyDataMessage.cpp @@ -103,7 +103,7 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con } GameMessages::PropertyDataMessage::PropertyDataMessage(uint32_t mapID) { - const auto propertyTemplate = CDClientManager::Instance().GetTable()->GetByMapID(mapID); + const auto propertyTemplate = CDClientManager::GetTable()->GetByMapID(mapID); TemplateID = propertyTemplate.id; ZoneId = propertyTemplate.mapID; diff --git a/dGame/dGameMessages/RequestServerProjectileImpact.h b/dGame/dGameMessages/RequestServerProjectileImpact.h index 090d8274..c15090c0 100644 --- a/dGame/dGameMessages/RequestServerProjectileImpact.h +++ b/dGame/dGameMessages/RequestServerProjectileImpact.h @@ -19,44 +19,44 @@ public: sBitStream = _sBitStream; } - RequestServerProjectileImpact(RakNet::BitStream* stream) : RequestServerProjectileImpact() { + RequestServerProjectileImpact(RakNet::BitStream& stream) : RequestServerProjectileImpact() { Deserialize(stream); } ~RequestServerProjectileImpact() { } - void Serialize(RakNet::BitStream* stream) { - stream->Write(eGameMessageType::REQUEST_SERVER_PROJECTILE_IMPACT); + void Serialize(RakNet::BitStream& stream) { + stream.Write(eGameMessageType::REQUEST_SERVER_PROJECTILE_IMPACT); - stream->Write(i64LocalID != LWOOBJID_EMPTY); - if (i64LocalID != LWOOBJID_EMPTY) stream->Write(i64LocalID); + stream.Write(i64LocalID != LWOOBJID_EMPTY); + if (i64LocalID != LWOOBJID_EMPTY) stream.Write(i64LocalID); - stream->Write(i64TargetID != LWOOBJID_EMPTY); - if (i64TargetID != LWOOBJID_EMPTY) stream->Write(i64TargetID); + stream.Write(i64TargetID != LWOOBJID_EMPTY); + if (i64TargetID != LWOOBJID_EMPTY) stream.Write(i64TargetID); uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); + stream.Write(sBitStreamLength); for (uint32_t k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); + stream.Write(sBitStream[k]); } } - bool Deserialize(RakNet::BitStream* stream) { + bool Deserialize(RakNet::BitStream& stream) { bool i64LocalIDIsDefault{}; - stream->Read(i64LocalIDIsDefault); - if (i64LocalIDIsDefault != 0) stream->Read(i64LocalID); + stream.Read(i64LocalIDIsDefault); + if (i64LocalIDIsDefault != 0) stream.Read(i64LocalID); bool i64TargetIDIsDefault{}; - stream->Read(i64TargetIDIsDefault); - if (i64TargetIDIsDefault != 0) stream->Read(i64TargetID); + stream.Read(i64TargetIDIsDefault); + if (i64TargetIDIsDefault != 0) stream.Read(i64TargetID); uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); + stream.Read(sBitStreamLength); for (uint32_t k = 0; k < sBitStreamLength; k++) { unsigned char character; - stream->Read(character); + stream.Read(character); sBitStream.push_back(character); } diff --git a/dGame/dGameMessages/StartSkill.h b/dGame/dGameMessages/StartSkill.h index 40bc210f..bc0f18d7 100644 --- a/dGame/dGameMessages/StartSkill.h +++ b/dGame/dGameMessages/StartSkill.h @@ -16,13 +16,13 @@ public: consumableItemID = LWOOBJID_EMPTY; fCasterLatency = 0.0f; iCastType = 0; - lastClickedPosit = NiPoint3::ZERO; + lastClickedPosit = NiPoint3Constant::ZERO; optionalTargetID = LWOOBJID_EMPTY; - originatorRot = NiQuaternion::IDENTITY; + originatorRot = NiQuaternionConstant::IDENTITY; uiSkillHandle = 0; } - StartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, LWOOBJID _consumableItemID = LWOOBJID_EMPTY, float _fCasterLatency = 0.0f, int32_t _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternion::IDENTITY, uint32_t _uiSkillHandle = 0) { + StartSkill(LWOOBJID _optionalOriginatorID, std::string _sBitStream, TSkillID _skillID, bool _bUsedMouse = false, LWOOBJID _consumableItemID = LWOOBJID_EMPTY, float _fCasterLatency = 0.0f, int32_t _iCastType = 0, NiPoint3 _lastClickedPosit = NiPoint3Constant::ZERO, LWOOBJID _optionalTargetID = LWOOBJID_EMPTY, NiQuaternion _originatorRot = NiQuaternionConstant::IDENTITY, uint32_t _uiSkillHandle = 0) { bUsedMouse = _bUsedMouse; consumableItemID = _consumableItemID; fCasterLatency = _fCasterLatency; @@ -36,92 +36,92 @@ public: uiSkillHandle = _uiSkillHandle; } - StartSkill(RakNet::BitStream* stream) : StartSkill() { + StartSkill(RakNet::BitStream& stream) : StartSkill() { Deserialize(stream); } ~StartSkill() { } - void Serialize(RakNet::BitStream* stream) { - stream->Write(eGameMessageType::START_SKILL); + void Serialize(RakNet::BitStream& stream) { + stream.Write(eGameMessageType::START_SKILL); - stream->Write(bUsedMouse); + stream.Write(bUsedMouse); - stream->Write(consumableItemID != LWOOBJID_EMPTY); - if (consumableItemID != LWOOBJID_EMPTY) stream->Write(consumableItemID); + stream.Write(consumableItemID != LWOOBJID_EMPTY); + if (consumableItemID != LWOOBJID_EMPTY) stream.Write(consumableItemID); - stream->Write(fCasterLatency != 0.0f); - if (fCasterLatency != 0.0f) stream->Write(fCasterLatency); + stream.Write(fCasterLatency != 0.0f); + if (fCasterLatency != 0.0f) stream.Write(fCasterLatency); - stream->Write(iCastType != 0); - if (iCastType != 0) stream->Write(iCastType); + stream.Write(iCastType != 0); + if (iCastType != 0) stream.Write(iCastType); - stream->Write(lastClickedPosit != NiPoint3::ZERO); - if (lastClickedPosit != NiPoint3::ZERO) stream->Write(lastClickedPosit); + stream.Write(lastClickedPosit != NiPoint3Constant::ZERO); + if (lastClickedPosit != NiPoint3Constant::ZERO) stream.Write(lastClickedPosit); - stream->Write(optionalOriginatorID); + stream.Write(optionalOriginatorID); - stream->Write(optionalTargetID != LWOOBJID_EMPTY); - if (optionalTargetID != LWOOBJID_EMPTY) stream->Write(optionalTargetID); + stream.Write(optionalTargetID != LWOOBJID_EMPTY); + if (optionalTargetID != LWOOBJID_EMPTY) stream.Write(optionalTargetID); - stream->Write(originatorRot != NiQuaternion::IDENTITY); - if (originatorRot != NiQuaternion::IDENTITY) stream->Write(originatorRot); + stream.Write(originatorRot != NiQuaternionConstant::IDENTITY); + if (originatorRot != NiQuaternionConstant::IDENTITY) stream.Write(originatorRot); uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); + stream.Write(sBitStreamLength); for (uint32_t k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); + stream.Write(sBitStream[k]); } - stream->Write(skillID); + stream.Write(skillID); - stream->Write(uiSkillHandle != 0); - if (uiSkillHandle != 0) stream->Write(uiSkillHandle); + stream.Write(uiSkillHandle != 0); + if (uiSkillHandle != 0) stream.Write(uiSkillHandle); } - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bUsedMouse); + bool Deserialize(RakNet::BitStream& stream) { + stream.Read(bUsedMouse); bool consumableItemIDIsDefault{}; - stream->Read(consumableItemIDIsDefault); - if (consumableItemIDIsDefault != 0) stream->Read(consumableItemID); + stream.Read(consumableItemIDIsDefault); + if (consumableItemIDIsDefault != 0) stream.Read(consumableItemID); bool fCasterLatencyIsDefault{}; - stream->Read(fCasterLatencyIsDefault); - if (fCasterLatencyIsDefault != 0) stream->Read(fCasterLatency); + stream.Read(fCasterLatencyIsDefault); + if (fCasterLatencyIsDefault != 0) stream.Read(fCasterLatency); bool iCastTypeIsDefault{}; - stream->Read(iCastTypeIsDefault); - if (iCastTypeIsDefault != 0) stream->Read(iCastType); + stream.Read(iCastTypeIsDefault); + if (iCastTypeIsDefault != 0) stream.Read(iCastType); bool lastClickedPositIsDefault{}; - stream->Read(lastClickedPositIsDefault); - if (lastClickedPositIsDefault != 0) stream->Read(lastClickedPosit); + stream.Read(lastClickedPositIsDefault); + if (lastClickedPositIsDefault != 0) stream.Read(lastClickedPosit); - stream->Read(optionalOriginatorID); + stream.Read(optionalOriginatorID); bool optionalTargetIDIsDefault{}; - stream->Read(optionalTargetIDIsDefault); - if (optionalTargetIDIsDefault != 0) stream->Read(optionalTargetID); + stream.Read(optionalTargetIDIsDefault); + if (optionalTargetIDIsDefault != 0) stream.Read(optionalTargetID); bool originatorRotIsDefault{}; - stream->Read(originatorRotIsDefault); - if (originatorRotIsDefault != 0) stream->Read(originatorRot); + stream.Read(originatorRotIsDefault); + if (originatorRotIsDefault != 0) stream.Read(originatorRot); uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); + stream.Read(sBitStreamLength); for (uint32_t k = 0; k < sBitStreamLength; k++) { unsigned char character; - stream->Read(character); + stream.Read(character); sBitStream.push_back(character); } - stream->Read(skillID); + stream.Read(skillID); bool uiSkillHandleIsDefault{}; - stream->Read(uiSkillHandleIsDefault); - if (uiSkillHandleIsDefault != 0) stream->Read(uiSkillHandle); + stream.Read(uiSkillHandleIsDefault); + if (uiSkillHandleIsDefault != 0) stream.Read(uiSkillHandle); return true; } diff --git a/dGame/dGameMessages/SyncSkill.h b/dGame/dGameMessages/SyncSkill.h index 6485199e..b881d270 100644 --- a/dGame/dGameMessages/SyncSkill.h +++ b/dGame/dGameMessages/SyncSkill.h @@ -21,39 +21,39 @@ public: uiSkillHandle = _uiSkillHandle; } - SyncSkill(RakNet::BitStream* stream) : SyncSkill() { + SyncSkill(RakNet::BitStream& stream) : SyncSkill() { Deserialize(stream); } ~SyncSkill() { } - void Serialize(RakNet::BitStream* stream) { - stream->Write(eGameMessageType::SYNC_SKILL); + void Serialize(RakNet::BitStream& stream) { + stream.Write(eGameMessageType::SYNC_SKILL); - stream->Write(bDone); + stream.Write(bDone); uint32_t sBitStreamLength = sBitStream.length(); - stream->Write(sBitStreamLength); + stream.Write(sBitStreamLength); for (unsigned int k = 0; k < sBitStreamLength; k++) { - stream->Write(sBitStream[k]); + stream.Write(sBitStream[k]); } - stream->Write(uiBehaviorHandle); - stream->Write(uiSkillHandle); + stream.Write(uiBehaviorHandle); + stream.Write(uiSkillHandle); } - bool Deserialize(RakNet::BitStream* stream) { - stream->Read(bDone); + bool Deserialize(RakNet::BitStream& stream) { + stream.Read(bDone); uint32_t sBitStreamLength{}; - stream->Read(sBitStreamLength); + stream.Read(sBitStreamLength); for (uint32_t k = 0; k < sBitStreamLength; k++) { unsigned char character; - stream->Read(character); + stream.Read(character); sBitStream.push_back(character); } - stream->Read(uiBehaviorHandle); - stream->Read(uiSkillHandle); + stream.Read(uiBehaviorHandle); + stream.Read(uiSkillHandle); return true; } diff --git a/dGame/dInventory/CMakeLists.txt b/dGame/dInventory/CMakeLists.txt index a663a97d..b45b27bf 100644 --- a/dGame/dInventory/CMakeLists.txt +++ b/dGame/dInventory/CMakeLists.txt @@ -5,5 +5,32 @@ set(DGAME_DINVENTORY_SOURCES "ItemSet.cpp" "ItemSetPassiveAbility.cpp") -add_library(dInventory STATIC ${DGAME_DINVENTORY_SOURCES}) +add_library(dInventory OBJECT ${DGAME_DINVENTORY_SOURCES}) +target_include_directories(dInventory PUBLIC "." + "${PROJECT_SOURCE_DIR}/dGame/dUtilities" # Item.h uses Preconditions.h + "${PROJECT_SOURCE_DIR}/dCommon/eEnums" # Item.h uses dCommonVars.h + PRIVATE + "${PROJECT_SOURCE_DIR}/dCommon" + "${PROJECT_SOURCE_DIR}/dCommon/dEnums" + "${PROJECT_SOURCE_DIR}/dCommon/dClient" # Item.cpp uses AssetManager + + "${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase" + "${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase/CDClientTables" + + "${PROJECT_SOURCE_DIR}/dGame/dGameMessages" # direct + "${PROJECT_SOURCE_DIR}/dGame/dComponents" # direct InventoryComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dBehaviors" # via InventoryComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dEntity" # via dZoneManager/Spawner.h + "${PROJECT_SOURCE_DIR}/dGame/dMission" # via MissionComponent.h + "${PROJECT_SOURCE_DIR}/dZoneManager" # via Item.cpp +) target_precompile_headers(dInventory REUSE_FROM dGameBase) +# Workaround for compiler bug where the optimized code could result in a memcpy of 0 bytes, even though that isnt possible. +# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=97185 +if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") + set_source_files_properties("Item.cpp" PROPERTIES COMPILE_FLAGS "-Wno-stringop-overflow") +endif() +# INTERFACE link w/o dependency +#set_property(TARGET dInventory APPEND PROPERTY INTERFACE_LINK_LIBRARIES +# dNet dDatabaseCDClient +#) diff --git a/dGame/dInventory/Inventory.cpp b/dGame/dInventory/Inventory.cpp index 4475f77b..35222bea 100644 --- a/dGame/dInventory/Inventory.cpp +++ b/dGame/dInventory/Inventory.cpp @@ -275,9 +275,9 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) { } const CDItemComponent& Inventory::FindItemComponent(const LOT lot) { - auto* registry = CDClientManager::Instance().GetTable(); + auto* registry = CDClientManager::GetTable(); - auto* itemComponents = CDClientManager::Instance().GetTable(); + auto* itemComponents = CDClientManager::GetTable(); const auto componentId = registry->GetByIDAndType(lot, eReplicaComponentType::ITEM); @@ -293,7 +293,7 @@ const CDItemComponent& Inventory::FindItemComponent(const LOT lot) { } bool Inventory::IsValidItem(const LOT lot) { - auto* registry = CDClientManager::Instance().GetTable(); + auto* registry = CDClientManager::GetTable(); const auto componentId = registry->GetByIDAndType(lot, eReplicaComponentType::ITEM); diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 4a13cd92..d3f15315 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -247,7 +247,7 @@ bool Item::IsEquipped() const { } bool Item::Consume() { - auto* skillsTable = CDClientManager::Instance().GetTable(); + auto* skillsTable = CDClientManager::GetTable(); auto skills = skillsTable->Query([this](const CDObjectSkills entry) { return entry.objectTemplate == static_cast(lot); @@ -313,12 +313,12 @@ void Item::UseNonEquip(Item* item) { bool success = false; auto inventory = item->GetInventory(); if (inventory && inventory->GetType() == eInventoryType::ITEMS) { - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::PACKAGE); if (packageComponentId == 0) return; - auto* packCompTable = CDClientManager::Instance().GetTable(); + auto* packCompTable = CDClientManager::GetTable(); auto packages = packCompTable->Query([=](const CDPackageComponent entry) {return entry.id == static_cast(packageComponentId); }); auto success = !packages.empty(); @@ -396,7 +396,7 @@ void Item::Disassemble(const eInventoryType inventoryType) { } void Item::DisassembleModel(uint32_t numToDismantle) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto componentId = table->GetByIDAndType(GetLot(), eReplicaComponentType::RENDER); @@ -468,20 +468,20 @@ void Item::DisassembleModel(uint32_t numToDismantle) { // First iteration gets the count std::map parts; while (currentBrick) { - auto* designID = currentBrick->Attribute("designID"); + const char* const designID = currentBrick->Attribute("designID"); if (designID) { - uint32_t designId; - if (!GeneralUtils::TryParse(designID, designId)) { + const auto designId = GeneralUtils::TryParse(designID); + if (!designId) { LOG("Failed to parse designID %s", designID); continue; } - parts[designId]++; + parts[designId.value()]++; } currentBrick = currentBrick->NextSiblingElement(searchTerm.c_str()); } - auto* brickIDTable = CDClientManager::Instance().GetTable(); + auto* brickIDTable = CDClientManager::GetTable(); // Second iteration actually distributes the bricks for (const auto& [part, count] : parts) { diff --git a/dGame/dInventory/ItemSet.cpp b/dGame/dInventory/ItemSet.cpp index 3364b63b..1d086786 100644 --- a/dGame/dInventory/ItemSet.cpp +++ b/dGame/dInventory/ItemSet.cpp @@ -87,10 +87,8 @@ ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) { m_Items = {}; while (std::getline(stream, token, ',')) { - int32_t value; - if (GeneralUtils::TryParse(token, value)) { - m_Items.push_back(value); - } + const auto validToken = GeneralUtils::TryParse(token); + if (validToken) m_Items.push_back(validToken.value()); } m_Equipped = {}; @@ -129,7 +127,7 @@ void ItemSet::OnEquip(const LOT lot) { auto* missionComponent = m_InventoryComponent->GetParent()->GetComponent(); for (const auto skill : skillSet) { - auto* skillTable = CDClientManager::Instance().GetTable(); + auto* skillTable = CDClientManager::GetTable(); const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; @@ -161,7 +159,7 @@ void ItemSet::OnUnEquip(const LOT lot) { const auto& skillComponent = m_InventoryComponent->GetParent()->GetComponent(); for (const auto skill : skillSet) { - auto* skillTable = CDClientManager::Instance().GetTable(); + auto* skillTable = CDClientManager::GetTable(); const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; diff --git a/dGame/dMission/CMakeLists.txt b/dGame/dMission/CMakeLists.txt index 4e4bdec2..51f74c37 100644 --- a/dGame/dMission/CMakeLists.txt +++ b/dGame/dMission/CMakeLists.txt @@ -3,6 +3,16 @@ set(DGAME_DMISSION_SOURCES "MissionPrerequisites.cpp" "MissionTask.cpp") -add_library(dMission STATIC ${DGAME_DMISSION_SOURCES}) +add_library(dMission OBJECT ${DGAME_DMISSION_SOURCES}) target_link_libraries(dMission PUBLIC dDatabase) +target_include_directories(dMission PUBLIC "." + PRIVATE + "${PROJECT_SOURCE_DIR}/dGame/dComponents" + "${PROJECT_SOURCE_DIR}/dGame/dInventory" # via CharacterComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dUtilities" # via CharacterComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dGameMessages" # via LevelProgressionComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dEntity" # via dZoneManager/Spawner.h + "${PROJECT_SOURCE_DIR}/dGame/dBehaviors" # via InventoryComponent.h + "${PROJECT_SOURCE_DIR}/dZoneManager" # via Mission.cpp, MissionTask.cpp +) target_precompile_headers(dMission REUSE_FROM dGameBase) diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index 6799b834..4ed80bf3 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -24,6 +24,7 @@ #include "eMissionTaskType.h" #include "eMissionLockState.h" #include "eReplicaComponentType.h" +#include "Character.h" #include "CDMissionEmailTable.h" @@ -40,7 +41,7 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { m_State = eMissionState::UNKNOWN; - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionsTable = CDClientManager::GetTable(); auto* mis = missionsTable->GetPtrByMissionID(missionId); info = *mis; @@ -51,7 +52,7 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { return; } - auto* tasksTable = CDClientManager::Instance().GetTable(); + auto* tasksTable = CDClientManager::GetTable(); auto tasks = tasksTable->GetByMissionID(missionId); @@ -179,7 +180,7 @@ void Mission::UpdateXml(tinyxml2::XMLElement* element) { } bool Mission::IsValidMission(const uint32_t missionId) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto missions = table->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); @@ -189,7 +190,7 @@ bool Mission::IsValidMission(const uint32_t missionId) { } bool Mission::IsValidMission(const uint32_t missionId, CDMissions& info) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto missions = table->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); @@ -208,8 +209,8 @@ Entity* Mission::GetAssociate() const { return m_MissionComponent->GetParent(); } -User* Mission::GetUser() const { - return GetAssociate()->GetParentUser(); +Character* Mission::GetCharacter() const { + return GetAssociate()->GetCharacter(); } uint32_t Mission::GetMissionId() const { @@ -333,7 +334,7 @@ void Mission::Complete(const bool yieldRewards) { missionComponent->Progress(eMissionTaskType::RACING, info.id, static_cast(eRacingTaskParam::COMPLETE_TRACK_TASKS)); - auto* missionEmailTable = CDClientManager::Instance().GetTable(); + auto* missionEmailTable = CDClientManager::GetTable(); const auto missionId = GetMissionId(); @@ -390,7 +391,7 @@ void Mission::Catchup() { if (type == eMissionTaskType::PLAYER_FLAG) { for (int32_t target : task->GetAllTargets()) { - const auto flag = GetUser()->GetLastUsedChar()->GetPlayerFlag(target); + const auto flag = GetCharacter()->GetPlayerFlag(target); if (!flag) { continue; @@ -413,7 +414,7 @@ void Mission::YieldRewards() { return; } - auto* character = GetUser()->GetLastUsedChar(); + auto* character = GetCharacter(); auto* inventoryComponent = entity->GetComponent(); auto* levelComponent = entity->GetComponent(); @@ -599,8 +600,10 @@ void Mission::SetMissionState(const eMissionState state, const bool sendingRewar if (entity == nullptr) { return; } + auto* characterComponent = entity->GetComponent(); + if (!characterComponent) return; - GameMessages::SendNotifyMission(entity, entity->GetParentUser()->GetSystemAddress(), info.id, static_cast(state), sendingRewards); + GameMessages::SendNotifyMission(entity, characterComponent->GetSystemAddress(), info.id, static_cast(state), sendingRewards); } void Mission::SetMissionTypeState(eMissionLockState state, const std::string& type, const std::string& subType) { diff --git a/dGame/dMission/Mission.h b/dGame/dMission/Mission.h index f7c17003..d8c104e8 100644 --- a/dGame/dMission/Mission.h +++ b/dGame/dMission/Mission.h @@ -17,6 +17,7 @@ namespace tinyxml2 { enum class eMissionState : int; enum class eMissionLockState : int; class MissionComponent; +class Character; /** * A mission (or achievement) that a player may unlock, progress and complete. @@ -46,7 +47,7 @@ public: * Returns the account owns the entity that is currently progressing this mission * @return the account owns the entity that is currently progressing this mission */ - User* GetUser() const; + Character* GetCharacter() const; /** * Returns the current state of this mission diff --git a/dGame/dMission/MissionPrerequisites.cpp b/dGame/dMission/MissionPrerequisites.cpp index 89d547fd..b5b81160 100644 --- a/dGame/dMission/MissionPrerequisites.cpp +++ b/dGame/dMission/MissionPrerequisites.cpp @@ -161,7 +161,7 @@ bool MissionPrerequisites::CheckPrerequisites(uint32_t missionId, const std::uno return index->second->Execute(missions); } - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionsTable = CDClientManager::GetTable(); const auto missionEntries = missionsTable->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); }); diff --git a/dGame/dMission/MissionTask.cpp b/dGame/dMission/MissionTask.cpp index 604276ec..2fe9bc9f 100644 --- a/dGame/dMission/MissionTask.cpp +++ b/dGame/dMission/MissionTask.cpp @@ -27,19 +27,15 @@ MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) std::string token; while (std::getline(stream, token, ',')) { - uint32_t parameter; - if (GeneralUtils::TryParse(token, parameter)) { - parameters.push_back(parameter); - } + const auto parameter = GeneralUtils::TryParse(token); + if (parameter) parameters.push_back(parameter.value()); } stream = std::istringstream(info->targetGroup); while (std::getline(stream, token, ',')) { - uint32_t parameter; - if (GeneralUtils::TryParse(token, parameter)) { - targets.push_back(parameter); - } + const auto parameter = GeneralUtils::TryParse(token); + if (parameter) targets.push_back(parameter.value()); } } diff --git a/dGame/dPropertyBehaviors/BlockDefinition.cpp b/dGame/dPropertyBehaviors/BlockDefinition.cpp index 2950ac82..e67a90d8 100644 --- a/dGame/dPropertyBehaviors/BlockDefinition.cpp +++ b/dGame/dPropertyBehaviors/BlockDefinition.cpp @@ -2,8 +2,8 @@ BlockDefinition BlockDefinition::blockDefinitionDefault{}; -BlockDefinition::BlockDefinition(std::string defaultValue, float minimumValue, float maximumValue) { - this->defaultValue = defaultValue; - this->minimumValue = minimumValue; - this->maximumValue = maximumValue; +BlockDefinition::BlockDefinition(const std::string& defaultValue, const float minimumValue, const float maximumValue) + : m_DefaultValue{ defaultValue } + , m_MinimumValue{ minimumValue } + , m_MaximumValue{ maximumValue } { } diff --git a/dGame/dPropertyBehaviors/BlockDefinition.h b/dGame/dPropertyBehaviors/BlockDefinition.h index 3a5a6bf1..84722ea2 100644 --- a/dGame/dPropertyBehaviors/BlockDefinition.h +++ b/dGame/dPropertyBehaviors/BlockDefinition.h @@ -7,19 +7,20 @@ class AMFArrayValue; class BlockDefinition { public: - BlockDefinition(std::string defaultValue = "", float minimumValue = 0.0f, float maximumValue = 0.0f); + BlockDefinition(const std::string& defaultValue = "", const float minimumValue = 0.0f, const float maximumValue = 0.0f); static BlockDefinition blockDefinitionDefault; - std::string& GetDefaultValue() { return defaultValue; }; - float GetMinimumValue() { return minimumValue; }; - float GetMaximumValue() { return maximumValue; }; - void SetDefaultValue(std::string value) { defaultValue = value; }; - void SetMinimumValue(float value) { minimumValue = value; }; - void SetMaximumValue(float value) { maximumValue = value; }; + [[nodiscard]] const std::string& GetDefaultValue() const { return m_DefaultValue; } + [[nodiscard]] float GetMinimumValue() const noexcept { return m_MinimumValue; } + [[nodiscard]] float GetMaximumValue() const noexcept { return m_MaximumValue; } + void SetDefaultValue(const std::string& value) { m_DefaultValue = value; } + void SetMinimumValue(const float value) noexcept { m_MinimumValue = value; } + void SetMaximumValue(const float value) noexcept { m_MaximumValue = value; } + private: - std::string defaultValue; - float minimumValue; - float maximumValue; + std::string m_DefaultValue; + float m_MinimumValue; + float m_MaximumValue; }; #endif //!__BLOCKDEFINITION__H__ diff --git a/dGame/dPropertyBehaviors/CMakeLists.txt b/dGame/dPropertyBehaviors/CMakeLists.txt index 47c8ff23..3e03ba1d 100644 --- a/dGame/dPropertyBehaviors/CMakeLists.txt +++ b/dGame/dPropertyBehaviors/CMakeLists.txt @@ -12,5 +12,15 @@ foreach(file ${DGAME_DPROPERTYBEHAVIORS_CONTROLBEHAVIORMESSAGES}) set(DGAME_DPROPERTYBEHAVIORS_SOURCES ${DGAME_DPROPERTYBEHAVIORS_SOURCES} "ControlBehaviorMessages/${file}") endforeach() -add_library(dPropertyBehaviors STATIC ${DGAME_DPROPERTYBEHAVIORS_SOURCES}) +add_library(dPropertyBehaviors OBJECT ${DGAME_DPROPERTYBEHAVIORS_SOURCES}) +target_link_libraries(dPropertyBehaviors PRIVATE dDatabaseCDClient) +target_include_directories(dPropertyBehaviors PUBLIC "." "ControlBehaviorMessages" + PRIVATE + "${PROJECT_SOURCE_DIR}/dCommon/dClient" # ControlBehaviors.cpp uses AssetManager + "${PROJECT_SOURCE_DIR}/dGame/dUtilities" # ObjectIdManager.h + "${PROJECT_SOURCE_DIR}/dGame/dGameMessages" # GameMessages.h + "${PROJECT_SOURCE_DIR}/dGame/dComponents" # ModelComponent.h +) target_precompile_headers(dPropertyBehaviors REUSE_FROM dGameBase) + +target_link_libraries(dPropertyBehaviors INTERFACE dComponents) diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.cpp index 73f1391d..3e62a2d7 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.cpp @@ -1,46 +1,34 @@ #include "Action.h" #include "Amf3.h" -Action::Action() { - type = ""; - valueParameterName = ""; - valueParameterString = ""; - valueParameterDouble = 0.0; -} - -Action::Action(AMFArrayValue* arguments) { - type = ""; - valueParameterName = ""; - valueParameterString = ""; - valueParameterDouble = 0.0; - for (auto& [paramName, paramValue] : arguments->GetAssociative()) { +Action::Action(const AMFArrayValue& arguments) { + for (const auto& [paramName, paramValue] : arguments.GetAssociative()) { if (paramName == "Type") { if (paramValue->GetValueType() != eAmf::String) continue; - type = static_cast(paramValue)->GetValue(); + m_Type = static_cast(paramValue)->GetValue(); } else { - valueParameterName = paramName; + m_ValueParameterName = paramName; // Message is the only known string parameter - if (valueParameterName == "Message") { + if (m_ValueParameterName == "Message") { if (paramValue->GetValueType() != eAmf::String) continue; - valueParameterString = static_cast(paramValue)->GetValue(); + m_ValueParameterString = static_cast(paramValue)->GetValue(); } else { if (paramValue->GetValueType() != eAmf::Double) continue; - valueParameterDouble = static_cast(paramValue)->GetValue(); + m_ValueParameterDouble = static_cast(paramValue)->GetValue(); } } } } void Action::SendBehaviorBlocksToClient(AMFArrayValue& args) const { - auto* actionArgs = args.PushArray(); - actionArgs->Insert("Type", type); + auto* const actionArgs = args.PushArray(); + actionArgs->Insert("Type", m_Type); - auto valueParameterName = GetValueParameterName(); - if (valueParameterName.empty()) return; + if (m_ValueParameterName.empty()) return; - if (valueParameterName == "Message") { - actionArgs->Insert(valueParameterName, valueParameterString); + if (m_ValueParameterName == "Message") { + actionArgs->Insert(m_ValueParameterName, m_ValueParameterString); } else { - actionArgs->Insert(valueParameterName, valueParameterDouble); + actionArgs->Insert(m_ValueParameterName, m_ValueParameterDouble); } } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.h index df665889..988e616c 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/Action.h @@ -11,19 +11,20 @@ class AMFArrayValue; */ class Action { public: - Action(); - Action(AMFArrayValue* arguments); - const std::string& GetType() const { return type; }; - const std::string& GetValueParameterName() const { return valueParameterName; }; - const std::string& GetValueParameterString() const { return valueParameterString; }; - const double GetValueParameterDouble() const { return valueParameterDouble; }; + Action() = default; + Action(const AMFArrayValue& arguments); + [[nodiscard]] const std::string& GetType() const { return m_Type; }; + [[nodiscard]] const std::string& GetValueParameterName() const { return m_ValueParameterName; }; + [[nodiscard]] const std::string& GetValueParameterString() const { return m_ValueParameterString; }; + [[nodiscard]] double GetValueParameterDouble() const noexcept { return m_ValueParameterDouble; }; void SendBehaviorBlocksToClient(AMFArrayValue& args) const; + private: - std::string type; - std::string valueParameterName; - std::string valueParameterString; - double valueParameterDouble; + double m_ValueParameterDouble{ 0.0 }; + std::string m_Type{ "" }; + std::string m_ValueParameterName{ "" }; + std::string m_ValueParameterString{ "" }; }; #endif //!__ACTION__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.cpp index c2ba2eeb..36da8d73 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.cpp @@ -4,27 +4,20 @@ #include "Amf3.h" -ActionContext::ActionContext() { - stripId = 0; - stateId = BehaviorState::HOME_STATE; +ActionContext::ActionContext(const AMFArrayValue& arguments, const std::string& customStateKey, const std::string& customStripKey) + : m_StripId{ GetStripIdFromArgument(arguments, customStripKey) } + , m_StateId{ GetBehaviorStateFromArgument(arguments, customStateKey) } { } -ActionContext::ActionContext(AMFArrayValue* arguments, std::string customStateKey, std::string customStripKey) { - stripId = 0; - stateId = BehaviorState::HOME_STATE; - stripId = GetStripIdFromArgument(arguments, customStripKey); - stateId = GetBehaviorStateFromArgument(arguments, customStateKey); -} - -BehaviorState ActionContext::GetBehaviorStateFromArgument(AMFArrayValue* arguments, const std::string& key) { - auto* stateIDValue = arguments->Get(key); +BehaviorState ActionContext::GetBehaviorStateFromArgument(const AMFArrayValue& arguments, const std::string& key) const { + const auto* const stateIDValue = arguments.Get(key); if (!stateIDValue) throw std::invalid_argument("Unable to find behavior state from argument \"" + key + "\""); return static_cast(stateIDValue->GetValue()); } -StripId ActionContext::GetStripIdFromArgument(AMFArrayValue* arguments, const std::string& key) { - auto* stripIdValue = arguments->Get(key); +StripId ActionContext::GetStripIdFromArgument(const AMFArrayValue& arguments, const std::string& key) const { + const auto* const stripIdValue = arguments.Get(key); if (!stripIdValue) throw std::invalid_argument("Unable to find strip ID from argument \"" + key + "\""); return static_cast(stripIdValue->GetValue()); diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.h index 91e91e72..8ecea8a2 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/ActionContext.h @@ -12,15 +12,16 @@ class AMFArrayValue; */ class ActionContext { public: - ActionContext(); - ActionContext(AMFArrayValue* arguments, std::string customStateKey = "stateID", std::string customStripKey = "stripID"); - const StripId GetStripId() const { return stripId; }; - const BehaviorState GetStateId() const { return stateId; }; + ActionContext() noexcept = default; + ActionContext(const AMFArrayValue& arguments, const std::string& customStateKey = "stateID", const std::string& customStripKey = "stripID"); + [[nodiscard]] StripId GetStripId() const noexcept { return m_StripId; }; + [[nodiscard]] BehaviorState GetStateId() const noexcept { return m_StateId; }; + private: - BehaviorState GetBehaviorStateFromArgument(AMFArrayValue* arguments, const std::string& key); - StripId GetStripIdFromArgument(AMFArrayValue* arguments, const std::string& key); - StripId stripId; - BehaviorState stateId; + [[nodiscard]] BehaviorState GetBehaviorStateFromArgument(const AMFArrayValue& arguments, const std::string& key) const; + [[nodiscard]] StripId GetStripIdFromArgument(const AMFArrayValue& arguments, const std::string& key) const; + StripId m_StripId{ 0 }; + BehaviorState m_StateId{ BehaviorState::HOME_STATE }; }; #endif //!__ACTIONCONTEXT__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp index 36d9a3dc..35b9cf0d 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.cpp @@ -1,13 +1,14 @@ #include "AddActionMessage.h" -AddActionMessage::AddActionMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - actionContext = ActionContext(arguments); - actionIndex = GetActionIndexFromArgument(arguments); +AddActionMessage::AddActionMessage(const AMFArrayValue& arguments) + : BehaviorMessageBase{ arguments } + , m_ActionIndex{ GetActionIndexFromArgument(arguments) } + , m_ActionContext{ arguments } { - auto* actionValue = arguments->GetArray("action"); + const auto* const actionValue = arguments.GetArray("action"); if (!actionValue) return; - action = Action(actionValue); + m_Action = Action{ *actionValue }; - LOG_DEBUG("actionIndex %i stripId %i stateId %i type %s valueParameterName %s valueParameterString %s valueParameterDouble %f behaviorId %i", actionIndex, actionContext.GetStripId(), actionContext.GetStateId(), action.GetType().c_str(), action.GetValueParameterName().c_str(), action.GetValueParameterString().c_str(), action.GetValueParameterDouble(), behaviorId); + LOG_DEBUG("actionIndex %i stripId %i stateId %i type %s valueParameterName %s valueParameterString %s valueParameterDouble %f m_BehaviorId %i", m_ActionIndex, m_ActionContext.GetStripId(), m_ActionContext.GetStateId(), m_Action.GetType().c_str(), m_Action.GetValueParameterName().c_str(), m_Action.GetValueParameterString().c_str(), m_Action.GetValueParameterDouble(), m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h index ac3a9612..7f94820d 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddActionMessage.h @@ -13,14 +13,18 @@ class AMFArrayValue; */ class AddActionMessage : public BehaviorMessageBase { public: - AddActionMessage(AMFArrayValue* arguments); - int32_t GetActionIndex() const { return actionIndex; }; - Action GetAction() const { return action; }; - ActionContext GetActionContext() const { return actionContext; }; + AddActionMessage(const AMFArrayValue& arguments); + + [[nodiscard]] int32_t GetActionIndex() const noexcept { return m_ActionIndex; }; + + [[nodiscard]] const Action& GetAction() const noexcept { return m_Action; }; + + [[nodiscard]] const ActionContext& GetActionContext() const noexcept { return m_ActionContext; }; + private: - int32_t actionIndex = -1; - ActionContext actionContext; - Action action; + int32_t m_ActionIndex{ -1 }; + ActionContext m_ActionContext; + Action m_Action; }; #endif //!__ADDACTIONMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp index cf96ab13..45e3d974 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.cpp @@ -1,11 +1,9 @@ #include "AddMessage.h" -AddMessage::AddMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - behaviorIndex = 0; - auto* behaviorIndexValue = arguments->Get("BehaviorIndex"); - +AddMessage::AddMessage(const AMFArrayValue& arguments) : BehaviorMessageBase{ arguments } { + const auto* const behaviorIndexValue = arguments.Get("BehaviorIndex"); if (!behaviorIndexValue) return; - behaviorIndex = static_cast(behaviorIndexValue->GetValue()); - LOG_DEBUG("behaviorId %i index %i", behaviorId, behaviorIndex); + m_BehaviorIndex = static_cast(behaviorIndexValue->GetValue()); + LOG_DEBUG("behaviorId %i index %i", m_BehaviorId, m_BehaviorIndex); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h index 76627665..8bf0b70c 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddMessage.h @@ -9,10 +9,11 @@ */ class AddMessage : public BehaviorMessageBase { public: - AddMessage(AMFArrayValue* arguments); - const uint32_t GetBehaviorIndex() const { return behaviorIndex; }; + AddMessage(const AMFArrayValue& arguments); + [[nodiscard]] uint32_t GetBehaviorIndex() const noexcept { return m_BehaviorIndex; }; + private: - uint32_t behaviorIndex; + uint32_t m_BehaviorIndex{ 0 }; }; #endif //!__ADDMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp index 5e75f6c4..c7207b33 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.cpp @@ -2,23 +2,24 @@ #include "Action.h" -AddStripMessage::AddStripMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - actionContext = ActionContext(arguments); - position = StripUiPosition(arguments); +AddStripMessage::AddStripMessage(const AMFArrayValue& arguments) + : BehaviorMessageBase{ arguments } + , m_Position{ arguments } + , m_ActionContext{ arguments } { - auto* strip = arguments->GetArray("strip"); + const auto* const strip = arguments.GetArray("strip"); if (!strip) return; - auto* actions = strip->GetArray("actions"); + const auto* const actions = strip->GetArray("actions"); if (!actions) return; - for (uint32_t actionNumber = 0; actionNumber < actions->GetDense().size(); actionNumber++) { - auto* actionValue = actions->GetArray(actionNumber); + for (size_t actionNumber = 0; actionNumber < actions->GetDense().size(); ++actionNumber) { + const auto* const actionValue = actions->GetArray(actionNumber); if (!actionValue) continue; - actionsToAdd.push_back(Action(actionValue)); + m_ActionsToAdd.emplace_back(*actionValue); - LOG_DEBUG("xPosition %f yPosition %f stripId %i stateId %i behaviorId %i t %s valueParameterName %s valueParameterString %s valueParameterDouble %f", position.GetX(), position.GetY(), actionContext.GetStripId(), actionContext.GetStateId(), behaviorId, actionsToAdd.back().GetType().c_str(), actionsToAdd.back().GetValueParameterName().c_str(), actionsToAdd.back().GetValueParameterString().c_str(), actionsToAdd.back().GetValueParameterDouble()); + LOG_DEBUG("xPosition %f yPosition %f stripId %i stateId %i behaviorId %i t %s valueParameterName %s valueParameterString %s valueParameterDouble %f", m_Position.GetX(), m_Position.GetY(), m_ActionContext.GetStripId(), m_ActionContext.GetStateId(), m_BehaviorId, m_ActionsToAdd.back().GetType().c_str(), m_ActionsToAdd.back().GetValueParameterName().c_str(), m_ActionsToAdd.back().GetValueParameterString().c_str(), m_ActionsToAdd.back().GetValueParameterDouble()); } - LOG_DEBUG("number of actions %i", actionsToAdd.size()); + LOG_DEBUG("number of actions %i", m_ActionsToAdd.size()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h index 0b9a09e3..a5361034 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/AddStripMessage.h @@ -18,14 +18,18 @@ class AMFArrayValue; */ class AddStripMessage : public BehaviorMessageBase { public: - AddStripMessage(AMFArrayValue* arguments); - StripUiPosition GetPosition() const { return position; }; - ActionContext GetActionContext() const { return actionContext; }; - std::vector GetActionsToAdd() const { return actionsToAdd; }; + AddStripMessage(const AMFArrayValue& arguments); + + [[nodiscard]] const StripUiPosition& GetPosition() const noexcept { return m_Position; } + + [[nodiscard]] const ActionContext& GetActionContext() const noexcept { return m_ActionContext; } + + [[nodiscard]] const std::vector& GetActionsToAdd() const noexcept { return m_ActionsToAdd; } + private: - StripUiPosition position; - ActionContext actionContext; - std::vector actionsToAdd; + StripUiPosition m_Position; + ActionContext m_ActionContext; + std::vector m_ActionsToAdd; }; #endif //!__ADDSTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp index cc817cd7..a1cbb064 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp @@ -4,28 +4,24 @@ #include "BehaviorStates.h" #include "dCommonVars.h" -BehaviorMessageBase::BehaviorMessageBase(AMFArrayValue* arguments) { - behaviorId = GetBehaviorIdFromArgument(arguments); -} - -int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* arguments) { - const auto* key = "BehaviorID"; - auto* behaviorIDValue = arguments->Get(key); +int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(const AMFArrayValue& arguments) { + static constexpr const char* key = "BehaviorID"; + const auto* const behaviorIDValue = arguments.Get(key); + int32_t behaviorId = DefaultBehaviorId; if (behaviorIDValue && behaviorIDValue->GetValueType() == eAmf::String) { - GeneralUtils::TryParse(behaviorIDValue->GetValue(), behaviorId); - } else if (arguments->Get(key) && arguments->Get(key)->GetValueType() != eAmf::Undefined) { + behaviorId = + GeneralUtils::TryParse(behaviorIDValue->GetValue()).value_or(behaviorId); + } else if (arguments.Get(key) && arguments.Get(key)->GetValueType() != eAmf::Undefined) { throw std::invalid_argument("Unable to find behavior ID"); } return behaviorId; } -int32_t BehaviorMessageBase::GetActionIndexFromArgument(AMFArrayValue* arguments, const std::string& keyName) { - auto* actionIndexAmf = arguments->Get(keyName); - if (!actionIndexAmf) { - throw std::invalid_argument("Unable to find actionIndex"); - } +int32_t BehaviorMessageBase::GetActionIndexFromArgument(const AMFArrayValue& arguments, const std::string& keyName) const { + const auto* const actionIndexAmf = arguments.Get(keyName); + if (!actionIndexAmf) throw std::invalid_argument("Unable to find actionIndex"); return static_cast(actionIndexAmf->GetValue()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h index 8a841d7f..bb251a74 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.h @@ -15,14 +15,15 @@ enum class BehaviorState : uint32_t; */ class BehaviorMessageBase { public: - static inline int32_t DefaultBehaviorId = -1; - const int32_t GetBehaviorId() const { return behaviorId; }; - bool IsDefaultBehaviorId() { return behaviorId == DefaultBehaviorId; }; - BehaviorMessageBase(AMFArrayValue* arguments); + static constexpr int32_t DefaultBehaviorId{ -1 }; + BehaviorMessageBase(const AMFArrayValue& arguments) : m_BehaviorId{ GetBehaviorIdFromArgument(arguments) } {} + [[nodiscard]] int32_t GetBehaviorId() const noexcept { return m_BehaviorId; } + [[nodiscard]] bool IsDefaultBehaviorId() const noexcept { return m_BehaviorId == DefaultBehaviorId; } + protected: - int32_t GetBehaviorIdFromArgument(AMFArrayValue* arguments); - int32_t GetActionIndexFromArgument(AMFArrayValue* arguments, const std::string& keyName = "actionIndex"); - int32_t behaviorId = DefaultBehaviorId; + [[nodiscard]] int32_t GetBehaviorIdFromArgument(const AMFArrayValue& arguments); + [[nodiscard]] int32_t GetActionIndexFromArgument(const AMFArrayValue& arguments, const std::string& keyName = "actionIndex") const; + int32_t m_BehaviorId{ DefaultBehaviorId }; }; #endif //!__BEHAVIORMESSAGEBASE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp index 18327ecf..1efc5aee 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.cpp @@ -1,11 +1,11 @@ #include "MergeStripsMessage.h" -MergeStripsMessage::MergeStripsMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - sourceActionContext = ActionContext(arguments, "srcStateID", "srcStripID"); +MergeStripsMessage::MergeStripsMessage(const AMFArrayValue& arguments) + : BehaviorMessageBase{ arguments } + , m_DstActionIndex{ GetActionIndexFromArgument(arguments, "dstActionIndex") } + , m_SourceActionContext{ arguments, "srcStateID", "srcStripID" } + , m_DestinationActionContext{ arguments, "dstStateID", "dstStripID" } { - destinationActionContext = ActionContext(arguments, "dstStateID", "dstStripID"); - dstActionIndex = GetActionIndexFromArgument(arguments, "dstActionIndex"); - - LOG_DEBUG("srcstripId %i dststripId %i srcstateId %i dststateId %i dstactionIndex %i behaviorId %i", sourceActionContext.GetStripId(), destinationActionContext.GetStripId(), sourceActionContext.GetStateId(), destinationActionContext.GetStateId(), dstActionIndex, behaviorId); + LOG_DEBUG("srcstripId %i dststripId %i srcstateId %i dststateId %i dstactionIndex %i behaviorId %i", m_SourceActionContext.GetStripId(), m_DestinationActionContext.GetStripId(), m_SourceActionContext.GetStateId(), m_DestinationActionContext.GetStateId(), m_DstActionIndex, m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h index 7fa4d3a8..d778d632 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MergeStripsMessage.h @@ -13,17 +13,23 @@ class AMFArrayValue; */ class MergeStripsMessage : public BehaviorMessageBase { public: - MergeStripsMessage(AMFArrayValue* arguments); - int32_t GetDstActionIndex() const { return dstActionIndex; }; - ActionContext GetSourceActionContext() const { return sourceActionContext; }; - ActionContext GetDestinationActionContext() const { return destinationActionContext; }; - const std::vector& GetMigratedActions() const { return migratedActions; }; - void SetMigratedActions(std::vector::const_iterator start, std::vector::const_iterator end) { migratedActions.assign(start, end); }; + MergeStripsMessage(const AMFArrayValue& arguments); + + [[nodiscard]] int32_t GetDstActionIndex() const noexcept { return m_DstActionIndex; } + + [[nodiscard]] const ActionContext& GetSourceActionContext() const noexcept { return m_SourceActionContext; } + + [[nodiscard]] const ActionContext& GetDestinationActionContext() const noexcept { return m_DestinationActionContext; } + + [[nodiscard]] const std::vector& GetMigratedActions() const noexcept { return m_MigratedActions; } + + void SetMigratedActions(std::vector::const_iterator start, std::vector::const_iterator end) { m_MigratedActions.assign(start, end); }; + private: - std::vector migratedActions; - ActionContext sourceActionContext; - ActionContext destinationActionContext; - int32_t dstActionIndex; + int32_t m_DstActionIndex; + std::vector m_MigratedActions; + ActionContext m_SourceActionContext; + ActionContext m_DestinationActionContext; }; #endif //!__MERGESTRIPSMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp index 4d45429b..9791bc2a 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.cpp @@ -1,11 +1,11 @@ #include "MigrateActionsMessage.h" -MigrateActionsMessage::MigrateActionsMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - sourceActionContext = ActionContext(arguments, "srcStateID", "srcStripID"); - srcActionIndex = GetActionIndexFromArgument(arguments, "srcActionIndex"); +MigrateActionsMessage::MigrateActionsMessage(const AMFArrayValue& arguments) + : BehaviorMessageBase{ arguments } + , m_SrcActionIndex{ GetActionIndexFromArgument(arguments, "srcActionIndex") } + , m_DstActionIndex{ GetActionIndexFromArgument(arguments, "dstActionIndex") } + , m_SourceActionContext{ arguments, "srcStateID", "srcStripID" } + , m_DestinationActionContext{ arguments, "dstStateID", "dstStripID" } { - destinationActionContext = ActionContext(arguments, "dstStateID", "dstStripID"); - dstActionIndex = GetActionIndexFromArgument(arguments, "dstActionIndex"); - - LOG_DEBUG("srcactionIndex %i dstactionIndex %i srcstripId %i dststripId %i srcstateId %i dststateId %i behaviorId %i", srcActionIndex, dstActionIndex, sourceActionContext.GetStripId(), destinationActionContext.GetStripId(), sourceActionContext.GetStateId(), destinationActionContext.GetStateId(), behaviorId); + LOG_DEBUG("srcactionIndex %i dstactionIndex %i srcstripId %i dststripId %i srcstateId %i dststateId %i behaviorId %i", m_SrcActionIndex, m_DstActionIndex, m_SourceActionContext.GetStripId(), m_DestinationActionContext.GetStripId(), m_SourceActionContext.GetStateId(), m_DestinationActionContext.GetStateId(), m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h index 2f1ac243..9813fbf4 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MigrateActionsMessage.h @@ -13,19 +13,26 @@ class AMFArrayValue; */ class MigrateActionsMessage : public BehaviorMessageBase { public: - MigrateActionsMessage(AMFArrayValue* arguments); - int32_t GetSrcActionIndex() const { return srcActionIndex; }; - int32_t GetDstActionIndex() const { return dstActionIndex; }; - ActionContext GetSourceActionContext() const { return sourceActionContext; }; - ActionContext GetDestinationActionContext() const { return destinationActionContext; }; - const std::vector& GetMigratedActions() const { return migratedActions; }; - void SetMigratedActions(std::vector::const_iterator start, std::vector::const_iterator end) { migratedActions.assign(start, end); }; + MigrateActionsMessage(const AMFArrayValue& arguments); + + [[nodiscard]] int32_t GetSrcActionIndex() const noexcept { return m_SrcActionIndex; } + + [[nodiscard]] int32_t GetDstActionIndex() const noexcept { return m_DstActionIndex; } + + [[nodiscard]] const ActionContext& GetSourceActionContext() const noexcept { return m_SourceActionContext; } + + [[nodiscard]] const ActionContext& GetDestinationActionContext() const noexcept { return m_DestinationActionContext; } + + [[nodiscard]] const std::vector& GetMigratedActions() const noexcept { return m_MigratedActions; } + + void SetMigratedActions(std::vector::const_iterator start, std::vector::const_iterator end) { m_MigratedActions.assign(start, end); } + private: - std::vector migratedActions; - ActionContext sourceActionContext; - ActionContext destinationActionContext; - int32_t srcActionIndex; - int32_t dstActionIndex; + int32_t m_SrcActionIndex; + int32_t m_DstActionIndex; + std::vector m_MigratedActions; + ActionContext m_SourceActionContext; + ActionContext m_DestinationActionContext; }; #endif //!__MIGRATEACTIONSMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp index 5195e676..cab5c4a3 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.cpp @@ -1,9 +1,9 @@ #include "MoveToInventoryMessage.h" -MoveToInventoryMessage::MoveToInventoryMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - auto* behaviorIndexValue = arguments->Get("BehaviorIndex"); +MoveToInventoryMessage::MoveToInventoryMessage(const AMFArrayValue& arguments) : BehaviorMessageBase{ arguments } { + const auto* const behaviorIndexValue = arguments.Get("BehaviorIndex"); if (!behaviorIndexValue) return; - behaviorIndex = static_cast(behaviorIndexValue->GetValue()); - LOG_DEBUG("behaviorId %i behaviorIndex %i", behaviorId, behaviorIndex); + m_BehaviorIndex = static_cast(behaviorIndexValue->GetValue()); + LOG_DEBUG("behaviorId %i behaviorIndex %i", m_BehaviorId, m_BehaviorIndex); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h index dc105766..e1f88713 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/MoveToInventoryMessage.h @@ -7,15 +7,15 @@ class AMFArrayValue; /** * @brief Sent when a player moves a Behavior A at position B to their inventory. - * */ #pragma warning("This Control Behavior Message does not have a test yet. Non-developers can ignore this warning.") class MoveToInventoryMessage : public BehaviorMessageBase { public: - MoveToInventoryMessage(AMFArrayValue* arguments); - const uint32_t GetBehaviorIndex() const { return behaviorIndex; }; + MoveToInventoryMessage(const AMFArrayValue& arguments); + [[nodiscard]] uint32_t GetBehaviorIndex() const noexcept { return m_BehaviorIndex; }; + private: - uint32_t behaviorIndex; + uint32_t m_BehaviorIndex; }; #endif //!__MOVETOINVENTORYMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp index d612ae2a..99fe6f6a 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.cpp @@ -1,10 +1,10 @@ #include "RearrangeStripMessage.h" -RearrangeStripMessage::RearrangeStripMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - actionContext = ActionContext(arguments); - srcActionIndex = GetActionIndexFromArgument(arguments, "srcActionIndex"); +RearrangeStripMessage::RearrangeStripMessage(const AMFArrayValue& arguments) + : BehaviorMessageBase{ arguments } + , m_SrcActionIndex{ GetActionIndexFromArgument(arguments, "srcActionIndex") } + , m_DstActionIndex{ GetActionIndexFromArgument(arguments, "dstActionIndex") } + , m_ActionContext{ arguments } { - dstActionIndex = GetActionIndexFromArgument(arguments, "dstActionIndex"); - - LOG_DEBUG("srcactionIndex %i dstactionIndex %i stripId %i behaviorId %i stateId %i", srcActionIndex, dstActionIndex, actionContext.GetStripId(), behaviorId, actionContext.GetStateId()); + LOG_DEBUG("srcactionIndex %i dstactionIndex %i stripId %i behaviorId %i stateId %i", m_SrcActionIndex, m_DstActionIndex, m_ActionContext.GetStripId(), m_BehaviorId, m_ActionContext.GetStateId()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h index db12c046..629757bf 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RearrangeStripMessage.h @@ -10,14 +10,17 @@ */ class RearrangeStripMessage : public BehaviorMessageBase { public: - RearrangeStripMessage(AMFArrayValue* arguments); - int32_t GetSrcActionIndex() const { return srcActionIndex; }; - int32_t GetDstActionIndex() const { return dstActionIndex; }; - ActionContext GetActionContext() const { return actionContext; }; + RearrangeStripMessage(const AMFArrayValue& arguments); + + [[nodiscard]] int32_t GetSrcActionIndex() const noexcept { return m_SrcActionIndex; } + [[nodiscard]] int32_t GetDstActionIndex() const noexcept { return m_DstActionIndex; } + + [[nodiscard]] const ActionContext& GetActionContext() const noexcept { return m_ActionContext; } + private: - ActionContext actionContext; - int32_t srcActionIndex; - int32_t dstActionIndex; + int32_t m_SrcActionIndex; + int32_t m_DstActionIndex; + ActionContext m_ActionContext; }; #endif //!__REARRANGESTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp index c6164c6f..15407012 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.cpp @@ -1,8 +1,9 @@ #include "RemoveActionsMessage.h" -RemoveActionsMessage::RemoveActionsMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - actionContext = ActionContext(arguments); - actionIndex = GetActionIndexFromArgument(arguments); +RemoveActionsMessage::RemoveActionsMessage(const AMFArrayValue& arguments) + : BehaviorMessageBase{ arguments } + , m_ActionIndex{ GetActionIndexFromArgument(arguments) } + , m_ActionContext{ arguments } { - LOG_DEBUG("behaviorId %i actionIndex %i stripId %i stateId %i", behaviorId, actionIndex, actionContext.GetStripId(), actionContext.GetStateId()); + LOG_DEBUG("behaviorId %i actionIndex %i stripId %i stateId %i", m_BehaviorId, m_ActionIndex, m_ActionContext.GetStripId(), m_ActionContext.GetStateId()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h index 860df0af..2caa6366 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveActionsMessage.h @@ -12,12 +12,15 @@ class AMFArrayValue; */ class RemoveActionsMessage : public BehaviorMessageBase { public: - RemoveActionsMessage(AMFArrayValue* arguments); - int32_t GetActionIndex() const { return actionIndex; }; - ActionContext GetActionContext() const { return actionContext; }; + RemoveActionsMessage(const AMFArrayValue& arguments); + + [[nodiscard]] int32_t GetActionIndex() const noexcept { return m_ActionIndex; } + + [[nodiscard]] const ActionContext& GetActionContext() const noexcept { return m_ActionContext; } + private: - ActionContext actionContext; - int32_t actionIndex; + int32_t m_ActionIndex; + ActionContext m_ActionContext; }; #endif //!__REMOVEACTIONSMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp index b70beece..f0275377 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.cpp @@ -1,7 +1,8 @@ #include "RemoveStripMessage.h" -RemoveStripMessage::RemoveStripMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - actionContext = ActionContext(arguments); +RemoveStripMessage::RemoveStripMessage(const AMFArrayValue& arguments) + : BehaviorMessageBase{ arguments } + , m_ActionContext{ arguments } { - LOG_DEBUG("stripId %i stateId %i behaviorId %i", actionContext.GetStripId(), actionContext.GetStateId(), behaviorId); + LOG_DEBUG("stripId %i stateId %i behaviorId %i", m_ActionContext.GetStripId(), m_ActionContext.GetStateId(), m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h index 6a32ab0c..37501ea6 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RemoveStripMessage.h @@ -10,10 +10,12 @@ */ class RemoveStripMessage : public BehaviorMessageBase { public: - RemoveStripMessage(AMFArrayValue* arguments); - ActionContext GetActionContext() const { return actionContext; }; + RemoveStripMessage(const AMFArrayValue& arguments); + + const ActionContext& GetActionContext() const noexcept { return m_ActionContext; } + private: - ActionContext actionContext; + ActionContext m_ActionContext; }; #endif //!__REMOVESTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp index 17365be2..82d88bf8 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.cpp @@ -1,9 +1,9 @@ #include "RenameMessage.h" -RenameMessage::RenameMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - auto* nameAmf = arguments->Get("Name"); +RenameMessage::RenameMessage(const AMFArrayValue& arguments) : BehaviorMessageBase{ arguments } { + const auto* const nameAmf = arguments.Get("Name"); if (!nameAmf) return; - name = nameAmf->GetValue(); - LOG_DEBUG("behaviorId %i n %s", behaviorId, name.c_str()); + m_Name = nameAmf->GetValue(); + LOG_DEBUG("behaviorId %i n %s", m_BehaviorId, m_Name.c_str()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h index 3f4119d2..1f4e45c0 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/RenameMessage.h @@ -7,14 +7,14 @@ class AMFArrayValue; /** * @brief Sent when a player renames this behavior - * */ class RenameMessage : public BehaviorMessageBase { public: - RenameMessage(AMFArrayValue* arguments); - const std::string& GetName() const { return name; }; + RenameMessage(const AMFArrayValue& arguments); + [[nodiscard]] const std::string& GetName() const { return m_Name; }; + private: - std::string name; + std::string m_Name; }; #endif //!__RENAMEMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp index 45dad737..6003c982 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.cpp @@ -1,11 +1,11 @@ #include "SplitStripMessage.h" -SplitStripMessage::SplitStripMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - sourceActionContext = ActionContext(arguments, "srcStateID", "srcStripID"); - srcActionIndex = GetActionIndexFromArgument(arguments, "srcActionIndex"); +SplitStripMessage::SplitStripMessage(const AMFArrayValue& arguments) + : BehaviorMessageBase{ arguments } + , m_SrcActionIndex{ GetActionIndexFromArgument(arguments, "srcActionIndex") } + , m_SourceActionContext{ arguments, "srcStateID", "srcStripID" } + , m_DestinationActionContext{ arguments, "dstStateID", "dstStripID" } + , m_DestinationPosition{ arguments, "dstStripUI" } { - destinationActionContext = ActionContext(arguments, "dstStateID", "dstStripID"); - destinationPosition = StripUiPosition(arguments, "dstStripUI"); - - LOG_DEBUG("behaviorId %i xPosition %f yPosition %f sourceStrip %i destinationStrip %i sourceState %i destinationState %i srcActindex %i", behaviorId, destinationPosition.GetX(), destinationPosition.GetY(), sourceActionContext.GetStripId(), destinationActionContext.GetStripId(), sourceActionContext.GetStateId(), destinationActionContext.GetStateId(), srcActionIndex); + LOG_DEBUG("behaviorId %i xPosition %f yPosition %f sourceStrip %i destinationStrip %i sourceState %i destinationState %i srcActindex %i", m_BehaviorId, m_DestinationPosition.GetX(), m_DestinationPosition.GetY(), m_SourceActionContext.GetStripId(), m_DestinationActionContext.GetStripId(), m_SourceActionContext.GetStateId(), m_DestinationActionContext.GetStateId(), m_SrcActionIndex); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h index e41d50eb..33d6ec6a 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/SplitStripMessage.h @@ -14,20 +14,27 @@ class AMFArrayValue; */ class SplitStripMessage : public BehaviorMessageBase { public: - SplitStripMessage(AMFArrayValue* arguments); - ActionContext GetSourceActionContext() const { return sourceActionContext; }; - ActionContext GetDestinationActionContext() const { return destinationActionContext; }; - int32_t GetSrcActionIndex() const { return srcActionIndex; }; - StripUiPosition GetPosition() const { return destinationPosition; }; - const std::vector& GetTransferredActions() const { return transferredActions; }; - void SetTransferredActions(std::vector::const_iterator begin, std::vector::const_iterator end) { transferredActions.assign(begin, end); }; -private: - ActionContext sourceActionContext; - ActionContext destinationActionContext; - int32_t srcActionIndex; - StripUiPosition destinationPosition; + SplitStripMessage(const AMFArrayValue& arguments); + + [[nodiscard]] int32_t GetSrcActionIndex() const noexcept { return m_SrcActionIndex; } - std::vector transferredActions; + [[nodiscard]] const ActionContext& GetSourceActionContext() const noexcept { return m_SourceActionContext; } + + [[nodiscard]] const ActionContext& GetDestinationActionContext() const noexcept { return m_DestinationActionContext; } + + [[nodiscard]] const StripUiPosition& GetPosition() const noexcept { return m_DestinationPosition; } + + [[nodiscard]] const std::vector& GetTransferredActions() const noexcept { return m_TransferredActions; } + + void SetTransferredActions(std::vector::const_iterator begin, std::vector::const_iterator end) { m_TransferredActions.assign(begin, end); }; + +private: + int32_t m_SrcActionIndex; + ActionContext m_SourceActionContext; + ActionContext m_DestinationActionContext; + StripUiPosition m_DestinationPosition; + + std::vector m_TransferredActions; }; #endif //!__SPLITSTRIPMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.cpp index 8b2d1d36..56dc43ff 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.cpp @@ -2,27 +2,22 @@ #include "Amf3.h" -StripUiPosition::StripUiPosition() { - xPosition = 0.0; - yPosition = 0.0; -} - -StripUiPosition::StripUiPosition(AMFArrayValue* arguments, std::string uiKeyName) { - xPosition = 0.0; - yPosition = 0.0; - auto* uiArray = arguments->GetArray(uiKeyName); +StripUiPosition::StripUiPosition(const AMFArrayValue& arguments, const std::string& uiKeyName) { + const auto* const uiArray = arguments.GetArray(uiKeyName); if (!uiArray) return; - auto* xPositionValue = uiArray->Get("x"); - auto* yPositionValue = uiArray->Get("y"); - if (!xPositionValue || !yPositionValue) return; + const auto* const xPositionValue = uiArray->Get("x"); + if (!xPositionValue) return; - yPosition = yPositionValue->GetValue(); - xPosition = xPositionValue->GetValue(); + const auto* const yPositionValue = uiArray->Get("y"); + if (!yPositionValue) return; + + m_YPosition = yPositionValue->GetValue(); + m_XPosition = xPositionValue->GetValue(); } void StripUiPosition::SendBehaviorBlocksToClient(AMFArrayValue& args) const { - auto* uiArgs = args.InsertArray("ui"); - uiArgs->Insert("x", xPosition); - uiArgs->Insert("y", yPosition); + auto* const uiArgs = args.InsertArray("ui"); + uiArgs->Insert("x", m_XPosition); + uiArgs->Insert("y", m_YPosition); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.h index 92578cdc..f202210d 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/StripUiPosition.h @@ -9,14 +9,15 @@ class AMFArrayValue; */ class StripUiPosition { public: - StripUiPosition(); - StripUiPosition(AMFArrayValue* arguments, std::string uiKeyName = "ui"); + StripUiPosition() noexcept = default; + StripUiPosition(const AMFArrayValue& arguments, const std::string& uiKeyName = "ui"); void SendBehaviorBlocksToClient(AMFArrayValue& args) const; - double GetX() const { return xPosition; }; - double GetY() const { return yPosition; }; + [[nodiscard]] double GetX() const noexcept { return m_XPosition; } + [[nodiscard]] double GetY() const noexcept { return m_YPosition; } + private: - double xPosition; - double yPosition; + double m_XPosition{ 0.0 }; + double m_YPosition{ 0.0 }; }; #endif //!__STRIPUIPOSITION__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp index 924a9e62..fabf2726 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.cpp @@ -2,14 +2,15 @@ #include "Action.h" -UpdateActionMessage::UpdateActionMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - actionContext = ActionContext(arguments); +UpdateActionMessage::UpdateActionMessage(const AMFArrayValue& arguments) + : BehaviorMessageBase{ arguments } + , m_ActionIndex{ GetActionIndexFromArgument(arguments) } + , m_ActionContext{ arguments } { - auto* actionValue = arguments->GetArray("action"); + const auto* const actionValue = arguments.GetArray("action"); if (!actionValue) return; + + m_Action = Action{ *actionValue }; - action = Action(actionValue); - actionIndex = GetActionIndexFromArgument(arguments); - - LOG_DEBUG("type %s valueParameterName %s valueParameterString %s valueParameterDouble %f behaviorId %i actionIndex %i stripId %i stateId %i", action.GetType().c_str(), action.GetValueParameterName().c_str(), action.GetValueParameterString().c_str(), action.GetValueParameterDouble(), behaviorId, actionIndex, actionContext.GetStripId(), actionContext.GetStateId()); + LOG_DEBUG("type %s valueParameterName %s valueParameterString %s valueParameterDouble %f behaviorId %i actionIndex %i stripId %i stateId %i", m_Action.GetType().c_str(), m_Action.GetValueParameterName().c_str(), m_Action.GetValueParameterString().c_str(), m_Action.GetValueParameterDouble(), m_BehaviorId, m_ActionIndex, m_ActionContext.GetStripId(), m_ActionContext.GetStateId()); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h index aa34940b..c53a4d47 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateActionMessage.h @@ -13,14 +13,18 @@ class AMFArrayValue; */ class UpdateActionMessage : public BehaviorMessageBase { public: - UpdateActionMessage(AMFArrayValue* arguments); - int32_t GetActionIndex() const { return actionIndex; }; - ActionContext GetActionContext() const { return actionContext; }; - Action GetAction() const { return action; }; + UpdateActionMessage(const AMFArrayValue& arguments); + + [[nodiscard]] int32_t GetActionIndex() const noexcept { return m_ActionIndex; } + + [[nodiscard]] const ActionContext& GetActionContext() const noexcept { return m_ActionContext; } + + [[nodiscard]] const Action& GetAction() const noexcept { return m_Action; } + private: - int32_t actionIndex; - ActionContext actionContext; - Action action; + int32_t m_ActionIndex; + ActionContext m_ActionContext; + Action m_Action; }; #endif //!__UPDATEACTIONMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp index 05dc7cf7..badb8c7a 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.cpp @@ -1,8 +1,9 @@ #include "UpdateStripUiMessage.h" -UpdateStripUiMessage::UpdateStripUiMessage(AMFArrayValue* arguments) : BehaviorMessageBase(arguments) { - position = StripUiPosition(arguments); - actionContext = ActionContext(arguments); +UpdateStripUiMessage::UpdateStripUiMessage(const AMFArrayValue& arguments) + : BehaviorMessageBase{ arguments } + , m_Position{ arguments } + , m_ActionContext{ arguments } { - LOG_DEBUG("xPosition %f yPosition %f stripId %i stateId %i behaviorId %i", position.GetX(), position.GetY(), actionContext.GetStripId(), actionContext.GetStateId(), behaviorId); + LOG_DEBUG("xPosition %f yPosition %f stripId %i stateId %i behaviorId %i", m_Position.GetX(), m_Position.GetY(), m_ActionContext.GetStripId(), m_ActionContext.GetStateId(), m_BehaviorId); } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h index 0e9afe81..e684fd4a 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/UpdateStripUiMessage.h @@ -13,12 +13,15 @@ class AMFArrayValue; */ class UpdateStripUiMessage : public BehaviorMessageBase { public: - UpdateStripUiMessage(AMFArrayValue* arguments); - StripUiPosition GetPosition() const { return position; }; - ActionContext GetActionContext() const { return actionContext; }; + UpdateStripUiMessage(const AMFArrayValue& arguments); + + [[nodiscard]] const StripUiPosition& GetPosition() const noexcept { return m_Position; }; + + [[nodiscard]] const ActionContext& GetActionContext() const noexcept { return m_ActionContext; }; + private: - StripUiPosition position; - ActionContext actionContext; + StripUiPosition m_Position; + ActionContext m_ActionContext; }; #endif //!__UPDATESTRIPUIMESSAGE__H__ diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.cpp b/dGame/dPropertyBehaviors/ControlBehaviors.cpp index c541257c..2e074409 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviors.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviors.cpp @@ -13,6 +13,7 @@ #include "User.h" #include "tinyxml2.h" #include "CDClientDatabase.h" +#include "CharacterComponent.h" // Message includes #include "Action.h" @@ -62,7 +63,7 @@ void ControlBehaviors::SendBehaviorListToClient(const ControlBehaviorContext& co // TODO This is also supposed to serialize the state of the behaviors in progress but those aren't implemented yet void ControlBehaviors::SendBehaviorBlocksToClient(ControlBehaviorContext& context) { if (!context) return; - BehaviorMessageBase behaviorMsg(context.arguments); + BehaviorMessageBase behaviorMsg{ context.arguments }; context.modelComponent->VerifyBehaviors(); AMFArrayValue behavior; @@ -70,8 +71,8 @@ void ControlBehaviors::SendBehaviorBlocksToClient(ControlBehaviorContext& contex GameMessages::SendUIMessageServerToSingleClient(context.modelOwner, context.modelOwner->GetSystemAddress(), "UpdateBehaviorBlocks", behavior); } -void ControlBehaviors::UpdateAction(AMFArrayValue* arguments) { - UpdateActionMessage updateActionMessage(arguments); +void ControlBehaviors::UpdateAction(const AMFArrayValue& arguments) { + UpdateActionMessage updateActionMessage{ arguments }; auto blockDefinition = GetBlockInfo(updateActionMessage.GetAction().GetType()); if (!blockDefinition) { @@ -94,18 +95,18 @@ void ControlBehaviors::UpdateAction(AMFArrayValue* arguments) { } } -void ControlBehaviors::ProcessCommand(Entity* modelEntity, const SystemAddress& sysAddr, AMFArrayValue* arguments, std::string command, Entity* modelOwner) { - if (!isInitialized || !modelEntity || !modelOwner || !arguments) return; - auto* modelComponent = modelEntity->GetComponent(); +void ControlBehaviors::ProcessCommand(Entity* const modelEntity, const AMFArrayValue& arguments, const std::string& command, Entity* const modelOwner) { + if (!isInitialized || !modelEntity || !modelOwner) return; + auto* const modelComponent = modelEntity->GetComponent(); if (!modelComponent) return; - ControlBehaviorContext context(arguments, modelComponent, modelOwner); + ControlBehaviorContext context{ arguments, modelComponent, modelOwner }; if (command == "sendBehaviorListToClient") { SendBehaviorListToClient(context); } else if (command == "modelTypeChanged") { - auto* modelType = arguments->Get("ModelType"); + const auto* const modelType = arguments.Get("ModelType"); if (!modelType) return; modelEntity->SetVar(u"modelType", modelType->GetValue()); @@ -130,7 +131,7 @@ void ControlBehaviors::ProcessCommand(Entity* modelEntity, const SystemAddress& } else if (command == "rearrangeStrip") { context.modelComponent->HandleControlBehaviorsMsg(arguments); } else if (command == "add") { - AddMessage msg(context.arguments); + AddMessage msg{ context.arguments }; context.modelComponent->AddBehavior(msg); SendBehaviorListToClient(context); } else if (command == "removeActions") { @@ -143,12 +144,14 @@ void ControlBehaviors::ProcessCommand(Entity* modelEntity, const SystemAddress& } else if (command == "sendBehaviorBlocksToClient") { SendBehaviorBlocksToClient(context); } else if (command == "moveToInventory") { - MoveToInventoryMessage msg(arguments); + MoveToInventoryMessage msg{ arguments }; context.modelComponent->MoveToInventory(msg); + auto* characterComponent = modelOwner->GetComponent(); + if (!characterComponent) return; AMFArrayValue args; args.Insert("BehaviorID", std::to_string(msg.GetBehaviorId())); - GameMessages::SendUIMessageServerToSingleClient(modelOwner, modelOwner->GetParentUser()->GetSystemAddress(), "BehaviorRemoved", args); + GameMessages::SendUIMessageServerToSingleClient(modelOwner, characterComponent->GetSystemAddress(), "BehaviorRemoved", args); SendBehaviorListToClient(context); } else if (command == "updateAction") { @@ -236,7 +239,7 @@ ControlBehaviors::ControlBehaviors() { if (values) { auto* value = values->FirstChildElement("Value"); while (value) { - if (value->GetText() == blockDefinition.GetDefaultValue()) blockDefinition.GetDefaultValue() = std::to_string(blockDefinition.GetMaximumValue()); + if (value->GetText() == blockDefinition.GetDefaultValue()) blockDefinition.SetDefaultValue(std::to_string(blockDefinition.GetMaximumValue())); blockDefinition.SetMaximumValue(blockDefinition.GetMaximumValue() + 1); value = value->NextSiblingElement("Value"); } @@ -280,7 +283,7 @@ ControlBehaviors::ControlBehaviors() { } } -std::optional ControlBehaviors::GetBlockInfo(const BlockName& blockName) { +std::optional ControlBehaviors::GetBlockInfo(const std::string& blockName) { auto blockDefinition = blockTypes.find(blockName); return blockDefinition != blockTypes.end() ? std::optional(blockDefinition->second) : std::nullopt; } diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.h b/dGame/dPropertyBehaviors/ControlBehaviors.h index ab739408..f176a070 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviors.h +++ b/dGame/dPropertyBehaviors/ControlBehaviors.h @@ -19,15 +19,17 @@ class SystemAddress; typedef std::string BlockName; //! A block name struct ControlBehaviorContext { - ControlBehaviorContext(AMFArrayValue* args, ModelComponent* modelComponent, Entity* modelOwner) : arguments(args), modelComponent(modelComponent), modelOwner(modelOwner) {}; + ControlBehaviorContext(const AMFArrayValue& args, ModelComponent* modelComponent, Entity* modelOwner) noexcept + : arguments{ args }, modelComponent{ modelComponent }, modelOwner{ modelOwner } { + }; operator bool() const { - return arguments != nullptr && modelComponent != nullptr && modelOwner != nullptr; + return modelComponent != nullptr && modelOwner != nullptr; } - AMFArrayValue* arguments; - Entity* modelOwner; + std::reference_wrapper arguments; ModelComponent* modelComponent; + Entity* modelOwner; }; class ControlBehaviors: public Singleton { @@ -37,12 +39,11 @@ public: * @brief Main driver for processing Property Behavior commands * * @param modelEntity The model that sent this command - * @param sysAddr The SystemAddress to respond to * @param arguments The arguments formatted as an AMFArrayValue * @param command The command to perform * @param modelOwner The owner of the model which sent this command */ - void ProcessCommand(Entity* modelEntity, const SystemAddress& sysAddr, AMFArrayValue* arguments, std::string command, Entity* modelOwner); + void ProcessCommand(Entity* const modelEntity, const AMFArrayValue& arguments, const std::string& command, Entity* const modelOwner); /** * @brief Gets a blocks parameter values by the name @@ -52,13 +53,13 @@ public: * * @return A pair of the block parameter name to its typing */ - std::optional GetBlockInfo(const BlockName& blockName); + [[nodiscard]] std::optional GetBlockInfo(const std::string& blockName); private: void RequestUpdatedID(ControlBehaviorContext& context); void SendBehaviorListToClient(const ControlBehaviorContext& context); void SendBehaviorBlocksToClient(ControlBehaviorContext& context); - void UpdateAction(AMFArrayValue* arguments); - std::map blockTypes{}; + void UpdateAction(const AMFArrayValue& arguments); + std::map> blockTypes{}; // If false, property behaviors will not be able to be edited. bool isInitialized = false; diff --git a/dGame/dPropertyBehaviors/PropertyBehavior.cpp b/dGame/dPropertyBehaviors/PropertyBehavior.cpp index f6f6e4f1..423751c4 100644 --- a/dGame/dPropertyBehaviors/PropertyBehavior.cpp +++ b/dGame/dPropertyBehaviors/PropertyBehavior.cpp @@ -83,10 +83,6 @@ void PropertyBehavior::HandleMsg(AddMessage& msg) { isLoot = m_BehaviorId != 7965; }; -void PropertyBehavior::SetBehaviorId(int32_t behaviorId) { - m_BehaviorId = behaviorId; -} - void PropertyBehavior::SendBehaviorListToClient(AMFArrayValue& args) const { args.Insert("id", std::to_string(m_BehaviorId)); args.Insert("name", m_Name); @@ -111,19 +107,18 @@ void PropertyBehavior::VerifyLastEditedState() { } void PropertyBehavior::SendBehaviorBlocksToClient(AMFArrayValue& args) const { - auto* stateArray = args.InsertArray("states"); + auto* const stateArray = args.InsertArray("states"); - auto lastState = BehaviorState::HOME_STATE; - for (auto& [stateId, state] : m_States) { + for (const auto& [stateId, state] : m_States) { if (state.IsEmpty()) continue; LOG_DEBUG("Serializing state %i", stateId); - auto* stateArgs = stateArray->PushArray(); + auto* const stateArgs = stateArray->PushArray(); stateArgs->Insert("id", static_cast(stateId)); state.SendBehaviorBlocksToClient(*stateArgs); } - auto* executionState = args.InsertArray("executionState"); + auto* const executionState = args.InsertArray("executionState"); executionState->Insert("stateID", static_cast(m_LastEditedState)); executionState->InsertArray("strips"); diff --git a/dGame/dPropertyBehaviors/PropertyBehavior.h b/dGame/dPropertyBehaviors/PropertyBehavior.h index dc53bbed..c9cb4b98 100644 --- a/dGame/dPropertyBehaviors/PropertyBehavior.h +++ b/dGame/dPropertyBehaviors/PropertyBehavior.h @@ -13,7 +13,8 @@ class AMFArrayValue; class PropertyBehavior { public: PropertyBehavior(); - template + + template void HandleMsg(Msg& msg); // If the last edited state has no strips, this method will set the last edited state to the first state that has strips. @@ -21,8 +22,9 @@ public: void SendBehaviorListToClient(AMFArrayValue& args) const; void SendBehaviorBlocksToClient(AMFArrayValue& args) const; - int32_t GetBehaviorId() const { return m_BehaviorId; } - void SetBehaviorId(int32_t id); + [[nodiscard]] int32_t GetBehaviorId() const noexcept { return m_BehaviorId; } + void SetBehaviorId(int32_t id) noexcept { m_BehaviorId = id; } + private: // The states this behavior has. diff --git a/dGame/dPropertyBehaviors/State.cpp b/dGame/dPropertyBehaviors/State.cpp index 59a9aa8b..0c8a11d9 100644 --- a/dGame/dPropertyBehaviors/State.cpp +++ b/dGame/dPropertyBehaviors/State.cpp @@ -3,7 +3,7 @@ #include "Amf3.h" #include "ControlBehaviorMsgs.h" -template<> +template <> void State::HandleMsg(AddStripMessage& msg) { if (m_Strips.size() <= msg.GetActionContext().GetStripId()) { m_Strips.resize(msg.GetActionContext().GetStripId() + 1); @@ -11,7 +11,7 @@ void State::HandleMsg(AddStripMessage& msg) { m_Strips.at(msg.GetActionContext().GetStripId()).HandleMsg(msg); }; -template<> +template <> void State::HandleMsg(AddActionMessage& msg) { if (m_Strips.size() <= msg.GetActionContext().GetStripId()) { return; @@ -20,7 +20,7 @@ void State::HandleMsg(AddActionMessage& msg) { m_Strips.at(msg.GetActionContext().GetStripId()).HandleMsg(msg); }; -template<> +template <> void State::HandleMsg(UpdateStripUiMessage& msg) { if (m_Strips.size() <= msg.GetActionContext().GetStripId()) { return; @@ -29,7 +29,7 @@ void State::HandleMsg(UpdateStripUiMessage& msg) { m_Strips.at(msg.GetActionContext().GetStripId()).HandleMsg(msg); }; -template<> +template <> void State::HandleMsg(RemoveActionsMessage& msg) { if (m_Strips.size() <= msg.GetActionContext().GetStripId()) { return; @@ -38,7 +38,7 @@ void State::HandleMsg(RemoveActionsMessage& msg) { m_Strips.at(msg.GetActionContext().GetStripId()).HandleMsg(msg); }; -template<> +template <> void State::HandleMsg(RearrangeStripMessage& msg) { if (m_Strips.size() <= msg.GetActionContext().GetStripId()) { return; @@ -47,7 +47,7 @@ void State::HandleMsg(RearrangeStripMessage& msg) { m_Strips.at(msg.GetActionContext().GetStripId()).HandleMsg(msg); }; -template<> +template <> void State::HandleMsg(UpdateActionMessage& msg) { if (m_Strips.size() <= msg.GetActionContext().GetStripId()) { return; @@ -56,7 +56,7 @@ void State::HandleMsg(UpdateActionMessage& msg) { m_Strips.at(msg.GetActionContext().GetStripId()).HandleMsg(msg); }; -template<> +template <> void State::HandleMsg(RemoveStripMessage& msg) { if (m_Strips.size() <= msg.GetActionContext().GetStripId()) { return; @@ -65,7 +65,7 @@ void State::HandleMsg(RemoveStripMessage& msg) { m_Strips.at(msg.GetActionContext().GetStripId()).HandleMsg(msg); }; -template<> +template <> void State::HandleMsg(SplitStripMessage& msg) { if (msg.GetTransferredActions().empty()) { if (m_Strips.size() <= msg.GetSourceActionContext().GetStripId()) { @@ -82,7 +82,7 @@ void State::HandleMsg(SplitStripMessage& msg) { } }; -template<> +template <> void State::HandleMsg(MergeStripsMessage& msg) { if (msg.GetMigratedActions().empty()) { if (m_Strips.size() <= msg.GetSourceActionContext().GetStripId()) { @@ -99,7 +99,7 @@ void State::HandleMsg(MergeStripsMessage& msg) { } }; -template<> +template <> void State::HandleMsg(MigrateActionsMessage& msg) { if (msg.GetMigratedActions().empty()) { if (m_Strips.size() <= msg.GetSourceActionContext().GetStripId()) { @@ -117,19 +117,19 @@ void State::HandleMsg(MigrateActionsMessage& msg) { }; bool State::IsEmpty() const { - for (auto& strip : m_Strips) { + for (const auto& strip : m_Strips) { if (!strip.IsEmpty()) return false; } return true; } void State::SendBehaviorBlocksToClient(AMFArrayValue& args) const { - auto* strips = args.InsertArray("strips"); - for (int32_t stripId = 0; stripId < m_Strips.size(); stripId++) { - auto& strip = m_Strips.at(stripId); + auto* const strips = args.InsertArray("strips"); + for (size_t stripId = 0; stripId < m_Strips.size(); ++stripId) { + const auto& strip = m_Strips.at(stripId); if (strip.IsEmpty()) continue; - auto* stripArgs = strips->PushArray(); + auto* const stripArgs = strips->PushArray(); stripArgs->Insert("id", static_cast(stripId)); strip.SendBehaviorBlocksToClient(*stripArgs); diff --git a/dGame/dPropertyBehaviors/State.h b/dGame/dPropertyBehaviors/State.h index a6a6d23b..f0425763 100644 --- a/dGame/dPropertyBehaviors/State.h +++ b/dGame/dPropertyBehaviors/State.h @@ -7,11 +7,12 @@ class AMFArrayValue; class State { public: - template + template void HandleMsg(Msg& msg); void SendBehaviorBlocksToClient(AMFArrayValue& args) const; bool IsEmpty() const; + private: std::vector m_Strips; }; diff --git a/dGame/dPropertyBehaviors/Strip.cpp b/dGame/dPropertyBehaviors/Strip.cpp index 7d27cacd..0f459e46 100644 --- a/dGame/dPropertyBehaviors/Strip.cpp +++ b/dGame/dPropertyBehaviors/Strip.cpp @@ -3,48 +3,47 @@ #include "Amf3.h" #include "ControlBehaviorMsgs.h" -template<> +template <> void Strip::HandleMsg(AddStripMessage& msg) { m_Actions = msg.GetActionsToAdd(); m_Position = msg.GetPosition(); }; -template<> +template <> void Strip::HandleMsg(AddActionMessage& msg) { if (msg.GetActionIndex() == -1) return; - m_Actions.insert(m_Actions.begin() + msg.GetActionIndex(), msg.GetAction()); }; -template<> +template <> void Strip::HandleMsg(UpdateStripUiMessage& msg) { m_Position = msg.GetPosition(); }; -template<> +template <> void Strip::HandleMsg(RemoveStripMessage& msg) { m_Actions.clear(); }; -template<> +template <> void Strip::HandleMsg(RemoveActionsMessage& msg) { if (msg.GetActionIndex() >= m_Actions.size()) return; m_Actions.erase(m_Actions.begin() + msg.GetActionIndex(), m_Actions.end()); }; -template<> +template <> void Strip::HandleMsg(UpdateActionMessage& msg) { if (msg.GetActionIndex() >= m_Actions.size()) return; m_Actions.at(msg.GetActionIndex()) = msg.GetAction(); }; -template<> +template <> void Strip::HandleMsg(RearrangeStripMessage& msg) { if (msg.GetDstActionIndex() >= m_Actions.size() || msg.GetSrcActionIndex() >= m_Actions.size() || msg.GetSrcActionIndex() <= msg.GetDstActionIndex()) return; std::rotate(m_Actions.begin() + msg.GetDstActionIndex(), m_Actions.begin() + msg.GetSrcActionIndex(), m_Actions.end()); }; -template<> +template <> void Strip::HandleMsg(SplitStripMessage& msg) { if (msg.GetTransferredActions().empty() && !m_Actions.empty()) { auto startToMove = m_Actions.begin() + msg.GetSrcActionIndex(); @@ -56,7 +55,7 @@ void Strip::HandleMsg(SplitStripMessage& msg) { } }; -template<> +template <> void Strip::HandleMsg(MergeStripsMessage& msg) { if (msg.GetMigratedActions().empty() && !m_Actions.empty()) { msg.SetMigratedActions(m_Actions.begin(), m_Actions.end()); @@ -66,7 +65,7 @@ void Strip::HandleMsg(MergeStripsMessage& msg) { } }; -template<> +template <> void Strip::HandleMsg(MigrateActionsMessage& msg) { if (msg.GetMigratedActions().empty() && !m_Actions.empty()) { auto startToMove = m_Actions.begin() + msg.GetSrcActionIndex(); @@ -80,8 +79,8 @@ void Strip::HandleMsg(MigrateActionsMessage& msg) { void Strip::SendBehaviorBlocksToClient(AMFArrayValue& args) const { m_Position.SendBehaviorBlocksToClient(args); - auto* actions = args.InsertArray("actions"); - for (auto& action : m_Actions) { + auto* const actions = args.InsertArray("actions"); + for (const auto& action : m_Actions) { action.SendBehaviorBlocksToClient(*actions); } }; diff --git a/dGame/dPropertyBehaviors/Strip.h b/dGame/dPropertyBehaviors/Strip.h index f3e10964..107fee11 100644 --- a/dGame/dPropertyBehaviors/Strip.h +++ b/dGame/dPropertyBehaviors/Strip.h @@ -10,11 +10,12 @@ class AMFArrayValue; class Strip { public: - template + template void HandleMsg(Msg& msg); void SendBehaviorBlocksToClient(AMFArrayValue& args) const; - bool IsEmpty() const { return m_Actions.empty(); } + bool IsEmpty() const noexcept { return m_Actions.empty(); } + private: std::vector m_Actions; StripUiPosition m_Position; diff --git a/dGame/dUtilities/CMakeLists.txt b/dGame/dUtilities/CMakeLists.txt index 055cc706..1e54b59b 100644 --- a/dGame/dUtilities/CMakeLists.txt +++ b/dGame/dUtilities/CMakeLists.txt @@ -8,8 +8,18 @@ set(DGAME_DUTILITIES_SOURCES "BrickDatabase.cpp" "SlashCommandHandler.cpp" "VanityUtilities.cpp") -add_library(dUtilities STATIC ${DGAME_DUTILITIES_SOURCES}) +add_library(dUtilities OBJECT ${DGAME_DUTILITIES_SOURCES}) target_precompile_headers(dUtilities REUSE_FROM dGameBase) +target_include_directories(dUtilities PUBLIC "." + PRIVATE + "${PROJECT_SOURCE_DIR}/dGame/dComponents" + "${PROJECT_SOURCE_DIR}/dGame/dInventory" # transitive via PossessableComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dGameMessages" + "${PROJECT_SOURCE_DIR}/dGame/dBehaviors" # transitive via InventoryComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dMission" # transitive via MissionComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dEntity" # transitive via dZoneManager/Spawner.h + "${PROJECT_SOURCE_DIR}/dZoneManager" # Mail.cpp +) target_link_libraries(dUtilities PUBLIC dDatabase dPhysics INTERFACE dZoneManager) diff --git a/dGame/dUtilities/CheatDetection.cpp b/dGame/dUtilities/CheatDetection.cpp index bc50b2cc..a87157a1 100644 --- a/dGame/dUtilities/CheatDetection.cpp +++ b/dGame/dUtilities/CheatDetection.cpp @@ -2,7 +2,6 @@ #include "Database.h" #include "Entity.h" #include "PossessableComponent.h" -#include "Player.h" #include "Game.h" #include "EntityManager.h" #include "Character.h" @@ -59,13 +58,13 @@ void LogAndSaveFailedAntiCheatCheck(const LWOOBJID& id, const SystemAddress& sys player->GetCharacter()->GetName().c_str(), player->GetObjectID(), sysAddr.ToString(), entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); - toReport = player->GetParentUser(); + if (player->GetCharacter()) toReport = player->GetCharacter()->GetParentUser(); // In the case that the target entity id did not exist, just log the player info. } else if (player) { LOG("Player (%s) (%llu) at system address (%s) with sending player (%llu) does not match their own.", player->GetCharacter()->GetName().c_str(), player->GetObjectID(), sysAddr.ToString(), id); - toReport = player->GetParentUser(); + if (player->GetCharacter()) toReport = player->GetCharacter()->GetParentUser(); // In the rare case that the player does not exist, just log the system address and who the target id was. } else { LOG("Player at system address (%s) with sending player (%llu) does not match their own.", diff --git a/dGame/dUtilities/GUID.cpp b/dGame/dUtilities/GUID.cpp index 50ac8b03..ac4042a0 100644 --- a/dGame/dUtilities/GUID.cpp +++ b/dGame/dUtilities/GUID.cpp @@ -13,12 +13,12 @@ GUID::GUID(const std::string& guid) { &this->data4[4], &this->data4[5], &this->data4[6], &this->data4[7]); } -void GUID::Serialize(RakNet::BitStream* outBitStream) { - outBitStream->Write(GetData1()); - outBitStream->Write(GetData2()); - outBitStream->Write(GetData3()); +void GUID::Serialize(RakNet::BitStream& outBitStream) { + outBitStream.Write(GetData1()); + outBitStream.Write(GetData2()); + outBitStream.Write(GetData3()); for (const auto& guidSubPart : GetData4()) { - outBitStream->Write(guidSubPart); + outBitStream.Write(guidSubPart); } } diff --git a/dGame/dUtilities/GUID.h b/dGame/dUtilities/GUID.h index 38e57a6a..ce6d40c1 100644 --- a/dGame/dUtilities/GUID.h +++ b/dGame/dUtilities/GUID.h @@ -7,7 +7,7 @@ class GUID { public: explicit GUID(); explicit GUID(const std::string& guid); - void Serialize(RakNet::BitStream* outBitStream); + void Serialize(RakNet::BitStream& outBitStream); uint32_t GetData1() const { return data1; diff --git a/dGame/dUtilities/Loot.cpp b/dGame/dUtilities/Loot.cpp index 25c81e74..b2f96ac3 100644 --- a/dGame/dUtilities/Loot.cpp +++ b/dGame/dUtilities/Loot.cpp @@ -28,11 +28,11 @@ void Loot::CacheMatrix(uint32_t matrixIndex) { return; } CachedMatrices.insert(matrixIndex); - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance().GetTable(); - CDLootTableTable* lootTableTable = CDClientManager::Instance().GetTable(); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + CDLootMatrixTable* lootMatrixTable = CDClientManager::GetTable(); + CDLootTableTable* lootTableTable = CDClientManager::GetTable(); + CDRarityTableTable* rarityTableTable = CDClientManager::GetTable(); const auto& matrix = lootMatrixTable->GetMatrix(matrixIndex); @@ -47,11 +47,11 @@ void Loot::CacheMatrix(uint32_t matrixIndex) { } std::unordered_map Loot::RollLootMatrix(Entity* player, uint32_t matrixIndex) { - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance().GetTable(); - CDLootTableTable* lootTableTable = CDClientManager::Instance().GetTable(); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + CDLootMatrixTable* lootMatrixTable = CDClientManager::GetTable(); + CDLootTableTable* lootTableTable = CDClientManager::GetTable(); + CDRarityTableTable* rarityTableTable = CDClientManager::GetTable(); auto* missionComponent = player->GetComponent(); std::unordered_map drops; @@ -134,11 +134,11 @@ std::unordered_map Loot::RollLootMatrix(Entity* player, uint32_t m } std::unordered_map Loot::RollLootMatrix(uint32_t matrixIndex) { - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance().GetTable(); - CDLootTableTable* lootTableTable = CDClientManager::Instance().GetTable(); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + CDLootMatrixTable* lootMatrixTable = CDClientManager::GetTable(); + CDLootTableTable* lootTableTable = CDClientManager::GetTable(); + CDRarityTableTable* rarityTableTable = CDClientManager::GetTable(); std::unordered_map drops; const auto& matrix = lootMatrixTable->GetMatrix(matrixIndex); @@ -216,7 +216,7 @@ void Loot::GiveLoot(Entity* player, std::unordered_map& result, eL } void Loot::GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating) { - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance().GetTable(); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); const CDActivityRewards* selectedReward = nullptr; @@ -232,7 +232,7 @@ void Loot::GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, uint32_t minCoins = 0; uint32_t maxCoins = 0; - CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance().GetTable(); + CDCurrencyTableTable* currencyTableTable = CDClientManager::GetTable(); std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); if (currencyTable.size() > 0) { @@ -286,7 +286,7 @@ void Loot::DropLoot(Entity* player, Entity* killedObject, std::unordered_map(); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); const CDActivityRewards* selectedReward = nullptr; @@ -303,7 +303,7 @@ void Loot::DropActivityLoot(Entity* player, Entity* source, uint32_t activityID, uint32_t minCoins = 0; uint32_t maxCoins = 0; - CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance().GetTable(); + CDCurrencyTableTable* currencyTableTable = CDClientManager::GetTable(); std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); if (currencyTable.size() > 0) { diff --git a/dGame/dUtilities/Loot.h b/dGame/dUtilities/Loot.h index dacd3dcd..ac4d5233 100644 --- a/dGame/dUtilities/Loot.h +++ b/dGame/dUtilities/Loot.h @@ -1,6 +1,7 @@ #pragma once #include "dCommonVars.h" +#include "eLootSourceType.h" #include class Entity; diff --git a/dGame/dUtilities/Mail.cpp b/dGame/dUtilities/Mail.cpp index fc0c833e..a610c3a7 100644 --- a/dGame/dUtilities/Mail.cpp +++ b/dGame/dUtilities/Mail.cpp @@ -95,39 +95,39 @@ void Mail::SendMail(const LWOOBJID sender, const std::string& senderName, LWOOBJ } //Because we need it: -std::string ReadWStringAsString(RakNet::BitStream* bitStream, uint32_t size) { +std::string ReadWStringAsString(RakNet::BitStream& bitStream, uint32_t size) { std::string toReturn = ""; uint8_t buffer; bool isFinishedReading = false; for (uint32_t i = 0; i < size; ++i) { - bitStream->Read(buffer); + bitStream.Read(buffer); if (!isFinishedReading) toReturn.push_back(buffer); if (buffer == '\0') isFinishedReading = true; //so we don't continue to read garbage as part of the string. - bitStream->Read(buffer); //Read the null term + bitStream.Read(buffer); //Read the null term } return toReturn; } -void WriteStringAsWString(RakNet::BitStream* bitStream, std::string str, uint32_t size) { +void WriteStringAsWString(RakNet::BitStream& bitStream, std::string str, uint32_t size) { uint32_t sizeToFill = size - str.size(); for (uint32_t i = 0; i < str.size(); ++i) { - bitStream->Write(str[i]); - bitStream->Write(uint8_t(0)); + bitStream.Write(str[i]); + bitStream.Write(uint8_t(0)); } for (uint32_t i = 0; i < sizeToFill; ++i) { - bitStream->Write(uint16_t(0)); + bitStream.Write(uint16_t(0)); } } -void Mail::HandleMailStuff(RakNet::BitStream* packet, const SystemAddress& sysAddr, Entity* entity) { +void Mail::HandleMailStuff(RakNet::BitStream& packet, const SystemAddress& sysAddr, Entity* entity) { int mailStuffID = 0; - packet->Read(mailStuffID); + packet.Read(mailStuffID); - auto returnVal = std::async(std::launch::async, [packet, &sysAddr, entity, mailStuffID]() { + auto returnVal = std::async(std::launch::async, [&packet, &sysAddr, entity, mailStuffID]() { Mail::MailMessageID stuffID = MailMessageID(mailStuffID); switch (stuffID) { case MailMessageID::AttachmentCollect: @@ -154,7 +154,7 @@ void Mail::HandleMailStuff(RakNet::BitStream* packet, const SystemAddress& sysAd }); } -void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAddr, Entity* entity) { +void Mail::HandleSendMail(RakNet::BitStream& packet, const SystemAddress& sysAddr, Entity* entity) { //std::string subject = GeneralUtils::WStringToString(ReadFromPacket(packet, 50)); //std::string body = GeneralUtils::WStringToString(ReadFromPacket(packet, 400)); //std::string recipient = GeneralUtils::WStringToString(ReadFromPacket(packet, 32)); @@ -186,9 +186,9 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd LWOOBJID attachmentID; uint16_t attachmentCount; - packet->Read(unknown64); - packet->Read(attachmentID); - packet->Read(attachmentCount); //We don't care about the rest of the packet. + packet.Read(unknown64); + packet.Read(attachmentID); + packet.Read(attachmentCount); //We don't care about the rest of the packet. uint32_t itemID = static_cast(attachmentID); LOT itemLOT = 0; //Inventory::InventoryType itemType; @@ -261,7 +261,7 @@ void Mail::HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAdd character->SaveXMLToDatabase(); } -void Mail::HandleDataRequest(RakNet::BitStream* packet, const SystemAddress& sysAddr, Entity* player) { +void Mail::HandleDataRequest(RakNet::BitStream& packet, const SystemAddress& sysAddr, Entity* player) { auto playerMail = Database::Get()->GetMailForPlayer(player->GetCharacter()->GetID(), 20); RakNet::BitStream bitStream; @@ -275,9 +275,9 @@ void Mail::HandleDataRequest(RakNet::BitStream* packet, const SystemAddress& sys for (const auto& mail : playerMail) { bitStream.Write(mail.id); //MailID - WriteStringAsWString(&bitStream, mail.subject.c_str(), 50); //subject - WriteStringAsWString(&bitStream, mail.body.c_str(), 400); //body - WriteStringAsWString(&bitStream, mail.senderUsername.c_str(), 32); //sender + WriteStringAsWString(bitStream, mail.subject.c_str(), 50); //subject + WriteStringAsWString(bitStream, mail.body.c_str(), 400); //body + WriteStringAsWString(bitStream, mail.senderUsername.c_str(), 32); //sender bitStream.Write(uint32_t(0)); bitStream.Write(uint64_t(0)); @@ -303,16 +303,16 @@ void Mail::HandleDataRequest(RakNet::BitStream* packet, const SystemAddress& sys bitStream.Write(uint32_t(0)); } - Game::server->Send(&bitStream, sysAddr, false); + Game::server->Send(bitStream, sysAddr, false); } -void Mail::HandleAttachmentCollect(RakNet::BitStream* packet, const SystemAddress& sysAddr, Entity* player) { +void Mail::HandleAttachmentCollect(RakNet::BitStream& packet, const SystemAddress& sysAddr, Entity* player) { int unknown; uint64_t mailID; LWOOBJID playerID; - packet->Read(unknown); - packet->Read(mailID); - packet->Read(playerID); + packet.Read(unknown); + packet.Read(mailID); + packet.Read(playerID); if (mailID > 0 && playerID == player->GetObjectID()) { auto playerMail = Database::Get()->GetMail(mailID); @@ -336,22 +336,22 @@ void Mail::HandleAttachmentCollect(RakNet::BitStream* packet, const SystemAddres } } -void Mail::HandleMailDelete(RakNet::BitStream* packet, const SystemAddress& sysAddr) { +void Mail::HandleMailDelete(RakNet::BitStream& packet, const SystemAddress& sysAddr) { int unknown; uint64_t mailID; LWOOBJID playerID; - packet->Read(unknown); - packet->Read(mailID); - packet->Read(playerID); + packet.Read(unknown); + packet.Read(mailID); + packet.Read(playerID); if (mailID > 0) Mail::SendDeleteConfirm(sysAddr, mailID, playerID); } -void Mail::HandleMailRead(RakNet::BitStream* packet, const SystemAddress& sysAddr) { +void Mail::HandleMailRead(RakNet::BitStream& packet, const SystemAddress& sysAddr) { int unknown; uint64_t mailID; - packet->Read(unknown); - packet->Read(mailID); + packet.Read(unknown); + packet.Read(mailID); if (mailID > 0) Mail::SendReadConfirm(sysAddr, mailID); } @@ -367,7 +367,7 @@ void Mail::SendSendResponse(const SystemAddress& sysAddr, MailSendResponse respo BitStreamUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::MAIL); bitStream.Write(int(MailMessageID::SendResponse)); bitStream.Write(int(response)); - Game::server->Send(&bitStream, sysAddr, false); + Game::server->Send(bitStream, sysAddr, false); } void Mail::SendNotification(const SystemAddress& sysAddr, int mailCount) { @@ -386,7 +386,7 @@ void Mail::SendNotification(const SystemAddress& sysAddr, int mailCount) { bitStream.Write(s4); bitStream.Write(mailCount); bitStream.Write(int(0)); //Unknown - Game::server->Send(&bitStream, sysAddr, false); + Game::server->Send(bitStream, sysAddr, false); } void Mail::SendAttachmentRemoveConfirm(const SystemAddress& sysAddr, uint64_t mailID) { @@ -395,7 +395,7 @@ void Mail::SendAttachmentRemoveConfirm(const SystemAddress& sysAddr, uint64_t ma bitStream.Write(int(MailMessageID::AttachmentCollectConfirm)); bitStream.Write(int(0)); //unknown bitStream.Write(mailID); - Game::server->Send(&bitStream, sysAddr, false); + Game::server->Send(bitStream, sysAddr, false); } void Mail::SendDeleteConfirm(const SystemAddress& sysAddr, uint64_t mailID, LWOOBJID playerID) { @@ -404,7 +404,7 @@ void Mail::SendDeleteConfirm(const SystemAddress& sysAddr, uint64_t mailID, LWOO bitStream.Write(int(MailMessageID::MailDeleteConfirm)); bitStream.Write(int(0)); //unknown bitStream.Write(mailID); - Game::server->Send(&bitStream, sysAddr, false); + Game::server->Send(bitStream, sysAddr, false); Database::Get()->DeleteMail(mailID); } @@ -415,7 +415,7 @@ void Mail::SendReadConfirm(const SystemAddress& sysAddr, uint64_t mailID) { bitStream.Write(int(MailMessageID::MailReadConfirm)); bitStream.Write(int(0)); //unknown bitStream.Write(mailID); - Game::server->Send(&bitStream, sysAddr, false); + Game::server->Send(bitStream, sysAddr, false); Database::Get()->MarkMailRead(mailID); } diff --git a/dGame/dUtilities/Mail.h b/dGame/dUtilities/Mail.h index c8eabe6b..07c3e37f 100644 --- a/dGame/dUtilities/Mail.h +++ b/dGame/dUtilities/Mail.h @@ -79,12 +79,12 @@ namespace Mail { const SystemAddress& sysAddr ); - void HandleMailStuff(RakNet::BitStream* packet, const SystemAddress& sysAddr, Entity* entity); - void HandleSendMail(RakNet::BitStream* packet, const SystemAddress& sysAddr, Entity* entity); - void HandleDataRequest(RakNet::BitStream* packet, const SystemAddress& sysAddr, Entity* player); - void HandleAttachmentCollect(RakNet::BitStream* packet, const SystemAddress& sysAddr, Entity* player); - void HandleMailDelete(RakNet::BitStream* packet, const SystemAddress& sysAddr); - void HandleMailRead(RakNet::BitStream* packet, const SystemAddress& sysAddr); + void HandleMailStuff(RakNet::BitStream& packet, const SystemAddress& sysAddr, Entity* entity); + void HandleSendMail(RakNet::BitStream& packet, const SystemAddress& sysAddr, Entity* entity); + void HandleDataRequest(RakNet::BitStream& packet, const SystemAddress& sysAddr, Entity* player); + void HandleAttachmentCollect(RakNet::BitStream& packet, const SystemAddress& sysAddr, Entity* player); + void HandleMailDelete(RakNet::BitStream& packet, const SystemAddress& sysAddr); + void HandleMailRead(RakNet::BitStream& packet, const SystemAddress& sysAddr); void HandleNotificationRequest(const SystemAddress& sysAddr, uint32_t objectID); void SendSendResponse(const SystemAddress& sysAddr, MailSendResponse response); diff --git a/dGame/dUtilities/Preconditions.cpp b/dGame/dUtilities/Preconditions.cpp index 12059b5b..bd855962 100644 --- a/dGame/dUtilities/Preconditions.cpp +++ b/dGame/dUtilities/Preconditions.cpp @@ -40,10 +40,8 @@ Precondition::Precondition(const uint32_t condition) { std::string token; while (std::getline(stream, token, ',')) { - uint32_t value; - if (GeneralUtils::TryParse(token, value)) { - this->values.push_back(value); - } + const auto validToken = GeneralUtils::TryParse(token); + if (validToken) this->values.push_back(validToken.value()); } } diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 7c1a4867..7e314a3f 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -53,7 +53,6 @@ #include "Loot.h" #include "EntityInfo.h" #include "LUTriggers.h" -#include "Player.h" #include "PhantomPhysicsComponent.h" #include "ProximityMonitorComponent.h" #include "dpShapeSphere.h" @@ -88,6 +87,7 @@ #include "CDObjectsTable.h" #include "CDZoneTableTable.h" #include "ePlayerFlag.h" +#include "dNavMesh.h" void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entity* entity, const SystemAddress& sysAddr) { auto commandCopy = command; @@ -113,13 +113,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "setgmlevel" || chatCommand == "makegm" || chatCommand == "gmlevel") && user->GetMaxGMLevel() > eGameMasterLevel::CIVILIAN) { if (args.size() != 1) return; - uint32_t level_intermed = 0; + const auto level_intermed = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], level_intermed)) { + if (!level_intermed) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid gm level."); return; } - eGameMasterLevel level = static_cast(level_intermed); + eGameMasterLevel level = static_cast(level_intermed.value()); #ifndef DEVELOPER_SERVER if (user->GetMaxGMLevel() == eGameMasterLevel::JUNIOR_DEVELOPER) { @@ -396,26 +396,27 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "resetmission" && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - uint32_t missionId; - if (!GeneralUtils::TryParse(args[0], missionId)) { + const auto missionId = GeneralUtils::TryParse(args[0]); + if (!missionId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission ID."); return; } auto* missionComponent = entity->GetComponent(); if (!missionComponent) return; - missionComponent->ResetMission(missionId); + missionComponent->ResetMission(missionId.value()); } // Log command to database Database::Get()->InsertSlashCommandUsage(entity->GetObjectID(), chatCommand); if (chatCommand == "setminifig" && args.size() == 2 && entity->GetGMLevel() >= eGameMasterLevel::FORUM_MODERATOR) { // could break characters so only allow if GM > 0 - int32_t minifigItemId; - if (!GeneralUtils::TryParse(args[1], minifigItemId)) { + const auto minifigItemIdExists = GeneralUtils::TryParse(args[1]); + if (!minifigItemIdExists) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid Minifig Item Id ID."); return; } + const int32_t minifigItemId = minifigItemIdExists.value(); Game::entityManager->DestructEntity(entity, sysAddr); auto* charComp = entity->GetComponent(); std::string lowerName = args[0]; @@ -475,14 +476,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "unlock-emote" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - int32_t emoteID; + const auto emoteID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], emoteID)) { + if (!emoteID) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid emote ID."); return; } - entity->GetCharacter()->UnlockEmote(emoteID); + entity->GetCharacter()->UnlockEmote(emoteID.value()); } if (chatCommand == "force-save" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { @@ -504,19 +505,19 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "speedboost" && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - float boost; - - if (!GeneralUtils::TryParse(args[0], boost)) { + const auto boostOptional = GeneralUtils::TryParse(args[0]); + if (!boostOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid boost."); return; } + const float boost = boostOptional.value(); auto* controllablePhysicsComponent = entity->GetComponent(); if (!controllablePhysicsComponent) return; controllablePhysicsComponent->SetSpeedMultiplier(boost); - // speedboost possesables + // speedboost possessables auto possessor = entity->GetComponent(); if (possessor) { auto possessedID = possessor->GetPossessable(); @@ -545,14 +546,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "setcontrolscheme" && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - uint32_t scheme; + const auto scheme = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], scheme)) { + if (!scheme) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid control scheme."); return; } - GameMessages::SendSetPlayerControlScheme(entity, static_cast(scheme)); + GameMessages::SendSetPlayerControlScheme(entity, static_cast(scheme.value())); ChatPackets::SendSystemMessage(sysAddr, u"Switched control scheme."); return; @@ -592,29 +593,28 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if ((chatCommand == "setinventorysize" || chatCommand == "setinvsize") && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { - uint32_t size; - - if (!GeneralUtils::TryParse(args.at(0), size)) { + const auto sizeOptional = GeneralUtils::TryParse(args[0]); + if (!sizeOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid size."); return; } + const uint32_t size = sizeOptional.value(); eInventoryType selectedInventory = eInventoryType::ITEMS; // a possible inventory was provided if we got more than 1 argument if (args.size() >= 2) { - selectedInventory = eInventoryType::INVALID; - if (!GeneralUtils::TryParse(args.at(1), selectedInventory)) { + selectedInventory = GeneralUtils::TryParse(args.at(1)).value_or(eInventoryType::INVALID); + if (selectedInventory == eInventoryType::INVALID) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid inventory."); + return; + } else { // In this case, we treat the input as a string and try to find it in the reflection list std::transform(args.at(1).begin(), args.at(1).end(), args.at(1).begin(), ::toupper); for (uint32_t index = 0; index < NUMBER_OF_INVENTORIES; index++) { if (std::string_view(args.at(1)) == std::string_view(InventoryType::InventoryTypeToString(static_cast(index)))) selectedInventory = static_cast(index); } } - if (selectedInventory == eInventoryType::INVALID) { - ChatPackets::SendSystemMessage(sysAddr, u"Invalid inventory."); - return; - } ChatPackets::SendSystemMessage(sysAddr, u"Setting inventory " + GeneralUtils::ASCIIToUTF16(args.at(1)) + @@ -649,6 +649,9 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (infile.good()) { std::string line; while (std::getline(infile, line)) { + // Do this in two separate calls to catch both \n and \r\n + line.erase(std::remove(line.begin(), line.end(), '\n'), line.end()); + line.erase(std::remove(line.begin(), line.end(), '\r'), line.end()); SlashCommandHandler::HandleChatCommand(GeneralUtils::ASCIIToUTF16(line), entity, sysAddr); } } else { @@ -661,48 +664,48 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "addmission" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 0) return; - uint32_t missionID; + const auto missionID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], missionID)) { + if (!missionID) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission id."); return; } auto comp = static_cast(entity->GetComponent(eReplicaComponentType::MISSION)); - if (comp) comp->AcceptMission(missionID, true); + if (comp) comp->AcceptMission(missionID.value(), true); return; } if (chatCommand == "completemission" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 0) return; - uint32_t missionID; + const auto missionID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], missionID)) { + if (!missionID) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission id."); return; } auto comp = static_cast(entity->GetComponent(eReplicaComponentType::MISSION)); - if (comp) comp->CompleteMission(missionID, true); + if (comp) comp->CompleteMission(missionID.value(), true); return; } if (chatCommand == "setflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - int32_t flagId; + const auto flagId = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], flagId)) { + if (!flagId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } - entity->GetCharacter()->SetPlayerFlag(flagId, true); + entity->GetCharacter()->SetPlayerFlag(flagId.value(), true); } if (chatCommand == "setflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 2) { - int32_t flagId; - std::string onOffFlag = args[0]; - if (!GeneralUtils::TryParse(args[1], flagId)) { + const auto flagId = GeneralUtils::TryParse(args.at(1)); + std::string onOffFlag = args.at(0); + if (!flagId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } @@ -710,28 +713,26 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag type."); return; } - entity->GetCharacter()->SetPlayerFlag(flagId, onOffFlag == "on"); + entity->GetCharacter()->SetPlayerFlag(flagId.value(), onOffFlag == "on"); } if (chatCommand == "clearflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - int32_t flagId; + const auto flagId = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], flagId)) { + if (!flagId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } - entity->GetCharacter()->SetPlayerFlag(flagId, false); + entity->GetCharacter()->SetPlayerFlag(flagId.value(), false); } if (chatCommand == "playeffect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 3) { - int32_t effectID = 0; + const auto effectID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], effectID)) { - return; - } + if (!effectID) return; // FIXME: use fallible ASCIIToUTF16 conversion, because non-ascii isn't valid anyway - GameMessages::SendPlayFXEffect(entity->GetObjectID(), effectID, GeneralUtils::ASCIIToUTF16(args[1]), args[2]); + GameMessages::SendPlayFXEffect(entity->GetObjectID(), effectID.value(), GeneralUtils::ASCIIToUTF16(args.at(1)), args.at(2)); } if (chatCommand == "stopeffect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { @@ -774,7 +775,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit //Tell the master server that we're going to be shutting down whole "universe": CBITSTREAM; BitStreamUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::SHUTDOWN_UNIVERSE); - Game::server->SendToMaster(&bitStream); + Game::server->SendToMaster(bitStream); ChatPackets::SendSystemMessage(sysAddr, u"Sent universe shutdown notification to master."); //Tell chat to send an announcement to all servers @@ -786,41 +787,39 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto control = static_cast(entity->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (!control) return; - float y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(control->GetPosition()); + float y = dpWorld::GetNavMesh()->GetHeightAtPoint(control->GetPosition()); std::u16string msg = u"Navmesh height: " + (GeneralUtils::to_u16string(y)); ChatPackets::SendSystemMessage(sysAddr, msg); } if (chatCommand == "gmadditem" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 1) { - uint32_t itemLOT; + const auto itemLOT = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], itemLOT)) { + if (!itemLOT) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item LOT."); return; } InventoryComponent* inventory = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); - inventory->AddItem(itemLOT, 1, eLootSourceType::MODERATION); + inventory->AddItem(itemLOT.value(), 1, eLootSourceType::MODERATION); } else if (args.size() == 2) { - uint32_t itemLOT; - - if (!GeneralUtils::TryParse(args[0], itemLOT)) { + const auto itemLOT = GeneralUtils::TryParse(args.at(0)); + if (!itemLOT) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item LOT."); return; } - uint32_t count; - - if (!GeneralUtils::TryParse(args[1], count)) { + const auto count = GeneralUtils::TryParse(args.at(1)); + if (!count) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item count."); return; } InventoryComponent* inventory = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); - inventory->AddItem(itemLOT, count, eLootSourceType::MODERATION); + inventory->AddItem(itemLOT.value(), count.value(), eLootSourceType::MODERATION); } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /gmadditem "); } @@ -840,9 +839,9 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit receiverID = playerInfo->id; - LOT lot; + const auto lot = GeneralUtils::TryParse(args.at(1)); - if (!GeneralUtils::TryParse(args[1], lot)) { + if (!lot) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item lot."); return; } @@ -855,7 +854,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit mailInsert.subject = "Lost item"; mailInsert.body = "This is a replacement item for one you lost."; mailInsert.itemID = LWOOBJID_EMPTY; - mailInsert.itemLOT = lot; + mailInsert.itemLOT = lot.value(); mailInsert.itemSubkey = LWOOBJID_EMPTY; mailInsert.itemCount = 1; Database::Get()->InsertNewMail(mailInsert); @@ -889,46 +888,47 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit NiPoint3 pos{}; if (args.size() == 3) { - float x, y, z; - - if (!GeneralUtils::TryParse(args[0], x)) { + const auto x = GeneralUtils::TryParse(args.at(0)); + if (!x) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid x."); return; } - if (!GeneralUtils::TryParse(args[1], y)) { + const auto y = GeneralUtils::TryParse(args.at(1)); + if (!y) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid y."); return; } - if (!GeneralUtils::TryParse(args[2], z)) { + const auto z = GeneralUtils::TryParse(args.at(2)); + if (!z) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid z."); return; } - pos.SetX(x); - pos.SetY(y); - pos.SetZ(z); + pos.SetX(x.value()); + pos.SetY(y.value()); + pos.SetZ(z.value()); LOG("Teleporting objectID: %llu to %f, %f, %f", entity->GetObjectID(), pos.x, pos.y, pos.z); GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); } else if (args.size() == 2) { - float x, z; - - if (!GeneralUtils::TryParse(args[0], x)) { + const auto x = GeneralUtils::TryParse(args.at(0)); + if (!x) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid x."); return; } - if (!GeneralUtils::TryParse(args[1], z)) { + const auto z = GeneralUtils::TryParse(args.at(1)); + if (!z) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid z."); return; } - pos.SetX(x); + pos.SetX(x.value()); pos.SetY(0.0f); - pos.SetZ(z); + pos.SetZ(z.value()); LOG("Teleporting objectID: %llu to X: %f, Z: %f", entity->GetObjectID(), pos.x, pos.z); GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); @@ -988,10 +988,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit float speedScale = 1.0f; if (args.size() >= 1) { - float tempScaleStore; + const auto tempScaleStore = GeneralUtils::TryParse(args.at(0)); - if (GeneralUtils::TryParse(args[0], tempScaleStore)) { - speedScale = tempScaleStore; + if (tempScaleStore) { + speedScale = tempScaleStore.value(); } else { ChatPackets::SendSystemMessage(sysAddr, u"Failed to parse speed scale argument."); } @@ -1034,23 +1034,26 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } } else { - accountId = player->GetParentUser()->GetAccountID(); + auto* character = player->GetCharacter(); + auto* user = character != nullptr ? character->GetParentUser() : nullptr; + if (user) accountId = user->GetAccountID(); characterId = player->GetObjectID(); } time_t expire = 1; // Default to indefinate mute if (args.size() >= 2) { - uint32_t days = 0; - uint32_t hours = 0; - if (!GeneralUtils::TryParse(args[1], days)) { + const auto days = GeneralUtils::TryParse(args[1]); + if (!days) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid days."); return; } + std::optional hours; if (args.size() >= 3) { - if (!GeneralUtils::TryParse(args[2], hours)) { + hours = GeneralUtils::TryParse(args[2]); + if (!hours) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid hours."); return; @@ -1058,11 +1061,11 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } expire = time(NULL); - expire += 24 * 60 * 60 * days; - expire += 60 * 60 * hours; + expire += 24 * 60 * 60 * days.value(); + expire += 60 * 60 * hours.value_or(0); } - Database::Get()->UpdateAccountUnmuteTime(accountId, expire); + if (accountId != 0) Database::Get()->UpdateAccountUnmuteTime(accountId, expire); char buffer[32] = "brought up for review.\0"; @@ -1126,10 +1129,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } } else { - accountId = player->GetParentUser()->GetAccountID(); + auto* character = player->GetCharacter(); + auto* user = character != nullptr ? character->GetParentUser() : nullptr; + if (user) accountId = user->GetAccountID(); } - Database::Get()->UpdateAccountBan(accountId, true); + if (accountId != 0) Database::Get()->UpdateAccountBan(accountId, true); if (player != nullptr) { Game::server->Disconnect(player->GetSystemAddress(), eServerDisconnectIdentifiers::FREE_TRIAL_EXPIRED); @@ -1157,14 +1162,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "startcelebration" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - int32_t celebration; + const auto celebration = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], celebration)) { + if (!celebration) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid celebration."); return; } - GameMessages::SendStartCelebrationEffect(entity, entity->GetSystemAddress(), celebration); + GameMessages::SendStartCelebrationEffect(entity, entity->GetSystemAddress(), celebration.value()); } if (chatCommand == "buffmed" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { @@ -1218,15 +1223,15 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ControllablePhysicsComponent* comp = static_cast(entity->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (!comp) return; - uint32_t lot; + const auto lot = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], lot)) { + if (!lot) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid lot."); return; } EntityInfo info; - info.lot = lot; + info.lot = lot.value(); info.pos = comp->GetPosition(); info.rot = comp->GetRotation(); info.spawner = nullptr; @@ -1247,28 +1252,29 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto controllablePhysicsComponent = entity->GetComponent(); if (!controllablePhysicsComponent) return; - LOT lot{}; - uint32_t numberToSpawn{}; - float radiusToSpawnWithin{}; - - if (!GeneralUtils::TryParse(args[0], lot)) { + const auto lot = GeneralUtils::TryParse(args[0]); + if (!lot) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid lot."); return; } - if (!GeneralUtils::TryParse(args[1], numberToSpawn) && numberToSpawn > 0) { + const auto numberToSpawnOptional = GeneralUtils::TryParse(args[1]); + if (!numberToSpawnOptional && numberToSpawnOptional.value() > 0) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid number of enemies to spawn."); return; } + uint32_t numberToSpawn = numberToSpawnOptional.value(); // Must spawn within a radius of at least 0.0f - if (!GeneralUtils::TryParse(args[2], radiusToSpawnWithin) && radiusToSpawnWithin < 0.0f) { + const auto radiusToSpawnWithinOptional = GeneralUtils::TryParse(args[2]); + if (!radiusToSpawnWithinOptional && radiusToSpawnWithinOptional.value() < 0.0f) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid radius to spawn within."); return; } + const float radiusToSpawnWithin = radiusToSpawnWithinOptional.value(); EntityInfo info; - info.lot = lot; + info.lot = lot.value(); info.spawner = nullptr; info.spawnerID = entity->GetObjectID(); info.spawnerNodeID = 0; @@ -1295,12 +1301,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if ((chatCommand == "giveuscore") && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - int32_t uscore; - - if (!GeneralUtils::TryParse(args[0], uscore)) { + const auto uscoreOptional = GeneralUtils::TryParse(args[0]); + if (!uscoreOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid uscore."); return; } + const int32_t uscore = uscoreOptional.value(); CharacterComponent* character = entity->GetComponent(); if (character) character->SetUScore(character->GetUScore() + uscore); @@ -1308,9 +1314,9 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit eLootSourceType lootType = eLootSourceType::MODERATION; - int32_t type; - if (args.size() >= 2 && GeneralUtils::TryParse(args[1], type)) { - lootType = static_cast(type); + if (args.size() >= 2) { + const auto type = GeneralUtils::TryParse(args[1]); + lootType = type.value_or(lootType); } GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), uscore, lootType); @@ -1336,14 +1342,15 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit entity = requestedPlayer->GetOwner(); } - uint32_t requestedLevel; + const auto requestedLevelOptional = GeneralUtils::TryParse(args[0]); uint32_t oldLevel; - // first check the level is valid - if (!GeneralUtils::TryParse(args[0], requestedLevel)) { + // first check the level is valid + if (!requestedLevelOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid level."); return; } + uint32_t requestedLevel = requestedLevelOptional.value(); // query to set our uscore to the correct value for this level auto characterComponent = entity->GetComponent(); @@ -1416,31 +1423,31 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if ((chatCommand == "freemoney" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) && args.size() == 1) { - int64_t money; + const auto money = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], money)) { + if (!money) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid money."); return; } auto* ch = entity->GetCharacter(); - ch->SetCoins(ch->GetCoins() + money, eLootSourceType::MODERATION); + ch->SetCoins(ch->GetCoins() + money.value(), eLootSourceType::MODERATION); } if ((chatCommand == "setcurrency") && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - int32_t money; + const auto money = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], money)) { + if (!money) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid money."); return; } auto* ch = entity->GetCharacter(); - ch->SetCoins(money, eLootSourceType::MODERATION); + ch->SetCoins(money.value(), eLootSourceType::MODERATION); } // Allow for this on even while not a GM, as it sometimes toggles incorrrectly. - if (chatCommand == "gminvis" && entity->GetParentUser()->GetMaxGMLevel() >= eGameMasterLevel::DEVELOPER) { + if (chatCommand == "gminvis" && entity->GetCharacter()->GetParentUser()->GetMaxGMLevel() >= eGameMasterLevel::DEVELOPER) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); return; @@ -1449,17 +1456,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "gmimmune" && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* destroyableComponent = entity->GetComponent(); - int32_t state = false; + const auto state = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], state)) { + if (!state) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid state."); return; } - if (destroyableComponent != nullptr) { - destroyableComponent->SetIsGMImmune(state); - } - + if (destroyableComponent) destroyableComponent->SetIsGMImmune(state.value()); return; } @@ -1467,53 +1471,47 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "attackimmune" && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* destroyableComponent = entity->GetComponent(); - int32_t state = false; + const auto state = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], state)) { + if (!state) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid state."); return; } - if (destroyableComponent != nullptr) { - destroyableComponent->SetIsImmune(state); - } - + if (destroyableComponent) destroyableComponent->SetIsImmune(state.value()); return; } if (chatCommand == "buff" && args.size() >= 2 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* buffComponent = entity->GetComponent(); - int32_t id = 0; - int32_t duration = 0; - - if (!GeneralUtils::TryParse(args[0], id)) { + const auto id = GeneralUtils::TryParse(args[0]); + if (!id) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid buff id."); return; } - if (!GeneralUtils::TryParse(args[1], duration)) { + const auto duration = GeneralUtils::TryParse(args[1]); + if (!duration) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid buff duration."); return; } - if (buffComponent != nullptr) { - buffComponent->ApplyBuff(id, duration, entity->GetObjectID()); - } - + if (buffComponent) buffComponent->ApplyBuff(id.value(), duration.value(), entity->GetObjectID()); return; } if ((chatCommand == "testmap" && args.size() >= 1) && entity->GetGMLevel() >= eGameMasterLevel::FORUM_MODERATOR) { ChatPackets::SendSystemMessage(sysAddr, u"Requesting map change..."); - uint32_t reqZone; LWOCLONEID cloneId = 0; bool force = false; - if (!GeneralUtils::TryParse(args[0], reqZone)) { + const auto reqZoneOptional = GeneralUtils::TryParse(args[0]); + if (!reqZoneOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid zone."); return; } + const LWOMAPID reqZone = reqZoneOptional.value(); if (args.size() > 1) { auto index = 1; @@ -1524,9 +1522,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit force = true; } - if (args.size() > index && !GeneralUtils::TryParse(args[index], cloneId)) { - ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone id."); - return; + if (args.size() > index) { + const auto cloneIdOptional = GeneralUtils::TryParse(args[index]); + if (!cloneIdOptional) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone id."); + return; + } + cloneId = cloneIdOptional.value(); } } @@ -1564,23 +1566,21 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "createprivate" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 3) { - uint32_t zone; - - if (!GeneralUtils::TryParse(args[0], zone)) { + const auto zone = GeneralUtils::TryParse(args[0]); + if (!zone) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid zone."); return; } - uint32_t clone; - - if (!GeneralUtils::TryParse(args[1], clone)) { + const auto clone = GeneralUtils::TryParse(args[1]); + if (!clone) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone."); return; } const auto& password = args[2]; - ZoneInstanceManager::Instance()->CreatePrivateZone(Game::server, zone, clone, password); + ZoneInstanceManager::Instance()->CreatePrivateZone(Game::server, zone.value(), clone.value(), password); ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16("Sent request for private zone with password: " + password)); @@ -1607,14 +1607,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (args.size() >= 1) { - float time; + const auto time = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], time)) { + if (!time) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid boost time."); return; } else { GameMessages::SendVehicleAddPassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - entity->AddCallbackTimer(time, [vehicle]() { + entity->AddCallbackTimer(time.value(), [vehicle]() { if (!vehicle) return; GameMessages::SendVehicleRemovePassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); }); @@ -1690,20 +1690,19 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "reforge" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 2) { - LOT baseItem; - LOT reforgedItem; + const auto baseItem = GeneralUtils::TryParse(args[0]); + if (!baseItem) return; - if (!GeneralUtils::TryParse(args[0], baseItem)) return; - if (!GeneralUtils::TryParse(args[1], reforgedItem)) return; + const auto reforgedItem = GeneralUtils::TryParse(args[1]); + if (!reforgedItem) return; auto* inventoryComponent = entity->GetComponent(); - - if (inventoryComponent == nullptr) return; + if (!inventoryComponent) return; std::vector data{}; - data.push_back(new LDFData(u"reforgedLOT", reforgedItem)); + data.push_back(new LDFData(u"reforgedLOT", reforgedItem.value())); - inventoryComponent->AddItem(baseItem, 1, eLootSourceType::MODERATION, eInventoryType::INVALID, data); + inventoryComponent->AddItem(baseItem.value(), 1, eLootSourceType::MODERATION, eInventoryType::INVALID, data); } if (chatCommand == "crash" && entity->GetGMLevel() >= eGameMasterLevel::OPERATOR) { @@ -1755,10 +1754,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "reloadconfig" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { Game::config->ReloadConfig(); VanityUtilities::SpawnVanity(); - dpWorld::Instance().Reload(); + dpWorld::Reload(); auto entities = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); - for (auto entity : entities) { - auto* scriptedActivityComponent = entity->GetComponent(); + for (const auto* const entity : entities) { + auto* const scriptedActivityComponent = entity->GetComponent(); if (!scriptedActivityComponent) continue; scriptedActivityComponent->ReloadConfig(); @@ -1769,19 +1768,20 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "rollloot" && entity->GetGMLevel() >= eGameMasterLevel::OPERATOR && args.size() >= 3) { - uint32_t lootMatrixIndex = 0; - uint32_t targetLot = 0; - uint32_t loops = 1; + const auto lootMatrixIndex = GeneralUtils::TryParse(args[0]); + if (!lootMatrixIndex) return; - if (!GeneralUtils::TryParse(args[0], lootMatrixIndex)) return; - if (!GeneralUtils::TryParse(args[1], targetLot)) return; - if (!GeneralUtils::TryParse(args[2], loops)) return; + const auto targetLot = GeneralUtils::TryParse(args[1]); + if (!targetLot) return; + + const auto loops = GeneralUtils::TryParse(args[2]); + if (!loops) return; uint64_t totalRuns = 0; for (uint32_t i = 0; i < loops; i++) { while (true) { - auto lootRoll = Loot::RollLootMatrix(lootMatrixIndex); + auto lootRoll = Loot::RollLootMatrix(lootMatrixIndex.value()); totalRuns += 1; bool doBreak = false; for (const auto& kv : lootRoll) { @@ -1794,26 +1794,30 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } std::u16string message = u"Ran loot drops looking for " - + GeneralUtils::to_u16string(targetLot) + + GeneralUtils::to_u16string(targetLot.value()) + u", " - + GeneralUtils::to_u16string(loops) + + GeneralUtils::to_u16string(loops.value()) + u" times. It ran " + GeneralUtils::to_u16string(totalRuns) + u" times. Averaging out at " - + GeneralUtils::to_u16string(static_cast(totalRuns) / loops); + + GeneralUtils::to_u16string(static_cast(totalRuns) / loops.value()); ChatPackets::SendSystemMessage(sysAddr, message); } if (chatCommand == "deleteinven" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { eInventoryType inventoryType = eInventoryType::INVALID; - if (!GeneralUtils::TryParse(args[0], inventoryType)) { + + const auto inventoryTypeOptional = GeneralUtils::TryParse(args[0]); + if (!inventoryTypeOptional) { // In this case, we treat the input as a string and try to find it in the reflection list std::transform(args[0].begin(), args[0].end(), args[0].begin(), ::toupper); LOG("looking for inventory %s", args[0].c_str()); for (uint32_t index = 0; index < NUMBER_OF_INVENTORIES; index++) { if (std::string_view(args[0]) == std::string_view(InventoryType::InventoryTypeToString(static_cast(index)))) inventoryType = static_cast(index); } + } else { + inventoryType = inventoryTypeOptional.value(); } if (inventoryType == eInventoryType::INVALID || inventoryType >= NUMBER_OF_INVENTORIES) { @@ -1835,32 +1839,32 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "castskill" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto* skillComponent = entity->GetComponent(); if (skillComponent) { - uint32_t skillId; + const auto skillId = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], skillId)) { + if (!skillId) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting skill ID."); return; } else { - skillComponent->CastSkill(skillId, entity->GetObjectID(), entity->GetObjectID()); + skillComponent->CastSkill(skillId.value(), entity->GetObjectID(), entity->GetObjectID()); ChatPackets::SendSystemMessage(sysAddr, u"Cast skill"); } } } if (chatCommand == "setskillslot" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 2) { - uint32_t skillId; - int slot; - auto* inventoryComponent = entity->GetComponent(); + auto* const inventoryComponent = entity->GetComponent(); if (inventoryComponent) { - if (!GeneralUtils::TryParse(args[0], slot)) { + const auto slot = GeneralUtils::TryParse(args[0]); + if (!slot) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting slot."); return; } else { - if (!GeneralUtils::TryParse(args[1], skillId)) { + const auto skillId = GeneralUtils::TryParse(args[1]); + if (!skillId) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting skill."); return; } else { - if (inventoryComponent->SetSkill(slot, skillId)) ChatPackets::SendSystemMessage(sysAddr, u"Set skill to slot successfully"); + if (inventoryComponent->SetSkill(slot.value(), skillId.value())) ChatPackets::SendSystemMessage(sysAddr, u"Set skill to slot successfully"); else ChatPackets::SendSystemMessage(sysAddr, u"Set skill to slot failed"); } } @@ -1870,13 +1874,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "setfaction" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto* destroyableComponent = entity->GetComponent(); if (destroyableComponent) { - int32_t faction; + const auto faction = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], faction)) { + if (!faction) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting faction."); return; } else { - destroyableComponent->SetFaction(faction); + destroyableComponent->SetFaction(faction.value()); ChatPackets::SendSystemMessage(sysAddr, u"Set faction and updated enemies list"); } } @@ -1885,13 +1889,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "addfaction" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto* destroyableComponent = entity->GetComponent(); if (destroyableComponent) { - int32_t faction; + const auto faction = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], faction)) { + if (!faction) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting faction."); return; } else { - destroyableComponent->AddFaction(faction); + destroyableComponent->AddFaction(faction.value()); ChatPackets::SendSystemMessage(sysAddr, u"Added faction and updated enemies list"); } } @@ -1913,7 +1917,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "setrewardcode" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - auto* cdrewardCodes = CDClientManager::Instance().GetTable(); + auto* cdrewardCodes = CDClientManager::GetTable(); auto id = cdrewardCodes->GetCodeID(args[0]); if (id != -1) Database::Get()->InsertRewardCode(user->GetAccountID(), id); @@ -1937,13 +1941,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "inspect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { Entity* closest = nullptr; - eReplicaComponentType component; - std::u16string ldf; bool isLDF = false; - if (!GeneralUtils::TryParse(args[0], component)) { + auto component = GeneralUtils::TryParse(args[0]); + if (!component) { component = eReplicaComponentType::INVALID; ldf = GeneralUtils::UTF8ToUTF16(args[0]); @@ -1955,7 +1958,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto closestDistance = 0.0f; - const auto candidates = Game::entityManager->GetEntitiesByComponent(component); + const auto candidates = Game::entityManager->GetEntitiesByComponent(component.value()); for (auto* candidate : candidates) { if (candidate->GetLOT() == 1 || candidate->GetLOT() == 8092) { @@ -1966,7 +1969,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit continue; } - if (closest == nullptr) { + if (!closest) { closest = candidate; closestDistance = NiPoint3::Distance(candidate->GetPosition(), reference); @@ -1983,13 +1986,11 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (closest == nullptr) { - return; - } + if (!closest) return; Game::entityManager->SerializeEntity(closest); - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto& info = table->GetByID(closest->GetLOT()); @@ -2011,20 +2012,18 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (args.size() >= 2) { if (args[1] == "-m" && args.size() >= 3) { - auto* movingPlatformComponent = closest->GetComponent(); + auto* const movingPlatformComponent = closest->GetComponent(); - int32_t value = 0; + const auto mValue = GeneralUtils::TryParse(args[2]); - if (movingPlatformComponent == nullptr || !GeneralUtils::TryParse(args[2], value)) { - return; - } + if (!movingPlatformComponent || !mValue) return; movingPlatformComponent->SetSerialized(true); - if (value == -1) { + if (mValue == -1) { movingPlatformComponent->StopPathing(); } else { - movingPlatformComponent->GotoWaypoint(value); + movingPlatformComponent->GotoWaypoint(mValue.value()); } Game::entityManager->SerializeEntity(closest); @@ -2065,13 +2064,11 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (args.size() >= 3) { - int32_t faction; - if (!GeneralUtils::TryParse(args[2], faction)) { - return; - } + const auto faction = GeneralUtils::TryParse(args[2]); + if (!faction) return; destuctable->SetFaction(-1); - destuctable->AddFaction(faction, true); + destuctable->AddFaction(faction.value(), true); } } else if (args[1] == "-cf") { auto* destuctable = entity->GetComponent(); diff --git a/dGame/dUtilities/VanityUtilities.cpp b/dGame/dUtilities/VanityUtilities.cpp index fa1a3eac..cb893da3 100644 --- a/dGame/dUtilities/VanityUtilities.cpp +++ b/dGame/dUtilities/VanityUtilities.cpp @@ -22,18 +22,42 @@ #include -std::vector VanityUtilities::m_NPCs = {}; -std::vector VanityUtilities::m_Parties = {}; -std::vector VanityUtilities::m_PartyPhrases = {}; + +namespace { + std::vector objects; + std::set loadedFiles; +} + +void SetupNPCTalk(Entity* npc); +void NPCTalk(Entity* npc); +void ParseXml(const std::string& file); +LWOOBJID SpawnSpawner(const VanityObject& object, const VanityObjectLocation& location); +Entity* SpawnObject(const VanityObject& object, const VanityObjectLocation& location); +VanityObject* GetObject(const std::string& name); void VanityUtilities::SpawnVanity() { - if (Game::config->GetValue("disable_vanity") == "1") { - return; - } - const uint32_t zoneID = Game::server->GetZoneID(); - for (const auto& npc : m_NPCs) { + if (zoneID == 1200) { + { + EntityInfo info; + info.lot = 8139; + info.pos = { 259.5f, 246.4f, -705.2f }; + info.rot = { 0.0f, 0.0f, 1.0f, 0.0f }; + info.spawnerID = Game::entityManager->GetZoneControlEntity()->GetObjectID(); + info.settings = { + new LDFData(u"hasCustomText", true), + new LDFData(u"customText", ParseMarkdown((BinaryPathFinder::GetBinaryDir() / "vanity/TESTAMENT.md").string())) + }; + + auto* entity = Game::entityManager->CreateEntity(info); + Game::entityManager->ConstructEntity(entity); + } + } + + if (Game::config->GetValue("disable_vanity") == "1") return; + + for (const auto& npc : objects) { if (npc.m_ID == LWOOBJID_EMPTY) continue; if (npc.m_LOT == 176){ Game::zoneManager->RemoveSpawner(npc.m_ID); @@ -44,174 +68,73 @@ void VanityUtilities::SpawnVanity() { } } - m_NPCs.clear(); - m_Parties.clear(); - m_PartyPhrases.clear(); + objects.clear(); + loadedFiles.clear(); - ParseXML((BinaryPathFinder::GetBinaryDir() / "vanity/NPC.xml").string()); + ParseXml((BinaryPathFinder::GetBinaryDir() / "vanity/root.xml").string()); - // Loop through all parties - for (const auto& party : m_Parties) { - const auto chance = party.m_Chance; - const auto zone = party.m_Zone; + // Loop through all objects + for (auto& object : objects) { + if (object.m_Locations.find(Game::server->GetZoneID()) == object.m_Locations.end()) continue; - if (zone != Game::server->GetZoneID()) { - continue; - } - - float rate = GeneralUtils::GenerateRandomNumber(0, 1); - if (chance < rate) { - continue; - } - - // Copy m_NPCs into a new vector - std::vector npcList = m_NPCs; - std::vector taken = {}; - - LOG("Spawning party with %i locations", party.m_Locations.size()); - - // Loop through all locations - for (const auto& location : party.m_Locations) { - rate = GeneralUtils::GenerateRandomNumber(0, 1); - if (0.75f < rate) { - continue; - } - - // Get a random NPC - auto npcIndex = GeneralUtils::GenerateRandomNumber(0, npcList.size() - 1); - - while (std::find(taken.begin(), taken.end(), npcIndex) != taken.end()) { - npcIndex = GeneralUtils::GenerateRandomNumber(0, npcList.size() - 1); - } - - auto& npc = npcList[npcIndex]; - // Skip spawners - if (npc.m_LOT == 176) continue; - - taken.push_back(npcIndex); - - LOG("ldf size is %i", npc.ldf.size()); - if (npc.ldf.empty()) { - npc.ldf = { - new LDFData>(u"syncLDF", { u"custom_script_client" }), - new LDFData(u"custom_script_client", u"scripts\\ai\\SPEC\\MISSION_MINIGAME_CLIENT.lua") - }; - } - - // Spawn the NPC - if (npc.m_LOT == 176){ - npc.m_ID = SpawnSpawner(npc.m_LOT, location.m_Position, location.m_Rotation, npc.ldf); - } else { - auto* npcEntity = SpawnNPC(npc.m_LOT, npc.m_Name, location.m_Position, location.m_Rotation, npc.m_Equipment, npc.ldf); - if (!npc.m_Phrases.empty()) { - npcEntity->SetVar>(u"chats", m_PartyPhrases); - SetupNPCTalk(npcEntity); - } - } - } - return; - } - - // Loop through all NPCs - for (auto& npc : m_NPCs) { - if (npc.m_Locations.find(Game::server->GetZoneID()) == npc.m_Locations.end()) - continue; - - const std::vector& locations = npc.m_Locations.at(Game::server->GetZoneID()); + const std::vector& locations = object.m_Locations.at(Game::server->GetZoneID()); // Pick a random location const auto& location = locations[GeneralUtils::GenerateRandomNumber( static_cast(0), static_cast(locations.size() - 1))]; float rate = GeneralUtils::GenerateRandomNumber(0, 1); - if (location.m_Chance < rate) { - continue; - } + if (location.m_Chance < rate) continue; - if (npc.ldf.empty()) { - npc.ldf = { - new LDFData>(u"syncLDF", { u"custom_script_client" }), - new LDFData(u"custom_script_client", u"scripts\\ai\\SPEC\\MISSION_MINIGAME_CLIENT.lua") - }; - } - if (npc.m_LOT == 176){ - npc.m_ID = SpawnSpawner(npc.m_LOT, location.m_Position, location.m_Rotation, npc.ldf); + if (object.m_LOT == 176){ + object.m_ID = SpawnSpawner(object, location); } else { // Spawn the NPC - auto* npcEntity = SpawnNPC(npc.m_LOT, npc.m_Name, location.m_Position, location.m_Rotation, npc.m_Equipment, npc.ldf); - if (!npcEntity) continue; - npc.m_ID = npcEntity->GetObjectID(); - if (!npc.m_Phrases.empty()){ - npcEntity->SetVar>(u"chats", npc.m_Phrases); - - auto* scriptComponent = npcEntity->GetComponent(); - - if (scriptComponent && !npc.m_Script.empty()) { - scriptComponent->SetScript(npc.m_Script); - scriptComponent->SetSerialized(false); - - for (const auto& npc : npc.m_Flags) { - npcEntity->SetVar(GeneralUtils::ASCIIToUTF16(npc.first), npc.second); - } - } - SetupNPCTalk(npcEntity); + auto* objectEntity = SpawnObject(object, location); + if (!objectEntity) continue; + object.m_ID = objectEntity->GetObjectID(); + if (!object.m_Phrases.empty()){ + objectEntity->SetVar>(u"chats", object.m_Phrases); + SetupNPCTalk(objectEntity); } } } - - if (zoneID == 1200) { - { - EntityInfo info; - info.lot = 8139; - info.pos = { 259.5f, 246.4f, -705.2f }; - info.rot = { 0.0f, 0.0f, 1.0f, 0.0f }; - info.spawnerID = Game::entityManager->GetZoneControlEntity()->GetObjectID(); - - info.settings = { new LDFData(u"hasCustomText", true), - new LDFData(u"customText", ParseMarkdown((BinaryPathFinder::GetBinaryDir() / "vanity/TESTAMENT.md").string())) }; - - auto* entity = Game::entityManager->CreateEntity(info); - - Game::entityManager->ConstructEntity(entity); - } - } } -LWOOBJID VanityUtilities::SpawnSpawner(LOT lot, const NiPoint3& position, const NiQuaternion& rotation, const std::vector& ldf){ +LWOOBJID SpawnSpawner(const VanityObject& object, const VanityObjectLocation& location) { SceneObject obj; - obj.lot = lot; + obj.lot = object.m_LOT; // guratantee we have no collisions do { obj.id = ObjectIDManager::GenerateObjectID(); } while(Game::zoneManager->GetSpawner(obj.id)); - obj.position = position; - obj.rotation = rotation; - obj.settings = ldf; + obj.position = location.m_Position; + obj.rotation = location.m_Rotation; + obj.settings = object.m_Config; Level::MakeSpawner(obj); return obj.id; } -Entity* VanityUtilities::SpawnNPC(LOT lot, const std::string& name, const NiPoint3& position, const NiQuaternion& rotation, const std::vector& inventory, const std::vector& ldf) { +Entity* SpawnObject(const VanityObject& object, const VanityObjectLocation& location) { EntityInfo info; - info.lot = lot; - info.pos = position; - info.rot = rotation; + info.lot = object.m_LOT; + info.pos = location.m_Position; + info.rot = location.m_Rotation; + info.scale = location.m_Scale; info.spawnerID = Game::entityManager->GetZoneControlEntity()->GetObjectID(); - info.settings = ldf; + info.settings = object.m_Config; auto* entity = Game::entityManager->CreateEntity(info); - entity->SetVar(u"npcName", name); + if (!object.m_Name.empty()) entity->SetVar(u"npcName", object.m_Name); if (entity->GetVar(u"noGhosting")) entity->SetIsGhostingCandidate(false); auto* inventoryComponent = entity->GetComponent(); - - if (inventoryComponent && !inventory.empty()) { - inventoryComponent->SetNPCItems(inventory); + if (inventoryComponent && !object.m_Equipment.empty()) { + inventoryComponent->SetNPCItems(object.m_Equipment); } auto* destroyableComponent = entity->GetComponent(); - - if (destroyableComponent != nullptr) { + if (destroyableComponent) { destroyableComponent->SetIsGMImmune(true); destroyableComponent->SetMaxHealth(0); destroyableComponent->SetHealth(0); @@ -222,7 +145,12 @@ Entity* VanityUtilities::SpawnNPC(LOT lot, const std::string& name, const NiPoin return entity; } -void VanityUtilities::ParseXML(const std::string& file) { +void ParseXml(const std::string& file) { + if (loadedFiles.contains(file)){ + LOG("Trying to load vanity file %s twice!!!", file.c_str()); + return; + } + loadedFiles.insert(file); // Read the entire file std::ifstream xmlFile(file); std::string xml((std::istreambuf_iterator(xmlFile)), std::istreambuf_iterator()); @@ -231,210 +159,107 @@ void VanityUtilities::ParseXML(const std::string& file) { tinyxml2::XMLDocument doc; doc.Parse(xml.c_str(), xml.size()); - // Read the NPCs - auto* npcs = doc.FirstChildElement("npcs"); - - if (npcs == nullptr) { - LOG("Failed to parse NPCs"); - return; - } - - for (auto* party = npcs->FirstChildElement("party"); party != nullptr; party = party->NextSiblingElement("party")) { - // Get 'zone' as uint32_t and 'chance' as float - uint32_t zone = 0; - float chance = 0.0f; - - if (party->Attribute("zone") != nullptr) { - zone = std::stoul(party->Attribute("zone")); - } - - if (party->Attribute("chance") != nullptr) { - chance = std::stof(party->Attribute("chance")); - } - - VanityParty partyInfo; - partyInfo.m_Zone = zone; - partyInfo.m_Chance = chance; - - auto* locations = party->FirstChildElement("locations"); - - if (locations == nullptr) { - LOG("Failed to parse party locations"); - continue; - } - - for (auto* location = locations->FirstChildElement("location"); location != nullptr; - location = location->NextSiblingElement("location")) { - // Get the location data - auto* x = location->Attribute("x"); - auto* y = location->Attribute("y"); - auto* z = location->Attribute("z"); - auto* rw = location->Attribute("rw"); - auto* rx = location->Attribute("rx"); - auto* ry = location->Attribute("ry"); - auto* rz = location->Attribute("rz"); - - if (x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr - || rz == nullptr) { - LOG("Failed to parse party location data"); + // Read the objects + auto* files = doc.FirstChildElement("files"); + if (files) { + for (auto* file = files->FirstChildElement("file"); file != nullptr; file = file->NextSiblingElement("file")) { + std::string enabled = file->Attribute("enabled"); + std::string filename = file->Attribute("name"); + if (enabled != "1") { continue; } - - VanityNPCLocation locationData; - locationData.m_Position = { std::stof(x), std::stof(y), std::stof(z) }; - locationData.m_Rotation = { std::stof(rw), std::stof(rx), std::stof(ry), std::stof(rz) }; - locationData.m_Chance = 1.0f; - - partyInfo.m_Locations.push_back(locationData); - } - - m_Parties.push_back(partyInfo); - } - - auto* partyPhrases = npcs->FirstChildElement("partyphrases"); - - if (partyPhrases == nullptr) { - LOG("No party phrases found"); - } else { - for (auto* phrase = partyPhrases->FirstChildElement("phrase"); phrase != nullptr; - phrase = phrase->NextSiblingElement("phrase")) { - // Get the phrase - auto* text = phrase->GetText(); - - if (text == nullptr) { - LOG("Failed to parse party phrase"); - continue; - } - - m_PartyPhrases.push_back(text); + ParseXml((BinaryPathFinder::GetBinaryDir() / "vanity" / filename).string()); } } - for (auto* npc = npcs->FirstChildElement("npc"); npc != nullptr; npc = npc->NextSiblingElement("npc")) { - // Get the NPC name - auto* name = npc->Attribute("name"); + // Read the objects + auto* objectsElement = doc.FirstChildElement("objects"); + const uint32_t currentZoneID = Game::server->GetZoneID(); + if (objectsElement) { + for (auto* object = objectsElement->FirstChildElement("object"); object != nullptr; object = object->NextSiblingElement("object")) { + // for use later when adding to the vector of VanityObjects + bool useLocationsAsRandomSpawnPoint = false; + // Get the NPC name + auto* name = object->Attribute("name"); - if (!name) name = ""; + if (!name) name = ""; - // Get the NPC lot - auto* lot = npc->Attribute("lot"); + // Get the NPC lot + auto lot = GeneralUtils::TryParse(object->Attribute("lot")).value_or(LOT_NULL); - if (lot == nullptr) { - LOG("Failed to parse NPC lot"); - continue; - } - - // Get the equipment - auto* equipment = npc->FirstChildElement("equipment"); - std::vector inventory; - - if (equipment) { - auto* text = equipment->GetText(); - - if (text != nullptr) { - std::string equipmentString(text); - - std::vector splitEquipment = GeneralUtils::SplitString(equipmentString, ','); - - for (auto& item : splitEquipment) { - inventory.push_back(std::stoi(item)); - } - } - } - - - // Get the phrases - auto* phrases = npc->FirstChildElement("phrases"); - - std::vector phraseList = {}; - - if (phrases) { - for (auto* phrase = phrases->FirstChildElement("phrase"); phrase != nullptr; - phrase = phrase->NextSiblingElement("phrase")) { - // Get the phrase - auto* text = phrase->GetText(); - if (text == nullptr) { - LOG("Failed to parse NPC phrase"); - continue; - } - phraseList.push_back(text); - } - } - - // Get the script - auto* scriptElement = npc->FirstChildElement("script"); - - std::string scriptName = ""; - - if (scriptElement != nullptr) { - auto* scriptNameAttribute = scriptElement->Attribute("name"); - if (scriptNameAttribute) scriptName = scriptNameAttribute; - } - - auto* ldfElement = npc->FirstChildElement("ldf"); - std::vector keys = {}; - - std::vector ldf = {}; - if(ldfElement) { - for (auto* entry = ldfElement->FirstChildElement("entry"); entry != nullptr; - entry = entry->NextSiblingElement("entry")) { - // Get the ldf data - auto* data = entry->Attribute("data"); - if (!data) continue; - - LDFBaseData* ldfData = LDFBaseData::DataFromString(data); - keys.push_back(ldfData->GetKey()); - ldf.push_back(ldfData); - } - } - if (!keys.empty()) ldf.push_back(new LDFData>(u"syncLDF", keys)); - - VanityNPC npcData; - npcData.m_Name = name; - npcData.m_LOT = std::stoi(lot); - npcData.m_Equipment = inventory; - npcData.m_Phrases = phraseList; - npcData.m_Script = scriptName; - npcData.ldf = ldf; - - // Get flags - auto* flags = npc->FirstChildElement("flags"); - - if (flags != nullptr) { - for (auto* flag = flags->FirstChildElement("flag"); flag != nullptr; - flag = flag->NextSiblingElement("flag")) { - // Get the flag name - auto* name = flag->Attribute("name"); - - if (name == nullptr) { - LOG("Failed to parse NPC flag name"); - continue; - } - - // Get the flag value - auto* value = flag->Attribute("value"); - - if (value == nullptr) { - LOG("Failed to parse NPC flag value"); - continue; - } - - npcData.m_Flags[name] = std::stoi(value); - } - } - - // Get the zones - for (auto* zone = npc->FirstChildElement("zone"); zone != nullptr; zone = zone->NextSiblingElement("zone")) { - // Get the zone ID - auto* zoneID = zone->Attribute("id"); - - if (zoneID == nullptr) { - LOG("Failed to parse NPC zone ID"); + if (lot == LOT_NULL) { + LOG("Failed to parse object lot"); continue; } + // Get the equipment + auto* equipment = object->FirstChildElement("equipment"); + std::vector inventory; + + if (equipment) { + auto* text = equipment->GetText(); + + if (text != nullptr) { + std::string equipmentString(text); + + std::vector splitEquipment = GeneralUtils::SplitString(equipmentString, ','); + + for (auto& item : splitEquipment) { + // remove spaces for tryParse to work + item.erase(remove_if(item.begin(), item.end(), isspace), item.end()); + auto itemInt = GeneralUtils::TryParse(item); + if (itemInt) inventory.push_back(itemInt.value()); + } + } + } + + // Get the phrases + auto* phrases = object->FirstChildElement("phrases"); + std::vector phraseList = {}; + if (phrases) { + for (auto* phrase = phrases->FirstChildElement("phrase"); phrase != nullptr; + phrase = phrase->NextSiblingElement("phrase")) { + // Get the phrase + auto* text = phrase->GetText(); + if (text == nullptr) { + LOG("Failed to parse NPC phrase"); + continue; + } + phraseList.push_back(text); + } + } + + auto* configElement = object->FirstChildElement("config"); + std::vector keys = {}; + std::vector config = {}; + if(configElement) { + for (auto* key = configElement->FirstChildElement("key"); key != nullptr; + key = key->NextSiblingElement("key")) { + // Get the config data + auto* data = key->GetText(); + if (!data) continue; + + LDFBaseData* configData = LDFBaseData::DataFromString(data); + if (configData->GetKey() == u"useLocationsAsRandomSpawnPoint" && configData->GetValueType() == eLDFType::LDF_TYPE_BOOLEAN){ + useLocationsAsRandomSpawnPoint = static_cast(configData); + continue; + } + keys.push_back(configData->GetKey()); + config.push_back(configData); + } + } + if (!keys.empty()) config.push_back(new LDFData>(u"syncLDF", keys)); + + VanityObject objectData { + .m_Name = name, + .m_LOT = lot, + .m_Equipment = inventory, + .m_Phrases = phraseList, + .m_Config = config + }; + // Get the locations - auto* locations = zone->FirstChildElement("locations"); + auto* locations = object->FirstChildElement("locations"); if (locations == nullptr) { LOG("Failed to parse NPC locations"); @@ -443,53 +268,69 @@ void VanityUtilities::ParseXML(const std::string& file) { for (auto* location = locations->FirstChildElement("location"); location != nullptr; location = location->NextSiblingElement("location")) { + // Get the location data - auto* x = location->Attribute("x"); - auto* y = location->Attribute("y"); - auto* z = location->Attribute("z"); - auto* rw = location->Attribute("rw"); - auto* rx = location->Attribute("rx"); - auto* ry = location->Attribute("ry"); - auto* rz = location->Attribute("rz"); + auto zoneID = GeneralUtils::TryParse(location->Attribute("zone")); + auto x = GeneralUtils::TryParse(location->Attribute("x")); + auto y = GeneralUtils::TryParse(location->Attribute("y")); + auto z = GeneralUtils::TryParse(location->Attribute("z")); + auto rw = GeneralUtils::TryParse(location->Attribute("rw")); + auto rx = GeneralUtils::TryParse(location->Attribute("rx")); + auto ry = GeneralUtils::TryParse(location->Attribute("ry")); + auto rz = GeneralUtils::TryParse(location->Attribute("rz")); - if (x == nullptr || y == nullptr || z == nullptr || rw == nullptr || rx == nullptr || ry == nullptr - || rz == nullptr) { + if (!zoneID || !x || !y || !z || !rw || !rx || !ry || !rz) { LOG("Failed to parse NPC location data"); continue; } - VanityNPCLocation locationData; - locationData.m_Position = { std::stof(x), std::stof(y), std::stof(z) }; - locationData.m_Rotation = { std::stof(rw), std::stof(rx), std::stof(ry), std::stof(rz) }; - locationData.m_Chance = 1.0f; - - if (location->Attribute("chance") != nullptr) { - locationData.m_Chance = std::stof(location->Attribute("chance")); + if (zoneID.value() != currentZoneID) { + LOG_DEBUG("Skipping (%s) %i location because it is in %i and not the current zone (%i)", name, lot, zoneID.value(), currentZoneID); + continue; } - const auto& it = npcData.m_Locations.find(std::stoi(zoneID)); + VanityObjectLocation locationData { + .m_Position = { x.value(), y.value(), z.value() }, + .m_Rotation = { rw.value(), rx.value(), ry.value(), rz.value() }, + }; - if (it != npcData.m_Locations.end()) { + if (location->Attribute("chance")) { + locationData.m_Chance = GeneralUtils::TryParse(location->Attribute("chance")).value_or(1.0f); + } + + if (location->Attribute("scale")) { + locationData.m_Scale = GeneralUtils::TryParse(location->Attribute("scale")).value_or(1.0f); + } + + const auto& it = objectData.m_Locations.find(zoneID.value()); + + if (it != objectData.m_Locations.end()) { it->second.push_back(locationData); } else { - std::vector locations; + std::vector locations; locations.push_back(locationData); - npcData.m_Locations.insert(std::make_pair(std::stoi(zoneID), locations)); + objectData.m_Locations.insert(std::make_pair(zoneID.value(), locations)); + } + + if (!useLocationsAsRandomSpawnPoint) { + objects.push_back(objectData); + objectData.m_Locations.clear(); } } - } - m_NPCs.push_back(npcData); + if (useLocationsAsRandomSpawnPoint && !objectData.m_Locations.empty()) { + objects.push_back(objectData); + } + } } } -VanityNPC* VanityUtilities::GetNPC(const std::string& name) { - for (size_t i = 0; i < m_NPCs.size(); i++) { - if (m_NPCs[i].m_Name == name) { - return &m_NPCs[i]; +VanityObject* VanityUtilities::GetObject(const std::string& name) { + for (size_t i = 0; i < objects.size(); i++) { + if (objects[i].m_Name == name) { + return &objects[i]; } } - return nullptr; } @@ -498,10 +339,13 @@ std::string VanityUtilities::ParseMarkdown(const std::string& file) { // Read the file into a string std::ifstream t(file); - - // If the file does not exist, return an empty string. + std::stringstream output; + // If the file does not exist, return a useful error. if (!t.good()) { - return ""; + output << "File "; + output << file.substr(file.rfind("/") + 1); + output << " not found!\nContact your DarkflameServer admin\nor find the server source at https://github.com/DarkflameUniverse/DarkflameServer"; + return output.str(); } std::stringstream buffer; @@ -511,7 +355,6 @@ std::string VanityUtilities::ParseMarkdown(const std::string& file) { // Loop through all lines in the file. // Replace all instances of the markdown syntax with the corresponding HTML. // Only care about headers - std::stringstream output; std::string line; std::stringstream ss; ss << fileContents; @@ -555,13 +398,13 @@ std::string VanityUtilities::ParseMarkdown(const std::string& file) { return output.str(); } -void VanityUtilities::SetupNPCTalk(Entity* npc) { +void SetupNPCTalk(Entity* npc) { npc->AddCallbackTimer(15.0f, [npc]() { NPCTalk(npc); }); npc->SetProximityRadius(20.0f, "talk"); } -void VanityUtilities::NPCTalk(Entity* npc) { +void NPCTalk(Entity* npc) { auto* proximityMonitorComponent = npc->GetComponent(); if (!proximityMonitorComponent->GetProximityObjects("talk").empty()) { diff --git a/dGame/dUtilities/VanityUtilities.h b/dGame/dUtilities/VanityUtilities.h index cff73bce..a1d00501 100644 --- a/dGame/dUtilities/VanityUtilities.h +++ b/dGame/dUtilities/VanityUtilities.h @@ -3,73 +3,32 @@ #include "dCommonVars.h" #include "Entity.h" #include +#include -struct VanityNPCLocation -{ +struct VanityObjectLocation { float m_Chance = 1.0f; NiPoint3 m_Position; NiQuaternion m_Rotation; + float m_Scale = 1.0f; }; -struct VanityNPC -{ +struct VanityObject { LWOOBJID m_ID = LWOOBJID_EMPTY; std::string m_Name; - LOT m_LOT; + LOT m_LOT = LOT_NULL; std::vector m_Equipment; std::vector m_Phrases; - std::string m_Script; - std::map m_Flags; - std::map> m_Locations; - std::vector ldf; + std::map> m_Locations; + std::vector m_Config; }; -struct VanityParty -{ - uint32_t m_Zone; - float m_Chance = 1.0f; - std::vector m_Locations; -}; -class VanityUtilities -{ -public: - static void SpawnVanity(); +namespace VanityUtilities { + void SpawnVanity(); - static Entity* SpawnNPC( - LOT lot, - const std::string& name, - const NiPoint3& position, - const NiQuaternion& rotation, - const std::vector& inventory, - const std::vector& ldf - ); + VanityObject* GetObject(const std::string& name); - static LWOOBJID SpawnSpawner( - LOT lot, - const NiPoint3& position, - const NiQuaternion& rotation, - const std::vector& ldf - ); - - static std::string ParseMarkdown( + std::string ParseMarkdown( const std::string& file ); - - static void ParseXML( - const std::string& file - ); - - static VanityNPC* GetNPC(const std::string& name); - -private: - static void SetupNPCTalk(Entity* npc); - - static void NPCTalk(Entity* npc); - - static std::vector m_NPCs; - - static std::vector m_Parties; - - static std::vector m_PartyPhrases; }; diff --git a/dMasterServer/CMakeLists.txt b/dMasterServer/CMakeLists.txt index 32a7b1ec..260e4f16 100644 --- a/dMasterServer/CMakeLists.txt +++ b/dMasterServer/CMakeLists.txt @@ -7,10 +7,13 @@ set(DMASTERSERVER_SOURCES add_library(dMasterServer ${DMASTERSERVER_SOURCES}) add_executable(MasterServer "MasterServer.cpp") add_compile_definitions(MasterServer PRIVATE PROJECT_VERSION="\"${PROJECT_VERSION}\"") +target_include_directories(dMasterServer PUBLIC "." + "${PROJECT_SOURCE_DIR}/dZoneManager" # InstanceManager.h uses dZMCommon.h + ${PROJECT_SOURCE_DIR}/dServer/ # BinaryPathFinder.h +) target_link_libraries(dMasterServer ${COMMON_LIBRARIES}) -target_link_libraries(MasterServer ${COMMON_LIBRARIES} dMasterServer dServer) -target_include_directories(dMasterServer PRIVATE ${PROJECT_SOURCE_DIR}/dServer) +target_link_libraries(MasterServer ${COMMON_LIBRARIES} bcrypt dMasterServer dServer) if(WIN32) add_dependencies(MasterServer WorldServer AuthServer ChatServer) diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index a5a6d8dc..3ec42634 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -17,7 +17,8 @@ InstanceManager::InstanceManager(Logger* logger, const std::string& externalIP) { mLogger = logger; mExternalIP = externalIP; - GeneralUtils::TryParse(Game::config->GetValue("world_port_start"), m_LastPort); + m_LastPort = + GeneralUtils::TryParse(Game::config->GetValue("world_port_start")).value_or(m_LastPort); m_LastInstanceID = LWOINSTANCEID_INVALID; } @@ -180,7 +181,7 @@ void InstanceManager::RequestAffirmation(Instance* instance, const PendingInstan bitStream.Write(request.id); - Game::server->Send(&bitStream, instance->GetSysAddr(), false); + Game::server->Send(bitStream, instance->GetSysAddr(), false); LOG("Sent affirmation request %llu to %i/%i", request.id, static_cast(instance->GetZoneID().GetMapID()), @@ -322,7 +323,7 @@ Instance* InstanceManager::FindPrivateInstance(const std::string& password) { } int InstanceManager::GetSoftCap(LWOMAPID mapID) { - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable) { const CDZoneTable* zone = zoneTable->Query(mapID); @@ -335,7 +336,7 @@ int InstanceManager::GetSoftCap(LWOMAPID mapID) { } int InstanceManager::GetHardCap(LWOMAPID mapID) { - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable) { const CDZoneTable* zone = zoneTable->Query(mapID); @@ -360,7 +361,7 @@ void Instance::Shutdown() { BitStreamUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::SHUTDOWN); - Game::server->Send(&bitStream, this->m_SysAddr, false); + Game::server->Send(bitStream, this->m_SysAddr, false); LOG("Triggered world shutdown for zone/clone/instance %i/%i/%i", GetMapID(), GetCloneID(), GetInstanceID()); } diff --git a/dMasterServer/InstanceManager.h b/dMasterServer/InstanceManager.h index b9f1ec5a..1fc4af43 100644 --- a/dMasterServer/InstanceManager.h +++ b/dMasterServer/InstanceManager.h @@ -134,7 +134,7 @@ private: Logger* mLogger; std::string mExternalIP; std::vector m_Instances; - unsigned short m_LastPort = 3000; + uint16_t m_LastPort = 3000; LWOINSTANCEID m_LastInstanceID; /** diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index f15bb9a9..3d5f4aff 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -89,9 +89,8 @@ int main(int argc, char** argv) { if (!dConfig::Exists("worldconfig.ini")) LOG("Could not find worldconfig.ini, using default settings"); - uint32_t clientNetVersion = 171022; const auto clientNetVersionString = Game::config->GetValue("client_net_version"); - if (!clientNetVersionString.empty()) GeneralUtils::TryParse(clientNetVersionString, clientNetVersion); + const uint32_t clientNetVersion = GeneralUtils::TryParse(clientNetVersionString).value_or(171022); LOG("Using net version %i", clientNetVersion); @@ -177,17 +176,6 @@ int main(int argc, char** argv) { // Run migrations should any need to be run. MigrationRunner::RunSQLiteMigrations(); - //Get CDClient initial information - try { - CDClientManager::Instance(); - } catch (CppSQLite3Exception& e) { - LOG("Failed to initialize CDServer SQLite Database"); - LOG("May be caused by corrupted file: %s", (Game::assetManager->GetResPath() / "CDServer.sqlite").string().c_str()); - LOG("Error: %s", e.errorMessage()); - LOG("Error Code: %i", e.errorCode()); - return EXIT_FAILURE; - } - //If the first command line argument is -a or --account then make the user //input a username and password, with the password being hidden. if (argc > 1 && @@ -588,7 +576,7 @@ void HandlePacket(Packet* packet) { BitStreamUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::SESSION_KEY_RESPONSE); bitStream.Write(key.first); bitStream.Write(username); - Game::server->Send(&bitStream, packet->systemAddress, false); + Game::server->Send(bitStream, packet->systemAddress, false); break; } } @@ -687,7 +675,7 @@ void HandlePacket(Packet* packet) { const auto& zone = instance->GetZoneID(); - MasterPackets::SendZoneTransferResponse(Game::server, packet->systemAddress, requestID, (bool)mythranShift, zone.GetMapID(), instance->GetInstanceID(), zone.GetCloneID(), instance->GetIP(), instance->GetPort()); + MasterPackets::SendZoneTransferResponse(Game::server, packet->systemAddress, requestID, static_cast(mythranShift), zone.GetMapID(), instance->GetInstanceID(), zone.GetCloneID(), instance->GetIP(), instance->GetPort()); break; } @@ -798,7 +786,7 @@ int ShutdownSequence(int32_t signal) { { CBITSTREAM; BitStreamUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::SHUTDOWN); - Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); + Game::server->Send(bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); LOG("Triggered master shutdown"); } diff --git a/dNavigation/CMakeLists.txt b/dNavigation/CMakeLists.txt index 4c03d24b..e2a1c6ef 100644 --- a/dNavigation/CMakeLists.txt +++ b/dNavigation/CMakeLists.txt @@ -6,5 +6,12 @@ foreach(file ${DNAVIGATIONS_DTERRAIN_SOURCES}) set(DNAVIGATION_SOURCES ${DNAVIGATION_SOURCES} "dTerrain/${file}") endforeach() -add_library(dNavigation STATIC ${DNAVIGATION_SOURCES}) -target_link_libraries(dNavigation Detour Recast) +add_library(dNavigation OBJECT ${DNAVIGATION_SOURCES}) +target_include_directories(dNavigation PUBLIC "." + PRIVATE + "${PROJECT_SOURCE_DIR}/dZoneManager" + "${PROJECT_SOURCE_DIR}/dGame" + "${PROJECT_SOURCE_DIR}/dGame/dEntity" + "${PROJECT_SOURCE_DIR}/dNavigation/dTerrain" # via dNavMesh.cpp +) +target_link_libraries(dNavigation PRIVATE Detour Recast dCommon) diff --git a/dNavigation/dNavMesh.cpp b/dNavigation/dNavMesh.cpp index ab9ed2d5..f49dd31e 100644 --- a/dNavigation/dNavMesh.cpp +++ b/dNavigation/dNavMesh.cpp @@ -11,6 +11,7 @@ #include "dZoneManager.h" #include "DluAssert.h" +#include "DetourExtensions.h" dNavMesh::dNavMesh(uint32_t zoneId) { m_ZoneId = zoneId; @@ -30,16 +31,8 @@ dNavMesh::dNavMesh(uint32_t zoneId) { dNavMesh::~dNavMesh() { // Clean up Recast information - if(m_Solid) rcFreeHeightField(m_Solid); - if (m_CHF) rcFreeCompactHeightfield(m_CHF); - if (m_CSet) rcFreeContourSet(m_CSet); - if (m_PMesh) rcFreePolyMesh(m_PMesh); - if (m_PMDMesh) rcFreePolyMeshDetail(m_PMDMesh); if (m_NavMesh) dtFreeNavMesh(m_NavMesh); if (m_NavQuery) dtFreeNavMeshQuery(m_NavQuery); - - if (m_Ctx) delete m_Ctx; - if (m_Triareas) delete[] m_Triareas; } diff --git a/dNavigation/dNavMesh.h b/dNavigation/dNavMesh.h index 600b8b86..8a55c649 100644 --- a/dNavigation/dNavMesh.h +++ b/dNavigation/dNavMesh.h @@ -2,13 +2,17 @@ #include #include -#include -#include -#include - -#include "DetourExtensions.h" class NiPoint3; +class rcHeightfield; +class rcCompactHeightfield; +class rcContourSet; +class rcPolyMesh; +class rcPolyMeshDetail; +class InputGeom; +class dtNavMesh; +class dtNavMeshQuery; +class rcContext; class dNavMesh { public: @@ -26,24 +30,14 @@ public: float GetHeightAtPoint(const NiPoint3& location, const float halfExtentsHeight = 32.0f) const; std::vector GetPath(const NiPoint3& startPos, const NiPoint3& endPos, float speed = 10.0f); - class dtNavMesh* GetdtNavMesh() { return m_NavMesh; } + bool IsNavmeshLoaded() { return m_NavMesh != nullptr; } private: void LoadNavmesh(); uint32_t m_ZoneId; - uint8_t* m_Triareas = nullptr; - rcHeightfield* m_Solid = nullptr; - rcCompactHeightfield* m_CHF = nullptr; - rcContourSet* m_CSet = nullptr; - rcPolyMesh* m_PMesh = nullptr; - rcConfig m_Config; - rcPolyMeshDetail* m_PMDMesh = nullptr; - - class InputGeom* m_Geometry = nullptr; - class dtNavMesh* m_NavMesh = nullptr; - class dtNavMeshQuery* m_NavQuery = nullptr; + dtNavMesh* m_NavMesh = nullptr; + dtNavMeshQuery* m_NavQuery = nullptr; uint8_t m_NavMeshDrawFlags; - rcContext* m_Ctx = nullptr; }; diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index 2597c576..a2bf731c 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -7,8 +7,8 @@ #include "Database.h" #include "ZoneInstanceManager.h" #include "MD5.h" -#include "SHA512.h" #include "GeneralUtils.h" +#include "dClient/ClientVersion.h" #include @@ -28,10 +28,10 @@ namespace { std::vector claimCodes; } -void Stamp::Serialize(RakNet::BitStream* outBitStream){ - outBitStream->Write(type); - outBitStream->Write(value); - outBitStream->Write(timestamp); +void Stamp::Serialize(RakNet::BitStream& outBitStream){ + outBitStream.Write(type); + outBitStream.Write(value); + outBitStream.Write(timestamp); }; void AuthPackets::LoadClaimCodes() { @@ -39,10 +39,9 @@ void AuthPackets::LoadClaimCodes() { auto rcstring = Game::config->GetValue("rewardcodes"); auto codestrings = GeneralUtils::SplitString(rcstring, ','); for(auto const &codestring: codestrings){ - uint32_t code = -1; - if(GeneralUtils::TryParse(codestring, code) && code != -1){ - claimCodes.push_back(code); - } + const auto code = GeneralUtils::TryParse(codestring); + + if (code && code.value() != -1) claimCodes.push_back(code.value()); } } @@ -74,9 +73,8 @@ void AuthPackets::SendHandshake(dServer* server, const SystemAddress& sysAddr, c RakNet::BitStream bitStream; BitStreamUtils::WriteHeader(bitStream, eConnectionType::SERVER, eServerMessageType::VERSION_CONFIRM); - uint32_t clientNetVersion = 171022; const auto clientNetVersionString = Game::config->GetValue("client_net_version"); - if (!clientNetVersionString.empty()) GeneralUtils::TryParse(clientNetVersionString, clientNetVersion); + const uint32_t clientNetVersion = GeneralUtils::TryParse(clientNetVersionString).value_or(171022); bitStream.Write(clientNetVersion); bitStream.Write(861228100); @@ -84,9 +82,9 @@ void AuthPackets::SendHandshake(dServer* server, const SystemAddress& sysAddr, c if (serverType == ServerType::Auth) bitStream.Write(ServiceId::Auth); else if (serverType == ServerType::World) bitStream.Write(ServiceId::World); else bitStream.Write(ServiceId::General); - bitStream.Write(774909490); + bitStream.Write(215523405360); - server->Send(&bitStream, sysAddr, false); + server->Send(bitStream, sysAddr, false); } void AuthPackets::HandleLoginRequest(dServer* server, Packet* packet) { @@ -231,7 +229,7 @@ void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAdd RakNet::BitStream loginResponse; BitStreamUtils::WriteHeader(loginResponse, eConnectionType::CLIENT, eClientMessageType::LOGIN_RESPONSE); - loginResponse.Write(GeneralUtils::CastUnderlyingType(responseCode)); + loginResponse.Write(responseCode); // Event Gating loginResponse.Write(LUString(Game::config->GetValue("event_1"))); @@ -243,12 +241,12 @@ void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAdd loginResponse.Write(LUString(Game::config->GetValue("event_7"))); loginResponse.Write(LUString(Game::config->GetValue("event_8"))); - uint16_t version_major = 1; - uint16_t version_current = 10; - uint16_t version_minor = 64; - GeneralUtils::TryParse(Game::config->GetValue("version_major"), version_major); - GeneralUtils::TryParse(Game::config->GetValue("version_current"), version_current); - GeneralUtils::TryParse(Game::config->GetValue("version_minor"), version_minor); + const uint16_t version_major = + GeneralUtils::TryParse(Game::config->GetValue("version_major")).value_or(ClientVersion::major); + const uint16_t version_current = + GeneralUtils::TryParse(Game::config->GetValue("version_current")).value_or(ClientVersion::current); + const uint16_t version_minor = + GeneralUtils::TryParse(Game::config->GetValue("version_minor")).value_or(ClientVersion::minor); loginResponse.Write(version_major); loginResponse.Write(version_current); @@ -293,16 +291,16 @@ void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAdd stamps.emplace_back(eStamps::PASSPORT_AUTH_WORLD_COMMUNICATION_FINISH, 1); loginResponse.Write((sizeof(Stamp) * stamps.size()) + sizeof(uint32_t)); - for (auto& stamp : stamps) stamp.Serialize(&loginResponse); + for (auto& stamp : stamps) stamp.Serialize(loginResponse); - server->Send(&loginResponse, sysAddr, false); + server->Send(loginResponse, sysAddr, false); //Inform the master server that we've created a session for this user: if (responseCode == eLoginResponse::SUCCESS) { CBITSTREAM; BitStreamUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::SET_SESSION_KEY); bitStream.Write(sessionKey); bitStream.Write(LUString(username)); - server->SendToMaster(&bitStream); + server->SendToMaster(bitStream); LOG("Set sessionKey: %i for user %s", sessionKey, username.c_str()); } diff --git a/dNet/AuthPackets.h b/dNet/AuthPackets.h index 539bae75..ee1e4586 100644 --- a/dNet/AuthPackets.h +++ b/dNet/AuthPackets.h @@ -63,7 +63,7 @@ struct Stamp { this->timestamp = timestamp; } - void Serialize(RakNet::BitStream* outBitStream); + void Serialize(RakNet::BitStream& outBitStream); }; enum class ClientOS : uint8_t { diff --git a/dNet/CMakeLists.txt b/dNet/CMakeLists.txt index 68de8eb1..15cdda42 100644 --- a/dNet/CMakeLists.txt +++ b/dNet/CMakeLists.txt @@ -8,5 +8,24 @@ set(DNET_SOURCES "AuthPackets.cpp" "ZoneInstanceManager.cpp") add_library(dNet STATIC ${DNET_SOURCES}) +target_link_libraries(dNet PRIVATE bcrypt MD5) +target_include_directories(dNet PRIVATE + "${PROJECT_SOURCE_DIR}/dCommon" + "${PROJECT_SOURCE_DIR}/dCommon/dEnums" -target_link_libraries(dNet PUBLIC dCommon) + "${PROJECT_SOURCE_DIR}/dZoneManager" + + "${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase" + "${PROJECT_SOURCE_DIR}/dDatabase/CDClientDatabase/CDClientTables" + "${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase" + "${PROJECT_SOURCE_DIR}/dDatabase/GameDatabase/ITables" + "${PROJECT_SOURCE_DIR}/thirdparty/mariadb-connector-cpp/include" + + "${PROJECT_SOURCE_DIR}/dGame" # UserManager.h + "${PROJECT_SOURCE_DIR}/dGame/dComponents" + "${PROJECT_SOURCE_DIR}/dGame/dEntity" # via dZoneManager + "${PROJECT_SOURCE_DIR}/dGame/dGameMessages" # GameMessages.h + "${PROJECT_SOURCE_DIR}/dGame/dInventory" # via PossessableComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dUtilities" # via Item.h + "${PROJECT_SOURCE_DIR}/dScripts" # transitive through components +) diff --git a/dNet/MasterPackets.cpp b/dNet/MasterPackets.cpp index 6d70fedb..7bd8f4a5 100644 --- a/dNet/MasterPackets.cpp +++ b/dNet/MasterPackets.cpp @@ -12,7 +12,7 @@ void MasterPackets::SendPersistentIDRequest(dServer* server, uint64_t requestID) CBITSTREAM; BitStreamUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::REQUEST_PERSISTENT_ID); bitStream.Write(requestID); - server->SendToMaster(&bitStream); + server->SendToMaster(bitStream); } void MasterPackets::SendPersistentIDResponse(dServer* server, const SystemAddress& sysAddr, uint64_t requestID, uint32_t objID) { @@ -22,7 +22,7 @@ void MasterPackets::SendPersistentIDResponse(dServer* server, const SystemAddres bitStream.Write(requestID); bitStream.Write(objID); - server->Send(&bitStream, sysAddr, false); + server->Send(bitStream, sysAddr, false); } void MasterPackets::SendZoneTransferRequest(dServer* server, uint64_t requestID, bool mythranShift, uint32_t zoneID, uint32_t cloneID) { @@ -34,7 +34,7 @@ void MasterPackets::SendZoneTransferRequest(dServer* server, uint64_t requestID, bitStream.Write(zoneID); bitStream.Write(cloneID); - server->SendToMaster(&bitStream); + server->SendToMaster(bitStream); } void MasterPackets::SendZoneCreatePrivate(dServer* server, uint32_t zoneID, uint32_t cloneID, const std::string& password) { @@ -49,7 +49,7 @@ void MasterPackets::SendZoneCreatePrivate(dServer* server, uint32_t zoneID, uint bitStream.Write(character); } - server->SendToMaster(&bitStream); + server->SendToMaster(bitStream); } void MasterPackets::SendZoneRequestPrivate(dServer* server, uint64_t requestID, bool mythranShift, const std::string& password) { @@ -64,7 +64,7 @@ void MasterPackets::SendZoneRequestPrivate(dServer* server, uint64_t requestID, bitStream.Write(character); } - server->SendToMaster(&bitStream); + server->SendToMaster(bitStream); } void MasterPackets::SendWorldReady(dServer* server, LWOMAPID zoneId, LWOINSTANCEID instanceId) { @@ -74,7 +74,7 @@ void MasterPackets::SendWorldReady(dServer* server, LWOMAPID zoneId, LWOINSTANCE bitStream.Write(zoneId); bitStream.Write(instanceId); - server->SendToMaster(&bitStream); + server->SendToMaster(bitStream); } void MasterPackets::SendZoneTransferResponse(dServer* server, const SystemAddress& sysAddr, uint64_t requestID, bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, const std::string& serverIP, uint32_t serverPort) { @@ -89,7 +89,7 @@ void MasterPackets::SendZoneTransferResponse(dServer* server, const SystemAddres bitStream.Write(serverPort); bitStream.Write(LUString(serverIP, 255)); - server->Send(&bitStream, sysAddr, false); + server->Send(bitStream, sysAddr, false); } void MasterPackets::HandleServerInfo(Packet* packet) { @@ -119,5 +119,5 @@ void MasterPackets::SendServerInfo(dServer* server, Packet* packet) { bitStream.Write(server->GetServerType()); bitStream.Write(LUString(server->GetIP())); - server->SendToMaster(&bitStream); + server->SendToMaster(bitStream); } diff --git a/dNet/WorldPackets.cpp b/dNet/WorldPackets.cpp index 9d159704..71f0fc71 100644 --- a/dNet/WorldPackets.cpp +++ b/dNet/WorldPackets.cpp @@ -96,13 +96,13 @@ void WorldPackets::SendCreateCharacter(const SystemAddress& sysAddr, int64_t rep std::unique_ptr> chatmode(new LDFData(u"chatmode", static_cast(gm))); std::unique_ptr> reputationLdf(new LDFData(u"reputation", reputation)); - objid->WriteToPacket(&data); - lot->WriteToPacket(&data); - name->WriteToPacket(&data); - gmlevel->WriteToPacket(&data); - chatmode->WriteToPacket(&data); - xmlConfigData->WriteToPacket(&data); - reputationLdf->WriteToPacket(&data); + objid->WriteToPacket(data); + lot->WriteToPacket(data); + name->WriteToPacket(data); + gmlevel->WriteToPacket(data); + chatmode->WriteToPacket(data); + xmlConfigData->WriteToPacket(data); + reputationLdf->WriteToPacket(data); //Compress the data before sending: const uint32_t reservedSize = ZCompression::GetMaxCompressedLength(data.GetNumberOfBytesUsed()); diff --git a/dNet/dServer.cpp b/dNet/dServer.cpp index ed66b42c..e504a985 100644 --- a/dNet/dServer.cpp +++ b/dNet/dServer.cpp @@ -159,13 +159,13 @@ void dServer::DeallocateMasterPacket(Packet* packet) { mMasterPeer->DeallocatePacket(packet); } -void dServer::Send(RakNet::BitStream* bitStream, const SystemAddress& sysAddr, bool broadcast) { - mPeer->Send(bitStream, SYSTEM_PRIORITY, RELIABLE_ORDERED, 0, sysAddr, broadcast); +void dServer::Send(RakNet::BitStream& bitStream, const SystemAddress& sysAddr, bool broadcast) { + mPeer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE_ORDERED, 0, sysAddr, broadcast); } -void dServer::SendToMaster(RakNet::BitStream* bitStream) { +void dServer::SendToMaster(RakNet::BitStream& bitStream) { if (!mMasterConnectionActive) ConnectToMaster(); - mMasterPeer->Send(bitStream, SYSTEM_PRIORITY, RELIABLE_ORDERED, 0, mMasterSystemAddress, false); + mMasterPeer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE_ORDERED, 0, mMasterSystemAddress, false); } void dServer::Disconnect(const SystemAddress& sysAddr, eServerDisconnectIdentifiers disconNotifyID) { diff --git a/dNet/dServer.h b/dNet/dServer.h index ef47eea4..40f606f1 100644 --- a/dNet/dServer.h +++ b/dNet/dServer.h @@ -52,8 +52,8 @@ public: Packet* Receive(); void DeallocatePacket(Packet* packet); void DeallocateMasterPacket(Packet* packet); - virtual void Send(RakNet::BitStream* bitStream, const SystemAddress& sysAddr, bool broadcast); - void SendToMaster(RakNet::BitStream* bitStream); + virtual void Send(RakNet::BitStream& bitStream, const SystemAddress& sysAddr, bool broadcast); + void SendToMaster(RakNet::BitStream& bitStream); void Disconnect(const SystemAddress& sysAddr, eServerDisconnectIdentifiers disconNotifyID); diff --git a/dPhysics/CMakeLists.txt b/dPhysics/CMakeLists.txt index 340e4c3c..65588b4b 100644 --- a/dPhysics/CMakeLists.txt +++ b/dPhysics/CMakeLists.txt @@ -7,6 +7,10 @@ set(DPHYSICS_SOURCES "dpCollisionChecks.cpp" "dpWorld.cpp") add_library(dPhysics STATIC ${DPHYSICS_SOURCES}) +target_include_directories(dPhysics PUBLIC "." + "${PROJECT_SOURCE_DIR}/dCommon" + "${PROJECT_SOURCE_DIR}/dCommon/dEnums" +) target_link_libraries(dPhysics PUBLIC Recast Detour - INTERFACE dNavigation) + INTERFACE dNavigation dCommon) diff --git a/dPhysics/dpEntity.cpp b/dPhysics/dpEntity.cpp index 70bddb40..cbe3f5e8 100644 --- a/dPhysics/dpEntity.cpp +++ b/dPhysics/dpEntity.cpp @@ -76,7 +76,7 @@ void dpEntity::CheckCollision(dpEntity* other) { return; } - bool wasFound = (m_CurrentlyCollidingObjects.find(other->GetObjectID()) != m_CurrentlyCollidingObjects.end()); + bool wasFound = m_CurrentlyCollidingObjects.contains(other->GetObjectID()); bool isColliding = m_CollisionShape->IsColliding(other->GetShape()); diff --git a/dPhysics/dpGrid.cpp b/dPhysics/dpGrid.cpp index 1704e068..7a0db1f8 100644 --- a/dPhysics/dpGrid.cpp +++ b/dPhysics/dpGrid.cpp @@ -8,24 +8,14 @@ dpGrid::dpGrid(int numCells, int cellSize) { CELL_SIZE = cellSize; m_DeleteGrid = true; - //fill x - for (int i = 0; i < NUM_CELLS; i++) { - m_Cells.push_back(std::vector>()); - } - - //fill z - for (int i = 0; i < NUM_CELLS; i++) { - for (int i = 0; i < NUM_CELLS; i++) { - m_Cells[i].push_back(std::forward_list()); - } - } + m_Cells.resize(NUM_CELLS, std::vector>(NUM_CELLS)); } dpGrid::~dpGrid() { if (!this->m_DeleteGrid) return; for (auto& x : m_Cells) { //x - for (auto& y : x) { //y - for (auto en : y) { + for (auto& z : x) { //y + for (auto en : z) { if (!en) continue; delete en; en = nullptr; @@ -36,16 +26,15 @@ dpGrid::~dpGrid() { void dpGrid::Add(dpEntity* entity) { //Determine which grid cell it's in. - int cellX = (int)std::round(entity->m_Position.x) / dpGrid::CELL_SIZE + NUM_CELLS / 2; - int cellZ = (int)std::round(entity->m_Position.z) / dpGrid::CELL_SIZE + NUM_CELLS / 2; + int cellX = static_cast(std::round(entity->m_Position.x)) / dpGrid::CELL_SIZE + NUM_CELLS / 2; + int cellZ = static_cast(std::round(entity->m_Position.z)) / dpGrid::CELL_SIZE + NUM_CELLS / 2; - if (cellX < 0) cellX = 0; - if (cellZ < 0) cellZ = 0; - if (cellX >= NUM_CELLS) cellX = NUM_CELLS - 1; - if (cellZ >= NUM_CELLS) cellZ = NUM_CELLS - 1; + // Clamp values to the range [0, NUM_CELLS - 1] + cellX = std::clamp(cellX, 0, NUM_CELLS - 1); + cellZ = std::clamp(cellZ, 0, NUM_CELLS - 1); //Add to cell: - m_Cells[cellX][cellZ].push_front(entity); + m_Cells[cellX][cellZ].push_back(entity); //To verify that the object isn't gargantuan: if (entity->GetScale() >= CELL_SIZE * 2 || entity->GetIsGargantuan()) @@ -53,45 +42,52 @@ void dpGrid::Add(dpEntity* entity) { } void dpGrid::Move(dpEntity* entity, float x, float z) { - int oldCellX = (int)std::round(entity->m_Position.x) / dpGrid::CELL_SIZE + NUM_CELLS / 2; - int oldCellZ = (int)std::round(entity->m_Position.z) / dpGrid::CELL_SIZE + NUM_CELLS / 2; + int oldCellX = static_cast(std::round(entity->m_Position.x)) / dpGrid::CELL_SIZE + NUM_CELLS / 2; + int oldCellZ = static_cast(std::round(entity->m_Position.z)) / dpGrid::CELL_SIZE + NUM_CELLS / 2; - int cellX = (int)std::round(x) / dpGrid::CELL_SIZE + NUM_CELLS / 2; - int cellZ = (int)std::round(z) / dpGrid::CELL_SIZE + NUM_CELLS / 2; + int cellX = static_cast(std::round(x)) / dpGrid::CELL_SIZE + NUM_CELLS / 2; + int cellZ = static_cast(std::round(z)) / dpGrid::CELL_SIZE + NUM_CELLS / 2; - if (cellX < 0) cellX = 0; - if (cellZ < 0) cellZ = 0; - if (cellX >= NUM_CELLS) cellX = NUM_CELLS - 1; - if (cellZ >= NUM_CELLS) cellZ = NUM_CELLS - 1; + // Clamp values to the range [0, NUM_CELLS - 1] + cellX = std::clamp(cellX, 0, NUM_CELLS - 1); + cellZ = std::clamp(cellZ, 0, NUM_CELLS - 1); - if (oldCellX < 0) oldCellX = 0; - if (oldCellZ < 0) oldCellZ = 0; - if (oldCellX >= NUM_CELLS) oldCellX = NUM_CELLS - 1; - if (oldCellZ >= NUM_CELLS) oldCellZ = NUM_CELLS - 1; + oldCellX = std::clamp(oldCellX, 0, NUM_CELLS - 1); + oldCellZ = std::clamp(oldCellZ, 0, NUM_CELLS - 1); if (oldCellX == cellX && oldCellZ == cellZ) return; - //Remove from perv cell: - m_Cells[oldCellX][oldCellZ].remove(entity); + //Remove from prev cell: + auto& cell = m_Cells[oldCellX][oldCellZ]; + + // For speed, find the single match and swap it with the last element, then pop_back. + auto toRemove = std::find(cell.begin(), cell.end(), entity); + if (toRemove != cell.end()) { + *toRemove = cell.back(); + cell.pop_back(); + } //Add to the new cell - m_Cells[cellX][cellZ].push_front(entity); + m_Cells[cellX][cellZ].push_back(entity); } void dpGrid::Delete(dpEntity* entity) { if (!entity) return; - int oldCellX = (int)std::round(entity->m_Position.x) / dpGrid::CELL_SIZE + NUM_CELLS / 2; - int oldCellZ = (int)std::round(entity->m_Position.z) / dpGrid::CELL_SIZE + NUM_CELLS / 2; + int oldCellX = static_cast(std::round(entity->m_Position.x)) / dpGrid::CELL_SIZE + NUM_CELLS / 2; + int oldCellZ = static_cast(std::round(entity->m_Position.z)) / dpGrid::CELL_SIZE + NUM_CELLS / 2; - if (oldCellX < 0) oldCellX = 0; - if (oldCellZ < 0) oldCellZ = 0; - if (oldCellX >= NUM_CELLS) oldCellX = NUM_CELLS - 1; - if (oldCellZ >= NUM_CELLS) oldCellZ = NUM_CELLS - 1; + // Clamp values to the range [0, NUM_CELLS - 1] + oldCellX = std::clamp(oldCellX, 0, NUM_CELLS - 1); + oldCellZ = std::clamp(oldCellZ, 0, NUM_CELLS - 1); - m_Cells[oldCellX][oldCellZ].remove(entity); + auto& cell = m_Cells[oldCellX][oldCellZ]; + auto toRemove = std::find(cell.begin(), cell.end(), entity); + if (toRemove != cell.end()) { + *toRemove = cell.back(); + cell.pop_back(); + } - if (m_GargantuanObjects.find(entity->m_ObjectID) != m_GargantuanObjects.end()) - m_GargantuanObjects.erase(entity->m_ObjectID); + m_GargantuanObjects.erase(entity->m_ObjectID); if (entity) delete entity; entity = nullptr; @@ -100,8 +96,8 @@ void dpGrid::Delete(dpEntity* entity) { void dpGrid::Update(float deltaTime) { //Pre-update: for (auto& x : m_Cells) { //x - for (auto& y : x) { //y - for (auto en : y) { + for (auto& z : x) { //y + for (auto en : z) { if (!en) continue; en->PreUpdate(); } @@ -110,8 +106,8 @@ void dpGrid::Update(float deltaTime) { //Actual collision detection update: for (int x = 0; x < NUM_CELLS; x++) { - for (int y = 0; y < NUM_CELLS; y++) { - HandleCell(x, y, deltaTime); + for (int z = 0; z < NUM_CELLS; z++) { + HandleCell(x, z, deltaTime); } } } @@ -157,7 +153,7 @@ void dpGrid::HandleCell(int x, int z, float deltaTime) { HandleEntity(en, other); } - for (auto other : m_GargantuanObjects) - HandleEntity(en, other.second); + for (auto& [id, entity] : m_GargantuanObjects) + HandleEntity(en, entity); } } diff --git a/dPhysics/dpGrid.h b/dPhysics/dpGrid.h index 229e7449..39a9cfe7 100644 --- a/dPhysics/dpGrid.h +++ b/dPhysics/dpGrid.h @@ -1,8 +1,7 @@ #pragma once -#include -#include -#include #include +#include + #include "dCommonVars.h" class dpEntity; @@ -30,7 +29,8 @@ public: */ void SetDeleteGrid(bool value) { this->m_DeleteGrid = value; }; - std::vector>> GetCells() { return this->m_Cells; }; + // Intentional copy since this is only used when we delete this class to re-create it. + std::vector>> GetCells() { return this->m_Cells; }; private: void HandleEntity(dpEntity* entity, dpEntity* other); @@ -38,7 +38,7 @@ private: private: //cells on X, cells on Y for that X, then another vector that contains the entities within that cell. - std::vector>> m_Cells; + std::vector>> m_Cells; std::map m_GargantuanObjects; bool m_DeleteGrid = true; }; diff --git a/dPhysics/dpWorld.cpp b/dPhysics/dpWorld.cpp index 698ceb63..c9bc742a 100644 --- a/dPhysics/dpWorld.cpp +++ b/dPhysics/dpWorld.cpp @@ -9,11 +9,32 @@ #include "Logger.h" #include "dConfig.h" +#include "dNavMesh.h" + +namespace { + dpGrid* m_Grid = nullptr; + dNavMesh* m_NavMesh = nullptr; + int32_t phys_sp_tilesize = 205; + int32_t phys_sp_tilecount = 12; + + uint32_t m_ZoneID = 0; + + std::vector m_StaticEntities; + std::vector m_DynamicEntites; + bool phys_spatial_partitioning = true; +}; + void dpWorld::Initialize(unsigned int zoneID, bool generateNewNavMesh) { const auto physSpTilecount = Game::config->GetValue("phys_sp_tilecount"); - if (!physSpTilecount.empty()) GeneralUtils::TryParse(physSpTilecount, phys_sp_tilecount); + if (!physSpTilecount.empty()) { + phys_sp_tilecount = GeneralUtils::TryParse(physSpTilecount).value_or(phys_sp_tilecount); + } + const auto physSpTilesize = Game::config->GetValue("phys_sp_tilesize"); - if (!physSpTilesize.empty()) GeneralUtils::TryParse(physSpTilesize, phys_sp_tilesize); + if (!physSpTilesize.empty()) { + phys_sp_tilesize = GeneralUtils::TryParse(physSpTilesize).value_or(phys_sp_tilesize); + } + const auto physSpatialPartitioning = Game::config->GetValue("phys_spatial_partitioning"); if (!physSpatialPartitioning.empty()) phys_spatial_partitioning = physSpatialPartitioning == "1"; @@ -51,7 +72,7 @@ void dpWorld::Reload() { } } -dpWorld::~dpWorld() { +void dpWorld::Shutdown() { if (m_Grid) { // Triple check this is true m_Grid->SetDeleteGrid(true); @@ -65,6 +86,10 @@ dpWorld::~dpWorld() { } } +bool dpWorld::IsLoaded() { + return m_NavMesh->IsNavmeshLoaded(); +} + void dpWorld::StepWorld(float deltaTime) { if (m_Grid) { m_Grid->Update(deltaTime); @@ -91,6 +116,10 @@ void dpWorld::StepWorld(float deltaTime) { } } +dNavMesh* dpWorld::GetNavMesh() { + return m_NavMesh; +} + void dpWorld::AddEntity(dpEntity* entity) { if (m_Grid) entity->SetGrid(m_Grid); //This sorts this entity into the right cell else { //old method, slow @@ -125,7 +154,7 @@ void dpWorld::RemoveEntity(dpEntity* entity) { } } -bool dpWorld::ShouldUseSP(unsigned int zoneID) { +bool dpWorld::ShouldUseSP(uint32_t zoneID) { if (!phys_spatial_partitioning) return false; // TODO: Add to this list as needed. diff --git a/dPhysics/dpWorld.h b/dPhysics/dpWorld.h index bf2af06d..fc23a15c 100644 --- a/dPhysics/dpWorld.h +++ b/dPhysics/dpWorld.h @@ -1,48 +1,22 @@ #pragma once -#include "Singleton.h" +#include -//Navmesh includes: -#include "Recast.h" -#include "DetourNavMesh.h" -#include "DetourNavMeshBuilder.h" -#include "DetourNavMeshQuery.h" - -#include -#include - -#include "dNavMesh.h" - -class NiPoint3; +class dNavMesh; class dpEntity; -class dpGrid; -class dpWorld : public Singleton { -public: - void Initialize(unsigned int zoneID, bool generateNewNavMesh = true); +namespace dpWorld { + void Initialize(uint32_t zoneID, bool generateNewNavMesh = true); + void Shutdown(); void Reload(); - ~dpWorld(); - - bool ShouldUseSP(unsigned int zoneID); - bool IsLoaded() const { return m_NavMesh->GetdtNavMesh() != nullptr; } + bool ShouldUseSP(uint32_t zoneID); + bool IsLoaded(); void StepWorld(float deltaTime); void AddEntity(dpEntity* entity); void RemoveEntity(dpEntity* entity); - dNavMesh* GetNavMesh() { return m_NavMesh; } - -private: - dpGrid* m_Grid; - bool phys_spatial_partitioning = true; - int phys_sp_tilesize = 205; - int phys_sp_tilecount = 12; - - std::vector m_StaticEntities; - std::vector m_DynamicEntites; - - dNavMesh* m_NavMesh = nullptr; - uint32_t m_ZoneID = 0; + dNavMesh* GetNavMesh(); }; diff --git a/dScripts/02_server/CMakeLists.txt b/dScripts/02_server/CMakeLists.txt index 51eb24c8..8114b226 100644 --- a/dScripts/02_server/CMakeLists.txt +++ b/dScripts/02_server/CMakeLists.txt @@ -30,15 +30,28 @@ endforeach() add_subdirectory(Pets) -add_library(dScriptsServer STATIC ${DSCRIPTS_SOURCES_02_SERVER}) -target_include_directories(dScriptsServer PUBLIC "." +add_library(dScriptsServerBase OBJECT ${DSCRIPTS_SOURCES_02_SERVER}) +target_include_directories(dScriptsServerBase PUBLIC "." "DLU" "Equipment" "Minigame" "Minigame/General" "Objects" - "Pets") +) +target_precompile_headers(dScriptsServerBase REUSE_FROM dScriptsBase) + +add_library(dScriptsServer INTERFACE) +target_sources(dScriptsServer INTERFACE + $ + $ + $ +) target_link_libraries(dScriptsServer INTERFACE - dScriptsServerEnemy - dScriptsServerMap) -target_precompile_headers(dScriptsServer REUSE_FROM dScriptsBase) + dScriptsServerMap +) +target_include_directories(dScriptsServer INTERFACE + $ + $ + $ + $ +) diff --git a/dScripts/02_server/DLU/CMakeLists.txt b/dScripts/02_server/DLU/CMakeLists.txt index 64d4cbbd..fb257d3e 100644 --- a/dScripts/02_server/DLU/CMakeLists.txt +++ b/dScripts/02_server/DLU/CMakeLists.txt @@ -1,3 +1,3 @@ set(DSCRIPTS_SOURCES_02_SERVER_DLU - "DLUVanityNPC.cpp" + "DLUVanityTeleportingObject.cpp" PARENT_SCOPE) diff --git a/dScripts/02_server/DLU/DLUVanityNPC.cpp b/dScripts/02_server/DLU/DLUVanityTeleportingObject.cpp similarity index 51% rename from dScripts/02_server/DLU/DLUVanityNPC.cpp rename to dScripts/02_server/DLU/DLUVanityTeleportingObject.cpp index ba2c6604..60d2d715 100644 --- a/dScripts/02_server/DLU/DLUVanityNPC.cpp +++ b/dScripts/02_server/DLU/DLUVanityTeleportingObject.cpp @@ -1,24 +1,21 @@ -#include "DLUVanityNPC.h" +#include "DLUVanityTeleportingObject.h" #include "GameMessages.h" #include "dServer.h" #include "VanityUtilities.h" #include "RenderComponent.h" -void DLUVanityNPC::OnStartup(Entity* self) { - m_NPC = VanityUtilities::GetNPC("averysumner - Destroyer of Worlds"); +void DLUVanityTeleportingObject::OnStartup(Entity* self) { + if (!self->HasVar(u"npcName")) return; - if (m_NPC == nullptr) { - return; - } + m_Object = VanityUtilities::GetObject(self->GetVarAsString(u"npcName")); + if (!m_Object) return; + if (self->HasVar(u"teleportInterval")) m_TeleportInterval = self->GetVar(u"teleportInterval"); - if (self->GetVar(u"teleport")) { - self->AddTimer("setupTeleport", 15.0f); - } + self->AddTimer("setupTeleport", m_TeleportInterval); } -void DLUVanityNPC::OnTimerDone(Entity* self, std::string timerName) { +void DLUVanityTeleportingObject::OnTimerDone(Entity* self, std::string timerName) { if (timerName == "setupTeleport") { - RenderComponent::PlayAnimation(self, u"interact"); GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportBeam", "teleportBeam"); GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportRings", "teleportRings"); @@ -28,13 +25,14 @@ void DLUVanityNPC::OnTimerDone(Entity* self, std::string timerName) { GameMessages::SendStopFXEffect(self, true, "teleportBeam"); GameMessages::SendStopFXEffect(self, true, "teleportRings"); } else if (timerName == "teleport") { - std::vector& locations = m_NPC->m_Locations[Game::server->GetZoneID()]; + std::vector& locations = m_Object->m_Locations[Game::server->GetZoneID()]; selectLocation: - VanityNPCLocation& newLocation = locations[GeneralUtils::GenerateRandomNumber(0, locations.size() - 1)]; + VanityObjectLocation& newLocation = locations[GeneralUtils::GenerateRandomNumber(0, locations.size() - 1)]; + // try to get not the same position, but if we get the same one twice, it's fine if (self->GetPosition() == newLocation.m_Position) { - goto selectLocation; // cry about it + VanityObjectLocation& newLocation = locations[GeneralUtils::GenerateRandomNumber(0, locations.size() - 1)]; } self->SetPosition(newLocation.m_Position); @@ -42,6 +40,6 @@ void DLUVanityNPC::OnTimerDone(Entity* self, std::string timerName) { GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportBeam", "teleportBeam"); GameMessages::SendPlayFXEffect(self->GetObjectID(), 6478, u"teleportRings", "teleportRings"); self->AddTimer("stopFX", 2.0f); - self->AddTimer("setupTeleport", 15.0f); + self->AddTimer("setupTeleport", m_TeleportInterval); } } diff --git a/dScripts/02_server/DLU/DLUVanityNPC.h b/dScripts/02_server/DLU/DLUVanityTeleportingObject.h similarity index 54% rename from dScripts/02_server/DLU/DLUVanityNPC.h rename to dScripts/02_server/DLU/DLUVanityTeleportingObject.h index aeb8e051..a13ba901 100644 --- a/dScripts/02_server/DLU/DLUVanityNPC.h +++ b/dScripts/02_server/DLU/DLUVanityTeleportingObject.h @@ -1,13 +1,14 @@ #pragma once #include "CppScripts.h" -class VanityNPC; -class DLUVanityNPC : public CppScripts::Script +class VanityObject; +class DLUVanityTeleportingObject : public CppScripts::Script { public: void OnStartup(Entity* self) override; void OnTimerDone(Entity* self, std::string timerName) override; private: - VanityNPC* m_NPC; + VanityObject* m_Object; + float m_TeleportInterval = 15.0f; }; diff --git a/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp b/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp index f85e0561..40b248f5 100644 --- a/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp +++ b/dScripts/02_server/Enemy/AG/BossSpiderQueenEnemyServer.cpp @@ -85,7 +85,7 @@ void BossSpiderQueenEnemyServer::WithdrawSpider(Entity* self, const bool withdra GameMessages::SendNotifyClientObject(self->GetObjectID(), u"SetColGroup", 10, 0, 0, "", UNASSIGNED_SYSTEM_ADDRESS); //First rotate for anim - NiQuaternion rot = NiQuaternion::IDENTITY; + NiQuaternion rot = NiQuaternionConstant::IDENTITY; controllable->SetStatic(false); @@ -179,7 +179,7 @@ void BossSpiderQueenEnemyServer::SpiderWaveManager(Entity* self) { std::vector spiderEggs{}; - auto spooders = Game::entityManager->GetEntitiesInGroup("EGG"); + auto spooders = Game::entityManager->GetEntitiesInGroup("SpiderEggs"); for (auto spodder : spooders) { spiderEggs.push_back(spodder->GetObjectID()); } @@ -402,7 +402,7 @@ void BossSpiderQueenEnemyServer::OnTimerDone(Entity* self, const std::string tim const auto withdrawn = self->GetBoolean(u"isWithdrawn"); if (!withdrawn) return; - NiQuaternion rot = NiQuaternion::IDENTITY; + NiQuaternion rot = NiQuaternionConstant::IDENTITY; //First rotate for anim controllable->SetStatic(false); @@ -597,12 +597,12 @@ void BossSpiderQueenEnemyServer::OnUpdate(Entity* self) { if (!isWithdrawn) return; - if (controllable->GetRotation() == NiQuaternion::IDENTITY) { + if (controllable->GetRotation() == NiQuaternionConstant::IDENTITY) { return; } controllable->SetStatic(false); - controllable->SetRotation(NiQuaternion::IDENTITY); + controllable->SetRotation(NiQuaternionConstant::IDENTITY); controllable->SetStatic(true); Game::entityManager->SerializeEntity(self); diff --git a/dScripts/02_server/Enemy/CMakeLists.txt b/dScripts/02_server/Enemy/CMakeLists.txt index 62f61772..3c39721c 100644 --- a/dScripts/02_server/Enemy/CMakeLists.txt +++ b/dScripts/02_server/Enemy/CMakeLists.txt @@ -42,7 +42,7 @@ foreach(file ${DSCRIPTS_SOURCES_02_SERVER_ENEMY_WAVES}) set(DSCRIPTS_SOURCES_02_SERVER_ENEMY ${DSCRIPTS_SOURCES_02_SERVER_ENEMY} "Waves/${file}") endforeach() -add_library(dScriptsServerEnemy STATIC ${DSCRIPTS_SOURCES_02_SERVER_ENEMY}) +add_library(dScriptsServerEnemy OBJECT ${DSCRIPTS_SOURCES_02_SERVER_ENEMY}) target_link_libraries(dScriptsServerEnemy dScriptsBase) target_include_directories(dScriptsServerEnemy PUBLIC "." "AG" diff --git a/dScripts/02_server/Enemy/General/BaseEnemyMech.cpp b/dScripts/02_server/Enemy/General/BaseEnemyMech.cpp index c652dab0..8e70d4c3 100644 --- a/dScripts/02_server/Enemy/General/BaseEnemyMech.cpp +++ b/dScripts/02_server/Enemy/General/BaseEnemyMech.cpp @@ -7,6 +7,7 @@ #include "GeneralUtils.h" #include "DestroyableComponent.h" #include "eReplicaComponentType.h" +#include "dNavMesh.h" void BaseEnemyMech::OnStartup(Entity* self) { auto* destroyableComponent = self->GetComponent(); @@ -19,7 +20,7 @@ void BaseEnemyMech::OnDie(Entity* self, Entity* killer) { ControllablePhysicsComponent* controlPhys = static_cast(self->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (!controlPhys) return; - NiPoint3 newLoc = { controlPhys->GetPosition().x, dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(controlPhys->GetPosition()), controlPhys->GetPosition().z }; + NiPoint3 newLoc = { controlPhys->GetPosition().x, dpWorld::GetNavMesh()->GetHeightAtPoint(controlPhys->GetPosition()), controlPhys->GetPosition().z }; EntityInfo info = EntityInfo(); std::vector cfg; diff --git a/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp b/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp index 7fcea9fa..6e19922a 100644 --- a/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp +++ b/dScripts/02_server/Map/AG/AgLaserSensorServer.cpp @@ -13,7 +13,7 @@ void AgLaserSensorServer::OnStartup(Entity* self) { phantomPhysicsComponent->SetPhysicsEffectActive(true); phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::REPULSE); phantomPhysicsComponent->SetDirectionalMultiplier(repelForce); - phantomPhysicsComponent->SetDirection(NiPoint3::UNIT_Y); + phantomPhysicsComponent->SetDirection(NiPoint3Constant::UNIT_Y); } diff --git a/dScripts/02_server/Map/AG/CMakeLists.txt b/dScripts/02_server/Map/AG/CMakeLists.txt index a8315398..e13fd26a 100644 --- a/dScripts/02_server/Map/AG/CMakeLists.txt +++ b/dScripts/02_server/Map/AG/CMakeLists.txt @@ -14,6 +14,6 @@ set(DSCRIPTS_SOURCES_02_SERVER_MAP_AG "NpcCowboyServer.cpp" "NpcPirateServer.cpp") -add_library(dScriptsServerMapAG ${DSCRIPTS_SOURCES_02_SERVER_MAP_AG}) +add_library(dScriptsServerMapAG OBJECT ${DSCRIPTS_SOURCES_02_SERVER_MAP_AG}) target_include_directories(dScriptsServerMapAG PUBLIC ".") target_precompile_headers(dScriptsServerMapAG REUSE_FROM dScriptsBase) diff --git a/dScripts/02_server/Map/AG/NpcCowboyServer.cpp b/dScripts/02_server/Map/AG/NpcCowboyServer.cpp index 6dd212a4..996a99c2 100644 --- a/dScripts/02_server/Map/AG/NpcCowboyServer.cpp +++ b/dScripts/02_server/Map/AG/NpcCowboyServer.cpp @@ -1,6 +1,7 @@ #include "NpcCowboyServer.h" #include "eMissionState.h" #include "InventoryComponent.h" +#include "dZoneManager.h" void NpcCowboyServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { if (missionID != 1880) { @@ -23,4 +24,17 @@ void NpcCowboyServer::OnMissionDialogueOK(Entity* self, Entity* target, int miss } else if (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { inventoryComponent->RemoveItem(14378, 1); } + + // Next up hide or show the samples based on the mission state + int32_t visible = 1; + if (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { + visible = 0; + } + + auto spawners = Game::zoneManager->GetSpawnersByName("PlungerGunTargets"); + for (auto* spawner : spawners) { + for (const auto entity : spawner->GetSpawnedObjectIDs()) + GameMessages::SendNotifyClientObject(entity, u"SetVisibility", visible, 0, + target->GetObjectID(), "", target->GetSystemAddress()); + } } diff --git a/dScripts/02_server/Map/AG/NpcWispServer.cpp b/dScripts/02_server/Map/AG/NpcWispServer.cpp index e3b5398d..e087df24 100644 --- a/dScripts/02_server/Map/AG/NpcWispServer.cpp +++ b/dScripts/02_server/Map/AG/NpcWispServer.cpp @@ -1,9 +1,10 @@ #include "NpcWispServer.h" #include "InventoryComponent.h" -#include "EntityManager.h" +#include "dZoneManager.h" #include "Entity.h" #include "GameMessages.h" #include "eMissionState.h" +#include "Spawner.h" void NpcWispServer::OnMissionDialogueOK(Entity* self, Entity* target, int missionID, eMissionState missionState) { if (missionID != 1849 && missionID != 1883) @@ -25,7 +26,7 @@ void NpcWispServer::OnMissionDialogueOK(Entity* self, Entity* target, int missio } // Next up hide or show the samples based on the mission state - auto visible = 1; + int32_t visible = 1; if (missionState == eMissionState::READY_TO_COMPLETE || missionState == eMissionState::COMPLETE_READY_TO_COMPLETE) { visible = 0; } @@ -35,9 +36,10 @@ void NpcWispServer::OnMissionDialogueOK(Entity* self, Entity* target, int missio : std::vector{ "MaelstromSamples", "MaelstromSamples2ndary1", "MaelstromSamples2ndary2" }; for (const auto& group : groups) { - auto samples = Game::entityManager->GetEntitiesInGroup(group); - for (auto* sample : samples) { - GameMessages::SendNotifyClientObject(sample->GetObjectID(), u"SetVisibility", visible, 0, + auto spawners = Game::zoneManager->GetSpawnersByName(group); + for (const auto* spawner : spawners) { + for (const auto objId : spawner->GetSpawnedObjectIDs()) + GameMessages::SendNotifyClientObject(objId, u"SetVisibility", visible, 0, target->GetObjectID(), "", target->GetSystemAddress()); } } diff --git a/dScripts/02_server/Map/AG_Spider_Queen/CMakeLists.txt b/dScripts/02_server/Map/AG_Spider_Queen/CMakeLists.txt index 65019afe..30d09deb 100644 --- a/dScripts/02_server/Map/AG_Spider_Queen/CMakeLists.txt +++ b/dScripts/02_server/Map/AG_Spider_Queen/CMakeLists.txt @@ -2,7 +2,7 @@ set(DSCRIPTS_SOURCES_02_SERVER_MAP_AG_SPIDER_QUEEN "ZoneAgSpiderQueen.cpp" "SpiderBossTreasureChestServer.cpp") -add_library(dScriptsServerMapAGSpiderQueen ${DSCRIPTS_SOURCES_02_SERVER_MAP_AG_SPIDER_QUEEN}) +add_library(dScriptsServerMapAGSpiderQueen OBJECT ${DSCRIPTS_SOURCES_02_SERVER_MAP_AG_SPIDER_QUEEN}) target_include_directories(dScriptsServerMapAGSpiderQueen PUBLIC ".") target_link_libraries(dScriptsServerMapAGSpiderQueen dScriptsServerMapProperty) target_precompile_headers(dScriptsServerMapAGSpiderQueen REUSE_FROM dScriptsBase) diff --git a/dScripts/02_server/Map/AM/AmDrawBridge.cpp b/dScripts/02_server/Map/AM/AmDrawBridge.cpp index 11d52cd7..cd42f196 100644 --- a/dScripts/02_server/Map/AM/AmDrawBridge.cpp +++ b/dScripts/02_server/Map/AM/AmDrawBridge.cpp @@ -66,7 +66,7 @@ void AmDrawBridge::OnTimerDone(Entity* self, std::string timerName) { return; } - simplePhysicsComponent->SetAngularVelocity(NiPoint3::ZERO); + simplePhysicsComponent->SetAngularVelocity(NiPoint3Constant::ZERO); Game::entityManager->SerializeEntity(bridge); } diff --git a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp index 60b750cf..e88ec468 100644 --- a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp +++ b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp @@ -12,16 +12,12 @@ void AmDropshipComputer::OnStartup(Entity* self) { void AmDropshipComputer::OnUse(Entity* self, Entity* user) { auto* quickBuildComponent = self->GetComponent(); - if (quickBuildComponent == nullptr || quickBuildComponent->GetState() != eQuickBuildState::COMPLETED) { - return; - } + if (!quickBuildComponent || quickBuildComponent->GetState() != eQuickBuildState::COMPLETED) return; auto* missionComponent = user->GetComponent(); auto* inventoryComponent = user->GetComponent(); - if (missionComponent == nullptr || inventoryComponent == nullptr) { - return; - } + if (!missionComponent || !inventoryComponent) return; if (inventoryComponent->GetLotCount(m_NexusTalonDataCard) != 0 || missionComponent->GetMission(979)->GetMissionState() == eMissionState::COMPLETE) { return; @@ -33,14 +29,12 @@ void AmDropshipComputer::OnUse(Entity* self, Entity* user) { void AmDropshipComputer::OnDie(Entity* self, Entity* killer) { const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { - return; - } + const auto pipeNum = GeneralUtils::TryParse(myGroup.substr(10, 1)); + if (!pipeNum) return; const auto pipeGroup = myGroup.substr(0, 10); - const auto nextPipeNum = pipeNum + 1; + const auto nextPipeNum = pipeNum.value() + 1; const auto samePipeSpawners = Game::zoneManager->GetSpawnersByName(myGroup); @@ -70,11 +64,9 @@ void AmDropshipComputer::OnDie(Entity* self, Entity* killer) { } void AmDropshipComputer::OnTimerDone(Entity* self, std::string timerName) { - auto* quickBuildComponent = self->GetComponent(); + const auto* const quickBuildComponent = self->GetComponent(); - if (quickBuildComponent == nullptr) { - return; - } + if (!quickBuildComponent) return; if (timerName == "reset" && quickBuildComponent->GetState() == eQuickBuildState::OPEN) { self->Smash(self->GetObjectID(), eKillType::SILENT); diff --git a/dScripts/02_server/Map/AM/AmSkullkinTower.cpp b/dScripts/02_server/Map/AM/AmSkullkinTower.cpp index 0c0f7515..1eaad3c9 100644 --- a/dScripts/02_server/Map/AM/AmSkullkinTower.cpp +++ b/dScripts/02_server/Map/AM/AmSkullkinTower.cpp @@ -144,13 +144,10 @@ void AmSkullkinTower::OnChildRemoved(Entity* self, Entity* child) { ); for (const auto& mission : missions) { - int32_t missionID = 0; + const auto missionID = GeneralUtils::TryParse(mission); + if (!missionID) continue; - if (!GeneralUtils::TryParse(mission, missionID)) { - continue; - } - - missionIDs.push_back(missionID); + missionIDs.push_back(missionID.value()); } } diff --git a/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp b/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp index 3acc9063..82f1481a 100644 --- a/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp +++ b/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp @@ -12,12 +12,9 @@ void AmTemplateSkillVolume::OnSkillEventFired(Entity* self, Entity* caster, cons const auto missionIDs = GeneralUtils::SplitString(missionIDsVariable, '_'); for (const auto& missionIDStr : missionIDs) { - int32_t missionID = 0; + const auto missionID = GeneralUtils::TryParse(missionIDStr); + if (!missionID) continue; - if (!GeneralUtils::TryParse(missionIDStr, missionID)) { - continue; - } - - missionComponent->ForceProgressTaskType(missionID, 1, 1, false); + missionComponent->ForceProgressTaskType(missionID.value(), 1, 1, false); } } diff --git a/dScripts/02_server/Map/AM/CMakeLists.txt b/dScripts/02_server/Map/AM/CMakeLists.txt index 177b3c45..81a37548 100644 --- a/dScripts/02_server/Map/AM/CMakeLists.txt +++ b/dScripts/02_server/Map/AM/CMakeLists.txt @@ -15,8 +15,10 @@ set(DSCRIPTS_SOURCES_02_SERVER_MAP_AM "AmSkullkinDrillStand.cpp" "AmSkullkinTower.cpp" "AmBlueX.cpp" - "AmTeapotServer.cpp") + "AmTeapotServer.cpp" + "WanderingVendor.cpp" + ) -add_library(dScriptsServerMapAM ${DSCRIPTS_SOURCES_02_SERVER_MAP_AM}) +add_library(dScriptsServerMapAM OBJECT ${DSCRIPTS_SOURCES_02_SERVER_MAP_AM}) target_include_directories(dScriptsServerMapAM PUBLIC ".") target_precompile_headers(dScriptsServerMapAM REUSE_FROM dScriptsBase) diff --git a/dScripts/02_server/Map/AM/WanderingVendor.cpp b/dScripts/02_server/Map/AM/WanderingVendor.cpp new file mode 100644 index 00000000..ae49aa94 --- /dev/null +++ b/dScripts/02_server/Map/AM/WanderingVendor.cpp @@ -0,0 +1,33 @@ +#include "WanderingVendor.h" +#include "MovementAIComponent.h" +#include "ProximityMonitorComponent.h" + +void WanderingVendor::OnStartup(Entity* self) { + auto movementAIComponent = self->GetComponent(); + if (!movementAIComponent) return; + // movementAIComponent->Resume(); + self->SetProximityRadius(10, "playermonitor"); +} + +void WanderingVendor::OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) { + if (status == "ENTER" && entering->IsPlayer()) { + auto movementAIComponent = self->GetComponent(); + if (!movementAIComponent) return; + // movementAIComponent->Pause(); + self->CancelTimer("startWalking"); + } else if (status == "LEAVE") { + auto* proximityMonitorComponent = self->GetComponent(); + if (!proximityMonitorComponent) self->AddComponent(); + + const auto proxObjs = proximityMonitorComponent->GetProximityObjects("playermonitor"); + if (proxObjs.empty()) self->AddTimer("startWalking", 1.5); + } +} + +void WanderingVendor::OnTimerDone(Entity* self, std::string timerName) { + if (timerName == "startWalking") { + auto movementAIComponent = self->GetComponent(); + if (!movementAIComponent) return; + // movementAIComponent->Resume(); + } +} diff --git a/dScripts/02_server/Map/AM/WanderingVendor.h b/dScripts/02_server/Map/AM/WanderingVendor.h new file mode 100644 index 00000000..e0cb1645 --- /dev/null +++ b/dScripts/02_server/Map/AM/WanderingVendor.h @@ -0,0 +1,13 @@ +#ifndef __WANDERINGVENDOR__H__ +#define __WANDERINGVENDOR__H__ + +#include "CppScripts.h" + +class WanderingVendor : public CppScripts::Script { +public: + void OnStartup(Entity* self) override; + void OnProximityUpdate(Entity* self, Entity* entering, std::string name, std::string status) override; + void OnTimerDone(Entity* self, std::string timerName) override; +}; + +#endif //!__WANDERINGVENDOR__H__ diff --git a/dScripts/02_server/Map/CMakeLists.txt b/dScripts/02_server/Map/CMakeLists.txt index a5fb5b03..33bd9bd4 100644 --- a/dScripts/02_server/Map/CMakeLists.txt +++ b/dScripts/02_server/Map/CMakeLists.txt @@ -13,17 +13,33 @@ add_subdirectory(SS) add_subdirectory(VE) add_library(dScriptsServerMap INTERFACE) -target_link_libraries(dScriptsServerMap INTERFACE - dScriptsServerMapAG - dScriptsServerMapAGSpiderQueen - dScriptsServerMapAM - dScriptsServerMapFV - dScriptsServerMapGeneral - dScriptsServerMapGF - dScriptsServerMapNJHub - dScriptsServerMapNS - dScriptsServerMapNT - dScriptsServerMapPR - dScriptsServerMapProperty - dScriptsServerMapSS - dScriptsServerMapVE) +target_sources(dScriptsServerMap INTERFACE + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ +) +target_include_directories(dScriptsServerMap INTERFACE + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ +) diff --git a/dScripts/02_server/Map/FV/CMakeLists.txt b/dScripts/02_server/Map/FV/CMakeLists.txt index 6f774c98..9746a5dd 100644 --- a/dScripts/02_server/Map/FV/CMakeLists.txt +++ b/dScripts/02_server/Map/FV/CMakeLists.txt @@ -11,6 +11,6 @@ foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_FV_RACING}) set(DSCRIPTS_SOURCES_02_SERVER_MAP_FV ${DSCRIPTS_SOURCES_02_SERVER_MAP_FV} "Racing/${file}") endforeach() -add_library(dScriptsServerMapFV ${DSCRIPTS_SOURCES_02_SERVER_MAP_FV}) +add_library(dScriptsServerMapFV OBJECT ${DSCRIPTS_SOURCES_02_SERVER_MAP_FV}) target_include_directories(dScriptsServerMapFV PUBLIC "." "Racing") target_precompile_headers(dScriptsServerMapFV REUSE_FROM dScriptsBase) diff --git a/dScripts/02_server/Map/GF/CMakeLists.txt b/dScripts/02_server/Map/GF/CMakeLists.txt index 45ec871a..c6a95300 100644 --- a/dScripts/02_server/Map/GF/CMakeLists.txt +++ b/dScripts/02_server/Map/GF/CMakeLists.txt @@ -4,6 +4,6 @@ set(DSCRIPTS_SOURCES_02_SERVER_MAP_GF "MastTeleport.cpp" "SpawnLionServer.cpp") -add_library(dScriptsServerMapGF ${DSCRIPTS_SOURCES_02_SERVER_MAP_GF}) +add_library(dScriptsServerMapGF OBJECT ${DSCRIPTS_SOURCES_02_SERVER_MAP_GF}) target_include_directories(dScriptsServerMapGF PUBLIC ".") target_precompile_headers(dScriptsServerMapGF REUSE_FROM dScriptsBase) diff --git a/dScripts/02_server/Map/GF/MastTeleport.cpp b/dScripts/02_server/Map/GF/MastTeleport.cpp index 5a40507d..e181779e 100644 --- a/dScripts/02_server/Map/GF/MastTeleport.cpp +++ b/dScripts/02_server/Map/GF/MastTeleport.cpp @@ -81,7 +81,7 @@ void MastTeleport::OnTimerDone(Entity* self, std::string timerName) { GameMessages::SendOrientToAngle(playerId, true, rads, player->GetSystemAddress()); - GameMessages::SendTeleport(playerId, position, NiQuaternion::IDENTITY, player->GetSystemAddress()); + GameMessages::SendTeleport(playerId, position, NiQuaternionConstant::IDENTITY, player->GetSystemAddress()); GameMessages::SendSetStunned(playerId, eStateChangeType::POP, player->GetSystemAddress(), LWOOBJID_EMPTY, true, true, true, true, true, true, true diff --git a/dScripts/02_server/Map/General/CMakeLists.txt b/dScripts/02_server/Map/General/CMakeLists.txt index 4fe5aae8..3379e5b0 100644 --- a/dScripts/02_server/Map/General/CMakeLists.txt +++ b/dScripts/02_server/Map/General/CMakeLists.txt @@ -27,6 +27,6 @@ foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_GENERAL_NINJAGO}) set(DSCRIPTS_SOURCES_02_SERVER_MAP_GENERAL ${DSCRIPTS_SOURCES_02_SERVER_MAP_GENERAL} "Ninjago/${file}") endforeach() -add_library(dScriptsServerMapGeneral ${DSCRIPTS_SOURCES_02_SERVER_MAP_GENERAL}) +add_library(dScriptsServerMapGeneral OBJECT ${DSCRIPTS_SOURCES_02_SERVER_MAP_GENERAL}) target_include_directories(dScriptsServerMapGeneral PUBLIC "." "Ninjago") target_precompile_headers(dScriptsServerMapGeneral REUSE_FROM dScriptsBase) diff --git a/dScripts/02_server/Map/General/PetDigServer.cpp b/dScripts/02_server/Map/General/PetDigServer.cpp index 0ea78e4f..a55c2f29 100644 --- a/dScripts/02_server/Map/General/PetDigServer.cpp +++ b/dScripts/02_server/Map/General/PetDigServer.cpp @@ -107,7 +107,7 @@ void PetDigServer::HandleXBuildDig(const Entity* self, Entity* owner, Entity* pe return; auto* playerEntity = Game::entityManager->GetEntity(playerID); - if (!playerEntity || !playerEntity->GetParentUser() || !playerEntity->GetParentUser()->GetLastUsedChar()) + if (!playerEntity || !playerEntity->GetCharacter()) return; auto* player = playerEntity->GetCharacter(); diff --git a/dScripts/02_server/Map/General/QbEnemyStunner.cpp b/dScripts/02_server/Map/General/QbEnemyStunner.cpp index 8291f409..2238c410 100644 --- a/dScripts/02_server/Map/General/QbEnemyStunner.cpp +++ b/dScripts/02_server/Map/General/QbEnemyStunner.cpp @@ -17,12 +17,12 @@ void QbEnemyStunner::OnQuickBuildComplete(Entity* self, Entity* target) { if (!skillComponent) return; // Get the skill IDs of this object. - CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable(); + CDObjectSkillsTable* skillsTable = CDClientManager::GetTable(); auto skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == self->GetLOT()); }); std::map skillBehaviorMap; // For each skill, cast it with the associated behavior ID. for (auto skill : skills) { - CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::GetTable(); CDSkillBehavior behaviorData = skillBehaviorTable->GetSkillByID(skill.skillID); skillBehaviorMap.insert(std::make_pair(skill.skillID, behaviorData.behaviorID)); diff --git a/dScripts/02_server/Map/General/StoryBoxInteractServer.cpp b/dScripts/02_server/Map/General/StoryBoxInteractServer.cpp index 9a1a4908..4ad78d6a 100644 --- a/dScripts/02_server/Map/General/StoryBoxInteractServer.cpp +++ b/dScripts/02_server/Map/General/StoryBoxInteractServer.cpp @@ -6,7 +6,7 @@ #include "Entity.h" void StoryBoxInteractServer::OnUse(Entity* self, Entity* user) { - if (self->GetVar(u"hasCustomText")) { + if (self->HasVar(u"customText")) { const auto& customText = self->GetVar(u"customText"); { @@ -29,15 +29,19 @@ void StoryBoxInteractServer::OnUse(Entity* self, Entity* user) { return; } + if (!self->HasVar(u"storyText")) return; const auto storyText = self->GetVarAsString(u"storyText"); + if (storyText.length() > 2) { + auto storyValue = GeneralUtils::TryParse(storyText.substr(storyText.length() - 2)); + if(!storyValue) return; + int32_t boxFlag = self->GetVar(u"altFlagID"); + if (boxFlag <= 0) { + boxFlag = (10000 + Game::server->GetZoneID() + storyValue.value()); + } - int32_t boxFlag = self->GetVar(u"altFlagID"); - if (boxFlag <= 0) { - boxFlag = (10000 + Game::server->GetZoneID() + std::stoi(storyText.substr(storyText.length() - 2))); - } - - if (user->GetCharacter()->GetPlayerFlag(boxFlag) == false) { - user->GetCharacter()->SetPlayerFlag(boxFlag, true); - GameMessages::SendFireEventClientSide(self->GetObjectID(), user->GetSystemAddress(), u"achieve", LWOOBJID_EMPTY, 0, -1, LWOOBJID_EMPTY); + if (user->GetCharacter()->GetPlayerFlag(boxFlag) == false) { + user->GetCharacter()->SetPlayerFlag(boxFlag, true); + GameMessages::SendFireEventClientSide(self->GetObjectID(), user->GetSystemAddress(), u"achieve", LWOOBJID_EMPTY, 0, -1, LWOOBJID_EMPTY); + } } } diff --git a/dScripts/02_server/Map/NS/CMakeLists.txt b/dScripts/02_server/Map/NS/CMakeLists.txt index 4927f0c8..6be99dab 100644 --- a/dScripts/02_server/Map/NS/CMakeLists.txt +++ b/dScripts/02_server/Map/NS/CMakeLists.txt @@ -10,6 +10,6 @@ foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_NS_WAVES}) set(DSCRIPTS_SOURCES_02_SERVER_MAP_NS ${DSCRIPTS_SOURCES_02_SERVER_MAP_NS} "Waves/${file}") endforeach() -add_library(dScriptsServerMapNS ${DSCRIPTS_SOURCES_02_SERVER_MAP_NS}) +add_library(dScriptsServerMapNS OBJECT ${DSCRIPTS_SOURCES_02_SERVER_MAP_NS}) target_include_directories(dScriptsServerMapNS PUBLIC "." "Waves") target_precompile_headers(dScriptsServerMapNS REUSE_FROM dScriptsBase) diff --git a/dScripts/02_server/Map/NT/CMakeLists.txt b/dScripts/02_server/Map/NT/CMakeLists.txt index 49c6a5ae..5ab3307c 100644 --- a/dScripts/02_server/Map/NT/CMakeLists.txt +++ b/dScripts/02_server/Map/NT/CMakeLists.txt @@ -27,6 +27,6 @@ set(DSCRIPTS_SOURCES_02_SERVER_MAP_NT "NtBcSubmitServer.cpp" "NtNaomiBreadcrumbServer.cpp") -add_library(dScriptsServerMapNT ${DSCRIPTS_SOURCES_02_SERVER_MAP_NT}) +add_library(dScriptsServerMapNT OBJECT ${DSCRIPTS_SOURCES_02_SERVER_MAP_NT}) target_include_directories(dScriptsServerMapNT PUBLIC ".") target_precompile_headers(dScriptsServerMapNT REUSE_FROM dScriptsBase) diff --git a/dScripts/02_server/Map/NT/NtCombatChallengeDummy.cpp b/dScripts/02_server/Map/NT/NtCombatChallengeDummy.cpp index 5be5a9b3..13dd73c8 100644 --- a/dScripts/02_server/Map/NT/NtCombatChallengeDummy.cpp +++ b/dScripts/02_server/Map/NT/NtCombatChallengeDummy.cpp @@ -1,5 +1,6 @@ #include "NtCombatChallengeDummy.h" #include "EntityManager.h" +#include "Entity.h" void NtCombatChallengeDummy::OnDie(Entity* self, Entity* killer) { const auto challengeObjectID = self->GetVar(u"challengeObjectID"); @@ -7,9 +8,7 @@ void NtCombatChallengeDummy::OnDie(Entity* self, Entity* killer) { auto* challengeObject = Game::entityManager->GetEntity(challengeObjectID); if (challengeObject != nullptr) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) { - script->OnDie(challengeObject, killer); - } + challengeObject->GetScript()->OnDie(challengeObject, killer); } } @@ -19,8 +18,6 @@ void NtCombatChallengeDummy::OnHitOrHealResult(Entity* self, Entity* attacker, i auto* challengeObject = Game::entityManager->GetEntity(challengeObjectID); if (challengeObject != nullptr) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) { - script->OnHitOrHealResult(challengeObject, attacker, damage); - } + challengeObject->GetScript()->OnHitOrHealResult(challengeObject, attacker, damage); } } diff --git a/dScripts/02_server/Map/NT/NtCombatChallengeExplodingDummy.cpp b/dScripts/02_server/Map/NT/NtCombatChallengeExplodingDummy.cpp index 4ae2b335..c384b26d 100644 --- a/dScripts/02_server/Map/NT/NtCombatChallengeExplodingDummy.cpp +++ b/dScripts/02_server/Map/NT/NtCombatChallengeExplodingDummy.cpp @@ -9,9 +9,7 @@ void NtCombatChallengeExplodingDummy::OnDie(Entity* self, Entity* killer) { auto* challengeObject = Game::entityManager->GetEntity(challengeObjectID); if (challengeObject != nullptr) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) { - script->OnDie(challengeObject, killer); - } + challengeObject->GetScript()->OnDie(challengeObject, killer); } } @@ -32,9 +30,7 @@ void NtCombatChallengeExplodingDummy::OnHitOrHealResult(Entity* self, Entity* at auto* challengeObject = Game::entityManager->GetEntity(challengeObjectID); if (challengeObject != nullptr) { - for (CppScripts::Script* script : CppScripts::GetEntityScripts(challengeObject)) { - script->OnHitOrHealResult(challengeObject, attacker, damage); - } + challengeObject->GetScript()->OnHitOrHealResult(challengeObject, attacker, damage); } auto skillComponent = self->GetComponent(); if (skillComponent != nullptr) { diff --git a/dScripts/02_server/Map/PR/CMakeLists.txt b/dScripts/02_server/Map/PR/CMakeLists.txt index 13b3fd35..8de0e71d 100644 --- a/dScripts/02_server/Map/PR/CMakeLists.txt +++ b/dScripts/02_server/Map/PR/CMakeLists.txt @@ -3,6 +3,6 @@ set(DSCRIPTS_SOURCES_02_SERVER_MAP_PR "PrSeagullFly.cpp" "SpawnGryphonServer.cpp") -add_library(dScriptsServerMapPR ${DSCRIPTS_SOURCES_02_SERVER_MAP_PR}) +add_library(dScriptsServerMapPR OBJECT ${DSCRIPTS_SOURCES_02_SERVER_MAP_PR}) target_include_directories(dScriptsServerMapPR PUBLIC ".") target_precompile_headers(dScriptsServerMapPR REUSE_FROM dScriptsBase) diff --git a/dScripts/02_server/Map/Property/CMakeLists.txt b/dScripts/02_server/Map/Property/CMakeLists.txt index 52b91d0b..b4085cfb 100644 --- a/dScripts/02_server/Map/Property/CMakeLists.txt +++ b/dScripts/02_server/Map/Property/CMakeLists.txt @@ -19,7 +19,7 @@ foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY_NS_MED}) set(DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY ${DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY} "NS_Med/${file}") endforeach() -add_library(dScriptsServerMapProperty ${DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY}) +add_library(dScriptsServerMapProperty OBJECT ${DSCRIPTS_SOURCES_02_SERVER_MAP_PROPERTY}) target_precompile_headers(dScriptsServerMapProperty REUSE_FROM dScriptsBase) target_include_directories(dScriptsServerMapProperty PUBLIC "." "AG_Med" diff --git a/dScripts/02_server/Map/SS/CMakeLists.txt b/dScripts/02_server/Map/SS/CMakeLists.txt index ed6a7596..894d4ece 100644 --- a/dScripts/02_server/Map/SS/CMakeLists.txt +++ b/dScripts/02_server/Map/SS/CMakeLists.txt @@ -1,6 +1,6 @@ set(DSCRIPTS_SOURCES_02_SERVER_MAP_SS "SsModularBuildServer.cpp") -add_library(dScriptsServerMapSS ${DSCRIPTS_SOURCES_02_SERVER_MAP_SS}) +add_library(dScriptsServerMapSS OBJECT ${DSCRIPTS_SOURCES_02_SERVER_MAP_SS}) target_include_directories(dScriptsServerMapSS PUBLIC ".") target_precompile_headers(dScriptsServerMapSS REUSE_FROM dScriptsBase) diff --git a/dScripts/02_server/Map/VE/CMakeLists.txt b/dScripts/02_server/Map/VE/CMakeLists.txt index 2dbcaaff..8be55c9f 100644 --- a/dScripts/02_server/Map/VE/CMakeLists.txt +++ b/dScripts/02_server/Map/VE/CMakeLists.txt @@ -3,6 +3,6 @@ set(DSCRIPTS_SOURCES_02_SERVER_MAP_VE "VeEpsilonServer.cpp" "VeBricksampleServer.cpp") -add_library(dScriptsServerMapVE ${DSCRIPTS_SOURCES_02_SERVER_MAP_VE}) +add_library(dScriptsServerMapVE OBJECT ${DSCRIPTS_SOURCES_02_SERVER_MAP_VE}) target_include_directories(dScriptsServerMapVE PUBLIC ".") target_precompile_headers(dScriptsServerMapVE REUSE_FROM dScriptsBase) diff --git a/dScripts/02_server/Map/njhub/CMakeLists.txt b/dScripts/02_server/Map/njhub/CMakeLists.txt index 0f287ce3..94d99867 100644 --- a/dScripts/02_server/Map/njhub/CMakeLists.txt +++ b/dScripts/02_server/Map/njhub/CMakeLists.txt @@ -28,7 +28,7 @@ foreach(file ${DSCRIPTS_SOURCES_02_SERVER_MAP_NJHUB_BOSS_INSTANCE}) set(DSCRIPTS_SOURCES_02_SERVER_MAP_NJHUB ${DSCRIPTS_SOURCES_02_SERVER_MAP_NJHUB} "boss_instance/${file}") endforeach() -add_library(dScriptsServerMapNJHub ${DSCRIPTS_SOURCES_02_SERVER_MAP_NJHUB}) +add_library(dScriptsServerMapNJHub OBJECT ${DSCRIPTS_SOURCES_02_SERVER_MAP_NJHUB}) target_include_directories(dScriptsServerMapNJHub PUBLIC "." "boss_instance") target_link_libraries(dScriptsServerMapNJHub dScriptsServerPets diff --git a/dScripts/02_server/Pets/CMakeLists.txt b/dScripts/02_server/Pets/CMakeLists.txt index 79123ebe..aa1d0e3f 100644 --- a/dScripts/02_server/Pets/CMakeLists.txt +++ b/dScripts/02_server/Pets/CMakeLists.txt @@ -3,7 +3,7 @@ set(DSCRIPTS_SOURCES_02_SERVER_PETS "PetFromObjectServer.cpp" "DamagingPets.cpp") -add_library(dScriptsServerPets STATIC ${DSCRIPTS_SOURCES_02_SERVER_PETS}) +add_library(dScriptsServerPets OBJECT ${DSCRIPTS_SOURCES_02_SERVER_PETS}) target_include_directories(dScriptsServerPets PUBLIC ".") target_precompile_headers(dScriptsServerPets REUSE_FROM dScriptsBase) diff --git a/dScripts/02_server/Pets/PetFromDigServer.cpp b/dScripts/02_server/Pets/PetFromDigServer.cpp index 525f3e94..33bab32a 100644 --- a/dScripts/02_server/Pets/PetFromDigServer.cpp +++ b/dScripts/02_server/Pets/PetFromDigServer.cpp @@ -40,6 +40,6 @@ void PetFromDigServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, eP return; // TODO: Remove custom group? // Command the pet to the player as it may otherwise go to its spawn point which is non existant - // petComponent->Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 6, 202, true); + // petComponent->Command(NiPoint3Constant::ZERO, LWOOBJID_EMPTY, 6, 202, true); } } diff --git a/dScripts/CMakeLists.txt b/dScripts/CMakeLists.txt index b3fb7d44..29f04be3 100644 --- a/dScripts/CMakeLists.txt +++ b/dScripts/CMakeLists.txt @@ -11,24 +11,27 @@ set(DSCRIPTS_SOURCES "InvalidScript.cpp" "NPCAddRemoveItem.cpp" "NtFactionSpyServer.cpp" - "ScriptComponent.cpp" "ScriptedPowerupSpawner.cpp" "SpawnPetBaseServer.cpp") link_libraries(dDatabase dPhysics) -add_library(dScriptsBase STATIC ${DSCRIPTS_SOURCES}) -target_include_directories(dScriptsBase PUBLIC .) -target_link_libraries(dScriptsBase - INTERFACE dGameBase) +add_library(dScriptsBase OBJECT ${DSCRIPTS_SOURCES}) +target_link_libraries(dScriptsBase INTERFACE dGameBase dComponents) target_precompile_headers(dScriptsBase PRIVATE ${HEADERS_DGAME}) include_directories( - ${PROJECT_SOURCE_DIR}/dScripts - ${PROJECT_SOURCE_DIR}/dGame + "${PROJECT_SOURCE_DIR}/dScripts" + "${PROJECT_SOURCE_DIR}/dGame" + "${PROJECT_SOURCE_DIR}/dGame/dComponents" # e.g. ScriptedActivityComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dGameMessages" # e.g. direct ActivityManager + "${PROJECT_SOURCE_DIR}/dGame/dUtilities" # e.g. direct ActivityManager + "${PROJECT_SOURCE_DIR}/dGame/dEntity" # via dZoneManager.h + "${PROJECT_SOURCE_DIR}/dGame/dMission" # via MissionComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dBehaviors" # viaInventoryComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dInventory" # via InventoryComponent.h + "${PROJECT_SOURCE_DIR}/dZoneManager" ) -link_libraries(dScriptsBase) -# dComponents add_subdirectory(02_server) add_subdirectory(ai) @@ -37,14 +40,22 @@ add_subdirectory(EquipmentScripts) add_subdirectory(EquipmentTriggers) add_subdirectory(zone) -add_library(dScripts STATIC "CppScripts.cpp") +add_library(dScripts STATIC + $ + $ + $ + $ + $ + "CppScripts.cpp" +) +target_link_libraries(dScripts PRIVATE dScriptsAI dScriptsServer) +target_include_directories(dScripts PRIVATE + $ + $ + $ + $ + $ + $ + $ +) target_precompile_headers(dScripts REUSE_FROM dScriptsBase) -target_include_directories(dScripts PUBLIC ".") -target_link_libraries(dScripts - dScriptsBase - dScriptsServer - dScriptsAI - dScriptsClient - dScriptsEquipmentScripts - dScriptsEquipmentTriggers - dScriptsZone) diff --git a/dScripts/ChooseYourDestinationNsToNt.cpp b/dScripts/ChooseYourDestinationNsToNt.cpp index f9ca0a79..b736883c 100644 --- a/dScripts/ChooseYourDestinationNsToNt.cpp +++ b/dScripts/ChooseYourDestinationNsToNt.cpp @@ -41,11 +41,9 @@ void ChooseYourDestinationNsToNt::SetDestination(Entity* self, Entity* player) { void ChooseYourDestinationNsToNt::BaseChoiceBoxRespond(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { if (button != -1) { const auto newMapStr = GeneralUtils::UTF16ToWTF8(buttonIdentifier).substr(7, -1); - - int32_t newMap = 0; - if (!GeneralUtils::TryParse(newMapStr, newMap)) { - return; - } + const auto newMap = GeneralUtils::TryParse(newMapStr); + + if (!newMap) return; std::u16string strText = u""; @@ -56,7 +54,7 @@ void ChooseYourDestinationNsToNt::BaseChoiceBoxRespond(Entity* self, Entity* sen } self->SetVar(u"teleportString", strText); - self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap)); + self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap.value())); GameMessages::SendDisplayMessageBox(sender->GetObjectID(), true, self->GetObjectID(), u"TransferBox", 0, strText, u"", sender->GetSystemAddress()); } else { diff --git a/dScripts/CppScripts.cpp b/dScripts/CppScripts.cpp index 071bd7a3..9018c3f4 100644 --- a/dScripts/CppScripts.cpp +++ b/dScripts/CppScripts.cpp @@ -216,7 +216,7 @@ #include "NtNaomiBreadcrumbServer.h" // DLU Scripts -#include "DLUVanityNPC.h" +#include "DLUVanityTeleportingObject.h" // AM Scripts #include "AmConsoleTeleportServer.h" @@ -240,6 +240,7 @@ #include "AmDarklingDragon.h" #include "AmBlueX.h" #include "AmTeapotServer.h" +#include "WanderingVendor.h" // NJ Scripts #include "NjGarmadonCelebration.h" @@ -317,18 +318,22 @@ #include "WildNinjaSensei.h" #include "WildNinjaBricks.h" #include "VisToggleNotifierServer.h" +#include "LupGenericInteract.h" +#include "WblRobotCitizen.h" namespace { - InvalidScript* invalidToReturn = new InvalidScript(); + // This is in the translation unit instead of the header to prevent wierd linker errors + InvalidScript* const InvalidToReturn = new InvalidScript(); std::map m_Scripts; }; -CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scriptName) { - if (m_Scripts.find(scriptName) != m_Scripts.end()) { - return m_Scripts[scriptName]; +CppScripts::Script* const CppScripts::GetScript(Entity* parent, const std::string& scriptName) { + auto itr = m_Scripts.find(scriptName); + if (itr != m_Scripts.end()) { + return itr->second; } - Script* script = invalidToReturn; + Script* script = InvalidToReturn; //VE / AG: if (scriptName == "scripts\\ai\\AG\\L_AG_SHIP_PLAYER_DEATH_TRIGGER.lua") @@ -547,7 +552,7 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr //PR: else if (scriptName == "scripts\\client\\ai\\PR\\L_PR_WHISTLE.lua") script = new PrWhistle(); - else if (scriptName == "scripts\\02_server\\Map\\PR\\L_PR_SEAGULL_FLY.lua") + if (scriptName == "scripts\\02_server\\Map\\PR\\L_PR_SEAGULL_FLY.lua") script = new PrSeagullFly(); else if (scriptName == "scripts\\ai\\PETS\\L_HYDRANT_SMASHABLE.lua") script = new HydrantSmashable(); @@ -642,6 +647,8 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new MailBoxServer(); else if (scriptName == "scripts\\ai\\ACT\\L_ACT_MINE.lua") script = new ActMine(); + else if (scriptName == "scripts\\02_server\\Map\\AM\\L_WANDERING_VENDOR.lua") + script = new WanderingVendor(); //Racing: else if (scriptName == "scripts\\ai\\RACING\\OBJECTS\\RACE_IMAGINE_CRATE_SERVER.lua") @@ -726,7 +733,7 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new NTNaomiDirtServer(); //AM: - else if (scriptName == "scripts\\02_server\\Map\\AM\\L_AM_CONSOLE_TELEPORT_SERVER.lua") + if (scriptName == "scripts\\02_server\\Map\\AM\\L_AM_CONSOLE_TELEPORT_SERVER.lua") script = new AmConsoleTeleportServer(); else if (scriptName == "scripts\\02_server\\Map\\AM\\L_RANDOM_SPAWNER_FIN.lua") script = new RandomSpawnerFin(); @@ -806,7 +813,7 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new Lieutenant(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_RAIN_OF_ARROWS.lua") script = new RainOfArrows(); - else if (scriptName == "scripts\\02_server\\Map\\njhub\\L_CAVE_PRISON_CAGE.lua") + if (scriptName == "scripts\\02_server\\Map\\njhub\\L_CAVE_PRISON_CAGE.lua") script = new CavePrisonCage(); else if (scriptName == "scripts\\02_server\\Map\\njhub\\boss_instance\\L_MONASTERY_BOSS_INSTANCE_SERVER.lua") script = new NjMonastryBossInstance(); @@ -834,8 +841,8 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new NjNyaMissionitems(); //DLU: - else if (scriptName == "scripts\\02_server\\DLU\\DLUVanityNPC.lua") - script = new DLUVanityNPC(); + else if (scriptName == "scripts\\02_server\\DLU\\DLUVanityTeleportingObject.lua") + script = new DLUVanityTeleportingObject(); // Survival minigame else if (scriptName == "scripts\\02_server\\Enemy\\Survival\\L_AG_SURVIVAL_STROMBIE.lua") @@ -938,10 +945,14 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr script = new WildNinjaStudent(); else if (scriptName == "scripts\\ai\\WILD\\L_WILD_NINJA_SENSEI.lua") script = new WildNinjaSensei(); + else if (scriptName == "scripts\\ai\\WILD\\L_LUP_generic_interact.lua") + script = new LupGenericInteract(); + else if (scriptName.rfind("scripts\\zone\\LUPs\\RobotCity Intro\\WBL_RCIntro_RobotCitizen", 0) == 0) + script = new WblRobotCitizen(); // handle invalid script reporting if the path is greater than zero and it's not an ignored script // information not really needed for sys admins but is for developers - else if (script == invalidToReturn) { + else if (script == InvalidToReturn) { if ((scriptName.length() > 0) && !((scriptName == "scripts\\02_server\\Enemy\\General\\L_SUSPEND_LUA_AI.lua") || (scriptName == "scripts\\02_server\\Enemy\\General\\L_BASE_ENEMY_SPIDERLING.lua") || (scriptName =="scripts\\ai\\FV\\L_ACT_NINJA_STUDENT.lua") || @@ -954,13 +965,6 @@ CppScripts::Script* CppScripts::GetScript(Entity* parent, const std::string& scr return script; } -std::vector CppScripts::GetEntityScripts(Entity* entity) { - std::vector scripts; - std::vector comps = entity->GetScriptComponents(); - for (ScriptComponent* scriptComp : comps) { - if (scriptComp != nullptr) { - scripts.push_back(scriptComp->GetScript()); - } - } - return scripts; +CppScripts::Script* const CppScripts::GetInvalidScript() { + return InvalidToReturn; } diff --git a/dScripts/CppScripts.h b/dScripts/CppScripts.h index d005a14a..8d3b3b5d 100644 --- a/dScripts/CppScripts.h +++ b/dScripts/CppScripts.h @@ -357,6 +357,10 @@ namespace CppScripts { virtual void OnRequestActivityExit(Entity* sender, LWOOBJID player, bool canceled){}; }; - Script* GetScript(Entity* parent, const std::string& scriptName); - std::vector GetEntityScripts(Entity* entity); + Script* const GetScript(Entity* parent, const std::string& scriptName); + + // Get the invalid script. Would be a static variable of the namespace, but that would be + // more cluttery to use. Also this allows us to control where this invalid script is defined and initialized + // since we dont want anyone externally modifying it. + Script* const GetInvalidScript(); }; diff --git a/dScripts/EquipmentScripts/CMakeLists.txt b/dScripts/EquipmentScripts/CMakeLists.txt index 08966e08..60f31503 100644 --- a/dScripts/EquipmentScripts/CMakeLists.txt +++ b/dScripts/EquipmentScripts/CMakeLists.txt @@ -8,6 +8,6 @@ set(DSCRIPTS_SOURCES_EQUIPMENTSCRIPTS "FireFirstSkillonStartup.cpp" "StunImmunity.cpp") -add_library(dScriptsEquipmentScripts STATIC ${DSCRIPTS_SOURCES_EQUIPMENTSCRIPTS}) +add_library(dScriptsEquipmentScripts OBJECT ${DSCRIPTS_SOURCES_EQUIPMENTSCRIPTS}) target_include_directories(dScriptsEquipmentScripts PUBLIC ".") target_precompile_headers(dScriptsEquipmentScripts REUSE_FROM dScriptsBase) diff --git a/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp b/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp index 389f3621..0220711d 100644 --- a/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp +++ b/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp @@ -11,12 +11,12 @@ void FireFirstSkillonStartup::OnStartup(Entity* self) { if (!skillComponent) return; // Get the skill IDs of this object. - CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable(); + CDObjectSkillsTable* skillsTable = CDClientManager::GetTable(); std::vector skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == self->GetLOT()); }); // For each skill, cast it with the associated behavior ID. for (auto skill : skills) { - CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::GetTable(); CDSkillBehavior behaviorData = skillBehaviorTable->GetSkillByID(skill.skillID); // Should parent entity be null, make the originator self. diff --git a/dScripts/EquipmentTriggers/CMakeLists.txt b/dScripts/EquipmentTriggers/CMakeLists.txt index cb6e81a8..af0a1425 100644 --- a/dScripts/EquipmentTriggers/CMakeLists.txt +++ b/dScripts/EquipmentTriggers/CMakeLists.txt @@ -1,6 +1,6 @@ set(DSCRIPTS_SOURCES_EQUIPMENTTRIGGERSSCRIPTS "CoilBackpackBase.cpp") -add_library(dScriptsEquipmentTriggers STATIC ${DSCRIPTS_SOURCES_EQUIPMENTTRIGGERSSCRIPTS}) +add_library(dScriptsEquipmentTriggers OBJECT ${DSCRIPTS_SOURCES_EQUIPMENTTRIGGERSSCRIPTS}) target_include_directories(dScriptsEquipmentTriggers PUBLIC ".") target_precompile_headers(dScriptsEquipmentTriggers REUSE_FROM dScriptsBase) diff --git a/dScripts/ai/ACT/CMakeLists.txt b/dScripts/ai/ACT/CMakeLists.txt index 5071afa0..680c5e4c 100644 --- a/dScripts/ai/ACT/CMakeLists.txt +++ b/dScripts/ai/ACT/CMakeLists.txt @@ -9,6 +9,6 @@ foreach(file ${DSCRIPTS_SOURCES_AI_ACT_FOOTRACE}) set(DSCRIPTS_SOURCES_AI_ACT ${DSCRIPTS_SOURCES_AI_ACT} "FootRace/${file}") endforeach() -add_library(dScriptsAiAct STATIC ${DSCRIPTS_SOURCES_AI_ACT}) +add_library(dScriptsAiAct OBJECT ${DSCRIPTS_SOURCES_AI_ACT}) target_include_directories(dScriptsAiAct PUBLIC "." "FootRace") target_precompile_headers(dScriptsAiAct REUSE_FROM dScriptsBase) diff --git a/dScripts/ai/AG/CMakeLists.txt b/dScripts/ai/AG/CMakeLists.txt index e031e386..e74aac78 100644 --- a/dScripts/ai/AG/CMakeLists.txt +++ b/dScripts/ai/AG/CMakeLists.txt @@ -16,6 +16,6 @@ set(DSCRIPTS_SOURCES_AI_AG "AgStagePlatforms.cpp" "AgQbWall.cpp") -add_library(dScriptsAiAG STATIC ${DSCRIPTS_SOURCES_AI_AG}) +add_library(dScriptsAiAG OBJECT ${DSCRIPTS_SOURCES_AI_AG}) target_include_directories(dScriptsAiAG PUBLIC ".") target_precompile_headers(dScriptsAiAG REUSE_FROM dScriptsBase) diff --git a/dScripts/ai/CMakeLists.txt b/dScripts/ai/CMakeLists.txt index 7e94cd34..354bda21 100644 --- a/dScripts/ai/CMakeLists.txt +++ b/dScripts/ai/CMakeLists.txt @@ -15,18 +15,34 @@ add_subdirectory(SPEC) add_subdirectory(WILD) add_library(dScriptsAI INTERFACE) -target_link_libraries(dScriptsAI INTERFACE - dScriptsAiAct - dScriptsAiAG - dScriptsAiFV - dScriptsAiGeneral - dScriptsAiGF - dScriptsAiMinigame - dScriptsAiNP - dScriptsAiNS - dScriptsAiPets - dScriptsAiProperty - dScriptsAiRacing - dScriptsAiSpec - dScriptsAiWild +target_sources(dScriptsAI INTERFACE + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ +) + +target_include_directories(dScriptsAI INTERFACE + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ + $ ) diff --git a/dScripts/ai/FV/CMakeLists.txt b/dScripts/ai/FV/CMakeLists.txt index 55c68a27..535a02a6 100644 --- a/dScripts/ai/FV/CMakeLists.txt +++ b/dScripts/ai/FV/CMakeLists.txt @@ -18,7 +18,7 @@ set(DSCRIPTS_SOURCES_AI_FV "FvMaelstromGeyser.cpp" "TriggerGas.cpp") -add_library(dScriptsAiFV STATIC ${DSCRIPTS_SOURCES_AI_FV}) +add_library(dScriptsAiFV OBJECT ${DSCRIPTS_SOURCES_AI_FV}) target_include_directories(dScriptsAiFV PUBLIC ".") target_precompile_headers(dScriptsAiFV REUSE_FROM dScriptsBase) diff --git a/dScripts/ai/FV/FvBrickPuzzleServer.cpp b/dScripts/ai/FV/FvBrickPuzzleServer.cpp index e1f1ac88..f8601e3f 100644 --- a/dScripts/ai/FV/FvBrickPuzzleServer.cpp +++ b/dScripts/ai/FV/FvBrickPuzzleServer.cpp @@ -7,10 +7,8 @@ void FvBrickPuzzleServer::OnStartup(Entity* self) { const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { - return; - } + const auto pipeNum = GeneralUtils::TryParse(myGroup.substr(10, 1)); + if (!pipeNum) return; if (pipeNum != 1) { self->AddTimer("reset", 30); @@ -20,14 +18,12 @@ void FvBrickPuzzleServer::OnStartup(Entity* self) { void FvBrickPuzzleServer::OnDie(Entity* self, Entity* killer) { const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { - return; - } + const auto pipeNum = GeneralUtils::TryParse(myGroup.substr(10, 1)); + if (!pipeNum) return; const auto pipeGroup = myGroup.substr(0, 10); - const auto nextPipeNum = pipeNum + 1; + const auto nextPipeNum = pipeNum.value() + 1; const auto samePipeSpawners = Game::zoneManager->GetSpawnersByName(myGroup); @@ -37,7 +33,7 @@ void FvBrickPuzzleServer::OnDie(Entity* self, Entity* killer) { samePipeSpawners[0]->Deactivate(); } - if (killer != nullptr && killer->IsPlayer()) { + if (killer && killer->IsPlayer()) { const auto nextPipe = pipeGroup + std::to_string(nextPipeNum); const auto nextPipeSpawners = Game::zoneManager->GetSpawnersByName(nextPipe); diff --git a/dScripts/ai/GENERAL/CMakeLists.txt b/dScripts/ai/GENERAL/CMakeLists.txt index 9b7f2a2a..77441b4a 100644 --- a/dScripts/ai/GENERAL/CMakeLists.txt +++ b/dScripts/ai/GENERAL/CMakeLists.txt @@ -2,7 +2,7 @@ set(DSCRIPTS_SOURCES_AI_GENERAL "InstanceExitTransferPlayerToLastNonInstance.cpp" "LegoDieRoll.cpp") -add_library(dScriptsAiGeneral STATIC ${DSCRIPTS_SOURCES_AI_GENERAL}) +add_library(dScriptsAiGeneral OBJECT ${DSCRIPTS_SOURCES_AI_GENERAL}) target_include_directories(dScriptsAiGeneral PUBLIC ".") target_precompile_headers(dScriptsAiGeneral REUSE_FROM dScriptsBase) diff --git a/dScripts/ai/GF/CMakeLists.txt b/dScripts/ai/GF/CMakeLists.txt index 7a7a1723..d28b04f1 100644 --- a/dScripts/ai/GF/CMakeLists.txt +++ b/dScripts/ai/GF/CMakeLists.txt @@ -12,6 +12,6 @@ set(DSCRIPTS_SOURCES_AI_GF "PirateRep.cpp" "GfParrotCrash.cpp") -add_library(dScriptsAiGF STATIC ${DSCRIPTS_SOURCES_AI_GF}) +add_library(dScriptsAiGF OBJECT ${DSCRIPTS_SOURCES_AI_GF}) target_include_directories(dScriptsAiGF PUBLIC ".") target_precompile_headers(dScriptsAiGF REUSE_FROM dScriptsBase) diff --git a/dScripts/ai/GF/GfBanana.cpp b/dScripts/ai/GF/GfBanana.cpp index 6bc5c179..b06aae6f 100644 --- a/dScripts/ai/GF/GfBanana.cpp +++ b/dScripts/ai/GF/GfBanana.cpp @@ -56,7 +56,7 @@ void GfBanana::OnHit(Entity* self, Entity* attacker) { return; } - bananaEntity->SetPosition(bananaEntity->GetPosition() - NiPoint3::UNIT_Y * 8); + bananaEntity->SetPosition(bananaEntity->GetPosition() - NiPoint3Constant::UNIT_Y * 8); auto* bananaDestroyable = bananaEntity->GetComponent(); diff --git a/dScripts/ai/MINIGAME/CMakeLists.txt b/dScripts/ai/MINIGAME/CMakeLists.txt index 0e07d526..5598110b 100644 --- a/dScripts/ai/MINIGAME/CMakeLists.txt +++ b/dScripts/ai/MINIGAME/CMakeLists.txt @@ -12,6 +12,6 @@ foreach(file ${DSCRIPTS_SOURCES_AI_MINIGAME_OBJECTS}) set(DSCRIPTS_SOURCES_AI_MINIGAME ${DSCRIPTS_SOURCES_AI_MINIGAME} "Objects/${file}") endforeach() -add_library(dScriptsAiMinigame STATIC ${DSCRIPTS_SOURCES_AI_MINIGAME}) +add_library(dScriptsAiMinigame OBJECT ${DSCRIPTS_SOURCES_AI_MINIGAME}) target_include_directories(dScriptsAiMinigame PUBLIC "." "Objects" "SG_GF" "SG_GF/SERVER") target_precompile_headers(dScriptsAiMinigame REUSE_FROM dScriptsBase) diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp index c8563b53..1952831a 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp @@ -2,7 +2,6 @@ #include "EntityManager.h" #include "GameMessages.h" #include "dZoneManager.h" -#include "Player.h" #include "Character.h" #include "ShootingGalleryComponent.h" #include "PossessorComponent.h" diff --git a/dScripts/ai/NP/CMakeLists.txt b/dScripts/ai/NP/CMakeLists.txt index 9f3f6a65..b71bd1f8 100644 --- a/dScripts/ai/NP/CMakeLists.txt +++ b/dScripts/ai/NP/CMakeLists.txt @@ -1,6 +1,6 @@ set(DSCRIPTS_SOURCES_AI_NP "NpcNpSpacemanBob.cpp") -add_library(dScriptsAiNP STATIC ${DSCRIPTS_SOURCES_AI_NP}) +add_library(dScriptsAiNP OBJECT ${DSCRIPTS_SOURCES_AI_NP}) target_include_directories(dScriptsAiNP PUBLIC ".") target_precompile_headers(dScriptsAiNP REUSE_FROM dScriptsBase) diff --git a/dScripts/ai/NS/CMakeLists.txt b/dScripts/ai/NS/CMakeLists.txt index 0f0aa0c7..750ee67a 100644 --- a/dScripts/ai/NS/CMakeLists.txt +++ b/dScripts/ai/NS/CMakeLists.txt @@ -21,7 +21,7 @@ foreach(file ${DSCRIPTS_SOURCES_AI_NS_WH}) set(DSCRIPTS_SOURCES_AI_NS ${DSCRIPTS_SOURCES_AI_NS} "WH/${file}") endforeach() -add_library(dScriptsAiNS STATIC ${DSCRIPTS_SOURCES_AI_NS}) +add_library(dScriptsAiNS OBJECT ${DSCRIPTS_SOURCES_AI_NS}) target_include_directories(dScriptsAiNS PUBLIC "." "NS_PP_01" "WH" PRIVATE ${PROJECT_SOURCE_DIR}/dScripts/02_server/Map/NS) # NsConcertChoiceBuildManager.h diff --git a/dScripts/ai/PETS/CMakeLists.txt b/dScripts/ai/PETS/CMakeLists.txt index 8bd8630c..b7ae2033 100644 --- a/dScripts/ai/PETS/CMakeLists.txt +++ b/dScripts/ai/PETS/CMakeLists.txt @@ -1,6 +1,6 @@ set(DSCRIPTS_SOURCES_AI_PETS "HydrantSmashable.cpp") -add_library(dScriptsAiPets STATIC ${DSCRIPTS_SOURCES_AI_PETS}) +add_library(dScriptsAiPets OBJECT ${DSCRIPTS_SOURCES_AI_PETS}) target_include_directories(dScriptsAiPets PUBLIC "." "NS_PP_01" "WH") target_precompile_headers(dScriptsAiPets REUSE_FROM dScriptsBase) diff --git a/dScripts/ai/PROPERTY/CMakeLists.txt b/dScripts/ai/PROPERTY/CMakeLists.txt index a31b9257..07c528f7 100644 --- a/dScripts/ai/PROPERTY/CMakeLists.txt +++ b/dScripts/ai/PROPERTY/CMakeLists.txt @@ -8,6 +8,6 @@ foreach(file ${DSCRIPTS_SOURCES_AI_PROPERTY_AG}) set(DSCRIPTS_SOURCES_AI_PROPERTY ${DSCRIPTS_SOURCES_AI_PROPERTY} "AG/${file}") endforeach() -add_library(dScriptsAiProperty STATIC ${DSCRIPTS_SOURCES_AI_PROPERTY}) +add_library(dScriptsAiProperty OBJECT ${DSCRIPTS_SOURCES_AI_PROPERTY}) target_include_directories(dScriptsAiProperty PUBLIC "." "AG") target_precompile_headers(dScriptsAiProperty REUSE_FROM dScriptsBase) diff --git a/dScripts/ai/RACING/CMakeLists.txt b/dScripts/ai/RACING/CMakeLists.txt index b7343c61..a803b051 100644 --- a/dScripts/ai/RACING/CMakeLists.txt +++ b/dScripts/ai/RACING/CMakeLists.txt @@ -6,6 +6,6 @@ foreach(file ${DSCRIPTS_SOURCES_AI_RACING_OBJECTS}) set(DSCRIPTS_SOURCES_AI_RACING ${DSCRIPTS_SOURCES_AI_RACING} "OBJECTS/${file}") endforeach() -add_library(dScriptsAiRacing STATIC ${DSCRIPTS_SOURCES_AI_RACING}) +add_library(dScriptsAiRacing OBJECT ${DSCRIPTS_SOURCES_AI_RACING}) target_include_directories(dScriptsAiRacing PUBLIC "." "OBJECTS") target_precompile_headers(dScriptsAiRacing REUSE_FROM dScriptsBase) diff --git a/dScripts/ai/SPEC/CMakeLists.txt b/dScripts/ai/SPEC/CMakeLists.txt index c60372ac..29a781eb 100644 --- a/dScripts/ai/SPEC/CMakeLists.txt +++ b/dScripts/ai/SPEC/CMakeLists.txt @@ -3,6 +3,6 @@ set(DSCRIPTS_SOURCES_AI_SPEC "SpecialPowerupSpawner.cpp" "SpecialSpeedBuffSpawner.cpp") -add_library(dScriptsAiSpec STATIC ${DSCRIPTS_SOURCES_AI_SPEC}) +add_library(dScriptsAiSpec OBJECT ${DSCRIPTS_SOURCES_AI_SPEC}) target_include_directories(dScriptsAiSpec PUBLIC ".") target_precompile_headers(dScriptsAiSpec REUSE_FROM dScriptsBase) diff --git a/dScripts/ai/WILD/CMakeLists.txt b/dScripts/ai/WILD/CMakeLists.txt index 418ffb5f..5d4f43c3 100644 --- a/dScripts/ai/WILD/CMakeLists.txt +++ b/dScripts/ai/WILD/CMakeLists.txt @@ -1,5 +1,6 @@ set(DSCRIPTS_SOURCES_AI_WILD "AllCrateChicken.cpp" + "LupGenericInteract.cpp" "WildAmbients.cpp" "WildAmbientCrab.cpp" "WildAndScared.cpp" @@ -9,6 +10,6 @@ set(DSCRIPTS_SOURCES_AI_WILD "WildNinjaSensei.cpp" "WildPants.cpp") -add_library(dScriptsAiWild STATIC ${DSCRIPTS_SOURCES_AI_WILD}) +add_library(dScriptsAiWild OBJECT ${DSCRIPTS_SOURCES_AI_WILD}) target_include_directories(dScriptsAiWild PUBLIC ".") target_precompile_headers(dScriptsAiWild REUSE_FROM dScriptsBase) diff --git a/dScripts/ai/WILD/LupGenericInteract.cpp b/dScripts/ai/WILD/LupGenericInteract.cpp new file mode 100644 index 00000000..95eb7a96 --- /dev/null +++ b/dScripts/ai/WILD/LupGenericInteract.cpp @@ -0,0 +1,6 @@ +#include "LupGenericInteract.h" +#include "GameMessages.h" + +void LupGenericInteract::OnUse(Entity* self, Entity* user) { + GameMessages::SendPlayAnimation(self, u"interact"); +} diff --git a/dScripts/ai/WILD/LupGenericInteract.h b/dScripts/ai/WILD/LupGenericInteract.h new file mode 100644 index 00000000..68949bbf --- /dev/null +++ b/dScripts/ai/WILD/LupGenericInteract.h @@ -0,0 +1,12 @@ +#ifndef __LUCGENERICINTERACT__H__ +#define __LUCGENERICINTERACT__H__ + +#include "CppScripts.h" + +class LupGenericInteract : public CppScripts::Script { +public: + void OnUse(Entity* self, Entity* user) override; +}; + +#endif //!__LUCGENERICINTERACT__H__ + diff --git a/dScripts/client/CMakeLists.txt b/dScripts/client/CMakeLists.txt index b3ad08fb..f6760006 100644 --- a/dScripts/client/CMakeLists.txt +++ b/dScripts/client/CMakeLists.txt @@ -6,6 +6,6 @@ foreach(file ${DSCRIPTS_SOURCES_CLIENT_AI}) set(DSCRIPTS_SOURCES_CLIENT ${DSCRIPTS_SOURCES_CLIENT} "ai/${file}") endforeach() -add_library(dScriptsClient STATIC ${DSCRIPTS_SOURCES_CLIENT}) +add_library(dScriptsClient OBJECT ${DSCRIPTS_SOURCES_CLIENT}) target_include_directories(dScriptsClient PUBLIC "." "ai" "ai/PR") target_precompile_headers(dScriptsClient REUSE_FROM dScriptsBase) diff --git a/dScripts/client/ai/PR/CrabServer.cpp b/dScripts/client/ai/PR/CrabServer.cpp index f30142ba..6cdc2de8 100644 --- a/dScripts/client/ai/PR/CrabServer.cpp +++ b/dScripts/client/ai/PR/CrabServer.cpp @@ -39,6 +39,6 @@ void CrabServer::OnNotifyPetTamingMinigame(Entity* self, Entity* tamer, ePetTami return; // TODO: Remove custom group? // Command the pet to the player as it may otherwise go to its spawn point which is non existant - // petComponent->Command(NiPoint3::ZERO, LWOOBJID_EMPTY, 6, 202, true); + // petComponent->Command(NiPoint3Constant::ZERO, LWOOBJID_EMPTY, 6, 202, true); } } diff --git a/dScripts/zone/CMakeLists.txt b/dScripts/zone/CMakeLists.txt index 93ea70ca..fe919cd4 100644 --- a/dScripts/zone/CMakeLists.txt +++ b/dScripts/zone/CMakeLists.txt @@ -18,10 +18,11 @@ foreach(file ${DSCRIPTS_SOURCES_ZONE_PROPERTY}) set(DSCRIPTS_SOURCES_ZONE ${DSCRIPTS_SOURCES_ZONE} "PROPERTY/${file}") endforeach() -add_library(dScriptsZone STATIC ${DSCRIPTS_SOURCES_ZONE}) +add_library(dScriptsZone OBJECT ${DSCRIPTS_SOURCES_ZONE}) target_include_directories(dScriptsZone PUBLIC "." "AG" "LUPs" + "LUPs/RobotCity_Intro" "PROPERTY" "PROPERTY/FV" "PROPERTY/GF" diff --git a/dScripts/zone/LUPs/CMakeLists.txt b/dScripts/zone/LUPs/CMakeLists.txt index b3b55ad6..7ce84fcc 100644 --- a/dScripts/zone/LUPs/CMakeLists.txt +++ b/dScripts/zone/LUPs/CMakeLists.txt @@ -1,3 +1,11 @@ -set(DSCRIPTS_SOURCES_ZONE_LUPS +set(DSCRIPTS_SOURCES_ZONE_LUPS "WblGenericZone.cpp" - PARENT_SCOPE) +) + +add_subdirectory(RobotCity_Intro) + +foreach(file ${DSCRIPTS_SOURCES_ZONE_LUPS_ROBOTCITYINTRO}) + set(DSCRIPTS_SOURCES_ZONE_LUPS ${DSCRIPTS_SOURCES_ZONE_LUPS} "RobotCity_Intro/${file}") +endforeach() + +set(DSCRIPTS_SOURCES_ZONE_LUPS ${DSCRIPTS_SOURCES_ZONE_LUPS} PARENT_SCOPE) diff --git a/dScripts/zone/LUPs/RobotCity_Intro/CMakeLists.txt b/dScripts/zone/LUPs/RobotCity_Intro/CMakeLists.txt new file mode 100644 index 00000000..fae8793b --- /dev/null +++ b/dScripts/zone/LUPs/RobotCity_Intro/CMakeLists.txt @@ -0,0 +1,3 @@ +set(DSCRIPTS_SOURCES_ZONE_LUPS_ROBOTCITYINTRO + "WblRobotCitizen.cpp" + PARENT_SCOPE) diff --git a/dScripts/zone/LUPs/RobotCity_Intro/WblRobotCitizen.cpp b/dScripts/zone/LUPs/RobotCity_Intro/WblRobotCitizen.cpp new file mode 100644 index 00000000..93bf2576 --- /dev/null +++ b/dScripts/zone/LUPs/RobotCity_Intro/WblRobotCitizen.cpp @@ -0,0 +1,24 @@ +#include "WblRobotCitizen.h" +#include "MovementAIComponent.h" +#include "RenderComponent.h" + +void WblRobotCitizen::OnStartup(Entity* self) { + auto movementAIComponent = self->GetComponent(); + if (!movementAIComponent) return; + // movementAIComponent->Resume(); +} + +void WblRobotCitizen::OnUse(Entity* self, Entity* user) { + // auto movementAIComponent = self->GetComponent(); + // if (!movementAIComponent) movementAIComponent->Pause(); + auto face = NiQuaternion::LookAt(self->GetPosition(), user->GetPosition()); + self->SetRotation(face); + auto timer = RenderComponent::PlayAnimation(self, "wave"); + self->AddTimer("animation time", timer); +} + +void WblRobotCitizen::OnTimerDone(Entity* self, std::string timerName) { + auto movementAIComponent = self->GetComponent(); + if (!movementAIComponent) return; + // movementAIComponent->Resume(); +} diff --git a/dScripts/zone/LUPs/RobotCity_Intro/WblRobotCitizen.h b/dScripts/zone/LUPs/RobotCity_Intro/WblRobotCitizen.h new file mode 100644 index 00000000..2f720764 --- /dev/null +++ b/dScripts/zone/LUPs/RobotCity_Intro/WblRobotCitizen.h @@ -0,0 +1,13 @@ +#ifndef __WBLROBOTCITIZEN__H__ +#define __WBLROBOTCITIZEN__H__ + +#include "CppScripts.h" + +class WblRobotCitizen : public CppScripts::Script { +public: + void OnStartup(Entity* self) override; + void OnUse(Entity* self, Entity* user) override; + void OnTimerDone(Entity* self, std::string timerName) override; +}; + +#endif //!__WBLROBOTCITIZEN__H__ diff --git a/dServer/CMakeLists.txt b/dServer/CMakeLists.txt index 356e55b7..ca4e6198 100644 --- a/dServer/CMakeLists.txt +++ b/dServer/CMakeLists.txt @@ -4,3 +4,7 @@ set(DSERVER_SOURCES add_library(dServer STATIC ${DSERVER_SOURCES}) target_include_directories(dServer PUBLIC ".") + +target_include_directories(dServer PRIVATE + "${PROJECT_SOURCE_DIR}/dCommon/" # BinaryPathFinder.h +) diff --git a/dWorldServer/CMakeLists.txt b/dWorldServer/CMakeLists.txt index 41cba0e2..62a3767a 100644 --- a/dWorldServer/CMakeLists.txt +++ b/dWorldServer/CMakeLists.txt @@ -2,11 +2,22 @@ set(DWORLDSERVER_SOURCES "PerformanceManager.cpp" ) -add_library(dWorldServer ${DWORLDSERVER_SOURCES}) +add_library(dWorldServer OBJECT ${DWORLDSERVER_SOURCES}) +target_link_libraries(dWorldServer PUBLIC dGameBase dCommon) + add_executable(WorldServer "WorldServer.cpp") +target_include_directories(WorldServer PRIVATE "${PROJECT_SOURCE_DIR}/dChatFilter") add_compile_definitions(WorldServer PRIVATE PROJECT_VERSION="\"${PROJECT_VERSION}\"") -target_link_libraries(dWorldServer ${COMMON_LIBRARIES}) -target_link_libraries(WorldServer ${COMMON_LIBRARIES} dChatFilter dGame dZoneManager dPhysics Detour Recast tinyxml2 dWorldServer dNavigation dServer) -target_include_directories(WorldServer PRIVATE ${PROJECT_SOURCE_DIR}/dServer) +target_include_directories(WorldServer PRIVATE + "${PROJECT_SOURCE_DIR}/dServer" # BinaryPathFinder.h +) +target_link_libraries(WorldServer ${COMMON_LIBRARIES} + dScripts + dGameBase + dComponents + dUtilities + dGameMessages + dInventory + dGame dChatFilter dZoneManager dPhysics Detour Recast tinyxml2 dWorldServer dNavigation dServer) diff --git a/dWorldServer/PerformanceManager.cpp b/dWorldServer/PerformanceManager.cpp index 248be54a..052d075b 100644 --- a/dWorldServer/PerformanceManager.cpp +++ b/dWorldServer/PerformanceManager.cpp @@ -70,7 +70,7 @@ std::map PerformanceManager::m_Profiles = { void PerformanceManager::SelectProfile(LWOMAPID mapID) { // Try to get it from zoneTable - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable) { const CDZoneTable* zone = zoneTable->Query(mapID); if (zone) { diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 2ebb64ec..c434f8de 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -56,7 +56,6 @@ #include "DestroyableComponent.h" #include "Game.h" #include "MasterPackets.h" -#include "Player.h" #include "PropertyManagementComponent.h" #include "AssetManager.h" #include "LevelProgressionComponent.h" @@ -79,11 +78,11 @@ #include "Server.h" #include "PositionUpdate.h" #include "PlayerManager.h" +#include "eLoginResponse.h" namespace Game { Logger* logger = nullptr; dServer* server = nullptr; - dpWorld* physicsWorld = nullptr; dChatFilter* chatFilter = nullptr; dConfig* config = nullptr; AssetManager* assetManager = nullptr; @@ -181,7 +180,7 @@ int main(int argc, char** argv) { return EXIT_FAILURE; } - CDClientManager::Instance().LoadValuesFromDatabase(); + CDClientManager::LoadValuesFromDatabase(); Diagnostics::SetProduceMemoryDump(Game::config->GetValue("generate_dump") == "1"); @@ -209,8 +208,7 @@ int main(int argc, char** argv) { UserManager::Instance()->Initialize(); - bool dontGenerateDCF = false; - GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf"), dontGenerateDCF); + const bool dontGenerateDCF = GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf")).value_or(false); Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", dontGenerateDCF); Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, Game::config, &Game::lastSignal, zoneID); @@ -256,7 +254,7 @@ int main(int argc, char** argv) { Game::zoneManager = new dZoneManager(); //Load our level: if (zoneID != 0) { - dpWorld::Instance().Initialize(zoneID); + dpWorld::Initialize(zoneID); Game::zoneManager->Initialize(LWOZONEID(zoneID, instanceID, cloneID)); g_CloneID = cloneID; @@ -337,7 +335,7 @@ int main(int argc, char** argv) { // Update to the new framerate and scale all timings to said new framerate if (newFrameDelta != currentFrameDelta) { - float_t ratioBeforeToAfter = (float)currentFrameDelta / (float)newFrameDelta; + float_t ratioBeforeToAfter = static_cast(currentFrameDelta) / static_cast(newFrameDelta); currentFrameDelta = newFrameDelta; currentFramerate = MS_TO_FRAMES(newFrameDelta); LOG_DEBUG("Framerate for zone/instance/clone %i/%i/%i is now %i", zoneID, instanceID, cloneID, currentFramerate); @@ -387,7 +385,7 @@ int main(int argc, char** argv) { if (zoneID != 0 && deltaTime > 0.0f) { Metrics::StartMeasurement(MetricVariable::Physics); - dpWorld::Instance().StepWorld(deltaTime); + dpWorld::StepWorld(deltaTime); Metrics::EndMeasurement(MetricVariable::Physics); Metrics::StartMeasurement(MetricVariable::UpdateEntities); @@ -586,9 +584,10 @@ void HandlePacketChat(Packet* packet) { inStream.Read(expire); auto* entity = Game::entityManager->GetEntity(playerId); - - if (entity != nullptr) { - entity->GetParentUser()->SetMuteExpire(expire); + auto* character = entity != nullptr ? entity->GetCharacter() : nullptr; + auto* user = character != nullptr ? character->GetParentUser() : nullptr; + if (user) { + user->SetMuteExpire(expire); entity->GetCharacter()->SendMuteNotice(); } @@ -732,9 +731,9 @@ void HandleMasterPacket(Packet* packet) { { CBITSTREAM; BitStreamUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::PLAYER_ADDED); - bitStream.Write((LWOMAPID)Game::server->GetZoneID()); - bitStream.Write((LWOINSTANCEID)instanceID); - Game::server->SendToMaster(&bitStream); + bitStream.Write(Game::server->GetZoneID()); + bitStream.Write(instanceID); + Game::server->SendToMaster(bitStream); } } @@ -750,7 +749,7 @@ void HandleMasterPacket(Packet* packet) { BitStreamUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::AFFIRM_TRANSFER_RESPONSE); bitStream.Write(requestID); - Game::server->SendToMaster(&bitStream); + Game::server->SendToMaster(bitStream); break; } @@ -834,9 +833,9 @@ void HandlePacket(Packet* packet) { CBITSTREAM; BitStreamUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::PLAYER_REMOVED); - bitStream.Write((LWOMAPID)Game::server->GetZoneID()); - bitStream.Write((LWOINSTANCEID)instanceID); - Game::server->SendToMaster(&bitStream); + bitStream.Write(Game::server->GetZoneID()); + bitStream.Write(instanceID); + Game::server->SendToMaster(bitStream); } if (packet->data[0] != ID_USER_PACKET_ENUM || packet->length < 4) return; @@ -870,10 +869,28 @@ void HandlePacket(Packet* packet) { } // Developers may skip this check - if (accountInfo->maxGmLevel < eGameMasterLevel::DEVELOPER && clientDatabaseChecksum.string != databaseChecksum) { - LOG("Client's database checksum does not match the server's, aborting connection."); - Game::server->Disconnect(packet->systemAddress, eServerDisconnectIdentifiers::WRONG_GAME_VERSION); - return; + if (clientDatabaseChecksum.string != databaseChecksum) { + + if (accountInfo->maxGmLevel < eGameMasterLevel::DEVELOPER) { + LOG("Client's database checksum does not match the server's, aborting connection."); + std::vector stamps; + + // Using the LoginResponse here since the UI is still in the login screen state + // and we have a way to send a message about the client mismatch. + AuthPackets::SendLoginResponse( + Game::server, packet->systemAddress, eLoginResponse::PERMISSIONS_NOT_HIGH_ENOUGH, + Game::config->GetValue("cdclient_mismatch_message"), "", 0, "", stamps); + return; + } else { + AMFArrayValue args; + + args.Insert("title", Game::config->GetValue("cdclient_mismatch_title")); + args.Insert("message", Game::config->GetValue("cdclient_mismatch_message")); + + GameMessages::SendUIMessageServerToSingleClient("ToggleAnnounce", args, packet->systemAddress); + LOG("Account (%s) with GmLevel (%s) does not have a matching FDB, but is a developer and will skip this check." + , username.GetAsString().c_str(), StringifiedEnum::ToString(accountInfo->maxGmLevel).data()); + } } } @@ -881,7 +898,7 @@ void HandlePacket(Packet* packet) { CBITSTREAM; BitStreamUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::REQUEST_SESSION_KEY); bitStream.Write(username); - Game::server->SendToMaster(&bitStream); + Game::server->SendToMaster(bitStream); //Insert info into our pending list tempSessionInfo info; @@ -936,7 +953,7 @@ void HandlePacket(Packet* packet) { static_cast(messageID) ); - if (isSender) GameMessageHandler::HandleMessage(&dataStream, packet->systemAddress, objectID, messageID); + if (isSender) GameMessageHandler::HandleMessage(dataStream, packet->systemAddress, objectID, messageID); break; } @@ -1016,8 +1033,8 @@ void HandlePacket(Packet* packet) { Game::entityManager->ConstructEntity(player, UNASSIGNED_SYSTEM_ADDRESS, true); - if (respawnPoint != NiPoint3::ZERO) { - GameMessages::SendPlayerReachedRespawnCheckpoint(player, respawnPoint, NiQuaternion::IDENTITY); + if (respawnPoint != NiPoint3Constant::ZERO) { + GameMessages::SendPlayerReachedRespawnCheckpoint(player, respawnPoint, NiQuaternionConstant::IDENTITY); } Game::entityManager->ConstructAllEntities(packet->systemAddress); @@ -1112,9 +1129,10 @@ void HandlePacket(Packet* packet) { //Mail::HandleNotificationRequest(packet->systemAddress, player->GetObjectID()); //Notify chat that a player has loaded: - { - const auto& playerName = player->GetCharacter()->GetName(); - //RakNet::RakString playerName(player->GetCharacter()->GetName().c_str()); + auto* character = player->GetCharacter(); + auto* user = character != nullptr ? character->GetParentUser() : nullptr; + if (user) { + const auto& playerName = character->GetName(); CBITSTREAM; BitStreamUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatMessageType::PLAYER_ADDED_NOTIFICATION); @@ -1128,7 +1146,7 @@ void HandlePacket(Packet* packet) { bitStream.Write(zone.GetMapID()); bitStream.Write(zone.GetInstanceID()); bitStream.Write(zone.GetCloneID()); - bitStream.Write(player->GetParentUser()->GetMuteExpire()); + bitStream.Write(user->GetMuteExpire()); bitStream.Write(player->GetGMLevel()); Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); @@ -1162,7 +1180,7 @@ void HandlePacket(Packet* packet) { // FIXME: Change this to the macro to skip the header... LWOOBJID space; bitStream.Read(space); - Mail::HandleMailStuff(&bitStream, packet->systemAddress, UserManager::Instance()->GetUser(packet->systemAddress)->GetLastUsedChar()->GetEntity()); + Mail::HandleMailStuff(bitStream, packet->systemAddress, UserManager::Instance()->GetUser(packet->systemAddress)->GetLastUsedChar()->GetEntity()); break; } @@ -1423,6 +1441,7 @@ void FinalizeShutdown() { //Delete our objects here: Metrics::Clear(); + dpWorld::Shutdown(); Database::Destroy("WorldServer"); if (Game::chatFilter) delete Game::chatFilter; Game::chatFilter = nullptr; @@ -1445,5 +1464,5 @@ void FinalizeShutdown() { void SendShutdownMessageToMaster() { CBITSTREAM; BitStreamUtils::WriteHeader(bitStream, eConnectionType::MASTER, eMasterMessageType::SHUTDOWN_RESPONSE); - Game::server->SendToMaster(&bitStream); + Game::server->SendToMaster(bitStream); } diff --git a/dZoneManager/CMakeLists.txt b/dZoneManager/CMakeLists.txt index e7382367..544a01d9 100644 --- a/dZoneManager/CMakeLists.txt +++ b/dZoneManager/CMakeLists.txt @@ -3,7 +3,20 @@ set(DZONEMANAGER_SOURCES "dZoneManager.cpp" "Spawner.cpp" "Zone.cpp") -add_library(dZoneManager STATIC ${DZONEMANAGER_SOURCES}) +add_library(dZoneManager OBJECT ${DZONEMANAGER_SOURCES}) target_link_libraries(dZoneManager - PUBLIC dPhysics - INTERFACE dWorldServer) + PRIVATE dDatabaseCDClient + PUBLIC dPhysics) + +#set_property(TARGET dZoneManager APPEND PROPERTY INTERFACE_LINK_LIBRARIES dWorldServer) + +target_include_directories(dZoneManager PUBLIC "." + "${PROJECT_SOURCE_DIR}/dGame" # Entity.h + "${PROJECT_SOURCE_DIR}/dGame/dEntity" # EntityInfo.h + PRIVATE + "${PROJECT_SOURCE_DIR}/dGame/dComponents" #InventoryComponent.h + "${PROJECT_SOURCE_DIR}/dGame/dInventory" #InventoryComponent.h (transitive) + "${PROJECT_SOURCE_DIR}/dGame/dBehaviors" #BehaviorSlot.h + "${PROJECT_SOURCE_DIR}/dGame/dGameMessages" #GameMessages.h + "${PROJECT_SOURCE_DIR}/dGame/dUtilities" #VanityUtilities.h +) diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index 0a46dc89..5f35b629 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -14,6 +14,7 @@ #include "CDFeatureGatingTable.h" #include "CDClientManager.h" #include "AssetManager.h" +#include "ClientVersion.h" #include "dConfig.h" Level::Level(Zone* parentZone, const std::string& filepath) { @@ -199,24 +200,21 @@ void Level::ReadFileInfoChunk(std::istream& file, Header& header) { BinaryIO::BinaryRead(file, header.fileInfo.enviromentChunkStart); BinaryIO::BinaryRead(file, header.fileInfo.objectChunkStart); BinaryIO::BinaryRead(file, header.fileInfo.particleChunkStart); - - //PATCH FOR AG: (messed up file?) - if (header.fileInfo.revision == 0xCDCDCDCD && m_ParentZone->GetZoneID().GetMapID() == 1100) header.fileInfo.revision = 26; } void Level::ReadSceneObjectDataChunk(std::istream& file, Header& header) { uint32_t objectsCount = 0; BinaryIO::BinaryRead(file, objectsCount); - CDFeatureGatingTable* featureGatingTable = CDClientManager::Instance().GetTable(); + CDFeatureGatingTable* featureGatingTable = CDClientManager::GetTable(); CDFeatureGating gating; - gating.major = 1; - gating.current = 10; - gating.minor = 64; - GeneralUtils::TryParse(Game::config->GetValue("version_major"), gating.major); - GeneralUtils::TryParse(Game::config->GetValue("version_current"), gating.current); - GeneralUtils::TryParse(Game::config->GetValue("version_minor"), gating.minor); + gating.major = + GeneralUtils::TryParse(Game::config->GetValue("version_major")).value_or(ClientVersion::major); + gating.current = + GeneralUtils::TryParse(Game::config->GetValue("version_current")).value_or(ClientVersion::current); + gating.minor = + GeneralUtils::TryParse(Game::config->GetValue("version_minor")).value_or(ClientVersion::minor); const auto zoneControlObject = Game::zoneManager->GetZoneControlObject(); DluAssert(zoneControlObject != nullptr); diff --git a/dZoneManager/Spawner.cpp b/dZoneManager/Spawner.cpp index 31188907..3baf193f 100644 --- a/dZoneManager/Spawner.cpp +++ b/dZoneManager/Spawner.cpp @@ -25,16 +25,6 @@ Spawner::Spawner(const SpawnerInfo info) { m_Start = m_Info.noTimedSpawn; - //ssssh... - if (m_EntityInfo.lot == 14718) { //AG - MAELSTROM SAMPLE - m_Info.groups.emplace_back("MaelstromSamples"); - } - - if (m_EntityInfo.lot == 14375) //AG - SPIDER BOSS EGG - { - m_Info.groups.emplace_back("EGG"); - } - int timerCount = m_Info.amountMaintained; if (m_Info.amountMaintained > m_Info.nodes.size()) { diff --git a/dZoneManager/Spawner.h b/dZoneManager/Spawner.h index 79ba40d1..686c7588 100644 --- a/dZoneManager/Spawner.h +++ b/dZoneManager/Spawner.h @@ -12,8 +12,8 @@ #include "EntityInfo.h" struct SpawnerNode { - NiPoint3 position = NiPoint3::ZERO; - NiQuaternion rotation = NiQuaternion::IDENTITY; + NiPoint3 position = NiPoint3Constant::ZERO; + NiQuaternion rotation = NiQuaternionConstant::IDENTITY; uint32_t nodeID = 0; uint32_t nodeMax = 1; std::vector entities; diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index cbaccded..44532fc9 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -17,6 +17,8 @@ #include "eTriggerCommandType.h" #include "eTriggerEventType.h" +#include "eWaypointCommandType.h" +#include "dNavMesh.h" Zone::Zone(const LWOMAPID& mapID, const LWOINSTANCEID& instanceID, const LWOCLONEID& cloneID) : m_ZoneID(mapID, instanceID, cloneID) { @@ -153,7 +155,7 @@ void Zone::LoadZoneIntoMemory() { std::string Zone::GetFilePathForZoneID() { //We're gonna go ahead and presume we've got the db loaded already: - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); const CDZoneTable* zone = zoneTable->Query(this->GetZoneID().GetMapID()); if (zone != nullptr) { std::string toReturn = "maps/" + zone->zoneName; @@ -418,7 +420,7 @@ void Zone::LoadPath(std::istream& file) { if (path.pathType == PathType::MovingPlatform) { BinaryIO::BinaryRead(file, waypoint.movingPlatform.lockPlayer); - BinaryIO::BinaryRead(file, waypoint.movingPlatform.speed); + BinaryIO::BinaryRead(file, waypoint.speed); BinaryIO::BinaryRead(file, waypoint.movingPlatform.wait); if (path.pathVersion >= 13) { BinaryIO::ReadString(file, waypoint.movingPlatform.departSound, BinaryIO::ReadType::WideString); @@ -437,7 +439,7 @@ void Zone::LoadPath(std::istream& file) { BinaryIO::BinaryRead(file, waypoint.racing.planeHeight); BinaryIO::BinaryRead(file, waypoint.racing.shortestDistanceToEnd); } else if (path.pathType == PathType::Rail) { - if (path.pathVersion > 16) BinaryIO::BinaryRead(file, waypoint.rail.speed); + if (path.pathVersion > 16) BinaryIO::BinaryRead(file, waypoint.speed); } // object LDF configs @@ -451,21 +453,29 @@ void Zone::LoadPath(std::istream& file) { std::string value; BinaryIO::ReadString(file, value, BinaryIO::ReadType::WideString); - LDFBaseData* ldfConfig = nullptr; if (path.pathType == PathType::Movement || path.pathType == PathType::Rail) { - ldfConfig = LDFBaseData::DataFromString(parameter + "=0:" + value); + // cause NetDevil puts spaces in things that don't need spaces + parameter.erase(std::remove_if(parameter.begin(), parameter.end(), ::isspace), parameter.end()); + auto waypointCommand = WaypointCommandType::StringToWaypointCommandType(parameter); + if (waypointCommand == eWaypointCommandType::DELAY) value.erase(std::remove_if(value.begin(), value.end(), ::isspace), value.end()); + if (waypointCommand != eWaypointCommandType::INVALID) { + auto& command = waypoint.commands.emplace_back(); + command.command = waypointCommand; + command.data = value; + } else LOG("Tried to load invalid waypoint command '%s'", parameter.c_str()); } else { - ldfConfig = LDFBaseData::DataFromString(parameter + "=" + value); + waypoint.config.emplace_back(LDFBaseData::DataFromString(parameter + "=" + value)); } - if (ldfConfig) waypoint.config.push_back(ldfConfig); + } } + // We verify the waypoint heights against the navmesh because in many movement paths, // the waypoint is located near 0 height, if (path.pathType == PathType::Movement) { - if (dpWorld::Instance().IsLoaded()) { + if (dpWorld::IsLoaded()) { // 2000 should be large enough for every world. - waypoint.position.y = dpWorld::Instance().GetNavMesh()->GetHeightAtPoint(waypoint.position, 2000.0f); + waypoint.position.y = dpWorld::GetNavMesh()->GetHeightAtPoint(waypoint.position, 2000.0f); } } path.pathWaypoints.push_back(waypoint); diff --git a/dZoneManager/Zone.h b/dZoneManager/Zone.h index a62a81ed..c5bac6a6 100644 --- a/dZoneManager/Zone.h +++ b/dZoneManager/Zone.h @@ -13,6 +13,14 @@ namespace LUTriggers { class Level; +enum class eWaypointCommandType : uint32_t; + +struct WaypointCommand { + eWaypointCommandType command; + std::string data; +}; + + struct SceneRef { std::string filename; uint32_t id; @@ -40,7 +48,6 @@ struct SceneTransition { struct MovingPlatformPathWaypoint { uint8_t lockPlayer; - float speed; float wait; std::string departSound; std::string arriveSound; @@ -62,18 +69,15 @@ struct RacingPathWaypoint { float shortestDistanceToEnd; }; -struct RailPathWaypoint { - float speed; -}; - struct PathWaypoint { NiPoint3 position; NiQuaternion rotation; // not included in all, but it's more convenient here MovingPlatformPathWaypoint movingPlatform; CameraPathWaypoint camera; RacingPathWaypoint racing; - RailPathWaypoint rail; + float speed; std::vector config; + std::vector commands; }; enum class PathType : uint32_t { diff --git a/dZoneManager/dZoneManager.cpp b/dZoneManager/dZoneManager.cpp index 3aa35485..09baabed 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -29,7 +29,7 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { LOT zoneControlTemplate = 2365; - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable != nullptr) { const CDZoneTable* zone = zoneTable->Query(zoneID.GetMapID()); @@ -208,7 +208,7 @@ uint32_t dZoneManager::GetUniqueMissionIdStartingValue() { bool dZoneManager::CheckIfAccessibleZone(LWOMAPID zoneID) { //We're gonna go ahead and presume we've got the db loaded already: - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); const CDZoneTable* zone = zoneTable->Query(zoneID); if (zone != nullptr) { return Game::assetManager->HasFile(("maps/" + zone->zoneName).c_str()); diff --git a/docs/Vanity.md b/docs/Vanity.md new file mode 100644 index 00000000..ac2c4263 --- /dev/null +++ b/docs/Vanity.md @@ -0,0 +1,170 @@ +# DLU Vanity System + +Darkflame Universe Vanity System is a method of defined objects to be spawned serverside and communicated to the client without modifying the game's assets. + +You can check out the different `xml` files in `vanity/` and use `vanity/demo.xml` to follow along with this tutorial and documentation of thew various features, cabapilities, and limitations of this system. + +## `vanity/root.xml` +`root.xml` is the only file the server will load in by default. + +To load other files, you can do so like this: +```xml + + + + + +``` + +`name` is the name of the file relative to the vanity folder. +Ex: you have a folder like `vanity/events/` with a file called `halloween.xml` in it, you will include it as such: + +`` + +`enabled` tells if that file should be loaded. +files will only be loaded in, if `enabled="1"` + +There cannot be multiple `` per xml file, only the first one will be read, but you can have as many `` in it as you wish. + +## `vanity/demo.xml` + +This demo file covers most of the features of defining objects to spawn server side and will go over them one by one. + +The minimun data needed to define and ojbect to spawn is as follows: +```xml + + + + + + + +``` + + * `lot` the LEGO Object Template to be spawned + + * `` must have `zone`, `x`, `y`, `z` `rw`, `rx`, `ry`, and `rz` and one `location` must in exist in `locations` for it to be spawned + +Everything else is is optional. + +* LEGO Name Value (LNV) configs can control almost all functionality of the objects in the game, they are defined like `name=type:value`. types can be found in `dCommon/LDFFromat.h` + +```xml + + bool=7:1 + +``` + +### Story Plaque with custom text + +lot 8193 is the story plaque that is used in game to give the game lore to the player. + +DLU Vanity has the capability to provide custom text to it via a LNV config + +From `demo.xml` +```xml + + + customText=13:This story plaque has custom text that is defined by DLU's vanity system. Check out <font color="#000000" >vanity/demo.xml</font> to see how this works! + + + + + +``` + + * The `customText` config must be a type of `13` (wstring) + * HTML like formatting can be used for font color, but `<` must be reaplaced withh `>`, and `>` replaced with `<` + +### Object with multiple locations and scale + +```xml + + + + + + +``` +#### Multiple locations +Multiple location elements can be defined for an object. +For every location that object will spawn: +This will spawn two trees, one at each specified location. + +#### Scale +Each location can specify a `scale` which defaults to `1`. The object will be scaled by this attribute in the location when defined. + +### Object with multiple random locations and chance + +```xml + + + useLocationsAsRandomSpawnPoint=7:1 + + + + + + + +``` +#### Random Spawn Point +If the LNV config `useLocationsAsRandomSpawnPoint=7:1` is defined and is set to `1`, instead of spawning the object at every location, it will randomly choose between all locations in the current zone to spawn one instance of the object. +If a location is not in the current zone, it will not be considered. + +#### Chance +Each location can specify a `chance` attribute. This defines a chance from, `0` to `1` that the object will spawn, with `0` being never spawn, and `1` being always spawn. A `chance="0.8"` will have an 80% chance for the object to spawn at that location. + +`useLocationsAsRandomSpawnPoint` and `chance` are independent of each other and be used separately + +### Custom vendor with custom name and gear + +```xml + + 7630, 1727, 7453, 7521 + + vendorInvOverride=0:1727,7292,16553,2243,14535,14538,14531,6730 + + + + + +``` +#### Custom vendor + +For a custom vendor to work, you must use a LOT that already has a vendor compoenet attached to it. + +Without an LNV keys, it will give it's normal inventory +You muse define `vendorInvOverride=0:` and then a list of LOTs that the vendor will sell. This will override all items the vendor was selling and use the list of LOTs provided. + +LOTs must have an item component in order to be sold by a vendor. + +#### Custom Name + +The `name` attribute will give or override the name displayed for an object, if it displays one. +Using a ` - ` will allow you to define a title that will display under their name on their nametag (formally called a billboard). + +#### Custom Gear + +The `equipment` element is a lis of comma separated lots that will defind the geat an object will attempt to equip. + +LOTs must have an inventory component in order to equipe custom gear. + +### Creating Spawners +```xml + + + ... + spawntemplate=1:2295 + ... + + + + + + +``` + +LOT `167` is a spawner. The spawner config in the `demo.xml` was copied from an existing object via lcdr's luzviewer. + +The main config to care about is `spawntemplate` as that controls what the spawner spawns. diff --git a/resources/navmeshes.zip b/resources/navmeshes.zip index c3053520..95948656 100644 Binary files a/resources/navmeshes.zip and b/resources/navmeshes.zip differ diff --git a/resources/worldconfig.ini b/resources/worldconfig.ini index c68b42d2..91028ffe 100644 --- a/resources/worldconfig.ini +++ b/resources/worldconfig.ini @@ -73,3 +73,7 @@ help_4_description=Visit Discussions on the DarkflameServer GitHub page
to a # Toggleable quality of life feature to allow users to skip most cinematics. allow_players_to_skip_cinematics=0 + +# Customizable message for what to say when there is a cdclient fdb mismatch +cdclient_mismatch_title=Version out of date +cdclient_mismatch_message=We detected that your client is out of date. Please update your client to the latest version. diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 9ba75a2f..e8765191 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -1,20 +1,19 @@ -message (STATUS "Testing is enabled. Fetching gtest...") +message (STATUS "Testing is enabled.") enable_testing() -include(FetchContent) -FetchContent_Declare( - googletest - GIT_REPOSITORY https://github.com/google/googletest.git - GIT_TAG release-1.12.1 -) - -# For Windows: Prevent overriding the parent project's compiler/linker settings -set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) - -FetchContent_MakeAvailable(GoogleTest) +find_package(GoogleTest REQUIRED) include(GoogleTest) -message(STATUS "gtest fetched and is now ready.") +set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/bin) + +if(APPLE) + set(CMAKE_INSTALL_RPATH_USE_LINK_PATH True) + set(CMAKE_BUILD_WITH_INSTALL_RPATH True) + set(CMAKE_INSTALL_RPATH "@executable_path") +endif() + +add_custom_target(conncpp_tests + ${CMAKE_COMMAND} -E copy $ ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) # Add the subdirectories add_subdirectory(dCommonTests) diff --git a/tests/dCommonTests/AMFDeserializeTests.cpp b/tests/dCommonTests/AMFDeserializeTests.cpp index 58c46584..c949ae50 100644 --- a/tests/dCommonTests/AMFDeserializeTests.cpp +++ b/tests/dCommonTests/AMFDeserializeTests.cpp @@ -11,10 +11,10 @@ /** * Helper method that all tests use to get their respective AMF. */ -AMFBaseValue* ReadFromBitStream(RakNet::BitStream* bitStream) { +std::unique_ptr ReadFromBitStream(RakNet::BitStream& bitStream) { AMFDeserialize deserializer; AMFBaseValue* returnValue(deserializer.Read(bitStream)); - return returnValue; + return std::unique_ptr{ returnValue }; } /** @@ -23,7 +23,7 @@ AMFBaseValue* ReadFromBitStream(RakNet::BitStream* bitStream) { TEST(dCommonTests, AMFDeserializeAMFUndefinedTest) { CBITSTREAM; bitStream.Write(0x00); - std::unique_ptr res(ReadFromBitStream(&bitStream)); + std::unique_ptr res{ ReadFromBitStream(bitStream) }; ASSERT_EQ(res->GetValueType(), eAmf::Undefined); } @@ -34,7 +34,7 @@ TEST(dCommonTests, AMFDeserializeAMFUndefinedTest) { TEST(dCommonTests, AMFDeserializeAMFNullTest) { CBITSTREAM; bitStream.Write(0x01); - std::unique_ptr res(ReadFromBitStream(&bitStream)); + std::unique_ptr res{ ReadFromBitStream(bitStream) }; ASSERT_EQ(res->GetValueType(), eAmf::Null); } @@ -44,7 +44,7 @@ TEST(dCommonTests, AMFDeserializeAMFNullTest) { TEST(dCommonTests, AMFDeserializeAMFFalseTest) { CBITSTREAM; bitStream.Write(0x02); - std::unique_ptr res(ReadFromBitStream(&bitStream)); + std::unique_ptr res{ ReadFromBitStream(bitStream) }; ASSERT_EQ(res->GetValueType(), eAmf::False); } @@ -54,7 +54,7 @@ TEST(dCommonTests, AMFDeserializeAMFFalseTest) { TEST(dCommonTests, AMFDeserializeAMFTrueTest) { CBITSTREAM; bitStream.Write(0x03); - std::unique_ptr res(ReadFromBitStream(&bitStream)); + std::unique_ptr res{ ReadFromBitStream(bitStream) }; ASSERT_EQ(res->GetValueType(), eAmf::True); } @@ -67,7 +67,7 @@ TEST(dCommonTests, AMFDeserializeAMFIntegerTest) { bitStream.Write(0x04); // 127 == 01111111 bitStream.Write(127); - std::unique_ptr res(ReadFromBitStream(&bitStream)); + std::unique_ptr res{ ReadFromBitStream(bitStream) }; ASSERT_EQ(res->GetValueType(), eAmf::Integer); // Check that the max value of a byte can be read correctly ASSERT_EQ(static_cast(res.get())->GetValue(), 127); @@ -76,7 +76,7 @@ TEST(dCommonTests, AMFDeserializeAMFIntegerTest) { { bitStream.Write(0x04); bitStream.Write(UINT32_MAX); - std::unique_ptr res(ReadFromBitStream(&bitStream)); + std::unique_ptr res{ ReadFromBitStream(bitStream) }; ASSERT_EQ(res->GetValueType(), eAmf::Integer); // Check that we can read the maximum value correctly ASSERT_EQ(static_cast(res.get())->GetValue(), 536870911); @@ -90,7 +90,7 @@ TEST(dCommonTests, AMFDeserializeAMFIntegerTest) { bitStream.Write(255); // 127 == 01111111 bitStream.Write(127); - std::unique_ptr res(ReadFromBitStream(&bitStream)); + std::unique_ptr res{ ReadFromBitStream(bitStream) }; ASSERT_EQ(res->GetValueType(), eAmf::Integer); // Check that short max can be read correctly ASSERT_EQ(static_cast(res.get())->GetValue(), UINT16_MAX); @@ -102,7 +102,7 @@ TEST(dCommonTests, AMFDeserializeAMFIntegerTest) { bitStream.Write(255); // 127 == 01111111 bitStream.Write(127); - std::unique_ptr res(ReadFromBitStream(&bitStream)); + std::unique_ptr res{ ReadFromBitStream(bitStream) }; ASSERT_EQ(res->GetValueType(), eAmf::Integer); // Check that 2 byte max can be read correctly ASSERT_EQ(static_cast(res.get())->GetValue(), 16383); @@ -116,7 +116,7 @@ TEST(dCommonTests, AMFDeserializeAMFDoubleTest) { CBITSTREAM; bitStream.Write(0x05); bitStream.Write(25346.4f); - std::unique_ptr res(ReadFromBitStream(&bitStream)); + std::unique_ptr res{ ReadFromBitStream(bitStream) }; ASSERT_EQ(res->GetValueType(), eAmf::Double); ASSERT_EQ(static_cast(res.get())->GetValue(), 25346.4f); } @@ -130,7 +130,7 @@ TEST(dCommonTests, AMFDeserializeAMFStringTest) { bitStream.Write(0x0F); std::string toWrite = "stateID"; for (auto e : toWrite) bitStream.Write(e); - std::unique_ptr res(ReadFromBitStream(&bitStream)); + std::unique_ptr res{ ReadFromBitStream(bitStream) }; ASSERT_EQ(res->GetValueType(), eAmf::String); ASSERT_EQ(static_cast(res.get())->GetValue(), "stateID"); } @@ -145,7 +145,7 @@ TEST(dCommonTests, AMFDeserializeAMFArrayTest) { bitStream.Write(0x01); bitStream.Write(0x01); { - std::unique_ptr res(ReadFromBitStream(&bitStream)); + std::unique_ptr res{ ReadFromBitStream(bitStream) }; ASSERT_EQ(res->GetValueType(), eAmf::Array); ASSERT_EQ(static_cast(res.get())->GetAssociative().size(), 0); ASSERT_EQ(static_cast(res.get())->GetDense().size(), 0); @@ -164,7 +164,7 @@ TEST(dCommonTests, AMFDeserializeAMFArrayTest) { bitStream.Write(0x0B); for (auto e : "10447") if (e != '\0') bitStream.Write(e); { - std::unique_ptr res(ReadFromBitStream(&bitStream)); + std::unique_ptr res{ ReadFromBitStream(bitStream) }; ASSERT_EQ(res->GetValueType(), eAmf::Array); ASSERT_EQ(static_cast(res.get())->GetAssociative().size(), 1); ASSERT_EQ(static_cast(res.get())->GetDense().size(), 1); @@ -213,7 +213,7 @@ TEST(dCommonTests, AMFDeserializeUnimplementedValuesTest) { testBitStream.Write(value); bool caughtException = false; try { - ReadFromBitStream(&testBitStream); + ReadFromBitStream(testBitStream); } catch (eAmf unimplementedValueType) { caughtException = true; } @@ -238,119 +238,111 @@ TEST(dCommonTests, AMFDeserializeLivePacketTest) { testFileStream.close(); - std::unique_ptr resultFromFn(ReadFromBitStream(&testBitStream)); - auto result = static_cast(resultFromFn.get()); + std::unique_ptr resultFromFn{ ReadFromBitStream(testBitStream) }; + auto* result = static_cast(resultFromFn.get()); // Test the outermost array ASSERT_EQ(result->Get("BehaviorID")->GetValue(), "10447"); ASSERT_EQ(result->Get("objectID")->GetValue(), "288300744895913279"); // Test the execution state array - auto executionState = result->GetArray("executionState"); + auto* executionState = result->GetArray("executionState"); ASSERT_NE(executionState, nullptr); - auto strips = executionState->GetArray("strips")->GetDense(); + auto& strips = executionState->GetArray("strips")->GetDense(); ASSERT_EQ(strips.size(), 1); - auto stripsPosition0 = dynamic_cast(strips[0]); + auto* stripsPosition0 = dynamic_cast(strips[0]); - auto actionIndex = stripsPosition0->Get("actionIndex"); + auto* actionIndex = stripsPosition0->Get("actionIndex"); ASSERT_EQ(actionIndex->GetValue(), 0.0f); - auto stripIdExecution = stripsPosition0->Get("id"); + auto* stripIdExecution = stripsPosition0->Get("id"); ASSERT_EQ(stripIdExecution->GetValue(), 0.0f); - auto stateIdExecution = executionState->Get("stateID"); + auto* stateIdExecution = executionState->Get("stateID"); ASSERT_EQ(stateIdExecution->GetValue(), 0.0f); - auto states = result->GetArray("states")->GetDense(); + auto& states = result->GetArray("states")->GetDense(); ASSERT_EQ(states.size(), 1); - auto firstState = dynamic_cast(states[0]); + auto* firstState = dynamic_cast(states[0]); - auto stateID = firstState->Get("id"); + auto* stateID = firstState->Get("id"); ASSERT_EQ(stateID->GetValue(), 0.0f); - auto stripsInState = firstState->GetArray("strips")->GetDense(); + auto& stripsInState = firstState->GetArray("strips")->GetDense(); ASSERT_EQ(stripsInState.size(), 1); - auto firstStrip = dynamic_cast(stripsInState[0]); + auto* firstStrip = dynamic_cast(stripsInState[0]); - auto actionsInFirstStrip = firstStrip->GetArray("actions")->GetDense(); + auto& actionsInFirstStrip = firstStrip->GetArray("actions")->GetDense(); ASSERT_EQ(actionsInFirstStrip.size(), 3); - auto actionID = firstStrip->Get("id"); + auto* actionID = firstStrip->Get("id"); ASSERT_EQ(actionID->GetValue(), 0.0f); - auto uiArray = firstStrip->GetArray("ui"); + auto* uiArray = firstStrip->GetArray("ui"); - auto xPos = uiArray->Get("x"); - auto yPos = uiArray->Get("y"); + auto* xPos = uiArray->Get("x"); + auto* yPos = uiArray->Get("y"); ASSERT_EQ(xPos->GetValue(), 103.0f); ASSERT_EQ(yPos->GetValue(), 82.0f); - auto stripId = firstStrip->Get("id"); + auto* stripId = firstStrip->Get("id"); ASSERT_EQ(stripId->GetValue(), 0.0f); - auto firstAction = dynamic_cast(actionsInFirstStrip[0]); + auto* firstAction = dynamic_cast(actionsInFirstStrip[0]); - auto firstType = firstAction->Get("Type"); + auto* firstType = firstAction->Get("Type"); ASSERT_EQ(firstType->GetValue(), "OnInteract"); - auto firstCallback = firstAction->Get("__callbackID__"); + auto* firstCallback = firstAction->Get("__callbackID__"); ASSERT_EQ(firstCallback->GetValue(), ""); - auto secondAction = dynamic_cast(actionsInFirstStrip[1]); + auto* secondAction = dynamic_cast(actionsInFirstStrip[1]); - auto secondType = secondAction->Get("Type"); + auto* secondType = secondAction->Get("Type"); ASSERT_EQ(secondType->GetValue(), "FlyUp"); - auto secondCallback = secondAction->Get("__callbackID__"); + auto* secondCallback = secondAction->Get("__callbackID__"); ASSERT_EQ(secondCallback->GetValue(), ""); - auto secondDistance = secondAction->Get("Distance"); + auto* secondDistance = secondAction->Get("Distance"); ASSERT_EQ(secondDistance->GetValue(), 25.0f); - auto thirdAction = dynamic_cast(actionsInFirstStrip[2]); + auto* thirdAction = dynamic_cast(actionsInFirstStrip[2]); - auto thirdType = thirdAction->Get("Type"); + auto* thirdType = thirdAction->Get("Type"); ASSERT_EQ(thirdType->GetValue(), "FlyDown"); - auto thirdCallback = thirdAction->Get("__callbackID__"); + auto* thirdCallback = thirdAction->Get("__callbackID__"); ASSERT_EQ(thirdCallback->GetValue(), ""); - auto thirdDistance = thirdAction->Get("Distance"); + auto* thirdDistance = thirdAction->Get("Distance"); ASSERT_EQ(thirdDistance->GetValue(), 25.0f); } -/** - * @brief Tests that having no BitStream returns a nullptr. - */ -TEST(dCommonTests, AMFDeserializeNullTest) { - std::unique_ptr result(ReadFromBitStream(nullptr)); - ASSERT_EQ(result.get(), nullptr); -} - TEST(dCommonTests, AMFBadConversionTest) { std::ifstream testFileStream; testFileStream.open("AMFBitStreamTest.bin", std::ios::binary); @@ -364,7 +356,7 @@ TEST(dCommonTests, AMFBadConversionTest) { testFileStream.close(); - std::unique_ptr resultFromFn(ReadFromBitStream(&testBitStream)); + std::unique_ptr resultFromFn(ReadFromBitStream(testBitStream)); auto result = static_cast(resultFromFn.get()); // Actually a string value. diff --git a/tests/dCommonTests/CMakeLists.txt b/tests/dCommonTests/CMakeLists.txt index be23d866..ef7c4cba 100644 --- a/tests/dCommonTests/CMakeLists.txt +++ b/tests/dCommonTests/CMakeLists.txt @@ -1,7 +1,7 @@ set(DCOMMONTEST_SOURCES "AMFDeserializeTests.cpp" "Amf3Tests.cpp" - "CastUnderlyingTypeTests.cpp" + "ToUnderlyingTests.cpp" "HeaderSkipTest.cpp" "TestCDFeatureGatingTable.cpp" "TestLDFFormat.cpp" @@ -17,6 +17,19 @@ list(APPEND DCOMMONTEST_SOURCES ${DENUMS_TESTS}) # Set our executable add_executable(dCommonTests ${DCOMMONTEST_SOURCES}) +add_dependencies(dCommonTests conncpp_tests) + +# Apple needs some special linkage for the mariadb connector for tests. +if(APPLE) +add_custom_command(TARGET dCommonTests POST_BUILD + COMMAND otool ARGS -l dCommonTests + COMMAND otool ARGS -L dCommonTests + COMMAND ls + COMMAND otool ARGS -D libmariadbcpp.dylib + COMMAND install_name_tool ARGS -change libmariadbcpp.dylib @rpath/libmariadbcpp.dylib dCommonTests + COMMAND otool ARGS -L dCommonTests + WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +endif() # Link needed libraries target_link_libraries(dCommonTests ${COMMON_LIBRARIES} GTest::gtest_main) diff --git a/tests/dCommonTests/TestLDFFormat.cpp b/tests/dCommonTests/TestLDFFormat.cpp index 7baa5a0b..b761096c 100644 --- a/tests/dCommonTests/TestLDFFormat.cpp +++ b/tests/dCommonTests/TestLDFFormat.cpp @@ -27,7 +27,7 @@ TEST_F(LDFTests, LDFUTF16Test) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_16); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), u"IAmA weird string with :::: and spac,./;'][\\es that I expect to be parsed correctly...; "); + ASSERT_EQ((static_cast*>(data.get()))->GetValue(), u"IAmA weird string with :::: and spac,./;'][\\es that I expect to be parsed correctly...; "); ASSERT_EQ(data->GetString(), testWord); } @@ -37,7 +37,7 @@ TEST_F(LDFTests, LDFUTF16EmptyTest) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_16); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), u""); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), u""); ASSERT_EQ(data->GetString(), testWord); } @@ -47,7 +47,7 @@ TEST_F(LDFTests, LDFUTF16ColonTest) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_16); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), u"::"); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), u"::"); ASSERT_EQ(data->GetString(), testWord); } @@ -57,7 +57,7 @@ TEST_F(LDFTests, LDFUTF16EqualsTest) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_16); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), u"=="); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), u"=="); ASSERT_EQ(data->GetString(), testWord); } @@ -66,7 +66,7 @@ TEST_F(LDFTests, LDFS32Test) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_S32); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), -15); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), -15); ASSERT_EQ(data->GetString(), "KEY=1:-15"); } TEST_F(LDFTests, LDFU32Test) { @@ -74,7 +74,7 @@ TEST_F(LDFTests, LDFU32Test) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_U32); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), 15); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), 15); ASSERT_EQ(data->GetString(), "KEY=5:15"); } @@ -83,7 +83,7 @@ TEST_F(LDFTests, LDFU32TrueTest) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_U32); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), 1); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), 1); ASSERT_EQ(data->GetString(), "KEY=5:1"); } @@ -92,7 +92,7 @@ TEST_F(LDFTests, LDFU32FalseTest) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_U32); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), 0); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), 0); ASSERT_EQ(data->GetString(), "KEY=5:0"); } @@ -103,7 +103,7 @@ TEST_F(LDFTests, LDFFloatTest) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_FLOAT); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), 15.5f); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), 15.5f); ASSERT_EQ(data->GetString().find("KEY=3:15.5"), 0); } @@ -112,7 +112,7 @@ TEST_F(LDFTests, LDFDoubleTest) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_DOUBLE); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), 15.5); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), 15.5); ASSERT_EQ(data->GetString().find("KEY=4:15.5"), 0); } @@ -122,7 +122,7 @@ TEST_F(LDFTests, LDFBoolTrueTest) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_BOOLEAN); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), true); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), true); ASSERT_EQ(data->GetString(), "KEY=7:1"); } @@ -131,7 +131,7 @@ TEST_F(LDFTests, LDFBoolFalseTest) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_BOOLEAN); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), false); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), false); ASSERT_EQ(data->GetString(), "KEY=7:0"); } @@ -140,7 +140,7 @@ TEST_F(LDFTests, LDFBoolIntTest) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_BOOLEAN); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), true); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), true); ASSERT_EQ(data->GetString(), "KEY=7:1"); } @@ -149,7 +149,7 @@ TEST_F(LDFTests, LDFU64Test) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_U64); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), 15); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), 15); ASSERT_EQ(data->GetString(), "KEY=8:15"); } @@ -158,7 +158,7 @@ TEST_F(LDFTests, LDFLWOOBJIDTest) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_OBJID); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), 15); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), 15); ASSERT_EQ(data->GetString(), "KEY=9:15"); } @@ -168,7 +168,7 @@ TEST_F(LDFTests, LDFUTF8Test) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_8); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), "IAmA weird string with :::: and spac,./;'][\\es that I expect to be parsed correctly...; "); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), "IAmA weird string with :::: and spac,./;'][\\es that I expect to be parsed correctly...; "); ASSERT_EQ(data->GetString(), testWord); } @@ -178,7 +178,7 @@ TEST_F(LDFTests, LDFUTF8EmptyTest) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_8); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), ""); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), ""); ASSERT_EQ(data->GetString(), testWord); } @@ -188,7 +188,7 @@ TEST_F(LDFTests, LDFUTF8ColonsTest) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_8); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), "::"); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), "::"); ASSERT_EQ(data->GetString(), testWord); } TEST_F(LDFTests, LDFUTF8EqualsTest) { @@ -197,7 +197,7 @@ TEST_F(LDFTests, LDFUTF8EqualsTest) { ASSERT_NE(data, nullptr); ASSERT_EQ(data->GetValueType(), eLDFType::LDF_TYPE_UTF_8); ASSERT_EQ(data->GetKey(), u"KEY"); - ASSERT_EQ(((LDFData*)data.get())->GetValue(), "=="); + ASSERT_EQ(static_cast*>(data.get())->GetValue(), "=="); ASSERT_EQ(data->GetString(), testWord); } diff --git a/tests/dCommonTests/TestNiPoint3.cpp b/tests/dCommonTests/TestNiPoint3.cpp index fbc98eb0..49814d15 100644 --- a/tests/dCommonTests/TestNiPoint3.cpp +++ b/tests/dCommonTests/TestNiPoint3.cpp @@ -8,9 +8,9 @@ */ TEST(dCommonTests, NiPoint3Test) { // Check that Unitize works - ASSERT_EQ(NiPoint3(3, 0, 0).Unitize(), NiPoint3::UNIT_X); + ASSERT_EQ(NiPoint3(3, 0, 0).Unitize(), NiPoint3Constant::UNIT_X); // Check what unitize does to a vector of length 0 - ASSERT_EQ(NiPoint3::ZERO.Unitize(), NiPoint3::ZERO); + ASSERT_EQ(NiPoint3Constant::ZERO.Unitize(), NiPoint3Constant::ZERO); } TEST(dCommonTests, NiPoint3OperatorTest) { diff --git a/tests/dCommonTests/CastUnderlyingTypeTests.cpp b/tests/dCommonTests/ToUnderlyingTests.cpp similarity index 68% rename from tests/dCommonTests/CastUnderlyingTypeTests.cpp rename to tests/dCommonTests/ToUnderlyingTests.cpp index 9cdfcdd3..4cbf4635 100644 --- a/tests/dCommonTests/CastUnderlyingTypeTests.cpp +++ b/tests/dCommonTests/ToUnderlyingTests.cpp @@ -7,13 +7,13 @@ #include "eWorldMessageType.h" #define ASSERT_TYPE_EQ(TYPE, ENUM)\ - ASSERT_TRUE(typeid(TYPE) == typeid(GeneralUtils::CastUnderlyingType(static_cast(0)))); + ASSERT_TRUE(typeid(TYPE) == typeid(GeneralUtils::ToUnderlying(static_cast(0)))); #define ASSERT_TYPE_NE(TYPE, ENUM)\ - ASSERT_FALSE(typeid(TYPE) == typeid(GeneralUtils::CastUnderlyingType(static_cast(0)))); + ASSERT_FALSE(typeid(TYPE) == typeid(GeneralUtils::ToUnderlying(static_cast(0)))); // Verify that the underlying enum types are being cast correctly -TEST(CastUnderlyingTypeTests, VerifyCastUnderlyingType) { +TEST(ToUnderlyingTests, VerifyToUnderlying) { ASSERT_TYPE_EQ(uint8_t, eGameMasterLevel); ASSERT_TYPE_EQ(uint16_t, eGameMessageType); ASSERT_TYPE_EQ(uint32_t, eWorldMessageType) diff --git a/tests/dGameTests/CMakeLists.txt b/tests/dGameTests/CMakeLists.txt index b1fdaa07..58f213e0 100644 --- a/tests/dGameTests/CMakeLists.txt +++ b/tests/dGameTests/CMakeLists.txt @@ -12,8 +12,18 @@ file(COPY ${GAMEMESSAGE_TESTBITSTREAMS} DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) # Add the executable. Remember to add all tests above this! add_executable(dGameTests ${DGAMETEST_SOURCES}) +add_dependencies(dGameTests conncpp_tests) -target_link_libraries(dGameTests ${COMMON_LIBRARIES} GTest::gtest_main dGame dZoneManager dPhysics Detour Recast tinyxml2 dWorldServer dChatFilter dNavigation) +# Apple needs some special linkage for the mariadb connector for tests. +if(APPLE) +add_custom_command(TARGET dGameTests POST_BUILD + COMMAND install_name_tool ARGS -change libmariadbcpp.dylib @rpath/libmariadbcpp.dylib dGameTests + COMMAND otool ARGS -L dGameTests + WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}) +endif() + +target_link_libraries(dGameTests ${COMMON_LIBRARIES} GTest::gtest_main + dGame dScripts dPhysics Detour Recast tinyxml2 dWorldServer dZoneManager dChatFilter dNavigation) # Discover the tests gtest_discover_tests(dGameTests) diff --git a/tests/dGameTests/GameDependencies.h b/tests/dGameTests/GameDependencies.h index 8aefaa3d..52e3919a 100644 --- a/tests/dGameTests/GameDependencies.h +++ b/tests/dGameTests/GameDependencies.h @@ -19,14 +19,14 @@ public: dServerMock() {}; ~dServerMock() {}; RakNet::BitStream* GetMostRecentBitStream() { return sentBitStream; }; - void Send(RakNet::BitStream* bitStream, const SystemAddress& sysAddr, bool broadcast) override { sentBitStream = bitStream; }; + void Send(RakNet::BitStream& bitStream, const SystemAddress& sysAddr, bool broadcast) override { sentBitStream = &bitStream; }; }; class GameDependenciesTest : public ::testing::Test { protected: void SetUpDependencies() { - info.pos = NiPoint3::ZERO; - info.rot = NiQuaternion::IDENTITY; + info.pos = NiPoint3Constant::ZERO; + info.rot = NiQuaternionConstant::IDENTITY; info.scale = 1.0f; info.spawner = nullptr; info.lot = 999; @@ -36,7 +36,7 @@ protected: Game::entityManager = new EntityManager(); // Create a CDClientManager instance and load from defaults - CDClientManager::Instance().LoadValuesFromDefaults(); + CDClientManager::LoadValuesFromDefaults(); } void TearDownDependencies() { diff --git a/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp b/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp index ff37f154..d14004ee 100644 --- a/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp +++ b/tests/dGameTests/dComponentsTests/DestroyableComponentTests.cpp @@ -48,7 +48,7 @@ TEST_F(DestroyableTest, PlacementNewAddComponentTest) { * Test Construction of a DestroyableComponent */ TEST_F(DestroyableTest, DestroyableComponentSerializeConstructionTest) { - destroyableComponent->Serialize(&bitStream, true); + destroyableComponent->Serialize(bitStream, true); // Assert that the full number of bits are present ASSERT_EQ(bitStream.GetNumberOfUnreadBits(), 748); { @@ -178,7 +178,7 @@ TEST_F(DestroyableTest, DestroyableComponentSerializeTest) { destroyableComponent->SetMaxHealth(1233.0f); // Now we test a serialization for correctness. - destroyableComponent->Serialize(&bitStream, false); + destroyableComponent->Serialize(bitStream, false); ASSERT_EQ(bitStream.GetNumberOfUnreadBits(), 422); { // Now read in the full serialized BitStream diff --git a/tests/dGameTests/dComponentsTests/SimplePhysicsComponentTests.cpp b/tests/dGameTests/dComponentsTests/SimplePhysicsComponentTests.cpp index 896dcf5a..0116dfcc 100644 --- a/tests/dGameTests/dComponentsTests/SimplePhysicsComponentTests.cpp +++ b/tests/dGameTests/dComponentsTests/SimplePhysicsComponentTests.cpp @@ -30,7 +30,7 @@ protected: }; TEST_F(SimplePhysicsTest, SimplePhysicsSerializeTest) { - simplePhysicsComponent->Serialize(&bitStream, false); + simplePhysicsComponent->Serialize(bitStream, false); constexpr uint32_t sizeOfStream = 3 + BYTES_TO_BITS(3 * sizeof(NiPoint3)) + BYTES_TO_BITS(1 * sizeof(NiQuaternion)) + 1 * BYTES_TO_BITS(sizeof(uint32_t)); ASSERT_EQ(bitStream.GetNumberOfBitsUsed(), sizeOfStream); @@ -77,7 +77,7 @@ TEST_F(SimplePhysicsTest, SimplePhysicsSerializeTest) { } TEST_F(SimplePhysicsTest, SimplePhysicsConstructionTest) { - simplePhysicsComponent->Serialize(&bitStream, true); + simplePhysicsComponent->Serialize(bitStream, true); constexpr uint32_t sizeOfStream = 4 + BYTES_TO_BITS(1 * sizeof(int32_t)) + BYTES_TO_BITS(3 * sizeof(NiPoint3)) + BYTES_TO_BITS(1 * sizeof(NiQuaternion)) + 1 * BYTES_TO_BITS(sizeof(uint32_t)); ASSERT_EQ(bitStream.GetNumberOfBitsUsed(), sizeOfStream); diff --git a/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp b/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp index 047f56d6..2d37d102 100644 --- a/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp +++ b/tests/dGameTests/dGameMessagesTests/GameMessageTests.cpp @@ -38,11 +38,11 @@ protected: } return readFile; } - AMFArrayValue* ReadArrayFromBitStream(RakNet::BitStream* inStream) { + const AMFArrayValue& ReadArrayFromBitStream(RakNet::BitStream& inStream) { AMFDeserialize des; AMFBaseValue* readArray = des.Read(inStream); EXPECT_EQ(readArray->GetValueType(), eAmf::Array); - return static_cast(readArray); + return static_cast(*readArray); } }; @@ -87,13 +87,13 @@ TEST_F(GameMessageTests, SendBlueprintLoadItemResponse) { TEST_F(GameMessageTests, ControlBehaviorAddStrip) { auto data = ReadFromFile("addStrip"); - RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); - AddStripMessage addStrip(ReadArrayFromBitStream(&inStream)); + RakNet::BitStream inStream(reinterpret_cast(&data[0]), data.length(), true); + AddStripMessage addStrip(ReadArrayFromBitStream(inStream)); ASSERT_FLOAT_EQ(addStrip.GetPosition().GetX(), 50.65); ASSERT_FLOAT_EQ(addStrip.GetPosition().GetY(), 178.05); ASSERT_EQ(addStrip.GetActionContext().GetStripId(), 0); ASSERT_EQ(static_cast(addStrip.GetActionContext().GetStateId()), 0); - ASSERT_EQ(addStrip.GetBehaviorId(), -1); + ASSERT_EQ(addStrip.GetBehaviorId(), BehaviorMessageBase::DefaultBehaviorId); ASSERT_EQ(addStrip.GetActionsToAdd().front().GetType(), "DropImagination"); ASSERT_EQ(addStrip.GetActionsToAdd().front().GetValueParameterName(), "Amount"); ASSERT_EQ(addStrip.GetActionsToAdd().front().GetValueParameterString(), ""); @@ -102,29 +102,29 @@ TEST_F(GameMessageTests, ControlBehaviorAddStrip) { TEST_F(GameMessageTests, ControlBehaviorRemoveStrip) { auto data = ReadFromFile("removeStrip"); - RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); - RemoveStripMessage removeStrip(ReadArrayFromBitStream(&inStream)); + RakNet::BitStream inStream(reinterpret_cast(&data[0]), data.length(), true); + RemoveStripMessage removeStrip(ReadArrayFromBitStream(inStream)); ASSERT_EQ(static_cast(removeStrip.GetActionContext().GetStripId()), 1); ASSERT_EQ(static_cast(removeStrip.GetActionContext().GetStateId()), 0); - ASSERT_EQ(removeStrip.GetBehaviorId(), -1); + ASSERT_EQ(removeStrip.GetBehaviorId(), BehaviorMessageBase::DefaultBehaviorId); } TEST_F(GameMessageTests, ControlBehaviorMergeStrips) { auto data = ReadFromFile("mergeStrips"); - RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); - MergeStripsMessage mergeStrips(ReadArrayFromBitStream(&inStream)); + RakNet::BitStream inStream(reinterpret_cast(&data[0]), data.length(), true); + MergeStripsMessage mergeStrips(ReadArrayFromBitStream(inStream)); ASSERT_EQ(mergeStrips.GetSourceActionContext().GetStripId(), 2); ASSERT_EQ(mergeStrips.GetDestinationActionContext().GetStripId(), 0); ASSERT_EQ(static_cast(mergeStrips.GetSourceActionContext().GetStateId()), 0); ASSERT_EQ(static_cast(mergeStrips.GetDestinationActionContext().GetStateId()), 0); ASSERT_EQ(mergeStrips.GetDstActionIndex(), 0); - ASSERT_EQ(mergeStrips.GetBehaviorId(), -1); + ASSERT_EQ(mergeStrips.GetBehaviorId(), BehaviorMessageBase::DefaultBehaviorId); } TEST_F(GameMessageTests, ControlBehaviorSplitStrip) { auto data = ReadFromFile("splitStrip"); - RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); - SplitStripMessage splitStrip(ReadArrayFromBitStream(&inStream)); + RakNet::BitStream inStream(reinterpret_cast(&data[0]), data.length(), true); + SplitStripMessage splitStrip(ReadArrayFromBitStream(inStream)); ASSERT_EQ(splitStrip.GetBehaviorId(), -1); ASSERT_FLOAT_EQ(splitStrip.GetPosition().GetX(), 275.65); @@ -138,19 +138,19 @@ TEST_F(GameMessageTests, ControlBehaviorSplitStrip) { TEST_F(GameMessageTests, ControlBehaviorUpdateStripUI) { auto data = ReadFromFile("updateStripUI"); - RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); - UpdateStripUiMessage updateStripUi(ReadArrayFromBitStream(&inStream)); + RakNet::BitStream inStream(reinterpret_cast(&data[0]), data.length(), true); + UpdateStripUiMessage updateStripUi(ReadArrayFromBitStream(inStream)); ASSERT_FLOAT_EQ(updateStripUi.GetPosition().GetX(), 116.65); ASSERT_FLOAT_EQ(updateStripUi.GetPosition().GetY(), 35.35); ASSERT_EQ(updateStripUi.GetActionContext().GetStripId(), 0); ASSERT_EQ(static_cast(updateStripUi.GetActionContext().GetStateId()), 0); - ASSERT_EQ(updateStripUi.GetBehaviorId(), -1); + ASSERT_EQ(updateStripUi.GetBehaviorId(), BehaviorMessageBase::DefaultBehaviorId); } TEST_F(GameMessageTests, ControlBehaviorAddAction) { auto data = ReadFromFile("addAction"); - RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); - AddActionMessage addAction(ReadArrayFromBitStream(&inStream)); + RakNet::BitStream inStream(reinterpret_cast(&data[0]), data.length(), true); + AddActionMessage addAction(ReadArrayFromBitStream(inStream)); ASSERT_EQ(addAction.GetActionIndex(), 3); ASSERT_EQ(addAction.GetActionContext().GetStripId(), 0); ASSERT_EQ(static_cast(addAction.GetActionContext().GetStateId()), 0); @@ -158,45 +158,45 @@ TEST_F(GameMessageTests, ControlBehaviorAddAction) { ASSERT_EQ(addAction.GetAction().GetValueParameterName(), ""); ASSERT_EQ(addAction.GetAction().GetValueParameterString(), ""); ASSERT_EQ(addAction.GetAction().GetValueParameterDouble(), 0.0); - ASSERT_EQ(addAction.GetBehaviorId(), -1); + ASSERT_EQ(addAction.GetBehaviorId(), BehaviorMessageBase::DefaultBehaviorId); } TEST_F(GameMessageTests, ControlBehaviorMigrateActions) { auto data = ReadFromFile("migrateActions"); - RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); - MigrateActionsMessage migrateActions(ReadArrayFromBitStream(&inStream)); + RakNet::BitStream inStream(reinterpret_cast(&data[0]), data.length(), true); + MigrateActionsMessage migrateActions(ReadArrayFromBitStream(inStream)); ASSERT_EQ(migrateActions.GetSrcActionIndex(), 1); ASSERT_EQ(migrateActions.GetDstActionIndex(), 2); ASSERT_EQ(migrateActions.GetSourceActionContext().GetStripId(), 1); ASSERT_EQ(migrateActions.GetDestinationActionContext().GetStripId(), 0); ASSERT_EQ(static_cast(migrateActions.GetSourceActionContext().GetStateId()), 0); ASSERT_EQ(static_cast(migrateActions.GetDestinationActionContext().GetStateId()), 0); - ASSERT_EQ(migrateActions.GetBehaviorId(), -1); + ASSERT_EQ(migrateActions.GetBehaviorId(), BehaviorMessageBase::DefaultBehaviorId); } TEST_F(GameMessageTests, ControlBehaviorRearrangeStrip) { auto data = ReadFromFile("rearrangeStrip"); - RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); - RearrangeStripMessage rearrangeStrip(ReadArrayFromBitStream(&inStream)); + RakNet::BitStream inStream(reinterpret_cast(&data[0]), data.length(), true); + RearrangeStripMessage rearrangeStrip(ReadArrayFromBitStream(inStream)); ASSERT_EQ(rearrangeStrip.GetSrcActionIndex(), 2); ASSERT_EQ(rearrangeStrip.GetDstActionIndex(), 1); ASSERT_EQ(rearrangeStrip.GetActionContext().GetStripId(), 0); - ASSERT_EQ(rearrangeStrip.GetBehaviorId(), -1); + ASSERT_EQ(rearrangeStrip.GetBehaviorId(), BehaviorMessageBase::DefaultBehaviorId); ASSERT_EQ(static_cast(rearrangeStrip.GetActionContext().GetStateId()), 0); } TEST_F(GameMessageTests, ControlBehaviorAdd) { auto data = ReadFromFile("add"); - RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); - AddMessage add(ReadArrayFromBitStream(&inStream)); + RakNet::BitStream inStream(reinterpret_cast(&data[0]), data.length(), true); + AddMessage add(ReadArrayFromBitStream(inStream)); ASSERT_EQ(add.GetBehaviorId(), 10446); ASSERT_EQ(add.GetBehaviorIndex(), 0); } TEST_F(GameMessageTests, ControlBehaviorRemoveActions) { auto data = ReadFromFile("removeActions"); - RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); - RemoveActionsMessage removeActions(ReadArrayFromBitStream(&inStream)); + RakNet::BitStream inStream(reinterpret_cast(&data[0]), data.length(), true); + RemoveActionsMessage removeActions(ReadArrayFromBitStream(inStream)); ASSERT_EQ(removeActions.GetBehaviorId(), -1); ASSERT_EQ(removeActions.GetActionIndex(), 1); ASSERT_EQ(removeActions.GetActionContext().GetStripId(), 0); @@ -205,21 +205,21 @@ TEST_F(GameMessageTests, ControlBehaviorRemoveActions) { TEST_F(GameMessageTests, ControlBehaviorRename) { auto data = ReadFromFile("rename"); - RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); - RenameMessage rename(ReadArrayFromBitStream(&inStream)); + RakNet::BitStream inStream(reinterpret_cast(&data[0]), data.length(), true); + RenameMessage rename(ReadArrayFromBitStream(inStream)); ASSERT_EQ(rename.GetName(), "test"); - ASSERT_EQ(rename.GetBehaviorId(), -1); + ASSERT_EQ(rename.GetBehaviorId(), BehaviorMessageBase::DefaultBehaviorId); } TEST_F(GameMessageTests, ControlBehaviorUpdateAction) { auto data = ReadFromFile("updateAction"); - RakNet::BitStream inStream((unsigned char*)data.c_str(), data.length(), true); - UpdateActionMessage updateAction(ReadArrayFromBitStream(&inStream)); + RakNet::BitStream inStream(reinterpret_cast(&data[0]), data.length(), true); + UpdateActionMessage updateAction(ReadArrayFromBitStream(inStream)); ASSERT_EQ(updateAction.GetAction().GetType(), "FlyDown"); ASSERT_EQ(updateAction.GetAction().GetValueParameterName(), "Distance"); ASSERT_EQ(updateAction.GetAction().GetValueParameterString(), ""); ASSERT_EQ(updateAction.GetAction().GetValueParameterDouble(), 50.0); - ASSERT_EQ(updateAction.GetBehaviorId(), -1); + ASSERT_EQ(updateAction.GetBehaviorId(), BehaviorMessageBase::DefaultBehaviorId); ASSERT_EQ(updateAction.GetActionIndex(), 1); ASSERT_EQ(updateAction.GetActionContext().GetStripId(), 0); ASSERT_EQ(static_cast(updateAction.GetActionContext().GetStateId()), 0); diff --git a/tests/dGameTests/dGameMessagesTests/LegacyGameMessageTests.cpp b/tests/dGameTests/dGameMessagesTests/LegacyGameMessageTests.cpp index 0226b0ad..47b930ed 100644 --- a/tests/dGameTests/dGameMessagesTests/LegacyGameMessageTests.cpp +++ b/tests/dGameTests/dGameMessagesTests/LegacyGameMessageTests.cpp @@ -2,297 +2,297 @@ #include "eGameMessageType.h" TEST(LegacyGameMessageTests, AssertLegacyGmValues) { - EXPECT_EQ(eGameMessageType::TELEPORT, (eGameMessageType)19); - EXPECT_EQ(eGameMessageType::SET_PLAYER_CONTROL_SCHEME, (eGameMessageType)26); - EXPECT_EQ(eGameMessageType::DROP_CLIENT_LOOT, (eGameMessageType)30); - EXPECT_EQ(eGameMessageType::DIE, (eGameMessageType)37); - EXPECT_EQ(eGameMessageType::REQUEST_DIE, (eGameMessageType)38); - EXPECT_EQ(eGameMessageType::PLAY_EMOTE, (eGameMessageType)41); - EXPECT_EQ(eGameMessageType::PLAY_ANIMATION, (eGameMessageType)43); - EXPECT_EQ(eGameMessageType::CONTROL_BEHAVIORS, (eGameMessageType)48); - EXPECT_EQ(eGameMessageType::SET_NAME, (eGameMessageType)72); - EXPECT_EQ(eGameMessageType::ECHO_START_SKILL, (eGameMessageType)118); - EXPECT_EQ(eGameMessageType::START_SKILL, (eGameMessageType)119); - EXPECT_EQ(eGameMessageType::VERIFY_ACK, (eGameMessageType)121); - EXPECT_EQ(eGameMessageType::ADD_SKILL, (eGameMessageType)127); - EXPECT_EQ(eGameMessageType::REMOVE_SKILL, (eGameMessageType)128); - EXPECT_EQ(eGameMessageType::SET_CURRENCY, (eGameMessageType)133); - EXPECT_EQ(eGameMessageType::PICKUP_CURRENCY, (eGameMessageType)137); - EXPECT_EQ(eGameMessageType::PICKUP_ITEM, (eGameMessageType)139); - EXPECT_EQ(eGameMessageType::TEAM_PICKUP_ITEM, (eGameMessageType)140); - EXPECT_EQ(eGameMessageType::PLAY_FX_EFFECT, (eGameMessageType)154); - EXPECT_EQ(eGameMessageType::STOP_FX_EFFECT, (eGameMessageType)155); - EXPECT_EQ(eGameMessageType::REQUEST_RESURRECT, (eGameMessageType)159); - EXPECT_EQ(eGameMessageType::RESURRECT, (eGameMessageType)160); - EXPECT_EQ(eGameMessageType::PUSH_EQUIPPED_ITEMS_STATE, (eGameMessageType)191); - EXPECT_EQ(eGameMessageType::POP_EQUIPPED_ITEMS_STATE, (eGameMessageType)192); - EXPECT_EQ(eGameMessageType::SET_GM_LEVEL, (eGameMessageType)193); - EXPECT_EQ(eGameMessageType::SET_STUNNED, (eGameMessageType)198); - EXPECT_EQ(eGameMessageType::SET_STUN_IMMUNITY, (eGameMessageType)200); - EXPECT_EQ(eGameMessageType::KNOCKBACK, (eGameMessageType)202); - EXPECT_EQ(eGameMessageType::REBUILD_CANCEL, (eGameMessageType)209); - EXPECT_EQ(eGameMessageType::ENABLE_REBUILD, (eGameMessageType)213); - EXPECT_EQ(eGameMessageType::MOVE_ITEM_IN_INVENTORY, (eGameMessageType)224); - EXPECT_EQ(eGameMessageType::ADD_ITEM_TO_INVENTORY_CLIENT_SYNC, (eGameMessageType)227); - EXPECT_EQ(eGameMessageType::REMOVE_ITEM_FROM_INVENTORY, (eGameMessageType)230); - EXPECT_EQ(eGameMessageType::EQUIP_INVENTORY, (eGameMessageType)231); - EXPECT_EQ(eGameMessageType::UN_EQUIP_INVENTORY, (eGameMessageType)233); - EXPECT_EQ(eGameMessageType::OFFER_MISSION, (eGameMessageType)248); - EXPECT_EQ(eGameMessageType::RESPOND_TO_MISSION, (eGameMessageType)249); - EXPECT_EQ(eGameMessageType::NOTIFY_MISSION, (eGameMessageType)254); - EXPECT_EQ(eGameMessageType::NOTIFY_MISSION_TASK, (eGameMessageType)255); - EXPECT_EQ(eGameMessageType::REBUILD_NOTIFY_STATE, (eGameMessageType)336); - EXPECT_EQ(eGameMessageType::TERMINATE_INTERACTION, (eGameMessageType)357); - EXPECT_EQ(eGameMessageType::SERVER_TERMINATE_INTERACTION, (eGameMessageType)358); - EXPECT_EQ(eGameMessageType::REQUEST_USE, (eGameMessageType)364); - EXPECT_EQ(eGameMessageType::VENDOR_OPEN_WINDOW, (eGameMessageType)369); - EXPECT_EQ(eGameMessageType::BUY_FROM_VENDOR, (eGameMessageType)373); - EXPECT_EQ(eGameMessageType::SELL_TO_VENDOR, (eGameMessageType)374); - EXPECT_EQ(eGameMessageType::TEAM_SET_OFF_WORLD_FLAG, (eGameMessageType)383); - EXPECT_EQ(eGameMessageType::SET_INVENTORY_SIZE, (eGameMessageType)389); - EXPECT_EQ(eGameMessageType::ACKNOWLEDGE_POSSESSION, (eGameMessageType)391); - EXPECT_EQ(eGameMessageType::SET_SHOOTING_GALLERY_PARAMS, (eGameMessageType)400); - EXPECT_EQ(eGameMessageType::REQUEST_ACTIVITY_START_STOP, (eGameMessageType)402); - EXPECT_EQ(eGameMessageType::REQUEST_ACTIVITY_ENTER, (eGameMessageType)403); - EXPECT_EQ(eGameMessageType::REQUEST_ACTIVITY_EXIT, (eGameMessageType)404); - EXPECT_EQ(eGameMessageType::ACTIVITY_ENTER, (eGameMessageType)405); - EXPECT_EQ(eGameMessageType::ACTIVITY_EXIT, (eGameMessageType)406); - EXPECT_EQ(eGameMessageType::ACTIVITY_START, (eGameMessageType)407); - EXPECT_EQ(eGameMessageType::ACTIVITY_STOP, (eGameMessageType)408); - EXPECT_EQ(eGameMessageType::SHOOTING_GALLERY_CLIENT_AIM_UPDATE, (eGameMessageType)409); - EXPECT_EQ(eGameMessageType::SHOOTING_GALLERY_FIRE, (eGameMessageType)411); - EXPECT_EQ(eGameMessageType::REQUEST_VENDOR_STATUS_UPDATE, (eGameMessageType)416); - EXPECT_EQ(eGameMessageType::VENDOR_STATUS_UPDATE, (eGameMessageType)417); - EXPECT_EQ(eGameMessageType::NOTIFY_CLIENT_SHOOTING_GALLERY_SCORE, (eGameMessageType)425); - EXPECT_EQ(eGameMessageType::CONSUME_CLIENT_ITEM, (eGameMessageType)427); - EXPECT_EQ(eGameMessageType::CLIENT_ITEM_CONSUMED, (eGameMessageType)428); - EXPECT_EQ(eGameMessageType::UPDATE_SHOOTING_GALLERY_ROTATION, (eGameMessageType)448); - EXPECT_EQ(eGameMessageType::SET_FLAG, (eGameMessageType)471); - EXPECT_EQ(eGameMessageType::NOTIFY_CLIENT_FLAG_CHANGE, (eGameMessageType)472); - EXPECT_EQ(eGameMessageType::VENDOR_TRANSACTION_RESULT, (eGameMessageType)476); - EXPECT_EQ(eGameMessageType::HAS_BEEN_COLLECTED, (eGameMessageType)486); - EXPECT_EQ(eGameMessageType::DISPLAY_CHAT_BUBBLE, (eGameMessageType)495); - EXPECT_EQ(eGameMessageType::SPAWN_PET, (eGameMessageType)498); - EXPECT_EQ(eGameMessageType::DESPAWN_PET, (eGameMessageType)499); - EXPECT_EQ(eGameMessageType::PLAYER_LOADED, (eGameMessageType)505); - EXPECT_EQ(eGameMessageType::PLAYER_READY, (eGameMessageType)509); - EXPECT_EQ(eGameMessageType::REQUEST_LINKED_MISSION, (eGameMessageType)515); - EXPECT_EQ(eGameMessageType::INVALID_ZONE_TRANSFER_LIST, (eGameMessageType)519); - EXPECT_EQ(eGameMessageType::MISSION_DIALOGUE_OK, (eGameMessageType)520); - EXPECT_EQ(eGameMessageType::DISPLAY_MESSAGE_BOX, (eGameMessageType)529); - EXPECT_EQ(eGameMessageType::MESSAGE_BOX_RESPOND, (eGameMessageType)530); - EXPECT_EQ(eGameMessageType::CHOICE_BOX_RESPOND, (eGameMessageType)531); - EXPECT_EQ(eGameMessageType::SMASH, (eGameMessageType)537); - EXPECT_EQ(eGameMessageType::UN_SMASH, (eGameMessageType)538); - EXPECT_EQ(eGameMessageType::PLACE_MODEL_RESPONSE, (eGameMessageType)547); - EXPECT_EQ(eGameMessageType::SET_SHOOTING_GALLERY_RETICULE_EFFECT, (eGameMessageType)546); - EXPECT_EQ(eGameMessageType::SET_JET_PACK_MODE, (eGameMessageType)561); - EXPECT_EQ(eGameMessageType::REGISTER_PET_ID, (eGameMessageType)565); - EXPECT_EQ(eGameMessageType::REGISTER_PET_DBID, (eGameMessageType)566); - EXPECT_EQ(eGameMessageType::SHOW_ACTIVITY_COUNTDOWN, (eGameMessageType)568); - EXPECT_EQ(eGameMessageType::START_ACTIVITY_TIME, (eGameMessageType)576); - EXPECT_EQ(eGameMessageType::ACTIVITY_PAUSE, (eGameMessageType)602); - EXPECT_EQ(eGameMessageType::USE_NON_EQUIPMENT_ITEM, (eGameMessageType)603); - EXPECT_EQ(eGameMessageType::USE_ITEM_RESULT, (eGameMessageType)607); - EXPECT_EQ(eGameMessageType::COMMAND_PET, (eGameMessageType)640); - EXPECT_EQ(eGameMessageType::PET_RESPONSE, (eGameMessageType)641); - EXPECT_EQ(eGameMessageType::REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA, (eGameMessageType)648); - EXPECT_EQ(eGameMessageType::SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA, (eGameMessageType)649); - EXPECT_EQ(eGameMessageType::NOTIFY_OBJECT, (eGameMessageType)656); - EXPECT_EQ(eGameMessageType::CLIENT_NOTIFY_PET, (eGameMessageType)659); - EXPECT_EQ(eGameMessageType::NOTIFY_PET, (eGameMessageType)660); - EXPECT_EQ(eGameMessageType::NOTIFY_PET_TAMING_MINIGAME, (eGameMessageType)661); - EXPECT_EQ(eGameMessageType::START_SERVER_PET_MINIGAME_TIMER, (eGameMessageType)662); - EXPECT_EQ(eGameMessageType::CLIENT_EXIT_TAMING_MINIGAME, (eGameMessageType)663); - EXPECT_EQ(eGameMessageType::PET_NAME_CHANGED, (eGameMessageType)686); - EXPECT_EQ(eGameMessageType::PET_TAMING_MINIGAME_RESULT, (eGameMessageType)667); - EXPECT_EQ(eGameMessageType::PET_TAMING_TRY_BUILD_RESULT, (eGameMessageType)668); - EXPECT_EQ(eGameMessageType::NOTIFY_TAMING_BUILD_SUCCESS, (eGameMessageType)673); - EXPECT_EQ(eGameMessageType::NOTIFY_TAMING_MODEL_LOADED_ON_SERVER, (eGameMessageType)674); - EXPECT_EQ(eGameMessageType::ACTIVATE_BUBBLE_BUFF, (eGameMessageType)678); - EXPECT_EQ(eGameMessageType::DECTIVATE_BUBBLE_BUFF, (eGameMessageType)679); - EXPECT_EQ(eGameMessageType::ADD_PET_TO_PLAYER, (eGameMessageType)681); - EXPECT_EQ(eGameMessageType::REQUEST_SET_PET_NAME, (eGameMessageType)683); - EXPECT_EQ(eGameMessageType::SET_PET_NAME, (eGameMessageType)684); - EXPECT_EQ(eGameMessageType::NOTIFY_TAMING_PUZZLE_SELECTED, (eGameMessageType)675); - EXPECT_EQ(eGameMessageType::SHOW_PET_ACTION_BUTTON, (eGameMessageType)692); - EXPECT_EQ(eGameMessageType::SET_EMOTE_LOCK_STATE, (eGameMessageType)693); - EXPECT_EQ(eGameMessageType::USE_ITEM_REQUIREMENTS_RESPONSE, (eGameMessageType)703); - EXPECT_EQ(eGameMessageType::PLAY_EMBEDDED_EFFECT_ON_ALL_CLIENTS_NEAR_OBJECT, (eGameMessageType)713); - EXPECT_EQ(eGameMessageType::DOWNLOAD_PROPERTY_DATA, (eGameMessageType)716); - EXPECT_EQ(eGameMessageType::QUERY_PROPERTY_DATA, (eGameMessageType)717); - EXPECT_EQ(eGameMessageType::PROPERTY_EDITOR_BEGIN, (eGameMessageType)724); - EXPECT_EQ(eGameMessageType::PROPERTY_EDITOR_END, (eGameMessageType)725); - EXPECT_EQ(eGameMessageType::IS_MINIFIG_IN_A_BUBBLE, (eGameMessageType)729); - EXPECT_EQ(eGameMessageType::START_PATHING, (eGameMessageType)733); - EXPECT_EQ(eGameMessageType::ACTIVATE_BUBBLE_BUFF_FROM_SERVER, (eGameMessageType)734); - EXPECT_EQ(eGameMessageType::DEACTIVATE_BUBBLE_BUFF_FROM_SERVER, (eGameMessageType)735); - EXPECT_EQ(eGameMessageType::NOTIFY_CLIENT_ZONE_OBJECT, (eGameMessageType)737); - EXPECT_EQ(eGameMessageType::UPDATE_REPUTATION, (eGameMessageType)746); - EXPECT_EQ(eGameMessageType::PROPERTY_RENTAL_RESPONSE, (eGameMessageType)750); - EXPECT_EQ(eGameMessageType::REQUEST_PLATFORM_RESYNC, (eGameMessageType)760); - EXPECT_EQ(eGameMessageType::PLATFORM_RESYNC, (eGameMessageType)761); - EXPECT_EQ(eGameMessageType::PLAY_CINEMATIC, (eGameMessageType)762); - EXPECT_EQ(eGameMessageType::END_CINEMATIC, (eGameMessageType)763); - EXPECT_EQ(eGameMessageType::CINEMATIC_UPDATE, (eGameMessageType)764); - EXPECT_EQ(eGameMessageType::TOGGLE_GHOST_REFERENCE_OVERRIDE, (eGameMessageType)767); - EXPECT_EQ(eGameMessageType::SET_GHOST_REFERENCE_POSITION, (eGameMessageType)768); - EXPECT_EQ(eGameMessageType::FIRE_EVENT_SERVER_SIDE, (eGameMessageType)770); - EXPECT_EQ(eGameMessageType::SCRIPT_NETWORK_VAR_UPDATE, (eGameMessageType)781); - EXPECT_EQ(eGameMessageType::UPDATE_MODEL_FROM_CLIENT, (eGameMessageType)793); - EXPECT_EQ(eGameMessageType::DELETE_MODEL_FROM_CLIENT, (eGameMessageType)794); - EXPECT_EQ(eGameMessageType::PLAY_ND_AUDIO_EMITTER, (eGameMessageType)821); - EXPECT_EQ(eGameMessageType::PLAY2_D_AMBIENT_SOUND, (eGameMessageType)831); - EXPECT_EQ(eGameMessageType::ENTER_PROPERTY1, (eGameMessageType)840); - EXPECT_EQ(eGameMessageType::ENTER_PROPERTY2, (eGameMessageType)841); - EXPECT_EQ(eGameMessageType::PROPERTY_ENTRANCE_SYNC, (eGameMessageType)842); - EXPECT_EQ(eGameMessageType::PROPERTY_SELECT_QUERY, (eGameMessageType)845); - EXPECT_EQ(eGameMessageType::PARSE_CHAT_MESSAGE, (eGameMessageType)850); - EXPECT_EQ(eGameMessageType::BROADCAST_TEXT_TO_CHATBOX, (eGameMessageType)858); - EXPECT_EQ(eGameMessageType::OPEN_PROPERTY_MANAGEMENT, (eGameMessageType)860); - EXPECT_EQ(eGameMessageType::OPEN_PROPERTY_VENDOR, (eGameMessageType)861); - EXPECT_EQ(eGameMessageType::UPDATE_PROPERTY_OR_MODEL_FOR_FILTER_CHECK, (eGameMessageType)863); - EXPECT_EQ(eGameMessageType::CLIENT_TRADE_REQUEST, (eGameMessageType)868); - EXPECT_EQ(eGameMessageType::SERVER_TRADE_REQUEST, (eGameMessageType)869); - EXPECT_EQ(eGameMessageType::SERVER_TRADE_INVITE, (eGameMessageType)870); - EXPECT_EQ(eGameMessageType::CLIENT_TRADE_REPLY, (eGameMessageType)871); - EXPECT_EQ(eGameMessageType::SERVER_TRADE_REPLY, (eGameMessageType)872); - EXPECT_EQ(eGameMessageType::SERVER_TRADE_INITIAL_REPLY, (eGameMessageType)873); - EXPECT_EQ(eGameMessageType::SERVER_TRADE_FINAL_REPLY, (eGameMessageType)874); - EXPECT_EQ(eGameMessageType::CLIENT_TRADE_UPDATE, (eGameMessageType)875); - EXPECT_EQ(eGameMessageType::SERVER_SIDE_TRADE_UPDATE, (eGameMessageType)876); - EXPECT_EQ(eGameMessageType::SERVER_TRADE_UPDATE, (eGameMessageType)877); - EXPECT_EQ(eGameMessageType::CLIENT_TRADE_CANCEL, (eGameMessageType)878); - EXPECT_EQ(eGameMessageType::CLIENT_SIDE_TRADE_CANCEL, (eGameMessageType)879); - EXPECT_EQ(eGameMessageType::CLIENT_TRADE_ACCEPT, (eGameMessageType)880); - EXPECT_EQ(eGameMessageType::SERVER_SIDE_TRADE_ACCEPT, (eGameMessageType)881); - EXPECT_EQ(eGameMessageType::SERVER_SIDE_TRADE_CANCEL, (eGameMessageType)882); - EXPECT_EQ(eGameMessageType::SERVER_TRADE_CANCEL, (eGameMessageType)883); - EXPECT_EQ(eGameMessageType::SERVER_TRADE_ACCEPT, (eGameMessageType)884); - EXPECT_EQ(eGameMessageType::READY_FOR_UPDATES, (eGameMessageType)888); - EXPECT_EQ(eGameMessageType::ORIENT_TO_OBJECT, (eGameMessageType)905); - EXPECT_EQ(eGameMessageType::ORIENT_TO_POSITION, (eGameMessageType)906); - EXPECT_EQ(eGameMessageType::ORIENT_TO_ANGLE, (eGameMessageType)907); - EXPECT_EQ(eGameMessageType::BOUNCER_ACTIVE_STATUS, (eGameMessageType)942); - EXPECT_EQ(eGameMessageType::UN_USE_BBB_MODEL, (eGameMessageType)999); - EXPECT_EQ(eGameMessageType::BBB_LOAD_ITEM_REQUEST, (eGameMessageType)1000); - EXPECT_EQ(eGameMessageType::BBB_SAVE_REQUEST, (eGameMessageType)1001); - EXPECT_EQ(eGameMessageType::BBB_SAVE_RESPONSE, (eGameMessageType)1005); - EXPECT_EQ(eGameMessageType::NOTIFY_CLIENT_OBJECT, (eGameMessageType)1042); - EXPECT_EQ(eGameMessageType::DISPLAY_ZONE_SUMMARY, (eGameMessageType)1043); - EXPECT_EQ(eGameMessageType::ZONE_SUMMARY_DISMISSED, (eGameMessageType)1044); - EXPECT_EQ(eGameMessageType::ACTIVITY_STATE_CHANGE_REQUEST, (eGameMessageType)1053); - EXPECT_EQ(eGameMessageType::MODIFY_PLAYER_ZONE_STATISTIC, (eGameMessageType)1046); - EXPECT_EQ(eGameMessageType::START_BUILDING_WITH_ITEM, (eGameMessageType)1057); - EXPECT_EQ(eGameMessageType::START_ARRANGING_WITH_ITEM, (eGameMessageType)1061); - EXPECT_EQ(eGameMessageType::FINISH_ARRANGING_WITH_ITEM, (eGameMessageType)1062); - EXPECT_EQ(eGameMessageType::DONE_ARRANGING_WITH_ITEM, (eGameMessageType)1063); - EXPECT_EQ(eGameMessageType::SET_BUILD_MODE, (eGameMessageType)1068); - EXPECT_EQ(eGameMessageType::BUILD_MODE_SET, (eGameMessageType)1069); - EXPECT_EQ(eGameMessageType::SET_BUILD_MODE_CONFIRMED, (eGameMessageType)1073); - EXPECT_EQ(eGameMessageType::NOTIFY_CLIENT_FAILED_PRECONDITION, (eGameMessageType)1081); - EXPECT_EQ(eGameMessageType::MOVE_ITEM_BETWEEN_INVENTORY_TYPES, (eGameMessageType)1093); - EXPECT_EQ(eGameMessageType::MODULAR_BUILD_BEGIN, (eGameMessageType)1094); - EXPECT_EQ(eGameMessageType::MODULAR_BUILD_END, (eGameMessageType)1095); - EXPECT_EQ(eGameMessageType::MODULAR_BUILD_MOVE_AND_EQUIP, (eGameMessageType)1096); - EXPECT_EQ(eGameMessageType::MODULAR_BUILD_FINISH, (eGameMessageType)1097); - EXPECT_EQ(eGameMessageType::REPORT_BUG, (eGameMessageType)1198); - EXPECT_EQ(eGameMessageType::MISSION_DIALOGUE_CANCELLED, (eGameMessageType)1129); - EXPECT_EQ(eGameMessageType::ECHO_SYNC_SKILL, (eGameMessageType)1144); - EXPECT_EQ(eGameMessageType::SYNC_SKILL, (eGameMessageType)1145); - EXPECT_EQ(eGameMessageType::REQUEST_SERVER_PROJECTILE_IMPACT, (eGameMessageType)1148); - EXPECT_EQ(eGameMessageType::DO_CLIENT_PROJECTILE_IMPACT, (eGameMessageType)1151); - EXPECT_EQ(eGameMessageType::MODULAR_BUILD_CONVERT_MODEL, (eGameMessageType)1155); - EXPECT_EQ(eGameMessageType::SET_PLAYER_ALLOWED_RESPAWN, (eGameMessageType)1165); - EXPECT_EQ(eGameMessageType::UI_MESSAGE_SERVER_TO_SINGLE_CLIENT, (eGameMessageType)1184); - EXPECT_EQ(eGameMessageType::UI_MESSAGE_SERVER_TO_ALL_CLIENTS, (eGameMessageType)1185); - EXPECT_EQ(eGameMessageType::PET_TAMING_TRY_BUILD, (eGameMessageType)1197); - EXPECT_EQ(eGameMessageType::REQUEST_SMASH_PLAYER, (eGameMessageType)1202); - EXPECT_EQ(eGameMessageType::FIRE_EVENT_CLIENT_SIDE, (eGameMessageType)1213); - EXPECT_EQ(eGameMessageType::TOGGLE_GM_INVIS, (eGameMessageType)1218); - EXPECT_EQ(eGameMessageType::CHANGE_OBJECT_WORLD_STATE, (eGameMessageType)1223); - EXPECT_EQ(eGameMessageType::VEHICLE_LOCK_INPUT, (eGameMessageType)1230); - EXPECT_EQ(eGameMessageType::VEHICLE_UNLOCK_INPUT, (eGameMessageType)1231); - EXPECT_EQ(eGameMessageType::RACING_RESET_PLAYER_TO_LAST_RESET, (eGameMessageType)1252); - EXPECT_EQ(eGameMessageType::RACING_SERVER_SET_PLAYER_LAP_AND_PLANE, (eGameMessageType)1253); - EXPECT_EQ(eGameMessageType::RACING_SET_PLAYER_RESET_INFO, (eGameMessageType)1254); - EXPECT_EQ(eGameMessageType::RACING_PLAYER_INFO_RESET_FINISHED, (eGameMessageType)1255); - EXPECT_EQ(eGameMessageType::LOCK_NODE_ROTATION, (eGameMessageType)1260); - EXPECT_EQ(eGameMessageType::VEHICLE_SET_WHEEL_LOCK_STATE, (eGameMessageType)1273); - EXPECT_EQ(eGameMessageType::NOTIFY_VEHICLE_OF_RACING_OBJECT, (eGameMessageType)1276); - EXPECT_EQ(eGameMessageType::SET_NAME_BILLBOARD_STATE, (eGameMessageType)1284); - EXPECT_EQ(eGameMessageType::PLAYER_REACHED_RESPAWN_CHECKPOINT, (eGameMessageType)1296); - EXPECT_EQ(eGameMessageType::HANDLE_UGC_POST_DELETE_BASED_ON_EDIT_MODE, (eGameMessageType)1300); - EXPECT_EQ(eGameMessageType::HANDLE_UGC_POST_CREATE_BASED_ON_EDIT_MODE, (eGameMessageType)1301); - EXPECT_EQ(eGameMessageType::PROPERTY_CONTENTS_FROM_CLIENT, (eGameMessageType)1305); - EXPECT_EQ(eGameMessageType::GET_MODELS_ON_PROPERTY, (eGameMessageType)1306); - EXPECT_EQ(eGameMessageType::MATCH_REQUEST, (eGameMessageType)1308); - EXPECT_EQ(eGameMessageType::MATCH_RESPONSE, (eGameMessageType)1309); - EXPECT_EQ(eGameMessageType::MATCH_UPDATE, (eGameMessageType)1310); - EXPECT_EQ(eGameMessageType::MODULE_ASSEMBLY_DB_DATA_FOR_CLIENT, (eGameMessageType)1131); - EXPECT_EQ(eGameMessageType::MODULE_ASSEMBLY_QUERY_DATA, (eGameMessageType)1132); - EXPECT_EQ(eGameMessageType::SHOW_BILLBOARD_INTERACT_ICON, (eGameMessageType)1337); - EXPECT_EQ(eGameMessageType::CHANGE_IDLE_FLAGS, (eGameMessageType)1338); - EXPECT_EQ(eGameMessageType::VEHICLE_ADD_PASSIVE_BOOST_ACTION, (eGameMessageType)1340); - EXPECT_EQ(eGameMessageType::VEHICLE_REMOVE_PASSIVE_BOOST_ACTION, (eGameMessageType)1341); - EXPECT_EQ(eGameMessageType::NOTIFY_SERVER_VEHICLE_ADD_PASSIVE_BOOST_ACTION, (eGameMessageType)1342); - EXPECT_EQ(eGameMessageType::NOTIFY_SERVER_VEHICLE_REMOVE_PASSIVE_BOOST_ACTION, (eGameMessageType)1343); - EXPECT_EQ(eGameMessageType::VEHICLE_ADD_SLOWDOWN_ACTION, (eGameMessageType)1344); - EXPECT_EQ(eGameMessageType::VEHICLE_REMOVE_SLOWDOWN_ACTION, (eGameMessageType)1345); - EXPECT_EQ(eGameMessageType::NOTIFY_SERVER_VEHICLE_ADD_SLOWDOWN_ACTION, (eGameMessageType)1346); - EXPECT_EQ(eGameMessageType::NOTIFY_SERVER_VEHICLE_REMOVE_SLOWDOWN_ACTION, (eGameMessageType)1347); - EXPECT_EQ(eGameMessageType::BUYBACK_FROM_VENDOR, (eGameMessageType)1350); - EXPECT_EQ(eGameMessageType::SET_PROPERTY_ACCESS, (eGameMessageType)1366); - EXPECT_EQ(eGameMessageType::ZONE_PROPERTY_MODEL_PLACED, (eGameMessageType)1369); - EXPECT_EQ(eGameMessageType::ZONE_PROPERTY_MODEL_ROTATED, (eGameMessageType)1370); - EXPECT_EQ(eGameMessageType::ZONE_PROPERTY_MODEL_REMOVED_WHILE_EQUIPPED, (eGameMessageType)1371); - EXPECT_EQ(eGameMessageType::ZONE_PROPERTY_MODEL_EQUIPPED, (eGameMessageType)1372); - EXPECT_EQ(eGameMessageType::ZONE_PROPERTY_MODEL_PICKED_UP, (eGameMessageType)1373); - EXPECT_EQ(eGameMessageType::ZONE_PROPERTY_MODEL_REMOVED, (eGameMessageType)1374); - EXPECT_EQ(eGameMessageType::NOTIFY_RACING_CLIENT, (eGameMessageType)1390); - EXPECT_EQ(eGameMessageType::RACING_PLAYER_HACK_CAR, (eGameMessageType)1391); - EXPECT_EQ(eGameMessageType::RACING_PLAYER_LOADED, (eGameMessageType)1392); - EXPECT_EQ(eGameMessageType::RACING_CLIENT_READY, (eGameMessageType)1393); - EXPECT_EQ(eGameMessageType::UPDATE_CHAT_MODE, (eGameMessageType)1395); - EXPECT_EQ(eGameMessageType::VEHICLE_NOTIFY_FINISHED_RACE, (eGameMessageType)1396); - EXPECT_EQ(eGameMessageType::SET_CONSUMABLE_ITEM, (eGameMessageType)1409); - EXPECT_EQ(eGameMessageType::SET_STATUS_IMMUNITY, (eGameMessageType)1435); - EXPECT_EQ(eGameMessageType::SET_PET_NAME_MODERATED, (eGameMessageType)1448); - EXPECT_EQ(eGameMessageType::MODIFY_LEGO_SCORE, (eGameMessageType)1459); - EXPECT_EQ(eGameMessageType::RESTORE_TO_POST_LOAD_STATS, (eGameMessageType)1468); - EXPECT_EQ(eGameMessageType::SET_RAIL_MOVEMENT, (eGameMessageType)1471); - EXPECT_EQ(eGameMessageType::START_RAIL_MOVEMENT, (eGameMessageType)1472); - EXPECT_EQ(eGameMessageType::CANCEL_RAIL_MOVEMENT, (eGameMessageType)1474); - EXPECT_EQ(eGameMessageType::CLIENT_RAIL_MOVEMENT_READY, (eGameMessageType)1476); - EXPECT_EQ(eGameMessageType::PLAYER_RAIL_ARRIVED_NOTIFICATION, (eGameMessageType)1477); - EXPECT_EQ(eGameMessageType::UPDATE_PLAYER_STATISTIC, (eGameMessageType)1481); - EXPECT_EQ(eGameMessageType::MODULAR_ASSEMBLY_NIF_COMPLETED, (eGameMessageType)1498); - EXPECT_EQ(eGameMessageType::NOTIFY_NOT_ENOUGH_INV_SPACE, (eGameMessageType)1516); - EXPECT_EQ(eGameMessageType::TEAM_SET_LEADER, (eGameMessageType)1557); - EXPECT_EQ(eGameMessageType::TEAM_INVITE_CONFIRM, (eGameMessageType)1558); - EXPECT_EQ(eGameMessageType::TEAM_GET_STATUS_RESPONSE, (eGameMessageType)1559); - EXPECT_EQ(eGameMessageType::TEAM_ADD_PLAYER, (eGameMessageType)1562); - EXPECT_EQ(eGameMessageType::TEAM_REMOVE_PLAYER, (eGameMessageType)1563); - EXPECT_EQ(eGameMessageType::START_CELEBRATION_EFFECT, (eGameMessageType)1618); - EXPECT_EQ(eGameMessageType::ADD_BUFF, (eGameMessageType)1647); - EXPECT_EQ(eGameMessageType::SERVER_DONE_LOADING_ALL_OBJECTS, (eGameMessageType)1642); - EXPECT_EQ(eGameMessageType::PLACE_PROPERTY_MODEL, (eGameMessageType)1170); - EXPECT_EQ(eGameMessageType::VEHICLE_NOTIFY_HIT_IMAGINATION_SERVER, (eGameMessageType)1606); - EXPECT_EQ(eGameMessageType::ADD_RUN_SPEED_MODIFIER, (eGameMessageType)1505); - EXPECT_EQ(eGameMessageType::GET_HOT_PROPERTY_DATA, (eGameMessageType)1511); - EXPECT_EQ(eGameMessageType::SEND_HOT_PROPERTY_DATA, (eGameMessageType)1510); - EXPECT_EQ(eGameMessageType::REMOVE_RUN_SPEED_MODIFIER, (eGameMessageType)1506); - EXPECT_EQ(eGameMessageType::UPDATE_PROPERTY_PERFORMANCE_COST, (eGameMessageType)1547); - EXPECT_EQ(eGameMessageType::PROPERTY_ENTRANCE_BEGIN, (eGameMessageType)1553); - EXPECT_EQ(eGameMessageType::SET_RESURRECT_RESTORE_VALUES, (eGameMessageType)1591); - EXPECT_EQ(eGameMessageType::VEHICLE_STOP_BOOST, (eGameMessageType)1617); - EXPECT_EQ(eGameMessageType::REMOVE_BUFF, (eGameMessageType)1648); - EXPECT_EQ(eGameMessageType::REQUEST_MOVE_ITEM_BETWEEN_INVENTORY_TYPES, (eGameMessageType)1666); - EXPECT_EQ(eGameMessageType::RESPONSE_MOVE_ITEM_BETWEEN_INVENTORY_TYPES, (eGameMessageType)1667); - EXPECT_EQ(eGameMessageType::PLAYER_SET_CAMERA_CYCLING_MODE, (eGameMessageType)1676); - EXPECT_EQ(eGameMessageType::SET_MOUNT_INVENTORY_ID, (eGameMessageType)1727); - EXPECT_EQ(eGameMessageType::NOTIFY_SERVER_LEVEL_PROCESSING_COMPLETE, (eGameMessageType)1734); - EXPECT_EQ(eGameMessageType::NOTIFY_LEVEL_REWARDS, (eGameMessageType)1735); - EXPECT_EQ(eGameMessageType::DISMOUNT_COMPLETE, (eGameMessageType)1756); - EXPECT_EQ(eGameMessageType::MARK_INVENTORY_ITEM_AS_ACTIVE, (eGameMessageType)1767); + EXPECT_EQ(eGameMessageType::TELEPORT, static_cast(19)); + EXPECT_EQ(eGameMessageType::SET_PLAYER_CONTROL_SCHEME, static_cast(26)); + EXPECT_EQ(eGameMessageType::DROP_CLIENT_LOOT, static_cast(30)); + EXPECT_EQ(eGameMessageType::DIE, static_cast(37)); + EXPECT_EQ(eGameMessageType::REQUEST_DIE, static_cast(38)); + EXPECT_EQ(eGameMessageType::PLAY_EMOTE, static_cast(41)); + EXPECT_EQ(eGameMessageType::PLAY_ANIMATION, static_cast(43)); + EXPECT_EQ(eGameMessageType::CONTROL_BEHAVIORS, static_cast(48)); + EXPECT_EQ(eGameMessageType::SET_NAME, static_cast(72)); + EXPECT_EQ(eGameMessageType::ECHO_START_SKILL, static_cast(118)); + EXPECT_EQ(eGameMessageType::START_SKILL, static_cast(119)); + EXPECT_EQ(eGameMessageType::VERIFY_ACK, static_cast(121)); + EXPECT_EQ(eGameMessageType::ADD_SKILL, static_cast(127)); + EXPECT_EQ(eGameMessageType::REMOVE_SKILL, static_cast(128)); + EXPECT_EQ(eGameMessageType::SET_CURRENCY, static_cast(133)); + EXPECT_EQ(eGameMessageType::PICKUP_CURRENCY, static_cast(137)); + EXPECT_EQ(eGameMessageType::PICKUP_ITEM, static_cast(139)); + EXPECT_EQ(eGameMessageType::TEAM_PICKUP_ITEM, static_cast(140)); + EXPECT_EQ(eGameMessageType::PLAY_FX_EFFECT, static_cast(154)); + EXPECT_EQ(eGameMessageType::STOP_FX_EFFECT, static_cast(155)); + EXPECT_EQ(eGameMessageType::REQUEST_RESURRECT, static_cast(159)); + EXPECT_EQ(eGameMessageType::RESURRECT, static_cast(160)); + EXPECT_EQ(eGameMessageType::PUSH_EQUIPPED_ITEMS_STATE, static_cast(191)); + EXPECT_EQ(eGameMessageType::POP_EQUIPPED_ITEMS_STATE, static_cast(192)); + EXPECT_EQ(eGameMessageType::SET_GM_LEVEL, static_cast(193)); + EXPECT_EQ(eGameMessageType::SET_STUNNED, static_cast(198)); + EXPECT_EQ(eGameMessageType::SET_STUN_IMMUNITY, static_cast(200)); + EXPECT_EQ(eGameMessageType::KNOCKBACK, static_cast(202)); + EXPECT_EQ(eGameMessageType::REBUILD_CANCEL, static_cast(209)); + EXPECT_EQ(eGameMessageType::ENABLE_REBUILD, static_cast(213)); + EXPECT_EQ(eGameMessageType::MOVE_ITEM_IN_INVENTORY, static_cast(224)); + EXPECT_EQ(eGameMessageType::ADD_ITEM_TO_INVENTORY_CLIENT_SYNC, static_cast(227)); + EXPECT_EQ(eGameMessageType::REMOVE_ITEM_FROM_INVENTORY, static_cast(230)); + EXPECT_EQ(eGameMessageType::EQUIP_INVENTORY, static_cast(231)); + EXPECT_EQ(eGameMessageType::UN_EQUIP_INVENTORY, static_cast(233)); + EXPECT_EQ(eGameMessageType::OFFER_MISSION, static_cast(248)); + EXPECT_EQ(eGameMessageType::RESPOND_TO_MISSION, static_cast(249)); + EXPECT_EQ(eGameMessageType::NOTIFY_MISSION, static_cast(254)); + EXPECT_EQ(eGameMessageType::NOTIFY_MISSION_TASK, static_cast(255)); + EXPECT_EQ(eGameMessageType::REBUILD_NOTIFY_STATE, static_cast(336)); + EXPECT_EQ(eGameMessageType::TERMINATE_INTERACTION, static_cast(357)); + EXPECT_EQ(eGameMessageType::SERVER_TERMINATE_INTERACTION, static_cast(358)); + EXPECT_EQ(eGameMessageType::REQUEST_USE, static_cast(364)); + EXPECT_EQ(eGameMessageType::VENDOR_OPEN_WINDOW, static_cast(369)); + EXPECT_EQ(eGameMessageType::BUY_FROM_VENDOR, static_cast(373)); + EXPECT_EQ(eGameMessageType::SELL_TO_VENDOR, static_cast(374)); + EXPECT_EQ(eGameMessageType::TEAM_SET_OFF_WORLD_FLAG, static_cast(383)); + EXPECT_EQ(eGameMessageType::SET_INVENTORY_SIZE, static_cast(389)); + EXPECT_EQ(eGameMessageType::ACKNOWLEDGE_POSSESSION, static_cast(391)); + EXPECT_EQ(eGameMessageType::SET_SHOOTING_GALLERY_PARAMS, static_cast(400)); + EXPECT_EQ(eGameMessageType::REQUEST_ACTIVITY_START_STOP, static_cast(402)); + EXPECT_EQ(eGameMessageType::REQUEST_ACTIVITY_ENTER, static_cast(403)); + EXPECT_EQ(eGameMessageType::REQUEST_ACTIVITY_EXIT, static_cast(404)); + EXPECT_EQ(eGameMessageType::ACTIVITY_ENTER, static_cast(405)); + EXPECT_EQ(eGameMessageType::ACTIVITY_EXIT, static_cast(406)); + EXPECT_EQ(eGameMessageType::ACTIVITY_START, static_cast(407)); + EXPECT_EQ(eGameMessageType::ACTIVITY_STOP, static_cast(408)); + EXPECT_EQ(eGameMessageType::SHOOTING_GALLERY_CLIENT_AIM_UPDATE, static_cast(409)); + EXPECT_EQ(eGameMessageType::SHOOTING_GALLERY_FIRE, static_cast(411)); + EXPECT_EQ(eGameMessageType::REQUEST_VENDOR_STATUS_UPDATE, static_cast(416)); + EXPECT_EQ(eGameMessageType::VENDOR_STATUS_UPDATE, static_cast(417)); + EXPECT_EQ(eGameMessageType::NOTIFY_CLIENT_SHOOTING_GALLERY_SCORE, static_cast(425)); + EXPECT_EQ(eGameMessageType::CONSUME_CLIENT_ITEM, static_cast(427)); + EXPECT_EQ(eGameMessageType::CLIENT_ITEM_CONSUMED, static_cast(428)); + EXPECT_EQ(eGameMessageType::UPDATE_SHOOTING_GALLERY_ROTATION, static_cast(448)); + EXPECT_EQ(eGameMessageType::SET_FLAG, static_cast(471)); + EXPECT_EQ(eGameMessageType::NOTIFY_CLIENT_FLAG_CHANGE, static_cast(472)); + EXPECT_EQ(eGameMessageType::VENDOR_TRANSACTION_RESULT, static_cast(476)); + EXPECT_EQ(eGameMessageType::HAS_BEEN_COLLECTED, static_cast(486)); + EXPECT_EQ(eGameMessageType::DISPLAY_CHAT_BUBBLE, static_cast(495)); + EXPECT_EQ(eGameMessageType::SPAWN_PET, static_cast(498)); + EXPECT_EQ(eGameMessageType::DESPAWN_PET, static_cast(499)); + EXPECT_EQ(eGameMessageType::PLAYER_LOADED, static_cast(505)); + EXPECT_EQ(eGameMessageType::PLAYER_READY, static_cast(509)); + EXPECT_EQ(eGameMessageType::REQUEST_LINKED_MISSION, static_cast(515)); + EXPECT_EQ(eGameMessageType::INVALID_ZONE_TRANSFER_LIST, static_cast(519)); + EXPECT_EQ(eGameMessageType::MISSION_DIALOGUE_OK, static_cast(520)); + EXPECT_EQ(eGameMessageType::DISPLAY_MESSAGE_BOX, static_cast(529)); + EXPECT_EQ(eGameMessageType::MESSAGE_BOX_RESPOND, static_cast(530)); + EXPECT_EQ(eGameMessageType::CHOICE_BOX_RESPOND, static_cast(531)); + EXPECT_EQ(eGameMessageType::SMASH, static_cast(537)); + EXPECT_EQ(eGameMessageType::UN_SMASH, static_cast(538)); + EXPECT_EQ(eGameMessageType::PLACE_MODEL_RESPONSE, static_cast(547)); + EXPECT_EQ(eGameMessageType::SET_SHOOTING_GALLERY_RETICULE_EFFECT, static_cast(546)); + EXPECT_EQ(eGameMessageType::SET_JET_PACK_MODE, static_cast(561)); + EXPECT_EQ(eGameMessageType::REGISTER_PET_ID, static_cast(565)); + EXPECT_EQ(eGameMessageType::REGISTER_PET_DBID, static_cast(566)); + EXPECT_EQ(eGameMessageType::SHOW_ACTIVITY_COUNTDOWN, static_cast(568)); + EXPECT_EQ(eGameMessageType::START_ACTIVITY_TIME, static_cast(576)); + EXPECT_EQ(eGameMessageType::ACTIVITY_PAUSE, static_cast(602)); + EXPECT_EQ(eGameMessageType::USE_NON_EQUIPMENT_ITEM, static_cast(603)); + EXPECT_EQ(eGameMessageType::USE_ITEM_RESULT, static_cast(607)); + EXPECT_EQ(eGameMessageType::COMMAND_PET, static_cast(640)); + EXPECT_EQ(eGameMessageType::PET_RESPONSE, static_cast(641)); + EXPECT_EQ(eGameMessageType::REQUEST_ACTIVITY_SUMMARY_LEADERBOARD_DATA, static_cast(648)); + EXPECT_EQ(eGameMessageType::SEND_ACTIVITY_SUMMARY_LEADERBOARD_DATA, static_cast(649)); + EXPECT_EQ(eGameMessageType::NOTIFY_OBJECT, static_cast(656)); + EXPECT_EQ(eGameMessageType::CLIENT_NOTIFY_PET, static_cast(659)); + EXPECT_EQ(eGameMessageType::NOTIFY_PET, static_cast(660)); + EXPECT_EQ(eGameMessageType::NOTIFY_PET_TAMING_MINIGAME, static_cast(661)); + EXPECT_EQ(eGameMessageType::START_SERVER_PET_MINIGAME_TIMER, static_cast(662)); + EXPECT_EQ(eGameMessageType::CLIENT_EXIT_TAMING_MINIGAME, static_cast(663)); + EXPECT_EQ(eGameMessageType::PET_NAME_CHANGED, static_cast(686)); + EXPECT_EQ(eGameMessageType::PET_TAMING_MINIGAME_RESULT, static_cast(667)); + EXPECT_EQ(eGameMessageType::PET_TAMING_TRY_BUILD_RESULT, static_cast(668)); + EXPECT_EQ(eGameMessageType::NOTIFY_TAMING_BUILD_SUCCESS, static_cast(673)); + EXPECT_EQ(eGameMessageType::NOTIFY_TAMING_MODEL_LOADED_ON_SERVER, static_cast(674)); + EXPECT_EQ(eGameMessageType::ACTIVATE_BUBBLE_BUFF, static_cast(678)); + EXPECT_EQ(eGameMessageType::DECTIVATE_BUBBLE_BUFF, static_cast(679)); + EXPECT_EQ(eGameMessageType::ADD_PET_TO_PLAYER, static_cast(681)); + EXPECT_EQ(eGameMessageType::REQUEST_SET_PET_NAME, static_cast(683)); + EXPECT_EQ(eGameMessageType::SET_PET_NAME, static_cast(684)); + EXPECT_EQ(eGameMessageType::NOTIFY_TAMING_PUZZLE_SELECTED, static_cast(675)); + EXPECT_EQ(eGameMessageType::SHOW_PET_ACTION_BUTTON, static_cast(692)); + EXPECT_EQ(eGameMessageType::SET_EMOTE_LOCK_STATE, static_cast(693)); + EXPECT_EQ(eGameMessageType::USE_ITEM_REQUIREMENTS_RESPONSE, static_cast(703)); + EXPECT_EQ(eGameMessageType::PLAY_EMBEDDED_EFFECT_ON_ALL_CLIENTS_NEAR_OBJECT, static_cast(713)); + EXPECT_EQ(eGameMessageType::DOWNLOAD_PROPERTY_DATA, static_cast(716)); + EXPECT_EQ(eGameMessageType::QUERY_PROPERTY_DATA, static_cast(717)); + EXPECT_EQ(eGameMessageType::PROPERTY_EDITOR_BEGIN, static_cast(724)); + EXPECT_EQ(eGameMessageType::PROPERTY_EDITOR_END, static_cast(725)); + EXPECT_EQ(eGameMessageType::IS_MINIFIG_IN_A_BUBBLE, static_cast(729)); + EXPECT_EQ(eGameMessageType::START_PATHING, static_cast(733)); + EXPECT_EQ(eGameMessageType::ACTIVATE_BUBBLE_BUFF_FROM_SERVER, static_cast(734)); + EXPECT_EQ(eGameMessageType::DEACTIVATE_BUBBLE_BUFF_FROM_SERVER, static_cast(735)); + EXPECT_EQ(eGameMessageType::NOTIFY_CLIENT_ZONE_OBJECT, static_cast(737)); + EXPECT_EQ(eGameMessageType::UPDATE_REPUTATION, static_cast(746)); + EXPECT_EQ(eGameMessageType::PROPERTY_RENTAL_RESPONSE, static_cast(750)); + EXPECT_EQ(eGameMessageType::REQUEST_PLATFORM_RESYNC, static_cast(760)); + EXPECT_EQ(eGameMessageType::PLATFORM_RESYNC, static_cast(761)); + EXPECT_EQ(eGameMessageType::PLAY_CINEMATIC, static_cast(762)); + EXPECT_EQ(eGameMessageType::END_CINEMATIC, static_cast(763)); + EXPECT_EQ(eGameMessageType::CINEMATIC_UPDATE, static_cast(764)); + EXPECT_EQ(eGameMessageType::TOGGLE_GHOST_REFERENCE_OVERRIDE, static_cast(767)); + EXPECT_EQ(eGameMessageType::SET_GHOST_REFERENCE_POSITION, static_cast(768)); + EXPECT_EQ(eGameMessageType::FIRE_EVENT_SERVER_SIDE, static_cast(770)); + EXPECT_EQ(eGameMessageType::SCRIPT_NETWORK_VAR_UPDATE, static_cast(781)); + EXPECT_EQ(eGameMessageType::UPDATE_MODEL_FROM_CLIENT, static_cast(793)); + EXPECT_EQ(eGameMessageType::DELETE_MODEL_FROM_CLIENT, static_cast(794)); + EXPECT_EQ(eGameMessageType::PLAY_ND_AUDIO_EMITTER, static_cast(821)); + EXPECT_EQ(eGameMessageType::PLAY2_D_AMBIENT_SOUND, static_cast(831)); + EXPECT_EQ(eGameMessageType::ENTER_PROPERTY1, static_cast(840)); + EXPECT_EQ(eGameMessageType::ENTER_PROPERTY2, static_cast(841)); + EXPECT_EQ(eGameMessageType::PROPERTY_ENTRANCE_SYNC, static_cast(842)); + EXPECT_EQ(eGameMessageType::PROPERTY_SELECT_QUERY, static_cast(845)); + EXPECT_EQ(eGameMessageType::PARSE_CHAT_MESSAGE, static_cast(850)); + EXPECT_EQ(eGameMessageType::BROADCAST_TEXT_TO_CHATBOX, static_cast(858)); + EXPECT_EQ(eGameMessageType::OPEN_PROPERTY_MANAGEMENT, static_cast(860)); + EXPECT_EQ(eGameMessageType::OPEN_PROPERTY_VENDOR, static_cast(861)); + EXPECT_EQ(eGameMessageType::UPDATE_PROPERTY_OR_MODEL_FOR_FILTER_CHECK, static_cast(863)); + EXPECT_EQ(eGameMessageType::CLIENT_TRADE_REQUEST, static_cast(868)); + EXPECT_EQ(eGameMessageType::SERVER_TRADE_REQUEST, static_cast(869)); + EXPECT_EQ(eGameMessageType::SERVER_TRADE_INVITE, static_cast(870)); + EXPECT_EQ(eGameMessageType::CLIENT_TRADE_REPLY, static_cast(871)); + EXPECT_EQ(eGameMessageType::SERVER_TRADE_REPLY, static_cast(872)); + EXPECT_EQ(eGameMessageType::SERVER_TRADE_INITIAL_REPLY, static_cast(873)); + EXPECT_EQ(eGameMessageType::SERVER_TRADE_FINAL_REPLY, static_cast(874)); + EXPECT_EQ(eGameMessageType::CLIENT_TRADE_UPDATE, static_cast(875)); + EXPECT_EQ(eGameMessageType::SERVER_SIDE_TRADE_UPDATE, static_cast(876)); + EXPECT_EQ(eGameMessageType::SERVER_TRADE_UPDATE, static_cast(877)); + EXPECT_EQ(eGameMessageType::CLIENT_TRADE_CANCEL, static_cast(878)); + EXPECT_EQ(eGameMessageType::CLIENT_SIDE_TRADE_CANCEL, static_cast(879)); + EXPECT_EQ(eGameMessageType::CLIENT_TRADE_ACCEPT, static_cast(880)); + EXPECT_EQ(eGameMessageType::SERVER_SIDE_TRADE_ACCEPT, static_cast(881)); + EXPECT_EQ(eGameMessageType::SERVER_SIDE_TRADE_CANCEL, static_cast(882)); + EXPECT_EQ(eGameMessageType::SERVER_TRADE_CANCEL, static_cast(883)); + EXPECT_EQ(eGameMessageType::SERVER_TRADE_ACCEPT, static_cast(884)); + EXPECT_EQ(eGameMessageType::READY_FOR_UPDATES, static_cast(888)); + EXPECT_EQ(eGameMessageType::ORIENT_TO_OBJECT, static_cast(905)); + EXPECT_EQ(eGameMessageType::ORIENT_TO_POSITION, static_cast(906)); + EXPECT_EQ(eGameMessageType::ORIENT_TO_ANGLE, static_cast(907)); + EXPECT_EQ(eGameMessageType::BOUNCER_ACTIVE_STATUS, static_cast(942)); + EXPECT_EQ(eGameMessageType::UN_USE_BBB_MODEL, static_cast(999)); + EXPECT_EQ(eGameMessageType::BBB_LOAD_ITEM_REQUEST, static_cast(1000)); + EXPECT_EQ(eGameMessageType::BBB_SAVE_REQUEST, static_cast(1001)); + EXPECT_EQ(eGameMessageType::BBB_SAVE_RESPONSE, static_cast(1005)); + EXPECT_EQ(eGameMessageType::NOTIFY_CLIENT_OBJECT, static_cast(1042)); + EXPECT_EQ(eGameMessageType::DISPLAY_ZONE_SUMMARY, static_cast(1043)); + EXPECT_EQ(eGameMessageType::ZONE_SUMMARY_DISMISSED, static_cast(1044)); + EXPECT_EQ(eGameMessageType::ACTIVITY_STATE_CHANGE_REQUEST, static_cast(1053)); + EXPECT_EQ(eGameMessageType::MODIFY_PLAYER_ZONE_STATISTIC, static_cast(1046)); + EXPECT_EQ(eGameMessageType::START_BUILDING_WITH_ITEM, static_cast(1057)); + EXPECT_EQ(eGameMessageType::START_ARRANGING_WITH_ITEM, static_cast(1061)); + EXPECT_EQ(eGameMessageType::FINISH_ARRANGING_WITH_ITEM, static_cast(1062)); + EXPECT_EQ(eGameMessageType::DONE_ARRANGING_WITH_ITEM, static_cast(1063)); + EXPECT_EQ(eGameMessageType::SET_BUILD_MODE, static_cast(1068)); + EXPECT_EQ(eGameMessageType::BUILD_MODE_SET, static_cast(1069)); + EXPECT_EQ(eGameMessageType::SET_BUILD_MODE_CONFIRMED, static_cast(1073)); + EXPECT_EQ(eGameMessageType::NOTIFY_CLIENT_FAILED_PRECONDITION, static_cast(1081)); + EXPECT_EQ(eGameMessageType::MOVE_ITEM_BETWEEN_INVENTORY_TYPES, static_cast(1093)); + EXPECT_EQ(eGameMessageType::MODULAR_BUILD_BEGIN, static_cast(1094)); + EXPECT_EQ(eGameMessageType::MODULAR_BUILD_END, static_cast(1095)); + EXPECT_EQ(eGameMessageType::MODULAR_BUILD_MOVE_AND_EQUIP, static_cast(1096)); + EXPECT_EQ(eGameMessageType::MODULAR_BUILD_FINISH, static_cast(1097)); + EXPECT_EQ(eGameMessageType::REPORT_BUG, static_cast(1198)); + EXPECT_EQ(eGameMessageType::MISSION_DIALOGUE_CANCELLED, static_cast(1129)); + EXPECT_EQ(eGameMessageType::ECHO_SYNC_SKILL, static_cast(1144)); + EXPECT_EQ(eGameMessageType::SYNC_SKILL, static_cast(1145)); + EXPECT_EQ(eGameMessageType::REQUEST_SERVER_PROJECTILE_IMPACT, static_cast(1148)); + EXPECT_EQ(eGameMessageType::DO_CLIENT_PROJECTILE_IMPACT, static_cast(1151)); + EXPECT_EQ(eGameMessageType::MODULAR_BUILD_CONVERT_MODEL, static_cast(1155)); + EXPECT_EQ(eGameMessageType::SET_PLAYER_ALLOWED_RESPAWN, static_cast(1165)); + EXPECT_EQ(eGameMessageType::UI_MESSAGE_SERVER_TO_SINGLE_CLIENT, static_cast(1184)); + EXPECT_EQ(eGameMessageType::UI_MESSAGE_SERVER_TO_ALL_CLIENTS, static_cast(1185)); + EXPECT_EQ(eGameMessageType::PET_TAMING_TRY_BUILD, static_cast(1197)); + EXPECT_EQ(eGameMessageType::REQUEST_SMASH_PLAYER, static_cast(1202)); + EXPECT_EQ(eGameMessageType::FIRE_EVENT_CLIENT_SIDE, static_cast(1213)); + EXPECT_EQ(eGameMessageType::TOGGLE_GM_INVIS, static_cast(1218)); + EXPECT_EQ(eGameMessageType::CHANGE_OBJECT_WORLD_STATE, static_cast(1223)); + EXPECT_EQ(eGameMessageType::VEHICLE_LOCK_INPUT, static_cast(1230)); + EXPECT_EQ(eGameMessageType::VEHICLE_UNLOCK_INPUT, static_cast(1231)); + EXPECT_EQ(eGameMessageType::RACING_RESET_PLAYER_TO_LAST_RESET, static_cast(1252)); + EXPECT_EQ(eGameMessageType::RACING_SERVER_SET_PLAYER_LAP_AND_PLANE, static_cast(1253)); + EXPECT_EQ(eGameMessageType::RACING_SET_PLAYER_RESET_INFO, static_cast(1254)); + EXPECT_EQ(eGameMessageType::RACING_PLAYER_INFO_RESET_FINISHED, static_cast(1255)); + EXPECT_EQ(eGameMessageType::LOCK_NODE_ROTATION, static_cast(1260)); + EXPECT_EQ(eGameMessageType::VEHICLE_SET_WHEEL_LOCK_STATE, static_cast(1273)); + EXPECT_EQ(eGameMessageType::NOTIFY_VEHICLE_OF_RACING_OBJECT, static_cast(1276)); + EXPECT_EQ(eGameMessageType::SET_NAME_BILLBOARD_STATE, static_cast(1284)); + EXPECT_EQ(eGameMessageType::PLAYER_REACHED_RESPAWN_CHECKPOINT, static_cast(1296)); + EXPECT_EQ(eGameMessageType::HANDLE_UGC_POST_DELETE_BASED_ON_EDIT_MODE, static_cast(1300)); + EXPECT_EQ(eGameMessageType::HANDLE_UGC_POST_CREATE_BASED_ON_EDIT_MODE, static_cast(1301)); + EXPECT_EQ(eGameMessageType::PROPERTY_CONTENTS_FROM_CLIENT, static_cast(1305)); + EXPECT_EQ(eGameMessageType::GET_MODELS_ON_PROPERTY, static_cast(1306)); + EXPECT_EQ(eGameMessageType::MATCH_REQUEST, static_cast(1308)); + EXPECT_EQ(eGameMessageType::MATCH_RESPONSE, static_cast(1309)); + EXPECT_EQ(eGameMessageType::MATCH_UPDATE, static_cast(1310)); + EXPECT_EQ(eGameMessageType::MODULE_ASSEMBLY_DB_DATA_FOR_CLIENT, static_cast(1131)); + EXPECT_EQ(eGameMessageType::MODULE_ASSEMBLY_QUERY_DATA, static_cast(1132)); + EXPECT_EQ(eGameMessageType::SHOW_BILLBOARD_INTERACT_ICON, static_cast(1337)); + EXPECT_EQ(eGameMessageType::CHANGE_IDLE_FLAGS, static_cast(1338)); + EXPECT_EQ(eGameMessageType::VEHICLE_ADD_PASSIVE_BOOST_ACTION, static_cast(1340)); + EXPECT_EQ(eGameMessageType::VEHICLE_REMOVE_PASSIVE_BOOST_ACTION, static_cast(1341)); + EXPECT_EQ(eGameMessageType::NOTIFY_SERVER_VEHICLE_ADD_PASSIVE_BOOST_ACTION, static_cast(1342)); + EXPECT_EQ(eGameMessageType::NOTIFY_SERVER_VEHICLE_REMOVE_PASSIVE_BOOST_ACTION, static_cast(1343)); + EXPECT_EQ(eGameMessageType::VEHICLE_ADD_SLOWDOWN_ACTION, static_cast(1344)); + EXPECT_EQ(eGameMessageType::VEHICLE_REMOVE_SLOWDOWN_ACTION, static_cast(1345)); + EXPECT_EQ(eGameMessageType::NOTIFY_SERVER_VEHICLE_ADD_SLOWDOWN_ACTION, static_cast(1346)); + EXPECT_EQ(eGameMessageType::NOTIFY_SERVER_VEHICLE_REMOVE_SLOWDOWN_ACTION, static_cast(1347)); + EXPECT_EQ(eGameMessageType::BUYBACK_FROM_VENDOR, static_cast(1350)); + EXPECT_EQ(eGameMessageType::SET_PROPERTY_ACCESS, static_cast(1366)); + EXPECT_EQ(eGameMessageType::ZONE_PROPERTY_MODEL_PLACED, static_cast(1369)); + EXPECT_EQ(eGameMessageType::ZONE_PROPERTY_MODEL_ROTATED, static_cast(1370)); + EXPECT_EQ(eGameMessageType::ZONE_PROPERTY_MODEL_REMOVED_WHILE_EQUIPPED, static_cast(1371)); + EXPECT_EQ(eGameMessageType::ZONE_PROPERTY_MODEL_EQUIPPED, static_cast(1372)); + EXPECT_EQ(eGameMessageType::ZONE_PROPERTY_MODEL_PICKED_UP, static_cast(1373)); + EXPECT_EQ(eGameMessageType::ZONE_PROPERTY_MODEL_REMOVED, static_cast(1374)); + EXPECT_EQ(eGameMessageType::NOTIFY_RACING_CLIENT, static_cast(1390)); + EXPECT_EQ(eGameMessageType::RACING_PLAYER_HACK_CAR, static_cast(1391)); + EXPECT_EQ(eGameMessageType::RACING_PLAYER_LOADED, static_cast(1392)); + EXPECT_EQ(eGameMessageType::RACING_CLIENT_READY, static_cast(1393)); + EXPECT_EQ(eGameMessageType::UPDATE_CHAT_MODE, static_cast(1395)); + EXPECT_EQ(eGameMessageType::VEHICLE_NOTIFY_FINISHED_RACE, static_cast(1396)); + EXPECT_EQ(eGameMessageType::SET_CONSUMABLE_ITEM, static_cast(1409)); + EXPECT_EQ(eGameMessageType::SET_STATUS_IMMUNITY, static_cast(1435)); + EXPECT_EQ(eGameMessageType::SET_PET_NAME_MODERATED, static_cast(1448)); + EXPECT_EQ(eGameMessageType::MODIFY_LEGO_SCORE, static_cast(1459)); + EXPECT_EQ(eGameMessageType::RESTORE_TO_POST_LOAD_STATS, static_cast(1468)); + EXPECT_EQ(eGameMessageType::SET_RAIL_MOVEMENT, static_cast(1471)); + EXPECT_EQ(eGameMessageType::START_RAIL_MOVEMENT, static_cast(1472)); + EXPECT_EQ(eGameMessageType::CANCEL_RAIL_MOVEMENT, static_cast(1474)); + EXPECT_EQ(eGameMessageType::CLIENT_RAIL_MOVEMENT_READY, static_cast(1476)); + EXPECT_EQ(eGameMessageType::PLAYER_RAIL_ARRIVED_NOTIFICATION, static_cast(1477)); + EXPECT_EQ(eGameMessageType::UPDATE_PLAYER_STATISTIC, static_cast(1481)); + EXPECT_EQ(eGameMessageType::MODULAR_ASSEMBLY_NIF_COMPLETED, static_cast(1498)); + EXPECT_EQ(eGameMessageType::NOTIFY_NOT_ENOUGH_INV_SPACE, static_cast(1516)); + EXPECT_EQ(eGameMessageType::TEAM_SET_LEADER, static_cast(1557)); + EXPECT_EQ(eGameMessageType::TEAM_INVITE_CONFIRM, static_cast(1558)); + EXPECT_EQ(eGameMessageType::TEAM_GET_STATUS_RESPONSE, static_cast(1559)); + EXPECT_EQ(eGameMessageType::TEAM_ADD_PLAYER, static_cast(1562)); + EXPECT_EQ(eGameMessageType::TEAM_REMOVE_PLAYER, static_cast(1563)); + EXPECT_EQ(eGameMessageType::START_CELEBRATION_EFFECT, static_cast(1618)); + EXPECT_EQ(eGameMessageType::ADD_BUFF, static_cast(1647)); + EXPECT_EQ(eGameMessageType::SERVER_DONE_LOADING_ALL_OBJECTS, static_cast(1642)); + EXPECT_EQ(eGameMessageType::PLACE_PROPERTY_MODEL, static_cast(1170)); + EXPECT_EQ(eGameMessageType::VEHICLE_NOTIFY_HIT_IMAGINATION_SERVER, static_cast(1606)); + EXPECT_EQ(eGameMessageType::ADD_RUN_SPEED_MODIFIER, static_cast(1505)); + EXPECT_EQ(eGameMessageType::GET_HOT_PROPERTY_DATA, static_cast(1511)); + EXPECT_EQ(eGameMessageType::SEND_HOT_PROPERTY_DATA, static_cast(1510)); + EXPECT_EQ(eGameMessageType::REMOVE_RUN_SPEED_MODIFIER, static_cast(1506)); + EXPECT_EQ(eGameMessageType::UPDATE_PROPERTY_PERFORMANCE_COST, static_cast(1547)); + EXPECT_EQ(eGameMessageType::PROPERTY_ENTRANCE_BEGIN, static_cast(1553)); + EXPECT_EQ(eGameMessageType::SET_RESURRECT_RESTORE_VALUES, static_cast(1591)); + EXPECT_EQ(eGameMessageType::VEHICLE_STOP_BOOST, static_cast(1617)); + EXPECT_EQ(eGameMessageType::REMOVE_BUFF, static_cast(1648)); + EXPECT_EQ(eGameMessageType::REQUEST_MOVE_ITEM_BETWEEN_INVENTORY_TYPES, static_cast(1666)); + EXPECT_EQ(eGameMessageType::RESPONSE_MOVE_ITEM_BETWEEN_INVENTORY_TYPES, static_cast(1667)); + EXPECT_EQ(eGameMessageType::PLAYER_SET_CAMERA_CYCLING_MODE, static_cast(1676)); + EXPECT_EQ(eGameMessageType::SET_MOUNT_INVENTORY_ID, static_cast(1727)); + EXPECT_EQ(eGameMessageType::NOTIFY_SERVER_LEVEL_PROCESSING_COMPLETE, static_cast(1734)); + EXPECT_EQ(eGameMessageType::NOTIFY_LEVEL_REWARDS, static_cast(1735)); + EXPECT_EQ(eGameMessageType::DISMOUNT_COMPLETE, static_cast(1756)); + EXPECT_EQ(eGameMessageType::MARK_INVENTORY_ITEM_AS_ACTIVE, static_cast(1767)); } diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt index 11d278c0..41135a80 100644 --- a/thirdparty/CMakeLists.txt +++ b/thirdparty/CMakeLists.txt @@ -19,7 +19,11 @@ add_library(bcrypt ${SOURCES_LIBBCRYPT}) # Because we are not using the libbcrypt CMakeLists.txt, we need to include these headers for the library to use. # fortunately they are only needed for building the libbcrypt directory and nothing else, so these are marked private. -target_include_directories(bcrypt PRIVATE "libbcrypt/include") +if(NOT WIN32) + target_include_directories(bcrypt PRIVATE "libbcrypt/include/bcrypt") +endif() + +target_include_directories(bcrypt INTERFACE "libbcrypt/include") target_include_directories(bcrypt PRIVATE "libbcrypt/src") # Source code for sqlite @@ -28,9 +32,6 @@ add_subdirectory(SQLite) # Source code for magic_enum add_subdirectory(magic_enum) -# MariaDB C++ Connector -include(CMakeMariaDBLists.txt) - # Create our third party library objects add_subdirectory(raknet) @@ -57,3 +58,5 @@ if(UNIX AND NOT APPLE) include_directories(${backtrace_SOURCE_DIR}) endif() endif() + +add_subdirectory(MD5) diff --git a/thirdparty/MD5/CMakeLists.txt b/thirdparty/MD5/CMakeLists.txt new file mode 100644 index 00000000..755b4519 --- /dev/null +++ b/thirdparty/MD5/CMakeLists.txt @@ -0,0 +1,6 @@ +add_library(MD5 "MD5.cpp") + +# Disable deprecation warnings on MD5.cpp for Apple Clang +if (APPLE) + set_source_files_properties("MD5.cpp" PROPERTIES COMPILE_FLAGS "-Wno-deprecated-declarations") +endif() diff --git a/dCommon/MD5.cpp b/thirdparty/MD5/MD5.cpp similarity index 100% rename from dCommon/MD5.cpp rename to thirdparty/MD5/MD5.cpp diff --git a/dCommon/MD5.h b/thirdparty/MD5/MD5.h similarity index 100% rename from dCommon/MD5.h rename to thirdparty/MD5/MD5.h diff --git a/thirdparty/SQLite/CMakeLists.txt b/thirdparty/SQLite/CMakeLists.txt index aa7a6423..3aa066a4 100644 --- a/thirdparty/SQLite/CMakeLists.txt +++ b/thirdparty/SQLite/CMakeLists.txt @@ -10,5 +10,10 @@ if(UNIX) target_link_libraries(sqlite3 pthread dl m) # -Wno-unused-result -Wno-unknown-pragmas -fpermissive - target_compile_options(sqlite3 PRIVATE "-Wno-return-local-addr" "-Wno-maybe-uninitialized") + target_compile_options(sqlite3 PRIVATE) + if(NOT APPLE) + target_compile_options(sqlite3 PRIVATE "-Wno-return-local-addr" "-Wno-maybe-uninitialized") + else() + target_compile_options(sqlite3 PRIVATE "-Wno-return-stack-address" "-Wno-uninitialized" "-Wno-deprecated-declarations") + endif() endif() diff --git a/thirdparty/mariadb-connector-cpp b/thirdparty/mariadb-connector-cpp index 8641b145..ef087399 160000 --- a/thirdparty/mariadb-connector-cpp +++ b/thirdparty/mariadb-connector-cpp @@ -1 +1 @@ -Subproject commit 8641b1453ae3ce5a70f78248a1f7fc20a048cb88 +Subproject commit ef0873998b3f94a4f76a485fb90b14866fbb99d4 diff --git a/vanity/NPC.xml b/vanity/NPC.xml deleted file mode 100644 index 2311ab46..00000000 --- a/vanity/NPC.xml +++ /dev/null @@ -1,453 +0,0 @@ - - - 6802, 2519, 2623, 14806 - - Sorry for the mess. - To future endeavours! - What could imagination bring to light? - Vroom vroom... - Take care to preserve the universe. - Builders of the world, unite! - Everything is awesome! - I hope my behaviors are behaving themselves. - - - - - - - - - 12947, 12949, 12962, 12963 - - I hope quickbulds are still working! - Be careful crossing the gap! - Have The Maelstrom stopped going invisible? - - - - - - - - - 9950, 9944, 14102, 14092 - - Hello Explorer! It's great to see you made it! - Have you heard about Darkflame? - I've traveled across this entire system, but nothing beats the view here. - - - - - - - - - - - cmerw[acowipaejio;fawjioefasdl;kfjm; - I, for one, welcome our new robot overlords. - zxnpoasdfiopwemsadf'kawpfo[ekasdf;'s - *teleports behind you* - -