diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..ee4cd36 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,27 @@ +name: Build plugins + +on: + push: + pull_request: + schedule: + - cron: "0 4 * * 5" + +jobs: + build: + runs-on: ubuntu-latest + strategy: + matrix: + sm-version: ['1.10', '1.11'] + + name: build plugins + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Set up SourceMod compiler + uses: rumblefrog/setup-sp@master + with: + version: ${{ matrix.sm-version }} + + - name: Compile SourceMod plugins + run: make SPCOMP=spcomp SPFLAGS=-E diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..50d73c0 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,59 @@ +name: Create release + +on: + push: + tags: + - 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10 + +jobs: + build: + runs-on: ubuntu-latest + + name: Create release + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Setup environment + run: echo "RELEASE_VERSION=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV + + - name: Setup sourcemod compiler + uses: rumblefrog/setup-sp@master + with: + version: '1.10' + + - name: Compile sourcemod plugins and archive + run: make release.tar.gz release.zip SPCOMP=spcomp + + - name: Create release + id: create_release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token + with: + tag_name: ${{ github.ref }} + release_name: Release ${{ github.ref }} + draft: false + prerelease: false + + - name: Upload release asset as tar.gz + id: upload-release-asset-tgz + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps + asset_path: ./release.tar.gz + asset_name: ${{ github.event.repository.name }}-${{ env.RELEASE_VERSION }}.tar.gz + asset_content_type: application/gzip + + - name: Upload release asset as zip + id: upload-release-asset-zip + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ steps.create_release.outputs.upload_url }} # This pulls from the CREATE RELEASE step above, referencing it's ID to get its outputs object, which include a `upload_url`. See this blog post for more info: https://jasonet.co/posts/new-features-of-github-actions/#passing-data-to-future-steps + asset_path: ./release.zip + asset_name: ${{ github.event.repository.name }}-${{ env.RELEASE_VERSION }}.zip + asset_content_type: application/zip diff --git a/.gitignore b/.gitignore index 0e4dd6f..51c3393 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,15 @@ -#compiled files +# compiled files *.smx -*.exe -*.o +*.asm +*.lst +*.so -#vim files +# vim files *.sw* + +# tags +tags + +# release +*release.tar.gz +*release.zip diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 9502e1a..0000000 --- a/.travis.yml +++ /dev/null @@ -1,37 +0,0 @@ -language: c - -env: - - SMVERSION=1.6 - - SMVERSION=1.7 - - SMVERSION=1.8 - -matrix: - fast_finish: true - allow_failures: - - env: SMVERSION=1.8 - -before_install: - - sudo apt-get update - - sudo apt-get install gcc-multilib - - sudo apt-get install lynx - - sudo apt-get install lib32stdc++6 - - -before_script: - - SMPATTERN="http:.*sourcemod-.*-linux.*" - - SMURL="http://www.sourcemod.net/smdrop/$SMVERSION/" - - SMPACKAGE=`lynx -dump "$SMURL" | egrep -o "$SMPATTERN" | tail -1` - - wget $SMPACKAGE - - tar -xzf $(basename "$SMPACKAGE") - - cd addons/sourcemod/scripting/ - - chmod +x spcomp - -script: - - ./spcomp jetpack_plus.sp - - ./spcomp jetpack_bling.sp - -after_script: - - ls *.smx - -notifications: - email: false diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + 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. + + + Copyright (C) + + 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 . + +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: + + Copyright (C) + 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 +. + + 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 +. diff --git a/LICENSE.txt b/LICENSE.txt deleted file mode 100644 index 7d2d063..0000000 --- a/LICENSE.txt +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2014 CrimsonTautology - -MIT License - -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. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..2ec8dcd --- /dev/null +++ b/Makefile @@ -0,0 +1,126 @@ +# general Makefile for compiling Sourcemod plugins +# copyright (c) 2021 https://github.com/CrimsonTautology + +SHELL=/bin/bash + +# directories +override scripting_dir=addons/sourcemod/scripting +override include_dir=addons/sourcemod/scripting/include +override plugins_dir=addons/sourcemod/plugins +override configs_dir=addons/sourcemod/configs +override extensions_dir=addons/sourcemod/extensions +override gamedata_dir=addons/sourcemod/gamedata +override translations_dir=addons/sourcemod/translations + +# spcomp +SPCOMP=spcomp +INC=-i$(include_dir) +SPFLAGS= +DEBUG= + +# other programs +CTAGS=ctags +DOS2UNIX=dos2unix +ZIP=zip + +# files +override sourcefiles=$(wildcard $(scripting_dir)/*.sp) +override includefiles=$(shell find $(include_dir) -name '*.inc' 2>/dev/null) + +override plugins=\ + $(patsubst $(scripting_dir)/%.sp, $(plugins_dir)/%.smx, $(sourcefiles)) + +override configs=\ + $(shell find $(configs_dir) -name '*' -type f 2>/dev/null) + +override extensions=\ + $(shell find $(extensions_dir) -name '*.so' -type f 2>/dev/null) + +override gamedata=\ + $(shell find $(gamedata_dir) -name '*.txt' -type f 2>/dev/null) + +override translations=\ + $(shell find $(translations_dir) -name '*.phrases.txt' -type f 2>/dev/null) + +override release_files=README.md LICENSE Makefile addons cfg materials + +# installation +SRCDS=/tmp +override disabled=$(addprefix $(plugins_dir)/,\ + $(notdir $(wildcard $(SRCDS)/$(plugins_dir)/disabled/*.smx))) + +vpath %.sp $(scripting_dir) + +ifeq ($(DEBUG), 1) + SPFLAGS+=DEBUG=1 +endif + +all: clean compile tags + +$(plugins_dir)/%.smx: %.sp | $(plugins_dir) + $(SPCOMP) $^ -o$@ $(INC) $(SPFLAGS) + +$(plugins_dir)/%.asm: %.sp | $(plugins_dir) + $(SPCOMP) $^ -o$@ $(INC) $(SPFLAGS) -a + +$(plugins_dir)%.lst: %.sp | $(plugins_dir) + $(SPCOMP) $^ -o$@ $(INC) $(SPFLAGS) -l + +$(plugins_dir): + mkdir -p $@ + +clean: + $(RM) $(plugins_dir)/*.smx $(plugins_dir)/*.asm $(plugins_dir)/*.lst + +compile: $(plugins) + +tags: + -$(CTAGS) --langmap=c:+.sp,c:+.inc --recurse + +dos2unix: + $(DOS2UNIX) $(sourcefiles) $(includefiles) $(configs) $(gamedata) $(translations) + +list: + @printf 'plugins:\n' + @printf '%s\n' $(plugins) + @printf '\ndisabled plugins on install server:\n' + @printf '%s\n' $(disabled) + @printf '\nsource files:\n' + @printf '%s\n' $(sourcefiles) + @printf '\ninclude files:\n' + @printf '%s\n' $(includefiles) + @printf '\nconfigs:\n' + @printf '%s\n' $(configs) + @printf '\ngamedata:\n' + @printf '%s\n' $(gamedata) + @printf '\nextensions:\n' + @printf '%s\n' $(extensions) + @printf '\ntranslation:\n' + @printf '%s\n' $(translations) + +install: + @# install only plugins that are not in the 'disabled' folder + @$(foreach file, $(filter-out $(disabled), $(plugins)),\ + cp --parents $(file) -t $(SRCDS);) + @if [ -n "$(plugins)" ]; then cp -n --parents $(plugins) -t $(SRCDS); fi + @if [ -n "$(configs)" ]; then cp -n --parents $(configs) -t $(SRCDS); fi + @if [ -n "$(extensions)" ]; then cp -n --parents $(extensions) -t $(SRCDS); fi + @if [ -n "$(gamedata)" ]; then cp --parents $(gamedata) -t $(SRCDS); fi + @if [ -n "$(translations)" ]; then cp --parents $(translations) -t $(SRCDS); fi + @echo "install $(notdir $(filter-out $(disabled), $(plugins)) $(extensions)) to $(SRCDS)" + +uninstall: + @$(RM) \ + $(addprefix $(SRCDS)/, $(plugins)) \ + $(addprefix $(SRCDS)/, $(configs)) \ + $(addprefix $(SRCDS)/, $(gamedata)) \ + $(addprefix $(SRCDS)/, $(translations)) + @echo "uninstall $(notdir $(plugins)) from $(SRCDS)" + +release.tar.gz: compile + tar cvzf $@ $(release_files) --ignore-failed-read + +release.zip: compile + $(ZIP) -r $@ $(release_files) + +.PHONY: all clean compile tags dos2unix list install uninstall diff --git a/README.md b/README.md index 29bd2b9..2b8e0a6 100644 --- a/README.md +++ b/README.md @@ -1,35 +1,104 @@ -# Jetpack Plus -[![Build Status](https://travis-ci.org/CrimsonTautology/sm_jetpack_plus.svg?branch=master)](https://travis-ci.org/CrimsonTautology/sm_jetpack_plus) +# sm-jetpack-plus + +![Build Status](https://github.com/CrimsonTautology/sm-jetpack-plus/workflows/Build%20plugins/badge.svg?style=flat-square) +[![GitHub stars](https://img.shields.io/github/stars/CrimsonTautology/sm-jetpack-plus?style=flat-square)](https://github.com/CrimsonTautology/sm-jetpack-plus/stargazers) +[![GitHub issues](https://img.shields.io/github/issues/CrimsonTautology/sm-jetpack-plus.svg?style=flat-square&logo=github&logoColor=white)](https://github.com/CrimsonTautology/sm-jetpack-plus/issues) +[![GitHub pull requests](https://img.shields.io/github/issues-pr/CrimsonTautology/sm-jetpack-plus.svg?style=flat-square&logo=github&logoColor=white)](https://github.com/CrimsonTautology/sm-jetpack-plus/pulls) +[![GitHub All Releases](https://img.shields.io/github/downloads/CrimsonTautology/sm-jetpack-plus/total.svg?style=flat-square&logo=github&logoColor=white)](https://github.com/CrimsonTautology/sm-jetpack-plus/releases) Rewrite of Knagg0 and naris's [jetpack plugin](https://forums.alliedmods.net/showthread.php?p=488779) for Sourcemod. Redesigned to make it easier to extend and modify. Allows players to fly around while hold down their jump key. -##Installation -* Compile plugins with spcomp (e.g.) -> spcomp addons/sourcemod/scripting/jetpack_plus.sp -> spcomp addons/sourcemod/scripting/jetpack_bling.sp -* Move compiled .smx files into your `"/addons/sourcemod/plugins"` directory. - +## Requirements +* [SourceMod](https://www.sourcemod.net/) 1.10 or later + + +## Installation +Make sure your server has SourceMod installed. See [Installing SourceMod](https://wiki.alliedmods.net/Installing_SourceMod). If you are new to managing SourceMod on a server be sure to read the '[Installing Plugins](https://wiki.alliedmods.net/Managing_your_sourcemod_installation#Installing_Plugins)' section from the official SourceMod Wiki. + +Download the latest [release](https://github.com/CrimsonTautology/sm-jetpack-plus/releases/latest) and copy the contents of `addons` to your server's `addons` directory. It is recommended to restart your server after installing. -##Requirements -* [Donator Interface](https://forums.alliedmods.net/showthread.php?t=145542)(Optional) +To confirm the plugin is installed correctly, on your server's console type: +``` +sm plugins list +``` -# Jetpack +## Usage +There is no longer a need for a player to bind a key to +sm_jetpack. To use the jetpack just hold down the jump key. -* There is no longer a need for a player to bind a key to +sm_jetpack. To use the jetpack just hold down the jump key. -* `sm_jetpack` - Set to 1 to enable this plugin, 0 to disable -* `sm_jetpack_force` - Strength at which the jetpack pushes the player. -* `sm_jetpack_jump_delay` - The time in seconds the jump key needs to be pressed before the jetpack starts. -# Jetpack Bling +### Console Variables +| Command | Accepts | Values | Description | +| --- | --- | --- | --- | +| sm_foo | integer | 0-999 | Does Foo | +| sm_jetpack | boolean | 0-1 | Set to 1 to enable this plugin, 0 to disable | +| sm_jetpack_force | float | any | Strength at which the jetpack pushes the player. | +| sm_jetpack_jump_delay | float | any | The time in seconds the jump key needs to be pressed before the jetpack starts. | + + +## Jetpack Bling * Separate plugin to handle the sounds and particle effects; gives jetpacks their "bling" * You can add your own! Just edit `addons/sourcemod/configs/jetpacks..cfg` * The plugin will dynamicly load the config file for the corresponding game so you don't have to worry about incompatible sounds or particles. * Players can choose their jetpack's effects by typing `!bling` into chat. -* If the donator plugin is installed; this plugin can be restricted such that only donators can change their bling. -* `sm_jetpack_donators_only` - Set to 1 to prevent non-donators from changing their jetpack effects -# Notes + +### Commands +NOTE: All commands can be run from the in-game chat by replacing `sm_` with `!` or `/`. For example `sm_rtv` can be called with `!rtv`. + +| Command | Accepts | Values | SM Admin Flag | Description | +| --- | --- | --- | --- | --- | +| sm_bling | None | None | None | Change jetpack's particle effects | + + +## Notes * This has only been tested with TF2 but should work in other games, except... * I have only made a bling config for TF2, you will have to create your own `addons/sourcemod/configs/jetpacks..cfg` file for other games. If you want to add some for other mods send a pull request. + +## Compiling +If you are new to SourceMod development be sure to read the '[Compiling SourceMod Plugins](https://wiki.alliedmods.net/Compiling_SourceMod_Plugins)' page from the official SourceMod Wiki. + +You will need the `spcomp` compiler from the latest stable release of SourceMod. Download it from [here](https://www.sourcemod.net/downloads.php?branch=stable) and uncompress it to a folder. The compiler `spcomp` is located in `addons/sourcemod/scripting/`; you may wish to add this folder to your path. + +Once you have SourceMod downloaded you can then compile using the included [Makefile](Makefile). + +```sh +cd sm-jetpack-plus +make SPCOMP=/path/to/addons/sourcemod/scripting/spcomp +``` + +Other included Makefile targets that you may find useful for development: + +```sh +# compile plugin with DEBUG enabled +make DEBUG=1 + +# pass additonal flags to spcomp +make SPFLAGS="-E -w207" + +# install plugins and required files to local srcds install +make install SRCDS=/path/to/srcds + +# uninstall plugins and required files from local srcds install +make uninstall SRCDS=/path/to/srcds +``` + + +## Contributing +1. Fork the Project +2. Create your Feature Branch (`git checkout -b feature/AmazingFeature`) +3. Commit your Changes (`git commit -m 'Add some AmazingFeature'`) +4. Push to the Branch (`git push origin feature/AmazingFeature`) +5. Open a Pull Request + + +## License +[GNU General Public License v3.0](https://choosealicense.com/licenses/gpl-3.0/) + + +## Acknowledgements +* [Knagg0 and naris's original plugin](https://forums.alliedmods.net/showthread.php?p=488779) +* L. Duke's particle.inc +* [smlib](https://github.com/bcserv/smlib) +* [Flyflo's GoombaStomp plugin (majority of tags.inc)](https://github.com/Flyflo/SM-Goomba-Stomp) diff --git a/Rakefile b/Rakefile deleted file mode 100644 index de32642..0000000 --- a/Rakefile +++ /dev/null @@ -1,135 +0,0 @@ -require 'rake' -require 'fileutils' -require 'socket' - -SOURCEMOD = ENV["SOURCEMOD_DIR"] -SERVER = ENV["SOURCEMOD_DEV_SERVER"] -PASSWORD = ENV["SOURCEMOD_DEV_SERVER_PASSWORD"] - -SPCOMP = ENV["SPCOMP"] || File.join(SOURCEMOD, "scripting/spcomp") - -PROJECT_ROOT = Dir.pwd -SCRIPTING = 'addons/sourcemod/scripting/' -PLUGINS = 'addons/sourcemod/plugins/' -EXTENSIONS = 'addons/sourcemod/extensions/' -TRANSLATIONS = 'addons/sourcemod/translations/' -CONFIGS = 'addons/sourcemod/configs/' -CFG = 'cfg/sourcemod/' - -task :default => [:compile, :install, :reload] - -desc "Compile project" -task :compile do - fail 'Enviornment variable "SPCOMP" not set' unless SPCOMP - - Dir.chdir File.join(PROJECT_ROOT, SCRIPTING) - Dir.glob('*.sp') do |f| - smxfile = f.gsub(/\.sp$/, ".smx") - puts %x{#{SPCOMP} #{f} -i"$PWD/include" -o"../plugins/#{smxfile}" -w203 -w204} - puts "compile #{f}" - end -end - - -desc "Copy compiled project to development server" -task :install do - #Install smx files - install_filetype '*.smx', PLUGINS - - #Install translations - install_filetype '*.phrases.txt', TRANSLATIONS - - #Install extensions if they don't exist - install_filetype '*.so', EXTENSIONS, false - - #Install default configfiles if they don't exist - install_filetype '*.cfg', CFG, false - - #Install data configfiles - install_filetype '*.cfg', CONFIGS -end - -desc "Clean up compiled files" -task :clean do - Dir.chdir File.join(PROJECT_ROOT, PLUGINS) - Dir.glob('*.smx') do |f| - FileUtils.rm(f) - puts "clean #{f}" - end -end - -desc "Remove project from development server" -task :uninstall do - fail 'Enviornment variable "SOURCEMOD_DEV_SERVER" not set' unless SERVER - - Dir.chdir File.join(PROJECT_ROOT, PLUGINS) - Dir.glob('*.smx') do |f| - FileUtils.rm(File.join(SERVER, PLUGINS, f)) - puts "uninstall #{f}" - end -end - -desc "Reload sourcemod on development server" -task :reload do - rcon_session do |server| - puts server.rcon_exec('say [SRCDS] Reloading sourcemod') - puts server.rcon_exec('sm plugins unload_all') - puts server.rcon_exec('sm plugins refresh') - puts server.rcon_exec('say [SRCDS] Reload completed') - end -end - -desc "Send an RCON command to the development server (rake rcon['sv_cheats 1'])" -task :rcon, [:cmd] do |t, args| - rcon_session do |server| - puts server.rcon_exec("#{args.cmd}") - end -end - -desc "Update project's version number (e.g. rake version[1.2.3])" -task :version, [:ver] do |t, args| - puts "hit version" - Dir.chdir File.join(PROJECT_ROOT, SCRIPTING) - Dir.glob('*.sp') do |f| - content = File.read(f) - content.gsub!(/#define PLUGIN_VERSION "[^"]*"/, %Q{#define PLUGIN_VERSION "#{args.ver}"}) - - File.open(f, "w") {|file| file.puts content} - puts "bump #{f} to version #{args.ver}" - end - -end - -def rcon_session - require 'steam-condenser' - fail 'Enviornment variable "SOURCEMOD_DEV_SERVER_PASSWORD" not set' unless PASSWORD - - local_ip = Socket::getaddrinfo(Socket.gethostname,"echo",Socket::AF_INET)[0][3] - server = SourceServer.new(local_ip) - begin - server.rcon_auth(PASSWORD) - - yield(server) - rescue RCONNoAuthError - warn 'Could not authenticate with the game server.' - rescue Errno::ECONNREFUSED - warn "Server not found" - end -end - -def install_filetype glob, subdirectory, overwrite=true - fail 'Enviornment variable "SOURCEMOD_DEV_SERVER" not set' unless SERVER - return unless File.directory?(File.join(PROJECT_ROOT, subdirectory)) - - Dir.chdir File.join(PROJECT_ROOT, subdirectory) - Dir.glob(glob) do |f| - path = File.join(SERVER, subdirectory, f) - disabled = File.join(SERVER, subdirectory, "disabled", f) - next if FileTest.exists?(disabled) - - if overwrite || !FileTest.exists?(path) - FileUtils.cp(f, path) - puts "install #{f}" - end - end -end diff --git a/addons/sourcemod/plugins/.gitkeep b/addons/sourcemod/plugins/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/addons/sourcemod/scripting/include/donator.inc b/addons/sourcemod/scripting/include/donator.inc deleted file mode 100644 index 558502e..0000000 --- a/addons/sourcemod/scripting/include/donator.inc +++ /dev/null @@ -1,106 +0,0 @@ -#if defined _donator_included_ - #endinput -#endif -#define _donator_included_ - -#define DONATOR_API_VERSON 1.1 - -functag DonatorMenuCallback DonatorMenu:public(client); - -/** - * Register a menu item. - * - * @param name Name of the menu item. - * @param func Callback for menu items. - * @return Menu item ID. - */ -native Donator_RegisterMenuItem(const String:name[], DonatorMenuCallback:callback); - -/** - * Unregister a menu item. - * - * @param name Name of the menu item. - * @param func Callback for menu items. - * @return Bool - */ -native Donator_UnregisterMenuItem(iItemId); - -/** - * Get a clients donator level, -1 if invalid - * - * @param iClient Client - * @return Donator level - */ -native GetDonatorLevel(iClient); - -/** - * Sets a clients donator level - * - * @param iClient Client - * @param iLevel Donator level - * @return Nothing - */ -native SetDonatorLevel(iClient, iLevel); - -/** - * Returns True if a client is a donator, -1 if invalid - * - * @param iClient Client - * @return bool - */ -native bool:IsPlayerDonator(iClient); - -/** - * Returns True if a steamid is a donator, -1 if invalid - * - * @param iClient Client - * @return bool - */ -native bool:FindDonatorBySteamId(const String:szSteamId[]); - -/** - * Returns a donators connect message - - * @param iClient Client - * @return Clients connect message - */ -native GetDonatorMessage(iClient, const String:szMessage[], iLength); - -/** - * Sets a donators connect message - * - * @param iClient Client - * @param szMessage Message to show on donator connect - * @return Nothing - */ -native SetDonatorMessage(iClient, const String:szMessage[]); - -/* -native SaveToDatabase(const String:szColumnName[], any:data); -native GetFromDatabase(const String:szColumnName[], any:data); -*/ - -/** - * Forwards when a donator connects. - * Note: This is before OnPostDonatorCheck - Cookies are not loaded here - * - * @param iClient Client - * @noreturn - */ -forward OnDonatorConnect(iClient); - -/** - * Forwards after OnPostAdminCheck for everyone. - * - * @param iClient Client - * @noreturn - */ -forward OnPostDonatorCheck(iClient); - -/** - * Forwards after the donators has been reladed with sm_reloaddonators. - * - * @param iClient Client - * @noreturn - */ -forward OnDonatorsChanged(); diff --git a/addons/sourcemod/scripting/include/jetpack_plus.inc b/addons/sourcemod/scripting/include/jetpack_plus.inc index b3c2705..02221c6 100644 --- a/addons/sourcemod/scripting/include/jetpack_plus.inc +++ b/addons/sourcemod/scripting/include/jetpack_plus.inc @@ -13,7 +13,7 @@ #endif #define _jetpack_plus_included_ -public SharedPlugin:__pl_jetpack_plus = +public SharedPlugin __pl_jetpack_plus = { name = "jetpack_plus", file = "jetpack_plus.smx", @@ -30,7 +30,7 @@ public SharedPlugin:__pl_jetpack_plus = * @param client The client for which this jetpack started for * @return Plugin_Handled to stop the event, Plugin_Continue to modify. */ -forward Action:OnStartJetpack(client); +forward Action OnStartJetpack(int client); /** * @brief Called right after a jetpack starts for a client @@ -38,7 +38,7 @@ forward Action:OnStartJetpack(client); * @param client The client for which this jetpack started for * @noreturn */ -forward Action:OnStartJetpackPost(client); +forward Action OnStartJetpackPost(int client); /** * @brief Called right before a jetpack stops for a client @@ -46,7 +46,7 @@ forward Action:OnStartJetpackPost(client); * @param client The client for which this jetpack stopped for * @return Plugin_Handled to stop the event, Plugin_Continue to modify. */ -forward Action:OnStopJetpack(client); +forward Action OnStopJetpack(int client); /** * @brief Called right after a jetpack stops for a client @@ -54,7 +54,7 @@ forward Action:OnStopJetpack(client); * @param client The client for which this jetpack stopped for * @return Plugin_Handled to stop the event, Plugin_Continue to modify. */ -forward Action:OnStopJetpackPost(client); +forward Action OnStopJetpackPost(int client); /** * @brief Called each frame for which a jetpack is active for a client @@ -64,14 +64,14 @@ forward Action:OnStopJetpackPost(client); * @param force_stop (byref) set to true to force the jetpack to stop * @noreturn */ -forward Action:OnJetpackStep(client, &Float:force, &bool:force_stop); +forward Action OnJetpackStep(int client, float &force, bool &force_stop); /** * @brief Check if the jetpack plugin is enabled * * @return True if enabled, False otherwise */ -native bool:AreJetpacksEnabled(); +native bool AreJetpacksEnabled(); /** * @brief Check if a client is currently using a jetpack @@ -79,4 +79,4 @@ native bool:AreJetpacksEnabled(); * @param client Client to check * @return True if using, else false */ -native bool:IsClientUsingJetpack(client); +native bool IsClientUsingJetpack(int client); diff --git a/addons/sourcemod/scripting/include/smlib.inc b/addons/sourcemod/scripting/include/smlib.inc new file mode 100644 index 0000000..e41fda5 --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib.inc @@ -0,0 +1,32 @@ +#if defined _smlib_included + #endinput +#endif +#define _smlib_included + +#define SMLIB_VERSION "0.9.7" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +//#include +#include +#include +#include +#include +#include +#include +#include diff --git a/addons/sourcemod/scripting/include/smlib/arrays.inc b/addons/sourcemod/scripting/include/smlib/arrays.inc new file mode 100644 index 0000000..9fdcfef --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/arrays.inc @@ -0,0 +1,157 @@ +#if defined _smlib_array_included + #endinput +#endif +#define _smlib_array_included + +#include + +/** + * Returns the index for the first occurance of the given value. + * If the value cannot be found, -1 will be returned. + * + * @param array Static Array. + * @param size Size of the Array. + * @param value Value to search for. + * @param start Optional: Offset where to start (0 - (size-1)). + * @return Array index, or -1 if the value couldn't be found. + */ +stock int Array_FindValue(const any[] array, int size, any value, int start=0) +{ + if (start < 0) { + start = 0; + } + + for (int i=start; i < size; i++) { + + if (array[i] == value) { + return i; + } + } + + return -1; +} + +/** + * Searchs for the first occurance of a string in the array. + * If the value cannot be located, -1 will be returned. + * + * @param array Static Array. + * @param size Size of the Array. + * @param value String to search for. + * @param start Optional: Offset where to start(0 - (size-1)). + * @return Array index, or -1 if the value couldn't be found. + */ +stock int Array_FindString(const char[][] array, int size, const char[] str, bool caseSensitive=true, int start=0) +{ + if (start < 0) { + start = 0; + } + + for (int i=start; i < size; i++) { + + if (StrEqual(array[i], str, caseSensitive)) { + return i; + } + } + + return -1; +} + +/** + * Returns the Index of the Lowest value in the array + * + * @param array Static Array. + * @param size Size of the Array. + * @param start Optional: Offset where to start (0 - (size-1)). + * @return Array index. + */ +stock int Array_FindLowestValue(const any[] array, int size, int start=0) +{ + if (start < 0) { + start = 0; + } + + any value = array[start]; + any tempValue; + int x = start; + + for (int i=start; i < size; i++) { + + tempValue = array[i]; + + if (tempValue < value) { + value = tempValue; + x = i; + } + + } + + return x; +} + +/** + * Returns the Index of the Highest value in the array + * + * @param array Static Array. + * @param size Size of the Array. + * @param start Optional: Offset where to start (0 - (size-1)). + * @return Array index. + */ +stock int Array_FindHighestValue(const any[] array, int size, int start=0) +{ + if (start < 0) { + start = 0; + } + + any value = array[start]; + any tempValue; + int x = start; + + for (int i=start; i < size; i++) { + + tempValue = array[i]; + + if (tempValue > value) { + value = tempValue; + x = i; + } + + } + + return x; +} + +/** + * Fills an array with a given value in a 1 dimensional static array. + * You can specify the amount of cells to be written. + * + * @param array Static Array. + * @param size Number of cells to write (eg. the array's size) + * @param value Fill value. + * @param start Optional: Offset where to start (0 - (size-1)). + */ +stock void Array_Fill(any[] array, int size, any value, int start=0) +{ + if (start < 0) { + start = 0; + } + + for (int i=start; i < size; i++) { + array[i] = value; + } +} + +/** + * Copies a 1 dimensional static array. + * + * @param array Static Array to copy from. + * @param newArray New Array to copy to. + * @param size Size of the array (or number of cells to copy) + * @noreturn + */ +stock void Array_Copy(const any[] array, any[] newArray, int size) +{ + for (int i=0; i < size; i++) { + newArray[i] = array[i]; + } +} diff --git a/addons/sourcemod/scripting/include/smlib/clients.inc b/addons/sourcemod/scripting/include/smlib/clients.inc new file mode 100644 index 0000000..8248c1a --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/clients.inc @@ -0,0 +1,3077 @@ +#if defined _smlib_client_included + #endinput +#endif +#define _smlib_client_included + +// Defined here beacause needed in teams.inc +#define CLIENTFILTER_ALL 0 // No filtering +#define CLIENTFILTER_BOTS ( 1 << 1 ) // Fake clients +#define CLIENTFILTER_NOBOTS ( 1 << 2 ) // No fake clients +#define CLIENTFILTER_AUTHORIZED ( 1 << 3 ) // SteamID validated +#define CLIENTFILTER_NOTAUTHORIZED ( 1 << 4 ) // SteamID not validated (yet) +#define CLIENTFILTER_ADMINS ( 1 << 5 ) // Generic Admins (or higher) +#define CLIENTFILTER_NOADMINS ( 1 << 6 ) // No generic admins +// All flags below require ingame checking (optimization) +#define CLIENTFILTER_INGAME ( 1 << 7 ) // Ingame +#define CLIENTFILTER_INGAMEAUTH ( 1 << 8 ) // Ingame & Authorized +#define CLIENTFILTER_NOTINGAME ( 1 << 9 ) // Not ingame (currently connecting) +#define CLIENTFILTER_ALIVE ( 1 << 10 ) // Alive +#define CLIENTFILTER_DEAD ( 1 << 11 ) // Dead +#define CLIENTFILTER_SPECTATORS ( 1 << 12 ) // Spectators +#define CLIENTFILTER_NOSPECTATORS ( 1 << 13 ) // No Spectators +#define CLIENTFILTER_OBSERVERS ( 1 << 14 ) // Observers +#define CLIENTFILTER_NOOBSERVERS ( 1 << 15 ) // No Observers +#define CLIENTFILTER_TEAMONE ( 1 << 16 ) // First Team (Terrorists, ...) +#define CLIENTFILTER_TEAMTWO ( 1 << 17 ) // Second Team (Counter-Terrorists, ...) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/** + * Very useful macro to iterate all clients + * matching the specified flags. + * + * @param 1 Name of the client index variable (will be only valid in the loop). + * @param 2 CLIENTFILTER_ flags to check. + */ +#define LOOP_CLIENTS(%1,%2) for (int %1=Client_GetNext(%2); %1 >= 1 && %1 <= MaxClients; %1=Client_GetNext(%2, ++%1)) + +/** + * Macro for iterating trough all observers of a player. + * + * @param 1 Client Index for who to get the observers. + * @param 2 Name of the observer client index variable (will be only valid in the loop). + * @param 3 CLIENTFILTER_ flags to check. + */ +#define LOOP_OBSERVERS(%1,%2,%3) for (int %2=Client_GetNextObserver(%1, 1, %3); %2 >= 1 && %2 <= MaxClients; %2=Client_GetNextObserver(%1, ++%2, %3)) + +/** + * Very useful macro to iterate all weapons of a client. + * + * @param 1 Client Index + * @param 2 Name of the weapon index variable (will be only valid in the loop). + * @param 3 Name of the client's weapon index variable (will be only valid in the loop). + */ +#define LOOP_CLIENTWEAPONS(%1,%2,%3) for (int %3, %2=Client_GetNextWeapon(%1, %3); %2 != -1; %2=Client_GetNextWeapon(%1, %3)) + +// Hud Element hiding flags (possibly outdated) +#define HIDEHUD_WEAPONSELECTION ( 1<<0 ) // Hide ammo count & weapon selection +#define HIDEHUD_FLASHLIGHT ( 1<<1 ) +#define HIDEHUD_ALL ( 1<<2 ) +#define HIDEHUD_HEALTH ( 1<<3 ) // Hide health & armor / suit battery +#define HIDEHUD_PLAYERDEAD ( 1<<4 ) // Hide when local player's dead +#define HIDEHUD_NEEDSUIT ( 1<<5 ) // Hide when the local player doesn't have the HEV suit +#define HIDEHUD_MISCSTATUS ( 1<<6 ) // Hide miscellaneous status elements (trains, pickup history, death notices, etc) +#define HIDEHUD_CHAT ( 1<<7 ) // Hide all communication elements (saytext, voice icon, etc) +#define HIDEHUD_CROSSHAIR ( 1<<8 ) // Hide crosshairs +#define HIDEHUD_VEHICLE_CROSSHAIR ( 1<<9 ) // Hide vehicle crosshair +#define HIDEHUD_INVEHICLE ( 1<<10 ) +#define HIDEHUD_BONUS_PROGRESS ( 1<<11 ) // Hide bonus progress display (for bonus map challenges) + +/** +* Sets the Hide-Hud flags of a client +* +* @param client Client index. +* @param flags Flag to set, use one of the HIDEHUD_ hiding constants +*/ +stock void Client_SetHideHud(int client, int flags) +{ + SetEntProp(client, Prop_Send, "m_iHideHUD", flags); +} + +/** +* Checks if the specified index is a player and connected. +* +* @param entity An entity index. +* @param checkConnected Set to false to skip the IsClientConnected check +* @return Returns true if the specified entity index is a player connected, false otherwise. +*/ +stock bool Client_IsValid(int client, bool checkConnected=true) +{ + if (client > 4096) { + client = EntRefToEntIndex(client); + } + + if (client < 1 || client > MaxClients) { + return false; + } + + if (checkConnected && !IsClientConnected(client)) { + return false; + } + + return true; +} + +/** +* Checks if the specified index is a player and ingame. +* +* @param entity An entity index. +* @return Returns true if the specified index is a player and ingame, false otherwise. +*/ +stock bool Client_IsIngame(int client) +{ + if (!Client_IsValid(client, false)) { + return false; + } + + return IsClientInGame(client); +} + +/** +* Checks if the specified index is a player, ingame and authorized. +* +* @param entity An entity index. +* @return Returns true if the specified index is a player, ingame and authed, false otherwise. +*/ +stock bool Client_IsIngameAuthorized(int client) +{ + if (!Client_IsIngame(client)) { + return false; + } + + return IsClientAuthorized(client); +} + +#define MAX_STEAMAUTH_LENGTH 21 + +/** +* Finds a player by his SteamID +* +* @param auth SteamID to search for +* @return Client Index or -1 +*/ +stock int Client_FindBySteamId(const char[] auth) +{ + char clientAuth[MAX_STEAMAUTH_LENGTH]; + for (int client=1; client <= MaxClients; client++) { + if (!IsClientAuthorized(client)) { + continue; + } + + GetClientAuthId(client, AuthId_Steam2, clientAuth, sizeof(clientAuth)); + + if (StrEqual(auth, clientAuth)) { + return client; + } + } + + return -1; +} + +/** +* Finds a player by his name. +* Only returns the first matching player. +* +* @param name Name to search for. +* @param partOfName Whether to search for the part of a name or compare the full name. +* @param caseSensitive If true, comparison is case sensitive. If false (default), comparison is case insensitive. +* @return Client Index or -1 +*/ +stock int Client_FindByName(const char[] name, bool partOfName=true, bool caseSensitive=false) +{ + char clientName[MAX_NAME_LENGTH]; + for (int client=1; client <= MaxClients; client++) { + if (!IsClientAuthorized(client)) { + continue; + } + + GetClientName(client, clientName, sizeof(clientName)); + + if (partOfName) { + if (StrContains(clientName, name, caseSensitive) != -1) { + return client; + } + } + else if (StrEqual(name, clientName, caseSensitive)) { + return client; + } + } + + return -1; +} + +// Spectator Movement modes +enum Obs_Mode +{ + OBS_MODE_NONE = 0, // not in spectator mode + OBS_MODE_DEATHCAM, // special mode for death cam animation + OBS_MODE_FREEZECAM, // zooms to a target, and freeze-frames on them + OBS_MODE_FIXED, // view from a fixed camera position + OBS_MODE_IN_EYE, // follow a player in first person view + OBS_MODE_CHASE, // follow a player in third person view + OBS_MODE_ROAMING, // free roaming + + NUM_OBSERVER_MODES +}; + +// Force Camera Restrictions with mp_forcecamera +enum Obs_Allow +{ + OBS_ALLOW_ALL = 0, // allow all modes, all targets + OBS_ALLOW_TEAM, // allow only own team & first person, no PIP + OBS_ALLOW_NONE, // don't allow any spectating after death (fixed & fade to black) + + OBS_ALLOW_NUM_MODES, +}; + +/** + * Gets the client's observer mode (Obs_Mode). + * + * @param client Client Index. + * @return The current observer mode (ObsMode). + */ +stock Obs_Mode Client_GetObserverMode(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_iObserverMode")); +} + + +/** + * Sets the client's observer mode. + * Use a value of the Obs_Mode enum. + * This is a rewrite of CBasePlayer::SetObserverMode(). + * + * @param client Client Index. + * @param mode New Observer mode value (Obs_Mode). + * @param updateMoveType Set to true (default) to allow this function updating the movetype, false otherwise. + */ +stock void Client_SetObserverMode(int client, Obs_Mode mode, bool updateMoveType=true) +{ + if (mode < OBS_MODE_NONE || mode >= NUM_OBSERVER_MODES) { + return; + } + + // check mp_forcecamera settings for dead players + if (mode > OBS_MODE_FIXED && GetClientTeam(client) > TEAM_SPECTATOR) + { + ConVar mp_forcecamera = FindConVar("mp_forcecamera"); + + if (mp_forcecamera != INVALID_HANDLE) { + switch (mp_forcecamera.IntValue) + { + case OBS_ALLOW_TEAM: { + mode = OBS_MODE_IN_EYE; + } + case OBS_ALLOW_NONE: { + mode = OBS_MODE_FIXED; // don't allow anything + } + } + } + } + + Obs_Mode observerMode = Client_GetObserverMode(client); + if (observerMode > OBS_MODE_DEATHCAM) { + // remember mode if we were really spectating before + Client_SetObserverLastMode(client, observerMode); + } + + SetEntProp(client, Prop_Send, "m_iObserverMode", mode); + + switch (mode) { + case OBS_MODE_NONE, OBS_MODE_FIXED, OBS_MODE_DEATHCAM: { + Client_SetFOV(client, 0); // Reset FOV + + if (updateMoveType) { + SetEntityMoveType(client, MOVETYPE_NONE); + } + } + case OBS_MODE_CHASE, OBS_MODE_IN_EYE: { + // udpate FOV and viewmodels + Client_SetViewOffset(client, NULL_VECTOR); + + if (updateMoveType) { + SetEntityMoveType(client, MOVETYPE_OBSERVER); + } + } + case OBS_MODE_ROAMING: { + Client_SetFOV(client, 0); // Reset FOV + Client_SetViewOffset(client, NULL_VECTOR); + + if (updateMoveType) { + SetEntityMoveType(client, MOVETYPE_OBSERVER); + } + } + } +} + +/** + * Gets the client's last oberserver mode + * + * @param client Client Index. + * @return Last Observer mode + */ +stock Obs_Mode Client_GetObserverLastMode(int client) +{ + return view_as(GetEntProp(client, Prop_Data, "m_iObserverLastMode")); +} + +/** + * Sets the client's last oberserver mode + * + * @param client Client Index. + * @param mode Last Observer mode + */ +stock void Client_SetObserverLastMode(int client, Obs_Mode mode) +{ + SetEntProp(client, Prop_Data, "m_iObserverLastMode", mode); +} + +/** + * Gets the client's view offset. + * This is the position relative to the client itself. + * + * @param client Client Index. + * @param vec Vector Buffer. + */ +stock void Client_GetViewOffset(int client, float vec[3]) +{ + GetEntPropVector(client, Prop_Data, "m_vecViewOffset", vec); +} + +/** + * Sets the client's view offset. + * This is the position relative to the client itself. + * + * @param client Client Index. + * @param vec Vector buffer. + * @noreturn + */ +stock void Client_SetViewOffset(int client, float vec[3]) +{ + SetEntPropVector(client, Prop_Data, "m_vecViewOffset", vec); +} + +/** + * Gets the client's current observer target entity. + * + * @param client Client Index. + * @return Observed Entity Index. + */ +stock int Client_GetObserverTarget(int client) +{ + return GetEntPropEnt(client, Prop_Send, "m_hObserverTarget"); +} + +/** + * Sets the client's current observer target entity. + * + * @param client Client Index. + * @param entity Observed Entity Index. + * @param resetFOV If to reset the client's field of view. + */ +stock void Client_SetObserverTarget(int client, int entity, bool resetFOV=true) +{ + SetEntPropEnt(client, Prop_Send, "m_hObserverTarget", entity); + + if (resetFOV) { + Client_SetFOV(client, 0); + } +} + +/** + * Gets the client's Field Of View. + * + * @param client Client Index. + * @return Field Of View + */ +stock int Client_GetFOV(int client) +{ + return GetEntProp(client, Prop_Send, "m_iFOV"); +} + +/** + * Sets the client's Field Of View. + * + * @param client Client Index. + * @param value Field Of View + */ +stock void Client_SetFOV(int client, int value) +{ + SetEntProp(client, Prop_Send, "m_iFOV", value); +} + +/** + * Checks if the client's View Model is drawn for the client. + * + * @param client Client Index. + * @return True if the viewmodel is drawn, false otherwise. + */ +stock bool Client_DrawViewModel(int client) +{ + return GetEntProp(client, Prop_Send, "m_bDrawViewmodel") != 0; +} + +/** + * Sets if to draw the client's view model for the client. + * + * @param client Client Index. + * @param drawViewModel Set to true if to draw, false otherwise. + */ +stock void Client_SetDrawViewModel(int client, bool drawViewModel) +{ + SetEntProp(client, Prop_Send, "m_bDrawViewmodel", drawViewModel); +} + +/** + * Puts the specified client into thirdperson or back to firstperson when false + * This doesn't work correctly in all games, it works in CS:S and DOD:S and some other games. + * Todo: Enhance this + * + * @param client Client Index. + * @param enable If set to true, the client will be put into thirdperson mode, + * if false the client will be put in firstperson mode. + */ +stock void Client_SetThirdPersonMode(int client, bool enable=true) +{ + if (enable) { + Client_SetObserverTarget(client, 0); + Client_SetObserverMode(client, OBS_MODE_DEATHCAM, false); + Client_SetDrawViewModel(client, false); + Client_SetFOV(client, 120); + } + else { + Client_SetObserverTarget(client, -1); + Client_SetObserverMode(client, OBS_MODE_NONE, false); + Client_SetDrawViewModel(client, true); + Client_SetFOV(client, 90); + } +} + +/** + * Checks if the client is in thirdperson mode + * + * @param client Cient Undex + * @return true if the client is currently in thirdperson mode, false otherwise + */ +stock bool Client_IsInThirdPersonMode(int client) +{ + // FIXME: Is this enough? + return Client_GetObserverMode(client) == OBS_MODE_DEATHCAM; +} + +#define FFADE_IN 0x0001 // Just here so we don't pass 0 into the function +#define FFADE_OUT 0x0002 // Fade out (not in) +#define FFADE_MODULATE 0x0004 // Modulate (don't blend) +#define FFADE_STAYOUT 0x0008 // ignores the duration, stays faded out until new ScreenFade message received +#define FFADE_PURGE 0x0010 // Purges all other fades, replacing them with this one + +/** + * Fades a client's screen to a specified color + * Your adviced to read the FFADE_ Comments + * + * @param client Player for which to fade the screen + * @param duration duration in seconds the effect stays + * @param mode fade mode, see FFADE_ defines + * @param holdtime holdtime in seconds + * @param r red amount + * @param g green amount + * @param b blue amount + * @param a transparency + * @return True on success, false otherwise + */ +stock bool Client_ScreenFade(int client, int duration, int mode, int holdtime=-1, int r=0, int g=0, int b=0, int a=255, bool reliable=true) +{ + Handle userMessage = StartMessageOne("Fade", client, (reliable?USERMSG_RELIABLE:0)); + + if (userMessage == INVALID_HANDLE) { + return false; + } + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && + GetUserMessageType() == UM_Protobuf) { + + int color[4]; + color[0] = r; + color[1] = g; + color[2] = b; + color[3] = a; + + PbSetInt(userMessage, "duration", duration); + PbSetInt(userMessage, "hold_time", holdtime); + PbSetInt(userMessage, "flags", mode); + PbSetColor(userMessage, "clr", color); + } + else { + BfWriteShort(userMessage, duration); // Fade duration + BfWriteShort(userMessage, holdtime); // Fade hold time + BfWriteShort(userMessage, mode); // What to do + BfWriteByte(userMessage, r); // Color R + BfWriteByte(userMessage, g); // Color G + BfWriteByte(userMessage, b); // Color B + BfWriteByte(userMessage, a); // Color Alpha + } + EndMessage(); + + return true; +} + +/** + * This function retrieves an array that holds all clones of a client by IP check. + * Size of CloneList has to be MaxClients at least, or MAX_PLAYERS + * + * @param client Client index. + * @param closelist An array that holds all clones of a client. + * @return Returns how many clones a client has. + */ +stock int Client_GetClones(int client, int[] cloneList) +{ + int x=0; + char ip_client[16], ip_player[16]; + + GetClientIP(client, ip_client, sizeof(client)); + + for (int player=1; player <= MaxClients; player++) { + + if (IsClientInGame(player)) { + GetClientIP(player, ip_player, sizeof(ip_player)); + + if (StrEqual(ip_client, ip_player, false)) { + cloneList[x++] = player; + } + } + } + + return x; +} + +/* + * This function returns true if the client is at a ladder.. + * + * @param client Client index. + * @return Returns true if the client is on a ladder other wise false. + */ +stock bool Client_IsOnLadder(int client) +{ + MoveType movetype = GetEntityMoveType(client); + + if (movetype == MOVETYPE_LADDER) { + return true; + } + else{ + return false; + } +} + +enum Water_Level +{ + WATER_LEVEL_NOT_IN_WATER = 0, + WATER_LEVEL_FEET_IN_WATER, + WATER_LEVEL_WAIST_IN_WATER, + WATER_LEVEL_HEAD_IN_WATER +}; + +/* + * This function returns how deep a client is in water. + * + * @param client Client index. + * @return Returns 0 if not in water. 1 if feets are in water. 2 if waist is in water. 3 if head is in water. + */ +stock Water_Level Client_GetWaterLevel(int client) +{ + return view_as(GetEntProp(client, Prop_Send, "m_nWaterLevel")); +} + +/* + * Returns how much suit sprint power a client has left in percent. + * + * @param client Client index. + * @return returns the actual power left in percent. + */ +stock float Client_GetSuitSprintPower(int client) +{ + return GetEntPropFloat(client, Prop_Send, "m_flSuitPower"); +} + +/* + * Sets a client suit sprint power in percent. + * + * @param client Client index. + * @param power power (0.0 to 100.0) + */ +stock void Client_SetSuitSprintPower(int client, float power) +{ + SetEntPropFloat(client, Prop_Send, "m_flSuitPower", power); +} + +/* + * Returns the client count put in the server. + * + * @param inGameOnly If false connecting players are also counted. + * @param countBots If true bots will be counted too. + * @return Client count in the server. + */ +stock int Client_GetCount(bool countInGameOnly=true, bool countFakeClients=true) +{ + int numClients = 0; + + for (int client=1; client <= MaxClients; client++) { + + if (!IsClientConnected(client)) { + continue; + } + + if (countInGameOnly && !IsClientInGame(client)) { + continue; + } + + if (!countFakeClients && IsFakeClient(client)) { + continue; + } + + numClients++; + } + + return numClients; +} + +/* + * Returns the ping of a client like it is displayed in the scoreboard. + * The weird calculation formula is taken from Valve's SDK + * hl2sdk\game\server\util.cpp: UTIL_GetPlayerConnectionInfo() + * The Scoreboard uses the goldSource corrected Ping, the net_graph doesn't + * For Fake Clients 0 is returned. + * + * @param client Client index + * @param goldSource If true, get the ping as displayed in the player's scoreboard, false returns the net_graph variant. + * @return Client's fake ping or 0 for fake clients + */ +stock int Client_GetFakePing(int client, bool goldSource=true) +{ + if (IsFakeClient(client)) { + return 0; + } + + int ping; + float latency = GetClientLatency(client, NetFlow_Outgoing); // in seconds + + // that should be the correct latency, we assume that cmdrate is higher + // then updaterate, what is the case for default settings + char cl_cmdrate[4]; + GetClientInfo(client, "cl_cmdrate", cl_cmdrate, sizeof(cl_cmdrate)); + + float tickRate = GetTickInterval(); + latency -= (0.5 / StringToInt(cl_cmdrate)) + TICKS_TO_TIME(1.0); // correct latency + + if (goldSource) { + // in GoldSrc we had a different, not fixed tickrate. so we have to adjust + // Source pings by half a tick to match the old GoldSrc pings. + latency -= tickRate * 0.5; + } + + ping = RoundFloat(latency * 1000.0); // as msecs + ping = Math_Clamp(ping, 5, 1000); // set bounds, dont show pings under 5 msecs + + return ping; +} + +/** + * Searches for the closest client in relation to the given client. + * + * @param client Client index + * @return The closest client or -1 + */ +stock int Client_GetClosestToClient(int client) +{ + return Edict_GetClosestToEdict(client, true); +} + +/** + * Gets the name of the last place (if set by the game) + * + * @param entity Entity index. + * @param buffer String buffer + * @param size Size of the String buffer + */ +stock void Client_GetLastPlaceName(int client, char[] buffer, int size) +{ + GetEntPropString(client, Prop_Send, "m_szLastPlaceName", buffer, size); +} + +/** + * Returns the client's Score. + * + * @param client Client's index. + * @return Score. + */ +stock int Client_GetScore(int client) +{ + return GetClientFrags(client); +} + +/** + * Sets the client's Score. + * + * @param client Client's index. + * @param value Score. + * @noreturn + */ +stock int Client_SetScore(int client, int value) +{ + SetEntProp(client, Prop_Data, "m_iFrags", value); +} + +/** + * Returns the client's Death count + * + * @param client Client's index. + * @return Death count + */ +stock int Client_GetDeaths(int client) +{ + return GetEntProp(client, Prop_Data, "m_iDeaths"); +} + +/** + * Sets the client's Death count. + * + * @param client Client's index. + * @param value Death count + */ +stock void Client_SetDeaths(int client, int value) +{ + SetEntProp(client, Prop_Data, "m_iDeaths", value); +} + +/** + * Returns the client's Armor + * + * @param client Client's index. + * @return Armor value + */ +stock int Client_GetArmor(int client) +{ + return GetEntProp(client, Prop_Data, "m_ArmorValue"); +} + +/** + * Sets the client's Armor. + * + * @param client Client's index. + * @param value Armor value + */ +stock void Client_SetArmor(int client, int value) +{ + SetEntProp(client, Prop_Data, "m_ArmorValue", value); +} + +/** + * Returns the client's Suitpower + * + * @param client Client's index. + * @return Suitpower + */ +stock float Client_GetSuitPower(int client) +{ + return GetEntPropFloat(client, Prop_Data, "m_flSuitPower"); +} + +/** + * Sets the client's Suitpower + * + * @param client Client's index. + * @param value Suitpower + */ +stock void Client_SetSuitPower(int client, float value) +{ + SetEntPropFloat(client, Prop_Data, "m_flSuitPower", value); +} + +// suit usage bits +#define bits_SUIT_DEVICE_SPRINT 0x00000001 +#define bits_SUIT_DEVICE_FLASHLIGHT 0x00000002 +#define bits_SUIT_DEVICE_BREATHER 0x00000004 +#define MAX_SUIT_DEVICES 3 + +/** + * Returns the client's active devices (Max MAX_SUIT_DEVICES) + * The return is a bitwise value with bits_SUIT_DEVICE_SPRINT, + * bits_SUIT_DEVICE_FLASHLIGHT and/or bits_SUIT_DEVICE_BREATHER set. + * + * @param client Client's index. + * @return The active devices (bitwise value) + */ +stock int Client_GetActiveDevices(int client) +{ + return GetEntProp(client, Prop_Send, "m_bitsActiveDevices"); +} + +/** + * Returns the time when the client is allowed to spray + * a decal again. + * + * @param client Client's index. + * @return Next decal time + */ +stock float Client_GetNextDecalTime(int client) +{ + return GetEntPropFloat(client, Prop_Data, "m_flNextDecalTime"); +} + +/** + * Returns whether the client is allowed to spray a decal or not. + * + * @param client Client's index. + * @return True if he is allowed to spray a decal, false otherwise + */ +stock bool Client_CanSprayDecal(int client) +{ + return Client_GetNextDecalTime(client) <= GetGameTime(); +} + +/** + * Returns the vehicle the client is in, if the client + * isn't in a vehicle, -1 is returned. + * + * @param client Client's index. + * @return Vehicle index, -1 if the client isn't in a vehicle. + */ +stock int Client_GetVehicle(int client) +{ + int m_hVehicle = GetEntPropEnt(client, Prop_Send, "m_hVehicle"); + + return m_hVehicle; +} + +/** + * Returns whether the client is in a vehicle or not. + * + * @param client Client's index. + * @return True if he is in a vehicle, false otherwise + */ +stock bool Client_IsInVehicle(int client) +{ + return (Client_GetVehicle(client) != -1); +} + +/** + * Removes all decals for a client + * + * @param client Client's index. + */ +stock void Client_RemoveAllDecals(int client) +{ + ClientCommand(client, "r_cleardecals"); +} + +/** + * Let's the client exit the vehicle + * + * @param vehicle Client index. + * @return True on success, false otherwise. + */ +stock bool Client_ExitVehicle(int client) +{ + int vehicle = Client_GetVehicle(client); + + if (vehicle == -1) { + return false; + } + + return AcceptEntityInput(vehicle, "ExitVehicle"); +} + +/** + * Plays a soundfile as if the player is using voicecomm for a single client. + * The voiceindicator is shown on the right, as if the players is talking. + * Thanks to Peace-Maker for the function. + * + * @param client For whom to play the sound. + * @param emitter Player/Entity the voice stream comes from. + * @param soundfile Path to the soundfile relative to the sound folder. + * @param length Length in seconds how long the hud "voiceindicator" is shown. + * @param pitch The pitch of the audiofile. + * @return True on success, false on failure. + */ +stock bool Client_RawAudio(int client, int emitter, const char[] soundfile, float length = 0.0, int pitch = 100) +{ + Handle message = StartMessageOne("RawAudio", client); + + if (message == INVALID_HANDLE) { + return false; + } + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbSetInt(message, "pitch", pitch); + PbSetInt(message, "entidx", emitter); + PbSetFloat(message, "duration", length ); + PbSetString(message, "voice_filename", soundfile); + } + else { + BfWriteByte(message, pitch); + BfWriteByte(message, emitter); + BfWriteFloat(message, length); + BfWriteString(message, soundfile); + } + EndMessage(); + + return true; +} + +/** + * Plays a soundfile as if the player is using voicecomm for all players. + * The voiceindicator is shown on the right, as if the players is talking. + * Thanks to Peace-Maker for the function. + * + * @param emitter Player/Entity the voice stream comes from. + * @param soundfile Path to the soundfile relative to the sound folder. + * @param length Length in seconds how long the hud "voiceindicator" is shown. + * @param pitch The pitch of the audiofile. + * @return True on success, false on failure. + */ +stock bool Client_RawAudioToAll(int emitter, const char[] soundfile, float length = 0.0, int pitch = 100) +{ + Handle message = StartMessageAll("RawAudio"); + + if (message == INVALID_HANDLE) { + return false; + } + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbSetInt(message, "pitch", pitch); + PbSetInt(message, "entidx", emitter); + PbSetFloat(message, "duration", length); + PbSetString(message, "voice_filename", soundfile); + } + else { + BfWriteByte(message, pitch); + BfWriteByte(message, emitter); + BfWriteFloat(message, length); + BfWriteString(message, soundfile); + } + EndMessage(); + + return true; +} + +/** + * Sets an Impulse value for a client (eg: "impulse 100" for flashlight, value would be 100). + * See: http://developer.valvesoftware.com/wiki/Impulse + * + * @param client Client Index + * @param value The impulse command value. + * @return True on success, false on failure. + */ +stock void Client_Impulse(int client, int value) +{ + SetEntProp(client, Prop_Data, "m_nImpulse", value); +} + +/** + * Gets the offset for a client's weapon list (m_hMyWeapons). + * The offset will saved globally for optimization. + * + * @param client Client Index. + * @return Weapon list offset or -1 on failure. + */ +stock int Client_GetWeaponsOffset(int client) +{ + static int offset = -1; + + if (offset == -1) { + offset = FindDataMapInfo(client, "m_hMyWeapons"); + } + + return offset; +} + +/** + * Gets the current/active weapon of a client + * + * @param client Client Index. + * @return Weapon Index or INVALID_ENT_REFERENCE if the client has no active weapon. + */ +stock int Client_GetActiveWeapon(int client) +{ + int weapon = GetEntPropEnt(client, Prop_Data, "m_hActiveWeapon"); + + if (!Entity_IsValid(weapon)) { + return INVALID_ENT_REFERENCE; + } + + return weapon; +} + +/** + * Gets the classname and entity index of the current/active weapon of a client. + * + * @param client Client Index. + * @param buffer String Buffer to store the weapon's classname. + * @param size Max size of String: buffer. + * @return Weapon Entity Index on success or INVALID_ENT_REFERENCE otherwise + */ +stock int Client_GetActiveWeaponName(int client, char[] buffer, int size) +{ + int weapon = Client_GetActiveWeapon(client); + + if (weapon == INVALID_ENT_REFERENCE) { + buffer[0] = '\0'; + return INVALID_ENT_REFERENCE; + } + + Entity_GetClassName(weapon, buffer, size); + + return weapon; +} + +/** + * Changes the active/current weapon of a player by Index. + * Note: No changing animation will be played ! + * + * @param client Client Index. + * @param weapon Index of a valid weapon. + */ +stock void Client_SetActiveWeapon(int client, int weapon) +{ + SetEntPropEnt(client, Prop_Data, "m_hActiveWeapon", weapon); + ChangeEdictState(client, FindDataMapInfo(client, "m_hActiveWeapon")); +} + +/** + * Changes the active weapon the client is holding. + * Note: No changing animation will be played ! + * + * @param client Client Index. + * @param className Weapon Classname. + * @return True on success, false on failure. + */ +stock bool Client_ChangeWeapon(int client, const char[] className) +{ + int weapon = Client_GetWeapon(client, className); + + if (weapon == INVALID_ENT_REFERENCE) { + return false; + } + + Client_SetActiveWeapon(client,weapon); + + return true; +} + +/** + * Changes the active weapon to the last. + * If the last active weapon can't be found, the default weapon is taken. + * If the default weapon can't be found, the first weapon in the list is taken. + * If the first weapon can't be found, INVALID_ENT_REFERENCEE is returned. + * + * @param client Client Index. + * @return Entity Index or, INVALID_ENT_REFERENCE. + */ +stock int Client_ChangeToLastWeapon(int client) +{ + int weapon = Client_GetLastActiveWeapon(client); + + if (weapon == INVALID_ENT_REFERENCE) { + weapon = Client_GetDefaultWeapon(client); + + if (weapon == INVALID_ENT_REFERENCE) { + weapon = Client_GetFirstWeapon(client); + + if (weapon == INVALID_ENT_REFERENCE) { + return INVALID_ENT_REFERENCE; + } + } + } + + Client_SetActiveWeapon(client, weapon); + + return weapon; +} + +/** + * Gets the last active weapon of a client. + * + * @param client Client Index. + * @return Entity Index of the weapon on success, INVALID_ENT_REFERENCE on failure. + */ +stock int Client_GetLastActiveWeapon(int client) +{ + int weapon = GetEntPropEnt(client, Prop_Data, "m_hLastWeapon"); + + if (!Entity_IsValid(weapon)) { + return INVALID_ENT_REFERENCE; + } + + return weapon; +} + +/** + * Gets the classname of the last active weapon of a client. + * + * @param client Client Index. + * @param buffer Buffer to store the weapon classname. + * @param size Max size of String: buffer. + * @return Weapon Entity Index on success or INVALID_ENT_REFERENCE otherwise + */ +stock int Client_GetLastActiveWeaponName(int client, char[] buffer, int size) +{ + int weapon = Client_GetLastActiveWeapon(client); + + if (weapon == INVALID_ENT_REFERENCE) { + buffer[0] = '\0'; + return INVALID_ENT_REFERENCE; + } + + Entity_GetClassName(weapon, buffer, size); + + return weapon; +} + +/** + * Sets the last active weapon of a client. + * + * @param client Client Index. + * @param weapon Entity Index of a weapon. + * @noreturn + */ +stock void Client_SetLastActiveWeapon(int client, int weapon) +{ + SetEntPropEnt(client, Prop_Data, "m_hLastWeapon", weapon); + ChangeEdictState(client, FindDataMapInfo(client, "m_hLastWeapon")); +} + +/** + * Equips (attaches) a weapon to a client. + * + * @param client Client Index. + * @param weapon Entity Index of the weapon. + * @param switchTo If true, the client will switch to that weapon (make it active). + */ +stock void Client_EquipWeapon(int client, int weapon, bool switchTo=false) +{ + EquipPlayerWeapon(client, weapon); + + if (switchTo) { + Client_SetActiveWeapon(client, weapon); + } +} + +/** + * Savly detaches a clients weapon, to remove it as example. + * The client will select his last weapon when detached. + * + * @param client Client Index. + * @param weapon Entity Index of the weapon, you'd like to detach. + * @return True on success, false otherwise. + */ +stock bool Client_DetachWeapon(int client, int weapon) +{ + if (!RemovePlayerItem(client, weapon)) { + return false; + } + + if (Client_GetActiveWeapon(client) == INVALID_ENT_REFERENCE) { + Client_ChangeToLastWeapon(client); + } + + return true; +} + +/** + * Gives a client a weapon. + * + * @param client Client Index. + * @param className Weapon Classname String. + * @param switchTo If set to true, the client will switch the active weapon to the new weapon. + * @return Entity Index of the given weapon on success, INVALID_ENT_REFERENCE on failure. + */ +stock int Client_GiveWeapon(int client, const char[] className, bool switchTo=true) +{ + int weapon = Client_GetWeapon(client, className); + + if (weapon == INVALID_ENT_REFERENCE) { + weapon = Weapon_CreateForOwner(client, className); + + if (weapon == INVALID_ENT_REFERENCE) { + return INVALID_ENT_REFERENCE; + } + } + + Client_EquipWeapon(client, weapon, switchTo); + + return weapon; +} + +/** + * Gives a client a weapon and ammo for that weapon. + * + * @param client Client Index. + * @param className Weapon Classname String. + * @param switchTo If set to true, the client will switch the active weapon to the new weapon. + * @param primaryAmmo Primary ammo stock value from the client, if -1 the value is untouched. + * @param secondaryAmmo Secondary ammo stock value from the client, if -1 the value is untouched. + * @param primaryClip Primary ammo value in the weapon clip, if -1 the value is untouched. + * @param secondaryClip Secondary ammo value in the weapon clip, if -1 the value is untouched. + * @return Entity Index of the given weapon on success, INVALID_ENT_REFERENCE on failure. + */ +stock int Client_GiveWeaponAndAmmo(int client, const char[] className, bool switchTo=true, int primaryAmmo=-1, int secondaryAmmo=-1, int primaryClip=-1, int secondaryClip=-1) +{ + int weapon = Client_GiveWeapon(client, className, switchTo); + + if (weapon == INVALID_ENT_REFERENCE) { + return INVALID_ENT_REFERENCE; + } + + if (primaryClip != -1) { + Weapon_SetPrimaryClip(weapon, primaryClip); + } + + if (secondaryClip != -1) { + Weapon_SetSecondaryClip(weapon, secondaryClip); + } + + Client_SetWeaponPlayerAmmoEx(client, weapon, primaryAmmo, secondaryAmmo); + + return weapon; +} + +/** + * Removes a weapon from a client. + * + * @param client Client Index. + * @param className Weapon Classname String. + * @param firstOnly If false it loops trough the whole weapon list and deletes all weapons that match the specified classname. + * @param clearAmmo If true, the ammo the client carries for that weapon will be set to 0 (primary and secondary). + * @return True on success, false otherwise. + */ +stock bool Client_RemoveWeapon(int client, const char[] className, bool firstOnly=true, bool clearAmmo=false) +{ + int offset = Client_GetWeaponsOffset(client) - 4; + + for (int i=0; i < MAX_WEAPONS; i++) { + offset += 4; + + int weapon = GetEntDataEnt2(client, offset); + + if (!Weapon_IsValid(weapon)) { + continue; + } + + if (!Entity_ClassNameMatches(weapon, className)) { + continue; + } + + if (clearAmmo) { + Client_SetWeaponPlayerAmmoEx(client, weapon, 0, 0); + } + + if (Client_GetActiveWeapon(client) == weapon) { + Client_ChangeToLastWeapon(client); + } + + if (RemovePlayerItem(client, weapon)) { + Entity_Kill(weapon); + } + + if (firstOnly) { + return true; + } + } + + return false; +} + +/** + * Removes all weapons of a client. + * You can specify a weapon it shouldn't remove and if to + * clear the player's ammo for a weapon when it gets removed. + * + * @param client Client Index. + * @param exclude If not empty, this weapon won't be removed from the client. + * @param clearAmmo If true, the ammo the player carries for all removed weapons are set to 0 (primary and secondary). + * @return Number of removed weapons. + */ +stock int Client_RemoveAllWeapons(int client, const char[] exclude="", bool clearAmmo=false) +{ + int offset = Client_GetWeaponsOffset(client) - 4; + + int numWeaponsRemoved = 0; + for (int i=0; i < MAX_WEAPONS; i++) { + offset += 4; + + int weapon = GetEntDataEnt2(client, offset); + + if (!Weapon_IsValid(weapon)) { + continue; + } + + if (exclude[0] != '\0' && Entity_ClassNameMatches(weapon, exclude)) { + Client_SetActiveWeapon(client, weapon); + continue; + } + + if (clearAmmo) { + Client_SetWeaponPlayerAmmoEx(client, weapon, 0, 0); + } + + if (RemovePlayerItem(client, weapon)) { + Entity_Kill(weapon); + } + + numWeaponsRemoved++; + } + + return numWeaponsRemoved; +} + +/** + * Checks if a client has a specific weapon. + * + * @param client Client Index. + * @param className Weapon Classname. + * @return True if client has the weapon, otherwise false. + */ +stock bool Client_HasWeapon(int client, const char[] className) +{ + int weapon = Client_GetWeapon(client, className); + + return (weapon != INVALID_ENT_REFERENCE); +} + +/** + * Gets the weapon of a client by the weapon's classname. + * + * @param client Client Index. + * @param className Classname of the weapon. + * @return Entity index on success or INVALID_ENT_REFERENCE. + */ +stock int Client_GetWeapon(int client, const char[] className) +{ + int offset = Client_GetWeaponsOffset(client) - 4; + int weapon = INVALID_ENT_REFERENCE; + for (int i=0; i < MAX_WEAPONS; i++) { + offset += 4; + + weapon = GetEntDataEnt2(client, offset); + + if (!Weapon_IsValid(weapon)) { + continue; + } + + if (Entity_ClassNameMatches(weapon, className)) { + return weapon; + } + } + + return INVALID_ENT_REFERENCE; +} + +/** + * Gets the weapon of a client by slot number. + * Note: This is incompatible to games that have multiple + * weapons in one slot (eg.: hl2dm). + * + * @param client Client Index. + * @param slot Slot Index. + * @return Entity index on success or INVALID_ENT_REFERENCE. + */ +stock int Client_GetWeaponBySlot(int client, int slot) +{ + return GetPlayerWeaponSlot(client, slot); +} + +/** + * Gets the clients default weapon (Entity Index). + * + * @param client Client Index. + * @return Entity Index on success, INVALID_ENT_REFERENCE on failure. + */ +stock int Client_GetDefaultWeapon(int client) +{ + char weaponName[MAX_WEAPON_STRING]; + if (Client_GetDefaultWeaponName(client, weaponName, sizeof(weaponName))) { + return INVALID_ENT_REFERENCE; + } + + return Client_GetWeapon(client, weaponName); +} + +/** + * Gets the clients default weapon (classname). + * This function doesn't work in all games (maybe only works in hl2dm). + * It will return an empty string if cl_defaultweapon doesn't exist. + * + * @param client Client Index. + * @param buffer Buffer to store the default weapon's classname. + * @param size Max size of string: buffer. + * @return True on success, false otherwise. + */ +stock bool Client_GetDefaultWeaponName(int client, char[] buffer, int size) +{ + if (!GetClientInfo(client, "cl_defaultweapon", buffer, size)) { + buffer[0] = '\0'; + return false; + } + + return true; +} + +/** + * Gets the first weapon of the client's weapon list (m_hMyWeapons). + * Note: This has nothing to do with weapon slots. + * + * @param client Client Index. + * @return Entity Index of the weapon or INVALID_ENT_REFERENCE. + */ +stock int Client_GetFirstWeapon(int client) +{ + int offset = Client_GetWeaponsOffset(client) - 4; + + for (int i=0; i < MAX_WEAPONS; i++) { + offset += 4; + + int weapon = GetEntDataEnt2(client, offset); + + if (!Weapon_IsValid(weapon)) { + continue; + } + + return weapon; + } + + return INVALID_ENT_REFERENCE; +} + +/** + * Gets the number of weapons a client has. + * + * @param client Client Index. + * @return Number of weapons. + */ +stock int Client_GetWeaponCount(int client) +{ + int numWeapons = 0; + + int offset = Client_GetWeaponsOffset(client) - 4; + + for (int i=0; i < MAX_WEAPONS; i++) { + offset += 4; + + int weapon = GetEntDataEnt2(client, offset); + + if (!Weapon_IsValid(weapon)) { + continue; + } + + numWeapons++; + } + + return numWeapons; +} + +/** + * Checks whether the client is currently reloading his active weapon. + * + * @param client Client Index. + * @return True if client is reloading, false otherwise. + */ +stock bool Client_IsReloading(int client) +{ + int weapon = Client_GetActiveWeapon(client); + + if (weapon == INVALID_ENT_REFERENCE) { + return false; + } + + return Weapon_IsReloading(weapon); +} + +/** + * Sets the primary and secondary clip value of a weapon. + * + * @param client Client Index. + * @param classname Classname of a weapon. + * @param primaryClip Primary ammo value in the weapon clip, if -1 the value is untouched. + * @param secondaryClip Secondary ammo value in the weapon clip, if -1 the value is untouched. + * @return True on success, false on failure. + */ +stock bool Client_SetWeaponClipAmmo(int client, const char[] className, int primaryClip=-1, int secondoaryClip=-1) +{ + int weapon = Client_GetWeapon(client, className); + + if (weapon == INVALID_ENT_REFERENCE) { + return false; + } + + if (primaryClip != -1) { + Weapon_SetPrimaryClip(weapon, primaryClip); + } + + if (secondoaryClip != -1) { + Weapon_SetSecondaryClip(weapon, primaryClip); + } + + return true; +} + +/** + * Gets the primary and secondary ammo the player carries for a specific weapon classname. + * + * @param client Client Index. + * @param classname Classname of a weapon. + * @param primaryAmmo Primary ammo stock from the client, if -1 the value is untouched. + * @param secondaryAmmo Secondary ammo stock from the client, if -1 the value is untouched. + * @return True on success, false on failure. + */ +stock bool Client_GetWeaponPlayerAmmo(int client, const char[] className, int &primaryAmmo=-1, int &secondaryAmmo=-1) +{ + int weapon = Client_GetWeapon(client, className); + + if (weapon == INVALID_ENT_REFERENCE) { + return false; + } + + int offset_ammo = FindDataMapInfo(client, "m_iAmmo"); + + if (primaryAmmo != -1) { + int offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); + primaryAmmo = GetEntData(client, offset); + } + + if (secondaryAmmo != -1) { + int offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); + secondaryAmmo = GetEntData(client, offset); + } + + return true; +} + +/** + * Gets the primary and secondary ammo the player carries for a specific weapon index. + * + * @param client Client Index. + * @param weapon Weapon Entity Index. + * @param primaryAmmo Primary ammo stock value from the client, if -1 the value is untouched. + * @param secondaryAmmo Secondary ammo stock value from the client, if -1 the value is untouched. + */ +stock void Client_GetWeaponPlayerAmmoEx(int client, int weapon, int &primaryAmmo=-1, int &secondaryAmmo=-1) +{ + int offset_ammo = FindDataMapInfo(client, "m_iAmmo"); + + if (primaryAmmo != -1) { + int offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); + primaryAmmo = GetEntData(client, offset); + } + + if (secondaryAmmo != -1) { + int offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); + secondaryAmmo = GetEntData(client, offset); + } +} + +/** + * Sets the primary and secondary ammo the player carries for a specific weapon classname. + * + * @param client Client Index. + * @param classname Weapon Classname String. + * @param primaryAmmo Primary ammo stock from the client, if -1 the value is untouched. + * @param secondaryAmmo Secondary ammo stock from the client, if -1 the value is untouched. + * @return True on success, false on failure. + */ +stock bool Client_SetWeaponPlayerAmmo(int client, const char[] className, int primaryAmmo=-1, int secondaryAmmo=-1) +{ + int weapon = Client_GetWeapon(client, className); + + if (weapon == INVALID_ENT_REFERENCE) { + return false; + } + + Client_SetWeaponPlayerAmmoEx(client, weapon, primaryAmmo, secondaryAmmo); + + return true; +} + +/** + * Sets the primary and secondary ammo the player carries for a specific weapon index. + * + * @param client Client Index. + * @param weapon Weapon Entity Index. + * @param primaryAmmo Primary ammo stock value from the client, if -1 the value is untouched. + * @param secondaryAmmo Secondary ammo stock value from the client, if -1 the value is untouched. + */ +stock void Client_SetWeaponPlayerAmmoEx(int client, int weapon, int primaryAmmo=-1, int secondaryAmmo=-1) +{ + int offset_ammo = FindDataMapInfo(client, "m_iAmmo"); + + if (primaryAmmo != -1) { + int offset = offset_ammo + (Weapon_GetPrimaryAmmoType(weapon) * 4); + SetEntData(client, offset, primaryAmmo, 4, true); + } + + if (secondaryAmmo != -1) { + int offset = offset_ammo + (Weapon_GetSecondaryAmmoType(weapon) * 4); + SetEntData(client, offset, secondaryAmmo, 4, true); + } +} + +/** + * Sets the value from primary and secondary ammo stock, of a client. + * + * @param client Client Index. + * @param className Classname of a weapon. + * @param primaryAmmo Primary ammo stock value from the client, if -1 the value is untouched. + * @param secondaryAmmo Secondary ammo stock value from the client, if -1 the value is untouched. + * @param primaryClip Primary ammo value in the weapon clip, if -1 the value is untouched. + * @param secondaryClip Secondary ammo value in the weapon clip, if -1 the value is untouched. + * @return True on success, false on failure. + */ +stock bool Client_SetWeaponAmmo(int client, const char[] className, int primaryAmmo=-1, int secondaryAmmo=-1, int primaryClip=-1, int secondaryClip=-1) +{ + int weapon = Client_GetWeapon(client, className); + + if (weapon == INVALID_ENT_REFERENCE) { + return false; + } + + if (primaryClip != -1) { + Weapon_SetPrimaryClip(weapon, primaryClip); + } + if (secondaryClip != -1) { + Weapon_SetSecondaryClip(weapon, secondaryClip); + } + Client_SetWeaponPlayerAmmoEx(client, weapon, primaryAmmo, secondaryAmmo); + + return true; +} + +/** + * Gets the next weapon of a client, starting at start. + * + * @param client Client Index (must be a valid client ingame). + * @param index Reference to an index variable, will contain the index of the next weapon to check. + * @return Weapon Index or -1 if no more weapons are found. + */ +stock int Client_GetNextWeapon(int client, int &index = 0) +{ + int offset = Client_GetWeaponsOffset(client) + (index * 4); + + int weapon; + while (index < MAX_WEAPONS) { + index++; + + weapon = GetEntDataEnt2(client, offset); + + if (Weapon_IsValid(weapon)) { + return weapon; + } + + offset += 4; + } + + return -1; +} + +/** + * Prints white text to the bottom center of the screen + * for one client. Does not work in all games. + * Line Breaks can be done with "\n". + * + * @param client Client Index. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @return True on success, false if this usermessage doesn't exist. + */ +stock bool Client_PrintHintText(int client, const char[] format, any ...) +{ + Handle userMessage = StartMessageOne("HintText", client); + + if (userMessage == INVALID_HANDLE) { + return false; + } + + char buffer[254]; + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 3); + + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbSetString(userMessage, "text", buffer); + } + else { + BfWriteByte(userMessage, 1); + BfWriteString(userMessage, buffer); + } + + EndMessage(); + + return true; +} + +/** + * Prints white text to the bottom center of the screen + * for all clients. Does not work in all games. + * Line Breaks can be done with "\n". + * + * @param format Formatting rules. + * @param ... Variable number of format parameters. + */ +stock void Client_PrintHintTextToAll(const char[] format, any ...) +{ + char buffer[254]; + + for (int client=1; client <= MaxClients; client++) { + + if (!IsClientInGame(client)) { + continue; + } + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 2); + Client_PrintHintText(client, buffer); + } +} + +/** + * Prints white text to the right-center side of the screen + * for one client. Does not work in all games. + * Line Breaks can be done with "\n". + * + * @param client Client Index. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @return True on success, false if this usermessage doesn't exist. + */ +stock bool Client_PrintKeyHintText(int client, const char[] format, any ...) +{ + Handle userMessage = StartMessageOne("KeyHintText", client); + + if (userMessage == INVALID_HANDLE) { + return false; + } + + char buffer[254]; + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 3); + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbAddString(userMessage, "hints", buffer); + } + else { + BfWriteByte(userMessage, 1); + BfWriteString(userMessage, buffer); + } + + EndMessage(); + + return true; +} + +/** + * Prints white text to the right-center side of the screen + * for all clients. Does not work in all games. + * Line Breaks can be done with "\n". + * + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @noreturn + */ +stock void Client_PrintKeyHintTextToAll(const char[] format, any ...) +{ + char buffer[254]; + + for (int client=1; client <= MaxClients; client++) { + + if (!IsClientInGame(client)) { + continue; + } + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 2); + Client_PrintKeyHintText(client, buffer); + } +} + +/** + * Prints a reliable raw chat message to a client in the chat area. + * If the client == 0, the message will printed to server console. + * + * @param client Client Index. + * @param message String Message. + * @param subject Client Index/Subject (normally used for teamcolors) + * @param isChat Tells the game to handle the chat as normal (false) or chat message (true, plays a sound), only works if SayText2 is supported. + */ +stock void Client_PrintToChatRaw(int client, const char[] message, int subject=0, bool isChat=false) +{ + if (client == 0) { + char buffer[253]; + Color_StripFromChatText(message, buffer, sizeof(buffer)); + PrintToServer(buffer); + return; + } + + static bool sayText2_supported = true; + static bool sayText2_checked = false; + + if (!sayText2_checked) { + + if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID) { + sayText2_supported = false; + } + + sayText2_checked = true; + } + + Handle userMessage = INVALID_HANDLE; + + if (sayText2_supported) { + userMessage = StartMessageOne("SayText2", client, USERMSG_RELIABLE); + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbSetInt(userMessage, "ent_idx", subject); + PbSetBool(userMessage, "chat", isChat); + PbSetString(userMessage, "msg_name", message); + + // psychonic: Furthermore, some usermessages with repeated field, + // such as the commonly-used SayText2, expected an undocumented + // specific number of values added, else the client will crash when receiving. + PbAddString(userMessage, "params", ""); + PbAddString(userMessage, "params", ""); + PbAddString(userMessage, "params", ""); + PbAddString(userMessage, "params", ""); + } + else { + BfWriteByte(userMessage , subject); + BfWriteByte(userMessage , isChat); + BfWriteString(userMessage , message); + } + } + else { + userMessage = StartMessageOne("SayText", client, USERMSG_RELIABLE); + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbSetInt(userMessage, "ent_idx", subject); + PbSetString(userMessage, "text", message); + PbSetBool(userMessage, "chat", isChat); + } + else { + BfWriteByte(userMessage , subject); + BfWriteString(userMessage , message); + // For DoD:S nickname coloring + BfWriteByte(userMessage , -1); + } + } + + EndMessage(); +} + +/** + * Prints a reliable chat message to one client in the chat area. + * Allows up to 253 Characters (including \0) to be printed. + * Supports chat color tags (see: colors.inc). + * + * @param client Client Index. + * @param isChat Tells the game to handle the chat as normal (false) or chat message (true, plays a sound), only works if SayText2 is supported. + * @param format Formatting rules String. + * @param ... Variable number of format parameters. + */ +stock void Client_PrintToChat(int client, bool isChat, const char[] format, any ...) +{ + char + buffer[512], + buffer2[253]; + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 4); + int subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); + + Client_PrintToChatRaw(client, buffer2, subject, isChat); + + Color_ChatClearSubject(); +} + +static int printToChat_excludeclient = -1; + +/** + * Exclude a client from the next call to a Client_PrintToChat function. + * + * @param client Client Index. + * @noreturn + */ +stock void Client_PrintToChatExclude(int client) +{ + printToChat_excludeclient = client; +} + +/** + * Prints a reliable chat message to all clients in the chat area. + * Allows up to 253 Characters (including \0) to be printed. + * Supports chat color tags (see: colors.inc). + * + * @param isChat Tells the game to handle the chat as normal (false) or chat message (true, plays a sound), only works if SayText2 is supported. + * @param format Formatting rules String. + * @param ... Variable number of format parameters. + */ +stock void Client_PrintToChatAll(bool isChat, const char[] format, any ...) +{ + char + buffer[512], + buffer2[253]; + int + subject, + language, + lastLanguage = -1; + + for (int client=1; client <= MaxClients; client++) { + + if (!IsClientInGame(client)) { + continue; + } + + if (client == printToChat_excludeclient) { + printToChat_excludeclient = -1; + continue; + } + + language = GetClientLanguage(client); + + if (language != lastLanguage) { + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 3); + subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); + + lastLanguage = language; + } + + Client_PrintToChatRaw(client, buffer2, subject, isChat); + } + + Color_ChatClearSubject(); +} + +/** + * Prints a reliable chat message to the specified clients in the chat area. + * Allows up to 253 Characters (including \0) to be print. + * Supports chat color tags (see: colors.inc). + * + * @param clients Client Array. + * @param numClients Number of clients in the client array. + * @param isChat Tells the game to handle the chat as normal (false) or chat message (true, plays a sound), only works if SayText2 is supported. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + */ +stock void Client_PrintToChatEx(int[] clients, int numClients, bool isChat, const char[] format, any ...) +{ + char + buffer[512], + buffer2[253]; + int + client, + subject, + language, + lastLanguage = -1; + + for (int i=0; i < numClients; i++) { + + client = clients[i]; + + if (!IsClientInGame(client)) { + continue; + } + + if (client == printToChat_excludeclient) { + printToChat_excludeclient = -1; + continue; + } + + language = GetClientLanguage(client); + + if (language != lastLanguage) { + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 5); + subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); + + lastLanguage = language; + } + + Client_PrintToChatRaw(client, buffer2, subject, isChat); + } + + Color_ChatClearSubject(); +} + +enum ClientHudPrint { + ClientHudPrint_Notify = 1, + ClientHudPrint_Console, + ClientHudPrint_Talk, + Client_HudPrint_Center +}; + +/** + * Prints a relieable message to the client's console. + * Allows up to 254 Characters (including \0) to be print (253 for talk). + * Supports chat color tags (see: colors.inc, only available in Left 4 Dead (2) or higher). + * Chat colors are stripped automatically if not supported. + * + * @param clients Client Array. + * @param format Formatting rules. + * @param ... Variable number of format parameters. + */ +stock void Client_PrintToConsole(int client, const char[] format, any ...) +{ + char buffer[512]; + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 3); + + Client_Print(client, ClientHudPrint_Console, buffer); +} + +/** + * Prints a relieable message to the client's console. + * Allows up to 254 Characters (including \0) to be print. + * Supports chat color tags in chat & console (see: colors.inc). + * Chat colors are stripped automatically if not supported in the destination. + * + * @param clients Client Array. + * @param destination Destination place (use onf of the ClientHudPrint_) + * @param format Formatting rules. + * @param ... Variable number of format parameters. + */ +stock void Client_Print(int client, ClientHudPrint destination, const char[] format, any ...) +{ + char buffer[512], buffer2[254]; + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 4); + + int subject = Color_ParseChatText(buffer, buffer2, sizeof(buffer2)); + + if (destination == ClientHudPrint_Talk) { + Client_PrintToChatRaw(client, buffer2, subject, false); + return; + } + + EngineVersion engineVersion = GetEngineVersion(); + if (client == 0 || + destination != ClientHudPrint_Console || + (destination == ClientHudPrint_Console + && engineVersion != Engine_Left4Dead && engineVersion != Engine_Left4Dead2)) + { + Color_StripFromChatText(buffer2, buffer2, sizeof(buffer2)); + + if (client == 0) { + PrintToServer(buffer2); + return; + } + } + + Handle userMessage = INVALID_HANDLE; + userMessage = StartMessageOne("TextMsg", client, USERMSG_RELIABLE); + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbSetInt(userMessage, "msg_dst", view_as(destination)); + PbAddString(userMessage, "params", buffer2); + PbAddString(userMessage, "params", ""); + PbAddString(userMessage, "params", ""); + PbAddString(userMessage, "params", ""); + PbAddString(userMessage, "params", ""); + } + else { + BfWriteByte(userMessage , view_as(destination)); + BfWriteString(userMessage , buffer2); + } + + EndMessage(); +} + +/** + * Replies to a message in a command. + * A client index of 0 will use PrintToServer(). + * If the command was from the console, Client_PrintToConsole() is used. + * If the command was from chat, Client_PrintToChat() is used. + * + * @param client Client Index. + * @param format Formatting rules String. + * @param ... Variable number of format parameters. + */ +stock void Client_Reply(int client, const char[] format, any ...) +{ + char buffer[255]; + + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 3); + + if (GetCmdReplySource() == SM_REPLY_TO_CONSOLE) { + Client_PrintToConsole(client, buffer); + } + else { + Client_PrintToChat(client, false, buffer); + } +} + +#define SHAKE_START 0 // Starts the screen shake for all players within the radius. +#define SHAKE_STOP 1 // Stops the screen shake for all players within the radius. +#define SHAKE_AMPLITUDE 2 // Modifies the amplitude of an active screen shake for all players within the radius. +#define SHAKE_FREQUENCY 3 // Modifies the frequency of an active screen shake for all players within the radius. +#define SHAKE_START_RUMBLEONLY 4 // Starts a shake effect that only rumbles the controller, no screen effect. +#define SHAKE_START_NORUMBLE 5 // Starts a shake that does NOT rumble the controller. + +/** + * Shakes a client's screen with the specified amptitude, + * frequency & duration. + * + * @param client Client Index. + * @param command Shake Mode, use one of the SHAKE_ definitions. + * @param amplitude Shake magnitude/amplitude. + * @param frequency Shake noise frequency. + * @param duration Shake lasts this long. + * @return True on success, false otherwise. + */ +stock bool Client_Shake(int client, int command=SHAKE_START, float amplitude=50.0, float frequency=150.0, float duration=3.0) +{ + if (command == SHAKE_STOP) { + amplitude = 0.0; + } + else if (amplitude <= 0.0) { + return false; + } + + Handle userMessage = StartMessageOne("Shake", client); + + if (userMessage == INVALID_HANDLE) { + return false; + } + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available + && GetUserMessageType() == UM_Protobuf) { + + PbSetInt(userMessage, "command", command); + PbSetFloat(userMessage, "local_amplitude", amplitude); + PbSetFloat(userMessage, "frequency", frequency); + PbSetFloat(userMessage, "duration", duration); + } + else { + BfWriteByte(userMessage, command); // Shake Command + BfWriteFloat(userMessage, amplitude); // shake magnitude/amplitude + BfWriteFloat(userMessage, frequency); // shake noise frequency + BfWriteFloat(userMessage, duration); // shake lasts this long + } + + EndMessage(); + + return true; +} + +/** + * Checks whether the client is a generic admin. + * + * @param Client Index. + * @return True if the client is a generic admin, false otheriwse. + */ +stock bool Client_IsAdmin(int client) +{ + AdminId adminId = GetUserAdmin(client); + + if (adminId == INVALID_ADMIN_ID) { + return false; + } + + return GetAdminFlag(adminId, Admin_Generic); +} + +/** + * Checks whether a client has certain admin flags + * + * @param Client Index. + * @return True if the client has the admin flags, false otherwise. + */ +stock bool Client_HasAdminFlags(int client, int flags=ADMFLAG_GENERIC) +{ + AdminId adminId = GetUserAdmin(client); + + if (adminId == INVALID_ADMIN_ID) { + return false; + } + + return GetAdminFlags(adminId, Access_Effective) & flags == flags; +} + +/** + * Returns whether a player is in a specific admin group. + * + * @param client Client Index. + * @param groupName Admin group name to check. + * @param caseSensitive True if the group check has to be case sensitive, false otherwise. + * @return True if the client is in the admin group, false otherwise. + */ +stock bool Client_IsInAdminGroup(int client, const char[] groupName, bool caseSensitive=true) +{ + AdminId adminId = GetUserAdmin(client); + + // Validate id. + if (adminId == INVALID_ADMIN_ID) { + return false; + } + + // Get number of groups. + int count = GetAdminGroupCount(adminId); + + // Validate number of groups. + if (count == 0) { + return false; + } + + char groupname[64]; + + // Loop through each group. + for (int i = 0; i < count; i++) { + // Get group name. + GetAdminGroup(adminId, i, groupname, sizeof(groupname)); + + // Compare names. + if (StrEqual(groupName, groupname, caseSensitive)) { + return true; + } + } + + // No match. + return false; +} + +/** + * Checks if the client is currently looking at the wall in front + * of him with the given distance as max value. + * + * @param client Client Index. + * @param distance Max Distance as Float value. + * @return True if he is looking at a wall, false otherwise. + */ +stock bool Client_IsLookingAtWall(int client, float distance=40.0) { + + float posEye[3], posEyeAngles[3]; + bool isClientLookingAtWall = false; + + GetClientEyePosition(client, posEye); + GetClientEyeAngles(client, posEyeAngles); + + posEyeAngles[0] = 0.0; + + Handle trace = TR_TraceRayFilterEx(posEye, posEyeAngles, CONTENTS_SOLID, RayType_Infinite, _smlib_TraceEntityFilter); + + if (TR_DidHit(trace)) { + + if (TR_GetEntityIndex(trace) > 0) { + delete trace; + return false; + } + + float posEnd[3]; + + TR_GetEndPosition(posEnd, trace); + + if (GetVectorDistance(posEye, posEnd, true) <= (distance * distance)) { + isClientLookingAtWall = true; + } + } + + delete trace; + + return isClientLookingAtWall; +} + +public bool _smlib_TraceEntityFilter(int entity, int contentsMask) +{ + return entity == 0; +} + +/** + * Gets a client's class. + * Currently supported games are: TF2, Dark Messiah. + * Other games maybe work too, but are not tested. + * + * @param client Client Index. + * @return Class Index. + */ +stock int Client_GetClass(int client) +{ + if (GetEngineVersion() == Engine_DarkMessiah) { + return GetEntProp(client, Prop_Send, "m_iPlayerClass"); + } + + return GetEntProp(client, Prop_Send, "m_iClass"); +} + +/** + * Sets a client's class. + * Currently supported games are: TF2, Dark Messiah. + * Other games maybe work too, but are not tested. + * + * @param client Client Index. + * @param playerClass The class number to set the player to. Depends on game. + * @param persistant If true changes the players desired class so the change stays after death (probably TF2 only). + */ +stock void Client_SetClass(int client, int playerClass, bool persistant=false) +{ + if (GetEngineVersion() == Engine_DarkMessiah) { + SetEntProp(client, Prop_Send, "m_iPlayerClass", playerClass); + } else { + SetEntProp(client, Prop_Send, "m_iClass", playerClass); + + if (persistant) { + SetEntProp(client, Prop_Send, "m_iDesiredPlayerClass", playerClass); + } + } +} + +/** + * Returns what buttons are currently pressed by the client. + * + * @param client Client Index. + * @return Buttons as bitflag. + */ +stock int Client_GetButtons(int client) +{ + return GetClientButtons(client); +} + +/** + * Sets the client buttons. + * Note: This will only work OnPreThink (sdkhooks) or OnPlayerRunCmd. + * + * @param client Client Index. + * @param buttons Buttons as bitflag. + */ +stock void Client_SetButtons(int client, int buttons) +{ + SetEntProp(client, Prop_Data, "m_nButtons", buttons); +} + +/** + * Adds buttons to the already pressed buttons. + * Note: This will likely only work OnPreThink (sdkhooks) or OnPlayerRunCmd. + * + * @param client Client Index. + * @param buttons Buttons as bitflag. + */ +stock void Client_AddButtons(int client, int buttons) +{ + int newButtons = Client_GetButtons(client); + newButtons |= buttons; + Client_SetButtons(client, newButtons); +} + +/** + * Removes buttons from the already pressed buttons. + * Note: This will only work OnPreThink (sdkhooks) or OnPlayerRunCmd. + * + * @param client Client Index. + * @param buttons Buttons as bitflag. + */ +stock void Client_RemoveButtons(int client, int buttons) +{ + int newButtons = Client_GetButtons(client); + newButtons &= ~buttons; + Client_SetButtons(client, newButtons); +} + +/** + * Clears all buttons. + * Note: This will likely only work OnPreThink (sdkhooks) or OnPlayerRunCmd. + * + * @param client Client Index. + */ +stock void Client_ClearButtons(int client) +{ + Client_SetButtons(client,0); +} + +/** + * Returns if the given buttons are pressed by the client or not. + * + * @param client Client Index. + * @param buttons Buttons as bitflag. + * @return True if the buttons are pressed otherwise false. + */ +stock bool Client_HasButtons(int client, int buttons) +{ + return Client_GetButtons(client) & buttons == buttons; +} + +/** + * Returns only the buttons that have changed since the last call of this. + * Example usage: Within OnPlayerRunCmd use this function to call another function only once when a player pressed or released a button. + * + * @param client Client Index. + * @param buttons Buttons as bitflag. + * @return + */ +stock int Client_GetChangedButtons(int client) +{ + static int oldButtons[MAXPLAYERS+1] = {0,...}; + + int buttons = Client_GetButtons(client); + int changedButtons = buttons ^ oldButtons[client]; + + oldButtons[client] = buttons; + + return changedButtons; +} + +/** + * Sets the client's maxspeed to the given value (in units per second) + * + * @param Client Client Index + * @param maxspeed the maximum speed the client can move + */ +stock void Client_SetMaxSpeed(int client, float value) +{ + Entity_SetMaxSpeed(client, value); +} + +/** + * Shows a screen overlay tp a client. + * There can only be one overlay at a time. + * If you want to clear the overlay, pass + * an empty string to this function. + * + * @param Client Client Index. + * @param path Overlay path (based on the game/materials/ folder) or empty String to not show any overlay. + * @noreturn + */ +stock void Client_SetScreenOverlay(int client, const char[] path) +{ + ClientCommand(client, "r_screenoverlay \"%s\"", path); +} + +/** + * Shows a screen overlay to all clients. + * There can only be one overlay at a time. + * If you want to clear the overlay, pass + * an empty string to this function. + * + * @param Client Client Index. + * @param path Overlay path (based on the game/materials/ folder) or empty String to not show any overlay. + * @noreturn + */ +stock void Client_SetScreenOverlayForAll(const char[] path) +{ + LOOP_CLIENTS(client, CLIENTFILTER_INGAME | CLIENTFILTER_NOBOTS) { + Client_SetScreenOverlay(client, path); + } +} + +/** + * Mutes a client's voice + * + * @param Client Client Index. + * @noreturn + */ +stock void Client_Mute(int client) +{ + SetClientListeningFlags(client, VOICE_MUTED); +} + +/** + * UnMutes a client's voice + * Code copied from basecomm.sp + * + * @param Client Client Index. + */ +stock void Client_UnMute(int client) +{ + static ConVar cvDeadTalk = null; + + if (cvDeadTalk == INVALID_HANDLE) { + cvDeadTalk = FindConVar("sm_deadtalk"); + } + + if (cvDeadTalk == INVALID_HANDLE) { + SetClientListeningFlags(client, VOICE_NORMAL); + } + else { + if (cvDeadTalk.IntValue == 1 && !IsPlayerAlive(client)) { + SetClientListeningFlags(client, VOICE_LISTENALL); + } + else if (cvDeadTalk.IntValue == 2 && !IsPlayerAlive(client)) { + SetClientListeningFlags(client, VOICE_TEAM); + } + else { + SetClientListeningFlags(client, VOICE_NORMAL); + } + } +} + +/** + * Checks if a client's voice is muted + * + * @param Client Client Index. + * @return True if the client is muted, false otherwise. + */ +stock bool Client_IsMuted(int client) +{ + return GetClientListeningFlags(client) & VOICE_MUTED > 0; +} + +/** + * Checks if a client matches the specified flag filter. + * Use one of the CLIENTFILTER_ constants. + * Note that this already checks if the client is ingame or connected + * so you don't have to do that yourself. + * This function is optimized to make as less native calls as possible :) + * + * @param Client Client Index. + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + * @return True if the client if the client matches, false otherwise. + */ +stock bool Client_MatchesFilter(int client, int flags) +{ + bool isIngame = false; + + if (flags >= CLIENTFILTER_INGAME) { + isIngame = IsClientInGame(client); + + if (isIngame) { + if (flags & CLIENTFILTER_NOTINGAME) { + return false; + } + } + else { + return false; + } + } + else if (!IsClientConnected(client)) { + return false; + } + + if (!flags) { + return true; + } + + if (flags & CLIENTFILTER_INGAMEAUTH) { + flags |= CLIENTFILTER_INGAME | CLIENTFILTER_AUTHORIZED; + } + + if (flags & CLIENTFILTER_BOTS && !IsFakeClient(client)) { + return false; + } + + if (flags & CLIENTFILTER_NOBOTS && IsFakeClient(client)) { + return false; + } + + if (flags & CLIENTFILTER_ADMINS && !Client_IsAdmin(client)) { + return false; + } + + if (flags & CLIENTFILTER_NOADMINS && Client_IsAdmin(client)) { + return false; + } + + if (flags & CLIENTFILTER_AUTHORIZED && !IsClientAuthorized(client)) { + return false; + } + + if (flags & CLIENTFILTER_NOTAUTHORIZED && IsClientAuthorized(client)) { + return false; + } + + if (isIngame) { + + if (flags & CLIENTFILTER_ALIVE && !IsPlayerAlive(client)) { + return false; + } + + if (flags & CLIENTFILTER_DEAD && IsPlayerAlive(client)) { + return false; + } + + if (flags & CLIENTFILTER_SPECTATORS && GetClientTeam(client) != TEAM_SPECTATOR) { + return false; + } + + if (flags & CLIENTFILTER_NOSPECTATORS && GetClientTeam(client) == TEAM_SPECTATOR) { + return false; + } + + if (flags & CLIENTFILTER_OBSERVERS && !IsClientObserver(client)) { + return false; + } + + if (flags & CLIENTFILTER_NOOBSERVERS && IsClientObserver(client)) { + return false; + } + + if (flags & CLIENTFILTER_TEAMONE && GetClientTeam(client) != TEAM_ONE) { + return false; + } + + if (flags & CLIENTFILTER_TEAMTWO && GetClientTeam(client) != TEAM_TWO) { + return false; + } + } + + return true; +} + +/** + * Gets all clients matching the specified flags filter. + * + * @param client Client Array, size should be MaxClients or MAXPLAYERS + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + * @return The number of clients stored in the array + */ +stock int Client_Get(int[] clients, int flags=CLIENTFILTER_ALL) +{ + int x=0; + for (int client = 1; client <= MaxClients; client++) { + + if (!Client_MatchesFilter(client, flags)) { + continue; + } + + clients[x++] = client; + } + + return x; +} + +/** + * Gets a random client matching the specified flags filter. + * + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + * @return Client Index or -1 if no client was found + */ +stock int Client_GetRandom(int flags=CLIENTFILTER_ALL) +{ + int[] clients = new int[MaxClients]; + int num = Client_Get(clients, flags); + + if (num == 0) { + return -1; + } + else if (num == 1) { + return clients[0]; + } + + int random = Math_GetRandomInt(0, num-1); + + return clients[random]; +} + +/** + * Gets a client matching certain flags starting at start. + * + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + * @param start Start Index. + * @return Client Index or -1 if no client was found + */ +stock int Client_GetNext(int flags, int start=1) +{ + for (int client=start; client <= MaxClients; client++) { + + if (Client_MatchesFilter(client, flags)) { + return client; + } + } + + return -1; +} + +/** + * Retrieves the time duration a client played on the current map. + * + * @param client Client Index. + * @return Time in seconds as Float + */ +stock float Client_GetMapTime(int client) +{ + float fClientTime = GetClientTime(client); + float fGameTime = GetGameTime(); + + return (fClientTime < fGameTime) ? fClientTime : fGameTime; +} + +/** + * Gets client money value (for games like Counter-Strike:Source). + * + * @param client Client Index. + * @return Money value from the client. + */ +stock int Client_GetMoney(int client) +{ + return GetEntProp(client, Prop_Send, "m_iAccount"); +} + +/** + * Sets client money value (for games like Counter-Strike:Source). + * + * @param client Client Index. + * @param value Money value to set. + */ +stock void Client_SetMoney(int client, int value) +{ + SetEntProp(client, Prop_Send, "m_iAccount", value); +} + +/** + * Gets a client's observers. + * + * @param client Client Index. + * @param observers Array with size of MaxClients or MAXPLAYERS. + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + * @return Number of observers found. + */ +stock int Client_GetObservers(int client, int[] observers, int flags=CLIENTFILTER_ALL) +{ + int count = 0; + + LOOP_CLIENTS(player, CLIENTFILTER_OBSERVERS | flags) { + + if (Client_GetObserverTarget(player) == client) { + observers[count++] = player; + } + } + + return count; +} + +static float getPlayersInRadius_distances[MAXPLAYERS+1]; + +/** + * Gets all players near a player in a certain radius and + * orders the players by distance (optional). + * + * @param client Client Index. + * @param clients Array with size of MaxClients or MAXPLAYERS. + * @param radius radius Float (max distance) + * @param orderByDistance Set to true to order the clients by distance, false otherwise. + * @return Number of clients found. + */ +stock int Client_GetPlayersInRadius(int client, int[] clients, float radius, bool orderByDistance=true) +{ + float origin_client[3], distance; + int count=0; + + Entity_GetAbsOrigin(client, origin_client); + + LOOP_CLIENTS(player, CLIENTFILTER_INGAME) { + + if (player == client) { + continue; + } + + distance = Entity_GetDistanceOrigin(player, origin_client); + + if (distance <= radius) { + clients[count++] = player; + + if (orderByDistance) { + getPlayersInRadius_distances[player] = distance; + } + } + } + + if (orderByDistance) { + SortCustom1D(clients, count, __smlib_GetPlayersInRadius_Sort); + } + + return count; +} + +public int __smlib_GetPlayersInRadius_Sort(int player1, int player2, const int[] clients, Handle hndl) +{ + return FloatCompare(getPlayersInRadius_distances[player1], getPlayersInRadius_distances[player2]); +} + +/** + * Gets the next player observing client starting at start. + * + * @param client Client Index (Observer Target) + * @param start Start Index. + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + * @return Client Index or -1 if no client was found + */ +stock int Client_GetNextObserver(int client, int start=1, int flags=CLIENTFILTER_ALL) +{ + for (int player=start; player <= MaxClients; player++) { + + if (Client_MatchesFilter(player, CLIENTFILTER_OBSERVERS | flags)) { + + if (Client_GetObserverTarget(player) == client) { + return player; + } + } + } + + return -1; +} + +/** + * Searchs and returns the game's player_manager entity. + * This should be called on every map start. + * + * @return player_manager entity or INVALID_ENT_REFERENCE if not found. + */ +stock int Client_GetPlayerManager() +{ + static int player_manager = INVALID_ENT_REFERENCE; + + if (player_manager != INVALID_ENT_REFERENCE) { + + if (Entity_IsValid(player_manager)) { + return player_manager; + } + else { + player_manager = INVALID_ENT_REFERENCE; + } + } + + int maxEntities = GetMaxEntities(); + + for (int entity=MaxClients+1; entity < maxEntities; entity++) { + + if (!Entity_IsValid(entity)) { + continue; + } + + if (Entity_ClassNameMatches(entity, "player_manager", true)) { + player_manager = EntIndexToEntRef(entity); + + return player_manager; + } + } + + return INVALID_ENT_REFERENCE; +} + +/** + * Sets the client's ping as displayed in the scoreboards. + * Should be called OnGameFrame. + * + * @param client Client Index + * @param start New ping value. + * @return True on sucess, false otherwise. + */ +stock int Client_SetPing(int client, int value) +{ + int player_manager = Client_GetPlayerManager(); + + static int offset = -1; + + if (offset== -1) { + offset = GetEntSendPropOffs(player_manager, "m_iPing", true); + + if (offset == -1) { + return false; + } + } + + SetEntData(player_manager, offset + (client * 4), value, 4, true); + + return true; +} + +static int printToTop_excludeclient = -1; + +/** + * Exclude a client from the next call to a Client_PrintToTop function. + * + * @param client Client Index. + * @noreturn + */ +stock void Client_PrintToTopExclude(int client) +{ + printToTop_excludeclient = client; +} + +/** + * Prints colored text to the top left of the screen + * for one client. Does not work in all games. + * Line Breaks can't be done. + * + * @param client Client Index. + * @param r Red amount. + * @param g Green amount. + * @param b Blue amount. + * @param a Transparency. + * @param duration Duration in seconds the text stays (min 10 - max 200 seconds). + * @param text Text to print to. + * @return True on success, false if the key value for the dialog couldn't be created or closed. + */ +stock bool Client_PrintToTopRaw(int client, int r=255, int g=255, int b=255, int a=255, float duration=10.0, const char[] text) +{ + //message line max 50 + //overline: 39*_ + //underline: 44*T + KeyValues keyValue = CreateKeyValues("Stuff", "title", text); + + if (keyValue == INVALID_HANDLE) { + return false; + } + + KvSetColor(keyValue, "color", r, g, b, a); + KvSetNum(keyValue, "level", 1); + KvSetNum(keyValue, "time", RoundToFloor(duration)); + + CreateDialog(client, keyValue, DialogType_Msg); + delete keyValue; + + return true; +} + +/** + * Prints colored text to the top left of the screen + * for one client. Does not work in all games. + * Line Breaks can't be done. + * + * @param client Client Index. + * @param r Red amount. + * @param g Green amount. + * @param b Blue amount. + * @param a Transparency. + * @param duration Duration in seconds the text stays (min 10 - max 200 seconds). + * @param format Formatting rules. + * @param ... Variable number of format parameters. + * @return True on success, false if the key value for the dialog couldn't be created or closed. + */ +stock bool Client_PrintToTop(int client, int r=255, int g=255, int b=255, int a=255, float duration=10.0, const char[] format, any ...) +{ + char buffer[150]; + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 8); + + return Client_PrintToTopRaw(client, r, g, b, a, duration, buffer); +} + +/** + * Prints colored text to the top left of the screen + * to all clients. Does not work in all games. + * Line Breaks can't be done. + * + * @param r Red amount. + * @param g Green amount. + * @param b Blue amount. + * @param a Transparency. + * @param duration Duration in seconds the text stays (min 10 - max 200 seconds). + * @param format Formatting rules. + * @param ... Variable number of format parameters. + */ +stock void Client_PrintToTopAll(int r=255, int g=255, int b=255, int a=255, float duration=10.0, const char[] format, any ...) +{ + char buffer[150]; + int + language, + lastLanguage = -1; + + for (int client=1; client <= MaxClients; client++) { + + if (!IsClientInGame(client)) { + continue; + } + + if (client == printToTop_excludeclient) { + printToTop_excludeclient = -1; + continue; + } + + language = GetClientLanguage(client); + + if (language != lastLanguage) { + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 7); + + lastLanguage = language; + } + + Client_PrintToTopRaw(client, r, g, b, a, duration, buffer); + } +} + +/** + * Prints colored text to the top left of the screen + * to specified clients. Does not work in all games. + * Line Breaks can't be done. + * + * @param clients Client Array. + * @param numClients Number of clients in the clients array. + * @param r Red amount. + * @param g Green amount. + * @param b Blue amount. + * @param a Transparency. + * @param duration Duration in seconds the text stays (min 10 - max 200 seconds). + * @param format Formatting rules. + * @param ... Variable number of format parameters. + */ +stock void Client_PrintToTopEx(int[] clients, int numClients, int r=255, int g=255, int b=255, int a=255, float duration=10.0, const char[] format, any ...) +{ + char buffer[150]; + int + client, + language, + lastLanguage = -1; + + for (int i=0; i < numClients; i++) { + + client = clients[i]; + + if (!IsClientInGame(client)) { + continue; + } + + if (client == printToTop_excludeclient) { + printToTop_excludeclient = -1; + continue; + } + + language = GetClientLanguage(client); + + if (language != lastLanguage) { + SetGlobalTransTarget(client); + VFormat(buffer, sizeof(buffer), format, 9); + + lastLanguage = language; + } + + Client_PrintToTopRaw(client, r, g, b, a, duration, buffer); + } +} + +/** + * Opens the scoreboard for a specific client + * + * @tested csgo + * @param client Client index + */ +stock void Client_ShowScoreboard(int client, int flags=USERMSG_RELIABLE | USERMSG_BLOCKHOOKS) +{ + Handle handle = StartMessageOne("VGUIMenu", client, flags); + + if (GetFeatureStatus(FeatureType_Native, "GetUserMessageType") == FeatureStatus_Available && + GetUserMessageType() == UM_Protobuf) { + + PbSetString(handle, "name", "scores"); + PbSetBool(handle, "show", true); + } + else { + BfWriteString(handle, "scores"); + BfWriteByte(handle, 1); // Show + BfWriteByte(handle, 0); // subkeys count + } + + EndMessage(); +} diff --git a/addons/sourcemod/scripting/include/smlib/colors.inc b/addons/sourcemod/scripting/include/smlib/colors.inc new file mode 100644 index 0000000..b962f53 --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/colors.inc @@ -0,0 +1,575 @@ +#if defined _smlib_colors_included + #endinput +#endif +#define _smlib_colors_included + +#include +#include +#include + +#define CHATCOLOR_NOSUBJECT -2 +#define SMLIB_COLORS_GAMEDATAFILE "smlib_colors.games" + +enum ChatColorSubjectType +{ + ChatColorSubjectType_none = -3, + + // Subject/Team colors + ChatColorSubjectType_player = -2, + ChatColorSubjectType_undefined = -1, + ChatColorSubjectType_world = 0 + // Anything higher is a specific team +} + +enum struct ChatColorInfo +{ + int ChatColorInfo_Code; + int ChatColorInfo_Alternative; + bool ChatColorInfo_Supported; + ChatColorSubjectType ChatColorInfo_SubjectType; +} + +enum ChatColor +{ + ChatColor_Normal, + ChatColor_Orange, + ChatColor_Red, + ChatColor_RedBlue, + ChatColor_Blue, + ChatColor_BlueRed, + ChatColor_Team, + ChatColor_Lightgreen, + ChatColor_Gray, + ChatColor_Green, + ChatColor_Olivegreen, + ChatColor_Black, + ChatColor_MAXCOLORS +} + +static char chatColorTags[][] = { + "N", // Normal + "O", // Orange + "R", // Red + "RB", // Red, Blue + "B", // Blue + "BR", // Blue, Red + "T", // Team + "L", // Light green + "GRA", // Gray + "G", // Green + "OG", // Olive green + "BLA" // Black +}; + +static char chatColorNames[][] = { + "normal", // Normal + "orange", // Orange + "red", // Red + "redblue", // Red, Blue + "blue", // Blue + "bluered", // Blue, Red + "team", // Team + "lightgreen", // Light green + "gray", // Gray + "green", // Green + "olivegreen", // Olive green + "black" // Black +}; + +static ChatColorInfo chatColorInfo[ChatColor_MAXCOLORS]; + +static bool checkTeamPlay = false; +static ConVar mp_teamplay = null; +static bool isSayText2_supported = true; +static int chatSubject = CHATCOLOR_NOSUBJECT; + +/** + * Sets the subject (a client) for the chat color parser. + * Call this before Color_ParseChatText() or Client_PrintToChat(). + * + * @param client Client Index/Subject + */ +stock void Color_ChatSetSubject(int client) +{ + chatSubject = client; +} + +/** + * Gets the subject used for the chat color parser. + * + * @return Client Index/Subject, or CHATCOLOR_NOSUBJECT if none + */ +stock int Color_ChatGetSubject() +{ + return chatSubject; +} + +/** + * Clears the subject used for the chat color parser. + * Call this after Color_ParseChatText(). + */ +stock void Color_ChatClearSubject() +{ + chatSubject = CHATCOLOR_NOSUBJECT; +} + +/** + * Parses a chat string and converts all color tags to color codes. + * This is a very powerful function that works recursively over the color information + * table. The support colors are hardcoded, but can be overriden for each game by + * creating the file gamedata/smlib_colors.games.txt. + * + * @param str Chat String + * @param subject Output Buffer + * @param size Output Buffer size + * @return Returns a value for the subject + */ +stock int Color_ParseChatText(const char[] str, char[] buffer, int size) +{ + bool inBracket = false; + int x, x_buf, x_tag; + int subject = CHATCOLOR_NOSUBJECT; + + char sTag[10] = ""; // This should be able to hold "\x08RRGGBBAA"\0 + char colorCode[10] = ""; // This should be able to hold "\x08RRGGBBAA"\0 + char currentColor[10] = "\x01"; // Initialize with normal color + + size--; + + // Every chat message has to start with a + // color code, otherwise it will ignore all colors. + buffer[x_buf++] = '\x01'; + + while (str[x] != '\0') { + + if (size == x_buf) { + break; + } + + char character = str[x++]; + + if (inBracket) { + // We allow up to 9 characters in the tag (#RRGGBBAA) + if (character == '}' || x_tag > 9) { + inBracket = false; + sTag[x_tag] = '\0'; + x_tag = 0; + + if (character == '}') { + Color_TagToCode(sTag, subject, colorCode); + + if (colorCode[0] == '\0') { + // We got an unknown tag, ignore this + // and forward it to the buffer. + + // Terminate buffer with \0 so Format can handle it. + buffer[x_buf] = '\0'; + x_buf = Format(buffer, size, "%s{%s}", buffer, sTag); + + // We 'r done here + continue; + } + else if (!StrEqual(colorCode, currentColor)) { + // If we are already using this color, + // we don't need to set it again. + + // Write the color code to our buffer. + // x_buf will be increased by the number of cells written. + x_buf += strcopy(buffer[x_buf], size - x_buf, colorCode); + + // Remember the current color. + strcopy(currentColor, sizeof(currentColor), colorCode); + } + } + else { + // If the tag character limit exceeds 9, + // we have to do something. + + // Terminate buffer with \0 so Format can handle it. + buffer[x_buf] = '\0'; + x_buf = Format(buffer, size, "%s{%s%c", buffer, sTag, character); + } + } + else if (character == '{' && !x_tag) { + buffer[x_buf++] = '{'; + inBracket = false; + } + else { + sTag[x_tag++] = character; + } + } + else if (character == '{') { + inBracket = true; + } + else { + buffer[x_buf++] = character; + } + } + + // Write remaining text to the buffer, + // if we have been inside brackets. + if (inBracket) { + buffer[x_buf] = '\0'; + x_buf = Format(buffer, size, "%s{%s", buffer, sTag); + } + + buffer[x_buf] = '\0'; + + return subject; +} + +/** + * Converts a chat color tag to its code character. + * + * @param tag Color Tag String. + * @param subject Subject variable to pass + * @param result The result as character sequence (string). This will be \0 if the tag is unkown. + */ +stock void Color_TagToCode(const char[] tag, int &subject=-1, char result[10]) +{ + // Check if the tag starts with a '#'. + // We will handle it has RGB(A)-color code then. + if (tag[0] == '#') { + int length_tag = strlen(tag); + switch (length_tag - 1) { + // #RGB -> \07RRGGBB + case 3: { + FormatEx( + result, sizeof(result), "\x07%c%c%c%c%c%c", + tag[1], tag[1], tag[2], tag[2], tag[3], tag[3] + ); + } + // #RGBA -> \08RRGGBBAA + case 4: { + FormatEx( + result, sizeof(result), "\x08%c%c%c%c%c%c%c%c", + tag[1], tag[1], tag[2], tag[2], tag[3], tag[3], tag[4], tag[4] + ); + } + // #RRGGBB -> \07RRGGBB + case 6: { + FormatEx(result, sizeof(result), "\x07%s", tag[1]); + } + // #RRGGBBAA -> \08RRGGBBAA + case 8: { + FormatEx(result, sizeof(result), "\x08%s", tag[1]); + } + default: { + result[0] = '\0'; + } + } + + return; + } + else { + // Try to handle this string as color name + int n = Array_FindString(chatColorTags, sizeof(chatColorTags), tag); + + // Check if this tag is invalid + if (n == -1) { + result[0] = '\0'; + return; + } + + // Check if the color is actually supported 'n stuff. + Color_GetChatColorInfo(n, subject); + + result[0] = chatColorInfo[n].ChatColorInfo_Code; + result[1] = '\0'; + } + + return; +} + +/** + * Strips all color control characters in a string. + * The Output buffer can be the same as the input buffer. + * Original code by Psychonic, thanks. + * + * @param input Input String. + * @param output Output String. + * @param size Max Size of the Output string + */ +stock void Color_StripFromChatText(const char[] input, char[] output, int size) +{ + int x = 0; + for (int i=0; input[i] != '\0'; i++) { + + if (x+1 == size) { + break; + } + + char character = input[i]; + + if (character > 0x08) { + output[x++] = character; + } + } + + output[x] = '\0'; +} + +/** + * Checks the gamename and sets default values. + * For example if some colors are supported, or + * if a game uses another color code for a specific color. + * All those hardcoded default values can be overriden in + * smlib's color gamedata file. + */ +static stock void Color_ChatInitialize() +{ + static bool initialized = false; + + if (initialized) { + return; + } + + initialized = true; + + // Normal + chatColorInfo[ChatColor_Normal].ChatColorInfo_Code = '\x01'; + chatColorInfo[ChatColor_Normal].ChatColorInfo_Alternative = -1; /* None */ + chatColorInfo[ChatColor_Normal].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Normal].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + // Orange + chatColorInfo[ChatColor_Orange].ChatColorInfo_Code = '\x01'; + chatColorInfo[ChatColor_Orange].ChatColorInfo_Alternative = 0; /* None */ + chatColorInfo[ChatColor_Orange].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Orange].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + // Red + chatColorInfo[ChatColor_Red].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Red].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Red].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Red].ChatColorInfo_SubjectType = view_as(2); + + // Red, Blue + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_Alternative = 4; /* Blue */ + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_SubjectType = view_as(2); + + // Blue + chatColorInfo[ChatColor_Blue].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Blue].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Blue].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Blue].ChatColorInfo_SubjectType = view_as(3); + + // Blue, Red + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_Alternative = 2; /* Red */ + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_SubjectType = view_as(3); + + // Team + chatColorInfo[ChatColor_Team].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Team].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Team].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Team].ChatColorInfo_SubjectType = ChatColorSubjectType_player; + + // Light green + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_SubjectType = ChatColorSubjectType_world; + + // Gray + chatColorInfo[ChatColor_Gray].ChatColorInfo_Code = '\x03'; + chatColorInfo[ChatColor_Gray].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Gray].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Gray].ChatColorInfo_SubjectType = ChatColorSubjectType_undefined; + + // Green + chatColorInfo[ChatColor_Green].ChatColorInfo_Code = '\x04'; + chatColorInfo[ChatColor_Green].ChatColorInfo_Alternative = 0; /* Normal*/ + chatColorInfo[ChatColor_Green].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Green].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + // Olive green + chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_Code = '\x05'; + chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Olivegreen].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + // Black + chatColorInfo[ChatColor_Black].ChatColorInfo_Code = '\x06'; + chatColorInfo[ChatColor_Black].ChatColorInfo_Alternative = 9; /* Green */ + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Black].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + char gameFolderName[PLATFORM_MAX_PATH]; + GetGameFolderName(gameFolderName, sizeof(gameFolderName)); + + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = false; + + if (strncmp(gameFolderName, "left4dead", 9, false) != 0 && + !StrEqual(gameFolderName, "cstrike", false) && + !StrEqual(gameFolderName, "tf", false)) + { + chatColorInfo[ChatColor_Lightgreen].ChatColorInfo_Supported = false; + chatColorInfo[ChatColor_Gray].ChatColorInfo_Supported = false; + } + + if (StrEqual(gameFolderName, "tf", false)) { + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true; + + chatColorInfo[ChatColor_Gray].ChatColorInfo_Code = '\x01'; + chatColorInfo[ChatColor_Gray].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + } + else if (strncmp(gameFolderName, "left4dead", 9, false) == 0) { + chatColorInfo[ChatColor_Red].ChatColorInfo_SubjectType = view_as(3); + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_SubjectType = view_as(3); + chatColorInfo[ChatColor_Blue].ChatColorInfo_SubjectType = view_as(2); + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_SubjectType = view_as(2); + + chatColorInfo[ChatColor_Orange].ChatColorInfo_Code = '\x04'; + chatColorInfo[ChatColor_Green].ChatColorInfo_Code = '\x05'; + } + else if (StrEqual(gameFolderName, "hl2mp", false)) { + chatColorInfo[ChatColor_Red].ChatColorInfo_SubjectType = view_as(3); + chatColorInfo[ChatColor_RedBlue].ChatColorInfo_SubjectType = view_as(3); + chatColorInfo[ChatColor_Blue].ChatColorInfo_SubjectType = view_as(2); + chatColorInfo[ChatColor_BlueRed].ChatColorInfo_SubjectType = view_as(2); + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true; + + checkTeamPlay = true; + } + else if (StrEqual(gameFolderName, "dod", false)) { + chatColorInfo[ChatColor_Gray].ChatColorInfo_Code = '\x01'; + chatColorInfo[ChatColor_Gray].ChatColorInfo_SubjectType = ChatColorSubjectType_none; + + chatColorInfo[ChatColor_Black].ChatColorInfo_Supported = true; + chatColorInfo[ChatColor_Orange].ChatColorInfo_Supported = false; + } + + if (GetUserMessageId("SayText2") == INVALID_MESSAGE_ID) { + isSayText2_supported = false; + } + + char path_gamedata[PLATFORM_MAX_PATH]; + BuildPath(Path_SM, path_gamedata, sizeof(path_gamedata), "gamedata/%s.txt", SMLIB_COLORS_GAMEDATAFILE); + + if (FileExists(path_gamedata)) { + Handle gamedata = INVALID_HANDLE; + + if ((gamedata = LoadGameConfigFile(SMLIB_COLORS_GAMEDATAFILE)) != INVALID_HANDLE) { + + char keyName[32], buffer[6]; + + for (int i=0; i < sizeof(chatColorNames); i++) { + + Format(keyName, sizeof(keyName), "%s_code", chatColorNames[i]); + if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) { + chatColorInfo[i].ChatColorInfo_Code = StringToInt(buffer); + } + + Format(keyName, sizeof(keyName), "%s_alternative", chatColorNames[i]); + if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) { + chatColorInfo[i].ChatColorInfo_Alternative = buffer[0]; + } + + Format(keyName, sizeof(keyName), "%s_supported", chatColorNames[i]); + if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) { + chatColorInfo[i].ChatColorInfo_Supported = StrEqual(buffer, "true"); + } + + Format(keyName, sizeof(keyName), "%s_subjecttype", chatColorNames[i]); + if (GameConfGetKeyValue(gamedata, keyName, buffer, sizeof(buffer))) { + chatColorInfo[i].ChatColorInfo_SubjectType = view_as(StringToInt(buffer)); + } + } + + if (GameConfGetKeyValue(gamedata, "checkteamplay", buffer, sizeof(buffer))) { + checkTeamPlay = StrEqual(buffer, "true"); + } + + CloseHandle(gamedata); + } + } + + mp_teamplay = FindConVar("mp_teamplay"); +} + +/** + * Checks if the passed color index is actually supported + * for the current game. If not, the index will be overwritten + * The color resolving works recursively until a valid color is found. + * + * @param index + * @param subject A client index or CHATCOLOR_NOSUBJECT + */ +static stock int Color_GetChatColorInfo(int &index, int &subject=CHATCOLOR_NOSUBJECT) +{ + Color_ChatInitialize(); + + if (index == -1) { + index = 0; + } + + while (!chatColorInfo[index].ChatColorInfo_Supported) { + + int alternative = chatColorInfo[index].ChatColorInfo_Alternative; + + if (alternative == -1) { + index = 0; + break; + } + + index = alternative; + } + + if (index == -1) { + index = 0; + } + + int newSubject = CHATCOLOR_NOSUBJECT; + ChatColorSubjectType type = chatColorInfo[index].ChatColorInfo_SubjectType; + + switch (type) { + case ChatColorSubjectType_none: { + } + case ChatColorSubjectType_player: { + newSubject = chatSubject; + } + case ChatColorSubjectType_undefined: { + newSubject = -1; + } + case ChatColorSubjectType_world: { + newSubject = 0; + } + default: { + + if (!checkTeamPlay || mp_teamplay.BoolValue) { + + if (subject > 0 && subject <= MaxClients) { + + if (GetClientTeam(subject) == view_as(type)) { + newSubject = subject; + } + } + else if (subject == CHATCOLOR_NOSUBJECT) { + int client = Team_GetAnyClient(view_as(type)); + + if (client != -1) { + newSubject = client; + } + } + } + } + } + + if (type > ChatColorSubjectType_none && + ((subject != CHATCOLOR_NOSUBJECT && subject != newSubject) || newSubject == CHATCOLOR_NOSUBJECT || !isSayText2_supported)) + { + index = chatColorInfo[index].ChatColorInfo_Alternative; + newSubject = Color_GetChatColorInfo(index, subject); + } + + // Only set the subject if there is no subject set already. + if (subject == CHATCOLOR_NOSUBJECT) { + subject = newSubject; + } + + return newSubject; +} diff --git a/addons/sourcemod/scripting/include/smlib/concommands.inc b/addons/sourcemod/scripting/include/smlib/concommands.inc new file mode 100644 index 0000000..d3909f2 --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/concommands.inc @@ -0,0 +1,45 @@ +#if defined _smlib_concommands_included + #endinput +#endif +#define _smlib_concommands_included + +#include +#include + +/** + * Checks if a ConCommand has one or more flags set. + * + * @param command ConCommand name. + * @param flags Flags to check. + * @return True if flags are set, false otherwise. + */ +stock bool ConCommand_HasFlags(const char[] command, int flags) +{ + return GetCommandFlags(command) & flags > 0; +} + +/** + * Adds one or more flags to a ConCommand. + * + * @param command ConCommand name. + * @param flags Flags to add. + */ +stock void ConCommand_AddFlags(const char[] command, int flags) +{ + int newFlags = GetCommandFlags(command); + newFlags |= flags; + SetCommandFlags(command, newFlags); +} + +/** + * Removes one ore more flags from a ConCommand. + * + * @param command ConCommand name. + * @param flags Flags to remove + */ +stock void ConCommand_RemoveFlags(const char[] command, int flags) +{ + int newFlags = GetCommandFlags(command); + newFlags &= ~flags; + SetCommandFlags(command, newFlags); +} diff --git a/addons/sourcemod/scripting/include/smlib/convars.inc b/addons/sourcemod/scripting/include/smlib/convars.inc new file mode 100644 index 0000000..8da1529 --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/convars.inc @@ -0,0 +1,71 @@ +#if defined _smlib_convars_included + #endinput +#endif +#define _smlib_convars_included + +#include + +/** + * Checks if a ConVar has one or more flags set. + * + * @param convar ConVar Handle. + * @param flags Flags to check. + * @return True if flags are set, false otherwise. + */ +stock bool Convar_HasFlags(ConVar convar, int flags) +{ + return convar.Flags & flags > 0; +} + +/** + * Adds one or more flags to a ConVar. + * + * @param convar ConVar Handle. + * @param flags Flags to add. + */ +stock void Convar_AddFlags(ConVar convar, int flags) +{ + int newFlags = convar.Flags; + newFlags |= flags; + convar.Flags = newFlags; +} + +/** + * Removes one ore more flags from a ConVar. + * + * @param convar ConVar Handle. + * @param flags Flags to remove + * @noreturn + */ +stock void Convar_RemoveFlags(ConVar convar, int flags) +{ + int newFlags = convar.Flags; + newFlags &= ~flags; + convar.Flags = newFlags; +} + +/** + * Checks if a String is a valid ConVar or + * Console Command name. + * + * @param name String Name. + * @return True if the name specified is a valid ConVar or console command name, false otherwise. + */ +stock bool Convar_IsValidName(const char[] name) +{ + if (name[0] == '\0') { + return false; + } + + int n=0; + while (name[n] != '\0') { + + if (!IsValidConVarChar(name[n])) { + return false; + } + + n++; + } + + return true; +} diff --git a/addons/sourcemod/scripting/include/smlib/crypt.inc b/addons/sourcemod/scripting/include/smlib/crypt.inc new file mode 100644 index 0000000..e2903e9 --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/crypt.inc @@ -0,0 +1,625 @@ +#if defined _smlib_crypt_included + #endinput +#endif +#define _smlib_crypt_included + +#include + +/********************************************************************************** + * + * Base64 Encoding/Decoding Functions + * All Credits to to SirLamer & ScriptCoderPro + * Taken from http://forums.alliedmods.net/showthread.php?t=101764 + * + ***********************************************************************************/ + +// The Base64 encoding table +static const char base64_sTable[] = + // 0000000000111111111122222222223333333333444444444455555555556666 + // 0123456789012345678901234567890123456789012345678901234567890123 + "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +// The Base64 decoding table +static const int base64_decodeTable[] = { +// 0 1 2 3 4 5 6 7 8 9 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 9 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 10 - 19 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20 - 29 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 30 - 39 + 0, 0, 0, 62, 0, 0, 0, 63, 52, 53, // 40 - 49 + 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, // 50 - 59 + 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, // 60 - 69 + 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 70 - 79 + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 80 - 89 + 25, 0, 0, 0, 0, 0, 0, 26, 27, 28, // 90 - 99 + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // 100 - 109 + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, // 110 - 119 + 49, 50, 51, 0, 0, 0, 0, 0, 0, 0, // 120 - 129 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 130 - 139 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 140 - 149 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 150 - 159 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 160 - 169 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 170 - 179 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 180 - 189 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 190 - 199 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 200 - 209 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 210 - 219 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 220 - 229 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 230 - 239 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 240 - 249 + 0, 0, 0, 0, 0, 0 // 250 - 256 +}; + +/* + * For some reason the standard demands a string in 24-bit (3 character) intervals. + * This fill character is used to identify unused bytes at the end of the string. + */ +static const char base64_cFillChar = '='; + +// The conversion characters between the standard and URL-compliance Base64 protocols +static const char base64_mime_chars[] = "+/="; +static const char base64_url_chars[] = "-_."; + +/* + * Encodes a string or binary data into Base64 + * + * @param sString The input string or binary data to be encoded. + * @param sResult The storage buffer for the Base64-encoded result. + * @param len The maximum length of the storage buffer, in characters/bytes. + * @param sourcelen (optional): The number of characters or length in bytes to be read from the input source. + * This is not needed for a text string, but is important for binary data since there is no end-of-line character. + * @return The length of the written Base64 string, in bytes. + */ +stock int Crypt_Base64Encode(const char[] sString, char[] sResult, int len, int sourcelen=0) +{ + int nLength; // The string length to be read from the input + int resPos; // The string position in the result buffer + + // If the read length was specified, use it; otherwise, pull the string length from the input. + if (sourcelen > 0) { + nLength = sourcelen; + } + else { + nLength = strlen(sString); + } + + // Loop through and generate the Base64 encoded string + // NOTE: This performs the standard encoding process. Do not manipulate the logic within this loop. + for (int nPos = 0; nPos < nLength; nPos++) { + int cCode; + + cCode = (sString[nPos] >> 2) & 0x3f; + + resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]); + + cCode = (sString[nPos] << 4) & 0x3f; + if (++nPos < nLength) { + cCode |= (sString[nPos] >> 4) & 0x0f; + } + resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]); + + if ( nPos < nLength ) { + cCode = (sString[nPos] << 2) & 0x3f; + if (++nPos < nLength) { + cCode |= (sString[nPos] >> 6) & 0x03; + } + + resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]); + } + else { + nPos++; + resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_cFillChar); + } + + if (nPos < nLength) { + cCode = sString[nPos] & 0x3f; + resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_sTable[cCode]); + } + else { + resPos += FormatEx(sResult[resPos], len - resPos, "%c", base64_cFillChar); + } + } + + return resPos; +} + + +/* + * Decodes a Base64 string. + * + * @param sString The input string in compliant Base64 format to be decoded. + * @param sResult The storage buffer for the decoded text strihg or binary data. + * @param len The maximum length of the storage buffer, in characters/bytes. + * @return The length of the decoded data, in bytes. + */ +stock int Crypt_Base64Decode(const char[] sString, char[] sResult, int len) +{ + int nLength = strlen(sString); // The string length to be read from the input + int resPos; // The string position in the result buffer + + // Loop through and generate the Base64 encoded string + // NOTE: This performs the standard encoding process. Do not manipulate the logic within this loop. + for (int nPos = 0; nPos < nLength; nPos++) { + + int c, c1; + + c = base64_decodeTable[sString[nPos++]]; + c1 = base64_decodeTable[sString[nPos]]; + + c = (c << 2) | ((c1 >> 4) & 0x3); + + resPos += FormatEx(sResult[resPos], len - resPos, "%c", c); + + if (++nPos < nLength) { + + c = sString[nPos]; + + if (c == base64_cFillChar) + break; + + c = base64_decodeTable[sString[nPos]]; + c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf); + + resPos += FormatEx(sResult[resPos], len - resPos, "%c", c1); + } + + if (++nPos < nLength) { + + c1 = sString[nPos]; + + if (c1 == base64_cFillChar) + break; + + c1 = base64_decodeTable[sString[nPos]]; + c = ((c << 6) & 0xc0) | c1; + + resPos += FormatEx(sResult[resPos], len - resPos, "%c", c); + } + } + + return resPos; +} + + +/* + * Converts a standards-compliant Base64 string to the commonly accepted URL-compliant alternative. + * Note: The result will be the same length as the input string as long as the output buffer is large enough. + * + * @param sString The standards-compliant Base64 input string to converted. + * @param sResult The storage buffer for the URL-compliant result. + * @param len The maximum length of the storage buffer in characters/bytes. + * @return Number of cells written. + */ +stock int Crypt_Base64MimeToUrl(const char[] sString, char[] sResult, int len) +{ + int chars_len = sizeof(base64_mime_chars); // Length of the two standards vs. URL character lists + int nLength; // The string length to be read from the input + int temp_char; // Buffer character + + nLength = strlen(sString); + + char[] sTemp = new char[nLength+1]; // Buffer string + + // Loop through string + for (int i = 0; i < nLength; i++) { + temp_char = sString[i]; + + for (int j = 0; j < chars_len; j++) { + + if(temp_char == base64_mime_chars[j]) { + temp_char = base64_url_chars[j]; + break; + } + } + + sTemp[i] = temp_char; + } + + sTemp[nLength] = '\0'; + + return strcopy(sResult, len, sTemp); +} + +/* + * Base64UrlToMime(String:sResult[], len, const String:sString[], sourcelen) + * Converts a URL-compliant Base64 string to the standards-compliant version. + * Note: The result will be the same length as the input string as long as the output buffer is large enough. + * + * @param sString The URL-compliant Base64 input string to converted. + * @param sResult The storage buffer for the standards-compliant result. + * @param len The maximum length of the storage buffer in characters/bytes. + * @return Number of cells written. + */ +stock int Crypt_Base64UrlToMime(const char[] sString, char[] sResult, int len) +{ + int chars_len = sizeof(base64_mime_chars); // Length of the two standards vs. URL character lists + int nLength; // The string length to be read from the input + int temp_char; // Buffer character + + nLength = strlen(sString); + + char[] sTemp = new char[nLength+1]; // Buffer string + + // Loop through string + for (int i = 0; i < nLength; i++) { + temp_char = sString[i]; + for (int j = 0; j < chars_len; j++) { + if (temp_char == base64_url_chars[j]) { + temp_char = base64_mime_chars[j]; + break; + } + } + + sTemp[i] = temp_char; + } + + sTemp[nLength] = '\0'; + + return strcopy(sResult, len, sTemp); +} + +/********************************************************************************** + * + * MD5 Encoding Functions + * All Credits go to sslice + * RSA Data Security, Inc. MD5 Message Digest Algorithm + * Taken from http://forums.alliedmods.net/showthread.php?t=67683 + * + ***********************************************************************************/ + +/* + * Calculate the md5 hash of a string. + * + * @param str Input String + * @param output Output String Buffer + * @param maxlen Size of the Output String Buffer + */ +stock void Crypt_MD5(const char[] str, char[] output, int maxlen) +{ + int x[2]; + int buf[4]; + int input[64]; + int i, ii; + + int len = strlen(str); + + // MD5Init + x[0] = x[1] = 0; + buf[0] = 0x67452301; + buf[1] = 0xefcdab89; + buf[2] = 0x98badcfe; + buf[3] = 0x10325476; + + // MD5Update + int update[16]; + + update[14] = x[0]; + update[15] = x[1]; + + int mdi = (x[0] >>> 3) & 0x3F; + + if ((x[0] + (len << 3)) < x[0]) { + x[1] += 1; + } + + x[0] += len << 3; + x[1] += len >>> 29; + + int c = 0; + while (len--) { + input[mdi] = str[c]; + mdi += 1; + c += 1; + + if (mdi == 0x40) { + + for (i = 0, ii = 0; i < 16; ++i, ii += 4) + { + update[i] = (input[ii + 3] << 24) | (input[ii + 2] << 16) | (input[ii + 1] << 8) | input[ii]; + } + + // Transform + MD5Transform(buf, update); + + mdi = 0; + } + } + + // MD5Final + int padding[64] = { + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 + }; + + int inx[16]; + inx[14] = x[0]; + inx[15] = x[1]; + + mdi = (x[0] >>> 3) & 0x3F; + + len = (mdi < 56) ? (56 - mdi) : (120 - mdi); + update[14] = x[0]; + update[15] = x[1]; + + mdi = (x[0] >>> 3) & 0x3F; + + if ((x[0] + (len << 3)) < x[0]) { + x[1] += 1; + } + + x[0] += len << 3; + x[1] += len >>> 29; + + c = 0; + while (len--) { + input[mdi] = padding[c]; + mdi += 1; + c += 1; + + if (mdi == 0x40) { + + for (i = 0, ii = 0; i < 16; ++i, ii += 4) { + update[i] = (input[ii + 3] << 24) | (input[ii + 2] << 16) | (input[ii + 1] << 8) | input[ii]; + } + + // Transform + MD5Transform(buf, update); + + mdi = 0; + } + } + + for (i = 0, ii = 0; i < 14; ++i, ii += 4) { + inx[i] = (input[ii + 3] << 24) | (input[ii + 2] << 16) | (input[ii + 1] << 8) | input[ii]; + } + + MD5Transform(buf, inx); + + int digest[16]; + for (i = 0, ii = 0; i < 4; ++i, ii += 4) { + digest[ii] = (buf[i]) & 0xFF; + digest[ii + 1] = (buf[i] >>> 8) & 0xFF; + digest[ii + 2] = (buf[i] >>> 16) & 0xFF; + digest[ii + 3] = (buf[i] >>> 24) & 0xFF; + } + + FormatEx(output, maxlen, "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", + digest[0], digest[1], digest[2], digest[3], digest[4], digest[5], digest[6], digest[7], + digest[8], digest[9], digest[10], digest[11], digest[12], digest[13], digest[14], digest[15]); +} + +static stock void MD5Transform_FF(int &a, int &b, int &c, int &d, int x, int s, int ac) +{ + a += (((b) & (c)) | ((~b) & (d))) + x + ac; + a = (((a) << (s)) | ((a) >>> (32-(s)))); + a += b; +} + +static stock void MD5Transform_GG(int &a, int &b, int &c, int &d, int x, int s, int ac) +{ + a += (((b) & (d)) | ((c) & (~d))) + x + ac; + a = (((a) << (s)) | ((a) >>> (32-(s)))); + a += b; +} + +static stock void MD5Transform_HH(int &a, int &b, int &c, int &d, int x, int s, int ac) + { + a += ((b) ^ (c) ^ (d)) + x + ac; + a = (((a) << (s)) | ((a) >>> (32-(s)))); + a += b; +} + +static stock void MD5Transform_II(int &a, int &b, int &c, int &d, int x, int s, int ac) +{ + a += ((c) ^ ((b) | (~d))) + x + ac; + a = (((a) << (s)) | ((a) >>> (32-(s)))); + a += b; +} + +static stock void MD5Transform(int[] buf, int[] input){ + int a = buf[0]; + int b = buf[1]; + int c = buf[2]; + int d = buf[3]; + + MD5Transform_FF(a, b, c, d, input[0], 7, 0xd76aa478); + MD5Transform_FF(d, a, b, c, input[1], 12, 0xe8c7b756); + MD5Transform_FF(c, d, a, b, input[2], 17, 0x242070db); + MD5Transform_FF(b, c, d, a, input[3], 22, 0xc1bdceee); + MD5Transform_FF(a, b, c, d, input[4], 7, 0xf57c0faf); + MD5Transform_FF(d, a, b, c, input[5], 12, 0x4787c62a); + MD5Transform_FF(c, d, a, b, input[6], 17, 0xa8304613); + MD5Transform_FF(b, c, d, a, input[7], 22, 0xfd469501); + MD5Transform_FF(a, b, c, d, input[8], 7, 0x698098d8); + MD5Transform_FF(d, a, b, c, input[9], 12, 0x8b44f7af); + MD5Transform_FF(c, d, a, b, input[10], 17, 0xffff5bb1); + MD5Transform_FF(b, c, d, a, input[11], 22, 0x895cd7be); + MD5Transform_FF(a, b, c, d, input[12], 7, 0x6b901122); + MD5Transform_FF(d, a, b, c, input[13], 12, 0xfd987193); + MD5Transform_FF(c, d, a, b, input[14], 17, 0xa679438e); + MD5Transform_FF(b, c, d, a, input[15], 22, 0x49b40821); + + MD5Transform_GG(a, b, c, d, input[1], 5, 0xf61e2562); + MD5Transform_GG(d, a, b, c, input[6], 9, 0xc040b340); + MD5Transform_GG(c, d, a, b, input[11], 14, 0x265e5a51); + MD5Transform_GG(b, c, d, a, input[0], 20, 0xe9b6c7aa); + MD5Transform_GG(a, b, c, d, input[5], 5, 0xd62f105d); + MD5Transform_GG(d, a, b, c, input[10], 9, 0x02441453); + MD5Transform_GG(c, d, a, b, input[15], 14, 0xd8a1e681); + MD5Transform_GG(b, c, d, a, input[4], 20, 0xe7d3fbc8); + MD5Transform_GG(a, b, c, d, input[9], 5, 0x21e1cde6); + MD5Transform_GG(d, a, b, c, input[14], 9, 0xc33707d6); + MD5Transform_GG(c, d, a, b, input[3], 14, 0xf4d50d87); + MD5Transform_GG(b, c, d, a, input[8], 20, 0x455a14ed); + MD5Transform_GG(a, b, c, d, input[13], 5, 0xa9e3e905); + MD5Transform_GG(d, a, b, c, input[2], 9, 0xfcefa3f8); + MD5Transform_GG(c, d, a, b, input[7], 14, 0x676f02d9); + MD5Transform_GG(b, c, d, a, input[12], 20, 0x8d2a4c8a); + + MD5Transform_HH(a, b, c, d, input[5], 4, 0xfffa3942); + MD5Transform_HH(d, a, b, c, input[8], 11, 0x8771f681); + MD5Transform_HH(c, d, a, b, input[11], 16, 0x6d9d6122); + MD5Transform_HH(b, c, d, a, input[14], 23, 0xfde5380c); + MD5Transform_HH(a, b, c, d, input[1], 4, 0xa4beea44); + MD5Transform_HH(d, a, b, c, input[4], 11, 0x4bdecfa9); + MD5Transform_HH(c, d, a, b, input[7], 16, 0xf6bb4b60); + MD5Transform_HH(b, c, d, a, input[10], 23, 0xbebfbc70); + MD5Transform_HH(a, b, c, d, input[13], 4, 0x289b7ec6); + MD5Transform_HH(d, a, b, c, input[0], 11, 0xeaa127fa); + MD5Transform_HH(c, d, a, b, input[3], 16, 0xd4ef3085); + MD5Transform_HH(b, c, d, a, input[6], 23, 0x04881d05); + MD5Transform_HH(a, b, c, d, input[9], 4, 0xd9d4d039); + MD5Transform_HH(d, a, b, c, input[12], 11, 0xe6db99e5); + MD5Transform_HH(c, d, a, b, input[15], 16, 0x1fa27cf8); + MD5Transform_HH(b, c, d, a, input[2], 23, 0xc4ac5665); + + MD5Transform_II(a, b, c, d, input[0], 6, 0xf4292244); + MD5Transform_II(d, a, b, c, input[7], 10, 0x432aff97); + MD5Transform_II(c, d, a, b, input[14], 15, 0xab9423a7); + MD5Transform_II(b, c, d, a, input[5], 21, 0xfc93a039); + MD5Transform_II(a, b, c, d, input[12], 6, 0x655b59c3); + MD5Transform_II(d, a, b, c, input[3], 10, 0x8f0ccc92); + MD5Transform_II(c, d, a, b, input[10], 15, 0xffeff47d); + MD5Transform_II(b, c, d, a, input[1], 21, 0x85845dd1); + MD5Transform_II(a, b, c, d, input[8], 6, 0x6fa87e4f); + MD5Transform_II(d, a, b, c, input[15], 10, 0xfe2ce6e0); + MD5Transform_II(c, d, a, b, input[6], 15, 0xa3014314); + MD5Transform_II(b, c, d, a, input[13], 21, 0x4e0811a1); + MD5Transform_II(a, b, c, d, input[4], 6, 0xf7537e82); + MD5Transform_II(d, a, b, c, input[11], 10, 0xbd3af235); + MD5Transform_II(c, d, a, b, input[2], 15, 0x2ad7d2bb); + MD5Transform_II(b, c, d, a, input[9], 21, 0xeb86d391); + + buf[0] += a; + buf[1] += b; + buf[2] += c; + buf[3] += d; +} + +/********************************************************************************** + * + * RC4 Encoding Functions + * All Credits go to SirLamer and Raydan + * Taken from http://forums.alliedmods.net/showthread.php?t=101834 + * + ***********************************************************************************/ + +/* + * Encrypts a text string using RC4. + * Note: This function is NOT binary safe. + * Use Crypt_RC4EncodeBinary to encode binary data. + * + * @param input The source data to be encrypted. + * @param pwd The password/key used to encode and decode the data. + * @param output The encoded result. + * @param maxlen The maximum length of the output buffer. + */ +stock void Crypt_RC4Encode(const char[] input, const char[] pwd, char[] output, int maxlen) +{ + int pwd_len,str_len,i,j,a,k; + int key[256]; + int box[256]; + int tmp; + + pwd_len = strlen(pwd); + str_len = strlen(input); + + if (pwd_len > 0 && str_len > 0) { + + for (i=0; i < 256; i++) { + key[i] = pwd[i%pwd_len]; + box[i]=i; + } + + i=0; j=0; + + for (; i < 256; i++) { + j = (j + box[i] + key[i]) % 256; + tmp = box[i]; + box[i] = box[j]; + box[j] = tmp; + } + + i=0; j=0; a=0; + + for (; i < str_len; i++) { + a = (a + 1) % 256; + j = (j + box[a]) % 256; + tmp = box[a]; + box[a] = box[j]; + box[j] = tmp; + k = box[((box[a] + box[j]) % 256)]; + FormatEx(output[2*i], maxlen-2*i, "%02x", input[i] ^ k); + } + } +} + +/* + * Encrypts binary data using RC4. + * + * @param input The source data to be encrypted. + * @param str_len The length of the source data. + * @param pwd The password/key used to encode and decode the data. + * @param output The encoded result. + * @param maxlen The maximum length of the output buffer. + */ +stock int Crypt_RC4EncodeBinary(const char[] input, int str_len, const char[] pwd, char[] output, int maxlen) +{ + int pwd_len,i,j,a,k; + int key[256]; + int box[256]; + int tmp; + + pwd_len = strlen(pwd); + + if (pwd_len > 0 && str_len > 0) { + + for(i=0;i<256;i++) { + key[i] = pwd[i%pwd_len]; + box[i]=i; + } + + i=0; j=0; + + for (; i < 256; i++) { + j = (j + box[i] + key[i]) % 256; + tmp = box[i]; + box[i] = box[j]; + box[j] = tmp; + } + + i=0; j=0; a=0; + + if (str_len+1 > maxlen) { + str_len = maxlen - 1; + } + + for(; i < str_len; i++) { + a = (a + 1) % 256; + j = (j + box[a]) % 256; + tmp = box[a]; + box[a] = box[j]; + box[j] = tmp; + k = box[((box[a] + box[j]) % 256)]; + FormatEx(output[i], maxlen-i, "%c", input[i] ^ k); + } + + /* + * i = number of written bits (remember increment occurs at end of for loop, and THEN it fails the loop condition) + * Since we're working with binary data, the calling function should not depend on the escape + * character, but putting it here prevents crashes in case someone tries to read the data like a string + */ + output[i] = '\0'; + + return i; + } + else { + return -1; + } +} diff --git a/addons/sourcemod/scripting/include/smlib/debug.inc b/addons/sourcemod/scripting/include/smlib/debug.inc new file mode 100644 index 0000000..a2cb7f9 --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/debug.inc @@ -0,0 +1,28 @@ +#if defined _smlib_debug_included + #endinput +#endif +#define _smlib_debug_included + +#include + +/** + * Prints the values of a static Float-Array to the server console. + * + * @param array Static Float-Array. + * @param size Size of the Array. + */ +stock void Debug_FloatArray(const float[] array, int size=3) +{ + char output[64] = ""; + + for (int i=0; i < size; ++i) { + + if (i > 0 && i < size) { + StrCat(output, sizeof(output), ", "); + } + + Format(output, sizeof(output), "%s%f", output, array[i]); + } + + PrintToServer("[DEBUG] Vector[%d] = { %s }", size, output); +} diff --git a/addons/sourcemod/scripting/include/smlib/dynarrays.inc b/addons/sourcemod/scripting/include/smlib/dynarrays.inc new file mode 100644 index 0000000..fb85593 --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/dynarrays.inc @@ -0,0 +1,24 @@ +#if defined _smlib_dynarray_included + #endinput +#endif +#define _smlib_dynarray_included + +#include + +/** + * Retrieves a cell value from an array. + * This is a wrapper around the Sourcemod Function GetArrayCell, + * but it casts the result as bool + * + * @param array Array Handle. + * @param index Index in the array. + * @param block Optionally specify which block to read from + * (useful if the blocksize > 0). + * @param asChar Optionally read as a byte instead of a cell. + * @return Value read. + * @error Invalid Handle, invalid index, or invalid block. + */ +stock bool DynArray_GetBool(ArrayList array, int index, int block=0, bool asChar=false) +{ + return array.Get(index, block, asChar) != 0; +} diff --git a/addons/sourcemod/scripting/include/smlib/edicts.inc b/addons/sourcemod/scripting/include/smlib/edicts.inc new file mode 100644 index 0000000..ca6cd13 --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/edicts.inc @@ -0,0 +1,127 @@ +#if defined _smlib_edicts_included + #endinput +#endif +#define _smlib_edicts_included + +#include +#include + +/* + * Finds an edict by it's name + * It only finds the first occurence. + * + * @param name Name of the entity you want so search. + * @return Edict Index or INVALID_ENT_REFERENCE if no entity was found. + */ +stock int Edict_FindByName(const char[] name) +{ + int maxEntities = GetMaxEntities(); + for (int edict=0; edict < maxEntities; edict++) { + + if (!IsValidEdict(edict)) { + continue; + } + + if (Entity_NameMatches(edict, name)) { + return edict; + } + } + + return INVALID_ENT_REFERENCE; +} + +/* + * Finds an edict by its HammerID. + * The newer version of Valve's Hammer editor + * sets a unique ID for each entity in a map. + * It only finds the first occurence. + * + * @param hammerId Hammer editor ID + * @return Edict Index or INVALID_ENT_REFERENCE if no entity was found. + */ +stock int Edict_FindByHammerId(int hammerId) +{ + int maxEntities = GetMaxEntities(); + for (int edict=0; edict < maxEntities; edict++) { + + if (!IsValidEdict(edict)) { + continue; + } + + if (Entity_GetHammerId(edict) == hammerId) { + return edict; + } + } + + return INVALID_ENT_REFERENCE; +} + +/** + * Searches for the closest edict in relation to the given origin + * + * @param vecOrigin_center 3 dimensional origin array + * @param clientsOnly True if you only want to search for clients + * @param ignoreEntity Ignore this entity + * @return Edict Index or INVALID_ENT_REFERENCE if no entity was found. + */ +stock int Edict_GetClosest(float vecOrigin_center[3], bool clientsOnly=false, int ignoreEntity=-1) +{ + float vecOrigin_edict[3]; + float smallestDistance = 0.0; + int closestEdict = INVALID_ENT_REFERENCE; + + int maxEntities; + + if (clientsOnly) { + maxEntities = MaxClients; + } + else { + maxEntities = GetMaxEntities(); + } + + for (int edict=1; edict <= maxEntities; edict++) { + + if (!IsValidEdict(edict)) { + continue; + } + + if (ignoreEntity >= 0 && edict == ignoreEntity) { + continue; + } + + if (GetEntSendPropOffs(edict, "m_vecOrigin") == -1) { + continue; + } + + Entity_GetAbsOrigin(edict, vecOrigin_edict); + + float edict_distance = GetVectorDistance(vecOrigin_center, vecOrigin_edict, true); + + if (edict_distance < smallestDistance || smallestDistance == 0.0) { + smallestDistance = edict_distance; + closestEdict = edict; + } + } + + return closestEdict; +} + +/** + * Searches for the closest edict in relation to the given edict. + * + * @param edict Edict index + * @param clientsOnly True if you only want to search for clients + * @return The closest edict or INVALID_ENT_REFERENCE + */ +stock int Edict_GetClosestToEdict(int edict, bool clientsOnly=false) +{ + float vecOrigin[3]; + + if (!HasEntProp(edict, Prop_Send, "m_vecOrigin")) { + return INVALID_ENT_REFERENCE; + } + + Entity_GetAbsOrigin(edict, vecOrigin); + + return Edict_GetClosest(vecOrigin, clientsOnly, edict); +} diff --git a/addons/sourcemod/scripting/include/smlib/effects.inc b/addons/sourcemod/scripting/include/smlib/effects.inc new file mode 100644 index 0000000..4e13578 --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/effects.inc @@ -0,0 +1,722 @@ +#if defined _smlib_effects_included + #endinput +#endif +#define _smlib_effects_included + +#include +#include +#include +#include +#include +#include +#include +#include + + + +// Entity Dissolve types +enum DissolveType +{ + DISSOLVE_NORMAL = 0, + DISSOLVE_ELECTRICAL, + DISSOLVE_ELECTRICAL_LIGHT, + DISSOLVE_CORE +}; + +/** + * Dissolves a player + * + * @param client Client Index. + * @param dissolveType Dissolve Type, use the DissolveType enum. + * @param magnitude How strongly to push away from the center. + * @return True on success, otherwise false. + */ +stock bool Effect_DissolveEntity(int entity, DissolveType dissolveType=DISSOLVE_NORMAL, int magnitude=1) +{ + int env_entity_dissolver = CreateEntityByName("env_entity_dissolver"); + + if (env_entity_dissolver == -1) { + return false; + } + + Entity_PointAtTarget(env_entity_dissolver, entity); + SetEntProp(env_entity_dissolver, Prop_Send, "m_nDissolveType", dissolveType); + SetEntProp(env_entity_dissolver, Prop_Send, "m_nMagnitude", magnitude); + AcceptEntityInput(env_entity_dissolver, "Dissolve"); + Entity_Kill(env_entity_dissolver); + + return true; +} + +/** + * Dissolves a player's Ragdoll + * + * @param client Client Index. + * @param dissolveType Dissolve Type, use the DissolveType enum. + * @return True on success, otherwise false. + */ +stock bool Effect_DissolvePlayerRagDoll(int client, DissolveType dissolveType=DISSOLVE_NORMAL) +{ + int m_hRagdoll = GetEntPropEnt(client, Prop_Send, "m_hRagdoll"); + + if (m_hRagdoll == -1) { + return false; + } + + return Effect_DissolveEntity(m_hRagdoll, dissolveType); +} + +typedef EffectCallback = function void(int entity, any data); + +/** + * Fades an entity in our out. + * You can specifiy a callback function which will get called + * when the fade is finished. + * Important: The callback will be called if it is passed, + * no matter if the entity is still valid or not. That means you + * have to check if the entity is valid yourself. + * + * @param entity Entity Index. + * @param fadeOut Optional: Fade the entity out (true) or in (false). + * @param kill Optional: If to kill the entity when the fade is finished. + * @param fast Optional: Fade the entity fast (~0.7 secs) or slow (~3 secs) + * @param callback Optional: You can specify a callback Function that will get called when the fade is finished. + * @param data Optional: You can pass any data to the callback. + */ +stock void Effect_Fade(int entity, bool fadeOut=true, bool kill=false, bool fast=true, EffectCallback callback=INVALID_FUNCTION, any data=0) +{ + float timerTime = 0.0; + + if (fast) { + timerTime = 0.6; + + if (fadeOut) { + SetEntityRenderFx(entity, RENDERFX_FADE_FAST); + } + else { + SetEntityRenderFx(entity, RENDERFX_SOLID_FAST); + } + } + else { + timerTime = 3.0; + + if (fadeOut) { + SetEntityRenderFx(entity, RENDERFX_FADE_SLOW); + } + else { + SetEntityRenderFx(entity, RENDERFX_SOLID_SLOW); + } + } + + ChangeEdictState(entity, GetEntSendPropOffs(entity, "m_nRenderFX", true)); + + if (kill || callback != INVALID_FUNCTION) { + DataPack dataPack = null; + CreateDataTimer(timerTime, _smlib_Timer_Effect_Fade, dataPack, TIMER_FLAG_NO_MAPCHANGE | TIMER_DATA_HNDL_CLOSE); + + WritePackCell(dataPack, EntIndexToEntRef(entity)); + WritePackCell(dataPack, kill); + WritePackFunction(dataPack, callback); + WritePackCell(dataPack, data); + ResetPack(dataPack); + } +} + +/** + * Fades the entity in. + * A wrapper function around Effect_Fade(). + * + * @param entity Entity Index. + * @param fast Optional: Fade the entity fast (~0.7 secs) or slow (~3 secs) + * @param callback Optional: You can specify a callback Function that will get called when the fade is finished. + * @param data Optional: You can pass any data to the callback. + */ +stock void Effect_FadeIn(int entity, bool fast=true, EffectCallback callback=INVALID_FUNCTION, any data=0) +{ + Effect_Fade(entity, false, false, fast, callback, data); +} + +/** + * Fades the entity out. + * A wrapper function around Effect_Fade(). + * + * @param entity Entity Index. + * @param fadeOut Optional: Fade the entity out (true) or in (false). + * @param kill Optional: If to kill the entity when the fade is finished. + * @param fast Optional: Fade the entity fast (~0.7 secs) or slow (~3 secs) + * @param callback Optional: You can specify a callback Function that will get called when the fade is finished. + * @param data Optional: You can pass any data to the callback. + */ +stock void Effect_FadeOut(int entity, bool kill=false, bool fast=true, EffectCallback callback=INVALID_FUNCTION, any data=0) +{ + Effect_Fade(entity, true, kill, fast, callback, data); +} + +public Action _smlib_Timer_Effect_Fade(Handle Timer, DataPack dataPack) +{ + int entity = ReadPackCell(dataPack); + int kill = ReadPackCell(dataPack); + Function callback = ReadPackFunction(dataPack); + any data = ReadPackCell(dataPack); + + if (callback != INVALID_FUNCTION) { + Call_StartFunction(INVALID_HANDLE, callback); + Call_PushCell(entity); + Call_PushCell(data); + Call_Finish(); + } + + if (kill && IsValidEntity(entity)) { + Entity_Kill(entity); + } + + return Plugin_Stop; +} + +/** + * Sends a boxed beam effect to one player. + * + * Ported from eventscripts vecmath library. + * + * @param client The client to show the box to. + * @param bottomCorner One bottom corner of the box. + * @param upperCorner One upper corner of the box. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawBeamBoxToClient( + int client, + const float bottomCorner[3], + const float upperCorner[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 +) { + int clients[1]; + clients[0] = client; + Effect_DrawBeamBox(clients, 1, bottomCorner, upperCorner, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); +} + +/** + * Sends a boxed beam effect to all players. + * + * Ported from eventscripts vecmath library. + * + * @param bottomCorner One bottom corner of the box. + * @param upperCorner One upper corner of the box. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawBeamBoxToAll( + const float bottomCorner[3], + const float upperCorner[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 +) +{ + int[] clients = new int[MaxClients]; + int numClients = Client_Get(clients, CLIENTFILTER_INGAME); + + Effect_DrawBeamBox(clients, numClients, bottomCorner, upperCorner, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); +} + +/** + * Sends a boxed beam effect to a list of players. + * + * Ported from eventscripts vecmath library. + * + * @param clients An array of clients to show the box to. + * @param numClients Number of players in the array. + * @param bottomCorner One bottom corner of the box. + * @param upperCorner One upper corner of the box. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawBeamBox( + int[] clients, + int numClients, + const float bottomCorner[3], + const float upperCorner[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 +) { + // Create the additional corners of the box + float corners[8][3]; + + for (int i=0; i < 4; i++) { + Array_Copy(bottomCorner, corners[i], 3); + Array_Copy(upperCorner, corners[i+4], 3); + } + + corners[1][0] = upperCorner[0]; + corners[2][0] = upperCorner[0]; + corners[2][1] = upperCorner[1]; + corners[3][1] = upperCorner[1]; + corners[4][0] = bottomCorner[0]; + corners[4][1] = bottomCorner[1]; + corners[5][1] = bottomCorner[1]; + corners[7][0] = bottomCorner[0]; + + // Draw all the edges + + // Horizontal Lines + // Bottom + for (int i=0; i < 4; i++) { + int j = ( i == 3 ? 0 : i+1 ); + TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); + TE_Send(clients, numClients); + } + + // Top + for (int i=4; i < 8; i++) { + int j = ( i == 7 ? 4 : i+1 ); + TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); + TE_Send(clients, numClients); + } + + // All Vertical Lines + for (int i=0; i < 4; i++) { + TE_SetupBeamPoints(corners[i], corners[i+4], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); + TE_Send(clients, numClients); + } +} + + +/** + * Sends a boxed beam effect to one player. + * + * Ported from eventscripts vecmath library. + * + * @param client The client to show the box to. + * @param origin Origin/center of the box. + * @param mins Min size Vector + * @param maxs Max size Vector + * @param angles Angles used to rotate the box. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawBeamBoxRotatableToClient( + int client, + const float origin[3], + const float mins[3], + const float maxs[3], + const float angles[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 +) { + int clients[1]; + clients[0] = client; + Effect_DrawBeamBoxRotatable(clients, 1, origin, mins, maxs, angles, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); +} + + + +/** + * Sends a boxed beam effect to all players. + * + * Ported from eventscripts vecmath library. + * + * @param origin Origin/center of the box. + * @param mins Min size Vector + * @param maxs Max size Vector + * @param angles Angles used to rotate the box. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawBeamBoxRotatableToAll( + const float origin[3], + const float mins[3], + const float maxs[3], + const float angles[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 +) +{ + int[] clients = new int[MaxClients]; + int numClients = Client_Get(clients, CLIENTFILTER_INGAME); + + Effect_DrawBeamBoxRotatable(clients, numClients, origin, mins, maxs, angles, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); +} + +/** + * Sends a boxed beam effect to a list of players. + * + * Ported from eventscripts vecmath library. + * + * @param clients An array of clients to show the box to. + * @param numClients Number of players in the array. + * @param origin Origin/center of the box. + * @param mins Min size Vector + * @param maxs Max size Vector + * @param angles Angles used to rotate the box. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawBeamBoxRotatable( + int[] clients, + int numClients, + const float origin[3], + const float mins[3], + const float maxs[3], + const float angles[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + const int color[4]={ 255, 0, 0, 255 }, + int speed=0 +) { + // Create the additional corners of the box + float corners[8][3]; + Array_Copy(mins, corners[0], 3); + Math_MakeVector(maxs[0], mins[1], mins[2], corners[1]); + Math_MakeVector(maxs[0], maxs[1], mins[2], corners[2]); + Math_MakeVector(mins[0], maxs[1], mins[2], corners[3]); + Math_MakeVector(mins[0], mins[1], maxs[2], corners[4]); + Math_MakeVector(maxs[0], mins[1], maxs[2], corners[5]); + Array_Copy(maxs, corners[6], 3); + Math_MakeVector(mins[0], maxs[1], maxs[2], corners[7]); + + // Rotate all edges + for (int i=0; i < sizeof(corners); i++) { + Math_RotateVector(corners[i], angles, corners[i]); + } + + // Apply world offset (after rotation) + for (int i=0; i < sizeof(corners); i++) { + AddVectors(origin, corners[i], corners[i]); + } + + // Draw all the edges + // Horizontal Lines + // Bottom + for (int i=0; i < 4; i++) { + int j = ( i == 3 ? 0 : i+1 ); + TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); + TE_Send(clients, numClients); + } + + // Top + for (int i=4; i < 8; i++) { + int j = ( i == 7 ? 4 : i+1 ); + TE_SetupBeamPoints(corners[i], corners[j], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); + TE_Send(clients, numClients); + } + + // All Vertical Lines + for (int i=0; i < 4; i++) { + TE_SetupBeamPoints(corners[i], corners[i+4], modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, color, speed); + TE_Send(clients, numClients); + } +} + +/** + * Displays the given axis of rotation as beam effect to one player. + * + * @param client The client to show the box to. + * @param origin Origin/center of the box. + * @param angles Angles used to rotate the box. + * @param length The length in each direction. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawAxisOfRotationToClient( + int client, + const float origin[3], + const float angles[3], + const float length[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + int speed=0 +) { + int clients[1]; + clients[0] = client; + Effect_DrawAxisOfRotation(clients, 1, origin, angles, length, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, speed); +} + +/** + * Displays the given axis of rotation as beam effect to all players. + * + * @param origin Origin/center of the box. + * @param angles Angles used to rotate the box. + * @param length The length in each direction. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawAxisOfRotationToAll( + const float origin[3], + const float angles[3], + const float length[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + int speed=0 +) +{ + int[] clients = new int[MaxClients]; + int numClients = Client_Get(clients, CLIENTFILTER_INGAME); + + Effect_DrawAxisOfRotation(clients, numClients, origin, angles, length, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, speed); +} + +/** + * Displays the given axis of rotation as beam effect to a list of players. + * + * @param clients An array of clients to show the box to. + * @param numClients Number of players in the array. + * @param origin Origin/center of the box. + * @param angles Angles used to rotate the box. + * @param length The length in each direction. + * @param modelIndex Precached model index. + * @param haloIndex Precached model index. + * @param startFrame Initital frame to render. + * @param frameRate Beam frame rate. + * @param life Time duration of the beam. + * @param width Initial beam width. + * @param endWidth Final beam width. + * @param fadeLength Beam fade time duration. + * @param amplitude Beam amplitude. + * @param color Color array (r, g, b, a). + * @param speed Speed of the beam. + */ +stock void Effect_DrawAxisOfRotation( + int[] clients, + int numClients, + const float origin[3], + const float angles[3], + const float length[3], + int modelIndex, + int haloIndex, + int startFrame=0, + int frameRate=30, + float life=5.0, + float width=5.0, + float endWidth=5.0, + int fadeLength=2, + float amplitude=1.0, + int speed=0 +) { + // Create the additional corners of the box + float xAxis[3], yAxis[3], zAxis[3]; + xAxis[0] = length[0]; + yAxis[1] = length[1]; + zAxis[2] = length[2]; + + // Rotate all edges + Math_RotateVector(xAxis, angles, xAxis); + Math_RotateVector(yAxis, angles, yAxis); + Math_RotateVector(zAxis, angles, zAxis); + + // Apply world offset (after rotation) + AddVectors(origin, xAxis, xAxis); + AddVectors(origin, yAxis, yAxis); + AddVectors(origin, zAxis, zAxis); + + // Draw all + TE_SetupBeamPoints(origin, xAxis, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, {255, 0, 0, 255}, speed); + TE_Send(clients, numClients); + + TE_SetupBeamPoints(origin, yAxis, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, {0, 255, 0, 255}, speed); + TE_Send(clients, numClients); + + TE_SetupBeamPoints(origin, zAxis, modelIndex, haloIndex, startFrame, frameRate, life, width, endWidth, fadeLength, amplitude, {0, 0, 255, 255}, speed); + TE_Send(clients, numClients); +} + + +/** + * Creates an env_sprite. + * + * @param origin Origin of the Sprite. + * @param modelIndex Precached model index. + * @param color Color array (r, g, b, a). + * @param scale Scale (Note: many materials ignore a lower value than 0.25). + * @param targetName Targetname of the sprite. + * @param parent Entity Index of this sprite's parent in the movement hierarchy. + * @param renderMode Render mode (use the enum). + * @param renderFx Render fx (use the enum). + * @param glowProxySize Radius size of the glow when to be rendered, if inside a geometry. Ex: a block 2x2x2 units big, if the glowProxySize is between 0.0 and 2.0 the sprite will not be rendered, even if the actual size of the sprite is bigger, everything above 2.0 will render the sprite. Using an abnormal high value will render Sprites trough walls. + * @param frameRate Sprite frame rate. + * @param hdrColorScale Float value to multiply sprite color by when running with HDR. + * @param receiveShadows When false then this prevents the sprite from receiving shadows. + * @return Entity Index of the created Sprite. + */ +stock int Effect_EnvSprite( + const float origin[3], + int modelIndex, + const int color[4]={255, 255, 255, 255}, + float scale=0.25, + const char targetName[MAX_NAME_LENGTH]="", + int parent=-1, + RenderMode renderMode=RENDER_WORLDGLOW, + RenderFx renderFx=RENDERFX_NONE, + float glowProxySize=2.0, + float framerate=10.0, + float hdrColorScale=1.0, + bool receiveShadows = true +) { + int entity = Entity_Create("env_sprite"); + + if (entity == INVALID_ENT_REFERENCE) { + return INVALID_ENT_REFERENCE; + } + + DispatchKeyValue (entity, "disablereceiveshadows", (receiveShadows) ? "0" : "1"); + DispatchKeyValueFloat (entity, "framerate", framerate); + DispatchKeyValueFloat (entity, "GlowProxySize", glowProxySize); + DispatchKeyValue (entity, "spawnflags", "1"); + DispatchKeyValueFloat (entity, "HDRColorScale", hdrColorScale); + DispatchKeyValue (entity, "maxdxlevel", "0"); + DispatchKeyValue (entity, "mindxlevel", "0"); + DispatchKeyValueFloat (entity, "scale", scale); + + DispatchSpawn(entity); + + SetEntityRenderMode(entity, renderMode); + SetEntityRenderColor(entity, color[0], color[1], color[2], color[3]); + SetEntityRenderFx(entity, renderFx); + + Entity_SetName(entity, targetName); + Entity_SetModelIndex(entity, modelIndex); + Entity_SetAbsOrigin(entity, origin); + + if (parent != -1) { + Entity_SetParent(entity, parent); + } + + return entity; +} diff --git a/addons/sourcemod/scripting/include/smlib/entities.inc b/addons/sourcemod/scripting/include/smlib/entities.inc index 60dd15f..2252894 100644 --- a/addons/sourcemod/scripting/include/smlib/entities.inc +++ b/addons/sourcemod/scripting/include/smlib/entities.inc @@ -1,2152 +1,2094 @@ -#if defined _smlib_entities_included - #endinput -#endif -#define _smlib_entities_included - -#include -#include -#include - -/** - * Macro for iterating trough all children (entities it is parent of) of an entity. - * - * @param 1 Entity Index of the parent. - * @param 2 Name of the children entity index variable (will be only valid in the loop). - */ -#define LOOP_CHILDREN(%1,%2) for (new %2=Entity_GetNextChild(%1); %2 != INVALID_ENT_REFERENCE; %2=Entity_GetNextChild(%1, ++%2)) - -/* - * Checks if an entity is valid and exists. - * - * @param entity Entity Index. - * @return True if the entity is valid, false otherwise. - */ -stock Entity_IsValid(entity) -{ - return IsValidEntity(entity); -} - -/** - * Finds an entity by its name. - * You can optionally specify the classname to search for. - * Note: If the classname is specified it uses The Sourcemod native - * function FindEntityByClassname() which uses the engine's - * linked entity list for finding entities. This might be - * cheaper, use this if you call this function very often. - * - * @param name Name of the entity you want so search. - * @param className Optional: Classname of the entity - * @return Entity index or INVALID_ENT_REFERENCE if not matching entity was found. - */ -stock Entity_FindByName(const String:name[], const String:className[]="") -{ - if (className[0] == '\0') { - // Hack: Double the limit to gets none-networked entities too. - new realMaxEntities = GetMaxEntities() * 2; - for (new entity=0; entity < realMaxEntities; entity++) { - - if (!IsValidEntity(entity)) { - continue; - } - - if (Entity_NameMatches(entity, name)) { - return entity; - } - } - } - else { - new entity = INVALID_ENT_REFERENCE; - while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { - - if (Entity_NameMatches(entity, name)) { - return entity; - } - } - } - - return INVALID_ENT_REFERENCE; -} - -/** - * Finds an entity by its HammerID. - * The newer version of Valve's Hammer editor - * sets a unique ID for each entity in a map. - * It only finds the first occurence. - * Note: If the classname is specified it uses The Sourcemod native - * function FindEntityByClassname() which uses the engine's - * linked entity list for finding entities. This might be - * cheaper, use this if you call this function very often. - * - * @param hammerId Hammer editor ID - * @param className Optional: Classname of the entity - * @return Edict Index or INVALID_ENT_REFERENCE if no entity was found. - */ -stock Entity_FindByHammerId(hammerId, const String:className[]="") -{ - if (className[0] == '\0') { - // Hack: Double the limit to gets none-networked entities too. - new realMaxEntities = GetMaxEntities() * 2; - for (new entity=0; entity < realMaxEntities; entity++) { - - if (!IsValidEntity(entity)) { - continue; - } - - if (Entity_GetHammerId(entity) == hammerId) { - return entity; - } - } - } - else { - new entity = INVALID_ENT_REFERENCE; - while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { - - if (Entity_GetHammerId(entity) == hammerId) { - return entity; - } - } - } - - return INVALID_ENT_REFERENCE; -} - -/** - * Searches for an entity by classname. - * This is a wrapper around FindEntityByClassname - * and has been added for completion. - * - * @param startEnt The entity index after which to begin searching from. Use -1 to start from the first entity. - * @param classname Classname of the entity to find. - * @return Entity index >= 0 if found, -1 otherwise. - */ - -stock Entity_FindByClassName(startEntity, const String:className[]) -{ - return FindEntityByClassname(startEntity, className); -} - -/** - * Checks if an entity (partially) matches a specific entity class. - * - * @param entity Entity Index. - * @param className Classname String. - * @partialMatch If to do a partial classname check. - * @return True if the classname matches, false otherwise. - */ -stock bool:Entity_ClassNameMatches(entity, const String:className[], partialMatch=false) -{ - decl String:entity_className[64]; - Entity_GetClassName(entity, entity_className, sizeof(entity_className)); - - if (partialMatch) { - return (StrContains(entity_className, className) != -1); - } - - return StrEqual(entity_className, className); -} - -/** - * Checks if an entity matches a name - * - * @param entity Entity Index. - * @param class Name String. - * @return True if the name matches, false otherwise. - */ -stock bool:Entity_NameMatches(entity, const String:name[]) -{ - decl String:entity_name[128]; - Entity_GetName(entity, entity_name, sizeof(entity_name)); - - return StrEqual(name, entity_name); -} - -/** - * Gets the Name of an entity. - * - * @param entity Entity index. - * @param buffer Return/Output buffer. - * @param size Max size of buffer. - * @return Number of non-null bytes written. - */ -stock Entity_GetName(entity, String:buffer[], size) -{ - return GetEntPropString(entity, Prop_Data, "m_iName", buffer, size); -} - -/** - * Sets the Name of an entity. - * - * @param entity Entity index. - * @param name The name you want to give. - * @return True on success, false otherwise. - */ -stock Entity_SetName(entity, const String:name[], any:...) -{ - decl String:format[128]; - VFormat(format, sizeof(format), name, 3); - - return DispatchKeyValue(entity, "targetname", format); -} - -/** - * Gets the Classname of an entity. - * This is like GetEdictClassname(), except it works for ALL - * entities, not just edicts. - * - * @param entity Entity index. - * @param buffer Return/Output buffer. - * @param size Max size of buffer. - * @return Number of non-null bytes written. - */ -stock Entity_GetClassName(entity, String:buffer[], size) -{ - return GetEntPropString(entity, Prop_Data, "m_iClassname", buffer, size); -} - -/** - * Sets the Classname of an entity. - * - * @param entity Entity index. - * @param name The name you want to give. - * @return True on success, false otherwise. - */ -stock Entity_SetClassName(entity, const String:className[]) -{ - return DispatchKeyValue(entity, "classname", className); -} - -/** - * Gets the Target name of an other entity - * - * @param entity Entity index. - * @param buffer Return/Output buffer. - * @param size Max size of buffer. - * @return Number of non-null bytes written. - */ -stock Entity_GetTargetName(entity, String:buffer[], size) -{ - return GetEntPropString(entity, Prop_Data, "m_target", buffer, size); -} - -/** - * Sets the Target name of an other Entity - * - * @param entity Entity index. - * @param name The target name you want to set - * @return True on success, false otherwise. - */ -stock Entity_SetTargetName(entity, const String:name[], any:...) -{ - decl String:format[128]; - VFormat(format, sizeof(format), name, 3); - - return DispatchKeyValue(entity, "target", format); -} - -/** - * Gets the Global Name of an entity. - * - * @param entity Entity index. - * @param buffer Return/Output buffer. - * @param size Max size of buffer. - * @return Number of non-null bytes written. - */ -stock Entity_GetGlobalName(entity, String:buffer[], size) -{ - return GetEntPropString(entity, Prop_Data, "m_iGlobalname", buffer, size); -} - -/** - * Sets the Global Name of an entity. - * - * @param entity Entity index. - * @param name The global name you want to set. - * @return True on success, false otherwise. - */ -stock Entity_SetGlobalName(entity, const String:name[], any:...) -{ - decl String:format[128]; - VFormat(format, sizeof(format), name, 3); - - return DispatchKeyValue(entity, "globalname", format); -} - -/** - * Gets the Parent name of an entity. - * - * @param entity Entity index. - * @param buffer Return/Output buffer. - * @param size Max size of buffer. - * @return Number of non-null bytes written. - */ -stock Entity_GetParentName(entity, String:buffer[], size) -{ - return GetEntPropString(entity, Prop_Data, "m_iParent", buffer, size); -} - -/** - * Sets the Parent name of an entity. - * - * @param entity Entity index. - * @param name The parent name you want to set. - * @return True on success, false otherwise. - */ -stock Entity_SetParentName(entity, const String:name[], any:...) -{ - decl String:format[128]; - VFormat(format, sizeof(format), name, 3); - - return DispatchKeyValue(entity, "parentname", format); -} - -/** - * Gets the Hammer-ID of an entity. - * The Hammer Editor gives every entity a unique ID. - * Note: Old maps don't have Hammer-ID's set for entities - * - * @param entity Entity index. - * @return Hammer ID. - */ -stock Entity_GetHammerId(entity) -{ - return GetEntProp(entity, Prop_Data, "m_iHammerID"); -} - -/** - * Gets the radius (m_flRadius) of an entity. - * - * @param entity Entity index. - * @return Radius - */ -stock Float:Entity_GetRadius(entity) -{ - return GetEntPropFloat(entity, Prop_Data, "m_flRadius"); -} - -/** - * Sets the radius (m_flRadius) of an entity. - * - * @param entity Entity index. - * @param radius Radius value - * @noreturn - */ -stock Entity_SetRadius(entity, Float:radius) -{ - SetEntPropFloat(entity, Prop_Data, "m_flRadius", radius); -} - -/** - * Gets the Mins of an entity. - * - * @param entity Entity index. - * @param vec Vector. - * @noreturn - */ -stock Entity_GetMinSize(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Send, "m_vecMins", vec); -} - -/** - * Sets the Mins of an entity. - * - * @param entity Entity index. - * @param vec Vector. - * @noreturn - */ -stock Entity_SetMinSize(entity, const Float:vecMins[3]) -{ - SetEntPropVector(entity, Prop_Send, "m_vecMins", vecMins); -} - -/** - * Gets the Mins of an entity. - * This functions isn't safe to use, use Entity_SetMinMaxSize() instead. - * - * @param entity Entity index - * @param vec return vector. - * @noreturn - */ -stock Entity_GetMaxSize(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Send, "m_vecMaxs", vec); -} - -/** - * Sets the Maxs of an entity. - * This functions isn't safe to use, use Entity_SetMinMaxSize() instead. - * - * @param entity Entity index. - * @param vec Vector. - * @noreturn - */ -stock Entity_SetMaxSize(entity, const Float:vecMaxs[3]) -{ - SetEntPropVector(entity, Prop_Send, "m_vecMaxs", vecMaxs); -} - -/** - * Sets the Min and Max Size of an entity. - * Code is taken from HL2SDK and rewritten for Sourcemod. - * - * @param entity Entity index. - * @param vecMins Min size Vector - * @param vecMaxs Max size Vector - * @noreturn - */ -stock Entity_SetMinMaxSize(entity, Float:vecMins[3], Float:vecMaxs[3]) -{ - // Taken from hl2sdk-ob-valve\game\server\util.cpp SetMinMaxSize() - // Todo: Replace this by a SDK call - for (new i=0; i<3; i++) { - - if (vecMins[i] > vecMaxs[i]) { - ThrowError("Error: mins[%d] > maxs[%d] of entity %d", i, i, EntRefToEntIndex(entity)); - } - } - - decl Float:m_vecMins[3], Float:m_vecMaxs[3]; - Entity_GetMinSize(entity, m_vecMins); - Entity_GetMaxSize(entity, m_vecMaxs); - - if (Math_VectorsEqual(m_vecMins, vecMins) && Math_VectorsEqual(m_vecMaxs, vecMaxs)) { - return; - } - - Entity_SetMinSize(entity, vecMins); - Entity_SetMaxSize(entity, vecMaxs); - - decl Float:vecSize[3]; - SubtractVectors(vecMaxs, vecMins, vecSize); - Entity_SetRadius(entity, GetVectorLength(vecSize) * 0.5); - - Entity_MarkSurrBoundsDirty(entity); -} - -/* - * Spawn Flags - * Many entities define their specific spawnflags, check the HL2SDK. - */ - -/* - * Phys prop spawnflags - * Taken from hl2sdk-ob-valve\game\shared\props_shared.h - */ -#define SF_PHYSPROP_START_ASLEEP 0x000001 -#define SF_PHYSPROP_DONT_TAKE_PHYSICS_DAMAGE 0x000002 // this prop can't be damaged by physics collisions -#define SF_PHYSPROP_DEBRIS 0x000004 -#define SF_PHYSPROP_MOTIONDISABLED 0x000008 // motion disabled at startup (flag only valid in spawn - motion can be enabled via input) -#define SF_PHYSPROP_TOUCH 0x000010 // can be 'crashed through' by running player (plate glass) -#define SF_PHYSPROP_PRESSURE 0x000020 // can be broken by a player standing on it -#define SF_PHYSPROP_ENABLE_ON_PHYSCANNON 0x000040 // enable motion only if the player grabs it with the physcannon -#define SF_PHYSPROP_NO_ROTORWASH_PUSH 0x000080 // The rotorwash doesn't push these -#define SF_PHYSPROP_ENABLE_PICKUP_OUTPUT 0x000100 // If set, allow the player to +USE this for the purposes of generating an output -#define SF_PHYSPROP_PREVENT_PICKUP 0x000200 // If set, prevent +USE/Physcannon pickup of this prop -#define SF_PHYSPROP_PREVENT_PLAYER_TOUCH_ENABLE 0x000400 // If set, the player will not cause the object to enable its motion when bumped into -#define SF_PHYSPROP_HAS_ATTACHED_RAGDOLLS 0x000800 // Need to remove attached ragdolls on enable motion/etc -#define SF_PHYSPROP_FORCE_TOUCH_TRIGGERS 0x001000 // Override normal debris behavior and respond to triggers anyway -#define SF_PHYSPROP_FORCE_SERVER_SIDE 0x002000 // Force multiplayer physics object to be serverside -#define SF_PHYSPROP_RADIUS_PICKUP 0x004000 // For Xbox, makes small objects easier to pick up by allowing them to be found -#define SF_PHYSPROP_ALWAYS_PICK_UP 0x100000 // Physcannon can always pick this up, no matter what mass or constraints may apply. -#define SF_PHYSPROP_NO_COLLISIONS 0x200000 // Don't enable collisions on spawn -#define SF_PHYSPROP_IS_GIB 0x400000 // Limit # of active gibs - -/* - * Physbox Spawnflags. Start at 0x01000 to avoid collision with CBreakable's - * Taken from hl2sdk-ob-valve\game\server\physobj.h - */ -#define SF_PHYSBOX_ASLEEP 0x01000 -#define SF_PHYSBOX_IGNOREUSE 0x02000 -#define SF_PHYSBOX_DEBRIS 0x04000 -#define SF_PHYSBOX_MOTIONDISABLED 0x08000 -#define SF_PHYSBOX_USEPREFERRED 0x10000 -#define SF_PHYSBOX_ENABLE_ON_PHYSCANNON 0x20000 -#define SF_PHYSBOX_NO_ROTORWASH_PUSH 0x40000 // The rotorwash doesn't push these -#define SF_PHYSBOX_ENABLE_PICKUP_OUTPUT 0x80000 -#define SF_PHYSBOX_ALWAYS_PICK_UP 0x100000 // Physcannon can always pick this up, no matter what mass or constraints may apply. -#define SF_PHYSBOX_NEVER_PICK_UP 0x200000 // Physcannon will never be able to pick this up. -#define SF_PHYSBOX_NEVER_PUNT 0x400000 // Physcannon will never be able to punt this object. -#define SF_PHYSBOX_PREVENT_PLAYER_TOUCH_ENABLE 0x800000 // If set, the player will not cause the object to enable its motion when bumped into - -/* - * Spawnflags for func breakable - * Taken from hl2sdk-ob-valve\game\server\func_break.h - */ -#define SF_BREAK_TRIGGER_ONLY 0x0001 // may only be broken by trigger -#define SF_BREAK_TOUCH 0x0002 // can be 'crashed through' by running player (plate glass) -#define SF_BREAK_PRESSURE 0x0004 // can be broken by a player standing on it -#define SF_BREAK_PHYSICS_BREAK_IMMEDIATELY 0x0200 // the first physics collision this breakable has will immediately break it -#define SF_BREAK_DONT_TAKE_PHYSICS_DAMAGE 0x0400 // this breakable doesn't take damage from physics collisions -#define SF_BREAK_NO_BULLET_PENETRATION 0x0800 // don't allow bullets to penetrate - -/* - * Spawnflags for func_pushable (it's also func_breakable, so don't collide with those flags) - * Taken from hl2sdk-ob-valve\game\server\func_break.h - */ -#define SF_PUSH_BREAKABLE 0x0080 -#define SF_PUSH_NO_USE 0x0100 // player cannot +use pickup this ent - -/** - * Gets the Spawnflags of an entity. - * - * @param entity Entity index. - * @return Spawnflags value - */ -stock Entity_GetSpawnFlags(entity) -{ - return GetEntProp(entity, Prop_Data, "m_spawnflags"); -} - -/** - * Sets the Spawnflags of an entity. - * - * @param entity Entity index. - * @param flags Flags value - * @noreturn - */ -stock Entity_SetSpawnFlags(entity, flags) -{ - SetEntProp(entity, Prop_Data, "m_spawnflags", flags); -} - -/** - * Adds Spawnflags to an entity. - * - * @param entity Entity index. - * @param flags Flags value - * @noreturn - */ -stock Entity_AddSpawnFlags(entity, flags) -{ - new spawnFlags = Entity_GetSpawnFlags(entity); - spawnFlags |= flags; - Entity_SetSpawnFlags(entity, spawnFlags); -} - -/** - * Removes Spawnflags from an entity. - * - * @param entity Entity index. - * @param flags Flags value - * @noreturn - */ -stock Entity_RemoveSpawnFlags(entity, flags) -{ - new spawnFlags = Entity_GetSpawnFlags(entity); - spawnFlags &= ~flags; - Entity_SetSpawnFlags(entity, spawnFlags); -} - -/** - * Clears all Spawnflags of an entity. - * - * @param entity Entity index. - * @noreturn - */ -stock Entity_ClearSpawnFlags(entity) -{ - Entity_SetSpawnFlags(entity, 0); -} - -/** - * Returns whether the entity has specific Spawnflags. - * - * @param entity Entity index. - * @param flags Flags value. - * @return True if the entity has the spawnflags set, false otherwise. - */ -stock bool:Entity_HasSpawnFlags(entity, flags) -{ - return bool:(Entity_GetSpawnFlags(entity) & flags); -} - -/* - * Entity flags, CBaseEntity::m_iEFlags - * Taken from: hl2sdk-ob-valve\game\shared\shareddefs.h - */ -enum Entity_Flags -{ - EFL_KILLME = (1<<0), // This entity is marked for death -- This allows the game to actually delete ents at a safe time - EFL_DORMANT = (1<<1), // Entity is dormant, no updates to client - EFL_NOCLIP_ACTIVE = (1<<2), // Lets us know when the noclip command is active. - EFL_SETTING_UP_BONES = (1<<3), // Set while a model is setting up its bones. - EFL_KEEP_ON_RECREATE_ENTITIES = (1<<4), // This is a special entity that should not be deleted when we restart entities only - - EFL_HAS_PLAYER_CHILD= (1<<4), // One of the child entities is a player. - - EFL_DIRTY_SHADOWUPDATE = (1<<5), // Client only- need shadow manager to update the shadow... - EFL_NOTIFY = (1<<6), // Another entity is watching events on this entity (used by teleport) - - // The default behavior in ShouldTransmit is to not send an entity if it doesn't - // have a model. Certain entities want to be sent anyway because all the drawing logic - // is in the client DLL. They can set this flag and the engine will transmit them even - // if they don't have a model. - EFL_FORCE_CHECK_TRANSMIT = (1<<7), - - EFL_BOT_FROZEN = (1<<8), // This is set on bots that are frozen. - EFL_SERVER_ONLY = (1<<9), // Non-networked entity. - EFL_NO_AUTO_EDICT_ATTACH = (1<<10), // Don't attach the edict; we're doing it explicitly - - // Some dirty bits with respect to abs computations - EFL_DIRTY_ABSTRANSFORM = (1<<11), - EFL_DIRTY_ABSVELOCITY = (1<<12), - EFL_DIRTY_ABSANGVELOCITY = (1<<13), - EFL_DIRTY_SURR_COLLISION_BOUNDS = (1<<14), - EFL_DIRTY_SPATIAL_PARTITION = (1<<15), -// UNUSED = (1<<16), - - EFL_IN_SKYBOX = (1<<17), // This is set if the entity detects that it's in the skybox. - // This forces it to pass the "in PVS" for transmission. - EFL_USE_PARTITION_WHEN_NOT_SOL = (1<<18), // Entities with this flag set show up in the partition even when not solid - EFL_TOUCHING_FLUID = (1<<19), // Used to determine if an entity is floating - - // FIXME: Not really sure where I should add this... - EFL_IS_BEING_LIFTED_BY_BARNACLE = (1<<20), - EFL_NO_ROTORWASH_PUSH = (1<<21), // I shouldn't be pushed by the rotorwash - EFL_NO_THINK_FUNCTION = (1<<22), - EFL_NO_GAME_PHYSICS_SIMULATION = (1<<23), - - EFL_CHECK_UNTOUCH = (1<<24), - EFL_DONTBLOCKLOS = (1<<25), // I shouldn't block NPC line-of-sight - EFL_DONTWALKON = (1<<26), // NPC;s should not walk on this entity - EFL_NO_DISSOLVE = (1<<27), // These guys shouldn't dissolve - EFL_NO_MEGAPHYSCANNON_RAGDOLL = (1<<28), // Mega physcannon can't ragdoll these guys. - EFL_NO_WATER_VELOCITY_CHANGE = (1<<29), // Don't adjust this entity's velocity when transitioning into water - EFL_NO_PHYSCANNON_INTERACTION = (1<<30), // Physcannon can't pick these up or punt them - EFL_NO_DAMAGE_FORCES = (1<<31), // Doesn't accept forces from physics damage -}; - -/** - * Gets the Entity flags (m_iEFlags) of an entity. - * - * @param entity Entity index. - * @return Entity flags value - */ -stock Entity_Flags:Entity_GetEFlags(entity) -{ - return Entity_Flags:GetEntProp(entity, Prop_Data, "m_iEFlags"); -} - -/** - * Sets the entity's Entity flags (m_iEFlags). - * - * @param entity Entity index. - * @param flags Flags value - * @noreturn - */ -stock Entity_SetEFlags(entity, Entity_Flags:flags) -{ - SetEntProp(entity, Prop_Data, "m_iEFlags", flags); -} - -/** - * Adds Entity flags (m_iEFlags) to an entity. - * - * @param entity Entity index. - * @param flags Flags value - * @noreturn - */ -stock Entity_AddEFlags(entity, Entity_Flags:flags) -{ - new Entity_Flags:setFlags = Entity_GetEFlags(entity); - setFlags |= flags; - Entity_SetEFlags(entity, setFlags); -} - -/** - * Removes Entity flags (m_iEFlags) from an entity. - * - * @param entity Entity index. - * @param flags Flags value - * @noreturn - */ -stock Entity_RemoveEFlags(entity, Entity_Flags:flags) -{ - new Entity_Flags:setFlags = Entity_GetEFlags(entity); - setFlags &= ~flags; - Entity_SetEFlags(entity, setFlags); -} - -/** - * Checks if the entity has specific Entity flags (m_iEFlags) set. - * - * @param entity Entity index. - * @param flags Flags value - * @return True if the flags are set, false otherwise. - */ -stock bool:Entity_HasEFlags(entity, Entity_Flags:flags) -{ - new Entity_Flags:currentEFlags = Entity_GetEFlags(entity); - - return bool:(currentEFlags & flags); -} - -/** - * Marks the surrounding bounds of an entity as outdated. - * You normally call this when a collision setting has changed. - * - * @param entity Entity index. - * @noreturn - */ -stock Entity_MarkSurrBoundsDirty(entity) -{ - Entity_AddEFlags(entity, EFL_DIRTY_SURR_COLLISION_BOUNDS); -} - -/* - * CBaseEntity::m_fFlags Functions - * Use the FL_ Defines (FL_ONGROUND, ...) or - * special entity specific flags. - * Note: The flag FL_AIMTARGET probably doesn't work as - * we have current no way of adding/removing it to the AimTarget List. - */ - -/** - * Gets the Flags of an entity. - * - * @param entity Entity Index. - * @return Entity Flags. - */ -stock Entity_GetFlags(entity) -{ - return GetEntProp(entity, Prop_Data, "m_fFlags"); -} - -/** - * Sets the Flags of an entity. - * - * @param entity Entity index. - * @param flags New Flags value - * @noreturn - */ -stock Entity_SetFlags(entity, flags) -{ - SetEntProp(entity, Prop_Data, "m_fFlags", flags); -} - -/** - * Adds Flags to the entity - * - * @param entity Entity index. - * @param flags Flags to add - * @noreturn - */ -stock Entity_AddFlags(entity, flags) -{ - new setFlags = Entity_GetFlags(entity); - setFlags |= flags; - Entity_SetFlags(entity, flags); -} - -/** - * Removes flags from the entity - * - * @param entity Entity index. - * @param flags Flags to remove - * @noreturn - */ -stock Entity_RemoveFlags(entity, flags) -{ - new setFlags = Entity_GetFlags(entity); - setFlags &= ~flags; - Entity_SetFlags(entity, setFlags); -} - -/** - * Toggles the specified flag on the entity. - * Adds the flag to the entity if it doesn't exists - * or removes it otherwise. - * - * @param entity Entity index. - * @param flags Flag to Toggle - * @noreturn - */ -stock Entity_ToggleFlag(entity, flag) -{ - new setFlag = Entity_GetFlags(entity); - setFlag ^= flag; - Entity_SetFlags(entity, setFlag); -} - -/** - * Removes all flags from the entity - * - * @param entity Entity index. - * @noreturn - */ -stock Entity_ClearFlags(entity) -{ - Entity_SetFlags(entity, 0); -} - -/* edict->solid values - * NOTE: Some movetypes will cause collisions independent of SOLID_NOT/SOLID_TRIGGER when the entity moves - * SOLID only effects OTHER entities colliding with this one when they move - UGH! - * - * Solid type basically describes how the bounding volume of the object is represented - * NOTE: These numerical values are used in the FGD by the prop code (see prop_dynamic) - * Taken from: hl2sdk-ob-valve\public\const.h - */ - -enum SolidFlags_t -{ - FSOLID_CUSTOMRAYTEST = 0x0001, // Ignore solid type + always call into the entity for ray tests - FSOLID_CUSTOMBOXTEST = 0x0002, // Ignore solid type + always call into the entity for swept box tests - FSOLID_NOT_SOLID = 0x0004, // Are we currently not solid? - FSOLID_TRIGGER = 0x0008, // This is something may be collideable but fires touch functions - // even when it's not collideable (when the FSOLID_NOT_SOLID flag is set) - FSOLID_NOT_STANDABLE = 0x0010, // You can't stand on this - FSOLID_VOLUME_CONTENTS = 0x0020, // Contains volumetric contents (like water) - FSOLID_FORCE_WORLD_ALIGNED = 0x0040, // Forces the collision rep to be world-aligned even if it's SOLID_BSP or SOLID_VPHYSICS - FSOLID_USE_TRIGGER_BOUNDS = 0x0080, // Uses a special trigger bounds separate from the normal OBB - FSOLID_ROOT_PARENT_ALIGNED = 0x0100, // Collisions are defined in root parent's local coordinate space - FSOLID_TRIGGER_TOUCH_DEBRIS = 0x0200, // This trigger will touch debris objects - - FSOLID_MAX_BITS = 10 -}; - -/** - * Gets the solid flags of the entity - * - * @param entity Entity index. - * @return Solid Flags. - */ -stock SolidFlags_t:Entity_GetSolidFlags(entity) -{ - return SolidFlags_t:GetEntProp(entity, Prop_Data, "m_usSolidFlags", 2); -} - -/** - * Sets the solid flags of the entity - * - * @param entity Entity index. - * @param flags Solid Flags. - * @noreturn - */ -stock Entity_SetSolidFlags(entity, SolidFlags_t:flags) -{ - new SolidFlags_t:oldFlags = Entity_GetSolidFlags(entity); - flags = flags & SolidFlags_t:0xFFFF; - - if (oldFlags == flags) { - return; - } - - SetEntProp(entity, Prop_Data, "m_usSolidFlags", flags, 2); - - // These two flags, if changed, can produce different surrounding bounds - if ((oldFlags & (FSOLID_FORCE_WORLD_ALIGNED | FSOLID_USE_TRIGGER_BOUNDS)) != - (flags & (FSOLID_FORCE_WORLD_ALIGNED | FSOLID_USE_TRIGGER_BOUNDS))) - { - Entity_MarkSurrBoundsDirty(entity); - } -} - -/** - * Adds solid flags to the entity - * - * @param entity Entity index. - * @param flags Solid Flags. - * @noreturn - */ -stock Entity_AddSolidFlags(entity, SolidFlags_t:flags) -{ - new SolidFlags_t:newFlags = Entity_GetSolidFlags(entity); - newFlags |= flags; - Entity_SetSolidFlags(entity, newFlags); -} - -/** - * Removes solid flags from the entity. - * - * @param entity Entity index. - * @param flags Solid Flags. - * @noreturn - */ -stock Entity_RemoveSolidFlags(entity, SolidFlags_t:flags) -{ - new SolidFlags_t:newFlags = Entity_GetSolidFlags(entity); - newFlags &= ~flags; - Entity_SetSolidFlags(entity, newFlags); -} - -/** - * Removes all solid flags from the entity. - * - * @param entity Entity index. - * @noreturn - */ -stock Entity_ClearSolidFlags(entity) -{ - Entity_SetSolidFlags(entity, SolidFlags_t:0); -} - -/** - * Checks whether certain solid flags are set on the entity. - * - * @param entity Entity index. - * @param flags Solid Flags. - * @return True if the specified flags are set, false otherwise. - */ -stock bool:Entity_SolidFlagsSet(entity, SolidFlags_t:flagMask) -{ - return bool:(Entity_GetSolidFlags(entity) & flagMask); -} - -enum SolidType_t -{ - SOLID_NONE = 0, // no solid model - SOLID_BSP = 1, // a BSP tree - SOLID_BBOX = 2, // an AABB - SOLID_OBB = 3, // an OBB (not implemented yet) - SOLID_OBB_YAW = 4, // an OBB, constrained so that it can only yaw - SOLID_CUSTOM = 5, // Always call into the entity for tests - SOLID_VPHYSICS = 6, // solid vphysics object, get vcollide from the model and collide with that - SOLID_LAST, -}; - -/** - * Gets the solidity type of the entity - * - * @param entity Entity index. - * @return Solid Type - */ -stock SolidType_t:Entity_GetSolidType(entity) -{ - return SolidType_t:GetEntProp(entity, Prop_Data, "m_nSolidType", 1); -} - -/** - * Sets the solidity type of the entity - * - * @param entity Entity index. - * @param Solid Type value. - * @noreturn - */ -stock Entity_SetSolidType(entity, SolidType_t:value) -{ - SetEntProp(entity, Prop_Send, "m_nSolidType", value, 1); - Entity_MarkSurrBoundsDirty(entity); -} - -/** - * Checks whether the entity is solid or not. - * - * @param entity Entity index. - * @return True if the entity is solid, false otherwise. - */ -stock bool:Entity_IsSolid(entity) -{ - return (Entity_GetSolidType(entity) != SOLID_NONE && - !Entity_SolidFlagsSet(entity, FSOLID_NOT_SOLID)); -} - -/** - * Retrieves the model path of a given entity. - * Returns "*num" for Brush entities. - * - * @param entity entity reference or index - * @param model buffer String for the model - * @param size max size of buffer string - * @return Number of non-null bytes written. - */ -stock Entity_GetModel(entity, String:buffer[], size) -{ - return GetEntPropString(entity, Prop_Data, "m_ModelName", buffer, size); -} - -/** - * Sets the model to a given entity. - * Be sure it has been precached. - * This is an alias for SetEntityModel() - * - * @param entity Entity index - * @param model Model name - * @noreturn - */ -stock Entity_SetModel(entity, const String:model[]) -{ - SetEntityModel(entity, model); -} - -/** - * Gets the entity's model index, if it has one set. - * - * @param entity Entity index. - * @return The Entity's model index - */ -stock Entity_GetModelIndex(entity) -{ - return GetEntProp(entity, Prop_Data, "m_nModelIndex", 2); -} - -/** - * Sets the entity's model index (must be precached) - * - * @param entity Entity index. - * @param index Model Index. - * @noreturn - */ -stock Entity_SetModelIndex(entity, index) -{ - SetEntProp(entity, Prop_Data, "m_nModelIndex", index, 2); -} - -/** -* Sets the entity's maxspeed to the given value (in units per second) -* -* @param entity Entity index -* @param maxspeed the maximum speed the entity can move -* @noreturn -*/ -stock Entity_SetMaxSpeed(entity, Float:value) -{ - SetEntPropFloat(entity, Prop_Data, "m_flMaxspeed", value); -} - -/* - * Collision groups - * Taken from hl2sdk-ob-valve/public/const.h - */ -enum Collision_Group_t -{ - COLLISION_GROUP_NONE = 0, - COLLISION_GROUP_DEBRIS, // Collides with nothing but world and static stuff - COLLISION_GROUP_DEBRIS_TRIGGER, // Same as debris, but hits triggers - COLLISION_GROUP_INTERACTIVE_DEB, // Collides with everything except other interactive debris or debris - COLLISION_GROUP_INTERACTIVE, // Collides with everything except interactive debris or debris - COLLISION_GROUP_PLAYER, - COLLISION_GROUP_BREAKABLE_GLASS, - COLLISION_GROUP_VEHICLE, - COLLISION_GROUP_PLAYER_MOVEMENT, // For HL2, same as Collision_Group_Player, for - // TF2, this filters out other players and CBaseObjects - COLLISION_GROUP_NPC, // Generic NPC group - COLLISION_GROUP_IN_VEHICLE, // for any entity inside a vehicle - COLLISION_GROUP_WEAPON, // for any weapons that need collision detection - COLLISION_GROUP_VEHICLE_CLIP, // vehicle clip brush to restrict vehicle movement - COLLISION_GROUP_PROJECTILE, // Projectiles! - COLLISION_GROUP_DOOR_BLOCKER, // Blocks entities not permitted to get near moving doors - COLLISION_GROUP_PASSABLE_DOOR, // Doors that the player shouldn't collide with - COLLISION_GROUP_DISSOLVING, // Things that are dissolving are in this group - COLLISION_GROUP_PUSHAWAY, // Nonsolid on client and server, pushaway in player code - - COLLISION_GROUP_NPC_ACTOR, // Used so NPCs in scripts ignore the player. - COLLISION_GROUP_NPC_SCRIPTED // USed for NPCs in scripts that should not collide with each other -}; - -/** - * Gets the collision group of an entity. - * - * @param entity entity index - * @return Entity collision group. - */ -stock Collision_Group_t:Entity_GetCollisionGroup(entity) -{ - return Collision_Group_t:GetEntProp(entity, Prop_Data, "m_CollisionGroup"); -} - -/** - * Sets the collision group of an entity. - * - * @param entity entity index - * @param value the new collision group. - * @noreturn - */ -stock Entity_SetCollisionGroup(entity, Collision_Group_t:value) -{ - SetEntProp(entity, Prop_Data, "m_CollisionGroup", value); -} - -/** - * Functions for getting / setting the origin (position) of an entity. - * Go to http://developer.valvesoftware.com/wiki/Origin - * if you want to learn more about origins - */ - -/** - * Gets the Absolute Origin (position) of an entity. - * - * @param entity Entity index. - * @param vec 3 dimensional vector array. - * @noreturn - */ -stock Entity_GetAbsOrigin(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Send, "m_vecOrigin", vec); -} - -/** - * Sets the Absolute Origin (position) of an entity. - * - * @param entity Entity index. - * @param vec 3 dimensional vector array. - * @noreturn - */ -stock Entity_SetAbsOrigin(entity, const Float:vec[3]) -{ - // We use TeleportEntity to set the origin more safely - // Todo: Replace this with a call to UTIL_SetOrigin() or CBaseEntity::SetLocalOrigin() - TeleportEntity(entity, vec, NULL_VECTOR, NULL_VECTOR); -} - -/** - * Functions for getting / setting the angles (rotation) of an entity. - * http://developer.valvesoftware.com/wiki/Angles - * if you want to learn more about angles - */ - -/** - * Gets the Angles of an entity - * - * @param entity Entity index. - * @param vec 3 dimensional vector array. - * @noreturn - */ -stock Entity_GetAbsAngles(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Data, "m_angAbsRotation", vec); -} - -/** - * Sets the Angles of an entity - * - * @param entity Entity index. - * @param vec 3 dimensional vector array. - * @noreturn - */ -stock Entity_SetAbsAngles(entity, const Float:vec[3]) -{ - // We use TeleportEntity to set the angles more safely - // Todo: Replace this with a call to CBaseEntity::SetLocalAngles() - TeleportEntity(entity, NULL_VECTOR, vec, NULL_VECTOR); -} - -/** - * Functions for getting / setting the velocity of an entity. - * Go to http://developer.valvesoftware.com/wiki/Velocity - * if you want to learn more about the different kind of velocities. - */ - -/** - * Gets the Local velocity of an entity. - * The local velocity is the velocity generated by the entity. - * - * @param entity Entity index. - * @param vel An 3 dim array - * @noreturn - */ -stock Entity_GetLocalVelocity(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Data, "m_vecVelocity", vec); -} - -/** - * Sets the Local velocity of an entity. - * The local velocity is the velocity generated by the entity. - * Only use this if you know what you are doing, - * the entity can overwrite this value on next frame. - * - * @param entity Entity index. - * @param vel An 3 dim array - * @noreturn - */ -stock Entity_SetLocalVelocity(entity, const Float:vec[3]) -{ - SetEntPropVector(entity, Prop_Data, "m_vecVelocity", vec); -} - -/** - * Gets the Base velocity of an entity. - * The base velocity is the velocity applied - * to the entity from other sources . - * - * @param entity Entity index. - * @param vel An 3 dim array - * @noreturn - */ -stock Entity_GetBaseVelocity(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Data, "m_vecBaseVelocity", vec); -} - -/** - * Sets the Base velocity of an entity. - * The base velocity is the velocity applied - * to the entity from other sources . - * - * @param entity Entity index. - * @param vel An 3 dim array - * @noreturn - */ -stock Entity_SetBaseVelocity(entity, const Float:vec[3]) -{ - SetEntPropVector(entity, Prop_Data, "m_vecBaseVelocity", vec); -} - -/** - * Gets the Absolute velocity of an entity. - * The absolute velocity is the sum of the local - * and base velocities. It's the actual value used to move. - * - * @param entity Entity index. - * @param vel An 3 dim array - * @noreturn - */ -stock Entity_GetAbsVelocity(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Data, "m_vecAbsVelocity", vec); -} - -/** - * Sets the Absolute velocity of an entity. - * The absolute velocity is the sum of the local - * and base velocities. It's the actual value used to move. - * - * @param entity Entity index. - * @param vel An 3 dim array - * @noreturn - */ -stock Entity_SetAbsVelocity(entity, const Float:vec[3]) -{ - // We use TeleportEntity to set the velocity more safely - // Todo: Replace this with a call to CBaseEntity::SetAbsVelocity() - TeleportEntity(entity, NULL_VECTOR, NULL_VECTOR, vec); -} - -/** - * Returns true if the entity is locked. - * - * @param entity Entity index. - * @return True if locked otherwise false. - */ -stock bool:Entity_IsLocked(entity) -{ - return bool:GetEntProp(entity, Prop_Data, "m_bLocked", 1); -} - -/** - * Locks an entity. - * - * @param entity Entity index. - * @noreturn - */ -stock Entity_Lock(entity) -{ - SetEntProp(entity, Prop_Data, "m_bLocked", 1, 1); -} -/** - * Unlocks an entity. - * - * @param entity Entity index. - * @noreturn - */ -stock Entity_UnLock(entity) -{ - SetEntProp(entity, Prop_Data, "m_bLocked", 0, 1); -} - -/** - * Gets the health of an entity. - * - * @param entity entity index. - * @return current health points - */ -stock Entity_GetHealth(entity) -{ - return GetEntProp(entity, Prop_Data, "m_iHealth"); -} - -/** - * Sets the health of an entity. - * - * @param entity entity index. - * @param value health to set (anything above 511 will overload) - * @noreturn - */ -stock Entity_SetHealth(entity, value, ignoreMax=false, kill=true) -{ - new health = value; - - if (!ignoreMax) { - new maxHealth = Entity_GetMaxHealth(entity); - - if (health > maxHealth) { - health = maxHealth; - } - } - - if (health < 0) { - health = 0; - } - - SetEntProp(entity, Prop_Data, "m_iHealth", health); - - if (health <= 0) { - Entity_Kill(entity); - } - - return health; -} - -/** - * Add health to an entity - * - * @param entity entity index - * @param value health to add - * @return returns the new health value set - */ -stock Entity_AddHealth(entity, value, ignoreMax=false, kill=true) -{ - new health = Entity_GetHealth(entity); - - health += value; - - return Entity_SetHealth(entity, health, ignoreMax, kill); -} - -/** - * Takes health from an entity - * - * @param entity entity index - * @param value health to add - * @return returns the new health value set - */ -stock Entity_TakeHealth(entity, value, ignoreMax=false, kill=true) -{ - new health = Entity_GetHealth(entity); - - health -= value; - - return Entity_SetHealth(entity, health, ignoreMax, kill); -} - -/** - * Get the max health of an entity - * - * @param entity Entity Index - * @return Max health points - */ -stock Entity_GetMaxHealth(entity) -{ - return GetEntProp(entity, Prop_Data, "m_iMaxHealth"); -} - - -/** - * Set the max health of an entity. - * - * @param entity Entity index - * @param value Max health to set (anything above 511 will overload) - * @noreturn - */ -stock Entity_SetMaxHealth(entity, value) -{ - SetEntProp(entity, Prop_Data, "m_iMaxHealth", value); - return value; -} - -/** - * Returns the Float distance between an entity - * and a vector origin. - * - * @param entity Entity Index. - * @param target Vector Origin. - * @return Distance Float value. - */ -stock Float:Entity_GetDistanceOrigin(entity, const Float:vec[3]) -{ - new Float:entityVec[3]; - Entity_GetAbsOrigin(entity, entityVec); - - return GetVectorDistance(entityVec, vec); -} - -/** - * Returns the Float distance between two entities. - * Both entities must be valid. - * - * @param entity Entity Index. - * @param target Target Entity Index. - * @return Distance Float value. - */ -stock Float:Entity_GetDistance(entity, target) -{ - new Float:targetVec[3]; - Entity_GetAbsOrigin(target, targetVec); - - return Entity_GetDistanceOrigin(entity, targetVec); -} - -/** - * Checks if the given 2 entitys are within a given range. - * - * @param entity Entity Index. - * @param target Target Entity Index. - * @param distance Max Float distance. - * @return True if the given entities are closer than the given distance value, false otherwise. - */ -stock bool:Entity_InRange(entity, target, Float:distance) -{ - if (Entity_GetDistance(entity, target) > distance) { - return false; - } - - return true; -} - -/** - * Enables the motion of an entity. - * - * @param entity Entity index. - * @return True on success, false otherwise - */ -stock bool:Entity_EnableMotion(entity) -{ - return AcceptEntityInput(entity, "enablemotion"); -} - -/** - * Disables the motion of an entity. - * - * @param entity Entity index. - * @return True on success, false otherwise - */ -stock bool:Entity_DisableMotion(entity) -{ - return AcceptEntityInput(entity, "disablemotion"); -} - -/** - * Freezes an entity by setting the FL_FROZEN flag. - * - * @param entity Entity index. - * @return True on success, false otherwise - */ -stock Entity_Freeze(entity) -{ - Entity_AddFlags(entity, FL_FROZEN); -} - -/** - * Unfreezes an entity by removing the FL_FROZEN flag. - * - * @param entity Entity index. - * @return True on success, false otherwise - */ -stock Entity_UnFreeze(entity) -{ - Entity_RemoveFlags(entity, FL_FROZEN); -} - - -/** - * This function points an entity to another with the targetname - * and name. Useful for allot of entities like trigger_teleport. - * If the name is not specified it will be generated automatically. - * - * @param entity Entity index. - * @param target Target entity index. - * @param Optional: target name - * @noreturn - */ -stock Entity_PointAtTarget(entity, target, const String:name[]="") -{ - decl String:targetName[128]; - Entity_GetTargetName(entity, targetName, sizeof(targetName)); - - if (name[0] == '\0') { - - if (targetName[0] == '\0') { - // Let's generate our own name - Format( - targetName, - sizeof(targetName), - "_smlib_Entity_PointAtTarget:%d", - target - ); - } - } - else { - strcopy(targetName, sizeof(targetName), name); - } - - Entity_SetTargetName(entity, targetName); - Entity_SetName(target, targetName); -} - -/** - * This function points a point_hurt entity to another damage target entity.. - * and name. Useful for allot of entities like trigger_teleport. - * If the name is not specified it will be generated automatically. - * - * @param entity Entity index. - * @param target Target entity index. - * @param Optional: target name - * @noreturn - */ -stock Entity_PointHurtAtTarget(entity, target, const String:name[]="") -{ - decl String:targetName[128]; - Entity_GetTargetName(entity, targetName, sizeof(targetName)); - - if (name[0] == '\0') { - - if (targetName[0] == '\0') { - // Let's generate our own name - Format( - targetName, - sizeof(targetName), - "_smlib_Entity_PointHurtAtTarget:%d", - target - ); - } - } - else { - strcopy(targetName, sizeof(targetName), name); - } - - DispatchKeyValue(entity, "DamageTarget", targetName); - Entity_SetName(target, targetName); -} - -/** - * Checks if an entity is a player or not. - * No checks are done if the entity is actually valid, - * the player is connected or ingame. - * - * @param entity Entity index. - * @return True if the entity is a player, false otherwise. - */ -stock bool:Entity_IsPlayer(entity) -{ - if (entity < 1 || entity > MaxClients) { - return false; - } - - return true; -} - -/** - * Creates an entity by classname. - * - * @param className Classname String. - * @param ForceEdictIndex Edict Index to use. - * @return Entity Index or INVALID_ENT_REFERENCE if the slot is already in use. - */ -stock Entity_Create(const String:className[], ForceEdictIndex=-1) -{ - if (ForceEdictIndex != -1 && Entity_IsValid(ForceEdictIndex)) { - return INVALID_ENT_REFERENCE; - } - - return CreateEntityByName(className, ForceEdictIndex); -} - -/** - * Kills an entity on the next frame (delayed). - * It is safe to use with entity loops. - * If the entity is is player ForcePlayerSuicide() is called. - * - * @param kenny Entity index. - * @param killChildren When true, kennys children are killed too. - * @return True on success, false otherwise. - */ -stock bool:Entity_Kill(kenny, killChildren=false) -{ - if (Entity_IsPlayer(kenny)) { - // Oh My God! They Killed Kenny!! - ForcePlayerSuicide(kenny); - return true; - } - - if(killChildren){ - return AcceptEntityInput(kenny, "KillHierarchy"); - } - else { - return AcceptEntityInput(kenny, "Kill"); - } -} - -/** - * Kills all entities with the given networked classname. - * It is safe to use with entity loops. - * If the entity is is player ForcePlayerSuicide() is called. - * - * @param className Entity Network Class to search for. - * @return Number of entities killed. - */ -stock Entity_KillAllByClassName(const String:className[]) -{ - new x = 0; - - new entity = INVALID_ENT_REFERENCE; - while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { - AcceptEntityInput(entity, "kill"); - x++; - } - - return x; -} - -/** - * Gets the owner of an entity. - * For example the owner of a weapon entity. - * - * @param entity Entity index. - * @return Ground Entity or -1 - */ -stock Entity_GetOwner(entity) -{ - return GetEntPropEnt(entity, Prop_Data, "m_hOwnerEntity"); -} - -/** - * Sets the owner of an entity. - * For example the owner of a weapon entity. - * - * @param entity Entity index. - * @noreturn - */ -stock Entity_SetOwner(entity, newOwner) -{ - SetEntPropEnt(entity, Prop_Send, "m_hOwnerEntity", newOwner); -} - -/** - * Get's the ground entity this entity stands on. - * - * @param entity Entity index. - * @return Ground Entity or -1 - */ -stock Entity_GetGroundEntity(entity) -{ - return GetEntPropEnt(entity, Prop_Data, "m_hGroundEntity"); -} - -/* - * Damage definitions - */ - -#if !defined DMG_GENERIC - -#define DMG_GENERIC 0 // generic damage was done -#define DMG_CRUSH (1 << 0) // crushed by falling or moving object. - // NOTE: It's assumed crush damage is occurring as a result of physics collision, so no extra physics force is generated by crush damage. - // DON'T use DMG_CRUSH when damaging entities unless it's the result of a physics collision. You probably want DMG_CLUB instead. -#define DMG_BULLET (1 << 1) // shot -#define DMG_SLASH (1 << 2) // cut, clawed, stabbed -#define DMG_BURN (1 << 3) // heat burned -#define DMG_VEHICLE (1 << 4) // hit by a vehicle -#define DMG_FALL (1 << 5) // fell too far -#define DMG_BLAST (1 << 6) // explosive blast damage -#define DMG_CLUB (1 << 7) // crowbar, punch, headbutt -#define DMG_SHOCK (1 << 8) // electric shock -#define DMG_SONIC (1 << 9) // sound pulse shockwave -#define DMG_ENERGYBEAM (1 << 10) // laser or other high energy beam -#define DMG_PREVENT_PHYSICS_FORCE (1 << 11) // Prevent a physics force -#define DMG_NEVERGIB (1 << 12) // with this bit OR'd in, no damage type will be able to gib victims upon death -#define DMG_ALWAYSGIB (1 << 13) // with this bit OR'd in, any damage type can be made to gib victims upon death. -#define DMG_DROWN (1 << 14) // Drowning - - -#define DMG_PARALYZE (1 << 15) // slows affected creature down -#define DMG_NERVEGAS (1 << 16) // nerve toxins, very bad -#define DMG_POISON (1 << 17) // blood poisoning - heals over time like drowning damage -#define DMG_RADIATION (1 << 18) // radiation exposure -#define DMG_DROWNRECOVER (1 << 19) // drowning recovery -#define DMG_ACID (1 << 20) // toxic chemicals or acid burns -#define DMG_SLOWBURN (1 << 21) // in an oven - -#define DMG_REMOVENORAGDOLL (1<<22) // with this bit OR'd in, no ragdoll will be created, and the target will be quietly removed. - // use this to kill an entity that you've already got a server-side ragdoll for - -#define DMG_PHYSGUN (1<<23) // Hit by manipulator. Usually doesn't do any damage. -#define DMG_PLASMA (1<<24) // Shot by Cremator -#define DMG_AIRBOAT (1<<25) // Hit by the airboat's gun - -#define DMG_DISSOLVE (1<<26) // Dissolving! -#define DMG_BLAST_SURFACE (1<<27) // A blast on the surface of water that cannot harm things underwater -#define DMG_DIRECT (1<<28) -#define DMG_BUCKSHOT (1<<29) // not quite a bullet. Little, rounder, different. - -#endif - -/** - * Does damage to an entity. - * This is a powerful function that allows you to specify - * who the attacker is, the damage type and also what weapon - * should be displayed in the hud kill message. - * Note that for entities that fire another entity (RPG's, Crossbow's, - * you have to pass the bullet's class, not the weapon's class ! - * It hasn't been tested how expensive this function is, as it - * uses the entity point_hurt. - * If you need a cheaper function use Entity_RemoveHealth(). - * - * @param entity Entity index. - * @param damage Amount of damage. - * @param attacker Entity Index of the attacker. - * @param damageType Use the DMG_ definations. - * @param fakeClassName Classname to fake, you can set this if you - * want a specific weapon to be shown in the HUD kill message. - * @return True on success, false otherwise. - */ -stock bool:Entity_Hurt(entity, damage, attacker=0, damageType=DMG_GENERIC, const String:fakeClassName[]="") -{ - static point_hurt = INVALID_ENT_REFERENCE; - - if (point_hurt == INVALID_ENT_REFERENCE || !IsValidEntity(point_hurt)) { - point_hurt = EntIndexToEntRef(Entity_Create("point_hurt")); - - if (point_hurt == INVALID_ENT_REFERENCE) { - return false; - } - - DispatchSpawn(point_hurt); - } - - AcceptEntityInput(point_hurt, "TurnOn"); - SetEntProp(point_hurt, Prop_Data, "m_nDamage", damage); - SetEntProp(point_hurt, Prop_Data, "m_bitsDamageType", damageType); - Entity_PointHurtAtTarget(point_hurt, entity); - - if (fakeClassName[0] != '\0') { - Entity_SetClassName(point_hurt, fakeClassName); - } - - AcceptEntityInput(point_hurt, "Hurt", attacker); - AcceptEntityInput(point_hurt, "TurnOff"); - - if (fakeClassName[0] != '\0') { - Entity_SetClassName(point_hurt, "point_hurt"); - } - - return true; -} - -/* - * Gets the parent entity of an entity. - * - * @param entity Entity Index. - * @return Entity Index of the parent. - */ -stock Entity_GetParent(entity) -{ - return GetEntPropEnt(entity, Prop_Data, "m_pParent"); -} - -/* - * Clears the parent of an entity. - * - * @param entity Entity Index. - * @noreturn - */ -stock Entity_ClearParent(entity) -{ - SetVariantString(""); - AcceptEntityInput(entity, "ClearParent"); -} - -/* - * Sets the parent entity of an entity. - * - * @param entity Entity Index. - * @param parentEntity Entity Index of the new parent. - * @noreturn - */ -stock Entity_SetParent(entity, parent) -{ - SetVariantString("!activator"); - AcceptEntityInput(entity, "SetParent", parent); -} - - -/* - * Callback for Change_OverTime. - * Note that every parameter is a reference and can be changed during this callback. - * You can get the elapsed time since start by multiply tick with currentCall. - * - * @param entity Entity Index. - * @param interval The current interval from the current game time to execute the next call of this function. - * @param currentCall The current call number (0 is the 1st call at 0.0 seconds, 1 the 2nd call at tick*1 seconds, ...). - * @return When true this callback will be called again at the next defined tick, otherwise it won't. - */ -functag Entity_ChangeOverTimeCallback bool:public(&entity, &Float:interval, ¤tCall); - -/* - * Creates a timer and provides a callback to change various things about an entity over time. - * - * @param entity Entity Index. - * @param interval Interval from the current game time to execute the given function. - * @noreturn - */ -stock Entity_ChangeOverTime(entity, Float:interval=0.1, Entity_ChangeOverTimeCallback:valueCallback) -{ - new Handle:dataPack = CreateDataPack(); - WritePackCell(dataPack, EntIndexToEntRef(entity)); - WritePackFloat(dataPack, interval); - WritePackCell(dataPack, 0); -#if SOURCEMOD_V_MAJOR >= 1 && SOURCEMOD_V_MINOR >= 7 - WritePackFunction(dataPack, valueCallback); -#else - WritePackCell(dataPack, _:valueCallback); -#endif - ResetPack(dataPack); - __smlib_Timer_ChangeOverTime(INVALID_HANDLE,dataPack); -} - -public Action:__smlib_Timer_ChangeOverTime(Handle:Timer, Handle:dataPack) -{ - new entity = EntRefToEntIndex(ReadPackCell(dataPack)); - if(!Entity_IsValid(entity)){ - return Plugin_Stop; - } - - new Float:interval = ReadPackFloat(dataPack); - new currentCall = ReadPackCell(dataPack); -#if SOURCEMOD_V_MAJOR >= 1 && SOURCEMOD_V_MINOR >= 7 - new Function:callback = ReadPackFunction(dataPack); -#else - new Function:callback = Function:ReadPackCell(dataPack); -#endif - - new any:result; - Call_StartFunction(INVALID_HANDLE, callback); - Call_PushCellRef(entity); - Call_PushFloatRef(interval); - Call_PushCellRef(currentCall); - Call_Finish(result); - - if(result == false){ - return Plugin_Stop; - } - - ResetPack(dataPack,true); - WritePackCell(dataPack, EntIndexToEntRef(entity)); - WritePackFloat(dataPack, interval); - WritePackCell(dataPack, currentCall+1); -#if SOURCEMOD_V_MAJOR >= 1 && SOURCEMOD_V_MINOR >= 7 - WritePackFunction(dataPack, callback); -#else - WritePackCell(dataPack, _:callback); -#endif - ResetPack(dataPack); - CreateTimer(interval,__smlib_Timer_ChangeOverTime,dataPack); - return Plugin_Stop; -} - - -/** - * Gets the next child, entity is parent of. - * - * @param client Entity Index (of Parent) - * @param start Start Index. - * @return Entity Index or -1 if no entity was found. - */ -stock Entity_GetNextChild(parent, start=0) -{ - for (new entity=start; entity <= 2048; entity++) { - - if (!Entity_IsValid(entity)) { - continue; - } - - if (entity > 0 && entity <= MaxClients && !IsClientConnected(entity)) { - continue; - } - - if (Entity_GetParent(entity) == parent) { - return entity; - } - } - - return INVALID_ENT_REFERENCE; -} -/** - * Gets the move/open direction of an entity (only available for func_door*, prop_door* and func_movelinear). - * Ex: if vec[2] is 1.0 a func_door moves straight up. - * - * @param entity Entity index. - * @param vec Vector. - * @noreturn - */ -stock Entity_GetMoveDirection(entity, Float:vec[3]) -{ - GetEntPropVector(entity, Prop_Data, "m_vecMoveDir", vec); -} -/** - * Sets the move/open direction of an entity (only available for func_door*, prop_door* and func_movelinear). - * Ex: if vec[2] is 1.0 a func_door moves straight up. - * - * @param entity Entity index. - * @param vec Vector. - * @noreturn - */ -stock Entity_SetMoveDirection(entity, const Float:vec[3]) -{ - SetEntPropVector(entity, Prop_Data, "m_vecMoveDir", vec); -} - -/** - * Returns if the entity will force close (won't be blockable by players and/or objects) or not when triggered to move. - * - * @param entity Entity index. - * @return True if the door will force close, otherwise false. - */ -stock bool:Entity_GetForceClose(entity) -{ - return bool:GetEntProp(entity, Prop_Data, "m_bForceClosed"); -} - -/** - * Sets if the door should force close (souldn't be blockable by players and/or objects) or not when triggered to move. - * - * @param entity Entity index. - * @param forceClose If true the door will force close, otherwise it won't. - * @noreturn - */ -stock Entity_SetForceClose(entity, bool:forceClose) -{ - SetEntProp(entity, Prop_Data, "m_bForceClosed", forceClose); -} - -/** - * Gets the speed of a moving entity (like doors: open close speed). - * - * @param entity Entity index. - * @return Speed of the entity. - */ -stock Float:Entity_GetSpeed(entity) -{ - return GetEntPropFloat(entity, Prop_Data, "m_flSpeed"); -} - -/** - * Sets how fast an entity moves (like doors: open close speed). - * - * @param entity Entity index. - * @param speed The new speed of the entity. - * @noreturn - */ -stock Entity_SetSpeed(entity, Float:speed) -{ - SetEntPropFloat(entity, Prop_Data, "m_flSpeed", speed); -} - -/** - * Gets the damage of a moving entity when blocked (like doors when open or close and players and/or objects are between the entity and something else). - * Note: Negative values add health to the blocking entity. - * - * @param entity Entity index. - * @return Damage. - */ -stock Float:Entity_GetBlockDamage(entity) -{ - return GetEntPropFloat(entity, Prop_Data, "m_flBlockDamage"); -} - -/** - * Sets the damage of a moving entity when blocked (like doors when open or close and players and/or objects are between the entity and something else). - * Note: Negative values add health to the blocking entity. - * - * @param entity Entity index. - * @param damage Damage. - * @noreturn - */ -stock Entity_SetBlockDamage(entity, Float:damage) -{ - SetEntPropFloat(entity, Prop_Data, "m_flBlockDamage", damage); -} - -/** - * Returns if the given entity is disabled or not. - * - * @param entity Entity index. - * @return True if entity is disabled, otherwise false. - */ -stock bool:Entity_IsDisabled(entity) -{ - return bool:GetEntProp(entity, Prop_Data, "m_bDisabled", 1); -} - -/** - * Disables the given entity. - * - * @param entity Entity index. - * @return True if successful otherwise false. - */ -stock Entity_Disable(entity) -{ - return AcceptEntityInput(entity, "Disable"); -} - -/** - * Enables the given entity. - * - * @param entity Entity index. - * @return True if successful otherwise false. - */ -stock Entity_Enable(entity) -{ - return AcceptEntityInput(entity, "Enable"); -} - - -// settings for m_takedamage taken from hl2sdk-ob-valve\game\shared\shareddefs.h -#define DAMAGE_NO 0 -#define DAMAGE_EVENTS_ONLY 1 // Call damage functions, but don't modify health -#define DAMAGE_YES 2 -#define DAMAGE_AIM 3 - -/** - * Sets the mode for an entity to take damage. - * Note: This is used to give a client god mode (DAMAGE_NO). - * - * @param entity Entity index. - * @param value Mode, use DAMAGE_* defines. - * @noreturn - */ -stock Entity_SetTakeDamage(entity, value) -{ - SetEntProp(entity, Prop_Data, "m_takedamage", value, 1); -} - -/** - * Gets the mode for an entity to take damage. - * Note: When the return value is DAMAGE_NO then the client is using godmode. - * - * @param entity Entity index. - * @return Take damage mode (DAMAGE_*). - */ -stock Entity_GetTakeDamage(entity) -{ - return GetEntProp(entity, Prop_Data, "m_takedamage", 1); -} - -/** - * Sets the minimum of damage required to hurt this entity. - * Example: This is used to block any damage done by projectile weapons against a gun ship in Half-Life 2. - * - * @param entity Entity index. - * @param minDamage Minimum required damage. - * @noreturn - */ -stock Entity_SetMinHealthDamage(entity, minDamage) -{ - SetEntProp(entity, Prop_Data, "m_iMinHealthDmg", minDamage); -} - -/** - * Gets the minimum of damage required to hurt this entity. - * Example: This is used to block any damage done by projectile weapons against a gun ship in Half-Life 2. - * - * @param entity Entity index. - * @return Minimum required damage. - */ -stock Entity_GetMinHealthDamage(entity) -{ - return GetEntProp(entity, Prop_Data, "m_iMinHealthDmg"); -} - -/** - * Gets an entity's color. - * - * @param entity Entity index - * @param color 4 dimensional array where [r,g,b,a] values are stored - * @noreturn - * @error Invalid entity index, or lack of mod compliance. - */ -stock Entity_GetRenderColor(entity, color[4]) -{ - static bool:gotconfig = false; - static String:prop[32]; - - if (!gotconfig) { - new Handle:gc = LoadGameConfigFile("core.games"); - new bool:exists = GameConfGetKeyValue(gc, "m_clrRender", prop, sizeof(prop)); - CloseHandle(gc); - - if (!exists) { - strcopy(prop, sizeof(prop), "m_clrRender"); - } - - gotconfig = true; - } - - new offset = GetEntSendPropOffs(entity, prop); - - if (offset <= 0) { - ThrowError("SetEntityRenderColor not supported by this mod"); - } - - for (new i=0; i < 4; i++) { - color[i] = GetEntData(entity, offset + i + 1, 1); - } -} - -/** - * Sets an entity's color. - * Doesn't change the value, if set to -1. - * - * @param entity Entity index - * @param r Amount of red (0-255) - * @param g Amount of green (0-255) - * @param b Amount of blue (0-255) - * @param a Amount of alpha (0-255) - * @noreturn - * @error Invalid entity index, or lack of mod compliance. - */ -stock Entity_SetRenderColor(entity, r=-1, g=-1, b=-1, a=-1) -{ - static bool:gotconfig = false; - static String:prop[32]; - - if (!gotconfig) { - new Handle:gc = LoadGameConfigFile("core.games"); - new bool:exists = GameConfGetKeyValue(gc, "m_clrRender", prop, sizeof(prop)); - CloseHandle(gc); - - if (!exists) { - strcopy(prop, sizeof(prop), "m_clrRender"); - } - - gotconfig = true; - } - - new offset = GetEntSendPropOffs(entity, prop); - - if (offset <= 0) { - ThrowError("SetEntityRenderColor not supported by this mod"); - } - - if(r != -1) { - SetEntData(entity, offset, r, 1, true); - } - - if(g != -1) { - SetEntData(entity, offset + 1, g, 1, true); - } - - if(b != -1) { - SetEntData(entity, offset + 2, b, 1, true); - } - - if(a != -1) { - SetEntData(entity, offset + 3, a, 1, true); - } -} - -/** - * Sends the 'addouput' command to an entity. - * - * @param entity Entity Index. - * @param input Input command. - * @param activator Entity index which initiated the sequence of actions (-1 for a NULL entity). - * @param caller Entity index from which this event is sent (-1 for a NULL entity). - * @param outputid Unknown. - * @return True if successful, otherwise false. - */ -stock bool:Entity_AddOutput(entity, const String:input[], activator=-1, caller=-1, outputid=0) -{ - SetVariantString(input); - return AcceptEntityInput(entity, "addoutput", activator, caller, outputid); -} +#if defined _smlib_entities_included + #endinput +#endif +#define _smlib_entities_included + +#include +#include +#include + +/** + * Macro for iterating trough all children (entities it is parent of) of an entity. + * + * @param 1 Entity Index of the parent. + * @param 2 Name of the children entity index variable (will be only valid in the loop). + */ +#define LOOP_CHILDREN(%1,%2) for (int %2=Entity_GetNextChild(%1); %2 != INVALID_ENT_REFERENCE; %2=Entity_GetNextChild(%1, ++%2)) + +/* + * Checks if an entity is valid and exists. + * + * @param entity Entity Index. + * @return True if the entity is valid, false otherwise. + */ +stock bool Entity_IsValid(int entity) +{ + return IsValidEntity(entity); +} + +/** + * Finds an entity by its name. + * You can optionally specify the classname to search for. + * Note: If the classname is specified it uses The Sourcemod native + * function FindEntityByClassname() which uses the engine's + * linked entity list for finding entities. This might be + * cheaper, use this if you call this function very often. + * + * @param name Name of the entity you want so search. + * @param className Optional: Classname of the entity + * @return Entity index or INVALID_ENT_REFERENCE if not matching entity was found. + */ +stock int Entity_FindByName(const char[] name, const char[] className="") +{ + if (className[0] == '\0') { + // Hack: Double the limit to gets none-networked entities too. + int realMaxEntities = GetMaxEntities() * 2; + for (int entity=0; entity < realMaxEntities; entity++) { + + if (!IsValidEntity(entity)) { + continue; + } + + if (Entity_NameMatches(entity, name)) { + return entity; + } + } + } + else { + int entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { + + if (Entity_NameMatches(entity, name)) { + return entity; + } + } + } + + return INVALID_ENT_REFERENCE; +} + +/** + * Finds an entity by its HammerID. + * The newer version of Valve's Hammer editor + * sets a unique ID for each entity in a map. + * It only finds the first occurence. + * Note: If the classname is specified it uses The Sourcemod native + * function FindEntityByClassname() which uses the engine's + * linked entity list for finding entities. This might be + * cheaper, use this if you call this function very often. + * + * @param hammerId Hammer editor ID + * @param className Optional: Classname of the entity + * @return Edict Index or INVALID_ENT_REFERENCE if no entity was found. + */ +stock int Entity_FindByHammerId(int hammerId, const char[] className="") +{ + if (className[0] == '\0') { + // Hack: Double the limit to gets none-networked entities too. + int realMaxEntities = GetMaxEntities() * 2; + for (int entity=0; entity < realMaxEntities; entity++) { + + if (!IsValidEntity(entity)) { + continue; + } + + if (Entity_GetHammerId(entity) == hammerId) { + return entity; + } + } + } + else { + int entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { + + if (Entity_GetHammerId(entity) == hammerId) { + return entity; + } + } + } + + return INVALID_ENT_REFERENCE; +} + +/** + * Searches for an entity by classname. + * This is a wrapper around FindEntityByClassname + * and has been added for completion. + * + * @param startEnt The entity index after which to begin searching from. Use -1 to start from the first entity. + * @param classname Classname of the entity to find. + * @return Entity index >= 0 if found, -1 otherwise. + */ + +stock int Entity_FindByClassName(int startEntity, const char[] className) +{ + return FindEntityByClassname(startEntity, className); +} + +/** + * Checks if an entity (partially) matches a specific entity class. + * + * @param entity Entity Index. + * @param className Classname String. + * @partialMatch If to do a partial classname check. + * @return True if the classname matches, false otherwise. + */ +stock bool Entity_ClassNameMatches(int entity, const char[] className, bool partialMatch=false) +{ + char entity_className[64]; + Entity_GetClassName(entity, entity_className, sizeof(entity_className)); + + if (partialMatch) { + return (StrContains(entity_className, className) != -1); + } + + return StrEqual(entity_className, className); +} + +/** + * Checks if an entity matches a name + * + * @param entity Entity Index. + * @param class Name String. + * @return True if the name matches, false otherwise. + */ +stock bool Entity_NameMatches(int entity, const char[] name) +{ + char entity_name[128]; + Entity_GetName(entity, entity_name, sizeof(entity_name)); + + return StrEqual(name, entity_name); +} + +/** + * Gets the Name of an entity. + * + * @param entity Entity index. + * @param buffer Return/Output buffer. + * @param size Max size of buffer. + * @return Number of non-null bytes written. + */ +stock int Entity_GetName(int entity, char[] buffer, int size) +{ + return GetEntPropString(entity, Prop_Data, "m_iName", buffer, size); +} + +/** + * Sets the Name of an entity. + * + * @param entity Entity index. + * @param name The name you want to give. + * @return True on success, false otherwise. + */ +stock bool Entity_SetName(int entity, const char[] name, any ...) +{ + char format[128]; + VFormat(format, sizeof(format), name, 3); + + return DispatchKeyValue(entity, "targetname", format); +} + +/** + * Gets the Classname of an entity. + * This is like GetEdictClassname(), except it works for ALL + * entities, not just edicts. + * + * @param entity Entity index. + * @param buffer Return/Output buffer. + * @param size Max size of buffer. + * @return Number of non-null bytes written. + */ +stock int Entity_GetClassName(int entity, char[] buffer, int size) +{ + return GetEntPropString(entity, Prop_Data, "m_iClassname", buffer, size); +} + +/** + * Sets the Classname of an entity. + * + * @param entity Entity index. + * @param name The name you want to give. + * @return True on success, false otherwise. + */ +stock bool Entity_SetClassName(int entity, const char[] className) +{ + return DispatchKeyValue(entity, "classname", className); +} + +/** + * Gets the Target name of an other entity + * + * @param entity Entity index. + * @param buffer Return/Output buffer. + * @param size Max size of buffer. + * @return Number of non-null bytes written. + */ +stock int Entity_GetTargetName(int entity, char[] buffer, int size) +{ + return GetEntPropString(entity, Prop_Data, "m_target", buffer, size); +} + +/** + * Sets the Target name of an other Entity + * + * @param entity Entity index. + * @param name The target name you want to set + * @return True on success, false otherwise. + */ +stock bool Entity_SetTargetName(int entity, const char[] name, any ...) +{ + char format[128]; + VFormat(format, sizeof(format), name, 3); + + return DispatchKeyValue(entity, "target", format); +} + +/** + * Gets the Global Name of an entity. + * + * @param entity Entity index. + * @param buffer Return/Output buffer. + * @param size Max size of buffer. + * @return Number of non-null bytes written. + */ +stock int Entity_GetGlobalName(int entity, char[] buffer, int size) +{ + return GetEntPropString(entity, Prop_Data, "m_iGlobalname", buffer, size); +} + +/** + * Sets the Global Name of an entity. + * + * @param entity Entity index. + * @param name The global name you want to set. + * @return True on success, false otherwise. + */ +stock bool Entity_SetGlobalName(int entity, const char[] name, any ...) +{ + char format[128]; + VFormat(format, sizeof(format), name, 3); + + return DispatchKeyValue(entity, "globalname", format); +} + +/** + * Gets the Parent name of an entity. + * + * @param entity Entity index. + * @param buffer Return/Output buffer. + * @param size Max size of buffer. + * @return Number of non-null bytes written. + */ +stock int Entity_GetParentName(int entity, char[] buffer, int size) +{ + return GetEntPropString(entity, Prop_Data, "m_iParent", buffer, size); +} + +/** + * Sets the Parent name of an entity. + * + * @param entity Entity index. + * @param name The parent name you want to set. + * @return True on success, false otherwise. + */ +stock bool Entity_SetParentName(int entity, const char[] name, any ...) +{ + char format[128]; + VFormat(format, sizeof(format), name, 3); + + return DispatchKeyValue(entity, "parentname", format); +} + +/** + * Gets the Hammer-ID of an entity. + * The Hammer Editor gives every entity a unique ID. + * Note: Old maps don't have Hammer-ID's set for entities + * + * @param entity Entity index. + * @return Hammer ID. + */ +stock int Entity_GetHammerId(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_iHammerID"); +} + +/** + * Gets the radius (m_flRadius) of an entity. + * + * @param entity Entity index. + * @return Radius + */ +stock float Entity_GetRadius(int entity) +{ + return GetEntPropFloat(entity, Prop_Data, "m_flRadius"); +} + +/** + * Sets the radius (m_flRadius) of an entity. + * + * @param entity Entity index. + * @param radius Radius value + */ +stock void Entity_SetRadius(int entity, float radius) +{ + SetEntPropFloat(entity, Prop_Data, "m_flRadius", radius); +} + +/** + * Gets the Mins of an entity. + * + * @param entity Entity index. + * @param vec Buffer to hold the vector. + */ +stock void Entity_GetMinSize(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Send, "m_vecMins", vec); +} + +/** + * Sets the Mins of an entity. + * + * @param entity Entity index. + * @param vec Vector. + */ +stock void Entity_SetMinSize(int entity, const float vecMins[3]) +{ + SetEntPropVector(entity, Prop_Send, "m_vecMins", vecMins); +} + +/** + * Gets the Mins of an entity. + * This functions isn't safe to use, use Entity_SetMinMaxSize() instead. + * + * @param entity Entity index + * @param vec Buffer to hold the vector + */ +stock void Entity_GetMaxSize(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Send, "m_vecMaxs", vec); +} + +/** + * Sets the Maxs of an entity. + * This functions isn't safe to use, use Entity_SetMinMaxSize() instead. + * + * @param entity Entity index. + * @param vec Buffer to hold the vector. + */ +stock void Entity_SetMaxSize(int entity, const float vecMaxs[3]) +{ + SetEntPropVector(entity, Prop_Send, "m_vecMaxs", vecMaxs); +} + +/** + * Sets the Min and Max Size of an entity. + * Code is taken from HL2SDK and rewritten for Sourcemod. + * + * @param entity Entity index. + * @param vecMins Min size Vector + * @param vecMaxs Max size Vector + */ +stock void Entity_SetMinMaxSize(int entity, float vecMins[3], float vecMaxs[3]) +{ + // Taken from hl2sdk-ob-valve\game\server\util.cpp SetMinMaxSize() + // Todo: Replace this by a SDK call + for (int i=0; i<3; i++) { + + if (vecMins[i] > vecMaxs[i]) { + ThrowError("Error: mins[%d] > maxs[%d] of entity %d", i, i, EntRefToEntIndex(entity)); + } + } + + float m_vecMins[3], m_vecMaxs[3]; + Entity_GetMinSize(entity, m_vecMins); + Entity_GetMaxSize(entity, m_vecMaxs); + + if (Math_VectorsEqual(m_vecMins, vecMins) && Math_VectorsEqual(m_vecMaxs, vecMaxs)) { + return; + } + + Entity_SetMinSize(entity, vecMins); + Entity_SetMaxSize(entity, vecMaxs); + + float vecSize[3]; + SubtractVectors(vecMaxs, vecMins, vecSize); + Entity_SetRadius(entity, GetVectorLength(vecSize) * 0.5); + + Entity_MarkSurrBoundsDirty(entity); +} + +/* + * Spawn Flags + * Many entities define their specific spawnflags, check the HL2SDK. + */ + +/* + * Phys prop spawnflags + * Taken from hl2sdk-ob-valve\game\shared\props_shared.h + */ +#define SF_PHYSPROP_START_ASLEEP 0x000001 +#define SF_PHYSPROP_DONT_TAKE_PHYSICS_DAMAGE 0x000002 // this prop can't be damaged by physics collisions +#define SF_PHYSPROP_DEBRIS 0x000004 +#define SF_PHYSPROP_MOTIONDISABLED 0x000008 // motion disabled at startup (flag only valid in spawn - motion can be enabled via input) +#define SF_PHYSPROP_TOUCH 0x000010 // can be 'crashed through' by running player (plate glass) +#define SF_PHYSPROP_PRESSURE 0x000020 // can be broken by a player standing on it +#define SF_PHYSPROP_ENABLE_ON_PHYSCANNON 0x000040 // enable motion only if the player grabs it with the physcannon +#define SF_PHYSPROP_NO_ROTORWASH_PUSH 0x000080 // The rotorwash doesn't push these +#define SF_PHYSPROP_ENABLE_PICKUP_OUTPUT 0x000100 // If set, allow the player to +USE this for the purposes of generating an output +#define SF_PHYSPROP_PREVENT_PICKUP 0x000200 // If set, prevent +USE/Physcannon pickup of this prop +#define SF_PHYSPROP_PREVENT_PLAYER_TOUCH_ENABLE 0x000400 // If set, the player will not cause the object to enable its motion when bumped into +#define SF_PHYSPROP_HAS_ATTACHED_RAGDOLLS 0x000800 // Need to remove attached ragdolls on enable motion/etc +#define SF_PHYSPROP_FORCE_TOUCH_TRIGGERS 0x001000 // Override normal debris behavior and respond to triggers anyway +#define SF_PHYSPROP_FORCE_SERVER_SIDE 0x002000 // Force multiplayer physics object to be serverside +#define SF_PHYSPROP_RADIUS_PICKUP 0x004000 // For Xbox, makes small objects easier to pick up by allowing them to be found +#define SF_PHYSPROP_ALWAYS_PICK_UP 0x100000 // Physcannon can always pick this up, no matter what mass or constraints may apply. +#define SF_PHYSPROP_NO_COLLISIONS 0x200000 // Don't enable collisions on spawn +#define SF_PHYSPROP_IS_GIB 0x400000 // Limit # of active gibs + +/* + * Physbox Spawnflags. Start at 0x01000 to avoid collision with CBreakable's + * Taken from hl2sdk-ob-valve\game\server\physobj.h + */ +#define SF_PHYSBOX_ASLEEP 0x01000 +#define SF_PHYSBOX_IGNOREUSE 0x02000 +#define SF_PHYSBOX_DEBRIS 0x04000 +#define SF_PHYSBOX_MOTIONDISABLED 0x08000 +#define SF_PHYSBOX_USEPREFERRED 0x10000 +#define SF_PHYSBOX_ENABLE_ON_PHYSCANNON 0x20000 +#define SF_PHYSBOX_NO_ROTORWASH_PUSH 0x40000 // The rotorwash doesn't push these +#define SF_PHYSBOX_ENABLE_PICKUP_OUTPUT 0x80000 +#define SF_PHYSBOX_ALWAYS_PICK_UP 0x100000 // Physcannon can always pick this up, no matter what mass or constraints may apply. +#define SF_PHYSBOX_NEVER_PICK_UP 0x200000 // Physcannon will never be able to pick this up. +#define SF_PHYSBOX_NEVER_PUNT 0x400000 // Physcannon will never be able to punt this object. +#define SF_PHYSBOX_PREVENT_PLAYER_TOUCH_ENABLE 0x800000 // If set, the player will not cause the object to enable its motion when bumped into + +/* + * Spawnflags for func breakable + * Taken from hl2sdk-ob-valve\game\server\func_break.h + */ +#define SF_BREAK_TRIGGER_ONLY 0x0001 // may only be broken by trigger +#define SF_BREAK_TOUCH 0x0002 // can be 'crashed through' by running player (plate glass) +#define SF_BREAK_PRESSURE 0x0004 // can be broken by a player standing on it +#define SF_BREAK_PHYSICS_BREAK_IMMEDIATELY 0x0200 // the first physics collision this breakable has will immediately break it +#define SF_BREAK_DONT_TAKE_PHYSICS_DAMAGE 0x0400 // this breakable doesn't take damage from physics collisions +#define SF_BREAK_NO_BULLET_PENETRATION 0x0800 // don't allow bullets to penetrate + +/* + * Spawnflags for func_pushable (it's also func_breakable, so don't collide with those flags) + * Taken from hl2sdk-ob-valve\game\server\func_break.h + */ +#define SF_PUSH_BREAKABLE 0x0080 +#define SF_PUSH_NO_USE 0x0100 // player cannot +use pickup this ent + +/** + * Gets the Spawnflags of an entity. + * + * @param entity Entity index. + * @return Spawnflags value + */ +stock int Entity_GetSpawnFlags(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_spawnflags"); +} + +/** + * Sets the Spawnflags of an entity. + * + * @param entity Entity index. + * @param flags Flags value + */ +stock void Entity_SetSpawnFlags(int entity, int flags) +{ + SetEntProp(entity, Prop_Data, "m_spawnflags", flags); +} + +/** + * Adds Spawnflags to an entity. + * + * @param entity Entity index. + * @param flags Flags value + */ +stock void Entity_AddSpawnFlags(int entity, int flags) +{ + int spawnFlags = Entity_GetSpawnFlags(entity); + spawnFlags |= flags; + Entity_SetSpawnFlags(entity, spawnFlags); +} + +/** + * Removes Spawnflags from an entity. + * + * @param entity Entity index. + * @param flags Flags value + */ +stock void Entity_RemoveSpawnFlags(int entity, int flags) +{ + int spawnFlags = Entity_GetSpawnFlags(entity); + spawnFlags &= ~flags; + Entity_SetSpawnFlags(entity, spawnFlags); +} + +/** + * Clears all Spawnflags of an entity. + * + * @param entity Entity index. + * @noretur */ +stock void Entity_ClearSpawnFlags(int entity) +{ + Entity_SetSpawnFlags(entity, 0); +} + +/** + * Returns whether the entity has specific Spawnflags. + * + * @param entity Entity index. + * @param flags Flags value. + * @return True if the entity has the spawnflags set, false otherwise. + */ +stock bool Entity_HasSpawnFlags(int entity, int flags) +{ + return Entity_GetSpawnFlags(entity) & flags == flags; +} + +/* + * Entity flags, CBaseEntity::m_iEFlags + * Taken from: hl2sdk-ob-valve\game\shared\shareddefs.h + */ +enum Entity_Flags +{ + EFL_KILLME = (1<<0), // This entity is marked for death -- This allows the game to actually delete ents at a safe time + EFL_DORMANT = (1<<1), // Entity is dormant, no updates to client + EFL_NOCLIP_ACTIVE = (1<<2), // Lets us know when the noclip command is active. + EFL_SETTING_UP_BONES = (1<<3), // Set while a model is setting up its bones. + EFL_KEEP_ON_RECREATE_ENTITIES = (1<<4), // This is a special entity that should not be deleted when we restart entities only + + EFL_HAS_PLAYER_CHILD= (1<<4), // One of the child entities is a player. + + EFL_DIRTY_SHADOWUPDATE = (1<<5), // Client only- need shadow manager to update the shadow... + EFL_NOTIFY = (1<<6), // Another entity is watching events on this entity (used by teleport) + + // The default behavior in ShouldTransmit is to not send an entity if it doesn't + // have a model. Certain entities want to be sent anyway because all the drawing logic + // is in the client DLL. They can set this flag and the engine will transmit them even + // if they don't have a model. + EFL_FORCE_CHECK_TRANSMIT = (1<<7), + + EFL_BOT_FROZEN = (1<<8), // This is set on bots that are frozen. + EFL_SERVER_ONLY = (1<<9), // Non-networked entity. + EFL_NO_AUTO_EDICT_ATTACH = (1<<10), // Don't attach the edict; we're doing it explicitly + + // Some dirty bits with respect to abs computations + EFL_DIRTY_ABSTRANSFORM = (1<<11), + EFL_DIRTY_ABSVELOCITY = (1<<12), + EFL_DIRTY_ABSANGVELOCITY = (1<<13), + EFL_DIRTY_SURR_COLLISION_BOUNDS = (1<<14), + EFL_DIRTY_SPATIAL_PARTITION = (1<<15), +// UNUSED = (1<<16), + + EFL_IN_SKYBOX = (1<<17), // This is set if the entity detects that it's in the skybox. + // This forces it to pass the "in PVS" for transmission. + EFL_USE_PARTITION_WHEN_NOT_SOL = (1<<18), // Entities with this flag set show up in the partition even when not solid + EFL_TOUCHING_FLUID = (1<<19), // Used to determine if an entity is floating + + // FIXME: Not really sure where I should add this... + EFL_IS_BEING_LIFTED_BY_BARNACLE = (1<<20), + EFL_NO_ROTORWASH_PUSH = (1<<21), // I shouldn't be pushed by the rotorwash + EFL_NO_THINK_FUNCTION = (1<<22), + EFL_NO_GAME_PHYSICS_SIMULATION = (1<<23), + + EFL_CHECK_UNTOUCH = (1<<24), + EFL_DONTBLOCKLOS = (1<<25), // I shouldn't block NPC line-of-sight + EFL_DONTWALKON = (1<<26), // NPC;s should not walk on this entity + EFL_NO_DISSOLVE = (1<<27), // These guys shouldn't dissolve + EFL_NO_MEGAPHYSCANNON_RAGDOLL = (1<<28), // Mega physcannon can't ragdoll these guys. + EFL_NO_WATER_VELOCITY_CHANGE = (1<<29), // Don't adjust this entity's velocity when transitioning into water + EFL_NO_PHYSCANNON_INTERACTION = (1<<30), // Physcannon can't pick these up or punt them + EFL_NO_DAMAGE_FORCES = (1<<31), // Doesn't accept forces from physics damage +}; + +/** + * Gets the Entity flags (m_iEFlags) of an entity. + * + * @param entity Entity index. + * @return Entity flags value + */ +stock Entity_Flags Entity_GetEFlags(int entity) +{ + return view_as(GetEntProp(entity, Prop_Data, "m_iEFlags")); +} + +/** + * Sets the entity's Entity flags (m_iEFlags). + * + * @param entity Entity index. + * @param flags Flags value + */ +stock void Entity_SetEFlags(int entity, Entity_Flags flags) +{ + SetEntProp(entity, Prop_Data, "m_iEFlags", flags); +} + +/** + * Adds Entity flags (m_iEFlags) to an entity. + * + * @param entity Entity index. + * @param flags Flags value + */ +stock void Entity_AddEFlags(int entity, Entity_Flags flags) +{ + Entity_Flags setFlags = Entity_GetEFlags(entity); + setFlags |= flags; + Entity_SetEFlags(entity, setFlags); +} + +/** + * Removes Entity flags (m_iEFlags) from an entity. + * + * @param entity Entity index. + * @param flags Flags value + */ +stock void Entity_RemoveEFlags(int entity, Entity_Flags flags) +{ + Entity_Flags setFlags = Entity_GetEFlags(entity); + setFlags &= ~flags; + Entity_SetEFlags(entity, setFlags); +} + +/** + * Checks if the entity has specific Entity flags (m_iEFlags) set. + * + * @param entity Entity index. + * @param flags Flags value + * @return True if the flags are set, false otherwise. + */ +stock bool Entity_HasEFlags(int entity, Entity_Flags flags) +{ + Entity_Flags currentEFlags = Entity_GetEFlags(entity); + + return currentEFlags & flags == flags; +} + +/** + * Marks the surrounding bounds of an entity as outdated. + * You normally call this when a collision setting has changed. + * + * @param entity Entity index. + */ +stock void Entity_MarkSurrBoundsDirty(int entity) +{ + Entity_AddEFlags(entity, EFL_DIRTY_SURR_COLLISION_BOUNDS); +} + +/* + * CBaseEntity::m_fFlags Functions + * Use the FL_ Defines (FL_ONGROUND, ...) or + * special entity specific flags. + * Note: The flag FL_AIMTARGET probably doesn't work as + * we have current no way of adding/removing it to the AimTarget List. + */ + +/** + * Gets the Flags of an entity. + * + * @param entity Entity Index. + * @return Entity Flags. + */ +stock int Entity_GetFlags(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_fFlags"); +} + +/** + * Sets the Flags of an entity. + * + * @param entity Entity index. + * @param flags New Flags value + */ +stock void Entity_SetFlags(int entity, int flags) +{ + SetEntProp(entity, Prop_Data, "m_fFlags", flags); +} + +/** + * Adds Flags to the entity + * + * @param entity Entity index. + * @param flags Flags to add + * @noreturn + */ +stock void Entity_AddFlags(int entity, int flags) +{ + int setFlags = Entity_GetFlags(entity); + setFlags |= flags; + Entity_SetFlags(entity, flags); +} + +/** + * Removes flags from the entity + * + * @param entity Entity index. + * @param flags Flags to remove + */ +stock void Entity_RemoveFlags(int entity, int flags) +{ + int setFlags = Entity_GetFlags(entity); + setFlags &= ~flags; + Entity_SetFlags(entity, setFlags); +} + +/** + * Toggles the specified flag on the entity. + * Adds the flag to the entity if it doesn't exists + * or removes it otherwise. + * + * @param entity Entity index. + * @param flags Flag to Toggle + */ +stock void Entity_ToggleFlag(int entity, int flag) +{ + int setFlag = Entity_GetFlags(entity); + setFlag ^= flag; + Entity_SetFlags(entity, setFlag); +} + +/** + * Removes all flags from the entity + * + * @param entity Entity index. + */ +stock void Entity_ClearFlags(int entity) +{ + Entity_SetFlags(entity, 0); +} + +/* edict->solid values + * NOTE: Some movetypes will cause collisions independent of SOLID_NOT/SOLID_TRIGGER when the entity moves + * SOLID only effects OTHER entities colliding with this one when they move - UGH! + * + * Solid type basically describes how the bounding volume of the object is represented + * NOTE: These numerical values are used in the FGD by the prop code (see prop_dynamic) + * Taken from: hl2sdk-ob-valve\public\const.h + */ + +enum SolidFlags_t +{ + FSOLID_CUSTOMRAYTEST = 0x0001, // Ignore solid type + always call into the entity for ray tests + FSOLID_CUSTOMBOXTEST = 0x0002, // Ignore solid type + always call into the entity for swept box tests + FSOLID_NOT_SOLID = 0x0004, // Are we currently not solid? + FSOLID_TRIGGER = 0x0008, // This is something may be collideable but fires touch functions + // even when it's not collideable (when the FSOLID_NOT_SOLID flag is set) + FSOLID_NOT_STANDABLE = 0x0010, // You can't stand on this + FSOLID_VOLUME_CONTENTS = 0x0020, // Contains volumetric contents (like water) + FSOLID_FORCE_WORLD_ALIGNED = 0x0040, // Forces the collision rep to be world-aligned even if it's SOLID_BSP or SOLID_VPHYSICS + FSOLID_USE_TRIGGER_BOUNDS = 0x0080, // Uses a special trigger bounds separate from the normal OBB + FSOLID_ROOT_PARENT_ALIGNED = 0x0100, // Collisions are defined in root parent's local coordinate space + FSOLID_TRIGGER_TOUCH_DEBRIS = 0x0200, // This trigger will touch debris objects + + FSOLID_MAX_BITS = 10 +}; + +/** + * Gets the solid flags of the entity + * + * @param entity Entity index. + * @return Solid Flags. + */ +stock SolidFlags_t Entity_GetSolidFlags(int entity) +{ + return view_as(GetEntProp(entity, Prop_Data, "m_usSolidFlags", 2)); +} + +/** + * Sets the solid flags of the entity + * + * @param entity Entity index. + * @param flags Solid Flags. + */ +stock void Entity_SetSolidFlags(int entity, SolidFlags_t flags) +{ + SolidFlags_t oldFlags = Entity_GetSolidFlags(entity); + flags = flags & view_as(0xFFFF); + + if (oldFlags == flags) { + return; + } + + SetEntProp(entity, Prop_Data, "m_usSolidFlags", flags, 2); + + // These two flags, if changed, can produce different surrounding bounds + if ((oldFlags & (FSOLID_FORCE_WORLD_ALIGNED | FSOLID_USE_TRIGGER_BOUNDS)) != + (flags & (FSOLID_FORCE_WORLD_ALIGNED | FSOLID_USE_TRIGGER_BOUNDS))) + { + Entity_MarkSurrBoundsDirty(entity); + } +} + +/** + * Adds solid flags to the entity + * + * @param entity Entity index. + * @param flags Solid Flags. + */ +stock void Entity_AddSolidFlags(int entity, SolidFlags_t flags) +{ + SolidFlags_t newFlags = Entity_GetSolidFlags(entity); + newFlags |= flags; + Entity_SetSolidFlags(entity, newFlags); +} + +/** + * Removes solid flags from the entity. + * + * @param entity Entity index. + * @param flags Solid Flags. + */ +stock void Entity_RemoveSolidFlags(int entity, SolidFlags_t flags) +{ + SolidFlags_t newFlags = Entity_GetSolidFlags(entity); + newFlags &= ~flags; + Entity_SetSolidFlags(entity, newFlags); +} + +/** + * Removes all solid flags from the entity. + * + * @param entity Entity index. + */ +stock void Entity_ClearSolidFlags(int entity) +{ + Entity_SetSolidFlags(entity, view_as(0)); +} + +/** + * Checks whether certain solid flags are set on the entity. + * + * @param entity Entity index. + * @param flags Solid Flags. + * @return True if the specified flags are set, false otherwise. + */ +stock bool Entity_SolidFlagsSet(int entity, SolidFlags_t flagMask) +{ + return Entity_GetSolidFlags(entity) & flagMask == flagMask; +} + +enum SolidType_t +{ + SOLID_NONE = 0, // no solid model + SOLID_BSP = 1, // a BSP tree + SOLID_BBOX = 2, // an AABB + SOLID_OBB = 3, // an OBB (not implemented yet) + SOLID_OBB_YAW = 4, // an OBB, constrained so that it can only yaw + SOLID_CUSTOM = 5, // Always call into the entity for tests + SOLID_VPHYSICS = 6, // solid vphysics object, get vcollide from the model and collide with that + SOLID_LAST, +}; + +/** + * Gets the solidity type of the entity + * + * @param entity Entity index. + * @return Solid Type + */ +stock SolidType_t Entity_GetSolidType(int entity) +{ + return view_as(GetEntProp(entity, Prop_Data, "m_nSolidType", 1)); +} + +/** + * Sets the solidity type of the entity + * + * @param entity Entity index. + * @param Solid Type value. + */ +stock void Entity_SetSolidType(int entity, SolidType_t value) +{ + SetEntProp(entity, Prop_Send, "m_nSolidType", value, 1); + Entity_MarkSurrBoundsDirty(entity); +} + +/** + * Checks whether the entity is solid or not. + * + * @param entity Entity index. + * @return True if the entity is solid, false otherwise. + */ +stock bool Entity_IsSolid(int entity) +{ + return (Entity_GetSolidType(entity) != SOLID_NONE && + !Entity_SolidFlagsSet(entity, FSOLID_NOT_SOLID)); +} + +/** + * Retrieves the model path of a given entity. + * Returns "*num" for Brush entities. + * + * @param entity entity reference or index + * @param model buffer String for the model + * @param size max size of buffer string + * @return Number of non-null bytes written. + */ +stock int Entity_GetModel(int entity, char[] buffer, int size) +{ + return GetEntPropString(entity, Prop_Data, "m_ModelName", buffer, size); +} + +/** + * Sets the model to a given entity. + * Be sure it has been precached. + * This is an alias for SetEntityModel() + * + * @param entity Entity index + * @param model Model name + */ +stock void Entity_SetModel(int entity, const char[] model) +{ + SetEntityModel(entity, model); +} + +/** + * Gets the entity's model index, if it has one set. + * + * @param entity Entity index. + * @return The Entity's model index + */ +stock int Entity_GetModelIndex(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_nModelIndex", 2); +} + +/** + * Sets the entity's model index (must be precached) + * + * @param entity Entity index. + * @param index Model Index. + */ +stock void Entity_SetModelIndex(int entity, int index) +{ + SetEntProp(entity, Prop_Data, "m_nModelIndex", index, 2); +} + +/** +* Sets the entity's maxspeed to the given value (in units per second) +* +* @param entity Entity index +* @param maxspeed the maximum speed the entity can move +* @noreturn +*/ +stock void Entity_SetMaxSpeed(int entity, float value) +{ + SetEntPropFloat(entity, Prop_Data, "m_flMaxspeed", value); +} + +/* + * Collision groups + * Taken from hl2sdk-ob-valve/public/const.h + */ +enum Collision_Group_t +{ + COLLISION_GROUP_NONE = 0, + COLLISION_GROUP_DEBRIS, // Collides with nothing but world and static stuff + COLLISION_GROUP_DEBRIS_TRIGGER, // Same as debris, but hits triggers + COLLISION_GROUP_INTERACTIVE_DEB, // Collides with everything except other interactive debris or debris + COLLISION_GROUP_INTERACTIVE, // Collides with everything except interactive debris or debris + COLLISION_GROUP_PLAYER, + COLLISION_GROUP_BREAKABLE_GLASS, + COLLISION_GROUP_VEHICLE, + COLLISION_GROUP_PLAYER_MOVEMENT, // For HL2, same as Collision_Group_Player, for + // TF2, this filters out other players and CBaseObjects + COLLISION_GROUP_NPC, // Generic NPC group + COLLISION_GROUP_IN_VEHICLE, // for any entity inside a vehicle + COLLISION_GROUP_WEAPON, // for any weapons that need collision detection + COLLISION_GROUP_VEHICLE_CLIP, // vehicle clip brush to restrict vehicle movement + COLLISION_GROUP_PROJECTILE, // Projectiles! + COLLISION_GROUP_DOOR_BLOCKER, // Blocks entities not permitted to get near moving doors + COLLISION_GROUP_PASSABLE_DOOR, // Doors that the player shouldn't collide with + COLLISION_GROUP_DISSOLVING, // Things that are dissolving are in this group + COLLISION_GROUP_PUSHAWAY, // Nonsolid on client and server, pushaway in player code + + COLLISION_GROUP_NPC_ACTOR, // Used so NPCs in scripts ignore the player. + COLLISION_GROUP_NPC_SCRIPTED // USed for NPCs in scripts that should not collide with each other +}; + +/** + * Gets the collision group of an entity. + * + * @param entity entity index + * @return Entity collision group. + */ +stock Collision_Group_t Entity_GetCollisionGroup(int entity) +{ + return view_as(GetEntProp(entity, Prop_Data, "m_CollisionGroup")); +} + +/** + * Sets the collision group of an entity. + * + * @param entity entity index + * @param value the new collision group. + */ +stock void Entity_SetCollisionGroup(int entity, Collision_Group_t value) +{ + SetEntProp(entity, Prop_Data, "m_CollisionGroup", value); +} + +/** + * Functions for getting / setting the origin (position) of an entity. + * Go to http://developer.valvesoftware.com/wiki/Origin + * if you want to learn more about origins + */ + +/** + * Gets the Absolute Origin (position) of an entity. + * + * @param entity Entity index. + * @param vec 3 dimensional vector array. + */ +stock void Entity_GetAbsOrigin(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Send, "m_vecOrigin", vec); +} + +/** + * Sets the Absolute Origin (position) of an entity. + * + * @param entity Entity index. + * @param vec 3 dimensional vector array. + */ +stock void Entity_SetAbsOrigin(int entity, const float vec[3]) +{ + // We use TeleportEntity to set the origin more safely + // Todo: Replace this with a call to UTIL_SetOrigin() or CBaseEntity::SetLocalOrigin() + TeleportEntity(entity, vec, NULL_VECTOR, NULL_VECTOR); +} + +/** + * Functions for getting / setting the angles (rotation) of an entity. + * http://developer.valvesoftware.com/wiki/Angles + * if you want to learn more about angles + */ + +/** + * Gets the Angles of an entity + * + * @param entity Entity index. + * @param vec 3 dimensional vector array. + * @noreturn + */ +stock void Entity_GetAbsAngles(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Data, "m_angAbsRotation", vec); +} + +/** + * Sets the Angles of an entity + * + * @param entity Entity index. + * @param vec 3 dimensional vector array. + */ +stock void Entity_SetAbsAngles(int entity, const float vec[3]) +{ + // We use TeleportEntity to set the angles more safely + // Todo: Replace this with a call to CBaseEntity::SetLocalAngles() + TeleportEntity(entity, NULL_VECTOR, vec, NULL_VECTOR); +} + +/** + * Functions for getting / setting the velocity of an entity. + * Go to http://developer.valvesoftware.com/wiki/Velocity + * if you want to learn more about the different kind of velocities. + */ + +/** + * Gets the Local velocity of an entity. + * The local velocity is the velocity generated by the entity. + * + * @param entity Entity index. + * @param vel An 3 dim array + */ +stock void Entity_GetLocalVelocity(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Data, "m_vecVelocity", vec); +} + +/** + * Sets the Local velocity of an entity. + * The local velocity is the velocity generated by the entity. + * Only use this if you know what you are doing, + * the entity can overwrite this value on next frame. + * + * @param entity Entity index. + * @param vel An 3 dim array + */ +stock void Entity_SetLocalVelocity(int entity, const float vec[3]) +{ + SetEntPropVector(entity, Prop_Data, "m_vecVelocity", vec); +} + +/** + * Gets the Base velocity of an entity. + * The base velocity is the velocity applied + * to the entity from other sources . + * + * @param entity Entity index. + * @param vel An 3 dim array + */ +stock void Entity_GetBaseVelocity(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Data, "m_vecBaseVelocity", vec); +} + +/** + * Sets the Base velocity of an entity. + * The base velocity is the velocity applied + * to the entity from other sources . + * + * @param entity Entity index. + * @param vel An 3 dim array + */ +stock void Entity_SetBaseVelocity(int entity, const float vec[3]) +{ + SetEntPropVector(entity, Prop_Data, "m_vecBaseVelocity", vec); +} + +/** + * Gets the Absolute velocity of an entity. + * The absolute velocity is the sum of the local + * and base velocities. It's the actual value used to move. + * + * @param entity Entity index. + * @param vel An 3 dim array + */ +stock void Entity_GetAbsVelocity(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Data, "m_vecAbsVelocity", vec); +} + +/** + * Sets the Absolute velocity of an entity. + * The absolute velocity is the sum of the local + * and base velocities. It's the actual value used to move. + * + * @param entity Entity index. + * @param vel An 3 dim array + */ +stock void Entity_SetAbsVelocity(int entity, const float vec[3]) +{ + // We use TeleportEntity to set the velocity more safely + // Todo: Replace this with a call to CBaseEntity::SetAbsVelocity() + TeleportEntity(entity, NULL_VECTOR, NULL_VECTOR, vec); +} + +/** + * Returns true if the entity is locked. + * + * @param entity Entity index. + * @return True if locked otherwise false. + */ +stock bool Entity_IsLocked(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_bLocked", 1) != 0; +} + +/** + * Locks an entity. + * + * @param entity Entity index. + */ +stock void Entity_Lock(int entity) +{ + SetEntProp(entity, Prop_Data, "m_bLocked", 1, 1); +} +/** + * Unlocks an entity. + * + * @param entity Entity index. + */ +stock void Entity_UnLock(int entity) +{ + SetEntProp(entity, Prop_Data, "m_bLocked", 0, 1); +} + +/** + * Gets the health of an entity. + * + * @param entity entity index. + * @return current health points + */ +stock int Entity_GetHealth(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_iHealth"); +} + +/** + * Sets the health of an entity. + * + * @param entity Entity index. + * @param value Health to set (anything above 511 will overload) + * @param ignoreMax Ignore the entity's maxhealth setting. + * @param kill Kill the entity if health gets to 0. + * @return The health the entity actually got set to. + */ +stock int Entity_SetHealth(int entity, int value, bool ignoreMax=false, bool kill=true) +{ + int health = value; + + if (!ignoreMax) { + int maxHealth = Entity_GetMaxHealth(entity); + + if (health > maxHealth) { + health = maxHealth; + } + } + + if (health < 0) { + health = 0; + } + + SetEntProp(entity, Prop_Data, "m_iHealth", health); + + if (health <= 0) { + Entity_Kill(entity); + } + + return health; +} + +/** + * Add health to an entity + * + * @param entity Entity index + * @param value Health to add + * @param ignoreMax Ignore the entity's maxhealth setting. + * @param kill Kill the entity if health gets to 0. + * @return Returns the new health value set + */ +stock int Entity_AddHealth(int entity, int value, bool ignoreMax=false, bool kill=true) +{ + int health = Entity_GetHealth(entity); + + health += value; + + return Entity_SetHealth(entity, health, ignoreMax, kill); +} + +/** + * Takes health from an entity + * + * @param entity entity index + * @param value health to add + * @return returns the new health value set + */ +stock int Entity_TakeHealth(int entity, int value, bool ignoreMax=false, bool kill=true) +{ + int health = Entity_GetHealth(entity); + + health -= value; + + return Entity_SetHealth(entity, health, ignoreMax, kill); +} + +/** + * Get the max health of an entity + * + * @param entity Entity Index + * @return Max health points + */ +stock int Entity_GetMaxHealth(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_iMaxHealth"); +} + + +/** + * Set the max health of an entity. + * + * @param entity Entity index + * @param value Max health to set (anything above 511 will overload) + */ +stock void Entity_SetMaxHealth(int entity, int value) +{ + SetEntProp(entity, Prop_Data, "m_iMaxHealth", value); +} + +/** + * Returns the Float distance between an entity + * and a vector origin. + * + * @param entity Entity Index. + * @param target Vector Origin. + * @return Distance Float value. + */ +stock float Entity_GetDistanceOrigin(int entity, const float vec[3]) +{ + float entityVec[3]; + Entity_GetAbsOrigin(entity, entityVec); + + return GetVectorDistance(entityVec, vec); +} + +/** + * Returns the Float distance between two entities. + * Both entities must be valid. + * + * @param entity Entity Index. + * @param target Target Entity Index. + * @return Distance Float value. + */ +stock float Entity_GetDistance(int entity, int target) +{ + float targetVec[3]; + Entity_GetAbsOrigin(target, targetVec); + + return Entity_GetDistanceOrigin(entity, targetVec); +} + +/** + * Checks if the given 2 entitys are within a given range. + * + * @param entity Entity Index. + * @param target Target Entity Index. + * @param distance Max Float distance. + * @return True if the given entities are closer than the given distance value, false otherwise. + */ +stock bool Entity_InRange(int entity, int target, float distance) +{ + if (Entity_GetDistance(entity, target) > distance) { + return false; + } + + return true; +} + +/** + * Enables the motion of an entity. + * + * @param entity Entity index. + * @return True on success, false otherwise + */ +stock bool Entity_EnableMotion(int entity) +{ + return AcceptEntityInput(entity, "enablemotion"); +} + +/** + * Disables the motion of an entity. + * + * @param entity Entity index. + * @return True on success, false otherwise + */ +stock bool Entity_DisableMotion(int entity) +{ + return AcceptEntityInput(entity, "disablemotion"); +} + +/** + * Freezes an entity by setting the FL_FROZEN flag. + * + * @param entity Entity index. + */ +stock void Entity_Freeze(int entity) +{ + Entity_AddFlags(entity, FL_FROZEN); +} + +/** + * Unfreezes an entity by removing the FL_FROZEN flag. + * + * @param entity Entity index. + */ +stock void Entity_UnFreeze(int entity) +{ + Entity_RemoveFlags(entity, FL_FROZEN); +} + + +/** + * This function points an entity to another with the targetname + * and name. Useful for allot of entities like trigger_teleport. + * If the name is not specified it will be generated automatically. + * + * @param entity Entity index. + * @param target Target entity index. + * @param Optional: target name + */ +stock void Entity_PointAtTarget(int entity, int target, const char[] name="") +{ + char targetName[128]; + Entity_GetTargetName(entity, targetName, sizeof(targetName)); + + if (name[0] == '\0') { + + if (targetName[0] == '\0') { + // Let's generate our own name + Format( + targetName, + sizeof(targetName), + "_smlib_Entity_PointAtTarget:%d", + target + ); + } + } + else { + strcopy(targetName, sizeof(targetName), name); + } + + Entity_SetTargetName(entity, targetName); + Entity_SetName(target, targetName); +} + +/** + * This function points a point_hurt entity to another damage target entity.. + * and name. Useful for allot of entities like trigger_teleport. + * If the name is not specified it will be generated automatically. + * + * @param entity Entity index. + * @param target Target entity index. + * @param Optional: target name + */ +stock void Entity_PointHurtAtTarget(int entity, int target, const char[] name="") +{ + char targetName[128]; + Entity_GetTargetName(entity, targetName, sizeof(targetName)); + + if (name[0] == '\0') { + + if (targetName[0] == '\0') { + // Let's generate our own name + Format( + targetName, + sizeof(targetName), + "_smlib_Entity_PointHurtAtTarget:%d", + target + ); + } + } + else { + strcopy(targetName, sizeof(targetName), name); + } + + DispatchKeyValue(entity, "DamageTarget", targetName); + Entity_SetName(target, targetName); +} + +/** + * Checks if an entity is a player or not. + * No checks are done if the entity is actually valid, + * the player is connected or ingame. + * + * @param entity Entity index. + * @return True if the entity is a player, false otherwise. + */ +stock bool Entity_IsPlayer(int entity) +{ + if (entity < 1 || entity > MaxClients) { + return false; + } + + return true; +} + +/** + * Creates an entity by classname. + * + * @param className Classname String. + * @param ForceEdictIndex Edict Index to use. + * @return Entity Index or INVALID_ENT_REFERENCE if the slot is already in use. + */ +stock int Entity_Create(const char[] className, int ForceEdictIndex=-1) +{ + if (ForceEdictIndex != -1 && Entity_IsValid(ForceEdictIndex)) { + return INVALID_ENT_REFERENCE; + } + + return CreateEntityByName(className, ForceEdictIndex); +} + +/** + * Kills an entity on the next frame (delayed). + * It is safe to use with entity loops. + * If the entity is is player ForcePlayerSuicide() is called. + * + * @param kenny Entity index. + * @param killChildren When true, kennys children are killed too. + * @return True on success, false otherwise. + */ +stock bool Entity_Kill(int kenny, bool killChildren=false) +{ + if (Entity_IsPlayer(kenny)) { + // Oh My God! They Killed Kenny!! + ForcePlayerSuicide(kenny); + return true; + } + + if(killChildren){ + return AcceptEntityInput(kenny, "KillHierarchy"); + } + else { + return AcceptEntityInput(kenny, "Kill"); + } +} + +/** + * Kills all entities with the given networked classname. + * It is safe to use with entity loops. + * If the entity is is player ForcePlayerSuicide() is called. + * + * @param className Entity Network Class to search for. + * @return Number of entities killed. + */ +stock int Entity_KillAllByClassName(const char[] className) +{ + int x = 0; + + int entity = INVALID_ENT_REFERENCE; + while ((entity = FindEntityByClassname(entity, className)) != INVALID_ENT_REFERENCE) { + AcceptEntityInput(entity, "kill"); + x++; + } + + return x; +} + +/** + * Gets the owner of an entity. + * For example the owner of a weapon entity. + * + * @param entity Entity index. + * @return Ground Entity or -1 + */ +stock int Entity_GetOwner(int entity) +{ + return GetEntPropEnt(entity, Prop_Data, "m_hOwnerEntity"); +} + +/** + * Sets the owner of an entity. + * For example the owner of a weapon entity. + * + * @param entity Entity index. + */ +stock void Entity_SetOwner(int entity, int newOwner) +{ + SetEntPropEnt(entity, Prop_Send, "m_hOwnerEntity", newOwner); +} + +/** + * Get's the ground entity this entity stands on. + * + * @param entity Entity index. + * @return Ground Entity or -1 + */ +stock int Entity_GetGroundEntity(int entity) +{ + return GetEntPropEnt(entity, Prop_Data, "m_hGroundEntity"); +} + +/* + * Damage definitions + */ + +#if !defined DMG_GENERIC + +#define DMG_GENERIC 0 // generic damage was done +#define DMG_CRUSH (1 << 0) // crushed by falling or moving object. + // NOTE: It's assumed crush damage is occurring as a result of physics collision, so no extra physics force is generated by crush damage. + // DON'T use DMG_CRUSH when damaging entities unless it's the result of a physics collision. You probably want DMG_CLUB instead. +#define DMG_BULLET (1 << 1) // shot +#define DMG_SLASH (1 << 2) // cut, clawed, stabbed +#define DMG_BURN (1 << 3) // heat burned +#define DMG_VEHICLE (1 << 4) // hit by a vehicle +#define DMG_FALL (1 << 5) // fell too far +#define DMG_BLAST (1 << 6) // explosive blast damage +#define DMG_CLUB (1 << 7) // crowbar, punch, headbutt +#define DMG_SHOCK (1 << 8) // electric shock +#define DMG_SONIC (1 << 9) // sound pulse shockwave +#define DMG_ENERGYBEAM (1 << 10) // laser or other high energy beam +#define DMG_PREVENT_PHYSICS_FORCE (1 << 11) // Prevent a physics force +#define DMG_NEVERGIB (1 << 12) // with this bit OR'd in, no damage type will be able to gib victims upon death +#define DMG_ALWAYSGIB (1 << 13) // with this bit OR'd in, any damage type can be made to gib victims upon death. +#define DMG_DROWN (1 << 14) // Drowning + + +#define DMG_PARALYZE (1 << 15) // slows affected creature down +#define DMG_NERVEGAS (1 << 16) // nerve toxins, very bad +#define DMG_POISON (1 << 17) // blood poisoning - heals over time like drowning damage +#define DMG_RADIATION (1 << 18) // radiation exposure +#define DMG_DROWNRECOVER (1 << 19) // drowning recovery +#define DMG_ACID (1 << 20) // toxic chemicals or acid burns +#define DMG_SLOWBURN (1 << 21) // in an oven + +#define DMG_REMOVENORAGDOLL (1<<22) // with this bit OR'd in, no ragdoll will be created, and the target will be quietly removed. + // use this to kill an entity that you've already got a server-side ragdoll for + +#define DMG_PHYSGUN (1<<23) // Hit by manipulator. Usually doesn't do any damage. +#define DMG_PLASMA (1<<24) // Shot by Cremator +#define DMG_AIRBOAT (1<<25) // Hit by the airboat's gun + +#define DMG_DISSOLVE (1<<26) // Dissolving! +#define DMG_BLAST_SURFACE (1<<27) // A blast on the surface of water that cannot harm things underwater +#define DMG_DIRECT (1<<28) +#define DMG_BUCKSHOT (1<<29) // not quite a bullet. Little, rounder, different. + +#endif + +/** + * Does damage to an entity. + * This is a powerful function that allows you to specify + * who the attacker is, the damage type and also what weapon + * should be displayed in the hud kill message. + * Note that for entities that fire another entity (RPG's, Crossbow's, + * you have to pass the bullet's class, not the weapon's class ! + * It hasn't been tested how expensive this function is, as it + * uses the entity point_hurt. + * If you need a cheaper function use Entity_RemoveHealth(). + * + * @param entity Entity index. + * @param damage Amount of damage. + * @param attacker Entity Index of the attacker. + * @param damageType Use the DMG_ definations. + * @param fakeClassName Classname to fake, you can set this if you + * want a specific weapon to be shown in the HUD kill message. + * @return True on success, false otherwise. + */ +stock bool Entity_Hurt(int entity, int damage, int attacker=0, int damageType=DMG_GENERIC, const char[] fakeClassName="") +{ + static int point_hurt = INVALID_ENT_REFERENCE; + + if (point_hurt == INVALID_ENT_REFERENCE || !IsValidEntity(point_hurt)) { + point_hurt = EntIndexToEntRef(Entity_Create("point_hurt")); + + if (point_hurt == INVALID_ENT_REFERENCE) { + return false; + } + + DispatchSpawn(point_hurt); + } + + AcceptEntityInput(point_hurt, "TurnOn"); + SetEntProp(point_hurt, Prop_Data, "m_nDamage", damage); + SetEntProp(point_hurt, Prop_Data, "m_bitsDamageType", damageType); + + char orignalTargetName[128]; + Entity_GetName(entity, orignalTargetName, sizeof(orignalTargetName)); + Entity_PointHurtAtTarget(point_hurt, entity); + + if (fakeClassName[0] != '\0') { + Entity_SetClassName(point_hurt, fakeClassName); + } + + AcceptEntityInput(point_hurt, "Hurt", attacker); + AcceptEntityInput(point_hurt, "TurnOff"); + + if (fakeClassName[0] != '\0') { + Entity_SetClassName(point_hurt, "point_hurt"); + } + + DispatchKeyValue(entity, "targetname", orignalTargetName); + return true; +} + +/* + * Gets the parent entity of an entity. + * + * @param entity Entity Index. + * @return Entity Index of the parent. + */ +stock int Entity_GetParent(int entity) +{ + return GetEntPropEnt(entity, Prop_Data, "m_pParent"); +} + +/* + * Clears the parent of an entity. + * + * @param entity Entity Index. + */ +stock void Entity_ClearParent(int entity) +{ + //SetVariantString(""); + AcceptEntityInput(entity, "ClearParent"); +} + +/* + * Sets the parent entity of an entity. + * + * @param entity Entity Index. + * @param parent Entity Index of the new parent. + */ +stock void Entity_SetParent(int entity, int parent) +{ + SetVariantString("!activator"); + AcceptEntityInput(entity, "SetParent", parent); +} + + +/* + * Callback for Change_OverTime. + * Note that every parameter is a reference and can be changed during this callback. + * You can get the elapsed time since start by multiply tick with currentCall. + * + * @param entity Entity Index. + * @param interval The current interval from the current game time to execute the next call of this function. + * @param currentCall The current call number (0 is the 1st call at 0.0 seconds, 1 the 2nd call at tick*1 seconds, ...). + * @return When true this callback will be called again at the next defined tick, otherwise it won't. + */ +typedef Entity_ChangeOverTimeCallback = function bool (int &entity, float &interval, int ¤tCall); + +/* + * Creates a timer and provides a callback to change various things about an entity over time. + * + * @param entity Entity Index. + * @param interval Interval from the current game time to execute the given function. + * @noreturn + */ +stock void Entity_ChangeOverTime(int entity, float interval=0.1, Entity_ChangeOverTimeCallback valueCallback) +{ + DataPack dataPack = CreateDataPack(); + WritePackCell(dataPack, EntIndexToEntRef(entity)); + WritePackFloat(dataPack, interval); + WritePackCell(dataPack, 0); + WritePackFunction(dataPack, valueCallback); + ResetPack(dataPack); + __smlib_Timer_ChangeOverTime(INVALID_HANDLE,dataPack); +} + +public Action __smlib_Timer_ChangeOverTime(Handle Timer, DataPack dataPack) +{ + int entity = EntRefToEntIndex(ReadPackCell(dataPack)); + if(!Entity_IsValid(entity)){ + return Plugin_Stop; + } + + float interval = ReadPackFloat(dataPack); + int currentCall = ReadPackCell(dataPack); + Function callback = ReadPackFunction(dataPack); + + any result; + Call_StartFunction(INVALID_HANDLE, callback); + Call_PushCellRef(entity); + Call_PushFloatRef(interval); + Call_PushCellRef(currentCall); + Call_Finish(result); + + if(result == false){ + return Plugin_Stop; + } + + ResetPack(dataPack,true); + WritePackCell(dataPack, EntIndexToEntRef(entity)); + WritePackFloat(dataPack, interval); + WritePackCell(dataPack, currentCall+1); + WritePackFunction(dataPack, callback); + ResetPack(dataPack); + CreateTimer(interval, __smlib_Timer_ChangeOverTime, dataPack); + return Plugin_Stop; +} + + +/** + * Gets the next child, entity is parent of. + * + * @param parent Entity Index (of Parent) + * @param start Start Index. + * @return Entity Index or -1 if no entity was found. + */ +stock int Entity_GetNextChild(int parent, int start=0) +{ + int maxEntities = GetMaxEntities(); + for (int entity=start; entity < maxEntities; entity++) { + + if (!Entity_IsValid(entity)) { + continue; + } + + if (entity > 0 && entity <= MaxClients && !IsClientConnected(entity)) { + continue; + } + + if (Entity_GetParent(entity) == parent) { + return entity; + } + } + + return INVALID_ENT_REFERENCE; +} +/** + * Gets the move/open direction of an entity (only available for func_door*, prop_door* and func_movelinear). + * Ex: if vec[2] is 1.0 a func_door moves straight up. + * + * @param entity Entity index. + * @param vec Vector. + */ +stock void Entity_GetMoveDirection(int entity, float vec[3]) +{ + GetEntPropVector(entity, Prop_Data, "m_vecMoveDir", vec); +} +/** + * Sets the move/open direction of an entity (only available for func_door*, prop_door* and func_movelinear). + * Ex: if vec[2] is 1.0 a func_door moves straight up. + * + * @param entity Entity index. + * @param vec Vector. + */ +stock void Entity_SetMoveDirection(int entity, const float vec[3]) +{ + SetEntPropVector(entity, Prop_Data, "m_vecMoveDir", vec); +} + +/** + * Returns if the entity will force close (won't be blockable by players and/or objects) or not when triggered to move. + * + * @param entity Entity index. + * @return True if the door will force close, otherwise false. + */ +stock bool Entity_GetForceClose(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_bForceClosed") != 0; +} + +/** + * Sets if the door should force close (souldn't be blockable by players and/or objects) or not when triggered to move. + * + * @param entity Entity index. + * @param forceClose If true the door will force close, otherwise it won't. + */ +stock void Entity_SetForceClose(int entity, bool forceClose) +{ + SetEntProp(entity, Prop_Data, "m_bForceClosed", forceClose); +} + +/** + * Gets the speed of a moving entity (like doors: open close speed). + * + * @param entity Entity index. + * @return Speed of the entity. + */ +stock float Entity_GetSpeed(int entity) +{ + return GetEntPropFloat(entity, Prop_Data, "m_flSpeed"); +} + +/** + * Sets how fast an entity moves (like doors: open close speed). + * + * @param entity Entity index. + * @param speed The new speed of the entity. + */ +stock void Entity_SetSpeed(int entity, float speed) +{ + SetEntPropFloat(entity, Prop_Data, "m_flSpeed", speed); +} + +/** + * Gets the damage of a moving entity when blocked (like doors when open or close and players and/or objects are between the entity and something else). + * Note: Negative values add health to the blocking entity. + * + * @param entity Entity index. + * @return Damage. + */ +stock float Entity_GetBlockDamage(int entity) +{ + return GetEntPropFloat(entity, Prop_Data, "m_flBlockDamage"); +} + +/** + * Sets the damage of a moving entity when blocked (like doors when open or close and players and/or objects are between the entity and something else). + * Note: Negative values add health to the blocking entity. + * + * @param entity Entity index. + * @param damage Damage. + */ +stock void Entity_SetBlockDamage(int entity, float damage) +{ + SetEntPropFloat(entity, Prop_Data, "m_flBlockDamage", damage); +} + +/** + * Returns if the given entity is disabled or not. + * + * @param entity Entity index. + * @return True if entity is disabled, otherwise false. + */ +stock bool Entity_IsDisabled(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_bDisabled", 1) != 0; +} + +/** + * Disables the given entity. + * + * @param entity Entity index. + * @return True if successful otherwise false. + */ +stock bool Entity_Disable(int entity) +{ + return AcceptEntityInput(entity, "Disable"); +} + +/** + * Enables the given entity. + * + * @param entity Entity index. + * @return True if successful otherwise false. + */ +stock bool Entity_Enable(int entity) +{ + return AcceptEntityInput(entity, "Enable"); +} + + +// settings for m_takedamage taken from hl2sdk-ob-valve\game\shared\shareddefs.h +#define DAMAGE_NO 0 +#define DAMAGE_EVENTS_ONLY 1 // Call damage functions, but don't modify health +#define DAMAGE_YES 2 +#define DAMAGE_AIM 3 + +/** + * Sets the mode for an entity to take damage. + * Note: This is used to give a client god mode (DAMAGE_NO). + * + * @param entity Entity index. + * @param value Mode, use DAMAGE_* defines. + */ +stock void Entity_SetTakeDamage(int entity, int value) +{ + SetEntProp(entity, Prop_Data, "m_takedamage", value, 1); +} + +/** + * Gets the mode for an entity to take damage. + * Note: When the return value is DAMAGE_NO then the client is using godmode. + * + * @param entity Entity index. + * @return Take damage mode (DAMAGE_*). + */ +stock int Entity_GetTakeDamage(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_takedamage", 1); +} + +/** + * Sets the minimum of damage required to hurt this entity. + * Example: This is used to block any damage done by projectile weapons against a gun ship in Half-Life 2. + * + * @param entity Entity index. + * @param minDamage Minimum required damage. + */ +stock void Entity_SetMinHealthDamage(int entity, int minDamage) +{ + SetEntProp(entity, Prop_Data, "m_iMinHealthDmg", minDamage); +} + +/** + * Gets the minimum of damage required to hurt this entity. + * Example: This is used to block any damage done by projectile weapons against a gun ship in Half-Life 2. + * + * @param entity Entity index. + * @return Minimum required damage. + */ +stock int Entity_GetMinHealthDamage(int entity) +{ + return GetEntProp(entity, Prop_Data, "m_iMinHealthDmg"); +} + +/** + * Gets an entity's color. + * + * @param entity Entity index + * @param color 4 dimensional array where [r,g,b,a] values are stored + * @error Invalid entity index, or lack of mod compliance. + */ +stock void Entity_GetRenderColor(int entity, int color[4]) +{ + static bool gotconfig = false; + static char prop[32]; + + if (!gotconfig) { + Handle gc = LoadGameConfigFile("core.games"); + bool exists = GameConfGetKeyValue(gc, "m_clrRender", prop, sizeof(prop)); + delete gc; + + if (!exists) { + strcopy(prop, sizeof(prop), "m_clrRender"); + } + + gotconfig = true; + } + + int offset = GetEntSendPropOffs(entity, prop); + + if (offset <= 0) { + ThrowError("SetEntityRenderColor not supported by this mod"); + } + + for (int i=0; i < 4; i++) { + color[i] = GetEntData(entity, offset + i + 1, 1); + } +} + +/** + * Sets an entity's color. + * Doesn't change the value, if set to -1. + * + * @param entity Entity index + * @param r Amount of red (0-255) + * @param g Amount of green (0-255) + * @param b Amount of blue (0-255) + * @param a Amount of alpha (0-255) + * @error Invalid entity index, or lack of mod compliance. + */ +stock void Entity_SetRenderColor(int entity, int r=-1, int g=-1, int b=-1, int a=-1) +{ + static bool gotconfig = false; + static char prop[32]; + + if (!gotconfig) { + Handle gc = LoadGameConfigFile("core.games"); + bool exists = GameConfGetKeyValue(gc, "m_clrRender", prop, sizeof(prop)); + delete gc; + + if (!exists) { + strcopy(prop, sizeof(prop), "m_clrRender"); + } + + gotconfig = true; + } + + int offset = GetEntSendPropOffs(entity, prop); + + if (offset <= 0) { + ThrowError("SetEntityRenderColor not supported by this mod"); + } + + if(r != -1) { + SetEntData(entity, offset, r, 1, true); + } + + if(g != -1) { + SetEntData(entity, offset + 1, g, 1, true); + } + + if(b != -1) { + SetEntData(entity, offset + 2, b, 1, true); + } + + if(a != -1) { + SetEntData(entity, offset + 3, a, 1, true); + } +} + +/** + * Sends the 'addouput' command to an entity. + * + * @param entity Entity Index. + * @param input Input command. + * @param activator Entity index which initiated the sequence of actions (-1 for a NULL entity). + * @param caller Entity index from which this event is sent (-1 for a NULL entity). + * @param outputid Unknown. + * @return True if successful, otherwise false. + */ +stock bool Entity_AddOutput(int entity, const char[] input, int activator=-1, int caller=-1, int outputid=0) +{ + //SetVariantString(input); + return AcceptEntityInput(entity, "addoutput", activator, caller, outputid); +} diff --git a/addons/sourcemod/scripting/include/smlib/files.inc b/addons/sourcemod/scripting/include/smlib/files.inc new file mode 100644 index 0000000..e11fad4 --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/files.inc @@ -0,0 +1,451 @@ +#if defined _smlib_files_included + #endinput +#endif +#define _smlib_files_included + +#include +#include +#include + +/** + * Gets the Base name of a path. + * Examples: + * blub.txt -> "blub.txt" + * /sourcemod/extensions/example.ext.so -> "example.ext.so" + * + * @param path File path + * @param buffer String buffer array + * @param size Size of string buffer + */ +stock void File_GetBaseName(const char[] path, char[] buffer, int size) +{ + if (path[0] == '\0') { + buffer[0] = '\0'; + return; + } + + int pos_start = FindCharInString(path, '/', true); + + if (pos_start == -1) { + pos_start = FindCharInString(path, '\\', true); + } + + pos_start++; + + strcopy(buffer, size, path[pos_start]); +} + +/** + * Gets the Directory of a path (without the file name). + * Does not work with "." as the path. + * Examples: + * blub.txt -> "blub.txt" + * /sourcemod/extensions/example.ext.so -> "example.ext.so" + * + * @param path File path + * @param buffer String buffer array + * @param size Size of string buffer + */ +stock void File_GetDirName(const char[] path, char[] buffer, int size) +{ + if (path[0] == '\0') { + buffer[0] = '\0'; + return; + } + + int pos_start = FindCharInString(path, '/', true); + + if (pos_start == -1) { + pos_start = FindCharInString(path, '\\', true); + + if (pos_start == -1) { + buffer[0] = '\0'; + return; + } + } + + strcopy(buffer, size, path); + buffer[pos_start] = '\0'; +} + +/** + * Gets the File name of a path. + * blub.txt -> "blub" + * /sourcemod/extensions/example.ext.so -> "example.ext" + * + * @param path File path + * @param buffer String buffer array + * @param size Size of string buffer + */ +stock void File_GetFileName(const char[] path, char[] buffer, int size) +{ + if (path[0] == '\0') { + buffer[0] = '\0'; + return; + } + + File_GetBaseName(path, buffer, size); + + int pos_ext = FindCharInString(buffer, '.', true); + + if (pos_ext != -1) { + buffer[pos_ext] = '\0'; + } +} + +/** + * Gets the Extension of a file. + * Examples: + * blub.inc.txt -> "txt" + * /sourcemod/extensions/example.ext.so -> "so" + * + * @param path Path String + * @param buffer String buffer array + * @param size Max length of string buffer + */ +stock void File_GetExtension(const char[] path, char[] buffer, int size) +{ + int extpos = FindCharInString(path, '.', true); + + if (extpos == -1) { + buffer[0] = '\0'; + return; + } + + strcopy(buffer, size, path[++extpos]); +} + +/** + * Adds a path to the downloadables network string table. + * This can be a file or directory and also works recursed. + * You can optionally specify file extensions that should be ignored. + * Bz2 and ztmp are automatically ignored. + * It only adds files that actually exist. + * You can also specify a wildcard * after the ., very useful for models. + * This forces a client to download the file if they do not already have it. + * + * @param path Path String + * @param recursive Whether to do recursion or not. + * @param ignoreExts Optional: 2 dimensional String array.You can define it like this: new String:ignore[][] = { ".ext1", ".ext2" }; + * @param size This should be set to the number of file extensions in the ignoreExts array (sizeof(ignore) for the example above) + */ + +// Damn you SourcePawn :( I didn't want to +char _smlib_empty_twodimstring_array[][] = { { '\0' } }; +stock void File_AddToDownloadsTable(const char[] path, bool recursive=true, const char[][] ignoreExts=_smlib_empty_twodimstring_array, int size=0) +{ + if (path[0] == '\0') { + return; + } + + if (FileExists(path)) { + + char fileExtension[5]; + File_GetExtension(path, fileExtension, sizeof(fileExtension)); + + if (StrEqual(fileExtension, "bz2", false) || StrEqual(fileExtension, "ztmp", false)) { + return; + } + + if (Array_FindString(ignoreExts, size, fileExtension) != -1) { + return; + } + + char path_new[PLATFORM_MAX_PATH]; + strcopy(path_new, sizeof(path_new), path); + ReplaceString(path_new, sizeof(path_new), "//", "/"); + + AddFileToDownloadsTable(path_new); + } + else if (recursive && DirExists(path)) { + + char dirEntry[PLATFORM_MAX_PATH]; + DirectoryListing __dir = OpenDirectory(path); + + while (ReadDirEntry(__dir, dirEntry, sizeof(dirEntry))) { + + if (StrEqual(dirEntry, ".") || StrEqual(dirEntry, "..")) { + continue; + } + + Format(dirEntry, sizeof(dirEntry), "%s/%s", path, dirEntry); + File_AddToDownloadsTable(dirEntry, recursive, ignoreExts, size); + } + + delete __dir; + } + else if (FindCharInString(path, '*', true)) { + + char fileExtension[4]; + File_GetExtension(path, fileExtension, sizeof(fileExtension)); + + if (StrEqual(fileExtension, "*")) { + + char dirName[PLATFORM_MAX_PATH], + fileName[PLATFORM_MAX_PATH], + dirEntry[PLATFORM_MAX_PATH]; + + File_GetDirName(path, dirName, sizeof(dirName)); + File_GetFileName(path, fileName, sizeof(fileName)); + StrCat(fileName, sizeof(fileName), "."); + + DirectoryListing __dir = OpenDirectory(dirName); + while (ReadDirEntry(__dir, dirEntry, sizeof(dirEntry))) { + + if (StrEqual(dirEntry, ".") || StrEqual(dirEntry, "..")) { + continue; + } + + if (strncmp(dirEntry, fileName, strlen(fileName)) == 0) { + Format(dirEntry, sizeof(dirEntry), "%s/%s", dirName, dirEntry); + File_AddToDownloadsTable(dirEntry, recursive, ignoreExts, size); + } + } + + delete __dir; + } + } +} + + +/* + * Adds all files/paths in the given text file to the download table. + * Recursive mode enabled, see File_AddToDownloadsTable() + * Comments are allowed ! Supported comment types are ; // # + * + * @param path Path to the .txt file. + */ +stock void File_ReadDownloadList(const char[] path) +{ + File file = OpenFile(path, "r"); + + if (file == INVALID_HANDLE) { + return; + } + + char buffer[PLATFORM_MAX_PATH]; + while (!IsEndOfFile(file)) { + ReadFileLine(file, buffer, sizeof(buffer)); + + int pos; + pos = StrContains(buffer, "//"); + if (pos != -1) { + buffer[pos] = '\0'; + } + + pos = StrContains(buffer, "#"); + if (pos != -1) { + buffer[pos] = '\0'; + } + + pos = StrContains(buffer, ";"); + if (pos != -1) { + buffer[pos] = '\0'; + } + + TrimString(buffer); + + if (buffer[0] == '\0') { + continue; + } + + File_AddToDownloadsTable(buffer); + } + + delete file; +} + +/* + * Attempts to load a translation file and optionally unloads the plugin if the file + * doesn't exist (also prints an error message). + * + * @param file Filename of the translations file (eg. .phrases). + * @param setFailState If true, it sets the failstate if the translations file doesn't exist + * @return True on success, false otherwise (only if setFailState is set to false) + */ +stock bool File_LoadTranslations(const char[] file, bool setFailState=true) +{ + char path[PLATFORM_MAX_PATH]; + + BuildPath(Path_SM, path, sizeof(path), "translations/%s", file); + + if (FileExists(path)) { + LoadTranslations(file); + return true; + } + + Format(path,sizeof(path), "%s.txt", path); + + if (!FileExists(path)) { + + if (setFailState) { + SetFailState("Unable to locate translation file (%s).", path); + } + + return false; + } + + LoadTranslations(file); + + return true; +} + +/* + * Reads the contents of a given file into a string buffer in binary mode. + * + * @param path Path to the file + * @param buffer String buffer + * @param size If -1, reads until a null terminator is encountered in the file. Otherwise, read_count bytes are read into the buffer provided. In this case the buffer is not explicitly null terminated, and the buffer will contain any null terminators read from the file. + * @return Number of characters written to the buffer, or -1 if an error was encountered. + */ +stock int File_ToString(const char[] path, char[] buffer, int size) +{ + File file = OpenFile(path, "rb"); + + if (file == INVALID_HANDLE) { + buffer[0] = '\0'; + return -1; + } + + int num_bytes_written = ReadFileString(file, buffer, size); + delete file; + + return num_bytes_written; +} + +/* + * Writes a string into a file in binary mode. + * + * @param file Path to the file + * @param str String to write + * @return True on success, false otherwise + */ +stock bool File_StringToFile(const char[] path, char[] str) +{ + File file = OpenFile(path, "wb"); + + if (file == INVALID_HANDLE) { + return false; + } + + bool success = WriteFileString(file, str, false); + delete file; + + return success; +} + +/* + * Copies file source to destination + * Based on code of javalia: + * http://forums.alliedmods.net/showthread.php?t=159895 + * + * @param source Input file + * @param destination Output file + * @return True on success, false otherwise + */ +stock bool File_Copy(const char[] source, const char[] destination) +{ + File file_source = OpenFile(source, "rb"); + + if (file_source == INVALID_HANDLE) { + return false; + } + + File file_destination = OpenFile(destination, "wb"); + + if (file_destination == INVALID_HANDLE) { + delete file_source; + return false; + } + + int buffer[32]; + int cache; + + while (!IsEndOfFile(file_source)) { + cache = ReadFile(file_source, buffer, sizeof(buffer), 1); + WriteFile(file_destination, buffer, cache, 1); + } + + delete file_source; + delete file_destination; + + return true; +} + +/* + * Recursively copies (the content) of a directory or file specified + * by "path" to "destination". + * Note that because of Sourcemod API limitations this currently does not + * takeover the file permissions (it leaves them default). + * Links will be resolved. + * + * @param path Source path + * @param destination Destination directory (This can only be a directory) + * @param stop_on_error Optional: Set to true to stop on error (ie can't read a file) + * @param dirMode Optional: File mode for directories that will be created (Default = 0755), don't forget to convert FROM octal + * @return True on success, false otherwise + */ +stock bool File_CopyRecursive(const char[] path, const char[] destination, bool stop_on_error=false, int dirMode=493) +{ + if (FileExists(path)) { + return File_Copy(path, destination); + } + else if (DirExists(path)) { + return Sub_File_CopyRecursive(path, destination, stop_on_error, FileType_Directory, dirMode); + } + else { + return false; + } +} + +static stock bool Sub_File_CopyRecursive(const char[] path, const char[] destination, bool stop_on_error=false, FileType fileType, int dirMode) +{ + if (fileType == FileType_File) { + return File_Copy(path, destination); + } + else if (fileType == FileType_Directory) { + + if (!CreateDirectory(destination, dirMode) && stop_on_error) { + return false; + } + + DirectoryListing directory = OpenDirectory(path); + + if (directory == INVALID_HANDLE) { + return false; + } + + char + source_buffer[PLATFORM_MAX_PATH], + destination_buffer[PLATFORM_MAX_PATH]; + FileType type; + + while (ReadDirEntry(directory, source_buffer, sizeof(source_buffer), type)) { + + if (StrEqual(source_buffer, "..") || StrEqual(source_buffer, ".")) { + continue; + } + + Format(destination_buffer, sizeof(destination_buffer), "%s/%s", destination, source_buffer); + Format(source_buffer, sizeof(source_buffer), "%s/%s", path, source_buffer); + + if (type == FileType_File) { + File_Copy(source_buffer, destination_buffer); + } + else if (type == FileType_Directory) { + + if (!File_CopyRecursive(source_buffer, destination_buffer, stop_on_error, dirMode) && stop_on_error) { + delete directory; + return false; + } + } + } + + delete directory; + } + else if (fileType == FileType_Unknown) { + return false; + } + + return true; +} diff --git a/addons/sourcemod/scripting/include/smlib/game.inc b/addons/sourcemod/scripting/include/smlib/game.inc new file mode 100644 index 0000000..1c0550d --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/game.inc @@ -0,0 +1,57 @@ +#if defined _smlib_game_included + #endinput +#endif +#define _smlib_game_included + +#include +#include +#include + +/* + * End's the game and displays the scoreboard with intermission time. + * + * @return True on success, false otherwise + */ +stock bool Game_End() +{ + int game_end = FindEntityByClassname(-1, "game_end"); + + if (game_end == -1) { + game_end = CreateEntityByName("game_end"); + + if (game_end == -1) { + ThrowError("Unable to find or create entity \"game_end\""); + } + } + + return AcceptEntityInput(game_end, "EndGame"); +} + +/* + * End's the current round, allows specifying the winning + * team and more. + * This function currently works in TF2 only (it uses the game_round_win entity). + * + * @param team The winning Team, pass 0 for Sudden Death mode (no winning team) + * @param forceMapReset If to force the map to reset during the force respawn after the round is over. + * @param switchTeams If to switch the teams when the game is going to be reset. + * @return True on success, false otherwise + */ +stock bool Game_EndRound(int team=0, bool forceMapReset=false, bool switchTeams=false) +{ + int game_round_win = FindEntityByClassname(-1, "game_round_win"); + + if (game_round_win == -1) { + game_round_win = CreateEntityByName("game_round_win"); + + if (game_round_win == -1) { + ThrowError("Unable to find or create entity \"game_round_win\""); + } + } + + DispatchKeyValue(game_round_win, "TeamNum" , (team ? "true" : "false")); + DispatchKeyValue(game_round_win, "force_map_reset" , (forceMapReset? "true" : "false")); + DispatchKeyValue(game_round_win, "switch_teams" , (switchTeams ? "true" : "false")); + + return AcceptEntityInput(game_round_win, "RoundWin"); +} diff --git a/addons/sourcemod/scripting/include/smlib/general.inc b/addons/sourcemod/scripting/include/smlib/general.inc index a7d004c..c3e904c 100644 --- a/addons/sourcemod/scripting/include/smlib/general.inc +++ b/addons/sourcemod/scripting/include/smlib/general.inc @@ -1,251 +1,251 @@ -#if defined _smlib_general_included - #endinput -#endif -#define _smlib_general_included - -#include -#include -#include - -#define TIME_TO_TICKS(%1) ( (int)( 0.5 + (float)(%1) / GetTickInterval() ) ) -#define TICKS_TO_TIME(%1) ( GetTickInterval() * %1 ) -#define ROUND_TO_TICKS(%1) ( TICK_INTERVAL * TIME_TO_TICKS( %1 ) ) - -/* - * Precaches the given model. - * It's best to call this OnMapStart(). - * - * @param material Path of the material to precache. - * @return Returns the material index, INVALID_STRING_INDEX on error. - */ -stock PrecacheMaterial(const String:material[]) -{ - static materialNames = INVALID_STRING_TABLE; - - if (materialNames == INVALID_STRING_TABLE) { - if ((materialNames = FindStringTable("Materials")) == INVALID_STRING_TABLE) { - return INVALID_STRING_INDEX; - } - } - - new index = FindStringIndex2(materialNames, material); - if (index == INVALID_STRING_INDEX) { - new numStrings = GetStringTableNumStrings(materialNames); - if (numStrings >= GetStringTableMaxStrings(materialNames)) { - return INVALID_STRING_INDEX; - } - - AddToStringTable(materialNames, material); - index = numStrings; - } - - return index; -} - -/* - * Checks if the material is precached. - * - * @param material Path of the material. - * @return True if it is precached, false otherwise. - */ -stock bool:IsMaterialPrecached(const String:material[]) -{ - static materialNames = INVALID_STRING_TABLE; - - if (materialNames == INVALID_STRING_TABLE) { - if ((materialNames = FindStringTable("Materials")) == INVALID_STRING_TABLE) { - return false; - } - } - - return (FindStringIndex2(materialNames, material) != INVALID_STRING_INDEX); -} - -/* - * Precaches the given particle system. - * It's best to call this OnMapStart(). - * Code based on Rochellecrab's, thanks. - * - * @param particleSystem Name of the particle system to precache. - * @return Returns the particle system index, INVALID_STRING_INDEX on error. - */ -stock PrecacheParticleSystem(const String:particleSystem[]) -{ - static particleEffectNames = INVALID_STRING_TABLE; - - if (particleEffectNames == INVALID_STRING_TABLE) { - if ((particleEffectNames = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { - return INVALID_STRING_INDEX; - } - } - - new index = FindStringIndex2(particleEffectNames, particleSystem); - if (index == INVALID_STRING_INDEX) { - new numStrings = GetStringTableNumStrings(particleEffectNames); - if (numStrings >= GetStringTableMaxStrings(particleEffectNames)) { - return INVALID_STRING_INDEX; - } - - AddToStringTable(particleEffectNames, particleSystem); - index = numStrings; - } - - return index; -} - -/* - * Checks if the particle system is precached. - * - * @param material Name of the particle system - * @return True if it is precached, false otherwise. - */ -stock bool:IsParticleSystemPrecached(const String:particleSystem[]) -{ - static particleEffectNames = INVALID_STRING_TABLE; - - if (particleEffectNames == INVALID_STRING_TABLE) { - if ((particleEffectNames = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { - return false; - } - } - - return (FindStringIndex2(particleEffectNames, particleSystem) != INVALID_STRING_INDEX); -} - -/* - * Searches for the index of a given string in a string table. - * - * @param table String table name. - * @param str String to find. - * @return String index if found, INVALID_STRING_INDEX otherwise. - */ -stock FindStringIndexByTableName(const String:table[], const String:str[]) -{ - new tableIndex = INVALID_STRING_TABLE; - if ((tableIndex = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { - return INVALID_STRING_INDEX; - } - - return FindStringIndex2(tableIndex, str); -} - -/* - * Rewrite of FindStringIndex, because in my tests - * FindStringIndex failed to work correctly. - * Searches for the index of a given string in a string table. - * - * @param tableidx A string table index. - * @param str String to find. - * @return String index if found, INVALID_STRING_INDEX otherwise. - */ -stock FindStringIndex2(tableidx, const String:str[]) -{ - decl String:buf[1024]; - - new numStrings = GetStringTableNumStrings(tableidx); - for (new i=0; i < numStrings; i++) { - ReadStringTable(tableidx, i, buf, sizeof(buf)); - - if (StrEqual(buf, str)) { - return i; - } - } - - return INVALID_STRING_INDEX; -} - -/* - * Converts a long IP to a dotted format String. - * - * @param ip IP Long - * @param buffer String Buffer (size = 16) - * @param size String Buffer size - * @noreturn - */ -stock LongToIP(ip, String:buffer[], size) -{ - Format( - buffer, size, - "%d.%d.%d.%d", - (ip >> 24) & 0xFF, - (ip >> 16) & 0xFF, - (ip >> 8 ) & 0xFF, - ip & 0xFF - ); -} - -/* - * Converts a dotted format String IP to a long. - * - * @param ip IP String - * @return Long IP - */ -stock IPToLong(const String:ip[]) -{ - decl String:pieces[4][4]; - - if (ExplodeString(ip, ".", pieces, sizeof(pieces), sizeof(pieces[])) != 4) { - return 0; - } - - return ( - StringToInt(pieces[0]) << 24 | - StringToInt(pieces[1]) << 16 | - StringToInt(pieces[2]) << 8 | - StringToInt(pieces[3]) - ); -} - -static localIPRanges[] = -{ - 10 << 24, // 10. - 127 << 24 | 1 , // 127.0.0.1 - 127 << 24 | 16 << 16, // 127.16. - 192 << 24 | 168 << 16, // 192.168. -}; - -/* - * Checks whether an IP is a private/internal IP - * - * @param ip IP Long - * @return True if the IP is local, false otherwise. - */ -stock bool:IsIPLocal(ip) -{ - new range, bits, move, bool:matches; - - for (new i=0; i < sizeof(localIPRanges); i++) { - - range = localIPRanges[i]; - matches = true; - - for (new j=0; j < 4; j++) { - move = j * 8; - bits = (range >> move) & 0xFF; - - if (bits && bits != ((ip >> move) & 0xFF)) { - matches = false; - } - } - - if (matches) { - return true; - } - } - - return false; -} - -/* - * Closes the given hindle and sets it to INVALID_HANDLE. - * - * @param handle handle - * @noreturn - */ -stock ClearHandle(&Handle:handle) -{ - if (handle != INVALID_HANDLE) { - CloseHandle(handle); - handle = INVALID_HANDLE; - } -} +#if defined _smlib_general_included + #endinput +#endif +#define _smlib_general_included + +#include +#include +#include + +#define TIME_TO_TICKS(%1) ( (int)( 0.5 + (float)(%1) / GetTickInterval() ) ) +#define TICKS_TO_TIME(%1) ( GetTickInterval() * %1 ) +#define ROUND_TO_TICKS(%1) ( TICK_INTERVAL * TIME_TO_TICKS( %1 ) ) + +/* + * Precaches the given model. + * It's best to call this OnMapStart(). + * + * @param material Path of the material to precache. + * @return Returns the material index, INVALID_STRING_INDEX on error. + */ +stock int PrecacheMaterial(const char[] material) +{ + static int materialNames = INVALID_STRING_TABLE; + + if (materialNames == INVALID_STRING_TABLE) { + if ((materialNames = FindStringTable("Materials")) == INVALID_STRING_TABLE) { + return INVALID_STRING_INDEX; + } + } + + int index = FindStringIndex2(materialNames, material); + if (index == INVALID_STRING_INDEX) { + int numStrings = GetStringTableNumStrings(materialNames); + if (numStrings >= GetStringTableMaxStrings(materialNames)) { + return INVALID_STRING_INDEX; + } + + AddToStringTable(materialNames, material); + index = numStrings; + } + + return index; +} + +/* + * Checks if the material is precached. + * + * @param material Path of the material. + * @return True if it is precached, false otherwise. + */ +stock bool IsMaterialPrecached(const char[] material) +{ + static int materialNames = INVALID_STRING_TABLE; + + if (materialNames == INVALID_STRING_TABLE) { + if ((materialNames = FindStringTable("Materials")) == INVALID_STRING_TABLE) { + return false; + } + } + + return (FindStringIndex2(materialNames, material) != INVALID_STRING_INDEX); +} + +/* + * Precaches the given particle system. + * It's best to call this OnMapStart(). + * Code based on Rochellecrab's, thanks. + * + * @param particleSystem Name of the particle system to precache. + * @return Returns the particle system index, INVALID_STRING_INDEX on error. + */ +stock int PrecacheParticleSystem(const char[] particleSystem) +{ + static int particleEffectNames = INVALID_STRING_TABLE; + + if (particleEffectNames == INVALID_STRING_TABLE) { + if ((particleEffectNames = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { + return INVALID_STRING_INDEX; + } + } + + int index = FindStringIndex2(particleEffectNames, particleSystem); + if (index == INVALID_STRING_INDEX) { + int numStrings = GetStringTableNumStrings(particleEffectNames); + if (numStrings >= GetStringTableMaxStrings(particleEffectNames)) { + return INVALID_STRING_INDEX; + } + + AddToStringTable(particleEffectNames, particleSystem); + index = numStrings; + } + + return index; +} + +/* + * Checks if the particle system is precached. + * + * @param material Name of the particle system + * @return True if it is precached, false otherwise. + */ +stock bool IsParticleSystemPrecached(const char[] particleSystem) +{ + static int particleEffectNames = INVALID_STRING_TABLE; + + if (particleEffectNames == INVALID_STRING_TABLE) { + if ((particleEffectNames = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { + return false; + } + } + + return (FindStringIndex2(particleEffectNames, particleSystem) != INVALID_STRING_INDEX); +} + +/* + * Searches for the index of a given string in a string table. + * + * @param table String table name. + * @param str String to find. + * @return String index if found, INVALID_STRING_INDEX otherwise. + */ +stock int FindStringIndexByTableName(const char[] table, const char[] str) +{ + int tableIndex = INVALID_STRING_TABLE; + if ((tableIndex = FindStringTable("ParticleEffectNames")) == INVALID_STRING_TABLE) { + return INVALID_STRING_INDEX; + } + + return FindStringIndex2(tableIndex, str); +} + +/* + * Rewrite of FindStringIndex, because in my tests + * FindStringIndex failed to work correctly. + * Searches for the index of a given string in a string table. + * + * @param tableidx A string table index. + * @param str String to find. + * @return String index if found, INVALID_STRING_INDEX otherwise. + */ +stock int FindStringIndex2(int tableidx, const char[] str) +{ + char buf[1024]; + + int numStrings = GetStringTableNumStrings(tableidx); + for (int i=0; i < numStrings; i++) { + ReadStringTable(tableidx, i, buf, sizeof(buf)); + + if (StrEqual(buf, str)) { + return i; + } + } + + return INVALID_STRING_INDEX; +} + +/* + * Converts a long IP to a dotted format String. + * + * @param ip IP Long + * @param buffer String Buffer (size = 16) + * @param size String Buffer size + */ +stock void LongToIP(int ip, char[] buffer, int size) +{ + Format( + buffer, size, + "%d.%d.%d.%d", + (ip >> 24) & 0xFF, + (ip >> 16) & 0xFF, + (ip >> 8 ) & 0xFF, + ip & 0xFF + ); +} + +/* + * Converts a dotted format String IP to a long. + * + * @param ip IP String + * @return Long IP + */ +stock int IPToLong(const char[] ip) +{ + char pieces[4][4]; + + if (ExplodeString(ip, ".", pieces, sizeof(pieces), sizeof(pieces[])) != 4) { + return 0; + } + + return ( + StringToInt(pieces[0]) << 24 | + StringToInt(pieces[1]) << 16 | + StringToInt(pieces[2]) << 8 | + StringToInt(pieces[3]) + ); +} + +static int localIPRanges[] = +{ + 10 << 24, // 10. + 127 << 24 | 1 , // 127.0.0.1 + 127 << 24 | 16 << 16, // 127.16. + 192 << 24 | 168 << 16, // 192.168. +}; + +/* + * Checks whether an IP is a private/internal IP + * + * @param ip IP Long + * @return True if the IP is local, false otherwise. + */ +stock bool IsIPLocal(int ip) +{ + int range, bits, move; + bool matches; + + for (int i=0; i < sizeof(localIPRanges); i++) { + + range = localIPRanges[i]; + matches = true; + + for (int j=0; j < 4; j++) { + move = j * 8; + bits = (range >> move) & 0xFF; + + if (bits && bits != ((ip >> move) & 0xFF)) { + matches = false; + } + } + + if (matches) { + return true; + } + } + + return false; +} + +/* + * Closes the given hindle and sets it to INVALID_HANDLE. + * Obsolete now. Just use |delete handle|. + * + * @param handle handle + */ +stock void ClearHandle(Handle &handle) +{ + if (handle != INVALID_HANDLE) { + CloseHandle(handle); + handle = INVALID_HANDLE; + } +} diff --git a/addons/sourcemod/scripting/include/smlib/math.inc b/addons/sourcemod/scripting/include/smlib/math.inc index 16019a8..7744a15 100644 --- a/addons/sourcemod/scripting/include/smlib/math.inc +++ b/addons/sourcemod/scripting/include/smlib/math.inc @@ -1,309 +1,346 @@ -#if defined _smlib_math_included - #endinput -#endif -#define _smlib_math_included - -#include - -#define SIZE_OF_INT 2147483647 // without 0 - -#define GAMEUNITS_TO_METERS 0.01905 -#define METERS_TO_GAMEUNITS 52.49343832020997 -#define METERS_TO_FEET 3.2808399 -#define FEET_TO_METERS 0.3048 - -enum VecAngle -{ - ANG_ALPHA, - ANG_BETA, - ANG_GAMMA -} - -/** - * Makes a negative integer number to a positive integer number. - * This is faster than Sourcemod's native FloatAbs() for integers. - * Use FloatAbs() for Float numbers. - * - * @param number A number that can be positive or negative. - * @return Positive number. - */ -stock Math_Abs(value) -{ - return (value ^ (value >> 31)) - (value >> 31); -} - -/** - * Checks if 2 vectors are equal. - * You can specfiy a tolerance, which is the maximum distance at which vectors are considered equals - * - * @param vec1 First vector (3 dim array) - * @param vec2 Second vector (3 dim array) - * @param tolerance If you want to check that those vectors are somewhat even. 0.0 means they are 100% even if this function returns true. - * @return True if vectors are equal, false otherwise. - */ -stock bool:Math_VectorsEqual(Float:vec1[3], Float:vec2[3], Float:tolerance=0.0) -{ - new Float:distance = GetVectorDistance(vec1, vec2, true); - - return distance <= (tolerance * tolerance); -} - -/** - * Sets the given value to min - * if the value is smaller than the given. - * - * @param value Value - * @param min Min Value used as lower border - * @return Correct value not lower than min - */ -stock any:Math_Min(any:value, any:min) -{ - if (value < min) { - value = min; - } - - return value; -} - -/** - * Sets the given value to max - * if the value is greater than the given. - * - * @param value Value - * @param max Max Value used as upper border - * @return Correct value not upper than max - */ -stock any:Math_Max(any:value, any:max) -{ - if (value > max) { - value = max; - } - - return value; -} - -/** - * Makes sure a value is within a certain range and - * returns the value. - * If the value is outside the range it is set to either - * min or max, if it is inside the range it will just return - * the specified value. - * - * @param value Value - * @param min Min value used as lower border - * @param max Max value used as upper border - * @return Correct value not lower than min and not greater than max. - */ -stock any:Math_Clamp(any:value, any:min, any:max) -{ - value = Math_Min(value, min); - value = Math_Max(value, max); - - return value; -} - -/* - * Checks if the value is within the given bounds (min & max). - * - * @param value The value you want to check. - * @param min The lower border. - * @param max The upper border. - * @return True if the value is within bounds (bigger or equal min / smaller or equal max), false otherwise. - */ -stock bool:Math_IsInBounds(any:value, any:min, any:max) -{ - if (value < min || value > max) { - return false; - } - - return true; -} - -/** - * Let's the specified value "overflow" if it is outside the given limit. - * This is like with integers when it reaches a value above the max possible - * integer size. - * - * @param value Value - * @param min Min value used as lower border - * @param max Max value used as upper border - * @return Overflowed number - */ -stock any:Math_Overflow(any:value, any:min, any:max) -{ - return (value % max) + min; -} - -/** - * Returns a random, uniform Integer number in the specified (inclusive) range. - * This is safe to use multiple times in a function. - * The seed is set automatically for each plugin. - * Rewritten by MatthiasVance, thanks. - * - * @param min Min value used as lower border - * @param max Max value used as upper border - * @return Random Integer number between min and max - */ -stock Math_GetRandomInt(min, max) -{ - new random = GetURandomInt(); - - if (random == 0) { - random++; - } - - return RoundToCeil(float(random) / (float(SIZE_OF_INT) / float(max - min + 1))) + min - 1; -} - -/** - * Returns a random, uniform Float number in the specified (inclusive) range. - * This is safe to use multiple times in a function. - * The seed is set automatically for each plugin. - * - * @param min Min value used as lower border - * @param max Max value used as upper border - * @return Random Float number between min and max - */ -stock Float:Math_GetRandomFloat(Float:min, Float:max) -{ - return (GetURandomFloat() * (max - min)) + min; -} - -/** - * Gets the percentage of amount in all as Integer where - * amount and all are numbers and amount usually - * is a subset of all. - * - * @param value Integer value - * @param all Integer value - * @return An Integer value between 0 and 100 (inclusive). - */ -stock Math_GetPercentage(value, all) { - return RoundToNearest((float(value) / float(all)) * 100.0); -} - -/** - * Gets the percentage of amount in all as Float where - * amount and all are numbers and amount usually - * is a subset of all. - * - * @param value Float value - * @param all Float value - * @return A Float value between 0.0 and 100.0 (inclusive). - */ -stock Float:Math_GetPercentageFloat(Float:value, Float:all) { - return (value / all) * 100.0; -} - -/* - * Moves the start vector on a direct line to the end vector by the given scale. - * Note: If scale is 0.0 the output will be the same as the start vector and if scale is 1.0 the output vector will be the same as the end vector. - * Exmaple usage: Move an entity to another entity but only 12 units: Vector_MoveVector(entity1Origin,entity2Origin,(12.0 / GetVectorDistance(entity1Origin,entity2Origin)),newEntity1Origin); now only teleport your entity to newEntity1Origin. - * - * @param start The start vector where the imagined line starts. - * @param end The end vector where the imagined line ends. - * @param scale The position on the line 0.0 is the start 1.0 is the end. - * @param output Output vector - * @noreturn - */ -stock Math_MoveVector(const Float:start[3], const Float:end[3], Float:scale, Float:output[3]) -{ - SubtractVectors(end,start,output); - ScaleVector(output,scale); - AddVectors(start,output,output); -} - -/** - * Puts x, y and z into a vector. - * - * @param x Float value. - * @param y Float value. - * @param z Float value. - * @param result Output vector. - * @noreturn - */ -stock Math_MakeVector(const Float:x, const Float:y, const Float:z, Float:result[3]) -{ - result[0] = x; - result[1] = y; - result[2] = z; -} - -/** - * Rotates a vector around its zero-point. - * Note: As example you can rotate mins and maxs of an entity and then add its origin to mins and maxs to get its bounding box in relation to the world and its rotation. - * When used with players use the following angle input: - * angles[0] = 0.0; - * angles[1] = 0.0; - * angles[2] = playerEyeAngles[1]; - * - * @param vec Vector to rotate. - * @param angles How to rotate the vector. - * @param result Output vector. - * @noreturn - */ -stock Math_RotateVector(const Float:vec[3], const Float:angles[3], Float:result[3]) -{ - // First the angle/radiant calculations - decl Float:rad[3]; - // I don't really know why, but the alpha, beta, gamma order of the angles are messed up... - // 2 = xAxis - // 0 = yAxis - // 1 = zAxis - rad[0] = DegToRad(angles[2]); - rad[1] = DegToRad(angles[0]); - rad[2] = DegToRad(angles[1]); - - // Pre-calc function calls - new Float:cosAlpha = Cosine(rad[0]); - new Float:sinAlpha = Sine(rad[0]); - new Float:cosBeta = Cosine(rad[1]); - new Float:sinBeta = Sine(rad[1]); - new Float:cosGamma = Cosine(rad[2]); - new Float:sinGamma = Sine(rad[2]); - - // 3D rotation matrix for more information: http://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions - new Float:x = vec[0], Float:y = vec[1], Float:z = vec[2]; - new Float:newX, Float:newY, Float:newZ; - newY = cosAlpha*y - sinAlpha*z; - newZ = cosAlpha*z + sinAlpha*y; - y = newY; - z = newZ; - - newX = cosBeta*x + sinBeta*z; - newZ = cosBeta*z - sinBeta*x; - x = newX; - z = newZ; - - newX = cosGamma*x - sinGamma*y; - newY = cosGamma*y + sinGamma*x; - x = newX; - y = newY; - - // Store everything... - result[0] = x; - result[1] = y; - result[2] = z; -} - -/** - * Converts Source Game Units to metric Meters - * - * @param units Float value - * @return Meters as Float value. - */ -stock Float:Math_UnitsToMeters(Float:units) -{ - return (units * GAMEUNITS_TO_METERS); -} - -/** - * Converts Source Game Units to Meters - * - * @param units Float value - * @return Feet as Float value. - */ -stock Float:Math_UnitsToFeet(Float:units) -{ - return (Math_UnitsToMeters(units) * METERS_TO_FEET); -} +#if defined _smlib_math_included + #endinput +#endif +#define _smlib_math_included + +#include + +#define SIZE_OF_INT 2147483647 // without 0 +#define INT_MAX_DIGITS 10 + +#define GAMEUNITS_TO_METERS 0.01905 +#define METERS_TO_GAMEUNITS 52.49343832020997 +#define METERS_TO_FEET 3.2808399 +#define FEET_TO_METERS 0.3048 +#define KILOMETERS_TO_MILES 0.62137 + +enum VecAngle +{ + ANG_ALPHA, + ANG_BETA, + ANG_GAMMA +}; + +/** + * Makes a negative integer number to a positive integer number. + * This is faster than Sourcemod's native FloatAbs() for integers. + * Use FloatAbs() for Float numbers. + * + * @param number A number that can be positive or negative. + * @return Positive number. + */ +stock int Math_Abs(int value) +{ + return (value ^ (value >> 31)) - (value >> 31); +} + +/** + * Checks if 2 vectors are equal. + * You can specfiy a tolerance, which is the maximum distance at which vectors are considered equals + * + * @param vec1 First vector (3 dim array) + * @param vec2 Second vector (3 dim array) + * @param tolerance If you want to check that those vectors are somewhat even. 0.0 means they are 100% even if this function returns true. + * @return True if vectors are equal, false otherwise. + */ +stock bool Math_VectorsEqual(float vec1[3], float vec2[3], float tolerance=0.0) +{ + float distance = GetVectorDistance(vec1, vec2, true); + + return distance <= (tolerance * tolerance); +} + +/** + * Sets the given value to min + * if the value is smaller than the given. + * Don't use this with float values. + * + * @param value Value + * @param min Min Value used as lower border + * @return Correct value not lower than min + */ +stock any Math_Min(any value, any min) +{ + if (value < min) { + value = min; + } + + return value; +} + +/** + * Sets the given value to max + * if the value is greater than the given. + * Don't use this with float values. + * + * @param value Value + * @param max Max Value used as upper border + * @return Correct value not upper than max + */ +stock any Math_Max(any value, any max) +{ + if (value > max) { + value = max; + } + + return value; +} + +/** + * Makes sure a value is within a certain range and + * returns the value. + * If the value is outside the range it is set to either + * min or max, if it is inside the range it will just return + * the specified value. + * Don't use this with float values. + * + * @param value Value + * @param min Min value used as lower border + * @param max Max value used as upper border + * @return Correct value not lower than min and not greater than max. + */ +stock any Math_Clamp(any value, any min, any max) +{ + value = Math_Min(value, min); + value = Math_Max(value, max); + + return value; +} + +/* + * Checks if the value is within the given bounds (min & max). + * Don't use this with float values. + * + * @param value The value you want to check. + * @param min The lower border. + * @param max The upper border. + * @return True if the value is within bounds (bigger or equal min / smaller or equal max), false otherwise. + */ +stock bool Math_IsInBounds(any value, any min, any max) +{ + if (value < min || value > max) { + return false; + } + + return true; +} + +/** + * Let's the specified value "overflow" if it is outside the given limit. + * This is like with integers when it reaches a value above the max possible + * integer size. + * Don't use this with float values. + * + * @param value Value + * @param min Min value used as lower border + * @param max Max value used as upper border + * @return Overflowed number + */ +stock any Math_Overflow(any value, any min, any max) +{ + return (value % max) + min; +} + +/** + * Returns a random, uniform Integer number in the specified (inclusive) range. + * This is safe to use multiple times in a function. + * The seed is set automatically for each plugin. + * Rewritten by MatthiasVance, thanks. + * + * @param min Min value used as lower border + * @param max Max value used as upper border + * @return Random Integer number between min and max + */ +stock int Math_GetRandomInt(int min, int max) +{ + int random = GetURandomInt(); + + if (random == 0) { + random++; + } + + return RoundToCeil(float(random) / (float(SIZE_OF_INT) / float(max - min + 1))) + min - 1; +} + +/** + * Returns a random, uniform Float number in the specified (inclusive) range. + * This is safe to use multiple times in a function. + * The seed is set automatically for each plugin. + * + * @param min Min value used as lower border + * @param max Max value used as upper border + * @return Random Float number between min and max + */ +stock float Math_GetRandomFloat(float min, float max) +{ + return (GetURandomFloat() * (max - min)) + min; +} + +/** + * Gets the percentage of amount in all as Integer where + * amount and all are numbers and amount usually + * is a subset of all. + * + * @param value Integer value + * @param all Integer value + * @return An Integer value between 0 and 100 (inclusive). + */ +stock int Math_GetPercentage(int value, int all) { + return RoundToNearest((float(value) / float(all)) * 100.0); +} + +/** + * Gets the percentage of amount in all as Float where + * amount and all are numbers and amount usually + * is a subset of all. + * + * @param value Float value + * @param all Float value + * @return A Float value between 0.0 and 100.0 (inclusive). + */ +stock float Math_GetPercentageFloat(float value, float all) { + return (value / all) * 100.0; +} + +/* + * Moves the start vector on a direct line to the end vector by the given scale. + * Note: If scale is 0.0 the output will be the same as the start vector and if scale is 1.0 the output vector will be the same as the end vector. + * Exmaple usage: Move an entity to another entity but only 12 units: Vector_MoveVector(entity1Origin,entity2Origin,(12.0 / GetVectorDistance(entity1Origin,entity2Origin)),newEntity1Origin); now only teleport your entity to newEntity1Origin. + * + * @param start The start vector where the imagined line starts. + * @param end The end vector where the imagined line ends. + * @param scale The position on the line 0.0 is the start 1.0 is the end. + * @param output Output vector + */ +stock void Math_MoveVector(const float start[3], const float end[3], float scale, float output[3]) +{ + SubtractVectors(end,start,output); + ScaleVector(output,scale); + AddVectors(start,output,output); +} + +/** + * Puts x, y and z into a vector. + * + * @param x Float value. + * @param y Float value. + * @param z Float value. + * @param result Output vector. + */ +stock void Math_MakeVector(float x, float y, float z, float result[3]) +{ + result[0] = x; + result[1] = y; + result[2] = z; +} + +/** + * Rotates a vector around its zero-point. + * Note: As example you can rotate mins and maxs of an entity and then add its origin to mins and maxs to get its bounding box in relation to the world and its rotation. + * When used with players use the following angle input: + * angles[0] = 0.0; + * angles[1] = 0.0; + * angles[2] = playerEyeAngles[1]; + * + * @param vec Vector to rotate. + * @param angles How to rotate the vector. + * @param result Output vector. + */ +stock void Math_RotateVector(const float vec[3], const float angles[3], float result[3]) +{ + // First the angle/radiant calculations + float rad[3]; + // I don't really know why, but the alpha, beta, gamma order of the angles are messed up... + // 2 = xAxis + // 0 = yAxis + // 1 = zAxis + rad[0] = DegToRad(angles[2]); + rad[1] = DegToRad(angles[0]); + rad[2] = DegToRad(angles[1]); + + // Pre-calc function calls + float cosAlpha = Cosine(rad[0]); + float sinAlpha = Sine(rad[0]); + float cosBeta = Cosine(rad[1]); + float sinBeta = Sine(rad[1]); + float cosGamma = Cosine(rad[2]); + float sinGamma = Sine(rad[2]); + + // 3D rotation matrix for more information: http://en.wikipedia.org/wiki/Rotation_matrix#In_three_dimensions + float x = vec[0], y = vec[1], z = vec[2]; + float newX, newY, newZ; + newY = cosAlpha*y - sinAlpha*z; + newZ = cosAlpha*z + sinAlpha*y; + y = newY; + z = newZ; + + newX = cosBeta*x + sinBeta*z; + newZ = cosBeta*z - sinBeta*x; + x = newX; + z = newZ; + + newX = cosGamma*x - sinGamma*y; + newY = cosGamma*y + sinGamma*x; + x = newX; + y = newY; + + // Store everything... + result[0] = x; + result[1] = y; + result[2] = z; +} + +/** + * Converts Source Game Units to metric Meters + * + * @param units Float value + * @return Meters as Float value. + */ +stock float Math_UnitsToMeters(float units) +{ + return (units * GAMEUNITS_TO_METERS); +} + +/** + * Converts Source Game Units to Meters + * + * @param units Float value + * @return Feet as Float value. + */ +stock float Math_UnitsToFeet(float units) +{ + return (Math_UnitsToMeters(units) * METERS_TO_FEET); +} + +/** + * Converts Source Game Units to Centimeters + * + * @param units Float value + * @return Centimeters as Float value. + */ +stock float Math_UnitsToCentimeters(float units) +{ + return (Math_UnitsToMeters(units) * 100.0); +} + +/** + * Converts Source Game Units to Kilometers + * + * @param units Float value + * @return Kilometers as Float value. + */ +stock float Math_UnitsToKilometers(float units) +{ + return (Math_UnitsToMeters(units) / 1000.0); +} + +/** + * Converts Source Game Units to Miles + * + * @param units Float value + * @return Miles as Float value. + */ +stock float Math_UnitsToMiles(float units) +{ + return (Math_UnitsToKilometers(units) * KILOMETERS_TO_MILES); +} diff --git a/addons/sourcemod/scripting/include/smlib/menus.inc b/addons/sourcemod/scripting/include/smlib/menus.inc new file mode 100644 index 0000000..87f253e --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/menus.inc @@ -0,0 +1,37 @@ +#if defined _smlib_menus_included + #endinput +#endif +#define _smlib_menus_included + +#include +#include + +/** + * Adds an option to a menu with a String display but an integer + * identifying the option. + * + * @param menu Handle to the menu + * @param value Integer value for the option + * @param display Display text for the menu + */ +stock void Menu_AddIntItem(Menu menu, any value, char[] display) +{ + char buffer[INT_MAX_DIGITS + 1]; + IntToString(value, buffer, sizeof(buffer)); + menu.AddItem(buffer, display); +} + +/** + * Retrieves an integer-value choice from a menu, where the + * menu's information strings were created as integers. + * + * @param menu Handle to the menu + * @param param2 The item position selected from the menu. + * @return Integer choice from the menu, or 0 if the integer could not be parsed. + */ +stock any Menu_GetIntItem(Menu menu, any param2) +{ + char buffer[INT_MAX_DIGITS + 1]; + menu.GetItem(param2, buffer, sizeof(buffer)); + return StringToInt(buffer); +} diff --git a/addons/sourcemod/scripting/include/smlib/server.inc b/addons/sourcemod/scripting/include/smlib/server.inc new file mode 100644 index 0000000..af95038 --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/server.inc @@ -0,0 +1,135 @@ +#if defined _smlib_server_included + #endinput +#endif +#define _smlib_server_included + +#include +#include + +/* + * Gets the server's public/external (default) or + * private/local (usually server's behind a NAT) IP. + * If your server is behind a NAT Router, you need the SteamTools + * extension available at http://forums.alliedmods.net/showthread.php?t=129763 + * to get the public IP. has to be included BEFORE . + * If the server is not behind NAT, the public IP is the same as the private IP. + * + * @param public Set to true to retrieve the server's public/external IP, false otherwise. + * @return Long IP or 0 if the IP couldn't be retrieved. + */ +stock int Server_GetIP(bool public_=true) +{ + int ip = 0; + + static ConVar cvHostip = null; + + if (cvHostip == INVALID_HANDLE) { + cvHostip = FindConVar("hostip"); + MarkNativeAsOptional("Steam_GetPublicIP"); + } + + if (cvHostip != INVALID_HANDLE) { + ip = cvHostip.IntValue; + } + + if (ip != 0 && IsIPLocal(ip) == public_) { + ip = 0; + } + +#if defined _steamtools_included + if (ip == 0) { + if (CanTestFeatures() && GetFeatureStatus(FeatureType_Native, "Steam_GetPublicIP") == FeatureStatus_Available) { + int octets[4]; + Steam_GetPublicIP(octets); + + ip = + octets[0] << 24 | + octets[1] << 16 | + octets[2] << 8 | + octets[3]; + + if (IsIPLocal(ip) == public_) { + ip = 0; + } + } + } +#endif + + return ip; +} + +/* + * Gets the server's public/external (default) or + * private/local (usually server's behind a NAT) as IP String in dotted format. + * If your server is behind a NAT Router, you need the SteamTools + * extension available at http://forums.alliedmods.net/showthread.php?t=129763 + * to get the public IP. has to be included BEFORE . + * If the public IP couldn't be found, an empty String is returned. + * If the server is not behind NAT, the public IP is the same as the private IP. + * + * @param buffer String buffer (size=16) + * @param size String buffer size. + * @param public Set to true to retrieve the server's public/external IP, false otherwise. + * @return True on success, false otherwise. + */ +stock bool Server_GetIPString(char[] buffer, int size, bool public_=true) +{ + int ip; + + if ((ip = Server_GetIP(public_)) == 0) { + buffer[0] = '\0'; + return false; + } + + LongToIP(ip, buffer, size); + + return true; +} + +/* + * Gets the server's local port. + * + * @noparam + * @return The server's port, 0 if there is no port. + */ +stock int Server_GetPort() +{ + static ConVar cvHostport = null; + + if (cvHostport == INVALID_HANDLE) { + cvHostport = FindConVar("hostport"); + } + + if (cvHostport == INVALID_HANDLE) { + return 0; + } + + int port = cvHostport.IntValue; + + return port; +} + +/* + * Gets the server's hostname + * + * @param hostname String buffer + * @param size String buffer size + * @return True on success, false otherwise. + */ +stock bool Server_GetHostName(char[] buffer, int size) +{ + static ConVar cvHostname = null; + + if (cvHostname == INVALID_HANDLE) { + cvHostname = FindConVar("hostname"); + } + + if (cvHostname == INVALID_HANDLE) { + buffer[0] = '\0'; + return false; + } + + cvHostname.GetString(buffer, size); + + return true; +} diff --git a/addons/sourcemod/scripting/include/smlib/sql.inc b/addons/sourcemod/scripting/include/smlib/sql.inc new file mode 100644 index 0000000..e02470f --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/sql.inc @@ -0,0 +1,107 @@ +#if defined _smlib_sql_included + #endinput +#endif +#define _smlib_sql_included + +#include +#include + +/** + * Executes a threaded SQL Query (See: SQL_TQuery) + * This function supports the printf Syntax. + * + * + * @param database A database Handle. + * @param callback Callback; database is in "owner" and the query Handle is passed in "hndl". + * @param data Extra data value to pass to the callback. + * @param format Query string, printf syntax supported + * @param priority Priority queue to use + * @param ... Variable number of format parameters. + */ +stock void SQL_TQueryF(Database database, SQLTCallback callback, any data, DBPriority priority=DBPrio_Normal, const char[] format, any ...) { + + if (!database) { + ThrowError("[SMLIB] Error: Invalid database handle."); + return; + } + + char query[16384]; + VFormat(query, sizeof(query), format, 6); + + SQL_TQuery(database, callback, query, data, priority); +} + +/** + * Fetches an integer from a field in the current row of a result set (See: SQL_FetchInt) + * + * @param query A query (or statement) Handle. + * @param field The field index (starting from 0). + * @param result Optional variable to store the status of the return value. + * @return An integer value. + * @error Invalid query Handle or field index, invalid + * type conversion requested from the database, + * or no current result set. + */ +stock int SQL_FetchIntByName(DBResultSet query, const char[] fieldName, DBResult &result=DBVal_Error) { + + int fieldNum; + SQL_FieldNameToNum(query, fieldName, fieldNum); + + return SQL_FetchInt(query, fieldNum, result); +} + +/** + * Fetches a bool from a field in the current row of a result set (See: SQL_FetchInt) + * + * @param query A query (or statement) Handle. + * @param field The field index (starting from 0). + * @param result Optional variable to store the status of the return value. + * @return A bool value. + * @error Invalid query Handle or field index, invalid + * type conversion requested from the database, + * or no current result set. + */ +stock bool SQL_FetchBoolByName(DBResultSet query, const char[] fieldName, DBResult &result=DBVal_Error) { + + return SQL_FetchIntByName(query, fieldName, result) != 0; +} + +/** + * Fetches a float from a field in the current row of a result set. (See: SQL_FetchFloat) + * + * @param query A query (or statement) Handle. + * @param field The field index (starting from 0). + * @param result Optional variable to store the status of the return value. + * @return A float value. + * @error Invalid query Handle or field index, invalid + * type conversion requested from the database, + * or no current result set. + */ +stock float SQL_FetchFloatByName(DBResultSet query, const char[] fieldName, DBResult &result=DBVal_Error) { + + int fieldNum; + SQL_FieldNameToNum(query, fieldName, fieldNum); + + return SQL_FetchFloat(query, fieldNum, result); +} + +/** + * Fetches a string from a field in the current row of a result set. (See: SQL_FetchString) + * + * @param query A query (or statement) Handle. + * @param field The field index (starting from 0). + * @param buffer String buffer. + * @param maxlength Maximum size of the string buffer. + * @param result Optional variable to store the status of the return value. + * @return Number of bytes written. + * @error Invalid query Handle or field index, invalid + * type conversion requested from the database, + * or no current result set. + */ +stock int SQL_FetchStringByName(DBResultSet query, const char[] fieldName, char[] buffer, int maxlength, DBResult &result=DBVal_Error) { + + int fieldNum; + SQL_FieldNameToNum(query, fieldName, fieldNum); + + return SQL_FetchString(query, fieldNum, buffer, maxlength, result); +} diff --git a/addons/sourcemod/scripting/include/smlib/strings.inc b/addons/sourcemod/scripting/include/smlib/strings.inc new file mode 100644 index 0000000..7f568c0 --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/strings.inc @@ -0,0 +1,228 @@ +#if defined _smlib_strings_included + #endinput +#endif +#define _smlib_strings_included + +#include +#include + +/** + * Checks if the string is numeric. + * This correctly handles + - . in the String. + * + * @param str String to check. + * @return True if the String is numeric, false otherwise.. + */ +stock bool String_IsNumeric(const char[] str) +{ + int x=0; + int dotsFound=0; + int numbersFound=0; + + if (str[x] == '+' || str[x] == '-') { + x++; + } + + while (str[x] != '\0') { + + if (IsCharNumeric(str[x])) { + numbersFound++; + } + else if (str[x] == '.') { + dotsFound++; + + if (dotsFound > 1) { + return false; + } + } + else { + return false; + } + + x++; + } + + if (!numbersFound) { + return false; + } + + return true; +} + +/** + * Trims a string by removing the specified chars from beginning and ending. + * Removes all ' ', '\t', '\r', '\n' characters by default. + * The Output String can be the same as the Input String. + * + * @param str Input String. + * @param output Output String (Can be the as the input). + * @param size Size of the output String. + * @param chars Characters to remove. + */ +stock void String_Trim(const char[] str, char[] output, int size, const char[] chrs=" \t\r\n") +{ + int x=0; + while (str[x] != '\0' && FindCharInString(chrs, str[x]) != -1) { + x++; + } + + x = strcopy(output, size, str[x]); + x--; + + while (x >= 0 && FindCharInString(chrs, output[x]) != -1) { + x--; + } + + output[++x] = '\0'; +} + +/** + * Removes a list of strings from a string. + * + * @param buffer Input/Output buffer. + * @param removeList A list of strings which should be removed from buffer. + * @param size Number of Strings in the List. + * @param caseSensitive If true, comparison is case sensitive. If false (default), comparison is case insensitive. + */ +stock void String_RemoveList(char[] buffer, const char[][] removeList, int size, bool caseSensitive=false) +{ + for (int i=0; i < size; i++) { + ReplaceString(buffer, SIZE_OF_INT, removeList[i], "", caseSensitive); + } +} + +/** + * Converts the whole String to lower case. + * Only works with alphabetical characters (not ÖÄÜ) because Sourcemod suxx ! + * The Output String can be the same as the Input String. + * + * @param input Input String. + * @param output Output String. + * @param size Max Size of the Output string + */ +stock void String_ToLower(const char[] input, char[] output, int size) +{ + size--; + + int x=0; + while (input[x] != '\0' && x < size) { + + output[x] = CharToLower(input[x]); + + x++; + } + + output[x] = '\0'; +} + +/** + * Converts the whole String to upper case. + * Only works with alphabetical characters (not öäü) because Sourcemod suxx ! + * The Output String can be the same as the Input String. + * + * @param input Input String. + * @param output Output String. + * @param size Max Size of the Output string + */ +stock void String_ToUpper(const char[] input, char[] output, int size) +{ + size--; + + int x=0; + while (input[x] != '\0' && x < size) { + + output[x] = CharToUpper(input[x]); + + x++; + } + + output[x] = '\0'; +} + +/** + * Generates a random string. + * + * + * @param buffer String Buffer. + * @param size String Buffer size (must be length+1) + * @param length Number of characters being generated. + * @param chrs String for specifying the characters used for random character generation. + * By default it will use all letters of the alphabet (upper and lower) and all numbers. + * If you pass an empty String, it will use all readable ASCII characters (33 - 126) + */ +stock void String_GetRandom(char[] buffer, int size, int length=32, const char[] chrs="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234556789") +{ + int random, len; + size--; + + if (chrs[0] != '\0') { + len = strlen(chrs) - 1; + } + + int n = 0; + while (n < length && n < size) { + + if (chrs[0] == '\0') { + random = Math_GetRandomInt(33, 126); + buffer[n] = random; + } + else { + random = Math_GetRandomInt(0, len); + buffer[n] = chrs[random]; + } + + n++; + } + + buffer[length] = '\0'; +} + +/** + * Checks if string str starts with subString. + * + * + * @param str String to check + * @param subString Sub-String to check in str + * @return True if str starts with subString, false otherwise. + */ +stock bool String_StartsWith(const char[] str, const char[] subString) +{ + int n = 0; + while (subString[n] != '\0') { + + if (str[n] == '\0' || str[n] != subString[n]) { + return false; + } + + n++; + } + + return true; +} + +/** + * Checks if string str ends with subString. + * + * + * @param str String to check + * @param subString Sub-String to check in str + * @return True if str ends with subString, false otherwise. + */ +stock bool String_EndsWith(const char[] str, const char[] subString) +{ + int n_str = strlen(str) - 1; + int n_subString = strlen(subString) - 1; + + if(n_str < n_subString) { + return false; + } + + while (n_str != 0 && n_subString != 0) { + + if (str[n_str--] != subString[n_subString--]) { + return false; + } + } + + return true; +} diff --git a/addons/sourcemod/scripting/include/smlib/teams.inc b/addons/sourcemod/scripting/include/smlib/teams.inc new file mode 100644 index 0000000..5d4eba1 --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/teams.inc @@ -0,0 +1,317 @@ +#if defined _smlib_teams_included + #endinput +#endif +#define _smlib_teams_included + +#include +#include +#include + +#define MAX_TEAMS 32 // Max number of teams in a game +#define MAX_TEAM_NAME_LENGTH 32 // Max length of a team's name + +// Team Defines +#define TEAM_INVALID -1 +#define TEAM_UNASSIGNED 0 +#define TEAM_SPECTATOR 1 +#define TEAM_ONE 2 +#define TEAM_TWO 3 +#define TEAM_THREE 4 +#define TEAM_FOUR 5 + +/* + * If one team is empty its assumed single team mode is enabled and the game won't start. + * + * @noparam + * @return True if one team is empty, false otherwise. + */ +stock bool Team_HaveAllPlayers(bool countFakeClients=true) { + + int teamCount = GetTeamCount(); + for (int i=2; i < teamCount; i++) { + + if (Team_GetClientCount(i, ((countFakeClients) ? CLIENTFILTER_ALL : CLIENTFILTER_NOBOTS)) == 0) { + return false; + } + } + + return true; +} + +/* + * Returns the client count of the players in a team. + * + * @param team Team Index. + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + * @return Client count in the server. + */ +stock int Team_GetClientCount(int team, int flags=0) +{ + flags |= CLIENTFILTER_INGAME; + + int numClients = 0; + for (int client=1; client <= MaxClients; client++) { + + if (!Client_MatchesFilter(client, flags)) { + continue; + } + + if (GetClientTeam(client) == team) { + numClients++; + } + } + + return numClients; +} + +/* + * Returns the client counts of the first two teams (eg.: Terrorists - Counter). + * Use this function for optimization if you have to get the counts of both teams, + * otherwise use Team_GetClientCount(). + * + * @param team1 Pass an integer variable by reference + * @param team2 Pass an integer variable by reference + * @param flags Client Filter Flags (Use the CLIENTFILTER_ constants). + */ +stock void Team_GetClientCounts(int &team1=0, int &team2=0, int flags=0) +{ + flags |= CLIENTFILTER_INGAME; + + for (int client=1; client <= MaxClients; client++) { + + if (!Client_MatchesFilter(client, flags)) { + continue; + } + + if (GetClientTeam(client) == TEAM_ONE) { + team1++; + } + else if (GetClientTeam(client) == TEAM_TWO) { + team2++; + } + } +} + +/* + * Gets the name of a team. + * Don't call this before OnMapStart() + * + * @param index Team Index. + * @param str String buffer + * @param size String Buffer Size + * @return True on success, false otherwise + */ +stock bool Team_GetName(int index, char[] str, int size) +{ + int edict = Team_GetEdict(index); + + if (edict == -1) { + str[0] = '\0'; + return false; + } + + GetEntPropString(edict, Prop_Send, "m_szTeamname", str, size); + + return true; +} + +/* + * Changes a team's name. + * Use this carefully ! + * Only set the teamname OnMapStart() or OnEntityCreated() + * when no players are ingame, otherwise it can crash the server. + * + * @param index Team Index. + * @param name New Name String + * @return True on success, false otherwise + */ +stock bool Team_SetName(int index, const char[] name) +{ + int edict = Team_GetEdict(index); + + if (edict == -1) { + return false; + } + + SetEntPropString(edict, Prop_Send, "m_szTeamname", name); + ChangeEdictState(edict, GetEntSendPropOffs(edict, "m_szTeamname", true)); + + return true; +} + +/* + * Changes a team's score. + * Don't use this before OnMapStart(). + * + * @param index Team Index. + * @return Team Score or -1 if the team is not valid. + */ +stock int Team_GetScore(int index) +{ + int edict = Team_GetEdict(index); + + if (edict == -1) { + return -1; + } + + return GetEntProp(edict, Prop_Send, "m_iScore"); +} + +/* + * Changes a team's score. + * Don't use this before OnMapStart(). + * + * @param index Team Index. + * @param score Score value. + * @return True on success, false otherwise + */ +stock bool Team_SetScore(int index, int score) +{ + int edict = Team_GetEdict(index); + + if (edict == -1) { + return false; + } + + SetEntProp(edict, Prop_Send, "m_iScore", score); + + ChangeEdictState(edict, GetEntSendPropOffs(edict, "m_iScore", true)); + + return true; +} + +/* + * Gets a team's edict (*team_manager) Team Index. + * Don't call this before OnMapStart() + * + * @param edict Edict + * @return Team Index + */ +stock int Team_EdictGetNum(int edict) +{ + return GetEntProp(edict, Prop_Send, "m_iTeamNum"); +} + +/* + * Check's whether the index is a valid team index or not. + * Don't call this before OnMapStart() + * + * @param index Index. + * @return True if the Index is a valid team, false otherwise. + */ +stock bool Team_IsValid(int index) +{ + return (Team_GetEdict(index) != -1); +} + +/* + * Gets a team's edict (team_manager) Team Index. + * Don't call this before OnMapStart() + * + * @param index Edict + * @return Team Index + */ +stock int Team_EdictIsValid(int edict) +{ + return GetEntProp(edict, Prop_Send, "m_iTeamNum"); +} + +/* + * Gets a team's edict (team_manager). + * This function caches found team edicts. + * Don't call this before OnMapStart() + * + * @param index Team Index. + * @return Team edict or -1 if not found + */ +stock int Team_GetEdict(int index) +{ + static int teams[MAX_TEAMS] = { INVALID_ENT_REFERENCE, ... }; + + if (index < 0 || index > MAX_TEAMS) { + return -1; + } + + int edict = teams[index]; + if (Entity_IsValid(edict)) { + return edict; + } + + bool foundTeamManager = false; + + int maxEntities = GetMaxEntities(); + for (int entity=MaxClients+1; entity < maxEntities; entity++) { + + if (!IsValidEntity(entity)) { + continue; + } + + if (Entity_ClassNameMatches(entity, "team_manager", true)) { + foundTeamManager = true; + } + // Do not continue when no team managers are found anymore (for optimization) + else if (foundTeamManager) { + return -1; + } + else { + continue; + } + + int num = Team_EdictGetNum(entity); + + if (num >= 0 && num <= MAX_TEAMS) { + teams[num] = EntIndexToEntRef(entity); + } + + if (num == index) { + return entity; + } + } + + return -1; +} + +/* + * Trys to find a client in the specified team. + * This function is NOT random, it returns the first + * or the cached player (Use Client_GetRandom() instead). + * + * @param index Team Index. + * @return Client Index or -1 if no client was found in the specified team. + */ +stock int Team_GetAnyClient(int index) +{ + static int client_cache[MAX_TEAMS] = {-1, ...}; + int client; + + if (index > 0) { + client = client_cache[index]; + + if (client > 0 && client <= MaxClients) { + + if (IsClientInGame(client) && GetClientTeam(client) == index) { + return client; + } + } + else { + client = -1; + } + } + + for (client=1; client <= MaxClients; client++) { + + if (!IsClientInGame(client)) { + continue; + } + + if (GetClientTeam(client) != index) { + continue; + } + + client_cache[index] = client; + + return client; + } + + return -1; +} diff --git a/addons/sourcemod/scripting/include/smlib/vehicles.inc b/addons/sourcemod/scripting/include/smlib/vehicles.inc new file mode 100644 index 0000000..232f5b4 --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/vehicles.inc @@ -0,0 +1,137 @@ +#if defined _smlib_vehicles_included + #endinput +#endif +#define _smlib_vehicles_included + +#include +#include +#include +#include + +/** + * Returns the vehicle's driver. + * If there is no driver in the vehicle, -1 is returned. + * + * @param vehicle Entity index. + * @return Client index, or -1 if there is no driver. + */ +stock int Vehicle_GetDriver(int vehicle) +{ + int m_hVehicle = GetEntPropEnt(vehicle, Prop_Send, "m_hPlayer"); + + return m_hVehicle; +} + +/** + * Returns whether there is a driver in the vehicle or not. + * + * @param vehicle Entity index. + * @return True if the vehicle has a driver, false otherwise + */ +stock bool Vehicle_HasDriver(int vehicle) +{ + return Vehicle_GetDriver(vehicle) != -1; +} + +/** + * Kicks the driver ouf of the vehicle + * + * @param vehicle Entity index. + * @return True on success, false otherwise. + */ +stock bool Vehicle_ExitDriver(int vehicle) +{ + if (!Vehicle_HasDriver(vehicle)) { + return false; + } + + return AcceptEntityInput(vehicle, "ExitVehicle"); +} + +/** + * Start's the vehicle's engine + * + * @param vehicle Entity index. + * @return True on success, false otherwise. + */ +stock bool Vehicle_TurnOn(int vehicle) +{ + return AcceptEntityInput(vehicle, "TurnOn"); +} + +/** + * Shuts down the vehicle's engine + * + * @param vehicle Entity index. + * @return True on success, false otherwise. + */ +stock bool Vehicle_TurnOff(int vehicle) +{ + return AcceptEntityInput(vehicle, "TurnOff"); +} + +/** + * Locks the vehicle. + * + * @param vehicle Entity index. + * @return True on success, false otherwise. + */ +stock bool Vehicle_Lock(int vehicle) +{ + return AcceptEntityInput(vehicle, "Lock"); +} + +/** + * Unlocks the vehicle. + * + * @param vehicle Entity index. + * @return True on success, false otherwise. + */ +stock bool Vehicle_Unlock(int vehicle) +{ + return AcceptEntityInput(vehicle, "Unlock"); +} + +/** + * Returns wether the entity is a valid vehicle or not. + * + * @param vehicle Entity index. + * @return True if it is a valid vehicle, false otherwise. + */ +stock bool Vehicle_IsValid(int vehicle) +{ + if (!Entity_IsValid(vehicle)) { + return false; + } + + return Entity_ClassNameMatches(vehicle, "prop_vehicle", true); +} + +/** + * Reads the vehicle script from a vehicle. + * This script contains all the vehicle settings like its speed + * and that stuff. + * + * @param vehicle Entity index. + * @param buffer String Buffer. + * @param size String Buffer size. + * @noreturn + */ +stock bool Vehicle_GetScript(int vehicle, char[] buffer, int size) +{ + GetEntPropString(vehicle, Prop_Data, "m_vehicleScript", buffer, size); +} + +/** + * Sets the script of a vehicle. + * This script contains all the vehicle settings like its speed + * and that stuff. + * + * @param vehicle Entity index. + * @param buffer Vehicle Script path. + * @noreturn + */ +stock bool Vehicle_SetScript(int vehicle, char[] script) +{ + DispatchKeyValue(vehicle, "vehiclescript", script); +} diff --git a/addons/sourcemod/scripting/include/smlib/weapons.inc b/addons/sourcemod/scripting/include/smlib/weapons.inc new file mode 100644 index 0000000..f17cbef --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/weapons.inc @@ -0,0 +1,393 @@ +#if defined _smlib_weapons_included + #endinput +#endif +#define _smlib_weapons_included + +#include +#include +#include + +#define MAX_WEAPON_OFFSET 64 +#define MAX_WEAPON_SLOTS 6 // hud item selection slots +#define MAX_WEAPON_POSITIONS 20 // max number of items within a slot +#define MAX_WEAPONS 48 // Max number of weapons availabl +#define WEAPON_NOCLIP -1 // clip sizes set to this tell the weapon it doesn't use a clip +#define MAX_AMMO_TYPES 32 +#define MAX_AMMO_SLOTS 32 // not really slots + +#define MAX_WEAPON_STRING 80 +#define MAX_WEAPON_PREFIX 16 +#define MAX_WEAPON_AMMO_NAME 32 + +/* + * Gets the owner (usually a client) of the weapon + * + * @param weapon Weapon Entity. + * @return Owner of the weapon or INVALID_ENT_REFERENCE if the weapon has no owner. + */ +stock int Weapon_GetOwner(int weapon) +{ + return GetEntPropEnt(weapon, Prop_Data, "m_hOwner"); +} + +/* + * Sets the owner (usually a client) of the weapon + * + * @param weapon Weapon Entity. + * @param entity Entity Index. + * @noreturn + */ +stock int Weapon_SetOwner(int weapon, int entity) +{ + SetEntPropEnt(weapon, Prop_Data, "m_hOwner", entity); +} + +/* + * Checks whether the entity is a valid weapon or not. + * + * @param weapon Weapon Entity. + * @return True if the entity is a valid weapon, false otherwise. + */ +stock bool Weapon_IsValid(int weapon) +{ + if (!IsValidEdict(weapon)) { + return false; + } + + return Entity_ClassNameMatches(weapon, "weapon_", true); +} + +/* + * Create's a weapon and spawns it in the world at the specified location. + * + * @param className Classname String of the weapon to spawn + * @param absOrigin Absolute Origin Vector where to spawn the weapon. + * @param absAngles Absolute Angles Vector. + * @return Weapon Index of the created weapon or INVALID_ENT_REFERENCE on error. + */ +stock int Weapon_Create(const char[] className, float absOrigin[3], float absAngles[3]) +{ + int weapon = Entity_Create(className); + + if (weapon == INVALID_ENT_REFERENCE) { + return INVALID_ENT_REFERENCE; + } + + Entity_SetAbsOrigin(weapon, absOrigin); + Entity_SetAbsAngles(weapon, absAngles); + + DispatchSpawn(weapon); + + return weapon; +} + +/* + * Create's a weapon and spawns it in the world at the specified location. + * + * @param className Classname String of the weapon to spawn + * @param absOrigin Absolute Origin Vector where to spawn the weapon. + * @param absAngles Absolute Angles Vector. + * @return Weapon Index of the created weapon or INVALID_ENT_REFERENCE on error. + */ +stock int Weapon_CreateForOwner(int client, const char[] className) +{ + float absOrigin[3], absAngles[3]; + Entity_GetAbsOrigin(client, absOrigin); + Entity_GetAbsAngles(client, absAngles); + + int weapon = Weapon_Create(className, absOrigin, absAngles); + + if (weapon == INVALID_ENT_REFERENCE) { + return INVALID_ENT_REFERENCE; + } + + Entity_SetOwner(weapon, client); + + return weapon; +} + +/* + * Gets the weapon's subtype. + * The subtype is only used when a player has multiple weapons of the same type. + * + * @param weapon Weapon Entity. + * @return Subtype of the weapon. + */ +stock int Weapon_GetSubType(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iSubType"); +} + +/* + * Is the weapon currently reloading ? + * + * @param weapon Weapon Entity. + * @return True if weapon is currently reloading, false if not. + */ +stock bool Weapon_IsReloading(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_bInReload") != 0; +} + +/* + * Weapon m_iState + */ +#define WEAPON_IS_ONTARGET 0x40 +#define WEAPON_NOT_CARRIED 0 // Weapon is on the ground +#define WEAPON_IS_CARRIED_BY_PLAYER 1 // This client is carrying this weapon. +#define WEAPON_IS_ACTIVE 2 // This client is carrying this weapon and it's the currently held weapon + +/* + * Get's the state of the weapon. + * This returns whether the weapon is currently carried by a client, + * if it is active and if it is on a target. + * + * @param weapon Weapon Entity. + * @return Weapon State. + */ +stock int Weapon_GetState(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iState"); +} + +/* + * Returns whether the weapon can fire primary ammo under water. + * + * @param weapon Weapon Entity. + * @return True or False. + */ +stock bool Weapon_FiresUnderWater(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_bFiresUnderwater") != 0; +} + +/* + * Sets if the weapon can fire primary ammo under water. + * + * @param weapon Weapon Entity. + * @param can True or False. + */ +stock void Weapon_SetFiresUnderWater(int weapon, bool can=true) +{ + SetEntProp(weapon, Prop_Data, "m_bFiresUnderwater", can); +} + +/* + * Returns whether the weapon can fire secondary ammo under water. + * + * @param weapon Weapon Entity. + * @return True or False. + */ +stock bool Weapon_FiresUnderWaterAlt(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_bAltFiresUnderwater") != 0; +} + +/* + * Sets if the weapon can fire secondary ammo under water. + * + * @param weapon Weapon Entity. + * @param can True or False. + */ +stock void Weapon_SetFiresUnderWaterAlt(int weapon, bool can=true) +{ + SetEntProp(weapon, Prop_Data, "m_bAltFiresUnderwater", can); +} + +/* + * Gets the primary ammo Type (int offset) + * + * @param weapon Weapon Entity. + * @return Primary ammo type value. + */ +stock int Weapon_GetPrimaryAmmoType(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoType"); +} + +/* + * Sets the primary ammo Type (int offset) + * + * @param weapon Weapon Entity. + * @param type Primary ammo type value. + */ +stock void Weapon_SetPrimaryAmmoType(int weapon, int type) +{ + SetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoType", type); +} + +/* + * Gets the secondary ammo Type (int offset) + * + * @param weapon Weapon Entity. + * @return Secondary ammo type value. + */ +stock int Weapon_GetSecondaryAmmoType(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoType"); +} + +/* + * Sets the secondary ammo Type (int offset) + * + * @param weapon Weapon Entity. + * @param type Secondary ammo type value. + */ +stock void Weapon_SetSecondaryAmmoType(int weapon, int type) +{ + SetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoType", type); +} + +/* + * Gets the primary clip count of a weapon. + * + * @param weapon Weapon Entity. + * @return Primary Clip count. + */ +stock int Weapon_GetPrimaryClip(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iClip1"); +} + +/* + * Sets the primary clip count of a weapon. + * + * @param weapon Weapon Entity. + * @param value Clip Count value. + */ +stock void Weapon_SetPrimaryClip(int weapon, int value) +{ + SetEntProp(weapon, Prop_Data, "m_iClip1", value); +} + +/* + * Gets the secondary clip count of a weapon. + * + * @param weapon Weapon Entity. + * @return Secondy Clip count. + */ +stock int Weapon_GetSecondaryClip(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iClip2"); +} + +/* + * Sets the secondary clip count of a weapon. + * + * @param weapon Weapon Entity. + * @param value Clip Count value. + */ +stock void Weapon_SetSecondaryClip(int weapon, int value) +{ + SetEntProp(weapon, Prop_Data, "m_iClip2", value); +} + +/* + * Sets the primary & secondary clip count of a weapon. + * + * @param weapon Weapon Entity. + * @param primary Primary Clip Count value. + * @param secondary Primary Clip Count value. + */ +stock void Weapon_SetClips(int weapon, int primary, int secondary) +{ + Weapon_SetPrimaryClip(weapon, primary); + Weapon_SetSecondaryClip(weapon, secondary); +} + +/* + * Gets the primary ammo count of a weapon. + * This is only used when the weapon is not carried + * by a player to give a player ammo when he picks up + * the weapon. + * + * @param weapon Weapon Entity. + * @return Primary Ammo Count. + */ +stock int Weapon_GetPrimaryAmmoCount(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoCount"); +} + +/* + * Sets the primary ammo count of a weapon. + * This is only used when the weapon is not carried + * by a player to give a player ammo when he picks up + * the weapon. + * + * @param weapon Weapon Entity. + * @param value Primary Ammo Count. + */ +stock void Weapon_SetPrimaryAmmoCount(int weapon, int value) +{ + SetEntProp(weapon, Prop_Data, "m_iPrimaryAmmoCount", value); +} + +/* + * Gets the secondary ammo count of a weapon. + * This is only used when the weapon is not carried + * by a player to give a player ammo when he picks up + * the weapon. + * + * @param weapon Weapon Entity. + * @return Secondary Ammo Count. + */ +stock int Weapon_GetSecondaryAmmoCount(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoCount"); +} + +/* + * Sets the secodary ammo count of a weapon. + * This is only used when the weapon is not carried + * by a player to give a player ammo when he picks up + * the weapon. + * + * @param weapon Weapon Entity. + * @param value Secondary Ammo Count. + */ +stock void Weapon_SetSecondaryAmmoCount(int weapon, int value) +{ + SetEntProp(weapon, Prop_Data, "m_iSecondaryAmmoCount", value); +} + +/* + * Sets both, the primary & the secondary ammo count of a weapon. + * This is only used when the weapon is not carried + * by a player to give a player ammo when he picks up + * the weapon. + * + * @param weapon Weapon Entity. + * @value primary Primary Ammo Count. + * @value secondary Secondary Ammo Count. + */ +stock void Weapon_SetAmmoCounts(int weapon, int primary, int secondary) +{ + Weapon_SetPrimaryAmmoCount(weapon, primary); + Weapon_SetSecondaryAmmoCount(weapon, secondary); +} + +/* + * Gets the Model Index of the weapon's view model. + * + * @param weapon Weapon Entity. + * @return View Model Index. + */ +stock int Weapon_GetViewModelIndex(int weapon) +{ + return GetEntProp(weapon, Prop_Data, "m_nViewModelIndex"); +} + +/* + * Sets the Model Index of the weapon's view model. + * You can get the Model Index by precaching a model with PrecacheModel(). + * + * @param weapon Weapon Entity. + * @param index Model Index. + * @noreturn + */ +stock void Weapon_SetViewModelIndex(int weapon, int index) +{ + SetEntProp(weapon, Prop_Data, "m_nViewModelIndex", index); + ChangeEdictState(weapon, FindDataMapInfo(weapon, "m_nViewModelIndex")); +} diff --git a/addons/sourcemod/scripting/include/smlib/world.inc b/addons/sourcemod/scripting/include/smlib/world.inc new file mode 100644 index 0000000..9cfdcba --- /dev/null +++ b/addons/sourcemod/scripting/include/smlib/world.inc @@ -0,0 +1,16 @@ +#if defined _smlib_world_included + #endinput +#endif +#define _smlib_world_included + +#include + +/* + * Gets the world's max size + * + * @param vec Vector buffer + */ +stock void World_GetMaxs(float vec[3]) { + + GetEntPropVector(0, Prop_Data, "m_WorldMaxs", vec); +} diff --git a/addons/sourcemod/scripting/jetpack_bling.sp b/addons/sourcemod/scripting/jetpack_bling.sp index 0a2b404..35e4e45 100644 --- a/addons/sourcemod/scripting/jetpack_bling.sp +++ b/addons/sourcemod/scripting/jetpack_bling.sp @@ -2,8 +2,7 @@ * vim: set ts=4 : * ============================================================================= * Jetpack Plus - * Handles the sounds and particle effects for the jetpacks. Also allows - * donators to customize their jetpack. + * Handles the sounds and particle effects for the jetpacks. * * Copyright 2014 CrimsonTautology * ============================================================================= @@ -18,10 +17,8 @@ #include #include #include -#undef REQUIRE_PLUGIN -#include -#define PLUGIN_VERSION "1.2.3" +#define PLUGIN_VERSION "1.10.0" #define PLUGIN_NAME "Jetpack Plus (Bling)" #define MAX_JETPACK_TYPES 64 @@ -33,13 +30,9 @@ public Plugin:myinfo = author = "CrimsonTautology", description = "Handles sounds and particle effects for jetpacks", version = PLUGIN_VERSION, - url = "https://github.com/CrimsonTautology/sm_jetpack_plus" + url = "https://github.com/CrimsonTautology/sm-jetpack-plus" }; -new Handle:g_Cvar_DonatorsOnly = INVALID_HANDLE; - -new bool:g_DonatorLibraryExists = false; - //Player options new Handle:g_Cookie_SelectedJetpack = INVALID_HANDLE; new g_SelectedJetpack[MAXPLAYERS+1] = {DEFAULT_JETPACK, ...}; @@ -57,12 +50,10 @@ public OnPluginStart() LoadTranslations("jetpack_plus.phrases"); CreateConVar("sm_jetpack_bling_version", PLUGIN_VERSION, PLUGIN_NAME, FCVAR_SPONLY | FCVAR_REPLICATED | FCVAR_NOTIFY | FCVAR_DONTRECORD); - g_Cvar_DonatorsOnly = CreateConVar("sm_jetpack_donators_only", "0", "Whether only dontaors can change their jetpack bling"); RegConsoleCmd("sm_bling", Command_Bling, "Change jetpack bling."); g_Cookie_SelectedJetpack = RegClientCookie("selected_jetpack", "Selected jetpack type", CookieAccess_Private); - g_DonatorLibraryExists = LibraryExists("donator.core"); } public APLRes:AskPluginLoad2(Handle:myself, bool:late, String:error[], err_max) @@ -73,30 +64,6 @@ public APLRes:AskPluginLoad2(Handle:myself, bool:late, String:error[], err_max) return APLRes_Success; } -public OnAllPluginsLoaded() -{ - if (g_DonatorLibraryExists) - { - Donator_RegisterMenuItem("Jetpack Effects", JetpackBlingMenu); - } -} - -public OnLibraryRemoved(const String:name[]) -{ - if (StrEqual(name, "donator.core")) - { - g_DonatorLibraryExists = false; - } -} - -public OnLibraryAdded(const String:name[]) -{ - if (StrEqual(name, "donator.core")) - { - g_DonatorLibraryExists = true; - } -} - public OnClientCookiesCached(client) { new String:buffer[11]; @@ -174,12 +141,6 @@ KvGetJetpack(Handle:kv, &index) public Action:Command_Bling(client, args) { - if(!DonatorCheck(client)) - { - ReplyToCommand(client, "\x04%t", "donators_only"); - return Plugin_Handled; - } - if(client) { ChangeJetpackMenu(client); @@ -231,15 +192,6 @@ ClearJetpackEffects(client) DeleteParticle(g_JetpackParticle[client]); } -//True if client can use a donator action. If donations are not enabled this -//will always be true, otherwise check if client is a donator. -public bool:DonatorCheck(client) -{ - if(!g_DonatorLibraryExists || !GetConVarBool(g_Cvar_DonatorsOnly)) - return true; - else - return IsPlayerDonator(client); -} //Menus public DonatorMenu:JetpackBlingMenu(client) ChangeJetpackMenu(client); ChangeJetpackMenu(client) diff --git a/addons/sourcemod/scripting/jetpack_plus.sp b/addons/sourcemod/scripting/jetpack_plus.sp index 9fb144d..fee86cf 100644 --- a/addons/sourcemod/scripting/jetpack_plus.sp +++ b/addons/sourcemod/scripting/jetpack_plus.sp @@ -16,7 +16,7 @@ #include #include -#define PLUGIN_VERSION "1.2.3" +#define PLUGIN_VERSION "1.10.0" #define PLUGIN_NAME "Jetpack Plus" #define JETPACK_TAG "jetpack" @@ -30,7 +30,7 @@ public Plugin:myinfo = author = "CrimsonTautology", description = "Let client's fly around by holding jump.", version = PLUGIN_VERSION, - url = "https://github.com/CrimsonTautology/sm_jetpack_plus" + url = "https://github.com/CrimsonTautology/sm-jetpack-plus" };