Compare commits

...

32 Commits

Author SHA1 Message Date
roflmuffin
0de951cb6f fix: allows game events to be freed, frees event in print to center html
closes #346
2024-03-08 10:39:59 +10:00
Michael Wilson
c3d44a87bc feat: use concurrent queue for next frame & world update tasks (#365) 2024-03-06 21:08:22 +10:00
B3none
bd3c0c76e3 [no ci] Update minimum api version for shared api docs (#364) 2024-03-06 15:42:34 +10:00
Yarukon
656c0e3a84 Fix TerminateRound params (#363) 2024-03-04 10:59:02 +00:00
Michael Wilson
40c842149c fix: add error handling to OnAllPluginsLoaded 2024-03-04 17:21:50 +10:00
roflmuffin
64d1c0a9f4 chore: remove erroneous log 2024-03-04 16:56:49 +10:00
roflmuffin
a6de51c444 fix: use concurrent dictionary for function reference 2024-03-04 13:41:18 +10:00
roflmuffin
2535ac0575 feat: add assembly name lazy loading of shared libraries 2024-03-04 12:15:37 +10:00
Michael Wilson
bc61323315 chore: migrate to protobufs submodule (#362) 2024-03-04 10:48:52 +10:00
roflmuffin
241817b7f2 feat: update game events dump from Feb 14 update 2024-03-04 10:34:58 +10:00
BuSheeZy
fbcdce34fc fix: allow empty overrides to skip checks (#357)
Co-authored-by: Michael Wilson <roflmuffin@users.noreply.github.com>
2024-03-04 00:13:17 +00:00
Michael Wilson
daf0d25f36 Shared Plugin APIs/Capabilities (#253)
Co-authored-by: B3none <ablackham2000@gmail.com>
Co-authored-by: B3none <24966460+B3none@users.noreply.github.com>
2024-03-04 09:45:34 +10:00
Yarukon
12485be29f Adding the proper way to do resource precache (#358) 2024-03-02 15:10:37 +10:00
Roflmuffin
983d91491d fix: update gamedata 2024-02-29 12:01:01 +10:00
BuSheeZy
71507b1e25 fix: allow using an empty flag array in overrides (#351)
Co-authored-by: Ryan Bucshon <busheezy@users.noreply.github.com>
Co-authored-by: Michael Wilson <roflmuffin@users.noreply.github.com>
2024-02-29 01:35:21 +00:00
B3none
cfe14b35fe [no ci] Bump the min api version in the fake convars example plugin (#350) 2024-02-28 15:08:23 +10:00
Poggu
5a6cdf0da3 feat: improve entity validation (#348) 2024-02-27 16:12:56 +10:00
Michael Wilson
a5399dd5fe feat: add FakeConVar class (#325) 2024-02-26 16:55:19 +10:00
Roflmuffin
ab996c34e9 fix: use function reference for next frame tasks
fixes #178
2024-02-26 09:20:56 +10:00
B3none
6e2e25b96e Re-implemented css_lang command (#343) 2024-02-26 08:56:16 +10:00
Roflmuffin
1142c9f063 [no ci] remove untriaged label when milestoning issues 2024-02-24 14:58:01 +10:00
Michael Wilson
72178c9598 feat: add chat color method for player controller (#339) 2024-02-24 14:56:56 +10:00
Michael Wilson
7617bd1556 fix: handle byte array schema properties correctly (#338) 2024-02-24 14:27:45 +10:00
Michael Wilson
501d51a668 feat: add CommandCallingContext to commands (#337) 2024-02-24 10:41:07 +10:00
Michael Wilson
87f48cb35c chore: update hl2sdk (#336) 2024-02-22 21:52:39 +10:00
Michael Wilson
39aa430528 [no ci] Create FUNDING.yml 🥰 2024-02-22 15:03:49 +10:00
roflmuffin
a404a4d9d5 [no ci] remove untriaged when author action label applied 2024-02-22 10:58:44 +10:00
roflmuffin
62ba29891d [no ci] add basic issue management workflows 2024-02-22 10:51:18 +10:00
Michael Wilson
48fa9ca076 Command Overhaul (#330) 2024-02-19 18:38:07 +10:00
Roflmuffin
607e6c61f5 feat: add ExecuteClientCommandFromServer native 2024-02-16 18:33:20 +10:00
Michael Wilson
2675d280e3 [no ci] Update LICENSE 2024-02-12 22:54:16 +10:00
B3none
f336dec616 Update .gitmodules to use https references rather than git reference (#297)
Co-authored-by: Michael Wilson <roflmuffin@users.noreply.github.com>
2024-02-11 06:43:23 +00:00
144 changed files with 6893 additions and 1228 deletions

14
.github/FUNDING.yml vendored Normal file
View File

@@ -0,0 +1,14 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
custom: ['https://support.cssharp.dev']

View File

@@ -0,0 +1,29 @@
name: Add comment for needs-author-action
on:
issues:
types:
- labeled
jobs:
add-comment:
if: github.event.label.name == 'needs-author-action'
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- name: Add comment
run: gh issue comment "$NUMBER" --body "$BODY"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
NUMBER: ${{ github.event.issue.number }}
BODY: This issue has been marked `needs-author-action` and may be missing some important information.
- name: Remove label
run: gh issue edit "$NUMBER" --remove-label "$LABELS"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
NUMBER: ${{ github.event.issue.number }}
LABELS: untriaged

View File

@@ -0,0 +1,29 @@
name: Add comment for needs-author-action
on:
issue_comment:
types:
- created
jobs:
add-comment:
if: (github.event.sender.id == github.event.issue.user.id) && contains(github.event.issue.labels.*.name, 'needs-author-action')
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- name: Remove label
run: gh issue edit "$NUMBER" --remove-label "$LABELS"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
NUMBER: ${{ github.event.issue.number }}
LABELS: needs-author-action
- name: Add label
run: gh issue edit "$NUMBER" --add-label "$LABELS"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
NUMBER: ${{ github.event.issue.number }}
LABELS: needs-further-triage

24
.github/workflows/issues-stale.yml vendored Normal file
View File

@@ -0,0 +1,24 @@
name: Mark stale issues
on:
schedule:
- cron: '28 3 * * *'
jobs:
stale:
runs-on: ubuntu-latest
permissions:
issues: write
pull-requests: write
steps:
- uses: actions/stale@v5
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
days-before-issue-stale: 14
days-before-issue-close: 14
stale-issue-label: 'no-recent-activity'
only-labels: 'needs-author-action'
stale-issue-message: 'This issue has been automatically marked `no-recent-activity` because it has not had any activity for 14 days. It will be closed if no further activity occurs within 14 more days. Any new comment (by anyone, not necessarily the author) will remove no-recent-activity.'
close-issue-message: 'This issue will now be closed since it had been marked `no-recent-activity` but received no further activity in the past 14 days.'

20
.github/workflows/issues-triage-new.yml vendored Normal file
View File

@@ -0,0 +1,20 @@
name: Label new issues
on:
issues:
types:
- reopened
- opened
jobs:
label_issues:
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- run: gh issue edit "$NUMBER" --add-label "$LABELS"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
NUMBER: ${{ github.event.issue.number }}
LABELS: untriaged

View File

@@ -0,0 +1,20 @@
name: Label new issues
on:
issues:
types:
- milestoned
jobs:
label_issues:
runs-on: ubuntu-latest
permissions:
issues: write
steps:
- name: Remove label
run: gh issue edit "$NUMBER" --remove-label "$LABELS"
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
NUMBER: ${{ github.event.issue.number }}
LABELS: untriaged

10
.gitmodules vendored
View File

@@ -14,12 +14,12 @@
[submodule "libraries/dyncall"]
path = libraries/dyncall
url = https://github.com/LWJGL-CI/dyncall
[submodule "libraries/GameTracking-CS2"]
path = libraries/GameTracking-CS2
url = https://github.com/SteamDatabase/GameTracking-CS2
[submodule "libraries/DynoHook"]
path = libraries/DynoHook
url = git@github.com:qubka/DynoHook.git
url = https://github.com/qubka/DynoHook
[submodule "libraries/asmjit"]
path = libraries/asmjit
url = git@github.com:asmjit/asmjit.git
url = https://github.com/asmjit/asmjit
[submodule "libraries/Protobufs"]
path = libraries/Protobufs
url = https://github.com/SteamDatabase/Protobufs

View File

@@ -18,8 +18,10 @@ SET(SOURCE_FILES
src/mm_plugin.h
libraries/hl2sdk-cs2/tier1/convar.cpp
libraries/hl2sdk-cs2/tier1/generichash.cpp
libraries/hl2sdk-cs2/tier1/keyvalues3.cpp
libraries/hl2sdk-cs2/entity2/entityidentity.cpp
libraries/hl2sdk-cs2/entity2/entitysystem.cpp
libraries/hl2sdk-cs2/entity2/entitykeyvalues.cpp
libraries/dotnet/hostfxr.h
libraries/dotnet/coreclr_delegates.h
libraries/metamod-source/core/sourcehook/sourcehook.cpp
@@ -88,6 +90,8 @@ SET(SOURCE_FILES
src/core/managers/voice_manager.cpp
src/core/managers/voice_manager.h
src/scripting/natives/natives_dynamichooks.cpp
src/core/game_system.h
src/core/game_system.cpp
)
@@ -99,8 +103,8 @@ if (LINUX)
)
endif()
set(PROTO_DIRS -I${CMAKE_CURRENT_SOURCE_DIR}/libraries/GameTracking-CS2/Protobufs)
file(GLOB PROTOS "${CMAKE_CURRENT_SOURCE_DIR}/libraries/GameTracking-CS2/Protobufs/*.proto")
set(PROTO_DIRS -I${CMAKE_CURRENT_SOURCE_DIR}/libraries/Protobufs/csgo)
file(GLOB PROTOS "${CMAKE_CURRENT_SOURCE_DIR}/libraries/Protobufs/csgo/*.proto")
## Generate protobuf source & headers
if (LINUX)

683
LICENSE
View File

@@ -1,674 +1,9 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program 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.
This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
CounterStrikeSharp is licensed under the GNU General Public License, version 3.
As a special exception to the GNU General Public License 3.0, the license holder
permits licensing of DERIVATIVE WORKS ONLY (that is,
CounterStrikeSharp plugins and extensions, or any software built
referencing published .NET packages) under the MIT license.
A copy of the GNU General Public License 3.0 is available in LICENSE.GPL3
A copy of the MIT License is available in LICENSE.MIT

674
LICENSE.GPL3 Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program 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.
This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

8
LICENSE.MIT Normal file
View File

@@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright © 2024 Michael (Roflmuffin) Wilson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -128,4 +128,10 @@ Build
```bash
cmake --build . --config Debug
```
License
-------
CounterStrikeSharp is licensed under the GNU General Public License version 3. A special exemption is outlined regarding published plugins, which you can find in the [LICENSE](LICENSE) file.
<img src="https://repobeats.axiom.co/api/embed/a96f228b8fa98c032070fa8dd831c967334ee553.svg" width="100%" />

View File

@@ -28,8 +28,8 @@
},
"CCSPlayerController_Respawn": {
"offsets": {
"windows": 245,
"linux": 247
"windows": 244,
"linux": 246
}
},
"CBasePlayerController_SetPawn": {
@@ -206,5 +206,18 @@
"windows": "\\x4C\\x89\\x4C\\x24\\x20\\x53\\x55\\x57\\x41\\x54\\x41\\x56\\x48\\x81\\xEC",
"linux": "\\x55\\x48\\x89\\xE5\\x41\\x57\\x41\\x56\\x41\\x55\\x41\\x54\\x49\\x89\\xD4\\x53\\x48\\x89\\xF3\\x48\\x83\\xEC\\x58"
}
},
"IGameSystem_InitAllSystems_pFirst": {
"signatures": {
"library": "server",
"windows": "\\x48\\x8B\\x1D\\x2A\\x2A\\x2A\\x2A\\x48\\x85\\xDB\\x0F\\x84\\x2A\\x2A\\x2A\\x2A\\xBE\\x2A\\x2A\\x2A\\x2A\\x0F\\x1F\\x00\\x48\\x8B\\x7B\\x10",
"linux": "\\x4C\\x8B\\x35\\x2A\\x2A\\x2A\\x2A\\x4D\\x85\\xF6\\x75\\x2D\\xE9\\x2A\\x2A\\x2A\\x2A\\x0F\\x1F\\x40\\x00\\x48\\x8B\\x05"
}
},
"CEntityResourceManifest_AddResource": {
"offsets": {
"windows": 2,
"linux": 2
}
}
}

View File

@@ -0,0 +1 @@
This folder should contain any shared APIs, in the same DLL structure as the plugins folder (MySharedApi/MySharedApi.dll)

View File

@@ -0,0 +1,67 @@
---
title: Shared Plugin API (Capabilities)
description: How to add inter-plugin communication to CounterStrikeSharp plugins.
---
# Shared Plugin API
How to expose and use shared plugin APIs between multiple plugins.
## Creating a Contract Library
Inter-plugin communication requires a contract/shared library that simply exposes the shape of the API, using simple interfaces. e.g.
```csharp
public interface IBalanceHandler
{
decimal Balance { get; }
// These are just here to show that you can have methods on your shared types.
// You could also add a Setter to the Balance property.
public decimal Add(decimal amount);
public decimal Subtract(decimal amount);
}
```
This library ideally should not contain any business logic, and simply define the schema for callers.
This library should be placed in the `shared` subfolder, in the same folder layout as the plugins folder. So if a contract DLL is named `MySharedApi.dll` its file path should be: `shared/MySharedApi/MySharedApi.dll`.
## Creating a Capability
A capability can be declared with a simple static variable in your plugin class. A `PlayerCapability` is a player specific capability, and a `PluginCapability` is generic functionality that a plugin can expose.
```csharp
public static PlayerCapability<IBalanceHandler> BalanceCapability { get; } = new("myplugin:balance");
public static PluginCapability<IBalanceService> BalanceServiceCapability { get; } = new("myplugin:balance_service");
```
For every plugin that wishes to use this new "Balance API", they must ensure they create a capability using the shared API interface (`IBalanceHandler`), as well as use the same name (`myplugin:balance`).
## Registering a Capability
If you are the plugin that is expected to provide the basis of the API (i.e. you are providing a currency/balance plugin which does nothing except store users balances), then you will need to provide the implementation that other callers will use. This is done through the use of static members on the `Capabilities` class:
```csharp
// Player capabilities are given the calling player context
Capabilities.RegisterPlayerCapability(BalanceCapability, player => new BalanceHandler(player));
// Plugin capabilities can simply return an instance of the interface
Capabilities.RegisterPluginCapability(BalanceServiceCapability, () => new BalanceService());
```
### Using Capabilities
To utilise a capability, simply call the `.Get()` method provided on the static capability you declared earlier, i.e.
```csharp
var balance = BalanceCapability.Get(player);
var balanceService = BalanceServiceCapability.Get();
if (balance == null) return;
balance.Add(500);
```
This value _MUST_ be checked for null, as if there are no plugins providing implementations for a given capability, this method will return null, and you must handle this flow in your plugin.

View File

@@ -9,3 +9,6 @@
- name: Global Listeners
href: global-listeners.md
- name: Shared Plugin API
href: shared-plugin-api.md

View File

@@ -0,0 +1,5 @@
[!INCLUDE [WithFakeConvars](../../examples/WithFakeConvars/README.md)]
<a href="https://github.com/roflmuffin/CounterStrikeSharp/tree/main/examples/WithFakeConvars" class="btn btn-secondary">View project on Github <i class="bi bi-github"></i></a>
[!code-csharp[](../../examples/WithFakeConvars/WithFakeConvarsPlugin.cs)]

View File

@@ -0,0 +1,11 @@
[!INCLUDE [WithSharedTypes](../../examples/WithSharedTypes/README.md)]
<a href="https://github.com/roflmuffin/CounterStrikeSharp/tree/main/examples/WithSharedTypes" class="btn btn-secondary">View project on Github <i class="bi bi-github"></i></a>
[!code-csharp[](../../examples/WithSharedTypes/WithSharedTypesPlugin.cs)]
[!INCLUDE [WithSharedTypesConsumer](../../examples/WithSharedTypesConsumer/README.md)]
<a href="https://github.com/roflmuffin/CounterStrikeSharp/tree/main/examples/WithSharedTypesConsumer" class="btn btn-secondary">View project on Github <i class="bi bi-github"></i></a>
[!code-csharp[](../../examples/WithSharedTypesConsumer/WithSharedTypesConsumerPlugin.cs)]

View File

@@ -3,6 +3,8 @@ items:
href: HelloWorld.md
- name: Commands
href: WithCommands.md
- name: Fake ConVars
href: WithFakeConvars.md
- name: Config
href: WithConfig.md
- name: Dependency Injection
@@ -13,6 +15,8 @@ items:
href: WithGameEventHandlers.md
- name: Database (Dapper)
href: WithDatabase.md
- name: Shared Plugin Types
href: WithSharedTypes.md
- name: Translations
href: WithTranslations.md
- name: Voice Overrides

View File

@@ -0,0 +1,11 @@
namespace MySharedTypes.Contracts;
public interface IBalanceHandler
{
decimal Balance { get; }
// These are just here to show that you can have methods on your shared types.
// You could also add a Setter to the Balance property.
public decimal Add(decimal amount);
public decimal Subtract(decimal amount);
}

View File

@@ -0,0 +1,6 @@
namespace MySharedTypes.Contracts;
public interface IBalanceService
{
public void ClearAllBalances();
}

View File

@@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>

View File

@@ -0,0 +1,9 @@
using CounterStrikeSharp.API.Modules.Cvars;
namespace WithFakeConvars;
public static class ConVars
{
// This convar is registered from the plugin instance but can be used anywhere.
public static FakeConVar<int> ExampleStaticCvar = new("example_static", "An example static cvar");
}

View File

@@ -0,0 +1,21 @@
using CounterStrikeSharp.API.Modules.Cvars.Validators;
namespace WithFakeConvars;
// This is an example of a custom validator that checks if a number is even.
public class EvenNumberValidator : IValidator<int>
{
public bool Validate(int value, out string? errorMessage)
{
if (value % 2 == 0)
{
errorMessage = null;
return true;
}
else
{
errorMessage = "Value must be an even number";
return false;
}
}
}

View File

@@ -0,0 +1,2 @@
# With Fake Convars
This is an example that shows how to register "fake" convars, which are actually console commands that track their internal state.

View File

@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\managed\CounterStrikeSharp.API\CounterStrikeSharp.API.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,58 @@
using CounterStrikeSharp.API;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Modules.Cvars;
using CounterStrikeSharp.API.Modules.Cvars.Validators;
namespace WithFakeConvars;
[MinimumApiVersion(175)]
public class WithFakeConvarsPlugin : BasePlugin
{
public override string ModuleName => "Example: With Fake Convars";
public override string ModuleVersion => "1.0.0";
public override string ModuleAuthor => "CounterStrikeSharp & Contributors";
public override string ModuleDescription => "A simple plugin that registers some console variables";
// FakeConVar is a class that can be used to create custom console variables.
// You can specify a name, description, default value, and custom validators.
public FakeConVar<bool> BoolCvar = new("example_bool", "An example boolean cvar", true);
// Range validator is an inbuilt validator that can be used to ensure that a value is within a certain range.
public FakeConVar<int> ExampleIntCvar = new("example_int", "An example integer cvar", 10, flags: ConVarFlags.FCVAR_NONE, new RangeValidator<int>(0, 100));
public FakeConVar<float> ExampleFloatCvar = new("example_float", "An example float cvar", 10, flags: ConVarFlags.FCVAR_NONE, new RangeValidator<float>(5, 20));
public FakeConVar<string> ExampleStringCvar = new("example_string", "An example string cvar", "default");
// Replicated, Cheat & Protected flags are supported.
public FakeConVar<float> ExamplePublicCvar = new("example_public_float", "An example public float cvar", 5,
ConVarFlags.FCVAR_REPLICATED);
// Can only be changed if sv_cheats is enabled.
public FakeConVar<float> ExampleCheatCvar = new("example_cheat_float", "An example cheat float cvar", 5,
ConVarFlags.FCVAR_CHEAT);
// Protected cvars do not output their value when queried.
public FakeConVar<float> ExampleProtectedCvar = new("example_protected_float", "An example cheat float cvar", 5,
ConVarFlags.FCVAR_PROTECTED);
// You can create your own custom validators by implementing the IValidator interface.
public FakeConVar<int> ExampleEvenNumberCvar = new("example_even_number", "An example even number cvar", 0, flags: ConVarFlags.FCVAR_NONE, new EvenNumberValidator());
public FakeConVar<int> RequiresRestartCvar = new("example_requires_restart", "A cvar that requires a restart when changed");
public override void Load(bool hotReload)
{
// You can subscribe to the ValueChanged event to execute code when the value of a cvar changes.
// In this example, we restart the game when the value of RequiresRestartCvar is greater than 5.
RequiresRestartCvar.ValueChanged += (sender, value) =>
{
if (value > 5)
{
Server.ExecuteCommand("mp_restartgame 1");
}
};
RegisterFakeConVars(typeof(ConVars));
}
}

View File

@@ -0,0 +1,33 @@
using CounterStrikeSharp.API.Core;
using MySharedTypes.Contracts;
namespace WithSharedTypes;
public class BalanceHandler : IBalanceHandler
{
private readonly CCSPlayerController _player;
// This could be a database, a file, or a dictionary like this.
internal static readonly Dictionary<CCSPlayerController, decimal> Balances = new();
public BalanceHandler(CCSPlayerController player)
{
_player = player;
}
public decimal Balance
{
get => Balances.TryGetValue(_player, out var balance) ? balance : 0;
set => Balances[_player] = value;
}
public decimal Add(decimal amount)
{
return Balance += amount;
}
public decimal Subtract(decimal amount)
{
return Balance -= amount;
}
}

View File

@@ -0,0 +1,11 @@
using MySharedTypes.Contracts;
namespace WithSharedTypes;
public class BalanceService : IBalanceService
{
public void ClearAllBalances()
{
BalanceHandler.Balances.Clear();
}
}

View File

@@ -0,0 +1,5 @@
# With Shared Types (Capabilities)
An example plugin that exposes a balance contract library, to use as a shared library between multiple plugins.
This allows one plugin to expose a capability for a player or plugin, and other plugins to use the exposed API.

View File

@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\managed\CounterStrikeSharp.API\CounterStrikeSharp.API.csproj" />
<ProjectReference Include="..\MySharedTypes.Contracts\MySharedTypes.Contracts\MySharedTypes.Contracts.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,57 @@
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Core.Capabilities;
using MySharedTypes.Contracts;
namespace WithSharedTypes;
[MinimumApiVersion(184)]
public class WithSharedTypesPlugin : BasePlugin
{
public override string ModuleName => "Example: Shared Types";
public override string ModuleVersion => "1.0.0";
public override string ModuleAuthor => "CounterStrikeSharp & Contributors";
public override string ModuleDescription => "A simple plugin that shares types between multiple plugins";
// Declares a player capability, that stores some sort of functionality for a player.
// In this case, it's a balance handler, which is used to store a player's balance.
// Note that we use the same name for the capability as the one in the other plugin.
// IBalanceHandler is defined in MySharedTypes.Contracts, which is a shared library and placed in the `shared/` subfolder.
public static PlayerCapability<IBalanceHandler> BalanceCapability { get; } = new("myplugin:balance");
// Declares a player capability of a primitive type, in this case, a decimal.
public static PlayerCapability<Decimal> BalanceCapabilityDecimal { get; } = new("myplugin:balance_decimal");
// Plugin capabilities are similar to player capabilities, but they are not tied to a player, and are just generic APIs
// that are exposed by a plugin. In this case, we expose a balance service, which is used to clear all balances.
public static PluginCapability<IBalanceService> BalanceServiceCapability { get; } = new("myplugin:balance_service");
public override void Load(bool hotReload)
{
// Register the capability implementations here. Note that plugins don't need to register an implementation if it is already implemented in another plugin.
Capabilities.RegisterPlayerCapability(BalanceCapability, player => new BalanceHandler(player));
Capabilities.RegisterPluginCapability(BalanceServiceCapability, () => new BalanceService());
Capabilities.RegisterPlayerCapability(BalanceCapabilityDecimal, (player) => new BalanceHandler(player).Balance);
AddCommand("css_balance", "Gets your current balance", (player, info) =>
{
if (player == null) return;
player.PrintToChat($"Your balance is {BalanceCapability.Get(player)?.Balance}");
});
AddCommand("css_give", "Gives you money", (player, info) =>
{
if (player == null) return;
var balance = BalanceCapability.Get(player);
if (balance == null) return;
balance.Add(100);
player.PrintToChat($"Your balance is now {balance.Balance}");
});
}
public override void Unload(bool hotReload)
{
}
}

View File

@@ -0,0 +1,2 @@
# With Shared Types (Consumer Plugin)
Uses the decimal balance shared library.

View File

@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
<CopyLocalLockFileAssemblies>false</CopyLocalLockFileAssemblies>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\managed\CounterStrikeSharp.API\CounterStrikeSharp.API.csproj" />
<ProjectReference Include="..\MySharedTypes.Contracts\MySharedTypes.Contracts\MySharedTypes.Contracts.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,56 @@
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Core.Capabilities;
using CounterStrikeSharp.API.Core.Plugin;
using MySharedTypes.Contracts;
namespace WithSharedTypesConsumer;
[MinimumApiVersion(184)]
public class WithSharedTypesConsumerPlugin : BasePlugin
{
public override string ModuleName => "Example: Shared Types (Consumer)";
public override string ModuleVersion => "1.0.0";
public override string ModuleAuthor => "CounterStrikeSharp & Contributors";
public override string ModuleDescription => "A simple plugin that utilises the balance api from another plugin";
public static PlayerCapability<IBalanceHandler> BalanceCapability { get; } = new("myplugin:balance");
public static PlayerCapability<Decimal> BalanceCapabilityDecimal { get; } = new("myplugin:balance_decimal");
public static PluginCapability<IBalanceService> BalanceServiceCapability { get; } = new("myplugin:balance_service");
public override void Load(bool hotReload)
{
AddCommand("css_subtract", "Subtracts 50 from your balance", (player, info) =>
{
if (player == null) return;
var balance = BalanceCapability.Get(player);
if (balance == null) return;
balance.Subtract(50);
player.PrintToChat($"Your balance is now {balance.Balance}");
});
AddCommand("css_clearbalances", "Clears all balances", (player, info) =>
{
if (player == null) return;
var service = BalanceServiceCapability.Get();
if (service == null) return;
service.ClearAllBalances();
var balance = BalanceCapability.Get(player);
if (balance == null) return;
player.PrintToChat($"Your balance is now {balance.Balance}");
});
AddCommand("css_decimalbalance", "Gets your current balance", (player, info) =>
{
if (player == null) return;
player.PrintToChat($"Your balance is {BalanceCapabilityDecimal.Get(player)}");
});
}
public override void Unload(bool hotReload)
{
}
}

1
libraries/Protobufs Submodule

Submodule libraries/Protobufs added at 686a0628e6

File diff suppressed because it is too large Load Diff

View File

@@ -51,6 +51,7 @@ include_directories(
libraries/tl
libraries/funchook/include
libraries/DynoHook/src
libraries/moodycamel
libraries
)

View File

@@ -102,9 +102,18 @@ public class AdminTests
[Fact]
public void ShouldAddCommandPermissionOverridesAtRuntime()
{
Assert.False(AdminManager.CommandIsOverriden("runtime_command"));
AdminManager.AddPermissionOverride("runtime_command", "@runtime/override");
Assert.True(AdminManager.CommandIsOverriden("runtime_command"));
Assert.Equal("@runtime/override", AdminManager.GetPermissionOverrides("runtime_command").Single());
Assert.False(AdminManager.CommandIsOverriden("runtime_command_a"));
AdminManager.AddPermissionOverride("runtime_command_a", "@runtime/override");
Assert.True(AdminManager.CommandIsOverriden("runtime_command_a"));
Assert.Equal("@runtime/override", AdminManager.GetPermissionOverrides("runtime_command_a").Single());
}
[Fact]
public void ShouldAddCommandPermissionOverridesWithEmpty()
{
Assert.False(AdminManager.CommandIsOverriden("runtime_command_b"));
AdminManager.AddPermissionOverride("runtime_command_b");
Assert.True(AdminManager.CommandIsOverriden("runtime_command_b"));
Assert.False(AdminManager.GetPermissionOverrides("runtime_command_b").Any());
}
}

View File

@@ -1,14 +1,16 @@
using System;
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using CounterStrikeSharp.API.Core;
using CounterStrikeSharp.API.Core.Commands;
using CounterStrikeSharp.API.Core.Hosting;
using CounterStrikeSharp.API.Core.Logging;
using CounterStrikeSharp.API.Core.Plugin;
using CounterStrikeSharp.API.Core.Plugin.Host;
using CounterStrikeSharp.API.Core.Translations;
using CounterStrikeSharp.API.Modules.Admin;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
@@ -42,6 +44,7 @@ public static class Bootstrap
services.AddSingleton<IPluginManager, PluginManager>();
services.AddSingleton<IPlayerLanguageManager, PlayerLanguageManager>();
services.AddScoped<IPluginContextQueryHandler, PluginContextQueryHandler>();
services.AddSingleton<ICommandManager, CommandManager>();
services.Scan(i => i.FromCallingAssembly()
.AddClasses(c => c.AssignableTo<IStartupService>())
@@ -50,12 +53,13 @@ public static class Bootstrap
})
.Build();
using IServiceScope scope = host.Services.CreateScope();
using IServiceScope rootScope = host.Services.CreateScope();
// TODO: Improve static singleton access
GameData.GameDataProvider = scope.ServiceProvider.GetRequiredService<GameDataProvider>();
GameData.GameDataProvider = rootScope.ServiceProvider.GetRequiredService<GameDataProvider>();
AdminManager.CommandManagerProvider = rootScope.ServiceProvider.GetRequiredService<ICommandManager>();
var application = scope.ServiceProvider.GetRequiredService<Application>();
var application = rootScope.ServiceProvider.GetRequiredService<Application>();
application.Start();
return 1;

View File

@@ -61,6 +61,12 @@
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0001</DiagnosticId>
<Target>T:CounterStrikeSharp.API.Modules.Utils.CommandUtils</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>F:CounterStrikeSharp.API.Core.AnimParamType_t.ANIMPARAM_STRINGTOKEN</Target>
@@ -169,6 +175,24 @@
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>F:CounterStrikeSharp.API.Modules.Memory.VirtualFunctions.CCSPlayerPawn_Respawn</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>F:CounterStrikeSharp.API.Modules.Memory.VirtualFunctions.CCSPlayerPawn_RespawnFunc</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:CounterStrikeSharp.API.Core.Application.#ctor(Microsoft.Extensions.Logging.ILoggerFactory,CounterStrikeSharp.API.Core.Hosting.IScriptHostConfiguration,CounterStrikeSharp.API.Core.GameDataProvider,CounterStrikeSharp.API.Core.CoreConfig,CounterStrikeSharp.API.Core.Plugin.Host.IPluginManager,CounterStrikeSharp.API.Core.Plugin.Host.IPluginContextQueryHandler,CounterStrikeSharp.API.Core.Translations.IPlayerLanguageManager)</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:CounterStrikeSharp.API.Core.CBaseAnimGraph.get_AnimGraphDirty</Target>
@@ -277,6 +301,12 @@
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:CounterStrikeSharp.API.Core.CCSPlayerPawn.Respawn</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:CounterStrikeSharp.API.Core.CDynamicProp.get_AnimateOnServer</Target>
@@ -313,6 +343,12 @@
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:CounterStrikeSharp.API.Core.CoreConfig.#ctor(CounterStrikeSharp.API.Core.Hosting.IScriptHostConfiguration,Microsoft.Extensions.Logging.ILogger{CounterStrikeSharp.API.Core.CoreConfig})</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:CounterStrikeSharp.API.Core.CPlayer_WeaponServices.get_AllowSwitchToNoWeapon</Target>
@@ -391,6 +427,54 @@
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:CounterStrikeSharp.API.Core.FunctionReference.Create(System.Delegate)</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:CounterStrikeSharp.API.Core.NativeAPI.QueueTaskForNextFrame(System.IntPtr)</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:CounterStrikeSharp.API.Core.NativeAPI.QueueTaskForNextWorldUpdate(System.IntPtr)</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:CounterStrikeSharp.API.Core.Plugin.Host.PluginManager.#ctor(CounterStrikeSharp.API.Core.Hosting.IScriptHostConfiguration,Microsoft.Extensions.Logging.ILogger{CounterStrikeSharp.API.Core.Plugin.Host.PluginManager},System.IServiceProvider)</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:CounterStrikeSharp.API.Core.Plugin.PluginContext.#ctor(System.IServiceProvider,CounterStrikeSharp.API.Core.Hosting.IScriptHostConfiguration,System.String,System.Int32)</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>M:CounterStrikeSharp.API.Core.IPlugin.OnAllPluginsLoaded(System.Boolean)</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>P:CounterStrikeSharp.API.Core.Hosting.IScriptHostConfiguration.SharedPath</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0006</DiagnosticId>
<Target>P:CounterStrikeSharp.API.Core.IPlugin.CommandManager</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0010</DiagnosticId>
<Target>T:CounterStrikeSharp.API.Core.RenderMultisampleType_t</Target>
@@ -986,20 +1070,14 @@
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>F:CounterStrikeSharp.API.Modules.Memory.VirtualFunctions.CCSPlayerPawn_Respawn</Target>
<DiagnosticId>CP1002</DiagnosticId>
<Target>Microsoft.Extensions.Localization.Abstractions, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>F:CounterStrikeSharp.API.Modules.Memory.VirtualFunctions.CCSPlayerPawn_RespawnFunc</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>
<Suppression>
<DiagnosticId>CP0002</DiagnosticId>
<Target>M:CounterStrikeSharp.API.Core.CCSPlayerPawn.Respawn</Target>
<DiagnosticId>CP1002</DiagnosticId>
<Target>Serilog, Version=2.0.0.0, Culture=neutral, PublicKeyToken=24c2f752a8e58a10</Target>
<Left>.\ApiCompat\v151.dll</Left>
<Right>obj\Debug\net7.0\CounterStrikeSharp.API.dll</Right>
</Suppression>

View File

@@ -23,6 +23,7 @@ namespace CounterStrikeSharp.API
[Flags]
public enum ConVarFlags : Int64
{
FCVAR_NONE = 0,
FCVAR_LINKED_CONCOMMAND = (1 << 0),
FCVAR_DEVELOPMENTONLY =

View File

@@ -1,6 +1,7 @@
using System;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Commands;
namespace CounterStrikeSharp.API.Core
{
@@ -124,10 +125,21 @@ namespace CounterStrikeSharp.API.Core
}
}
public static void IssueClientCommand(int clientindex, string command){
public static CommandCallingContext CommandGetCallingContext(IntPtr command){
lock (ScriptContext.GlobalScriptContext.Lock) {
ScriptContext.GlobalScriptContext.Reset();
ScriptContext.GlobalScriptContext.Push(clientindex);
ScriptContext.GlobalScriptContext.Push(command);
ScriptContext.GlobalScriptContext.SetIdentifier(0x886D0EB6);
ScriptContext.GlobalScriptContext.Invoke();
ScriptContext.GlobalScriptContext.CheckErrors();
return (CommandCallingContext)ScriptContext.GlobalScriptContext.GetResult(typeof(CommandCallingContext));
}
}
public static void IssueClientCommand(int slot, string command){
lock (ScriptContext.GlobalScriptContext.Lock) {
ScriptContext.GlobalScriptContext.Reset();
ScriptContext.GlobalScriptContext.Push(slot);
ScriptContext.GlobalScriptContext.Push(command);
ScriptContext.GlobalScriptContext.SetIdentifier(0xCA5BA982);
ScriptContext.GlobalScriptContext.Invoke();
@@ -135,6 +147,17 @@ namespace CounterStrikeSharp.API.Core
}
}
public static void IssueClientCommandFromServer(int slot, string command){
lock (ScriptContext.GlobalScriptContext.Lock) {
ScriptContext.GlobalScriptContext.Reset();
ScriptContext.GlobalScriptContext.Push(slot);
ScriptContext.GlobalScriptContext.Push(command);
ScriptContext.GlobalScriptContext.SetIdentifier(0x85376751);
ScriptContext.GlobalScriptContext.Invoke();
ScriptContext.GlobalScriptContext.CheckErrors();
}
}
public static IntPtr FindConvar(string name){
lock (ScriptContext.GlobalScriptContext.Lock) {
ScriptContext.GlobalScriptContext.Reset();
@@ -479,20 +502,20 @@ namespace CounterStrikeSharp.API.Core
}
}
public static void QueueTaskForNextFrame(IntPtr callback){
public static void QueueTaskForNextFrame(InputArgument callback){
lock (ScriptContext.GlobalScriptContext.Lock) {
ScriptContext.GlobalScriptContext.Reset();
ScriptContext.GlobalScriptContext.Push(callback);
ScriptContext.GlobalScriptContext.Push((InputArgument)callback);
ScriptContext.GlobalScriptContext.SetIdentifier(0x9FE394D8);
ScriptContext.GlobalScriptContext.Invoke();
ScriptContext.GlobalScriptContext.CheckErrors();
}
}
public static void QueueTaskForNextWorldUpdate(IntPtr callback){
public static void QueueTaskForNextWorldUpdate(InputArgument callback){
lock (ScriptContext.GlobalScriptContext.Lock) {
ScriptContext.GlobalScriptContext.Reset();
ScriptContext.GlobalScriptContext.Push(callback);
ScriptContext.GlobalScriptContext.Push((InputArgument)callback);
ScriptContext.GlobalScriptContext.SetIdentifier(0xAD51A0C9);
ScriptContext.GlobalScriptContext.Invoke();
ScriptContext.GlobalScriptContext.CheckErrors();
@@ -726,6 +749,16 @@ namespace CounterStrikeSharp.API.Core
}
}
public static void FreeEvent(IntPtr gameevent){
lock (ScriptContext.GlobalScriptContext.Lock) {
ScriptContext.GlobalScriptContext.Reset();
ScriptContext.GlobalScriptContext.Push(gameevent);
ScriptContext.GlobalScriptContext.SetIdentifier(0x7E8B60C2);
ScriptContext.GlobalScriptContext.Invoke();
ScriptContext.GlobalScriptContext.CheckErrors();
}
}
public static void FireEvent(IntPtr gameevent, bool dontbroadcast){
lock (ScriptContext.GlobalScriptContext.Lock) {
ScriptContext.GlobalScriptContext.Reset();

View File

@@ -17,6 +17,7 @@
using System.Globalization;
using System.Linq;
using System.Text;
using CounterStrikeSharp.API.Core.Commands;
using CounterStrikeSharp.API.Core.Hosting;
using CounterStrikeSharp.API.Core.Plugin;
using CounterStrikeSharp.API.Core.Plugin.Host;
@@ -26,6 +27,7 @@ using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Menu;
using CounterStrikeSharp.API.Modules.Utils;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace CounterStrikeSharp.API.Core
@@ -34,6 +36,7 @@ namespace CounterStrikeSharp.API.Core
{
private static Application _instance = null!;
public ILogger Logger { get; }
public static Application Instance => _instance!;
public static string RootDirectory => Instance._scriptHostConfiguration.RootPath;
@@ -44,10 +47,12 @@ namespace CounterStrikeSharp.API.Core
private readonly IPluginManager _pluginManager;
private readonly IPluginContextQueryHandler _pluginContextQueryHandler;
private readonly IPlayerLanguageManager _playerLanguageManager;
private readonly ICommandManager _commandManager;
public Application(ILoggerFactory loggerFactory, IScriptHostConfiguration scriptHostConfiguration,
GameDataProvider gameDataProvider, CoreConfig coreConfig, IPluginManager pluginManager,
IPluginContextQueryHandler pluginContextQueryHandler, IPlayerLanguageManager playerLanguageManager)
IPluginContextQueryHandler pluginContextQueryHandler, IPlayerLanguageManager playerLanguageManager,
ICommandManager commandManager)
{
Logger = loggerFactory.CreateLogger("Core");
_scriptHostConfiguration = scriptHostConfiguration;
@@ -56,6 +61,7 @@ namespace CounterStrikeSharp.API.Core
_pluginManager = pluginManager;
_pluginContextQueryHandler = pluginContextQueryHandler;
_playerLanguageManager = playerLanguageManager;
_commandManager = commandManager;
_instance = this;
}
@@ -69,7 +75,7 @@ namespace CounterStrikeSharp.API.Core
var adminPath = Path.Combine(_scriptHostConfiguration.RootPath, "configs", "admins.json");
Logger.LogInformation("Loading Admins from {Path}", adminPath);
AdminManager.LoadAdminData(adminPath);
var adminGroupsPath = Path.Combine(_scriptHostConfiguration.RootPath, "configs", "admin_groups.json");
Logger.LogInformation("Loading Admin Groups from {Path}", adminGroupsPath);
AdminManager.LoadAdminGroups(adminGroupsPath);
@@ -81,24 +87,23 @@ namespace CounterStrikeSharp.API.Core
AdminManager.MergeGroupPermsIntoAdmins();
AdminManager.AddCommands();
RegisterPluginCommands();
_pluginManager.Load();
for (var i = 1; i <= 9; i++)
{
CommandUtils.AddStandaloneCommand($"css_{i}", "Command Key Handler", (player, info) =>
{
if (player == null) return;
var key = Convert.ToInt32(info.GetArg(0).Split("_")[1]);
MenuManager.OnKeyPress(player, key);
});
_commandManager.RegisterCommand(new($"css_{i}", "Command Key Handler",
(player, info) =>
{
if (player == null) return;
var key = Convert.ToInt32(info.GetArg(0).Split("_")[1]);
MenuManager.OnKeyPress(player, key);
}));
}
RegisterPluginCommands();
}
[RequiresPermissions("@css/generic")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
private void OnCSSCommand(CCSPlayerController? caller, CommandInfo info)
{
var currentVersion = Api.GetVersion();
@@ -107,18 +112,11 @@ namespace CounterStrikeSharp.API.Core
" CounterStrikeSharp was created and is maintained by Michael \"roflmuffin\" Wilson.\n" +
" Counter-Strike Sharp uses code borrowed from SourceMod, Source.Python, FiveM, Saul Rennison, source2gen and CS2Fixes.\n" +
" See ACKNOWLEDGEMENTS.md for more information.\n" +
" Current API Version: " + currentVersion, true);
" Current API Version: " + currentVersion);
return;
}
[RequiresPermissions("@css/generic")]
[CommandHelper(minArgs: 1,
usage: "[option]\n" +
" list - List all plugins currently loaded.\n" +
" start / load - Loads a plugin not currently loaded.\n" +
" stop / unload - Unloads a plugin currently loaded.\n" +
" restart / reload - Reloads a plugin currently loaded.",
whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
private void OnCSSPluginCommand(CCSPlayerController? caller, CommandInfo info)
{
switch (info.GetArg(1))
@@ -126,25 +124,24 @@ namespace CounterStrikeSharp.API.Core
case "list":
{
info.ReplyToCommand(
$" List of all plugins currently loaded by CounterStrikeSharp: {_pluginManager.GetLoadedPlugins().Count()} plugins loaded.",
true);
$" List of all plugins currently loaded by CounterStrikeSharp: {_pluginManager.GetLoadedPlugins().Count()} plugins loaded.");
foreach (var plugin in _pluginManager.GetLoadedPlugins())
{
var sb = new StringBuilder();
sb.AppendFormat(" [#{0}:{1}]: \"{2}\" ({3})", plugin.PluginId,
plugin.State.ToString().ToUpper(), plugin.Plugin.ModuleName,
plugin.Plugin.ModuleVersion);
if (!string.IsNullOrEmpty(plugin.Plugin.ModuleAuthor))
plugin.State.ToString().ToUpper(), plugin.Plugin?.ModuleName ?? "Unknown",
plugin.Plugin?.ModuleVersion ?? "Unknown");
if (!string.IsNullOrEmpty(plugin.Plugin?.ModuleAuthor))
sb.AppendFormat(" by {0}", plugin.Plugin.ModuleAuthor);
if (!string.IsNullOrEmpty(plugin.Plugin.ModuleDescription))
if (!string.IsNullOrEmpty(plugin.Plugin?.ModuleDescription))
{
sb.Append("\n");
sb.Append(" ");
sb.Append(plugin.Plugin.ModuleDescription);
}
info.ReplyToCommand(sb.ToString(), true);
info.ReplyToCommand(sb.ToString());
}
break;
@@ -155,8 +152,7 @@ namespace CounterStrikeSharp.API.Core
if (info.ArgCount < 3)
{
info.ReplyToCommand(
"Valid usage: css_plugins start/load [relative plugin path || absolute plugin path] (e.g \"TestPlugin\", \"plugins/TestPlugin/TestPlugin.dll\")\n",
true);
"Valid usage: css_plugins start/load [relative plugin path || absolute plugin path] (e.g \"TestPlugin\", \"plugins/TestPlugin/TestPlugin.dll\")\n");
break;
}
@@ -179,16 +175,19 @@ namespace CounterStrikeSharp.API.Core
try
{
_pluginManager.LoadPlugin(path);
plugin = _pluginContextQueryHandler.FindPluginByModulePath(path);
plugin.Plugin.OnAllPluginsLoaded(false);
}
catch (Exception e)
{
info.ReplyToCommand($"Could not load plugin \"{path}\"", true);
info.ReplyToCommand($"Could not load plugin \"{path}\"");
Logger.LogError(e, "Could not load plugin \"{Path}\"", path);
}
}
else
{
plugin.Load(false);
plugin.Plugin.OnAllPluginsLoaded(false);
}
break;
@@ -200,8 +199,7 @@ namespace CounterStrikeSharp.API.Core
if (info.ArgCount < 3)
{
info.ReplyToCommand(
"Valid usage: css_plugins stop/unload [plugin name || #plugin id] (e.g \"TestPlugin\", \"1\")\n",
true);
"Valid usage: css_plugins stop/unload [plugin name || #plugin id] (e.g \"TestPlugin\", \"1\")\n");
break;
}
@@ -209,7 +207,7 @@ namespace CounterStrikeSharp.API.Core
IPluginContext? plugin = _pluginContextQueryHandler.FindPluginByIdOrName(pluginIdentifier);
if (plugin == null)
{
info.ReplyToCommand($"Could not unload plugin \"{pluginIdentifier}\"", true);
info.ReplyToCommand($"Could not unload plugin \"{pluginIdentifier}\"");
break;
}
@@ -223,8 +221,7 @@ namespace CounterStrikeSharp.API.Core
if (info.ArgCount < 3)
{
info.ReplyToCommand(
"Valid usage: css_plugins restart/reload [plugin name || #plugin id] (e.g \"TestPlugin\", \"#1\")\n",
true);
"Valid usage: css_plugins restart/reload [plugin name || #plugin id] (e.g \"TestPlugin\", \"#1\")\n");
break;
}
@@ -233,12 +230,13 @@ namespace CounterStrikeSharp.API.Core
if (plugin == null)
{
info.ReplyToCommand($"Could not reload plugin \"{pluginIdentifier}\"", true);
info.ReplyToCommand($"Could not reload plugin \"{pluginIdentifier}\"");
break;
}
plugin.Unload(true);
plugin.Load(true);
plugin.Plugin.OnAllPluginsLoaded(true);
break;
}
@@ -247,23 +245,21 @@ namespace CounterStrikeSharp.API.Core
" list - List all plugins currently loaded.\n" +
" start / load - Loads a plugin not currently loaded.\n" +
" stop / unload - Unloads a plugin currently loaded.\n" +
" restart / reload - Reloads a plugin currently loaded."
, true);
" restart / reload - Reloads a plugin currently loaded.");
break;
}
}
[CommandHelper(usage: "[language code, e.g. \"de\", \"pl\", \"en\"]", whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
private void OnLangCommand(CCSPlayerController? player, CommandInfo command)
{
if (player == null) return;
SteamID steamId = (SteamID)player.SteamID;
var steamId = (SteamID)player.SteamID;
if (command.ArgCount == 1)
{
var language = _playerLanguageManager.GetLanguage(steamId);
command.ReplyToCommand(string.Format("Current language is \"{0}\" ({1})", language.Name, language.NativeName));
command.ReplyToCommand($"Current language is \"{language.Name}\" ({language.NativeName})");
return;
}
@@ -271,7 +267,7 @@ namespace CounterStrikeSharp.API.Core
{
return;
}
try
{
var language = command.GetArg(1);
@@ -287,10 +283,26 @@ namespace CounterStrikeSharp.API.Core
private void RegisterPluginCommands()
{
CommandUtils.AddStandaloneCommand("css", "Counter-Strike Sharp options.", OnCSSCommand);
CommandUtils.AddStandaloneCommand("css_plugins", "Counter-Strike Sharp plugin options.",
OnCSSPluginCommand);
CommandUtils.AddStandaloneCommand("css_lang", "Set Counter-Strike Sharp language.", OnLangCommand);
_commandManager.RegisterCommand(new("css", "Counter-Strike Sharp options.", OnCSSCommand)
{
ExecutableBy = CommandUsage.CLIENT_AND_SERVER,
});
_commandManager.RegisterCommand(new("css_plugins", "Counter-Strike Sharp plugin options.",
OnCSSPluginCommand)
{
ExecutableBy = CommandUsage.CLIENT_AND_SERVER,
MinArgs = 1,
UsageHint = "[option]\n" +
" list - List all plugins currently loaded.\n" +
" start / load - Loads a plugin not currently loaded.\n" +
" stop / unload - Unloads a plugin currently loaded.\n" +
" restart / reload - Reloads a plugin currently loaded.",
});
_commandManager.RegisterCommand(new("css_lang", "Set Counter-Strike Sharp language.", OnLangCommand)
{
ExecutableBy = CommandUsage.CLIENT_AND_SERVER,
UsageHint = "[language code, e.g. \"de\", \"pl\", \"en\"]",
});
}
}
}

View File

@@ -22,11 +22,13 @@ using System.Reflection;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Core.Attributes.Registration;
using CounterStrikeSharp.API.Core.Translations;
using CounterStrikeSharp.API.Core.Commands;
using CounterStrikeSharp.API.Modules.Admin;
using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Events;
using CounterStrikeSharp.API.Modules.Timers;
using CounterStrikeSharp.API.Modules.Config;
using CounterStrikeSharp.API.Modules.Cvars;
using CounterStrikeSharp.API.Modules.Entities;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
@@ -59,6 +61,8 @@ namespace CounterStrikeSharp.API.Core
public string ModuleDirectory => Path.GetDirectoryName(ModulePath);
public ILogger Logger { get; set; }
public ICommandManager CommandManager { get; set; }
public IStringLocalizer Localizer { get; set; }
@@ -69,6 +73,10 @@ namespace CounterStrikeSharp.API.Core
public virtual void Unload(bool hotReload)
{
}
public virtual void OnAllPluginsLoaded(bool hotReload)
{
}
public class CallbackSubscriber : IDisposable
{
@@ -170,102 +178,13 @@ namespace CounterStrikeSharp.API.Core
/// <param name="handler">The callback function to be invoked when the command is executed.</param>
public void AddCommand(string name, string description, CommandInfo.CommandCallback handler)
{
var wrappedHandler = new Action<int, IntPtr>((i, ptr) =>
{
var caller = (i != -1) ? new CCSPlayerController(NativeAPI.GetEntityFromIndex(i + 1)) : null;
var command = new CommandInfo(ptr, caller);
using var temporaryCulture = new WithTemporaryCulture(caller.GetLanguage());
var methodInfo = handler?.GetMethodInfo();
// We do not need to do permission checks on commands executed from the server console.
// The server will always be allowed to execute commands (unless marked as client only like above)
if (caller != null)
{
// Do not execute command if we do not have the correct permissions.
var adminData = AdminManager.GetPlayerAdminData(caller!.AuthorizedSteamID);
var permissionsToCheck = new List<BaseRequiresPermissions>();
// If our command is overriden, we dynamically create a new permissions attribute
// based on the data that is stored in admin_overrides.json.
if (AdminManager.CommandIsOverriden(name))
{
var data = AdminManager.GetCommandOverrideData(name);
if (data != null)
{
var attrType = (data.CheckType == "all") ? typeof(RequiresPermissions) : typeof(RequiresPermissionsOr);
var attr = (BaseRequiresPermissions)Activator.CreateInstance(attrType, args: AdminManager.GetPermissionOverrides(name));
if (attr != null) permissionsToCheck.Add(attr);
}
}
// The permissions for this command are not being overriden here, so we
// grab the permissions to check straight from the attribute.
else
{
var permissions = methodInfo?.GetCustomAttributes<BaseRequiresPermissions>();
if (permissions != null) permissionsToCheck.AddRange(permissions);
}
foreach (var attr in permissionsToCheck)
{
attr.Command = name;
if (!attr.CanExecuteCommand(caller))
{
var responseStr = (attr.GetType() == typeof(RequiresPermissions)) ?
"You are missing the correct permissions" : "You do not have one of the correct permissions";
var flags = attr.Permissions.Except(adminData?.GetAllFlags() ?? new HashSet<string>());
flags = flags.Except(adminData?.Groups ?? new HashSet<string>());
command.ReplyToCommand($"[CSS] {responseStr} ({string.Join(", ", flags)}) to execute this command.");
return;
}
}
}
// Do not execute if we shouldn't be calling this command.
var helperAttribute = methodInfo?.GetCustomAttribute<CommandHelperAttribute>();
if (helperAttribute != null)
{
switch (helperAttribute.WhoCanExcecute)
{
case CommandUsage.CLIENT_AND_SERVER: break; // Allow command through.
case CommandUsage.CLIENT_ONLY:
if (caller == null || !caller.IsValid) { command.ReplyToCommand("[CSS] This command can only be executed by clients."); return; }
break;
case CommandUsage.SERVER_ONLY:
if (caller != null && caller.IsValid) { command.ReplyToCommand("[CSS] This command can only be executed by the server."); return; }
break;
default: throw new ArgumentException("Unrecognised CommandUsage value passed in CommandHelperAttribute.");
}
// Technically the command itself counts as the first argument,
// but we'll just ignore that for this check.
if (helperAttribute.MinArgs != 0 && command.ArgCount - 1 < helperAttribute.MinArgs)
{
// Remove the "css_" from the beginning of the command name if it's present.
// Most of the time, users will be calling commands from chat.
var commandCalled = command.ArgByIndex(0);
var properCommandName = (commandCalled.StartsWith("css_")) ? commandCalled.Replace("css_", "") : commandCalled;
command.ReplyToCommand($"[CSS] Expected usage: \"!{properCommandName} {helperAttribute.Usage}\".");
return;
}
}
handler?.Invoke(caller, command);
});
var methodInfo = handler?.GetMethodInfo();
var helperAttribute = methodInfo?.GetCustomAttribute<CommandHelperAttribute>();
var subscriber = new CallbackSubscriber(handler, wrappedHandler, () => { RemoveCommand(name, handler); });
NativeAPI.AddCommand(name, description, (helperAttribute?.WhoCanExcecute == CommandUsage.SERVER_ONLY),
(int)ConCommandFlags.FCVAR_LINKED_CONCOMMAND, subscriber.GetInputArgument());
CommandHandlers[handler] = subscriber;
var definition = new CommandDefinition(name, description, handler);
CommandManager.RegisterCommand(definition);
}
private void AddCommand(CommandDefinition definition)
{
CommandManager.RegisterCommand(definition);
}
public void AddCommandListener(string? name, CommandInfo.CommandListenerCallback handler, HookMode mode = HookMode.Pre)
@@ -394,6 +313,7 @@ namespace CounterStrikeSharp.API.Core
this.RegisterAttributeHandlers(instance);
this.RegisterConsoleCommandAttributeHandlers(instance);
this.RegisterEntityOutputAttributeHandlers(instance);
this.RegisterFakeConVars(instance);
}
public void InitializeConfig(object instance, Type pluginType)
@@ -462,10 +382,19 @@ namespace CounterStrikeSharp.API.Core
foreach (var eventHandler in eventHandlers)
{
var attributes = eventHandler.GetCustomAttributes<ConsoleCommandAttribute>();
var helperAttribute = eventHandler.GetCustomAttribute<CommandHelperAttribute>();
foreach (var commandInfo in attributes)
{
AddCommand(commandInfo.Command, commandInfo.Description,
eventHandler.CreateDelegate<CommandInfo.CommandCallback>(instance));
var definition = new CommandDefinition()
{
Name = commandInfo.Command,
Description = commandInfo.Description,
Callback = eventHandler.CreateDelegate<CommandInfo.CommandCallback>(instance),
MinArgs = helperAttribute?.MinArgs,
UsageHint = helperAttribute?.Usage,
ExecutableBy = helperAttribute?.WhoCanExcecute ?? CommandUsage.CLIENT_AND_SERVER,
};
AddCommand(definition);
}
}
}
@@ -487,6 +416,43 @@ namespace CounterStrikeSharp.API.Core
}
}
public void RegisterFakeConVars(Type type, object instance = null)
{
var convars = type
.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
.Where(prop => prop.FieldType.IsGenericType &&
prop.FieldType.GetGenericTypeDefinition() == typeof(FakeConVar<>));
foreach (var prop in convars)
{
object propValue = prop.GetValue(instance); // FakeConvar<?> instance
var propValueType = prop.FieldType.GenericTypeArguments[0];
var name = prop.FieldType.GetProperty("Name", BindingFlags.Public | BindingFlags.Instance)
.GetValue(propValue);
var description = prop.FieldType.GetProperty("Description", BindingFlags.Public | BindingFlags.Instance)
.GetValue(propValue);
MethodInfo executeCommandMethod = prop.FieldType
.GetMethod("ExecuteCommand", BindingFlags.Instance | BindingFlags.NonPublic);
this.AddCommand((string)name, (string) description, (caller, command) =>
{
executeCommandMethod.Invoke(propValue, new object[] {caller, command});
});
}
}
/// <summary>
/// Used to bind a fake ConVar to a plugin command. Only required for ConVars that are not public properties of the plugin class.
/// </summary>
/// <param name="convar"></param>
/// <typeparam name="T"></typeparam>
public void RegisterFakeConVars(object instance)
{
RegisterFakeConVars(instance.GetType(), instance);
}
public void HookEntityOutput(string classname, string outputName, EntityIO.EntityOutputHandler handler, HookMode mode = HookMode.Pre)
{
var subscriber = new CallbackSubscriber(handler, handler,

View File

@@ -0,0 +1,25 @@
namespace CounterStrikeSharp.API.Core.Capabilities;
public static class Capabilities
{
public static void RegisterPluginCapability<T>(PluginCapability<T> capability, Func<T> supplier)
{
if (!PluginCapability<T>.Providers.ContainsKey(capability.Name))
{
PluginCapability<T>.Providers.Add(capability.Name, new());
}
PluginCapability<T>.Providers[capability.Name].Add(supplier);
}
public static void RegisterPlayerCapability<T>(PlayerCapability<T> capability,
Func<CCSPlayerController, T> supplier)
{
if (!PlayerCapability<T>.Providers.ContainsKey(capability.Name))
{
PlayerCapability<T>.Providers.Add(capability.Name, new());
}
PlayerCapability<T>.Providers[capability.Name].Add(supplier);
}
}

View File

@@ -0,0 +1,24 @@
using System.Collections.Generic;
namespace CounterStrikeSharp.API.Core.Capabilities;
public sealed class PlayerCapability<T>
{
public string Name { get; }
internal static readonly Dictionary<string, List<Func<CCSPlayerController, T>>> Providers = new();
public PlayerCapability(string name)
{
Name = name;
}
public T? Get(CCSPlayerController entity)
{
foreach (var provider in Providers[Name])
{
return provider(entity);
}
return default;
}
}

View File

@@ -0,0 +1,24 @@
using System.Collections.Generic;
namespace CounterStrikeSharp.API.Core.Capabilities;
public sealed class PluginCapability<T>
{
public string Name { get; }
internal static readonly Dictionary<string, List<Func<T>>> Providers = new();
public PluginCapability(string name)
{
Name = name;
}
public T? Get()
{
foreach (var provider in Providers[Name])
{
return provider();
}
return default;
}
}

View File

@@ -0,0 +1,33 @@
using CounterStrikeSharp.API.Modules.Commands;
namespace CounterStrikeSharp.API.Core.Commands;
public class CommandDefinition
{
public CommandDefinition(string name, string description, CommandInfo.CommandCallback callback)
{
Name = name;
Description = description;
Callback = callback;
}
public CommandDefinition()
{
}
public string Name { get; init; }
public string Description { get; init; }
public CommandInfo.CommandCallback Callback { get; init; }
public CommandUsage ExecutableBy { get; init; } = CommandUsage.CLIENT_AND_SERVER;
public string? UsageHint { get; init; }
public int? MinArgs { get; init; }
public override string ToString()
{
return $"Name: {Name}, Description: {Description}, ExecutableBy: {ExecutableBy}, " +
$"UsageHint: {UsageHint}, MinArgs: {MinArgs}";
}
}

View File

@@ -0,0 +1,163 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using CounterStrikeSharp.API.Core.Translations;
using CounterStrikeSharp.API.Modules.Admin;
using CounterStrikeSharp.API.Modules.Commands;
using Microsoft.Extensions.Logging;
namespace CounterStrikeSharp.API.Core.Commands;
public class CommandManager : ICommandManager
{
private readonly Dictionary<string, IList<CommandDefinition>> _commandDefinitions =
new(StringComparer.InvariantCultureIgnoreCase);
private readonly ILogger<CommandManager> _logger;
private readonly FunctionReference _internalFunctionReference;
public CommandManager(ILogger<CommandManager> logger)
{
_logger = logger;
_internalFunctionReference = FunctionReference.Create(HandleCommandInternal);
}
public void RegisterCommand(CommandDefinition definition)
{
bool isRegistered = true;
if (!_commandDefinitions.ContainsKey(definition.Name))
{
_commandDefinitions.Add(definition.Name, new List<CommandDefinition>());
isRegistered = false;
}
_commandDefinitions[definition.Name].Add(definition);
_logger.LogDebug("Registering command {Command}", definition.Name);
if (!isRegistered)
{
NativeAPI.AddCommand(definition.Name, definition.Description,
definition.ExecutableBy == CommandUsage.SERVER_ONLY,
(int)ConCommandFlags.FCVAR_LINKED_CONCOMMAND, _internalFunctionReference);
}
}
public void RemoveCommand(CommandDefinition definition)
{
_logger.LogDebug("Removing command {Command}", definition.Name);
if (_commandDefinitions.TryGetValue(definition.Name, out var commandDefinition))
{
commandDefinition.Remove(definition);
}
if (_commandDefinitions[definition.Name].Count == 0)
{
NativeAPI.RemoveCommand(definition.Name, _internalFunctionReference);
_commandDefinitions.Remove(definition.Name);
}
}
private void HandleCommandInternal(int playerSlot, IntPtr commandInfo)
{
var caller = (playerSlot != -1) ? Utilities.GetPlayerFromSlot(playerSlot) : null;
var info = new CommandInfo(commandInfo, caller);
var name = info.GetArg(0).ToLower();
using var temporaryCulture = new WithTemporaryCulture(caller.GetLanguage());
if (_commandDefinitions.TryGetValue(name, out var handler))
{
foreach (var command in handler)
{
var methodInfo = command.Callback?.GetMethodInfo();
// We do not need to do permission checks on commands executed from the server console.
// The server will always be allowed to execute commands (unless marked as client only like above)
if (caller != null)
{
// Do not execute command if we do not have the correct permissions.
var adminData = AdminManager.GetPlayerAdminData(caller!.AuthorizedSteamID);
var permissionsToCheck = new List<BaseRequiresPermissions>();
// If our command is overriden, we dynamically create a new permissions attribute
// based on the data that is stored in admin_overrides.json.
if (AdminManager.CommandIsOverriden(name))
{
var data = AdminManager.GetCommandOverrideData(name);
if (data != null)
{
var attrType = (data.CheckType == "all") ? typeof(RequiresPermissions) : typeof(RequiresPermissionsOr);
var attr = (BaseRequiresPermissions)Activator.CreateInstance(attrType, args: AdminManager.GetPermissionOverrides(name));
if (attr != null) permissionsToCheck.Add(attr);
}
}
// The permissions for this command are not being overriden here, so we
// grab the permissions to check straight from the attribute.
else
{
var permissions = methodInfo?.GetCustomAttributes<BaseRequiresPermissions>();
if (permissions != null) permissionsToCheck.AddRange(permissions);
}
foreach (var attr in permissionsToCheck)
{
if (attr.Permissions.Count == 0)
{
continue;
}
attr.Command = name;
if (!attr.CanExecuteCommand(caller))
{
var responseStr = (attr.GetType() == typeof(RequiresPermissions)) ?
"You are missing the correct permissions" : "You do not have one of the correct permissions";
var flags = attr.Permissions.Except(adminData?.GetAllFlags() ?? new HashSet<string>());
flags = flags.Except(adminData?.Groups ?? new HashSet<string>());
info.ReplyToCommand($"[CSS] {responseStr} ({string.Join(", ", flags)}) to execute this command.");
return;
}
}
}
// Do not execute if we shouldn't be calling this command.
var helperAttribute = methodInfo?.GetCustomAttribute<CommandHelperAttribute>();
if (helperAttribute != null)
{
switch (helperAttribute.WhoCanExcecute)
{
case CommandUsage.CLIENT_AND_SERVER: break; // Allow command through.
case CommandUsage.CLIENT_ONLY:
if (caller == null || !caller.IsValid) { info.ReplyToCommand("[CSS] This command can only be executed by clients."); return; }
break;
case CommandUsage.SERVER_ONLY:
if (caller != null && caller.IsValid) { info.ReplyToCommand("[CSS] This command can only be executed by the server."); return; }
break;
default: throw new ArgumentException("Unrecognised CommandUsage value passed in CommandHelperAttribute.");
}
// Technically the command itself counts as the first argument,
// but we'll just ignore that for this check.
if (helperAttribute.MinArgs != 0 && info.ArgCount - 1 < helperAttribute.MinArgs)
{
// Remove the "css_" from the beginning of the command name if it's present.
// Most of the time, users will be calling commands from chat.
var commandCalled = info.ArgByIndex(0);
var properCommandName = (commandCalled.StartsWith("css_")) ? commandCalled.Replace("css_", "") : commandCalled;
info.ReplyToCommand($"[CSS] Expected usage: \"!{properCommandName} {helperAttribute.Usage}\".");
return;
}
}
command.Callback?.Invoke(caller, info);
}
}
}
}

View File

@@ -0,0 +1,10 @@
using CounterStrikeSharp.API.Modules.Commands;
namespace CounterStrikeSharp.API.Core.Commands;
public interface ICommandManager
{
void RegisterCommand(CommandDefinition definition);
void RemoveCommand(CommandDefinition definition);
}

View File

@@ -0,0 +1,46 @@
using System.Collections.Generic;
using CounterStrikeSharp.API.Core.Plugin;
using Microsoft.Extensions.Logging;
namespace CounterStrikeSharp.API.Core.Commands;
/// <summary>
/// Decorator for <see cref="ICommandManager"/> that tracks registered commands and removes them when disposed.
/// Used for plugins that register commands to ensure they are removed when the plugin is unloaded.
/// </summary>
public class PluginCommandManagerDecorator : ICommandManager, IDisposable
{
private readonly ICommandManager _inner;
private readonly List<CommandDefinition> _trackedCommands = new();
private readonly IPluginContext _pluginContext;
private readonly ILogger<PluginCommandManagerDecorator> _logger;
public PluginCommandManagerDecorator(ICommandManager inner, IPluginContext pluginContext, ILogger<PluginCommandManagerDecorator> logger)
{
_pluginContext = pluginContext;
_logger = logger;
_inner = inner;
}
public void RegisterCommand(CommandDefinition definition)
{
_inner.RegisterCommand(definition);
_trackedCommands.Add(definition);
_logger.LogDebug("Registered command {Command} from plugin {Plugin}", definition.Name, _pluginContext.Plugin.ModuleName);
}
public void RemoveCommand(CommandDefinition definition)
{
_inner.RemoveCommand(definition);
_trackedCommands.Remove(definition);
_logger.LogDebug("Removed command {Command} from plugin {Plugin}", definition.Name, _pluginContext.Plugin.ModuleName);
}
public void Dispose()
{
for (int i = _trackedCommands.Count - 1; i >= 0; i--)
{
RemoveCommand(_trackedCommands[i]);
}
}
}

View File

@@ -25,6 +25,7 @@ using CounterStrikeSharp.API.Modules.Commands;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using CounterStrikeSharp.API.Core.Commands;
using CounterStrikeSharp.API.Core.Hosting;
using CounterStrikeSharp.API.Core.Logging;
using Microsoft.Extensions.Hosting;
@@ -101,12 +102,15 @@ namespace CounterStrikeSharp.API.Core
{
private static CoreConfigData _coreConfig = new CoreConfigData();
private readonly ICommandManager _commandManager;
private readonly ILogger<CoreConfig> _logger;
private readonly string _coreConfigPath;
private bool _commandsRegistered = false;
public CoreConfig(IScriptHostConfiguration scriptHostConfiguration, ILogger<CoreConfig> logger)
public CoreConfig(IScriptHostConfiguration scriptHostConfiguration, ICommandManager commandManager, ILogger<CoreConfig> logger)
{
_commandManager = commandManager;
_logger = logger;
_coreConfigPath = Path.Join(scriptHostConfiguration.ConfigsPath, "core.json");
}
@@ -120,9 +124,14 @@ namespace CounterStrikeSharp.API.Core
public void Load()
{
CommandUtils.AddStandaloneCommand("css_core_reload", "Reloads the core configuration file.",
ReloadCoreConfigCommand);
if (!_commandsRegistered)
{
_commandManager.RegisterCommand(new CommandDefinition("css_core_reload",
"Reloads the core configuration file.",
ReloadCoreConfigCommand));
_commandsRegistered = true;
}
if (!File.Exists(_coreConfigPath))
{
_logger.LogWarning(

View File

@@ -14,87 +14,121 @@
* along with CounterStrikeSharp. If not, see <https://www.gnu.org/licenses/>. *
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.Concurrent;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace CounterStrikeSharp.API.Core
{
/// <summary>
/// Describes the lifetime of a function reference.
/// </summary>
public enum FunctionLifetime
{
/// <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>
Permanent
}
/// <summary>
/// Represents a reference to a function that can be called from native code.
/// </summary>
public class FunctionReference
{
private readonly Delegate m_method;
public unsafe delegate void CallbackDelegate(fxScriptContext* context);
private CallbackDelegate s_callback;
private FunctionReference(Delegate method)
private static readonly ConcurrentDictionary<int, FunctionReference> IdToFunctionReferencesMap = new();
private static readonly ConcurrentDictionary<Delegate, FunctionReference> TargetMethodToFunctionReferencesMap = new();
private static readonly object ReferenceCounterLock = new();
private static int _referenceCounter;
private readonly Delegate _targetMethod;
private readonly CallbackDelegate _nativeCallback;
private readonly TaskCompletionSource _taskCompletionSource = new();
private FunctionReference(Delegate method, FunctionLifetime lifetime)
{
m_method = method;
unsafe
{
var dg = new CallbackDelegate((fxScriptContext* context) =>
{
try
{
var scriptContext = new ScriptContext(context);
if (method.Method.GetParameters().FirstOrDefault()?.ParameterType == typeof(ScriptContext))
{
var returnO = m_method.DynamicInvoke(scriptContext);
if (returnO != null)
{
scriptContext.SetResult(returnO, context);
}
return;
}
var paramsList = method.Method.GetParameters().Select((x, i) =>
{
var param = method.Method.GetParameters()[i];
object obj = null;
if (typeof(NativeObject).IsAssignableFrom(param.ParameterType))
{
obj = Activator.CreateInstance(param.ParameterType,
new[] {scriptContext.GetArgument(typeof(IntPtr), i)});
}
else
{
obj = scriptContext.GetArgument(param.ParameterType, i);
}
return obj;
}).ToArray();
var returnObj = m_method.DynamicInvoke(paramsList);
if (returnObj != null)
{
scriptContext.SetResult(returnObj, context);
}
}
catch (Exception e)
{
Application.Instance.Logger.LogError(e, "Error invoking callback");
}
});
s_callback = dg;
}
Lifetime = lifetime;
_targetMethod = method;
_nativeCallback = CreateWrappedCallback();
}
/// <summary>
/// <inheritdoc cref="FunctionLifetime"/>
/// </summary>
public FunctionLifetime Lifetime { get; }
/// <summary>
/// For <see cref="FunctionLifetime.SingleUse"/> function references, this task will complete when
/// the function has finished invoking.
/// </summary>
public Task CompletionTask => _taskCompletionSource.Task;
public int Identifier { get; private set; }
public static FunctionReference Create(Delegate method)
private unsafe CallbackDelegate CreateWrappedCallback()
{
if (references.ContainsKey(method))
return context =>
{
return references[method];
try
{
var scriptContext = new ScriptContext(context);
// Allow for manual handling of the script context
if (_targetMethod.Method.GetParameters().FirstOrDefault()?.ParameterType == typeof(ScriptContext))
{
var returnValue = _targetMethod.DynamicInvoke(scriptContext);
if (returnValue != null)
{
scriptContext.SetResult(returnValue, context);
}
return;
}
var parameterList = _targetMethod.Method.GetParameters().Select((_, i) =>
{
var parameter = _targetMethod.Method.GetParameters()[i];
return scriptContext.GetArgument(parameter.ParameterType, i);
}).ToArray();
var returnObj = _targetMethod.DynamicInvoke(parameterList);
if (returnObj != null)
{
scriptContext.SetResult(returnObj, context);
}
}
catch (Exception e)
{
Application.Instance.Logger.LogError(e, "Error invoking callback");
}
finally
{
if (Lifetime == FunctionLifetime.SingleUse)
{
RemoveSelf();
}
_taskCompletionSource.TrySetResult();
}
};
}
public static FunctionReference Create(Delegate method, FunctionLifetime lifetime = FunctionLifetime.Permanent)
{
// We always want to create a new reference if the lifetime is single use.
if (lifetime == FunctionLifetime.Permanent && TargetMethodToFunctionReferencesMap.TryGetValue(method, out var existingReference))
{
return existingReference;
}
var reference = new FunctionReference(method);
var reference = new FunctionReference(method, lifetime);
var referenceId = Register(reference);
reference.Identifier = referenceId;
@@ -102,44 +136,41 @@ namespace CounterStrikeSharp.API.Core
return reference;
}
private static Dictionary<int, FunctionReference> ms_references = new Dictionary<int, FunctionReference>();
private static int ms_referenceId;
private static Dictionary<Delegate, FunctionReference> references =
new Dictionary<Delegate, FunctionReference>();
private static int Register(FunctionReference reference)
{
var thisRefId = ms_referenceId;
ms_references[thisRefId] = reference;
references[reference.m_method] = reference;
unchecked { ms_referenceId++; }
return thisRefId;
}
public static FunctionReference Get(int reference)
{
if (ms_references.ContainsKey(reference))
lock (ReferenceCounterLock)
{
return ms_references[reference];
}
var thisRefId = _referenceCounter;
IdToFunctionReferencesMap[thisRefId] = reference;
TargetMethodToFunctionReferencesMap[reference._targetMethod] = reference;
return null;
unchecked
{
_referenceCounter++;
}
return thisRefId;
}
}
public IntPtr GetFunctionPointer()
public IntPtr GetFunctionPointer() => Marshal.GetFunctionPointerForDelegate(_nativeCallback);
private void RemoveSelf()
{
IntPtr cb = Marshal.GetFunctionPointerForDelegate(s_callback);
return cb;
Remove(Identifier);
}
public static void Remove(int reference)
{
if (ms_references.TryGetValue(reference, out var funcRef))
if (IdToFunctionReferencesMap.TryGetValue(reference, out var functionReference))
{
ms_references.Remove(reference);
if (TargetMethodToFunctionReferencesMap.ContainsKey(functionReference._targetMethod))
{
TargetMethodToFunctionReferencesMap.Remove(functionReference._targetMethod, out _);
}
IdToFunctionReferencesMap.Remove(reference, out _);
Application.Instance.Logger.LogDebug("Removing function/callback reference: {Reference}", reference);
}

View File

@@ -7119,6 +7119,15 @@ namespace CounterStrikeSharp.API.Core
}
}
[EventName("warmup_end")]
public class EventWarmupEnd : GameEvent
{
public EventWarmupEnd(IntPtr pointer) : base(pointer){}
public EventWarmupEnd(bool force) : base("warmup_end", force){}
}
[EventName("weapon_fire")]
public class EventWeaponFire : GameEvent
{

View File

@@ -18,6 +18,12 @@ public interface IScriptHostConfiguration
/// </summary>
string PluginPath { get; }
/// <summary>
/// Gets the absolute path to the directory that contains CounterStrikeSharp plugin shared APIS.
/// e.g. /game/csgo/addons/counterstrikesharp/shared
/// </summary>
string SharedPath { get; }
/// <summary>
/// Gets the absolute path to the directory that contains CounterStrikeSharp configs.
/// e.g. /game/csgo/addons/counterstrikesharp/configs

View File

@@ -7,12 +7,14 @@ internal sealed class ScriptHostConfiguration : IScriptHostConfiguration
{
public string RootPath { get; }
public string PluginPath { get; }
public string SharedPath { get; }
public string ConfigsPath { get; }
public string GameDataPath { get; }
public ScriptHostConfiguration(IHostEnvironment hostEnvironment)
{
RootPath = Path.Join(new[] { hostEnvironment.ContentRootPath });
SharedPath = Path.Join(new[] { hostEnvironment.ContentRootPath, "shared" });
PluginPath = Path.Join(new[] { hostEnvironment.ContentRootPath, "plugins" });
ConfigsPath = Path.Join(new[] { hostEnvironment.ContentRootPath, "configs" });
GameDataPath = Path.Join(new[] { hostEnvironment.ContentRootPath, "gamedata" });

View File

@@ -1,4 +1,4 @@
/*
/*
* 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
@@ -15,6 +15,7 @@
*/
using System;
using CounterStrikeSharp.API.Core.Commands;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
@@ -52,11 +53,21 @@ namespace CounterStrikeSharp.API.Core
/// </summary>
void Unload(bool hotReload);
/// <summary>
/// Will be called by CounterStrikeSharp after all plugins have been loaded.
/// This will also be called for convenience after a reload or a late l oad, so that you don't have to handle
/// re-wiring everything.
/// </summary>
/// <param name="hotReload"></param>
void OnAllPluginsLoaded(bool hotReload);
string ModulePath { get; internal set; }
ILogger Logger { get; set; }
IStringLocalizer Localizer { get; set; }
ICommandManager CommandManager { get; set; }
void RegisterAllAttributes(object instance);

View File

@@ -2,6 +2,7 @@
using System;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Utils;
namespace CounterStrikeSharp.API.Core
{
@@ -154,5 +155,13 @@ namespace CounterStrikeSharp.API.Core
/// <param name="simulating"><see langword="true"/> if simulating, <see langword="false"/> otherwise</param>
[ListenerName("OnServerPreWorldUpdate")]
public delegate void OnServerPreWorldUpdate(bool simulating);
/// <summary>
/// Called when the server precaching resources (only when initial startup / changing map).
/// </summary>
/// <param name="manifest">Resource Manifest</param>
[ListenerName("OnServerPrecacheResources")]
public delegate void OnServerPrecacheResources(ResourceManifest manifest);
}
}
}

View File

@@ -1,4 +1,5 @@
using System.Runtime.InteropServices;
using System;
using System.Runtime.InteropServices;
using CounterStrikeSharp.API.Modules.Memory;
using CounterStrikeSharp.API.Modules.Utils;
@@ -6,14 +7,20 @@ namespace CounterStrikeSharp.API.Core;
public partial class CBaseEntity
{
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void Teleport(Vector position, QAngle angles, Vector velocity)
{
Guard.IsValidEntity(this);
VirtualFunction.CreateVoid<IntPtr, IntPtr, IntPtr, IntPtr>(Handle, GameData.GetOffset("CBaseEntity_Teleport"))(
Handle, position.Handle, angles.Handle, velocity.Handle);
}
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void DispatchSpawn()
{
Guard.IsValidEntity(this);
VirtualFunctions.CBaseEntity_DispatchSpawn(Handle, IntPtr.Zero);
}
@@ -25,7 +32,13 @@ public partial class CBaseEntity
/// <summary>
/// Shorthand for accessing an entity's CBodyComponent?.SceneNode?.AbsRotation;
/// </summary>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public QAngle? AbsRotation => CBodyComponent?.SceneNode?.AbsRotation;
public T? GetVData<T>() where T : CEntitySubclassVDataBase => (T)Activator.CreateInstance(typeof(T), Marshal.ReadIntPtr(SubclassID.Handle + 4));
public T? GetVData<T>() where T : CEntitySubclassVDataBase
{
Guard.IsValidEntity(this);
return (T) Activator.CreateInstance(typeof(T), Marshal.ReadIntPtr(SubclassID.Handle + 4));
}
}

View File

@@ -20,8 +20,11 @@ namespace CounterStrikeSharp.API.Core;
public partial class CBaseModelEntity
{
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void SetModel(string model)
{
Guard.IsValidEntity(this);
VirtualFunctions.SetModel(Handle, model);
}
}

View File

@@ -1,5 +1,4 @@
using System;
using CounterStrikeSharp.API.Modules.Cvars;
using CounterStrikeSharp.API.Modules.Entities;
using CounterStrikeSharp.API.Modules.Entities.Constants;
@@ -10,10 +9,13 @@ namespace CounterStrikeSharp.API.Core;
public partial class CBasePlayerController
{
public void SetPawn(CBasePlayerPawn? pawn)
{
if (pawn is null) return;
if (!pawn.IsValid) return;
VirtualFunctions.CBasePlayerController_SetPawnFunc.Invoke(this, pawn, true, false);
}
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void SetPawn(CBasePlayerPawn? pawn)
{
Guard.IsValidEntity(this);
if (pawn is null) return;
if (!pawn.IsValid) return;
VirtualFunctions.CBasePlayerController_SetPawnFunc.Invoke(this, pawn, true, false);
}
}

View File

@@ -10,17 +10,24 @@ public partial class CBasePlayerPawn
/// </summary>
/// <param name="explode"></param>
/// <param name="force"></param>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void CommitSuicide(bool explode, bool force)
{
Guard.IsValidEntity(this);
VirtualFunction.CreateVoid<IntPtr, bool, bool>(Handle, GameData.GetOffset("CBasePlayerPawn_CommitSuicide"))(Handle, explode, force);
}
/// <summary>
/// Remove Player Item
/// </summary>
/// <param name="weapon"></param>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void RemovePlayerItem(CBasePlayerWeapon weapon)
{
Guard.IsValidEntity(this);
Guard.IsValidEntity(weapon);
VirtualFunctions.RemovePlayerItemVirtual(Handle, weapon.Handle);
}
}

View File

@@ -26,6 +26,6 @@ public partial class CCSGameRules
/// </summary>
public void TerminateRound(float delay, RoundEndReason roundEndReason)
{
VirtualFunctions.TerminateRound(Handle, roundEndReason, delay);
VirtualFunctions.TerminateRound(Handle, roundEndReason, delay, 0, 0);
}
}

View File

@@ -13,8 +13,11 @@ public partial class CCSPlayerController
public int? UserId => NativeAPI.GetUseridFromIndex((int)Index);
public CsTeam Team => (CsTeam)TeamNum;
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public IntPtr GiveNamedItem(string item)
{
Guard.IsValidEntity(this);
if (!PlayerPawn.IsValid) return 0;
if (PlayerPawn.Value == null) return 0;
if (!PlayerPawn.Value.IsValid) return 0;
@@ -34,25 +37,37 @@ public partial class CCSPlayerController
return GiveNamedItem(itemString);
}
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void PrintToConsole(string message)
{
Guard.IsValidEntity(this);
NativeAPI.PrintToConsole((int)Index, $"{message}\n\0");
}
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void PrintToChat(string message)
{
Guard.IsValidEntity(this);
VirtualFunctions.ClientPrint(Handle, HudDestination.Chat, message, 0, 0, 0, 0);
}
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void PrintToCenter(string message)
{
Guard.IsValidEntity(this);
VirtualFunctions.ClientPrint(Handle, HudDestination.Center, message, 0, 0, 0, 0);
}
public void PrintToCenterHtml(string message) => PrintToCenterHtml(message, 5);
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void PrintToCenterHtml(string message, int duration)
{
Guard.IsValidEntity(this);
var @event = new EventShowSurvivalRespawnStatus(true)
{
LocToken = message,
@@ -60,13 +75,16 @@ public partial class CCSPlayerController
Userid = this
};
@event.FireEventToClient(this);
@event.Free();
}
/// <summary>
/// Drops the active player weapon on the ground.
/// </summary>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void DropActiveWeapon()
{
Guard.IsValidEntity(this);
if (!PlayerPawn.IsValid) return;
if (PlayerPawn.Value == null) return;
if (!PlayerPawn.Value.IsValid) return;
@@ -83,8 +101,10 @@ public partial class CCSPlayerController
/// <summary>
/// Removes every weapon from the player.
/// </summary>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void RemoveWeapons()
{
Guard.IsValidEntity(this);
if (!PlayerPawn.IsValid) return;
if (PlayerPawn.Value == null) return;
if (!PlayerPawn.Value.IsValid) return;
@@ -99,8 +119,10 @@ public partial class CCSPlayerController
/// </summary>
/// <param name="explode"></param>
/// <param name="force"></param>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void CommitSuicide(bool explode, bool force)
{
Guard.IsValidEntity(this);
if (!PlayerPawn.IsValid) return;
if (PlayerPawn.Value == null) return;
if (!PlayerPawn.Value.IsValid) return;
@@ -111,8 +133,10 @@ public partial class CCSPlayerController
/// <summary>
/// Respawn player
/// </summary>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void Respawn()
{
Guard.IsValidEntity(this);
if (!PlayerPawn.IsValid) return;
if (PlayerPawn.Value == null) return;
if (!PlayerPawn.Value.IsValid) return;
@@ -128,8 +152,11 @@ public partial class CCSPlayerController
/// Forcibly switches the team of the player, the player will remain alive and keep their weapons.
/// </summary>
/// <param name="team">The team to switch to</param>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void SwitchTeam(CsTeam team)
{
Guard.IsValidEntity(this);
VirtualFunctions.SwitchTeam(Handle, (byte)team);
}
@@ -140,8 +167,11 @@ public partial class CCSPlayerController
/// </remarks>
/// </summary>
/// <param name="team">The team to change to</param>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void ChangeTeam(CsTeam team)
{
Guard.IsValidEntity(this);
VirtualFunction.CreateVoid<IntPtr, CsTeam>(Handle, GameData.GetOffset("CCSPlayerController_ChangeTeam"))(Handle,
team);
}
@@ -151,8 +181,11 @@ public partial class CCSPlayerController
/// </summary>
/// <param name="conVar">Name of the convar to retrieve</param>
/// <returns>ConVar string value</returns>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public string GetConVarValue(string conVar)
{
Guard.IsValidEntity(this);
return NativeAPI.GetClientConvarValue(Slot, conVar);
}
@@ -171,13 +204,12 @@ public partial class CCSPlayerController
/// </summary>
/// <param name="conVar">Console variable name</param>
/// <param name="value">String value to set</param>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
/// <exception cref="InvalidOperationException">Player is not a bot</exception>
public void SetFakeClientConVar(string conVar, string value)
{
if (!IsBot)
{
throw new InvalidOperationException("'SetFakeClientConVar' can only be called for fake clients (bots)");
}
Guard.IsValidEntity(this);
if (!IsBot) throw new InvalidOperationException("'SetFakeClientConVar' can only be called for fake clients (bots)");
NativeAPI.SetFakeClientConvarValue(Slot, conVar, value);
}
@@ -202,20 +234,50 @@ public partial class CCSPlayerController
/// </summary>
public PlayerButtons Buttons => (PlayerButtons)Pawn.Value.MovementServices!.Buttons.ButtonStates[0];
public void ExecuteClientCommand(string command) => NativeAPI.IssueClientCommand(Slot, command);
/// <summary>
/// Issue the specified command to the specified client (mimics that client typing the command at the console).
/// Note: Only works for some commands, marked with the FCVAR_CLIENT_CAN_EXECUTE flag (not many).
/// </summary>
/// <param name="command"></param>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void ExecuteClientCommand(string command)
{
Guard.IsValidEntity(this);
NativeAPI.IssueClientCommand(Slot, command);
}
/// <summary>
/// Issue the specified command directly from the server (mimics the server executing the command with the given player context).
/// <remarks>Works with server commands like `kill`, `explode`, `noclip`, etc. </remarks>
/// </summary>
/// <param name="command"></param>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void ExecuteClientCommandFromServer(string command)
{
Guard.IsValidEntity(this);
NativeAPI.IssueClientCommandFromServer(Slot, command);
}
/// <summary>
/// Overrides who a player can hear in voice chat.
/// </summary>
/// <param name="sender">Player talking in the voice chat</param>
/// <param name="override">Whether the talker should be heard</param>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void SetListenOverride(CCSPlayerController sender, ListenOverride @override)
{
Guard.IsValidEntity(this);
NativeAPI.SetClientListening(Handle, sender.Handle, (Byte)@override);
}
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public ListenOverride GetListenOverride(CCSPlayerController sender)
{
Guard.IsValidEntity(this);
return NativeAPI.GetClientListening(Handle, sender.Handle);
}
@@ -224,27 +286,31 @@ public partial class CCSPlayerController
/// <summary>
/// Returns the authorized SteamID of this user which has been validated with the SteamAPI.
/// </summary>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public SteamID? AuthorizedSteamID
{
get
{
if (!IsValid) return null;
Guard.IsValidEntity(this);
var authorizedSteamId = NativeAPI.GetPlayerAuthorizedSteamid(Slot);
if ((long)authorizedSteamId == -1) return null;
return (SteamID)authorizedSteamId;
}
}
/// <summary>
/// Returns the IP address (and possibly port) of this player.
/// <remarks>Returns 127.0.0.1 if the player is a bot.</remarks>
/// </summary>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public string? IpAddress
{
get
{
if (!IsValid) return null;
Guard.IsValidEntity(this);
var ipAddress = NativeAPI.GetPlayerIpAddress(Slot);
if (string.IsNullOrWhiteSpace(ipAddress)) return null;
@@ -255,9 +321,20 @@ public partial class CCSPlayerController
/// <summary>
/// Determines how the player interacts with voice chat.
/// </summary>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public VoiceFlags VoiceFlags
{
get => (VoiceFlags)NativeAPI.GetClientVoiceFlags(Handle);
set => NativeAPI.SetClientVoiceFlags(Handle, (Byte)value);
get
{
Guard.IsValidEntity(this);
return (VoiceFlags)NativeAPI.GetClientVoiceFlags(Handle);
}
set
{
Guard.IsValidEntity(this);
NativeAPI.SetClientVoiceFlags(Handle, (Byte)value);
}
}
}

View File

@@ -23,16 +23,26 @@ public partial class CCSPlayer_ItemServices
/// <summary>
/// Drops the active player weapon on the ground.
/// </summary>
/// <exception cref="InvalidOperationException">ItemServices points to null</exception>
public void DropActivePlayerWeapon(CBasePlayerWeapon activeWeapon)
{
if(Handle == IntPtr.Zero)
throw new InvalidOperationException("ItemServices points to null.");
Guard.IsValidEntity(activeWeapon);
VirtualFunction.CreateVoid<nint, nint>(Handle, GameData.GetOffset("CCSPlayer_ItemServices_DropActivePlayerWeapon"))(Handle, activeWeapon.Handle);
}
/// <summary>
/// Removes every weapon from the player.
/// </summary>
/// <exception cref="InvalidOperationException">ItemServices points to null</exception>
public void RemoveWeapons()
{
if (Handle == IntPtr.Zero)
throw new InvalidOperationException("ItemServices points to null.");
VirtualFunction.CreateVoid<nint>(Handle, GameData.GetOffset("CCSPlayer_ItemServices_RemoveWeapons"))(Handle);
}
}

View File

@@ -32,7 +32,12 @@ public partial class CEntityInstance : IEquatable<CEntityInstance>
public string DesignerName => IsValid ? Entity?.DesignerName : null;
public void Remove() => VirtualFunctions.UTIL_Remove(this.Handle);
public void Remove()
{
Guard.IsValidEntity(this);
VirtualFunctions.UTIL_Remove(this.Handle);
}
public bool Equals(CEntityInstance? other)
{
@@ -58,7 +63,7 @@ public partial class CEntityInstance : IEquatable<CEntityInstance>
{
return !Equals(left, right);
}
/// <summary>
/// Calls a named input method on an entity.
/// <example>
@@ -72,8 +77,11 @@ public partial class CEntityInstance : IEquatable<CEntityInstance>
/// <param name="caller">Entity that is sending the event, <see langword="null"/> for no entity</param>
/// <param name="value">String variant value to send with the event</param>
/// <param name="outputId">Unknown, defaults to 0</param>
/// <exception cref="InvalidOperationException">Entity is not valid</exception>
public void AcceptInput(string inputName, CEntityInstance? activator = null, CEntityInstance? caller = null, string value = "", int outputId = 0)
{
Guard.IsValidEntity(this);
VirtualFunctions.AcceptInput(Handle, inputName, activator?.Handle ?? IntPtr.Zero, caller?.Handle ?? IntPtr.Zero, value, 0);
}
}

View File

@@ -23,8 +23,11 @@ public partial class CGameSceneNode
/// <summary>
/// Gets the <see cref="CSkeletonInstance"/> instance from the node.
/// </summary>
/// <exception cref="InvalidOperationException">GameSceneNode points to null</exception>
public CSkeletonInstance GetSkeletonInstance()
{
if (Handle == IntPtr.Zero) throw new InvalidOperationException("GameSceneNode points to null.");
return new CSkeletonInstance(VirtualFunction.Create<nint, nint>(Handle, GameData.GetOffset("CGameSceneNode_GetSkeletonInstance"))(Handle));
}
}

View File

@@ -1,6 +1,12 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using CounterStrikeSharp.API.Core.Capabilities;
using CounterStrikeSharp.API.Core.Commands;
using CounterStrikeSharp.API.Core.Hosting;
using McMaster.NETCore.Plugins;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace CounterStrikeSharp.API.Core.Plugin.Host;
@@ -9,16 +15,51 @@ public class PluginManager : IPluginManager
{
private readonly HashSet<PluginContext> _loadedPluginContexts = new();
private readonly IScriptHostConfiguration _scriptHostConfiguration;
private readonly ICommandManager _commandManager;
private readonly IServiceProvider _serviceProvider;
private readonly ILogger<PluginManager> _logger;
private readonly Dictionary<string, Assembly> _sharedAssemblies = new();
private bool _loadedSharedLibs = false;
public PluginManager(IScriptHostConfiguration scriptHostConfiguration, ILogger<PluginManager> logger, IServiceProvider serviceProvider)
public PluginManager(IScriptHostConfiguration scriptHostConfiguration, ICommandManager commandManager,
ILogger<PluginManager> logger, IServiceProvider serviceProvider, IServiceScopeFactory serviceScopeFactory)
{
_scriptHostConfiguration = scriptHostConfiguration;
_commandManager = commandManager;
_logger = logger;
_serviceProvider = serviceProvider;
}
private void LoadLibrary(string path)
{
var loader = PluginLoader.CreateFromAssemblyFile(path, new[] { typeof(IPlugin), typeof(PluginCapability<>), typeof(PlayerCapability<>) },
config => { config.PreferSharedTypes = true; });
var assembly = loader.LoadDefaultAssembly();
_sharedAssemblies[assembly.GetName().FullName] = assembly;
}
private void LoadSharedLibraries()
{
var sharedDirectory = Directory.GetDirectories(_scriptHostConfiguration.SharedPath);
var sharedAssemblyPaths = sharedDirectory
.Select(dir => Path.Combine(dir, Path.GetFileName(dir) + ".dll"))
.Where(File.Exists)
.ToArray();
foreach (var sharedAssemblyPath in sharedAssemblyPaths)
{
try
{
LoadLibrary(sharedAssemblyPath);
}
catch (Exception e)
{
_logger.LogError(e, "Failed to load shared assembly from {Path}", sharedAssemblyPath);
}
}
}
public void Load()
{
var pluginDirectories = Directory.GetDirectories(_scriptHostConfiguration.PluginPath);
@@ -27,6 +68,22 @@ public class PluginManager : IPluginManager
.Where(File.Exists)
.ToArray();
AssemblyLoadContext.Default.Resolving += (context, name) =>
{
if (!_loadedSharedLibs)
{
LoadSharedLibraries();
_loadedSharedLibs = true;
}
if (!_sharedAssemblies.TryGetValue(name.FullName, out var assembly))
{
return null;
}
return assembly;
};
foreach (var path in pluginAssemblyPaths)
{
try
@@ -38,6 +95,18 @@ public class PluginManager : IPluginManager
_logger.LogError(e, "Failed to load plugin from {Path}", path);
}
}
foreach (var plugin in _loadedPluginContexts)
{
try
{
plugin.Plugin?.OnAllPluginsLoaded(false);
}
catch (Exception e)
{
_logger.LogError(e, "OnAllPluginsLoaded failed");
}
}
}
public IEnumerable<PluginContext> GetLoadedPlugins()
@@ -47,7 +116,8 @@ public class PluginManager : IPluginManager
public void LoadPlugin(string path)
{
var plugin = new PluginContext(_serviceProvider, _scriptHostConfiguration, path, _loadedPluginContexts.Select(x => x.PluginId).DefaultIfEmpty(0).Max() + 1);
var plugin = new PluginContext(_serviceProvider, _commandManager, _scriptHostConfiguration, path,
_loadedPluginContexts.Select(x => x.PluginId).DefaultIfEmpty(0).Max() + 1);
_loadedPluginContexts.Add(plugin);
plugin.Load();
}

View File

@@ -18,9 +18,12 @@ using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using CounterStrikeSharp.API.Core.Attributes;
using CounterStrikeSharp.API.Core.Capabilities;
using CounterStrikeSharp.API.Core.Commands;
using CounterStrikeSharp.API.Core.Hosting;
using CounterStrikeSharp.API.Core.Logging;
using CounterStrikeSharp.API.Core.Translations;
using CounterStrikeSharp.API.Core.Plugin.Host;
using McMaster.NETCore.Plugins;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
@@ -38,37 +41,43 @@ namespace CounterStrikeSharp.API.Core.Plugin
private PluginLoader Loader { get; set; }
private IServiceProvider ServiceProvider { get; set; }
private ServiceProvider ServiceProvider { get; set; }
public int PluginId { get; }
private readonly ICommandManager _commandManager;
private readonly IScriptHostConfiguration _hostConfiguration;
private readonly string _path;
private readonly FileSystemWatcher _fileWatcher;
private readonly IServiceProvider _applicationServiceProvider;
public string FilePath => _path;
private IServiceScope _serviceScope;
// TOOD: ServiceCollection
private ILogger _logger = CoreLogging.Factory.CreateLogger<PluginContext>();
public PluginContext(IServiceProvider applicationServiceProvider, IScriptHostConfiguration hostConfiguration, string path, int id)
public PluginContext(IServiceProvider applicationServiceProvider, ICommandManager commandManager,
IScriptHostConfiguration hostConfiguration,
string path, int id)
{
_applicationServiceProvider = applicationServiceProvider;
_commandManager = commandManager;
_hostConfiguration = hostConfiguration;
_path = path;
PluginId = id;
Loader = PluginLoader.CreateFromAssemblyFile(path,
new[]
{
typeof(IPlugin), typeof(ILogger), typeof(IServiceCollection), typeof(IPluginServiceCollection<>)
typeof(IPlugin), typeof(ILogger), typeof(IServiceCollection), typeof(IPluginServiceCollection<>),
typeof(ICommandManager)
}, config =>
{
config.EnableHotReload = true;
config.IsUnloadable = true;
config.PreferSharedTypes = true;
});
if (CoreConfig.PluginHotReloadEnabled)
{
_fileWatcher = new FileSystemWatcher
@@ -102,6 +111,7 @@ namespace CounterStrikeSharp.API.Core.Plugin
Loader = eventargs.Loader;
Unload(hotReload: true);
Load(hotReload: true);
Plugin.OnAllPluginsLoaded(hotReload: true);
});
return Task.CompletedTask;
@@ -110,12 +120,12 @@ namespace CounterStrikeSharp.API.Core.Plugin
public void Load(bool hotReload = false)
{
if (State == PluginState.Loaded) return;
using (Loader.EnterContextualReflection())
{
var defaultAssembly = Loader.LoadDefaultAssembly();
Type pluginType = defaultAssembly.GetTypes()
Type pluginType = defaultAssembly.GetExportedTypes()
.FirstOrDefault(t => typeof(IPlugin).IsAssignableFrom(t));
if (pluginType == null) throw new Exception("Unable to find plugin in assembly");
@@ -168,12 +178,14 @@ namespace CounterStrikeSharp.API.Core.Plugin
method?.Invoke(pluginServiceCollection, new object[] { serviceCollection });
}
}
serviceCollection.AddScoped<ICommandManager>(c => _commandManager);
serviceCollection.DecorateSingleton<ICommandManager, PluginCommandManagerDecorator>();
serviceCollection.AddSingleton<IPluginContext>(this);
serviceCollection.TryAddSingleton<IStringLocalizerFactory, JsonStringLocalizerFactory>();
serviceCollection.TryAddTransient(typeof(IStringLocalizer<>), typeof(StringLocalizer<>));
serviceCollection.TryAddTransient(typeof(IStringLocalizer), typeof(StringLocalizer));
ServiceProvider = serviceCollection.BuildServiceProvider();
var minimumApiVersion = pluginType.GetCustomAttribute<MinimumApiVersion>()?.Version;
@@ -186,13 +198,18 @@ namespace CounterStrikeSharp.API.Core.Plugin
_logger.LogInformation("Loading plugin {Name}", pluginType.Assembly.GetName().Name);
Plugin = ServiceProvider.GetRequiredService(pluginType) as IPlugin;
_serviceScope = ServiceProvider.CreateScope();
Plugin = _serviceScope.ServiceProvider.GetRequiredService(pluginType) as IPlugin;
if (Plugin == null) throw new Exception("Unable to create plugin instance");
State = PluginState.Loading;
Plugin.ModulePath = _path;
Plugin.Logger = _serviceScope.ServiceProvider.GetRequiredService<ILoggerFactory>()
.CreateLogger(pluginType);
Plugin.CommandManager = _serviceScope.ServiceProvider.GetRequiredService<ICommandManager>();
Plugin.RegisterAllAttributes(Plugin);
Plugin.Localizer = ServiceProvider.GetRequiredService<IStringLocalizer>();
Plugin.Logger = ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger(pluginType);
@@ -206,6 +223,7 @@ namespace CounterStrikeSharp.API.Core.Plugin
}
}
public void Unload(bool hotReload = false)
{
if (State == PluginState.Unloaded) return;
@@ -218,6 +236,7 @@ namespace CounterStrikeSharp.API.Core.Plugin
Plugin.Unload(hotReload);
Plugin.Dispose();
_serviceScope.Dispose();
_logger.LogInformation("Finished unloading plugin {Name}", cachedName);
}

View File

@@ -23,7 +23,7 @@ public partial class CBaseIssue : NativeObject
public string TypeString
{
get { return Schema.GetString(this.Handle, "CBaseIssue", "m_szTypeString"); }
set { Schema.SetString(this.Handle, "CBaseIssue", "m_szTypeString", value); }
set { Schema.SetStringBytes(this.Handle, "CBaseIssue", "m_szTypeString", value, 64); }
}
// m_szDetailsString
@@ -31,7 +31,7 @@ public partial class CBaseIssue : NativeObject
public string DetailsString
{
get { return Schema.GetString(this.Handle, "CBaseIssue", "m_szDetailsString"); }
set { Schema.SetString(this.Handle, "CBaseIssue", "m_szDetailsString", value); }
set { Schema.SetStringBytes(this.Handle, "CBaseIssue", "m_szDetailsString", value, 260); }
}
// m_iNumYesVotes

View File

@@ -55,7 +55,7 @@ public partial class CBasePlayerController : CBaseEntity
public string PlayerName
{
get { return Schema.GetString(this.Handle, "CBasePlayerController", "m_iszPlayerName"); }
set { Schema.SetString(this.Handle, "CBasePlayerController", "m_iszPlayerName", value); }
set { Schema.SetStringBytes(this.Handle, "CBasePlayerController", "m_iszPlayerName", value, 128); }
}
// m_szNetworkIDString

View File

@@ -31,7 +31,7 @@ public partial class CCSBot : CBot
public string Name
{
get { return Schema.GetString(this.Handle, "CCSBot", "m_name"); }
set { Schema.SetString(this.Handle, "CCSBot", "m_name", value); }
set { Schema.SetStringBytes(this.Handle, "CCSBot", "m_name", value, 64); }
}
// m_combatRange

View File

@@ -195,7 +195,7 @@ public partial class CCSGameRules : CTeamplayRules
public string TournamentEventName
{
get { return Schema.GetString(this.Handle, "CCSGameRules", "m_szTournamentEventName"); }
set { Schema.SetString(this.Handle, "CCSGameRules", "m_szTournamentEventName", value); }
set { Schema.SetStringBytes(this.Handle, "CCSGameRules", "m_szTournamentEventName", value, 512); }
}
// m_szTournamentEventStage
@@ -203,7 +203,7 @@ public partial class CCSGameRules : CTeamplayRules
public string TournamentEventStage
{
get { return Schema.GetString(this.Handle, "CCSGameRules", "m_szTournamentEventStage"); }
set { Schema.SetString(this.Handle, "CCSGameRules", "m_szTournamentEventStage", value); }
set { Schema.SetStringBytes(this.Handle, "CCSGameRules", "m_szTournamentEventStage", value, 512); }
}
// m_szMatchStatTxt
@@ -211,7 +211,7 @@ public partial class CCSGameRules : CTeamplayRules
public string MatchStatTxt
{
get { return Schema.GetString(this.Handle, "CCSGameRules", "m_szMatchStatTxt"); }
set { Schema.SetString(this.Handle, "CCSGameRules", "m_szMatchStatTxt", value); }
set { Schema.SetStringBytes(this.Handle, "CCSGameRules", "m_szMatchStatTxt", value, 512); }
}
// m_szTournamentPredictionsTxt
@@ -219,7 +219,7 @@ public partial class CCSGameRules : CTeamplayRules
public string TournamentPredictionsTxt
{
get { return Schema.GetString(this.Handle, "CCSGameRules", "m_szTournamentPredictionsTxt"); }
set { Schema.SetString(this.Handle, "CCSGameRules", "m_szTournamentPredictionsTxt", value); }
set { Schema.SetStringBytes(this.Handle, "CCSGameRules", "m_szTournamentPredictionsTxt", value, 512); }
}
// m_nTournamentPredictionsPct

View File

@@ -111,7 +111,7 @@ public partial class CCSPlayerController : CBasePlayerController
public string ClanName
{
get { return Schema.GetString(this.Handle, "CCSPlayerController", "m_szClanName"); }
set { Schema.SetString(this.Handle, "CCSPlayerController", "m_szClanName", value); }
set { Schema.SetStringBytes(this.Handle, "CCSPlayerController", "m_szClanName", value, 32); }
}
// m_iCoachingTeam

View File

@@ -67,7 +67,7 @@ public partial class CCSPlayerPawn : CCSPlayerPawnBase
public string LastPlaceName
{
get { return Schema.GetString(this.Handle, "CCSPlayerPawn", "m_szLastPlaceName"); }
set { Schema.SetString(this.Handle, "CCSPlayerPawn", "m_szLastPlaceName", value); }
set { Schema.SetStringBytes(this.Handle, "CCSPlayerPawn", "m_szLastPlaceName", value, 18); }
}
// m_bInHostageResetZone
@@ -199,7 +199,7 @@ public partial class CCSPlayerPawn : CCSPlayerPawnBase
public string RagdollDamageWeaponName
{
get { return Schema.GetString(this.Handle, "CCSPlayerPawn", "m_szRagdollDamageWeaponName"); }
set { Schema.SetString(this.Handle, "CCSPlayerPawn", "m_szRagdollDamageWeaponName", value); }
set { Schema.SetStringBytes(this.Handle, "CCSPlayerPawn", "m_szRagdollDamageWeaponName", value, 64); }
}
// m_bRagdollDamageHeadshot

View File

@@ -243,7 +243,7 @@ public partial class CCSPlayerPawnBase : CBasePlayerPawn
public string MenuStringBuffer
{
get { return Schema.GetString(this.Handle, "CCSPlayerPawnBase", "m_MenuStringBuffer"); }
set { Schema.SetString(this.Handle, "CCSPlayerPawnBase", "m_MenuStringBuffer", value); }
set { Schema.SetStringBytes(this.Handle, "CCSPlayerPawnBase", "m_MenuStringBuffer", value, 1024); }
}
// m_fIntroCamTime

View File

@@ -35,7 +35,7 @@ public partial class CCSTeam : CTeam
public string TeamMatchStat
{
get { return Schema.GetString(this.Handle, "CCSTeam", "m_szTeamMatchStat"); }
set { Schema.SetString(this.Handle, "CCSTeam", "m_szTeamMatchStat", value); }
set { Schema.SetStringBytes(this.Handle, "CCSTeam", "m_szTeamMatchStat", value, 512); }
}
// m_numMapVictories
@@ -59,7 +59,7 @@ public partial class CCSTeam : CTeam
public string ClanTeamname
{
get { return Schema.GetString(this.Handle, "CCSTeam", "m_szClanTeamname"); }
set { Schema.SetString(this.Handle, "CCSTeam", "m_szClanTeamname", value); }
set { Schema.SetStringBytes(this.Handle, "CCSTeam", "m_szClanTeamname", value, 129); }
}
// m_iClanID
@@ -71,7 +71,7 @@ public partial class CCSTeam : CTeam
public string TeamFlagImage
{
get { return Schema.GetString(this.Handle, "CCSTeam", "m_szTeamFlagImage"); }
set { Schema.SetString(this.Handle, "CCSTeam", "m_szTeamFlagImage", value); }
set { Schema.SetStringBytes(this.Handle, "CCSTeam", "m_szTeamFlagImage", value, 8); }
}
// m_szTeamLogoImage
@@ -79,7 +79,7 @@ public partial class CCSTeam : CTeam
public string TeamLogoImage
{
get { return Schema.GetString(this.Handle, "CCSTeam", "m_szTeamLogoImage"); }
set { Schema.SetString(this.Handle, "CCSTeam", "m_szTeamLogoImage", value); }
set { Schema.SetStringBytes(this.Handle, "CCSTeam", "m_szTeamLogoImage", value, 8); }
}
// m_flNextResourceTime

View File

@@ -83,7 +83,7 @@ public partial class CColorCorrection : CBaseEntity
public string NetlookupFilename
{
get { return Schema.GetString(this.Handle, "CColorCorrection", "m_netlookupFilename"); }
set { Schema.SetString(this.Handle, "CColorCorrection", "m_netlookupFilename", value); }
set { Schema.SetStringBytes(this.Handle, "CColorCorrection", "m_netlookupFilename", value, 512); }
}
// m_lookupFilename

View File

@@ -43,7 +43,7 @@ public partial class CColorCorrectionVolume : CBaseTrigger
public string LookupFilename
{
get { return Schema.GetString(this.Handle, "CColorCorrectionVolume", "m_lookupFilename"); }
set { Schema.SetString(this.Handle, "CColorCorrectionVolume", "m_lookupFilename", value); }
set { Schema.SetStringBytes(this.Handle, "CColorCorrectionVolume", "m_lookupFilename", value, 512); }
}
// m_LastEnterWeight

View File

@@ -67,7 +67,7 @@ public partial class CEconItemView : IEconItemInterface
public string CustomName
{
get { return Schema.GetString(this.Handle, "CEconItemView", "m_szCustomName"); }
set { Schema.SetString(this.Handle, "CEconItemView", "m_szCustomName", value); }
set { Schema.SetStringBytes(this.Handle, "CEconItemView", "m_szCustomName", value, 161); }
}
// m_szCustomNameOverride
@@ -75,7 +75,7 @@ public partial class CEconItemView : IEconItemInterface
public string CustomNameOverride
{
get { return Schema.GetString(this.Handle, "CEconItemView", "m_szCustomNameOverride"); }
set { Schema.SetString(this.Handle, "CEconItemView", "m_szCustomNameOverride", value); }
set { Schema.SetStringBytes(this.Handle, "CEconItemView", "m_szCustomNameOverride", value, 161); }
}
}

View File

@@ -87,7 +87,7 @@ public partial class CEnvMicrophone : CPointEntity
public string LastSound
{
get { return Schema.GetString(this.Handle, "CEnvMicrophone", "m_szLastSound"); }
set { Schema.SetString(this.Handle, "CEnvMicrophone", "m_szLastSound", value); }
set { Schema.SetStringBytes(this.Handle, "CEnvMicrophone", "m_szLastSound", value, 256); }
}
// m_iLastRoutedFrame

View File

@@ -115,7 +115,7 @@ public partial class CEnvProjectedTexture : CModelPointEntity
public string SpotlightTextureName
{
get { return Schema.GetString(this.Handle, "CEnvProjectedTexture", "m_SpotlightTextureName"); }
set { Schema.SetString(this.Handle, "CEnvProjectedTexture", "m_SpotlightTextureName", value); }
set { Schema.SetStringBytes(this.Handle, "CEnvProjectedTexture", "m_SpotlightTextureName", value, 512); }
}
// m_nSpotlightTextureFrame

View File

@@ -23,7 +23,7 @@ public partial class CGameRules : NativeObject
public string QuestName
{
get { return Schema.GetString(this.Handle, "CGameRules", "m_szQuestName"); }
set { Schema.SetString(this.Handle, "CGameRules", "m_szQuestName", value); }
set { Schema.SetStringBytes(this.Handle, "CGameRules", "m_szQuestName", value, 128); }
}
// m_nQuestPhase

View File

@@ -23,7 +23,7 @@ public partial class CParticleSystem : CBaseModelEntity
public string SnapshotFileName
{
get { return Schema.GetString(this.Handle, "CParticleSystem", "m_szSnapshotFileName"); }
set { Schema.SetString(this.Handle, "CParticleSystem", "m_szSnapshotFileName", value); }
set { Schema.SetStringBytes(this.Handle, "CParticleSystem", "m_szSnapshotFileName", value, 512); }
}
// m_bActive

View File

@@ -39,7 +39,7 @@ public partial class CPlayerPing : CBaseEntity
public string PlaceName
{
get { return Schema.GetString(this.Handle, "CPlayerPing", "m_szPlaceName"); }
set { Schema.SetString(this.Handle, "CPlayerPing", "m_szPlaceName", value); }
set { Schema.SetStringBytes(this.Handle, "CPlayerPing", "m_szPlaceName", value, 18); }
}
}

View File

@@ -23,7 +23,7 @@ public partial class CPointClientUIWorldTextPanel : CPointClientUIWorldPanel
public string MessageText
{
get { return Schema.GetString(this.Handle, "CPointClientUIWorldTextPanel", "m_messageText"); }
set { Schema.SetString(this.Handle, "CPointClientUIWorldTextPanel", "m_messageText", value); }
set { Schema.SetStringBytes(this.Handle, "CPointClientUIWorldTextPanel", "m_messageText", value, 512); }
}
}

View File

@@ -23,7 +23,7 @@ public partial class CPointWorldText : CModelPointEntity
public string MessageText
{
get { return Schema.GetString(this.Handle, "CPointWorldText", "m_messageText"); }
set { Schema.SetString(this.Handle, "CPointWorldText", "m_messageText", value); }
set { Schema.SetStringBytes(this.Handle, "CPointWorldText", "m_messageText", value, 512); }
}
// m_FontName
@@ -31,7 +31,7 @@ public partial class CPointWorldText : CModelPointEntity
public string FontName
{
get { return Schema.GetString(this.Handle, "CPointWorldText", "m_FontName"); }
set { Schema.SetString(this.Handle, "CPointWorldText", "m_FontName", value); }
set { Schema.SetStringBytes(this.Handle, "CPointWorldText", "m_FontName", value, 64); }
}
// m_bEnabled

View File

@@ -35,7 +35,7 @@ public partial class CTeam : CBaseEntity
public string Teamname
{
get { return Schema.GetString(this.Handle, "CTeam", "m_szTeamname"); }
set { Schema.SetString(this.Handle, "CTeam", "m_szTeamname", value); }
set { Schema.SetStringBytes(this.Handle, "CTeam", "m_szTeamname", value, 129); }
}
}

View File

@@ -75,7 +75,7 @@ public partial class CTriggerSndSosOpvar : CBaseTrigger
public string OpvarNameChar
{
get { return Schema.GetString(this.Handle, "CTriggerSndSosOpvar", "m_opvarNameChar"); }
set { Schema.SetString(this.Handle, "CTriggerSndSosOpvar", "m_opvarNameChar", value); }
set { Schema.SetStringBytes(this.Handle, "CTriggerSndSosOpvar", "m_opvarNameChar", value, 256); }
}
// m_stackNameChar
@@ -83,7 +83,7 @@ public partial class CTriggerSndSosOpvar : CBaseTrigger
public string StackNameChar
{
get { return Schema.GetString(this.Handle, "CTriggerSndSosOpvar", "m_stackNameChar"); }
set { Schema.SetString(this.Handle, "CTriggerSndSosOpvar", "m_stackNameChar", value); }
set { Schema.SetStringBytes(this.Handle, "CTriggerSndSosOpvar", "m_stackNameChar", value, 256); }
}
// m_operatorNameChar
@@ -91,7 +91,7 @@ public partial class CTriggerSndSosOpvar : CBaseTrigger
public string OperatorNameChar
{
get { return Schema.GetString(this.Handle, "CTriggerSndSosOpvar", "m_operatorNameChar"); }
set { Schema.SetString(this.Handle, "CTriggerSndSosOpvar", "m_operatorNameChar", value); }
set { Schema.SetStringBytes(this.Handle, "CTriggerSndSosOpvar", "m_operatorNameChar", value, 256); }
}
// m_VecNormPos

View File

@@ -16,6 +16,7 @@
<PublishRepositoryUrl>true</PublishRepositoryUrl>
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<!-- <GenerateCompatibilitySuppressionFile>true</GenerateCompatibilitySuppressionFile> -->
</PropertyGroup>
<PropertyGroup>
<ApiCompatValidateAssemblies>true</ApiCompatValidateAssemblies>

View File

@@ -1,5 +1,7 @@
// Global using directives
global using System;
global using System.Linq;
global using System.IO;
global using System.Collections.Generic;
global using CounterStrikeSharp.API.Core;

View File

@@ -0,0 +1,11 @@
namespace CounterStrikeSharp.API
{
public static class Guard
{
public static void IsValidEntity(CEntityInstance ent)
{
if (!ent.IsValid)
throw new InvalidOperationException("Entity is not valid");
}
}
}

View File

@@ -19,7 +19,7 @@ namespace CounterStrikeSharp.API.Modules.Admin
public static partial class AdminManager
{
private static Dictionary<string, CommandData> CommandOverrides = new();
private static Dictionary<string, CommandData> CommandOverrides = new(StringComparer.InvariantCultureIgnoreCase);
public static void LoadCommandOverrides(string overridePath)
{
try
@@ -62,7 +62,7 @@ namespace CounterStrikeSharp.API.Modules.Admin
{
CommandOverrides.TryGetValue(commandName, out var overrideDef);
if (overrideDef == null) return false;
return overrideDef.Enabled && overrideDef?.Flags.Count() > 0;
return overrideDef.Enabled;
}
/// <summary>

View File

@@ -2,20 +2,30 @@ using CounterStrikeSharp.API.Modules.Commands;
using CounterStrikeSharp.API.Modules.Utils;
using System.Linq;
using System.Reflection;
using CounterStrikeSharp.API.Core.Commands;
using CounterStrikeSharp.API.Core.Logging;
using Microsoft.Extensions.Logging;
namespace CounterStrikeSharp.API.Modules.Admin
{
public static partial class AdminManager
{
public static ICommandManager CommandManagerProvider { get; internal set; } = null!;
public static void AddCommands()
{
CommandUtils.AddStandaloneCommand("css_admins_reload", "Reloads the admin file.", ReloadAdminsCommand);
CommandUtils.AddStandaloneCommand("css_admins_list", "List admins and their flags.", ListAdminsCommand);
CommandUtils.AddStandaloneCommand("css_groups_reload", "Reloads the admin groups file.", ReloadAdminGroupsCommand);
CommandUtils.AddStandaloneCommand("css_groups_list", "List admin groups and their flags.", ListAdminGroupsCommand);
CommandUtils.AddStandaloneCommand("css_overrides_reload", "Reloads the admin command overrides file.", ReloadAdminOverridesCommand);
CommandUtils.AddStandaloneCommand("css_overrides_list", "List admin command overrides and their flags.", ListAdminOverridesCommand);
CommandManagerProvider.RegisterCommand(new CommandDefinition("css_admins_reload", "Reloads the admin file.",
ReloadAdminsCommand));
CommandManagerProvider.RegisterCommand(new CommandDefinition("css_admins_list",
"List admins and their flags.", ListAdminsCommand));
CommandManagerProvider.RegisterCommand(new CommandDefinition("css_groups_reload",
"Reloads the admin groups file.", ReloadAdminGroupsCommand));
CommandManagerProvider.RegisterCommand(new CommandDefinition("css_groups_list",
"List admin groups and their flags.", ListAdminGroupsCommand));
CommandManagerProvider.RegisterCommand(new CommandDefinition("css_overrides_reload",
"Reloads the admin command overrides file.", ReloadAdminOverridesCommand));
CommandManagerProvider.RegisterCommand(new CommandDefinition("css_overrides_list",
"List admin command overrides and their flags.", ListAdminOverridesCommand));
}
public static void MergeGroupPermsIntoAdmins()
@@ -26,7 +36,7 @@ namespace CounterStrikeSharp.API.Modules.Admin
}
}
[RequiresPermissions(permissions:"@css/generic")]
[RequiresPermissions(permissions: "@css/generic")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
private static void ReloadAdminsCommand(CCSPlayerController? player, CommandInfo command)
{
@@ -36,7 +46,7 @@ namespace CounterStrikeSharp.API.Modules.Admin
MergeGroupPermsIntoAdmins();
}
[RequiresPermissions(permissions:"@css/generic")]
[RequiresPermissions(permissions: "@css/generic")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
private static void ListAdminsCommand(CCSPlayerController? player, CommandInfo command)
{
@@ -50,7 +60,7 @@ namespace CounterStrikeSharp.API.Modules.Admin
}
}
[RequiresPermissions(permissions:"@css/generic")]
[RequiresPermissions(permissions: "@css/generic")]
[CommandHelper(whoCanExecute: CommandUsage.CLIENT_AND_SERVER)]
private static void ReloadAdminGroupsCommand(CCSPlayerController? player, CommandInfo command)
{
@@ -85,8 +95,9 @@ namespace CounterStrikeSharp.API.Modules.Admin
{
foreach (var (commandName, commandDef) in CommandOverrides)
{
command.ReplyToCommand($"{commandName} (enabled: {commandDef.Enabled.ToString()}) - {string.Join(", ", commandDef.Flags)}");
command.ReplyToCommand(
$"{commandName} (enabled: {commandDef.Enabled.ToString()}) - {string.Join(", ", commandDef.Flags)}");
}
}
}
}
}

View File

@@ -132,7 +132,6 @@ namespace CounterStrikeSharp.API.Modules.Admin
foreach (var adminDef in adminsFromFile.Values)
{
adminDef.InitalizeFlags();
Console.WriteLine($"Domains: {adminDef.Flags.Count}");
if (SteamID.TryParse(adminDef.Identity, out var steamId))
{

View File

@@ -34,9 +34,9 @@ namespace CounterStrikeSharp.API.Modules.Admin
if (caller?.AuthorizedSteamID == null) return false;
var adminData = AdminManager.GetPlayerAdminData(caller.AuthorizedSteamID);
if (adminData == null) return false;
if (adminData.CommandOverrides.ContainsKey(Command))
if (adminData.CommandOverrides.TryGetValue(Command, out var command))
{
return adminData.CommandOverrides[Command];
return command;
}
return true;

View File

@@ -0,0 +1,7 @@
namespace CounterStrikeSharp.API.Modules.Commands;
public enum CommandCallingContext
{
Console = 0,
Chat = 1
}

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