Merge remote-tracking branch 'upstream/main' into MSVCCompilerFlags

This commit is contained in:
jadebenn 2024-04-03 19:00:39 -05:00
commit 199c8224a5
413 changed files with 5654 additions and 4943 deletions

View File

@ -1,9 +1,12 @@
cmake_minimum_required(VERSION 3.18) cmake_minimum_required(VERSION 3.25)
project(Darkflame) project(Darkflame)
include(CTest) include(CTest)
set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD 20)
set(CXX_STANDARD_REQUIRED ON) set(CXX_STANDARD_REQUIRED ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON) # Export the compile commands for debugging
set(CMAKE_POLICY_DEFAULT_CMP0063 NEW) # Set CMAKE visibility policy to NEW on project and subprojects
set(CMAKE_VISIBILITY_INLINES_HIDDEN ON) # Set C and C++ symbol visibility to hide inlined functions
set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake") set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
# Read variables from file # Read variables from file
@ -78,6 +81,7 @@ endif()
# Our output dir # Our output dir
set(CMAKE_BINARY_DIR ${PROJECT_BINARY_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 # TODO make this not have to override the build type directories
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_BINARY_DIR}) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELWITHDEBINFO ${CMAKE_BINARY_DIR})
@ -91,6 +95,8 @@ set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
find_package(MariaDB)
# Create a /resServer directory # Create a /resServer directory
make_directory(${CMAKE_BINARY_DIR}/resServer) make_directory(${CMAKE_BINARY_DIR}/resServer)
@ -180,7 +186,7 @@ file(ARCHIVE_EXTRACT INPUT ${PROJECT_BINARY_DIR}/navmeshes.zip DESTINATION ${PRO
file(REMOVE ${PROJECT_BINARY_DIR}/navmeshes.zip) file(REMOVE ${PROJECT_BINARY_DIR}/navmeshes.zip)
# Copy vanity files on first build # 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}) foreach(file ${VANITY_FILES})
configure_file("${CMAKE_SOURCE_DIR}/vanity/${file}" "${CMAKE_BINARY_DIR}/vanity/${file}" COPYONLY) configure_file("${CMAKE_SOURCE_DIR}/vanity/${file}" "${CMAKE_BINARY_DIR}/vanity/${file}" COPYONLY)
@ -203,91 +209,47 @@ foreach(file ${SQL_FILES})
configure_file(${CMAKE_SOURCE_DIR}/migrations/cdserver/${file} ${PROJECT_BINARY_DIR}/migrations/cdserver/${file}) configure_file(${CMAKE_SOURCE_DIR}/migrations/cdserver/${file} ${PROJECT_BINARY_DIR}/migrations/cdserver/${file})
endforeach() 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 # Create our list of include directories
set(INCLUDED_DIRECTORIES include_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"
"dPhysics" "dPhysics"
"dNavigation" "dNavigation"
"dNavigation/dTerrain"
"dZoneManager"
"dDatabase"
"dDatabase/CDClientDatabase"
"dDatabase/CDClientDatabase/CDClientTables"
"dDatabase/GameDatabase"
"dDatabase/GameDatabase/ITables"
"dDatabase/GameDatabase/MySQL"
"dDatabase/GameDatabase/MySQL/Tables"
"dNet" "dNet"
"thirdparty/magic_enum/include/magic_enum"
"thirdparty/raknet/Source"
"thirdparty/tinyxml2"
"thirdparty/recastnavigation"
"thirdparty/SQLite"
"thirdparty/cpplinq"
"thirdparty/cpp-httplib"
"thirdparty/MD5"
"tests" "tests"
"tests/dCommonTests" "tests/dCommonTests"
"tests/dGameTests" "tests/dGameTests"
"tests/dGameTests/dComponentsTests" "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) # Add system specfic includes for Apple, Windows and Other Unix OS' (including Linux)
# TODO: Should probably not do this.
if(APPLE) if(APPLE)
include_directories("/usr/local/include/") include_directories("/usr/local/include/")
endif() 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: # Add linking directories:
link_directories(${PROJECT_BINARY_DIR})
# Load all of our third party directories
add_subdirectory(thirdparty)
if (UNIX) if (UNIX)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wold-style-cast -Werror") # Warning flags
endif() endif()
# 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
)
file( file(
GLOB HEADERS_DZONEMANAGER GLOB HEADERS_DZONEMANAGER
LIST_DIRECTORIES false LIST_DIRECTORIES false
@ -322,7 +284,7 @@ add_subdirectory(dPhysics)
add_subdirectory(dServer) add_subdirectory(dServer)
# Create a list of common libraries shared between all binaries # Create a list of common libraries shared between all binaries
set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "raknet" "mariadbConnCpp" "magic_enum" "MD5") set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "raknet" "MariaDB::ConnCpp" "magic_enum")
# Add platform specific common libraries # Add platform specific common libraries
if(UNIX) if(UNIX)
@ -344,12 +306,6 @@ target_precompile_headers(
${HEADERS_DZONEMANAGER} ${HEADERS_DZONEMANAGER}
) )
# Need to specify to use the CXX compiler language here or else we get errors including <string>.
target_precompile_headers(
dDatabase PRIVATE
"$<$<COMPILE_LANGUAGE:CXX>:${HEADERS_DDATABASE}>"
)
target_precompile_headers( target_precompile_headers(
dCommon PRIVATE dCommon PRIVATE
${HEADERS_DCOMMON} ${HEADERS_DCOMMON}

View File

@ -23,8 +23,7 @@ RUN --mount=type=cache,id=build-apt-cache,target=/var/cache/apt \
rm -rf /var/lib/apt/lists/* rm -rf /var/lib/apt/lists/*
# Grab libraries and load them # 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/libmariadbcpp.so /usr/local/lib/
COPY --from=build /app/build/mariadbcpp/src/mariadb_connector_cpp-build/libmariadb/libmariadb/libmariadb.so.3 /usr/local/lib
RUN ldconfig RUN ldconfig
# Server bins # Server bins

View File

@ -51,7 +51,7 @@ git clone --recursive https://github.com/DarkflameUniverse/DarkflameServer
### Windows packages ### 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. 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 <font size="4">**CMake version 3.18**</font> or later!). You'll also need to download and install [CMake](https://cmake.org/download/) (version <font size="4">**CMake version 3.25**</font> or later!).
### MacOS packages ### MacOS packages
Ensure you have [brew](https://brew.sh) installed. Ensure you have [brew](https://brew.sh) installed.
@ -73,7 +73,7 @@ sudo apt install build-essential gcc zlib1g-dev libssl-dev openssl mariadb-serve
``` ```
#### Required CMake version #### Required CMake version
This project uses <font size="4">**CMake version 3.18**</font> or higher and as such you will need to ensure you have this version installed. This project uses <font size="4">**CMake version 3.25**</font> or higher and as such you will need to ensure you have this version installed.
You can check your CMake version by using the following command in a terminal. You can check your CMake version by using the following command in a terminal.
```bash ```bash
cmake --version cmake --version

View File

@ -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)

View File

@ -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") set(MARIADB_CONNECTOR_CPP_MSI "mariadb-connector-cpp-${MARIADB_CONNECTOR_CPP_VERSION}-win64.msi")
if(NOT EXISTS "${MARIADB_MSI_DIR}/${MARIADB_CONNECTOR_C_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} 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}" "${MARIADB_MSI_DIR}/${MARIADB_CONNECTOR_C_MSI}"
EXPECTED_HASH MD5=${MARIADB_CONNECTOR_C_MD5}) EXPECTED_HASH MD5=${MARIADB_CONNECTOR_C_MD5})
endif() endif()
if(NOT EXISTS "${MARIADB_MSI_DIR}/${MARIADB_CONNECTOR_CPP_MSI}" ) 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} 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}" "${MARIADB_MSI_DIR}/${MARIADB_CONNECTOR_CPP_MSI}"
EXPECTED_HASH MD5=${MARIADB_CONNECTOR_CPP_MD5}) 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) file(TO_NATIVE_PATH "${MARIADB_MSI_DIR}/${MARIADB_CONNECTOR_C_MSI}" MSI_DIR)
execute_process(COMMAND msiexec /a ${MSI_DIR} /qn TARGETDIR=${MSIEXEC_TARGETDIR}) execute_process(COMMAND msiexec /a ${MSI_DIR} /qn TARGETDIR=${MSIEXEC_TARGETDIR})
endif() endif()
set(MARIADBC_SHARED_LIBRARY_LOCATION "${MARIADB_C_CONNECTOR_DIR}/lib/libmariadb.dll")
if(NOT EXISTS "${MARIADB_CPP_CONNECTOR_DIR}") if(NOT EXISTS "${MARIADB_CPP_CONNECTOR_DIR}")
file(TO_NATIVE_PATH "${MARIADB_MSI_DIR}/${MARIADB_CONNECTOR_CPP_MSI}" MSI_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}) execute_process(COMMAND msiexec /a ${MSI_DIR} /qn TARGETDIR=${MSIEXEC_TARGETDIR})
endif() 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_IMPLIB_LOCATION "${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.lib")
set(MARIADB_INCLUDE_DIR "${MARIADB_CPP_CONNECTOR_DIR}/include/mariadb") set(MARIADB_INCLUDE_DIR "${MARIADB_CPP_CONNECTOR_DIR}/include/mariadb")
add_custom_target(mariadb_connector_cpp) add_custom_target(mariadb_connector_cpp)
add_custom_command(TARGET mariadb_connector_cpp POST_BUILD add_custom_command(TARGET mariadb_connector_cpp POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different COMMAND ${CMAKE_COMMAND} -E copy_if_different
"${MARIADB_CPP_CONNECTOR_DIR}/mariadbcpp.dll" "${MARIADBCPP_SHARED_LIBRARY_LOCATION}"
"${MARIADB_C_CONNECTOR_DIR}/lib/libmariadb.dll" "${MARIADBC_SHARED_LIBRARY_LOCATION}"
"${PROJECT_BINARY_DIR}") "${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, # 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. # 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 # 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") add_compile_definitions(MARIADB_PLUGIN_DIR_OVERRIDE="${MARIADB_CPP_CONNECTOR_DIR}/plugin")
else() # Build from source else() # Build from source
@ -85,77 +86,61 @@ else() # Build from source
-DCMAKE_CXX_FLAGS=-D_GLIBCXX_USE_CXX11_ABI=0) -DCMAKE_CXX_FLAGS=-D_GLIBCXX_USE_CXX11_ABI=0)
endif() 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 ExternalProject_Add(mariadb_connector_cpp
SOURCE_DIR ${CMAKE_SOURCE_DIR}/thirdparty/mariadb-connector-cpp PREFIX "${PROJECT_BINARY_DIR}/thirdparty/mariadb-connector-cpp"
CMAKE_ARGS -Wno-dev SOURCE_DIR ${MARIADBCPP_SOURCE_DIR}
-DCMAKE_BUILD_RPATH_USE_ORIGIN=${CMAKE_BUILD_RPATH_USE_ORIGIN} INSTALL_DIR ${MARIADBCPP_INSTALL_DIR}
-DCMAKE_INSTALL_PREFIX=./mariadbcpp # Points the connector to the correct plugin directory CMAKE_ARGS -Wno-dev
-DINSTALL_PLUGINDIR=plugin -DWITH_UNIT_TESTS=OFF
${MARIADB_EXTRA_CMAKE_ARGS} -DMARIADB_LINK_DYNAMIC=OFF
PREFIX "${PROJECT_BINARY_DIR}/mariadbcpp" -DCMAKE_BUILD_RPATH_USE_ORIGIN=${CMAKE_BUILD_RPATH_USE_ORIGIN}
BUILD_COMMAND cmake --build . --config RelWithDebInfo -j${MARIADB_CONNECTOR_COMPILE_JOBS} -DCMAKE_INSTALL_PREFIX=<INSTALL_DIR>
INSTALL_COMMAND "") -DINSTALL_LIBDIR=${MARIADBCPP_LIBRARY_DIR}
-DINSTALL_PLUGINDIR=${MARIADBCPP_PLUGIN_DIR}
ExternalProject_Get_Property(mariadb_connector_cpp BINARY_DIR) ${MARIADB_EXTRA_CMAKE_ARGS}
BUILD_ALWAYS true
)
if(WIN32) if(WIN32)
set(MARIADB_SHARED_LIBRARY_NAME mariadbcpp.dll) set(MARIADB_SHARED_LIBRARY_NAME mariadbcpp.dll)
set(MARIADB_PLUGIN_SUFFIX .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 # When built from source windows only seems to check same folder as exe instead specified folder, so use
# environment variable to force it # environment variable to force it
add_link_options(/DELAYLOAD:mariadbcpp.dll) 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() else()
set(MARIADB_SHARED_LIBRARY_NAME libmariadbcpp${CMAKE_SHARED_LIBRARY_SUFFIX}) set(MARIADB_SHARED_LIBRARY_NAME libmariadbcpp${CMAKE_SHARED_LIBRARY_SUFFIX})
set(MARIADB_PLUGIN_SUFFIX .so) set(MARIADB_PLUGIN_SUFFIX ${CMAKE_SHARED_LIBRARY_SUFFIX})
endif() endif()
get_property(isMultiConfig GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) set(MARIADBCPP_SHARED_LIBRARY_LOCATION "${MARIADBCPP_LIBRARY_DIR}/${MARIADB_SHARED_LIBRARY_NAME}")
if(isMultiConfig) if(WIN32)
set(MARIADB_SHARED_LIBRARY_LOCATION "${BINARY_DIR}/RelWithDebInfo/${MARIADB_SHARED_LIBRARY_NAME}") set(MARIADBC_SHARED_LIBRARY_LOCATION "${MARIADBCPP_LIBRARY_DIR}/libmariadb.lib")
set(MARIADB_SHARED_LIBRARY_COPY_LOCATION "${PROJECT_BINARY_DIR}/$<CONFIG>")
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")
endif() 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() endif()
# Create mariadb connector library object # Create mariadb connector library object
add_library(mariadbConnCpp SHARED IMPORTED GLOBAL) add_library(MariaDB::ConnCpp SHARED IMPORTED GLOBAL)
set_property(TARGET mariadbConnCpp PROPERTY IMPORTED_LOCATION ${MARIADB_SHARED_LIBRARY_LOCATION}) add_dependencies(MariaDB::ConnCpp mariadb_connector_cpp)
set_target_properties(MariaDB::ConnCpp PROPERTIES
IMPORTED_LOCATION "${MARIADBCPP_SHARED_LIBRARY_LOCATION}")
if(WIN32) 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() endif()
# Add directories to include lists # Add directories to include lists
target_include_directories(mariadbConnCpp INTERFACE ${MARIADB_INCLUDE_DIR}) target_include_directories(MariaDB::ConnCpp SYSTEM INTERFACE ${MARIADB_INCLUDE_DIR})
add_dependencies(mariadbConnCpp mariadb_connector_cpp)
set(MariaDB_FOUND TRUE)

View File

@ -5,10 +5,12 @@ set(DCHATSERVER_SOURCES
) )
add_executable(ChatServer "ChatServer.cpp") add_executable(ChatServer "ChatServer.cpp")
add_library(dChatServer ${DCHATSERVER_SOURCES}) target_include_directories(ChatServer PRIVATE "${PROJECT_SOURCE_DIR}/dChatFilter")
target_include_directories(dChatServer PRIVATE ${PROJECT_SOURCE_DIR}/dServer)
add_compile_definitions(ChatServer PRIVATE PROJECT_VERSION="\"${PROJECT_VERSION}\"") 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(dChatServer ${COMMON_LIBRARIES} dChatFilter)
target_link_libraries(ChatServer ${COMMON_LIBRARIES} dChatFilter dChatServer dServer) target_link_libraries(ChatServer ${COMMON_LIBRARIES} dChatFilter dChatServer dServer)

View File

@ -59,7 +59,7 @@ void ChatIgnoreList::GetIgnoreList(Packet* packet) {
bitStream.Write(LUWString(ignoredPlayer.playerName, 36)); 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) { void ChatIgnoreList::AddIgnore(Packet* packet) {
@ -131,7 +131,7 @@ void ChatIgnoreList::AddIgnore(Packet* packet) {
bitStream.Write(playerNameSend); bitStream.Write(playerNameSend);
bitStream.Write(ignoredPlayerId); bitStream.Write(ignoredPlayerId);
Game::server->Send(&bitStream, packet->systemAddress, false); Game::server->Send(bitStream, packet->systemAddress, false);
} }
void ChatIgnoreList::RemoveIgnore(Packet* packet) { void ChatIgnoreList::RemoveIgnore(Packet* packet) {
@ -167,5 +167,5 @@ void ChatIgnoreList::RemoveIgnore(Packet* packet) {
LUWString playerNameSend(removedIgnoreStr, 33); LUWString playerNameSend(removedIgnoreStr, 33);
bitStream.Write(playerNameSend); bitStream.Write(playerNameSend);
Game::server->Send(&bitStream, packet->systemAddress, false); Game::server->Send(bitStream, packet->systemAddress, false);
} }

View File

@ -101,7 +101,7 @@ int main(int argc, char** argv) {
//It's safe to pass 'localhost' here, as the IP is only used as the external IP. //It's safe to pass 'localhost' here, as the IP is only used as the external IP.
std::string ourIP = "localhost"; std::string ourIP = "localhost";
const uint32_t maxClients = GeneralUtils::TryParse<uint32_t>(Game::config->GetValue("max_clients")).value_or(999); const uint32_t maxClients = GeneralUtils::TryParse<uint32_t>(Game::config->GetValue("max_clients")).value_or(999);
const uint32_t ourPort = GeneralUtils::TryParse<uint32_t>(Game::config->GetValue("chat_server_port")).value_or(1501); const uint32_t ourPort = GeneralUtils::TryParse<uint32_t>(Game::config->GetValue("chat_server_port")).value_or(2005);
const auto externalIPString = Game::config->GetValue("external_ip"); const auto externalIPString = Game::config->GetValue("external_ip");
if (!externalIPString.empty()) ourIP = externalIPString; if (!externalIPString.empty()) ourIP = externalIPString;
@ -211,7 +211,7 @@ void HandlePacket(Packet* packet) {
case eChatInternalMessageType::ANNOUNCEMENT: { case eChatInternalMessageType::ANNOUNCEMENT: {
//we just forward this packet to every connected server //we just forward this packet to every connected server
CINSTREAM; CINSTREAM;
Game::server->Send(&inStream, packet->systemAddress, true); //send to everyone except origin Game::server->Send(inStream, packet->systemAddress, true); //send to everyone except origin
break; break;
} }

View File

@ -150,7 +150,7 @@ void PlayerContainer::BroadcastMuteUpdate(LWOOBJID player, time_t time) {
bitStream.Write(player); bitStream.Write(player);
bitStream.Write(time); bitStream.Write(time);
Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); Game::server->Send(bitStream, UNASSIGNED_SYSTEM_ADDRESS, true);
} }
TeamData* PlayerContainer::CreateLocalTeam(std::vector<LWOOBJID> members) { TeamData* PlayerContainer::CreateLocalTeam(std::vector<LWOOBJID> members) {
@ -365,7 +365,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) { std::u16string PlayerContainer::GetName(LWOOBJID playerID) {
@ -390,7 +390,7 @@ LWOOBJID PlayerContainer::GetId(const std::u16string& playerName) {
} }
PlayerData& PlayerContainer::GetPlayerDataMutable(const LWOOBJID& playerID) { PlayerData& PlayerContainer::GetPlayerDataMutable(const LWOOBJID& playerID) {
return m_Players[playerID]; return m_Players.contains(playerID) ? m_Players[playerID] : m_Players[LWOOBJID_EMPTY];
} }
PlayerData& PlayerContainer::GetPlayerDataMutable(const std::string& playerName) { PlayerData& PlayerContainer::GetPlayerDataMutable(const std::string& playerName) {

View File

@ -9,12 +9,11 @@
* AMF3 Deserializer written by EmosewaMC * AMF3 Deserializer written by EmosewaMC
*/ */
AMFBaseValue* AMFDeserialize::Read(RakNet::BitStream* inStream) { AMFBaseValue* AMFDeserialize::Read(RakNet::BitStream& inStream) {
if (!inStream) return nullptr;
AMFBaseValue* returnValue = nullptr; AMFBaseValue* returnValue = nullptr;
// Read in the value type from the bitStream // Read in the value type from the bitStream
eAmf marker; eAmf marker;
inStream->Read(marker); inStream.Read(marker);
// Based on the typing, create the value associated with that and return the base value class // Based on the typing, create the value associated with that and return the base value class
switch (marker) { switch (marker) {
case eAmf::Undefined: { case eAmf::Undefined: {
@ -79,13 +78,13 @@ AMFBaseValue* AMFDeserialize::Read(RakNet::BitStream* inStream) {
return returnValue; return returnValue;
} }
uint32_t AMFDeserialize::ReadU29(RakNet::BitStream* inStream) { uint32_t AMFDeserialize::ReadU29(RakNet::BitStream& inStream) {
bool byteFlag = true; bool byteFlag = true;
uint32_t actualNumber{}; uint32_t actualNumber{};
uint8_t numberOfBytesRead{}; uint8_t numberOfBytesRead{};
while (byteFlag && numberOfBytesRead < 4) { while (byteFlag && numberOfBytesRead < 4) {
uint8_t byte{}; uint8_t byte{};
inStream->Read(byte); inStream.Read(byte);
// Parse the byte // Parse the byte
if (numberOfBytesRead < 3) { if (numberOfBytesRead < 3) {
byteFlag = byte & static_cast<uint8_t>(1 << 7); byteFlag = byte & static_cast<uint8_t>(1 << 7);
@ -101,7 +100,7 @@ uint32_t AMFDeserialize::ReadU29(RakNet::BitStream* inStream) {
return actualNumber; return actualNumber;
} }
const std::string AMFDeserialize::ReadString(RakNet::BitStream* inStream) { const std::string AMFDeserialize::ReadString(RakNet::BitStream& inStream) {
auto length = ReadU29(inStream); auto length = ReadU29(inStream);
// Check if this is a reference // Check if this is a reference
bool isReference = length % 2 == 1; bool isReference = length % 2 == 1;
@ -109,7 +108,7 @@ const std::string AMFDeserialize::ReadString(RakNet::BitStream* inStream) {
length = length >> 1; length = length >> 1;
if (isReference) { if (isReference) {
std::string value(length, 0); std::string value(length, 0);
inStream->Read(&value[0], length); inStream.Read(&value[0], length);
// Empty strings are never sent by reference // Empty strings are never sent by reference
if (!value.empty()) accessedElements.push_back(value); if (!value.empty()) accessedElements.push_back(value);
return 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; double value;
inStream->Read<double>(value); inStream.Read<double>(value);
return new AMFDoubleValue(value); return new AMFDoubleValue(value);
} }
AMFBaseValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream* inStream) { AMFBaseValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream& inStream) {
auto arrayValue = new AMFArrayValue(); auto arrayValue = new AMFArrayValue();
// Read size of dense array // Read size of dense array
auto sizeOfDenseArray = (ReadU29(inStream) >> 1); const auto sizeOfDenseArray = (ReadU29(inStream) >> 1);
// Then read associative portion // Then read associative portion
while (true) { while (true) {
auto key = ReadString(inStream); const auto key = ReadString(inStream);
// No more associative values when we encounter an empty string key // No more associative values when we encounter an empty string key
if (key.size() == 0) break; if (key.size() == 0) break;
arrayValue->Insert(key, Read(inStream)); arrayValue->Insert(key, Read(inStream));
@ -144,10 +143,10 @@ AMFBaseValue* AMFDeserialize::ReadAmfArray(RakNet::BitStream* inStream) {
return arrayValue; return arrayValue;
} }
AMFBaseValue* AMFDeserialize::ReadAmfString(RakNet::BitStream* inStream) { AMFBaseValue* AMFDeserialize::ReadAmfString(RakNet::BitStream& inStream) {
return new AMFStringValue(ReadString(inStream)); return new AMFStringValue(ReadString(inStream));
} }
AMFBaseValue* AMFDeserialize::ReadAmfInteger(RakNet::BitStream* inStream) { AMFBaseValue* AMFDeserialize::ReadAmfInteger(RakNet::BitStream& inStream) {
return new AMFIntValue(ReadU29(inStream)); return new AMFIntValue(ReadU29(inStream));
} }

View File

@ -15,7 +15,7 @@ public:
* @param inStream inStream to read value from. * @param inStream inStream to read value from.
* @return Returns an AMFValue with all the information from the bitStream in it. * @return Returns an AMFValue with all the information from the bitStream in it.
*/ */
AMFBaseValue* Read(RakNet::BitStream* inStream); AMFBaseValue* Read(RakNet::BitStream& inStream);
private: private:
/** /**
* @brief Private method to read a U29 integer from a bitstream * @brief Private method to read a U29 integer from a bitstream
@ -23,7 +23,7 @@ private:
* @param inStream bitstream to read data from * @param inStream bitstream to read data from
* @return The number as an unsigned 29 bit integer * @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 * @brief Reads a string from a bitstream
@ -31,7 +31,7 @@ private:
* @param inStream bitStream to read data from * @param inStream bitStream to read data from
* @return The read string * @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 * @brief Read an AMFDouble value from a bitStream
@ -39,7 +39,7 @@ private:
* @param inStream bitStream to read data from * @param inStream bitStream to read data from
* @return Double value represented as an AMFValue * @return Double value represented as an AMFValue
*/ */
AMFBaseValue* ReadAmfDouble(RakNet::BitStream* inStream); AMFBaseValue* ReadAmfDouble(RakNet::BitStream& inStream);
/** /**
* @brief Read an AMFArray from a bitStream * @brief Read an AMFArray from a bitStream
@ -47,7 +47,7 @@ private:
* @param inStream bitStream to read data from * @param inStream bitStream to read data from
* @return Array value represented as an AMFValue * @return Array value represented as an AMFValue
*/ */
AMFBaseValue* ReadAmfArray(RakNet::BitStream* inStream); AMFBaseValue* ReadAmfArray(RakNet::BitStream& inStream);
/** /**
* @brief Read an AMFString from a bitStream * @brief Read an AMFString from a bitStream
@ -55,7 +55,7 @@ private:
* @param inStream bitStream to read data from * @param inStream bitStream to read data from
* @return String value represented as an AMFValue * @return String value represented as an AMFValue
*/ */
AMFBaseValue* ReadAmfString(RakNet::BitStream* inStream); AMFBaseValue* ReadAmfString(RakNet::BitStream& inStream);
/** /**
* @brief Read an AMFInteger from a bitStream * @brief Read an AMFInteger from a bitStream
@ -63,7 +63,7 @@ private:
* @param inStream bitStream to read data from * @param inStream bitStream to read data from
* @return Integer value represented as an AMFValue * @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. * List of strings read so far saved to be read by reference.

View File

@ -41,12 +41,14 @@ template <typename ValueType>
class AMFValue : public AMFBaseValue { class AMFValue : public AMFBaseValue {
public: public:
AMFValue() = default; AMFValue() = default;
AMFValue(const ValueType value) { m_Data = value; } AMFValue(const ValueType value) : m_Data{ value } {}
virtual ~AMFValue() override = default; virtual ~AMFValue() override = default;
[[nodiscard]] constexpr eAmf GetValueType() const noexcept override; [[nodiscard]] constexpr eAmf GetValueType() const noexcept override;
[[nodiscard]] const ValueType& GetValue() const { return m_Data; } [[nodiscard]] const ValueType& GetValue() const { return m_Data; }
void SetValue(const ValueType value) { m_Data = value; } void SetValue(const ValueType value) { m_Data = value; }
protected: protected:
@ -54,7 +56,7 @@ protected:
}; };
// Explicit template class instantiations // Explicit template class instantiations
template class AMFValue<std::nullptr_t>; template class AMFValue<std::nullptr_t>;
template class AMFValue<bool>; template class AMFValue<bool>;
template class AMFValue<int32_t>; template class AMFValue<int32_t>;
template class AMFValue<uint32_t>; template class AMFValue<uint32_t>;
@ -110,7 +112,7 @@ public:
[[nodiscard]] constexpr eAmf GetValueType() const noexcept override { return eAmf::Array; } [[nodiscard]] constexpr eAmf GetValueType() const noexcept override { return eAmf::Array; }
~AMFArrayValue() override { ~AMFArrayValue() override {
for (auto valueToDelete : GetDense()) { for (const auto* valueToDelete : GetDense()) {
if (valueToDelete) { if (valueToDelete) {
delete valueToDelete; delete valueToDelete;
valueToDelete = nullptr; valueToDelete = nullptr;
@ -127,12 +129,12 @@ public:
/** /**
* Returns the Associative portion of the object * Returns the Associative portion of the object
*/ */
[[nodiscard]] inline AMFAssociative& GetAssociative() noexcept { return this->associative; } [[nodiscard]] inline const AMFAssociative& GetAssociative() const noexcept { return m_Associative; }
/** /**
* Returns the dense portion of the object * Returns the dense portion of the object
*/ */
[[nodiscard]] inline AMFDense& GetDense() noexcept { return this->dense; } [[nodiscard]] inline const AMFDense& GetDense() const noexcept { return m_Dense; }
/** /**
* Inserts an AMFValue into the associative portion with the given key. * Inserts an AMFValue into the associative portion with the given key.
@ -150,12 +152,12 @@ public:
*/ */
template <typename ValueType> template <typename ValueType>
[[maybe_unused]] std::pair<AMFValue<ValueType>*, bool> Insert(const std::string& key, const ValueType value) { [[maybe_unused]] std::pair<AMFValue<ValueType>*, bool> Insert(const std::string& key, const ValueType value) {
auto element = associative.find(key); const auto element = m_Associative.find(key);
AMFValue<ValueType>* val = nullptr; AMFValue<ValueType>* val = nullptr;
bool found = true; bool found = true;
if (element == associative.end()) { if (element == m_Associative.cend()) {
val = new AMFValue<ValueType>(value); val = new AMFValue<ValueType>(value);
associative.insert(std::make_pair(key, val)); m_Associative.emplace(key, val);
} else { } else {
val = dynamic_cast<AMFValue<ValueType>*>(element->second); val = dynamic_cast<AMFValue<ValueType>*>(element->second);
found = false; found = false;
@ -165,12 +167,12 @@ public:
// Associates an array with a string key // Associates an array with a string key
[[maybe_unused]] std::pair<AMFBaseValue*, bool> Insert(const std::string& key) { [[maybe_unused]] std::pair<AMFBaseValue*, bool> Insert(const std::string& key) {
auto element = associative.find(key); const auto element = m_Associative.find(key);
AMFArrayValue* val = nullptr; AMFArrayValue* val = nullptr;
bool found = true; bool found = true;
if (element == associative.end()) { if (element == m_Associative.cend()) {
val = new AMFArrayValue(); val = new AMFArrayValue();
associative.insert(std::make_pair(key, val)); m_Associative.emplace(key, val);
} else { } else {
val = dynamic_cast<AMFArrayValue*>(element->second); val = dynamic_cast<AMFArrayValue*>(element->second);
found = false; found = false;
@ -182,13 +184,13 @@ public:
[[maybe_unused]] std::pair<AMFBaseValue*, bool> Insert(const size_t index) { [[maybe_unused]] std::pair<AMFBaseValue*, bool> Insert(const size_t index) {
AMFArrayValue* val = nullptr; AMFArrayValue* val = nullptr;
bool inserted = false; bool inserted = false;
if (index >= dense.size()) { if (index >= m_Dense.size()) {
dense.resize(index + 1); m_Dense.resize(index + 1);
val = new AMFArrayValue(); val = new AMFArrayValue();
dense.at(index) = val; m_Dense.at(index) = val;
inserted = true; inserted = true;
} }
return std::make_pair(dynamic_cast<AMFArrayValue*>(dense.at(index)), inserted); return std::make_pair(dynamic_cast<AMFArrayValue*>(m_Dense.at(index)), inserted);
} }
/** /**
@ -205,13 +207,13 @@ public:
[[maybe_unused]] std::pair<AMFValue<ValueType>*, bool> Insert(const size_t index, const ValueType value) { [[maybe_unused]] std::pair<AMFValue<ValueType>*, bool> Insert(const size_t index, const ValueType value) {
AMFValue<ValueType>* val = nullptr; AMFValue<ValueType>* val = nullptr;
bool inserted = false; bool inserted = false;
if (index >= this->dense.size()) { if (index >= m_Dense.size()) {
this->dense.resize(index + 1); m_Dense.resize(index + 1);
val = new AMFValue<ValueType>(value); val = new AMFValue<ValueType>(value);
this->dense.at(index) = val; m_Dense.at(index) = val;
inserted = true; inserted = true;
} }
return std::make_pair(dynamic_cast<AMFValue<ValueType>*>(this->dense.at(index)), inserted); return std::make_pair(dynamic_cast<AMFValue<ValueType>*>(m_Dense.at(index)), inserted);
} }
/** /**
@ -224,12 +226,12 @@ public:
* @param value The value to insert * @param value The value to insert
*/ */
void Insert(const std::string& key, AMFBaseValue* const value) { void Insert(const std::string& key, AMFBaseValue* const value) {
auto element = associative.find(key); const auto element = m_Associative.find(key);
if (element != associative.end() && element->second) { if (element != m_Associative.cend() && element->second) {
delete element->second; delete element->second;
element->second = value; element->second = value;
} else { } else {
associative.insert(std::make_pair(key, value)); m_Associative.emplace(key, value);
} }
} }
@ -243,13 +245,13 @@ public:
* @param value The value to insert * @param value The value to insert
*/ */
void Insert(const size_t index, AMFBaseValue* const value) { void Insert(const size_t index, AMFBaseValue* const value) {
if (index < dense.size()) { if (index < m_Dense.size()) {
AMFDense::iterator itr = dense.begin() + index; const AMFDense::const_iterator itr = m_Dense.cbegin() + index;
if (*itr) delete dense.at(index); if (*itr) delete m_Dense.at(index);
} else { } else {
dense.resize(index + 1); m_Dense.resize(index + 1);
} }
dense.at(index) = value; m_Dense.at(index) = value;
} }
/** /**
@ -264,7 +266,7 @@ public:
*/ */
template <typename ValueType> template <typename ValueType>
[[maybe_unused]] inline AMFValue<ValueType>* Push(const ValueType value) { [[maybe_unused]] inline AMFValue<ValueType>* Push(const ValueType value) {
return Insert(this->dense.size(), value).first; return Insert(m_Dense.size(), value).first;
} }
/** /**
@ -275,10 +277,10 @@ public:
* @param key The key to remove from the associative portion * @param key The key to remove from the associative portion
*/ */
void Remove(const std::string& key, const bool deleteValue = true) { void Remove(const std::string& key, const bool deleteValue = true) {
AMFAssociative::iterator it = this->associative.find(key); const AMFAssociative::const_iterator it = m_Associative.find(key);
if (it != this->associative.end()) { if (it != m_Associative.cend()) {
if (deleteValue) delete it->second; if (deleteValue) delete it->second;
this->associative.erase(it); m_Associative.erase(it);
} }
} }
@ -286,27 +288,24 @@ public:
* Pops the last element in the dense portion, deleting it in the process. * Pops the last element in the dense portion, deleting it in the process.
*/ */
void Remove(const size_t index) { void Remove(const size_t index) {
if (!this->dense.empty() && index < this->dense.size()) { if (!m_Dense.empty() && index < m_Dense.size()) {
auto itr = this->dense.begin() + index; const auto itr = m_Dense.cbegin() + index;
if (*itr) delete (*itr); if (*itr) delete (*itr);
this->dense.erase(itr); m_Dense.erase(itr);
} }
} }
void Pop() { void Pop() {
if (!this->dense.empty()) Remove(this->dense.size() - 1); if (!m_Dense.empty()) Remove(m_Dense.size() - 1);
} }
[[nodiscard]] AMFArrayValue* GetArray(const std::string& key) { [[nodiscard]] AMFArrayValue* GetArray(const std::string& key) const {
AMFAssociative::const_iterator it = this->associative.find(key); const AMFAssociative::const_iterator it = m_Associative.find(key);
if (it != this->associative.end()) { return it != m_Associative.cend() ? dynamic_cast<AMFArrayValue*>(it->second) : nullptr;
return dynamic_cast<AMFArrayValue*>(it->second);
}
return nullptr;
} }
[[nodiscard]] AMFArrayValue* GetArray(const size_t index) { [[nodiscard]] AMFArrayValue* GetArray(const size_t index) const {
return index >= this->dense.size() ? nullptr : dynamic_cast<AMFArrayValue*>(this->dense.at(index)); return index < m_Dense.size() ? dynamic_cast<AMFArrayValue*>(m_Dense.at(index)) : nullptr;
} }
[[maybe_unused]] inline AMFArrayValue* InsertArray(const std::string& key) { [[maybe_unused]] inline AMFArrayValue* InsertArray(const std::string& key) {
@ -318,7 +317,7 @@ public:
} }
[[maybe_unused]] inline AMFArrayValue* PushArray() { [[maybe_unused]] inline AMFArrayValue* PushArray() {
return static_cast<AMFArrayValue*>(Insert(this->dense.size()).first); return static_cast<AMFArrayValue*>(Insert(m_Dense.size()).first);
} }
/** /**
@ -332,16 +331,16 @@ public:
*/ */
template <typename AmfType> template <typename AmfType>
[[nodiscard]] AMFValue<AmfType>* Get(const std::string& key) const { [[nodiscard]] AMFValue<AmfType>* Get(const std::string& key) const {
AMFAssociative::const_iterator it = this->associative.find(key); const AMFAssociative::const_iterator it = m_Associative.find(key);
return it != this->associative.end() ? return it != m_Associative.cend() ?
dynamic_cast<AMFValue<AmfType>*>(it->second) : dynamic_cast<AMFValue<AmfType>*>(it->second) :
nullptr; nullptr;
} }
// Get from the array but dont cast it // Get from the array but dont cast it
[[nodiscard]] AMFBaseValue* Get(const std::string& key) const { [[nodiscard]] AMFBaseValue* Get(const std::string& key) const {
AMFAssociative::const_iterator it = this->associative.find(key); const AMFAssociative::const_iterator it = m_Associative.find(key);
return it != this->associative.end() ? it->second : nullptr; return it != m_Associative.cend() ? it->second : nullptr;
} }
/** /**
@ -355,27 +354,27 @@ public:
*/ */
template <typename AmfType> template <typename AmfType>
[[nodiscard]] AMFValue<AmfType>* Get(const size_t index) const { [[nodiscard]] AMFValue<AmfType>* Get(const size_t index) const {
return index < this->dense.size() ? return index < m_Dense.size() ?
dynamic_cast<AMFValue<AmfType>*>(this->dense.at(index)) : dynamic_cast<AMFValue<AmfType>*>(m_Dense.at(index)) :
nullptr; nullptr;
} }
// Get from the dense but dont cast it // Get from the dense but dont cast it
[[nodiscard]] AMFBaseValue* Get(const size_t index) const { [[nodiscard]] AMFBaseValue* Get(const size_t index) const {
return index < this->dense.size() ? this->dense.at(index) : nullptr; return index < m_Dense.size() ? m_Dense.at(index) : nullptr;
} }
private: private:
/** /**
* The associative portion. These values are key'd with strings to an AMFValue. * 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 * The dense portion. These AMFValue's are stored one after
* another with the most recent addition being at the back. * another with the most recent addition being at the back.
*/ */
AMFDense dense; AMFDense m_Dense;
}; };
#endif //!__AMF3__H__ #endif //!__AMF3__H__

View File

@ -53,7 +53,7 @@ void RakNet::BitStream::Write<AMFBaseValue&>(AMFBaseValue& value) {
* A private function to write an value to a RakNet::BitStream * A private function to write an value to a RakNet::BitStream
* RakNet writes in the correct byte order - do not reverse this. * 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<unsigned char>(v); unsigned char b4 = static_cast<unsigned char>(v);
if (v < 0x00200000) { if (v < 0x00200000) {
b4 = b4 & 0x7F; b4 = b4 & 0x7F;
@ -65,10 +65,10 @@ void WriteUInt29(RakNet::BitStream* bs, uint32_t v) {
unsigned char b2; unsigned char b2;
v = v >> 7; v = v >> 7;
b2 = static_cast<unsigned char>(v) | 0x80; b2 = static_cast<unsigned char>(v) | 0x80;
bs->Write(b2); bs.Write(b2);
} }
bs->Write(b3); bs.Write(b3);
} }
} else { } else {
unsigned char b1; unsigned char b1;
@ -82,19 +82,19 @@ void WriteUInt29(RakNet::BitStream* bs, uint32_t v) {
v = v >> 7; v = v >> 7;
b1 = static_cast<unsigned char>(v) | 0x80; b1 = static_cast<unsigned char>(v) | 0x80;
bs->Write(b1); bs.Write(b1);
bs->Write(b2); bs.Write(b2);
bs->Write(b3); bs.Write(b3);
} }
bs->Write(b4); bs.Write(b4);
} }
/** /**
* Writes a flag number to a RakNet::BitStream * Writes a flag number to a RakNet::BitStream
* RakNet writes in the correct byte order - do not reverse this. * 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; v = (v << 1) | 0x01;
WriteUInt29(bs, v); 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. * 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<uint32_t>(str.size())); WriteFlagNumber(bs, static_cast<uint32_t>(str.size()));
bs->Write(str.c_str(), static_cast<uint32_t>(str.size())); bs.Write(str.c_str(), static_cast<uint32_t>(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. * RakNet writes in the correct byte order - do not reverse this.
*/ */
void WriteAMFU16(RakNet::BitStream* bs, uint16_t value) { void WriteAMFU16(RakNet::BitStream& bs, uint16_t value) {
bs->Write(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. * RakNet writes in the correct byte order - do not reverse this.
*/ */
void WriteAMFU32(RakNet::BitStream* bs, uint32_t value) { void WriteAMFU32(RakNet::BitStream& bs, uint32_t value) {
bs->Write(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. * RakNet writes in the correct byte order - do not reverse this.
*/ */
void WriteAMFU64(RakNet::BitStream* bs, uint64_t value) { void WriteAMFU64(RakNet::BitStream& bs, uint64_t value) {
bs->Write(value); bs.Write(value);
} }
// Writes an AMFIntegerValue to BitStream // Writes an AMFIntegerValue to BitStream
template<> template<>
void RakNet::BitStream::Write<AMFIntValue&>(AMFIntValue& value) { void RakNet::BitStream::Write<AMFIntValue&>(AMFIntValue& value) {
WriteUInt29(this, value.GetValue()); WriteUInt29(*this, value.GetValue());
} }
// Writes an AMFDoubleValue to BitStream // Writes an AMFDoubleValue to BitStream
template<> template<>
void RakNet::BitStream::Write<AMFDoubleValue&>(AMFDoubleValue& value) { void RakNet::BitStream::Write<AMFDoubleValue&>(AMFDoubleValue& value) {
double d = value.GetValue(); double d = value.GetValue();
WriteAMFU64(this, *reinterpret_cast<uint64_t*>(&d)); WriteAMFU64(*this, *reinterpret_cast<uint64_t*>(&d));
} }
// Writes an AMFStringValue to BitStream // Writes an AMFStringValue to BitStream
template<> template<>
void RakNet::BitStream::Write<AMFStringValue&>(AMFStringValue& value) { void RakNet::BitStream::Write<AMFStringValue&>(AMFStringValue& value) {
WriteAMFString(this, value.GetValue()); WriteAMFString(*this, value.GetValue());
} }
// Writes an AMFArrayValue to BitStream // Writes an AMFArrayValue to BitStream
template<> template<>
void RakNet::BitStream::Write<AMFArrayValue&>(AMFArrayValue& value) { void RakNet::BitStream::Write<AMFArrayValue&>(AMFArrayValue& value) {
uint32_t denseSize = value.GetDense().size(); uint32_t denseSize = value.GetDense().size();
WriteFlagNumber(this, denseSize); WriteFlagNumber(*this, denseSize);
auto it = value.GetAssociative().begin(); auto it = value.GetAssociative().begin();
auto end = value.GetAssociative().end(); auto end = value.GetAssociative().end();
while (it != end) { while (it != end) {
WriteAMFString(this, it->first); WriteAMFString(*this, it->first);
this->Write<AMFBaseValue&>(*it->second); this->Write<AMFBaseValue&>(*it->second);
it++; it++;
} }

View File

@ -30,11 +30,15 @@ foreach(file ${DCOMMON_DCLIENT_SOURCES})
set(DCOMMON_SOURCES ${DCOMMON_SOURCES} "dClient/${file}") set(DCOMMON_SOURCES ${DCOMMON_SOURCES} "dClient/${file}")
endforeach() endforeach()
include_directories(${PROJECT_SOURCE_DIR}/dCommon/)
add_library(dCommon STATIC ${DCOMMON_SOURCES}) add_library(dCommon STATIC ${DCOMMON_SOURCES})
target_include_directories(dCommon
target_link_libraries(dCommon bcrypt dDatabase tinyxml2) 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) if (UNIX)
find_package(ZLIB REQUIRED) find_package(ZLIB REQUIRED)
@ -65,4 +69,6 @@ else ()
) )
endif () endif ()
target_link_libraries(dCommon ZLIB::ZLIB) target_link_libraries(dCommon
PRIVATE ZLIB::ZLIB bcrypt tinyxml2
INTERFACE dDatabase)

View File

@ -278,14 +278,14 @@ std::vector<std::string> GeneralUtils::SplitString(const std::string& str, char
return vector; return vector;
} }
std::u16string GeneralUtils::ReadWString(RakNet::BitStream* inStream) { std::u16string GeneralUtils::ReadWString(RakNet::BitStream& inStream) {
uint32_t length; uint32_t length;
inStream->Read<uint32_t>(length); inStream.Read<uint32_t>(length);
std::u16string string; std::u16string string;
for (auto i = 0; i < length; i++) { for (auto i = 0; i < length; i++) {
uint16_t c; uint16_t c;
inStream->Read(c); inStream.Read(c);
string.push_back(c); string.push_back(c);
} }
@ -294,28 +294,50 @@ std::u16string GeneralUtils::ReadWString(RakNet::BitStream* inStream) {
std::vector<std::string> GeneralUtils::GetSqlFileNamesFromFolder(const std::string& folder) { std::vector<std::string> 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. // Because we dont know how large the initial number before the first _ is we need to make it a map like so.
std::map<uint32_t, std::string> filenames{}; std::map<uint32_t, std::string> filenames{};
for (auto& t : std::filesystem::directory_iterator(folder)) { for (auto& t : std::filesystem::directory_iterator(folder)) {
auto filename = t.path().filename().string(); auto filename = t.path().filename().string();
auto index = std::stoi(GeneralUtils::SplitString(filename, '_').at(0)); auto index = std::stoi(GeneralUtils::SplitString(filename, '_').at(0));
filenames.insert(std::make_pair(index, filename)); filenames.insert(std::make_pair(index, filename));
} }
// Now sort the map by the oldest migration. // Now sort the map by the oldest migration.
std::vector<std::string> sortedFiles{}; std::vector<std::string> sortedFiles{};
auto fileIterator = filenames.begin(); auto fileIterator = filenames.begin();
std::map<uint32_t, std::string>::iterator oldest = filenames.begin(); std::map<uint32_t, std::string>::iterator oldest = filenames.begin();
while (!filenames.empty()) { while (!filenames.empty()) {
if (fileIterator == filenames.end()) { if (fileIterator == filenames.end()) {
sortedFiles.push_back(oldest->second); sortedFiles.push_back(oldest->second);
filenames.erase(oldest); filenames.erase(oldest);
fileIterator = filenames.begin(); fileIterator = filenames.begin();
oldest = filenames.begin(); oldest = filenames.begin();
continue; continue;
} }
if (oldest->first > fileIterator->first) oldest = fileIterator; if (oldest->first > fileIterator->first) oldest = fileIterator;
fileIterator++; fileIterator++;
} }
return sortedFiles; return sortedFiles;
} }
#ifdef DARKFLAME_PLATFORM_MACOS
// MacOS floating-point parse function specializations
namespace GeneralUtils::details {
template <>
[[nodiscard]] float _parse<float>(const std::string_view str, size_t& parseNum) {
return std::stof(std::string{ str }, &parseNum);
}
template <>
[[nodiscard]] double _parse<double>(const std::string_view str, size_t& parseNum) {
return std::stod(std::string{ str }, &parseNum);
}
template <>
[[nodiscard]] long double _parse<long double>(const std::string_view str, size_t& parseNum) {
return std::stold(std::string{ str }, &parseNum);
}
}
#endif

View File

@ -116,7 +116,7 @@ namespace GeneralUtils {
bool ReplaceInString(std::string& str, const std::string& from, const std::string& to); 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<std::wstring> SplitString(std::wstring& str, wchar_t delimiter); std::vector<std::wstring> SplitString(std::wstring& str, wchar_t delimiter);
@ -166,27 +166,12 @@ namespace GeneralUtils {
return isParsed ? static_cast<T>(result) : std::optional<T>{}; return isParsed ? static_cast<T>(result) : std::optional<T>{};
} }
#ifdef DARKFLAME_PLATFORM_MACOS #if !(__GNUC__ >= 11 || _MSC_VER >= 1924)
// Anonymous namespace containing MacOS floating-point parse function specializations // MacOS floating-point parse helper function specializations
namespace { namespace details {
template <std::floating_point T> template <std::floating_point T>
[[nodiscard]] T Parse(const std::string_view str, size_t* parseNum); [[nodiscard]] T _parse(const std::string_view str, size_t& parseNum);
template <>
[[nodiscard]] float Parse<float>(const std::string_view str, size_t* parseNum) {
return std::stof(std::string{ str }, parseNum);
}
template <>
[[nodiscard]] double Parse<double>(const std::string_view str, size_t* parseNum) {
return std::stod(std::string{ str }, parseNum);
}
template <>
[[nodiscard]] long double Parse<long double>(const std::string_view str, size_t* parseNum) {
return std::stold(std::string{ str }, parseNum);
}
} }
/** /**
@ -196,9 +181,10 @@ namespace GeneralUtils {
* @returns An std::optional containing the desired value if it is equivalent to the string * @returns An std::optional containing the desired value if it is equivalent to the string
*/ */
template <std::floating_point T> template <std::floating_point T>
[[nodiscard]] std::optional<T> TryParse(const std::string_view str) noexcept try { [[nodiscard]] std::optional<T> TryParse(const std::string_view str) noexcept
try {
size_t parseNum; size_t parseNum;
const T result = Parse<T>(str, &parseNum); const T result = details::_parse<T>(str, parseNum);
const bool isParsed = str.length() == parseNum; const bool isParsed = str.length() == parseNum;
return isParsed ? result : std::optional<T>{}; return isParsed ? result : std::optional<T>{};
@ -278,8 +264,8 @@ namespace GeneralUtils {
* @returns The enum entry's value in its underlying type * @returns The enum entry's value in its underlying type
*/ */
template <Enum eType> template <Enum eType>
constexpr typename std::underlying_type_t<eType> CastUnderlyingType(const eType entry) noexcept { constexpr std::underlying_type_t<eType> ToUnderlying(const eType entry) noexcept {
return static_cast<typename std::underlying_type_t<eType>>(entry); return static_cast<std::underlying_type_t<eType>>(entry);
} }
// on Windows we need to undef these or else they conflict with our numeric limits calls // on Windows we need to undef these or else they conflict with our numeric limits calls

View File

@ -31,7 +31,7 @@ public:
virtual ~LDFBaseData() {} virtual ~LDFBaseData() {}
virtual void WriteToPacket(RakNet::BitStream* packet) = 0; virtual void WriteToPacket(RakNet::BitStream& packet) = 0;
virtual const std::u16string& GetKey() = 0; virtual const std::u16string& GetKey() = 0;
@ -62,17 +62,17 @@ private:
T value; T value;
//! Writes the key to the packet //! Writes the key to the packet
void WriteKey(RakNet::BitStream* packet) { void WriteKey(RakNet::BitStream& packet) {
packet->Write<uint8_t>(this->key.length() * sizeof(uint16_t)); packet.Write<uint8_t>(this->key.length() * sizeof(uint16_t));
for (uint32_t i = 0; i < this->key.length(); ++i) { for (uint32_t i = 0; i < this->key.length(); ++i) {
packet->Write<uint16_t>(this->key[i]); packet.Write<uint16_t>(this->key[i]);
} }
} }
//! Writes the value to the packet //! Writes the value to the packet
void WriteValue(RakNet::BitStream* packet) { void WriteValue(RakNet::BitStream& packet) {
packet->Write<uint8_t>(this->GetValueType()); packet.Write<uint8_t>(this->GetValueType());
packet->Write(this->value); packet.Write(this->value);
} }
public: public:
@ -108,7 +108,7 @@ public:
/*! /*!
\param packet The packet \param packet The packet
*/ */
void WriteToPacket(RakNet::BitStream* packet) override { void WriteToPacket(RakNet::BitStream& packet) override {
this->WriteKey(packet); this->WriteKey(packet);
this->WriteValue(packet); this->WriteValue(packet);
} }
@ -178,31 +178,31 @@ template<> inline eLDFType LDFData<std::string>::GetValueType(void) { return LDF
// The specialized version for std::u16string (UTF-16) // The specialized version for std::u16string (UTF-16)
template<> template<>
inline void LDFData<std::u16string>::WriteValue(RakNet::BitStream* packet) { inline void LDFData<std::u16string>::WriteValue(RakNet::BitStream& packet) {
packet->Write<uint8_t>(this->GetValueType()); packet.Write<uint8_t>(this->GetValueType());
packet->Write<uint32_t>(this->value.length()); packet.Write<uint32_t>(this->value.length());
for (uint32_t i = 0; i < this->value.length(); ++i) { for (uint32_t i = 0; i < this->value.length(); ++i) {
packet->Write<uint16_t>(this->value[i]); packet.Write<uint16_t>(this->value[i]);
} }
} }
// The specialized version for bool // The specialized version for bool
template<> template<>
inline void LDFData<bool>::WriteValue(RakNet::BitStream* packet) { inline void LDFData<bool>::WriteValue(RakNet::BitStream& packet) {
packet->Write<uint8_t>(this->GetValueType()); packet.Write<uint8_t>(this->GetValueType());
packet->Write<uint8_t>(this->value); packet.Write<uint8_t>(this->value);
} }
// The specialized version for std::string (UTF-8) // The specialized version for std::string (UTF-8)
template<> template<>
inline void LDFData<std::string>::WriteValue(RakNet::BitStream* packet) { inline void LDFData<std::string>::WriteValue(RakNet::BitStream& packet) {
packet->Write<uint8_t>(this->GetValueType()); packet.Write<uint8_t>(this->GetValueType());
packet->Write<uint32_t>(this->value.length()); packet.Write<uint32_t>(this->value.length());
for (uint32_t i = 0; i < this->value.length(); ++i) { for (uint32_t i = 0; i < this->value.length(); ++i) {
packet->Write<uint8_t>(this->value[i]); packet.Write<uint8_t>(this->value[i]);
} }
} }

View File

@ -6,28 +6,14 @@
struct RemoteInputInfo { 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) { 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; 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_RemoteInputX = 0;
float m_RemoteInputY; float m_RemoteInputY = 0;
bool m_IsPowersliding; bool m_IsPowersliding = false;
bool m_IsModified; bool m_IsModified = false;
}; };
struct LocalSpaceInfo { struct LocalSpaceInfo {

View File

@ -34,8 +34,8 @@ constexpr uint32_t lowFrameDelta = FRAMES_TO_MS(lowFramerate);
#define CINSTREAM RakNet::BitStream inStream(packet->data, packet->length, false); #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 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 CMSGHEADER BitStreamUtils::WriteHeader(bitStream, eConnectionType::CLIENT, eClientMessageType::GAME_MSG);
#define SEND_PACKET Game::server->Send(&bitStream, sysAddr, false); #define SEND_PACKET Game::server->Send(bitStream, sysAddr, false);
#define SEND_PACKET_BROADCAST Game::server->Send(&bitStream, UNASSIGNED_SYSTEM_ADDRESS, true); #define SEND_PACKET_BROADCAST Game::server->Send(bitStream, UNASSIGNED_SYSTEM_ADDRESS, true);
//=========== TYPEDEFS ========== //=========== TYPEDEFS ==========

View File

@ -106,7 +106,7 @@ enum class eReplicaComponentType : uint32_t {
INTERACTION_MANAGER, INTERACTION_MANAGER,
DONATION_VENDOR, DONATION_VENDOR,
COMBAT_MEDIATOR, COMBAT_MEDIATOR,
COMMENDATION_VENDOR, ACHIEVEMENT_VENDOR,
GATE_RUSH_CONTROL, GATE_RUSH_CONTROL,
RAIL_ACTIVATOR, RAIL_ACTIVATOR,
ROLLER, ROLLER,

View File

@ -0,0 +1,15 @@
#ifndef __EVENDORTRANSACTIONRESULT__
#define __EVENDORTRANSACTIONRESULT__
#include <cstdint>
enum class eVendorTransactionResult : uint32_t {
SELL_SUCCESS = 0,
SELL_FAIL,
PURCHASE_SUCCESS,
PURCHASE_FAIL,
DONATION_FAIL,
DONATION_FULL
};
#endif // !__EVENDORTRANSACTIONRESULT__

View File

@ -0,0 +1,59 @@
#ifndef __EWAYPOINTCOMMANDTYPES__H__
#define __EWAYPOINTCOMMANDTYPES__H__
#include <cstdint>
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<std::string, eWaypointCommandType> 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__

View File

@ -58,7 +58,7 @@ void CDLootTableTable::LoadValuesFromDatabase() {
CDLootTable entry; CDLootTable entry;
uint32_t lootTableIndex = tableData.getIntField("LootTableIndex", -1); uint32_t lootTableIndex = tableData.getIntField("LootTableIndex", -1);
entries[lootTableIndex].push_back(ReadRow(tableData)); entries[lootTableIndex].emplace_back(ReadRow(tableData));
tableData.nextRow(); tableData.nextRow();
} }
for (auto& [id, table] : entries) { for (auto& [id, table] : entries) {
@ -66,7 +66,7 @@ void CDLootTableTable::LoadValuesFromDatabase() {
} }
} }
const LootTableEntries& CDLootTableTable::GetTable(uint32_t tableId) { const LootTableEntries& CDLootTableTable::GetTable(const uint32_t tableId) {
auto& entries = GetEntriesMutable(); auto& entries = GetEntriesMutable();
auto itr = entries.find(tableId); auto itr = entries.find(tableId);
if (itr != entries.end()) { if (itr != entries.end()) {
@ -79,7 +79,7 @@ const LootTableEntries& CDLootTableTable::GetTable(uint32_t tableId) {
while (!tableData.eof()) { while (!tableData.eof()) {
CDLootTable entry; CDLootTable entry;
entries[tableId].push_back(ReadRow(tableData)); entries[tableId].emplace_back(ReadRow(tableData));
tableData.nextRow(); tableData.nextRow();
} }
SortTable(entries[tableId]); SortTable(entries[tableId]);

View File

@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDLootTable { struct CDLootTable {
uint32_t itemid; //!< The LOT of the item uint32_t itemid; //!< The LOT of the item
uint32_t LootTableIndex; //!< The Loot Table Index uint32_t LootTableIndex; //!< The Loot Table Index
@ -20,6 +22,5 @@ private:
public: public:
void LoadValuesFromDatabase(); void LoadValuesFromDatabase();
// Queries the table with a custom "where" clause // Queries the table with a custom "where" clause
const LootTableEntries& GetTable(uint32_t tableId); const LootTableEntries& GetTable(const uint32_t tableId);
}; };

View File

@ -20,7 +20,7 @@ void CDMissionEmailTable::LoadValuesFromDatabase() {
// Now get the data // Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionEmail"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionEmail");
while (!tableData.eof()) { while (!tableData.eof()) {
CDMissionEmail entry; auto& entry = entries.emplace_back();
entry.ID = tableData.getIntField("ID", -1); entry.ID = tableData.getIntField("ID", -1);
entry.messageType = tableData.getIntField("messageType", -1); entry.messageType = tableData.getIntField("messageType", -1);
entry.notificationGroup = tableData.getIntField("notificationGroup", -1); entry.notificationGroup = tableData.getIntField("notificationGroup", -1);
@ -30,11 +30,8 @@ void CDMissionEmailTable::LoadValuesFromDatabase() {
entry.locStatus = tableData.getIntField("locStatus", -1); entry.locStatus = tableData.getIntField("locStatus", -1);
entry.gate_version = tableData.getStringField("gate_version", ""); entry.gate_version = tableData.getStringField("gate_version", "");
entries.push_back(entry);
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize();
} }
//! Queries the table with a custom "where" clause //! Queries the table with a custom "where" clause

View File

@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDMissionEmail { struct CDMissionEmail {
uint32_t ID; uint32_t ID;
uint32_t messageType; uint32_t messageType;

View File

@ -20,18 +20,15 @@ void CDMissionNPCComponentTable::LoadValuesFromDatabase() {
// Now get the data // Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionNPCComponent"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionNPCComponent");
while (!tableData.eof()) { while (!tableData.eof()) {
CDMissionNPCComponent entry; auto& entry = entries.emplace_back();
entry.id = tableData.getIntField("id", -1); entry.id = tableData.getIntField("id", -1);
entry.missionID = tableData.getIntField("missionID", -1); entry.missionID = tableData.getIntField("missionID", -1);
entry.offersMission = tableData.getIntField("offersMission", -1) == 1 ? true : false; entry.offersMission = tableData.getIntField("offersMission", -1) == 1 ? true : false;
entry.acceptsMission = tableData.getIntField("acceptsMission", -1) == 1 ? true : false; entry.acceptsMission = tableData.getIntField("acceptsMission", -1) == 1 ? true : false;
entry.gate_version = tableData.getStringField("gate_version", ""); entry.gate_version = tableData.getStringField("gate_version", "");
entries.push_back(entry);
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize();
} }
//! Queries the table with a custom "where" clause //! Queries the table with a custom "where" clause

View File

@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDMissionNPCComponent { struct CDMissionNPCComponent {
uint32_t id; //!< The ID uint32_t id; //!< The ID
uint32_t missionID; //!< The Mission ID uint32_t missionID; //!< The Mission ID
@ -17,4 +19,3 @@ public:
// Queries the table with a custom "where" clause // Queries the table with a custom "where" clause
std::vector<CDMissionNPCComponent> Query(std::function<bool(CDMissionNPCComponent)> predicate); std::vector<CDMissionNPCComponent> Query(std::function<bool(CDMissionNPCComponent)> predicate);
}; };

View File

@ -20,7 +20,7 @@ void CDMissionTasksTable::LoadValuesFromDatabase() {
// Now get the data // Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionTasks"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionTasks");
while (!tableData.eof()) { while (!tableData.eof()) {
CDMissionTasks entry; auto& entry = entries.emplace_back();
entry.id = tableData.getIntField("id", -1); entry.id = tableData.getIntField("id", -1);
UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1)); UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1));
entry.taskType = tableData.getIntField("taskType", -1); entry.taskType = tableData.getIntField("taskType", -1);
@ -35,11 +35,8 @@ void CDMissionTasksTable::LoadValuesFromDatabase() {
UNUSED(entry.localize = tableData.getIntField("localize", -1) == 1 ? true : false); UNUSED(entry.localize = tableData.getIntField("localize", -1) == 1 ? true : false);
UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); UNUSED(entry.gate_version = tableData.getStringField("gate_version", ""));
entries.push_back(entry);
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize();
} }
std::vector<CDMissionTasks> CDMissionTasksTable::Query(std::function<bool(CDMissionTasks)> predicate) { std::vector<CDMissionTasks> CDMissionTasksTable::Query(std::function<bool(CDMissionTasks)> predicate) {
@ -51,7 +48,7 @@ std::vector<CDMissionTasks> CDMissionTasksTable::Query(std::function<bool(CDMiss
return data; return data;
} }
std::vector<CDMissionTasks*> CDMissionTasksTable::GetByMissionID(uint32_t missionID) { std::vector<CDMissionTasks*> CDMissionTasksTable::GetByMissionID(const uint32_t missionID) {
std::vector<CDMissionTasks*> tasks; std::vector<CDMissionTasks*> tasks;
// TODO: this should not be linear(?) and also shouldnt need to be a pointer // TODO: this should not be linear(?) and also shouldnt need to be a pointer

View File

@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDMissionTasks { struct CDMissionTasks {
uint32_t id; //!< The Mission ID that the task belongs to uint32_t id; //!< The Mission ID that the task belongs to
UNUSED(uint32_t locStatus); //!< ??? UNUSED(uint32_t locStatus); //!< ???
@ -25,7 +27,7 @@ public:
// Queries the table with a custom "where" clause // Queries the table with a custom "where" clause
std::vector<CDMissionTasks> Query(std::function<bool(CDMissionTasks)> predicate); std::vector<CDMissionTasks> Query(std::function<bool(CDMissionTasks)> predicate);
std::vector<CDMissionTasks*> GetByMissionID(uint32_t missionID); std::vector<CDMissionTasks*> GetByMissionID(const uint32_t missionID);
// TODO: Remove this and replace it with a proper lookup function. // TODO: Remove this and replace it with a proper lookup function.
const CDTable::StorageType& GetEntries() const; const CDTable::StorageType& GetEntries() const;

View File

@ -22,7 +22,7 @@ void CDMissionsTable::LoadValuesFromDatabase() {
// Now get the data // Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Missions"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Missions");
while (!tableData.eof()) { while (!tableData.eof()) {
CDMissions entry; auto& entry = entries.emplace_back();
entry.id = tableData.getIntField("id", -1); entry.id = tableData.getIntField("id", -1);
entry.defined_type = tableData.getStringField("defined_type", ""); entry.defined_type = tableData.getStringField("defined_type", "");
entry.defined_subtype = tableData.getStringField("defined_subtype", ""); entry.defined_subtype = tableData.getStringField("defined_subtype", "");
@ -76,10 +76,8 @@ void CDMissionsTable::LoadValuesFromDatabase() {
UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1)); UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1));
entry.reward_bankinventory = tableData.getIntField("reward_bankinventory", -1); entry.reward_bankinventory = tableData.getIntField("reward_bankinventory", -1);
entries.push_back(entry);
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize(); tableData.finalize();
Default.id = -1; Default.id = -1;
@ -118,3 +116,12 @@ const CDMissions& CDMissionsTable::GetByMissionID(uint32_t missionID, bool& foun
return Default; return Default;
} }
const std::set<int32_t> CDMissionsTable::GetMissionsForReward(LOT lot) {
std::set<int32_t> 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;
}

View File

@ -70,6 +70,8 @@ public:
const CDMissions& GetByMissionID(uint32_t missionID, bool& found) const; const CDMissions& GetByMissionID(uint32_t missionID, bool& found) const;
const std::set<int32_t> GetMissionsForReward(LOT lot);
static CDMissions Default; static CDMissions Default;
}; };

View File

@ -20,7 +20,7 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() {
// Now get the data // Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MovementAIComponent"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MovementAIComponent");
while (!tableData.eof()) { while (!tableData.eof()) {
CDMovementAIComponent entry; auto& entry = entries.emplace_back();
entry.id = tableData.getIntField("id", -1); entry.id = tableData.getIntField("id", -1);
entry.MovementType = tableData.getStringField("MovementType", ""); entry.MovementType = tableData.getStringField("MovementType", "");
entry.WanderChance = tableData.getFloatField("WanderChance", -1.0f); entry.WanderChance = tableData.getFloatField("WanderChance", -1.0f);
@ -30,11 +30,8 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() {
entry.WanderRadius = tableData.getFloatField("WanderRadius", -1.0f); entry.WanderRadius = tableData.getFloatField("WanderRadius", -1.0f);
entry.attachedPath = tableData.getStringField("attachedPath", ""); entry.attachedPath = tableData.getStringField("attachedPath", "");
entries.push_back(entry);
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize();
} }
std::vector<CDMovementAIComponent> CDMovementAIComponentTable::Query(std::function<bool(CDMovementAIComponent)> predicate) { std::vector<CDMovementAIComponent> CDMovementAIComponentTable::Query(std::function<bool(CDMovementAIComponent)> predicate) {

View File

@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDMovementAIComponent { struct CDMovementAIComponent {
uint32_t id; uint32_t id;
std::string MovementType; std::string MovementType;

View File

@ -20,17 +20,14 @@ void CDObjectSkillsTable::LoadValuesFromDatabase() {
// Now get the data // Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ObjectSkills"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ObjectSkills");
while (!tableData.eof()) { while (!tableData.eof()) {
CDObjectSkills entry; auto &entry = entries.emplace_back();
entry.objectTemplate = tableData.getIntField("objectTemplate", -1); entry.objectTemplate = tableData.getIntField("objectTemplate", -1);
entry.skillID = tableData.getIntField("skillID", -1); entry.skillID = tableData.getIntField("skillID", -1);
entry.castOnType = tableData.getIntField("castOnType", -1); entry.castOnType = tableData.getIntField("castOnType", -1);
entry.AICombatWeight = tableData.getIntField("AICombatWeight", -1); entry.AICombatWeight = tableData.getIntField("AICombatWeight", -1);
entries.push_back(entry);
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize();
} }
std::vector<CDObjectSkills> CDObjectSkillsTable::Query(std::function<bool(CDObjectSkills)> predicate) { std::vector<CDObjectSkills> CDObjectSkillsTable::Query(std::function<bool(CDObjectSkills)> predicate) {

View File

@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDObjectSkills { struct CDObjectSkills {
uint32_t objectTemplate; //!< The LOT of the item uint32_t objectTemplate; //!< The LOT of the item
uint32_t skillID; //!< The Skill ID of the object uint32_t skillID; //!< The Skill ID of the object

View File

@ -1,7 +1,7 @@
#include "CDObjectsTable.h" #include "CDObjectsTable.h"
namespace { namespace {
CDObjects m_default; CDObjects ObjDefault;
}; };
void CDObjectsTable::LoadValuesFromDatabase() { void CDObjectsTable::LoadValuesFromDatabase() {
@ -20,8 +20,10 @@ void CDObjectsTable::LoadValuesFromDatabase() {
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Objects"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Objects");
auto& entries = GetEntriesMutable(); auto& entries = GetEntriesMutable();
while (!tableData.eof()) { while (!tableData.eof()) {
CDObjects entry; const uint32_t lot = tableData.getIntField("id", 0);
entry.id = tableData.getIntField("id", -1);
auto& entry = entries[lot];
entry.id = lot;
entry.name = tableData.getStringField("name", ""); entry.name = tableData.getStringField("name", "");
UNUSED_COLUMN(entry.placeable = tableData.getIntField("placeable", -1);) UNUSED_COLUMN(entry.placeable = tableData.getIntField("placeable", -1);)
entry.type = tableData.getStringField("type", ""); entry.type = tableData.getStringField("type", "");
@ -36,35 +38,34 @@ void CDObjectsTable::LoadValuesFromDatabase() {
UNUSED_COLUMN(entry.gate_version = tableData.getStringField("gate_version", "");) UNUSED_COLUMN(entry.gate_version = tableData.getStringField("gate_version", "");)
UNUSED_COLUMN(entry.HQ_valid = tableData.getIntField("HQ_valid", -1);) UNUSED_COLUMN(entry.HQ_valid = tableData.getIntField("HQ_valid", -1);)
entries.insert(std::make_pair(entry.id, entry));
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize(); ObjDefault.id = 0;
m_default.id = 0;
} }
const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) { const CDObjects& CDObjectsTable::GetByID(const uint32_t lot) {
auto& entries = GetEntriesMutable(); auto& entries = GetEntriesMutable();
const auto& it = entries.find(LOT); const auto& it = entries.find(lot);
if (it != entries.end()) { if (it != entries.end()) {
return it->second; return it->second;
} }
auto query = CDClientDatabase::CreatePreppedStmt("SELECT * FROM Objects WHERE id = ?;"); auto query = CDClientDatabase::CreatePreppedStmt("SELECT * FROM Objects WHERE id = ?;");
query.bind(1, static_cast<int32_t>(LOT)); query.bind(1, static_cast<int32_t>(lot));
auto tableData = query.execQuery(); auto tableData = query.execQuery();
if (tableData.eof()) { if (tableData.eof()) {
entries.insert(std::make_pair(LOT, m_default)); entries.emplace(lot, ObjDefault);
return m_default; return ObjDefault;
} }
// Now get the data // Now get the data
while (!tableData.eof()) { while (!tableData.eof()) {
CDObjects entry; const uint32_t lot = tableData.getIntField("id", 0);
entry.id = tableData.getIntField("id", -1);
auto& entry = entries[lot];
entry.id = lot;
entry.name = tableData.getStringField("name", ""); entry.name = tableData.getStringField("name", "");
UNUSED(entry.placeable = tableData.getIntField("placeable", -1)); UNUSED(entry.placeable = tableData.getIntField("placeable", -1));
entry.type = tableData.getStringField("type", ""); entry.type = tableData.getStringField("type", "");
@ -79,17 +80,15 @@ const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) {
UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); UNUSED(entry.gate_version = tableData.getStringField("gate_version", ""));
UNUSED(entry.HQ_valid = tableData.getIntField("HQ_valid", -1)); UNUSED(entry.HQ_valid = tableData.getIntField("HQ_valid", -1));
entries.insert(std::make_pair(entry.id, entry));
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize(); tableData.finalize();
const auto& it2 = entries.find(LOT); const auto& it2 = entries.find(lot);
if (it2 != entries.end()) { if (it2 != entries.end()) {
return it2->second; return it2->second;
} }
return m_default; return ObjDefault;
} }

View File

@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDObjects { struct CDObjects {
uint32_t id; //!< The LOT of the object uint32_t id; //!< The LOT of the object
std::string name; //!< The internal name of the object std::string name; //!< The internal name of the object
@ -24,6 +26,6 @@ class CDObjectsTable : public CDTable<CDObjectsTable, std::map<uint32_t, CDObjec
public: public:
void LoadValuesFromDatabase(); void LoadValuesFromDatabase();
// Gets an entry by ID // Gets an entry by ID
const CDObjects& GetByID(uint32_t LOT); const CDObjects& GetByID(const uint32_t lot);
}; };

View File

@ -19,12 +19,11 @@ void CDPackageComponentTable::LoadValuesFromDatabase() {
// Now get the data // Now get the data
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PackageComponent"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PackageComponent");
while (!tableData.eof()) { while (!tableData.eof()) {
CDPackageComponent entry; auto& entry = entries.emplace_back();
entry.id = tableData.getIntField("id", -1); entry.id = tableData.getIntField("id", -1);
entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1);
entry.packageType = tableData.getIntField("packageType", -1); entry.packageType = tableData.getIntField("packageType", -1);
entries.push_back(entry);
tableData.nextRow(); tableData.nextRow();
} }

View File

@ -3,6 +3,8 @@
// Custom Classes // Custom Classes
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
struct CDPackageComponent { struct CDPackageComponent {
uint32_t id; uint32_t id;
uint32_t LootMatrixIndex; uint32_t LootMatrixIndex;

View File

@ -4,32 +4,31 @@ void CDPhysicsComponentTable::LoadValuesFromDatabase() {
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PhysicsComponent"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PhysicsComponent");
auto& entries = GetEntriesMutable(); auto& entries = GetEntriesMutable();
while (!tableData.eof()) { while (!tableData.eof()) {
CDPhysicsComponent entry; const uint32_t componentID = tableData.getIntField("id", -1);
entry.id = tableData.getIntField("id", -1);
auto& entry = entries[componentID];
entry.id = componentID;
entry.bStatic = tableData.getIntField("static", -1) != 0; entry.bStatic = tableData.getIntField("static", -1) != 0;
entry.physicsAsset = tableData.getStringField("physics_asset", ""); entry.physicsAsset = tableData.getStringField("physics_asset", "");
UNUSED(entry->jump = tableData.getIntField("jump", -1) != 0); UNUSED_COLUMN(entry.jump = tableData.getIntField("jump", -1) != 0;)
UNUSED(entry->doublejump = tableData.getIntField("doublejump", -1) != 0); UNUSED_COLUMN(entry.doubleJump = tableData.getIntField("doublejump", -1) != 0;)
entry.speed = tableData.getFloatField("speed", -1); entry.speed = static_cast<float>(tableData.getFloatField("speed", -1));
UNUSED(entry->rotSpeed = tableData.getFloatField("rotSpeed", -1)); UNUSED_COLUMN(entry.rotSpeed = tableData.getFloatField("rotSpeed", -1);)
entry.playerHeight = tableData.getFloatField("playerHeight"); entry.playerHeight = static_cast<float>(tableData.getFloatField("playerHeight"));
entry.playerRadius = tableData.getFloatField("playerRadius"); entry.playerRadius = static_cast<float>(tableData.getFloatField("playerRadius"));
entry.pcShapeType = tableData.getIntField("pcShapeType"); entry.pcShapeType = tableData.getIntField("pcShapeType");
entry.collisionGroup = tableData.getIntField("collisionGroup"); entry.collisionGroup = tableData.getIntField("collisionGroup");
UNUSED(entry->airSpeed = tableData.getFloatField("airSpeed")); UNUSED_COLUMN(entry.airSpeed = tableData.getFloatField("airSpeed");)
UNUSED(entry->boundaryAsset = tableData.getStringField("boundaryAsset")); UNUSED_COLUMN(entry.boundaryAsset = tableData.getStringField("boundaryAsset");)
UNUSED(entry->jumpAirSpeed = tableData.getFloatField("jumpAirSpeed")); UNUSED_COLUMN(entry.jumpAirSpeed = tableData.getFloatField("jumpAirSpeed");)
UNUSED(entry->friction = tableData.getFloatField("friction")); UNUSED_COLUMN(entry.friction = tableData.getFloatField("friction");)
UNUSED(entry->gravityVolumeAsset = tableData.getStringField("gravityVolumeAsset")); UNUSED_COLUMN(entry.gravityVolumeAsset = tableData.getStringField("gravityVolumeAsset");)
entries.insert(std::make_pair(entry.id, entry));
tableData.nextRow(); tableData.nextRow();
} }
tableData.finalize();
} }
CDPhysicsComponent* CDPhysicsComponentTable::GetByID(uint32_t componentID) { CDPhysicsComponent* CDPhysicsComponentTable::GetByID(const uint32_t componentID) {
auto& entries = GetEntriesMutable(); auto& entries = GetEntriesMutable();
auto itr = entries.find(componentID); auto itr = entries.find(componentID);
return itr != entries.end() ? &itr->second : nullptr; return itr != entries.end() ? &itr->second : nullptr;

View File

@ -1,5 +1,6 @@
#pragma once #pragma once
#include "CDTable.h" #include "CDTable.h"
#include <cstdint>
#include <string> #include <string>
struct CDPhysicsComponent { struct CDPhysicsComponent {
@ -7,7 +8,7 @@ struct CDPhysicsComponent {
bool bStatic; bool bStatic;
std::string physicsAsset; std::string physicsAsset;
UNUSED(bool jump); UNUSED(bool jump);
UNUSED(bool doublejump); UNUSED(bool doubleJump);
float speed; float speed;
UNUSED(float rotSpeed); UNUSED(float rotSpeed);
float playerHeight; float playerHeight;
@ -26,5 +27,5 @@ public:
void LoadValuesFromDatabase(); void LoadValuesFromDatabase();
static const std::string GetTableName() { return "PhysicsComponent"; }; static const std::string GetTableName() { return "PhysicsComponent"; };
CDPhysicsComponent* GetByID(uint32_t componentID); CDPhysicsComponent* GetByID(const uint32_t componentID);
}; };

View File

@ -9,4 +9,28 @@ foreach(file ${DDATABASE_CDCLIENTDATABASE_CDCLIENTTABLES_SOURCES})
set(DDATABASE_CDCLIENTDATABASE_SOURCES ${DDATABASE_CDCLIENTDATABASE_SOURCES} "CDClientTables/${file}") set(DDATABASE_CDCLIENTDATABASE_SOURCES ${DDATABASE_CDCLIENTDATABASE_SOURCES} "CDClientTables/${file}")
endforeach() 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 <string>.
target_precompile_headers(
dDatabaseCDClient PRIVATE
"$<$<COMPILE_LANGUAGE:CXX>:${HEADERS_DDATABASE_CDCLIENT}>"
)

View File

@ -1,20 +1,7 @@
set(DDATABASE_SOURCES)
add_subdirectory(CDClientDatabase) add_subdirectory(CDClientDatabase)
foreach(file ${DDATABASE_CDCLIENTDATABASE_SOURCES})
set(DDATABASE_SOURCES ${DDATABASE_SOURCES} "CDClientDatabase/${file}")
endforeach()
add_subdirectory(GameDatabase) add_subdirectory(GameDatabase)
foreach(file ${DDATABASE_GAMEDATABASE_SOURCES}) add_library(dDatabase STATIC "MigrationRunner.cpp")
set(DDATABASE_SOURCES ${DDATABASE_SOURCES} "GameDatabase/${file}") target_include_directories(dDatabase PUBLIC ".")
endforeach() target_link_libraries(dDatabase
PUBLIC dDatabaseCDClient dDatabaseGame)
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()

View File

@ -1,6 +1,5 @@
set(DDATABASE_GAMEDATABASE_SOURCES set(DDATABASE_GAMEDATABASE_SOURCES
"Database.cpp" "Database.cpp"
"MigrationRunner.cpp"
) )
add_subdirectory(MySQL) add_subdirectory(MySQL)
@ -9,4 +8,25 @@ foreach(file ${DDATABSE_DATABSES_MYSQL_SOURCES})
set(DDATABASE_GAMEDATABASE_SOURCES ${DDATABASE_GAMEDATABASE_SOURCES} "MySQL/${file}") set(DDATABASE_GAMEDATABASE_SOURCES ${DDATABASE_GAMEDATABASE_SOURCES} "MySQL/${file}")
endforeach() 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 <string>.
target_precompile_headers(
dDatabaseGame PRIVATE
"$<$<COMPILE_LANGUAGE:CXX>:${HEADERS_DDATABASE_GAME}>"
)

View File

@ -3,6 +3,7 @@
#include <cstdint> #include <cstdint>
#include <optional> #include <optional>
#include <string>
#include <string_view> #include <string_view>
enum class eGameMasterLevel : uint8_t; enum class eGameMasterLevel : uint8_t;

View File

@ -13,11 +13,25 @@ include_directories(
${PROJECT_SOURCE_DIR}/dGame ${PROJECT_SOURCE_DIR}/dGame
) )
add_library(dGameBase ${DGAME_SOURCES}) add_library(dGameBase OBJECT ${DGAME_SOURCES})
target_precompile_headers(dGameBase PRIVATE ${HEADERS_DGAME}) target_precompile_headers(dGameBase PRIVATE ${HEADERS_DGAME})
target_link_libraries(dGameBase target_include_directories(dGameBase PUBLIC "." "dEntity"
PUBLIC dDatabase dPhysics PRIVATE "dComponents" "dGameMessages" "dBehaviors" "dMission" "dUtilities" "dInventory"
INTERFACE dComponents dEntity) $<TARGET_PROPERTY:dPropertyBehaviors,INTERFACE_INCLUDE_DIRECTORIES>
"${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(dBehaviors)
add_subdirectory(dComponents) add_subdirectory(dComponents)
@ -28,7 +42,26 @@ add_subdirectory(dMission)
add_subdirectory(dPropertyBehaviors) add_subdirectory(dPropertyBehaviors)
add_subdirectory(dUtilities) add_subdirectory(dUtilities)
add_library(dGame INTERFACE) add_library(dGame STATIC
target_link_libraries(dGame INTERFACE $<TARGET_OBJECTS:dGameBase>
dGameBase dBehaviors dComponents dEntity dGameMessages dInventory dMission dPropertyBehaviors dUtilities dScripts $<TARGET_OBJECTS:dBehaviors>
$<TARGET_OBJECTS:dComponents>
$<TARGET_OBJECTS:dEntity>
$<TARGET_OBJECTS:dGameMessages>
$<TARGET_OBJECTS:dInventory>
$<TARGET_OBJECTS:dMission>
$<TARGET_OBJECTS:dPropertyBehaviors>
$<TARGET_OBJECTS:dUtilities>
)
target_link_libraries(dGame INTERFACE dNet)
target_include_directories(dGame INTERFACE
$<TARGET_PROPERTY:dGameBase,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dBehaviors,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dComponents,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dEntity,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dGameMessages,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dInventory,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dMission,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dPropertyBehaviors,INTERFACE_INCLUDE_DIRECTORIES>
$<TARGET_PROPERTY:dUtilities,INTERFACE_INCLUDE_DIRECTORIES>
) )

View File

@ -82,6 +82,7 @@
#include "CollectibleComponent.h" #include "CollectibleComponent.h"
#include "ItemComponent.h" #include "ItemComponent.h"
#include "GhostComponent.h" #include "GhostComponent.h"
#include "AchievementVendorComponent.h"
// Table includes // Table includes
#include "CDComponentsRegistryTable.h" #include "CDComponentsRegistryTable.h"
@ -145,17 +146,15 @@ Entity::~Entity() {
return; return;
} }
Entity* zoneControl = Game::entityManager->GetZoneControlEntity(); auto* zoneControl = Game::entityManager->GetZoneControlEntity();
for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { if (zoneControl) {
script->OnPlayerExit(zoneControl, this); zoneControl->GetScript()->OnPlayerExit(zoneControl, this);
} }
std::vector<Entity*> scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); std::vector<Entity*> scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY);
for (Entity* scriptEntity : scriptedActs) { for (Entity* scriptEntity : scriptedActs) {
if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds
for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { scriptEntity->GetScript()->OnPlayerExit(scriptEntity, this);
script->OnPlayerExit(scriptEntity, this);
}
} }
} }
} }
@ -615,6 +614,8 @@ void Entity::Initialize() {
AddComponent<VendorComponent>(); AddComponent<VendorComponent>();
} else if ((compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::DONATION_VENDOR, -1) != -1)) { } else if ((compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::DONATION_VENDOR, -1) != -1)) {
AddComponent<DonationVendorComponent>(); AddComponent<DonationVendorComponent>();
} else if ((compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::ACHIEVEMENT_VENDOR, -1) != -1)) {
AddComponent<AchievementVendorComponent>();
} }
if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROPERTY_VENDOR, -1) != -1) { if (compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROPERTY_VENDOR, -1) != -1) {
@ -730,15 +731,21 @@ void Entity::Initialize() {
// if we have a moving platform path, then we need a moving platform component // if we have a moving platform path, then we need a moving platform component
if (path->pathType == PathType::MovingPlatform) { if (path->pathType == PathType::MovingPlatform) {
AddComponent<MovingPlatformComponent>(pathName); AddComponent<MovingPlatformComponent>(pathName);
// else if we are a movement path } else if (path->pathType == PathType::Movement) {
} /*else if (path->pathType == PathType::Movement) { auto movementAIcomponent = GetComponent<MovementAIComponent>();
auto movementAIcomp = GetComponent<MovementAIComponent>(); if (movementAIcomponent && combatAiId == 0) {
if (movementAIcomp){ movementAIcomponent->SetPath(pathName);
// TODO: set path in existing movementAIComp
} else { } else {
// TODO: create movementAIcomp and set path MovementAIInfo moveInfo = MovementAIInfo();
moveInfo.movementType = "";
moveInfo.wanderChance = 0;
moveInfo.wanderRadius = 16;
moveInfo.wanderSpeed = 2.5f;
moveInfo.wanderDelayMax = 5;
moveInfo.wanderDelayMin = 2;
AddComponent<MovementAIComponent>(moveInfo);
} }
}*/ }
} else { } else {
// else we still need to setup moving platform if it has a moving platform comp but no path // else we still need to setup moving platform if it has a moving platform comp but no path
int32_t movingPlatformComponentId = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::MOVING_PLATFORM, -1); int32_t movingPlatformComponentId = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::MOVING_PLATFORM, -1);
@ -759,9 +766,7 @@ void Entity::Initialize() {
// Hacky way to trigger these when the object has had a chance to get constructed // Hacky way to trigger these when the object has had a chance to get constructed
AddCallbackTimer(0, [this]() { AddCallbackTimer(0, [this]() {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { this->GetScript()->OnStartup(this);
script->OnStartup(this);
}
}); });
if (!m_Character && Game::entityManager->GetGhostingEnabled()) { if (!m_Character && Game::entityManager->GetGhostingEnabled()) {
@ -836,17 +841,6 @@ bool Entity::HasComponent(const eReplicaComponentType componentId) const {
return m_Components.find(componentId) != m_Components.end(); return m_Components.find(componentId) != m_Components.end();
} }
std::vector<ScriptComponent*> Entity::GetScriptComponents() {
std::vector<ScriptComponent*> comps;
for (std::pair<eReplicaComponentType, void*> p : m_Components) {
if (p.first == eReplicaComponentType::SCRIPT) {
comps.push_back(static_cast<ScriptComponent*>(p.second));
}
}
return comps;
}
void Entity::Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName) { void Entity::Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName) {
if (notificationName == "HitOrHealResult" || notificationName == "Hit") { if (notificationName == "HitOrHealResult" || notificationName == "Hit") {
auto* destroyableComponent = GetComponent<DestroyableComponent>(); auto* destroyableComponent = GetComponent<DestroyableComponent>();
@ -896,34 +890,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) { if (packetType == eReplicaPacketType::CONSTRUCTION) {
outBitStream->Write(m_ObjectID); outBitStream.Write(m_ObjectID);
outBitStream->Write(m_TemplateID); outBitStream.Write(m_TemplateID);
if (IsPlayer()) { if (IsPlayer()) {
std::string name = m_Character != nullptr ? m_Character->GetName() : "Invalid"; std::string name = m_Character != nullptr ? m_Character->GetName() : "Invalid";
outBitStream->Write<uint8_t>(uint8_t(name.size())); outBitStream.Write<uint8_t>(uint8_t(name.size()));
for (size_t i = 0; i < name.size(); ++i) { for (size_t i = 0; i < name.size(); ++i) {
outBitStream->Write<uint16_t>(name[i]); outBitStream.Write<uint16_t>(name[i]);
} }
} else { } else {
const auto& name = GetVar<std::string>(u"npcName"); const auto& name = GetVar<std::string>(u"npcName");
outBitStream->Write<uint8_t>(uint8_t(name.size())); outBitStream.Write<uint8_t>(uint8_t(name.size()));
for (size_t i = 0; i < name.size(); ++i) { for (size_t i = 0; i < name.size(); ++i) {
outBitStream->Write<uint16_t>(name[i]); outBitStream.Write<uint16_t>(name[i]);
} }
} }
outBitStream->Write<uint32_t>(0); //Time since created on server outBitStream.Write<uint32_t>(0); //Time since created on server
const auto& syncLDF = GetVar<std::vector<std::u16string>>(u"syncLDF"); const auto& syncLDF = GetVar<std::vector<std::u16string>>(u"syncLDF");
// Only sync for models. // Only sync for models.
if (m_Settings.size() > 0 && (GetComponent<ModelComponent>() && !GetComponent<PetComponent>())) { if (m_Settings.size() > 0 && (GetComponent<ModelComponent>() && !GetComponent<PetComponent>())) {
outBitStream->Write1(); //ldf data outBitStream.Write1(); //ldf data
RakNet::BitStream settingStream; RakNet::BitStream settingStream;
int32_t numberOfValidKeys = m_Settings.size(); int32_t numberOfValidKeys = m_Settings.size();
@ -940,13 +934,13 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke
for (LDFBaseData* data : m_Settings) { for (LDFBaseData* data : m_Settings) {
if (data && data->GetValueType() != eLDFType::LDF_TYPE_UNKNOWN) { if (data && data->GetValueType() != eLDFType::LDF_TYPE_UNKNOWN) {
data->WriteToPacket(&settingStream); data->WriteToPacket(settingStream);
} }
} }
outBitStream->Write(settingStream.GetNumberOfBytesUsed() + 1); outBitStream.Write(settingStream.GetNumberOfBytesUsed() + 1);
outBitStream->Write<uint8_t>(0); //no compression used outBitStream.Write<uint8_t>(0); //no compression used
outBitStream->Write(settingStream); outBitStream.Write(settingStream);
} else if (!syncLDF.empty()) { } else if (!syncLDF.empty()) {
std::vector<LDFBaseData*> ldfData; std::vector<LDFBaseData*> ldfData;
@ -954,79 +948,79 @@ void Entity::WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacke
ldfData.push_back(GetVarData(data)); ldfData.push_back(GetVarData(data));
} }
outBitStream->Write1(); //ldf data outBitStream.Write1(); //ldf data
RakNet::BitStream settingStream; RakNet::BitStream settingStream;
settingStream.Write<uint32_t>(ldfData.size()); settingStream.Write<uint32_t>(ldfData.size());
for (LDFBaseData* data : ldfData) { for (LDFBaseData* data : ldfData) {
if (data) { if (data) {
data->WriteToPacket(&settingStream); data->WriteToPacket(settingStream);
} }
} }
outBitStream->Write(settingStream.GetNumberOfBytesUsed() + 1); outBitStream.Write(settingStream.GetNumberOfBytesUsed() + 1);
outBitStream->Write<uint8_t>(0); //no compression used outBitStream.Write<uint8_t>(0); //no compression used
outBitStream->Write(settingStream); outBitStream.Write(settingStream);
} else { } else {
outBitStream->Write0(); //No ldf data outBitStream.Write0(); //No ldf data
} }
TriggerComponent* triggerComponent; TriggerComponent* triggerComponent;
if (TryGetComponent(eReplicaComponentType::TRIGGER, triggerComponent)) { if (TryGetComponent(eReplicaComponentType::TRIGGER, triggerComponent)) {
// has trigger component, check to see if we have events to handle // has trigger component, check to see if we have events to handle
auto* trigger = triggerComponent->GetTrigger(); auto* trigger = triggerComponent->GetTrigger();
outBitStream->Write<bool>(trigger && trigger->events.size() > 0); outBitStream.Write<bool>(trigger && trigger->events.size() > 0);
} else { // no trigger componenet, so definitely no triggers } else { // no trigger componenet, so definitely no triggers
outBitStream->Write0(); outBitStream.Write0();
} }
if (m_ParentEntity != nullptr || m_SpawnerID != 0) { if (m_ParentEntity != nullptr || m_SpawnerID != 0) {
outBitStream->Write1(); outBitStream.Write1();
if (m_ParentEntity != nullptr) outBitStream->Write(GeneralUtils::SetBit(m_ParentEntity->GetObjectID(), static_cast<uint32_t>(eObjectBits::CLIENT))); if (m_ParentEntity != nullptr) outBitStream.Write(GeneralUtils::SetBit(m_ParentEntity->GetObjectID(), static_cast<uint32_t>(eObjectBits::CLIENT)));
else if (m_Spawner != nullptr && m_Spawner->m_Info.isNetwork) outBitStream->Write(m_SpawnerID); else if (m_Spawner != nullptr && m_Spawner->m_Info.isNetwork) outBitStream.Write(m_SpawnerID);
else outBitStream->Write(GeneralUtils::SetBit(m_SpawnerID, static_cast<uint32_t>(eObjectBits::CLIENT))); else outBitStream.Write(GeneralUtils::SetBit(m_SpawnerID, static_cast<uint32_t>(eObjectBits::CLIENT)));
} else outBitStream->Write0(); } else outBitStream.Write0();
outBitStream->Write(m_HasSpawnerNodeID); outBitStream.Write(m_HasSpawnerNodeID);
if (m_HasSpawnerNodeID) outBitStream->Write(m_SpawnerNodeID); 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 { else {
outBitStream->Write1(); outBitStream.Write1();
outBitStream->Write(m_Scale); outBitStream.Write(m_Scale);
} }
outBitStream->Write0(); //ObjectWorldState outBitStream.Write0(); //ObjectWorldState
if (m_GMLevel != eGameMasterLevel::CIVILIAN) { if (m_GMLevel != eGameMasterLevel::CIVILIAN) {
outBitStream->Write1(); outBitStream.Write1();
outBitStream->Write(m_GMLevel); outBitStream.Write(m_GMLevel);
} else outBitStream->Write0(); //No GM Level } 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. // 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) { if (m_IsParentChildDirty || packetType == eReplicaPacketType::CONSTRUCTION) {
m_IsParentChildDirty = false; m_IsParentChildDirty = false;
outBitStream->Write(m_ParentEntity != nullptr); outBitStream.Write(m_ParentEntity != nullptr);
if (m_ParentEntity) { if (m_ParentEntity) {
outBitStream->Write(m_ParentEntity->GetObjectID()); outBitStream.Write(m_ParentEntity->GetObjectID());
outBitStream->Write0(); outBitStream.Write0();
} }
outBitStream->Write(m_ChildEntities.size() > 0); outBitStream.Write(m_ChildEntities.size() > 0);
if (m_ChildEntities.size() > 0) { if (m_ChildEntities.size() > 0) {
outBitStream->Write<uint16_t>(m_ChildEntities.size()); outBitStream.Write<uint16_t>(m_ChildEntities.size());
for (Entity* child : m_ChildEntities) { for (Entity* child : m_ChildEntities) {
outBitStream->Write<uint64_t>(child->GetObjectID()); outBitStream.Write<uint64_t>(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. * This has to be done in a specific order.
@ -1114,7 +1108,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType
possessorComponent->Serialize(outBitStream, bIsInitialUpdate); possessorComponent->Serialize(outBitStream, bIsInitialUpdate);
} else { } else {
// Should never happen, but just to be safe // Should never happen, but just to be safe
outBitStream->Write0(); outBitStream.Write0();
} }
LevelProgressionComponent* levelProgressionComponent; LevelProgressionComponent* levelProgressionComponent;
@ -1122,7 +1116,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType
levelProgressionComponent->Serialize(outBitStream, bIsInitialUpdate); levelProgressionComponent->Serialize(outBitStream, bIsInitialUpdate);
} else { } else {
// Should never happen, but just to be safe // Should never happen, but just to be safe
outBitStream->Write0(); outBitStream.Write0();
} }
PlayerForcedMovementComponent* playerForcedMovementComponent; PlayerForcedMovementComponent* playerForcedMovementComponent;
@ -1130,7 +1124,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType
playerForcedMovementComponent->Serialize(outBitStream, bIsInitialUpdate); playerForcedMovementComponent->Serialize(outBitStream, bIsInitialUpdate);
} else { } else {
// Should never happen, but just to be safe // Should never happen, but just to be safe
outBitStream->Write0(); outBitStream.Write0();
} }
characterComponent->Serialize(outBitStream, bIsInitialUpdate); characterComponent->Serialize(outBitStream, bIsInitialUpdate);
@ -1191,6 +1185,11 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType
donationVendorComponent->Serialize(outBitStream, bIsInitialUpdate); donationVendorComponent->Serialize(outBitStream, bIsInitialUpdate);
} }
AchievementVendorComponent* achievementVendorComponent;
if (TryGetComponent(eReplicaComponentType::ACHIEVEMENT_VENDOR, achievementVendorComponent)) {
achievementVendorComponent->Serialize(outBitStream, bIsInitialUpdate);
}
BouncerComponent* bouncerComponent; BouncerComponent* bouncerComponent;
if (TryGetComponent(eReplicaComponentType::BOUNCER, bouncerComponent)) { if (TryGetComponent(eReplicaComponentType::BOUNCER, bouncerComponent)) {
bouncerComponent->Serialize(outBitStream, bIsInitialUpdate); bouncerComponent->Serialize(outBitStream, bIsInitialUpdate);
@ -1242,7 +1241,7 @@ void Entity::WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType
// BBB Component, unused currently // BBB Component, unused currently
// Need to to write0 so that is serialized correctly // Need to to write0 so that is serialized correctly
// TODO: Implement BBB Component // TODO: Implement BBB Component
outBitStream->Write0(); outBitStream.Write0();
} }
void Entity::UpdateXMLDoc(tinyxml2::XMLDocument* doc) { void Entity::UpdateXMLDoc(tinyxml2::XMLDocument* doc) {
@ -1270,9 +1269,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 // 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(); auto timerName = timer.GetName();
m_Timers.erase(m_Timers.begin() + timerPosition); m_Timers.erase(m_Timers.begin() + timerPosition);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnTimerDone(this, timerName);
script->OnTimerDone(this, timerName);
}
TriggerEvent(eTriggerEventType::TIMER_DONE, this); TriggerEvent(eTriggerEventType::TIMER_DONE, this);
} else { } else {
@ -1318,9 +1315,7 @@ void Entity::Update(const float deltaTime) {
Wake(); Wake();
} }
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnUpdate(this);
script->OnUpdate(this);
}
for (const auto& pair : m_Components) { for (const auto& pair : m_Components) {
if (pair.second == nullptr) continue; if (pair.second == nullptr) continue;
@ -1337,9 +1332,7 @@ void Entity::OnCollisionProximity(LWOOBJID otherEntity, const std::string& proxN
Entity* other = Game::entityManager->GetEntity(otherEntity); Entity* other = Game::entityManager->GetEntity(otherEntity);
if (!other) return; if (!other) return;
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnProximityUpdate(this, other, proxName, status);
script->OnProximityUpdate(this, other, proxName, status);
}
RocketLaunchpadControlComponent* rocketComp = GetComponent<RocketLaunchpadControlComponent>(); RocketLaunchpadControlComponent* rocketComp = GetComponent<RocketLaunchpadControlComponent>();
if (!rocketComp) return; if (!rocketComp) return;
@ -1351,9 +1344,7 @@ void Entity::OnCollisionPhantom(const LWOOBJID otherEntity) {
auto* other = Game::entityManager->GetEntity(otherEntity); auto* other = Game::entityManager->GetEntity(otherEntity);
if (!other) return; if (!other) return;
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnCollisionPhantom(this, other);
script->OnCollisionPhantom(this, other);
}
for (const auto& callback : m_PhantomCollisionCallbacks) { for (const auto& callback : m_PhantomCollisionCallbacks) {
callback(other); callback(other);
@ -1392,9 +1383,7 @@ void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) {
auto* other = Game::entityManager->GetEntity(otherEntity); auto* other = Game::entityManager->GetEntity(otherEntity);
if (!other) return; if (!other) return;
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnOffCollisionPhantom(this, other);
script->OnOffCollisionPhantom(this, other);
}
TriggerEvent(eTriggerEventType::EXIT, other); TriggerEvent(eTriggerEventType::EXIT, other);
@ -1411,46 +1400,32 @@ void Entity::OnCollisionLeavePhantom(const LWOOBJID otherEntity) {
} }
void Entity::OnFireEventServerSide(Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) { void Entity::OnFireEventServerSide(Entity* sender, std::string args, int32_t param1, int32_t param2, int32_t param3) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnFireEventServerSide(this, sender, args, param1, param2, param3);
script->OnFireEventServerSide(this, sender, args, param1, param2, param3);
}
} }
void Entity::OnActivityStateChangeRequest(LWOOBJID senderID, int32_t value1, int32_t value2, const std::u16string& stringValue) { void Entity::OnActivityStateChangeRequest(LWOOBJID senderID, int32_t value1, int32_t value2, const std::u16string& stringValue) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnActivityStateChangeRequest(this, senderID, value1, value2, stringValue);
script->OnActivityStateChangeRequest(this, senderID, value1, value2, stringValue);
}
} }
void Entity::OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName, void Entity::OnCinematicUpdate(Entity* self, Entity* sender, eCinematicEvent event, const std::u16string& pathName,
float_t pathTime, float_t totalTime, int32_t waypoint) { float_t pathTime, float_t totalTime, int32_t waypoint) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnCinematicUpdate(self, sender, event, pathName, pathTime, totalTime, waypoint);
script->OnCinematicUpdate(self, sender, event, pathName, pathTime, totalTime, waypoint);
}
} }
void Entity::NotifyObject(Entity* sender, const std::string& name, int32_t param1, int32_t param2) { 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); GameMessages::SendNotifyObject(GetObjectID(), sender->GetObjectID(), GeneralUtils::ASCIIToUTF16(name), UNASSIGNED_SYSTEM_ADDRESS);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnNotifyObject(this, sender, name, param1, param2);
script->OnNotifyObject(this, sender, name, param1, param2);
}
} }
void Entity::OnEmoteReceived(const int32_t emote, Entity* target) { void Entity::OnEmoteReceived(const int32_t emote, Entity* target) {
for (auto* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnEmoteReceived(this, emote, target);
script->OnEmoteReceived(this, emote, target);
}
} }
void Entity::OnUse(Entity* originator) { void Entity::OnUse(Entity* originator) {
TriggerEvent(eTriggerEventType::INTERACT, originator); TriggerEvent(eTriggerEventType::INTERACT, originator);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnUse(this, originator);
script->OnUse(this, originator);
}
// component base class when
for (const auto& pair : m_Components) { for (const auto& pair : m_Components) {
if (pair.second == nullptr) continue; if (pair.second == nullptr) continue;
@ -1460,82 +1435,63 @@ void Entity::OnUse(Entity* originator) {
} }
void Entity::OnHitOrHealResult(Entity* attacker, int32_t damage) { void Entity::OnHitOrHealResult(Entity* attacker, int32_t damage) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnHitOrHealResult(this, attacker, damage);
script->OnHitOrHealResult(this, attacker, damage);
}
} }
void Entity::OnHit(Entity* attacker) { void Entity::OnHit(Entity* attacker) {
TriggerEvent(eTriggerEventType::HIT, attacker); TriggerEvent(eTriggerEventType::HIT, attacker);
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnHit(this, attacker);
script->OnHit(this, attacker);
}
} }
void Entity::OnZonePropertyEditBegin() { void Entity::OnZonePropertyEditBegin() {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyEditBegin(this);
script->OnZonePropertyEditBegin(this);
}
} }
void Entity::OnZonePropertyEditEnd() { void Entity::OnZonePropertyEditEnd() {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyEditEnd(this);
script->OnZonePropertyEditEnd(this);
}
} }
void Entity::OnZonePropertyModelEquipped() { void Entity::OnZonePropertyModelEquipped() {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyModelEquipped(this);
script->OnZonePropertyModelEquipped(this);
}
} }
void Entity::OnZonePropertyModelPlaced(Entity* player) { void Entity::OnZonePropertyModelPlaced(Entity* player) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyModelPlaced(this, player);
script->OnZonePropertyModelPlaced(this, player);
}
} }
void Entity::OnZonePropertyModelPickedUp(Entity* player) { void Entity::OnZonePropertyModelPickedUp(Entity* player) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyModelPickedUp(this, player);
script->OnZonePropertyModelPickedUp(this, player);
}
} }
void Entity::OnZonePropertyModelRemoved(Entity* player) { void Entity::OnZonePropertyModelRemoved(Entity* player) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyModelRemoved(this, player);
script->OnZonePropertyModelRemoved(this, player);
}
} }
void Entity::OnZonePropertyModelRemovedWhileEquipped(Entity* player) { void Entity::OnZonePropertyModelRemovedWhileEquipped(Entity* player) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyModelRemovedWhileEquipped(this, player);
script->OnZonePropertyModelRemovedWhileEquipped(this, player);
}
} }
void Entity::OnZonePropertyModelRotated(Entity* player) { void Entity::OnZonePropertyModelRotated(Entity* player) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnZonePropertyModelRotated(this, player);
script->OnZonePropertyModelRotated(this, player);
}
} }
void Entity::OnMessageBoxResponse(Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) { void Entity::OnMessageBoxResponse(Entity* sender, int32_t button, const std::u16string& identifier, const std::u16string& userData) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnMessageBoxResponse(this, sender, button, identifier, userData);
script->OnMessageBoxResponse(this, sender, button, identifier, userData);
}
} }
void Entity::OnChoiceBoxResponse(Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { void Entity::OnChoiceBoxResponse(Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnChoiceBoxResponse(this, sender, button, buttonIdentifier, identifier);
script->OnChoiceBoxResponse(this, sender, button, buttonIdentifier, identifier);
}
} }
void Entity::RequestActivityExit(Entity* sender, LWOOBJID player, bool canceled) { void Entity::RequestActivityExit(Entity* sender, LWOOBJID player, bool canceled) {
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnRequestActivityExit(sender, player, canceled);
script->OnRequestActivityExit(sender, player, canceled); }
}
CppScripts::Script* const Entity::GetScript() {
auto* scriptComponent = GetComponent<ScriptComponent>();
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) { void Entity::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType) {
@ -1568,9 +1524,7 @@ void Entity::Kill(Entity* murderer, const eKillType killType) {
//OMAI WA MOU, SHINDERIU //OMAI WA MOU, SHINDERIU
for (CppScripts::Script* script : CppScripts::GetEntityScripts(this)) { GetScript()->OnDie(this, murderer);
script->OnDie(this, murderer);
}
if (m_Spawner != nullptr) { if (m_Spawner != nullptr) {
m_Spawner->NotifyOfEntityDeath(m_ObjectID); m_Spawner->NotifyOfEntityDeath(m_ObjectID);
@ -2118,9 +2072,7 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) {
havokVehiclePhysicsComponent->SetIsOnGround(update.onGround); havokVehiclePhysicsComponent->SetIsOnGround(update.onGround);
havokVehiclePhysicsComponent->SetIsOnRail(update.onRail); havokVehiclePhysicsComponent->SetIsOnRail(update.onRail);
havokVehiclePhysicsComponent->SetVelocity(update.velocity); havokVehiclePhysicsComponent->SetVelocity(update.velocity);
havokVehiclePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3Constant::ZERO);
havokVehiclePhysicsComponent->SetAngularVelocity(update.angularVelocity); havokVehiclePhysicsComponent->SetAngularVelocity(update.angularVelocity);
havokVehiclePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3Constant::ZERO);
havokVehiclePhysicsComponent->SetRemoteInputInfo(update.remoteInputInfo); havokVehiclePhysicsComponent->SetRemoteInputInfo(update.remoteInputInfo);
} else { } else {
// Need to get the mount's controllable physics // Need to get the mount's controllable physics
@ -2131,9 +2083,7 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) {
possessedControllablePhysicsComponent->SetIsOnGround(update.onGround); possessedControllablePhysicsComponent->SetIsOnGround(update.onGround);
possessedControllablePhysicsComponent->SetIsOnRail(update.onRail); possessedControllablePhysicsComponent->SetIsOnRail(update.onRail);
possessedControllablePhysicsComponent->SetVelocity(update.velocity); possessedControllablePhysicsComponent->SetVelocity(update.velocity);
possessedControllablePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3Constant::ZERO);
possessedControllablePhysicsComponent->SetAngularVelocity(update.angularVelocity); possessedControllablePhysicsComponent->SetAngularVelocity(update.angularVelocity);
possessedControllablePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3Constant::ZERO);
} }
Game::entityManager->SerializeEntity(possassableEntity); Game::entityManager->SerializeEntity(possassableEntity);
} }
@ -2155,9 +2105,7 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) {
controllablePhysicsComponent->SetIsOnGround(update.onGround); controllablePhysicsComponent->SetIsOnGround(update.onGround);
controllablePhysicsComponent->SetIsOnRail(update.onRail); controllablePhysicsComponent->SetIsOnRail(update.onRail);
controllablePhysicsComponent->SetVelocity(update.velocity); controllablePhysicsComponent->SetVelocity(update.velocity);
controllablePhysicsComponent->SetDirtyVelocity(update.velocity != NiPoint3Constant::ZERO);
controllablePhysicsComponent->SetAngularVelocity(update.angularVelocity); controllablePhysicsComponent->SetAngularVelocity(update.angularVelocity);
controllablePhysicsComponent->SetDirtyAngularVelocity(update.angularVelocity != NiPoint3Constant::ZERO);
auto* ghostComponent = GetComponent<GhostComponent>(); auto* ghostComponent = GetComponent<GhostComponent>();
if (ghostComponent) ghostComponent->SetGhostReferencePoint(update.position); if (ghostComponent) ghostComponent->SetGhostReferencePoint(update.position);

View File

@ -146,7 +146,8 @@ public:
void AddComponent(eReplicaComponentType componentId, Component* component); void AddComponent(eReplicaComponentType componentId, Component* component);
std::vector<ScriptComponent*> 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 Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName);
void Unsubscribe(LWOOBJID scriptObjId, const std::string& notificationName); void Unsubscribe(LWOOBJID scriptObjId, const std::string& notificationName);
@ -171,8 +172,8 @@ public:
std::unordered_map<eReplicaComponentType, Component*>& GetComponents() { return m_Components; } // TODO: Remove std::unordered_map<eReplicaComponentType, Component*>& GetComponents() { return m_Components; } // TODO: Remove
void WriteBaseReplicaData(RakNet::BitStream* outBitStream, eReplicaPacketType packetType); void WriteBaseReplicaData(RakNet::BitStream& outBitStream, eReplicaPacketType packetType);
void WriteComponents(RakNet::BitStream* outBitStream, eReplicaPacketType packetType); void WriteComponents(RakNet::BitStream& outBitStream, eReplicaPacketType packetType);
void UpdateXMLDoc(tinyxml2::XMLDocument* doc); void UpdateXMLDoc(tinyxml2::XMLDocument* doc);
void Update(float deltaTime); void Update(float deltaTime);
@ -295,6 +296,9 @@ public:
void ProcessPositionUpdate(PositionUpdate& update); 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: protected:
LWOOBJID m_ObjectID; LWOOBJID m_ObjectID;

View File

@ -178,18 +178,18 @@ void EntityManager::SerializeEntities() {
stream.Write<char>(ID_REPLICA_MANAGER_SERIALIZE); stream.Write<char>(ID_REPLICA_MANAGER_SERIALIZE);
stream.Write<unsigned short>(entity->GetNetworkId()); stream.Write<unsigned short>(entity->GetNetworkId());
entity->WriteBaseReplicaData(&stream, eReplicaPacketType::SERIALIZATION); entity->WriteBaseReplicaData(stream, eReplicaPacketType::SERIALIZATION);
entity->WriteComponents(&stream, eReplicaPacketType::SERIALIZATION); entity->WriteComponents(stream, eReplicaPacketType::SERIALIZATION);
if (entity->GetIsGhostingCandidate()) { if (entity->GetIsGhostingCandidate()) {
for (auto* player : PlayerManager::GetAllPlayers()) { for (auto* player : PlayerManager::GetAllPlayers()) {
auto* ghostComponent = player->GetComponent<GhostComponent>(); auto* ghostComponent = player->GetComponent<GhostComponent>();
if (ghostComponent && ghostComponent->IsObserved(toSerialize)) { if (ghostComponent && ghostComponent->IsObserved(toSerialize)) {
Game::server->Send(&stream, player->GetSystemAddress(), false); Game::server->Send(stream, player->GetSystemAddress(), false);
} }
} }
} else { } else {
Game::server->Send(&stream, UNASSIGNED_SYSTEM_ADDRESS, true); Game::server->Send(stream, UNASSIGNED_SYSTEM_ADDRESS, true);
} }
} }
m_EntitiesToSerialize.clear(); m_EntitiesToSerialize.clear();
@ -359,16 +359,16 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr
stream.Write(true); stream.Write(true);
stream.Write<uint16_t>(entity->GetNetworkId()); stream.Write<uint16_t>(entity->GetNetworkId());
entity->WriteBaseReplicaData(&stream, eReplicaPacketType::CONSTRUCTION); entity->WriteBaseReplicaData(stream, eReplicaPacketType::CONSTRUCTION);
entity->WriteComponents(&stream, eReplicaPacketType::CONSTRUCTION); entity->WriteComponents(stream, eReplicaPacketType::CONSTRUCTION);
if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) { if (sysAddr == UNASSIGNED_SYSTEM_ADDRESS) {
if (skipChecks) { if (skipChecks) {
Game::server->Send(&stream, UNASSIGNED_SYSTEM_ADDRESS, true); Game::server->Send(stream, UNASSIGNED_SYSTEM_ADDRESS, true);
} else { } else {
for (auto* player : PlayerManager::GetAllPlayers()) { for (auto* player : PlayerManager::GetAllPlayers()) {
if (player->GetPlayerReadyForUpdates()) { if (player->GetPlayerReadyForUpdates()) {
Game::server->Send(&stream, player->GetSystemAddress(), false); Game::server->Send(stream, player->GetSystemAddress(), false);
} else { } else {
auto* ghostComponent = player->GetComponent<GhostComponent>(); auto* ghostComponent = player->GetComponent<GhostComponent>();
if (ghostComponent) ghostComponent->AddLimboConstruction(entity->GetObjectID()); if (ghostComponent) ghostComponent->AddLimboConstruction(entity->GetObjectID());
@ -376,7 +376,7 @@ void EntityManager::ConstructEntity(Entity* entity, const SystemAddress& sysAddr
} }
} }
} else { } else {
Game::server->Send(&stream, sysAddr, false); Game::server->Send(stream, sysAddr, false);
} }
if (entity->IsPlayer()) { if (entity->IsPlayer()) {
@ -407,7 +407,7 @@ void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr)
stream.Write<uint8_t>(ID_REPLICA_MANAGER_DESTRUCTION); stream.Write<uint8_t>(ID_REPLICA_MANAGER_DESTRUCTION);
stream.Write<uint16_t>(entity->GetNetworkId()); stream.Write<uint16_t>(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()) { for (auto* player : PlayerManager::GetAllPlayers()) {
if (!player->GetPlayerReadyForUpdates()) { if (!player->GetPlayerReadyForUpdates()) {
@ -418,10 +418,16 @@ void EntityManager::DestructEntity(Entity* entity, const SystemAddress& sysAddr)
} }
void EntityManager::SerializeEntity(Entity* entity) { 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()) { void EntityManager::SerializeEntity(const Entity& entity) {
m_EntitiesToSerialize.push_back(entity->GetObjectID()); 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());
} }
} }
@ -575,13 +581,13 @@ void EntityManager::ScheduleForKill(Entity* entity) {
const auto objectId = entity->GetObjectID(); const auto objectId = entity->GetObjectID();
if (std::find(m_EntitiesToKill.begin(), m_EntitiesToKill.end(), objectId) != m_EntitiesToKill.end()) { 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) { void EntityManager::ScheduleForDeletion(LWOOBJID entity) {
if (std::find(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity) != m_EntitiesToDelete.end()) { if (std::find(m_EntitiesToDelete.begin(), m_EntitiesToDelete.end(), entity) == m_EntitiesToDelete.end()) {
m_EntitiesToDelete.push_back(entity); m_EntitiesToDelete.push_back(entity);
} }
} }

View File

@ -45,6 +45,7 @@ public:
void ConstructEntity(Entity* entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, bool skipChecks = false); void ConstructEntity(Entity* entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS, bool skipChecks = false);
void DestructEntity(Entity* entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS); void DestructEntity(Entity* entity, const SystemAddress& sysAddr = UNASSIGNED_SYSTEM_ADDRESS);
void SerializeEntity(Entity* entity); void SerializeEntity(Entity* entity);
void SerializeEntity(const Entity& entity);
void ConstructAllEntities(const SystemAddress& sysAddr); void ConstructAllEntities(const SystemAddress& sysAddr);
void DestructAllEntities(const SystemAddress& sysAddr); void DestructAllEntities(const SystemAddress& sysAddr);

View File

@ -43,9 +43,9 @@ inline void WriteLeaderboardRow(std::ostringstream& leaderboard, const uint32_t&
leaderboard << "\nResult[0].Row[" << index << "]." << data->GetString(); leaderboard << "\nResult[0].Row[" << index << "]." << data->GetString();
} }
void Leaderboard::Serialize(RakNet::BitStream* bitStream) const { void Leaderboard::Serialize(RakNet::BitStream& bitStream) const {
bitStream->Write(gameID); bitStream.Write(gameID);
bitStream->Write(infoType); bitStream.Write(infoType);
std::ostringstream leaderboard; std::ostringstream leaderboard;
@ -64,12 +64,12 @@ void Leaderboard::Serialize(RakNet::BitStream* bitStream) const {
// Serialize the thing to a BitStream // Serialize the thing to a BitStream
uint32_t leaderboardSize = leaderboard.tellp(); uint32_t leaderboardSize = leaderboard.tellp();
bitStream->Write<uint32_t>(leaderboardSize); bitStream.Write<uint32_t>(leaderboardSize);
// Doing this all in 1 call so there is no possbility of a dangling pointer. // Doing this all in 1 call so there is no possbility of a dangling pointer.
bitStream->WriteAlignedBytes(reinterpret_cast<const unsigned char*>(GeneralUtils::ASCIIToUTF16(leaderboard.str()).c_str()), leaderboardSize * sizeof(char16_t)); bitStream.WriteAlignedBytes(reinterpret_cast<const unsigned char*>(GeneralUtils::ASCIIToUTF16(leaderboard.str()).c_str()), leaderboardSize * sizeof(char16_t));
if (leaderboardSize > 0) bitStream->Write<uint16_t>(0); if (leaderboardSize > 0) bitStream.Write<uint16_t>(0);
bitStream->Write0(); bitStream.Write0();
bitStream->Write0(); bitStream.Write0();
} }
void Leaderboard::QueryToLdf(std::unique_ptr<sql::ResultSet>& rows) { void Leaderboard::QueryToLdf(std::unique_ptr<sql::ResultSet>& rows) {

View File

@ -88,7 +88,7 @@ public:
* *
* Expensive! Leaderboards are very string intensive so be wary of performatnce calling this method. * 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 * Builds the leaderboard from the database based on the associated gameID

View File

@ -5,35 +5,35 @@
#include "Game.h" #include "Game.h"
#include "Logger.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{}; uint32_t handle{};
if (!bitStream->Read(handle)) { if (!bitStream.Read(handle)) {
LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits());
return; return;
} }
context->RegisterSyncBehavior(handle, this, branch, this->m_Timeout); 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(); 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{}; uint32_t behaviorId{};
if (!bitStream->Read(behaviorId)) { if (!bitStream.Read(behaviorId)) {
LOG("Unable to read behaviorId from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits()); LOG("Unable to read behaviorId from bitStream, aborting Sync! %i", bitStream.GetNumberOfUnreadBits());
return; return;
} }
LWOOBJID target{}; LWOOBJID target{};
if (!bitStream->Read(target)) { if (!bitStream.Read(target)) {
LOG("Unable to read target from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits()); LOG("Unable to read target from bitStream, aborting Sync! %i", bitStream.GetNumberOfUnreadBits());
return; return;
} }

View File

@ -6,11 +6,11 @@ class AirMovementBehavior final : public Behavior
public: public:
explicit AirMovementBehavior(const uint32_t behavior_id) : Behavior(behavior_id) {} 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; void Load() override;
private: private:

View File

@ -3,13 +3,13 @@
#include "Game.h" #include "Game.h"
#include "Logger.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) { for (auto* behavior : this->m_behaviors) {
behavior->Handle(context, bitStream, branch); 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) { for (auto* behavior : this->m_behaviors) {
behavior->Calculate(context, bitStream, branch); behavior->Calculate(context, bitStream, branch);
} }

View File

@ -15,9 +15,9 @@ public:
explicit AndBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { 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; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override;

View File

@ -5,7 +5,7 @@
#include "BuffComponent.h" #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); auto* entity = Game::entityManager->GetEntity(branch.target == LWOOBJID_EMPTY ? context->originator : branch.target);
if (entity == nullptr) return; if (entity == nullptr) return;
@ -30,7 +30,7 @@ void ApplyBuffBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext b
buffComponent->RemoveBuff(m_BuffId); 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); Handle(context, bitStream, branch);
} }

View File

@ -24,11 +24,11 @@ public:
explicit ApplyBuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { 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 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; void Load() override;
private: private:

View File

@ -12,11 +12,11 @@
#include "Game.h" #include "Game.h"
#include "Logger.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{}; uint32_t targetCount{};
if (!bitStream->Read(targetCount)) { if (!bitStream.Read(targetCount)) {
LOG("Unable to read targetCount from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); LOG("Unable to read targetCount from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits());
return; return;
} }
@ -40,7 +40,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* b
for (auto i = 0u; i < targetCount; ++i) { for (auto i = 0u; i < targetCount; ++i) {
LWOOBJID target{}; LWOOBJID target{};
if (!bitStream->Read(target)) { if (!bitStream.Read(target)) {
LOG("failed to read in target %i from bitStream, aborting target Handle!", i); LOG("failed to read in target %i from bitStream, aborting target Handle!", i);
}; };
targets.push_back(target); targets.push_back(target);
@ -54,7 +54,7 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* b
PlayFx(u"cast", context->originator); 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); auto* caster = Game::entityManager->GetEntity(context->caster);
if (!caster) return; if (!caster) return;
@ -83,7 +83,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream
// resize if we have more than max targets allows // resize if we have more than max targets allows
if (targets.size() > this->m_maxTargets) targets.resize(this->m_maxTargets); if (targets.size() > this->m_maxTargets) targets.resize(this->m_maxTargets);
bitStream->Write<uint32_t>(targets.size()); bitStream.Write<uint32_t>(targets.size());
if (targets.size() == 0) { if (targets.size() == 0) {
PlayFx(u"miss", context->originator); PlayFx(u"miss", context->originator);
@ -92,7 +92,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream
context->foundTarget = true; context->foundTarget = true;
// write all the targets to the bitstream // write all the targets to the bitstream
for (auto* target : targets) { for (auto* target : targets) {
bitStream->Write(target->GetObjectID()); bitStream.Write(target->GetObjectID());
} }
// then cast all the actions // then cast all the actions

View File

@ -6,8 +6,8 @@ class AreaOfEffectBehavior final : public Behavior
{ {
public: public:
explicit AreaOfEffectBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} explicit AreaOfEffectBehavior(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; void Load() override;
private: private:
Behavior* m_action; Behavior* m_action;

View File

@ -4,11 +4,11 @@
#include "Game.h" #include "Game.h"
#include "Logger.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{}; uint32_t handle{};
if (!bitStream->Read(handle)) { if (!bitStream.Read(handle)) {
LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); LOG("Unable to read handle from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits());
return; 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(); const auto handle = context->GetUniqueSkillId();
bitStream->Write(handle); bitStream.Write(handle);
context->foundTarget = true; 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); 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); PlayFx(u"cast", context->originator);
this->m_action->Calculate(context, bitStream, branch); this->m_action->Calculate(context, bitStream, branch);

View File

@ -19,13 +19,13 @@ public:
explicit AttackDelayBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { 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; void Load() override;
}; };

View File

@ -9,7 +9,7 @@
#include "BehaviorContext.h" #include "BehaviorContext.h"
#include "eBasicAttackSuccessTypes.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) { if (context->unmanaged) {
auto* entity = Game::entityManager->GetEntity(branch.target); auto* entity = Game::entityManager->GetEntity(branch.target);
@ -30,22 +30,22 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi
return; return;
} }
bitStream->AlignReadToByteBoundary(); bitStream.AlignReadToByteBoundary();
uint16_t allocatedBits{}; uint16_t allocatedBits{};
if (!bitStream->Read(allocatedBits) || allocatedBits == 0) { if (!bitStream.Read(allocatedBits) || allocatedBits == 0) {
LOG_DEBUG("No allocated bits"); LOG_DEBUG("No allocated bits");
return; return;
} }
LOG_DEBUG("Number of allocated bits %i", allocatedBits); LOG_DEBUG("Number of allocated bits %i", allocatedBits);
const auto baseAddress = bitStream->GetReadOffset(); const auto baseAddress = bitStream.GetReadOffset();
DoHandleBehavior(context, bitStream, branch); 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); auto* targetEntity = Game::entityManager->GetEntity(branch.target);
if (!targetEntity) { if (!targetEntity) {
LOG("Target targetEntity %llu not found.", branch.target); LOG("Target targetEntity %llu not found.", branch.target);
@ -62,7 +62,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
bool isImmune{}; bool isImmune{};
bool isSuccess{}; bool isSuccess{};
if (!bitStream->Read(isBlocked)) { if (!bitStream.Read(isBlocked)) {
LOG("Unable to read isBlocked"); LOG("Unable to read isBlocked");
return; return;
} }
@ -74,7 +74,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
return; return;
} }
if (!bitStream->Read(isImmune)) { if (!bitStream.Read(isImmune)) {
LOG("Unable to read isImmune"); LOG("Unable to read isImmune");
return; return;
} }
@ -85,20 +85,20 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
return; return;
} }
if (!bitStream->Read(isSuccess)) { if (!bitStream.Read(isSuccess)) {
LOG("failed to read success from bitstream"); LOG("failed to read success from bitstream");
return; return;
} }
if (isSuccess) { if (isSuccess) {
uint32_t armorDamageDealt{}; uint32_t armorDamageDealt{};
if (!bitStream->Read(armorDamageDealt)) { if (!bitStream.Read(armorDamageDealt)) {
LOG("Unable to read armorDamageDealt"); LOG("Unable to read armorDamageDealt");
return; return;
} }
uint32_t healthDamageDealt{}; uint32_t healthDamageDealt{};
if (!bitStream->Read(healthDamageDealt)) { if (!bitStream.Read(healthDamageDealt)) {
LOG("Unable to read healthDamageDealt"); LOG("Unable to read healthDamageDealt");
return; return;
} }
@ -111,7 +111,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
} }
bool died{}; bool died{};
if (!bitStream->Read(died)) { if (!bitStream.Read(died)) {
LOG("Unable to read died"); LOG("Unable to read died");
return; return;
} }
@ -122,7 +122,7 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
} }
uint8_t successState{}; uint8_t successState{};
if (!bitStream->Read(successState)) { if (!bitStream.Read(successState)) {
LOG("Unable to read success state"); LOG("Unable to read success state");
return; return;
} }
@ -144,26 +144,26 @@ void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::Bit
} }
} }
void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) {
bitStream->AlignWriteToByteBoundary(); bitStream.AlignWriteToByteBoundary();
const auto allocatedAddress = bitStream->GetWriteOffset(); const auto allocatedAddress = bitStream.GetWriteOffset();
bitStream->Write<uint16_t>(0); bitStream.Write<uint16_t>(0);
const auto startAddress = bitStream->GetWriteOffset(); const auto startAddress = bitStream.GetWriteOffset();
DoBehaviorCalculation(context, bitStream, branch); DoBehaviorCalculation(context, bitStream, branch);
const auto endAddress = bitStream->GetWriteOffset(); const auto endAddress = bitStream.GetWriteOffset();
const uint16_t allocate = endAddress - startAddress; const uint16_t allocate = endAddress - startAddress;
bitStream->SetWriteOffset(allocatedAddress); bitStream.SetWriteOffset(allocatedAddress);
bitStream->Write(allocate); bitStream.Write(allocate);
bitStream->SetWriteOffset(startAddress + 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); auto* targetEntity = Game::entityManager->GetEntity(branch.target);
if (!targetEntity) { if (!targetEntity) {
LOG("Target entity %llu is null!", branch.target); LOG("Target entity %llu is null!", branch.target);
@ -178,7 +178,7 @@ void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet
const bool isBlocking = destroyableComponent->GetAttacksToBlock() > 0; const bool isBlocking = destroyableComponent->GetAttacksToBlock() > 0;
bitStream->Write(isBlocking); bitStream.Write(isBlocking);
if (isBlocking) { if (isBlocking) {
destroyableComponent->SetAttacksToBlock(destroyableComponent->GetAttacksToBlock() - 1); destroyableComponent->SetAttacksToBlock(destroyableComponent->GetAttacksToBlock() - 1);
@ -188,7 +188,7 @@ void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet
} }
const bool isImmune = destroyableComponent->IsImmune() || destroyableComponent->IsCooldownImmune(); const bool isImmune = destroyableComponent->IsImmune() || destroyableComponent->IsCooldownImmune();
bitStream->Write(isImmune); bitStream.Write(isImmune);
if (isImmune) { if (isImmune) {
LOG_DEBUG("Target targetEntity %llu is immune!", branch.target); 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(); const uint32_t healthDamageDealt = previousHealth - destroyableComponent->GetHealth();
isSuccess = armorDamageDealt > 0 || healthDamageDealt > 0 || (armorDamageDealt + healthDamageDealt) > 0; isSuccess = armorDamageDealt > 0 || healthDamageDealt > 0 || (armorDamageDealt + healthDamageDealt) > 0;
bitStream->Write(isSuccess); bitStream.Write(isSuccess);
//Handle player damage cooldown //Handle player damage cooldown
if (isSuccess && targetEntity->IsPlayer() && !this->m_DontApplyImmune) { if (isSuccess && targetEntity->IsPlayer() && !this->m_DontApplyImmune) {
@ -222,15 +222,15 @@ void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet
if (healthDamageDealt >= 1) { if (healthDamageDealt >= 1) {
successState = eBasicAttackSuccessTypes::SUCCESS; successState = eBasicAttackSuccessTypes::SUCCESS;
} else if (armorDamageDealt >= 1) { } else if (armorDamageDealt >= 1) {
successState = this->m_OnFailArmor->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY ? eBasicAttackSuccessTypes::FAILIMMUNE : eBasicAttackSuccessTypes::FAILARMOR; successState = this->m_OnFailArmor->m_templateId == BehaviorTemplate::EMPTY ? eBasicAttackSuccessTypes::FAILIMMUNE : eBasicAttackSuccessTypes::FAILARMOR;
} }
bitStream->Write(armorDamageDealt); bitStream.Write(armorDamageDealt);
bitStream->Write(healthDamageDealt); bitStream.Write(healthDamageDealt);
bitStream->Write(targetEntity->GetIsDead()); bitStream.Write(targetEntity->GetIsDead());
} }
bitStream->Write(successState); bitStream.Write(successState);
switch (static_cast<eBasicAttackSuccessTypes>(successState)) { switch (static_cast<eBasicAttackSuccessTypes>(successState)) {
case eBasicAttackSuccessTypes::SUCCESS: case eBasicAttackSuccessTypes::SUCCESS:

View File

@ -12,7 +12,7 @@ public:
* is then offset to after the allocated bits for this stream. * 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. * @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. * 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. * @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 * @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. * 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 * @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 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. * @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: * @brief Loads this Behaviors parameters from the database. For this behavior specifically:

View File

@ -5,7 +5,7 @@
#include "CDActivitiesTable.h" #include "CDActivitiesTable.h"
#include "Game.h" #include "Game.h"
#include "Logger.h" #include "Logger.h"
#include "BehaviorTemplates.h" #include "BehaviorTemplate.h"
#include "BehaviorBranchContext.h" #include "BehaviorBranchContext.h"
#include <unordered_map> #include <unordered_map>
@ -110,176 +110,176 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) {
Behavior* behavior = nullptr; Behavior* behavior = nullptr;
switch (templateId) { switch (templateId) {
case BehaviorTemplates::BEHAVIOR_EMPTY: break; case BehaviorTemplate::EMPTY: break;
case BehaviorTemplates::BEHAVIOR_BASIC_ATTACK: case BehaviorTemplate::BASIC_ATTACK:
behavior = new BasicAttackBehavior(behaviorId); behavior = new BasicAttackBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_TAC_ARC: case BehaviorTemplate::TAC_ARC:
behavior = new TacArcBehavior(behaviorId); behavior = new TacArcBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_AND: case BehaviorTemplate::AND:
behavior = new AndBehavior(behaviorId); behavior = new AndBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_PROJECTILE_ATTACK: case BehaviorTemplate::PROJECTILE_ATTACK:
behavior = new ProjectileAttackBehavior(behaviorId); behavior = new ProjectileAttackBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_HEAL: case BehaviorTemplate::HEAL:
behavior = new HealBehavior(behaviorId); behavior = new HealBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_MOVEMENT_SWITCH: case BehaviorTemplate::MOVEMENT_SWITCH:
behavior = new MovementSwitchBehavior(behaviorId); behavior = new MovementSwitchBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_AREA_OF_EFFECT: case BehaviorTemplate::AREA_OF_EFFECT:
behavior = new AreaOfEffectBehavior(behaviorId); behavior = new AreaOfEffectBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_PLAY_EFFECT: case BehaviorTemplate::PLAY_EFFECT:
behavior = new PlayEffectBehavior(behaviorId); behavior = new PlayEffectBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_IMMUNITY: case BehaviorTemplate::IMMUNITY:
behavior = new ImmunityBehavior(behaviorId); behavior = new ImmunityBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_DAMAGE_BUFF: break; case BehaviorTemplate::DAMAGE_BUFF: break;
case BehaviorTemplates::BEHAVIOR_DAMAGE_ABSORBTION: case BehaviorTemplate::DAMAGE_ABSORBTION:
behavior = new DamageAbsorptionBehavior(behaviorId); behavior = new DamageAbsorptionBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_OVER_TIME: case BehaviorTemplate::OVER_TIME:
behavior = new OverTimeBehavior(behaviorId); behavior = new OverTimeBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_IMAGINATION: case BehaviorTemplate::IMAGINATION:
behavior = new ImaginationBehavior(behaviorId); behavior = new ImaginationBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_TARGET_CASTER: case BehaviorTemplate::TARGET_CASTER:
behavior = new TargetCasterBehavior(behaviorId); behavior = new TargetCasterBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_STUN: case BehaviorTemplate::STUN:
behavior = new StunBehavior(behaviorId); behavior = new StunBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_DURATION: case BehaviorTemplate::DURATION:
behavior = new DurationBehavior(behaviorId); behavior = new DurationBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_KNOCKBACK: case BehaviorTemplate::KNOCKBACK:
behavior = new KnockbackBehavior(behaviorId); behavior = new KnockbackBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_ATTACK_DELAY: case BehaviorTemplate::ATTACK_DELAY:
behavior = new AttackDelayBehavior(behaviorId); behavior = new AttackDelayBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_CAR_BOOST: case BehaviorTemplate::CAR_BOOST:
behavior = new CarBoostBehavior(behaviorId); behavior = new CarBoostBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_FALL_SPEED: case BehaviorTemplate::FALL_SPEED:
behavior = new FallSpeedBehavior(behaviorId); behavior = new FallSpeedBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_SHIELD: break; case BehaviorTemplate::SHIELD: break;
case BehaviorTemplates::BEHAVIOR_REPAIR_ARMOR: case BehaviorTemplate::REPAIR_ARMOR:
behavior = new RepairBehavior(behaviorId); behavior = new RepairBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_SPEED: case BehaviorTemplate::SPEED:
behavior = new SpeedBehavior(behaviorId); behavior = new SpeedBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_DARK_INSPIRATION: case BehaviorTemplate::DARK_INSPIRATION:
behavior = new DarkInspirationBehavior(behaviorId); behavior = new DarkInspirationBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_LOOT_BUFF: case BehaviorTemplate::LOOT_BUFF:
behavior = new LootBuffBehavior(behaviorId); behavior = new LootBuffBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_VENTURE_VISION: case BehaviorTemplate::VENTURE_VISION:
behavior = new VentureVisionBehavior(behaviorId); behavior = new VentureVisionBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_SPAWN_OBJECT: case BehaviorTemplate::SPAWN_OBJECT:
behavior = new SpawnBehavior(behaviorId); behavior = new SpawnBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_LAY_BRICK: break; case BehaviorTemplate::LAY_BRICK: break;
case BehaviorTemplates::BEHAVIOR_SWITCH: case BehaviorTemplate::SWITCH:
behavior = new SwitchBehavior(behaviorId); behavior = new SwitchBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_BUFF: case BehaviorTemplate::BUFF:
behavior = new BuffBehavior(behaviorId); behavior = new BuffBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_JETPACK: case BehaviorTemplate::JETPACK:
behavior = new JetPackBehavior(behaviorId); behavior = new JetPackBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_SKILL_EVENT: case BehaviorTemplate::SKILL_EVENT:
behavior = new SkillEventBehavior(behaviorId); behavior = new SkillEventBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_CONSUME_ITEM: case BehaviorTemplate::CONSUME_ITEM:
behavior = new ConsumeItemBehavior(behaviorId); behavior = new ConsumeItemBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_SKILL_CAST_FAILED: case BehaviorTemplate::SKILL_CAST_FAILED:
behavior = new SkillCastFailedBehavior(behaviorId); behavior = new SkillCastFailedBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_IMITATION_SKUNK_STINK: break; case BehaviorTemplate::IMITATION_SKUNK_STINK: break;
case BehaviorTemplates::BEHAVIOR_CHANGE_IDLE_FLAGS: case BehaviorTemplate::CHANGE_IDLE_FLAGS:
behavior = new ChangeIdleFlagsBehavior(behaviorId); behavior = new ChangeIdleFlagsBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_APPLY_BUFF: case BehaviorTemplate::APPLY_BUFF:
behavior = new ApplyBuffBehavior(behaviorId); behavior = new ApplyBuffBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_CHAIN: case BehaviorTemplate::CHAIN:
behavior = new ChainBehavior(behaviorId); behavior = new ChainBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_CHANGE_ORIENTATION: case BehaviorTemplate::CHANGE_ORIENTATION:
behavior = new ChangeOrientationBehavior(behaviorId); behavior = new ChangeOrientationBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_FORCE_MOVEMENT: case BehaviorTemplate::FORCE_MOVEMENT:
behavior = new ForceMovementBehavior(behaviorId); behavior = new ForceMovementBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_INTERRUPT: case BehaviorTemplate::INTERRUPT:
behavior = new InterruptBehavior(behaviorId); behavior = new InterruptBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_ALTER_COOLDOWN: break; case BehaviorTemplate::ALTER_COOLDOWN: break;
case BehaviorTemplates::BEHAVIOR_CHARGE_UP: case BehaviorTemplate::CHARGE_UP:
behavior = new ChargeUpBehavior(behaviorId); behavior = new ChargeUpBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_SWITCH_MULTIPLE: case BehaviorTemplate::SWITCH_MULTIPLE:
behavior = new SwitchMultipleBehavior(behaviorId); behavior = new SwitchMultipleBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_START: case BehaviorTemplate::START:
behavior = new StartBehavior(behaviorId); behavior = new StartBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_END: case BehaviorTemplate::END:
behavior = new EndBehavior(behaviorId); behavior = new EndBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_ALTER_CHAIN_DELAY: break; case BehaviorTemplate::ALTER_CHAIN_DELAY: break;
case BehaviorTemplates::BEHAVIOR_CAMERA: break; case BehaviorTemplate::CAMERA: break;
case BehaviorTemplates::BEHAVIOR_REMOVE_BUFF: case BehaviorTemplate::REMOVE_BUFF:
behavior = new RemoveBuffBehavior(behaviorId); behavior = new RemoveBuffBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_GRAB: break; case BehaviorTemplate::GRAB: break;
case BehaviorTemplates::BEHAVIOR_MODULAR_BUILD: break; case BehaviorTemplate::MODULAR_BUILD: break;
case BehaviorTemplates::BEHAVIOR_NPC_COMBAT_SKILL: case BehaviorTemplate::NPC_COMBAT_SKILL:
behavior = new NpcCombatSkillBehavior(behaviorId); behavior = new NpcCombatSkillBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_BLOCK: case BehaviorTemplate::BLOCK:
behavior = new BlockBehavior(behaviorId); behavior = new BlockBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_VERIFY: case BehaviorTemplate::VERIFY:
behavior = new VerifyBehavior(behaviorId); behavior = new VerifyBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_TAUNT: case BehaviorTemplate::TAUNT:
behavior = new TauntBehavior(behaviorId); behavior = new TauntBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_AIR_MOVEMENT: case BehaviorTemplate::AIR_MOVEMENT:
behavior = new AirMovementBehavior(behaviorId); behavior = new AirMovementBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_SPAWN_QUICKBUILD: case BehaviorTemplate::SPAWN_QUICKBUILD:
behavior = new SpawnBehavior(behaviorId); behavior = new SpawnBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_PULL_TO_POINT: case BehaviorTemplate::PULL_TO_POINT:
behavior = new PullToPointBehavior(behaviorId); behavior = new PullToPointBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_PROPERTY_ROTATE: break; case BehaviorTemplate::PROPERTY_ROTATE: break;
case BehaviorTemplates::BEHAVIOR_DAMAGE_REDUCTION: case BehaviorTemplate::DAMAGE_REDUCTION:
behavior = new DamageReductionBehavior(behaviorId); behavior = new DamageReductionBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_PROPERTY_TELEPORT: case BehaviorTemplate::PROPERTY_TELEPORT:
behavior = new PropertyTeleportBehavior(behaviorId); behavior = new PropertyTeleportBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_PROPERTY_CLEAR_TARGET: case BehaviorTemplate::PROPERTY_CLEAR_TARGET:
behavior = new ClearTargetBehavior(behaviorId); behavior = new ClearTargetBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_TAKE_PICTURE: break; case BehaviorTemplate::TAKE_PICTURE: break;
case BehaviorTemplates::BEHAVIOR_MOUNT: break; case BehaviorTemplate::MOUNT: break;
case BehaviorTemplates::BEHAVIOR_SKILL_SET: break; case BehaviorTemplate::SKILL_SET: break;
default: default:
//LOG("Failed to load behavior with invalid template id (%i)!", templateId); //LOG("Failed to load behavior with invalid template id (%i)!", templateId);
break; break;
@ -296,19 +296,19 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) {
return behavior; return behavior;
} }
BehaviorTemplates Behavior::GetBehaviorTemplate(const uint32_t behaviorId) { BehaviorTemplate Behavior::GetBehaviorTemplate(const uint32_t behaviorId) {
auto behaviorTemplateTable = CDClientManager::GetTable<CDBehaviorTemplateTable>(); auto behaviorTemplateTable = CDClientManager::GetTable<CDBehaviorTemplateTable>();
BehaviorTemplates templateID = BehaviorTemplates::BEHAVIOR_EMPTY; BehaviorTemplate templateID = BehaviorTemplate::EMPTY;
// Find behavior template by its behavior id. Default to 0. // Find behavior template by its behavior id. Default to 0.
if (behaviorTemplateTable) { if (behaviorTemplateTable) {
auto templateEntry = behaviorTemplateTable->GetByBehaviorID(behaviorId); auto templateEntry = behaviorTemplateTable->GetByBehaviorID(behaviorId);
if (templateEntry.behaviorID == behaviorId) { if (templateEntry.behaviorID == behaviorId) {
templateID = static_cast<BehaviorTemplates>(templateEntry.templateID); templateID = static_cast<BehaviorTemplate>(templateEntry.templateID);
} }
} }
if (templateID == BehaviorTemplates::BEHAVIOR_EMPTY && behaviorId != 0) { if (templateID == BehaviorTemplate::EMPTY && behaviorId != 0) {
LOG("Failed to load behavior template with id (%i)!", behaviorId); LOG("Failed to load behavior template with id (%i)!", behaviorId);
} }
@ -335,26 +335,22 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID
const auto typeString = GeneralUtils::UTF16ToWTF8(type); const auto typeString = GeneralUtils::UTF16ToWTF8(type);
if (m_effectNames == nullptr) { const auto itr = m_effectNames.find(typeString);
m_effectNames = new std::unordered_map<std::string, std::string>();
} else {
const auto pair = m_effectNames->find(typeString);
if (type.empty()) { if (type.empty()) {
type = GeneralUtils::ASCIIToUTF16(*m_effectType); type = GeneralUtils::ASCIIToUTF16(m_effectType);
} }
if (pair != m_effectNames->end()) { if (itr != m_effectNames.end()) {
if (renderComponent == nullptr) { if (renderComponent == nullptr) {
GameMessages::SendPlayFXEffect(targetEntity, effectId, type, pair->second, secondary, 1, 1, true); GameMessages::SendPlayFXEffect(targetEntity, effectId, type, itr->second, secondary, 1, 1, true);
return;
}
renderComponent->PlayEffect(effectId, type, pair->second, secondary);
return; return;
} }
renderComponent->PlayEffect(effectId, type, itr->second, secondary);
return;
} }
// The SQlite result object becomes invalid if the query object leaves scope. // The SQlite result object becomes invalid if the query object leaves scope.
@ -388,12 +384,12 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID
type = GeneralUtils::ASCIIToUTF16(typeResult); type = GeneralUtils::ASCIIToUTF16(typeResult);
m_effectType = new std::string(typeResult); m_effectType = typeResult;
} }
result.finalize(); result.finalize();
m_effectNames->insert_or_assign(typeString, name); m_effectNames.insert_or_assign(typeString, name);
if (renderComponent == nullptr) { if (renderComponent == nullptr) {
GameMessages::SendPlayFXEffect(targetEntity, effectId, type, name, secondary, 1, 1, true); GameMessages::SendPlayFXEffect(targetEntity, effectId, type, name, secondary, 1, 1, true);
@ -423,8 +419,7 @@ Behavior::Behavior(const uint32_t behaviorId) {
if (behaviorId == 0) { if (behaviorId == 0) {
this->m_effectId = 0; this->m_effectId = 0;
this->m_effectHandle = nullptr; this->m_templateId = BehaviorTemplate::EMPTY;
this->m_templateId = BehaviorTemplates::BEHAVIOR_EMPTY;
} }
// Make sure we do not proceed if we are trying to load an invalid behavior // Make sure we do not proceed if we are trying to load an invalid behavior
@ -432,17 +427,16 @@ Behavior::Behavior(const uint32_t behaviorId) {
LOG("Failed to load behavior with id (%i)!", behaviorId); LOG("Failed to load behavior with id (%i)!", behaviorId);
this->m_effectId = 0; this->m_effectId = 0;
this->m_effectHandle = nullptr; this->m_templateId = BehaviorTemplate::EMPTY;
this->m_templateId = BehaviorTemplates::BEHAVIOR_EMPTY;
return; return;
} }
this->m_templateId = static_cast<BehaviorTemplates>(templateInDatabase.templateID); this->m_templateId = static_cast<BehaviorTemplate>(templateInDatabase.templateID);
this->m_effectId = templateInDatabase.effectID; this->m_effectId = templateInDatabase.effectID;
this->m_effectHandle = *templateInDatabase.effectHandle != "" ? new std::string(*templateInDatabase.effectHandle) : nullptr; this->m_effectHandle = *templateInDatabase.effectHandle;
} }
@ -487,10 +481,10 @@ std::map<std::string, float> Behavior::GetParameterNames() const {
void Behavior::Load() { 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) { void Behavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) {
@ -502,14 +496,8 @@ void Behavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWO
void Behavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { 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() {
delete m_effectNames;
delete m_effectType;
delete m_effectHandle;
} }

View File

@ -6,7 +6,7 @@
#include <unordered_map> #include <unordered_map>
#include "BitStream.h" #include "BitStream.h"
#include "BehaviorTemplates.h" #include "BehaviorTemplate.h"
#include "dCommonVars.h" #include "dCommonVars.h"
struct BehaviorContext; struct BehaviorContext;
@ -26,7 +26,7 @@ public:
static Behavior* CreateBehavior(uint32_t behaviorId); static Behavior* CreateBehavior(uint32_t behaviorId);
static BehaviorTemplates GetBehaviorTemplate(uint32_t behaviorId); static BehaviorTemplate GetBehaviorTemplate(uint32_t behaviorId);
/* /*
* Utilities * Utilities
@ -39,11 +39,11 @@ public:
*/ */
uint32_t m_behaviorId; uint32_t m_behaviorId;
BehaviorTemplates m_templateId; BehaviorTemplate m_templateId;
uint32_t m_effectId; uint32_t m_effectId;
std::string* m_effectHandle = nullptr; std::string m_effectHandle;
std::unordered_map<std::string, std::string>* m_effectNames = nullptr; std::unordered_map<std::string, std::string> m_effectNames;
std::string* m_effectType = nullptr; std::string m_effectType;
/* /*
* Behavior parameters * Behavior parameters
@ -68,9 +68,9 @@ public:
virtual void Load(); virtual void Load();
// Player side // 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); virtual void UnCast(BehaviorContext* context, BehaviorBranchContext branch);
@ -79,14 +79,20 @@ public:
virtual void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second); virtual void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second);
// Npc side // 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 * Creations/destruction
*/ */
explicit Behavior(uint32_t behaviorId); explicit Behavior(uint32_t behaviorId);
virtual ~Behavior(); virtual ~Behavior() = default;
Behavior(const Behavior& other) = default;
Behavior(Behavior&& other) = default;
Behavior& operator=(const Behavior& other) = default;
Behavior& operator=(Behavior&& other) = default;
}; };

View File

@ -105,7 +105,7 @@ void BehaviorContext::ExecuteUpdates() {
this->scheduledUpdates.clear(); 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; BehaviorSyncEntry entry;
auto found = false; auto found = false;
@ -243,27 +243,25 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) {
echo.uiBehaviorHandle = entry.handle; echo.uiBehaviorHandle = entry.handle;
echo.uiSkillHandle = this->skillUId; echo.uiSkillHandle = this->skillUId;
auto* bitStream = new RakNet::BitStream(); RakNet::BitStream bitStream{};
// Calculate sync // Calculate sync
entry.behavior->SyncCalculation(this, bitStream, entry.branchContext); entry.behavior->SyncCalculation(this, bitStream, entry.branchContext);
if (!clientInitalized) { if (!clientInitalized) {
echo.sBitStream.assign(reinterpret_cast<char*>(bitStream->GetData()), bitStream->GetNumberOfBytesUsed()); echo.sBitStream.assign(reinterpret_cast<char*>(bitStream.GetData()), bitStream.GetNumberOfBytesUsed());
// Write message // Write message
RakNet::BitStream message; RakNet::BitStream message;
BitStreamUtils::WriteHeader(message, eConnectionType::CLIENT, eClientMessageType::GAME_MSG); BitStreamUtils::WriteHeader(message, eConnectionType::CLIENT, eClientMessageType::GAME_MSG);
message.Write(this->originator); 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(); ExecuteUpdates();
delete bitStream;
} }
std::vector<BehaviorSyncEntry> valid; std::vector<BehaviorSyncEntry> valid;

View File

@ -93,7 +93,7 @@ struct BehaviorContext
void ExecuteUpdates(); void ExecuteUpdates();
void SyncBehavior(uint32_t syncId, RakNet::BitStream* bitStream); void SyncBehavior(uint32_t syncId, RakNet::BitStream& bitStream);
void Update(float deltaTime); void Update(float deltaTime);

View File

@ -0,0 +1,70 @@
#pragma once
enum class BehaviorTemplate : unsigned int {
EMPTY, // Not a real behavior, indicates invalid behaviors
BASIC_ATTACK,
TAC_ARC,
AND,
PROJECTILE_ATTACK,
HEAL,
MOVEMENT_SWITCH,
AREA_OF_EFFECT,
PLAY_EFFECT,
IMMUNITY,
DAMAGE_BUFF,
DAMAGE_ABSORBTION,
OVER_TIME,
IMAGINATION,
TARGET_CASTER,
STUN,
DURATION,
KNOCKBACK,
ATTACK_DELAY,
CAR_BOOST,
FALL_SPEED,
SHIELD,
REPAIR_ARMOR,
SPEED,
DARK_INSPIRATION,
LOOT_BUFF,
VENTURE_VISION,
SPAWN_OBJECT,
LAY_BRICK,
SWITCH,
BUFF,
JETPACK,
SKILL_EVENT,
CONSUME_ITEM,
SKILL_CAST_FAILED,
IMITATION_SKUNK_STINK,
CHANGE_IDLE_FLAGS,
APPLY_BUFF,
CHAIN,
CHANGE_ORIENTATION,
FORCE_MOVEMENT,
INTERRUPT,
ALTER_COOLDOWN,
CHARGE_UP,
SWITCH_MULTIPLE,
START,
END,
ALTER_CHAIN_DELAY,
CAMERA,
REMOVE_BUFF,
GRAB,
MODULAR_BUILD,
NPC_COMBAT_SKILL,
BLOCK,
VERIFY,
TAUNT,
AIR_MOVEMENT,
SPAWN_QUICKBUILD,
PULL_TO_POINT,
PROPERTY_ROTATE,
DAMAGE_REDUCTION,
PROPERTY_TELEPORT,
PROPERTY_CLEAR_TARGET,
TAKE_PICTURE,
MOUNT,
SKILL_SET
};

View File

@ -1 +0,0 @@
#include "BehaviorTemplates.h"

View File

@ -1,70 +0,0 @@
#pragma once
enum class BehaviorTemplates : unsigned int {
BEHAVIOR_EMPTY, // Not a real behavior, indicates invalid behaviors
BEHAVIOR_BASIC_ATTACK,
BEHAVIOR_TAC_ARC,
BEHAVIOR_AND,
BEHAVIOR_PROJECTILE_ATTACK,
BEHAVIOR_HEAL,
BEHAVIOR_MOVEMENT_SWITCH,
BEHAVIOR_AREA_OF_EFFECT,
BEHAVIOR_PLAY_EFFECT,
BEHAVIOR_IMMUNITY,
BEHAVIOR_DAMAGE_BUFF,
BEHAVIOR_DAMAGE_ABSORBTION,
BEHAVIOR_OVER_TIME,
BEHAVIOR_IMAGINATION,
BEHAVIOR_TARGET_CASTER,
BEHAVIOR_STUN,
BEHAVIOR_DURATION,
BEHAVIOR_KNOCKBACK,
BEHAVIOR_ATTACK_DELAY,
BEHAVIOR_CAR_BOOST,
BEHAVIOR_FALL_SPEED,
BEHAVIOR_SHIELD,
BEHAVIOR_REPAIR_ARMOR,
BEHAVIOR_SPEED,
BEHAVIOR_DARK_INSPIRATION,
BEHAVIOR_LOOT_BUFF,
BEHAVIOR_VENTURE_VISION,
BEHAVIOR_SPAWN_OBJECT,
BEHAVIOR_LAY_BRICK,
BEHAVIOR_SWITCH,
BEHAVIOR_BUFF,
BEHAVIOR_JETPACK,
BEHAVIOR_SKILL_EVENT,
BEHAVIOR_CONSUME_ITEM,
BEHAVIOR_SKILL_CAST_FAILED,
BEHAVIOR_IMITATION_SKUNK_STINK,
BEHAVIOR_CHANGE_IDLE_FLAGS,
BEHAVIOR_APPLY_BUFF,
BEHAVIOR_CHAIN,
BEHAVIOR_CHANGE_ORIENTATION,
BEHAVIOR_FORCE_MOVEMENT,
BEHAVIOR_INTERRUPT,
BEHAVIOR_ALTER_COOLDOWN,
BEHAVIOR_CHARGE_UP,
BEHAVIOR_SWITCH_MULTIPLE,
BEHAVIOR_START,
BEHAVIOR_END,
BEHAVIOR_ALTER_CHAIN_DELAY,
BEHAVIOR_CAMERA,
BEHAVIOR_REMOVE_BUFF,
BEHAVIOR_GRAB,
BEHAVIOR_MODULAR_BUILD,
BEHAVIOR_NPC_COMBAT_SKILL,
BEHAVIOR_BLOCK,
BEHAVIOR_VERIFY,
BEHAVIOR_TAUNT,
BEHAVIOR_AIR_MOVEMENT,
BEHAVIOR_SPAWN_QUICKBUILD,
BEHAVIOR_PULL_TO_POINT,
BEHAVIOR_PROPERTY_ROTATE,
BEHAVIOR_DAMAGE_REDUCTION,
BEHAVIOR_PROPERTY_TELEPORT,
BEHAVIOR_PROPERTY_CLEAR_TARGET,
BEHAVIOR_TAKE_PICTURE,
BEHAVIOR_MOUNT,
BEHAVIOR_SKILL_SET
};

View File

@ -7,7 +7,7 @@
#include "Logger.h" #include "Logger.h"
#include "DestroyableComponent.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; const auto target = context->originator;
auto* entity = Game::entityManager->GetEntity(target); 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); Handle(context, bitStream, branch);
} }

View File

@ -13,9 +13,9 @@ public:
explicit BlockBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { 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; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override;

View File

@ -7,7 +7,7 @@
#include "Logger.h" #include "Logger.h"
#include "DestroyableComponent.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; const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator;
auto* entity = Game::entityManager->GetEntity(target); auto* entity = Game::entityManager->GetEntity(target);

View File

@ -16,7 +16,7 @@ public:
explicit BuffBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { 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; void UnCast(BehaviorContext* context, BehaviorBranchContext branch) override;

View File

@ -7,7 +7,6 @@ set(DGAME_DBEHAVIORS_SOURCES "AirMovementBehavior.cpp"
"Behavior.cpp" "Behavior.cpp"
"BehaviorBranchContext.cpp" "BehaviorBranchContext.cpp"
"BehaviorContext.cpp" "BehaviorContext.cpp"
"BehaviorTemplates.cpp"
"BlockBehavior.cpp" "BlockBehavior.cpp"
"BuffBehavior.cpp" "BuffBehavior.cpp"
"CarBoostBehavior.cpp" "CarBoostBehavior.cpp"
@ -21,7 +20,6 @@ set(DGAME_DBEHAVIORS_SOURCES "AirMovementBehavior.cpp"
"DamageReductionBehavior.cpp" "DamageReductionBehavior.cpp"
"DarkInspirationBehavior.cpp" "DarkInspirationBehavior.cpp"
"DurationBehavior.cpp" "DurationBehavior.cpp"
"EmptyBehavior.cpp"
"EndBehavior.cpp" "EndBehavior.cpp"
"FallSpeedBehavior.cpp" "FallSpeedBehavior.cpp"
"ForceMovementBehavior.cpp" "ForceMovementBehavior.cpp"
@ -56,7 +54,15 @@ set(DGAME_DBEHAVIORS_SOURCES "AirMovementBehavior.cpp"
"VentureVisionBehavior.cpp" "VentureVisionBehavior.cpp"
"VerifyBehavior.cpp") "VerifyBehavior.cpp")
add_library(dBehaviors STATIC ${DGAME_DBEHAVIORS_SOURCES}) add_library(dBehaviors OBJECT ${DGAME_DBEHAVIORS_SOURCES})
target_link_libraries(dBehaviors PUBLIC dPhysics) target_link_libraries(dBehaviors PUBLIC dDatabaseCDClient dPhysics)
target_include_directories(dBehaviors PUBLIC ".") 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) target_precompile_headers(dBehaviors REUSE_FROM dGameBase)

View File

@ -8,7 +8,7 @@
#include "Logger.h" #include "Logger.h"
#include "PossessableComponent.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); GameMessages::SendVehicleAddPassiveBoostAction(branch.target, UNASSIGNED_SYSTEM_ADDRESS);
auto* entity = Game::entityManager->GetEntity(context->originator); auto* entity = Game::entityManager->GetEntity(context->originator);

View File

@ -17,7 +17,7 @@ public:
explicit CarBoostBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { 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; void Load() override;
}; };

View File

@ -3,11 +3,11 @@
#include "Game.h" #include "Game.h"
#include "Logger.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{}; uint32_t chainIndex{};
if (!bitStream->Read(chainIndex)) { if (!bitStream.Read(chainIndex)) {
LOG("Unable to read chainIndex from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits()); LOG("Unable to read chainIndex from bitStream, aborting Handle! %i", bitStream.GetNumberOfUnreadBits());
return; return;
} }
@ -16,12 +16,12 @@ void ChainBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStrea
if (chainIndex < this->m_behaviors.size()) { if (chainIndex < this->m_behaviors.size()) {
this->m_behaviors.at(chainIndex)->Handle(context, bitStream, branch); this->m_behaviors.at(chainIndex)->Handle(context, bitStream, branch);
} else { } 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) { void ChainBehavior::Calculate(BehaviorContext* context, RakNet::BitStream& bitStream, const BehaviorBranchContext branch) {
bitStream->Write(1); bitStream.Write(1);
this->m_behaviors.at(0)->Calculate(context, bitStream, branch); this->m_behaviors.at(0)->Calculate(context, bitStream, branch);
} }

View File

@ -16,9 +16,9 @@ public:
explicit ChainBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { 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; void Load() override;
}; };

View File

@ -3,7 +3,7 @@
#include "BehaviorContext.h" #include "BehaviorContext.h"
#include "BehaviorBranchContext.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; const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator;
if (!target) return; 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); Handle(context, bitStream, branch);
} }

View File

@ -11,8 +11,8 @@ public:
*/ */
explicit ChangeIdleFlagsBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} explicit ChangeIdleFlagsBehavior(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 Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override;
void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override;
void Load() override; void Load() override;

View File

@ -3,7 +3,7 @@
#include "BehaviorContext.h" #include "BehaviorContext.h"
#include "EntityManager.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; Entity* sourceEntity;
if (this->m_orientCaster) sourceEntity = Game::entityManager->GetEntity(context->originator); if (this->m_orientCaster) sourceEntity = Game::entityManager->GetEntity(context->originator);
else sourceEntity = Game::entityManager->GetEntity(branch.target); else sourceEntity = Game::entityManager->GetEntity(branch.target);

View File

@ -5,7 +5,7 @@
class ChangeOrientationBehavior final : public Behavior { class ChangeOrientationBehavior final : public Behavior {
public: public:
explicit ChangeOrientationBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} 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; void Load() override;
private: private:
bool m_orientCaster; bool m_orientCaster;

View File

@ -4,10 +4,10 @@
#include "Game.h" #include "Game.h"
#include "Logger.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{}; uint32_t handle{};
if (!bitStream->Read(handle)) { if (!bitStream.Read(handle)) {
LOG("Unable to read handle from bitStream, aborting Handle! variable_type"); LOG("Unable to read handle from bitStream, aborting Handle! variable_type");
return; return;
}; };
@ -15,10 +15,10 @@ void ChargeUpBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitSt
context->RegisterSyncBehavior(handle, this, branch, this->m_MaxDuration); 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); this->m_action->Handle(context, bitStream, branch);
} }

View File

@ -6,11 +6,11 @@ class ChargeUpBehavior final : public Behavior
public: public:
explicit ChargeUpBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} 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; void Load() override;
private: private:

View File

@ -3,13 +3,13 @@
#include "BehaviorContext.h" #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; branch.target = LWOOBJID_EMPTY;
this->m_action->Handle(context, bitStream, branch); 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; branch.target = LWOOBJID_EMPTY;
this->m_action->Calculate(context, bitStream, branch); this->m_action->Calculate(context, bitStream, branch);

View File

@ -14,9 +14,9 @@ public:
explicit ClearTargetBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { 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; void Load() override;
}; };

View File

@ -3,7 +3,7 @@
#include "BehaviorBranchContext.h" #include "BehaviorBranchContext.h"
#include "InventoryComponent.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; auto action_to_cast = m_ActionNotConsumed;
if (this->m_ConsumeLOT != -1) { if (this->m_ConsumeLOT != -1) {
auto caster = Game::entityManager->GetEntity(context->caster); 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); 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); Handle(context, bitStream, branch);
} }

View File

@ -5,8 +5,8 @@ class ConsumeItemBehavior final : public Behavior
{ {
public: public:
explicit ConsumeItemBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {} explicit ConsumeItemBehavior(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 Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Sync(BehaviorContext* context, RakNet::BitStream& bitStream, BehaviorBranchContext branch) override;
void Load() override; void Load() override;
private: private:

View File

@ -7,7 +7,7 @@
#include "Logger.h" #include "Logger.h"
#include "DestroyableComponent.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); auto* target = Game::entityManager->GetEntity(branch.target);
if (target == nullptr) { if (target == nullptr) {
@ -29,7 +29,7 @@ void DamageAbsorptionBehavior::Handle(BehaviorContext* context, RakNet::BitStrea
context->RegisterTimerBehavior(this, branch, target->GetObjectID()); 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); Handle(context, bitStream, branch);
} }

View File

@ -13,9 +13,9 @@ public:
explicit DamageAbsorptionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { 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; void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override;

View File

@ -7,7 +7,7 @@
#include "Logger.h" #include "Logger.h"
#include "DestroyableComponent.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); auto* target = Game::entityManager->GetEntity(branch.target);
if (target == nullptr) { if (target == nullptr) {
@ -27,7 +27,7 @@ void DamageReductionBehavior::Handle(BehaviorContext* context, RakNet::BitStream
context->RegisterTimerBehavior(this, branch, target->GetObjectID()); 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); Handle(context, bitStream, branch);
} }

View File

@ -13,9 +13,9 @@ public:
explicit DamageReductionBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { 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; void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override;

View File

@ -6,7 +6,7 @@
#include "EntityManager.h" #include "EntityManager.h"
#include "BehaviorContext.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); auto* target = Game::entityManager->GetEntity(branch.target);
if (target == nullptr) { 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); auto* target = Game::entityManager->GetEntity(branch.target);
if (target == nullptr) { if (target == nullptr) {

View File

@ -11,9 +11,9 @@ public:
explicit DarkInspirationBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { 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; void Load() override;
private: private:

View File

@ -2,13 +2,13 @@
#include "BehaviorBranchContext.h" #include "BehaviorBranchContext.h"
#include "BehaviorContext.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; branch.duration = this->m_duration;
this->m_action->Handle(context, bitStream, branch); 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; branch.duration = this->m_duration;
this->m_action->Calculate(context, bitStream, branch); this->m_action->Calculate(context, bitStream, branch);

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