1 Commits

Author SHA1 Message Date
NotAlwaysTrue bac426f509 Added A DebugTestMod to test if the chage was working
Make Penetration work when explosions dealing damage on characters
Removed hard-coded StructureDamage limit
2026-03-08 05:03:06 +08:00
291 changed files with 987 additions and 31281 deletions
+2 -37
View File
@@ -1,41 +1,6 @@
root = true
[*.cs]
[*]
charset = utf-8
insert_final_newline = true
[*.{sln,cs}]
# VS defaults to utf-8 with BOM -- let's not create more merge conflicts
# XXX: csproj files dont't have a BOM for some reason?
charset = utf-8-bom
[*.cs]
indent_style = space
indent_size = 4
csharp_prefer_braces = when_multiline:warning
csharp_indent_case_contents_when_block = false
# CS1591: Missing XML comment for publicly visible type or member
dotnet_diagnostic.CS1591.severity = none
# IDE0090: Use 'new(...)'
csharp_style_implicit_object_creation_when_type_is_apparent = false
dotnet_diagnostic.CA1806.severity = silent
[*.{html,xml,csproj}]
indent_style = space
indent_size = 2
[*.{sh,ps1}]
indent_style = space
indent_size = 2
[*.py]
indent_style = space
indent_size = 4
[*.{js,json}]
indent_style = space
indent_size = 2
[*.lua]
indent_style = space
indent_size = 2
+5 -101
View File
@@ -1,101 +1,5 @@
name: Bug Report
description: Found a bug? Help us squash it by making a bug report!
body:
- type: markdown
attributes:
value: |
Thanks for taking the time to report a bug! Actionable reports are very important in identifying and fixing bugs, so please fill out all the fields carefully and provide as much information as you can while being concise. Please also note that we get lots of reports and may not always write back to each individually that does not mean we have not read it.
- type: checkboxes
id: checks
attributes:
label: "Disclaimers"
options:
- label: "I have searched the issue tracker to check if the issue has already been reported."
required: true
- label: "My issue happened while using mods."
required: false
- type: textarea
id: what-happened
attributes:
label: What happened?
description: Please tell us also what you expected should have happened if the game was behaving correctly.
placeholder: "Using the bike horn crashes the game."
validations:
required: true
- type: textarea
id: repro
attributes:
label: Reproduction steps
description: |
If possible, describe how the developers can get the bug to happen (or, in other words, what actions lead to you encountering the bug). **This is by far the most important part of the report** - it is often extremely difficult, or even impossible, to diagnose an issue if we don't know the conditions it occurs in.
If you have a save, a submarine file, screenshots or any other files that might help us diagnose the issue, you can attach them here. Note that GitHub doesn't support the .save or .sub file extensions, so you should .zip those types of files to allow them to be attached.
placeholder: |
1. Start a multiplayer campaign
2. Spawn a bike horn with console commands
3. Use the bike horn
4. Observe how the game crashes
validations:
required: true
- type: dropdown
id: prevalence
attributes:
label: Bug prevalence
description: "How often do you or others encounter this bug?"
options:
- Just once
- Happens every now and then
- Happens regularly
- Happens every time I play
validations:
required: true
- type: dropdown
id: mporsp
attributes:
label: Single player or multiplayer?
description: Did the issue happen in single player, multiplayer, or both? How was the server being hosted?
options:
- Single player
- Multiplayer hosted from the in-game menu (= using a listen server)
- Multiplayer hosted using a dedicated server
- Happens in both single player and multiplayer
- Happens outside single player or multiplayer game modes (e.g. game launches on startup, something broken in the main menu)
- Other
validations:
required: true
- type: input
id: othermporsp
attributes:
label: "-"
description: If you selected "Other" in the above dropdown, please clarify here.
- type: dropdown
id: version
attributes:
label: Version
description: Which version of the game did the bug happen in? You can see the current version number in the bottom left corner of your screen in the main menu.
options:
- Latest Stable
- Unstable
- Other
validations:
required: true
- type: input
id: otherversion
attributes:
label: "-"
description: If you selected "Other" in the above dropdown because you are e.g. using a custom build, please tell us more about it here.
- type: dropdown
id: operating-systems
attributes:
label: Which operating system did you encounter this bug on?
options:
- Windows
- MacOS
- Linux
validations:
required: true
- type: textarea
id: errors
attributes:
label: Relevant error messages and crash reports
description: If the game produces any text relevant to your issue, please include those in full. You can copy error messages from the in-game console by right clicking the error and selecting "copy". Crash reports will be named crashreport.log or servercrashreport.log and they're automatically generated into the root of the game's installation folder on your computer. You can usually find the game files location through Steam (Right click Barotrauma in your Steam Library -> Properties -> Local files -> Browse local files).
render: shell
blank_issues_enabled: false
contact_links:
- name: Bug reports
url: https://github.com/FakeFishGames/Barotrauma/discussions/categories/bug-reports
about: Please post your bug reports in the Discussions section.
-9
View File
@@ -1,9 +0,0 @@
# yaml-language-server: $schema=https://json.schemastore.org/dependabot-2.0.json
version: 2
updates:
- package-ecosystem: github-actions
target-branch: develop
directory: /
schedule:
interval: daily
-51
View File
@@ -1,51 +0,0 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: Build
on:
workflow_dispatch:
workflow_call:
inputs:
target:
required: true
type: string
env:
CI_DIR: 717a3c49-f5dc-42eb-b332-fcf2988d00e3
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout branch
uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
with:
ref: ${{ inputs.target }}
submodules: recursive
- name: Setup .NET
uses: actions/setup-dotnet@6bd8b7f7774af54e05809fcc5431931b3eb1ddee # v4.0.1
with:
dotnet-version: |
8.0.x
- name: Run deploy script
run: |
set -e
shopt -s globstar nullglob
shopt -u dotglob
cd Deploy
git apply < ./patches/disable-interactivity.diff
git apply < ./patches/prevent-crash-on-missing-dir.diff
./DeployAll.sh
- name: Create tarball
run: |
mkdir -p "$CI_DIR"
tar -czf "$CI_DIR/build.tar.gz" -C Deploy/bin/content .
- name: Upload tarball
uses: actions/upload-artifact@834a144ee995460fba8ed112a2fc961b36a5ec5a # v4.3.6
with:
name: build
path: ${{ env.CI_DIR }}/build.tar.gz
-89
View File
@@ -1,89 +0,0 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: Create pre-release
on:
schedule:
- cron: "0 0 * * *"
workflow_dispatch:
jobs:
check-if-release-needed:
runs-on: ubuntu-latest
outputs:
latest-commit-sha: ${{ steps.get-latest-commit.outputs.result }}
has-new-commits: ${{ steps.check-for-new-commits.outputs.has-new-commits }}
steps:
- name: Extract branch name
id: extract-branch-name
run: |
echo "result=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" >> "$GITHUB_OUTPUT"
- name: Sanity checks
if: ${{ github.event_name == 'workflow_dispatch' && steps.extract-branch-name.outputs.result != 'OBT-Release' }}
run: |
echo "::error::this workflow can only be run on the \"OBT-Release\" branch"
exit 1
- name: Get latest nightly-tagged commit
id: get-latest-tag
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
with:
result-encoding: string
script: |
try {
const ref = await github.rest.git.getRef({
owner: context.repo.owner,
repo: context.repo.repo,
ref: "tags/nightly",
});
return ref.data.object.sha;
} catch (err) {
if (err.name === "HttpError" && err.status === 404) {
return "tag-doesnt-exist";
}
throw err;
}
- name: Get latest commit on dev branch
id: get-latest-commit
uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
with:
result-encoding: string
script: |
const ref = await github.rest.git.getRef({
owner: context.repo.owner,
repo: context.repo.repo,
ref: "heads/OBT-Release",
});
return ref.data.object.sha;
- name: Check for new commits
id: check-for-new-commits
if: ${{ steps.get-latest-tag.outputs.result != 'tag-doesnt-exist' }}
env:
LATEST_TAGGED_SHA: "${{ steps.get-latest-tag.outputs.result }}"
LATEST_SHA: "${{ steps.get-latest-commit.outputs.result }}"
run: |
if [[ -z "$LATEST_TAGGED_SHA" ]]; then
echo "::error::LATEST_TAGGED_SHA env var is invalid"
exit 1
fi
if [[ -z "$LATEST_SHA" ]]; then
echo "::error::LATEST_TAGGED_SHA env var is invalid"
exit 1
fi
if [[ "$LATEST_TAGGED_SHA" == "$LATEST_SHA" ]]; then
echo "has-new-commits=false" >> "$GITHUB_OUTPUT"
else
echo "has-new-commits=true" >> "$GITHUB_OUTPUT"
fi
publish-release:
needs: [check-if-release-needed]
if: true
uses: ./.github/workflows/publish-release.yml
with:
target: ${{ needs.check-if-release-needed.outputs.latest-commit-sha }}
tag: nightly
prerelease: true
-21
View File
@@ -1,21 +0,0 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: Harden CI security
on:
workflow_call:
inputs:
target:
required: true
type: string
jobs:
ensure-sha-pinned-actions:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
with:
ref: ${{ inputs.target }}
- name: Ensure all actions are pinned to a specific commit
uses: zgosalvez/github-actions-ensure-sha-pinned-actions@3c16e895bb662b4d7e284f032cbe8835a57773cc # v3.0.11
-22
View File
@@ -1,22 +0,0 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: On push to master branch
on:
push:
branches: [master]
paths-ignore:
- ".github/**"
- "*.md"
jobs:
run-tests:
uses: ./.github/workflows/run-tests.yml
with:
target: ${{ github.event.ref }}
publish-release:
uses: ./.github/workflows/publish-release.yml
with:
target: ${{ github.event.ref }}
tag: latest
@@ -1,16 +0,0 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: On push to a secondary branch
on:
push:
branches-ignore: [master]
paths-ignore:
- ".github/**"
- "*.md"
jobs:
run-tests:
uses: ./.github/workflows/run-tests.yml
with:
target: ${{ github.event.ref }}
-17
View File
@@ -1,17 +0,0 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: On push to a PR
on:
pull_request:
jobs:
harden-ci-security:
uses: ./.github/workflows/harden-ci-security.yml
with:
target: ${{ github.event.pull_request.head.sha }}
run-tests-for-pr:
uses: ./.github/workflows/run-tests.yml
with:
target: ${{ github.event.pull_request.head.sha }}
@@ -1,14 +0,0 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: On changes to .github
on:
push:
paths-ignore:
- "./.github/**"
jobs:
harden-ci-security:
uses: ./.github/workflows/harden-ci-security.yml
with:
target: ${{ github.event.ref }}
-214
View File
@@ -1,214 +0,0 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: Publish release
on:
workflow_dispatch:
workflow_call:
inputs:
target:
description: "The git ref to checkout, build from and release"
required: true
type: string
tag:
description: "The tag of the release"
required: true
type: string
prerelease:
description: "Prerelease"
required: false
default: false
type: boolean
env:
CI_DIR: 2049ef39-42a2-46d2-b513-ee6d2e3a7b15
RELEASES: |
windows:client:Windows/Client
windows:server:Windows/Server
linux:client:Linux/Client
linux:server:Linux/Server
mac:client:Mac/Client/Barotrauma.app/Contents/MacOS
mac:server:Mac/Server
ARCHIVE_BASE_NAME: luacsforbarotrauma
# XXX: these file names are subject to shell expansion.
# Be careful when using special characters.
ARCHIVE_FILES_SERVER: |
DedicatedServer.deps.json
DedicatedServer.dll
DedicatedServer.pdb
Publicized/DedicatedServer.dll
ARCHIVE_FILES_CLIENT: |
Barotrauma.deps.json
Barotrauma.dll
Barotrauma.pdb
DedicatedServer.deps.json
DedicatedServer.dll
DedicatedServer.pdb
Publicized/Barotrauma.dll
Publicized/DedicatedServer.dll
ARCHIVE_FILES_SHARED: |
BarotraumaCore.dll
BarotraumaCore.pdb
Publicized/BarotraumaCore.dll
0Harmony.dll
Sigil.dll
MoonSharp.Interpreter.dll
MoonSharp.VsCodeDebugger.dll
MonoMod.Backports.dll
MonoMod.Core.dll
MonoMod.RuntimeDetour.dll
MonoMod.ILHelpers.dll
MonoMod.Utils.dll
MonoMod.Iced.dll
Mono.Cecil.dll
Mono.Cecil.Mdb.dll
Mono.Cecil.Pdb.dll
Mono.Cecil.Rocks.dll
Microsoft.CodeAnalysis.CSharp.Scripting.dll
Microsoft.CodeAnalysis.CSharp.dll
Microsoft.CodeAnalysis.dll
Microsoft.CodeAnalysis.Scripting.dll
System.Collections.Immutable.dll
System.Reflection.Metadata.dll
System.Runtime.CompilerServices.Unsafe.dll
mscordaccore_amd64_amd64_*
Lua
jobs:
build:
uses: ./.github/workflows/build.yml
with:
target: ${{ inputs.target }}
publish-release:
runs-on: ubuntu-latest
needs: [build]
steps:
- name: Download build artifacts
uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
with:
name: build
path: ${{ env.CI_DIR }}
- name: Extract build artifacts
run: |
artifacts_dir="$(realpath -m "$CI_DIR/artifacts")"
mkdir -p "$artifacts_dir"
tar -xzf "$CI_DIR/build.tar.gz" -C "$artifacts_dir"
rm "$CI_DIR/build.tar.gz"
- name: Create archives
run: |
set -e
shopt -s globstar nullglob
shopt -u dotglob
# This converts a newline-separated (LF) list into a Bash array
# NOTE: this doesn't discard the trailing LF that GitHub actions
# append (which results in an extra entry in the array).
lines_to_array() {
IFS=$'\n' readarray -td $'\n' "$1" <<< "${!1}"
}
lines_to_array ARCHIVE_FILES_SHARED
lines_to_array ARCHIVE_FILES_CLIENT
lines_to_array ARCHIVE_FILES_SERVER
lines_to_array RELEASES
artifacts_dir="$(realpath -m "$CI_DIR/artifacts")"
mkdir -p "$artifacts_dir"
archives_dir="$(realpath -m "$CI_DIR/archives")"
mkdir -p "$archives_dir"
refs_dir="$(realpath -m "$CI_DIR/refs")"
mkdir -p "${refs_dir}"
mkdir -p "${refs_dir}/Windows"
mkdir -p "${refs_dir}/Linux"
mkdir -p "${refs_dir}/OSX"
# Archive Refs, used by mod developers
cp "${artifacts_dir}/Windows/Client/Publicized/Barotrauma.dll" "${refs_dir}/Windows/Barotrauma.dll"
cp "${artifacts_dir}/Windows/Client/Publicized/DedicatedServer.dll" "${refs_dir}/Windows/DedicatedServer.dll"
cp "${artifacts_dir}/Windows/Client/Publicized/BarotraumaCore.dll" "${refs_dir}/Windows/BarotraumaCore.dll"
cp "${artifacts_dir}/Linux/Client/Publicized/Barotrauma.dll" "${refs_dir}/Linux/Barotrauma.dll"
cp "${artifacts_dir}/Linux/Client/Publicized/DedicatedServer.dll" "${refs_dir}/Linux/DedicatedServer.dll"
cp "${artifacts_dir}/Linux/Client/Publicized/BarotraumaCore.dll" "${refs_dir}/Linux/BarotraumaCore.dll"
cp "${artifacts_dir}/Mac/Client/Barotrauma.app/Contents/MacOS/Publicized/Barotrauma.dll" "${refs_dir}/OSX/Barotrauma.dll"
cp "${artifacts_dir}/Mac/Client/Barotrauma.app/Contents/MacOS/Publicized/DedicatedServer.dll" "${refs_dir}/OSX/DedicatedServer.dll"
cp "${artifacts_dir}/Mac/Client/Barotrauma.app/Contents/MacOS/Publicized/BarotraumaCore.dll" "${refs_dir}/OSX/BarotraumaCore.dll"
cp "${artifacts_dir}/Windows/Client/Publicized/MonoGame.Framework.Windows.NetStandard.dll" "${refs_dir}/MonoGame.Framework.Windows.NetStandard.dll"
cp "${artifacts_dir}/Linux/Client/Publicized/MonoGame.Framework.Linux.NetStandard.dll" "${refs_dir}/MonoGame.Framework.Linux.NetStandard.dll"
cp "${artifacts_dir}/Mac/Client/Barotrauma.app/Contents/MacOS/Publicized/MonoGame.Framework.MacOS.NetStandard.dll" "${refs_dir}/MonoGame.Framework.MacOS.NetStandard.dll"
# Those are the same across all the platforms, so i guess it doesn't matter?
cp "${artifacts_dir}/Windows/Client/Publicized/0Harmony.dll" "${refs_dir}/0Harmony.dll"
cp "${artifacts_dir}/Windows/Client/Publicized/MonoMod.Utils.dll" "${refs_dir}/MonoMod.Utils.dll"
cp "${artifacts_dir}/Windows/Client/Publicized/MonoMod.RuntimeDetour.dll" "${refs_dir}/MonoMod.RuntimeDetour.dll"
cp "${artifacts_dir}/Windows/Client/Publicized/MonoMod.ILHelpers.dll" "${refs_dir}/MonoMod.ILHelpers.dll"
cp "${artifacts_dir}/Windows/Client/Publicized/MonoMod.Iced.dll" "${refs_dir}/MonoMod.Iced.dll"
cp "${artifacts_dir}/Windows/Client/Publicized/MonoMod.Backports.dll" "${refs_dir}/MonoMod.Backports.dll"
cp "${artifacts_dir}/Windows/Client/Publicized/Farseer.NetStandard.dll" "${refs_dir}/Farseer.NetStandard.dll"
cp "${artifacts_dir}/Windows/Client/Publicized/Lidgren.NetStandard.dll" "${refs_dir}/Lidgren.NetStandard.dll"
cp "${artifacts_dir}/Windows/Client/Publicized/Mono.Cecil.dll" "${refs_dir}/Mono.Cecil.dll"
cp "${artifacts_dir}/Windows/Client/Publicized/MoonSharp.Interpreter.dll" "${refs_dir}/MoonSharp.Interpreter.dll"
cp "${artifacts_dir}/Windows/Client/Publicized/XNATypes.dll" "${refs_dir}/XNATypes.dll"
cd "${refs_dir}"
zip -r "${archives_dir}/${ARCHIVE_BASE_NAME}_refs.zip" .
for i in "${!RELEASES[@]}"; do
[[ -z "${RELEASES[i]}" ]] && continue
(
IFS=':' read platform side publish_dir _rest <<< "${RELEASES[i]}"
cd "${artifacts_dir}/${publish_dir}"
echo "Creating build_${platform}_${side}.zip"
zip --must-match -qr "${archives_dir}/${ARCHIVE_BASE_NAME}_build_${platform}_${side}.zip" *
echo "Creating build_${platform}_${side}.tar.gz"
tar -czf "${archives_dir}/${ARCHIVE_BASE_NAME}_build_${platform}_${side}.tar.gz" \
--owner=0 --group=0 \
*
if [[ "$side" == "client" ]]; then
files=(
${ARCHIVE_FILES_SHARED[@]}
${ARCHIVE_FILES_CLIENT[@]}
)
elif [[ "$side" == "server" ]]; then
files=(
${ARCHIVE_FILES_SHARED[@]}
${ARCHIVE_FILES_SERVER[@]}
)
else
echo "Invalid side: $side"
exit 1
fi
echo "Creating patch_${platform}_${side}.zip"
zip \
--must-match \
-qr \
"${archives_dir}/${ARCHIVE_BASE_NAME}_patch_${platform}_${side}.zip" \
"${files[@]}"
echo "Creating patch_${platform}_${side}.tar.gz"
tar \
-zcf "${archives_dir}/${ARCHIVE_BASE_NAME}_patch_${platform}_${side}.tar.gz" \
--owner=0 --group=0 \
"${files[@]}"
)
done
- name: Publish release
uses: notpeelz/action-gh-create-release@c1bebd17c8a128e8db4165a68be4dc4e3f106ff1 # v5.0.1
with:
target: ${{ inputs.target }}
tag: ${{ inputs.tag }}
prerelease: ${{ inputs.prerelease }}
strategy: replace
title: "Automatic build"
body: "Automatic build"
files: |
${{ env.CI_DIR }}/archives/${{ env.ARCHIVE_BASE_NAME }}_{build,patch}_{windows,linux,mac}_{client,server}.zip
${{ env.CI_DIR }}/archives/${{ env.ARCHIVE_BASE_NAME }}_{build,patch}_linux_{client,server}.tar.gz
${{ env.CI_DIR }}/archives/${{ env.ARCHIVE_BASE_NAME }}_refs.zip
-27
View File
@@ -1,27 +0,0 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: Report test results
# HACK: the "on-push-pr" workflow gets run with read-only perms.
# This workflow will run in our repo with write permissions after
# the PR checks are done running.
on:
workflow_run:
workflows:
- On push to master branch
- On push to a secondary branch
- On push to a PR
types: [completed]
jobs:
report-test-results:
runs-on: ubuntu-latest
steps:
- name: Report test results
uses: dorny/test-reporter@31a54ee7ebcacc03a09ea97a7e5465a47b84aea5 # v1.9.1
with:
name: Test results
artifact: test-results
path: test-results.trx
fail-on-error: false
reporter: dotnet-trx
-47
View File
@@ -1,47 +0,0 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: Run tests
on:
workflow_call:
inputs:
target:
required: true
type: string
jobs:
run-tests:
runs-on: ubuntu-latest
steps:
- name: Checkout branch
uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
with:
repository: ${{ inputs.repository }}
ref: ${{ inputs.target }}
submodules: recursive
- name: Setup .NET
uses: actions/setup-dotnet@6bd8b7f7774af54e05809fcc5431931b3eb1ddee # v4.0.1
with:
dotnet-version: |
8.0.x
- name: Initialize environment
run: |
mkdir -p ~/".local/share/Daedalic Entertainment GmbH/Barotrauma"
- name: Run tests
continue-on-error: true
run: |
set +e
dotnet test LinuxSolution.sln -clp:"ErrorsOnly;Summary" --logger "trx;LogFileName=$PWD/test-results.trx"
echo "EXITCODE=$?" >> "$GITHUB_ENV"
- name: Upload test results
uses: actions/upload-artifact@834a144ee995460fba8ed112a2fc961b36a5ec5a # v4.3.6
with:
name: test-results
path: test-results.trx
- name: Set exit code
run: exit "$EXITCODE"
-118
View File
@@ -1,118 +0,0 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: Update documentation
on:
workflow_dispatch:
env:
CI_DEPLOY_DIR: luacs-docs/ci-deploy
CI_ARTIFACTS_DIR: luacs-docs/ci-artifacts
DOCS_LUA_ROOT: luacs-docs/lua
DOCS_CS_ROOT: luacs-docs/cs
DOCS_LANDINGPAGE_ROOT: luacs-docs/landing-page
jobs:
update-docs-lua:
runs-on: ubuntu-latest
steps:
- name: Checkout branch
uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
with:
submodules: recursive
- name: Setup .NET
uses: actions/setup-dotnet@6bd8b7f7774af54e05809fcc5431931b3eb1ddee # v4.0.1
with:
dotnet-version: |
6.0.x
- uses: leafo/gh-actions-lua@35bcb06abec04ec87df82e08caa84d545348536e # v10.0.0
with:
luaVersion: "5.2"
- uses: leafo/gh-actions-luarocks@e65774a6386cb4f24e293dca7fc4ff89165b64c5 # v4.3.0
- name: Run install script
working-directory: ${{ env.DOCS_LUA_ROOT }}
run: ./scripts/install.sh
- name: Run docs generator script
working-directory: ${{ env.DOCS_LUA_ROOT }}
run: ./scripts/generate_docs.sh
- name: Run build script
working-directory: ${{ env.DOCS_LUA_ROOT }}
run: ./scripts/build.sh
- name: Create tarball
run: |
mkdir -p "$CI_ARTIFACTS_DIR"
tar -czf "$CI_ARTIFACTS_DIR"/lua.tar.gz -C "$DOCS_LUA_ROOT"/build .
- name: Upload tarball
uses: actions/upload-artifact@834a144ee995460fba8ed112a2fc961b36a5ec5a # v4.3.6
with:
name: docs-lua
path: ${{ env.CI_ARTIFACTS_DIR }}/lua.tar.gz
update-docs-cs:
runs-on: ubuntu-latest
steps:
- name: Checkout branch
uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
- name: Install doxygen
run: sudo apt-get update && sudo apt-get install -y doxygen
- name: Run build script
working-directory: ${{ env.DOCS_CS_ROOT }}
run: ./scripts/build.sh
- name: Create tarball
run: |
mkdir -p "$CI_ARTIFACTS_DIR"
tar -czf "$CI_ARTIFACTS_DIR"/cs.tar.gz -C "$DOCS_CS_ROOT"/build .
- name: Upload tarball
uses: actions/upload-artifact@834a144ee995460fba8ed112a2fc961b36a5ec5a # v4.3.6
with:
name: docs-cs
path: ${{ env.CI_ARTIFACTS_DIR }}/cs.tar.gz
deploy-docs:
runs-on: ubuntu-latest
needs: [update-docs-lua, update-docs-cs]
steps:
- name: Checkout branch
uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
- run: mkdir -p "$CI_ARTIFACTS_DIR" "$CI_DEPLOY_DIR"
- name: "Download build artifacts: lua docs"
uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
with:
name: docs-lua
path: ${{ env.CI_ARTIFACTS_DIR }}
- name: "Download build artifacts: cs docs"
uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8
with:
name: docs-cs
path: ${{ env.CI_ARTIFACTS_DIR }}
- name: Extract lua and cs tarballs
run: |
mkdir -p "$CI_DEPLOY_DIR"/{lua,cs}-docs
tar -xzf "$CI_ARTIFACTS_DIR"/lua.tar.gz -C "$CI_DEPLOY_DIR"/lua-docs
tar -xzf "$CI_ARTIFACTS_DIR"/cs.tar.gz -C "$CI_DEPLOY_DIR"/cs-docs
- name: Copy landing page files
run: cp -r "$DOCS_LANDINGPAGE_ROOT"/. "$CI_DEPLOY_DIR"
- name: Deploy
uses: peaceiris/actions-gh-pages@4f9cc6602d3f66b9c108549d475ec49e8ef4d45e #v4.0.0
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ${{ env.CI_DEPLOY_DIR }}
keep_files: true
-33
View File
@@ -1,33 +0,0 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow.json
name: Update MoonSharp
on:
workflow_dispatch:
env:
SUBMODULE_PATH: Libraries/moonsharp
GIT_USER_EMAIL: "41898282+github-actions[bot]@users.noreply.github.com"
GIT_USER_NAME: "github-actions[bot]"
jobs:
update-moonsharp:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # v4.1.7
with:
submodules: recursive
- name: Update submodule
run: git submodule update --recursive --remote "$SUBMODULE_PATH"
- name: Create commit
run: |
git config user.name "$GIT_USER_NAME"
git config user.email "$GIT_USER_EMAIL"
git commit -am "Update submodule: $SUBMODULE_PATH"
- name: Push
run: git push
-2
View File
@@ -16,7 +16,6 @@ bld/
[Dd]ebugLinux/
[Rr]eleaseLinux/
*.o
*/Barotrauma*/doc/
# Misc vs crap
*.v12.suo
@@ -59,4 +58,3 @@ Deploy/DeployAll/PrivateKey.*
#Rider
*.DotSettings.user
.vscode/settings.json
-6
View File
@@ -1,6 +0,0 @@
[submodule "Libraries/moonsharp"]
path = Libraries/moonsharp
url = https://github.com/evilfactory/moonsharp.git
[submodule "luacs-docs/lua/libs/ldoc"]
path = luacs-docs/lua/libs/ldoc
url = https://github.com/evilfactory/LDoc.git
@@ -222,8 +222,6 @@ namespace Barotrauma
private static bool IsCommandPermitted(Identifier command, GameClient client)
{
if (GameMain.LuaCs.Game.IsCustomCommandPermitted(command)) { return true; }
switch (command.Value.ToLowerInvariant())
{
case "kick":
@@ -659,14 +657,6 @@ namespace Barotrauma
return;
}
bool luaCsEnabled = true;
if (args.Length > 3)
{
bool.TryParse(args[3], out luaCsEnabled);
}
if (luaCsEnabled) { GameMain.LuaCs.Initialize(); }
GameMain.MainMenuScreen.QuickStart(fixedSeed: false, subName, difficulty, levelGenerationParams);
}, getValidArgs: () => new[] { SubmarineInfo.SavedSubmarines.Select(s => s.Name).Distinct().OrderBy(s => s).ToArray() }));
@@ -4224,46 +4214,7 @@ namespace Barotrauma
}
});
commands.Add(new Command("cl_lua", $"cl_lua: Runs a string on the client.", (string[] args) =>
{
if (GameMain.Client != null && !GameMain.Client.HasPermission(ClientPermissions.ConsoleCommands))
{
ThrowError("Command not permitted.");
return;
}
if (GameMain.LuaCs.Lua == null)
{
ThrowError("LuaCs not initialized, use the console command cl_reloadluacs to force initialization.");
return;
}
try
{
GameMain.LuaCs.Lua.DoString(string.Join(" ", args));
}
catch(Exception ex)
{
LuaCsLogger.HandleException(ex, LuaCsMessageOrigin.LuaMod);
}
}));
commands.Add(new Command("cl_reloadlua|cl_reloadcs|cl_reloadluacs", "Re-initializes the LuaCs environment.", (string[] args) =>
{
GameMain.LuaCs.Initialize();
}));
commands.Add(new Command("cl_toggleluadebug", "Toggles the MoonSharp Debug Server.", (string[] args) =>
{
int port = 41912;
if (args.Length > 0)
{
int.TryParse(args[0], out port);
}
GameMain.LuaCs.ToggleDebugger(port);
}));
}
@@ -411,12 +411,6 @@ namespace Barotrauma
public void AddMessage(ChatMessage message)
{
if (GameMain.IsSingleplayer)
{
var should = GameMain.LuaCs.Hook.Call<bool?>("chatMessage", message.Text, message.SenderClient, message.Type, message);
if (should != null && should.Value) { return; }
}
while (chatBox.Content.CountChildren > 60)
{
chatBox.RemoveChild(chatBox.Content.Children.First());
@@ -36,16 +36,6 @@ namespace Barotrauma
/// If the event launches, the text should already be up to date!
/// </summary>
public event OnTextChangedHandler OnTextChanged;
public OnTextChangedHandler OnTextChangedDelegate
{
set
{
OnTextChanged += (GUITextBox a, string b) =>
{
return value.Invoke(a, b);
};
}
}
public bool CaretEnabled { get; set; }
public Color? CaretColor { get; set; }
@@ -23,7 +23,6 @@ namespace Barotrauma
{
class GameMain : Game
{
public static LuaCsSetup LuaCs;
public static bool ShowFPS;
public static bool ShowPerf;
public static bool DebugDraw;
@@ -244,8 +243,6 @@ namespace Barotrauma
throw new Exception("Content folder not found. If you are trying to compile the game from the source code and own a legal copy of the game, you can copy the Content folder from the game's files to BarotraumaShared/Content.");
}
LuaCs = new LuaCsSetup();
GameSettings.Init();
CreatureMetrics.Init();
@@ -636,9 +633,6 @@ namespace Barotrauma
HasLoaded = true;
log("LOADING COROUTINE FINISHED");
#if CLIENT
LuaCsInstaller.CheckUpdate();
#endif
contentLoaded = true;
while (postContentLoadActions.TryDequeue(out Action action))
@@ -986,8 +980,6 @@ namespace Barotrauma
Screen.Selected.AddToGUIUpdateList();
LuaCsLogger.AddToGUIUpdateList();
Client?.AddToGUIUpdateList();
SubmarinePreview.AddToGUIUpdateList();
@@ -1054,8 +1046,6 @@ namespace Barotrauma
SoundManager?.Update();
GameMain.LuaCs.Update();
Timing.Accumulator -= Timing.Step;
updateCount++;
@@ -1237,8 +1227,6 @@ namespace Barotrauma
GUIMessageBox.CloseAll();
MainMenuScreen.Select();
GameSession = null;
GameMain.LuaCs.Stop();
}
public void ShowBugReporter()
@@ -179,8 +179,6 @@ namespace Barotrauma.Tutorials
public void Start()
{
GameMain.LuaCs.CheckInitialize();
GameMain.Instance.ShowLoading(Loading());
ObjectiveManager.ResetObjectives();
@@ -1,122 +0,0 @@
using System;
using System.IO;
using System.Linq;
namespace Barotrauma
{
static partial class LuaCsInstaller
{
public static void Uninstall()
{
if (!File.Exists("Temp/Original/Barotrauma.dll"))
{
new GUIMessageBox("Error", "Error: Temp/Original/Barotrauma.dll not found, Github version? Use Steam validate files instead.");
return;
}
var msg = new GUIMessageBox("Confirm", "Are you sure you want to remove Client-Side LuaCs?", new LocalizedString[2] { TextManager.Get("Yes"), TextManager.Get("Cancel") });
msg.Buttons[0].OnClicked = (GUIButton button, object obj) =>
{
msg.Close();
string[] filesToRemove = new string[]
{
"Barotrauma.dll", "Barotrauma.deps.json", "Barotrauma.pdb", "BarotraumaCore.dll", "BarotraumaCore.pdb",
"System.Reflection.Metadata.dll", "System.Collections.Immutable.dll",
"System.Runtime.CompilerServices.Unsafe.dll"
};
try
{
CreateMissingDirectory();
foreach (string file in filesToRemove)
{
File.Move(file, "Temp/ToDelete/" + file, true);
File.Move("Temp/Original/" + file, file, true);
}
}
catch (Exception e)
{
new GUIMessageBox("Error", $"{e} {e.InnerException} \nTry verifying files instead.");
return false;
}
new GUIMessageBox("Restart", "Restart your game to apply the changes. If the mod continues to stay active after the restart, try verifying games instead.");
return true;
};
msg.Buttons[1].OnClicked = (GUIButton button, object obj) =>
{
msg.Close();
return true;
};
}
public static void CheckUpdate()
{
if (!File.Exists(LuaCsSetup.VersionFile)) { return; }
ContentPackage luaPackage = LuaCsSetup.GetPackage(LuaCsSetup.LuaForBarotraumaId);
if (luaPackage == null) { return; }
string luaCsPath = Path.GetDirectoryName(luaPackage.Path);
string clientVersion = File.ReadAllText(LuaCsSetup.VersionFile);
string workshopVersion = luaPackage.ModVersion;
if (clientVersion == workshopVersion || File.Exists("debugsomething")) { return; }
var msg = new GUIMessageBox($"LuaCs Update", $"Your LuaCs client version is different from the version found in the LuaCsForBarotrauma workshop files. Do you want to update?\n\n Client Version: {clientVersion}\n Workshop Version: {workshopVersion}",
new LocalizedString[2] { TextManager.Get("Yes"), TextManager.Get("Cancel") });
msg.Buttons[0].OnClicked = (GUIButton button, object obj) =>
{
string[] filesToUpdate = trackingFiles.Concat(Directory.EnumerateFiles(luaCsPath, "*.dll", SearchOption.AllDirectories)
.Where(s => s.Contains("mscordaccore_amd64_amd64")).Select(s => Path.GetFileName(s))).ToArray();
try
{
CreateMissingDirectory();
foreach (string file in filesToUpdate)
{
try
{
File.Move(file, "Temp/Old/" + file, true);
File.Copy(Path.Combine(luaCsPath, "Binary", file), file, true);
}
catch (Exception e)
{
DebugConsole.ThrowError($"Failed to update file {e}");
}
}
File.WriteAllText(LuaCsSetup.VersionFile, workshopVersion);
}
catch (Exception e)
{
new GUIMessageBox("Failed", $"Failed to update, error: {e}");
msg.Close();
return true;
}
new GUIMessageBox("Restart", $"LuaCs updated! Restart your game to apply the changes.");
msg.Close();
return true;
};
msg.Buttons[1].OnClicked = (GUIButton button, object obj) =>
{
msg.Close();
return true;
};
}
}
}
@@ -1,50 +0,0 @@
using Microsoft.Xna.Framework;
namespace Barotrauma
{
partial class LuaCsLogger
{
private static GUIFrame overlayFrame;
private static GUITextBlock textBlock;
private static double showTimer = 0;
private static void CreateOverlay(string message)
{
overlayFrame = new GUIFrame(new RectTransform(new Vector2(0.4f, 0.03f), null), null, new Color(50, 50, 50, 100))
{
CanBeFocused = false
};
GUILayoutGroup layout = new GUILayoutGroup(new RectTransform(new Vector2(0.8f, 0.8f), overlayFrame.RectTransform, Anchor.CenterLeft), false, Anchor.Center)
{
};
textBlock = new GUITextBlock(new RectTransform(new Vector2(1f, 0f), layout.RectTransform), message);
overlayFrame.RectTransform.MinSize = new Point((int)(textBlock.TextSize.X * 1.2), 0);
layout.Recalculate();
}
public static void AddToGUIUpdateList()
{
if (overlayFrame != null && Timing.TotalTime <= showTimer)
{
overlayFrame.AddToGUIUpdateList();
}
}
public static void ShowErrorOverlay(string message, float time = 5f, float duration = 1.5f)
{
if (Timing.TotalTime <= showTimer)
{
return;
}
CreateOverlay(message);
overlayFrame.Flash(Color.Red, duration, true);
showTimer = Timing.TotalTime + time;
}
}
}
@@ -1,143 +0,0 @@
using Barotrauma.Networking;
using System.Collections.Generic;
namespace Barotrauma
{
partial class LuaCsNetworking
{
private Dictionary<ushort, Queue<IReadMessage>> receiveQueue = new Dictionary<ushort, Queue<IReadMessage>>();
public void SendSyncMessage()
{
if (GameMain.Client == null) { return; }
WriteOnlyMessage message = new WriteOnlyMessage();
message.WriteByte((byte)ClientPacketHeader.LUA_NET_MESSAGE);
message.WriteByte((byte)LuaCsClientToServer.RequestAllIds);
GameMain.Client.ClientPeer.Send(message, DeliveryMethod.Reliable);
}
public void NetMessageReceived(IReadMessage netMessage, ServerPacketHeader header, Client client = null)
{
if (header != ServerPacketHeader.LUA_NET_MESSAGE)
{
GameMain.LuaCs.Hook.Call("netMessageReceived", netMessage, header, client);
return;
}
LuaCsServerToClient luaCsHeader = (LuaCsServerToClient)netMessage.ReadByte();
switch (luaCsHeader)
{
case LuaCsServerToClient.NetMessageString:
HandleNetMessageString(netMessage);
break;
case LuaCsServerToClient.NetMessageId:
HandleNetMessageId(netMessage);
break;
case LuaCsServerToClient.ReceiveIds:
ReadIds(netMessage);
break;
}
}
public IWriteMessage Start(string netMessageName)
{
var message = new WriteOnlyMessage();
message.WriteByte((byte)ClientPacketHeader.LUA_NET_MESSAGE);
if (stringToId.ContainsKey(netMessageName))
{
message.WriteByte((byte)LuaCsClientToServer.NetMessageId);
message.WriteUInt16(stringToId[netMessageName]);
}
else
{
message.WriteByte((byte)LuaCsClientToServer.NetMessageString);
message.WriteString(netMessageName);
}
return message;
}
public void Receive(string netMessageName, LuaCsAction callback)
{
RequestId(netMessageName);
netReceives[netMessageName] = callback;
}
public void RequestId(string netMessageName)
{
if (stringToId.ContainsKey(netMessageName)) { return; }
if (GameMain.Client == null) { return; }
WriteOnlyMessage message = new WriteOnlyMessage();
message.WriteByte((byte)ClientPacketHeader.LUA_NET_MESSAGE);
message.WriteByte((byte)LuaCsClientToServer.RequestSingleId);
message.WriteString(netMessageName);
Send(message, DeliveryMethod.Reliable);
}
public void Send(IWriteMessage netMessage, DeliveryMethod deliveryMethod = DeliveryMethod.Reliable)
{
GameMain.Client.ClientPeer.Send(netMessage, deliveryMethod);
}
private void HandleNetMessageId(IReadMessage netMessage, Client client = null)
{
ushort id = netMessage.ReadUInt16();
if (idToString.ContainsKey(id))
{
string name = idToString[id];
HandleNetMessage(netMessage, name, client);
}
else
{
if (!receiveQueue.ContainsKey(id)) { receiveQueue[id] = new Queue<IReadMessage>(); }
receiveQueue[id].Enqueue(netMessage);
if (GameSettings.CurrentConfig.VerboseLogging)
{
LuaCsLogger.LogMessage($"Received NetMessage with unknown id {id} from server, storing in queue in case we receive the id later.");
}
}
}
private void ReadIds(IReadMessage netMessage)
{
ushort size = netMessage.ReadUInt16();
for (int i = 0; i < size; i++)
{
ushort id = netMessage.ReadUInt16();
string name = netMessage.ReadString();
idToString[id] = name;
stringToId[name] = id;
if (!receiveQueue.ContainsKey(id))
{
continue;
}
while (receiveQueue[id].TryDequeue(out var queueMessage))
{
if (netReceives.ContainsKey(name))
{
netReceives[name](queueMessage, null);
}
}
}
}
}
}
@@ -1,115 +0,0 @@
using Microsoft.Xna.Framework;
namespace Barotrauma
{
static class LuaCsSettingsMenu
{
private static GUIFrame frame;
public static void Open(RectTransform rectTransform)
{
Close();
frame = new GUIFrame(new RectTransform(new Vector2(0.4f, 0.6f), rectTransform, Anchor.Center));
GUIListBox list = new GUIListBox(new RectTransform(new Vector2(0.95f, 0.95f), frame.RectTransform, Anchor.Center), false);
new GUITextBlock(new RectTransform(new Vector2(1f, 0.1f), list.Content.RectTransform), "LuaCs Settings", textAlignment: Alignment.Center);
new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Enable CSharp Scripting")
{
Selected = GameMain.LuaCs.Config.EnableCsScripting,
ToolTip = "This enables CSharp Scripting for mods to use, WARNING: CSharp is NOT sandboxed, be careful with what mods you download.",
OnSelected = (GUITickBox tick) =>
{
GameMain.LuaCs.Config.EnableCsScripting = tick.Selected;
GameMain.LuaCs.WriteSettings();
return true;
}
};
new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Treat Forced Mods As Normal")
{
Selected = GameMain.LuaCs.Config.TreatForcedModsAsNormal,
ToolTip = "This makes mods that were setup to run even when disabled to only run when enabled.",
OnSelected = (GUITickBox tick) =>
{
GameMain.LuaCs.Config.TreatForcedModsAsNormal = tick.Selected;
GameMain.LuaCs.WriteSettings();
return true;
}
};
new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Prefer To Use Workshop Lua Setup")
{
Selected = GameMain.LuaCs.Config.PreferToUseWorkshopLuaSetup,
ToolTip = "This makes Lua look first for the Lua/LuaSetup.lua located in the Workshop package instead of the one located locally.",
OnSelected = (GUITickBox tick) =>
{
GameMain.LuaCs.Config.PreferToUseWorkshopLuaSetup = tick.Selected;
GameMain.LuaCs.WriteSettings();
return true;
}
};
new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Disable Error GUI Overlay")
{
Selected = GameMain.LuaCs.Config.DisableErrorGUIOverlay,
ToolTip = "",
OnSelected = (GUITickBox tick) =>
{
GameMain.LuaCs.Config.DisableErrorGUIOverlay = tick.Selected;
GameMain.LuaCs.WriteSettings();
return true;
}
};
new GUITickBox(new RectTransform(new Vector2(0.8f, 0.1f), list.Content.RectTransform), "Hide usernames In Error Logs")
{
Selected = GameMain.LuaCs.Config.HideUserNames,
ToolTip = "Hides the operating system username when displaying error logs (eg your username on windows).",
OnSelected = (GUITickBox tick) =>
{
GameMain.LuaCs.Config.HideUserNames = tick.Selected;
GameMain.LuaCs.WriteSettings();
return true;
}
};
new GUIButton(new RectTransform(new Vector2(1f, 0.1f), list.Content.RectTransform), $"Remove Client-Side LuaCs", style: "GUIButtonSmall")
{
ToolTip = "Remove Client-Side LuaCs.",
OnClicked = (tb, userdata) =>
{
LuaCsInstaller.Uninstall();
return true;
}
};
new GUIButton(new RectTransform(new Vector2(0.8f, 0.01f), frame.RectTransform, Anchor.BottomCenter)
{
RelativeOffset = new Vector2(0f, 0.05f)
}, "Close")
{
OnClicked = (GUIButton button, object obj) =>
{
Close();
return true;
}
};
}
public static void Close()
{
frame?.Parent.RemoveChild(frame);
frame = null;
}
}
}
@@ -1,75 +0,0 @@
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Barotrauma
{
partial class LuaCsSetup
{
public void AddToGUIUpdateList()
{
if (!GameMain.LuaCs.Config.DisableErrorGUIOverlay)
{
LuaCsLogger.AddToGUIUpdateList();
}
}
public void CheckInitialize()
{
List<ContentPackage> csharpMods = new List<ContentPackage>();
foreach (ContentPackage cp in ContentPackageManager.EnabledPackages.All)
{
if (Directory.Exists(cp.Dir + "/CSharp") || Directory.Exists(cp.Dir + "/bin"))
{
csharpMods.Add(cp);
}
}
if (csharpMods.Count == 0 || ShouldRunCs)
{
Initialize();
return;
}
StringBuilder sb = new StringBuilder();
foreach (ContentPackage cp in csharpMods)
{
if (cp.UgcId.TryUnwrap(out ContentPackageId id))
{
sb.AppendLine($"- {cp.Name} ({id})");
}
else
{
sb.AppendLine($"- {cp.Name} (Not On Workshop)");
}
}
if (GameMain.Client == null || GameMain.Client.IsServerOwner)
{
new GUIMessageBox("", $"You have CSharp mods enabled but don't have the CSharp Scripting enabled, those mods might not work, go to the Main Menu, click on LuaCs Settings and check Enable CSharp Scripting.\n\n{sb}");
Initialize();
return;
}
GUIMessageBox msg = new GUIMessageBox(
"Confirm",
$"This server has the following CSharp mods installed: \n{sb}\nDo you wish to run them? Cs mods are not sandboxed so make sure you trust these mods.",
new LocalizedString[2] { "Run", "Don't Run" });
msg.Buttons[0].OnClicked = (GUIButton button, object obj) =>
{
Initialize(true);
msg.Close();
return true;
};
msg.Buttons[1].OnClicked = (GUIButton button, object obj) =>
{
Initialize();
msg.Close();
return true;
};
}
}
}
@@ -284,7 +284,7 @@ namespace Barotrauma.Networking
otherClients = new List<Client>();
ServerSettings = new ServerSettings(this, serverName, 0, 0, 0, false, false, System.Net.IPAddress.Any);
ServerSettings = new ServerSettings(this, serverName, 0, 0, 0, false, false);
Voting = new Voting();
serverEndpoints = endpoints;
@@ -603,8 +603,6 @@ namespace Barotrauma.Networking
{
ServerPacketHeader header = (ServerPacketHeader)inc.ReadByte();
GameMain.LuaCs.Networking.NetMessageReceived(inc, header);
if (roundInitStatus == RoundInitStatus.WaitingForStartGameFinalize
&& header is not (
ServerPacketHeader.STARTGAMEFINALIZE
@@ -2905,8 +2903,6 @@ namespace Barotrauma.Networking
public void Quit()
{
GameMain.LuaCs.Stop();
ClientPeer?.Close(PeerDisconnectPacket.WithReason(DisconnectReason.Disconnected));
GUIMessageBox.MessageBoxes.RemoveAll(c => c?.UserData is RoundSummary);
@@ -3006,9 +3002,6 @@ namespace Barotrauma.Networking
public override void AddChatMessage(ChatMessage message)
{
var should = GameMain.LuaCs.Hook.Call<bool?>("chatMessage", message.Text, message.SenderClient, message.Type, message);
if (should != null && should.Value) { return; }
if (string.IsNullOrEmpty(message.Text)) { return; }
if (message.SenderCharacter is { IsDead: false } sender)
{
@@ -222,7 +222,7 @@ namespace Barotrauma
}
}
public class PlayerInput
public static class PlayerInput
{
static MouseState mouseState, oldMouseState;
static MouseState latestMouseState; //the absolute latest state, do NOT use for player interaction
@@ -495,8 +495,6 @@ namespace Barotrauma
allowInput = true;
}
GameMain.LuaCs.Hook.Call("keyUpdate", deltaTime);
oldMouseState = mouseState;
mouseState = latestMouseState;
UpdateVariable();
@@ -95,7 +95,6 @@ namespace Barotrauma
}
GameMain.GameSession?.AddToGUIUpdateList();
Character.AddAllToGUIUpdateList();
base.AddToGUIUpdateList();
}
public override void Draw(double deltaTime, GraphicsDevice graphics, SpriteBatch spriteBatch)
@@ -531,24 +531,6 @@ namespace Barotrauma
}
};
#endif
new GUIButton(new RectTransform(new Point(300, 30), Frame.RectTransform, Anchor.TopLeft) { AbsoluteOffset = new Point(40, 50) },
$"Open LuaCs Settings", style: "MainMenuGUIButton", color: GUIStyle.Red)
{
IgnoreLayoutGroups = true,
OnClicked = (tb, userdata) =>
{
LuaCsSettingsMenu.Open(Frame.RectTransform);
return true;
}
};
string version = File.Exists(LuaCsSetup.VersionFile) ? File.ReadAllText(LuaCsSetup.VersionFile) : "Github";
new GUITextBlock(new RectTransform(new Point(300, 30), Frame.RectTransform, Anchor.TopLeft) { AbsoluteOffset = new Point(10, 10) }, $"Using LuaCsForBarotrauma revision {AssemblyInfo.GitRevision} version {version}", Color.Red)
{
IgnoreLayoutGroups = false
};
var minButtonSize = new Point(120, 20);
var maxButtonSize = new Point(480, 80);
@@ -703,8 +685,6 @@ namespace Barotrauma
#region Selection
public override void Select()
{
GameMain.LuaCs.Stop();
ResetModUpdateButton();
if (WorkshopItemsToUpdate.Any())
@@ -1314,8 +1294,6 @@ namespace Barotrauma
return;
}
GameMain.LuaCs.CheckInitialize();
selectedSub = new SubmarineInfo(Path.Combine(SaveUtil.TempPath, selectedSub.Name + ".sub"));
GameMain.GameSession = new GameSession(selectedSub, Option.None, CampaignDataPath.CreateRegular(savePath), GameModePreset.SinglePlayerCampaign, settings, mapSeed);
@@ -1331,8 +1309,6 @@ namespace Barotrauma
{
if (string.IsNullOrWhiteSpace(path)) return;
GameMain.LuaCs.CheckInitialize();
try
{
CampaignDataPath dataPath =
@@ -118,7 +118,6 @@ namespace Barotrauma
ContentPackageManager.EnabledPackages.SetRegular(regularPackages);
}
GameMain.NetLobbyScreen.Select();
GameMain.LuaCs.CheckInitialize();
return;
}
@@ -379,7 +378,6 @@ namespace Barotrauma
}
GameMain.NetLobbyScreen.UpdateSubList(GameMain.NetLobbyScreen.SubList, GameMain.Client.ServerSubmarines);
GameMain.NetLobbyScreen.Select();
GameMain.LuaCs.CheckInitialize();
}
}
else if (GameMain.Client.FileReceiver.ActiveTransfers.None())
@@ -1531,8 +1531,6 @@ namespace Barotrauma
public override void Select()
{
Select(enableAutoSave: true);
GameMain.LuaCs.CheckInitialize();
}
public void Select(bool enableAutoSave = true)
@@ -211,9 +211,4 @@
<Import Project="../BarotraumaShared/DeployEosPrivate.props" />
<Import Project="../BarotraumaShared/DeployGameAnalytics.props" />
<Import Project="../BarotraumaShared/Luatrauma.props" />
<ItemGroup>
<None Include="../BarotraumaShared/Luatrauma.props" />
</ItemGroup>
</Project>
@@ -14,7 +14,6 @@
<Configurations>Debug;Release;Unstable</Configurations>
<InvariantGlobalization>true</InvariantGlobalization>
<WarningsAsErrors>;NU1605;CS0114;CS0108;CS8597;CS8600;CS8601;CS8602;CS8603;CS8604;CS8605;CS8606;CS8607;CS8608;CS8609;CS8610;CS8611;CS8612;CS8613;CS8614;CS8615;CS8616;CS8617;CS8618;CS8619;CS8620;CS8621;CS8622;CS8624;CS8625;CS8626;CS8629;CS8631;CS8632;CS8633;CS8634;CS8638;CS8643;CS8644;CS8645;CS8653;CS8654;CS8655;CS8667;CS8669;CS8670;CS8714;CS8717;CS8765</WarningsAsErrors>
<ErrorOnDuplicatePublishOutputFiles>false</ErrorOnDuplicatePublishOutputFiles>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
@@ -216,9 +215,4 @@
<Import Project="../BarotraumaShared/DeployEosPrivate.props" />
<Import Project="../BarotraumaShared/DeployGameAnalytics.props" />
<Import Project="../BarotraumaShared/Luatrauma.props" />
<ItemGroup>
<None Include="../BarotraumaShared/Luatrauma.props" />
</ItemGroup>
</Project>
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
@@ -243,9 +243,4 @@
<Import Project="../BarotraumaShared/DeployEosPrivate.props" />
<Import Project="../BarotraumaShared/DeployGameAnalytics.props" />
<Import Project="../BarotraumaShared/Luatrauma.props" />
<ItemGroup>
<None Include="../BarotraumaShared/Luatrauma.props" />
</ItemGroup>
</Project>
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
@@ -55,7 +55,7 @@
</PropertyGroup>
<ItemGroup>
<Content Include="..\BarotraumaShared\**\*" CopyToOutputDirectory="PreserveNewest" Exclude="..\BarotraumaShared\Data\Saves\*.save;..\BarotraumaShared\ModLists\*.xml" />
<Content Include="..\BarotraumaShared\**\*" CopyToOutputDirectory="PreserveNewest" Exclude="..\BarotraumaShared\Data\Saves\*.save;..\BarotraumaShared\ModLists\*.xml;..\BarotraumaShared\LocalMods\[DebugOnlyTest]*\**" />
<Content Remove="..\BarotraumaShared\**\*.cs" />
<Content Remove="..\BarotraumaShared\**\*.props" />
<Compile Include="..\BarotraumaShared\**\*.cs" />
@@ -157,8 +157,4 @@
</PropertyGroup>
<Import Project="../BarotraumaShared/DeployEosPrivate.props" />
<Import Project="../BarotraumaShared/Luatrauma.props" />
<ItemGroup>
<None Include="../BarotraumaShared/Luatrauma.props" />
</ItemGroup>
</Project>
+1 -5
View File
@@ -59,7 +59,7 @@
</PropertyGroup>
<ItemGroup>
<Content Include="..\BarotraumaShared\**\*" CopyToOutputDirectory="PreserveNewest" Exclude="..\BarotraumaShared\Data\Saves\*.save;..\BarotraumaShared\ModLists\*.xml" />
<Content Include="..\BarotraumaShared\**\*" CopyToOutputDirectory="PreserveNewest" Exclude="..\BarotraumaShared\Data\Saves\*.save;..\BarotraumaShared\ModLists\*.xml;..\BarotraumaShared\LocalMods\[DebugOnlyTest]*\**" />
<Content Remove="..\BarotraumaShared\**\*.cs" />
<Content Remove="..\BarotraumaShared\**\*.props" />
<Compile Include="..\BarotraumaShared\**\*.cs" />
@@ -162,8 +162,4 @@
</PropertyGroup>
<Import Project="../BarotraumaShared/DeployEosPrivate.props" />
<Import Project="../BarotraumaShared/Luatrauma.props" />
<ItemGroup>
<None Include="../BarotraumaShared/Luatrauma.props" />
</ItemGroup>
</Project>
@@ -64,13 +64,10 @@ namespace Barotrauma
{
var owner = GameMain.Server.ConnectedClients.Find(c => c.Character == this);
if (owner != null)
{
if (!GameMain.LuaCs.Game.overrideTraitors)
{
GameMain.Server.SendDirectChatMessage(TextManager.FormatServerMessage("KilledByTraitorNotification"), owner, ChatMessageType.ServerMessageBoxInGame);
}
}
}
foreach (Client client in GameMain.Server.ConnectedClients)
{
if (client.InGame)
@@ -319,12 +319,8 @@ namespace Barotrauma
if (prefab == null) { continue; }
if (TalentTree.IsViableTalentForCharacter(this, prefab.Identifier, talentSelection))
{
bool? should = GameMain.LuaCs.Hook.Call<bool?>("character.updateTalent", this, prefab, c);
if (should == null)
{
GiveTalent(prefab.Identifier);
}
talentSelection.Add(prefab.Identifier);
}
}
@@ -815,7 +811,7 @@ namespace Barotrauma
var tempBuffer = new ReadWriteMessage();
WriteStatus(tempBuffer, forceAfflictionData: true);
if (msgLengthBeforeStatus + tempBuffer.LengthBytes >= 255 && restrictMessageSize && GameMain.LuaCs.Networking.RestrictMessageSize)
if (msgLengthBeforeStatus + tempBuffer.LengthBytes >= 255 && restrictMessageSize)
{
msg.WriteBoolean(false);
if (msgLengthBeforeStatus < 255)
@@ -5,7 +5,6 @@ using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Barotrauma.Steam;
@@ -314,7 +313,7 @@ namespace Barotrauma
return client;
}
public static void AssignOnClientRequestExecute(string names, Action<Client, Vector2, string[]> onClientRequestExecute)
private static void AssignOnClientRequestExecute(string names, Action<Client, Vector2, string[]> onClientRequestExecute)
{
var matchingCommand = commands.Find(c => c.Names.Intersect(names.Split('|').ToIdentifiers()).Any());
if (matchingCommand == null)
@@ -1287,41 +1286,6 @@ namespace Barotrauma
GameMain.NetLobbyScreen.LevelSeed = string.Join(" ", args);
}));
commands.Add(new Command("lua", "lua: Runs a string.", (string[] args) =>
{
try
{
GameMain.LuaCs.Lua.DoString(string.Join(" ", args));
}
catch (Exception ex)
{
LuaCsLogger.HandleException(ex, LuaCsMessageOrigin.LuaMod);
}
}));
commands.Add(new Command("reloadlua|reloadcs|reloadluacs", "Re-initializes the LuaCs environment.", (string[] args) =>
{
GameMain.LuaCs.Initialize();
}));
commands.Add(new Command("toggleluadebug", "Toggles the MoonSharp Debug Server.", (string[] args) =>
{
int port = 41912;
if (args.Length > 0)
{
int.TryParse(args[0], out port);
}
GameMain.LuaCs.ToggleDebugger(port);
}));
#if DEBUG
commands.Add(new Command("install_cl_lua|install_cl|install_cl_cs|install_cl_luacs", "Installs Client-Side LuaCs into your client.", (string[] args) =>
{
LuaCsInstaller.Install();
}));
#endif
commands.Add(new Command("randomizeseed", "randomizeseed: Toggles level seed randomization on/off.", (string[] args) =>
{
GameMain.Server.ServerSettings.RandomizeSeed = !GameMain.Server.ServerSettings.RandomizeSeed;
@@ -2769,12 +2733,6 @@ namespace Barotrauma
}
);
commands.Add(new Command("ShowServerPerf", "Immediately log server performance info in ServerMessage", (string[] args) =>
{
GameServer.Log(PerformenceMonitor.PM.ToString(), ServerLog.MessageType.ServerMessage);
NewMessage(PerformenceMonitor.PM.ToString(), Color.Green);
}));
#if DEBUG
commands.Add(new Command("spamevents", "A debug command that creates a ton of entity events.", (string[] args) =>
{
@@ -10,10 +10,7 @@ using System.Linq;
using System.Reflection;
using System.Threading;
using System.Xml.Linq;
using MoonSharp.Interpreter;
using System.Net;
using Barotrauma.Extensions;
using System.Threading.Tasks;
namespace Barotrauma
{
@@ -35,8 +32,6 @@ namespace Barotrauma
set { world = value; }
}
public static LuaCsSetup LuaCs;
public static GameServer Server;
public static NetworkMember NetworkMember
{
@@ -131,8 +126,6 @@ namespace Barotrauma
NetLobbyScreen = new NetLobbyScreen();
CheckContentPackage();
LuaCs = new LuaCsSetup();
}
@@ -159,7 +152,6 @@ namespace Barotrauma
int maxPlayers = 10;
Option<int> ownerKey = Option.None;
Option<P2PEndpoint> ownerEndpoint = Option.None;
IPAddress listenIp = IPAddress.Any;
XDocument doc = XMLExtensions.TryLoadXml(ServerSettings.SettingsFile);
if (doc?.Root == null)
@@ -195,12 +187,6 @@ namespace Barotrauma
name = CommandLineArgs[i + 1];
i++;
break;
case "-ip":
if (IPAddress.TryParse(CommandLineArgs[i + 1], out IPAddress address))
listenIp = address;
else
DebugConsole.ThrowError($"Invalid Ip Address '{CommandLineArgs[i + 1]}'.");
break;
case "-port":
int.TryParse(CommandLineArgs[i + 1], out port);
i++;
@@ -249,7 +235,6 @@ namespace Barotrauma
Server = new GameServer(
name,
listenIp,
port,
queryPort,
publiclyVisible,
@@ -328,10 +313,8 @@ namespace Barotrauma
}
Stopwatch performanceCounterTimer = Stopwatch.StartNew();
stopwatch = Stopwatch.StartNew();
PerformenceMonitor PM = new PerformenceMonitor();
long prevTicks = stopwatch.ElapsedTicks;
while (ShouldRun)
{
@@ -351,8 +334,6 @@ namespace Barotrauma
prevTicks = currTicks;
while (Timing.Accumulator >= Timing.Step)
{
performanceCounterTimer.Start();
Timing.TotalTime += Timing.Step;
Timing.TotalTimeUnpaused += Timing.Step;
DebugConsole.Update();
@@ -367,17 +348,8 @@ namespace Barotrauma
TaskPool.Update();
CoroutineManager.Update(paused: false, (float)Timing.Step);
GameMain.LuaCs.Update();
performanceCounterTimer.Stop();
if (GameMain.LuaCs.PerformanceCounter.EnablePerformanceCounter)
{
GameMain.LuaCs.PerformanceCounter.UpdateElapsedTime = (double)performanceCounterTimer.ElapsedTicks / Stopwatch.Frequency;
}
performanceCounterTimer.Reset();
Timing.Accumulator -= Timing.Step;
updateCount++;
PM.Update();
}
#if !DEBUG
@@ -425,9 +397,6 @@ namespace Barotrauma
updateCount = 0;
}
}
PerformenceMonitor.PM.Dispose();
stopwatch.Stop();
CloseServer();
@@ -459,7 +428,6 @@ namespace Barotrauma
public void Exit()
{
ShouldRun = false;
GameMain.LuaCs.Stop();
}
}
}
@@ -1,107 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Barotrauma.Networking
{
partial class Client
{
public void SetClientCharacter(Character character)
{
GameMain.Server.SetClientCharacter(this, character);
}
public void Kick(string reason = "")
{
GameMain.Server.KickClient(this.Connection, reason);
}
public void Ban(string reason = "", float seconds = -1)
{
if (seconds == -1)
{
GameMain.Server.BanClient(this, reason, null);
}
else
{
GameMain.Server.BanClient(this, reason, TimeSpan.FromSeconds(seconds));
}
}
public static void UnbanPlayer(string playerName)
{
GameMain.Server.UnbanPlayer(playerName);
}
public static void BanPlayer(string player, string reason, bool range = false, float seconds = -1)
{
if (seconds == -1)
{
GameMain.Server.BanPlayer(player, reason, null);
}
else
{
GameMain.Server.BanPlayer(player, reason, TimeSpan.FromSeconds(seconds));
}
}
public bool CheckPermission(ClientPermissions permissions)
{
return this.Permissions.HasFlag(permissions);
}
}
}
namespace Barotrauma
{
using Microsoft.Xna.Framework;
using System.Reflection;
partial class Item
{
public object CreateServerEventString(string component)
{
var comp = GetComponentString(component);
if (comp == null)
return null;
MethodInfo method = typeof(Item).GetMethod(nameof(Item.CreateServerEvent), new Type[]{ Type.MakeGenericMethodParameter(0) });
MethodInfo generic = method.MakeGenericMethod(comp.GetType());
return generic.Invoke(this, new object[]{ comp });
}
public object CreateServerEventString(string component, object[] extraData)
{
var comp = GetComponentString(component);
if (comp == null)
return null;
MethodInfo method = typeof(Item).GetMethod(nameof(Item.CreateServerEvent), new Type[]{ Type.MakeGenericMethodParameter(0), typeof(object[]) });
MethodInfo generic = method.MakeGenericMethod(comp.GetType());
return generic.Invoke(this, new object[]{comp, extraData });
}
}
}
namespace Barotrauma.Items.Components
{
using Barotrauma.Networking;
partial struct Signal
{
public static Signal Create(string value, int stepsTaken = 0, Character sender = null, Item source = null, float power = 0.0f, float strength = 1.0f)
{
return new Signal(value, stepsTaken, sender, source, power, strength);
}
}
partial class Quality
{
public void SetValue(StatType statType, float value)
{
statValues[statType] = value;
}
}
}
@@ -1,70 +0,0 @@
using Barotrauma.Networking;
using System;
using System.IO;
using System.Linq;
namespace Barotrauma
{
static partial class LuaCsInstaller
{
public static void Install()
{
ContentPackage luaPackage = LuaCsSetup.GetPackage(LuaCsSetup.LuaForBarotraumaId);
if (luaPackage == null)
{
GameMain.Server.SendChatMessage("Couldn't find the LuaCs For Barotrauma package.", ChatMessageType.ServerMessageBox);
return;
}
try
{
string path = Path.GetDirectoryName(luaPackage.Path);
string[] filesToCopy = trackingFiles.Concat(Directory.EnumerateFiles(path, "*.dll", SearchOption.AllDirectories)
.Where(s => s.Contains("mscordaccore_amd64_amd64")).Select(s => Path.GetFileName(s))).ToArray();
CreateMissingDirectory();
File.Move("Barotrauma.dll", "Temp/Original/Barotrauma.dll", true);
File.Move("Barotrauma.deps.json", "Temp/Original/Barotrauma.deps.json", true);
File.Move("Barotrauma.pdb", "Temp/Original/Barotrauma.pdb", true);
File.Move("BarotraumaCore.dll", "Temp/Original/BarotraumaCore.dll", true);
File.Move("BarotraumaCore.pdb", "Temp/Original/BarotraumaCore.pdb", true);
File.Move("System.Reflection.Metadata.dll", "Temp/Original/System.Reflection.Metadata.dll", true);
File.Move("System.Collections.Immutable.dll", "Temp/Original/System.Collections.Immutable.dll", true);
File.Move("System.Runtime.CompilerServices.Unsafe.dll", "Temp/Original/System.Runtime.CompilerServices.Unsafe.dll", true);
foreach (string file in filesToCopy)
{
if (File.Exists(file))
{
File.Move(file, "Temp/ToDelete/" + file, true);
}
File.Copy(Path.Combine(path, "Binary", file), file, true);
}
File.WriteAllText(LuaCsSetup.VersionFile, luaPackage.ModVersion);
#if WINDOWS
File.WriteAllText("LuaCsDedicatedServer.bat", "\"%LocalAppData%/Daedalic Entertainment GmbH/Barotrauma/WorkshopMods/Installed/2559634234/Binary/DedicatedServer.exe\"");
#endif
}
catch (UnauthorizedAccessException e)
{
LuaCsLogger.LogError($"Unauthorized file access exception. This usually means you already have LuaCs installed. ${e}", LuaCsMessageOrigin.LuaCs);
return;
}
catch (Exception e)
{
LuaCsLogger.HandleException(e, LuaCsMessageOrigin.LuaCs);
return;
}
GameMain.Server.SendChatMessage("Client-Side LuaCs installed, restart your game to apply changes.", ChatMessageType.ServerMessageBox);
}
}
}
@@ -1,194 +0,0 @@
using Barotrauma.Networking;
using System.Collections.Generic;
using System.Linq;
namespace Barotrauma
{
partial class LuaCsNetworking
{
private const int MaxRegisterPerClient = 1000;
private Dictionary<string, int> clientRegisterCount = new Dictionary<string, int>();
private ushort currentId = 0;
public void NetMessageReceived(IReadMessage netMessage, ClientPacketHeader header, Client client = null)
{
if (header != ClientPacketHeader.LUA_NET_MESSAGE)
{
GameMain.LuaCs.Hook.Call("netMessageReceived", netMessage, header, client);
return;
}
LuaCsClientToServer luaCsHeader = (LuaCsClientToServer)netMessage.ReadByte();
switch (luaCsHeader)
{
case LuaCsClientToServer.NetMessageString:
HandleNetMessageString(netMessage, client);
break;
case LuaCsClientToServer.NetMessageId:
HandleNetMessageId(netMessage, client);
break;
case LuaCsClientToServer.RequestAllIds:
WriteAllIds(client);
break;
case LuaCsClientToServer.RequestSingleId:
RequestIdSingle(netMessage, client);
break;
}
}
private void HandleNetMessageId(IReadMessage netMessage, Client client = null)
{
ushort id = netMessage.ReadUInt16();
if (idToString.ContainsKey(id))
{
string name = idToString[id];
HandleNetMessage(netMessage, name, client);
}
else
{
if (GameSettings.CurrentConfig.VerboseLogging)
{
LuaCsLogger.LogError($"Received NetMessage for unknown id {id} from {GameServer.ClientLogName(client)}.");
}
}
}
public IWriteMessage Start(string netMessageName)
{
var message = new WriteOnlyMessage();
message.WriteByte((byte)ServerPacketHeader.LUA_NET_MESSAGE);
if (stringToId.ContainsKey(netMessageName))
{
message.WriteByte((byte)LuaCsServerToClient.NetMessageId);
message.WriteUInt16(stringToId[netMessageName]);
}
else
{
message.WriteByte((byte)LuaCsServerToClient.NetMessageString);
message.WriteString(netMessageName);
}
return message;
}
public void Receive(string netMessageName, LuaCsAction callback)
{
RegisterId(netMessageName);
netReceives[netMessageName] = callback;
}
public ushort RegisterId(string name)
{
if (stringToId.ContainsKey(name))
{
return stringToId[name];
}
if (currentId >= ushort.MaxValue)
{
LuaCsLogger.LogError($"Tried to register more than {ushort.MaxValue} network ids!");
return 0;
}
currentId++;
idToString[currentId] = name;
stringToId[name] = currentId;
WriteIdToAll(currentId, name);
return currentId;
}
private void RequestIdSingle(IReadMessage netMessage, Client client)
{
string name = netMessage.ReadString();
if (!stringToId.ContainsKey(name) && client.AccountId.TryUnwrap(out AccountId id))
{
if (!clientRegisterCount.ContainsKey(id.StringRepresentation))
{
clientRegisterCount[id.StringRepresentation] = 0;
}
clientRegisterCount[id.StringRepresentation]++;
if (clientRegisterCount[id.StringRepresentation] > MaxRegisterPerClient)
{
LuaCsLogger.Log($"{GameServer.ClientLogName(client)} Tried to register more than {MaxRegisterPerClient} Ids!");
return;
}
}
RegisterId(name);
}
private void WriteIdToAll(ushort id, string name)
{
WriteOnlyMessage message = new WriteOnlyMessage();
message.WriteByte((byte)ServerPacketHeader.LUA_NET_MESSAGE);
message.WriteByte((byte)LuaCsServerToClient.ReceiveIds);
message.WriteUInt16(1);
message.WriteUInt16(id);
message.WriteString(name);
Send(message, null, DeliveryMethod.Reliable);
}
private void WriteAllIds(Client client)
{
WriteOnlyMessage message = new WriteOnlyMessage();
message.WriteByte((byte)ServerPacketHeader.LUA_NET_MESSAGE);
message.WriteByte((byte)LuaCsServerToClient.ReceiveIds);
message.WriteUInt16((ushort)idToString.Count());
foreach ((ushort id, string name) in idToString)
{
message.WriteUInt16(id);
message.WriteString(name);
}
Send(message, client.Connection, DeliveryMethod.Reliable);
}
public void ClientWriteLobby(Client client) => GameMain.Server.ClientWriteLobby(client);
public void Send(IWriteMessage netMessage, NetworkConnection connection = null, DeliveryMethod deliveryMethod = DeliveryMethod.Reliable)
{
if (connection == null)
{
foreach (NetworkConnection conn in Client.ClientList.Select(c => c.Connection))
{
GameMain.Server.ServerPeer.Send(netMessage, conn, deliveryMethod);
}
}
else
{
GameMain.Server.ServerPeer.Send(netMessage, connection, deliveryMethod);
}
}
public void UpdateClientPermissions(Client client)
{
GameMain.Server.UpdateClientPermissions(client);
}
public int FileSenderMaxPacketsPerUpdate
{
get { return FileSender.FileTransferOut.MaxPacketsPerUpdate; }
set { FileSender.FileTransferOut.MaxPacketsPerUpdate = value; }
}
}
}
@@ -1,6 +1,5 @@
using System;
using System.Text;
using MoonSharp.Interpreter;
namespace Barotrauma.Networking
{
@@ -86,13 +85,6 @@ namespace Barotrauma.Networking
HandleSpamFilter(c, txt, out bool flaggedAsSpam, similarityMultiplier);
if (flaggedAsSpam) { return; }
var should = GameMain.LuaCs.Hook.Call<bool?>("chatMessage", txt, c, type);
if (should != null && should.Value)
{
return;
}
if (type == ChatMessageType.Order)
{
if (c.Character == null || c.Character.SpeechImpediment >= 100.0f || c.Character.IsDead) { return; }
@@ -135,8 +127,6 @@ namespace Barotrauma.Networking
{
GameMain.Server.SendChatMessage(txt, senderClient: c, chatMode: chatMode, type: type == ChatMessageType.Team ? type : null);
}
}
/// <summary>
@@ -207,7 +197,7 @@ namespace Barotrauma.Networking
int length = 1 + //(byte)ServerNetObject.CHAT_MESSAGE
2 + //(UInt16)NetStateID
1 + //(byte)Type
(Text == null ? 0 : Encoding.UTF8.GetBytes(Text).Length) + 2;
Encoding.UTF8.GetBytes(Text).Length + 2;
if (SenderClient != null)
{
@@ -52,7 +52,7 @@ namespace Barotrauma.Networking
}
}
public static int MaxPacketsPerUpdate = 10;
public const int MaxPacketsPerUpdate = 10;
public float PacketsPerUpdate { get; set; } = 1.0f;
public byte[] Data { get; }
@@ -11,8 +11,6 @@ using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Xml.Linq;
using MoonSharp.Interpreter;
using System.Net;
using Barotrauma.PerkBehaviors;
namespace Barotrauma.Networking
@@ -170,7 +168,6 @@ namespace Barotrauma.Networking
public GameServer(
string name,
IPAddress listenIp,
int port,
int queryPort,
bool isPublic,
@@ -187,7 +184,7 @@ namespace Barotrauma.Networking
LastClientListUpdateID = 0;
ServerSettings = new ServerSettings(this, name, port, queryPort, maxPlayers, isPublic, attemptUPnP, listenIp);
ServerSettings = new ServerSettings(this, name, port, queryPort, maxPlayers, isPublic, attemptUPnP);
KarmaManager.SelectPreset(ServerSettings.KarmaPreset);
ServerSettings.SetPassword(password);
ServerSettings.SaveSettings();
@@ -245,7 +242,6 @@ namespace Barotrauma.Networking
VoipServer = new VoipServer(serverPeer);
GameMain.LuaCs.Initialize();
Log("Server started", ServerLog.MessageType.ServerMessage);
GameMain.NetLobbyScreen.Select();
@@ -339,8 +335,6 @@ namespace Barotrauma.Networking
SendConsoleMessage("Granted all permissions to " + newClient.Name + ".", newClient);
}
GameMain.LuaCs.Hook.Call("client.connected", newClient);
SendChatMessage($"ServerMessage.JoinedServer~[client]={ClientLogName(newClient)}", ChatMessageType.Server, changeType: PlayerConnectionChangeType.Joined);
ServerSettings.ServerDetailsChanged = true;
@@ -441,12 +435,9 @@ namespace Barotrauma.Networking
(!spectating ||
(permadeathMode && (!character.IsDead || character.CauseOfDeath?.Type == CauseOfDeathType.Disconnected)));
if (!character.IsDead)
{
if (!GameMain.LuaCs.Game.disableDisconnectCharacter)
{
character.KillDisconnectedTimer += deltaTime;
character.SetStun(1.0f);
}
float killTime = permadeathMode ? ServerSettings.DespawnDisconnectedPermadeathTime : ServerSettings.KillDisconnectedTime;
//owner decided to spectate -> kill the character immediately,
@@ -837,9 +828,6 @@ namespace Barotrauma.Networking
using var _ = dosProtection.Start(connectedClient);
ClientPacketHeader header = (ClientPacketHeader)inc.ReadByte();
GameMain.LuaCs.Networking.NetMessageReceived(inc, header, connectedClient);
switch (header)
{
case ClientPacketHeader.PING_RESPONSE:
@@ -1218,9 +1206,7 @@ namespace Barotrauma.Networking
errorLines.Add("");
errorLines.Add("EntitySpawner events:");
try
{
foreach (var entityEvent in entityEventManager.UniqueEvents.ToList())
foreach (var entityEvent in entityEventManager.UniqueEvents)
{
if (entityEvent.Entity is EntitySpawner)
{
@@ -1232,11 +1218,6 @@ namespace Barotrauma.Networking
" (" + spawnData.ID + ", " + spawnData.Entity.ID + ")");
}
}
}
catch
{
errorLines.Add("Failed to write EntitySpawner events.");
}
errorLines.Add("");
errorLines.Add("Last debug messages:");
@@ -2312,7 +2293,6 @@ namespace Barotrauma.Networking
segmentTable.StartNewSegment(ServerNetSegment.ClientList);
outmsg.WriteUInt16(LastClientListUpdateID);
GameMain.LuaCs.Hook.Call("writeClientList", c, outmsg);
outmsg.WriteByte((byte)Team1Count);
outmsg.WriteByte((byte)Team2Count);
@@ -2339,19 +2319,12 @@ namespace Barotrauma.Networking
IsDownloading = FileSender.ActiveTransfers.Any(t => t.Connection == client.Connection)
};
var result = GameMain.LuaCs.Hook.Call<TempClient?>("writeClientList.modifyTempClientData", c, client, tempClientData, outmsg);
if (result != null)
{
tempClientData = result.Value;
}
outmsg.WriteNetSerializableStruct(tempClientData);
outmsg.WritePadBits();
}
}
public void ClientWriteLobby(Client c)
private void ClientWriteLobby(Client c)
{
bool isInitialUpdate = false;
@@ -3197,14 +3170,7 @@ namespace Barotrauma.Networking
}
TraitorManager.Initialize(GameMain.GameSession.EventManager, Level.Loaded);
if (GameMain.LuaCs.Game.overrideTraitors)
{
TraitorManager.Enabled = false;
}
else
{
TraitorManager.Enabled = Rand.Range(0.0f, 1.0f) < ServerSettings.TraitorProbability;
}
GameAnalyticsManager.AddDesignEvent("Traitors:" + (TraitorManager == null ? "Disabled" : "Enabled"));
@@ -3226,8 +3192,6 @@ namespace Barotrauma.Networking
roundStartTime = DateTime.Now;
GameMain.LuaCs.Hook.Call("roundStart");
startGameCoroutine = null;
yield return CoroutineStatus.Success;
}
@@ -3400,15 +3364,6 @@ namespace Barotrauma.Networking
GameMain.GameSession.EndRound(endMessage);
}
TraitorManager.TraitorResults? traitorResults = traitorManager?.GetEndResults() ?? null;
var result = GameMain.LuaCs.Hook.Call<List<object>>("roundEnd");
if (result != null)
{
foreach (var data in result)
{
if (data is TraitorManager.TraitorResults traitorResultData) { traitorResults = traitorResultData; }
if (data is string endMessageData) { endMessage = endMessageData; }
}
}
EndRoundTimer = 0.0f;
@@ -3541,14 +3496,6 @@ namespace Barotrauma.Networking
return false;
}
var result = GameMain.LuaCs.Hook.Call<bool?>("tryChangeClientName", c, newName, newJob, newTeam);
if (result != null)
{
LastClientListUpdateID++;
return result.Value;
}
return TryChangeClientName(c, newName, clientRenamingSelf: true);
}
@@ -3745,8 +3692,6 @@ namespace Barotrauma.Networking
{
if (client == null) return;
GameMain.LuaCs.Hook.Call("client.disconnected", client);
if (client.Character != null)
{
client.Character.ClientDisconnected = true;
@@ -3995,21 +3940,13 @@ namespace Barotrauma.Networking
senderName = null;
senderCharacter = null;
}
else if (type == ChatMessageType.Radio && !GameMain.LuaCs.Game.overrideSignalRadio)
else if (type == ChatMessageType.Radio)
{
//send to chat-linked wifi components
Signal s = new Signal(message, sender: senderCharacter, source: senderRadio.Item);
senderRadio.TransmitSignal(s, sentFromChat: true);
}
var hookChatMsg = ChatMessage.Create(senderName, message, (ChatMessageType)type, senderCharacter, senderClient, changeType);
var should = GameMain.LuaCs.Hook.Call<bool?>("modifyChatMessage", hookChatMsg, senderRadio);
if (should != null && should.Value)
return;
//check which clients can receive the message and apply distance effects
foreach (Client client in ConnectedClients)
{
@@ -4046,7 +3983,6 @@ namespace Barotrauma.Networking
break;
}
var chatMsg = ChatMessage.Create(
senderName,
modifiedMessage,
@@ -4680,8 +4616,6 @@ namespace Barotrauma.Networking
$"No suitable jobs available for {c.Name} (karma {c.Karma}). Assigning a random job: {c.AssignedJob.Prefab.Name}.");
}
}
GameMain.LuaCs.Hook.Call("jobsAssigned", unassigned);
}
public void AssignBotJobs(List<CharacterInfo> bots, CharacterTeamType teamID, bool isPvP)
@@ -4812,8 +4746,6 @@ namespace Barotrauma.Networking
{
if (GameMain.Server == null || !GameMain.Server.ServerSettings.SaveServerLogs) { return; }
GameMain.LuaCs?.Hook?.Call("serverLog", line, messageType);
GameMain.Server.ServerSettings.ServerLog.WriteLine(line, messageType);
foreach (Client client in GameMain.Server.ConnectedClients)
@@ -1,12 +1,8 @@
using Barotrauma.Extensions;
using Microsoft.Xna.Framework;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using static Barotrauma.EosInterface.Ownership;
namespace Barotrauma.Networking
{
@@ -48,8 +44,6 @@ namespace Barotrauma.Networking
class ServerEntityEventManager : NetEntityEventManager
{
static public ServerEntityEventManager SEM;
private readonly List<ServerEntityEvent> events;
//list of unique events (i.e. !IsDuplicate) created during the round
@@ -108,20 +102,6 @@ namespace Barotrauma.Networking
private readonly GameServer server;
private double lastEventCountHighWarning;
private class PendingCreateEvent
{
public IServerSerializable Entity;
public NetEntityEvent.IData Data;
public PendingCreateEvent(IServerSerializable entity, NetEntityEvent.IData data)
{
Entity = entity;
Data = data;
}
}
private readonly ConcurrentQueue<PendingCreateEvent> pendingCreateQueue;
private readonly Task createEventTask;
public ServerEntityEventManager(GameServer server)
{
@@ -133,38 +113,18 @@ namespace Barotrauma.Networking
uniqueEvents = new List<ServerEntityEvent>();
pendingCreateQueue = new ConcurrentQueue<PendingCreateEvent>();
lastWarningTime = -10.0;
SEM = this;
createEventTask = Task.Run(async () => await CreateEventProcessorLoop());
}
private Task CreateEventProcessorLoop()
{
while (true)
{
ProcessPendingCreateEvents();
}
}
private void ProcessPendingCreateEvents()
public void CreateEvent(IServerSerializable entity, NetEntityEvent.IData extraData = null)
{
// Dequeue and process all pending events currently in the queue.
// Use a lock to synchronize modifications to shared lists / ID.
while (pendingCreateQueue.TryDequeue(out PendingCreateEvent pending))
{
// The original CreateEvent logic (mostly unchanged) but executed under a lock
if (pending == null || pending.Entity == null) { continue; }
var entity = pending.Entity;
var extraData = pending.Data;
if (!ValidateEntity(entity)) { return; }
var newEvent = new ServerEntityEvent(entity, (UInt16)(ID + 1));
if (extraData != null) newEvent.SetData(extraData);
bool inGameClientsPresent = server.ConnectedClients.Count(c => c.InGame) > 0;
//remove old events that have been sent to all clients, they are redundant now
// keep at least one event in the list (lastSentToAll == e.ID) so we can use it to keep track of the latest ID
// and events less than 15 seconds old to give disconnected clients a bit of time to reconnect without getting desynced
@@ -175,19 +135,12 @@ namespace Barotrauma.Networking
e.CreateTime < Timing.TotalTime - server.ServerSettings.EventRemovalTime);
}
bool duplicateFound = false;
for (int i = events.Count - 1; i >= 0; i--)
{
//we already have an identical event that's waiting to be sent
// -> no need to add a new one
if (events[i].IsDuplicate(newEvent) && !events[i].Sent)
{
duplicateFound = true;
break;
if (events[i].IsDuplicate(newEvent) && !events[i].Sent) return;
}
}
if (duplicateFound) { continue; }
ID++;
@@ -202,17 +155,9 @@ namespace Barotrauma.Networking
uniqueEvents.Add(uniqueEvent);
}
}
}
public void CreateEvent(IServerSerializable entity, NetEntityEvent.IData extraData = null)
{
if (!ValidateEntity(entity)) { return; }
// enqueue and let background task handle the rest
pendingCreateQueue.Enqueue(new PendingCreateEvent(entity, extraData));
}
public void Update(List<Client> clients)
{
foreach (BufferedEvent bufferedEvent in bufferedEvents)
{
if (bufferedEvent.Character == null || bufferedEvent.Character.IsDead)
@@ -30,8 +30,7 @@ namespace Barotrauma.Networking
MaximumConnections = NetConfig.MaxPlayers * 2,
EnableUPnP = serverSettings.EnableUPnP,
Port = serverSettings.Port,
DualStack = GameSettings.CurrentConfig.UseDualModeSockets,
LocalAddress = serverSettings.ListenIPAddress,
DualStack = GameSettings.CurrentConfig.UseDualModeSockets
};
netPeerConfiguration.DisableMessageType(
@@ -187,16 +186,7 @@ namespace Barotrauma.Networking
{
if (netServer == null) { return; }
var skipDeny = false;
{
var result = GameMain.LuaCs.Hook.Call<bool?>("lidgren.handleConnection", inc);
if (result != null) {
if (result.Value) skipDeny = true;
else return;
}
}
if (!skipDeny && connectedClients.Count >= serverSettings.MaxPlayers)
if (connectedClients.Count >= serverSettings.MaxPlayers)
{
inc.SenderConnection.Deny(PeerDisconnectPacket.WithReason(DisconnectReason.ServerFull).ToLidgrenStringRepresentation());
return;
@@ -33,7 +33,7 @@ namespace Barotrauma.Networking
contentPackages = contentPackageList.ToImmutableArray();
}
public sealed class PendingClient
protected sealed class PendingClient
{
public string? Name;
public Option<int> OwnerKey;
@@ -257,22 +257,17 @@ namespace Barotrauma.Networking
protected void UpdatePendingClient(PendingClient pendingClient)
{
var skipRemove = false;
var result = GameMain.LuaCs.Hook.Call<bool?>("handlePendingClient", pendingClient);
if (result != null) skipRemove = result.Value;
if (!skipRemove && connectedClients.Count >= serverSettings.MaxPlayers)
{
RemovePendingClient(pendingClient, PeerDisconnectPacket.WithReason(DisconnectReason.ServerFull));
}
if (IsPendingClientBanned(pendingClient, out string? banReason))
{
RemovePendingClient(pendingClient, PeerDisconnectPacket.Banned(banReason));
return;
}
if (connectedClients.Count >= serverSettings.MaxPlayers)
{
RemovePendingClient(pendingClient, PeerDisconnectPacket.WithReason(DisconnectReason.ServerFull));
}
if (pendingClient.InitializationStep == ConnectionInitialization.Success)
{
TConnection newConnection = pendingClient.Connection;
@@ -342,7 +337,7 @@ namespace Barotrauma.Networking
protected virtual void CheckOwnership(PendingClient pendingClient) { }
public void RemovePendingClient(PendingClient pendingClient, PeerDisconnectPacket peerDisconnectPacket)
protected void RemovePendingClient(PendingClient pendingClient, PeerDisconnectPacket peerDisconnectPacket)
{
if (pendingClients.Contains(pendingClient))
{
@@ -18,9 +18,6 @@ namespace Barotrauma.Networking
MultiPlayerCampaign campaign = GameMain.GameSession.GameMode as MultiPlayerCampaign;
foreach (Client c in networkMember.ConnectedClients)
{
if (GameMain.LuaCs.Game.overrideRespawnSub)
continue;
if (!c.InGame) { continue; }
if (c.SpectateOnly && (GameMain.Server.ServerSettings.AllowSpectating || GameMain.Server.OwnerConnection == c.Connection)) { continue; }
if (c.Character != null && !c.Character.IsDead) { continue; }
@@ -169,10 +166,6 @@ namespace Barotrauma.Networking
private bool ShouldStartRespawnCountdown(int characterToRespawnCount)
{
if (GameMain.LuaCs.Game.overrideRespawnSub)
{
characterToRespawnCount = 0;
}
return characterToRespawnCount >= GetMinCharactersToRespawn();
}
@@ -187,7 +180,7 @@ namespace Barotrauma.Networking
var teamId = teamSpecificState.TeamID;
var respawnShuttle = GetShuttle(teamId);
if (respawnShuttle != null && !GameMain.LuaCs.Game.overrideRespawnSub)
if (respawnShuttle != null)
{
respawnShuttle.Velocity = Vector2.Zero;
}
@@ -235,19 +228,12 @@ namespace Barotrauma.Networking
}
}
public void DispatchShuttle(TeamSpecificState teamSpecificState)
private void DispatchShuttle(TeamSpecificState teamSpecificState)
{
if (RespawnShuttles.Any())
{
ResetShuttle(teamSpecificState);
if (GameMain.LuaCs.Game.overrideRespawnSub)
{
teamSpecificState.CurrentState = State.Waiting;
}
else
{
teamSpecificState.CurrentState = State.Transporting;
}
GameMain.Server.CreateEntityEvent(this);
SetShuttleBodyType(teamSpecificState.TeamID, FarseerPhysics.BodyType.Dynamic);
}
@@ -522,23 +522,6 @@ namespace Barotrauma.Networking
DebugConsole.ThrowError("Error in " + ClientPermissionsFile + " - \"" + permissionsStr + "\" is not a valid client permission.");
continue;
}
if (permissions.HasFlag(Networking.ClientPermissions.ConsoleCommands))
{
foreach (XElement commandElement in clientElement.Elements())
{
if (!commandElement.Name.ToString().Equals("command", StringComparison.OrdinalIgnoreCase)) { continue; }
string commandName = commandElement.GetAttributeString("name", "");
DebugConsole.Command command = DebugConsole.FindCommand(commandName);
if (command == null)
{
command = new DebugConsole.Command(commandName, "", (_) => {}, null, true);
}
permittedCommands.Add(command);
}
}
}
else
{
@@ -96,13 +96,6 @@ namespace Barotrauma.Networking
ChatMessage.CanUseRadio(sender.Character, out WifiComponent senderRadio) &&
(recipientSpectating || ChatMessage.CanUseRadio(recipient.Character, out recipientRadio)))
{
var canUse = GameMain.LuaCs.Hook.Call<bool?>("canUseVoiceRadio", new object[] { sender, recipient });
if (canUse != null)
{
return canUse.Value;
}
if (recipientSpectating)
{
if (recipient.SpectatePos == null) { return true; }
@@ -116,8 +109,6 @@ namespace Barotrauma.Networking
}
}
float range = GameMain.LuaCs.Hook.Call<float?>("changeLocalVoiceRange", sender, recipient) ?? 1.0f;
if (recipientSpectating)
{
if (recipient.SpectatePos == null) { return true; }
@@ -129,7 +120,7 @@ namespace Barotrauma.Networking
//otherwise do a distance check
float garbleAmount = ChatMessage.GetGarbleAmount(recipient.Character, sender.Character, ChatMessage.SpeakRangeVOIP);
distanceFactor = garbleAmount;
return garbleAmount < range;
return garbleAmount < 1.0f;
}
}
@@ -1,175 +0,0 @@
using Barotrauma.Networking;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Barotrauma
{
public class PerformenceMonitor
{
static public PerformenceMonitor PM;
private Stopwatch PMStopwatch = new Stopwatch();
private double tickratetimer = 0;
private double tickrate60stimer = 0;
private static Queue<double> tickrate60s = new Queue<double>(61);
public int ItemCount
{
get{ return Item.ItemList.Count; }
}
public int CharacterCount
{
get { return Character.CharacterList.Count; }
}
public int PhysicsBodyCount
{
get { return PhysicsBody.List.Count; }
}
public double RealTickRate
{
get; set;
}
public long TotalTicks
{
get;set;
}
public int LastSecondTicks
{
get; set;
} = 0;
public float AverageTickRate
{
get
{
return TotalTicks / (float)TotalTimeElapsed * 1000;
}
}
public double AverageTickRate10s
{
get
{
return tickrate60s.Count > 0 ? tickrate60s.Average() : 60;
}
}
public double TotalTimeElapsed
{
get
{
return PMStopwatch.Elapsed.TotalMilliseconds;
}
}
public TimeSpan TimeElapsed
{
get
{
return TimeSpan.FromMilliseconds(TotalTimeElapsed);
}
}
public float MemoryUsage
{
get
{
Process proc = Process.GetCurrentProcess();
float memory = MathF.Round(proc.PrivateMemorySize64 / (1024 * 1024), 2);
proc.Dispose();
return memory;
}
}
public double TickRateLow
{
get; set;
}
public double TickRateHigh
{
get; set;
}
public PerformenceMonitor()
{
PM = this;
RealTickRate = 60;
TotalTicks = 0;
LastSecondTicks = 60;
TickRateLow = 60;
TickRateHigh = 60;
PMStopwatch.Start();
}
public void Update()
{
TotalTicks += 1;
LastSecondTicks += 1;
if (tickrate60s.Count > 60)
{
tickrate60s.Dequeue();
}
if (TotalTimeElapsed - 1000 >= tickratetimer)
{
RealTickRate = LastSecondTicks / (TotalTimeElapsed - tickratetimer) * 1000;
tickrate60s.Enqueue(RealTickRate);
tickratetimer = TotalTimeElapsed;
LastSecondTicks = 0;
}
if (TotalTimeElapsed - 60000 >= tickrate60stimer)
{
GameServer.Log(PM.ToString(), ServerLog.MessageType.ServerMessage);
TickRateLow = 60;
TickRateHigh = 60;
tickrate60stimer = TotalTimeElapsed;
}
if (RealTickRate > TickRateHigh)
{
TickRateHigh = RealTickRate;
}
if (RealTickRate < TickRateLow)
{
TickRateLow = RealTickRate;
}
}
public void Dispose()
{
PMStopwatch.Reset();
PM = null;
}
override public string ToString()
{
return $"Server Performence Info \n" +
$"Item Count: {ItemCount}\n" +
$"Character Count: {CharacterCount}\n" +
$"PhysicsBody Count: {PhysicsBodyCount}\n" +
$"Tick Rate: {RealTickRate}\n" +
$"Min Tick Rate: {TickRateLow}\n" +
$"Max Tick Rate: {TickRateHigh}\n" +
$"Total Ticks: {TotalTicks}\n" +
$"All time Average Tick Rate: {AverageTickRate}\n" +
$"60s Average Tick Rate: {AverageTickRate10s}\n" +
$"Server Run Time: {TimeElapsed}\n" +
$"Memory Usage: {MemoryUsage}\n";
}
}
}
@@ -76,11 +76,7 @@ namespace Barotrauma
}
string executableDir = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
if (!File.Exists(Path.Combine(executableDir, "workshop.txt")))
{
Directory.SetCurrentDirectory(executableDir);
}
DebugConsoleCore.Init(
newMessage: (s, c) => DebugConsole.NewMessage(s, c),
log: DebugConsole.Log);
@@ -144,14 +144,9 @@ namespace Barotrauma
GameModes = GameModePreset.List.ToArray();
}
private List<SubmarineInfo> subs;
private readonly List<SubmarineInfo> subs;
public IReadOnlyList<SubmarineInfo> GetSubList() => subs;
public void AddSub(SubmarineInfo sub)
{
subs.Add(sub);
}
public string LevelSeed
{
get
@@ -18,8 +18,7 @@ namespace Barotrauma.Steam
{
GamePort = (ushort)server.Port,
QueryPort = isPublic ? (ushort)server.QueryPort : (ushort)0,
Mode = isPublic ? Steamworks.InitServerMode.Authentication : Steamworks.InitServerMode.NoAuthentication,
IpAddress = server.ServerSettings.ListenIPAddress
Mode = isPublic ? Steamworks.InitServerMode.Authentication : Steamworks.InitServerMode.NoAuthentication
};
//options.QueryShareGamePort();
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
@@ -61,7 +61,7 @@
</PropertyGroup>
<ItemGroup>
<Content Include="..\BarotraumaShared\**\*" CopyToOutputDirectory="PreserveNewest" Exclude="..\BarotraumaShared\Data\Saves\*.save;..\BarotraumaShared\ModLists\*.xml" />
<Content Include="..\BarotraumaShared\**\*" CopyToOutputDirectory="PreserveNewest" Exclude="..\BarotraumaShared\Data\Saves\*.save;..\BarotraumaShared\ModLists\*.xml;..\BarotraumaShared\LocalMods\[DebugOnlyTest]*\**" />
<Content Remove="..\BarotraumaShared\**\*.cs" />
<Content Remove="..\BarotraumaShared\**\*.props" />
<Compile Include="..\BarotraumaShared\**\*.cs" />
@@ -164,8 +164,4 @@
</PropertyGroup>
<Import Project="../BarotraumaShared/DeployEosPrivate.props" />
<Import Project="../BarotraumaShared/Luatrauma.props" />
<ItemGroup>
<None Include="../BarotraumaShared/Luatrauma.props" />
</ItemGroup>
</Project>
@@ -0,0 +1,154 @@
<?xml version="1.0" encoding="utf-8"?>
<Items>
<Item name="[DebugOnlyTest]EXPLOSIONTESTSUIT" identifier="EXPLOSIONTESTSUIT" category="Diving,Equipment" tags="diving,deepdiving,human,respawnsuit" scale="0.5" fireproof="true" description="" allowdroppingonswapwith="diving" impactsoundtag="impact_metal_heavy" botpriority="3" cargocontaineridentifier="">
<Deconstruct time="1"/>
<InventoryIcon texture="Content/Items/InventoryIconAtlas2.png" sourcerect="0,832,128,128" origin="0.5,0.5" />
<Sprite name="Respawn Diving Suit Item" texture="Content/Items/Diving/RespawnSuit_Items.png" sourcerect="0,0,157,121" depth="0.55" origin="0.5,0.5" />
<ContainedSprite name="Respawn Diving Suit In Vertical Locker" allowedcontainertags="divingsuitcontainervertical" texture="Content/Items/Diving/RespawnSuit_Items.png" sourcerect="181,0,70,192" depth="0.55" origin="0.5,0.5" />
<ContainedSprite name="Respawn Diving Suit Behind Window" allowedcontainertags="divingsuitcontainerwindow" texture="Content/Items/Containers/containers.png" sourcerect="118,379,77,214" depth="0.55" origin="-0.12,-0.13" />
<ContainedSprite name="Respawn Diving Suit In Horizontal Locker" allowedcontainertags="divingsuitcontainerhorizontal" texture="Content/Items/Diving/RespawnSuit_Items.png" sourcerect="0,193,230,63" depth="0.55" origin="0.6,0.5" />
<Body radius="45" width="34" density="20" />
<Wearable slots="OuterClothes" msg="ItemMsgEquipSelect" displaycontainedstatus="true" canbeselected="false" canbepicked="true" pickkey="Select">
<sprite texture="Content/Items/Jobgear/headgears.png" limb="Head" inheritlimbdepth="true" inheritscale="true" ignorelimbscale="true" scale="0.65" hidelimb="false" alphaclipotherwearables="true" sourcerect="100,409,103,103" origin="0.5,0.5"/>
<sprite texture="RespawnSuit.png" limb="Torso" hidelimb="true" inherittexturescale="true" hideotherwearables="true" inheritorigin="true" inheritsourcerect="true" />
<sprite texture="RespawnSuit.png" limb="RightHand" hidelimb="true" inherittexturescale="true" hideotherwearables="true" inheritorigin="true" inheritsourcerect="true" />
<sprite texture="RespawnSuit.png" limb="LeftHand" hidelimb="true" inherittexturescale="true" hideotherwearables="true" inheritorigin="true" inheritsourcerect="true" />
<sprite texture="RespawnSuit.png" limb="RightArm" depthlimb="RightForearm" hidelimb="true" inherittexturescale="true" hideotherwearables="true" inheritorigin="true" inheritsourcerect="true" />
<sprite texture="RespawnSuit.png" limb="LeftArm" hidelimb="true" inherittexturescale="true" hideotherwearables="true" inheritorigin="true" inheritsourcerect="true" />
<sprite texture="RespawnSuit.png" limb="RightForearm" depthlimb="RightArm" hidelimb="true" inherittexturescale="true" hideotherwearables="true" inheritorigin="true" inheritsourcerect="true" />
<sprite texture="RespawnSuit.png" limb="LeftForearm" hidelimb="true" inherittexturescale="true" hideotherwearables="true" inheritorigin="true" inheritsourcerect="true" />
<sprite texture="RespawnSuit.png" limb="Waist" hidelimb="true" inherittexturescale="true" hideotherwearables="true" inheritorigin="true" inheritsourcerect="true" />
<sprite texture="RespawnSuit.png" limb="RightThigh" hidelimb="true" inherittexturescale="true" hideotherwearables="true" inheritorigin="true" inheritsourcerect="true" />
<sprite texture="RespawnSuit.png" limb="LeftThigh" hidelimb="true" inherittexturescale="true" hideotherwearables="true" inheritorigin="true" inheritsourcerect="true" />
<sprite texture="RespawnSuit.png" limb="RightLeg" hidelimb="true" inherittexturescale="true" hideotherwearables="true" inheritorigin="true" inheritsourcerect="true" />
<sprite texture="RespawnSuit.png" limb="LeftLeg" hidelimb="true" inherittexturescale="true" hideotherwearables="true" inheritorigin="true" inheritsourcerect="true" />
<sprite texture="RespawnSuit.png" limb="LeftFoot" sound="footstep_armor_heavy" hidelimb="true" inherittexturescale="true" hideotherwearables="true" inheritorigin="true" inheritsourcerect="true" />
<sprite texture="RespawnSuit.png" limb="RightFoot" sound="footstep_armor_heavy" hidelimb="true" inherittexturescale="true" hideotherwearables="true" inheritorigin="true" inheritsourcerect="true" />
<damagemodifier armorsector="0.0,360.0" afflictionidentifiers="explosiondamage" damagemultiplier="0" damagesound="LimbArmor" deflectprojectiles="true" />
</Wearable>
<Holdable slots="RightHand+LeftHand" controlpose="true" holdpos="0,-50" handle1="-10,-20" handle2="10,-20" holdangle="45" msg="ItemMsgPickUpUse" canbeselected="false" canbepicked="true" pickkey="Use" />
<aitarget maxsightrange="1500" />
</Item>
<Item name="[DebugOnlyTest]C4WithoutPen" identifier="testC40pen" category="Weapon" Tags="smallitem,explosive,demolitionsexpert" maxstacksize="32" maxstacksizecharacterinventory="8" Scale="0.5" cargocontaineridentifier="explosivecrate" impactsoundtag="impact_soft">
<Upgrade gameversion="0.9.3.0" scale="0.5"/>
<PreferredContainer primary="secarmcab" minamount="1" maxamount="2" spawnprobability="0.5" notcampaign="true" notpvp="true"/>
<PreferredContainer secondary="wreckarmcab,abandonedarmcab,piratearmcab" amount="1" spawnprobability="0.05"/>
<PreferredContainer secondary="armcab"/>
<Price baseprice="160">
<Price storeidentifier="merchantoutpost" sold="false" multiplier="1.4"/>
<Price storeidentifier="merchantcity" multiplier="1.25" minavailable="2" sold="false"/>
<Price storeidentifier="merchantresearch" sold="false" multiplier="1.25"/>
<Price storeidentifier="merchantmilitary" multiplier="0.9" minavailable="3" />
<Price storeidentifier="merchantmine" sold="false" />
<Price storeidentifier="merchantarmory" multiplier="0.9" minavailable="3" />
</Price>
<Fabricate suitablefabricators="fabricator" requiredtime="20">
<RequiredSkill identifier="weapons" level="70" />
<RequiredItem identifier="uex" />
<RequiredItem identifier="plastic" />
</Fabricate>
<InventoryIcon texture="Content/Items/InventoryIconAtlas.png" sourcerect="768,64,64,64" origin="0.5,0.5" />
<Sprite texture="Content/Items/Weapons/weapons_new.png" depth="0.55" sourcerect="51,478,48,33" origin="0.5,0.5" />
<Body width="45" height="30" density="20" />
<Throwable characterusable="false" slots="Any,RightHand,LeftHand" canbecombined="true" removeoncombined="true" throwforce="3.5" aimpos="35,-10" msg="ItemMsgPickUpSelect">
<StatusEffect type="OnUse" target="This" Condition="-100.0" disabledeltatime="true"/>
<StatusEffect type="OnBroken" target="This">
<sound file="Content/Items/Weapons/ExplosionMedium1.ogg" range="8000" />
<sound file="Content/Items/Weapons/ExplosionMedium2.ogg" range="8000" />
<sound file="Content/Items/Weapons/ExplosionMedium3.ogg" range="8000" />
<Explosion range="750.0" ballastfloradamage="150" structuredamage="0" itemdamage="1000" force="20" severlimbsprobability="2" debris="true" decal="explosion" decalsize="0.75">
<Affliction identifier="explosiondamage" strength="250" />
</Explosion>
<Remove />
</StatusEffect>
<StatusEffect type="OnBroken" target="This">
<sound file="Content/Items/Weapons/ExplosionDebris5.ogg" range="6000" />
</StatusEffect>
</Throwable>
<Quality>
<QualityStat stattype="ExplosionRadius" value="0.1"/>
<QualityStat stattype="ExplosionDamage" value="0.1"/>
</Quality>
</Item>
<Item name="[DebugOnlyTest]C4WithPen" identifier="testC41pen" category="Weapon" Tags="smallitem,explosive,demolitionsexpert" maxstacksize="32" maxstacksizecharacterinventory="8" Scale="0.5" cargocontaineridentifier="explosivecrate" impactsoundtag="impact_soft">
<Upgrade gameversion="0.9.3.0" scale="0.5"/>
<PreferredContainer primary="secarmcab" minamount="1" maxamount="2" spawnprobability="0.5" notcampaign="true" notpvp="true"/>
<PreferredContainer secondary="wreckarmcab,abandonedarmcab,piratearmcab" amount="1" spawnprobability="0.05"/>
<PreferredContainer secondary="armcab"/>
<Price baseprice="160">
<Price storeidentifier="merchantoutpost" sold="false" multiplier="1.4"/>
<Price storeidentifier="merchantcity" multiplier="1.25" minavailable="2" sold="false"/>
<Price storeidentifier="merchantresearch" sold="false" multiplier="1.25"/>
<Price storeidentifier="merchantmilitary" multiplier="0.9" minavailable="3" />
<Price storeidentifier="merchantmine" sold="false" />
<Price storeidentifier="merchantarmory" multiplier="0.9" minavailable="3" />
</Price>
<Fabricate suitablefabricators="fabricator" requiredtime="20">
<RequiredSkill identifier="weapons" level="70" />
<RequiredItem identifier="uex" />
<RequiredItem identifier="plastic" />
</Fabricate>
<InventoryIcon texture="Content/Items/InventoryIconAtlas.png" sourcerect="768,64,64,64" origin="0.5,0.5" />
<Sprite texture="Content/Items/Weapons/weapons_new.png" depth="0.55" sourcerect="51,478,48,33" origin="0.5,0.5" />
<Body width="45" height="30" density="20" />
<Throwable characterusable="false" slots="Any,RightHand,LeftHand" canbecombined="true" removeoncombined="true" throwforce="3.5" aimpos="35,-10" msg="ItemMsgPickUpSelect">
<StatusEffect type="OnUse" target="This" Condition="-100.0" disabledeltatime="true"/>
<StatusEffect type="OnBroken" target="This">
<sound file="Content/Items/Weapons/ExplosionMedium1.ogg" range="8000" />
<sound file="Content/Items/Weapons/ExplosionMedium2.ogg" range="8000" />
<sound file="Content/Items/Weapons/ExplosionMedium3.ogg" range="8000" />
<Explosion range="750.0" ballastfloradamage="150" structuredamage="0" itemdamage="1000" force="20" severlimbsprobability="2" debris="true" decal="explosion" decalsize="0.75" penetration="1">
<Affliction identifier="explosiondamage" strength="250" />
</Explosion>
<Remove />
</StatusEffect>
<StatusEffect type="OnBroken" target="This">
<sound file="Content/Items/Weapons/ExplosionDebris5.ogg" range="6000" />
</StatusEffect>
</Throwable>
<Quality>
<QualityStat stattype="ExplosionRadius" value="0.1"/>
<QualityStat stattype="ExplosionDamage" value="0.1"/>
</Quality>
</Item>
<Item name="[DebugOnlyTest]C4With2000range" identifier="testC42000" category="Weapon" Tags="smallitem,explosive,demolitionsexpert" maxstacksize="32" maxstacksizecharacterinventory="8" Scale="0.5" cargocontaineridentifier="explosivecrate" impactsoundtag="impact_soft">
<Upgrade gameversion="0.9.3.0" scale="0.5"/>
<PreferredContainer primary="secarmcab" minamount="1" maxamount="2" spawnprobability="0.5" notcampaign="true" notpvp="true"/>
<PreferredContainer secondary="wreckarmcab,abandonedarmcab,piratearmcab" amount="1" spawnprobability="0.05"/>
<PreferredContainer secondary="armcab"/>
<Price baseprice="160">
<Price storeidentifier="merchantoutpost" sold="false" multiplier="1.4"/>
<Price storeidentifier="merchantcity" multiplier="1.25" minavailable="2" sold="false"/>
<Price storeidentifier="merchantresearch" sold="false" multiplier="1.25"/>
<Price storeidentifier="merchantmilitary" multiplier="0.9" minavailable="3" />
<Price storeidentifier="merchantmine" sold="false" />
<Price storeidentifier="merchantarmory" multiplier="0.9" minavailable="3" />
</Price>
<Fabricate suitablefabricators="fabricator" requiredtime="20">
<RequiredSkill identifier="weapons" level="70" />
<RequiredItem identifier="uex" />
<RequiredItem identifier="plastic" />
</Fabricate>
<InventoryIcon texture="Content/Items/InventoryIconAtlas.png" sourcerect="768,64,64,64" origin="0.5,0.5" />
<Sprite texture="Content/Items/Weapons/weapons_new.png" depth="0.55" sourcerect="51,478,48,33" origin="0.5,0.5" />
<Body width="45" height="30" density="20" />
<Throwable characterusable="false" slots="Any,RightHand,LeftHand" canbecombined="true" removeoncombined="true" throwforce="3.5" aimpos="35,-10" msg="ItemMsgPickUpSelect">
<StatusEffect type="OnUse" target="This" Condition="-100.0" disabledeltatime="true"/>
<StatusEffect type="OnBroken" target="This">
<sound file="Content/Items/Weapons/ExplosionMedium1.ogg" range="8000" />
<sound file="Content/Items/Weapons/ExplosionMedium2.ogg" range="8000" />
<sound file="Content/Items/Weapons/ExplosionMedium3.ogg" range="8000" />
<Explosion range="5000.0" ballastfloradamage="150" structuredamage="1000" itemdamage="1000" force="20" IgnoreCover="true" DistanceFalloff="false" severlimbsprobability="2" debris="true" decal="explosion" decalsize="0.75">
</Explosion>
<Remove />
</StatusEffect>
<StatusEffect type="OnBroken" target="This">
<sound file="Content/Items/Weapons/ExplosionDebris5.ogg" range="6000" />
</StatusEffect>
</Throwable>
<Quality>
<QualityStat stattype="ExplosionRadius" value="0.1"/>
<QualityStat stattype="ExplosionDamage" value="0.1"/>
</Quality>
</Item>
</Items>
Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

@@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<contentpackage name="Explosion Test" modversion="1.0.1" corepackage="False" gameversion="1.11.5.0">
<Item file="%ModDir%/Items.xml" />
<Submarine file="%ModDir%/TestCamel.sub" />
</contentpackage>
-11
View File
@@ -1,11 +0,0 @@
{
"version": "0.2.0",
"configurations": [
{
"name": "MoonSharp Attach",
"type": "moonsharp-debug",
"debugServer": 41912,
"request": "attach"
}
]
}
-40
View File
@@ -1,40 +0,0 @@
{
"Lua.diagnostics.globals": [
"Game",
"Player",
"Random",
"Hook",
"Timer",
"bit32",
"TotalTime",
"DoFile",
"WayPoint",
"SpawnType",
"Level",
"Submarine",
"Vector2",
"PositionType",
"ServerLog_MessageType",
"Character",
"TraitorMessageType",
"ChatMessageType",
"CauseOfDeathType",
"CreateVector2",
"Item",
"ChatMessage",
"AfflictionPrefab",
"Gap",
"File",
"Networking",
"printNoLog",
"Client",
"SERVER",
"setmodulepaths",
"Type",
"BindingFlags",
"UserData",
"LuaUserData",
"CLIENT",
"ContentPackageManager"
]
}
@@ -1,97 +0,0 @@
-- Contains things to be removed later, they exist only for compatibility reasons.
local compatibilityLib = {}
local networking = LuaUserData.RegisterType("Barotrauma.LuaCsNetworking")
LuaUserData.AddMethod(networking, "RequestGetHTTP", Networking.HttpGet)
LuaUserData.AddMethod(networking, "RequestPostHTTP", Networking.HttpPost)
compatibilityLib.CreateVector2 = Vector2.__new
compatibilityLib.CreateVector3 = Vector3.__new
compatibilityLib.CreateVector4 = Vector4.__new
local luaRandom = {}
luaRandom.Range = function (min, max)
return math.random(min, max - 1)
end
luaRandom.RangeFloat = function (min, max)
return math.random() + math.random(min, max)
end
compatibilityLib["Random"] = luaRandom
local luaPlayer = {}
luaPlayer.GetAllCharacters = function ()
return Character.CharacterList
end
luaPlayer.GetAllClients = function ()
return Client.ClientList
end
luaPlayer.SetClientCharacter = function (client, character)
client.SetClientCharacter(character)
end
luaPlayer.SetCharacterTeam = function (character, team)
character.TeamID = team
end
luaPlayer.SetClientTeam = function (client, team)
client.TeamID = team
end
luaPlayer.Kick = function (client, reason)
client.Kick(reason)
end
luaPlayer.Ban = function (client, reason, range, seconds)
client.Ban(reason, range, seconds)
end
luaPlayer.UnbanPlayer = function (player, endpoint)
Client.Unban(player, endpoint)
end
luaPlayer.SetSpectatorPos = function ()
end
luaPlayer.SetRadioRange = function (character, range)
if (character.Inventory == nil) then return end
for item in character.Inventory.AllItems do
if item ~= nil and item.Prefab.Identifier == "headset" then
item.GetComponentString("WifiComponent").Range = range;
end
end
end
luaPlayer.CheckPermission = function (client, permissions)
return client.CheckPermission(permissions)
end
compatibilityLib["Player"] = luaPlayer
Hook.Add("character.created", "compatibility.character.created", function (character)
Hook.Call("characterCreated", character)
end)
Hook.Add("character.death", "compatibility.character.death", function (character, causeOfDeathAffliction)
Hook.Call("characterDeath", character, causeOfDeathAffliction)
end)
Hook.Add("client.connected", "compatibility.client.connected", function (client)
Hook.Call("clientConnected", client)
end)
Hook.Add("client.disconnected", "compatibility.client.disconnected", function (client)
Hook.Call("clientDisconnected", client)
end)
return compatibilityLib
@@ -1,68 +0,0 @@
Hook.Patch("Barotrauma.Item", "TryInteract",
{
"Barotrauma.Character",
"System.Boolean",
"System.Boolean",
"System.Boolean"
},
function(instance, p)
if Hook.Call("item.interact", instance, p["user"], p["ignoreRequiredItems"], p["forceSelectKey"], p["forceUseKey"]) == true then
p.PreventExecution = true
return false
end
end, Hook.HookMethodType.Before)
Hook.Patch("Barotrauma.Item", "ApplyTreatment",
{
"Barotrauma.Character",
"Barotrauma.Character",
"Barotrauma.Limb"
},
function(instance, p)
if Hook.Call("item.applyTreatment", instance, p["user"], p["character"], p["targetLimb"]) then
p.PreventExecution = true
return false
end
end, Hook.HookMethodType.Before)
Hook.Patch("Barotrauma.Item", "Combine",
{
"Barotrauma.Item",
"Barotrauma.Character"
},
function(instance, p)
if Hook.Call("item.combine", instance, p["item"], p["user"]) == true then
p.PreventExecution = true
return false
end
end, Hook.HookMethodType.Before)
Hook.Patch("Barotrauma.Item", "Drop",
function(instance, p)
if Hook.Call("item.drop", instance, p["dropper"]) == true then
p.PreventExecution = true
return false
end
end, Hook.HookMethodType.Before)
Hook.Patch("Barotrauma.Item", "Equip",
{
"Barotrauma.Character"
},
function(instance, p)
if Hook.Call("item.equip", instance, p["character"]) == true then
p.PreventExecution = true
return false
end
end, Hook.HookMethodType.Before)
Hook.Patch("Barotrauma.Item", "Unequip",
{
"Barotrauma.Character"
},
function(instance, p)
if Hook.Call("item.unequip", instance, p["character"]) == true then
p.PreventExecution = true
return false
end
end, Hook.HookMethodType.Before)
@@ -1,91 +0,0 @@
local defaultLib = {}
local CreateStatic = LuaSetup.LuaUserData.CreateStatic
local CreateEnum = LuaSetup.LuaUserData.CreateEnumTable
local AddCallMetaTable = LuaSetup.LuaUserData.AddCallMetaTable
local localizedStrings = {
"LocalizedString", "LimitLString", "WrappedLString", "AddedPunctuationLString", "CapitalizeLString", "ConcatLString", "FallbackLString", "FormattedLString", "InputTypeLString", "JoinLString", "LowerLString", "RawLString", "ReplaceLString", "ServerMsgLString", "SplitLString", "TagLString", "TrimLString", "UpperLString", "StripRichTagsLString",
}
for key, value in pairs(localizedStrings) do
defaultLib[value] = CreateStatic("Barotrauma." .. value, true)
end
local sounds = {}
sounds.LowpassFilter = CreateStatic("Barotrauma.Sounds.LowpassFilter")
sounds.HighpassFilter = CreateStatic("Barotrauma.Sounds.HighpassFilter")
sounds.BandpassFilter = CreateStatic("Barotrauma.Sounds.BandpassFilter")
sounds.NotchFilter = CreateStatic("Barotrauma.Sounds.NotchFilter")
sounds.LowShelfFilter = CreateStatic("Barotrauma.Sounds.LowShelfFilter")
sounds.HighShelfFilter = CreateStatic("Barotrauma.Sounds.HighShelfFilter")
sounds.PeakFilter = CreateStatic("Barotrauma.Sounds.PeakFilter")
defaultLib["Sounds"] = sounds
defaultLib["SpriteEffects"] = CreateStatic("Microsoft.Xna.Framework.Graphics.SpriteEffects")
defaultLib["SoundPlayer"] = CreateStatic("Barotrauma.SoundPlayer")
defaultLib["SoundPrefab"] = CreateStatic("Barotrauma.SoundPrefab", true)
defaultLib["BackgroundMusic"] = CreateStatic("Barotrauma.BackgroundMusic", true)
defaultLib["GUISound"] = CreateStatic("Barotrauma.GUISound", true)
defaultLib["DamageSound"] = CreateStatic("Barotrauma.DamageSound", true)
defaultLib["WaterRenderer"] = CreateStatic("Barotrauma.WaterRenderer", true)
defaultLib["TextureLoader"] = CreateStatic("Barotrauma.TextureLoader")
defaultLib["Sprite"] = CreateStatic("Barotrauma.Sprite", true)
defaultLib["PlayerInput"] = CreateStatic("Barotrauma.PlayerInput", true)
defaultLib["Keys"] = CreateStatic("Microsoft.Xna.Framework.Input.Keys", true)
defaultLib["GUI"] = {
GUI = CreateStatic("Barotrauma.GUI", true),
Style = CreateStatic("Barotrauma.GUIStyle", true),
Component = CreateStatic("Barotrauma.GUIComponent"),
RectTransform = CreateStatic("Barotrauma.RectTransform", true),
LayoutGroup = CreateStatic("Barotrauma.GUILayoutGroup", true),
Button = CreateStatic("Barotrauma.GUIButton", true),
TextBox = CreateStatic("Barotrauma.GUITextBox", true),
Canvas = CreateStatic("Barotrauma.GUICanvas", true),
Frame = CreateStatic("Barotrauma.GUIFrame", true),
TextBlock = CreateStatic("Barotrauma.GUITextBlock", true),
TickBox = CreateStatic("Barotrauma.GUITickBox", true),
Image = CreateStatic("Barotrauma.GUIImage", true),
ListBox = CreateStatic("Barotrauma.GUIListBox", true),
ScrollBar = CreateStatic("Barotrauma.GUIScrollBar", true),
DropDown = CreateStatic("Barotrauma.GUIDropDown", true),
NumberInput = CreateStatic("Barotrauma.GUINumberInput", true),
MessageBox = CreateStatic("Barotrauma.GUIMessageBox", true),
ColorPicker = CreateStatic("Barotrauma.GUIColorPicker", true),
ProgressBar = CreateStatic("Barotrauma.GUIProgressBar", true),
CustomComponent = CreateStatic("Barotrauma.GUICustomComponent", true),
ScissorComponent = CreateStatic("Barotrauma.GUIScissorComponent", true),
VideoPlayer = CreateStatic("Barotrauma.VideoPlayer", true),
Graph = CreateStatic("Barotrauma.Graph", true),
SerializableEntityEditor = CreateStatic("Barotrauma.SerializableEntityEditor", true),
SlideshowPlayer = CreateStatic("Barotrauma.SlideshowPlayer", true),
CreditsPlayer = CreateStatic("Barotrauma.CreditsPlayer", true),
DragHandle = CreateStatic("Barotrauma.GUIDragHandle", true),
ContextMenu = CreateStatic("Barotrauma.GUIContextMenu", true),
ContextMenuOption = CreateStatic("Barotrauma.ContextMenuOption", true),
Screen = CreateStatic("Barotrauma.Screen"),
Anchor = CreateStatic("Barotrauma.Anchor"),
Alignment = CreateStatic("Barotrauma.Alignment"),
Pivot = CreateStatic("Barotrauma.Pivot"),
SoundType = CreateEnum("Barotrauma.GUISoundType"),
CursorState = CreateEnum("Barotrauma.CursorState"),
GUIStyle = CreateStatic("Barotrauma.GUIStyle", true),
}
setmetatable(defaultLib["GUI"], {
__index = function (table, key)
return defaultLib["GUI"].GUI[key]
end
})
AddCallMetaTable(defaultLib["GUI"].VideoPlayer.VideoSettings)
AddCallMetaTable(defaultLib["GUI"].VideoPlayer.TextSettings)
return defaultLib
@@ -1,14 +0,0 @@
local defaultLib = {}
local CreateStatic = LuaSetup.LuaUserData.CreateStatic
local CreateEnum = LuaSetup.LuaUserData.CreateEnumTable
local localizedStrings = {
"LocalizedString", "AddedPunctuationLString", "CapitalizeLString", "ConcatLString", "FallbackLString", "FormattedLString", "InputTypeLString", "JoinLString", "LowerLString", "RawLString", "ReplaceLString", "ServerMsgLString", "SplitLString", "TagLString", "TrimLString", "UpperLString", "StripRichTagsLString",
}
for key, value in pairs(localizedStrings) do
defaultLib[value] = CreateStatic("Barotrauma." .. value, true)
end
return defaultLib
@@ -1,195 +0,0 @@
local defaultLib = {}
local AddCallMetaTable = LuaSetup.LuaUserData.AddCallMetaTable
local CreateStatic = LuaSetup.LuaUserData.CreateStatic
local CreateEnum = LuaSetup.LuaUserData.CreateEnumTable
defaultLib["SByte"] = CreateStatic("Barotrauma.LuaSByte", true)
defaultLib["Byte"] = CreateStatic("Barotrauma.LuaByte", true)
defaultLib["Int16"] = CreateStatic("Barotrauma.LuaInt16", true)
defaultLib["UInt16"] = CreateStatic("Barotrauma.LuaUInt16", true)
defaultLib["Int32"] = CreateStatic("Barotrauma.LuaInt32", true)
defaultLib["UInt32"] = CreateStatic("Barotrauma.LuaUInt32", true)
defaultLib["Int64"] = CreateStatic("Barotrauma.LuaInt64", true)
defaultLib["UInt64"] = CreateStatic("Barotrauma.LuaUInt64", true)
defaultLib["Single"] = CreateStatic("Barotrauma.LuaSingle", true)
defaultLib["Double"] = CreateStatic("Barotrauma.LuaDouble", true)
-- Backward compatibility
defaultLib["Float"] = CreateStatic("Barotrauma.LuaSingle", true)
defaultLib["Short"] = CreateStatic("Barotrauma.LuaInt16", true)
defaultLib["UShort"] = CreateStatic("Barotrauma.LuaUInt16", true)
defaultLib["SpawnType"] = CreateEnum("Barotrauma.SpawnType")
defaultLib["ChatMessageType"] = CreateEnum("Barotrauma.Networking.ChatMessageType")
defaultLib["ServerLog_MessageType"] = CreateEnum("Barotrauma.Networking.ServerLog+MessageType")
defaultLib["ServerLogMessageType"] = CreateEnum("Barotrauma.Networking.ServerLog+MessageType")
defaultLib["PositionType"] = CreateEnum("Barotrauma.Level+PositionType")
defaultLib["InvSlotType"] = CreateEnum("Barotrauma.InvSlotType")
defaultLib["LimbType"] = CreateEnum("Barotrauma.LimbType")
defaultLib["ActionType"] = CreateEnum("Barotrauma.ActionType")
defaultLib["AbilityEffectType"] = CreateEnum("Barotrauma.AbilityEffectType")
defaultLib["StatTypes"] = CreateEnum("Barotrauma.StatTypes")
defaultLib["AbilityFlags"] = CreateEnum("Barotrauma.AbilityFlags")
defaultLib["DeliveryMethod"] = CreateEnum("Barotrauma.Networking.DeliveryMethod")
defaultLib["ClientPacketHeader"] = CreateEnum("Barotrauma.Networking.ClientPacketHeader")
defaultLib["ServerPacketHeader"] = CreateEnum("Barotrauma.Networking.ServerPacketHeader")
defaultLib["RandSync"] = CreateEnum("Barotrauma.Rand+RandSync")
defaultLib["DisconnectReason"] = CreateEnum("Barotrauma.Networking.DisconnectReason")
defaultLib["CombatMode"] = CreateEnum("Barotrauma.AIObjectiveCombat+CombatMode")
defaultLib["CauseOfDeathType"] = CreateEnum("Barotrauma.CauseOfDeathType")
defaultLib["CharacterTeamType"] = CreateEnum("Barotrauma.CharacterTeamType")
defaultLib["ClientPermissions"] = CreateEnum("Barotrauma.Networking.ClientPermissions")
defaultLib["OrderCategory"] = CreateEnum("Barotrauma.OrderCategory")
defaultLib["WearableType"] = CreateEnum("Barotrauma.WearableType")
defaultLib["NumberType"] = CreateEnum("Barotrauma.NumberType")
defaultLib["ChatMode"] = CreateEnum("Barotrauma.ChatMode")
defaultLib["CharacterType"] = CreateEnum("Barotrauma.CharacterType")
defaultLib["VoteType"] = CreateEnum("Barotrauma.Networking.VoteType")
defaultLib["CanEnterSubmarine"] = CreateEnum("Barotrauma.CanEnterSubmarine")
defaultLib["InputType"] = CreateStatic("Barotrauma.InputType")
defaultLib["EventPrefab"] = CreateStatic("Barotrauma.EventPrefab", true)
defaultLib["TraitorEventPrefab"] = CreateStatic("Barotrauma.TraitorEventPrefab", true)
defaultLib["TraitorEvent"] = CreateStatic("Barotrauma.TraitorEvent", true)
defaultLib["EventSet"] = CreateStatic("Barotrauma.EventSet", true)
defaultLib["EventManagerSettings"] = CreateStatic("Barotrauma.EventManagerSettings", true)
defaultLib["NetConfig"] = CreateStatic("Barotrauma.Networking.NetConfig")
defaultLib["NetworkConnection"] = CreateStatic("Barotrauma.Networking.NetworkConnection")
defaultLib["Inventory"] = CreateStatic("Barotrauma.Inventory", true)
defaultLib["CharacterInventory"] = CreateStatic("Barotrauma.CharacterInventory", true)
defaultLib["ItemInventory"] = CreateStatic("Barotrauma.ItemInventory", true)
defaultLib["ContentPackageManager"] = CreateStatic("Barotrauma.ContentPackageManager")
defaultLib["GameSettings"] = CreateStatic("Barotrauma.GameSettings")
defaultLib["RichString"] = CreateStatic("Barotrauma.RichString", true)
defaultLib["Identifier"] = CreateStatic("Barotrauma.Identifier", true)
defaultLib["LanguageIdentifier"] = CreateStatic("Barotrauma.LanguageIdentifier", true)
defaultLib["ContentPackage"] = CreateStatic("Barotrauma.ContentPackage", true)
defaultLib["WayPoint"] = CreateStatic("Barotrauma.WayPoint", true)
defaultLib["Submarine"] = CreateStatic("Barotrauma.Submarine", true)
defaultLib["Client"] = CreateStatic("Barotrauma.Networking.Client", true)
defaultLib["Character"] = CreateStatic("Barotrauma.Character")
defaultLib["CharacterHealth"] = CreateStatic("Barotrauma.CharacterHealth", true)
defaultLib["CharacterPrefab"] = CreateStatic("Barotrauma.CharacterPrefab", true)
defaultLib["CharacterInfo"] = CreateStatic("Barotrauma.CharacterInfo", true)
AddCallMetaTable(defaultLib["CharacterInfo"].HeadPreset)
AddCallMetaTable(defaultLib["CharacterInfo"].HeadInfo)
defaultLib["CharacterInfoPrefab"] = CreateStatic("Barotrauma.CharacterInfoPrefab")
defaultLib["Item"] = CreateStatic("Barotrauma.Item", true)
AddCallMetaTable(defaultLib["Item"].ChangePropertyEventData)
defaultLib["MapEntityPrefab"] = CreateStatic("Barotrauma.MapEntityPrefab")
defaultLib["ItemPrefab"] = CreateStatic("Barotrauma.ItemPrefab", true)
defaultLib["TalentTree"] = CreateStatic("Barotrauma.TalentTree", true)
defaultLib["TalentPrefab"] = CreateStatic("Barotrauma.TalentPrefab", true)
defaultLib["FactionPrefab"] = CreateStatic("Barotrauma.FactionPrefab", true)
defaultLib["MissionPrefab"] = CreateStatic("Barotrauma.MissionPrefab", true)
defaultLib["Mission"] = CreateStatic("Barotrauma.Mission", true)
defaultLib["Level"] = CreateStatic("Barotrauma.Level")
defaultLib["LevelGenerationParams"] = CreateStatic("Barotrauma.LevelGenerationParams", true)
defaultLib["OutpostGenerationParams"] = CreateStatic("Barotrauma.OutpostGenerationParams", true)
defaultLib["RuinGenerationParams"] = CreateStatic("Barotrauma.RuinGeneration.RuinGenerationParams", true)
defaultLib["Job"] = CreateStatic("Barotrauma.Job", true)
defaultLib["JobPrefab"] = CreateStatic("Barotrauma.JobPrefab", true)
defaultLib["JobVariant"] = CreateStatic("Barotrauma.JobVariant", true)
defaultLib["AfflictionPrefab"] = CreateStatic("Barotrauma.AfflictionPrefab", true)
defaultLib["SkillSettings"] = CreateStatic("Barotrauma.SkillSettings", true)
defaultLib["ChatMessage"] = CreateStatic("Barotrauma.Networking.ChatMessage")
defaultLib["Structure"] = CreateStatic("Barotrauma.Structure", true)
defaultLib["Hull"] = CreateStatic("Barotrauma.Hull", true)
defaultLib["Gap"] = CreateStatic("Barotrauma.Gap", true)
defaultLib["Signal"] = CreateStatic("Barotrauma.Items.Components.Signal", true)
defaultLib["SubmarineInfo"] = CreateStatic("Barotrauma.SubmarineInfo", true)
defaultLib["Entity"] = CreateStatic("Barotrauma.Entity", true)
defaultLib["MapEntity"] = CreateStatic("Barotrauma.MapEntity", true)
defaultLib["Physics"] = CreateStatic("Barotrauma.Physics")
defaultLib["FireSource"] = CreateStatic("Barotrauma.FireSource", true)
defaultLib["TextManager"] = CreateStatic("Barotrauma.TextManager")
defaultLib["NetEntityEvent"] = CreateStatic("Barotrauma.Networking.NetEntityEvent")
defaultLib["Screen"] = CreateStatic("Barotrauma.Screen")
defaultLib["AttackResult"] = CreateStatic("Barotrauma.AttackResult", true)
defaultLib["TempClient"] = CreateStatic("Barotrauma.Networking.TempClient", true)
defaultLib["DecalManager"] = CreateStatic("Barotrauma.DecalManager", true)
defaultLib["AutoItemPlacer"] = CreateStatic("Barotrauma.AutoItemPlacer")
defaultLib["PropertyConditional"] = CreateStatic("Barotrauma.PropertyConditional", true)
defaultLib["StatusEffect"] = CreateStatic("Barotrauma.StatusEffect", true)
defaultLib["OutpostGenerator"] = CreateStatic("Barotrauma.OutpostGenerator")
defaultLib["DamageModifier"] = CreateStatic("Barotrauma.DamageModifier", true)
defaultLib["TraitorManager"] = CreateStatic("Barotrauma.TraitorManager", true)
AddCallMetaTable(defaultLib["TraitorManager"].TraitorResults)
defaultLib["Md5Hash"] = CreateStatic("Barotrauma.Md5Hash", true)
defaultLib["ContentXElement"] = CreateStatic("Barotrauma.ContentXElement", true)
defaultLib["ContentPath"] = CreateStatic("Barotrauma.ContentPath", true)
defaultLib["XElement"] = CreateStatic("System.Xml.Linq.XElement", true)
defaultLib["XName"] = CreateStatic("System.Xml.Linq.XName", true)
defaultLib["XAttribute"] = CreateStatic("System.Xml.Linq.XAttribute", true)
defaultLib["XContainer"] = CreateStatic("System.Xml.Linq.XContainer", true)
defaultLib["XDocument"] = CreateStatic("System.Xml.Linq.XDocument", true)
defaultLib["XNode"] = CreateStatic("System.Xml.Linq.XNode", true)
defaultLib["SoundsFile"] = CreateStatic("Barotrauma.SoundsFile", true)
defaultLib["Voting"] = CreateStatic("Barotrauma.Voting")
defaultLib["TimeSpan"] = CreateStatic("System.TimeSpan")
defaultLib["IPAddress"] = CreateStatic("System.Net.IPAddress")
defaultLib["ContentPackageId"] = CreateStatic("Barotrauma.ContentPackageId")
defaultLib["Address"] = CreateStatic("Barotrauma.Networking.Address")
defaultLib["AccountId"] = CreateStatic("Barotrauma.Networking.AccountId")
defaultLib["Endpoint"] = CreateStatic("Barotrauma.Networking.Endpoint")
defaultLib["Explosion"] = CreateStatic("Barotrauma.Explosion", true)
defaultLib["ConvertUnits"] = CreateStatic("FarseerPhysics.ConvertUnits")
defaultLib["ToolBox"] = CreateStatic("Barotrauma.ToolBox")
defaultLib["AIObjective"] = CreateStatic("Barotrauma.AIObjective", true)
defaultLib["AIObjectiveChargeBatteries"] = CreateStatic("Barotrauma.AIObjectiveChargeBatteries", true)
defaultLib["AIObjectiveCleanupItem"] = CreateStatic("Barotrauma.AIObjectiveCleanupItem", true)
defaultLib["AIObjectiveCleanupItems"] = CreateStatic("Barotrauma.AIObjectiveCleanupItems", true)
defaultLib["AIObjectiveCombat"] = CreateStatic("Barotrauma.AIObjectiveCombat", true)
defaultLib["AIObjectiveContainItem"] = CreateStatic("Barotrauma.AIObjectiveContainItem", true)
defaultLib["AIObjectiveDeconstructItem"] = CreateStatic("Barotrauma.AIObjectiveDeconstructItem", true)
defaultLib["AIObjectiveDeconstructItems"] = CreateStatic("Barotrauma.AIObjectiveDeconstructItems", true)
defaultLib["AIObjectiveEscapeHandcuffs"] = CreateStatic("Barotrauma.AIObjectiveEscapeHandcuffs", true)
defaultLib["AIObjectiveExtinguishFire"] = CreateStatic("Barotrauma.AIObjectiveExtinguishFire", true)
defaultLib["AIObjectiveExtinguishFires"] = CreateStatic("Barotrauma.AIObjectiveExtinguishFires", true)
defaultLib["AIObjectiveFightIntruders"] = CreateStatic("Barotrauma.AIObjectiveFightIntruders", true)
defaultLib["AIObjectiveFindDivingGear"] = CreateStatic("Barotrauma.AIObjectiveFindDivingGear", true)
defaultLib["AIObjectiveFindSafety"] = CreateStatic("Barotrauma.AIObjectiveFindSafety", true)
defaultLib["AIObjectiveFixLeak"] = CreateStatic("Barotrauma.AIObjectiveFixLeak", true)
defaultLib["AIObjectiveFixLeaks"] = CreateStatic("Barotrauma.AIObjectiveFixLeaks", true)
defaultLib["AIObjectiveGetItem"] = CreateStatic("Barotrauma.AIObjectiveGetItem", true)
defaultLib["AIObjectiveGoTo"] = CreateStatic("Barotrauma.AIObjectiveGoTo", true)
defaultLib["AIObjectiveIdle"] = CreateStatic("Barotrauma.AIObjectiveIdle", true)
defaultLib["AIObjectiveOperateItem"] = CreateStatic("Barotrauma.AIObjectiveOperateItem", true)
defaultLib["AIObjectiveOperateItem"] = CreateStatic("Barotrauma.AIObjectiveOperateItem", true)
defaultLib["AIObjectivePumpWater"] = CreateStatic("Barotrauma.AIObjectivePumpWater", true)
defaultLib["AIObjectiveRepairItem"] = CreateStatic("Barotrauma.AIObjectiveRepairItem", true)
defaultLib["AIObjectiveRepairItems"] = CreateStatic("Barotrauma.AIObjectiveRepairItems", true)
defaultLib["AIObjectiveRescue"] = CreateStatic("Barotrauma.AIObjectiveRescue", true)
defaultLib["AIObjectiveRescueAll"] = CreateStatic("Barotrauma.AIObjectiveRescueAll", true)
defaultLib["AIObjectiveReturn"] = CreateStatic("Barotrauma.AIObjectiveReturn", true)
defaultLib["AITarget"] = CreateStatic("Barotrauma.AITarget", true)
defaultLib["Order"] = CreateStatic("Barotrauma.Order", true)
defaultLib["OrderPrefab"] = CreateStatic("Barotrauma.OrderPrefab", true)
defaultLib["OrderTarget"] = CreateStatic("Barotrauma.OrderTarget", true)
local componentsToReference = { "DockingPort", "Door", "GeneticMaterial", "Growable", "Holdable", "LevelResource", "ItemComponent", "ItemLabel", "LightComponent", "Controller", "Deconstructor", "Engine", "Fabricator", "OutpostTerminal", "Pump", "Reactor", "Steering", "PowerContainer", "Projectile", "Repairable", "Rope", "Scanner", "ButtonTerminal", "ConnectionPanel", "CustomInterface", "MemoryComponent", "Terminal", "WifiComponent", "Wire", "TriggerComponent", "ElectricalDischarger", "EntitySpawnerComponent", "ProducedItem", "VineTile", "GrowthSideExtension", "IdCard", "MeleeWeapon", "Pickable", "Propulsion", "RangedWeapon", "RepairTool", "Sprayer", "Throwable", "ItemContainer", "Ladder", "LimbPos", "MiniMap", "OxygenGenerator", "Sonar", "SonarTransducer", "Vent", "NameTag", "Planter", "Powered", "PowerTransfer", "Quality", "RemoteController", "AdderComponent", "AndComponent", "ArithmeticComponent", "ColorComponent", "ConcatComponent", "Connection", "DelayComponent", "DivideComponent", "EqualsComponent", "ExponentiationComponent", "FunctionComponent", "GreaterComponent", "ModuloComponent", "MotionSensor", "MultiplyComponent", "NotComponent", "OrComponent", "OscillatorComponent", "OxygenDetector", "RegExFindComponent", "RelayComponent", "SignalCheckComponent", "SmokeDetector", "StringComponent", "SubtractComponent", "TrigonometricFunctionComponent", "WaterDetector", "XorComponent", "StatusHUD", "Turret", "Wearable", "CustomInterface"
}
defaultLib["Components"] = {}
for key, value in pairs(componentsToReference) do
defaultLib["Components"][value] = CreateStatic("Barotrauma.Items.Components." .. value, true)
end
defaultLib["Vector2"] = CreateStatic("Microsoft.Xna.Framework.Vector2", true)
defaultLib["Vector3"] = CreateStatic("Microsoft.Xna.Framework.Vector3", true)
defaultLib["Vector4"] = CreateStatic("Microsoft.Xna.Framework.Vector4", true)
defaultLib["Color"] = CreateStatic("Microsoft.Xna.Framework.Color", true)
defaultLib["Point"] = CreateStatic("Microsoft.Xna.Framework.Point", true)
defaultLib["Rectangle"] = CreateStatic("Microsoft.Xna.Framework.Rectangle", true)
defaultLib["Matrix"] = CreateStatic("Microsoft.Xna.Framework.Matrix", true)
return defaultLib
@@ -1,40 +0,0 @@
math.lerp = function (a, b, t)
if type(a) ~= "number" then error(string.format("bad argument #1 to 'lerp' (number expected, got %s)", type(a)), 2) end
if type(b) ~= "number" then error(string.format("bad argument #2 to 'lerp' (number expected, got %s)", type(b)), 2) end
if type(t) ~= "number" then error(string.format("bad argument #3 to 'lerp' (number expected, got %s)", type(t)), 2) end
return a * (1 - t) + b * t
end
math.clamp = function (value, min, max)
if type(value) ~= "number" then error(string.format("bad argument #1 to 'clamp' (number expected, got %s)", type(value)), 2) end
if type(min) ~= "number" then error(string.format("bad argument #2 to 'clamp' (number expected, got %s)", type(min)), 2) end
if type(max) ~= "number" then error(string.format("bad argument #3 to 'clamp' (number expected, got %s)", type(max)), 2) end
return math.max(min, math.min(max, value))
end
math.round = function (value, decimals)
if type(value) ~= "number" then error(string.format("bad argument #1 to 'round' (number expected, got %s)", type(value)), 2) end
if type(decimals) ~= "number" then error(string.format("bad argument #2 to 'round' (number expected, got %s)", type(decimals)), 2) end
decimals = decimals or 0
local mult = 10 ^ decimals
return math.floor(value * mult + 0.5) / mult
end
math.sign = function (value)
if type(value) ~= "number" then error(string.format("bad argument #1 to 'sign' (number expected, got %s)", type(value)), 2) end
return value >= 0 and 1 or -1
end
math.remap = function (value, inMin, inMax, outMin, outMax)
if type(value) ~= "number" then error(string.format("bad argument #1 to 'remap' (number expected, got %s)", type(value)), 2) end
if type(inMin) ~= "number" then error(string.format("bad argument #2 to 'remap' (number expected, got %s)", type(inMin)), 2) end
if type(inMax) ~= "number" then error(string.format("bad argument #3 to 'remap' (number expected, got %s)", type(inMax)), 2) end
if type(outMin) ~= "number" then error(string.format("bad argument #4 to 'remap' (number expected, got %s)", type(outMin)), 2) end
if type(outMax) ~= "number" then error(string.format("bad argument #5 to 'remap' (number expected, got %s)", type(outMax)), 2) end
return outMin + (outMax - outMin) * ((value - inMin) / (inMax - inMin))
end
@@ -1,26 +0,0 @@
local descriptor = LuaUserData.RegisterType("Barotrauma.LuaCsSteam")
LuaUserData.AddMethod(descriptor, "GetWorkshopCollection", function (id, callback)
id = tostring(id)
Networking.RequestPostHTTP("https://api.steampowered.com/ISteamRemoteStorage/GetCollectionDetails/v1/", function (result)
local data = json.parse(result)
if data.response.collectiondetails[1].children == nil then
callback()
return
end
local workshopItems = {}
for key, value in pairs(data.response.collectiondetails[1].children) do
table.insert(workshopItems, value.publishedfileid)
end
if callback then
callback(workshopItems)
end
end,
"collectioncount=1&publishedfileids[0]=" .. id,
"application/x-www-form-urlencoded")
end)
@@ -1,13 +0,0 @@
string.startsWith = function(str, start)
if type(str) ~= "string" then error(string.format("bad argument #1 to 'startsWith' (string expected, got %s)", type(str)), 2) end
if type(start) ~= "string" then error(string.format("bad argument #2 to 'startsWith' (string expected, got %s)", type(start)), 2) end
return string.sub(str, 1, string.len(start)) == start
end
string.endsWith = function(str, ending)
if type(str) ~= "string" then error(string.format("bad argument #1 to 'endsWith' (string expected, got %s)", type(str)), 2) end
if type(ending) ~= "string" then error(string.format("bad argument #2 to 'endsWith' (string expected, got %s)", type(ending)), 2) end
return ending == "" or string.sub(str, -string.len(ending)) == ending
end
@@ -1,86 +0,0 @@
Util = {}
local itemDictionary = {}
local itemGroups = {}
local function AddItem(item)
for _, itemGroup in pairs(itemGroups) do
if itemGroup.func(item) then
table.insert(itemGroup.items, item)
end
end
local id = item.Prefab.Identifier.Value
if itemDictionary[id] == nil then
itemDictionary[id] = {}
end
table.insert(itemDictionary[id], item)
end
Hook.Add("item.created", "luaSetup.util.itemDictionary", function (item)
AddItem(item)
end)
Hook.Add("roundEnd", "luaSetup.util.itemDictionary", function (item)
itemDictionary = {}
for _, itemGroup in pairs(itemGroups) do
itemGroup.items = {}
end
end)
for _, item in pairs(Item.ItemList) do
AddItem(item)
end
Util.RegisterItemGroup = function(groupName, func)
if type(groupName) ~= "string" then
error(string.format("bad argument #1 to 'RegisterItemGroup' (string expected, got %s)", type(groupName)), 2)
end
if type(func) ~= "function" then
error(string.format("bad argument #2 to 'RegisterItemGroup' (function expected, got %s)", type(func)), 2)
end
local items = {}
for _, item in pairs(Item.ItemList) do
if func(item) then
table.insert(items, item)
end
end
itemGroups[groupName] = {
func = func,
items = items
}
end
Util.GetItemGroup = function(groupName)
if type(groupName) ~= "string" then
error(string.format("bad argument #1 to 'GetItemGroup' (string expected, got %s)", type(groupName)), 2)
end
if not itemGroups[groupName] then
error("bad argument #1 to 'GetItemGroup' couldn't find the specified groupName", 2)
end
return itemGroups[groupName].items or {}
end
Util.GetItemsById = function(id)
if id == nil then
error(string.format("bad argument #1 to 'GetItemsById' (string expected, got %s)", type(id)), 2)
end
return itemDictionary[id]
end
Util.FindClientCharacter = function(character)
if CLIENT and Game.IsSingleplayer then return nil end
for _, client in pairs(Client.ClientList) do
if client.Character == character then
return client
end
end
end
@@ -1,150 +0,0 @@
local Register = LuaSetup.LuaUserData.RegisterType
local RegisterBarotrauma = LuaSetup.LuaUserData.RegisterTypeBarotrauma
local localizedStrings = {
"LocalizedString", "LimitLString", "WrappedLString", "AddedPunctuationLString", "CapitalizeLString", "ConcatLString", "FallbackLString", "FormattedLString", "InputTypeLString", "JoinLString", "LowerLString", "RawLString", "ReplaceLString", "ServerMsgLString", "SplitLString", "TagLString", "TrimLString", "UpperLString", "StripRichTagsLString",
}
for key, value in pairs(localizedStrings) do
RegisterBarotrauma(value)
end
RegisterBarotrauma("EditorScreen")
RegisterBarotrauma("SubEditorScreen")
RegisterBarotrauma("EventEditorScreen")
RegisterBarotrauma("CharacterEditor.CharacterEditorScreen")
RegisterBarotrauma("SpriteEditorScreen")
RegisterBarotrauma("LevelEditorScreen")
RegisterBarotrauma("Networking.ClientPeer")
RegisterBarotrauma("Networking.GameClient")
RegisterBarotrauma("Networking.VoipCapture")
RegisterBarotrauma("Media.Video")
RegisterBarotrauma("SoundsFile")
RegisterBarotrauma("SoundPrefab")
RegisterBarotrauma("PrefabCollection`1")
RegisterBarotrauma("PrefabSelector`1")
RegisterBarotrauma("BackgroundMusic")
RegisterBarotrauma("GUISound")
RegisterBarotrauma("DamageSound")
RegisterBarotrauma("Sounds.SoundManager")
RegisterBarotrauma("Sounds.OggSound")
RegisterBarotrauma("Sounds.VideoSound")
RegisterBarotrauma("Sounds.VoipSound")
RegisterBarotrauma("Sounds.SoundChannel")
RegisterBarotrauma("Sounds.SoundBuffers")
RegisterBarotrauma("RoundSound")
RegisterBarotrauma("CharacterSound")
RegisterBarotrauma("SoundPlayer")
RegisterBarotrauma("Items.Components.ItemSound")
RegisterBarotrauma("Sounds.LowpassFilter")
RegisterBarotrauma("Sounds.HighpassFilter")
RegisterBarotrauma("Sounds.BandpassFilter")
RegisterBarotrauma("Sounds.NotchFilter")
RegisterBarotrauma("Sounds.LowShelfFilter")
RegisterBarotrauma("Sounds.HighShelfFilter")
RegisterBarotrauma("Sounds.PeakFilter")
RegisterBarotrauma("Particles.ParticleManager")
RegisterBarotrauma("Particles.Particle")
RegisterBarotrauma("Particles.ParticleEmitterProperties")
RegisterBarotrauma("Particles.ParticleEmitter")
RegisterBarotrauma("Particles.ParticlePrefab")
RegisterBarotrauma("Lights.LightManager")
RegisterBarotrauma("Lights.LightSource")
RegisterBarotrauma("Lights.LightSourceParams")
RegisterBarotrauma("LevelWallVertexBuffer")
RegisterBarotrauma("LevelRenderer")
RegisterBarotrauma("WaterRenderer")
RegisterBarotrauma("WaterVertexData")
RegisterBarotrauma("ChatBox")
RegisterBarotrauma("GUICanvas")
RegisterBarotrauma("Anchor")
RegisterBarotrauma("Alignment")
RegisterBarotrauma("Pivot")
RegisterBarotrauma("Key")
RegisterBarotrauma("PlayerInput")
RegisterBarotrauma("ScalableFont")
Register("Microsoft.Xna.Framework.Graphics.Effect")
Register("Microsoft.Xna.Framework.Graphics.EffectParameterCollection")
Register("Microsoft.Xna.Framework.Graphics.EffectParameter")
Register("Microsoft.Xna.Framework.Graphics.SpriteBatch")
Register("Microsoft.Xna.Framework.Graphics.Texture2D")
Register("EventInput.KeyboardDispatcher")
Register("EventInput.KeyEventArgs")
Register("Microsoft.Xna.Framework.Input.Keys")
Register("Microsoft.Xna.Framework.Input.KeyboardState")
RegisterBarotrauma("TextureLoader")
RegisterBarotrauma("Sprite")
RegisterBarotrauma("GUI")
RegisterBarotrauma("GUIStyle")
RegisterBarotrauma("GUIComponent")
RegisterBarotrauma("GUILayoutGroup")
RegisterBarotrauma("GUITextBox")
RegisterBarotrauma("GUITextBlock")
RegisterBarotrauma("GUIButton")
RegisterBarotrauma("RectTransform")
RegisterBarotrauma("GUIFrame")
RegisterBarotrauma("GUITickBox")
RegisterBarotrauma("GUIImage")
RegisterBarotrauma("GUIListBox")
RegisterBarotrauma("GUIScrollBar")
RegisterBarotrauma("GUIDropDown")
RegisterBarotrauma("GUINumberInput")
RegisterBarotrauma("GUIMessage")
RegisterBarotrauma("GUIMessageBox")
RegisterBarotrauma("GUIColorPicker")
RegisterBarotrauma("GUIProgressBar")
RegisterBarotrauma("GUICustomComponent")
RegisterBarotrauma("GUIScissorComponent")
RegisterBarotrauma("GUIComponentStyle")
RegisterBarotrauma("GUIFontPrefab")
RegisterBarotrauma("GUIFont")
RegisterBarotrauma("GUISpritePrefab")
RegisterBarotrauma("GUISprite")
RegisterBarotrauma("GUISpriteSheetPrefab")
RegisterBarotrauma("GUISpriteSheet")
RegisterBarotrauma("GUICursorPrefab")
RegisterBarotrauma("GUICursor")
RegisterBarotrauma("GUIRadioButtonGroup")
RegisterBarotrauma("GUIDragHandle")
RegisterBarotrauma("GUIContextMenu")
RegisterBarotrauma("ContextMenuOption")
RegisterBarotrauma("VideoPlayer")
RegisterBarotrauma("CreditsPlayer")
RegisterBarotrauma("SlideshowPlayer")
RegisterBarotrauma("SerializableEntityEditor")
RegisterBarotrauma("CircuitBoxWireRenderer")
RegisterBarotrauma("CircuitBoxLabel")
RegisterBarotrauma("CircuitBoxMouseDragSnapshotHandler")
RegisterBarotrauma("CircuitBoxUI")
RegisterBarotrauma("SettingsMenu")
RegisterBarotrauma("TabMenu")
RegisterBarotrauma("Widget")
RegisterBarotrauma("UpgradeStore")
RegisterBarotrauma("VotingInterface")
RegisterBarotrauma("MedicalClinicUI")
RegisterBarotrauma("LoadingScreen")
RegisterBarotrauma("HUD")
RegisterBarotrauma("HUDLayoutSettings")
RegisterBarotrauma("HUDProgressBar")
RegisterBarotrauma("Graph")
RegisterBarotrauma("HRManagerUI")
RegisterBarotrauma("SubmarineSelection")
RegisterBarotrauma("Store")
RegisterBarotrauma("UISprite")
RegisterBarotrauma("ParamsEditor")
RegisterBarotrauma("Inventory+SlotReference")
RegisterBarotrauma("VisualSlot")
@@ -1,20 +0,0 @@
local Register = LuaSetup.LuaUserData.RegisterType
local RegisterBarotrauma = LuaSetup.LuaUserData.RegisterTypeBarotrauma
local localizedStrings = {
"LocalizedString", "AddedPunctuationLString", "CapitalizeLString", "ConcatLString", "FallbackLString", "FormattedLString", "InputTypeLString", "JoinLString", "LowerLString", "RawLString", "ReplaceLString", "ServerMsgLString", "SplitLString", "TagLString", "TrimLString", "UpperLString", "StripRichTagsLString",
}
for key, value in pairs(localizedStrings) do
RegisterBarotrauma(value)
end
Register("Steamworks.SteamServer")
RegisterBarotrauma("Character+TeamChangeEventData")
RegisterBarotrauma("Networking.GameServer")
RegisterBarotrauma("Networking.ServerPeer")
RegisterBarotrauma("Networking.FileSender")
@@ -1,479 +0,0 @@
local Register = LuaSetup.LuaUserData.RegisterType
local RegisterExtension = LuaSetup.LuaUserData.RegisterExtensionType
local RegisterBarotrauma = LuaSetup.LuaUserData.RegisterTypeBarotrauma
Register("System.TimeSpan")
Register("System.Exception")
Register("System.Console")
Register("System.Exception")
RegisterBarotrauma("Success`2")
RegisterBarotrauma("Failure`2")
RegisterBarotrauma("LuaSByte")
RegisterBarotrauma("LuaByte")
RegisterBarotrauma("LuaInt16")
RegisterBarotrauma("LuaUInt16")
RegisterBarotrauma("LuaInt32")
RegisterBarotrauma("LuaUInt32")
RegisterBarotrauma("LuaInt64")
RegisterBarotrauma("LuaUInt64")
RegisterBarotrauma("LuaSingle")
RegisterBarotrauma("LuaDouble")
RegisterBarotrauma("GameMain")
RegisterBarotrauma("Networking.BanList")
RegisterBarotrauma("Networking.BannedPlayer")
RegisterBarotrauma("Range`1")
RegisterBarotrauma("RichString")
RegisterBarotrauma("Identifier")
RegisterBarotrauma("LanguageIdentifier")
RegisterBarotrauma("Job")
RegisterBarotrauma("JobPrefab")
RegisterBarotrauma("JobVariant")
Register("Voronoi2.DoubleVector2")
Register("Voronoi2.Site")
Register("Voronoi2.Edge")
Register("Voronoi2.Halfedge")
Register("Voronoi2.VoronoiCell")
Register("Voronoi2.GraphEdge")
RegisterBarotrauma("WayPoint")
RegisterBarotrauma("Level")
RegisterBarotrauma("LevelData")
RegisterBarotrauma("Level+InterestingPosition")
RegisterBarotrauma("LevelGenerationParams")
RegisterBarotrauma("LevelObjectManager")
RegisterBarotrauma("LevelObject")
RegisterBarotrauma("LevelObjectPrefab")
RegisterBarotrauma("LevelTrigger")
RegisterBarotrauma("CaveGenerationParams")
RegisterBarotrauma("CaveGenerator")
RegisterBarotrauma("OutpostGenerationParams")
RegisterBarotrauma("OutpostGenerator")
RegisterBarotrauma("OutpostModuleInfo")
RegisterBarotrauma("BeaconStationInfo")
RegisterBarotrauma("NPCSet")
RegisterBarotrauma("RuinGeneration.Ruin")
RegisterBarotrauma("RuinGeneration.RuinGenerationParams")
RegisterBarotrauma("LevelWall")
RegisterBarotrauma("DestructibleLevelWall")
RegisterBarotrauma("Biome")
RegisterBarotrauma("Map")
RegisterBarotrauma("Networking.RespawnManager")
RegisterBarotrauma("Networking.RespawnManager+TeamSpecificState")
RegisterBarotrauma("Character")
RegisterBarotrauma("CharacterPrefab")
RegisterBarotrauma("CharacterInfo")
RegisterBarotrauma("CharacterInfoPrefab")
RegisterBarotrauma("CharacterInfo+HeadPreset")
RegisterBarotrauma("CharacterInfo+HeadInfo")
RegisterBarotrauma("CharacterHealth")
RegisterBarotrauma("CharacterHealth+LimbHealth")
RegisterBarotrauma("DamageModifier")
RegisterBarotrauma("CharacterInventory")
RegisterBarotrauma("CharacterParams")
RegisterBarotrauma("CharacterParams+AIParams")
RegisterBarotrauma("CharacterParams+TargetParams")
RegisterBarotrauma("CharacterParams+InventoryParams")
RegisterBarotrauma("CharacterParams+HealthParams")
RegisterBarotrauma("CharacterParams+ParticleParams")
RegisterBarotrauma("CharacterParams+SoundParams")
RegisterBarotrauma("SteeringManager")
RegisterBarotrauma("IndoorsSteeringManager")
RegisterBarotrauma("SteeringPath")
RegisterBarotrauma("CreatureMetrics")
RegisterBarotrauma("Item")
RegisterBarotrauma("DeconstructItem")
RegisterBarotrauma("PurchasedItem")
RegisterBarotrauma("PurchasedItemSwap")
RegisterBarotrauma("PurchasedUpgrade")
RegisterBarotrauma("SoldItem")
RegisterBarotrauma("StartItem")
RegisterBarotrauma("StartItemSet")
RegisterBarotrauma("RelatedItem")
RegisterBarotrauma("UpgradeManager")
RegisterBarotrauma("CargoManager")
RegisterBarotrauma("HireManager")
RegisterBarotrauma("FabricationRecipe")
RegisterBarotrauma("PreferredContainer")
RegisterBarotrauma("SwappableItem")
RegisterBarotrauma("FabricationRecipe+RequiredItemByIdentifier")
RegisterBarotrauma("FabricationRecipe+RequiredItemByTag")
RegisterBarotrauma("Submarine")
RegisterBarotrauma("Networking.AccountInfo")
RegisterBarotrauma("Networking.AccountId")
RegisterBarotrauma("Networking.SteamId")
RegisterBarotrauma("Networking.EpicAccountId")
RegisterBarotrauma("Networking.Address")
RegisterBarotrauma("Networking.UnknownAddress")
RegisterBarotrauma("Networking.P2PAddress")
RegisterBarotrauma("Networking.EosP2PAddress")
RegisterBarotrauma("Networking.SteamP2PAddress")
RegisterBarotrauma("Networking.PipeAddress")
RegisterBarotrauma("Networking.LidgrenAddress")
RegisterBarotrauma("Networking.Endpoint")
RegisterBarotrauma("Networking.SteamP2PEndpoint")
RegisterBarotrauma("Networking.PipeEndpoint")
RegisterBarotrauma("Networking.LidgrenEndpoint")
RegisterBarotrauma("INetSerializableStruct")
RegisterBarotrauma("Networking.Client")
RegisterBarotrauma("Networking.TempClient")
RegisterBarotrauma("Networking.NetworkConnection")
RegisterBarotrauma("Networking.LidgrenConnection")
RegisterBarotrauma("Networking.SteamP2PConnection")
RegisterBarotrauma("Networking.VoipQueue")
RegisterBarotrauma("Networking.ChatMessage")
RegisterBarotrauma("AnimController")
RegisterBarotrauma("HumanoidAnimController")
RegisterBarotrauma("FishAnimController")
RegisterBarotrauma("Limb")
RegisterBarotrauma("Ragdoll")
RegisterBarotrauma("RagdollParams")
RegisterBarotrauma("AfflictionPrefab")
RegisterBarotrauma("Affliction")
RegisterBarotrauma("AttackResult")
RegisterBarotrauma("Attack")
RegisterBarotrauma("Entity")
RegisterBarotrauma("EntityGrid")
RegisterBarotrauma("EntitySpawner")
RegisterBarotrauma("MapEntity")
RegisterBarotrauma("MapEntityPrefab")
RegisterBarotrauma("CauseOfDeath")
RegisterBarotrauma("Hull")
RegisterBarotrauma("WallSection")
RegisterBarotrauma("Structure")
RegisterBarotrauma("Gap")
RegisterBarotrauma("PhysicsBody")
RegisterBarotrauma("AbilityFlags")
RegisterBarotrauma("ItemPrefab")
RegisterBarotrauma("ItemAssemblyPrefab")
RegisterBarotrauma("InputType")
RegisterBarotrauma("FireSource")
RegisterBarotrauma("SerializableProperty")
LuaUserData.MakeFieldAccessible(RegisterBarotrauma("StatusEffect"), "user")
RegisterBarotrauma("DurationListElement")
RegisterBarotrauma("PropertyConditional")
RegisterBarotrauma("DelayedListElement")
RegisterBarotrauma("DelayedEffect")
RegisterBarotrauma("ContentPackageManager")
RegisterBarotrauma("ContentPackageManager+PackageSource")
RegisterBarotrauma("ContentPackageManager+EnabledPackages")
RegisterBarotrauma("ContentPackage")
RegisterBarotrauma("RegularPackage")
RegisterBarotrauma("CorePackage")
RegisterBarotrauma("ContentXElement")
RegisterBarotrauma("ContentPath")
RegisterBarotrauma("ContentPackageId")
RegisterBarotrauma("SteamWorkshopId")
RegisterBarotrauma("Md5Hash")
RegisterBarotrauma("AfflictionsFile")
RegisterBarotrauma("BackgroundCreaturePrefabsFile")
RegisterBarotrauma("BallastFloraFile")
RegisterBarotrauma("BeaconStationFile")
RegisterBarotrauma("CaveGenerationParametersFile")
RegisterBarotrauma("CharacterFile")
RegisterBarotrauma("ContentFile")
RegisterBarotrauma("CorpsesFile")
RegisterBarotrauma("DecalsFile")
RegisterBarotrauma("EnemySubmarineFile")
RegisterBarotrauma("EventManagerSettingsFile")
RegisterBarotrauma("FactionsFile")
RegisterBarotrauma("ItemAssemblyFile")
RegisterBarotrauma("ItemFile")
RegisterBarotrauma("JobsFile")
RegisterBarotrauma("LevelGenerationParametersFile")
RegisterBarotrauma("LevelObjectPrefabsFile")
RegisterBarotrauma("LocationTypesFile")
RegisterBarotrauma("MapGenerationParametersFile")
RegisterBarotrauma("MissionsFile")
RegisterBarotrauma("NPCConversationsFile")
RegisterBarotrauma("NPCPersonalityTraitsFile")
RegisterBarotrauma("NPCSetsFile")
RegisterBarotrauma("OrdersFile")
RegisterBarotrauma("OtherFile")
RegisterBarotrauma("OutpostConfigFile")
RegisterBarotrauma("OutpostFile")
RegisterBarotrauma("OutpostModuleFile")
RegisterBarotrauma("ParticlesFile")
RegisterBarotrauma("RandomEventsFile")
RegisterBarotrauma("RuinConfigFile")
RegisterBarotrauma("ServerExecutableFile")
RegisterBarotrauma("SkillSettingsFile")
RegisterBarotrauma("SoundsFile")
RegisterBarotrauma("StartItemsFile")
RegisterBarotrauma("StructureFile")
RegisterBarotrauma("SubmarineFile")
RegisterBarotrauma("TalentsFile")
RegisterBarotrauma("TalentTreesFile")
RegisterBarotrauma("TextFile")
RegisterBarotrauma("TutorialsFile")
RegisterBarotrauma("UIStyleFile")
RegisterBarotrauma("UpgradeModulesFile")
RegisterBarotrauma("WreckAIConfigFile")
RegisterBarotrauma("WreckFile")
Register("System.Xml.Linq.XElement")
Register("System.Xml.Linq.XName")
Register("System.Xml.Linq.XAttribute")
Register("System.Xml.Linq.XContainer")
Register("System.Xml.Linq.XDocument")
Register("System.Xml.Linq.XNode")
RegisterBarotrauma("SubmarineBody")
RegisterBarotrauma("Explosion")
RegisterBarotrauma("Networking.ServerSettings")
RegisterBarotrauma("Networking.ServerSettings+SavedClientPermission")
RegisterBarotrauma("Inventory")
RegisterBarotrauma("ItemInventory")
RegisterBarotrauma("Inventory+ItemSlot")
RegisterBarotrauma("FireSource")
RegisterBarotrauma("AutoItemPlacer")
RegisterBarotrauma("CircuitBoxConnection")
RegisterBarotrauma("CircuitBoxComponent")
RegisterBarotrauma("CircuitBoxNode")
RegisterBarotrauma("CircuitBoxWire")
RegisterBarotrauma("CircuitBoxInputOutputNode")
RegisterBarotrauma("CircuitBoxSelectable")
RegisterBarotrauma("CircuitBoxSizes")
local componentsToRegister = { "DockingPort", "Door", "GeneticMaterial", "Growable", "Holdable", "LevelResource", "ItemComponent", "ItemLabel", "LightComponent", "Controller", "Deconstructor", "Engine", "Fabricator", "OutpostTerminal", "Pump", "Reactor", "Steering", "PowerContainer", "Projectile", "Repairable", "Rope", "Scanner", "ButtonTerminal", "ConnectionPanel", "CustomInterface", "MemoryComponent", "Terminal", "WifiComponent", "Wire", "TriggerComponent", "ElectricalDischarger", "EntitySpawnerComponent", "ProducedItem", "VineTile", "GrowthSideExtension", "IdCard", "MeleeWeapon", "Pickable", "AbilityItemPickingTime", "Propulsion", "RangedWeapon", "AbilityRangedWeapon", "RepairTool", "Sprayer", "Throwable", "ItemContainer", "AbilityItemContainer", "Ladder", "LimbPos", "AbilityDeconstructedItem", "AbilityItemCreationMultiplier", "AbilityItemDeconstructedInventory", "MiniMap", "OxygenGenerator", "Sonar", "SonarTransducer", "Vent", "NameTag", "Planter", "Powered", "PowerTransfer", "Quality", "RemoteController", "AdderComponent", "AndComponent", "ArithmeticComponent", "ColorComponent", "ConcatComponent", "Connection", "CircuitBox", "DelayComponent", "DivideComponent", "EqualsComponent", "ExponentiationComponent", "FunctionComponent", "GreaterComponent", "ModuloComponent", "MotionSensor", "MultiplyComponent", "NotComponent", "OrComponent", "OscillatorComponent", "OxygenDetector", "RegExFindComponent", "RelayComponent", "SignalCheckComponent", "SmokeDetector", "StringComponent", "SubtractComponent", "TrigonometricFunctionComponent", "WaterDetector", "XorComponent", "StatusHUD", "Turret", "Wearable",
"GridInfo", "PowerSourceGroup"
}
for key, value in pairs(componentsToRegister) do
RegisterBarotrauma("Items.Components." .. value)
end
LuaUserData.MakeFieldAccessible(RegisterBarotrauma("Items.Components.CustomInterface"), "customInterfaceElementList")
RegisterBarotrauma("Items.Components.CustomInterface+CustomInterfaceElement")
RegisterBarotrauma("WearableSprite")
RegisterBarotrauma("AIController")
RegisterBarotrauma("EnemyAIController")
RegisterBarotrauma("HumanAIController")
RegisterBarotrauma("AICharacter")
RegisterBarotrauma("AITarget")
RegisterBarotrauma("AITargetMemory")
RegisterBarotrauma("AIChatMessage")
RegisterBarotrauma("AIObjectiveManager")
RegisterBarotrauma("WreckAI")
RegisterBarotrauma("WreckAIConfig")
RegisterBarotrauma("AIObjectiveChargeBatteries")
RegisterBarotrauma("AIObjective")
RegisterBarotrauma("AIObjectiveCleanupItem")
RegisterBarotrauma("AIObjectiveCleanupItems")
RegisterBarotrauma("AIObjectiveCombat")
RegisterBarotrauma("AIObjectiveContainItem")
RegisterBarotrauma("AIObjectiveDeconstructItem")
RegisterBarotrauma("AIObjectiveDeconstructItems")
RegisterBarotrauma("AIObjectiveEscapeHandcuffs")
RegisterBarotrauma("AIObjectiveExtinguishFire")
RegisterBarotrauma("AIObjectiveExtinguishFires")
RegisterBarotrauma("AIObjectiveFightIntruders")
RegisterBarotrauma("AIObjectiveFindDivingGear")
RegisterBarotrauma("AIObjectiveFindSafety")
RegisterBarotrauma("AIObjectiveFixLeak")
RegisterBarotrauma("AIObjectiveFixLeaks")
RegisterBarotrauma("AIObjectiveGetItem")
RegisterBarotrauma("AIObjectiveGoTo")
RegisterBarotrauma("AIObjectiveIdle")
RegisterBarotrauma("AIObjectiveOperateItem")
RegisterBarotrauma("AIObjectivePumpWater")
RegisterBarotrauma("AIObjectiveRepairItem")
RegisterBarotrauma("AIObjectiveRepairItems")
RegisterBarotrauma("AIObjectiveRescue")
RegisterBarotrauma("AIObjectiveRescueAll")
RegisterBarotrauma("AIObjectiveReturn")
RegisterBarotrauma("Order")
RegisterBarotrauma("OrderPrefab")
RegisterBarotrauma("OrderTarget")
RegisterBarotrauma("TalentPrefab")
RegisterBarotrauma("TalentOption")
RegisterBarotrauma("TalentSubTree")
RegisterBarotrauma("TalentTree")
RegisterBarotrauma("CharacterTalent")
RegisterBarotrauma("Upgrade")
RegisterBarotrauma("UpgradeCategory")
RegisterBarotrauma("UpgradePrefab")
RegisterBarotrauma("UpgradeManager")
RegisterBarotrauma("Screen")
RegisterBarotrauma("GameScreen")
RegisterBarotrauma("GameSession")
RegisterBarotrauma("GameSettings")
RegisterBarotrauma("CrewManager")
RegisterBarotrauma("KarmaManager")
RegisterBarotrauma("GameMode")
RegisterBarotrauma("MissionMode")
RegisterBarotrauma("PvPMode")
RegisterBarotrauma("Mission")
RegisterBarotrauma("AbandonedOutpostMission")
RegisterBarotrauma("EliminateTargetsMission")
RegisterBarotrauma("EndMission")
RegisterBarotrauma("BeaconMission")
RegisterBarotrauma("CargoMission")
RegisterBarotrauma("CombatMission")
RegisterBarotrauma("EscortMission")
RegisterBarotrauma("GoToMission")
RegisterBarotrauma("MineralMission")
RegisterBarotrauma("MonsterMission")
RegisterBarotrauma("NestMission")
RegisterBarotrauma("PirateMission")
RegisterBarotrauma("SalvageMission")
RegisterBarotrauma("ScanMission")
RegisterBarotrauma("MissionPrefab")
RegisterBarotrauma("CampaignMode")
RegisterBarotrauma("CoOpMode")
RegisterBarotrauma("MultiPlayerCampaign")
RegisterBarotrauma("Radiation")
RegisterBarotrauma("CampaignMetadata")
RegisterBarotrauma("Wallet")
RegisterBarotrauma("Faction")
RegisterBarotrauma("FactionPrefab")
RegisterBarotrauma("Reputation")
RegisterBarotrauma("Location")
RegisterBarotrauma("LocationConnection")
RegisterBarotrauma("LocationType")
RegisterBarotrauma("LocationTypeChange")
RegisterBarotrauma("DebugConsole")
RegisterBarotrauma("DebugConsole+Command")
RegisterBarotrauma("TextManager")
RegisterBarotrauma("TextPack")
local descriptor = RegisterBarotrauma("NetLobbyScreen")
if SERVER then
LuaUserData.MakeFieldAccessible(descriptor, "subs")
end
RegisterBarotrauma("EventManager")
RegisterBarotrauma("EventManagerSettings")
RegisterBarotrauma("Event")
RegisterBarotrauma("ArtifactEvent")
RegisterBarotrauma("MonsterEvent")
RegisterBarotrauma("ScriptedEvent")
RegisterBarotrauma("MalfunctionEvent")
RegisterBarotrauma("EventSet")
RegisterBarotrauma("EventPrefab")
RegisterBarotrauma("Networking.NetConfig")
RegisterBarotrauma("Networking.IWriteMessage")
RegisterBarotrauma("Networking.IReadMessage")
RegisterBarotrauma("Networking.NetEntityEvent")
RegisterBarotrauma("Networking.INetSerializable")
Register("Lidgren.Network.NetIncomingMessage")
Register("Lidgren.Network.NetConnection")
Register("System.Net.IPEndPoint")
Register("System.Net.IPAddress")
RegisterBarotrauma("Skill")
RegisterBarotrauma("SkillPrefab")
RegisterBarotrauma("SkillSettings")
RegisterBarotrauma("TraitorManager")
RegisterBarotrauma("TraitorEvent")
RegisterBarotrauma("TraitorEventPrefab")
RegisterBarotrauma("TraitorManager+TraitorResults")
Register("FarseerPhysics.Dynamics.Body")
Register("FarseerPhysics.Dynamics.World")
Register("FarseerPhysics.Dynamics.Fixture")
Register("FarseerPhysics.ConvertUnits")
Register("FarseerPhysics.Collision.AABB")
Register("FarseerPhysics.Collision.ContactFeature")
Register("FarseerPhysics.Collision.ManifoldPoint")
Register("FarseerPhysics.Collision.ContactID")
Register("FarseerPhysics.Collision.Manifold")
Register("FarseerPhysics.Collision.RayCastInput")
Register("FarseerPhysics.Collision.ClipVertex")
Register("FarseerPhysics.Collision.RayCastOutput")
Register("FarseerPhysics.Collision.EPAxis")
Register("FarseerPhysics.Collision.ReferenceFace")
Register("FarseerPhysics.Collision.Collision")
RegisterBarotrauma("Physics")
local toolBox = RegisterBarotrauma("ToolBox")
if CLIENT then
LuaUserData.RemoveMember(toolBox, "OpenFileWithShell")
end
RegisterBarotrauma("Camera")
RegisterBarotrauma("Key")
RegisterBarotrauma("PrefabCollection`1")
RegisterBarotrauma("PrefabSelector`1")
RegisterBarotrauma("Pair`2")
RegisterBarotrauma("Items.Components.Signal")
RegisterBarotrauma("SubmarineInfo")
RegisterBarotrauma("MapCreatures.Behavior.BallastFloraBehavior")
RegisterBarotrauma("MapCreatures.Behavior.BallastFloraBranch")
RegisterBarotrauma("PetBehavior")
RegisterBarotrauma("SwarmBehavior")
RegisterBarotrauma("LatchOntoAI")
RegisterBarotrauma("Decal")
RegisterBarotrauma("DecalPrefab")
RegisterBarotrauma("DecalManager")
RegisterBarotrauma("PriceInfo")
RegisterBarotrauma("Voting")
Register("Microsoft.Xna.Framework.Vector2")
Register("Microsoft.Xna.Framework.Vector3")
Register("Microsoft.Xna.Framework.Vector4")
Register("Microsoft.Xna.Framework.Color")
Register("Microsoft.Xna.Framework.Point")
Register("Microsoft.Xna.Framework.Rectangle")
Register("Microsoft.Xna.Framework.Matrix")
local friend = Register("Steamworks.Friend")
LuaUserData.RemoveMember(friend, "InviteToGame")
LuaUserData.RemoveMember(friend, "SendMessage")
local workshopItem = Register("Steamworks.Ugc.Item")
LuaUserData.RemoveMember(workshopItem, "Subscribe")
LuaUserData.RemoveMember(workshopItem, "DownloadAsync")
LuaUserData.RemoveMember(workshopItem, "Unsubscribe")
LuaUserData.RemoveMember(workshopItem, "AddFavorite")
LuaUserData.RemoveMember(workshopItem, "RemoveFavorite")
LuaUserData.RemoveMember(workshopItem, "Vote")
LuaUserData.RemoveMember(workshopItem, "GetUserVote")
LuaUserData.RemoveMember(workshopItem, "Edit")
RegisterExtension("Barotrauma.MathUtils")
RegisterExtension("Barotrauma.XMLExtensions")
@@ -1,50 +0,0 @@
LuaSetup = {}
local path = table.pack(...)[1]
package.path = {path .. "/?.lua"}
setmodulepaths(package.path)
-- Setup Libraries
require("LuaUserData")
require("DefaultRegister/RegisterShared")
if SERVER then
require("DefaultRegister/RegisterServer")
else
require("DefaultRegister/RegisterClient")
end
local function AddTableToGlobal(tbl)
for k, v in pairs(tbl) do
_G[k] = v
end
end
if SERVER then
AddTableToGlobal(require("DefaultLib/LibServer"))
else
AddTableToGlobal(require("DefaultLib/LibClient"))
end
AddTableToGlobal(require("DefaultLib/LibShared"))
AddTableToGlobal(require("CompatibilityLib"))
require("DefaultHook")
Descriptors = LuaSetup.LuaUserData.Descriptors
LuaUserData = LuaSetup.LuaUserData
require("DefaultLib/Utils/Math")
require("DefaultLib/Utils/String")
require("DefaultLib/Utils/Util")
require("DefaultLib/Utils/SteamApi")
require("PostSetup")
LuaSetup = nil
require("ModLoader")
@@ -1,97 +0,0 @@
local clrLuaUserData = LuaUserData
local luaUserData = {}
luaUserData.Descriptors = {}
LuaSetup.LuaUserData = luaUserData
luaUserData.IsRegistered = clrLuaUserData.IsRegistered
luaUserData.UnregisterType = clrLuaUserData.UnregisterType
luaUserData.RegisterGenericType = clrLuaUserData.RegisterGenericType
luaUserData.RegisterExtensionType = clrLuaUserData.RegisterExtensionType
luaUserData.UnregisterGenericType = clrLuaUserData.UnregisterGenericType
luaUserData.IsTargetType = clrLuaUserData.IsTargetType
luaUserData.TypeOf = clrLuaUserData.TypeOf
luaUserData.GetType = clrLuaUserData.GetType
luaUserData.CreateEnumTable = clrLuaUserData.CreateEnumTable
luaUserData.MakeFieldAccessible = clrLuaUserData.MakeFieldAccessible
luaUserData.MakeMethodAccessible = clrLuaUserData.MakeMethodAccessible
luaUserData.MakePropertyAccessible = clrLuaUserData.MakePropertyAccessible
luaUserData.AddMethod = clrLuaUserData.AddMethod
luaUserData.AddField = clrLuaUserData.AddField
luaUserData.RemoveMember = clrLuaUserData.RemoveMember
luaUserData.CreateUserDataFromDescriptor = clrLuaUserData.CreateUserDataFromDescriptor
luaUserData.CreateUserDataFromType = clrLuaUserData.CreateUserDataFromType
luaUserData.HasMember = clrLuaUserData.HasMember
luaUserData.RegisterType = function(typeName)
local success, result = pcall(clrLuaUserData.RegisterType, typeName)
if not success then
error(result, 2)
end
luaUserData.Descriptors[typeName] = result
return result
end
luaUserData.RegisterTypeBarotrauma = function(typeName)
typeName = "Barotrauma." .. typeName
local success, result = pcall(luaUserData.RegisterType, typeName)
if not success then
error(result, 2)
end
return result
end
luaUserData.AddCallMetaTable = function (userdata)
if userdata == nil then
error("Attempted to add a call metatable to a nil value.", 2)
end
if not LuaUserData.HasMember(userdata, ".ctor") then
error("Attempted to add a call metatable to a userdata that does not have a constructor.", 2)
end
debug.setmetatable(userdata, {
__call = function(obj, ...)
if userdata == nil then
error("userdata was nil.", 2)
end
local success, result = pcall(userdata.__new, ...)
if not success then
error(result, 2)
end
return result
end
})
end
luaUserData.CreateStatic = function(typeName)
if type(typeName) ~= "string" then
error("Expected a string for typeName, got " .. type(typeName) .. ".", 2)
end
local success, result = pcall(clrLuaUserData.CreateStatic, typeName)
if not success then
error(result, 2)
end
if result == nil then
return
end
if LuaUserData.HasMember(result, ".ctor") then
luaUserData.AddCallMetaTable(result)
end
return result
end
@@ -1,193 +0,0 @@
local LUA_MOD_REQUIRE_PATH = "/Lua/?.lua"
local LUA_MOD_AUTORUN_PATH = "/Lua/Autorun"
local LUA_MOD_FORCEDAUTORUN_PATH = "/Lua/ForcedAutorun"
local function EndsWith(str, suffix)
return str:sub(-string.len(suffix)) == suffix
end
local function GetFileName(file)
return file:match("^.+/(.+)$")
end
local function ExecuteProtected(s, folder)
loadfile(s)(folder)
end
local function RunFolder(folder, rootFolder, package)
local search = File.DirSearch(folder)
for i = 1, #search, 1 do
local s = search[i]:gsub("\\", "/")
if EndsWith(s, ".lua") then
local time = os.clock()
local ok, result = pcall(ExecuteProtected, s, rootFolder)
local diff = os.clock() - time
print(string.format(" - %s (Took %.5fms)", GetFileName(s), diff))
if not ok then
printerror(result)
end
end
end
end
local function AssertTypes(expectedTypes, ...)
local args = table.pack(...)
assert(
#args == #expectedTypes,
string.format(
"Assertion failed: incorrect number of args\n\texpected = %s\n\tgot = %s",
#expectedTypes, #args
)
)
for i = 1, #args do
local arg = args[i]
local expectedType = expectedTypes[i]
assert(
type(arg) == expectedType,
string.format(
"Assertion failed: incorrect argument type (arg #%d)\n\texpected = %s\n\tgot = %s",
i, expectedType, type(arg)
)
)
end
end
local function ExecutionQueue()
local executionQueue = {}
executionQueue.Queue = {}
executionQueue.Process = function()
while executionQueue.Queue[1] ~= nil do
local folder, rootFolder, package = table.unpack(table.remove(executionQueue.Queue, 1))
print(string.format("%s %s", package.Name, package.ModVersion))
RunFolder(folder, rootFolder, package)
end
end
executionQueue.Add = function(...)
AssertTypes({ 'string', 'string', 'userdata' }, ...)
table.insert(executionQueue.Queue, table.pack(...))
end
return executionQueue
end
local QueueAutorun = ExecutionQueue()
local QueueForcedAutorun = ExecutionQueue()
local function nocase(s)
s = string.gsub(s, "%a", function(c)
return string.format("[%s%s]", string.lower(c), string.upper(c))
end)
return s
end
local function ProcessPackages(packages, fn)
for pkg in packages do
if pkg then
local pkgPath = pkg.Path
:gsub("\\", "/")
:gsub(nocase("/filelist.xml"), "")
fn(pkg, pkgPath)
end
end
end
ProcessPackages(ContentPackageManager.EnabledPackages.All, function(pkg, pkgPath)
table.insert(package.path, pkgPath .. LUA_MOD_REQUIRE_PATH)
local autorunPath = pkgPath .. LUA_MOD_AUTORUN_PATH
if File.DirectoryExists(autorunPath) then
QueueAutorun.Add(autorunPath, pkgPath, pkg)
end
end)
-- we don't want to execute workshop ForcedAutorun if we have a local Package
local executedLocalPackages = {}
ProcessPackages(ContentPackageManager.EnabledPackages.All, function(pkg, pkgPath)
table.insert(package.path, pkgPath .. LUA_MOD_REQUIRE_PATH)
local forcedAutorunPath = pkgPath .. LUA_MOD_FORCEDAUTORUN_PATH
if File.DirectoryExists(forcedAutorunPath) then
QueueForcedAutorun.Add(forcedAutorunPath, pkgPath, pkg)
executedLocalPackages[pkg.Name] = true
end
end)
if not LuaCsConfig.TreatForcedModsAsNormal then
ProcessPackages(ContentPackageManager.LocalPackages, function(pkg, pkgPath)
if not executedLocalPackages[pkg.Name] then
table.insert(package.path, pkgPath .. LUA_MOD_REQUIRE_PATH)
local forcedAutorunPath = pkgPath .. LUA_MOD_FORCEDAUTORUN_PATH
if File.DirectoryExists(forcedAutorunPath) then
QueueForcedAutorun.Add(forcedAutorunPath, pkgPath, pkg)
executedLocalPackages[pkg.Name] = true
end
end
end)
ProcessPackages(ContentPackageManager.AllPackages, function(pkg, pkgPath)
if not executedLocalPackages[pkg.Name] then
table.insert(package.path, pkgPath .. LUA_MOD_REQUIRE_PATH)
local forcedAutorunPath = pkgPath .. LUA_MOD_FORCEDAUTORUN_PATH
if File.DirectoryExists(forcedAutorunPath) then
QueueForcedAutorun.Add(forcedAutorunPath, pkgPath, pkg)
end
end
end)
end
setmodulepaths(package.path)
setmodulepaths = nil
local allExecuted = {}
for key, value in pairs(QueueAutorun.Queue) do table.insert(allExecuted, value[3]) end
for key, value in pairs(QueueForcedAutorun.Queue) do table.insert(allExecuted, value[3]) end
if SERVER then
Networking.Receive("_luastart", function (message, client)
local num = message.ReadUInt16()
local packages = {}
for i = 1, num, 1 do
table.insert(packages, {
Name = message.ReadString(),
Version = message.ReadString(),
Id = message.ReadUInt64(),
Hash = message.ReadString()
})
end
Hook.Call("client.packages", client, packages)
end)
elseif Game.IsMultiplayer then
local message = Networking.Start("_luastart")
message.WriteUInt16(#allExecuted)
for key, package in pairs(allExecuted) do
local id = package.UgcId
local hash = package.Hash and package.Hash.StringRepresentation or ""
if id == nil then id = 0 end
message.WriteString(package.Name)
message.WriteString(package.ModVersion)
message.WriteUInt64(UInt64(id))
message.WriteString(hash)
end
Networking.Send(message)
end
QueueAutorun.Process()
QueueForcedAutorun.Process()
Hook.Add("stop", "luaSetup.stop", function()
print("Stopping Lua...")
end)
Hook.Call("loaded")
@@ -1,75 +0,0 @@
if CSActive then
return
end
local function IsAllowed(typeName)
if string.startsWith(typeName, "Barotrauma.Lua") or string.startsWith(typeName, "Barotrauma.Cs") or string.startsWith(typeName, "Barotrauma.LuaCs") then
return false
end
if string.startsWith(typeName, "System.Collections") then return true end
if string.startsWith(typeName, "Microsoft.Xna") then return true end
if string.startsWith(typeName, "Barotrauma.IO") then return false end
if string.startsWith(typeName, "Barotrauma.ToolBox") then return false end
if string.startsWith(typeName, "Barotrauma.SaveUtil") then return false end
if string.startsWith(typeName, "Barotrauma.") then return true end
return false
end
local function CanBeReRegistered(typeName)
if string.startsWith(typeName, "Barotrauma.Lua") or string.startsWith(typeName, "Barotrauma.Cs") or string.startsWith(typeName, "Barotrauma.LuaCs") then
return false
end
return true
end
local originalRegisterType = LuaUserData.RegisterType
LuaUserData.RegisterType = function (typeName)
if not (CanBeReRegistered(typeName) and LuaUserData.IsRegistered(typeName)) and not IsAllowed(typeName) then
error("Couldn't register type " .. typeName .. ".", 2)
end
local success, result = pcall(originalRegisterType, typeName)
if not success then
error(result, 2)
end
return result
end
local originalRegisterGenericType = LuaUserData.RegisterType
LuaUserData.RegisterGenericType = function (typeName, ...)
if not (CanBeReRegistered(typeName) and LuaUserData.IsRegistered(typeName)) and not IsAllowed(typeName) then
error("Couldn't register generic type " .. typeName .. ".", 2)
end
local success, result = pcall(originalRegisterGenericType, typeName, ...)
if not success then
error(result, 2)
end
return result
end
local originalCreateStatic = LuaUserData.CreateStatic
LuaUserData.CreateStatic = function (typeName, addCallMethod)
if not (CanBeReRegistered(typeName) and LuaUserData.IsRegistered(typeName)) and not IsAllowed(typeName) then
error("Couldn't create static type " .. typeName .. ".", 2)
end
local success, result = pcall(originalCreateStatic, typeName, addCallMethod)
if not success then
error(result, 2)
end
return result
end
@@ -1,20 +0,0 @@
<Project>
<ItemGroup>
<PackageReference Include="Luatrauma.Internal.AssemblyPublicizer.MSBuild" Version="0.1.4" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="4.1.0" />
<PackageReference Include="MonoMod.RuntimeDetour" Version="25.2.3" />
<PackageReference Include="HarmonyX" Version="2.14.0" />
<PackageReference Include="Sigil" Version="5.0.0" />
<ProjectReference Include="$(MSBuildThisFileDirectory)..\..\Libraries\moonsharp\MoonSharp.Interpreter\MoonSharp.Interpreter.csproj" />
<ProjectReference Include="$(MSBuildThisFileDirectory)..\..\Libraries\moonsharp\MoonSharp.VsCodeDebugger\MoonSharp.VsCodeDebugger.csproj" />
</ItemGroup>
<!--
The `Microsoft.CodeAnalysis.CSharp.Scripting` package includes satellites
assemblies, which end up polluting the build folder.
This suppresses the extra satellite assemblies.
-->
<PropertyGroup>
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
</PropertyGroup>
</Project>
@@ -96,17 +96,8 @@ namespace Barotrauma
CreateAutonomousObjectives();
}
public void AddObjective(AIObjective objective)
{
AddObjective<AIObjective>(objective);
}
public void AddObjective<T>(T objective) where T : AIObjective
{
var result = GameMain.LuaCs.Hook.Call<bool?>("AI.addObjective", this, objective);
if (result != null && result.Value) return;
if (objective == null)
{
#if DEBUG
@@ -1305,11 +1305,6 @@ namespace Barotrauma
//increase oxygen and clamp it above zero
// -> the character should be revived if there are no major afflictions in addition to lack of oxygen
target.Oxygen = Math.Max(target.Oxygen + 10.0f, 10.0f);
GameMain.LuaCs.Hook.Call("human.CPRSuccess", this);
}
else
{
GameMain.LuaCs.Hook.Call("human.CPRFailed", this);
}
}
}
@@ -11,7 +11,6 @@ using System.Xml.Linq;
using Barotrauma.Extensions;
using LimbParams = Barotrauma.RagdollParams.LimbParams;
using JointParams = Barotrauma.RagdollParams.JointParams;
using MoonSharp.Interpreter;
namespace Barotrauma
{
@@ -857,13 +856,6 @@ namespace Barotrauma
float impactDamage = GetImpactDamage(impact, impactTolerance);
var should = GameMain.LuaCs.Hook.Call<float?>("changeFallDamage", impactDamage, character, impactPos, velocity);
if (should != null)
{
impactDamage = should.Value;
}
character.LastDamageSource = null;
character.AddDamage(impactPos, AfflictionPrefab.ImpactDamage.Instantiate(impactDamage).ToEnumerable(), 0.0f, true);
strongestImpact = Math.Max(strongestImpact, impact - impactTolerance);
@@ -32,9 +32,6 @@ namespace Barotrauma
{
public static readonly List<Character> CharacterList = new List<Character>();
public static int CharacterUpdateInterval = 1;
private static int characterUpdateTick = 1;
public const float MaxHighlightDistance = 150.0f;
public const float MaxDragDistance = 200.0f;
@@ -1432,9 +1429,6 @@ namespace Barotrauma
Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(newCharacter));
}
#endif
GameMain.LuaCs.Hook.Call("character.created", new object[] { newCharacter });
return newCharacter;
}
@@ -1889,7 +1883,6 @@ namespace Barotrauma
}
}
info.Job?.GiveJobItems(this, isPvPMode, spawnPoint);
GameMain.LuaCs.Hook.Call("character.giveJobItems", this, spawnPoint, isPvPMode);
}
public void GiveIdCardTags(WayPoint spawnPoint, bool createNetworkEvent = false)
@@ -3385,21 +3378,8 @@ namespace Barotrauma
}
}
characterUpdateTick++;
if (characterUpdateTick % CharacterUpdateInterval == 0)
foreach (Character character in CharacterList)
{
for (int i = 0; i < CharacterList.Count; i++)
{
if (GameMain.LuaCs.Game.UpdatePriorityCharacters.Contains(CharacterList[i])) continue;
CharacterList[i].Update(deltaTime * CharacterUpdateInterval, cam);
}
}
foreach (Character character in GameMain.LuaCs.Game.UpdatePriorityCharacters)
{
if (character.Removed) { continue; }
Debug.Assert(character is { Removed: false });
character.Update(deltaTime, cam);
}
@@ -4563,12 +4543,12 @@ namespace Barotrauma
}
}
public AttackResult AddDamage(Vector2 worldPosition, IEnumerable<Affliction> afflictions, float stun, bool playSound, Vector2? attackImpulse = null, Character attacker = null, float damageMultiplier = 1f)
public AttackResult AddDamage(Vector2 worldPosition, IEnumerable<Affliction> afflictions, float stun, bool playSound, Vector2? attackImpulse = null, Character attacker = null, float damageMultiplier = 1f, float penetration = 0f)
{
return AddDamage(worldPosition, afflictions, stun, playSound, attackImpulse ?? Vector2.Zero, out _, attacker, damageMultiplier: damageMultiplier);
return AddDamage(worldPosition, afflictions, stun, playSound, attackImpulse ?? Vector2.Zero, out _, attacker, damageMultiplier: damageMultiplier,penetration: penetration);
}
public AttackResult AddDamage(Vector2 worldPosition, IEnumerable<Affliction> afflictions, float stun, bool playSound, Vector2 attackImpulse, out Limb hitLimb, Character attacker = null, float damageMultiplier = 1)
public AttackResult AddDamage(Vector2 worldPosition, IEnumerable<Affliction> afflictions, float stun, bool playSound, Vector2 attackImpulse, out Limb hitLimb, Character attacker = null, float damageMultiplier = 1f, float penetration = 0f)
{
hitLimb = null;
@@ -4585,7 +4565,7 @@ namespace Barotrauma
}
}
return DamageLimb(worldPosition, hitLimb, afflictions, stun, playSound, attackImpulse, attacker, damageMultiplier);
return DamageLimb(worldPosition, hitLimb, afflictions, stun, playSound, attackImpulse, attacker, damageMultiplier,penetration: penetration);
}
public void RecordKill(Character target)
@@ -4609,12 +4589,6 @@ namespace Barotrauma
{
if (Removed) { return new AttackResult(); }
AttackResult? retAttackResult = GameMain.LuaCs.Hook.Call<AttackResult?>("character.damageLimb", this, worldPosition, hitLimb, afflictions, stun, playSound, attackImpulse, attacker, damageMultiplier, allowStacking, penetration, shouldImplode);
if (retAttackResult != null)
{
return retAttackResult.Value;
}
SetStun(stun);
if (attacker != null && attacker != this &&
@@ -5129,7 +5103,6 @@ namespace Barotrauma
AchievementManager.OnCharacterKilled(this, CauseOfDeath);
}
GameMain.LuaCs.Hook.Call("character.death", this, causeOfDeathAffliction);
KillProjSpecific(causeOfDeath, causeOfDeathAffliction, log);
if (info != null)
@@ -482,7 +482,6 @@ namespace Barotrauma
{
GrainEffectStrength -= amount;
}
GameMain.LuaCs.Hook.Call("afflictionUpdate", new object[] { this, characterHealth, targetLimb, deltaTime });
}
public void ApplyStatusEffects(ActionType type, float deltaTime, CharacterHealth characterHealth, Limb targetLimb)
@@ -337,13 +337,12 @@ namespace Barotrauma
if (Prefab is AfflictionPrefabHusk huskPrefab)
{
if (huskPrefab.ControlHusk || GameMain.LuaCs.Game.enableControlHusk)
if (huskPrefab.ControlHusk)
{
#if SERVER
if (client != null)
{
GameMain.Server.SetClientCharacter(client, husk);
GameMain.LuaCs.Hook.Call("husk.clientControlHusk", new object[] { client, husk });
}
#else
if (!character.IsRemotelyControlled && character == Character.Controlled)
@@ -7,17 +7,12 @@ using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;
using Barotrauma.Networking;
using Barotrauma.Extensions;
using System.Globalization;
using MoonSharp.Interpreter;
using Barotrauma.Abilities;
namespace Barotrauma
{
partial class CharacterHealth
{
public class LimbHealth
class LimbHealth
{
public Sprite IndicatorSprite;
public Sprite HighlightSprite;
@@ -485,7 +480,6 @@ namespace Barotrauma
{
AddLimbAffliction(limbHealth, limb: null, affliction, allowStacking: allowStacking, recalculateVitality: recalculateVitality);
}
}
else
{
@@ -503,7 +497,6 @@ namespace Barotrauma
/// </summary>
public float GetResistance(AfflictionPrefab afflictionPrefab, LimbType limbType)
{
lock (afflictions) {
// This is a % resistance (0 to 1.0)
float resistance = 0.0f;
foreach (KeyValuePair<Affliction, LimbHealth> kvp in afflictions)
@@ -516,7 +509,6 @@ namespace Barotrauma
// The returned value is calculated to be a % resistance again
return 1 - ((1 - resistance) * abilityResistanceMultiplier);
}
}
public float GetStatValue(StatTypes statType)
{
@@ -657,9 +649,6 @@ namespace Barotrauma
return;
}
var should = GameMain.LuaCs.Hook.Call<bool?>("character.applyDamage", this, attackResult, hitLimb, allowStacking);
if (should != null && should.Value) { return; }
foreach (Affliction newAffliction in attackResult.Afflictions)
{
if (newAffliction.Prefab.LimbSpecific)
@@ -828,11 +817,6 @@ namespace Barotrauma
if (newAffliction.Prefab.TargetSpecies.Any() && newAffliction.Prefab.TargetSpecies.None(s => s == Character.SpeciesName)) { return; }
if (Character.Params.Health.ImmunityIdentifiers.Contains(newAffliction.Identifier)) { return; }
var should = GameMain.LuaCs.Hook.Call<bool?>("character.applyAffliction", this, limbHealth, newAffliction, allowStacking);
if (should != null && should.Value)
return;
Affliction existingAffliction = null;
foreach ((Affliction affliction, LimbHealth value) in afflictions)
{
@@ -282,9 +282,7 @@ namespace Barotrauma
#if SERVER
if (GameMain.Server != null && Entity.Spawner != null && createNetworkEvents)
{
try
{
if (GameMain.Server.EntityEventManager.UniqueEvents.ToList().Any(ev => ev.Entity == item))
if (GameMain.Server.EntityEventManager.UniqueEvents.Any(ev => ev.Entity == item))
{
string errorMsg = $"Error while spawning job items. Item {item.Name} created network events before the spawn event had been created.";
DebugConsole.ThrowError(errorMsg);
@@ -292,18 +290,9 @@ namespace Barotrauma
GameMain.Server.EntityEventManager.UniqueEvents.RemoveAll(ev => ev.Entity == item);
GameMain.Server.EntityEventManager.Events.RemoveAll(ev => ev.Entity == item);
}
}
catch
{
#if SERVER
Networking.GameServer.Log("Try making UniqueEvents snapshot failed", Networking.ServerLog.MessageType.Error);
#endif
}
finally
{
Entity.Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(item));
}
}
#endif
if (itemElement.GetAttributeBool("equip", false))
{
@@ -170,9 +170,7 @@ namespace Barotrauma
#if SERVER
if (GameMain.Server != null && Entity.Spawner != null)
{
try
{
if (GameMain.Server.EntityEventManager.UniqueEvents.ToList().Any(ev => ev.Entity == item))
if (GameMain.Server.EntityEventManager.UniqueEvents.Any(ev => ev.Entity == item))
{
string errorMsg = $"Error while spawning job items. Item {item.Name} created network events before the spawn event had been created.";
DebugConsole.ThrowError(errorMsg);
@@ -180,18 +178,8 @@ namespace Barotrauma
GameMain.Server.EntityEventManager.UniqueEvents.RemoveAll(ev => ev.Entity == item);
GameMain.Server.EntityEventManager.Events.RemoveAll(ev => ev.Entity == item);
}
}
catch
{
#if SERVER
Networking.GameServer.Log("Try making UniqueEvents snapshot failed", Networking.ServerLog.MessageType.Error);
#endif
}
finally
{
Entity.Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(item));
}
Entity.Spawner.CreateNetworkEvent(new EntitySpawner.SpawnEntity(item));
}
#endif
@@ -42,7 +42,7 @@ namespace Barotrauma
? (Core as ContentPackage).ToEnumerable().CollectionConcat(Regular)
: Enumerable.Empty<ContentPackage>();
public static class BackupPackages
private static class BackupPackages
{
public static CorePackage? Core;
public static ImmutableArray<RegularPackage>? Regular;
@@ -39,7 +39,6 @@ namespace Barotrauma
static partial class DebugConsole
{
public partial class Command
{
public readonly ImmutableArray<Identifier> Names;
@@ -165,7 +164,7 @@ namespace Barotrauma
private static WeakReference<Character> previousControlledCharacter; // For SP freecam
public static void AssignOnExecute(string names, Action<string[]> onExecute)
private static void AssignOnExecute(string names, Action<string[]> onExecute)
{
var matchingCommand = commands.Find(c => c.Names.Intersect(names.Split('|').ToIdentifiers()).Any());
if (matchingCommand == null)
@@ -3160,7 +3159,7 @@ namespace Barotrauma
}
}
public static void SpawnItem(string[] args, Vector2 cursorPos, Character controlledCharacter, out string errorMsg)
private static void SpawnItem(string[] args, Vector2 cursorPos, Character controlledCharacter, out string errorMsg)
{
errorMsg = "";
if (args.Length < 1) return;
@@ -759,8 +759,6 @@ namespace Barotrauma
ReadyCheck.ReadyCheckCooldown = DateTime.MinValue;
GUI.PreventPauseMenuToggle = false;
HintManager.OnRoundStarted();
GameMain.LuaCs.Hook.Call("roundStart");
EnableEventLogNotificationIcon(enabled: false);
LogStartRoundStats();
@@ -1047,9 +1045,6 @@ namespace Barotrauma
/// </remarks>
public static ImmutableHashSet<Character> GetSessionCrewCharacters(CharacterType type)
{
var result = GameMain.LuaCs.Hook.Call<Character[]?>("getSessionCrewCharacters", type);
if (result != null) return ImmutableHashSet.Create(result);
if (GameMain.GameSession?.CrewManager is not { } crewManager) { return ImmutableHashSet<Character>.Empty; }
IEnumerable<Character> players;
@@ -1088,9 +1083,6 @@ namespace Barotrauma
{
RoundEnding = true;
#if CLIENT
GameMain.LuaCs.Hook.Call("roundEnd");
#endif
//Clear the grids to allow for garbage collection
Powered.Grids.Clear();
Powered.ChangedConnections.Clear();
@@ -1109,8 +1101,6 @@ namespace Barotrauma
character.CheckTalents(AbilityEffectType.OnRoundEnd);
}
GameMain.LuaCs.Hook.Call("missionsEnded", missions);
#if CLIENT
if (GUI.PauseMenuOpen)
{
@@ -435,7 +435,6 @@ namespace Barotrauma.Items.Components
Structure targetStructure = target.UserData as Structure ?? targetFixture.UserData as Structure;
Item targetItem = target.UserData is Holdable h ? h.Item : target.UserData as Item ?? targetFixture.UserData as Item;
Entity targetEntity = targetCharacter ?? targetStructure ?? targetItem ?? target.UserData as Entity;
GameMain.LuaCs.Hook.Call("meleeWeapon.handleImpact", this, target);
if (Attack != null)
{
@@ -5,8 +5,6 @@ using System.Linq;
using System.Reflection;
using System.Xml.Linq;
using Barotrauma.Extensions;
using Barotrauma;
using MoonSharp.Interpreter;
using Barotrauma.IO;
using Barotrauma.Networking;
#if CLIENT
@@ -332,9 +332,6 @@ namespace Barotrauma.Items.Components
GameAnalyticsManager.AddDesignEvent("ItemDeconstructed:" + (GameMain.GameSession?.GameMode?.Preset.Identifier.Value ?? "none") + ":" + targetItem.Prefab.Identifier);
}
bool? result = GameMain.LuaCs.Hook.Call<bool?>("item.deconstructed", targetItem, this, user, allowRemove);
if (result == true) { return; }
if (targetItem.AllowDeconstruct && allowRemove)
{
//drop all items that are inside the deconstructed item
@@ -350,15 +350,11 @@ namespace Barotrauma.Items.Components
wire.RegisterSignal(signal, source: this);
#endif
SendSignalIntoConnection(signal, recipient);
GameMain.LuaCs.Hook.Call("signalReceived", signal, recipient);
GameMain.LuaCs.Hook.Call("signalReceived." + recipient.item.Prefab.Identifier, signal, recipient);
}
foreach (CircuitBoxConnection connection in CircuitBoxConnections)
{
connection.ReceiveSignal(signal);
GameMain.LuaCs.Hook.Call("signalReceived", signal, connection.Connection);
GameMain.LuaCs.Hook.Call("signalReceived." + connection.Connection.Item.Prefab.Identifier, signal, connection);
}
enumeratingWires = false;
foreach (var removedWire in removedWires)
@@ -1,18 +1,18 @@
namespace Barotrauma.Items.Components
{
partial struct Signal
public struct Signal
{
public string value;
public int stepsTaken;
public Character sender;
public Item source;
public float power;
public float strength;
internal string value;
internal int stepsTaken;
internal Character sender;
internal Item source;
internal float power;
internal float strength;
public readonly double CreationTime;
public double TimeSinceCreated => Timing.TotalTimeUnpaused - CreationTime;
public Signal(string value, int stepsTaken = 0, Character sender = null,
internal Signal(string value, int stepsTaken = 0, Character sender = null,
Item source = null, float power = 0.0f, float strength = 1.0f)
{
this.value = value;
@@ -228,10 +228,6 @@ namespace Barotrauma.Items.Components
public void TransmitSignal(Signal signal, bool sentFromChat)
{
var should = GameMain.LuaCs.Hook.Call<bool?>("wifiSignalTransmitted", this, signal, sentFromChat);
if (should != null && should.Value) { return; }
bool chatMsgSent = false;
var receivers = GetReceiversInRange();

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