Compare commits

...

38 Commits

Author SHA1 Message Date
Michael Wilson
7af153cf25 release: v1.0.319 2025-06-20 12:39:17 +00:00
Michal
6f663164ee Improve FunctionReference trace logging with real user stack origin (#895)
Co-authored-by: Michael Wilson <roflmuffin@users.noreply.github.com>
Co-authored-by: root <root@ns3203586.ip-146-59-53.eu>
2025-06-20 12:28:14 +00:00
Michael Wilson
22f5c06c49 release: v1.0.318 2025-05-12 06:08:34 +00:00
Michael Wilson
073728b4ce fix(gameevents): merge and sort game event properties if duplicate events 2025-05-12 05:59:21 +00:00
Michael Wilson
6511a0098a chore: cleanup cpp & add clang format linting (#862) 2025-05-12 15:46:13 +10:00
Eason
f50fb783bb chore(build): duplicate include path: ${SOURCESDK}/public/entity2 (#756)
Co-authored-by: Michael Wilson <roflmuffin@users.noreply.github.com>
2025-05-12 04:23:03 +00:00
roflmuffin
49e8ab0e27 release: v1.0.317 2025-05-10 12:34:59 +10:00
roflmuffin
4be0634625 chore(gameevents): update game events (bullet_damage changes) 2025-05-10 12:32:05 +10:00
roflmuffin
7025b62615 chore(schema): update (mainly removal of danger zone classes) 2025-05-10 12:31:38 +10:00
Michael Wilson
462ca52229 chore(deps): upgrade metamod & hl2sdk (#856) 2025-05-10 12:17:45 +10:00
dependabot[bot]
d7e23e8282 chore(deps): bump libraries/Protobufs from 3d85413 to 53da9bc (#857)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-05-08 14:37:58 +10:00
roflmuffin
3ddfa71e3f feat: add Scoreboard and Inspect buttons to PlayerButtons 2025-05-02 20:16:02 +10:00
ipsvn
688b226bcf Fix potential event natives crashes (#852) 2025-04-29 14:32:50 +10:00
Michael Wilson
0d23387347 release: v1.0.316 2025-04-04 01:09:56 +00:00
Michael Wilson
68e6ffaebe fix(gamedata): update CCSPlayer_WeaponServices_CanUse signature 2025-04-04 11:08:07 +10:00
Michael Wilson
2f8f370cd3 fix: commit links in changelog finally 2025-04-01 17:02:15 +10:00
Michael Wilson
169d43e31d release: 1.0.315 2025-04-01 02:05:37 +00:00
schwarper
0ce4a2903c Update CCSPlayer_ItemServices_CanAcquire signature (#832) 2025-04-01 11:24:21 +10:00
Pawel Bartusiak
33b46eb214 docs: add automatic build and deploy guide (#831) 2025-03-31 11:45:43 +10:00
Michael Wilson
a27ba3b005 fix: move EventPlayerChat to dedicated file and exclude from generator
- Created a separate EventPlayerChat since this is being fired manually
- Updated event generator to exclude player_chat event from GameEvents.g.cs
2025-03-31 11:44:15 +10:00
Michael Wilson
57286c9990 chore(changelog): cleanup whitespace once and for all 2025-03-28 06:53:49 +00:00
Michael Wilson
ae808c05c8 [no ci] chore: fix commit links in release changelog 2025-03-27 14:46:17 +10:00
Michael Wilson
c9f8e477d3 release: 1.0.314 2025-03-27 04:06:33 +00:00
Michael Wilson
2398ba0a5d fix: manually revert EventPlayerChat to old value (#827) 2025-03-27 13:56:15 +10:00
roflmuffin
e45c20481d ci: hide release commits in changelog 2025-03-25 20:56:03 +10:00
roflmuffin
fe321ee93d ci: include full changelog link in discord message 2025-03-25 20:31:42 +10:00
roflmuffin
be19103556 chore: remove footer from cliff changelog 2025-03-25 20:29:16 +10:00
roflmuffin
64cb26b86d chore: fix newlines in changelog 2025-03-25 20:24:26 +10:00
roflmuffin
637224dc55 ci: fix cliff generation 2025-03-25 20:18:15 +10:00
roflmuffin
3aca7c37f1 ci: add changelog to release & webhook 2025-03-25 20:07:02 +10:00
roflmuffin
87f38d72ee release: v1.0.313 2025-03-25 19:28:06 +10:00
roflmuffin
5daf94791f chore(changelog): update cliff.toml 2025-03-25 19:18:19 +10:00
Michael Wilson
c50213c442 feat(config): add toml loading support (#804) 2025-03-25 19:12:29 +10:00
roflmuffin
c02d31cb2e chore: add links to contributors github page 2025-03-24 19:49:53 +10:00
roflmuffin
98cbca44d4 chore: update changelog to use semantic tags 2025-03-24 19:44:22 +10:00
Michael Wilson
4cf88fc03e fix(gameevents): promote core.gameevents to have higher priority (#819) 2025-03-24 19:32:47 +10:00
Michael Wilson
f1dff6d4d3 chrore: Implement SemVer instead of build numbers (#816) 2025-03-24 19:15:46 +10:00
Michael Wilson
414a59a36d fix(schema): inherited schema classes with clashing properties (#818) 2025-03-24 18:43:41 +10:00
137 changed files with 9359 additions and 7281 deletions

View File

@@ -38,7 +38,7 @@ BraceWrapping:
SplitEmptyNamespace: true
PointerAlignment: Left
SortIncludes: CaseSensitive
SortIncludes: Never
IncludeBlocks: Regroup
IncludeCategories:
# External headers in <> with extension or /

View File

@@ -1,11 +1,20 @@
{
"name": "SteamRT Sniper SDK",
"image": "registry.gitlab.steamos.cloud/steamrt/sniper/sdk:latest",
"customizations": {
"updateContentCommand": "git submodule update --init --recursive",
"postCreateCommand": "cmake -S . -B build -DCMAKE_BUILD_TYPE=RelWithDebInfo && cmake --build build -j$(nproc)",
"customizations": {
"vscode": {
"extensions": [
"ms-vscode.cpptools"
"ms-dotnettools.csdevkit",
"ms-vscode.cpptools",
"ms-vscode.cpptools-extension-pack",
"GitHub.copilot",
"jeff-hykin.better-cpp-syntax"
]
}
},
"features": {
"ghcr.io/devcontainers/features/dotnet": "8.0"
}
}
}

View File

@@ -1,30 +1,45 @@
name: Build & Publish
env:
BUILD_TYPE: Release
# Remove default permissions of GITHUB_TOKEN for security
# https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs
permissions: {}
on:
push:
paths-ignore:
- "docfx/**"
branches: ["main", "dev"]
branches: ["main"]
tags:
- "v*"
pull_request:
branches: ["main", "dev"]
env:
BUILD_TYPE: Release
branches: ["main"]
jobs:
setup:
permissions:
contents: write
runs-on: ubuntu-latest
outputs:
buildnumber: ${{ steps.buildnumber.outputs.build_number }}
gitversion_semver: ${{ steps.gitversion.outputs.semVer }}
gitversion_fullsemver: ${{ steps.gitversion.outputs.fullSemVer }}
gitversion_assemblysemver: ${{ steps.gitversion.outputs.assemblySemVer }}
gitversion_informationalversion: ${{ steps.gitversion.outputs.informationalVersion }}
steps:
- name: Generate build number
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
id: buildnumber
uses: onyxmueller/build-tag-number@v1
with:
token: ${{secrets.github_token}}
- name: Install GitVersion
uses: gittools/actions/gitversion/setup@v1
with:
versionSpec: 6.0.x
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Execute GitVersion
id: gitversion
uses: gittools/actions/gitversion/execute@v1
with:
useConfigFile: true
build_windows:
needs: setup
@@ -32,16 +47,9 @@ jobs:
steps:
- name: Prepare env
shell: bash
run: echo "GITHUB_SHA_SHORT=${GITHUB_SHA::7}" >> $GITHUB_ENV
- name: Fallback build number
if: ${{ github.event_name == 'pull_request' || github.ref != 'refs/heads/main' }}
shell: bash
run: echo "BUILD_NUMBER=0" >> $GITHUB_ENV
- name: Main build number
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
run: echo "BUILD_NUMBER=${{ needs.setup.outputs.buildnumber }}" >> $GITHUB_ENV
run: |
echo "GITHUB_SHA_SHORT=${GITHUB_SHA::7}" >> $GITHUB_ENV
echo "SEMVER=${{ needs.setup.outputs.gitversion_semver }}" >> $GITHUB_ENV
- name: Visual Studio environment
shell: cmd
@@ -56,7 +64,7 @@ jobs:
echo>>"%GITHUB_ENV%" %%a=%%b
)
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
submodules: "recursive"
@@ -76,7 +84,7 @@ jobs:
- uses: actions/upload-artifact@v4
with:
name: counterstrikesharp-build-windows-${{ env.GITHUB_SHA_SHORT }}
name: counterstrikesharp-windows-${{ needs.setup.outputs.gitversion_semver }}
path: build/output/
build_linux:
@@ -88,18 +96,11 @@ jobs:
steps:
- name: Prepare env
shell: bash
run: echo "GITHUB_SHA_SHORT=${GITHUB_SHA::7}" >> $GITHUB_ENV
run: |
echo "GITHUB_SHA_SHORT=${GITHUB_SHA::7}" >> $GITHUB_ENV
echo "SEMVER=${{ needs.setup.outputs.gitversion_semver }}" >> $GITHUB_ENV
- name: Fallback build number
if: ${{ github.event_name == 'pull_request' || github.ref != 'refs/heads/main' }}
shell: bash
run: echo "BUILD_NUMBER=0" >> $GITHUB_ENV
- name: Main build number
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
run: echo "BUILD_NUMBER=${{ needs.setup.outputs.buildnumber }}" >> $GITHUB_ENV
- uses: actions/checkout@v3
- uses: actions/checkout@v4
with:
submodules: "recursive"
@@ -117,7 +118,7 @@ jobs:
- uses: actions/upload-artifact@v4
with:
name: counterstrikesharp-build-linux-${{ env.GITHUB_SHA_SHORT }}
name: counterstrikesharp-linux-${{ needs.setup.outputs.gitversion_semver }}
path: build/output/
build_managed:
@@ -130,20 +131,11 @@ jobs:
shell: bash
run: echo "GITHUB_SHA_SHORT=${GITHUB_SHA::7}" >> $GITHUB_ENV
- name: Fallback build number
if: ${{ github.event_name == 'pull_request' || github.ref != 'refs/heads/main' }}
shell: bash
run: echo "BUILD_NUMBER=0" >> $GITHUB_ENV
- name: Main build number
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
run: echo "BUILD_NUMBER=${{ needs.setup.outputs.buildnumber }}" >> $GITHUB_ENV
# We don't need expensive submodules for the managed side.
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- name: Build runtime v${{ env.BUILD_NUMBER }}
uses: actions/setup-dotnet@v3
- name: Build runtime v${{ needs.setup.outputs.gitversion_semver }}
uses: actions/setup-dotnet@v4
with:
dotnet-version: "8.0.x"
@@ -151,27 +143,36 @@ jobs:
run: dotnet restore managed/CounterStrikeSharp.sln
- name: Run tests
run: dotnet test --logger trx --results-directory "TestResults-${{ env.GITHUB_SHA_SHORT }}" managed/CounterStrikeSharp.API.Tests/CounterStrikeSharp.API.Tests.csproj
run: dotnet test --logger trx --results-directory "TestResults-${{ needs.setup.outputs.gitversion_semver }}" managed/CounterStrikeSharp.API.Tests/CounterStrikeSharp.API.Tests.csproj
- name: Upload dotnet test results
uses: actions/upload-artifact@v4
with:
name: test-results-${{ env.GITHUB_SHA_SHORT }}
path: TestResults-${{ env.GITHUB_SHA_SHORT }}
name: test-results-${{ needs.setup.outputs.gitversion_semver }}
path: TestResults-${{ needs.setup.outputs.gitversion_semver }}
if: ${{ always() }}
- name: Publish artifacts
run: |
dotnet publish -c Release /p:Version=1.0.${{ env.BUILD_NUMBER }} managed/CounterStrikeSharp.API
dotnet pack -c Release /p:Version=1.0.${{ env.BUILD_NUMBER }} managed/CounterStrikeSharp.API
dotnet publish -c Release \
/p:Version=${{ needs.setup.outputs.gitversion_semver }} \
/p:AssemblyVersion=${{ needs.setup.outputs.gitversion_assemblySemver }} \
/p:InformationalVersion=${{ needs.setup.outputs.gitversion_informationalversion }} \
managed/CounterStrikeSharp.API
dotnet pack -c Release \
/p:Version=${{ needs.setup.outputs.gitversion_semver }} \
/p:AssemblyVersion=${{ needs.setup.outputs.gitversion_assemblySemver }} \
/p:InformationalVersion=${{ needs.setup.outputs.gitversion_informationalversion }} \
managed/CounterStrikeSharp.API
- uses: actions/upload-artifact@v4
with:
name: counterstrikesharp-build-api-${{ env.GITHUB_SHA_SHORT }}
name: counterstrikesharp-api-${{ needs.setup.outputs.gitversion_semver }}
path: managed/CounterStrikeSharp.API/bin/Release
publish:
if: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
if: ${{ github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') && github.repository == 'roflmuffin/CounterStrikeSharp' }}
permissions:
contents: write
needs: ["setup", "build_linux", "build_windows", "build_managed"]
@@ -181,19 +182,24 @@ jobs:
shell: bash
run: echo "GITHUB_SHA_SHORT=${GITHUB_SHA::7}" >> $GITHUB_ENV
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- uses: actions/download-artifact@v4
with:
name: counterstrikesharp-build-windows-${{ env.GITHUB_SHA_SHORT }}
name: counterstrikesharp-windows-${{ needs.setup.outputs.gitversion_semver }}
path: build/windows
- uses: actions/download-artifact@v4
with:
name: counterstrikesharp-build-linux-${{ env.GITHUB_SHA_SHORT }}
name: counterstrikesharp-linux-${{ needs.setup.outputs.gitversion_semver }}
path: build/linux
- uses: actions/download-artifact@v4
with:
name: counterstrikesharp-build-api-${{ env.GITHUB_SHA_SHORT }}
name: counterstrikesharp-api-${{ needs.setup.outputs.gitversion_semver }}
path: build/api
# TODO: This stuff should really be in a matrix
@@ -206,8 +212,8 @@ jobs:
- name: Zip Builds
run: |
(cd build/linux && zip -qq -r ../../counterstrikesharp-build-${{ needs.setup.outputs.buildnumber }}-linux-${{ env.GITHUB_SHA_SHORT }}.zip *)
(cd build/windows && zip -qq -r ../../counterstrikesharp-build-${{ needs.setup.outputs.buildnumber }}-windows-${{ env.GITHUB_SHA_SHORT }}.zip *)
(cd build/linux && zip -qq -r ../../counterstrikesharp-linux-${{ needs.setup.outputs.gitversion_semver }}.zip *)
(cd build/windows && zip -qq -r ../../counterstrikesharp-windows-${{ needs.setup.outputs.gitversion_semver }}.zip *)
- name: Add dotnet runtime
run: |
@@ -221,28 +227,44 @@ jobs:
- name: Zip Builds
run: |
(cd build/linux && zip -qq -r ../../counterstrikesharp-with-runtime-build-${{ needs.setup.outputs.buildnumber }}-linux-${{ env.GITHUB_SHA_SHORT }}.zip *)
(cd build/windows && zip -qq -r ../../counterstrikesharp-with-runtime-build-${{ needs.setup.outputs.buildnumber }}-windows-${{ env.GITHUB_SHA_SHORT }}.zip *)
(cd build/linux && zip -qq -r ../../counterstrikesharp-with-runtime-linux-${{ needs.setup.outputs.gitversion_semver }}.zip *)
(cd build/windows && zip -qq -r ../../counterstrikesharp-with-runtime-windows-${{ needs.setup.outputs.gitversion_semver }}.zip *)
- name: Generate a changelog
uses: orhun/git-cliff-action@v4
id: git-cliff
with:
config: cliff.toml
args: --current -s footer
- name: Release
id: release
uses: softprops/action-gh-release@v1
with:
tag_name: v${{ needs.setup.outputs.buildnumber }}
append_body: true
body: |
${{ steps.git-cliff.outputs.content }}
Please refer to [CHANGELOG.md](https://github.com/roflmuffin/CounterStrikeSharp/blob/${{ github.ref_name }}/CHANGELOG.md) for details.
files: |
counterstrikesharp-build-${{ needs.setup.outputs.buildnumber }}-windows-${{ env.GITHUB_SHA_SHORT }}.zip
counterstrikesharp-with-runtime-build-${{ needs.setup.outputs.buildnumber }}-windows-${{ env.GITHUB_SHA_SHORT }}.zip
counterstrikesharp-build-${{ needs.setup.outputs.buildnumber }}-linux-${{ env.GITHUB_SHA_SHORT }}.zip
counterstrikesharp-with-runtime-build-${{ needs.setup.outputs.buildnumber }}-linux-${{ env.GITHUB_SHA_SHORT }}.zip
counterstrikesharp-windows-${{ needs.setup.outputs.gitversion_semver }}.zip
counterstrikesharp-with-runtime-windows-${{ needs.setup.outputs.gitversion_semver }}.zip
counterstrikesharp-linux-${{ needs.setup.outputs.gitversion_semver }}.zip
counterstrikesharp-with-runtime-linux-${{ needs.setup.outputs.gitversion_semver }}.zip
- name: Publish NuGet package
run: |
dotnet nuget push build/api/CounterStrikeSharp.API.1.0.${{ needs.setup.outputs.buildnumber }}.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate
dotnet nuget push build/api/CounterStrikeSharp.API.1.0.${{ needs.setup.outputs.buildnumber }}.snupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate
dotnet nuget push build/api/CounterStrikeSharp.API.${{ needs.setup.outputs.gitversion_semver }}.nupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate
dotnet nuget push build/api/CounterStrikeSharp.API.${{ needs.setup.outputs.gitversion_semver }}.snupkg --api-key ${{ secrets.NUGET_API_KEY }} --source https://api.nuget.org/v3/index.json --skip-duplicate
- name: Send Notification to Discord
env:
DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
uses: Ilshidur/action-discord@0.3.2
with:
args: "A new release of CS# has been tagged (v${{ needs.setup.outputs.buildnumber }}) at ${{ steps.release.outputs.url }}"
args: |
A new release of CS# has been tagged [v${{ needs.setup.outputs.gitversion_semver }}](${{ steps.release.outputs.url }})
${{ steps.git-cliff.outputs.content }}
Please refer to [CHANGELOG.md](https://github.com/roflmuffin/CounterStrikeSharp/blob/${{ github.ref_name }}/CHANGELOG.md) for details.

25
.github/workflows/lint-code.yaml vendored Normal file
View File

@@ -0,0 +1,25 @@
name: Code format checks
on:
pull_request:
paths:
- '.github/workflows/**'
- 'src/**'
- '.clang-format'
push:
paths:
- '.github/workflows/**'
- 'src/**'
- '.clang-format'
jobs:
lint:
name: Lint code with clang-format
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: jidicula/clang-format-action@4726374d1aa3c6aecf132e5197e498979588ebc8
with:
clang-format-version: '20'
check-path: 'src'
exclude-regex: '(sdk|\.proto)'

File diff suppressed because it is too large Load Diff

17
Dockerfile Normal file
View File

@@ -0,0 +1,17 @@
FROM registry.gitlab.steamos.cloud/steamrt/sniper/sdk:latest
WORKDIR /workspace
RUN apt update && apt install -y \
clang-16 \
cmake \
ninja-build \
git \
zlib1g-dev \
libssl-dev \
libprotobuf-dev \
protobuf-compiler \
pkg-config \
curl && \
ln -sf /usr/bin/clang-16 /usr/bin/clang && \
ln -sf /usr/bin/clang++-16 /usr/bin/clang++

1
GitVersion.yml Normal file
View File

@@ -0,0 +1 @@
workflow: GitHubFlow/v1

View File

@@ -1,9 +1,9 @@
# git-cliff ~ configuration file
# https://git-cliff.org/docs/configuration
# [remote.github]
# owner = "roflmuffin"
# repo = "CounterStrikeSharp"
[remote.github]
owner = "roflmuffin"
repo = "CounterStrikeSharp"
# token = ""
[changelog]
@@ -14,17 +14,15 @@ body = """
{%- if version %} in {{ version }}{%- endif -%}
{% for commit in commits %}
{% if commit.remote.pr_title -%}
{%- set commit_message = commit.remote.pr_title -%}
{%- else -%}
{%- set commit_message = commit.message -%}
{%- endif -%}
* {{ commit_message | split(pat="\n") | first | trim }}\
{% if commit.remote.username %} by @{{ commit.remote.username }}{%- endif -%}
* {{ commit.message | split(pat="\n") | first | trim }}\
{% if commit.remote.username and commit.remote.username != remote.github.owner %} by \
[@{{ commit.remote.username }}](https://github.com/{{ commit.remote.username }}) \
{%- endif -%}
{% if commit.remote.pr_number %} in \
[#{{ commit.remote.pr_number }}]({{ self::remote_url() }}/pull/{{ commit.remote.pr_number }}) \
[#{{ commit.remote.pr_number }}]({{ self::remote_url() }}/pull/{{ commit.remote.pr_number }})\
{%- endif %}
([{{ commit.id | truncate(length=7, end="") }}]({{ commit.id }}))
{%- if commit.id %} ([{{ commit.id | truncate(length=7, end="") }}]({{ self::remote_url()}}/commit/{{ commit.id }})){%- endif -%}
{%- endfor -%}
{%- if github -%}
@@ -33,7 +31,7 @@ body = """
## New Contributors
{%- endif %}\
{% for contributor in github.contributors | filter(attribute="is_first_time", value=true) %}
* @{{ contributor.username }} made their first contribution
* [@{{ contributor.username }}](https://github.com/{{ contributor.username }}) made their first contribution
{%- if contributor.pr_number %} in \
[#{{ contributor.pr_number }}]({{ self::remote_url() }}/pull/{{ contributor.pr_number }}) \
{%- endif %}
@@ -70,11 +68,18 @@ filter_unconventional = true
# Split commits on newlines, treating each line as an individual commit.
split_commits = false
# An array of regex based parsers to modify commit messages prior to further processing.
commit_preprocessors = [{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "" }]
commit_preprocessors = [
{ pattern = '\((\w+\s)?#([0-9]+)\)', replace = "" },
{ pattern = '\[no ci\]', replace = "" }
]
commit_parsers = [
{ message = "^release:", skip = true }
]
# Exclude commits that are not matched by any commit parser.
filter_commits = false
# Order releases topologically instead of chronologically.
topo_order = false
# Order of commits in each group/release within the changelog.
# Allowed values: newest, oldest
sort_commits = "newest"
sort_commits = "newest"
tag_pattern = "v[0-9]+\\.[0-9]+\\.[0-9]+"

View File

@@ -84,15 +84,15 @@
"CCSPlayer_WeaponServices_CanUse": {
"signatures": {
"library": "server",
"windows": "48 89 5C 24 ? 48 89 6C 24 ? 56 57 41 56 48 83 EC ? 48 8B 01 48 8B FA",
"linux": "55 48 8D 15 ? ? ? ? 48 89 E5 41 55 49 89 FD 41 54 49 89 F4"
"windows": "48 89 5C 24 ? 48 89 6C 24 ? 48 89 74 24 ? 57 48 83 EC ? 48 8B 01 48 8B F2",
"linux": "55 48 8D 15 ? ? ? ? 48 89 E5 41 55 49 89 F5 41 54 49 89 FC 53 48 83 EC ? 48 8B 07 48 8B 80 ? ? ? ? 48 39 D0 0F 85 ? ? ? ? 80 BF"
}
},
"CCSPlayer_ItemServices_CanAcquire": {
"signatures": {
"library": "server",
"windows": "44 89 44 24 ? 48 89 54 24 ? 48 89 4C 24 ? 55 56 57 41 54 41 55 41 56 41 57 48 8B EC",
"linux": "55 48 89 E5 41 57 41 56 41 55 49 89 CD 41 54 53 48 83 EC"
"linux": "55 48 89 E5 41 57 41 56 48 8D 45 ? 41 55 41 54 53 48 89 CB"
}
},
"GetCSWeaponDataFromKey": {
@@ -267,10 +267,17 @@
"linux": 0
}
},
"CheckTransmit": {
"signatures": {
"library": "server",
"windows": "48 8B C4 4C 89 48 ? 44 89 40 ? 48 89 50 ? 48 89 48 ? 55",
"linux": "55 48 89 E5 41 57 49 89 CF 41 56 41 55 41 54 53 48 81 EC"
}
},
"CheckTransmitPlayerSlot": {
"offsets": {
"windows": 584,
"linux": 584
}
}
}
}

View File

@@ -0,0 +1,99 @@
---
title: Automatically build/deploy your changes
description: Automatically build and deploy plugin changes to a remote development server as you work.
---
# Automatically build and deploy your changes
<sup>Adapted from the
[original guide](https://github.com/uFloppyDisk/create-cssharp-plugin/blob/c8fca43f86a61a5e874624f2f3ed39c5271c9a55/templates/standard-plugin/docs/auto-live-hot-reloading.md).
</sup>
During development of your plugin, you may find yourself repeating a workflow
similar to the following:
1. Make a change to your plugin
2. Run your build task (ex. `dotnet build`)
3. Upload plugin DLLs to your server using an FTP client
4. Alt-tab to the game
5. Test your changes
6. Repeat
Iterating on your plugin this way is painfully slow and impacts your productivity.
Below, you will find a guide and recommendations on how to setup your dev environment
to watch for file changes and automatically update plugin files on your server as you work.
By following this guide, your new workflow should look like this:
1. Make a change to your plugin
2. Alt-tab to the game
3. Test your changes
4. Repeat
> [!CAUTION]
> Exercise caution when developing your plugin while using this workflow.
> Build time errors are mostly caught by .NET SDK before files are committed
> but incomplete implementation may lead to issues such as server crashes.
> Avoid using this workflow on a production server meant for players.
## Setup
#### 1. Build plugin on file changes
The `dotnet` CLI, included with the .NET SDK, offers a convenient command for
automatically watching for source file changes. If you have access to the `dotnet`
CLI, run the following command to start watching your source code.
```shell
dotnet watch build --project path/to/projectName.csproj
```
<sup>By default, `dotnet watch` executes the `dotnet run` command on file changes
so specifying `build` as the first argument is required.</sup>
Your plugin will now build automatically on file change. By default, your builds
should be placed in `bin/<config>/<framework>` in the same directory as your `.csproj`.
```txt
projectDirectory
├── projectName.csproj
├── bin
│   └── Debug
│   └── net8.0
│      └── PLUGIN BUILDS HERE
```
> [!TIP]
> You can have your plugin build to a more convenient location by setting the
> `<OutDir>` build property in your `.csproj` file.
> Example: `<OutDir>./build/$(MSBuildProjectName)</OutDir>`
#### 2. Setup automatic uploads
##### Using WinSCP (Windows only)
Once connected to your server:
1. Go to the `Commands` tab at the top of the WinSCP window
and click `Keep Remote Directory up to Date`.
2. Select the plugin build directory containing your DLLs.
3. Select the plugin destination.
(`csgo/addons/counterstrikesharp/plugins/<projectName>`)
4. Click `Start`
> [!IMPORTANT]
> **For WSL users:**
> Applications running on Windows, such as WinSCP, cannot watch your Linux subsystem for file
> changes. Try using [this workaround](#using-winscp-while-developing-in-wsl) or consider
> moving development to Windows.
##### Using `lsyncd` (Linux)
> **TODO:** in-depth guide for setting up lsyncd
Learn more about `lsyncd`: https://github.com/lsyncd/lsyncd
___
#### Using WinSCP while developing in WSL
Run the following watch command in place of the one mentioned in
[Step 1](#1-build-plugin-on-file-changes) to build to a directory in your Windows filesystem
```shell
dotnet watch build --project path/to/<projectName>.csproj --property:OutDir=/mnt/<drive-letter>/some/path/<projectName>`
```
and have [WinSCP in Step 2](#2-setup-automatic-uploads) watch that path instead.
[Learn about Windows filesystem mounts in WSL](https://blogs.windows.com/windowsdeveloper/2016/07/22/fun-with-the-windows-subsystem-for-linux/#Working%20with%20Windows%20files:~:text=Working%20with%20Windows%20files)

View File

@@ -8,4 +8,7 @@
href: dependency-injection.md
- name: Referencing Players
href: referencing-players.md
href: referencing-players.md
- name: Automatically build and deploy your changes
href: auto-build-and-deploy.md

View File

@@ -1,38 +1,60 @@
using System.Text.Json.Serialization;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes;
namespace WithConfig;
public class SampleConfig : BasePluginConfig
{
[JsonPropertyName("ChatPrefix")] public string ChatPrefix { get; set; } = "My Cool Plugin";
[JsonPropertyName("ChatInterval")] public float ChatInterval { get; set; } = 60;
}
[MinimumApiVersion(80)]
public class WithConfigPlugin : BasePlugin, IPluginConfig<SampleConfig>
{
public override string ModuleName => "Example: With Config";
public override string ModuleVersion => "1.0.0";
public SampleConfig Config { get; set; }
public void OnConfigParsed(SampleConfig config)
{
// Do manual verification of the config and override any invalid values
if (config.ChatInterval > 60)
{
config.ChatInterval = 60;
}
if (config.ChatPrefix.Length > 25)
{
throw new Exception($"Invalid value has been set to config value 'ChatPrefix': {config.ChatPrefix}");
}
// Once we've validated the config, we can set it to the instance
Config = config;
}
}
using System.Text.Json.Serialization;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using CounterStrikeSharp.API.Modules.Admin;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Config;
using CounterStrikeSharp.API.Modules.Extensions;
namespace WithConfig;
public class SampleConfig : BasePluginConfig
{
[JsonPropertyName("ChatPrefix")] public string ChatPrefix { get; set; } = "My Cool Plugin";
[JsonPropertyName("ChatInterval")] public float ChatInterval { get; set; } = 60;
}
[MinimumApiVersion(80)]
public class WithConfigPlugin : BasePlugin, IPluginConfig<SampleConfig>
{
public override string ModuleName => "Example: With Config";
public override string ModuleVersion => "1.0.0";
public SampleConfig Config { get; set; }
public void OnConfigParsed(SampleConfig config)
{
// Do manual verification of the config and override any invalid values
if (config.ChatInterval > 60)
{
config.ChatInterval = 60;
}
if (config.ChatPrefix.Length > 25)
{
throw new Exception($"Invalid value has been set to config value 'ChatPrefix': {config.ChatPrefix}");
}
// Once we've validated the config, we can set it to the instance
Config = config;
}
[ConsoleCommand("css_reload_config", "Reloads the plugin config")]
public void OnReloadConfig(CCSPlayerController? player, CommandInfo commandInfo)
{
commandInfo.ReplyToCommand("Chat Interval before reload: " + Config.ChatInterval);
Config.Reload();
commandInfo.ReplyToCommand("Chat Interval after reload: " + Config.ChatInterval);
}
[ConsoleCommand("css_reset_config", "Resets the plugin config")]
public void OnResetConfig(CCSPlayerController? player, CommandInfo commandInfo)
{
commandInfo.ReplyToCommand("Chat Interval before reset: " + Config.ChatInterval);
Config.ChatInterval = 60;
Config.Update();
commandInfo.ReplyToCommand("Chat Interval after reset: " + Config.ChatInterval);
}
}

View File

@@ -35,10 +35,10 @@ else()
add_definitions(-DGITHUB_SHA="Local")
endif()
if(DEFINED ENV{BUILD_NUMBER})
add_definitions(-DBUILD_NUMBER="$ENV{BUILD_NUMBER}")
if(DEFINED ENV{SEMVER})
add_definitions(-DSEMVER="$ENV{SEMVER}")
else()
add_definitions(-DBUILD_NUMBER="0")
add_definitions(-DSEMVER="Local")
endif()
if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU")
@@ -58,7 +58,6 @@ include_directories(
${SOURCESDK}/public/tier1
${SOURCESDK}/public/entity2
${SOURCESDK}/public/game/server
${SOURCESDK}/public/entity2
${SOURCESDK}/public/schemasystem
${METAMOD_DIR}/core
${METAMOD_DIR}/core/sourcehook

File diff suppressed because it is too large Load Diff

View File

@@ -15,6 +15,7 @@
*/
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
@@ -26,7 +27,7 @@ namespace CounterStrikeSharp.API.Core
/// </summary>
public enum FunctionLifetime
{
/// <summary>Delegate will be removed after the first invocation.</summary>
/// <summary>Delegate will be removed after the first invocation.</summary>
SingleUse,
/// <summary>Delegate will remain in memory for the lifetime of the application (or until <see cref="FunctionReference.Remove"/> is called).</summary>
@@ -57,7 +58,7 @@ namespace CounterStrikeSharp.API.Core
_targetMethod = method;
_nativeCallback = CreateWrappedCallback();
}
/// <summary>
/// <inheritdoc cref="FunctionLifetime"/>
/// </summary>
@@ -73,6 +74,25 @@ namespace CounterStrikeSharp.API.Core
private unsafe CallbackDelegate CreateWrappedCallback()
{
var methodName = _targetMethod.Method.DeclaringType?.FullName + "." + _targetMethod.Method.Name;
var profileName = "ScriptCallback::Execute::" + _targetMethod.Method.Name;
var stackTrace = new StackTrace(2, true);
var firstUserFrame = stackTrace.GetFrames()?.FirstOrDefault(frame =>
{
var declaring = frame.GetMethod()?.DeclaringType?.FullName;
return declaring != null &&
!declaring.StartsWith("CounterStrikeSharp") &&
!declaring.Contains("SafeExecutor") &&
!declaring.Contains("FunctionReference");
});
string caller = firstUserFrame != null
? $"{firstUserFrame.GetMethod()?.DeclaringType?.FullName}.{firstUserFrame.GetMethod()?.Name} @ {firstUserFrame.GetFileName()}:{firstUserFrame.GetFileLineNumber()}"
: "Unknown (no user frame)";
Helpers.RegisterCallbackTrace(methodName, 1, profileName, caller);
return context =>
{
try
@@ -176,4 +196,4 @@ namespace CounterStrikeSharp.API.Core
}
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -29,5 +29,8 @@ namespace CounterStrikeSharp.API.Core
[SecurityCritical]
[DllImport(dllPath, EntryPoint = "InvokeNative")]
public static extern void InvokeNative(IntPtr ptr);
[DllImport(dllPath, EntryPoint = "RegisterCallbackTrace")]
public static extern void RegisterCallbackTrace(string name, int count, string profile, string callerStack);
}
}
}

View File

@@ -58,8 +58,8 @@ public partial class CBaseAnimGraph : CBaseModelEntity
[SchemaMember("CBaseAnimGraph", "m_bRagdollClientSide")]
public ref bool RagdollClientSide => ref Schema.GetRef<bool>(this.Handle, "CBaseAnimGraph", "m_bRagdollClientSide");
// m_nLastDestructiblePartDestroyedAnimgraphSetTick
[SchemaMember("CBaseAnimGraph", "m_nLastDestructiblePartDestroyedAnimgraphSetTick")]
public ref Int32 LastDestructiblePartDestroyedAnimgraphSetTick => ref Schema.GetRef<Int32>(this.Handle, "CBaseAnimGraph", "m_nLastDestructiblePartDestroyedAnimgraphSetTick");
// m_nLastDestructiblePartDestroyedAnimgraphSetTick
[SchemaMember("CBaseAnimGraph", "m_nLastDestructiblePartDestroyedAnimgraphSetTick")]
public ref Int32 LastDestructiblePartDestroyedAnimgraphSetTick => ref Schema.GetRef<Int32>(this.Handle, "CBaseAnimGraph", "m_nLastDestructiblePartDestroyedAnimgraphSetTick");
}

View File

@@ -78,8 +78,8 @@ public partial class CBaseCSGrenadeProjectile : CBaseGrenade
[SchemaMember("CBaseCSGrenadeProjectile", "m_nTicksAtZeroVelocity")]
public ref Int32 TicksAtZeroVelocity => ref Schema.GetRef<Int32>(this.Handle, "CBaseCSGrenadeProjectile", "m_nTicksAtZeroVelocity");
// m_bHasEverHitEnemy
[SchemaMember("CBaseCSGrenadeProjectile", "m_bHasEverHitEnemy")]
public ref bool HasEverHitEnemy => ref Schema.GetRef<bool>(this.Handle, "CBaseCSGrenadeProjectile", "m_bHasEverHitEnemy");
// m_bHasEverHitEnemy
[SchemaMember("CBaseCSGrenadeProjectile", "m_bHasEverHitEnemy")]
public ref bool HasEverHitEnemy => ref Schema.GetRef<bool>(this.Handle, "CBaseCSGrenadeProjectile", "m_bHasEverHitEnemy");
}

View File

@@ -26,34 +26,34 @@ public partial class CBaseModelEntity : CBaseEntity
[SchemaMember("CBaseModelEntity", "m_CHitboxComponent")]
public CHitboxComponent CHitboxComponent => Schema.GetDeclaredClass<CHitboxComponent>(this.Handle, "CBaseModelEntity", "m_CHitboxComponent");
// m_nDestructiblePartInitialStateDestructed0
[SchemaMember("CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed0")]
public ref HitGroup_t DestructiblePartInitialStateDestructed0 => ref Schema.GetRef<HitGroup_t>(this.Handle, "CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed0");
// m_nDestructiblePartInitialStateDestructed1
[SchemaMember("CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed1")]
public ref HitGroup_t DestructiblePartInitialStateDestructed1 => ref Schema.GetRef<HitGroup_t>(this.Handle, "CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed1");
// m_nDestructiblePartInitialStateDestructed2
[SchemaMember("CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed2")]
public ref HitGroup_t DestructiblePartInitialStateDestructed2 => ref Schema.GetRef<HitGroup_t>(this.Handle, "CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed2");
// m_nDestructiblePartInitialStateDestructed3
[SchemaMember("CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed3")]
public ref HitGroup_t DestructiblePartInitialStateDestructed3 => ref Schema.GetRef<HitGroup_t>(this.Handle, "CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed3");
// m_nDestructiblePartInitialStateDestructed4
[SchemaMember("CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed4")]
public ref HitGroup_t DestructiblePartInitialStateDestructed4 => ref Schema.GetRef<HitGroup_t>(this.Handle, "CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed4");
// m_nLastHitDestructiblePartIndex
[SchemaMember("CBaseModelEntity", "m_nLastHitDestructiblePartIndex")]
public ref Int32 LastHitDestructiblePartIndex => ref Schema.GetRef<Int32>(this.Handle, "CBaseModelEntity", "m_nLastHitDestructiblePartIndex");
// m_LastHitGroup
[SchemaMember("CBaseModelEntity", "m_LastHitGroup")]
public ref HitGroup_t LastHitGroup => ref Schema.GetRef<HitGroup_t>(this.Handle, "CBaseModelEntity", "m_LastHitGroup");
// m_nDestructiblePartInitialStateDestructed0
[SchemaMember("CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed0")]
public ref HitGroup_t DestructiblePartInitialStateDestructed0 => ref Schema.GetRef<HitGroup_t>(this.Handle, "CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed0");
// m_nDestructiblePartInitialStateDestructed1
[SchemaMember("CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed1")]
public ref HitGroup_t DestructiblePartInitialStateDestructed1 => ref Schema.GetRef<HitGroup_t>(this.Handle, "CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed1");
// m_nDestructiblePartInitialStateDestructed2
[SchemaMember("CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed2")]
public ref HitGroup_t DestructiblePartInitialStateDestructed2 => ref Schema.GetRef<HitGroup_t>(this.Handle, "CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed2");
// m_nDestructiblePartInitialStateDestructed3
[SchemaMember("CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed3")]
public ref HitGroup_t DestructiblePartInitialStateDestructed3 => ref Schema.GetRef<HitGroup_t>(this.Handle, "CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed3");
// m_nDestructiblePartInitialStateDestructed4
[SchemaMember("CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed4")]
public ref HitGroup_t DestructiblePartInitialStateDestructed4 => ref Schema.GetRef<HitGroup_t>(this.Handle, "CBaseModelEntity", "m_nDestructiblePartInitialStateDestructed4");
// m_nLastHitDestructiblePartIndex
[SchemaMember("CBaseModelEntity", "m_nLastHitDestructiblePartIndex")]
public ref Int32 LastHitDestructiblePartIndex => ref Schema.GetRef<Int32>(this.Handle, "CBaseModelEntity", "m_nLastHitDestructiblePartIndex");
// m_LastHitGroup
[SchemaMember("CBaseModelEntity", "m_LastHitGroup")]
public ref HitGroup_t LastHitGroup => ref Schema.GetRef<HitGroup_t>(this.Handle, "CBaseModelEntity", "m_LastHitGroup");
// m_flDissolveStartTime
[SchemaMember("CBaseModelEntity", "m_flDissolveStartTime")]
public ref float DissolveStartTime => ref Schema.GetRef<float>(this.Handle, "CBaseModelEntity", "m_flDissolveStartTime");
@@ -96,7 +96,7 @@ public partial class CBaseModelEntity : CBaseEntity
// m_Collision
[SchemaMember("CBaseModelEntity", "m_Collision")]
public CCollisionProperty Collision => Schema.GetDeclaredClass<CCollisionProperty>(this.Handle, "CBaseModelEntity", "m_Collision");
public new CCollisionProperty Collision => Schema.GetDeclaredClass<CCollisionProperty>(this.Handle, "CBaseModelEntity", "m_Collision");
// m_Glow
[SchemaMember("CBaseModelEntity", "m_Glow")]

View File

@@ -82,10 +82,6 @@ public partial class CBasePlayerController : CBaseEntity
[SchemaMember("CBasePlayerController", "m_bPredict")]
public ref bool Predict => ref Schema.GetRef<bool>(this.Handle, "CBasePlayerController", "m_bPredict");
// m_bAutoKickDisabled
[SchemaMember("CBasePlayerController", "m_bAutoKickDisabled")]
public ref bool AutoKickDisabled => ref Schema.GetRef<bool>(this.Handle, "CBasePlayerController", "m_bAutoKickDisabled");
// m_bIsLowViolence
[SchemaMember("CBasePlayerController", "m_bIsLowViolence")]
public ref bool IsLowViolence => ref Schema.GetRef<bool>(this.Handle, "CBasePlayerController", "m_bIsLowViolence");

View File

@@ -52,7 +52,7 @@ public partial class CBasePropDoor : CDynamicProp
// m_hBlocker
[SchemaMember("CBasePropDoor", "m_hBlocker")]
public CHandle<CBaseEntity> Blocker => Schema.GetDeclaredClass<CHandle<CBaseEntity>>(this.Handle, "CBasePropDoor", "m_hBlocker");
public new CHandle<CBaseEntity> Blocker => Schema.GetDeclaredClass<CHandle<CBaseEntity>>(this.Handle, "CBasePropDoor", "m_hBlocker");
// m_bFirstBlocked
[SchemaMember("CBasePropDoor", "m_bFirstBlocked")]

View File

@@ -88,7 +88,7 @@ public partial class CBeam : CBaseModelEntity
// m_fSpeed
[SchemaMember("CBeam", "m_fSpeed")]
public ref float Speed => ref Schema.GetRef<float>(this.Handle, "CBeam", "m_fSpeed");
public new ref float Speed => ref Schema.GetRef<float>(this.Handle, "CBeam", "m_fSpeed");
// m_flFrame
[SchemaMember("CBeam", "m_flFrame")]

View File

@@ -20,6 +20,6 @@ public partial class CBodyComponentPoint : CBodyComponent
// m_sceneNode
[SchemaMember("CBodyComponentPoint", "m_sceneNode")]
public CGameSceneNode SceneNode => Schema.GetDeclaredClass<CGameSceneNode>(this.Handle, "CBodyComponentPoint", "m_sceneNode");
public new CGameSceneNode SceneNode => Schema.GetDeclaredClass<CGameSceneNode>(this.Handle, "CBodyComponentPoint", "m_sceneNode");
}

View File

@@ -1,21 +0,0 @@
// <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CBreachCharge : CCSWeaponBase
{
public CBreachCharge (IntPtr pointer) : base(pointer) {}
}

View File

@@ -1,21 +0,0 @@
// <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CBreachChargeProjectile : CBaseGrenade
{
public CBreachChargeProjectile (IntPtr pointer) : base(pointer) {}
}

View File

@@ -1,21 +0,0 @@
// <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CBumpMine : CCSWeaponBase
{
public CBumpMine (IntPtr pointer) : base(pointer) {}
}

View File

@@ -1,21 +0,0 @@
// <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CBumpMineProjectile : CBaseGrenade
{
public CBumpMineProjectile (IntPtr pointer) : base(pointer) {}
}

View File

@@ -286,10 +286,6 @@ public partial class CCSGameRules : CTeamplayRules
[SchemaMember("CCSGameRules", "m_flNextRespawnWave")]
public Span<float> NextRespawnWave => Schema.GetFixedArray<float>(this.Handle, "CCSGameRules", "m_flNextRespawnWave", 32);
// m_nServerQuestID
[SchemaMember("CCSGameRules", "m_nServerQuestID")]
public ref Int32 ServerQuestID => ref Schema.GetRef<Int32>(this.Handle, "CCSGameRules", "m_nServerQuestID");
// m_vMinimapMins
[SchemaMember("CCSGameRules", "m_vMinimapMins")]
public Vector MinimapMins => Schema.GetDeclaredClass<Vector>(this.Handle, "CCSGameRules", "m_vMinimapMins");
@@ -306,6 +302,10 @@ public partial class CCSGameRules : CTeamplayRules
[SchemaMember("CCSGameRules", "m_bSpawnedTerrorHuntHeavy")]
public ref bool SpawnedTerrorHuntHeavy => ref Schema.GetRef<bool>(this.Handle, "CCSGameRules", "m_bSpawnedTerrorHuntHeavy");
// m_ullLocalMatchID
[SchemaMember("CCSGameRules", "m_ullLocalMatchID")]
public ref UInt64 UllLocalMatchID => ref Schema.GetRef<UInt64>(this.Handle, "CCSGameRules", "m_ullLocalMatchID");
// m_nEndMatchMapGroupVoteTypes
[SchemaMember("CCSGameRules", "m_nEndMatchMapGroupVoteTypes")]
public Span<Int32> EndMatchMapGroupVoteTypes => Schema.GetFixedArray<Int32>(this.Handle, "CCSGameRules", "m_nEndMatchMapGroupVoteTypes", 10);

View File

@@ -42,6 +42,10 @@ public partial class CCSPlayerController : CBasePlayerController
[SchemaMember("CCSPlayerController", "m_bHasCommunicationAbuseMute")]
public ref bool HasCommunicationAbuseMute => ref Schema.GetRef<bool>(this.Handle, "CCSPlayerController", "m_bHasCommunicationAbuseMute");
// m_uiCommunicationMuteFlags
[SchemaMember("CCSPlayerController", "m_uiCommunicationMuteFlags")]
public ref UInt32 UiCommunicationMuteFlags => ref Schema.GetRef<UInt32>(this.Handle, "CCSPlayerController", "m_uiCommunicationMuteFlags");
// m_szCrosshairCodes
[SchemaMember("CCSPlayerController", "m_szCrosshairCodes")]
public string CrosshairCodes
@@ -98,10 +102,10 @@ public partial class CCSPlayerController : CBasePlayerController
[SchemaMember("CCSPlayerController", "m_bRemoveAllItemsOnNextRoundReset")]
public ref bool RemoveAllItemsOnNextRoundReset => ref Schema.GetRef<bool>(this.Handle, "CCSPlayerController", "m_bRemoveAllItemsOnNextRoundReset");
// m_flLastJoinTeamTime
[SchemaMember("CCSPlayerController", "m_flLastJoinTeamTime")]
public ref float LastJoinTeamTime => ref Schema.GetRef<float>(this.Handle, "CCSPlayerController", "m_flLastJoinTeamTime");
// m_flLastJoinTeamTime
[SchemaMember("CCSPlayerController", "m_flLastJoinTeamTime")]
public ref float LastJoinTeamTime => ref Schema.GetRef<float>(this.Handle, "CCSPlayerController", "m_flLastJoinTeamTime");
// m_szClan
[SchemaMember("CCSPlayerController", "m_szClan")]
public string Clan
@@ -162,6 +166,10 @@ public partial class CCSPlayerController : CBasePlayerController
[SchemaMember("CCSPlayerController", "m_unActiveQuestId")]
public ref UInt16 ActiveQuestId => ref Schema.GetRef<UInt16>(this.Handle, "CCSPlayerController", "m_unActiveQuestId");
// m_rtActiveMissionPeriod
[SchemaMember("CCSPlayerController", "m_rtActiveMissionPeriod")]
public ref UInt32 RtActiveMissionPeriod => ref Schema.GetRef<UInt32>(this.Handle, "CCSPlayerController", "m_rtActiveMissionPeriod");
// m_unPlayerTvControlFlags
[SchemaMember("CCSPlayerController", "m_unPlayerTvControlFlags")]
public ref UInt32 PlayerTvControlFlags => ref Schema.GetRef<UInt32>(this.Handle, "CCSPlayerController", "m_unPlayerTvControlFlags");
@@ -178,6 +186,10 @@ public partial class CCSPlayerController : CBasePlayerController
[SchemaMember("CCSPlayerController", "m_uiAbandonRecordedReason")]
public ref UInt32 UiAbandonRecordedReason => ref Schema.GetRef<UInt32>(this.Handle, "CCSPlayerController", "m_uiAbandonRecordedReason");
// m_eNetworkDisconnectionReason
[SchemaMember("CCSPlayerController", "m_eNetworkDisconnectionReason")]
public ref UInt32 NetworkDisconnectionReason => ref Schema.GetRef<UInt32>(this.Handle, "CCSPlayerController", "m_eNetworkDisconnectionReason");
// m_bCannotBeKicked
[SchemaMember("CCSPlayerController", "m_bCannotBeKicked")]
public ref bool CannotBeKicked => ref Schema.GetRef<bool>(this.Handle, "CCSPlayerController", "m_bCannotBeKicked");
@@ -294,17 +306,17 @@ public partial class CCSPlayerController : CBasePlayerController
[SchemaMember("CCSPlayerController", "m_iRoundsWon")]
public ref Int32 RoundsWon => ref Schema.GetRef<Int32>(this.Handle, "CCSPlayerController", "m_iRoundsWon");
// m_recentKillQueue
[SchemaMember("CCSPlayerController", "m_recentKillQueue")]
public Span<byte> RecentKillQueue => Schema.GetFixedArray<byte>(this.Handle, "CCSPlayerController", "m_recentKillQueue", 8);
// m_nFirstKill
[SchemaMember("CCSPlayerController", "m_nFirstKill")]
public ref byte FirstKill => ref Schema.GetRef<byte>(this.Handle, "CCSPlayerController", "m_nFirstKill");
// m_nKillCount
[SchemaMember("CCSPlayerController", "m_nKillCount")]
public ref byte KillCount => ref Schema.GetRef<byte>(this.Handle, "CCSPlayerController", "m_nKillCount");
// m_recentKillQueue
[SchemaMember("CCSPlayerController", "m_recentKillQueue")]
public Span<byte> RecentKillQueue => Schema.GetFixedArray<byte>(this.Handle, "CCSPlayerController", "m_recentKillQueue", 8);
// m_nFirstKill
[SchemaMember("CCSPlayerController", "m_nFirstKill")]
public ref byte FirstKill => ref Schema.GetRef<byte>(this.Handle, "CCSPlayerController", "m_nFirstKill");
// m_nKillCount
[SchemaMember("CCSPlayerController", "m_nKillCount")]
public ref byte KillCount => ref Schema.GetRef<byte>(this.Handle, "CCSPlayerController", "m_nKillCount");
// m_bMvpNoMusic
[SchemaMember("CCSPlayerController", "m_bMvpNoMusic")]
@@ -382,8 +394,8 @@ public partial class CCSPlayerController : CBasePlayerController
[SchemaMember("CCSPlayerController", "m_nNonSuspiciousHitStreak")]
public ref UInt32 NonSuspiciousHitStreak => ref Schema.GetRef<UInt32>(this.Handle, "CCSPlayerController", "m_nNonSuspiciousHitStreak");
// m_bFireBulletsSeedSynchronized
[SchemaMember("CCSPlayerController", "m_bFireBulletsSeedSynchronized")]
public ref bool FireBulletsSeedSynchronized => ref Schema.GetRef<bool>(this.Handle, "CCSPlayerController", "m_bFireBulletsSeedSynchronized");
// m_bFireBulletsSeedSynchronized
[SchemaMember("CCSPlayerController", "m_bFireBulletsSeedSynchronized")]
public ref bool FireBulletsSeedSynchronized => ref Schema.GetRef<bool>(this.Handle, "CCSPlayerController", "m_bFireBulletsSeedSynchronized");
}

View File

@@ -170,12 +170,12 @@ public partial class CCSPlayer_MovementServices : CPlayer_MovementServices_Human
[SchemaMember("CCSPlayer_MovementServices", "m_flMaxJumpHeightLastJump")]
public ref float MaxJumpHeightLastJump => ref Schema.GetRef<float>(this.Handle, "CCSPlayer_MovementServices", "m_flMaxJumpHeightLastJump");
// m_flStaminaAtJumpStart
[SchemaMember("CCSPlayer_MovementServices", "m_flStaminaAtJumpStart")]
public ref float StaminaAtJumpStart => ref Schema.GetRef<float>(this.Handle, "CCSPlayer_MovementServices", "m_flStaminaAtJumpStart");
// m_flAccumulatedJumpError
[SchemaMember("CCSPlayer_MovementServices", "m_flAccumulatedJumpError")]
public ref float AccumulatedJumpError => ref Schema.GetRef<float>(this.Handle, "CCSPlayer_MovementServices", "m_flAccumulatedJumpError");
// m_flStaminaAtJumpStart
[SchemaMember("CCSPlayer_MovementServices", "m_flStaminaAtJumpStart")]
public ref float StaminaAtJumpStart => ref Schema.GetRef<float>(this.Handle, "CCSPlayer_MovementServices", "m_flStaminaAtJumpStart");
// m_flAccumulatedJumpError
[SchemaMember("CCSPlayer_MovementServices", "m_flAccumulatedJumpError")]
public ref float AccumulatedJumpError => ref Schema.GetRef<float>(this.Handle, "CCSPlayer_MovementServices", "m_flAccumulatedJumpError");
}

View File

@@ -86,10 +86,6 @@ public partial class CCSWeaponBase : CBasePlayerWeapon
[SchemaMember("CCSWeaponBase", "m_flLastTimeInAir")]
public ref float LastTimeInAir => ref Schema.GetRef<float>(this.Handle, "CCSWeaponBase", "m_flLastTimeInAir");
// m_flLastDeployTime
[SchemaMember("CCSWeaponBase", "m_flLastDeployTime")]
public ref float LastDeployTime => ref Schema.GetRef<float>(this.Handle, "CCSWeaponBase", "m_flLastDeployTime");
// m_nLastEmptySoundCmdNum
[SchemaMember("CCSWeaponBase", "m_nLastEmptySoundCmdNum")]
public ref Int32 LastEmptySoundCmdNum => ref Schema.GetRef<Int32>(this.Handle, "CCSWeaponBase", "m_nLastEmptySoundCmdNum");
@@ -222,10 +218,10 @@ public partial class CCSWeaponBase : CBasePlayerWeapon
[SchemaMember("CCSWeaponBase", "m_nextPrevOwnerTouchTime")]
public ref float NextPrevOwnerTouchTime => ref Schema.GetRef<float>(this.Handle, "CCSWeaponBase", "m_nextPrevOwnerTouchTime");
// m_nextPrevOwnerUseTime
[SchemaMember("CCSWeaponBase", "m_nextPrevOwnerUseTime")]
public ref float NextPrevOwnerUseTime => ref Schema.GetRef<float>(this.Handle, "CCSWeaponBase", "m_nextPrevOwnerUseTime");
// m_nextPrevOwnerUseTime
[SchemaMember("CCSWeaponBase", "m_nextPrevOwnerUseTime")]
public ref float NextPrevOwnerUseTime => ref Schema.GetRef<float>(this.Handle, "CCSWeaponBase", "m_nextPrevOwnerUseTime");
// m_hPrevOwner
[SchemaMember("CCSWeaponBase", "m_hPrevOwner")]
public CHandle<CCSPlayerPawn> PrevOwner => Schema.GetDeclaredClass<CHandle<CCSPlayerPawn>>(this.Handle, "CCSWeaponBase", "m_hPrevOwner");

View File

@@ -58,10 +58,10 @@ public partial class CDamageRecord : NativeObject
[SchemaMember("CDamageRecord", "m_RecipientXuid")]
public ref UInt64 RecipientXuid => ref Schema.GetRef<UInt64>(this.Handle, "CDamageRecord", "m_RecipientXuid");
// m_iBulletsDamage
[SchemaMember("CDamageRecord", "m_iBulletsDamage")]
public ref Int32 BulletsDamage => ref Schema.GetRef<Int32>(this.Handle, "CDamageRecord", "m_iBulletsDamage");
// m_iBulletsDamage
[SchemaMember("CDamageRecord", "m_iBulletsDamage")]
public ref Int32 BulletsDamage => ref Schema.GetRef<Int32>(this.Handle, "CDamageRecord", "m_iBulletsDamage");
// m_iDamage
[SchemaMember("CDamageRecord", "m_iDamage")]
public ref Int32 Damage => ref Schema.GetRef<Int32>(this.Handle, "CDamageRecord", "m_iDamage");

View File

@@ -36,7 +36,7 @@ public partial class CEnvBeam : CBeam
// m_iszEndEntity
[SchemaMember("CEnvBeam", "m_iszEndEntity")]
public string EndEntity
public new string EndEntity
{
get { return Schema.GetUtf8String(this.Handle, "CEnvBeam", "m_iszEndEntity"); }
set { Schema.SetString(this.Handle, "CEnvBeam", "m_iszEndEntity", value); }
@@ -56,7 +56,7 @@ public partial class CEnvBeam : CBeam
// m_speed
[SchemaMember("CEnvBeam", "m_speed")]
public ref Int32 Speed => ref Schema.GetRef<Int32>(this.Handle, "CEnvBeam", "m_speed");
public new ref Int32 Speed => ref Schema.GetRef<Int32>(this.Handle, "CEnvBeam", "m_speed");
// m_restrike
[SchemaMember("CEnvBeam", "m_restrike")]

View File

@@ -44,6 +44,6 @@ public partial class CEnvLaser : CBeam
// m_flStartFrame
[SchemaMember("CEnvLaser", "m_flStartFrame")]
public ref float StartFrame => ref Schema.GetRef<float>(this.Handle, "CEnvLaser", "m_flStartFrame");
public new ref float StartFrame => ref Schema.GetRef<float>(this.Handle, "CEnvLaser", "m_flStartFrame");
}

View File

@@ -14,7 +14,7 @@ using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CEnvSoundscape : CBaseEntity
public partial class CEnvSoundscape : CBaseEntity
{
public CEnvSoundscape (IntPtr pointer) : base(pointer) {}
@@ -58,16 +58,16 @@ public partial class CEnvSoundscape : CBaseEntity
[SchemaMember("CEnvSoundscape", "m_bDisabled")]
public ref bool Disabled => ref Schema.GetRef<bool>(this.Handle, "CEnvSoundscape", "m_bDisabled");
// m_soundscapeName
[SchemaMember("CEnvSoundscape", "m_soundscapeName")]
public string SoundscapeName
{
get { return Schema.GetUtf8String(this.Handle, "CEnvSoundscape", "m_soundscapeName"); }
set { Schema.SetString(this.Handle, "CEnvSoundscape", "m_soundscapeName", value); }
}
// m_soundEventHash
[SchemaMember("CEnvSoundscape", "m_soundEventHash")]
public ref UInt32 SoundEventHash => ref Schema.GetRef<UInt32>(this.Handle, "CEnvSoundscape", "m_soundEventHash");
// m_soundscapeName
[SchemaMember("CEnvSoundscape", "m_soundscapeName")]
public string SoundscapeName
{
get { return Schema.GetUtf8String(this.Handle, "CEnvSoundscape", "m_soundscapeName"); }
set { Schema.SetString(this.Handle, "CEnvSoundscape", "m_soundscapeName", value); }
}
// m_soundEventHash
[SchemaMember("CEnvSoundscape", "m_soundEventHash")]
public ref UInt32 SoundEventHash => ref Schema.GetRef<UInt32>(this.Handle, "CEnvSoundscape", "m_soundEventHash");
}

View File

@@ -64,7 +64,7 @@ public partial class CFish : CBaseAnimGraph
// m_speed
[SchemaMember("CFish", "m_speed")]
public ref float Speed => ref Schema.GetRef<float>(this.Handle, "CFish", "m_speed");
public new ref float Speed => ref Schema.GetRef<float>(this.Handle, "CFish", "m_speed");
// m_desiredSpeed
[SchemaMember("CFish", "m_desiredSpeed")]

View File

@@ -32,7 +32,7 @@ public partial class CFishPool : CBaseEntity
// m_waterLevel
[SchemaMember("CFishPool", "m_waterLevel")]
public ref float WaterLevel => ref Schema.GetRef<float>(this.Handle, "CFishPool", "m_waterLevel");
public new ref float WaterLevel => ref Schema.GetRef<float>(this.Handle, "CFishPool", "m_waterLevel");
// m_isDormant
[SchemaMember("CFishPool", "m_isDormant")]

View File

@@ -1,49 +0,0 @@
// <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CFists : CCSWeaponBase
{
public CFists (IntPtr pointer) : base(pointer) {}
// m_bPlayingUninterruptableAct
[SchemaMember("CFists", "m_bPlayingUninterruptableAct")]
public ref bool PlayingUninterruptableAct => ref Schema.GetRef<bool>(this.Handle, "CFists", "m_bPlayingUninterruptableAct");
// m_nUninterruptableActivity
[SchemaMember("CFists", "m_nUninterruptableActivity")]
public ref PlayerAnimEvent_t UninterruptableActivity => ref Schema.GetRef<PlayerAnimEvent_t>(this.Handle, "CFists", "m_nUninterruptableActivity");
// m_bRestorePrevWep
[SchemaMember("CFists", "m_bRestorePrevWep")]
public ref bool RestorePrevWep => ref Schema.GetRef<bool>(this.Handle, "CFists", "m_bRestorePrevWep");
// m_hWeaponBeforePrevious
[SchemaMember("CFists", "m_hWeaponBeforePrevious")]
public CHandle<CBasePlayerWeapon> WeaponBeforePrevious => Schema.GetDeclaredClass<CHandle<CBasePlayerWeapon>>(this.Handle, "CFists", "m_hWeaponBeforePrevious");
// m_hWeaponPrevious
[SchemaMember("CFists", "m_hWeaponPrevious")]
public CHandle<CBasePlayerWeapon> WeaponPrevious => Schema.GetDeclaredClass<CHandle<CBasePlayerWeapon>>(this.Handle, "CFists", "m_hWeaponPrevious");
// m_bDelayedHardPunchIncoming
[SchemaMember("CFists", "m_bDelayedHardPunchIncoming")]
public ref bool DelayedHardPunchIncoming => ref Schema.GetRef<bool>(this.Handle, "CFists", "m_bDelayedHardPunchIncoming");
// m_bDestroyAfterTaunt
[SchemaMember("CFists", "m_bDestroyAfterTaunt")]
public ref bool DestroyAfterTaunt => ref Schema.GetRef<bool>(this.Handle, "CFists", "m_bDestroyAfterTaunt");
}

View File

@@ -44,7 +44,7 @@ public partial class CFuncMover : CBaseModelEntity
// m_eMoveType
[SchemaMember("CFuncMover", "m_eMoveType")]
public ref CFuncMoverMove_t MoveType => ref Schema.GetRef<CFuncMoverMove_t>(this.Handle, "CFuncMover", "m_eMoveType");
public new ref CFuncMoverMove_t MoveType => ref Schema.GetRef<CFuncMoverMove_t>(this.Handle, "CFuncMover", "m_eMoveType");
// m_bIsReversing
[SchemaMember("CFuncMover", "m_bIsReversing")]
@@ -52,7 +52,7 @@ public partial class CFuncMover : CBaseModelEntity
// m_vTarget
[SchemaMember("CFuncMover", "m_vTarget")]
public Vector Target => Schema.GetDeclaredClass<Vector>(this.Handle, "CFuncMover", "m_vTarget");
public new Vector Target => Schema.GetDeclaredClass<Vector>(this.Handle, "CFuncMover", "m_vTarget");
// m_flStartSpeed
[SchemaMember("CFuncMover", "m_flStartSpeed")]

View File

@@ -44,6 +44,6 @@ public partial class CInstancedSceneEntity : CSceneEntity
// m_hTarget
[SchemaMember("CInstancedSceneEntity", "m_hTarget")]
public CHandle<CBaseEntity> Target => Schema.GetDeclaredClass<CHandle<CBaseEntity>>(this.Handle, "CInstancedSceneEntity", "m_hTarget");
public new CHandle<CBaseEntity> Target => Schema.GetDeclaredClass<CHandle<CBaseEntity>>(this.Handle, "CInstancedSceneEntity", "m_hTarget");
}

View File

@@ -52,7 +52,7 @@ public partial class CLogicMeasureMovement : CLogicalEntity
// m_hTarget
[SchemaMember("CLogicMeasureMovement", "m_hTarget")]
public CHandle<CBaseEntity> Target => Schema.GetDeclaredClass<CHandle<CBaseEntity>>(this.Handle, "CLogicMeasureMovement", "m_hTarget");
public new CHandle<CBaseEntity> Target => Schema.GetDeclaredClass<CHandle<CBaseEntity>>(this.Handle, "CLogicMeasureMovement", "m_hTarget");
// m_hTargetReference
[SchemaMember("CLogicMeasureMovement", "m_hTargetReference")]

View File

@@ -50,8 +50,8 @@ public partial class CMapInfo : CPointEntity
[SchemaMember("CMapInfo", "m_bFadePlayerVisibilityFarZ")]
public ref bool FadePlayerVisibilityFarZ => ref Schema.GetRef<bool>(this.Handle, "CMapInfo", "m_bFadePlayerVisibilityFarZ");
// m_bRainTraceToSkyEnabled
[SchemaMember("CMapInfo", "m_bRainTraceToSkyEnabled")]
public ref bool RainTraceToSkyEnabled => ref Schema.GetRef<bool>(this.Handle, "CMapInfo", "m_bRainTraceToSkyEnabled");
// m_bRainTraceToSkyEnabled
[SchemaMember("CMapInfo", "m_bRainTraceToSkyEnabled")]
public ref bool RainTraceToSkyEnabled => ref Schema.GetRef<bool>(this.Handle, "CMapInfo", "m_bRainTraceToSkyEnabled");
}

View File

@@ -1,21 +0,0 @@
// <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CMelee : CCSWeaponBase
{
public CMelee (IntPtr pointer) : base(pointer) {}
}

View File

@@ -20,7 +20,7 @@ public partial class CPointEntityFinder : CBaseEntity
// m_hEntity
[SchemaMember("CPointEntityFinder", "m_hEntity")]
public CHandle<CBaseEntity> Entity => Schema.GetDeclaredClass<CHandle<CBaseEntity>>(this.Handle, "CPointEntityFinder", "m_hEntity");
public new CHandle<CBaseEntity> Entity => Schema.GetDeclaredClass<CHandle<CBaseEntity>>(this.Handle, "CPointEntityFinder", "m_hEntity");
// m_iFilterName
[SchemaMember("CPointEntityFinder", "m_iFilterName")]

View File

@@ -34,14 +34,14 @@ public partial class CPointWorldText : CModelPointEntity
set { Schema.SetStringBytes(this.Handle, "CPointWorldText", "m_FontName", value, 64); }
}
// m_BackgroundMaterialName
[SchemaMember("CPointWorldText", "m_BackgroundMaterialName")]
public string BackgroundMaterialName
{
get { return Schema.GetString(this.Handle, "CPointWorldText", "m_BackgroundMaterialName"); }
set { Schema.SetStringBytes(this.Handle, "CPointWorldText", "m_BackgroundMaterialName", value, 64); }
}
// m_BackgroundMaterialName
[SchemaMember("CPointWorldText", "m_BackgroundMaterialName")]
public string BackgroundMaterialName
{
get { return Schema.GetString(this.Handle, "CPointWorldText", "m_BackgroundMaterialName"); }
set { Schema.SetStringBytes(this.Handle, "CPointWorldText", "m_BackgroundMaterialName", value, 64); }
}
// m_bEnabled
[SchemaMember("CPointWorldText", "m_bEnabled")]
public ref bool Enabled => ref Schema.GetRef<bool>(this.Handle, "CPointWorldText", "m_bEnabled");
@@ -62,22 +62,22 @@ public partial class CPointWorldText : CModelPointEntity
[SchemaMember("CPointWorldText", "m_flDepthOffset")]
public ref float DepthOffset => ref Schema.GetRef<float>(this.Handle, "CPointWorldText", "m_flDepthOffset");
// m_bDrawBackground
[SchemaMember("CPointWorldText", "m_bDrawBackground")]
public ref bool DrawBackground => ref Schema.GetRef<bool>(this.Handle, "CPointWorldText", "m_bDrawBackground");
// m_flBackgroundBorderWidth
[SchemaMember("CPointWorldText", "m_flBackgroundBorderWidth")]
public ref float BackgroundBorderWidth => ref Schema.GetRef<float>(this.Handle, "CPointWorldText", "m_flBackgroundBorderWidth");
// m_flBackgroundBorderHeight
[SchemaMember("CPointWorldText", "m_flBackgroundBorderHeight")]
public ref float BackgroundBorderHeight => ref Schema.GetRef<float>(this.Handle, "CPointWorldText", "m_flBackgroundBorderHeight");
// m_flBackgroundWorldToUV
[SchemaMember("CPointWorldText", "m_flBackgroundWorldToUV")]
public ref float BackgroundWorldToUV => ref Schema.GetRef<float>(this.Handle, "CPointWorldText", "m_flBackgroundWorldToUV");
// m_bDrawBackground
[SchemaMember("CPointWorldText", "m_bDrawBackground")]
public ref bool DrawBackground => ref Schema.GetRef<bool>(this.Handle, "CPointWorldText", "m_bDrawBackground");
// m_flBackgroundBorderWidth
[SchemaMember("CPointWorldText", "m_flBackgroundBorderWidth")]
public ref float BackgroundBorderWidth => ref Schema.GetRef<float>(this.Handle, "CPointWorldText", "m_flBackgroundBorderWidth");
// m_flBackgroundBorderHeight
[SchemaMember("CPointWorldText", "m_flBackgroundBorderHeight")]
public ref float BackgroundBorderHeight => ref Schema.GetRef<float>(this.Handle, "CPointWorldText", "m_flBackgroundBorderHeight");
// m_flBackgroundWorldToUV
[SchemaMember("CPointWorldText", "m_flBackgroundWorldToUV")]
public ref float BackgroundWorldToUV => ref Schema.GetRef<float>(this.Handle, "CPointWorldText", "m_flBackgroundWorldToUV");
// m_Color
[SchemaMember("CPointWorldText", "m_Color")]
public Color Color

View File

@@ -60,7 +60,7 @@ public partial class CPostProcessingVolume : CBaseTrigger
// m_bMaster
[SchemaMember("CPostProcessingVolume", "m_bMaster")]
public ref bool Master => ref Schema.GetRef<bool>(this.Handle, "CPostProcessingVolume", "m_bMaster");
public new ref bool Master => ref Schema.GetRef<bool>(this.Handle, "CPostProcessingVolume", "m_bMaster");
// m_bExposureControl
[SchemaMember("CPostProcessingVolume", "m_bExposureControl")]

View File

@@ -30,8 +30,8 @@ public partial class CRagdollManager : CBaseEntity
[SchemaMember("CRagdollManager", "m_bSaveImportant")]
public ref bool SaveImportant => ref Schema.GetRef<bool>(this.Handle, "CRagdollManager", "m_bSaveImportant");
// m_bCanTakeDamage
[SchemaMember("CRagdollManager", "m_bCanTakeDamage")]
public ref bool CanTakeDamage => ref Schema.GetRef<bool>(this.Handle, "CRagdollManager", "m_bCanTakeDamage");
// m_bCanTakeDamage
[SchemaMember("CRagdollManager", "m_bCanTakeDamage")]
public ref bool CanTakeDamage => ref Schema.GetRef<bool>(this.Handle, "CRagdollManager", "m_bCanTakeDamage");
}

View File

@@ -68,7 +68,7 @@ public partial class CScriptedSequence : CBaseEntity
// m_iszEntity
[SchemaMember("CScriptedSequence", "m_iszEntity")]
public string Entity
public new string Entity
{
get { return Schema.GetUtf8String(this.Handle, "CScriptedSequence", "m_iszEntity"); }
set { Schema.SetString(this.Handle, "CScriptedSequence", "m_iszEntity", value); }

View File

@@ -1,21 +0,0 @@
// <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CSensorGrenade : CBaseCSGrenade
{
public CSensorGrenade (IntPtr pointer) : base(pointer) {}
}

View File

@@ -1,33 +0,0 @@
// <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CSensorGrenadeProjectile : CBaseCSGrenadeProjectile
{
public CSensorGrenadeProjectile (IntPtr pointer) : base(pointer) {}
// m_fExpireTime
[SchemaMember("CSensorGrenadeProjectile", "m_fExpireTime")]
public ref float ExpireTime => ref Schema.GetRef<float>(this.Handle, "CSensorGrenadeProjectile", "m_fExpireTime");
// m_fNextDetectPlayerSound
[SchemaMember("CSensorGrenadeProjectile", "m_fNextDetectPlayerSound")]
public ref float NextDetectPlayerSound => ref Schema.GetRef<float>(this.Handle, "CSensorGrenadeProjectile", "m_fNextDetectPlayerSound");
// m_hDisplayGrenade
[SchemaMember("CSensorGrenadeProjectile", "m_hDisplayGrenade")]
public CHandle<CBaseEntity> DisplayGrenade => Schema.GetDeclaredClass<CHandle<CBaseEntity>>(this.Handle, "CSensorGrenadeProjectile", "m_hDisplayGrenade");
}

View File

@@ -42,14 +42,14 @@ public partial class CSmokeGrenadeProjectile : CBaseCSGrenadeProjectile
[SchemaMember("CSmokeGrenadeProjectile", "m_VoxelFrameData")]
public NetworkedVector<byte> VoxelFrameData => Schema.GetDeclaredClass<NetworkedVector<byte>>(this.Handle, "CSmokeGrenadeProjectile", "m_VoxelFrameData");
// m_nVoxelFrameDataSize
[SchemaMember("CSmokeGrenadeProjectile", "m_nVoxelFrameDataSize")]
public ref Int32 VoxelFrameDataSize => ref Schema.GetRef<Int32>(this.Handle, "CSmokeGrenadeProjectile", "m_nVoxelFrameDataSize");
// m_nVoxelUpdate
[SchemaMember("CSmokeGrenadeProjectile", "m_nVoxelUpdate")]
public ref Int32 VoxelUpdate => ref Schema.GetRef<Int32>(this.Handle, "CSmokeGrenadeProjectile", "m_nVoxelUpdate");
// m_nVoxelFrameDataSize
[SchemaMember("CSmokeGrenadeProjectile", "m_nVoxelFrameDataSize")]
public ref Int32 VoxelFrameDataSize => ref Schema.GetRef<Int32>(this.Handle, "CSmokeGrenadeProjectile", "m_nVoxelFrameDataSize");
// m_nVoxelUpdate
[SchemaMember("CSmokeGrenadeProjectile", "m_nVoxelUpdate")]
public ref Int32 VoxelUpdate => ref Schema.GetRef<Int32>(this.Handle, "CSmokeGrenadeProjectile", "m_nVoxelUpdate");
// m_flLastBounce
[SchemaMember("CSmokeGrenadeProjectile", "m_flLastBounce")]
public ref float LastBounce => ref Schema.GetRef<float>(this.Handle, "CSmokeGrenadeProjectile", "m_flLastBounce");

View File

@@ -1,21 +0,0 @@
// <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CTablet : CCSWeaponBase
{
public CTablet (IntPtr pointer) : base(pointer) {}
}

View File

@@ -20,7 +20,7 @@ public partial class CTriggerPhysics : CBaseTrigger
// m_gravityScale
[SchemaMember("CTriggerPhysics", "m_gravityScale")]
public ref float GravityScale => ref Schema.GetRef<float>(this.Handle, "CTriggerPhysics", "m_gravityScale");
public new ref float GravityScale => ref Schema.GetRef<float>(this.Handle, "CTriggerPhysics", "m_gravityScale");
// m_linearLimit
[SchemaMember("CTriggerPhysics", "m_linearLimit")]

View File

@@ -1,21 +0,0 @@
// <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CTriggerTripWire : CBaseTrigger
{
public CTriggerTripWire (IntPtr pointer) : base(pointer) {}
}

View File

@@ -1,21 +0,0 @@
// <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CTripWireFire : CBaseCSGrenade
{
public CTripWireFire (IntPtr pointer) : base(pointer) {}
}

View File

@@ -1,21 +0,0 @@
// <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CTripWireFireProjectile : CBaseGrenade
{
public CTripWireFireProjectile (IntPtr pointer) : base(pointer) {}
}

View File

@@ -1,33 +0,0 @@
// <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CWeaponShield : CCSWeaponBaseGun
{
public CWeaponShield (IntPtr pointer) : base(pointer) {}
// m_flBulletDamageAbsorbed
[SchemaMember("CWeaponShield", "m_flBulletDamageAbsorbed")]
public ref float BulletDamageAbsorbed => ref Schema.GetRef<float>(this.Handle, "CWeaponShield", "m_flBulletDamageAbsorbed");
// m_flLastBulletHitSoundTime
[SchemaMember("CWeaponShield", "m_flLastBulletHitSoundTime")]
public ref float LastBulletHitSoundTime => ref Schema.GetRef<float>(this.Handle, "CWeaponShield", "m_flLastBulletHitSoundTime");
// m_flDisplayHealth
[SchemaMember("CWeaponShield", "m_flDisplayHealth")]
public ref float DisplayHealth => ref Schema.GetRef<float>(this.Handle, "CWeaponShield", "m_flDisplayHealth");
}

View File

@@ -1,21 +0,0 @@
// <auto-generated />
#nullable enable
#pragma warning disable CS1591
using System;
using System.Diagnostics;
using System.Drawing;
using CounterStrikeSharp;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
using CounterStrikeSharp.API.Core.Attributes;
namespace CounterStrikeSharp.API.Core;
public partial class CWeaponZoneRepulsor : CCSWeaponBaseGun
{
public CWeaponZoneRepulsor (IntPtr pointer) : base(pointer) {}
}

View File

@@ -13,17 +13,9 @@ public enum CSPlayerBlockingUseAction_t : uint
k_CSPlayerBlockingUseAction_DefusingWithKit = 0x2,
k_CSPlayerBlockingUseAction_HostageGrabbing = 0x3,
k_CSPlayerBlockingUseAction_HostageDropping = 0x4,
k_CSPlayerBlockingUseAction_OpeningSafe = 0x5,
k_CSPlayerBlockingUseAction_EquippingParachute = 0x6,
k_CSPlayerBlockingUseAction_EquippingHeavyArmor = 0x7,
k_CSPlayerBlockingUseAction_EquippingContract = 0x8,
k_CSPlayerBlockingUseAction_EquippingTabletUpgrade = 0x9,
k_CSPlayerBlockingUseAction_TakingOffHeavyArmor = 0xA,
k_CSPlayerBlockingUseAction_PayingToOpenDoor = 0xB,
k_CSPlayerBlockingUseAction_CancelingSpawnRappelling = 0xC,
k_CSPlayerBlockingUseAction_EquippingExoJump = 0xD,
k_CSPlayerBlockingUseAction_PickingUpBumpMine = 0xE,
k_CSPlayerBlockingUseAction_MapLongUseEntity_Pickup = 0xF,
k_CSPlayerBlockingUseAction_MapLongUseEntity_Place = 0x10,
k_CSPlayerBlockingUseAction_MaxCount = 0x11,
k_CSPlayerBlockingUseAction_EquippingHeavyArmor = 0x5,
k_CSPlayerBlockingUseAction_TakingOffHeavyArmor = 0x6,
k_CSPlayerBlockingUseAction_MapLongUseEntity_Pickup = 0x7,
k_CSPlayerBlockingUseAction_MapLongUseEntity_Place = 0x8,
k_CSPlayerBlockingUseAction_MaxCount = 0x9,
}

View File

@@ -8,7 +8,7 @@ namespace CounterStrikeSharp.API.Core;
public enum CSWeaponType : uint
{
WEAPONTYPE_KNIFE = 0x0,
WEAPONTYPE_KNIFE = 0x0,
WEAPONTYPE_PISTOL = 0x1,
WEAPONTYPE_SUBMACHINEGUN = 0x2,
WEAPONTYPE_RIFLE = 0x3,

View File

@@ -13,7 +13,5 @@ public enum GrenadeType_t : uint
GRENADE_TYPE_FIRE = 0x2,
GRENADE_TYPE_DECOY = 0x3,
GRENADE_TYPE_SMOKE = 0x4,
GRENADE_TYPE_SENSOR = 0x5,
GRENADE_TYPE_SNOWBALL = 0x6,
GRENADE_TYPE_TOTAL = 0x7,
GRENADE_TYPE_TOTAL = 0x5,
}

View File

@@ -25,6 +25,7 @@
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

View File

@@ -39,6 +39,7 @@
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.0"/>
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0"/>
<PackageReference Include="System.Data.DataSetExtensions" Version="4.5.0"/>
<PackageReference Include="Tomlyn" Version="0.19.0"/>
</ItemGroup>
<ItemGroup>
<Folder Include="Core\Schema\"/>
@@ -59,9 +60,9 @@
</PropertyGroup>
<Target Name="SetSourceRevisionId" BeforeTargets="InitializeSourceControlInformation">
<Exec
Command="git describe --long --always --exclude=* --abbrev=7"
ConsoleToMSBuild="True"
IgnoreExitCode="False"
Command="git describe --long --always --exclude=* --abbrev=7"
ConsoleToMSBuild="True"
IgnoreExitCode="False"
>
<Output PropertyName="SourceRevisionId" TaskParameter="ConsoleOutput"/>
</Exec>

View File

@@ -14,18 +14,21 @@
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Text.Json;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Logging;
using Microsoft.Extensions.Logging;
using Tomlyn;
namespace CounterStrikeSharp.API.Modules.Config
{
enum ConfigType
{
Json,
Toml
}
public static class ConfigManager
{
private static readonly DirectoryInfo? _rootDir;
@@ -33,47 +36,59 @@ namespace CounterStrikeSharp.API.Modules.Config
private static readonly string _pluginConfigsFolderPath;
private static ILogger _logger = CoreLogging.Factory.CreateLogger("ConfigManager");
internal static JsonSerializerOptions JsonSerializerOptions { get; } = new()
{
WriteIndented = true,
ReadCommentHandling = JsonCommentHandling.Skip
};
internal static TomlModelOptions TomlModelOptions { get; } = new()
{
ConvertPropertyName = name => name
};
static ConfigManager()
{
_rootDir = new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.Parent;
_pluginConfigsFolderPath = Path.Combine(_rootDir.FullName, "configs", "plugins");
}
public static T Load<T>(string pluginName) where T : IBasePluginConfig, new()
public static T Load<T>(string pluginName) where T : class, IBasePluginConfig, new()
{
string directoryPath = Path.Combine(_pluginConfigsFolderPath, pluginName);
string configPath = Path.Combine(directoryPath, $"{pluginName}.json");
string exampleConfigPath = Path.Combine(directoryPath, $"{pluginName}.example.json");
string configPath = Path.Combine(directoryPath, $"{pluginName}");
string exampleConfigPath = Path.Combine(directoryPath, $"{pluginName}.example");
T config = (T)Activator.CreateInstance(typeof(T))!;
string[] configFilePaths =
[
$"{configPath}.toml",
$"{configPath}.json",
];
if (!File.Exists(configPath) && !File.Exists(exampleConfigPath))
foreach (var path in configFilePaths)
{
try
if (File.Exists(path))
{
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
return Deserialize<T>(path);
}
}
StringBuilder builder = new StringBuilder();
builder.Append(
$"// This configuration was automatically generated by CounterStrikeSharp for plugin '{pluginName}', at {DateTimeOffset.Now:yyyy/MM/dd hh:mm:ss}\n");
builder.Append(JsonSerializer.Serialize<T>(config,
new JsonSerializerOptions { WriteIndented = true }));
File.WriteAllText(configPath, builder.ToString());
return config;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to generate configuration file for {PluginName}", pluginName);
}
} else if (File.Exists(exampleConfigPath) && !File.Exists(configPath))
string[] exampleFilePaths =
[
$"{exampleConfigPath}.toml",
$"{exampleConfigPath}.json"
];
foreach (var path in exampleFilePaths)
{
if (!File.Exists(path)) continue;
try
{
_logger.LogInformation("Copying example configuration file for {PluginName}", pluginName);
File.Copy(exampleConfigPath, configPath);
var destPath = Path.Combine(directoryPath, Path.GetFileName(path).Replace(".example", ""));
File.Copy(path, destPath);
return Deserialize<T>(destPath);
}
catch (Exception ex)
{
@@ -83,14 +98,58 @@ namespace CounterStrikeSharp.API.Modules.Config
try
{
config = JsonSerializer.Deserialize<T>(File.ReadAllText(configPath), new JsonSerializerOptions() { ReadCommentHandling = JsonCommentHandling.Skip })!;
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
var config = new T();
var output = Serialize(config, ConfigType.Json, pluginName);
File.WriteAllText(Path.Combine(directoryPath, $"{pluginName}.json"), output);
return config;
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to parse configuration file for {PluginName}", pluginName);
_logger.LogError(ex, "Failed to generate configuration file for {PluginName}", pluginName);
return new T();
}
}
private static T Deserialize<T>(string path) where T : class, IBasePluginConfig, new()
{
switch (Path.GetExtension(path))
{
case ".toml":
return Toml.ToModel<T>(File.ReadAllText(path), options: TomlModelOptions);
case ".json":
return JsonSerializer.Deserialize<T>(File.ReadAllText(path), JsonSerializerOptions)!;
}
return config;
throw new NotSupportedException("Unsupported configuration file format");
}
private static string Serialize<T>(T config, ConfigType configType, string pluginName) where T : class, IBasePluginConfig, new()
{
StringBuilder builder = new StringBuilder();
string comment =
$"This configuration was automatically generated by CounterStrikeSharp for plugin '{pluginName}', at {DateTimeOffset.Now:yyyy/MM/dd hh:mm:ss}\n";
switch (configType)
{
case ConfigType.Json:
builder.Append($"// {comment}");
builder.Append(JsonSerializer.Serialize<T>(config, JsonSerializerOptions));
break;
case ConfigType.Toml:
builder.Append($"# {comment}");
builder.Append(Toml.FromModel(config, options: TomlModelOptions));
break;
default:
throw new NotSupportedException("Unsupported configuration file format");
}
return builder.ToString();
}
}
}
}

View File

@@ -0,0 +1,41 @@
using System;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Modules.Entities;
namespace CounterStrikeSharp.API.Modules.Events
{
[EventName("player_chat")]
public class EventPlayerChat : GameEvent
{
public EventPlayerChat(IntPtr pointer) : base(pointer){}
public EventPlayerChat(bool force) : base("player_chat", force){}
/// <summary>
/// If this chat message was sent to team only
/// </summary>
public bool Teamonly
{
get => Get<bool>("teamonly");
set => Set<bool>("teamonly", value);
}
/// <summary>
/// The user ID of the player who sent the chat message
/// </summary>
public int Userid
{
get => Get<int>("userid");
set => Set<int>("userid", value);
}
/// <summary>
/// The text content of the chat message
/// </summary>
public string Text
{
get => Get<string>("text");
set => Set<string>("text", value);
}
}
}

View File

@@ -1,17 +1,14 @@
using System.Text.Json;
using System.Reflection;
using System.Runtime.Serialization;
using CounterStrikeSharp.API.Modules.Config;
using Tomlyn;
namespace CounterStrikeSharp.API.Modules.Extensions;
public static class PluginConfigExtensions
{
private static readonly JsonSerializerOptions _jsonSerializerOptions = new()
{
WriteIndented = true,
ReadCommentHandling = JsonCommentHandling.Skip
};
public static JsonSerializerOptions JsonSerializerOptions => _jsonSerializerOptions;
public static JsonSerializerOptions JsonSerializerOptions => ConfigManager.JsonSerializerOptions;
/// <summary>
/// Gets the configuration file path
@@ -21,7 +18,24 @@ public static class PluginConfigExtensions
public static string GetConfigPath<T>(this T _) where T : BasePluginConfig, new()
{
string assemblyName = typeof(T).Assembly.GetName().Name ?? string.Empty;
return Path.Combine(Server.GameDirectory, "csgo", "addons", "counterstrikesharp", "configs", "plugins", assemblyName, $"{assemblyName}.json");
string[] configFilePaths =
[
Path.Combine(Server.GameDirectory, "csgo", "addons", "counterstrikesharp", "configs", "plugins", assemblyName,
$"{assemblyName}.json"),
Path.Combine(Server.GameDirectory, "csgo", "addons", "counterstrikesharp", "configs", "plugins", assemblyName,
$"{assemblyName}.toml"),
];
foreach (var path in configFilePaths)
{
if (File.Exists(path))
{
return path;
}
}
return configFilePaths[0];
}
/// <summary>
@@ -37,7 +51,22 @@ public static class PluginConfigExtensions
{
using var stream = new FileStream(configPath, FileMode.Create, FileAccess.Write, FileShare.None);
using var writer = new StreamWriter(stream);
writer.Write(JsonSerializer.Serialize(config, JsonSerializerOptions));
switch (Path.GetExtension(configPath))
{
case ".json":
{
writer.Write(JsonSerializer.Serialize(config, ConfigManager.JsonSerializerOptions));
break;
}
case ".toml":
writer.Write(Toml.FromModel(config, ConfigManager.TomlModelOptions));
break;
default:
throw new NotSupportedException($"Configuration file type '{Path.GetExtension(configPath)}' is not supported.");
}
}
catch (Exception ex)
{
@@ -63,8 +92,22 @@ public static class PluginConfigExtensions
var configContent = File.ReadAllText(configPath);
var newConfig = JsonSerializer.Deserialize<T>(configContent, JsonSerializerOptions)
?? throw new JsonException($"Deserialization failed for configuration file '{configPath}'.");
T? newConfig = null;
switch (Path.GetExtension(configPath))
{
case ".json":
newConfig = JsonSerializer.Deserialize<T>(configContent, ConfigManager.JsonSerializerOptions)
?? throw new JsonException($"Deserialization failed for configuration file '{configPath}'.");
break;
case ".toml":
newConfig = Toml.ToModel<T>(configContent, options: ConfigManager.TomlModelOptions);
break;
}
if (newConfig is null)
{
throw new SerializationException($"Deserialization failed for configuration file '{configPath}'.");
}
foreach (var property in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public))
{

View File

@@ -124,6 +124,9 @@ public abstract class BaseMenuInstance : IMenuInstance
var menuItemIndex = CurrentOffset + desiredValue - 1;
if (Menu?.MenuOptions == null)
return;
if (menuItemIndex >= 0 && menuItemIndex < Menu.MenuOptions.Count)
{
var menuOption = Menu.MenuOptions[menuItemIndex];

View File

@@ -43,6 +43,8 @@ namespace CounterStrikeSharp.API
Bullrush = (1 << 21),
Grenade1 = (1 << 22), /** grenade 1 */
Grenade2 = (1 << 23), /** grenade 2 */
Attack3 = (1 << 24)
Attack3 = (1 << 24),
Scoreboard = ((ulong)1 << 33),
Inspect = ((ulong)1 << 35),
}
}

View File

@@ -26,12 +26,8 @@ public static class NetworkClasses
"CBaseViewModel",
"CBeam",
"CBombTarget",
"CBreachCharge",
"CBreachChargeProjectile",
"CBreakable",
"CBreakableProp",
"CBumpMine",
"CBumpMineProjectile",
"CC4",
"CChicken",
"CColorCorrection",
@@ -83,7 +79,6 @@ public static class NetworkClasses
"CFireCrackerBlast",
"CFireSmoke",
"CFish",
"CFists",
"CFlashbang",
"CFogController",
"CFootstepControl",
@@ -120,7 +115,6 @@ public static class NetworkClasses
"CLightOrthoEntity",
"CLightSpotEntity",
"CMapVetoPickController",
"CMelee",
"CModelPointEntity",
"CMolotovGrenade",
"CMolotovProjectile",
@@ -153,8 +147,6 @@ public static class NetworkClasses
"CRectLight",
"CRopeKeyframe",
"CSceneEntity",
"CSensorGrenade",
"CSensorGrenadeProjectile",
"CShatterGlassShardPhysics",
"CSkyCamera",
"CSmokeGrenade",
@@ -172,15 +164,11 @@ public static class NetworkClasses
"CSprite",
"CSpriteOriented",
"CSun",
"CTablet",
"CTeam",
"CTextureBasedAnimatable",
"CTonemapController2",
"CTriggerBuoyancy",
"CTriggerTripWire",
"CTriggerVolume",
"CTripWireFire",
"CTripWireFireProjectile",
"CVoteController",
"CWaterBullet",
"CWeaponAug",
@@ -207,13 +195,11 @@ public static class NetworkClasses
"CWeaponSawedoff",
"CWeaponSCAR20",
"CWeaponSG556",
"CWeaponShield",
"CWeaponSSG08",
"CWeaponTaser",
"CWeaponTec9",
"CWeaponUMP45",
"CWeaponXM1014",
"CWeaponZoneRepulsor",
"CWorld",
};
}

View File

@@ -104,7 +104,7 @@ internal static partial class Program
if (IgnoreClasses.Contains(className))
continue;
allClasses[className] = schemaClass;
allClasses[className] = schemaClass with { Name = className };
}
}
@@ -174,7 +174,7 @@ internal static partial class Program
{
search.Compute(networkClassName);
}
// Clear output directory
if (Directory.Exists(outputPath))
{
@@ -194,7 +194,7 @@ internal static partial class Program
var newBuilder = new StringBuilder(enumBuilder.ToString());
WriteEnum(newBuilder, enumName, schemaEnum);
File.WriteAllText(Path.Combine(outputPath, "Enums", $"{SanitiseTypeName(enumName)}.g.cs"),
newBuilder.ToString());
newBuilder.ToString().ReplaceLineEndings("\r\n"));
}
// Manually whitelist some classes
@@ -217,20 +217,39 @@ internal static partial class Program
var isPointeeType = pointeeTypes.Contains(className);
var newBuilder = new StringBuilder(classBuilder.ToString());
WriteClass(newBuilder, className, schemaClass, parentToChildMap, isPointeeType);
WriteClass(newBuilder, className, schemaClass, allClasses, isPointeeType);
visitedClassNames.Add(className);
File.WriteAllText(Path.Combine(outputPath, "Classes", $"{SanitiseTypeName(className)}.g.cs"),
newBuilder.ToString());
newBuilder.ToString().ReplaceLineEndings("\r\n"));
}
}
}
private static IEnumerable<(SchemaClass clazz, SchemaField field)> GetAllParentFields(
SchemaClass schemaClass,
SortedDictionary<string, SchemaClass> allClasses)
{
while (schemaClass.Parent != null)
{
allClasses.TryGetValue(schemaClass.Parent, out var parentClass);
if (parentClass == null)
break;
foreach (var field in parentClass.Fields)
{
yield return (parentClass, field);
}
schemaClass = parentClass;
}
}
private static void WriteClass(
StringBuilder builder,
string schemaClassName,
SchemaClass schemaClass,
IReadOnlyDictionary<string, ImmutableList<KeyValuePair<string, SchemaClass>>> parentToChildMap,
SortedDictionary<string, SchemaClass> allClasses,
bool isPointeeType)
{
var isEntityClass =
@@ -242,8 +261,12 @@ internal static partial class Program
builder.AppendLine();
builder.Append($"public partial class {classNameCs}");
(SchemaClass clazz, SchemaField field)[] parentFields = [];
if (schemaClass.Parent != null)
{
builder.Append($" : {schemaClass.Parent}");
parentFields = GetAllParentFields(schemaClass, allClasses).ToArray();
}
if (schemaClass.Parent == null)
{
@@ -276,6 +299,8 @@ internal static partial class Program
if (IgnoreClasses.Contains(field.Type.Inner!.Name)) continue;
}
var requiresNewKeyword = parentFields.Any(x => x.clazz.CsPropertyNameForField(x.clazz.Name, x.field) == schemaClass.CsPropertyNameForField(schemaClassName, field));
var handleParams = $"this.Handle, \"{schemaClassName}\", \"{field.Name}\"";
builder.AppendLine($"\t// {field.Name}");
@@ -286,7 +311,7 @@ internal static partial class Program
var getter = $"return Schema.GetString({handleParams});";
var setter = $"Schema.SetString({handleParams}, value{(field.Type.ArraySize != null ? ", " + field.Type.ArraySize : "")});";
builder.AppendLine(
$"\tpublic {SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)}");
$"\tpublic {(requiresNewKeyword ? "new ": "")}{SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)}");
builder.AppendLine($"\t{{");
builder.AppendLine(
$"\t\tget {{ {getter} }}");
@@ -301,7 +326,7 @@ internal static partial class Program
var getter = $"return Schema.GetString({handleParams});";
var setter = $"Schema.SetStringBytes({handleParams}, value, {field.Type.ArraySize});";
builder.AppendLine(
$"\tpublic {SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)}");
$"\tpublic {(requiresNewKeyword ? "new ": "")}{SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)}");
builder.AppendLine($"\t{{");
builder.AppendLine(
$"\t\tget {{ {getter} }}");
@@ -316,7 +341,7 @@ internal static partial class Program
var getter = $"return Schema.GetUtf8String({handleParams});";
var setter = $"Schema.SetString({handleParams}, value);";
builder.AppendLine(
$"\tpublic {SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)}");
$"\tpublic {(requiresNewKeyword ? "new ": "")}{SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)}");
builder.AppendLine($"\t{{");
builder.AppendLine(
$"\t\tget {{ {getter} }}");
@@ -330,7 +355,7 @@ internal static partial class Program
var getter =
$"Schema.GetFixedArray<{SanitiseTypeName(field.Type.Inner!.CsTypeName)}>({handleParams}, {field.Type.ArraySize});";
builder.AppendLine(
$"\tpublic Span<{SanitiseTypeName(field.Type.Inner!.CsTypeName)}> {schemaClass.CsPropertyNameForField(schemaClassName, field)} => {getter}");
$"\tpublic {(requiresNewKeyword ? "new ": "")}Span<{SanitiseTypeName(field.Type.Inner!.CsTypeName)}> {schemaClass.CsPropertyNameForField(schemaClassName, field)} => {getter}");
builder.AppendLine();
}
else if (field.Type.Category == SchemaTypeCategory.DeclaredClass &&
@@ -338,7 +363,7 @@ internal static partial class Program
{
var getter = $"Schema.GetDeclaredClass<{SanitiseTypeName(field.Type.CsTypeName)}>({handleParams});";
builder.AppendLine(
$"\tpublic {SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)} => {getter}");
$"\tpublic {(requiresNewKeyword ? "new ": "")}{SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)} => {getter}");
builder.AppendLine();
}
else if ((field.Type.Category == SchemaTypeCategory.Builtin ||
@@ -347,7 +372,7 @@ internal static partial class Program
{
var getter = $"ref Schema.GetRef<{SanitiseTypeName(field.Type.CsTypeName)}>({handleParams});";
builder.AppendLine(
$"\tpublic ref {SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)} => {getter}");
$"\tpublic {(requiresNewKeyword ? "new ": "")}ref {SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)} => {getter}");
builder.AppendLine();
}
else if (field.Type.Category == SchemaTypeCategory.Ptr)
@@ -356,7 +381,7 @@ internal static partial class Program
if (inner.Category != SchemaTypeCategory.DeclaredClass) continue;
builder.AppendLine(
$"\tpublic {SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)} => Schema.GetPointer<{SanitiseTypeName(inner.CsTypeName)}>({handleParams});");
$"\tpublic {(requiresNewKeyword ? "new ": "")}{SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)} => Schema.GetPointer<{SanitiseTypeName(inner.CsTypeName)}>({handleParams});");
builder.AppendLine();
}
else if (field.Type is { Category: SchemaTypeCategory.Atomic, Name: "Color" })
@@ -364,7 +389,7 @@ internal static partial class Program
var getter = $"return Schema.GetCustomMarshalledType<{field.Type.CsTypeName}>({handleParams});";
var setter = $"Schema.SetCustomMarshalledType<{field.Type.CsTypeName}>({handleParams}, value);";
builder.AppendLine(
$"\tpublic {SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)}");
$"\tpublic {(requiresNewKeyword ? "new ": "")}{SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)}");
builder.AppendLine($"\t{{");
builder.AppendLine(
$"\t\tget {{ {getter} }}");
@@ -377,7 +402,7 @@ internal static partial class Program
{
var getter = $"Schema.GetDeclaredClass<{SanitiseTypeName(field.Type.CsTypeName)}>({handleParams});";
builder.AppendLine(
$"\tpublic {SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)} => {getter}");
$"\tpublic {(requiresNewKeyword ? "new ": "")}{SanitiseTypeName(field.Type.CsTypeName)} {schemaClass.CsPropertyNameForField(schemaClassName, field)} => {getter}");
builder.AppendLine();
}
}
@@ -425,4 +450,4 @@ internal static partial class Program
builder.AppendLine("}");
}
}
}

View File

@@ -7614,13 +7614,6 @@
"name": "bool"
}
},
{
"name": "m_bAutoKickDisabled",
"type": {
"category": 0,
"name": "bool"
}
},
{
"name": "m_bIsLowViolence",
"type": {
@@ -10570,14 +10563,6 @@
}
]
},
"CBreachCharge": {
"fields": [],
"parent": "CCSWeaponBase"
},
"CBreachChargeProjectile": {
"fields": [],
"parent": "CBaseGrenade"
},
"CBreakable": {
"fields": [
{
@@ -11320,14 +11305,6 @@
],
"parent": "CBaseModelEntity"
},
"CBumpMine": {
"fields": [],
"parent": "CCSWeaponBase"
},
"CBumpMineProjectile": {
"fields": [],
"parent": "CBaseGrenade"
},
"CBuoyancyHelper": {
"fields": [
{
@@ -13259,13 +13236,6 @@
"name": "GameTime_t[32]"
}
},
{
"name": "m_nServerQuestID",
"type": {
"category": 0,
"name": "int32"
}
},
{
"name": "m_vMinimapMins",
"type": {
@@ -13300,6 +13270,13 @@
"name": "bool"
}
},
{
"name": "m_ullLocalMatchID",
"type": {
"category": 0,
"name": "uint64"
}
},
{
"name": "m_nEndMatchMapGroupVoteTypes",
"type": {
@@ -14430,6 +14407,13 @@
"name": "bool"
}
},
{
"name": "m_uiCommunicationMuteFlags",
"type": {
"category": 0,
"name": "uint32"
}
},
{
"name": "m_szCrosshairCodes",
"type": {
@@ -14625,6 +14609,13 @@
"name": "uint16"
}
},
{
"name": "m_rtActiveMissionPeriod",
"type": {
"category": 0,
"name": "uint32"
}
},
{
"name": "m_nQuestProgressReason",
"type": {
@@ -14660,6 +14651,13 @@
"name": "uint32"
}
},
{
"name": "m_eNetworkDisconnectionReason",
"type": {
"category": 0,
"name": "uint32"
}
},
{
"name": "m_bCannotBeKicked",
"type": {
@@ -17468,13 +17466,6 @@
"name": "GameTime_t"
}
},
{
"name": "m_flLastDeployTime",
"type": {
"category": 5,
"name": "GameTime_t"
}
},
{
"name": "m_nLastEmptySoundCmdNum",
"type": {
@@ -26474,72 +26465,6 @@
],
"parent": "CBaseEntity"
},
"CFists": {
"fields": [
{
"name": "m_bPlayingUninterruptableAct",
"type": {
"category": 0,
"name": "bool"
}
},
{
"name": "m_nUninterruptableActivity",
"type": {
"category": 6,
"name": "PlayerAnimEvent_t"
}
},
{
"name": "m_bRestorePrevWep",
"type": {
"category": 0,
"name": "bool"
}
},
{
"name": "m_hWeaponBeforePrevious",
"type": {
"atomic": 1,
"category": 4,
"inner": {
"category": 5,
"name": "CBasePlayerWeapon"
},
"name": "CHandle< CBasePlayerWeapon >",
"outer": "CHandle"
}
},
{
"name": "m_hWeaponPrevious",
"type": {
"atomic": 1,
"category": 4,
"inner": {
"category": 5,
"name": "CBasePlayerWeapon"
},
"name": "CHandle< CBasePlayerWeapon >",
"outer": "CHandle"
}
},
{
"name": "m_bDelayedHardPunchIncoming",
"type": {
"category": 0,
"name": "bool"
}
},
{
"name": "m_bDestroyAfterTaunt",
"type": {
"category": 0,
"name": "bool"
}
}
],
"parent": "CCSWeaponBase"
},
"CFlashbang": {
"fields": [],
"parent": "CBaseCSGrenade"
@@ -35808,10 +35733,6 @@
],
"parent": "CLogicalEntity"
},
"CMelee": {
"fields": [],
"parent": "CCSWeaponBase"
},
"CMeshletDescriptor": {
"fields": [
{
@@ -55640,42 +55561,6 @@
],
"parent": "CAnimUpdateNodeBase"
},
"CSensorGrenade": {
"fields": [],
"parent": "CBaseCSGrenade"
},
"CSensorGrenadeProjectile": {
"fields": [
{
"name": "m_fExpireTime",
"type": {
"category": 5,
"name": "GameTime_t"
}
},
{
"name": "m_fNextDetectPlayerSound",
"type": {
"category": 5,
"name": "GameTime_t"
}
},
{
"name": "m_hDisplayGrenade",
"type": {
"atomic": 1,
"category": 4,
"inner": {
"category": 5,
"name": "CBaseEntity"
},
"name": "CHandle< CBaseEntity >",
"outer": "CHandle"
}
}
],
"parent": "CBaseCSGrenadeProjectile"
},
"CSeqAutoLayer": {
"fields": [
{
@@ -60297,10 +60182,6 @@
],
"parent": "CConcreteAnimParameter"
},
"CTablet": {
"fields": [],
"parent": "CCSWeaponBase"
},
"CTakeDamageInfo": {
"fields": [
{
@@ -62408,10 +62289,6 @@
"fields": [],
"parent": "CBaseTrigger"
},
"CTriggerTripWire": {
"fields": [],
"parent": "CBaseTrigger"
},
"CTriggerVolume": {
"fields": [
{
@@ -62437,14 +62314,6 @@
],
"parent": "CBaseModelEntity"
},
"CTripWireFire": {
"fields": [],
"parent": "CBaseCSGrenade"
},
"CTripWireFireProjectile": {
"fields": [],
"parent": "CBaseGrenade"
},
"CTurnHelperUpdateNode": {
"fields": [
{
@@ -63748,32 +63617,6 @@
"fields": [],
"parent": "CCSWeaponBase"
},
"CWeaponShield": {
"fields": [
{
"name": "m_flBulletDamageAbsorbed",
"type": {
"category": 0,
"name": "float32"
}
},
{
"name": "m_flLastBulletHitSoundTime",
"type": {
"category": 5,
"name": "GameTime_t"
}
},
{
"name": "m_flDisplayHealth",
"type": {
"category": 0,
"name": "float32"
}
}
],
"parent": "CCSWeaponBaseGun"
},
"CWeaponTaser": {
"fields": [
{
@@ -63809,10 +63652,6 @@
"fields": [],
"parent": "CCSWeaponBase"
},
"CWeaponZoneRepulsor": {
"fields": [],
"parent": "CCSWeaponBaseGun"
},
"CWorld": {
"fields": [],
"parent": "CBaseModelEntity"
@@ -100411,56 +100250,24 @@
"value": 4
},
{
"name": "k_CSPlayerBlockingUseAction_OpeningSafe",
"name": "k_CSPlayerBlockingUseAction_EquippingHeavyArmor",
"value": 5
},
{
"name": "k_CSPlayerBlockingUseAction_EquippingParachute",
"name": "k_CSPlayerBlockingUseAction_TakingOffHeavyArmor",
"value": 6
},
{
"name": "k_CSPlayerBlockingUseAction_EquippingHeavyArmor",
"name": "k_CSPlayerBlockingUseAction_MapLongUseEntity_Pickup",
"value": 7
},
{
"name": "k_CSPlayerBlockingUseAction_EquippingContract",
"name": "k_CSPlayerBlockingUseAction_MapLongUseEntity_Place",
"value": 8
},
{
"name": "k_CSPlayerBlockingUseAction_EquippingTabletUpgrade",
"value": 9
},
{
"name": "k_CSPlayerBlockingUseAction_TakingOffHeavyArmor",
"value": 10
},
{
"name": "k_CSPlayerBlockingUseAction_PayingToOpenDoor",
"value": 11
},
{
"name": "k_CSPlayerBlockingUseAction_CancelingSpawnRappelling",
"value": 12
},
{
"name": "k_CSPlayerBlockingUseAction_EquippingExoJump",
"value": 13
},
{
"name": "k_CSPlayerBlockingUseAction_PickingUpBumpMine",
"value": 14
},
{
"name": "k_CSPlayerBlockingUseAction_MapLongUseEntity_Pickup",
"value": 15
},
{
"name": "k_CSPlayerBlockingUseAction_MapLongUseEntity_Place",
"value": 16
},
{
"name": "k_CSPlayerBlockingUseAction_MaxCount",
"value": 17
"value": 9
}
]
},
@@ -102444,17 +102251,9 @@
"name": "GRENADE_TYPE_SMOKE",
"value": 4
},
{
"name": "GRENADE_TYPE_SENSOR",
"value": 5
},
{
"name": "GRENADE_TYPE_SNOWBALL",
"value": 6
},
{
"name": "GRENADE_TYPE_TOTAL",
"value": 7
"value": 5
}
]
},
@@ -110629,4 +110428,4 @@
]
}
}
}
}

View File

@@ -4,6 +4,7 @@ namespace CounterStrikeSharp.SchemaGen;
public partial record SchemaClass(
int Index,
string Name,
string? Parent,
IReadOnlyList<SchemaField> Fields)
{

View File

@@ -1,41 +1,41 @@
/*
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#include "UserMessage.h"
#include "networksystem/inetworkserializer.h"
using namespace google;
namespace counterstrikesharp {
int UserMessage::GetMessageID() { return msgSerializable->GetNetMessageInfo()->m_MessageId; }
std::string UserMessage::GetMessageName() { return msgSerializable->GetUnscopedName(); }
bool UserMessage::HasField(std::string fieldName)
{
const google::protobuf::Descriptor* descriptor = msg->GetDescriptor();
const google::protobuf::FieldDescriptor* field = descriptor->FindFieldByName(fieldName);
if (field == nullptr || (field->label() == google::protobuf::FieldDescriptor::LABEL_REPEATED))
{
return false;
}
return this->msg->GetReflection()->HasField(*this->msg, field);
}
const CNetMessagePB<google::protobuf::Message>* UserMessage::GetProtobufMessage() { return msg; }
} // namespace counterstrikesharp
/*
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#include "UserMessage.h"
#include "networksystem/inetworkserializer.h"
using namespace google;
namespace counterstrikesharp {
int UserMessage::GetMessageID() { return msgSerializable->GetNetMessageInfo()->m_MessageId; }
std::string UserMessage::GetMessageName() { return msgSerializable->GetUnscopedName(); }
bool UserMessage::HasField(std::string fieldName)
{
const google::protobuf::Descriptor* descriptor = msg->GetDescriptor();
const google::protobuf::FieldDescriptor* field = descriptor->FindFieldByName(fieldName);
if (field == nullptr || (field->label() == google::protobuf::FieldDescriptor::LABEL_REPEATED))
{
return false;
}
return this->msg->GetReflection()->HasField(*this->msg, field);
}
const CNetMessagePB<google::protobuf::Message>* UserMessage::GetProtobufMessage() { return msg; }
} // namespace counterstrikesharp

View File

@@ -28,8 +28,7 @@ class CGameResourceService
public:
CGameEntitySystem* GetGameEntitySystem()
{
return *reinterpret_cast<CGameEntitySystem**>(
(uintptr_t)(this) +
counterstrikesharp::globals::gameConfig->GetOffset("GameEntitySystem"));
return *reinterpret_cast<CGameEntitySystem**>((uintptr_t)(this) +
counterstrikesharp::globals::gameConfig->GetOffset("GameEntitySystem"));
}
};
};

View File

@@ -26,11 +26,10 @@
#include "tier0/memdbgon.h"
namespace counterstrikesharp {
void interfaces::Initialize() {
pGameResourceServiceServer = (CGameResourceService*)modules::engine->FindInterface(
GAMERESOURCESERVICESERVER_INTERFACE_VERSION);
void interfaces::Initialize()
{
pGameResourceServiceServer = (CGameResourceService*)modules::engine->FindInterface(GAMERESOURCESERVICESERVER_INTERFACE_VERSION);
g_pCVar = (ICvar*)modules::tier0->FindInterface(CVAR_INTERFACE_VERSION);
g_pSource2GameEntities = (ISource2GameEntities*)modules::server->FindInterface(
SOURCE2GAMEENTITIES_INTERFACE_VERSION);
g_pSource2GameEntities = (ISource2GameEntities*)modules::server->FindInterface(SOURCE2GAMEENTITIES_INTERFACE_VERSION);
}
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -25,6 +25,6 @@ namespace counterstrikesharp {
namespace interfaces {
void Initialize();
inline CGameResourceService *pGameResourceServiceServer = nullptr;
} // namespace interfaces
} // namespace counterstrikesharp
inline CGameResourceService* pGameResourceServiceServer = nullptr;
} // namespace interfaces
} // namespace counterstrikesharp

View File

@@ -33,8 +33,10 @@
using SchemaKeyValueMap_t = CUtlMap<uint32_t, SchemaKey>;
using SchemaTableMap_t = CUtlMap<uint32_t, SchemaKeyValueMap_t*>;
bool IsFieldNetworked(SchemaClassFieldData_t& field) {
for (int i = 0; i < field.m_nStaticMetadataCount; i++) {
bool IsFieldNetworked(SchemaClassFieldData_t& field)
{
for (int i = 0; i < field.m_nStaticMetadataCount; i++)
{
static auto networkEnabled = hash_32_fnv1a_const("MNetworkEnable");
if (networkEnabled == hash_32_fnv1a_const(field.m_pStaticMetadata[i].m_pszName)) return true;
}
@@ -42,16 +44,16 @@ bool IsFieldNetworked(SchemaClassFieldData_t& field) {
return false;
}
static bool InitSchemaFieldsForClass(SchemaTableMap_t* tableMap,
const char* className,
uint32_t classKey) {
static bool InitSchemaFieldsForClass(SchemaTableMap_t* tableMap, const char* className, uint32_t classKey)
{
CSchemaSystemTypeScope* pType = counterstrikesharp::globals::schemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT);
if (!pType) return false;
SchemaClassInfoData_t* pClassInfo = pType->FindDeclaredClass(className).Get();
if (!pClassInfo) {
if (!pClassInfo)
{
SchemaKeyValueMap_t* map = new SchemaKeyValueMap_t(0, 0, DefLessFunc(uint32_t));
tableMap->Insert(classKey, map);
@@ -66,31 +68,34 @@ static bool InitSchemaFieldsForClass(SchemaTableMap_t* tableMap,
keyValueMap->EnsureCapacity(fieldsSize);
tableMap->Insert(classKey, keyValueMap);
for (int i = 0; i < fieldsSize; ++i) {
for (int i = 0; i < fieldsSize; ++i)
{
SchemaClassFieldData_t& field = pFields[i];
keyValueMap->Insert(hash_32_fnv1a_const(field.m_pszName),
{field.m_nSingleInheritanceOffset, IsFieldNetworked(field)});
keyValueMap->Insert(hash_32_fnv1a_const(field.m_pszName), { field.m_nSingleInheritanceOffset, IsFieldNetworked(field) });
}
return true;
}
int16_t schema::FindChainOffset(const char* className) {
CSchemaSystemTypeScope* pType =
counterstrikesharp::globals::schemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT);
int16_t schema::FindChainOffset(const char* className)
{
CSchemaSystemTypeScope* pType = counterstrikesharp::globals::schemaSystem->FindTypeScopeForModule(MODULE_PREFIX "server" MODULE_EXT);
if (!pType) return false;
auto* pClassInfo = pType->FindDeclaredClass(className).Get();
do {
do
{
SchemaClassFieldData_t* pFields = pClassInfo->m_pFields;
short fieldsSize = pClassInfo->m_nFieldCount;
for (int i = 0; i < fieldsSize; ++i) {
for (int i = 0; i < fieldsSize; ++i)
{
SchemaClassFieldData_t& field = pFields[i];
if (V_strcmp(field.m_pszName, "__m_pChainEntity") == 0) {
if (V_strcmp(field.m_pszName, "__m_pChainEntity") == 0)
{
return field.m_nSingleInheritanceOffset;
}
}
@@ -99,29 +104,29 @@ int16_t schema::FindChainOffset(const char* className) {
return 0;
}
SchemaKey schema::GetOffset(const char* className,
uint32_t classKey,
const char* memberName,
uint32_t memberKey) {
SchemaKey schema::GetOffset(const char* className, uint32_t classKey, const char* memberName, uint32_t memberKey)
{
static SchemaTableMap_t schemaTableMap(0, 0, DefLessFunc(uint32_t));
int16_t tableMapIndex = schemaTableMap.Find(classKey);
if (!schemaTableMap.IsValidIndex(tableMapIndex)) {
if (InitSchemaFieldsForClass(&schemaTableMap, className, classKey))
return GetOffset(className, classKey, memberName, memberKey);
if (!schemaTableMap.IsValidIndex(tableMapIndex))
{
if (InitSchemaFieldsForClass(&schemaTableMap, className, classKey)) return GetOffset(className, classKey, memberName, memberKey);
return {0, 0};
return { 0, 0 };
}
SchemaKeyValueMap_t* tableMap = schemaTableMap[tableMapIndex];
int16_t memberIndex = tableMap->Find(memberKey);
if (!tableMap->IsValidIndex(memberIndex)) {
return {0, 0};
if (!tableMap->IsValidIndex(memberIndex))
{
return { 0, 0 };
}
return tableMap->Element(memberIndex);
}
void SetStateChanged(Z_CBaseEntity* pEntity, int offset) {
void SetStateChanged(Z_CBaseEntity* pEntity, int offset)
{
// addresses::StateChanged(pEntity->m_NetworkTransmitComponent(), pEntity, offset, -1, -1);
auto vars = counterstrikesharp::globals::getGlobalVars();

View File

@@ -30,29 +30,28 @@
#undef schema
struct SchemaKey {
struct SchemaKey
{
int32_t offset;
bool networked;
};
class Z_CBaseEntity;
void SetStateChanged(Z_CBaseEntity *pEntity, int offset);
void SetStateChanged(Z_CBaseEntity* pEntity, int offset);
inline uint32_t val_32_const = 0x811c9dc5;
inline uint32_t prime_32_const = 0x1000193;
inline uint64_t val_64_const = 0xcbf29ce484222325;
inline uint64_t prime_64_const = 0x100000001b3;
inline uint32_t hash_32_fnv1a_const(const char *str, const uint32_t value = val_32_const) noexcept {
return (str[0] == '\0')
? value
: hash_32_fnv1a_const(&str[1], (value ^ uint32_t(str[0])) * prime_32_const);
inline uint32_t hash_32_fnv1a_const(const char* str, const uint32_t value = val_32_const) noexcept
{
return (str[0] == '\0') ? value : hash_32_fnv1a_const(&str[1], (value ^ uint32_t(str[0])) * prime_32_const);
}
inline uint64_t hash_64_fnv1a_const(const char *str, const uint64_t value = val_64_const) noexcept {
return (str[0] == '\0')
? value
: hash_64_fnv1a_const(&str[1], (value ^ uint64_t(str[0])) * prime_64_const);
inline uint64_t hash_64_fnv1a_const(const char* str, const uint64_t value = val_64_const) noexcept
{
return (str[0] == '\0') ? value : hash_64_fnv1a_const(&str[1], (value ^ uint64_t(str[0])) * prime_64_const);
}
namespace schema {
@@ -95,6 +94,6 @@ static std::vector<std::string> CS2BadList = {
"m_nMusicID",
};
int16_t FindChainOffset(const char *className);
SchemaKey GetOffset(const char *className, uint32_t classKey, const char *memberName, uint32_t memberKey);
} // namespace schema
int16_t FindChainOffset(const char* className);
SchemaKey GetOffset(const char* className, uint32_t classKey, const char* memberName, uint32_t memberKey);
} // namespace schema

View File

@@ -52,30 +52,30 @@ std::map<dyno::Hook*, ValveFunction*> g_HookMap;
// ============================================================================
int GetDynCallConvention(Convention_t eConv)
{
switch (eConv) {
case CONV_CUSTOM:
return -1;
case CONV_CDECL:
return DC_CALL_C_DEFAULT;
case CONV_THISCALL:
switch (eConv)
{
case CONV_CUSTOM:
return -1;
case CONV_CDECL:
return DC_CALL_C_DEFAULT;
case CONV_THISCALL:
#ifdef _WIN32
return DC_CALL_C_X86_WIN32_THIS_MS;
return DC_CALL_C_X86_WIN32_THIS_MS;
#else
return DC_CALL_C_X86_WIN32_THIS_GNU;
return DC_CALL_C_X86_WIN32_THIS_GNU;
#endif
#ifdef _WIN32
case CONV_STDCALL:
return DC_CALL_C_X86_WIN32_STD;
case CONV_FASTCALL:
return DC_CALL_C_X86_WIN32_FAST_MS;
case CONV_STDCALL:
return DC_CALL_C_X86_WIN32_STD;
case CONV_FASTCALL:
return DC_CALL_C_X86_WIN32_FAST_MS;
#endif
}
return -1;
}
ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention,
std::vector<DataType_t> args, DataType_t returnType)
ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention, std::vector<DataType_t> args, DataType_t returnType)
: m_ulAddr(ulAddr)
{
m_Args = args;
@@ -87,8 +87,7 @@ ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention,
m_iCallingConvention = GetDynCallConvention(m_eCallingConvention);
}
ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention, DataType_t* args,
int argCount, DataType_t returnType)
ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention, DataType_t* args, int argCount, DataType_t returnType)
: m_ulAddr(ulAddr)
{
@@ -101,13 +100,9 @@ ValveFunction::ValveFunction(void* ulAddr, Convention_t callingConvention, DataT
ValveFunction::~ValveFunction() {}
bool ValveFunction::IsCallable()
{
return (m_eCallingConvention != CONV_CUSTOM) && (m_iCallingConvention != -1);
}
bool ValveFunction::IsCallable() { return (m_eCallingConvention != CONV_CUSTOM) && (m_iCallingConvention != -1); }
template <class ReturnType, class Function>
ReturnType CallHelper(Function func, DCCallVM* vm, void* addr)
template <class ReturnType, class Function> ReturnType CallHelper(Function func, DCCallVM* vm, void* addr)
{
ReturnType result;
result = (ReturnType)func(vm, (void*)addr);
@@ -118,119 +113,120 @@ void CallHelperVoid(DCCallVM* vm, void* addr) { dcCallVoid(vm, (void*)addr); }
void ValveFunction::Call(ScriptContext& script_context, int offset)
{
if (!IsCallable())
return;
if (!IsCallable()) return;
dcReset(g_pCallVM);
dcMode(g_pCallVM, m_iCallingConvention);
for (size_t i = 0; i < m_Args.size(); i++) {
for (size_t i = 0; i < m_Args.size(); i++)
{
int contextIndex = i + offset;
switch (m_Args[i]) {
case DATA_TYPE_BOOL:
dcArgBool(g_pCallVM, script_context.GetArgument<bool>(contextIndex));
break;
case DATA_TYPE_CHAR:
dcArgChar(g_pCallVM, script_context.GetArgument<char>(contextIndex));
break;
case DATA_TYPE_UCHAR:
dcArgChar(g_pCallVM, script_context.GetArgument<unsigned char>(contextIndex));
break;
case DATA_TYPE_SHORT:
dcArgShort(g_pCallVM, script_context.GetArgument<short>(contextIndex));
break;
case DATA_TYPE_USHORT:
dcArgShort(g_pCallVM, script_context.GetArgument<unsigned short>(contextIndex));
break;
case DATA_TYPE_INT:
dcArgInt(g_pCallVM, script_context.GetArgument<int>(contextIndex));
break;
case DATA_TYPE_UINT:
dcArgInt(g_pCallVM, script_context.GetArgument<unsigned int>(contextIndex));
break;
case DATA_TYPE_LONG:
dcArgLong(g_pCallVM, script_context.GetArgument<long>(contextIndex));
break;
case DATA_TYPE_ULONG:
dcArgLong(g_pCallVM, script_context.GetArgument<unsigned long>(contextIndex));
break;
case DATA_TYPE_LONG_LONG:
dcArgLongLong(g_pCallVM, script_context.GetArgument<long long>(contextIndex));
break;
case DATA_TYPE_ULONG_LONG:
dcArgLongLong(g_pCallVM, script_context.GetArgument<unsigned long long>(contextIndex));
break;
case DATA_TYPE_FLOAT:
dcArgFloat(g_pCallVM, script_context.GetArgument<float>(contextIndex));
break;
case DATA_TYPE_DOUBLE:
dcArgDouble(g_pCallVM, script_context.GetArgument<double>(contextIndex));
break;
case DATA_TYPE_POINTER:
dcArgPointer(g_pCallVM, script_context.GetArgument<void*>(contextIndex));
break;
case DATA_TYPE_STRING:
dcArgPointer(g_pCallVM, (void*)script_context.GetArgument<const char*>(contextIndex));
break;
default:
assert(!"Unknown function parameter type!");
break;
switch (m_Args[i])
{
case DATA_TYPE_BOOL:
dcArgBool(g_pCallVM, script_context.GetArgument<bool>(contextIndex));
break;
case DATA_TYPE_CHAR:
dcArgChar(g_pCallVM, script_context.GetArgument<char>(contextIndex));
break;
case DATA_TYPE_UCHAR:
dcArgChar(g_pCallVM, script_context.GetArgument<unsigned char>(contextIndex));
break;
case DATA_TYPE_SHORT:
dcArgShort(g_pCallVM, script_context.GetArgument<short>(contextIndex));
break;
case DATA_TYPE_USHORT:
dcArgShort(g_pCallVM, script_context.GetArgument<unsigned short>(contextIndex));
break;
case DATA_TYPE_INT:
dcArgInt(g_pCallVM, script_context.GetArgument<int>(contextIndex));
break;
case DATA_TYPE_UINT:
dcArgInt(g_pCallVM, script_context.GetArgument<unsigned int>(contextIndex));
break;
case DATA_TYPE_LONG:
dcArgLong(g_pCallVM, script_context.GetArgument<long>(contextIndex));
break;
case DATA_TYPE_ULONG:
dcArgLong(g_pCallVM, script_context.GetArgument<unsigned long>(contextIndex));
break;
case DATA_TYPE_LONG_LONG:
dcArgLongLong(g_pCallVM, script_context.GetArgument<long long>(contextIndex));
break;
case DATA_TYPE_ULONG_LONG:
dcArgLongLong(g_pCallVM, script_context.GetArgument<unsigned long long>(contextIndex));
break;
case DATA_TYPE_FLOAT:
dcArgFloat(g_pCallVM, script_context.GetArgument<float>(contextIndex));
break;
case DATA_TYPE_DOUBLE:
dcArgDouble(g_pCallVM, script_context.GetArgument<double>(contextIndex));
break;
case DATA_TYPE_POINTER:
dcArgPointer(g_pCallVM, script_context.GetArgument<void*>(contextIndex));
break;
case DATA_TYPE_STRING:
dcArgPointer(g_pCallVM, (void*)script_context.GetArgument<const char*>(contextIndex));
break;
default:
assert(!"Unknown function parameter type!");
break;
}
}
switch (m_eReturnType) {
case DATA_TYPE_VOID:
CallHelperVoid(g_pCallVM, m_ulAddr);
break;
case DATA_TYPE_BOOL:
script_context.SetResult(CallHelper<bool>(dcCallBool, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_CHAR:
script_context.SetResult(CallHelper<char>(dcCallChar, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_UCHAR:
script_context.SetResult(CallHelper<unsigned char>(dcCallChar, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_SHORT:
script_context.SetResult(CallHelper<short>(dcCallShort, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_USHORT:
script_context.SetResult(CallHelper<unsigned short>(dcCallShort, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_INT:
script_context.SetResult(CallHelper<int>(dcCallInt, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_UINT:
script_context.SetResult(CallHelper<unsigned int>(dcCallInt, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_LONG:
script_context.SetResult(CallHelper<long>(dcCallLong, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_ULONG:
script_context.SetResult(CallHelper<unsigned long>(dcCallLong, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_LONG_LONG:
script_context.SetResult(CallHelper<long long>(dcCallLongLong, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_ULONG_LONG:
script_context.SetResult(
CallHelper<unsigned long long>(dcCallLongLong, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_FLOAT:
script_context.SetResult(CallHelper<float>(dcCallFloat, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_DOUBLE:
script_context.SetResult(CallHelper<double>(dcCallDouble, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_POINTER:
script_context.SetResult(CallHelper<void*>(dcCallPointer, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_STRING:
script_context.SetResult(CallHelper<const char*>(dcCallPointer, g_pCallVM, m_ulAddr));
break;
default:
assert(!"Unknown function return type!");
break;
switch (m_eReturnType)
{
case DATA_TYPE_VOID:
CallHelperVoid(g_pCallVM, m_ulAddr);
break;
case DATA_TYPE_BOOL:
script_context.SetResult(CallHelper<bool>(dcCallBool, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_CHAR:
script_context.SetResult(CallHelper<char>(dcCallChar, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_UCHAR:
script_context.SetResult(CallHelper<unsigned char>(dcCallChar, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_SHORT:
script_context.SetResult(CallHelper<short>(dcCallShort, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_USHORT:
script_context.SetResult(CallHelper<unsigned short>(dcCallShort, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_INT:
script_context.SetResult(CallHelper<int>(dcCallInt, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_UINT:
script_context.SetResult(CallHelper<unsigned int>(dcCallInt, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_LONG:
script_context.SetResult(CallHelper<long>(dcCallLong, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_ULONG:
script_context.SetResult(CallHelper<unsigned long>(dcCallLong, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_LONG_LONG:
script_context.SetResult(CallHelper<long long>(dcCallLongLong, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_ULONG_LONG:
script_context.SetResult(CallHelper<unsigned long long>(dcCallLongLong, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_FLOAT:
script_context.SetResult(CallHelper<float>(dcCallFloat, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_DOUBLE:
script_context.SetResult(CallHelper<double>(dcCallDouble, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_POINTER:
script_context.SetResult(CallHelper<void*>(dcCallPointer, g_pCallVM, m_ulAddr));
break;
case DATA_TYPE_STRING:
script_context.SetResult(CallHelper<const char*>(dcCallPointer, g_pCallVM, m_ulAddr));
break;
default:
assert(!"Unknown function return type!");
break;
}
}
@@ -240,23 +236,24 @@ dyno::ReturnAction HookHandler(dyno::HookType hookType, dyno::Hook& hook)
auto callback = hookType == dyno::HookType::Pre ? vf->m_precallback : vf->m_postcallback;
if (callback == nullptr) {
if (callback == nullptr)
{
return dyno::ReturnAction::Ignored;
}
callback->Reset();
callback->ScriptContext().Push(&hook);
for (auto fnMethodToCall : callback->GetFunctions()) {
if (!fnMethodToCall)
continue;
for (auto fnMethodToCall : callback->GetFunctions())
{
if (!fnMethodToCall) continue;
fnMethodToCall(&callback->ScriptContextStruct());
auto result = callback->ScriptContext().GetResult<HookResult>();
CSSHARP_CORE_TRACE("Received hook callback result of {}, hook mode {}", result,
(int)hookType);
CSSHARP_CORE_TRACE("Received hook callback result of {}, hook mode {}", result, (int)hookType);
if (result >= HookResult::Handled) {
if (result >= HookResult::Handled)
{
return dyno::ReturnAction::Supercede;
}
}
@@ -269,7 +266,8 @@ std::vector<dyno::DataObject> ConvertArgsToDynoHook(const std::vector<DataType_t
std::vector<dyno::DataObject> converted;
converted.reserve(dataTypes.size());
for (DataType_t dt : dataTypes) {
for (DataType_t dt : dataTypes)
{
converted.push_back(dyno::DataObject(static_cast<dyno::DataType>(dt)));
}
@@ -290,19 +288,25 @@ void ValveFunction::AddHook(CallbackT callable, bool post)
hook->addCallback(dyno::HookType::Post, (dyno::HookHandler*)&HookHandler);
hook->addCallback(dyno::HookType::Pre, (dyno::HookHandler*)&HookHandler);
if (post) {
if (m_postcallback == nullptr) {
if (post)
{
if (m_postcallback == nullptr)
{
m_postcallback = globals::callbackManager.CreateCallback("");
}
m_postcallback->AddListener(callable);
} else {
if (m_precallback == nullptr) {
}
else
{
if (m_precallback == nullptr)
{
m_precallback = globals::callbackManager.CreateCallback("");
}
m_precallback->AddListener(callable);
}
}
void ValveFunction::RemoveHook(CallbackT callable, bool post) {
void ValveFunction::RemoveHook(CallbackT callable, bool post)
{
dyno::HookManager& manager = dyno::HookManager::Get();
dyno::Hook* hook = manager.hook((void*)m_ulAddr, [this] {
#ifdef _WIN32
@@ -313,12 +317,17 @@ void ValveFunction::RemoveHook(CallbackT callable, bool post) {
});
g_HookMap[hook] = this;
if (post) {
if (m_postcallback != nullptr) {
if (post)
{
if (m_postcallback != nullptr)
{
m_postcallback->RemoveListener(callable);
}
} else {
if (m_precallback != nullptr) {
}
else
{
if (m_precallback != nullptr)
{
m_precallback->RemoveListener(callable);
}
}

View File

@@ -40,7 +40,8 @@ class Hook;
namespace counterstrikesharp {
enum DataType_t {
enum DataType_t
{
DATA_TYPE_VOID,
DATA_TYPE_BOOL,
DATA_TYPE_CHAR,
@@ -60,7 +61,8 @@ enum DataType_t {
DATA_TYPE_VARIANT
};
enum Protection_t {
enum Protection_t
{
PROTECTION_NONE,
PROTECTION_READ,
PROTECTION_READ_WRITE,
@@ -69,19 +71,20 @@ enum Protection_t {
PROTECTION_EXECUTE_READ_WRITE
};
enum Convention_t { CONV_CUSTOM, CONV_CDECL, CONV_THISCALL, CONV_STDCALL, CONV_FASTCALL };
enum Convention_t
{
CONV_CUSTOM,
CONV_CDECL,
CONV_THISCALL,
CONV_STDCALL,
CONV_FASTCALL
};
class ValveFunction {
public:
ValveFunction(void* ulAddr,
Convention_t callingConvention,
std::vector<DataType_t> args,
DataType_t returnType);
ValveFunction(void* ulAddr,
Convention_t callingConvention,
DataType_t* args,
int argCount,
DataType_t returnType);
class ValveFunction
{
public:
ValveFunction(void* ulAddr, Convention_t callingConvention, std::vector<DataType_t> args, DataType_t returnType);
ValveFunction(void* ulAddr, Convention_t callingConvention, DataType_t* args, int argCount, DataType_t returnType);
~ValveFunction();
@@ -110,4 +113,4 @@ public:
ScriptCallback* m_postcallback = nullptr;
};
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -36,7 +36,8 @@ bool InitGameSystems()
// bytes so we skip those
uint8* ptr = (uint8*)counterstrikesharp::globals::gameConfig->ResolveSignature("IGameSystem_InitAllSystems_pFirst") + 3;
if (!ptr) {
if (!ptr)
{
CSSHARP_CORE_ERROR("Failed to InitGameSystems, see warnings above.");
return false;
}
@@ -63,4 +64,4 @@ GS_EVENT_MEMBER(CGameSystem, BuildGameSessionManifest)
CSSHARP_CORE_INFO("CGameSystem::BuildGameSessionManifest");
counterstrikesharp::globals::serverManager.OnPrecacheResources(pResourceManifest);
}
}

View File

@@ -37,11 +37,10 @@ class CGameSystem : public CBaseGameSystem
void SetGameSystemGlobalPtrs(void* pValue) override
{
if (sm_Factory)
sm_Factory->SetGlobalPtr(pValue);
if (sm_Factory) sm_Factory->SetGlobalPtr(pValue);
}
bool DoesGameSystemReallocate() override { return sm_Factory->ShouldAutoAdd(); }
static IGameSystemFactory* sm_Factory;
};
};

View File

@@ -3,7 +3,6 @@
#include <fstream>
#include "log.h"
#include "metamod_oslink.h"
namespace counterstrikesharp {

View File

@@ -1,6 +1,5 @@
#pragma once
#include "core/globals.h"
#include "core/memory_module.h"
#include <KeyValues.h>

View File

@@ -32,34 +32,37 @@
#pragma once
namespace counterstrikesharp {
class GlobalClass {
public:
class GlobalClass
{
public:
virtual ~GlobalClass() = default;
GlobalClass() {
GlobalClass()
{
m_pGlobalClassNext = GlobalClass::head;
GlobalClass::head = this;
}
public:
public:
virtual void OnStartup() {}
virtual void OnShutdown() {}
virtual void OnAllInitialized() {}
virtual void OnGameLoopInitialized() {}
virtual void OnAllInitialized_Post() {}
virtual void OnLevelChange(const char *mapName) {}
virtual void OnLevelChange(const char* mapName) {}
virtual void OnLevelEnd() {}
public:
GlobalClass *m_pGlobalClassNext;
static GlobalClass *head;
public:
GlobalClass* m_pGlobalClassNext;
static GlobalClass* head;
};
} // namespace counterstrikesharp
} // namespace counterstrikesharp
#define CALL_GLOBAL_LISTENER(func) \
GlobalClass *pBase = GlobalClass::head; \
GlobalClass* pBase = GlobalClass::head; \
pBase = GlobalClass::head; \
while (pBase) { \
while (pBase) \
{ \
pBase->func; \
pBase = pBase->m_pGlobalClassNext; \
}

View File

@@ -1,4 +1,3 @@
// clang-format off
#include "mm_plugin.h"
#include "core/globals.h"
#include "core/managers/player_manager.h"
@@ -28,7 +27,6 @@
#include <public/entity2/entitysystem.h>
#include <funchook.h>
// clang-format on
namespace counterstrikesharp {
@@ -142,7 +140,8 @@ void DetourGameEventManagerInit(IGameEventManager2* pGameEventManager)
}
int source_hook_pluginid = 0;
CGlobalVars* getGlobalVars() {
CGlobalVars* getGlobalVars()
{
INetworkGameServer* server = networkServerService->GetIGameServer();
if (!server) return nullptr;
return networkServerService->GetIGameServer()->GetGlobals();

View File

@@ -1,10 +1,6 @@
#pragma once
#define protected public
#define private public
#include <tier1/convar.h>
#undef protected
#undef private
#include <sourcehook/sourcehook.h>

View File

@@ -7,7 +7,8 @@
namespace counterstrikesharp {
std::shared_ptr<spdlog::logger> Log::m_core_logger;
void Log::Init() {
void Log::Init()
{
std::vector<spdlog::sink_ptr> log_sinks;
auto color_sink = std::make_shared<spdlog::sinks::stderr_color_sink_mt>();
#if _WIN32
@@ -17,8 +18,7 @@ void Log::Init() {
#endif
log_sinks.emplace_back(color_sink);
log_sinks.emplace_back(
std::make_shared<spdlog::sinks::basic_file_sink_mt>("counterstrikesharp.log", true));
log_sinks.emplace_back(std::make_shared<spdlog::sinks::basic_file_sink_mt>("counterstrikesharp.log", true));
log_sinks[0]->set_pattern("%^[%T.%e] %n: %v%$");
log_sinks[1]->set_pattern("[%T.%e] [%l] %n: %v");
@@ -31,8 +31,9 @@ void Log::Init() {
spdlog::cfg::load_env_levels();
}
void Log::Close() {
void Log::Close()
{
spdlog::drop("CSSharp");
m_core_logger = nullptr;
}
} // namespace counterstrikesharp
} // namespace counterstrikesharp

View File

@@ -6,21 +6,22 @@
#include <spdlog/spdlog.h>
namespace counterstrikesharp {
class Log {
public:
class Log
{
public:
static void Init();
static void Close();
static std::shared_ptr<spdlog::logger> &GetCoreLogger() { return m_core_logger; }
static std::shared_ptr<spdlog::logger>& GetCoreLogger() { return m_core_logger; }
private:
private:
static std::shared_ptr<spdlog::logger> m_core_logger;
};
} // namespace counterstrikesharp
} // namespace counterstrikesharp
#define CSSHARP_CORE_TRACE(...) ::counterstrikesharp::Log::GetCoreLogger()->trace(__VA_ARGS__)
#define CSSHARP_CORE_DEBUG(...) ::counterstrikesharp::Log::GetCoreLogger()->debug(__VA_ARGS__)
#define CSSHARP_CORE_INFO(...) ::counterstrikesharp::Log::GetCoreLogger()->info(__VA_ARGS__)
#define CSSHARP_CORE_WARN(...) ::counterstrikesharp::Log::GetCoreLogger()->warn(__VA_ARGS__)
#define CSSHARP_CORE_ERROR(...) ::counterstrikesharp::Log::GetCoreLogger()->error(__VA_ARGS__)
#define CSSHARP_CORE_TRACE(...) ::counterstrikesharp::Log::GetCoreLogger()->trace(__VA_ARGS__)
#define CSSHARP_CORE_DEBUG(...) ::counterstrikesharp::Log::GetCoreLogger()->debug(__VA_ARGS__)
#define CSSHARP_CORE_INFO(...) ::counterstrikesharp::Log::GetCoreLogger()->info(__VA_ARGS__)
#define CSSHARP_CORE_WARN(...) ::counterstrikesharp::Log::GetCoreLogger()->warn(__VA_ARGS__)
#define CSSHARP_CORE_ERROR(...) ::counterstrikesharp::Log::GetCoreLogger()->error(__VA_ARGS__)
#define CSSHARP_CORE_CRITICAL(...) ::counterstrikesharp::Log::GetCoreLogger()->critical(__VA_ARGS__)

View File

@@ -1,127 +1,127 @@
/*
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#include "core/managers/chat_manager.h"
#include <funchook.h>
#include <igameevents.h>
#include <public/eiface.h>
#include "characterset.h"
#include "core/coreconfig.h"
#include "core/gameconfig.h"
#include "core/log.h"
#include "core/managers/con_command_manager.h"
#include "core/memory.h"
#include "core/memory_module.h"
#include "scripting/callback_manager.h"
namespace counterstrikesharp {
ChatManager::ChatManager() {}
ChatManager::~ChatManager() {}
void ChatManager::OnAllInitialized()
{
m_pHostSay = reinterpret_cast<HostSay>(modules::server->FindSignature(globals::gameConfig->GetSignature("Host_Say")));
if (m_pHostSay == nullptr)
{
CSSHARP_CORE_ERROR("Failed to find signature for \'Host_Say\'");
return;
}
auto m_hook = funchook_create();
funchook_prepare(m_hook, (void**)&m_pHostSay, (void*)&DetourHostSay);
funchook_install(m_hook, 0);
}
void ChatManager::OnShutdown() {}
void DetourHostSay(CEntityInstance* pController, CCommand& args, bool teamonly, int unk1, const char* unk2)
{
if (pController)
{
auto pEvent = globals::gameEventManager->CreateEvent("player_chat", true);
if (pEvent)
{
pEvent->SetBool("teamonly", teamonly);
pEvent->SetInt("userid", pController->GetEntityIndex().Get() - 1);
pEvent->SetString("text", args[1]);
globals::gameEventManager->FireEvent(pEvent, true);
}
}
std::string prefix;
bool bSilent = globals::coreConfig->IsSilentChatTrigger(args[1], prefix);
bool bCommand = globals::coreConfig->IsPublicChatTrigger(args[1], prefix) || bSilent;
if (!bSilent)
{
m_pHostSay(pController, args, teamonly, unk1, unk2);
}
if (bCommand)
{
char* pszMessage = (char*)(args.ArgS() + prefix.length() + 1);
// Trailing slashes are only removed if Host_Say has been called.
if (bSilent) pszMessage[V_strlen(pszMessage) - 1] = 0;
CCommand args;
args.Tokenize(pszMessage);
auto prefixedPhrase = std::string("css_") + args.Arg(0);
auto bValidWithPrefix = globals::conCommandManager.IsValidValveCommand(prefixedPhrase.c_str());
if (bValidWithPrefix)
{
// Re-tokenize with a `css_` prefix if we have found that its a valid command.
args.Tokenize(("css_" + std::string(pszMessage)).c_str());
}
globals::chatManager.OnSayCommandPost(pController, args);
}
}
bool ChatManager::OnSayCommandPre(CEntityInstance* pController, CCommand& command) { return false; }
void ChatManager::OnSayCommandPost(CEntityInstance* pController, CCommand& command)
{
auto commandStr = command.Arg(0);
return InternalDispatch(pController, commandStr, command);
}
void ChatManager::InternalDispatch(CEntityInstance* pPlayerController, const char* szTriggerPhase, CCommand& fullCommand)
{
if (pPlayerController == nullptr)
{
globals::conCommandManager.ExecuteCommandCallbacks(fullCommand.Arg(0),
CCommandContext(CommandTarget_t::CT_NO_TARGET, CPlayerSlot(-1)), fullCommand,
HookMode::Pre, CommandCallingContext::Chat);
return;
}
auto index = pPlayerController->GetEntityIndex().Get();
auto slot = CPlayerSlot(index - 1);
globals::conCommandManager.ExecuteCommandCallbacks(fullCommand.Arg(0), CCommandContext(CommandTarget_t::CT_NO_TARGET, slot),
fullCommand, HookMode::Pre, CommandCallingContext::Chat);
}
} // namespace counterstrikesharp
/*
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#include "core/managers/chat_manager.h"
#include <funchook.h>
#include <igameevents.h>
#include <public/eiface.h>
#include "characterset.h"
#include "core/coreconfig.h"
#include "core/gameconfig.h"
#include "core/log.h"
#include "core/managers/con_command_manager.h"
#include "core/memory.h"
#include "core/memory_module.h"
#include "scripting/callback_manager.h"
namespace counterstrikesharp {
ChatManager::ChatManager() {}
ChatManager::~ChatManager() {}
void ChatManager::OnAllInitialized()
{
m_pHostSay = reinterpret_cast<HostSay>(modules::server->FindSignature(globals::gameConfig->GetSignature("Host_Say")));
if (m_pHostSay == nullptr)
{
CSSHARP_CORE_ERROR("Failed to find signature for \'Host_Say\'");
return;
}
auto m_hook = funchook_create();
funchook_prepare(m_hook, (void**)&m_pHostSay, (void*)&DetourHostSay);
funchook_install(m_hook, 0);
}
void ChatManager::OnShutdown() {}
void DetourHostSay(CEntityInstance* pController, CCommand& args, bool teamonly, int unk1, const char* unk2)
{
if (pController)
{
auto pEvent = globals::gameEventManager->CreateEvent("player_chat", true);
if (pEvent)
{
pEvent->SetBool("teamonly", teamonly);
pEvent->SetInt("userid", pController->GetEntityIndex().Get() - 1);
pEvent->SetString("text", args[1]);
globals::gameEventManager->FireEvent(pEvent, true);
}
}
std::string prefix;
bool bSilent = globals::coreConfig->IsSilentChatTrigger(args[1], prefix);
bool bCommand = globals::coreConfig->IsPublicChatTrigger(args[1], prefix) || bSilent;
if (!bSilent)
{
m_pHostSay(pController, args, teamonly, unk1, unk2);
}
if (bCommand)
{
char* pszMessage = (char*)(args.ArgS() + prefix.length() + 1);
// Trailing slashes are only removed if Host_Say has been called.
if (bSilent) pszMessage[V_strlen(pszMessage) - 1] = 0;
CCommand args;
args.Tokenize(pszMessage);
auto prefixedPhrase = std::string("css_") + args.Arg(0);
auto bValidWithPrefix = globals::conCommandManager.IsValidValveCommand(prefixedPhrase.c_str());
if (bValidWithPrefix)
{
// Re-tokenize with a `css_` prefix if we have found that its a valid command.
args.Tokenize(("css_" + std::string(pszMessage)).c_str());
}
globals::chatManager.OnSayCommandPost(pController, args);
}
}
bool ChatManager::OnSayCommandPre(CEntityInstance* pController, CCommand& command) { return false; }
void ChatManager::OnSayCommandPost(CEntityInstance* pController, CCommand& command)
{
auto commandStr = command.Arg(0);
return InternalDispatch(pController, commandStr, command);
}
void ChatManager::InternalDispatch(CEntityInstance* pPlayerController, const char* szTriggerPhase, CCommand& fullCommand)
{
if (pPlayerController == nullptr)
{
globals::conCommandManager.ExecuteCommandCallbacks(fullCommand.Arg(0),
CCommandContext(CommandTarget_t::CT_NO_TARGET, CPlayerSlot(-1)), fullCommand,
HookMode::Pre, CommandCallingContext::Chat);
return;
}
auto index = pPlayerController->GetEntityIndex().Get();
auto slot = CPlayerSlot(index - 1);
globals::conCommandManager.ExecuteCommandCallbacks(fullCommand.Arg(0), CCommandContext(CommandTarget_t::CT_NO_TARGET, slot),
fullCommand, HookMode::Pre, CommandCallingContext::Chat);
}
} // namespace counterstrikesharp

View File

@@ -1,68 +1,68 @@
/*
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#pragma once
#include <map>
#include <vector>
#include "core/global_listener.h"
#include "core/globals.h"
#include "scripting/script_engine.h"
namespace counterstrikesharp {
class ScriptCallback;
typedef void (*HostSay)(CEntityInstance*, CCommand&, bool, int, const char*);
class ChatCommandInfo
{
friend class ChatManager;
public:
ChatCommandInfo() {}
public:
ScriptCallback* GetCallback() { return callback_pre; }
private:
std::string command;
ScriptCallback* callback_pre;
ScriptCallback* callback_post;
};
class ChatManager : public GlobalClass
{
public:
ChatManager();
~ChatManager();
void OnAllInitialized() override;
void OnShutdown() override;
bool OnSayCommandPre(CEntityInstance* pController, CCommand& args);
void OnSayCommandPost(CEntityInstance* pController, CCommand& args);
private:
void InternalDispatch(CEntityInstance* pPlayerController, const char* szTriggerPhrase, CCommand& pFullCommand);
std::vector<ChatCommandInfo*> m_cmd_list;
std::map<std::string, ChatCommandInfo*> m_cmd_lookup;
};
static void DetourHostSay(CEntityInstance* pController, CCommand& args, bool teamonly, int unk1, const char* unk2);
static HostSay m_pHostSay = nullptr;
} // namespace counterstrikesharp
/*
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#pragma once
#include <map>
#include <vector>
#include "core/global_listener.h"
#include "core/globals.h"
#include "scripting/script_engine.h"
namespace counterstrikesharp {
class ScriptCallback;
typedef void (*HostSay)(CEntityInstance*, CCommand&, bool, int, const char*);
class ChatCommandInfo
{
friend class ChatManager;
public:
ChatCommandInfo() {}
public:
ScriptCallback* GetCallback() { return callback_pre; }
private:
std::string command;
ScriptCallback* callback_pre;
ScriptCallback* callback_post;
};
class ChatManager : public GlobalClass
{
public:
ChatManager();
~ChatManager();
void OnAllInitialized() override;
void OnShutdown() override;
bool OnSayCommandPre(CEntityInstance* pController, CCommand& args);
void OnSayCommandPost(CEntityInstance* pController, CCommand& args);
private:
void InternalDispatch(CEntityInstance* pPlayerController, const char* szTriggerPhrase, CCommand& pFullCommand);
std::vector<ChatCommandInfo*> m_cmd_list;
std::map<std::string, ChatCommandInfo*> m_cmd_lookup;
};
static void DetourHostSay(CEntityInstance* pController, CCommand& args, bool teamonly, int unk1, const char* unk2);
static HostSay m_pHostSay = nullptr;
} // namespace counterstrikesharp

View File

@@ -179,7 +179,7 @@ CON_COMMAND(dump_schema, "dump schema symbols")
output << std::setw(2) << j << std::endl;
}
SH_DECL_HOOK3_void(ICvar, DispatchConCommand, SH_NOATTRIB, 0, ConCommandHandle, const CCommandContext&, const CCommand&);
SH_DECL_HOOK3_void(ICvar, DispatchConCommand, SH_NOATTRIB, 0, ConCommandRef, const CCommandContext&, const CCommand&);
ConCommandInfo::ConCommandInfo()
{
@@ -222,45 +222,31 @@ void UnlockConVars()
{
int unhiddenConVars = 0;
ConVar* currentCvar = nullptr;
ConVarHandle currentCvarHandle;
currentCvarHandle.Set(0);
do
for (ConVarRefAbstract ref(ConVarRef((uint16)0)); ref.IsValidRef(); ref = ConVarRefAbstract(ConVarRef(ref.GetAccessIndex() + 1)))
{
currentCvar = globals::cvars->GetConVar(currentCvarHandle);
if (!ref.IsFlagSet(flagsToRemove)) continue;
currentCvarHandle.Set(currentCvarHandle.Get() + 1);
if (!currentCvar) continue;
if (!(currentCvar->flags & flagsToRemove)) continue;
currentCvar->flags &= ~flagsToRemove;
ref.RemoveFlags(flagsToRemove);
unhiddenConVars++;
} while (currentCvar);
}
}
void UnlockConCommands()
{
int unhiddenConCommands = 0;
ConCommand* currentConCommand = nullptr;
ConCommand* invalidConCommand = globals::cvars->GetCommand(ConCommandHandle());
ConCommandHandle conCommandHandle;
conCommandHandle.Set(0);
ConCommandData* currentConCommand = nullptr;
ConCommandData* invalidConCommand = globals::cvars->GetConCommandData(ConCommandRef());
ConCommandRef ref = ConCommandRef((uint16)0);
do
ConCommandData* data = g_pCVar->GetConCommandData(ConCommandRef());
for (ConCommandRef ref = ConCommandRef((uint16)0); ref.GetRawData() != data; ref = ConCommandRef(ref.GetAccessIndex() + 1))
{
currentConCommand = globals::cvars->GetCommand(conCommandHandle);
if (!ref.IsFlagSet(flagsToRemove)) continue;
conCommandHandle.Set(conCommandHandle.Get() + 1);
if (!currentConCommand || currentConCommand == invalidConCommand || !(currentConCommand->GetFlags() & flagsToRemove)) continue;
currentConCommand->RemoveFlags(flagsToRemove);
ref.RemoveFlags(flagsToRemove);
unhiddenConCommands++;
} while (currentConCommand && currentConCommand != invalidConCommand);
}
}
void ConCommandManager::OnShutdown()
@@ -301,10 +287,10 @@ void ConCommandManager::AddCommandListener(const char* name, CallbackT callback,
pInfo = new ConCommandInfo();
m_cmd_lookup[strName] = pInfo;
ConCommandHandle hExistingCommand = globals::cvars->FindCommand(name);
if (hExistingCommand.IsValid())
ConCommandRef hExistingCommand = globals::cvars->FindConCommand(name);
if (hExistingCommand.IsValidRef())
{
pInfo->command = globals::cvars->GetCommand(hExistingCommand);
pInfo->command = globals::cvars->GetConCommandData(hExistingCommand);
}
}
@@ -353,11 +339,10 @@ void ConCommandManager::RemoveCommandListener(const char* name, CallbackT callba
bool ConCommandManager::AddValveCommand(const char* name, const char* description, bool server_only, int flags)
{
ConCommandHandle hExistingCommand = globals::cvars->FindCommand(name);
if (hExistingCommand.IsValid()) return false;
ConCommandRef hExistingCommand = globals::cvars->FindConCommand(name);
if (hExistingCommand.IsValidRef()) return false;
ConCommandRefAbstract conCommandRefAbstract;
auto conCommand = new ConCommand(&conCommandRefAbstract, strdup(name), CommandCallback, description ? strdup(description) : "", flags);
auto conCommand = new ConCommand(strdup(name), CommandCallback, description ? strdup(description) : "", flags);
ConCommandInfo* pInfo = m_cmd_lookup[std::string(name)];
@@ -367,8 +352,7 @@ bool ConCommandManager::AddValveCommand(const char* name, const char* descriptio
m_cmd_lookup[std::string(name)] = pInfo;
}
pInfo->p_cmd = conCommandRefAbstract;
pInfo->command = conCommand;
pInfo->command = conCommand->GetRawData();
pInfo->server_only = server_only;
return true;
@@ -376,14 +360,14 @@ bool ConCommandManager::AddValveCommand(const char* name, const char* descriptio
bool ConCommandManager::RemoveValveCommand(const char* name)
{
auto hFoundCommand = globals::cvars->FindCommand(name);
auto hFoundCommand = globals::cvars->FindConCommand(name);
if (!hFoundCommand.IsValid())
if (!hFoundCommand.IsValidRef())
{
return false;
}
globals::cvars->UnregisterConCommand(hFoundCommand);
globals::cvars->UnregisterConCommandCallbacks(hFoundCommand);
auto pInfo = m_cmd_lookup[std::string(name)];
if (!pInfo)
@@ -474,7 +458,7 @@ HookResult ConCommandManager::ExecuteCommandCallbacks(
return result;
}
void ConCommandManager::Hook_DispatchConCommand(ConCommandHandle cmd, const CCommandContext& ctx, const CCommand& args)
void ConCommandManager::Hook_DispatchConCommand(ConCommandRef cmd, const CCommandContext& ctx, const CCommand& args)
{
const char* name = args.Arg(0);
@@ -486,7 +470,7 @@ void ConCommandManager::Hook_DispatchConCommand(ConCommandHandle cmd, const CCom
RETURN_META(MRES_SUPERCEDE);
}
}
void ConCommandManager::Hook_DispatchConCommand_Post(ConCommandHandle cmd, const CCommandContext& ctx, const CCommand& args)
void ConCommandManager::Hook_DispatchConCommand_Post(ConCommandRef cmd, const CCommandContext& ctx, const CCommand& args)
{
const char* name = args.Arg(0);
@@ -498,8 +482,8 @@ void ConCommandManager::Hook_DispatchConCommand_Post(ConCommandHandle cmd, const
}
bool ConCommandManager::IsValidValveCommand(const char* name)
{
ConCommandHandle pCmd = globals::cvars->FindCommand(name);
return pCmd.IsValid();
ConCommandRef pCmd = globals::cvars->FindConCommand(name);
return pCmd.IsValidRef();
}
CommandCallingContext ConCommandManager::GetCommandCallingContext(CCommand* args) { return m_cmd_contexts[args]; }

View File

@@ -78,8 +78,7 @@ class ConCommandInfo
ScriptCallback* GetCallback() { return callback_pre; }
private:
ConCommandRefAbstract p_cmd;
ConCommand* command;
ConCommandData* command;
ScriptCallback* callback_pre;
ScriptCallback* callback_post;
bool server_only;
@@ -100,8 +99,8 @@ class ConCommandManager : public GlobalClass
bool IsValidValveCommand(const char* name);
bool AddValveCommand(const char* name, const char* description, bool server_only, int flags);
bool RemoveValveCommand(const char* name);
void Hook_DispatchConCommand(ConCommandHandle cmd, const CCommandContext& ctx, const CCommand& args);
void Hook_DispatchConCommand_Post(ConCommandHandle cmd, const CCommandContext& ctx, const CCommand& args);
void Hook_DispatchConCommand(ConCommandRef cmd, const CCommandContext& ctx, const CCommand& args);
void Hook_DispatchConCommand_Post(ConCommandRef cmd, const CCommandContext& ctx, const CCommand& args);
HookResult ExecuteCommandCallbacks(
const char* name, const CCommandContext& ctx, const CCommand& args, HookMode mode, CommandCallingContext callingContext);

View File

@@ -1,18 +1,18 @@
/*
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#include "core/managers/entity_manager.h"
#include "core/gameconfig.h"
@@ -25,18 +25,28 @@
#include <public/eiface.h>
#include "scripting/callback_manager.h"
SH_DECL_HOOK7_void(ISource2GameEntities, CheckTransmit, SH_NOATTRIB, 0, CCheckTransmitInfo**, int, CBitVec<16384>&, const Entity2Networkable_t**, const uint16*, int, bool);
SH_DECL_HOOK7_void(ISource2GameEntities,
CheckTransmit,
SH_NOATTRIB,
0,
CCheckTransmitInfo**,
int,
CBitVec<16384>&,
const Entity2Networkable_t**,
const uint16*,
int,
bool);
namespace counterstrikesharp {
EntityManager::EntityManager()
{
m_profile_name = "EntityManager";
}
EntityManager::EntityManager() { m_profile_name = "EntityManager"; }
EntityManager::~EntityManager() {}
CCheckTransmitInfoList::CCheckTransmitInfoList(CCheckTransmitInfo** pInfoInfoList, int nInfoCount) : infoList(pInfoInfoList), infoCount(nInfoCount) {}
CCheckTransmitInfoList::CCheckTransmitInfoList(CCheckTransmitInfo** pInfoInfoList, int nInfoCount)
: infoList(pInfoInfoList), infoCount(nInfoCount)
{
}
void EntityManager::OnAllInitialized()
{
@@ -46,13 +56,13 @@ void EntityManager::OnAllInitialized()
on_entity_spawned_callback = globals::callbackManager.CreateCallback("OnEntitySpawned");
on_entity_created_callback = globals::callbackManager.CreateCallback("OnEntityCreated");
on_entity_deleted_callback = globals::callbackManager.CreateCallback("OnEntityDeleted");
on_entity_parent_changed_callback =
globals::callbackManager.CreateCallback("OnEntityParentChanged");
on_entity_parent_changed_callback = globals::callbackManager.CreateCallback("OnEntityParentChanged");
m_pFireOutputInternal = reinterpret_cast<FireOutputInternal>(modules::server->FindSignature(
globals::gameConfig->GetSignature("CEntityIOOutput_FireOutputInternal")));
m_pFireOutputInternal = reinterpret_cast<FireOutputInternal>(
modules::server->FindSignature(globals::gameConfig->GetSignature("CEntityIOOutput_FireOutputInternal")));
if (m_pFireOutputInternal == nullptr) {
if (m_pFireOutputInternal == nullptr)
{
CSSHARP_CORE_CRITICAL("Failed to find signature for \'CEntityIOOutput_FireOutputInternal\'");
return;
}
@@ -73,7 +83,7 @@ void EntityManager::OnAllInitialized()
CSSHARP_CORE_CRITICAL("Failed to find signature for \'CEntitySystem_AddEntityIOEvent\'");
}
CBaseEntity_EmitSoundFilter = decltype(CBaseEntity_EmitSoundFilter) (
CBaseEntity_EmitSoundFilter = decltype(CBaseEntity_EmitSoundFilter)(
modules::server->FindSignature(globals::gameConfig->GetSignature("CBaseEntity_EmitSoundFilter")));
if (!CBaseEntity_EmitSoundFilter)
@@ -104,7 +114,8 @@ void CEntityListener::OnEntitySpawned(CEntityInstance* pEntity)
{
auto callback = globals::entityManager.on_entity_spawned_callback;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->ScriptContext().Push(pEntity);
callback->Execute();
@@ -114,7 +125,8 @@ void CEntityListener::OnEntityCreated(CEntityInstance* pEntity)
{
auto callback = globals::entityManager.on_entity_created_callback;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->ScriptContext().Push(pEntity);
callback->Execute();
@@ -124,7 +136,8 @@ void CEntityListener::OnEntityDeleted(CEntityInstance* pEntity)
{
auto callback = globals::entityManager.on_entity_deleted_callback;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->ScriptContext().Push(pEntity);
callback->Execute();
@@ -134,7 +147,8 @@ void CEntityListener::OnEntityParentChanged(CEntityInstance* pEntity, CEntityIns
{
auto callback = globals::entityManager.on_entity_parent_changed_callback;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
callback->ScriptContext().Reset();
callback->ScriptContext().Push(pEntity);
callback->ScriptContext().Push(pNewParent);
@@ -142,49 +156,58 @@ void CEntityListener::OnEntityParentChanged(CEntityInstance* pEntity, CEntityIns
}
}
void EntityManager::HookEntityOutput(const char* szClassname, const char* szOutput,
CallbackT fnCallback, HookMode mode)
void EntityManager::HookEntityOutput(const char* szClassname, const char* szOutput, CallbackT fnCallback, HookMode mode)
{
auto outputKey = OutputKey_t(szClassname, szOutput);
CallbackPair* pCallbackPair;
auto search = m_pHookMap.find(outputKey);
if (search == m_pHookMap.end()) {
if (search == m_pHookMap.end())
{
m_pHookMap[outputKey] = new CallbackPair();
pCallbackPair = m_pHookMap[outputKey];
} else
}
else
pCallbackPair = search->second;
auto* pCallback = mode == HookMode::Pre ? pCallbackPair->pre : pCallbackPair->post;
pCallback->AddListener(fnCallback);
}
void EntityManager::UnhookEntityOutput(const char* szClassname, const char* szOutput,
CallbackT fnCallback, HookMode mode)
void EntityManager::UnhookEntityOutput(const char* szClassname, const char* szOutput, CallbackT fnCallback, HookMode mode)
{
auto outputKey = OutputKey_t(szClassname, szOutput);
auto search = m_pHookMap.find(outputKey);
if (search != m_pHookMap.end()) {
if (search != m_pHookMap.end())
{
auto* pCallbackPair = search->second;
auto* pCallback = mode == Pre ? pCallbackPair->pre : pCallbackPair->post;
pCallback->RemoveListener(fnCallback);
if (!pCallbackPair->HasCallbacks()) {
if (!pCallbackPair->HasCallbacks())
{
m_pHookMap.erase(outputKey);
}
}
}
void EntityManager::CheckTransmit(CCheckTransmitInfo** pInfoInfoList, int nInfoCount, CBitVec<16384>& unionTransmitEdicts, const Entity2Networkable_t** pNetworkables, const uint16* pEntityIndicies, int nEntityIndices, bool bEnablePVSBits)
void EntityManager::CheckTransmit(CCheckTransmitInfo** pInfoInfoList,
int nInfoCount,
CBitVec<16384>& unionTransmitEdicts,
const Entity2Networkable_t** pNetworkables,
const uint16* pEntityIndicies,
int nEntityIndices,
bool bEnablePVSBits)
{
VPROF_BUDGET(m_profile_name.c_str(), "CS# CheckTransmit");
auto callback = globals::entityManager.check_transmit;
if (callback && callback->GetFunctionCount()) {
if (callback && callback->GetFunctionCount())
{
CCheckTransmitInfoList* infoList = new CCheckTransmitInfoList(pInfoInfoList, nInfoCount);
callback->ScriptContext().Reset();
@@ -195,39 +218,43 @@ void EntityManager::CheckTransmit(CCheckTransmitInfo** pInfoInfoList, int nInfoC
}
}
void DetourFireOutputInternal(CEntityIOOutput* const pThis, CEntityInstance* pActivator,
CEntityInstance* pCaller, const CVariant* const value, float flDelay)
void DetourFireOutputInternal(
CEntityIOOutput* const pThis, CEntityInstance* pActivator, CEntityInstance* pCaller, const CVariant* const value, float flDelay)
{
std::vector vecSearchKeys{OutputKey_t("*", pThis->m_pDesc->m_pName),
OutputKey_t("*", "*")};
std::vector vecSearchKeys{ OutputKey_t("*", pThis->m_pDesc->m_pName), OutputKey_t("*", "*") };
if (pCaller) {
if (pCaller)
{
vecSearchKeys.push_back(OutputKey_t(pCaller->GetClassname(), pThis->m_pDesc->m_pName));
OutputKey_t(pCaller->GetClassname(), "*");
}
std::vector<CallbackPair*> vecCallbackPairs;
if (pCaller) {
CSSHARP_CORE_TRACE("[EntityManager][FireOutputHook] - {}, {}", pThis->m_pDesc->m_pName,
pCaller->GetClassname());
if (pCaller)
{
CSSHARP_CORE_TRACE("[EntityManager][FireOutputHook] - {}, {}", pThis->m_pDesc->m_pName, pCaller->GetClassname());
auto& hookMap = globals::entityManager.m_pHookMap;
for (auto& searchKey : vecSearchKeys) {
for (auto& searchKey : vecSearchKeys)
{
auto search = hookMap.find(searchKey);
if (search != hookMap.end()) {
if (search != hookMap.end())
{
vecCallbackPairs.push_back(search->second);
}
}
} else
CSSHARP_CORE_TRACE("[EntityManager][FireOutputHook] - {}, unknown caller",
pThis->m_pDesc->m_pName);
}
else
CSSHARP_CORE_TRACE("[EntityManager][FireOutputHook] - {}, unknown caller", pThis->m_pDesc->m_pName);
HookResult result = HookResult::Continue;
for (auto pCallbackPair : vecCallbackPairs) {
if (pCallbackPair->pre->GetFunctionCount()) {
for (auto pCallbackPair : vecCallbackPairs)
{
if (pCallbackPair->pre->GetFunctionCount())
{
pCallbackPair->pre->ScriptContext().Reset();
pCallbackPair->pre->ScriptContext().Push(pThis);
pCallbackPair->pre->ScriptContext().Push(pThis->m_pDesc->m_pName);
@@ -236,32 +263,37 @@ void DetourFireOutputInternal(CEntityIOOutput* const pThis, CEntityInstance* pAc
pCallbackPair->pre->ScriptContext().Push(value);
pCallbackPair->pre->ScriptContext().Push(flDelay);
for (auto fnMethodToCall : pCallbackPair->pre->GetFunctions()) {
if (!fnMethodToCall)
continue;
for (auto fnMethodToCall : pCallbackPair->pre->GetFunctions())
{
if (!fnMethodToCall) continue;
fnMethodToCall(&pCallbackPair->pre->ScriptContextStruct());
auto thisResult = pCallbackPair->pre->ScriptContext().GetResult<HookResult>();
if (thisResult >= HookResult::Stop) {
if (thisResult >= HookResult::Stop)
{
return;
}
if (thisResult > result) {
if (thisResult > result)
{
result = thisResult;
}
}
}
}
if (result >= HookResult::Handled) {
if (result >= HookResult::Handled)
{
return;
}
m_pFireOutputInternal(pThis, pActivator, pCaller, value, flDelay);
for (auto pCallbackPair : vecCallbackPairs) {
if (pCallbackPair->post->GetFunctionCount()) {
for (auto pCallbackPair : vecCallbackPairs)
{
if (pCallbackPair->post->GetFunctionCount())
{
pCallbackPair->post->ScriptContext().Reset();
pCallbackPair->post->ScriptContext().Push(pThis);
pCallbackPair->post->ScriptContext().Push(pThis->m_pDesc->m_pName);
@@ -276,8 +308,10 @@ void DetourFireOutputInternal(CEntityIOOutput* const pThis, CEntityInstance* pAc
SndOpEventGuid_t EntityEmitSoundFilter(IRecipientFilter& filter, uint32 ent, const char* pszSound, float flVolume, float flPitch)
{
if (!CBaseEntity_EmitSoundFilter) {
CSSHARP_CORE_ERROR("[EntityManager][EmitSoundFilter] - Failed to emit a sound. Signature for \'CBaseEntity_EmitSoundFilter\' is not found. The latest update may have broken it.");
if (!CBaseEntity_EmitSoundFilter)
{
CSSHARP_CORE_ERROR("[EntityManager][EmitSoundFilter] - Failed to emit a sound. Signature for \'CBaseEntity_EmitSoundFilter\' is "
"not found. The latest update may have broken it.");
return SndOpEventGuid_t{};
}

View File

@@ -1,18 +1,18 @@
/*
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
* This file is part of CounterStrikeSharp.
* CounterStrikeSharp is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CounterStrikeSharp is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
#pragma once
@@ -34,24 +34,29 @@ class ScriptCallback;
typedef std::pair<std::string, std::string> OutputKey_t;
class CEntityListener : public IEntityListener {
void OnEntitySpawned(CEntityInstance *pEntity) override;
void OnEntityCreated(CEntityInstance *pEntity) override;
void OnEntityDeleted(CEntityInstance *pEntity) override;
void OnEntityParentChanged(CEntityInstance *pEntity, CEntityInstance *pNewParent) override;
class CEntityListener : public IEntityListener
{
void OnEntitySpawned(CEntityInstance* pEntity) override;
void OnEntityCreated(CEntityInstance* pEntity) override;
void OnEntityDeleted(CEntityInstance* pEntity) override;
void OnEntityParentChanged(CEntityInstance* pEntity, CEntityInstance* pNewParent) override;
};
class CCheckTransmitInfoList {
public:
class CCheckTransmitInfoList
{
public:
CCheckTransmitInfoList(CCheckTransmitInfo** pInfoInfoList, int nInfoCount);
private:
private:
CCheckTransmitInfo** infoList;
int infoCount;
};
class EntityManager : public GlobalClass {
class EntityManager : public GlobalClass
{
friend CEntityListener;
public:
public:
EntityManager();
~EntityManager();
void OnAllInitialized() override;
@@ -60,19 +65,25 @@ public:
void UnhookEntityOutput(const char* szClassname, const char* szOutput, CallbackT fnCallback, HookMode mode);
CEntityListener entityListener;
std::map<OutputKey_t, CallbackPair*> m_pHookMap;
private:
void CheckTransmit(CCheckTransmitInfo** pInfoInfoList, int nInfoCount, CBitVec<16384>& unionTransmitEdicts, const Entity2Networkable_t** pNetworkables, const uint16* pEntityIndicies, int nEntityIndices, bool bEnablePVSBits);
ScriptCallback *on_entity_spawned_callback;
ScriptCallback *on_entity_created_callback;
ScriptCallback *on_entity_deleted_callback;
ScriptCallback *on_entity_parent_changed_callback;
ScriptCallback *check_transmit;
private:
void CheckTransmit(CCheckTransmitInfo** pInfoInfoList,
int nInfoCount,
CBitVec<16384>& unionTransmitEdicts,
const Entity2Networkable_t** pNetworkables,
const uint16* pEntityIndicies,
int nEntityIndices,
bool bEnablePVSBits);
ScriptCallback* on_entity_spawned_callback;
ScriptCallback* on_entity_created_callback;
ScriptCallback* on_entity_deleted_callback;
ScriptCallback* on_entity_parent_changed_callback;
ScriptCallback* check_transmit;
std::string m_profile_name;
};
enum EntityIOTargetType_t
{
ENTITY_IO_TARGET_INVALID = 0xFFFFFFFF,
@@ -118,16 +129,16 @@ class CEntityIOOutput
EntityIOOutputDesc_t* m_pDesc;
};
typedef void (*FireOutputInternal)(CEntityIOOutput* const, CEntityInstance*, CEntityInstance*,
const CVariant* const, float);
typedef void (*FireOutputInternal)(CEntityIOOutput* const, CEntityInstance*, CEntityInstance*, const CVariant* const, float);
static void DetourFireOutputInternal(CEntityIOOutput* const pThis, CEntityInstance* pActivator,
CEntityInstance* pCaller, const CVariant* const value, float flDelay);
static void DetourFireOutputInternal(
CEntityIOOutput* const pThis, CEntityInstance* pActivator, CEntityInstance* pCaller, const CVariant* const value, float flDelay);
static FireOutputInternal m_pFireOutputInternal = nullptr;
// Do it in here because i didn't found a good place to do this
inline void (*CEntityInstance_AcceptInput)(CEntityInstance* pThis, const char* pInputName, CEntityInstance* pActivator, CEntityInstance* pCaller, variant_t* value, int nOutputID);
inline void (*CEntityInstance_AcceptInput)(
CEntityInstance* pThis, const char* pInputName, CEntityInstance* pActivator, CEntityInstance* pCaller, variant_t* value, int nOutputID);
inline void (*CEntitySystem_AddEntityIOEvent)(CEntitySystem* pEntitySystem,
CEntityInstance* pTarget,
@@ -142,66 +153,53 @@ typedef uint32 SoundEventGuid_t;
enum gender_t : uint8
{
GENDER_NONE = 0x0,
GENDER_MALE = 0x1,
GENDER_FEMALE = 0x2,
GENDER_NAMVET = 0x3,
GENDER_TEENGIRL = 0x4,
GENDER_BIKER = 0x5,
GENDER_MANAGER = 0x6,
GENDER_GAMBLER = 0x7,
GENDER_PRODUCER = 0x8,
GENDER_COACH = 0x9,
GENDER_MECHANIC = 0xA,
GENDER_CEDA = 0xB,
GENDER_CRAWLER = 0xC,
GENDER_UNDISTRACTABLE = 0xD,
GENDER_FALLEN = 0xE,
GENDER_RIOT_CONTROL = 0xF,
GENDER_CLOWN = 0x10,
GENDER_JIMMY = 0x11,
GENDER_HOSPITAL_PATIENT = 0x12,
GENDER_BRIDE = 0x13,
GENDER_LAST = 0x14,
GENDER_NONE = 0x0,
GENDER_MALE = 0x1,
GENDER_FEMALE = 0x2,
GENDER_NAMVET = 0x3,
GENDER_TEENGIRL = 0x4,
GENDER_BIKER = 0x5,
GENDER_MANAGER = 0x6,
GENDER_GAMBLER = 0x7,
GENDER_PRODUCER = 0x8,
GENDER_COACH = 0x9,
GENDER_MECHANIC = 0xA,
GENDER_CEDA = 0xB,
GENDER_CRAWLER = 0xC,
GENDER_UNDISTRACTABLE = 0xD,
GENDER_FALLEN = 0xE,
GENDER_RIOT_CONTROL = 0xF,
GENDER_CLOWN = 0x10,
GENDER_JIMMY = 0x11,
GENDER_HOSPITAL_PATIENT = 0x12,
GENDER_BRIDE = 0x13,
GENDER_LAST = 0x14,
};
struct EmitSound_t
{
EmitSound_t() :
m_nChannel(0),
m_pSoundName(0),
m_flVolume(VOL_NORM),
m_SoundLevel(SNDLVL_NONE),
m_nFlags(0),
m_nPitch(PITCH_NORM),
m_pOrigin(0),
m_flSoundTime(0.0f),
m_pflSoundDuration(0),
m_bEmitCloseCaption(true),
m_bWarnOnMissingCloseCaption(false),
m_bWarnOnDirectWaveReference(false),
m_nSpeakerEntity(-1),
m_UtlVecSoundOrigin(),
m_nForceGuid(0),
m_SpeakerGender(GENDER_NONE)
{
}
int m_nChannel;
const char* m_pSoundName;
float m_flVolume;
soundlevel_t m_SoundLevel;
int m_nFlags;
int m_nPitch;
const Vector* m_pOrigin;
float m_flSoundTime;
float* m_pflSoundDuration;
bool m_bEmitCloseCaption;
bool m_bWarnOnMissingCloseCaption;
bool m_bWarnOnDirectWaveReference;
CEntityIndex m_nSpeakerEntity;
CUtlVector<Vector, CUtlMemory<Vector, int> > m_UtlVecSoundOrigin;
SoundEventGuid_t m_nForceGuid;
gender_t m_SpeakerGender;
EmitSound_t()
: m_nChannel(0), m_pSoundName(0), m_flVolume(VOL_NORM), m_SoundLevel(SNDLVL_NONE), m_nFlags(0), m_nPitch(PITCH_NORM), m_pOrigin(0),
m_flSoundTime(0.0f), m_pflSoundDuration(0), m_bEmitCloseCaption(true), m_bWarnOnMissingCloseCaption(false),
m_bWarnOnDirectWaveReference(false), m_nSpeakerEntity(-1), m_UtlVecSoundOrigin(), m_nForceGuid(0), m_SpeakerGender(GENDER_NONE)
{
}
int m_nChannel;
const char* m_pSoundName;
float m_flVolume;
soundlevel_t m_SoundLevel;
int m_nFlags;
int m_nPitch;
const Vector* m_pOrigin;
float m_flSoundTime;
float* m_pflSoundDuration;
bool m_bEmitCloseCaption;
bool m_bWarnOnMissingCloseCaption;
bool m_bWarnOnDirectWaveReference;
CEntityIndex m_nSpeakerEntity;
CUtlVector<Vector, CUtlMemory<Vector, int>> m_UtlVecSoundOrigin;
SoundEventGuid_t m_nForceGuid;
gender_t m_SpeakerGender;
};
struct SndOpEventGuid_t
@@ -212,5 +210,6 @@ struct SndOpEventGuid_t
inline SndOpEventGuid_t(FASTCALL* CBaseEntity_EmitSoundFilter)(IRecipientFilter& filter, CEntityIndex ent, const EmitSound_t& params);
SndOpEventGuid_t EntityEmitSoundFilter(IRecipientFilter& filter, uint32 ent, const char* pszSound, float flVolume = 1.0f, float flPitch = 1.0f);
} // namespace counterstrikesharp
SndOpEventGuid_t
EntityEmitSoundFilter(IRecipientFilter& filter, uint32 ent, const char* pszSound, float flVolume = 1.0f, float flPitch = 1.0f);
} // namespace counterstrikesharp

View File

@@ -270,8 +270,15 @@ bool EventManager::OnFireEventPost(IGameEvent* pEvent, bool bDontBroadcast)
pCallback->ScriptContext().Push(&override);
pCallback->Execute();
globals::gameEventManager->FreeEvent(pEventCopy);
m_EventCopies.pop();
if (pEventCopy)
{
globals::gameEventManager->FreeEvent(pEventCopy);
m_EventCopies.pop();
}
else
{
CSSHARP_CORE_WARN("OnFireEventPost: pEventCopy is nullptr, cannot free event");
}
}
}

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