Merge branch 'main' into use-npc-paths

This commit is contained in:
Aaron Kimbre 2023-01-07 00:52:22 -06:00
commit 7a9bf57af0
238 changed files with 4420 additions and 2382 deletions

6
.gitmodules vendored
View File

@ -14,12 +14,6 @@
path = thirdparty/mariadb-connector-cpp path = thirdparty/mariadb-connector-cpp
url = https://github.com/mariadb-corporation/mariadb-connector-cpp.git url = https://github.com/mariadb-corporation/mariadb-connector-cpp.git
ignore = dirty ignore = dirty
[submodule "thirdparty/docker-utils"]
path = thirdparty/docker-utils
url = https://github.com/lcdr/utils.git
[submodule "thirdparty/LUnpack"]
path = thirdparty/LUnpack
url = https://github.com/Xiphoseer/LUnpack.git
[submodule "thirdparty/AccountManager"] [submodule "thirdparty/AccountManager"]
path = thirdparty/AccountManager path = thirdparty/AccountManager
url = https://github.com/DarkflameUniverse/AccountManager url = https://github.com/DarkflameUniverse/AccountManager

View File

@ -89,8 +89,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})
# Create a /res directory # Create a /resServer directory
make_directory(${CMAKE_BINARY_DIR}/res) make_directory(${CMAKE_BINARY_DIR}/resServer)
# Create a /logs directory # Create a /logs directory
make_directory(${CMAKE_BINARY_DIR}/logs) make_directory(${CMAKE_BINARY_DIR}/logs)
@ -176,6 +176,7 @@ set(INCLUDED_DIRECTORIES
"dScripts/ai" "dScripts/ai"
"dScripts/client" "dScripts/client"
"dScripts/EquipmentScripts" "dScripts/EquipmentScripts"
"dScripts/EquipmentTriggers"
"dScripts/zone" "dScripts/zone"
"dScripts/02_server/DLU" "dScripts/02_server/DLU"
"dScripts/02_server/Enemy" "dScripts/02_server/Enemy"

View File

@ -23,10 +23,7 @@
"name": "ci-macos-11", "name": "ci-macos-11",
"displayName": "CI configure step for MacOS", "displayName": "CI configure step for MacOS",
"description": "Same as default, Used in GitHub actions workflow", "description": "Same as default, Used in GitHub actions workflow",
"inherits": "default", "inherits": "default"
"cacheVariables": {
"OPENSSL_ROOT_DIR": "/usr/local/opt/openssl@3/"
}
}, },
{ {
"name": "ci-windows-2022", "name": "ci-windows-2022",

View File

@ -8,15 +8,17 @@ LICENSE=AGPL-3.0
# 171022 - Unmodded client # 171022 - Unmodded client
NET_VERSION=171022 NET_VERSION=171022
# Debugging # Debugging
__dynamic=1
# Set __dynamic to 1 to enable the -rdynamic flag for the linker, yielding some symbols in crashlogs. # Set __dynamic to 1 to enable the -rdynamic flag for the linker, yielding some symbols in crashlogs.
# __ggdb=1 __dynamic=1
# Set __ggdb to 1 to enable the -ggdb flag for the linker, including more debug info. # Set __ggdb to 1 to enable the -ggdb flag for the linker, including more debug info.
# __include_backtrace__=1 # __ggdb=1
# Set __include_backtrace__ to 1 to includes the backtrace library for better crashlogs. # Set __include_backtrace__ to 1 to includes the backtrace library for better crashlogs.
# __compile_backtrace__=1 # __include_backtrace__=1
# Set __compile_backtrace__ to 1 to compile the backtrace library instead of using system libraries. # Set __compile_backtrace__ to 1 to compile the backtrace library instead of using system libraries.
__maria_db_connector_compile_jobs__=1 # __compile_backtrace__=1
# Set to the number of jobs (make -j equivalent) to compile the mariadbconn files with. # Set to the number of jobs (make -j equivalent) to compile the mariadbconn files with.
__enable_testing__=1 __maria_db_connector_compile_jobs__=1
# When set to 1 and uncommented, compiling and linking testing folders and libraries will be done. # When set to 1 and uncommented, compiling and linking testing folders and libraries will be done.
__enable_testing__=1
# The path to OpenSSL. Change this if your OpenSSL install path is different than the default.
OPENSSL_ROOT_DIR=/usr/local/opt/openssl@3/

View File

@ -4,7 +4,7 @@
- [Docker](https://docs.docker.com/get-docker/) (Docker Desktop or on Linux normal Docker) - [Docker](https://docs.docker.com/get-docker/) (Docker Desktop or on Linux normal Docker)
- [Docker Compose](https://docs.docker.com/compose/install/) (Included in Docker Desktop) - [Docker Compose](https://docs.docker.com/compose/install/) (Included in Docker Desktop)
- LEGO® Universe packed Client. Check the main [README](./README.md) for details on this. - LEGO® Universe Client. Check the main [README](./README.md) for details on this.
## Run server inside Docker ## Run server inside Docker

View File

@ -25,7 +25,7 @@
11. Once the command has completed (you can see you path again and can enter commands), close the window. 11. Once the command has completed (you can see you path again and can enter commands), close the window.
12. Inside the downloaded folder, copy `.env.example` and name the copy `.env` 12. Inside the downloaded folder, copy `.env.example` and name the copy `.env`
13. Open `.env` with Notepad by right-clicking it and selecting _Open With_ -> _More apps_ -> _Notepad_. 13. Open `.env` with Notepad by right-clicking it and selecting _Open With_ -> _More apps_ -> _Notepad_.
14. Change the text after `CLIENT_PATH=` to the location of your client. The folder you are pointing to must contain a folder called `client` which should contain the client files. 14. Change the text after `CLIENT_PATH=` to the location of your client. This folder must contain either a folder `client` or `legouniverse.exe`.
> If you need the extra performance, place the client files in `\\wsl$\<your linux OS>\...` to avoid working across file systems, see [Docker Best Practices](https://docs.docker.com/desktop/windows/wsl/#best-practices) and [WSL documentation](https://docs.microsoft.com/en-us/windows/wsl/filesystems#file-storage-and-performance-across-file-systems). > If you need the extra performance, place the client files in `\\wsl$\<your linux OS>\...` to avoid working across file systems, see [Docker Best Practices](https://docs.docker.com/desktop/windows/wsl/#best-practices) and [WSL documentation](https://docs.microsoft.com/en-us/windows/wsl/filesystems#file-storage-and-performance-across-file-systems).
15. Optionally, you can change the number after `BUILD_THREADS=` to the number of cores / threads your processor has. If your computer crashes while building, you can try to reduce this value. 15. Optionally, you can change the number after `BUILD_THREADS=` to the number of cores / threads your processor has. If your computer crashes while building, you can try to reduce this value.

611
README.md
View File

@ -18,210 +18,188 @@ Darkflame Universe is licensed under AGPLv3, please read [LICENSE](LICENSE). Som
Throughout the entire build and setup process a level of familiarity with the command line and preferably a Unix-like development environment is greatly advantageous. Throughout the entire build and setup process a level of familiarity with the command line and preferably a Unix-like development environment is greatly advantageous.
### Hosting a server ### Hosting a server
We do not recommend hosting public servers. DLU is intended for small scale deployment, for example within a group of friends. It has not been tested for large scale deployment which comes with additional security risks. We do not recommend hosting public servers. Darkflame Universe is intended for small scale deployment, for example within a group of friends. It has not been tested for large scale deployment which comes with additional security risks.
### Supply of resource files ### Supply of resource files
Darkflame Universe is a server emulator and does not distribute any LEGO® Universe files. A separate game client is required to setup this server emulator and play the game, which we cannot supply. Users are strongly suggested to refer to the safe checksums listed in the resources tab below when checking if a client will work. Darkflame Universe is a server emulator and does not distribute any LEGO® Universe files. A separate game client is required to setup this server emulator and play the game, which we cannot supply. Users are strongly suggested to refer to the safe checksums listed [here](#verifying-your-client-files) to see if a client will work.
## Build ## Steps to setup server
Development of the latest iteration of Darkflame Universe has been done primarily in a Unix-like environment and is where it has been tested and designed for deployment. It is therefore highly recommended that Darkflame Universe be built and deployed using a Unix-like environment for the most streamlined experience. * [Clone this repository](#clone-the-repository)
* [Install dependencies](#install-dependencies)
* [Database setup](#database-setup)
* [Build the server](#build-the-server)
* [Configuring your server](#configuring-your-server)
* [Required Configuration](#required-configuration)
* [Optional Configuration](#optional-configuration)
* [Verify your setup](#verify-your-setup)
* [Running the server](#running-the-server)
* [User Guide](#user-guide)
### Prerequisites ## Clone the repository
#### Clone the repository If you are on Windows, you will need to download and install git from [here](https://git-scm.com/download/win)
Then run the following command
```bash ```bash
git clone --recursive https://github.com/DarkflameUniverse/DarkflameServer git clone --recursive https://github.com/DarkflameUniverse/DarkflameServer
``` ```
#### Python
Some tools utilized to streamline the setup process require Python 3, make sure you have it installed. ## Install dependencies
### Windows packages
Ensure that you have either the [MSVC C++ compiler](https://visualstudio.microsoft.com/vs/features/cplusplus/) (recommended) or the [Clang compiler](https://github.com/llvm/llvm-project/releases/) installed.
You'll also need to download and install [CMake](https://cmake.org/download/) (version <font size="4">**CMake version 3.18**</font> or later!).
### Choosing the right version for your client ### MacOS packages
DLU clients identify themselves using a higher version number than the regular live clients out there. Ensure you have [brew](https://brew.sh) installed.
This was done make sure that older and incomplete clients wouldn't produce false positive bug reports for us, and because we made bug fixes and new content for the client. You will need to install the following packages
```bash
brew install cmake gcc mariadb openssl zlib
```
If you're using a DLU client you'll have to go into the "CMakeVariables.txt" file and change the NET_VERSION variable to 171023 to match the modified client's version number. ### Linux packages
Make sure packages like `gcc`, and `zlib` are installed. Depending on the distribution, these packages might already be installed. Note that on systems like Ubuntu, you will need the `zlib1g-dev` package so that the header files are available. `libssl-dev` will also be required as well as `openssl`. You will also need a MySQL database solution to use. We recommend using `mariadb-server`.
### Enabling testing For Ubuntu, you would run the following commands. On other systems, the package install command will differ.
While it is highly recommended to enable testing, if you would like to save compilation time, you'll want to comment out the enable_testing variable in CMakeVariables.txt.
It is recommended that after building and if testing is enabled, to run `ctest` and make sure all the tests pass.
### Using Docker ```bash
Refer to [Docker.md](/Docker.md). sudo apt update && sudo apt upgrade
For Windows, refer to [Docker_Windows.md](/Docker_Windows.md). # Install packages
sudo apt install build-essential gcc zlib1g-dev libssl-dev openssl mariadb-server cmake
```
### Linux builds #### Required CMake version
Make sure packages like `gcc`, `cmake`, and `zlib` are installed. Depending on the distribution, these packages might already be installed. Note that on systems like Ubuntu, you will need the `zlib1g-dev` package so that the header files are available. `libssl-dev` will also be required as well as `openssl`. 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.
You can check your CMake version by using the following command in a terminal.
```bash
cmake --version
```
CMake must be version 3.14 or higher! If you are going to be using an Ubuntu environment to run the server, you may need to get a more recent version of `cmake` than the packages available may provide.
#### Build the repository The general approach to do so would be to obtain a copy of the signing key and then add the CMake repository to your apt.
You can do so with the following commands.
[Source of the below commands](https://askubuntu.com/questions/355565/how-do-i-install-the-latest-version-of-cmake-from-the-command-line)
```bash
# Remove the old version of CMake
sudo apt purge --auto-remove cmake
# Prepare for installation
sudo apt update && sudo apt install -y software-properties-common lsb-release && sudo apt clean all
# Obtain a copy of the signing key
wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | gpg --dearmor - | sudo tee /etc/apt/trusted.gpg.d/kitware.gpg >/dev/null
# Add the repository to your sources list.
sudo apt-add-repository "deb https://apt.kitware.com/ubuntu/ $(lsb_release -cs) main"
# Next you'll want to ensure that Kitware's keyring stays up to date
sudo apt update
sudo apt install kitware-archive-keyring
sudo rm /etc/apt/trusted.gpg.d/kitware.gpg
# If sudo apt update above returned an error, copy the public key at the end of the error message and run the following command
# if the error message was "The following signatures couldn't be verified because the public key is not available: NO_PUBKEY 6AF7F09730B3F0A4"
# then the below command would be "sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 6AF7F09730B3F0A4"
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys <TheCopiedPublicKey>
# Finally update and install
sudo apt update
sudo apt install cmake
```
## Database setup
First you'll need to start MariaDB.
For Windows the service is always running by default.
For MacOS, run the following command
```bash
brew services start mariadb
```
For Linux, run the following command
```bash
sudo systemctl start mysql
# If systemctl is not a known command on your distribution, try the following instead
sudo service mysql start
```
<font size="4">**You will need to run this command every time you restart your environment**</font>
If you are using Linux and `systemctl` and want the MariaDB instance to start on startup, run the following command
```bash
sudo systemctl enable --now mysql
```
Once MariaDB is started, you'll need to create a user and an empty database for Darkflame Universe to use.
First, login to the MariaDB instance.
To do this on Ubuntu/Linux, MacOS, or another Unix like operating system, run the following command in a terminal
```bash
# Logs you into the MariaDB instance as root
sudo mysql
```
For Windows, run the following command in the `Command Prompt (MariaDB xx.xx)` terminal
```bash
# Logs you into the mysql instance
mysql -u root -p
# You will then be prompted for the password you set for root during installation of MariaDB
```
Now that you are logged in, run the following commands.
```bash
# Creates a user for this computer which uses a password and grant said user all privileges.
# Change mydarkflameuser to a custom username and password to a custom password.
GRANT ALL ON *.* TO 'mydarkflameuser'@'localhost' IDENTIFIED BY 'password' WITH GRANT OPTION;
FLUSH PRIVILEGES;
# Then create a database for Darkflame Universe to use.
CREATE DATABASE darkflame;
```
## Build the server
You can either run `build.sh` when in the root folder of the repository: You can either run `build.sh` when in the root folder of the repository:
```bash ```bash
./build.sh ./build.sh
``` ```
Or manually run the commands used in `build.sh`: Or manually run the commands used in [build.sh](build.sh).
```bash ### Notes
# Create the build directory, preserving it if it already exists Depending on your operating system, you may need to adjust some pre-processor defines in [CMakeVariables.txt](./CMakeVariables.txt) before building:
mkdir -p build * If you are on MacOS, ensure OPENSSL_ROOT_DIR is pointing to the openssl root directory.
cd build * If you are using a Darkflame Universe client, ensure NET_VERSION is changed to 171023.
# Run CMake to generate make files ## Configuring your server
cmake .. This server has a few steps that need to be taken to configure the server for your use case.
# To build utilizing multiple cores, append `-j` and the amount of cores to utilize, for example `cmake --build . --config Release -j8' ### Required Configuration
cmake --build . --config Release Darkflame Universe can run with either a packed or an unpacked client.
``` Navigate to `build/sharedconfig.ini` and fill in the following fields:
* `mysql_host` (This is the IP address or hostname of your MariaDB server. This is highly likely `localhost`)
* If you setup your MariaDB instance on a port other than 3306, which can be done on a Windows install, you will need to make this value `tcp://localhost:portNum` where portNum is replaced with the port you chose to run MariaDB on.
* `mysql_database` (This is the database you created for the server)
* `mysql_username` (This is the user you created for the server)
* `mysql_password` (This is the password for the user you created for the server)
* `client_location` (This is the location of the client files. This should be the folder path of a packed or unpacked client)
* Ideally the path to the client should not contain any spaces.
### MacOS builds ### Optional Configuration
Ensure `cmake`, `zlib` and `open ssl` are installed as well as a compiler (e.g `clang` or `gcc`). * After the server has been built there should be five `ini` files in the build directory: `sharedconfig.ini`, `authconfig.ini`, `chatconfig.ini`, `masterconfig.ini`, and `worldconfig.ini`.
* `authconfig.ini` contains an option to enable or disable play keys on your server. Do not change the default port for auth.
In the repository root folder run the following. Ensure -DOPENSSL_ROOT_DIR=/path/to/openssl points to your openssl install location * `chatconfig.ini` contains a port option.
```bash * `masterconfig.ini` contains options related to permissions you want to run your servers with.
# Create the build directory, preserving it if it already exists * `sharedconfig.ini` contains several options that are shared across all servers
mkdir -p build * `worldconfig.ini` contains several options to turn on QOL improvements should you want them. If you would like the most vanilla experience possible, you will need to turn some of these settings off.
cd build
# Run CMake to generate build files
cmake .. -DOPENSSL_ROOT_DIR=/path/to/openssl
# Get cmake to build the project. If make files are being used then using make and appending `-j` and the amount of cores to utilize may be preferable, for example `make -j8`
cmake --build . --config Release
```
### Windows builds (native)
Ensure that you have either the [MSVC](https://visualstudio.microsoft.com/vs/) or the [Clang](https://github.com/llvm/llvm-project/releases/) (recommended) compiler installed. You will also need to install [CMake](https://cmake.org/download/). Currently on native Windows the server will only work in Release mode.
#### Build the repository
```batch
:: Create the build directory
mkdir build
cd build
:: Run CMake to generate make files
cmake ..
:: Run CMake with build flag to build
cmake --build . --config Release
```
#### Windows for ARM has not been tested but should build by doing the following
```batch
:: Create the build directory
mkdir build
cd build
:: Run CMake to generate make files
cmake .. -DMARIADB_BUILD_SOURCE=ON
:: Run CMake with build flag to build
cmake --build . --config Release
```
### Windows builds (WSL)
This section will go through how to install [WSL](https://docs.microsoft.com/en-us/windows/wsl/install) and building in a Linux environment under Windows. WSL requires Windows 10 version 2004 and higher (Build 19041 and higher) or Windows 11.
#### Open the Command Prompt application with Administrator permissions and run the following:
```bash
# Installing Windows Subsystem for Linux
wsl --install
```
#### Open the Ubuntu application and run the following:
```bash
# Make sure the install is up to date
apt update && apt upgrade
# Make sure the gcc, cmake, and build-essentials are installed
sudo apt install gcc
sudo apt install cmake
sudo apt install build-essential
```
[**Follow the Linux instructions**](#linux-builds)
### ARM builds
AArch64 builds should work on linux and MacOS using their respective build steps. Windows ARM should build but it has not been tested
### Updating your build
To update your server to the latest version navigate to your cloned directory
```bash
cd /path/to/DarkflameServer
```
run the following commands to update to the latest changes
```bash
git pull
git submodule update --init --recursive
```
now follow the build section for your system
## Setting up the environment
### Resources
#### LEGO® Universe 1.10.64
This repository does not distribute any LEGO® Universe files. A full install of LEGO® Universe version 1.10.64 (latest) is required to finish setting up Darkflame Universe.
Known good SHA256 checksums of the client:
- `8f6c7e84eca3bab93232132a88c4ae6f8367227d7eafeaa0ef9c40e86c14edf5` (packed client, rar compressed)
- `c1531bf9401426042e8bab2de04ba1b723042dc01d9907c2635033d417de9e05` (packed client, includes extra locales, rar compressed)
- `0d862f71eedcadc4494c4358261669721b40b2131101cbd6ef476c5a6ec6775b` (unpacked client, includes extra locales, rar compressed)
Known good *SHA1* checksum of the DLU client:
- `91498e09b83ce69f46baf9e521d48f23fe502985` (packed client, zip compressed)
How to generate a SHA256 checksum:
```bash
# Replace <file> with the file path to the client
# If on Linux or MacOS
shasum -a 256 <file>
# If on Windows
certutil -hashfile <file> SHA256
```
#### Unpacking the client
* Clone lcdr's utilities repository [here](https://github.com/lcdr/utils)
* Use `pkextractor.pyw` to unpack the client files if they are not already unpacked
#### Setup resource directory
* In the `build` directory create a `res` directory if it does not already exist.
* Copy over or create symlinks from `macros`, `BrickModels`, `chatplus_en_us.txt`, `names`, and `maps` in your client `res` directory to the server `build/res` directory
* Unzip the navmeshes [here](./resources/navmeshes.zip) and place them in `build/res/maps/navmeshes`
#### Setup locale
* In the `build` directory create a `locale` directory if it does not already exist
* Copy over or create symlinks from `locale.xml` in your client `locale` directory to the `build/locale` directory
#### Client database
* Move the file `res/cdclient.fdb` from the unpacked client to the `build/res` folder on the server.
* The server will automatically copy and convert the file from fdb to sqlite should `CDServer.sqlite` not already exist.
* You can also convert the database manually using `fdb_to_sqlite.py` using lcdr's utilities. Just make sure to rename the file to `CDServer.sqlite` instead of `cdclient.sqlite`.
* Migrations to the database are automatically run on server start. When migrations are needed to be ran, the server may take a bit longer to start.
### Database
Darkflame Universe utilizes a MySQL/MariaDB database for account and character information.
Initial setup can vary drastically based on which operating system or distribution you are running; there are instructions out there for most setups, follow those and come back here when you have a database up and running.
* All that you need to do is create a database to connect to. As long as the server can connect to the database, the schema will always be kept up to date when you start the server.
#### Configuration
After the server has been built there should be four `ini` files in the build director: `sharedconfig.ini`, `authconfig.ini`, `chatconfig.ini`, `masterconfig.ini`, and `worldconfig.ini`. Go through them and fill in the database credentials and configure other settings if necessary.
#### Migrations
The database is automatically setup and migrated to what it should look like for the latest commit whenever you start the server.
#### Verify
## Verify your setup
Your build directory should now look like this: Your build directory should now look like this:
* AuthServer * AuthServer
* ChatServer * ChatServer
@ -230,42 +208,35 @@ Your build directory should now look like this:
* authconfig.ini * authconfig.ini
* chatconfig.ini * chatconfig.ini
* masterconfig.ini * masterconfig.ini
* sharedconfig.ini
* worldconfig.ini * worldconfig.ini
* **locale/**
* locale.xml
* **res/**
* cdclient.fdb
* chatplus_en_us.txt
* **macros/**
* ...
* **BrickModels/**
* ...
* **maps/**
* **navmeshes/**
* ...
* ...
* ... * ...
## Running the server ## Running the server
If everything has been configured correctly you should now be able to run the `MasterServer` binary. Darkflame Universe utilizes port numbers under 1024, so under Linux you either have to give the binary network permissions or run it under sudo. If everything has been configured correctly you should now be able to run the `MasterServer` binary which is located in the `build` directory. Darkflame Universe utilizes port numbers under 1024, so under Linux you either have to give the `AuthServer` binary network permissions or run it under sudo.
To give `AuthServer` network permissions and not require sudo, run the following command
```bash
sudo setcap 'cap_net_bind_service=+ep' AuthServer
```
and then go to `build/masterconfig.ini` and change `use_sudo_auth` to 0.
### First admin user ### First admin user
Run `MasterServer -a` to get prompted to create an admin account. This method is only intended for the system administrator as a means to get started, do NOT use this method to create accounts for other users! Run `MasterServer -a` to get prompted to create an admin account. This method is only intended for the system administrator as a means to get started, do NOT use this method to create accounts for other users!
### Account Manager ### Account management tool (Nexus Dashboard)
**If you are just using this server for yourself, you can skip setting up Nexus Dashboard**
Follow the instructions [here](https://github.com/DarkflameUniverse/AccountManager) to setup the DLU account management Python web application. This is the intended way for users to create accounts. Follow the instructions [here](https://github.com/DarkflameUniverse/NexusDashboard) to setup the DLU Nexus Dashboard web application. This is the intended way for users to create accounts and the intended way for moderators to approve names/pets/properties and do other moderation actions.
### Admin levels ### Admin levels
The admin level, or Game Master level (hereafter referred to as gmlevel), is specified in the `accounts.gm_level` column in the MySQL database. Normal players should have this set to `0`, which comes with no special privileges. The system administrator will have this set to `9`, which comes will all privileges. gmlevel `8` should be used to give a player a majority of privileges without the safety critical once.
The admin level, or game master level, is specified in the `accounts.gm_level` column in the MySQL database. Normal players should have this set to `0`, which comes with no special privileges. The system administrator will have this set to `9`, which comes will all privileges. Admin level `8` should be used to give a player a majority of privileges without the safety critical once. While a character has a gmlevel of anything but `0`, some gameplay behavior will change. When testing gameplay, you should always use a character with a gmlevel of `0`.
While a character has a gmlevel of anything but 0, some gameplay behavior will change. When testing gameplay, you should always use a character with a gmlevel of 0. # User guide
Some changes to the client `boot.cfg` file are needed to play on your server.
## User guide ## Allowing a user to connect to your server
A few modifications have to be made to the client.
### Client configuration
To connect to a server follow these steps: To connect to a server follow these steps:
* In the client directory, locate `boot.cfg` * In the client directory, locate `boot.cfg`
* Open it in a text editor and locate where it says `AUTHSERVERIP=0:` * Open it in a text editor and locate where it says `AUTHSERVERIP=0:`
@ -273,159 +244,88 @@ To connect to a server follow these steps:
* Launch `legouniverse.exe`, through `wine` if on a Unix-like operating system * Launch `legouniverse.exe`, through `wine` if on a Unix-like operating system
* Note that if you are on WSL2, you will need to configure the public IP in the server and client to be the IP of the WSL2 instance and not localhost, which can be found by running `ifconfig` in the terminal. Windows defaults to WSL1, so this will not apply to most users. * Note that if you are on WSL2, you will need to configure the public IP in the server and client to be the IP of the WSL2 instance and not localhost, which can be found by running `ifconfig` in the terminal. Windows defaults to WSL1, so this will not apply to most users.
### Brick-By-Brick building ## Brick-By-Brick building
Should you choose to do any brick building, you will want to have some form of a http server that returns a 404 error since we are unable to emulate live User Generated Content at the moment. If you attempt to do any brick building without a 404 server running properly, you will be unable to load into your game. Python is the easiest way to do this, but any thing that returns a 404 should work fine.
* Note: the client hard codes this request on port 80.
Brick-By-Brick building requires `PATCHSERVERIP=0:` in the `boot.cfg` to point to a HTTP server which always returns `HTTP 404 - Not Found` for all requests. This can be achieved by pointing it to `localhost` while having `sudo python -m http.server 80` running in the background. <font size="4">**If you do not plan on doing any Brick Building, then you can skip this step.**</font>
### In-game commands The easiest way to do this is to install [python](https://www.python.org/downloads/).
Here is a summary of the commands available in-game. All commands are prefixed by `/` and typed in the in-game chat window. Some commands requires admin privileges. Operands within `<>` are required, operands within `()` are not. For the full list of in-game commands, please checkout [the source file](./dGame/dUtilities/SlashCommandHandler.cpp).
<table> ### Allowing a user to build in Brick-by-Brick mode
<thead> Brick-By-Brick building requires `PATCHSERVERIP=0:` and `UGCSERVERIP=0:` in the `boot.cfg` to point to a HTTP server which always returns `HTTP 404 - Not Found` for all requests. This can be most easily achieved by pointing both of those variables to `localhost` while having running in the background.
<th> Each client must have their own 404 server running if they are using a locally hosted 404 server.
Command ```bash
</th> # If on linux run this command. Because this is run on a port below 1024, binary network permissions are needed.
<th> sudo python3 -m http.server 80
Usage
</th> # If on windows one of the following will work when run through Powershell or Command Prompt assuming python is installed
<th> python3 -m http.server 80
Description python http.server 80
</th> py -m http.server 80
<th> ```
Admin Level Requirement
</th> ## Updating your server
</thead> To update your server to the latest version navigate to your cloned directory
<tbody> ```bash
<tr> cd path/to/DarkflameServer
<td> ```
info Run the following commands to update to the latest changes
</td> ```bash
<td> git pull
/info git submodule update --init --recursive
</td> ```
<td> Now follow the [build](#build-the-server) section for your system and your server is up to date.
Displays server info to the user, including where to find the server's source code.
</td> ## In-game commands
<td> * A list of all in-game commands can be found [here](./docs/Commands.md).
</td>
</tr> ## Verifying your client files
<tr>
<td> ### LEGO® Universe 1.10.64
credits To verify that you are indeed using a LEGO® Universe 1.10.64 client, make sure you have the full client compressed **in a rar file** and run the following command.
</td> ```bash
<td> # Replace <file> with the file path to the zipped client
/credits
</td> # If on Linux or MacOS
<td> shasum -a 256 <file>
Displays the names of the people behind Darkflame Universe.
</td> # If on Windows using the Command Prompt
<td> certutil -hashfile <file> SHA256
</td> ```
</tr>
<tr> Below are known good SHA256 checksums of the client:
<td> * `8f6c7e84eca3bab93232132a88c4ae6f8367227d7eafeaa0ef9c40e86c14edf5` (packed client, rar compressed)
instanceinfo * `c1531bf9401426042e8bab2de04ba1b723042dc01d9907c2635033d417de9e05` (packed client, includes extra locales, rar compressed)
</td> * `0d862f71eedcadc4494c4358261669721b40b2131101cbd6ef476c5a6ec6775b` (unpacked client, includes extra locales, rar compressed)
<td>
/instanceinfo If the returned hash matches one of the lines above then you can continue with setting up the server. If you are using a fully downloaded and complete client from live, then it will work, but the hash above may not match. Otherwise you must obtain a full install of LEGO® Universe 1.10.64.
</td>
<td> ### Darkflame Universe Client
Displays in the chat the current zone, clone, and instance id. Darkflame Universe clients identify themselves using a higher version number than the regular live clients out there.
</td> This was done make sure that older and incomplete clients wouldn't produce false positive bug reports for us, and because we made bug fixes and new content for the client.
<td>
</td> To verify that you are indeed using a Darkflame Universe client, make sure you have the full client compressed **in a zip file** and run the following command.
</tr>
<tr> ```bash
<td> # Replace <file> with the file path to the zipped client
gmlevel
</td> # If on Linux or MacOS
<td> shasum -a 1 <file>
/gmlevel &#60;level&#62;
</td> # If on Windows using the Command Prompt
<td> certutil -hashfile <file> SHA1
Within the authorized range of levels for the current account, changes the character's game master level to the specified value. This is required to use certain commands. ```
</td>
<td> Known good *SHA1* checksum of the Darkflame Universe client:
</td> - `91498e09b83ce69f46baf9e521d48f23fe502985` (packed client, zip compressed)
</tr>
<tr> # Development Documentation
<td> This is a Work in Progress, but below are some quick links to documentaion for systems and structs in the server
testmap [Networked message structs](https://lcdruniverse.org/lu_packets/lu_packets/index.html)
</td> [General system documentation](https://docs.lu-dev.net/en/latest/index.html)
<td>
/testmap &#60;zone&#62; (clone-id)
</td>
<td>
Transfers you to the given zone by id and clone id.
</td>
<td>
1
</td>
</tr>
<tr>
<td>
ban
</td>
<td>
/ban &#60;username&#62;
</td>
<td>
Bans a user from the server.
</td>
<td>
4
</td>
</tr>
<tr>
<td>
gmadditem
</td>
<td>
/gmadditem &#60;id&#62; (count)
</td>
<td>
Adds the given item to your inventory by id.
</td>
<td>
8
</td>
</tr>
<tr>
<td>
spawn
</td>
<td>
/spawn &#60;id&#62;
</td>
<td>
Spawns an object at your location by id.
</td>
<td>
8
</td>
</tr>
<tr>
<td>
metrics
</td>
<td>
/metrics
</td>
<td>
Prints some information about the server's performance.
</td>
<td>
8
</td>
</tr>
</tbody>
</table>
# Credits # Credits
## Active Contributors
* [EmosewaMC](https://github.com/EmosewaMC)
* [Jettford](https://github.com/Jettford)
* [Aaron K.](https://github.com/aronwk-aaron)
## DLU Team ## DLU Team
* [DarwinAnim8or](https://github.com/DarwinAnim8or) * [DarwinAnim8or](https://github.com/DarwinAnim8or)
@ -434,25 +334,30 @@ Here is a summary of the commands available in-game. All commands are prefixed b
* [averysumner](https://github.com/codeshaunted) * [averysumner](https://github.com/codeshaunted)
* [Jon002](https://github.com/jaller200) * [Jon002](https://github.com/jaller200)
* [Jonny](https://github.com/cuzitsjonny) * [Jonny](https://github.com/cuzitsjonny)
* [Aaron K.](https://github.com/aronwk-aaron)
### Research and tools ### Research and Tools
* [lcdr](https://github.com/lcdr) * [lcdr](https://github.com/lcdr)
* [Xiphoseer](https://github.com/Xiphoseer) * [Xiphoseer](https://github.com/Xiphoseer)
### Community management ### Community Management
* [Neal](https://github.com/NealSpellman) * [Neal](https://github.com/NealSpellman)
### Former contributors ### Logo
* Cole Peterson (BlasterBuilder)
## Active Contributors
* [EmosewaMC](https://github.com/EmosewaMC)
* [Jettford](https://github.com/Jettford)
## Former Contributors
* TheMachine * TheMachine
* Matthew * Matthew
* [Raine](https://github.com/Rainebannister) * [Raine](https://github.com/Rainebannister)
* Bricknave * Bricknave
### Logo ## Special Thanks
* Cole Peterson (BlasterBuilder)
## Special thanks
* humanoid24 * humanoid24
* pwjones1969 * pwjones1969
* [Simon](https://github.com/SimonNitzsche) * [Simon](https://github.com/SimonNitzsche)
* ALL OF THE NETDEVIL AND LEGO TEAMS! * [ALL OF THE NETDEVIL AND LEGO TEAMS!](https://www.mobygames.com/game/macintosh/lego-universe/credits)

View File

@ -22,37 +22,40 @@
#include "Game.h" #include "Game.h"
namespace Game { namespace Game {
dLogger* logger; dLogger* logger = nullptr;
dServer* server; dServer* server = nullptr;
dConfig* config; dConfig* config = nullptr;
bool shouldShutdown = false;
} }
dLogger* SetupLogger(); dLogger* SetupLogger();
void HandlePacket(Packet* packet); void HandlePacket(Packet* packet);
int main(int argc, char** argv) { int main(int argc, char** argv) {
constexpr uint32_t authFramerate = mediumFramerate;
constexpr uint32_t authFrameDelta = mediumFrameDelta;
Diagnostics::SetProcessName("Auth"); Diagnostics::SetProcessName("Auth");
Diagnostics::SetProcessFileName(argv[0]); Diagnostics::SetProcessFileName(argv[0]);
Diagnostics::Initialize(); Diagnostics::Initialize();
//Create all the objects we need to run our service: //Create all the objects we need to run our service:
Game::logger = SetupLogger(); Game::logger = SetupLogger();
if (!Game::logger) return 0; if (!Game::logger) return EXIT_FAILURE;
//Read our config:
Game::config = new dConfig((BinaryPathFinder::GetBinaryDir() / "authconfig.ini").string());
Game::logger->SetLogToConsole(Game::config->GetValue("log_to_console") != "0");
Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1");
Game::logger->Log("AuthServer", "Starting Auth server..."); Game::logger->Log("AuthServer", "Starting Auth server...");
Game::logger->Log("AuthServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); Game::logger->Log("AuthServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR);
Game::logger->Log("AuthServer", "Compiled on: %s", __TIMESTAMP__); Game::logger->Log("AuthServer", "Compiled on: %s", __TIMESTAMP__);
//Read our config:
dConfig config("authconfig.ini");
Game::config = &config;
Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console"))));
Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1");
//Connect to the MySQL Database //Connect to the MySQL Database
std::string mysql_host = config.GetValue("mysql_host"); std::string mysql_host = Game::config->GetValue("mysql_host");
std::string mysql_database = config.GetValue("mysql_database"); std::string mysql_database = Game::config->GetValue("mysql_database");
std::string mysql_username = config.GetValue("mysql_username"); std::string mysql_username = Game::config->GetValue("mysql_username");
std::string mysql_password = config.GetValue("mysql_password"); std::string mysql_password = Game::config->GetValue("mysql_password");
try { try {
Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password);
@ -61,12 +64,12 @@ int main(int argc, char** argv) {
Database::Destroy("AuthServer"); Database::Destroy("AuthServer");
delete Game::server; delete Game::server;
delete Game::logger; delete Game::logger;
return 0; return EXIT_FAILURE;
} }
//Find out the master's IP: //Find out the master's IP:
std::string masterIP; std::string masterIP;
int masterPort = 1500; uint32_t masterPort = 1500;
sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';"); sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';");
auto res = stmt->executeQuery(); auto res = stmt->executeQuery();
while (res->next()) { while (res->next()) {
@ -78,26 +81,28 @@ int main(int argc, char** argv) {
delete stmt; delete stmt;
//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.
int maxClients = 50; uint32_t maxClients = 50;
int ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default. uint32_t ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default.
if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients"));
if (config.GetValue("port") != "") ourPort = std::atoi(config.GetValue("port").c_str()); if (Game::config->GetValue("port") != "") ourPort = std::atoi(Game::config->GetValue("port").c_str());
Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Auth, Game::config); Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Auth, Game::config, &Game::shouldShutdown);
//Run it until server gets a kill message from Master: //Run it until server gets a kill message from Master:
auto t = std::chrono::high_resolution_clock::now(); auto t = std::chrono::high_resolution_clock::now();
Packet* packet = nullptr; Packet* packet = nullptr;
int framesSinceLastFlush = 0; constexpr uint32_t logFlushTime = 30 * authFramerate; // 30 seconds in frames
int framesSinceMasterDisconnect = 0; constexpr uint32_t sqlPingTime = 10 * 60 * authFramerate; // 10 minutes in frames
int framesSinceLastSQLPing = 0; uint32_t framesSinceLastFlush = 0;
uint32_t framesSinceMasterDisconnect = 0;
uint32_t framesSinceLastSQLPing = 0;
while (true) { while (!Game::shouldShutdown) {
//Check if we're still connected to master: //Check if we're still connected to master:
if (!Game::server->GetIsConnectedToMaster()) { if (!Game::server->GetIsConnectedToMaster()) {
framesSinceMasterDisconnect++; framesSinceMasterDisconnect++;
if (framesSinceMasterDisconnect >= 30) if (framesSinceMasterDisconnect >= authFramerate)
break; //Exit our loop, shut down. break; //Exit our loop, shut down.
} else framesSinceMasterDisconnect = 0; } else framesSinceMasterDisconnect = 0;
@ -113,16 +118,16 @@ int main(int argc, char** argv) {
} }
//Push our log every 30s: //Push our log every 30s:
if (framesSinceLastFlush >= 900) { if (framesSinceLastFlush >= logFlushTime) {
Game::logger->Flush(); Game::logger->Flush();
framesSinceLastFlush = 0; framesSinceLastFlush = 0;
} else framesSinceLastFlush++; } else framesSinceLastFlush++;
//Every 10 min we ping our sql server to keep it alive hopefully: //Every 10 min we ping our sql server to keep it alive hopefully:
if (framesSinceLastSQLPing >= 40000) { if (framesSinceLastSQLPing >= sqlPingTime) {
//Find out the master's IP for absolutely no reason: //Find out the master's IP for absolutely no reason:
std::string masterIP; std::string masterIP;
int masterPort; uint32_t masterPort;
sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';"); sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';");
auto res = stmt->executeQuery(); auto res = stmt->executeQuery();
while (res->next()) { while (res->next()) {
@ -137,7 +142,7 @@ int main(int argc, char** argv) {
} else framesSinceLastSQLPing++; } else framesSinceLastSQLPing++;
//Sleep our thread since auth can afford to. //Sleep our thread since auth can afford to.
t += std::chrono::milliseconds(mediumFramerate); //Auth can run at a lower "fps" t += std::chrono::milliseconds(authFrameDelta); //Auth can run at a lower "fps"
std::this_thread::sleep_until(t); std::this_thread::sleep_until(t);
} }
@ -145,8 +150,8 @@ int main(int argc, char** argv) {
Database::Destroy("AuthServer"); Database::Destroy("AuthServer");
delete Game::server; delete Game::server;
delete Game::logger; delete Game::logger;
delete Game::config;
exit(EXIT_SUCCESS);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }

View File

@ -19,16 +19,18 @@
#include "ChatPacketHandler.h" #include "ChatPacketHandler.h"
#include "Game.h" #include "Game.h"
namespace Game {
dLogger* logger;
dServer* server;
dConfig* config;
dChatFilter* chatFilter;
AssetManager* assetManager;
}
//RakNet includes: //RakNet includes:
#include "RakNetDefines.h" #include "RakNetDefines.h"
namespace Game {
dLogger* logger = nullptr;
dServer* server = nullptr;
dConfig* config = nullptr;
dChatFilter* chatFilter = nullptr;
AssetManager* assetManager = nullptr;
bool shouldShutdown = false;
}
dLogger* SetupLogger(); dLogger* SetupLogger();
void HandlePacket(Packet* packet); void HandlePacket(Packet* packet);
@ -36,25 +38,27 @@ void HandlePacket(Packet* packet);
PlayerContainer playerContainer; PlayerContainer playerContainer;
int main(int argc, char** argv) { int main(int argc, char** argv) {
constexpr uint32_t chatFramerate = mediumFramerate;
constexpr uint32_t chatFrameDelta = mediumFrameDelta;
Diagnostics::SetProcessName("Chat"); Diagnostics::SetProcessName("Chat");
Diagnostics::SetProcessFileName(argv[0]); Diagnostics::SetProcessFileName(argv[0]);
Diagnostics::Initialize(); Diagnostics::Initialize();
//Create all the objects we need to run our service: //Create all the objects we need to run our service:
Game::logger = SetupLogger(); Game::logger = SetupLogger();
if (!Game::logger) return 0; if (!Game::logger) return EXIT_FAILURE;
//Read our config:
Game::config = new dConfig((BinaryPathFinder::GetBinaryDir() / "chatconfig.ini").string());
Game::logger->SetLogToConsole(Game::config->GetValue("log_to_console") != "0");
Game::logger->SetLogDebugStatements(Game::config->GetValue("log_debug_statements") == "1");
Game::logger->Log("ChatServer", "Starting Chat server..."); Game::logger->Log("ChatServer", "Starting Chat server...");
Game::logger->Log("ChatServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR); Game::logger->Log("ChatServer", "Version: %i.%i", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR);
Game::logger->Log("ChatServer", "Compiled on: %s", __TIMESTAMP__); Game::logger->Log("ChatServer", "Compiled on: %s", __TIMESTAMP__);
//Read our config:
dConfig config("chatconfig.ini");
Game::config = &config;
Game::logger->SetLogToConsole(bool(std::stoi(config.GetValue("log_to_console"))));
Game::logger->SetLogDebugStatements(config.GetValue("log_debug_statements") == "1");
try { try {
std::string clientPathStr = config.GetValue("client_location"); std::string clientPathStr = Game::config->GetValue("client_location");
if (clientPathStr.empty()) clientPathStr = "./res"; if (clientPathStr.empty()) clientPathStr = "./res";
std::filesystem::path clientPath = std::filesystem::path(clientPathStr); std::filesystem::path clientPath = std::filesystem::path(clientPathStr);
if (clientPath.is_relative()) { if (clientPath.is_relative()) {
@ -69,10 +73,10 @@ int main(int argc, char** argv) {
} }
//Connect to the MySQL Database //Connect to the MySQL Database
std::string mysql_host = config.GetValue("mysql_host"); std::string mysql_host = Game::config->GetValue("mysql_host");
std::string mysql_database = config.GetValue("mysql_database"); std::string mysql_database = Game::config->GetValue("mysql_database");
std::string mysql_username = config.GetValue("mysql_username"); std::string mysql_username = Game::config->GetValue("mysql_username");
std::string mysql_password = config.GetValue("mysql_password"); std::string mysql_password = Game::config->GetValue("mysql_password");
try { try {
Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password); Database::Connect(mysql_host, mysql_database, mysql_username, mysql_password);
@ -81,12 +85,12 @@ int main(int argc, char** argv) {
Database::Destroy("ChatServer"); Database::Destroy("ChatServer");
delete Game::server; delete Game::server;
delete Game::logger; delete Game::logger;
return 0; return EXIT_FAILURE;
} }
//Find out the master's IP: //Find out the master's IP:
std::string masterIP; std::string masterIP;
int masterPort = 1000; uint32_t masterPort = 1000;
sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';"); sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';");
auto res = stmt->executeQuery(); auto res = stmt->executeQuery();
while (res->next()) { while (res->next()) {
@ -98,28 +102,30 @@ int main(int argc, char** argv) {
delete stmt; delete stmt;
//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.
int maxClients = 50; uint32_t maxClients = 50;
int ourPort = 1501; uint32_t ourPort = 1501;
if (config.GetValue("max_clients") != "") maxClients = std::stoi(config.GetValue("max_clients")); if (Game::config->GetValue("max_clients") != "") maxClients = std::stoi(Game::config->GetValue("max_clients"));
if (config.GetValue("port") != "") ourPort = std::atoi(config.GetValue("port").c_str()); if (Game::config->GetValue("port") != "") ourPort = std::atoi(Game::config->GetValue("port").c_str());
Game::server = new dServer(config.GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config); Game::server = new dServer(Game::config->GetValue("external_ip"), ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config, &Game::shouldShutdown);
Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(config.GetValue("dont_generate_dcf")))); Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", bool(std::stoi(Game::config->GetValue("dont_generate_dcf"))));
//Run it until server gets a kill message from Master: //Run it until server gets a kill message from Master:
auto t = std::chrono::high_resolution_clock::now(); auto t = std::chrono::high_resolution_clock::now();
Packet* packet = nullptr; Packet* packet = nullptr;
int framesSinceLastFlush = 0; constexpr uint32_t logFlushTime = 30 * chatFramerate; // 30 seconds in frames
int framesSinceMasterDisconnect = 0; constexpr uint32_t sqlPingTime = 10 * 60 * chatFramerate; // 10 minutes in frames
int framesSinceLastSQLPing = 0; uint32_t framesSinceLastFlush = 0;
uint32_t framesSinceMasterDisconnect = 0;
uint32_t framesSinceLastSQLPing = 0;
while (true) { while (!Game::shouldShutdown) {
//Check if we're still connected to master: //Check if we're still connected to master:
if (!Game::server->GetIsConnectedToMaster()) { if (!Game::server->GetIsConnectedToMaster()) {
framesSinceMasterDisconnect++; framesSinceMasterDisconnect++;
if (framesSinceMasterDisconnect >= 30) if (framesSinceMasterDisconnect >= chatFramerate)
break; //Exit our loop, shut down. break; //Exit our loop, shut down.
} else framesSinceMasterDisconnect = 0; } else framesSinceMasterDisconnect = 0;
@ -135,16 +141,16 @@ int main(int argc, char** argv) {
} }
//Push our log every 30s: //Push our log every 30s:
if (framesSinceLastFlush >= 900) { if (framesSinceLastFlush >= logFlushTime) {
Game::logger->Flush(); Game::logger->Flush();
framesSinceLastFlush = 0; framesSinceLastFlush = 0;
} else framesSinceLastFlush++; } else framesSinceLastFlush++;
//Every 10 min we ping our sql server to keep it alive hopefully: //Every 10 min we ping our sql server to keep it alive hopefully:
if (framesSinceLastSQLPing >= 40000) { if (framesSinceLastSQLPing >= sqlPingTime) {
//Find out the master's IP for absolutely no reason: //Find out the master's IP for absolutely no reason:
std::string masterIP; std::string masterIP;
int masterPort; uint32_t masterPort;
sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';"); sql::PreparedStatement* stmt = Database::CreatePreppedStmt("SELECT ip, port FROM servers WHERE name='master';");
auto res = stmt->executeQuery(); auto res = stmt->executeQuery();
while (res->next()) { while (res->next()) {
@ -159,7 +165,7 @@ int main(int argc, char** argv) {
} else framesSinceLastSQLPing++; } else framesSinceLastSQLPing++;
//Sleep our thread since auth can afford to. //Sleep our thread since auth can afford to.
t += std::chrono::milliseconds(mediumFramerate); //Chat can run at a lower "fps" t += std::chrono::milliseconds(chatFrameDelta); //Chat can run at a lower "fps"
std::this_thread::sleep_until(t); std::this_thread::sleep_until(t);
} }
@ -167,8 +173,8 @@ int main(int argc, char** argv) {
Database::Destroy("ChatServer"); Database::Destroy("ChatServer");
delete Game::server; delete Game::server;
delete Game::logger; delete Game::logger;
delete Game::config;
exit(EXIT_SUCCESS);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }

View File

@ -10,10 +10,11 @@
#include "GeneralUtils.h" #include "GeneralUtils.h"
#include "Game.h" #include "Game.h"
#include "dLogger.h" #include "dLogger.h"
#include "AssetManager.h"
#include "eSqliteDataType.h" #include "eSqliteDataType.h"
std::map<eSqliteDataType, std::string> FdbToSqlite::Convert::sqliteType = { std::map<eSqliteDataType, std::string> FdbToSqlite::Convert::m_SqliteType = {
{ eSqliteDataType::NONE, "none"}, { eSqliteDataType::NONE, "none"},
{ eSqliteDataType::INT32, "int32"}, { eSqliteDataType::INT32, "int32"},
{ eSqliteDataType::REAL, "real"}, { eSqliteDataType::REAL, "real"},
@ -23,20 +24,23 @@ std::map<eSqliteDataType, std::string> FdbToSqlite::Convert::sqliteType = {
{ eSqliteDataType::TEXT_8, "text_8"} { eSqliteDataType::TEXT_8, "text_8"}
}; };
FdbToSqlite::Convert::Convert(std::string basePath) { FdbToSqlite::Convert::Convert(std::string binaryOutPath) {
this->basePath = basePath; this->m_BinaryOutPath = binaryOutPath;
} }
bool FdbToSqlite::Convert::ConvertDatabase() { bool FdbToSqlite::Convert::ConvertDatabase(AssetMemoryBuffer& buffer) {
fdb.open(basePath + "/cdclient.fdb", std::ios::binary); if (m_ConversionStarted) return false;
std::istream cdClientBuffer(&buffer);
this->m_ConversionStarted = true;
try { try {
CDClientDatabase::Connect(basePath + "/CDServer.sqlite"); CDClientDatabase::Connect(m_BinaryOutPath + "/CDServer.sqlite");
CDClientDatabase::ExecuteQuery("BEGIN TRANSACTION;"); CDClientDatabase::ExecuteQuery("BEGIN TRANSACTION;");
int32_t numberOfTables = ReadInt32(); int32_t numberOfTables = ReadInt32(cdClientBuffer);
ReadTables(numberOfTables); ReadTables(numberOfTables, cdClientBuffer);
CDClientDatabase::ExecuteQuery("COMMIT;"); CDClientDatabase::ExecuteQuery("COMMIT;");
} catch (CppSQLite3Exception& e) { } catch (CppSQLite3Exception& e) {
@ -44,138 +48,133 @@ bool FdbToSqlite::Convert::ConvertDatabase() {
return false; return false;
} }
fdb.close();
return true; return true;
} }
int32_t FdbToSqlite::Convert::ReadInt32() { int32_t FdbToSqlite::Convert::ReadInt32(std::istream& cdClientBuffer) {
int32_t nextInt{}; int32_t nextInt{};
BinaryIO::BinaryRead(fdb, nextInt); BinaryIO::BinaryRead(cdClientBuffer, nextInt);
return nextInt; return nextInt;
} }
int64_t FdbToSqlite::Convert::ReadInt64() { int64_t FdbToSqlite::Convert::ReadInt64(std::istream& cdClientBuffer) {
int32_t prevPosition = SeekPointer(); int32_t prevPosition = SeekPointer(cdClientBuffer);
int64_t value{}; int64_t value{};
BinaryIO::BinaryRead(fdb, value); BinaryIO::BinaryRead(cdClientBuffer, value);
fdb.seekg(prevPosition); cdClientBuffer.seekg(prevPosition);
return value; return value;
} }
std::string FdbToSqlite::Convert::ReadString() { std::string FdbToSqlite::Convert::ReadString(std::istream& cdClientBuffer) {
int32_t prevPosition = SeekPointer(); int32_t prevPosition = SeekPointer(cdClientBuffer);
auto readString = BinaryIO::ReadString(fdb); auto readString = BinaryIO::ReadString(cdClientBuffer);
fdb.seekg(prevPosition); cdClientBuffer.seekg(prevPosition);
return readString; return readString;
} }
int32_t FdbToSqlite::Convert::SeekPointer() { int32_t FdbToSqlite::Convert::SeekPointer(std::istream& cdClientBuffer) {
int32_t position{}; int32_t position{};
BinaryIO::BinaryRead(fdb, position); BinaryIO::BinaryRead(cdClientBuffer, position);
int32_t prevPosition = fdb.tellg(); int32_t prevPosition = cdClientBuffer.tellg();
fdb.seekg(position); cdClientBuffer.seekg(position);
return prevPosition; return prevPosition;
} }
std::string FdbToSqlite::Convert::ReadColumnHeader() { std::string FdbToSqlite::Convert::ReadColumnHeader(std::istream& cdClientBuffer) {
int32_t prevPosition = SeekPointer(); int32_t prevPosition = SeekPointer(cdClientBuffer);
int32_t numberOfColumns = ReadInt32(); int32_t numberOfColumns = ReadInt32(cdClientBuffer);
std::string tableName = ReadString(); std::string tableName = ReadString(cdClientBuffer);
auto columns = ReadColumns(numberOfColumns); auto columns = ReadColumns(numberOfColumns, cdClientBuffer);
std::string newTable = "CREATE TABLE IF NOT EXISTS '" + tableName + "' (" + columns + ");"; std::string newTable = "CREATE TABLE IF NOT EXISTS '" + tableName + "' (" + columns + ");";
CDClientDatabase::ExecuteDML(newTable); CDClientDatabase::ExecuteDML(newTable);
fdb.seekg(prevPosition); cdClientBuffer.seekg(prevPosition);
return tableName; return tableName;
} }
void FdbToSqlite::Convert::ReadTables(int32_t& numberOfTables) { void FdbToSqlite::Convert::ReadTables(int32_t& numberOfTables, std::istream& cdClientBuffer) {
int32_t prevPosition = SeekPointer(); int32_t prevPosition = SeekPointer(cdClientBuffer);
for (int32_t i = 0; i < numberOfTables; i++) { for (int32_t i = 0; i < numberOfTables; i++) {
auto columnHeader = ReadColumnHeader(); auto columnHeader = ReadColumnHeader(cdClientBuffer);
ReadRowHeader(columnHeader); ReadRowHeader(columnHeader, cdClientBuffer);
} }
fdb.seekg(prevPosition); cdClientBuffer.seekg(prevPosition);
} }
std::string FdbToSqlite::Convert::ReadColumns(int32_t& numberOfColumns) { std::string FdbToSqlite::Convert::ReadColumns(int32_t& numberOfColumns, std::istream& cdClientBuffer) {
std::stringstream columnsToCreate; std::stringstream columnsToCreate;
int32_t prevPosition = SeekPointer(); int32_t prevPosition = SeekPointer(cdClientBuffer);
std::string name{}; std::string name{};
eSqliteDataType dataType{}; eSqliteDataType dataType{};
for (int32_t i = 0; i < numberOfColumns; i++) { for (int32_t i = 0; i < numberOfColumns; i++) {
if (i != 0) columnsToCreate << ", "; if (i != 0) columnsToCreate << ", ";
dataType = static_cast<eSqliteDataType>(ReadInt32()); dataType = static_cast<eSqliteDataType>(ReadInt32(cdClientBuffer));
name = ReadString(); name = ReadString(cdClientBuffer);
columnsToCreate << "'" << name << "' " << FdbToSqlite::Convert::sqliteType[dataType]; columnsToCreate << "'" << name << "' " << FdbToSqlite::Convert::m_SqliteType[dataType];
} }
fdb.seekg(prevPosition); cdClientBuffer.seekg(prevPosition);
return columnsToCreate.str(); return columnsToCreate.str();
} }
void FdbToSqlite::Convert::ReadRowHeader(std::string& tableName) { void FdbToSqlite::Convert::ReadRowHeader(std::string& tableName, std::istream& cdClientBuffer) {
int32_t prevPosition = SeekPointer(); int32_t prevPosition = SeekPointer(cdClientBuffer);
int32_t numberOfAllocatedRows = ReadInt32(); int32_t numberOfAllocatedRows = ReadInt32(cdClientBuffer);
if (numberOfAllocatedRows != 0) assert((numberOfAllocatedRows & (numberOfAllocatedRows - 1)) == 0); // assert power of 2 allocation size if (numberOfAllocatedRows != 0) assert((numberOfAllocatedRows & (numberOfAllocatedRows - 1)) == 0); // assert power of 2 allocation size
ReadRows(numberOfAllocatedRows, tableName); ReadRows(numberOfAllocatedRows, tableName, cdClientBuffer);
fdb.seekg(prevPosition); cdClientBuffer.seekg(prevPosition);
} }
void FdbToSqlite::Convert::ReadRows(int32_t& numberOfAllocatedRows, std::string& tableName) { void FdbToSqlite::Convert::ReadRows(int32_t& numberOfAllocatedRows, std::string& tableName, std::istream& cdClientBuffer) {
int32_t prevPosition = SeekPointer(); int32_t prevPosition = SeekPointer(cdClientBuffer);
int32_t rowid = 0; int32_t rowid = 0;
for (int32_t row = 0; row < numberOfAllocatedRows; row++) { for (int32_t row = 0; row < numberOfAllocatedRows; row++) {
int32_t rowPointer = ReadInt32(); int32_t rowPointer = ReadInt32(cdClientBuffer);
if (rowPointer == -1) rowid++; if (rowPointer == -1) rowid++;
else ReadRow(rowid, rowPointer, tableName); else ReadRow(rowPointer, tableName, cdClientBuffer);
} }
fdb.seekg(prevPosition); cdClientBuffer.seekg(prevPosition);
} }
void FdbToSqlite::Convert::ReadRow(int32_t& rowid, int32_t& position, std::string& tableName) { void FdbToSqlite::Convert::ReadRow(int32_t& position, std::string& tableName, std::istream& cdClientBuffer) {
int32_t prevPosition = fdb.tellg(); int32_t prevPosition = cdClientBuffer.tellg();
fdb.seekg(position); cdClientBuffer.seekg(position);
while (true) { while (true) {
ReadRowInfo(tableName); ReadRowInfo(tableName, cdClientBuffer);
int32_t linked = ReadInt32(); int32_t linked = ReadInt32(cdClientBuffer);
rowid += 1;
if (linked == -1) break; if (linked == -1) break;
cdClientBuffer.seekg(linked);
fdb.seekg(linked);
} }
fdb.seekg(prevPosition); cdClientBuffer.seekg(prevPosition);
} }
void FdbToSqlite::Convert::ReadRowInfo(std::string& tableName) { void FdbToSqlite::Convert::ReadRowInfo(std::string& tableName, std::istream& cdClientBuffer) {
int32_t prevPosition = SeekPointer(); int32_t prevPosition = SeekPointer(cdClientBuffer);
int32_t numberOfColumns = ReadInt32(); int32_t numberOfColumns = ReadInt32(cdClientBuffer);
ReadRowValues(numberOfColumns, tableName); ReadRowValues(numberOfColumns, tableName, cdClientBuffer);
fdb.seekg(prevPosition); cdClientBuffer.seekg(prevPosition);
} }
void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string& tableName) { void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string& tableName, std::istream& cdClientBuffer) {
int32_t prevPosition = SeekPointer(); int32_t prevPosition = SeekPointer(cdClientBuffer);
int32_t emptyValue{}; int32_t emptyValue{};
int32_t intValue{}; int32_t intValue{};
@ -189,26 +188,26 @@ void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string&
for (int32_t i = 0; i < numberOfColumns; i++) { for (int32_t i = 0; i < numberOfColumns; i++) {
if (i != 0) insertedRow << ", "; // Only append comma and space after first entry in row. if (i != 0) insertedRow << ", "; // Only append comma and space after first entry in row.
switch (static_cast<eSqliteDataType>(ReadInt32())) { switch (static_cast<eSqliteDataType>(ReadInt32(cdClientBuffer))) {
case eSqliteDataType::NONE: case eSqliteDataType::NONE:
BinaryIO::BinaryRead(fdb, emptyValue); BinaryIO::BinaryRead(cdClientBuffer, emptyValue);
assert(emptyValue == 0); assert(emptyValue == 0);
insertedRow << "NULL"; insertedRow << "NULL";
break; break;
case eSqliteDataType::INT32: case eSqliteDataType::INT32:
intValue = ReadInt32(); intValue = ReadInt32(cdClientBuffer);
insertedRow << intValue; insertedRow << intValue;
break; break;
case eSqliteDataType::REAL: case eSqliteDataType::REAL:
BinaryIO::BinaryRead(fdb, floatValue); BinaryIO::BinaryRead(cdClientBuffer, floatValue);
insertedRow << std::fixed << std::setprecision(34) << floatValue; // maximum precision of floating point number insertedRow << std::fixed << std::setprecision(34) << floatValue; // maximum precision of floating point number
break; break;
case eSqliteDataType::TEXT_4: case eSqliteDataType::TEXT_4:
case eSqliteDataType::TEXT_8: { case eSqliteDataType::TEXT_8: {
stringValue = ReadString(); stringValue = ReadString(cdClientBuffer);
size_t position = 0; size_t position = 0;
// Need to escape quote with a double of ". // Need to escape quote with a double of ".
@ -224,12 +223,12 @@ void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string&
} }
case eSqliteDataType::INT_BOOL: case eSqliteDataType::INT_BOOL:
BinaryIO::BinaryRead(fdb, boolValue); BinaryIO::BinaryRead(cdClientBuffer, boolValue);
insertedRow << static_cast<bool>(boolValue); insertedRow << static_cast<bool>(boolValue);
break; break;
case eSqliteDataType::INT64: case eSqliteDataType::INT64:
int64Value = ReadInt64(); int64Value = ReadInt64(cdClientBuffer);
insertedRow << std::to_string(int64Value); insertedRow << std::to_string(int64Value);
break; break;
@ -244,5 +243,5 @@ void FdbToSqlite::Convert::ReadRowValues(int32_t& numberOfColumns, std::string&
auto copiedString = insertedRow.str(); auto copiedString = insertedRow.str();
CDClientDatabase::ExecuteDML(copiedString); CDClientDatabase::ExecuteDML(copiedString);
fdb.seekg(prevPosition); cdClientBuffer.seekg(prevPosition);
} }

View File

@ -7,43 +7,139 @@
#include <iosfwd> #include <iosfwd>
#include <map> #include <map>
class AssetMemoryBuffer;
enum class eSqliteDataType : int32_t; enum class eSqliteDataType : int32_t;
namespace FdbToSqlite { namespace FdbToSqlite {
class Convert { class Convert {
public: public:
Convert(std::string inputFile); /**
* Create a new convert object with an input .fdb file and an output binary path.
*
* @param inputFile The file which ends in .fdb to be converted
* @param binaryPath The base path where the file will be saved
*/
Convert(std::string binaryOutPath);
bool ConvertDatabase(); /**
* Converts the input file to sqlite. Calling multiple times is safe.
*
* @return true if the database was converted properly, false otherwise.
*/
bool ConvertDatabase(AssetMemoryBuffer& buffer);
int32_t ReadInt32(); /**
* @brief Reads a 32 bit int from the fdb file.
*
* @return The read value
*/
int32_t ReadInt32(std::istream& cdClientBuffer);
int64_t ReadInt64(); /**
* @brief Reads a 64 bit integer from the fdb file.
*
* @return The read value
*/
int64_t ReadInt64(std::istream& cdClientBuffer);
std::string ReadString(); /**
* @brief Reads a string from the fdb file.
*
* @return The read string
*
* TODO This needs to be translated to latin-1!
*/
std::string ReadString(std::istream& cdClientBuffer);
int32_t SeekPointer(); /**
* @brief Seeks to a pointer position.
*
* @return The previous position before the seek
*/
int32_t SeekPointer(std::istream& cdClientBuffer);
std::string ReadColumnHeader(); /**
* @brief Reads a column header from the fdb file and creates the table in the database
*
* @return The table name
*/
std::string ReadColumnHeader(std::istream& cdClientBuffer);
void ReadTables(int32_t& numberOfTables); /**
* @brief Read the tables from the fdb file.
*
* @param numberOfTables The number of tables to read
*/
void ReadTables(int32_t& numberOfTables, std::istream& cdClientBuffer);
std::string ReadColumns(int32_t& numberOfColumns); /**
* @brief Reads the columns from the fdb file.
*
* @param numberOfColumns The number of columns to read
* @return All columns of the table formatted for a sql query
*/
std::string ReadColumns(int32_t& numberOfColumns, std::istream& cdClientBuffer);
void ReadRowHeader(std::string& tableName); /**
* @brief Reads the row header from the fdb file.
*
* @param tableName The tables name
*/
void ReadRowHeader(std::string& tableName, std::istream& cdClientBuffer);
void ReadRows(int32_t& numberOfAllocatedRows, std::string& tableName); /**
* @brief Read the rows from the fdb file.,
*
* @param numberOfAllocatedRows The number of rows that were allocated. Always a power of 2!
* @param tableName The tables name.
*/
void ReadRows(int32_t& numberOfAllocatedRows, std::string& tableName, std::istream& cdClientBuffer);
void ReadRow(int32_t& rowid, int32_t& position, std::string& tableName); /**
* @brief Reads a row from the fdb file.
*
* @param position The position to seek in the fdb to
* @param tableName The tables name
*/
void ReadRow(int32_t& position, std::string& tableName, std::istream& cdClientBuffer);
void ReadRowInfo(std::string& tableName); /**
* @brief Reads the row info from the fdb file.
*
* @param tableName The tables name
*/
void ReadRowInfo(std::string& tableName, std::istream& cdClientBuffer);
void ReadRowValues(int32_t& numberOfColumns, std::string& tableName); /**
* @brief Reads each row and its values from the fdb file and inserts them into the database
*
* @param numberOfColumns The number of columns to read in
* @param tableName The tables name
*/
void ReadRowValues(int32_t& numberOfColumns, std::string& tableName, std::istream& cdClientBuffer);
private: private:
static std::map<eSqliteDataType, std::string> sqliteType;
std::string basePath{}; /**
std::ifstream fdb{}; * Maps each sqlite data type to its string equivalent.
}; // class FdbToSqlite */
static std::map<eSqliteDataType, std::string> m_SqliteType;
/**
* Base path of the folder containing the fdb file
*/
std::string m_BasePath{};
/**
* Whether or not a conversion was started. If one was started, do not attempt to convert the file again.
*/
bool m_ConversionStarted{};
/**
* The path where the CDServer will be stored
*/
std::string m_BinaryOutPath{};
}; //! class FdbToSqlite
}; //! namespace FdbToSqlite }; //! namespace FdbToSqlite
#endif //!__FDBTOSQLITE__H__ #endif //!__FDBTOSQLITE__H__

View File

@ -5,7 +5,6 @@
class dServer; class dServer;
class dLogger; class dLogger;
class InstanceManager; class InstanceManager;
class dpWorld;
class dChatFilter; class dChatFilter;
class dConfig; class dConfig;
class RakPeerInterface; class RakPeerInterface;
@ -16,11 +15,11 @@ namespace Game {
extern dLogger* logger; extern dLogger* logger;
extern dServer* server; extern dServer* server;
extern InstanceManager* im; extern InstanceManager* im;
extern dpWorld* physicsWorld;
extern dChatFilter* chatFilter; extern dChatFilter* chatFilter;
extern dConfig* config; extern dConfig* config;
extern std::mt19937 randomEngine; extern std::mt19937 randomEngine;
extern RakPeerInterface* chatServer; extern RakPeerInterface* chatServer;
extern AssetManager* assetManager; extern AssetManager* assetManager;
extern SystemAddress chatSysAddr; extern SystemAddress chatSysAddr;
extern bool shouldShutdown;
} }

View File

@ -14,6 +14,8 @@
#include "Game.h" #include "Game.h"
#include "dLogger.h" #include "dLogger.h"
enum eInventoryType : uint32_t;
/*! /*!
\file GeneralUtils.hpp \file GeneralUtils.hpp
\brief A namespace containing general utility functions \brief A namespace containing general utility functions
@ -174,6 +176,11 @@ namespace GeneralUtils {
return std::stoull(value); return std::stoull(value);
} }
template <>
inline eInventoryType Parse(const char* value) {
return static_cast<eInventoryType>(std::stoul(value));
}
template <typename T> template <typename T>
bool TryParse(const char* value, T& dst) { bool TryParse(const char* value, T& dst) {
try { try {

View File

@ -45,9 +45,6 @@ AssetManager::AssetManager(const std::filesystem::path& path) {
switch (m_AssetBundleType) { switch (m_AssetBundleType) {
case eAssetBundleType::Packed: { case eAssetBundleType::Packed: {
this->LoadPackIndex(); this->LoadPackIndex();
this->UnpackRequiredAssets();
break; break;
} }
} }
@ -160,31 +157,6 @@ AssetMemoryBuffer AssetManager::GetFileAsBuffer(const char* name) {
return AssetMemoryBuffer(buf, len, success); return AssetMemoryBuffer(buf, len, success);
} }
void AssetManager::UnpackRequiredAssets() {
if (std::filesystem::exists(m_ResPath / "cdclient.fdb")) return;
char* data;
uint32_t size;
bool success = this->GetFile("cdclient.fdb", &data, &size);
if (!success) {
Game::logger->Log("AssetManager", "Failed to extract required files from the packs.");
delete data;
return;
}
std::ofstream cdclientOutput(m_ResPath / "cdclient.fdb", std::ios::out | std::ios::binary);
cdclientOutput.write(data, size);
cdclientOutput.close();
delete data;
return;
}
uint32_t AssetManager::crc32b(uint32_t base, uint8_t* message, size_t l) { uint32_t AssetManager::crc32b(uint32_t base, uint8_t* message, size_t l) {
size_t i, j; size_t i, j;
uint32_t crc, msb; uint32_t crc, msb;

View File

@ -60,7 +60,6 @@ public:
private: private:
void LoadPackIndex(); void LoadPackIndex();
void UnpackRequiredAssets();
// Modified crc algorithm (mpeg2) // Modified crc algorithm (mpeg2)
// Reference: https://stackoverflow.com/questions/54339800/how-to-modify-crc-32-to-crc-32-mpeg-2 // Reference: https://stackoverflow.com/questions/54339800/how-to-modify-crc-32-to-crc-32-mpeg-2

View File

@ -24,7 +24,6 @@ public:
* Reloads the config file to reset values * Reloads the config file to reset values
*/ */
void ReloadConfig(); void ReloadConfig();
private: private:
void ProcessLine(const std::string& line); void ProcessLine(const std::string& line);

View File

@ -6,7 +6,7 @@
/** /**
* Represents the possible states a mission can be in * Represents the possible states a mission can be in
*/ */
enum class MissionState : int { enum class MissionState : int32_t {
/** /**
* The mission state is unknown * The mission state is unknown
*/ */

View File

@ -6,15 +6,25 @@
#include <cstdint> #include <cstdint>
#include <string> #include <string>
#include <set> #include <set>
#include "../thirdparty/raknet/Source/BitStream.h" #include "BitStream.h"
#pragma warning (disable:4251) //Disables SQL warnings #pragma warning (disable:4251) //Disables SQL warnings
typedef int RESTICKET; typedef int RESTICKET;
const int highFrameRate = 16; //60fps // These are the same define, but they mean two different things in different contexts
const int mediumFramerate = 33; //30fps // so a different define to distinguish what calculation is happening will help clarity.
const int lowFramerate = 66; //15fps #define FRAMES_TO_MS(x) 1000 / x
#define MS_TO_FRAMES(x) 1000 / x
//=========== FRAME TIMINGS ===========
constexpr uint32_t highFramerate = 60;
constexpr uint32_t mediumFramerate = 30;
constexpr uint32_t lowFramerate = 15;
constexpr uint32_t highFrameDelta = FRAMES_TO_MS(highFramerate);
constexpr uint32_t mediumFrameDelta = FRAMES_TO_MS(mediumFramerate);
constexpr uint32_t lowFrameDelta = FRAMES_TO_MS(lowFramerate);
//========== MACROS =========== //========== MACROS ===========
@ -356,7 +366,7 @@ enum eControlSceme {
SCHEME_WEAR_A_ROBOT //== freecam? SCHEME_WEAR_A_ROBOT //== freecam?
}; };
enum eStunState { enum class eStateChangeType : uint32_t {
PUSH, PUSH,
POP POP
}; };
@ -427,26 +437,6 @@ enum class UseItemResponse : uint32_t {
MountsNotAllowed MountsNotAllowed
}; };
/**
* Represents the different types of inventories an entity may have
*/
enum eInventoryType : uint32_t {
ITEMS = 0,
VAULT_ITEMS,
BRICKS,
MODELS_IN_BBB,
TEMP_ITEMS = 4,
MODELS,
TEMP_MODELS,
BEHAVIORS,
PROPERTY_DEEDS,
VENDOR_BUYBACK = 11,
HIDDEN = 12, //Used for missional items
VAULT_MODELS = 14,
ITEM_SETS, //internal
INVALID // made up, for internal use!!!
};
enum eRebuildState : uint32_t { enum eRebuildState : uint32_t {
REBUILD_OPEN, REBUILD_OPEN,
REBUILD_COMPLETED = 2, REBUILD_COMPLETED = 2,

View File

@ -293,6 +293,7 @@ enum GAME_MSG : unsigned short {
GAME_MSG_POP_EQUIPPED_ITEMS_STATE = 192, GAME_MSG_POP_EQUIPPED_ITEMS_STATE = 192,
GAME_MSG_SET_GM_LEVEL = 193, GAME_MSG_SET_GM_LEVEL = 193,
GAME_MSG_SET_STUNNED = 198, GAME_MSG_SET_STUNNED = 198,
GAME_MSG_SET_STUN_IMMUNITY = 200,
GAME_MSG_KNOCKBACK = 202, GAME_MSG_KNOCKBACK = 202,
GAME_MSG_REBUILD_CANCEL = 209, GAME_MSG_REBUILD_CANCEL = 209,
GAME_MSG_ENABLE_REBUILD = 213, GAME_MSG_ENABLE_REBUILD = 213,
@ -373,6 +374,8 @@ enum GAME_MSG : unsigned short {
GAME_MSG_PET_TAMING_TRY_BUILD_RESULT = 668, GAME_MSG_PET_TAMING_TRY_BUILD_RESULT = 668,
GAME_MSG_NOTIFY_TAMING_BUILD_SUCCESS = 673, GAME_MSG_NOTIFY_TAMING_BUILD_SUCCESS = 673,
GAME_MSG_NOTIFY_TAMING_MODEL_LOADED_ON_SERVER = 674, GAME_MSG_NOTIFY_TAMING_MODEL_LOADED_ON_SERVER = 674,
GAME_MSG_ACTIVATE_BUBBLE_BUFF = 678,
GAME_MSG_DEACTIVATE_BUBBLE_BUFF = 679,
GAME_MSG_ADD_PET_TO_PLAYER = 681, GAME_MSG_ADD_PET_TO_PLAYER = 681,
GAME_MSG_REQUEST_SET_PET_NAME = 683, GAME_MSG_REQUEST_SET_PET_NAME = 683,
GAME_MSG_SET_PET_NAME = 684, GAME_MSG_SET_PET_NAME = 684,
@ -385,7 +388,10 @@ enum GAME_MSG : unsigned short {
GAME_MSG_QUERY_PROPERTY_DATA = 717, GAME_MSG_QUERY_PROPERTY_DATA = 717,
GAME_MSG_PROPERTY_EDITOR_BEGIN = 724, GAME_MSG_PROPERTY_EDITOR_BEGIN = 724,
GAME_MSG_PROPERTY_EDITOR_END = 725, GAME_MSG_PROPERTY_EDITOR_END = 725,
GAME_MSG_START_PATHING = 735, GAME_MSG_IS_MINIFIG_IN_A_BUBBLE = 729,
GAME_MSG_START_PATHING = 733,
GAME_MSG_ACTIVATE_BUBBLE_BUFF_FROM_SERVER = 734,
GAME_MSG_DEACTIVATE_BUBBLE_BUFF_FROM_SERVER = 735,
GAME_MSG_NOTIFY_CLIENT_ZONE_OBJECT = 737, GAME_MSG_NOTIFY_CLIENT_ZONE_OBJECT = 737,
GAME_MSG_UPDATE_REPUTATION = 746, GAME_MSG_UPDATE_REPUTATION = 746,
GAME_MSG_PROPERTY_RENTAL_RESPONSE = 750, GAME_MSG_PROPERTY_RENTAL_RESPONSE = 750,
@ -488,6 +494,7 @@ enum GAME_MSG : unsigned short {
GAME_MSG_MATCH_UPDATE = 1310, GAME_MSG_MATCH_UPDATE = 1310,
GAME_MSG_MODULE_ASSEMBLY_DB_DATA_FOR_CLIENT = 1131, GAME_MSG_MODULE_ASSEMBLY_DB_DATA_FOR_CLIENT = 1131,
GAME_MSG_MODULE_ASSEMBLY_QUERY_DATA = 1132, GAME_MSG_MODULE_ASSEMBLY_QUERY_DATA = 1132,
GAME_MSG_CHANGE_IDLE_FLAGS = 1338,
GAME_MSG_VEHICLE_ADD_PASSIVE_BOOST_ACTION = 1340, GAME_MSG_VEHICLE_ADD_PASSIVE_BOOST_ACTION = 1340,
GAME_MSG_VEHICLE_REMOVE_PASSIVE_BOOST_ACTION = 1341, GAME_MSG_VEHICLE_REMOVE_PASSIVE_BOOST_ACTION = 1341,
GAME_MSG_VEHICLE_NOTIFY_SERVER_ADD_PASSIVE_BOOST_ACTION = 1342, GAME_MSG_VEHICLE_NOTIFY_SERVER_ADD_PASSIVE_BOOST_ACTION = 1342,
@ -511,6 +518,7 @@ enum GAME_MSG : unsigned short {
GAME_MSG_UPDATE_CHAT_MODE = 1395, GAME_MSG_UPDATE_CHAT_MODE = 1395,
GAME_MSG_VEHICLE_NOTIFY_FINISHED_RACE = 1396, GAME_MSG_VEHICLE_NOTIFY_FINISHED_RACE = 1396,
GAME_MSG_SET_CONSUMABLE_ITEM = 1409, GAME_MSG_SET_CONSUMABLE_ITEM = 1409,
GAME_MSG_SET_STATUS_IMMUNITY = 1435,
GAME_MSG_SET_PET_NAME_MODERATED = 1448, GAME_MSG_SET_PET_NAME_MODERATED = 1448,
GAME_MSG_MODIFY_LEGO_SCORE = 1459, GAME_MSG_MODIFY_LEGO_SCORE = 1459,
GAME_MSG_RESTORE_TO_POST_LOAD_STATS = 1468, GAME_MSG_RESTORE_TO_POST_LOAD_STATS = 1468,

View File

@ -6,7 +6,7 @@
#include <cstdint> #include <cstdint>
enum class eAnimationFlags : uint32_t { enum class eAnimationFlags : uint32_t {
IDLE_INVALID = 0, // made up, for internal use!!! IDLE_NONE = 0,
IDLE_BASIC, IDLE_BASIC,
IDLE_SWIM, IDLE_SWIM,
IDLE_CARRY, IDLE_CARRY,

View File

@ -0,0 +1,12 @@
#ifndef __EBASICATTACKSUCCESSTYPES__H__
#define __EBASICATTACKSUCCESSTYPES__H__
#include <cstdint>
enum class eBasicAttackSuccessTypes : uint8_t {
SUCCESS = 1,
FAILARMOR,
FAILIMMUNE
};
#endif //!__EBASICATTACKSUCCESSTYPES__H__

View File

@ -0,0 +1,14 @@
#pragma once
#ifndef __EBUBBLETYPE__H__
#define __EBUBBLETYPE__H__
#include <cstdint>
enum class eBubbleType : uint32_t {
DEFAULT = 0,
ENERGY = 1,
SKUNK = 2,
};
#endif //!__EBUBBLETYPE__H__

View File

@ -0,0 +1,21 @@
#pragma once
#ifndef __ECHARACTERVERSION__H__
#define __ECHARACTERVERSION__H__
#include <cstdint>
enum class eCharacterVersion : uint32_t {
// Versions from the live game
RELEASE = 0, // Initial release of the game
LIVE, // Fixes for the 1.9 release bug fixes for missions leading up to joining a faction
// New versions for DLU fixes
// Fixes the "Joined a faction" player flag not being set properly
PLAYER_FACTION_FLAGS,
// Fixes vault size value
VAULT_SIZE,
// Fixes speed base value in level component
UP_TO_DATE, // will become SPEED_BASE
};
#endif //!__ECHARACTERVERSION__H__

View File

@ -0,0 +1,59 @@
#pragma once
#ifndef __EINVENTORYTYPE__H__
#define __EINVENTORYTYPE__H__
#include <cstdint>
static const uint8_t NUMBER_OF_INVENTORIES = 17;
/**
* Represents the different types of inventories an entity may have
*/
enum eInventoryType : uint32_t {
ITEMS = 0,
VAULT_ITEMS,
BRICKS,
MODELS_IN_BBB,
TEMP_ITEMS,
MODELS,
TEMP_MODELS,
BEHAVIORS,
PROPERTY_DEEDS,
BRICKS_IN_BBB,
VENDOR,
VENDOR_BUYBACK,
QUEST, //Used for mission items
DONATION,
VAULT_MODELS,
ITEM_SETS, //internal, technically this is BankBehaviors.
INVALID // made up, for internal use!!!, Technically this called the ALL inventory.
};
class InventoryType {
public:
static const char* InventoryTypeToString(eInventoryType inventory) {
const char* eInventoryTypeTable[NUMBER_OF_INVENTORIES] = {
"ITEMS",
"VAULT_ITEMS",
"BRICKS",
"MODELS_IN_BBB",
"TEMP_ITEMS",
"MODELS",
"TEMP_MODELS",
"BEHAVIORS",
"PROPERTY_DEEDS",
"BRICKS_IN_BBB",
"VENDOR",
"VENDOR_BUYBACK",
"QUEST", //Used for mission items
"DONATION",
"VAULT_MODELS",
"ITEM_SETS", //internal, technically this is BankBehaviors.
"INVALID" // made up, for internal use!!!, Technically this called the ALL inventory.
};
if (inventory > NUMBER_OF_INVENTORIES - 1) return nullptr;
return eInventoryTypeTable[inventory];
};
};
#endif //!__EINVENTORYTYPE__H__

View File

@ -0,0 +1,16 @@
#ifndef __EMOVEMENTPLATFORMSTATE__H__
#define __EMOVEMENTPLATFORMSTATE__H__
#include <cstdint>
/**
* The different types of platform movement state, supposedly a bitmap
*/
enum class eMovementPlatformState : uint32_t
{
Moving = 0b00010,
Stationary = 0b11001,
Stopped = 0b01100
};
#endif //!__EMOVEMENTPLATFORMSTATE__H__

View File

@ -89,7 +89,7 @@ void dLogger::Log(const std::string& className, const std::string& message) {
void dLogger::LogDebug(const char* className, const char* format, ...) { void dLogger::LogDebug(const char* className, const char* format, ...) {
if (!m_logDebugStatements) return; if (!m_logDebugStatements) return;
va_list args; va_list args;
std::string log = "[" + std::string(className) + "] " + std::string(format); std::string log = "[" + std::string(className) + "] " + std::string(format) + "\n";
va_start(args, format); va_start(args, format);
vLog(log.c_str(), args); vLog(log.c_str(), args);
va_end(args); va_end(args);

View File

@ -54,7 +54,7 @@ void MigrationRunner::RunMigrations() {
if (doExit) continue; if (doExit) continue;
Game::logger->Log("MigrationRunner", "Running migration: %s", migration.name.c_str()); Game::logger->Log("MigrationRunner", "Running migration: %s", migration.name.c_str());
if (migration.name == "5_brick_model_sd0.sql") { if (migration.name == "dlu/5_brick_model_sd0.sql") {
runSd0Migrations = true; runSd0Migrations = true;
} else { } else {
finalSQL.append(migration.data.c_str()); finalSQL.append(migration.data.c_str());

View File

@ -4,9 +4,9 @@
//! Constructor //! Constructor
CDBehaviorParameterTable::CDBehaviorParameterTable(void) { CDBehaviorParameterTable::CDBehaviorParameterTable(void) {
auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorParameter"); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorParameter");
size_t hash = 0; uint32_t uniqueParameterId = 0;
uint64_t hash = 0;
while (!tableData.eof()) { while (!tableData.eof()) {
hash = 0;
CDBehaviorParameter entry; CDBehaviorParameter entry;
entry.behaviorID = tableData.getIntField(0, -1); entry.behaviorID = tableData.getIntField(0, -1);
auto candidateStringToAdd = std::string(tableData.getStringField(1, "")); auto candidateStringToAdd = std::string(tableData.getStringField(1, ""));
@ -14,15 +14,13 @@ CDBehaviorParameterTable::CDBehaviorParameterTable(void) {
if (parameter != m_ParametersList.end()) { if (parameter != m_ParametersList.end()) {
entry.parameterID = parameter; entry.parameterID = parameter;
} else { } else {
entry.parameterID = m_ParametersList.insert(candidateStringToAdd).first; entry.parameterID = m_ParametersList.insert(std::make_pair(candidateStringToAdd, uniqueParameterId)).first;
uniqueParameterId++;
} }
hash = entry.behaviorID;
hash = (hash << 31U) | entry.parameterID->second;
entry.value = tableData.getFloatField(2, -1.0f); entry.value = tableData.getFloatField(2, -1.0f);
GeneralUtils::hash_combine(hash, entry.behaviorID);
GeneralUtils::hash_combine(hash, *entry.parameterID);
auto it = m_Entries.find(entry.behaviorID);
m_ParametersList.insert(*entry.parameterID);
m_Entries.insert(std::make_pair(hash, entry)); m_Entries.insert(std::make_pair(hash, entry));
tableData.nextRow(); tableData.nextRow();
@ -38,31 +36,28 @@ std::string CDBehaviorParameterTable::GetName(void) const {
return "BehaviorParameter"; return "BehaviorParameter";
} }
CDBehaviorParameter CDBehaviorParameterTable::GetEntry(const uint32_t behaviorID, const std::string& name, const float defaultValue) { float CDBehaviorParameterTable::GetValue(const uint32_t behaviorID, const std::string& name, const float defaultValue) {
CDBehaviorParameter returnValue; auto parameterID = this->m_ParametersList.find(name);
returnValue.behaviorID = 0; if (parameterID == this->m_ParametersList.end()) return defaultValue;
returnValue.parameterID = m_ParametersList.end();
returnValue.value = defaultValue;
size_t hash = 0; uint64_t hash = behaviorID;
GeneralUtils::hash_combine(hash, behaviorID);
GeneralUtils::hash_combine(hash, name); hash = (hash << 31U) | parameterID->second;
// Search for specific parameter // Search for specific parameter
const auto& it = m_Entries.find(hash); const auto& it = m_Entries.find(hash);
return it != m_Entries.end() ? it->second : returnValue; return it != m_Entries.end() ? it->second.value : defaultValue;
} }
std::map<std::string, float> CDBehaviorParameterTable::GetParametersByBehaviorID(uint32_t behaviorID) { std::map<std::string, float> CDBehaviorParameterTable::GetParametersByBehaviorID(uint32_t behaviorID) {
size_t hash; uint64_t hashBase = behaviorID;
std::map<std::string, float> returnInfo; std::map<std::string, float> returnInfo;
for (auto parameterCandidate : m_ParametersList) { uint64_t hash;
hash = 0; for (auto& parameterCandidate : m_ParametersList) {
GeneralUtils::hash_combine(hash, behaviorID); hash = (hashBase << 31U) | parameterCandidate.second;
GeneralUtils::hash_combine(hash, parameterCandidate);
auto infoCandidate = m_Entries.find(hash); auto infoCandidate = m_Entries.find(hash);
if (infoCandidate != m_Entries.end()) { if (infoCandidate != m_Entries.end()) {
returnInfo.insert(std::make_pair(*(infoCandidate->second.parameterID), infoCandidate->second.value)); returnInfo.insert(std::make_pair(infoCandidate->second.parameterID->first, infoCandidate->second.value));
} }
} }
return returnInfo; return returnInfo;

View File

@ -13,15 +13,15 @@
//! BehaviorParameter Entry Struct //! BehaviorParameter Entry Struct
struct CDBehaviorParameter { struct CDBehaviorParameter {
unsigned int behaviorID; //!< The Behavior ID unsigned int behaviorID; //!< The Behavior ID
std::unordered_set<std::string>::iterator parameterID; //!< The Parameter ID std::unordered_map<std::string, uint32_t>::iterator parameterID; //!< The Parameter ID
float value; //!< The value of the behavior template float value; //!< The value of the behavior template
}; };
//! BehaviorParameter table //! BehaviorParameter table
class CDBehaviorParameterTable : public CDTable { class CDBehaviorParameterTable : public CDTable {
private: private:
std::unordered_map<size_t, CDBehaviorParameter> m_Entries; std::unordered_map<uint64_t, CDBehaviorParameter> m_Entries;
std::unordered_set<std::string> m_ParametersList; std::unordered_map<std::string, uint32_t> m_ParametersList;
public: public:
//! Constructor //! Constructor
@ -36,7 +36,7 @@ public:
*/ */
std::string GetName(void) const override; std::string GetName(void) const override;
CDBehaviorParameter GetEntry(const uint32_t behaviorID, const std::string& name, const float defaultValue = 0); float GetValue(const uint32_t behaviorID, const std::string& name, const float defaultValue = 0);
std::map<std::string, float> GetParametersByBehaviorID(uint32_t behaviorID); std::map<std::string, float> GetParametersByBehaviorID(uint32_t behaviorID);
}; };

View File

@ -15,6 +15,7 @@
#include "Zone.h" #include "Zone.h"
#include "ChatPackets.h" #include "ChatPackets.h"
#include "Inventory.h" #include "Inventory.h"
#include "InventoryComponent.h"
Character::Character(uint32_t id, User* parentUser) { Character::Character(uint32_t id, User* parentUser) {
//First load the name, etc: //First load the name, etc:

View File

@ -17,6 +17,11 @@
#include "UserManager.h" #include "UserManager.h"
#include "dpWorld.h" #include "dpWorld.h"
#include "Player.h" #include "Player.h"
#include "LUTriggers.h"
#include "User.h"
#include "EntityTimer.h"
#include "EntityCallbackTimer.h"
#include "Loot.h"
//Component includes: //Component includes:
#include "Component.h" #include "Component.h"
@ -772,8 +777,8 @@ no_ghosting:
auto* controllablePhysicsComponent = GetComponent<ControllablePhysicsComponent>(); auto* controllablePhysicsComponent = GetComponent<ControllablePhysicsComponent>();
auto* levelComponent = GetComponent<LevelProgressionComponent>(); auto* levelComponent = GetComponent<LevelProgressionComponent>();
if (controllablePhysicsComponent != nullptr && levelComponent->GetLevel() >= 20) { if (controllablePhysicsComponent && levelComponent) {
controllablePhysicsComponent->SetSpeedMultiplier(525.0f / 500.0f); controllablePhysicsComponent->SetSpeedMultiplier(levelComponent->GetSpeedBase() / 500.0f);
} }
} }
} }
@ -827,6 +832,22 @@ std::vector<ScriptComponent*> Entity::GetScriptComponents() {
return comps; return comps;
} }
void Entity::Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName) {
if (notificationName == "HitOrHealResult" || notificationName == "Hit") {
auto* destroyableComponent = GetComponent<DestroyableComponent>();
if (!destroyableComponent) return;
destroyableComponent->Subscribe(scriptObjId, scriptToAdd);
}
}
void Entity::Unsubscribe(LWOOBJID scriptObjId, const std::string& notificationName) {
if (notificationName == "HitOrHealResult" || notificationName == "Hit") {
auto* destroyableComponent = GetComponent<DestroyableComponent>();
if (!destroyableComponent) return;
destroyableComponent->Unsubscribe(scriptObjId);
}
}
void Entity::SetProximityRadius(float proxRadius, std::string name) { void Entity::SetProximityRadius(float proxRadius, std::string name) {
ProximityMonitorComponent* proxMon = GetComponent<ProximityMonitorComponent>(); ProximityMonitorComponent* proxMon = GetComponent<ProximityMonitorComponent>();
if (!proxMon) { if (!proxMon) {

View File

@ -4,29 +4,39 @@
#include <functional> #include <functional>
#include <typeinfo> #include <typeinfo>
#include <type_traits> #include <type_traits>
#include <unordered_map>
#include <vector> #include <vector>
#include "../thirdparty/raknet/Source/Replica.h"
#include "../thirdparty/raknet/Source/ReplicaManager.h"
#include "dCommonVars.h"
#include "User.h"
#include "NiPoint3.h" #include "NiPoint3.h"
#include "NiQuaternion.h" #include "NiQuaternion.h"
#include "LDFFormat.h" #include "LDFFormat.h"
#include "Loot.h"
#include "Zone.h"
#include "EntityTimer.h" namespace Loot {
#include "EntityCallbackTimer.h" class Info;
#include "EntityInfo.h" };
namespace tinyxml2 {
class XMLDocument;
};
namespace LUTriggers {
struct Trigger;
};
class Player; class Player;
class EntityInfo;
class User;
class Spawner; class Spawner;
class ScriptComponent; class ScriptComponent;
class dpEntity; class dpEntity;
class EntityTimer;
class Component; class Component;
class Item;
class Character; class Character;
class EntityCallbackTimer;
namespace CppScripts {
class Script;
};
/** /**
* An entity in the world. Has multiple components. * An entity in the world. Has multiple components.
@ -139,6 +149,9 @@ public:
std::vector<ScriptComponent*> GetScriptComponents(); std::vector<ScriptComponent*> GetScriptComponents();
void Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd, const std::string& notificationName);
void Unsubscribe(LWOOBJID scriptObjId, const std::string& notificationName);
void SetProximityRadius(float proxRadius, std::string name); void SetProximityRadius(float proxRadius, std::string name);
void SetProximityRadius(dpEntity* entity, std::string name); void SetProximityRadius(dpEntity* entity, std::string name);

View File

@ -17,6 +17,7 @@
#include "MissionComponent.h" #include "MissionComponent.h"
#include "Game.h" #include "Game.h"
#include "dLogger.h" #include "dLogger.h"
#include "MessageIdentifiers.h"
EntityManager* EntityManager::m_Address = nullptr; EntityManager* EntityManager::m_Address = nullptr;

View File

@ -2,15 +2,17 @@
#define ENTITYMANAGER_H #define ENTITYMANAGER_H
#include "dCommonVars.h" #include "dCommonVars.h"
#include "../thirdparty/raknet/Source/Replica.h"
#include <map> #include <map>
#include <stack> #include <stack>
#include "Entity.h"
#include <vector> #include <vector>
#include <unordered_map>
class Entity;
class EntityInfo;
class Player;
class User;
struct SystemAddress; struct SystemAddress;
class User;
class EntityManager { class EntityManager {
public: public:

View File

@ -7,6 +7,7 @@
#include "GameMessages.h" #include "GameMessages.h"
#include "dLogger.h" #include "dLogger.h"
#include "dConfig.h" #include "dConfig.h"
#include "CDClientManager.h"
Leaderboard::Leaderboard(uint32_t gameID, uint32_t infoType, bool weekly, std::vector<LeaderboardEntry> entries, Leaderboard::Leaderboard(uint32_t gameID, uint32_t infoType, bool weekly, std::vector<LeaderboardEntry> entries,
LWOOBJID relatedPlayer, LeaderboardType leaderboardType) { LWOOBJID relatedPlayer, LeaderboardType leaderboardType) {

View File

@ -13,7 +13,9 @@
#include "dZoneManager.h" #include "dZoneManager.h"
#include "CharacterComponent.h" #include "CharacterComponent.h"
#include "Mail.h" #include "Mail.h"
#include "User.h"
#include "CppScripts.h" #include "CppScripts.h"
#include "Loot.h"
std::vector<Player*> Player::m_Players = {}; std::vector<Player*> Player::m_Players = {};

View File

@ -103,6 +103,7 @@ void Trade::SetAccepted(LWOOBJID participant, bool value) {
} }
Complete(); Complete();
TradingManager::Instance()->CancelTrade(m_TradeId);
} }
} }
@ -121,33 +122,59 @@ void Trade::Complete() {
if (inventoryA == nullptr || inventoryB == nullptr || characterA == nullptr || characterB == nullptr || missionsA == nullptr || missionsB == nullptr) return; if (inventoryA == nullptr || inventoryB == nullptr || characterA == nullptr || characterB == nullptr || missionsA == nullptr || missionsB == nullptr) return;
// First verify both players have the coins and items requested for the trade.
if (characterA->GetCoins() < m_CoinsA || characterB->GetCoins() < m_CoinsB) {
Game::logger->Log("TradingManager", "Possible coin trade cheating attempt! Aborting trade.");
return;
}
for (const auto& tradeItem : m_ItemsA) {
auto* itemToRemove = inventoryA->FindItemById(tradeItem.itemId);
if (itemToRemove) {
if (itemToRemove->GetCount() < tradeItem.itemCount) {
Game::logger->Log("TradingManager", "Possible cheating attempt from %s in trading!!! Aborting trade", characterA->GetName().c_str());
return;
}
} else {
Game::logger->Log("TradingManager", "Possible cheating attempt from %s in trading due to item not being available!!!", characterA->GetName().c_str());
return;
}
}
for (const auto& tradeItem : m_ItemsB) {
auto* itemToRemove = inventoryB->FindItemById(tradeItem.itemId);
if (itemToRemove) {
if (itemToRemove->GetCount() < tradeItem.itemCount) {
Game::logger->Log("TradingManager", "Possible cheating attempt from %s in trading!!! Aborting trade", characterB->GetName().c_str());
return;
}
} else {
Game::logger->Log("TradingManager", "Possible cheating attempt from %s in trading due to item not being available!!! Aborting trade", characterB->GetName().c_str());
return;
}
}
// Now actually do the trade.
characterA->SetCoins(characterA->GetCoins() - m_CoinsA + m_CoinsB, eLootSourceType::LOOT_SOURCE_TRADE); characterA->SetCoins(characterA->GetCoins() - m_CoinsA + m_CoinsB, eLootSourceType::LOOT_SOURCE_TRADE);
characterB->SetCoins(characterB->GetCoins() - m_CoinsB + m_CoinsA, eLootSourceType::LOOT_SOURCE_TRADE); characterB->SetCoins(characterB->GetCoins() - m_CoinsB + m_CoinsA, eLootSourceType::LOOT_SOURCE_TRADE);
for (const auto& tradeItem : m_ItemsA) { for (const auto& tradeItem : m_ItemsA) {
inventoryA->RemoveItem(tradeItem.itemLot, tradeItem.itemCount, INVALID, true); auto* itemToRemove = inventoryA->FindItemById(tradeItem.itemId);
if (itemToRemove) itemToRemove->SetCount(itemToRemove->GetCount() - tradeItem.itemCount);
missionsA->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount); missionsA->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount);
}
for (const auto& tradeItem : m_ItemsB) {
inventoryB->RemoveItem(tradeItem.itemLot, tradeItem.itemCount, INVALID, true);
missionsB->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount);
}
for (const auto& tradeItem : m_ItemsA) {
inventoryB->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); inventoryB->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE);
} }
for (const auto& tradeItem : m_ItemsB) { for (const auto& tradeItem : m_ItemsB) {
auto* itemToRemove = inventoryB->FindItemById(tradeItem.itemId);
if (itemToRemove) itemToRemove->SetCount(itemToRemove->GetCount() - tradeItem.itemCount);
missionsB->Progress(MissionTaskType::MISSION_TASK_TYPE_ITEM_COLLECTION, tradeItem.itemLot, LWOOBJID_EMPTY, "", -tradeItem.itemCount);
inventoryA->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE); inventoryA->AddItem(tradeItem.itemLot, tradeItem.itemCount, eLootSourceType::LOOT_SOURCE_TRADE);
} }
TradingManager::Instance()->CancelTrade(m_TradeId);
characterA->SaveXMLToDatabase(); characterA->SaveXMLToDatabase();
characterB->SaveXMLToDatabase(); characterB->SaveXMLToDatabase();
return;
} }
void Trade::Cancel() { void Trade::Cancel() {

View File

@ -21,6 +21,8 @@
#include "EntityManager.h" #include "EntityManager.h"
#include "SkillComponent.h" #include "SkillComponent.h"
#include "AssetManager.h" #include "AssetManager.h"
#include "CDClientDatabase.h"
#include "dMessageIdentifiers.h"
UserManager* UserManager::m_Address = nullptr; UserManager* UserManager::m_Address = nullptr;

View File

@ -2,11 +2,16 @@
#include "BehaviorBranchContext.h" #include "BehaviorBranchContext.h"
#include "BehaviorContext.h" #include "BehaviorContext.h"
#include "EntityManager.h" #include "EntityManager.h"
#include "Game.h"
#include "dLogger.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{};
bitStream->Read(handle); if (!bitStream->Read(handle)) {
Game::logger->Log("AirMovementBehavior", "Unable to read handle from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
}
context->RegisterSyncBehavior(handle, this, branch); context->RegisterSyncBehavior(handle, this, branch);
} }
@ -17,14 +22,20 @@ void AirMovementBehavior::Calculate(BehaviorContext* context, RakNet::BitStream*
bitStream->Write(handle); bitStream->Write(handle);
} }
void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
uint32_t behaviorId; uint32_t behaviorId{};
bit_stream->Read(behaviorId); if (!bitStream->Read(behaviorId)) {
Game::logger->Log("AirMovementBehavior", "Unable to read behaviorId from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits());
return;
}
LWOOBJID target; LWOOBJID target{};
bit_stream->Read(target); if (!bitStream->Read(target)) {
Game::logger->Log("AirMovementBehavior", "Unable to read target from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits());
return;
}
auto* behavior = CreateBehavior(behaviorId); auto* behavior = CreateBehavior(behaviorId);
@ -32,7 +43,7 @@ void AirMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bit_
branch.target = target; branch.target = target;
} }
behavior->Handle(context, bit_stream, branch); behavior->Handle(context, bitStream, branch);
} }
void AirMovementBehavior::Load() { void AirMovementBehavior::Load() {

View File

@ -16,7 +16,7 @@ public:
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* bit_stream, BehaviorBranchContext branch) override; void Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Load() override; void Load() override;
}; };

View File

@ -9,11 +9,16 @@
#include "BehaviorContext.h" #include "BehaviorContext.h"
#include "RebuildComponent.h" #include "RebuildComponent.h"
#include "DestroyableComponent.h" #include "DestroyableComponent.h"
#include "Game.h"
#include "dLogger.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{};
bitStream->Read(targetCount); if (!bitStream->Read(targetCount)) {
Game::logger->Log("AreaOfEffectBehavior", "Unable to read targetCount from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
}
if (targetCount > this->m_maxTargets) { if (targetCount > this->m_maxTargets) {
return; return;
@ -24,9 +29,12 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* b
targets.reserve(targetCount); targets.reserve(targetCount);
for (auto i = 0u; i < targetCount; ++i) { for (auto i = 0u; i < targetCount; ++i) {
LWOOBJID target; LWOOBJID target{};
bitStream->Read(target); if (!bitStream->Read(target)) {
Game::logger->Log("AreaOfEffectBehavior", "failed to read in target %i from bitStream, aborting target Handle!", i);
return;
};
targets.push_back(target); targets.push_back(target);
} }
@ -40,9 +48,8 @@ void AreaOfEffectBehavior::Handle(BehaviorContext* context, RakNet::BitStream* b
void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
auto* self = EntityManager::Instance()->GetEntity(context->caster); auto* self = EntityManager::Instance()->GetEntity(context->caster);
if (self == nullptr) { if (self == nullptr) {
Game::logger->Log("TacArcBehavior", "Invalid self for (%llu)!", context->originator); Game::logger->Log("AreaOfEffectBehavior", "Invalid self for (%llu)!", context->originator);
return; return;
} }
@ -71,7 +78,7 @@ void AreaOfEffectBehavior::Calculate(BehaviorContext* context, RakNet::BitStream
auto* entity = EntityManager::Instance()->GetEntity(validTarget); auto* entity = EntityManager::Instance()->GetEntity(validTarget);
if (entity == nullptr) { if (entity == nullptr) {
Game::logger->Log("TacArcBehavior", "Invalid target (%llu) for (%llu)!", validTarget, context->originator); Game::logger->Log("AreaOfEffectBehavior", "Invalid target (%llu) for (%llu)!", validTarget, context->originator);
continue; continue;
} }

View File

@ -5,12 +5,15 @@
#include "dLogger.h" #include "dLogger.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{};
bitStream->Read(handle); if (!bitStream->Read(handle)) {
Game::logger->Log("AttackDelayBehavior", "Unable to read handle from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
for (auto i = 0u; i < this->m_numIntervals; ++i) { for (auto i = 0u; i < this->m_numIntervals; ++i) {
context->RegisterSyncBehavior(handle, this, branch); context->RegisterSyncBehavior(handle, this, branch, m_ignoreInterrupts);
} }
} }

View File

@ -5,7 +5,7 @@
#include "EntityManager.h" #include "EntityManager.h"
#include "DestroyableComponent.h" #include "DestroyableComponent.h"
#include "BehaviorContext.h" #include "BehaviorContext.h"
#include "eBasicAttackSuccessTypes.h"
void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
if (context->unmanaged) { if (context->unmanaged) {
@ -14,122 +14,137 @@ void BasicAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bi
auto* destroyableComponent = entity->GetComponent<DestroyableComponent>(); auto* destroyableComponent = entity->GetComponent<DestroyableComponent>();
if (destroyableComponent != nullptr) { if (destroyableComponent != nullptr) {
PlayFx(u"onhit", entity->GetObjectID()); PlayFx(u"onhit", entity->GetObjectID());
destroyableComponent->Damage(this->m_maxDamage, context->originator, context->skillID); destroyableComponent->Damage(this->m_MaxDamage, context->originator, context->skillID);
} }
this->m_onSuccess->Handle(context, bitStream, branch); this->m_OnSuccess->Handle(context, bitStream, branch);
return; return;
} }
bitStream->AlignReadToByteBoundary(); bitStream->AlignReadToByteBoundary();
uint16_t allocatedBits; uint16_t allocatedBits{};
bitStream->Read(allocatedBits); if (!bitStream->Read(allocatedBits) || allocatedBits == 0) {
Game::logger->LogDebug("BasicAttackBehavior", "No allocated bits");
return;
}
Game::logger->LogDebug("BasicAttackBehavior", "Number of allocated bits %i", allocatedBits);
const auto baseAddress = bitStream->GetReadOffset(); const auto baseAddress = bitStream->GetReadOffset();
if (bitStream->ReadBit()) { // Blocked
return;
}
if (bitStream->ReadBit()) { // Immune DoHandleBehavior(context, bitStream, branch);
return;
}
if (bitStream->ReadBit()) { // Success
uint32_t unknown;
bitStream->Read(unknown);
uint32_t damageDealt;
bitStream->Read(damageDealt);
// A value that's too large may be a cheating attempt, so we set it to MIN too
if (damageDealt > this->m_maxDamage || damageDealt < this->m_minDamage) {
damageDealt = this->m_minDamage;
}
auto* entity = EntityManager::Instance()->GetEntity(branch.target);
bool died;
bitStream->Read(died);
if (entity != nullptr) {
auto* destroyableComponent = entity->GetComponent<DestroyableComponent>();
if (destroyableComponent != nullptr) {
PlayFx(u"onhit", entity->GetObjectID());
destroyableComponent->Damage(damageDealt, context->originator, context->skillID);
}
}
}
uint8_t successState;
bitStream->Read(successState);
switch (successState) {
case 1:
this->m_onSuccess->Handle(context, bitStream, branch);
break;
default:
Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!", successState);
break;
}
bitStream->SetReadOffset(baseAddress + allocatedBits); bitStream->SetReadOffset(baseAddress + allocatedBits);
} }
void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { void BasicAttackBehavior::DoHandleBehavior(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
auto* self = EntityManager::Instance()->GetEntity(context->originator); auto* targetEntity = EntityManager::Instance()->GetEntity(branch.target);
if (self == nullptr) { if (!targetEntity) {
Game::logger->Log("BasicAttackBehavior", "Invalid self entity (%llu)!", context->originator); Game::logger->Log("BasicAttackBehavior", "Target targetEntity %llu not found.", branch.target);
return; return;
} }
auto* destroyableComponent = targetEntity->GetComponent<DestroyableComponent>();
if (!destroyableComponent) {
Game::logger->Log("BasicAttackBehavior", "No destroyable found on the obj/lot %llu/%i", branch.target, targetEntity->GetLOT());
return;
}
bool isBlocked{};
bool isImmune{};
bool isSuccess{};
if (!bitStream->Read(isBlocked)) {
Game::logger->Log("BasicAttackBehavior", "Unable to read isBlocked");
return;
}
if (isBlocked) {
destroyableComponent->SetAttacksToBlock(std::min(destroyableComponent->GetAttacksToBlock() - 1, 0U));
EntityManager::Instance()->SerializeEntity(targetEntity);
this->m_OnFailBlocked->Handle(context, bitStream, branch);
return;
}
if (!bitStream->Read(isImmune)) {
Game::logger->Log("BasicAttackBehavior", "Unable to read isImmune");
return;
}
if (isImmune) {
this->m_OnFailImmune->Handle(context, bitStream, branch);
return;
}
if (!bitStream->Read(isSuccess)) {
Game::logger->Log("BasicAttackBehavior", "failed to read success from bitstream");
return;
}
if (isSuccess) {
uint32_t armorDamageDealt{};
if (!bitStream->Read(armorDamageDealt)) {
Game::logger->Log("BasicAttackBehavior", "Unable to read armorDamageDealt");
return;
}
uint32_t healthDamageDealt{};
if (!bitStream->Read(healthDamageDealt)) {
Game::logger->Log("BasicAttackBehavior", "Unable to read healthDamageDealt");
return;
}
uint32_t totalDamageDealt = armorDamageDealt + healthDamageDealt;
// A value that's too large may be a cheating attempt, so we set it to MIN
if (totalDamageDealt > this->m_MaxDamage) {
totalDamageDealt = this->m_MinDamage;
}
bool died{};
if (!bitStream->Read(died)) {
Game::logger->Log("BasicAttackBehavior", "Unable to read died");
return;
}
auto previousArmor = destroyableComponent->GetArmor();
auto previousHealth = destroyableComponent->GetHealth();
PlayFx(u"onhit", targetEntity->GetObjectID());
destroyableComponent->Damage(totalDamageDealt, context->originator, context->skillID);
}
uint8_t successState{};
if (!bitStream->Read(successState)) {
Game::logger->Log("BasicAttackBehavior", "Unable to read success state");
return;
}
switch (static_cast<eBasicAttackSuccessTypes>(successState)) {
case eBasicAttackSuccessTypes::SUCCESS:
this->m_OnSuccess->Handle(context, bitStream, branch);
break;
case eBasicAttackSuccessTypes::FAILARMOR:
this->m_OnFailArmor->Handle(context, bitStream, branch);
break;
default:
if (static_cast<eBasicAttackSuccessTypes>(successState) != eBasicAttackSuccessTypes::FAILIMMUNE) {
Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!", successState);
return;
}
this->m_OnFailImmune->Handle(context, bitStream, branch);
break;
}
}
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();
bitStream->Write0(); // Blocked DoBehaviorCalculation(context, bitStream, branch);
bitStream->Write0(); // Immune
bitStream->Write1(); // Success
if (true) {
uint32_t unknown3 = 0;
bitStream->Write(unknown3);
auto damage = this->m_minDamage;
auto* entity = EntityManager::Instance()->GetEntity(branch.target);
if (entity == nullptr) {
damage = 0;
bitStream->Write(damage);
bitStream->Write(false);
} else {
bitStream->Write(damage);
bitStream->Write(true);
auto* destroyableComponent = entity->GetComponent<DestroyableComponent>();
if (damage != 0 && destroyableComponent != nullptr) {
PlayFx(u"onhit", entity->GetObjectID(), 1);
destroyableComponent->Damage(damage, context->originator, context->skillID, false);
context->ScheduleUpdate(branch.target);
}
}
}
uint8_t successState = 1;
bitStream->Write(successState);
switch (successState) {
case 1:
this->m_onSuccess->Calculate(context, bitStream, branch);
break;
default:
Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!", successState);
break;
}
const auto endAddress = bitStream->GetWriteOffset(); const auto endAddress = bitStream->GetWriteOffset();
const uint16_t allocate = endAddress - startAddress + 1; const uint16_t allocate = endAddress - startAddress + 1;
@ -139,12 +154,102 @@ void BasicAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream*
bitStream->SetWriteOffset(startAddress + allocate); bitStream->SetWriteOffset(startAddress + allocate);
} }
void BasicAttackBehavior::Load() { void BasicAttackBehavior::DoBehaviorCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
this->m_minDamage = GetInt("min damage"); auto* targetEntity = EntityManager::Instance()->GetEntity(branch.target);
if (this->m_minDamage == 0) this->m_minDamage = 1; if (!targetEntity) {
Game::logger->Log("BasicAttackBehavior", "Target entity %llu is null!", branch.target);
this->m_maxDamage = GetInt("max damage"); return;
if (this->m_maxDamage == 0) this->m_maxDamage = 1; }
this->m_onSuccess = GetAction("on_success"); auto* destroyableComponent = targetEntity->GetComponent<DestroyableComponent>();
if (!destroyableComponent || !destroyableComponent->GetParent()) {
Game::logger->Log("BasicAttackBehavior", "No destroyable component on %llu", branch.target);
return;
}
const bool isBlocking = destroyableComponent->GetAttacksToBlock() > 0;
bitStream->Write(isBlocking);
if (isBlocking) {
destroyableComponent->SetAttacksToBlock(destroyableComponent->GetAttacksToBlock() - 1);
EntityManager::Instance()->SerializeEntity(targetEntity);
this->m_OnFailBlocked->Calculate(context, bitStream, branch);
return;
}
const bool isImmune = destroyableComponent->IsImmune();
bitStream->Write(isImmune);
if (isImmune) {
this->m_OnFailImmune->Calculate(context, bitStream, branch);
return;
}
bool isSuccess = false;
const uint32_t previousHealth = destroyableComponent->GetHealth();
const uint32_t previousArmor = destroyableComponent->GetArmor();
const auto damage = this->m_MinDamage;
PlayFx(u"onhit", targetEntity->GetObjectID(), 1);
destroyableComponent->Damage(damage, context->originator, context->skillID, false);
context->ScheduleUpdate(branch.target);
const uint32_t armorDamageDealt = previousArmor - destroyableComponent->GetArmor();
const uint32_t healthDamageDealt = previousHealth - destroyableComponent->GetHealth();
isSuccess = armorDamageDealt > 0 || healthDamageDealt > 0 || (armorDamageDealt + healthDamageDealt) > 0;
bitStream->Write(isSuccess);
eBasicAttackSuccessTypes successState = eBasicAttackSuccessTypes::FAILIMMUNE;
if (isSuccess) {
if (healthDamageDealt >= 1) {
successState = eBasicAttackSuccessTypes::SUCCESS;
} else if (armorDamageDealt >= 1) {
successState = this->m_OnFailArmor->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY ? eBasicAttackSuccessTypes::FAILIMMUNE : eBasicAttackSuccessTypes::FAILARMOR;
}
bitStream->Write(armorDamageDealt);
bitStream->Write(healthDamageDealt);
bitStream->Write(targetEntity->GetIsDead());
}
bitStream->Write(successState);
switch (static_cast<eBasicAttackSuccessTypes>(successState)) {
case eBasicAttackSuccessTypes::SUCCESS:
this->m_OnSuccess->Calculate(context, bitStream, branch);
break;
case eBasicAttackSuccessTypes::FAILARMOR:
this->m_OnFailArmor->Calculate(context, bitStream, branch);
break;
default:
if (static_cast<eBasicAttackSuccessTypes>(successState) != eBasicAttackSuccessTypes::FAILIMMUNE) {
Game::logger->Log("BasicAttackBehavior", "Unknown success state (%i)!", successState);
break;
}
this->m_OnFailImmune->Calculate(context, bitStream, branch);
break;
}
}
void BasicAttackBehavior::Load() {
this->m_MinDamage = GetInt("min damage");
if (this->m_MinDamage == 0) this->m_MinDamage = 1;
this->m_MaxDamage = GetInt("max damage");
if (this->m_MaxDamage == 0) this->m_MaxDamage = 1;
// The client sets the minimum damage to maximum, so we'll do the same. These are usually the same value anyways.
if (this->m_MinDamage < this->m_MaxDamage) this->m_MinDamage = this->m_MaxDamage;
this->m_OnSuccess = GetAction("on_success");
this->m_OnFailArmor = GetAction("on_fail_armor");
this->m_OnFailImmune = GetAction("on_fail_immune");
this->m_OnFailBlocked = GetAction("on_fail_blocked");
} }

View File

@ -4,18 +4,59 @@
class BasicAttackBehavior final : public Behavior class BasicAttackBehavior final : public Behavior
{ {
public: public:
uint32_t m_minDamage;
uint32_t m_maxDamage;
Behavior* m_onSuccess;
explicit BasicAttackBehavior(const uint32_t behaviorId) : Behavior(behaviorId) { explicit BasicAttackBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {
} }
/**
* @brief Reads a 16bit short from the bitStream and when the actual behavior handling finishes with all of its branches, the bitStream
* is then offset to after the allocated bits for this stream.
*
*/
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.
*
* @param context The Skill's Behavior context. All behaviors in the same tree share the same context
* @param bitStream The bitStream to deserialize. BitStreams will always check their bounds before reading in a behavior
* and will fail gracefully if an overread is detected.
* @param branch The context of this specific branch of the Skill Behavior. Changes based on which branch you are going down.
*/
void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
/**
* @brief Writes a 16bit short to the bitStream and when the actual behavior calculation finishes with all of its branches, the number
* of bits used is then written to where the 16bit short initially was.
*
*/
void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override; void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
/**
* @brief Calculates a server initialized Basic Attack Behavior cast to be serialized to the client
*
* @param context The Skill's Behavior context. All behaviors in the same tree share the same context
* @param bitStream The bitStream to serialize to.
* @param branch The context of this specific branch of the Skill Behavior. Changes based on which branch you are going down.
*/
void DoBehaviorCalculation(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch);
/**
* @brief Loads this Behaviors parameters from the database. For this behavior specifically:
* max and min damage will always be the same. If min is less than max, they are both set to max.
* If an action is not in the database, then no action is taken for that result.
*
*/
void Load() override; void Load() override;
private:
uint32_t m_MinDamage;
uint32_t m_MaxDamage;
Behavior* m_OnSuccess;
Behavior* m_OnFailArmor;
Behavior* m_OnFailImmune;
Behavior* m_OnFailBlocked;
}; };

View File

@ -48,6 +48,7 @@
#include "PlayEffectBehavior.h" #include "PlayEffectBehavior.h"
#include "DamageAbsorptionBehavior.h" #include "DamageAbsorptionBehavior.h"
#include "VentureVisionBehavior.h" #include "VentureVisionBehavior.h"
#include "PropertyTeleportBehavior.h"
#include "BlockBehavior.h" #include "BlockBehavior.h"
#include "ClearTargetBehavior.h" #include "ClearTargetBehavior.h"
#include "PullToPointBehavior.h" #include "PullToPointBehavior.h"
@ -60,6 +61,8 @@
#include "SpeedBehavior.h" #include "SpeedBehavior.h"
#include "DamageReductionBehavior.h" #include "DamageReductionBehavior.h"
#include "JetPackBehavior.h" #include "JetPackBehavior.h"
#include "ChangeIdleFlagsBehavior.h"
#include "DarkInspirationBehavior.h"
//CDClient includes //CDClient includes
#include "CDBehaviorParameterTable.h" #include "CDBehaviorParameterTable.h"
@ -168,7 +171,9 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) {
case BehaviorTemplates::BEHAVIOR_SPEED: case BehaviorTemplates::BEHAVIOR_SPEED:
behavior = new SpeedBehavior(behaviorId); behavior = new SpeedBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_DARK_INSPIRATION: break; case BehaviorTemplates::BEHAVIOR_DARK_INSPIRATION:
behavior = new DarkInspirationBehavior(behaviorId);
break;
case BehaviorTemplates::BEHAVIOR_LOOT_BUFF: case BehaviorTemplates::BEHAVIOR_LOOT_BUFF:
behavior = new LootBuffBehavior(behaviorId); behavior = new LootBuffBehavior(behaviorId);
break; break;
@ -196,7 +201,9 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) {
behavior = new SkillCastFailedBehavior(behaviorId); behavior = new SkillCastFailedBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_IMITATION_SKUNK_STINK: break; case BehaviorTemplates::BEHAVIOR_IMITATION_SKUNK_STINK: break;
case BehaviorTemplates::BEHAVIOR_CHANGE_IDLE_FLAGS: break; case BehaviorTemplates::BEHAVIOR_CHANGE_IDLE_FLAGS:
behavior = new ChangeIdleFlagsBehavior(behaviorId);
break;
case BehaviorTemplates::BEHAVIOR_APPLY_BUFF: case BehaviorTemplates::BEHAVIOR_APPLY_BUFF:
behavior = new ApplyBuffBehavior(behaviorId); behavior = new ApplyBuffBehavior(behaviorId);
break; break;
@ -257,7 +264,9 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) {
case BehaviorTemplates::BEHAVIOR_DAMAGE_REDUCTION: case BehaviorTemplates::BEHAVIOR_DAMAGE_REDUCTION:
behavior = new DamageReductionBehavior(behaviorId); behavior = new DamageReductionBehavior(behaviorId);
break; break;
case BehaviorTemplates::BEHAVIOR_PROPERTY_TELEPORT: break; case BehaviorTemplates::BEHAVIOR_PROPERTY_TELEPORT:
behavior = new PropertyTeleportBehavior(behaviorId);
break;
case BehaviorTemplates::BEHAVIOR_PROPERTY_CLEAR_TARGET: case BehaviorTemplates::BEHAVIOR_PROPERTY_CLEAR_TARGET:
behavior = new ClearTargetBehavior(behaviorId); behavior = new ClearTargetBehavior(behaviorId);
break; break;
@ -433,7 +442,7 @@ Behavior::Behavior(const uint32_t behaviorId) {
float Behavior::GetFloat(const std::string& name, const float defaultValue) const { float Behavior::GetFloat(const std::string& name, const float defaultValue) const {
// Get the behavior parameter entry and return its value. // Get the behavior parameter entry and return its value.
if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance()->GetTable<CDBehaviorParameterTable>("BehaviorParameter"); if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance()->GetTable<CDBehaviorParameterTable>("BehaviorParameter");
return BehaviorParameterTable->GetEntry(this->m_behaviorId, name, defaultValue).value; return BehaviorParameterTable->GetValue(this->m_behaviorId, name, defaultValue);
} }

View File

@ -15,6 +15,8 @@ struct BehaviorBranchContext
uint32_t start = 0; uint32_t start = 0;
bool isSync = false;
BehaviorBranchContext(); BehaviorBranchContext();
BehaviorBranchContext(LWOOBJID target, float duration = 0, const NiPoint3& referencePosition = NiPoint3(0, 0, 0)); BehaviorBranchContext(LWOOBJID target, float duration = 0, const NiPoint3& referencePosition = NiPoint3(0, 0, 0));

View File

@ -10,8 +10,9 @@
#include <sstream> #include <sstream>
#include "dMessageIdentifiers.h"
#include "DestroyableComponent.h" #include "DestroyableComponent.h"
#include "EchoSyncSkill.h"
#include "PhantomPhysicsComponent.h" #include "PhantomPhysicsComponent.h"
#include "RebuildComponent.h" #include "RebuildComponent.h"
@ -45,12 +46,14 @@ uint32_t BehaviorContext::GetUniqueSkillId() const {
} }
void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext) { void BehaviorContext::RegisterSyncBehavior(const uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext, bool ignoreInterrupts) {
auto entry = BehaviorSyncEntry(); auto entry = BehaviorSyncEntry();
entry.handle = syncId; entry.handle = syncId;
entry.behavior = behavior; entry.behavior = behavior;
entry.branchContext = branchContext; entry.branchContext = branchContext;
entry.branchContext.isSync = true;
entry.ignoreInterrupts = ignoreInterrupts;
this->syncEntries.push_back(entry); this->syncEntries.push_back(entry);
} }
@ -214,7 +217,7 @@ bool BehaviorContext::CalculateUpdate(const float deltaTime) {
} }
// Echo sync // Echo sync
GameMessages::EchoSyncSkill echo; EchoSyncSkill echo;
echo.bDone = true; echo.bDone = true;
echo.uiBehaviorHandle = entry.handle; echo.uiBehaviorHandle = entry.handle;

View File

@ -80,7 +80,7 @@ struct BehaviorContext
uint32_t GetUniqueSkillId() const; uint32_t GetUniqueSkillId() const;
void RegisterSyncBehavior(uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext); void RegisterSyncBehavior(uint32_t syncId, Behavior* behavior, const BehaviorBranchContext& branchContext, bool ignoreInterrupts = false);
void RegisterTimerBehavior(Behavior* behavior, const BehaviorBranchContext& branchContext, LWOOBJID second = LWOOBJID_EMPTY); void RegisterTimerBehavior(Behavior* behavior, const BehaviorBranchContext& branchContext, LWOOBJID second = LWOOBJID_EMPTY);

View File

@ -12,11 +12,13 @@ set(DGAME_DBEHAVIORS_SOURCES "AirMovementBehavior.cpp"
"BuffBehavior.cpp" "BuffBehavior.cpp"
"CarBoostBehavior.cpp" "CarBoostBehavior.cpp"
"ChainBehavior.cpp" "ChainBehavior.cpp"
"ChangeIdleFlagsBehavior.cpp"
"ChangeOrientationBehavior.cpp" "ChangeOrientationBehavior.cpp"
"ChargeUpBehavior.cpp" "ChargeUpBehavior.cpp"
"ClearTargetBehavior.cpp" "ClearTargetBehavior.cpp"
"DamageAbsorptionBehavior.cpp" "DamageAbsorptionBehavior.cpp"
"DamageReductionBehavior.cpp" "DamageReductionBehavior.cpp"
"DarkInspirationBehavior.cpp"
"DurationBehavior.cpp" "DurationBehavior.cpp"
"EmptyBehavior.cpp" "EmptyBehavior.cpp"
"EndBehavior.cpp" "EndBehavior.cpp"
@ -33,6 +35,7 @@ set(DGAME_DBEHAVIORS_SOURCES "AirMovementBehavior.cpp"
"OverTimeBehavior.cpp" "OverTimeBehavior.cpp"
"PlayEffectBehavior.cpp" "PlayEffectBehavior.cpp"
"ProjectileAttackBehavior.cpp" "ProjectileAttackBehavior.cpp"
"PropertyTeleportBehavior.cpp"
"PullToPointBehavior.cpp" "PullToPointBehavior.cpp"
"RemoveBuffBehavior.cpp" "RemoveBuffBehavior.cpp"
"RepairBehavior.cpp" "RepairBehavior.cpp"

View File

@ -4,14 +4,19 @@
#include "dLogger.h" #include "dLogger.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 chain_index; uint32_t chainIndex{};
bitStream->Read(chain_index); if (!bitStream->Read(chainIndex)) {
Game::logger->Log("ChainBehavior", "Unable to read chainIndex from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
}
chain_index--; chainIndex--;
if (chain_index < this->m_behaviors.size()) { if (chainIndex < this->m_behaviors.size()) {
this->m_behaviors.at(chain_index)->Handle(context, bitStream, branch); this->m_behaviors.at(chainIndex)->Handle(context, bitStream, branch);
} else {
Game::logger->Log("ChainBehavior", "chainIndex out of bounds, aborting handle of chain %i bits unread %i", chainIndex, bitStream->GetNumberOfUnreadBits());
} }
} }

View File

@ -0,0 +1,37 @@
#include "ChangeIdleFlagsBehavior.h"
#include "BehaviorContext.h"
#include "BehaviorBranchContext.h"
void ChangeIdleFlagsBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator;
if (!target) return;
GameMessages::SendChangeIdleFlags(target, m_FlagsOn, m_FlagsOff, UNASSIGNED_SYSTEM_ADDRESS);
if (branch.duration > 0.0f) {
context->RegisterTimerBehavior(this, branch);
} else if (branch.start > 0) {
context->RegisterEndBehavior(this, branch);
}
}
void ChangeIdleFlagsBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
Handle(context, bitStream, branch);
}
void ChangeIdleFlagsBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) {
const auto target = branch.target != LWOOBJID_EMPTY ? branch.target : context->originator;
if (!target) return;
// flip on and off to end behavior
GameMessages::SendChangeIdleFlags(target, m_FlagsOff, m_FlagsOn, UNASSIGNED_SYSTEM_ADDRESS);
}
void ChangeIdleFlagsBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) {
End(context, branch, second);
}
void ChangeIdleFlagsBehavior::Load() {
m_FlagsOff = static_cast<eAnimationFlags>(GetInt("flags_off", 0));
m_FlagsOn = static_cast<eAnimationFlags>(GetInt("flags_on", 0));
}

View File

@ -0,0 +1,23 @@
#pragma once
#include "Behavior.h"
#include "eAninmationFlags.h"
class ChangeIdleFlagsBehavior final : public Behavior {
public:
/*
* Inherited
*/
explicit ChangeIdleFlagsBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {}
void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override;
void End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override;
void Load() override;
private:
eAnimationFlags m_FlagsOff;
eAnimationFlags m_FlagsOn;
};

View File

@ -1,12 +1,16 @@
#include "ChargeUpBehavior.h" #include "ChargeUpBehavior.h"
#include "BehaviorBranchContext.h" #include "BehaviorBranchContext.h"
#include "BehaviorContext.h" #include "BehaviorContext.h"
#include "Game.h"
#include "dLogger.h" #include "dLogger.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{};
bitStream->Read(handle); if (!bitStream->Read(handle)) {
Game::logger->Log("ChargeUpBehavior", "Unable to read handle from bitStream, aborting Handle! variable_type");
return;
};
context->RegisterSyncBehavior(handle, this, branch); context->RegisterSyncBehavior(handle, this, branch);
} }

View File

@ -0,0 +1,52 @@
#include "DarkInspirationBehavior.h"
#include "BehaviorBranchContext.h"
#include "Entity.h"
#include "DestroyableComponent.h"
#include "EntityManager.h"
#include "BehaviorContext.h"
void DarkInspirationBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) {
auto* target = EntityManager::Instance()->GetEntity(branch.target);
if (target == nullptr) {
Game::logger->LogDebug("DarkInspirationBehavior", "Failed to find target (%llu)!", branch.target);
return;
}
auto* destroyableComponent = target->GetComponent<DestroyableComponent>();
if (destroyableComponent == nullptr) {
return;
}
if (destroyableComponent->HasFaction(m_FactionList)) {
this->m_ActionIfFactionMatches->Handle(context, bitStream, branch);
}
}
void DarkInspirationBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
auto* target = EntityManager::Instance()->GetEntity(branch.target);
if (target == nullptr) {
Game::logger->LogDebug("DarkInspirationBehavior", "Failed to find target (%llu)!", branch.target);
return;
}
auto* destroyableComponent = target->GetComponent<DestroyableComponent>();
if (destroyableComponent == nullptr) {
return;
}
if (destroyableComponent->HasFaction(m_FactionList)) {
this->m_ActionIfFactionMatches->Calculate(context, bitStream, branch);
}
}
void DarkInspirationBehavior::Load() {
this->m_ActionIfFactionMatches = GetAction("action");
this->m_FactionList = GetInt("faction_list");
}

View File

@ -0,0 +1,22 @@
#pragma once
#include "Behavior.h"
class DarkInspirationBehavior final : public Behavior
{
public:
/*
* Inherited
*/
explicit DarkInspirationBehavior(const uint32_t behaviorId) : Behavior(behaviorId) {
}
void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Load() override;
private:
Behavior* m_ActionIfFactionMatches;
uint32_t m_FactionList;
};

View File

@ -3,23 +3,34 @@
#include "BehaviorContext.h" #include "BehaviorContext.h"
#include "ControllablePhysicsComponent.h" #include "ControllablePhysicsComponent.h"
#include "EntityManager.h" #include "EntityManager.h"
#include "Game.h"
#include "dLogger.h"
void ForceMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { void ForceMovementBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) {
if (this->m_hitAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitEnemyAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitFactionAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { if (this->m_hitAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitEnemyAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_hitFactionAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) {
return; return;
} }
uint32_t handle; uint32_t handle{};
bitStream->Read(handle); if (!bitStream->Read(handle)) {
Game::logger->Log("ForceMovementBehavior", "Unable to read handle from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
}
context->RegisterSyncBehavior(handle, this, branch); context->RegisterSyncBehavior(handle, this, branch);
} }
void ForceMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { void ForceMovementBehavior::Sync(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
uint32_t next; uint32_t next{};
bitStream->Read(next); if (!bitStream->Read(next)) {
Game::logger->Log("ForceMovementBehavior", "Unable to read target from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits());
return;
}
LWOOBJID target; LWOOBJID target{};
bitStream->Read(target); if (!bitStream->Read(target)) {
Game::logger->Log("ForceMovementBehavior", "Unable to read target from bitStream, aborting Sync! %i", bitStream->GetNumberOfUnreadBits());
return;
}
branch.target = target; branch.target = target;
auto* behavior = CreateBehavior(next); auto* behavior = CreateBehavior(next);

View File

@ -6,28 +6,47 @@
#include "Game.h" #include "Game.h"
#include "dLogger.h" #include "dLogger.h"
#include "DestroyableComponent.h" #include "DestroyableComponent.h"
#include "ControllablePhysicsComponent.h"
void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { void ImmunityBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) {
auto* target = EntityManager::Instance()->GetEntity(branch.target); auto* target = EntityManager::Instance()->GetEntity(branch.target);
if (target == nullptr) { if (!target) {
Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target); Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", branch.target);
return; return;
} }
auto* destroyable = static_cast<DestroyableComponent*>(target->GetComponent(COMPONENT_TYPE_DESTROYABLE)); auto* destroyableComponent = target->GetComponent<DestroyableComponent>();
if (destroyableComponent) {
if (destroyable == nullptr) { destroyableComponent->SetStatusImmunity(
return; eStateChangeType::PUSH,
this->m_ImmuneToBasicAttack,
this->m_ImmuneToDamageOverTime,
this->m_ImmuneToKnockback,
this->m_ImmuneToInterrupt,
this->m_ImmuneToSpeed,
this->m_ImmuneToImaginationGain,
this->m_ImmuneToImaginationLoss,
this->m_ImmuneToQuickbuildInterrupt,
this->m_ImmuneToPullToPoint
);
} }
if (!this->m_immuneBasicAttack) { auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>();
return; if (controllablePhysicsComponent) {
controllablePhysicsComponent->SetStunImmunity(
eStateChangeType::PUSH,
context->caster,
this->m_ImmuneToStunAttack,
this->m_ImmuneToStunEquip,
this->m_ImmuneToStunInteract,
this->m_ImmuneToStunJump,
this->m_ImmuneToStunMove,
this->m_ImmuneToStunTurn,
this->m_ImmuneToStunUseItem
);
} }
destroyable->PushImmunity();
context->RegisterTimerBehavior(this, branch, target->GetObjectID()); context->RegisterTimerBehavior(this, branch, target->GetObjectID());
} }
@ -38,21 +57,60 @@ void ImmunityBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bi
void ImmunityBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) { void ImmunityBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, const LWOOBJID second) {
auto* target = EntityManager::Instance()->GetEntity(second); auto* target = EntityManager::Instance()->GetEntity(second);
if (target == nullptr) { if (!target) {
Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", second); Game::logger->Log("DamageAbsorptionBehavior", "Failed to find target (%llu)!", second);
return; return;
} }
auto* destroyable = static_cast<DestroyableComponent*>(target->GetComponent(COMPONENT_TYPE_DESTROYABLE)); auto* destroyableComponent = target->GetComponent<DestroyableComponent>();
if (destroyableComponent) {
if (destroyable == nullptr) { destroyableComponent->SetStatusImmunity(
return; eStateChangeType::POP,
this->m_ImmuneToBasicAttack,
this->m_ImmuneToDamageOverTime,
this->m_ImmuneToKnockback,
this->m_ImmuneToInterrupt,
this->m_ImmuneToSpeed,
this->m_ImmuneToImaginationGain,
this->m_ImmuneToImaginationLoss,
this->m_ImmuneToQuickbuildInterrupt,
this->m_ImmuneToPullToPoint
);
}
auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>();
if (controllablePhysicsComponent) {
controllablePhysicsComponent->SetStunImmunity(
eStateChangeType::POP,
context->caster,
this->m_ImmuneToStunAttack,
this->m_ImmuneToStunEquip,
this->m_ImmuneToStunInteract,
this->m_ImmuneToStunJump,
this->m_ImmuneToStunMove,
this->m_ImmuneToStunTurn,
this->m_ImmuneToStunUseItem
);
} }
destroyable->PopImmunity();
} }
void ImmunityBehavior::Load() { void ImmunityBehavior::Load() {
this->m_immuneBasicAttack = GetBoolean("immune_basic_attack"); //Stun
this->m_ImmuneToStunAttack = GetBoolean("immune_stun_attack", false);
this->m_ImmuneToStunEquip = GetBoolean("immune_stun_equip", false);
this->m_ImmuneToStunInteract = GetBoolean("immune_stun_interact", false);
this->m_ImmuneToStunMove = GetBoolean("immune_stun_move", false);
this->m_ImmuneToStunTurn = GetBoolean("immune_stun_rotate", false);
// Status
this->m_ImmuneToBasicAttack = GetBoolean("immune_basic_attack", false);
this->m_ImmuneToDamageOverTime = GetBoolean("immune_damage_over_time", false);
this->m_ImmuneToKnockback = GetBoolean("immune_knockback", false);
this->m_ImmuneToInterrupt = GetBoolean("immune_interrupt", false);
this->m_ImmuneToSpeed = GetBoolean("immune_speed", false);
this->m_ImmuneToImaginationGain = GetBoolean("immune_imagination_gain", false);
this->m_ImmuneToImaginationLoss = GetBoolean("immune_imagination_loss", false);
this->m_ImmuneToQuickbuildInterrupt = GetBoolean("immune_quickbuild_interrupts", false);
this->m_ImmuneToPullToPoint = GetBoolean("immune_pulltopoint", false);
} }

View File

@ -4,8 +4,6 @@
class ImmunityBehavior final : public Behavior class ImmunityBehavior final : public Behavior
{ {
public: public:
uint32_t m_immuneBasicAttack;
/* /*
* Inherited * Inherited
*/ */
@ -20,4 +18,25 @@ public:
void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override; void Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) override;
void Load() override; void Load() override;
private:
// stuns
bool m_ImmuneToStunAttack = false;
bool m_ImmuneToStunEquip = false;
bool m_ImmuneToStunInteract = false;
bool m_ImmuneToStunJump = false; // Unused
bool m_ImmuneToStunMove = false;
bool m_ImmuneToStunTurn = false;
bool m_ImmuneToStunUseItem = false; // Unused
//status
bool m_ImmuneToBasicAttack = false;
bool m_ImmuneToDamageOverTime = false;
bool m_ImmuneToKnockback = false;
bool m_ImmuneToInterrupt = false;
bool m_ImmuneToSpeed = false;
bool m_ImmuneToImaginationGain = false;
bool m_ImmuneToImaginationLoss = false;
bool m_ImmuneToQuickbuildInterrupt = false;
bool m_ImmuneToPullToPoint = false; // Unused in cdclient, but used in client
}; };

View File

@ -11,7 +11,10 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS
if (branch.target != context->originator) { if (branch.target != context->originator) {
bool unknown = false; bool unknown = false;
bitStream->Read(unknown); if (!bitStream->Read(unknown)) {
Game::logger->Log("InterruptBehavior", "Unable to read unknown1 from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
if (unknown) return; if (unknown) return;
} }
@ -19,7 +22,10 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS
if (!this->m_interruptBlock) { if (!this->m_interruptBlock) {
bool unknown = false; bool unknown = false;
bitStream->Read(unknown); if (!bitStream->Read(unknown)) {
Game::logger->Log("InterruptBehavior", "Unable to read unknown2 from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
if (unknown) return; if (unknown) return;
} }
@ -28,7 +34,10 @@ void InterruptBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitS
{ {
bool unknown = false; bool unknown = false;
bitStream->Read(unknown); if (!bitStream->Read(unknown)) {
Game::logger->Log("InterruptBehavior", "Unable to read unknown3 from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
} }
if (branch.target == context->originator) return; if (branch.target == context->originator) return;

View File

@ -6,11 +6,16 @@
#include "EntityManager.h" #include "EntityManager.h"
#include "GameMessages.h" #include "GameMessages.h"
#include "DestroyableComponent.h" #include "DestroyableComponent.h"
#include "Game.h"
#include "dLogger.h"
void KnockbackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { void KnockbackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
bool unknown; bool unknown{};
bitStream->Read(unknown); if (!bitStream->Read(unknown)) {
Game::logger->Log("KnockbackBehavior", "Unable to read unknown from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
} }
void KnockbackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { void KnockbackBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {

View File

@ -4,18 +4,20 @@
#include "dLogger.h" #include "dLogger.h"
void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) { void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, const BehaviorBranchContext branch) {
uint32_t movementType{};
if (!bitStream->Read(movementType)) {
if (this->m_groundAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && if (this->m_groundAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY &&
this->m_jumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_jumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY &&
this->m_fallingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_fallingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY &&
this->m_doubleJumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_doubleJumpAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY &&
this->m_airAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY && this->m_airAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY &&
this->m_jetpackAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) { this->m_jetpackAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY &&
this->m_movingAction->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) {
return; return;
} }
Game::logger->Log("MovementSwitchBehavior", "Unable to read movementType from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
uint32_t movementType; return;
};
bitStream->Read(movementType);
switch (movementType) { switch (movementType) {
case 1: case 1:
@ -25,34 +27,40 @@ void MovementSwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream*
this->m_jumpAction->Handle(context, bitStream, branch); this->m_jumpAction->Handle(context, bitStream, branch);
break; break;
case 3: case 3:
this->m_fallingAction->Handle(context, bitStream, branch); this->m_airAction->Handle(context, bitStream, branch);
break; break;
case 4: case 4:
this->m_doubleJumpAction->Handle(context, bitStream, branch); this->m_doubleJumpAction->Handle(context, bitStream, branch);
break; break;
case 5: case 5:
this->m_airAction->Handle(context, bitStream, branch); this->m_fallingAction->Handle(context, bitStream, branch);
break; break;
case 6: case 6:
this->m_jetpackAction->Handle(context, bitStream, branch); this->m_jetpackAction->Handle(context, bitStream, branch);
break; break;
default: default:
Game::logger->Log("MovementSwitchBehavior", "Invalid movement behavior type (%i)!", movementType); this->m_groundAction->Handle(context, bitStream, branch);
break; break;
} }
} }
void MovementSwitchBehavior::Load() { Behavior* MovementSwitchBehavior::LoadMovementType(std::string movementType) {
this->m_airAction = GetAction("air_action"); float actionValue = GetFloat(movementType, -1.0f);
auto loadedBehavior = GetAction(actionValue != -1.0f ? actionValue : 0.0f);
this->m_doubleJumpAction = GetAction("double_jump_action"); if (actionValue == -1.0f && loadedBehavior->m_templateId == BehaviorTemplates::BEHAVIOR_EMPTY) {
loadedBehavior = this->m_groundAction;
this->m_fallingAction = GetAction("falling_action"); }
return loadedBehavior;
this->m_groundAction = GetAction("ground_action");
this->m_jetpackAction = GetAction("jetpack_action");
this->m_jumpAction = GetAction("jump_action");
} }
void MovementSwitchBehavior::Load() {
float groundActionValue = GetFloat("ground_action", -1.0f);
this->m_groundAction = GetAction(groundActionValue != -1.0f ? groundActionValue : 0.0f);
this->m_airAction = LoadMovementType("air_action");
this->m_doubleJumpAction = LoadMovementType("double_jump_action");
this->m_fallingAction = LoadMovementType("falling_action");
this->m_jetpackAction = LoadMovementType("jetpack_action");
this->m_jumpAction = LoadMovementType("jump_action");
this->m_movingAction = LoadMovementType("moving_action");
}

View File

@ -3,7 +3,7 @@
class MovementSwitchBehavior final : public Behavior class MovementSwitchBehavior final : public Behavior
{ {
public: private:
/* /*
* Members * Members
*/ */
@ -19,6 +19,17 @@ public:
Behavior* m_jumpAction; Behavior* m_jumpAction;
Behavior* m_movingAction;
/**
* @brief Loads a movement type from the database into a behavior
*
* @param movementType The movement type to lookup in the database
* @param behaviorToLoad The Behavior where the result will be stored
*/
Behavior* LoadMovementType(std::string movementType);
public:
/* /*
* Inherited * Inherited
*/ */

View File

@ -6,6 +6,8 @@
#include "EntityManager.h" #include "EntityManager.h"
#include "SkillComponent.h" #include "SkillComponent.h"
#include "DestroyableComponent.h" #include "DestroyableComponent.h"
#include "CDClientDatabase.h"
#include "CDClientManager.h"
void OverTimeBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { void OverTimeBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
const auto originator = context->originator; const auto originator = context->originator;

View File

@ -8,9 +8,12 @@
#include "../dWorldServer/ObjectIDManager.h" #include "../dWorldServer/ObjectIDManager.h"
void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
LWOOBJID target; LWOOBJID target{};
bitStream->Read(target); if (!bitStream->Read(target)) {
Game::logger->Log("ProjectileAttackBehavior", "Unable to read target from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
auto* entity = EntityManager::Instance()->GetEntity(context->originator); auto* entity = EntityManager::Instance()->GetEntity(context->originator);
@ -28,17 +31,23 @@ void ProjectileAttackBehavior::Handle(BehaviorContext* context, RakNet::BitStrea
return; return;
} }
if (m_useMouseposit) { if (m_useMouseposit && !branch.isSync) {
NiPoint3 targetPosition = NiPoint3::ZERO; NiPoint3 targetPosition = NiPoint3::ZERO;
bitStream->Read(targetPosition); if (!bitStream->Read(targetPosition)) {
Game::logger->Log("ProjectileAttackBehavior", "Unable to read targetPosition from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
} }
auto* targetEntity = EntityManager::Instance()->GetEntity(target); auto* targetEntity = EntityManager::Instance()->GetEntity(target);
for (auto i = 0u; i < this->m_projectileCount; ++i) { for (auto i = 0u; i < this->m_projectileCount; ++i) {
LWOOBJID projectileId; LWOOBJID projectileId{};
bitStream->Read(projectileId); if (!bitStream->Read(projectileId)) {
Game::logger->Log("ProjectileAttackBehavior", "Unable to read projectileId from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
branch.target = target; branch.target = target;
branch.isProjectile = true; branch.isProjectile = true;
@ -98,7 +107,7 @@ void ProjectileAttackBehavior::Calculate(BehaviorContext* context, RakNet::BitSt
for (auto i = 0u; i < this->m_projectileCount; ++i) { for (auto i = 0u; i < this->m_projectileCount; ++i) {
auto id = static_cast<LWOOBJID>(ObjectIDManager::Instance()->GenerateObjectID()); auto id = static_cast<LWOOBJID>(ObjectIDManager::Instance()->GenerateObjectID());
id = GeneralUtils::SetBit(id, OBJECT_BIT_CLIENT); id = GeneralUtils::SetBit(id, OBJECT_BIT_SPAWNED);
bitStream->Write(id); bitStream->Write(id);
@ -148,4 +157,6 @@ void ProjectileAttackBehavior::Load() {
this->m_trackRadius = GetFloat("track_radius"); this->m_trackRadius = GetFloat("track_radius");
this->m_useMouseposit = GetBoolean("use_mouseposit"); this->m_useMouseposit = GetBoolean("use_mouseposit");
this->m_ProjectileType = GetInt("projectile_type");
} }

View File

@ -23,6 +23,8 @@ public:
bool m_useMouseposit; bool m_useMouseposit;
int32_t m_ProjectileType;
/* /*
* Inherited * Inherited
*/ */

View File

@ -0,0 +1,61 @@
#include "PropertyTeleportBehavior.h"
#include "BehaviorBranchContext.h"
#include "BehaviorContext.h"
#include "Character.h"
#include "CharacterComponent.h"
#include "ChatPackets.h"
#include "WorldPackets.h"
#include "EntityManager.h"
#include "Game.h"
#include "ZoneInstanceManager.h"
#include "dZoneManager.h"
void PropertyTeleportBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
auto* caster = EntityManager::Instance()->GetEntity(context->caster);
if (!caster) return;
auto* character = caster->GetCharacter();
if (!character) return;
LWOOBJID objId = caster->GetObjectID();
LWOMAPID targetMapId = m_MapId;
LWOCLONEID targetCloneId = character->GetPropertyCloneID();
if (dZoneManager::Instance()->GetZoneID().GetCloneID() == character->GetPropertyCloneID()) {
targetMapId = character->GetLastNonInstanceZoneID();
targetCloneId = 0;
} else {
character->SetLastNonInstanceZoneID(dZoneManager::Instance()->GetZoneID().GetMapID());
}
ZoneInstanceManager::Instance()->RequestZoneTransfer(Game::server, targetMapId, targetCloneId, false, [objId](bool mythranShift, uint32_t zoneID, uint32_t zoneInstance, uint32_t zoneClone, std::string serverIP, uint16_t serverPort) {
auto* entity = EntityManager::Instance()->GetEntity(objId);
if (!entity) return;
const auto sysAddr = entity->GetSystemAddress();
if (zoneClone != 0) ChatPackets::SendSystemMessage(sysAddr, u"Transfering to your property!");
else ChatPackets::SendSystemMessage(sysAddr, u"Transfering back to previous world!");
Game::logger->Log("PropertyTeleportBehavior", "Transferring %s to Zone %i (Instance %i | Clone %i | Mythran Shift: %s) with IP %s and Port %i", sysAddr.ToString(), zoneID, zoneInstance, zoneClone, mythranShift == true ? "true" : "false", serverIP.c_str(), serverPort);
if (entity->GetCharacter()) {
entity->GetCharacter()->SetZoneID(zoneID);
entity->GetCharacter()->SetZoneInstance(zoneInstance);
entity->GetCharacter()->SetZoneClone(zoneClone);
entity->GetComponent<CharacterComponent>()->SetLastRocketConfig(u"");
}
entity->GetCharacter()->SaveXMLToDatabase();
WorldPackets::SendTransferToWorld(sysAddr, serverIP, serverPort, mythranShift);
return;
});
}
void PropertyTeleportBehavior::Load() {
this->m_CancelIfInteracting = GetBoolean("cancel_if_interacting"); // TODO unused
this->m_MapId = LWOMAPID(GetInt("mapID"));
}

View File

@ -0,0 +1,21 @@
#pragma once
#include "Behavior.h"
class PropertyTeleportBehavior final : public Behavior
{
public:
/*
* Inherited
*/
explicit PropertyTeleportBehavior(const uint32_t behavior_id) : Behavior(behavior_id) {
}
void Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) override;
void Load() override;
private:
LWOMAPID m_MapId;
bool m_CancelIfInteracting;
};

View File

@ -7,6 +7,8 @@
#include "dLogger.h" #include "dLogger.h"
#include "DestroyableComponent.h" #include "DestroyableComponent.h"
#include "RebuildComponent.h" #include "RebuildComponent.h"
#include "Entity.h"
#include "EntityInfo.h"
void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { void SpawnBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
auto* origin = EntityManager::Instance()->GetEntity(context->originator); auto* origin = EntityManager::Instance()->GetEntity(context->originator);

View File

@ -7,85 +7,48 @@
void SpeedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) { void SpeedBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
if (m_AffectsCaster) { if (m_AffectsCaster) branch.target = context->caster;
branch.target = context->caster;
}
auto* target = EntityManager::Instance()->GetEntity(branch.target); auto* target = EntityManager::Instance()->GetEntity(branch.target);
if (!target) return;
if (target == nullptr) {
return;
}
auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>(); auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>();
if (!controllablePhysicsComponent) return;
if (controllablePhysicsComponent == nullptr) { controllablePhysicsComponent->AddSpeedboost(m_RunSpeed);
return;
}
const auto current = controllablePhysicsComponent->GetSpeedMultiplier();
controllablePhysicsComponent->SetSpeedMultiplier(current + ((m_RunSpeed - 500.0f) / 500.0f));
EntityManager::Instance()->SerializeEntity(target); EntityManager::Instance()->SerializeEntity(target);
if (branch.duration > 0.0f) { if (branch.duration > 0.0f) {
context->RegisterTimerBehavior(this, branch); context->RegisterTimerBehavior(this, branch);
} else if (branch.start > 0) { } else if (branch.start > 0) {
controllablePhysicsComponent->SetIgnoreMultipliers(true);
context->RegisterEndBehavior(this, branch); context->RegisterEndBehavior(this, branch);
} }
} }
void SpeedBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
Handle(context, bitStream, branch);
}
void SpeedBehavior::UnCast(BehaviorContext* context, BehaviorBranchContext branch) {
End(context, branch, LWOOBJID_EMPTY);
}
void SpeedBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { void SpeedBehavior::Timer(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) {
auto* target = EntityManager::Instance()->GetEntity(branch.target); End(context, branch, second);
if (target == nullptr) {
return;
}
auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>();
if (controllablePhysicsComponent == nullptr) {
return;
}
const auto current = controllablePhysicsComponent->GetSpeedMultiplier();
controllablePhysicsComponent->SetSpeedMultiplier(current - ((m_RunSpeed - 500.0f) / 500.0f));
EntityManager::Instance()->SerializeEntity(target);
} }
void SpeedBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) { void SpeedBehavior::End(BehaviorContext* context, BehaviorBranchContext branch, LWOOBJID second) {
auto* target = EntityManager::Instance()->GetEntity(branch.target); auto* target = EntityManager::Instance()->GetEntity(branch.target);
if (!target) return;
if (target == nullptr) {
return;
}
auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>(); auto* controllablePhysicsComponent = target->GetComponent<ControllablePhysicsComponent>();
if (!controllablePhysicsComponent) return;
if (controllablePhysicsComponent == nullptr) { controllablePhysicsComponent->RemoveSpeedboost(m_RunSpeed);
return;
}
const auto current = controllablePhysicsComponent->GetSpeedMultiplier();
controllablePhysicsComponent->SetIgnoreMultipliers(false);
controllablePhysicsComponent->SetSpeedMultiplier(current - ((m_RunSpeed - 500.0f) / 500.0f));
EntityManager::Instance()->SerializeEntity(target); EntityManager::Instance()->SerializeEntity(target);
} }
void SpeedBehavior::Load() { void SpeedBehavior::Load() {
m_RunSpeed = GetFloat("run_speed"); m_RunSpeed = GetFloat("run_speed");
if (m_RunSpeed < 500.0f) {
m_RunSpeed = 500.0f;
}
m_AffectsCaster = GetBoolean("affects_caster"); m_AffectsCaster = GetBoolean("affects_caster");
} }

View File

@ -13,6 +13,10 @@ public:
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 UnCast(BehaviorContext* context, 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;

View File

@ -14,8 +14,11 @@ void StunBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream
return; return;
} }
bool blocked; bool blocked{};
bitStream->Read(blocked); if (!bitStream->Read(blocked)) {
Game::logger->Log("StunBehavior", "Unable to read blocked from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
auto* target = EntityManager::Instance()->GetEntity(branch.target); auto* target = EntityManager::Instance()->GetEntity(branch.target);

View File

@ -10,7 +10,10 @@ void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre
auto state = true; auto state = true;
if (this->m_imagination > 0 || !this->m_isEnemyFaction) { if (this->m_imagination > 0 || !this->m_isEnemyFaction) {
bitStream->Read(state); if (!bitStream->Read(state)) {
Game::logger->Log("SwitchBehavior", "Unable to read state from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
} }
auto* entity = EntityManager::Instance()->GetEntity(context->originator); auto* entity = EntityManager::Instance()->GetEntity(context->originator);
@ -25,7 +28,7 @@ void SwitchBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre
return; return;
} }
Game::logger->Log("SwitchBehavior", "[%i] State: (%d), imagination: (%i) / (%f)", entity->GetLOT(), state, destroyableComponent->GetImagination(), destroyableComponent->GetMaxImagination()); Game::logger->LogDebug("SwitchBehavior", "[%i] State: (%d), imagination: (%i) / (%f)", entity->GetLOT(), state, destroyableComponent->GetImagination(), destroyableComponent->GetMaxImagination());
if (state || (entity->GetLOT() == 8092 && destroyableComponent->GetImagination() >= m_imagination)) { if (state || (entity->GetLOT() == 8092 && destroyableComponent->GetImagination() >= m_imagination)) {
this->m_actionTrue->Handle(context, bitStream, branch); this->m_actionTrue->Handle(context, bitStream, branch);

View File

@ -9,10 +9,13 @@
#include "EntityManager.h" #include "EntityManager.h"
void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
float value; float value{};
bit_stream->Read(value); if (!bitStream->Read(value)) {
Game::logger->Log("SwitchMultipleBehavior", "Unable to read value from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
uint32_t trigger = 0; uint32_t trigger = 0;
@ -30,10 +33,10 @@ void SwitchMultipleBehavior::Handle(BehaviorContext* context, RakNet::BitStream*
auto* behavior = this->m_behaviors.at(trigger).second; auto* behavior = this->m_behaviors.at(trigger).second;
behavior->Handle(context, bit_stream, branch); behavior->Handle(context, bitStream, branch);
} }
void SwitchMultipleBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bit_stream, BehaviorBranchContext branch) { void SwitchMultipleBehavior::Calculate(BehaviorContext* context, RakNet::BitStream* bitStream, BehaviorBranchContext branch) {
// TODO // TODO
} }

View File

@ -20,12 +20,18 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre
bool hit = false; bool hit = false;
bitStream->Read(hit); if (!bitStream->Read(hit)) {
Game::logger->Log("TacArcBehavior", "Unable to read hit from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
if (this->m_checkEnv) { if (this->m_checkEnv) {
bool blocked = false; bool blocked = false;
bitStream->Read(blocked); if (!bitStream->Read(blocked)) {
Game::logger->Log("TacArcBehavior", "Unable to read blocked from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
if (blocked) { if (blocked) {
this->m_blockedAction->Handle(context, bitStream, branch); this->m_blockedAction->Handle(context, bitStream, branch);
@ -37,7 +43,10 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre
if (hit) { if (hit) {
uint32_t count = 0; uint32_t count = 0;
bitStream->Read(count); if (!bitStream->Read(count)) {
Game::logger->Log("TacArcBehavior", "Unable to read count from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
if (count > m_maxTargets && m_maxTargets > 0) { if (count > m_maxTargets && m_maxTargets > 0) {
count = m_maxTargets; count = m_maxTargets;
@ -46,9 +55,12 @@ void TacArcBehavior::Handle(BehaviorContext* context, RakNet::BitStream* bitStre
std::vector<LWOOBJID> targets; std::vector<LWOOBJID> targets;
for (auto i = 0u; i < count; ++i) { for (auto i = 0u; i < count; ++i) {
LWOOBJID id; LWOOBJID id{};
bitStream->Read(id); if (!bitStream->Read(id)) {
Game::logger->Log("TacArcBehavior", "Unable to read id from bitStream, aborting Handle! %i", bitStream->GetNumberOfUnreadBits());
return;
};
targets.push_back(id); targets.push_back(id);
} }

View File

@ -25,7 +25,7 @@
BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id): Component(parent) { BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id): Component(parent) {
m_Target = LWOOBJID_EMPTY; m_Target = LWOOBJID_EMPTY;
m_State = AiState::spawn; SetAiState(AiState::spawn);
m_Timer = 1.0f; m_Timer = 1.0f;
m_StartPosition = parent->GetPosition(); m_StartPosition = parent->GetPosition();
m_MovementAI = nullptr; m_MovementAI = nullptr;
@ -179,7 +179,7 @@ void BaseCombatAIComponent::Update(const float deltaTime) {
if (m_Disabled || m_Parent->GetIsDead()) if (m_Disabled || m_Parent->GetIsDead())
return; return;
bool stunnedThisFrame = m_Stunned;
CalculateCombat(deltaTime); // Putting this here for now CalculateCombat(deltaTime); // Putting this here for now
if (m_StartPosition == NiPoint3::ZERO) { if (m_StartPosition == NiPoint3::ZERO) {
@ -192,7 +192,7 @@ void BaseCombatAIComponent::Update(const float deltaTime) {
return; return;
} }
if (m_Stunned) { if (stunnedThisFrame) {
m_MovementAI->Stop(); m_MovementAI->Stop();
return; return;
@ -206,7 +206,7 @@ void BaseCombatAIComponent::Update(const float deltaTime) {
switch (m_State) { switch (m_State) {
case AiState::spawn: case AiState::spawn:
Stun(2.0f); Stun(2.0f);
m_State = AiState::idle; SetAiState(AiState::idle);
break; break;
case AiState::idle: case AiState::idle:
@ -248,13 +248,13 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) {
if (m_Disabled) return; if (m_Disabled) return;
if (m_StunTime > 0.0f) { if (m_Stunned) {
m_StunTime -= deltaTime; m_StunTime -= deltaTime;
if (m_StunTime > 0.0f) { if (m_StunTime > 0.0f) {
return; return;
} }
m_StunTime = 0.0f;
m_Stunned = false; m_Stunned = false;
} }
@ -320,9 +320,9 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) {
m_Timer = 0; m_Timer = 0;
} }
m_State = AiState::aggro; SetAiState(AiState::aggro);
} else { } else {
m_State = AiState::idle; SetAiState(AiState::idle);
} }
for (auto i = 0; i < m_SkillEntries.size(); ++i) { for (auto i = 0; i < m_SkillEntries.size(); ++i) {
@ -348,7 +348,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) {
} }
if (m_Target == LWOOBJID_EMPTY) { if (m_Target == LWOOBJID_EMPTY) {
m_State = AiState::idle; SetAiState(AiState::idle);
return; return;
} }
@ -375,7 +375,7 @@ void BaseCombatAIComponent::CalculateCombat(const float deltaTime) {
m_MovementAI->Stop(); m_MovementAI->Stop();
} }
m_State = AiState::aggro; SetAiState(AiState::aggro);
m_Timer = 0; m_Timer = 0;
@ -532,11 +532,20 @@ bool BaseCombatAIComponent::IsMech() {
void BaseCombatAIComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { void BaseCombatAIComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) {
outBitStream->Write1(); outBitStream->Write(m_DirtyStateOrTarget || bIsInitialUpdate);
if (m_DirtyStateOrTarget || bIsInitialUpdate) {
outBitStream->Write(uint32_t(m_State)); outBitStream->Write(uint32_t(m_State));
outBitStream->Write(m_Target); outBitStream->Write(m_Target);
m_DirtyStateOrTarget = false;
}
} }
void BaseCombatAIComponent::SetAiState(AiState newState) {
if (newState == this->m_State) return;
this->m_State = newState;
m_DirtyStateOrTarget = true;
EntityManager::Instance()->SerializeEntity(m_Parent);
}
bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const { bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const {
auto* entity = EntityManager::Instance()->GetEntity(target); auto* entity = EntityManager::Instance()->GetEntity(target);
@ -585,7 +594,10 @@ bool BaseCombatAIComponent::IsEnemy(LWOOBJID target) const {
} }
void BaseCombatAIComponent::SetTarget(const LWOOBJID target) { void BaseCombatAIComponent::SetTarget(const LWOOBJID target) {
if (this->m_Target == target) return;
m_Target = target; m_Target = target;
m_DirtyStateOrTarget = true;
EntityManager::Instance()->SerializeEntity(m_Parent);
} }
Entity* BaseCombatAIComponent::GetTargetEntity() const { Entity* BaseCombatAIComponent::GetTargetEntity() const {
@ -700,7 +712,7 @@ void BaseCombatAIComponent::OnAggro() {
m_MovementAI->SetDestination(targetPos); m_MovementAI->SetDestination(targetPos);
m_State = AiState::tether; SetAiState(AiState::tether);
} }
m_Timer += 0.5f; m_Timer += 0.5f;
@ -726,7 +738,7 @@ void BaseCombatAIComponent::OnTether() {
m_MovementAI->SetDestination(m_StartPosition); m_MovementAI->SetDestination(m_StartPosition);
m_State = AiState::aggro; SetAiState(AiState::aggro);
} else { } else {
if (IsMech() && Vector3::DistanceSquared(targetPos, currentPos) > m_AttackRadius * m_AttackRadius * 3 * 3) return; if (IsMech() && Vector3::DistanceSquared(targetPos, currentPos) > m_AttackRadius * m_AttackRadius * 3 * 3) return;

View File

@ -243,6 +243,12 @@ private:
*/ */
std::vector<LWOOBJID> GetTargetWithinAggroRange() const; std::vector<LWOOBJID> GetTargetWithinAggroRange() const;
/**
* @brief Sets the AiState and prepares the entity for serialization next frame.
*
*/
void SetAiState(AiState newState);
/** /**
* The current state of the AI * The current state of the AI
*/ */
@ -374,6 +380,12 @@ private:
*/ */
bool m_DirtyThreat = false; bool m_DirtyThreat = false;
/**
* Whether or not the Component has dirty information and should update next frame
*
*/
bool m_DirtyStateOrTarget = false;
/** /**
* Whether the current entity is a mech enemy, needed as mechs tether radius works differently * Whether the current entity is a mech enemy, needed as mechs tether radius works differently
* @return whether this entity is a mech * @return whether this entity is a mech

View File

@ -9,6 +9,7 @@
#include "SkillComponent.h" #include "SkillComponent.h"
#include "ControllablePhysicsComponent.h" #include "ControllablePhysicsComponent.h"
#include "EntityManager.h" #include "EntityManager.h"
#include "CDClientManager.h"
std::unordered_map<int32_t, std::vector<BuffParameter>> BuffComponent::m_Cache{}; std::unordered_map<int32_t, std::vector<BuffParameter>> BuffComponent::m_Cache{};
@ -169,17 +170,10 @@ void BuffComponent::ApplyBuffEffect(int32_t id) {
destroyable->SetMaxImagination(destroyable->GetMaxImagination() + maxImagination); destroyable->SetMaxImagination(destroyable->GetMaxImagination() + maxImagination);
} else if (parameter.name == "speed") { } else if (parameter.name == "speed") {
const auto speed = parameter.value;
auto* controllablePhysicsComponent = this->GetParent()->GetComponent<ControllablePhysicsComponent>(); auto* controllablePhysicsComponent = this->GetParent()->GetComponent<ControllablePhysicsComponent>();
if (!controllablePhysicsComponent) return;
if (controllablePhysicsComponent == nullptr) return; const auto speed = parameter.value;
controllablePhysicsComponent->AddSpeedboost(speed);
const auto current = controllablePhysicsComponent->GetSpeedMultiplier();
controllablePhysicsComponent->SetSpeedMultiplier(current + ((speed - 500.0f) / 500.0f));
EntityManager::Instance()->SerializeEntity(this->GetParent());
} }
} }
} }
@ -212,17 +206,10 @@ void BuffComponent::RemoveBuffEffect(int32_t id) {
destroyable->SetMaxImagination(destroyable->GetMaxImagination() - maxImagination); destroyable->SetMaxImagination(destroyable->GetMaxImagination() - maxImagination);
} else if (parameter.name == "speed") { } else if (parameter.name == "speed") {
const auto speed = parameter.value;
auto* controllablePhysicsComponent = this->GetParent()->GetComponent<ControllablePhysicsComponent>(); auto* controllablePhysicsComponent = this->GetParent()->GetComponent<ControllablePhysicsComponent>();
if (!controllablePhysicsComponent) return;
if (controllablePhysicsComponent == nullptr) return; const auto speed = parameter.value;
controllablePhysicsComponent->RemoveSpeedboost(speed);
const auto current = controllablePhysicsComponent->GetSpeedMultiplier();
controllablePhysicsComponent->SetSpeedMultiplier(current - ((speed - 500.0f) / 500.0f));
EntityManager::Instance()->SerializeEntity(this->GetParent());
} }
} }
} }

View File

@ -13,6 +13,7 @@
#include "VehiclePhysicsComponent.h" #include "VehiclePhysicsComponent.h"
#include "GameMessages.h" #include "GameMessages.h"
#include "Item.h" #include "Item.h"
#include "AMFFormat.h"
CharacterComponent::CharacterComponent(Entity* parent, Character* character) : Component(parent) { CharacterComponent::CharacterComponent(Entity* parent, Character* character) : Component(parent) {
m_Character = character; m_Character = character;

View File

@ -12,6 +12,7 @@
#include "EntityManager.h" #include "EntityManager.h"
#include "Character.h" #include "Character.h"
#include "dZoneManager.h" #include "dZoneManager.h"
#include "LevelProgressionComponent.h"
ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Component(entity) { ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Component(entity) {
m_Position = {}; m_Position = {};
@ -30,10 +31,25 @@ ControllablePhysicsComponent::ControllablePhysicsComponent(Entity* entity) : Com
m_GravityScale = 1; m_GravityScale = 1;
m_DirtyCheats = false; m_DirtyCheats = false;
m_IgnoreMultipliers = false; m_IgnoreMultipliers = false;
m_DirtyEquippedItemInfo = true;
m_PickupRadius = 0.0f; m_PickupRadius = 0.0f;
m_DirtyPickupRadiusScale = true;
m_DirtyBubble = false;
m_IsInBubble = false;
m_SpecialAnims = false;
m_BubbleType = eBubbleType::DEFAULT;
m_IsTeleporting = false; m_IsTeleporting = false;
m_ImmuneToStunAttackCount = 0;
m_ImmuneToStunEquipCount = 0;
m_ImmuneToStunInteractCount = 0;
m_ImmuneToStunJumpCount = 0;
m_ImmuneToStunMoveCount = 0;
m_ImmuneToStunTurnCount = 0;
m_ImmuneToStunUseItemCount = 0;
if (entity->GetLOT() != 1) // Other physics entities we care about will be added by BaseCombatAI if (entity->GetLOT() != 1) // Other physics entities we care about will be added by BaseCombatAI
return; return;
@ -70,16 +86,17 @@ void ControllablePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bo
outBitStream->Write(m_JetpackBypassChecks); outBitStream->Write(m_JetpackBypassChecks);
} }
outBitStream->Write0(); //This contains info about immunities, but for now I'm leaving it out. outBitStream->Write1(); // always write these on construction
outBitStream->Write(m_ImmuneToStunMoveCount);
outBitStream->Write(m_ImmuneToStunJumpCount);
outBitStream->Write(m_ImmuneToStunTurnCount);
outBitStream->Write(m_ImmuneToStunAttackCount);
outBitStream->Write(m_ImmuneToStunUseItemCount);
outBitStream->Write(m_ImmuneToStunEquipCount);
outBitStream->Write(m_ImmuneToStunInteractCount);
} }
if (m_SpeedMultiplier < 1.0f) { if (m_IgnoreMultipliers) m_DirtyCheats = false;
m_DirtyCheats = false;
}
if (m_IgnoreMultipliers) {
m_DirtyCheats = false;
}
outBitStream->Write(m_DirtyCheats); outBitStream->Write(m_DirtyCheats);
if (m_DirtyCheats) { if (m_DirtyCheats) {
@ -89,14 +106,22 @@ void ControllablePhysicsComponent::Serialize(RakNet::BitStream* outBitStream, bo
m_DirtyCheats = false; m_DirtyCheats = false;
} }
outBitStream->Write(m_DirtyPickupRadiusScale); outBitStream->Write(m_DirtyEquippedItemInfo);
if (m_DirtyPickupRadiusScale) { if (m_DirtyEquippedItemInfo) {
outBitStream->Write(m_PickupRadius); outBitStream->Write(m_PickupRadius);
outBitStream->Write0(); //No clue what this is so im leaving it false. outBitStream->Write(m_InJetpackMode);
m_DirtyPickupRadiusScale = false; m_DirtyEquippedItemInfo = false;
} }
outBitStream->Write0(); outBitStream->Write(m_DirtyBubble);
if (m_DirtyBubble) {
outBitStream->Write(m_IsInBubble);
if (m_IsInBubble) {
outBitStream->Write(m_BubbleType);
outBitStream->Write(m_SpecialAnims);
}
m_DirtyBubble = false;
}
outBitStream->Write(m_DirtyPosition || bIsInitialUpdate); outBitStream->Write(m_DirtyPosition || bIsInitialUpdate);
if (m_DirtyPosition || bIsInitialUpdate) { if (m_DirtyPosition || bIsInitialUpdate) {
@ -253,7 +278,7 @@ void ControllablePhysicsComponent::AddPickupRadiusScale(float value) {
m_ActivePickupRadiusScales.push_back(value); m_ActivePickupRadiusScales.push_back(value);
if (value > m_PickupRadius) { if (value > m_PickupRadius) {
m_PickupRadius = value; m_PickupRadius = value;
m_DirtyPickupRadiusScale = true; m_DirtyEquippedItemInfo = true;
} }
} }
@ -263,16 +288,102 @@ void ControllablePhysicsComponent::RemovePickupRadiusScale(float value) {
if (pos != m_ActivePickupRadiusScales.end()) { if (pos != m_ActivePickupRadiusScales.end()) {
m_ActivePickupRadiusScales.erase(pos); m_ActivePickupRadiusScales.erase(pos);
} else { } else {
Game::logger->Log("ControllablePhysicsComponent", "Warning: Could not find pickup radius %f in list of active radii. List has %i active radii.", value, m_ActivePickupRadiusScales.size()); Game::logger->LogDebug("ControllablePhysicsComponent", "Warning: Could not find pickup radius %f in list of active radii. List has %i active radii.", value, m_ActivePickupRadiusScales.size());
return; return;
} }
// Recalculate pickup radius since we removed one by now // Recalculate pickup radius since we removed one by now
m_PickupRadius = 0.0f; m_PickupRadius = 0.0f;
m_DirtyPickupRadiusScale = true; m_DirtyEquippedItemInfo = true;
for (uint32_t i = 0; i < m_ActivePickupRadiusScales.size(); i++) { for (uint32_t i = 0; i < m_ActivePickupRadiusScales.size(); i++) {
auto candidateRadius = m_ActivePickupRadiusScales[i]; auto candidateRadius = m_ActivePickupRadiusScales[i];
if (m_PickupRadius < candidateRadius) m_PickupRadius = candidateRadius; if (m_PickupRadius < candidateRadius) m_PickupRadius = candidateRadius;
} }
EntityManager::Instance()->SerializeEntity(m_Parent); EntityManager::Instance()->SerializeEntity(m_Parent);
} }
void ControllablePhysicsComponent::AddSpeedboost(float value) {
m_ActiveSpeedBoosts.push_back(value);
m_SpeedBoost = value;
SetSpeedMultiplier(value / 500.0f); // 500 being the base speed
}
void ControllablePhysicsComponent::RemoveSpeedboost(float value) {
const auto pos = std::find(m_ActiveSpeedBoosts.begin(), m_ActiveSpeedBoosts.end(), value);
if (pos != m_ActiveSpeedBoosts.end()) {
m_ActiveSpeedBoosts.erase(pos);
} else {
Game::logger->LogDebug("ControllablePhysicsComponent", "Warning: Could not find speedboost %f in list of active speedboosts. List has %i active speedboosts.", value, m_ActiveSpeedBoosts.size());
return;
}
// Recalculate speedboost since we removed one
m_SpeedBoost = 0.0f;
if (m_ActiveSpeedBoosts.size() == 0) { // no active speed boosts left, so return to base speed
auto* levelProgressionComponent = m_Parent->GetComponent<LevelProgressionComponent>();
if (levelProgressionComponent) m_SpeedBoost = levelProgressionComponent->GetSpeedBase();
} else { // Used the last applied speedboost
m_SpeedBoost = m_ActiveSpeedBoosts.back();
}
SetSpeedMultiplier(m_SpeedBoost / 500.0f); // 500 being the base speed
EntityManager::Instance()->SerializeEntity(m_Parent);
}
void ControllablePhysicsComponent::ActivateBubbleBuff(eBubbleType bubbleType, bool specialAnims){
if (m_IsInBubble) {
Game::logger->Log("ControllablePhysicsComponent", "Already in bubble");
return;
}
m_BubbleType = bubbleType;
m_IsInBubble = true;
m_DirtyBubble = true;
m_SpecialAnims = specialAnims;
EntityManager::Instance()->SerializeEntity(m_Parent);
}
void ControllablePhysicsComponent::DeactivateBubbleBuff(){
m_DirtyBubble = true;
m_IsInBubble = false;
EntityManager::Instance()->SerializeEntity(m_Parent);
};
void ControllablePhysicsComponent::SetStunImmunity(
const eStateChangeType state,
const LWOOBJID originator,
const bool bImmuneToStunAttack,
const bool bImmuneToStunEquip,
const bool bImmuneToStunInteract,
const bool bImmuneToStunJump,
const bool bImmuneToStunMove,
const bool bImmuneToStunTurn,
const bool bImmuneToStunUseItem){
if (state == eStateChangeType::POP){
if (bImmuneToStunAttack && m_ImmuneToStunAttackCount > 0) m_ImmuneToStunAttackCount -= 1;
if (bImmuneToStunEquip && m_ImmuneToStunEquipCount > 0) m_ImmuneToStunEquipCount -= 1;
if (bImmuneToStunInteract && m_ImmuneToStunInteractCount > 0) m_ImmuneToStunInteractCount -= 1;
if (bImmuneToStunJump && m_ImmuneToStunJumpCount > 0) m_ImmuneToStunJumpCount -= 1;
if (bImmuneToStunMove && m_ImmuneToStunMoveCount > 0) m_ImmuneToStunMoveCount -= 1;
if (bImmuneToStunTurn && m_ImmuneToStunTurnCount > 0) m_ImmuneToStunTurnCount -= 1;
if (bImmuneToStunUseItem && m_ImmuneToStunUseItemCount > 0) m_ImmuneToStunUseItemCount -= 1;
} else if (state == eStateChangeType::PUSH) {
if (bImmuneToStunAttack) m_ImmuneToStunAttackCount += 1;
if (bImmuneToStunEquip) m_ImmuneToStunEquipCount += 1;
if (bImmuneToStunInteract) m_ImmuneToStunInteractCount += 1;
if (bImmuneToStunJump) m_ImmuneToStunJumpCount += 1;
if (bImmuneToStunMove) m_ImmuneToStunMoveCount += 1;
if (bImmuneToStunTurn) m_ImmuneToStunTurnCount += 1;
if (bImmuneToStunUseItem) m_ImmuneToStunUseItemCount += 1;
}
GameMessages::SendSetStunImmunity(
m_Parent->GetObjectID(), state, m_Parent->GetSystemAddress(), originator,
bImmuneToStunAttack,
bImmuneToStunEquip,
bImmuneToStunInteract,
bImmuneToStunJump,
bImmuneToStunMove,
bImmuneToStunTurn,
bImmuneToStunUseItem
);
}

View File

@ -9,6 +9,7 @@
#include "Component.h" #include "Component.h"
#include "dpCollisionChecks.h" #include "dpCollisionChecks.h"
#include "PhantomPhysicsComponent.h" #include "PhantomPhysicsComponent.h"
#include "eBubbleType.h"
class Entity; class Entity;
class dpEntity; class dpEntity;
@ -257,6 +258,63 @@ public:
*/ */
std::vector<float> GetActivePickupRadiusScales() { return m_ActivePickupRadiusScales; }; std::vector<float> GetActivePickupRadiusScales() { return m_ActivePickupRadiusScales; };
/**
* Add a Speed boost to the entity
* This will recalculate the speed boost based on what is being added
*/
void AddSpeedboost(float value);
/**
* Remove speed boost from entity
* This will recalculate the speed boost based on what is the last one in te vector
*/
void RemoveSpeedboost(float value);
/**
* The speed boosts of this component.
* @return All active Speed boosts for this component.
*/
std::vector<float> GetActiveSpeedboosts() { return m_ActivePickupRadiusScales; };
/**
* Activates the Bubble Buff
*/
void ActivateBubbleBuff(eBubbleType bubbleType = eBubbleType::DEFAULT, bool specialAnims = true);
/**
* Deactivates the Bubble Buff
*/
void DeactivateBubbleBuff();
/**
* Gets if the Entity is in a bubble
*/
bool GetIsInBubble(){ return m_IsInBubble; };
/**
* Push or Pop a layer of stun immunity to this entity
*/
void SetStunImmunity(
const eStateChangeType state,
const LWOOBJID originator = LWOOBJID_EMPTY,
const bool bImmuneToStunAttack = false,
const bool bImmuneToStunEquip = false,
const bool bImmuneToStunInteract = false,
const bool bImmuneToStunJump = false,
const bool bImmuneToStunMove = false,
const bool bImmuneToStunTurn = false,
const bool bImmuneToStunUseItem = false
);
// getters for stun immunities
const bool GetImmuneToStunAttack() { return m_ImmuneToStunAttackCount > 0;};
const bool GetImmuneToStunEquip() { return m_ImmuneToStunEquipCount > 0;};
const bool GetImmuneToStunInteract() { return m_ImmuneToStunInteractCount > 0;};
const bool GetImmuneToStunJump() { return m_ImmuneToStunJumpCount > 0;};
const bool GetImmuneToStunMove() { return m_ImmuneToStunMoveCount > 0;};
const bool GetImmuneToStunTurn() { return m_ImmuneToStunTurnCount > 0;};
const bool GetImmuneToStunUseItem() { return m_ImmuneToStunUseItemCount > 0;};
private: private:
/** /**
* The entity that owns this component * The entity that owns this component
@ -356,7 +414,7 @@ private:
/** /**
* Whether the pickup scale is dirty. * Whether the pickup scale is dirty.
*/ */
bool m_DirtyPickupRadiusScale; bool m_DirtyEquippedItemInfo;
/** /**
* The list of pickup radius scales for this entity * The list of pickup radius scales for this entity
@ -372,6 +430,47 @@ private:
* If the entity is teleporting * If the entity is teleporting
*/ */
bool m_IsTeleporting; bool m_IsTeleporting;
/**
* The list of speed boosts for this entity
*/
std::vector<float> m_ActiveSpeedBoosts;
/**
* The active speed boost for this entity
*/
float m_SpeedBoost;
/*
* If Bubble info is dirty
*/
bool m_DirtyBubble;
/*
* If the entity is in a bubble
*/
bool m_IsInBubble;
/*
* The type of bubble the entity has
*/
eBubbleType m_BubbleType;
/*
* If the entity should be using the special animations
*/
bool m_SpecialAnims;
/**
* stun immunity counters
*/
int32_t m_ImmuneToStunAttackCount;
int32_t m_ImmuneToStunEquipCount;
int32_t m_ImmuneToStunInteractCount;
int32_t m_ImmuneToStunJumpCount;
int32_t m_ImmuneToStunMoveCount;
int32_t m_ImmuneToStunTurnCount;
int32_t m_ImmuneToStunUseItemCount;
}; };
#endif // CONTROLLABLEPHYSICSCOMPONENT_H #endif // CONTROLLABLEPHYSICSCOMPONENT_H

View File

@ -28,7 +28,9 @@
#include "CharacterComponent.h" #include "CharacterComponent.h"
#include "PossessableComponent.h" #include "PossessableComponent.h"
#include "PossessorComponent.h" #include "PossessorComponent.h"
#include "InventoryComponent.h"
#include "dZoneManager.h" #include "dZoneManager.h"
#include "WorldConfig.h"
DestroyableComponent::DestroyableComponent(Entity* parent) : Component(parent) { DestroyableComponent::DestroyableComponent(Entity* parent) : Component(parent) {
m_iArmor = 0; m_iArmor = 0;
@ -53,8 +55,17 @@ DestroyableComponent::DestroyableComponent(Entity* parent) : Component(parent) {
m_LootMatrixID = 0; m_LootMatrixID = 0;
m_MinCoins = 0; m_MinCoins = 0;
m_MaxCoins = 0; m_MaxCoins = 0;
m_ImmuneStacks = 0;
m_DamageReduction = 0; m_DamageReduction = 0;
m_ImmuneToBasicAttackCount = 0;
m_ImmuneToDamageOverTimeCount = 0;
m_ImmuneToKnockbackCount = 0;
m_ImmuneToInterruptCount = 0;
m_ImmuneToSpeedCount = 0;
m_ImmuneToImaginationGainCount = 0;
m_ImmuneToImaginationLossCount = 0;
m_ImmuneToQuickbuildInterruptCount = 0;
m_ImmuneToPullToPointCount = 0;
} }
DestroyableComponent::~DestroyableComponent() { DestroyableComponent::~DestroyableComponent() {
@ -104,7 +115,16 @@ void DestroyableComponent::Reinitialize(LOT templateID) {
void DestroyableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags) { void DestroyableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, uint32_t& flags) {
if (bIsInitialUpdate) { if (bIsInitialUpdate) {
outBitStream->Write0(); //Contains info about immunities this object has, but it's left out for now. outBitStream->Write1(); // always write these on construction
outBitStream->Write(m_ImmuneToBasicAttackCount);
outBitStream->Write(m_ImmuneToDamageOverTimeCount);
outBitStream->Write(m_ImmuneToKnockbackCount);
outBitStream->Write(m_ImmuneToInterruptCount);
outBitStream->Write(m_ImmuneToSpeedCount);
outBitStream->Write(m_ImmuneToImaginationGainCount);
outBitStream->Write(m_ImmuneToImaginationLossCount);
outBitStream->Write(m_ImmuneToQuickbuildInterruptCount);
outBitStream->Write(m_ImmuneToPullToPointCount);
} }
outBitStream->Write(m_DirtyHealth || bIsInitialUpdate); outBitStream->Write(m_DirtyHealth || bIsInitialUpdate);
@ -334,7 +354,7 @@ void DestroyableComponent::SetDamageReduction(int32_t value) {
void DestroyableComponent::SetIsImmune(bool value) { void DestroyableComponent::SetIsImmune(bool value) {
m_DirtyHealth = true; m_DirtyHealth = true;
m_ImmuneStacks = value ? 1 : 0; m_ImmuneToBasicAttackCount = value ? 1 : 0;
} }
void DestroyableComponent::SetIsGMImmune(bool value) { void DestroyableComponent::SetIsGMImmune(bool value) {
@ -437,7 +457,7 @@ void DestroyableComponent::SetAttacksToBlock(const uint32_t value) {
} }
bool DestroyableComponent::IsImmune() const { bool DestroyableComponent::IsImmune() const {
return m_ImmuneStacks > 0 || m_IsGMImmune; return m_IsGMImmune || m_ImmuneToBasicAttackCount > 0;
} }
bool DestroyableComponent::IsKnockbackImmune() const { bool DestroyableComponent::IsKnockbackImmune() const {
@ -630,6 +650,7 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32
auto* attacker = EntityManager::Instance()->GetEntity(source); auto* attacker = EntityManager::Instance()->GetEntity(source);
m_Parent->OnHit(attacker); m_Parent->OnHit(attacker);
m_Parent->OnHitOrHealResult(attacker, sourceDamage); m_Parent->OnHitOrHealResult(attacker, sourceDamage);
NotifySubscribers(attacker, sourceDamage);
for (const auto& cb : m_OnHitCallbacks) { for (const auto& cb : m_OnHitCallbacks) {
cb(attacker); cb(attacker);
@ -647,6 +668,29 @@ void DestroyableComponent::Damage(uint32_t damage, const LWOOBJID source, uint32
Smash(source, eKillType::VIOLENT, u"", skillID); Smash(source, eKillType::VIOLENT, u"", skillID);
} }
void DestroyableComponent::Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd) {
m_SubscribedScripts.insert(std::make_pair(scriptObjId, scriptToAdd));
Game::logger->LogDebug("DestroyableComponent", "Added script %llu to entity %llu", scriptObjId, m_Parent->GetObjectID());
Game::logger->LogDebug("DestroyableComponent", "Number of subscribed scripts %i", m_SubscribedScripts.size());
}
void DestroyableComponent::Unsubscribe(LWOOBJID scriptObjId) {
auto foundScript = m_SubscribedScripts.find(scriptObjId);
if (foundScript != m_SubscribedScripts.end()) {
m_SubscribedScripts.erase(foundScript);
Game::logger->LogDebug("DestroyableComponent", "Removed script %llu from entity %llu", scriptObjId, m_Parent->GetObjectID());
} else {
Game::logger->LogDebug("DestroyableComponent", "Tried to remove a script for Entity %llu but script %llu didnt exist", m_Parent->GetObjectID(), scriptObjId);
}
Game::logger->LogDebug("DestroyableComponent", "Number of subscribed scripts %i", m_SubscribedScripts.size());
}
void DestroyableComponent::NotifySubscribers(Entity* attacker, uint32_t damage) {
for (auto script : m_SubscribedScripts) {
script.second->NotifyHitOrHealResult(m_Parent, attacker, damage);
}
}
void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType, uint32_t skillID) { void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType, const std::u16string& deathType, uint32_t skillID) {
if (m_iHealth > 0) { if (m_iHealth > 0) {
SetArmor(0); SetArmor(0);
@ -669,13 +713,13 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType
auto* inventoryComponent = owner->GetComponent<InventoryComponent>(); auto* inventoryComponent = owner->GetComponent<InventoryComponent>();
if (inventoryComponent != nullptr && isEnemy) { if (inventoryComponent != nullptr && isEnemy) {
inventoryComponent->TriggerPassiveAbility(PassiveAbilityTrigger::EnemySmashed); inventoryComponent->TriggerPassiveAbility(PassiveAbilityTrigger::EnemySmashed, m_Parent);
} }
auto* missions = owner->GetComponent<MissionComponent>(); auto* missions = owner->GetComponent<MissionComponent>();
if (missions != nullptr) { if (missions != nullptr) {
if (team != nullptr && isEnemy) { if (team != nullptr) {
for (const auto memberId : team->members) { for (const auto memberId : team->members) {
auto* member = EntityManager::Instance()->GetEntity(memberId); auto* member = EntityManager::Instance()->GetEntity(memberId);
@ -738,22 +782,17 @@ void DestroyableComponent::Smash(const LWOOBJID source, const eKillType killType
if (dZoneManager::Instance()->GetPlayerLoseCoinOnDeath()) { if (dZoneManager::Instance()->GetPlayerLoseCoinOnDeath()) {
auto* character = m_Parent->GetCharacter(); auto* character = m_Parent->GetCharacter();
uint64_t coinsTotal = character->GetCoins(); uint64_t coinsTotal = character->GetCoins();
const uint64_t minCoinsToLose = dZoneManager::Instance()->GetWorldConfig()->coinsLostOnDeathMin;
if (coinsTotal >= minCoinsToLose) {
const uint64_t maxCoinsToLose = dZoneManager::Instance()->GetWorldConfig()->coinsLostOnDeathMax;
const float coinPercentageToLose = dZoneManager::Instance()->GetWorldConfig()->coinsLostOnDeathPercent;
if (coinsTotal > 0) { uint64_t coinsToLose = std::max(static_cast<uint64_t>(coinsTotal * coinPercentageToLose), minCoinsToLose);
uint64_t coinsToLoose = 1; coinsToLose = std::min(maxCoinsToLose, coinsToLose);
if (coinsTotal >= 200) { coinsTotal -= coinsToLose;
float hundreth = (coinsTotal / 100.0f);
coinsToLoose = static_cast<int>(hundreth);
}
if (coinsToLoose > 10000) { LootGenerator::Instance().DropLoot(m_Parent, m_Parent, -1, coinsToLose, coinsToLose);
coinsToLoose = 10000;
}
coinsTotal -= coinsToLoose;
LootGenerator::Instance().DropLoot(m_Parent, m_Parent, -1, coinsToLoose, coinsToLoose);
character->SetCoins(coinsTotal, eLootSourceType::LOOT_SOURCE_PICKUP); character->SetCoins(coinsTotal, eLootSourceType::LOOT_SOURCE_PICKUP);
} }
} }
@ -783,12 +822,53 @@ void DestroyableComponent::SetFaction(int32_t factionID, bool ignoreChecks) {
AddFaction(factionID, ignoreChecks); AddFaction(factionID, ignoreChecks);
} }
void DestroyableComponent::PushImmunity(int32_t stacks) { void DestroyableComponent::SetStatusImmunity(
m_ImmuneStacks += stacks; const eStateChangeType state,
const bool bImmuneToBasicAttack,
const bool bImmuneToDamageOverTime,
const bool bImmuneToKnockback,
const bool bImmuneToInterrupt,
const bool bImmuneToSpeed,
const bool bImmuneToImaginationGain,
const bool bImmuneToImaginationLoss,
const bool bImmuneToQuickbuildInterrupt,
const bool bImmuneToPullToPoint) {
if (state == eStateChangeType::POP) {
if (bImmuneToBasicAttack && m_ImmuneToBasicAttackCount > 0) m_ImmuneToBasicAttackCount -= 1;
if (bImmuneToDamageOverTime && m_ImmuneToDamageOverTimeCount > 0) m_ImmuneToDamageOverTimeCount -= 1;
if (bImmuneToKnockback && m_ImmuneToKnockbackCount > 0) m_ImmuneToKnockbackCount -= 1;
if (bImmuneToInterrupt && m_ImmuneToInterruptCount > 0) m_ImmuneToInterruptCount -= 1;
if (bImmuneToSpeed && m_ImmuneToSpeedCount > 0) m_ImmuneToSpeedCount -= 1;
if (bImmuneToImaginationGain && m_ImmuneToImaginationGainCount > 0) m_ImmuneToImaginationGainCount -= 1;
if (bImmuneToImaginationLoss && m_ImmuneToImaginationLossCount > 0) m_ImmuneToImaginationLossCount -= 1;
if (bImmuneToQuickbuildInterrupt && m_ImmuneToQuickbuildInterruptCount > 0) m_ImmuneToQuickbuildInterruptCount -= 1;
if (bImmuneToPullToPoint && m_ImmuneToPullToPointCount > 0) m_ImmuneToPullToPointCount -= 1;
} else if (state == eStateChangeType::PUSH){
if (bImmuneToBasicAttack) m_ImmuneToBasicAttackCount += 1;
if (bImmuneToDamageOverTime) m_ImmuneToDamageOverTimeCount += 1;
if (bImmuneToKnockback) m_ImmuneToKnockbackCount += 1;
if (bImmuneToInterrupt) m_ImmuneToInterruptCount += 1;
if (bImmuneToSpeed) m_ImmuneToSpeedCount += 1;
if (bImmuneToImaginationGain) m_ImmuneToImaginationGainCount += 1;
if (bImmuneToImaginationLoss) m_ImmuneToImaginationLossCount += 1;
if (bImmuneToQuickbuildInterrupt) m_ImmuneToQuickbuildInterruptCount += 1;
if (bImmuneToPullToPoint) m_ImmuneToPullToPointCount += 1;
} }
void DestroyableComponent::PopImmunity(int32_t stacks) { GameMessages::SendSetStatusImmunity(
m_ImmuneStacks -= stacks; m_Parent->GetObjectID(), state, m_Parent->GetSystemAddress(),
bImmuneToBasicAttack,
bImmuneToDamageOverTime,
bImmuneToKnockback,
bImmuneToInterrupt,
bImmuneToSpeed,
bImmuneToImaginationGain,
bImmuneToImaginationLoss,
bImmuneToQuickbuildInterrupt,
bImmuneToPullToPoint
);
} }
void DestroyableComponent::FixStats() { void DestroyableComponent::FixStats() {

View File

@ -7,6 +7,10 @@
#include "Entity.h" #include "Entity.h"
#include "Component.h" #include "Component.h"
namespace CppScripts {
class Script;
}; //! namespace CppScripts
/** /**
* Represents the stats of an entity, for example its health, imagination and armor. Also handles factions, which * Represents the stats of an entity, for example its health, imagination and armor. Also handles factions, which
* indicate which enemies this entity has. * indicate which enemies this entity has.
@ -392,16 +396,31 @@ public:
void Smash(LWOOBJID source, eKillType killType = eKillType::VIOLENT, const std::u16string& deathType = u"", uint32_t skillID = 0); void Smash(LWOOBJID source, eKillType killType = eKillType::VIOLENT, const std::u16string& deathType = u"", uint32_t skillID = 0);
/** /**
* Pushes a layer of immunity to this entity, making it immune for longer * Push or Pop a layer of status immunity to this entity
* @param stacks the amount of immunity to add
*/ */
void PushImmunity(int32_t stacks = 1); void SetStatusImmunity(
const eStateChangeType state,
const bool bImmuneToBasicAttack = false,
const bool bImmuneToDamageOverTime = false,
const bool bImmuneToKnockback = false,
const bool bImmuneToInterrupt = false,
const bool bImmuneToSpeed = false,
const bool bImmuneToImaginationGain = false,
const bool bImmuneToImaginationLoss = false,
const bool bImmuneToQuickbuildInterrupt = false,
const bool bImmuneToPullToPoint = false
);
/** // Getters for status immunities
* Pops layers of immunity, making it immune for less longer const bool GetImmuneToBasicAttack() {return m_ImmuneToBasicAttackCount > 0;};
* @param stacks the number of layers of immunity to remove const bool GetImmuneToDamageOverTime() {return m_ImmuneToDamageOverTimeCount > 0;};
*/ const bool GetImmuneToKnockback() {return m_ImmuneToKnockbackCount > 0;};
void PopImmunity(int32_t stacks = 1); const bool GetImmuneToInterrupt() {return m_ImmuneToInterruptCount > 0;};
const bool GetImmuneToSpeed() {return m_ImmuneToSpeedCount > 0;};
const bool GetImmuneToImaginationGain() {return m_ImmuneToImaginationGainCount > 0;};
const bool GetImmuneToImaginationLoss() {return m_ImmuneToImaginationLossCount > 0;};
const bool GetImmuneToQuickbuildInterrupt() {return m_ImmuneToQuickbuildInterruptCount > 0;};
const bool GetImmuneToPullToPoint() {return m_ImmuneToPullToPointCount > 0;};
/** /**
* Utility to reset all stats to the default stats based on items and completed missions * Utility to reset all stats to the default stats based on items and completed missions
@ -422,6 +441,17 @@ public:
*/ */
void AddFactionNoLookup(int32_t faction) { m_FactionIDs.push_back(faction); }; void AddFactionNoLookup(int32_t faction) { m_FactionIDs.push_back(faction); };
/**
* Notify subscribed scripts of Damage actions.
*
* @param attacker The attacking Entity
* @param damage The amount of damage that was done
*/
void NotifySubscribers(Entity* attacker, uint32_t damage);
void Subscribe(LWOOBJID scriptObjId, CppScripts::Script* scriptToAdd);
void Unsubscribe(LWOOBJID scriptObjId);
private: private:
/** /**
* Whether or not the health should be serialized * Whether or not the health should be serialized
@ -478,11 +508,6 @@ private:
*/ */
uint32_t m_AttacksToBlock; uint32_t m_AttacksToBlock;
/**
* The layers of immunity this entity has left
*/
int32_t m_ImmuneStacks;
/** /**
* The amount of damage that should be reduced from every attack * The amount of damage that should be reduced from every attack
*/ */
@ -557,6 +582,24 @@ private:
* The list of callbacks that will be called when this entity gets hit * The list of callbacks that will be called when this entity gets hit
*/ */
std::vector<std::function<void(Entity*)>> m_OnHitCallbacks; std::vector<std::function<void(Entity*)>> m_OnHitCallbacks;
/**
* The list of scripts subscribed to this components actions
*/
std::map<LWOOBJID, CppScripts::Script*> m_SubscribedScripts;
/**
* status immunity counters
*/
uint32_t m_ImmuneToBasicAttackCount;
uint32_t m_ImmuneToDamageOverTimeCount;
uint32_t m_ImmuneToKnockbackCount;
uint32_t m_ImmuneToInterruptCount;
uint32_t m_ImmuneToSpeedCount;
uint32_t m_ImmuneToImaginationGainCount;
uint32_t m_ImmuneToImaginationLossCount;
uint32_t m_ImmuneToQuickbuildInterruptCount;
uint32_t m_ImmuneToPullToPointCount;
}; };
#endif // DESTROYABLECOMPONENT_H #endif // DESTROYABLECOMPONENT_H

View File

@ -27,6 +27,7 @@
#include "dConfig.h" #include "dConfig.h"
#include "eItemType.h" #include "eItemType.h"
#include "eUnequippableActiveType.h" #include "eUnequippableActiveType.h"
#include "CppScripts.h"
InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document): Component(parent) { InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* document): Component(parent) {
this->m_Dirty = true; this->m_Dirty = true;
@ -867,6 +868,8 @@ void InventoryComponent::EquipItem(Item* item, const bool skipChecks) {
AddItemSkills(item->GetLot()); AddItemSkills(item->GetLot());
EquipScripts(item);
EntityManager::Instance()->SerializeEntity(m_Parent); EntityManager::Instance()->SerializeEntity(m_Parent);
} }
@ -895,6 +898,8 @@ void InventoryComponent::UnEquipItem(Item* item) {
PurgeProxies(item); PurgeProxies(item);
UnequipScripts(item);
EntityManager::Instance()->SerializeEntity(m_Parent); EntityManager::Instance()->SerializeEntity(m_Parent);
// Trigger property event // Trigger property event
@ -904,6 +909,37 @@ void InventoryComponent::UnEquipItem(Item* item) {
} }
} }
void InventoryComponent::EquipScripts(Item* equippedItem) {
CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry");
if (!compRegistryTable) return;
int32_t scriptComponentID = compRegistryTable->GetByIDAndType(equippedItem->GetLot(), COMPONENT_TYPE_SCRIPT, -1);
if (scriptComponentID > -1) {
CDScriptComponentTable* scriptCompTable = CDClientManager::Instance()->GetTable<CDScriptComponentTable>("ScriptComponent");
CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID);
auto* itemScript = CppScripts::GetScript(m_Parent, scriptCompData.script_name);
if (!itemScript) {
Game::logger->Log("InventoryComponent", "null script?");
}
itemScript->OnFactionTriggerItemEquipped(m_Parent, equippedItem->GetId());
}
}
void InventoryComponent::UnequipScripts(Item* unequippedItem) {
CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance()->GetTable<CDComponentsRegistryTable>("ComponentsRegistry");
if (!compRegistryTable) return;
int32_t scriptComponentID = compRegistryTable->GetByIDAndType(unequippedItem->GetLot(), COMPONENT_TYPE_SCRIPT, -1);
if (scriptComponentID > -1) {
CDScriptComponentTable* scriptCompTable = CDClientManager::Instance()->GetTable<CDScriptComponentTable>("ScriptComponent");
CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID);
auto* itemScript = CppScripts::GetScript(m_Parent, scriptCompData.script_name);
if (!itemScript) {
Game::logger->Log("InventoryComponent", "null script?");
}
itemScript->OnFactionTriggerItemUnequipped(m_Parent, unequippedItem->GetId());
}
}
void InventoryComponent::HandlePossession(Item* item) { void InventoryComponent::HandlePossession(Item* item) {
auto* characterComponent = m_Parent->GetComponent<CharacterComponent>(); auto* characterComponent = m_Parent->GetComponent<CharacterComponent>();
if (!characterComponent) return; if (!characterComponent) return;
@ -923,7 +959,7 @@ void InventoryComponent::HandlePossession(Item* item) {
return; return;
} }
GameMessages::SendSetStunned(m_Parent->GetObjectID(), eStunState::PUSH, m_Parent->GetSystemAddress(), LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); GameMessages::SendSetStunned(m_Parent->GetObjectID(), eStateChangeType::PUSH, m_Parent->GetSystemAddress(), LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true);
// Set the mount Item ID so that we know what were handling // Set the mount Item ID so that we know what were handling
possessorComponent->SetMountItemID(item->GetId()); possessorComponent->SetMountItemID(item->GetId());
@ -1160,9 +1196,9 @@ void InventoryComponent::RemoveItemSkills(const LOT lot) {
} }
} }
void InventoryComponent::TriggerPassiveAbility(PassiveAbilityTrigger trigger) { void InventoryComponent::TriggerPassiveAbility(PassiveAbilityTrigger trigger, Entity* target) {
for (auto* set : m_Itemsets) { for (auto* set : m_Itemsets) {
set->TriggerPassiveAbility(trigger); set->TriggerPassiveAbility(trigger, target);
} }
} }

View File

@ -19,6 +19,7 @@
#include "ItemSetPassiveAbility.h" #include "ItemSetPassiveAbility.h"
#include "ItemSetPassiveAbilityID.h" #include "ItemSetPassiveAbilityID.h"
#include "PossessorComponent.h" #include "PossessorComponent.h"
#include "eInventoryType.h"
class Entity; class Entity;
class ItemSet; class ItemSet;
@ -282,7 +283,7 @@ public:
* Triggers one of the passive abilities from the equipped item set * Triggers one of the passive abilities from the equipped item set
* @param trigger the trigger to fire * @param trigger the trigger to fire
*/ */
void TriggerPassiveAbility(PassiveAbilityTrigger trigger); void TriggerPassiveAbility(PassiveAbilityTrigger trigger, Entity* target = nullptr);
/** /**
* Returns if the entity has any of the passed passive abilities equipped * Returns if the entity has any of the passed passive abilities equipped
@ -351,6 +352,20 @@ public:
*/ */
static uint32_t FindSkill(LOT lot); static uint32_t FindSkill(LOT lot);
/**
* Call this when you equip an item. This calls OnFactionTriggerItemEquipped for any scripts found on the items.
*
* @param equippedItem The item script to lookup and call equip on
*/
void EquipScripts(Item* equippedItem);
/**
* Call this when you unequip an item. This calls OnFactionTriggerItemUnequipped for any scripts found on the items.
*
* @param unequippedItem The item script to lookup and call unequip on
*/
void UnequipScripts(Item* unequippedItem);
~InventoryComponent() override; ~InventoryComponent() override;
private: private:

View File

@ -7,6 +7,8 @@
LevelProgressionComponent::LevelProgressionComponent(Entity* parent) : Component(parent) { LevelProgressionComponent::LevelProgressionComponent(Entity* parent) : Component(parent) {
m_Parent = parent; m_Parent = parent;
m_Level = 1; m_Level = 1;
m_SpeedBase = 500.0f;
m_CharacterVersion = eCharacterVersion::LIVE;
} }
void LevelProgressionComponent::UpdateXml(tinyxml2::XMLDocument* doc) { void LevelProgressionComponent::UpdateXml(tinyxml2::XMLDocument* doc) {
@ -16,7 +18,8 @@ void LevelProgressionComponent::UpdateXml(tinyxml2::XMLDocument* doc) {
return; return;
} }
level->SetAttribute("l", m_Level); level->SetAttribute("l", m_Level);
level->SetAttribute("sb", m_SpeedBase);
level->SetAttribute("cv", static_cast<uint32_t>(m_CharacterVersion));
} }
void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc) { void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc) {
@ -26,7 +29,10 @@ void LevelProgressionComponent::LoadFromXml(tinyxml2::XMLDocument* doc) {
return; return;
} }
level->QueryAttribute("l", &m_Level); level->QueryAttribute("l", &m_Level);
level->QueryAttribute("sb", &m_SpeedBase);
uint32_t characterVersion;
level->QueryAttribute("cv", &characterVersion);
m_CharacterVersion = static_cast<eCharacterVersion>(characterVersion);
} }
void LevelProgressionComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { void LevelProgressionComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) {
@ -60,7 +66,8 @@ void LevelProgressionComponent::HandleLevelUp() {
} }
break; break;
case 9: case 9:
controllablePhysicsComponent->SetSpeedMultiplier(static_cast<float>(reward->value) / 500.0f); SetSpeedBase(static_cast<float>(reward->value) );
controllablePhysicsComponent->SetSpeedMultiplier(GetSpeedBase() / 500.0f);
break; break;
case 11: case 11:
case 12: case 12:
@ -72,3 +79,9 @@ void LevelProgressionComponent::HandleLevelUp() {
// Tell the client we have finished sending level rewards. // Tell the client we have finished sending level rewards.
if (rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, !rewardingItem); if (rewardingItem) GameMessages::NotifyLevelRewards(m_Parent->GetObjectID(), m_Parent->GetSystemAddress(), m_Level, !rewardingItem);
} }
void LevelProgressionComponent::SetRetroactiveBaseSpeed(){
if (m_Level >= 20) m_SpeedBase = 525.0f;
auto* controllablePhysicsComponent = m_Parent->GetComponent<ControllablePhysicsComponent>();
if (controllablePhysicsComponent) controllablePhysicsComponent->SetSpeedMultiplier(m_SpeedBase / 500.0f);
}

View File

@ -3,11 +3,13 @@
#include "Entity.h" #include "Entity.h"
#include "GameMessages.h" #include "GameMessages.h"
#include "Component.h" #include "Component.h"
#include "eCharacterVersion.h"
/** /**
* Component that handles level progression and serilization. * Component that handles level progression and serilization.
* *
*/ */
class LevelProgressionComponent : public Component { class LevelProgressionComponent : public Component {
public: public:
static const uint32_t ComponentType = eReplicaComponentType::COMPONENT_TYPE_LEVEL_PROGRESSION; static const uint32_t ComponentType = eReplicaComponentType::COMPONENT_TYPE_LEVEL_PROGRESSION;
@ -44,11 +46,40 @@ public:
*/ */
void SetLevel(uint32_t level) { m_Level = level; m_DirtyLevelInfo = true; } void SetLevel(uint32_t level) { m_Level = level; m_DirtyLevelInfo = true; }
/**
* Gets the current Speed Base of the entity
* @return the current Speed Base of the entity
*/
const uint32_t GetSpeedBase() const { return m_SpeedBase; }
/**
* Sets the Speed Base of the entity
* @param SpeedBase the Speed Base to set
*/
void SetSpeedBase(uint32_t SpeedBase) { m_SpeedBase = SpeedBase; }
/** /**
* Gives the player rewards for the last level that they leveled up from * Gives the player rewards for the last level that they leveled up from
*/ */
void HandleLevelUp(); void HandleLevelUp();
/**
* Gets the current Character Version of the entity
* @return the current Character Version of the entity
*/
const eCharacterVersion GetCharacterVersion() const { return m_CharacterVersion; }
/**
* Sets the Character Version of the entity
* @param CharacterVersion the Character Version to set
*/
void SetCharacterVersion(eCharacterVersion CharacterVersion) { m_CharacterVersion = CharacterVersion; }
/**
* Set the Base Speed retroactively of the entity
*/
void SetRetroactiveBaseSpeed();
private: private:
/** /**
* whether the level is dirty * whether the level is dirty
@ -59,4 +90,15 @@ private:
* Level of the entity * Level of the entity
*/ */
uint32_t m_Level; uint32_t m_Level;
/**
* The base speed of the entity
*/
float m_SpeedBase;
/**
* The Character format version
*/
eCharacterVersion m_CharacterVersion;
}; };

View File

@ -10,6 +10,7 @@
#include "EntityManager.h" #include "EntityManager.h"
#include "SimplePhysicsComponent.h" #include "SimplePhysicsComponent.h"
#include "dZoneManager.h" #include "dZoneManager.h"
#include "CDClientManager.h"
std::map<LOT, float> MovementAIComponent::m_PhysicsSpeedCache = {}; std::map<LOT, float> MovementAIComponent::m_PhysicsSpeedCache = {};

View File

@ -12,11 +12,12 @@
#include "GameMessages.h" #include "GameMessages.h"
#include "CppScripts.h" #include "CppScripts.h"
#include "SimplePhysicsComponent.h" #include "SimplePhysicsComponent.h"
#include "Zone.h"
MoverSubComponent::MoverSubComponent(const NiPoint3& startPos) { MoverSubComponent::MoverSubComponent(const NiPoint3& startPos) {
mPosition = {}; mPosition = {};
mState = MovementPlatformState::Stopped; mState = eMovementPlatformState::Stopped;
mDesiredWaypointIndex = 0; // -1; mDesiredWaypointIndex = 0; // -1;
mInReverse = false; mInReverse = false;
mShouldStopAtDesiredWaypoint = false; mShouldStopAtDesiredWaypoint = false;
@ -127,7 +128,7 @@ void MovingPlatformComponent::OnCompleteRebuild() {
StartPathing(); StartPathing();
} }
void MovingPlatformComponent::SetMovementState(MovementPlatformState value) { void MovingPlatformComponent::SetMovementState(eMovementPlatformState value) {
auto* subComponent = static_cast<MoverSubComponent*>(m_MoverSubComponent); auto* subComponent = static_cast<MoverSubComponent*>(m_MoverSubComponent);
subComponent->mState = value; subComponent->mState = value;
@ -152,7 +153,7 @@ void MovingPlatformComponent::StartPathing() {
auto* subComponent = static_cast<MoverSubComponent*>(m_MoverSubComponent); auto* subComponent = static_cast<MoverSubComponent*>(m_MoverSubComponent);
subComponent->mShouldStopAtDesiredWaypoint = true; subComponent->mShouldStopAtDesiredWaypoint = true;
subComponent->mState = MovementPlatformState::Stationary; subComponent->mState = eMovementPlatformState::Stationary;
NiPoint3 targetPosition; NiPoint3 targetPosition;
@ -174,7 +175,7 @@ void MovingPlatformComponent::StartPathing() {
} }
m_Parent->AddCallbackTimer(subComponent->mWaitTime, [this] { m_Parent->AddCallbackTimer(subComponent->mWaitTime, [this] {
SetMovementState(MovementPlatformState::Moving); SetMovementState(eMovementPlatformState::Moving);
}); });
const auto travelTime = Vector3::Distance(targetPosition, subComponent->mPosition) / subComponent->mSpeed + 1.5f; const auto travelTime = Vector3::Distance(targetPosition, subComponent->mPosition) / subComponent->mSpeed + 1.5f;
@ -199,7 +200,7 @@ void MovingPlatformComponent::StartPathing() {
void MovingPlatformComponent::ContinuePathing() { void MovingPlatformComponent::ContinuePathing() {
auto* subComponent = static_cast<MoverSubComponent*>(m_MoverSubComponent); auto* subComponent = static_cast<MoverSubComponent*>(m_MoverSubComponent);
subComponent->mState = MovementPlatformState::Stationary; subComponent->mState = eMovementPlatformState::Stationary;
subComponent->mCurrentWaypointIndex = subComponent->mNextWaypointIndex; subComponent->mCurrentWaypointIndex = subComponent->mNextWaypointIndex;
@ -282,7 +283,7 @@ void MovingPlatformComponent::ContinuePathing() {
m_Parent->CancelCallbackTimers(); m_Parent->CancelCallbackTimers();
m_Parent->AddCallbackTimer(subComponent->mWaitTime, [this] { m_Parent->AddCallbackTimer(subComponent->mWaitTime, [this] {
SetMovementState(MovementPlatformState::Moving); SetMovementState(eMovementPlatformState::Moving);
}); });
auto travelTime = Vector3::Distance(targetPosition, subComponent->mPosition) / subComponent->mSpeed + 1.5; auto travelTime = Vector3::Distance(targetPosition, subComponent->mPosition) / subComponent->mSpeed + 1.5;
@ -313,7 +314,7 @@ void MovingPlatformComponent::StopPathing() {
m_PathingStopped = true; m_PathingStopped = true;
subComponent->mState = MovementPlatformState::Stopped; subComponent->mState = eMovementPlatformState::Stopped;
subComponent->mDesiredWaypointIndex = -1; subComponent->mDesiredWaypointIndex = -1;
subComponent->mShouldStopAtDesiredWaypoint = false; subComponent->mShouldStopAtDesiredWaypoint = false;

View File

@ -13,6 +13,9 @@
#include "dCommonVars.h" #include "dCommonVars.h"
#include "EntityManager.h" #include "EntityManager.h"
#include "Component.h" #include "Component.h"
#include "eMovementPlatformState.h"
class Path;
/** /**
* Different types of available platforms * Different types of available platforms
@ -26,16 +29,6 @@ enum class eMoverSubComponentType : uint32_t {
simpleMover = 5, simpleMover = 5,
}; };
/**
* The different types of platform movement state, supposedly a bitmap
*/
enum class MovementPlatformState : uint32_t
{
Moving = 0b00010,
Stationary = 0b11001,
Stopped = 0b01100
};
/** /**
* Sub component for moving platforms that determine the actual current movement state * Sub component for moving platforms that determine the actual current movement state
*/ */
@ -49,7 +42,7 @@ public:
/** /**
* The state the platform is currently in * The state the platform is currently in
*/ */
MovementPlatformState mState = MovementPlatformState::Stationary; eMovementPlatformState mState = eMovementPlatformState::Stationary;
/** /**
* The waypoint this platform currently wants to traverse to * The waypoint this platform currently wants to traverse to
@ -133,7 +126,7 @@ public:
* Updates the movement state for the moving platform * Updates the movement state for the moving platform
* @param value the movement state to set * @param value the movement state to set
*/ */
void SetMovementState(MovementPlatformState value); void SetMovementState(eMovementPlatformState value);
/** /**
* Instructs the moving platform to go to some waypoint * Instructs the moving platform to go to some waypoint

View File

@ -20,6 +20,7 @@
#include "dConfig.h" #include "dConfig.h"
#include "dChatFilter.h" #include "dChatFilter.h"
#include "Database.h" #include "Database.h"
#include "EntityInfo.h"
std::unordered_map<LOT, PetComponent::PetPuzzleData> PetComponent::buildCache{}; std::unordered_map<LOT, PetComponent::PetPuzzleData> PetComponent::buildCache{};
std::unordered_map<LWOOBJID, LWOOBJID> PetComponent::currentActivities{}; std::unordered_map<LWOOBJID, LWOOBJID> PetComponent::currentActivities{};
@ -118,6 +119,7 @@ void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpd
outBitStream->Write(m_Owner); outBitStream->Write(m_Owner);
} }
if (bIsInitialUpdate) {
outBitStream->Write(tamed); outBitStream->Write(tamed);
if (tamed) { if (tamed) {
outBitStream->Write(m_ModerationStatus); outBitStream->Write(m_ModerationStatus);
@ -136,6 +138,7 @@ void PetComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpd
} }
} }
} }
}
void PetComponent::OnUse(Entity* originator) { void PetComponent::OnUse(Entity* originator) {
if (m_Owner != LWOOBJID_EMPTY) { if (m_Owner != LWOOBJID_EMPTY) {

View File

@ -19,6 +19,7 @@
#include "CDComponentsRegistryTable.h" #include "CDComponentsRegistryTable.h"
#include "CDPhysicsComponentTable.h" #include "CDPhysicsComponentTable.h"
#include "dServer.h" #include "dServer.h"
#include "EntityInfo.h"
#include "dpWorld.h" #include "dpWorld.h"
#include "dpEntity.h" #include "dpEntity.h"

View File

@ -7,8 +7,8 @@ PlayerForcedMovementComponent::PlayerForcedMovementComponent(Entity* parent) : C
PlayerForcedMovementComponent::~PlayerForcedMovementComponent() {} PlayerForcedMovementComponent::~PlayerForcedMovementComponent() {}
void PlayerForcedMovementComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) { void PlayerForcedMovementComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsInitialUpdate, unsigned int& flags) {
outBitStream->Write(m_DirtyInfo); outBitStream->Write(m_DirtyInfo || bIsInitialUpdate);
if (m_DirtyInfo) { if (m_DirtyInfo || bIsInitialUpdate) {
outBitStream->Write(m_PlayerOnRail); outBitStream->Write(m_PlayerOnRail);
outBitStream->Write(m_ShowBillboard); outBitStream->Write(m_ShowBillboard);
} }

View File

@ -34,8 +34,8 @@ void PossessableComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIn
outBitStream->Write(m_Possessor != LWOOBJID_EMPTY); outBitStream->Write(m_Possessor != LWOOBJID_EMPTY);
if (m_Possessor != LWOOBJID_EMPTY) outBitStream->Write(m_Possessor); if (m_Possessor != LWOOBJID_EMPTY) outBitStream->Write(m_Possessor);
outBitStream->Write(m_AnimationFlag != eAnimationFlags::IDLE_INVALID); outBitStream->Write(m_AnimationFlag != eAnimationFlags::IDLE_NONE);
if (m_AnimationFlag != eAnimationFlags::IDLE_INVALID) outBitStream->Write(m_AnimationFlag); if (m_AnimationFlag != eAnimationFlags::IDLE_NONE) outBitStream->Write(m_AnimationFlag);
outBitStream->Write(m_ImmediatelyDepossess); outBitStream->Write(m_ImmediatelyDepossess);
m_ImmediatelyDepossess = false; // reset flag m_ImmediatelyDepossess = false; // reset flag

View File

@ -109,7 +109,7 @@ private:
* @brief What animaiton flag to use * @brief What animaiton flag to use
* *
*/ */
eAnimationFlags m_AnimationFlag = eAnimationFlags::IDLE_INVALID; eAnimationFlags m_AnimationFlag = eAnimationFlags::IDLE_NONE;
/** /**
* @brief Should this be immediately depossessed * @brief Should this be immediately depossessed

View File

@ -54,7 +54,7 @@ void PossessorComponent::Mount(Entity* mount) {
// GM's to send // GM's to send
GameMessages::SendSetJetPackMode(m_Parent, false); GameMessages::SendSetJetPackMode(m_Parent, false);
GameMessages::SendVehicleUnlockInput(mount->GetObjectID(), false, m_Parent->GetSystemAddress()); GameMessages::SendVehicleUnlockInput(mount->GetObjectID(), false, m_Parent->GetSystemAddress());
GameMessages::SendSetStunned(m_Parent->GetObjectID(), eStunState::PUSH, m_Parent->GetSystemAddress(), LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true); GameMessages::SendSetStunned(m_Parent->GetObjectID(), eStateChangeType::PUSH, m_Parent->GetSystemAddress(), LWOOBJID_EMPTY, true, false, true, false, false, false, false, true, true, true, true, true, true, true, true, true);
EntityManager::Instance()->SerializeEntity(m_Parent); EntityManager::Instance()->SerializeEntity(m_Parent);
EntityManager::Instance()->SerializeEntity(mount); EntityManager::Instance()->SerializeEntity(mount);

View File

@ -11,6 +11,7 @@
#include "CharacterComponent.h" #include "CharacterComponent.h"
#include "UserManager.h" #include "UserManager.h"
#include "dLogger.h" #include "dLogger.h"
#include "AMFFormat.h"
PropertyEntranceComponent::PropertyEntranceComponent(uint32_t componentID, Entity* parent) : Component(parent) { PropertyEntranceComponent::PropertyEntranceComponent(uint32_t componentID, Entity* parent) : Component(parent) {
this->propertyQueries = {}; this->propertyQueries = {};

View File

@ -17,6 +17,7 @@
#include "Player.h" #include "Player.h"
#include "RocketLaunchpadControlComponent.h" #include "RocketLaunchpadControlComponent.h"
#include "PropertyEntranceComponent.h" #include "PropertyEntranceComponent.h"
#include "InventoryComponent.h"
#include <vector> #include <vector>
#include "CppScripts.h" #include "CppScripts.h"
@ -717,7 +718,7 @@ void PropertyManagementComponent::Save() {
insertion->setDouble(9, rotation.y); insertion->setDouble(9, rotation.y);
insertion->setDouble(10, rotation.z); insertion->setDouble(10, rotation.z);
insertion->setDouble(11, rotation.w); insertion->setDouble(11, rotation.w);
insertion->setString(12, "Objects_" + std::to_string(entity->GetLOT()) + "_name"); // Model name. TODO make this customizable insertion->setString(12, ("Objects_" + std::to_string(entity->GetLOT()) + "_name").c_str()); // Model name. TODO make this customizable
insertion->setString(13, ""); // Model description. TODO implement this. insertion->setString(13, ""); // Model description. TODO implement this.
insertion->setDouble(14, 0); // behavior 1. TODO implement this. insertion->setDouble(14, 0); // behavior 1. TODO implement this.
insertion->setDouble(15, 0); // behavior 2. TODO implement this. insertion->setDouble(15, 0); // behavior 2. TODO implement this.

View File

@ -21,6 +21,7 @@
#include "dServer.h" #include "dServer.h"
#include "dZoneManager.h" #include "dZoneManager.h"
#include "dConfig.h" #include "dConfig.h"
#include "Loot.h"
#ifndef M_PI #ifndef M_PI
#define M_PI 3.14159265358979323846264338327950288 #define M_PI 3.14159265358979323846264338327950288
@ -98,7 +99,7 @@ void RacingControlComponent::OnPlayerLoaded(Entity* player) {
} }
void RacingControlComponent::LoadPlayerVehicle(Entity* player, void RacingControlComponent::LoadPlayerVehicle(Entity* player,
bool initialLoad) { uint32_t positionNumber, bool initialLoad) {
// Load the player's vehicle. // Load the player's vehicle.
if (player == nullptr) { if (player == nullptr) {
@ -126,33 +127,18 @@ void RacingControlComponent::LoadPlayerVehicle(Entity* player,
auto* path = dZoneManager::Instance()->GetZone()->GetPath( auto* path = dZoneManager::Instance()->GetZone()->GetPath(
GeneralUtils::UTF16ToWTF8(m_PathName)); GeneralUtils::UTF16ToWTF8(m_PathName));
auto startPosition = path->pathWaypoints[0].position + NiPoint3::UNIT_Y * 3; auto spawnPointEntities = EntityManager::Instance()->GetEntitiesByLOT(4843);
auto startPosition = NiPoint3::ZERO;
const auto spacing = 15; auto startRotation = NiQuaternion::IDENTITY;
const std::string placementAsString = std::to_string(positionNumber);
// This sometimes spawns the vehicle out of the map if there are lots of for (auto entity : spawnPointEntities) {
// players loaded. if (!entity) continue;
if (entity->GetVarAsString(u"placement") == placementAsString) {
const auto range = m_LoadedPlayers * spacing; startPosition = entity->GetPosition();
startRotation = entity->GetRotation();
startPosition = break;
startPosition + NiPoint3::UNIT_Z * ((m_LeadingPlayer / 2) + }
m_RacingPlayers.size() * spacing); }
auto startRotation =
NiQuaternion::LookAt(startPosition, startPosition + NiPoint3::UNIT_X);
auto angles = startRotation.GetEulerAngles();
angles.y -= M_PI;
startRotation = NiQuaternion::FromEulerAngles(angles);
Game::logger->Log("RacingControlComponent",
"Start position <%f, %f, %f>, <%f, %f, %f>",
startPosition.x, startPosition.y, startPosition.z,
angles.x * (180.0f / M_PI), angles.y * (180.0f / M_PI),
angles.z * (180.0f / M_PI));
// Make sure the player is at the correct position. // Make sure the player is at the correct position.
@ -567,12 +553,12 @@ void RacingControlComponent::Update(float deltaTime) {
Game::logger->Log("RacingControlComponent", Game::logger->Log("RacingControlComponent",
"Loading all players..."); "Loading all players...");
for (size_t i = 0; i < m_LobbyPlayers.size(); i++) { for (size_t positionNumber = 0; positionNumber < m_LobbyPlayers.size(); positionNumber++) {
Game::logger->Log("RacingControlComponent", Game::logger->Log("RacingControlComponent",
"Loading player now!"); "Loading player now!");
auto* player = auto* player =
EntityManager::Instance()->GetEntity(m_LobbyPlayers[i]); EntityManager::Instance()->GetEntity(m_LobbyPlayers[positionNumber]);
if (player == nullptr) { if (player == nullptr) {
return; return;
@ -581,7 +567,7 @@ void RacingControlComponent::Update(float deltaTime) {
Game::logger->Log("RacingControlComponent", Game::logger->Log("RacingControlComponent",
"Loading player now NOW!"); "Loading player now NOW!");
LoadPlayerVehicle(player, true); LoadPlayerVehicle(player, positionNumber + 1, true);
m_Loaded = true; m_Loaded = true;
} }

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