commit 0ed16688c0f92a45cbe6f7e0c2745716401b091f Author: Dmitry Novikov Date: Thu Jun 20 20:31:44 2024 +0700 Initial commit diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..27e3ede --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +# Manual: +# http://EditorConfig.org + +# top-most EditorConfig file +root = true + +# 1 tab = 4 spaces indentation and with a newline ending every file +[*] +indent_style = tab +indent_size = 4 +trim_trailing_whitespace = true +insert_final_newline = true diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..ceec833 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,37 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +# Sources +*.c text eol=crlf diff=c +*.cc text eol=crlf diff=cpp +*.cxx text eol=crlf diff=cpp +*.cpp text eol=crlf diff=cpp +*.c++ text eol=crlf diff=cpp +*.hpp text eol=crlf diff=cpp +*.h text eol=crlf diff=c +*.h++ text eol=crlf diff=cpp +*.hh text eol=crlf diff=cpp + +# Compiled Object files +*.o binary +*.a binary +*.obj binary +*.lib binary +*.jar binary + +# Project files +*.sln text eol=crlf +*.vcxproj text eol=crlf +*.vcxproj.filters text eol=crlf + +# Scripts +*.sh text eol=lf + +# Resources files +*.bmp binary +*.ico binary +*.png binary +*.wav binary +*.tga binary diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..8be8c72 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,147 @@ +name: C/C++ CI + +on: + push: + paths-ignore: + - '**.md' + + pull_request: + types: [opened, reopened, synchronize] + release: + types: [published] + +jobs: + windows: + name: 'Windows' + runs-on: windows-2019 + + env: + solution: 'msvc/reunion.sln' + buildPlatform: 'Win32' + buildRelease: 'Release' + + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Setup MSBuild + uses: microsoft/setup-msbuild@v1.1.3 + with: + vs-version: '16.8' + + - name: Build + run: | + msbuild ${{ env.solution }} -p:Configuration="${{ env.buildRelease }}" /t:Clean,Build /p:Platform=${{ env.buildPlatform }} /p:PlatformToolset=v140_xp /p:XPDeprecationWarning=false + + - name: Move files + run: | + mkdir publish\bin\Windows + move msvc\${{ env.buildRelease }}\reunion_mm.dll publish\bin\Windows\reunion_mm.dll + + - name: Deploy artifacts + uses: actions/upload-artifact@v3.1.1 + with: + name: win32 + path: publish/* + + linux: + name: 'Linux' + runs-on: ubuntu-latest + container: s1lentq/linux86buildtools:latest + outputs: + app-version: ${{ steps.app-version.outputs.version }} + + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Build using Intel C++ Compiler 19.0 + run: | + rm -rf build && CC=icc CXX=icpc cmake -B build && cmake --build build -j8 + + - name: Reading appversion.h + id: app-version + run: | + if [ -e "reunion/version/appversion.h" ]; then + APP_VERSION=$(cat "reunion/version/appversion.h" | grep -wi '#define APP_VERSION_STRD' | sed -e 's/#define APP_VERSION_STRD[ \t\r\n\v\f]\+\(.*\)/\1/i' -e 's/\r//g') + if [ $? -ne 0 ]; then + APP_VERSION="" + else + # Remove quotes + APP_VERSION=$(echo $APP_VERSION | xargs) + fi + fi + echo "version=${APP_VERSION}" >> "$GITHUB_OUTPUT" + shell: bash + + - name: Move files + run: | + mkdir -p publish/bin/Linux + rsync -a reunion/dist/ publish/ --exclude=*.tpl + rsync -a reunion/src/reunion_api.h publish/public/ + rsync -a reunion/extra/ publish/amxx/ + mv build/reunion/reunion_mm_i386.so publish/bin/Linux/reunion_mm_i386.so + + - name: Run GLIBC/ABI version compat test + run: | + binaries=( + "publish/bin/Linux/reunion_mm_i386.so" + ) + bash ./reunion/version/glibc_test.sh ${binaries[@]} + if [[ $? -ne 0 ]]; then + exit 1 # Assertion failed + fi + shell: bash + + - name: Deploy artifacts + uses: actions/upload-artifact@v3.1.1 + id: upload-job + with: + name: linux32 + path: publish/* + + publish: + name: 'Publish' + runs-on: ubuntu-latest + needs: [windows, linux] + + steps: + - name: Deploying linux artifacts + uses: actions/download-artifact@v3 + with: + name: linux32 + + - name: Deploying windows artifacts + uses: actions/download-artifact@v3 + with: + name: win32 + + - name: Packaging + id: packaging-job + run: | + 7z a -tzip reunion-${{ needs.linux.outputs.app-version }}.zip . + + - name: Publish artifacts + uses: actions/upload-artifact@v3.1.1 + with: + name: reunion-${{ needs.linux.outputs.app-version }} + path: | + *.zip + + - name: Release artifacts + uses: softprops/action-gh-release@v1 + id: publish-job + if: | + github.event_name == 'release' && + github.event.action == 'published' && + startsWith(github.ref, 'refs/tags/') && + steps.packaging-job.outcome == 'success' + with: + files: | + *.zip + env: + GITHUB_TOKEN: ${{ secrets.API_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c84ee20 --- /dev/null +++ b/.gitignore @@ -0,0 +1,31 @@ +**/build +**/publish +**/workspace +*.iml +*.bat +*.aps +*.hint +*.tlog +*.log +*.lnk +*.pdb +**/.vscode/** +**/msvc/bin* +**/msvc/obj* +**/msvc/Debug* +**/msvc/Release* +**/msvc/.vs +**/msvc/*.db +**/msvc/*.opendb +**/msvc/*.sdf +**/msvc/*.opensdf +**/msvc/*.user +**/msvc/*.suo +**/msvc/*.db +**/msvc/*.opendb +**/msvc/ipch +**/PublishPath*.ini + +publish +**/appversion.h +**/reunion/dist/Readme.txt diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..97ab9c6 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,12 @@ +cmake_minimum_required(VERSION 3.1) +project(reunion CXX) + +if (WIN32) + message(FATAL_ERROR "CMakeLists.txt Windows platform isn't supported yet. Use msvc/Reunion.sln instead it!") +endif() + +add_custom_target(appversion DEPENDS + COMMAND "${PROJECT_SOURCE_DIR}/reunion/version/appversion.sh" "${PROJECT_SOURCE_DIR}" +) + +add_subdirectory(reunion) 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/README.md b/README.md new file mode 100644 index 0000000..5c6c517 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# Reunion +Metamod plugin that allows protocol 47 and 48 no-steam clients to join the ReHLDS server diff --git a/build.sh b/build.sh new file mode 100644 index 0000000..5f474d9 --- /dev/null +++ b/build.sh @@ -0,0 +1,60 @@ +#!/bin/bash + +main() +{ + CC=gcc + CXX=g++ + + if [[ "$*" =~ "--help" ]]; then + help + exit 0; + fi + + n=0 + args=() + for i in "$@" + do + case $i in + -j=*|--jobs=*) + jobs="-j${i#*=}" + shift + ;; + -c=*|--compiler=*) + C="${i#*=}" + shift + ;; + *) + args[$n]="$i" + ((++n)) + ;; + esac + done + + case "$C" in + ("intel"|"icc") CC=icc CXX=icpc ;; + ("gcc"|"g++") CC=gcc CXX=g++ ;; + ("clang"|"llvm") CC=clang CXX=clang++ ;; + *) + ;; + esac + + rm -rf build + mkdir build + pushd build &> /dev/null + CC=$CC CXX=$CXX cmake ${args[@]} .. + make ${jobs} + popd > /dev/null +} + +help() +{ + printf "Usage: ./build.sh \n\n" + printf " -c= | --compiler= - Select preferred C/C++ compiler to build\n" + printf " -j= | --jobs= - Specifies the number of jobs (commands) to run simultaneously (For faster building)\n\n" +} + +# Initialize +main $* + +# Exit normally +exit 0 diff --git a/dep/metamod/dllapi.h b/dep/metamod/dllapi.h new file mode 100644 index 0000000..ebc6fc0 --- /dev/null +++ b/dep/metamod/dllapi.h @@ -0,0 +1,35 @@ +#pragma once + +#include + +#ifndef DLLEXPORT + #ifdef _WIN32 + #define DLLEXPORT __declspec(dllexport) + // WINAPI should be provided in the windows compiler headers. + // It's usually defined to something like "__stdcall". + #else + #define DLLEXPORT __attribute__((visibility("default"))) + #define WINAPI /**/ + #endif // _WIN32 +#endif // DLLEXPORT + +#ifndef C_DLLEXPORT +#define C_DLLEXPORT extern "C" DLLEXPORT +#endif + +typedef void (*FN_GAMEINIT)(); + +// Typedefs for these are provided in SDK engine/eiface.h, but I didn't +// like the names (APIFUNCTION, APIFUNCTION2, NEW_DLL_FUNCTIONS_FN). +typedef int (*GETENTITYAPI_FN)(DLL_FUNCTIONS* pFunctionTable, int interfaceVersion); +typedef int (*GETENTITYAPI2_FN)(DLL_FUNCTIONS* pFunctionTable, int* interfaceVersion); +typedef int (*GETNEWDLLFUNCTIONS_FN)(NEW_DLL_FUNCTIONS* pFunctionTable, int* interfaceVersion); + +C_DLLEXPORT int GetEntityAPI(DLL_FUNCTIONS* pFunctionTable, int interfaceVersion); +C_DLLEXPORT int GetEntityAPI2(DLL_FUNCTIONS* pFunctionTable, int* interfaceVersion); +C_DLLEXPORT int GetNewDLLFunctions(NEW_DLL_FUNCTIONS* pNewFunctionTable, int* interfaceVersion); + +#ifdef METAMOD_CORE +void compile_gamedll_callbacks(); +void disable_clientcommand_fwd(); +#endif diff --git a/dep/metamod/engine_api.h b/dep/metamod/engine_api.h new file mode 100644 index 0000000..234fe57 --- /dev/null +++ b/dep/metamod/engine_api.h @@ -0,0 +1,20 @@ +#pragma once + +struct enginefuncs_s; + +// Plugin's GetEngineFunctions, called by metamod. +typedef int (*GET_ENGINE_FUNCTIONS_FN)(enginefuncs_s* pengfuncsFromEngine, int* interfaceVersion); + +// According to SDK engine/eiface.h: +// ONLY ADD NEW FUNCTIONS TO THE END OF THIS STRUCT. INTERFACE VERSION IS FROZEN AT 138 +#define ENGINE_INTERFACE_VERSION 138 + +// Protect against other projects which use this include file but use the +// normal enginefuncs_t type for their meta_engfuncs. +#ifdef METAMOD_CORE +extern enginefuncs_t g_meta_engfuncs; + +void compile_engine_callbacks(); +#else + extern enginefuncs_t meta_engfuncs; +#endif diff --git a/dep/metamod/enginecallbacks.h b/dep/metamod/enginecallbacks.h new file mode 100644 index 0000000..db1536a --- /dev/null +++ b/dep/metamod/enginecallbacks.h @@ -0,0 +1,24 @@ +#pragma once + +// This file is a wrapper around the SDK's enginecallback.h file. We need +// this because we use a different type for the global object g_engfuncs, +// which is still compatible with the enginefuncs_t that the SDK +// uses. +// This is only done for files that belong to Metamod, not other projects +// like plugins that use this file, or others that include it, too. +// Since we don't have a clean seperation of include files right now we +// "hack" our way around that by using a flag METAMOD_CORE which is set +// when compiling Metamod proper. + +#include // ALERT, etc + +// Also, create some additional macros for engine callback functions, which +// weren't in SDK dlls/enginecallbacks.h but probably should have been. +#define GET_INFOKEYBUFFER (*g_engfuncs.pfnGetInfoKeyBuffer) +#define INFOKEY_VALUE (*g_engfuncs.pfnInfoKeyValue) +#define SET_CLIENT_KEYVALUE (*g_engfuncs.pfnSetClientKeyValue) +#define REG_SVR_COMMAND (*g_engfuncs.pfnAddServerCommand) +#define SERVER_PRINT (*g_engfuncs.pfnServerPrint) +#define SET_SERVER_KEYVALUE (*g_engfuncs.pfnSetKeyValue) +#define QUERY_CLIENT_CVAR_VALUE (*g_engfuncs.pfnQueryClientCvarValue) +#define QUERY_CLIENT_CVAR_VALUE2 (*g_engfuncs.pfnQueryClientCvarValue2) diff --git a/dep/metamod/h_export.h b/dep/metamod/h_export.h new file mode 100644 index 0000000..9f95777 --- /dev/null +++ b/dep/metamod/h_export.h @@ -0,0 +1,5 @@ +#pragma once + +// Our GiveFnptrsToDll, called by engine. +typedef void (WINAPI *GIVE_ENGINE_FUNCTIONS_FN)(enginefuncs_t* pengfuncsFromEngine, globalvars_t* pGlobals); +C_DLLEXPORT void WINAPI GiveFnptrsToDll(enginefuncs_t* pengfuncsFromEngine, globalvars_t* pGlobals); diff --git a/dep/metamod/meta_api.h b/dep/metamod/meta_api.h new file mode 100644 index 0000000..8d94813 --- /dev/null +++ b/dep/metamod/meta_api.h @@ -0,0 +1,189 @@ +#pragma once + +#include "dllapi.h" // GETENTITYAPI_FN, etc +#include "engine_api.h" // GET_ENGINE_FUNCTIONS_FN, etc +#include "enginecallbacks.h" +#include "h_export.h" +#include "plinfo.h" // plugin_info_t, etc +#include "mutil.h" + +// Version consists of "major:minor", two separate integer numbers. +// Version 1 original +// Version 2 added plugin_info_t **pinfo +// Version 3 init split into query and attach, added detach +// Version 4 added (PLUG_LOADTIME now) to attach +// Version 5 changed mm ifvers int* to string, moved pl ifvers to info +// Version 5:1 added link support for entity "adminmod_timer" (adminmod) +// Version 5:2 added gamedll_funcs to meta_attach() [v1.0-rc2] +// Version 5:3 added mutil_funcs to meta_query() [v1.05] +// Version 5:4 added centersay utility functions [v1.06] +// Version 5:5 added Meta_Init to plugin API [v1.08] +// Version 5:6 added CallGameEntity utility function [v1.09] +// Version 5:7 added GetUserMsgID, GetUserMsgName util funcs [v1.11] +// Version 5:8 added GetPluginPath [v1.11] +// Version 5:9 added GetGameInfo [v1.14] +// Version 5:10 added GINFO_REALDLL_FULLPATH for GetGameInfo [v1.17] +// Version 5:11 added plugin loading and unloading API [v1.18] +// Version 5:12 added IS_QUERYING_CLIENT_CVAR to mutils [v1.18] +// Version 5:13 added MAKE_REQUESTID and GET_HOOK_TABLES to mutils [v1.19] +#define META_INTERFACE_VERSION "5:13" + +// Flags returned by a plugin's api function. +// NOTE: order is crucial, as greater/less comparisons are made. +enum META_RES +{ + MRES_UNSET = 0, + MRES_IGNORED, // plugin didn't take any action + MRES_HANDLED, // plugin did something, but real function should still be called + MRES_OVERRIDE, // call real function, but use my return value + MRES_SUPERCEDE, // skip real function; use my return value +}; + +// Variables provided to plugins. +struct meta_globals_t +{ + META_RES mres; // writable; plugin's return flag + META_RES prev_mres; // readable; return flag of the previous plugin called + META_RES status; // readable; "highest" return flag so far + void *orig_ret; // readable; return value from "real" function + void *override_ret; // readable; return value from overriding/superceding plugin + +#ifdef METAMOD_CORE + uint32* esp_save; +#endif +}; + +extern meta_globals_t *gpMetaGlobals; +#define SET_META_RESULT(result) gpMetaGlobals->mres = result + +#define RETURN_META(result) \ + do { gpMetaGlobals->mres = result; return; } while (0) + +#define RETURN_META_VALUE(result, value) \ + do { gpMetaGlobals->mres = result; return value; } while (0) + +#define META_RESULT_STATUS gpMetaGlobals->status +#define META_RESULT_PREVIOUS gpMetaGlobals->prev_mres +#define META_RESULT_ORIG_RET(type) *(type *)gpMetaGlobals->orig_ret +#define META_RESULT_OVERRIDE_RET(type) *(type *)gpMetaGlobals->override_ret + +// Table of getapi functions, retrieved from each plugin. +struct META_FUNCTIONS +{ + GETENTITYAPI_FN pfnGetEntityAPI; + GETENTITYAPI_FN pfnGetEntityAPI_Post; + GETENTITYAPI2_FN pfnGetEntityAPI2; + GETENTITYAPI2_FN pfnGetEntityAPI2_Post; + GETNEWDLLFUNCTIONS_FN pfnGetNewDLLFunctions; + GETNEWDLLFUNCTIONS_FN pfnGetNewDLLFunctions_Post; + GET_ENGINE_FUNCTIONS_FN pfnGetEngineFunctions; + GET_ENGINE_FUNCTIONS_FN pfnGetEngineFunctions_Post; +}; + +// Pair of function tables provided by game DLL. +struct gamedll_funcs_t +{ + DLL_FUNCTIONS *dllapi_table; + NEW_DLL_FUNCTIONS *newapi_table; +}; + +// Declared in plugin; referenced in macros. +extern gamedll_funcs_t *gpGamedllFuncs; +extern mutil_funcs_t *gpMetaUtilFuncs; + +// Tell the dll that we'll be loading it as a metamod plugin, in case it +// needs to do something special prior to the standard query/attach +// procedure. In particular, this will allow for DLL's that can be used as +// both standalone DLL's and metamod plugins. (optional; not required in +// plugin) +C_DLLEXPORT void Meta_Init(); +typedef void (*META_INIT_FN)(); + +// Get info about plugin, compare meta_interface versions, provide meta +// utility callback functions. +C_DLLEXPORT int Meta_Query(char *interfaceVersion, plugin_info_t **plinfo, mutil_funcs_t *pMetaUtilFuncs); +typedef int (*META_QUERY_FN) (char *interfaceVersion, plugin_info_t **plinfo, mutil_funcs_t *pMetaUtilFuncs); + +// Attach the plugin to the API; get the table of getapi functions; give +// meta_globals and gamedll_funcs. +C_DLLEXPORT int Meta_Attach(PLUG_LOADTIME now, META_FUNCTIONS *pFunctionTable, meta_globals_t *pMGlobals, gamedll_funcs_t *pGamedllFuncs); +typedef int (*META_ATTACH_FN) (PLUG_LOADTIME now, META_FUNCTIONS *pFunctionTable, meta_globals_t *pMGlobals, gamedll_funcs_t *pGamedllFuncs); + +// Detach the plugin; tell why and when. +C_DLLEXPORT int Meta_Detach(PLUG_LOADTIME now, PL_UNLOAD_REASON reason); +typedef int (*META_DETACH_FN) (PLUG_LOADTIME now, PL_UNLOAD_REASON reason); + +// Standard HL SDK interface function prototypes. +C_DLLEXPORT int GetEntityAPI_Post(DLL_FUNCTIONS *pFunctionTable, int interfaceVersion ); +C_DLLEXPORT int GetEntityAPI2_Post(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion ); + +// Additional SDK-like interface function prototypes. +C_DLLEXPORT int GetNewDLLFunctions_Post(NEW_DLL_FUNCTIONS *pNewFunctionTable, int *interfaceVersion ); +C_DLLEXPORT int GetEngineFunctions(enginefuncs_t *pengfuncsFromEngine, int *interfaceVersion); +C_DLLEXPORT int GetEngineFunctions_Post(enginefuncs_t *pengfuncsFromEngine, int *interfaceVersion); + +// Convenience macros for accessing GameDLL functions. Note: these talk +// _directly_ to the gamedll, and are not multiplexed through Metamod to +// the other plugins. + +// DLL API functions: +#define MDLL_FUNC gpGamedllFuncs->dllapi_table + +#define MDLL_GameDLLInit MDLL_FUNC->pfnGameInit +#define MDLL_Spawn MDLL_FUNC->pfnSpawn +#define MDLL_Think MDLL_FUNC->pfnThink +#define MDLL_Use MDLL_FUNC->pfnUse +#define MDLL_Touch MDLL_FUNC->pfnTouch +#define MDLL_Blocked MDLL_FUNC->pfnBlocked +#define MDLL_KeyValue MDLL_FUNC->pfnKeyValue +#define MDLL_Save MDLL_FUNC->pfnSave +#define MDLL_Restore MDLL_FUNC->pfnRestore +#define MDLL_ObjectCollsionBox MDLL_FUNC->pfnAbsBox +#define MDLL_SaveWriteFields MDLL_FUNC->pfnSaveWriteFields +#define MDLL_SaveReadFields MDLL_FUNC->pfnSaveReadFields +#define MDLL_SaveGlobalState MDLL_FUNC->pfnSaveGlobalState +#define MDLL_RestoreGlobalState MDLL_FUNC->pfnRestoreGlobalState +#define MDLL_ResetGlobalState MDLL_FUNC->pfnResetGlobalState +#define MDLL_ClientConnect MDLL_FUNC->pfnClientConnect +#define MDLL_ClientDisconnect MDLL_FUNC->pfnClientDisconnect +#define MDLL_ClientKill MDLL_FUNC->pfnClientKill +#define MDLL_ClientPutInServer MDLL_FUNC->pfnClientPutInServer +#define MDLL_ClientCommand MDLL_FUNC->pfnClientCommand +#define MDLL_ClientUserInfoChanged MDLL_FUNC->pfnClientUserInfoChanged +#define MDLL_ServerActivate MDLL_FUNC->pfnServerActivate +#define MDLL_ServerDeactivate MDLL_FUNC->pfnServerDeactivate +#define MDLL_PlayerPreThink MDLL_FUNC->pfnPlayerPreThink +#define MDLL_PlayerPostThink MDLL_FUNC->pfnPlayerPostThink +#define MDLL_StartFrame MDLL_FUNC->pfnStartFrame +#define MDLL_ParmsNewLevel MDLL_FUNC->pfnParmsNewLevel +#define MDLL_ParmsChangeLevel MDLL_FUNC->pfnParmsChangeLevel +#define MDLL_GetGameDescription MDLL_FUNC->pfnGetGameDescription +#define MDLL_PlayerCustomization MDLL_FUNC->pfnPlayerCustomization +#define MDLL_SpectatorConnect MDLL_FUNC->pfnSpectatorConnect +#define MDLL_SpectatorDisconnect MDLL_FUNC->pfnSpectatorDisconnect +#define MDLL_SpectatorThink MDLL_FUNC->pfnSpectatorThink +#define MDLL_Sys_Error MDLL_FUNC->pfnSys_Error +#define MDLL_PM_Move MDLL_FUNC->pfnPM_Move +#define MDLL_PM_Init MDLL_FUNC->pfnPM_Init +#define MDLL_PM_FindTextureType MDLL_FUNC->pfnPM_FindTextureType +#define MDLL_SetupVisibility MDLL_FUNC->pfnSetupVisibility +#define MDLL_UpdateClientData MDLL_FUNC->pfnUpdateClientData +#define MDLL_AddToFullPack MDLL_FUNC->pfnAddToFullPack +#define MDLL_CreateBaseline MDLL_FUNC->pfnCreateBaseline +#define MDLL_RegisterEncoders MDLL_FUNC->pfnRegisterEncoders +#define MDLL_GetWeaponData MDLL_FUNC->pfnGetWeaponData +#define MDLL_CmdStart MDLL_FUNC->pfnCmdStart +#define MDLL_CmdEnd MDLL_FUNC->pfnCmdEnd +#define MDLL_ConnectionlessPacket MDLL_FUNC->pfnConnectionlessPacket +#define MDLL_GetHullBounds MDLL_FUNC->pfnGetHullBounds +#define MDLL_CreateInstancedBaselines MDLL_FUNC->pfnCreateInstancedBaselines +#define MDLL_InconsistentFile MDLL_FUNC->pfnInconsistentFile +#define MDLL_AllowLagCompensation MDLL_FUNC->pfnAllowLagCompensation + +// NEW API functions: +#define MNEW_FUNC gpGamedllFuncs->newapi_table + +#define MNEW_OnFreeEntPrivateData MNEW_FUNC->pfnOnFreeEntPrivateData +#define MNEW_GameShutdown MNEW_FUNC->pfnGameShutdown +#define MNEW_ShouldCollide MNEW_FUNC->pfnShouldCollide +#define MNEW_CvarValue MNEW_FUNC->pfnCvarValue diff --git a/dep/metamod/mutil.h b/dep/metamod/mutil.h new file mode 100644 index 0000000..449c257 --- /dev/null +++ b/dep/metamod/mutil.h @@ -0,0 +1,80 @@ +#pragma once + +#include +#include "plinfo.h" + +// For GetGameInfo: +enum ginfo_t +{ + GINFO_NAME = 0, + GINFO_DESC, + GINFO_GAMEDIR, + GINFO_DLL_FULLPATH, + GINFO_DLL_FILENAME, + GINFO_REALDLL_FULLPATH, +}; + +// Meta Utility Function table type. +struct mutil_funcs_t +{ + void (*pfnLogConsole) (plid_t plid, const char *fmt, ...); + void (*pfnLogMessage) (plid_t plid, const char *fmt, ...); + void (*pfnLogError) (plid_t plid, const char *fmt, ...); + void (*pfnLogDeveloper) (plid_t plid, const char *fmt, ...); + void (*pfnCenterSay) (plid_t plid, const char *fmt, ...); + void (*pfnCenterSayParms) (plid_t plid, hudtextparms_t tparms, const char *fmt, ...); + void (*pfnCenterSayVarargs) (plid_t plid, hudtextparms_t tparms, const char *fmt, va_list ap); + qboolean (*pfnCallGameEntity) (plid_t plid, const char *entStr, entvars_t *pev); + int (*pfnGetUserMsgID) (plid_t plid, const char *msgname, int *size); + const char* (*pfnGetUserMsgName) (plid_t plid, int msgid, int *size); + const char* (*pfnGetPluginPath) (plid_t plid); + const char* (*pfnGetGameInfo) (plid_t plid, ginfo_t tag); + int (*pfnLoadPlugin) (plid_t plid, const char *cmdline, PLUG_LOADTIME now, void **plugin_handle); + int (*pfnUnloadPlugin) (plid_t plid, const char *cmdline, PLUG_LOADTIME now, PL_UNLOAD_REASON reason); + int (*pfnUnloadPluginByHandle)(plid_t plid, void *plugin_handle, PLUG_LOADTIME now, PL_UNLOAD_REASON reason); + const char* (*pfnIsQueryingClientCvar)(plid_t plid, const edict_t *pEdict); + int (*pfnMakeRequestId) (plid_t plid); + void (*pfnGetHookTables) (plid_t plid, enginefuncs_t **peng, DLL_FUNCTIONS **pdll, NEW_DLL_FUNCTIONS **pnewdll); +}; + +extern mutil_funcs_t g_MetaUtilFunctions; + +// Meta Utility Functions +void mutil_LogConsole(plid_t plid, const char *fmt, ...); +void mutil_LogMessage(plid_t plid, const char *fmt, ...); +void mutil_LogError(plid_t plid, const char *fmt, ...); +void mutil_LogDeveloper(plid_t plid, const char *fmt, ...); + +void mutil_CenterSay(plid_t plid, const char *fmt, ...); +void mutil_CenterSayParms(plid_t plid, hudtextparms_t tparms, const char *fmt, ...); +void mutil_CenterSayVarargs(plid_t plid, hudtextparms_t tparms, const char *fmt, va_list ap); + +qboolean mutil_CallGameEntity(plid_t plid, const char *entStr, entvars_t *pev); + +int mutil_GetUserMsgID(plid_t plid, const char *name, int *size); +const char *mutil_GetUserMsgName(plid_t plid, int msgid, int *size); +const char *mutil_GetPluginPath(plid_t plid); +const char *mutil_GetGameInfo(plid_t plid, ginfo_t tag); +const char *mutil_IsQueryingClientCvar(plid_t plid, const edict_t *pEdict); +int mutil_MakeRequestId(plid_t plid); +void mutil_GetHookTables(plid_t plid, enginefuncs_t **peng, DLL_FUNCTIONS **pdll, NEW_DLL_FUNCTIONS **pnewdll); + +// Convenience macros for MetaUtil functions +#define LOG_CONSOLE (*gpMetaUtilFuncs->pfnLogConsole) +#define LOG_MESSAGE (*gpMetaUtilFuncs->pfnLogMessage) +#define LOG_ERROR (*gpMetaUtilFuncs->pfnLogError) +#define LOG_DEVELOPER (*gpMetaUtilFuncs->pfnLogDeveloper) +#define CENTER_SAY (*gpMetaUtilFuncs->pfnCenterSay) +#define CENTER_SAY_PARMS (*gpMetaUtilFuncs->pfnCenterSayParms) +#define CENTER_SAY_VARARGS (*gpMetaUtilFuncs->pfnCenterSayVarargs) +#define CALL_GAME_ENTITY (*gpMetaUtilFuncs->pfnCallGameEntity) +#define GET_USER_MSG_ID (*gpMetaUtilFuncs->pfnGetUserMsgID) +#define GET_USER_MSG_NAME (*gpMetaUtilFuncs->pfnGetUserMsgName) +#define GET_PLUGIN_PATH (*gpMetaUtilFuncs->pfnGetPluginPath) +#define GET_GAME_INFO (*gpMetaUtilFuncs->pfnGetGameInfo) +#define LOAD_PLUGIN (*gpMetaUtilFuncs->pfnLoadPlugin) +#define UNLOAD_PLUGIN (*gpMetaUtilFuncs->pfnUnloadPlugin) +#define UNLOAD_PLUGIN_BY_HANDLE (*gpMetaUtilFuncs->pfnUnloadPluginByHandle) +#define IS_QUERYING_CLIENT_CVAR (*gpMetaUtilFuncs->pfnIsQueryingClientCvar) +#define MAKE_REQUESTID (*gpMetaUtilFuncs->pfnMakeRequestId) +#define GET_HOOK_TABLES (*gpMetaUtilFuncs->pfnGetHookTables) diff --git a/dep/metamod/plinfo.h b/dep/metamod/plinfo.h new file mode 100644 index 0000000..2fb30b0 --- /dev/null +++ b/dep/metamod/plinfo.h @@ -0,0 +1,48 @@ +#pragma once + +// Flags for plugin to indicate when it can be be loaded/unloaded. +// NOTE: order is crucial, as greater/less comparisons are made. +enum PLUG_LOADTIME +{ + PT_NEVER, + PT_STARTUP, // should only be loaded/unloaded at initial hlds execution + PT_CHANGELEVEL, // can be loaded/unloaded between maps + PT_ANYTIME, // can be loaded/unloaded at any time + PT_ANYPAUSE, // can be loaded/unloaded at any time, and can be "paused" during a map +}; + +// Flags to indicate why the plugin is being unloaded. +enum PL_UNLOAD_REASON +{ + PNL_NULL, + PNL_INI_DELETED, // was deleted from plugins.ini + PNL_FILE_NEWER, // file on disk is newer than last load + PNL_COMMAND, // requested by server/console command + PNL_CMD_FORCED, // forced by server/console command + PNL_DELAYED, // delayed from previous request; can't tell origin + + // only used for 'real_reason' on MPlugin::unload() + PNL_PLUGIN, // requested by plugin function call + PNL_PLG_FORCED, // forced by plugin function call + PNL_RELOAD, // forced unload by reload() +}; + +// Information plugin provides about itself. +struct plugin_info_t +{ + const char* ifvers; // meta_interface version + const char* name; // full name of plugin + const char* version; // version + const char* date; // date + const char* author; // author name/email + const char* url; // URL + const char* logtag; // log message prefix (unused right now) + PLUG_LOADTIME loadable; // when loadable + PLUG_LOADTIME unloadable; // when unloadable +}; + +extern plugin_info_t Plugin_info; + +// Plugin identifier, passed to all Meta Utility Functions. +typedef plugin_info_t *plid_t; +#define PLID &Plugin_info diff --git a/dep/rehlsdk/common/BaseSystemModule.cpp b/dep/rehlsdk/common/BaseSystemModule.cpp new file mode 100644 index 0000000..3233b54 --- /dev/null +++ b/dep/rehlsdk/common/BaseSystemModule.cpp @@ -0,0 +1,164 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +BaseSystemModule::BaseSystemModule() +{ + m_System = nullptr; + m_Serial = 0; + m_SystemTime = 0; + m_State = MODULE_UNDEFINED; + + Q_memset(m_Name, 0, sizeof(m_Name)); +} + +char *BaseSystemModule::GetName() +{ + return m_Name; +} + +char *BaseSystemModule::GetType() +{ + return "GenericModule"; +} + +char *BaseSystemModule::GetStatusLine() +{ + return "No status available.\n"; +} + +void BaseSystemModule::ExecuteCommand(int commandID, char *commandLine) +{ + m_System->DPrintf("WARNING! Undeclared ExecuteCommand().\n"); +} + +extern int COM_BuildNumber(); + +int BaseSystemModule::GetVersion() +{ + return COM_BuildNumber(); +} + +int BaseSystemModule::GetSerial() +{ + return m_Serial; +} + +IBaseSystem *BaseSystemModule::GetSystem() +{ + return m_System; +} + +bool BaseSystemModule::Init(IBaseSystem *system, int serial, char *name) +{ + if (!system) + return false; + + m_State = MODULE_INITIALIZING; + m_System = system; + m_Serial = serial; + m_SystemTime = 0; + + if (name) { + Q_strlcpy(m_Name, name); + } + + return true; +} + +void BaseSystemModule::RunFrame(double time) +{ + m_SystemTime = time; +} + +void BaseSystemModule::ShutDown() +{ + if (m_State == MODULE_DISCONNECTED) + return; + + m_Listener.Clear(); + m_State = MODULE_DISCONNECTED; + + if (!m_System->RemoveModule(this)) + { + m_System->DPrintf("ERROR! BaseSystemModule::ShutDown: faild to remove module %s.\n", m_Name); + } +} + +void BaseSystemModule::RegisterListener(ISystemModule *module) +{ + ISystemModule *listener = (ISystemModule *)m_Listener.GetFirst(); + while (listener) + { + if (listener->GetSerial() == module->GetSerial()) + { + m_System->DPrintf("WARNING! BaseSystemModule::RegisterListener: module %s already added.\n", module->GetName()); + return; + } + + listener = (ISystemModule *)m_Listener.GetNext(); + } + + m_Listener.Add(module); +} + +void BaseSystemModule::RemoveListener(ISystemModule *module) +{ + ISystemModule *listener = (ISystemModule *)m_Listener.GetFirst(); + while (listener) + { + if (listener->GetSerial() == module->GetSerial()) + { + m_Listener.Remove(module); + return; + } + + listener = (ISystemModule *)m_Listener.GetNext(); + } +} + +void BaseSystemModule::FireSignal(unsigned int signal, void *data) +{ + ISystemModule *listener = (ISystemModule *)m_Listener.GetFirst(); + while (listener) + { + listener->ReceiveSignal(this, signal, data); + listener = (ISystemModule *)m_Listener.GetNext(); + } +} + +void BaseSystemModule::ReceiveSignal(ISystemModule *module, unsigned int signal, void *data) +{ + m_System->DPrintf("WARNING! Unhandled signal (%i) from module %s.\n", signal, module->GetName()); +} + +int BaseSystemModule::GetState() +{ + return m_State; +} diff --git a/dep/rehlsdk/common/BaseSystemModule.h b/dep/rehlsdk/common/BaseSystemModule.h new file mode 100644 index 0000000..f4998b4 --- /dev/null +++ b/dep/rehlsdk/common/BaseSystemModule.h @@ -0,0 +1,75 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "ObjectList.h" +#include "IBaseSystem.h" + +// C4250 - 'class1' : inherits 'BaseSystemModule::member' via dominance +#pragma warning(disable:4250) + +class BaseSystemModule: virtual public ISystemModule { +public: + BaseSystemModule(); + virtual ~BaseSystemModule() {} + + EXT_FUNC virtual bool Init(IBaseSystem *system, int serial, char *name); + EXT_FUNC virtual void RunFrame(double time); + EXT_FUNC virtual void ReceiveSignal(ISystemModule *module, unsigned int signal, void *data); + EXT_FUNC virtual void ExecuteCommand(int commandID, char *commandLine); + EXT_FUNC virtual void RegisterListener(ISystemModule *module); + EXT_FUNC virtual void RemoveListener(ISystemModule *module); + EXT_FUNC virtual IBaseSystem *GetSystem(); + EXT_FUNC virtual int GetSerial(); + EXT_FUNC virtual char *GetStatusLine(); + EXT_FUNC virtual char *GetType(); + EXT_FUNC virtual char *GetName(); + + enum ModuleState { + MODULE_UNDEFINED = 0, + MODULE_INITIALIZING, + MODULE_CONNECTING, + MODULE_RUNNING, + MODULE_DISCONNECTED + }; + + EXT_FUNC virtual int GetState(); + EXT_FUNC virtual int GetVersion(); + EXT_FUNC virtual void ShutDown(); + EXT_FUNC virtual char *GetBaseDir() { return ""; } + void FireSignal(unsigned int signal, void *data = nullptr); + +protected: + IBaseSystem *m_System; + ObjectList m_Listener; + char m_Name[255]; + unsigned int m_State; + unsigned int m_Serial; + double m_SystemTime; +}; diff --git a/dep/rehlsdk/common/IAdminServer.h b/dep/rehlsdk/common/IAdminServer.h new file mode 100644 index 0000000..ab367ce --- /dev/null +++ b/dep/rehlsdk/common/IAdminServer.h @@ -0,0 +1,54 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "interface.h" + +// handle to a game window +typedef unsigned int ManageServerUIHandle_t; +class IManageServer; + +// Purpose: Interface to server administration functions +class IAdminServer: public IBaseInterface +{ +public: + // opens a manage server dialog for a local server + virtual ManageServerUIHandle_t OpenManageServerDialog(const char *serverName, const char *gameDir) = 0; + + // opens a manage server dialog to a remote server + virtual ManageServerUIHandle_t OpenManageServerDialog(unsigned int gameIP, unsigned int gamePort, const char *password) = 0; + + // forces the game info dialog closed + virtual void CloseManageServerDialog(ManageServerUIHandle_t gameDialog) = 0; + + // Gets a handle to the interface + virtual IManageServer *GetManageServerInterface(ManageServerUIHandle_t handle) = 0; +}; + +#define ADMINSERVER_INTERFACE_VERSION "AdminServer002" diff --git a/dep/rehlsdk/common/IBaseSystem.h b/dep/rehlsdk/common/IBaseSystem.h new file mode 100644 index 0000000..9f50fe3 --- /dev/null +++ b/dep/rehlsdk/common/IBaseSystem.h @@ -0,0 +1,91 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#if defined(_WIN32) + #define LIBRARY_PREFIX "dll" +#elif defined(OSX) + #define LIBRARY_PREFIX "dylib" +#else + #define LIBRARY_PREFIX "so" +#endif + +#include "ISystemModule.h" +#include "IVGuiModule.h" + +class Panel; +class ObjectList; +class IFileSystem; + +class IBaseSystem: virtual public ISystemModule { +public: + virtual ~IBaseSystem() {} + + virtual double GetTime() = 0; + virtual unsigned int GetTick() = 0; + virtual void SetFPS(float fps) = 0; + + virtual void Printf(char *fmt, ...) = 0; + virtual void DPrintf(char *fmt, ...) = 0; + + virtual void RedirectOutput(char *buffer = nullptr, int maxSize = 0) = 0; + + virtual IFileSystem *GetFileSystem() = 0; + virtual unsigned char *LoadFile(const char *name, int *length = nullptr) = 0; + virtual void FreeFile(unsigned char *fileHandle) = 0; + + virtual void SetTitle(char *text) = 0; + virtual void SetStatusLine(char *text) = 0; + + virtual void ShowConsole(bool visible) = 0; + virtual void LogConsole(char *filename) = 0; + + virtual bool InitVGUI(IVGuiModule *module) = 0; + +#ifdef _WIN32 + virtual Panel *GetPanel() = 0; +#endif // _WIN32 + + virtual bool RegisterCommand(char *name, ISystemModule *module, int commandID) = 0; + virtual void GetCommandMatches(char *string, ObjectList *pMatchList) = 0; + virtual void ExecuteString(char *commands) = 0; + virtual void ExecuteFile(char *filename) = 0; + virtual void Errorf(char *fmt, ...) = 0; + + virtual char *CheckParam(char *param) = 0; + + virtual bool AddModule(ISystemModule *module, char *name) = 0; + virtual ISystemModule *GetModule(char *interfacename, char *library, char *instancename = nullptr) = 0; + virtual bool RemoveModule(ISystemModule *module) = 0; + + virtual void Stop() = 0; + virtual char *GetBaseDir() = 0; +}; + +#define BASESYSTEM_INTERFACE_VERSION "basesystem002" diff --git a/dep/rehlsdk/common/IDemoPlayer.h b/dep/rehlsdk/common/IDemoPlayer.h new file mode 100644 index 0000000..2431b54 --- /dev/null +++ b/dep/rehlsdk/common/IDemoPlayer.h @@ -0,0 +1,93 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "ref_params.h" + +class IWorld; +class IProxy; +class DirectorCmd; +class IBaseSystem; +class ISystemModule; +class IObjectContainer; + +class IDemoPlayer { +public: + virtual ~IDemoPlayer() {} + + virtual bool Init(IBaseSystem *system, int serial, char *name) = 0; + virtual void RunFrame(double time) = 0; + virtual void ReceiveSignal(ISystemModule *module, unsigned int signal, void *data) = 0; + virtual void ExecuteCommand(int commandID, char *commandLine) = 0; + virtual void RegisterListener(ISystemModule *module) = 0; + virtual void RemoveListener(ISystemModule *module) = 0; + virtual IBaseSystem *GetSystem() = 0; + virtual int GetSerial() = 0; + virtual char *GetStatusLine() = 0; + virtual char *GetType() = 0; + virtual char *GetName() = 0; + virtual int GetState() = 0; + virtual int GetVersion() = 0; + virtual void ShutDown() = 0; + + virtual void NewGame(IWorld *world, IProxy *proxy = nullptr) = 0; + virtual char *GetModName() = 0; + virtual void WriteCommands(BitBuffer *stream, float startTime, float endTime) = 0; + virtual int AddCommand(DirectorCmd *cmd) = 0; + virtual bool RemoveCommand(int index) = 0; + virtual DirectorCmd *GetLastCommand() = 0; + virtual IObjectContainer *GetCommands() = 0; + virtual void SetWorldTime(double time, bool relative) = 0; + virtual void SetTimeScale(float scale) = 0; + virtual void SetPaused(bool state) = 0; + virtual void SetEditMode(bool state) = 0; + virtual void SetMasterMode(bool state) = 0; + virtual bool IsPaused() = 0; + virtual bool IsLoading() = 0; + virtual bool IsActive() = 0; + virtual bool IsEditMode() = 0; + virtual bool IsMasterMode() = 0; + virtual void RemoveFrames(double starttime, double endtime) = 0; + virtual void ExecuteDirectorCmd(DirectorCmd *cmd) = 0; + virtual double GetWorldTime() = 0; + virtual double GetStartTime() = 0; + virtual double GetEndTime() = 0; + virtual float GetTimeScale() = 0; + virtual IWorld *GetWorld() = 0; + virtual char *GetFileName() = 0; + virtual bool SaveGame(char *filename) = 0; + virtual bool LoadGame(char *filename) = 0; + virtual void Stop() = 0; + virtual void ForceHLTV(bool state) = 0; + virtual void GetDemoViewInfo(ref_params_t *rp, float *view, int *viewmodel) = 0; + virtual int ReadDemoMessage(unsigned char *buffer, int size) = 0; + virtual void ReadNetchanState(int *incoming_sequence, int *incoming_acknowledged, int *incoming_reliable_acknowledged, int *incoming_reliable_sequence, int *outgoing_sequence, int *reliable_sequence, int *last_reliable_sequence) = 0; +}; + +#define DEMOPLAYER_INTERFACE_VERSION "demoplayer001" diff --git a/dep/rehlsdk/common/IEngineWrapper.h b/dep/rehlsdk/common/IEngineWrapper.h new file mode 100644 index 0000000..0a58d4c --- /dev/null +++ b/dep/rehlsdk/common/IEngineWrapper.h @@ -0,0 +1,56 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "event_args.h" +#include "vmodes.h" +#include "cdll_int.h" + +class IBaseSystem; +class ISystemModule; + +class IEngineWrapper: virtual public ISystemModule { +public: + virtual ~IEngineWrapper() {} + + virtual bool GetViewOrigin(float *origin) = 0; + virtual bool GetViewAngles(float *angles) = 0; + virtual int GetTraceEntity() = 0; + virtual float GetCvarFloat(char *szName) = 0; + virtual char *GetCvarString(char *szName) = 0; + virtual void SetCvar(char *szName, char *szValue) = 0; + virtual void Cbuf_AddText(char *text) = 0; + virtual void DemoUpdateClientData(client_data_t *cdat) = 0; + virtual void CL_QueueEvent(int flags, int index, float delay, event_args_t *pargs) = 0; + virtual void HudWeaponAnim(int iAnim, int body) = 0; + virtual void CL_DemoPlaySound(int channel, char *sample, float attenuation, float volume, int flags, int pitch) = 0; + virtual void ClientDLL_ReadDemoBuffer(int size, unsigned char *buffer) = 0; +}; + +#define ENGINEWRAPPER_INTERFACE_VERSION "enginewrapper001" diff --git a/dep/rehlsdk/common/IGameServerData.h b/dep/rehlsdk/common/IGameServerData.h new file mode 100644 index 0000000..d431f00 --- /dev/null +++ b/dep/rehlsdk/common/IGameServerData.h @@ -0,0 +1,15 @@ +#pragma once + +#include "maintypes.h" +#include "interface.h" + +class IGameServerData : public IBaseInterface { +public: + virtual ~IGameServerData() { }; + + virtual void WriteDataRequest(const void *buffer, int bufferSize) = 0; + + virtual int ReadDataResponse(void *data, int len) = 0; +}; + +#define GAMESERVERDATA_INTERFACE_VERSION "GameServerData001" diff --git a/dep/rehlsdk/common/IObjectContainer.h b/dep/rehlsdk/common/IObjectContainer.h new file mode 100644 index 0000000..333e9d0 --- /dev/null +++ b/dep/rehlsdk/common/IObjectContainer.h @@ -0,0 +1,47 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class IObjectContainer { +public: + virtual ~IObjectContainer() {} + + virtual void Init() = 0; + + virtual bool Add(void *newObject) = 0; + virtual bool Remove(void *object) = 0; + virtual void Clear(bool freeElementsMemory) = 0; + + virtual void *GetFirst() = 0; + virtual void *GetNext() = 0; + + virtual int CountElements() = 0; + virtual bool Contains(void *object) = 0; + virtual bool IsEmpty() = 0; +}; diff --git a/dep/rehlsdk/common/ISystemModule.h b/dep/rehlsdk/common/ISystemModule.h new file mode 100644 index 0000000..9004a95 --- /dev/null +++ b/dep/rehlsdk/common/ISystemModule.h @@ -0,0 +1,57 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "interface.h" + +class IBaseSystem; +class ISystemModule; + +class ISystemModule: public IBaseInterface { +public: + virtual ~ISystemModule() {} + virtual bool Init(IBaseSystem *system, int serial, char *name) = 0; + + virtual void RunFrame(double time) = 0; + virtual void ReceiveSignal(ISystemModule *module, unsigned int signal, void *data = nullptr) = 0; + virtual void ExecuteCommand(int commandID, char *commandLine) = 0; + virtual void RegisterListener(ISystemModule *module) = 0; + virtual void RemoveListener(ISystemModule *module) = 0; + + virtual IBaseSystem *GetSystem() = 0; + + virtual int GetSerial() = 0; + virtual char *GetStatusLine() = 0; + virtual char *GetType() = 0; + virtual char *GetName() = 0; + + virtual int GetState() = 0; + virtual int GetVersion() = 0; + virtual void ShutDown() = 0; +}; diff --git a/dep/rehlsdk/common/IVGuiModule.h b/dep/rehlsdk/common/IVGuiModule.h new file mode 100644 index 0000000..e6864c8 --- /dev/null +++ b/dep/rehlsdk/common/IVGuiModule.h @@ -0,0 +1,76 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include +#include "interface.h" + +// Purpose: Standard interface to loading vgui modules +class IVGuiModule: public IBaseInterface +{ +public: + // called first to setup the module with the vgui + // returns true on success, false on failure + virtual bool Initialize(CreateInterfaceFn *vguiFactories, int factoryCount) = 0; + + // called after all the modules have been initialized + // modules should use this time to link to all the other module interfaces + virtual bool PostInitialize(CreateInterfaceFn *modules = nullptr, int factoryCount = 0) = 0; + + // called when the module is selected from the menu or otherwise activated + virtual bool Activate() = 0; + + // returns true if the module is successfully initialized and available + virtual bool IsValid() = 0; + + // requests that the UI is temporarily disabled and all data files saved + virtual void Deactivate() = 0; + + // restart from a Deactivate() + virtual void Reactivate() = 0; + + // called when the module is about to be shutdown + virtual void Shutdown() = 0; + + // returns a handle to the main module panel + virtual vgui2::VPANEL GetPanel() = 0; + + // sets the parent of the main module panel + virtual void SetParent(vgui2::VPANEL parent) = 0; + + // messages sent through through the panel returned by GetPanel(): + // + // "ConnectedToGame" "ip" "port" "gamedir" + // "DisconnectedFromGame" + // "ActiveGameName" "name" + // "LoadingStarted" "type" "name" + // "LoadingFinished" "type" "name" +}; + +#define VGUIMODULE_INTERFACE_VERSION "VGuiModuleAdminServer001" diff --git a/dep/rehlsdk/common/ObjectDictionary.cpp b/dep/rehlsdk/common/ObjectDictionary.cpp new file mode 100644 index 0000000..84a0f88 --- /dev/null +++ b/dep/rehlsdk/common/ObjectDictionary.cpp @@ -0,0 +1,515 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +ObjectDictionary::ObjectDictionary() +{ + m_currentEntry = 0; + m_findKey = 0; + m_entries = nullptr; + + Q_memset(m_cache, 0, sizeof(m_cache)); + + m_cacheIndex = 0; + m_size = 0; + m_maxSize = 0; +} + +ObjectDictionary::~ObjectDictionary() +{ + if (m_entries) { + Mem_Free(m_entries); + } +} + +void ObjectDictionary::Clear(bool freeObjectssMemory) +{ + if (freeObjectssMemory) + { + for (int i = 0; i < m_size; i++) + { + void *obj = m_entries[i].object; + if (obj) { + Mem_Free(obj); + } + } + } + + m_size = 0; + CheckSize(); + ClearCache(); +} + +bool ObjectDictionary::Add(void *object, float key) +{ + if (m_size == m_maxSize && !CheckSize()) + return false; + + entry_t *p; + if (m_size && key < m_entries[m_size - 1].key) + { + p = &m_entries[FindClosestAsIndex(key)]; + + entry_t *e1 = &m_entries[m_size]; + entry_t *e2 = &m_entries[m_size - 1]; + + while (p->key <= key) { p++; } + while (p != e1) + { + e1->object = e2->object; + e1->key = e2->key; + + e1--; + e2--; + } + } + else + p = &m_entries[m_size]; + + p->key = key; + p->object = object; + m_size++; + + ClearCache(); + AddToCache(p); + + return true; +} + +int ObjectDictionary::FindClosestAsIndex(float key) +{ + if (m_size <= 0) + return -1; + + if (key <= m_entries->key) + return 0; + + int index = FindKeyInCache(key); + if (index >= 0) { + return index; + } + + int middle; + int first = 0; + int last = m_size - 1; + float keyMiddle, keyNext; + + if (key < m_entries[last].key) + { + while (true) + { + middle = (last + first) >> 1; + keyMiddle = m_entries[middle].key; + + if (keyMiddle == key) + break; + + if (keyMiddle < key) + { + if (m_entries[middle + 1].key >= key) + { + if (m_entries[middle + 1].key - key < key - keyMiddle) + ++middle; + break; + } + + first = (last + first) >> 1; + } + else + { + last = (last + first) >> 1; + } + } + } + else + { + middle = last; + } + + keyNext = m_entries[middle - 1].key; + while (keyNext == key) { + keyNext = m_entries[middle--].key; + } + + AddToCache(&m_entries[middle], key); + return middle; +} + +void ObjectDictionary::ClearCache() +{ + Q_memset(m_cache, 0, sizeof(m_cache)); + m_cacheIndex = 0; +} + +bool ObjectDictionary::RemoveIndex(int index, bool freeObjectMemory) +{ + if (index < 0 || index >= m_size) + return false; + + entry_t *p = &m_entries[m_size - 1]; + entry_t *e1 = &m_entries[index]; + entry_t *e2 = &m_entries[index + 1]; + + if (freeObjectMemory && e1->object) + Mem_Free(e1->object); + + while (p != e1) + { + e1->object = e2->object; + e1->key = e2->key; + + e1++; + e2++; + } + + p->object = nullptr; + p->key = 0; + m_size--; + + CheckSize(); + ClearCache(); + + return false; +} + +bool ObjectDictionary::RemoveIndexRange(int minIndex, int maxIndex) +{ + if (minIndex > maxIndex) + { + if (maxIndex < 0) + maxIndex = 0; + + if (minIndex >= m_size) + minIndex = m_size - 1; + } + else + { + if (minIndex < 0) + minIndex = 0; + + if (maxIndex >= m_size) + maxIndex = m_size - 1; + } + + int offset = minIndex + maxIndex - 1; + m_size -= offset; + CheckSize(); + return true; +} + +bool ObjectDictionary::Remove(void *object) +{ + bool found = false; + for (int i = 0; i < m_size; i++) + { + if (m_entries[i].object == object) { + RemoveIndex(i); + found = true; + } + } + + return found ? true : false; +} + +bool ObjectDictionary::RemoveSingle(void *object) +{ + for (int i = 0; i < m_size; i++) + { + if (m_entries[i].object == object) { + RemoveIndex(i); + return true; + } + } + + return false; +} + +bool ObjectDictionary::RemoveKey(float key) +{ + int i = FindClosestAsIndex(key); + if (m_entries[i].key == key) + { + int j = i; + do { + ++j; + } + while (key == m_entries[j + 1].key); + + return RemoveIndexRange(i, j); + } + + return false; +} + +bool ObjectDictionary::CheckSize() +{ + int newSize = m_maxSize; + if (m_size == m_maxSize) + { + newSize = 1 - (int)(m_maxSize * -1.25f); + } + else if (m_maxSize * 0.5f > m_size) + { + newSize = (int)(m_maxSize * 0.75f); + } + + if (newSize != m_maxSize) + { + entry_t *newEntries = (entry_t *)Mem_Malloc(sizeof(entry_t) * newSize); + if (!newEntries) + return false; + + Q_memset(&newEntries[m_size], 0, sizeof(entry_t) * (newSize - m_size)); + + if (m_entries && m_size) + { + Q_memcpy(newEntries, m_entries, sizeof(entry_t) * m_size); + Mem_Free(m_entries); + } + + m_entries = newEntries; + m_maxSize = newSize; + } + + return true; +} + +void ObjectDictionary::Init() +{ + m_size = 0; + m_maxSize = 0; + m_entries = nullptr; + + CheckSize(); + ClearCache(); +} + +void ObjectDictionary::Init(int baseSize) +{ + m_size = 0; + m_maxSize = 0; + m_entries = (entry_t *)Mem_ZeroMalloc(sizeof(entry_t) * baseSize); + + if (m_entries) { + m_maxSize = baseSize; + } +} + +bool ObjectDictionary::Add(void *object) +{ + return Add(object, 0); +} + +int ObjectDictionary::CountElements() +{ + return m_size; +} + +bool ObjectDictionary::IsEmpty() +{ + return (m_size == 0) ? true : false; +} + +bool ObjectDictionary::Contains(void *object) +{ + if (FindObjectInCache(object) >= 0) + return true; + + for (int i = 0; i < m_size; i++) + { + entry_t *e = &m_entries[i]; + if (e->object == object) { + AddToCache(e); + return true; + } + } + + return false; +} + +void *ObjectDictionary::GetFirst() +{ + m_currentEntry = 0; + return GetNext(); +} + +void *ObjectDictionary::GetLast() +{ + return (m_size > 0) ? m_entries[m_size - 1].object : nullptr; +} + +bool ObjectDictionary::ChangeKey(void *object, float newKey) +{ + int pos = FindObjectInCache(object); + if (pos < 0) + { + for (pos = 0; pos < m_size; pos++) + { + if (m_entries[pos].object == object) { + AddToCache(&m_entries[pos]); + break; + } + } + + if (pos == m_size) { + return false; + } + } + + entry_t *p, *e; + + p = &m_entries[pos]; + if (p->key == newKey) + return false; + + int newpos = FindClosestAsIndex(newKey); + e = &m_entries[newpos]; + if (pos < newpos) + { + if (e->key > newKey) + e--; + + entry_t *e2 = &m_entries[pos + 1]; + while (p < e) + { + p->object = e2->object; + p->key = e2->key; + + p++; + e2++; + } + } + else if (pos > newpos) + { + if (e->key > newKey) + e++; + + entry_t *e2 = &m_entries[pos - 1]; + while (p > e) + { + p->object = e2->object; + p->key = e2->key; + + p--; + e2--; + } + } + + p->object = object; + p->key = newKey; + ClearCache(); + + return true; +} + +bool ObjectDictionary::UnsafeChangeKey(void *object, float newKey) +{ + int pos = FindObjectInCache(object); + if (pos < 0) + { + for (pos = 0; pos < m_size; pos++) + { + if (m_entries[pos].object == object) { + break; + } + } + + if (pos == m_size) { + return false; + } + } + + m_entries[pos].key = newKey; + ClearCache(); + return true; +} + +void ObjectDictionary::AddToCache(entry_t *entry) +{ + int i = (m_cacheIndex % MAX_OBJECT_CACHE); + + m_cache[i].object = entry; + m_cache[i].key = entry->key; + m_cacheIndex++; +} + +void ObjectDictionary::AddToCache(entry_t *entry, float key) +{ + int i = (m_cacheIndex % MAX_OBJECT_CACHE); + + m_cache[i].object = entry; + m_cache[i].key = key; + m_cacheIndex++; +} + +int ObjectDictionary::FindKeyInCache(float key) +{ + for (auto& ch : m_cache) + { + if (ch.object && ch.key == key) { + return (entry_t *)ch.object - m_entries; + } + } + + return -1; +} + +int ObjectDictionary::FindObjectInCache(void *object) +{ + for (auto& ch : m_cache) + { + if (ch.object && ch.object == object) { + return (entry_t *)ch.object - m_entries; + } + } + + return -1; +} + +void *ObjectDictionary::FindClosestKey(float key) +{ + m_currentEntry = FindClosestAsIndex(key); + return GetNext(); +} + +void *ObjectDictionary::GetNext() +{ + if (m_currentEntry < 0 || m_currentEntry >= m_size) + return nullptr; + + return m_entries[m_currentEntry++].object; +} + +void *ObjectDictionary::FindExactKey(float key) +{ + if ((m_currentEntry = FindClosestAsIndex(key)) < 0) + return nullptr; + + return (m_entries[m_currentEntry].key == key) ? GetNext() : nullptr; +} diff --git a/dep/rehlsdk/common/ObjectDictionary.h b/dep/rehlsdk/common/ObjectDictionary.h new file mode 100644 index 0000000..bf1b77f --- /dev/null +++ b/dep/rehlsdk/common/ObjectDictionary.h @@ -0,0 +1,94 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "IObjectContainer.h" + +class ObjectDictionary: public IObjectContainer { +public: + ObjectDictionary(); + virtual ~ObjectDictionary(); + + void Init(); + void Init(int baseSize); + + bool Add(void *object); + bool Contains(void *object); + bool IsEmpty(); + int CountElements(); + + void Clear(bool freeObjectssMemory = false); + + bool Add(void *object, float key); + bool ChangeKey(void *object, float newKey); + bool UnsafeChangeKey(void *object, float newKey); + + bool Remove(void *object); + bool RemoveSingle(void *object); + bool RemoveKey(float key); + bool RemoveRange(float startKey, float endKey); + + void *FindClosestKey(float key); + void *FindExactKey(float key); + + void *GetFirst(); + void *GetLast(); + void *GetNext(); + + int FindKeyInCache(float key); + int FindObjectInCache(void *object); + + void ClearCache(); + bool CheckSize(); + + typedef struct entry_s { + void *object; + float key; + } entry_t; + + void AddToCache(entry_t *entry); + void AddToCache(entry_t *entry, float key); + + bool RemoveIndex(int index, bool freeObjectMemory = false); + bool RemoveIndexRange(int minIndex, int maxIndex); + int FindClosestAsIndex(float key); + +protected: + int m_currentEntry; + float m_findKey; + + enum { MAX_OBJECT_CACHE = 32 }; + + entry_t *m_entries; + entry_t m_cache[MAX_OBJECT_CACHE]; + + int m_cacheIndex; + int m_size; + int m_maxSize; +}; diff --git a/dep/rehlsdk/common/ObjectList.cpp b/dep/rehlsdk/common/ObjectList.cpp new file mode 100644 index 0000000..4518090 --- /dev/null +++ b/dep/rehlsdk/common/ObjectList.cpp @@ -0,0 +1,259 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +ObjectList::ObjectList() +{ + m_head = m_tail = m_current = nullptr; + m_number = 0; +} + +ObjectList::~ObjectList() +{ + Clear(false); +} + +bool ObjectList::AddHead(void *newObject) +{ + // create new element + element_t *newElement = (element_t *)Mem_ZeroMalloc(sizeof(element_t)); + + // out of memory + if (!newElement) + return false; + + // insert element + newElement->object = newObject; + + if (m_head) + { + newElement->next = m_head; + m_head->prev = newElement; + } + + m_head = newElement; + + // if list was empty set new m_tail + if (!m_tail) + m_tail = m_head; + + m_number++; + return true; +} + +void *ObjectList::RemoveHead() +{ + void *retObj; + + // check m_head is present + if (m_head) + { + retObj = m_head->object; + element_t *newHead = m_head->next; + if (newHead) + newHead->prev = nullptr; + + // if only one element is in list also update m_tail + // if we remove this prev element + if (m_tail == m_head) + m_tail = nullptr; + + Mem_Free(m_head); + m_head = newHead; + + m_number--; + } + else + retObj = nullptr; + + return retObj; +} + +bool ObjectList::AddTail(void *newObject) +{ + // create new element + element_t *newElement = (element_t *)Mem_ZeroMalloc(sizeof(element_t)); + + // out of memory + if (!newElement) + return false; + + // insert element + newElement->object = newObject; + + if (m_tail) + { + newElement->prev = m_tail; + m_tail->next = newElement; + } + + m_tail = newElement; + + // if list was empty set new m_tail + if (!m_head) + m_head = m_tail; + + m_number++; + return true; +} + +void *ObjectList::RemoveTail() +{ + void *retObj; + + // check m_tail is present + if (m_tail) + { + retObj = m_tail->object; + element_t *newTail = m_tail->prev; + if (newTail) + newTail->next = nullptr; + + // if only one element is in list also update m_tail + // if we remove this prev element + if (m_head == m_tail) + m_head = nullptr; + + Mem_Free(m_tail); + m_tail = newTail; + + m_number--; + + } + else + retObj = nullptr; + + return retObj; +} + +bool ObjectList::IsEmpty() +{ + return (m_head == nullptr); +} + +int ObjectList::CountElements() +{ + return m_number; +} + +bool ObjectList::Contains(void *object) +{ + element_t *e = m_head; + + while (e && e->object != object) { e = e->next; } + + if (e) + { + m_current = e; + return true; + } + else + { + return false; + } +} + +void ObjectList::Clear(bool freeElementsMemory) +{ + element_t *ne; + element_t *e = m_head; + + while (e) + { + ne = e->next; + + if (freeElementsMemory && e->object) + Mem_Free(e->object); + + Mem_Free(e); + e = ne; + } + + m_head = m_tail = m_current = nullptr; + m_number = 0; +} + +bool ObjectList::Remove(void *object) +{ + element_t *e = m_head; + + while (e && e->object != object) { e = e->next; } + + if (e) + { + if (e->prev) e->prev->next = e->next; + if (e->next) e->next->prev = e->prev; + + if (m_head == e) m_head = e->next; + if (m_tail == e) m_tail = e->prev; + if (m_current == e) m_current= e->next; + + Mem_Free(e); + m_number--; + } + + return (e != nullptr); +} + +void ObjectList::Init() +{ + m_head = m_tail = m_current = nullptr; + m_number = 0; +} + +void *ObjectList::GetFirst() +{ + if (m_head) + { + m_current = m_head->next; + return m_head->object; + } + else + { + m_current = nullptr; + return nullptr; + } +} + +void *ObjectList::GetNext() +{ + void *retObj = nullptr; + if (m_current) + { + retObj = m_current->object; + m_current = m_current->next; + } + + return retObj; +} + +bool ObjectList::Add(void *newObject) +{ + return AddTail(newObject); +} diff --git a/dep/rehlsdk/common/ObjectList.h b/dep/rehlsdk/common/ObjectList.h new file mode 100644 index 0000000..aa023f8 --- /dev/null +++ b/dep/rehlsdk/common/ObjectList.h @@ -0,0 +1,65 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "IObjectContainer.h" + +class ObjectList: public IObjectContainer { +public: + EXT_FUNC void Init(); + EXT_FUNC bool Add(void *newObject); + EXT_FUNC void *GetFirst(); + EXT_FUNC void *GetNext(); + + ObjectList(); + virtual ~ObjectList(); + + EXT_FUNC void Clear(bool freeElementsMemory = false); + EXT_FUNC int CountElements(); + void *RemoveTail(); + void *RemoveHead(); + + bool AddTail(void *newObject); + bool AddHead(void *newObject); + EXT_FUNC bool Remove(void *object); + EXT_FUNC bool Contains(void *object); + EXT_FUNC bool IsEmpty(); + + typedef struct element_s { + struct element_s *prev; // pointer to the last element or NULL + struct element_s *next; // pointer to the next elemnet or NULL + void *object; // the element's object + } element_t; + +protected: + element_t *m_head; // first element in list + element_t *m_tail; // last element in list + element_t *m_current; // current element in list + int m_number; +}; diff --git a/dep/rehlsdk/common/Sequence.h b/dep/rehlsdk/common/Sequence.h new file mode 100644 index 0000000..8df553d --- /dev/null +++ b/dep/rehlsdk/common/Sequence.h @@ -0,0 +1,201 @@ +//--------------------------------------------------------------------------- +// +// S c r i p t e d S e q u e n c e s +// +//--------------------------------------------------------------------------- +#ifndef _INCLUDE_SEQUENCE_H_ +#define _INCLUDE_SEQUENCE_H_ + + +#ifndef _DEF_BYTE_ +typedef unsigned char byte; +#endif + +//--------------------------------------------------------------------------- +// client_textmessage_t +//--------------------------------------------------------------------------- +typedef struct client_textmessage_s +{ + int effect; + byte r1, g1, b1, a1; // 2 colors for effects + byte r2, g2, b2, a2; + float x; + float y; + float fadein; + float fadeout; + float holdtime; + float fxtime; + const char *pName; + const char *pMessage; +} client_textmessage_t; + + +//-------------------------------------------------------------------------- +// sequenceDefaultBits_e +// +// Enumerated list of possible modifiers for a command. This enumeration +// is used in a bitarray controlling what modifiers are specified for a command. +//--------------------------------------------------------------------------- +enum sequenceModifierBits +{ + SEQUENCE_MODIFIER_EFFECT_BIT = (1 << 1), + SEQUENCE_MODIFIER_POSITION_BIT = (1 << 2), + SEQUENCE_MODIFIER_COLOR_BIT = (1 << 3), + SEQUENCE_MODIFIER_COLOR2_BIT = (1 << 4), + SEQUENCE_MODIFIER_FADEIN_BIT = (1 << 5), + SEQUENCE_MODIFIER_FADEOUT_BIT = (1 << 6), + SEQUENCE_MODIFIER_HOLDTIME_BIT = (1 << 7), + SEQUENCE_MODIFIER_FXTIME_BIT = (1 << 8), + SEQUENCE_MODIFIER_SPEAKER_BIT = (1 << 9), + SEQUENCE_MODIFIER_LISTENER_BIT = (1 << 10), + SEQUENCE_MODIFIER_TEXTCHANNEL_BIT = (1 << 11), +}; +typedef enum sequenceModifierBits sequenceModifierBits_e ; + + +//--------------------------------------------------------------------------- +// sequenceCommandEnum_e +// +// Enumerated sequence command types. +//--------------------------------------------------------------------------- +enum sequenceCommandEnum_ +{ + SEQUENCE_COMMAND_ERROR = -1, + SEQUENCE_COMMAND_PAUSE = 0, + SEQUENCE_COMMAND_FIRETARGETS, + SEQUENCE_COMMAND_KILLTARGETS, + SEQUENCE_COMMAND_TEXT, + SEQUENCE_COMMAND_SOUND, + SEQUENCE_COMMAND_GOSUB, + SEQUENCE_COMMAND_SENTENCE, + SEQUENCE_COMMAND_REPEAT, + SEQUENCE_COMMAND_SETDEFAULTS, + SEQUENCE_COMMAND_MODIFIER, + SEQUENCE_COMMAND_POSTMODIFIER, + SEQUENCE_COMMAND_NOOP, + + SEQUENCE_MODIFIER_EFFECT, + SEQUENCE_MODIFIER_POSITION, + SEQUENCE_MODIFIER_COLOR, + SEQUENCE_MODIFIER_COLOR2, + SEQUENCE_MODIFIER_FADEIN, + SEQUENCE_MODIFIER_FADEOUT, + SEQUENCE_MODIFIER_HOLDTIME, + SEQUENCE_MODIFIER_FXTIME, + SEQUENCE_MODIFIER_SPEAKER, + SEQUENCE_MODIFIER_LISTENER, + SEQUENCE_MODIFIER_TEXTCHANNEL, +}; +typedef enum sequenceCommandEnum_ sequenceCommandEnum_e; + + +//--------------------------------------------------------------------------- +// sequenceCommandType_e +// +// Typeerated sequence command types. +//--------------------------------------------------------------------------- +enum sequenceCommandType_ +{ + SEQUENCE_TYPE_COMMAND, + SEQUENCE_TYPE_MODIFIER, +}; +typedef enum sequenceCommandType_ sequenceCommandType_e; + + +//--------------------------------------------------------------------------- +// sequenceCommandMapping_s +// +// A mapping of a command enumerated-value to its name. +//--------------------------------------------------------------------------- +typedef struct sequenceCommandMapping_ sequenceCommandMapping_s; +struct sequenceCommandMapping_ +{ + sequenceCommandEnum_e commandEnum; + const char* commandName; + sequenceCommandType_e commandType; +}; + + +//--------------------------------------------------------------------------- +// sequenceCommandLine_s +// +// Structure representing a single command (usually 1 line) from a +// .SEQ file entry. +//--------------------------------------------------------------------------- +typedef struct sequenceCommandLine_ sequenceCommandLine_s; +struct sequenceCommandLine_ +{ + int commandType; // Specifies the type of command + client_textmessage_t clientMessage; // Text HUD message struct + char* speakerName; // Targetname of speaking entity + char* listenerName; // Targetname of entity being spoken to + char* soundFileName; // Name of sound file to play + char* sentenceName; // Name of sentences.txt to play + char* fireTargetNames; // List of targetnames to fire + char* killTargetNames; // List of targetnames to remove + float delay; // Seconds 'till next command + int repeatCount; // If nonzero, reset execution pointer to top of block (N times, -1 = infinite) + int textChannel; // Display channel on which text message is sent + int modifierBitField; // Bit field to specify what clientmessage fields are valid + sequenceCommandLine_s* nextCommandLine; // Next command (linked list) +}; + + +//--------------------------------------------------------------------------- +// sequenceEntry_s +// +// Structure representing a single command (usually 1 line) from a +// .SEQ file entry. +//--------------------------------------------------------------------------- +typedef struct sequenceEntry_ sequenceEntry_s; +struct sequenceEntry_ +{ + char* fileName; // Name of sequence file without .SEQ extension + char* entryName; // Name of entry label in file + sequenceCommandLine_s* firstCommand; // Linked list of commands in entry + sequenceEntry_s* nextEntry; // Next loaded entry + qboolean isGlobal; // Is entry retained over level transitions? +}; + + + +//--------------------------------------------------------------------------- +// sentenceEntry_s +// Structure representing a single sentence of a group from a .SEQ +// file entry. Sentences are identical to entries in sentences.txt, but +// can be unique per level and are loaded/unloaded with the level. +//--------------------------------------------------------------------------- +typedef struct sentenceEntry_ sentenceEntry_s; +struct sentenceEntry_ +{ + char* data; // sentence data (ie "We have hostiles" ) + sentenceEntry_s* nextEntry; // Next loaded entry + qboolean isGlobal; // Is entry retained over level transitions? + unsigned int index; // this entry's position in the file. +}; + +//-------------------------------------------------------------------------- +// sentenceGroupEntry_s +// Structure representing a group of sentences found in a .SEQ file. +// A sentence group is defined by all sentences with the same name, ignoring +// the number at the end of the sentence name. Groups enable a sentence +// to be picked at random across a group. +//-------------------------------------------------------------------------- +typedef struct sentenceGroupEntry_ sentenceGroupEntry_s; +struct sentenceGroupEntry_ +{ + char* groupName; // name of the group (ie CT_ALERT ) + unsigned int numSentences; // number of sentences in group + sentenceEntry_s* firstSentence; // head of linked list of sentences in group + sentenceGroupEntry_s* nextEntry; // next loaded group +}; + +//--------------------------------------------------------------------------- +// Function declarations +//--------------------------------------------------------------------------- +sequenceEntry_s* SequenceGet( const char* fileName, const char* entryName ); +void Sequence_ParseFile( const char* fileName, qboolean isGlobal ); +void Sequence_OnLevelLoad( const char* mapName ); +sentenceEntry_s* SequencePickSentence( const char *groupName, int pickMethod, int *picked ); + +#endif // _INCLUDE_SEQUENCE_H_ diff --git a/dep/rehlsdk/common/SteamAppStartUp.cpp b/dep/rehlsdk/common/SteamAppStartUp.cpp new file mode 100644 index 0000000..7f13f4b --- /dev/null +++ b/dep/rehlsdk/common/SteamAppStartUp.cpp @@ -0,0 +1,211 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +#ifdef _WIN32 +#include "SteamAppStartup.h" + +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include +#include +#include + +#define STEAM_PARM "-steam" + +bool FileExists(const char *fileName) +{ + struct _stat statbuf; + return (_stat(fileName, &statbuf) == 0); +} + +// Handles launching the game indirectly via steam +void LaunchSelfViaSteam(const char *params) +{ + // calculate the details of our launch + char appPath[MAX_PATH]; + ::GetModuleFileName((HINSTANCE)GetModuleHandle(NULL), appPath, sizeof(appPath)); + + // strip out the exe name + char *slash = Q_strrchr(appPath, '\\'); + if (slash) + { + *slash = '\0'; + } + + // save out our details to the registry + HKEY hKey; + if (ERROR_SUCCESS == RegOpenKey(HKEY_CURRENT_USER, "Software\\Valve\\Steam", &hKey)) + { + DWORD dwType = REG_SZ; + DWORD dwSize = static_cast(Q_strlen(appPath) + 1); + RegSetValueEx(hKey, "TempAppPath", NULL, dwType, (LPBYTE)appPath, dwSize); + dwSize = static_cast(Q_strlen(params) + 1); + RegSetValueEx(hKey, "TempAppCmdLine", NULL, dwType, (LPBYTE)params, dwSize); + // clear out the appID (since we don't know it yet) + dwType = REG_DWORD; + int appID = -1; + RegSetValueEx(hKey, "TempAppID", NULL, dwType, (LPBYTE)&appID, sizeof(appID)); + RegCloseKey(hKey); + } + + // search for an active steam instance + HWND hwnd = ::FindWindow("Valve_SteamIPC_Class", "Hidden Window"); + if (hwnd) + { + ::PostMessage(hwnd, WM_USER + 3, 0, 0); + } + else + { + // couldn't find steam, find and launch it + + // first, search backwards through our current set of directories + char steamExe[MAX_PATH] = ""; + char dir[MAX_PATH]; + + if (::GetCurrentDirectoryA(sizeof(dir), dir)) + { + char *slash = Q_strrchr(dir, '\\'); + while (slash) + { + // see if steam_dev.exe is in the directory first + slash[1] = '\0'; + Q_strcat(slash, "steam_dev.exe"); + FILE *f = fopen(dir, "rb"); + if (f) + { + // found it + fclose(f); + Q_strcpy(steamExe, dir); + break; + } + + // see if steam.exe is in the directory + slash[1] = '\0'; + Q_strcat(slash, "steam.exe"); + f = fopen(dir, "rb"); + if (f) + { + // found it + fclose(f); + Q_strcpy(steamExe, dir); + break; + } + + // kill the string at the slash + slash[0] = '\0'; + + // move to the previous slash + slash = Q_strrchr(dir, '\\'); + } + } + + if (!steamExe[0]) + { + // still not found, use the one in the registry + HKEY hKey; + if (ERROR_SUCCESS == RegOpenKey(HKEY_CURRENT_USER, "Software\\Valve\\Steam", &hKey)) + { + DWORD dwType; + DWORD dwSize = sizeof(steamExe); + RegQueryValueEx(hKey, "SteamExe", NULL, &dwType, (LPBYTE)steamExe, &dwSize); + RegCloseKey(hKey); + } + } + + if (!steamExe[0]) + { + // still no path, error + ::MessageBox(NULL, "Error running game: could not find steam.exe to launch", "Fatal Error", MB_OK | MB_ICONERROR); + return; + } + + // fix any slashes + for (char *slash = steamExe; *slash; slash++) + { + if (*slash == '/') + { + *slash = '\\'; + } + } + + // change to the steam directory + Q_strcpy(dir, steamExe); + char *delimiter = Q_strrchr(dir, '\\'); + if (delimiter) + { + *delimiter = '\0'; + _chdir(dir); + } + + // exec steam.exe, in silent mode, with the launch app param + char *args[4] = { steamExe, "-silent", "-applaunch", '\0' }; + _spawnv(_P_NOWAIT, steamExe, args); + } +} + +// Launches steam if necessary +bool ShouldLaunchAppViaSteam(const char *lpCmdLine, const char *steamFilesystemDllName, const char *stdioFilesystemDllName) +{ + // see if steam is on the command line + const char *steamStr = Q_strstr(lpCmdLine, STEAM_PARM); + + // check the character following it is a whitespace or null + if (steamStr) + { + const char *postChar = steamStr + Q_strlen(STEAM_PARM); + if (*postChar == 0 || isspace(*postChar)) + { + // we're running under steam already, let the app continue + return false; + } + } + + // we're not running under steam, see which filesystems are available + if (FileExists(stdioFilesystemDllName)) + { + // we're being run with a stdio filesystem, so we can continue without steam + return false; + } + + // make sure we have a steam filesystem available + if (!FileExists(steamFilesystemDllName)) + { + return false; + } + + // we have the steam filesystem, and no stdio filesystem, so we must need to be run under steam + // launch steam + LaunchSelfViaSteam(lpCmdLine); + return true; +} + +#endif // _WIN32 diff --git a/dep/rehlsdk/common/SteamAppStartUp.h b/dep/rehlsdk/common/SteamAppStartUp.h new file mode 100644 index 0000000..2b9fbe7 --- /dev/null +++ b/dep/rehlsdk/common/SteamAppStartUp.h @@ -0,0 +1,37 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +// Call this first thing at startup +// Works out if the app is a steam app that is being ran outside of steam, +// and if so, launches steam and tells it to run us as a steam app +// +// if it returns true, then exit +// if it ruturns false, then continue with normal startup +bool ShouldLaunchAppViaSteam(const char *cmdLine, const char *steamFilesystemDllName, const char *stdioFilesystemDllName); diff --git a/dep/rehlsdk/common/SteamCommon.h b/dep/rehlsdk/common/SteamCommon.h new file mode 100644 index 0000000..c3fb1b0 --- /dev/null +++ b/dep/rehlsdk/common/SteamCommon.h @@ -0,0 +1,707 @@ + +//========= Copyright Valve Corporation, All rights reserved. ============// +/* +** The copyright to the contents herein is the property of Valve Corporation. +** The contents may be used and/or copied only with the written permission of +** Valve, or in accordance with the terms and conditions stipulated in +** the agreement/contract under which the contents have been supplied. +** +******************************************************************************* +** +** Contents: +** +** Common types used in the Steam DLL interface. +** +** This file is distributed to Steam application developers. +** +** +** +*******************************************************************************/ + +#ifndef INCLUDED_STEAM_COMMON_STEAMCOMMON_H +#define INCLUDED_STEAM_COMMON_STEAMCOMMON_H + +#if defined(_MSC_VER) && (_MSC_VER > 1000) +#pragma once +#endif + + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* Applications should not define STEAM_EXPORTS. */ + +#if defined ( _WIN32 ) + +#ifdef STEAM_EXPORTS +#define STEAM_API __declspec(dllexport) EXT_FUNC +#else +#define STEAM_API __declspec(dllimport) +#endif + +#define STEAM_CALL __cdecl + +#else + +#ifdef STEAM_EXPORTS +#define STEAM_API EXT_FUNC +#else +#define STEAM_API /* */ +#endif +#define STEAM_CALL /* */ + +#endif + +typedef void (STEAM_CALL *KeyValueIteratorCallback_t )(const char *Key, const char *Val, void *pvParam); + + +/****************************************************************************** +** +** Exported macros and constants +** +******************************************************************************/ + +/* DEPRECATED -- these are ignored now, all API access is granted on SteamStartup */ +#define STEAM_USING_FILESYSTEM (0x00000001) +#define STEAM_USING_LOGGING (0x00000002) +#define STEAM_USING_USERID (0x00000004) +#define STEAM_USING_ACCOUNT (0x00000008) +#define STEAM_USING_ALL (0x0000000f) +/* END DEPRECATED */ + +#define STEAM_MAX_PATH (255) +#define STEAM_QUESTION_MAXLEN (255) +#define STEAM_SALT_SIZE (8) +#define STEAM_PROGRESS_PERCENT_SCALE (0x00001000) + +/* These are maximum significant string lengths, excluding nul-terminator. */ +#define STEAM_CARD_NUMBER_SIZE (17) +#define STEAM_CARD_HOLDERNAME_SIZE (100) +#define STEAM_CARD_EXPYEAR_SIZE (4) +#define STEAM_CARD_EXPMONTH_SIZE (2) +#define STEAM_CARD_CVV2_SIZE (5) +#define STEAM_BILLING_ADDRESS1_SIZE (128) +#define STEAM_BILLING_ADDRESS2_SIZE (128) +#define STEAM_BILLING_CITY_SIZE (50) +#define STEAM_BILLING_ZIP_SIZE (16) +#define STEAM_BILLING_STATE_SIZE (32) +#define STEAM_BILLING_COUNTRY_SIZE (32) +#define STEAM_BILLING_PHONE_SIZE (20) +#define STEAM_BILLING_EMAIL_ADDRESS_SIZE (100) +#define STEAM_TYPE_OF_PROOF_OF_PURCHASE_SIZE (20) +#define STEAM_PROOF_OF_PURCHASE_TOKEN_SIZE (200) +#define STEAM_EXTERNAL_ACCOUNTNAME_SIZE (100) +#define STEAM_EXTERNAL_ACCOUNTPASSWORD_SIZE (80) +#define STEAM_BILLING_CONFIRMATION_CODE_SIZE (22) +#define STEAM_BILLING_CARD_APPROVAL_CODE_SIZE (100) +#define STEAM_BILLING_TRANS_DATE_SIZE (9) // mm/dd/yy +#define STEAM_BILLING_TRANS_TIME_SIZE (9) // hh:mm:ss + +/****************************************************************************** +** +** Scalar type and enumerated type definitions. +** +******************************************************************************/ + + +typedef unsigned int SteamHandle_t; + +typedef void * SteamUserIDTicketValidationHandle_t; + +typedef unsigned int SteamCallHandle_t; + +#if defined(_MSC_VER) +typedef unsigned __int64 SteamUnsigned64_t; +#else +typedef unsigned long long SteamUnsigned64_t; +#endif + +typedef enum +{ + eSteamSeekMethodSet = 0, + eSteamSeekMethodCur = 1, + eSteamSeekMethodEnd = 2 +} ESteamSeekMethod; + +typedef enum +{ + eSteamBufferMethodFBF = 0, + eSteamBufferMethodNBF = 1 +} ESteamBufferMethod; + +typedef enum +{ + eSteamErrorNone = 0, + eSteamErrorUnknown = 1, + eSteamErrorLibraryNotInitialized = 2, + eSteamErrorLibraryAlreadyInitialized = 3, + eSteamErrorConfig = 4, + eSteamErrorContentServerConnect = 5, + eSteamErrorBadHandle = 6, + eSteamErrorHandlesExhausted = 7, + eSteamErrorBadArg = 8, + eSteamErrorNotFound = 9, + eSteamErrorRead = 10, + eSteamErrorEOF = 11, + eSteamErrorSeek = 12, + eSteamErrorCannotWriteNonUserConfigFile = 13, + eSteamErrorCacheOpen = 14, + eSteamErrorCacheRead = 15, + eSteamErrorCacheCorrupted = 16, + eSteamErrorCacheWrite = 17, + eSteamErrorCacheSession = 18, + eSteamErrorCacheInternal = 19, + eSteamErrorCacheBadApp = 20, + eSteamErrorCacheVersion = 21, + eSteamErrorCacheBadFingerPrint = 22, + + eSteamErrorNotFinishedProcessing = 23, + eSteamErrorNothingToDo = 24, + eSteamErrorCorruptEncryptedUserIDTicket = 25, + eSteamErrorSocketLibraryNotInitialized = 26, + eSteamErrorFailedToConnectToUserIDTicketValidationServer = 27, + eSteamErrorBadProtocolVersion = 28, + eSteamErrorReplayedUserIDTicketFromClient = 29, + eSteamErrorReceiveResultBufferTooSmall = 30, + eSteamErrorSendFailed = 31, + eSteamErrorReceiveFailed = 32, + eSteamErrorReplayedReplyFromUserIDTicketValidationServer = 33, + eSteamErrorBadSignatureFromUserIDTicketValidationServer = 34, + eSteamErrorValidationStalledSoAborted = 35, + eSteamErrorInvalidUserIDTicket = 36, + eSteamErrorClientLoginRateTooHigh = 37, + eSteamErrorClientWasNeverValidated = 38, + eSteamErrorInternalSendBufferTooSmall = 39, + eSteamErrorInternalReceiveBufferTooSmall = 40, + eSteamErrorUserTicketExpired = 41, + eSteamErrorCDKeyAlreadyInUseOnAnotherClient = 42, + + eSteamErrorNotLoggedIn = 101, + eSteamErrorAlreadyExists = 102, + eSteamErrorAlreadySubscribed = 103, + eSteamErrorNotSubscribed = 104, + eSteamErrorAccessDenied = 105, + eSteamErrorFailedToCreateCacheFile = 106, + eSteamErrorCallStalledSoAborted = 107, + eSteamErrorEngineNotRunning = 108, + eSteamErrorEngineConnectionLost = 109, + eSteamErrorLoginFailed = 110, + eSteamErrorAccountPending = 111, + eSteamErrorCacheWasMissingRetry = 112, + eSteamErrorLocalTimeIncorrect = 113, + eSteamErrorCacheNeedsDecryption = 114, + eSteamErrorAccountDisabled = 115, + eSteamErrorCacheNeedsRepair = 116, + eSteamErrorRebootRequired = 117, + + eSteamErrorNetwork = 200, + eSteamErrorOffline = 201 + + +} ESteamError; + + +typedef enum +{ + eNoDetailedErrorAvailable, + eStandardCerrno, + eWin32LastError, + eWinSockLastError, + eDetailedPlatformErrorCount +} EDetailedPlatformErrorType; + +typedef enum /* Filter elements returned by SteamFind{First,Next} */ +{ + eSteamFindLocalOnly, /* limit search to local filesystem */ + eSteamFindRemoteOnly, /* limit search to remote repository */ + eSteamFindAll /* do not limit search (duplicates allowed) */ +} ESteamFindFilter; + + +/****************************************************************************** +** +** Exported structure and complex type definitions. +** +******************************************************************************/ + + +typedef struct +{ + ESteamError eSteamError; + EDetailedPlatformErrorType eDetailedErrorType; + int nDetailedErrorCode; + char szDesc[STEAM_MAX_PATH]; +} TSteamError; + + + +typedef struct +{ + int bIsDir; /* If non-zero, element is a directory; if zero, element is a file */ + unsigned int uSizeOrCount; /* If element is a file, this contains size of file in bytes */ + int bIsLocal; /* If non-zero, reported item is a standalone element on local filesystem */ + char cszName[STEAM_MAX_PATH]; /* Base element name (no path) */ + long lLastAccessTime; /* Seconds since 1/1/1970 (like time_t) when element was last accessed */ + long lLastModificationTime; /* Seconds since 1/1/1970 (like time_t) when element was last modified */ + long lCreationTime; /* Seconds since 1/1/1970 (like time_t) when element was created */ +} TSteamElemInfo; + + +typedef struct +{ + unsigned int uNumSubscriptions; + unsigned int uMaxNameChars; + unsigned int uMaxApps; + +} TSteamSubscriptionStats; + + +typedef struct +{ + unsigned int uNumApps; + unsigned int uMaxNameChars; + unsigned int uMaxInstallDirNameChars; + unsigned int uMaxVersionLabelChars; + unsigned int uMaxLaunchOptions; + unsigned int uMaxLaunchOptionDescChars; + unsigned int uMaxLaunchOptionCmdLineChars; + unsigned int uMaxNumIcons; + unsigned int uMaxIconSize; + unsigned int uMaxDependencies; + +} TSteamAppStats; + +typedef struct +{ + char *szLabel; + unsigned int uMaxLabelChars; + unsigned int uVersionId; + int bIsNotAvailable; +} TSteamAppVersion; + +typedef struct +{ + char *szDesc; + unsigned int uMaxDescChars; + char *szCmdLine; + unsigned int uMaxCmdLineChars; + unsigned int uIndex; + unsigned int uIconIndex; + int bNoDesktopShortcut; + int bNoStartMenuShortcut; + int bIsLongRunningUnattended; + +} TSteamAppLaunchOption; + + +typedef struct +{ + char *szName; + unsigned int uMaxNameChars; + char *szLatestVersionLabel; + unsigned int uMaxLatestVersionLabelChars; + char *szCurrentVersionLabel; + unsigned int uMaxCurrentVersionLabelChars; + char *szInstallDirName; + unsigned int uMaxInstallDirNameChars; + unsigned int uId; + unsigned int uLatestVersionId; + unsigned int uCurrentVersionId; + unsigned int uMinCacheFileSizeMB; + unsigned int uMaxCacheFileSizeMB; + unsigned int uNumLaunchOptions; + unsigned int uNumIcons; + unsigned int uNumVersions; + unsigned int uNumDependencies; + +} TSteamApp; + +typedef enum +{ + eNoCost = 0, + eBillOnceOnly = 1, + eBillMonthly = 2, + eProofOfPrepurchaseOnly = 3, + eGuestPass = 4, + eHardwarePromo = 5, + eNumBillingTypes, +} EBillingType; + +typedef struct +{ + char *szName; + unsigned int uMaxNameChars; + unsigned int *puAppIds; + unsigned int uMaxAppIds; + unsigned int uId; + unsigned int uNumApps; + EBillingType eBillingType; + unsigned int uCostInCents; + unsigned int uNumDiscounts; + int bIsPreorder; + int bRequiresShippingAddress; + unsigned int uDomesticShippingCostInCents; + unsigned int uInternationalShippingCostInCents; + bool bIsCyberCafeSubscription; + unsigned int uGameCode; + char szGameCodeDesc[STEAM_MAX_PATH]; + bool bIsDisabled; + bool bRequiresCD; + unsigned int uTerritoryCode; + bool bIsSteam3Subscription; + +} TSteamSubscription; + +typedef struct +{ + char szName[STEAM_MAX_PATH]; + unsigned int uDiscountInCents; + unsigned int uNumQualifiers; + +} TSteamSubscriptionDiscount; + +typedef struct +{ + char szName[STEAM_MAX_PATH]; + unsigned int uRequiredSubscription; + int bIsDisqualifier; + +} TSteamDiscountQualifier; + +typedef struct TSteamProgress +{ + int bValid; /* non-zero if call provides progress info */ + unsigned int uPercentDone; /* 0 to 100 * STEAM_PROGRESS_PERCENT_SCALE if bValid */ + char szProgress[STEAM_MAX_PATH]; /* additional progress info */ +} TSteamProgress; + +typedef enum +{ + eSteamNotifyTicketsWillExpire, + eSteamNotifyAccountInfoChanged, + eSteamNotifyContentDescriptionChanged, + eSteamNotifyPleaseShutdown, + eSteamNotifyNewContentServer, + eSteamNotifySubscriptionStatusChanged, + eSteamNotifyContentServerConnectionLost, + eSteamNotifyCacheLoadingCompleted, + eSteamNotifyCacheNeedsDecryption, + eSteamNotifyCacheNeedsRepair +} ESteamNotificationCallbackEvent; + + +typedef void(*SteamNotificationCallback_t)(ESteamNotificationCallbackEvent eEvent, unsigned int nData); + + +typedef char SteamPersonalQuestion_t[ STEAM_QUESTION_MAXLEN + 1 ]; + +typedef struct +{ + unsigned char uchSalt[STEAM_SALT_SIZE]; +} SteamSalt_t; + +typedef enum +{ + eVisa = 1, + eMaster = 2, + eAmericanExpress = 3, + eDiscover = 4, + eDinnersClub = 5, + eJCB = 6 +} ESteamPaymentCardType; + +typedef struct +{ + ESteamPaymentCardType eCardType; + char szCardNumber[ STEAM_CARD_NUMBER_SIZE +1 ]; + char szCardHolderName[ STEAM_CARD_HOLDERNAME_SIZE + 1]; + char szCardExpYear[ STEAM_CARD_EXPYEAR_SIZE + 1 ]; + char szCardExpMonth[ STEAM_CARD_EXPMONTH_SIZE+ 1 ]; + char szCardCVV2[ STEAM_CARD_CVV2_SIZE + 1 ]; + char szBillingAddress1[ STEAM_BILLING_ADDRESS1_SIZE + 1 ]; + char szBillingAddress2[ STEAM_BILLING_ADDRESS2_SIZE + 1 ]; + char szBillingCity[ STEAM_BILLING_CITY_SIZE + 1 ]; + char szBillingZip[ STEAM_BILLING_ZIP_SIZE + 1 ]; + char szBillingState[ STEAM_BILLING_STATE_SIZE + 1 ]; + char szBillingCountry[ STEAM_BILLING_COUNTRY_SIZE + 1 ]; + char szBillingPhone[ STEAM_BILLING_PHONE_SIZE + 1 ]; + char szBillingEmailAddress[ STEAM_BILLING_EMAIL_ADDRESS_SIZE + 1 ]; + unsigned int uExpectedCostInCents; + unsigned int uExpectedTaxInCents; + /* If the TSteamSubscription says that shipping info is required, */ + /* then the following fields must be filled out. */ + /* If szShippingName is empty, then assumes so are the rest. */ + char szShippingName[ STEAM_CARD_HOLDERNAME_SIZE + 1]; + char szShippingAddress1[ STEAM_BILLING_ADDRESS1_SIZE + 1 ]; + char szShippingAddress2[ STEAM_BILLING_ADDRESS2_SIZE + 1 ]; + char szShippingCity[ STEAM_BILLING_CITY_SIZE + 1 ]; + char szShippingZip[ STEAM_BILLING_ZIP_SIZE + 1 ]; + char szShippingState[ STEAM_BILLING_STATE_SIZE + 1 ]; + char szShippingCountry[ STEAM_BILLING_COUNTRY_SIZE + 1 ]; + char szShippingPhone[ STEAM_BILLING_PHONE_SIZE + 1 ]; + unsigned int uExpectedShippingCostInCents; + +} TSteamPaymentCardInfo; + +typedef struct +{ + char szTypeOfProofOfPurchase[ STEAM_TYPE_OF_PROOF_OF_PURCHASE_SIZE + 1 ]; + + /* A ProofOfPurchase token is not necessarily a nul-terminated string; it may be binary data + (perhaps encrypted). Hence we need a length and an array of bytes. */ + unsigned int uLengthOfBinaryProofOfPurchaseToken; + char cBinaryProofOfPurchaseToken[ STEAM_PROOF_OF_PURCHASE_TOKEN_SIZE + 1 ]; +} TSteamPrepurchaseInfo; + +typedef struct +{ + char szAccountName[ STEAM_EXTERNAL_ACCOUNTNAME_SIZE + 1 ]; + char szPassword[ STEAM_EXTERNAL_ACCOUNTPASSWORD_SIZE + 1 ]; +} TSteamExternalBillingInfo; + +typedef enum +{ + ePaymentCardInfo = 1, + ePrepurchasedInfo = 2, + eAccountBillingInfo = 3, + eExternalBillingInfo = 4, /* indirect billing via ISP etc (not supported yet) */ + ePaymentCardReceipt = 5, + ePrepurchaseReceipt = 6, + eEmptyReceipt = 7 +} ESteamSubscriptionBillingInfoType; + +typedef struct +{ + ESteamSubscriptionBillingInfoType eBillingInfoType; + union { + TSteamPaymentCardInfo PaymentCardInfo; + TSteamPrepurchaseInfo PrepurchaseInfo; + TSteamExternalBillingInfo ExternalBillingInfo; + char bUseAccountBillingInfo; + }; + +} TSteamSubscriptionBillingInfo; + +typedef enum +{ + /* Subscribed */ + eSteamSubscriptionOK = 0, /* Subscribed */ + eSteamSubscriptionPending = 1, /* Awaiting transaction completion */ + eSteamSubscriptionPreorder = 2, /* Is currently a pre-order */ + eSteamSubscriptionPrepurchaseTransferred = 3, /* hop to this account */ + /* Unusbscribed */ + eSteamSubscriptionPrepurchaseInvalid = 4, /* Invalid cd-key */ + eSteamSubscriptionPrepurchaseRejected = 5, /* hopped out / banned / etc */ + eSteamSubscriptionPrepurchaseRevoked = 6, /* hop away from this account */ + eSteamSubscriptionPaymentCardDeclined = 7, /* CC txn declined */ + eSteamSubscriptionCancelledByUser = 8, /* Cancelled by client */ + eSteamSubscriptionCancelledByVendor = 9, /* Cancelled by us */ + eSteamSubscriptionPaymentCardUseLimit = 10, /* Card used too many times, potential fraud */ + eSteamSubscriptionPaymentCardAlert = 11, /* Got a "pick up card" or the like from bank */ + eSteamSubscriptionFailed = 12, /* Other Error in subscription data or transaction failed/lost */ + eSteamSubscriptionPaymentCardAVSFailure = 13, /* Card failed Address Verification check */ + eSteamSubscriptionPaymentCardInsufficientFunds = 14, /* Card failed due to insufficient funds */ + eSteamSubscriptionRestrictedCountry = 15 /* The subscription is not available in the user's country */ + +} ESteamSubscriptionStatus; + +typedef struct +{ + ESteamPaymentCardType eCardType; + char szCardLastFourDigits[ 4 + 1 ]; + char szCardHolderName[ STEAM_CARD_HOLDERNAME_SIZE + 1]; + char szBillingAddress1[ STEAM_BILLING_ADDRESS1_SIZE + 1 ]; + char szBillingAddress2[ STEAM_BILLING_ADDRESS2_SIZE + 1 ]; + char szBillingCity[ STEAM_BILLING_CITY_SIZE + 1 ]; + char szBillingZip[ STEAM_BILLING_ZIP_SIZE + 1 ]; + char szBillingState[ STEAM_BILLING_STATE_SIZE + 1 ]; + char szBillingCountry[ STEAM_BILLING_COUNTRY_SIZE + 1 ]; + + // The following are only available after the subscription leaves "pending" status + char szCardApprovalCode[ STEAM_BILLING_CARD_APPROVAL_CODE_SIZE + 1]; + char szTransDate[ STEAM_BILLING_TRANS_DATE_SIZE + 1]; /* mm/dd/yy */ + char szTransTime[ STEAM_BILLING_TRANS_TIME_SIZE + 1]; /* hh:mm:ss */ + unsigned int uPriceWithoutTax; + unsigned int uTaxAmount; + unsigned int uShippingCost; + +} TSteamPaymentCardReceiptInfo; + +typedef struct +{ + char szTypeOfProofOfPurchase[ STEAM_TYPE_OF_PROOF_OF_PURCHASE_SIZE + 1 ]; +} TSteamPrepurchaseReceiptInfo; + +typedef struct +{ + ESteamSubscriptionStatus eStatus; + ESteamSubscriptionStatus ePreviousStatus; + ESteamSubscriptionBillingInfoType eReceiptInfoType; + char szConfirmationCode[ STEAM_BILLING_CONFIRMATION_CODE_SIZE + 1]; + union { + TSteamPaymentCardReceiptInfo PaymentCardReceiptInfo; + TSteamPrepurchaseReceiptInfo PrepurchaseReceiptInfo; + }; + +} TSteamSubscriptionReceipt; + +typedef enum +{ + ePhysicalBytesReceivedThisSession = 1, + eAppReadyToLaunchStatus = 2, + eAppPreloadStatus = 3, + eAppEntireDepot = 4, + eCacheBytesPresent = 5 +} ESteamAppUpdateStatsQueryType; + +typedef struct +{ + SteamUnsigned64_t uBytesTotal; + SteamUnsigned64_t uBytesPresent; +} TSteamUpdateStats; + +typedef enum +{ + eSteamUserAdministrator = 0x00000001, /* May subscribe, unsubscribe, etc */ + eSteamUserDeveloper = 0x00000002, /* Steam or App developer */ + eSteamUserCyberCafe = 0x00000004 /* CyberCafe, school, etc -- UI should ask for password */ + /* before allowing logout, unsubscribe, etc */ +} ESteamUserTypeFlags; + +typedef enum +{ + eSteamAccountStatusDefault = 0x00000000, + eSteamAccountStatusEmailVerified = 0x00000001, + /* Note: Mask value 0x2 is reserved for future use. (Some, but not all, public accounts already have this set.) */ + eSteamAccountDisabled = 0x00000004 +} ESteamAccountStatusBitFields ; + + +typedef enum +{ + eSteamBootstrapperError = -1, + eSteamBootstrapperDontCheckForUpdate = 0, + eSteamBootstrapperCheckForUpdateAndRerun = 7 + +} ESteamBootStrapperClientAppResult; + +typedef enum +{ + eSteamOnline = 0, + eSteamOffline = 1, + eSteamNoAuthMode = 2, + eSteamBillingOffline = 3 +} eSteamOfflineStatus; + +typedef struct +{ + int eOfflineNow; + int eOfflineNextSession; +} TSteamOfflineStatus; + +typedef struct +{ + unsigned int uAppId; + int bIsSystemDefined; + char szMountPath[STEAM_MAX_PATH]; +} TSteamAppDependencyInfo; + +typedef enum +{ + eSteamOpenFileRegular = 0x0, + eSteamOpenFileIgnoreLocal = 0x1, + eSteamOpenFileChecksumReads = 0x2 +} ESteamOpenFileFlags; + +typedef enum +{ + eSteamValveCDKeyValidationServer = 0, + eSteamHalfLifeMasterServer = 1, + eSteamFriendsServer = 2, + eSteamCSERServer = 3, + eSteamHalfLife2MasterServer = 4, + eSteamRDKFMasterServer = 5, + eMaxServerTypes = 6 +} ESteamServerType; + +/****************************************************************************** +** +** More exported constants +** +******************************************************************************/ + + +#ifdef __cplusplus + +const SteamHandle_t STEAM_INVALID_HANDLE = 0; +const SteamCallHandle_t STEAM_INVALID_CALL_HANDLE = 0; +const SteamUserIDTicketValidationHandle_t STEAM_INACTIVE_USERIDTICKET_VALIDATION_HANDLE = 0; +const unsigned int STEAM_USE_LATEST_VERSION = 0xFFFFFFFF; + +#else + +#define STEAM_INVALID_HANDLE ((SteamHandle_t)(0)) +#define STEAM_INVALID_CALL_HANDLE ((SteamCallHandle_t)(0)) +#define STEAM_INACTIVE_USERIDTICKET_VALIDATION_HANDLE ((SteamUserIDTicketValidationHandle_t)(0)) +#define STEAM_USE_LATEST_VERSION (0xFFFFFFFFu); + +#endif + + +/****************************************************************************** +** Each Steam instance (licensed Steam Service Provider) has a unique SteamInstanceID_t. +** +** Each Steam instance as its own DB of users. +** Each user in the DB has a unique SteamLocalUserID_t (a serial number, with possible +** rare gaps in the sequence). +** +******************************************************************************/ + +typedef unsigned short SteamInstanceID_t; // MUST be 16 bits + + +#if defined ( _WIN32 ) +typedef unsigned __int64 SteamLocalUserID_t; // MUST be 64 bits +#else +typedef unsigned long long SteamLocalUserID_t; // MUST be 64 bits +#endif + +/****************************************************************************** +** +** Applications need to be able to authenticate Steam users from ANY instance. +** So a SteamIDTicket contains SteamGlobalUserID, which is a unique combination of +** instance and user id. +** +** SteamLocalUserID is an unsigned 64-bit integer. +** For platforms without 64-bit int support, we provide access via a union that splits it into +** high and low unsigned 32-bit ints. Such platforms will only need to compare LocalUserIDs +** for equivalence anyway - not perform arithmetic with them. +** +********************************************************************************/ +typedef struct +{ + unsigned int Low32bits; + unsigned int High32bits; +} TSteamSplitLocalUserID; + +typedef struct +{ + SteamInstanceID_t m_SteamInstanceID; + + union + { + SteamLocalUserID_t As64bits; + TSteamSplitLocalUserID Split; + } m_SteamLocalUserID; + +} TSteamGlobalUserID; + + +#ifdef __cplusplus +} +#endif + + +#endif diff --git a/dep/rehlsdk/common/TextConsoleUnix.cpp b/dep/rehlsdk/common/TextConsoleUnix.cpp new file mode 100644 index 0000000..32671ae --- /dev/null +++ b/dep/rehlsdk/common/TextConsoleUnix.cpp @@ -0,0 +1,324 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +#if !defined(_WIN32) + +#include "TextConsoleUnix.h" +#include "icommandline.h" + +#include +#include +#include +#include +#include +#include +#include + +CTextConsoleUnix console; + +CTextConsoleUnix::~CTextConsoleUnix() +{ + CTextConsoleUnix::ShutDown(); +} + +bool CTextConsoleUnix::Init(IBaseSystem *system) +{ + static struct termios termNew; + sigset_t block_ttou; + + sigemptyset(&block_ttou); + sigaddset(&block_ttou, SIGTTOU); + sigprocmask(SIG_BLOCK, &block_ttou, NULL); + + tty = stdout; + + // this code is for echo-ing key presses to the connected tty + // (which is != STDOUT) + if (isatty(STDIN_FILENO)) + { + tty = fopen(ctermid(NULL), "w+"); + if (!tty) + { + printf("Unable to open tty(%s) for output\n", ctermid(NULL)); + tty = stdout; + } + else + { + // turn buffering off + setbuf(tty, NULL); + } + } + else + { + tty = fopen("/dev/null", "w+"); + if (!tty) + { + tty = stdout; + } + } + + tcgetattr(STDIN_FILENO, &termStored); + + Q_memcpy(&termNew, &termStored, sizeof(struct termios)); + + // Disable canonical mode, and set buffer size to 1 byte + termNew.c_lflag &= (~ICANON); + termNew.c_cc[ VMIN ] = 1; + termNew.c_cc[ VTIME ] = 0; + + // disable echo + termNew.c_lflag &= (~ECHO); + + tcsetattr(STDIN_FILENO, TCSANOW, &termNew); + sigprocmask(SIG_UNBLOCK, &block_ttou, NULL); + + return CTextConsole::Init(system); +} + +void CTextConsoleUnix::ShutDown() +{ + sigset_t block_ttou; + + sigemptyset(&block_ttou); + sigaddset(&block_ttou, SIGTTOU); + sigprocmask(SIG_BLOCK, &block_ttou, NULL); + tcsetattr(STDIN_FILENO, TCSANOW, &termStored); + sigprocmask(SIG_UNBLOCK, &block_ttou, NULL); + + CTextConsole::ShutDown(); +} + +// return 0 if the kb isn't hit +int CTextConsoleUnix::kbhit() +{ + fd_set rfds; + struct timeval tv; + + // Watch stdin (fd 0) to see when it has input. + FD_ZERO(&rfds); + FD_SET(STDIN_FILENO, &rfds); + + // Return immediately. + tv.tv_sec = 0; + tv.tv_usec = 0; + + // Must be in raw or cbreak mode for this to work correctly. + return select(STDIN_FILENO + 1, &rfds, NULL, NULL, &tv) != -1 && FD_ISSET(STDIN_FILENO, &rfds); +} + +char *CTextConsoleUnix::GetLine() +{ + // early return for 99.999% case :) + if (!kbhit()) + return NULL; + + escape_sequence_t es; + + es = ESCAPE_CLEAR; + sigset_t block_ttou; + + sigemptyset(&block_ttou); + sigaddset(&block_ttou, SIGTTOU); + sigaddset(&block_ttou, SIGTTIN); + sigprocmask(SIG_BLOCK, &block_ttou, NULL); + + while (true) + { + if (!kbhit()) + break; + + int nLen; + char ch = 0; + int numRead = read(STDIN_FILENO, &ch, 1); + if (!numRead) + break; + + switch (ch) + { + case '\n': // Enter + es = ESCAPE_CLEAR; + + nLen = ReceiveNewline(); + if (nLen) + { + sigprocmask(SIG_UNBLOCK, &block_ttou, NULL); + return m_szConsoleText; + } + break; + + case 127: // Backspace + case '\b': // Backspace + es = ESCAPE_CLEAR; + ReceiveBackspace(); + break; + + case '\t': // TAB + es = ESCAPE_CLEAR; + ReceiveTab(); + break; + + case 27: // Escape character + es = ESCAPE_RECEIVED; + break; + + case '[': // 2nd part of escape sequence + case 'O': + case 'o': + switch (es) + { + case ESCAPE_CLEAR: + case ESCAPE_BRACKET_RECEIVED: + es = ESCAPE_CLEAR; + ReceiveStandardChar(ch); + break; + + case ESCAPE_RECEIVED: + es = ESCAPE_BRACKET_RECEIVED; + break; + } + break; + case 'A': + if (es == ESCAPE_BRACKET_RECEIVED) + { + es = ESCAPE_CLEAR; + ReceiveUpArrow(); + } + else + { + es = ESCAPE_CLEAR; + ReceiveStandardChar(ch); + } + break; + case 'B': + if (es == ESCAPE_BRACKET_RECEIVED) + { + es = ESCAPE_CLEAR; + ReceiveDownArrow(); + } + else + { + es = ESCAPE_CLEAR; + ReceiveStandardChar(ch); + } + break; + case 'C': + if (es == ESCAPE_BRACKET_RECEIVED) + { + es = ESCAPE_CLEAR; + ReceiveRightArrow(); + } + else + { + es = ESCAPE_CLEAR; + ReceiveStandardChar(ch); + } + break; + case 'D': + if (es == ESCAPE_BRACKET_RECEIVED) + { + es = ESCAPE_CLEAR; + ReceiveLeftArrow(); + } + else + { + es = ESCAPE_CLEAR; + ReceiveStandardChar(ch); + } + break; + default: + // Just eat this char if it's an unsupported escape + if (es != ESCAPE_BRACKET_RECEIVED) + { + // dont' accept nonprintable chars + if ((ch >= ' ') && (ch <= '~')) + { + es = ESCAPE_CLEAR; + ReceiveStandardChar(ch); + } + } + break; + } + + fflush(stdout); + } + + sigprocmask(SIG_UNBLOCK, &block_ttou, NULL); + return NULL; +} + +void CTextConsoleUnix::PrintRaw(char *pszMsg, int nChars) +{ + if (nChars == 0) + { + printf("%s", pszMsg); + } + else + { + for (int nCount = 0; nCount < nChars; nCount++) + { + putchar(pszMsg[ nCount ]); + } + } +} + +void CTextConsoleUnix::Echo(char *pszMsg, int nChars) +{ + if (nChars == 0) + { + fputs(pszMsg, tty); + } + else + { + for (int nCount = 0; nCount < nChars; nCount++) + { + fputc(pszMsg[ nCount ], tty); + } + } +} + +int CTextConsoleUnix::GetWidth() +{ + struct winsize ws; + int nWidth = 0; + + if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0) + { + nWidth = (int)ws.ws_col; + } + + if (nWidth <= 1) + { + nWidth = 80; + } + + return nWidth; +} + +#endif // !defined(_WIN32) diff --git a/dep/rehlsdk/common/TextConsoleUnix.h b/dep/rehlsdk/common/TextConsoleUnix.h new file mode 100644 index 0000000..b40cbc4 --- /dev/null +++ b/dep/rehlsdk/common/TextConsoleUnix.h @@ -0,0 +1,59 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include +#include "textconsole.h" + +enum escape_sequence_t +{ + ESCAPE_CLEAR, + ESCAPE_RECEIVED, + ESCAPE_BRACKET_RECEIVED +}; + +class CTextConsoleUnix: public CTextConsole { +public: + virtual ~CTextConsoleUnix(); + + bool Init(IBaseSystem *system = nullptr); + void ShutDown(); + void PrintRaw(char *pszMsg, int nChars = 0); + void Echo(char *pszMsg, int nChars = 0); + char *GetLine(); + int GetWidth(); + +private: + int kbhit(); + + struct termios termStored; + FILE *tty; +}; + +extern CTextConsoleUnix console; diff --git a/dep/rehlsdk/common/TextConsoleWin32.cpp b/dep/rehlsdk/common/TextConsoleWin32.cpp new file mode 100644 index 0000000..aeaefb3 --- /dev/null +++ b/dep/rehlsdk/common/TextConsoleWin32.cpp @@ -0,0 +1,282 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +#if defined(_WIN32) + +CTextConsoleWin32 console; +#pragma comment(lib, "user32.lib") + +BOOL WINAPI ConsoleHandlerRoutine(DWORD CtrlType) +{ + // TODO ? + /*if (CtrlType != CTRL_C_EVENT && CtrlType != CTRL_BREAK_EVENT) + { + // don't quit on break or ctrl+c + m_System->Stop(); + }*/ + + return TRUE; +} + +// GetConsoleHwnd() helper function from MSDN Knowledge Base Article Q124103 +// needed, because HWND GetConsoleWindow(VOID) is not avaliable under Win95/98/ME +HWND GetConsoleHwnd() +{ + HWND hwndFound; // This is what is returned to the caller. + char pszNewWindowTitle[1024]; // Contains fabricated WindowTitle + char pszOldWindowTitle[1024]; // Contains original WindowTitle + + // Fetch current window title. + GetConsoleTitle(pszOldWindowTitle, sizeof(pszOldWindowTitle)); + + // Format a "unique" NewWindowTitle. + wsprintf(pszNewWindowTitle, "%d/%d", GetTickCount(), GetCurrentProcessId()); + + // Change current window title. + SetConsoleTitle(pszNewWindowTitle); + + // Ensure window title has been updated. + Sleep(40); + + // Look for NewWindowTitle. + hwndFound = FindWindow(nullptr, pszNewWindowTitle); + + // Restore original window title. + SetConsoleTitle(pszOldWindowTitle); + + return hwndFound; +} + +CTextConsoleWin32::~CTextConsoleWin32() +{ + CTextConsoleWin32::ShutDown(); +} + +bool CTextConsoleWin32::Init(IBaseSystem *system) +{ + if (!AllocConsole()) + m_System = system; + + SetTitle(m_System ? m_System->GetName() : "Console"); + + hinput = GetStdHandle(STD_INPUT_HANDLE); + houtput = GetStdHandle(STD_OUTPUT_HANDLE); + + if (!SetConsoleCtrlHandler(&ConsoleHandlerRoutine, TRUE)) { + Print("WARNING! TextConsole::Init: Could not attach console hook.\n"); + } + + Attrib = FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY; + SetWindowPos(GetConsoleHwnd(), HWND_TOP, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOREPOSITION | SWP_SHOWWINDOW); + + return CTextConsole::Init(system); +} + +void CTextConsoleWin32::ShutDown() +{ + FreeConsole(); + CTextConsole::ShutDown(); +} + +void CTextConsoleWin32::SetVisible(bool visible) +{ + ShowWindow(GetConsoleHwnd(), visible ? SW_SHOW : SW_HIDE); + m_ConsoleVisible = visible; +} + +char *CTextConsoleWin32::GetLine() +{ + while (true) + { + INPUT_RECORD recs[1024]; + unsigned long numread; + unsigned long numevents; + + if (!GetNumberOfConsoleInputEvents(hinput, &numevents)) + { + if (m_System) { + m_System->Errorf("CTextConsoleWin32::GetLine: !GetNumberOfConsoleInputEvents\n"); + } + + return nullptr; + } + + if (numevents <= 0) + break; + + if (!ReadConsoleInput(hinput, recs, ARRAYSIZE(recs), &numread)) + { + if (m_System) { + m_System->Errorf("CTextConsoleWin32::GetLine: !ReadConsoleInput\n"); + } + + return nullptr; + } + + if (numread == 0) + return nullptr; + + for (int i = 0; i < (int)numread; i++) + { + INPUT_RECORD *pRec = &recs[i]; + if (pRec->EventType != KEY_EVENT) + continue; + + if (pRec->Event.KeyEvent.bKeyDown) + { + // check for cursor keys + if (pRec->Event.KeyEvent.wVirtualKeyCode == VK_UP) + { + ReceiveUpArrow(); + } + else if (pRec->Event.KeyEvent.wVirtualKeyCode == VK_DOWN) + { + ReceiveDownArrow(); + } + else if (pRec->Event.KeyEvent.wVirtualKeyCode == VK_LEFT) + { + ReceiveLeftArrow(); + } + else if (pRec->Event.KeyEvent.wVirtualKeyCode == VK_RIGHT) + { + ReceiveRightArrow(); + } + else + { + int nLen; + char ch = pRec->Event.KeyEvent.uChar.AsciiChar; + switch (ch) + { + case '\r': // Enter + nLen = ReceiveNewline(); + if (nLen) + { + return m_szConsoleText; + } + break; + case '\b': // Backspace + ReceiveBackspace(); + break; + case '\t': // TAB + ReceiveTab(); + break; + default: + // dont' accept nonprintable chars + if ((ch >= ' ') && (ch <= '~')) + { + ReceiveStandardChar(ch); + } + break; + } + } + } + } + } + + return nullptr; +} + +void CTextConsoleWin32::PrintRaw(char *pszMsg, int nChars) +{ +#ifdef LAUNCHER_FIXES + char outputStr[2048]; + WCHAR unicodeStr[1024]; + + DWORD nSize = MultiByteToWideChar(CP_UTF8, 0, pszMsg, -1, NULL, 0); + if (nSize > sizeof(unicodeStr)) + return; + + MultiByteToWideChar(CP_UTF8, 0, pszMsg, -1, unicodeStr, nSize); + DWORD nLength = WideCharToMultiByte(CP_OEMCP, 0, unicodeStr, -1, 0, 0, NULL, NULL); + if (nLength > sizeof(outputStr)) + return; + + WideCharToMultiByte(CP_OEMCP, 0, unicodeStr, -1, outputStr, nLength, NULL, NULL); + WriteFile(houtput, outputStr, nChars ? nChars : Q_strlen(outputStr), NULL, NULL); +#else + WriteFile(houtput, pszMsg, nChars ? nChars : Q_strlen(pszMsg), NULL, NULL); +#endif +} + +void CTextConsoleWin32::Echo(char *pszMsg, int nChars) +{ + PrintRaw(pszMsg, nChars); +} + +int CTextConsoleWin32::GetWidth() +{ + CONSOLE_SCREEN_BUFFER_INFO csbi; + int nWidth = 0; + + if (GetConsoleScreenBufferInfo(houtput, &csbi)) { + nWidth = csbi.dwSize.X; + } + + if (nWidth <= 1) + nWidth = 80; + + return nWidth; +} + +void CTextConsoleWin32::SetStatusLine(char *pszStatus) +{ + Q_strncpy(statusline, pszStatus, sizeof(statusline) - 1); + statusline[sizeof(statusline) - 2] = '\0'; + UpdateStatus(); +} + +void CTextConsoleWin32::UpdateStatus() +{ + COORD coord; + DWORD dwWritten = 0; + WORD wAttrib[ 80 ]; + + for (int i = 0; i < 80; i++) + { + wAttrib[i] = Attrib; // FOREGROUND_GREEN | FOREGROUND_INTENSITY | BACKGROUND_INTENSITY; + } + + coord.X = coord.Y = 0; + + WriteConsoleOutputAttribute(houtput, wAttrib, 80, coord, &dwWritten); + WriteConsoleOutputCharacter(houtput, statusline, 80, coord, &dwWritten); +} + +void CTextConsoleWin32::SetTitle(char *pszTitle) +{ + SetConsoleTitle(pszTitle); +} + +void CTextConsoleWin32::SetColor(WORD attrib) +{ + Attrib = attrib; +} + +#endif // defined(_WIN32) diff --git a/dep/rehlsdk/common/TextConsoleWin32.h b/dep/rehlsdk/common/TextConsoleWin32.h new file mode 100644 index 0000000..656110e --- /dev/null +++ b/dep/rehlsdk/common/TextConsoleWin32.h @@ -0,0 +1,62 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers +#include +#include "TextConsole.h" + +class CTextConsoleWin32: public CTextConsole { +public: + virtual ~CTextConsoleWin32(); + + bool Init(IBaseSystem *system = nullptr); + void ShutDown(); + + void SetTitle(char *pszTitle); + void SetStatusLine(char *pszStatus); + void UpdateStatus(); + + void PrintRaw(char * pszMsz, int nChars = 0); + void Echo(char * pszMsz, int nChars = 0); + char *GetLine(); + int GetWidth(); + + void SetVisible(bool visible); + void SetColor(WORD); + +private: + HANDLE hinput; // standard input handle + HANDLE houtput; // standard output handle + WORD Attrib; // attrib colours for status bar + + char statusline[81]; // first line in console is status line +}; + +extern CTextConsoleWin32 console; diff --git a/dep/rehlsdk/common/TokenLine.cpp b/dep/rehlsdk/common/TokenLine.cpp new file mode 100644 index 0000000..7f88555 --- /dev/null +++ b/dep/rehlsdk/common/TokenLine.cpp @@ -0,0 +1,132 @@ +#include "precompiled.h" + +TokenLine::TokenLine() +{ + Q_memset(m_token, 0, sizeof(m_token)); + Q_memset(m_fullLine, 0, sizeof(m_fullLine)); + Q_memset(m_tokenBuffer, 0, sizeof(m_tokenBuffer)); + + m_tokenNumber = 0; +} + +TokenLine::TokenLine(char *string) +{ + SetLine(string); +} + +TokenLine::~TokenLine() +{ + +} + +bool TokenLine::SetLine(const char *newLine) +{ + m_tokenNumber = 0; + + if (!newLine || (Q_strlen(newLine) >= (MAX_LINE_CHARS - 1))) + { + Q_memset(m_fullLine, 0, sizeof(m_fullLine)); + Q_memset(m_tokenBuffer, 0, sizeof(m_tokenBuffer)); + return false; + } + + Q_strlcpy(m_fullLine, newLine); + Q_strlcpy(m_tokenBuffer, newLine); + + // parse tokens + char *charPointer = m_tokenBuffer; + while (*charPointer && (m_tokenNumber < MAX_LINE_TOKENS)) + { + // skip nonprintable chars + while (*charPointer && ((*charPointer <= ' ') || (*charPointer > '~'))) + charPointer++; + + if (*charPointer) + { + m_token[m_tokenNumber] = charPointer; + + // special treatment for quotes + if (*charPointer == '\"') + { + charPointer++; + m_token[m_tokenNumber] = charPointer; + while (*charPointer && (*charPointer != '\"')) + charPointer++; + } + else + { + m_token[m_tokenNumber] = charPointer; + while (*charPointer && ((*charPointer > 32) && (*charPointer <= 126))) + charPointer++; + } + + m_tokenNumber++; + + if (*charPointer) + { + *charPointer = '\0'; + charPointer++; + } + } + } + + return (m_tokenNumber != MAX_LINE_TOKENS); +} + +char *TokenLine::GetLine() +{ + return m_fullLine; +} + +char *TokenLine::GetToken(int i) +{ + if (i >= m_tokenNumber) + return NULL; + + return m_token[i]; +} + +// if the given parm is not present return NULL +// otherwise return the address of the following token, or an empty string +char *TokenLine::CheckToken(char *parm) +{ + for (int i = 0; i < m_tokenNumber; i++) + { + if (!m_token[i]) + continue; + + if (!Q_strcmp(parm, m_token[i])) + { + char *ret = m_token[i + 1]; + + // if this token doesn't exist, since index i was the last + // return an empty string + if (m_tokenNumber == (i + 1)) + ret = ""; + + return ret; + } + } + + return NULL; +} + +int TokenLine::CountToken() +{ + int c = 0; + for (int i = 0; i < m_tokenNumber; i++) + { + if (m_token[i]) + c++; + } + + return c; +} + +char *TokenLine::GetRestOfLine(int i) +{ + if (i >= m_tokenNumber) + return NULL; + + return m_fullLine + (m_token[i] - m_tokenBuffer); +} diff --git a/dep/rehlsdk/common/TokenLine.h b/dep/rehlsdk/common/TokenLine.h new file mode 100644 index 0000000..0d16fb6 --- /dev/null +++ b/dep/rehlsdk/common/TokenLine.h @@ -0,0 +1,51 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class TokenLine { +public: + TokenLine(); + TokenLine(char *string); + virtual ~TokenLine(); + + char *GetRestOfLine(int i); // returns all chars after token i + int CountToken(); // returns number of token + char *CheckToken(char *parm); // returns token after token parm or "" + char *GetToken(int i); // returns token i + char *GetLine(); // returns full line + bool SetLine(const char *newLine); // set new token line and parses it + +private: + enum { MAX_LINE_CHARS = 2048, MAX_LINE_TOKENS = 128 }; + + char m_tokenBuffer[MAX_LINE_CHARS]; + char m_fullLine[MAX_LINE_CHARS]; + char *m_token[MAX_LINE_TOKENS]; + int m_tokenNumber; +}; diff --git a/dep/rehlsdk/common/beamdef.h b/dep/rehlsdk/common/beamdef.h new file mode 100644 index 0000000..fd77a76 --- /dev/null +++ b/dep/rehlsdk/common/beamdef.h @@ -0,0 +1,62 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined ( BEAMDEFH ) +#define BEAMDEFH +#ifdef _WIN32 +#pragma once +#endif + +#define FBEAM_STARTENTITY 0x00000001 +#define FBEAM_ENDENTITY 0x00000002 +#define FBEAM_FADEIN 0x00000004 +#define FBEAM_FADEOUT 0x00000008 +#define FBEAM_SINENOISE 0x00000010 +#define FBEAM_SOLID 0x00000020 +#define FBEAM_SHADEIN 0x00000040 +#define FBEAM_SHADEOUT 0x00000080 +#define FBEAM_STARTVISIBLE 0x10000000 // Has this client actually seen this beam's start entity yet? +#define FBEAM_ENDVISIBLE 0x20000000 // Has this client actually seen this beam's end entity yet? +#define FBEAM_ISACTIVE 0x40000000 +#define FBEAM_FOREVER 0x80000000 + +typedef struct beam_s BEAM; +struct beam_s +{ + BEAM *next; + int type; + int flags; + vec3_t source; + vec3_t target; + vec3_t delta; + float t; // 0 .. 1 over lifetime of beam + float freq; + float die; + float width; + float amplitude; + float r, g, b; + float brightness; + float speed; + float frameRate; + float frame; + int segments; + int startEntity; + int endEntity; + int modelIndex; + int frameCount; + struct model_s *pFollowModel; + struct particle_s *particles; +}; + +#endif diff --git a/dep/rehlsdk/common/cl_entity.h b/dep/rehlsdk/common/cl_entity.h new file mode 100644 index 0000000..a7cd472 --- /dev/null +++ b/dep/rehlsdk/common/cl_entity.h @@ -0,0 +1,115 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// cl_entity.h +#if !defined( CL_ENTITYH ) +#define CL_ENTITYH +#ifdef _WIN32 +#pragma once +#endif + +typedef struct efrag_s +{ + struct mleaf_s *leaf; + struct efrag_s *leafnext; + struct cl_entity_s *entity; + struct efrag_s *entnext; +} efrag_t; + +typedef struct +{ + byte mouthopen; // 0 = mouth closed, 255 = mouth agape + byte sndcount; // counter for running average + int sndavg; // running average +} mouth_t; + +typedef struct +{ + float prevanimtime; + float sequencetime; + byte prevseqblending[2]; + vec3_t prevorigin; + vec3_t prevangles; + + int prevsequence; + float prevframe; + + byte prevcontroller[4]; + byte prevblending[2]; +} latchedvars_t; + +typedef struct +{ + // Time stamp for this movement + float animtime; + + vec3_t origin; + vec3_t angles; +} position_history_t; + +typedef struct cl_entity_s cl_entity_t; + +#define HISTORY_MAX 64 // Must be power of 2 +#define HISTORY_MASK ( HISTORY_MAX - 1 ) + + +#if !defined( ENTITY_STATEH ) +#include "entity_state.h" +#endif + +#if !defined( PROGS_H ) +#include "progs.h" +#endif + +struct cl_entity_s +{ + int index; // Index into cl_entities ( should match actual slot, but not necessarily ) + + qboolean player; // True if this entity is a "player" + + entity_state_t baseline; // The original state from which to delta during an uncompressed message + entity_state_t prevstate; // The state information from the penultimate message received from the server + entity_state_t curstate; // The state information from the last message received from server + + int current_position; // Last received history update index + position_history_t ph[ HISTORY_MAX ]; // History of position and angle updates for this player + + mouth_t mouth; // For synchronizing mouth movements. + + latchedvars_t latched; // Variables used by studio model rendering routines + + // Information based on interplocation, extrapolation, prediction, or just copied from last msg received. + // + float lastmove; + + // Actual render position and angles + vec3_t origin; + vec3_t angles; + + // Attachment points + vec3_t attachment[4]; + + // Other entity local information + int trivial_accept; + + struct model_s *model; // cl.model_precache[ curstate.modelindes ]; all visible entities have a model + struct efrag_s *efrag; // linked list of efrags + struct mnode_s *topnode; // for bmodels, first world node that splits bmodel, or NULL if not split + + float syncbase; // for client-side animations -- used by obsolete alias animation system, remove? + int visframe; // last frame this entity was found in an active leaf + colorVec cvFloorColor; +}; + +#endif // !CL_ENTITYH diff --git a/dep/rehlsdk/common/com_model.h b/dep/rehlsdk/common/com_model.h new file mode 100644 index 0000000..d6e3d42 --- /dev/null +++ b/dep/rehlsdk/common/com_model.h @@ -0,0 +1,340 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +// com_model.h +#pragma once + +#define STUDIO_RENDER 1 +#define STUDIO_EVENTS 2 + +//#define MAX_MODEL_NAME 64 +//#define MAX_MAP_HULLS 4 +//#define MIPLEVELS 4 +//#define NUM_AMBIENTS 4 // automatic ambient sounds +//#define MAXLIGHTMAPS 4 +#define PLANE_ANYZ 5 + +#define ALIAS_Z_CLIP_PLANE 5 + +// flags in finalvert_t.flags +#define ALIAS_LEFT_CLIP 0x0001 +#define ALIAS_TOP_CLIP 0x0002 +#define ALIAS_RIGHT_CLIP 0x0004 +#define ALIAS_BOTTOM_CLIP 0x0008 +#define ALIAS_Z_CLIP 0x0010 +#define ALIAS_ONSEAM 0x0020 +#define ALIAS_XY_CLIP_MASK 0x000F + +#define ZISCALE ((float)0x8000) + +#define CACHE_SIZE 32 // used to align key data structures + +//typedef enum +//{ +// mod_brush, +// mod_sprite, +// mod_alias, +// mod_studio +//} modtype_t; + +// must match definition in modelgen.h +//#ifndef SYNCTYPE_T +//#define SYNCTYPE_T +// +//typedef enum +//{ +// ST_SYNC=0, +// ST_RAND +//} synctype_t; +// +//#endif + +//typedef struct +//{ +// float mins[3], maxs[3]; +// float origin[3]; +// int headnode[MAX_MAP_HULLS]; +// int visleafs; // not including the solid leaf 0 +// int firstface, numfaces; +//} dmodel_t; + +// plane_t structure +//typedef struct mplane_s +//{ +// vec3_t normal; // surface normal +// float dist; // closest appoach to origin +// byte type; // for texture axis selection and fast side tests +// byte signbits; // signx + signy<<1 + signz<<1 +// byte pad[2]; +//} mplane_t; + +//typedef struct +//{ +// vec3_t position; +//} mvertex_t; + +//typedef struct +//{ +// unsigned short v[2]; +// unsigned int cachededgeoffset; +//} medge_t; + +//typedef struct texture_s +//{ +// char name[16]; +// unsigned width, height; +// int anim_total; // total tenths in sequence ( 0 = no) +// int anim_min, anim_max; // time for this frame min <=time< max +// struct texture_s *anim_next; // in the animation sequence +// struct texture_s *alternate_anims; // bmodels in frame 1 use these +// unsigned offsets[MIPLEVELS]; // four mip maps stored +// unsigned paloffset; +//} texture_t; + +//typedef struct +//{ +// float vecs[2][4]; // [s/t] unit vectors in world space. +// // [i][3] is the s/t offset relative to the origin. +// // s or t = dot(3Dpoint,vecs[i])+vecs[i][3] +// float mipadjust; // ?? mipmap limits for very small surfaces +// texture_t *texture; +// int flags; // sky or slime, no lightmap or 256 subdivision +//} mtexinfo_t; + +//typedef struct mnode_s +//{ +// // common with leaf +// int contents; // 0, to differentiate from leafs +// int visframe; // node needs to be traversed if current +// +// short minmaxs[6]; // for bounding box culling +// +// struct mnode_s *parent; +// +// // node specific +// mplane_t *plane; +// struct mnode_s *children[2]; +// +// unsigned short firstsurface; +// unsigned short numsurfaces; +//} mnode_t; + +//typedef struct msurface_s msurface_t; +//typedef struct decal_s decal_t; + +// JAY: Compress this as much as possible +//struct decal_s +//{ +// decal_t *pnext; // linked list for each surface +// msurface_t *psurface; // Surface id for persistence / unlinking +// short dx; // Offsets into surface texture (in texture coordinates, so we don't need floats) +// short dy; +// short texture; // Decal texture +// byte scale; // Pixel scale +// byte flags; // Decal flags +// +// short entityIndex; // Entity this is attached to +//}; + +//typedef struct mleaf_s +//{ +// // common with node +// int contents; // wil be a negative contents number +// int visframe; // node needs to be traversed if current +// +// short minmaxs[6]; // for bounding box culling +// +// struct mnode_s *parent; +// +// // leaf specific +// byte *compressed_vis; +// struct efrag_s *efrags; +// +// msurface_t **firstmarksurface; +// int nummarksurfaces; +// int key; // BSP sequence number for leaf's contents +// byte ambient_sound_level[NUM_AMBIENTS]; +//} mleaf_t; + +//struct msurface_s +//{ +// int visframe; // should be drawn when node is crossed +// +// int dlightframe; // last frame the surface was checked by an animated light +// int dlightbits; // dynamically generated. Indicates if the surface illumination +// // is modified by an animated light. +// +// mplane_t *plane; // pointer to shared plane +// int flags; // see SURF_ #defines +// +// int firstedge; // look up in model->surfedges[], negative numbers +// int numedges; // are backwards edges +// +// // surface generation data +// struct surfcache_s *cachespots[MIPLEVELS]; +// +// short texturemins[2]; // smallest s/t position on the surface. +// short extents[2]; // ?? s/t texture size, 1..256 for all non-sky surfaces +// +// mtexinfo_t *texinfo; +// +// // lighting info +// byte styles[MAXLIGHTMAPS]; // index into d_lightstylevalue[] for animated lights +// // no one surface can be effected by more than 4 +// // animated lights. +// color24 *samples; +// +// decal_t *pdecals; +//}; + +//typedef struct +//{ +// int planenum; +// short children[2]; // negative numbers are contents +//} dclipnode_t; + +//typedef struct hull_s +//{ +// dclipnode_t *clipnodes; +// mplane_t *planes; +// int firstclipnode; +// int lastclipnode; +// vec3_t clip_mins; +// vec3_t clip_maxs; +//} hull_t; + +typedef struct cache_user_s +{ + void *data; +} cache_user_t; + +//typedef struct model_s +//{ +// char name[ MAX_MODEL_NAME ]; +// qboolean needload; // bmodels and sprites don't cache normally +// +// modtype_t type; +// int numframes; +// synctype_t synctype; +// +// int flags; +// +// // +// // volume occupied by the model +// // +// vec3_t mins, maxs; +// float radius; +// +// // +// // brush model +// // +// int firstmodelsurface, nummodelsurfaces; +// +// int numsubmodels; +// dmodel_t *submodels; +// +// int numplanes; +// mplane_t *planes; +// +// int numleafs; // number of visible leafs, not counting 0 +// struct mleaf_s *leafs; +// +// int numvertexes; +// mvertex_t *vertexes; +// +// int numedges; +// medge_t *edges; +// +// int numnodes; +// mnode_t *nodes; +// +// int numtexinfo; +// mtexinfo_t *texinfo; +// +// int numsurfaces; +// msurface_t *surfaces; +// +// int numsurfedges; +// int *surfedges; +// +// int numclipnodes; +// dclipnode_t *clipnodes; +// +// int nummarksurfaces; +// msurface_t **marksurfaces; +// +// hull_t hulls[MAX_MAP_HULLS]; +// +// int numtextures; +// texture_t **textures; +// +// byte *visdata; +// +// color24 *lightdata; +// +// char *entities; +// +// // +// // additional model data +// // +// cache_user_t cache; // only access through Mod_Extradata +// +//} model_t; + +//typedef vec_t vec4_t[4]; + +typedef struct alight_s +{ + int ambientlight; // clip at 128 + int shadelight; // clip at 192 - ambientlight + vec3_t color; + float *plightvec; +} alight_t; + +typedef struct auxvert_s +{ + float fv[3]; // viewspace x, y +} auxvert_t; + +#include "custom.h" + +//#define MAX_SCOREBOARDNAME 32 + +// Defined in client.h differently +//typedef struct player_info_s +//{ +// // User id on server +// int userid; +// +// // User info string +// char userinfo[ MAX_INFO_STRING ]; +// +// // Name +// char name[ MAX_SCOREBOARDNAME ]; +// +// // Spectator or not, unused +// int spectator; +// +// int ping; +// int packet_loss; +// +// // skin information +// char model[MAX_QPATH]; +// int topcolor; +// int bottomcolor; +// +// // last frame rendered +// int renderframe; +// +// // Gait frame estimation +// int gaitsequence; +// float gaitframe; +// float gaityaw; +// vec3_t prevgaitorigin; +// +// customization_t customdata; +//} player_info_t; diff --git a/dep/rehlsdk/common/commandline.cpp b/dep/rehlsdk/common/commandline.cpp new file mode 100644 index 0000000..9be292c --- /dev/null +++ b/dep/rehlsdk/common/commandline.cpp @@ -0,0 +1,356 @@ +#include "precompiled.h" + +class CCommandLine: public ICommandLine { +public: + CCommandLine(); + virtual ~CCommandLine(); + + void CreateCmdLine(const char *commandline); + void CreateCmdLine(int argc, const char *argv[]); + const char *GetCmdLine() const; + + // Check whether a particular parameter exists + const char *CheckParm(const char *psz, char **ppszValue = nullptr) const; + void RemoveParm(const char *pszParm); + void AppendParm(const char *pszParm, const char *pszValues); + + void SetParm(const char *pszParm, const char *pszValues); + void SetParm(const char *pszParm, int iValue); + + // When the commandline contains @name, it reads the parameters from that file + void LoadParametersFromFile(const char *&pSrc, char *&pDst, int maxDestLen); + +private: + // Copy of actual command line + char *m_pszCmdLine; +}; + +CCommandLine g_CmdLine; +ICommandLine *cmdline = &g_CmdLine; + +ICommandLine *CommandLine() +{ + return &g_CmdLine; +} + +CCommandLine::CCommandLine() +{ + m_pszCmdLine = nullptr; +} + +CCommandLine::~CCommandLine() +{ + if (m_pszCmdLine) + { + delete [] m_pszCmdLine; + m_pszCmdLine = nullptr; + } +} + +char *CopyString(const char *src) +{ + if (!src) + return nullptr; + + char *out = (char *)new char[Q_strlen(src) + 1]; + Q_strcpy(out, src); + return out; +} + +// Creates a command line from the arguments passed in +void CCommandLine::CreateCmdLine(int argc, const char *argv[]) +{ + char cmdline[4096] = ""; + const int MAX_CHARS = sizeof(cmdline) - 1; + + for (int i = 0; i < argc; ++i) + { + if (Q_strchr(argv[i], ' ')) + { + Q_strlcat(cmdline, "\""); + Q_strlcat(cmdline, argv[i]); + Q_strlcat(cmdline, "\""); + } + else + { + Q_strlcat(cmdline, argv[i]); + } + + Q_strlcat(cmdline, " "); + } + + cmdline[Q_strlen(cmdline)] = '\0'; + CreateCmdLine(cmdline); +} + +void CCommandLine::LoadParametersFromFile(const char *&pSrc, char *&pDst, int maxDestLen) +{ + // Suck out the file name + char szFileName[ MAX_PATH ]; + char *pOut; + char *pDestStart = pDst; + + // Skip the @ sign + pSrc++; + pOut = szFileName; + + while (*pSrc && *pSrc != ' ') + { + *pOut++ = *pSrc++; +#if 0 + if ((pOut - szFileName) >= (MAX_PATH - 1)) + break; +#endif + } + + *pOut = '\0'; + + // Skip the space after the file name + if (*pSrc) + pSrc++; + + // Now read in parameters from file + FILE *fp = fopen(szFileName, "r"); + if (fp) + { + char c; + c = (char)fgetc(fp); + while (c != EOF) + { + // Turn return characters into spaces + if (c == '\n') + c = ' '; + + *pDst++ = c; + +#if 0 + // Don't go past the end, and allow for our terminating space character AND a terminating null character. + if ((pDst - pDestStart) >= (maxDestLen - 2)) + break; +#endif + + // Get the next character, if there are more + c = (char)fgetc(fp); + } + + // Add a terminating space character + *pDst++ = ' '; + + fclose(fp); + } + else + { + printf("Parameter file '%s' not found, skipping...", szFileName); + } +} + +// Purpose: Create a command line from the passed in string +// Note that if you pass in a @filename, then the routine will read settings from a file instead of the command line +void CCommandLine::CreateCmdLine(const char *commandline) +{ + if (m_pszCmdLine) + { + delete[] m_pszCmdLine; + m_pszCmdLine = nullptr; + } + + char szFull[4096]; + + char *pDst = szFull; + const char *pSrc = commandline; + + bool allowAtSign = true; + + while (*pSrc) + { + if (*pSrc == '@') + { + if (allowAtSign) + { + LoadParametersFromFile(pSrc, pDst, sizeof(szFull) - (pDst - szFull)); + continue; + } + } + + allowAtSign = isspace(*pSrc) != 0; + +#if 0 + // Don't go past the end. + if ((pDst - szFull) >= (sizeof(szFull) - 1)) + break; +#endif + *pDst++ = *pSrc++; + } + + *pDst = '\0'; + + int len = Q_strlen(szFull) + 1; + m_pszCmdLine = new char[len]; + Q_memcpy(m_pszCmdLine, szFull, len); +} + +// Purpose: Remove specified string ( and any args attached to it ) from command line +void CCommandLine::RemoveParm(const char *pszParm) +{ + if (!m_pszCmdLine) + return; + + if (!pszParm || *pszParm == '\0') + return; + + // Search for first occurrence of pszParm + char *p, *found; + char *pnextparam; + int n; + int curlen; + + p = m_pszCmdLine; + while (*p) + { + curlen = Q_strlen(p); + found = Q_strstr(p, pszParm); + + if (!found) + break; + + pnextparam = found + 1; + while (pnextparam && *pnextparam && (*pnextparam != '-') && (*pnextparam != '+')) + pnextparam++; + + if (pnextparam && *pnextparam) + { + // We are either at the end of the string, or at the next param. Just chop out the current param. + // # of characters after this param. + n = curlen - (pnextparam - p); + + Q_memcpy(found, pnextparam, n); + found[n] = '\0'; + } + else + { + // Clear out rest of string. + n = pnextparam - found; + Q_memset(found, 0, n); + } + } + + // Strip and trailing ' ' characters left over. + while (1) + { + int curpos = Q_strlen(m_pszCmdLine); + if (curpos == 0 || m_pszCmdLine[ curpos - 1 ] != ' ') + break; + + m_pszCmdLine[curpos - 1] = '\0'; + } +} + +// Purpose: Append parameter and argument values to command line +void CCommandLine::AppendParm(const char *pszParm, const char *pszValues) +{ + int nNewLength = 0; + char *pCmdString; + + // Parameter. + nNewLength = Q_strlen(pszParm); + + // Values + leading space character. + if (pszValues) + nNewLength += Q_strlen(pszValues) + 1; + + // Terminal 0; + nNewLength++; + + if (!m_pszCmdLine) + { + m_pszCmdLine = new char[ nNewLength ]; + Q_strcpy(m_pszCmdLine, pszParm); + if (pszValues) + { + Q_strcat(m_pszCmdLine, " "); + Q_strcat(m_pszCmdLine, pszValues); + } + + return; + } + + // Remove any remnants from the current Cmd Line. + RemoveParm(pszParm); + + nNewLength += Q_strlen(m_pszCmdLine) + 1 + 1; + + pCmdString = new char[ nNewLength ]; + Q_memset(pCmdString, 0, nNewLength); + + Q_strcpy(pCmdString, m_pszCmdLine); // Copy old command line. + Q_strcat(pCmdString, " "); // Put in a space + Q_strcat(pCmdString, pszParm); + + if (pszValues) + { + Q_strcat(pCmdString, " "); + Q_strcat(pCmdString, pszValues); + } + + // Kill off the old one + delete[] m_pszCmdLine; + + // Point at the new command line. + m_pszCmdLine = pCmdString; +} + +void CCommandLine::SetParm(const char *pszParm, const char *pszValues) +{ + RemoveParm(pszParm); + AppendParm(pszParm, pszValues); +} + +void CCommandLine::SetParm(const char *pszParm, int iValue) +{ + char buf[64]; + Q_snprintf(buf, sizeof(buf), "%d", iValue); + SetParm(pszParm, buf); +} + +// Purpose: Search for the parameter in the current commandline +const char *CCommandLine::CheckParm(const char *psz, char **ppszValue) const +{ + static char sz[128] = ""; + + if (!m_pszCmdLine) + return nullptr; + + if (ppszValue) + *ppszValue = nullptr; + + char *pret = Q_strstr(m_pszCmdLine, psz); + if (!pret || !ppszValue) + return pret; + + // find the next whitespace + char *p1 = pret; + do { + ++p1; + } while (*p1 != ' ' && *p1); + + int i = 0; + char *p2 = p1 + 1; + + do { + if (p2[i] == '\0' || p2[i] == ' ') + break; + + sz[i] = p2[i]; + i++; + } while (i < sizeof(sz)); + + sz[i] = '\0'; + *ppszValue = sz; + + return pret; +} + +const char *CCommandLine::GetCmdLine() const +{ + return m_pszCmdLine; +} diff --git a/dep/rehlsdk/common/con_nprint.h b/dep/rehlsdk/common/con_nprint.h new file mode 100644 index 0000000..b2a1888 --- /dev/null +++ b/dep/rehlsdk/common/con_nprint.h @@ -0,0 +1,38 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( CON_NPRINTH ) +#define CON_NPRINTH +#ifdef _WIN32 +#pragma once +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct con_nprint_s +{ + int index; // Row # + float time_to_live; // # of seconds before it dissappears + float color[ 3 ]; // RGB colors ( 0.0 -> 1.0 scale ) +} con_nprint_t; + +void Con_NPrintf( int idx, const char *fmt, ... ); +void Con_NXPrintf( struct con_nprint_s *info, const char *fmt, ... ); +#ifdef __cplusplus +} +#endif + +#endif diff --git a/dep/rehlsdk/common/const.h b/dep/rehlsdk/common/const.h new file mode 100644 index 0000000..aa081dc --- /dev/null +++ b/dep/rehlsdk/common/const.h @@ -0,0 +1,806 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef CONST_H +#define CONST_H +#ifdef _WIN32 +#pragma once +#endif + +// Max # of clients allowed in a server. +#define MAX_CLIENTS 32 + +// How many bits to use to encode an edict. +#define MAX_EDICT_BITS 11 // # of bits needed to represent max edicts +// Max # of edicts in a level (2048) +#define MAX_EDICTS (1<flags +#define FL_FLY (1<<0) // Changes the SV_Movestep() behavior to not need to be on ground +#define FL_SWIM (1<<1) // Changes the SV_Movestep() behavior to not need to be on ground (but stay in water) +#define FL_CONVEYOR (1<<2) +#define FL_CLIENT (1<<3) +#define FL_INWATER (1<<4) +#define FL_MONSTER (1<<5) +#define FL_GODMODE (1<<6) +#define FL_NOTARGET (1<<7) +#define FL_SKIPLOCALHOST (1<<8) // Don't send entity to local host, it's predicting this entity itself +#define FL_ONGROUND (1<<9) // At rest / on the ground +#define FL_PARTIALGROUND (1<<10) // not all corners are valid +#define FL_WATERJUMP (1<<11) // player jumping out of water +#define FL_FROZEN (1<<12) // Player is frozen for 3rd person camera +#define FL_FAKECLIENT (1<<13) // JAC: fake client, simulated server side; don't send network messages to them +#define FL_DUCKING (1<<14) // Player flag -- Player is fully crouched +#define FL_FLOAT (1<<15) // Apply floating force to this entity when in water +#define FL_GRAPHED (1<<16) // worldgraph has this ent listed as something that blocks a connection + +// UNDONE: Do we need these? +#define FL_IMMUNE_WATER (1<<17) +#define FL_IMMUNE_SLIME (1<<18) +#define FL_IMMUNE_LAVA (1<<19) + +#define FL_PROXY (1<<20) // This is a spectator proxy +#define FL_ALWAYSTHINK (1<<21) // Brush model flag -- call think every frame regardless of nextthink - ltime (for constantly changing velocity/path) +#define FL_BASEVELOCITY (1<<22) // Base velocity has been applied this frame (used to convert base velocity into momentum) +#define FL_MONSTERCLIP (1<<23) // Only collide in with monsters who have FL_MONSTERCLIP set +#define FL_ONTRAIN (1<<24) // Player is _controlling_ a train, so movement commands should be ignored on client during prediction. +#define FL_WORLDBRUSH (1<<25) // Not moveable/removeable brush entity (really part of the world, but represented as an entity for transparency or something) +#define FL_SPECTATOR (1<<26) // This client is a spectator, don't run touch functions, etc. +#define FL_CUSTOMENTITY (1<<29) // This is a custom entity +#define FL_KILLME (1<<30) // This entity is marked for death -- This allows the engine to kill ents at the appropriate time +#define FL_DORMANT (1<<31) // Entity is dormant, no updates to client + +// SV_EmitSound2 flags +#define SND_EMIT2_NOPAS (1<<0) // never to do check PAS +#define SND_EMIT2_INVOKER (1<<1) // do not send to the client invoker + +// Engine edict->spawnflags +#define SF_NOTINDEATHMATCH 0x0800 // Do not spawn when deathmatch and loading entities from a file + + +// Goes into globalvars_t.trace_flags +#define FTRACE_SIMPLEBOX (1<<0) // Traceline with a simple box + + +// walkmove modes +#define WALKMOVE_NORMAL 0 // normal walkmove +#define WALKMOVE_WORLDONLY 1 // doesn't hit ANY entities, no matter what the solid type +#define WALKMOVE_CHECKONLY 2 // move, but don't touch triggers + +// edict->movetype values +#define MOVETYPE_NONE 0 // never moves +//#define MOVETYPE_ANGLENOCLIP 1 +//#define MOVETYPE_ANGLECLIP 2 +#define MOVETYPE_WALK 3 // Player only - moving on the ground +#define MOVETYPE_STEP 4 // gravity, special edge handling -- monsters use this +#define MOVETYPE_FLY 5 // No gravity, but still collides with stuff +#define MOVETYPE_TOSS 6 // gravity/collisions +#define MOVETYPE_PUSH 7 // no clip to world, push and crush +#define MOVETYPE_NOCLIP 8 // No gravity, no collisions, still do velocity/avelocity +#define MOVETYPE_FLYMISSILE 9 // extra size to monsters +#define MOVETYPE_BOUNCE 10 // Just like Toss, but reflect velocity when contacting surfaces +#define MOVETYPE_BOUNCEMISSILE 11 // bounce w/o gravity +#define MOVETYPE_FOLLOW 12 // track movement of aiment +#define MOVETYPE_PUSHSTEP 13 // BSP model that needs physics/world collisions (uses nearest hull for world collision) + +// 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! +#define SOLID_NOT 0 // no interaction with other objects +#define SOLID_TRIGGER 1 // touch on edge, but not blocking +#define SOLID_BBOX 2 // touch on edge, block +#define SOLID_SLIDEBOX 3 // touch on edge, but not an onground +#define SOLID_BSP 4 // bsp clip, touch on edge, block + +// edict->deadflag values +#define DEAD_NO 0 // alive +#define DEAD_DYING 1 // playing death animation or still falling off of a ledge waiting to hit ground +#define DEAD_DEAD 2 // dead. lying still. +#define DEAD_RESPAWNABLE 3 +#define DEAD_DISCARDBODY 4 + +#define DAMAGE_NO 0 +#define DAMAGE_YES 1 +#define DAMAGE_AIM 2 + +// entity effects +#define EF_BRIGHTFIELD 1 // swirling cloud of particles +#define EF_MUZZLEFLASH 2 // single frame ELIGHT on entity attachment 0 +#define EF_BRIGHTLIGHT 4 // DLIGHT centered at entity origin +#define EF_DIMLIGHT 8 // player flashlight +#define EF_INVLIGHT 16 // get lighting from ceiling +#define EF_NOINTERP 32 // don't interpolate the next frame +#define EF_LIGHT 64 // rocket flare glow sprite +#define EF_NODRAW 128 // don't draw entity +#define EF_NIGHTVISION 256 // player nightvision +#define EF_SNIPERLASER 512 // sniper laser effect +#define EF_FIBERCAMERA 1024// fiber camera + + +// entity flags +#define EFLAG_SLERP 1 // do studio interpolation of this entity + +// +// temp entity events +// +#define TE_BEAMPOINTS 0 // beam effect between two points +// coord coord coord (start position) +// coord coord coord (end position) +// short (sprite index) +// byte (starting frame) +// byte (frame rate in 0.1's) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte (noise amplitude in 0.01's) +// byte,byte,byte (color) +// byte (brightness) +// byte (scroll speed in 0.1's) + +#define TE_BEAMENTPOINT 1 // beam effect between point and entity +// short (start entity) +// coord coord coord (end position) +// short (sprite index) +// byte (starting frame) +// byte (frame rate in 0.1's) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte (noise amplitude in 0.01's) +// byte,byte,byte (color) +// byte (brightness) +// byte (scroll speed in 0.1's) + +#define TE_GUNSHOT 2 // particle effect plus ricochet sound +// coord coord coord (position) + +#define TE_EXPLOSION 3 // additive sprite, 2 dynamic lights, flickering particles, explosion sound, move vertically 8 pps +// coord coord coord (position) +// short (sprite index) +// byte (scale in 0.1's) +// byte (framerate) +// byte (flags) +// +// The Explosion effect has some flags to control performance/aesthetic features: +#define TE_EXPLFLAG_NONE 0 // all flags clear makes default Half-Life explosion +#define TE_EXPLFLAG_NOADDITIVE 1 // sprite will be drawn opaque (ensure that the sprite you send is a non-additive sprite) +#define TE_EXPLFLAG_NODLIGHTS 2 // do not render dynamic lights +#define TE_EXPLFLAG_NOSOUND 4 // do not play client explosion sound +#define TE_EXPLFLAG_NOPARTICLES 8 // do not draw particles + + +#define TE_TAREXPLOSION 4 // Quake1 "tarbaby" explosion with sound +// coord coord coord (position) + +#define TE_SMOKE 5 // alphablend sprite, move vertically 30 pps +// coord coord coord (position) +// short (sprite index) +// byte (scale in 0.1's) +// byte (framerate) + +#define TE_TRACER 6 // tracer effect from point to point +// coord, coord, coord (start) +// coord, coord, coord (end) + +#define TE_LIGHTNING 7 // TE_BEAMPOINTS with simplified parameters +// coord, coord, coord (start) +// coord, coord, coord (end) +// byte (life in 0.1's) +// byte (width in 0.1's) +// byte (amplitude in 0.01's) +// short (sprite model index) + +#define TE_BEAMENTS 8 +// short (start entity) +// short (end entity) +// short (sprite index) +// byte (starting frame) +// byte (frame rate in 0.1's) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte (noise amplitude in 0.01's) +// byte,byte,byte (color) +// byte (brightness) +// byte (scroll speed in 0.1's) + +#define TE_SPARKS 9 // 8 random tracers with gravity, ricochet sprite +// coord coord coord (position) + +#define TE_LAVASPLASH 10 // Quake1 lava splash +// coord coord coord (position) + +#define TE_TELEPORT 11 // Quake1 teleport splash +// coord coord coord (position) + +#define TE_EXPLOSION2 12 // Quake1 colormaped (base palette) particle explosion with sound +// coord coord coord (position) +// byte (starting color) +// byte (num colors) + +#define TE_BSPDECAL 13 // Decal from the .BSP file +// coord, coord, coord (x,y,z), decal position (center of texture in world) +// short (texture index of precached decal texture name) +// short (entity index) +// [optional - only included if previous short is non-zero (not the world)] short (index of model of above entity) + +#define TE_IMPLOSION 14 // tracers moving toward a point +// coord, coord, coord (position) +// byte (radius) +// byte (count) +// byte (life in 0.1's) + +#define TE_SPRITETRAIL 15 // line of moving glow sprites with gravity, fadeout, and collisions +// coord, coord, coord (start) +// coord, coord, coord (end) +// short (sprite index) +// byte (count) +// byte (life in 0.1's) +// byte (scale in 0.1's) +// byte (velocity along vector in 10's) +// byte (randomness of velocity in 10's) + +#define TE_BEAM 16 // obsolete + +#define TE_SPRITE 17 // additive sprite, plays 1 cycle +// coord, coord, coord (position) +// short (sprite index) +// byte (scale in 0.1's) +// byte (brightness) + +#define TE_BEAMSPRITE 18 // A beam with a sprite at the end +// coord, coord, coord (start position) +// coord, coord, coord (end position) +// short (beam sprite index) +// short (end sprite index) + +#define TE_BEAMTORUS 19 // screen aligned beam ring, expands to max radius over lifetime +// coord coord coord (center position) +// coord coord coord (axis and radius) +// short (sprite index) +// byte (starting frame) +// byte (frame rate in 0.1's) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte (noise amplitude in 0.01's) +// byte,byte,byte (color) +// byte (brightness) +// byte (scroll speed in 0.1's) + +#define TE_BEAMDISK 20 // disk that expands to max radius over lifetime +// coord coord coord (center position) +// coord coord coord (axis and radius) +// short (sprite index) +// byte (starting frame) +// byte (frame rate in 0.1's) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte (noise amplitude in 0.01's) +// byte,byte,byte (color) +// byte (brightness) +// byte (scroll speed in 0.1's) + +#define TE_BEAMCYLINDER 21 // cylinder that expands to max radius over lifetime +// coord coord coord (center position) +// coord coord coord (axis and radius) +// short (sprite index) +// byte (starting frame) +// byte (frame rate in 0.1's) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte (noise amplitude in 0.01's) +// byte,byte,byte (color) +// byte (brightness) +// byte (scroll speed in 0.1's) + +#define TE_BEAMFOLLOW 22 // create a line of decaying beam segments until entity stops moving +// short (entity:attachment to follow) +// short (sprite index) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte,byte,byte (color) +// byte (brightness) + +#define TE_GLOWSPRITE 23 +// coord, coord, coord (pos) short (model index) byte (scale / 10) + +#define TE_BEAMRING 24 // connect a beam ring to two entities +// short (start entity) +// short (end entity) +// short (sprite index) +// byte (starting frame) +// byte (frame rate in 0.1's) +// byte (life in 0.1's) +// byte (line width in 0.1's) +// byte (noise amplitude in 0.01's) +// byte,byte,byte (color) +// byte (brightness) +// byte (scroll speed in 0.1's) + +#define TE_STREAK_SPLASH 25 // oriented shower of tracers +// coord coord coord (start position) +// coord coord coord (direction vector) +// byte (color) +// short (count) +// short (base speed) +// short (ramdon velocity) + +#define TE_BEAMHOSE 26 // obsolete + +#define TE_DLIGHT 27 // dynamic light, effect world, minor entity effect +// coord, coord, coord (pos) +// byte (radius in 10's) +// byte byte byte (color) +// byte (brightness) +// byte (life in 10's) +// byte (decay rate in 10's) + +#define TE_ELIGHT 28 // point entity light, no world effect +// short (entity:attachment to follow) +// coord coord coord (initial position) +// coord (radius) +// byte byte byte (color) +// byte (life in 0.1's) +// coord (decay rate) + +#define TE_TEXTMESSAGE 29 +// short 1.2.13 x (-1 = center) +// short 1.2.13 y (-1 = center) +// byte Effect 0 = fade in/fade out + // 1 is flickery credits + // 2 is write out (training room) + +// 4 bytes r,g,b,a color1 (text color) +// 4 bytes r,g,b,a color2 (effect color) +// ushort 8.8 fadein time +// ushort 8.8 fadeout time +// ushort 8.8 hold time +// optional ushort 8.8 fxtime (time the highlight lags behing the leading text in effect 2) +// string text message (512 chars max sz string) +#define TE_LINE 30 +// coord, coord, coord startpos +// coord, coord, coord endpos +// short life in 0.1 s +// 3 bytes r, g, b + +#define TE_BOX 31 +// coord, coord, coord boxmins +// coord, coord, coord boxmaxs +// short life in 0.1 s +// 3 bytes r, g, b + +#define TE_KILLBEAM 99 // kill all beams attached to entity +// short (entity) + +#define TE_LARGEFUNNEL 100 +// coord coord coord (funnel position) +// short (sprite index) +// short (flags) + +#define TE_BLOODSTREAM 101 // particle spray +// coord coord coord (start position) +// coord coord coord (spray vector) +// byte (color) +// byte (speed) + +#define TE_SHOWLINE 102 // line of particles every 5 units, dies in 30 seconds +// coord coord coord (start position) +// coord coord coord (end position) + +#define TE_BLOOD 103 // particle spray +// coord coord coord (start position) +// coord coord coord (spray vector) +// byte (color) +// byte (speed) + +#define TE_DECAL 104 // Decal applied to a brush entity (not the world) +// coord, coord, coord (x,y,z), decal position (center of texture in world) +// byte (texture index of precached decal texture name) +// short (entity index) + +#define TE_FIZZ 105 // create alpha sprites inside of entity, float upwards +// short (entity) +// short (sprite index) +// byte (density) + +#define TE_MODEL 106 // create a moving model that bounces and makes a sound when it hits +// coord, coord, coord (position) +// coord, coord, coord (velocity) +// angle (initial yaw) +// short (model index) +// byte (bounce sound type) +// byte (life in 0.1's) + +#define TE_EXPLODEMODEL 107 // spherical shower of models, picks from set +// coord, coord, coord (origin) +// coord (velocity) +// short (model index) +// short (count) +// byte (life in 0.1's) + +#define TE_BREAKMODEL 108 // box of models or sprites +// coord, coord, coord (position) +// coord, coord, coord (size) +// coord, coord, coord (velocity) +// byte (random velocity in 10's) +// short (sprite or model index) +// byte (count) +// byte (life in 0.1 secs) +// byte (flags) + +#define TE_GUNSHOTDECAL 109 // decal and ricochet sound +// coord, coord, coord (position) +// short (entity index???) +// byte (decal???) + +#define TE_SPRITE_SPRAY 110 // spay of alpha sprites +// coord, coord, coord (position) +// coord, coord, coord (velocity) +// short (sprite index) +// byte (count) +// byte (speed) +// byte (noise) + +#define TE_ARMOR_RICOCHET 111 // quick spark sprite, client ricochet sound. +// coord, coord, coord (position) +// byte (scale in 0.1's) + +#define TE_PLAYERDECAL 112 // ??? +// byte (playerindex) +// coord, coord, coord (position) +// short (entity???) +// byte (decal number???) +// [optional] short (model index???) + +#define TE_BUBBLES 113 // create alpha sprites inside of box, float upwards +// coord, coord, coord (min start position) +// coord, coord, coord (max start position) +// coord (float height) +// short (model index) +// byte (count) +// coord (speed) + +#define TE_BUBBLETRAIL 114 // create alpha sprites along a line, float upwards +// coord, coord, coord (min start position) +// coord, coord, coord (max start position) +// coord (float height) +// short (model index) +// byte (count) +// coord (speed) + +#define TE_BLOODSPRITE 115 // spray of opaque sprite1's that fall, single sprite2 for 1..2 secs (this is a high-priority tent) +// coord, coord, coord (position) +// short (sprite1 index) +// short (sprite2 index) +// byte (color) +// byte (scale) + +#define TE_WORLDDECAL 116 // Decal applied to the world brush +// coord, coord, coord (x,y,z), decal position (center of texture in world) +// byte (texture index of precached decal texture name) + +#define TE_WORLDDECALHIGH 117 // Decal (with texture index > 256) applied to world brush +// coord, coord, coord (x,y,z), decal position (center of texture in world) +// byte (texture index of precached decal texture name - 256) + +#define TE_DECALHIGH 118 // Same as TE_DECAL, but the texture index was greater than 256 +// coord, coord, coord (x,y,z), decal position (center of texture in world) +// byte (texture index of precached decal texture name - 256) +// short (entity index) + +#define TE_PROJECTILE 119 // Makes a projectile (like a nail) (this is a high-priority tent) +// coord, coord, coord (position) +// coord, coord, coord (velocity) +// short (modelindex) +// byte (life) +// byte (owner) projectile won't collide with owner (if owner == 0, projectile will hit any client). + +#define TE_SPRAY 120 // Throws a shower of sprites or models +// coord, coord, coord (position) +// coord, coord, coord (direction) +// short (modelindex) +// byte (count) +// byte (speed) +// byte (noise) +// byte (rendermode) + +#define TE_PLAYERSPRITES 121 // sprites emit from a player's bounding box (ONLY use for players!) +// byte (playernum) +// short (sprite modelindex) +// byte (count) +// byte (variance) (0 = no variance in size) (10 = 10% variance in size) + +#define TE_PARTICLEBURST 122 // very similar to lavasplash. +// coord (origin) +// short (radius) +// byte (particle color) +// byte (duration * 10) (will be randomized a bit) + +#define TE_FIREFIELD 123 // makes a field of fire. +// coord (origin) +// short (radius) (fire is made in a square around origin. -radius, -radius to radius, radius) +// short (modelindex) +// byte (count) +// byte (flags) +// byte (duration (in seconds) * 10) (will be randomized a bit) +// +// to keep network traffic low, this message has associated flags that fit into a byte: +#define TEFIRE_FLAG_ALLFLOAT 1 // all sprites will drift upwards as they animate +#define TEFIRE_FLAG_SOMEFLOAT 2 // some of the sprites will drift upwards. (50% chance) +#define TEFIRE_FLAG_LOOP 4 // if set, sprite plays at 15 fps, otherwise plays at whatever rate stretches the animation over the sprite's duration. +#define TEFIRE_FLAG_ALPHA 8 // if set, sprite is rendered alpha blended at 50% else, opaque +#define TEFIRE_FLAG_PLANAR 16 // if set, all fire sprites have same initial Z instead of randomly filling a cube. +#define TEFIRE_FLAG_ADDITIVE 32 // if set, sprite is rendered non-opaque with additive + +#define TE_PLAYERATTACHMENT 124 // attaches a TENT to a player (this is a high-priority tent) +// byte (entity index of player) +// coord (vertical offset) ( attachment origin.z = player origin.z + vertical offset ) +// short (model index) +// short (life * 10 ); + +#define TE_KILLPLAYERATTACHMENTS 125 // will expire all TENTS attached to a player. +// byte (entity index of player) + +#define TE_MULTIGUNSHOT 126 // much more compact shotgun message +// This message is used to make a client approximate a 'spray' of gunfire. +// Any weapon that fires more than one bullet per frame and fires in a bit of a spread is +// a good candidate for MULTIGUNSHOT use. (shotguns) +// +// NOTE: This effect makes the client do traces for each bullet, these client traces ignore +// entities that have studio models.Traces are 4096 long. +// +// coord (origin) +// coord (origin) +// coord (origin) +// coord (direction) +// coord (direction) +// coord (direction) +// coord (x noise * 100) +// coord (y noise * 100) +// byte (count) +// byte (bullethole decal texture index) + +#define TE_USERTRACER 127 // larger message than the standard tracer, but allows some customization. +// coord (origin) +// coord (origin) +// coord (origin) +// coord (velocity) +// coord (velocity) +// coord (velocity) +// byte ( life * 10 ) +// byte ( color ) this is an index into an array of color vectors in the engine. (0 - ) +// byte ( length * 10 ) + + + +#define MSG_BROADCAST 0 // unreliable to all +#define MSG_ONE 1 // reliable to one (msg_entity) +#define MSG_ALL 2 // reliable to all +#define MSG_INIT 3 // write to the init string +#define MSG_PVS 4 // Ents in PVS of org +#define MSG_PAS 5 // Ents in PAS of org +#define MSG_PVS_R 6 // Reliable to PVS +#define MSG_PAS_R 7 // Reliable to PAS +#define MSG_ONE_UNRELIABLE 8 // Send to one client, but don't put in reliable stream, put in unreliable datagram ( could be dropped ) +#define MSG_SPEC 9 // Sends to all spectator proxies + +// contents of a spot in the world +#define CONTENTS_EMPTY -1 +#define CONTENTS_SOLID -2 +#define CONTENTS_WATER -3 +#define CONTENTS_SLIME -4 +#define CONTENTS_LAVA -5 +#define CONTENTS_SKY -6 +/* These additional contents constants are defined in bspfile.h +#define CONTENTS_ORIGIN -7 // removed at csg time +#define CONTENTS_CLIP -8 // changed to contents_solid +#define CONTENTS_CURRENT_0 -9 +#define CONTENTS_CURRENT_90 -10 +#define CONTENTS_CURRENT_180 -11 +#define CONTENTS_CURRENT_270 -12 +#define CONTENTS_CURRENT_UP -13 +#define CONTENTS_CURRENT_DOWN -14 + +#define CONTENTS_TRANSLUCENT -15 +*/ +#define CONTENTS_LADDER -16 + +#define CONTENT_FLYFIELD -17 +#define CONTENT_GRAVITY_FLYFIELD -18 +#define CONTENT_FOG -19 + +#define CONTENT_EMPTY -1 +#define CONTENT_SOLID -2 +#define CONTENT_WATER -3 +#define CONTENT_SLIME -4 +#define CONTENT_LAVA -5 +#define CONTENT_SKY -6 + +// channels +#define CHAN_AUTO 0 +#define CHAN_WEAPON 1 +#define CHAN_VOICE 2 +#define CHAN_ITEM 3 +#define CHAN_BODY 4 +#define CHAN_STREAM 5 // allocate stream channel from the static or dynamic area +#define CHAN_STATIC 6 // allocate channel from the static area +#define CHAN_NETWORKVOICE_BASE 7 // voice data coming across the network +#define CHAN_NETWORKVOICE_END 500 // network voice data reserves slots (CHAN_NETWORKVOICE_BASE through CHAN_NETWORKVOICE_END). +#define CHAN_BOT 501 // channel used for bot chatter. + +// attenuation values +#define ATTN_NONE 0 +#define ATTN_NORM (float)0.8 +#define ATTN_IDLE (float)2 +#define ATTN_STATIC (float)1.25 + +// pitch values +#define PITCH_NORM 100 // non-pitch shifted +#define PITCH_LOW 95 // other values are possible - 0-255, where 255 is very high +#define PITCH_HIGH 120 + +// volume values +#define VOL_NORM 1.0 + +// plats +#define PLAT_LOW_TRIGGER 1 + +// Trains +#define SF_TRAIN_WAIT_RETRIGGER 1 +#define SF_TRAIN_START_ON 4 // Train is initially moving +#define SF_TRAIN_PASSABLE 8 // Train is not solid -- used to make water trains + +// buttons +#ifndef IN_BUTTONS_H +#include "in_buttons.h" +#endif + +// Break Model Defines + +#define BREAK_TYPEMASK 0x4F +#define BREAK_GLASS 0x01 +#define BREAK_METAL 0x02 +#define BREAK_FLESH 0x04 +#define BREAK_WOOD 0x08 + +#define BREAK_SMOKE 0x10 +#define BREAK_TRANS 0x20 +#define BREAK_CONCRETE 0x40 +#define BREAK_2 0x80 + +// Colliding temp entity sounds + +#define BOUNCE_GLASS BREAK_GLASS +#define BOUNCE_METAL BREAK_METAL +#define BOUNCE_FLESH BREAK_FLESH +#define BOUNCE_WOOD BREAK_WOOD +#define BOUNCE_SHRAP 0x10 +#define BOUNCE_SHELL 0x20 +#define BOUNCE_CONCRETE BREAK_CONCRETE +#define BOUNCE_SHOTSHELL 0x80 + +// Temp entity bounce sound types +#define TE_BOUNCE_NULL 0 +#define TE_BOUNCE_SHELL 1 +#define TE_BOUNCE_SHOTSHELL 2 + +// Rendering constants +enum +{ + kRenderNormal, // src + kRenderTransColor, // c*a+dest*(1-a) + kRenderTransTexture, // src*a+dest*(1-a) + kRenderGlow, // src*a+dest -- No Z buffer checks + kRenderTransAlpha, // src*srca+dest*(1-srca) + kRenderTransAdd, // src*a+dest +}; + +enum +{ + kRenderFxNone = 0, + kRenderFxPulseSlow, + kRenderFxPulseFast, + kRenderFxPulseSlowWide, + kRenderFxPulseFastWide, + kRenderFxFadeSlow, + kRenderFxFadeFast, + kRenderFxSolidSlow, + kRenderFxSolidFast, + kRenderFxStrobeSlow, + kRenderFxStrobeFast, + kRenderFxStrobeFaster, + kRenderFxFlickerSlow, + kRenderFxFlickerFast, + kRenderFxNoDissipation, + kRenderFxDistort, // Distort/scale/translate flicker + kRenderFxHologram, // kRenderFxDistort + distance fade + kRenderFxDeadPlayer, // kRenderAmt is the player index + kRenderFxExplode, // Scale up really big! + kRenderFxGlowShell, // Glowing Shell + kRenderFxClampMinScale, // Keep this sprite from getting very small (SPRITES only!) + kRenderFxLightMultiplier, //CTM !!!CZERO added to tell the studiorender that the value in iuser2 is a lightmultiplier +}; + + +typedef unsigned int func_t; +typedef unsigned int string_t; + +typedef unsigned char byte; +typedef unsigned short word; +#define _DEF_BYTE_ + +#undef true +#undef false + +#ifndef __cplusplus +typedef enum {false, true} qboolean; +#else +typedef int qboolean; +#endif + +typedef struct +{ + byte r, g, b; +} color24; + +typedef struct +{ + unsigned r, g, b, a; +} colorVec; + +#ifdef _WIN32 +#pragma pack(push,2) +#endif + +typedef struct +{ + unsigned short r, g, b, a; +} PackedColorVec; + +#ifdef _WIN32 +#pragma pack(pop) +#endif +typedef struct link_s +{ + struct link_s *prev, *next; +} link_t; + +typedef struct edict_s edict_t; + +typedef struct +{ + vec3_t normal; + float dist; +} plane_t; + +typedef struct +{ + qboolean allsolid; // if true, plane is not valid + qboolean startsolid; // if true, the initial point was in a solid area + qboolean inopen, inwater; + float fraction; // time completed, 1.0 = didn't hit anything + vec3_t endpos; // final position + plane_t plane; // surface normal at impact + edict_t * ent; // entity the surface is on + int hitgroup; // 0 == generic, non zero is specific body part +} trace_t; + +#endif // CONST_H diff --git a/dep/rehlsdk/common/crc.h b/dep/rehlsdk/common/crc.h new file mode 100644 index 0000000..f7c6bb2 --- /dev/null +++ b/dep/rehlsdk/common/crc.h @@ -0,0 +1,38 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +/* crc.h */ +#pragma once + +#include "quakedef.h" + +typedef unsigned int CRC32_t; + +#ifdef __cplusplus +extern "C" +{ +#endif + +void CRC32_Init(CRC32_t *pulCRC); +CRC32_t CRC32_Final(CRC32_t pulCRC); +void CRC32_ProcessByte(CRC32_t *pulCRC, unsigned char ch); +void CRC32_ProcessBuffer(CRC32_t *pulCRC, void *pBuffer, int nBuffer); +BOOL CRC_File(CRC32_t *crcvalue, char *pszFileName); + +#ifdef __cplusplus +} +#endif + +byte COM_BlockSequenceCRCByte(byte *base, int length, int sequence); +int CRC_MapFile(CRC32_t *crcvalue, char *pszFileName); diff --git a/dep/rehlsdk/common/cvardef.h b/dep/rehlsdk/common/cvardef.h new file mode 100644 index 0000000..7bba22b --- /dev/null +++ b/dep/rehlsdk/common/cvardef.h @@ -0,0 +1,50 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef CVARDEF_H +#define CVARDEF_H + +#define FCVAR_ARCHIVE (1<<0) // set to cause it to be saved to vars.rc +#define FCVAR_USERINFO (1<<1) // changes the client's info string +#define FCVAR_SERVER (1<<2) // notifies players when changed +#define FCVAR_EXTDLL (1<<3) // defined by external DLL +#define FCVAR_CLIENTDLL (1<<4) // defined by the client dll +#define FCVAR_PROTECTED (1<<5) // It's a server cvar, but we don't send the data since it's a password, etc. Sends 1 if it's not bland/zero, 0 otherwise as value +#define FCVAR_SPONLY (1<<6) // This cvar cannot be changed by clients connected to a multiplayer server. +#define FCVAR_PRINTABLEONLY (1<<7) // This cvar's string cannot contain unprintable characters ( e.g., used for player name etc ). +#define FCVAR_UNLOGGED (1<<8) // If this is a FCVAR_SERVER, don't log changes to the log file / console if we are creating a log +#define FCVAR_NOEXTRAWHITEPACE (1<<9) // strip trailing/leading white space from this cvar + +typedef struct cvar_s +{ + const char *name; + char *string; + int flags; + float value; + struct cvar_s *next; +} cvar_t; + +using cvar_callback_t = void (*)(const char *pszNewValue); + +struct cvar_listener_t +{ + cvar_listener_t(const char *var_name, cvar_callback_t handler) : + func(handler), name(var_name) {} + + cvar_callback_t func; + const char *name; +}; + +#endif // CVARDEF_H diff --git a/dep/rehlsdk/common/demo_api.h b/dep/rehlsdk/common/demo_api.h new file mode 100644 index 0000000..8284a81 --- /dev/null +++ b/dep/rehlsdk/common/demo_api.h @@ -0,0 +1,31 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined ( DEMO_APIH ) +#define DEMO_APIH +#ifdef _WIN32 +#pragma once +#endif + +typedef struct demo_api_s +{ + int ( *IsRecording ) ( void ); + int ( *IsPlayingback ) ( void ); + int ( *IsTimeDemo ) ( void ); + void ( *WriteBuffer ) ( int size, unsigned char *buffer ); +} demo_api_t; + +extern demo_api_t demoapi; + +#endif diff --git a/dep/rehlsdk/common/director_cmds.h b/dep/rehlsdk/common/director_cmds.h new file mode 100644 index 0000000..4c8fdd5 --- /dev/null +++ b/dep/rehlsdk/common/director_cmds.h @@ -0,0 +1,38 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +// director_cmds.h +// sub commands for svc_director + +#define DRC_ACTIVE 0 // tells client that he's an spectator and will get director command +#define DRC_STATUS 1 // send status infos about proxy +#define DRC_CAMERA 2 // set the actual director camera position +#define DRC_EVENT 3 // informs the dircetor about ann important game event + + +#define DRC_FLAG_PRIO_MASK 0x0F // priorities between 0 and 15 (15 most important) +#define DRC_FLAG_SIDE (1<<4) +#define DRC_FLAG_DRAMATIC (1<<5) + + + +// commands of the director API function CallDirectorProc(...) + +#define DRCAPI_NOP 0 // no operation +#define DRCAPI_ACTIVE 1 // de/acivates director mode in engine +#define DRCAPI_STATUS 2 // request proxy information +#define DRCAPI_SETCAM 3 // set camera n to given position and angle +#define DRCAPI_GETCAM 4 // request camera n position and angle +#define DRCAPI_DIRPLAY 5 // set director time and play with normal speed +#define DRCAPI_DIRFREEZE 6 // freeze directo at this time +#define DRCAPI_SETVIEWMODE 7 // overview or 4 cameras +#define DRCAPI_SETOVERVIEWPARAMS 8 // sets parameter for overview mode +#define DRCAPI_SETFOCUS 9 // set the camera which has the input focus +#define DRCAPI_GETTARGETS 10 // queries engine for player list +#define DRCAPI_SETVIEWPOINTS 11 // gives engine all waypoints + + diff --git a/dep/rehlsdk/common/dlight.h b/dep/rehlsdk/common/dlight.h new file mode 100644 index 0000000..f869c98 --- /dev/null +++ b/dep/rehlsdk/common/dlight.h @@ -0,0 +1,33 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined ( DLIGHTH ) +#define DLIGHTH +#ifdef _WIN32 +#pragma once +#endif + +typedef struct dlight_s +{ + vec3_t origin; + float radius; + color24 color; + float die; // stop lighting after this time + float decay; // drop this each second + float minlight; // don't add when contributing less + int key; + qboolean dark; // subtracts light instead of adding +} dlight_t; + +#endif diff --git a/dep/rehlsdk/common/dll_state.h b/dep/rehlsdk/common/dll_state.h new file mode 100644 index 0000000..ad16296 --- /dev/null +++ b/dep/rehlsdk/common/dll_state.h @@ -0,0 +1,23 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +//DLL State Flags + +#define DLL_INACTIVE 0 // no dll +#define DLL_ACTIVE 1 // dll is running +#define DLL_PAUSED 2 // dll is paused +#define DLL_CLOSE 3 // closing down dll +#define DLL_TRANS 4 // Level Transition + +// DLL Pause reasons + +#define DLL_NORMAL 0 // User hit Esc or something. +#define DLL_QUIT 4 // Quit now +#define DLL_RESTART 5 // Switch to launcher for linux, does a quit but returns 1 + +// DLL Substate info ( not relevant ) +#define ENG_NORMAL (1<<0) diff --git a/dep/rehlsdk/common/entity_state.h b/dep/rehlsdk/common/entity_state.h new file mode 100644 index 0000000..2fe67c9 --- /dev/null +++ b/dep/rehlsdk/common/entity_state.h @@ -0,0 +1,198 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef ENTITY_STATE_H +#define ENTITY_STATE_H +#ifdef _WIN32 +#pragma once +#endif + +#include "const.h" + + +// For entityType below +#define ENTITY_NORMAL (1<<0) +#define ENTITY_BEAM (1<<1) +#define ENTITY_UNINITIALIZED (1<<30) + +// Entity state is used for the baseline and for delta compression of a packet of +// entities that is sent to a client. +typedef struct entity_state_s entity_state_t; + +struct entity_state_s +{ +// Fields which are filled in by routines outside of delta compression + int entityType; + // Index into cl_entities array for this entity. + int number; + float msg_time; + + // Message number last time the player/entity state was updated. + int messagenum; + + // Fields which can be transitted and reconstructed over the network stream + vec3_t origin; + vec3_t angles; + + int modelindex; + int sequence; + float frame; + int colormap; + short skin; + short solid; + int effects; + float scale; + + byte eflags; + + // Render information + int rendermode; + int renderamt; + color24 rendercolor; + int renderfx; + + int movetype; + float animtime; + float framerate; + int body; + byte controller[4]; + byte blending[4]; + vec3_t velocity; + + // Send bbox down to client for use during prediction. + vec3_t mins; + vec3_t maxs; + + int aiment; + // If owned by a player, the index of that player ( for projectiles ). + int owner; + + // Friction, for prediction. + float friction; + // Gravity multiplier + float gravity; + +// PLAYER SPECIFIC + int team; + int playerclass; + int health; + qboolean spectator; + int weaponmodel; + int gaitsequence; + // If standing on conveyor, e.g. + vec3_t basevelocity; + // Use the crouched hull, or the regular player hull. + int usehull; + // Latched buttons last time state updated. + int oldbuttons; + // -1 = in air, else pmove entity number + int onground; + int iStepLeft; + // How fast we are falling + float flFallVelocity; + + float fov; + int weaponanim; + + // Parametric movement overrides + vec3_t startpos; + vec3_t endpos; + float impacttime; + float starttime; + + // For mods + int iuser1; + int iuser2; + int iuser3; + int iuser4; + float fuser1; + float fuser2; + float fuser3; + float fuser4; + vec3_t vuser1; + vec3_t vuser2; + vec3_t vuser3; + vec3_t vuser4; +}; + +#include "pm_info.h" + +typedef struct clientdata_s +{ + vec3_t origin; + vec3_t velocity; + + int viewmodel; + vec3_t punchangle; + int flags; + int waterlevel; + int watertype; + vec3_t view_ofs; + float health; + + int bInDuck; + + int weapons; // remove? + + int flTimeStepSound; + int flDuckTime; + int flSwimTime; + int waterjumptime; + + float maxspeed; + + float fov; + int weaponanim; + + int m_iId; + int ammo_shells; + int ammo_nails; + int ammo_cells; + int ammo_rockets; + float m_flNextAttack; + + int tfstate; + + int pushmsec; + + int deadflag; + + char physinfo[ MAX_PHYSINFO_STRING ]; + + // For mods + int iuser1; + int iuser2; + int iuser3; + int iuser4; + float fuser1; + float fuser2; + float fuser3; + float fuser4; + vec3_t vuser1; + vec3_t vuser2; + vec3_t vuser3; + vec3_t vuser4; +} clientdata_t; + +#include "weaponinfo.h" + +typedef struct local_state_s +{ + entity_state_t playerstate; + clientdata_t client; + weapon_data_t weapondata[ 64 ]; +} local_state_t; + +#endif // ENTITY_STATE_H diff --git a/dep/rehlsdk/common/entity_types.h b/dep/rehlsdk/common/entity_types.h new file mode 100644 index 0000000..ff783df --- /dev/null +++ b/dep/rehlsdk/common/entity_types.h @@ -0,0 +1,26 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// entity_types.h +#if !defined( ENTITY_TYPESH ) +#define ENTITY_TYPESH + +#define ET_NORMAL 0 +#define ET_PLAYER 1 +#define ET_TEMPENTITY 2 +#define ET_BEAM 3 +// BMODEL or SPRITE that was split across BSP nodes +#define ET_FRAGMENTED 4 + +#endif // !ENTITY_TYPESH diff --git a/dep/rehlsdk/common/enums.h b/dep/rehlsdk/common/enums.h new file mode 100644 index 0000000..ad8bfe0 --- /dev/null +++ b/dep/rehlsdk/common/enums.h @@ -0,0 +1,28 @@ +/*** + * + * Copyright (c) 2009, Valve LLC. All rights reserved. + * + * This product contains software technology licensed from Id + * Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. + * All Rights Reserved. + * + * Use, distribution, and modification of this source code and/or resulting + * object code is restricted to non-commercial enhancements to products from + * Valve LLC. All other use, distribution, or modification is prohibited + * without written permission from Valve LLC. + * + ****/ + +#ifndef ENUMS_H +#define ENUMS_H + +// Used as array indexer +typedef enum netsrc_s +{ + NS_CLIENT = 0, + NS_SERVER, + NS_MULTICAST, // xxxMO + NS_MAX +} netsrc_t; + +#endif diff --git a/dep/rehlsdk/common/event_api.h b/dep/rehlsdk/common/event_api.h new file mode 100644 index 0000000..722dfe2 --- /dev/null +++ b/dep/rehlsdk/common/event_api.h @@ -0,0 +1,51 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined ( EVENT_APIH ) +#define EVENT_APIH +#ifdef _WIN32 +#pragma once +#endif + +#define EVENT_API_VERSION 1 + +typedef struct event_api_s +{ + int version; + void ( *EV_PlaySound ) ( int ent, float *origin, int channel, const char *sample, float volume, float attenuation, int fFlags, int pitch ); + void ( *EV_StopSound ) ( int ent, int channel, const char *sample ); + int ( *EV_FindModelIndex )( const char *pmodel ); + int ( *EV_IsLocal ) ( int playernum ); + int ( *EV_LocalPlayerDucking ) ( void ); + void ( *EV_LocalPlayerViewheight ) ( float * ); + void ( *EV_LocalPlayerBounds ) ( int hull, float *mins, float *maxs ); + int ( *EV_IndexFromTrace) ( struct pmtrace_s *pTrace ); + struct physent_s *( *EV_GetPhysent ) ( int idx ); + void ( *EV_SetUpPlayerPrediction ) ( int dopred, int bIncludeLocalClient ); + void ( *EV_PushPMStates ) ( void ); + void ( *EV_PopPMStates ) ( void ); + void ( *EV_SetSolidPlayers ) (int playernum); + void ( *EV_SetTraceHull ) ( int hull ); + void ( *EV_PlayerTrace ) ( float *start, float *end, int traceFlags, int ignore_pe, struct pmtrace_s *tr ); + void ( *EV_WeaponAnimation ) ( int sequence, int body ); + unsigned short ( *EV_PrecacheEvent ) ( int type, const char* psz ); + void ( *EV_PlaybackEvent ) ( int flags, const struct edict_s *pInvoker, unsigned short eventindex, float delay, float *origin, float *angles, float fparam1, float fparam2, int iparam1, int iparam2, int bparam1, int bparam2 ); + const char *( *EV_TraceTexture ) ( int ground, float *vstart, float *vend ); + void ( *EV_StopAllSounds ) ( int entnum, int entchannel ); + void ( *EV_KillEvents ) ( int entnum, const char *eventname ); +} event_api_t; + +extern event_api_t eventapi; + +#endif diff --git a/dep/rehlsdk/common/event_args.h b/dep/rehlsdk/common/event_args.h new file mode 100644 index 0000000..99dd49a --- /dev/null +++ b/dep/rehlsdk/common/event_args.h @@ -0,0 +1,50 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( EVENT_ARGSH ) +#define EVENT_ARGSH +#ifdef _WIN32 +#pragma once +#endif + +// Event was invoked with stated origin +#define FEVENT_ORIGIN ( 1<<0 ) + +// Event was invoked with stated angles +#define FEVENT_ANGLES ( 1<<1 ) + +typedef struct event_args_s +{ + int flags; + + // Transmitted + int entindex; + + float origin[3]; + float angles[3]; + float velocity[3]; + + int ducking; + + float fparam1; + float fparam2; + + int iparam1; + int iparam2; + + int bparam1; + int bparam2; +} event_args_t; + +#endif diff --git a/dep/rehlsdk/common/event_flags.h b/dep/rehlsdk/common/event_flags.h new file mode 100644 index 0000000..43f804f --- /dev/null +++ b/dep/rehlsdk/common/event_flags.h @@ -0,0 +1,47 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( EVENT_FLAGSH ) +#define EVENT_FLAGSH +#ifdef _WIN32 +#pragma once +#endif + +// Skip local host for event send. +#define FEV_NOTHOST (1<<0) + +// Send the event reliably. You must specify the origin and angles and use +// PLAYBACK_EVENT_FULL for this to work correctly on the server for anything +// that depends on the event origin/angles. I.e., the origin/angles are not +// taken from the invoking edict for reliable events. +#define FEV_RELIABLE (1<<1) + +// Don't restrict to PAS/PVS, send this event to _everybody_ on the server ( useful for stopping CHAN_STATIC +// sounds started by client event when client is not in PVS anymore ( hwguy in TFC e.g. ). +#define FEV_GLOBAL (1<<2) + +// If this client already has one of these events in its queue, just update the event instead of sending it as a duplicate +// +#define FEV_UPDATE (1<<3) + +// Only send to entity specified as the invoker +#define FEV_HOSTONLY (1<<4) + +// Only send if the event was created on the server. +#define FEV_SERVER (1<<5) + +// Only issue event client side ( from shared code ) +#define FEV_CLIENT (1<<6) + +#endif diff --git a/dep/rehlsdk/common/hltv.h b/dep/rehlsdk/common/hltv.h new file mode 100644 index 0000000..ea420a3 --- /dev/null +++ b/dep/rehlsdk/common/hltv.h @@ -0,0 +1,60 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +// hltv.h +// all shared consts between server, clients and proxy + +#ifndef HLTV_H +#define HLTV_H + +#define TYPE_CLIENT 0 // client is a normal HL client (default) +#define TYPE_PROXY 1 // client is another proxy +#define TYPE_DIRECTOR 2 +#define TYPE_COMMENTATOR 3 // client is a commentator +#define TYPE_DEMO 4 // client is a demo file + +// sub commands of svc_hltv: +#define HLTV_ACTIVE 0 // tells client that he's an spectator and will get director commands +#define HLTV_STATUS 1 // send status infos about proxy +#define HLTV_LISTEN 2 // tell client to listen to a multicast stream + +// director command types: +#define DRC_CMD_NONE 0 // NULL director command +#define DRC_CMD_START 1 // start director mode +#define DRC_CMD_EVENT 2 // informs about director command +#define DRC_CMD_MODE 3 // switches camera modes +#define DRC_CMD_CAMERA 4 // set fixed camera +#define DRC_CMD_TIMESCALE 5 // sets time scale +#define DRC_CMD_MESSAGE 6 // send HUD centerprint +#define DRC_CMD_SOUND 7 // plays a particular sound +#define DRC_CMD_STATUS 8 // HLTV broadcast status +#define DRC_CMD_BANNER 9 // set GUI banner +#define DRC_CMD_STUFFTEXT 10 // like the normal svc_stufftext but as director command +#define DRC_CMD_CHASE 11 // chase a certain player +#define DRC_CMD_INEYE 12 // view player through own eyes +#define DRC_CMD_MAP 13 // show overview map +#define DRC_CMD_CAMPATH 14 // define camera waypoint +#define DRC_CMD_WAYPOINTS 15 // start moving camera, inetranl message + +#define DRC_CMD_LAST 15 + +// DRC_CMD_EVENT event flags +#define DRC_FLAG_PRIO_MASK 0x0F // priorities between 0 and 15 (15 most important) +#define DRC_FLAG_SIDE (1<<4) // +#define DRC_FLAG_DRAMATIC (1<<5) // is a dramatic scene +#define DRC_FLAG_SLOWMOTION (1<<6) // would look good in SloMo +#define DRC_FLAG_FACEPLAYER (1<<7) // player is doning something (reload/defuse bomb etc) +#define DRC_FLAG_INTRO (1<<8) // is a introduction scene +#define DRC_FLAG_FINAL (1<<9) // is a final scene +#define DRC_FLAG_NO_RANDOM (1<<10) // don't randomize event data + +// DRC_CMD_WAYPOINT flags +#define DRC_FLAG_STARTPATH 1 // end with speed 0.0 +#define DRC_FLAG_SLOWSTART 2 // start with speed 0.0 +#define DRC_FLAG_SLOWEND 4 // end with speed 0.0 + +#endif // HLTV_H diff --git a/dep/rehlsdk/common/in_buttons.h b/dep/rehlsdk/common/in_buttons.h new file mode 100644 index 0000000..4196a2d --- /dev/null +++ b/dep/rehlsdk/common/in_buttons.h @@ -0,0 +1,38 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef IN_BUTTONS_H +#define IN_BUTTONS_H +#ifdef _WIN32 +#pragma once +#endif + +#define IN_ATTACK (1 << 0) +#define IN_JUMP (1 << 1) +#define IN_DUCK (1 << 2) +#define IN_FORWARD (1 << 3) +#define IN_BACK (1 << 4) +#define IN_USE (1 << 5) +#define IN_CANCEL (1 << 6) +#define IN_LEFT (1 << 7) +#define IN_RIGHT (1 << 8) +#define IN_MOVELEFT (1 << 9) +#define IN_MOVERIGHT (1 << 10) +#define IN_ATTACK2 (1 << 11) +#define IN_RUN (1 << 12) +#define IN_RELOAD (1 << 13) +#define IN_ALT1 (1 << 14) +#define IN_SCORE (1 << 15) // Used by client.dll for when scoreboard is held down + +#endif // IN_BUTTONS_H diff --git a/dep/rehlsdk/common/ivoicetweak.h b/dep/rehlsdk/common/ivoicetweak.h new file mode 100644 index 0000000..da568c5 --- /dev/null +++ b/dep/rehlsdk/common/ivoicetweak.h @@ -0,0 +1,38 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#ifndef IVOICETWEAK_H +#define IVOICETWEAK_H +#ifdef _WIN32 +#pragma once +#endif + +// These provide access to the voice controls. +typedef enum +{ + MicrophoneVolume=0, // values 0-1. + OtherSpeakerScale, // values 0-1. Scales how loud other players are. + MicBoost, // 20 db gain to voice input +} VoiceTweakControl; + + +typedef struct IVoiceTweak_s +{ + // These turn voice tweak mode on and off. While in voice tweak mode, the user's voice is echoed back + // without sending to the server. + int (*StartVoiceTweakMode)(); // Returns 0 on error. + void (*EndVoiceTweakMode)(); + + // Get/set control values. + void (*SetControlFloat)(VoiceTweakControl iControl, float value); + float (*GetControlFloat)(VoiceTweakControl iControl); + + int (*GetSpeakingVolume)(); +} IVoiceTweak; + + +#endif // IVOICETWEAK_H diff --git a/dep/rehlsdk/common/kbutton.h b/dep/rehlsdk/common/kbutton.h new file mode 100644 index 0000000..5607568 --- /dev/null +++ b/dep/rehlsdk/common/kbutton.h @@ -0,0 +1,41 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef KBUTTON_H +#define KBUTTON_H +#ifdef _WIN32 +#pragma once +#endif + +typedef struct kbutton_s +{ + int down[2]; + int state; +} kbutton_t; + +#endif // KBUTTON_H diff --git a/dep/rehlsdk/common/mathlib.h b/dep/rehlsdk/common/mathlib.h new file mode 100644 index 0000000..097fa1c --- /dev/null +++ b/dep/rehlsdk/common/mathlib.h @@ -0,0 +1,132 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef MATHLIB_H +#define MATHLIB_H +#ifdef _WIN32 +#pragma once +#endif + +typedef float vec_t; + +#if !defined DID_VEC3_T_DEFINE && !defined vec3_t +#define DID_VEC3_T_DEFINE +typedef vec_t vec3_t[3]; +#endif + +typedef vec_t vec4_t[4]; +typedef int fixed16_t; + +typedef union DLONG_u +{ + int i[2]; + double d; + float f; +} DLONG; + +#define M_PI 3.14159265358979323846 + +#ifdef __cplusplus +#ifdef min +#undef min +#endif + +#ifdef max +#undef max +#endif + +#ifdef clamp +#undef clamp +#endif + +template +inline T min(T a, T b) +{ + return (a < b) ? a : b; +} + +template +inline T max(T a, T b) +{ + return (a < b) ? b : a; +} + +template +inline T clamp(T a, T min, T max) +{ + return (a > max) ? max : (a < min) ? min : a; +} + +template +inline T M_min(T a, T b) +{ + return min(a, b); +} + +template +inline T M_max(T a, T b) +{ + return max(a, b); +} + +template +inline T M_clamp(T a, T min, T max) +{ + return clamp(a, min, max); +} + +template +inline double M_sqrt(T value) +{ + return sqrt(value); +} + +template +inline T bswap(T s) +{ + switch (sizeof(T)) + { + case 2: {auto res = __builtin_bswap16(*(uint16 *)&s); return *(T *)&res; } + case 4: {auto res = __builtin_bswap32(*(uint32 *)&s); return *(T *)&res; } + case 8: {auto res = __builtin_bswap64(*(uint64 *)&s); return *(T *)&res; } + default: return s; + } +} +#else // __cplusplus +#ifndef max +#define max(a,b) (((a) > (b)) ? (a) : (b)) +#endif + +#ifndef min +#define min(a,b) (((a) < (b)) ? (a) : (b)) +#endif + +#define clamp(val, min, max) (((val) > (max)) ? (max) : (((val) < (min)) ? (min) : (val))) +#endif // __cplusplus + +#endif // MATHLIB_H diff --git a/dep/rehlsdk/common/md5.h b/dep/rehlsdk/common/md5.h new file mode 100644 index 0000000..637ba0f --- /dev/null +++ b/dep/rehlsdk/common/md5.h @@ -0,0 +1,34 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#pragma once + +#include + +// MD5 Hash +typedef struct +{ + unsigned int buf[4]; + unsigned int bits[2]; + unsigned char in[64]; +} MD5Context_t; + +void MD5Init(MD5Context_t *ctx); +void MD5Update(MD5Context_t *ctx, const unsigned char *buf, unsigned int len); +void MD5Final(unsigned char digest[16], MD5Context_t *ctx); +void MD5Transform(unsigned int buf[4], const unsigned int in[16]); + +BOOL MD5_Hash_File(unsigned char digest[16], char *pszFileName, BOOL bUsefopen, BOOL bSeed, unsigned int seed[4]); +char *MD5_Print(unsigned char hash[16]); diff --git a/dep/rehlsdk/common/net_api.h b/dep/rehlsdk/common/net_api.h new file mode 100644 index 0000000..9551d18 --- /dev/null +++ b/dep/rehlsdk/common/net_api.h @@ -0,0 +1,99 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#if !defined( NET_APIH ) +#define NET_APIH +#ifdef _WIN32 +#pragma once +#endif + +#if !defined ( NETADRH ) +#include "netadr.h" +#endif + +#define NETAPI_REQUEST_SERVERLIST ( 0 ) // Doesn't need a remote address +#define NETAPI_REQUEST_PING ( 1 ) +#define NETAPI_REQUEST_RULES ( 2 ) +#define NETAPI_REQUEST_PLAYERS ( 3 ) +#define NETAPI_REQUEST_DETAILS ( 4 ) + +// Set this flag for things like broadcast requests, etc. where the engine should not +// kill the request hook after receiving the first response +#define FNETAPI_MULTIPLE_RESPONSE ( 1<<0 ) + +typedef void ( *net_api_response_func_t ) ( struct net_response_s *response ); + +#define NET_SUCCESS ( 0 ) +#define NET_ERROR_TIMEOUT ( 1<<0 ) +#define NET_ERROR_PROTO_UNSUPPORTED ( 1<<1 ) +#define NET_ERROR_UNDEFINED ( 1<<2 ) + +typedef struct net_adrlist_s +{ + struct net_adrlist_s *next; + netadr_t remote_address; +} net_adrlist_t; + +typedef struct net_response_s +{ + // NET_SUCCESS or an error code + int error; + + // Context ID + int context; + // Type + int type; + + // Server that is responding to the request + netadr_t remote_address; + + // Response RTT ping time + double ping; + // Key/Value pair string ( separated by backlash \ characters ) + // WARNING: You must copy this buffer in the callback function, because it is freed + // by the engine right after the call!!!! + // ALSO: For NETAPI_REQUEST_SERVERLIST requests, this will be a pointer to a linked list of net_adrlist_t's + void *response; +} net_response_t; + +typedef struct net_status_s +{ + // Connected to remote server? 1 == yes, 0 otherwise + int connected; + // Client's IP address + netadr_t local_address; + // Address of remote server + netadr_t remote_address; + // Packet Loss ( as a percentage ) + int packet_loss; + // Latency, in seconds ( multiply by 1000.0 to get milliseconds ) + double latency; + // Connection time, in seconds + double connection_time; + // Rate setting ( for incoming data ) + double rate; +} net_status_t; + +typedef struct net_api_s +{ + // APIs + void ( *InitNetworking )( void ); + void ( *Status ) ( struct net_status_s *status ); + void ( *SendRequest) ( int context, int request, int flags, double timeout, struct netadr_s *remote_address, net_api_response_func_t response ); + void ( *CancelRequest ) ( int context ); + void ( *CancelAllRequests ) ( void ); + char *( *AdrToString ) ( struct netadr_s *a ); + int ( *CompareAdr ) ( struct netadr_s *a, struct netadr_s *b ); + int ( *StringToAdr ) ( char *s, struct netadr_s *a ); + const char *( *ValueForKey ) ( const char *s, const char *key ); + void ( *RemoveKey ) ( char *s, const char *key ); + void ( *SetValueForKey ) (char *s, const char *key, const char *value, int maxsize ); +} net_api_t; + +extern net_api_t netapi; + +#endif // NET_APIH diff --git a/dep/rehlsdk/common/netadr.h b/dep/rehlsdk/common/netadr.h new file mode 100644 index 0000000..0a468d2 --- /dev/null +++ b/dep/rehlsdk/common/netadr.h @@ -0,0 +1,40 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef NETADR_H +#define NETADR_H +#ifdef _WIN32 +#pragma once +#endif + +typedef enum +{ + NA_UNUSED, + NA_LOOPBACK, + NA_BROADCAST, + NA_IP, + NA_IPX, + NA_BROADCAST_IPX, +} netadrtype_t; + +typedef struct netadr_s +{ + netadrtype_t type; + unsigned char ip[4]; + unsigned char ipx[10]; + unsigned short port; +} netadr_t; + +#endif // NETADR_H diff --git a/dep/rehlsdk/common/netapi.cpp b/dep/rehlsdk/common/netapi.cpp new file mode 100644 index 0000000..7c69449 --- /dev/null +++ b/dep/rehlsdk/common/netapi.cpp @@ -0,0 +1,208 @@ +#include +#include + +#ifdef _WIN32 + #include "winsock.h" +#else + #include + #include + #include + #include + #include + #include +#endif // _WIN32 + +#include "netapi.h" + +class CNetAPI: public INetAPI { +public: + virtual void NetAdrToSockAddr(netadr_t *a, struct sockaddr *s); + virtual void SockAddrToNetAdr(struct sockaddr *s, netadr_t *a); + + virtual char *AdrToString(netadr_t *a); + virtual bool StringToAdr(const char *s, netadr_t *a); + + virtual void GetSocketAddress(int socket, netadr_t *a); + virtual bool CompareAdr(netadr_t *a, netadr_t *b); + virtual void GetLocalIP(netadr_t *a); +}; + +// Expose interface +CNetAPI g_NetAPI; +INetAPI *net = (INetAPI *)&g_NetAPI; + +void CNetAPI::NetAdrToSockAddr(netadr_t *a, struct sockaddr *s) +{ + memset(s, 0, sizeof(*s)); + + if (a->type == NA_BROADCAST) + { + ((struct sockaddr_in *)s)->sin_family = AF_INET; + ((struct sockaddr_in *)s)->sin_port = a->port; + ((struct sockaddr_in *)s)->sin_addr.s_addr = INADDR_BROADCAST; + } + else if (a->type == NA_IP) + { + ((struct sockaddr_in *)s)->sin_family = AF_INET; + ((struct sockaddr_in *)s)->sin_addr.s_addr = *(int *)&a->ip; + ((struct sockaddr_in *)s)->sin_port = a->port; + } +} + +void CNetAPI::SockAddrToNetAdr(struct sockaddr *s, netadr_t *a) +{ + if (s->sa_family == AF_INET) + { + a->type = NA_IP; + *(int *)&a->ip = ((struct sockaddr_in *)s)->sin_addr.s_addr; + a->port = ((struct sockaddr_in *)s)->sin_port; + } +} + +char *CNetAPI::AdrToString(netadr_t *a) +{ + static char s[64]; + memset(s, 0, sizeof(s)); + + if (a) + { + if (a->type == NA_LOOPBACK) + { + sprintf(s, "loopback"); + } + else if (a->type == NA_IP) + { + sprintf(s, "%i.%i.%i.%i:%i", a->ip[0], a->ip[1], a->ip[2], a->ip[3], ntohs(a->port)); + } + } + + return s; +} + +bool StringToSockaddr(const char *s, struct sockaddr *sadr) +{ + struct hostent *h; + char *colon; + char copy[128]; + struct sockaddr_in *p; + + memset(sadr, 0, sizeof(*sadr)); + + p = (struct sockaddr_in *)sadr; + p->sin_family = AF_INET; + p->sin_port = 0; + + strcpy(copy, s); + + // strip off a trailing :port if present + for (colon = copy ; *colon ; colon++) + { + if (*colon == ':') + { + // terminate + *colon = '\0'; + + // Start at next character + p->sin_port = htons((short)atoi(colon + 1)); + } + } + + // Numeric IP, no DNS + if (copy[0] >= '0' && copy[0] <= '9' && strstr(copy, ".")) + { + *(int *)&p->sin_addr = inet_addr(copy); + } + else + { + // DNS it + if (!(h = gethostbyname(copy))) + { + return false; + } + + // Use first result + *(int *)&p->sin_addr = *(int *)h->h_addr_list[0]; + } + + return true; +} + +bool CNetAPI::StringToAdr(const char *s, netadr_t *a) +{ + struct sockaddr sadr; + if (!strcmp(s, "localhost")) + { + memset(a, 0, sizeof(*a)); + a->type = NA_LOOPBACK; + return true; + } + + if (!StringToSockaddr(s, &sadr)) + { + return false; + } + + SockAddrToNetAdr(&sadr, a); + return true; +} + +// Lookup the IP address for the specified IP socket +void CNetAPI::GetSocketAddress(int socket, netadr_t *a) +{ + char buff[512]; + struct sockaddr_in address; + int namelen; + + memset(a, 0, sizeof(*a)); + gethostname(buff, sizeof(buff)); + + // Ensure that it doesn't overrun the buffer + buff[sizeof buff - 1] = '\0'; + StringToAdr(buff, a); + + namelen = sizeof(address); + if (getsockname(socket, (struct sockaddr *)&address, (int *)&namelen) == 0) + { + a->port = address.sin_port; + } +} + +bool CNetAPI::CompareAdr(netadr_t *a, netadr_t *b) +{ + if (a->type != b->type) + { + return false; + } + + if (a->type == NA_LOOPBACK) + { + return true; + } + + if (a->type == NA_IP && + a->ip[0] == b->ip[0] && + a->ip[1] == b->ip[1] && + a->ip[2] == b->ip[2] && + a->ip[3] == b->ip[3] && + a->port == b->port) + { + return true; + } + + return false; +} + +void CNetAPI::GetLocalIP(netadr_t *a) +{ + char s[64]; + if(!::gethostname(s, 64)) + { + struct hostent *localip = ::gethostbyname(s); + if(localip) + { + a->type = NA_IP; + a->port = 0; + memcpy(a->ip, localip->h_addr_list[0], 4); + } + } +} diff --git a/dep/rehlsdk/common/netapi.h b/dep/rehlsdk/common/netapi.h new file mode 100644 index 0000000..8401c92 --- /dev/null +++ b/dep/rehlsdk/common/netapi.h @@ -0,0 +1,25 @@ +#ifndef NETAPI_H +#define NETAPI_H +#ifdef _WIN32 +#pragma once +#endif + +#include "netadr.h" + +class INetAPI { +public: + virtual void NetAdrToSockAddr(netadr_t *a, struct sockaddr *s) = 0; // Convert a netadr_t to sockaddr + virtual void SockAddrToNetAdr(struct sockaddr *s, netadr_t *a) = 0; // Convert a sockaddr to netadr_t + + virtual char *AdrToString(netadr_t *a) = 0; // Convert a netadr_t to a string + virtual bool StringToAdr(const char *s, netadr_t *a) = 0; // Convert a string address to a netadr_t, doing DNS if needed + virtual void GetSocketAddress(int socket, netadr_t *a) = 0; // Look up IP address for socket + virtual bool CompareAdr(netadr_t *a, netadr_t *b) = 0; + + // return the IP of the local host + virtual void GetLocalIP(netadr_t *a) = 0; +}; + +extern INetAPI *net; + +#endif // NETAPI_H diff --git a/dep/rehlsdk/common/nowin.h b/dep/rehlsdk/common/nowin.h new file mode 100644 index 0000000..0b1f577 --- /dev/null +++ b/dep/rehlsdk/common/nowin.h @@ -0,0 +1,16 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#ifndef INC_NOWIN_H +#define INC_NOWIN_H +#ifndef _WIN32 + +#include +#include + +#endif //!_WIN32 +#endif //INC_NOWIN_H diff --git a/dep/rehlsdk/common/parsemsg.cpp b/dep/rehlsdk/common/parsemsg.cpp new file mode 100644 index 0000000..6742db2 --- /dev/null +++ b/dep/rehlsdk/common/parsemsg.cpp @@ -0,0 +1,259 @@ +/*** +* +* Copyright (c) 1999, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// +// parsemsg.cpp +// +//-------------------------------------------------------------------------------------------------------------- +#include "parsemsg.h" +#include + +typedef unsigned char byte; +#define true 1 + +static byte *gpBuf; +static int giSize; +static int giRead; +static int giBadRead; + +int READ_OK( void ) +{ + return !giBadRead; +} + +void BEGIN_READ( void *buf, int size ) +{ + giRead = 0; + giBadRead = 0; + giSize = size; + gpBuf = (byte*)buf; +} + + +int READ_CHAR( void ) +{ + int c; + + if (giRead + 1 > giSize) + { + giBadRead = true; + return -1; + } + + c = (signed char)gpBuf[giRead]; + giRead++; + + return c; +} + +int READ_BYTE( void ) +{ + int c; + + if (giRead+1 > giSize) + { + giBadRead = true; + return -1; + } + + c = (unsigned char)gpBuf[giRead]; + giRead++; + + return c; +} + +int READ_SHORT( void ) +{ + int c; + + if (giRead+2 > giSize) + { + giBadRead = true; + return -1; + } + + c = (short)( gpBuf[giRead] + ( gpBuf[giRead+1] << 8 ) ); + + giRead += 2; + + return c; +} + +int READ_WORD( void ) +{ + return READ_SHORT(); +} + + +int READ_LONG( void ) +{ + int c; + + if (giRead+4 > giSize) + { + giBadRead = true; + return -1; + } + + c = gpBuf[giRead] + (gpBuf[giRead + 1] << 8) + (gpBuf[giRead + 2] << 16) + (gpBuf[giRead + 3] << 24); + + giRead += 4; + + return c; +} + +float READ_FLOAT( void ) +{ + union + { + byte b[4]; + float f; + int l; + } dat; + + dat.b[0] = gpBuf[giRead]; + dat.b[1] = gpBuf[giRead+1]; + dat.b[2] = gpBuf[giRead+2]; + dat.b[3] = gpBuf[giRead+3]; + giRead += 4; + +// dat.l = LittleLong (dat.l); + + return dat.f; +} + +char* READ_STRING( void ) +{ + static char string[2048]; + int l,c; + + string[0] = 0; + + l = 0; + do + { + if ( giRead+1 > giSize ) + break; // no more characters + + c = READ_CHAR(); + if (c == -1 || c == 0) + break; + string[l] = c; + l++; + } while (l < sizeof(string)-1); + + string[l] = 0; + + return string; +} + +float READ_COORD( void ) +{ + return (float)(READ_SHORT() * (1.0/8)); +} + +float READ_ANGLE( void ) +{ + return (float)(READ_CHAR() * (360.0/256)); +} + +float READ_HIRESANGLE( void ) +{ + return (float)(READ_SHORT() * (360.0/65536)); +} + +//-------------------------------------------------------------------------------------------------------------- +BufferWriter::BufferWriter() +{ + Init( NULL, 0 ); +} + +//-------------------------------------------------------------------------------------------------------------- +BufferWriter::BufferWriter( unsigned char *buffer, int bufferLen ) +{ + Init( buffer, bufferLen ); +} + +//-------------------------------------------------------------------------------------------------------------- +void BufferWriter::Init( unsigned char *buffer, int bufferLen ) +{ + m_overflow = false; + m_buffer = buffer; + m_remaining = bufferLen; + m_overallLength = bufferLen; +} + +//-------------------------------------------------------------------------------------------------------------- +void BufferWriter::WriteByte( unsigned char data ) +{ + if (!m_buffer || !m_remaining) + { + m_overflow = true; + return; + } + + *m_buffer = data; + ++m_buffer; + --m_remaining; +} + +//-------------------------------------------------------------------------------------------------------------- +void BufferWriter::WriteLong( int data ) +{ + if (!m_buffer || m_remaining < 4) + { + m_overflow = true; + return; + } + + m_buffer[0] = data&0xff; + m_buffer[1] = (data>>8)&0xff; + m_buffer[2] = (data>>16)&0xff; + m_buffer[3] = data>>24; + m_buffer += 4; + m_remaining -= 4; +} + +//-------------------------------------------------------------------------------------------------------------- +void BufferWriter::WriteString( const char *str ) +{ + if (!m_buffer || !m_remaining) + { + m_overflow = true; + return; + } + + if (!str) + str = ""; + + int len = strlen(str)+1; + if ( len > m_remaining ) + { + m_overflow = true; + str = ""; + len = 1; + } + + strcpy((char *)m_buffer, str); + m_remaining -= len; + m_buffer += len; +} + +//-------------------------------------------------------------------------------------------------------------- +int BufferWriter::GetSpaceUsed() +{ + return m_overallLength - m_remaining; +} + +//-------------------------------------------------------------------------------------------------------------- diff --git a/dep/rehlsdk/common/parsemsg.h b/dep/rehlsdk/common/parsemsg.h new file mode 100644 index 0000000..be7affc --- /dev/null +++ b/dep/rehlsdk/common/parsemsg.h @@ -0,0 +1,66 @@ +/*** +* +* Copyright (c) 1999, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// +// parsemsg.h +// MDC - copying from cstrike\cl_dll so career-mode stuff can catch messages +// in this dll. (and C++ifying it) +// + +#ifndef PARSEMSG_H +#define PARSEMSG_H + +#define ASSERT( x ) +//-------------------------------------------------------------------------------------------------------------- +void BEGIN_READ( void *buf, int size ); +int READ_CHAR( void ); +int READ_BYTE( void ); +int READ_SHORT( void ); +int READ_WORD( void ); +int READ_LONG( void ); +float READ_FLOAT( void ); +char* READ_STRING( void ); +float READ_COORD( void ); +float READ_ANGLE( void ); +float READ_HIRESANGLE( void ); +int READ_OK( void ); + +//-------------------------------------------------------------------------------------------------------------- +class BufferWriter +{ +public: + BufferWriter(); + BufferWriter( unsigned char *buffer, int bufferLen ); + void Init( unsigned char *buffer, int bufferLen ); + + void WriteByte( unsigned char data ); + void WriteLong( int data ); + void WriteString( const char *str ); + + bool HasOverflowed(); + int GetSpaceUsed(); + +protected: + unsigned char *m_buffer; + int m_remaining; + bool m_overflow; + int m_overallLength; +}; + +//-------------------------------------------------------------------------------------------------------------- + +#endif // PARSEMSG_H + + + diff --git a/dep/rehlsdk/common/particledef.h b/dep/rehlsdk/common/particledef.h new file mode 100644 index 0000000..7e4043a --- /dev/null +++ b/dep/rehlsdk/common/particledef.h @@ -0,0 +1,57 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( PARTICLEDEFH ) +#define PARTICLEDEFH +#ifdef _WIN32 +#pragma once +#endif + +typedef enum { + pt_static, + pt_grav, + pt_slowgrav, + pt_fire, + pt_explode, + pt_explode2, + pt_blob, + pt_blob2, + pt_vox_slowgrav, + pt_vox_grav, + pt_clientcustom // Must have callback function specified +} ptype_t; + +// !!! if this is changed, it must be changed in d_ifacea.h too !!! +typedef struct particle_s +{ +// driver-usable fields + vec3_t org; + short color; + short packedColor; +// drivers never touch the following fields + struct particle_s *next; + vec3_t vel; + float ramp; + float die; + ptype_t type; + void (*deathfunc)( struct particle_s *particle ); + + // for pt_clientcusttom, we'll call this function each frame + void (*callback)( struct particle_s *particle, float frametime ); + + // For deathfunc, etc. + unsigned char context; +} particle_t; + +#endif diff --git a/dep/rehlsdk/common/pmtrace.h b/dep/rehlsdk/common/pmtrace.h new file mode 100644 index 0000000..1784e9c --- /dev/null +++ b/dep/rehlsdk/common/pmtrace.h @@ -0,0 +1,43 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( PMTRACEH ) +#define PMTRACEH +#ifdef _WIN32 +#pragma once +#endif + +typedef struct +{ + vec3_t normal; + float dist; +} pmplane_t; + +typedef struct pmtrace_s pmtrace_t; + +struct pmtrace_s +{ + qboolean allsolid; // if true, plane is not valid + qboolean startsolid; // if true, the initial point was in a solid area + qboolean inopen, inwater; // End point is in empty space or in water + float fraction; // time completed, 1.0 = didn't hit anything + vec3_t endpos; // final position + pmplane_t plane; // surface normal at impact + int ent; // entity at impact + vec3_t deltavelocity; // Change in player's velocity caused by impact. + // Only run on server. + int hitgroup; +}; + +#endif diff --git a/dep/rehlsdk/common/port.h b/dep/rehlsdk/common/port.h new file mode 100644 index 0000000..a0838a7 --- /dev/null +++ b/dep/rehlsdk/common/port.h @@ -0,0 +1,119 @@ +// port.h: portability helper +// +////////////////////////////////////////////////////////////////////// + +#pragma once + +#include "archtypes.h" // DAL + +#ifdef _WIN32 + + // Insert your headers here + #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers + #define WIN32_EXTRA_LEAN + + #include "winsani_in.h" + #include + #include "winsani_out.h" + + #include + #include + #include + +#else // _WIN32 + + #include + #include + #include // exit() + #include // strncpy() + #include // tolower() + #include + #include + #include + #include + + typedef unsigned char BYTE; + + typedef int32 LONG; + //typedef uint32 ULONG; + + #ifndef ARCHTYPES_H + typedef uint32 ULONG; + #endif + + typedef void *HANDLE; + + #ifndef HMODULE + typedef void *HMODULE; + #endif + + typedef char * LPSTR; + + #define __cdecl + + + #ifdef __linux__ + typedef struct POINT_s + { + int x; + int y; + } POINT; + typedef void *HINSTANCE; + typedef void *HWND; + typedef void *HDC; + typedef void *HGLRC; + + typedef struct RECT_s + { + int left; + int right; + int top; + int bottom; + } RECT; + #endif + + + #ifdef __cplusplus + + //#undef FALSE + //#undef TRUE + + #ifdef OSX + //#else + //const bool FALSE = false; + //const bool TRUE = true; + #endif + #endif + + #ifndef NULL + #ifdef __cplusplus + #define NULL 0 + #else + #define NULL ((void *)0) + #endif + #endif + + #ifdef __cplusplus + inline int ioctlsocket( int d, int cmd, uint32 *argp ) { return ioctl( d, cmd, argp ); } + inline int closesocket( int fd ) { return close( fd ); } + inline char * GetCurrentDirectory( size_t size, char * buf ) { return getcwd( buf, size ); } + inline int WSAGetLastError() { return errno; } + + inline void DebugBreak( void ) { exit( 1 ); } + #endif + + extern char g_szEXEName[ 4096 ]; + + #define _snprintf snprintf + + #if defined(OSX) + #define SO_ARCH_SUFFIX ".dylib" + #else + #if defined ( __x86_64__ ) + #define SO_ARCH_SUFFIX "_amd64.so" + #else + #define SO_ARCH_SUFFIX ".so" + #endif + #endif +#endif + diff --git a/dep/rehlsdk/common/qfont.h b/dep/rehlsdk/common/qfont.h new file mode 100644 index 0000000..2fc8129 --- /dev/null +++ b/dep/rehlsdk/common/qfont.h @@ -0,0 +1,41 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( QFONTH ) +#define QFONTH +#ifdef _WIN32 +#pragma once +#endif + +// Font stuff + +#define NUM_GLYPHS 256 +// does not exist: // #include "basetypes.h" + +typedef struct +{ + short startoffset; + short charwidth; +} charinfo; + +typedef struct qfont_s +{ + int width, height; + int rowcount; + int rowheight; + charinfo fontinfo[ NUM_GLYPHS ]; + unsigned char data[4]; +} qfont_t; + +#endif // qfont.h diff --git a/dep/rehlsdk/common/qlimits.h b/dep/rehlsdk/common/qlimits.h new file mode 100644 index 0000000..1a67bd5 --- /dev/null +++ b/dep/rehlsdk/common/qlimits.h @@ -0,0 +1,44 @@ +//========= Copyright (c) 1996-2002, Valve LLC, All rights reserved. ========== +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#ifndef QLIMITS_H +#define QLIMITS_H + +#if defined( _WIN32 ) +#pragma once +#endif + +// DATA STRUCTURE INFO + +#define MAX_NUM_ARGVS 50 + +// SYSTEM INFO +#define MAX_QPATH 64 // max length of a game pathname +#define MAX_OSPATH 260 // max length of a filesystem pathname + +#define ON_EPSILON 0.1 // point on plane side epsilon + +#define MAX_LIGHTSTYLE_INDEX_BITS 6 +#define MAX_LIGHTSTYLES (1< + +#if !defined(_WIN32) +void NORETURN Sys_Error(const char *error, ...); + +// This file adds the necessary compatibility tricks to avoid symbols with +// version GLIBCXX_3.4.16 and bigger, keeping binary compatibility with libstdc++ 4.6.1. +namespace std +{ + // We shouldn't be throwing exceptions at all, but it sadly turns out we call STL (inline) functions that do. + void __throw_out_of_range_fmt(const char *fmt, ...) + { + va_list ap; + char buf[1024]; // That should be big enough. + + va_start(ap, fmt); + vsnprintf(buf, sizeof(buf), fmt, ap); + buf[sizeof(buf) - 1] = '\0'; + va_end(ap); + + Sys_Error(buf); + } +}; // namespace std + +// Technically, this symbol is not in GLIBCXX_3.4.20, but in CXXABI_1.3.8, +// but that's equivalent, version-wise. Those calls are added by the compiler +// itself on `new Class[n]` calls. +extern "C" +void __cxa_throw_bad_array_new_length() +{ + Sys_Error("Bad array new length."); +} +#endif // !defined(_WIN32) diff --git a/dep/rehlsdk/common/studio_event.h b/dep/rehlsdk/common/studio_event.h new file mode 100644 index 0000000..c79c210 --- /dev/null +++ b/dep/rehlsdk/common/studio_event.h @@ -0,0 +1,29 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( STUDIO_EVENTH ) +#define STUDIO_EVENTH +#ifdef _WIN32 +#pragma once +#endif + +typedef struct mstudioevent_s +{ + int frame; + int event; + int type; + char options[64]; +} mstudioevent_t; + +#endif // STUDIO_EVENTH diff --git a/dep/rehlsdk/common/textconsole.cpp b/dep/rehlsdk/common/textconsole.cpp new file mode 100644 index 0000000..45d13d7 --- /dev/null +++ b/dep/rehlsdk/common/textconsole.cpp @@ -0,0 +1,392 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "precompiled.h" + +bool CTextConsole::Init(IBaseSystem *system) +{ + // NULL or a valid base system interface + m_System = system; + + Q_memset(m_szConsoleText, 0, sizeof(m_szConsoleText)); + m_nConsoleTextLen = 0; + m_nCursorPosition = 0; + + Q_memset(m_szSavedConsoleText, 0, sizeof(m_szSavedConsoleText)); + m_nSavedConsoleTextLen = 0; + + Q_memset(m_aszLineBuffer, 0, sizeof(m_aszLineBuffer)); + m_nTotalLines = 0; + m_nInputLine = 0; + m_nBrowseLine = 0; + + // these are log messages, not related to console + Sys_Printf("\n"); + Sys_Printf("Console initialized.\n"); + + m_ConsoleVisible = true; + + return true; +} + +void CTextConsole::InitSystem(IBaseSystem *system) +{ + m_System = system; +} + +void CTextConsole::SetVisible(bool visible) +{ + m_ConsoleVisible = visible; +} + +bool CTextConsole::IsVisible() +{ + return m_ConsoleVisible; +} + +void CTextConsole::ShutDown() +{ + ; +} + +void CTextConsole::Print(char *pszMsg) +{ + if (m_nConsoleTextLen) + { + int nLen = m_nConsoleTextLen; + while (nLen--) + { + PrintRaw("\b \b"); + } + } + + PrintRaw(pszMsg); + + if (m_nConsoleTextLen) + { + PrintRaw(m_szConsoleText, m_nConsoleTextLen); + } + + UpdateStatus(); +} + +int CTextConsole::ReceiveNewline() +{ + int nLen = 0; + + Echo("\n"); + + if (m_nConsoleTextLen) + { + nLen = m_nConsoleTextLen; + + m_szConsoleText[ m_nConsoleTextLen ] = '\0'; + m_nConsoleTextLen = 0; + m_nCursorPosition = 0; + + // cache line in buffer, but only if it's not a duplicate of the previous line + if ((m_nInputLine == 0) || (Q_strcmp(m_aszLineBuffer[ m_nInputLine - 1 ], m_szConsoleText))) + { + Q_strncpy(m_aszLineBuffer[ m_nInputLine ], m_szConsoleText, MAX_CONSOLE_TEXTLEN); + m_nInputLine++; + + if (m_nInputLine > m_nTotalLines) + m_nTotalLines = m_nInputLine; + + if (m_nInputLine >= MAX_BUFFER_LINES) + m_nInputLine = 0; + + } + + m_nBrowseLine = m_nInputLine; + } + + return nLen; +} + +void CTextConsole::ReceiveBackspace() +{ + int nCount; + + if (m_nCursorPosition == 0) + { + return; + } + + m_nConsoleTextLen--; + m_nCursorPosition--; + + Echo("\b"); + + for (nCount = m_nCursorPosition; nCount < m_nConsoleTextLen; ++nCount) + { + m_szConsoleText[ nCount ] = m_szConsoleText[ nCount + 1 ]; + Echo(m_szConsoleText + nCount, 1); + } + + Echo(" "); + + nCount = m_nConsoleTextLen; + while (nCount >= m_nCursorPosition) + { + Echo("\b"); + nCount--; + } + + m_nBrowseLine = m_nInputLine; +} + +void CTextConsole::ReceiveTab() +{ + if (!m_System) + return; + + ObjectList matches; + m_szConsoleText[ m_nConsoleTextLen ] = '\0'; + m_System->GetCommandMatches(m_szConsoleText, &matches); + + if (matches.IsEmpty()) + return; + + if (matches.CountElements() == 1) + { + char *pszCmdName = (char *)matches.GetFirst(); + char *pszRest = pszCmdName + Q_strlen(m_szConsoleText); + + if (pszRest) + { + Echo(pszRest); + Q_strlcat(m_szConsoleText, pszRest); + m_nConsoleTextLen += Q_strlen(pszRest); + + Echo(" "); + Q_strlcat(m_szConsoleText, " "); + m_nConsoleTextLen++; + } + } + else + { + int nLongestCmd = 0; + int nSmallestCmd = 0; + int nCurrentColumn; + int nTotalColumns; + char szCommonCmd[256]; // Should be enough. + char szFormatCmd[256]; + char *pszSmallestCmd; + char *pszCurrentCmd = (char *)matches.GetFirst(); + nSmallestCmd = Q_strlen(pszCurrentCmd); + pszSmallestCmd = pszCurrentCmd; + while (pszCurrentCmd) + { + if ((int)Q_strlen(pszCurrentCmd) > nLongestCmd) + { + nLongestCmd = Q_strlen(pszCurrentCmd); + } + if ((int)Q_strlen(pszCurrentCmd) < nSmallestCmd) + { + nSmallestCmd = Q_strlen(pszCurrentCmd); + pszSmallestCmd = pszCurrentCmd; + } + pszCurrentCmd = (char *)matches.GetNext(); + } + + nTotalColumns = (GetWidth() - 1) / (nLongestCmd + 1); + nCurrentColumn = 0; + + Echo("\n"); + Q_strcpy(szCommonCmd, pszSmallestCmd); + + // Would be nice if these were sorted, but not that big a deal + pszCurrentCmd = (char *)matches.GetFirst(); + while (pszCurrentCmd) + { + if (++nCurrentColumn > nTotalColumns) + { + Echo("\n"); + nCurrentColumn = 1; + } + + Q_snprintf(szFormatCmd, sizeof(szFormatCmd), "%-*s ", nLongestCmd, pszCurrentCmd); + Echo(szFormatCmd); + for (char *pCur = pszCurrentCmd, *pCommon = szCommonCmd; (*pCur && *pCommon); pCur++, pCommon++) + { + if (*pCur != *pCommon) + { + *pCommon = 0; + break; + } + } + + pszCurrentCmd = (char *)matches.GetNext(); + } + + Echo("\n"); + if (Q_strcmp(szCommonCmd, m_szConsoleText)) + { + Q_strcpy(m_szConsoleText, szCommonCmd); + m_nConsoleTextLen = Q_strlen(szCommonCmd); + } + + Echo(m_szConsoleText); + } + + m_nCursorPosition = m_nConsoleTextLen; + m_nBrowseLine = m_nInputLine; +} + +void CTextConsole::ReceiveStandardChar(const char ch) +{ + int nCount; + + // If the line buffer is maxed out, ignore this char + if (m_nConsoleTextLen >= (sizeof(m_szConsoleText) - 2)) + { + return; + } + + nCount = m_nConsoleTextLen; + while (nCount > m_nCursorPosition) + { + m_szConsoleText[ nCount ] = m_szConsoleText[ nCount - 1 ]; + nCount--; + } + + m_szConsoleText[ m_nCursorPosition ] = ch; + + Echo(m_szConsoleText + m_nCursorPosition, m_nConsoleTextLen - m_nCursorPosition + 1); + + m_nConsoleTextLen++; + m_nCursorPosition++; + + nCount = m_nConsoleTextLen; + while (nCount > m_nCursorPosition) + { + Echo("\b"); + nCount--; + } + + m_nBrowseLine = m_nInputLine; +} + +void CTextConsole::ReceiveUpArrow() +{ + int nLastCommandInHistory = m_nInputLine + 1; + if (nLastCommandInHistory > m_nTotalLines) + nLastCommandInHistory = 0; + + if (m_nBrowseLine == nLastCommandInHistory) + return; + + if (m_nBrowseLine == m_nInputLine) + { + if (m_nConsoleTextLen > 0) + { + // Save off current text + Q_strncpy(m_szSavedConsoleText, m_szConsoleText, m_nConsoleTextLen); + // No terminator, it's a raw buffer we always know the length of + } + + m_nSavedConsoleTextLen = m_nConsoleTextLen; + } + + m_nBrowseLine--; + if (m_nBrowseLine < 0) + { + m_nBrowseLine = m_nTotalLines - 1; + } + + // delete old line + while (m_nConsoleTextLen--) + { + Echo("\b \b"); + } + + // copy buffered line + Echo(m_aszLineBuffer[ m_nBrowseLine ]); + + Q_strncpy(m_szConsoleText, m_aszLineBuffer[ m_nBrowseLine ], MAX_CONSOLE_TEXTLEN); + + m_nConsoleTextLen = Q_strlen(m_aszLineBuffer[ m_nBrowseLine ]); + m_nCursorPosition = m_nConsoleTextLen; +} + +void CTextConsole::ReceiveDownArrow() +{ + if (m_nBrowseLine == m_nInputLine) + return; + + if (++m_nBrowseLine > m_nTotalLines) + m_nBrowseLine = 0; + + // delete old line + while (m_nConsoleTextLen--) + { + Echo("\b \b"); + } + + if (m_nBrowseLine == m_nInputLine) + { + if (m_nSavedConsoleTextLen > 0) + { + // Restore current text + Q_strncpy(m_szConsoleText, m_szSavedConsoleText, m_nSavedConsoleTextLen); + // No terminator, it's a raw buffer we always know the length of + + Echo(m_szConsoleText, m_nSavedConsoleTextLen); + } + + m_nConsoleTextLen = m_nSavedConsoleTextLen; + } + else + { + // copy buffered line + Echo(m_aszLineBuffer[ m_nBrowseLine ]); + Q_strncpy(m_szConsoleText, m_aszLineBuffer[ m_nBrowseLine ], MAX_CONSOLE_TEXTLEN); + m_nConsoleTextLen = Q_strlen(m_aszLineBuffer[ m_nBrowseLine ]); + } + + m_nCursorPosition = m_nConsoleTextLen; +} + +void CTextConsole::ReceiveLeftArrow() +{ + if (m_nCursorPosition == 0) + return; + + Echo("\b"); + m_nCursorPosition--; +} + +void CTextConsole::ReceiveRightArrow() +{ + if (m_nCursorPosition == m_nConsoleTextLen) + return; + + Echo(m_szConsoleText + m_nCursorPosition, 1); + m_nCursorPosition++; +} diff --git a/dep/rehlsdk/common/textconsole.h b/dep/rehlsdk/common/textconsole.h new file mode 100644 index 0000000..9d1b67e --- /dev/null +++ b/dep/rehlsdk/common/textconsole.h @@ -0,0 +1,95 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "IBaseSystem.h" + +#define MAX_CONSOLE_TEXTLEN 256 +#define MAX_BUFFER_LINES 30 + +class CTextConsole { +public: + virtual ~CTextConsole() {} + + virtual bool Init(IBaseSystem *system = nullptr); + virtual void ShutDown(); + virtual void Print(char *pszMsg); + + virtual void SetTitle(char *pszTitle) {} + virtual void SetStatusLine(char *pszStatus) {} + virtual void UpdateStatus() {} + + // Must be provided by children + virtual void PrintRaw(char *pszMsg, int nChars = 0) = 0; + virtual void Echo(char *pszMsg, int nChars = 0) = 0; + virtual char *GetLine() = 0; + virtual int GetWidth() = 0; + + virtual void SetVisible(bool visible); + virtual bool IsVisible(); + + void InitSystem(IBaseSystem *system); + +protected: + char m_szConsoleText[MAX_CONSOLE_TEXTLEN]; // console text buffer + int m_nConsoleTextLen; // console textbuffer length + int m_nCursorPosition; // position in the current input line + + // Saved input data when scrolling back through command history + char m_szSavedConsoleText[MAX_CONSOLE_TEXTLEN]; // console text buffer + int m_nSavedConsoleTextLen; // console textbuffer length + + char m_aszLineBuffer[MAX_BUFFER_LINES][MAX_CONSOLE_TEXTLEN]; // command buffer last MAX_BUFFER_LINES commands + int m_nInputLine; // Current line being entered + int m_nBrowseLine; // current buffer line for up/down arrow + int m_nTotalLines; // # of nonempty lines in the buffer + + bool m_ConsoleVisible; + + IBaseSystem *m_System; + + int ReceiveNewline(); + void ReceiveBackspace(); + void ReceiveTab(); + void ReceiveStandardChar(const char ch); + void ReceiveUpArrow(); + void ReceiveDownArrow(); + void ReceiveLeftArrow(); + void ReceiveRightArrow(); +}; + +#include "SteamAppStartUp.h" + +#if defined(_WIN32) + #include "TextConsoleWin32.h" +#else + #include "TextConsoleUnix.h" +#endif // defined(_WIN32) + +void Sys_Printf(char *fmt, ...); diff --git a/dep/rehlsdk/common/triangleapi.h b/dep/rehlsdk/common/triangleapi.h new file mode 100644 index 0000000..069a4d6 --- /dev/null +++ b/dep/rehlsdk/common/triangleapi.h @@ -0,0 +1,64 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( TRIANGLEAPIH ) +#define TRIANGLEAPIH +#ifdef _WIN32 +#pragma once +#endif + +typedef enum +{ + TRI_FRONT = 0, + TRI_NONE = 1, +} TRICULLSTYLE; + +#define TRI_API_VERSION 1 + +#define TRI_TRIANGLES 0 +#define TRI_TRIANGLE_FAN 1 +#define TRI_QUADS 2 +#define TRI_POLYGON 3 +#define TRI_LINES 4 +#define TRI_TRIANGLE_STRIP 5 +#define TRI_QUAD_STRIP 6 + +typedef struct triangleapi_s +{ + int version; + + void ( *RenderMode )( int mode ); + void ( *Begin )( int primitiveCode ); + void ( *End ) ( void ); + + void ( *Color4f ) ( float r, float g, float b, float a ); + void ( *Color4ub ) ( unsigned char r, unsigned char g, unsigned char b, unsigned char a ); + void ( *TexCoord2f ) ( float u, float v ); + void ( *Vertex3fv ) ( float *worldPnt ); + void ( *Vertex3f ) ( float x, float y, float z ); + void ( *Brightness ) ( float brightness ); + void ( *CullFace ) ( TRICULLSTYLE style ); + int ( *SpriteTexture ) ( struct model_s *pSpriteModel, int frame ); + int ( *WorldToScreen ) ( float *world, float *screen ); // Returns 1 if it's z clipped + void ( *Fog ) ( float flFogColor[3], float flStart, float flEnd, int bOn ); // Works just like GL_FOG, flFogColor is r/g/b. + void ( *ScreenToWorld ) ( float *screen, float *world ); + void ( *GetMatrix ) ( const int pname, float *matrix ); + int ( *BoxInPVS ) ( float *mins, float *maxs ); + void ( *LightAtPoint ) ( float *pos, float *value ); + void ( *Color4fRendermode ) ( float r, float g, float b, float a, int rendermode ); + void ( *FogParams ) ( float flDensity, int iFogSkybox ); // Used with Fog()...sets fog density and whether the fog should be applied to the skybox + +} triangleapi_t; + +#endif // !TRIANGLEAPIH diff --git a/dep/rehlsdk/common/usercmd.h b/dep/rehlsdk/common/usercmd.h new file mode 100644 index 0000000..7cdcfe2 --- /dev/null +++ b/dep/rehlsdk/common/usercmd.h @@ -0,0 +1,41 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef USERCMD_H +#define USERCMD_H +#ifdef _WIN32 +#pragma once +#endif + +typedef struct usercmd_s +{ + short lerp_msec; // Interpolation time on client + byte msec; // Duration in ms of command + vec3_t viewangles; // Command view angles. + +// intended velocities + float forwardmove; // Forward velocity. + float sidemove; // Sideways velocity. + float upmove; // Upward velocity. + byte lightlevel; // Light level at spot where we are standing. + unsigned short buttons; // Attack buttons + byte impulse; // Impulse command issued. + byte weaponselect; // Current weapon id + +// Experimental player impact stuff. + int impact_index; + vec3_t impact_position; +} usercmd_t; + +#endif // USERCMD_H diff --git a/dep/rehlsdk/common/vmodes.h b/dep/rehlsdk/common/vmodes.h new file mode 100644 index 0000000..9765bca --- /dev/null +++ b/dep/rehlsdk/common/vmodes.h @@ -0,0 +1,33 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +typedef struct rect_s +{ + int left, right, top, bottom; +} wrect_t; diff --git a/dep/rehlsdk/common/weaponinfo.h b/dep/rehlsdk/common/weaponinfo.h new file mode 100644 index 0000000..251a096 --- /dev/null +++ b/dep/rehlsdk/common/weaponinfo.h @@ -0,0 +1,53 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef WEAPONINFO_H +#define WEAPONINFO_H +#ifdef _WIN32 +#pragma once +#endif + +// Info about weapons player might have in his/her possession +typedef struct weapon_data_s +{ + int m_iId; + int m_iClip; + + float m_flNextPrimaryAttack; + float m_flNextSecondaryAttack; + float m_flTimeWeaponIdle; + + int m_fInReload; + int m_fInSpecialReload; + float m_flNextReload; + float m_flPumpTime; + float m_fReloadTime; + + float m_fAimedDamage; + float m_fNextAimBonus; + int m_fInZoom; + int m_iWeaponState; + + int iuser1; + int iuser2; + int iuser3; + int iuser4; + float fuser1; + float fuser2; + float fuser3; + float fuser4; +} weapon_data_t; + +#endif // WEAPONINFO_H diff --git a/dep/rehlsdk/common/winsani_in.h b/dep/rehlsdk/common/winsani_in.h new file mode 100644 index 0000000..d8c8527 --- /dev/null +++ b/dep/rehlsdk/common/winsani_in.h @@ -0,0 +1,7 @@ +#if _MSC_VER >= 1500 // MSVC++ 9.0 (Visual Studio 2008) +#pragma push_macro("ARRAYSIZE") +#ifdef ARRAYSIZE +#undef ARRAYSIZE +#endif +#define HSPRITE WINDOWS_HSPRITE +#endif diff --git a/dep/rehlsdk/common/winsani_out.h b/dep/rehlsdk/common/winsani_out.h new file mode 100644 index 0000000..2726950 --- /dev/null +++ b/dep/rehlsdk/common/winsani_out.h @@ -0,0 +1,4 @@ +#if _MSC_VER >= 1500 // MSVC++ 9.0 (Visual Studio 2008) +#undef HSPRITE +#pragma pop_macro("ARRAYSIZE") +#endif diff --git a/dep/rehlsdk/dlls/activity.h b/dep/rehlsdk/dlls/activity.h new file mode 100644 index 0000000..6fd3a18 --- /dev/null +++ b/dep/rehlsdk/dlls/activity.h @@ -0,0 +1,109 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef ACTIVITY_H +#define ACTIVITY_H + + +typedef enum { + ACT_RESET = 0, // Set m_Activity to this invalid value to force a reset to m_IdealActivity + ACT_IDLE = 1, + ACT_GUARD, + ACT_WALK, + ACT_RUN, + ACT_FLY, // Fly (and flap if appropriate) + ACT_SWIM, + ACT_HOP, // vertical jump + ACT_LEAP, // long forward jump + ACT_FALL, + ACT_LAND, + ACT_STRAFE_LEFT, + ACT_STRAFE_RIGHT, + ACT_ROLL_LEFT, // tuck and roll, left + ACT_ROLL_RIGHT, // tuck and roll, right + ACT_TURN_LEFT, // turn quickly left (stationary) + ACT_TURN_RIGHT, // turn quickly right (stationary) + ACT_CROUCH, // the act of crouching down from a standing position + ACT_CROUCHIDLE, // holding body in crouched position (loops) + ACT_STAND, // the act of standing from a crouched position + ACT_USE, + ACT_SIGNAL1, + ACT_SIGNAL2, + ACT_SIGNAL3, + ACT_TWITCH, + ACT_COWER, + ACT_SMALL_FLINCH, + ACT_BIG_FLINCH, + ACT_RANGE_ATTACK1, + ACT_RANGE_ATTACK2, + ACT_MELEE_ATTACK1, + ACT_MELEE_ATTACK2, + ACT_RELOAD, + ACT_ARM, // pull out gun, for instance + ACT_DISARM, // reholster gun + ACT_EAT, // monster chowing on a large food item (loop) + ACT_DIESIMPLE, + ACT_DIEBACKWARD, + ACT_DIEFORWARD, + ACT_DIEVIOLENT, + ACT_BARNACLE_HIT, // barnacle tongue hits a monster + ACT_BARNACLE_PULL, // barnacle is lifting the monster ( loop ) + ACT_BARNACLE_CHOMP, // barnacle latches on to the monster + ACT_BARNACLE_CHEW, // barnacle is holding the monster in its mouth ( loop ) + ACT_SLEEP, + ACT_INSPECT_FLOOR, // for active idles, look at something on or near the floor + ACT_INSPECT_WALL, // for active idles, look at something directly ahead of you ( doesn't HAVE to be a wall or on a wall ) + ACT_IDLE_ANGRY, // alternate idle animation in which the monster is clearly agitated. (loop) + ACT_WALK_HURT, // limp (loop) + ACT_RUN_HURT, // limp (loop) + ACT_HOVER, // Idle while in flight + ACT_GLIDE, // Fly (don't flap) + ACT_FLY_LEFT, // Turn left in flight + ACT_FLY_RIGHT, // Turn right in flight + ACT_DETECT_SCENT, // this means the monster smells a scent carried by the air + ACT_SNIFF, // this is the act of actually sniffing an item in front of the monster + ACT_BITE, // some large monsters can eat small things in one bite. This plays one time, EAT loops. + ACT_THREAT_DISPLAY, // without attacking, monster demonstrates that it is angry. (Yell, stick out chest, etc ) + ACT_FEAR_DISPLAY, // monster just saw something that it is afraid of + ACT_EXCITED, // for some reason, monster is excited. Sees something he really likes to eat, or whatever. + ACT_SPECIAL_ATTACK1, // very monster specific special attacks. + ACT_SPECIAL_ATTACK2, + ACT_COMBAT_IDLE, // agitated idle. + ACT_WALK_SCARED, + ACT_RUN_SCARED, + ACT_VICTORY_DANCE, // killed a player, do a victory dance. + ACT_DIE_HEADSHOT, // die, hit in head. + ACT_DIE_CHESTSHOT, // die, hit in chest + ACT_DIE_GUTSHOT, // die, hit in gut + ACT_DIE_BACKSHOT, // die, hit in back + ACT_FLINCH_HEAD, + ACT_FLINCH_CHEST, + ACT_FLINCH_STOMACH, + ACT_FLINCH_LEFTARM, + ACT_FLINCH_RIGHTARM, + ACT_FLINCH_LEFTLEG, + ACT_FLINCH_RIGHTLEG, +} Activity; + + +typedef struct { + int type; + char *name; +} activity_map_t; + +extern activity_map_t activity_map[]; + + +#endif //ACTIVITY_H diff --git a/dep/rehlsdk/dlls/activitymap.h b/dep/rehlsdk/dlls/activitymap.h new file mode 100644 index 0000000..92cadae --- /dev/null +++ b/dep/rehlsdk/dlls/activitymap.h @@ -0,0 +1,97 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#define _A( a ) { a, #a } + +activity_map_t activity_map[] = +{ +_A( ACT_IDLE ), +_A( ACT_GUARD ), +_A( ACT_WALK ), +_A( ACT_RUN ), +_A( ACT_FLY ), +_A( ACT_SWIM ), +_A( ACT_HOP ), +_A( ACT_LEAP ), +_A( ACT_FALL ), +_A( ACT_LAND ), +_A( ACT_STRAFE_LEFT ), +_A( ACT_STRAFE_RIGHT ), +_A( ACT_ROLL_LEFT ), +_A( ACT_ROLL_RIGHT ), +_A( ACT_TURN_LEFT ), +_A( ACT_TURN_RIGHT ), +_A( ACT_CROUCH ), +_A( ACT_CROUCHIDLE ), +_A( ACT_STAND ), +_A( ACT_USE ), +_A( ACT_SIGNAL1 ), +_A( ACT_SIGNAL2 ), +_A( ACT_SIGNAL3 ), +_A( ACT_TWITCH ), +_A( ACT_COWER ), +_A( ACT_SMALL_FLINCH ), +_A( ACT_BIG_FLINCH ), +_A( ACT_RANGE_ATTACK1 ), +_A( ACT_RANGE_ATTACK2 ), +_A( ACT_MELEE_ATTACK1 ), +_A( ACT_MELEE_ATTACK2 ), +_A( ACT_RELOAD ), +_A( ACT_ARM ), +_A( ACT_DISARM ), +_A( ACT_EAT ), +_A( ACT_DIESIMPLE ), +_A( ACT_DIEBACKWARD ), +_A( ACT_DIEFORWARD ), +_A( ACT_DIEVIOLENT ), +_A( ACT_BARNACLE_HIT ), +_A( ACT_BARNACLE_PULL ), +_A( ACT_BARNACLE_CHOMP ), +_A( ACT_BARNACLE_CHEW ), +_A( ACT_SLEEP ), +_A( ACT_INSPECT_FLOOR ), +_A( ACT_INSPECT_WALL ), +_A( ACT_IDLE_ANGRY ), +_A( ACT_WALK_HURT ), +_A( ACT_RUN_HURT ), +_A( ACT_HOVER ), +_A( ACT_GLIDE ), +_A( ACT_FLY_LEFT ), +_A( ACT_FLY_RIGHT ), +_A( ACT_DETECT_SCENT ), +_A( ACT_SNIFF ), +_A( ACT_BITE ), +_A( ACT_THREAT_DISPLAY ), +_A( ACT_FEAR_DISPLAY ), +_A( ACT_EXCITED ), +_A( ACT_SPECIAL_ATTACK1 ), +_A( ACT_SPECIAL_ATTACK2 ), +_A( ACT_COMBAT_IDLE ), +_A( ACT_WALK_SCARED ), +_A( ACT_RUN_SCARED ), +_A( ACT_VICTORY_DANCE ), +_A( ACT_DIE_HEADSHOT ), +_A( ACT_DIE_CHESTSHOT ), +_A( ACT_DIE_GUTSHOT ), +_A( ACT_DIE_BACKSHOT ), +_A( ACT_FLINCH_HEAD ), +_A( ACT_FLINCH_CHEST ), +_A( ACT_FLINCH_STOMACH ), +_A( ACT_FLINCH_LEFTARM ), +_A( ACT_FLINCH_RIGHTARM ), +_A( ACT_FLINCH_LEFTLEG ), +_A( ACT_FLINCH_RIGHTLEG ), +0, NULL +}; diff --git a/dep/rehlsdk/dlls/animation.h b/dep/rehlsdk/dlls/animation.h new file mode 100644 index 0000000..174bd71 --- /dev/null +++ b/dep/rehlsdk/dlls/animation.h @@ -0,0 +1,47 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef ANIMATION_H +#define ANIMATION_H + +#define ACTIVITY_NOT_AVAILABLE -1 + +#ifndef MONSTEREVENT_H +#include "monsterevent.h" +#endif + +extern int IsSoundEvent( int eventNumber ); + +int LookupActivity( void *pmodel, entvars_t *pev, int activity ); +int LookupActivityHeaviest( void *pmodel, entvars_t *pev, int activity ); +int LookupSequence( void *pmodel, const char *label ); +void GetSequenceInfo( void *pmodel, entvars_t *pev, float *pflFrameRate, float *pflGroundSpeed ); +int GetSequenceFlags( void *pmodel, entvars_t *pev ); +int LookupAnimationEvents( void *pmodel, entvars_t *pev, float flStart, float flEnd ); +float SetController( void *pmodel, entvars_t *pev, int iController, float flValue ); +float SetBlending( void *pmodel, entvars_t *pev, int iBlender, float flValue ); +void GetEyePosition( void *pmodel, float *vecEyePosition ); +void SequencePrecache( void *pmodel, const char *pSequenceName ); +int FindTransition( void *pmodel, int iEndingAnim, int iGoalAnim, int *piDir ); +void SetBodygroup( void *pmodel, entvars_t *pev, int iGroup, int iValue ); +int GetBodygroup( void *pmodel, entvars_t *pev, int iGroup ); + +int GetAnimationEvent( void *pmodel, entvars_t *pev, MonsterEvent_t *pMonsterEvent, float flStart, float flEnd, int index ); +int ExtractBbox( void *pmodel, int sequence, float *mins, float *maxs ); + +// From /engine/studio.h +#define STUDIO_LOOPING 0x0001 + + +#endif //ANIMATION_H diff --git a/dep/rehlsdk/dlls/basemonster.h b/dep/rehlsdk/dlls/basemonster.h new file mode 100644 index 0000000..43a2ed7 --- /dev/null +++ b/dep/rehlsdk/dlls/basemonster.h @@ -0,0 +1,94 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef BASEMONSTER_H +#define BASEMONSTER_H + +class CBaseMonster : public CBaseToggle +{ +public: + Activity m_Activity;// what the monster is doing (animation) + Activity m_IdealActivity;// monster should switch to this activity + int m_LastHitGroup; // the last body region that took damage + int m_bitsDamageType; // what types of damage has monster (player) taken + BYTE m_rgbTimeBasedDamage[CDMG_TIMEBASED]; + MONSTERSTATE m_MonsterState;// monster's current state + MONSTERSTATE m_IdealMonsterState;// monster should change to this state + int m_afConditions; + int m_afMemory; + float m_flNextAttack; // cannot attack again until this time + EHANDLE m_hEnemy; // the entity that the monster is fighting. + EHANDLE m_hTargetEnt; // the entity that the monster is trying to reach + float m_flFieldOfView;// width of monster's field of view ( dot product ) + int m_bloodColor; // color of blood particless + Vector m_HackedGunPos; // HACK until we can query end of gun + Vector m_vecEnemyLKP;// last known position of enemy. (enemy's origin) + + + void KeyValue( KeyValueData *pkvd ); + + void MakeIdealYaw( Vector vecTarget ); + virtual float ChangeYaw ( int speed ); + virtual BOOL HasHumanGibs( void ); + virtual BOOL HasAlienGibs( void ); + virtual void FadeMonster( void ); // Called instead of GibMonster() when gibs are disabled + virtual void GibMonster( void ); + virtual Activity GetDeathActivity ( void ); + Activity GetSmallFlinchActivity( void ); + virtual void BecomeDead( void ); + BOOL ShouldGibMonster( int iGib ); + void CallGibMonster( void ); + virtual BOOL ShouldFadeOnDeath( void ); + BOOL FCheckAITrigger( void );// checks and, if necessary, fires the monster's trigger target. + virtual int IRelationship ( CBaseEntity *pTarget ); + virtual int TakeHealth( float flHealth, int bitsDamageType ); + virtual int TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType); + int DeadTakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType ); + float DamageForce( float damage ); + virtual void Killed( entvars_t *pevAttacker, int iGib ); + virtual void PainSound ( void ) { return; }; + + void RadiusDamage(entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int iClassIgnore, int bitsDamageType ); + void RadiusDamage(Vector vecSrc, entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int iClassIgnore, int bitsDamageType ); + + inline void SetConditions( int iConditions ) { m_afConditions |= iConditions; } + inline void ClearConditions( int iConditions ) { m_afConditions &= ~iConditions; } + inline BOOL HasConditions( int iConditions ) { if ( m_afConditions & iConditions ) return TRUE; return FALSE; } + inline BOOL HasAllConditions( int iConditions ) { if ( (m_afConditions & iConditions) == iConditions ) return TRUE; return FALSE; } + + inline void Remember( int iMemory ) { m_afMemory |= iMemory; } + inline void Forget( int iMemory ) { m_afMemory &= ~iMemory; } + inline BOOL HasMemory( int iMemory ) { if ( m_afMemory & iMemory ) return TRUE; return FALSE; } + inline BOOL HasAllMemories( int iMemory ) { if ( (m_afMemory & iMemory) == iMemory ) return TRUE; return FALSE; } + + // This will stop animation until you call ResetSequenceInfo() at some point in the future + inline void StopAnimation( void ) { pev->framerate = 0; } + + virtual void ReportAIState( void ); + virtual void MonsterInitDead( void ); // Call after animation/pose is set up + void EXPORT CorpseFallThink( void ); + + virtual void Look ( int iDistance );// basic sight function for monsters + virtual CBaseEntity* BestVisibleEnemy ( void );// finds best visible enemy for attack + CBaseEntity *CheckTraceHullAttack( float flDist, int iDamage, int iDmgType ); + virtual BOOL FInViewCone ( CBaseEntity *pEntity );// see if pEntity is in monster's view cone + virtual BOOL FInViewCone ( Vector *pOrigin );// see if given location is in monster's view cone + void TraceAttack( entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType); + void MakeDamageBloodDecal ( int cCount, float flNoise, TraceResult *ptr, const Vector &vecDir ); + virtual BOOL IsAlive( void ) { return (pev->deadflag != DEAD_DEAD); } + +}; + + +#endif diff --git a/dep/rehlsdk/dlls/cbase.h b/dep/rehlsdk/dlls/cbase.h new file mode 100644 index 0000000..87cb8fd --- /dev/null +++ b/dep/rehlsdk/dlls/cbase.h @@ -0,0 +1,802 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +/* + +Class Hierachy + +CBaseEntity + CBaseDelay + CBaseToggle + CBaseItem + CBaseMonster + CBaseCycler + CBasePlayer + CBaseGroup +*/ + +#define MAX_PATH_SIZE 10 // max number of nodes available for a path. + +// These are caps bits to indicate what an object's capabilities (currently used for save/restore and level transitions) +#define FCAP_CUSTOMSAVE 0x00000001 +#define FCAP_ACROSS_TRANSITION 0x00000002 // should transfer between transitions +#define FCAP_MUST_SPAWN 0x00000004 // Spawn after restore +#define FCAP_DONT_SAVE 0x80000000 // Don't save this +#define FCAP_IMPULSE_USE 0x00000008 // can be used by the player +#define FCAP_CONTINUOUS_USE 0x00000010 // can be used by the player +#define FCAP_ONOFF_USE 0x00000020 // can be used by the player +#define FCAP_DIRECTIONAL_USE 0x00000040 // Player sends +/- 1 when using (currently only tracktrains) +#define FCAP_MASTER 0x00000080 // Can be used to "master" other entities (like multisource) + +// UNDONE: This will ignore transition volumes (trigger_transition), but not the PVS!!! +#define FCAP_FORCE_TRANSITION 0x00000080 // ALWAYS goes across transitions + +#include "archtypes.h" // DAL +#include "saverestore.h" +#include "schedule.h" + +#ifndef MONSTEREVENT_H +#include "monsterevent.h" +#endif + +// C functions for external declarations that call the appropriate C++ methods + +#ifndef CBASE_DLLEXPORT +#ifdef _WIN32 +#define CBASE_DLLEXPORT _declspec( dllexport ) EXT_FUNC +#else +#define CBASE_DLLEXPORT __attribute__ ((visibility("default"))) EXT_FUNC +#endif +#endif + +#define EXPORT CBASE_DLLEXPORT + +extern "C" CBASE_DLLEXPORT int GetEntityAPI( DLL_FUNCTIONS *pFunctionTable, int interfaceVersion ); +extern "C" CBASE_DLLEXPORT int GetEntityAPI2( DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion ); + +extern int DispatchSpawn( edict_t *pent ); +extern void DispatchKeyValue( edict_t *pentKeyvalue, KeyValueData *pkvd ); +extern void DispatchTouch( edict_t *pentTouched, edict_t *pentOther ); +extern void DispatchUse( edict_t *pentUsed, edict_t *pentOther ); +extern void DispatchThink( edict_t *pent ); +extern void DispatchBlocked( edict_t *pentBlocked, edict_t *pentOther ); +extern void DispatchSave( edict_t *pent, SAVERESTOREDATA *pSaveData ); +extern int DispatchRestore( edict_t *pent, SAVERESTOREDATA *pSaveData, int globalEntity ); +extern void DispatchObjectCollsionBox( edict_t *pent ); +extern void SaveWriteFields( SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount ); +extern void SaveReadFields( SAVERESTOREDATA *pSaveData, const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount ); +extern void SaveGlobalState( SAVERESTOREDATA *pSaveData ); +extern void RestoreGlobalState( SAVERESTOREDATA *pSaveData ); +extern void ResetGlobalState( void ); + +typedef enum { USE_OFF = 0, USE_ON = 1, USE_SET = 2, USE_TOGGLE = 3 } USE_TYPE; + +extern void FireTargets( const char *targetName, CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); + +typedef void (CBaseEntity::*BASEPTR)(void); +typedef void (CBaseEntity::*ENTITYFUNCPTR)(CBaseEntity *pOther ); +typedef void (CBaseEntity::*USEPTR)( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); + +// For CLASSIFY +#define CLASS_NONE 0 +#define CLASS_MACHINE 1 +#define CLASS_PLAYER 2 +#define CLASS_HUMAN_PASSIVE 3 +#define CLASS_HUMAN_MILITARY 4 +#define CLASS_ALIEN_MILITARY 5 +#define CLASS_ALIEN_PASSIVE 6 +#define CLASS_ALIEN_MONSTER 7 +#define CLASS_ALIEN_PREY 8 +#define CLASS_ALIEN_PREDATOR 9 +#define CLASS_INSECT 10 +#define CLASS_PLAYER_ALLY 11 +#define CLASS_PLAYER_BIOWEAPON 12 // hornets and snarks.launched by players +#define CLASS_ALIEN_BIOWEAPON 13 // hornets and snarks.launched by the alien menace +#define CLASS_BARNACLE 99 // special because no one pays attention to it, and it eats a wide cross-section of creatures. + +class CBaseEntity; +class CBaseMonster; +class CBasePlayerItem; +class CSquadMonster; + + +#define SF_NORESPAWN ( 1 << 30 )// !!!set this bit on guns and stuff that should never respawn. + +// +// EHANDLE. Safe way to point to CBaseEntities who may die between frames +// +class EHANDLE +{ +private: + edict_t *m_pent; + int m_serialnumber; +public: + edict_t *Get( void ); + edict_t *Set( edict_t *pent ); + + operator int (); + + operator CBaseEntity *(); + + CBaseEntity * operator = (CBaseEntity *pEntity); + CBaseEntity * operator ->(); +}; + + +// +// Base Entity. All entity types derive from this +// +class CBaseEntity +{ +public: + // Constructor. Set engine to use C/C++ callback functions + // pointers to engine data + entvars_t *pev; // Don't need to save/restore this pointer, the engine resets it + + // path corners + CBaseEntity *m_pGoalEnt;// path corner we are heading towards + CBaseEntity *m_pLink;// used for temporary link-list operations. + + // initialization functions + virtual void Spawn( void ) { return; } + virtual void Precache( void ) { return; } + virtual void KeyValue( KeyValueData* pkvd) { pkvd->fHandled = FALSE; } + virtual int Save( CSave &save ); + virtual int Restore( CRestore &restore ); + virtual int ObjectCaps( void ) { return FCAP_ACROSS_TRANSITION; } + virtual void Activate( void ) {} + + // Setup the object->object collision box (pev->mins / pev->maxs is the object->world collision box) + virtual void SetObjectCollisionBox( void ); + +// Classify - returns the type of group (i.e, "houndeye", or "human military" so that monsters with different classnames +// still realize that they are teammates. (overridden for monsters that form groups) + virtual int Classify ( void ) { return CLASS_NONE; }; + virtual void DeathNotice ( entvars_t *pevChild ) {}// monster maker children use this to tell the monster maker that they have died. + + + static TYPEDESCRIPTION m_SaveData[]; + + virtual void TraceAttack( entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType); + virtual int TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType ); + virtual int TakeHealth( float flHealth, int bitsDamageType ); + virtual void Killed( entvars_t *pevAttacker, int iGib ); + virtual int BloodColor( void ) { return DONT_BLEED; } + virtual void TraceBleed( float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType ); + virtual BOOL IsTriggered( CBaseEntity *pActivator ) {return TRUE;} + virtual CBaseMonster *MyMonsterPointer( void ) { return NULL;} + virtual CSquadMonster *MySquadMonsterPointer( void ) { return NULL;} + virtual int GetToggleState( void ) { return TS_AT_TOP; } + virtual void AddPoints( int score, BOOL bAllowNegativeScore ) {} + virtual void AddPointsToTeam( int score, BOOL bAllowNegativeScore ) {} + virtual BOOL AddPlayerItem( CBasePlayerItem *pItem ) { return 0; } + virtual BOOL RemovePlayerItem( CBasePlayerItem *pItem ) { return 0; } + virtual int GiveAmmo( int iAmount, char *szName, int iMax ) { return -1; }; + virtual float GetDelay( void ) { return 0; } + virtual int IsMoving( void ) { return pev->velocity != g_vecZero; } + virtual void OverrideReset( void ) {} + virtual int DamageDecal( int bitsDamageType ); + // This is ONLY used by the node graph to test movement through a door + virtual void SetToggleState( int state ) {} + virtual void StartSneaking( void ) {} + virtual void StopSneaking( void ) {} + virtual BOOL OnControls( entvars_t *pev ) { return FALSE; } + virtual BOOL IsSneaking( void ) { return FALSE; } + virtual BOOL IsAlive( void ) { return (pev->deadflag == DEAD_NO) && pev->health > 0; } + virtual BOOL IsBSPModel( void ) { return pev->solid == SOLID_BSP || pev->movetype == MOVETYPE_PUSHSTEP; } + virtual BOOL ReflectGauss( void ) { return ( IsBSPModel() && !pev->takedamage ); } + virtual BOOL HasTarget( string_t targetname ) { return FStrEq(STRING(targetname), STRING(pev->targetname) ); } + virtual BOOL IsInWorld( void ); + virtual BOOL IsPlayer( void ) { return FALSE; } + virtual BOOL IsNetClient( void ) { return FALSE; } + virtual const char *TeamID( void ) { return ""; } + + +// virtual void SetActivator( CBaseEntity *pActivator ) {} + virtual CBaseEntity *GetNextTarget( void ); + + // fundamental callbacks + void (CBaseEntity ::*m_pfnThink)(void); + void (CBaseEntity ::*m_pfnTouch)( CBaseEntity *pOther ); + void (CBaseEntity ::*m_pfnUse)( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); + void (CBaseEntity ::*m_pfnBlocked)( CBaseEntity *pOther ); + + virtual void Think( void ) { if (m_pfnThink) (this->*m_pfnThink)(); }; + virtual void Touch( CBaseEntity *pOther ) { if (m_pfnTouch) (this->*m_pfnTouch)( pOther ); }; + virtual void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ) + { + if (m_pfnUse) + (this->*m_pfnUse)( pActivator, pCaller, useType, value ); + } + virtual void Blocked( CBaseEntity *pOther ) { if (m_pfnBlocked) (this->*m_pfnBlocked)( pOther ); }; + + // allow engine to allocate instance data + void *operator new( size_t stAllocateBlock, entvars_t *pev ) + { + return (void *)ALLOC_PRIVATE(ENT(pev), stAllocateBlock); + }; + + // don't use this. +#if _MSC_VER >= 1200 // only build this code if MSVC++ 6.0 or higher + void operator delete(void *pMem, entvars_t *pev) + { + pev->flags |= FL_KILLME; + }; +#endif + + void UpdateOnRemove( void ); + + // common member functions + void EXPORT SUB_Remove( void ); + void EXPORT SUB_DoNothing( void ); + void EXPORT SUB_StartFadeOut ( void ); + void EXPORT SUB_FadeOut ( void ); + void EXPORT SUB_CallUseToggle( void ) { this->Use( this, this, USE_TOGGLE, 0 ); } + int ShouldToggle( USE_TYPE useType, BOOL currentState ); + void FireBullets( ULONG cShots, Vector vecSrc, Vector vecDirShooting, Vector vecSpread, float flDistance, int iBulletType, int iTracerFreq = 4, int iDamage = 0, entvars_t *pevAttacker = NULL ); + Vector FireBulletsPlayer( ULONG cShots, Vector vecSrc, Vector vecDirShooting, Vector vecSpread, float flDistance, int iBulletType, int iTracerFreq = 4, int iDamage = 0, entvars_t *pevAttacker = NULL, int shared_rand = 0 ); + + virtual CBaseEntity *Respawn( void ) { return NULL; } + + void SUB_UseTargets( CBaseEntity *pActivator, USE_TYPE useType, float value ); + // Do the bounding boxes of these two intersect? + int Intersects( CBaseEntity *pOther ); + void MakeDormant( void ); + int IsDormant( void ); + BOOL IsLockedByMaster( void ) { return FALSE; } + + static CBaseEntity *Instance( edict_t *pent ) + { + if ( !pent ) + pent = ENT(0); + CBaseEntity *pEnt = (CBaseEntity *)GET_PRIVATE(pent); + return pEnt; + } + + static CBaseEntity *Instance( entvars_t *pev ) { return Instance( ENT( pev ) ); } + static CBaseEntity *Instance( int eoffset) { return Instance( ENT( eoffset) ); } + + CBaseMonster *GetMonsterPointer( entvars_t *pevMonster ) + { + CBaseEntity *pEntity = Instance( pevMonster ); + if ( pEntity ) + return pEntity->MyMonsterPointer(); + return NULL; + } + CBaseMonster *GetMonsterPointer( edict_t *pentMonster ) + { + CBaseEntity *pEntity = Instance( pentMonster ); + if ( pEntity ) + return pEntity->MyMonsterPointer(); + return NULL; + } + + + // Ugly code to lookup all functions to make sure they are exported when set. +#ifdef _DEBUG + void FunctionCheck( void *pFunction, char *name ) + { + if (pFunction && !NAME_FOR_FUNCTION((uint32)pFunction) ) + ALERT( at_error, "No EXPORT: %s:%s (%08lx)\n", STRING(pev->classname), name, (uint32)pFunction ); + } + + BASEPTR ThinkSet( BASEPTR func, char *name ) + { + m_pfnThink = func; + FunctionCheck( (void *)*((int *)((char *)this + ( offsetof(CBaseEntity,m_pfnThink)))), name ); + return func; + } + ENTITYFUNCPTR TouchSet( ENTITYFUNCPTR func, char *name ) + { + m_pfnTouch = func; + FunctionCheck( (void *)*((int *)((char *)this + ( offsetof(CBaseEntity,m_pfnTouch)))), name ); + return func; + } + USEPTR UseSet( USEPTR func, char *name ) + { + m_pfnUse = func; + FunctionCheck( (void *)*((int *)((char *)this + ( offsetof(CBaseEntity,m_pfnUse)))), name ); + return func; + } + ENTITYFUNCPTR BlockedSet( ENTITYFUNCPTR func, char *name ) + { + m_pfnBlocked = func; + FunctionCheck( (void *)*((int *)((char *)this + ( offsetof(CBaseEntity,m_pfnBlocked)))), name ); + return func; + } + +#endif + + + // virtual functions used by a few classes + + // used by monsters that are created by the MonsterMaker + virtual void UpdateOwner( void ) { return; }; + + + // + static CBaseEntity *Create( char *szName, const Vector &vecOrigin, const Vector &vecAngles, edict_t *pentOwner = NULL ); + + virtual BOOL FBecomeProne( void ) {return FALSE;}; + edict_t *edict() { return ENT( pev ); }; + EOFFSET eoffset( ) { return OFFSET( pev ); }; + int entindex( ) { return ENTINDEX( edict() ); }; + + virtual Vector Center( ) { return (pev->absmax + pev->absmin) * 0.5; }; // center point of entity + virtual Vector EyePosition( ) { return pev->origin + pev->view_ofs; }; // position of eyes + virtual Vector EarPosition( ) { return pev->origin + pev->view_ofs; }; // position of ears + virtual Vector BodyTarget( const Vector &posSrc ) { return Center( ); }; // position to shoot at + + virtual int Illumination( ) { return GETENTITYILLUM( ENT( pev ) ); }; + + virtual BOOL FVisible ( CBaseEntity *pEntity ); + virtual BOOL FVisible ( const Vector &vecOrigin ); + + //We use this variables to store each ammo count. + int ammo_9mm; + int ammo_357; + int ammo_bolts; + int ammo_buckshot; + int ammo_rockets; + int ammo_uranium; + int ammo_hornets; + int ammo_argrens; + //Special stuff for grenades and satchels. + float m_flStartThrow; + float m_flReleaseThrow; + int m_chargeReady; + int m_fInAttack; + + enum EGON_FIRESTATE { FIRE_OFF, FIRE_CHARGE }; + int m_fireState; +}; + + + +// Ugly technique to override base member functions +// Normally it's illegal to cast a pointer to a member function of a derived class to a pointer to a +// member function of a base class. static_cast is a sleezy way around that problem. + +#ifdef _DEBUG + +#define SetThink( a ) ThinkSet( static_cast (a), #a ) +#define SetTouch( a ) TouchSet( static_cast (a), #a ) +#define SetUse( a ) UseSet( static_cast (a), #a ) +#define SetBlocked( a ) BlockedSet( static_cast (a), #a ) + +#else + +#define SetThink( a ) m_pfnThink = static_cast (a) +#define SetTouch( a ) m_pfnTouch = static_cast (a) +#define SetUse( a ) m_pfnUse = static_cast (a) +#define SetBlocked( a ) m_pfnBlocked = static_cast (a) + +#endif + + +class CPointEntity : public CBaseEntity +{ +public: + void Spawn( void ); + virtual int ObjectCaps( void ) { return CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } +private: +}; + + +typedef struct locksounds // sounds that doors and buttons make when locked/unlocked +{ + string_t sLockedSound; // sound a door makes when it's locked + string_t sLockedSentence; // sentence group played when door is locked + string_t sUnlockedSound; // sound a door makes when it's unlocked + string_t sUnlockedSentence; // sentence group played when door is unlocked + + int iLockedSentence; // which sentence in sentence group to play next + int iUnlockedSentence; // which sentence in sentence group to play next + + float flwaitSound; // time delay between playing consecutive 'locked/unlocked' sounds + float flwaitSentence; // time delay between playing consecutive sentences + BYTE bEOFLocked; // true if hit end of list of locked sentences + BYTE bEOFUnlocked; // true if hit end of list of unlocked sentences +} locksound_t; + +void PlayLockSounds(entvars_t *pev, locksound_t *pls, int flocked, int fbutton); + +// +// MultiSouce +// + +#define MAX_MULTI_TARGETS 16 // maximum number of targets a single multi_manager entity may be assigned. +#define MS_MAX_TARGETS 32 + +class CMultiSource : public CPointEntity +{ +public: + void Spawn( ); + void KeyValue( KeyValueData *pkvd ); + void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); + int ObjectCaps( void ) { return (CPointEntity::ObjectCaps() | FCAP_MASTER); } + BOOL IsTriggered( CBaseEntity *pActivator ); + void EXPORT Register( void ); + virtual int Save( CSave &save ); + virtual int Restore( CRestore &restore ); + + static TYPEDESCRIPTION m_SaveData[]; + + EHANDLE m_rgEntities[MS_MAX_TARGETS]; + int m_rgTriggered[MS_MAX_TARGETS]; + + int m_iTotal; + string_t m_globalstate; +}; + + +// +// generic Delay entity. +// +class CBaseDelay : public CBaseEntity +{ +public: + float m_flDelay; + int m_iszKillTarget; + + virtual void KeyValue( KeyValueData* pkvd); + virtual int Save( CSave &save ); + virtual int Restore( CRestore &restore ); + + static TYPEDESCRIPTION m_SaveData[]; + // common member functions + void SUB_UseTargets( CBaseEntity *pActivator, USE_TYPE useType, float value ); + void EXPORT DelayThink( void ); +}; + + +class CBaseAnimating : public CBaseDelay +{ +public: + virtual int Save( CSave &save ); + virtual int Restore( CRestore &restore ); + + static TYPEDESCRIPTION m_SaveData[]; + + // Basic Monster Animation functions + float StudioFrameAdvance( float flInterval = 0.0 ); // accumulate animation frame time from last time called until now + int GetSequenceFlags( void ); + int LookupActivity ( int activity ); + int LookupActivityHeaviest ( int activity ); + int LookupSequence ( const char *label ); + void ResetSequenceInfo ( ); + void DispatchAnimEvents ( float flFutureInterval = 0.1 ); // Handle events that have happend since last time called up until X seconds into the future + virtual void HandleAnimEvent( MonsterEvent_t *pEvent ) { return; }; + float SetBoneController ( int iController, float flValue ); + void InitBoneControllers ( void ); + float SetBlending ( int iBlender, float flValue ); + void GetBonePosition ( int iBone, Vector &origin, Vector &angles ); + void GetAutomovement( Vector &origin, Vector &angles, float flInterval = 0.1 ); + int FindTransition( int iEndingSequence, int iGoalSequence, int *piDir ); + void GetAttachment ( int iAttachment, Vector &origin, Vector &angles ); + void SetBodygroup( int iGroup, int iValue ); + int GetBodygroup( int iGroup ); + int ExtractBbox( int sequence, float *mins, float *maxs ); + void SetSequenceBox( void ); + + // animation needs + float m_flFrameRate; // computed FPS for current sequence + float m_flGroundSpeed; // computed linear movement rate for current sequence + float m_flLastEventCheck; // last time the event list was checked + BOOL m_fSequenceFinished;// flag set when StudioAdvanceFrame moves across a frame boundry + BOOL m_fSequenceLoops; // true if the sequence loops +}; + + +// +// generic Toggle entity. +// +#define SF_ITEM_USE_ONLY 256 // ITEM_USE_ONLY = BUTTON_USE_ONLY = DOOR_USE_ONLY!!! + +class CBaseToggle : public CBaseAnimating +{ +public: + void KeyValue( KeyValueData *pkvd ); + + TOGGLE_STATE m_toggle_state; + float m_flActivateFinished;//like attack_finished, but for doors + float m_flMoveDistance;// how far a door should slide or rotate + float m_flWait; + float m_flLip; + float m_flTWidth;// for plats + float m_flTLength;// for plats + + Vector m_vecPosition1; + Vector m_vecPosition2; + Vector m_vecAngle1; + Vector m_vecAngle2; + + int m_cTriggersLeft; // trigger_counter only, # of activations remaining + float m_flHeight; + EHANDLE m_hActivator; + void (CBaseToggle::*m_pfnCallWhenMoveDone)(void); + Vector m_vecFinalDest; + Vector m_vecFinalAngle; + + int m_bitsDamageInflict; // DMG_ damage type that the door or tigger does + + virtual int Save( CSave &save ); + virtual int Restore( CRestore &restore ); + + static TYPEDESCRIPTION m_SaveData[]; + + virtual int GetToggleState( void ) { return m_toggle_state; } + virtual float GetDelay( void ) { return m_flWait; } + + // common member functions + void LinearMove( Vector vecDest, float flSpeed ); + void EXPORT LinearMoveDone( void ); + void AngularMove( Vector vecDestAngle, float flSpeed ); + void EXPORT AngularMoveDone( void ); + BOOL IsLockedByMaster( void ); + + static float AxisValue( int flags, const Vector &angles ); + static void AxisDir( entvars_t *pev ); + static float AxisDelta( int flags, const Vector &angle1, const Vector &angle2 ); + + string_t m_sMaster; // If this button has a master switch, this is the targetname. + // A master switch must be of the multisource type. If all + // of the switches in the multisource have been triggered, then + // the button will be allowed to operate. Otherwise, it will be + // deactivated. +}; +#define SetMoveDone( a ) m_pfnCallWhenMoveDone = static_cast (a) + + +// people gib if their health is <= this at the time of death +#define GIB_HEALTH_VALUE -30 + +#define ROUTE_SIZE 8 // how many waypoints a monster can store at one time +#define MAX_OLD_ENEMIES 4 // how many old enemies to remember + +#define bits_CAP_DUCK ( 1 << 0 )// crouch +#define bits_CAP_JUMP ( 1 << 1 )// jump/leap +#define bits_CAP_STRAFE ( 1 << 2 )// strafe ( walk/run sideways) +#define bits_CAP_SQUAD ( 1 << 3 )// can form squads +#define bits_CAP_SWIM ( 1 << 4 )// proficiently navigate in water +#define bits_CAP_CLIMB ( 1 << 5 )// climb ladders/ropes +#define bits_CAP_USE ( 1 << 6 )// open doors/push buttons/pull levers +#define bits_CAP_HEAR ( 1 << 7 )// can hear forced sounds +#define bits_CAP_AUTO_DOORS ( 1 << 8 )// can trigger auto doors +#define bits_CAP_OPEN_DOORS ( 1 << 9 )// can open manual doors +#define bits_CAP_TURN_HEAD ( 1 << 10)// can turn head, always bone controller 0 + +#define bits_CAP_RANGE_ATTACK1 ( 1 << 11)// can do a range attack 1 +#define bits_CAP_RANGE_ATTACK2 ( 1 << 12)// can do a range attack 2 +#define bits_CAP_MELEE_ATTACK1 ( 1 << 13)// can do a melee attack 1 +#define bits_CAP_MELEE_ATTACK2 ( 1 << 14)// can do a melee attack 2 + +#define bits_CAP_FLY ( 1 << 15)// can fly, move all around + +#define bits_CAP_DOORS_GROUP (bits_CAP_USE | bits_CAP_AUTO_DOORS | bits_CAP_OPEN_DOORS) + +// used by suit voice to indicate damage sustained and repaired type to player + +// instant damage + +#define DMG_GENERIC 0 // generic damage was done +#define DMG_CRUSH (1 << 0) // crushed by falling or moving object +#define DMG_BULLET (1 << 1) // shot +#define DMG_SLASH (1 << 2) // cut, clawed, stabbed +#define DMG_BURN (1 << 3) // heat burned +#define DMG_FREEZE (1 << 4) // frozen +#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_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 +// time-based damage +#define DMG_TIMEBASED (~(0x3fff)) // mask for time-based damage + +#define DMG_PARALYZE (1 << 15) // slows affected creature down +#define DMG_NERVEGAS (1 << 16) // nerve toxins, very bad +#define DMG_POISON (1 << 17) // blood poisioning +#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_SLOWFREEZE (1 << 22) // in a subzero freezer +#define DMG_MORTAR (1 << 23) // Hit by air raid (done to distinguish grenade from mortar) + +// these are the damage types that are allowed to gib corpses +#define DMG_GIB_CORPSE ( DMG_CRUSH | DMG_FALL | DMG_BLAST | DMG_SONIC | DMG_CLUB ) + +// these are the damage types that have client hud art +#define DMG_SHOWNHUD (DMG_POISON | DMG_ACID | DMG_FREEZE | DMG_SLOWFREEZE | DMG_DROWN | DMG_BURN | DMG_SLOWBURN | DMG_NERVEGAS | DMG_RADIATION | DMG_SHOCK) + +// NOTE: tweak these values based on gameplay feedback: + +#define PARALYZE_DURATION 2 // number of 2 second intervals to take damage +#define PARALYZE_DAMAGE 1.0 // damage to take each 2 second interval + +#define NERVEGAS_DURATION 2 +#define NERVEGAS_DAMAGE 5.0 + +#define POISON_DURATION 5 +#define POISON_DAMAGE 2.0 + +#define RADIATION_DURATION 2 +#define RADIATION_DAMAGE 1.0 + +#define ACID_DURATION 2 +#define ACID_DAMAGE 5.0 + +#define SLOWBURN_DURATION 2 +#define SLOWBURN_DAMAGE 1.0 + +#define SLOWFREEZE_DURATION 2 +#define SLOWFREEZE_DAMAGE 1.0 + + +#define itbd_Paralyze 0 +#define itbd_NerveGas 1 +#define itbd_Poison 2 +#define itbd_Radiation 3 +#define itbd_DrownRecover 4 +#define itbd_Acid 5 +#define itbd_SlowBurn 6 +#define itbd_SlowFreeze 7 +#define CDMG_TIMEBASED 8 + +// when calling KILLED(), a value that governs gib behavior is expected to be +// one of these three values +#define GIB_NORMAL 0// gib if entity was overkilled +#define GIB_NEVER 1// never gib, no matter how much death damage is done ( freezing, etc ) +#define GIB_ALWAYS 2// always gib ( Houndeye Shock, Barnacle Bite ) + +class CBaseMonster; +class CCineMonster; +class CSound; + +#include "basemonster.h" + + +char *ButtonSound( int sound ); // get string of button sound number + + +// +// Generic Button +// +class CBaseButton : public CBaseToggle +{ +public: + void Spawn( void ); + virtual void Precache( void ); + void RotSpawn( void ); + virtual void KeyValue( KeyValueData* pkvd); + + void ButtonActivate( ); + void SparkSoundCache( void ); + + void EXPORT ButtonShot( void ); + void EXPORT ButtonTouch( CBaseEntity *pOther ); + void EXPORT ButtonSpark ( void ); + void EXPORT TriggerAndWait( void ); + void EXPORT ButtonReturn( void ); + void EXPORT ButtonBackHome( void ); + void EXPORT ButtonUse ( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); + virtual int TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType ); + virtual int Save( CSave &save ); + virtual int Restore( CRestore &restore ); + + enum BUTTON_CODE { BUTTON_NOTHING, BUTTON_ACTIVATE, BUTTON_RETURN }; + BUTTON_CODE ButtonResponseToTouch( void ); + + static TYPEDESCRIPTION m_SaveData[]; + // Buttons that don't take damage can be IMPULSE used + virtual int ObjectCaps( void ) { return (CBaseToggle:: ObjectCaps() & ~FCAP_ACROSS_TRANSITION) | (pev->takedamage?0:FCAP_IMPULSE_USE); } + + BOOL m_fStayPushed; // button stays pushed in until touched again? + BOOL m_fRotating; // a rotating button? default is a sliding button. + + string_t m_strChangeTarget; // if this field is not null, this is an index into the engine string array. + // when this button is touched, it's target entity's TARGET field will be set + // to the button's ChangeTarget. This allows you to make a func_train switch paths, etc. + + locksound_t m_ls; // door lock sounds + + BYTE m_bLockedSound; // ordinals from entity selection + BYTE m_bLockedSentence; + BYTE m_bUnlockedSound; + BYTE m_bUnlockedSentence; + int m_sounds; +}; + +// +// Weapons +// + +#define BAD_WEAPON 0x00007FFF + +// +// Converts a entvars_t * to a class pointer +// It will allocate the class and entity if necessary +// +template T * GetClassPtr( T *a ) +{ + entvars_t *pev = (entvars_t *)a; + + // allocate entity if necessary + if (pev == NULL) + pev = VARS(CREATE_ENTITY()); + + // get the private data + a = (T *)GET_PRIVATE(ENT(pev)); + + if (a == NULL) + { + // allocate private data + a = new(pev) T; + a->pev = pev; + } + return a; +} + + +/* +bit_PUSHBRUSH_DATA | bit_TOGGLE_DATA +bit_MONSTER_DATA +bit_DELAY_DATA +bit_TOGGLE_DATA | bit_DELAY_DATA | bit_MONSTER_DATA +bit_PLAYER_DATA | bit_MONSTER_DATA +bit_MONSTER_DATA | CYCLER_DATA +bit_LIGHT_DATA +path_corner_data +bit_MONSTER_DATA | wildcard_data +bit_MONSTER_DATA | bit_GROUP_DATA +boid_flock_data +boid_data +CYCLER_DATA +bit_ITEM_DATA +bit_ITEM_DATA | func_hud_data +bit_TOGGLE_DATA | bit_ITEM_DATA +EOFFSET +env_sound_data +env_sound_data +push_trigger_data +*/ + +#define TRACER_FREQ 4 // Tracers fire every 4 bullets + +typedef struct _SelAmmo +{ + BYTE Ammo1Type; + BYTE Ammo1; + BYTE Ammo2Type; + BYTE Ammo2; +} SelAmmo; + + +// this moved here from world.cpp, to allow classes to be derived from it +//======================= +// CWorld +// +// This spawns first when each level begins. +//======================= +class CWorld : public CBaseEntity +{ +public: + void Spawn( void ); + void Precache( void ); + void KeyValue( KeyValueData *pkvd ); +}; diff --git a/dep/rehlsdk/dlls/cdll_dll.h b/dep/rehlsdk/dlls/cdll_dll.h new file mode 100644 index 0000000..920fa29 --- /dev/null +++ b/dep/rehlsdk/dlls/cdll_dll.h @@ -0,0 +1,46 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// +// cdll_dll.h + +// this file is included by both the game-dll and the client-dll, + +#ifndef CDLL_DLL_H +#define CDLL_DLL_H + +#define MAX_WEAPONS 32 // ??? + +#define MAX_WEAPON_SLOTS 5 // hud item selection slots +#define MAX_ITEM_TYPES 6 // hud item selection slots + +#define MAX_ITEMS 5 // hard coded item types + +#define HIDEHUD_WEAPONS ( 1<<0 ) +#define HIDEHUD_FLASHLIGHT ( 1<<1 ) +#define HIDEHUD_ALL ( 1<<2 ) +#define HIDEHUD_HEALTH ( 1<<3 ) + +#define MAX_AMMO_TYPES 32 // ??? +#define MAX_AMMO_SLOTS 32 // not really slots + +#define HUD_PRINTNOTIFY 1 +#define HUD_PRINTCONSOLE 2 +#define HUD_PRINTTALK 3 +#define HUD_PRINTCENTER 4 + + +#define WEAPON_SUIT 31 + +#endif diff --git a/dep/rehlsdk/dlls/client.h b/dep/rehlsdk/dlls/client.h new file mode 100644 index 0000000..1e66cc8 --- /dev/null +++ b/dep/rehlsdk/dlls/client.h @@ -0,0 +1,65 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef CLIENT_H +#define CLIENT_H + +extern void respawn( entvars_t* pev, BOOL fCopyCorpse ); +extern BOOL ClientConnect( edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ] ); +extern void ClientDisconnect( edict_t *pEntity ); +extern void ClientKill( edict_t *pEntity ); +extern void ClientPutInServer( edict_t *pEntity ); +extern void ClientCommand( edict_t *pEntity ); +extern void ClientUserInfoChanged( edict_t *pEntity, char *infobuffer ); +extern void ServerActivate( edict_t *pEdictList, int edictCount, int clientMax ); +extern void ServerDeactivate( void ); +extern void StartFrame( void ); +extern void PlayerPostThink( edict_t *pEntity ); +extern void PlayerPreThink( edict_t *pEntity ); +extern void ParmsNewLevel( void ); +extern void ParmsChangeLevel( void ); + +extern void ClientPrecache( void ); + +extern const char *GetGameDescription( void ); +extern void PlayerCustomization( edict_t *pEntity, customization_t *pCust ); + +extern void SpectatorConnect ( edict_t *pEntity ); +extern void SpectatorDisconnect ( edict_t *pEntity ); +extern void SpectatorThink ( edict_t *pEntity ); + +extern void Sys_Error( const char *error_string ); + +extern void SetupVisibility( edict_t *pViewEntity, edict_t *pClient, unsigned char **pvs, unsigned char **pas ); +extern void UpdateClientData ( const struct edict_s *ent, int sendweapons, struct clientdata_s *cd ); +extern int AddToFullPack( struct entity_state_s *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet ); +extern void CreateBaseline( int player, int eindex, struct entity_state_s *baseline, struct edict_s *entity, int playermodelindex, vec3_t player_mins, vec3_t player_maxs ); +extern void RegisterEncoders( void ); + +extern int GetWeaponData( struct edict_s *player, struct weapon_data_s *info ); + +extern void CmdStart( const edict_t *player, const struct usercmd_s *cmd, unsigned int random_seed ); +extern void CmdEnd ( const edict_t *player ); + +extern int ConnectionlessPacket( const struct netadr_s *net_from, const char *args, char *response_buffer, int *response_buffer_size ); + +extern int GetHullBounds( int hullnumber, float *mins, float *maxs ); + +extern void CreateInstancedBaselines ( void ); + +extern int InconsistentFile( const edict_t *player, const char *filename, char *disconnect_message ); + +extern int AllowLagCompensation( void ); + +#endif // CLIENT_H diff --git a/dep/rehlsdk/dlls/decals.h b/dep/rehlsdk/dlls/decals.h new file mode 100644 index 0000000..f66da95 --- /dev/null +++ b/dep/rehlsdk/dlls/decals.h @@ -0,0 +1,84 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef DECALS_H +#define DECALS_H + +// +// Dynamic Decals +// +enum decal_e +{ + DECAL_GUNSHOT1 = 0, + DECAL_GUNSHOT2, + DECAL_GUNSHOT3, + DECAL_GUNSHOT4, + DECAL_GUNSHOT5, + DECAL_LAMBDA1, + DECAL_LAMBDA2, + DECAL_LAMBDA3, + DECAL_LAMBDA4, + DECAL_LAMBDA5, + DECAL_LAMBDA6, + DECAL_SCORCH1, + DECAL_SCORCH2, + DECAL_BLOOD1, + DECAL_BLOOD2, + DECAL_BLOOD3, + DECAL_BLOOD4, + DECAL_BLOOD5, + DECAL_BLOOD6, + DECAL_YBLOOD1, + DECAL_YBLOOD2, + DECAL_YBLOOD3, + DECAL_YBLOOD4, + DECAL_YBLOOD5, + DECAL_YBLOOD6, + DECAL_GLASSBREAK1, + DECAL_GLASSBREAK2, + DECAL_GLASSBREAK3, + DECAL_BIGSHOT1, + DECAL_BIGSHOT2, + DECAL_BIGSHOT3, + DECAL_BIGSHOT4, + DECAL_BIGSHOT5, + DECAL_SPIT1, + DECAL_SPIT2, + DECAL_BPROOF1, // Bulletproof glass decal + DECAL_GARGSTOMP1, // Gargantua stomp crack + DECAL_SMALLSCORCH1, // Small scorch mark + DECAL_SMALLSCORCH2, // Small scorch mark + DECAL_SMALLSCORCH3, // Small scorch mark + DECAL_MOMMABIRTH, // Big momma birth splatter + DECAL_MOMMASPLAT, +}; + +typedef struct +{ + char *name; + short entityIndex; + byte depth; + byte flags; + vec3_t position; +} DECALLIST; + +typedef struct +{ + char *name; + int index; +} DLL_DECALLIST; + +extern DLL_DECALLIST gDecals[]; + +#endif // DECALS_H diff --git a/dep/rehlsdk/dlls/doors.h b/dep/rehlsdk/dlls/doors.h new file mode 100644 index 0000000..8008861 --- /dev/null +++ b/dep/rehlsdk/dlls/doors.h @@ -0,0 +1,33 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef DOORS_H +#define DOORS_H + +// doors +#define SF_DOOR_ROTATE_Y 0 +#define SF_DOOR_START_OPEN 1 +#define SF_DOOR_ROTATE_BACKWARDS 2 +#define SF_DOOR_PASSABLE 8 +#define SF_DOOR_ONEWAY 16 +#define SF_DOOR_NO_AUTO_RETURN 32 +#define SF_DOOR_ROTATE_Z 64 +#define SF_DOOR_ROTATE_X 128 +#define SF_DOOR_USE_ONLY 256 // door must be opened by player's use button. +#define SF_DOOR_NOMONSTERS 512 // Monster can't open +#define SF_DOOR_SILENT 0x80000000 + + + +#endif //DOORS_H diff --git a/dep/rehlsdk/dlls/effects.h b/dep/rehlsdk/dlls/effects.h new file mode 100644 index 0000000..f93a9d8 --- /dev/null +++ b/dep/rehlsdk/dlls/effects.h @@ -0,0 +1,209 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef EFFECTS_H +#define EFFECTS_H + +#define SF_BEAM_STARTON 0x0001 +#define SF_BEAM_TOGGLE 0x0002 +#define SF_BEAM_RANDOM 0x0004 +#define SF_BEAM_RING 0x0008 +#define SF_BEAM_SPARKSTART 0x0010 +#define SF_BEAM_SPARKEND 0x0020 +#define SF_BEAM_DECALS 0x0040 +#define SF_BEAM_SHADEIN 0x0080 +#define SF_BEAM_SHADEOUT 0x0100 +#define SF_BEAM_TEMPORARY 0x8000 + +#define SF_SPRITE_STARTON 0x0001 +#define SF_SPRITE_ONCE 0x0002 +#define SF_SPRITE_TEMPORARY 0x8000 + +class CSprite : public CPointEntity +{ +public: + void Spawn( void ); + void Precache( void ); + + int ObjectCaps( void ) + { + int flags = 0; + if ( pev->spawnflags & SF_SPRITE_TEMPORARY ) + flags = FCAP_DONT_SAVE; + return (CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION) | flags; + } + void EXPORT AnimateThink( void ); + void EXPORT ExpandThink( void ); + void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); + void Animate( float frames ); + void Expand( float scaleSpeed, float fadeSpeed ); + void SpriteInit( const char *pSpriteName, const Vector &origin ); + + inline void SetAttachment( edict_t *pEntity, int attachment ) + { + if ( pEntity ) + { + pev->skin = ENTINDEX(pEntity); + pev->body = attachment; + pev->aiment = pEntity; + pev->movetype = MOVETYPE_FOLLOW; + } + } + void TurnOff( void ); + void TurnOn( void ); + inline float Frames( void ) { return m_maxFrame; } + inline void SetTransparency( int rendermode, int r, int g, int b, int a, int fx ) + { + pev->rendermode = rendermode; + pev->rendercolor.x = r; + pev->rendercolor.y = g; + pev->rendercolor.z = b; + pev->renderamt = a; + pev->renderfx = fx; + } + inline void SetTexture( int spriteIndex ) { pev->modelindex = spriteIndex; } + inline void SetScale( float scale ) { pev->scale = scale; } + inline void SetColor( int r, int g, int b ) { pev->rendercolor.x = r; pev->rendercolor.y = g; pev->rendercolor.z = b; } + inline void SetBrightness( int brightness ) { pev->renderamt = brightness; } + + inline void AnimateAndDie( float framerate ) + { + SetThink(&CSprite::AnimateUntilDead); + pev->framerate = framerate; + pev->dmgtime = gpGlobals->time + (m_maxFrame / framerate); + pev->nextthink = gpGlobals->time; + } + + void EXPORT AnimateUntilDead( void ); + + virtual int Save( CSave &save ); + virtual int Restore( CRestore &restore ); + static TYPEDESCRIPTION m_SaveData[]; + static CSprite *SpriteCreate( const char *pSpriteName, const Vector &origin, BOOL animate ); + +private: + + float m_lastTime; + float m_maxFrame; +}; + + +class CBeam : public CBaseEntity +{ +public: + void Spawn( void ); + void Precache( void ); + int ObjectCaps( void ) + { + int flags = 0; + if ( pev->spawnflags & SF_BEAM_TEMPORARY ) + flags = FCAP_DONT_SAVE; + return (CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION) | flags; + } + + void EXPORT TriggerTouch( CBaseEntity *pOther ); + + // These functions are here to show the way beams are encoded as entities. + // Encoding beams as entities simplifies their management in the client/server architecture + inline void SetType( int type ) { pev->rendermode = (pev->rendermode & 0xF0) | (type&0x0F); } + inline void SetFlags( int flags ) { pev->rendermode = (pev->rendermode & 0x0F) | (flags&0xF0); } + inline void SetStartPos( const Vector& pos ) { pev->origin = pos; } + inline void SetEndPos( const Vector& pos ) { pev->angles = pos; } + void SetStartEntity( int entityIndex ); + void SetEndEntity( int entityIndex ); + + inline void SetStartAttachment( int attachment ) { pev->sequence = (pev->sequence & 0x0FFF) | ((attachment&0xF)<<12); } + inline void SetEndAttachment( int attachment ) { pev->skin = (pev->skin & 0x0FFF) | ((attachment&0xF)<<12); } + + inline void SetTexture( int spriteIndex ) { pev->modelindex = spriteIndex; } + inline void SetWidth( int width ) { pev->scale = width; } + inline void SetNoise( int amplitude ) { pev->body = amplitude; } + inline void SetColor( int r, int g, int b ) { pev->rendercolor.x = r; pev->rendercolor.y = g; pev->rendercolor.z = b; } + inline void SetBrightness( int brightness ) { pev->renderamt = brightness; } + inline void SetFrame( float frame ) { pev->frame = frame; } + inline void SetScrollRate( int speed ) { pev->animtime = speed; } + + inline int GetType( void ) { return pev->rendermode & 0x0F; } + inline int GetFlags( void ) { return pev->rendermode & 0xF0; } + inline int GetStartEntity( void ) { return pev->sequence & 0xFFF; } + inline int GetEndEntity( void ) { return pev->skin & 0xFFF; } + + const Vector &GetStartPos( void ); + const Vector &GetEndPos( void ); + + Vector Center( void ) { return (GetStartPos() + GetEndPos()) * 0.5; }; // center point of beam + + inline int GetTexture( void ) { return pev->modelindex; } + inline int GetWidth( void ) { return pev->scale; } + inline int GetNoise( void ) { return pev->body; } + // inline void GetColor( int r, int g, int b ) { pev->rendercolor.x = r; pev->rendercolor.y = g; pev->rendercolor.z = b; } + inline int GetBrightness( void ) { return pev->renderamt; } + inline int GetFrame( void ) { return pev->frame; } + inline int GetScrollRate( void ) { return pev->animtime; } + + // Call after you change start/end positions + void RelinkBeam( void ); +// void SetObjectCollisionBox( void ); + + void DoSparks( const Vector &start, const Vector &end ); + CBaseEntity *RandomTargetname( const char *szName ); + void BeamDamage( TraceResult *ptr ); + // Init after BeamCreate() + void BeamInit( const char *pSpriteName, int width ); + void PointsInit( const Vector &start, const Vector &end ); + void PointEntInit( const Vector &start, int endIndex ); + void EntsInit( int startIndex, int endIndex ); + void HoseInit( const Vector &start, const Vector &direction ); + + static CBeam *BeamCreate( const char *pSpriteName, int width ); + + inline void LiveForTime( float time ) { SetThink(&CBeam::SUB_Remove); pev->nextthink = gpGlobals->time + time; } + inline void BeamDamageInstant( TraceResult *ptr, float damage ) + { + pev->dmg = damage; + pev->dmgtime = gpGlobals->time - 1; + BeamDamage(ptr); + } +}; + + +#define SF_MESSAGE_ONCE 0x0001 // Fade in, not out +#define SF_MESSAGE_ALL 0x0002 // Send to all clients + + +class CLaser : public CBeam +{ +public: + void Spawn( void ); + void Precache( void ); + void KeyValue( KeyValueData *pkvd ); + + void TurnOn( void ); + void TurnOff( void ); + int IsOn( void ); + + void FireAtPoint( TraceResult &point ); + + void EXPORT StrikeThink( void ); + void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); + virtual int Save( CSave &save ); + virtual int Restore( CRestore &restore ); + static TYPEDESCRIPTION m_SaveData[]; + + CSprite *m_pSprite; + int m_iszSpriteName; + Vector m_firePosition; +}; + +#endif //EFFECTS_H diff --git a/dep/rehlsdk/dlls/enginecallback.h b/dep/rehlsdk/dlls/enginecallback.h new file mode 100644 index 0000000..ddca3d3 --- /dev/null +++ b/dep/rehlsdk/dlls/enginecallback.h @@ -0,0 +1,160 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef ENGINECALLBACK_H +#define ENGINECALLBACK_H +#ifdef _WIN32 +#pragma once +#endif + +#include "event_flags.h" + +// Must be provided by user of this code +extern enginefuncs_t g_engfuncs; + +// The actual engine callbacks +#define GETPLAYERUSERID (*g_engfuncs.pfnGetPlayerUserId) +#define PRECACHE_MODEL (*g_engfuncs.pfnPrecacheModel) +#define PRECACHE_SOUND (*g_engfuncs.pfnPrecacheSound) +#define PRECACHE_GENERIC (*g_engfuncs.pfnPrecacheGeneric) +#define SET_MODEL (*g_engfuncs.pfnSetModel) +#define MODEL_INDEX (*g_engfuncs.pfnModelIndex) +#define MODEL_FRAMES (*g_engfuncs.pfnModelFrames) +#define SET_SIZE (*g_engfuncs.pfnSetSize) +#define CHANGE_LEVEL (*g_engfuncs.pfnChangeLevel) +#define GET_SPAWN_PARMS (*g_engfuncs.pfnGetSpawnParms) +#define SAVE_SPAWN_PARMS (*g_engfuncs.pfnSaveSpawnParms) +#define VEC_TO_YAW (*g_engfuncs.pfnVecToYaw) +#define VEC_TO_ANGLES (*g_engfuncs.pfnVecToAngles) +#define MOVE_TO_ORIGIN (*g_engfuncs.pfnMoveToOrigin) +#define oldCHANGE_YAW (*g_engfuncs.pfnChangeYaw) +#define CHANGE_PITCH (*g_engfuncs.pfnChangePitch) +#define MAKE_VECTORS (*g_engfuncs.pfnMakeVectors) +#define CREATE_ENTITY (*g_engfuncs.pfnCreateEntity) +#define REMOVE_ENTITY (*g_engfuncs.pfnRemoveEntity) +#define CREATE_NAMED_ENTITY (*g_engfuncs.pfnCreateNamedEntity) +#define MAKE_STATIC (*g_engfuncs.pfnMakeStatic) +#define ENT_IS_ON_FLOOR (*g_engfuncs.pfnEntIsOnFloor) +#define DROP_TO_FLOOR (*g_engfuncs.pfnDropToFloor) +#define WALK_MOVE (*g_engfuncs.pfnWalkMove) +#define SET_ORIGIN (*g_engfuncs.pfnSetOrigin) +#define EMIT_SOUND_DYN2 (*g_engfuncs.pfnEmitSound) +#define BUILD_SOUND_MSG (*g_engfuncs.pfnBuildSoundMsg) +#define TRACE_LINE (*g_engfuncs.pfnTraceLine) +#define TRACE_TOSS (*g_engfuncs.pfnTraceToss) +#define TRACE_MONSTER_HULL (*g_engfuncs.pfnTraceMonsterHull) +#define TRACE_HULL (*g_engfuncs.pfnTraceHull) +#define GET_AIM_VECTOR (*g_engfuncs.pfnGetAimVector) +#define SERVER_COMMAND (*g_engfuncs.pfnServerCommand) +#define SERVER_EXECUTE (*g_engfuncs.pfnServerExecute) +#define CLIENT_COMMAND (*g_engfuncs.pfnClientCommand) +#define PARTICLE_EFFECT (*g_engfuncs.pfnParticleEffect) +#define LIGHT_STYLE (*g_engfuncs.pfnLightStyle) +#define DECAL_INDEX (*g_engfuncs.pfnDecalIndex) +#define POINT_CONTENTS (*g_engfuncs.pfnPointContents) +#define CRC32_INIT (*g_engfuncs.pfnCRC32_Init) +#define CRC32_PROCESS_BUFFER (*g_engfuncs.pfnCRC32_ProcessBuffer) +#define CRC32_PROCESS_BYTE (*g_engfuncs.pfnCRC32_ProcessByte) +#define CRC32_FINAL (*g_engfuncs.pfnCRC32_Final) +#define RANDOM_LONG (*g_engfuncs.pfnRandomLong) +#define RANDOM_FLOAT (*g_engfuncs.pfnRandomFloat) +#define GETPLAYERAUTHID (*g_engfuncs.pfnGetPlayerAuthId) + +inline void MESSAGE_BEGIN( int msg_dest, int msg_type, const float *pOrigin = NULL, edict_t *ed = NULL ) { + (*g_engfuncs.pfnMessageBegin)(msg_dest, msg_type, pOrigin, ed); +} +#define MESSAGE_END (*g_engfuncs.pfnMessageEnd) +#define WRITE_BYTE (*g_engfuncs.pfnWriteByte) +#define WRITE_CHAR (*g_engfuncs.pfnWriteChar) +#define WRITE_SHORT (*g_engfuncs.pfnWriteShort) +#define WRITE_LONG (*g_engfuncs.pfnWriteLong) +#define WRITE_ANGLE (*g_engfuncs.pfnWriteAngle) +#define WRITE_COORD (*g_engfuncs.pfnWriteCoord) +#define WRITE_STRING (*g_engfuncs.pfnWriteString) +#define WRITE_ENTITY (*g_engfuncs.pfnWriteEntity) +#define CVAR_REGISTER (*g_engfuncs.pfnCVarRegister) +#define CVAR_GET_FLOAT (*g_engfuncs.pfnCVarGetFloat) +#define CVAR_GET_STRING (*g_engfuncs.pfnCVarGetString) +#define CVAR_SET_FLOAT (*g_engfuncs.pfnCVarSetFloat) +#define CVAR_SET_STRING (*g_engfuncs.pfnCVarSetString) +#define CVAR_GET_POINTER (*g_engfuncs.pfnCVarGetPointer) +#define ALERT (*g_engfuncs.pfnAlertMessage) +#define ENGINE_FPRINTF (*g_engfuncs.pfnEngineFprintf) +#define ALLOC_PRIVATE (*g_engfuncs.pfnPvAllocEntPrivateData) +inline void *GET_PRIVATE( edict_t *pent ) +{ + if ( pent ) + return pent->pvPrivateData; + return NULL; +} + +#define FREE_PRIVATE (*g_engfuncs.pfnFreeEntPrivateData) +//#define STRING (*g_engfuncs.pfnSzFromIndex) +#define ALLOC_STRING (*g_engfuncs.pfnAllocString) +#define FIND_ENTITY_BY_STRING (*g_engfuncs.pfnFindEntityByString) +#define GETENTITYILLUM (*g_engfuncs.pfnGetEntityIllum) +#define FIND_ENTITY_IN_SPHERE (*g_engfuncs.pfnFindEntityInSphere) +#define FIND_CLIENT_IN_PVS (*g_engfuncs.pfnFindClientInPVS) +#define EMIT_AMBIENT_SOUND (*g_engfuncs.pfnEmitAmbientSound) +#define GET_MODEL_PTR (*g_engfuncs.pfnGetModelPtr) +#define REG_USER_MSG (*g_engfuncs.pfnRegUserMsg) +#define GET_BONE_POSITION (*g_engfuncs.pfnGetBonePosition) +#define FUNCTION_FROM_NAME (*g_engfuncs.pfnFunctionFromName) +#define NAME_FOR_FUNCTION (*g_engfuncs.pfnNameForFunction) +#define TRACE_TEXTURE (*g_engfuncs.pfnTraceTexture) +#define CLIENT_PRINTF (*g_engfuncs.pfnClientPrintf) +#define CMD_ARGS (*g_engfuncs.pfnCmd_Args) +#define CMD_ARGC (*g_engfuncs.pfnCmd_Argc) +#define CMD_ARGV (*g_engfuncs.pfnCmd_Argv) +#define GET_ATTACHMENT (*g_engfuncs.pfnGetAttachment) +#define SET_VIEW (*g_engfuncs.pfnSetView) +#define SET_CROSSHAIRANGLE (*g_engfuncs.pfnCrosshairAngle) +#define LOAD_FILE_FOR_ME (*g_engfuncs.pfnLoadFileForMe) +#define FREE_FILE (*g_engfuncs.pfnFreeFile) +#define COMPARE_FILE_TIME (*g_engfuncs.pfnCompareFileTime) +#define GET_GAME_DIR (*g_engfuncs.pfnGetGameDir) +#define IS_MAP_VALID (*g_engfuncs.pfnIsMapValid) +#define NUMBER_OF_ENTITIES (*g_engfuncs.pfnNumberOfEntities) +#define IS_DEDICATED_SERVER (*g_engfuncs.pfnIsDedicatedServer) + +#define PRECACHE_EVENT (*g_engfuncs.pfnPrecacheEvent) +#define PLAYBACK_EVENT_FULL (*g_engfuncs.pfnPlaybackEvent) + +#define ENGINE_SET_PVS (*g_engfuncs.pfnSetFatPVS) +#define ENGINE_SET_PAS (*g_engfuncs.pfnSetFatPAS) + +#define ENGINE_CHECK_VISIBILITY (*g_engfuncs.pfnCheckVisibility) + +#define DELTA_SET ( *g_engfuncs.pfnDeltaSetField ) +#define DELTA_UNSET ( *g_engfuncs.pfnDeltaUnsetField ) +#define DELTA_ADDENCODER ( *g_engfuncs.pfnDeltaAddEncoder ) +#define ENGINE_CURRENT_PLAYER ( *g_engfuncs.pfnGetCurrentPlayer ) + +#define ENGINE_CANSKIP ( *g_engfuncs.pfnCanSkipPlayer ) + +#define DELTA_FINDFIELD ( *g_engfuncs.pfnDeltaFindField ) +#define DELTA_SETBYINDEX ( *g_engfuncs.pfnDeltaSetFieldByIndex ) +#define DELTA_UNSETBYINDEX ( *g_engfuncs.pfnDeltaUnsetFieldByIndex ) + +#define ENGINE_GETPHYSINFO ( *g_engfuncs.pfnGetPhysicsInfoString ) + +#define ENGINE_SETGROUPMASK ( *g_engfuncs.pfnSetGroupMask ) + +#define ENGINE_INSTANCE_BASELINE ( *g_engfuncs.pfnCreateInstancedBaseline ) + +#define ENGINE_FORCE_UNMODIFIED ( *g_engfuncs.pfnForceUnmodified ) + +#define PLAYER_CNX_STATS ( *g_engfuncs.pfnGetPlayerStats ) + +#endif //ENGINECALLBACK_H diff --git a/dep/rehlsdk/dlls/explode.h b/dep/rehlsdk/dlls/explode.h new file mode 100644 index 0000000..3feb011 --- /dev/null +++ b/dep/rehlsdk/dlls/explode.h @@ -0,0 +1,32 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef EXPLODE_H +#define EXPLODE_H + + +#define SF_ENVEXPLOSION_NODAMAGE ( 1 << 0 ) // when set, ENV_EXPLOSION will not actually inflict damage +#define SF_ENVEXPLOSION_REPEATABLE ( 1 << 1 ) // can this entity be refired? +#define SF_ENVEXPLOSION_NOFIREBALL ( 1 << 2 ) // don't draw the fireball +#define SF_ENVEXPLOSION_NOSMOKE ( 1 << 3 ) // don't draw the smoke +#define SF_ENVEXPLOSION_NODECAL ( 1 << 4 ) // don't make a scorch mark +#define SF_ENVEXPLOSION_NOSPARKS ( 1 << 5 ) // don't make a scorch mark + +extern DLL_GLOBAL short g_sModelIndexFireball; +extern DLL_GLOBAL short g_sModelIndexSmoke; + + +extern void ExplosionCreate( const Vector ¢er, const Vector &angles, edict_t *pOwner, int magnitude, BOOL doDamage ); + +#endif //EXPLODE_H diff --git a/dep/rehlsdk/dlls/extdll.h b/dep/rehlsdk/dlls/extdll.h new file mode 100644 index 0000000..2f8786c --- /dev/null +++ b/dep/rehlsdk/dlls/extdll.h @@ -0,0 +1,97 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef EXTDLL_H +#define EXTDLL_H + + +// +// Global header file for extension DLLs +// + +// Allow "DEBUG" in addition to default "_DEBUG" +#ifdef _DEBUG +#define DEBUG 1 +#endif + +// Silence certain warnings +#pragma warning(disable : 4244) // int or float down-conversion +#pragma warning(disable : 4305) // int or float data truncation +#pragma warning(disable : 4201) // nameless struct/union +#pragma warning(disable : 4514) // unreferenced inline function removed +#pragma warning(disable : 4100) // unreferenced formal parameter + +#include "archtypes.h" // DAL + +// Prevent tons of unused windows definitions +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#define NOWINRES +#define NOSERVICE +#define NOMCX +#define NOIME +#include "winsani_in.h" +#include "windows.h" +#include "winsani_out.h" +#else // _WIN32 +#ifndef TRUE +#define FALSE 0 +#define TRUE (!FALSE) +#endif //TRUE +typedef uint32 ULONG; +typedef unsigned char BYTE; +typedef int BOOL; +#ifndef MAX_PATH +#define MAX_PATH PATH_MAX +#endif // MAX_PATH +#include +#include +#include // memset +#ifndef min +#define min(a,b) (((a) < (b)) ? (a) : (b)) +#endif +#ifndef max +#define max(a,b) (((a) > (b)) ? (a) : (b)) +#define _vsnprintf(a,b,c,d) vsnprintf(a,b,c,d) +#endif +#endif //_WIN32 + +// Misc C-runtime library headers +#include "stdio.h" +#include "stdlib.h" +#include "math.h" + +// Header file containing definition of globalvars_t and entvars_t +typedef unsigned int func_t; // +typedef unsigned int string_t; // from engine's pr_comp.h; +typedef float vec_t; // needed before including progdefs.h + +// Vector class +#include "vector.h" + +// Defining it as a (bogus) struct helps enforce type-checking +#define vec3_t Vector + +// Shared engine/DLL constants +#include "const.h" +#include "progdefs.h" +#include "edict.h" + +// Shared header describing protocol between engine and DLLs +#include "eiface.h" + +// Shared header between the client DLL and the game DLLs +#include "cdll_dll.h" + +#endif //EXTDLL_H diff --git a/dep/rehlsdk/dlls/func_break.h b/dep/rehlsdk/dlls/func_break.h new file mode 100644 index 0000000..9bb281d --- /dev/null +++ b/dep/rehlsdk/dlls/func_break.h @@ -0,0 +1,74 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef FUNC_BREAK_H +#define FUNC_BREAK_H + +typedef enum { expRandom, expDirected} Explosions; +typedef enum { matGlass = 0, matWood, matMetal, matFlesh, matCinderBlock, matCeilingTile, matComputer, matUnbreakableGlass, matRocks, matNone, matLastMaterial } Materials; + +#define NUM_SHARDS 6 // this many shards spawned when breakable objects break; + +class CBreakable : public CBaseDelay +{ +public: + // basic functions + void Spawn( void ); + void Precache( void ); + void KeyValue( KeyValueData* pkvd); + void EXPORT BreakTouch( CBaseEntity *pOther ); + void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); + void DamageSound( void ); + + // breakables use an overridden takedamage + virtual int TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType ); + // To spark when hit + void TraceAttack( entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType ); + + BOOL IsBreakable( void ); + BOOL SparkWhenHit( void ); + + int DamageDecal( int bitsDamageType ); + + void EXPORT Die( void ); + virtual int ObjectCaps( void ) { return (CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION); } + virtual int Save( CSave &save ); + virtual int Restore( CRestore &restore ); + + inline BOOL Explodable( void ) { return ExplosionMagnitude() > 0; } + inline int ExplosionMagnitude( void ) { return pev->impulse; } + inline void ExplosionSetMagnitude( int magnitude ) { pev->impulse = magnitude; } + + static void MaterialSoundPrecache( Materials precacheMaterial ); + static void MaterialSoundRandom( edict_t *pEdict, Materials soundMaterial, float volume ); + static const char **MaterialSoundList( Materials precacheMaterial, int &soundCount ); + + static const char *pSoundsWood[]; + static const char *pSoundsFlesh[]; + static const char *pSoundsGlass[]; + static const char *pSoundsMetal[]; + static const char *pSoundsConcrete[]; + static const char *pSpawnObjects[]; + + static TYPEDESCRIPTION m_SaveData[]; + + Materials m_Material; + Explosions m_Explosion; + int m_idShard; + float m_angle; + int m_iszGibModel; + int m_iszSpawnObject; +}; + +#endif // FUNC_BREAK_H diff --git a/dep/rehlsdk/dlls/game.h b/dep/rehlsdk/dlls/game.h new file mode 100644 index 0000000..58e7e75 --- /dev/null +++ b/dep/rehlsdk/dlls/game.h @@ -0,0 +1,45 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef GAME_H +#define GAME_H + +extern void GameDLLInit( void ); + + +extern cvar_t displaysoundlist; + +// multiplayer server rules +extern cvar_t teamplay; +extern cvar_t fraglimit; +extern cvar_t timelimit; +extern cvar_t friendlyfire; +extern cvar_t falldamage; +extern cvar_t weaponstay; +extern cvar_t forcerespawn; +extern cvar_t flashlight; +extern cvar_t aimcrosshair; +extern cvar_t decalfrequency; +extern cvar_t teamlist; +extern cvar_t teamoverride; +extern cvar_t defaultteam; +extern cvar_t allowmonsters; + +// Engine Cvars +extern cvar_t *g_psv_gravity; +extern cvar_t *g_psv_aim; +extern cvar_t *g_footsteps; + +#endif // GAME_H diff --git a/dep/rehlsdk/dlls/gamerules.h b/dep/rehlsdk/dlls/gamerules.h new file mode 100644 index 0000000..76b3515 --- /dev/null +++ b/dep/rehlsdk/dlls/gamerules.h @@ -0,0 +1,360 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +//========================================================= +// GameRules +//========================================================= + +//#include "weapons.h" +//#include "items.h" +class CBasePlayerItem; +class CBasePlayer; +class CItem; +class CBasePlayerAmmo; + +// weapon respawning return codes +enum +{ + GR_NONE = 0, + + GR_WEAPON_RESPAWN_YES, + GR_WEAPON_RESPAWN_NO, + + GR_AMMO_RESPAWN_YES, + GR_AMMO_RESPAWN_NO, + + GR_ITEM_RESPAWN_YES, + GR_ITEM_RESPAWN_NO, + + GR_PLR_DROP_GUN_ALL, + GR_PLR_DROP_GUN_ACTIVE, + GR_PLR_DROP_GUN_NO, + + GR_PLR_DROP_AMMO_ALL, + GR_PLR_DROP_AMMO_ACTIVE, + GR_PLR_DROP_AMMO_NO, +}; + +// Player relationship return codes +enum +{ + GR_NOTTEAMMATE = 0, + GR_TEAMMATE, + GR_ENEMY, + GR_ALLY, + GR_NEUTRAL, +}; + +class CGameRules +{ +public: + virtual void RefreshSkillData( void );// fill skill data struct with proper values + virtual void Think( void ) = 0;// GR_Think - runs every server frame, should handle any timer tasks, periodic events, etc. + virtual BOOL IsAllowedToSpawn( CBaseEntity *pEntity ) = 0; // Can this item spawn (eg monsters don't spawn in deathmatch). + + virtual BOOL FAllowFlashlight( void ) = 0;// Are players allowed to switch on their flashlight? + virtual BOOL FShouldSwitchWeapon( CBasePlayer *pPlayer, CBasePlayerItem *pWeapon ) = 0;// should the player switch to this weapon? + virtual BOOL GetNextBestWeapon( CBasePlayer *pPlayer, CBasePlayerItem *pCurrentWeapon ) = 0;// I can't use this weapon anymore, get me the next best one. + +// Functions to verify the single/multiplayer status of a game + virtual BOOL IsMultiplayer( void ) = 0;// is this a multiplayer game? (either coop or deathmatch) + virtual BOOL IsDeathmatch( void ) = 0;//is this a deathmatch game? + virtual BOOL IsTeamplay( void ) { return FALSE; };// is this deathmatch game being played with team rules? + virtual BOOL IsCoOp( void ) = 0;// is this a coop game? + virtual const char *GetGameDescription( void ) { return "Half-Life"; } // this is the game name that gets seen in the server browser + +// Client connection/disconnection + virtual BOOL ClientConnected( edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ] ) = 0;// a client just connected to the server (player hasn't spawned yet) + virtual void InitHUD( CBasePlayer *pl ) = 0; // the client dll is ready for updating + virtual void ClientDisconnected( edict_t *pClient ) = 0;// a client just disconnected from the server + virtual void UpdateGameMode( CBasePlayer *pPlayer ) {} // the client needs to be informed of the current game mode + +// Client damage rules + virtual float FlPlayerFallDamage( CBasePlayer *pPlayer ) = 0;// this client just hit the ground after a fall. How much damage? + virtual BOOL FPlayerCanTakeDamage( CBasePlayer *pPlayer, CBaseEntity *pAttacker ) {return TRUE;};// can this player take damage from this attacker? + virtual BOOL ShouldAutoAim( CBasePlayer *pPlayer, edict_t *target ) { return TRUE; } + +// Client spawn/respawn control + virtual void PlayerSpawn( CBasePlayer *pPlayer ) = 0;// called by CBasePlayer::Spawn just before releasing player into the game + virtual void PlayerThink( CBasePlayer *pPlayer ) = 0; // called by CBasePlayer::PreThink every frame, before physics are run and after keys are accepted + virtual BOOL FPlayerCanRespawn( CBasePlayer *pPlayer ) = 0;// is this player allowed to respawn now? + virtual float FlPlayerSpawnTime( CBasePlayer *pPlayer ) = 0;// When in the future will this player be able to spawn? + virtual edict_t *GetPlayerSpawnSpot( CBasePlayer *pPlayer );// Place this player on their spawnspot and face them the proper direction. + + virtual BOOL AllowAutoTargetCrosshair( void ) { return TRUE; }; + virtual BOOL ClientCommand( CBasePlayer *pPlayer, const char *pcmd ) { return FALSE; }; // handles the user commands; returns TRUE if command handled properly + virtual void ClientUserInfoChanged( CBasePlayer *pPlayer, char *infobuffer ) {} // the player has changed userinfo; can change it now + +// Client kills/scoring + virtual int IPointsForKill( CBasePlayer *pAttacker, CBasePlayer *pKilled ) = 0;// how many points do I award whoever kills this player? + virtual void PlayerKilled( CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor ) = 0;// Called each time a player dies + virtual void DeathNotice( CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor )= 0;// Call this from within a GameRules class to report an obituary. +// Weapon retrieval + virtual BOOL CanHavePlayerItem( CBasePlayer *pPlayer, CBasePlayerItem *pWeapon );// The player is touching an CBasePlayerItem, do I give it to him? + virtual void PlayerGotWeapon( CBasePlayer *pPlayer, CBasePlayerItem *pWeapon ) = 0;// Called each time a player picks up a weapon from the ground + +// Weapon spawn/respawn control + virtual int WeaponShouldRespawn( CBasePlayerItem *pWeapon ) = 0;// should this weapon respawn? + virtual float FlWeaponRespawnTime( CBasePlayerItem *pWeapon ) = 0;// when may this weapon respawn? + virtual float FlWeaponTryRespawn( CBasePlayerItem *pWeapon ) = 0; // can i respawn now, and if not, when should i try again? + virtual Vector VecWeaponRespawnSpot( CBasePlayerItem *pWeapon ) = 0;// where in the world should this weapon respawn? + +// Item retrieval + virtual BOOL CanHaveItem( CBasePlayer *pPlayer, CItem *pItem ) = 0;// is this player allowed to take this item? + virtual void PlayerGotItem( CBasePlayer *pPlayer, CItem *pItem ) = 0;// call each time a player picks up an item (battery, healthkit, longjump) + +// Item spawn/respawn control + virtual int ItemShouldRespawn( CItem *pItem ) = 0;// Should this item respawn? + virtual float FlItemRespawnTime( CItem *pItem ) = 0;// when may this item respawn? + virtual Vector VecItemRespawnSpot( CItem *pItem ) = 0;// where in the world should this item respawn? + +// Ammo retrieval + virtual BOOL CanHaveAmmo( CBasePlayer *pPlayer, const char *pszAmmoName, int iMaxCarry );// can this player take more of this ammo? + virtual void PlayerGotAmmo( CBasePlayer *pPlayer, char *szName, int iCount ) = 0;// called each time a player picks up some ammo in the world + +// Ammo spawn/respawn control + virtual int AmmoShouldRespawn( CBasePlayerAmmo *pAmmo ) = 0;// should this ammo item respawn? + virtual float FlAmmoRespawnTime( CBasePlayerAmmo *pAmmo ) = 0;// when should this ammo item respawn? + virtual Vector VecAmmoRespawnSpot( CBasePlayerAmmo *pAmmo ) = 0;// where in the world should this ammo item respawn? + // by default, everything spawns + +// Healthcharger respawn control + virtual float FlHealthChargerRechargeTime( void ) = 0;// how long until a depleted HealthCharger recharges itself? + virtual float FlHEVChargerRechargeTime( void ) { return 0; }// how long until a depleted HealthCharger recharges itself? + +// What happens to a dead player's weapons + virtual int DeadPlayerWeapons( CBasePlayer *pPlayer ) = 0;// what do I do with a player's weapons when he's killed? + +// What happens to a dead player's ammo + virtual int DeadPlayerAmmo( CBasePlayer *pPlayer ) = 0;// Do I drop ammo when the player dies? How much? + +// Teamplay stuff + virtual const char *GetTeamID( CBaseEntity *pEntity ) = 0;// what team is this entity on? + virtual int PlayerRelationship( CBaseEntity *pPlayer, CBaseEntity *pTarget ) = 0;// What is the player's relationship with this entity? + virtual int GetTeamIndex( const char *pTeamName ) { return -1; } + virtual const char *GetIndexedTeamName( int teamIndex ) { return ""; } + virtual BOOL IsValidTeam( const char *pTeamName ) { return TRUE; } + virtual void ChangePlayerTeam( CBasePlayer *pPlayer, const char *pTeamName, BOOL bKill, BOOL bGib ) {} + virtual const char *SetDefaultPlayerTeam( CBasePlayer *pPlayer ) { return ""; } + +// Sounds + virtual BOOL PlayTextureSounds( void ) { return TRUE; } + virtual BOOL PlayFootstepSounds( CBasePlayer *pl, float fvol ) { return TRUE; } + +// Monsters + virtual BOOL FAllowMonsters( void ) = 0;//are monsters allowed + + // Immediately end a multiplayer game + virtual void EndMultiplayerGame( void ) {} +}; + +extern CGameRules *InstallGameRules( void ); + + +//========================================================= +// CHalfLifeRules - rules for the single player Half-Life +// game. +//========================================================= +class CHalfLifeRules : public CGameRules +{ +public: + CHalfLifeRules ( void ); + +// GR_Think + virtual void Think( void ); + virtual BOOL IsAllowedToSpawn( CBaseEntity *pEntity ); + virtual BOOL FAllowFlashlight( void ) { return TRUE; }; + + virtual BOOL FShouldSwitchWeapon( CBasePlayer *pPlayer, CBasePlayerItem *pWeapon ); + virtual BOOL GetNextBestWeapon( CBasePlayer *pPlayer, CBasePlayerItem *pCurrentWeapon ); + +// Functions to verify the single/multiplayer status of a game + virtual BOOL IsMultiplayer( void ); + virtual BOOL IsDeathmatch( void ); + virtual BOOL IsCoOp( void ); + +// Client connection/disconnection + virtual BOOL ClientConnected( edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ] ); + virtual void InitHUD( CBasePlayer *pl ); // the client dll is ready for updating + virtual void ClientDisconnected( edict_t *pClient ); + +// Client damage rules + virtual float FlPlayerFallDamage( CBasePlayer *pPlayer ); + +// Client spawn/respawn control + virtual void PlayerSpawn( CBasePlayer *pPlayer ); + virtual void PlayerThink( CBasePlayer *pPlayer ); + virtual BOOL FPlayerCanRespawn( CBasePlayer *pPlayer ); + virtual float FlPlayerSpawnTime( CBasePlayer *pPlayer ); + + virtual BOOL AllowAutoTargetCrosshair( void ); + +// Client kills/scoring + virtual int IPointsForKill( CBasePlayer *pAttacker, CBasePlayer *pKilled ); + virtual void PlayerKilled( CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor ); + virtual void DeathNotice( CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor ); + +// Weapon retrieval + virtual void PlayerGotWeapon( CBasePlayer *pPlayer, CBasePlayerItem *pWeapon ); + +// Weapon spawn/respawn control + virtual int WeaponShouldRespawn( CBasePlayerItem *pWeapon ); + virtual float FlWeaponRespawnTime( CBasePlayerItem *pWeapon ); + virtual float FlWeaponTryRespawn( CBasePlayerItem *pWeapon ); + virtual Vector VecWeaponRespawnSpot( CBasePlayerItem *pWeapon ); + +// Item retrieval + virtual BOOL CanHaveItem( CBasePlayer *pPlayer, CItem *pItem ); + virtual void PlayerGotItem( CBasePlayer *pPlayer, CItem *pItem ); + +// Item spawn/respawn control + virtual int ItemShouldRespawn( CItem *pItem ); + virtual float FlItemRespawnTime( CItem *pItem ); + virtual Vector VecItemRespawnSpot( CItem *pItem ); + +// Ammo retrieval + virtual void PlayerGotAmmo( CBasePlayer *pPlayer, char *szName, int iCount ); + +// Ammo spawn/respawn control + virtual int AmmoShouldRespawn( CBasePlayerAmmo *pAmmo ); + virtual float FlAmmoRespawnTime( CBasePlayerAmmo *pAmmo ); + virtual Vector VecAmmoRespawnSpot( CBasePlayerAmmo *pAmmo ); + +// Healthcharger respawn control + virtual float FlHealthChargerRechargeTime( void ); + +// What happens to a dead player's weapons + virtual int DeadPlayerWeapons( CBasePlayer *pPlayer ); + +// What happens to a dead player's ammo + virtual int DeadPlayerAmmo( CBasePlayer *pPlayer ); + +// Monsters + virtual BOOL FAllowMonsters( void ); + +// Teamplay stuff + virtual const char *GetTeamID( CBaseEntity *pEntity ) {return "";}; + virtual int PlayerRelationship( CBaseEntity *pPlayer, CBaseEntity *pTarget ); +}; + +//========================================================= +// CHalfLifeMultiplay - rules for the basic half life multiplayer +// competition +//========================================================= +class CHalfLifeMultiplay : public CGameRules +{ +public: + CHalfLifeMultiplay(); + +// GR_Think + virtual void Think( void ); + virtual void RefreshSkillData( void ); + virtual BOOL IsAllowedToSpawn( CBaseEntity *pEntity ); + virtual BOOL FAllowFlashlight( void ); + + virtual BOOL FShouldSwitchWeapon( CBasePlayer *pPlayer, CBasePlayerItem *pWeapon ); + virtual BOOL GetNextBestWeapon( CBasePlayer *pPlayer, CBasePlayerItem *pCurrentWeapon ); + +// Functions to verify the single/multiplayer status of a game + virtual BOOL IsMultiplayer( void ); + virtual BOOL IsDeathmatch( void ); + virtual BOOL IsCoOp( void ); + +// Client connection/disconnection + // If ClientConnected returns FALSE, the connection is rejected and the user is provided the reason specified in + // svRejectReason + // Only the client's name and remote address are provided to the dll for verification. + virtual BOOL ClientConnected( edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ] ); + virtual void InitHUD( CBasePlayer *pl ); // the client dll is ready for updating + virtual void ClientDisconnected( edict_t *pClient ); + virtual void UpdateGameMode( CBasePlayer *pPlayer ); // the client needs to be informed of the current game mode + +// Client damage rules + virtual float FlPlayerFallDamage( CBasePlayer *pPlayer ); + virtual BOOL FPlayerCanTakeDamage( CBasePlayer *pPlayer, CBaseEntity *pAttacker ); + +// Client spawn/respawn control + virtual void PlayerSpawn( CBasePlayer *pPlayer ); + virtual void PlayerThink( CBasePlayer *pPlayer ); + virtual BOOL FPlayerCanRespawn( CBasePlayer *pPlayer ); + virtual float FlPlayerSpawnTime( CBasePlayer *pPlayer ); + virtual edict_t *GetPlayerSpawnSpot( CBasePlayer *pPlayer ); + + virtual BOOL AllowAutoTargetCrosshair( void ); + virtual BOOL ClientCommand( CBasePlayer *pPlayer, const char *pcmd ); + +// Client kills/scoring + virtual int IPointsForKill( CBasePlayer *pAttacker, CBasePlayer *pKilled ); + virtual void PlayerKilled( CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor ); + virtual void DeathNotice( CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor ); + +// Weapon retrieval + virtual void PlayerGotWeapon( CBasePlayer *pPlayer, CBasePlayerItem *pWeapon ); + virtual BOOL CanHavePlayerItem( CBasePlayer *pPlayer, CBasePlayerItem *pWeapon );// The player is touching an CBasePlayerItem, do I give it to him? + +// Weapon spawn/respawn control + virtual int WeaponShouldRespawn( CBasePlayerItem *pWeapon ); + virtual float FlWeaponRespawnTime( CBasePlayerItem *pWeapon ); + virtual float FlWeaponTryRespawn( CBasePlayerItem *pWeapon ); + virtual Vector VecWeaponRespawnSpot( CBasePlayerItem *pWeapon ); + +// Item retrieval + virtual BOOL CanHaveItem( CBasePlayer *pPlayer, CItem *pItem ); + virtual void PlayerGotItem( CBasePlayer *pPlayer, CItem *pItem ); + +// Item spawn/respawn control + virtual int ItemShouldRespawn( CItem *pItem ); + virtual float FlItemRespawnTime( CItem *pItem ); + virtual Vector VecItemRespawnSpot( CItem *pItem ); + +// Ammo retrieval + virtual void PlayerGotAmmo( CBasePlayer *pPlayer, char *szName, int iCount ); + +// Ammo spawn/respawn control + virtual int AmmoShouldRespawn( CBasePlayerAmmo *pAmmo ); + virtual float FlAmmoRespawnTime( CBasePlayerAmmo *pAmmo ); + virtual Vector VecAmmoRespawnSpot( CBasePlayerAmmo *pAmmo ); + +// Healthcharger respawn control + virtual float FlHealthChargerRechargeTime( void ); + virtual float FlHEVChargerRechargeTime( void ); + +// What happens to a dead player's weapons + virtual int DeadPlayerWeapons( CBasePlayer *pPlayer ); + +// What happens to a dead player's ammo + virtual int DeadPlayerAmmo( CBasePlayer *pPlayer ); + +// Teamplay stuff + virtual const char *GetTeamID( CBaseEntity *pEntity ) {return "";} + virtual int PlayerRelationship( CBaseEntity *pPlayer, CBaseEntity *pTarget ); + + virtual BOOL PlayTextureSounds( void ) { return FALSE; } + virtual BOOL PlayFootstepSounds( CBasePlayer *pl, float fvol ); + +// Monsters + virtual BOOL FAllowMonsters( void ); + + // Immediately end a multiplayer game + virtual void EndMultiplayerGame( void ) { GoToIntermission(); } + +protected: + virtual void ChangeLevel( void ); + virtual void GoToIntermission( void ); + float m_flIntermissionEndTime; + BOOL m_iEndIntermissionButtonHit; + void SendMOTDToClient( edict_t *client ); +}; + +extern DLL_GLOBAL CGameRules* g_pGameRules; diff --git a/dep/rehlsdk/dlls/hornet.h b/dep/rehlsdk/dlls/hornet.h new file mode 100644 index 0000000..98d1710 --- /dev/null +++ b/dep/rehlsdk/dlls/hornet.h @@ -0,0 +1,58 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +//========================================================= +// Hornets +//========================================================= + +//========================================================= +// Hornet Defines +//========================================================= +#define HORNET_TYPE_RED 0 +#define HORNET_TYPE_ORANGE 1 +#define HORNET_RED_SPEED (float)600 +#define HORNET_ORANGE_SPEED (float)800 +#define HORNET_BUZZ_VOLUME (float)0.8 + +extern int iHornetPuff; + +//========================================================= +// Hornet - this is the projectile that the Alien Grunt fires. +//========================================================= +class CHornet : public CBaseMonster +{ +public: + void Spawn( void ); + void Precache( void ); + int Classify ( void ); + int IRelationship ( CBaseEntity *pTarget ); + virtual int Save( CSave &save ); + virtual int Restore( CRestore &restore ); + static TYPEDESCRIPTION m_SaveData[]; + + void IgniteTrail( void ); + void EXPORT StartTrack ( void ); + void EXPORT StartDart ( void ); + void EXPORT TrackTarget ( void ); + void EXPORT TrackTouch ( CBaseEntity *pOther ); + void EXPORT DartTouch( CBaseEntity *pOther ); + void EXPORT DieTouch ( CBaseEntity *pOther ); + + int TakeDamage( entvars_t *pevInflictor, entvars_t *pevAttacker, float flDamage, int bitsDamageType ); + + float m_flStopAttack; + int m_iHornetType; + float m_flFlySpeed; +}; + diff --git a/dep/rehlsdk/dlls/items.h b/dep/rehlsdk/dlls/items.h new file mode 100644 index 0000000..e985296 --- /dev/null +++ b/dep/rehlsdk/dlls/items.h @@ -0,0 +1,29 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef ITEMS_H +#define ITEMS_H + + +class CItem : public CBaseEntity +{ +public: + void Spawn( void ); + CBaseEntity* Respawn( void ); + void EXPORT ItemTouch( CBaseEntity *pOther ); + void EXPORT Materialize( void ); + virtual BOOL MyTouch( CBasePlayer *pPlayer ) { return FALSE; }; +}; + +#endif // ITEMS_H diff --git a/dep/rehlsdk/dlls/maprules.h b/dep/rehlsdk/dlls/maprules.h new file mode 100644 index 0000000..57f9939 --- /dev/null +++ b/dep/rehlsdk/dlls/maprules.h @@ -0,0 +1,22 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef MAPRULES_H +#define MAPRULES_H + + + +#endif // MAPRULES_H + diff --git a/dep/rehlsdk/dlls/monsterevent.h b/dep/rehlsdk/dlls/monsterevent.h new file mode 100644 index 0000000..46c5624 --- /dev/null +++ b/dep/rehlsdk/dlls/monsterevent.h @@ -0,0 +1,34 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef MONSTEREVENT_H +#define MONSTEREVENT_H + +typedef struct +{ + int event; + char *options; +} MonsterEvent_t; + +#define EVENT_SPECIFIC 0 +#define EVENT_SCRIPTED 1000 +#define EVENT_SHARED 2000 +#define EVENT_CLIENT 5000 + +#define MONSTER_EVENT_BODYDROP_LIGHT 2001 +#define MONSTER_EVENT_BODYDROP_HEAVY 2002 + +#define MONSTER_EVENT_SWISHSOUND 2010 + +#endif // MONSTEREVENT_H diff --git a/dep/rehlsdk/dlls/monsters.h b/dep/rehlsdk/dlls/monsters.h new file mode 100644 index 0000000..591ea52 --- /dev/null +++ b/dep/rehlsdk/dlls/monsters.h @@ -0,0 +1,183 @@ +/*** +* +* Copyright (c) 1996-2001, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* This source code contains proprietary and confidential information of +* Valve LLC and its suppliers. Access to this code is restricted to +* persons who have executed a written SDK license with Valve. Any access, +* use or distribution of this code by or to any unlicensed person is illegal. +* +****/ +#ifndef MONSTERS_H +#include "skill.h" +#define MONSTERS_H + +/* + +===== monsters.h ======================================================== + + Header file for monster-related utility code + +*/ + +// CHECKLOCALMOVE result types +#define LOCALMOVE_INVALID 0 // move is not possible +#define LOCALMOVE_INVALID_DONT_TRIANGULATE 1 // move is not possible, don't try to triangulate +#define LOCALMOVE_VALID 2 // move is possible + +// Hit Group standards +#define HITGROUP_GENERIC 0 +#define HITGROUP_HEAD 1 +#define HITGROUP_CHEST 2 +#define HITGROUP_STOMACH 3 +#define HITGROUP_LEFTARM 4 +#define HITGROUP_RIGHTARM 5 +#define HITGROUP_LEFTLEG 6 +#define HITGROUP_RIGHTLEG 7 + + +// Monster Spawnflags +#define SF_MONSTER_WAIT_TILL_SEEN 1// spawnflag that makes monsters wait until player can see them before attacking. +#define SF_MONSTER_GAG 2 // no idle noises from this monster +#define SF_MONSTER_HITMONSTERCLIP 4 +// 8 +#define SF_MONSTER_PRISONER 16 // monster won't attack anyone, no one will attacke him. +// 32 +// 64 +#define SF_MONSTER_WAIT_FOR_SCRIPT 128 //spawnflag that makes monsters wait to check for attacking until the script is done or they've been attacked +#define SF_MONSTER_PREDISASTER 256 //this is a predisaster scientist or barney. Influences how they speak. +#define SF_MONSTER_FADECORPSE 512 // Fade out corpse after death +#define SF_MONSTER_FALL_TO_GROUND 0x80000000 + +// specialty spawnflags +#define SF_MONSTER_TURRET_AUTOACTIVATE 32 +#define SF_MONSTER_TURRET_STARTINACTIVE 64 +#define SF_MONSTER_WAIT_UNTIL_PROVOKED 64 // don't attack the player unless provoked + + + +// MoveToOrigin stuff +#define MOVE_START_TURN_DIST 64 // when this far away from moveGoal, start turning to face next goal +#define MOVE_STUCK_DIST 32 // if a monster can't step this far, it is stuck. + + +// MoveToOrigin stuff +#define MOVE_NORMAL 0// normal move in the direction monster is facing +#define MOVE_STRAFE 1// moves in direction specified, no matter which way monster is facing + +// spawn flags 256 and above are already taken by the engine +extern void UTIL_MoveToOrigin( edict_t* pent, const Vector &vecGoal, float flDist, int iMoveType ); + +Vector VecCheckToss ( entvars_t *pev, const Vector &vecSpot1, Vector vecSpot2, float flGravityAdj = 1.0 ); +Vector VecCheckThrow ( entvars_t *pev, const Vector &vecSpot1, Vector vecSpot2, float flSpeed, float flGravityAdj = 1.0 ); +extern DLL_GLOBAL Vector g_vecAttackDir; +extern DLL_GLOBAL CONSTANT float g_flMeleeRange; +extern DLL_GLOBAL CONSTANT float g_flMediumRange; +extern DLL_GLOBAL CONSTANT float g_flLongRange; +extern void EjectBrass (const Vector &vecOrigin, const Vector &vecVelocity, float rotation, int model, int soundtype ); +extern void ExplodeModel( const Vector &vecOrigin, float speed, int model, int count ); + +BOOL FBoxVisible ( entvars_t *pevLooker, entvars_t *pevTarget ); +BOOL FBoxVisible ( entvars_t *pevLooker, entvars_t *pevTarget, Vector &vecTargetOrigin, float flSize = 0.0 ); + +// monster to monster relationship types +#define R_AL -2 // (ALLY) pals. Good alternative to R_NO when applicable. +#define R_FR -1// (FEAR)will run +#define R_NO 0// (NO RELATIONSHIP) disregard +#define R_DL 1// (DISLIKE) will attack +#define R_HT 2// (HATE)will attack this character instead of any visible DISLIKEd characters +#define R_NM 3// (NEMESIS) A monster Will ALWAYS attack its nemsis, no matter what + + +// these bits represent the monster's memory +#define MEMORY_CLEAR 0 +#define bits_MEMORY_PROVOKED ( 1 << 0 )// right now only used for houndeyes. +#define bits_MEMORY_INCOVER ( 1 << 1 )// monster knows it is in a covered position. +#define bits_MEMORY_SUSPICIOUS ( 1 << 2 )// Ally is suspicious of the player, and will move to provoked more easily +#define bits_MEMORY_PATH_FINISHED ( 1 << 3 )// Finished monster path (just used by big momma for now) +#define bits_MEMORY_ON_PATH ( 1 << 4 )// Moving on a path +#define bits_MEMORY_MOVE_FAILED ( 1 << 5 )// Movement has already failed +#define bits_MEMORY_FLINCHED ( 1 << 6 )// Has already flinched +#define bits_MEMORY_KILLED ( 1 << 7 )// HACKHACK -- remember that I've already called my Killed() +#define bits_MEMORY_CUSTOM4 ( 1 << 28 ) // Monster-specific memory +#define bits_MEMORY_CUSTOM3 ( 1 << 29 ) // Monster-specific memory +#define bits_MEMORY_CUSTOM2 ( 1 << 30 ) // Monster-specific memory +#define bits_MEMORY_CUSTOM1 ( 1 << 31 ) // Monster-specific memory + +// trigger conditions for scripted AI +// these MUST match the CHOICES interface in halflife.fgd for the base monster +enum +{ + AITRIGGER_NONE = 0, + AITRIGGER_SEEPLAYER_ANGRY_AT_PLAYER, + AITRIGGER_TAKEDAMAGE, + AITRIGGER_HALFHEALTH, + AITRIGGER_DEATH, + AITRIGGER_SQUADMEMBERDIE, + AITRIGGER_SQUADLEADERDIE, + AITRIGGER_HEARWORLD, + AITRIGGER_HEARPLAYER, + AITRIGGER_HEARCOMBAT, + AITRIGGER_SEEPLAYER_UNCONDITIONAL, + AITRIGGER_SEEPLAYER_NOT_IN_COMBAT, +}; +/* + 0 : "No Trigger" + 1 : "See Player" + 2 : "Take Damage" + 3 : "50% Health Remaining" + 4 : "Death" + 5 : "Squad Member Dead" + 6 : "Squad Leader Dead" + 7 : "Hear World" + 8 : "Hear Player" + 9 : "Hear Combat" +*/ + +// +// A gib is a chunk of a body, or a piece of wood/metal/rocks/etc. +// +class CGib : public CBaseEntity +{ +public: + void Spawn( const char *szGibModel ); + void EXPORT BounceGibTouch ( CBaseEntity *pOther ); + void EXPORT StickyGibTouch ( CBaseEntity *pOther ); + void EXPORT WaitTillLand( void ); + void LimitVelocity( void ); + + virtual int ObjectCaps( void ) { return (CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION) | FCAP_DONT_SAVE; } + static void SpawnHeadGib( entvars_t *pevVictim ); + static void SpawnRandomGibs( entvars_t *pevVictim, int cGibs, int human ); + static void SpawnStickyGibs( entvars_t *pevVictim, Vector vecOrigin, int cGibs ); + + int m_bloodColor; + int m_cBloodDecals; + int m_material; + float m_lifeTime; +}; + + +#define CUSTOM_SCHEDULES\ + virtual Schedule_t *ScheduleFromName( const char *pName );\ + static Schedule_t *m_scheduleList[]; + +#define DEFINE_CUSTOM_SCHEDULES(derivedClass)\ + Schedule_t *derivedClass::m_scheduleList[] = + +#define IMPLEMENT_CUSTOM_SCHEDULES(derivedClass, baseClass)\ + Schedule_t *derivedClass::ScheduleFromName( const char *pName )\ + {\ + Schedule_t *pSchedule = ScheduleInList( pName, m_scheduleList, ARRAYSIZE(m_scheduleList) );\ + if ( !pSchedule )\ + return baseClass::ScheduleFromName(pName);\ + return pSchedule;\ + } + + + +#endif //MONSTERS_H diff --git a/dep/rehlsdk/dlls/nodes.h b/dep/rehlsdk/dlls/nodes.h new file mode 100644 index 0000000..29ffc5c --- /dev/null +++ b/dep/rehlsdk/dlls/nodes.h @@ -0,0 +1,379 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +//========================================================= +// nodes.h +//========================================================= + +#ifndef NODES_H +#define NODES_H + +//========================================================= +// DEFINE +//========================================================= +#define MAX_STACK_NODES 100 +#define NO_NODE -1 +#define MAX_NODE_HULLS 4 + +#define bits_NODE_LAND ( 1 << 0 ) // Land node, so nudge if necessary. +#define bits_NODE_AIR ( 1 << 1 ) // Air node, don't nudge. +#define bits_NODE_WATER ( 1 << 2 ) // Water node, don't nudge. +#define bits_NODE_GROUP_REALM (bits_NODE_LAND | bits_NODE_AIR | bits_NODE_WATER) + +//========================================================= +// Instance of a node. +//========================================================= +class CNode +{ +public: + Vector m_vecOrigin;// location of this node in space + Vector m_vecOriginPeek; // location of this node (LAND nodes are NODE_HEIGHT higher). + BYTE m_Region[3]; // Which of 256 regions do each of the coordinate belong? + int m_afNodeInfo;// bits that tell us more about this location + + int m_cNumLinks; // how many links this node has + int m_iFirstLink;// index of this node's first link in the link pool. + + // Where to start looking in the compressed routing table (offset into m_pRouteInfo). + // (4 hull sizes -- smallest to largest + fly/swim), and secondly, door capability. + // + int m_pNextBestNode[MAX_NODE_HULLS][2]; + + // Used in finding the shortest path. m_fClosestSoFar is -1 if not visited. + // Then it is the distance to the source. If another path uses this node + // and has a closer distance, then m_iPreviousNode is also updated. + // + float m_flClosestSoFar; // Used in finding the shortest path. + int m_iPreviousNode; + + short m_sHintType;// there is something interesting in the world at this node's position + short m_sHintActivity;// there is something interesting in the world at this node's position + float m_flHintYaw;// monster on this node should face this yaw to face the hint. +}; + +//========================================================= +// CLink - A link between 2 nodes +//========================================================= +#define bits_LINK_SMALL_HULL ( 1 << 0 )// headcrab box can fit through this connection +#define bits_LINK_HUMAN_HULL ( 1 << 1 )// player box can fit through this connection +#define bits_LINK_LARGE_HULL ( 1 << 2 )// big box can fit through this connection +#define bits_LINK_FLY_HULL ( 1 << 3 )// a flying big box can fit through this connection +#define bits_LINK_DISABLED ( 1 << 4 )// link is not valid when the set + +#define NODE_SMALL_HULL 0 +#define NODE_HUMAN_HULL 1 +#define NODE_LARGE_HULL 2 +#define NODE_FLY_HULL 3 + +class CLink +{ +public: + int m_iSrcNode;// the node that 'owns' this link ( keeps us from having to make reverse lookups ) + int m_iDestNode;// the node on the other end of the link. + + entvars_t *m_pLinkEnt;// the entity that blocks this connection (doors, etc) + + // m_szLinkEntModelname is not necessarily NULL terminated (so we can store it in a more alignment-friendly 4 bytes) + char m_szLinkEntModelname[ 4 ];// the unique name of the brush model that blocks the connection (this is kept for save/restore) + + int m_afLinkInfo;// information about this link + float m_flWeight;// length of the link line segment +}; + + +typedef struct +{ + int m_SortedBy[3]; + int m_CheckedEvent; +} DIST_INFO; + +typedef struct +{ + Vector v; + short n; // Nearest node or -1 if no node found. +} CACHE_ENTRY; + +//========================================================= +// CGraph +//========================================================= +#define GRAPH_VERSION (int)16// !!!increment this whever graph/node/link classes change, to obsolesce older disk files. +class CGraph +{ +public: + +// the graph has two flags, and should not be accessed unless both flags are TRUE! + BOOL m_fGraphPresent;// is the graph in memory? + BOOL m_fGraphPointersSet;// are the entity pointers for the graph all set? + BOOL m_fRoutingComplete; // are the optimal routes computed, yet? + + CNode *m_pNodes;// pointer to the memory block that contains all node info + CLink *m_pLinkPool;// big list of all node connections + char *m_pRouteInfo; // compressed routing information the nodes use. + + int m_cNodes;// total number of nodes + int m_cLinks;// total number of links + int m_nRouteInfo; // size of m_pRouteInfo in bytes. + + // Tables for making nearest node lookup faster. SortedBy provided nodes in a + // order of a particular coordinate. Instead of doing a binary search, RangeStart + // and RangeEnd let you get to the part of SortedBy that you are interested in. + // + // Once you have a point of interest, the only way you'll find a closer point is + // if at least one of the coordinates is closer than the ones you have now. So we + // search each range. After the search is exhausted, we know we have the closest + // node. + // +#define CACHE_SIZE 128 +#define NUM_RANGES 256 + DIST_INFO *m_di; // This is m_cNodes long, but the entries don't correspond to CNode entries. + int m_RangeStart[3][NUM_RANGES]; + int m_RangeEnd[3][NUM_RANGES]; + float m_flShortest; + int m_iNearest; + int m_minX, m_minY, m_minZ, m_maxX, m_maxY, m_maxZ; + int m_minBoxX, m_minBoxY, m_minBoxZ, m_maxBoxX, m_maxBoxY, m_maxBoxZ; + int m_CheckedCounter; + float m_RegionMin[3], m_RegionMax[3]; // The range of nodes. + CACHE_ENTRY m_Cache[CACHE_SIZE]; + + + int m_HashPrimes[16]; + short *m_pHashLinks; + int m_nHashLinks; + + + // kinda sleazy. In order to allow variety in active idles for monster groups in a room with more than one node, + // we keep track of the last node we searched from and store it here. Subsequent searches by other monsters will pick + // up where the last search stopped. + int m_iLastActiveIdleSearch; + + // another such system used to track the search for cover nodes, helps greatly with two monsters trying to get to the same node. + int m_iLastCoverSearch; + + // functions to create the graph + int LinkVisibleNodes ( CLink *pLinkPool, FILE *file, int *piBadNode ); + int RejectInlineLinks ( CLink *pLinkPool, FILE *file ); + int FindShortestPath ( int *piPath, int iStart, int iDest, int iHull, int afCapMask); + int FindNearestNode ( const Vector &vecOrigin, CBaseEntity *pEntity ); + int FindNearestNode ( const Vector &vecOrigin, int afNodeTypes ); + //int FindNearestLink ( const Vector &vecTestPoint, int *piNearestLink, BOOL *pfAlongLine ); + float PathLength( int iStart, int iDest, int iHull, int afCapMask ); + int NextNodeInRoute( int iCurrentNode, int iDest, int iHull, int iCap ); + + enum NODEQUERY { NODEGRAPH_DYNAMIC, NODEGRAPH_STATIC }; + // A static query means we're asking about the possiblity of handling this entity at ANY time + // A dynamic query means we're asking about it RIGHT NOW. So we should query the current state + int HandleLinkEnt ( int iNode, entvars_t *pevLinkEnt, int afCapMask, NODEQUERY queryType ); + entvars_t* LinkEntForLink ( CLink *pLink, CNode *pNode ); + void ShowNodeConnections ( int iNode ); + void InitGraph( void ); + int AllocNodes ( void ); + + int CheckNODFile(char *szMapName); + int FLoadGraph(char *szMapName); + int FSaveGraph(char *szMapName); + int FSetGraphPointers(void); + void CheckNode(Vector vecOrigin, int iNode); + + void BuildRegionTables(void); + void ComputeStaticRoutingTables(void); + void TestRoutingTables(void); + + void HashInsert(int iSrcNode, int iDestNode, int iKey); + void HashSearch(int iSrcNode, int iDestNode, int &iKey); + void HashChoosePrimes(int TableSize); + void BuildLinkLookups(void); + + void SortNodes(void); + + int HullIndex( const CBaseEntity *pEntity ); // what hull the monster uses + int NodeType( const CBaseEntity *pEntity ); // what node type the monster uses + inline int CapIndex( int afCapMask ) + { + if (afCapMask & (bits_CAP_OPEN_DOORS | bits_CAP_AUTO_DOORS | bits_CAP_USE)) + return 1; + return 0; + } + + + inline CNode &Node( int i ) + { +#ifdef _DEBUG + if ( !m_pNodes || i < 0 || i > m_cNodes ) + ALERT( at_error, "Bad Node!\n" ); +#endif + return m_pNodes[i]; + } + + inline CLink &Link( int i ) + { +#ifdef _DEBUG + if ( !m_pLinkPool || i < 0 || i > m_cLinks ) + ALERT( at_error, "Bad link!\n" ); +#endif + return m_pLinkPool[i]; + } + + inline CLink &NodeLink( int iNode, int iLink ) + { + return Link( Node( iNode ).m_iFirstLink + iLink ); + } + + inline CLink &NodeLink( const CNode &node, int iLink ) + { + return Link( node.m_iFirstLink + iLink ); + } + + inline int INodeLink ( int iNode, int iLink ) + { + return NodeLink( iNode, iLink ).m_iDestNode; + } + +#if 0 + inline CNode &SourceNode( int iNode, int iLink ) + { + return Node( NodeLink( iNode, iLink ).m_iSrcNode ); + } + + inline CNode &DestNode( int iNode, int iLink ) + { + return Node( NodeLink( iNode, iLink ).m_iDestNode ); + } + + inline CNode *PNodeLink ( int iNode, int iLink ) + { + return &DestNode( iNode, iLink ); + } +#endif +}; + +//========================================================= +// Nodes start out as ents in the level. The node graph +// is built, then these ents are discarded. +//========================================================= +class CNodeEnt : public CBaseEntity +{ + void Spawn( void ); + void KeyValue( KeyValueData *pkvd ); + virtual int ObjectCaps( void ) { return CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } + + short m_sHintType; + short m_sHintActivity; +}; + + +//========================================================= +// CStack - last in, first out. +//========================================================= +class CStack +{ +public: + CStack( void ); + void Push( int value ); + int Pop( void ); + int Top( void ); + int Empty( void ) { return m_level==0; } + int Size( void ) { return m_level; } + void CopyToArray ( int *piArray ); + +private: + int m_stack[ MAX_STACK_NODES ]; + int m_level; +}; + + +//========================================================= +// CQueue - first in, first out. +//========================================================= +class CQueue +{ +public: + + CQueue( void );// constructor + inline int Full ( void ) { return ( m_cSize == MAX_STACK_NODES ); } + inline int Empty ( void ) { return ( m_cSize == 0 ); } + //inline int Tail ( void ) { return ( m_queue[ m_tail ] ); } + inline int Size ( void ) { return ( m_cSize ); } + void Insert( int, float ); + int Remove( float & ); + +private: + int m_cSize; + struct tag_QUEUE_NODE + { + int Id; + float Priority; + } m_queue[ MAX_STACK_NODES ]; + int m_head; + int m_tail; +}; + +//========================================================= +// CQueuePriority - Priority queue (smallest item out first). +// +//========================================================= +class CQueuePriority +{ +public: + + CQueuePriority( void );// constructor + inline int Full ( void ) { return ( m_cSize == MAX_STACK_NODES ); } + inline int Empty ( void ) { return ( m_cSize == 0 ); } + //inline int Tail ( float & ) { return ( m_queue[ m_tail ].Id ); } + inline int Size ( void ) { return ( m_cSize ); } + void Insert( int, float ); + int Remove( float &); + +private: + int m_cSize; + struct tag_HEAP_NODE + { + int Id; + float Priority; + } m_heap[ MAX_STACK_NODES ]; + void Heap_SiftDown(int); + void Heap_SiftUp(void); + +}; + +//========================================================= +// hints - these MUST coincide with the HINTS listed under +// info_node in the FGD file! +//========================================================= +enum +{ + HINT_NONE = 0, + HINT_WORLD_DOOR, + HINT_WORLD_WINDOW, + HINT_WORLD_BUTTON, + HINT_WORLD_MACHINERY, + HINT_WORLD_LEDGE, + HINT_WORLD_LIGHT_SOURCE, + HINT_WORLD_HEAT_SOURCE, + HINT_WORLD_BLINKING_LIGHT, + HINT_WORLD_BRIGHT_COLORS, + HINT_WORLD_HUMAN_BLOOD, + HINT_WORLD_ALIEN_BLOOD, + + HINT_TACTICAL_EXIT = 100, + HINT_TACTICAL_VANTAGE, + HINT_TACTICAL_AMBUSH, + + HINT_STUKA_PERCH = 300, + HINT_STUKA_LANDING, +}; + +extern CGraph WorldGraph; + +#endif // NODES_H diff --git a/dep/rehlsdk/dlls/plane.h b/dep/rehlsdk/dlls/plane.h new file mode 100644 index 0000000..af70f1c --- /dev/null +++ b/dep/rehlsdk/dlls/plane.h @@ -0,0 +1,43 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef PLANE_H +#define PLANE_H + +//========================================================= +// Plane +//========================================================= +class CPlane +{ +public: + CPlane ( void ); + + //========================================================= + // InitializePlane - Takes a normal for the plane and a + // point on the plane and + //========================================================= + void InitializePlane ( const Vector &vecNormal, const Vector &vecPoint ); + + //========================================================= + // PointInFront - determines whether the given vector is + // in front of the plane. + //========================================================= + BOOL PointInFront ( const Vector &vecPoint ); + + Vector m_vecNormal; + float m_flDist; + BOOL m_fInitialized; +}; + +#endif // PLANE_H diff --git a/dep/rehlsdk/dlls/player.h b/dep/rehlsdk/dlls/player.h new file mode 100644 index 0000000..f760548 --- /dev/null +++ b/dep/rehlsdk/dlls/player.h @@ -0,0 +1,336 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef PLAYER_H +#define PLAYER_H + + +#include "pm_materials.h" + + +#define PLAYER_FATAL_FALL_SPEED 1024// approx 60 feet +#define PLAYER_MAX_SAFE_FALL_SPEED 580// approx 20 feet +#define DAMAGE_FOR_FALL_SPEED (float) 100 / ( PLAYER_FATAL_FALL_SPEED - PLAYER_MAX_SAFE_FALL_SPEED )// damage per unit per second. +#define PLAYER_MIN_BOUNCE_SPEED 200 +#define PLAYER_FALL_PUNCH_THRESHHOLD (float)350 // won't punch player's screen/make scrape noise unless player falling at least this fast. + +// +// Player PHYSICS FLAGS bits +// +#define PFLAG_ONLADDER ( 1<<0 ) +#define PFLAG_ONSWING ( 1<<0 ) +#define PFLAG_ONTRAIN ( 1<<1 ) +#define PFLAG_ONBARNACLE ( 1<<2 ) +#define PFLAG_DUCKING ( 1<<3 ) // In the process of ducking, but totally squatted yet +#define PFLAG_USING ( 1<<4 ) // Using a continuous entity +#define PFLAG_OBSERVER ( 1<<5 ) // player is locked in stationary cam mode. Spectators can move, observers can't. + +// +// generic player +// +//----------------------------------------------------- +//This is Half-Life player entity +//----------------------------------------------------- +#define CSUITPLAYLIST 4 // max of 4 suit sentences queued up at any time + +#define SUIT_GROUP TRUE +#define SUIT_SENTENCE FALSE + +#define SUIT_REPEAT_OK 0 +#define SUIT_NEXT_IN_30SEC 30 +#define SUIT_NEXT_IN_1MIN 60 +#define SUIT_NEXT_IN_5MIN 300 +#define SUIT_NEXT_IN_10MIN 600 +#define SUIT_NEXT_IN_30MIN 1800 +#define SUIT_NEXT_IN_1HOUR 3600 + +#define CSUITNOREPEAT 32 + +#define SOUND_FLASHLIGHT_ON "items/flashlight1.wav" +#define SOUND_FLASHLIGHT_OFF "items/flashlight1.wav" + +#define TEAM_NAME_LENGTH 16 + +typedef enum +{ + PLAYER_IDLE, + PLAYER_WALK, + PLAYER_JUMP, + PLAYER_SUPERJUMP, + PLAYER_DIE, + PLAYER_ATTACK1, +} PLAYER_ANIM; + +#define MAX_ID_RANGE 2048 +#define SBAR_STRING_SIZE 128 + +enum sbar_data +{ + SBAR_ID_TARGETNAME = 1, + SBAR_ID_TARGETHEALTH, + SBAR_ID_TARGETARMOR, + SBAR_END, +}; + +#define CHAT_INTERVAL 1.0f + +class CBasePlayer : public CBaseMonster +{ +public: + + // Spectator camera + void Observer_FindNextPlayer( bool bReverse ); + void Observer_HandleButtons(); + void Observer_SetMode( int iMode ); + void Observer_CheckTarget(); + void Observer_CheckProperties(); + EHANDLE m_hObserverTarget; + float m_flNextObserverInput; + int m_iObserverWeapon; // weapon of current tracked target + int m_iObserverLastMode;// last used observer mode + int IsObserver() { return pev->iuser1; }; + int random_seed; // See that is shared between client & server for shared weapons code + + int m_iPlayerSound;// the index of the sound list slot reserved for this player + int m_iTargetVolume;// ideal sound volume. + int m_iWeaponVolume;// how loud the player's weapon is right now. + int m_iExtraSoundTypes;// additional classification for this weapon's sound + int m_iWeaponFlash;// brightness of the weapon flash + float m_flStopExtraSoundTime; + + float m_flFlashLightTime; // Time until next battery draw/Recharge + int m_iFlashBattery; // Flashlight Battery Draw + + int m_afButtonLast; + int m_afButtonPressed; + int m_afButtonReleased; + + edict_t *m_pentSndLast; // last sound entity to modify player room type + float m_flSndRoomtype; // last roomtype set by sound entity + float m_flSndRange; // dist from player to sound entity + + float m_flFallVelocity; + + int m_rgItems[MAX_ITEMS]; + int m_fKnownItem; // True when a new item needs to be added + int m_fNewAmmo; // True when a new item has been added + + unsigned int m_afPhysicsFlags; // physics flags - set when 'normal' physics should be revisited or overriden + float m_fNextSuicideTime; // the time after which the player can next use the suicide command + + +// these are time-sensitive things that we keep track of + float m_flTimeStepSound; // when the last stepping sound was made + float m_flTimeWeaponIdle; // when to play another weapon idle animation. + float m_flSwimTime; // how long player has been underwater + float m_flDuckTime; // how long we've been ducking + float m_flWallJumpTime; // how long until next walljump + + float m_flSuitUpdate; // when to play next suit update + int m_rgSuitPlayList[CSUITPLAYLIST];// next sentencenum to play for suit update + int m_iSuitPlayNext; // next sentence slot for queue storage; + int m_rgiSuitNoRepeat[CSUITNOREPEAT]; // suit sentence no repeat list + float m_rgflSuitNoRepeatTime[CSUITNOREPEAT]; // how long to wait before allowing repeat + int m_lastDamageAmount; // Last damage taken + float m_tbdPrev; // Time-based damage timer + + float m_flgeigerRange; // range to nearest radiation source + float m_flgeigerDelay; // delay per update of range msg to client + int m_igeigerRangePrev; + int m_iStepLeft; // alternate left/right foot stepping sound + char m_szTextureName[CBTEXTURENAMEMAX]; // current texture name we're standing on + char m_chTextureType; // current texture type + + int m_idrowndmg; // track drowning damage taken + int m_idrownrestored; // track drowning damage restored + + int m_bitsHUDDamage; // Damage bits for the current fame. These get sent to + // the hude via the DAMAGE message + BOOL m_fInitHUD; // True when deferred HUD restart msg needs to be sent + BOOL m_fGameHUDInitialized; + int m_iTrain; // Train control position + BOOL m_fWeapon; // Set this to FALSE to force a reset of the current weapon HUD info + + EHANDLE m_pTank; // the tank which the player is currently controlling, NULL if no tank + float m_fDeadTime; // the time at which the player died (used in PlayerDeathThink()) + + BOOL m_fNoPlayerSound; // a debugging feature. Player makes no sound if this is true. + BOOL m_fLongJump; // does this player have the longjump module? + + float m_tSneaking; + int m_iUpdateTime; // stores the number of frame ticks before sending HUD update messages + int m_iClientHealth; // the health currently known by the client. If this changes, send a new + int m_iClientBattery; // the Battery currently known by the client. If this changes, send a new + int m_iHideHUD; // the players hud weapon info is to be hidden + int m_iClientHideHUD; + int m_iFOV; // field of view + int m_iClientFOV; // client's known FOV + // usable player items + CBasePlayerItem *m_rgpPlayerItems[MAX_ITEM_TYPES]; + CBasePlayerItem *m_pActiveItem; + CBasePlayerItem *m_pClientActiveItem; // client version of the active item + CBasePlayerItem *m_pLastItem; + // shared ammo slots + int m_rgAmmo[MAX_AMMO_SLOTS]; + int m_rgAmmoLast[MAX_AMMO_SLOTS]; + + Vector m_vecAutoAim; + BOOL m_fOnTarget; + int m_iDeaths; + float m_iRespawnFrames; // used in PlayerDeathThink() to make sure players can always respawn + + int m_lastx, m_lasty; // These are the previous update's crosshair angles, DON"T SAVE/RESTORE + + int m_nCustomSprayFrames;// Custom clan logo frames for this player + float m_flNextDecalTime;// next time this player can spray a decal + + char m_szTeamName[TEAM_NAME_LENGTH]; + + virtual void Spawn( void ); + void Pain( void ); + +// virtual void Think( void ); + virtual void Jump( void ); + virtual void Duck( void ); + virtual void PreThink( void ); + virtual void PostThink( void ); + virtual Vector GetGunPosition( void ); + virtual int TakeHealth( float flHealth, int bitsDamageType ); + virtual void TraceAttack( entvars_t *pevAttacker, float flDamage, Vector vecDir, TraceResult *ptr, int bitsDamageType); + virtual int TakeDamage( entvars_t* pevInflictor, entvars_t* pevAttacker, float flDamage, int bitsDamageType); + virtual void Killed( entvars_t *pevAttacker, int iGib ); + virtual Vector BodyTarget( const Vector &posSrc ) { return Center( ) + pev->view_ofs * RANDOM_FLOAT( 0.5, 1.1 ); }; // position to shoot at + virtual void StartSneaking( void ) { m_tSneaking = gpGlobals->time - 1; } + virtual void StopSneaking( void ) { m_tSneaking = gpGlobals->time + 30; } + virtual BOOL IsSneaking( void ) { return m_tSneaking <= gpGlobals->time; } + virtual BOOL IsAlive( void ) { return (pev->deadflag == DEAD_NO) && pev->health > 0; } + virtual BOOL ShouldFadeOnDeath( void ) { return FALSE; } + virtual BOOL IsPlayer( void ) { return TRUE; } // Spectators should return FALSE for this, they aren't "players" as far as game logic is concerned + + virtual BOOL IsNetClient( void ) { return TRUE; } // Bots should return FALSE for this, they can't receive NET messages + // Spectators should return TRUE for this + virtual const char *TeamID( void ); + + virtual int Save( CSave &save ); + virtual int Restore( CRestore &restore ); + void RenewItems(void); + void PackDeadPlayerItems( void ); + void RemoveAllItems( BOOL removeSuit ); + BOOL SwitchWeapon( CBasePlayerItem *pWeapon ); + + // JOHN: sends custom messages if player HUD data has changed (eg health, ammo) + virtual void UpdateClientData( void ); + + static TYPEDESCRIPTION m_playerSaveData[]; + + // Player is moved across the transition by other means + virtual int ObjectCaps( void ) { return CBaseMonster :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION; } + virtual void Precache( void ); + BOOL IsOnLadder( void ); + BOOL FlashlightIsOn( void ); + void FlashlightTurnOn( void ); + void FlashlightTurnOff( void ); + + void UpdatePlayerSound ( void ); + void DeathSound ( void ); + + int Classify ( void ); + void SetAnimation( PLAYER_ANIM playerAnim ); + void SetWeaponAnimType( const char *szExtention ); + char m_szAnimExtention[32]; + + // custom player functions + virtual void ImpulseCommands( void ); + void CheatImpulseCommands( int iImpulse ); + + void StartDeathCam( void ); + void StartObserver( Vector vecPosition, Vector vecViewAngle ); + + void AddPoints( int score, BOOL bAllowNegativeScore ); + void AddPointsToTeam( int score, BOOL bAllowNegativeScore ); + BOOL AddPlayerItem( CBasePlayerItem *pItem ); + BOOL RemovePlayerItem( CBasePlayerItem *pItem ); + void DropPlayerItem ( char *pszItemName ); + BOOL HasPlayerItem( CBasePlayerItem *pCheckItem ); + BOOL HasNamedPlayerItem( const char *pszItemName ); + BOOL HasWeapons( void );// do I have ANY weapons? + void SelectPrevItem( int iItem ); + void SelectNextItem( int iItem ); + void SelectLastItem(void); + void SelectItem(const char *pstr); + void ItemPreFrame( void ); + void ItemPostFrame( void ); + void GiveNamedItem( const char *szName ); + void EnableControl(BOOL fControl); + + int GiveAmmo( int iAmount, char *szName, int iMax ); + void SendAmmoUpdate(void); + + void WaterMove( void ); + void EXPORT PlayerDeathThink( void ); + void PlayerUse( void ); + + void CheckSuitUpdate(); + void SetSuitUpdate(char *name, int fgroup, int iNoRepeat); + void UpdateGeigerCounter( void ); + void CheckTimeBasedDamage( void ); + + BOOL FBecomeProne ( void ); + void BarnacleVictimBitten ( entvars_t *pevBarnacle ); + void BarnacleVictimReleased ( void ); + static int GetAmmoIndex(const char *psz); + int AmmoInventory( int iAmmoIndex ); + int Illumination( void ); + + void ResetAutoaim( void ); + Vector GetAutoaimVector( float flDelta ); + Vector AutoaimDeflection( Vector &vecSrc, float flDist, float flDelta ); + + void ForceClientDllUpdate( void ); // Forces all client .dll specific data to be resent to client. + + void DeathMessage( entvars_t *pevKiller ); + + void SetCustomDecalFrames( int nFrames ); + int GetCustomDecalFrames( void ); + + void CBasePlayer::TabulateAmmo( void ); + + float m_flStartCharge; + float m_flAmmoStartCharge; + float m_flPlayAftershock; + float m_flNextAmmoBurn;// while charging, when to absorb another unit of player's ammo? + + //Player ID + void InitStatusBar( void ); + void UpdateStatusBar( void ); + int m_izSBarState[ SBAR_END ]; + float m_flNextSBarUpdateTime; + float m_flStatusBarDisappearDelay; + char m_SbarString0[ SBAR_STRING_SIZE ]; + char m_SbarString1[ SBAR_STRING_SIZE ]; + + float m_flNextChatTime; + +}; + +#define AUTOAIM_2DEGREES 0.0348994967025 +#define AUTOAIM_5DEGREES 0.08715574274766 +#define AUTOAIM_8DEGREES 0.1391731009601 +#define AUTOAIM_10DEGREES 0.1736481776669 + + +extern int gmsgHudText; +extern BOOL gInitHUD; + +#endif // PLAYER_H diff --git a/dep/rehlsdk/dlls/saverestore.h b/dep/rehlsdk/dlls/saverestore.h new file mode 100644 index 0000000..c3761f3 --- /dev/null +++ b/dep/rehlsdk/dlls/saverestore.h @@ -0,0 +1,169 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// Implementation in UTIL.CPP +#ifndef SAVERESTORE_H +#define SAVERESTORE_H + +class CBaseEntity; + +class CSaveRestoreBuffer +{ +public: + CSaveRestoreBuffer( void ); + CSaveRestoreBuffer( SAVERESTOREDATA *pdata ); + ~CSaveRestoreBuffer( void ); + + int EntityIndex( entvars_t *pevLookup ); + int EntityIndex( edict_t *pentLookup ); + int EntityIndex( EOFFSET eoLookup ); + int EntityIndex( CBaseEntity *pEntity ); + + int EntityFlags( int entityIndex, int flags ) { return EntityFlagsSet( entityIndex, 0 ); } + int EntityFlagsSet( int entityIndex, int flags ); + + edict_t *EntityFromIndex( int entityIndex ); + + unsigned short TokenHash( const char *pszToken ); + +protected: + SAVERESTOREDATA *m_pdata; + void BufferRewind( int size ); + unsigned int HashString( const char *pszToken ); +}; + + +class CSave : public CSaveRestoreBuffer +{ +public: + CSave( SAVERESTOREDATA *pdata ) : CSaveRestoreBuffer( pdata ) {}; + + void WriteShort( const char *pname, const short *value, int count ); + void WriteInt( const char *pname, const int *value, int count ); // Save an int + void WriteFloat( const char *pname, const float *value, int count ); // Save a float + void WriteTime( const char *pname, const float *value, int count ); // Save a float (timevalue) + void WriteData( const char *pname, int size, const char *pdata ); // Save a binary data block + void WriteString( const char *pname, const char *pstring ); // Save a null-terminated string + void WriteString( const char *pname, const int *stringId, int count ); // Save a null-terminated string (engine string) + void WriteVector( const char *pname, const Vector &value ); // Save a vector + void WriteVector( const char *pname, const float *value, int count ); // Save a vector + void WritePositionVector( const char *pname, const Vector &value ); // Offset for landmark if necessary + void WritePositionVector( const char *pname, const float *value, int count ); // array of pos vectors + void WriteFunction( const char *pname, void **value, int count ); // Save a function pointer + int WriteEntVars( const char *pname, entvars_t *pev ); // Save entvars_t (entvars_t) + int WriteFields( const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount ); + +private: + int DataEmpty( const char *pdata, int size ); + void BufferField( const char *pname, int size, const char *pdata ); + void BufferString( char *pdata, int len ); + void BufferData( const char *pdata, int size ); + void BufferHeader( const char *pname, int size ); +}; + +typedef struct +{ + unsigned short size; + unsigned short token; + char *pData; +} HEADER; + +class CRestore : public CSaveRestoreBuffer +{ +public: + CRestore( SAVERESTOREDATA *pdata ) : CSaveRestoreBuffer( pdata ) { m_global = 0; m_precache = TRUE; } + int ReadEntVars( const char *pname, entvars_t *pev ); // entvars_t + int ReadFields( const char *pname, void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount ); + int ReadField( void *pBaseData, TYPEDESCRIPTION *pFields, int fieldCount, int startField, int size, char *pName, void *pData ); + int ReadInt( void ); + short ReadShort( void ); + int ReadNamedInt( const char *pName ); + char *ReadNamedString( const char *pName ); + int Empty( void ) { return (m_pdata == NULL) || ((m_pdata->pCurrentData-m_pdata->pBaseData)>=m_pdata->bufferSize); } + inline void SetGlobalMode( int global ) { m_global = global; } + void PrecacheMode( BOOL mode ) { m_precache = mode; } + +private: + char *BufferPointer( void ); + void BufferReadBytes( char *pOutput, int size ); + void BufferSkipBytes( int bytes ); + int BufferSkipZString( void ); + int BufferCheckZString( const char *string ); + + void BufferReadHeader( HEADER *pheader ); + + int m_global; // Restoring a global entity? + BOOL m_precache; +}; + +#define MAX_ENTITYARRAY 64 + +//#define ARRAYSIZE(p) (sizeof(p)/sizeof(p[0])) + +#define IMPLEMENT_SAVERESTORE(derivedClass,baseClass) \ + int derivedClass::Save( CSave &save )\ + {\ + if ( !baseClass::Save(save) )\ + return 0;\ + return save.WriteFields( #derivedClass, this, m_SaveData, ARRAYSIZE(m_SaveData) );\ + }\ + int derivedClass::Restore( CRestore &restore )\ + {\ + if ( !baseClass::Restore(restore) )\ + return 0;\ + return restore.ReadFields( #derivedClass, this, m_SaveData, ARRAYSIZE(m_SaveData) );\ + } + + +typedef enum { GLOBAL_OFF = 0, GLOBAL_ON = 1, GLOBAL_DEAD = 2 } GLOBALESTATE; + +typedef struct globalentity_s globalentity_t; + +struct globalentity_s +{ + char name[64]; + char levelName[32]; + GLOBALESTATE state; + globalentity_t *pNext; +}; + +class CGlobalState +{ +public: + CGlobalState(); + void Reset( void ); + void ClearStates( void ); + void EntityAdd( string_t globalname, string_t mapName, GLOBALESTATE state ); + void EntitySetState( string_t globalname, GLOBALESTATE state ); + void EntityUpdate( string_t globalname, string_t mapname ); + const globalentity_t *EntityFromTable( string_t globalname ); + GLOBALESTATE EntityGetState( string_t globalname ); + int EntityInTable( string_t globalname ) { return (Find( globalname ) != NULL) ? 1 : 0; } + int Save( CSave &save ); + int Restore( CRestore &restore ); + static TYPEDESCRIPTION m_SaveData[]; + +//#ifdef _DEBUG + void DumpGlobals( void ); +//#endif + +private: + globalentity_t *Find( string_t globalname ); + globalentity_t *m_pList; + int m_listCount; +}; + +extern CGlobalState gGlobalState; + +#endif //SAVERESTORE_H diff --git a/dep/rehlsdk/dlls/schedule.h b/dep/rehlsdk/dlls/schedule.h new file mode 100644 index 0000000..0c09441 --- /dev/null +++ b/dep/rehlsdk/dlls/schedule.h @@ -0,0 +1,290 @@ +/*** +* +* Copyright (c) 1996-2001, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* This source code contains proprietary and confidential information of +* Valve LLC and its suppliers. Access to this code is restricted to +* persons who have executed a written SDK license with Valve. Any access, +* use or distribution of this code by or to any unlicensed person is illegal. +* +****/ +//========================================================= +// Scheduling +//========================================================= + +#ifndef SCHEDULE_H +#define SCHEDULE_H + +#define TASKSTATUS_NEW 0 // Just started +#define TASKSTATUS_RUNNING 1 // Running task & movement +#define TASKSTATUS_RUNNING_MOVEMENT 2 // Just running movement +#define TASKSTATUS_RUNNING_TASK 3 // Just running task +#define TASKSTATUS_COMPLETE 4 // Completed, get next task + + +//========================================================= +// These are the schedule types +//========================================================= +typedef enum +{ + SCHED_NONE = 0, + SCHED_IDLE_STAND, + SCHED_IDLE_WALK, + SCHED_WAKE_ANGRY, + SCHED_WAKE_CALLED, + SCHED_ALERT_FACE, + SCHED_ALERT_SMALL_FLINCH, + SCHED_ALERT_BIG_FLINCH, + SCHED_ALERT_STAND, + SCHED_INVESTIGATE_SOUND, + SCHED_COMBAT_FACE, + SCHED_COMBAT_STAND, + SCHED_CHASE_ENEMY, + SCHED_CHASE_ENEMY_FAILED, + SCHED_VICTORY_DANCE, + SCHED_TARGET_FACE, + SCHED_TARGET_CHASE, + SCHED_SMALL_FLINCH, + SCHED_TAKE_COVER_FROM_ENEMY, + SCHED_TAKE_COVER_FROM_BEST_SOUND, + SCHED_TAKE_COVER_FROM_ORIGIN, + SCHED_COWER, // usually a last resort! + SCHED_MELEE_ATTACK1, + SCHED_MELEE_ATTACK2, + SCHED_RANGE_ATTACK1, + SCHED_RANGE_ATTACK2, + SCHED_SPECIAL_ATTACK1, + SCHED_SPECIAL_ATTACK2, + SCHED_STANDOFF, + SCHED_ARM_WEAPON, + SCHED_RELOAD, + SCHED_GUARD, + SCHED_AMBUSH, + SCHED_DIE, + SCHED_WAIT_TRIGGER, + SCHED_FOLLOW, + SCHED_SLEEP, + SCHED_WAKE, + SCHED_BARNACLE_VICTIM_GRAB, + SCHED_BARNACLE_VICTIM_CHOMP, + SCHED_AISCRIPT, + SCHED_FAIL, + + LAST_COMMON_SCHEDULE // Leave this at the bottom +} SCHEDULE_TYPE; + +//========================================================= +// These are the shared tasks +//========================================================= +typedef enum +{ + TASK_INVALID = 0, + TASK_WAIT, + TASK_WAIT_FACE_ENEMY, + TASK_WAIT_PVS, + TASK_SUGGEST_STATE, + TASK_WALK_TO_TARGET, + TASK_RUN_TO_TARGET, + TASK_MOVE_TO_TARGET_RANGE, + TASK_GET_PATH_TO_ENEMY, + TASK_GET_PATH_TO_ENEMY_LKP, + TASK_GET_PATH_TO_ENEMY_CORPSE, + TASK_GET_PATH_TO_LEADER, + TASK_GET_PATH_TO_SPOT, + TASK_GET_PATH_TO_TARGET, + TASK_GET_PATH_TO_HINTNODE, + TASK_GET_PATH_TO_LASTPOSITION, + TASK_GET_PATH_TO_BESTSOUND, + TASK_GET_PATH_TO_BESTSCENT, + TASK_RUN_PATH, + TASK_WALK_PATH, + TASK_STRAFE_PATH, + TASK_CLEAR_MOVE_WAIT, + TASK_STORE_LASTPOSITION, + TASK_CLEAR_LASTPOSITION, + TASK_PLAY_ACTIVE_IDLE, + TASK_FIND_HINTNODE, + TASK_CLEAR_HINTNODE, + TASK_SMALL_FLINCH, + TASK_FACE_IDEAL, + TASK_FACE_ROUTE, + TASK_FACE_ENEMY, + TASK_FACE_HINTNODE, + TASK_FACE_TARGET, + TASK_FACE_LASTPOSITION, + TASK_RANGE_ATTACK1, + TASK_RANGE_ATTACK2, + TASK_MELEE_ATTACK1, + TASK_MELEE_ATTACK2, + TASK_RELOAD, + TASK_RANGE_ATTACK1_NOTURN, + TASK_RANGE_ATTACK2_NOTURN, + TASK_MELEE_ATTACK1_NOTURN, + TASK_MELEE_ATTACK2_NOTURN, + TASK_RELOAD_NOTURN, + TASK_SPECIAL_ATTACK1, + TASK_SPECIAL_ATTACK2, + TASK_CROUCH, + TASK_STAND, + TASK_GUARD, + TASK_STEP_LEFT, + TASK_STEP_RIGHT, + TASK_STEP_FORWARD, + TASK_STEP_BACK, + TASK_DODGE_LEFT, + TASK_DODGE_RIGHT, + TASK_SOUND_ANGRY, + TASK_SOUND_DEATH, + TASK_SET_ACTIVITY, + TASK_SET_SCHEDULE, + TASK_SET_FAIL_SCHEDULE, + TASK_CLEAR_FAIL_SCHEDULE, + TASK_PLAY_SEQUENCE, + TASK_PLAY_SEQUENCE_FACE_ENEMY, + TASK_PLAY_SEQUENCE_FACE_TARGET, + TASK_SOUND_IDLE, + TASK_SOUND_WAKE, + TASK_SOUND_PAIN, + TASK_SOUND_DIE, + TASK_FIND_COVER_FROM_BEST_SOUND,// tries lateral cover first, then node cover + TASK_FIND_COVER_FROM_ENEMY,// tries lateral cover first, then node cover + TASK_FIND_LATERAL_COVER_FROM_ENEMY, + TASK_FIND_NODE_COVER_FROM_ENEMY, + TASK_FIND_NEAR_NODE_COVER_FROM_ENEMY,// data for this one is the MAXIMUM acceptable distance to the cover. + TASK_FIND_FAR_NODE_COVER_FROM_ENEMY,// data for this one is there MINIMUM aceptable distance to the cover. + TASK_FIND_COVER_FROM_ORIGIN, + TASK_EAT, + TASK_DIE, + TASK_WAIT_FOR_SCRIPT, + TASK_PLAY_SCRIPT, + TASK_ENABLE_SCRIPT, + TASK_PLANT_ON_SCRIPT, + TASK_FACE_SCRIPT, + TASK_WAIT_RANDOM, + TASK_WAIT_INDEFINITE, + TASK_STOP_MOVING, + TASK_TURN_LEFT, + TASK_TURN_RIGHT, + TASK_REMEMBER, + TASK_FORGET, + TASK_WAIT_FOR_MOVEMENT, // wait until MovementIsComplete() + LAST_COMMON_TASK, // LEAVE THIS AT THE BOTTOM!! (sjb) +} SHARED_TASKS; + + +// These go in the flData member of the TASK_WALK_TO_TARGET, TASK_RUN_TO_TARGET +enum +{ + TARGET_MOVE_NORMAL = 0, + TARGET_MOVE_SCRIPTED = 1, +}; + + +// A goal should be used for a task that requires several schedules to complete. +// The goal index should indicate which schedule (ordinally) the monster is running. +// That way, when tasks fail, the AI can make decisions based on the context of the +// current goal and sequence rather than just the current schedule. +enum +{ + GOAL_ATTACK_ENEMY, + GOAL_MOVE, + GOAL_TAKE_COVER, + GOAL_MOVE_TARGET, + GOAL_EAT, +}; + +// an array of tasks is a task list +// an array of schedules is a schedule list +struct Task_t +{ + + int iTask; + float flData; +}; + +struct Schedule_t +{ + + Task_t *pTasklist; + int cTasks; + int iInterruptMask;// a bit mask of conditions that can interrupt this schedule + + // a more specific mask that indicates which TYPES of sounds will interrupt the schedule in the + // event that the schedule is broken by COND_HEAR_SOUND + int iSoundMask; + const char *pName; +}; + +// an array of waypoints makes up the monster's route. +// !!!LATER- this declaration doesn't belong in this file. +struct WayPoint_t +{ + Vector vecLocation; + int iType; +}; + +// these MoveFlag values are assigned to a WayPoint's TYPE in order to demonstrate the +// type of movement the monster should use to get there. +#define bits_MF_TO_TARGETENT ( 1 << 0 ) // local move to targetent. +#define bits_MF_TO_ENEMY ( 1 << 1 ) // local move to enemy +#define bits_MF_TO_COVER ( 1 << 2 ) // local move to a hiding place +#define bits_MF_TO_DETOUR ( 1 << 3 ) // local move to detour point. +#define bits_MF_TO_PATHCORNER ( 1 << 4 ) // local move to a path corner +#define bits_MF_TO_NODE ( 1 << 5 ) // local move to a node +#define bits_MF_TO_LOCATION ( 1 << 6 ) // local move to an arbitrary point +#define bits_MF_IS_GOAL ( 1 << 7 ) // this waypoint is the goal of the whole move. +#define bits_MF_DONT_SIMPLIFY ( 1 << 8 ) // Don't let the route code simplify this waypoint + +// If you define any flags that aren't _TO_ flags, add them here so we can mask +// them off when doing compares. +#define bits_MF_NOT_TO_MASK (bits_MF_IS_GOAL | bits_MF_DONT_SIMPLIFY) + +#define MOVEGOAL_NONE (0) +#define MOVEGOAL_TARGETENT (bits_MF_TO_TARGETENT) +#define MOVEGOAL_ENEMY (bits_MF_TO_ENEMY) +#define MOVEGOAL_PATHCORNER (bits_MF_TO_PATHCORNER) +#define MOVEGOAL_LOCATION (bits_MF_TO_LOCATION) +#define MOVEGOAL_NODE (bits_MF_TO_NODE) + +// these bits represent conditions that may befall the monster, of which some are allowed +// to interrupt certain schedules. +#define bits_COND_NO_AMMO_LOADED ( 1 << 0 ) // weapon needs to be reloaded! +#define bits_COND_SEE_HATE ( 1 << 1 ) // see something that you hate +#define bits_COND_SEE_FEAR ( 1 << 2 ) // see something that you are afraid of +#define bits_COND_SEE_DISLIKE ( 1 << 3 ) // see something that you dislike +#define bits_COND_SEE_ENEMY ( 1 << 4 ) // target entity is in full view. +#define bits_COND_ENEMY_OCCLUDED ( 1 << 5 ) // target entity occluded by the world +#define bits_COND_SMELL_FOOD ( 1 << 6 ) +#define bits_COND_ENEMY_TOOFAR ( 1 << 7 ) +#define bits_COND_LIGHT_DAMAGE ( 1 << 8 ) // hurt a little +#define bits_COND_HEAVY_DAMAGE ( 1 << 9 ) // hurt a lot +#define bits_COND_CAN_RANGE_ATTACK1 ( 1 << 10) +#define bits_COND_CAN_MELEE_ATTACK1 ( 1 << 11) +#define bits_COND_CAN_RANGE_ATTACK2 ( 1 << 12) +#define bits_COND_CAN_MELEE_ATTACK2 ( 1 << 13) +// #define bits_COND_CAN_RANGE_ATTACK3 ( 1 << 14) +#define bits_COND_PROVOKED ( 1 << 15) +#define bits_COND_NEW_ENEMY ( 1 << 16) +#define bits_COND_HEAR_SOUND ( 1 << 17) // there is an interesting sound +#define bits_COND_SMELL ( 1 << 18) // there is an interesting scent +#define bits_COND_ENEMY_FACING_ME ( 1 << 19) // enemy is facing me +#define bits_COND_ENEMY_DEAD ( 1 << 20) // enemy was killed. If you get this in combat, try to find another enemy. If you get it in alert, victory dance. +#define bits_COND_SEE_CLIENT ( 1 << 21) // see a client +#define bits_COND_SEE_NEMESIS ( 1 << 22) // see my nemesis + +#define bits_COND_SPECIAL1 ( 1 << 28) // Defined by individual monster +#define bits_COND_SPECIAL2 ( 1 << 29) // Defined by individual monster + +#define bits_COND_TASK_FAILED ( 1 << 30) +#define bits_COND_SCHEDULE_DONE ( 1 << 31) + + +#define bits_COND_ALL_SPECIAL (bits_COND_SPECIAL1 | bits_COND_SPECIAL2) + +#define bits_COND_CAN_ATTACK (bits_COND_CAN_RANGE_ATTACK1 | bits_COND_CAN_MELEE_ATTACK1 | bits_COND_CAN_RANGE_ATTACK2 | bits_COND_CAN_MELEE_ATTACK2) + +#endif // SCHEDULE_H diff --git a/dep/rehlsdk/dlls/scriptevent.h b/dep/rehlsdk/dlls/scriptevent.h new file mode 100644 index 0000000..42377cf --- /dev/null +++ b/dep/rehlsdk/dlls/scriptevent.h @@ -0,0 +1,29 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef SCRIPTEVENT_H +#define SCRIPTEVENT_H + +#define SCRIPT_EVENT_DEAD 1000 // character is now dead +#define SCRIPT_EVENT_NOINTERRUPT 1001 // does not allow interrupt +#define SCRIPT_EVENT_CANINTERRUPT 1002 // will allow interrupt +#define SCRIPT_EVENT_FIREEVENT 1003 // event now fires +#define SCRIPT_EVENT_SOUND 1004 // Play named wave file (on CHAN_BODY) +#define SCRIPT_EVENT_SENTENCE 1005 // Play named sentence +#define SCRIPT_EVENT_INAIR 1006 // Leave the character in air at the end of the sequence (don't find the floor) +#define SCRIPT_EVENT_ENDANIMATION 1007 // Set the animation by name after the sequence completes +#define SCRIPT_EVENT_SOUND_VOICE 1008 // Play named wave file (on CHAN_VOICE) +#define SCRIPT_EVENT_SENTENCE_RND1 1009 // Play sentence group 25% of the time +#define SCRIPT_EVENT_NOT_DEAD 1010 // Bring back to life (for life/death sequences) +#endif //SCRIPTEVENT_H diff --git a/dep/rehlsdk/dlls/skill.h b/dep/rehlsdk/dlls/skill.h new file mode 100644 index 0000000..5ec320c --- /dev/null +++ b/dep/rehlsdk/dlls/skill.h @@ -0,0 +1,147 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +//========================================================= +// skill.h - skill level concerns +//========================================================= + +struct skilldata_t +{ + + int iSkillLevel; // game skill level + +// Monster Health & Damage + float agruntHealth; + float agruntDmgPunch; + + float apacheHealth; + + float barneyHealth; + + float bigmommaHealthFactor; // Multiply each node's health by this + float bigmommaDmgSlash; // melee attack damage + float bigmommaDmgBlast; // mortar attack damage + float bigmommaRadiusBlast; // mortar attack radius + + float bullsquidHealth; + float bullsquidDmgBite; + float bullsquidDmgWhip; + float bullsquidDmgSpit; + + float gargantuaHealth; + float gargantuaDmgSlash; + float gargantuaDmgFire; + float gargantuaDmgStomp; + + float hassassinHealth; + + float headcrabHealth; + float headcrabDmgBite; + + float hgruntHealth; + float hgruntDmgKick; + float hgruntShotgunPellets; + float hgruntGrenadeSpeed; + + float houndeyeHealth; + float houndeyeDmgBlast; + + float slaveHealth; + float slaveDmgClaw; + float slaveDmgClawrake; + float slaveDmgZap; + + float ichthyosaurHealth; + float ichthyosaurDmgShake; + + float leechHealth; + float leechDmgBite; + + float controllerHealth; + float controllerDmgZap; + float controllerSpeedBall; + float controllerDmgBall; + + float nihilanthHealth; + float nihilanthZap; + + float scientistHealth; + + float snarkHealth; + float snarkDmgBite; + float snarkDmgPop; + + float zombieHealth; + float zombieDmgOneSlash; + float zombieDmgBothSlash; + + float turretHealth; + float miniturretHealth; + float sentryHealth; + + +// Player Weapons + float plrDmgCrowbar; + float plrDmg9MM; + float plrDmg357; + float plrDmgMP5; + float plrDmgM203Grenade; + float plrDmgBuckshot; + float plrDmgCrossbowClient; + float plrDmgCrossbowMonster; + float plrDmgRPG; + float plrDmgGauss; + float plrDmgEgonNarrow; + float plrDmgEgonWide; + float plrDmgHornet; + float plrDmgHandGrenade; + float plrDmgSatchel; + float plrDmgTripmine; + +// weapons shared by monsters + float monDmg9MM; + float monDmgMP5; + float monDmg12MM; + float monDmgHornet; + +// health/suit charge + float suitchargerCapacity; + float batteryCapacity; + float healthchargerCapacity; + float healthkitCapacity; + float scientistHeal; + +// monster damage adj + float monHead; + float monChest; + float monStomach; + float monLeg; + float monArm; + +// player damage adj + float plrHead; + float plrChest; + float plrStomach; + float plrLeg; + float plrArm; +}; + +extern DLL_GLOBAL skilldata_t gSkillData; +float GetSkillCvar( char *pName ); + +extern DLL_GLOBAL int g_iSkillLevel; + +#define SKILL_EASY 1 +#define SKILL_MEDIUM 2 +#define SKILL_HARD 3 diff --git a/dep/rehlsdk/dlls/soundent.h b/dep/rehlsdk/dlls/soundent.h new file mode 100644 index 0000000..150daac --- /dev/null +++ b/dep/rehlsdk/dlls/soundent.h @@ -0,0 +1,95 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +//========================================================= +// Soundent.h - the entity that spawns when the world +// spawns, and handles the world's active and free sound +// lists. +//========================================================= + +#define MAX_WORLD_SOUNDS 64 // maximum number of sounds handled by the world at one time. + +#define bits_SOUND_NONE 0 +#define bits_SOUND_COMBAT ( 1 << 0 )// gunshots, explosions +#define bits_SOUND_WORLD ( 1 << 1 )// door opening/closing, glass breaking +#define bits_SOUND_PLAYER ( 1 << 2 )// all noises generated by player. walking, shooting, falling, splashing +#define bits_SOUND_CARCASS ( 1 << 3 )// dead body +#define bits_SOUND_MEAT ( 1 << 4 )// gib or pork chop +#define bits_SOUND_DANGER ( 1 << 5 )// pending danger. Grenade that is about to explode, explosive barrel that is damaged, falling crate +#define bits_SOUND_GARBAGE ( 1 << 6 )// trash cans, banana peels, old fast food bags. + +#define bits_ALL_SOUNDS 0xFFFFFFFF + +#define SOUNDLIST_EMPTY -1 + +#define SOUNDLISTTYPE_FREE 1// identifiers passed to functions that can operate on either list, to indicate which list to operate on. +#define SOUNDLISTTYPE_ACTIVE 2 + +#define SOUND_NEVER_EXPIRE -1 // with this set as a sound's ExpireTime, the sound will never expire. + +//========================================================= +// CSound - an instance of a sound in the world. +//========================================================= +class CSound +{ +public: + + void Clear ( void ); + void Reset ( void ); + + Vector m_vecOrigin; // sound's location in space + int m_iType; // what type of sound this is + int m_iVolume; // how loud the sound is + float m_flExpireTime; // when the sound should be purged from the list + int m_iNext; // index of next sound in this list ( Active or Free ) + int m_iNextAudible; // temporary link that monsters use to build a list of audible sounds + + BOOL FIsSound( void ); + BOOL FIsScent( void ); +}; + +//========================================================= +// CSoundEnt - a single instance of this entity spawns when +// the world spawns. The SoundEnt's job is to update the +// world's Free and Active sound lists. +//========================================================= +class CSoundEnt : public CBaseEntity +{ +public: + + void Precache ( void ); + void Spawn( void ); + void Think( void ); + void Initialize ( void ); + + static void InsertSound ( int iType, const Vector &vecOrigin, int iVolume, float flDuration ); + static void FreeSound ( int iSound, int iPrevious ); + static int ActiveList( void );// return the head of the active list + static int FreeList( void );// return the head of the free list + static CSound* SoundPointerForIndex( int iIndex );// return a pointer for this index in the sound list + static int ClientSoundIndex ( edict_t *pClient ); + + BOOL IsEmpty( void ) { return m_iActiveSound == SOUNDLIST_EMPTY; } + int ISoundsInList ( int iListType ); + int IAllocSound ( void ); + virtual int ObjectCaps( void ) { return FCAP_DONT_SAVE; } + + int m_iFreeSound; // index of the first sound in the free sound list + int m_iActiveSound; // indes of the first sound in the active sound list + int m_cLastActiveSounds; // keeps track of the number of active sounds at the last update. (for diagnostic work) + BOOL m_fShowReport; // if true, dump information about free/active sounds. + +private: + CSound m_SoundPool[ MAX_WORLD_SOUNDS ]; +}; diff --git a/dep/rehlsdk/dlls/spectator.h b/dep/rehlsdk/dlls/spectator.h new file mode 100644 index 0000000..2f755d6 --- /dev/null +++ b/dep/rehlsdk/dlls/spectator.h @@ -0,0 +1,27 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// Spectator.h + +class CBaseSpectator : public CBaseEntity +{ +public: + void Spawn(); + void SpectatorConnect(void); + void SpectatorDisconnect(void); + void SpectatorThink(void); + +private: + void SpectatorImpulseCommand(void); +}; diff --git a/dep/rehlsdk/dlls/talkmonster.h b/dep/rehlsdk/dlls/talkmonster.h new file mode 100644 index 0000000..25c1fc6 --- /dev/null +++ b/dep/rehlsdk/dlls/talkmonster.h @@ -0,0 +1,26 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef TALKMONSTER_H +#define TALKMONSTER_H + +class CTalkMonster : public CBaseMonster +{ +public: + static float g_talkWaitTime; + +}; + +#endif //TALKMONSTER_H diff --git a/dep/rehlsdk/dlls/teamplay_gamerules.h b/dep/rehlsdk/dlls/teamplay_gamerules.h new file mode 100644 index 0000000..5d4246b --- /dev/null +++ b/dep/rehlsdk/dlls/teamplay_gamerules.h @@ -0,0 +1,57 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// +// teamplay_gamerules.h +// + +#define MAX_TEAMNAME_LENGTH 16 +#define MAX_TEAMS 32 + +#define TEAMPLAY_TEAMLISTLENGTH MAX_TEAMS*MAX_TEAMNAME_LENGTH + +class CHalfLifeTeamplay : public CHalfLifeMultiplay +{ +public: + CHalfLifeTeamplay(); + + virtual BOOL ClientCommand( CBasePlayer *pPlayer, const char *pcmd ); + virtual void ClientUserInfoChanged( CBasePlayer *pPlayer, char *infobuffer ); + virtual BOOL IsTeamplay( void ); + virtual BOOL FPlayerCanTakeDamage( CBasePlayer *pPlayer, CBaseEntity *pAttacker ); + virtual int PlayerRelationship( CBaseEntity *pPlayer, CBaseEntity *pTarget ); + virtual const char *GetTeamID( CBaseEntity *pEntity ); + virtual BOOL ShouldAutoAim( CBasePlayer *pPlayer, edict_t *target ); + virtual int IPointsForKill( CBasePlayer *pAttacker, CBasePlayer *pKilled ); + virtual void InitHUD( CBasePlayer *pl ); + virtual void DeathNotice( CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pevInflictor ); + virtual const char *GetGameDescription( void ) { return "HL Teamplay"; } // this is the game name that gets seen in the server browser + virtual void UpdateGameMode( CBasePlayer *pPlayer ); // the client needs to be informed of the current game mode + virtual void PlayerKilled( CBasePlayer *pVictim, entvars_t *pKiller, entvars_t *pInflictor ); + virtual void Think ( void ); + virtual int GetTeamIndex( const char *pTeamName ); + virtual const char *GetIndexedTeamName( int teamIndex ); + virtual BOOL IsValidTeam( const char *pTeamName ); + const char *SetDefaultPlayerTeam( CBasePlayer *pPlayer ); + virtual void ChangePlayerTeam( CBasePlayer *pPlayer, const char *pTeamName, BOOL bKill, BOOL bGib ); + +private: + void RecountTeams( bool bResendInfo = FALSE ); + const char *TeamWithFewestPlayers( void ); + + BOOL m_DisableDeathMessages; + BOOL m_DisableDeathPenalty; + BOOL m_teamLimit; // This means the server set only some teams as valid + char m_szTeamList[TEAMPLAY_TEAMLISTLENGTH]; +}; diff --git a/dep/rehlsdk/dlls/trains.h b/dep/rehlsdk/dlls/trains.h new file mode 100644 index 0000000..87aec76 --- /dev/null +++ b/dep/rehlsdk/dlls/trains.h @@ -0,0 +1,127 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef TRAINS_H +#define TRAINS_H + +// Tracktrain spawn flags +#define SF_TRACKTRAIN_NOPITCH 0x0001 +#define SF_TRACKTRAIN_NOCONTROL 0x0002 +#define SF_TRACKTRAIN_FORWARDONLY 0x0004 +#define SF_TRACKTRAIN_PASSABLE 0x0008 + +// Spawnflag for CPathTrack +#define SF_PATH_DISABLED 0x00000001 +#define SF_PATH_FIREONCE 0x00000002 +#define SF_PATH_ALTREVERSE 0x00000004 +#define SF_PATH_DISABLE_TRAIN 0x00000008 +#define SF_PATH_ALTERNATE 0x00008000 + +// Spawnflags of CPathCorner +#define SF_CORNER_WAITFORTRIG 0x001 +#define SF_CORNER_TELEPORT 0x002 +#define SF_CORNER_FIREONCE 0x004 + +//#define PATH_SPARKLE_DEBUG 1 // This makes a particle effect around path_track entities for debugging +class CPathTrack : public CPointEntity +{ +public: + void Spawn( void ); + void Activate( void ); + void KeyValue( KeyValueData* pkvd); + + void SetPrevious( CPathTrack *pprevious ); + void Link( void ); + void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); + + CPathTrack *ValidPath( CPathTrack *ppath, int testFlag ); // Returns ppath if enabled, NULL otherwise + void Project( CPathTrack *pstart, CPathTrack *pend, Vector *origin, float dist ); + + static CPathTrack *Instance( edict_t *pent ); + + CPathTrack *LookAhead( Vector *origin, float dist, int move ); + CPathTrack *Nearest( Vector origin ); + + CPathTrack *GetNext( void ); + CPathTrack *GetPrevious( void ); + + virtual int Save( CSave &save ); + virtual int Restore( CRestore &restore ); + + static TYPEDESCRIPTION m_SaveData[]; +#if PATH_SPARKLE_DEBUG + void EXPORT Sparkle(void); +#endif + + float m_length; + string_t m_altName; + CPathTrack *m_pnext; + CPathTrack *m_pprevious; + CPathTrack *m_paltpath; +}; + + +class CFuncTrackTrain : public CBaseEntity +{ +public: + void Spawn( void ); + void Precache( void ); + + void Blocked( CBaseEntity *pOther ); + void Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); + void KeyValue( KeyValueData* pkvd ); + + void EXPORT Next( void ); + void EXPORT Find( void ); + void EXPORT NearestPath( void ); + void EXPORT DeadEnd( void ); + + void NextThink( float thinkTime, BOOL alwaysThink ); + + void SetTrack( CPathTrack *track ) { m_ppath = track->Nearest(pev->origin); } + void SetControls( entvars_t *pevControls ); + BOOL OnControls( entvars_t *pev ); + + void StopSound ( void ); + void UpdateSound ( void ); + + static CFuncTrackTrain *Instance( edict_t *pent ); + + virtual int Save( CSave &save ); + virtual int Restore( CRestore &restore ); + + static TYPEDESCRIPTION m_SaveData[]; + virtual int ObjectCaps( void ) { return (CBaseEntity :: ObjectCaps() & ~FCAP_ACROSS_TRANSITION) | FCAP_DIRECTIONAL_USE; } + + virtual void OverrideReset( void ); + + CPathTrack *m_ppath; + float m_length; + float m_height; + float m_speed; + float m_dir; + float m_startSpeed; + Vector m_controlMins; + Vector m_controlMaxs; + int m_soundPlaying; + int m_sounds; + float m_flVolume; + float m_flBank; + float m_oldSpeed; + +private: + unsigned short m_usAdjustPitch; +}; + +#endif diff --git a/dep/rehlsdk/dlls/util.h b/dep/rehlsdk/dlls/util.h new file mode 100644 index 0000000..6ab9b4f --- /dev/null +++ b/dep/rehlsdk/dlls/util.h @@ -0,0 +1,547 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#include "archtypes.h" // DAL + +// +// Misc utility code +// +#ifndef ACTIVITY_H +#include "activity.h" +#endif + +#ifndef ENGINECALLBACK_H +#include "enginecallback.h" +#endif +inline void MESSAGE_BEGIN( int msg_dest, int msg_type, const float *pOrigin, entvars_t *ent ); // implementation later in this file + +extern globalvars_t *gpGlobals; + +// Use this instead of ALLOC_STRING on constant strings +#define STRING(offset) ((const char *)(gpGlobals->pStringBase + (unsigned int)(offset))) +#define MAKE_STRING(str) ((uint64)(str) - (uint64)(STRING(0))) + +inline edict_t *FIND_ENTITY_BY_CLASSNAME(edict_t *entStart, const char *pszName) +{ + return FIND_ENTITY_BY_STRING(entStart, "classname", pszName); +} + +inline edict_t *FIND_ENTITY_BY_TARGETNAME(edict_t *entStart, const char *pszName) +{ + return FIND_ENTITY_BY_STRING(entStart, "targetname", pszName); +} + +// for doing a reverse lookup. Say you have a door, and want to find its button. +inline edict_t *FIND_ENTITY_BY_TARGET(edict_t *entStart, const char *pszName) +{ + return FIND_ENTITY_BY_STRING(entStart, "target", pszName); +} + +// Keeps clutter down a bit, when writing key-value pairs +#define WRITEKEY_INT(pf, szKeyName, iKeyValue) ENGINE_FPRINTF(pf, "\"%s\" \"%d\"\n", szKeyName, iKeyValue) +#define WRITEKEY_FLOAT(pf, szKeyName, flKeyValue) \ + ENGINE_FPRINTF(pf, "\"%s\" \"%f\"\n", szKeyName, flKeyValue) +#define WRITEKEY_STRING(pf, szKeyName, szKeyValue) \ + ENGINE_FPRINTF(pf, "\"%s\" \"%s\"\n", szKeyName, szKeyValue) +#define WRITEKEY_VECTOR(pf, szKeyName, flX, flY, flZ) \ + ENGINE_FPRINTF(pf, "\"%s\" \"%f %f %f\"\n", szKeyName, flX, flY, flZ) + +// Keeps clutter down a bit, when using a float as a bit-vector +#define SetBits(flBitVector, bits) ((flBitVector) = (int)(flBitVector) | (bits)) +#define ClearBits(flBitVector, bits) ((flBitVector) = (int)(flBitVector) & ~(bits)) +#define FBitSet(flBitVector, bit) ((int)(flBitVector) & (bit)) + +// Makes these more explicit, and easier to find +#define FILE_GLOBAL static +#define DLL_GLOBAL + +// Until we figure out why "const" gives the compiler problems, we'll just have to use +// this bogus "empty" define to mark things as constant. +#define CONSTANT + +// More explicit than "int" +typedef int EOFFSET; + +// In case it's not alread defined +typedef int BOOL; + +// In case this ever changes +#define M_PI 3.14159265358979323846 + +// Keeps clutter down a bit, when declaring external entity/global method prototypes +#define DECLARE_GLOBAL_METHOD(MethodName) extern void UTIL_DLLEXPORT MethodName( void ) +#define GLOBAL_METHOD(funcname) void UTIL_DLLEXPORT funcname(void) + +#ifndef UTIL_DLLEXPORT +#ifdef _WIN32 +#define UTIL_DLLEXPORT _declspec( dllexport ) EXT_FUNC +#else +#define UTIL_DLLEXPORT __attribute__ ((visibility("default"))) EXT_FUNC +#endif +#endif + +// This is the glue that hooks .MAP entity class names to our CPP classes +// The _declspec forces them to be exported by name so we can do a lookup with GetProcAddress() +// The function is used to intialize / allocate the object for the entity +#define LINK_ENTITY_TO_CLASS(mapClassName,DLLClassName) \ + extern "C" UTIL_DLLEXPORT void mapClassName( entvars_t *pev ); \ + void mapClassName( entvars_t *pev ) { GetClassPtr( (DLLClassName *)pev ); } + + +// +// Conversion among the three types of "entity", including identity-conversions. +// +#ifdef DEBUG + extern edict_t *DBG_EntOfVars(const entvars_t *pev); + inline edict_t *ENT(const entvars_t *pev) { return DBG_EntOfVars(pev); } +#else + inline edict_t *ENT(const entvars_t *pev) { return pev->pContainingEntity; } +#endif +inline edict_t *ENT(edict_t *pent) { return pent; } +inline edict_t *ENT(EOFFSET eoffset) { return (*g_engfuncs.pfnPEntityOfEntOffset)(eoffset); } +inline EOFFSET OFFSET(EOFFSET eoffset) { return eoffset; } +inline EOFFSET OFFSET(const edict_t *pent) +{ +#if _DEBUG + if ( !pent ) + ALERT( at_error, "Bad ent in OFFSET()\n" ); +#endif + return (*g_engfuncs.pfnEntOffsetOfPEntity)(pent); +} +inline EOFFSET OFFSET(entvars_t *pev) +{ +#if _DEBUG + if ( !pev ) + ALERT( at_error, "Bad pev in OFFSET()\n" ); +#endif + return OFFSET(ENT(pev)); +} +inline entvars_t *VARS(entvars_t *pev) { return pev; } + +inline entvars_t *VARS(edict_t *pent) +{ + if ( !pent ) + return NULL; + + return &pent->v; +} + +inline entvars_t* VARS(EOFFSET eoffset) { return VARS(ENT(eoffset)); } +inline int ENTINDEX(edict_t *pEdict) { return (*g_engfuncs.pfnIndexOfEdict)(pEdict); } +inline edict_t* INDEXENT( int iEdictNum ) { return (*g_engfuncs.pfnPEntityOfEntIndex)(iEdictNum); } +inline void MESSAGE_BEGIN( int msg_dest, int msg_type, const float *pOrigin, entvars_t *ent ) { + (*g_engfuncs.pfnMessageBegin)(msg_dest, msg_type, pOrigin, ENT(ent)); +} + +// Testing the three types of "entity" for nullity +#define eoNullEntity 0 +inline BOOL FNullEnt(EOFFSET eoffset) { return eoffset == 0; } +inline BOOL FNullEnt(const edict_t* pent) { return pent == NULL || FNullEnt(OFFSET(pent)); } +inline BOOL FNullEnt(entvars_t* pev) { return pev == NULL || FNullEnt(OFFSET(pev)); } + +// Testing strings for nullity +#define iStringNull 0 +inline BOOL FStringNull(int iString) { return iString == iStringNull; } + +#define cchMapNameMost 32 + +// Dot products for view cone checking +#define VIEW_FIELD_FULL (float)-1.0 // +-180 degrees +#define VIEW_FIELD_WIDE (float)-0.7 // +-135 degrees 0.1 // +-85 degrees, used for full FOV checks +#define VIEW_FIELD_NARROW (float)0.7 // +-45 degrees, more narrow check used to set up ranged attacks +#define VIEW_FIELD_ULTRA_NARROW (float)0.9 // +-25 degrees, more narrow check used to set up ranged attacks + +// All monsters need this data +#define DONT_BLEED -1 +#define BLOOD_COLOR_RED (BYTE)247 +#define BLOOD_COLOR_YELLOW (BYTE)195 +#define BLOOD_COLOR_GREEN BLOOD_COLOR_YELLOW + +typedef enum +{ + + MONSTERSTATE_NONE = 0, + MONSTERSTATE_IDLE, + MONSTERSTATE_COMBAT, + MONSTERSTATE_ALERT, + MONSTERSTATE_HUNT, + MONSTERSTATE_PRONE, + MONSTERSTATE_SCRIPT, + MONSTERSTATE_PLAYDEAD, + MONSTERSTATE_DEAD + +} MONSTERSTATE; + + + +// Things that toggle (buttons/triggers/doors) need this +typedef enum + { + TS_AT_TOP, + TS_AT_BOTTOM, + TS_GOING_UP, + TS_GOING_DOWN + } TOGGLE_STATE; + +// Misc useful +inline BOOL FStrEq(const char*sz1, const char*sz2) + { return (strcmp(sz1, sz2) == 0); } +inline BOOL FClassnameIs(edict_t* pent, const char* szClassname) + { return FStrEq(STRING(VARS(pent)->classname), szClassname); } +inline BOOL FClassnameIs(entvars_t* pev, const char* szClassname) + { return FStrEq(STRING(pev->classname), szClassname); } + +class CBaseEntity; + +// Misc. Prototypes +extern void UTIL_SetSize (entvars_t* pev, const Vector &vecMin, const Vector &vecMax); +extern float UTIL_VecToYaw (const Vector &vec); +extern Vector UTIL_VecToAngles (const Vector &vec); +extern float UTIL_AngleMod (float a); +extern float UTIL_AngleDiff ( float destAngle, float srcAngle ); + +extern CBaseEntity *UTIL_FindEntityInSphere(CBaseEntity *pStartEntity, const Vector &vecCenter, float flRadius); +extern CBaseEntity *UTIL_FindEntityByString(CBaseEntity *pStartEntity, const char *szKeyword, const char *szValue ); +extern CBaseEntity *UTIL_FindEntityByClassname(CBaseEntity *pStartEntity, const char *szName ); +extern CBaseEntity *UTIL_FindEntityByTargetname(CBaseEntity *pStartEntity, const char *szName ); +extern CBaseEntity *UTIL_FindEntityGeneric(const char *szName, Vector &vecSrc, float flRadius ); + +// returns a CBaseEntity pointer to a player by index. Only returns if the player is spawned and connected +// otherwise returns NULL +// Index is 1 based +extern CBaseEntity *UTIL_PlayerByIndex( int playerIndex ); + +#define UTIL_EntitiesInPVS(pent) (*g_engfuncs.pfnEntitiesInPVS)(pent) +extern void UTIL_MakeVectors (const Vector &vecAngles); + +// Pass in an array of pointers and an array size, it fills the array and returns the number inserted +extern int UTIL_MonstersInSphere( CBaseEntity **pList, int listMax, const Vector ¢er, float radius ); +extern int UTIL_EntitiesInBox( CBaseEntity **pList, int listMax, const Vector &mins, const Vector &maxs, int flagMask ); + +inline void UTIL_MakeVectorsPrivate( const Vector &vecAngles, float *p_vForward, float *p_vRight, float *p_vUp ) +{ + g_engfuncs.pfnAngleVectors( vecAngles, p_vForward, p_vRight, p_vUp ); +} + +extern void UTIL_MakeAimVectors ( const Vector &vecAngles ); // like MakeVectors, but assumes pitch isn't inverted +extern void UTIL_MakeInvVectors ( const Vector &vec, globalvars_t *pgv ); + +extern void UTIL_SetOrigin ( entvars_t* pev, const Vector &vecOrigin ); +extern void UTIL_EmitAmbientSound ( edict_t *entity, const Vector &vecOrigin, const char *samp, float vol, float attenuation, int fFlags, int pitch ); +extern void UTIL_ParticleEffect ( const Vector &vecOrigin, const Vector &vecDirection, ULONG ulColor, ULONG ulCount ); +extern void UTIL_ScreenShake ( const Vector ¢er, float amplitude, float frequency, float duration, float radius ); +extern void UTIL_ScreenShakeAll ( const Vector ¢er, float amplitude, float frequency, float duration ); +extern void UTIL_ShowMessage ( const char *pString, CBaseEntity *pPlayer ); +extern void UTIL_ShowMessageAll ( const char *pString ); +extern void UTIL_ScreenFadeAll ( const Vector &color, float fadeTime, float holdTime, int alpha, int flags ); +extern void UTIL_ScreenFade ( CBaseEntity *pEntity, const Vector &color, float fadeTime, float fadeHold, int alpha, int flags ); + +typedef enum { ignore_monsters=1, dont_ignore_monsters=0, missile=2 } IGNORE_MONSTERS; +typedef enum { ignore_glass=1, dont_ignore_glass=0 } IGNORE_GLASS; +extern void UTIL_TraceLine (const Vector &vecStart, const Vector &vecEnd, IGNORE_MONSTERS igmon, edict_t *pentIgnore, TraceResult *ptr); +extern void UTIL_TraceLine (const Vector &vecStart, const Vector &vecEnd, IGNORE_MONSTERS igmon, IGNORE_GLASS ignoreGlass, edict_t *pentIgnore, TraceResult *ptr); +typedef enum { point_hull=0, human_hull=1, large_hull=2, head_hull=3 } __HLSDK_HULL_TYPE; +extern void UTIL_TraceHull (const Vector &vecStart, const Vector &vecEnd, IGNORE_MONSTERS igmon, int hullNumber, edict_t *pentIgnore, TraceResult *ptr); +extern TraceResult UTIL_GetGlobalTrace (void); +extern void UTIL_TraceModel (const Vector &vecStart, const Vector &vecEnd, int hullNumber, edict_t *pentModel, TraceResult *ptr); +extern Vector UTIL_GetAimVector (edict_t* pent, float flSpeed); +extern int UTIL_PointContents (const Vector &vec); + +extern int UTIL_IsMasterTriggered (string_t sMaster, CBaseEntity *pActivator); +extern void UTIL_BloodStream( const Vector &origin, const Vector &direction, int color, int amount ); +extern void UTIL_BloodDrips( const Vector &origin, const Vector &direction, int color, int amount ); +extern Vector UTIL_RandomBloodVector( void ); +extern BOOL UTIL_ShouldShowBlood( int bloodColor ); +extern void UTIL_BloodDecalTrace( TraceResult *pTrace, int bloodColor ); +extern void UTIL_DecalTrace( TraceResult *pTrace, int decalNumber ); +extern void UTIL_PlayerDecalTrace( TraceResult *pTrace, int playernum, int decalNumber, BOOL bIsCustom ); +extern void UTIL_GunshotDecalTrace( TraceResult *pTrace, int decalNumber ); +extern void UTIL_Sparks( const Vector &position ); +extern void UTIL_Ricochet( const Vector &position, float scale ); +extern void UTIL_StringToVector( float *pVector, const char *pString ); +extern void UTIL_StringToIntArray( int *pVector, int count, const char *pString ); +extern Vector UTIL_ClampVectorToBox( const Vector &input, const Vector &clampSize ); +extern float UTIL_Approach( float target, float value, float speed ); +extern float UTIL_ApproachAngle( float target, float value, float speed ); +extern float UTIL_AngleDistance( float next, float cur ); + +extern char *UTIL_VarArgs( char *format, ... ); +extern void UTIL_Remove( CBaseEntity *pEntity ); +extern BOOL UTIL_IsValidEntity( edict_t *pent ); +extern BOOL UTIL_TeamsMatch( const char *pTeamName1, const char *pTeamName2 ); + +// Use for ease-in, ease-out style interpolation (accel/decel) +extern float UTIL_SplineFraction( float value, float scale ); + +// Search for water transition along a vertical line +extern float UTIL_WaterLevel( const Vector &position, float minz, float maxz ); +extern void UTIL_Bubbles( Vector mins, Vector maxs, int count ); +extern void UTIL_BubbleTrail( Vector from, Vector to, int count ); + +// allows precacheing of other entities +extern void UTIL_PrecacheOther( const char *szClassname ); + +// prints a message to each client +extern void UTIL_ClientPrintAll( int msg_dest, const char *msg_name, const char *param1 = NULL, const char *param2 = NULL, const char *param3 = NULL, const char *param4 = NULL ); +inline void UTIL_CenterPrintAll( const char *msg_name, const char *param1 = NULL, const char *param2 = NULL, const char *param3 = NULL, const char *param4 = NULL ) +{ + UTIL_ClientPrintAll( HUD_PRINTCENTER, msg_name, param1, param2, param3, param4 ); +} + +class CBasePlayerItem; +class CBasePlayer; +extern BOOL UTIL_GetNextBestWeapon( CBasePlayer *pPlayer, CBasePlayerItem *pCurrentWeapon ); + +// prints messages through the HUD +extern void ClientPrint( entvars_t *client, int msg_dest, const char *msg_name, const char *param1 = NULL, const char *param2 = NULL, const char *param3 = NULL, const char *param4 = NULL ); + +// prints a message to the HUD say (chat) +extern void UTIL_SayText( const char *pText, CBaseEntity *pEntity ); +extern void UTIL_SayTextAll( const char *pText, CBaseEntity *pEntity ); + + +typedef struct hudtextparms_s +{ + float x; + float y; + int effect; + byte r1, g1, b1, a1; + byte r2, g2, b2, a2; + float fadeinTime; + float fadeoutTime; + float holdTime; + float fxTime; + int channel; +} hudtextparms_t; + +// prints as transparent 'title' to the HUD +extern void UTIL_HudMessageAll( const hudtextparms_t &textparms, const char *pMessage ); +extern void UTIL_HudMessage( CBaseEntity *pEntity, const hudtextparms_t &textparms, const char *pMessage ); + +// for handy use with ClientPrint params +extern char *UTIL_dtos1( int d ); +extern char *UTIL_dtos2( int d ); +extern char *UTIL_dtos3( int d ); +extern char *UTIL_dtos4( int d ); + +// Writes message to console with timestamp and FragLog header. +extern void UTIL_LogPrintf( char *fmt, ... ); +extern void UTIL_ServerPrintf( const char *fmt, ... ); + +// Sorta like FInViewCone, but for nonmonsters. +extern float UTIL_DotPoints ( const Vector &vecSrc, const Vector &vecCheck, const Vector &vecDir ); + +extern void UTIL_StripToken( const char *pKey, char *pDest );// for redundant keynames + +// Misc functions +extern void SetMovedir(entvars_t* pev); +extern Vector VecBModelOrigin( entvars_t* pevBModel ); +extern int BuildChangeList( LEVELLIST *pLevelList, int maxList ); + +// +// How did I ever live without ASSERT? +// +#ifdef DEBUG +void DBG_AssertFunction(BOOL fExpr, const char* szExpr, const char* szFile, int szLine, const char* szMessage); +#define ASSERT(f) DBG_AssertFunction(f, #f, __FILE__, __LINE__, NULL) +#define ASSERTSZ(f, sz) DBG_AssertFunction(f, #f, __FILE__, __LINE__, sz) +#else // !DEBUG +#define ASSERT(f) +#define ASSERTSZ(f, sz) +#endif // !DEBUG + + +extern DLL_GLOBAL const Vector g_vecZero; + +// +// Constants that were used only by QC (maybe not used at all now) +// +// Un-comment only as needed +// +#define LANGUAGE_ENGLISH 0 +#define LANGUAGE_GERMAN 1 +#define LANGUAGE_FRENCH 2 +#define LANGUAGE_BRITISH 3 + +extern DLL_GLOBAL int g_Language; + +#define AMBIENT_SOUND_STATIC 0 // medium radius attenuation +#define AMBIENT_SOUND_EVERYWHERE 1 +#define AMBIENT_SOUND_SMALLRADIUS 2 +#define AMBIENT_SOUND_MEDIUMRADIUS 4 +#define AMBIENT_SOUND_LARGERADIUS 8 +#define AMBIENT_SOUND_START_SILENT 16 +#define AMBIENT_SOUND_NOT_LOOPING 32 + +#define SPEAKER_START_SILENT 1 // wait for trigger 'on' to start announcements + +#define SND_SPAWNING (1<<8) // duplicated in protocol.h we're spawing, used in some cases for ambients +#define SND_STOP (1<<5) // duplicated in protocol.h stop sound +#define SND_CHANGE_VOL (1<<6) // duplicated in protocol.h change sound vol +#define SND_CHANGE_PITCH (1<<7) // duplicated in protocol.h change sound pitch + +#define LFO_SQUARE 1 +#define LFO_TRIANGLE 2 +#define LFO_RANDOM 3 + +// func_rotating +#define SF_BRUSH_ROTATE_Y_AXIS 0 +#define SF_BRUSH_ROTATE_INSTANT 1 +#define SF_BRUSH_ROTATE_BACKWARDS 2 +#define SF_BRUSH_ROTATE_Z_AXIS 4 +#define SF_BRUSH_ROTATE_X_AXIS 8 +#define SF_PENDULUM_AUTO_RETURN 16 +#define SF_PENDULUM_PASSABLE 32 + + +#define SF_BRUSH_ROTATE_SMALLRADIUS 128 +#define SF_BRUSH_ROTATE_MEDIUMRADIUS 256 +#define SF_BRUSH_ROTATE_LARGERADIUS 512 + +#define PUSH_BLOCK_ONLY_X 1 +#define PUSH_BLOCK_ONLY_Y 2 + +#define VEC_HULL_MIN Vector(-16, -16, -36) +#define VEC_HULL_MAX Vector( 16, 16, 36) +#define VEC_HUMAN_HULL_MIN Vector( -16, -16, 0 ) +#define VEC_HUMAN_HULL_MAX Vector( 16, 16, 72 ) +#define VEC_HUMAN_HULL_DUCK Vector( 16, 16, 36 ) + +#define VEC_VIEW Vector( 0, 0, 28 ) + +#define VEC_DUCK_HULL_MIN Vector(-16, -16, -18 ) +#define VEC_DUCK_HULL_MAX Vector( 16, 16, 18) +#define VEC_DUCK_VIEW Vector( 0, 0, 12 ) + +#define SVC_TEMPENTITY 23 +#define SVC_INTERMISSION 30 +#define SVC_CDTRACK 32 +#define SVC_WEAPONANIM 35 +#define SVC_ROOMTYPE 37 +#define SVC_DIRECTOR 51 + + + +// triggers +#define SF_TRIGGER_ALLOWMONSTERS 1// monsters allowed to fire this trigger +#define SF_TRIGGER_NOCLIENTS 2// players not allowed to fire this trigger +#define SF_TRIGGER_PUSHABLES 4// only pushables can fire this trigger + +// func breakable +#define SF_BREAK_TRIGGER_ONLY 1// may only be broken by trigger +#define SF_BREAK_TOUCH 2// can be 'crashed through' by running player (plate glass) +#define SF_BREAK_PRESSURE 4// can be broken by a player standing on it +#define SF_BREAK_CROWBAR 256// instant break if hit with crowbar + +// func_pushable (it's also func_breakable, so don't collide with those flags) +#define SF_PUSH_BREAKABLE 128 + +#define SF_LIGHT_START_OFF 1 + +#define SPAWNFLAG_NOMESSAGE 1 +#define SPAWNFLAG_NOTOUCH 1 +#define SPAWNFLAG_DROIDONLY 4 + +#define SPAWNFLAG_USEONLY 1 // can't be touched, must be used (buttons) + +#define TELE_PLAYER_ONLY 1 +#define TELE_SILENT 2 + +#define SF_TRIG_PUSH_ONCE 1 + + +// Sound Utilities + +// sentence groups +#define CBSENTENCENAME_MAX 16 +#define CVOXFILESENTENCEMAX 1536 // max number of sentences in game. NOTE: this must match + // CVOXFILESENTENCEMAX in engine\sound.h!!! + +extern char gszallsentencenames[CVOXFILESENTENCEMAX][CBSENTENCENAME_MAX]; +extern int gcallsentences; + +int USENTENCEG_Pick(int isentenceg, char *szfound); +int USENTENCEG_PickSequential(int isentenceg, char *szfound, int ipick, int freset); +void USENTENCEG_InitLRU(unsigned char *plru, int count); + +void SENTENCEG_Init(); +void SENTENCEG_Stop(edict_t *entity, int isentenceg, int ipick); +int SENTENCEG_PlayRndI(edict_t *entity, int isentenceg, float volume, float attenuation, int flags, int pitch); +int SENTENCEG_PlayRndSz(edict_t *entity, const char *szrootname, float volume, float attenuation, int flags, int pitch); +int SENTENCEG_PlaySequentialSz(edict_t *entity, const char *szrootname, float volume, float attenuation, int flags, int pitch, int ipick, int freset); +int SENTENCEG_GetIndex(const char *szrootname); +int SENTENCEG_Lookup(const char *sample, char *sentencenum); + +void TEXTURETYPE_Init(); +char TEXTURETYPE_Find(char *name); +float TEXTURETYPE_PlaySound(TraceResult *ptr, Vector vecSrc, Vector vecEnd, int iBulletType); + +// NOTE: use EMIT_SOUND_DYN to set the pitch of a sound. Pitch of 100 +// is no pitch shift. Pitch > 100 up to 255 is a higher pitch, pitch < 100 +// down to 1 is a lower pitch. 150 to 70 is the realistic range. +// EMIT_SOUND_DYN with pitch != 100 should be used sparingly, as it's not quite as +// fast as EMIT_SOUND (the pitchshift mixer is not native coded). + +void EMIT_SOUND_DYN(edict_t *entity, int channel, const char *sample, float volume, float attenuation, + int flags, int pitch); + + +inline void EMIT_SOUND(edict_t *entity, int channel, const char *sample, float volume, float attenuation) +{ + EMIT_SOUND_DYN(entity, channel, sample, volume, attenuation, 0, PITCH_NORM); +} + +inline void STOP_SOUND(edict_t *entity, int channel, const char *sample) +{ + EMIT_SOUND_DYN(entity, channel, sample, 0, 0, SND_STOP, PITCH_NORM); +} + +void EMIT_SOUND_SUIT(edict_t *entity, const char *sample); +void EMIT_GROUPID_SUIT(edict_t *entity, int isentenceg); +void EMIT_GROUPNAME_SUIT(edict_t *entity, const char *groupname); + +#define PRECACHE_SOUND_ARRAY( a ) \ + { for (int i = 0; i < ARRAYSIZE( a ); i++ ) PRECACHE_SOUND((char *) a [i]); } + +#define EMIT_SOUND_ARRAY_DYN( chan, array ) \ + EMIT_SOUND_DYN ( ENT(pev), chan , array [ RANDOM_LONG(0,ARRAYSIZE( array )-1) ], 1.0, ATTN_NORM, 0, RANDOM_LONG(95,105) ); + +#define RANDOM_SOUND_ARRAY( array ) (array) [ RANDOM_LONG(0,ARRAYSIZE( (array) )-1) ] + +#define PLAYBACK_EVENT( flags, who, index ) PLAYBACK_EVENT_FULL( flags, who, index, 0, (float *)&g_vecZero, (float *)&g_vecZero, 0.0, 0.0, 0, 0, 0, 0 ); +#define PLAYBACK_EVENT_DELAY( flags, who, index, delay ) PLAYBACK_EVENT_FULL( flags, who, index, delay, (float *)&g_vecZero, (float *)&g_vecZero, 0.0, 0.0, 0, 0, 0, 0 ); + +#define GROUP_OP_AND 0 +#define GROUP_OP_NAND 1 + +extern int g_groupmask; +extern int g_groupop; + +class UTIL_GroupTrace +{ +public: + UTIL_GroupTrace( int groupmask, int op ); + ~UTIL_GroupTrace( void ); + +private: + int m_oldgroupmask, m_oldgroupop; +}; + +void UTIL_SetGroupTrace( int groupmask, int op ); +void UTIL_UnsetGroupTrace( void ); + +int UTIL_SharedRandomLong( unsigned int seed, int low, int high ); +float UTIL_SharedRandomFloat( unsigned int seed, float low, float high ); + +float UTIL_WeaponTimeBase( void ); diff --git a/dep/rehlsdk/dlls/vector.h b/dep/rehlsdk/dlls/vector.h new file mode 100644 index 0000000..de8924f --- /dev/null +++ b/dep/rehlsdk/dlls/vector.h @@ -0,0 +1,113 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#ifndef VECTOR_H +#define VECTOR_H + + +//========================================================= +// 2DVector - used for many pathfinding and many other +// operations that are treated as planar rather than 3d. +//========================================================= +class Vector2D +{ +public: + inline Vector2D(void): x(0.0), y(0.0) { } + inline Vector2D(float X, float Y): x(0.0), y(0.0) { x = X; y = Y; } + inline Vector2D operator+(const Vector2D& v) const { return Vector2D(x+v.x, y+v.y); } + inline Vector2D operator-(const Vector2D& v) const { return Vector2D(x-v.x, y-v.y); } + inline Vector2D operator*(float fl) const { return Vector2D(x*fl, y*fl); } + inline Vector2D operator/(float fl) const { return Vector2D(x/fl, y/fl); } + + inline float Length(void) const { return sqrt(x*x + y*y ); } + + inline Vector2D Normalize ( void ) const + { + // Vector2D vec2; + + float flLen = Length(); + if ( flLen == 0 ) + { + return Vector2D( 0, 0 ); + } + else + { + flLen = 1 / flLen; + return Vector2D( x * flLen, y * flLen ); + } + } + + vec_t x, y; +}; + +inline float DotProduct(const Vector2D& a, const Vector2D& b) { return( a.x*b.x + a.y*b.y ); } +inline Vector2D operator*(float fl, const Vector2D& v) { return v * fl; } + +//========================================================= +// 3D Vector +//========================================================= +class Vector // same data-layout as engine's vec3_t, +{ // which is a vec_t[3] +public: + // Construction/destruction + inline Vector(void): x(0.0), y(0.0), z(0.0) { } + inline Vector(float X, float Y, float Z): x(0.0), y(0.0), z(0.0) { x = X; y = Y; z = Z; } + //inline Vector(double X, double Y, double Z) { x = (float)X; y = (float)Y; z = (float)Z; } + //inline Vector(int X, int Y, int Z) { x = (float)X; y = (float)Y; z = (float)Z; } + inline Vector(const Vector& v): x(0.0), y(0.0), z(0.0) { x = v.x; y = v.y; z = v.z; } + inline Vector(float rgfl[3]): x(0.0), y(0.0), z(0.0) { x = rgfl[0]; y = rgfl[1]; z = rgfl[2]; } + + // Operators + inline Vector operator-(void) const { return Vector(-x,-y,-z); } + inline int operator==(const Vector& v) const { return x==v.x && y==v.y && z==v.z; } + inline int operator!=(const Vector& v) const { return !(*this==v); } + inline Vector operator+(const Vector& v) const { return Vector(x+v.x, y+v.y, z+v.z); } + inline Vector operator-(const Vector& v) const { return Vector(x-v.x, y-v.y, z-v.z); } + inline Vector operator*(float fl) const { return Vector(x*fl, y*fl, z*fl); } + inline Vector operator/(float fl) const { return Vector(x/fl, y/fl, z/fl); } + + // Methods + inline void CopyToArray(float* rgfl) const { rgfl[0] = x, rgfl[1] = y, rgfl[2] = z; } + inline float Length(void) const { return sqrt(x*x + y*y + z*z); } + operator float *() { return &x; } // Vectors will now automatically convert to float * when needed + operator const float *() const { return &x; } // Vectors will now automatically convert to float * when needed + inline Vector Normalize(void) const + { + float flLen = Length(); + if (flLen == 0) return Vector(0,0,1); // ???? + flLen = 1 / flLen; + return Vector(x * flLen, y * flLen, z * flLen); + } + + inline Vector2D Make2D ( void ) const + { + Vector2D Vec2; + + Vec2.x = x; + Vec2.y = y; + + return Vec2; + } + inline float Length2D(void) const { return sqrt(x*x + y*y); } + + // Members + vec_t x, y, z; +}; + +inline Vector operator*(float fl, const Vector& v) { return v * fl; } +inline float DotProduct(const Vector& a, const Vector& b) { return(a.x*b.x+a.y*b.y+a.z*b.z); } +inline Vector CrossProduct(const Vector& a, const Vector& b) { return Vector( a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x ); } + +#endif diff --git a/dep/rehlsdk/dlls/weapons.h b/dep/rehlsdk/dlls/weapons.h new file mode 100644 index 0000000..be407f5 --- /dev/null +++ b/dep/rehlsdk/dlls/weapons.h @@ -0,0 +1,1019 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef WEAPONS_H +#define WEAPONS_H + +#include "effects.h" + +class CBasePlayer; +extern int gmsgWeapPickup; + +void DeactivateSatchels( CBasePlayer *pOwner ); + +// Contact Grenade / Timed grenade / Satchel Charge +class CGrenade : public CBaseMonster +{ +public: + void Spawn( void ); + + typedef enum { SATCHEL_DETONATE = 0, SATCHEL_RELEASE } SATCHELCODE; + + static CGrenade *ShootTimed( entvars_t *pevOwner, Vector vecStart, Vector vecVelocity, float time ); + static CGrenade *ShootContact( entvars_t *pevOwner, Vector vecStart, Vector vecVelocity ); + static CGrenade *ShootSatchelCharge( entvars_t *pevOwner, Vector vecStart, Vector vecVelocity ); + static void UseSatchelCharges( entvars_t *pevOwner, SATCHELCODE code ); + + void Explode( Vector vecSrc, Vector vecAim ); + void Explode( TraceResult *pTrace, int bitsDamageType ); + void EXPORT Smoke( void ); + + void EXPORT BounceTouch( CBaseEntity *pOther ); + void EXPORT SlideTouch( CBaseEntity *pOther ); + void EXPORT ExplodeTouch( CBaseEntity *pOther ); + void EXPORT DangerSoundThink( void ); + void EXPORT PreDetonate( void ); + void EXPORT Detonate( void ); + void EXPORT DetonateUse( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value ); + void EXPORT TumbleThink( void ); + + virtual void BounceSound( void ); + virtual int BloodColor( void ) { return DONT_BLEED; } + virtual void Killed( entvars_t *pevAttacker, int iGib ); + + BOOL m_fRegisteredSound;// whether or not this grenade has issued its DANGER sound to the world sound list yet. +}; + + +// constant items +#define ITEM_HEALTHKIT 1 +#define ITEM_ANTIDOTE 2 +#define ITEM_SECURITY 3 +#define ITEM_BATTERY 4 + +#define WEAPON_NONE 0 +#define WEAPON_CROWBAR 1 +#define WEAPON_GLOCK 2 +#define WEAPON_PYTHON 3 +#define WEAPON_MP5 4 +#define WEAPON_CHAINGUN 5 +#define WEAPON_CROSSBOW 6 +#define WEAPON_SHOTGUN 7 +#define WEAPON_RPG 8 +#define WEAPON_GAUSS 9 +#define WEAPON_EGON 10 +#define WEAPON_HORNETGUN 11 +#define WEAPON_HANDGRENADE 12 +#define WEAPON_TRIPMINE 13 +#define WEAPON_SATCHEL 14 +#define WEAPON_SNARK 15 + +#define WEAPON_ALLWEAPONS (~(1<absmin = pev->origin + Vector(-16, -16, -5); + pev->absmax = pev->origin + Vector(16, 16, 28); + } + + void PrimaryAttack( void ); + BOOL Deploy( void ); + void Holster( int skiplocal = 0 ); + void WeaponIdle( void ); + + virtual BOOL UseDecrement( void ) + { +#if defined( CLIENT_WEAPONS ) + return TRUE; +#else + return FALSE; +#endif + } + +private: + unsigned short m_usTripFire; + +}; + +class CSqueak : public CBasePlayerWeapon +{ +public: + void Spawn( void ); + void Precache( void ); + int iItemSlot( void ) { return 5; } + int GetItemInfo(ItemInfo *p); + + void PrimaryAttack( void ); + void SecondaryAttack( void ); + BOOL Deploy( void ); + void Holster( int skiplocal = 0 ); + void WeaponIdle( void ); + int m_fJustThrown; + + virtual BOOL UseDecrement( void ) + { +#if defined( CLIENT_WEAPONS ) + return TRUE; +#else + return FALSE; +#endif + } + +private: + unsigned short m_usSnarkFire; +}; + + +#endif // WEAPONS_H diff --git a/dep/rehlsdk/engine/FlightRecorder.h b/dep/rehlsdk/engine/FlightRecorder.h new file mode 100644 index 0000000..66a6477 --- /dev/null +++ b/dep/rehlsdk/engine/FlightRecorder.h @@ -0,0 +1,61 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#include "archtypes.h" + +class IRehldsFlightRecorder +{ +public: + virtual ~IRehldsFlightRecorder() { } + + virtual uint16 RegisterMessage(const char* module, const char *message, unsigned int version, bool inOut) = 0; + + virtual void StartMessage(uint16 msg, bool entrance) = 0; + virtual void EndMessage(uint16 msg, bool entrance) = 0; + + virtual void WriteInt8(int8 v) = 0; + virtual void WriteUInt8(uint8 v) = 0; + + virtual void WriteInt16(int16 v) = 0; + virtual void WriteUInt16(uint16 v) = 0; + + virtual void WriteInt32(int32 v) = 0; + virtual void WriteUInt32(uint32 v) = 0; + + virtual void WriteInt64(int64 v) = 0; + virtual void WriteUInt64(uint64 v) = 0; + + virtual void WriteFloat(float v) = 0; + virtual void WriteDouble(double v) = 0; + + virtual void WriteString(const char* s) = 0; + + virtual void WriteBuffer(const void* data ,unsigned int len) = 0; + +}; diff --git a/dep/rehlsdk/engine/Sequence.h b/dep/rehlsdk/engine/Sequence.h new file mode 100644 index 0000000..6253018 --- /dev/null +++ b/dep/rehlsdk/engine/Sequence.h @@ -0,0 +1,201 @@ +//--------------------------------------------------------------------------- +// +// S c r i p t e d S e q u e n c e s +// +//--------------------------------------------------------------------------- +#ifndef _INCLUDE_SEQUENCE_H_ +#define _INCLUDE_SEQUENCE_H_ + + +#ifndef _DEF_BYTE_ +typedef unsigned char byte; +#endif + +//--------------------------------------------------------------------------- +// client_textmessage_t +//--------------------------------------------------------------------------- +typedef struct client_textmessage_s +{ + int effect; + byte r1, g1, b1, a1; // 2 colors for effects + byte r2, g2, b2, a2; + float x; + float y; + float fadein; + float fadeout; + float holdtime; + float fxtime; + const char *pName; + const char *pMessage; +} client_textmessage_t; + + +//-------------------------------------------------------------------------- +// sequenceDefaultBits_e +// +// Enumerated list of possible modifiers for a command. This enumeration +// is used in a bitarray controlling what modifiers are specified for a command. +//--------------------------------------------------------------------------- +enum sequenceModifierBits +{ + SEQUENCE_MODIFIER_EFFECT_BIT = (1 << 1), + SEQUENCE_MODIFIER_POSITION_BIT = (1 << 2), + SEQUENCE_MODIFIER_COLOR_BIT = (1 << 3), + SEQUENCE_MODIFIER_COLOR2_BIT = (1 << 4), + SEQUENCE_MODIFIER_FADEIN_BIT = (1 << 5), + SEQUENCE_MODIFIER_FADEOUT_BIT = (1 << 6), + SEQUENCE_MODIFIER_HOLDTIME_BIT = (1 << 7), + SEQUENCE_MODIFIER_FXTIME_BIT = (1 << 8), + SEQUENCE_MODIFIER_SPEAKER_BIT = (1 << 9), + SEQUENCE_MODIFIER_LISTENER_BIT = (1 << 10), + SEQUENCE_MODIFIER_TEXTCHANNEL_BIT = (1 << 11), +}; +typedef enum sequenceModifierBits sequenceModifierBits_e ; + + +//--------------------------------------------------------------------------- +// sequenceCommandEnum_e +// +// Enumerated sequence command types. +//--------------------------------------------------------------------------- +enum sequenceCommandEnum_ +{ + SEQUENCE_COMMAND_ERROR = -1, + SEQUENCE_COMMAND_PAUSE = 0, + SEQUENCE_COMMAND_FIRETARGETS, + SEQUENCE_COMMAND_KILLTARGETS, + SEQUENCE_COMMAND_TEXT, + SEQUENCE_COMMAND_SOUND, + SEQUENCE_COMMAND_GOSUB, + SEQUENCE_COMMAND_SENTENCE, + SEQUENCE_COMMAND_REPEAT, + SEQUENCE_COMMAND_SETDEFAULTS, + SEQUENCE_COMMAND_MODIFIER, + SEQUENCE_COMMAND_POSTMODIFIER, + SEQUENCE_COMMAND_NOOP, + + SEQUENCE_MODIFIER_EFFECT, + SEQUENCE_MODIFIER_POSITION, + SEQUENCE_MODIFIER_COLOR, + SEQUENCE_MODIFIER_COLOR2, + SEQUENCE_MODIFIER_FADEIN, + SEQUENCE_MODIFIER_FADEOUT, + SEQUENCE_MODIFIER_HOLDTIME, + SEQUENCE_MODIFIER_FXTIME, + SEQUENCE_MODIFIER_SPEAKER, + SEQUENCE_MODIFIER_LISTENER, + SEQUENCE_MODIFIER_TEXTCHANNEL, +}; +typedef enum sequenceCommandEnum_ sequenceCommandEnum_e; + + +//--------------------------------------------------------------------------- +// sequenceCommandType_e +// +// Typeerated sequence command types. +//--------------------------------------------------------------------------- +enum sequenceCommandType_ +{ + SEQUENCE_TYPE_COMMAND, + SEQUENCE_TYPE_MODIFIER, +}; +typedef enum sequenceCommandType_ sequenceCommandType_e; + + +//--------------------------------------------------------------------------- +// sequenceCommandMapping_s +// +// A mapping of a command enumerated-value to its name. +//--------------------------------------------------------------------------- +typedef struct sequenceCommandMapping_ sequenceCommandMapping_s; +struct sequenceCommandMapping_ +{ + sequenceCommandEnum_e commandEnum; + const char* commandName; + sequenceCommandType_e commandType; +}; + + +//--------------------------------------------------------------------------- +// sequenceCommandLine_s +// +// Structure representing a single command (usually 1 line) from a +// .SEQ file entry. +//--------------------------------------------------------------------------- +typedef struct sequenceCommandLine_ sequenceCommandLine_s; +struct sequenceCommandLine_ +{ + int commandType; // Specifies the type of command + client_textmessage_t clientMessage; // Text HUD message struct + char* speakerName; // Targetname of speaking entity + char* listenerName; // Targetname of entity being spoken to + char* soundFileName; // Name of sound file to play + char* sentenceName; // Name of sentences.txt to play + char* fireTargetNames; // List of targetnames to fire + char* killTargetNames; // List of targetnames to remove + float delay; // Seconds 'till next command + int repeatCount; // If nonzero, reset execution pointer to top of block (N times, -1 = infinite) + int textChannel; // Display channel on which text message is sent + int modifierBitField; // Bit field to specify what clientmessage fields are valid + sequenceCommandLine_s* nextCommandLine; // Next command (linked list) +}; + + +//--------------------------------------------------------------------------- +// sequenceEntry_s +// +// Structure representing a single command (usually 1 line) from a +// .SEQ file entry. +//--------------------------------------------------------------------------- +typedef struct sequenceEntry_ sequenceEntry_s; +struct sequenceEntry_ +{ + char* fileName; // Name of sequence file without .SEQ extension + char* entryName; // Name of entry label in file + sequenceCommandLine_s* firstCommand; // Linked list of commands in entry + sequenceEntry_s* nextEntry; // Next loaded entry + qboolean isGlobal; // Is entry retained over level transitions? +}; + + + +//--------------------------------------------------------------------------- +// sentenceEntry_s +// Structure representing a single sentence of a group from a .SEQ +// file entry. Sentences are identical to entries in sentences.txt, but +// can be unique per level and are loaded/unloaded with the level. +//--------------------------------------------------------------------------- +typedef struct sentenceEntry_ sentenceEntry_s; +struct sentenceEntry_ +{ + char* data; // sentence data (ie "We have hostiles" ) + sentenceEntry_s* nextEntry; // Next loaded entry + qboolean isGlobal; // Is entry retained over level transitions? + unsigned int index; // this entry's position in the file. +}; + +//-------------------------------------------------------------------------- +// sentenceGroupEntry_s +// Structure representing a group of sentences found in a .SEQ file. +// A sentence group is defined by all sentences with the same name, ignoring +// the number at the end of the sentence name. Groups enable a sentence +// to be picked at random across a group. +//-------------------------------------------------------------------------- +typedef struct sentenceGroupEntry_ sentenceGroupEntry_s; +struct sentenceGroupEntry_ +{ + char* groupName; // name of the group (ie CT_ALERT ) + unsigned int numSentences; // number of sentences in group + sentenceEntry_s* firstSentence; // head of linked list of sentences in group + sentenceGroupEntry_s* nextEntry; // next loaded group +}; + +//--------------------------------------------------------------------------- +// Function declarations +//--------------------------------------------------------------------------- +sequenceEntry_s* SequenceGet( const char* fileName, const char* entryName ); +void Sequence_ParseFile( const char* fileName, qboolean isGlobal ); +void Sequence_OnLevelLoad( const char* mapName ); +sentenceEntry_s* SequencePickSentence( const char *groupName, int pickMethod, int *picked ); + +#endif /* _INCLUDE_SEQUENCE_H_ */ diff --git a/dep/rehlsdk/engine/archtypes.h b/dep/rehlsdk/engine/archtypes.h new file mode 100644 index 0000000..e528a6d --- /dev/null +++ b/dep/rehlsdk/engine/archtypes.h @@ -0,0 +1,66 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/#ifndef ARCHTYPES_H +#define ARCHTYPES_H + +#ifdef __x86_64__ +#define X64BITS +#endif + +#if defined( _WIN32 ) && (! defined( __MINGW32__ )) + +typedef __int8 int8; +typedef unsigned __int8 uint8; +typedef __int16 int16; +typedef unsigned __int16 uint16; +typedef __int32 int32; +typedef unsigned __int32 uint32; +typedef __int64 int64; +typedef unsigned __int64 uint64; +typedef __int32 intp; // intp is an integer that can accomodate a pointer +typedef unsigned __int32 uintp; // (ie, sizeof(intp) >= sizeof(int) && sizeof(intp) >= sizeof(void *) + +#else /* _WIN32 */ +typedef char int8; +typedef unsigned char uint8; +typedef short int16; +typedef unsigned short uint16; +typedef int int32; +typedef unsigned int uint32; +typedef long long int64; +typedef unsigned long long uint64; +#ifdef X64BITS +typedef long long intp; +typedef unsigned long long uintp; +#else +typedef int intp; +typedef unsigned int uintp; +#endif + +#endif /* else _WIN32 */ + +#endif /* ARCHTYPES_H */ diff --git a/dep/rehlsdk/engine/bspfile.h b/dep/rehlsdk/engine/bspfile.h new file mode 100644 index 0000000..b6d498c --- /dev/null +++ b/dep/rehlsdk/engine/bspfile.h @@ -0,0 +1,160 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +// header +#define Q1BSP_VERSION 29 // quake1 regular version (beta is 28) +#define HLBSP_VERSION 30 // half-life regular version + +#define MAX_MAP_HULLS 4 + +#define CONTENTS_ORIGIN -7 // removed at csg time +#define CONTENTS_CLIP -8 // changed to contents_solid +#define CONTENTS_CURRENT_0 -9 +#define CONTENTS_CURRENT_90 -10 +#define CONTENTS_CURRENT_180 -11 +#define CONTENTS_CURRENT_270 -12 +#define CONTENTS_CURRENT_UP -13 +#define CONTENTS_CURRENT_DOWN -14 + +#define CONTENTS_TRANSLUCENT -15 + +#define LUMP_ENTITIES 0 +#define LUMP_PLANES 1 +#define LUMP_TEXTURES 2 +#define LUMP_VERTEXES 3 +#define LUMP_VISIBILITY 4 +#define LUMP_NODES 5 +#define LUMP_TEXINFO 6 +#define LUMP_FACES 7 +#define LUMP_LIGHTING 8 +#define LUMP_CLIPNODES 9 +#define LUMP_LEAFS 10 +#define LUMP_MARKSURFACES 11 +#define LUMP_EDGES 12 +#define LUMP_SURFEDGES 13 +#define LUMP_MODELS 14 + +#define HEADER_LUMPS 15 + +typedef struct lump_s +{ + int fileofs; + int filelen; +} lump_t; + +typedef struct dmodel_s +{ + float mins[3], maxs[3]; + float origin[3]; + int headnode[MAX_MAP_HULLS]; + int visleafs; // not including the solid leaf 0 + int firstface, numfaces; +} dmodel_t; + +typedef struct dheader_s +{ + int version; + lump_t lumps[15]; +} dheader_t; + +typedef struct dmiptexlump_s +{ + int _nummiptex; + int dataofs[4]; +} dmiptexlump_t; + +typedef struct miptex_s +{ + char name[16]; + unsigned width; + unsigned height; + unsigned offsets[4]; +} miptex_t; + +typedef struct dvertex_s +{ + float point[3]; +} dvertex_t; + +typedef struct dplane_s +{ + float normal[3]; + float dist; + int type; +} dplane_t; + +typedef struct dnode_s +{ + int planenum; + short children[2]; + short mins[3]; + short maxs[3]; + unsigned short firstface; + unsigned short numfaces; +} dnode_t; + +typedef struct dclipnode_s +{ + int planenum; + short children[2]; // negative numbers are contents +} dclipnode_t; + +typedef struct texinfo_s +{ + float vecs[2][4]; + int _miptex; + int flags; +} texinfo_t; + +typedef struct dedge_s +{ + unsigned short v[2]; +} dedge_t; + +typedef struct dface_s +{ + short planenum; + short side; + int firstedge; + short numedges; + short texinfo; + byte styles[4]; + int lightofs; +} dface_t; + +typedef struct dleaf_s +{ + int contents; + int visofs; + short mins[3]; + short maxs[3]; + unsigned short firstmarksurface; + unsigned short nummarksurfaces; + byte ambient_level[4]; +} dleaf_t; diff --git a/dep/rehlsdk/engine/cmd_rehlds.h b/dep/rehlsdk/engine/cmd_rehlds.h new file mode 100644 index 0000000..003cb60 --- /dev/null +++ b/dep/rehlsdk/engine/cmd_rehlds.h @@ -0,0 +1,49 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#include "archtypes.h" + +typedef void(*xcommand_t)(void); +typedef struct cmd_function_s +{ + struct cmd_function_s *next; + const char *name; + xcommand_t function; + int flags; +} cmd_function_t; + +typedef enum cmd_source_s +{ + src_client = 0, // came in over a net connection as a clc_stringcmd. host_client will be valid during this state. + src_command = 1, // from the command buffer. +} cmd_source_t; + +#define FCMD_HUD_COMMAND BIT(0) +#define FCMD_GAME_COMMAND BIT(1) +#define FCMD_WRAPPER_COMMAND BIT(2) diff --git a/dep/rehlsdk/engine/common_rehlds.h b/dep/rehlsdk/engine/common_rehlds.h new file mode 100644 index 0000000..02c2d77 --- /dev/null +++ b/dep/rehlsdk/engine/common_rehlds.h @@ -0,0 +1,85 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#include "const.h" +#include "qlimits.h" + +#ifdef REHLDS_FIXES +#define COM_TOKEN_LEN 2048 +#else +#define COM_TOKEN_LEN 1024 +#endif + +// Don't allow overflow +#define SIZEBUF_CHECK_OVERFLOW 0 +#define SIZEBUF_ALLOW_OVERFLOW BIT(0) +#define SIZEBUF_OVERFLOWED BIT(1) + +#define MAX_NUM_ARGVS 50 +#define NUM_SAFE_ARGVS 7 + +#define COM_COPY_CHUNK_SIZE 1024 +#define COM_MAX_CMD_LINE 256 + +typedef struct sizebuf_s +{ + const char *buffername; + uint16 flags; + byte *data; + int maxsize; + int cursize; +} sizebuf_t; + +typedef struct downloadtime_s +{ + qboolean bUsed; + float fTime; + int nBytesRemaining; +} downloadtime_t; + +typedef struct incomingtransfer_s +{ + qboolean doneregistering; + int percent; + qboolean downloadrequested; + downloadtime_t rgStats[8]; + int nCurStat; + int nTotalSize; + int nTotalToTransfer; + int nRemainingToTransfer; + float fLastStatusUpdate; + qboolean custom; +} incomingtransfer_t; + +typedef enum server_state_e +{ + ss_dead = 0, + ss_loading = 1, + ss_active = 2, +} server_state_t; diff --git a/dep/rehlsdk/engine/crc32c.cpp b/dep/rehlsdk/engine/crc32c.cpp new file mode 100644 index 0000000..1d6fa9b --- /dev/null +++ b/dep/rehlsdk/engine/crc32c.cpp @@ -0,0 +1,154 @@ +/* +Copyright (C) 2010 by Ronnie Sahlberg +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details. +You should have received a copy of the GNU Lesser General Public License +along with this program; if not, see . +*/ + +#include "crc32c.h" +#include "sys_shared.h" +#include "immintrin.h" + +/*****************************************************************/ +/* */ +/* CRC LOOKUP TABLE */ +/* ================ */ +/* The following CRC lookup table was generated automagically */ +/* by the Rocksoft^tm Model CRC Algorithm Table Generation */ +/* Program V1.0 using the following model parameters: */ +/* */ +/* Width : 4 bytes. */ +/* Poly : 0x1EDC6F41L */ +/* Reverse : TRUE. */ +/* */ +/* For more information on the Rocksoft^tm Model CRC Algorithm, */ +/* see the document titled "A Painless Guide to CRC Error */ +/* Detection Algorithms" by Ross Williams */ +/* (ross@guest.adelaide.edu.au.). This document is likely to be */ +/* in the FTP archive "ftp.adelaide.edu.au/pub/rocksoft". */ +/* */ +/*****************************************************************/ + +static uint32 crctable[256] = { + 0x00000000L, 0xF26B8303L, 0xE13B70F7L, 0x1350F3F4L, + 0xC79A971FL, 0x35F1141CL, 0x26A1E7E8L, 0xD4CA64EBL, + 0x8AD958CFL, 0x78B2DBCCL, 0x6BE22838L, 0x9989AB3BL, + 0x4D43CFD0L, 0xBF284CD3L, 0xAC78BF27L, 0x5E133C24L, + 0x105EC76FL, 0xE235446CL, 0xF165B798L, 0x030E349BL, + 0xD7C45070L, 0x25AFD373L, 0x36FF2087L, 0xC494A384L, + 0x9A879FA0L, 0x68EC1CA3L, 0x7BBCEF57L, 0x89D76C54L, + 0x5D1D08BFL, 0xAF768BBCL, 0xBC267848L, 0x4E4DFB4BL, + 0x20BD8EDEL, 0xD2D60DDDL, 0xC186FE29L, 0x33ED7D2AL, + 0xE72719C1L, 0x154C9AC2L, 0x061C6936L, 0xF477EA35L, + 0xAA64D611L, 0x580F5512L, 0x4B5FA6E6L, 0xB93425E5L, + 0x6DFE410EL, 0x9F95C20DL, 0x8CC531F9L, 0x7EAEB2FAL, + 0x30E349B1L, 0xC288CAB2L, 0xD1D83946L, 0x23B3BA45L, + 0xF779DEAEL, 0x05125DADL, 0x1642AE59L, 0xE4292D5AL, + 0xBA3A117EL, 0x4851927DL, 0x5B016189L, 0xA96AE28AL, + 0x7DA08661L, 0x8FCB0562L, 0x9C9BF696L, 0x6EF07595L, + 0x417B1DBCL, 0xB3109EBFL, 0xA0406D4BL, 0x522BEE48L, + 0x86E18AA3L, 0x748A09A0L, 0x67DAFA54L, 0x95B17957L, + 0xCBA24573L, 0x39C9C670L, 0x2A993584L, 0xD8F2B687L, + 0x0C38D26CL, 0xFE53516FL, 0xED03A29BL, 0x1F682198L, + 0x5125DAD3L, 0xA34E59D0L, 0xB01EAA24L, 0x42752927L, + 0x96BF4DCCL, 0x64D4CECFL, 0x77843D3BL, 0x85EFBE38L, + 0xDBFC821CL, 0x2997011FL, 0x3AC7F2EBL, 0xC8AC71E8L, + 0x1C661503L, 0xEE0D9600L, 0xFD5D65F4L, 0x0F36E6F7L, + 0x61C69362L, 0x93AD1061L, 0x80FDE395L, 0x72966096L, + 0xA65C047DL, 0x5437877EL, 0x4767748AL, 0xB50CF789L, + 0xEB1FCBADL, 0x197448AEL, 0x0A24BB5AL, 0xF84F3859L, + 0x2C855CB2L, 0xDEEEDFB1L, 0xCDBE2C45L, 0x3FD5AF46L, + 0x7198540DL, 0x83F3D70EL, 0x90A324FAL, 0x62C8A7F9L, + 0xB602C312L, 0x44694011L, 0x5739B3E5L, 0xA55230E6L, + 0xFB410CC2L, 0x092A8FC1L, 0x1A7A7C35L, 0xE811FF36L, + 0x3CDB9BDDL, 0xCEB018DEL, 0xDDE0EB2AL, 0x2F8B6829L, + 0x82F63B78L, 0x709DB87BL, 0x63CD4B8FL, 0x91A6C88CL, + 0x456CAC67L, 0xB7072F64L, 0xA457DC90L, 0x563C5F93L, + 0x082F63B7L, 0xFA44E0B4L, 0xE9141340L, 0x1B7F9043L, + 0xCFB5F4A8L, 0x3DDE77ABL, 0x2E8E845FL, 0xDCE5075CL, + 0x92A8FC17L, 0x60C37F14L, 0x73938CE0L, 0x81F80FE3L, + 0x55326B08L, 0xA759E80BL, 0xB4091BFFL, 0x466298FCL, + 0x1871A4D8L, 0xEA1A27DBL, 0xF94AD42FL, 0x0B21572CL, + 0xDFEB33C7L, 0x2D80B0C4L, 0x3ED04330L, 0xCCBBC033L, + 0xA24BB5A6L, 0x502036A5L, 0x4370C551L, 0xB11B4652L, + 0x65D122B9L, 0x97BAA1BAL, 0x84EA524EL, 0x7681D14DL, + 0x2892ED69L, 0xDAF96E6AL, 0xC9A99D9EL, 0x3BC21E9DL, + 0xEF087A76L, 0x1D63F975L, 0x0E330A81L, 0xFC588982L, + 0xB21572C9L, 0x407EF1CAL, 0x532E023EL, 0xA145813DL, + 0x758FE5D6L, 0x87E466D5L, 0x94B49521L, 0x66DF1622L, + 0x38CC2A06L, 0xCAA7A905L, 0xD9F75AF1L, 0x2B9CD9F2L, + 0xFF56BD19L, 0x0D3D3E1AL, 0x1E6DCDEEL, 0xEC064EEDL, + 0xC38D26C4L, 0x31E6A5C7L, 0x22B65633L, 0xD0DDD530L, + 0x0417B1DBL, 0xF67C32D8L, 0xE52CC12CL, 0x1747422FL, + 0x49547E0BL, 0xBB3FFD08L, 0xA86F0EFCL, 0x5A048DFFL, + 0x8ECEE914L, 0x7CA56A17L, 0x6FF599E3L, 0x9D9E1AE0L, + 0xD3D3E1ABL, 0x21B862A8L, 0x32E8915CL, 0xC083125FL, + 0x144976B4L, 0xE622F5B7L, 0xF5720643L, 0x07198540L, + 0x590AB964L, 0xAB613A67L, 0xB831C993L, 0x4A5A4A90L, + 0x9E902E7BL, 0x6CFBAD78L, 0x7FAB5E8CL, 0x8DC0DD8FL, + 0xE330A81AL, 0x115B2B19L, 0x020BD8EDL, 0xF0605BEEL, + 0x24AA3F05L, 0xD6C1BC06L, 0xC5914FF2L, 0x37FACCF1L, + 0x69E9F0D5L, 0x9B8273D6L, 0x88D28022L, 0x7AB90321L, + 0xAE7367CAL, 0x5C18E4C9L, 0x4F48173DL, 0xBD23943EL, + 0xF36E6F75L, 0x0105EC76L, 0x12551F82L, 0xE03E9C81L, + 0x34F4F86AL, 0xC69F7B69L, 0xD5CF889DL, 0x27A40B9EL, + 0x79B737BAL, 0x8BDCB4B9L, 0x988C474DL, 0x6AE7C44EL, + 0xBE2DA0A5L, 0x4C4623A6L, 0x5F16D052L, 0xAD7D5351L +}; + +uint32 crc32c_t8_nosse(uint32 iCRC, uint8 u8) { + return (iCRC >> 8) ^ crctable[(iCRC ^ u8) & 0xFF]; +} + +uint32 crc32c_t_nosse(uint32 iCRC, const uint8 *buf, int len) { + uint32 crc = iCRC; + while (len-- > 0) { + crc = (crc >> 8) ^ crctable[(crc ^ (*buf++)) & 0xFF]; + } + return crc; +} + +#ifdef REHLDS_SSE +FUNC_TARGET("sse4.2") +uint32 crc32c_t8_sse(uint32 iCRC, uint8 u8) { + return _mm_crc32_u8(iCRC, u8); +} + +FUNC_TARGET("sse4.2") +uint32 crc32c_t_sse(uint32 iCRC, const uint8 *buf, unsigned int len) { + uint32 crc32cval = iCRC; + unsigned int i = 0; + + for (; i < (len >> 2); i += 4) { + crc32cval = _mm_crc32_u32(crc32cval, *(uint32*)&buf[i]); + } + + for (; i < len; i++) { + crc32cval = _mm_crc32_u8(crc32cval, buf[i]); + } + + return crc32cval; +} + +uint32 crc32c_t(uint32 iCRC, const uint8 *buf, unsigned int len) { + return cpuinfo.sse4_2 ? crc32c_t_sse(iCRC, buf, len) : crc32c_t_nosse(iCRC, buf, len); +} + +#else + +uint32 crc32c_t(uint32 iCRC, const uint8 *buf, unsigned int len) { + return crc32c_t_nosse(iCRC, buf, len); +} + +#endif // REHLDS_SSE + +uint32 crc32c(const uint8 *buf, int len) { + return crc32c_t(0xffffffff, buf, len); +} diff --git a/dep/rehlsdk/engine/crc32c.h b/dep/rehlsdk/engine/crc32c.h new file mode 100644 index 0000000..044b013 --- /dev/null +++ b/dep/rehlsdk/engine/crc32c.h @@ -0,0 +1,24 @@ +/* +Copyright (C) 2010 by Ronnie Sahlberg +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details. +You should have received a copy of the GNU Lesser General Public License +along with this program; if not, see . +*/ + +#pragma once + +#include "archtypes.h" + +extern uint32 crc32c_t8_nosse(uint32 iCRC, uint8 u8); +extern uint32 crc32c_t8_sse(uint32 iCRC, uint8 u8); +extern uint32 crc32c_t_nosse(uint32 iCRC, const uint8 *buf, int len); +extern uint32 crc32c_t_sse(uint32 iCRC, const uint8 *buf, unsigned int len); +extern uint32 crc32c_t(uint32 iCRC, const uint8 *buf, unsigned int len); +extern uint32 crc32c(const uint8 *buf, int len); diff --git a/dep/rehlsdk/engine/custom.h b/dep/rehlsdk/engine/custom.h new file mode 100644 index 0000000..333a4a0 --- /dev/null +++ b/dep/rehlsdk/engine/custom.h @@ -0,0 +1,108 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// Customization.h +#pragma once + +#include "const.h" + +#define MAX_QPATH 64 // Must match value in quakedefs.h +#define MAX_RESOURCE_LIST 1280 + +///////////////// +// Customization +// passed to pfnPlayerCustomization +// For automatic downloading. +typedef enum +{ + t_sound = 0, + t_skin, + t_model, + t_decal, + t_generic, + t_eventscript, + t_world, // Fake type for world, is really t_model + rt_unk, + + rt_max +} resourcetype_t; + + +typedef struct +{ + int size; +} _resourceinfo_t; + +typedef struct resourceinfo_s +{ + _resourceinfo_t info[ rt_max ]; +} resourceinfo_t; + +#define RES_FATALIFMISSING (1<<0) // Disconnect if we can't get this file. +#define RES_WASMISSING (1<<1) // Do we have the file locally, did we get it ok? +#define RES_CUSTOM (1<<2) // Is this resource one that corresponds to another player's customization + // or is it a server startup resource. +#define RES_REQUESTED (1<<3) // Already requested a download of this one +#define RES_PRECACHED (1<<4) // Already precached +#define RES_ALWAYS (1<<5) // download always even if available on client +#define RES_UNK_6 (1<<6) // TODO: what is it? +#define RES_CHECKFILE (1<<7) // check file on client + +#include "crc.h" + +typedef struct resource_s +{ +#ifdef HOOK_HLTV + // NOTE HLTV: array szFileName declared on 260 cell, + // this changes necessary for compatibility hookers. + char szFileName[MAX_PATH]; +#else + char szFileName[MAX_QPATH]; // File name to download/precache. +#endif // HOOK_HLTV + + resourcetype_t type; // t_sound, t_skin, t_model, t_decal. + int nIndex; // For t_decals + int nDownloadSize; // Size in Bytes if this must be downloaded. + unsigned char ucFlags; + +// For handling client to client resource propagation + unsigned char rgucMD5_hash[16]; // To determine if we already have it. + unsigned char playernum; // Which player index this resource is associated with, if it's a custom resource. + + unsigned char rguc_reserved[ 32 ]; // For future expansion + struct resource_s *pNext; // Next in chain. + +#if !defined(HLTV) + struct resource_s *pPrev; +#else + unsigned char *data; +#endif // !defined(HLTV) +} resource_t; + +typedef struct customization_s +{ + qboolean bInUse; // Is this customization in use; + resource_t resource; // The resource_t for this customization + qboolean bTranslated; // Has the raw data been translated into a useable format? + // (e.g., raw decal .wad make into texture_t *) + int nUserData1; // Customization specific data + int nUserData2; // Customization specific data + void *pInfo; // Buffer that holds the data structure that references the data (e.g., the cachewad_t) + void *pBuffer; // Buffer that holds the data for the customization (the raw .wad data) + struct customization_s *pNext; // Next in chain +} customization_t; + +#define FCUST_FROMHPAK ( 1<<0 ) +#define FCUST_WIPEDATA ( 1<<1 ) +#define FCUST_IGNOREINIT ( 1<<2 ) diff --git a/dep/rehlsdk/engine/customentity.h b/dep/rehlsdk/engine/customentity.h new file mode 100644 index 0000000..0895bee --- /dev/null +++ b/dep/rehlsdk/engine/customentity.h @@ -0,0 +1,38 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef CUSTOMENTITY_H +#define CUSTOMENTITY_H + +// Custom Entities + +// Start/End Entity is encoded as 12 bits of entity index, and 4 bits of attachment (4:12) +#define BEAMENT_ENTITY(x) ((x)&0xFFF) +#define BEAMENT_ATTACHMENT(x) (((x)>>12)&0xF) + +// Beam types, encoded as a byte +enum +{ + BEAM_POINTS = 0, + BEAM_ENTPOINT, + BEAM_ENTS, + BEAM_HOSE, +}; + +#define BEAM_FSINE 0x10 +#define BEAM_FSOLID 0x20 +#define BEAM_FSHADEIN 0x40 +#define BEAM_FSHADEOUT 0x80 + +#endif //CUSTOMENTITY_H diff --git a/dep/rehlsdk/engine/d_local.h b/dep/rehlsdk/engine/d_local.h new file mode 100644 index 0000000..c2d2f59 --- /dev/null +++ b/dep/rehlsdk/engine/d_local.h @@ -0,0 +1,43 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +typedef struct surfcache_s +{ + struct surfcache_s *next; + struct surfcache_s **owner; + int lightadj[4]; + int dlight; + int size; + unsigned width; + unsigned height; + float mipscale; + struct texture_s *texture; + unsigned char data[4]; +} surfcache_t; diff --git a/dep/rehlsdk/engine/edict.h b/dep/rehlsdk/engine/edict.h new file mode 100644 index 0000000..9a38993 --- /dev/null +++ b/dep/rehlsdk/engine/edict.h @@ -0,0 +1,36 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#if !defined EDICT_H +#define EDICT_H +#ifdef _WIN32 +#pragma once +#endif +#define MAX_ENT_LEAFS 48 + +#include "progdefs.h" + +struct edict_s +{ + qboolean free; + int serialnumber; + link_t area; // linked to a division node or leaf + + int headnode; // -1 to use normal leaf check + int num_leafs; + short leafnums[MAX_ENT_LEAFS]; + + float freetime; // sv.time when the object was freed + + void* pvPrivateData; // Alloced and freed by engine, used by DLLs + + entvars_t v; // C exported fields from progs + + // other fields from progs come immediately after +}; + +#endif diff --git a/dep/rehlsdk/engine/eiface.h b/dep/rehlsdk/engine/eiface.h new file mode 100644 index 0000000..63f3b3c --- /dev/null +++ b/dep/rehlsdk/engine/eiface.h @@ -0,0 +1,536 @@ +/*** +* +* Copyright (c) 1999, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#pragma once + +#include "archtypes.h" // DAL + +#ifdef HLDEMO_BUILD +#define INTERFACE_VERSION 001 +#else // !HLDEMO_BUILD, i.e., regular version of HL +#define INTERFACE_VERSION 140 +#endif // !HLDEMO_BUILD + +#include +#include "custom.h" +#include "cvardef.h" +#include "Sequence.h" +// +// Defines entity interface between engine and DLLs. +// This header file included by engine files and DLL files. +// +// Before including this header, DLLs must: +// include progdefs.h +// This is conveniently done for them in extdll.h +// + +/* +#ifdef _WIN32 +#define DLLEXPORT __stdcall EXT_FUNC +#else +#define DLLEXPORT __attribute__ ((visibility("default"))) EXT_FUNC +#endif +*/ + +enum ALERT_TYPE +{ + at_notice, + at_console, // same as at_notice, but forces a ConPrintf, not a message box + at_aiconsole, // same as at_console, but only shown if developer level is 2! + at_warning, + at_error, + at_logged // Server print to console ( only in multiplayer games ). +}; + +// 4-22-98 JOHN: added for use in pfnClientPrintf +enum PRINT_TYPE +{ + print_console, + print_center, + print_chat, +}; + +// For integrity checking of content on clients +enum FORCE_TYPE +{ + force_exactfile, // File on client must exactly match server's file + force_model_samebounds, // For model files only, the geometry must fit in the same bbox + force_model_specifybounds, // For model files only, the geometry must fit in the specified bbox + force_model_specifybounds_if_avail, // For Steam model files only, the geometry must fit in the specified bbox (if the file is available) +}; + +// Returned by TraceLine +struct TraceResult +{ + int fAllSolid; // if true, plane is not valid + int fStartSolid; // if true, the initial point was in a solid area + int fInOpen; + int fInWater; + float flFraction; // time completed, 1.0 = didn't hit anything + vec3_t vecEndPos; // final position + float flPlaneDist; + vec3_t vecPlaneNormal; // surface normal at impact + edict_t *pHit; // entity the surface is on + int iHitgroup; // 0 == generic, non zero is specific body part +}; + +// CD audio status +typedef struct +{ + int fPlaying;// is sound playing right now? + int fWasPlaying;// if not, CD is paused if WasPlaying is true. + int fInitialized; + int fEnabled; + int fPlayLooping; + float cdvolume; + //BYTE remap[100]; + int fCDRom; + int fPlayTrack; +} CDStatus; + +#include "../common/crc.h" + + +// Engine hands this to DLLs for functionality callbacks +typedef struct enginefuncs_s +{ + int (*pfnPrecacheModel) (const char* s); + int (*pfnPrecacheSound) (const char* s); + void (*pfnSetModel) (edict_t *e, const char *m); + int (*pfnModelIndex) (const char *m); + int (*pfnModelFrames) (int modelIndex); + void (*pfnSetSize) (edict_t *e, const float *rgflMin, const float *rgflMax); + void (*pfnChangeLevel) (const char* s1, const char* s2); + void (*pfnGetSpawnParms) (edict_t *ent); + void (*pfnSaveSpawnParms) (edict_t *ent); + float (*pfnVecToYaw) (const float *rgflVector); + void (*pfnVecToAngles) (const float *rgflVectorIn, float *rgflVectorOut); + void (*pfnMoveToOrigin) (edict_t *ent, const float *pflGoal, float dist, int iMoveType); + void (*pfnChangeYaw) (edict_t* ent); + void (*pfnChangePitch) (edict_t* ent); + edict_t* (*pfnFindEntityByString) (edict_t *pEdictStartSearchAfter, const char *pszField, const char *pszValue); + int (*pfnGetEntityIllum) (edict_t* pEnt); + edict_t* (*pfnFindEntityInSphere) (edict_t *pEdictStartSearchAfter, const float *org, float rad); + edict_t* (*pfnFindClientInPVS) (edict_t *pEdict); + edict_t* (*pfnEntitiesInPVS) (edict_t *pplayer); + void (*pfnMakeVectors) (const float *rgflVector); + void (*pfnAngleVectors) (const float *rgflVector, float *forward, float *right, float *up); + edict_t* (*pfnCreateEntity) (void); + void (*pfnRemoveEntity) (edict_t* e); + edict_t* (*pfnCreateNamedEntity) (int className); + void (*pfnMakeStatic) (edict_t *ent); + int (*pfnEntIsOnFloor) (edict_t *e); + int (*pfnDropToFloor) (edict_t* e); + int (*pfnWalkMove) (edict_t *ent, float yaw, float dist, int iMode); + void (*pfnSetOrigin) (edict_t *e, const float *rgflOrigin); + void (*pfnEmitSound) (edict_t *entity, int channel, const char *sample, /*int*/float volume, float attenuation, int fFlags, int pitch); + void (*pfnEmitAmbientSound) (edict_t *entity, float *pos, const char *samp, float vol, float attenuation, int fFlags, int pitch); + void (*pfnTraceLine) (const float *v1, const float *v2, int fNoMonsters, edict_t *pentToSkip, TraceResult *ptr); + void (*pfnTraceToss) (edict_t* pent, edict_t* pentToIgnore, TraceResult *ptr); + int (*pfnTraceMonsterHull) (edict_t *pEdict, const float *v1, const float *v2, int fNoMonsters, edict_t *pentToSkip, TraceResult *ptr); + void (*pfnTraceHull) (const float *v1, const float *v2, int fNoMonsters, int hullNumber, edict_t *pentToSkip, TraceResult *ptr); + void (*pfnTraceModel) (const float *v1, const float *v2, int hullNumber, edict_t *pent, TraceResult *ptr); + const char *(*pfnTraceTexture) (edict_t *pTextureEntity, const float *v1, const float *v2 ); + void (*pfnTraceSphere) (const float *v1, const float *v2, int fNoMonsters, float radius, edict_t *pentToSkip, TraceResult *ptr); + void (*pfnGetAimVector) (edict_t* ent, float speed, float *rgflReturn); + void (*pfnServerCommand) (const char* str); + void (*pfnServerExecute) (void); + void (*pfnClientCommand) (edict_t* pEdict, const char* szFmt, ...); + void (*pfnParticleEffect) (const float *org, const float *dir, float color, float count); + void (*pfnLightStyle) (int style, const char* val); + int (*pfnDecalIndex) (const char *name); + int (*pfnPointContents) (const float *rgflVector); + void (*pfnMessageBegin) (int msg_dest, int msg_type, const float *pOrigin, edict_t *ed); + void (*pfnMessageEnd) (void); + void (*pfnWriteByte) (int iValue); + void (*pfnWriteChar) (int iValue); + void (*pfnWriteShort) (int iValue); + void (*pfnWriteLong) (int iValue); + void (*pfnWriteAngle) (float flValue); + void (*pfnWriteCoord) (float flValue); + void (*pfnWriteString) (const char *sz); + void (*pfnWriteEntity) (int iValue); + void (*pfnCVarRegister) (cvar_t *pCvar); + float (*pfnCVarGetFloat) (const char *szVarName); + const char* (*pfnCVarGetString) (const char *szVarName); + void (*pfnCVarSetFloat) (const char *szVarName, float flValue); + void (*pfnCVarSetString) (const char *szVarName, const char *szValue); + void (*pfnAlertMessage) (ALERT_TYPE atype, const char *szFmt, ...); + void (*pfnEngineFprintf) (void *pfile, const char *szFmt, ...); + void* (*pfnPvAllocEntPrivateData) (edict_t *pEdict, int32 cb); + void* (*pfnPvEntPrivateData) (edict_t *pEdict); + void (*pfnFreeEntPrivateData) (edict_t *pEdict); + const char* (*pfnSzFromIndex) (int iString); + int (*pfnAllocString) (const char *szValue); + struct entvars_s* (*pfnGetVarsOfEnt) (edict_t *pEdict); + edict_t* (*pfnPEntityOfEntOffset) (int iEntOffset); + int (*pfnEntOffsetOfPEntity) (const edict_t *pEdict); + int (*pfnIndexOfEdict) (const edict_t *pEdict); + edict_t* (*pfnPEntityOfEntIndex) (int iEntIndex); + edict_t* (*pfnFindEntityByVars) (struct entvars_s* pvars); + void* (*pfnGetModelPtr) (edict_t* pEdict); + int (*pfnRegUserMsg) (const char *pszName, int iSize); + void (*pfnAnimationAutomove) (const edict_t* pEdict, float flTime); + void (*pfnGetBonePosition) (const edict_t* pEdict, int iBone, float *rgflOrigin, float *rgflAngles ); + uint32 (*pfnFunctionFromName) ( const char *pName ); + const char *(*pfnNameForFunction) ( uint32 function ); + void (*pfnClientPrintf) ( edict_t* pEdict, PRINT_TYPE ptype, const char *szMsg ); // JOHN: engine callbacks so game DLL can print messages to individual clients + void (*pfnServerPrint) ( const char *szMsg ); + const char *(*pfnCmd_Args) ( void ); // these 3 added + const char *(*pfnCmd_Argv) ( int argc ); // so game DLL can easily + int (*pfnCmd_Argc) ( void ); // access client 'cmd' strings + void (*pfnGetAttachment) (const edict_t *pEdict, int iAttachment, float *rgflOrigin, float *rgflAngles ); + void (*pfnCRC32_Init) (CRC32_t *pulCRC); + void (*pfnCRC32_ProcessBuffer) (CRC32_t *pulCRC, void *p, int len); + void (*pfnCRC32_ProcessByte) (CRC32_t *pulCRC, unsigned char ch); + CRC32_t (*pfnCRC32_Final) (CRC32_t pulCRC); + int32 (*pfnRandomLong) (int32 lLow, int32 lHigh); + float (*pfnRandomFloat) (float flLow, float flHigh); + void (*pfnSetView) (const edict_t *pClient, const edict_t *pViewent ); + float (*pfnTime) ( void ); + void (*pfnCrosshairAngle) (const edict_t *pClient, float pitch, float yaw); + byte * (*pfnLoadFileForMe) (const char *filename, int *pLength); + void (*pfnFreeFile) (void *buffer); + void (*pfnEndSection) (const char *pszSectionName); // trigger_endsection + int (*pfnCompareFileTime) (char *filename1, char *filename2, int *iCompare); + void (*pfnGetGameDir) (char *szGetGameDir); + void (*pfnCvar_RegisterVariable) (cvar_t *variable); + void (*pfnFadeClientVolume) (const edict_t *pEdict, int fadePercent, int fadeOutSeconds, int holdTime, int fadeInSeconds); + void (*pfnSetClientMaxspeed) (edict_t *pEdict, float fNewMaxspeed); + edict_t * (*pfnCreateFakeClient) (const char *netname); // returns NULL if fake client can't be created + void (*pfnRunPlayerMove) (edict_t *fakeclient, const float *viewangles, float forwardmove, float sidemove, float upmove, unsigned short buttons, byte impulse, byte msec ); + int (*pfnNumberOfEntities) (void); + char* (*pfnGetInfoKeyBuffer) (edict_t *e); // passing in NULL gets the serverinfo + char* (*pfnInfoKeyValue) (char *infobuffer, const char *key); + void (*pfnSetKeyValue) (char *infobuffer, const char *key, const char *value); + void (*pfnSetClientKeyValue) (int clientIndex, char *infobuffer, const char *key, const char *value); + int (*pfnIsMapValid) (const char *filename); + void (*pfnStaticDecal) ( const float *origin, int decalIndex, int entityIndex, int modelIndex ); + int (*pfnPrecacheGeneric) (const char* s); + int (*pfnGetPlayerUserId) (edict_t *e ); // returns the server assigned userid for this player. useful for logging frags, etc. returns -1 if the edict couldn't be found in the list of clients + void (*pfnBuildSoundMsg) (edict_t *entity, int channel, const char *sample, /*int*/float volume, float attenuation, int fFlags, int pitch, int msg_dest, int msg_type, const float *pOrigin, edict_t *ed); + int (*pfnIsDedicatedServer) (void);// is this a dedicated server? + cvar_t *(*pfnCVarGetPointer) (const char *szVarName); + unsigned int (*pfnGetPlayerWONId) (edict_t *e); // returns the server assigned WONid for this player. useful for logging frags, etc. returns -1 if the edict couldn't be found in the list of clients + + // YWB 8/1/99 TFF Physics additions + void (*pfnInfo_RemoveKey) ( char *s, const char *key ); + const char *(*pfnGetPhysicsKeyValue) ( const edict_t *pClient, const char *key ); + void (*pfnSetPhysicsKeyValue) ( const edict_t *pClient, const char *key, const char *value ); + const char *(*pfnGetPhysicsInfoString) ( const edict_t *pClient ); + unsigned short (*pfnPrecacheEvent) ( int type, const char*psz ); + void (*pfnPlaybackEvent) ( int flags, const edict_t *pInvoker, unsigned short eventindex, float delay, float *origin, float *angles, float fparam1, float fparam2, int iparam1, int iparam2, int bparam1, int bparam2 ); + + unsigned char *(*pfnSetFatPVS) ( float *org ); + unsigned char *(*pfnSetFatPAS) ( float *org ); + + int (*pfnCheckVisibility ) ( edict_t *entity, unsigned char *pset ); + + void (*pfnDeltaSetField) ( struct delta_s *pFields, const char *fieldname ); + void (*pfnDeltaUnsetField) ( struct delta_s *pFields, const char *fieldname ); + void (*pfnDeltaAddEncoder) ( const char *name, void (*conditionalencode)( struct delta_s *pFields, const unsigned char *from, const unsigned char *to ) ); + int (*pfnGetCurrentPlayer) ( void ); + int (*pfnCanSkipPlayer) ( const edict_t *player ); + int (*pfnDeltaFindField) ( struct delta_s *pFields, const char *fieldname ); + void (*pfnDeltaSetFieldByIndex) ( struct delta_s *pFields, int fieldNumber ); + void (*pfnDeltaUnsetFieldByIndex)( struct delta_s *pFields, int fieldNumber ); + + void (*pfnSetGroupMask) ( int mask, int op ); + + int (*pfnCreateInstancedBaseline) ( int classname, struct entity_state_s *baseline ); + void (*pfnCvar_DirectSet) ( struct cvar_s *var, const char *value ); + + // Forces the client and server to be running with the same version of the specified file + // ( e.g., a player model ). + // Calling this has no effect in single player + void (*pfnForceUnmodified) ( FORCE_TYPE type, float *mins, float *maxs, const char *filename ); + + void (*pfnGetPlayerStats) ( const edict_t *pClient, int *ping, int *packet_loss ); + + void (*pfnAddServerCommand) ( const char *cmd_name, void (*function) (void) ); + + // For voice communications, set which clients hear eachother. + // NOTE: these functions take player entity indices (starting at 1). + qboolean (*pfnVoice_GetClientListening)(int iReceiver, int iSender); + qboolean (*pfnVoice_SetClientListening)(int iReceiver, int iSender, qboolean bListen); + + const char *(*pfnGetPlayerAuthId) ( edict_t *e ); + + // PSV: Added for CZ training map +// const char *(*pfnKeyNameForBinding) ( const char* pBinding ); + + sequenceEntry_s* (*pfnSequenceGet) ( const char* fileName, const char* entryName ); + sentenceEntry_s* (*pfnSequencePickSentence) ( const char* groupName, int pickMethod, int *picked ); + + // LH: Give access to filesize via filesystem + int (*pfnGetFileSize) ( const char *filename ); + + unsigned int (*pfnGetApproxWavePlayLen) (const char *filepath); + // MDC: Added for CZ career-mode + int (*pfnIsCareerMatch) ( void ); + + // BGC: return the number of characters of the localized string referenced by using "label" + int (*pfnGetLocalizedStringLength) (const char *label); + + // BGC: added to facilitate persistent storage of tutor message decay values for + // different career game profiles. Also needs to persist regardless of mp.dll being + // destroyed and recreated. + void (*pfnRegisterTutorMessageShown) (int mid); + int (*pfnGetTimesTutorMessageShown) (int mid); + void (*pfnProcessTutorMessageDecayBuffer) (int *buffer, int bufferLength); + void (*pfnConstructTutorMessageDecayBuffer) (int *buffer, int bufferLength); + void (*pfnResetTutorMessageDecayData) ( void ); + + // Added 2005/08/11 (no SDK update): + void(*pfnQueryClientCvarValue) (const edict_t *player, const char *cvarName); + + // Added 2005/11/21 (no SDK update): + void(*pfnQueryClientCvarValue2) (const edict_t *player, const char *cvarName, int requestID); + + // Added 2009/06/19 (no SDK update): + int(*pfnEngCheckParm) (const char *pchCmdLineToken, char **ppnext); +} enginefuncs_t; + + +// ONLY ADD NEW FUNCTIONS TO THE END OF THIS STRUCT. INTERFACE VERSION IS FROZEN AT 138 + +// Passed to pfnKeyValue +typedef struct KeyValueData_s +{ + char *szClassName; // in: entity classname + char *szKeyName; // in: name of key + char *szValue; // in: value of key + qboolean fHandled; // out: DLL sets to true if key-value pair was understood +} KeyValueData; + + +typedef struct +{ + char mapName[ 32 ]; + char landmarkName[ 32 ]; + edict_t *pentLandmark; + vec3_t vecLandmarkOrigin; +} LEVELLIST; +#define MAX_LEVEL_CONNECTIONS 16 // These are encoded in the lower 16bits of ENTITYTABLE->flags + +typedef struct +{ + int id; // Ordinal ID of this entity (used for entity <--> pointer conversions) + edict_t *pent; // Pointer to the in-game entity + + int location; // Offset from the base data of this entity + int size; // Byte size of this entity's data + int flags; // This could be a short -- bit mask of transitions that this entity is in the PVS of + string_t classname; // entity class name + +} ENTITYTABLE; + +#define FENTTABLE_PLAYER 0x80000000 +#define FENTTABLE_REMOVED 0x40000000 +#define FENTTABLE_MOVEABLE 0x20000000 +#define FENTTABLE_GLOBAL 0x10000000 + +typedef struct saverestore_s SAVERESTOREDATA; + +#ifdef _WIN32 +typedef +#endif +struct saverestore_s +{ + char *pBaseData; // Start of all entity save data + char *pCurrentData; // Current buffer pointer for sequential access + int size; // Current data size + int bufferSize; // Total space for data + int tokenSize; // Size of the linear list of tokens + int tokenCount; // Number of elements in the pTokens table + char **pTokens; // Hash table of entity strings (sparse) + int currentIndex; // Holds a global entity table ID + int tableCount; // Number of elements in the entity table + int connectionCount;// Number of elements in the levelList[] + ENTITYTABLE *pTable; // Array of ENTITYTABLE elements (1 for each entity) + LEVELLIST levelList[ MAX_LEVEL_CONNECTIONS ]; // List of connections from this level + + // smooth transition + int fUseLandmark; + char szLandmarkName[20];// landmark we'll spawn near in next level + vec3_t vecLandmarkOffset;// for landmark transitions + float time; + char szCurrentMapName[32]; // To check global entities + +} +#ifdef _WIN32 +SAVERESTOREDATA +#endif +; + +typedef enum _fieldtypes +{ + FIELD_FLOAT = 0, // Any floating point value + FIELD_STRING, // A string ID (return from ALLOC_STRING) + FIELD_ENTITY, // An entity offset (EOFFSET) + FIELD_CLASSPTR, // CBaseEntity * + FIELD_EHANDLE, // Entity handle + FIELD_EVARS, // EVARS * + FIELD_EDICT, // edict_t *, or edict_t * (same thing) + FIELD_VECTOR, // Any vector + FIELD_POSITION_VECTOR, // A world coordinate (these are fixed up across level transitions automagically) + FIELD_POINTER, // Arbitrary data pointer... to be removed, use an array of FIELD_CHARACTER + FIELD_INTEGER, // Any integer or enum + FIELD_FUNCTION, // A class function pointer (Think, Use, etc) + FIELD_BOOLEAN, // boolean, implemented as an int, I may use this as a hint for compression + FIELD_SHORT, // 2 byte integer + FIELD_CHARACTER, // a byte + FIELD_TIME, // a floating point time (these are fixed up automatically too!) + FIELD_MODELNAME, // Engine string that is a model name (needs precache) + FIELD_SOUNDNAME, // Engine string that is a sound name (needs precache) + + FIELD_TYPECOUNT, // MUST BE LAST +} FIELDTYPE; + +#if !defined(offsetof) && !defined(GNUC) +#define offsetof(s,m) (size_t)&(((s *)0)->m) +#endif + +#define _FIELD(type,name,fieldtype,count,flags) { fieldtype, #name, offsetof(type, name), count, flags } +#define DEFINE_FIELD(type,name,fieldtype) _FIELD(type, name, fieldtype, 1, 0) +#define DEFINE_ARRAY(type,name,fieldtype,count) _FIELD(type, name, fieldtype, count, 0) +#define DEFINE_ENTITY_FIELD(name,fieldtype) _FIELD(entvars_t, name, fieldtype, 1, 0 ) +#define DEFINE_ENTITY_GLOBAL_FIELD(name,fieldtype) _FIELD(entvars_t, name, fieldtype, 1, FTYPEDESC_GLOBAL ) +#define DEFINE_GLOBAL_FIELD(type,name,fieldtype) _FIELD(type, name, fieldtype, 1, FTYPEDESC_GLOBAL ) + + +#define FTYPEDESC_GLOBAL 0x0001 // This field is masked for global entity save/restore + +typedef struct +{ + FIELDTYPE fieldType; + char *fieldName; + int fieldOffset; + short fieldSize; + short flags; +} TYPEDESCRIPTION; + +#ifndef ARRAYSIZE +#define ARRAYSIZE(p) (sizeof(p)/sizeof(p[0])) +#endif + +typedef struct +{ + // Initialize/shutdown the game (one-time call after loading of game .dll ) + void (*pfnGameInit) ( void ); + int (*pfnSpawn) ( edict_t *pent ); + void (*pfnThink) ( edict_t *pent ); + void (*pfnUse) ( edict_t *pentUsed, edict_t *pentOther ); + void (*pfnTouch) ( edict_t *pentTouched, edict_t *pentOther ); + void (*pfnBlocked) ( edict_t *pentBlocked, edict_t *pentOther ); + void (*pfnKeyValue) ( edict_t *pentKeyvalue, KeyValueData *pkvd ); + void (*pfnSave) ( edict_t *pent, SAVERESTOREDATA *pSaveData ); + int (*pfnRestore) ( edict_t *pent, SAVERESTOREDATA *pSaveData, int globalEntity ); + void (*pfnSetAbsBox) ( edict_t *pent ); + + void (*pfnSaveWriteFields) ( SAVERESTOREDATA *, const char *, void *, TYPEDESCRIPTION *, int ); + void (*pfnSaveReadFields) ( SAVERESTOREDATA *, const char *, void *, TYPEDESCRIPTION *, int ); + + void (*pfnSaveGlobalState) ( SAVERESTOREDATA * ); + void (*pfnRestoreGlobalState) ( SAVERESTOREDATA * ); + void (*pfnResetGlobalState) ( void ); + + qboolean (*pfnClientConnect) ( edict_t *pEntity, const char *pszName, const char *pszAddress, char szRejectReason[ 128 ] ); + + void (*pfnClientDisconnect) ( edict_t *pEntity ); + void (*pfnClientKill) ( edict_t *pEntity ); + void (*pfnClientPutInServer) ( edict_t *pEntity ); + void (*pfnClientCommand) ( edict_t *pEntity ); + void (*pfnClientUserInfoChanged)( edict_t *pEntity, char *infobuffer ); + + void (*pfnServerActivate) ( edict_t *pEdictList, int edictCount, int clientMax ); + void (*pfnServerDeactivate) ( void ); + + void (*pfnPlayerPreThink) ( edict_t *pEntity ); + void (*pfnPlayerPostThink) ( edict_t *pEntity ); + + void (*pfnStartFrame) ( void ); + void (*pfnParmsNewLevel) ( void ); + void (*pfnParmsChangeLevel) ( void ); + + // Returns string describing current .dll. E.g., TeamFotrress 2, Half-Life + const char *(*pfnGetGameDescription)( void ); + + // Notify dll about a player customization. + void (*pfnPlayerCustomization) ( edict_t *pEntity, customization_t *pCustom ); + + // Spectator funcs + void (*pfnSpectatorConnect) ( edict_t *pEntity ); + void (*pfnSpectatorDisconnect) ( edict_t *pEntity ); + void (*pfnSpectatorThink) ( edict_t *pEntity ); + + // Notify game .dll that engine is going to shut down. Allows mod authors to set a breakpoint. + void (*pfnSys_Error) ( const char *error_string ); + + void (*pfnPM_Move) ( struct playermove_s *ppmove, qboolean server ); + void (*pfnPM_Init) ( struct playermove_s *ppmove ); + char (*pfnPM_FindTextureType)( char *name ); + void (*pfnSetupVisibility)( struct edict_s *pViewEntity, struct edict_s *pClient, unsigned char **pvs, unsigned char **pas ); + void (*pfnUpdateClientData) ( const struct edict_s *ent, int sendweapons, struct clientdata_s *cd ); + int (*pfnAddToFullPack)( struct entity_state_s *state, int e, edict_t *ent, edict_t *host, int hostflags, int player, unsigned char *pSet ); + void (*pfnCreateBaseline) ( int player, int eindex, struct entity_state_s *baseline, struct edict_s *entity, int playermodelindex, vec3_t player_mins, vec3_t player_maxs ); + void (*pfnRegisterEncoders) ( void ); + int (*pfnGetWeaponData) ( struct edict_s *player, struct weapon_data_s *info ); + + void (*pfnCmdStart) ( const edict_t *player, const struct usercmd_s *cmd, unsigned int random_seed ); + void (*pfnCmdEnd) ( const edict_t *player ); + + // Return 1 if the packet is valid. Set response_buffer_size if you want to send a response packet. Incoming, it holds the max + // size of the response_buffer, so you must zero it out if you choose not to respond. + int (*pfnConnectionlessPacket ) ( const struct netadr_s *net_from_, const char *args, char *response_buffer, int *response_buffer_size ); + + // Enumerates player hulls. Returns 0 if the hull number doesn't exist, 1 otherwise + int (*pfnGetHullBounds) ( int hullnumber, float *mins, float *maxs ); + + // Create baselines for certain "unplaced" items. + void (*pfnCreateInstancedBaselines) ( void ); + + // One of the pfnForceUnmodified files failed the consistency check for the specified player + // Return 0 to allow the client to continue, 1 to force immediate disconnection ( with an optional disconnect message of up to 256 characters ) + int (*pfnInconsistentFile)( const struct edict_s *player, const char *filename, char *disconnect_message ); + + // The game .dll should return 1 if lag compensation should be allowed ( could also just set + // the sv_unlag cvar. + // Most games right now should return 0, until client-side weapon prediction code is written + // and tested for them. + int (*pfnAllowLagCompensation)( void ); +} DLL_FUNCTIONS; + +extern DLL_FUNCTIONS gEntityInterface; + +// Current version. +#define NEW_DLL_FUNCTIONS_VERSION 1 + +typedef struct +{ + // Called right before the object's memory is freed. + // Calls its destructor. + void (*pfnOnFreeEntPrivateData)(edict_t *pEnt); + void (*pfnGameShutdown)(void); + int (*pfnShouldCollide)( edict_t *pentTouched, edict_t *pentOther ); + void (*pfnCvarValue)( const edict_t *pEnt, const char *value ); + void (*pfnCvarValue2)( const edict_t *pEnt, int requestID, const char *cvarName, const char *value ); +} NEW_DLL_FUNCTIONS; +typedef int(*NEW_DLL_FUNCTIONS_FN)(NEW_DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion); + +// Pointers will be null if the game DLL doesn't support this API. +extern NEW_DLL_FUNCTIONS gNewDLLFunctions; + +typedef int(*APIFUNCTION)(DLL_FUNCTIONS *pFunctionTable, int interfaceVersion); +typedef int(*APIFUNCTION2)(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion); diff --git a/dep/rehlsdk/engine/hookchains.h b/dep/rehlsdk/engine/hookchains.h new file mode 100644 index 0000000..197b8a3 --- /dev/null +++ b/dep/rehlsdk/engine/hookchains.h @@ -0,0 +1,80 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +template +class IHookChain { +protected: + virtual ~IHookChain() {} + +public: + virtual t_ret callNext(t_args... args) = 0; + virtual t_ret callOriginal(t_args... args) = 0; +}; + +template +class IVoidHookChain +{ +protected: + virtual ~IVoidHookChain() {} + +public: + virtual void callNext(t_args... args) = 0; + virtual void callOriginal(t_args... args) = 0; +}; + +// Specifies priorities for hooks call order in the chain. +// For equal priorities first registered hook will be called first. +enum HookChainPriority +{ + HC_PRIORITY_UNINTERRUPTABLE = 255, // Hook will be called before other hooks. + HC_PRIORITY_HIGH = 192, // Hook will be called before hooks with default priority. + HC_PRIORITY_DEFAULT = 128, // Default hook call priority. + HC_PRIORITY_MEDIUM = 64, // Hook will be called after hooks with default priority. + HC_PRIORITY_LOW = 0, // Hook will be called after all other hooks. +}; + +// Hook chain registry(for hooks [un]registration) +template +class IHookChainRegistry { +public: + typedef t_ret(*hookfunc_t)(IHookChain*, t_args...); + + virtual void registerHook(hookfunc_t hook, int priority = HC_PRIORITY_DEFAULT) = 0; + virtual void unregisterHook(hookfunc_t hook) = 0; +}; + +// Hook chain registry(for hooks [un]registration) +template +class IVoidHookChainRegistry { +public: + typedef void(*hookfunc_t)(IVoidHookChain*, t_args...); + + virtual void registerHook(hookfunc_t hook, int priority = HC_PRIORITY_DEFAULT) = 0; + virtual void unregisterHook(hookfunc_t hook) = 0; +}; diff --git a/dep/rehlsdk/engine/keydefs.h b/dep/rehlsdk/engine/keydefs.h new file mode 100644 index 0000000..ef9b2fc --- /dev/null +++ b/dep/rehlsdk/engine/keydefs.h @@ -0,0 +1,131 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +// keydefs.h +#ifndef KEYDEFS_H +#define KEYDEFS_H +#ifdef _WIN32 +#ifndef __MINGW32__ +#pragma once +#endif /* not __MINGW32__ */ +#endif + +// +// these are the key numbers that should be passed to Key_Event +// +#define K_TAB 9 +#define K_ENTER 13 +#define K_ESCAPE 27 +#define K_SPACE 32 + +// normal keys should be passed as lowercased ascii + +#define K_BACKSPACE 127 +#define K_UPARROW 128 +#define K_DOWNARROW 129 +#define K_LEFTARROW 130 +#define K_RIGHTARROW 131 + +#define K_ALT 132 +#define K_CTRL 133 +#define K_SHIFT 134 +#define K_F1 135 +#define K_F2 136 +#define K_F3 137 +#define K_F4 138 +#define K_F5 139 +#define K_F6 140 +#define K_F7 141 +#define K_F8 142 +#define K_F9 143 +#define K_F10 144 +#define K_F11 145 +#define K_F12 146 +#define K_INS 147 +#define K_DEL 148 +#define K_PGDN 149 +#define K_PGUP 150 +#define K_HOME 151 +#define K_END 152 + +#define K_KP_HOME 160 +#define K_KP_UPARROW 161 +#define K_KP_PGUP 162 +#define K_KP_LEFTARROW 163 +#define K_KP_5 164 +#define K_KP_RIGHTARROW 165 +#define K_KP_END 166 +#define K_KP_DOWNARROW 167 +#define K_KP_PGDN 168 +#define K_KP_ENTER 169 +#define K_KP_INS 170 +#define K_KP_DEL 171 +#define K_KP_SLASH 172 +#define K_KP_MINUS 173 +#define K_KP_PLUS 174 +#define K_CAPSLOCK 175 + + +// +// joystick buttons +// +#define K_JOY1 203 +#define K_JOY2 204 +#define K_JOY3 205 +#define K_JOY4 206 + +// +// aux keys are for multi-buttoned joysticks to generate so they can use +// the normal binding process +// +#define K_AUX1 207 +#define K_AUX2 208 +#define K_AUX3 209 +#define K_AUX4 210 +#define K_AUX5 211 +#define K_AUX6 212 +#define K_AUX7 213 +#define K_AUX8 214 +#define K_AUX9 215 +#define K_AUX10 216 +#define K_AUX11 217 +#define K_AUX12 218 +#define K_AUX13 219 +#define K_AUX14 220 +#define K_AUX15 221 +#define K_AUX16 222 +#define K_AUX17 223 +#define K_AUX18 224 +#define K_AUX19 225 +#define K_AUX20 226 +#define K_AUX21 227 +#define K_AUX22 228 +#define K_AUX23 229 +#define K_AUX24 230 +#define K_AUX25 231 +#define K_AUX26 232 +#define K_AUX27 233 +#define K_AUX28 234 +#define K_AUX29 235 +#define K_AUX30 236 +#define K_AUX31 237 +#define K_AUX32 238 +#define K_MWHEELDOWN 239 +#define K_MWHEELUP 240 + +#define K_PAUSE 255 + +// +// mouse buttons generate virtual keys +// +#define K_MOUSE1 241 +#define K_MOUSE2 242 +#define K_MOUSE3 243 +#define K_MOUSE4 244 +#define K_MOUSE5 245 + +#endif // KEYDEFS_H diff --git a/dep/rehlsdk/engine/maintypes.h b/dep/rehlsdk/engine/maintypes.h new file mode 100644 index 0000000..f55bac9 --- /dev/null +++ b/dep/rehlsdk/engine/maintypes.h @@ -0,0 +1,70 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef MAINTYPES_H +#define MAINTYPES_H +#ifdef _WIN32 +#pragma once +#endif + +#include "osconfig.h" +#include "mathlib.h" + +// Has no references on server side. +#define NOXREF +// Function body is not implemented. +#define NOBODY +// Function is not tested at all. +#define UNTESTED + +#define CONST_INTEGER_AS_STRING(x) #x //Wraps the integer in quotes, allowing us to form constant strings with it +#define __HACK_LINE_AS_STRING__(x) CONST_INTEGER_AS_STRING(x) //__LINE__ can only be converted to an actual number by going through this, otherwise the output is literally "__LINE__" +#define __LINE__AS_STRING __HACK_LINE_AS_STRING__(__LINE__) //Gives you the line number in constant string form + +#if defined _MSC_VER || defined __INTEL_COMPILER +#define NOXREFCHECK int __retAddr; __asm { __asm mov eax, [ebp + 4] __asm mov __retAddr, eax }; Sys_Error("[NOXREFCHECK]: %s: (" __FILE__ ":" __LINE__AS_STRING ") NOXREF, but called from 0x%.08x", __func__, __retAddr) +#else +// For EBP based stack (older gcc) (uncomment version apropriate for your compiler) +//#define NOXREFCHECK int __retAddr; __asm__ __volatile__("movl 4(%%ebp), %%eax;" "movl %%eax, %0":"=r"(__retAddr)::"%eax"); Sys_Error("[NOXREFCHECK]: %s: (" __FILE__ ":" __LINE__AS_STRING ") NOXREF, but called from 0x%.08x", __func__, __retAddr); +// For ESP based stack (newer gcc) (uncomment version apropriate for your compiler) +#define NOXREFCHECK int __retAddr; __asm__ __volatile__("movl 16(%%esp), %%eax;" "movl %%eax, %0":"=r"(__retAddr)::"%eax"); Sys_Error("[NOXREFCHECK]: %s: (" __FILE__ ":" __LINE__AS_STRING ") NOXREF, but called from 0x%.08x", __func__, __retAddr); +#endif + +#define BIT(n) (1<<(n)) + +// From engine/pr_comp.h; +typedef unsigned int string_t; + +// From engine/server.h +typedef enum sv_delta_s +{ + sv_packet_nodelta, + sv_packet_delta, +} sv_delta_t; + +#endif // MAINTYPES_H diff --git a/dep/rehlsdk/engine/model.h b/dep/rehlsdk/engine/model.h new file mode 100644 index 0000000..354a815 --- /dev/null +++ b/dep/rehlsdk/engine/model.h @@ -0,0 +1,409 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#include "const.h" +#include "modelgen.h" +#include "spritegn.h" +#include "bspfile.h" +#include "crc.h" +#include "com_model.h" +#include "commonmacros.h" + +// header +#define ALIAS_MODEL_VERSION 0x006 +#define IDPOLYHEADER MAKEID('I', 'D', 'P', 'O') // little-endian "IDPO" + +#define MAX_LBM_HEIGHT 480 +#define MAX_ALIAS_MODEL_VERTS 2000 + +#define SURF_PLANEBACK 2 +#define SURF_DRAWSKY 4 +#define SURF_DRAWSPRITE 8 +#define SURF_DRAWTURB 0x10 +#define SURF_DRAWTILED 0x20 +#define SURF_DRAWBACKGROUND 0x40 + +#define MAX_MODEL_NAME 64 +#define MIPLEVELS 4 +#define NUM_AMBIENTS 4 // automatic ambient sounds +#define MAXLIGHTMAPS 4 +#define MAX_KNOWN_MODELS 1024 + +typedef struct mvertex_s +{ + vec3_t position; +} mvertex_t; + +typedef struct mplane_s +{ + vec3_t normal; // surface normal + float dist; // closest appoach to origin + byte type; // for texture axis selection and fast side tests + byte signbits; // signx + signy<<1 + signz<<1 + byte pad[2]; +} mplane_t; + +typedef struct texture_s +{ + char name[16]; + unsigned width, height; + +#if !defined(SWDS) && !defined(HLTV) + int gl_texturenum; + struct msurface_s * texturechain; +#endif + + int anim_total; // total tenths in sequence ( 0 = no) + int anim_min, anim_max; // time for this frame min <=time< max + struct texture_s *anim_next; // in the animation sequence + struct texture_s *alternate_anims; // bmodels in frame 1 use these + unsigned offsets[MIPLEVELS]; // four mip maps stored + +#if defined(SWDS) || defined(HLTV) + unsigned paloffset; +#else + byte *pPal; +#endif + +} texture_t; + +typedef struct medge_s +{ + unsigned short v[2]; + unsigned int cachededgeoffset; +} medge_t; + +typedef struct mtexinfo_s +{ + float vecs[2][4]; // [s/t] unit vectors in world space. + // [i][3] is the s/t offset relative to the origin. + // s or t = dot(3Dpoint,vecs[i])+vecs[i][3] + float mipadjust; // ?? mipmap limits for very small surfaces + texture_t *texture; + int flags; // sky or slime, no lightmap or 256 subdivision +} mtexinfo_t; +#define TEX_SPECIAL 1 // sky or slime, no lightmap or 256 subdivision + +typedef struct msurface_s msurface_t; +typedef struct decal_s decal_t; + +// JAY: Compress this as much as possible +struct decal_s +{ + decal_t *pnext; // linked list for each surface + msurface_t *psurface; // Surface id for persistence / unlinking + short dx; // Offsets into surface texture (in texture coordinates, so we don't need floats) + short dy; + short texture; // Decal texture + byte scale; // Pixel scale + byte flags; // Decal flags + + short entityIndex; // Entity this is attached to +}; + +struct msurface_s +{ + int visframe; // should be drawn when node is crossed + + int dlightframe; // last frame the surface was checked by an animated light + int dlightbits; // dynamically generated. Indicates if the surface illumination + // is modified by an animated light. + + mplane_t *plane; // pointer to shared plane + int flags; // see SURF_ #defines + + int firstedge; // look up in model->surfedges[], negative numbers + int numedges; // are backwards edges + + // surface generation data + struct surfcache_s *cachespots[MIPLEVELS]; + + short texturemins[2]; // smallest s/t position on the surface. + short extents[2]; // ?? s/t texture size, 1..256 for all non-sky surfaces + + mtexinfo_t *texinfo; + + // lighting info + byte styles[MAXLIGHTMAPS]; // index into d_lightstylevalue[] for animated lights + // no one surface can be effected by more than 4 + // animated lights. + color24 *samples; + + decal_t *pdecals; +}; + +typedef struct mnode_s +{ + // common with leaf + int contents; // 0, to differentiate from leafs + int visframe; // node needs to be traversed if current + + short minmaxs[6]; // for bounding box culling + + struct mnode_s *parent; + + // node specific + mplane_t *plane; + struct mnode_s *children[2]; + + unsigned short firstsurface; + unsigned short numsurfaces; +} mnode_t; + +typedef struct mleaf_s +{ + // common with node + int contents; // wil be a negative contents number + int visframe; // node needs to be traversed if current + + short minmaxs[6]; // for bounding box culling + + struct mnode_s *parent; + + // leaf specific + byte *compressed_vis; + struct efrag_s *efrags; + + msurface_t **firstmarksurface; + int nummarksurfaces; + int key; // BSP sequence number for leaf's contents + byte ambient_sound_level[NUM_AMBIENTS]; +} mleaf_t; + +typedef struct hull_s +{ + dclipnode_t *clipnodes; + mplane_t *planes; + int firstclipnode; + int lastclipnode; + vec3_t clip_mins, clip_maxs; +} hull_t; + +typedef struct mspriteframe_t +{ + int width; + int height; + void *pcachespot; + float up, down, left, right; + byte pixels[4]; +} mspriteframe_s; + +typedef struct mspritegroup_s +{ + int numframes; + float *intervals; + mspriteframe_t *frames[1]; +} mspritegroup_t; + +typedef struct mspriteframedesc_s +{ + spriteframetype_t type; + mspriteframe_t *frameptr; +} mspriteframedesc_t; + +typedef struct msprite_s +{ + short int type; + short int texFormat; + int maxwidth, maxheight; + int numframes; + int paloffset; + float beamlength; + void *cachespot; + mspriteframedesc_t frames[1]; +} msprite_t; + +typedef struct maliasframedesc_s +{ + aliasframetype_t type; + trivertx_t bboxmin, bboxmax; + int frame; + char name[16]; +} maliasframedesc_t; + +typedef struct maliasskindesc_s +{ + aliasskintype_t type; + void *pcachespot; + int skin; +} maliasskindesc_t; + +typedef struct maliasgroupframedesc_s +{ + trivertx_t bboxmin, bboxmax; + int frame; +} maliasgroupframedesc_t; + +typedef struct maliasgroup_s +{ + int numframes; + int intervals; + maliasgroupframedesc_t frames[1]; +} maliasgroup_t; + +typedef struct maliasskingroup_s +{ + int numskins; + int intervals; + maliasskindesc_t skindescs[1]; +} maliasskingroup_t; + +typedef struct mtriangle_s +{ + int facesfront; + int vertindex[3]; +} mtriangle_t; + +typedef struct aliashdr_s +{ + int model; + int stverts; + int skindesc; + int triangles; + int palette; + maliasframedesc_t frames[1]; +} aliashdr_t; + +typedef enum modtype_e +{ + mod_bad = -1, + mod_brush, + mod_sprite, + mod_alias, + mod_studio, +} modtype_t; + +typedef struct model_s +{ + char name[MAX_MODEL_NAME]; + + int needload; // bmodels and sprites don't cache normally + + modtype_t type; + int numframes; + synctype_t synctype; + + int flags; + + // + // volume occupied by the model + // + vec3_t mins, maxs; + float radius; + + // + // brush model + // + int firstmodelsurface, nummodelsurfaces; + + int numsubmodels; + dmodel_t *submodels; + + int numplanes; + mplane_t *planes; + + int numleafs; // number of visible leafs, not counting 0 + struct mleaf_s *leafs; + + int numvertexes; + mvertex_t *vertexes; + + int numedges; + medge_t *edges; + + int numnodes; + mnode_t *nodes; + + int numtexinfo; + mtexinfo_t *texinfo; + + int numsurfaces; + msurface_t *surfaces; + + int numsurfedges; + int *surfedges; + + int numclipnodes; + dclipnode_t *clipnodes; + + int nummarksurfaces; + msurface_t **marksurfaces; + + hull_t hulls[MAX_MAP_HULLS]; + + int numtextures; + texture_t **textures; + + byte *visdata; + + color24 *lightdata; + + char *entities; + + // + // additional model data + // + cache_user_t cache; // only access through Mod_Extradata +} model_t; + +typedef struct cachepic_s +{ + char name[64]; + cache_user_t cache; +} cachepic_t; + +typedef struct cachewad_s cachewad_t; + +typedef void(*PFNCACHE)(cachewad_t *, unsigned char *); + +typedef struct cachewad_s +{ + char *name; + cachepic_t *cache; + int cacheCount; + int cacheMax; + struct lumpinfo_s *lumps; + int lumpCount; + int cacheExtra; + PFNCACHE pfnCacheBuild; + int numpaths; + char **basedirs; + int *lumppathindices; +#ifndef SWDS + int tempWad; +#endif // SWDS +} cachewad_t; + +typedef struct mod_known_info_s +{ + qboolean shouldCRC; + qboolean firstCRCDone; + CRC32_t initialCRC; +} mod_known_info_t; + diff --git a/dep/rehlsdk/engine/modelgen.h b/dep/rehlsdk/engine/modelgen.h new file mode 100644 index 0000000..48fd9b8 --- /dev/null +++ b/dep/rehlsdk/engine/modelgen.h @@ -0,0 +1,128 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef MODELGEN_H +#define MODELGEN_H +#ifdef _WIN32 +#pragma once +#endif + +typedef enum synctype_e +{ + ST_SYNC = 0, + ST_RAND = 1, +} synctype_t; + +typedef enum aliasframetype_s +{ + ALIAS_SINGLE = 0, + ALIAS_GROUP = 1, +} aliasframetype_t; + +typedef enum aliasskintype_s +{ + ALIAS_SKIN_SINGLE = 0, + ALIAS_SKIN_GROUP = 1, +} aliasskintype_t; + +typedef struct mdl_s +{ + int ident; + int version; + vec3_t scale; + vec3_t scale_origin; + float boundingradius; + vec3_t eyeposition; + int numskins; + int skinwidth; + int skinheight; + int numverts; + int numtris; + int numframes; + synctype_t synctype; + int flags; + float size; +} mdl_t; + +typedef struct stvert_s +{ + int onseam; + int s; + int t; +} stvert_t; + +typedef struct dtriangle_s +{ + int facesfront; + int vertindex[3]; +} dtriangle_t; + +typedef struct trivertx_s +{ + byte v[3]; + byte lightnormalindex; +} trivertx_t; + +typedef struct daliasframe_s +{ + trivertx_t bboxmin, bboxmax; + char name[16]; +} daliasframe_t; + +typedef struct daliasgroup_s +{ + int numframes; + trivertx_t bboxmin, bboxmax; +} daliasgroup_t; + +typedef struct daliasskingroup_s +{ + int numskins; +} daliasskingroup_t; + +typedef struct daliasinterval_s +{ + float interval; +} daliasinterval_t; + +typedef struct daliasskininterval_s +{ + float interval; +} daliasskininterval_t; + +typedef struct daliasframetype_s +{ + aliasframetype_t type; +} daliasframetype_t; + +typedef struct daliasskintype_s +{ + aliasskintype_t type; +} daliasskintype_t; + +#endif // MODELGEN_H diff --git a/dep/rehlsdk/engine/osconfig.h b/dep/rehlsdk/engine/osconfig.h new file mode 100644 index 0000000..9c96e0c --- /dev/null +++ b/dep/rehlsdk/engine/osconfig.h @@ -0,0 +1,221 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef _OSCONFIG_H +#define _OSCONFIG_H + +#ifdef _WIN32 // WINDOWS + #pragma warning(disable : 4005) +#endif // _WIN32 + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#ifdef _WIN32 // WINDOWS + #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers + #include + #include + #include // for support IPX + #define PSAPI_VERSION 1 + #include + #include + #include + #include + #include + #include +#else // _WIN32 + #include + #include + //#include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#endif // _WIN32 + +#include +#include +#include +#include + +#include +#include + + +#ifdef _WIN32 // WINDOWS + // Define __func__ on VS less than 2015 + #if _MSC_VER < 1900 + #define __func__ __FUNCTION__ + #endif + + #define _CRT_SECURE_NO_WARNINGS + #define WIN32_LEAN_AND_MEAN + + #ifndef CDECL + #define CDECL __cdecl + #endif + #define FASTCALL __fastcall + #define STDCALL __stdcall + #define HIDDEN + #define FORCEINLINE __forceinline + #define NOINLINE __declspec(noinline) + #define ALIGN16 __declspec(align(16)) + #define NORETURN __declspec(noreturn) + #define FORCE_STACK_ALIGN + #define FUNC_TARGET(x) + + #define __builtin_bswap16 _byteswap_ushort + #define __builtin_bswap32 _byteswap_ulong + #define __builtin_bswap64 _byteswap_uint64 + + //inline bool SOCKET_FIONBIO(SOCKET s, int m) { return (ioctlsocket(s, FIONBIO, (u_long*)&m) == 0); } + //inline int SOCKET_MSGLEN(SOCKET s, u_long& r) { return ioctlsocket(s, FIONREAD, (u_long*)&r); } + typedef int socklen_t; + #define SOCKET_FIONBIO(s, m) ioctlsocket(s, FIONBIO, (u_long*)&m) + #define SOCKET_MSGLEN(s, r) ioctlsocket(s, FIONREAD, (u_long*)&r) + #define SIN_GET_ADDR(saddr, r) r = (saddr)->S_un.S_addr + #define SIN_SET_ADDR(saddr, r) (saddr)->S_un.S_addr = (r) + #define SOCKET_CLOSE(s) closesocket(s) + #define SOCKET_AGAIN() (WSAGetLastError() == WSAEWOULDBLOCK) + + inline void* sys_allocmem(unsigned int size) { + return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE); + } + + inline void sys_freemem(void* ptr, unsigned int size) { + VirtualFree(ptr, 0, MEM_RELEASE); + } +#else // _WIN32 + #ifndef PAGESIZE + #define PAGESIZE 4096 + #endif + #define ALIGN(addr) (size_t)((size_t)addr & ~(PAGESIZE-1)) + #define ARRAYSIZE(p) (sizeof(p)/sizeof(p[0])) + + #define _MAX_FNAME NAME_MAX + #define MAX_PATH 260 + + typedef void *HWND; + + typedef unsigned long DWORD; + typedef unsigned short WORD; + typedef unsigned int UNINT32; + + #define FASTCALL + #define CDECL __attribute__ ((cdecl)) + #define STDCALL __attribute__ ((stdcall)) + #define HIDDEN __attribute__((visibility("hidden"))) + #define FORCEINLINE inline + #define NOINLINE __attribute__((noinline)) + #define ALIGN16 __attribute__((aligned(16))) + #define NORETURN __attribute__((noreturn)) + #define FORCE_STACK_ALIGN __attribute__((force_align_arg_pointer)) + +#if defined __INTEL_COMPILER + #define FUNC_TARGET(x) + + #define __builtin_bswap16 _bswap16 + #define __builtin_bswap32 _bswap + #define __builtin_bswap64 _bswap64 +#else + #define FUNC_TARGET(x) __attribute__((target(x))) +#endif // __INTEL_COMPILER + + //inline bool SOCKET_FIONBIO(SOCKET s, int m) { return (ioctl(s, FIONBIO, (int*)&m) == 0); } + //inline int SOCKET_MSGLEN(SOCKET s, u_long& r) { return ioctl(s, FIONREAD, (int*)&r); } + typedef int SOCKET; + #define INVALID_SOCKET (SOCKET)(~0) + #define SOCKET_FIONBIO(s, m) ioctl(s, FIONBIO, (char*)&m) + #define SOCKET_MSGLEN(s, r) ioctl(s, FIONREAD, (char*)&r) + #define SIN_GET_ADDR(saddr, r) r = (saddr)->s_addr + #define SIN_SET_ADDR(saddr, r) (saddr)->s_addr = (r) + #define SOCKET_CLOSE(s) close(s) + #define SOCKET_AGAIN() (errno == EAGAIN) + #define SOCKET_ERROR -1 + + inline int ioctlsocket(int fd, int cmd, unsigned int *argp) { return ioctl(fd, cmd, argp); } + inline int closesocket(int fd) { return close(fd); } + inline int WSAGetLastError() { return errno; } + + inline void* sys_allocmem(unsigned int size) { + return mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + } + inline void sys_freemem(void* ptr, unsigned int size) { + munmap(ptr, size); + } + + #define WSAENOPROTOOPT ENOPROTOOPT + + #ifndef FALSE + #define FALSE 0 + #endif + #ifndef TRUE + #define TRUE 1 + #endif +#endif // _WIN32 + +#ifdef _WIN32 + static const bool __isWindows = true; + static const bool __isLinux = false; +#else + static const bool __isWindows = false; + static const bool __isLinux = true; +#endif + +#define EXT_FUNC FORCE_STACK_ALIGN + +// Used to obtain the string name of a variable. +#define nameof_variable(name) template_nameof_variable(name, #name) +template const char* template_nameof_variable(const T& /*validate_type*/, const char* name) { return name; } + +#endif // _OSCONFIG_H diff --git a/dep/rehlsdk/engine/pr_dlls.h b/dep/rehlsdk/engine/pr_dlls.h new file mode 100644 index 0000000..d7b72c1 --- /dev/null +++ b/dep/rehlsdk/engine/pr_dlls.h @@ -0,0 +1,51 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "maintypes.h" +#include "eiface.h" + +const int MAX_EXTENSION_DLL = 50; + +typedef struct functiontable_s +{ + uint32 pFunction; + char *pFunctionName; +} functiontable_t; + +typedef struct extensiondll_s +{ + void *lDLLHandle; + functiontable_t *functionTable; + int functionCount; +} extensiondll_t; + +typedef void(*ENTITYINIT)(struct entvars_s *); +typedef void(*DISPATCHFUNCTION)(struct entvars_s *, void *); +typedef void(*FIELDIOFUNCTION)(SAVERESTOREDATA *, const char *, void *, TYPEDESCRIPTION *, int); diff --git a/dep/rehlsdk/engine/progdefs.h b/dep/rehlsdk/engine/progdefs.h new file mode 100644 index 0000000..e27dc50 --- /dev/null +++ b/dep/rehlsdk/engine/progdefs.h @@ -0,0 +1,224 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef PROGDEFS_H +#define PROGDEFS_H +#ifdef _WIN32 +#pragma once +#endif + +typedef struct globalvars_s +{ + float time; + float frametime; + float force_retouch; + string_t mapname; + string_t startspot; + float deathmatch_; + float coop_; + float teamplay; + float serverflags; + float found_secrets; + vec3_t v_forward; + vec3_t v_up; + vec3_t v_right; + float trace_allsolid; + float trace_startsolid; + float trace_fraction; + vec3_t trace_endpos; + vec3_t trace_plane_normal; + float trace_plane_dist; + edict_t *trace_ent; + float trace_inopen; + float trace_inwater; + int trace_hitgroup; + int trace_flags; + int msg_entity; + int cdAudioTrack; + int maxClients; + int maxEntities; + const char *pStringBase; + + void *pSaveData; + vec3_t vecLandmarkOffset; +} globalvars_t; + + +typedef struct entvars_s +{ + string_t classname; + string_t globalname; + + vec3_t origin; + vec3_t oldorigin; + vec3_t velocity; + vec3_t basevelocity; + vec3_t clbasevelocity; // Base velocity that was passed in to server physics so + // client can predict conveyors correctly. Server zeroes it, so we need to store here, too. + vec3_t movedir; + + vec3_t angles; // Model angles + vec3_t avelocity; // angle velocity (degrees per second) + vec3_t punchangle; // auto-decaying view angle adjustment + vec3_t v_angle; // Viewing angle (player only) + + // For parametric entities + vec3_t endpos; + vec3_t startpos; + float impacttime; + float starttime; + + int fixangle; // 0:nothing, 1:force view angles, 2:add avelocity + float idealpitch; + float pitch_speed; + float ideal_yaw; + float yaw_speed; + + int modelindex; + string_t model; + + int viewmodel; // player's viewmodel + int weaponmodel; // what other players see + + vec3_t absmin; // BB max translated to world coord + vec3_t absmax; // BB max translated to world coord + vec3_t mins; // local BB min + vec3_t maxs; // local BB max + vec3_t size; // maxs - mins + + float ltime; + float nextthink; + + int movetype; + int solid; + + int skin; + int body; // sub-model selection for studiomodels + int effects; + + float gravity; // % of "normal" gravity + float friction; // inverse elasticity of MOVETYPE_BOUNCE + + int light_level; + + int sequence; // animation sequence + int gaitsequence; // movement animation sequence for player (0 for none) + float frame; // % playback position in animation sequences (0..255) + float animtime; // world time when frame was set + float framerate; // animation playback rate (-8x to 8x) + byte controller[4]; // bone controller setting (0..255) + byte blending[2]; // blending amount between sub-sequences (0..255) + + float scale; // sprite rendering scale (0..255) + + int rendermode; + float renderamt; + vec3_t rendercolor; + int renderfx; + + float health; + float frags; + int weapons; // bit mask for available weapons + float takedamage; + + int deadflag; + vec3_t view_ofs; // eye position + + int button; + int impulse; + + edict_t *chain; // Entity pointer when linked into a linked list + edict_t *dmg_inflictor; + edict_t *enemy; + edict_t *aiment; // entity pointer when MOVETYPE_FOLLOW + edict_t *owner; + edict_t *groundentity; + + int spawnflags; + int flags; + + int colormap; // lowbyte topcolor, highbyte bottomcolor + int team; + + float max_health; + float teleport_time; + float armortype; + float armorvalue; + int waterlevel; + int watertype; + + string_t target; + string_t targetname; + string_t netname; + string_t message; + + float dmg_take; + float dmg_save; + float dmg; + float dmgtime; + + string_t noise; + string_t noise1; + string_t noise2; + string_t noise3; + + float speed; + float air_finished; + float pain_finished; + float radsuit_finished; + + edict_t *pContainingEntity; + + int playerclass; + float maxspeed; + + float fov; + int weaponanim; + + int pushmsec; + + int bInDuck; + int flTimeStepSound; + int flSwimTime; + int flDuckTime; + int iStepLeft; + float flFallVelocity; + + int gamestate; + + int oldbuttons; + + int groupinfo; + + // For mods + int iuser1; + int iuser2; + int iuser3; + int iuser4; + float fuser1; + float fuser2; + float fuser3; + float fuser4; + vec3_t vuser1; + vec3_t vuser2; + vec3_t vuser3; + vec3_t vuser4; + edict_t *euser1; + edict_t *euser2; + edict_t *euser3; + edict_t *euser4; +} entvars_t; + + +#endif // PROGDEFS_H diff --git a/dep/rehlsdk/engine/progs.h b/dep/rehlsdk/engine/progs.h new file mode 100644 index 0000000..bd04e8e --- /dev/null +++ b/dep/rehlsdk/engine/progs.h @@ -0,0 +1,82 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef PROGS_H +#define PROGS_H + +#include "progdefs.h" + +// 16 simultaneous events, max +#define MAX_EVENT_QUEUE 64 + +#define DEFAULT_EVENT_RESENDS 1 + +#include "event_flags.h" + +typedef struct event_info_s event_info_t; + +#include "event_args.h" + +struct event_info_s +{ + unsigned short index; // 0 implies not in use + + short packet_index; // Use data from state info for entity in delta_packet . -1 implies separate info based on event + // parameter signature + short entity_index; // The edict this event is associated with + + float fire_time; // if non-zero, the time when the event should be fired ( fixed up on the client ) + + event_args_t args; + +// CLIENT ONLY + int flags; // Reliable or not, etc. + +}; + +typedef struct event_state_s event_state_t; + +struct event_state_s +{ + struct event_info_s ei[ MAX_EVENT_QUEUE ]; +}; + +#if !defined( ENTITY_STATEH ) +#include "entity_state.h" +#endif + +#if !defined( EDICT_H ) +#include "edict.h" +#endif + +#define STRUCT_FROM_LINK(l,t,m) ((t *)((byte *)l - offsetof(t, m))) +#define EDICT_FROM_AREA(l) STRUCT_FROM_LINK(l,edict_t,area) + +//============================================================================ + +extern char *pr_strings; +extern globalvars_t gGlobalVariables; + +//============================================================================ + +edict_t *ED_Alloc (void); +void ED_Free (edict_t *ed); +void ED_LoadFromFile (char *data); + +edict_t *EDICT_NUM(int n); +int NUM_FOR_EDICT(const edict_t *e); + +#define PROG_TO_EDICT(e) ((edict_t *)((byte *)sv.edicts + e)) + +#endif // PROGS_H diff --git a/dep/rehlsdk/engine/rehlds_api.h b/dep/rehlsdk/engine/rehlds_api.h new file mode 100644 index 0000000..ba752f6 --- /dev/null +++ b/dep/rehlsdk/engine/rehlds_api.h @@ -0,0 +1,387 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once +#include "archtypes.h" +#include "cmd_rehlds.h" +#include "rehlds_interfaces.h" +#include "hookchains.h" +#include "FlightRecorder.h" +#include "interface.h" +#include "model.h" +#include "ObjectList.h" +#include "pr_dlls.h" + +#define REHLDS_API_VERSION_MAJOR 3 +#define REHLDS_API_VERSION_MINOR 10 + +//Steam_NotifyClientConnect hook +typedef IHookChain IRehldsHook_Steam_NotifyClientConnect; +typedef IHookChainRegistry IRehldsHookRegistry_Steam_NotifyClientConnect; + +//SV_ConnectClient hook +typedef IVoidHookChain<> IRehldsHook_SV_ConnectClient; +typedef IVoidHookChainRegistry<> IRehldsHookRegistry_SV_ConnectClient; + +//SV_GetIDString hook +typedef IHookChain IRehldsHook_SV_GetIDString; +typedef IHookChainRegistry IRehldsHookRegistry_SV_GetIDString; + +//SV_SendServerinfo hook +typedef IVoidHookChain IRehldsHook_SV_SendServerinfo; +typedef IVoidHookChainRegistry IRehldsHookRegistry_SV_SendServerinfo; + +//SV_CheckProtocol hook +typedef IHookChain IRehldsHook_SV_CheckProtocol; +typedef IHookChainRegistry IRehldsHookRegistry_SV_CheckProtocol; + +//SVC_GetChallenge_mod hook +typedef IVoidHookChain IRehldsHook_SVC_GetChallenge_mod; +typedef IVoidHookChainRegistry IRehldsHookRegistry_SVC_GetChallenge_mod; + +//SV_CheckKeyInfo hook +typedef IHookChain IRehldsHook_SV_CheckKeyInfo; +typedef IHookChainRegistry IRehldsHookRegistry_SV_CheckKeyInfo; + +//SV_CheckIPRestrictions hook +typedef IHookChain IRehldsHook_SV_CheckIPRestrictions; +typedef IHookChainRegistry IRehldsHookRegistry_SV_CheckIPRestrictions; + +//SV_FinishCertificateCheck hook +typedef IHookChain IRehldsHook_SV_FinishCertificateCheck; +typedef IHookChainRegistry IRehldsHookRegistry_SV_FinishCertificateCheck; + +//Steam_NotifyBotConnect hook +typedef IHookChain IRehldsHook_Steam_NotifyBotConnect; +typedef IHookChainRegistry IRehldsHookRegistry_Steam_NotifyBotConnect; + +//SerializeSteamId +typedef IVoidHookChain IRehldsHook_SerializeSteamId; +typedef IVoidHookChainRegistry IRehldsHookRegistry_SerializeSteamId; + +//SV_CompareUserID hook +typedef IHookChain IRehldsHook_SV_CompareUserID; +typedef IHookChainRegistry IRehldsHookRegistry_SV_CompareUserID; + +//Steam_NotifyClientDisconnect +typedef IVoidHookChain IRehldsHook_Steam_NotifyClientDisconnect; +typedef IVoidHookChainRegistry IRehldsHookRegistry_Steam_NotifyClientDisconnect; + +//PreProcessPacket +typedef IHookChain IRehldsHook_PreprocessPacket; +typedef IHookChainRegistry IRehldsHookRegistry_PreprocessPacket; + +//ValidateCommand +typedef IHookChain IRehldsHook_ValidateCommand; +typedef IHookChainRegistry IRehldsHookRegistry_ValidateCommand; + +//ExecuteServerStringCmd +typedef IVoidHookChain IRehldsHook_ExecuteServerStringCmd; +typedef IVoidHookChainRegistry IRehldsHookRegistry_ExecuteServerStringCmd; + +//ClientConnected +typedef IVoidHookChain IRehldsHook_ClientConnected; +typedef IVoidHookChainRegistry IRehldsHookRegistry_ClientConnected; + +//HandleNetCommand +typedef IVoidHookChain IRehldsHook_HandleNetCommand; +typedef IVoidHookChainRegistry IRehldsHookRegistry_HandleNetCommand; + +//Mod_LoadBrushModel +typedef IVoidHookChain IRehldsHook_Mod_LoadBrushModel; +typedef IVoidHookChainRegistry IRehldsHookRegistry_Mod_LoadBrushModel; + +//Mod_LoadStudioModel +typedef IVoidHookChain IRehldsHook_Mod_LoadStudioModel; +typedef IVoidHookChainRegistry IRehldsHookRegistry_Mod_LoadStudioModel; + +//SV_EmitEvents hook +typedef IVoidHookChain IRehldsHook_SV_EmitEvents; +typedef IVoidHookChainRegistry IRehldsHookRegistry_SV_EmitEvents; + +//EV_PlayReliableEvent hook +typedef IVoidHookChain IRehldsHook_EV_PlayReliableEvent; +typedef IVoidHookChainRegistry IRehldsHookRegistry_EV_PlayReliableEvent; + +//SV_StartSound hook +typedef IVoidHookChain IRehldsHook_SV_StartSound; +typedef IVoidHookChainRegistry IRehldsHookRegistry_SV_StartSound; + +//PF_Remove_I hook +typedef IVoidHookChain IRehldsHook_PF_Remove_I; +typedef IVoidHookChainRegistry IRehldsHookRegistry_PF_Remove_I; + +//PF_BuildSoundMsg_I hook +typedef IVoidHookChain IRehldsHook_PF_BuildSoundMsg_I; +typedef IVoidHookChainRegistry IRehldsHookRegistry_PF_BuildSoundMsg_I; + +//SV_WriteFullClientUpdate hook +typedef IVoidHookChain IRehldsHook_SV_WriteFullClientUpdate; +typedef IVoidHookChainRegistry IRehldsHookRegistry_SV_WriteFullClientUpdate; + +//SV_CheckConsistencyResponse hook +typedef IHookChain IRehldsHook_SV_CheckConsistencyResponse; +typedef IHookChainRegistry IRehldsHookRegistry_SV_CheckConsistencyResponse; + +//SV_DropClient hook +typedef IVoidHookChain IRehldsHook_SV_DropClient; +typedef IVoidHookChainRegistry IRehldsHookRegistry_SV_DropClient; + +//SV_ActivateServer hook +typedef IVoidHookChain IRehldsHook_SV_ActivateServer; +typedef IVoidHookChainRegistry IRehldsHookRegistry_SV_ActivateServer; + +//SV_WriteVoiceCodec hook +typedef IVoidHookChain IRehldsHook_SV_WriteVoiceCodec; +typedef IVoidHookChainRegistry IRehldsHookRegistry_SV_WriteVoiceCodec; + +//Steam_GSGetSteamID hook +typedef IHookChain IRehldsHook_Steam_GSGetSteamID; +typedef IHookChainRegistry IRehldsHookRegistry_Steam_GSGetSteamID; + +//SV_TransferConsistencyInfo hook +typedef IHookChain IRehldsHook_SV_TransferConsistencyInfo; +typedef IHookChainRegistry IRehldsHookRegistry_SV_TransferConsistencyInfo; + +//Steam_GSBUpdateUserData hook +typedef IHookChain IRehldsHook_Steam_GSBUpdateUserData; +typedef IHookChainRegistry IRehldsHookRegistry_Steam_GSBUpdateUserData; + +//Cvar_DirectSet hook +typedef IVoidHookChain IRehldsHook_Cvar_DirectSet; +typedef IVoidHookChainRegistry IRehldsHookRegistry_Cvar_DirectSet; + +//SV_EstablishTimeBase hook +typedef IVoidHookChain IRehldsHook_SV_EstablishTimeBase; +typedef IVoidHookChainRegistry IRehldsHookRegistry_SV_EstablishTimeBase; + +//SV_Spawn_f hook +typedef IVoidHookChain<> IRehldsHook_SV_Spawn_f; +typedef IVoidHookChainRegistry<> IRehldsHookRegistry_SV_Spawn_f; + +//SV_CreatePacketEntities hook +typedef IHookChain IRehldsHook_SV_CreatePacketEntities; +typedef IHookChainRegistry IRehldsHookRegistry_SV_CreatePacketEntities; + +//SV_EmitSound2 hook +typedef IHookChain IRehldsHook_SV_EmitSound2; +typedef IHookChainRegistry IRehldsHookRegistry_SV_EmitSound2; + +//CreateFakeClient hook +typedef IHookChain IRehldsHook_CreateFakeClient; +typedef IHookChainRegistry IRehldsHookRegistry_CreateFakeClient; + +//SV_CheckConnectionLessRateLimits +typedef IHookChain IRehldsHook_SV_CheckConnectionLessRateLimits; +typedef IHookChainRegistry IRehldsHookRegistry_SV_CheckConnectionLessRateLimits; + +//SV_Frame hook +typedef IVoidHookChain<> IRehldsHook_SV_Frame; +typedef IVoidHookChainRegistry<> IRehldsHookRegistry_SV_Frame; + +//SV_ShouldSendConsistencyList hook +typedef IHookChain IRehldsHook_SV_ShouldSendConsistencyList; +typedef IHookChainRegistry IRehldsHookRegistry_SV_ShouldSendConsistencyList; + +//GetEntityInit hook +typedef IHookChain IRehldsHook_GetEntityInit; +typedef IHookChainRegistry IRehldsHookRegistry_GetEntityInit; + + +class IRehldsHookchains { +public: + virtual ~IRehldsHookchains() { } + + virtual IRehldsHookRegistry_Steam_NotifyClientConnect* Steam_NotifyClientConnect() = 0; + virtual IRehldsHookRegistry_SV_ConnectClient* SV_ConnectClient() = 0; + virtual IRehldsHookRegistry_SV_GetIDString* SV_GetIDString() = 0; + virtual IRehldsHookRegistry_SV_SendServerinfo* SV_SendServerinfo() = 0; + virtual IRehldsHookRegistry_SV_CheckProtocol* SV_CheckProtocol() = 0; + virtual IRehldsHookRegistry_SVC_GetChallenge_mod* SVC_GetChallenge_mod() = 0; + virtual IRehldsHookRegistry_SV_CheckKeyInfo* SV_CheckKeyInfo() = 0; + virtual IRehldsHookRegistry_SV_CheckIPRestrictions* SV_CheckIPRestrictions() = 0; + virtual IRehldsHookRegistry_SV_FinishCertificateCheck* SV_FinishCertificateCheck() = 0; + virtual IRehldsHookRegistry_Steam_NotifyBotConnect* Steam_NotifyBotConnect() = 0; + virtual IRehldsHookRegistry_SerializeSteamId* SerializeSteamId() = 0; + virtual IRehldsHookRegistry_SV_CompareUserID* SV_CompareUserID() = 0; + virtual IRehldsHookRegistry_Steam_NotifyClientDisconnect* Steam_NotifyClientDisconnect() = 0; + virtual IRehldsHookRegistry_PreprocessPacket* PreprocessPacket() = 0; + virtual IRehldsHookRegistry_ValidateCommand* ValidateCommand() = 0; + virtual IRehldsHookRegistry_ClientConnected* ClientConnected() = 0; + virtual IRehldsHookRegistry_HandleNetCommand* HandleNetCommand() = 0; + virtual IRehldsHookRegistry_Mod_LoadBrushModel* Mod_LoadBrushModel() = 0; + virtual IRehldsHookRegistry_Mod_LoadStudioModel* Mod_LoadStudioModel() = 0; + virtual IRehldsHookRegistry_ExecuteServerStringCmd* ExecuteServerStringCmd() = 0; + virtual IRehldsHookRegistry_SV_EmitEvents* SV_EmitEvents() = 0; + virtual IRehldsHookRegistry_EV_PlayReliableEvent* EV_PlayReliableEvent() = 0; + virtual IRehldsHookRegistry_SV_StartSound* SV_StartSound() = 0; + virtual IRehldsHookRegistry_PF_Remove_I* PF_Remove_I() = 0; + virtual IRehldsHookRegistry_PF_BuildSoundMsg_I* PF_BuildSoundMsg_I() = 0; + virtual IRehldsHookRegistry_SV_WriteFullClientUpdate* SV_WriteFullClientUpdate() = 0; + virtual IRehldsHookRegistry_SV_CheckConsistencyResponse* SV_CheckConsistencyResponse() = 0; + virtual IRehldsHookRegistry_SV_DropClient* SV_DropClient() = 0; + virtual IRehldsHookRegistry_SV_ActivateServer* SV_ActivateServer() = 0; + virtual IRehldsHookRegistry_SV_WriteVoiceCodec* SV_WriteVoiceCodec() = 0; + virtual IRehldsHookRegistry_Steam_GSGetSteamID* Steam_GSGetSteamID() = 0; + virtual IRehldsHookRegistry_SV_TransferConsistencyInfo* SV_TransferConsistencyInfo() = 0; + virtual IRehldsHookRegistry_Steam_GSBUpdateUserData* Steam_GSBUpdateUserData() = 0; + virtual IRehldsHookRegistry_Cvar_DirectSet* Cvar_DirectSet() = 0; + virtual IRehldsHookRegistry_SV_EstablishTimeBase* SV_EstablishTimeBase() = 0; + virtual IRehldsHookRegistry_SV_Spawn_f* SV_Spawn_f() = 0; + virtual IRehldsHookRegistry_SV_CreatePacketEntities* SV_CreatePacketEntities() = 0; + virtual IRehldsHookRegistry_SV_EmitSound2* SV_EmitSound2() = 0; + virtual IRehldsHookRegistry_CreateFakeClient* CreateFakeClient() = 0; + virtual IRehldsHookRegistry_SV_CheckConnectionLessRateLimits* SV_CheckConnectionLessRateLimits() = 0; + virtual IRehldsHookRegistry_SV_Frame* SV_Frame() = 0; + virtual IRehldsHookRegistry_SV_ShouldSendConsistencyList* SV_ShouldSendConsistencyList() = 0; + virtual IRehldsHookRegistry_GetEntityInit* GetEntityInit() = 0; +}; + +struct RehldsFuncs_t { + void(*DropClient)(IGameClient* cl, bool crash, const char* fmt, ...); + void(*RejectConnection)(netadr_t *adr, char *fmt, ...); + qboolean(*SteamNotifyBotConnect)(IGameClient* cl); + sizebuf_t*(*GetNetMessage)(); + IGameClient*(*GetHostClient)(); + int*(*GetMsgReadCount)(); + qboolean(*FilterUser)(USERID_t*); + void(*NET_SendPacket)(unsigned int length, void *data, const netadr_t &to); + void(*TokenizeString)(char* s); + bool(*CheckChallenge)(const netadr_t& adr, int challenge); + void(*SendUserReg)(sizebuf_t* msg); + void(*WriteDeltaDescriptionsToClient)(sizebuf_t* msg); + void(*SetMoveVars)(); + void(*WriteMovevarsToClient)(sizebuf_t* msg); + char*(*GetClientFallback)(); + int*(*GetAllowCheats)(); + bool(*GSBSecure)(); + int(*GetBuildNumber)(); + double(*GetRealTime)(); + int*(*GetMsgBadRead)(); + cmd_source_t*(*GetCmdSource)(); + void(*Log)(const char* prefix, const char* msg); + DLL_FUNCTIONS *(*GetEntityInterface)(); + void(*EV_PlayReliableEvent)(IGameClient *cl, int entindex, unsigned short eventindex, float delay, struct event_args_s *pargs); + int(*SV_LookupSoundIndex)(const char *sample); + void(*MSG_StartBitWriting)(sizebuf_t *buf); + void(*MSG_WriteBits)(uint32 data, int numbits); + void(*MSG_WriteBitVec3Coord)(const float *fa); + void(*MSG_EndBitWriting)(sizebuf_t *buf); + void*(*SZ_GetSpace)(sizebuf_t *buf, int length); + cvar_t*(*GetCvarVars)(); + int (*SV_GetChallenge)(const netadr_t& adr); + void (*SV_AddResource)(resourcetype_t type, const char *name, int size, unsigned char flags, int index); + int(*MSG_ReadShort)(); + int(*MSG_ReadBuf)(int iSize, void *pbuf); + void(*MSG_WriteBuf)(sizebuf_t *sb, int iSize, void *buf); + void(*MSG_WriteByte)(sizebuf_t *sb, int c); + void(*MSG_WriteShort)(sizebuf_t *sb, int c); + void(*MSG_WriteString)(sizebuf_t *sb, const char *s); + void*(*GetPluginApi)(const char *name); + void(*RegisterPluginApi)(const char *name, void *impl); + qboolean(*SV_FileInConsistencyList)(const char *filename, struct consistency_s **ppconsist); + qboolean(*Steam_NotifyClientConnect)(IGameClient *cl, const void *pvSteam2Key, unsigned int ucbSteam2Key); + void(*Steam_NotifyClientDisconnect)(IGameClient* cl); + void(*SV_StartSound)(int recipients, edict_t *entity, int channel, const char *sample, int volume, float attenuation, int flags, int pitch); + bool(*SV_EmitSound2)(edict_t *entity, IGameClient *receiver, int channel, const char *sample, float volume, float attenuation, int flags, int pitch, int emitFlags, const float *pOrigin); + void(*SV_UpdateUserInfo)(IGameClient *pGameClient); + bool(*StripUnprintableAndSpace)(char *pch); + void(*Cmd_RemoveCmd)(const char *cmd_name); + void(*GetCommandMatches)(const char *string, ObjectList *pMatchList); + bool(*AddExtDll)(void *hModule); + void(*AddCvarListener)(const char *var_name, cvar_callback_t func); + void(*RemoveExtDll)(void *hModule); + void(*RemoveCvarListener)(const char *var_name, cvar_callback_t func); + ENTITYINIT(*GetEntityInit)(char *pszClassName); + + // Read functions + int(*MSG_ReadChar)(); + int(*MSG_ReadByte)(); + int(*MSG_ReadLong)(); + float(*MSG_ReadFloat)(); + char*(*MSG_ReadString)(); + char*(*MSG_ReadStringLine)(); + float(*MSG_ReadAngle)(); + float(*MSG_ReadHiresAngle)(); + void(*MSG_ReadUsercmd)(struct usercmd_s *to, struct usercmd_s *from); + float(*MSG_ReadCoord)(); + void(*MSG_ReadVec3Coord)(sizebuf_t *sb, vec3_t fa); + + // Read bit functions + bool(*MSG_IsBitReading)(); + void(*MSG_StartBitReading)(sizebuf_t *buf); + void(*MSG_EndBitReading)(sizebuf_t *buf); + uint32(*MSG_PeekBits)(int numbits); + int(*MSG_ReadOneBit)(); + uint32(*MSG_ReadBits)(int numbits); + int(*MSG_ReadSBits)(int numbits); + float(*MSG_ReadBitCoord)(); + void(*MSG_ReadBitVec3Coord)(vec_t *fa); + float(*MSG_ReadBitAngle)(int numbits); + int(*MSG_ReadBitData)(void *dest, int length); + char*(*MSG_ReadBitString)(); + int(*MSG_CurrentBit)(); + + // Write functions + void(*MSG_WriteLong)(sizebuf_t *sb, int c); + void(*MSG_WriteFloat)(sizebuf_t *sb, float f); + void(*MSG_WriteAngle)(sizebuf_t *sb, float f); + void(*MSG_WriteHiresAngle)(sizebuf_t *sb, float f); + void(*MSG_WriteUsercmd)(sizebuf_t *sb, struct usercmd_s *to, struct usercmd_s *from); + void(*MSG_WriteCoord)(sizebuf_t *sb, float f); + void(*MSG_WriteVec3Coord)(sizebuf_t *sb, const vec3_t fa); + + // Write bit functions + bool(*MSG_IsBitWriting)(); + void(*MSG_WriteOneBit)(int nValue); + void(*MSG_WriteSBits)(uint32 data, int numbits); + void(*MSG_WriteBitCoord)(float f); + void(*MSG_WriteBitAngle)(float fAngle, int numbits); + void(*MSG_WriteBitData)(void *src, int length); + void(*MSG_WriteBitString)(const char *p); + void(*SZ_Write)(sizebuf_t *buf, const void *data, int length); + void(*SZ_Print)(sizebuf_t *buf, const char *data); + void(*SZ_Clear)(sizebuf_t *buf); + void(*MSG_BeginReading)(); + double(*GetHostFrameTime)(); + struct cmd_function_s *(*GetFirstCmdFunctionHandle)(); +}; + +class IRehldsApi { +public: + virtual ~IRehldsApi() { } + + virtual int GetMajorVersion() = 0; + virtual int GetMinorVersion() = 0; + virtual const RehldsFuncs_t* GetFuncs() = 0; + virtual IRehldsHookchains* GetHookchains() = 0; + virtual IRehldsServerStatic* GetServerStatic() = 0; + virtual IRehldsServerData* GetServerData() = 0; + virtual IRehldsFlightRecorder* GetFlightRecorder() = 0; +}; + +#define VREHLDS_HLDS_API_VERSION "VREHLDS_HLDS_API_VERSION001" diff --git a/dep/rehlsdk/engine/rehlds_interfaces.h b/dep/rehlsdk/engine/rehlds_interfaces.h new file mode 100644 index 0000000..c404e61 --- /dev/null +++ b/dep/rehlsdk/engine/rehlds_interfaces.h @@ -0,0 +1,327 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +class INetChan; +class IGameClient; + +#include "archtypes.h" +#include "const.h" +#include "netadr.h" + +#include "common_rehlds.h" +#include "userid_rehlds.h" +#include "FileSystem.h" + +#ifdef REHLDS_SELF +#include "server.h" +#endif + +class INetChan; +class IGameClient; + +class IGameClient { +public: + virtual int GetId() = 0; + + // false = client is free + virtual bool IsActive() = 0; + virtual void SetActive(bool active) = 0; + + // false = don't send datagrams + virtual bool IsSpawned() = 0; + virtual void SetSpawned(bool spawned) = 0; + + // The client's net connection + virtual INetChan* GetNetChan() = 0; + + // The datagram is written to after every frame, but only cleared + // when it is sent out to the client. It can be harmlessly overflowed + virtual sizebuf_t* GetDatagram() = 0; + + // EDICT_NUM(clientnum + 1) + virtual edict_t* GetEdict() = 0; + + virtual USERID_t* GetNetworkUserID() = 0; + + virtual const char* GetName() = 0; + + virtual bool IsConnected() = 0; + virtual void SetConnected(bool connected) = 0; + + // Which other clients does this guy's voice stream go to? + virtual uint32 GetVoiceStream(int stream_id) = 0; + virtual void SetLastVoiceTime(double time) = 0; + virtual double GetLastVoiceTime() = 0; + + // Does this client want to hear his own voice? + virtual bool GetLoopback() = 0; + virtual struct usercmd_s *GetLastCmd() = 0; + + // This is spectator proxy (hltv) + virtual bool IsProxy() = 0; + virtual void SetProxy(bool proxy) = 0; + + // This client is a fake player controlled by the game DLL + virtual bool IsFakeClient() = 0; + virtual void SetFakeClient(bool state) = 0; + + // On server, getting data + virtual bool IsFullyConnected() = 0; + virtual void SetFullyConnected(bool state) = 0; + + virtual bool IsUploading() = 0; + virtual void SetUploading(bool state) = 0; + + virtual bool IsHasUserMsgs() = 0; + virtual void SetHasUserMsgs(bool value) = 0; + + virtual bool HasForceUnmodified() = 0; + virtual void SetHasForceUnmodified(bool value) = 0; + + // Number of packets choked at the server because the client - server network channel + // is backlogged with too much data + virtual int GetChokeCount() = 0; + virtual void SetChokeCount(int count) = 0; + + // -1 = no compression. This is where the server is creating the compressed info from + virtual int GetDeltaSequence() = 0; + virtual void SetDeltaSequence(int value) = 0; + + // For filling in big drops + virtual void SetLastCmd(struct usercmd_s *ucmd) = 0; + + virtual double GetConnectTime() = 0; + virtual void SetConnectTime(double time) = 0; + + virtual double GetCmdTime() = 0; + virtual void SetCmdTime(double time) = 0; + + virtual double GetIgnoreCmdTime() = 0; + virtual void SetIgnoreCmdTime(double time) = 0; + + virtual float GetLatency() = 0; + virtual void SetLatency(float latency) = 0; + + virtual float GetPacketLoss() = 0; + virtual void SetPacketLoss(float packetLoss) = 0; + + virtual double GetLocalTime() = 0; + virtual void SetLocalTime(double time) = 0; + + virtual double GetSvTimeBase() = 0; + virtual void SetSvTimeBase(double time) = 0; + + // Or time of disconnect for zombies + virtual double GetConnectionStartedTime() = 0; + virtual void SetConnectionStartedTime(double time) = 0; + + // Time when we should send next world state update (datagram) + virtual double GetNextMessageTime() = 0; + virtual void SetNextMessageTime(double time) = 0; + + // Default time to wait for next message + virtual double GetNextMessageIntervalTime() = 0; + virtual void SetNextMessageIntervalTime(double time_interval) = 0; + + // false - only send messages if the client has sent one and the bandwidth is not choked + virtual bool GetSendMessageState() = 0; + virtual void SetSendMessageState(bool state) = 0; + + virtual bool GetSkipMessageState() = 0; + virtual void SetSkipMessageState(bool state) = 0; + + virtual bool GetSendInfoState() = 0; + virtual void SetSendInfoState(bool state) = 0; + + virtual float GetSendInfoTime() = 0; + virtual void SetSendInfoTime(float time) = 0; + + // updates can be deltad from here + virtual struct client_frame_s *GetFrames() = 0; + + // Per edict events + virtual struct event_state_s *GetEvents() = 0; + + // View Entity (camera or the client itself) svc_setview + virtual const edict_t *GetViewEntity() = 0; + virtual void SetViewEntity(const edict_t *entity) = 0; + + // Identifying number on server + virtual int GetUserID() = 0; + virtual void SetUserID(int iUserID) = 0; + + // name, etc (received from client) + virtual char *GetUserInfo() = 0; + + // MD5 hash is 32 hex #'s, plus trailing 0 + // Hashed CD Key (32 hex alphabetic chars + 0 terminator) + virtual char *GetHashedCDKey() = 0; + + virtual int GetTopColor() = 0; + virtual void SetTopColor(int color) = 0; + + virtual int GetBottomColor() = 0; + virtual void SetBottomColor(int color) = 0; + + virtual resource_t *GetResourcesOnHand() = 0; + virtual resource_t *GetResourcesNeeded() = 0; + + virtual FileHandle_t GetUploadFileHandle() = 0; + virtual void SetUploadFileHandle(FileHandle_t fhFile) = 0; + + virtual bool IsUploadDoneRegistering() = 0; + virtual void SetUploadDoneRegistering(bool state) = 0; + + virtual customization_t *GetCustomizationData() = 0; + + virtual int GetCRC32MapValue() = 0; + virtual void SetCRC32MapValue(int crcMapValue) = 0; + + // Perform client side prediction of weapon effects + // Determines that the client enabled prediction weapons and will be handled pfnGetWeaponData + virtual bool IsClientPredictingWeapons() = 0; + virtual void SetClientPredictingWeapons(bool state) = 0; + + // Perform server side lag compensation of player movement + // Determines that the client is requesting lag compensation + virtual bool IsClientLagCompensation() = 0; + virtual void SetClientLagCompensation(bool state) = 0; + + // Set on server (transmit to client) + virtual char *GetPhysInfo() = 0; + + virtual void SetVoiceStream(int stream_id, int value) = 0; + + virtual int GetSendResourceCount() = 0; + virtual void SetSendResourceCount(int count) = 0; + + virtual bool IsSentNewResponse() = 0; + virtual void SetSentNewResponse(bool state) = 0; + + // this must be the last virtual function in class +#ifdef REHLDS_SELF + virtual client_t* GetClient() = 0; +#endif +}; + +class INetChan { +public: + virtual const netadr_t* GetRemoteAdr() = 0; + virtual sizebuf_t* GetMessageBuf() = 0; + + + // this must be the last virtual function in class +#ifdef REHLDS_SELF + virtual netchan_t* GetChan() = 0; +#endif +}; + +#ifndef REHLDS_SELF +struct client_t; +#endif + +class IRehldsServerStatic { +public: + virtual ~IRehldsServerStatic() { } + + virtual int GetMaxClients() = 0; + virtual bool IsLogActive() = 0; + virtual IGameClient* GetClient(int id) = 0; + virtual client_t* GetClient_t(int id) = 0; + virtual int GetIndexOfClient_t(client_t* client) = 0; + virtual int GetMaxClientsLimit() = 0; + virtual client_t *GetNextClient_t(client_t *client) = 0; + virtual int GetSpawnCount() = 0; + virtual void SetSpawnCount(int count) = 0; + virtual struct server_log_s *GetLog() = 0; + virtual bool IsSecure() = 0; + virtual void SetSecure(bool value) = 0; +}; + +class IRehldsServerData { +public: + virtual ~IRehldsServerData() { } + + virtual const char* GetModelName() = 0; + virtual const char* GetName() = 0; + virtual uint32 GetWorldmapCrc() = 0; + virtual uint8* GetClientDllMd5() = 0; + virtual sizebuf_t* GetDatagram() = 0; + virtual sizebuf_t* GetReliableDatagram() = 0; + + virtual void SetModelName(const char* modelname) = 0; + virtual void SetConsistencyNum(int num) = 0; + virtual int GetConsistencyNum() = 0; + virtual int GetResourcesNum() = 0; + virtual int GetDecalNameNum() = 0; + + virtual double GetTime() = 0; + virtual void SetResourcesNum(int num) = 0; + virtual struct resource_s *GetResource(int index) = 0; + virtual void SetName(const char* name) = 0; + virtual class ISteamGameServer *GetSteamGameServer() = 0; + virtual struct netadr_s *GetNetFrom() = 0; + virtual double GetOldTime() = 0; + + virtual void SetNetFrom(struct netadr_s *from) = 0; + virtual void SetWorldmapCrc(uint32 crcValue) = 0; + virtual void SetDecalNameNum(int num) = 0; + + virtual bool IsActive() = 0; + virtual void SetActive(bool state) = 0; + virtual bool IsPaused() = 0; + virtual void SetPaused(bool state) = 0; + virtual int GetLastIndexCheckInPVS() = 0; + virtual void SetLastIndexCheckInPVS(int id) = 0; + virtual double GetLastIndexCheckTimeInPVS() = 0; + virtual void SetLastIndexCheckTimeInPVS(double time) = 0; + virtual const char *GetOldName() = 0; + virtual void SetOldName(const char *name) = 0; + virtual const char *GetStartSpotName() = 0; + virtual void SetStartSpotName(const char *startspot) = 0; + virtual struct model_s *GetWorldModel() = 0; + virtual void SetWorldModel(struct model_s *model) = 0; + virtual struct consistency_s *GetConsistency(int index) = 0; + virtual struct model_s *GetModel(int index) = 0; + virtual struct event_s *GetEventPrecache(int index) = 0; + virtual struct entity_state_s *GetEntityBaseline(int index) = 0; + virtual struct extra_baselines_s *GetEntityInstanceBaselines() = 0; + virtual int GetNumGenericNames() = 0; + virtual void SetNumGenericNames(int num) = 0; + virtual int GetNumEdicts() = 0; + virtual void SetNumEdicts(int num_edicts) = 0; + virtual int GetMaxEdicts() = 0; + virtual void SetMaxEdicts(int max_edicts) = 0; + virtual edict_t *GetEdict(int index) = 0; + virtual server_state_t GetState() = 0; + virtual void SetState(server_state_t st) = 0; + virtual sizebuf_t *GetMulticastBuf() = 0; + virtual sizebuf_t *GetSpectatorBuf() = 0; + virtual sizebuf_t *GetSignonBuf() = 0; +}; diff --git a/dep/rehlsdk/engine/shake.h b/dep/rehlsdk/engine/shake.h new file mode 100644 index 0000000..1146a5e --- /dev/null +++ b/dep/rehlsdk/engine/shake.h @@ -0,0 +1,57 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef SHAKE_H +#define SHAKE_H + +// Screen / View effects + +// screen shake +extern int gmsgShake; + +// This structure is sent over the net to describe a screen shake event +typedef struct +{ + unsigned short amplitude; // FIXED 4.12 amount of shake + unsigned short duration; // FIXED 4.12 seconds duration + unsigned short frequency; // FIXED 8.8 noise frequency (low frequency is a jerk,high frequency is a rumble) +} ScreenShake; + +extern void V_ApplyShake( float *origin, float *angles, float factor ); +extern void V_CalcShake( void ); +extern int V_ScreenShake( const char *pszName, int iSize, void *pbuf ); +extern int V_ScreenFade( const char *pszName, int iSize, void *pbuf ); + + +// Fade in/out +extern int gmsgFade; + +#define FFADE_IN 0x0000 // Just here so we don't pass 0 into the function +#define FFADE_OUT 0x0001 // Fade out (not in) +#define FFADE_MODULATE 0x0002 // Modulate (don't blend) +#define FFADE_STAYOUT 0x0004 // ignores the duration, stays faded out until new ScreenFade message received +#define FFADE_LONGFADE 0x0008 // used to indicate the fade can be longer than 16 seconds (added for czero) + + +// This structure is sent over the net to describe a screen fade event +typedef struct +{ + unsigned short duration; // FIXED 4.12 seconds duration + unsigned short holdTime; // FIXED 4.12 seconds duration until reset (fade & hold) + short fadeFlags; // flags + byte r, g, b, a; // fade to color ( max alpha ) +} ScreenFade; + +#endif // SHAKE_H + diff --git a/dep/rehlsdk/engine/spritegn.h b/dep/rehlsdk/engine/spritegn.h new file mode 100644 index 0000000..f6145d7 --- /dev/null +++ b/dep/rehlsdk/engine/spritegn.h @@ -0,0 +1,84 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef SPRITEGN_H +#define SPRITEGN_H +#ifdef _WIN32 +#pragma once +#endif + +#include "modelgen.h" +#include "commonmacros.h" + +#define SPRITE_VERSION 2 // Half-Life sprites +#define IDSPRITEHEADER MAKEID('I', 'D', 'S', 'P') // little-endian "IDSP" + +typedef enum spriteframetype_e +{ + SPR_SINGLE = 0, + SPR_GROUP, + SPR_ANGLED +} spriteframetype_t; + +typedef struct dsprite_s +{ + int ident; + int version; + int type; + int texFormat; + float boundingradius; + int width; + int height; + int numframes; + float beamlength; + synctype_t synctype; +} dsprite_t; + +typedef struct dspriteframe_s +{ + int origin[2]; + int width; + int height; +} dspriteframe_t; + +typedef struct dspritegroup_s +{ + int numframes; +} dspritegroup_t; + +typedef struct dspriteinterval_s +{ + float interval; +} dspriteinterval_t; + +typedef struct dspriteframetype_s +{ + spriteframetype_t type; +} dspriteframetype_t; + +#endif // SPRITEGN_H diff --git a/dep/rehlsdk/engine/static_map.h b/dep/rehlsdk/engine/static_map.h new file mode 100644 index 0000000..6fe7496 --- /dev/null +++ b/dep/rehlsdk/engine/static_map.h @@ -0,0 +1,260 @@ +#pragma once + +#include "archtypes.h" +#include "crc32c.h" + +template +class CStaticMap { +protected: + virtual uint32 hash(const T_KEY& val) { + return crc32c((const unsigned char*)&val, sizeof(T_KEY)); + } + + virtual bool equals(const T_KEY& val1, const T_KEY& val2) { + return 0 == memcmp(&val1, &val2, sizeof(T_KEY)); + } + + struct map_node_t { + map_node_t* prev; + map_node_t* next; + T_KEY key; + T_VAL val; + }; + +private: + map_node_t* m_RootNodes[1 << ASSOC_2N]; + map_node_t m_AllNodes[MAX_VALS]; + map_node_t* m_FreeRoot; + + unsigned int GetRoodNodeId(const T_KEY& val) { return hash(val) & (0xFFFFFFFF >> (32 - ASSOC_2N)); } + + void unlink(map_node_t* node) { + map_node_t* prev = node->prev; + map_node_t* next = node->next; + + if (prev) { + prev->next = next; + } + + if (next) { + next->prev = prev; + } + + if (!prev) { + // this was a root node + unsigned int rootId = GetRoodNodeId(node->key); + if (m_RootNodes[rootId] != node) { + Sys_Error("%s: invalid root node", __func__); + return; + } + + m_RootNodes[rootId] = next; + } + } + + void link(map_node_t* node) { + unsigned int rootId = GetRoodNodeId(node->key); + map_node_t* root = m_RootNodes[rootId]; + node->prev = NULL; + node->next = root; + + if (root) { + root->prev = node; + } + + m_RootNodes[rootId] = node; + } + + void linkToFreeStack(map_node_t* node) { + node->next = m_FreeRoot; + if (m_FreeRoot) { + m_FreeRoot->prev = node; + } + m_FreeRoot = node; + } + +public: + CStaticMap() { + clear(); + } + + void clear() { + memset(m_RootNodes, 0, sizeof(m_RootNodes)); + memset(m_AllNodes, 0, sizeof(m_AllNodes)); + m_FreeRoot = NULL; + + for (int i = 0; i < MAX_VALS; i++) { + linkToFreeStack(&m_AllNodes[i]); + } + } + + map_node_t* get(const T_KEY& key) { + unsigned int rootId = GetRoodNodeId(key); + map_node_t* n = m_RootNodes[rootId]; + while (n) { + if (equals(n->key, key)) { + return n; + } + n = n->next; + } + return NULL; + } + + bool put(const T_KEY& key, T_VAL& val) { + map_node_t* n = get(key); + if (n) { + n->val = val; + return true; + } + + if (!m_FreeRoot) { + return false; + } + + n = m_FreeRoot; + m_FreeRoot = m_FreeRoot->next; + + n->key = key; + n->val = val; + + unsigned int rootId = GetRoodNodeId(key); + map_node_t* root = m_RootNodes[rootId]; + + if (root) { + root->prev = n; + } + + n->prev = NULL; + n->next = root; + m_RootNodes[rootId] = n; + + return true; + } + + void remove(map_node_t* node) { + unlink(node); + linkToFreeStack(node); + } + + bool remove(const T_KEY& key) { + map_node_t* n = get(key); + if (!n) { + return false; + } + + remove(n); + return true; + } + + class Iterator { + friend class CStaticMap; + protected: + CStaticMap* m_Map; + map_node_t** m_RootNodes; + unsigned int m_NextRootNode; + map_node_t* m_CurNode; + + void searchForNextNode() { + if (m_CurNode && m_CurNode->next) { + m_CurNode = m_CurNode->next; + return; + } + + m_CurNode = NULL; + while (!m_CurNode) { + if (m_NextRootNode >= (1 << ASSOC_2N)) { + return; + } + m_CurNode = m_RootNodes[m_NextRootNode++]; + } + } + + Iterator(CStaticMap* m) { + m_Map = m; + m_RootNodes = m_Map->m_RootNodes; + m_NextRootNode = 0; + m_CurNode = NULL; + searchForNextNode(); + } + + public: + map_node_t* next() { + searchForNextNode(); + return m_CurNode; + } + + map_node_t* current() { + return m_CurNode; + } + + void remove() { + m_Map->remove(m_CurNode); + m_CurNode = NULL; + } + + bool hasElement() { + return m_CurNode != NULL; + } + }; + + Iterator iterator() { + return Iterator(this); + } +}; + +template +class CStringKeyStaticMap : public CStaticMap { +protected: + virtual uint32 hash(const char* const &val) { + return crc32c((const unsigned char*)val, strlen(val)); + } + + virtual bool equals(const char* const &val1, const char* const &val2) { + return !strcmp(val1, val2); + } + +public: + CStringKeyStaticMap() { + } + +}; + +template +class CICaseStringKeyStaticMap : public CStaticMap { +protected: + virtual uint32 hash(const char* const &val) { + uint32 cksum = 0; + const char* pcc = val; +#ifdef REHLDS_SSE + if (cpuinfo.sse4_2) { + while (*pcc) { + char cc = *(pcc++); + if (cc >= 'A' || cc <= 'Z') { + cc |= 0x20; + } + cksum = crc32c_t8_sse(cksum, cc); + } + } + else +#endif // REHLDS_SSE + { + while (*pcc) { + char cc = *(pcc++); + if (cc >= 'A' || cc <= 'Z') { + cc |= 0x20; + } + cksum = crc32c_t8_nosse(cksum, cc); + } + } + return cksum; + } + + virtual bool equals(const char* const &val1, const char* const &val2) { + return !_stricmp(val1, val2); + } + +public: + CICaseStringKeyStaticMap() { + } + +}; diff --git a/dep/rehlsdk/engine/studio.h b/dep/rehlsdk/engine/studio.h new file mode 100644 index 0000000..b59a90a --- /dev/null +++ b/dep/rehlsdk/engine/studio.h @@ -0,0 +1,354 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +#pragma once + +/* +============================================================================== + +STUDIO MODELS + +Studio models are position independent, so the cache manager can move them. +============================================================================== +*/ + +#define MAXSTUDIOTRIANGLES 20000 // TODO: tune this +#define MAXSTUDIOVERTS 2048 // TODO: tune this +#define MAXSTUDIOSEQUENCES 2048 // total animation sequences +#define MAXSTUDIOSKINS 100 // total textures +#define MAXSTUDIOSRCBONES 512 // bones allowed at source movement +#define MAXSTUDIOBONES 128 // total bones actually used +#define MAXSTUDIOMODELS 32 // sub-models per model +#define MAXSTUDIOBODYPARTS 32 +#define MAXSTUDIOGROUPS 16 +#define MAXSTUDIOANIMATIONS 2048 // per sequence +#define MAXSTUDIOMESHES 256 +#define MAXSTUDIOEVENTS 1024 +#define MAXSTUDIOPIVOTS 256 +#define MAXSTUDIOCONTROLLERS 8 + +typedef struct +{ + int id; + int version; + + char name[64]; + int length; + + vec3_t eyeposition; // ideal eye position + vec3_t min; // ideal movement hull size + vec3_t max; + + vec3_t bbmin; // clipping bounding box + vec3_t bbmax; + + int flags; + + int numbones; // bones + int boneindex; + + int numbonecontrollers; // bone controllers + int bonecontrollerindex; + + int numhitboxes; // complex bounding boxes + int hitboxindex; + + int numseq; // animation sequences + int seqindex; + + int numseqgroups; // demand loaded sequences + int seqgroupindex; + + int numtextures; // raw textures + int textureindex; + int texturedataindex; + + int numskinref; // replaceable textures + int numskinfamilies; + int skinindex; + + int numbodyparts; + int bodypartindex; + + int numattachments; // queryable attachable points + int attachmentindex; + + int soundtable; + int soundindex; + int soundgroups; + int soundgroupindex; + + int numtransitions; // animation node to animation node transition graph + int transitionindex; +} studiohdr_t; + +// header for demand loaded sequence group data +typedef struct +{ + int id; + int version; + + char name[64]; + int length; +} studioseqhdr_t; + +// bones +typedef struct +{ + char name[32]; // bone name for symbolic links + int parent; // parent bone + int flags; // ?? + int bonecontroller[6]; // bone controller index, -1 == none + float value[6]; // default DoF values + float scale[6]; // scale for delta DoF values +} mstudiobone_t; + +// bone controllers +typedef struct +{ + int bone; // -1 == 0 + int type; // X, Y, Z, XR, YR, ZR, M + float start; + float end; + int rest; // byte index value at rest + int index; // 0-3 user set controller, 4 mouth +} mstudiobonecontroller_t; + +// intersection boxes +typedef struct +{ + int bone; + int group; // intersection group + vec3_t bbmin; // bounding box + vec3_t bbmax; +} mstudiobbox_t; + +// demand loaded sequence groups +typedef struct +{ + char label[32]; // textual name + char name[64]; // file name + int32 unused1; // was "cache" - index pointer + int unused2; // was "data" - hack for group 0 +} mstudioseqgroup_t; + +// sequence descriptions +typedef struct +{ + char label[32]; // sequence label + + float fps; // frames per second + int flags; // looping/non-looping flags + + int activity; + int actweight; + + int numevents; + int eventindex; + + int numframes; // number of frames per sequence + + int numpivots; // number of foot pivots + int pivotindex; + + int motiontype; + int motionbone; + vec3_t linearmovement; + int automoveposindex; + int automoveangleindex; + + vec3_t bbmin; // per sequence bounding box + vec3_t bbmax; + + int numblends; + int animindex; // mstudioanim_t pointer relative to start of sequence group data + // [blend][bone][X, Y, Z, XR, YR, ZR] + + int blendtype[2]; // X, Y, Z, XR, YR, ZR + float blendstart[2]; // starting value + float blendend[2]; // ending value + int blendparent; + + int seqgroup; // sequence group for demand loading + + int entrynode; // transition node at entry + int exitnode; // transition node at exit + int nodeflags; // transition rules + + int nextseq; // auto advancing sequences +} mstudioseqdesc_t; + +// events +#include "studio_event.h" +/* +typedef struct +{ + int frame; + int event; + int type; + char options[64]; +} mstudioevent_t; +*/ + +// pivots +typedef struct +{ + vec3_t org; // pivot point + int start; + int end; +} mstudiopivot_t; + +// attachment +typedef struct +{ + char name[32]; + int type; + int bone; + vec3_t org; // attachment point + vec3_t vectors[3]; +} mstudioattachment_t; + +typedef struct +{ + unsigned short offset[6]; +} mstudioanim_t; + +// animation frames +typedef union +{ + struct { + byte valid; + byte total; + } num; + short value; +} mstudioanimvalue_t; + +// body part index +typedef struct +{ + char name[64]; + int nummodels; + int base; + int modelindex; // index into models array +} mstudiobodyparts_t; + +// skin info +typedef struct +{ + char name[64]; + int flags; + int width; + int height; + int index; +} mstudiotexture_t; + +// skin families +// short index[skinfamilies][skinref] + +// studio models +typedef struct +{ + char name[64]; + + int type; + + float boundingradius; + + int nummesh; + int meshindex; + + int numverts; // number of unique vertices + int vertinfoindex; // vertex bone info + int vertindex; // vertex vec3_t + int numnorms; // number of unique surface normals + int norminfoindex; // normal bone info + int normindex; // normal vec3_t + + int numgroups; // deformation groups + int groupindex; +} mstudiomodel_t; + +// vec3_t boundingbox[model][bone][2]; // complex intersection info + +// meshes +typedef struct +{ + int numtris; + int triindex; + int skinref; + int numnorms; // per mesh normals + int normindex; // normal vec3_t +} mstudiomesh_t; + +// triangles +#if 0 +typedef struct +{ + short vertindex; // index into vertex array + short normindex; // index into normal array + short s,t; // s,t position on skin +} mstudiotrivert_t; +#endif + +#define STUDIO_DYNAMIC_LIGHT 0x0100 // dynamically get lighting from floor or ceil (flying monsters) +#define STUDIO_TRACE_HITBOX 0x0200 // always use hitbox trace instead of bbox + +// lighting options +#define STUDIO_NF_FLATSHADE 0x0001 +#define STUDIO_NF_CHROME 0x0002 +#define STUDIO_NF_FULLBRIGHT 0x0004 +#define STUDIO_NF_NOMIPS 0x0008 +#define STUDIO_NF_ALPHA 0x0010 +#define STUDIO_NF_ADDITIVE 0x0020 +#define STUDIO_NF_MASKED 0x0040 + +// motion flags +#define STUDIO_X 0x0001 +#define STUDIO_Y 0x0002 +#define STUDIO_Z 0x0004 +#define STUDIO_XR 0x0008 +#define STUDIO_YR 0x0010 +#define STUDIO_ZR 0x0020 +#define STUDIO_LX 0x0040 +#define STUDIO_LY 0x0080 +#define STUDIO_LZ 0x0100 +#define STUDIO_AX 0x0200 +#define STUDIO_AY 0x0400 +#define STUDIO_AZ 0x0800 +#define STUDIO_AXR 0x1000 +#define STUDIO_AYR 0x2000 +#define STUDIO_AZR 0x4000 +#define STUDIO_TYPES 0x7FFF +#define STUDIO_RLOOP 0x8000 // controller that wraps shortest distance + +// bonecontroller types +#define STUDIO_MOUTH 4 // hardcoded + +// sequence flags +#define STUDIO_LOOPING 0x0001 + +// bone flags +#define STUDIO_HAS_NORMALS 0x0001 +#define STUDIO_HAS_VERTICES 0x0002 +#define STUDIO_HAS_BBOX 0x0004 +#define STUDIO_HAS_CHROME 0x0008 // if any of the textures have chrome on them + +#define RAD_TO_STUDIO (32768.0/M_PI) +#define STUDIO_TO_RAD (M_PI/32768.0) + +#define STUDIO_NUM_HULLS 128 +#define STUDIO_NUM_PLANES (STUDIO_NUM_HULLS * 6) +#define STUDIO_CACHE_SIZE 16 +#define STUDIO_CACHEMASK (STUDIO_CACHE_SIZE - 1) diff --git a/dep/rehlsdk/engine/sys_shared.cpp b/dep/rehlsdk/engine/sys_shared.cpp new file mode 100644 index 0000000..16fd966 --- /dev/null +++ b/dep/rehlsdk/engine/sys_shared.cpp @@ -0,0 +1,74 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#include "sys_shared.h" + +#if defined(__GNUC__) +#include +#elif _MSC_VER >= 1400 && !defined(ASMLIB_H) +#include // __cpuidex +#endif + +#define SSE3_FLAG (1<<0) +#define SSSE3_FLAG (1<<9) +#define SSE4_1_FLAG (1<<19) +#define SSE4_2_FLAG (1<<20) +#define POPCNT_FLAG (1<<23) +#define AVX_FLAG (1<<28) +#define AVX2_FLAG (1<<5) + +cpuinfo_t cpuinfo; + +void Sys_CheckCpuInstructionsSupport(void) +{ + unsigned int cpuid_data[4]{}; + +#if defined ASMLIB_H + cpuid_ex((int *)cpuid_data, 1, 0); +#elif defined(__GNUC__) + __get_cpuid(0x1, &cpuid_data[0], &cpuid_data[1], &cpuid_data[2], &cpuid_data[3]); +#else + __cpuidex((int *)cpuid_data, 1, 0); +#endif + + cpuinfo.sse3 = (cpuid_data[2] & SSE3_FLAG) ? 1 : 0; // ecx + cpuinfo.ssse3 = (cpuid_data[2] & SSSE3_FLAG) ? 1 : 0; + cpuinfo.sse4_1 = (cpuid_data[2] & SSE4_1_FLAG) ? 1 : 0; + cpuinfo.sse4_2 = (cpuid_data[2] & SSE4_2_FLAG) ? 1 : 0; + cpuinfo.popcnt = (cpuid_data[2] & POPCNT_FLAG) ? 1 : 0; + cpuinfo.avx = (cpuid_data[2] & AVX_FLAG) ? 1 : 0; + +#if defined ASMLIB_H + cpuid_ex((int *)cpuid_data, 7, 0); +#elif defined(__GNUC__) + __get_cpuid(0x7, &cpuid_data[0], &cpuid_data[1], &cpuid_data[2], &cpuid_data[3]); +#else + __cpuidex((int *)cpuid_data, 7, 0); +#endif + + cpuinfo.avx2 = (cpuid_data[1] & AVX2_FLAG) ? 1 : 0; // ebx +} diff --git a/dep/rehlsdk/engine/sys_shared.h b/dep/rehlsdk/engine/sys_shared.h new file mode 100644 index 0000000..5b5da98 --- /dev/null +++ b/dep/rehlsdk/engine/sys_shared.h @@ -0,0 +1,39 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#include + +typedef struct cpuinfo_s +{ + uint8 sse3, ssse3, sse4_1, sse4_2, avx, avx2, popcnt; +} cpuinfo_t; + +extern cpuinfo_t cpuinfo; + +void Sys_CheckCpuInstructionsSupport(void); diff --git a/dep/rehlsdk/engine/userid_rehlds.h b/dep/rehlsdk/engine/userid_rehlds.h new file mode 100644 index 0000000..53b76f4 --- /dev/null +++ b/dep/rehlsdk/engine/userid_rehlds.h @@ -0,0 +1,46 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ +#pragma once + +#include "archtypes.h" + +// Authentication types +enum AUTH_IDTYPE +{ + AUTH_IDTYPE_UNKNOWN = 0, + AUTH_IDTYPE_STEAM = 1, + AUTH_IDTYPE_VALVE = 2, + AUTH_IDTYPE_LOCAL = 3 +}; + +typedef struct USERID_s +{ + int idtype; + uint64 m_SteamID; + unsigned int clientip; +} USERID_t; diff --git a/dep/rehlsdk/pm_shared/pm_debug.h b/dep/rehlsdk/pm_shared/pm_debug.h new file mode 100644 index 0000000..6eca1f0 --- /dev/null +++ b/dep/rehlsdk/pm_shared/pm_debug.h @@ -0,0 +1,26 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#ifndef PM_DEBUG_H +#define PM_DEBUG_H +#ifdef _WIN32 +#pragma once +#endif + +void PM_ViewEntity( void ); +void PM_DrawBBox(vec3_t mins, vec3_t maxs, vec3_t origin, int pcolor, float life); +void PM_ParticleLine(vec3_t start, vec3_t end, int pcolor, float life, float vert); +void PM_ShowClipBox( void ); + +#endif // PMOVEDBG_H diff --git a/dep/rehlsdk/pm_shared/pm_defs.h b/dep/rehlsdk/pm_shared/pm_defs.h new file mode 100644 index 0000000..0038bb4 --- /dev/null +++ b/dep/rehlsdk/pm_shared/pm_defs.h @@ -0,0 +1,228 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// pm_defs.h +#if !defined( PM_DEFSH ) +#define PM_DEFSH +#ifdef _WIN32 +#pragma once +#endif + +#include "archtypes.h" // DAL +#define MAX_PHYSENTS 600 // Must have room for all entities in the world. +#define MAX_MOVEENTS 64 +#define MAX_CLIP_PLANES 5 + +#define PM_NORMAL 0x00000000 +#define PM_STUDIO_IGNORE 0x00000001 // Skip studio models +#define PM_STUDIO_BOX 0x00000002 // Use boxes for non-complex studio models (even in traceline) +#define PM_GLASS_IGNORE 0x00000004 // Ignore entities with non-normal rendermode +#define PM_WORLD_ONLY 0x00000008 // Only trace against the world + +// Values for flags parameter of PM_TraceLine +#define PM_TRACELINE_PHYSENTSONLY 0 +#define PM_TRACELINE_ANYVISIBLE 1 + + +#include "pm_info.h" + +// PM_PlayerTrace results. +#include "pmtrace.h" + +#if !defined ( USERCMD_H ) +#include "usercmd.h" +#endif + +#include "const.h" + + +// physent_t +typedef struct physent_s +{ + char name[32]; // Name of model, or "player" or "world". + int player; + vec3_t origin; // Model's origin in world coordinates. + struct model_s *model; // only for bsp models + struct model_s *studiomodel; // SOLID_BBOX, but studio clip intersections. + vec3_t mins, maxs; // only for non-bsp models + int info; // For client or server to use to identify (index into edicts or cl_entities) + vec3_t angles; // rotated entities need this info for hull testing to work. + + int solid; // Triggers and func_door type WATER brushes are SOLID_NOT + int skin; // BSP Contents for such things like fun_door water brushes. + int rendermode; // So we can ignore glass + + // Complex collision detection. + float frame; + int sequence; + byte controller[4]; + byte blending[2]; + + int movetype; + int takedamage; + int blooddecal; + int team; + int classnumber; + + // For mods + int iuser1; + int iuser2; + int iuser3; + int iuser4; + float fuser1; + float fuser2; + float fuser3; + float fuser4; + vec3_t vuser1; + vec3_t vuser2; + vec3_t vuser3; + vec3_t vuser4; +} physent_t; + + +typedef struct playermove_s +{ + int player_index; // So we don't try to run the PM_CheckStuck nudging too quickly. + qboolean server; // For debugging, are we running physics code on server side? + + qboolean multiplayer; // 1 == multiplayer server + float time; // realtime on host, for reckoning duck timing + float frametime; // Duration of this frame + + vec3_t forward, right, up; // Vectors for angles + // player state + vec3_t origin; // Movement origin. + vec3_t angles; // Movement view angles. + vec3_t oldangles; // Angles before movement view angles were looked at. + vec3_t velocity; // Current movement direction. + vec3_t movedir; // For waterjumping, a forced forward velocity so we can fly over lip of ledge. + vec3_t basevelocity; // Velocity of the conveyor we are standing, e.g. + + // For ducking/dead + vec3_t view_ofs; // Our eye position. + float flDuckTime; // Time we started duck + qboolean bInDuck; // In process of ducking or ducked already? + + // For walking/falling + int flTimeStepSound; // Next time we can play a step sound + int iStepLeft; + + float flFallVelocity; + vec3_t punchangle; + + float flSwimTime; + + float flNextPrimaryAttack; + + int effects; // MUZZLE FLASH, e.g. + + int flags; // FL_ONGROUND, FL_DUCKING, etc. + int usehull; // 0 = regular player hull, 1 = ducked player hull, 2 = point hull + float gravity; // Our current gravity and friction. + float friction; + int oldbuttons; // Buttons last usercmd + float waterjumptime; // Amount of time left in jumping out of water cycle. + qboolean dead; // Are we a dead player? + int deadflag; + int spectator; // Should we use spectator physics model? + int movetype; // Our movement type, NOCLIP, WALK, FLY + + int onground; + int waterlevel; + int watertype; + int oldwaterlevel; + + char sztexturename[256]; + char chtexturetype; + + float maxspeed; + float clientmaxspeed; // Player specific maxspeed + + // For mods + int iuser1; + int iuser2; + int iuser3; + int iuser4; + float fuser1; + float fuser2; + float fuser3; + float fuser4; + vec3_t vuser1; + vec3_t vuser2; + vec3_t vuser3; + vec3_t vuser4; + // world state + // Number of entities to clip against. + int numphysent; + physent_t physents[MAX_PHYSENTS]; + // Number of momvement entities (ladders) + int nummoveent; + // just a list of ladders + physent_t moveents[MAX_MOVEENTS]; + + // All things being rendered, for tracing against things you don't actually collide with + int numvisent; + physent_t visents[ MAX_PHYSENTS ]; + + // input to run through physics. + usercmd_t cmd; + + // Trace results for objects we collided with. + int numtouch; + pmtrace_t touchindex[MAX_PHYSENTS]; + + char physinfo[ MAX_PHYSINFO_STRING ]; // Physics info string + + struct movevars_s *_movevars; + vec3_t player_mins[MAX_MAP_HULLS]; + vec3_t player_maxs[MAX_MAP_HULLS]; + + // Common functions + const char *(*PM_Info_ValueForKey) ( const char *s, const char *key ); + void (*PM_Particle)( float *origin, int color, float life, int zpos, int zvel); + int (*PM_TestPlayerPosition) (float *pos, pmtrace_t *ptrace ); + void (*Con_NPrintf)( int idx, const char *fmt, ... ); + void (*Con_DPrintf)( const char *fmt, ... ); + void (*Con_Printf)( const char *fmt, ... ); + double (*Sys_FloatTime)( void ); + void (*PM_StuckTouch)( int hitent, pmtrace_t *ptraceresult ); + int (*PM_PointContents) (float *p, int *truecontents /*filled in if this is non-null*/ ); + int (*PM_TruePointContents) (float *p); + int (*PM_HullPointContents) ( struct hull_s *hull, int num, float *p); + pmtrace_t (*PM_PlayerTrace) (float *start, float *end, int traceFlags, int ignore_pe ); + struct pmtrace_s *(*PM_TraceLine)( float *start, float *end, int flags, int usehulll, int ignore_pe ); + int32 (*RandomLong)( int32 lLow, int32 lHigh ); + float (*RandomFloat)( float flLow, float flHigh ); + int (*PM_GetModelType)( struct model_s *mod ); + void (*PM_GetModelBounds)( struct model_s *mod, float *mins, float *maxs ); + struct hull_s *(*PM_HullForBsp)( physent_t *pe, float *offset ); + float (*PM_TraceModel)( physent_t *pEnt, float *start, float *end, trace_t *trace ); + int (*COM_FileSize)(const char *filename); + byte *(*COM_LoadFile) (const char *path, int usehunk, int *pLength); + void (*COM_FreeFile) ( void *buffer ); + char *(*memfgets)( byte *pMemFile, int fileSize, int *pFilePos, char *pBuffer, int bufferSize ); + + // Functions + // Run functions for this frame? + qboolean runfuncs; + void (*PM_PlaySound) ( int channel, const char *sample, float volume, float attenuation, int fFlags, int pitch ); + const char *(*PM_TraceTexture) ( int ground, float *vstart, float *vend ); + void (*PM_PlaybackEventFull) ( int flags, int clientindex, unsigned short eventindex, float delay, float *origin, float *angles, float fparam1, float fparam2, int iparam1, int iparam2, int bparam1, int bparam2 ); + + pmtrace_t (*PM_PlayerTraceEx) (float *start, float *end, int traceFlags, int (*pfnIgnore)( physent_t *pe ) ); + int (*PM_TestPlayerPositionEx) (float *pos, pmtrace_t *ptrace, int (*pfnIgnore)( physent_t *pe ) ); + struct pmtrace_s *(*PM_TraceLineEx)( float *start, float *end, int flags, int usehulll, int (*pfnIgnore)( physent_t *pe ) ); +} playermove_t; + +#endif diff --git a/dep/rehlsdk/pm_shared/pm_info.h b/dep/rehlsdk/pm_shared/pm_info.h new file mode 100644 index 0000000..9b705cd --- /dev/null +++ b/dep/rehlsdk/pm_shared/pm_info.h @@ -0,0 +1,25 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +// Physics info string definition + +#ifndef PM_INFO_H +#define PM_INFO_H +#ifdef _WIN32 +#pragma once +#endif + +#define MAX_PHYSINFO_STRING 256 + +#endif // PM_INFO_H diff --git a/dep/rehlsdk/pm_shared/pm_materials.h b/dep/rehlsdk/pm_shared/pm_materials.h new file mode 100644 index 0000000..1b88b2d --- /dev/null +++ b/dep/rehlsdk/pm_shared/pm_materials.h @@ -0,0 +1,36 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +#if !defined( PM_MATERIALSH ) +#define PM_MATERIALSH +#ifdef _WIN32 +#pragma once +#endif + +#define CBTEXTURENAMEMAX 13 // only load first n chars of name + +#define CHAR_TEX_CONCRETE 'C' // texture types +#define CHAR_TEX_METAL 'M' +#define CHAR_TEX_DIRT 'D' +#define CHAR_TEX_VENT 'V' +#define CHAR_TEX_GRATE 'G' +#define CHAR_TEX_TILE 'T' +#define CHAR_TEX_SLOSH 'S' +#define CHAR_TEX_WOOD 'W' +#define CHAR_TEX_COMPUTER 'P' +#define CHAR_TEX_GLASS 'Y' +#define CHAR_TEX_FLESH 'F' +#define CHAR_TEX_SNOW 'N' + +#endif // !PM_MATERIALSH diff --git a/dep/rehlsdk/pm_shared/pm_movevars.h b/dep/rehlsdk/pm_shared/pm_movevars.h new file mode 100644 index 0000000..66c99ee --- /dev/null +++ b/dep/rehlsdk/pm_shared/pm_movevars.h @@ -0,0 +1,47 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +// pm_movevars.h +#if !defined( PM_MOVEVARSH ) +#define PM_MOVEVARSH + +// movevars_t // Physics variables. +typedef struct movevars_s movevars_t; + +struct movevars_s +{ + float gravity; // Gravity for map + float stopspeed; // Deceleration when not moving + float maxspeed; // Max allowed speed + float spectatormaxspeed; + float accelerate; // Acceleration factor + float airaccelerate; // Same for when in open air + float wateraccelerate; // Same for when in water + float friction; + float edgefriction; // Extra friction near dropofs + float waterfriction; // Less in water + float entgravity; // 1.0 + float bounce; // Wall bounce value. 1.0 + float stepsize; // sv_stepsize; + float maxvelocity; // maximum server velocity. + float zmax; // Max z-buffer range (for GL) + float waveHeight; // Water wave height (for GL) + qboolean footsteps; // Play footstep sounds + char skyName[32]; // Name of the sky map + float rollangle; + float rollspeed; + float skycolor_r; // Sky color + float skycolor_g; // + float skycolor_b; // + float skyvec_x; // Sky vector + float skyvec_y; // + float skyvec_z; // +}; + +extern movevars_t movevars; + +#endif diff --git a/dep/rehlsdk/pm_shared/pm_shared.h b/dep/rehlsdk/pm_shared/pm_shared.h new file mode 100644 index 0000000..c860aa8 --- /dev/null +++ b/dep/rehlsdk/pm_shared/pm_shared.h @@ -0,0 +1,38 @@ +/*** +* +* Copyright (c) 1996-2002, Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ + +// +// pm_shared.h +// +#if !defined( PM_SHAREDH ) +#define PM_SHAREDH +#ifdef _WIN32 +#pragma once +#endif + +void PM_Init( struct playermove_s *ppmove ); +void PM_Move ( struct playermove_s *ppmove, int server ); +char PM_FindTextureType( char *name ); + +// Spectator Movement modes (stored in pev->iuser1, so the physics code can get at them) +#define OBS_NONE 0 +#define OBS_CHASE_LOCKED 1 +#define OBS_CHASE_FREE 2 +#define OBS_ROAMING 3 +#define OBS_IN_EYE 4 +#define OBS_MAP_FREE 5 +#define OBS_MAP_CHASE 6 + +#endif diff --git a/dep/rehlsdk/public/FileSystem.h b/dep/rehlsdk/public/FileSystem.h new file mode 100644 index 0000000..eeea8e8 --- /dev/null +++ b/dep/rehlsdk/public/FileSystem.h @@ -0,0 +1,203 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "interface.h" +#include +#include + +// There is only one instance of the IFileSystem interface, +// located in the filesystem_stdio library (filesystem_steam is obsolete). +#ifdef _WIN32 + #define STDIO_FILESYSTEM_LIB "filesystem_stdio.dll" + #define STEAM_FILESYSTEM_LIB "filesystem_steam.dll" +#else + #define STDIO_FILESYSTEM_LIB "filesystem_stdio.so" + #define STEAM_FILESYSTEM_LIB "filesystem_steam.so" +#endif // _WIN32 + +// Forward declarations +typedef FILE *FileHandle_t; +typedef int FileFindHandle_t; +typedef int WaitForResourcesHandle_t; +typedef void (*WarningFunc_t)(const char *fmt, ...); + +// Enums used by the interface +#ifndef FILESYSTEM_INTERNAL_H +typedef enum +{ + FILESYSTEM_SEEK_HEAD = 0, + FILESYSTEM_SEEK_CURRENT, + FILESYSTEM_SEEK_TAIL, +} FileSystemSeek_t; + +enum +{ + FILESYSTEM_INVALID_FIND_HANDLE = -1 +}; + +typedef enum +{ + FILESYSTEM_WARNING = -1, // A problem! + FILESYSTEM_WARNING_QUIET = 0, // Don't print anything + FILESYSTEM_WARNING_REPORTUNCLOSED, // On shutdown, report names of files left unclosed + FILESYSTEM_WARNING_REPORTUSAGE, // Report number of times a file was opened, closed + FILESYSTEM_WARNING_REPORTALLACCESSES // Report all open/close events to console (!slow!) +} FileWarningLevel_t; + +const FileHandle_t FILESYSTEM_INVALID_HANDLE = nullptr; + +#endif // FILESYSTEM_INTERNAL_H + +// turn off any windows defines +#undef GetCurrentDirectory + +// Purpose: Main file system interface +class IFileSystem: public IBaseInterface +{ +public: + // Mount and unmount the filesystem + virtual void Mount() = 0; + virtual void Unmount() = 0; + + // Remove all search paths (including write path?) + virtual void RemoveAllSearchPaths() = 0; + + // Add paths in priority order (mod dir, game dir, ....) + // If one or more .pak files are in the specified directory, then they are + // added after the file system path + // If the path is the relative path to a .bsp file, then any previous .bsp file + // override is cleared and the current .bsp is searched for an embedded PAK file + // and this file becomes the highest priority search path (i.e., it's looked at first + // even before the mod's file system path). + virtual void AddSearchPath(const char *pPath, const char *pathID) = 0; + virtual bool RemoveSearchPath(const char *pPath) = 0; + + // Deletes a file + virtual void RemoveFile(const char *pRelativePath, const char *pathID) = 0; + + // this isn't implementable on STEAM as is. + virtual void CreateDirHierarchy(const char *path, const char *pathID) = 0; + + // File I/O and info + virtual bool FileExists(const char *pFileName) = 0; + virtual bool IsDirectory(const char *pFileName) = 0; + + // opens a file + // if pathID is NULL, all paths will be searched for the file + virtual FileHandle_t Open(const char *pFileName, const char *pOptions, const char *pathID = 0L) = 0; + + virtual void Close(FileHandle_t file) = 0; + + virtual void Seek(FileHandle_t file, int pos, FileSystemSeek_t seekType) = 0; + virtual size_t Tell(FileHandle_t file) = 0; + + virtual size_t Size(FileHandle_t file) = 0; + virtual size_t Size(const char *pFileName) = 0; + + virtual long GetFileTime(const char *pFileName) = 0; + virtual void FileTimeToString(char *pStrip, int maxCharsIncludingTerminator, long fileTime) = 0; + + virtual bool IsOk(FileHandle_t file) = 0; + + virtual void Flush(FileHandle_t file) = 0; + virtual bool EndOfFile(FileHandle_t file) = 0; + + virtual int Read(void *pOutput, int size, FileHandle_t file) = 0; + virtual int Write(void const *pInput, int size, FileHandle_t file) = 0; + virtual char *ReadLine(char *pOutput, int maxChars, FileHandle_t file) = 0; + virtual int FPrintf(FileHandle_t file, const char *fmt, ...) = 0; + + // direct filesystem buffer access + // returns a handle to a buffer containing the file data + // this is the optimal way to access the complete data for a file, + // since the file preloader has probably already got it in memory + virtual void *GetReadBuffer(FileHandle_t file, int *outBufferSize, bool failIfNotInCache) = 0; + virtual void ReleaseReadBuffer(FileHandle_t file, void *readBuffer) = 0; + + // FindFirst/FindNext + virtual const char *FindFirst(const char *pWildCard, FileFindHandle_t *pHandle, const char *pathID = 0L) = 0; + virtual const char *FindNext(FileFindHandle_t handle) = 0; + virtual bool FindIsDirectory(FileFindHandle_t handle) = 0; + virtual void FindClose(FileFindHandle_t handle) = 0; + + virtual void GetLocalCopy(const char *pFileName) = 0; + + virtual const char *GetLocalPath(const char *pFileName, char *pLocalPath, int localPathBufferSize) = 0; + + // Note: This is sort of a secondary feature; but it's really useful to have it here + virtual char *ParseFile(char *pFileBytes, char *pToken, bool *pWasQuoted) = 0; + + // Returns true on success (based on current list of search paths, otherwise false if it can't be resolved) + virtual bool FullPathToRelativePath(const char *pFullpath, char *pRelative) = 0; + + // Gets the current working directory + virtual bool GetCurrentDirectory(char *pDirectory, int maxlen) = 0; + + // Dump to printf/OutputDebugString the list of files that have not been closed + virtual void PrintOpenedFiles() = 0; + + virtual void SetWarningFunc(WarningFunc_t pfnWarning) = 0; + virtual void SetWarningLevel(FileWarningLevel_t level) = 0; + + virtual void LogLevelLoadStarted(const char *name) = 0; + virtual void LogLevelLoadFinished(const char *name) = 0; + virtual int HintResourceNeed(const char *hintlist, int forgetEverything) = 0; + virtual int PauseResourcePreloading() = 0; + virtual int ResumeResourcePreloading() = 0; + virtual int SetVBuf(FileHandle_t stream, char *buffer, int mode, long size) = 0; + virtual void GetInterfaceVersion(char *p, int maxlen) = 0; + virtual bool IsFileImmediatelyAvailable(const char *pFileName) = 0; + + // starts waiting for resources to be available + // returns FILESYSTEM_INVALID_HANDLE if there is nothing to wait on + virtual WaitForResourcesHandle_t WaitForResources(const char *resourcelist) = 0; + + // get progress on waiting for resources; progress is a float [0, 1], complete is true on the waiting being done + // returns false if no progress is available + // any calls after complete is true or on an invalid handle will return false, 0.0f, true + virtual bool GetWaitForResourcesProgress(WaitForResourcesHandle_t handle, float *progress /* out */ , bool *complete /* out */) = 0; + + // cancels a progress call + virtual void CancelWaitForResources(WaitForResourcesHandle_t handle) = 0; + // returns true if the appID has all its caches fully preloaded + virtual bool IsAppReadyForOfflinePlay(int appID) = 0; + + // interface for custom pack files > 4Gb + virtual bool AddPackFile(const char *fullpath, const char *pathID) = 0; + + // open a file but force the data to come from the steam cache, NOT from disk + virtual FileHandle_t OpenFromCacheForRead(const char *pFileName, const char *pOptions, const char *pathID = 0L) = 0; + virtual void AddSearchPathNoWrite(const char *pPath, const char *pathID) = 0; +}; + +// Steam3/Src compat +#define IBaseFileSystem IFileSystem + +#define FILESYSTEM_INTERFACE_VERSION "VFileSystem009" diff --git a/dep/rehlsdk/public/HLTV/IBSPModel.h b/dep/rehlsdk/public/HLTV/IBSPModel.h new file mode 100644 index 0000000..22a6438 --- /dev/null +++ b/dep/rehlsdk/public/HLTV/IBSPModel.h @@ -0,0 +1,45 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class IBaseSystem; +class IBSPModel { +public: + virtual ~IBSPModel() {}; + + virtual void Init(IBaseSystem *system) = 0; + virtual void Clear() = 0; + virtual bool Load(const char *name, bool minimal) = 0; + virtual bool IsValid() = 0; + virtual bool IsMinimal() = 0; + virtual void SetPVS(float *point) = 0; + virtual bool InPVS(float *point) = 0; + virtual bool TraceLine(float *start, float *end, float *impact) = 0; + virtual int TruePointContents(float *point) = 0; +}; diff --git a/dep/rehlsdk/public/HLTV/IClient.h b/dep/rehlsdk/public/HLTV/IClient.h new file mode 100644 index 0000000..fe51503 --- /dev/null +++ b/dep/rehlsdk/public/HLTV/IClient.h @@ -0,0 +1,51 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class IWorld; +class InfoString; +class IClient: virtual public ISystemModule { +public: + virtual ~IClient() {} + + virtual bool Connect(INetSocket *socket, NetAddress *adr, char *userinfo) = 0; + virtual void Send(unsigned char *data, int length, bool isReliable) = 0; + virtual void Disconnect(const char *reason = nullptr) = 0; + virtual void Reconnect() = 0; + virtual void SetWorld(IWorld *world) = 0; + virtual int GetClientType() = 0; + virtual char *GetClientName() = 0; + virtual InfoString *GetUserInfo() = 0; + virtual NetAddress *GetAddress() = 0; + virtual bool IsActive() = 0; + virtual bool IsHearingVoices() = 0; + virtual bool HasChatEnabled() = 0; +}; + +#define CLIENT_INTERFACE_VERSION "client001" diff --git a/dep/rehlsdk/public/HLTV/IDirector.h b/dep/rehlsdk/public/HLTV/IDirector.h new file mode 100644 index 0000000..b840662 --- /dev/null +++ b/dep/rehlsdk/public/HLTV/IDirector.h @@ -0,0 +1,52 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "ISystemModule.h" + +class IWorld; +class IProxy; +class BitBuffer; +class DirectorCmd; +class IObjectContainer; + +class IDirector: virtual public ISystemModule { +public: + virtual ~IDirector() {} + + virtual void NewGame(IWorld *world, IProxy *proxy) = 0; + virtual char *GetModName() = 0; + virtual void WriteCommands(BitBuffer *stream, float startTime, float endTime) = 0; + virtual int AddCommand(DirectorCmd *cmd) = 0; + virtual bool RemoveCommand(int index) = 0; + virtual DirectorCmd *GetLastCommand() = 0; + virtual IObjectContainer *GetCommands() = 0; +}; + +#define DIRECTOR_INTERFACE_VERSION "director001" diff --git a/dep/rehlsdk/public/HLTV/INetChannel.h b/dep/rehlsdk/public/HLTV/INetChannel.h new file mode 100644 index 0000000..dad99f6 --- /dev/null +++ b/dep/rehlsdk/public/HLTV/INetChannel.h @@ -0,0 +1,60 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class INetSocket; +class IBaseSystem; +class INetChannel { +public: + virtual ~INetChannel() {} + + virtual bool Create(IBaseSystem *system, INetSocket *netsocket = nullptr, NetAddress *adr = nullptr) = 0; + virtual NetAddress *GetTargetAddress() = 0; + virtual void Close() = 0; + virtual void Clear() = 0; + virtual void Reset() = 0; + virtual bool IsConnected() = 0; + virtual bool IsReadyToSend() = 0; + virtual bool IsCrashed() = 0; + virtual bool IsTimedOut() = 0; + virtual bool IsFakeChannel() = 0; + virtual bool KeepAlive() = 0; + virtual void SetRate(int newRate) = 0; + virtual void SetUpdateRate(int newupdaterate) = 0; + virtual void SetTimeOut(float time) = 0; + virtual void SetKeepAlive(bool flag) = 0; + virtual float GetIdleTime() = 0; + virtual int GetRate() = 0; + virtual int GetUpdateRate() = 0; + virtual float GetLoss() = 0; + virtual void TransmitOutgoing() = 0; + virtual void ProcessIncoming(unsigned char *data, int size) = 0; + virtual void OutOfBandPrintf(const char *format, ...) = 0; + virtual void FakeAcknowledgement() = 0; +}; diff --git a/dep/rehlsdk/public/HLTV/INetSocket.h b/dep/rehlsdk/public/HLTV/INetSocket.h new file mode 100644 index 0000000..972d441 --- /dev/null +++ b/dep/rehlsdk/public/HLTV/INetSocket.h @@ -0,0 +1,55 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +class INetwork; +class INetChannel; +class NetPacket; + +class INetSocket { +public: + virtual ~INetSocket() {}; + + virtual NetPacket *ReceivePacket() = 0; + virtual void FreePacket(NetPacket *packet) = 0; + virtual bool SendPacket(NetPacket *packet) = 0; + virtual bool SendPacket(NetAddress *to, const void *data, int length) = 0; + virtual void AddPacket(NetPacket *packet) = 0; + virtual bool AddChannel(INetChannel *channel) = 0; + virtual bool RemoveChannel(INetChannel *channel) = 0; + + virtual INetwork *GetNetwork() = 0; + virtual void OutOfBandPrintf(NetAddress *to, const char *format, ...) = 0; + virtual void Flush() = 0; + virtual void GetFlowStats(float *totalIn, float *totalOut) = 0; + virtual bool LeaveGroup(NetAddress *group) = 0; + virtual bool JoinGroup(NetAddress *group) = 0; + virtual void Close() = 0; + virtual int GetPort() = 0; +}; diff --git a/dep/rehlsdk/public/HLTV/INetwork.h b/dep/rehlsdk/public/HLTV/INetwork.h new file mode 100644 index 0000000..05c31a0 --- /dev/null +++ b/dep/rehlsdk/public/HLTV/INetwork.h @@ -0,0 +1,62 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "ISystemModule.h" + +class INetSocket; +class INetwork { +public: + virtual ~INetwork() {}; + + virtual bool Init(IBaseSystem *system, int serial, char *name) = 0; + virtual void RunFrame(double time) = 0; + virtual void ReceiveSignal(ISystemModule *module, unsigned int signal, void *data) = 0; + virtual void ExecuteCommand(int commandID, char *commandLine) = 0; + virtual void RegisterListener(ISystemModule *module) = 0; + virtual void RemoveListener(ISystemModule *module) = 0; + virtual IBaseSystem *GetSystem() = 0; + virtual int GetSerial() = 0; + virtual char *GetStatusLine() = 0; + virtual char *GetType() = 0; + virtual char *GetName() = 0; + virtual int GetState() = 0; + virtual int GetVersion() = 0; + virtual void ShutDown() = 0; + + virtual INetSocket *CreateSocket(int port, bool reuse = false, bool loopback = false) = 0; + virtual bool RemoveSocket(INetSocket *netsocket) = 0; + virtual NetAddress *GetLocalAddress() = 0; + virtual bool ResolveAddress(char *string, NetAddress *address) = 0; + virtual void GetFlowStats(float *totalIn, float *totalOut) = 0; + virtual int GetLastErrorCode() = 0; + virtual char *GetErrorText(int code) = 0; +}; + +#define NETWORK_INTERFACE_VERSION "network001" diff --git a/dep/rehlsdk/public/HLTV/IProxy.h b/dep/rehlsdk/public/HLTV/IProxy.h new file mode 100644 index 0000000..68f0d75 --- /dev/null +++ b/dep/rehlsdk/public/HLTV/IProxy.h @@ -0,0 +1,107 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "ISystemModule.h" +#include "custom.h" + +class IWorld; +class IServer; +class IDirector; +class INetSocket; +class BitBuffer; +class NetAddress; +class IObjectContainer; + +#define MAX_PROXY_CLIENTS 255 + +#define GROUP_CLIENT 0x00001 // Broadcast to client +#define GROUP_PROXY 0x00002 // Broadcast to proxy +#define GROUP_DEMO 0x00004 // Broadcast to demo file +#define GROUP_MULTICAST 0x00008 // Broadcast to multicast (obsolete) +#define GROUP_VOICE 0x00010 // Broadcast to voice enabled clients +#define GROUP_CHAT 0x00020 // Broadcast to chat enabled clients + +#define GROUP_CLIENT_ALL GROUP_CLIENT | GROUP_PROXY | GROUP_DEMO | GROUP_MULTICAST + +enum ChatMode_e : int +{ + CHAT_OFF, // Spectators can't chat. + CHAT_LOCAL, // Only spectators connected to the same proxy can see their chat messages. + CHAT_GLOBAL, // All spectators can chat between each other (then Master and all Relay proxies must have set chatmode 2). +}; + +class IProxy: virtual public ISystemModule { +public: + virtual ~IProxy() {} + + virtual void Reset() = 0; + virtual void Broadcast(byte *data, int length, int groupType, bool isReliable) = 0; + virtual void IncreaseCheering(int votes) = 0; + virtual void ParseStatusMsg(BitBuffer *stream) = 0; + virtual void ParseStatusReport(NetAddress *from, BitBuffer *stream) = 0; + virtual bool ProcessConnectionlessMessage(NetAddress *from, BitBuffer *stream) = 0; + virtual void ChatCommentator(char *nick, char *text) = 0; + virtual void ChatSpectator(char *nick, char *text) = 0; + virtual void CountLocalClients(int &spectators, int &proxies) = 0; + virtual struct resource_s *AddResource(char *fileName, resourcetype_t type, char *asFileName = nullptr) = 0; + virtual bool IsLanOnly() = 0; + virtual bool IsMaster() = 0; + virtual bool IsActive() = 0; + virtual bool IsPublicGame() = 0; + virtual bool IsPasswordProtected() = 0; + virtual bool IsStressed() = 0; + virtual void SetDelay(float seconds) = 0; + virtual void SetClientTime(double time, bool relative) = 0; + virtual void SetClientTimeScale(float scale) = 0; + virtual void SetMaxRate(int rate) = 0; + virtual void SetMaxLoss(float maxloss) = 0; + virtual void SetMaxUpdateRate(int updaterate) = 0; + virtual bool SetMaxClients(int number) = 0; + virtual void SetRegion(unsigned char region) = 0; + virtual float GetDelay() = 0; + virtual double GetSpectatorTime() = 0; + virtual double GetProxyTime() = 0; + virtual int GetMaxClients() = 0; + virtual IWorld *GetWorld() = 0; + virtual IServer *GetServer() = 0; + virtual IDirector *GetDirector() = 0; + virtual INetSocket *GetSocket() = 0; + virtual ChatMode_e GetChatMode() = 0; + virtual void GetStatistics(int &proxies, int &slots, int &spectators) = 0; + virtual int GetMaxRate() = 0; + virtual int GetMaxUpdateRate() = 0; + virtual struct resource_s *GetResource(char *fileName) = 0; + virtual int GetDispatchMode() = 0; + virtual unsigned char GetRegion() = 0; + virtual IObjectContainer *GetClients() = 0; + virtual bool WriteSignonData(int type, BitBuffer *stream) = 0; +}; + +#define PROXY_INTERFACE_VERSION "proxy001" diff --git a/dep/rehlsdk/public/HLTV/IServer.h b/dep/rehlsdk/public/HLTV/IServer.h new file mode 100644 index 0000000..37640cf --- /dev/null +++ b/dep/rehlsdk/public/HLTV/IServer.h @@ -0,0 +1,101 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "ISystemModule.h" + +class IWorld; +class IProxy; +class IDirector; +class INetSocket; +class ISystemModule; +class IBaseSystem; + +class NetAddress; +class InfoString; +class BitBuffer; + +class IServer { +public: + virtual ~IServer() {} + + virtual bool Init(IBaseSystem *system, int serial, char *name) = 0; + virtual void RunFrame(double time) = 0; + virtual void ReceiveSignal(ISystemModule *module, unsigned int signal, void *data) = 0; + virtual void ExecuteCommand(int commandID, char *commandLine) = 0; + virtual void RegisterListener(ISystemModule *module) = 0; + virtual void RemoveListener(ISystemModule *module) = 0; + virtual IBaseSystem *GetSystem() = 0; + virtual int GetSerial() = 0; + virtual char *GetStatusLine() = 0; + virtual char *GetType() = 0; + virtual char *GetName() = 0; + virtual int GetState() = 0; + virtual int GetVersion() = 0; + virtual void ShutDown() = 0; + + virtual bool Connect(IWorld *world, NetAddress *adr, INetSocket *socket) = 0; + virtual bool LoadDemo(IWorld *world, char *filename, bool forceHLTV, bool continuous) = 0; + virtual void Reconnect() = 0; + virtual void Disconnect() = 0; + virtual void Retry() = 0; + virtual void StopRetry() = 0; + virtual void SendStringCommand(char *command) = 0; + virtual void SendHLTVCommand(BitBuffer *msg) = 0; + virtual bool IsConnected() = 0; + virtual bool IsDemoFile() = 0; + virtual bool IsGameServer() = 0; + virtual bool IsRelayProxy() = 0; + virtual bool IsVoiceBlocking() = 0; + virtual void SetProxy(IProxy *proxy) = 0; + virtual void SetDirector(IDirector *director) = 0; + virtual void SetPlayerName(char *newName) = 0; + virtual void SetDelayReconnect(bool state) = 0; + virtual void SetAutoRetry(bool state) = 0; + virtual void SetVoiceBlocking(bool state) = 0; + virtual void SetRate(int rate) = 0; + virtual void SetUpdateRate(int updaterate) = 0; + virtual void SetUserInfo(char *key, char *value) = 0; + virtual bool SetProtocol(int version) = 0; + virtual void SetGameDirectory(const char *defaultDir, const char *gameDir = nullptr) = 0; + virtual int GetRate() = 0; + virtual int GetUpdateRate() = 0; + virtual InfoString *GetServerInfoString() = 0; + virtual char *GetPlayerName() = 0; + virtual float GetTime() = 0; + virtual IWorld *GetWorld() = 0; + virtual char *GetDemoFileName() = 0; + virtual NetAddress *GetAddress() = 0; + virtual char *GetHostName() = 0; + virtual bool GetAutoRetry() = 0; + virtual float GetPacketLoss() = 0; + virtual int GetProtocol() = 0; +}; + +#define SERVER_INTERFACE_VERSION "server001" diff --git a/dep/rehlsdk/public/HLTV/IWorld.h b/dep/rehlsdk/public/HLTV/IWorld.h new file mode 100644 index 0000000..8e24c26 --- /dev/null +++ b/dep/rehlsdk/public/HLTV/IWorld.h @@ -0,0 +1,163 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "IBSPModel.h" +#include "IDirector.h" +#include "ISystemModule.h" +#include "common/ServerInfo.h" + +#include "pm_movevars.h" +#include "usermsg.h" +#include "entity_state.h" + +typedef struct frame_s +{ + float time; + unsigned int seqnr; + unsigned char *data; + void *entities; + unsigned int entitiesSize; + unsigned int entitynum; + void *clientData; + unsigned int clientDataSize; + unsigned char *events; + unsigned int eventsSize; + unsigned int eventnum; + unsigned char *reliableData; + unsigned int reliableDataSize; + unsigned char *unreliableData; + unsigned int unreliableDataSize; + unsigned char *userMessages; + unsigned int userMessagesSize; + unsigned char *voiceData; + unsigned int voiceDataSize; + unsigned char *demoData; + unsigned int demoDataSize; + void *demoInfo; + unsigned int delta; +} frame_t; + +class InfoString; +class NetAddress; + +class IWorld { +public: + virtual ~IWorld() {} + + virtual bool Init(IBaseSystem *system, int serial, char *name) = 0; + virtual void RunFrame(double time) = 0; + virtual void ReceiveSignal(ISystemModule *module, unsigned int signal, void *data) = 0; + virtual void ExecuteCommand(int commandID, char *commandLine) = 0; + virtual void RegisterListener(ISystemModule *module) = 0; + virtual void RemoveListener(ISystemModule *module) = 0; + virtual IBaseSystem *GetSystem() = 0; + virtual int GetSerial() = 0; + virtual char *GetStatusLine() = 0; + virtual char *GetType() = 0; + virtual char *GetName() = 0; + virtual int GetState() = 0; + virtual int GetVersion() = 0; + virtual void ShutDown() = 0; + + virtual double GetTime() = 0; + virtual NetAddress *GetGameServerAddress() = 0; + virtual char *GetLevelName() = 0; + virtual char *GetGameDir() = 0; + virtual frame_t *GetFrameByTime(double time) = 0; + virtual frame_t *GetFrameBySeqNr(unsigned int seqnr) = 0; + virtual frame_t *GetLastFrame() = 0; + virtual frame_t *GetFirstFrame() = 0; + virtual int GetServerCount() = 0; + virtual int GetSlotNumber() = 0; + virtual int GetMaxClients() = 0; + virtual int GetNumPlayers() = 0; + virtual IBSPModel *GetWorldModel() = 0; + virtual InfoString *GetServerInfoString() = 0; + virtual bool GetPlayerInfoString(int playerNum, InfoString *infoString) = 0; + virtual UserMsg *GetUserMsg(int msgNumber) = 0; + virtual char *GetHostName() = 0; + virtual serverinfo_t *GetServerInfo() = 0; + virtual bool IsPlayerIndex(int index) = 0; + virtual bool IsVoiceEnabled() = 0; + virtual bool IsActive() = 0; + virtual bool IsPaused() = 0; + virtual bool IsComplete() = 0; + virtual bool IsHLTV() = 0; + virtual void Reset() = 0; + virtual void SetServerInfo(int protocol, CRC32_t nserverCRC, byte *nclientdllmd5, int nmaxclients, int nplayernum, int ngametype, char *ngamedir, char *nservername, char *nlevelname) = 0; + virtual void SetServerInfoString(char *infostring) = 0; + virtual void SetServerInfo(serverinfo_t *serverinfo) = 0; + virtual void UpdateServerInfo() = 0; + virtual void SetPaused(bool state) = 0; + virtual void SetTime(double newTime) = 0; + virtual void SetBufferSize(float seconds) = 0; + virtual void SetVoiceEnabled(bool state) = 0; + virtual void SetMoveVars(movevars_t *nmovevars) = 0; + virtual void SetCDInfo(int ncdtrack, int nlooptrack) = 0; + virtual void SetHLTV(bool state) = 0; + virtual void SetExtraInfo(char *nclientfallback, int nallowCheats) = 0; + virtual void SetViewEntity(int nviewentity) = 0; + virtual void SetGameServerAddress(NetAddress *address) = 0; + virtual void SetHostName(char *name) = 0; + virtual void NewGame(int newServerCount) = 0; + virtual void FinishGame() = 0; + virtual bool SaveAsDemo(char *filename, IDirector *director) = 0; + virtual void StopGame() = 0; + virtual int FindUserMsgByName(char *name) = 0; + virtual void ParseDeltaDescription(BitBuffer *stream) = 0; + virtual void ParseBaseline(BitBuffer *stream) = 0; + virtual void ParseEvent(BitBuffer *stream) = 0; + virtual void ParseClientData(BitBuffer *stream, unsigned int deltaSeqNr, BitBuffer *to, clientdata_t *clientData) = 0; + virtual bool GetUncompressedFrame(unsigned int seqNr, frame_t *frame) = 0; + virtual bool UncompressEntitiesFromStream(frame_t *frame, BitBuffer *stream) = 0; + virtual bool UncompressEntitiesFromStream(frame_t *frame, BitBuffer *stream, unsigned int from) = 0; + virtual bool GetClientData(unsigned int SeqNr, clientdata_t *clientData) = 0; + virtual bool GetClientData(frame_t *frame, clientdata_t *clientData) = 0; + virtual int AddFrame(frame_t *newFrame) = 0; + virtual bool AddResource(resource_t *resource) = 0; + virtual void AddLightStyle(int index, char *style) = 0; + virtual bool AddSignonData(unsigned char type, unsigned char *data, int size) = 0; + virtual bool AddUserMessage(int msgNumber, int size, char *name) = 0; + virtual void AddBaselineEntity(int index, entity_state_t *ent) = 0; + virtual void AddInstancedBaselineEntity(int index, entity_state_t *ent) = 0; + virtual void UpdatePlayer(int playerNum, int userId, char *infostring, char *hashedcdkey) = 0; + virtual void WriteFrame(frame_t *frame, unsigned int lastFrameSeqnr, BitBuffer *reliableStream, BitBuffer *unreliableStream, unsigned int deltaSeqNr, unsigned int clientDelta, bool addVoice) = 0; + virtual void WriteNewData(BitBuffer *stream) = 0; + virtual void WriteClientUpdate(BitBuffer *stream, int playerIndex) = 0; + virtual void WriteMovevars(BitBuffer *stream) = 0; + virtual void WriteSigonData(BitBuffer *stream) = 0; + virtual void WriteLightStyles(BitBuffer *stream) = 0; + virtual int RemoveFrames(unsigned int startSeqNr, unsigned int endSeqNr) = 0; + virtual int DuplicateFrames(unsigned int startSeqNr, unsigned int endSeqNr) = 0; + virtual int MoveFrames(unsigned int startSeqNr, unsigned int endSeqNr, double destSeqnr) = 0; + virtual int RevertFrames(unsigned int startSeqNr, unsigned int endSeqNr) = 0; +}; + +#define WORLD_INTERFACE_VERSION "world001" diff --git a/dep/rehlsdk/public/asmlib.h b/dep/rehlsdk/public/asmlib.h new file mode 100644 index 0000000..c1bc9af --- /dev/null +++ b/dep/rehlsdk/public/asmlib.h @@ -0,0 +1,123 @@ +/*************************** asmlib.h *************************************** +* Author: Agner Fog +* Date created: 2003-12-12 +* Last modified: 2013-10-04 +* Project: asmlib.zip +* Source URL: www.agner.org/optimize +* +* Description: +* Header file for the asmlib function library. +* This library is available in many versions for different platforms. +* See asmlib-instructions.pdf for details. +* +* (c) Copyright 2003 - 2013 by Agner Fog. +* GNU General Public License http://www.gnu.org/licenses/gpl.html +*****************************************************************************/ + + +#ifndef ASMLIB_H +#define ASMLIB_H + + +/*********************************************************************** +Define compiler-specific types and directives +***********************************************************************/ + +// Define type size_t +#ifndef _SIZE_T_DEFINED +#include "stddef.h" +#endif + +// Define integer types with known size: int32_t, uint32_t, int64_t, uint64_t. +// If this doesn't work then insert compiler-specific definitions here: +#if defined(__GNUC__) || (defined(_MSC_VER) && _MSC_VER >= 1600) + // Compilers supporting C99 or C++0x have stdint.h defining these integer types + #include + #define INT64_SUPPORTED // Remove this if the compiler doesn't support 64-bit integers +#elif defined(_MSC_VER) + // Older Microsoft compilers have their own definition + typedef signed __int16 int16_t; + typedef unsigned __int16 uint16_t; + typedef signed __int32 int32_t; + typedef unsigned __int32 uint32_t; + typedef signed __int64 int64_t; + typedef unsigned __int64 uint64_t; + #define INT64_SUPPORTED // Remove this if the compiler doesn't support 64-bit integers +#else + // This works with most compilers + typedef signed short int int16_t; + typedef unsigned short int uint16_t; + typedef signed int int32_t; + typedef unsigned int uint32_t; + typedef long long int64_t; + typedef unsigned long long uint64_t; + #define INT64_SUPPORTED // Remove this if the compiler doesn't support 64-bit integers +#endif + + +// Turn off name mangling +#ifdef __cplusplus +extern "C" { +#endif + +/*********************************************************************** +Function prototypes, memory and string functions +***********************************************************************/ +void * A_memcpy (void * dest, const void * src, size_t count); // Copy count bytes from src to dest +void * A_memmove(void * dest, const void * src, size_t count); // Same as memcpy, allows overlap between src and dest +void * A_memset (void * dest, int c, size_t count); // Set count bytes in dest to (char)c +int A_memcmp (const void * buf1, const void * buf2, size_t num); // Compares two blocks of memory +size_t GetMemcpyCacheLimit(void); // Data blocks bigger than this will be copied uncached by memcpy and memmove +void SetMemcpyCacheLimit(size_t); // Change limit in GetMemcpyCacheLimit +size_t GetMemsetCacheLimit(void); // Data blocks bigger than this will be stored uncached by memset +void SetMemsetCacheLimit(size_t); // Change limit in GetMemsetCacheLimit +char * A_strcat (char * dest, const char * src); // Concatenate strings dest and src. Store result in dest +char * A_strcpy (char * dest, const char * src); // Copy string src to dest +size_t A_strlen (const char * str); // Get length of zero-terminated string +int A_strcmp (const char * a, const char * b); // Compare strings. Case sensitive +int A_stricmp (const char *string1, const char *string2); // Compare strings. Case insensitive for A-Z only +char * A_strstr (char * haystack, const char * needle); // Search for substring in string +void A_strtolower(char * string); // Convert string to lower case for A-Z only +void A_strtoupper(char * string); // Convert string to upper case for a-z only +size_t A_substring(char * dest, const char * source, size_t pos, size_t len); // Copy a substring for source into dest +size_t A_strspn (const char * str, const char * set); // Find span of characters that belong to set +size_t A_strcspn(const char * str, const char * set); // Find span of characters that don't belong to set +size_t strCountInSet(const char * str, const char * set); // Count characters that belong to set +size_t strcount_UTF8(const char * str); // Counts the number of characters in a UTF-8 encoded string + + +/*********************************************************************** +Function prototypes, miscellaneous functions +***********************************************************************/ +uint32_t A_popcount(uint32_t x); // Count 1-bits in 32-bit integer +int RoundD (double x); // Round to nearest or even +int RoundF (float x); // Round to nearest or even +int InstructionSet(void); // Tell which instruction set is supported +char * ProcessorName(void); // ASCIIZ text describing microprocessor +void CpuType(int * vendor, int * family, int * model); // Get CPU vendor, family and model +size_t DataCacheSize(int level); // Get size of data cache +void A_DebugBreak(void); // Makes a debug breakpoint +#ifdef INT64_SUPPORTED + uint64_t ReadTSC(void); // Read microprocessor internal clock (64 bits) +#else + uint32_t ReadTSC(void); // Read microprocessor internal clock (only 32 bits supported by compiler) +#endif +void cpuid_ex (int abcd[4], int eax, int ecx); // call CPUID instruction +static inline void cpuid_abcd (int abcd[4], int eax) { + cpuid_ex(abcd, eax, 0);} + +#ifdef __cplusplus +} // end of extern "C" + +// Define overloaded versions if compiling as C++ + +static inline int Round (double x) { // Overload name Round + return RoundD(x);} +static inline int Round (float x) { // Overload name Round + return RoundF(x);} +static inline const char * A_strstr(const char * haystack, const char * needle) { + return A_strstr((char*)haystack, needle);} // Overload A_strstr with const char * version + +#endif // __cplusplus + +#endif // ASMLIB_H diff --git a/dep/rehlsdk/public/basetypes.h b/dep/rehlsdk/public/basetypes.h new file mode 100644 index 0000000..4a1e0d5 --- /dev/null +++ b/dep/rehlsdk/public/basetypes.h @@ -0,0 +1,78 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#ifndef BASETYPES_H +#define BASETYPES_H +#ifdef _WIN32 +#pragma once +#endif + +#include "osconfig.h" +#include "commonmacros.h" + +#include "archtypes.h" +#include "mathlib.h" + +// For backward compatibilty only... +#include "tier0/platform.h" + +// stdio.h +#ifndef NULL +#define NULL 0 +#endif + +// Pad a number so it lies on an N byte boundary. +// So PAD_NUMBER(0,4) is 0 and PAD_NUMBER(1,4) is 4 +#define PAD_NUMBER(number, boundary) \ + (((number) + ((boundary) - 1)) / (boundary)) * (boundary) + +#ifndef FALSE +#define FALSE 0 +#define TRUE (!FALSE) +#endif + +typedef int BOOL; +typedef int qboolean; +typedef unsigned long ULONG; +typedef unsigned char BYTE; +typedef unsigned char byte; +typedef unsigned short word; + +typedef float vec_t; + +#ifndef UNUSED +#define UNUSED(x) (x = x) // for pesky compiler / lint warnings +#endif + +struct vrect_t +{ + int x, y, width, height; + vrect_t *pnext; +}; + +#endif // BASETYPES_H diff --git a/dep/rehlsdk/public/cl_dll/IGameClientExports.h b/dep/rehlsdk/public/cl_dll/IGameClientExports.h new file mode 100644 index 0000000..d45d53a --- /dev/null +++ b/dep/rehlsdk/public/cl_dll/IGameClientExports.h @@ -0,0 +1,34 @@ +//========= Copyright © 1996-2002, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#ifndef IGAMECLIENTEXPORTS_H +#define IGAMECLIENTEXPORTS_H +#ifdef _WIN32 +#pragma once +#endif + +#include "interface.h" + +//----------------------------------------------------------------------------- +// Purpose: Exports a set of functions for the GameUI interface to interact with the game client +//----------------------------------------------------------------------------- +class IGameClientExports : public IBaseInterface +{ +public: + // returns the name of the server the user is connected to, if any + virtual const char *GetServerHostName() = 0; + + // ingame voice manipulation + virtual bool IsPlayerGameVoiceMuted(int playerIndex) = 0; + virtual void MutePlayerGameVoice(int playerIndex) = 0; + virtual void UnmutePlayerGameVoice(int playerIndex) = 0; +}; + +#define GAMECLIENTEXPORTS_INTERFACE_VERSION "GameClientExports001" + + +#endif // IGAMECLIENTEXPORTS_H diff --git a/dep/rehlsdk/public/commonmacros.h b/dep/rehlsdk/public/commonmacros.h new file mode 100644 index 0000000..e82bfd6 --- /dev/null +++ b/dep/rehlsdk/public/commonmacros.h @@ -0,0 +1,30 @@ +#ifndef COMMONMACROS_H +#define COMMONMACROS_H +#pragma once + + +// ------------------------------------------------------- +// +// commonmacros.h +// +// This should contain ONLY general purpose macros that are +// appropriate for use in engine/launcher/all tools +// +// ------------------------------------------------------- + +#include "osconfig.h" +// Makes a 4-byte "packed ID" int out of 4 characters +#define MAKEID(d,c,b,a) ( ((int)(a) << 24) | ((int)(b) << 16) | ((int)(c) << 8) | ((int)(d)) ) + +// Compares a string with a 4-byte packed ID constant +#define STRING_MATCHES_ID( p, id ) ( (*((int *)(p)) == (id) ) ? true : false ) +#define ID_TO_STRING( id, p ) ( (p)[3] = (((id)>>24) & 0xFF), (p)[2] = (((id)>>16) & 0xFF), (p)[1] = (((id)>>8) & 0xFF), (p)[0] = (((id)>>0) & 0xFF) ) + +#define ARRAYSIZE(p) (sizeof(p)/sizeof(p[0])) + +// Keeps clutter down a bit, when using a float as a bit-vector +#define SetBits(flBitVector, bits) ((flBitVector) = (int)(flBitVector) | (bits)) +#define ClearBits(flBitVector, bits) ((flBitVector) = (int)(flBitVector) & ~(bits)) +#define FBitSet(flBitVector, bit) ((int)(flBitVector) & (bit)) + +#endif // COMMONMACROS_H diff --git a/dep/rehlsdk/public/engine_hlds_api.h b/dep/rehlsdk/public/engine_hlds_api.h new file mode 100644 index 0000000..53ceb36 --- /dev/null +++ b/dep/rehlsdk/public/engine_hlds_api.h @@ -0,0 +1,49 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "interface.h" + +#ifdef _WIN32 + #define ENGINE_LIB "swds.dll" +#else + #define ENGINE_LIB "engine_i486.so" +#endif // _WIN32 + +class IDedicatedServerAPI : public IBaseInterface +{ +public: + virtual bool Init(char *basedir, char *cmdline, CreateInterfaceFn launcherFactory, CreateInterfaceFn filesystemFactory) = 0; + virtual int Shutdown() = 0; + virtual bool RunFrame() = 0; + virtual void AddConsoleText(char *text) = 0; + virtual void UpdateStatus(float *fps, int *nActive, int *nMaxPlayers, char *pszMap) = 0; +}; + +#define VENGINE_HLDS_API_VERSION "VENGINE_HLDS_API_VERSION002" diff --git a/dep/rehlsdk/public/engine_launcher_api.h b/dep/rehlsdk/public/engine_launcher_api.h new file mode 100644 index 0000000..1c60e6a --- /dev/null +++ b/dep/rehlsdk/public/engine_launcher_api.h @@ -0,0 +1,46 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "interface.h" + +#ifdef _WIN32 + #define ENGINE_CLIENT_LIB "hw.dll" // OpenGL/D3D video mode + #define ENGINE_CLIENT_SOFT_LIB "sw.dll" // Software video mode +#else + #define ENGINE_CLIENT_LIB "hw.so" +#endif // _WIN32 + +class IEngineAPI : public IBaseInterface +{ +public: + virtual int Run(void *instance, char *basedir, char *cmdline, char *postRestartCmdLineArgs, CreateInterfaceFn launcherFactory, CreateInterfaceFn filesystemFactory) = 0; +}; + +#define VENGINE_LAUNCHER_API_VERSION "VENGINE_LAUNCHER_API_VERSION002" diff --git a/dep/rehlsdk/public/icommandline.h b/dep/rehlsdk/public/icommandline.h new file mode 100644 index 0000000..a06ba94 --- /dev/null +++ b/dep/rehlsdk/public/icommandline.h @@ -0,0 +1,47 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +// Interface to engine command line +class ICommandLine { +public: + virtual void CreateCmdLine(const char *commandline) = 0; + virtual void CreateCmdLine(int argc, const char **argv) = 0; + virtual const char *GetCmdLine() const = 0; + + // Check whether a particular parameter exists + virtual const char *CheckParm(const char *psz, char **ppszValue = nullptr) const = 0; + virtual void RemoveParm(const char *pszParm) = 0; + virtual void AppendParm(const char *pszParm, const char *pszValues) = 0; + + virtual void SetParm(const char *pszParm, const char *pszValues) = 0; + virtual void SetParm(const char *pszParm, int iValue) = 0; +}; + +ICommandLine *CommandLine(); diff --git a/dep/rehlsdk/public/idedicatedexports.h b/dep/rehlsdk/public/idedicatedexports.h new file mode 100644 index 0000000..5cbe36c --- /dev/null +++ b/dep/rehlsdk/public/idedicatedexports.h @@ -0,0 +1,40 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "interface.h" + +class IDedicatedExports : public IBaseInterface +{ +public: + virtual ~IDedicatedExports() {}; + virtual void Sys_Printf(char *text) = 0; +}; + +#define VENGINE_DEDICATEDEXPORTS_API_VERSION "VENGINE_DEDICATEDEXPORTS_API_VERSION001" diff --git a/dep/rehlsdk/public/interface.cpp b/dep/rehlsdk/public/interface.cpp new file mode 100644 index 0000000..c496d05 --- /dev/null +++ b/dep/rehlsdk/public/interface.cpp @@ -0,0 +1,244 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#include "interface.h" + +#ifdef _WIN32 + #define WIN32_LEAN_AND_MEAN + #include "windows.h" +#endif // _WIN32 + +// InterfaceReg +InterfaceReg *InterfaceReg::s_pInterfaceRegs = nullptr; + +InterfaceReg::InterfaceReg(InstantiateInterfaceFn fn, const char *pName) : m_pName(pName) +{ + m_CreateFn = fn; + m_pNext = s_pInterfaceRegs; + s_pInterfaceRegs = this; +} + +// This is the primary exported function by a dll, referenced by name via dynamic binding +// that exposes an opqaue function pointer to the interface. +// +// We have the Internal variant so Sys_GetFactoryThis() returns the correct internal +// symbol under GCC/Linux/Mac as CreateInterface is DLL_EXPORT so its global so the loaders +// on those OS's pick exactly 1 of the CreateInterface symbols to be the one that is process wide and +// all Sys_GetFactoryThis() calls find that one, which doesn't work. Using the internal walkthrough here +// makes sure Sys_GetFactoryThis() has the dll specific symbol and GetProcAddress() returns the module specific +// function for CreateInterface again getting the dll specific symbol we need. +EXPORT_FUNCTION IBaseInterface *CreateInterface(const char *pName, int *pReturnCode) +{ + InterfaceReg *pCur; + for (pCur = InterfaceReg::s_pInterfaceRegs; pCur; pCur = pCur->m_pNext) + { + if (strcmp(pCur->m_pName, pName) == 0) + { + if (pReturnCode) + { + *pReturnCode = IFACE_OK; + } + + return pCur->m_CreateFn(); + } + } + + if (pReturnCode) + { + *pReturnCode = IFACE_FAILED; + } + + return nullptr; +} + +#ifndef _WIN32 +// Linux doesn't have this function so this emulates its functionality +void *GetModuleHandle(const char *name) +{ + void *handle; + if (name == nullptr) + { + // hmm, how can this be handled under linux.... + // is it even needed? + return nullptr; + } + + if ((handle = dlopen(name, RTLD_NOW)) == nullptr) + { + //printf("Error:%s\n",dlerror()); + // couldn't open this file + return nullptr; + } + + // read "man dlopen" for details + // in short dlopen() inc a ref count + // so dec the ref count by performing the close + dlclose(handle); + return handle; +} +#endif // _WIN32 + +// Purpose: returns a pointer to a function, given a module +// Input : pModuleName - module name +// *pName - proc name +//static hlds_run wants to use this function +void *Sys_GetProcAddress(const char *pModuleName, const char *pName) +{ + return GetProcAddress(GetModuleHandle(pModuleName), pName); +} + +// Purpose: returns a pointer to a function, given a module +// Input : pModuleName - module name +// *pName - proc name +// hlds_run wants to use this function +void *Sys_GetProcAddress(void *pModuleHandle, const char *pName) +{ + return GetProcAddress((HMODULE)pModuleHandle, pName); +} + +// Purpose: Returns a module handle by its name. +// Input : pModuleName - module name +// Output : the module handle or NULL in case of an error +CSysModule *Sys_GetModuleHandle(const char *pModuleName) +{ + return reinterpret_cast(GetModuleHandle(pModuleName)); +} + +// Purpose: Loads a DLL/component from disk and returns a handle to it +// Input : *pModuleName - filename of the component +// Output : opaque handle to the module (hides system dependency) +CSysModule *Sys_LoadModule(const char *pModuleName) +{ +#ifdef _WIN32 + HMODULE hDLL = LoadLibrary(pModuleName); +#else + HMODULE hDLL = nullptr; + char szAbsoluteModuleName[1024]; + if (pModuleName[0] != '/') + { + char szCwd[1024]; + getcwd(szCwd, sizeof(szCwd)); + if (szCwd[strlen(szCwd) - 1] == '/') + szCwd[strlen(szCwd) - 1] = '\0'; + + _snprintf(szAbsoluteModuleName, sizeof(szAbsoluteModuleName), "%s/%s", szCwd, pModuleName); + hDLL = dlopen(szAbsoluteModuleName, RTLD_NOW); + } + else + { + _snprintf(szAbsoluteModuleName, sizeof(szAbsoluteModuleName), "%s", pModuleName); + hDLL = dlopen(pModuleName, RTLD_NOW); + } +#endif // _WIN32 + + if (!hDLL) + { + char str[512]; + +#if defined(_WIN32) + _snprintf(str, sizeof(str), "%s.dll", pModuleName); + hDLL = LoadLibrary(str); +#elif defined(OSX) + printf("Error: %s\n", dlerror()); + _snprintf(str, sizeof(str), "%s.dylib", szAbsoluteModuleName); + hDLL = dlopen(str, RTLD_NOW); +#else + printf("Error: %s\n", dlerror()); + _snprintf(str, sizeof(str), "%s.so", szAbsoluteModuleName); + hDLL = dlopen(str, RTLD_NOW); +#endif + } + + return reinterpret_cast(hDLL); +} + +// Purpose: Unloads a DLL/component from +// Input : *pModuleName - filename of the component +// Output : opaque handle to the module (hides system dependency) +void Sys_UnloadModule(CSysModule *pModule) +{ + if (!pModule) + return; + + HMODULE hDLL = reinterpret_cast(pModule); + +#ifdef _WIN32 + FreeLibrary(hDLL); +#else + dlclose(hDLL); +#endif // _WIN32 +} + +// Purpose: returns a pointer to a function, given a module +// Input : module - windows HMODULE from Sys_LoadModule() +// *pName - proc name +// Output : factory for this module +CreateInterfaceFn Sys_GetFactory(CSysModule *pModule) +{ + if (!pModule) + return nullptr; + + return reinterpret_cast(Sys_GetProcAddress(pModule, CREATEINTERFACE_PROCNAME)); +} + +// Purpose: returns the instance of this module +// Output : CreateInterfaceFn +CreateInterfaceFn Sys_GetFactoryThis() +{ + return CreateInterface; +} + +// Purpose: returns the instance of the named module +// Input : *pModuleName - name of the module +// Output : CreateInterfaceFn - instance of that module +CreateInterfaceFn Sys_GetFactory(const char *pModuleName) +{ + return reinterpret_cast(Sys_GetProcAddress(pModuleName, CREATEINTERFACE_PROCNAME)); +} + +// Purpose: finds a particular interface in the factory set +void *InitializeInterface(char const *interfaceName, CreateInterfaceFn *factoryList, int numFactories) +{ + void *retval; + + for (int i = 0; i < numFactories; i++) + { + CreateInterfaceFn factory = factoryList[ i ]; + if (!factory) + continue; + + retval = factory(interfaceName, nullptr); + if (retval) + return retval; + } + + // No provider for requested interface!!! + // assert(!"No provider for requested interface!!!"); + + return nullptr; +} diff --git a/dep/rehlsdk/public/interface.h b/dep/rehlsdk/public/interface.h new file mode 100644 index 0000000..5ac6a44 --- /dev/null +++ b/dep/rehlsdk/public/interface.h @@ -0,0 +1,124 @@ +// This header defines the interface convention used in the valve engine. +// To make an interface and expose it: +// 1. Derive from IBaseInterface. +// 2. The interface must be ALL pure virtuals, and have no data members. +// 3. Define a name for it. +// 4. In its implementation file, use EXPOSE_INTERFACE or EXPOSE_SINGLE_INTERFACE. + +// Versioning +// There are two versioning cases that are handled by this: +// 1. You add functions to the end of an interface, so it is binary compatible with the previous interface. In this case, +// you need two EXPOSE_INTERFACEs: one to expose your class as the old interface and one to expose it as the new interface. +// 2. You update an interface so it's not compatible anymore (but you still want to be able to expose the old interface +// for legacy code). In this case, you need to make a new version name for your new interface, and make a wrapper interface and +// expose it for the old interface. + +#pragma once + +#ifndef _WIN32 + +#include // dlopen, dlclose, et al +#include + +#define HMODULE void * +#define GetProcAddress dlsym + +#define _snprintf snprintf + +#endif // _WIN32 + +void *Sys_GetProcAddress(const char *pModuleName, const char *pName); +void *Sys_GetProcAddress(void *pModuleHandle, const char *pName); + +// All interfaces derive from this. +class IBaseInterface +{ +public: + virtual ~IBaseInterface() {} +}; + +#define CREATEINTERFACE_PROCNAME "CreateInterface" + +typedef IBaseInterface *(*CreateInterfaceFn)(const char *pName, int *pReturnCode); +typedef IBaseInterface *(*InstantiateInterfaceFn)(); + +// Used internally to register classes. +class InterfaceReg +{ +public: + InterfaceReg(InstantiateInterfaceFn fn, const char *pName); + +public: + + InstantiateInterfaceFn m_CreateFn; + const char *m_pName; + + InterfaceReg *m_pNext; // For the global list. + static InterfaceReg *s_pInterfaceRegs; +}; + +// Use this to expose an interface that can have multiple instances. +// e.g.: +// EXPOSE_INTERFACE(CInterfaceImp, IInterface, "MyInterface001") +// This will expose a class called CInterfaceImp that implements IInterface (a pure class) +// clients can receive a pointer to this class by calling CreateInterface("MyInterface001") +// +// In practice, the shared header file defines the interface (IInterface) and version name ("MyInterface001") +// so that each component can use these names/vtables to communicate +// +// A single class can support multiple interfaces through multiple inheritance +// +// Use this if you want to write the factory function. +#define EXPOSE_INTERFACE_FN(functionName, interfaceName, versionName)\ + static InterfaceReg __g_Create##interfaceName##_reg(functionName, versionName); + +#define EXPOSE_INTERFACE(className, interfaceName, versionName)\ + static IBaseInterface *__Create##className##_interface() {return (interfaceName *)new className;}\ + static InterfaceReg __g_Create##className##_reg(__Create##className##_interface, versionName); + +// Use this to expose a singleton interface with a global variable you've created. +#define EXPOSE_SINGLE_INTERFACE_GLOBALVAR(className, interfaceName, versionName, globalVarName)\ + static IBaseInterface *__Create##className##interfaceName##_interface() {return (IBaseInterface *)&globalVarName;}\ + static InterfaceReg __g_Create##className##interfaceName##_reg(__Create##className##interfaceName##_interface, versionName); + +// Use this to expose a singleton interface. This creates the global variable for you automatically. +#define EXPOSE_SINGLE_INTERFACE(className, interfaceName, versionName)\ + static className __g_##className##_singleton;\ + EXPOSE_SINGLE_INTERFACE_GLOBALVAR(className, interfaceName, versionName, __g_##className##_singleton) + +#ifdef _WIN32 + #define EXPORT_FUNCTION __declspec(dllexport) EXT_FUNC +#else + #define EXPORT_FUNCTION __attribute__((visibility("default"))) EXT_FUNC +#endif // _WIN32 + +// This function is automatically exported and allows you to access any interfaces exposed with the above macros. +// if pReturnCode is set, it will return one of the following values +// extend this for other error conditions/code +enum +{ + IFACE_OK = 0, + IFACE_FAILED +}; + +extern "C" +{ + EXPORT_FUNCTION IBaseInterface *CreateInterface(const char *pName, int *pReturnCode); +}; + +extern CreateInterfaceFn Sys_GetFactoryThis(); + +// UNDONE: This is obsolete, use the module load/unload/get instead!!! +extern CreateInterfaceFn Sys_GetFactory(const char *pModuleName); + +// load/unload components +class CSysModule; + +// Load & Unload should be called in exactly one place for each module +// The factory for that module should be passed on to dependent components for +// proper versioning. +extern CSysModule *Sys_LoadModule(const char *pModuleName); +extern CSysModule *Sys_GetModuleHandle(const char *pModuleName); +extern void Sys_UnloadModule(CSysModule *pModule); +extern CreateInterfaceFn Sys_GetFactory(CSysModule *pModule); +extern void *InitializeInterface(char const *interfaceName, CreateInterfaceFn *factoryList, int numFactories); diff --git a/dep/rehlsdk/public/iregistry.h b/dep/rehlsdk/public/iregistry.h new file mode 100644 index 0000000..4b00a6e --- /dev/null +++ b/dep/rehlsdk/public/iregistry.h @@ -0,0 +1,35 @@ +//========= Copyright © 1996-2001, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#if !defined( UTIL_REGISTRY_H ) +#define UTIL_REGISTRY_H +#ifdef _WIN32 +#pragma once +#endif + +//----------------------------------------------------------------------------- +// Purpose: Interface to registry +//----------------------------------------------------------------------------- +class IRegistry +{ +public: + // Init/shutdown + virtual void Init(void) = 0; + virtual void Shutdown(void) = 0; + + // Read/write integers + virtual int ReadInt(const char *key, int defaultValue = 0) = 0; + virtual void WriteInt(const char *key, int value) = 0; + + // Read/write strings + virtual const char *ReadString(const char *key, const char *defaultValue = NULL) = 0; + virtual void WriteString(const char *key, const char *value) = 0; +}; + +extern IRegistry *registry; + +#endif // UTIL_REGISTRY_H diff --git a/dep/rehlsdk/public/keydefs.h b/dep/rehlsdk/public/keydefs.h new file mode 100644 index 0000000..6f1e43f --- /dev/null +++ b/dep/rehlsdk/public/keydefs.h @@ -0,0 +1,124 @@ +// keydefs.h +#ifndef KEYDEFS_H +#define KEYDEFS_H +#ifdef _WIN32 +#pragma once +#endif + +// +// these are the key numbers that should be passed to Key_Event +// +#define K_TAB 9 +#define K_ENTER 13 +#define K_ESCAPE 27 +#define K_SPACE 32 + +// normal keys should be passed as lowercased ascii + +#define K_BACKSPACE 127 +#define K_UPARROW 128 +#define K_DOWNARROW 129 +#define K_LEFTARROW 130 +#define K_RIGHTARROW 131 + +#define K_ALT 132 +#define K_CTRL 133 +#define K_SHIFT 134 +#define K_F1 135 +#define K_F2 136 +#define K_F3 137 +#define K_F4 138 +#define K_F5 139 +#define K_F6 140 +#define K_F7 141 +#define K_F8 142 +#define K_F9 143 +#define K_F10 144 +#define K_F11 145 +#define K_F12 146 +#define K_INS 147 +#define K_DEL 148 +#define K_PGDN 149 +#define K_PGUP 150 +#define K_HOME 151 +#define K_END 152 + +#define K_KP_HOME 160 +#define K_KP_UPARROW 161 +#define K_KP_PGUP 162 +#define K_KP_LEFTARROW 163 +#define K_KP_5 164 +#define K_KP_RIGHTARROW 165 +#define K_KP_END 166 +#define K_KP_DOWNARROW 167 +#define K_KP_PGDN 168 +#define K_KP_ENTER 169 +#define K_KP_INS 170 +#define K_KP_DEL 171 +#define K_KP_SLASH 172 +#define K_KP_MINUS 173 +#define K_KP_PLUS 174 +#define K_CAPSLOCK 175 +#define K_KP_MUL 176 +#define K_WIN 177 + + +// +// joystick buttons +// +#define K_JOY1 203 +#define K_JOY2 204 +#define K_JOY3 205 +#define K_JOY4 206 + +// +// aux keys are for multi-buttoned joysticks to generate so they can use +// the normal binding process +// +#define K_AUX1 207 +#define K_AUX2 208 +#define K_AUX3 209 +#define K_AUX4 210 +#define K_AUX5 211 +#define K_AUX6 212 +#define K_AUX7 213 +#define K_AUX8 214 +#define K_AUX9 215 +#define K_AUX10 216 +#define K_AUX11 217 +#define K_AUX12 218 +#define K_AUX13 219 +#define K_AUX14 220 +#define K_AUX15 221 +#define K_AUX16 222 +#define K_AUX17 223 +#define K_AUX18 224 +#define K_AUX19 225 +#define K_AUX20 226 +#define K_AUX21 227 +#define K_AUX22 228 +#define K_AUX23 229 +#define K_AUX24 230 +#define K_AUX25 231 +#define K_AUX26 232 +#define K_AUX27 233 +#define K_AUX28 234 +#define K_AUX29 235 +#define K_AUX30 236 +#define K_AUX31 237 +#define K_AUX32 238 +#define K_MWHEELDOWN 239 +#define K_MWHEELUP 240 + +#define K_PAUSE 255 + +// +// mouse buttons generate virtual keys +// +#define K_MOUSE1 241 +#define K_MOUSE2 242 +#define K_MOUSE3 243 +#define K_MOUSE4 244 +#define K_MOUSE5 245 + +#endif // KEYDEFS_H diff --git a/dep/rehlsdk/public/particleman.h b/dep/rehlsdk/public/particleman.h new file mode 100644 index 0000000..0f9b702 --- /dev/null +++ b/dep/rehlsdk/public/particleman.h @@ -0,0 +1,101 @@ +#ifndef PARTICLEMAN_H +#define PARTICLEMAN_H + +#include "interface.h" +#include "pman_triangleffect.h" + +#define PARTICLEMAN_INTERFACE "create_particleman" + +#ifdef _WIN32 +#define PARTICLEMAN_DLLNAME "cl_dlls/particleman.dll" +#elif defined(OSX) +#define PARTICLEMAN_DLLNAME "cl_dlls/particleman.dylib" +#elif defined(LINUX) +#define PARTICLEMAN_DLLNAME "cl_dlls/particleman.so" +#else +#error +#endif + +class CBaseParticle; + +class IParticleMan : public IBaseInterface +{ + +protected: + virtual ~IParticleMan() {} + +public: + + virtual void SetUp( cl_enginefunc_t *pEnginefuncs ) = 0; + virtual void Update ( void ) = 0; + virtual void SetVariables ( float flGravity, Vector vViewAngles ) = 0; + virtual void ResetParticles ( void ) = 0; + virtual void ApplyForce ( Vector vOrigin, Vector vDirection, float flRadius, float flStrength, float flDuration ) = 0; + virtual void AddCustomParticleClassSize ( unsigned long lSize ) = 0; + + //Use this if you want to create a new particle without any overloaded functions, Think, Touch, etc. + //Just call this function, set the particle's behavior and let it rip. + virtual CBaseParticle *CreateParticle( Vector org, Vector normal, model_s * sprite, float size, float brightness, const char *classname ) = 0; + + //Use this to take a block from the mempool for custom particles ( used in new ). + virtual char *RequestNewMemBlock( int iSize ) = 0; + + //These ones are used along a custom Create for new particles you want to override their behavior. + //You can call these whenever you want, but they are mainly used by CBaseParticle. + virtual void CoreInitializeSprite ( CCoreTriangleEffect *pParticle, Vector org, Vector normal, model_s *sprite, float size, float brightness ) = 0; //Only use this for TrianglePlanes + virtual void CoreThink( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreDraw( CCoreTriangleEffect *pParticle ) = 0; + virtual void CoreAnimate( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreAnimateAndDie( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreExpand ( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreContract ( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreFade ( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreSpin ( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreCalculateVelocity( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreCheckCollision( CCoreTriangleEffect *pParticle, float time ) = 0; + virtual void CoreTouch ( CCoreTriangleEffect *pParticle, Vector pos, Vector normal, int index ) = 0; + virtual void CoreDie ( CCoreTriangleEffect *pParticle ) = 0; + virtual void CoreForce ( CCoreTriangleEffect *pParticle ) = 0; + virtual bool CoreCheckVisibility ( CCoreTriangleEffect *pParticle ) = 0; + virtual void SetRender( int iRender ) = 0; +}; + +extern IParticleMan *g_pParticleMan; + +class CBaseParticle : public CCoreTriangleEffect +{ +public: + virtual void Think( float time ){ g_pParticleMan->CoreThink( this, time ); } + virtual void Draw( void ) { g_pParticleMan->CoreDraw( this ); } + virtual void Animate( float time ) { g_pParticleMan->CoreAnimate( this, time ); } + virtual void AnimateAndDie( float time ) { g_pParticleMan->CoreAnimateAndDie( this, time ); } + virtual void Expand( float time ) { g_pParticleMan->CoreExpand( this, time ); } + virtual void Contract( float time ) { g_pParticleMan->CoreContract( this, time ); } + virtual void Fade( float time ) { g_pParticleMan->CoreFade( this, time ); } + virtual void Spin( float time ) { g_pParticleMan->CoreSpin( this, time ); } + virtual void CalculateVelocity( float time ) { g_pParticleMan->CoreCalculateVelocity( this, time ); } + virtual void CheckCollision( float time ) { g_pParticleMan->CoreCheckCollision( this, time ); } + virtual void Touch(Vector pos, Vector normal, int index) { g_pParticleMan->CoreTouch( this, pos, normal, index ); } + virtual void Die ( void ) { g_pParticleMan->CoreDie( this ); } + virtual void Force ( void ) { g_pParticleMan->CoreForce( this ); } + virtual bool CheckVisibility ( void ) { return g_pParticleMan->CoreCheckVisibility( this ); } + + virtual void InitializeSprite( Vector org, Vector normal, model_s *sprite, float size, float brightness ) + { + g_pParticleMan->CoreInitializeSprite ( this, org, normal, sprite, size, brightness ); + } + + void * operator new( size_t size ) //this asks for a new block of memory from the MiniMem class + { + return( g_pParticleMan->RequestNewMemBlock( size ) ); + } +#ifdef POSIX + void * operator new( size_t size, const std::nothrow_t&) throw() //this asks for a new block of memory from the MiniMem class + { + return( g_pParticleMan->RequestNewMemBlock( size ) ); + } +#endif +}; + + +#endif //PARTICLEMAN_H diff --git a/dep/rehlsdk/public/pman_particlemem.h b/dep/rehlsdk/public/pman_particlemem.h new file mode 100644 index 0000000..e2a03fc --- /dev/null +++ b/dep/rehlsdk/public/pman_particlemem.h @@ -0,0 +1,197 @@ +#ifndef PARTICLEMEM_H__ +#define PARTICLEMEM_H__ + +#ifdef _WIN32 +#pragma once +#endif + +#include + +class CCoreTriangleEffect; + +#define TRIANGLE_FPS 30 + +typedef struct visibleparticles_s +{ + CCoreTriangleEffect *pVisibleParticle; +} visibleparticles_t; + +//--------------------------------------------------------------------------- +// Memory block record. +class MemoryBlock +{ +private: + char *m_pData; + //bool m_bBlockIsInUse; +public: + MemoryBlock(long lBlockSize) + : next(NULL), prev(NULL) + //m_bBlockIsInUse(false) // Initialize block to 'free' state. + { + // Allocate memory here. + m_pData = new char[lBlockSize]; + } + + virtual ~MemoryBlock() + { + // Free memory. + delete[] m_pData; + } + + inline char *Memory(void) { return m_pData; } + + MemoryBlock * next; + MemoryBlock * prev; +}; + +class MemList +{ +public: + MemList() : m_pHead(NULL) {} + + ~MemList() { Reset(); } + + void Push(MemoryBlock * newItem) + { + if(!m_pHead) + { + m_pHead = newItem; + newItem->next = NULL; + newItem->prev = NULL; + return; + } + + MemoryBlock * temp = m_pHead; + m_pHead = newItem; + m_pHead->next = temp; + m_pHead->prev = NULL; + + temp->prev = m_pHead; + } + + + MemoryBlock * Front( void ) + { + return(m_pHead); + } + + MemoryBlock * Pop( void ) + { + if(!m_pHead) + return(NULL); + + MemoryBlock * temp = m_pHead; + + m_pHead = m_pHead->next; + + if(m_pHead) + m_pHead->prev = NULL; + + temp->next = NULL; + temp->prev = NULL; + + return(temp); + } + + void Delete( MemoryBlock * pItem) + { + + if(m_pHead == pItem) + { + MemoryBlock * temp = m_pHead; + + m_pHead = m_pHead->next; + if(m_pHead) + m_pHead->prev = NULL; + + temp->next = NULL; + temp->prev = NULL; + return; + } + + MemoryBlock * prev = pItem->prev; + MemoryBlock * next = pItem->next; + + if(prev) + prev->next = next; + + if(next) + next->prev = prev; + + pItem->next = NULL; + pItem->prev = NULL; + } + + void Reset( void ) + { + while(m_pHead) + Delete(m_pHead); + } + +private: + MemoryBlock * m_pHead; +}; + + +// Some helpful typedefs. +typedef std::vector VectorOfMemoryBlocks; +typedef VectorOfMemoryBlocks::iterator MemoryBlockIterator; + +// Mini memory manager - singleton. +class CMiniMem +{ +private: + // Main memory pool. Array is fine, but vectors are + // easier. :) + static VectorOfMemoryBlocks m_vecMemoryPool; + // Size of memory blocks in pool. + static long m_lMemoryBlockSize; + static long m_lMaxBlocks; + static long m_lMemoryPoolSize; + static CMiniMem *_instance; + + int m_iTotalParticles; + int m_iParticlesDrawn; + +protected: + // private constructor and destructor. + CMiniMem(long lMemoryPoolSize, long lMaxBlockSize); + virtual ~CMiniMem(); + + // ------------ Memory pool manager calls. + // Find a free block and mark it as "in use". Return NULL + // if no free blocks found. + char *AllocateFreeBlock(void); +public: + + // Return a pointer to usable block of memory. + char *newBlock(void); + + // Mark a target memory item as no longer "in use". + void deleteBlock(MemoryBlock *p); + + // Return the remaining capacity of the memory pool as a percent. + long PercentUsed(void); + + void ProcessAll( void ); //Processes all + + void Reset( void ); //clears memory, setting all particles to not used. + + static int ApplyForce( Vector vOrigin, Vector vDirection, float flRadius, float flStrength ); + + static CMiniMem *Instance(void); + static long MaxBlockSize(void); + + bool CheckSize( int iSize ); + + int GetTotalParticles( void ) { return m_iTotalParticles; } + int GetDrawnParticles( void ) { return m_iParticlesDrawn; } + void IncreaseParticlesDrawn( void ){ m_iParticlesDrawn++; } + + void Shutdown( void ); + + visibleparticles_t *m_pVisibleParticles; +}; + + +#endif//PARTICLEMEM_H__ diff --git a/dep/rehlsdk/public/pman_triangleffect.h b/dep/rehlsdk/public/pman_triangleffect.h new file mode 100644 index 0000000..6af4c2b --- /dev/null +++ b/dep/rehlsdk/public/pman_triangleffect.h @@ -0,0 +1,209 @@ +#ifndef TRIANGLEEFFECT_H__ +#define TRIANGLEEFFECT_H__ + +#ifdef _WIN32 +#pragma once +#endif + +#define TRI_COLLIDEWORLD 0x00000020 +#define TRI_COLLIDEALL 0x00001000 // will collide with world and slideboxes +#define TRI_COLLIDEKILL 0x00004000 // tent is removed upon collision with anything +#define TRI_SPIRAL 0x00008000 +#define TRI_ANIMATEDIE 0x00016000 //animate once and then die +#define TRI_WATERTRACE 0x00032000 + + +#define CULL_FRUSTUM_POINT ( 1 << 0 ) +#define CULL_FRUSTUM_SPHERE ( 1 << 1 ) +#define CULL_FRUSTUM_PLANE ( 1 << 2 ) +#define CULL_PVS ( 1 << 3 ) + +#define LIGHT_NONE ( 1 << 4 ) +#define LIGHT_COLOR ( 1 << 5 ) +#define LIGHT_INTENSITY ( 1 << 6 ) + +#define RENDER_FACEPLAYER ( 1 << 7 ) // m_vAngles == Player view angles +#define RENDER_FACEPLAYER_ROTATEZ ( 1 << 8 ) //Just like above but m_vAngles.z is untouched so the sprite can rotate. + + +#include "pman_particlemem.h" + +//pure virtual baseclass +class CCoreTriangleEffect +{ +private: + int m_iRenderFlags; + float m_flNextPVSCheck; + bool m_bInPVS; + + int m_iCollisionFlags; + float m_flPlayerDistance; //Used for sorting the particles, DO NOT TOUCH. + +public: + + void * operator new(size_t size) + { + // Requested size should match size of class. + if ( size != sizeof( CCoreTriangleEffect ) ) +#ifdef _WIN32 + throw "Error in requested size of new particle class instance."; +#else + return NULL; +#endif + + return((CCoreTriangleEffect *) CMiniMem::Instance()->newBlock()); + + }//this asks for a new block of memory from the MiniMen class + + virtual void Think( float time ) = 0; + virtual bool CheckVisibility ( void ) = 0; + virtual void Draw( void ) = 0; + virtual void Animate( float time ) = 0; + virtual void AnimateAndDie( float time ) = 0; + virtual void Expand( float time ) = 0; + virtual void Contract( float time ) = 0; + virtual void Fade( float time ) = 0; + virtual void Spin( float time ) = 0; + virtual void CalculateVelocity( float time ) = 0; + virtual void CheckCollision( float time ) = 0; + virtual void Touch(Vector pos, Vector normal, int index) = 0; + virtual void Die ( void ) = 0; + virtual void InitializeSprite( Vector org, Vector normal, model_s * sprite, float size, float brightness ) = 0; + virtual void Force ( void ) = 0; + + float m_flSize; //scale of object + float m_flScaleSpeed; //speed at which object expands + float m_flContractSpeed; //speed at which object expands + + float m_flStretchX; + float m_flStretchY; + + float m_flBrightness; //transparency of object + float m_flFadeSpeed; //speed at which object fades + + float m_flTimeCreated; //time object was instanced + float m_flDieTime; //time to remove an object + + float m_flGravity; //how effected by gravity is this object + float m_flAfterDampGrav; + float m_flDampingVelocity; + float m_flDampingTime; + + int m_iFramerate; + int m_iNumFrames; + int m_iFrame; + int m_iRendermode; + + Vector m_vOrigin; //object's position + Vector m_vAngles; //normal angles of object + + Vector m_vAVelocity; + + Vector m_vVelocity; + + Vector m_vLowLeft; + Vector m_vLowRight; + Vector m_vTopLeft; + + Vector m_vColor; + float m_flMass; + + model_s * m_pTexture; + + float m_flBounceFactor; + + char m_szClassname[32]; + + bool m_bInWater; + bool m_bAffectedByForce; + + int m_iAfterDampFlags; + + void SetLightFlag ( int iFlag ) + { + m_iRenderFlags &= ~( LIGHT_NONE | LIGHT_INTENSITY | LIGHT_COLOR ); + m_iRenderFlags |= iFlag; + } + + void SetCullFlag( int iFlag ) + { + m_iRenderFlags &= ~( CULL_PVS | CULL_FRUSTUM_POINT | CULL_FRUSTUM_PLANE | CULL_FRUSTUM_SPHERE ); + m_iRenderFlags |= iFlag; + } + + int GetRenderFlags( void ) + { + return m_iRenderFlags; + } + + bool GetParticlePVS ( void ) + { + return m_bInPVS; + } + + void SetParticlePVS ( bool bPVSStat ) + { + m_bInPVS = bPVSStat; + } + + float GetNextPVSCheck( void ) + { + return m_flNextPVSCheck; + } + + void SetNextPVSCheck( float flTime ) + { + m_flNextPVSCheck = flTime; + } + + void SetCollisionFlags ( int iFlag ) + { + m_iCollisionFlags |= iFlag; + } + + void ClearCollisionFlags ( int iFlag ) + { + m_iCollisionFlags &= ~iFlag; + } + + int GetCollisionFlags ( void ) + { + return m_iCollisionFlags; + } + + void SetRenderFlag( int iFlag ) + { + m_iRenderFlags |= iFlag; + } + + float GetPlayerDistance ( void ) { return m_flPlayerDistance; } + void SetPlayerDistance ( float flDistance ) { m_flPlayerDistance = flDistance; } + +protected: + float m_flOriginalSize; + Vector m_vOriginalAngles; + float m_flOriginalBrightness; + Vector m_vPrevOrigin; + + float m_flNextCollisionTime; + +protected: + static bool CheckSize(int size) + { + // This check will help prevent a class frome being defined later, + // that is larger than the max size MemoryPool is expecting, + // from being successfully allocated. + if (size > (unsigned long) CMiniMem::Instance()->MaxBlockSize()) + { +#ifdef _WIN32 + throw "New particle class is larger than memory pool max size, update lMaxParticleClassSize() function."; +#endif + return(false); + } + + return(true); + } +}; + + +#endif//TRIANGLEEFFECT_H__ diff --git a/dep/rehlsdk/public/registry.cpp b/dep/rehlsdk/public/registry.cpp new file mode 100644 index 0000000..c858419 --- /dev/null +++ b/dep/rehlsdk/public/registry.cpp @@ -0,0 +1,255 @@ +//========= Copyright © 1996-2001, Valve LLC, All rights reserved. ============ +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#include "precompiled.h" + +#ifndef _WIN32 +typedef int HKEY; +#endif + +//----------------------------------------------------------------------------- +// Purpose: Exposes registry interface to rest of launcher +//----------------------------------------------------------------------------- +class CRegistry : public IRegistry +{ +public: + CRegistry(void); + virtual ~CRegistry(void); + + void Init(void); + void Shutdown(void); + + int ReadInt(const char *key, int defaultValue = 0); + void WriteInt(const char *key, int value); + + const char *ReadString(const char *key, const char *defaultValue = NULL); + void WriteString(const char *key, const char *value); + +private: + bool m_bValid; + HKEY m_hKey; +}; + +static CRegistry g_Registry; +IRegistry *registry = (IRegistry *)&g_Registry; + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +CRegistry::CRegistry(void) +{ + // Assume failure + m_bValid = false; + m_hKey = 0; +} + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +CRegistry::~CRegistry(void) +{ +} + +//----------------------------------------------------------------------------- +// Purpose: Read integer from registry +// Input : *key - +// defaultValue - +// Output : int +//----------------------------------------------------------------------------- +int CRegistry::ReadInt(const char *key, int defaultValue /*= 0*/) +{ +#ifdef _WIN32 + LONG lResult; // Registry function result code + DWORD dwType; // Type of key + DWORD dwSize; // Size of element data + + int value; + + if (!m_bValid) + { + return defaultValue; + } + + dwSize = sizeof(DWORD); + + lResult = RegQueryValueEx( + m_hKey, // handle to key + key, // value name + 0, // reserved + &dwType, // type buffer + (LPBYTE)&value, // data buffer + &dwSize); // size of data buffer + + if (lResult != ERROR_SUCCESS) // Failure + return defaultValue; + + if (dwType != REG_DWORD) + return defaultValue; + + return value; +#else + return defaultValue; +#endif +} + +//----------------------------------------------------------------------------- +// Purpose: Save integer to registry +// Input : *key - +// value - +//----------------------------------------------------------------------------- +void CRegistry::WriteInt(const char *key, int value) +{ +#ifdef _WIN32 + // Size of element data + DWORD dwSize; + + if (!m_bValid) + { + return; + } + + dwSize = sizeof(DWORD); + + RegSetValueEx( + m_hKey, // handle to key + key, // value name + 0, // reserved + REG_DWORD, // type buffer + (LPBYTE)&value, // data buffer + dwSize); // size of data buffer +#endif +} + +//----------------------------------------------------------------------------- +// Purpose: Read string value from registry +// Input : *key - +// *defaultValue - +// Output : const char +//----------------------------------------------------------------------------- +const char *CRegistry::ReadString(const char *key, const char *defaultValue /* = NULL */) +{ +#ifdef _WIN32 + LONG lResult; + // Type of key + DWORD dwType; + // Size of element data + DWORD dwSize = 512; + + static char value[512]; + + value[0] = 0; + + if (!m_bValid) + { + return defaultValue; + } + + lResult = RegQueryValueEx( + m_hKey, // handle to key + key, // value name + 0, // reserved + &dwType, // type buffer + (unsigned char *)value, // data buffer + &dwSize); // size of data buffer + + if (lResult != ERROR_SUCCESS) + { + return defaultValue; + } + + if (dwType != REG_SZ) + { + return defaultValue; + } + + return value; +#else + return defaultValue; +#endif +} + +//----------------------------------------------------------------------------- +// Purpose: Save string to registry +// Input : *key - +// *value - +//----------------------------------------------------------------------------- +void CRegistry::WriteString(const char *key, const char *value) +{ +#ifdef _WIN32 + DWORD dwSize; // Size of element data + + if (!m_bValid) + { + return; + } + + dwSize = strlen(value) + 1; + + RegSetValueEx( + m_hKey, // handle to key + key, // value name + 0, // reserved + REG_SZ, // type buffer + (LPBYTE)value, // data buffer + dwSize); // size of data buffer +#endif +} + +// FIXME: SHould be "steam" +static char *GetPlatformName(void) +{ + return "Half-Life"; +} + +//----------------------------------------------------------------------------- +// Purpose: Open default launcher key based on game directory +//----------------------------------------------------------------------------- +void CRegistry::Init(void) +{ +#ifdef _WIN32 + LONG lResult; // Registry function result code + DWORD dwDisposition; // Type of key opening event + + char szModelKey[1024]; + wsprintf(szModelKey, "Software\\Valve\\%s\\Settings\\", GetPlatformName()); + + lResult = RegCreateKeyEx( + HKEY_CURRENT_USER, // handle of open key + szModelKey, // address of name of subkey to open + 0, // DWORD ulOptions, // reserved + NULL, // Type of value + REG_OPTION_NON_VOLATILE, // Store permanently in reg. + KEY_ALL_ACCESS, // REGSAM samDesired, // security access mask + NULL, + &m_hKey, // Key we are creating + &dwDisposition); // Type of creation + + if (lResult != ERROR_SUCCESS) + { + m_bValid = false; + return; + } + + // Success + m_bValid = true; +#endif +} + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +void CRegistry::Shutdown(void) +{ +#ifdef _WIN32 + if (!m_bValid) + return; + + // Make invalid + m_bValid = false; + RegCloseKey(m_hKey); +#endif +} diff --git a/dep/rehlsdk/public/savegame_version.h b/dep/rehlsdk/public/savegame_version.h new file mode 100644 index 0000000..f14564d --- /dev/null +++ b/dep/rehlsdk/public/savegame_version.h @@ -0,0 +1,35 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "commonmacros.h" + +#define SAVEFILE_HEADER MAKEID('V','A','L','V') // little-endian "VALV" +#define SAVEGAME_HEADER MAKEID('J','S','A','V') // little-endian "JSAV" +#define SAVEGAME_VERSION 0x0071 // Version 0.71 diff --git a/dep/rehlsdk/public/steam/isteamapps.h b/dep/rehlsdk/public/steam/isteamapps.h new file mode 100644 index 0000000..7021a35 --- /dev/null +++ b/dep/rehlsdk/public/steam/isteamapps.h @@ -0,0 +1,127 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to app data in Steam +// +//============================================================================= + +#ifndef ISTEAMAPPS_H +#define ISTEAMAPPS_H +#ifdef _WIN32 +#pragma once +#endif + +const int k_cubAppProofOfPurchaseKeyMax = 64; // max bytes of a legacy cd key we support + + +//----------------------------------------------------------------------------- +// Purpose: interface to app data +//----------------------------------------------------------------------------- +class ISteamApps +{ +public: + virtual bool BIsSubscribed() = 0; + virtual bool BIsLowViolence() = 0; + virtual bool BIsCybercafe() = 0; + virtual bool BIsVACBanned() = 0; + virtual const char *GetCurrentGameLanguage() = 0; + virtual const char *GetAvailableGameLanguages() = 0; + + // only use this member if you need to check ownership of another game related to yours, a demo for example + virtual bool BIsSubscribedApp( AppId_t appID ) = 0; + + // Takes AppID of DLC and checks if the user owns the DLC & if the DLC is installed + virtual bool BIsDlcInstalled( AppId_t appID ) = 0; + + // returns the Unix time of the purchase of the app + virtual uint32 GetEarliestPurchaseUnixTime( AppId_t nAppID ) = 0; + + // Checks if the user is subscribed to the current app through a free weekend + // This function will return false for users who have a retail or other type of license + // Before using, please ask your Valve technical contact how to package and secure your free weekened + virtual bool BIsSubscribedFromFreeWeekend() = 0; + + // Returns the number of DLC pieces for the running app + virtual int GetDLCCount() = 0; + + // Returns metadata for DLC by index, of range [0, GetDLCCount()] + virtual bool BGetDLCDataByIndex( int iDLC, AppId_t *pAppID, bool *pbAvailable, char *pchName, int cchNameBufferSize ) = 0; + + // Install/Uninstall control for optional DLC + virtual void InstallDLC( AppId_t nAppID ) = 0; + virtual void UninstallDLC( AppId_t nAppID ) = 0; + + // Request cd-key for yourself or owned DLC. If you are interested in this + // data then make sure you provide us with a list of valid keys to be distributed + // to users when they purchase the game, before the game ships. + // You'll receive an AppProofOfPurchaseKeyResponse_t callback when + // the key is available (which may be immediately). + virtual void RequestAppProofOfPurchaseKey( AppId_t nAppID ) = 0; + + virtual bool GetCurrentBetaName( char *pchName, int cchNameBufferSize ) = 0; // returns current beta branch name, 'public' is the default branch + virtual bool MarkContentCorrupt( bool bMissingFilesOnly ) = 0; // signal Steam that game files seems corrupt or missing + virtual uint32 GetInstalledDepots( DepotId_t *pvecDepots, uint32 cMaxDepots ) = 0; // return installed depots in mount order + + // returns current app install folder for AppID, returns folder name length + virtual uint32 GetAppInstallDir( AppId_t appID, char *pchFolder, uint32 cchFolderBufferSize ) = 0; + +#ifdef _PS3 + // Result returned in a RegisterActivationCodeResponse_t callresult + virtual SteamAPICall_t RegisterActivationCode( const char *pchActivationCode ) = 0; +#endif +}; + +#define STEAMAPPS_INTERFACE_VERSION "STEAMAPPS_INTERFACE_VERSION005" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif +//----------------------------------------------------------------------------- +// Purpose: posted after the user gains ownership of DLC & that DLC is installed +//----------------------------------------------------------------------------- +struct DlcInstalled_t +{ + enum { k_iCallback = k_iSteamAppsCallbacks + 5 }; + AppId_t m_nAppID; // AppID of the DLC +}; + + +//----------------------------------------------------------------------------- +// Purpose: possible results when registering an activation code +//----------------------------------------------------------------------------- +enum ERegisterActivationCodeResult +{ + k_ERegisterActivationCodeResultOK = 0, + k_ERegisterActivationCodeResultFail = 1, + k_ERegisterActivationCodeResultAlreadyRegistered = 2, + k_ERegisterActivationCodeResultTimeout = 3, + k_ERegisterActivationCodeAlreadyOwned = 4, +}; + + +//----------------------------------------------------------------------------- +// Purpose: response to RegisterActivationCode() +//----------------------------------------------------------------------------- +struct RegisterActivationCodeResponse_t +{ + enum { k_iCallback = k_iSteamAppsCallbacks + 8 }; + ERegisterActivationCodeResult m_eResult; + uint32 m_unPackageRegistered; // package that was registered. Only set on success +}; + +//----------------------------------------------------------------------------- +// Purpose: response to RegisterActivationCode() +//----------------------------------------------------------------------------- +struct AppProofOfPurchaseKeyResponse_t +{ + enum { k_iCallback = k_iSteamAppsCallbacks + 13 }; + EResult m_eResult; + uint32 m_nAppID; + char m_rgchKey[ k_cubAppProofOfPurchaseKeyMax ]; +}; +#pragma pack( pop ) +#endif // ISTEAMAPPS_H diff --git a/dep/rehlsdk/public/steam/isteambilling.h b/dep/rehlsdk/public/steam/isteambilling.h new file mode 100644 index 0000000..7bf63b8 --- /dev/null +++ b/dep/rehlsdk/public/steam/isteambilling.h @@ -0,0 +1,108 @@ +//====== Copyright © 1996-2004, Valve Corporation, All rights reserved. ======= +// +// Purpose: interface to Billings data in Steam +// +//============================================================================= + +#ifndef ISTEAMBILLING_H +#define ISTEAMBILLING_H +#ifdef _WIN32 +#pragma once +#endif + +//----------------------------------------------------------------------------- +// Purpose: interface to billing +//----------------------------------------------------------------------------- +class ISteamBilling +{ +public: + // Sets the billing address in the ISteamBilling object for use by other ISteamBilling functions (not stored on server) + virtual bool SetBillingAddress( const char *pchName, + const char *pchAddress1, + const char *pchAddress2, + const char *pchCity, + const char *pchPostcode, + const char *pchState, + const char *pchCountry, + const char *pchPhone ) = 0; + // Gets any previous set billing address in the ISteamBilling object (not stored on server) + virtual bool GetBillingAddress( char *pchName, + char *pchAddress1, + char *pchAddress2, + char *pchCity, + char *pchPostcode, + char *pchState, + char *pchCountry, + char *pchPhone ) = 0; + // Sets the billing address in the ISteamBilling object for use by other ISteamBilling functions (not stored on server) + virtual bool SetShippingAddress( const char *pchName, + const char *pchAddress1, + const char *pchAddress2, + const char *pchCity, + const char *pchPostcode, + const char *pchState, + const char *pchCountry, + const char *pchPhone ) = 0; + // Gets any previous set billing address in the ISteamBilling object (not stored on server) + virtual bool GetShippingAddress( char *pchName, + char *pchAddress1, + char *pchAddress2, + char *pchCity, + char *pchPostcode, + char *pchState, + char *pchCountry, + char *pchPhone ) = 0; + // Ask the server for the final price of package: requires that ISteamBilling billing & shipping address are set (can be same) + virtual bool GetFinalPrice( int32 nPackageID ) = 0; + + // Sets the credit card info in the ISteamBilling object for use by other ISteamBilling functions (may eventually also be stored on server) + virtual bool SetCardInfo( int32 eCreditCardType, + const char *pchCardNumber, + const char *pchCardHolderName, + const char *pchCardExpYear, + const char *pchCardExpMonth, + const char *pchCardCVV2 ) = 0; + // Gets any credit card info in the ISteamBilling object (not stored on server) + virtual bool GetCardInfo( int32 *eCreditCardType, + char *pchCardNumber, + char *pchCardHolderName, + char *pchCardExpYear, + char *pchCardExpMonth, + char *pchCardCVV2 ) = 0; + + // Ask the server to purchase a package: requires that ISteamBilling cardinfo, billing & shipping address are set + virtual bool Purchase( int32 nPackageID, + int32 nExpectedCostCents, + uint64 gidCardID, // if non-NIL, use a server stored card + bool bStoreCardInfo ) = 0; // Should this cardinfo also be stored on the server +}; + + +#define STEAMBILLING_INTERFACE_VERSION "SteamBilling001" + + +enum { k_iSteamBillingCallbacks = 400 }; + +//----------------------------------------------------------------------------- +// Purpose: called when this client has received a finalprice message from a Billing +//----------------------------------------------------------------------------- +struct FinalPriceMsg_t +{ + enum { k_iCallback = k_iSteamBillingCallbacks + 1 }; + + uint32 m_bSuccess; + uint32 m_nBaseCost; + uint32 m_nTotalDiscount; + uint32 m_nTax; + uint32 m_nShippingCost; +}; + +struct PurchaseMsg_t +{ + enum { k_iCallback = k_iSteamBillingCallbacks + 2 }; + + uint32 m_bSuccess; + int32 m_EPurchaseResultDetail; // Detailed result information +}; + +#endif // ISTEAMBILLING_H diff --git a/dep/rehlsdk/public/steam/isteamclient.h b/dep/rehlsdk/public/steam/isteamclient.h new file mode 100644 index 0000000..43a2076 --- /dev/null +++ b/dep/rehlsdk/public/steam/isteamclient.h @@ -0,0 +1,349 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: Main interface for loading and accessing Steamworks API's from the +// Steam client. +// For most uses, this code is wrapped inside of SteamAPI_Init() +//============================================================================= + +#ifndef ISTEAMCLIENT_H +#define ISTEAMCLIENT_H +#ifdef _WIN32 +#pragma once +#endif + +#include "steamtypes.h" +#include "steamclientpublic.h" + +// Define compile time assert macros to let us validate the structure sizes. +#define VALVE_COMPILE_TIME_ASSERT( pred ) typedef char compile_time_assert_type[(pred) ? 1 : -1]; + +#if defined(__linux__) || defined(__APPLE__) +// The 32-bit version of gcc has the alignment requirement for uint64 and double set to +// 4 meaning that even with #pragma pack(8) these types will only be four-byte aligned. +// The 64-bit version of gcc has the alignment requirement for these types set to +// 8 meaning that unless we use #pragma pack(4) our structures will get bigger. +// The 64-bit structure packing has to match the 32-bit structure packing for each platform. +#define VALVE_CALLBACK_PACK_SMALL +#else +#define VALVE_CALLBACK_PACK_LARGE +#endif + +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error ??? +#endif + +typedef struct +{ + uint32 m_u32; + uint64 m_u64; + uint16 m_u16; + double m_d; +} ValvePackingSentinel_t; + +#pragma pack( pop ) + + +#if defined(VALVE_CALLBACK_PACK_SMALL) +VALVE_COMPILE_TIME_ASSERT( sizeof(ValvePackingSentinel_t) == 24 ) +#elif defined(VALVE_CALLBACK_PACK_LARGE) +VALVE_COMPILE_TIME_ASSERT( sizeof(ValvePackingSentinel_t) == 32 ) +#else +#error ??? +#endif + + +// handle to a communication pipe to the Steam client +typedef int32 HSteamPipe; +// handle to single instance of a steam user +typedef int32 HSteamUser; +// function prototype +#if defined( POSIX ) +#define __cdecl +#endif +extern "C" typedef void (__cdecl *SteamAPIWarningMessageHook_t)(int, const char *); + +#if defined( __SNC__ ) + #pragma diag_suppress=1700 // warning 1700: class "%s" has virtual functions but non-virtual destructor +#endif + +// interface predec +class ISteamUser; +class ISteamGameServer; +class ISteamFriends; +class ISteamUtils; +class ISteamMatchmaking; +class ISteamContentServer; +class ISteamMatchmakingServers; +class ISteamUserStats; +class ISteamApps; +class ISteamNetworking; +class ISteamRemoteStorage; +class ISteamScreenshots; +class ISteamGameServerStats; +class ISteamPS3OverlayRender; +class ISteamHTTP; +class ISteamUnifiedMessages; + +//----------------------------------------------------------------------------- +// Purpose: Interface to creating a new steam instance, or to +// connect to an existing steam instance, whether it's in a +// different process or is local. +// +// For most scenarios this is all handled automatically via SteamAPI_Init(). +// You'll only need to use these interfaces if you have a more complex versioning scheme, +// where you want to get different versions of the same interface in different dll's in your project. +//----------------------------------------------------------------------------- +class ISteamClient +{ +public: + // Creates a communication pipe to the Steam client + virtual HSteamPipe CreateSteamPipe() = 0; + + // Releases a previously created communications pipe + virtual bool BReleaseSteamPipe( HSteamPipe hSteamPipe ) = 0; + + // connects to an existing global user, failing if none exists + // used by the game to coordinate with the steamUI + virtual HSteamUser ConnectToGlobalUser( HSteamPipe hSteamPipe ) = 0; + + // used by game servers, create a steam user that won't be shared with anyone else + virtual HSteamUser CreateLocalUser( HSteamPipe *phSteamPipe, EAccountType eAccountType ) = 0; + + // removes an allocated user + virtual void ReleaseUser( HSteamPipe hSteamPipe, HSteamUser hUser ) = 0; + + // retrieves the ISteamUser interface associated with the handle + virtual ISteamUser *GetISteamUser( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // retrieves the ISteamGameServer interface associated with the handle + virtual ISteamGameServer *GetISteamGameServer( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // set the local IP and Port to bind to + // this must be set before CreateLocalUser() + virtual void SetLocalIPBinding( uint32 unIP, uint16 usPort ) = 0; + + // returns the ISteamFriends interface + virtual ISteamFriends *GetISteamFriends( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // returns the ISteamUtils interface + virtual ISteamUtils *GetISteamUtils( HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // returns the ISteamMatchmaking interface + virtual ISteamMatchmaking *GetISteamMatchmaking( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // returns the ISteamMatchmakingServers interface + virtual ISteamMatchmakingServers *GetISteamMatchmakingServers( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // returns the a generic interface + virtual void *GetISteamGenericInterface( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // returns the ISteamUserStats interface + virtual ISteamUserStats *GetISteamUserStats( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // returns the ISteamGameServerStats interface + virtual ISteamGameServerStats *GetISteamGameServerStats( HSteamUser hSteamuser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // returns apps interface + virtual ISteamApps *GetISteamApps( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // networking + virtual ISteamNetworking *GetISteamNetworking( HSteamUser hSteamUser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // remote storage + virtual ISteamRemoteStorage *GetISteamRemoteStorage( HSteamUser hSteamuser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // user screenshots + virtual ISteamScreenshots *GetISteamScreenshots( HSteamUser hSteamuser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + + // this needs to be called every frame to process matchmaking results + // redundant if you're already calling SteamAPI_RunCallbacks() + virtual void RunFrame() = 0; + + // returns the number of IPC calls made since the last time this function was called + // Used for perf debugging so you can understand how many IPC calls your game makes per frame + // Every IPC call is at minimum a thread context switch if not a process one so you want to rate + // control how often you do them. + virtual uint32 GetIPCCallCount() = 0; + + // API warning handling + // 'int' is the severity; 0 for msg, 1 for warning + // 'const char *' is the text of the message + // callbacks will occur directly after the API function is called that generated the warning or message + virtual void SetWarningMessageHook( SteamAPIWarningMessageHook_t pFunction ) = 0; + + // Trigger global shutdown for the DLL + virtual bool BShutdownIfAllPipesClosed() = 0; + +#ifdef _PS3 + virtual ISteamPS3OverlayRender *GetISteamPS3OverlayRender() = 0; +#endif + + // Expose HTTP interface + virtual ISteamHTTP *GetISteamHTTP( HSteamUser hSteamuser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + + // Exposes the ISteamUnifiedMessages interface + virtual ISteamUnifiedMessages *GetISteamUnifiedMessages( HSteamUser hSteamuser, HSteamPipe hSteamPipe, const char *pchVersion ) = 0; + +}; + +#define STEAMCLIENT_INTERFACE_VERSION "SteamClient012" + +//----------------------------------------------------------------------------- +// Purpose: Base values for callback identifiers, each callback must +// have a unique ID. +//----------------------------------------------------------------------------- +enum { k_iSteamUserCallbacks = 100 }; +enum { k_iSteamGameServerCallbacks = 200 }; +enum { k_iSteamFriendsCallbacks = 300 }; +enum { k_iSteamBillingCallbacks = 400 }; +enum { k_iSteamMatchmakingCallbacks = 500 }; +enum { k_iSteamContentServerCallbacks = 600 }; +enum { k_iSteamUtilsCallbacks = 700 }; +enum { k_iClientFriendsCallbacks = 800 }; +enum { k_iClientUserCallbacks = 900 }; +enum { k_iSteamAppsCallbacks = 1000 }; +enum { k_iSteamUserStatsCallbacks = 1100 }; +enum { k_iSteamNetworkingCallbacks = 1200 }; +enum { k_iClientRemoteStorageCallbacks = 1300 }; +enum { k_iSteamUserItemsCallbacks = 1400 }; +enum { k_iSteamGameServerItemsCallbacks = 1500 }; +enum { k_iClientUtilsCallbacks = 1600 }; +enum { k_iSteamGameCoordinatorCallbacks = 1700 }; +enum { k_iSteamGameServerStatsCallbacks = 1800 }; +enum { k_iSteam2AsyncCallbacks = 1900 }; +enum { k_iSteamGameStatsCallbacks = 2000 }; +enum { k_iClientHTTPCallbacks = 2100 }; +enum { k_iClientScreenshotsCallbacks = 2200 }; +enum { k_iSteamScreenshotsCallbacks = 2300 }; +enum { k_iClientAudioCallbacks = 2400 }; +enum { k_iClientUnifiedMessagesCallbacks = 2500 }; +enum { k_iSteamStreamLauncherCallbacks = 2600 }; +enum { k_iClientControllerCallbacks = 2700 }; +enum { k_iSteamControllerCallbacks = 2800 }; +enum { k_iClientParentalSettingsCallbacks = 2900 }; +enum { k_iClientDeviceAuthCallbacks = 3000 }; +enum { k_iClientNetworkDeviceManagerCallbacks = 3100 }; + + +//----------------------------------------------------------------------------- +// The CALLBACK macros are for client side callback logging enabled with +// log_callback +// Do not change any of these. +//----------------------------------------------------------------------------- + +class CSteamCallback +{ +public: + virtual const char *GetCallbackName() const = 0; + virtual uint32 GetCallbackID() const = 0; + virtual uint8 *GetFixedData() const = 0; + virtual uint32 GetFixedSize() const = 0; + virtual uint32 GetNumMemberVariables() const = 0; + virtual bool GetMemberVariable( uint32 index, uint32 &varOffset, uint32 &varSize, uint32 &varCount, const char **pszName, const char **pszType ) const = 0; +}; + +#define DEFINE_CALLBACK( callbackname, callbackid ) \ +struct callbackname##_t { \ + enum { k_iCallback = callbackid }; \ + static callbackname##_t *GetNullPointer() { return 0; } + +#define CALLBACK_MEMBER( varidx, vartype, varname ) \ + public: vartype varname ; \ + static void GetMemberVar_##varidx( unsigned int &varOffset, unsigned int &varSize, uint32 &varCount, const char **pszName, const char **pszType ) { \ + varOffset = (unsigned int)(size_t)&GetNullPointer()->varname; \ + varSize = sizeof( vartype ); \ + varCount = 1; \ + *pszName = #varname; *pszType = #vartype; } + +#define CALLBACK_ARRAY( varidx, vartype, varname, varcount ) \ + public: vartype varname [ varcount ]; \ + static void GetMemberVar_##varidx( unsigned int &varOffset, unsigned int &varSize, uint32 &varCount, const char **pszName, const char **pszType ) { \ + varOffset = (unsigned int)(size_t)&GetNullPointer()->varname[0]; \ + varSize = sizeof( vartype ); \ + varCount = varcount; \ + *pszName = #varname; *pszType = #vartype; } + + +#define END_CALLBACK_INTERNAL_BEGIN( callbackname, numvars ) }; \ +class C##callbackname : public CSteamCallback { \ +public: callbackname##_t m_Data; \ + C##callbackname () { memset( &m_Data, 0, sizeof(m_Data) ); } \ + virtual const char *GetCallbackName() const { return #callbackname; } \ + virtual uint32 GetCallbackID() const { return callbackname##_t::k_iCallback; } \ + virtual uint32 GetFixedSize() const { return sizeof( m_Data ); } \ + virtual uint8 *GetFixedData() const { return (uint8*)&m_Data; } \ + virtual uint32 GetNumMemberVariables() const { return numvars; } \ + virtual bool GetMemberVariable( uint32 index, uint32 &varOffset, uint32 &varSize, uint32 &varCount, const char **pszName, const char **pszType ) const { \ + switch ( index ) { default : return false; + + +#define END_CALLBACK_INTERNAL_SWITCH( varidx ) case varidx : m_Data.GetMemberVar_##varidx( varOffset, varSize, varCount, pszName, pszType ); return true; + +#define END_CALLBACK_INTERNAL_END() }; }; }; + +#define END_DEFINE_CALLBACK_0( callbackname ) }; \ +class C##callbackname : public CSteamCallback { \ +public: callbackname##_t m_Data; \ + virtual const char *GetCallbackName() const { return #callbackname; } \ + virtual uint32 GetCallbackID() const { return callbackname##_t::k_iCallback; } \ + virtual uint32 GetFixedSize() const { return sizeof( m_Data ); } \ + virtual uint8 *GetFixedData() const { return (uint8*)&m_Data; } \ + virtual uint32 GetNumMemberVariables() const { return 0; } \ + virtual bool GetMemberVariable( uint32 index, uint32 &varOffset, uint32 &varSize, uint32 &varCount, const char **pszName, const char **pszType ) const { return false; } \ + }; \ + + +#define END_DEFINE_CALLBACK_1( callbackname ) \ + END_CALLBACK_INTERNAL_BEGIN( callbackname, 1 ) \ + END_CALLBACK_INTERNAL_SWITCH( 0 ) \ + END_CALLBACK_INTERNAL_END() + +#define END_DEFINE_CALLBACK_2( callbackname ) \ + END_CALLBACK_INTERNAL_BEGIN( callbackname, 2 ) \ + END_CALLBACK_INTERNAL_SWITCH( 0 ) \ + END_CALLBACK_INTERNAL_SWITCH( 1 ) \ + END_CALLBACK_INTERNAL_END() + +#define END_DEFINE_CALLBACK_3( callbackname ) \ + END_CALLBACK_INTERNAL_BEGIN( callbackname, 3 ) \ + END_CALLBACK_INTERNAL_SWITCH( 0 ) \ + END_CALLBACK_INTERNAL_SWITCH( 1 ) \ + END_CALLBACK_INTERNAL_SWITCH( 2 ) \ + END_CALLBACK_INTERNAL_END() + +#define END_DEFINE_CALLBACK_4( callbackname ) \ + END_CALLBACK_INTERNAL_BEGIN( callbackname, 4 ) \ + END_CALLBACK_INTERNAL_SWITCH( 0 ) \ + END_CALLBACK_INTERNAL_SWITCH( 1 ) \ + END_CALLBACK_INTERNAL_SWITCH( 2 ) \ + END_CALLBACK_INTERNAL_SWITCH( 3 ) \ + END_CALLBACK_INTERNAL_END() + + +#define END_DEFINE_CALLBACK_6( callbackname ) \ + END_CALLBACK_INTERNAL_BEGIN( callbackname, 6 ) \ + END_CALLBACK_INTERNAL_SWITCH( 0 ) \ + END_CALLBACK_INTERNAL_SWITCH( 1 ) \ + END_CALLBACK_INTERNAL_SWITCH( 2 ) \ + END_CALLBACK_INTERNAL_SWITCH( 3 ) \ + END_CALLBACK_INTERNAL_SWITCH( 4 ) \ + END_CALLBACK_INTERNAL_SWITCH( 5 ) \ + END_CALLBACK_INTERNAL_END() + +#define END_DEFINE_CALLBACK_7( callbackname ) \ + END_CALLBACK_INTERNAL_BEGIN( callbackname, 7 ) \ + END_CALLBACK_INTERNAL_SWITCH( 0 ) \ + END_CALLBACK_INTERNAL_SWITCH( 1 ) \ + END_CALLBACK_INTERNAL_SWITCH( 2 ) \ + END_CALLBACK_INTERNAL_SWITCH( 3 ) \ + END_CALLBACK_INTERNAL_SWITCH( 4 ) \ + END_CALLBACK_INTERNAL_SWITCH( 5 ) \ + END_CALLBACK_INTERNAL_SWITCH( 6 ) \ + END_CALLBACK_INTERNAL_END() + +#endif // ISTEAMCLIENT_H diff --git a/dep/rehlsdk/public/steam/isteamcontroller.h b/dep/rehlsdk/public/steam/isteamcontroller.h new file mode 100644 index 0000000..6975e56 --- /dev/null +++ b/dep/rehlsdk/public/steam/isteamcontroller.h @@ -0,0 +1,62 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to valve controller +// +//============================================================================= + +#ifndef ISTEAMCONTROLLER_H +#define ISTEAMCONTROLLER_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + + +#pragma pack( pop ) + +//----------------------------------------------------------------------------- +// Purpose: Functions for accessing stats, achievements, and leaderboard information +//----------------------------------------------------------------------------- +class ISteamController +{ +public: + +}; + +#define STEAMCONTROLLER_INTERFACE_VERSION "STEAMCONTROLLER_INTERFACE_VERSION" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +/* +struct ControllerCallback_t +{ + enum { k_iCallback = k_iSteamControllerCallbacks + 1 }; + +}; +*/ + + +#pragma pack( pop ) + + +#endif // ISTEAMCONTROLLER_H diff --git a/dep/rehlsdk/public/steam/isteamfriends.h b/dep/rehlsdk/public/steam/isteamfriends.h new file mode 100644 index 0000000..fc0a8e7 --- /dev/null +++ b/dep/rehlsdk/public/steam/isteamfriends.h @@ -0,0 +1,606 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to both friends list data and general information about users +// +//============================================================================= + +#ifndef ISTEAMFRIENDS_H +#define ISTEAMFRIENDS_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" +#include "steamclientpublic.h" + + +//----------------------------------------------------------------------------- +// Purpose: set of relationships to other users +//----------------------------------------------------------------------------- +enum EFriendRelationship +{ + k_EFriendRelationshipNone = 0, + k_EFriendRelationshipBlocked = 1, + k_EFriendRelationshipRequestRecipient = 2, + k_EFriendRelationshipFriend = 3, + k_EFriendRelationshipRequestInitiator = 4, + k_EFriendRelationshipIgnored = 5, + k_EFriendRelationshipIgnoredFriend = 6, + k_EFriendRelationshipSuggested = 7, + + // keep this updated + k_EFriendRelationshipMax = 8, +}; + +// maximum length of friend group name (not including terminating nul!) +const int k_cchMaxFriendsGroupName = 64; + +// maximum number of groups a single user is allowed +const int k_cFriendsGroupLimit = 100; + +const int k_cEnumerateFollowersMax = 50; + + +//----------------------------------------------------------------------------- +// Purpose: list of states a friend can be in +//----------------------------------------------------------------------------- +enum EPersonaState +{ + k_EPersonaStateOffline = 0, // friend is not currently logged on + k_EPersonaStateOnline = 1, // friend is logged on + k_EPersonaStateBusy = 2, // user is on, but busy + k_EPersonaStateAway = 3, // auto-away feature + k_EPersonaStateSnooze = 4, // auto-away for a long time + k_EPersonaStateLookingToTrade = 5, // Online, trading + k_EPersonaStateLookingToPlay = 6, // Online, wanting to play + k_EPersonaStateMax, +}; + + +//----------------------------------------------------------------------------- +// Purpose: flags for enumerating friends list, or quickly checking a the relationship between users +//----------------------------------------------------------------------------- +enum EFriendFlags +{ + k_EFriendFlagNone = 0x00, + k_EFriendFlagBlocked = 0x01, + k_EFriendFlagFriendshipRequested = 0x02, + k_EFriendFlagImmediate = 0x04, // "regular" friend + k_EFriendFlagClanMember = 0x08, + k_EFriendFlagOnGameServer = 0x10, + // k_EFriendFlagHasPlayedWith = 0x20, // not currently used + // k_EFriendFlagFriendOfFriend = 0x40, // not currently used + k_EFriendFlagRequestingFriendship = 0x80, + k_EFriendFlagRequestingInfo = 0x100, + k_EFriendFlagIgnored = 0x200, + k_EFriendFlagIgnoredFriend = 0x400, + k_EFriendFlagSuggested = 0x800, + k_EFriendFlagAll = 0xFFFF, +}; + + +// friend game played information +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif +struct FriendGameInfo_t +{ + CGameID m_gameID; + uint32 m_unGameIP; + uint16 m_usGamePort; + uint16 m_usQueryPort; + CSteamID m_steamIDLobby; +}; +#pragma pack( pop ) + +// maximum number of characters in a user's name. Two flavors; one for UTF-8 and one for UTF-16. +// The UTF-8 version has to be very generous to accomodate characters that get large when encoded +// in UTF-8. +enum +{ + k_cchPersonaNameMax = 128, + k_cwchPersonaNameMax = 32, +}; + +//----------------------------------------------------------------------------- +// Purpose: user restriction flags +//----------------------------------------------------------------------------- +enum EUserRestriction +{ + k_nUserRestrictionNone = 0, // no known chat/content restriction + k_nUserRestrictionUnknown = 1, // we don't know yet (user offline) + k_nUserRestrictionAnyChat = 2, // user is not allowed to (or can't) send/recv any chat + k_nUserRestrictionVoiceChat = 4, // user is not allowed to (or can't) send/recv voice chat + k_nUserRestrictionGroupChat = 8, // user is not allowed to (or can't) send/recv group chat + k_nUserRestrictionRating = 16, // user is too young according to rating in current region + k_nUserRestrictionGameInvites = 32, // user cannot send or recv game invites (e.g. mobile) + k_nUserRestrictionTrading = 64, // user cannot participate in trading (console, mobile) +}; + +//----------------------------------------------------------------------------- +// Purpose: information about user sessions +//----------------------------------------------------------------------------- +struct FriendSessionStateInfo_t +{ + uint32 m_uiOnlineSessionInstances; + uint8 m_uiPublishedToFriendsSessionInstance; +}; + + + +// size limit on chat room or member metadata +const uint32 k_cubChatMetadataMax = 8192; + +// size limits on Rich Presence data +enum { k_cchMaxRichPresenceKeys = 20 }; +enum { k_cchMaxRichPresenceKeyLength = 64 }; +enum { k_cchMaxRichPresenceValueLength = 256 }; + +// These values are passed as parameters to the store +enum EOverlayToStoreFlag +{ + k_EOverlayToStoreFlag_None = 0, + k_EOverlayToStoreFlag_AddToCart = 1, + k_EOverlayToStoreFlag_AddToCartAndShow = 2, +}; + +//----------------------------------------------------------------------------- +// Purpose: interface to accessing information about individual users, +// that can be a friend, in a group, on a game server or in a lobby with the local user +//----------------------------------------------------------------------------- +class ISteamFriends +{ +public: + // returns the local players name - guaranteed to not be NULL. + // this is the same name as on the users community profile page + // this is stored in UTF-8 format + // like all the other interface functions that return a char *, it's important that this pointer is not saved + // off; it will eventually be free'd or re-allocated + virtual const char *GetPersonaName() = 0; + + // Sets the player name, stores it on the server and publishes the changes to all friends who are online. + // Changes take place locally immediately, and a PersonaStateChange_t is posted, presuming success. + // + // The final results are available through the return value SteamAPICall_t, using SetPersonaNameResponse_t. + // + // If the name change fails to happen on the server, then an additional global PersonaStateChange_t will be posted + // to change the name back, in addition to the SetPersonaNameResponse_t callback. + virtual SteamAPICall_t SetPersonaName( const char *pchPersonaName ) = 0; + + // gets the status of the current user + virtual EPersonaState GetPersonaState() = 0; + + // friend iteration + // takes a set of k_EFriendFlags, and returns the number of users the client knows about who meet that criteria + // then GetFriendByIndex() can then be used to return the id's of each of those users + virtual int GetFriendCount( int iFriendFlags ) = 0; + + // returns the steamID of a user + // iFriend is a index of range [0, GetFriendCount()) + // iFriendsFlags must be the same value as used in GetFriendCount() + // the returned CSteamID can then be used by all the functions below to access details about the user + virtual CSteamID GetFriendByIndex( int iFriend, int iFriendFlags ) = 0; + + // returns a relationship to a user + virtual EFriendRelationship GetFriendRelationship( CSteamID steamIDFriend ) = 0; + + // returns the current status of the specified user + // this will only be known by the local user if steamIDFriend is in their friends list; on the same game server; in a chat room or lobby; or in a small group with the local user + virtual EPersonaState GetFriendPersonaState( CSteamID steamIDFriend ) = 0; + + // returns the name another user - guaranteed to not be NULL. + // same rules as GetFriendPersonaState() apply as to whether or not the user knowns the name of the other user + // note that on first joining a lobby, chat room or game server the local user will not known the name of the other users automatically; that information will arrive asyncronously + // + virtual const char *GetFriendPersonaName( CSteamID steamIDFriend ) = 0; + + // returns true if the friend is actually in a game, and fills in pFriendGameInfo with an extra details + virtual bool GetFriendGamePlayed( CSteamID steamIDFriend, FriendGameInfo_t *pFriendGameInfo ) = 0; + // accesses old friends names - returns an empty string when their are no more items in the history + virtual const char *GetFriendPersonaNameHistory( CSteamID steamIDFriend, int iPersonaName ) = 0; + + // returns true if the specified user meets any of the criteria specified in iFriendFlags + // iFriendFlags can be the union (binary or, |) of one or more k_EFriendFlags values + virtual bool HasFriend( CSteamID steamIDFriend, int iFriendFlags ) = 0; + + // clan (group) iteration and access functions + virtual int GetClanCount() = 0; + virtual CSteamID GetClanByIndex( int iClan ) = 0; + virtual const char *GetClanName( CSteamID steamIDClan ) = 0; + virtual const char *GetClanTag( CSteamID steamIDClan ) = 0; + // returns the most recent information we have about what's happening in a clan + virtual bool GetClanActivityCounts( CSteamID steamIDClan, int *pnOnline, int *pnInGame, int *pnChatting ) = 0; + // for clans a user is a member of, they will have reasonably up-to-date information, but for others you'll have to download the info to have the latest + virtual SteamAPICall_t DownloadClanActivityCounts( CSteamID *psteamIDClans, int cClansToRequest ) = 0; + + // iterators for getting users in a chat room, lobby, game server or clan + // note that large clans that cannot be iterated by the local user + // note that the current user must be in a lobby to retrieve CSteamIDs of other users in that lobby + // steamIDSource can be the steamID of a group, game server, lobby or chat room + virtual int GetFriendCountFromSource( CSteamID steamIDSource ) = 0; + virtual CSteamID GetFriendFromSourceByIndex( CSteamID steamIDSource, int iFriend ) = 0; + + // returns true if the local user can see that steamIDUser is a member or in steamIDSource + virtual bool IsUserInSource( CSteamID steamIDUser, CSteamID steamIDSource ) = 0; + + // User is in a game pressing the talk button (will suppress the microphone for all voice comms from the Steam friends UI) + virtual void SetInGameVoiceSpeaking( CSteamID steamIDUser, bool bSpeaking ) = 0; + + // activates the game overlay, with an optional dialog to open + // valid options are "Friends", "Community", "Players", "Settings", "OfficialGameGroup", "Stats", "Achievements" + virtual void ActivateGameOverlay( const char *pchDialog ) = 0; + + // activates game overlay to a specific place + // valid options are + // "steamid" - opens the overlay web browser to the specified user or groups profile + // "chat" - opens a chat window to the specified user, or joins the group chat + // "jointrade" - opens a window to a Steam Trading session that was started with the ISteamEconomy/StartTrade Web API + // "stats" - opens the overlay web browser to the specified user's stats + // "achievements" - opens the overlay web browser to the specified user's achievements + // "friendadd" - opens the overlay in minimal mode prompting the user to add the target user as a friend + // "friendremove" - opens the overlay in minimal mode prompting the user to remove the target friend + // "friendrequestaccept" - opens the overlay in minimal mode prompting the user to accept an incoming friend invite + // "friendrequestignore" - opens the overlay in minimal mode prompting the user to ignore an incoming friend invite + virtual void ActivateGameOverlayToUser( const char *pchDialog, CSteamID steamID ) = 0; + + // activates game overlay web browser directly to the specified URL + // full address with protocol type is required, e.g. http://www.steamgames.com/ + virtual void ActivateGameOverlayToWebPage( const char *pchURL ) = 0; + + // activates game overlay to store page for app + virtual void ActivateGameOverlayToStore( AppId_t nAppID, EOverlayToStoreFlag eFlag ) = 0; + + // Mark a target user as 'played with'. This is a client-side only feature that requires that the calling user is + // in game + virtual void SetPlayedWith( CSteamID steamIDUserPlayedWith ) = 0; + + // activates game overlay to open the invite dialog. Invitations will be sent for the provided lobby. + virtual void ActivateGameOverlayInviteDialog( CSteamID steamIDLobby ) = 0; + + // gets the small (32x32) avatar of the current user, which is a handle to be used in IClientUtils::GetImageRGBA(), or 0 if none set + virtual int GetSmallFriendAvatar( CSteamID steamIDFriend ) = 0; + + // gets the medium (64x64) avatar of the current user, which is a handle to be used in IClientUtils::GetImageRGBA(), or 0 if none set + virtual int GetMediumFriendAvatar( CSteamID steamIDFriend ) = 0; + + // gets the large (184x184) avatar of the current user, which is a handle to be used in IClientUtils::GetImageRGBA(), or 0 if none set + // returns -1 if this image has yet to be loaded, in this case wait for a AvatarImageLoaded_t callback and then call this again + virtual int GetLargeFriendAvatar( CSteamID steamIDFriend ) = 0; + + // requests information about a user - persona name & avatar + // if bRequireNameOnly is set, then the avatar of a user isn't downloaded + // - it's a lot slower to download avatars and churns the local cache, so if you don't need avatars, don't request them + // if returns true, it means that data is being requested, and a PersonaStateChanged_t callback will be posted when it's retrieved + // if returns false, it means that we already have all the details about that user, and functions can be called immediately + virtual bool RequestUserInformation( CSteamID steamIDUser, bool bRequireNameOnly ) = 0; + + // requests information about a clan officer list + // when complete, data is returned in ClanOfficerListResponse_t call result + // this makes available the calls below + // you can only ask about clans that a user is a member of + // note that this won't download avatars automatically; if you get an officer, + // and no avatar image is available, call RequestUserInformation( steamID, false ) to download the avatar + virtual SteamAPICall_t RequestClanOfficerList( CSteamID steamIDClan ) = 0; + + // iteration of clan officers - can only be done when a RequestClanOfficerList() call has completed + + // returns the steamID of the clan owner + virtual CSteamID GetClanOwner( CSteamID steamIDClan ) = 0; + // returns the number of officers in a clan (including the owner) + virtual int GetClanOfficerCount( CSteamID steamIDClan ) = 0; + // returns the steamID of a clan officer, by index, of range [0,GetClanOfficerCount) + virtual CSteamID GetClanOfficerByIndex( CSteamID steamIDClan, int iOfficer ) = 0; + // if current user is chat restricted, he can't send or receive any text/voice chat messages. + // the user can't see custom avatars. But the user can be online and send/recv game invites. + // a chat restricted user can't add friends or join any groups. + virtual uint32 GetUserRestrictions() = 0; + + // Rich Presence data is automatically shared between friends who are in the same game + // Each user has a set of Key/Value pairs + // Up to 20 different keys can be set + // There are two magic keys: + // "status" - a UTF-8 string that will show up in the 'view game info' dialog in the Steam friends list + // "connect" - a UTF-8 string that contains the command-line for how a friend can connect to a game + // GetFriendRichPresence() returns an empty string "" if no value is set + // SetRichPresence() to a NULL or an empty string deletes the key + // You can iterate the current set of keys for a friend with GetFriendRichPresenceKeyCount() + // and GetFriendRichPresenceKeyByIndex() (typically only used for debugging) + virtual bool SetRichPresence( const char *pchKey, const char *pchValue ) = 0; + virtual void ClearRichPresence() = 0; + virtual const char *GetFriendRichPresence( CSteamID steamIDFriend, const char *pchKey ) = 0; + virtual int GetFriendRichPresenceKeyCount( CSteamID steamIDFriend ) = 0; + virtual const char *GetFriendRichPresenceKeyByIndex( CSteamID steamIDFriend, int iKey ) = 0; + // Requests rich presence for a specific user. + virtual void RequestFriendRichPresence( CSteamID steamIDFriend ) = 0; + + // rich invite support + // if the target accepts the invite, the pchConnectString gets added to the command-line for launching the game + // if the game is already running, a GameRichPresenceJoinRequested_t callback is posted containing the connect string + // invites can only be sent to friends + virtual bool InviteUserToGame( CSteamID steamIDFriend, const char *pchConnectString ) = 0; + + // recently-played-with friends iteration + // this iterates the entire list of users recently played with, across games + // GetFriendCoplayTime() returns as a unix time + virtual int GetCoplayFriendCount() = 0; + virtual CSteamID GetCoplayFriend( int iCoplayFriend ) = 0; + virtual int GetFriendCoplayTime( CSteamID steamIDFriend ) = 0; + virtual AppId_t GetFriendCoplayGame( CSteamID steamIDFriend ) = 0; + + // chat interface for games + // this allows in-game access to group (clan) chats from in the game + // the behavior is somewhat sophisticated, because the user may or may not be already in the group chat from outside the game or in the overlay + // use ActivateGameOverlayToUser( "chat", steamIDClan ) to open the in-game overlay version of the chat + virtual SteamAPICall_t JoinClanChatRoom( CSteamID steamIDClan ) = 0; + virtual bool LeaveClanChatRoom( CSteamID steamIDClan ) = 0; + virtual int GetClanChatMemberCount( CSteamID steamIDClan ) = 0; + virtual CSteamID GetChatMemberByIndex( CSteamID steamIDClan, int iUser ) = 0; + virtual bool SendClanChatMessage( CSteamID steamIDClanChat, const char *pchText ) = 0; + virtual int GetClanChatMessage( CSteamID steamIDClanChat, int iMessage, void *prgchText, int cchTextMax, EChatEntryType *, CSteamID * ) = 0; + virtual bool IsClanChatAdmin( CSteamID steamIDClanChat, CSteamID steamIDUser ) = 0; + + // interact with the Steam (game overlay / desktop) + virtual bool IsClanChatWindowOpenInSteam( CSteamID steamIDClanChat ) = 0; + virtual bool OpenClanChatWindowInSteam( CSteamID steamIDClanChat ) = 0; + virtual bool CloseClanChatWindowInSteam( CSteamID steamIDClanChat ) = 0; + + // peer-to-peer chat interception + // this is so you can show P2P chats inline in the game + virtual bool SetListenForFriendsMessages( bool bInterceptEnabled ) = 0; + virtual bool ReplyToFriendMessage( CSteamID steamIDFriend, const char *pchMsgToSend ) = 0; + virtual int GetFriendMessage( CSteamID steamIDFriend, int iMessageID, void *pvData, int cubData, EChatEntryType *peChatEntryType ) = 0; + + // following apis + virtual SteamAPICall_t GetFollowerCount( CSteamID steamID ) = 0; + virtual SteamAPICall_t IsFollowing( CSteamID steamID ) = 0; + virtual SteamAPICall_t EnumerateFollowingList( uint32 unStartIndex ) = 0; +}; + +#define STEAMFRIENDS_INTERFACE_VERSION "SteamFriends013" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: called when a friends' status changes +//----------------------------------------------------------------------------- +struct PersonaStateChange_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 4 }; + + uint64 m_ulSteamID; // steamID of the friend who changed + int m_nChangeFlags; // what's changed +}; + + +// used in PersonaStateChange_t::m_nChangeFlags to describe what's changed about a user +// these flags describe what the client has learned has changed recently, so on startup you'll see a name, avatar & relationship change for every friend +enum EPersonaChange +{ + k_EPersonaChangeName = 0x0001, + k_EPersonaChangeStatus = 0x0002, + k_EPersonaChangeComeOnline = 0x0004, + k_EPersonaChangeGoneOffline = 0x0008, + k_EPersonaChangeGamePlayed = 0x0010, + k_EPersonaChangeGameServer = 0x0020, + k_EPersonaChangeAvatar = 0x0040, + k_EPersonaChangeJoinedSource= 0x0080, + k_EPersonaChangeLeftSource = 0x0100, + k_EPersonaChangeRelationshipChanged = 0x0200, + k_EPersonaChangeNameFirstSet = 0x0400, + k_EPersonaChangeFacebookInfo = 0x0800, + k_EPersonaChangeNickname = 0x1000, + k_EPersonaChangeSteamLevel = 0x2000, +}; + + +//----------------------------------------------------------------------------- +// Purpose: posted when game overlay activates or deactivates +// the game can use this to be pause or resume single player games +//----------------------------------------------------------------------------- +struct GameOverlayActivated_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 31 }; + uint8 m_bActive; // true if it's just been activated, false otherwise +}; + + +//----------------------------------------------------------------------------- +// Purpose: called when the user tries to join a different game server from their friends list +// game client should attempt to connect to specified server when this is received +//----------------------------------------------------------------------------- +struct GameServerChangeRequested_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 32 }; + char m_rgchServer[64]; // server address ("127.0.0.1:27015", "tf2.valvesoftware.com") + char m_rgchPassword[64]; // server password, if any +}; + + +//----------------------------------------------------------------------------- +// Purpose: called when the user tries to join a lobby from their friends list +// game client should attempt to connect to specified lobby when this is received +//----------------------------------------------------------------------------- +struct GameLobbyJoinRequested_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 33 }; + CSteamID m_steamIDLobby; + + // The friend they did the join via (will be invalid if not directly via a friend) + // + // On PS3, the friend will be invalid if this was triggered by a PSN invite via the XMB, but + // the account type will be console user so you can tell at least that this was from a PSN friend + // rather than a Steam friend. + CSteamID m_steamIDFriend; +}; + + +//----------------------------------------------------------------------------- +// Purpose: called when an avatar is loaded in from a previous GetLargeFriendAvatar() call +// if the image wasn't already available +//----------------------------------------------------------------------------- +struct AvatarImageLoaded_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 34 }; + CSteamID m_steamID; // steamid the avatar has been loaded for + int m_iImage; // the image index of the now loaded image + int m_iWide; // width of the loaded image + int m_iTall; // height of the loaded image +}; + + +//----------------------------------------------------------------------------- +// Purpose: marks the return of a request officer list call +//----------------------------------------------------------------------------- +struct ClanOfficerListResponse_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 35 }; + CSteamID m_steamIDClan; + int m_cOfficers; + uint8 m_bSuccess; +}; + + +//----------------------------------------------------------------------------- +// Purpose: callback indicating updated data about friends rich presence information +//----------------------------------------------------------------------------- +struct FriendRichPresenceUpdate_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 36 }; + CSteamID m_steamIDFriend; // friend who's rich presence has changed + AppId_t m_nAppID; // the appID of the game (should always be the current game) +}; + + +//----------------------------------------------------------------------------- +// Purpose: called when the user tries to join a game from their friends list +// rich presence will have been set with the "connect" key which is set here +//----------------------------------------------------------------------------- +struct GameRichPresenceJoinRequested_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 37 }; + CSteamID m_steamIDFriend; // the friend they did the join via (will be invalid if not directly via a friend) + char m_rgchConnect[k_cchMaxRichPresenceValueLength]; +}; + + +//----------------------------------------------------------------------------- +// Purpose: a chat message has been received for a clan chat the game has joined +//----------------------------------------------------------------------------- +struct GameConnectedClanChatMsg_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 38 }; + CSteamID m_steamIDClanChat; + CSteamID m_steamIDUser; + int m_iMessageID; +}; + + +//----------------------------------------------------------------------------- +// Purpose: a user has joined a clan chat +//----------------------------------------------------------------------------- +struct GameConnectedChatJoin_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 39 }; + CSteamID m_steamIDClanChat; + CSteamID m_steamIDUser; +}; + + +//----------------------------------------------------------------------------- +// Purpose: a user has left the chat we're in +//----------------------------------------------------------------------------- +struct GameConnectedChatLeave_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 40 }; + CSteamID m_steamIDClanChat; + CSteamID m_steamIDUser; + bool m_bKicked; // true if admin kicked + bool m_bDropped; // true if Steam connection dropped +}; + + +//----------------------------------------------------------------------------- +// Purpose: a DownloadClanActivityCounts() call has finished +//----------------------------------------------------------------------------- +struct DownloadClanActivityCountsResult_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 41 }; + bool m_bSuccess; +}; + + +//----------------------------------------------------------------------------- +// Purpose: a JoinClanChatRoom() call has finished +//----------------------------------------------------------------------------- +struct JoinClanChatRoomCompletionResult_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 42 }; + CSteamID m_steamIDClanChat; + EChatRoomEnterResponse m_eChatRoomEnterResponse; +}; + +//----------------------------------------------------------------------------- +// Purpose: a chat message has been received from a user +//----------------------------------------------------------------------------- +struct GameConnectedFriendChatMsg_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 43 }; + CSteamID m_steamIDUser; + int m_iMessageID; +}; + + +struct FriendsGetFollowerCount_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 44 }; + EResult m_eResult; + CSteamID m_steamID; + int m_nCount; +}; + + +struct FriendsIsFollowing_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 45 }; + EResult m_eResult; + CSteamID m_steamID; + bool m_bIsFollowing; +}; + + +struct FriendsEnumerateFollowingList_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 46 }; + EResult m_eResult; + CSteamID m_rgSteamID[ k_cEnumerateFollowersMax ]; + int32 m_nResultsReturned; + int32 m_nTotalResultCount; +}; + +//----------------------------------------------------------------------------- +// Purpose: reports the result of an attempt to change the user's persona name +//----------------------------------------------------------------------------- +struct SetPersonaNameResponse_t +{ + enum { k_iCallback = k_iSteamFriendsCallbacks + 47 }; + + bool m_bSuccess; // true if name change succeeded completely. + bool m_bLocalSuccess; // true if name change was retained locally. (We might not have been able to communicate with Steam) + EResult m_result; // detailed result code +}; + + +#pragma pack( pop ) + +#endif // ISTEAMFRIENDS_H diff --git a/dep/rehlsdk/public/steam/isteamgameserver.h b/dep/rehlsdk/public/steam/isteamgameserver.h new file mode 100644 index 0000000..c5667c1 --- /dev/null +++ b/dep/rehlsdk/public/steam/isteamgameserver.h @@ -0,0 +1,391 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to steam for game servers +// +//============================================================================= + +#ifndef ISTEAMGAMESERVER_H +#define ISTEAMGAMESERVER_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" + +#define MASTERSERVERUPDATERPORT_USEGAMESOCKETSHARE ((uint16)-1) + +//----------------------------------------------------------------------------- +// Purpose: Functions for authenticating users via Steam to play on a game server +//----------------------------------------------------------------------------- +class ISteamGameServer +{ +public: + +// +// Basic server data. These properties, if set, must be set before before calling LogOn. They +// may not be changed after logged in. +// + + /// This is called by SteamGameServer_Init, and you will usually not need to call it directly + virtual bool InitGameServer( uint32 unIP, uint16 usGamePort, uint16 usQueryPort, uint32 unFlags, AppId_t nGameAppId, const char *pchVersionString ) = 0; + + /// Game product identifier. This is currently used by the master server for version checking purposes. + /// It's a required field, but will eventually will go away, and the AppID will be used for this purpose. + virtual void SetProduct( const char *pszProduct ) = 0; + + /// Description of the game. This is a required field and is displayed in the steam server browser....for now. + /// This is a required field, but it will go away eventually, as the data should be determined from the AppID. + virtual void SetGameDescription( const char *pszGameDescription ) = 0; + + /// If your game is a "mod," pass the string that identifies it. The default is an empty string, meaning + /// this application is the original game, not a mod. + /// + /// @see k_cbMaxGameServerGameDir + virtual void SetModDir( const char *pszModDir ) = 0; + + /// Is this is a dedicated server? The default value is false. + virtual void SetDedicatedServer( bool bDedicated ) = 0; + +// +// Login +// + + /// Begin process to login to a persistent game server account + /// + /// You need to register for callbacks to determine the result of this operation. + /// @see SteamServersConnected_t + /// @see SteamServerConnectFailure_t + /// @see SteamServersDisconnected_t + virtual void LogOn( + const char *pszAccountName, + const char *pszPassword + ) = 0; + + /// Login to a generic, anonymous account. + /// + /// Note: in previous versions of the SDK, this was automatically called within SteamGameServer_Init, + /// but this is no longer the case. + virtual void LogOnAnonymous() = 0; + + /// Begin process of logging game server out of steam + virtual void LogOff() = 0; + + // status functions + virtual bool BLoggedOn() = 0; + virtual bool BSecure() = 0; + virtual CSteamID GetSteamID() = 0; + + /// Returns true if the master server has requested a restart. + /// Only returns true once per request. + virtual bool WasRestartRequested() = 0; + +// +// Server state. These properties may be changed at any time. +// + + /// Max player count that will be reported to server browser and client queries + virtual void SetMaxPlayerCount( int cPlayersMax ) = 0; + + /// Number of bots. Default value is zero + virtual void SetBotPlayerCount( int cBotplayers ) = 0; + + /// Set the name of server as it will appear in the server browser + /// + /// @see k_cbMaxGameServerName + virtual void SetServerName( const char *pszServerName ) = 0; + + /// Set name of map to report in the server browser + /// + /// @see k_cbMaxGameServerName + virtual void SetMapName( const char *pszMapName ) = 0; + + /// Let people know if your server will require a password + virtual void SetPasswordProtected( bool bPasswordProtected ) = 0; + + /// Spectator server. The default value is zero, meaning the service + /// is not used. + virtual void SetSpectatorPort( uint16 unSpectatorPort ) = 0; + + /// Name of the spectator server. (Only used if spectator port is nonzero.) + /// + /// @see k_cbMaxGameServerMapName + virtual void SetSpectatorServerName( const char *pszSpectatorServerName ) = 0; + + /// Call this to clear the whole list of key/values that are sent in rules queries. + virtual void ClearAllKeyValues() = 0; + + /// Call this to add/update a key/value pair. + virtual void SetKeyValue( const char *pKey, const char *pValue ) = 0; + + /// Sets a string defining the "gametags" for this server, this is optional, but if it is set + /// it allows users to filter in the matchmaking/server-browser interfaces based on the value + /// + /// @see k_cbMaxGameServerTags + virtual void SetGameTags( const char *pchGameTags ) = 0; + + /// Sets a string defining the "gamedata" for this server, this is optional, but if it is set + /// it allows users to filter in the matchmaking/server-browser interfaces based on the value + /// don't set this unless it actually changes, its only uploaded to the master once (when + /// acknowledged) + /// + /// @see k_cbMaxGameServerGameData + virtual void SetGameData( const char *pchGameData) = 0; + + /// Region identifier. This is an optional field, the default value is empty, meaning the "world" region + virtual void SetRegion( const char *pszRegion ) = 0; + +// +// Player list management / authentication +// + + // Handles receiving a new connection from a Steam user. This call will ask the Steam + // servers to validate the users identity, app ownership, and VAC status. If the Steam servers + // are off-line, then it will validate the cached ticket itself which will validate app ownership + // and identity. The AuthBlob here should be acquired on the game client using SteamUser()->InitiateGameConnection() + // and must then be sent up to the game server for authentication. + // + // Return Value: returns true if the users ticket passes basic checks. pSteamIDUser will contain the Steam ID of this user. pSteamIDUser must NOT be NULL + // If the call succeeds then you should expect a GSClientApprove_t or GSClientDeny_t callback which will tell you whether authentication + // for the user has succeeded or failed (the steamid in the callback will match the one returned by this call) + virtual bool SendUserConnectAndAuthenticate( uint32 unIPClient, const void *pvAuthBlob, uint32 cubAuthBlobSize, CSteamID *pSteamIDUser ) = 0; + + // Creates a fake user (ie, a bot) which will be listed as playing on the server, but skips validation. + // + // Return Value: Returns a SteamID for the user to be tracked with, you should call HandleUserDisconnect() + // when this user leaves the server just like you would for a real user. + virtual CSteamID CreateUnauthenticatedUserConnection() = 0; + + // Should be called whenever a user leaves our game server, this lets Steam internally + // track which users are currently on which servers for the purposes of preventing a single + // account being logged into multiple servers, showing who is currently on a server, etc. + virtual void SendUserDisconnect( CSteamID steamIDUser ) = 0; + + // Update the data to be displayed in the server browser and matchmaking interfaces for a user + // currently connected to the server. For regular users you must call this after you receive a + // GSUserValidationSuccess callback. + // + // Return Value: true if successful, false if failure (ie, steamIDUser wasn't for an active player) + virtual bool BUpdateUserData( CSteamID steamIDUser, const char *pchPlayerName, uint32 uScore ) = 0; + + // New auth system APIs - do not mix with the old auth system APIs. + // ---------------------------------------------------------------- + + // Retrieve ticket to be sent to the entity who wishes to authenticate you ( using BeginAuthSession API ). + // pcbTicket retrieves the length of the actual ticket. + virtual HAuthTicket GetAuthSessionTicket( void *pTicket, int cbMaxTicket, uint32 *pcbTicket ) = 0; + + // Authenticate ticket ( from GetAuthSessionTicket ) from entity steamID to be sure it is valid and isnt reused + // Registers for callbacks if the entity goes offline or cancels the ticket ( see ValidateAuthTicketResponse_t callback and EAuthSessionResponse ) + virtual EBeginAuthSessionResult BeginAuthSession( const void *pAuthTicket, int cbAuthTicket, CSteamID steamID ) = 0; + + // Stop tracking started by BeginAuthSession - called when no longer playing game with this entity + virtual void EndAuthSession( CSteamID steamID ) = 0; + + // Cancel auth ticket from GetAuthSessionTicket, called when no longer playing game with the entity you gave the ticket to + virtual void CancelAuthTicket( HAuthTicket hAuthTicket ) = 0; + + // After receiving a user's authentication data, and passing it to SendUserConnectAndAuthenticate, use this function + // to determine if the user owns downloadable content specified by the provided AppID. + virtual EUserHasLicenseForAppResult UserHasLicenseForApp( CSteamID steamID, AppId_t appID ) = 0; + + // Ask if a user in in the specified group, results returns async by GSUserGroupStatus_t + // returns false if we're not connected to the steam servers and thus cannot ask + virtual bool RequestUserGroupStatus( CSteamID steamIDUser, CSteamID steamIDGroup ) = 0; + +// +// Query steam for server data +// + + // Ask for the gameplay stats for the server. Results returned in a callback + virtual void GetGameplayStats( ) = 0; + + // Gets the reputation score for the game server. This API also checks if the server or some + // other server on the same IP is banned from the Steam master servers. + virtual SteamAPICall_t GetServerReputation( ) = 0; + + // Returns the public IP of the server according to Steam, useful when the server is + // behind NAT and you want to advertise its IP in a lobby for other clients to directly + // connect to + virtual uint32 GetPublicIP() = 0; + +// These are in GameSocketShare mode, where instead of ISteamGameServer creating its own +// socket to talk to the master server on, it lets the game use its socket to forward messages +// back and forth. This prevents us from requiring server ops to open up yet another port +// in their firewalls. +// +// the IP address and port should be in host order, i.e 127.0.0.1 == 0x7f000001 + + // These are used when you've elected to multiplex the game server's UDP socket + // rather than having the master server updater use its own sockets. + // + // Source games use this to simplify the job of the server admins, so they + // don't have to open up more ports on their firewalls. + + // Call this when a packet that starts with 0xFFFFFFFF comes in. That means + // it's for us. + virtual bool HandleIncomingPacket( const void *pData, int cbData, uint32 srcIP, uint16 srcPort ) = 0; + + // AFTER calling HandleIncomingPacket for any packets that came in that frame, call this. + // This gets a packet that the master server updater needs to send out on UDP. + // It returns the length of the packet it wants to send, or 0 if there are no more packets to send. + // Call this each frame until it returns 0. + virtual int GetNextOutgoingPacket( void *pOut, int cbMaxOut, uint32 *pNetAdr, uint16 *pPort ) = 0; + +// +// Control heartbeats / advertisement with master server +// + + // Call this as often as you like to tell the master server updater whether or not + // you want it to be active (default: off). + virtual void EnableHeartbeats( bool bActive ) = 0; + + // You usually don't need to modify this. + // Pass -1 to use the default value for iHeartbeatInterval. + // Some mods change this. + virtual void SetHeartbeatInterval( int iHeartbeatInterval ) = 0; + + // Force a heartbeat to steam at the next opportunity + virtual void ForceHeartbeat() = 0; + + // associate this game server with this clan for the purposes of computing player compat + virtual SteamAPICall_t AssociateWithClan( CSteamID steamIDClan ) = 0; + + // ask if any of the current players dont want to play with this new player - or vice versa + virtual SteamAPICall_t ComputeNewPlayerCompatibility( CSteamID steamIDNewPlayer ) = 0; + +}; + +#define STEAMGAMESERVER_INTERFACE_VERSION "SteamGameServer011" + +// game server flags +const uint32 k_unServerFlagNone = 0x00; +const uint32 k_unServerFlagActive = 0x01; // server has users playing +const uint32 k_unServerFlagSecure = 0x02; // server wants to be secure +const uint32 k_unServerFlagDedicated = 0x04; // server is dedicated +const uint32 k_unServerFlagLinux = 0x08; // linux build +const uint32 k_unServerFlagPassworded = 0x10; // password protected +const uint32 k_unServerFlagPrivate = 0x20; // server shouldn't list on master server and + // won't enforce authentication of users that connect to the server. + // Useful when you run a server where the clients may not + // be connected to the internet but you want them to play (i.e LANs) + + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + + +// client has been approved to connect to this game server +struct GSClientApprove_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 1 }; + CSteamID m_SteamID; +}; + + +// client has been denied to connection to this game server +struct GSClientDeny_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 2 }; + CSteamID m_SteamID; + EDenyReason m_eDenyReason; + char m_rgchOptionalText[128]; +}; + + +// request the game server should kick the user +struct GSClientKick_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 3 }; + CSteamID m_SteamID; + EDenyReason m_eDenyReason; +}; + +// NOTE: callback values 4 and 5 are skipped because they are used for old deprecated callbacks, +// do not reuse them here. + + +// client achievement info +struct GSClientAchievementStatus_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 6 }; + uint64 m_SteamID; + char m_pchAchievement[128]; + bool m_bUnlocked; +}; + +// received when the game server requests to be displayed as secure (VAC protected) +// m_bSecure is true if the game server should display itself as secure to users, false otherwise +struct GSPolicyResponse_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 15 }; + uint8 m_bSecure; +}; + +// GS gameplay stats info +struct GSGameplayStats_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 7 }; + EResult m_eResult; // Result of the call + int32 m_nRank; // Overall rank of the server (0-based) + uint32 m_unTotalConnects; // Total number of clients who have ever connected to the server + uint32 m_unTotalMinutesPlayed; // Total number of minutes ever played on the server +}; + +// send as a reply to RequestUserGroupStatus() +struct GSClientGroupStatus_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 8 }; + CSteamID m_SteamIDUser; + CSteamID m_SteamIDGroup; + bool m_bMember; + bool m_bOfficer; +}; + +// Sent as a reply to GetServerReputation() +struct GSReputation_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 9 }; + EResult m_eResult; // Result of the call; + uint32 m_unReputationScore; // The reputation score for the game server + bool m_bBanned; // True if the server is banned from the Steam + // master servers + + // The following members are only filled out if m_bBanned is true. They will all + // be set to zero otherwise. Master server bans are by IP so it is possible to be + // banned even when the score is good high if there is a bad server on another port. + // This information can be used to determine which server is bad. + + uint32 m_unBannedIP; // The IP of the banned server + uint16 m_usBannedPort; // The port of the banned server + uint64 m_ulBannedGameID; // The game ID the banned server is serving + uint32 m_unBanExpires; // Time the ban expires, expressed in the Unix epoch (seconds since 1/1/1970) +}; + +// Sent as a reply to AssociateWithClan() +struct AssociateWithClanResult_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 10 }; + EResult m_eResult; // Result of the call; +}; + +// Sent as a reply to ComputeNewPlayerCompatibility() +struct ComputeNewPlayerCompatibilityResult_t +{ + enum { k_iCallback = k_iSteamGameServerCallbacks + 11 }; + EResult m_eResult; // Result of the call; + int m_cPlayersThatDontLikeCandidate; + int m_cPlayersThatCandidateDoesntLike; + int m_cClanPlayersThatDontLikeCandidate; + CSteamID m_SteamIDCandidate; +}; + + +#pragma pack( pop ) + +#endif // ISTEAMGAMESERVER_H diff --git a/dep/rehlsdk/public/steam/isteamgameserverstats.h b/dep/rehlsdk/public/steam/isteamgameserverstats.h new file mode 100644 index 0000000..8d53186 --- /dev/null +++ b/dep/rehlsdk/public/steam/isteamgameserverstats.h @@ -0,0 +1,99 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface for game servers to steam stats and achievements +// +//============================================================================= + +#ifndef ISTEAMGAMESERVERSTATS_H +#define ISTEAMGAMESERVERSTATS_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" + +//----------------------------------------------------------------------------- +// Purpose: Functions for authenticating users via Steam to play on a game server +//----------------------------------------------------------------------------- +class ISteamGameServerStats +{ +public: + // downloads stats for the user + // returns a GSStatsReceived_t callback when completed + // if the user has no stats, GSStatsReceived_t.m_eResult will be set to k_EResultFail + // these stats will only be auto-updated for clients playing on the server. For other + // users you'll need to call RequestUserStats() again to refresh any data + virtual SteamAPICall_t RequestUserStats( CSteamID steamIDUser ) = 0; + + // requests stat information for a user, usable after a successful call to RequestUserStats() + virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, int32 *pData ) = 0; + virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, float *pData ) = 0; + virtual bool GetUserAchievement( CSteamID steamIDUser, const char *pchName, bool *pbAchieved ) = 0; + + // Set / update stats and achievements. + // Note: These updates will work only on stats game servers are allowed to edit and only for + // game servers that have been declared as officially controlled by the game creators. + // Set the IP range of your official servers on the Steamworks page + virtual bool SetUserStat( CSteamID steamIDUser, const char *pchName, int32 nData ) = 0; + virtual bool SetUserStat( CSteamID steamIDUser, const char *pchName, float fData ) = 0; + virtual bool UpdateUserAvgRateStat( CSteamID steamIDUser, const char *pchName, float flCountThisSession, double dSessionLength ) = 0; + + virtual bool SetUserAchievement( CSteamID steamIDUser, const char *pchName ) = 0; + virtual bool ClearUserAchievement( CSteamID steamIDUser, const char *pchName ) = 0; + + // Store the current data on the server, will get a GSStatsStored_t callback when set. + // + // If the callback has a result of k_EResultInvalidParam, one or more stats + // uploaded has been rejected, either because they broke constraints + // or were out of date. In this case the server sends back updated values. + // The stats should be re-iterated to keep in sync. + virtual SteamAPICall_t StoreUserStats( CSteamID steamIDUser ) = 0; +}; + +#define STEAMGAMESERVERSTATS_INTERFACE_VERSION "SteamGameServerStats001" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: called when the latests stats and achievements have been received +// from the server +//----------------------------------------------------------------------------- +struct GSStatsReceived_t +{ + enum { k_iCallback = k_iSteamGameServerStatsCallbacks }; + EResult m_eResult; // Success / error fetching the stats + CSteamID m_steamIDUser; // The user for whom the stats are retrieved for +}; + + +//----------------------------------------------------------------------------- +// Purpose: result of a request to store the user stats for a game +//----------------------------------------------------------------------------- +struct GSStatsStored_t +{ + enum { k_iCallback = k_iSteamGameServerStatsCallbacks + 1 }; + EResult m_eResult; // success / error + CSteamID m_steamIDUser; // The user for whom the stats were stored +}; + +//----------------------------------------------------------------------------- +// Purpose: Callback indicating that a user's stats have been unloaded. +// Call RequestUserStats again to access stats for this user +//----------------------------------------------------------------------------- +struct GSStatsUnloaded_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 8 }; + CSteamID m_steamIDUser; // User whose stats have been unloaded +}; + +#pragma pack( pop ) + + +#endif // ISTEAMGAMESERVERSTATS_H diff --git a/dep/rehlsdk/public/steam/isteamhttp.h b/dep/rehlsdk/public/steam/isteamhttp.h new file mode 100644 index 0000000..15b6528 --- /dev/null +++ b/dep/rehlsdk/public/steam/isteamhttp.h @@ -0,0 +1,176 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to http client +// +//============================================================================= + +#ifndef ISTEAMHTTP_H +#define ISTEAMHTTP_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" +#include "steamhttpenums.h" + +// Handle to a HTTP Request handle +typedef uint32 HTTPRequestHandle; +#define INVALID_HTTPREQUEST_HANDLE 0 + +//----------------------------------------------------------------------------- +// Purpose: interface to http client +//----------------------------------------------------------------------------- +class ISteamHTTP +{ +public: + + // Initializes a new HTTP request, returning a handle to use in further operations on it. Requires + // the method (GET or POST) and the absolute URL for the request. Only http requests (ie, not https) are + // currently supported, so this string must start with http:// or https:// and should look like http://store.steampowered.com/app/250/ + // or such. + virtual HTTPRequestHandle CreateHTTPRequest( EHTTPMethod eHTTPRequestMethod, const char *pchAbsoluteURL ) = 0; + + // Set a context value for the request, which will be returned in the HTTPRequestCompleted_t callback after + // sending the request. This is just so the caller can easily keep track of which callbacks go with which request data. + virtual bool SetHTTPRequestContextValue( HTTPRequestHandle hRequest, uint64 ulContextValue ) = 0; + + // Set a timeout in seconds for the HTTP request, must be called prior to sending the request. Default + // timeout is 60 seconds if you don't call this. Returns false if the handle is invalid, or the request + // has already been sent. + virtual bool SetHTTPRequestNetworkActivityTimeout( HTTPRequestHandle hRequest, uint32 unTimeoutSeconds ) = 0; + + // Set a request header value for the request, must be called prior to sending the request. Will + // return false if the handle is invalid or the request is already sent. + virtual bool SetHTTPRequestHeaderValue( HTTPRequestHandle hRequest, const char *pchHeaderName, const char *pchHeaderValue ) = 0; + + // Set a GET or POST parameter value on the request, which is set will depend on the EHTTPMethod specified + // when creating the request. Must be called prior to sending the request. Will return false if the + // handle is invalid or the request is already sent. + virtual bool SetHTTPRequestGetOrPostParameter( HTTPRequestHandle hRequest, const char *pchParamName, const char *pchParamValue ) = 0; + + // Sends the HTTP request, will return false on a bad handle, otherwise use SteamCallHandle to wait on + // asynchronous response via callback. + // + // Note: If the user is in offline mode in Steam, then this will add a only-if-cached cache-control + // header and only do a local cache lookup rather than sending any actual remote request. + virtual bool SendHTTPRequest( HTTPRequestHandle hRequest, SteamAPICall_t *pCallHandle ) = 0; + + // Sends the HTTP request, will return false on a bad handle, otherwise use SteamCallHandle to wait on + // asynchronous response via callback for completion, and listen for HTTPRequestHeadersReceived_t and + // HTTPRequestDataReceived_t callbacks while streaming. + virtual bool SendHTTPRequestAndStreamResponse( HTTPRequestHandle hRequest, SteamAPICall_t *pCallHandle ) = 0; + + // Defers a request you have sent, the actual HTTP client code may have many requests queued, and this will move + // the specified request to the tail of the queue. Returns false on invalid handle, or if the request is not yet sent. + virtual bool DeferHTTPRequest( HTTPRequestHandle hRequest ) = 0; + + // Prioritizes a request you have sent, the actual HTTP client code may have many requests queued, and this will move + // the specified request to the head of the queue. Returns false on invalid handle, or if the request is not yet sent. + virtual bool PrioritizeHTTPRequest( HTTPRequestHandle hRequest ) = 0; + + // Checks if a response header is present in a HTTP response given a handle from HTTPRequestCompleted_t, also + // returns the size of the header value if present so the caller and allocate a correctly sized buffer for + // GetHTTPResponseHeaderValue. + virtual bool GetHTTPResponseHeaderSize( HTTPRequestHandle hRequest, const char *pchHeaderName, uint32 *unResponseHeaderSize ) = 0; + + // Gets header values from a HTTP response given a handle from HTTPRequestCompleted_t, will return false if the + // header is not present or if your buffer is too small to contain it's value. You should first call + // BGetHTTPResponseHeaderSize to check for the presence of the header and to find out the size buffer needed. + virtual bool GetHTTPResponseHeaderValue( HTTPRequestHandle hRequest, const char *pchHeaderName, uint8 *pHeaderValueBuffer, uint32 unBufferSize ) = 0; + + // Gets the size of the body data from a HTTP response given a handle from HTTPRequestCompleted_t, will return false if the + // handle is invalid. + virtual bool GetHTTPResponseBodySize( HTTPRequestHandle hRequest, uint32 *unBodySize ) = 0; + + // Gets the body data from a HTTP response given a handle from HTTPRequestCompleted_t, will return false if the + // handle is invalid or is to a streaming response, or if the provided buffer is not the correct size. Use BGetHTTPResponseBodySize first to find out + // the correct buffer size to use. + virtual bool GetHTTPResponseBodyData( HTTPRequestHandle hRequest, uint8 *pBodyDataBuffer, uint32 unBufferSize ) = 0; + + // Gets the body data from a streaming HTTP response given a handle from HTTPRequestDataReceived_t. Will return false if the + // handle is invalid or is to a non-streaming response (meaning it wasn't sent with SendHTTPRequestAndStreamResponse), or if the buffer size and offset + // do not match the size and offset sent in HTTPRequestDataReceived_t. + virtual bool GetHTTPStreamingResponseBodyData( HTTPRequestHandle hRequest, uint32 cOffset, uint8 *pBodyDataBuffer, uint32 unBufferSize ) = 0; + + // Releases an HTTP response handle, should always be called to free resources after receiving a HTTPRequestCompleted_t + // callback and finishing using the response. + virtual bool ReleaseHTTPRequest( HTTPRequestHandle hRequest ) = 0; + + // Gets progress on downloading the body for the request. This will be zero unless a response header has already been + // received which included a content-length field. For responses that contain no content-length it will report + // zero for the duration of the request as the size is unknown until the connection closes. + virtual bool GetHTTPDownloadProgressPct( HTTPRequestHandle hRequest, float *pflPercentOut ) = 0; + + // Sets the body for an HTTP Post request. Will fail and return false on a GET request, and will fail if POST params + // have already been set for the request. Setting this raw body makes it the only contents for the post, the pchContentType + // parameter will set the content-type header for the request so the server may know how to interpret the body. + virtual bool SetHTTPRequestRawPostBody( HTTPRequestHandle hRequest, const char *pchContentType, uint8 *pubBody, uint32 unBodyLen ) = 0; +}; + +#define STEAMHTTP_INTERFACE_VERSION "STEAMHTTP_INTERFACE_VERSION002" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +struct HTTPRequestCompleted_t +{ + enum { k_iCallback = k_iClientHTTPCallbacks + 1 }; + + // Handle value for the request that has completed. + HTTPRequestHandle m_hRequest; + + // Context value that the user defined on the request that this callback is associated with, 0 if + // no context value was set. + uint64 m_ulContextValue; + + // This will be true if we actually got any sort of response from the server (even an error). + // It will be false if we failed due to an internal error or client side network failure. + bool m_bRequestSuccessful; + + // Will be the HTTP status code value returned by the server, k_EHTTPStatusCode200OK is the normal + // OK response, if you get something else you probably need to treat it as a failure. + EHTTPStatusCode m_eStatusCode; +}; + + +struct HTTPRequestHeadersReceived_t +{ + enum { k_iCallback = k_iClientHTTPCallbacks + 2 }; + + // Handle value for the request that has received headers. + HTTPRequestHandle m_hRequest; + + // Context value that the user defined on the request that this callback is associated with, 0 if + // no context value was set. + uint64 m_ulContextValue; +}; + +struct HTTPRequestDataReceived_t +{ + enum { k_iCallback = k_iClientHTTPCallbacks + 3 }; + + // Handle value for the request that has received data. + HTTPRequestHandle m_hRequest; + + // Context value that the user defined on the request that this callback is associated with, 0 if + // no context value was set. + uint64 m_ulContextValue; + + + // Offset to provide to GetHTTPStreamingResponseBodyData to get this chunk of data + uint32 m_cOffset; + + // Size to provide to GetHTTPStreamingResponseBodyData to get this chunk of data + uint32 m_cBytesReceived; +}; + + +#pragma pack( pop ) + +#endif // ISTEAMHTTP_H diff --git a/dep/rehlsdk/public/steam/isteammatchmaking.h b/dep/rehlsdk/public/steam/isteammatchmaking.h new file mode 100644 index 0000000..3d664f5 --- /dev/null +++ b/dep/rehlsdk/public/steam/isteammatchmaking.h @@ -0,0 +1,731 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to steam managing game server/client match making +// +//============================================================================= + +#ifndef ISTEAMMATCHMAKING +#define ISTEAMMATCHMAKING +#ifdef _WIN32 +#pragma once +#endif + +#include "steamtypes.h" +#include "steamclientpublic.h" +#include "matchmakingtypes.h" +#include "isteamclient.h" +#include "isteamfriends.h" + +// lobby type description +enum ELobbyType +{ + k_ELobbyTypePrivate = 0, // only way to join the lobby is to invite to someone else + k_ELobbyTypeFriendsOnly = 1, // shows for friends or invitees, but not in lobby list + k_ELobbyTypePublic = 2, // visible for friends and in lobby list + k_ELobbyTypeInvisible = 3, // returned by search, but not visible to other friends + // useful if you want a user in two lobbies, for example matching groups together + // a user can be in only one regular lobby, and up to two invisible lobbies +}; + +// lobby search filter tools +enum ELobbyComparison +{ + k_ELobbyComparisonEqualToOrLessThan = -2, + k_ELobbyComparisonLessThan = -1, + k_ELobbyComparisonEqual = 0, + k_ELobbyComparisonGreaterThan = 1, + k_ELobbyComparisonEqualToOrGreaterThan = 2, + k_ELobbyComparisonNotEqual = 3, +}; + +// lobby search distance. Lobby results are sorted from closest to farthest. +enum ELobbyDistanceFilter +{ + k_ELobbyDistanceFilterClose, // only lobbies in the same immediate region will be returned + k_ELobbyDistanceFilterDefault, // only lobbies in the same region or near by regions + k_ELobbyDistanceFilterFar, // for games that don't have many latency requirements, will return lobbies about half-way around the globe + k_ELobbyDistanceFilterWorldwide, // no filtering, will match lobbies as far as India to NY (not recommended, expect multiple seconds of latency between the clients) +}; + +// maximum number of characters a lobby metadata key can be +#define k_nMaxLobbyKeyLength 255 + +//----------------------------------------------------------------------------- +// Purpose: Functions for match making services for clients to get to favorites +// and to operate on game lobbies. +//----------------------------------------------------------------------------- +class ISteamMatchmaking +{ +public: + // game server favorites storage + // saves basic details about a multiplayer game server locally + + // returns the number of favorites servers the user has stored + virtual int GetFavoriteGameCount() = 0; + + // returns the details of the game server + // iGame is of range [0,GetFavoriteGameCount()) + // *pnIP, *pnConnPort are filled in the with IP:port of the game server + // *punFlags specify whether the game server was stored as an explicit favorite or in the history of connections + // *pRTime32LastPlayedOnServer is filled in the with the Unix time the favorite was added + virtual bool GetFavoriteGame( int iGame, AppId_t *pnAppID, uint32 *pnIP, uint16 *pnConnPort, uint16 *pnQueryPort, uint32 *punFlags, uint32 *pRTime32LastPlayedOnServer ) = 0; + + // adds the game server to the local list; updates the time played of the server if it already exists in the list + virtual int AddFavoriteGame( AppId_t nAppID, uint32 nIP, uint16 nConnPort, uint16 nQueryPort, uint32 unFlags, uint32 rTime32LastPlayedOnServer ) =0; + + // removes the game server from the local storage; returns true if one was removed + virtual bool RemoveFavoriteGame( AppId_t nAppID, uint32 nIP, uint16 nConnPort, uint16 nQueryPort, uint32 unFlags ) = 0; + + /////// + // Game lobby functions + + // Get a list of relevant lobbies + // this is an asynchronous request + // results will be returned by LobbyMatchList_t callback & call result, with the number of lobbies found + // this will never return lobbies that are full + // to add more filter, the filter calls below need to be call before each and every RequestLobbyList() call + // use the CCallResult<> object in steam_api.h to match the SteamAPICall_t call result to a function in an object, e.g. + /* + class CMyLobbyListManager + { + CCallResult m_CallResultLobbyMatchList; + void FindLobbies() + { + // SteamMatchmaking()->AddRequestLobbyListFilter*() functions would be called here, before RequestLobbyList() + SteamAPICall_t hSteamAPICall = SteamMatchmaking()->RequestLobbyList(); + m_CallResultLobbyMatchList.Set( hSteamAPICall, this, &CMyLobbyListManager::OnLobbyMatchList ); + } + + void OnLobbyMatchList( LobbyMatchList_t *pLobbyMatchList, bool bIOFailure ) + { + // lobby list has be retrieved from Steam back-end, use results + } + } + */ + // + virtual SteamAPICall_t RequestLobbyList() = 0; + // filters for lobbies + // this needs to be called before RequestLobbyList() to take effect + // these are cleared on each call to RequestLobbyList() + virtual void AddRequestLobbyListStringFilter( const char *pchKeyToMatch, const char *pchValueToMatch, ELobbyComparison eComparisonType ) = 0; + // numerical comparison + virtual void AddRequestLobbyListNumericalFilter( const char *pchKeyToMatch, int nValueToMatch, ELobbyComparison eComparisonType ) = 0; + // returns results closest to the specified value. Multiple near filters can be added, with early filters taking precedence + virtual void AddRequestLobbyListNearValueFilter( const char *pchKeyToMatch, int nValueToBeCloseTo ) = 0; + // returns only lobbies with the specified number of slots available + virtual void AddRequestLobbyListFilterSlotsAvailable( int nSlotsAvailable ) = 0; + // sets the distance for which we should search for lobbies (based on users IP address to location map on the Steam backed) + virtual void AddRequestLobbyListDistanceFilter( ELobbyDistanceFilter eLobbyDistanceFilter ) = 0; + // sets how many results to return, the lower the count the faster it is to download the lobby results & details to the client + virtual void AddRequestLobbyListResultCountFilter( int cMaxResults ) = 0; + + virtual void AddRequestLobbyListCompatibleMembersFilter( CSteamID steamIDLobby ) = 0; + + // returns the CSteamID of a lobby, as retrieved by a RequestLobbyList call + // should only be called after a LobbyMatchList_t callback is received + // iLobby is of the range [0, LobbyMatchList_t::m_nLobbiesMatching) + // the returned CSteamID::IsValid() will be false if iLobby is out of range + virtual CSteamID GetLobbyByIndex( int iLobby ) = 0; + + // Create a lobby on the Steam servers. + // If private, then the lobby will not be returned by any RequestLobbyList() call; the CSteamID + // of the lobby will need to be communicated via game channels or via InviteUserToLobby() + // this is an asynchronous request + // results will be returned by LobbyCreated_t callback and call result; lobby is joined & ready to use at this point + // a LobbyEnter_t callback will also be received (since the local user is joining their own lobby) + virtual SteamAPICall_t CreateLobby( ELobbyType eLobbyType, int cMaxMembers ) = 0; + + // Joins an existing lobby + // this is an asynchronous request + // results will be returned by LobbyEnter_t callback & call result, check m_EChatRoomEnterResponse to see if was successful + // lobby metadata is available to use immediately on this call completing + virtual SteamAPICall_t JoinLobby( CSteamID steamIDLobby ) = 0; + + // Leave a lobby; this will take effect immediately on the client side + // other users in the lobby will be notified by a LobbyChatUpdate_t callback + virtual void LeaveLobby( CSteamID steamIDLobby ) = 0; + + // Invite another user to the lobby + // the target user will receive a LobbyInvite_t callback + // will return true if the invite is successfully sent, whether or not the target responds + // returns false if the local user is not connected to the Steam servers + // if the other user clicks the join link, a GameLobbyJoinRequested_t will be posted if the user is in-game, + // or if the game isn't running yet the game will be launched with the parameter +connect_lobby <64-bit lobby id> + virtual bool InviteUserToLobby( CSteamID steamIDLobby, CSteamID steamIDInvitee ) = 0; + + // Lobby iteration, for viewing details of users in a lobby + // only accessible if the lobby user is a member of the specified lobby + // persona information for other lobby members (name, avatar, etc.) will be asynchronously received + // and accessible via ISteamFriends interface + + // returns the number of users in the specified lobby + virtual int GetNumLobbyMembers( CSteamID steamIDLobby ) = 0; + // returns the CSteamID of a user in the lobby + // iMember is of range [0,GetNumLobbyMembers()) + // note that the current user must be in a lobby to retrieve CSteamIDs of other users in that lobby + virtual CSteamID GetLobbyMemberByIndex( CSteamID steamIDLobby, int iMember ) = 0; + + // Get data associated with this lobby + // takes a simple key, and returns the string associated with it + // "" will be returned if no value is set, or if steamIDLobby is invalid + virtual const char *GetLobbyData( CSteamID steamIDLobby, const char *pchKey ) = 0; + // Sets a key/value pair in the lobby metadata + // each user in the lobby will be broadcast this new value, and any new users joining will receive any existing data + // this can be used to set lobby names, map, etc. + // to reset a key, just set it to "" + // other users in the lobby will receive notification of the lobby data change via a LobbyDataUpdate_t callback + virtual bool SetLobbyData( CSteamID steamIDLobby, const char *pchKey, const char *pchValue ) = 0; + + // returns the number of metadata keys set on the specified lobby + virtual int GetLobbyDataCount( CSteamID steamIDLobby ) = 0; + + // returns a lobby metadata key/values pair by index, of range [0, GetLobbyDataCount()) + virtual bool GetLobbyDataByIndex( CSteamID steamIDLobby, int iLobbyData, char *pchKey, int cchKeyBufferSize, char *pchValue, int cchValueBufferSize ) = 0; + + // removes a metadata key from the lobby + virtual bool DeleteLobbyData( CSteamID steamIDLobby, const char *pchKey ) = 0; + + // Gets per-user metadata for someone in this lobby + virtual const char *GetLobbyMemberData( CSteamID steamIDLobby, CSteamID steamIDUser, const char *pchKey ) = 0; + // Sets per-user metadata (for the local user implicitly) + virtual void SetLobbyMemberData( CSteamID steamIDLobby, const char *pchKey, const char *pchValue ) = 0; + + // Broadcasts a chat message to the all the users in the lobby + // users in the lobby (including the local user) will receive a LobbyChatMsg_t callback + // returns true if the message is successfully sent + // pvMsgBody can be binary or text data, up to 4k + // if pvMsgBody is text, cubMsgBody should be strlen( text ) + 1, to include the null terminator + virtual bool SendLobbyChatMsg( CSteamID steamIDLobby, const void *pvMsgBody, int cubMsgBody ) = 0; + // Get a chat message as specified in a LobbyChatMsg_t callback + // iChatID is the LobbyChatMsg_t::m_iChatID value in the callback + // *pSteamIDUser is filled in with the CSteamID of the member + // *pvData is filled in with the message itself + // return value is the number of bytes written into the buffer + virtual int GetLobbyChatEntry( CSteamID steamIDLobby, int iChatID, CSteamID *pSteamIDUser, void *pvData, int cubData, EChatEntryType *peChatEntryType ) = 0; + + // Refreshes metadata for a lobby you're not necessarily in right now + // you never do this for lobbies you're a member of, only if your + // this will send down all the metadata associated with a lobby + // this is an asynchronous call + // returns false if the local user is not connected to the Steam servers + // results will be returned by a LobbyDataUpdate_t callback + // if the specified lobby doesn't exist, LobbyDataUpdate_t::m_bSuccess will be set to false + virtual bool RequestLobbyData( CSteamID steamIDLobby ) = 0; + + // sets the game server associated with the lobby + // usually at this point, the users will join the specified game server + // either the IP/Port or the steamID of the game server has to be valid, depending on how you want the clients to be able to connect + virtual void SetLobbyGameServer( CSteamID steamIDLobby, uint32 unGameServerIP, uint16 unGameServerPort, CSteamID steamIDGameServer ) = 0; + // returns the details of a game server set in a lobby - returns false if there is no game server set, or that lobby doesn't exist + virtual bool GetLobbyGameServer( CSteamID steamIDLobby, uint32 *punGameServerIP, uint16 *punGameServerPort, CSteamID *psteamIDGameServer ) = 0; + + // set the limit on the # of users who can join the lobby + virtual bool SetLobbyMemberLimit( CSteamID steamIDLobby, int cMaxMembers ) = 0; + // returns the current limit on the # of users who can join the lobby; returns 0 if no limit is defined + virtual int GetLobbyMemberLimit( CSteamID steamIDLobby ) = 0; + + // updates which type of lobby it is + // only lobbies that are k_ELobbyTypePublic or k_ELobbyTypeInvisible, and are set to joinable, will be returned by RequestLobbyList() calls + virtual bool SetLobbyType( CSteamID steamIDLobby, ELobbyType eLobbyType ) = 0; + + // sets whether or not a lobby is joinable - defaults to true for a new lobby + // if set to false, no user can join, even if they are a friend or have been invited + virtual bool SetLobbyJoinable( CSteamID steamIDLobby, bool bLobbyJoinable ) = 0; + + // returns the current lobby owner + // you must be a member of the lobby to access this + // there always one lobby owner - if the current owner leaves, another user will become the owner + // it is possible (bur rare) to join a lobby just as the owner is leaving, thus entering a lobby with self as the owner + virtual CSteamID GetLobbyOwner( CSteamID steamIDLobby ) = 0; + + // changes who the lobby owner is + // you must be the lobby owner for this to succeed, and steamIDNewOwner must be in the lobby + // after completion, the local user will no longer be the owner + virtual bool SetLobbyOwner( CSteamID steamIDLobby, CSteamID steamIDNewOwner ) = 0; + + // link two lobbies for the purposes of checking player compatibility + // you must be the lobby owner of both lobbies + virtual bool SetLinkedLobby( CSteamID steamIDLobby, CSteamID steamIDLobbyDependent ) = 0; + +#ifdef _PS3 + // changes who the lobby owner is + // you must be the lobby owner for this to succeed, and steamIDNewOwner must be in the lobby + // after completion, the local user will no longer be the owner + virtual void CheckForPSNGameBootInvite( unsigned int iGameBootAttributes ) = 0; +#endif +}; +#define STEAMMATCHMAKING_INTERFACE_VERSION "SteamMatchMaking009" + + +//----------------------------------------------------------------------------- +// Callback interfaces for server list functions (see ISteamMatchmakingServers below) +// +// The idea here is that your game code implements objects that implement these +// interfaces to receive callback notifications after calling asynchronous functions +// inside the ISteamMatchmakingServers() interface below. +// +// This is different than normal Steam callback handling due to the potentially +// large size of server lists. +//----------------------------------------------------------------------------- + +//----------------------------------------------------------------------------- +// Typedef for handle type you will receive when requesting server list. +//----------------------------------------------------------------------------- +typedef void* HServerListRequest; + +//----------------------------------------------------------------------------- +// Purpose: Callback interface for receiving responses after a server list refresh +// or an individual server update. +// +// Since you get these callbacks after requesting full list refreshes you will +// usually implement this interface inside an object like CServerBrowser. If that +// object is getting destructed you should use ISteamMatchMakingServers()->CancelQuery() +// to cancel any in-progress queries so you don't get a callback into the destructed +// object and crash. +//----------------------------------------------------------------------------- +class ISteamMatchmakingServerListResponse +{ +public: + // Server has responded ok with updated data + virtual void ServerResponded( HServerListRequest hRequest, int iServer ) = 0; + + // Server has failed to respond + virtual void ServerFailedToRespond( HServerListRequest hRequest, int iServer ) = 0; + + // A list refresh you had initiated is now 100% completed + virtual void RefreshComplete( HServerListRequest hRequest, EMatchMakingServerResponse response ) = 0; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Callback interface for receiving responses after pinging an individual server +// +// These callbacks all occur in response to querying an individual server +// via the ISteamMatchmakingServers()->PingServer() call below. If you are +// destructing an object that implements this interface then you should call +// ISteamMatchmakingServers()->CancelServerQuery() passing in the handle to the query +// which is in progress. Failure to cancel in progress queries when destructing +// a callback handler may result in a crash when a callback later occurs. +//----------------------------------------------------------------------------- +class ISteamMatchmakingPingResponse +{ +public: + // Server has responded successfully and has updated data + virtual void ServerResponded( gameserveritem_t &server ) = 0; + + // Server failed to respond to the ping request + virtual void ServerFailedToRespond() = 0; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Callback interface for receiving responses after requesting details on +// who is playing on a particular server. +// +// These callbacks all occur in response to querying an individual server +// via the ISteamMatchmakingServers()->PlayerDetails() call below. If you are +// destructing an object that implements this interface then you should call +// ISteamMatchmakingServers()->CancelServerQuery() passing in the handle to the query +// which is in progress. Failure to cancel in progress queries when destructing +// a callback handler may result in a crash when a callback later occurs. +//----------------------------------------------------------------------------- +class ISteamMatchmakingPlayersResponse +{ +public: + // Got data on a new player on the server -- you'll get this callback once per player + // on the server which you have requested player data on. + virtual void AddPlayerToList( const char *pchName, int nScore, float flTimePlayed ) = 0; + + // The server failed to respond to the request for player details + virtual void PlayersFailedToRespond() = 0; + + // The server has finished responding to the player details request + // (ie, you won't get anymore AddPlayerToList callbacks) + virtual void PlayersRefreshComplete() = 0; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Callback interface for receiving responses after requesting rules +// details on a particular server. +// +// These callbacks all occur in response to querying an individual server +// via the ISteamMatchmakingServers()->ServerRules() call below. If you are +// destructing an object that implements this interface then you should call +// ISteamMatchmakingServers()->CancelServerQuery() passing in the handle to the query +// which is in progress. Failure to cancel in progress queries when destructing +// a callback handler may result in a crash when a callback later occurs. +//----------------------------------------------------------------------------- +class ISteamMatchmakingRulesResponse +{ +public: + // Got data on a rule on the server -- you'll get one of these per rule defined on + // the server you are querying + virtual void RulesResponded( const char *pchRule, const char *pchValue ) = 0; + + // The server failed to respond to the request for rule details + virtual void RulesFailedToRespond() = 0; + + // The server has finished responding to the rule details request + // (ie, you won't get anymore RulesResponded callbacks) + virtual void RulesRefreshComplete() = 0; +}; + + +//----------------------------------------------------------------------------- +// Typedef for handle type you will receive when querying details on an individual server. +//----------------------------------------------------------------------------- +typedef int HServerQuery; +const int HSERVERQUERY_INVALID = 0xffffffff; + +//----------------------------------------------------------------------------- +// Purpose: Functions for match making services for clients to get to game lists and details +//----------------------------------------------------------------------------- +class ISteamMatchmakingServers +{ +public: + // Request a new list of servers of a particular type. These calls each correspond to one of the EMatchMakingType values. + // Each call allocates a new asynchronous request object. + // Request object must be released by calling ReleaseRequest( hServerListRequest ) + virtual HServerListRequest RequestInternetServerList( AppId_t iApp, MatchMakingKeyValuePair_t **ppchFilters, uint32 nFilters, ISteamMatchmakingServerListResponse *pRequestServersResponse ) = 0; + virtual HServerListRequest RequestLANServerList( AppId_t iApp, ISteamMatchmakingServerListResponse *pRequestServersResponse ) = 0; + virtual HServerListRequest RequestFriendsServerList( AppId_t iApp, MatchMakingKeyValuePair_t **ppchFilters, uint32 nFilters, ISteamMatchmakingServerListResponse *pRequestServersResponse ) = 0; + virtual HServerListRequest RequestFavoritesServerList( AppId_t iApp, MatchMakingKeyValuePair_t **ppchFilters, uint32 nFilters, ISteamMatchmakingServerListResponse *pRequestServersResponse ) = 0; + virtual HServerListRequest RequestHistoryServerList( AppId_t iApp, MatchMakingKeyValuePair_t **ppchFilters, uint32 nFilters, ISteamMatchmakingServerListResponse *pRequestServersResponse ) = 0; + virtual HServerListRequest RequestSpectatorServerList( AppId_t iApp, MatchMakingKeyValuePair_t **ppchFilters, uint32 nFilters, ISteamMatchmakingServerListResponse *pRequestServersResponse ) = 0; + + // Releases the asynchronous request object and cancels any pending query on it if there's a pending query in progress. + // RefreshComplete callback is not posted when request is released. + virtual void ReleaseRequest( HServerListRequest hServerListRequest ) = 0; + + /* the filter operation codes that go in the key part of MatchMakingKeyValuePair_t should be one of these: + + "map" + - Server passes the filter if the server is playing the specified map. + "gamedataand" + - Server passes the filter if the server's game data (ISteamGameServer::SetGameData) contains all of the + specified strings. The value field is a comma-delimited list of strings to match. + "gamedataor" + - Server passes the filter if the server's game data (ISteamGameServer::SetGameData) contains at least one of the + specified strings. The value field is a comma-delimited list of strings to match. + "gamedatanor" + - Server passes the filter if the server's game data (ISteamGameServer::SetGameData) does not contain any + of the specified strings. The value field is a comma-delimited list of strings to check. + "gametagsand" + - Server passes the filter if the server's game tags (ISteamGameServer::SetGameTags) contains all + of the specified strings. The value field is a comma-delimited list of strings to check. + "gametagsnor" + - Server passes the filter if the server's game tags (ISteamGameServer::SetGameTags) does not contain any + of the specified strings. The value field is a comma-delimited list of strings to check. + "and" (x1 && x2 && ... && xn) + "or" (x1 || x2 || ... || xn) + "nand" !(x1 && x2 && ... && xn) + "nor" !(x1 || x2 || ... || xn) + - Performs Boolean operation on the following filters. The operand to this filter specifies + the "size" of the Boolean inputs to the operation, in Key/value pairs. (The keyvalue + pairs must immediately follow, i.e. this is a prefix logical operator notation.) + In the simplest case where Boolean expressions are not nested, this is simply + the number of operands. + + For example, to match servers on a particular map or with a particular tag, would would + use these filters. + + ( server.map == "cp_dustbowl" || server.gametags.contains("payload") ) + "or", "2" + "map", "cp_dustbowl" + "gametagsand", "payload" + + If logical inputs are nested, then the operand specifies the size of the entire + "length" of its operands, not the number of immediate children. + + ( server.map == "cp_dustbowl" || ( server.gametags.contains("payload") && !server.gametags.contains("payloadrace") ) ) + "or", "4" + "map", "cp_dustbowl" + "and", "2" + "gametagsand", "payload" + "gametagsnor", "payloadrace" + + Unary NOT can be achieved using either "nand" or "nor" with a single operand. + + "addr" + - Server passes the filter if the server's query address matches the specified IP or IP:port. + "gameaddr" + - Server passes the filter if the server's game address matches the specified IP or IP:port. + + The following filter operations ignore the "value" part of MatchMakingKeyValuePair_t + + "dedicated" + - Server passes the filter if it passed true to SetDedicatedServer. + "secure" + - Server passes the filter if the server is VAC-enabled. + "notfull" + - Server passes the filter if the player count is less than the reported max player count. + "hasplayers" + - Server passes the filter if the player count is greater than zero. + "noplayers" + - Server passes the filter if it doesn't have any players. + "linux" + - Server passes the filter if it's a linux server + */ + + // Get details on a given server in the list, you can get the valid range of index + // values by calling GetServerCount(). You will also receive index values in + // ISteamMatchmakingServerListResponse::ServerResponded() callbacks + virtual gameserveritem_t *GetServerDetails( HServerListRequest hRequest, int iServer ) = 0; + + // Cancel an request which is operation on the given list type. You should call this to cancel + // any in-progress requests before destructing a callback object that may have been passed + // to one of the above list request calls. Not doing so may result in a crash when a callback + // occurs on the destructed object. + // Canceling a query does not release the allocated request handle. + // The request handle must be released using ReleaseRequest( hRequest ) + virtual void CancelQuery( HServerListRequest hRequest ) = 0; + + // Ping every server in your list again but don't update the list of servers + // Query callback installed when the server list was requested will be used + // again to post notifications and RefreshComplete, so the callback must remain + // valid until another RefreshComplete is called on it or the request + // is released with ReleaseRequest( hRequest ) + virtual void RefreshQuery( HServerListRequest hRequest ) = 0; + + // Returns true if the list is currently refreshing its server list + virtual bool IsRefreshing( HServerListRequest hRequest ) = 0; + + // How many servers in the given list, GetServerDetails above takes 0... GetServerCount() - 1 + virtual int GetServerCount( HServerListRequest hRequest ) = 0; + + // Refresh a single server inside of a query (rather than all the servers ) + virtual void RefreshServer( HServerListRequest hRequest, int iServer ) = 0; + + + //----------------------------------------------------------------------------- + // Queries to individual servers directly via IP/Port + //----------------------------------------------------------------------------- + + // Request updated ping time and other details from a single server + virtual HServerQuery PingServer( uint32 unIP, uint16 usPort, ISteamMatchmakingPingResponse *pRequestServersResponse ) = 0; + + // Request the list of players currently playing on a server + virtual HServerQuery PlayerDetails( uint32 unIP, uint16 usPort, ISteamMatchmakingPlayersResponse *pRequestServersResponse ) = 0; + + // Request the list of rules that the server is running (See ISteamGameServer::SetKeyValue() to set the rules server side) + virtual HServerQuery ServerRules( uint32 unIP, uint16 usPort, ISteamMatchmakingRulesResponse *pRequestServersResponse ) = 0; + + // Cancel an outstanding Ping/Players/Rules query from above. You should call this to cancel + // any in-progress requests before destructing a callback object that may have been passed + // to one of the above calls to avoid crashing when callbacks occur. + virtual void CancelServerQuery( HServerQuery hServerQuery ) = 0; +}; +#define STEAMMATCHMAKINGSERVERS_INTERFACE_VERSION "SteamMatchMakingServers002" + +// game server flags +const uint32 k_unFavoriteFlagNone = 0x00; +const uint32 k_unFavoriteFlagFavorite = 0x01; // this game favorite entry is for the favorites list +const uint32 k_unFavoriteFlagHistory = 0x02; // this game favorite entry is for the history list + + +//----------------------------------------------------------------------------- +// Purpose: Used in ChatInfo messages - fields specific to a chat member - must fit in a uint32 +//----------------------------------------------------------------------------- +enum EChatMemberStateChange +{ + // Specific to joining / leaving the chatroom + k_EChatMemberStateChangeEntered = 0x0001, // This user has joined or is joining the chat room + k_EChatMemberStateChangeLeft = 0x0002, // This user has left or is leaving the chat room + k_EChatMemberStateChangeDisconnected = 0x0004, // User disconnected without leaving the chat first + k_EChatMemberStateChangeKicked = 0x0008, // User kicked + k_EChatMemberStateChangeBanned = 0x0010, // User kicked and banned +}; + +// returns true of the flags indicate that a user has been removed from the chat +#define BChatMemberStateChangeRemoved( rgfChatMemberStateChangeFlags ) ( rgfChatMemberStateChangeFlags & ( k_EChatMemberStateChangeDisconnected | k_EChatMemberStateChangeLeft | k_EChatMemberStateChangeKicked | k_EChatMemberStateChangeBanned ) ) + + +//----------------------------------------------------------------------------- +// Callbacks for ISteamMatchmaking (which go through the regular Steam callback registration system) +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: a server was added/removed from the favorites list, you should refresh now +//----------------------------------------------------------------------------- +struct FavoritesListChanged_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 2 }; + uint32 m_nIP; // an IP of 0 means reload the whole list, any other value means just one server + uint32 m_nQueryPort; + uint32 m_nConnPort; + uint32 m_nAppID; + uint32 m_nFlags; + bool m_bAdd; // true if this is adding the entry, otherwise it is a remove +}; + + +//----------------------------------------------------------------------------- +// Purpose: Someone has invited you to join a Lobby +// normally you don't need to do anything with this, since +// the Steam UI will also display a ' has invited you to the lobby, join?' dialog +// +// if the user outside a game chooses to join, your game will be launched with the parameter "+connect_lobby <64-bit lobby id>", +// or with the callback GameLobbyJoinRequested_t if they're already in-game +//----------------------------------------------------------------------------- +struct LobbyInvite_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 3 }; + + uint64 m_ulSteamIDUser; // Steam ID of the person making the invite + uint64 m_ulSteamIDLobby; // Steam ID of the Lobby + uint64 m_ulGameID; // GameID of the Lobby +}; + + +//----------------------------------------------------------------------------- +// Purpose: Sent on entering a lobby, or on failing to enter +// m_EChatRoomEnterResponse will be set to k_EChatRoomEnterResponseSuccess on success, +// or a higher value on failure (see enum EChatRoomEnterResponse) +//----------------------------------------------------------------------------- +struct LobbyEnter_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 4 }; + + uint64 m_ulSteamIDLobby; // SteamID of the Lobby you have entered + uint32 m_rgfChatPermissions; // Permissions of the current user + bool m_bLocked; // If true, then only invited users may join + uint32 m_EChatRoomEnterResponse; // EChatRoomEnterResponse +}; + + +//----------------------------------------------------------------------------- +// Purpose: The lobby metadata has changed +// if m_ulSteamIDMember is the steamID of a lobby member, use GetLobbyMemberData() to access per-user details +// if m_ulSteamIDMember == m_ulSteamIDLobby, use GetLobbyData() to access lobby metadata +//----------------------------------------------------------------------------- +struct LobbyDataUpdate_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 5 }; + + uint64 m_ulSteamIDLobby; // steamID of the Lobby + uint64 m_ulSteamIDMember; // steamID of the member whose data changed, or the room itself + uint8 m_bSuccess; // true if we lobby data was successfully changed; + // will only be false if RequestLobbyData() was called on a lobby that no longer exists +}; + + +//----------------------------------------------------------------------------- +// Purpose: The lobby chat room state has changed +// this is usually sent when a user has joined or left the lobby +//----------------------------------------------------------------------------- +struct LobbyChatUpdate_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 6 }; + + uint64 m_ulSteamIDLobby; // Lobby ID + uint64 m_ulSteamIDUserChanged; // user who's status in the lobby just changed - can be recipient + uint64 m_ulSteamIDMakingChange; // Chat member who made the change (different from SteamIDUserChange if kicking, muting, etc.) + // for example, if one user kicks another from the lobby, this will be set to the id of the user who initiated the kick + uint32 m_rgfChatMemberStateChange; // bitfield of EChatMemberStateChange values +}; + + +//----------------------------------------------------------------------------- +// Purpose: A chat message for this lobby has been sent +// use GetLobbyChatEntry( m_iChatID ) to retrieve the contents of this message +//----------------------------------------------------------------------------- +struct LobbyChatMsg_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 7 }; + + uint64 m_ulSteamIDLobby; // the lobby id this is in + uint64 m_ulSteamIDUser; // steamID of the user who has sent this message + uint8 m_eChatEntryType; // type of message + uint32 m_iChatID; // index of the chat entry to lookup +}; + + +//----------------------------------------------------------------------------- +// Purpose: A game created a game for all the members of the lobby to join, +// as triggered by a SetLobbyGameServer() +// it's up to the individual clients to take action on this; the usual +// game behavior is to leave the lobby and connect to the specified game server +//----------------------------------------------------------------------------- +struct LobbyGameCreated_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 9 }; + + uint64 m_ulSteamIDLobby; // the lobby we were in + uint64 m_ulSteamIDGameServer; // the new game server that has been created or found for the lobby members + uint32 m_unIP; // IP & Port of the game server (if any) + uint16 m_usPort; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Number of matching lobbies found +// iterate the returned lobbies with GetLobbyByIndex(), from values 0 to m_nLobbiesMatching-1 +//----------------------------------------------------------------------------- +struct LobbyMatchList_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 10 }; + uint32 m_nLobbiesMatching; // Number of lobbies that matched search criteria and we have SteamIDs for +}; + + +//----------------------------------------------------------------------------- +// Purpose: posted if a user is forcefully removed from a lobby +// can occur if a user loses connection to Steam +//----------------------------------------------------------------------------- +struct LobbyKicked_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 12 }; + uint64 m_ulSteamIDLobby; // Lobby + uint64 m_ulSteamIDAdmin; // User who kicked you - possibly the ID of the lobby itself + uint8 m_bKickedDueToDisconnect; // true if you were kicked from the lobby due to the user losing connection to Steam (currently always true) +}; + + +//----------------------------------------------------------------------------- +// Purpose: Result of our request to create a Lobby +// m_eResult == k_EResultOK on success +// at this point, the lobby has been joined and is ready for use +// a LobbyEnter_t callback will also be received (since the local user is joining their own lobby) +//----------------------------------------------------------------------------- +struct LobbyCreated_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 13 }; + + EResult m_eResult; // k_EResultOK - the lobby was successfully created + // k_EResultNoConnection - your Steam client doesn't have a connection to the back-end + // k_EResultTimeout - you the message to the Steam servers, but it didn't respond + // k_EResultFail - the server responded, but with an unknown internal error + // k_EResultAccessDenied - your game isn't set to allow lobbies, or your client does haven't rights to play the game + // k_EResultLimitExceeded - your game client has created too many lobbies + + uint64 m_ulSteamIDLobby; // chat room, zero if failed +}; + +// used by now obsolete RequestFriendsLobbiesResponse_t +// enum { k_iCallback = k_iSteamMatchmakingCallbacks + 14 }; + + +//----------------------------------------------------------------------------- +// Purpose: Result of CheckForPSNGameBootInvite +// m_eResult == k_EResultOK on success +// at this point, the local user may not have finishing joining this lobby; +// game code should wait until the subsequent LobbyEnter_t callback is received +//----------------------------------------------------------------------------- +struct PSNGameBootInviteResult_t +{ + enum { k_iCallback = k_iSteamMatchmakingCallbacks + 15 }; + + bool m_bGameBootInviteExists; + CSteamID m_steamIDLobby; // Should be valid if m_bGameBootInviteExists == true +}; +#pragma pack( pop ) + + +#endif // ISTEAMMATCHMAKING diff --git a/dep/rehlsdk/public/steam/isteamnetworking.h b/dep/rehlsdk/public/steam/isteamnetworking.h new file mode 100644 index 0000000..c77f7bf --- /dev/null +++ b/dep/rehlsdk/public/steam/isteamnetworking.h @@ -0,0 +1,306 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to steam managing network connections between game clients & servers +// +//============================================================================= + +#ifndef ISTEAMNETWORKING +#define ISTEAMNETWORKING +#ifdef _WIN32 +#pragma once +#endif + +#include "steamtypes.h" +#include "steamclientpublic.h" + + +// list of possible errors returned by SendP2PPacket() API +// these will be posted in the P2PSessionConnectFail_t callback +enum EP2PSessionError +{ + k_EP2PSessionErrorNone = 0, + k_EP2PSessionErrorNotRunningApp = 1, // target is not running the same game + k_EP2PSessionErrorNoRightsToApp = 2, // local user doesn't own the app that is running + k_EP2PSessionErrorDestinationNotLoggedIn = 3, // target user isn't connected to Steam + k_EP2PSessionErrorTimeout = 4, // target isn't responding, perhaps not calling AcceptP2PSessionWithUser() + // corporate firewalls can also block this (NAT traversal is not firewall traversal) + // make sure that UDP ports 3478, 4379, and 4380 are open in an outbound direction + k_EP2PSessionErrorMax = 5 +}; + +// SendP2PPacket() send types +// Typically k_EP2PSendUnreliable is what you want for UDP-like packets, k_EP2PSendReliable for TCP-like packets +enum EP2PSend +{ + // Basic UDP send. Packets can't be bigger than 1200 bytes (your typical MTU size). Can be lost, or arrive out of order (rare). + // The sending API does have some knowledge of the underlying connection, so if there is no NAT-traversal accomplished or + // there is a recognized adjustment happening on the connection, the packet will be batched until the connection is open again. + k_EP2PSendUnreliable = 0, + + // As above, but if the underlying p2p connection isn't yet established the packet will just be thrown away. Using this on the first + // packet sent to a remote host almost guarantees the packet will be dropped. + // This is only really useful for kinds of data that should never buffer up, i.e. voice payload packets + k_EP2PSendUnreliableNoDelay = 1, + + // Reliable message send. Can send up to 1MB of data in a single message. + // Does fragmentation/re-assembly of messages under the hood, as well as a sliding window for efficient sends of large chunks of data. + k_EP2PSendReliable = 2, + + // As above, but applies the Nagle algorithm to the send - sends will accumulate + // until the current MTU size (typically ~1200 bytes, but can change) or ~200ms has passed (Nagle algorithm). + // Useful if you want to send a set of smaller messages but have the coalesced into a single packet + // Since the reliable stream is all ordered, you can do several small message sends with k_EP2PSendReliableWithBuffering and then + // do a normal k_EP2PSendReliable to force all the buffered data to be sent. + k_EP2PSendReliableWithBuffering = 3, + +}; + + +// connection state to a specified user, returned by GetP2PSessionState() +// this is under-the-hood info about what's going on with a SendP2PPacket(), shouldn't be needed except for debuggin +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif +struct P2PSessionState_t +{ + uint8 m_bConnectionActive; // true if we've got an active open connection + uint8 m_bConnecting; // true if we're currently trying to establish a connection + uint8 m_eP2PSessionError; // last error recorded (see enum above) + uint8 m_bUsingRelay; // true if it's going through a relay server (TURN) + int32 m_nBytesQueuedForSend; + int32 m_nPacketsQueuedForSend; + uint32 m_nRemoteIP; // potential IP:Port of remote host. Could be TURN server. + uint16 m_nRemotePort; // Only exists for compatibility with older authentication api's +}; +#pragma pack( pop ) + + +// handle to a socket +typedef uint32 SNetSocket_t; // CreateP2PConnectionSocket() +typedef uint32 SNetListenSocket_t; // CreateListenSocket() + +// connection progress indicators, used by CreateP2PConnectionSocket() +enum ESNetSocketState +{ + k_ESNetSocketStateInvalid = 0, + + // communication is valid + k_ESNetSocketStateConnected = 1, + + // states while establishing a connection + k_ESNetSocketStateInitiated = 10, // the connection state machine has started + + // p2p connections + k_ESNetSocketStateLocalCandidatesFound = 11, // we've found our local IP info + k_ESNetSocketStateReceivedRemoteCandidates = 12,// we've received information from the remote machine, via the Steam back-end, about their IP info + + // direct connections + k_ESNetSocketStateChallengeHandshake = 15, // we've received a challenge packet from the server + + // failure states + k_ESNetSocketStateDisconnecting = 21, // the API shut it down, and we're in the process of telling the other end + k_ESNetSocketStateLocalDisconnect = 22, // the API shut it down, and we've completed shutdown + k_ESNetSocketStateTimeoutDuringConnect = 23, // we timed out while trying to creating the connection + k_ESNetSocketStateRemoteEndDisconnected = 24, // the remote end has disconnected from us + k_ESNetSocketStateConnectionBroken = 25, // connection has been broken; either the other end has disappeared or our local network connection has broke + +}; + +// describes how the socket is currently connected +enum ESNetSocketConnectionType +{ + k_ESNetSocketConnectionTypeNotConnected = 0, + k_ESNetSocketConnectionTypeUDP = 1, + k_ESNetSocketConnectionTypeUDPRelay = 2, +}; + + +//----------------------------------------------------------------------------- +// Purpose: Functions for making connections and sending data between clients, +// traversing NAT's where possible +//----------------------------------------------------------------------------- +class ISteamNetworking +{ +public: + //////////////////////////////////////////////////////////////////////////////////////////// + // Session-less connection functions + // automatically establishes NAT-traversing or Relay server connections + + // Sends a P2P packet to the specified user + // UDP-like, unreliable and a max packet size of 1200 bytes + // the first packet send may be delayed as the NAT-traversal code runs + // if we can't get through to the user, an error will be posted via the callback P2PSessionConnectFail_t + // see EP2PSend enum above for the descriptions of the different ways of sending packets + // + // nChannel is a routing number you can use to help route message to different systems - you'll have to call ReadP2PPacket() + // with the same channel number in order to retrieve the data on the other end + // using different channels to talk to the same user will still use the same underlying p2p connection, saving on resources + virtual bool SendP2PPacket( CSteamID steamIDRemote, const void *pubData, uint32 cubData, EP2PSend eP2PSendType, int nChannel = 0 ) = 0; + + // returns true if any data is available for read, and the amount of data that will need to be read + virtual bool IsP2PPacketAvailable( uint32 *pcubMsgSize, int nChannel = 0 ) = 0; + + // reads in a packet that has been sent from another user via SendP2PPacket() + // returns the size of the message and the steamID of the user who sent it in the last two parameters + // if the buffer passed in is too small, the message will be truncated + // this call is not blocking, and will return false if no data is available + virtual bool ReadP2PPacket( void *pubDest, uint32 cubDest, uint32 *pcubMsgSize, CSteamID *psteamIDRemote, int nChannel = 0 ) = 0; + + // AcceptP2PSessionWithUser() should only be called in response to a P2PSessionRequest_t callback + // P2PSessionRequest_t will be posted if another user tries to send you a packet that you haven't talked to yet + // if you don't want to talk to the user, just ignore the request + // if the user continues to send you packets, another P2PSessionRequest_t will be posted periodically + // this may be called multiple times for a single user + // (if you've called SendP2PPacket() on the other user, this implicitly accepts the session request) + virtual bool AcceptP2PSessionWithUser( CSteamID steamIDRemote ) = 0; + + // call CloseP2PSessionWithUser() when you're done talking to a user, will free up resources under-the-hood + // if the remote user tries to send data to you again, another P2PSessionRequest_t callback will be posted + virtual bool CloseP2PSessionWithUser( CSteamID steamIDRemote ) = 0; + + // call CloseP2PChannelWithUser() when you're done talking to a user on a specific channel. Once all channels + // open channels to a user have been closed, the open session to the user will be closed and new data from this + // user will trigger a P2PSessionRequest_t callback + virtual bool CloseP2PChannelWithUser( CSteamID steamIDRemote, int nChannel ) = 0; + + // fills out P2PSessionState_t structure with details about the underlying connection to the user + // should only needed for debugging purposes + // returns false if no connection exists to the specified user + virtual bool GetP2PSessionState( CSteamID steamIDRemote, P2PSessionState_t *pConnectionState ) = 0; + + // Allow P2P connections to fall back to being relayed through the Steam servers if a direct connection + // or NAT-traversal cannot be established. Only applies to connections created after setting this value, + // or to existing connections that need to automatically reconnect after this value is set. + // + // P2P packet relay is allowed by default + virtual bool AllowP2PPacketRelay( bool bAllow ) = 0; + + + //////////////////////////////////////////////////////////////////////////////////////////// + // LISTEN / CONNECT style interface functions + // + // This is an older set of functions designed around the Berkeley TCP sockets model + // it's preferential that you use the above P2P functions, they're more robust + // and these older functions will be removed eventually + // + //////////////////////////////////////////////////////////////////////////////////////////// + + + // creates a socket and listens others to connect + // will trigger a SocketStatusCallback_t callback on another client connecting + // nVirtualP2PPort is the unique ID that the client will connect to, in case you have multiple ports + // this can usually just be 0 unless you want multiple sets of connections + // unIP is the local IP address to bind to + // pass in 0 if you just want the default local IP + // unPort is the port to use + // pass in 0 if you don't want users to be able to connect via IP/Port, but expect to be always peer-to-peer connections only + virtual SNetListenSocket_t CreateListenSocket( int nVirtualP2PPort, uint32 nIP, uint16 nPort, bool bAllowUseOfPacketRelay ) = 0; + + // creates a socket and begin connection to a remote destination + // can connect via a known steamID (client or game server), or directly to an IP + // on success will trigger a SocketStatusCallback_t callback + // on failure or timeout will trigger a SocketStatusCallback_t callback with a failure code in m_eSNetSocketState + virtual SNetSocket_t CreateP2PConnectionSocket( CSteamID steamIDTarget, int nVirtualPort, int nTimeoutSec, bool bAllowUseOfPacketRelay ) = 0; + virtual SNetSocket_t CreateConnectionSocket( uint32 nIP, uint16 nPort, int nTimeoutSec ) = 0; + + // disconnects the connection to the socket, if any, and invalidates the handle + // any unread data on the socket will be thrown away + // if bNotifyRemoteEnd is set, socket will not be completely destroyed until the remote end acknowledges the disconnect + virtual bool DestroySocket( SNetSocket_t hSocket, bool bNotifyRemoteEnd ) = 0; + // destroying a listen socket will automatically kill all the regular sockets generated from it + virtual bool DestroyListenSocket( SNetListenSocket_t hSocket, bool bNotifyRemoteEnd ) = 0; + + // sending data + // must be a handle to a connected socket + // data is all sent via UDP, and thus send sizes are limited to 1200 bytes; after this, many routers will start dropping packets + // use the reliable flag with caution; although the resend rate is pretty aggressive, + // it can still cause stalls in receiving data (like TCP) + virtual bool SendDataOnSocket( SNetSocket_t hSocket, void *pubData, uint32 cubData, bool bReliable ) = 0; + + // receiving data + // returns false if there is no data remaining + // fills out *pcubMsgSize with the size of the next message, in bytes + virtual bool IsDataAvailableOnSocket( SNetSocket_t hSocket, uint32 *pcubMsgSize ) = 0; + + // fills in pubDest with the contents of the message + // messages are always complete, of the same size as was sent (i.e. packetized, not streaming) + // if *pcubMsgSize < cubDest, only partial data is written + // returns false if no data is available + virtual bool RetrieveDataFromSocket( SNetSocket_t hSocket, void *pubDest, uint32 cubDest, uint32 *pcubMsgSize ) = 0; + + // checks for data from any socket that has been connected off this listen socket + // returns false if there is no data remaining + // fills out *pcubMsgSize with the size of the next message, in bytes + // fills out *phSocket with the socket that data is available on + virtual bool IsDataAvailable( SNetListenSocket_t hListenSocket, uint32 *pcubMsgSize, SNetSocket_t *phSocket ) = 0; + + // retrieves data from any socket that has been connected off this listen socket + // fills in pubDest with the contents of the message + // messages are always complete, of the same size as was sent (i.e. packetized, not streaming) + // if *pcubMsgSize < cubDest, only partial data is written + // returns false if no data is available + // fills out *phSocket with the socket that data is available on + virtual bool RetrieveData( SNetListenSocket_t hListenSocket, void *pubDest, uint32 cubDest, uint32 *pcubMsgSize, SNetSocket_t *phSocket ) = 0; + + // returns information about the specified socket, filling out the contents of the pointers + virtual bool GetSocketInfo( SNetSocket_t hSocket, CSteamID *pSteamIDRemote, int *peSocketStatus, uint32 *punIPRemote, uint16 *punPortRemote ) = 0; + + // returns which local port the listen socket is bound to + // *pnIP and *pnPort will be 0 if the socket is set to listen for P2P connections only + virtual bool GetListenSocketInfo( SNetListenSocket_t hListenSocket, uint32 *pnIP, uint16 *pnPort ) = 0; + + // returns true to describe how the socket ended up connecting + virtual ESNetSocketConnectionType GetSocketConnectionType( SNetSocket_t hSocket ) = 0; + + // max packet size, in bytes + virtual int GetMaxPacketSize( SNetSocket_t hSocket ) = 0; +}; +#define STEAMNETWORKING_INTERFACE_VERSION "SteamNetworking005" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +// callback notification - a user wants to talk to us over the P2P channel via the SendP2PPacket() API +// in response, a call to AcceptP2PPacketsFromUser() needs to be made, if you want to talk with them +struct P2PSessionRequest_t +{ + enum { k_iCallback = k_iSteamNetworkingCallbacks + 2 }; + CSteamID m_steamIDRemote; // user who wants to talk to us +}; + + +// callback notification - packets can't get through to the specified user via the SendP2PPacket() API +// all packets queued packets unsent at this point will be dropped +// further attempts to send will retry making the connection (but will be dropped if we fail again) +struct P2PSessionConnectFail_t +{ + enum { k_iCallback = k_iSteamNetworkingCallbacks + 3 }; + CSteamID m_steamIDRemote; // user we were sending packets to + uint8 m_eP2PSessionError; // EP2PSessionError indicating why we're having trouble +}; + + +// callback notification - status of a socket has changed +// used as part of the CreateListenSocket() / CreateP2PConnectionSocket() +struct SocketStatusCallback_t +{ + enum { k_iCallback = k_iSteamNetworkingCallbacks + 1 }; + SNetSocket_t m_hSocket; // the socket used to send/receive data to the remote host + SNetListenSocket_t m_hListenSocket; // this is the server socket that we were listening on; NULL if this was an outgoing connection + CSteamID m_steamIDRemote; // remote steamID we have connected to, if it has one + int m_eSNetSocketState; // socket state, ESNetSocketState +}; + +#pragma pack( pop ) + +#endif // ISTEAMNETWORKING diff --git a/dep/rehlsdk/public/steam/isteamremotestorage.h b/dep/rehlsdk/public/steam/isteamremotestorage.h new file mode 100644 index 0000000..68f0f7e --- /dev/null +++ b/dep/rehlsdk/public/steam/isteamremotestorage.h @@ -0,0 +1,610 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: public interface to user remote file storage in Steam +// +//============================================================================= + +#ifndef ISTEAMREMOTESTORAGE_H +#define ISTEAMREMOTESTORAGE_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" + + +//----------------------------------------------------------------------------- +// Purpose: Defines the largest allowed file size. Cloud files cannot be written +// in a single chunk over 100MB (and cannot be over 200MB total.) +//----------------------------------------------------------------------------- +const uint32 k_unMaxCloudFileChunkSize = 100 * 1024 * 1024; + + +//----------------------------------------------------------------------------- +// Purpose: Structure that contains an array of const char * strings and the number of those strings +//----------------------------------------------------------------------------- +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif +struct SteamParamStringArray_t +{ + const char ** m_ppStrings; + int32 m_nNumStrings; +}; +#pragma pack( pop ) + +// A handle to a piece of user generated content +typedef uint64 UGCHandle_t; +typedef uint64 PublishedFileUpdateHandle_t; +typedef uint64 PublishedFileId_t; +const UGCHandle_t k_UGCHandleInvalid = 0xffffffffffffffffull; +const PublishedFileUpdateHandle_t k_PublishedFileUpdateHandleInvalid = 0xffffffffffffffffull; + +// Handle for writing to Steam Cloud +typedef uint64 UGCFileWriteStreamHandle_t; +const UGCFileWriteStreamHandle_t k_UGCFileStreamHandleInvalid = 0xffffffffffffffffull; + +const uint32 k_cchPublishedDocumentTitleMax = 128 + 1; +const uint32 k_cchPublishedDocumentDescriptionMax = 8000; +const uint32 k_cchPublishedDocumentChangeDescriptionMax = 8000; +const uint32 k_unEnumeratePublishedFilesMaxResults = 50; +const uint32 k_cchTagListMax = 1024 + 1; +const uint32 k_cchFilenameMax = 260; +const uint32 k_cchPublishedFileURLMax = 256; + +// Ways to handle a synchronization conflict +enum EResolveConflict +{ + k_EResolveConflictKeepClient = 1, // The local version of each file will be used to overwrite the server version + k_EResolveConflictKeepServer = 2, // The server version of each file will be used to overwrite the local version +}; + +enum ERemoteStoragePlatform +{ + k_ERemoteStoragePlatformNone = 0, + k_ERemoteStoragePlatformWindows = (1 << 0), + k_ERemoteStoragePlatformOSX = (1 << 1), + k_ERemoteStoragePlatformPS3 = (1 << 2), + k_ERemoteStoragePlatformLinux = (1 << 3), + k_ERemoteStoragePlatformReserved2 = (1 << 4), + + k_ERemoteStoragePlatformAll = 0xffffffff +}; + +enum ERemoteStoragePublishedFileVisibility +{ + k_ERemoteStoragePublishedFileVisibilityPublic = 0, + k_ERemoteStoragePublishedFileVisibilityFriendsOnly = 1, + k_ERemoteStoragePublishedFileVisibilityPrivate = 2, +}; + + +enum EWorkshopFileType +{ + k_EWorkshopFileTypeFirst = 0, + + k_EWorkshopFileTypeCommunity = 0, + k_EWorkshopFileTypeMicrotransaction = 1, + k_EWorkshopFileTypeCollection = 2, + k_EWorkshopFileTypeArt = 3, + k_EWorkshopFileTypeVideo = 4, + k_EWorkshopFileTypeScreenshot = 5, + k_EWorkshopFileTypeGame = 6, + k_EWorkshopFileTypeSoftware = 7, + k_EWorkshopFileTypeConcept = 8, + k_EWorkshopFileTypeWebGuide = 9, + k_EWorkshopFileTypeIntegratedGuide = 10, + k_EWorkshopFileTypeMerch = 11, + + // Update k_EWorkshopFileTypeMax if you add values + k_EWorkshopFileTypeMax = 12 + +}; + +enum EWorkshopVote +{ + k_EWorkshopVoteUnvoted = 0, + k_EWorkshopVoteFor = 1, + k_EWorkshopVoteAgainst = 2, +}; + +enum EWorkshopFileAction +{ + k_EWorkshopFileActionPlayed = 0, + k_EWorkshopFileActionCompleted = 1, +}; + +enum EWorkshopEnumerationType +{ + k_EWorkshopEnumerationTypeRankedByVote = 0, + k_EWorkshopEnumerationTypeRecent = 1, + k_EWorkshopEnumerationTypeTrending = 2, + k_EWorkshopEnumerationTypeFavoritesOfFriends = 3, + k_EWorkshopEnumerationTypeVotedByFriends = 4, + k_EWorkshopEnumerationTypeContentByFriends = 5, + k_EWorkshopEnumerationTypeRecentFromFollowedUsers = 6, +}; + +enum EWorkshopVideoProvider +{ + k_EWorkshopVideoProviderNone = 0, + k_EWorkshopVideoProviderYoutube = 1 +}; + +//----------------------------------------------------------------------------- +// Purpose: Functions for accessing, reading and writing files stored remotely +// and cached locally +//----------------------------------------------------------------------------- +class ISteamRemoteStorage +{ + public: + // NOTE + // + // Filenames are case-insensitive, and will be converted to lowercase automatically. + // So "foo.bar" and "Foo.bar" are the same file, and if you write "Foo.bar" then + // iterate the files, the filename returned will be "foo.bar". + // + + // file operations + virtual bool FileWrite( const char *pchFile, const void *pvData, int32 cubData ) = 0; + virtual int32 FileRead( const char *pchFile, void *pvData, int32 cubDataToRead ) = 0; + virtual bool FileForget( const char *pchFile ) = 0; + virtual bool FileDelete( const char *pchFile ) = 0; + virtual SteamAPICall_t FileShare( const char *pchFile ) = 0; + virtual bool SetSyncPlatforms( const char *pchFile, ERemoteStoragePlatform eRemoteStoragePlatform ) = 0; + + // file operations that cause network IO + virtual UGCFileWriteStreamHandle_t FileWriteStreamOpen( const char *pchFile ) = 0; + virtual bool FileWriteStreamWriteChunk( UGCFileWriteStreamHandle_t writeHandle, const void *pvData, int32 cubData ) = 0; + virtual bool FileWriteStreamClose( UGCFileWriteStreamHandle_t writeHandle ) = 0; + virtual bool FileWriteStreamCancel( UGCFileWriteStreamHandle_t writeHandle ) = 0; + + // file information + virtual bool FileExists( const char *pchFile ) = 0; + virtual bool FilePersisted( const char *pchFile ) = 0; + virtual int32 GetFileSize( const char *pchFile ) = 0; + virtual int64 GetFileTimestamp( const char *pchFile ) = 0; + virtual ERemoteStoragePlatform GetSyncPlatforms( const char *pchFile ) = 0; + + // iteration + virtual int32 GetFileCount() = 0; + virtual const char *GetFileNameAndSize( int iFile, int32 *pnFileSizeInBytes ) = 0; + + // configuration management + virtual bool GetQuota( int32 *pnTotalBytes, int32 *puAvailableBytes ) = 0; + virtual bool IsCloudEnabledForAccount() = 0; + virtual bool IsCloudEnabledForApp() = 0; + virtual void SetCloudEnabledForApp( bool bEnabled ) = 0; + + // user generated content + + // Downloads a UGC file. A priority value of 0 will download the file immediately, + // otherwise it will wait to download the file until all downloads with a lower priority + // value are completed. Downloads with equal priority will occur simultaneously. + virtual SteamAPICall_t UGCDownload( UGCHandle_t hContent, uint32 unPriority ) = 0; + + // Gets the amount of data downloaded so far for a piece of content. pnBytesExpected can be 0 if function returns false + // or if the transfer hasn't started yet, so be careful to check for that before dividing to get a percentage + virtual bool GetUGCDownloadProgress( UGCHandle_t hContent, int32 *pnBytesDownloaded, int32 *pnBytesExpected ) = 0; + + // Gets metadata for a file after it has been downloaded. This is the same metadata given in the RemoteStorageDownloadUGCResult_t call result + virtual bool GetUGCDetails( UGCHandle_t hContent, AppId_t *pnAppID, char **ppchName, int32 *pnFileSizeInBytes, CSteamID *pSteamIDOwner ) = 0; + + // After download, gets the content of the file. + // Small files can be read all at once by calling this function with an offset of 0 and cubDataToRead equal to the size of the file. + // Larger files can be read in chunks to reduce memory usage (since both sides of the IPC client and the game itself must allocate + // enough memory for each chunk). Once the last byte is read, the file is implicitly closed and further calls to UGCRead will fail + // unless UGCDownload is called again. + // For especially large files (anything over 100MB) it is a requirement that the file is read in chunks. + virtual int32 UGCRead( UGCHandle_t hContent, void *pvData, int32 cubDataToRead, uint32 cOffset ) = 0; + + // Functions to iterate through UGC that has finished downloading but has not yet been read via UGCRead() + virtual int32 GetCachedUGCCount() = 0; + virtual UGCHandle_t GetCachedUGCHandle( int32 iCachedContent ) = 0; + + // The following functions are only necessary on the Playstation 3. On PC & Mac, the Steam client will handle these operations for you + // On Playstation 3, the game controls which files are stored in the cloud, via FilePersist, FileFetch, and FileForget. + +#if defined(_PS3) || defined(_SERVER) + // Connect to Steam and get a list of files in the Cloud - results in a RemoteStorageAppSyncStatusCheck_t callback + virtual void GetFileListFromServer() = 0; + // Indicate this file should be downloaded in the next sync + virtual bool FileFetch( const char *pchFile ) = 0; + // Indicate this file should be persisted in the next sync + virtual bool FilePersist( const char *pchFile ) = 0; + // Pull any requested files down from the Cloud - results in a RemoteStorageAppSyncedClient_t callback + virtual bool SynchronizeToClient() = 0; + // Upload any requested files to the Cloud - results in a RemoteStorageAppSyncedServer_t callback + virtual bool SynchronizeToServer() = 0; + // Reset any fetch/persist/etc requests + virtual bool ResetFileRequestState() = 0; +#endif + + // publishing UGC + virtual SteamAPICall_t PublishWorkshopFile( const char *pchFile, const char *pchPreviewFile, AppId_t nConsumerAppId, const char *pchTitle, const char *pchDescription, ERemoteStoragePublishedFileVisibility eVisibility, SteamParamStringArray_t *pTags, EWorkshopFileType eWorkshopFileType ) = 0; + virtual PublishedFileUpdateHandle_t CreatePublishedFileUpdateRequest( PublishedFileId_t unPublishedFileId ) = 0; + virtual bool UpdatePublishedFileFile( PublishedFileUpdateHandle_t updateHandle, const char *pchFile ) = 0; + virtual bool UpdatePublishedFilePreviewFile( PublishedFileUpdateHandle_t updateHandle, const char *pchPreviewFile ) = 0; + virtual bool UpdatePublishedFileTitle( PublishedFileUpdateHandle_t updateHandle, const char *pchTitle ) = 0; + virtual bool UpdatePublishedFileDescription( PublishedFileUpdateHandle_t updateHandle, const char *pchDescription ) = 0; + virtual bool UpdatePublishedFileVisibility( PublishedFileUpdateHandle_t updateHandle, ERemoteStoragePublishedFileVisibility eVisibility ) = 0; + virtual bool UpdatePublishedFileTags( PublishedFileUpdateHandle_t updateHandle, SteamParamStringArray_t *pTags ) = 0; + virtual SteamAPICall_t CommitPublishedFileUpdate( PublishedFileUpdateHandle_t updateHandle ) = 0; + // Gets published file details for the given publishedfileid. If unMaxSecondsOld is greater than 0, + // cached data may be returned, depending on how long ago it was cached. A value of 0 will force a refresh, + // a value of -1 will use cached data if it exists, no matter how old it is. + virtual SteamAPICall_t GetPublishedFileDetails( PublishedFileId_t unPublishedFileId, uint32 unMaxSecondsOld ) = 0; + virtual SteamAPICall_t DeletePublishedFile( PublishedFileId_t unPublishedFileId ) = 0; + // enumerate the files that the current user published with this app + virtual SteamAPICall_t EnumerateUserPublishedFiles( uint32 unStartIndex ) = 0; + virtual SteamAPICall_t SubscribePublishedFile( PublishedFileId_t unPublishedFileId ) = 0; + virtual SteamAPICall_t EnumerateUserSubscribedFiles( uint32 unStartIndex ) = 0; + virtual SteamAPICall_t UnsubscribePublishedFile( PublishedFileId_t unPublishedFileId ) = 0; + virtual bool UpdatePublishedFileSetChangeDescription( PublishedFileUpdateHandle_t updateHandle, const char *pchChangeDescription ) = 0; + virtual SteamAPICall_t GetPublishedItemVoteDetails( PublishedFileId_t unPublishedFileId ) = 0; + virtual SteamAPICall_t UpdateUserPublishedItemVote( PublishedFileId_t unPublishedFileId, bool bVoteUp ) = 0; + virtual SteamAPICall_t GetUserPublishedItemVoteDetails( PublishedFileId_t unPublishedFileId ) = 0; + virtual SteamAPICall_t EnumerateUserSharedWorkshopFiles( CSteamID steamId, uint32 unStartIndex, SteamParamStringArray_t *pRequiredTags, SteamParamStringArray_t *pExcludedTags ) = 0; + virtual SteamAPICall_t PublishVideo( EWorkshopVideoProvider eVideoProvider, const char *pchVideoAccount, const char *pchVideoIdentifier, const char *pchPreviewFile, AppId_t nConsumerAppId, const char *pchTitle, const char *pchDescription, ERemoteStoragePublishedFileVisibility eVisibility, SteamParamStringArray_t *pTags ) = 0; + virtual SteamAPICall_t SetUserPublishedFileAction( PublishedFileId_t unPublishedFileId, EWorkshopFileAction eAction ) = 0; + virtual SteamAPICall_t EnumeratePublishedFilesByUserAction( EWorkshopFileAction eAction, uint32 unStartIndex ) = 0; + // this method enumerates the public view of workshop files + virtual SteamAPICall_t EnumeratePublishedWorkshopFiles( EWorkshopEnumerationType eEnumerationType, uint32 unStartIndex, uint32 unCount, uint32 unDays, SteamParamStringArray_t *pTags, SteamParamStringArray_t *pUserTags ) = 0; + + virtual SteamAPICall_t UGCDownloadToLocation( UGCHandle_t hContent, const char *pchLocation, uint32 unPriority ) = 0; +}; + +#define STEAMREMOTESTORAGE_INTERFACE_VERSION "STEAMREMOTESTORAGE_INTERFACE_VERSION011" + + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: sent when the local file cache is fully synced with the server for an app +// That means that an application can be started and has all latest files +//----------------------------------------------------------------------------- +struct RemoteStorageAppSyncedClient_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 1 }; + AppId_t m_nAppID; + EResult m_eResult; + int m_unNumDownloads; +}; + +//----------------------------------------------------------------------------- +// Purpose: sent when the server is fully synced with the local file cache for an app +// That means that we can shutdown Steam and our data is stored on the server +//----------------------------------------------------------------------------- +struct RemoteStorageAppSyncedServer_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 2 }; + AppId_t m_nAppID; + EResult m_eResult; + int m_unNumUploads; +}; + +//----------------------------------------------------------------------------- +// Purpose: Status of up and downloads during a sync session +// +//----------------------------------------------------------------------------- +struct RemoteStorageAppSyncProgress_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 3 }; + char m_rgchCurrentFile[k_cchFilenameMax]; // Current file being transferred + AppId_t m_nAppID; // App this info relates to + uint32 m_uBytesTransferredThisChunk; // Bytes transferred this chunk + double m_dAppPercentComplete; // Percent complete that this app's transfers are + bool m_bUploading; // if false, downloading +}; + +// +// IMPORTANT! k_iClientRemoteStorageCallbacks + 4 is used, see iclientremotestorage.h +// + + +//----------------------------------------------------------------------------- +// Purpose: Sent after we've determined the list of files that are out of sync +// with the server. +//----------------------------------------------------------------------------- +struct RemoteStorageAppSyncStatusCheck_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 5 }; + AppId_t m_nAppID; + EResult m_eResult; +}; + +//----------------------------------------------------------------------------- +// Purpose: Sent after a conflict resolution attempt. +//----------------------------------------------------------------------------- +struct RemoteStorageConflictResolution_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 6 }; + AppId_t m_nAppID; + EResult m_eResult; +}; + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to FileShare() +//----------------------------------------------------------------------------- +struct RemoteStorageFileShareResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 7 }; + EResult m_eResult; // The result of the operation + UGCHandle_t m_hFile; // The handle that can be shared with users and features +}; + + +// k_iClientRemoteStorageCallbacks + 8 is deprecated! Do not reuse + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to PublishFile() +//----------------------------------------------------------------------------- +struct RemoteStoragePublishFileResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 9 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; + bool m_bUserNeedsToAcceptWorkshopLegalAgreement; +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to DeletePublishedFile() +//----------------------------------------------------------------------------- +struct RemoteStorageDeletePublishedFileResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 11 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to EnumerateUserPublishedFiles() +//----------------------------------------------------------------------------- +struct RemoteStorageEnumerateUserPublishedFilesResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 12 }; + EResult m_eResult; // The result of the operation. + int32 m_nResultsReturned; + int32 m_nTotalResultCount; + PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to SubscribePublishedFile() +//----------------------------------------------------------------------------- +struct RemoteStorageSubscribePublishedFileResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 13 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to EnumerateSubscribePublishedFiles() +//----------------------------------------------------------------------------- +struct RemoteStorageEnumerateUserSubscribedFilesResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 14 }; + EResult m_eResult; // The result of the operation. + int32 m_nResultsReturned; + int32 m_nTotalResultCount; + PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; + uint32 m_rgRTimeSubscribed[ k_unEnumeratePublishedFilesMaxResults ]; +}; + +#if defined(VALVE_CALLBACK_PACK_SMALL) + VALVE_COMPILE_TIME_ASSERT( sizeof( RemoteStorageEnumerateUserSubscribedFilesResult_t ) == (1 + 1 + 1 + 50 + 100) * 4 ); +#elif defined(VALVE_CALLBACK_PACK_LARGE) + VALVE_COMPILE_TIME_ASSERT( sizeof( RemoteStorageEnumerateUserSubscribedFilesResult_t ) == (1 + 1 + 1 + 50 + 100) * 4 + 4 ); +#else +#warning You must first include isteamclient.h +#endif + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to UnsubscribePublishedFile() +//----------------------------------------------------------------------------- +struct RemoteStorageUnsubscribePublishedFileResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 15 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to CommitPublishedFileUpdate() +//----------------------------------------------------------------------------- +struct RemoteStorageUpdatePublishedFileResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 16 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; + bool m_bUserNeedsToAcceptWorkshopLegalAgreement; +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to UGCDownload() +//----------------------------------------------------------------------------- +struct RemoteStorageDownloadUGCResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 17 }; + EResult m_eResult; // The result of the operation. + UGCHandle_t m_hFile; // The handle to the file that was attempted to be downloaded. + AppId_t m_nAppID; // ID of the app that created this file. + int32 m_nSizeInBytes; // The size of the file that was downloaded, in bytes. + char m_pchFileName[k_cchFilenameMax]; // The name of the file that was downloaded. + uint64 m_ulSteamIDOwner; // Steam ID of the user who created this content. +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to GetPublishedFileDetails() +//----------------------------------------------------------------------------- +struct RemoteStorageGetPublishedFileDetailsResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 18 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; + AppId_t m_nCreatorAppID; // ID of the app that created this file. + AppId_t m_nConsumerAppID; // ID of the app that will consume this file. + char m_rgchTitle[k_cchPublishedDocumentTitleMax]; // title of document + char m_rgchDescription[k_cchPublishedDocumentDescriptionMax]; // description of document + UGCHandle_t m_hFile; // The handle of the primary file + UGCHandle_t m_hPreviewFile; // The handle of the preview file + uint64 m_ulSteamIDOwner; // Steam ID of the user who created this content. + uint32 m_rtimeCreated; // time when the published file was created + uint32 m_rtimeUpdated; // time when the published file was last updated + ERemoteStoragePublishedFileVisibility m_eVisibility; + bool m_bBanned; + char m_rgchTags[k_cchTagListMax]; // comma separated list of all tags associated with this file + bool m_bTagsTruncated; // whether the list of tags was too long to be returned in the provided buffer + char m_pchFileName[k_cchFilenameMax]; // The name of the primary file + int32 m_nFileSize; // Size of the primary file + int32 m_nPreviewFileSize; // Size of the preview file + char m_rgchURL[k_cchPublishedFileURLMax]; // URL (for a video or a website) + EWorkshopFileType m_eFileType; // Type of the file +}; + + +struct RemoteStorageEnumerateWorkshopFilesResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 19 }; + EResult m_eResult; + int32 m_nResultsReturned; + int32 m_nTotalResultCount; + PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; + float m_rgScore[ k_unEnumeratePublishedFilesMaxResults ]; +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of GetPublishedItemVoteDetails +//----------------------------------------------------------------------------- +struct RemoteStorageGetPublishedItemVoteDetailsResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 20 }; + EResult m_eResult; + PublishedFileId_t m_unPublishedFileId; + int32 m_nVotesFor; + int32 m_nVotesAgainst; + int32 m_nReports; + float m_fScore; +}; + + +//----------------------------------------------------------------------------- +// Purpose: User subscribed to a file for the app (from within the app or on the web) +//----------------------------------------------------------------------------- +struct RemoteStoragePublishedFileSubscribed_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 21 }; + PublishedFileId_t m_nPublishedFileId; // The published file id + AppId_t m_nAppID; // ID of the app that will consume this file. +}; + +//----------------------------------------------------------------------------- +// Purpose: User unsubscribed from a file for the app (from within the app or on the web) +//----------------------------------------------------------------------------- +struct RemoteStoragePublishedFileUnsubscribed_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 22 }; + PublishedFileId_t m_nPublishedFileId; // The published file id + AppId_t m_nAppID; // ID of the app that will consume this file. +}; + + +//----------------------------------------------------------------------------- +// Purpose: Published file that a user owns was deleted (from within the app or the web) +//----------------------------------------------------------------------------- +struct RemoteStoragePublishedFileDeleted_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 23 }; + PublishedFileId_t m_nPublishedFileId; // The published file id + AppId_t m_nAppID; // ID of the app that will consume this file. +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to UpdateUserPublishedItemVote() +//----------------------------------------------------------------------------- +struct RemoteStorageUpdateUserPublishedItemVoteResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 24 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; // The published file id +}; + + +//----------------------------------------------------------------------------- +// Purpose: The result of a call to GetUserPublishedItemVoteDetails() +//----------------------------------------------------------------------------- +struct RemoteStorageUserVoteDetails_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 25 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; // The published file id + EWorkshopVote m_eVote; // what the user voted +}; + +struct RemoteStorageEnumerateUserSharedWorkshopFilesResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 26 }; + EResult m_eResult; // The result of the operation. + int32 m_nResultsReturned; + int32 m_nTotalResultCount; + PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; +}; + +struct RemoteStorageSetUserPublishedFileActionResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 27 }; + EResult m_eResult; // The result of the operation. + PublishedFileId_t m_nPublishedFileId; // The published file id + EWorkshopFileAction m_eAction; // the action that was attempted +}; + +struct RemoteStorageEnumeratePublishedFilesByUserActionResult_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 28 }; + EResult m_eResult; // The result of the operation. + EWorkshopFileAction m_eAction; // the action that was filtered on + int32 m_nResultsReturned; + int32 m_nTotalResultCount; + PublishedFileId_t m_rgPublishedFileId[ k_unEnumeratePublishedFilesMaxResults ]; + uint32 m_rgRTimeUpdated[ k_unEnumeratePublishedFilesMaxResults ]; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Called periodically while a PublishWorkshopFile is in progress +//----------------------------------------------------------------------------- +struct RemoteStoragePublishFileProgress_t +{ + enum { k_iCallback = k_iClientRemoteStorageCallbacks + 29 }; + double m_dPercentFile; + bool m_bPreview; +}; + + + +#pragma pack( pop ) + + +#endif // ISTEAMREMOTESTORAGE_H diff --git a/dep/rehlsdk/public/steam/isteamscreenshots.h b/dep/rehlsdk/public/steam/isteamscreenshots.h new file mode 100644 index 0000000..1636c16 --- /dev/null +++ b/dep/rehlsdk/public/steam/isteamscreenshots.h @@ -0,0 +1,96 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: public interface to user remote file storage in Steam +// +//============================================================================= + +#ifndef ISTEAMSCREENSHOTS_H +#define ISTEAMSCREENSHOTS_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" + +const uint32 k_nScreenshotMaxTaggedUsers = 32; +const uint32 k_nScreenshotMaxTaggedPublishedFiles = 32; +const int k_cubUFSTagTypeMax = 255; +const int k_cubUFSTagValueMax = 255; + +// Required with of a thumbnail provided to AddScreenshotToLibrary. If you do not provide a thumbnail +// one will be generated. +const int k_ScreenshotThumbWidth = 200; + +// Handle is valid for the lifetime of your process and no longer +typedef uint32 ScreenshotHandle; +#define INVALID_SCREENSHOT_HANDLE 0 + +//----------------------------------------------------------------------------- +// Purpose: Functions for adding screenshots to the user's screenshot library +//----------------------------------------------------------------------------- +class ISteamScreenshots +{ +public: + // Writes a screenshot to the user's screenshot library given the raw image data, which must be in RGB format. + // The return value is a handle that is valid for the duration of the game process and can be used to apply tags. + virtual ScreenshotHandle WriteScreenshot( void *pubRGB, uint32 cubRGB, int nWidth, int nHeight ) = 0; + + // Adds a screenshot to the user's screenshot library from disk. If a thumbnail is provided, it must be 200 pixels wide and the same aspect ratio + // as the screenshot, otherwise a thumbnail will be generated if the user uploads the screenshot. The screenshots must be in either JPEG or TGA format. + // The return value is a handle that is valid for the duration of the game process and can be used to apply tags. + // JPEG, TGA, and PNG formats are supported. + virtual ScreenshotHandle AddScreenshotToLibrary( const char *pchFilename, const char *pchThumbnailFilename, int nWidth, int nHeight ) = 0; + + // Causes the Steam overlay to take a screenshot. If screenshots are being hooked by the game then a ScreenshotRequested_t callback is sent back to the game instead. + virtual void TriggerScreenshot() = 0; + + // Toggles whether the overlay handles screenshots when the user presses the screenshot hotkey, or the game handles them. If the game is hooking screenshots, + // then the ScreenshotRequested_t callback will be sent if the user presses the hotkey, and the game is expected to call WriteScreenshot or AddScreenshotToLibrary + // in response. + virtual void HookScreenshots( bool bHook ) = 0; + + // Sets metadata about a screenshot's location (for example, the name of the map) + virtual bool SetLocation( ScreenshotHandle hScreenshot, const char *pchLocation ) = 0; + + // Tags a user as being visible in the screenshot + virtual bool TagUser( ScreenshotHandle hScreenshot, CSteamID steamID ) = 0; + + // Tags a published file as being visible in the screenshot + virtual bool TagPublishedFile( ScreenshotHandle hScreenshot, PublishedFileId_t unPublishedFileID ) = 0; +}; + +#define STEAMSCREENSHOTS_INTERFACE_VERSION "STEAMSCREENSHOTS_INTERFACE_VERSION002" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif +//----------------------------------------------------------------------------- +// Purpose: Screenshot successfully written or otherwise added to the library +// and can now be tagged +//----------------------------------------------------------------------------- +struct ScreenshotReady_t +{ + enum { k_iCallback = k_iSteamScreenshotsCallbacks + 1 }; + ScreenshotHandle m_hLocal; + EResult m_eResult; +}; + +//----------------------------------------------------------------------------- +// Purpose: Screenshot has been requested by the user. Only sent if +// HookScreenshots() has been called, in which case Steam will not take +// the screenshot itself. +//----------------------------------------------------------------------------- +struct ScreenshotRequested_t +{ + enum { k_iCallback = k_iSteamScreenshotsCallbacks + 2 }; +}; + +#pragma pack( pop ) + + +#endif // ISTEAMSCREENSHOTS_H diff --git a/dep/rehlsdk/public/steam/isteamunifiedmessages.h b/dep/rehlsdk/public/steam/isteamunifiedmessages.h new file mode 100644 index 0000000..edee4a4 --- /dev/null +++ b/dep/rehlsdk/public/steam/isteamunifiedmessages.h @@ -0,0 +1,63 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: Interface to unified messages client +// +// You should not need to use this interface except if your product is using a language other than C++. +// Contact your Steam Tech contact for more details. +// +//============================================================================= + +#ifndef ISTEAMUNIFIEDMESSAGES_H +#define ISTEAMUNIFIEDMESSAGES_H +#ifdef _WIN32 +#pragma once +#endif + +typedef uint64 ClientUnifiedMessageHandle; + +class ISteamUnifiedMessages +{ +public: + static const ClientUnifiedMessageHandle k_InvalidUnifiedMessageHandle = 0; + + // Sends a service method (in binary serialized form) using the Steam Client. + // Returns a unified message handle (k_InvalidUnifiedMessageHandle if could not send the message). + virtual ClientUnifiedMessageHandle SendMethod( const char *pchServiceMethod, const void *pRequestBuffer, uint32 unRequestBufferSize, uint64 unContext ) = 0; + + // Gets the size of the response and the EResult. Returns false if the response is not ready yet. + virtual bool GetMethodResponseInfo( ClientUnifiedMessageHandle hHandle, uint32 *punResponseSize, EResult *peResult ) = 0; + + // Gets a response in binary serialized form (and optionally release the corresponding allocated memory). + virtual bool GetMethodResponseData( ClientUnifiedMessageHandle hHandle, void *pResponseBuffer, uint32 unResponseBufferSize, bool bAutoRelease ) = 0; + + // Releases the message and its corresponding allocated memory. + virtual bool ReleaseMethod( ClientUnifiedMessageHandle hHandle ) = 0; + + // Sends a service notification (in binary serialized form) using the Steam Client. + // Returns true if the notification was sent successfully. + virtual bool SendNotification( const char *pchServiceNotification, const void *pNotificationBuffer, uint32 unNotificationBufferSize ) = 0; +}; + +#define STEAMUNIFIEDMESSAGES_INTERFACE_VERSION "STEAMUNIFIEDMESSAGES_INTERFACE_VERSION001" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +struct SteamUnifiedMessagesSendMethodResult_t +{ + enum { k_iCallback = k_iClientUnifiedMessagesCallbacks + 1 }; + ClientUnifiedMessageHandle m_hHandle; // The handle returned by SendMethod(). + uint64 m_unContext; // Context provided when calling SendMethod(). + EResult m_eResult; // The result of the method call. + uint32 m_unResponseSize; // The size of the response. +}; + +#pragma pack( pop ) + +#endif // ISTEAMUNIFIEDMESSAGES_H diff --git a/dep/rehlsdk/public/steam/isteamuser.h b/dep/rehlsdk/public/steam/isteamuser.h new file mode 100644 index 0000000..5470acb --- /dev/null +++ b/dep/rehlsdk/public/steam/isteamuser.h @@ -0,0 +1,339 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to user account information in Steam +// +//============================================================================= + +#ifndef ISTEAMUSER_H +#define ISTEAMUSER_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" + +// structure that contains client callback data +// see callbacks documentation for more details +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif +struct CallbackMsg_t +{ + HSteamUser m_hSteamUser; + int m_iCallback; + uint8 *m_pubParam; + int m_cubParam; +}; +#pragma pack( pop ) + +// reference to a steam call, to filter results by +typedef int32 HSteamCall; + +//----------------------------------------------------------------------------- +// Purpose: Functions for accessing and manipulating a steam account +// associated with one client instance +//----------------------------------------------------------------------------- +class ISteamUser +{ +public: + // returns the HSteamUser this interface represents + // this is only used internally by the API, and by a few select interfaces that support multi-user + virtual HSteamUser GetHSteamUser() = 0; + + // returns true if the Steam client current has a live connection to the Steam servers. + // If false, it means there is no active connection due to either a networking issue on the local machine, or the Steam server is down/busy. + // The Steam client will automatically be trying to recreate the connection as often as possible. + virtual bool BLoggedOn() = 0; + + // returns the CSteamID of the account currently logged into the Steam client + // a CSteamID is a unique identifier for an account, and used to differentiate users in all parts of the Steamworks API + virtual CSteamID GetSteamID() = 0; + + // Multiplayer Authentication functions + + // InitiateGameConnection() starts the state machine for authenticating the game client with the game server + // It is the client portion of a three-way handshake between the client, the game server, and the steam servers + // + // Parameters: + // void *pAuthBlob - a pointer to empty memory that will be filled in with the authentication token. + // int cbMaxAuthBlob - the number of bytes of allocated memory in pBlob. Should be at least 2048 bytes. + // CSteamID steamIDGameServer - the steamID of the game server, received from the game server by the client + // CGameID gameID - the ID of the current game. For games without mods, this is just CGameID( ) + // uint32 unIPServer, uint16 usPortServer - the IP address of the game server + // bool bSecure - whether or not the client thinks that the game server is reporting itself as secure (i.e. VAC is running) + // + // return value - returns the number of bytes written to pBlob. If the return is 0, then the buffer passed in was too small, and the call has failed + // The contents of pBlob should then be sent to the game server, for it to use to complete the authentication process. + virtual int InitiateGameConnection( void *pAuthBlob, int cbMaxAuthBlob, CSteamID steamIDGameServer, uint32 unIPServer, uint16 usPortServer, bool bSecure ) = 0; + + // notify of disconnect + // needs to occur when the game client leaves the specified game server, needs to match with the InitiateGameConnection() call + virtual void TerminateGameConnection( uint32 unIPServer, uint16 usPortServer ) = 0; + + // Legacy functions + + // used by only a few games to track usage events + virtual void TrackAppUsageEvent( CGameID gameID, int eAppUsageEvent, const char *pchExtraInfo = "" ) = 0; + + // get the local storage folder for current Steam account to write application data, e.g. save games, configs etc. + // this will usually be something like "C:\Progam Files\Steam\userdata\\\local" + virtual bool GetUserDataFolder( char *pchBuffer, int cubBuffer ) = 0; + + // Starts voice recording. Once started, use GetVoice() to get the data + virtual void StartVoiceRecording( ) = 0; + + // Stops voice recording. Because people often release push-to-talk keys early, the system will keep recording for + // a little bit after this function is called. GetVoice() should continue to be called until it returns + // k_eVoiceResultNotRecording + virtual void StopVoiceRecording( ) = 0; + + // Determine the amount of captured audio data that is available in bytes. + // This provides both the compressed and uncompressed data. Please note that the uncompressed + // data is not the raw feed from the microphone: data may only be available if audible + // levels of speech are detected. + // nUncompressedVoiceDesiredSampleRate is necessary to know the number of bytes to return in pcbUncompressed - can be set to 0 if you don't need uncompressed (the usual case) + // If you're upgrading from an older Steamworks API, you'll want to pass in 11025 to nUncompressedVoiceDesiredSampleRate + virtual EVoiceResult GetAvailableVoice(uint32 *pcbCompressed, uint32 *pcbUncompressed, uint32 nUncompressedVoiceDesiredSampleRate) = 0; + + // Gets the latest voice data from the microphone. Compressed data is an arbitrary format, and is meant to be handed back to + // DecompressVoice() for playback later as a binary blob. Uncompressed data is 16-bit, signed integer, 11025Hz PCM format. + // Please note that the uncompressed data is not the raw feed from the microphone: data may only be available if audible + // levels of speech are detected, and may have passed through denoising filters, etc. + // This function should be called as often as possible once recording has started; once per frame at least. + // nBytesWritten is set to the number of bytes written to pDestBuffer. + // nUncompressedBytesWritten is set to the number of bytes written to pUncompressedDestBuffer. + // You must grab both compressed and uncompressed here at the same time, if you want both. + // Matching data that is not read during this call will be thrown away. + // GetAvailableVoice() can be used to determine how much data is actually available. + // If you're upgrading from an older Steamworks API, you'll want to pass in 11025 to nUncompressedVoiceDesiredSampleRate + virtual EVoiceResult GetVoice( bool bWantCompressed, void *pDestBuffer, uint32 cbDestBufferSize, uint32 *nBytesWritten, bool bWantUncompressed, void *pUncompressedDestBuffer, uint32 cbUncompressedDestBufferSize, uint32 *nUncompressBytesWritten, uint32 nUncompressedVoiceDesiredSampleRate ) = 0; + + // Decompresses a chunk of compressed data produced by GetVoice(). + // nBytesWritten is set to the number of bytes written to pDestBuffer unless the return value is k_EVoiceResultBufferTooSmall. + // In that case, nBytesWritten is set to the size of the buffer required to decompress the given + // data. The suggested buffer size for the destination buffer is 22 kilobytes. + // The output format of the data is 16-bit signed at the requested samples per second. + // If you're upgrading from an older Steamworks API, you'll want to pass in 11025 to nDesiredSampleRate + virtual EVoiceResult DecompressVoice( const void *pCompressed, uint32 cbCompressed, void *pDestBuffer, uint32 cbDestBufferSize, uint32 *nBytesWritten, uint32 nDesiredSampleRate ) = 0; + + // This returns the frequency of the voice data as it's stored internally; calling DecompressVoice() with this size will yield the best results + virtual uint32 GetVoiceOptimalSampleRate() = 0; + + // Retrieve ticket to be sent to the entity who wishes to authenticate you. + // pcbTicket retrieves the length of the actual ticket. + virtual HAuthTicket GetAuthSessionTicket( void *pTicket, int cbMaxTicket, uint32 *pcbTicket ) = 0; + + // Authenticate ticket from entity steamID to be sure it is valid and isnt reused + // Registers for callbacks if the entity goes offline or cancels the ticket ( see ValidateAuthTicketResponse_t callback and EAuthSessionResponse ) + virtual EBeginAuthSessionResult BeginAuthSession( const void *pAuthTicket, int cbAuthTicket, CSteamID steamID ) = 0; + + // Stop tracking started by BeginAuthSession - called when no longer playing game with this entity + virtual void EndAuthSession( CSteamID steamID ) = 0; + + // Cancel auth ticket from GetAuthSessionTicket, called when no longer playing game with the entity you gave the ticket to + virtual void CancelAuthTicket( HAuthTicket hAuthTicket ) = 0; + + // After receiving a user's authentication data, and passing it to BeginAuthSession, use this function + // to determine if the user owns downloadable content specified by the provided AppID. + virtual EUserHasLicenseForAppResult UserHasLicenseForApp( CSteamID steamID, AppId_t appID ) = 0; + + // returns true if this users looks like they are behind a NAT device. Only valid once the user has connected to steam + // (i.e a SteamServersConnected_t has been issued) and may not catch all forms of NAT. + virtual bool BIsBehindNAT() = 0; + + // set data to be replicated to friends so that they can join your game + // CSteamID steamIDGameServer - the steamID of the game server, received from the game server by the client + // uint32 unIPServer, uint16 usPortServer - the IP address of the game server + virtual void AdvertiseGame( CSteamID steamIDGameServer, uint32 unIPServer, uint16 usPortServer ) = 0; + + // Requests a ticket encrypted with an app specific shared key + // pDataToInclude, cbDataToInclude will be encrypted into the ticket + // ( This is asynchronous, you must wait for the ticket to be completed by the server ) + virtual SteamAPICall_t RequestEncryptedAppTicket( void *pDataToInclude, int cbDataToInclude ) = 0; + + // retrieve a finished ticket + virtual bool GetEncryptedAppTicket( void *pTicket, int cbMaxTicket, uint32 *pcbTicket ) = 0; + +#ifdef _PS3 + // Initiates PS3 Logon request using just PSN ticket. + // + // PARAMS: bInteractive - If set tells Steam to go ahead and show the PS3 NetStart dialog if needed to + // prompt the user for network setup/PSN logon before initiating the Steam side of the logon. + // + // Listen for SteamServersConnected_t or SteamServerConnectFailure_t for status. SteamServerConnectFailure_t + // may return with EResult k_EResultExternalAccountUnlinked if the PSN account is unknown to Steam. You should + // then call LogOnAndLinkSteamAccountToPSN() after prompting the user for credentials to establish a link. + // Future calls to LogOn() after the one time link call should succeed as long as the user is connected to PSN. + virtual void LogOn( bool bInteractive ) = 0; + + // Initiates a request to logon with a specific steam username/password and create a PSN account link at + // the same time. Should call this only if LogOn() has failed and indicated the PSN account is unlinked. + // + // PARAMS: bInteractive - If set tells Steam to go ahead and show the PS3 NetStart dialog if needed to + // prompt the user for network setup/PSN logon before initiating the Steam side of the logon. pchUserName + // should be the users Steam username, and pchPassword should be the users Steam password. + // + // Listen for SteamServersConnected_t or SteamServerConnectFailure_t for status. SteamServerConnectFailure_t + // may return with EResult k_EResultOtherAccountAlreadyLinked if already linked to another account. + virtual void LogOnAndLinkSteamAccountToPSN( bool bInteractive, const char *pchUserName, const char *pchPassword ) = 0; + + // Final logon option for PS3, this logs into an existing account if already linked, but if not already linked + // creates a new account using the info in the PSN ticket to generate a unique account name. The new account is + // then linked to the PSN ticket. This is the faster option for new users who don't have an existing Steam account + // to get into multiplayer. + // + // PARAMS: bInteractive - If set tells Steam to go ahead and show the PS3 NetStart dialog if needed to + // prompt the user for network setup/PSN logon before initiating the Steam side of the logon. + virtual void LogOnAndCreateNewSteamAccountIfNeeded( bool bInteractive ) = 0; + + // Returns a special SteamID that represents the user's PSN information. Can be used to query the user's PSN avatar, + // online name, etc. through the standard Steamworks interfaces. + virtual CSteamID GetConsoleSteamID() = 0; +#endif + +}; + +#define STEAMUSER_INTERFACE_VERSION "SteamUser016" + + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: called when a connections to the Steam back-end has been established +// this means the Steam client now has a working connection to the Steam servers +// usually this will have occurred before the game has launched, and should +// only be seen if the user has dropped connection due to a networking issue +// or a Steam server update +//----------------------------------------------------------------------------- +struct SteamServersConnected_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 1 }; +}; + +//----------------------------------------------------------------------------- +// Purpose: called when a connection attempt has failed +// this will occur periodically if the Steam client is not connected, +// and has failed in it's retry to establish a connection +//----------------------------------------------------------------------------- +struct SteamServerConnectFailure_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 2 }; + EResult m_eResult; +}; + + +//----------------------------------------------------------------------------- +// Purpose: called if the client has lost connection to the Steam servers +// real-time services will be disabled until a matching SteamServersConnected_t has been posted +//----------------------------------------------------------------------------- +struct SteamServersDisconnected_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 3 }; + EResult m_eResult; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Sent by the Steam server to the client telling it to disconnect from the specified game server, +// which it may be in the process of or already connected to. +// The game client should immediately disconnect upon receiving this message. +// This can usually occur if the user doesn't have rights to play on the game server. +//----------------------------------------------------------------------------- +struct ClientGameServerDeny_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 13 }; + + uint32 m_uAppID; + uint32 m_unGameServerIP; + uint16 m_usGameServerPort; + uint16 m_bSecure; + uint32 m_uReason; +}; + + +//----------------------------------------------------------------------------- +// Purpose: called when the callback system for this client is in an error state (and has flushed pending callbacks) +// When getting this message the client should disconnect from Steam, reset any stored Steam state and reconnect. +// This usually occurs in the rare event the Steam client has some kind of fatal error. +//----------------------------------------------------------------------------- +struct IPCFailure_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 17 }; + enum EFailureType + { + k_EFailureFlushedCallbackQueue, + k_EFailurePipeFail, + }; + uint8 m_eFailureType; +}; + + +//----------------------------------------------------------------------------- +// callback for BeginAuthSession +//----------------------------------------------------------------------------- +struct ValidateAuthTicketResponse_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 43 }; + CSteamID m_SteamID; + EAuthSessionResponse m_eAuthSessionResponse; +}; + + +//----------------------------------------------------------------------------- +// Purpose: called when a user has responded to a microtransaction authorization request +//----------------------------------------------------------------------------- +struct MicroTxnAuthorizationResponse_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 52 }; + + uint32 m_unAppID; // AppID for this microtransaction + uint64 m_ulOrderID; // OrderID provided for the microtransaction + uint8 m_bAuthorized; // if user authorized transaction +}; + + +//----------------------------------------------------------------------------- +// Purpose: Result from RequestEncryptedAppTicket +//----------------------------------------------------------------------------- +struct EncryptedAppTicketResponse_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 54 }; + + EResult m_eResult; +}; + +//----------------------------------------------------------------------------- +// callback for GetAuthSessionTicket +//----------------------------------------------------------------------------- +struct GetAuthSessionTicketResponse_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 63 }; + HAuthTicket m_hAuthTicket; + EResult m_eResult; +}; + + +//----------------------------------------------------------------------------- +// Purpose: sent to your game in response to a steam://gamewebcallback/ command +//----------------------------------------------------------------------------- +struct GameWebCallback_t +{ + enum { k_iCallback = k_iSteamUserCallbacks + 64 }; + char m_szURL[256]; +}; + + +#pragma pack( pop ) + +#endif // ISTEAMUSER_H diff --git a/dep/rehlsdk/public/steam/isteamuserstats.h b/dep/rehlsdk/public/steam/isteamuserstats.h new file mode 100644 index 0000000..c5847cf --- /dev/null +++ b/dep/rehlsdk/public/steam/isteamuserstats.h @@ -0,0 +1,463 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to stats, achievements, and leaderboards +// +//============================================================================= + +#ifndef ISTEAMUSERSTATS_H +#define ISTEAMUSERSTATS_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" +#include "isteamremotestorage.h" + +// size limit on stat or achievement name (UTF-8 encoded) +enum { k_cchStatNameMax = 128 }; + +// maximum number of bytes for a leaderboard name (UTF-8 encoded) +enum { k_cchLeaderboardNameMax = 128 }; + +// maximum number of details int32's storable for a single leaderboard entry +enum { k_cLeaderboardDetailsMax = 64 }; + +// handle to a single leaderboard +typedef uint64 SteamLeaderboard_t; + +// handle to a set of downloaded entries in a leaderboard +typedef uint64 SteamLeaderboardEntries_t; + +// type of data request, when downloading leaderboard entries +enum ELeaderboardDataRequest +{ + k_ELeaderboardDataRequestGlobal = 0, + k_ELeaderboardDataRequestGlobalAroundUser = 1, + k_ELeaderboardDataRequestFriends = 2, + k_ELeaderboardDataRequestUsers = 3 +}; + +// the sort order of a leaderboard +enum ELeaderboardSortMethod +{ + k_ELeaderboardSortMethodNone = 0, + k_ELeaderboardSortMethodAscending = 1, // top-score is lowest number + k_ELeaderboardSortMethodDescending = 2, // top-score is highest number +}; + +// the display type (used by the Steam Community web site) for a leaderboard +enum ELeaderboardDisplayType +{ + k_ELeaderboardDisplayTypeNone = 0, + k_ELeaderboardDisplayTypeNumeric = 1, // simple numerical score + k_ELeaderboardDisplayTypeTimeSeconds = 2, // the score represents a time, in seconds + k_ELeaderboardDisplayTypeTimeMilliSeconds = 3, // the score represents a time, in milliseconds +}; + +enum ELeaderboardUploadScoreMethod +{ + k_ELeaderboardUploadScoreMethodNone = 0, + k_ELeaderboardUploadScoreMethodKeepBest = 1, // Leaderboard will keep user's best score + k_ELeaderboardUploadScoreMethodForceUpdate = 2, // Leaderboard will always replace score with specified +}; + +// a single entry in a leaderboard, as returned by GetDownloadedLeaderboardEntry() +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +struct LeaderboardEntry_t +{ + CSteamID m_steamIDUser; // user with the entry - use SteamFriends()->GetFriendPersonaName() & SteamFriends()->GetFriendAvatar() to get more info + int32 m_nGlobalRank; // [1..N], where N is the number of users with an entry in the leaderboard + int32 m_nScore; // score as set in the leaderboard + int32 m_cDetails; // number of int32 details available for this entry + UGCHandle_t m_hUGC; // handle for UGC attached to the entry +}; + +#pragma pack( pop ) + + +//----------------------------------------------------------------------------- +// Purpose: Functions for accessing stats, achievements, and leaderboard information +//----------------------------------------------------------------------------- +class ISteamUserStats +{ +public: + // Ask the server to send down this user's data and achievements for this game + virtual bool RequestCurrentStats() = 0; + + // Data accessors + virtual bool GetStat( const char *pchName, int32 *pData ) = 0; + virtual bool GetStat( const char *pchName, float *pData ) = 0; + + // Set / update data + virtual bool SetStat( const char *pchName, int32 nData ) = 0; + virtual bool SetStat( const char *pchName, float fData ) = 0; + virtual bool UpdateAvgRateStat( const char *pchName, float flCountThisSession, double dSessionLength ) = 0; + + // Achievement flag accessors + virtual bool GetAchievement( const char *pchName, bool *pbAchieved ) = 0; + virtual bool SetAchievement( const char *pchName ) = 0; + virtual bool ClearAchievement( const char *pchName ) = 0; + + // Get the achievement status, and the time it was unlocked if unlocked. + // If the return value is true, but the unlock time is zero, that means it was unlocked before Steam + // began tracking achievement unlock times (December 2009). Time is seconds since January 1, 1970. + virtual bool GetAchievementAndUnlockTime( const char *pchName, bool *pbAchieved, uint32 *punUnlockTime ) = 0; + + // Store the current data on the server, will get a callback when set + // And one callback for every new achievement + // + // If the callback has a result of k_EResultInvalidParam, one or more stats + // uploaded has been rejected, either because they broke constraints + // or were out of date. In this case the server sends back updated values. + // The stats should be re-iterated to keep in sync. + virtual bool StoreStats() = 0; + + // Achievement / GroupAchievement metadata + + // Gets the icon of the achievement, which is a handle to be used in ISteamUtils::GetImageRGBA(), or 0 if none set. + // A return value of 0 may indicate we are still fetching data, and you can wait for the UserAchievementIconFetched_t callback + // which will notify you when the bits are ready. If the callback still returns zero, then there is no image set for the + // specified achievement. + virtual int GetAchievementIcon( const char *pchName ) = 0; + + // Get general attributes for an achievement. Accepts the following keys: + // - "name" and "desc" for retrieving the localized achievement name and description (returned in UTF8) + // - "hidden" for retrieving if an achievement is hidden (returns "0" when not hidden, "1" when hidden) + virtual const char *GetAchievementDisplayAttribute( const char *pchName, const char *pchKey ) = 0; + + // Achievement progress - triggers an AchievementProgress callback, that is all. + // Calling this w/ N out of N progress will NOT set the achievement, the game must still do that. + virtual bool IndicateAchievementProgress( const char *pchName, uint32 nCurProgress, uint32 nMaxProgress ) = 0; + + // Used for iterating achievements. In general games should not need these functions because they should have a + // list of existing achievements compiled into them + virtual uint32 GetNumAchievements() = 0; + // Get achievement name iAchievement in [0,GetNumAchievements) + virtual const char *GetAchievementName( uint32 iAchievement ) = 0; + + // Friends stats & achievements + + // downloads stats for the user + // returns a UserStatsReceived_t received when completed + // if the other user has no stats, UserStatsReceived_t.m_eResult will be set to k_EResultFail + // these stats won't be auto-updated; you'll need to call RequestUserStats() again to refresh any data + virtual SteamAPICall_t RequestUserStats( CSteamID steamIDUser ) = 0; + + // requests stat information for a user, usable after a successful call to RequestUserStats() + virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, int32 *pData ) = 0; + virtual bool GetUserStat( CSteamID steamIDUser, const char *pchName, float *pData ) = 0; + virtual bool GetUserAchievement( CSteamID steamIDUser, const char *pchName, bool *pbAchieved ) = 0; + // See notes for GetAchievementAndUnlockTime above + virtual bool GetUserAchievementAndUnlockTime( CSteamID steamIDUser, const char *pchName, bool *pbAchieved, uint32 *punUnlockTime ) = 0; + + // Reset stats + virtual bool ResetAllStats( bool bAchievementsToo ) = 0; + + // Leaderboard functions + + // asks the Steam back-end for a leaderboard by name, and will create it if it's not yet + // This call is asynchronous, with the result returned in LeaderboardFindResult_t + virtual SteamAPICall_t FindOrCreateLeaderboard( const char *pchLeaderboardName, ELeaderboardSortMethod eLeaderboardSortMethod, ELeaderboardDisplayType eLeaderboardDisplayType ) = 0; + + // as above, but won't create the leaderboard if it's not found + // This call is asynchronous, with the result returned in LeaderboardFindResult_t + virtual SteamAPICall_t FindLeaderboard( const char *pchLeaderboardName ) = 0; + + // returns the name of a leaderboard + virtual const char *GetLeaderboardName( SteamLeaderboard_t hSteamLeaderboard ) = 0; + + // returns the total number of entries in a leaderboard, as of the last request + virtual int GetLeaderboardEntryCount( SteamLeaderboard_t hSteamLeaderboard ) = 0; + + // returns the sort method of the leaderboard + virtual ELeaderboardSortMethod GetLeaderboardSortMethod( SteamLeaderboard_t hSteamLeaderboard ) = 0; + + // returns the display type of the leaderboard + virtual ELeaderboardDisplayType GetLeaderboardDisplayType( SteamLeaderboard_t hSteamLeaderboard ) = 0; + + // Asks the Steam back-end for a set of rows in the leaderboard. + // This call is asynchronous, with the result returned in LeaderboardScoresDownloaded_t + // LeaderboardScoresDownloaded_t will contain a handle to pull the results from GetDownloadedLeaderboardEntries() (below) + // You can ask for more entries than exist, and it will return as many as do exist. + // k_ELeaderboardDataRequestGlobal requests rows in the leaderboard from the full table, with nRangeStart & nRangeEnd in the range [1, TotalEntries] + // k_ELeaderboardDataRequestGlobalAroundUser requests rows around the current user, nRangeStart being negate + // e.g. DownloadLeaderboardEntries( hLeaderboard, k_ELeaderboardDataRequestGlobalAroundUser, -3, 3 ) will return 7 rows, 3 before the user, 3 after + // k_ELeaderboardDataRequestFriends requests all the rows for friends of the current user + virtual SteamAPICall_t DownloadLeaderboardEntries( SteamLeaderboard_t hSteamLeaderboard, ELeaderboardDataRequest eLeaderboardDataRequest, int nRangeStart, int nRangeEnd ) = 0; + // as above, but downloads leaderboard entries for an arbitrary set of users - ELeaderboardDataRequest is k_ELeaderboardDataRequestUsers + // if a user doesn't have a leaderboard entry, they won't be included in the result + // a max of 100 users can be downloaded at a time, with only one outstanding call at a time + virtual SteamAPICall_t DownloadLeaderboardEntriesForUsers( SteamLeaderboard_t hSteamLeaderboard, CSteamID *prgUsers, int cUsers ) = 0; + + // Returns data about a single leaderboard entry + // use a for loop from 0 to LeaderboardScoresDownloaded_t::m_cEntryCount to get all the downloaded entries + // e.g. + // void OnLeaderboardScoresDownloaded( LeaderboardScoresDownloaded_t *pLeaderboardScoresDownloaded ) + // { + // for ( int index = 0; index < pLeaderboardScoresDownloaded->m_cEntryCount; index++ ) + // { + // LeaderboardEntry_t leaderboardEntry; + // int32 details[3]; // we know this is how many we've stored previously + // GetDownloadedLeaderboardEntry( pLeaderboardScoresDownloaded->m_hSteamLeaderboardEntries, index, &leaderboardEntry, details, 3 ); + // assert( leaderboardEntry.m_cDetails == 3 ); + // ... + // } + // once you've accessed all the entries, the data will be free'd, and the SteamLeaderboardEntries_t handle will become invalid + virtual bool GetDownloadedLeaderboardEntry( SteamLeaderboardEntries_t hSteamLeaderboardEntries, int index, LeaderboardEntry_t *pLeaderboardEntry, int32 *pDetails, int cDetailsMax ) = 0; + + // Uploads a user score to the Steam back-end. + // This call is asynchronous, with the result returned in LeaderboardScoreUploaded_t + // Details are extra game-defined information regarding how the user got that score + // pScoreDetails points to an array of int32's, cScoreDetailsCount is the number of int32's in the list + virtual SteamAPICall_t UploadLeaderboardScore( SteamLeaderboard_t hSteamLeaderboard, ELeaderboardUploadScoreMethod eLeaderboardUploadScoreMethod, int32 nScore, const int32 *pScoreDetails, int cScoreDetailsCount ) = 0; + + // Attaches a piece of user generated content the user's entry on a leaderboard. + // hContent is a handle to a piece of user generated content that was shared using ISteamUserRemoteStorage::FileShare(). + // This call is asynchronous, with the result returned in LeaderboardUGCSet_t. + virtual SteamAPICall_t AttachLeaderboardUGC( SteamLeaderboard_t hSteamLeaderboard, UGCHandle_t hUGC ) = 0; + + // Retrieves the number of players currently playing your game (online + offline) + // This call is asynchronous, with the result returned in NumberOfCurrentPlayers_t + virtual SteamAPICall_t GetNumberOfCurrentPlayers() = 0; + + // Requests that Steam fetch data on the percentage of players who have received each achievement + // for the game globally. + // This call is asynchronous, with the result returned in GlobalAchievementPercentagesReady_t. + virtual SteamAPICall_t RequestGlobalAchievementPercentages() = 0; + + // Get the info on the most achieved achievement for the game, returns an iterator index you can use to fetch + // the next most achieved afterwards. Will return -1 if there is no data on achievement + // percentages (ie, you haven't called RequestGlobalAchievementPercentages and waited on the callback). + virtual int GetMostAchievedAchievementInfo( char *pchName, uint32 unNameBufLen, float *pflPercent, bool *pbAchieved ) = 0; + + // Get the info on the next most achieved achievement for the game. Call this after GetMostAchievedAchievementInfo or another + // GetNextMostAchievedAchievementInfo call passing the iterator from the previous call. Returns -1 after the last + // achievement has been iterated. + virtual int GetNextMostAchievedAchievementInfo( int iIteratorPrevious, char *pchName, uint32 unNameBufLen, float *pflPercent, bool *pbAchieved ) = 0; + + // Returns the percentage of users who have achieved the specified achievement. + virtual bool GetAchievementAchievedPercent( const char *pchName, float *pflPercent ) = 0; + + // Requests global stats data, which is available for stats marked as "aggregated". + // This call is asynchronous, with the results returned in GlobalStatsReceived_t. + // nHistoryDays specifies how many days of day-by-day history to retrieve in addition + // to the overall totals. The limit is 60. + virtual SteamAPICall_t RequestGlobalStats( int nHistoryDays ) = 0; + + // Gets the lifetime totals for an aggregated stat + virtual bool GetGlobalStat( const char *pchStatName, int64 *pData ) = 0; + virtual bool GetGlobalStat( const char *pchStatName, double *pData ) = 0; + + // Gets history for an aggregated stat. pData will be filled with daily values, starting with today. + // So when called, pData[0] will be today, pData[1] will be yesterday, and pData[2] will be two days ago, + // etc. cubData is the size in bytes of the pubData buffer. Returns the number of + // elements actually set. + virtual int32 GetGlobalStatHistory( const char *pchStatName, int64 *pData, uint32 cubData ) = 0; + virtual int32 GetGlobalStatHistory( const char *pchStatName, double *pData, uint32 cubData ) = 0; + +#ifdef _PS3 + // Call to kick off installation of the PS3 trophies. This call is asynchronous, and the results will be returned in a PS3TrophiesInstalled_t + // callback. + virtual bool InstallPS3Trophies() = 0; + + // Returns the amount of space required at boot to install trophies. This value can be used when comparing the amount of space needed + // by the game to the available space value passed to the game at boot. The value is set during InstallPS3Trophies(). + virtual uint64 GetTrophySpaceRequiredBeforeInstall() = 0; + + // On PS3, user stats & achievement progress through Steam must be stored with the user's saved game data. + // At startup, before calling RequestCurrentStats(), you must pass the user's stats data to Steam via this method. + // If you do not have any user data, call this function with pvData = NULL and cubData = 0 + virtual bool SetUserStatsData( const void *pvData, uint32 cubData ) = 0; + + // Call to get the user's current stats data. You should retrieve this data after receiving successful UserStatsReceived_t & UserStatsStored_t + // callbacks, and store the data with the user's save game data. You can call this method with pvData = NULL and cubData = 0 to get the required + // buffer size. + virtual bool GetUserStatsData( void *pvData, uint32 cubData, uint32 *pcubWritten ) = 0; +#endif +}; + +#define STEAMUSERSTATS_INTERFACE_VERSION "STEAMUSERSTATS_INTERFACE_VERSION011" + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: called when the latests stats and achievements have been received +// from the server +//----------------------------------------------------------------------------- +struct UserStatsReceived_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 1 }; + uint64 m_nGameID; // Game these stats are for + EResult m_eResult; // Success / error fetching the stats + CSteamID m_steamIDUser; // The user for whom the stats are retrieved for +}; + + +//----------------------------------------------------------------------------- +// Purpose: result of a request to store the user stats for a game +//----------------------------------------------------------------------------- +struct UserStatsStored_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 2 }; + uint64 m_nGameID; // Game these stats are for + EResult m_eResult; // success / error +}; + + +//----------------------------------------------------------------------------- +// Purpose: result of a request to store the achievements for a game, or an +// "indicate progress" call. If both m_nCurProgress and m_nMaxProgress +// are zero, that means the achievement has been fully unlocked. +//----------------------------------------------------------------------------- +struct UserAchievementStored_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 3 }; + + uint64 m_nGameID; // Game this is for + bool m_bGroupAchievement; // if this is a "group" achievement + char m_rgchAchievementName[k_cchStatNameMax]; // name of the achievement + uint32 m_nCurProgress; // current progress towards the achievement + uint32 m_nMaxProgress; // "out of" this many +}; + + +//----------------------------------------------------------------------------- +// Purpose: call result for finding a leaderboard, returned as a result of FindOrCreateLeaderboard() or FindLeaderboard() +// use CCallResult<> to map this async result to a member function +//----------------------------------------------------------------------------- +struct LeaderboardFindResult_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 4 }; + SteamLeaderboard_t m_hSteamLeaderboard; // handle to the leaderboard serarched for, 0 if no leaderboard found + uint8 m_bLeaderboardFound; // 0 if no leaderboard found +}; + + +//----------------------------------------------------------------------------- +// Purpose: call result indicating scores for a leaderboard have been downloaded and are ready to be retrieved, returned as a result of DownloadLeaderboardEntries() +// use CCallResult<> to map this async result to a member function +//----------------------------------------------------------------------------- +struct LeaderboardScoresDownloaded_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 5 }; + SteamLeaderboard_t m_hSteamLeaderboard; + SteamLeaderboardEntries_t m_hSteamLeaderboardEntries; // the handle to pass into GetDownloadedLeaderboardEntries() + int m_cEntryCount; // the number of entries downloaded +}; + + +//----------------------------------------------------------------------------- +// Purpose: call result indicating scores has been uploaded, returned as a result of UploadLeaderboardScore() +// use CCallResult<> to map this async result to a member function +//----------------------------------------------------------------------------- +struct LeaderboardScoreUploaded_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 6 }; + uint8 m_bSuccess; // 1 if the call was successful + SteamLeaderboard_t m_hSteamLeaderboard; // the leaderboard handle that was + int32 m_nScore; // the score that was attempted to set + uint8 m_bScoreChanged; // true if the score in the leaderboard change, false if the existing score was better + int m_nGlobalRankNew; // the new global rank of the user in this leaderboard + int m_nGlobalRankPrevious; // the previous global rank of the user in this leaderboard; 0 if the user had no existing entry in the leaderboard +}; + +struct NumberOfCurrentPlayers_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 7 }; + uint8 m_bSuccess; // 1 if the call was successful + int32 m_cPlayers; // Number of players currently playing +}; + + + +//----------------------------------------------------------------------------- +// Purpose: Callback indicating that a user's stats have been unloaded. +// Call RequestUserStats again to access stats for this user +//----------------------------------------------------------------------------- +struct UserStatsUnloaded_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 8 }; + CSteamID m_steamIDUser; // User whose stats have been unloaded +}; + + + +//----------------------------------------------------------------------------- +// Purpose: Callback indicating that an achievement icon has been fetched +//----------------------------------------------------------------------------- +struct UserAchievementIconFetched_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 9 }; + + CGameID m_nGameID; // Game this is for + char m_rgchAchievementName[k_cchStatNameMax]; // name of the achievement + bool m_bAchieved; // Is the icon for the achieved or not achieved version? + int m_nIconHandle; // Handle to the image, which can be used in SteamUtils()->GetImageRGBA(), 0 means no image is set for the achievement +}; + + +//----------------------------------------------------------------------------- +// Purpose: Callback indicating that global achievement percentages are fetched +//----------------------------------------------------------------------------- +struct GlobalAchievementPercentagesReady_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 10 }; + + uint64 m_nGameID; // Game this is for + EResult m_eResult; // Result of the operation +}; + + +//----------------------------------------------------------------------------- +// Purpose: call result indicating UGC has been uploaded, returned as a result of SetLeaderboardUGC() +//----------------------------------------------------------------------------- +struct LeaderboardUGCSet_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 11 }; + EResult m_eResult; // The result of the operation + SteamLeaderboard_t m_hSteamLeaderboard; // the leaderboard handle that was +}; + + +//----------------------------------------------------------------------------- +// Purpose: callback indicating that PS3 trophies have been installed +//----------------------------------------------------------------------------- +struct PS3TrophiesInstalled_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 12 }; + uint64 m_nGameID; // Game these stats are for + EResult m_eResult; // The result of the operation + uint64 m_ulRequiredDiskSpace; // If m_eResult is k_EResultDiskFull, will contain the amount of space needed to install trophies + +}; + + +//----------------------------------------------------------------------------- +// Purpose: callback indicating global stats have been received. +// Returned as a result of RequestGlobalStats() +//----------------------------------------------------------------------------- +struct GlobalStatsReceived_t +{ + enum { k_iCallback = k_iSteamUserStatsCallbacks + 12 }; + uint64 m_nGameID; // Game global stats were requested for + EResult m_eResult; // The result of the request +}; + +#pragma pack( pop ) + + +#endif // ISTEAMUSER_H diff --git a/dep/rehlsdk/public/steam/isteamutils.h b/dep/rehlsdk/public/steam/isteamutils.h new file mode 100644 index 0000000..ab032df --- /dev/null +++ b/dep/rehlsdk/public/steam/isteamutils.h @@ -0,0 +1,304 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: interface to utility functions in Steam +// +//============================================================================= + +#ifndef ISTEAMUTILS_H +#define ISTEAMUTILS_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" + + +// Steam API call failure results +enum ESteamAPICallFailure +{ + k_ESteamAPICallFailureNone = -1, // no failure + k_ESteamAPICallFailureSteamGone = 0, // the local Steam process has gone away + k_ESteamAPICallFailureNetworkFailure = 1, // the network connection to Steam has been broken, or was already broken + // SteamServersDisconnected_t callback will be sent around the same time + // SteamServersConnected_t will be sent when the client is able to talk to the Steam servers again + k_ESteamAPICallFailureInvalidHandle = 2, // the SteamAPICall_t handle passed in no longer exists + k_ESteamAPICallFailureMismatchedCallback = 3,// GetAPICallResult() was called with the wrong callback type for this API call +}; + + +// Input modes for the Big Picture gamepad text entry +enum EGamepadTextInputMode +{ + k_EGamepadTextInputModeNormal = 0, + k_EGamepadTextInputModePassword = 1 +}; + + +// Controls number of allowed lines for the Big Picture gamepad text entry +enum EGamepadTextInputLineMode +{ + k_EGamepadTextInputLineModeSingleLine = 0, + k_EGamepadTextInputLineModeMultipleLines = 1 +}; + + +// function prototype for warning message hook +#if defined( POSIX ) +#define __cdecl +#endif +extern "C" typedef void (__cdecl *SteamAPIWarningMessageHook_t)(int, const char *); + +//----------------------------------------------------------------------------- +// Purpose: interface to user independent utility functions +//----------------------------------------------------------------------------- +class ISteamUtils +{ +public: + // return the number of seconds since the user + virtual uint32 GetSecondsSinceAppActive() = 0; + virtual uint32 GetSecondsSinceComputerActive() = 0; + + // the universe this client is connecting to + virtual EUniverse GetConnectedUniverse() = 0; + + // Steam server time - in PST, number of seconds since January 1, 1970 (i.e unix time) + virtual uint32 GetServerRealTime() = 0; + + // returns the 2 digit ISO 3166-1-alpha-2 format country code this client is running in (as looked up via an IP-to-location database) + // e.g "US" or "UK". + virtual const char *GetIPCountry() = 0; + + // returns true if the image exists, and valid sizes were filled out + virtual bool GetImageSize( int iImage, uint32 *pnWidth, uint32 *pnHeight ) = 0; + + // returns true if the image exists, and the buffer was successfully filled out + // results are returned in RGBA format + // the destination buffer size should be 4 * height * width * sizeof(char) + virtual bool GetImageRGBA( int iImage, uint8 *pubDest, int nDestBufferSize ) = 0; + + // returns the IP of the reporting server for valve - currently only used in Source engine games + virtual bool GetCSERIPPort( uint32 *unIP, uint16 *usPort ) = 0; + + // return the amount of battery power left in the current system in % [0..100], 255 for being on AC power + virtual uint8 GetCurrentBatteryPower() = 0; + + // returns the appID of the current process + virtual uint32 GetAppID() = 0; + + // Sets the position where the overlay instance for the currently calling game should show notifications. + // This position is per-game and if this function is called from outside of a game context it will do nothing. + virtual void SetOverlayNotificationPosition( ENotificationPosition eNotificationPosition ) = 0; + + // API asynchronous call results + // can be used directly, but more commonly used via the callback dispatch API (see steam_api.h) + virtual bool IsAPICallCompleted( SteamAPICall_t hSteamAPICall, bool *pbFailed ) = 0; + virtual ESteamAPICallFailure GetAPICallFailureReason( SteamAPICall_t hSteamAPICall ) = 0; + virtual bool GetAPICallResult( SteamAPICall_t hSteamAPICall, void *pCallback, int cubCallback, int iCallbackExpected, bool *pbFailed ) = 0; + + // this needs to be called every frame to process matchmaking results + // redundant if you're already calling SteamAPI_RunCallbacks() + virtual void RunFrame() = 0; + + // returns the number of IPC calls made since the last time this function was called + // Used for perf debugging so you can understand how many IPC calls your game makes per frame + // Every IPC call is at minimum a thread context switch if not a process one so you want to rate + // control how often you do them. + virtual uint32 GetIPCCallCount() = 0; + + // API warning handling + // 'int' is the severity; 0 for msg, 1 for warning + // 'const char *' is the text of the message + // callbacks will occur directly after the API function is called that generated the warning or message + virtual void SetWarningMessageHook( SteamAPIWarningMessageHook_t pFunction ) = 0; + + // Returns true if the overlay is running & the user can access it. The overlay process could take a few seconds to + // start & hook the game process, so this function will initially return false while the overlay is loading. + virtual bool IsOverlayEnabled() = 0; + + // Normally this call is unneeded if your game has a constantly running frame loop that calls the + // D3D Present API, or OGL SwapBuffers API every frame. + // + // However, if you have a game that only refreshes the screen on an event driven basis then that can break + // the overlay, as it uses your Present/SwapBuffers calls to drive it's internal frame loop and it may also + // need to Present() to the screen any time an even needing a notification happens or when the overlay is + // brought up over the game by a user. You can use this API to ask the overlay if it currently need a present + // in that case, and then you can check for this periodically (roughly 33hz is desirable) and make sure you + // refresh the screen with Present or SwapBuffers to allow the overlay to do it's work. + virtual bool BOverlayNeedsPresent() = 0; + +#ifndef _PS3 + // Asynchronous call to check if an executable file has been signed using the public key set on the signing tab + // of the partner site, for example to refuse to load modified executable files. + // The result is returned in CheckFileSignature_t. + // k_ECheckFileSignatureNoSignaturesFoundForThisApp - This app has not been configured on the signing tab of the partner site to enable this function. + // k_ECheckFileSignatureNoSignaturesFoundForThisFile - This file is not listed on the signing tab for the partner site. + // k_ECheckFileSignatureFileNotFound - The file does not exist on disk. + // k_ECheckFileSignatureInvalidSignature - The file exists, and the signing tab has been set for this file, but the file is either not signed or the signature does not match. + // k_ECheckFileSignatureValidSignature - The file is signed and the signature is valid. + virtual SteamAPICall_t CheckFileSignature( const char *szFileName ) = 0; +#endif + +#ifdef _PS3 + virtual void PostPS3SysutilCallback( uint64 status, uint64 param, void* userdata ) = 0; + virtual bool BIsReadyToShutdown() = 0; + virtual bool BIsPSNOnline() = 0; + + // Call this with localized strings for the language the game is running in, otherwise default english + // strings will be used by Steam. + virtual void SetPSNGameBootInviteStrings( const char *pchSubject, const char *pchBody ) = 0; +#endif + + // Activates the Big Picture text input dialog which only supports gamepad input + virtual bool ShowGamepadTextInput( EGamepadTextInputMode eInputMode, EGamepadTextInputLineMode eLineInputMode, const char *pchDescription, uint32 unCharMax ) = 0; + + // Returns previously entered text & length + virtual uint32 GetEnteredGamepadTextLength() = 0; + virtual bool GetEnteredGamepadTextInput( char *pchText, uint32 cchText ) = 0; + + // returns the language the steam client is running in, you probably want ISteamApps::GetCurrentGameLanguage instead, this is for very special usage cases + virtual const char *GetSteamUILanguage() = 0; +}; + +#define STEAMUTILS_INTERFACE_VERSION "SteamUtils006" + + +// callbacks +#if defined( VALVE_CALLBACK_PACK_SMALL ) +#pragma pack( push, 4 ) +#elif defined( VALVE_CALLBACK_PACK_LARGE ) +#pragma pack( push, 8 ) +#else +#error isteamclient.h must be included +#endif + +//----------------------------------------------------------------------------- +// Purpose: The country of the user changed +//----------------------------------------------------------------------------- +struct IPCountry_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 1 }; +}; + + +//----------------------------------------------------------------------------- +// Purpose: Fired when running on a laptop and less than 10 minutes of battery is left, fires then every minute +//----------------------------------------------------------------------------- +struct LowBatteryPower_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 2 }; + uint8 m_nMinutesBatteryLeft; +}; + + +//----------------------------------------------------------------------------- +// Purpose: called when a SteamAsyncCall_t has completed (or failed) +//----------------------------------------------------------------------------- +struct SteamAPICallCompleted_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 3 }; + SteamAPICall_t m_hAsyncCall; +}; + + +//----------------------------------------------------------------------------- +// called when Steam wants to shutdown +//----------------------------------------------------------------------------- +struct SteamShutdown_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 4 }; +}; + +//----------------------------------------------------------------------------- +// results for CheckFileSignature +//----------------------------------------------------------------------------- +enum ECheckFileSignature +{ + k_ECheckFileSignatureInvalidSignature = 0, + k_ECheckFileSignatureValidSignature = 1, + k_ECheckFileSignatureFileNotFound = 2, + k_ECheckFileSignatureNoSignaturesFoundForThisApp = 3, + k_ECheckFileSignatureNoSignaturesFoundForThisFile = 4, +}; + +//----------------------------------------------------------------------------- +// callback for CheckFileSignature +//----------------------------------------------------------------------------- +struct CheckFileSignature_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 5 }; + ECheckFileSignature m_eCheckFileSignature; +}; + +#ifdef _PS3 +//----------------------------------------------------------------------------- +// callback for NetCtlNetStartDialog finishing on PS3 +//----------------------------------------------------------------------------- +struct NetStartDialogFinished_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 6 }; +}; + +//----------------------------------------------------------------------------- +// callback for NetCtlNetStartDialog unloaded on PS3 +//----------------------------------------------------------------------------- +struct NetStartDialogUnloaded_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 7 }; +}; + +//----------------------------------------------------------------------------- +// callback for system menu closing on PS3 - should trigger resyncronizing friends list, etc. +//----------------------------------------------------------------------------- +struct PS3SystemMenuClosed_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 8 }; +}; + +//----------------------------------------------------------------------------- +// callback for NP message being selected by user on PS3 - should trigger handling of message if it's a lobby invite, etc. +//----------------------------------------------------------------------------- +struct PS3NPMessageSelected_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 9 }; + uint32 dataid; +}; + +//----------------------------------------------------------------------------- +// callback for when the PS3 keyboard dialog closes +//----------------------------------------------------------------------------- +struct PS3KeyboardDialogFinished_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 10 }; +}; + +// k_iSteamUtilsCallbacks + 11 is taken + +//----------------------------------------------------------------------------- +// callback for PSN status changing on PS3 +//----------------------------------------------------------------------------- +struct PS3PSNStatusChange_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 12 }; + bool m_bPSNOnline; +}; + +#endif + +// k_iSteamUtilsCallbacks + 13 is taken + + +//----------------------------------------------------------------------------- +// Big Picture gamepad text input has been closed +//----------------------------------------------------------------------------- +struct GamepadTextInputDismissed_t +{ + enum { k_iCallback = k_iSteamUtilsCallbacks + 14 }; + bool m_bSubmitted; // true if user entered & accepted text (Call ISteamUtils::GetEnteredGamepadTextInput() for text), false if canceled input + uint32 m_unSubmittedText; +}; + +// k_iSteamUtilsCallbacks + 15 is taken + +#pragma pack( pop ) + +#endif // ISTEAMUTILS_H diff --git a/dep/rehlsdk/public/steam/matchmakingtypes.h b/dep/rehlsdk/public/steam/matchmakingtypes.h new file mode 100644 index 0000000..e5cb1da --- /dev/null +++ b/dep/rehlsdk/public/steam/matchmakingtypes.h @@ -0,0 +1,247 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: +// +// $NoKeywords: $ +//============================================================================= + +#ifndef MATCHMAKINGTYPES_H +#define MATCHMAKINGTYPES_H + +#ifdef _WIN32 +#pragma once +#endif + +#ifdef POSIX +#ifndef _snprintf +#define _snprintf snprintf +#endif +#endif + +#include +#include + +// +// Max size (in bytes of UTF-8 data, not in characters) of server fields, including null terminator. +// WARNING: These cannot be changed easily, without breaking clients using old interfaces. +// +const int k_cbMaxGameServerGameDir = 32; +const int k_cbMaxGameServerMapName = 32; +const int k_cbMaxGameServerGameDescription = 64; +const int k_cbMaxGameServerName = 64; +const int k_cbMaxGameServerTags = 128; +const int k_cbMaxGameServerGameData = 2048; + +struct MatchMakingKeyValuePair_t +{ + MatchMakingKeyValuePair_t() { m_szKey[0] = m_szValue[0] = 0; } + MatchMakingKeyValuePair_t( const char *pchKey, const char *pchValue ) + { + strncpy( m_szKey, pchKey, sizeof(m_szKey) ); // this is a public header, use basic c library string funcs only! + m_szKey[ sizeof( m_szKey ) - 1 ] = '\0'; + strncpy( m_szValue, pchValue, sizeof(m_szValue) ); + m_szValue[ sizeof( m_szValue ) - 1 ] = '\0'; + } + char m_szKey[ 256 ]; + char m_szValue[ 256 ]; +}; + + +enum EMatchMakingServerResponse +{ + eServerResponded = 0, + eServerFailedToRespond, + eNoServersListedOnMasterServer // for the Internet query type, returned in response callback if no servers of this type match +}; + +// servernetadr_t is all the addressing info the serverbrowser needs to know about a game server, +// namely: its IP, its connection port, and its query port. +class servernetadr_t +{ +public: + + void Init( unsigned int ip, uint16 usQueryPort, uint16 usConnectionPort ); + +// Uncompatible feature commented +//#ifdef NETADR_H +// netadr_t GetIPAndQueryPort(); +//#endif + + // Access the query port. + uint16 GetQueryPort() const; + void SetQueryPort( uint16 usPort ); + + // Access the connection port. + uint16 GetConnectionPort() const; + void SetConnectionPort( uint16 usPort ); + + // Access the IP + uint32 GetIP() const; + void SetIP( uint32 ); + + // This gets the 'a.b.c.d:port' string with the connection port (instead of the query port). + const char *GetConnectionAddressString() const; + const char *GetQueryAddressString() const; + + // Comparison operators and functions. + bool operator<(const servernetadr_t &netadr) const; + void operator=( const servernetadr_t &that ) + { + m_usConnectionPort = that.m_usConnectionPort; + m_usQueryPort = that.m_usQueryPort; + m_unIP = that.m_unIP; + } + + +private: + const char *ToString( uint32 unIP, uint16 usPort ) const; + uint16 m_usConnectionPort; // (in HOST byte order) + uint16 m_usQueryPort; + uint32 m_unIP; +}; + + +inline void servernetadr_t::Init( unsigned int ip, uint16 usQueryPort, uint16 usConnectionPort ) +{ + m_unIP = ip; + m_usQueryPort = usQueryPort; + m_usConnectionPort = usConnectionPort; +} + +// Uncompatible feature commented +//#ifdef NETADR_H +//inline netadr_t servernetadr_t::GetIPAndQueryPort() +//{ +// return netadr_t( m_unIP, m_usQueryPort ); +//} +//#endif + +inline uint16 servernetadr_t::GetQueryPort() const +{ + return m_usQueryPort; +} + +inline void servernetadr_t::SetQueryPort( uint16 usPort ) +{ + m_usQueryPort = usPort; +} + +inline uint16 servernetadr_t::GetConnectionPort() const +{ + return m_usConnectionPort; +} + +inline void servernetadr_t::SetConnectionPort( uint16 usPort ) +{ + m_usConnectionPort = usPort; +} + +inline uint32 servernetadr_t::GetIP() const +{ + return m_unIP; +} + +inline void servernetadr_t::SetIP( uint32 unIP ) +{ + m_unIP = unIP; +} + +inline const char *servernetadr_t::ToString( uint32 unIP, uint16 usPort ) const +{ + static char s[4][64]; + static int nBuf = 0; + unsigned char *ipByte = (unsigned char *)&unIP; +#ifdef VALVE_BIG_ENDIAN + snprintf (s[nBuf], sizeof( s[nBuf] ), "%u.%u.%u.%u:%i", (int)(ipByte[0]), (int)(ipByte[1]), (int)(ipByte[2]), (int)(ipByte[3]), usPort ); +#else + snprintf (s[nBuf], sizeof( s[nBuf] ), "%u.%u.%u.%u:%i", (int)(ipByte[3]), (int)(ipByte[2]), (int)(ipByte[1]), (int)(ipByte[0]), usPort ); +#endif + const char *pchRet = s[nBuf]; + ++nBuf; + nBuf %= ( (sizeof(s)/sizeof(s[0])) ); + return pchRet; +} + +inline const char* servernetadr_t::GetConnectionAddressString() const +{ + return ToString( m_unIP, m_usConnectionPort ); +} + +inline const char* servernetadr_t::GetQueryAddressString() const +{ + return ToString( m_unIP, m_usQueryPort ); +} + +inline bool servernetadr_t::operator<(const servernetadr_t &netadr) const +{ + return ( m_unIP < netadr.m_unIP ) || ( m_unIP == netadr.m_unIP && m_usQueryPort < netadr.m_usQueryPort ); +} + +//----------------------------------------------------------------------------- +// Purpose: Data describing a single server +//----------------------------------------------------------------------------- +class gameserveritem_t +{ +public: + gameserveritem_t(); + + const char* GetName() const; + void SetName( const char *pName ); + +public: + servernetadr_t m_NetAdr; ///< IP/Query Port/Connection Port for this server + int m_nPing; ///< current ping time in milliseconds + bool m_bHadSuccessfulResponse; ///< server has responded successfully in the past + bool m_bDoNotRefresh; ///< server is marked as not responding and should no longer be refreshed + char m_szGameDir[k_cbMaxGameServerGameDir]; ///< current game directory + char m_szMap[k_cbMaxGameServerMapName]; ///< current map + char m_szGameDescription[k_cbMaxGameServerGameDescription]; ///< game description + uint32 m_nAppID; ///< Steam App ID of this server + int m_nPlayers; ///< total number of players currently on the server. INCLUDES BOTS!! + int m_nMaxPlayers; ///< Maximum players that can join this server + int m_nBotPlayers; ///< Number of bots (i.e simulated players) on this server + bool m_bPassword; ///< true if this server needs a password to join + bool m_bSecure; ///< Is this server protected by VAC + uint32 m_ulTimeLastPlayed; ///< time (in unix time) when this server was last played on (for favorite/history servers) + int m_nServerVersion; ///< server version as reported to Steam + +private: + + /// Game server name + char m_szServerName[k_cbMaxGameServerName]; + + // For data added after SteamMatchMaking001 add it here +public: + /// the tags this server exposes + char m_szGameTags[k_cbMaxGameServerTags]; + + /// steamID of the game server - invalid if it's doesn't have one (old server, or not connected to Steam) + CSteamID m_steamID; +}; + + +inline gameserveritem_t::gameserveritem_t() +{ + m_szGameDir[0] = m_szMap[0] = m_szGameDescription[0] = m_szServerName[0] = 0; + m_bHadSuccessfulResponse = m_bDoNotRefresh = m_bPassword = m_bSecure = false; + m_nPing = m_nAppID = m_nPlayers = m_nMaxPlayers = m_nBotPlayers = m_ulTimeLastPlayed = m_nServerVersion = 0; + m_szGameTags[0] = 0; +} + +inline const char* gameserveritem_t::GetName() const +{ + // Use the IP address as the name if nothing is set yet. + if ( m_szServerName[0] == 0 ) + return m_NetAdr.GetConnectionAddressString(); + else + return m_szServerName; +} + +inline void gameserveritem_t::SetName( const char *pName ) +{ + strncpy( m_szServerName, pName, sizeof( m_szServerName ) ); + m_szServerName[ sizeof( m_szServerName ) - 1 ] = '\0'; +} + + +#endif // MATCHMAKINGTYPES_H diff --git a/dep/rehlsdk/public/steam/steam_api.h b/dep/rehlsdk/public/steam/steam_api.h new file mode 100644 index 0000000..026e285 --- /dev/null +++ b/dep/rehlsdk/public/steam/steam_api.h @@ -0,0 +1,545 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: +// +//============================================================================= + +#ifndef STEAM_API_H +#define STEAM_API_H +#ifdef _WIN32 +#pragma once +#endif + +#include "isteamclient.h" +#include "isteamuser.h" +#include "isteamfriends.h" +#include "isteamutils.h" +#include "isteammatchmaking.h" +#include "isteamuserstats.h" +#include "isteamapps.h" +#include "isteamnetworking.h" +#include "isteamremotestorage.h" +#include "isteamscreenshots.h" +#include "isteamhttp.h" +#include "isteamunifiedmessages.h" +#include "isteamcontroller.h" + +#if defined( _PS3 ) +#include "steamps3params.h" +#endif + +// Steam API export macro +#if defined( _WIN32 ) && !defined( _X360 ) + #if defined( STEAM_API_EXPORTS ) + #define S_API extern "C" __declspec( dllexport ) EXT_FUNC + #elif defined( STEAM_API_NODLL ) + #define S_API extern "C" + #else + #define S_API extern "C" __declspec( dllimport ) + #endif // STEAM_API_EXPORTS +#elif defined( GNUC ) + #if defined( STEAM_API_EXPORTS ) + #define S_API extern "C" __attribute__ ((visibility("default"))) EXT_FUNC + #else + #define S_API extern "C" + #endif // STEAM_API_EXPORTS +#else // !WIN32 + #if defined( STEAM_API_EXPORTS ) + #define S_API extern "C" EXT_FUNC + #else + #define S_API extern "C" + #endif // STEAM_API_EXPORTS +#endif + +class CCallbackBase; + +#ifdef REHLDS_SELF +#include "rehlds/platform.h" +#endif + +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// Steam API setup & shutdown +// +// These functions manage loading, initializing and shutdown of the steamclient.dll +// +//----------------------------------------------------------------------------------------------------------------------------------------------------------// + +// S_API void SteamAPI_Init(); (see below) +S_API void SteamAPI_Shutdown(); + +// checks if a local Steam client is running +S_API bool SteamAPI_IsSteamRunning(); + +// Detects if your executable was launched through the Steam client, and restarts your game through +// the client if necessary. The Steam client will be started if it is not running. +// +// Returns: true if your executable was NOT launched through the Steam client. This function will +// then start your application through the client. Your current process should exit. +// +// false if your executable was started through the Steam client or a steam_appid.txt file +// is present in your game's directory (for development). Your current process should continue. +// +// NOTE: This function should be used only if you are using CEG or not using Steam's DRM. Once applied +// to your executable, Steam's DRM will handle restarting through Steam if necessary. +S_API bool SteamAPI_RestartAppIfNecessary( uint32 unOwnAppID ); + +// crash dump recording functions +S_API void SteamAPI_WriteMiniDump( uint32 uStructuredExceptionCode, void* pvExceptionInfo, uint32 uBuildID ); +S_API void SteamAPI_SetMiniDumpComment( const char *pchMsg ); + +// interface pointers, configured by SteamAPI_Init() +S_API ISteamClient *SteamClient(); + + +// +// VERSION_SAFE_STEAM_API_INTERFACES is usually not necessary, but it provides safety against releasing +// new steam_api.dll's without recompiling/rereleasing modules that use it. +// +// If you use VERSION_SAFE_STEAM_API_INTERFACES, then you should call SteamAPI_InitSafe(). Also, to get the +// Steam interfaces, you must create and Init() a CSteamAPIContext (below) and use the interfaces in there. +// +// If you don't use VERSION_SAFE_STEAM_API_INTERFACES, then you can use SteamAPI_Init() and the SteamXXXX() +// functions below to get at the Steam interfaces. +// +#ifdef VERSION_SAFE_STEAM_API_INTERFACES +S_API bool SteamAPI_InitSafe(); +#else + +#if defined(_PS3) +S_API bool SteamAPI_Init( SteamPS3Params_t *pParams ); +#else +S_API bool SteamAPI_Init(); +#endif + +S_API ISteamUser *SteamUser(); +S_API ISteamFriends *SteamFriends(); +S_API ISteamUtils *SteamUtils(); +S_API ISteamMatchmaking *SteamMatchmaking(); +S_API ISteamUserStats *SteamUserStats(); +S_API ISteamApps *SteamApps(); +S_API ISteamNetworking *SteamNetworking(); +S_API ISteamMatchmakingServers *SteamMatchmakingServers(); +S_API ISteamRemoteStorage *SteamRemoteStorage(); +S_API ISteamScreenshots *SteamScreenshots(); +S_API ISteamHTTP *SteamHTTP(); +S_API ISteamUnifiedMessages *SteamUnifiedMessages(); +#ifdef _PS3 +S_API ISteamPS3OverlayRender * SteamPS3OverlayRender(); +#endif +#endif // VERSION_SAFE_STEAM_API_INTERFACES + +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// steam callback helper functions +// +// The following classes/macros are used to be able to easily multiplex callbacks +// from the Steam API into various objects in the app in a thread-safe manner +// +// These functors are triggered via the SteamAPI_RunCallbacks() function, mapping the callback +// to as many functions/objects as are registered to it +//----------------------------------------------------------------------------------------------------------------------------------------------------------// + +S_API void SteamAPI_RunCallbacks(); + + + +// functions used by the utility CCallback objects to receive callbacks +S_API void SteamAPI_RegisterCallback( class CCallbackBase *pCallback, int iCallback ); +S_API void SteamAPI_UnregisterCallback( class CCallbackBase *pCallback ); +// functions used by the utility CCallResult objects to receive async call results +S_API void SteamAPI_RegisterCallResult( class CCallbackBase *pCallback, SteamAPICall_t hAPICall ); +S_API void SteamAPI_UnregisterCallResult( class CCallbackBase *pCallback, SteamAPICall_t hAPICall ); + + +//----------------------------------------------------------------------------- +// Purpose: base for callbacks, +// used only by CCallback, shouldn't be used directly +//----------------------------------------------------------------------------- +class CCallbackBase +{ +public: + CCallbackBase() { m_nCallbackFlags = 0; m_iCallback = 0; } + // don't add a virtual destructor because we export this binary interface across dll's + virtual void Run( void *pvParam ) = 0; + virtual void Run( void *pvParam, bool bIOFailure, SteamAPICall_t hSteamAPICall ) = 0; + int GetICallback() { return m_iCallback; } + virtual int GetCallbackSizeBytes() = 0; + + //Added for hooking support + uint8 GetFlags() { return m_nCallbackFlags; } + void SetFlags(uint8 flags) { m_nCallbackFlags = flags; } + void SetICallback(int cb) { m_iCallback = cb; } + +protected: + enum { k_ECallbackFlagsRegistered = 0x01, k_ECallbackFlagsGameServer = 0x02 }; + uint8 m_nCallbackFlags; + int m_iCallback; + friend class CCallbackMgr; +}; + + +//----------------------------------------------------------------------------- +// Purpose: maps a steam async call result to a class member function +// template params: T = local class, P = parameter struct +//----------------------------------------------------------------------------- +template< class T, class P > +class CCallResult : private CCallbackBase +{ +public: + typedef void (T::*func_t)( P*, bool ); + + CCallResult() + { + m_hAPICall = k_uAPICallInvalid; + m_pObj = NULL; + m_Func = NULL; + m_iCallback = P::k_iCallback; + } + + void Set( SteamAPICall_t hAPICall, T *p, func_t func ) + { + if ( m_hAPICall ) + SteamAPI_UnregisterCallResult( this, m_hAPICall ); + + m_hAPICall = hAPICall; + m_pObj = p; + m_Func = func; + + if ( hAPICall ) + SteamAPI_RegisterCallResult( this, hAPICall ); + } + + bool IsActive() const + { + return ( m_hAPICall != k_uAPICallInvalid ); + } + + void Cancel() + { + if ( m_hAPICall != k_uAPICallInvalid ) + { + SteamAPI_UnregisterCallResult( this, m_hAPICall ); + m_hAPICall = k_uAPICallInvalid; + } + + } + + ~CCallResult() + { + Cancel(); + } + + void SetGameserverFlag() { m_nCallbackFlags |= k_ECallbackFlagsGameServer; } +private: + virtual void Run( void *pvParam ) + { + m_hAPICall = k_uAPICallInvalid; // caller unregisters for us + (m_pObj->*m_Func)( (P *)pvParam, false ); + } + void Run( void *pvParam, bool bIOFailure, SteamAPICall_t hSteamAPICall ) + { + if ( hSteamAPICall == m_hAPICall ) + { + m_hAPICall = k_uAPICallInvalid; // caller unregisters for us + (m_pObj->*m_Func)( (P *)pvParam, bIOFailure ); + } + } + int GetCallbackSizeBytes() + { + return sizeof( P ); + } + + SteamAPICall_t m_hAPICall; + T *m_pObj; + func_t m_Func; +}; + + + +//----------------------------------------------------------------------------- +// Purpose: maps a steam callback to a class member function +// template params: T = local class, P = parameter struct +//----------------------------------------------------------------------------- +template< class T, class P, bool bGameServer > +class CCallback : protected CCallbackBase +{ +public: + typedef void (T::*func_t)( P* ); + + // If you can't support constructing a callback with the correct parameters + // then uncomment the empty constructor below and manually call + // ::Register() for your object + // Or, just call the regular constructor with (NULL, NULL) + // CCallback() {} + + // constructor for initializing this object in owner's constructor + CCallback( T *pObj, func_t func ) : m_pObj( pObj ), m_Func( func ) + { + if ( pObj && func ) + Register( pObj, func ); + } + + ~CCallback() + { + if ( m_nCallbackFlags & k_ECallbackFlagsRegistered ) + Unregister(); + } + + // manual registration of the callback + void Register( T *pObj, func_t func ) + { + if ( !pObj || !func ) + return; + + if ( m_nCallbackFlags & k_ECallbackFlagsRegistered ) + Unregister(); + + if ( bGameServer ) + { + m_nCallbackFlags |= k_ECallbackFlagsGameServer; + } + m_pObj = pObj; + m_Func = func; + // SteamAPI_RegisterCallback sets k_ECallbackFlagsRegistered + +#ifdef REHLDS_SELF + CRehldsPlatformHolder::get()->SteamAPI_RegisterCallback(this, P::k_iCallback); +#else + SteamAPI_RegisterCallback(this, P::k_iCallback); +#endif // REHLDS_SELF + } + + void Unregister() + { + // SteamAPI_UnregisterCallback removes k_ECallbackFlagsRegistered + +#ifdef REHLDS_SELF + CRehldsPlatformHolder::get()->SteamAPI_UnregisterCallback(this); +#else + SteamAPI_UnregisterCallback(this); +#endif // REHLDS_SELF + } + + void SetGameserverFlag() { m_nCallbackFlags |= k_ECallbackFlagsGameServer; } +protected: + virtual void Run( void *pvParam ) + { + (m_pObj->*m_Func)( (P *)pvParam ); + } + virtual void Run( void *pvParam, bool, SteamAPICall_t ) + { + (m_pObj->*m_Func)( (P *)pvParam ); + } + int GetCallbackSizeBytes() + { + return sizeof( P ); + } + + T *m_pObj; + func_t m_Func; +}; + +// Allows you to defer registration of the callback +template< class T, class P, bool bGameServer > +class CCallbackManual : public CCallback< T, P, bGameServer > +{ +public: + CCallbackManual() : CCallback< T, P, bGameServer >( NULL, NULL ) {} +}; + +// utility macro for declaring the function and callback object together +#define STEAM_CALLBACK( thisclass, func, param, var ) CCallback< thisclass, param, false > var; void func( param *pParam ) + +// same as above, but lets you defer the callback binding by calling Register later +#define STEAM_CALLBACK_MANUAL( thisclass, func, param, var ) CCallbackManual< thisclass, param, false > var; void func( param *pParam ) + + +#ifdef _WIN32 +// disable this warning; this pattern need for steam callback registration +#pragma warning( disable: 4355 ) // 'this' : used in base member initializer list +#endif + + +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// steamclient.dll private wrapper functions +// +// The following functions are part of abstracting API access to the steamclient.dll, but should only be used in very specific cases +//----------------------------------------------------------------------------------------------------------------------------------------------------------// + +// pumps out all the steam messages, calling the register callback +S_API void Steam_RunCallbacks( HSteamPipe hSteamPipe, bool bGameServerCallbacks ); + +// register the callback funcs to use to interact with the steam dll +S_API void Steam_RegisterInterfaceFuncs( void *hModule ); + +// returns the HSteamUser of the last user to dispatch a callback +S_API HSteamUser Steam_GetHSteamUserCurrent(); + +// returns the filename path of the current running Steam process, used if you need to load an explicit steam dll by name +S_API const char *SteamAPI_GetSteamInstallPath(); + +// returns the pipe we are communicating to Steam with +S_API HSteamPipe SteamAPI_GetHSteamPipe(); + +// sets whether or not Steam_RunCallbacks() should do a try {} catch (...) {} around calls to issuing callbacks +S_API void SteamAPI_SetTryCatchCallbacks( bool bTryCatchCallbacks ); + +// backwards compat export, passes through to SteamAPI_ variants +S_API HSteamPipe GetHSteamPipe(); +S_API HSteamUser GetHSteamUser(); + +#ifdef VERSION_SAFE_STEAM_API_INTERFACES +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// VERSION_SAFE_STEAM_API_INTERFACES uses CSteamAPIContext to provide interfaces to each module in a way that +// lets them each specify the interface versions they are compiled with. +// +// It's important that these stay inlined in the header so the calling module specifies the interface versions +// for whatever Steam API version it has. +//----------------------------------------------------------------------------------------------------------------------------------------------------------// + +S_API HSteamUser SteamAPI_GetHSteamUser(); + +class CSteamAPIContext +{ +public: + CSteamAPIContext(); + void Clear(); + + bool Init(); + + ISteamUser* SteamUser() { return m_pSteamUser; } + ISteamFriends* SteamFriends() { return m_pSteamFriends; } + ISteamUtils* SteamUtils() { return m_pSteamUtils; } + ISteamMatchmaking* SteamMatchmaking() { return m_pSteamMatchmaking; } + ISteamUserStats* SteamUserStats() { return m_pSteamUserStats; } + ISteamApps* SteamApps() { return m_pSteamApps; } + ISteamMatchmakingServers* SteamMatchmakingServers() { return m_pSteamMatchmakingServers; } + ISteamNetworking* SteamNetworking() { return m_pSteamNetworking; } + ISteamRemoteStorage* SteamRemoteStorage() { return m_pSteamRemoteStorage; } + ISteamScreenshots* SteamScreenshots() { return m_pSteamScreenshots; } + ISteamHTTP* SteamHTTP() { return m_pSteamHTTP; } + ISteamUnifiedMessages* SteamUnifiedMessages() { return m_pSteamUnifiedMessages; } +#ifdef _PS3 + ISteamPS3OverlayRender* SteamPS3OverlayRender() { return m_pSteamPS3OverlayRender; } +#endif + +private: + ISteamUser *m_pSteamUser; + ISteamFriends *m_pSteamFriends; + ISteamUtils *m_pSteamUtils; + ISteamMatchmaking *m_pSteamMatchmaking; + ISteamUserStats *m_pSteamUserStats; + ISteamApps *m_pSteamApps; + ISteamMatchmakingServers *m_pSteamMatchmakingServers; + ISteamNetworking *m_pSteamNetworking; + ISteamRemoteStorage *m_pSteamRemoteStorage; + ISteamScreenshots *m_pSteamScreenshots; + ISteamHTTP *m_pSteamHTTP; + ISteamUnifiedMessages*m_pSteamUnifiedMessages; + ISteamController *m_pController; +#ifdef _PS3 + ISteamPS3OverlayRender *m_pSteamPS3OverlayRender; +#endif +}; + +inline CSteamAPIContext::CSteamAPIContext() +{ + Clear(); +} + +inline void CSteamAPIContext::Clear() +{ + m_pSteamUser = NULL; + m_pSteamFriends = NULL; + m_pSteamUtils = NULL; + m_pSteamMatchmaking = NULL; + m_pSteamUserStats = NULL; + m_pSteamApps = NULL; + m_pSteamMatchmakingServers = NULL; + m_pSteamNetworking = NULL; + m_pSteamRemoteStorage = NULL; + m_pSteamHTTP = NULL; + m_pSteamScreenshots = NULL; + m_pSteamUnifiedMessages = NULL; +#ifdef _PS3 + m_pSteamPS3OverlayRender = NULL; +#endif +} + +// This function must be inlined so the module using steam_api.dll gets the version names they want. +inline bool CSteamAPIContext::Init() +{ + if ( !SteamClient() ) + return false; + + HSteamUser hSteamUser = SteamAPI_GetHSteamUser(); + HSteamPipe hSteamPipe = SteamAPI_GetHSteamPipe(); + + m_pSteamUser = SteamClient()->GetISteamUser( hSteamUser, hSteamPipe, STEAMUSER_INTERFACE_VERSION ); + if ( !m_pSteamUser ) + return false; + + m_pSteamFriends = SteamClient()->GetISteamFriends( hSteamUser, hSteamPipe, STEAMFRIENDS_INTERFACE_VERSION ); + if ( !m_pSteamFriends ) + return false; + + m_pSteamUtils = SteamClient()->GetISteamUtils( hSteamPipe, STEAMUTILS_INTERFACE_VERSION ); + if ( !m_pSteamUtils ) + return false; + + m_pSteamMatchmaking = SteamClient()->GetISteamMatchmaking( hSteamUser, hSteamPipe, STEAMMATCHMAKING_INTERFACE_VERSION ); + if ( !m_pSteamMatchmaking ) + return false; + + m_pSteamMatchmakingServers = SteamClient()->GetISteamMatchmakingServers( hSteamUser, hSteamPipe, STEAMMATCHMAKINGSERVERS_INTERFACE_VERSION ); + if ( !m_pSteamMatchmakingServers ) + return false; + + m_pSteamUserStats = SteamClient()->GetISteamUserStats( hSteamUser, hSteamPipe, STEAMUSERSTATS_INTERFACE_VERSION ); + if ( !m_pSteamUserStats ) + return false; + + m_pSteamApps = SteamClient()->GetISteamApps( hSteamUser, hSteamPipe, STEAMAPPS_INTERFACE_VERSION ); + if ( !m_pSteamApps ) + return false; + + m_pSteamNetworking = SteamClient()->GetISteamNetworking( hSteamUser, hSteamPipe, STEAMNETWORKING_INTERFACE_VERSION ); + if ( !m_pSteamNetworking ) + return false; + + m_pSteamRemoteStorage = SteamClient()->GetISteamRemoteStorage( hSteamUser, hSteamPipe, STEAMREMOTESTORAGE_INTERFACE_VERSION ); + if ( !m_pSteamRemoteStorage ) + return false; + + m_pSteamScreenshots = SteamClient()->GetISteamScreenshots( hSteamUser, hSteamPipe, STEAMSCREENSHOTS_INTERFACE_VERSION ); + if ( !m_pSteamScreenshots ) + return false; + + m_pSteamHTTP = SteamClient()->GetISteamHTTP( hSteamUser, hSteamPipe, STEAMHTTP_INTERFACE_VERSION ); + if ( !m_pSteamHTTP ) + return false; + + m_pSteamUnifiedMessages = SteamClient()->GetISteamUnifiedMessages( hSteamUser, hSteamPipe, STEAMUNIFIEDMESSAGES_INTERFACE_VERSION ); + if ( !m_pSteamUnifiedMessages ) + return false; + +#ifdef _PS3 + m_pSteamPS3OverlayRender = SteamClient()->GetISteamPS3OverlayRender(); +#endif + + return true; +} + +#endif // VERSION_SAFE_STEAM_API_INTERFACES + +#if defined(USE_BREAKPAD_HANDLER) || defined(STEAM_API_EXPORTS) +// this should be called before the game initialized the steam APIs +// pchDate should be of the format "Mmm dd yyyy" (such as from the __DATE __ macro ) +// pchTime should be of the format "hh:mm:ss" (such as from the __TIME __ macro ) +// bFullMemoryDumps (Win32 only) -- writes out a uuid-full.dmp in the client/dumps folder +// pvContext-- can be NULL, will be the void * context passed into m_pfnPreMinidumpCallback +// PFNPreMinidumpCallback m_pfnPreMinidumpCallback -- optional callback which occurs just before a .dmp file is written during a crash. Applications can hook this to allow adding additional information into the .dmp comment stream. +S_API void SteamAPI_UseBreakpadCrashHandler( char const *pchVersion, char const *pchDate, char const *pchTime, bool bFullMemoryDumps, void *pvContext, PFNPreMinidumpCallback m_pfnPreMinidumpCallback ); +S_API void SteamAPI_SetBreakpadAppID( uint32 unAppID ); +#endif + +#endif // STEAM_API_H diff --git a/dep/rehlsdk/public/steam/steam_gameserver.h b/dep/rehlsdk/public/steam/steam_gameserver.h new file mode 100644 index 0000000..e031e31 --- /dev/null +++ b/dep/rehlsdk/public/steam/steam_gameserver.h @@ -0,0 +1,163 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: +// +//============================================================================= + +#ifndef STEAM_GAMESERVER_H +#define STEAM_GAMESERVER_H +#ifdef _WIN32 +#pragma once +#endif + +#include "steam_api.h" +#include "isteamgameserver.h" +#include "isteamgameserverstats.h" + +enum EServerMode +{ + eServerModeInvalid = 0, // DO NOT USE + eServerModeNoAuthentication = 1, // Don't authenticate user logins and don't list on the server list + eServerModeAuthentication = 2, // Authenticate users, list on the server list, don't run VAC on clients that connect + eServerModeAuthenticationAndSecure = 3, // Authenticate users, list on the server list and VAC protect clients +}; + +// Initialize ISteamGameServer interface object, and set server properties which may not be changed. +// +// After calling this function, you should set any additional server parameters, and then +// call ISteamGameServer::LogOnAnonymous() or ISteamGameServer::LogOn() +// +// - usSteamPort is the local port used to communicate with the steam servers. +// - usGamePort is the port that clients will connect to for gameplay. +// - usQueryPort is the port that will manage server browser related duties and info +// pings from clients. If you pass MASTERSERVERUPDATERPORT_USEGAMESOCKETSHARE for usQueryPort, then it +// will use "GameSocketShare" mode, which means that the game is responsible for sending and receiving +// UDP packets for the master server updater. See references to GameSocketShare in isteamgameserver.h. +// - The version string is usually in the form x.x.x.x, and is used by the master server to detect when the +// server is out of date. (Only servers with the latest version will be listed.) +#ifndef _PS3 + +#ifdef VERSION_SAFE_STEAM_API_INTERFACES +S_API bool SteamGameServer_InitSafe( uint32 unIP, uint16 usSteamPort, uint16 usGamePort, uint16 usQueryPort, EServerMode eServerMode, const char *pchVersionString ); +#else +S_API bool SteamGameServer_Init( uint32 unIP, uint16 usSteamPort, uint16 usGamePort, uint16 usQueryPort, EServerMode eServerMode, const char *pchVersionString ); +#endif + +#else + +#ifdef VERSION_SAFE_STEAM_API_INTERFACES +S_API bool SteamGameServer_InitSafe( const SteamPS3Params_t *ps3Params, uint32 unIP, uint16 usSteamPort, uint16 usGamePort, uint16 usQueryPort, EServerMode eServerMode, const char *pchVersionString ); +#else +S_API bool SteamGameServer_Init( const SteamPS3Params_t *ps3Params, uint32 unIP, uint16 usSteamPort, uint16 usGamePort, uint16 usQueryPort, EServerMode eServerMode, const char *pchVersionString ); +#endif + +#endif + +#ifndef VERSION_SAFE_STEAM_API_INTERFACES +S_API ISteamGameServer *SteamGameServer(); +S_API ISteamUtils *SteamGameServerUtils(); +S_API ISteamNetworking *SteamGameServerNetworking(); +S_API ISteamGameServerStats *SteamGameServerStats(); +S_API ISteamHTTP *SteamGameServerHTTP(); +#endif + +S_API void SteamGameServer_Shutdown(); +S_API void SteamGameServer_RunCallbacks(); + +S_API bool SteamGameServer_BSecure(); +S_API uint64 SteamGameServer_GetSteamID(); + +#define STEAM_GAMESERVER_CALLBACK( thisclass, func, param, var ) CCallback< thisclass, param, true > var; void func( param *pParam ) + + +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// steamclient.dll private wrapper functions +// +// The following functions are part of abstracting API access to the steamclient.dll, but should only be used in very specific cases +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +S_API HSteamPipe SteamGameServer_GetHSteamPipe(); + +#ifdef VERSION_SAFE_STEAM_API_INTERFACES +//----------------------------------------------------------------------------------------------------------------------------------------------------------// +// VERSION_SAFE_STEAM_API_INTERFACES uses CSteamAPIContext to provide interfaces to each module in a way that +// lets them each specify the interface versions they are compiled with. +// +// It's important that these stay inlined in the header so the calling module specifies the interface versions +// for whatever Steam API version it has. +//----------------------------------------------------------------------------------------------------------------------------------------------------------// + +S_API HSteamUser SteamGameServer_GetHSteamUser(); + +class CSteamGameServerAPIContext +{ +public: + CSteamGameServerAPIContext(); + void Clear(); + + bool Init(); + + ISteamGameServer *SteamGameServer() { return m_pSteamGameServer; } + ISteamUtils *SteamGameServerUtils() { return m_pSteamGameServerUtils; } + ISteamNetworking *SteamGameServerNetworking() { return m_pSteamGameServerNetworking; } + ISteamGameServerStats *SteamGameServerStats() { return m_pSteamGameServerStats; } + ISteamHTTP *SteamHTTP() { return m_pSteamHTTP; } + +private: + ISteamGameServer *m_pSteamGameServer; + ISteamUtils *m_pSteamGameServerUtils; + ISteamNetworking *m_pSteamGameServerNetworking; + ISteamGameServerStats *m_pSteamGameServerStats; + ISteamHTTP *m_pSteamHTTP; +}; + +inline CSteamGameServerAPIContext::CSteamGameServerAPIContext() +{ + Clear(); +} + +inline void CSteamGameServerAPIContext::Clear() +{ + m_pSteamGameServer = NULL; + m_pSteamGameServerUtils = NULL; + m_pSteamGameServerNetworking = NULL; + m_pSteamGameServerStats = NULL; + m_pSteamHTTP = NULL; +} + +S_API ISteamClient *g_pSteamClientGameServer; +// This function must be inlined so the module using steam_api.dll gets the version names they want. +inline bool CSteamGameServerAPIContext::Init() +{ + if ( !g_pSteamClientGameServer ) + return false; + + HSteamUser hSteamUser = SteamGameServer_GetHSteamUser(); + HSteamPipe hSteamPipe = SteamGameServer_GetHSteamPipe(); + + m_pSteamGameServer = g_pSteamClientGameServer->GetISteamGameServer( hSteamUser, hSteamPipe, STEAMGAMESERVER_INTERFACE_VERSION ); + if ( !m_pSteamGameServer ) + return false; + + m_pSteamGameServerUtils = g_pSteamClientGameServer->GetISteamUtils( hSteamPipe, STEAMUTILS_INTERFACE_VERSION ); + if ( !m_pSteamGameServerUtils ) + return false; + + m_pSteamGameServerNetworking = g_pSteamClientGameServer->GetISteamNetworking( hSteamUser, hSteamPipe, STEAMNETWORKING_INTERFACE_VERSION ); + if ( !m_pSteamGameServerNetworking ) + return false; + + m_pSteamGameServerStats = g_pSteamClientGameServer->GetISteamGameServerStats( hSteamUser, hSteamPipe, STEAMGAMESERVERSTATS_INTERFACE_VERSION ); + if ( !m_pSteamGameServerStats ) + return false; + + m_pSteamHTTP = g_pSteamClientGameServer->GetISteamHTTP( hSteamUser, hSteamPipe, STEAMHTTP_INTERFACE_VERSION ); + if ( !m_pSteamGameServerStats ) + return false; + + return true; +} + +#endif // VERSION_SAFE_STEAM_API_INTERFACES + + +#endif // STEAM_GAMESERVER_H diff --git a/dep/rehlsdk/public/steam/steamclientpublic.h b/dep/rehlsdk/public/steam/steamclientpublic.h new file mode 100644 index 0000000..b129267 --- /dev/null +++ b/dep/rehlsdk/public/steam/steamclientpublic.h @@ -0,0 +1,1086 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: +// +//============================================================================= + +#ifndef STEAMCLIENTPUBLIC_H +#define STEAMCLIENTPUBLIC_H +#ifdef _WIN32 +#pragma once +#endif +//lint -save -e1931 -e1927 -e1924 -e613 -e726 + +// This header file defines the interface between the calling application and the code that +// knows how to communicate with the connection manager (CM) from the Steam service + +// This header file is intended to be portable; ideally this 1 header file plus a lib or dll +// is all you need to integrate the client library into some other tree. So please avoid +// including or requiring other header files if possible. This header should only describe the +// interface layer, no need to include anything about the implementation. + +#include "steamtypes.h" + + +// General result codes +enum EResult +{ + k_EResultOK = 1, // success + k_EResultFail = 2, // generic failure + k_EResultNoConnection = 3, // no/failed network connection +// k_EResultNoConnectionRetry = 4, // OBSOLETE - removed + k_EResultInvalidPassword = 5, // password/ticket is invalid + k_EResultLoggedInElsewhere = 6, // same user logged in elsewhere + k_EResultInvalidProtocolVer = 7, // protocol version is incorrect + k_EResultInvalidParam = 8, // a parameter is incorrect + k_EResultFileNotFound = 9, // file was not found + k_EResultBusy = 10, // called method busy - action not taken + k_EResultInvalidState = 11, // called object was in an invalid state + k_EResultInvalidName = 12, // name is invalid + k_EResultInvalidEmail = 13, // email is invalid + k_EResultDuplicateName = 14, // name is not unique + k_EResultAccessDenied = 15, // access is denied + k_EResultTimeout = 16, // operation timed out + k_EResultBanned = 17, // VAC2 banned + k_EResultAccountNotFound = 18, // account not found + k_EResultInvalidSteamID = 19, // steamID is invalid + k_EResultServiceUnavailable = 20, // The requested service is currently unavailable + k_EResultNotLoggedOn = 21, // The user is not logged on + k_EResultPending = 22, // Request is pending (may be in process, or waiting on third party) + k_EResultEncryptionFailure = 23, // Encryption or Decryption failed + k_EResultInsufficientPrivilege = 24, // Insufficient privilege + k_EResultLimitExceeded = 25, // Too much of a good thing + k_EResultRevoked = 26, // Access has been revoked (used for revoked guest passes) + k_EResultExpired = 27, // License/Guest pass the user is trying to access is expired + k_EResultAlreadyRedeemed = 28, // Guest pass has already been redeemed by account, cannot be acked again + k_EResultDuplicateRequest = 29, // The request is a duplicate and the action has already occurred in the past, ignored this time + k_EResultAlreadyOwned = 30, // All the games in this guest pass redemption request are already owned by the user + k_EResultIPNotFound = 31, // IP address not found + k_EResultPersistFailed = 32, // failed to write change to the data store + k_EResultLockingFailed = 33, // failed to acquire access lock for this operation + k_EResultLogonSessionReplaced = 34, + k_EResultConnectFailed = 35, + k_EResultHandshakeFailed = 36, + k_EResultIOFailure = 37, + k_EResultRemoteDisconnect = 38, + k_EResultShoppingCartNotFound = 39, // failed to find the shopping cart requested + k_EResultBlocked = 40, // a user didn't allow it + k_EResultIgnored = 41, // target is ignoring sender + k_EResultNoMatch = 42, // nothing matching the request found + k_EResultAccountDisabled = 43, + k_EResultServiceReadOnly = 44, // this service is not accepting content changes right now + k_EResultAccountNotFeatured = 45, // account doesn't have value, so this feature isn't available + k_EResultAdministratorOK = 46, // allowed to take this action, but only because requester is admin + k_EResultContentVersion = 47, // A Version mismatch in content transmitted within the Steam protocol. + k_EResultTryAnotherCM = 48, // The current CM can't service the user making a request, user should try another. + k_EResultPasswordRequiredToKickSession = 49,// You are already logged in elsewhere, this cached credential login has failed. + k_EResultAlreadyLoggedInElsewhere = 50, // You are already logged in elsewhere, you must wait + k_EResultSuspended = 51, // Long running operation (content download) suspended/paused + k_EResultCancelled = 52, // Operation canceled (typically by user: content download) + k_EResultDataCorruption = 53, // Operation canceled because data is ill formed or unrecoverable + k_EResultDiskFull = 54, // Operation canceled - not enough disk space. + k_EResultRemoteCallFailed = 55, // an remote call or IPC call failed + k_EResultPasswordUnset = 56, // Password could not be verified as it's unset server side + k_EResultExternalAccountUnlinked = 57, // External account (PSN, Facebook...) is not linked to a Steam account + k_EResultPSNTicketInvalid = 58, // PSN ticket was invalid + k_EResultExternalAccountAlreadyLinked = 59, // External account (PSN, Facebook...) is already linked to some other account, must explicitly request to replace/delete the link first + k_EResultRemoteFileConflict = 60, // The sync cannot resume due to a conflict between the local and remote files + k_EResultIllegalPassword = 61, // The requested new password is not legal + k_EResultSameAsPreviousValue = 62, // new value is the same as the old one ( secret question and answer ) + k_EResultAccountLogonDenied = 63, // account login denied due to 2nd factor authentication failure + k_EResultCannotUseOldPassword = 64, // The requested new password is not legal + k_EResultInvalidLoginAuthCode = 65, // account login denied due to auth code invalid + k_EResultAccountLogonDeniedNoMail = 66, // account login denied due to 2nd factor auth failure - and no mail has been sent + k_EResultHardwareNotCapableOfIPT = 67, // + k_EResultIPTInitError = 68, // + k_EResultParentalControlRestricted = 69, // operation failed due to parental control restrictions for current user + k_EResultFacebookQueryError = 70, // Facebook query returned an error + k_EResultExpiredLoginAuthCode = 71, // account login denied due to auth code expired + k_EResultIPLoginRestrictionFailed = 72, + k_EResultAccountLockedDown = 73, + k_EResultAccountLogonDeniedVerifiedEmailRequired = 74, + k_EResultNoMatchingURL = 75, + k_EResultBadResponse = 76, // parse failure, missing field, etc. + k_EResultRequirePasswordReEntry = 77, // The user cannot complete the action until they re-enter their password + k_EResultValueOutOfRange = 78 // the value entered is outside the acceptable range +}; + +// Error codes for use with the voice functions +enum EVoiceResult +{ + k_EVoiceResultOK = 0, + k_EVoiceResultNotInitialized = 1, + k_EVoiceResultNotRecording = 2, + k_EVoiceResultNoData = 3, + k_EVoiceResultBufferTooSmall = 4, + k_EVoiceResultDataCorrupted = 5, + k_EVoiceResultRestricted = 6, + k_EVoiceResultUnsupportedCodec = 7, + +}; + +// Result codes to GSHandleClientDeny/Kick +typedef enum +{ + k_EDenyInvalid = 0, + k_EDenyInvalidVersion = 1, + k_EDenyGeneric = 2, + k_EDenyNotLoggedOn = 3, + k_EDenyNoLicense = 4, + k_EDenyCheater = 5, + k_EDenyLoggedInElseWhere = 6, + k_EDenyUnknownText = 7, + k_EDenyIncompatibleAnticheat = 8, + k_EDenyMemoryCorruption = 9, + k_EDenyIncompatibleSoftware = 10, + k_EDenySteamConnectionLost = 11, + k_EDenySteamConnectionError = 12, + k_EDenySteamResponseTimedOut = 13, + k_EDenySteamValidationStalled = 14, + k_EDenySteamOwnerLeftGuestUser = 15, +} EDenyReason; + +// return type of GetAuthSessionTicket +typedef uint32 HAuthTicket; +const HAuthTicket k_HAuthTicketInvalid = 0; + +// results from BeginAuthSession +typedef enum +{ + k_EBeginAuthSessionResultOK = 0, // Ticket is valid for this game and this steamID. + k_EBeginAuthSessionResultInvalidTicket = 1, // Ticket is not valid. + k_EBeginAuthSessionResultDuplicateRequest = 2, // A ticket has already been submitted for this steamID + k_EBeginAuthSessionResultInvalidVersion = 3, // Ticket is from an incompatible interface version + k_EBeginAuthSessionResultGameMismatch = 4, // Ticket is not for this game + k_EBeginAuthSessionResultExpiredTicket = 5, // Ticket has expired +} EBeginAuthSessionResult; + +// Callback values for callback ValidateAuthTicketResponse_t which is a response to BeginAuthSession +typedef enum +{ + k_EAuthSessionResponseOK = 0, // Steam has verified the user is online, the ticket is valid and ticket has not been reused. + k_EAuthSessionResponseUserNotConnectedToSteam = 1, // The user in question is not connected to steam + k_EAuthSessionResponseNoLicenseOrExpired = 2, // The license has expired. + k_EAuthSessionResponseVACBanned = 3, // The user is VAC banned for this game. + k_EAuthSessionResponseLoggedInElseWhere = 4, // The user account has logged in elsewhere and the session containing the game instance has been disconnected. + k_EAuthSessionResponseVACCheckTimedOut = 5, // VAC has been unable to perform anti-cheat checks on this user + k_EAuthSessionResponseAuthTicketCanceled = 6, // The ticket has been canceled by the issuer + k_EAuthSessionResponseAuthTicketInvalidAlreadyUsed = 7, // This ticket has already been used, it is not valid. + k_EAuthSessionResponseAuthTicketInvalid = 8, // This ticket is not from a user instance currently connected to steam. +} EAuthSessionResponse; + +// results from UserHasLicenseForApp +typedef enum +{ + k_EUserHasLicenseResultHasLicense = 0, // User has a license for specified app + k_EUserHasLicenseResultDoesNotHaveLicense = 1, // User does not have a license for the specified app + k_EUserHasLicenseResultNoAuth = 2, // User has not been authenticated +} EUserHasLicenseForAppResult; + + +// Steam universes. Each universe is a self-contained Steam instance. +enum EUniverse +{ + k_EUniverseInvalid = 0, + k_EUniversePublic = 1, + k_EUniverseBeta = 2, + k_EUniverseInternal = 3, + k_EUniverseDev = 4, + // k_EUniverseRC = 5, // no such universe anymore + k_EUniverseMax +}; + +// Steam account types +enum EAccountType +{ + k_EAccountTypeInvalid = 0, + k_EAccountTypeIndividual = 1, // single user account + k_EAccountTypeMultiseat = 2, // multiseat (e.g. cybercafe) account + k_EAccountTypeGameServer = 3, // game server account + k_EAccountTypeAnonGameServer = 4, // anonymous game server account + k_EAccountTypePending = 5, // pending + k_EAccountTypeContentServer = 6, // content server + k_EAccountTypeClan = 7, + k_EAccountTypeChat = 8, + k_EAccountTypeConsoleUser = 9, // Fake SteamID for local PSN account on PS3 or Live account on 360, etc. + k_EAccountTypeAnonUser = 10, + + // Max of 16 items in this field + k_EAccountTypeMax +}; + + + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +enum EAppReleaseState +{ + k_EAppReleaseState_Unknown = 0, // unknown, required appinfo or license info is missing + k_EAppReleaseState_Unavailable = 1, // even if user 'just' owns it, can see game at all + k_EAppReleaseState_Prerelease = 2, // can be purchased and is visible in games list, nothing else. Common appInfo section released + k_EAppReleaseState_PreloadOnly = 3, // owners can preload app, not play it. AppInfo fully released. + k_EAppReleaseState_Released = 4, // owners can download and play app. +}; + + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +enum EAppOwernshipFlags +{ + k_EAppOwernshipFlags_None = 0, // unknown + k_EAppOwernshipFlags_OwnsLicense = 1, // owns license for this game + k_EAppOwernshipFlags_FreeLicense = 2, // not paid for game + k_EAppOwernshipFlags_RegionRestricted = 4, // owns app, but not allowed to play in current region + k_EAppOwernshipFlags_LowViolence = 8, // only low violence version + k_EAppOwernshipFlags_InvalidPlatform = 16, // app not supported on current platform + k_EAppOwernshipFlags_DeviceLicense = 32, // license was granted by authorized local device +}; + + +//----------------------------------------------------------------------------- +// Purpose: designed as flags to allow filters masks +//----------------------------------------------------------------------------- +enum EAppType +{ + k_EAppType_Invalid = 0x000, // unknown / invalid + k_EAppType_Game = 0x001, // playable game, default type + k_EAppType_Application = 0x002, // software application + k_EAppType_Tool = 0x004, // SDKs, editors & dedicated servers + k_EAppType_Demo = 0x008, // game demo + k_EAppType_Media = 0x010, // media trailer + k_EAppType_DLC = 0x020, // down loadable content + k_EAppType_Guide = 0x040, // game guide, PDF etc + k_EAppType_Driver = 0x080, // hardware driver updater (ATI, Razor etc) + + k_EAppType_Shortcut = 0x40000000, // just a shortcut, client side only + k_EAppType_DepotOnly = 0x80000000, // placeholder since depots and apps share the same namespace +}; + + +//----------------------------------------------------------------------------- +// types of user game stats fields +// WARNING: DO NOT RENUMBER EXISTING VALUES - STORED IN DATABASE +//----------------------------------------------------------------------------- +enum ESteamUserStatType +{ + k_ESteamUserStatTypeINVALID = 0, + k_ESteamUserStatTypeINT = 1, + k_ESteamUserStatTypeFLOAT = 2, + // Read as FLOAT, set with count / session length + k_ESteamUserStatTypeAVGRATE = 3, + k_ESteamUserStatTypeACHIEVEMENTS = 4, + k_ESteamUserStatTypeGROUPACHIEVEMENTS = 5, + + // max, for sanity checks + k_ESteamUserStatTypeMAX +}; + + +//----------------------------------------------------------------------------- +// Purpose: Chat Entry Types (previously was only friend-to-friend message types) +//----------------------------------------------------------------------------- +enum EChatEntryType +{ + k_EChatEntryTypeInvalid = 0, + k_EChatEntryTypeChatMsg = 1, // Normal text message from another user + k_EChatEntryTypeTyping = 2, // Another user is typing (not used in multi-user chat) + k_EChatEntryTypeInviteGame = 3, // Invite from other user into that users current game + k_EChatEntryTypeEmote = 4, // text emote message (deprecated, should be treated as ChatMsg) + //k_EChatEntryTypeLobbyGameStart = 5, // lobby game is starting (dead - listen for LobbyGameCreated_t callback instead) + k_EChatEntryTypeLeftConversation = 6, // user has left the conversation ( closed chat window ) + // Above are previous FriendMsgType entries, now merged into more generic chat entry types + k_EChatEntryTypeEntered = 7, // user has entered the conversation (used in multi-user chat and group chat) + k_EChatEntryTypeWasKicked = 8, // user was kicked (data: 64-bit steamid of actor performing the kick) + k_EChatEntryTypeWasBanned = 9, // user was banned (data: 64-bit steamid of actor performing the ban) + k_EChatEntryTypeDisconnected = 10, // user disconnected + k_EChatEntryTypeHistoricalChat = 11, // a chat message from user's chat history or offilne message + +}; + + +//----------------------------------------------------------------------------- +// Purpose: Chat Room Enter Responses +//----------------------------------------------------------------------------- +enum EChatRoomEnterResponse +{ + k_EChatRoomEnterResponseSuccess = 1, // Success + k_EChatRoomEnterResponseDoesntExist = 2, // Chat doesn't exist (probably closed) + k_EChatRoomEnterResponseNotAllowed = 3, // General Denied - You don't have the permissions needed to join the chat + k_EChatRoomEnterResponseFull = 4, // Chat room has reached its maximum size + k_EChatRoomEnterResponseError = 5, // Unexpected Error + k_EChatRoomEnterResponseBanned = 6, // You are banned from this chat room and may not join + k_EChatRoomEnterResponseLimited = 7, // Joining this chat is not allowed because you are a limited user (no value on account) + k_EChatRoomEnterResponseClanDisabled = 8, // Attempt to join a clan chat when the clan is locked or disabled + k_EChatRoomEnterResponseCommunityBan = 9, // Attempt to join a chat when the user has a community lock on their account + k_EChatRoomEnterResponseMemberBlockedYou = 10, // Join failed - some member in the chat has blocked you from joining + k_EChatRoomEnterResponseYouBlockedMember = 11, // Join failed - you have blocked some member already in the chat + // k_EChatRoomEnterResponseNoRankingDataLobby = 12, // No longer used + // k_EChatRoomEnterResponseNoRankingDataUser = 13, // No longer used + // k_EChatRoomEnterResponseRankOutOfRange = 14, // No longer used +}; + + +//----------------------------------------------------------------------------- +// Purpose: Status of a given depot version, these are stored in the DB, don't renumber +//----------------------------------------------------------------------------- +enum EStatusDepotVersion +{ + k_EStatusDepotVersionInvalid = 0, + k_EStatusDepotVersionDisabled = 1, // version was disabled, no manifest & content available + k_EStatusDepotVersionAvailable = 2, // manifest & content is available, but not current + k_EStatusDepotVersionCurrent = 3, // current depot version. The can be multiple, one for public and one for each beta key +}; + + +typedef void (*PFNLegacyKeyRegistration)( const char *pchCDKey, const char *pchInstallPath ); +typedef bool (*PFNLegacyKeyInstalled)(); + +const unsigned int k_unSteamAccountIDMask = 0xFFFFFFFF; +const unsigned int k_unSteamAccountInstanceMask = 0x000FFFFF; +// we allow 3 simultaneous user account instances right now, 1= desktop, 2 = console, 4 = web, 0 = all +const unsigned int k_unSteamUserDesktopInstance = 1; +const unsigned int k_unSteamUserConsoleInstance = 2; +const unsigned int k_unSteamUserWebInstance = 4; + +// Special flags for Chat accounts - they go in the top 8 bits +// of the steam ID's "instance", leaving 12 for the actual instances +enum EChatSteamIDInstanceFlags +{ + k_EChatAccountInstanceMask = 0x00000FFF, // top 8 bits are flags + + k_EChatInstanceFlagClan = ( k_unSteamAccountInstanceMask + 1 ) >> 1, // top bit + k_EChatInstanceFlagLobby = ( k_unSteamAccountInstanceMask + 1 ) >> 2, // next one down, etc + k_EChatInstanceFlagMMSLobby = ( k_unSteamAccountInstanceMask + 1 ) >> 3, // next one down, etc + + // Max of 8 flags +}; + + +//----------------------------------------------------------------------------- +// Purpose: Marketing message flags that change how a client should handle them +//----------------------------------------------------------------------------- +enum EMarketingMessageFlags +{ + k_EMarketingMessageFlagsNone = 0, + k_EMarketingMessageFlagsHighPriority = 1 << 0, + k_EMarketingMessageFlagsPlatformWindows = 1 << 1, + k_EMarketingMessageFlagsPlatformMac = 1 << 2, + k_EMarketingMessageFlagsPlatformLinux = 1 << 3, + + //aggregate flags + k_EMarketingMessageFlagsPlatformRestrictions = + k_EMarketingMessageFlagsPlatformWindows | + k_EMarketingMessageFlagsPlatformMac | + k_EMarketingMessageFlagsPlatformLinux, +}; + + + +//----------------------------------------------------------------------------- +// Purpose: Possible positions to tell the overlay to show notifications in +//----------------------------------------------------------------------------- +enum ENotificationPosition +{ + k_EPositionTopLeft = 0, + k_EPositionTopRight = 1, + k_EPositionBottomLeft = 2, + k_EPositionBottomRight = 3, +}; + + +#pragma pack( push, 1 ) + +#define CSTEAMID_DEFINED + +// Steam ID structure (64 bits total) +class CSteamID +{ +public: + + //----------------------------------------------------------------------------- + // Purpose: Constructor + //----------------------------------------------------------------------------- + CSteamID() + { + m_steamid.m_comp.m_unAccountID = 0; + m_steamid.m_comp.m_EAccountType = k_EAccountTypeInvalid; + m_steamid.m_comp.m_EUniverse = k_EUniverseInvalid; + m_steamid.m_comp.m_unAccountInstance = 0; + } + + + //----------------------------------------------------------------------------- + // Purpose: Constructor + // Input : unAccountID - 32-bit account ID + // eUniverse - Universe this account belongs to + // eAccountType - Type of account + //----------------------------------------------------------------------------- + CSteamID( uint32 unAccountID, EUniverse eUniverse, EAccountType eAccountType ) + { + Set( unAccountID, eUniverse, eAccountType ); + } + + + //----------------------------------------------------------------------------- + // Purpose: Constructor + // Input : unAccountID - 32-bit account ID + // unAccountInstance - instance + // eUniverse - Universe this account belongs to + // eAccountType - Type of account + //----------------------------------------------------------------------------- + CSteamID( uint32 unAccountID, unsigned int unAccountInstance, EUniverse eUniverse, EAccountType eAccountType ) + { +#if defined(_SERVER) && defined(Assert) + Assert( ! ( ( k_EAccountTypeIndividual == eAccountType ) && ( unAccountInstance > k_unSteamUserWebInstance ) ) ); // enforce that for individual accounts, instance is always 1 +#endif // _SERVER + InstancedSet( unAccountID, unAccountInstance, eUniverse, eAccountType ); + } + + + //----------------------------------------------------------------------------- + // Purpose: Constructor + // Input : ulSteamID - 64-bit representation of a Steam ID + // Note: Will not accept a uint32 or int32 as input, as that is a probable mistake. + // See the stubbed out overloads in the private: section for more info. + //----------------------------------------------------------------------------- + CSteamID( uint64 ulSteamID ) + { + SetFromUint64( ulSteamID ); + } + + + //----------------------------------------------------------------------------- + // Purpose: Sets parameters for steam ID + // Input : unAccountID - 32-bit account ID + // eUniverse - Universe this account belongs to + // eAccountType - Type of account + //----------------------------------------------------------------------------- + void Set( uint32 unAccountID, EUniverse eUniverse, EAccountType eAccountType ) + { + m_steamid.m_comp.m_unAccountID = unAccountID; + m_steamid.m_comp.m_EUniverse = eUniverse; + m_steamid.m_comp.m_EAccountType = eAccountType; + + if ( eAccountType == k_EAccountTypeClan ) + { + m_steamid.m_comp.m_unAccountInstance = 0; + } + else + { + // by default we pick the desktop instance + m_steamid.m_comp.m_unAccountInstance = k_unSteamUserDesktopInstance; + } + } + + + //----------------------------------------------------------------------------- + // Purpose: Sets parameters for steam ID + // Input : unAccountID - 32-bit account ID + // eUniverse - Universe this account belongs to + // eAccountType - Type of account + //----------------------------------------------------------------------------- + void InstancedSet( uint32 unAccountID, uint32 unInstance, EUniverse eUniverse, EAccountType eAccountType ) + { + m_steamid.m_comp.m_unAccountID = unAccountID; + m_steamid.m_comp.m_EUniverse = eUniverse; + m_steamid.m_comp.m_EAccountType = eAccountType; + m_steamid.m_comp.m_unAccountInstance = unInstance; + } + + + //----------------------------------------------------------------------------- + // Purpose: Initializes a steam ID from its 52 bit parts and universe/type + // Input : ulIdentifier - 52 bits of goodness + //----------------------------------------------------------------------------- + void FullSet( uint64 ulIdentifier, EUniverse eUniverse, EAccountType eAccountType ) + { + m_steamid.m_comp.m_unAccountID = ( ulIdentifier & k_unSteamAccountIDMask ); // account ID is low 32 bits + m_steamid.m_comp.m_unAccountInstance = ( ( ulIdentifier >> 32 ) & k_unSteamAccountInstanceMask ); // account instance is next 20 bits + m_steamid.m_comp.m_EUniverse = eUniverse; + m_steamid.m_comp.m_EAccountType = eAccountType; + } + + + //----------------------------------------------------------------------------- + // Purpose: Initializes a steam ID from its 64-bit representation + // Input : ulSteamID - 64-bit representation of a Steam ID + //----------------------------------------------------------------------------- + void SetFromUint64( uint64 ulSteamID ) + { + m_steamid.m_unAll64Bits = ulSteamID; + } + + + //----------------------------------------------------------------------------- + // Purpose: Clear all fields, leaving an invalid ID. + //----------------------------------------------------------------------------- + void Clear() + { + m_steamid.m_comp.m_unAccountID = 0; + m_steamid.m_comp.m_EAccountType = k_EAccountTypeInvalid; + m_steamid.m_comp.m_EUniverse = k_EUniverseInvalid; + m_steamid.m_comp.m_unAccountInstance = 0; + } + + +#if defined( INCLUDED_STEAM_COMMON_STEAMCOMMON_H ) + //----------------------------------------------------------------------------- + // Purpose: Initializes a steam ID from a Steam2 ID structure + // Input: pTSteamGlobalUserID - Steam2 ID to convert + // eUniverse - universe this ID belongs to + //----------------------------------------------------------------------------- + void SetFromSteam2( TSteamGlobalUserID *pTSteamGlobalUserID, EUniverse eUniverse ) + { + m_steamid.m_comp.m_unAccountID = pTSteamGlobalUserID->m_SteamLocalUserID.Split.Low32bits * 2 + + pTSteamGlobalUserID->m_SteamLocalUserID.Split.High32bits; + m_steamid.m_comp.m_EUniverse = eUniverse; // set the universe + m_steamid.m_comp.m_EAccountType = k_EAccountTypeIndividual; // Steam 2 accounts always map to account type of individual + m_steamid.m_comp.m_unAccountInstance = k_unSteamUserDesktopInstance; // Steam2 only knew desktop instances + } + + //----------------------------------------------------------------------------- + // Purpose: Fills out a Steam2 ID structure + // Input: pTSteamGlobalUserID - Steam2 ID to write to + //----------------------------------------------------------------------------- + void ConvertToSteam2( TSteamGlobalUserID *pTSteamGlobalUserID ) const + { + // only individual accounts have any meaning in Steam 2, only they can be mapped + // Assert( m_steamid.m_comp.m_EAccountType == k_EAccountTypeIndividual ); + + pTSteamGlobalUserID->m_SteamInstanceID = 0; + pTSteamGlobalUserID->m_SteamLocalUserID.Split.High32bits = m_steamid.m_comp.m_unAccountID % 2; + pTSteamGlobalUserID->m_SteamLocalUserID.Split.Low32bits = m_steamid.m_comp.m_unAccountID / 2; + } +#endif // defined( INCLUDED_STEAM_COMMON_STEAMCOMMON_H ) + + //----------------------------------------------------------------------------- + // Purpose: Converts steam ID to its 64-bit representation + // Output : 64-bit representation of a Steam ID + //----------------------------------------------------------------------------- + uint64 ConvertToUint64() const + { + return m_steamid.m_unAll64Bits; + } + + + //----------------------------------------------------------------------------- + // Purpose: Converts the static parts of a steam ID to a 64-bit representation. + // For multiseat accounts, all instances of that account will have the + // same static account key, so they can be grouped together by the static + // account key. + // Output : 64-bit static account key + //----------------------------------------------------------------------------- + uint64 GetStaticAccountKey() const + { + // note we do NOT include the account instance (which is a dynamic property) in the static account key + return (uint64) ( ( ( (uint64) m_steamid.m_comp.m_EUniverse ) << 56 ) + ((uint64) m_steamid.m_comp.m_EAccountType << 52 ) + m_steamid.m_comp.m_unAccountID ); + } + + + //----------------------------------------------------------------------------- + // Purpose: create an anonymous game server login to be filled in by the AM + //----------------------------------------------------------------------------- + void CreateBlankAnonLogon( EUniverse eUniverse ) + { + m_steamid.m_comp.m_unAccountID = 0; + m_steamid.m_comp.m_EAccountType = k_EAccountTypeAnonGameServer; + m_steamid.m_comp.m_EUniverse = eUniverse; + m_steamid.m_comp.m_unAccountInstance = 0; + } + + + //----------------------------------------------------------------------------- + // Purpose: create an anonymous game server login to be filled in by the AM + //----------------------------------------------------------------------------- + void CreateBlankAnonUserLogon( EUniverse eUniverse ) + { + m_steamid.m_comp.m_unAccountID = 0; + m_steamid.m_comp.m_EAccountType = k_EAccountTypeAnonUser; + m_steamid.m_comp.m_EUniverse = eUniverse; + m_steamid.m_comp.m_unAccountInstance = 0; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this an anonymous game server login that will be filled in? + //----------------------------------------------------------------------------- + bool BBlankAnonAccount() const + { + return m_steamid.m_comp.m_unAccountID == 0 && BAnonAccount() && m_steamid.m_comp.m_unAccountInstance == 0; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this a game server account id? (Either persistent or anonymous) + //----------------------------------------------------------------------------- + bool BGameServerAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeGameServer || m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonGameServer; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this a persistent (not anonymous) game server account id? + //----------------------------------------------------------------------------- + bool BPersistentGameServerAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeGameServer; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this an anonymous game server account id? + //----------------------------------------------------------------------------- + bool BAnonGameServerAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonGameServer; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this a content server account id? + //----------------------------------------------------------------------------- + bool BContentServerAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeContentServer; + } + + + //----------------------------------------------------------------------------- + // Purpose: Is this a clan account id? + //----------------------------------------------------------------------------- + bool BClanAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeClan; + } + + + //----------------------------------------------------------------------------- + // Purpose: Is this a chat account id? + //----------------------------------------------------------------------------- + bool BChatAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeChat; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this a chat account id? + //----------------------------------------------------------------------------- + bool IsLobby() const + { + return ( m_steamid.m_comp.m_EAccountType == k_EAccountTypeChat ) + && ( m_steamid.m_comp.m_unAccountInstance & k_EChatInstanceFlagLobby ); + } + + + //----------------------------------------------------------------------------- + // Purpose: Is this an individual user account id? + //----------------------------------------------------------------------------- + bool BIndividualAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeIndividual || m_steamid.m_comp.m_EAccountType == k_EAccountTypeConsoleUser; + } + + + //----------------------------------------------------------------------------- + // Purpose: Is this an anonymous account? + //----------------------------------------------------------------------------- + bool BAnonAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonUser || m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonGameServer; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this an anonymous user account? ( used to create an account or reset a password ) + //----------------------------------------------------------------------------- + bool BAnonUserAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeAnonUser; + } + + //----------------------------------------------------------------------------- + // Purpose: Is this a faked up Steam ID for a PSN friend account? + //----------------------------------------------------------------------------- + bool BConsoleUserAccount() const + { + return m_steamid.m_comp.m_EAccountType == k_EAccountTypeConsoleUser; + } + + // simple accessors + void SetAccountID( uint32 unAccountID ) { m_steamid.m_comp.m_unAccountID = unAccountID; } + void SetAccountInstance( uint32 unInstance ){ m_steamid.m_comp.m_unAccountInstance = unInstance; } + void ClearIndividualInstance() { if ( BIndividualAccount() ) m_steamid.m_comp.m_unAccountInstance = 0; } + bool HasNoIndividualInstance() const { return BIndividualAccount() && (m_steamid.m_comp.m_unAccountInstance==0); } + AccountID_t GetAccountID() const { return m_steamid.m_comp.m_unAccountID; } + uint32 GetUnAccountInstance() const { return m_steamid.m_comp.m_unAccountInstance; } + EAccountType GetEAccountType() const { return ( EAccountType ) m_steamid.m_comp.m_EAccountType; } + EUniverse GetEUniverse() const { return m_steamid.m_comp.m_EUniverse; } + void SetEUniverse( EUniverse eUniverse ) { m_steamid.m_comp.m_EUniverse = eUniverse; } + bool IsValid() const; + + // this set of functions is hidden, will be moved out of class + explicit CSteamID( const char *pchSteamID, EUniverse eDefaultUniverse = k_EUniverseInvalid ); + const char * Render() const; // renders this steam ID to string + static const char * Render( uint64 ulSteamID ); // static method to render a uint64 representation of a steam ID to a string + + void SetFromString( const char *pchSteamID, EUniverse eDefaultUniverse ); + // SetFromString allows many partially-correct strings, constraining how + // we might be able to change things in the future. + // SetFromStringStrict requires the exact string forms that we support + // and is preferred when the caller knows it's safe to be strict. + // Returns whether the string parsed correctly. + bool SetFromStringStrict( const char *pchSteamID, EUniverse eDefaultUniverse ); + bool SetFromSteam2String( const char *pchSteam2ID, EUniverse eUniverse ); + + inline bool operator==( const CSteamID &val ) const { return m_steamid.m_unAll64Bits == val.m_steamid.m_unAll64Bits; } + inline bool operator!=( const CSteamID &val ) const { return !operator==( val ); } + inline bool operator<( const CSteamID &val ) const { return m_steamid.m_unAll64Bits < val.m_steamid.m_unAll64Bits; } + inline bool operator>( const CSteamID &val ) const { return m_steamid.m_unAll64Bits > val.m_steamid.m_unAll64Bits; } + + // DEBUG function + bool BValidExternalSteamID() const; + +private: + // These are defined here to prevent accidental implicit conversion of a u32AccountID to a CSteamID. + // If you get a compiler error about an ambiguous constructor/function then it may be because you're + // passing a 32-bit int to a function that takes a CSteamID. You should explicitly create the SteamID + // using the correct Universe and account Type/Instance values. + CSteamID( uint32 ); + CSteamID( int32 ); + + // 64 bits total + union SteamID_t + { + struct SteamIDComponent_t + { +#ifdef VALVE_BIG_ENDIAN + EUniverse m_EUniverse : 8; // universe this account belongs to + unsigned int m_EAccountType : 4; // type of account - can't show as EAccountType, due to signed / unsigned difference + unsigned int m_unAccountInstance : 20; // dynamic instance ID + uint32 m_unAccountID : 32; // unique account identifier +#else + uint32 m_unAccountID : 32; // unique account identifier + unsigned int m_unAccountInstance : 20; // dynamic instance ID + unsigned int m_EAccountType : 4; // type of account - can't show as EAccountType, due to signed / unsigned difference + EUniverse m_EUniverse : 8; // universe this account belongs to +#endif + } m_comp; + + uint64 m_unAll64Bits; + } m_steamid; +}; + +inline bool CSteamID::IsValid() const +{ + if ( m_steamid.m_comp.m_EAccountType <= k_EAccountTypeInvalid || m_steamid.m_comp.m_EAccountType >= k_EAccountTypeMax ) + return false; + + if ( m_steamid.m_comp.m_EUniverse <= k_EUniverseInvalid || m_steamid.m_comp.m_EUniverse >= k_EUniverseMax ) + return false; + + if ( m_steamid.m_comp.m_EAccountType == k_EAccountTypeIndividual ) + { + if ( m_steamid.m_comp.m_unAccountID == 0 || m_steamid.m_comp.m_unAccountInstance > k_unSteamUserWebInstance ) + return false; + } + + if ( m_steamid.m_comp.m_EAccountType == k_EAccountTypeClan ) + { + if ( m_steamid.m_comp.m_unAccountID == 0 || m_steamid.m_comp.m_unAccountInstance != 0 ) + return false; + } + + if ( m_steamid.m_comp.m_EAccountType == k_EAccountTypeGameServer ) + { + if ( m_steamid.m_comp.m_unAccountID == 0 ) + return false; + // Any limit on instances? We use them for local users and bots + } + return true; +} + +// generic invalid CSteamID +#define k_steamIDNil CSteamID() + +// This steamID comes from a user game connection to an out of date GS that hasnt implemented the protocol +// to provide its steamID +#define k_steamIDOutofDateGS CSteamID( 0, 0, k_EUniverseInvalid, k_EAccountTypeInvalid ) +// This steamID comes from a user game connection to an sv_lan GS +#define k_steamIDLanModeGS CSteamID( 0, 0, k_EUniversePublic, k_EAccountTypeInvalid ) +// This steamID can come from a user game connection to a GS that has just booted but hasnt yet even initialized +// its steam3 component and started logging on. +#define k_steamIDNotInitYetGS CSteamID( 1, 0, k_EUniverseInvalid, k_EAccountTypeInvalid ) +// This steamID can come from a user game connection to a GS that isn't using the steam authentication system but still +// wants to support the "Join Game" option in the friends list +#define k_steamIDNonSteamGS CSteamID( 2, 0, k_EUniverseInvalid, k_EAccountTypeInvalid ) + + +#ifdef STEAM +// Returns the matching chat steamID, with the default instance of 0 +// If the steamID passed in is already of type k_EAccountTypeChat it will be returned with the same instance +CSteamID ChatIDFromSteamID( const CSteamID &steamID ); +// Returns the matching clan steamID, with the default instance of 0 +// If the steamID passed in is already of type k_EAccountTypeClan it will be returned with the same instance +CSteamID ClanIDFromSteamID( const CSteamID &steamID ); +// Asserts steamID type before conversion +CSteamID ChatIDFromClanID( const CSteamID &steamIDClan ); +// Asserts steamID type before conversion +CSteamID ClanIDFromChatID( const CSteamID &steamIDChat ); + +#endif // _STEAM + + +//----------------------------------------------------------------------------- +// Purpose: encapsulates an appID/modID pair +//----------------------------------------------------------------------------- +class CGameID +{ +public: + + CGameID() + { + m_gameID.m_nType = k_EGameIDTypeApp; + m_gameID.m_nAppID = k_uAppIdInvalid; + m_gameID.m_nModID = 0; + } + + explicit CGameID( uint64 ulGameID ) + { + m_ulGameID = ulGameID; + } + + explicit CGameID( int32 nAppID ) + { + m_ulGameID = 0; + m_gameID.m_nAppID = nAppID; + } + + explicit CGameID( uint32 nAppID ) + { + m_ulGameID = 0; + m_gameID.m_nAppID = nAppID; + } + + CGameID( uint32 nAppID, uint32 nModID ) + { + m_ulGameID = 0; + m_gameID.m_nAppID = nAppID; + m_gameID.m_nModID = nModID; + m_gameID.m_nType = k_EGameIDTypeGameMod; + } + + // Hidden functions used only by Steam + explicit CGameID( const char *pchGameID ); + const char *Render() const; // render this Game ID to string + static const char *Render( uint64 ulGameID ); // static method to render a uint64 representation of a Game ID to a string + + // must include checksum_crc.h first to get this functionality +#if defined( CHECKSUM_CRC_H ) + CGameID( uint32 nAppID, const char *pchModPath ) + { + m_ulGameID = 0; + m_gameID.m_nAppID = nAppID; + m_gameID.m_nType = k_EGameIDTypeGameMod; + + char rgchModDir[MAX_PATH]; + Q_FileBase( pchModPath, rgchModDir, sizeof( rgchModDir ) ); + CRC32_t crc32; + CRC32_Init( &crc32 ); + CRC32_ProcessBuffer( &crc32, rgchModDir, Q_strlen( rgchModDir ) ); + CRC32_Final( &crc32 ); + + // set the high-bit on the mod-id + // reduces crc32 to 31bits, but lets us use the modID as a guaranteed unique + // replacement for appID's + m_gameID.m_nModID = crc32 | (0x80000000); + } + + CGameID( const char *pchExePath, const char *pchAppName ) + { + m_ulGameID = 0; + m_gameID.m_nAppID = k_uAppIdInvalid; + m_gameID.m_nType = k_EGameIDTypeShortcut; + + CRC32_t crc32; + CRC32_Init( &crc32 ); + CRC32_ProcessBuffer( &crc32, pchExePath, Q_strlen( pchExePath ) ); + CRC32_ProcessBuffer( &crc32, pchAppName, Q_strlen( pchAppName ) ); + CRC32_Final( &crc32 ); + + // set the high-bit on the mod-id + // reduces crc32 to 31bits, but lets us use the modID as a guaranteed unique + // replacement for appID's + m_gameID.m_nModID = crc32 | (0x80000000); + } + +#if defined( VSTFILEID_H ) + + CGameID( VstFileID vstFileID ) + { + m_ulGameID = 0; + m_gameID.m_nAppID = k_uAppIdInvalid; + m_gameID.m_nType = k_EGameIDTypeP2P; + + CRC32_t crc32; + CRC32_Init( &crc32 ); + const char *pchFileId = vstFileID.Render(); + CRC32_ProcessBuffer( &crc32, pchFileId, Q_strlen( pchFileId ) ); + CRC32_Final( &crc32 ); + + // set the high-bit on the mod-id + // reduces crc32 to 31bits, but lets us use the modID as a guaranteed unique + // replacement for appID's + m_gameID.m_nModID = crc32 | (0x80000000); + } + +#endif /* VSTFILEID_H */ + +#endif /* CHECKSUM_CRC_H */ + + + uint64 ToUint64() const + { + return m_ulGameID; + } + + uint64 *GetUint64Ptr() + { + return &m_ulGameID; + } + + void Set( uint64 ulGameID ) + { + m_ulGameID = ulGameID; + } + + bool IsMod() const + { + return ( m_gameID.m_nType == k_EGameIDTypeGameMod ); + } + + bool IsShortcut() const + { + return ( m_gameID.m_nType == k_EGameIDTypeShortcut ); + } + + bool IsP2PFile() const + { + return ( m_gameID.m_nType == k_EGameIDTypeP2P ); + } + + bool IsSteamApp() const + { + return ( m_gameID.m_nType == k_EGameIDTypeApp ); + } + + uint32 ModID() const + { + return m_gameID.m_nModID; + } + + uint32 AppID() const + { + return m_gameID.m_nAppID; + } + + bool operator == ( const CGameID &rhs ) const + { + return m_ulGameID == rhs.m_ulGameID; + } + + bool operator != ( const CGameID &rhs ) const + { + return !(*this == rhs); + } + + bool operator < ( const CGameID &rhs ) const + { + return ( m_ulGameID < rhs.m_ulGameID ); + } + + bool IsValid() const + { + // each type has it's own invalid fixed point: + switch( m_gameID.m_nType ) + { + case k_EGameIDTypeApp: + return m_gameID.m_nAppID != k_uAppIdInvalid; + + case k_EGameIDTypeGameMod: + return m_gameID.m_nAppID != k_uAppIdInvalid && m_gameID.m_nModID & 0x80000000; + + case k_EGameIDTypeShortcut: + return (m_gameID.m_nModID & 0x80000000) != 0; + + case k_EGameIDTypeP2P: + return m_gameID.m_nAppID == k_uAppIdInvalid && m_gameID.m_nModID & 0x80000000; + + default: +#if defined(Assert) + Assert(false); +#endif + return false; + } + + } + + void Reset() + { + m_ulGameID = 0; + } + + + +private: + + enum EGameIDType + { + k_EGameIDTypeApp = 0, + k_EGameIDTypeGameMod = 1, + k_EGameIDTypeShortcut = 2, + k_EGameIDTypeP2P = 3, + }; + + struct GameID_t + { +#ifdef VALVE_BIG_ENDIAN + unsigned int m_nModID : 32; + unsigned int m_nType : 8; + unsigned int m_nAppID : 24; +#else + unsigned int m_nAppID : 24; + unsigned int m_nType : 8; + unsigned int m_nModID : 32; +#endif + }; + + union + { + uint64 m_ulGameID; + GameID_t m_gameID; + }; +}; + +#pragma pack( pop ) + +const int k_cchGameExtraInfoMax = 64; + + +//----------------------------------------------------------------------------- +// Constants used for query ports. +//----------------------------------------------------------------------------- + +#define QUERY_PORT_NOT_INITIALIZED 0xFFFF // We haven't asked the GS for this query port's actual value yet. +#define QUERY_PORT_ERROR 0xFFFE // We were unable to get the query port for this server. + + +//----------------------------------------------------------------------------- +// Purpose: Passed as argument to SteamAPI_UseBreakpadCrashHandler to enable optional callback +// just before minidump file is captured after a crash has occurred. (Allows app to append additional comment data to the dump, etc.) +//----------------------------------------------------------------------------- +typedef void (*PFNPreMinidumpCallback)(void *context); + +//----------------------------------------------------------------------------- +// Purpose: Used by ICrashHandler interfaces to reference particular installed crash handlers +//----------------------------------------------------------------------------- +typedef void *BREAKPAD_HANDLE; +#define BREAKPAD_INVALID_HANDLE (BREAKPAD_HANDLE)0 + +#endif // STEAMCLIENTPUBLIC_H diff --git a/dep/rehlsdk/public/steam/steamhttpenums.h b/dep/rehlsdk/public/steam/steamhttpenums.h new file mode 100644 index 0000000..59782d5 --- /dev/null +++ b/dep/rehlsdk/public/steam/steamhttpenums.h @@ -0,0 +1,94 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: HTTP related enums, stuff that is shared by both clients and servers, and our +// UI projects goes here. +// +//============================================================================= + +#ifndef STEAMHTTPENUMS_H +#define STEAMHTTPENUMS_H +#ifdef _WIN32 +#pragma once +#endif + +// HTTP related types + +// This enum is used in client API methods, do not re-number existing values. +enum EHTTPMethod +{ + k_EHTTPMethodInvalid = 0, + k_EHTTPMethodGET, + k_EHTTPMethodHEAD, + k_EHTTPMethodPOST, + + // The remaining HTTP methods are not yet supported, per rfc2616 section 5.1.1 only GET and HEAD are required for + // a compliant general purpose server. We'll likely add more as we find uses for them. + + // k_EHTTPMethodOPTIONS, + k_EHTTPMethodPUT, + k_EHTTPMethodDELETE, + // k_EHTTPMethodTRACE, + // k_EHTTPMethodCONNECT +}; + + +// HTTP Status codes that the server can send in response to a request, see rfc2616 section 10.3 for descriptions +// of each of these. +enum EHTTPStatusCode +{ + // Invalid status code (this isn't defined in HTTP, used to indicate unset in our code) + k_EHTTPStatusCodeInvalid = 0, + + // Informational codes + k_EHTTPStatusCode100Continue = 100, + k_EHTTPStatusCode101SwitchingProtocols = 101, + + // Success codes + k_EHTTPStatusCode200OK = 200, + k_EHTTPStatusCode201Created = 201, + k_EHTTPStatusCode202Accepted = 202, + k_EHTTPStatusCode203NonAuthoritative = 203, + k_EHTTPStatusCode204NoContent = 204, + k_EHTTPStatusCode205ResetContent = 205, + k_EHTTPStatusCode206PartialContent = 206, + + // Redirection codes + k_EHTTPStatusCode300MultipleChoices = 300, + k_EHTTPStatusCode301MovedPermanently = 301, + k_EHTTPStatusCode302Found = 302, + k_EHTTPStatusCode303SeeOther = 303, + k_EHTTPStatusCode304NotModified = 304, + k_EHTTPStatusCode305UseProxy = 305, + //k_EHTTPStatusCode306Unused = 306, (used in old HTTP spec, now unused in 1.1) + k_EHTTPStatusCode307TemporaryRedirect = 307, + + // Error codes + k_EHTTPStatusCode400BadRequest = 400, + k_EHTTPStatusCode401Unauthorized = 401, + k_EHTTPStatusCode402PaymentRequired = 402, // This is reserved for future HTTP specs, not really supported by clients + k_EHTTPStatusCode403Forbidden = 403, + k_EHTTPStatusCode404NotFound = 404, + k_EHTTPStatusCode405MethodNotAllowed = 405, + k_EHTTPStatusCode406NotAcceptable = 406, + k_EHTTPStatusCode407ProxyAuthRequired = 407, + k_EHTTPStatusCode408RequestTimeout = 408, + k_EHTTPStatusCode409Conflict = 409, + k_EHTTPStatusCode410Gone = 410, + k_EHTTPStatusCode411LengthRequired = 411, + k_EHTTPStatusCode412PreconditionFailed = 412, + k_EHTTPStatusCode413RequestEntityTooLarge = 413, + k_EHTTPStatusCode414RequestURITooLong = 414, + k_EHTTPStatusCode415UnsupportedMediaType = 415, + k_EHTTPStatusCode416RequestedRangeNotSatisfiable = 416, + k_EHTTPStatusCode417ExpectationFailed = 417, + + // Server error codes + k_EHTTPStatusCode500InternalServerError = 500, + k_EHTTPStatusCode501NotImplemented = 501, + k_EHTTPStatusCode502BadGateway = 502, + k_EHTTPStatusCode503ServiceUnavailable = 503, + k_EHTTPStatusCode504GatewayTimeout = 504, + k_EHTTPStatusCode505HTTPVersionNotSupported = 505, +}; + +#endif // STEAMHTTPENUMS_H diff --git a/dep/rehlsdk/public/steam/steamtypes.h b/dep/rehlsdk/public/steam/steamtypes.h new file mode 100644 index 0000000..57ffc93 --- /dev/null +++ b/dep/rehlsdk/public/steam/steamtypes.h @@ -0,0 +1,120 @@ +//========= Copyright Valve Corporation, All rights reserved. ============// +// +// Purpose: +// +//============================================================================= + +#ifndef STEAMTYPES_H +#define STEAMTYPES_H +#ifdef _WIN32 +#pragma once +#endif + +// Steam-specific types. Defined here so this header file can be included in other code bases. +#ifndef WCHARTYPES_H +typedef unsigned char uint8; +#endif + +#if defined( __GNUC__ ) && !defined(POSIX) + #if __GNUC__ < 4 + #error "Steamworks requires GCC 4.X (4.2 or 4.4 have been tested)" + #endif + #define POSIX 1 +#endif + +#if defined(__x86_64__) || defined(_WIN64) +#define X64BITS +#endif + +// Make sure VALVE_BIG_ENDIAN gets set on PS3, may already be set previously in Valve internal code. +#if !defined(VALVE_BIG_ENDIAN) && defined(_PS3) +#define VALVE_BIG_ENDIAN +#endif + +#if defined( _WIN32 ) + +#ifdef X64BITS +typedef __int64 intp; // intp is an integer that can accomodate a pointer +typedef unsigned __int64 uintp; // (ie, sizeof(intp) >= sizeof(int) && sizeof(intp) >= sizeof(void *) +#else +typedef __int32 intp; +typedef unsigned __int32 uintp; +#endif + +#else // _WIN32 + +#ifdef X64BITS +typedef long long intp; +typedef unsigned long long uintp; +#else +typedef int intp; +typedef unsigned int uintp; +#endif + +#endif // else _WIN32 + +const int k_cubSaltSize = 8; +typedef uint8 Salt_t[ k_cubSaltSize ]; + +//----------------------------------------------------------------------------- +// GID (GlobalID) stuff +// This is a globally unique identifier. It's guaranteed to be unique across all +// racks and servers for as long as a given universe persists. +//----------------------------------------------------------------------------- +// NOTE: for GID parsing/rendering and other utils, see gid.h +typedef uint64 GID_t; + +const GID_t k_GIDNil = 0xffffffffffffffffull; + +// For convenience, we define a number of types that are just new names for GIDs +typedef GID_t JobID_t; // Each Job has a unique ID +typedef GID_t TxnID_t; // Each financial transaction has a unique ID + +const GID_t k_TxnIDNil = k_GIDNil; +const GID_t k_TxnIDUnknown = 0; + + +// this is baked into client messages and interfaces as an int, +// make sure we never break this. +typedef uint32 PackageId_t; +const PackageId_t k_uPackageIdFreeSub = 0x0; +const PackageId_t k_uPackageIdInvalid = 0xFFFFFFFF; + + +// this is baked into client messages and interfaces as an int, +// make sure we never break this. +typedef uint32 AppId_t; +const AppId_t k_uAppIdInvalid = 0x0; + +typedef uint64 AssetClassId_t; +const AssetClassId_t k_ulAssetClassIdInvalid = 0x0; + +typedef uint32 PhysicalItemId_t; +const PhysicalItemId_t k_uPhysicalItemIdInvalid = 0x0; + + +// this is baked into client messages and interfaces as an int, +// make sure we never break this. AppIds and DepotIDs also presently +// share the same namespace, but since we'd like to change that in the future +// I've defined it seperately here. +typedef uint32 DepotId_t; +const DepotId_t k_uDepotIdInvalid = 0x0; + +// RTime32 +// We use this 32 bit time representing real world time. +// It offers 1 second resolution beginning on January 1, 1970 (Unix time) +typedef uint32 RTime32; + +typedef uint32 CellID_t; +const CellID_t k_uCellIDInvalid = 0xFFFFFFFF; + +// handle to a Steam API call +typedef uint64 SteamAPICall_t; +const SteamAPICall_t k_uAPICallInvalid = 0x0; + +typedef uint32 AccountID_t; + +typedef uint32 PartnerId_t; +const PartnerId_t k_uPartnerIdInvalid = 0; + +#endif // STEAMTYPES_H diff --git a/dep/rehlsdk/public/steamid.cpp b/dep/rehlsdk/public/steamid.cpp new file mode 100644 index 0000000..db24cea --- /dev/null +++ b/dep/rehlsdk/public/steamid.cpp @@ -0,0 +1,32 @@ +#include "precompiled.h" + +bool CSteamID::SetFromSteam2String(const char *pchSteam2ID, EUniverse eUniverse) +{ + Assert(pchSteam2ID); + + // Convert the Steam2 ID string to a Steam2 ID structure + TSteamGlobalUserID steam2ID; + steam2ID.m_SteamInstanceID = 0; + steam2ID.m_SteamLocalUserID.Split.High32bits = 0; + steam2ID.m_SteamLocalUserID.Split.Low32bits = 0; + + const char *pchTSteam2ID = pchSteam2ID; + + // Customer support is fond of entering steam IDs in the following form: STEAM_n:x:y + char *pchOptionalLeadString = "STEAM_"; + if (Q_strnicmp(pchSteam2ID, pchOptionalLeadString, Q_strlen(pchOptionalLeadString)) == 0) + pchTSteam2ID = pchSteam2ID + Q_strlen(pchOptionalLeadString); + + char cExtraCharCheck = 0; + + int cFieldConverted = sscanf(pchTSteam2ID, "%hu:%u:%u%c", &steam2ID.m_SteamInstanceID, + &steam2ID.m_SteamLocalUserID.Split.High32bits, &steam2ID.m_SteamLocalUserID.Split.Low32bits, &cExtraCharCheck); + + // Validate the conversion ... a special case is steam2 instance ID 1 which is reserved for special DoD handling + if (cExtraCharCheck != 0 || cFieldConverted == EOF || cFieldConverted < 2 || (cFieldConverted < 3 && steam2ID.m_SteamInstanceID != 1)) + return false; + + // Now convert to steam ID from the Steam2 ID structure + SetFromSteam2(&steam2ID, eUniverse); + return true; +} diff --git a/dep/rehlsdk/public/strtools.h b/dep/rehlsdk/public/strtools.h new file mode 100644 index 0000000..5cdf8c4 --- /dev/null +++ b/dep/rehlsdk/public/strtools.h @@ -0,0 +1,212 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#ifdef _WIN32 +const char CORRECT_PATH_SEPARATOR = '\\'; +const char INCORRECT_PATH_SEPARATOR = '/'; +#else +const char CORRECT_PATH_SEPARATOR = '/'; +const char INCORRECT_PATH_SEPARATOR = '\\'; +#endif + +#if !defined(_WIN32) +inline char *_strupr(char *start) +{ + char *str = start; + while (str && *str) + { + *str = (char)toupper(*str); + str++; + } + + return start; +} + +inline char *_strlwr(char *start) +{ + char *str = start; + while (str && *str) + { + *str = (char)tolower(*str); + str++; + } + + return start; +} +#endif + +#if defined(ASMLIB_H) && defined(HAVE_OPT_STRTOOLS) + #define Q_memset A_memset + #define Q_memcpy A_memcpy + #define Q_memcmp A_memcmp + #define Q_memmove A_memmove + #define Q_strlen A_strlen + #define Q_strcpy A_strcpy + #define Q_strncpy strncpy + #define Q_strcat A_strcat + #define Q_strncat strncat + #define Q_strcmp A_strcmp + #define Q_strncmp strncmp + #define Q_strdup _strdup + #define Q_stricmp A_stricmp + #define Q_strnicmp _strnicmp + #define Q_strstr A_strstr + #define Q_strchr strchr + #define Q_strrchr strrchr + #define Q_strtok strtok + #define Q_strlwr A_strtolower + #define Q_strupr A_strtoupper + #define Q_sprintf sprintf + #define Q_snprintf _snprintf + #define Q_vsnprintf _vsnprintf + #define Q_vsnwprintf _vsnwprintf + #define Q_atoi atoi + #define Q_atof atof + #define Q_sqrt M_sqrt + #define Q_min M_min + #define Q_max M_max + #define Q_clamp M_clamp + #define Q_abs abs + #define Q_fabs fabs + #define Q_tan tan + #define Q_atan atan + #define Q_atan2 atan2 + #define Q_acos acos + #define Q_cos cos + #define Q_sin sin + #define Q_pow pow + #define Q_fmod fmod +#else + #define Q_memset memset + #define Q_memcpy memcpy + #define Q_memcmp memcmp + #define Q_memmove memmove + #define Q_strlen strlen + #define Q_strcpy strcpy + #define Q_strncpy strncpy + #define Q_strcat strcat + #define Q_strncat strncat + #define Q_strcmp strcmp + #define Q_strncmp strncmp + #define Q_strdup _strdup + #define Q_stricmp _stricmp + #define Q_strnicmp _strnicmp + #define Q_strstr strstr + #define Q_strchr strchr + #define Q_strrchr strrchr + #define Q_strtok strtok + #define Q_strlwr _strlwr + #define Q_strupr _strupr + #define Q_sprintf sprintf + #define Q_snprintf _snprintf + #define Q_vsnprintf _vsnprintf + #define Q_vsnwprintf _vsnwprintf + #define Q_atoi atoi + #define Q_atof atof + #define Q_sqrt sqrt + #define Q_min min + #define Q_max max + #define Q_clamp clamp + #define Q_abs abs + #define Q_fabs fabs + #define Q_tan tan + #define Q_atan atan + #define Q_atan2 atan2 + #define Q_acos acos + #define Q_cos cos + #define Q_sin sin + #define Q_pow pow + #define Q_fmod fmod +#endif // #if defined(ASMLIB_H) && defined(HAVE_OPT_STRTOOLS) + +// size - sizeof(buffer) +inline char *Q_strlcpy(char *dest, const char *src, size_t size) { + Q_strncpy(dest, src, size - 1); + dest[size - 1] = '\0'; + return dest; +} + +// a safe variant of strcpy that truncates the result to fit in the destination buffer +template +char *Q_strlcpy(char (&dest)[size], const char *src) { + return Q_strlcpy(dest, src, size); +} + +// safely concatenate two strings. +// a variant of strcat that truncates the result to fit in the destination buffer +template +size_t Q_strlcat(char (&dest)[size], const char *src) +{ + size_t srclen; // Length of source string + size_t dstlen; // Length of destination string + + // Figure out how much room is left + dstlen = Q_strlen(dest); + size_t length = size - dstlen + 1; + + if (!length) { + // No room, return immediately + return dstlen; + } + + // Figure out how much room is needed + srclen = Q_strlen(src); + + // Copy the appropriate amount + if (srclen > length) { + srclen = length; + } + + Q_memcpy(dest + dstlen, src, srclen); + dest[dstlen + srclen] = '\0'; + + return dstlen + srclen; +} + +// Force slashes of either type to be = separator character +inline void Q_FixSlashes(char *pname, char separator = CORRECT_PATH_SEPARATOR) +{ + while (*pname) + { + if (*pname == INCORRECT_PATH_SEPARATOR || *pname == CORRECT_PATH_SEPARATOR) + { + *pname = separator; + } + + pname++; + } +} + +// strcpy that works correctly with overlapping src and dst buffers +inline char *Q_strcpy_s(char *dst, char *src) { + int len = Q_strlen(src); + Q_memmove(dst, src, len + 1); + return dst; +} diff --git a/dep/rehlsdk/public/utlbuffer.cpp b/dep/rehlsdk/public/utlbuffer.cpp new file mode 100644 index 0000000..53ad7f4 --- /dev/null +++ b/dep/rehlsdk/public/utlbuffer.cpp @@ -0,0 +1,419 @@ +//========= Copyright © 1996-2001, Valve LLC, All rights reserved. ============ +// +// The copyright to the contents herein is the property of Valve, L.L.C. +// The contents may be used and/or copied only with the written permission of +// Valve, L.L.C., or in accordance with the terms and conditions stipulated in +// the agreement/contract under which the contents have been supplied. +// +// $Header: $ +// $NoKeywords: $ +// +// Serialization buffer +//============================================================================= + +#include "precompiled.h" + +//----------------------------------------------------------------------------- +// constructors +//----------------------------------------------------------------------------- +CUtlBuffer::CUtlBuffer(int growSize, int initSize, bool text) : +m_Memory(growSize, initSize), m_Error(0) +{ + m_Get = 0; + m_Put = 0; + m_Flags = 0; + if (text) + { + m_Flags |= TEXT_BUFFER; + } +} + +CUtlBuffer::CUtlBuffer(void const* pBuffer, int size, bool text) : +m_Memory((unsigned char*)pBuffer, size), m_Error(0) +{ + m_Get = 0; + m_Put = 0; + m_Flags = 0; + if (text) + m_Flags |= TEXT_BUFFER; +} + + +//----------------------------------------------------------------------------- +// Attaches the buffer to external memory.... +//----------------------------------------------------------------------------- +void CUtlBuffer::SetExternalBuffer(void* pMemory, int numElements, bool text) +{ + m_Memory.SetExternalBuffer((unsigned char*)pMemory, numElements); + + // Reset all indices; we just changed memory + m_Get = 0; + m_Put = 0; + m_Flags = 0; + if (text) + m_Flags |= TEXT_BUFFER; +} + + +//----------------------------------------------------------------------------- +// Makes sure we've got at least this much memory +//----------------------------------------------------------------------------- +void CUtlBuffer::EnsureCapacity(int num) +{ + m_Memory.EnsureCapacity(num); +} + + +//----------------------------------------------------------------------------- +// Base get method from which all others derive +//----------------------------------------------------------------------------- +void CUtlBuffer::Get(void* pMem, int size) +{ + Assert(m_Get + size <= m_Memory.NumAllocated()); + memcpy(pMem, &m_Memory[m_Get], size); + m_Get += size; +} + + +//----------------------------------------------------------------------------- +// Eats whitespace +//----------------------------------------------------------------------------- +void CUtlBuffer::EatWhiteSpace() +{ + if (IsText() && IsValid()) + { + int lastpos = Size(); + while (m_Get < lastpos) + { + if (!isspace(*(char*)&m_Memory[m_Get])) + break; + m_Get += sizeof(char); + } + } +} + + +//----------------------------------------------------------------------------- +// Reads a null-terminated string +//----------------------------------------------------------------------------- +void CUtlBuffer::GetString(char* pString, int nMaxLen) +{ + if (!IsValid()) + { + *pString = 0; + return; + } + + if (nMaxLen == 0) + { + nMaxLen = INT_MAX; + } + + if (!IsText()) + { + int len = strlen((char*)&m_Memory[m_Get]) + 1; + if (len <= nMaxLen) + { + Get(pString, len); + } + else + { + Get(pString, nMaxLen); + pString[nMaxLen - 1] = 0; + SeekGet(SEEK_CURRENT, len - nMaxLen); + } + } + else + { + // eat all whitespace + EatWhiteSpace(); + + // Eat characters + int nCount = 0; + int nLastPos = Size(); + while (m_Get < nLastPos) + { + char c = *(char*)&m_Memory[m_Get]; + if (isspace(c) || (!c)) + break; + + if (nCount < nMaxLen - 1) + { + *pString++ = c; + } + ++nCount; + ++m_Get; + } + + // Terminate + *pString = 0; + } +} + + +//----------------------------------------------------------------------------- +// Checks if a get is ok +//----------------------------------------------------------------------------- +bool CUtlBuffer::CheckGet(int size) +{ + if (m_Error) + return false; + + if (m_Memory.NumAllocated() >= m_Get + size) + return true; + + m_Error |= GET_OVERFLOW; + return false; +} + + +//----------------------------------------------------------------------------- +// Change where I'm reading +//----------------------------------------------------------------------------- +void CUtlBuffer::SeekGet(SeekType_t type, int offset) +{ + switch (type) + { + case SEEK_HEAD: + m_Get = offset; + break; + + case SEEK_CURRENT: + m_Get += offset; + break; + + case SEEK_TAIL: + m_Get = m_Memory.NumAllocated() - offset; + break; + } +} + + +//----------------------------------------------------------------------------- +// Parse... +//----------------------------------------------------------------------------- + +#pragma warning ( disable : 4706 ) + +int CUtlBuffer::VaScanf(char const* pFmt, va_list list) +{ + Assert(pFmt); + if (m_Error || !IsText()) + return 0; + + int numScanned = 0; + + char c; + char* pEnd; + while (c = *pFmt++) + { + // Stop if we hit the end of the buffer + if (m_Get >= Size()) + { + m_Error |= GET_OVERFLOW; + break; + } + + switch (c) + { + case ' ': + // eat all whitespace + EatWhiteSpace(); + break; + + case '%': + { + // Conversion character... try to convert baby! + char type = *pFmt++; + if (type == 0) + return numScanned; + + switch (type) + { + case 'c': + { + char* ch = va_arg(list, char *); + *ch = (char)m_Memory[m_Get]; + ++m_Get; + } + break; + + case 'i': + case 'd': + { + int* i = va_arg(list, int *); + *i = strtol((char*)PeekGet(), &pEnd, 10); + if (pEnd == PeekGet()) + return numScanned; + m_Get = (int)pEnd - (int)Base(); + } + break; + + case 'x': + { + int* i = va_arg(list, int *); + *i = strtol((char*)PeekGet(), &pEnd, 16); + if (pEnd == PeekGet()) + return numScanned; + m_Get = (int)pEnd - (int)Base(); + } + break; + + case 'u': + { + unsigned int* u = va_arg(list, unsigned int *); + *u = strtoul((char*)PeekGet(), &pEnd, 10); + if (pEnd == PeekGet()) + return numScanned; + m_Get = (int)pEnd - (int)Base(); + } + break; + + case 'f': + { + float* f = va_arg(list, float *); + *f = (float)strtod((char*)PeekGet(), &pEnd); + if (pEnd == PeekGet()) + return numScanned; + m_Get = (int)pEnd - (int)Base(); + } + break; + + case 's': + { + char* s = va_arg(list, char *); + GetString(s); + } + break; + + default: + { + // unimplemented scanf type + Assert(0); + return numScanned; + } + break; + } + + ++numScanned; + } + break; + + default: + { + // Here we have to match the format string character + // against what's in the buffer or we're done. + if (c != m_Memory[m_Get]) + return numScanned; + ++m_Get; + } + } + } + return numScanned; +} + +#pragma warning ( default : 4706 ) + +int CUtlBuffer::Scanf(char const* pFmt, ...) +{ + va_list args; + + va_start(args, pFmt); + int count = VaScanf(pFmt, args); + va_end(args); + + return count; +} + + +//----------------------------------------------------------------------------- +// Serialization +//----------------------------------------------------------------------------- + +void CUtlBuffer::Put(void const* pMem, int size) +{ + if (CheckPut(size)) + { + memcpy(&m_Memory[m_Put], pMem, size); + m_Put += size; + } +} + + +//----------------------------------------------------------------------------- +// Writes a null-terminated string +//----------------------------------------------------------------------------- + +void CUtlBuffer::PutString(char const* pString) +{ + int len = strlen(pString); + + // Not text? append a null at the end. + if (!IsText()) + ++len; + + Put(pString, len); +} + +void CUtlBuffer::VaPrintf(char const* pFmt, va_list list) +{ + char temp[2048]; + int len = vsprintf(temp, pFmt, list); + Assert(len < 2048); + + // Not text? append a null at the end. + if (!IsText()) + ++len; + + Put(temp, len); +} + +void CUtlBuffer::Printf(char const* pFmt, ...) +{ + va_list args; + + va_start(args, pFmt); + VaPrintf(pFmt, args); + va_end(args); +} + + +//----------------------------------------------------------------------------- +// Checks if a put is ok +//----------------------------------------------------------------------------- + +bool CUtlBuffer::CheckPut(int size) +{ + if (m_Error) + return false; + + while (m_Memory.NumAllocated() < m_Put + size) + { + if (m_Memory.IsExternallyAllocated()) + { + m_Error |= PUT_OVERFLOW; + return false; + } + + m_Memory.Grow(); + } + return true; +} + +void CUtlBuffer::SeekPut(SeekType_t type, int offset) +{ + switch (type) + { + case SEEK_HEAD: + m_Put = offset; + break; + + case SEEK_CURRENT: + m_Put += offset; + break; + + case SEEK_TAIL: + m_Put = m_Memory.NumAllocated() - offset; + break; + } +} diff --git a/dep/rehlsdk/public/utlbuffer.h b/dep/rehlsdk/public/utlbuffer.h new file mode 100644 index 0000000..2351249 --- /dev/null +++ b/dep/rehlsdk/public/utlbuffer.h @@ -0,0 +1,341 @@ +//========= Copyright © 1996-2001, Valve LLC, All rights reserved. ============ +// +// The copyright to the contents herein is the property of Valve, L.L.C. +// The contents may be used and/or copied only with the written permission of +// Valve, L.L.C., or in accordance with the terms and conditions stipulated in +// the agreement/contract under which the contents have been supplied. +// +// $Header: $ +// $NoKeywords: $ +// +// Serialization/unserialization buffer +//============================================================================= + +#ifndef UTLBUFFER_H +#define UTLBUFFER_H + +#include "osconfig.h" +#include "utlmemory.h" +#include + +//----------------------------------------------------------------------------- +// Command parsing.. +//----------------------------------------------------------------------------- + +class CUtlBuffer +{ +public: + enum SeekType_t + { + SEEK_HEAD = 0, + SEEK_CURRENT, + SEEK_TAIL + }; + + CUtlBuffer(int growSize = 0, int initSize = 0, bool text = false); + CUtlBuffer(void const* pBuffer, int size, bool text = false); + + // Makes sure we've got at least this much memory + void EnsureCapacity(int num); + + // Attaches the buffer to external memory.... + void SetExternalBuffer(void* pMemory, int numElements, bool text = false); + + // Read stuff out. + // Binary mode: it'll just read the bits directly in, and characters will be + // read for strings until a null character is reached. + // Text mode: it'll parse the file, turning text #s into real numbers. + // GetString will read a string until a space is reaced + char GetChar(); + unsigned char GetUnsignedChar(); + short GetShort(); + unsigned short GetUnsignedShort(); + int GetInt(); + int GetIntHex(); + unsigned int GetUnsignedInt(); + float GetFloat(); + double GetDouble(); + void GetString(char* pString, int nMaxLen = 0); + void Get(void* pMem, int size); + + // Just like scanf, but doesn't work in binary mode + int Scanf(char const* pFmt, ...); + int VaScanf(char const* pFmt, va_list list); + + // Eats white space, advances Get index + void EatWhiteSpace(); + + // Write stuff in + // Binary mode: it'll just write the bits directly in, and strings will be + // written with a null terminating character + // Text mode: it'll convert the numbers to text versions + // PutString will not write a terminating character + void PutChar(char c); + void PutUnsignedChar(unsigned char uc); + void PutShort(short s); + void PutUnsignedShort(unsigned short us); + void PutInt(int i); + void PutUnsignedInt(unsigned int u); + void PutFloat(float f); + void PutDouble(double d); + void PutString(char const* pString); + void Put(void const* pMem, int size); + + // Just like printf, writes a terminating zero in binary mode + void Printf(char const* pFmt, ...); + void VaPrintf(char const* pFmt, va_list list); + + // What am I writing (put)/reading (get)? + void* PeekPut(int offset = 0); + void const* PeekGet(int offset = 0) const; + + // Where am I writing (put)/reading (get)? + int TellPut() const; + int TellGet() const; + + // Change where I'm writing (put)/reading (get) + void SeekPut(SeekType_t type, int offset); + void SeekGet(SeekType_t type, int offset); + + // Buffer base + void const* Base() const; + void* Base(); + + // memory allocation size, does *not* reflect size written or read, + // use TellPut or TellGet for that + int Size() const; + + // Am I a text buffer? + inline bool IsText() const { return (m_Flags & TEXT_BUFFER) != 0; } + + // Am I valid? (overflow or underflow error), Once invalid it stays invalid + inline bool IsValid() const { return m_Error == 0; } + +private: + // error flags + enum + { + PUT_OVERFLOW = 0x1, + GET_OVERFLOW = 0x2, + }; + + // flags + enum + { + TEXT_BUFFER = 0x1, + }; + + // Checks if a get/put is ok + bool CheckPut(int size); + bool CheckGet(int size); + + CUtlMemory m_Memory; + int m_Get; + int m_Put; + unsigned char m_Error; + unsigned char m_Flags; +}; + + +//----------------------------------------------------------------------------- +// Where am I reading? +//----------------------------------------------------------------------------- + +inline int CUtlBuffer::TellGet() const +{ + return m_Get; +} + + +//----------------------------------------------------------------------------- +// What am I reading? +//----------------------------------------------------------------------------- +inline void const* CUtlBuffer::PeekGet(int offset) const +{ + return &m_Memory[m_Get + offset]; +} + + +//----------------------------------------------------------------------------- +// Unserialization +//----------------------------------------------------------------------------- +#define GET_TYPE( _type, _val, _fmt ) \ + if (!IsText()) \ + { \ + if (CheckGet( sizeof(_type) )) \ + { \ + _val = *(_type *)PeekGet(); \ + m_Get += sizeof(_type); \ + } \ + else \ + { \ + _val = 0; \ + } \ + } \ + else \ + { \ + _val = 0; \ + Scanf( _fmt, &_val ); \ + } + +inline char CUtlBuffer::GetChar() +{ + char c; + GET_TYPE(char, c, "%c"); + return c; +} + +inline unsigned char CUtlBuffer::GetUnsignedChar() +{ + unsigned char c; + GET_TYPE(unsigned char, c, "%u"); + return c; +} + +inline short CUtlBuffer::GetShort() +{ + short s; + GET_TYPE(short, s, "%d"); + return s; +} + +inline unsigned short CUtlBuffer::GetUnsignedShort() +{ + unsigned short s; + GET_TYPE(unsigned short, s, "%u"); + return s; +} + +inline int CUtlBuffer::GetInt() +{ + int i; + GET_TYPE(int, i, "%d"); + return i; +} + +inline int CUtlBuffer::GetIntHex() +{ + int i; + GET_TYPE(int, i, "%x"); + return i; +} + +inline unsigned int CUtlBuffer::GetUnsignedInt() +{ + unsigned int u; + GET_TYPE(unsigned int, u, "%u"); + return u; +} + +inline float CUtlBuffer::GetFloat() +{ + float f; + GET_TYPE(float, f, "%f"); + return f; +} + +inline double CUtlBuffer::GetDouble() +{ + double d; + GET_TYPE(double, d, "%f"); + return d; +} + + +//----------------------------------------------------------------------------- +// Where am I writing? +//----------------------------------------------------------------------------- +inline int CUtlBuffer::TellPut() const +{ + return m_Put; +} + + +//----------------------------------------------------------------------------- +// What am I reading? +//----------------------------------------------------------------------------- +inline void* CUtlBuffer::PeekPut(int offset) +{ + return &m_Memory[m_Put + offset]; +} + + +//----------------------------------------------------------------------------- +// Various put methods +//----------------------------------------------------------------------------- +#define PUT_TYPE( _type, _val, _fmt ) \ + if (!IsText()) \ + { \ + if (CheckPut( sizeof(_type) )) \ + { \ + *(_type *)PeekPut() = _val; \ + m_Put += sizeof(_type); \ + } \ + } \ + else \ + { \ + Printf( _fmt, _val ); \ + } + + +inline void CUtlBuffer::PutChar(char c) +{ + PUT_TYPE(char, c, "%c"); +} + +inline void CUtlBuffer::PutUnsignedChar(unsigned char c) +{ + PUT_TYPE(unsigned char, c, "%u"); +} + +inline void CUtlBuffer::PutShort(short s) +{ + PUT_TYPE(short, s, "%d"); +} + +inline void CUtlBuffer::PutUnsignedShort(unsigned short s) +{ + PUT_TYPE(unsigned short, s, "%u"); +} + +inline void CUtlBuffer::PutInt(int i) +{ + PUT_TYPE(int, i, "%d"); +} + +inline void CUtlBuffer::PutUnsignedInt(unsigned int u) +{ + PUT_TYPE(unsigned int, u, "%u"); +} + +inline void CUtlBuffer::PutFloat(float f) +{ + PUT_TYPE(float, f, "%f"); +} + +inline void CUtlBuffer::PutDouble(double d) +{ + PUT_TYPE(double, d, "%f"); +} + +//----------------------------------------------------------------------------- +// Buffer base and size +//----------------------------------------------------------------------------- + +inline void const* CUtlBuffer::Base() const +{ + return m_Memory.Base(); +} + +inline void* CUtlBuffer::Base() +{ + return m_Memory.Base(); +} + +inline int CUtlBuffer::Size() const +{ + return m_Memory.NumAllocated(); +} + + +#endif // UTLBUFFER_H diff --git a/dep/rehlsdk/public/utllinkedlist.h b/dep/rehlsdk/public/utllinkedlist.h new file mode 100644 index 0000000..5dbf1fc --- /dev/null +++ b/dep/rehlsdk/public/utllinkedlist.h @@ -0,0 +1,692 @@ +//======== (C) Copyright 1999, 2000 Valve, L.L.C. All rights reserved. ======== +// +// The copyright to the contents herein is the property of Valve, L.L.C. +// The contents may be used and/or copied only with the written permission of +// Valve, L.L.C., or in accordance with the terms and conditions stipulated in +// the agreement/contract under which the contents have been supplied. +// +// Purpose: Linked list container class +// +// $Revision: $ +// $NoKeywords: $ +//============================================================================= + +#ifndef UTLLINKEDLIST_H +#define UTLLINKEDLIST_H + +#ifdef _WIN32 +#pragma once +#endif + +#include "basetypes.h" +#include "utlmemory.h" +#include "tier0/dbg.h" + + +// This is a useful macro to iterate from head to tail in a linked list. +#define FOR_EACH_LL( listName, iteratorName ) \ + for( int iteratorName=listName.Head(); iteratorName != listName.InvalidIndex(); iteratorName = listName.Next( iteratorName ) ) + +#define INVALID_LLIST_IDX ((I)~0) + +//----------------------------------------------------------------------------- +// class CUtlLinkedList: +// description: +// A lovely index-based linked list! T is the class type, I is the index +// type, which usually should be an unsigned short or smaller. +//----------------------------------------------------------------------------- + +template +class CUtlLinkedList +{ +public: + typedef T ElemType_t; + typedef I IndexType_t; + + // constructor, destructor + CUtlLinkedList(int growSize = 0, int initSize = 0); + CUtlLinkedList(void *pMemory, int memsize); + ~CUtlLinkedList(); + + // gets particular elements + T& Element(I i); + T const& Element(I i) const; + T& operator[](I i); + T const& operator[](I i) const; + + // Make sure we have a particular amount of memory + void EnsureCapacity(int num); + + // Memory deallocation + void Purge(); + + // Delete all the elements then call Purge. + void PurgeAndDeleteElements(); + + // Insertion methods.... + I InsertBefore(I before); + I InsertAfter(I after); + I AddToHead(); + I AddToTail(); + + I InsertBefore(I before, T const& src); + I InsertAfter(I after, T const& src); + I AddToHead(T const& src); + I AddToTail(T const& src); + + // Find an element and return its index or InvalidIndex() if it couldn't be found. + I Find(const T &src) const; + + // Look for the element. If it exists, remove it and return true. Otherwise, return false. + bool FindAndRemove(const T &src); + + // Removal methods + void Remove(I elem); + void RemoveAll(); + + // Allocation/deallocation methods + // If multilist == true, then list list may contain many + // non-connected lists, and IsInList and Head + Tail are meaningless... + I Alloc(bool multilist = false); + void Free(I elem); + + // list modification + void LinkBefore(I before, I elem); + void LinkAfter(I after, I elem); + void Unlink(I elem); + void LinkToHead(I elem); + void LinkToTail(I elem); + + // invalid index + inline static I InvalidIndex() { return INVALID_LLIST_IDX; } + inline static size_t ElementSize() { return sizeof(ListElem_t); } + + // list statistics + int Count() const; + I MaxElementIndex() const; + + // Traversing the list + I Head() const; + I Tail() const; + I Previous(I i) const; + I Next(I i) const; + + // Are nodes in the list or valid? + bool IsValidIndex(I i) const; + bool IsInList(I i) const; + +protected: + // What the linked list element looks like + struct ListElem_t + { + T m_Element; + I m_Previous; + I m_Next; + + private: + // No copy constructor for these... + ListElem_t(const ListElem_t&); + }; + + // constructs the class + I AllocInternal(bool multilist = false); + void ConstructList(); + + // Gets at the list element.... + ListElem_t& InternalElement(I i) { return m_Memory[i]; } + ListElem_t const& InternalElement(I i) const { return m_Memory[i]; } + + void ResetDbgInfo() + { + m_pElements = m_Memory.Base(); + } + + // copy constructors not allowed + CUtlLinkedList(CUtlLinkedList const& list) { Assert(0); } + + CUtlMemory m_Memory; + I m_Head; + I m_Tail; + I m_FirstFree; + I m_ElementCount; // The number actually in the list + I m_TotalElements; // The number allocated + + // For debugging purposes; + // it's in release builds so this can be used in libraries correctly + ListElem_t *m_pElements; +}; + + +//----------------------------------------------------------------------------- +// constructor, destructor +//----------------------------------------------------------------------------- + +template +CUtlLinkedList::CUtlLinkedList(int growSize, int initSize) : +m_Memory(growSize, initSize) +{ + ConstructList(); + ResetDbgInfo(); +} + +template +CUtlLinkedList::CUtlLinkedList(void* pMemory, int memsize) : +m_Memory((ListElem_t *)pMemory, memsize / sizeof(ListElem_t)) +{ + ConstructList(); + ResetDbgInfo(); +} + +template +CUtlLinkedList::~CUtlLinkedList() +{ + RemoveAll(); +} + +template +void CUtlLinkedList::ConstructList() +{ + m_Head = InvalidIndex(); + m_Tail = InvalidIndex(); + m_FirstFree = InvalidIndex(); + m_ElementCount = m_TotalElements = 0; +} + + +//----------------------------------------------------------------------------- +// gets particular elements +//----------------------------------------------------------------------------- + +template +inline T& CUtlLinkedList::Element(I i) +{ + return m_Memory[i].m_Element; +} + +template +inline T const& CUtlLinkedList::Element(I i) const +{ + return m_Memory[i].m_Element; +} + +template +inline T& CUtlLinkedList::operator[](I i) +{ + return m_Memory[i].m_Element; +} + +template +inline T const& CUtlLinkedList::operator[](I i) const +{ + return m_Memory[i].m_Element; +} + +//----------------------------------------------------------------------------- +// list statistics +//----------------------------------------------------------------------------- + +template +inline int CUtlLinkedList::Count() const +{ + return m_ElementCount; +} + +template +inline I CUtlLinkedList::MaxElementIndex() const +{ + return m_Memory.NumAllocated(); +} + + +//----------------------------------------------------------------------------- +// Traversing the list +//----------------------------------------------------------------------------- + +template +inline I CUtlLinkedList::Head() const +{ + return m_Head; +} + +template +inline I CUtlLinkedList::Tail() const +{ + return m_Tail; +} + +template +inline I CUtlLinkedList::Previous(I i) const +{ + Assert(IsValidIndex(i)); + return InternalElement(i).m_Previous; +} + +template +inline I CUtlLinkedList::Next(I i) const +{ + Assert(IsValidIndex(i)); + return InternalElement(i).m_Next; +} + + +//----------------------------------------------------------------------------- +// Are nodes in the list or valid? +//----------------------------------------------------------------------------- + +template +inline bool CUtlLinkedList::IsValidIndex(I i) const +{ + return (i < m_TotalElements) && (i >= 0) && + ((m_Memory[i].m_Previous != i) || (m_Memory[i].m_Next == i)); +} + +template +inline bool CUtlLinkedList::IsInList(I i) const +{ + return (i < m_TotalElements) && (i >= 0) && (Previous(i) != i); +} + +//----------------------------------------------------------------------------- +// Makes sure we have enough memory allocated to store a requested # of elements +//----------------------------------------------------------------------------- + +template< class T, class I > +void CUtlLinkedList::EnsureCapacity(int num) +{ + m_Memory.EnsureCapacity(num); + ResetDbgInfo(); +} + + +//----------------------------------------------------------------------------- +// Deallocate memory +//----------------------------------------------------------------------------- + +template +void CUtlLinkedList::Purge() +{ + RemoveAll(); + m_Memory.Purge(); + m_FirstFree = InvalidIndex(); + m_TotalElements = 0; + ResetDbgInfo(); + +} + + +template +void CUtlLinkedList::PurgeAndDeleteElements() +{ + int iNext; + for (int i = Head(); i != InvalidIndex(); i = iNext) + { + iNext = Next(i); + delete Element(i); + } + + Purge(); +} + + +//----------------------------------------------------------------------------- +// Node allocation/deallocation +//----------------------------------------------------------------------------- +template +I CUtlLinkedList::AllocInternal(bool multilist) +{ + I elem; + if (m_FirstFree == InvalidIndex()) + { + // Nothing in the free list; add. + // Since nothing is in the free list, m_TotalElements == total # of elements + // the list knows about. + if (m_TotalElements == m_Memory.NumAllocated()) + m_Memory.Grow(); + + Assert(m_TotalElements != InvalidIndex()); + + elem = (I)m_TotalElements; + ++m_TotalElements; + + if (elem == InvalidIndex()) + { + Error("CUtlLinkedList overflow!\n"); + } + } + else + { + elem = m_FirstFree; + m_FirstFree = InternalElement(m_FirstFree).m_Next; + } + + if (!multilist) + InternalElement(elem).m_Next = InternalElement(elem).m_Previous = elem; + else + InternalElement(elem).m_Next = InternalElement(elem).m_Previous = InvalidIndex(); + + ResetDbgInfo(); + + return elem; +} + +template +I CUtlLinkedList::Alloc(bool multilist) +{ + I elem = AllocInternal(multilist); + Construct(&Element(elem)); + + return elem; +} + +template +void CUtlLinkedList::Free(I elem) +{ + Assert(IsValidIndex(elem)); + Unlink(elem); + + ListElem_t &internalElem = InternalElement(elem); + Destruct(&internalElem.m_Element); + internalElem.m_Next = m_FirstFree; + m_FirstFree = elem; +} + +//----------------------------------------------------------------------------- +// Insertion methods; allocates and links (uses default constructor) +//----------------------------------------------------------------------------- + +template +I CUtlLinkedList::InsertBefore(I before) +{ + // Make a new node + I newNode = AllocInternal(); + + // Link it in + LinkBefore(before, newNode); + + // Construct the data + Construct(&Element(newNode)); + + return newNode; +} + +template +I CUtlLinkedList::InsertAfter(I after) +{ + // Make a new node + I newNode = AllocInternal(); + + // Link it in + LinkAfter(after, newNode); + + // Construct the data + Construct(&Element(newNode)); + + return newNode; +} + +template +inline I CUtlLinkedList::AddToHead() +{ + return InsertAfter(InvalidIndex()); +} + +template +inline I CUtlLinkedList::AddToTail() +{ + return InsertBefore(InvalidIndex()); +} + + +//----------------------------------------------------------------------------- +// Insertion methods; allocates and links (uses copy constructor) +//----------------------------------------------------------------------------- + +template +I CUtlLinkedList::InsertBefore(I before, T const& src) +{ + // Make a new node + I newNode = AllocInternal(); + + // Link it in + LinkBefore(before, newNode); + + // Construct the data + CopyConstruct(&Element(newNode), src); + + return newNode; +} + +template +I CUtlLinkedList::InsertAfter(I after, T const& src) +{ + // Make a new node + I newNode = AllocInternal(); + + // Link it in + LinkAfter(after, newNode); + + // Construct the data + CopyConstruct(&Element(newNode), src); + + return newNode; +} + +template +inline I CUtlLinkedList::AddToHead(T const& src) +{ + return InsertAfter(InvalidIndex(), src); +} + +template +inline I CUtlLinkedList::AddToTail(T const& src) +{ + return InsertBefore(InvalidIndex(), src); +} + + +//----------------------------------------------------------------------------- +// Removal methods +//----------------------------------------------------------------------------- + +template +I CUtlLinkedList::Find(const T &src) const +{ + for (I i = Head(); i != InvalidIndex(); i = Next(i)) + { + if (Element(i) == src) + return i; + } + return InvalidIndex(); +} + + +template +bool CUtlLinkedList::FindAndRemove(const T &src) +{ + I i = Find(src); + if (i == InvalidIndex()) + { + return false; + } + else + { + Remove(i); + return true; + } +} + + +template +void CUtlLinkedList::Remove(I elem) +{ + Free(elem); +} + +template +void CUtlLinkedList::RemoveAll() +{ + if (m_TotalElements == 0) + return; + + // Put everything into the free list + I prev = InvalidIndex(); + for (int i = (int)m_TotalElements; --i >= 0;) + { + // Invoke the destructor + if (IsValidIndex((I)i)) + Destruct(&Element((I)i)); + + // next points to the next free list item + InternalElement((I)i).m_Next = prev; + + // Indicates it's in the free list + InternalElement((I)i).m_Previous = (I)i; + prev = (I)i; + } + + // First free points to the first element + m_FirstFree = 0; + + // Clear everything else out + m_Head = InvalidIndex(); + m_Tail = InvalidIndex(); + m_ElementCount = 0; +} + + +//----------------------------------------------------------------------------- +// list modification +//----------------------------------------------------------------------------- + +template +void CUtlLinkedList::LinkBefore(I before, I elem) +{ + Assert(IsValidIndex(elem)); + + // Unlink it if it's in the list at the moment + Unlink(elem); + + ListElem_t& newElem = InternalElement(elem); + + // The element *after* our newly linked one is the one we linked before. + newElem.m_Next = before; + + if (before == InvalidIndex()) + { + // In this case, we're linking to the end of the list, so reset the tail + newElem.m_Previous = m_Tail; + m_Tail = elem; + } + else + { + // Here, we're not linking to the end. Set the prev pointer to point to + // the element we're linking. + Assert(IsInList(before)); + ListElem_t& beforeElem = InternalElement(before); + newElem.m_Previous = beforeElem.m_Previous; + beforeElem.m_Previous = elem; + } + + // Reset the head if we linked to the head of the list + if (newElem.m_Previous == InvalidIndex()) + m_Head = elem; + else + InternalElement(newElem.m_Previous).m_Next = elem; + + // one more element baby + ++m_ElementCount; +} + +template +void CUtlLinkedList::LinkAfter(I after, I elem) +{ + Assert(IsValidIndex(elem)); + + // Unlink it if it's in the list at the moment + if (IsInList(elem)) + Unlink(elem); + + ListElem_t& newElem = InternalElement(elem); + + // The element *before* our newly linked one is the one we linked after + newElem.m_Previous = after; + if (after == InvalidIndex()) + { + // In this case, we're linking to the head of the list, reset the head + newElem.m_Next = m_Head; + m_Head = elem; + } + else + { + // Here, we're not linking to the end. Set the next pointer to point to + // the element we're linking. + Assert(IsInList(after)); + ListElem_t& afterElem = InternalElement(after); + newElem.m_Next = afterElem.m_Next; + afterElem.m_Next = elem; + } + + // Reset the tail if we linked to the tail of the list + if (newElem.m_Next == InvalidIndex()) + m_Tail = elem; + else + InternalElement(newElem.m_Next).m_Previous = elem; + + // one more element baby + ++m_ElementCount; +} + +template +void CUtlLinkedList::Unlink(I elem) +{ + Assert(IsValidIndex(elem)); + if (IsInList(elem)) + { + ListElem_t *pBase = m_Memory.Base(); + ListElem_t *pOldElem = &pBase[elem]; + + // If we're the first guy, reset the head + // otherwise, make our previous node's next pointer = our next + if (pOldElem->m_Previous != INVALID_LLIST_IDX) + { + pBase[pOldElem->m_Previous].m_Next = pOldElem->m_Next; + } + else + { + m_Head = pOldElem->m_Next; + } + + // If we're the last guy, reset the tail + // otherwise, make our next node's prev pointer = our prev + if (pOldElem->m_Next != INVALID_LLIST_IDX) + { + pBase[pOldElem->m_Next].m_Previous = pOldElem->m_Previous; + } + else + { + m_Tail = pOldElem->m_Previous; + } + + // This marks this node as not in the list, + // but not in the free list either + pOldElem->m_Previous = pOldElem->m_Next = elem; + + // One less puppy + --m_ElementCount; + } +} + +template +inline void CUtlLinkedList::LinkToHead(I elem) +{ + LinkAfter(InvalidIndex(), elem); +} + +template +inline void CUtlLinkedList::LinkToTail(I elem) +{ + LinkBefore(InvalidIndex(), elem); +} + + +#endif // UTLLINKEDLIST_H diff --git a/dep/rehlsdk/public/utlmap.h b/dep/rehlsdk/public/utlmap.h new file mode 100644 index 0000000..4433f26 --- /dev/null +++ b/dep/rehlsdk/public/utlmap.h @@ -0,0 +1,261 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "tier0/dbg.h" +#include "utlrbtree.h" + +// Purpose: An associative container. Pretty much identical to std::map. +// This is a useful macro to iterate from start to end in order in a map +#define FOR_EACH_MAP(mapName, iteratorName)\ + for (int iteratorName = (mapName).FirstInorder(); (mapName).IsUtlMap && iteratorName != (mapName).InvalidIndex(); iteratorName = (mapName).NextInorder(iteratorName)) + +// faster iteration, but in an unspecified order +#define FOR_EACH_MAP_FAST(mapName, iteratorName)\ + for (int iteratorName = 0; (mapName).IsUtlMap && iteratorName < (mapName).MaxElement(); ++iteratorName) if (!(mapName).IsValidIndex(iteratorName)) continue; else + +struct base_utlmap_t +{ +public: + // This enum exists so that FOR_EACH_MAP and FOR_EACH_MAP_FAST cannot accidentally + // be used on a type that is not a CUtlMap. If the code compiles then all is well. + // The check for IsUtlMap being true should be free. + // Using an enum rather than a static const bool ensures that this trick works even + // with optimizations disabled on gcc. + enum CompileTimeCheck + { + IsUtlMap = 1 + }; +}; + +template +class CUtlMap: public base_utlmap_t +{ +public: + typedef K KeyType_t; + typedef T ElemType_t; + typedef I IndexType_t; + + // Less func typedef + // Returns true if the first parameter is "less" than the second + typedef bool (*LessFunc_t)(const KeyType_t &, const KeyType_t &); + + // constructor, destructor + // Left at growSize = 0, the memory will first allocate 1 element and double in size + // at each increment. + // LessFunc_t is required, but may be set after the constructor using SetLessFunc() below + CUtlMap(int growSize = 0, int initSize = 0, LessFunc_t lessfunc = 0) + : m_Tree(growSize, initSize, CKeyLess(lessfunc)) + { + if (!lessfunc) { + SetLessFunc(DefLessFunc(K)); + } + } + + CUtlMap(LessFunc_t lessfunc) + : m_Tree(CKeyLess(lessfunc)) + { + if (!lessfunc) { + SetLessFunc(DefLessFunc(K)); + } + } + + void EnsureCapacity(int num) { m_Tree.EnsureCapacity(num); } + + // gets particular elements + ElemType_t & Element(IndexType_t i) { return m_Tree.Element(i).elem; } + const ElemType_t & Element(IndexType_t i) const { return m_Tree.Element(i).elem; } + ElemType_t & operator[](IndexType_t i) { return m_Tree.Element(i).elem; } + const ElemType_t & operator[](IndexType_t i) const { return m_Tree.Element(i).elem; } + KeyType_t & Key(IndexType_t i) { return m_Tree.Element(i).key; } + const KeyType_t & Key(IndexType_t i) const { return m_Tree.Element(i).key; } + + + // Num elements + unsigned int Count() const { return m_Tree.Count(); } + + // Max "size" of the vector + IndexType_t MaxElement() const { return m_Tree.MaxElement(); } + + // Checks if a node is valid and in the map + bool IsValidIndex(IndexType_t i) const { return m_Tree.IsValidIndex(i); } + + // Checks if the map as a whole is valid + bool IsValid() const { return m_Tree.IsValid(); } + + // Invalid index + static IndexType_t InvalidIndex() { return CTree::InvalidIndex(); } + + // Sets the less func + void SetLessFunc(LessFunc_t func) + { + m_Tree.SetLessFunc(CKeyLess(func)); + } + + // Insert method (inserts in order) + IndexType_t Insert(const KeyType_t &key, const ElemType_t &insert) + { + Node_t node; + node.key = key; + node.elem = insert; + return m_Tree.Insert(node); + } + + IndexType_t Insert(const KeyType_t &key) + { + Node_t node; + node.key = key; + return m_Tree.Insert(node); + } + + // Find method + IndexType_t Find(const KeyType_t &key) const + { + Node_t dummyNode; + dummyNode.key = key; + return m_Tree.Find(dummyNode); + } + + // Remove methods + void RemoveAt(IndexType_t i) { m_Tree.RemoveAt(i); } + bool Remove(const KeyType_t &key) + { + Node_t dummyNode; + dummyNode.key = key; + return m_Tree.Remove(dummyNode); + } + + void RemoveAll() { m_Tree.RemoveAll(); } + void Purge() { m_Tree.Purge(); } + + // Purges the list and calls delete on each element in it. + void PurgeAndDeleteElements(); + + // Iteration + IndexType_t FirstInorder() const { return m_Tree.FirstInorder(); } + IndexType_t NextInorder(IndexType_t i) const { return m_Tree.NextInorder(i); } + IndexType_t PrevInorder(IndexType_t i) const { return m_Tree.PrevInorder(i); } + IndexType_t LastInorder() const { return m_Tree.LastInorder(); } + + // If you change the search key, this can be used to reinsert the + // element into the map. + void Reinsert(const KeyType_t &key, IndexType_t i) + { + m_Tree[i].key = key; + m_Tree.Reinsert(i); + } + + IndexType_t InsertOrReplace(const KeyType_t &key, const ElemType_t &insert) + { + IndexType_t i = Find(key); + if (i != InvalidIndex()) + { + Element(i) = insert; + return i; + } + + return Insert(key, insert); + } + + void Swap(CUtlMap &that) + { + m_Tree.Swap(that.m_Tree); + } + + struct Node_t + { + Node_t() + { + } + + Node_t(const Node_t &from) + : key(from.key), + elem(from.elem) + { + } + + KeyType_t key; + ElemType_t elem; + }; + + class CKeyLess + { + public: + CKeyLess(LessFunc_t lessFunc) : m_LessFunc(lessFunc) {} + + bool operator!() const + { + return !m_LessFunc; + } + + bool operator()(const Node_t &left, const Node_t &right) const + { + return m_LessFunc(left.key, right.key); + } + + LessFunc_t m_LessFunc; + }; + + typedef CUtlRBTree CTree; + + CTree *AccessTree() { return &m_Tree; } + +protected: + CTree m_Tree; +}; + +// Purges the list and calls delete on each element in it. +template +inline void CUtlMap::PurgeAndDeleteElements() +{ + for (I i = 0; i < MaxElement(); ++i) + { + if (!IsValidIndex(i)) + continue; + + delete Element(i); + } + + Purge(); +} + +// This is horrible and slow and meant to be used only when you're dealing with really +// non-time/memory-critical code and desperately want to copy a whole map element-by-element +// for whatever reason. +template +void DeepCopyMap(const CUtlMap &pmapIn, CUtlMap *out_pmapOut) +{ + Assert(out_pmapOut); + + out_pmapOut->Purge(); + FOR_EACH_MAP_FAST(pmapIn, i) + { + out_pmapOut->Insert(pmapIn.Key(i), pmapIn.Element(i)); + } +} diff --git a/dep/rehlsdk/public/utlmemory.h b/dep/rehlsdk/public/utlmemory.h new file mode 100644 index 0000000..704cf9e --- /dev/null +++ b/dep/rehlsdk/public/utlmemory.h @@ -0,0 +1,335 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "osconfig.h" +#include "tier0/dbg.h" +#include + +#pragma warning (disable:4100) +#pragma warning (disable:4514) + +// The CUtlMemory class: +// A growable memory class which doubles in size by default. +template +class CUtlMemory +{ +public: + // constructor, destructor + CUtlMemory(int nGrowSize = 0, int nInitSize = 0); + CUtlMemory(T *pMemory, int numElements); + ~CUtlMemory(); + + // Set the size by which the memory grows + void Init(int nGrowSize = 0, int nInitSize = 0); + + class Iterator_t + { + public: + Iterator_t(I i) : m_index(i) {} + I m_index; + + bool operator==(const Iterator_t it) const { return m_index == it.m_index; } + bool operator!=(const Iterator_t it) const { return m_index != it.m_index; } + }; + + Iterator_t First() const { return Iterator_t(IsIdxValid(0) ? 0 : InvalidIndex()); } + Iterator_t Next(const Iterator_t &it) const { return Iterator_t(IsIdxValid(it.index + 1) ? it.index + 1 : InvalidIndex()); } + I GetIndex(const Iterator_t &it) const { return it.index; } + bool IsIdxAfter(I i, const Iterator_t &it) const { return i > it.index; } + bool IsValidIterator(const Iterator_t &it) const { return IsIdxValid(it.index); } + Iterator_t InvalidIterator() const { return Iterator_t(InvalidIndex()); } + + // element access + T& Element(I i); + T const& Element(I i) const; + T& operator[](I i); + T const& operator[](I i) const; + + // Can we use this index? + bool IsIdxValid(I i) const; + + // Specify the invalid ('null') index that we'll only return on failure + static const I INVALID_INDEX = (I)-1; // For use with COMPILE_TIME_ASSERT + static I InvalidIndex() { return INVALID_INDEX; } + + // Gets the base address (can change when adding elements!) + T *Base(); + T const *Base() const; + + // Attaches the buffer to external memory.... + void SetExternalBuffer(T *pMemory, int numElements); + + // Size + int NumAllocated() const; + int Count() const; + + // Grows the memory, so that at least allocated + num elements are allocated + void Grow(int num = 1); + + // Makes sure we've got at least this much memory + void EnsureCapacity(int num); + + // Memory deallocation + void Purge(); + + // is the memory externally allocated? + bool IsExternallyAllocated() const; + + // Set the size by which the memory grows + void SetGrowSize(int size); + +private: + enum + { + EXTERNAL_BUFFER_MARKER = -1, + }; + + T *m_pMemory; + int m_nAllocationCount; + int m_nGrowSize; +}; + +// Constructor, Destructor +template +CUtlMemory::CUtlMemory(int nGrowSize, int nInitSize) : m_pMemory(0), +m_nAllocationCount(nInitSize), m_nGrowSize(nGrowSize) +{ + Assert((nGrowSize >= 0) && (nGrowSize != EXTERNAL_BUFFER_MARKER)); + if (m_nAllocationCount) + { + m_pMemory = (T *)malloc(m_nAllocationCount * sizeof(T)); + } +} + +template +CUtlMemory::CUtlMemory(T *pMemory, int numElements) : m_pMemory(pMemory), +m_nAllocationCount(numElements) +{ + // Special marker indicating externally supplied memory + m_nGrowSize = EXTERNAL_BUFFER_MARKER; +} + +template +CUtlMemory::~CUtlMemory() +{ + Purge(); +} + +template +void CUtlMemory::Init(int nGrowSize, int nInitSize) +{ + Purge(); + + m_nGrowSize = nGrowSize; + m_nAllocationCount = nInitSize; + Assert(nGrowSize >= 0); + if (m_nAllocationCount) + { + m_pMemory = (T *)malloc(m_nAllocationCount * sizeof(T)); + } +} + +// Attaches the buffer to external memory.... +template +void CUtlMemory::SetExternalBuffer(T *pMemory, int numElements) +{ + // Blow away any existing allocated memory + Purge(); + + m_pMemory = pMemory; + m_nAllocationCount = numElements; + + // Indicate that we don't own the memory + m_nGrowSize = EXTERNAL_BUFFER_MARKER; +} + +// Element access +template +inline T& CUtlMemory::operator[](I i) +{ + Assert(IsIdxValid(i)); + return m_pMemory[i]; +} + +template +inline T const& CUtlMemory::operator[](I i) const +{ + Assert(IsIdxValid(i)); + return m_pMemory[i]; +} + +template +inline T& CUtlMemory::Element(I i) +{ + Assert(IsIdxValid(i)); + return m_pMemory[i]; +} + +template +inline T const& CUtlMemory::Element(I i) const +{ + Assert(IsIdxValid(i)); + return m_pMemory[i]; +} + +// Is the memory externally allocated? +template +bool CUtlMemory::IsExternallyAllocated() const +{ + return m_nGrowSize == EXTERNAL_BUFFER_MARKER; +} + +template +void CUtlMemory::SetGrowSize(int nSize) +{ + Assert((nSize >= 0) && (nSize != EXTERNAL_BUFFER_MARKER)); + m_nGrowSize = nSize; +} + +// Gets the base address (can change when adding elements!) +template +inline T *CUtlMemory::Base() +{ + return m_pMemory; +} + +template +inline T const *CUtlMemory::Base() const +{ + return m_pMemory; +} + +// Size +template +inline int CUtlMemory::NumAllocated() const +{ + return m_nAllocationCount; +} + +template +inline int CUtlMemory::Count() const +{ + return m_nAllocationCount; +} + +// Is element index valid? +template +inline bool CUtlMemory::IsIdxValid(I i) const +{ + return (((int)i) >= 0) && (((int) i) < m_nAllocationCount); +} + +// Grows the memory +template +void CUtlMemory::Grow(int num) +{ + Assert(num > 0); + + if (IsExternallyAllocated()) + { + // Can't grow a buffer whose memory was externally allocated + Assert(0); + return; + } + + // Make sure we have at least numallocated + num allocations. + // Use the grow rules specified for this memory (in m_nGrowSize) + int nAllocationRequested = m_nAllocationCount + num; + while (m_nAllocationCount < nAllocationRequested) + { + if (m_nAllocationCount != 0) + { + if (m_nGrowSize) + { + m_nAllocationCount += m_nGrowSize; + } + else + { + m_nAllocationCount += m_nAllocationCount; + } + } + else + { + // Compute an allocation which is at least as big as a cache line... + m_nAllocationCount = (31 + sizeof(T)) / sizeof(T); + Assert(m_nAllocationCount != 0); + } + } + + if (m_pMemory) + { + m_pMemory = (T *)realloc(m_pMemory, m_nAllocationCount * sizeof(T)); + } + else + { + m_pMemory = (T *)malloc(m_nAllocationCount * sizeof(T)); + } +} + +// Makes sure we've got at least this much memory +template +inline void CUtlMemory::EnsureCapacity(int num) +{ + if (m_nAllocationCount >= num) + return; + + if (IsExternallyAllocated()) + { + // Can't grow a buffer whose memory was externally allocated + Assert(0); + return; + } + + m_nAllocationCount = num; + if (m_pMemory) + { + m_pMemory = (T *)realloc(m_pMemory, m_nAllocationCount * sizeof(T)); + } + else + { + m_pMemory = (T *)malloc(m_nAllocationCount * sizeof(T)); + } +} + +// Memory deallocation +template +void CUtlMemory::Purge() +{ + if (!IsExternallyAllocated()) + { + if (m_pMemory) + { + free((void *)m_pMemory); + m_pMemory = 0; + } + + m_nAllocationCount = 0; + } +} diff --git a/dep/rehlsdk/public/utlrbtree.h b/dep/rehlsdk/public/utlrbtree.h new file mode 100644 index 0000000..c991275 --- /dev/null +++ b/dep/rehlsdk/public/utlrbtree.h @@ -0,0 +1,1172 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "utlmemory.h" + +// Tool to generate a default compare function for any type that implements +// operator<, including all simple types +template +class CDefOps +{ +public: + static bool LessFunc(const T &lhs, const T &rhs) { return (lhs < rhs); } +}; + +#define DefLessFunc(type) CDefOps::LessFunc + +inline bool StringLessThan(const char *const &lhs, const char *const &rhs) { return (strcmp(lhs, rhs) < 0); } +inline bool CaselessStringLessThan(const char *const &lhs, const char *const &rhs) { return (_stricmp(lhs, rhs) < 0); } + +// inline these two templates to stop multiple definitions of the same code +template <> inline bool CDefOps::LessFunc(const char *const &lhs, const char *const &rhs) { return StringLessThan(lhs, rhs); } +template <> inline bool CDefOps::LessFunc(char *const &lhs, char *const &rhs) { return StringLessThan(lhs, rhs); } + +template +void SetDefLessFunc(RBTREE_T &RBTree) +{ + RBTree.SetLessFunc(DefLessFunc(typename RBTREE_T::KeyType_t)); +} + +// A red-black binary search tree +template +struct UtlRBTreeLinks_t +{ + I m_Left; + I m_Right; + I m_Parent; + I m_Tag; +}; + +template +struct UtlRBTreeNode_t: public UtlRBTreeLinks_t +{ + T m_Data; +}; + +// A red-black binary search tree +template , I>> +class CUtlRBTree +{ +public: + typedef T KeyType_t; + typedef T ElemType_t; + typedef I IndexType_t; + + // Less func typedef + // Returns true if the first parameter is "less" than the second + typedef L LessFunc_t; + + // constructor, destructor + // Left at growSize = 0, the memory will first allocate 1 element and double in size + // at each increment. + // LessFunc_t is required, but may be set after the constructor using SetLessFunc() below + CUtlRBTree(int growSize = 0, int initSize = 0, LessFunc_t lessfunc = 0); + ~CUtlRBTree(); + + // gets particular elements + T& Element(I i); + T const& Element(I i) const; + T& operator[](I i); + T const& operator[](I i) const; + + // Gets the root + I Root() const; + + // Num elements + unsigned int Count() const; + + // Max "size" of the vector + I MaxElement() const; + + // Gets the children + I Parent(I i) const; + I LeftChild(I i) const; + I RightChild(I i) const; + + // Tests if a node is a left or right child + bool IsLeftChild(I i) const; + bool IsRightChild(I i) const; + + // Tests if root or leaf + bool IsRoot(I i) const; + bool IsLeaf(I i) const; + + // Checks if a node is valid and in the tree + bool IsValidIndex(I i) const; + + // Checks if the tree as a whole is valid + bool IsValid() const; + + // Invalid index + static I InvalidIndex(); + + // returns the tree depth (not a very fast operation) + int Depth(I node) const; + int Depth() const; + + // Sets the less func + void SetLessFunc(LessFunc_t func); + + // Allocation method + I NewNode(); + + // Insert method (inserts in order) + I Insert(T const &insert); + void Insert(const T *pArray, int nItems); + + // Find method + I Find(T const &search) const; + + // Remove methods + void RemoveAt(I i); + bool Remove(T const &remove); + void RemoveAll(); + + // Allocation, deletion + void FreeNode(I i); + + // Iteration + I FirstInorder() const; + I NextInorder(I i) const; + I PrevInorder(I i) const; + I LastInorder() const; + + I FirstPreorder() const; + I NextPreorder(I i) const; + I PrevPreorder(I i) const; + I LastPreorder() const; + + I FirstPostorder() const; + I NextPostorder(I i) const; + + // If you change the search key, this can be used to reinsert the + // element into the tree. + void Reinsert(I elem); + +private: + // Can't copy the tree this way! + CUtlRBTree &operator=(const CUtlRBTree &other); + +protected: + enum NodeColor_t + { + RED = 0, + BLACK + }; + + typedef UtlRBTreeNode_t Node_t; + typedef UtlRBTreeLinks_t Links_t; + + // Sets the children + void SetParent(I i, I parent); + void SetLeftChild(I i, I child); + void SetRightChild(I i, I child); + void LinkToParent(I i, I parent, bool isLeft); + + // Gets at the links + Links_t const& Links(I i) const; + Links_t& Links(I i); + + // Checks if a link is red or black + bool IsRed(I i) const; + bool IsBlack(I i) const; + + // Sets/gets node color + NodeColor_t Color(I i) const; + void SetColor(I i, NodeColor_t c); + + // operations required to preserve tree balance + void RotateLeft(I i); + void RotateRight(I i); + void InsertRebalance(I i); + void RemoveRebalance(I i); + + // Insertion, removal + I InsertAt(I parent, bool leftchild); + + // copy constructors not allowed + CUtlRBTree(CUtlRBTree const &tree); + + // Inserts a node into the tree, doesn't copy the data in. + void FindInsertionPosition(T const &insert, I &parent, bool &leftchild); + + // Remove and add back an element in the tree. + void Unlink(I elem); + void Link(I elem); + + // Used for sorting. + LessFunc_t m_LessFunc; + + M m_Elements; + I m_Root; + I m_NumElements; + I m_FirstFree; + I m_TotalElements; +}; + +// Constructor, Destructor +template +CUtlRBTree::CUtlRBTree(int growSize, int initSize, LessFunc_t lessfunc) : + m_Elements(growSize, initSize), + m_LessFunc(lessfunc), + m_Root(InvalidIndex()), + m_NumElements(0), m_TotalElements(0), + m_FirstFree(InvalidIndex()) +{ +} + +template +CUtlRBTree::~CUtlRBTree() +{ +} + +// Gets particular elements +template +inline T &CUtlRBTree::Element(I i) +{ + return m_Elements[i].m_Data; +} + +template +inline T const &CUtlRBTree::Element(I i) const +{ + return m_Elements[i].m_Data; +} + +template +inline T &CUtlRBTree::operator[](I i) +{ + return Element(i); +} + +template +inline T const &CUtlRBTree::operator[](I i) const +{ + return Element(i); +} + +// Gets the root +template +inline I CUtlRBTree::Root() const +{ + return m_Root; +} + +// Num elements +template +inline unsigned int CUtlRBTree::Count() const +{ + return (unsigned int)m_NumElements; +} + +// Max "size" of the vector +template +inline I CUtlRBTree::MaxElement() const +{ + return (I)m_TotalElements; +} + +// Gets the children +template +inline I CUtlRBTree::Parent(I i) const +{ + return Links(i).m_Parent; +} + +template +inline I CUtlRBTree::LeftChild(I i) const +{ + return Links(i).m_Left; +} + +template +inline I CUtlRBTree::RightChild(I i) const +{ + return Links(i).m_Right; +} + +// Tests if a node is a left or right child +template +inline bool CUtlRBTree::IsLeftChild(I i) const +{ + return LeftChild(Parent(i)) == i; +} + +template +inline bool CUtlRBTree::IsRightChild(I i) const +{ + return RightChild(Parent(i)) == i; +} + +// Tests if root or leaf +template +inline bool CUtlRBTree::IsRoot(I i) const +{ + return i == m_Root; +} + +template +inline bool CUtlRBTree::IsLeaf(I i) const +{ + return (LeftChild(i) == InvalidIndex()) && (RightChild(i) == InvalidIndex()); +} + +// Checks if a node is valid and in the tree +template +inline bool CUtlRBTree::IsValidIndex(I i) const +{ + return LeftChild(i) != i; +} + +// Invalid index +template +I CUtlRBTree::InvalidIndex() +{ + return (I)M::InvalidIndex(); +} + +// returns the tree depth (not a very fast operation) +template +inline int CUtlRBTree::Depth() const +{ + return Depth(Root()); +} + +// Sets the children +template +inline void CUtlRBTree::SetParent(I i, I parent) +{ + Links(i).m_Parent = parent; +} + +template +inline void CUtlRBTree::SetLeftChild(I i, I child) +{ + Links(i).m_Left = child; +} + +template +inline void CUtlRBTree::SetRightChild(I i, I child) +{ + Links(i).m_Right = child; +} + +// Gets at the links +template +inline typename CUtlRBTree::Links_t const &CUtlRBTree::Links(I i) const +{ + // Sentinel node, makes life easier + static Links_t s_Sentinel = + { + InvalidIndex(), InvalidIndex(), InvalidIndex(), CUtlRBTree::BLACK + }; + + return (i != InvalidIndex()) ? + *(Links_t*)&m_Elements[i] : + *(Links_t*)&s_Sentinel; +} + +template +inline typename CUtlRBTree::Links_t &CUtlRBTree::Links(I i) +{ + Assert(i != InvalidIndex()); + return *(Links_t *)&m_Elements[i]; +} + +// Checks if a link is red or black +template +inline bool CUtlRBTree::IsRed(I i) const +{ + return (Links(i).m_Tag == RED); +} + +template +inline bool CUtlRBTree::IsBlack(I i) const +{ + return (Links(i).m_Tag == BLACK); +} + +// Sets/gets node color +template +inline typename CUtlRBTree::NodeColor_t CUtlRBTree::Color(I i) const +{ + return (NodeColor_t)Links(i).m_Tag; +} + +template +inline void CUtlRBTree::SetColor(I i, typename CUtlRBTree::NodeColor_t c) +{ + Links(i).m_Tag = (I)c; +} + +// Allocates/ deallocates nodes +template +I CUtlRBTree::NewNode() +{ + I newElem; + + // Nothing in the free list; add. + if (m_FirstFree == InvalidIndex()) + { + if (m_Elements.NumAllocated() == m_TotalElements) + m_Elements.Grow(); + newElem = m_TotalElements++; + } + else + { + newElem = m_FirstFree; + m_FirstFree = RightChild(m_FirstFree); + } + +#ifdef _DEBUG + // reset links to invalid.... + Links_t &node = Links(newElem); + node.m_Left = node.m_Right = node.m_Parent = InvalidIndex(); +#endif + + Construct(&Element(newElem)); + return newElem; +} + +template +void CUtlRBTree::FreeNode(I i) +{ + Assert(IsValidIndex(i) && (i != InvalidIndex())); + Destruct(&Element(i)); + SetLeftChild(i, i); // indicates it's in not in the tree + SetRightChild(i, m_FirstFree); + m_FirstFree = i; +} + +// Rotates node i to the left +template +void CUtlRBTree::RotateLeft(I elem) +{ + I rightchild = RightChild(elem); + SetRightChild(elem, LeftChild(rightchild)); + if (LeftChild(rightchild) != InvalidIndex()) + SetParent(LeftChild(rightchild), elem); + + if (rightchild != InvalidIndex()) + SetParent(rightchild, Parent(elem)); + if (!IsRoot(elem)) + { + if (IsLeftChild(elem)) + SetLeftChild(Parent(elem), rightchild); + else + SetRightChild(Parent(elem), rightchild); + } + else + m_Root = rightchild; + + SetLeftChild(rightchild, elem); + if (elem != InvalidIndex()) + SetParent(elem, rightchild); +} + +// Rotates node i to the right +template +void CUtlRBTree::RotateRight(I elem) +{ + I leftchild = LeftChild(elem); + SetLeftChild(elem, RightChild(leftchild)); + if (RightChild(leftchild) != InvalidIndex()) + SetParent(RightChild(leftchild), elem); + + if (leftchild != InvalidIndex()) + SetParent(leftchild, Parent(elem)); + if (!IsRoot(elem)) + { + if (IsRightChild(elem)) + SetRightChild(Parent(elem), leftchild); + else + SetLeftChild(Parent(elem), leftchild); + } + else + m_Root = leftchild; + + SetRightChild(leftchild, elem); + if (elem != InvalidIndex()) + SetParent(elem, leftchild); +} + +// Rebalances the tree after an insertion +template +void CUtlRBTree::InsertRebalance(I elem) +{ + while (!IsRoot(elem) && (Color(Parent(elem)) == RED)) + { + I parent = Parent(elem); + I grandparent = Parent(parent); + + // we have a violation + if (IsLeftChild(parent)) + { + I uncle = RightChild(grandparent); + if (IsRed(uncle)) + { + // uncle is RED + SetColor(parent, BLACK); + SetColor(uncle, BLACK); + SetColor(grandparent, RED); + elem = grandparent; + } + else + { + // uncle is BLACK + if (IsRightChild(elem)) + { + // make x a left child, will change parent and grandparent + elem = parent; + RotateLeft(elem); + parent = Parent(elem); + grandparent = Parent(parent); + } + + // recolor and rotate + SetColor(parent, BLACK); + SetColor(grandparent, RED); + RotateRight(grandparent); + } + } + else + { + // mirror image of above code + I uncle = LeftChild(grandparent); + if (IsRed(uncle)) + { + // uncle is RED + SetColor(parent, BLACK); + SetColor(uncle, BLACK); + SetColor(grandparent, RED); + elem = grandparent; + } + else + { + // uncle is BLACK + if (IsLeftChild(elem)) + { + // make x a right child, will change parent and grandparent + elem = parent; + RotateRight(parent); + parent = Parent(elem); + grandparent = Parent(parent); + } + // recolor and rotate + SetColor(parent, BLACK); + SetColor(grandparent, RED); + RotateLeft(grandparent); + } + } + } + SetColor(m_Root, BLACK); +} + +// Insert a node into the tree +template +I CUtlRBTree::InsertAt(I parent, bool leftchild) +{ + I i = NewNode(); + LinkToParent(i, parent, leftchild); + m_NumElements++; + return i; +} + +template +void CUtlRBTree::LinkToParent(I i, I parent, bool isLeft) +{ + Links_t &elem = Links(i); + elem.m_Parent = parent; + elem.m_Left = elem.m_Right = InvalidIndex(); + elem.m_Tag = RED; + + // insert node in tree + if (parent != InvalidIndex()) + { + if (isLeft) + Links(parent).m_Left = i; + else + Links(parent).m_Right = i; + } + else + { + m_Root = i; + } + + InsertRebalance(i); + + Assert(IsValid()); +} + +// Rebalance the tree after a deletion +template +void CUtlRBTree::RemoveRebalance(I elem) +{ + while (elem != m_Root && IsBlack(elem)) + { + I parent = Parent(elem); + + // If elem is the left child of the parent + if (elem == LeftChild(parent)) + { + // Get our sibling + I sibling = RightChild(parent); + if (IsRed(sibling)) + { + SetColor(sibling, BLACK); + SetColor(parent, RED); + RotateLeft(parent); + + // We may have a new parent now + parent = Parent(elem); + sibling = RightChild(parent); + } + if ((IsBlack(LeftChild(sibling))) && (IsBlack(RightChild(sibling)))) + { + if (sibling != InvalidIndex()) + SetColor(sibling, RED); + elem = parent; + } + else + { + if (IsBlack(RightChild(sibling))) + { + SetColor(LeftChild(sibling), BLACK); + SetColor(sibling, RED); + RotateRight(sibling); + + // rotation may have changed this + parent = Parent(elem); + sibling = RightChild(parent); + } + SetColor(sibling, Color(parent)); + SetColor(parent, BLACK); + SetColor(RightChild(sibling), BLACK); + RotateLeft(parent); + elem = m_Root; + } + } + else + { + // Elem is the right child of the parent + I sibling = LeftChild(parent); + if (IsRed(sibling)) + { + SetColor(sibling, BLACK); + SetColor(parent, RED); + RotateRight(parent); + + // We may have a new parent now + parent = Parent(elem); + sibling = LeftChild(parent); + } + if ((IsBlack(RightChild(sibling))) && (IsBlack(LeftChild(sibling)))) + { + if (sibling != InvalidIndex()) + SetColor(sibling, RED); + elem = parent; + } + else + { + if (IsBlack(LeftChild(sibling))) + { + SetColor(RightChild(sibling), BLACK); + SetColor(sibling, RED); + RotateLeft(sibling); + + // rotation may have changed this + parent = Parent(elem); + sibling = LeftChild(parent); + } + SetColor(sibling, Color(parent)); + SetColor(parent, BLACK); + SetColor(LeftChild(sibling), BLACK); + RotateRight(parent); + elem = m_Root; + } + } + } + SetColor(elem, BLACK); +} + +template +void CUtlRBTree::Unlink(I elem) +{ + if (elem != InvalidIndex()) + { + I x, y; + + if ((LeftChild(elem) == InvalidIndex()) || + (RightChild(elem) == InvalidIndex())) + { + // y has a NIL node as a child + y = elem; + } + else + { + // find tree successor with a NIL node as a child + y = RightChild(elem); + while (LeftChild(y) != InvalidIndex()) + y = LeftChild(y); + } + + // x is y's only child + if (LeftChild(y) != InvalidIndex()) + x = LeftChild(y); + else + x = RightChild(y); + + // remove y from the parent chain + if (x != InvalidIndex()) + SetParent(x, Parent(y)); + if (!IsRoot(y)) + { + if (IsLeftChild(y)) + SetLeftChild(Parent(y), x); + else + SetRightChild(Parent(y), x); + } + else + m_Root = x; + + // need to store this off now, we'll be resetting y's color + NodeColor_t ycolor = Color(y); + if (y != elem) + { + // Standard implementations copy the data around, we cannot here. + // Hook in y to link to the same stuff elem used to. + SetParent(y, Parent(elem)); + SetRightChild(y, RightChild(elem)); + SetLeftChild(y, LeftChild(elem)); + + if (!IsRoot(elem)) + if (IsLeftChild(elem)) + SetLeftChild(Parent(elem), y); + else + SetRightChild(Parent(elem), y); + else + m_Root = y; + + if (LeftChild(y) != InvalidIndex()) + SetParent(LeftChild(y), y); + if (RightChild(y) != InvalidIndex()) + SetParent(RightChild(y), y); + + SetColor(y, Color(elem)); + } + + if ((x != InvalidIndex()) && (ycolor == BLACK)) + RemoveRebalance(x); + } +} + +template +void CUtlRBTree::Link(I elem) +{ + if (elem != InvalidIndex()) + { + I parent; + bool leftchild; + FindInsertionPosition(Element(elem), parent, leftchild); + LinkToParent(elem, parent, leftchild); + } +} + +// Delete a node from the tree +template +void CUtlRBTree::RemoveAt(I elem) +{ + if (elem != InvalidIndex()) + { + Unlink(elem); + + FreeNode(elem); + m_NumElements--; + } +} + +// remove a node in the tree +template +bool CUtlRBTree::Remove(T const &search) +{ + I node = Find(search); + if (node != InvalidIndex()) + { + RemoveAt(node); + return true; + } + return false; +} + +// Removes all nodes from the tree +template +void CUtlRBTree::RemoveAll() +{ + // Just iterate through the whole list and add to free list + // much faster than doing all of the rebalancing + // also, do it so the free list is pointing to stuff in order + // to get better cache coherence when re-adding stuff to this tree. + I prev = InvalidIndex(); + for (int i = (int)m_TotalElements; --i >= 0;) + { + I idx = (I)i; + if (IsValidIndex(idx)) + Destruct(&Element(idx)); + SetRightChild(idx, prev); + SetLeftChild(idx, idx); + prev = idx; + } + m_FirstFree = m_TotalElements ? (I)0 : InvalidIndex(); + m_Root = InvalidIndex(); + m_NumElements = 0; +} + +// Iteration +template +I CUtlRBTree::FirstInorder() const +{ + I i = m_Root; + while (LeftChild(i) != InvalidIndex()) + i = LeftChild(i); + return i; +} + +template +I CUtlRBTree::NextInorder(I i) const +{ + Assert(IsValidIndex(i)); + + if (RightChild(i) != InvalidIndex()) + { + i = RightChild(i); + while (LeftChild(i) != InvalidIndex()) + i = LeftChild(i); + return i; + } + + I parent = Parent(i); + while (IsRightChild(i)) + { + i = parent; + if (i == InvalidIndex()) break; + parent = Parent(i); + } + return parent; +} + +template +I CUtlRBTree::PrevInorder(I i) const +{ + Assert(IsValidIndex(i)); + + if (LeftChild(i) != InvalidIndex()) + { + i = LeftChild(i); + while (RightChild(i) != InvalidIndex()) + i = RightChild(i); + return i; + } + + I parent = Parent(i); + while (IsLeftChild(i)) + { + i = parent; + if (i == InvalidIndex()) break; + parent = Parent(i); + } + return parent; +} + +template +I CUtlRBTree::LastInorder() const +{ + I i = m_Root; + while (RightChild(i) != InvalidIndex()) + i = RightChild(i); + return i; +} + +template +I CUtlRBTree::FirstPreorder() const +{ + return m_Root; +} + +template +I CUtlRBTree::NextPreorder(I i) const +{ + if (LeftChild(i) != InvalidIndex()) + return LeftChild(i); + + if (RightChild(i) != InvalidIndex()) + return RightChild(i); + + I parent = Parent(i); + while(parent != InvalidIndex()) + { + if (IsLeftChild(i) && (RightChild(parent) != InvalidIndex())) + return RightChild(parent); + i = parent; + parent = Parent(parent); + } + return InvalidIndex(); +} + +template +I CUtlRBTree::PrevPreorder(I i) const +{ + Assert(0); // Not implemented yet + return InvalidIndex(); +} + +template +I CUtlRBTree::LastPreorder() const +{ + I i = m_Root; + while (1) + { + while (RightChild(i) != InvalidIndex()) + i = RightChild(i); + + if (LeftChild(i) != InvalidIndex()) + i = LeftChild(i); + else + break; + } + return i; +} + +template +I CUtlRBTree::FirstPostorder() const +{ + I i = m_Root; + while (!IsLeaf(i)) + { + if (LeftChild(i)) + i = LeftChild(i); + else + i = RightChild(i); + } + return i; +} + +template +I CUtlRBTree::NextPostorder(I i) const +{ + I parent = Parent(i); + if (parent == InvalidIndex()) + return InvalidIndex(); + + if (IsRightChild(i)) + return parent; + + if (RightChild(parent) == InvalidIndex()) + return parent; + + i = RightChild(parent); + while (!IsLeaf(i)) + { + if (LeftChild(i)) + i = LeftChild(i); + else + i = RightChild(i); + } + return i; +} + +template +void CUtlRBTree::Reinsert(I elem) +{ + Unlink(elem); + Link(elem); +} + +// Returns the tree depth (not a very fast operation) +template +int CUtlRBTree::Depth(I node) const +{ + if (node == InvalidIndex()) + return 0; + + int depthright = Depth(RightChild(node)); + int depthleft = Depth(LeftChild(node)); + return max(depthright, depthleft) + 1; +} + +// Makes sure the tree is valid after every operation +template +bool CUtlRBTree::IsValid() const +{ + if (!Count()) + return true; + + if ((Root() >= MaxElement()) || (Parent(Root()) != InvalidIndex())) + goto InvalidTree; + +#ifdef UTLTREE_PARANOID + + // First check to see that mNumEntries matches reality. + // count items on the free list + int numFree = 0; + int curr = m_FirstFree; + while (curr != InvalidIndex()) + { + numFree++; + curr = RightChild(curr); + if ((curr > MaxElement()) && (curr != InvalidIndex())) + goto InvalidTree; + } + if (MaxElement() - numFree != Count()) + goto InvalidTree; + + // Iterate over all elements, looking for validity + // based on the self pointers + int numFree2 = 0; + for (curr = 0; curr < MaxElement(); curr++) + { + if (!IsValidIndex(curr)) + numFree2++; + else + { + int right = RightChild(curr); + int left = LeftChild(curr); + if ((right == left) && (right != InvalidIndex())) + goto InvalidTree; + + if (right != InvalidIndex()) + { + if (!IsValidIndex(right)) + goto InvalidTree; + if (Parent(right) != curr) + goto InvalidTree; + if (IsRed(curr) && IsRed(right)) + goto InvalidTree; + } + + if (left != InvalidIndex()) + { + if (!IsValidIndex(left)) + goto InvalidTree; + if (Parent(left) != curr) + goto InvalidTree; + if (IsRed(curr) && IsRed(left)) + goto InvalidTree; + } + } + } + if (numFree2 != numFree) + goto InvalidTree; + +#endif // UTLTREE_PARANOID + + return true; + +InvalidTree: + return false; +} + +// Sets the less func +template +void CUtlRBTree::SetLessFunc(typename CUtlRBTree::LessFunc_t func) +{ + if (!m_LessFunc) + m_LessFunc = func; + else + { + // Need to re-sort the tree here.... + Assert(0); + } +} + +// Inserts a node into the tree, doesn't copy the data in. +template +void CUtlRBTree::FindInsertionPosition(T const &insert, I &parent, bool &leftchild) +{ + Assert(m_LessFunc); + + // Find where node belongs + I current = m_Root; + parent = InvalidIndex(); + leftchild = false; + while (current != InvalidIndex()) + { + parent = current; + if (m_LessFunc(insert, Element(current))) + { + leftchild = true; + current = LeftChild(current); + } + else + { + leftchild = false; + current = RightChild(current); + } + } +} + +template +I CUtlRBTree::Insert(T const &insert) +{ + // Use copy constructor to copy it in + I parent; + bool leftchild; + FindInsertionPosition(insert, parent, leftchild); + I newNode = InsertAt(parent, leftchild); + CopyConstruct(&Element(newNode), insert); + return newNode; +} + +template +void CUtlRBTree::Insert(const T *pArray, int nItems) +{ + while (nItems--) + { + Insert(*pArray++); + } +} + +// Finds a node in the tree +template +I CUtlRBTree::Find(T const &search) const +{ + Assert(m_LessFunc); + + I current = m_Root; + while (current != InvalidIndex()) + { + if (m_LessFunc(search, Element(current))) + current = LeftChild(current); + else if (m_LessFunc(Element(current), search)) + current = RightChild(current); + else + break; + } + return current; +} diff --git a/dep/rehlsdk/public/utlvector.h b/dep/rehlsdk/public/utlvector.h new file mode 100644 index 0000000..5a20143 --- /dev/null +++ b/dep/rehlsdk/public/utlvector.h @@ -0,0 +1,554 @@ +/* +* +* 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 2 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, write to the Free Software Foundation, +* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +* +* In addition, as a special exception, the author gives permission to +* link the code of this program with the Half-Life Game Engine ("HL +* Engine") and Modified Game Libraries ("MODs") developed by Valve, +* L.L.C ("Valve"). You must obey the GNU General Public License in all +* respects for all of the code used other than the HL Engine and MODs +* from Valve. If you modify this file, you may extend this exception +* to your version of the file, but you are not obligated to do so. If +* you do not wish to do so, delete this exception statement from your +* version. +* +*/ + +#pragma once + +#include "utlmemory.h" + +template +class CUtlVector +{ +public: + typedef T ElemType_t; + + // constructor, destructor + CUtlVector(int growSize = 0, int initSize = 0); + CUtlVector(T *pMemory, int numElements); + ~CUtlVector(); + + // features C++11 ranged based for + T *begin() { return &m_Memory[0]; } + T *end() { return &m_Memory[m_Size - 1]; } + + T const *begin() const { return &m_Memory[0]; } + T const *end() const { return &m_Memory[m_Size - 1]; } + + // Copy the array. + CUtlVector &operator=(const CUtlVector &other); + + // element access + T &operator[](int i); + T const &operator[](int i) const; + T &Element(int i); + T const &Element(int i) const; + + // Gets the base address (can change when adding elements!) + T *Base(); + T const *Base() const; + + // Returns the number of elements in the vector + // SIZE IS DEPRECATED! + int Count() const; + int Size() const; // don't use me! + + // Is element index valid? + bool IsValidIndex(int i) const; + static int InvalidIndex(void); + + // Adds an element, uses default constructor + int AddToHead(); + int AddToTail(); + int InsertBefore(int elem); + int InsertAfter(int elem); + + // Adds an element, uses copy constructor + int AddToHead(T const &src); + int AddToTail(T const &src); + int InsertBefore(int elem, T const &src); + int InsertAfter(int elem, T const &src); + + // Adds multiple elements, uses default constructor + int AddMultipleToHead(int num); + int AddMultipleToTail(int num, const T *pToCopy = nullptr); + int InsertMultipleBefore(int elem, int num, const T *pToCopy = nullptr); // If pToCopy is set, then it's an array of length 'num' and + int InsertMultipleAfter(int elem, int num); + + // Calls RemoveAll() then AddMultipleToTail. + void SetSize(int size); + void SetCount(int count); + + // Calls SetSize and copies each element. + void CopyArray(T const *pArray, int size); + + // Add the specified array to the tail. + int AddVectorToTail(CUtlVector const &src); + + // Finds an element (element needs operator== defined) + int Find(T const &src) const; + + bool HasElement(T const &src); + + // Makes sure we have enough memory allocated to store a requested # of elements + void EnsureCapacity(int num); + + // Makes sure we have at least this many elements + void EnsureCount(int num); + + // Element removal + void FastRemove(int elem); // doesn't preserve order + void Remove(int elem); // preserves order, shifts elements + void FindAndRemove(T const &src); // removes first occurrence of src, preserves order, shifts elements + void RemoveMultiple(int elem, int num); // preserves order, shifts elements + void RemoveAll(); // doesn't deallocate memory + + // Memory deallocation + void Purge(); + + // Purges the list and calls delete on each element in it. + void PurgeAndDeleteElements(); + + // Set the size by which it grows when it needs to allocate more memory. + void SetGrowSize(int size); + +protected: + // Can't copy this unless we explicitly do it! + CUtlVector(CUtlVector const &vec) { Assert(0); } + + // Grows the vector + void GrowVector(int num = 1); + + // Shifts elements.... + void ShiftElementsRight(int elem, int num = 1); + void ShiftElementsLeft(int elem, int num = 1); + + // For easier access to the elements through the debugger + void ResetDbgInfo(); + + CUtlMemory m_Memory; + int m_Size; + + // For easier access to the elements through the debugger + // it's in release builds so this can be used in libraries correctly + T *m_pElements; +}; + +// For easier access to the elements through the debugger +template +inline void CUtlVector::ResetDbgInfo() +{ + m_pElements = m_Memory.Base(); +} + +// constructor, destructor +template +inline CUtlVector::CUtlVector(int growSize, int initSize) : + m_Memory(growSize, initSize), m_Size(0) +{ + ResetDbgInfo(); +} + +template +inline CUtlVector::CUtlVector(T *pMemory, int numElements) : + m_Memory(pMemory, numElements), m_Size(0) +{ + ResetDbgInfo(); +} + +template +inline CUtlVector::~CUtlVector() +{ + Purge(); +} + +template +inline CUtlVector &CUtlVector::operator=(const CUtlVector &other) +{ + CopyArray(other.Base(), other.Count()); + return *this; +} + +// element access +template +inline T &CUtlVector::operator[](int i) +{ + Assert(IsValidIndex(i)); + return m_Memory[i]; +} + +template +inline T const &CUtlVector::operator[](int i) const +{ + Assert(IsValidIndex(i)); + return m_Memory[i]; +} + +template +inline T &CUtlVector::Element(int i) +{ + Assert(IsValidIndex(i)); + return m_Memory[i]; +} + +template +inline T const &CUtlVector::Element(int i) const +{ + Assert(IsValidIndex(i)); + return m_Memory[i]; +} + +// Gets the base address (can change when adding elements!) +template +inline T *CUtlVector::Base() +{ + return m_Memory.Base(); +} + +template +inline T const *CUtlVector::Base() const +{ + return m_Memory.Base(); +} + +// Count +template +inline int CUtlVector::Size() const +{ + return m_Size; +} + +template +inline int CUtlVector::Count() const +{ + return m_Size; +} + +// Is element index valid? +template +inline bool CUtlVector::IsValidIndex(int i) const +{ + return (i >= 0) && (i < m_Size); +} + +// Returns in invalid index +template +inline int CUtlVector::InvalidIndex(void) +{ + return -1; +} + +// Grows the vector +template +void CUtlVector::GrowVector(int num) +{ + if (m_Size + num - 1 >= m_Memory.NumAllocated()) + { + m_Memory.Grow(m_Size + num - m_Memory.NumAllocated()); + } + + m_Size += num; + ResetDbgInfo(); +} + +// Makes sure we have enough memory allocated to store a requested # of elements +template +void CUtlVector::EnsureCapacity(int num) +{ + m_Memory.EnsureCapacity(num); + ResetDbgInfo(); +} + +// Makes sure we have at least this many elements +template +void CUtlVector::EnsureCount(int num) +{ + if (Count() < num) + AddMultipleToTail(num - Count()); +} + +// Shifts elements +template +void CUtlVector::ShiftElementsRight(int elem, int num) +{ + Assert(IsValidIndex(elem) || (m_Size == 0) || (num == 0)); + int numToMove = m_Size - elem - num; + if ((numToMove > 0) && (num > 0)) + memmove(&Element(elem+num), &Element(elem), numToMove * sizeof(T)); +} + +template +void CUtlVector::ShiftElementsLeft(int elem, int num) +{ + Assert(IsValidIndex(elem) || (m_Size == 0) || (num == 0)); + int numToMove = m_Size - elem - num; + if ((numToMove > 0) && (num > 0)) + { + memmove(&Element(elem), &Element(elem + num), numToMove * sizeof(T)); + +#ifdef _DEBUG + memset(&Element(m_Size-num), 0xDD, num * sizeof(T)); +#endif + } +} + +// Adds an element, uses default constructor +template +inline int CUtlVector::AddToHead() +{ + return InsertBefore(0); +} + +template +inline int CUtlVector::AddToTail() +{ + return InsertBefore(m_Size); +} + +template +inline int CUtlVector::InsertAfter(int elem) +{ + return InsertBefore(elem + 1); +} + +template +int CUtlVector::InsertBefore(int elem) +{ + // Can insert at the end + Assert((elem == Count()) || IsValidIndex(elem)); + + GrowVector(); + ShiftElementsRight(elem); + Construct(&Element(elem)); + return elem; +} + +// Adds an element, uses copy constructor +template +inline int CUtlVector::AddToHead(T const &src) +{ + return InsertBefore(0, src); +} + +template< class T > +inline int CUtlVector::AddToTail(T const &src) +{ + return InsertBefore(m_Size, src); +} + +template< class T > +inline int CUtlVector::InsertAfter(int elem, T const &src) +{ + return InsertBefore(elem + 1, src); +} + +template< class T > +int CUtlVector::InsertBefore(int elem, T const &src) +{ + // Can insert at the end + Assert((elem == Count()) || IsValidIndex(elem)); + + GrowVector(); + ShiftElementsRight(elem); + CopyConstruct(&Element(elem), src); + return elem; +} + +// Adds multiple elements, uses default constructor +template +inline int CUtlVector::AddMultipleToHead(int num) +{ + return InsertMultipleBefore(0, num); +} + +template +inline int CUtlVector::AddMultipleToTail(int num, const T *pToCopy) +{ + return InsertMultipleBefore(m_Size, num, pToCopy); +} + +template +int CUtlVector::InsertMultipleAfter(int elem, int num) +{ + return InsertMultipleBefore(elem + 1, num); +} + +template +void CUtlVector::SetCount(int count) +{ + RemoveAll(); + AddMultipleToTail(count); +} + +template +inline void CUtlVector::SetSize(int size) +{ + SetCount(size); +} + +template +void CUtlVector::CopyArray(T const *pArray, int size) +{ + SetSize(size); + for(int i = 0; i < size; i++) + { + (*this)[i] = pArray[i]; + } +} + +template +int CUtlVector::AddVectorToTail(CUtlVector const &src) +{ + int base = Count(); + + // Make space. + AddMultipleToTail(src.Count()); + + // Copy the elements. + for (int i = 0; i < src.Count(); i++) + { + (*this)[base + i] = src[i]; + } + + return base; +} + +template +inline int CUtlVector::InsertMultipleBefore(int elem, int num, const T *pToInsert) +{ + if(num == 0) + return elem; + + // Can insert at the end + Assert((elem == Count()) || IsValidIndex(elem)); + + GrowVector(num); + ShiftElementsRight(elem, num); + + // Invoke default constructors + for (int i = 0; i < num; i++) + { + Construct(&Element(elem+i)); + } + + // Copy stuff in? + if (pToInsert) + { + for (int i = 0; i < num; i++) + { + Element(elem+i) = pToInsert[i]; + } + } + + return elem; +} + +// Finds an element (element needs operator== defined) +template +int CUtlVector::Find(T const &src) const +{ + for (int i = 0; i < Count(); i++) + { + if (Element(i) == src) + return i; + } + + return InvalidIndex(); +} + +template +bool CUtlVector::HasElement(T const &src) +{ + return (Find(src) >= 0); +} + +// Element removal +template +void CUtlVector::FastRemove(int elem) +{ + Assert(IsValidIndex(elem)); + + Destruct(&Element(elem)); + if (m_Size > 0) + { + memcpy(&Element(elem), &Element(m_Size - 1), sizeof(T)); + m_Size--; + } +} + +template +void CUtlVector::Remove(int elem) +{ + Destruct(&Element(elem)); + ShiftElementsLeft(elem); + m_Size--; +} + +template +void CUtlVector::FindAndRemove(T const &src) +{ + int elem = Find(src); + if (elem != InvalidIndex()) + { + Remove(elem); + } +} + +template +void CUtlVector::RemoveMultiple(int elem, int num) +{ + Assert(IsValidIndex(elem)); + Assert(elem + num <= Count()); + + for (int i = elem + num; --i >= elem;) + Destruct(&Element(i)); + + ShiftElementsLeft(elem, num); + m_Size -= num; +} + +template +void CUtlVector::RemoveAll() +{ + for (int i = m_Size; --i >= 0;) + Destruct(&Element(i)); + + m_Size = 0; +} + +// Memory deallocation +template +void CUtlVector::Purge() +{ + RemoveAll(); + m_Memory.Purge(); + ResetDbgInfo(); +} + +template +inline void CUtlVector::PurgeAndDeleteElements() +{ + for (int i = 0; i < m_Size; i++) + delete Element(i); + + Purge(); +} + +template +void CUtlVector::SetGrowSize(int size) +{ + m_Memory.SetGrowSize(size); +} diff --git a/dep/rehlsdk/public/vgui/VGUI.h b/dep/rehlsdk/public/vgui/VGUI.h new file mode 100644 index 0000000..cdaed0d --- /dev/null +++ b/dep/rehlsdk/public/vgui/VGUI.h @@ -0,0 +1,30 @@ +#pragma once + +#ifdef _WIN32 + #define VGUI2_LIB "vgui2.dll" +#else + #define VGUI2_LIB "vgui2.so" +#endif // _WIN32 + +namespace vgui2 +{ +// handle to an internal vgui panel +// this is the only handle to a panel that is valid across dll boundaries +typedef unsigned int VPANEL; + +// handles to vgui objects +// NULL values signify an invalid value +typedef unsigned long HScheme; +typedef unsigned long HTexture; +typedef unsigned long HCursor; + +typedef int HContext; +typedef unsigned long HPanel; +typedef unsigned long HFont; + +// the value of an invalid font handle +const VPANEL NULL_PANEL = 0; +const HFont INVALID_FONT = 0; +const HPanel INVALID_PANEL = 0xffffffff; + +} // namespace vgui2 diff --git a/msvc/Reunion.sln b/msvc/Reunion.sln new file mode 100644 index 0000000..25496bd --- /dev/null +++ b/msvc/Reunion.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.34301.259 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "Reunion", "..\reunion\msvc\Reunion.vcxproj", "{9A72E8DC-7667-46C1-899D-1E8B939564D2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {9A72E8DC-7667-46C1-899D-1E8B939564D2}.Debug|Win32.ActiveCfg = Debug|Win32 + {9A72E8DC-7667-46C1-899D-1E8B939564D2}.Debug|Win32.Build.0 = Debug|Win32 + {9A72E8DC-7667-46C1-899D-1E8B939564D2}.Release|Win32.ActiveCfg = Release|Win32 + {9A72E8DC-7667-46C1-899D-1E8B939564D2}.Release|Win32.Build.0 = Release|Win32 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {E2C458B4-2E83-42FB-886A-7C3FCC19ECDF} + EndGlobalSection +EndGlobal diff --git a/reunion/CMakeLists.txt b/reunion/CMakeLists.txt new file mode 100644 index 0000000..6593ed4 --- /dev/null +++ b/reunion/CMakeLists.txt @@ -0,0 +1,175 @@ +#---------------------------------------- +# 1. Preparing build: +# rm -rf build +# mkdir build && cd build +# +# 2. Select compiler and build it +# - Compile with Clang: +# CC="clang" CXX="clang++" cmake .. +# make +# +# - Compile with Intel C++ Compiler: +# CC="icc" CXX="icpc" cmake .. +# make +# +# - Compile with GCC Compiler: +# cmake .. +# make +#---------------------------------------- + +cmake_minimum_required(VERSION 3.1) +project(reunion CXX) + +option(DEBUG "Build with debug information." OFF) +option(USE_STATIC_LIBSTDC "Enables static linking libstdc++." OFF) + +set(CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +# Avoid -fPIC option +set(CMAKE_SHARED_LIBRARY_CXX_FLAGS "") + +set(COMPILE_FLAGS "-m32 -U_FORTIFY_SOURCE") +set(LINK_FLAGS "-m32 -s") + +set(COMPILE_FLAGS "${COMPILE_FLAGS} -Wall -fno-exceptions -fno-builtin -Wno-unknown-pragmas -Wno-write-strings -fvisibility=hidden -fvisibility-inlines-hidden -fno-rtti") + +# Remove noxref code and data +set(COMPILE_FLAGS "${COMPILE_FLAGS} -ffunction-sections -fdata-sections") + +if (DEBUG) + set(COMPILE_FLAGS "${COMPILE_FLAGS} -g3 -O3 -s -ggdb") +else() + set(COMPILE_FLAGS "${COMPILE_FLAGS} -g0 -O3 -s -fno-stack-protector") +endif() + +# Check Intel C++ compiler +if ("$ENV{CXX}" MATCHES "icpc") + # + # -fp-model=precise + # ICC uses -fp-model fast=1 by default for more aggressive optimizations on floating-point calculations + # https://software.intel.com/content/www/us/en/develop/documentation/cpp-compiler-developer-guide-and-reference/top/compiler-reference/compiler-options/compiler-option-details/floating-point-options/fp-model-fp.html#fp-model-fp_GUID-99936BBA-1508-4E9F-AC09-FA98613CE2F5 + # + set(COMPILE_FLAGS "${COMPILE_FLAGS} \ + -fp-model=precise -msse2 -fomit-frame-pointer\ + -Qoption,cpp,--treat_func_as_string_literal_cpp\ + -inline-forceinline\ + -no-ansi-alias") + + set(LINK_FLAGS "${LINK_FLAGS} \ + -static-intel\ + -no-intel-extensions") + + if (NOT DEBUG) + set(COMPILE_FLAGS "${COMPILE_FLAGS} -ipo") + set(LINK_FLAGS "${LINK_FLAGS} -ipo") + endif() +else() + # Produce code optimized for the most common IA32/AMD64/EM64T processors. + # As new processors are deployed in the marketplace, the behavior of this option will change. + set(COMPILE_FLAGS "${COMPILE_FLAGS} \ + -mtune=generic -msse3\ + -fno-sized-deallocation -Wno-strict-aliasing") +endif() + +# GCC >= 8.3 +if (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 8.0) + set(COMPILE_FLAGS "${COMPILE_FLAGS} -fcf-protection=none") +endif() + +if (NOT DEBUG) + set(LINK_FLAGS "${LINK_FLAGS} \ + -Wl,-gc-sections -Wl,--version-script=\"${PROJECT_SOURCE_DIR}/../version_script.lds\"") +endif() + +#PROJECT_SOURCE_DIR - /mnt/d/GitHub/reunion/reunion + +set(PROJECT_SRC_DIR + "${PROJECT_SOURCE_DIR}/../reunion" + "${PROJECT_SOURCE_DIR}/../reunion/src" + "${PROJECT_SOURCE_DIR}/../reunion/version" +) + +set(PROJECT_HLSDK_DIR + "${PROJECT_SOURCE_DIR}/../dep/rehlsdk/common" + "${PROJECT_SOURCE_DIR}/../dep/rehlsdk/dlls" + "${PROJECT_SOURCE_DIR}/../dep/rehlsdk/engine" + "${PROJECT_SOURCE_DIR}/../dep/rehlsdk/pm_shared" + "${PROJECT_SOURCE_DIR}/../dep/rehlsdk/public" +) + +set(PROJECT_METAMOD_DIR + "${PROJECT_SOURCE_DIR}/../dep/metamod" +) + +set(REUNION_SRCS + "src/client_auth.cpp" + "src/dllapi.cpp" + "src/h_export.cpp" + "src/meta_api.cpp" + "src/murmur3.cpp" + "src/public_amalgamation.cpp" + "src/query_banlist.cpp" + "src/query_bugfix.cpp" + "src/query_limiter.cpp" + "src/reunion_api.cpp" + "src/reunion_authorizers.cpp" + "src/reunion_cfg.cpp" + "src/reunion_player.cpp" + "src/reunion_rehlds_api.cpp" + "src/reunion_utils.cpp" + "src/Rijndael.cpp" + "src/RijndaelChanged.cpp" + "src/sdk_util.cpp" + "src/server_info.cpp" + "src/sha2.cpp" + "src/Sizebuf.cpp" + "src/stdc++compat.cpp" +) + +add_library(reunion SHARED ${appversion.sh}) + +if (NOT TARGET appversion) + add_custom_target(appversion DEPENDS COMMAND "${PROJECT_SOURCE_DIR}/../version/appversion.sh" "${PROJECT_SOURCE_DIR}/..") +endif() + +add_dependencies(reunion appversion) + +target_include_directories(reunion PRIVATE + ${PROJECT_SRC_DIR} + ${PROJECT_HLSDK_DIR} + ${PROJECT_METAMOD_DIR} +) + +target_compile_definitions(reunion PRIVATE + linux + LINUX + _LINUX + __linux__ + NDEBUG + _GLIBCXX_USE_CXX11_ABI=0 + _stricmp=strcasecmp + _strnicmp=strncasecmp + _snprintf=snprintf +) + +target_sources(reunion PRIVATE + ${REUNION_SRCS} +) + +target_link_libraries(reunion PRIVATE + dl +) + +if (USE_STATIC_LIBSTDC) + target_compile_definitions(reunion PRIVATE BUILD_STATIC_LIBSTDC) + set(LINK_FLAGS "${LINK_FLAGS} -static-libgcc -static-libstdc++") +endif() + +set_target_properties(reunion PROPERTIES + OUTPUT_NAME reunion_mm_i386 + PREFIX "" + COMPILE_FLAGS ${COMPILE_FLAGS} + LINK_FLAGS ${LINK_FLAGS} + POSITION_INDEPENDENT_CODE OFF +) diff --git a/reunion/dist/Readme.tpl b/reunion/dist/Readme.tpl new file mode 100644 index 0000000..40bcd62 --- /dev/null +++ b/reunion/dist/Readme.tpl @@ -0,0 +1,77 @@ +Reunion is a plugin for metamod that allows p.47 and 48 no-steam clients to join the rehlds-based server. + +CURRENT VERSION: ${APP_VERSION_STRD} +For more information and updates please check http://cs.rin.ru/forum/viewtopic.php?f=29&t=69235 + +ARCHIVE CONTAINS: + amxx directory - some samples of AmxModX plugins that uses reunion functionality. + bin directory - binaries (libraries) for linux and windows. + public - C++ API for modders + Readme.txt - this file. + reunion.cfg - reunion configuration file. + +REQUIREMENTS: + - ReHLDS-based server + - metamod 1.20 or higher + +INSTALLATION: + 1. Go to /addons/ and make new directory named reunion + - it is a game directory; cstrike for Counter-Strike, valve for Half-Life, etc + 2. Copy reunion_mm.dll or reunion_mm_i386.so to /addons/reunion/ + 3. Go to metamod installation directory (usually its /addons/metamod/) and edit plugins.ini: + add this line for windows + win32 addons\reunion\reunion_mm.dll + or this for linux + linux addons/reunion/reunion_mm_i386.so + at the beginning of the file + 4. Copy reunion.cfg to server root or gamedir. + 5. Start the server. When server loads, type "meta list" in console. You'll see something like this: + + Currently loaded plugins: + description stat pend file vers src load unlod + [ 1] Reunion RUN - reunion_mm_i386. v${APP_VERSION_STRD} ini Start Never + [ 2] AMX Mod X RUN - amxmodx_mm_i386. v1.8.1.3 ini Start ANY + 2 plugins, 2 running + 6. If status is not "RUN", start server with "+log on +mp_logecho 1" parameters and look through console output. In 99% cases you'll find reason there. + 7. Installation of AmxModX plugins from amxx directory is not necessary. + +HOW TO CHANGE STEAMIDS OF CLIENTS + Use cid* options in AUTHID MANAGEMENT section of reunion.cfg + For example, if you want to assign steamids generated by IP for p47 clients that not support unique id generation, you should set: + cid_NoSteam47 = 3 for assigning STEAM_x:y:z steamid to these clients + cid_NoSteam47 = 4 for assigning VALVE_x:y:z steamid to these clients + + If you want to drop these clients, just set clientid to 5: + cid_NoSteam47 = 5 + And all p47 clients without emulators will be dropped with message that you can customize (see next section). + +HOW TO CHANGE REJECT MESSAGES WHEN CLIENTID IS 5 (DEPRECATED) + This could be done using these cvars: + dp_rejmsg_steam for legit steam (cid_Steam) clients + dp_rejmsg_nosteam47 for no-steam p47 (cid_NoSteam47) clients + dp_rejmsg_nosteam48 for no-steam p48 (cid_NoSteam48) clients + dp_rejmsg_hltv for HLTV (cid_HLTV) clients + dp_rejmsg_pending for unathorized (cid_cid_SteamPending) clients + dp_rejmsg_revemu for revEmu (>= 9.74 && <= 9.82) clients + dp_rejmsg_steamemu for steamEmu clients + dp_rejmsg_oldrevemu for old revEmu clients (< 9.74) + dp_rejmsg_avsmp for AVSMP clients + dp_rejmsg_revemu_sc2009 for revEmu (> 9.82) and SteamClient2009 clients + dp_rejmsg_sxei for clients with sXe Injected if EnableSXEIdGeneration is set to 1 + dp_rejmsg_revemu2013 for revEmu 2013 clients + dp_rejmsg_sse3 for SmartSteamEmu3 clients + + Just put message to them and it will be displayed for rejected clients. + + Example, a part of server.cfg: + dp_rejmsg_nosteam47 "Sorry, you're using old client, download a new one and come back ;)" + +HOW TO GET CLIENT PROTOCOL IN AMXX: + check the amxx/reu_test.sma. This is sample plugin that outputs protocol number when client connecting. + NOTE: this is _sample_ plugin and its installation is not necessary. + +THANKS TO: + dreamstalker for ReHLDS project; + all people who helped with development of dproto. + kazakh758 for testing a fix of issue related to the client hanging on connect. + BombermaG for finding a bug in query emulator diff --git a/reunion/dist/Readme.txt b/reunion/dist/Readme.txt new file mode 100644 index 0000000..6f4eedd --- /dev/null +++ b/reunion/dist/Readme.txt @@ -0,0 +1,76 @@ +Reunion is a plugin for metamod that allows p.47 and 48 no-steam clients to join the rehlds-based server. + +CURRENT VERSION: 0.2.0.13 +For more information and updates please check http://cs.rin.ru/forum/viewtopic.php?f=29&t=69235 + +ARCHIVE CONTAINS: + amxx directory - some samples of AmxModX plugins that uses reunion functionality. + bin directory - binaries (libraries) for linux and windows. + public - C++ API for modders + Readme.txt - this file. + reunion.cfg - reunion configuration file. + +REQUIREMENTS: + - ReHLDS-based server + - metamod 1.20 or higher + +INSTALLATION: + 1. Go to /addons/ and make new directory named reunion + - it is a game directory; cstrike for Counter-Strike, valve for Half-Life, etc + 2. Copy reunion_mm.dll or reunion_mm_i386.so to /addons/reunion/ + 3. Go to metamod installation directory (usually its /addons/metamod/) and edit plugins.ini: + add this line for windows + win32 addons\reunion\reunion_mm.dll + or this for linux + linux addons/reunion/reunion_mm_i386.so + at the beginning of the file + 4. Copy reunion.cfg to server root or gamedir. + 5. Start the server. When server loads, type "meta list" in console. You'll see something like this: + + Currently loaded plugins: + description stat pend file vers src load unlod + [ 1] Reunion RUN - reunion_mm_i386. v0.2.0.13 ini Start Never + [ 2] AMX Mod X RUN - amxmodx_mm_i386. v1.8.1.3 ini Start ANY + 2 plugins, 2 running + 6. If status is not "RUN", start server with "+log on +mp_logecho 1" parameters and look through console output. In 99% cases you'll find reason there. + 7. Installation of AmxModX plugins from amxx directory is not necessary. + +HOW TO CHANGE STEAMIDS OF CLIENTS + Use cid* options in AUTHID MANAGEMENT section of reunion.cfg + For example, if you want to assign steamids generated by IP for p47 clients that not support unique id generation, you should set: + cid_NoSteam47 = 3 for assigning STEAM_x:y:z steamid to these clients + cid_NoSteam47 = 4 for assigning VALVE_x:y:z steamid to these clients + + If you want to drop these clients, just set clientid to 5: + cid_NoSteam47 = 5 + And all p47 clients without emulators will be dropped with message that you can customize (see next section). + +HOW TO CHANGE REJECT MESSAGES WHEN CLIENTID IS 5 (DEPRECATED) + This could be done using these cvars: + dp_rejmsg_steam for legit steam (cid_Steam) clients + dp_rejmsg_nosteam47 for no-steam p47 (cid_NoSteam47) clients + dp_rejmsg_nosteam48 for no-steam p48 (cid_NoSteam48) clients + dp_rejmsg_hltv for HLTV (cid_HLTV) clients + dp_rejmsg_pending for unathorized (cid_cid_SteamPending) clients + dp_rejmsg_revemu for revEmu (>= 9.74 && <= 9.82) clients + dp_rejmsg_steamemu for steamEmu clients + dp_rejmsg_oldrevemu for old revEmu clients (< 9.74) + dp_rejmsg_avsmp for AVSMP clients + dp_rejmsg_revemu_sc2009 for revEmu (> 9.82) and SteamClient2009 clients + dp_rejmsg_sxei for clients with sXe Injected if EnableSXEIdGeneration is set to 1 + dp_rejmsg_revemu2013 for revEmu 2013 clients + + Just put message to them and it will be displayed for rejected clients. + + Example, a part of server.cfg: + dp_rejmsg_nosteam47 "Sorry, you're using old client, download a new one and come back ;)" + +HOW TO GET CLIENT PROTOCOL IN AMXX: + check the amxx/reu_test.sma. This is sample plugin that outputs protocol number when client connecting. + NOTE: this is _sample_ plugin and its installation is not necessary. + +THANKS TO: + dreamstalker for ReHLDS project; + all people who helped with development of dproto. + kazakh758 for testing a fix of issue related to the client hanging on connect. + BombermaG for finding a bug in query emulator diff --git a/reunion/dist/reunion.cfg b/reunion/dist/reunion.cfg new file mode 100644 index 0000000..6d55b29 --- /dev/null +++ b/reunion/dist/reunion.cfg @@ -0,0 +1,244 @@ +# ======================================================== +# REUNION CONFIGURATION +# ======================================================== + +# +# General rule for modifying this file: +# DONT CHANGE ANYTHING IF YOU DONT KNOW WHAT IT MEANS! +# + + +# ======================================================== +# AUTHID MANAGEMENT +# ======================================================== + +# ClientID types (for cid_* options) +# 1: Real (or generated by HW) steam (STEAM_xx:xx:xx) +# 2: Real (or generated by HW) valve (VALVE_xx:xx:xx) +# 3: STEAM_ by IP +# 4: VALVE_ by IP +# 5: Deprecated - client will be rejected +# 6: reserved for future use +# 7: HLTV +# 8: STEAM_ID_LAN +# 9: STEAM_ID_PENDING +# 10: VALVE_ID_LAN +# 11: VALVE_ID_PENDING +# 12: STEAM_666:88:666 + +# Use these options to set authid's for clients + +### AUTH CONTROL ### + +# For Legit Steam clients (default is real STEAM_xx:xx:xx [1]) +cid_Steam = 1 + +# Client recognized as pending when they sucessfully authorized, but did not get steam id +# REMARK: Actually, it got steamid, but it is useless (STEAM_0:0:0 for example) +# default is Deprecated [5] +cid_SteamPending = 5 + +# for HLTV (default is Deprecated [5]) +cid_HLTV = 5 + +# for p.47 clients that do not support unique id generation (default is Deprecated [5]) +cid_NoSteam47 = 5 + +# for p.48 clients that do not support unique id generation (default is Deprecated [5]) +cid_NoSteam48 = 5 + +# For players having revEmu ( >= 9.74) on client-side: +# default is real STEAM_xx:xx:xx [1] +cid_RevEmu = 1 + +# For players having RevEmu 2013 on client-side: +# default is real STEAM_xx:xx:xx [1] +cid_RevEmu2013 = 1 + +# For players having SteamClient 2009 / revEmu > 9.82 on client-side: +# default is real STEAM_xx:xx:xx [1] +cid_SC2009 = 1 + +# For players having old revEmu on client-side: +# default is real STEAM_xx:xx:xx [1] +cid_OldRevEmu = 1 + +# For players having hCupa's SteamEmu on client-side: +# default is real STEAM_xx:xx:xx [1] +cid_SteamEmu = 1 + +# For players having AVSMP (Cracked Steam) on client-side: +# default is real STEAM_xx:xx:xx [1] +cid_AVSMP = 1 + +# For SETTI ServerScanner +# default is STEAM_xx:xx:xx generated by IP [3] +cid_Setti = 3 + +# For SXEI Clients +# default is real STEAM_xx:xx:xx [1] +cid_SXEI = 1 + +# For players having SmartSteamEmu > 1.2.4 on client-side: +# default is real STEAM_xx:xx:xx [1] +cid_SSE3 = 1 + + +### AUTH SETTINGS ### + +# Authorization protocols version. All steamdid's of non-steams players will be changed in common with this value. +# 1: DProto (deprecated) +# 2: Reunion 2015-2018 +# 3: Reunion new (recommended) +AuthVersion = 3 + +# SteamIdHashSalt (string) +# Salt string for SteamIDs hashing. Irreversibly changes SteamIDs. Prevents SteamID stealing. +# Should be more than 31 chars length. If string is empty, hashing is not applied (AuthVersion < 3) or Reunion init will be failed (AuthVersion >= 3). +SteamIdHashSalt = + +# SC2009_RevCompatMode (0 / 1) +# Enable fix to make steamids generated for SC2009 compatible with revEmu. Can't be disabled with AuthVersion >= 3. +# Default: 1 +SC2009_RevCompatMode = 1 + +# EnableSXEIdGeneration (0 / 1) +# Turns on steamid generation based on info sent by sXeI client +# Enable this ONLY if you have sXeI server installed! +# Default: 0 +EnableSXEIdGeneration = 0 + +# EnableGenPrefix2 (0 / 1) +# Enable second prefix (STEAM_*:0/1:****) for generated authids. Reduces chance of authid collisions. Works only with configured SteamIdHashSalt. Can't be disabled with AuthVersion >= 3. +# Default: 0 +EnableGenPrefix2 = 0 + +# HLTVExcept_IP (ip addr) +# HLTV from this IP will be able to join the server even if cid_HLTV is set to 5 (deprecated) +HLTVExcept_IP = 127.0.0.1 + + +### AUTHID PREFIXES ### + +# This config section will be ignored when AuthVersion > 2. + +# IPGen_Prefix1 (int) +# STEAM_a:b:c +# first prefix (a) for authids generated by IP +IPGen_Prefix1 = 0 + +# IPGen_Prefix2 (int) +# STEAM_a:b:c +# second prefix (b) for authids generated by IP +IPGen_Prefix2 = 4 + +# Native_Prefix1 (int) +# STEAM_a:b:c +# first prefix (a) for authids generated by native auth method (Steam) +Native_Prefix1 = 0; + +# RevEmu_Prefix1 (int) +# STEAM_a:b:c +# first prefix (a) for authids generated by RevEmu +RevEmu_Prefix1 = 1; + +# RevEmu2013_Prefix1 (int) +# STEAM_a:b:c +# first prefix (a) for authids generated by RevEmu2013 +RevEmu2013_Prefix1 = 1; + +# SC2009_Prefix1 (int) +# STEAM_a:b:c +# first prefix (a) for authids generated by Steamclient 2009 +SC2009_Prefix1 = 1; + +# OldRevEmu_Prefix1 (int) +# STEAM_a:b:c +# first prefix (a) for authids generated by old RevEmu +OldRevEmu_Prefix1 = 2; + +# SteamEmu_Prefix1 (int) +# STEAM_a:b:c +# first prefix (a) for authids generated by SteamEmu +SteamEmu_Prefix1 = 3; + +# SteamEmu_Prefix1 (int) +# STEAM_a:b:c +# first prefix (a) for authids assigned for AVSMP Clients (Cracked steam) +AVSMP_Prefix1 = 4; + +# Setti_Prefix1 (int) +# STEAM_a:b:c +# first prefix (a) for authids assigned for Setti server scanner +Setti_Prefix1 = 5; + +# SXEI_Prefix1 (int) +# STEAM_a:b:c +# first prefix (a) for authids assigned for sXeI clients +SXEI_Prefix1 = 6; + +# SSE3_Prefix1 (int) +# STEAM_a:b:c +# first prefix (a) for authids assigned for SSE3 +SSE3_Prefix1 = 7; + +# Note that banid will use steamid WITHOUT any prefixes! + + + +# ======================================================== +# SERVER QUERIES MANAGEMENT +# ======================================================== + +# ServerInfoAnswerType (0/1/2) +# Sets server answer type for query requests +# 0 = New style (Steam) (recommended) +# 1 = Old Style (GoldSource Engine) +# 2 = Hybrid mode - Server is visible anywhere, but there are 3 packets generated for every serverinfo request +# Default: 0 +ServerInfoAnswerType = 0 + +# FixBuggedQuery (0 / 1) +# Enable fix for clients with bugged serverbrowser. Prevents hanging on connect. +# Default: 1 +FixBuggedQuery = 1 + +# EnableQueryLimiter (0 / 1) +# Enable ratelimit for server queries (TSource, players, etc). You can use 0 if external protection solutions used. +# Default: 1 +EnableQueryLimiter = 1 + +# QueryFloodBanLevel (320 - 2048). +# Queries/sec level for ip ban. Maximum measured legit level is 80/sec. +# Default: 400 +QueryFloodBanLevel = 400 + +# QueryFloodBanTime (0 - 60). +# Ban time in minutes for server query flooding. Use 0 to disable bans (block only). +# Default: 10 +QueryFloodBanTime = 10 + +[QueryLimiterExceptIP] +#127.0.0.1 + +# AllowSplitPackets (0 / 1) +# Allow splitting of outgoing packets if they size are greater than 1400. Used in original steamclient, but does not supported by some monitorings. +# Default: 0 +AllowSplitPackets = 0 + +# IDClientsLimit (0 - 32) +# Maximum number of clients from single steamid. Useful for debugging with multiple instances clients. +# 0 means unlimit +# Default: 1 +IDClientsLimit = 1 + +# ======================================================== +# OTHER STUFF +# ======================================================== + +# LoggingMode: +# 0 = None +# 1 = Console +# 2 = Log Files +# 3 = Both +LoggingMode = 0 diff --git a/reunion/extra/reu_test.sma b/reunion/extra/reu_test.sma new file mode 100644 index 0000000..07d7d6c --- /dev/null +++ b/reunion/extra/reu_test.sma @@ -0,0 +1,111 @@ +/* + This sample plugin shows how to get information about client's protocol and Steam ID. (plugin will write this info when client connecting) + +*/ + +#include +#include + + +#define DP_AUTH_NONE 0 +#define DP_AUTH_DPROTO 1 +#define DP_AUTH_STEAM 2 +#define DP_AUTH_STEAMEMU 3 +#define DP_AUTH_REVEMU 4 +#define DP_AUTH_OLDREVEMU 5 +#define DP_AUTH_HLTV 6 +#define DP_AUTH_SC2009 7 +#define DP_AUTH_AVSMP 8 +#define DP_AUTH_SXEI 9 +#define DP_AUTH_REVEMU2013 10 + + +// +// pointers to dp_r_protocol and dp_r_id_provider cvars +// reunion will store information in these cvars + +new pcv_dp_r_protocol +new pcv_dp_r_id_provider + +public plugin_init() +{ + register_plugin("reunion testing", "1", "") + + // + // Initialize cvar pointers + // + pcv_dp_r_protocol = get_cvar_pointer ("dp_r_protocol") + pcv_dp_r_id_provider = get_cvar_pointer ("dp_r_id_provider") + +} + +public client_connect(id) +{ + if (!pcv_dp_r_protocol || !pcv_dp_r_id_provider) + { + log_amx ("cant find dp_r_protocol or dp_r_id_provider cvars") + return PLUGIN_HANDLED + } + + /* + The "dp_clientinfo" command are exported by reunion. The syntax is: + dp_clientinfo + where id is slot index (1 to 32) + After executing this command reunion will set dp_r_protocol and dp_r_id_provider cvars. + The dp_r_protocol keeps client's protocol + The dp_r_id_provider cvar will be set to: + 1: if client's steam id assigned by reunion (player uses no-steam client without emulator) + 2: if client's steam id assigned by native steam library (or by another soft that emulates this library, server-side revEmu for example) + 3: if client's steam id assigned by reunion's SteamEmu emulator + 4: if client's steam id assigned by reunion's revEmu emulator + 5: if client's steam id assigned by reunion's old revEmu emulator + 6: if client is HLTV + 7: if client's steam id assigned by reunion's SC2009 emulator + 8: if client's steam id assigned by reunion's AVSMP emulator + 9: if client's steam id assigned by SXEI's *HID userinfo field + 10: if client's steam id assigned by reunion's revEmu2013 emulator + + If slot is empty, both dp_r_protocol and dp_r_id_provider cvars will be set to 0 + If slot is invalid (id < 1 or id > max players), both dp_r_protocol and dp_r_id_provider cvars will be set to -1 + */ + + // + // add command to queue + // + server_cmd("dp_clientinfo %d", id) + + // + // make server to execute all queued commands + // + server_exec() + + // + // now parse cvar values + // + new proto = get_pcvar_num(pcv_dp_r_protocol) + new authprov = get_pcvar_num(pcv_dp_r_id_provider) + new auth_prov_str[32] + new user_name[33] + + switch (authprov) + { + case DP_AUTH_NONE: copy(auth_prov_str, 32, "N/A") //slot is free + case DP_AUTH_DPROTO: copy(auth_prov_str, 32, "dproto") + case DP_AUTH_STEAM: copy(auth_prov_str, 32, "Steam(Native)") + case DP_AUTH_STEAMEMU: copy(auth_prov_str, 32, "SteamEmu") + case DP_AUTH_REVEMU: copy(auth_prov_str, 32, "revEmu") + case DP_AUTH_OLDREVEMU: copy(auth_prov_str, 32, "old revEmu") + case DP_AUTH_HLTV: copy(auth_prov_str, 32, "HLTV") + case DP_AUTH_SC2009: copy(auth_prov_str, 32, "SteamClient2009") + case DP_AUTH_AVSMP: copy(auth_prov_str, 32, "AVSMP") + case DP_AUTH_SXEI: copy(auth_prov_str, 32, "SXEI") + case DP_AUTH_REVEMU2013: copy(auth_prov_str, 32, "RevEmu2013") + default: copy(auth_prov_str, 32, "Erroneous") //-1 if slot id is invalid + } + + get_user_name (id, user_name, 33) + + server_print("User %s (%d) uses protocol %d; SteamID assigned by %s", user_name, id, proto, auth_prov_str) + + return PLUGIN_HANDLED +} diff --git a/reunion/extra/updatehint.sma b/reunion/extra/updatehint.sma new file mode 100644 index 0000000..51d12b3 --- /dev/null +++ b/reunion/extra/updatehint.sma @@ -0,0 +1,204 @@ +/* AMXModX Script +* +* Title: Update Client Hint +* Author: Lev/Crock +* +* Changelog: +* +* 23.03.2010 +* - Added HLTV recognition +* +* 04.08.2010 +* - Added new emulators support (AVSMP, SC2009) +* +* 19.10.2010 +* - Fixed AVSMP and SteamClient2009 support +* +* 07.08.2013 +* - Added sXeI support +* - Added RevEmu2013 support +* +*/ + +#pragma semicolon 1 +#pragma ctrlchar '\' + +#include +#include +#include +#include +#include + +#define DP_AUTH_NONE 0 // "N/A" - slot is free +#define DP_AUTH_DPROTO 1 // dproto +#define DP_AUTH_STEAM 2 // Native Steam +#define DP_AUTH_STEAMEMU 3 // SteamEmu +#define DP_AUTH_REVEMU 4 // RevEmu +#define DP_AUTH_OLDREVEMU 5 // Old RevEmu +#define DP_AUTH_HLTV 6 // HLTV +#define DP_AUTH_SC2009 7 // SteamClient 2009 +#define DP_AUTH_AVSMP 8 // AVSMP +#define DP_AUTH_SXEI 9 // sXe Injected +#define DP_AUTH_REVEMU2013 10 // RevEmu 2013 + +new const PLUGIN[] = "UpdateHint"; +new const VERSION[] = "1.3"; +new const AUTHOR[] = "Lev"; + +const BASE_TASK_ID_HINT = 3677; // random number +const BASE_TASK_ID_KICK = 6724; // random number +const MIN_SHOW_INTERVAL = 20; // minimum constrain for hint show interval +const MAX_URL_LENGTH = 70; // max length of the URL + +new bool:playerPutOrAuth[33]; // Player was put in server or auth. + +new pcvar_uh_url; +new pcvar_uh_interval; +new pcvar_uh_kickinterval; +new pcvar_dp_r_protocol; +new pcvar_dp_r_id_provider; + +public plugin_init() +{ + register_plugin(PLUGIN, VERSION, AUTHOR); + register_cvar("updatehint", VERSION, FCVAR_SERVER | FCVAR_SPONLY | FCVAR_UNLOGGED); + + register_dictionary("updatehint.txt"); + + pcvar_uh_url = register_cvar("uh_url", "http://some.addr/somefile"); // URL where player can goto to download new client. + pcvar_uh_interval = register_cvar("uh_interval", "60.0"); // Interval between hint shows. + pcvar_uh_kickinterval = register_cvar("uh_kickinterval", "0"); // Interval bwfoew kick client. + pcvar_dp_r_protocol = get_cvar_pointer ("dp_r_protocol"); // Reunion interface. + pcvar_dp_r_id_provider = get_cvar_pointer ("dp_r_id_provider"); // Reunion interface. +} + +public client_connect(id) +{ + playerPutOrAuth[id] = false; +} + +public client_authorized(id) +{ + if (playerPutOrAuth[id]) + { + return check_client_type(id); + } + playerPutOrAuth[id] = true; + return PLUGIN_CONTINUE; +} + +public client_putinserver(id) +{ + if (playerPutOrAuth[id]) + { + return check_client_type(id); + } + playerPutOrAuth[id] = true; + return PLUGIN_CONTINUE; +} + +stock NeedShowUpdateMsg(proto, authprov) +{ + if (authprov == DP_AUTH_HLTV) + return false; + + if (proto < 48) + return true; + + if (authprov == DP_AUTH_STEAM || + authprov == DP_AUTH_REVEMU || + authprov == DP_AUTH_SC2009 || + authprov == DP_AUTH_AVSMP || + authprov == DP_AUTH_SXEI || + authprov == DP_AUTH_REVEMU2013) + return false; + + return true; +} + +check_client_type(id) +{ + if (!pcvar_dp_r_protocol || !pcvar_dp_r_id_provider) + return PLUGIN_CONTINUE; + + server_cmd("dp_clientinfo %d", id); + server_exec(); + + new proto = get_pcvar_num(pcvar_dp_r_protocol); + new authprov = get_pcvar_num(pcvar_dp_r_id_provider); + + switch (authprov) + { + case DP_AUTH_DPROTO: + console_print(0, "Protocol: %d, authprovider: %s", proto, "DPROTO"); + case DP_AUTH_STEAM: + console_print(0, "Protocol: %d, authprovider: %s", proto, "STEAM"); + case DP_AUTH_REVEMU: + console_print(0, "Protocol: %d, authprovider: %s", proto, "REVEMU"); + case DP_AUTH_STEAMEMU: + console_print(0, "Protocol: %d, authprovider: %s", proto, "STEAMEMU"); + case DP_AUTH_OLDREVEMU: + console_print(0, "Protocol: %d, authprovider: %s", proto, "OLDREVEMU"); + case DP_AUTH_HLTV: + console_print(0, "Protocol: %d, authprovider: %s", proto, "HLTV"); + case DP_AUTH_SC2009: + console_print(0, "Protocol: %d, authprovider: %s", proto, "SteamClient2009/revEmu"); + case DP_AUTH_AVSMP: + console_print(0, "Protocol: %d, authprovider: %s", proto, "AVSMP"); + case DP_AUTH_SXEI: + console_print(0, "Protocol: %d, authprovider: %s", proto, "SXEI"); + case DP_AUTH_REVEMU2013: + console_print(0, "Protocol: %d, authprovider: %s", proto, "REVEMU2013"); + } + + if (NeedShowUpdateMsg(proto, authprov)) + { + set_task(get_uh_interval(), "show_update_hint", BASE_TASK_ID_HINT + id, _, _, "b"); + new kick_interval = get_pcvar_num(pcvar_uh_kickinterval); + if (kick_interval > 0) + set_task(float(kick_interval), "kick_client", BASE_TASK_ID_KICK + id); + } + + return PLUGIN_CONTINUE; +} + +public client_disconnect(id) +{ + remove_task(BASE_TASK_ID_HINT + id); + remove_task(BASE_TASK_ID_KICK + id); +} + +Float:get_uh_interval() +{ + new interval = get_pcvar_num(pcvar_uh_interval); + // Check to be no less then minimum value + return float((interval < MIN_SHOW_INTERVAL ) ? MIN_SHOW_INTERVAL : interval); +} + +public show_update_hint(id) +{ + id -= BASE_TASK_ID_HINT; + + if (0 > id || id > 31) + return; + + new url[MAX_URL_LENGTH]; + get_pcvar_string(pcvar_uh_url, url, charsmax(url)); + set_hudmessage(255, 100, 100, -1.0, 0.35, 0, 3.0, 5.0, 0.1, 0.1, 4); + show_hudmessage(id, "%L", id, "HUDHINT"); + client_print(id, print_chat, "%L", id, "CHATHINT", url); +} + +public kick_client(id) +{ + id -= BASE_TASK_ID_KICK; + + if (0 > id || id > 31) + return; + + new url[MAX_URL_LENGTH]; + get_pcvar_string(pcvar_uh_url, url, charsmax(url)); + client_print(id, print_chat, "%L", id, "CHATHINT", url); + new userid = get_user_userid(id); + server_cmd("kick #%d \"%L\"", userid, id, "HUDHINT"); +} diff --git a/reunion/extra/updatehint.txt b/reunion/extra/updatehint.txt new file mode 100644 index 0000000..4788341 --- /dev/null +++ b/reunion/extra/updatehint.txt @@ -0,0 +1,7 @@ +[en] +HUDHINT = Your client is outdated. Check chat and console for download URL. +CHATHINT = Download new client @ %s + +[ru] +HUDHINT = TBOU KJIUEHT YCTAPEJI. CMOTPU CCbIJIKY B 4ATE U B KOHCOJIU. +CHATHINT = Cka4au HoBbIU kJIUEHT TYT: %s diff --git a/reunion/msvc/PostBuild.bat b/reunion/msvc/PostBuild.bat new file mode 100644 index 0000000..14c1756 --- /dev/null +++ b/reunion/msvc/PostBuild.bat @@ -0,0 +1,78 @@ +@echo OFF +:: +:: Post-build auto-deploy script +:: Create and fill PublishPath.ini file with path to deployment folder +:: I.e. PublishPath.ini should contain one line with a folder path +:: Call it so: +:: IF EXIST "$(ProjectDir)PostBuild.bat" (CALL "$(ProjectDir)PostBuild.bat" "$(TargetDir)" "$(TargetName)" "$(TargetExt)" "$(ProjectDir)") +:: + +chcp 65001 + +SET targetDir=%~1 +SET targetName=%~2 +SET targetExt=%~3 +SET projectDir=%~4 + +IF NOT EXIST "%projectDir%\PublishPath.ini" ( + ECHO No deployment path specified. Create PublishPath.ini near PostBuild.bat with paths on separate lines for auto deployment. + exit /B 0 +) + +FOR /f "eol=; tokens=1-2 delims= usebackq" %%a IN ("%projectDir%\PublishPath.ini") DO ( + call :processParam %%a +) + +goto:End + +:processParam [] + + set includeDll=1 + set includePdb=1 + + IF [%2]==[Include] ( + set includeDll=0 + set includePdb=0 + + IF [%3]==[dll] ( + set includeDll=1 + ) ELSE IF [%3]==[pdb] ( + set includePdb=1 + ) + + IF [%4]==[dll] ( + set includeDll=1 + ) ELSE IF [%4]==[pdb] ( + set includePdb=1 + ) + ) + + :: Remove quotes + set v=%1 + set fullpath=%v:"=% + + IF NOT EXIST "%fullpath%" ( + @ECHO Invalid path specified: %fullpath% + ) ELSE ( + @ECHO Deploying to: %fullpath% + IF NOT "%fullpath%" == "" ( + IF EXIST "%fullpath%" ( + IF [%includeDll%]==[1] ( + @copy /Y "%targetDir%%targetName%%targetExt%" "%fullpath%" + ) + + IF NOT ERRORLEVEL 1 ( + IF [%includePdb%]==[1] ( + IF EXIST "%targetDir%%targetName%.pdb" ( + @copy /Y "%targetDir%%targetName%.pdb" "%fullpath%" + ) + ) + ) ELSE ( + @ECHO PostBuild.bat ^(27^) : warning : Can't copy '%targetName%%targetExt%' to deploy path '%fullpath%' + ) + ) + ) + ) + +:End +exit /B 0 diff --git a/reunion/msvc/Reunion.rc b/reunion/msvc/Reunion.rc new file mode 100644 index 0000000..027ea5a --- /dev/null +++ b/reunion/msvc/Reunion.rc @@ -0,0 +1,108 @@ +// Microsoft Visual C++ generated resource script. +// +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" +#include "..\version\appversion.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// Neutral resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_NEU) +#ifdef _WIN32 +LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL +#pragma code_page(1251) +#endif //_WIN32 + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +LANGUAGE LANG_NEUTRAL, SUBLANG_NEUTRAL +VS_VERSION_INFO VERSIONINFO +FILEVERSION APP_VERSION_C +PRODUCTVERSION APP_VERSION_C +FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS (APP_VERSION_FLAGS | VS_FF_DEBUG) +#else + FILEFLAGS (APP_VERSION_FLAGS) +#endif +FILEOS VOS__WINDOWS32 +FILETYPE VFT_DLL +FILESUBTYPE VFT2_UNKNOWN + +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "041904b0" + BEGIN + VALUE "CompanyName", "" + VALUE "FileDescription", "Double Protocol" + VALUE "FileVersion", APP_VERSION_STRD + VALUE "InternalName", "Reunion" + VALUE "LegalCopyright", "" + VALUE "OriginalFilename", "reunion.dll" + VALUE "ProductName", "Reunion" + VALUE "ProductVersion", APP_VERSION_STRD + #if APP_VERSION_FLAGS != 0x0L + VALUE "SpecialBuild", APP_VERSION_SPECIALBUILD + #endif + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x419, 1200 + END +END + +#endif // Neutral resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED + diff --git a/reunion/msvc/Reunion.vcxproj b/reunion/msvc/Reunion.vcxproj new file mode 100644 index 0000000..b9fa488 --- /dev/null +++ b/reunion/msvc/Reunion.vcxproj @@ -0,0 +1,237 @@ + + + + + Debug + Win32 + + + Release + Win32 + + + + {9A72E8DC-7667-46C1-899D-1E8B939564D2} + Win32Proj + Reunion + 10.0 + + + + DynamicLibrary + true + v120_xp + v140_xp + v141_xp + MultiByte + v140_xp + + + DynamicLibrary + false + v120_xp + v140_xp + v141_xp + MultiByte + v140_xp + true + + + + + + + + + + + + + reunion_mm + true + + + reunion_mm + true + + + + Use + Level3 + Disabled + _CRT_SECURE_NO_WARNINGS;WIN32;_DEBUG;_WINDOWS;_USRDLL;REUNION_EXPORTS;NOMINMAX;%(PreprocessorDefinitions) + $(SolutionDir)../;$(SolutionDir)../reunion/;$(SolutionDir)../dep/rehlsdk/common/;$(SolutionDir)../dep/rehlsdk/dlls/;$(SolutionDir)../dep/rehlsdk/engine/;$(SolutionDir)../dep/rehlsdk/public/;$(SolutionDir)../dep/bzip2/include/;$(SolutionDir)../dep/metamod/;%(AdditionalIncludeDirectories) + precompiled.h + MultiThreadedDebug + + + Windows + ws2_32.lib;%(AdditionalDependencies) + reunion.def + + + IF EXIST "$(ProjectDir)PostBuild.bat" (CALL "$(ProjectDir)PostBuild.bat" "$(TargetDir)" "$(TargetName)" "$(TargetExt)" "$(ProjectDir)") + + + Automatic deployment script + + + IF EXIST "$(ProjectDir)..\version\appversion.bat" (CALL "$(ProjectDir)..\version\appversion.bat" "$(ProjectDir)..\version\" "$(SolutionDir)..\") + Setup version from Git revision + + + echo Empty Action + Force build to run Pre-Build event + git.always.run + git.always.run + + + + + Level3 + Use + Full + true + true + _CRT_SECURE_NO_WARNINGS;WIN32;NDEBUG;_WINDOWS;_USRDLL;REUNION_EXPORTS;NOMINMAX;%(PreprocessorDefinitions) + $(SolutionDir)../;$(SolutionDir)../reunion/;$(SolutionDir)../dep/rehlsdk/common/;$(SolutionDir)../dep/rehlsdk/dlls/;$(SolutionDir)../dep/rehlsdk/engine/;$(SolutionDir)../dep/rehlsdk/public/;$(SolutionDir)../dep/bzip2/include/;$(SolutionDir)../dep/metamod/;%(AdditionalIncludeDirectories) + precompiled.h + MultiThreaded + AnySuitable + Speed + true + true + false + StreamingSIMDExtensions2 + 4530 + + + Windows + true + true + ws2_32.lib;%(AdditionalDependencies) + reunion.def + $(OutDir)$(TargetName)$(TargetExt) + false + + + IF EXIST "$(ProjectDir)PostBuild.bat" (CALL "$(ProjectDir)PostBuild.bat" "$(TargetDir)" "$(TargetName)" "$(TargetExt)" "$(ProjectDir)") + Automatic deployment script + + + IF EXIST "$(ProjectDir)..\version\appversion.bat" (CALL "$(ProjectDir)..\version\appversion.bat" "$(ProjectDir)..\version\" "$(SolutionDir)..\") + + + Setup version from Git revision + + + echo Empty Action + + + Force build to run Pre-Build event + + + git.always.run + + + git.always.run + + + + + true + true + + + true + true + + + + false + false + + + true + true + + + + + + + + + + + Create + Create + + + + + + + + + + + + + + true + true + + + + + + + + + + + + + + + + + + + + + + + + + true + + + + + + + true + true + + + true + true + + + + + + + + + + true + true + + + + + + \ No newline at end of file diff --git a/reunion/msvc/Reunion.vcxproj.filters b/reunion/msvc/Reunion.vcxproj.filters new file mode 100644 index 0000000..5783a80 --- /dev/null +++ b/reunion/msvc/Reunion.vcxproj.filters @@ -0,0 +1,187 @@ + + + + + {cc8861f7-9ca7-4d89-b581-eb4c90656d85} + + + {e703ce3f-72eb-415a-9789-dbd63e4d2ab9} + + + {cf6094ab-1021-440b-998f-361a3bb584a0} + + + {9f4edac4-aa51-4e20-af48-4e2ddd9a8cf0} + + + {a1c4d62e-4bdb-4719-8fa8-6a2aa7e47e2a} + + + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + public + + + public + + + src + + + src + + + src + + + src + + + src + + + version + + + src + + + src + + + src + + + src + + + src + + + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + src + + + + version + + + src + + + src + + + src + + + src + + + src + + + src + + + + + misc + + + + + extra + + + extra + + + + + + + + extra + + + \ No newline at end of file diff --git a/reunion/msvc/resource.h b/reunion/msvc/resource.h new file mode 100644 index 0000000..4dd2bd4 --- /dev/null +++ b/reunion/msvc/resource.h @@ -0,0 +1,14 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Reunion.rc + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 101 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/reunion/msvc/reunion.def b/reunion/msvc/reunion.def new file mode 100644 index 0000000..f82bba2 --- /dev/null +++ b/reunion/msvc/reunion.def @@ -0,0 +1,5 @@ +LIBRARY reunion_mm +EXPORTS + GiveFnptrsToDll @1 +SECTIONS + .data READ WRITE diff --git a/reunion/src/Rijndael.cpp b/reunion/src/Rijndael.cpp new file mode 100644 index 0000000..ab8858b --- /dev/null +++ b/reunion/src/Rijndael.cpp @@ -0,0 +1,1389 @@ +#include "precompiled.h" + +const int CRijndael::sm_alog[256] = +{ + 1, 3, 5, 15, 17, 51, 85, 255, 26, 46, 114, 150, 161, 248, 19, 53, + 95, 225, 56, 72, 216, 115, 149, 164, 247, 2, 6, 10, 30, 34, 102, 170, + 229, 52, 92, 228, 55, 89, 235, 38, 106, 190, 217, 112, 144, 171, 230, 49, + 83, 245, 4, 12, 20, 60, 68, 204, 79, 209, 104, 184, 211, 110, 178, 205, + 76, 212, 103, 169, 224, 59, 77, 215, 98, 166, 241, 8, 24, 40, 120, 136, + 131, 158, 185, 208, 107, 189, 220, 127, 129, 152, 179, 206, 73, 219, 118, 154, + 181, 196, 87, 249, 16, 48, 80, 240, 11, 29, 39, 105, 187, 214, 97, 163, + 254, 25, 43, 125, 135, 146, 173, 236, 47, 113, 147, 174, 233, 32, 96, 160, + 251, 22, 58, 78, 210, 109, 183, 194, 93, 231, 50, 86, 250, 21, 63, 65, + 195, 94, 226, 61, 71, 201, 64, 192, 91, 237, 44, 116, 156, 191, 218, 117, + 159, 186, 213, 100, 172, 239, 42, 126, 130, 157, 188, 223, 122, 142, 137, 128, + 155, 182, 193, 88, 232, 35, 101, 175, 234, 37, 111, 177, 200, 67, 197, 84, + 252, 31, 33, 99, 165, 244, 7, 9, 27, 45, 119, 153, 176, 203, 70, 202, + 69, 207, 74, 222, 121, 139, 134, 145, 168, 227, 62, 66, 198, 81, 243, 14, + 18, 54, 90, 238, 41, 123, 141, 140, 143, 138, 133, 148, 167, 242, 13, 23, + 57, 75, 221, 124, 132, 151, 162, 253, 28, 36, 108, 180, 199, 82, 246, 1 +}; + +const int CRijndael::sm_log[256] = +{ + 0, 0, 25, 1, 50, 2, 26, 198, 75, 199, 27, 104, 51, 238, 223, 3, + 100, 4, 224, 14, 52, 141, 129, 239, 76, 113, 8, 200, 248, 105, 28, 193, + 125, 194, 29, 181, 249, 185, 39, 106, 77, 228, 166, 114, 154, 201, 9, 120, + 101, 47, 138, 5, 33, 15, 225, 36, 18, 240, 130, 69, 53, 147, 218, 142, + 150, 143, 219, 189, 54, 208, 206, 148, 19, 92, 210, 241, 64, 70, 131, 56, + 102, 221, 253, 48, 191, 6, 139, 98, 179, 37, 226, 152, 34, 136, 145, 16, + 126, 110, 72, 195, 163, 182, 30, 66, 58, 107, 40, 84, 250, 133, 61, 186, + 43, 121, 10, 21, 155, 159, 94, 202, 78, 212, 172, 229, 243, 115, 167, 87, + 175, 88, 168, 80, 244, 234, 214, 116, 79, 174, 233, 213, 231, 230, 173, 232, + 44, 215, 117, 122, 235, 22, 11, 245, 89, 203, 95, 176, 156, 169, 81, 160, + 127, 12, 246, 111, 23, 196, 73, 236, 216, 67, 31, 45, 164, 118, 123, 183, + 204, 187, 62, 90, 251, 96, 177, 134, 59, 82, 161, 108, 170, 85, 41, 157, + 151, 178, 135, 144, 97, 190, 220, 252, 188, 149, 207, 205, 55, 63, 91, 209, + 83, 57, 132, 60, 65, 162, 109, 71, 20, 42, 158, 93, 86, 242, 211, 171, + 68, 17, 146, 217, 35, 32, 46, 137, 180, 124, 184, 38, 119, 153, 227, 165, + 103, 74, 237, 222, 197, 49, 254, 24, 13, 99, 140, 128, 192, 247, 112, 7 +}; + +const char CRijndael::sm_S[256] = +{ + 99, 124, 119, 123, -14, 107, 111, -59, 48, 1, 103, 43, -2, -41, -85, 118, + -54, -126, -55, 125, -6, 89, 71, -16, -83, -44, -94, -81, -100, -92, 114, -64, + -73, -3, -109, 38, 54, 63, -9, -52, 52, -91, -27, -15, 113, -40, 49, 21, + 4, -57, 35, -61, 24, -106, 5, -102, 7, 18, -128, -30, -21, 39, -78, 117, + 9, -125, 44, 26, 27, 110, 90, -96, 82, 59, -42, -77, 41, -29, 47, -124, + 83, -47, 0, -19, 32, -4, -79, 91, 106, -53, -66, 57, 74, 76, 88, -49, + -48, -17, -86, -5, 67, 77, 51, -123, 69, -7, 2, 127, 80, 60, -97, -88, + 81, -93, 64, -113, -110, -99, 56, -11, -68, -74, -38, 33, 16, -1, -13, -46, + -51, 12, 19, -20, 95, -105, 68, 23, -60, -89, 126, 61, 100, 93, 25, 115, + 96, -127, 79, -36, 34, 42, -112, -120, 70, -18, -72, 20, -34, 94, 11, -37, + -32, 50, 58, 10, 73, 6, 36, 92, -62, -45, -84, 98, -111, -107, -28, 121, + -25, -56, 55, 109, -115, -43, 78, -87, 108, 86, -12, -22, 101, 122, -82, 8, + -70, 120, 37, 46, 28, -90, -76, -58, -24, -35, 116, 31, 75, -67, -117, -118, + 112, 62, -75, 102, 72, 3, -10, 14, 97, 53, 87, -71, -122, -63, 29, -98, + -31, -8, -104, 17, 105, -39, -114, -108, -101, 30, -121, -23, -50, 85, 40, -33, + -116, -95, -119, 13, -65, -26, 66, 104, 65, -103, 45, 15, -80, 84, -69, 22 +}; + +const char CRijndael::sm_Si[256] = +{ + 82, 9, 106, -43, 48, 54, -91, 56, -65, 64, -93, -98, -127, -13, -41, -5, + 124, -29, 57, -126, -101, 47, -1, -121, 52, -114, 67, 68, -60, -34, -23, -53, + 84, 123, -108, 50, -90, -62, 35, 61, -18, 76, -107, 11, 66, -6, -61, 78, + 8, 46, -95, 102, 40, -39, 36, -78, 118, 91, -94, 73, 109, -117, -47, 37, + 114, -8, -10, 100, -122, 104, -104, 22, -44, -92, 92, -52, 93, 101, -74, -110, + 108, 112, 72, 80, -3, -19, -71, -38, 94, 21, 70, 87, -89, -115, -99, -124, + -112, -40, -85, 0, -116, -68, -45, 10, -9, -28, 88, 5, -72, -77, 69, 6, + -48, 44, 30, -113, -54, 63, 15, 2, -63, -81, -67, 3, 1, 19, -118, 107, + 58, -111, 17, 65, 79, 103, -36, -22, -105, -14, -49, -50, -16, -76, -26, 115, + -106, -84, 116, 34, -25, -83, 53, -123, -30, -7, 55, -24, 28, 117, -33, 110, + 71, -15, 26, 113, 29, 41, -59, -119, 111, -73, 98, 14, -86, 24, -66, 27, + -4, 86, 62, 75, -58, -46, 121, 32, -102, -37, -64, -2, 120, -51, 90, -12, + 31, -35, -88, 51, -120, 7, -57, 49, -79, 18, 16, 89, 39, -128, -20, 95, + 96, 81, 127, -87, 25, -75, 74, 13, 45, -27, 122, -97, -109, -55, -100, -17, + -96, -32, 59, 77, -82, 42, -11, -80, -56, -21, -69, 60, -125, 83, -103, 97, + 23, 43, 4, 126, -70, 119, -42, 38, -31, 105, 20, 99, 85, 33, 12, 125 +}; + +const int CRijndael::sm_T1[256] = +{ + -966564955, -126059388, -294160487, -159679603, + -855539, -697603139, -563122255, -1849309868, + 1613770832, 33620227, -832084055, 1445669757, + -402719207, -1244145822, 1303096294, -327780710, + -1882535355, 528646813, -1983264448, -92439161, + -268764651, -1302767125, -1907931191, -68095989, + 1101901292, -1277897625, 1604494077, 1169141738, + 597466303, 1403299063, -462261610, -1681866661, + 1974974402, -503448292, 1033081774, 1277568618, + 1815492186, 2118074177, -168298750, -2083730353, + 1748251740, 1369810420, -773462732, -101584632, + -495881837, -1411852173, 1647391059, 706024767, + 134480908, -1782069422, 1176707941, -1648114850, + 806885416, 932615841, 168101135, 798661301, + 235341577, 605164086, 461406363, -538779075, + -840176858, 1311188841, 2142417613, -361400929, + 302582043, 495158174, 1479289972, 874125870, + 907746093, -596742478, -1269146898, 1537253627, + -1538108682, 1983593293, -1210657183, 2108928974, + 1378429307, -572267714, 1580150641, 327451799, + -1504488459, -1177431704, 0, -1041371860, + 1075847264, -469959649, 2041688520, -1235526675, + -731223362, -1916023994, 1740553945, 1916352843, + -1807070498, -1739830060, -1336387352, -2049978550, + -1143943061, -974131414, 1336584933, -302253290, + -2042412091, -1706209833, 1714631509, 293963156, + -1975171633, -369493744, 67240454, -25198719, + -1605349136, 2017213508, 631218106, 1269344483, + -1571728909, 1571005438, -2143272768, 93294474, + 1066570413, 563977660, 1882732616, -235539196, + 1673313503, 2008463041, -1344611723, 1109467491, + 537923632, -436207846, -34344178, -1076702611, + -2117218996, 403442708, 638784309, -1007883217, + -1101045791, 899127202, -2008791860, 773265209, + -1815821225, 1437050866, -58818942, 2050833735, + -932944724, -1168286233, 840505643, -428641387, + -1067425632, 427917720, -1638969391, -1545806721, + 1143087718, 1412049534, 999329963, 193497219, + -1941551414, -940642775, 1807268051, 672404540, + -1478566279, -1134666014, 369822493, -1378100362, + -606019525, 1681011286, 1949973070, 336202270, + -1840690725, 201721354, 1210328172, -1201906460, + -1614626211, -1110191250, 1135389935, -1000185178, + 965841320, 831886756, -739974089, -226920053, + -706222286, -1949775805, 1849112409, -630362697, + 26054028, -1311386268, -1672589614, 1235855840, + -663982924, -1403627782, -202050553, -806688219, + -899324497, -193299826, 1202630377, 268961816, + 1874508501, -260540280, 1243948399, 1546530418, + 941366308, 1470539505, 1941222599, -1748580783, + -873928669, -1579295364, -395021156, 1042226977, + -1773450275, 1639824860, 227249030, 260737669, + -529502064, 2084453954, 1907733956, -865704278, + -1874310952, 100860677, -134810111, 470683154, + -1033805405, 1781871967, -1370007559, 1773779408, + 394692241, -1715355304, 974986535, 664706745, + -639508168, -336005101, 731420851, 571543859, + -764843589, -1445340816, 126783113, 865375399, + 765172662, 1008606754, 361203602, -907417312, + -2016489911, -1437248001, 1344809080, -1512054918, + 59542671, 1503764984, 160008576, 437062935, + 1707065306, -672733647, -2076032314, -798463816, + -2109652541, 697932208, 1512910199, 504303377, + 2075177163, -1470868228, 1841019862, 739644986 +}; + +const int CRijndael::sm_T2[256] = +{ + -1513725085, -2064089988, -1712425097, -1913226373, + 234877682, -1110021269, -1310822545, 1418839493, + 1348481072, 50462977, -1446090905, 2102799147, + 434634494, 1656084439, -431117397, -1695779210, + 1167051466, -1658879358, 1082771913, -2013627011, + 368048890, -340633255, -913422521, 201060592, + -331240019, 1739838676, -44064094, -364531793, + -1088185188, -145513308, -1763413390, 1536934080, + -1032472649, 484572669, -1371696237, 1783375398, + 1517041206, 1098792767, 49674231, 1334037708, + 1550332980, -195975771, 886171109, 150598129, + -1813876367, 1940642008, 1398944049, 1059722517, + 201851908, 1385547719, 1699095331, 1587397571, + 674240536, -1590192490, 252314885, -1255171430, + 151914247, 908333586, -1692696448, 1038082786, + 651029483, 1766729511, -847269198, -1612024459, + 454166793, -1642232957, 1951935532, 775166490, + 758520603, -1294176658, -290170278, -77881184, + -157003182, 1299594043, 1639438038, -830622797, + 2068982057, 1054729187, 1901997871, -1760328572, + -173649069, 1757008337, 0, 750906861, + 1614815264, 535035132, -931548751, -306816165, + -1093375382, 1183697867, -647512386, 1265776953, + -560706998, -728216500, -391096232, 1250283471, + 1807470800, 717615087, -447763798, 384695291, + -981056701, -677753523, 1432761139, -1810791035, + -813021883, 283769337, 100925954, -2114027649, + -257929136, 1148730428, -1171939425, -481580888, + -207466159, -27417693, -1065336768, -1979347057, + -1388342638, -1138647651, 1215313976, 82966005, + -547111748, -1049119050, 1974459098, 1665278241, + 807407632, 451280895, 251524083, 1841287890, + 1283575245, 337120268, 891687699, 801369324, + -507617441, -1573546089, -863484860, 959321879, + 1469301956, -229267545, -2097381762, 1199193405, + -1396153244, -407216803, 724703513, -1780059277, + -1598005152, -1743158911, -778154161, 2141445340, + 1715741218, 2119445034, -1422159728, -2096396152, + -896776634, 700968686, -747915080, 1009259540, + 2041044702, -490971554, 487983883, 1991105499, + 1004265696, 1449407026, 1316239930, 504629770, + -611169975, 168560134, 1816667172, -457679780, + 1570751170, 1857934291, -280777556, -1497079198, + -1472622191, -1540254315, 936633572, -1947043463, + 852879335, 1133234376, 1500395319, -1210421907, + -1946055283, 1689376213, -761508274, -532043351, + -1260884884, -89369002, 133428468, 634383082, + -1345690267, -1896580486, -381178194, 403703816, + -714097990, -1997506440, 1867130149, 1918643758, + 607656988, -245913946, -948718412, 1368901318, + 600565992, 2090982877, -1662487436, 557719327, + -577352885, -597574211, -2045932661, -2062579062, + -1864339344, 1115438654, -999180875, -1429445018, + -661632952, 84280067, 33027830, 303828494, + -1547542175, 1600795957, -106014889, -798377543, + -1860729210, 1486471617, 658119965, -1188585826, + 953803233, 334231800, -1288988520, 857870609, + -1143838359, 1890179545, -1995993458, -1489791852, + -1238525029, 574365214, -1844082809, 550103529, + 1233637070, -5614251, 2018519080, 2057691103, + -1895592820, -128343647, -2146858615, 387583245, + -630865985, 836232934, -964410814, -1194301336, + -1014873791, -1339450983, 2002398509, 287182607, + -881086288, -56077228, -697451589, 975967766 +}; + +const int CRijndael::sm_T3[256] = +{ + 1671808611, 2089089148, 2006576759, 2072901243, + -233963534, 1807603307, 1873927791, -984313403, + 810573872, 16974337, 1739181671, 729634347, + -31856642, -681396777, -1410970197, 1989864566, + -901410870, -2103631998, -918517303, 2106063485, + -99225606, 1508618841, 1204391495, -267650064, + -1377025619, -731401260, -1560453214, -1343601233, + -1665195108, -1527295068, 1922491506, -1067738176, + -1211992649, -48438787, -1817297517, 644500518, + 911895606, 1061256767, -150800905, -867204148, + 878471220, -1510714971, -449523227, -251069967, + 1905517169, -663508008, 827548209, 356461077, + 67897348, -950889017, 593839651, -1017209405, + 405286936, -1767819370, 84871685, -1699401830, + 118033927, 305538066, -2137318528, -499261470, + -349778453, 661212711, -1295155278, 1973414517, + 152769033, -2086789757, 745822252, 439235610, + 455947803, 1857215598, 1525593178, -1594139744, + 1391895634, 994932283, -698239018, -1278313037, + 695947817, -482419229, 795958831, -2070473852, + 1408607827, -781665839, 0, -315833875, + 543178784, -65018884, -1312261711, 1542305371, + 1790891114, -884568629, -1093048386, 961245753, + 1256100938, 1289001036, 1491644504, -817199665, + -798245936, -282409489, -1427812438, -82383365, + 1137018435, 1305975373, 861234739, -2053893755, + 1171229253, -116332039, 33948674, 2139225727, + 1357946960, 1011120188, -1615190625, -1461498968, + 1374921297, -1543610973, 1086357568, -1886780017, + -1834139758, -1648615011, 944271416, -184225291, + -1126210628, -1228834890, -629821478, 560153121, + 271589392, -15014401, -217121293, -764559406, + -850624051, 202643468, 322250259, -332413972, + 1608629855, -1750977129, 1154254916, 389623319, + -1000893500, -1477290585, 2122513534, 1028094525, + 1689045092, 1575467613, 422261273, 1939203699, + 1621147744, -2120738431, 1339137615, -595614756, + 577127458, 712922154, -1867826288, -2004677752, + 1187679302, -299251730, -1194103880, 339486740, + -562452514, 1591917662, 186455563, -612979237, + -532948000, 844522546, 978220090, 169743370, + 1239126601, 101321734, 611076132, 1558493276, + -1034051646, -747717165, -1393605716, 1655096418, + -1851246191, -1784401515, -466103324, 2039214713, + -416098841, -935097400, 928607799, 1840765549, + -1920204403, -714821163, 1322425422, -1444918871, + 1823791212, 1459268694, -200805388, -366620694, + 1706019429, 2056189050, -1360443474, 135794696, + -1160417350, 2022240376, 628050469, 779246638, + 472135708, -1494132826, -1261997132, -967731258, + -400307224, -579034659, 1956440180, 522272287, + 1272813131, -1109630531, -1954148981, -1970991222, + 1888542832, 1044544574, -1245417035, 1722469478, + 1222152264, 50660867, -167643146, 236067854, + 1638122081, 895445557, 1475980887, -1177523783, + -2037311610, -1051158079, 489110045, -1632032866, + -516367903, -132912136, -1733088360, 288563729, + 1773916777, -646927911, -1903622258, -1800981612, + -1682559589, 505560094, -2020469369, -383727127, + -834041906, 1442818645, 678973480, -545610273, + -1936784500, -1577559647, -1988097655, 219617805, + -1076206145, -432941082, 1120306242, 1756942440, + 1103331905, -1716508263, 762796589, 252780047, + -1328841808, 1425844308, -1143575109, 372911126 +}; + +const int CRijndael::sm_T4[256] = +{ + 1667474886, 2088535288, 2004326894, 2071694838, + -219017729, 1802223062, 1869591006, -976923503, + 808472672, 16843522, 1734846926, 724270422, + -16901657, -673750347, -1414797747, 1987484396, + -892713585, -2105369313, -909557623, 2105378810, + -84273681, 1499065266, 1195886990, -252703749, + -1381110719, -724277325, -1566376609, -1347425723, + -1667449053, -1532692653, 1920112356, -1061135461, + -1212693899, -33743647, -1819038147, 640051788, + 909531756, 1061110142, -134806795, -859025533, + 875846760, -1515850671, -437963567, -235861767, + 1903268834, -656903253, 825316194, 353713962, + 67374088, -943238507, 589522246, -1010606435, + 404236336, -1768513225, 84217610, -1701137105, + 117901582, 303183396, -2139055333, -488489505, + -336910643, 656894286, -1296904833, 1970642922, + 151591698, -2088526307, 741110872, 437923380, + 454765878, 1852748508, 1515908788, -1600062629, + 1381168804, 993742198, -690593353, -1280061827, + 690584402, -471646499, 791638366, -2071685357, + 1398011302, -774805319, 0, -303223615, + 538992704, -50585629, -1313748871, 1532751286, + 1785380564, -875870579, -1094788761, 960056178, + 1246420628, 1280103576, 1482221744, -808498555, + -791647301, -269538619, -1431640753, -67430675, + 1128514950, 1296947098, 859002214, -2054843375, + 1162203018, -101117719, 33687044, 2139062782, + 1347481760, 1010582648, -1616922075, -1465326773, + 1364325282, -1549533603, 1077985408, -1886418427, + -1835881153, -1650607071, 943212656, -168491791, + -1128472733, -1229536905, -623217233, 555836226, + 269496352, -58651, -202174723, -757961281, + -842183551, 202118168, 320025894, -320065597, + 1600119230, -1751670219, 1145359496, 387397934, + -993765485, -1482165675, 2122220284, 1027426170, + 1684319432, 1566435258, 421079858, 1936954854, + 1616945344, -2122213351, 1330631070, -589529181, + 572679748, 707427924, -1869567173, -2004319477, + 1179044492, -286381625, -1195846805, 336870440, + -555845209, 1583276732, 185277718, -606374227, + -522175525, 842159716, 976899700, 168435220, + 1229577106, 101059084, 606366792, 1549591736, + -1027449441, -741118275, -1397952701, 1650632388, + -1852725191, -1785355215, -454805549, 2038008818, + -404278571, -926399605, 926374254, 1835907034, + -1920103423, -707435343, 1313788572, -1448484791, + 1819063512, 1448540844, -185333773, -353753649, + 1701162954, 2054852340, -1364268729, 134748176, + -1162160785, 2021165296, 623210314, 774795868, + 471606328, -1499008681, -1263220877, -960081513, + -387439669, -572687199, 1953799400, 522133822, + 1263263126, -1111630751, -1953790451, -1970633457, + 1886425312, 1044267644, -1246378895, 1718004428, + 1212733584, 50529542, -151649801, 235803164, + 1633788866, 892690282, 1465383342, -1179004823, + -2038001385, -1044293479, 488449850, -1633765081, + -505333543, -117959701, -1734823125, 286339874, + 1768537042, -640061271, -1903261433, -1802197197, + -1684294099, 505291324, -2021158379, -370597687, + -825341561, 1431699370, 673740880, -539002203, + -1936945405, -1583220647, -1987477495, 218961690, + -1077945755, -421121577, 1111672452, 1751693520, + 1094828930, -1717981143, 757954394, 252645662, + -1330590853, 1414855848, -1145317779, 370555436 +}; + +const int CRijndael::sm_T5[256] = +{ + 1374988112, 2118214995, 437757123, 975658646, + 1001089995, 530400753, -1392879445, 1273168787, + 540080725, -1384747530, -1999866223, -184398811, + 1340463100, -987051049, 641025152, -1251826801, + -558802359, 632953703, 1172967064, 1576976609, + -1020300030, -2125664238, -1924753501, 1809054150, + 59727847, 361929877, -1083344149, -1789765158, + -725712083, 1484005843, 1239443753, -1899378620, + 1975683434, -191989384, -1722270101, 666464733, + -1092530250, -259478249, -920605594, 2110667444, + 1675577880, -451268222, -1756286112, 1649639237, + -1318815776, -1150570876, -25059300, -116905068, + 1883793496, -1891238631, -1797362553, 1383856311, + -1418472669, 1917518562, -484470953, 1716890410, + -1293211641, 800440835, -2033878118, -751368027, + 807962610, 599762354, 33778362, -317291940, + -1966138325, -1485196142, -217582864, 1315562145, + 1708848333, 101039829, -785096161, -995688822, + 875451293, -1561111136, 92987698, -1527321739, + 193195065, 1080094634, 1584504582, -1116860335, + 1042385657, -1763899843, -583137874, 1306967366, + -1856729675, 1908694277, 67556463, 1615861247, + 429456164, -692196969, -1992277044, 1742315127, + -1326955843, 126454664, -417768648, 2043211483, + -1585706425, 2084704233, -125559095, 0, + 159417987, 841739592, 504459436, 1817866830, + -49348613, 260388950, 1034867998, 908933415, + 168810852, 1750902305, -1688513327, 607530554, + 202008497, -1822955761, -1259432238, 463180190, + -2134850225, 1641816226, 1517767529, 470948374, + -493635062, -1063245083, 1008918595, 303765277, + 235474187, -225720403, 766945465, 337553864, + 1475418501, -1351284916, -291906117, -1551933187, + -150919521, 1551037884, 1147550661, 1543208500, + -1958532746, -886847780, -1225917336, -1192955549, + -684598070, 1113818384, 328671808, -2067394272, + -2058738563, -759480840, -1359400431, -953573011, + 496906059, -592301837, 226906860, 2009195472, + 733156972, -1452230247, 294930682, 1206477858, + -1459843900, -1594867942, 1451044056, 573804783, + -2025238841, -650587711, -1932877058, -1730933962, + -1493859889, -1518674392, -625504730, 1068351396, + 742039012, 1350078989, 1784663195, 1417561698, + -158526526, -1864845080, 775550814, -2101104651, + -1621262146, 1775276924, 1876241833, -819653965, + -928212677, 270040487, -392404114, -616842373, + -853116919, 1851332852, -325404927, -2091935064, + -426414491, -1426069890, 566021896, -283776794, + -1159226407, 1248802510, -358676012, 699432150, + 832877231, 708780849, -962227152, 899835584, + 1951317047, -58537306, -527380304, 866637845, + -251357110, 1106041591, 2144161806, 395441711, + 1984812685, 1139781709, -861254316, -459930401, + -1630423581, 1282050075, -1054072904, 1181045119, + -1654724092, 25965917, -91786125, -83148498, + -1285087910, -1831087534, -384805325, 1842759443, + -1697160820, 933301370, 1509430414, -351060855, + -827774994, -1218328267, -518199827, 2051518780, + -1663901863, 1441952575, 404016761, 1942435775, + 1408749034, 1610459739, -549621996, 2017778566, + -894438527, -1184316354, 941896748, -1029488545, + 371049330, -1126030068, 675039627, -15887039, + 967311729, 135050206, -659233636, 1683407248, + 2076935265, -718096784, 1215061108, -793225406 +}; + +const int CRijndael::sm_T6[256] = +{ + 1347548327, 1400783205, -1021700188, -1774573730, + -885281941, -249586363, -1414727080, -1823743229, + 1428173050, -156404115, -1853305738, 636813900, + -61872681, -674944309, -2144979644, -1883938141, + 1239331162, 1730525723, -1740248562, -513933632, + 46346101, 310463728, -1551022441, -966011911, + -419197089, -1793748324, -339776134, -627748263, + 768917123, -749177823, 692707433, 1150208456, + 1786102409, 2029293177, 1805211710, -584599183, + -1229004465, 401639597, 1724457132, -1266823622, + 409198410, -2098914767, 1620529459, 1164071807, + -525245321, -2068091986, 486441376, -1795618773, + 1483753576, 428819965, -2020286868, -1219331080, + 598438867, -495826174, 1474502543, 711349675, + 129166120, 53458370, -1702443653, -1512884472, + -231724921, -1306280027, -1174273174, 1559041666, + 730517276, -1834518092, -252508174, -1588696606, + -848962828, -721025602, 533804130, -1966823682, + -1657524653, -1599933611, 839224033, 1973745387, + 957055980, -1438621457, 106852767, 1371368976, + -113368694, 1033297158, -1361232379, 1179510461, + -1248766835, 91341917, 1862534868, -10465259, + 605657339, -1747534359, -863420349, 2003294622, + -1112479678, -2012771957, 954669403, -612775698, + 1201765386, -377732593, -906460130, 0, + -2096529274, 1211247597, -1407315600, 1315723890, + -67301633, 1443857720, 507358933, 657861945, + 1678381017, 560487590, -778347692, 975451694, + -1324610969, 261314535, -759894378, -1642357871, + 1333838021, -1570644960, 1767536459, 370938394, + 182621114, -440360918, 1128014560, 487725847, + 185469197, -1376613433, -1188186456, -938205527, + -2057834215, 1286567175, -1141990947, -39616672, + -1611202266, -1134791947, -985373125, 878443390, + 1988838185, -590666810, 1756818940, 1673061617, + -891866660, 272786309, 1075025698, 545572369, + 2105887268, -120407235, 296679730, 1841768865, + 1260232239, -203640272, -334657966, -797457949, + 1814803222, -1716948807, -99511224, 575138148, + -995558260, 446754879, -665420500, -282971248, + -947435186, -1042728751, -24327518, 915985419, + -811141759, 681933534, 651868046, -1539330625, + -466863459, 223377554, -1687527476, 1649704518, + -1024029421, -393160520, 1580087799, -175979601, + -1096852096, 2087309459, -1452288723, -1278270190, + 1003007129, -1492117379, 1860738147, 2077965243, + 164439672, -194094824, 32283319, -1467789414, + 1709610350, 2125135846, 136428751, -420538904, + -642062437, -833982666, -722821367, -701910916, + -1355701070, 824852259, 818324884, -1070226842, + 930369212, -1493400886, -1327460144, 355706840, + 1257309336, -146674470, 243256656, 790073846, + -1921626666, 1296297904, 1422699085, -538667516, + -476130891, 457992840, -1195299809, 2135319889, + 77422314, 1560382517, 1945798516, 788204353, + 1521706781, 1385356242, 870912086, 325965383, + -1936009375, 2050466060, -1906706412, -1981082820, + -288446169, 901210569, -304014107, 1014646705, + 1503449823, 1062597235, 2031621326, -1082931401, + -363595827, 1533017514, 350174575, -2038938405, + -2117423117, 1052338372, 741876788, 1606591296, + 1914052035, 213705253, -1960297399, 1107234197, + 1899603969, -569897805, -1663519516, -1872472383, + 1635502980, 1893020342, 1950903388, 1120974935 +}; + +const int CRijndael::sm_T7[256] = +{ + -1487908364, 1699970625, -1530717673, 1586903591, + 1808481195, 1173430173, 1487645946, 59984867, + -95084496, 1844882806, 1989249228, 1277555970, + -671330331, -875051734, 1149249077, -1550863006, + 1514790577, 459744698, 244860394, -1058972162, + 1963115311, -267222708, -1750889146, -104436781, + 1608975247, -1667951214, 2062270317, 1507497298, + -2094148418, 567498868, 1764313568, -935031095, + -1989511742, 2037970062, 1047239000, 1910319033, + 1337376481, -1390940024, -1402549984, 984907214, + 1243112415, 830661914, 861968209, 2135253587, + 2011214180, -1367032981, -1608712575, 731183368, + 1750626376, -48656571, 1820824798, -122203525, + -752637069, 48394827, -1890065633, -1423284651, + 671593195, -1039978571, 2073724613, 145085239, + -2014171096, -1515052097, 1790575107, -2107839210, + 472615631, -1265457287, -219090169, -492745111, + -187865638, -1093335547, 1646252340, -24460122, + 1402811438, 1436590835, -516815478, -344611594, + -331805821, -274055072, -1626972559, 273792366, + -1963377119, 104699613, 95345982, -1119466010, + -1917480620, 1560637892, -730921978, 369057872, + -81520232, -375925059, 1137477952, -1636341799, + 1119727848, -1954019447, 1530455833, -287606328, + 172466556, 266959938, 516552836, 0, + -2038232704, -314035669, 1890328081, 1917742170, + -262898, 945164165, -719438418, 958871085, + -647755249, -1507760036, 1423022939, 775562294, + 1739656202, -418409641, -1764576018, -1851909221, + -984645440, 547512796, 1265195639, 437656594, + -1173691757, 719700128, -532464606, 387781147, + 218828297, -944901493, -1464259146, -1446505442, + 428169201, 122466165, -574886247, 1627235199, + 648017665, -172204942, 1002783846, 2117360635, + 695634755, -958608605, -60246291, -245122844, + -590686415, -2062531997, 574624663, 287343814, + 612205898, 1039717051, 840019705, -1586641111, + 793451934, 821288114, 1391201670, -472877119, + 376187827, -1181111952, 1224348052, 1679968233, + -1933268740, 1058709744, 752375421, -1863376333, + 1321699145, -775825096, -1560376118, 188127444, + -2117097739, -567761542, -1910056265, -1079754835, + -1645990854, -1844621192, -862229921, 1180849278, + 331544205, -1192718120, -144822727, -1342864701, + -2134991011, -1820562992, 766078933, 313773861, + -1724135252, 2108100632, 1668212892, -1149510853, + 2013908262, 418672217, -1224610662, -1700232369, + 1852171925, -427906305, -821550660, -387518699, + -1680229657, 919489135, 164948639, 2094410160, + -1297141340, 590424639, -1808742747, 1723872674, + -1137216434, -895026046, -793714544, -669699161, + -1739919100, -621329940, 1343127501, -164685935, + -695372211, -1337113617, 1297403050, 81781910, + -1243373871, -2011476886, 532201772, 1367295589, + -368796322, 895287692, 1953757831, 1093597963, + 492483431, -766340389, 1446242576, 1192455638, + 1636604631, 209336225, 344873464, 1015671571, + 669961897, -919226527, -437395172, -1321436601, + -547775278, 1933530610, -830924780, 935293895, + -840281097, -1436852227, 1863638845, -611944380, + -209597777, -1002522264, 875313188, 1080017571, + -1015933411, 621591778, 1233856572, -1790836979, + 24197544, -1277294580, -459482956, -1047501738, + -2073986101, -1234119374, 1551124588, 1463996600 +}; + +const int CRijndael::sm_T8[256] = +{ + -190361519, 1097159550, 396673818, 660510266, + -1418998981, -1656360673, -94852180, -486304949, + 821712160, 1986918061, -864644728, 38544885, + -438830001, 718002117, 893681702, 1654886325, + -1319482914, -1172609243, -368142267, -20913827, + 796197571, 1290801793, 1184342925, -738605461, + -1889540349, -1835231979, 1836772287, 1381620373, + -1098699308, 1948373848, -529979063, -909622130, + -1031181707, -1904641804, 1480485785, -1183720153, + -514869570, -2001922064, 548169417, -835013507, + -548792221, 439452389, 1362321559, 1400849762, + 1685577905, 1806599355, -2120213250, 137073913, + 1214797936, 1174215055, -563312748, 2079897426, + 1943217067, 1258480242, 529487843, 1437280870, + -349698126, -1245576401, -981755258, 923313619, + 679998000, -1079659997, 57326082, 377642221, + -820237430, 2041877159, 133361907, 1776460110, + -621490843, 96392454, 878845905, -1493267772, + 777231668, -212492126, -1964953083, -152341084, + -2081670901, 1626319424, 1906247262, 1846563261, + 562755902, -586793578, 1040559837, -423803315, + 1418573201, -1000536719, 114585348, 1343618912, + -1728371687, -1108764714, 1078185097, -643926169, + -398279248, -1987344377, 425408743, -923870343, + 2081048481, 1108339068, -2078357000, 0, + -2138668279, 736970802, 292596766, 1517440620, + 251657213, -2059905521, -1361764803, 758720310, + 265905162, 1554391400, 1532285339, 908999204, + 174567692, 1474760595, -292105548, -1684955621, + -1060810880, -601841055, 2001430874, 303699484, + -1816524062, -1607801408, 585122620, 454499602, + 151849742, -1949848078, -1230456531, 514443284, + -249985705, 1963412655, -1713521682, 2137062819, + 19308535, 1928707164, 1715193156, -75615141, + 1126790795, 600235211, -302225226, -453942344, + 836553431, 1669664834, -1759363053, -971956092, + 1243905413, -1153566510, -114159186, 698445255, + -1641067747, -1305414692, -2041385971, -1042034569, + -1290376149, 1891211689, -1807156719, -379313593, + -57883480, -264299872, 2100090966, 865136418, + 1229899655, 953270745, -895287668, -737462632, + -176042074, 2061379749, -1215420710, -1379949505, + 983426092, 2022837584, 1607244650, 2118541908, + -1928084746, -658970480, 972512814, -1011878526, + 1568718495, -795640727, -718427793, 621982671, + -1399243832, 410887952, -1671205144, 1002142683, + 645401037, 1494807662, -1699282452, 1335535747, + -1787927066, -1671510, -1127282655, 367585007, + -409216582, 1865862730, -1626745622, -1333995991, + -1531793615, 1059270954, -1517014842, -1570324427, + 1320957812, -2100648196, -1865371424, -1479011021, + 77089521, -321194175, -850391425, -1846137065, + 1305906550, -273658557, -1437772596, -1778065436, + -776608866, 1787304780, 740276417, 1699839814, + 1592394909, -1942659839, -2022411270, 188821243, + 1729977011, -606973294, 274084841, -699985043, + -681472870, -1593017801, -132870567, 322734571, + -1457000754, 1640576439, 484830689, 1202797690, + -757114468, -227328171, 349075736, -952647821, + -137500077, -39167137, 1030690015, 1155237496, + -1342996022, 1757691577, 607398968, -1556062270, + 499347990, -500888388, 1011452712, 227885567, + -1476300487, 213114376, -1260086056, 1455525988, + -880516741, 850817237, 1817998408, -1202240816 +}; + +const int CRijndael::sm_U1[256] = +{ + 0, 235474187, 470948374, 303765277, + 941896748, 908933415, 607530554, 708780849, + 1883793496, 2118214995, 1817866830, 1649639237, + 1215061108, 1181045119, 1417561698, 1517767529, + -527380304, -291906117, -58537306, -225720403, + -659233636, -692196969, -995688822, -894438527, + -1864845080, -1630423581, -1932877058, -2101104651, + -1459843900, -1493859889, -1259432238, -1159226407, + -616842373, -718096784, -953573011, -920605594, + -484470953, -317291940, -15887039, -251357110, + -1418472669, -1518674392, -1218328267, -1184316354, + -1822955761, -1654724092, -1891238631, -2125664238, + 1001089995, 899835584, 666464733, 699432150, + 59727847, 226906860, 530400753, 294930682, + 1273168787, 1172967064, 1475418501, 1509430414, + 1942435775, 2110667444, 1876241833, 1641816226, + -1384747530, -1551933187, -1318815776, -1083344149, + -1789765158, -1688513327, -1992277044, -2025238841, + -583137874, -751368027, -1054072904, -819653965, + -451268222, -351060855, -116905068, -150919521, + 1306967366, 1139781709, 1374988112, 1610459739, + 1975683434, 2076935265, 1775276924, 1742315127, + 1034867998, 866637845, 566021896, 800440835, + 92987698, 193195065, 429456164, 395441711, + 1984812685, 2017778566, 1784663195, 1683407248, + 1315562145, 1080094634, 1383856311, 1551037884, + 101039829, 135050206, 437757123, 337553864, + 1042385657, 807962610, 573804783, 742039012, + -1763899843, -1730933962, -1966138325, -2067394272, + -1359400431, -1594867942, -1293211641, -1126030068, + -426414491, -392404114, -91786125, -191989384, + -558802359, -793225406, -1029488545, -861254316, + 1106041591, 1340463100, 1576976609, 1408749034, + 2043211483, 2009195472, 1708848333, 1809054150, + 832877231, 1068351396, 766945465, 599762354, + 159417987, 126454664, 361929877, 463180190, + -1585706425, -1351284916, -1116860335, -1285087910, + -1722270101, -1756286112, -2058738563, -1958532746, + -785096161, -549621996, -853116919, -1020300030, + -384805325, -417768648, -184398811, -83148498, + -1697160820, -1797362553, -2033878118, -1999866223, + -1561111136, -1392879445, -1092530250, -1326955843, + -358676012, -459930401, -158526526, -125559095, + -759480840, -592301837, -827774994, -1063245083, + 2051518780, 1951317047, 1716890410, 1750902305, + 1113818384, 1282050075, 1584504582, 1350078989, + 168810852, 67556463, 371049330, 404016761, + 841739592, 1008918595, 775550814, 540080725, + -325404927, -493635062, -259478249, -25059300, + -725712083, -625504730, -928212677, -962227152, + -1663901863, -1831087534, -2134850225, -1899378620, + -1527321739, -1426069890, -1192955549, -1225917336, + 202008497, 33778362, 270040487, 504459436, + 875451293, 975658646, 675039627, 641025152, + 2084704233, 1917518562, 1615861247, 1851332852, + 1147550661, 1248802510, 1484005843, 1451044056, + 933301370, 967311729, 733156972, 632953703, + 260388950, 25965917, 328671808, 496906059, + 1206477858, 1239443753, 1543208500, 1441952575, + 2144161806, 1908694277, 1675577880, 1842759443, + -684598070, -650587711, -886847780, -987051049, + -283776794, -518199827, -217582864, -49348613, + -1485196142, -1452230247, -1150570876, -1251826801, + -1621262146, -1856729675, -2091935064, -1924753501 +}; + +const int CRijndael::sm_U2[256] = +{ + 0, 185469197, 370938394, 487725847, + 741876788, 657861945, 975451694, 824852259, + 1483753576, 1400783205, 1315723890, 1164071807, + 1950903388, 2135319889, 1649704518, 1767536459, + -1327460144, -1141990947, -1493400886, -1376613433, + -1663519516, -1747534359, -1966823682, -2117423117, + -393160520, -476130891, -24327518, -175979601, + -995558260, -811141759, -759894378, -642062437, + 2077965243, 1893020342, 1841768865, 1724457132, + 1474502543, 1559041666, 1107234197, 1257309336, + 598438867, 681933534, 901210569, 1052338372, + 261314535, 77422314, 428819965, 310463728, + -885281941, -1070226842, -584599183, -701910916, + -419197089, -334657966, -249586363, -99511224, + -1823743229, -1740248562, -2057834215, -1906706412, + -1082931401, -1266823622, -1452288723, -1570644960, + -156404115, -39616672, -525245321, -339776134, + -627748263, -778347692, -863420349, -947435186, + -1361232379, -1512884472, -1195299809, -1278270190, + -2098914767, -1981082820, -1795618773, -1611202266, + 1179510461, 1296297904, 1347548327, 1533017514, + 1786102409, 1635502980, 2087309459, 2003294622, + 507358933, 355706840, 136428751, 53458370, + 839224033, 957055980, 605657339, 790073846, + -1921626666, -2038938405, -1687527476, -1872472383, + -1588696606, -1438621457, -1219331080, -1134791947, + -721025602, -569897805, -1021700188, -938205527, + -113368694, -231724921, -282971248, -466863459, + 1033297158, 915985419, 730517276, 545572369, + 296679730, 446754879, 129166120, 213705253, + 1709610350, 1860738147, 1945798516, 2029293177, + 1239331162, 1120974935, 1606591296, 1422699085, + -146674470, -61872681, -513933632, -363595827, + -612775698, -797457949, -848962828, -966011911, + -1355701070, -1539330625, -1188186456, -1306280027, + -2096529274, -2012771957, -1793748324, -1642357871, + 1201765386, 1286567175, 1371368976, 1521706781, + 1805211710, 1620529459, 2105887268, 1988838185, + 533804130, 350174575, 164439672, 46346101, + 870912086, 954669403, 636813900, 788204353, + -1936009375, -2020286868, -1702443653, -1853305738, + -1599933611, -1414727080, -1229004465, -1112479678, + -722821367, -538667516, -1024029421, -906460130, + -120407235, -203640272, -288446169, -440360918, + 1014646705, 930369212, 711349675, 560487590, + 272786309, 457992840, 106852767, 223377554, + 1678381017, 1862534868, 1914052035, 2031621326, + 1211247597, 1128014560, 1580087799, 1428173050, + 32283319, 182621114, 401639597, 486441376, + 768917123, 651868046, 1003007129, 818324884, + 1503449823, 1385356242, 1333838021, 1150208456, + 1973745387, 2125135846, 1673061617, 1756818940, + -1324610969, -1174273174, -1492117379, -1407315600, + -1657524653, -1774573730, -1960297399, -2144979644, + -377732593, -495826174, -10465259, -194094824, + -985373125, -833982666, -749177823, -665420500, + 2050466060, 1899603969, 1814803222, 1730525723, + 1443857720, 1560382517, 1075025698, 1260232239, + 575138148, 692707433, 878443390, 1062597235, + 243256656, 91341917, 409198410, 325965383, + -891866660, -1042728751, -590666810, -674944309, + -420538904, -304014107, -252508174, -67301633, + -1834518092, -1716948807, -2068091986, -1883938141, + -1096852096, -1248766835, -1467789414, -1551022441, +}; + +const int CRijndael::sm_U3[256] = +{ + 0, 218828297, 437656594, 387781147, + 875313188, 958871085, 775562294, 590424639, + 1750626376, 1699970625, 1917742170, 2135253587, + 1551124588, 1367295589, 1180849278, 1265195639, + -793714544, -574886247, -895026046, -944901493, + -459482956, -375925059, -24460122, -209597777, + -1192718120, -1243373871, -1560376118, -1342864701, + -1933268740, -2117097739, -1764576018, -1680229657, + -1149510853, -1234119374, -1586641111, -1402549984, + -1890065633, -2107839210, -1790836979, -1739919100, + -752637069, -567761542, -919226527, -1002522264, + -418409641, -368796322, -48656571, -267222708, + 1808481195, 1723872674, 1910319033, 2094410160, + 1608975247, 1391201670, 1173430173, 1224348052, + 59984867, 244860394, 428169201, 344873464, + 935293895, 984907214, 766078933, 547512796, + 1844882806, 1627235199, 2011214180, 2062270317, + 1507497298, 1423022939, 1137477952, 1321699145, + 95345982, 145085239, 532201772, 313773861, + 830661914, 1015671571, 731183368, 648017665, + -1119466010, -1337113617, -1487908364, -1436852227, + -1989511742, -2073986101, -1820562992, -1636341799, + -719438418, -669699161, -821550660, -1039978571, + -516815478, -331805821, -81520232, -164685935, + -695372211, -611944380, -862229921, -1047501738, + -492745111, -274055072, -122203525, -172204942, + -1093335547, -1277294580, -1530717673, -1446505442, + -1963377119, -2014171096, -1863376333, -1645990854, + 104699613, 188127444, 472615631, 287343814, + 840019705, 1058709744, 671593195, 621591778, + 1852171925, 1668212892, 1953757831, 2037970062, + 1514790577, 1463996600, 1080017571, 1297403050, + -621329940, -671330331, -1058972162, -840281097, + -287606328, -472877119, -187865638, -104436781, + -1297141340, -1079754835, -1464259146, -1515052097, + -2038232704, -1954019447, -1667951214, -1851909221, + 172466556, 122466165, 273792366, 492483431, + 1047239000, 861968209, 612205898, 695634755, + 1646252340, 1863638845, 2013908262, 1963115311, + 1446242576, 1530455833, 1277555970, 1093597963, + 1636604631, 1820824798, 2073724613, 1989249228, + 1436590835, 1487645946, 1337376481, 1119727848, + 164948639, 81781910, 331544205, 516552836, + 1039717051, 821288114, 669961897, 719700128, + -1321436601, -1137216434, -1423284651, -1507760036, + -2062531997, -2011476886, -1626972559, -1844621192, + -647755249, -730921978, -1015933411, -830924780, + -314035669, -532464606, -144822727, -95084496, + -1224610662, -1173691757, -1390940024, -1608712575, + -2094148418, -1910056265, -1724135252, -1808742747, + -547775278, -766340389, -984645440, -935031095, + -344611594, -427906305, -245122844, -60246291, + 1739656202, 1790575107, 2108100632, 1890328081, + 1402811438, 1586903591, 1233856572, 1149249077, + 266959938, 48394827, 369057872, 418672217, + 1002783846, 919489135, 567498868, 752375421, + 209336225, 24197544, 376187827, 459744698, + 945164165, 895287692, 574624663, 793451934, + 1679968233, 1764313568, 2117360635, 1933530610, + 1343127501, 1560637892, 1243112415, 1192455638, + -590686415, -775825096, -958608605, -875051734, + -387518699, -437395172, -219090169, -262898, + -1265457287, -1181111952, -1367032981, -1550863006, + -2134991011, -1917480620, -1700232369, -1750889146 +}; + +const int CRijndael::sm_U4[256] = +{ + 0, 151849742, 303699484, 454499602, + 607398968, 758720310, 908999204, 1059270954, + 1214797936, 1097159550, 1517440620, 1400849762, + 1817998408, 1699839814, 2118541908, 2001430874, + -1865371424, -1713521682, -2100648196, -1949848078, + -1260086056, -1108764714, -1493267772, -1342996022, + -658970480, -776608866, -895287668, -1011878526, + -57883480, -176042074, -292105548, -409216582, + 1002142683, 850817237, 698445255, 548169417, + 529487843, 377642221, 227885567, 77089521, + 1943217067, 2061379749, 1640576439, 1757691577, + 1474760595, 1592394909, 1174215055, 1290801793, + -1418998981, -1570324427, -1183720153, -1333995991, + -1889540349, -2041385971, -1656360673, -1807156719, + -486304949, -368142267, -249985705, -132870567, + -952647821, -835013507, -718427793, -601841055, + 1986918061, 2137062819, 1685577905, 1836772287, + 1381620373, 1532285339, 1078185097, 1229899655, + 1040559837, 923313619, 740276417, 621982671, + 439452389, 322734571, 137073913, 19308535, + -423803315, -273658557, -190361519, -39167137, + -1031181707, -880516741, -795640727, -643926169, + -1361764803, -1479011021, -1127282655, -1245576401, + -1964953083, -2081670901, -1728371687, -1846137065, + 1305906550, 1155237496, 1607244650, 1455525988, + 1776460110, 1626319424, 2079897426, 1928707164, + 96392454, 213114376, 396673818, 514443284, + 562755902, 679998000, 865136418, 983426092, + -586793578, -737462632, -820237430, -971956092, + -114159186, -264299872, -349698126, -500888388, + -1787927066, -1671205144, -2022411270, -1904641804, + -1319482914, -1202240816, -1556062270, -1437772596, + -321194175, -438830001, -20913827, -137500077, + -923870343, -1042034569, -621490843, -738605461, + -1531793615, -1379949505, -1230456531, -1079659997, + -2138668279, -1987344377, -1835231979, -1684955621, + 2081048481, 1963412655, 1846563261, 1729977011, + 1480485785, 1362321559, 1243905413, 1126790795, + 878845905, 1030690015, 645401037, 796197571, + 274084841, 425408743, 38544885, 188821243, + -681472870, -563312748, -981755258, -864644728, + -212492126, -94852180, -514869570, -398279248, + -1626745622, -1778065436, -1928084746, -2078357000, + -1153566510, -1305414692, -1457000754, -1607801408, + 1202797690, 1320957812, 1437280870, 1554391400, + 1669664834, 1787304780, 1906247262, 2022837584, + 265905162, 114585348, 499347990, 349075736, + 736970802, 585122620, 972512814, 821712160, + -1699282452, -1816524062, -2001922064, -2120213250, + -1098699308, -1215420710, -1399243832, -1517014842, + -757114468, -606973294, -1060810880, -909622130, + -152341084, -1671510, -453942344, -302225226, + 174567692, 57326082, 410887952, 292596766, + 777231668, 660510266, 1011452712, 893681702, + 1108339068, 1258480242, 1343618912, 1494807662, + 1715193156, 1865862730, 1948373848, 2100090966, + -1593017801, -1476300487, -1290376149, -1172609243, + -2059905521, -1942659839, -1759363053, -1641067747, + -379313593, -529979063, -75615141, -227328171, + -850391425, -1000536719, -548792221, -699985043, + 836553431, 953270745, 600235211, 718002117, + 367585007, 484830689, 133361907, 251657213, + 2041877159, 1891211689, 1806599355, 1654886325, + 1568718495, 1418573201, 1335535747, 1184342925 +}; + +const char CRijndael::sm_rcon[30] = +{ + 1, 2, 4, 8, 16, 32, + 64, -128, 27, 54, 108, -40, + -85, 77, -102, 47, 94, -68, + 99, -58, -105, 53, 106, -44, + -77, 125, -6, -17, -59, -111 +}; + +const int CRijndael::sm_shifts[3][4][2] = +{ + { {0, 0}, {1, 3}, {2, 2}, {3, 1} }, + { {0, 0}, {1, 5}, {2, 4}, {3, 3} }, + { {0, 0}, {1, 7}, {3, 5}, {4, 4} } +}; + +//Null chain +char const* CRijndael::sm_chain0 = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; + +//CONSTRUCTOR +CRijndael::CRijndael() : m_bKeyInit(false) +{ +} + +//DESTRUCTOR +CRijndael::~CRijndael() +{ +} + +//Expand a user-supplied key material into a session key. +// key - The 128/192/256-bit user-key to use. +// chain - initial chain block for CBC and CFB modes. +// keylength - 16, 24 or 32 bytes +// blockSize - The block size in bytes of this Rijndael (16, 24 or 32 bytes). +bool CRijndael::MakeKey(char const* key, char const* chain, int keylength, int blockSize) { + if (key == NULL) + return false; + if(!(16==keylength || 24==keylength || 32==keylength)) + return false; + if(!(16==blockSize || 24==blockSize || 32==blockSize)) + return false; + + m_keylength = keylength; + m_blockSize = blockSize; + + //Initialize the chain + memcpy(m_chain0, chain, m_blockSize); + memcpy(m_chain, chain, m_blockSize); + + //Calculate Number of Rounds + switch(m_keylength) + { + case 16: + m_iROUNDS = (m_blockSize == 16) ? 10 : (m_blockSize == 24 ? 12 : 14); + break; + + case 24: + m_iROUNDS = (m_blockSize != 32) ? 12 : 14; + break; + + default: // 32 bytes = 256 bits + m_iROUNDS = 14; + } + int BC = m_blockSize / 4; + int i, j; + for(i=0; i<=m_iROUNDS; i++) + { + for(j=0; j> 16) & 0xFF] & 0xFF) << 24 ^ + (sm_S[(tt >> 8) & 0xFF] & 0xFF) << 16 ^ + (sm_S[ tt & 0xFF] & 0xFF) << 8 ^ + (sm_S[(tt >> 24) & 0xFF] & 0xFF) ^ + (sm_rcon[rconpointer++] & 0xFF) << 24; + if(KC != 8) + for(i=1, j=0; i> 8) & 0xFF] & 0xFF) << 8 ^ + (sm_S[(tt >> 16) & 0xFF] & 0xFF) << 16 ^ + (sm_S[(tt >> 24) & 0xFF] & 0xFF) << 24; + for(j = KC/2, i=j+1; i> 24) & 0xFF] ^ + sm_U2[(tt >> 16) & 0xFF] ^ + sm_U3[(tt >> 8) & 0xFF] ^ + sm_U4[tt & 0xFF]; + } + m_bKeyInit = true; + + return true; +} + +//Convenience method to encrypt exactly one block of plaintext, assuming +//Rijndael's default block size (128-bit). +// in - The plaintext +// result - The ciphertext generated from a plaintext using the key +void CRijndael::DefEncryptBlock(char const* in, char* result) +{ + if(!m_bKeyInit) + return; + int* Ker = m_Ke[0]; + int t0 = ((unsigned char)*(in++) << 24); + t0 |= ((unsigned char)*(in++) << 16); + t0 |= ((unsigned char)*(in++) << 8); + (t0 |= (unsigned char)*(in++)) ^= Ker[0]; + int t1 = ((unsigned char)*(in++) << 24); + t1 |= ((unsigned char)*(in++) << 16); + t1 |= ((unsigned char)*(in++) << 8); + (t1 |= (unsigned char)*(in++)) ^= Ker[1]; + int t2 = ((unsigned char)*(in++) << 24); + t2 |= ((unsigned char)*(in++) << 16); + t2 |= ((unsigned char)*(in++) << 8); + (t2 |= (unsigned char)*(in++)) ^= Ker[2]; + int t3 = ((unsigned char)*(in++) << 24); + t3 |= ((unsigned char)*(in++) << 16); + t3 |= ((unsigned char)*(in++) << 8); + (t3 |= (unsigned char)*(in++)) ^= Ker[3]; + int a0, a1, a2, a3; + //Apply Round Transforms + for (int r = 1; r < m_iROUNDS; r++) + { + Ker = m_Ke[r]; + a0 = (sm_T1[(t0 >> 24) & 0xFF] ^ + sm_T2[(t1 >> 16) & 0xFF] ^ + sm_T3[(t2 >> 8) & 0xFF] ^ + sm_T4[t3 & 0xFF]) ^ Ker[0]; + a1 = (sm_T1[(t1 >> 24) & 0xFF] ^ + sm_T2[(t2 >> 16) & 0xFF] ^ + sm_T3[(t3 >> 8) & 0xFF] ^ + sm_T4[t0 & 0xFF]) ^ Ker[1]; + a2 = (sm_T1[(t2 >> 24) & 0xFF] ^ + sm_T2[(t3 >> 16) & 0xFF] ^ + sm_T3[(t0 >> 8) & 0xFF] ^ + sm_T4[t1 & 0xFF]) ^ Ker[2]; + a3 = (sm_T1[(t3 >> 24) & 0xFF] ^ + sm_T2[(t0 >> 16) & 0xFF] ^ + sm_T3[(t1 >> 8) & 0xFF] ^ + sm_T4[t2 & 0xFF]) ^ Ker[3]; + t0 = a0; + t1 = a1; + t2 = a2; + t3 = a3; + } + //Last Round is special + Ker = m_Ke[m_iROUNDS]; + int tt = Ker[0]; + result[0] = sm_S[(t0 >> 24) & 0xFF] ^ (tt >> 24); + result[1] = sm_S[(t1 >> 16) & 0xFF] ^ (tt >> 16); + result[2] = sm_S[(t2 >> 8) & 0xFF] ^ (tt >> 8); + result[3] = sm_S[t3 & 0xFF] ^ tt; + tt = Ker[1]; + result[4] = sm_S[(t1 >> 24) & 0xFF] ^ (tt >> 24); + result[5] = sm_S[(t2 >> 16) & 0xFF] ^ (tt >> 16); + result[6] = sm_S[(t3 >> 8) & 0xFF] ^ (tt >> 8); + result[7] = sm_S[t0 & 0xFF] ^ tt; + tt = Ker[2]; + result[8] = sm_S[(t2 >> 24) & 0xFF] ^ (tt >> 24); + result[9] = sm_S[(t3 >> 16) & 0xFF] ^ (tt >> 16); + result[10] = sm_S[(t0 >> 8) & 0xFF] ^ (tt >> 8); + result[11] = sm_S[t1 & 0xFF] ^ tt; + tt = Ker[3]; + result[12] = sm_S[(t3 >> 24) & 0xFF] ^ (tt >> 24); + result[13] = sm_S[(t0 >> 16) & 0xFF] ^ (tt >> 16); + result[14] = sm_S[(t1 >> 8) & 0xFF] ^ (tt >> 8); + result[15] = sm_S[t2 & 0xFF] ^ tt; +} + +//Convenience method to decrypt exactly one block of plaintext, assuming +//Rijndael's default block size (128-bit). +// in - The ciphertext. +// result - The plaintext generated from a ciphertext using the session key. +void CRijndael::DefDecryptBlock(char const* in, char* result) +{ + if(!m_bKeyInit) + return; + int* Kdr = m_Kd[0]; + int t0 = ((unsigned char)*(in++) << 24); + t0 = t0 | ((unsigned char)*(in++) << 16); + t0 |= ((unsigned char)*(in++) << 8); + (t0 |= (unsigned char)*(in++)) ^= Kdr[0]; + int t1 = ((unsigned char)*(in++) << 24); + t1 |= ((unsigned char)*(in++) << 16); + t1 |= ((unsigned char)*(in++) << 8); + (t1 |= (unsigned char)*(in++)) ^= Kdr[1]; + int t2 = ((unsigned char)*(in++) << 24); + t2 |= ((unsigned char)*(in++) << 16); + t2 |= ((unsigned char)*(in++) << 8); + (t2 |= (unsigned char)*(in++)) ^= Kdr[2]; + int t3 = ((unsigned char)*(in++) << 24); + t3 |= ((unsigned char)*(in++) << 16); + t3 |= ((unsigned char)*(in++) << 8); + (t3 |= (unsigned char)*(in++)) ^= Kdr[3]; + int a0, a1, a2, a3; + for(int r = 1; r < m_iROUNDS; r++) // apply round transforms + { + Kdr = m_Kd[r]; + a0 = (sm_T5[(t0 >> 24) & 0xFF] ^ + sm_T6[(t3 >> 16) & 0xFF] ^ + sm_T7[(t2 >> 8) & 0xFF] ^ + sm_T8[ t1 & 0xFF] ) ^ Kdr[0]; + a1 = (sm_T5[(t1 >> 24) & 0xFF] ^ + sm_T6[(t0 >> 16) & 0xFF] ^ + sm_T7[(t3 >> 8) & 0xFF] ^ + sm_T8[ t2 & 0xFF] ) ^ Kdr[1]; + a2 = (sm_T5[(t2 >> 24) & 0xFF] ^ + sm_T6[(t1 >> 16) & 0xFF] ^ + sm_T7[(t0 >> 8) & 0xFF] ^ + sm_T8[ t3 & 0xFF] ) ^ Kdr[2]; + a3 = (sm_T5[(t3 >> 24) & 0xFF] ^ + sm_T6[(t2 >> 16) & 0xFF] ^ + sm_T7[(t1 >> 8) & 0xFF] ^ + sm_T8[ t0 & 0xFF] ) ^ Kdr[3]; + t0 = a0; + t1 = a1; + t2 = a2; + t3 = a3; + } + //Last Round is special + Kdr = m_Kd[m_iROUNDS]; + int tt = Kdr[0]; + result[ 0] = sm_Si[(t0 >> 24) & 0xFF] ^ (tt >> 24); + result[ 1] = sm_Si[(t3 >> 16) & 0xFF] ^ (tt >> 16); + result[ 2] = sm_Si[(t2 >> 8) & 0xFF] ^ (tt >> 8); + result[ 3] = sm_Si[ t1 & 0xFF] ^ tt; + tt = Kdr[1]; + result[ 4] = sm_Si[(t1 >> 24) & 0xFF] ^ (tt >> 24); + result[ 5] = sm_Si[(t0 >> 16) & 0xFF] ^ (tt >> 16); + result[ 6] = sm_Si[(t3 >> 8) & 0xFF] ^ (tt >> 8); + result[ 7] = sm_Si[ t2 & 0xFF] ^ tt; + tt = Kdr[2]; + result[ 8] = sm_Si[(t2 >> 24) & 0xFF] ^ (tt >> 24); + result[ 9] = sm_Si[(t1 >> 16) & 0xFF] ^ (tt >> 16); + result[10] = sm_Si[(t0 >> 8) & 0xFF] ^ (tt >> 8); + result[11] = sm_Si[ t3 & 0xFF] ^ tt; + tt = Kdr[3]; + result[12] = sm_Si[(t3 >> 24) & 0xFF] ^ (tt >> 24); + result[13] = sm_Si[(t2 >> 16) & 0xFF] ^ (tt >> 16); + result[14] = sm_Si[(t1 >> 8) & 0xFF] ^ (tt >> 8); + result[15] = sm_Si[ t0 & 0xFF] ^ tt; +} + +//Encrypt exactly one block of plaintext. +// in - The plaintext. +// result - The ciphertext generated from a plaintext using the key. +bool CRijndael::EncryptBlock(char const* in, char* result) +{ + if(!m_bKeyInit) + return false; + + if(DEFAULT_BLOCK_SIZE == m_blockSize) + { + DefEncryptBlock(in, result); + return true; + } + + int BC = m_blockSize / 4; + int SC = (BC == 4) ? 0 : (BC == 6 ? 1 : 2); + int s1 = sm_shifts[SC][1][0]; + int s2 = sm_shifts[SC][2][0]; + int s3 = sm_shifts[SC][3][0]; + //Temporary Work Arrays + int i; + int tt; + int* pi = t; + for(i=0; i> 24) & 0xFF] ^ + sm_T2[(t[(i + s1) % BC] >> 16) & 0xFF] ^ + sm_T3[(t[(i + s2) % BC] >> 8) & 0xFF] ^ + sm_T4[ t[(i + s3) % BC] & 0xFF] ) ^ m_Ke[r][i]; + memcpy(t, a, 4*BC); + } + int j; + //Last Round is Special + for(i=0,j=0; i> 24) & 0xFF] ^ (tt >> 24); + result[j++] = sm_S[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16); + result[j++] = sm_S[(t[(i + s2) % BC] >> 8) & 0xFF] ^ (tt >> 8); + result[j++] = sm_S[ t[(i + s3) % BC] & 0xFF] ^ tt; + } + + return true; +} + +//Decrypt exactly one block of ciphertext. +// in - The ciphertext. +// result - The plaintext generated from a ciphertext using the session key. +bool CRijndael::DecryptBlock(char const* in, char* result) +{ + if(!m_bKeyInit) + return false; + + if(DEFAULT_BLOCK_SIZE == m_blockSize) + { + DefDecryptBlock(in, result); + return true; + } + + int BC = m_blockSize / 4; + int SC = BC == 4 ? 0 : (BC == 6 ? 1 : 2); + int s1 = sm_shifts[SC][1][1]; + int s2 = sm_shifts[SC][2][1]; + int s3 = sm_shifts[SC][3][1]; + //Temporary Work Arrays + int i; + int tt; + int* pi = t; + for(i=0; i> 24) & 0xFF] ^ + sm_T6[(t[(i + s1) % BC] >> 16) & 0xFF] ^ + sm_T7[(t[(i + s2) % BC] >> 8) & 0xFF] ^ + sm_T8[ t[(i + s3) % BC] & 0xFF]) ^ m_Kd[r][i]; + memcpy(t, a, 4*BC); + } + int j; + //Last Round is Special + for(i=0,j=0; i> 24) & 0xFF] ^ (tt >> 24); + result[j++] = sm_Si[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16); + result[j++] = sm_Si[(t[(i + s2) % BC] >> 8) & 0xFF] ^ (tt >> 8); + result[j++] = sm_Si[ t[(i + s3) % BC] & 0xFF] ^ tt; + } + + return true; +} + +bool CRijndael::Encrypt(char const* in, char* result, size_t n, int iMode) +{ + if (!m_bKeyInit) + return false; + + //n should be > 0 and multiple of m_blockSize + if(n == 0 || n % m_blockSize != 0) + return false; + + unsigned int i; + char const* pin; + char* presult; + if(CBC == iMode) { //CBC mode, using the Chain + for (i=0,pin=in,presult=result; i 0 and multiple of m_blockSize + if (n == 0 || n % m_blockSize != 0) + return false; + + unsigned int i; + char const* pin; + char* presult; + if(CBC == iMode) //CBC mode, using the Chain + { + for(i=0,pin=in,presult=result; i + +//Rijndael (pronounced Reindaal) is a block cipher, designed by Joan Daemen and Vincent Rijmen as a candidate algorithm for the AES. +//The cipher has a variable block length and key length. The authors currently specify how to use keys with a length +//of 128, 192, or 256 bits to encrypt blocks with al length of 128, 192 or 256 bits (all nine combinations of +//key length and block length are possible). Both block length and key length can be extended very easily to +// multiples of 32 bits. +//Rijndael can be implemented very efficiently on a wide range of processors and in hardware. +//This implementation is based on the Java Implementation used with the Cryptix toolkit found at: +//http://www.esat.kuleuven.ac.be/~rijmen/rijndael/rijndael.zip +//Java code authors: Raif S. Naffah, Paulo S. L. M. Barreto +//This Implementation was tested against KAT test published by the authors of the method and the +//results were identical. + +class CRijndael +{ +public: + //Operation Modes + //The Electronic Code Book (ECB), Cipher Block Chaining (CBC) and Cipher Feedback Block (CFB) modes + //are implemented. + //In ECB mode if the same block is encrypted twice with the same key, the resulting + //ciphertext blocks are the same. + //In CBC Mode a ciphertext block is obtained by first xoring the + //plaintext block with the previous ciphertext block, and encrypting the resulting value. + //In CFB mode a ciphertext block is obtained by encrypting the previous ciphertext block + //and xoring the resulting value with the plaintext. + enum { ECB=0, CBC=1, CFB=2 }; + +private: + enum { DEFAULT_BLOCK_SIZE=16 }; + enum { MAX_BLOCK_SIZE=32, MAX_ROUNDS=14, MAX_KC=8, MAX_BC=8 }; + + //Auxiliary Functions + //Multiply two elements of GF(2^m) + static int Mul(int a, int b) + { + return (a != 0 && b != 0) ? sm_alog[(sm_log[a & 0xFF] + sm_log[b & 0xFF]) % 255] : 0; + } + + //Convenience method used in generating Transposition Boxes + static int Mul4(int a, char b[]) + { + if(a == 0) + return 0; + a = sm_log[a & 0xFF]; + int a0 = (b[0] != 0) ? sm_alog[(a + sm_log[b[0] & 0xFF]) % 255] & 0xFF : 0; + int a1 = (b[1] != 0) ? sm_alog[(a + sm_log[b[1] & 0xFF]) % 255] & 0xFF : 0; + int a2 = (b[2] != 0) ? sm_alog[(a + sm_log[b[2] & 0xFF]) % 255] & 0xFF : 0; + int a3 = (b[3] != 0) ? sm_alog[(a + sm_log[b[3] & 0xFF]) % 255] & 0xFF : 0; + return a0 << 24 | a1 << 16 | a2 << 8 | a3; + } + +public: + //CONSTRUCTOR + CRijndael(); + + //DESTRUCTOR + virtual ~CRijndael(); + + //Expand a user-supplied key material into a session key. + // key - The 128/192/256-bit user-key to use. + // chain - initial chain block for CBC and CFB modes. + // keylength - 16, 24 or 32 bytes + // blockSize - The block size in bytes of this Rijndael (16, 24 or 32 bytes). + bool MakeKey(char const* key, char const* chain, int keylengt, int blockSize); + +private: + //Auxiliary Function + void Xor(char* buff, char const* chain) + { + for(unsigned int i=0; i> 16) & 0xFF] & 0xFF) << 24 ^ + (sm_S[(tt >> 8) & 0xFF] & 0xFF) << 16 ^ + (sm_S[ tt & 0xFF] & 0xFF) << 8 ^ + (sm_S[(tt >> 24) & 0xFF] & 0xFF) ^ + (sm_rcon[rconpointer++] & 0xFF) << 24; + if(KC != 8) + for(i=1, j=0; i> 8) & 0xFF] & 0xFF) << 8 ^ + (sm_S[(tt >> 16) & 0xFF] & 0xFF) << 16 ^ + (sm_S[(tt >> 24) & 0xFF] & 0xFF) << 24; + for(j = KC/2, i=j+1; i> 24) & 0xFF] ^ + sm_U2[(tt >> 16) & 0xFF] ^ + sm_U3[(tt >> 8) & 0xFF] ^ + sm_U4[tt & 0xFF]; + } + m_bKeyInit = true; + + return true; +} + +//Convenience method to encrypt exactly one block of plaintext, assuming +//Rijndael's default block size (128-bit). +// in - The plaintext +// result - The ciphertext generated from a plaintext using the key +void CRijndaelChanged::DefEncryptBlock(char const* in, char* result) +{ + if(!m_bKeyInit) + return; + int* Ker = m_Ke[0]; + int t0 = ((unsigned char)*(in++) << 24); + t0 |= ((unsigned char)*(in++) << 16); + t0 |= ((unsigned char)*(in++) << 8); + (t0 |= (unsigned char)*(in++)) ^= Ker[0]; + int t1 = ((unsigned char)*(in++) << 24); + t1 |= ((unsigned char)*(in++) << 16); + t1 |= ((unsigned char)*(in++) << 8); + (t1 |= (unsigned char)*(in++)) ^= Ker[1]; + int t2 = ((unsigned char)*(in++) << 24); + t2 |= ((unsigned char)*(in++) << 16); + t2 |= ((unsigned char)*(in++) << 8); + (t2 |= (unsigned char)*(in++)) ^= Ker[2]; + int t3 = ((unsigned char)*(in++) << 24); + t3 |= ((unsigned char)*(in++) << 16); + t3 |= ((unsigned char)*(in++) << 8); + (t3 |= (unsigned char)*(in++)) ^= Ker[3]; + int a0, a1, a2, a3; + //Apply Round Transforms + for (int r = 1; r < m_iROUNDS; r++) + { + Ker = m_Ke[r]; + a0 = (sm_T1[(t0 >> 24) & 0xFF] ^ + sm_T2[(t1 >> 16) & 0xFF] ^ + sm_T3[(t2 >> 8) & 0xFF] ^ + sm_T4[t3 & 0xFF]) ^ Ker[0]; + a1 = (sm_T1[(t1 >> 24) & 0xFF] ^ + sm_T2[(t2 >> 16) & 0xFF] ^ + sm_T3[(t3 >> 8) & 0xFF] ^ + sm_T4[t0 & 0xFF]) ^ Ker[1]; + a2 = (sm_T1[(t2 >> 24) & 0xFF] ^ + sm_T2[(t3 >> 16) & 0xFF] ^ + sm_T3[(t0 >> 8) & 0xFF] ^ + sm_T4[t1 & 0xFF]) ^ Ker[2]; + a3 = (sm_T1[(t3 >> 24) & 0xFF] ^ + sm_T2[(t0 >> 16) & 0xFF] ^ + sm_T3[(t1 >> 8) & 0xFF] ^ + sm_T4[t2 & 0xFF]) ^ Ker[3]; + t0 = a0; + t1 = a1; + t2 = a2; + t3 = a3; + } + //Last Round is special + Ker = m_Ke[m_iROUNDS]; + int tt = Ker[0]; + result[0] = sm_S[(t0 >> 24) & 0xFF] ^ (tt >> 24); + result[1] = sm_S[(t1 >> 16) & 0xFF] ^ (tt >> 16); + result[2] = sm_S[(t2 >> 8) & 0xFF] ^ (tt >> 8); + result[3] = sm_S[t3 & 0xFF] ^ tt; + tt = Ker[1]; + result[4] = sm_S[(t1 >> 24) & 0xFF] ^ (tt >> 24); + result[5] = sm_S[(t2 >> 16) & 0xFF] ^ (tt >> 16); + result[6] = sm_S[(t3 >> 8) & 0xFF] ^ (tt >> 8); + result[7] = sm_S[t0 & 0xFF] ^ tt; + tt = Ker[2]; + result[8] = sm_S[(t2 >> 24) & 0xFF] ^ (tt >> 24); + result[9] = sm_S[(t3 >> 16) & 0xFF] ^ (tt >> 16); + result[10] = sm_S[(t0 >> 8) & 0xFF] ^ (tt >> 8); + result[11] = sm_S[t1 & 0xFF] ^ tt; + tt = Ker[3]; + result[12] = sm_S[(t3 >> 24) & 0xFF] ^ (tt >> 24); + result[13] = sm_S[(t0 >> 16) & 0xFF] ^ (tt >> 16); + result[14] = sm_S[(t1 >> 8) & 0xFF] ^ (tt >> 8); + result[15] = sm_S[t2 & 0xFF] ^ tt; +} + +//Convenience method to decrypt exactly one block of plaintext, assuming +//Rijndael's default block size (128-bit). +// in - The ciphertext. +// result - The plaintext generated from a ciphertext using the session key. +void CRijndaelChanged::DefDecryptBlock(char const* in, char* result) +{ + if(!m_bKeyInit) + return; + int* Kdr = m_Kd[0]; + int t0 = ((unsigned char)*(in++) << 24); + t0 = t0 | ((unsigned char)*(in++) << 16); + t0 |= ((unsigned char)*(in++) << 8); + (t0 |= (unsigned char)*(in++)) ^= Kdr[0]; + int t1 = ((unsigned char)*(in++) << 24); + t1 |= ((unsigned char)*(in++) << 16); + t1 |= ((unsigned char)*(in++) << 8); + (t1 |= (unsigned char)*(in++)) ^= Kdr[1]; + int t2 = ((unsigned char)*(in++) << 24); + t2 |= ((unsigned char)*(in++) << 16); + t2 |= ((unsigned char)*(in++) << 8); + (t2 |= (unsigned char)*(in++)) ^= Kdr[2]; + int t3 = ((unsigned char)*(in++) << 24); + t3 |= ((unsigned char)*(in++) << 16); + t3 |= ((unsigned char)*(in++) << 8); + (t3 |= (unsigned char)*(in++)) ^= Kdr[3]; + int a0, a1, a2, a3; + for(int r = 1; r < m_iROUNDS; r++) // apply round transforms + { + Kdr = m_Kd[r]; + a0 = (sm_T5[(t0 >> 24) & 0xFF] ^ + sm_T6[(t3 >> 16) & 0xFF] ^ + sm_T7[(t2 >> 8) & 0xFF] ^ + sm_T8[ t1 & 0xFF] ) ^ Kdr[0]; + a1 = (sm_T5[(t1 >> 24) & 0xFF] ^ + sm_T6[(t0 >> 16) & 0xFF] ^ + sm_T7[(t3 >> 8) & 0xFF] ^ + sm_T8[ t2 & 0xFF] ) ^ Kdr[1]; + a2 = (sm_T5[(t2 >> 24) & 0xFF] ^ + sm_T6[(t1 >> 16) & 0xFF] ^ + sm_T7[(t0 >> 8) & 0xFF] ^ + sm_T8[ t3 & 0xFF] ) ^ Kdr[2]; + a3 = (sm_T5[(t3 >> 24) & 0xFF] ^ + sm_T6[(t2 >> 16) & 0xFF] ^ + sm_T7[(t1 >> 8) & 0xFF] ^ + sm_T8[ t0 & 0xFF] ) ^ Kdr[3]; + t0 = a0; + t1 = a1; + t2 = a2; + t3 = a3; + } + //Last Round is special + Kdr = m_Kd[m_iROUNDS]; + int tt = Kdr[0]; + result[ 0] = sm_Si[(t0 >> 24) & 0xFF] ^ (tt >> 24); + result[ 1] = sm_Si[(t3 >> 16) & 0xFF] ^ (tt >> 16); + result[ 2] = sm_Si[(t2 >> 8) & 0xFF] ^ (tt >> 8); + result[ 3] = sm_Si[ t1 & 0xFF] ^ tt; + tt = Kdr[1]; + result[ 4] = sm_Si[(t1 >> 24) & 0xFF] ^ (tt >> 24); + result[ 5] = sm_Si[(t0 >> 16) & 0xFF] ^ (tt >> 16); + result[ 6] = sm_Si[(t3 >> 8) & 0xFF] ^ (tt >> 8); + result[ 7] = sm_Si[ t2 & 0xFF] ^ tt; + tt = Kdr[2]; + result[ 8] = sm_Si[(t2 >> 24) & 0xFF] ^ (tt >> 24); + result[ 9] = sm_Si[(t1 >> 16) & 0xFF] ^ (tt >> 16); + result[10] = sm_Si[(t0 >> 8) & 0xFF] ^ (tt >> 8); + result[11] = sm_Si[ t3 & 0xFF] ^ tt; + tt = Kdr[3]; + result[12] = sm_Si[(t3 >> 24) & 0xFF] ^ (tt >> 24); + result[13] = sm_Si[(t2 >> 16) & 0xFF] ^ (tt >> 16); + result[14] = sm_Si[(t1 >> 8) & 0xFF] ^ (tt >> 8); + result[15] = sm_Si[ t0 & 0xFF] ^ tt; +} + +//Encrypt exactly one block of plaintext. +// in - The plaintext. +// result - The ciphertext generated from a plaintext using the key. +bool CRijndaelChanged::EncryptBlock(char const* in, char* result) +{ + if(!m_bKeyInit) + return false; + + if(DEFAULT_BLOCK_SIZE == m_blockSize) + { + DefEncryptBlock(in, result); + return true; + } + + int BC = m_blockSize / 4; + int SC = (BC == 4) ? 0 : (BC == 6 ? 1 : 2); + int s1 = sm_shifts[SC][1][0]; + int s2 = sm_shifts[SC][2][0]; + int s3 = sm_shifts[SC][3][0]; + //Temporary Work Arrays + int i; + int tt; + int* pi = t; + for(i=0; i> 24) & 0xFF] ^ + sm_T2[(t[(i + s1) % BC] >> 16) & 0xFF] ^ + sm_T3[(t[(i + s2) % BC] >> 8) & 0xFF] ^ + sm_T4[ t[(i + s3) % BC] & 0xFF] ) ^ m_Ke[r][i]; + memcpy(t, a, 4*BC); + } + int j; + //Last Round is Special + for(i=0,j=0; i> 24) & 0xFF] ^ (tt >> 24); + result[j++] = sm_S[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16); + result[j++] = sm_S[(t[(i + s2) % BC] >> 8) & 0xFF] ^ (tt >> 8); + result[j++] = sm_S[ t[(i + s3) % BC] & 0xFF] ^ tt; + } + + return true; +} + +//Decrypt exactly one block of ciphertext. +// in - The ciphertext. +// result - The plaintext generated from a ciphertext using the session key. +bool CRijndaelChanged::DecryptBlock(char const* in, char* result) +{ + if(!m_bKeyInit) + return false; + + if(DEFAULT_BLOCK_SIZE == m_blockSize) + { + DefDecryptBlock(in, result); + return true; + } + + int BC = m_blockSize / 4; + int SC = BC == 4 ? 0 : (BC == 6 ? 1 : 2); + int s1 = sm_shifts[SC][1][1]; + int s2 = sm_shifts[SC][2][1]; + int s3 = sm_shifts[SC][3][1]; + //Temporary Work Arrays + int i; + int tt; + int* pi = t; + for(i=0; i> 24) & 0xFF] ^ + sm_T6[(t[(i + s1) % BC] >> 16) & 0xFF] ^ + sm_T7[(t[(i + s2) % BC] >> 8) & 0xFF] ^ + sm_T8[ t[(i + s3) % BC] & 0xFF]) ^ m_Kd[r][i]; + memcpy(t, a, 4*BC); + } + int j; + //Last Round is Special + for(i=0,j=0; i> 24) & 0xFF] ^ (tt >> 24); + result[j++] = sm_Si[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16); + result[j++] = sm_Si[(t[(i + s2) % BC] >> 8) & 0xFF] ^ (tt >> 8); + result[j++] = sm_Si[ t[(i + s3) % BC] & 0xFF] ^ tt; + } + + return true; +} + +bool CRijndaelChanged::Encrypt(char const* in, char* result, size_t n, int iMode) +{ + if (!m_bKeyInit) + return false; + + //n should be > 0 and multiple of m_blockSize + if(n == 0 || n % m_blockSize != 0) + return false; + + unsigned int i; + char const* pin; + char* presult; + if(CBC == iMode) { //CBC mode, using the Chain + for (i=0,pin=in,presult=result; i 0 and multiple of m_blockSize + if (n == 0 || n % m_blockSize != 0) + return false; + + unsigned int i; + char const* pin; + char* presult; + if(CBC == iMode) //CBC mode, using the Chain + { + for(i=0,pin=in,presult=result; i + +//Rijndael (pronounced Reindaal) is a block cipher, designed by Joan Daemen and Vincent Rijmen as a candidate algorithm for the AES. +//The cipher has a variable block length and key length. The authors currently specify how to use keys with a length +//of 128, 192, or 256 bits to encrypt blocks with al length of 128, 192 or 256 bits (all nine combinations of +//key length and block length are possible). Both block length and key length can be extended very easily to +// multiples of 32 bits. +//Rijndael can be implemented very efficiently on a wide range of processors and in hardware. +//This implementation is based on the Java Implementation used with the Cryptix toolkit found at: +//http://www.esat.kuleuven.ac.be/~rijmen/rijndael/rijndael.zip +//Java code authors: Raif S. Naffah, Paulo S. L. M. Barreto +//This Implementation was tested against KAT test published by the authors of the method and the +//results were identical. + +class CRijndaelChanged +{ +public: + //Operation Modes + //The Electronic Code Book (ECB), Cipher Block Chaining (CBC) and Cipher Feedback Block (CFB) modes + //are implemented. + //In ECB mode if the same block is encrypted twice with the same key, the resulting + //ciphertext blocks are the same. + //In CBC Mode a ciphertext block is obtained by first xoring the + //plaintext block with the previous ciphertext block, and encrypting the resulting value. + //In CFB mode a ciphertext block is obtained by encrypting the previous ciphertext block + //and xoring the resulting value with the plaintext. + enum { ECB = 0, CBC = 1, CFB = 2 }; + +private: + enum { DEFAULT_BLOCK_SIZE = 16 }; + enum { MAX_BLOCK_SIZE = 32, MAX_ROUNDS = 14, MAX_KC = 8, MAX_BC = 8 }; + + //Auxiliary Functions + //Multiply two elements of GF(2^m) + static int Mul(int a, int b) + { + return (a != 0 && b != 0) ? sm_alog[(sm_log[a & 0xFF] + sm_log[b & 0xFF]) % 255] : 0; + } + + //Convenience method used in generating Transposition Boxes + static int Mul4(int a, char b[]) + { + if (a == 0) + return 0; + a = sm_log[a & 0xFF]; + int a0 = (b[0] != 0) ? sm_alog[(a + sm_log[b[0] & 0xFF]) % 255] & 0xFF : 0; + int a1 = (b[1] != 0) ? sm_alog[(a + sm_log[b[1] & 0xFF]) % 255] & 0xFF : 0; + int a2 = (b[2] != 0) ? sm_alog[(a + sm_log[b[2] & 0xFF]) % 255] & 0xFF : 0; + int a3 = (b[3] != 0) ? sm_alog[(a + sm_log[b[3] & 0xFF]) % 255] & 0xFF : 0; + return a0 << 24 | a1 << 16 | a2 << 8 | a3; + } + +public: + //CONSTRUCTOR + CRijndaelChanged(); + + //DESTRUCTOR + virtual ~CRijndaelChanged(); + + //Expand a user-supplied key material into a session key. + // key - The 128/192/256-bit user-key to use. + // chain - initial chain block for CBC and CFB modes. + // keylength - 16, 24 or 32 bytes + // blockSize - The block size in bytes of this Rijndael (16, 24 or 32 bytes). + bool MakeKey(char const* key, char const* chain, int keylength = DEFAULT_BLOCK_SIZE, int blockSize = DEFAULT_BLOCK_SIZE); + +private: + //Auxiliary Function + void Xor(char* buff, char const* chain) + { + for (unsigned int i = 0; i < m_blockSize; i++) + *(buff++) ^= *(chain++); + } + + //Convenience method to encrypt exactly one block of plaintext, assuming + //Rijndael's default block size (128-bit). + // in - The plaintext + // result - The ciphertext generated from a plaintext using the key + void DefEncryptBlock(char const* in, char* result); + + //Convenience method to decrypt exactly one block of plaintext, assuming + //Rijndael's default block size (128-bit). + // in - The ciphertext. + // result - The plaintext generated from a ciphertext using the session key. + void DefDecryptBlock(char const* in, char* result); + +public: + //Encrypt exactly one block of plaintext. + // in - The plaintext. + // result - The ciphertext generated from a plaintext using the key. + bool EncryptBlock(char const* in, char* result); + + //Decrypt exactly one block of ciphertext. + // in - The ciphertext. + // result - The plaintext generated from a ciphertext using the session key. + bool DecryptBlock(char const* in, char* result); + + bool Encrypt(char const* in, char* result, size_t n, int iMode = ECB); + + bool Decrypt(char const* in, char* result, size_t n, int iMode = ECB); + + //Get Key Length + int GetKeyLength() { + if (!m_bKeyInit) + return 0; + return m_keylength; + } + + //Block Size + int GetBlockSize() { + if (!m_bKeyInit) + return 0; + return m_blockSize; + } + + //Number of Rounds + int GetRounds() { + if (!m_bKeyInit) + return 0; + return m_iROUNDS; + } + + void ResetChain() + { + memcpy(m_chain, m_chain0, m_blockSize); + } + +public: + //Null chain + static char const* sm_chain0; + +private: + static const int sm_alog[256]; + static const int sm_log[256]; + static const char sm_S[256]; + static const char sm_Si[256]; + static const int sm_T1[256]; + static const int sm_T2[256]; + static const int sm_T3[256]; + static const int sm_T4[256]; + static const int sm_T5[256]; + static const int sm_T6[256]; + static const int sm_T7[256]; + static const int sm_T8[256]; + static const int sm_U1[256]; + static const int sm_U2[256]; + static const int sm_U3[256]; + static const int sm_U4[256]; + static const char sm_rcon[30]; + static const int sm_shifts[3][4][2]; + + //Key Initialization Flag + bool m_bKeyInit; + + //Encryption (m_Ke) round key + int m_Ke[MAX_ROUNDS + 1][MAX_BC]; + //Decryption (m_Kd) round key + int m_Kd[MAX_ROUNDS + 1][MAX_BC]; + + //Key Length + unsigned int m_keylength; + + //Block Size + unsigned int m_blockSize; + + //Number of Rounds + int m_iROUNDS; + //Chain Block + char m_chain0[MAX_BLOCK_SIZE]; + char m_chain[MAX_BLOCK_SIZE]; + //Auxiliary private use buffers + int tk[MAX_KC]; + int a[MAX_BC]; + int t[MAX_BC]; +}; diff --git a/reunion/src/Sizebuf.cpp b/reunion/src/Sizebuf.cpp new file mode 100644 index 0000000..4323dfb --- /dev/null +++ b/reunion/src/Sizebuf.cpp @@ -0,0 +1,455 @@ +#include "precompiled.h" + +uint8* CSizeBuf::GetSpace(unsigned int len) { + if (m_bOverflowed) { + return NULL; + } + + if (m_CurSize + len + BITS_WRITING_RESERVE > m_MaxSize) { + m_bOverflowed = true; + return NULL; + } + + uint8* res = m_Data + m_CurSize; + m_CurSize += len; + return res; +} + +bool CSizeBuf::Write(const void *data, unsigned int length) { + ensureNoBitsOp(); + uint8* buf = GetSpace(length); + if (!buf) + return false; + + memcpy(buf, data, length); + return true; +} + +bool CSizeBuf::Print(const char *data) { + ensureNoBitsOp(); + return Write(data, strlen(data) + 1); +} + +bool CSizeBuf::WriteChar(int8 val) { + return WritePrimitive(val); +} + +bool CSizeBuf::WriteByte(uint8 val) { + return WritePrimitive(val); +} + +bool CSizeBuf::WriteShort(int16 val) { + return WritePrimitive(val); +} + +bool CSizeBuf::WriteWord(uint16 val) { + return WritePrimitive(val); +} + +bool CSizeBuf::WriteDWord(uint32 val) { + return WritePrimitive(val); +} + +bool CSizeBuf::WriteUint64(uint64 val) { + return WritePrimitive(val); +} + +bool CSizeBuf::WriteLong(int32 val) { + return WritePrimitive(val); +} + +bool CSizeBuf::WriteFloat(float val) { + return WritePrimitive(val); +} + +bool CSizeBuf::WriteString(const char* s) { + if (!s) s = ""; + return Write(s, strlen(s) + 1); +} + +#ifdef SIZEBUF_BITS +const uint32 BITTABLE[] = +{ + 0x00000001, 0x00000002, 0x00000004, 0x00000008, + 0x00000010, 0x00000020, 0x00000040, 0x00000080, + 0x00000100, 0x00000200, 0x00000400, 0x00000800, + 0x00001000, 0x00002000, 0x00004000, 0x00008000, + 0x00010000, 0x00020000, 0x00040000, 0x00080000, + 0x00100000, 0x00200000, 0x00400000, 0x00800000, + 0x01000000, 0x02000000, 0x04000000, 0x08000000, + 0x10000000, 0x20000000, 0x40000000, 0x80000000, + 0x00000000, +}; + +const uint32 ROWBITTABLE[] = +{ + 0x00000000, 0x00000001, 0x00000003, 0x00000007, + 0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F, + 0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF, + 0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF, + 0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF, + 0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF, + 0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, + 0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, + 0xFFFFFFFF, +}; + +const uint32 INVBITTABLE[] = +{ + 0xFFFFFFFE, 0xFFFFFFFD, 0xFFFFFFFB, 0xFFFFFFF7, + 0xFFFFFFEF, 0xFFFFFFDF, 0xFFFFFFBF, 0xFFFFFF7F, + 0xFFFFFEFF, 0xFFFFFDFF, 0xFFFFFBFF, 0xFFFFF7FF, + 0xFFFFEFFF, 0xFFFFDFFF, 0xFFFFBFFF, 0xFFFF7FFF, + 0xFFFEFFFF, 0xFFFDFFFF, 0xFFFBFFFF, 0xFFF7FFFF, + 0xFFEFFFFF, 0xFFDFFFFF, 0xFFBFFFFF, 0xFF7FFFFF, + 0xFEFFFFFF, 0xFDFFFFFF, 0xFBFFFFFF, 0xF7FFFFFF, + 0xEFFFFFFF, 0xDFFFFFFF, 0xBFFFFFFF, 0x7FFFFFFF, + 0xFFFFFFFF, +}; + +void CSizeBuf::StartBitWriting() { + ensureNoBitsOp(); + + m_BFWrite.nCurOutputBit = 0; + m_BFWrite.pOutByte = m_Data + m_CurSize; + m_bBitsWriting = true; +} + +void CSizeBuf::EndBitWriting() { + ensureBitsWriting(); + m_bBitsWriting = false; + + if (m_bOverflowed) { + return; + } + + *m_BFWrite.pOutByte &= 255 >> (8 - m_BFWrite.nCurOutputBit); + GetSpace(1); + m_BFWrite.nCurOutputBit = 0; + m_BFWrite.pOutByte = 0; +} + +void CSizeBuf::WriteOneBit(int val) { + ensureBitsWriting(); + + if (m_BFWrite.nCurOutputBit >= 8) + { + m_BFWrite.pOutByte = GetSpace(1); + m_BFWrite.nCurOutputBit = 0; + } + + if (m_bOverflowed) + return; + + if (val) { + *m_BFWrite.pOutByte |= BITTABLE[m_BFWrite.nCurOutputBit]; + } else { + *m_BFWrite.pOutByte &= INVBITTABLE[m_BFWrite.nCurOutputBit * 4]; + } + + m_BFWrite.nCurOutputBit++; +} + +void CSizeBuf::WriteBits(uint32 data, unsigned int numbits) { + ensureBitsWriting(); + if (numbits < 32) + { + if (data >= (uint32)(1 << numbits)) + data = ROWBITTABLE[numbits]; + } + + int surplusBytes = 0; + if ((uint32)m_BFWrite.nCurOutputBit >= 8) + { + surplusBytes = 1; + m_BFWrite.nCurOutputBit = 0; + ++m_BFWrite.pOutByte; + } + + int bits = numbits + m_BFWrite.nCurOutputBit; + if (bits <= 32) + { + int bytesToWrite = bits >> 3; + int bitsLeft = bits & 7; + if (!bitsLeft) + --bytesToWrite; + GetSpace(surplusBytes + bytesToWrite); + if (!m_bOverflowed) + { + *(uint32 *)m_BFWrite.pOutByte = (data << m_BFWrite.nCurOutputBit) | *(uint32 *)m_BFWrite.pOutByte & ROWBITTABLE[m_BFWrite.nCurOutputBit]; + m_BFWrite.nCurOutputBit = 8; + if (bitsLeft) + m_BFWrite.nCurOutputBit = bitsLeft; + m_BFWrite.pOutByte = &m_BFWrite.pOutByte[bytesToWrite]; + } + } + else + { + GetSpace(surplusBytes + 4); + if (!m_bOverflowed) + { + *(uint32 *)m_BFWrite.pOutByte = (data << m_BFWrite.nCurOutputBit) | *(uint32 *)m_BFWrite.pOutByte & ROWBITTABLE[m_BFWrite.nCurOutputBit]; + int leftBits = 32 - m_BFWrite.nCurOutputBit; + m_BFWrite.nCurOutputBit = bits & 7; + m_BFWrite.pOutByte += 4; + *(uint32 *)m_BFWrite.pOutByte = data >> leftBits; + } + } +} + +void CSizeBuf::WriteSBits(int data, unsigned int numbits) { + ensureBitsWriting(); + int idata = data; + + if (numbits < 32) + { + int maxnum = (1 << (numbits - 1)) - 1; + + if (data > maxnum || (maxnum = -maxnum, data < maxnum)) + { + idata = maxnum; + } + } + + int sigbits = idata < 0; + + WriteOneBit(sigbits); + WriteBits(abs(idata), numbits - 1); +} + +void CSizeBuf::WriteBitString(const char *p) { + ensureBitsWriting(); + const char *pch = p; + + while (*pch) { + WriteBits(*pch, 8); + ++pch; + } + + WriteBits(0, 8); +} + +void CSizeBuf::WriteBitData(void *src, unsigned int length) { + ensureBitsWriting(); + uint8 *p = (uint8 *)src; + + for (unsigned int i = 0; i < length; i++, p++) { + WriteBits(*p, 8); + } +} + +void CSizeBuf::StartBitReading() { + ensureNoBitsOp(); + m_BFRead.nCurInputBit = 0; + m_BFRead.nBytesRead = 0; + m_BFRead.nBitFieldReadStartByte = m_ReadCount; + m_BFRead.pInByte = m_Data + m_ReadCount; + m_BFRead.nMsgReadCount = m_ReadCount + 1; + + if (m_ReadCount + 1 > m_CurSize) { + m_bBadRead = true; + } + + m_bBitsReading = true; +} + +void CSizeBuf::EndBitReading() { + ensureBitsReading(); + + if (m_BFRead.nMsgReadCount > m_CurSize) { + m_bBadRead = true; + } + + m_ReadCount = m_BFRead.nMsgReadCount; + m_BFRead.nBitFieldReadStartByte = 0; + m_BFRead.nCurInputBit = 0; + m_BFRead.nBytesRead = 0; + m_BFRead.pInByte = 0; + + m_bBitsReading = false; +} + +int CSizeBuf::CurrentBit() { + ensureBitsReading(); + + return m_BFRead.nCurInputBit + 8 * m_BFRead.nBytesRead; +} + +int CSizeBuf::ReadOneBit() { + int nValue; + + if (m_bBadRead) { + return 1; + } + + if (m_BFRead.nCurInputBit >= 8) + { + ++m_BFRead.nMsgReadCount; + m_BFRead.nCurInputBit = 0; + ++m_BFRead.nBytesRead; + ++m_BFRead.pInByte; + } + + if (m_BFRead.nMsgReadCount <= m_CurSize) + { + nValue = (*m_BFRead.pInByte & BITTABLE[m_BFRead.nCurInputBit]) != 0; + ++m_BFRead.nCurInputBit; + } + else + { + nValue = 1; + m_bBadRead = true; + } + + return nValue; +} + +uint32 CSizeBuf::ReadBits(unsigned int numbits) { + uint32 result; + + if (m_bBadRead) { + return 1; + } + + if (m_BFRead.nCurInputBit >= 8) + { + ++m_BFRead.nMsgReadCount; + ++m_BFRead.nBytesRead; + ++m_BFRead.pInByte; + + m_BFRead.nCurInputBit = 0; + } + + uint32 bits = (m_BFRead.nCurInputBit + numbits) & 7; + + if ((unsigned int)(m_BFRead.nCurInputBit + numbits) <= 32) { + result = (*(unsigned int *)m_BFRead.pInByte >> m_BFRead.nCurInputBit) & ROWBITTABLE[numbits]; + + uint32 bytes = (m_BFRead.nCurInputBit + numbits) >> 3; + + if (bits) { + m_BFRead.nCurInputBit = bits; + } else { + m_BFRead.nCurInputBit = 8; + bytes--; + } + + m_BFRead.pInByte += bytes; + m_BFRead.nMsgReadCount += bytes; + m_BFRead.nBytesRead += bytes; + } + else + { + result = ((*(unsigned int *)(m_BFRead.pInByte + 4) & ROWBITTABLE[bits]) << (32 - m_BFRead.nCurInputBit)) | (*(unsigned int *)m_BFRead.pInByte >> m_BFRead.nCurInputBit); + m_BFRead.nCurInputBit = bits; + m_BFRead.pInByte += 4; + m_BFRead.nMsgReadCount += 4; + m_BFRead.nBytesRead += 4; + } + + if (m_BFRead.nMsgReadCount > m_CurSize) + { + result = 1; + m_bBadRead = true; + } + + return result; +} + +int CSizeBuf::ReadSBits(unsigned int numbits) { + int nSignBit = ReadOneBit(); + int result = ReadBits(numbits - 1); + + if (nSignBit) { + result = -result; + } + + return result; +} +#endif // SIZEBUF_BITS + +CSizeBuf::CSizeBuf(const uint8* buf, unsigned int maxSize, unsigned int curSize) { + Clear(); + m_Data = (uint8_t *)buf; + m_MaxSize = maxSize; + m_CurSize = curSize; +} + +void CSizeBuf::Clear() { + m_CurSize = m_ReadCount = 0; + m_bOverflowed = m_bBadRead = false; +#ifdef SIZEBUF_BITS + m_bBitsWriting = m_bBitsReading = false; + + memset(&m_BFRead, 0, sizeof(m_BFRead)); + memset(&m_BFWrite, 0, sizeof(m_BFWrite)); +#endif // SIZEBUF_BITS +} + +uint32 CSizeBuf::ReadDWord() { + return ReadPrimitive(); +} + +uint64 CSizeBuf::ReadUint64() { + return ReadPrimitive(); +} + +int32 CSizeBuf::ReadLong() { + return ReadPrimitive(); +} + +int8 CSizeBuf::ReadChar() { + return ReadPrimitive(); +} + +uint8 CSizeBuf::ReadByte() { + return ReadPrimitive(); +} + +int16 CSizeBuf::ReadShort() { + return ReadPrimitive(); +} + +uint16 CSizeBuf::ReadWord() { + return ReadPrimitive(); +} + +char* CSizeBuf::ReadString() +{ + int c = 0, l = 0; + static char string[8192]; + + while ((c = ReadChar(), c) && c != -1 && (unsigned)l < ARRAYSIZE(string) - 1) { + string[l++] = c; + } + string[l] = 0; + + return string; +} + +char* CSizeBuf::ReadStringLine() { + int c = 0, l = 0; + static char string[8192]; + + while ((c = ReadChar(), c) && c != -1 && (unsigned)l < ARRAYSIZE(string) - 1) { + string[l++] = c; + } + string[l] = 0; + + return string; +} + +void CSizeBuf::Cut(unsigned int cutpos, unsigned int cutlen) { + if (cutpos + cutlen > m_CurSize) { + util_syserror("CSizeBuf::Cut: Invalid cut request; cutpos=%u, cutlen=%u, curSize=%u", cutpos, cutlen, m_CurSize); + return; + } + + uint8* wpos = m_Data + cutpos; + uint8* rpos = m_Data + cutpos + cutlen; + unsigned int moveLen = m_CurSize - (cutpos + cutlen); + if (moveLen) { + memmove(wpos, rpos, moveLen); + } + m_CurSize -= cutlen; +} diff --git a/reunion/src/Sizebuf.h b/reunion/src/Sizebuf.h new file mode 100644 index 0000000..3c795ec --- /dev/null +++ b/reunion/src/Sizebuf.h @@ -0,0 +1,149 @@ +#pragma once + +#include "reunion_shared.h" + +class CSizeBuf { +private: + struct bf_write_t + { + unsigned int nCurOutputBit; + unsigned char *pOutByte; + }; + + struct bf_read_t + { + unsigned int nMsgReadCount; // was msg_readcount + unsigned int nBitFieldReadStartByte; + unsigned int nBytesRead; + unsigned int nCurInputBit; + unsigned char *pInByte; + }; + +#ifdef SIZEBUF_BITS + static const unsigned int BITS_WRITING_RESERVE = 5; +#else + static const unsigned int BITS_WRITING_RESERVE = 0; +#endif + +private: + uint8* m_Data; + unsigned int m_MaxSize; + unsigned int m_CurSize; + unsigned int m_ReadCount; + bool m_bOverflowed; + bool m_bBadRead; +#ifdef SIZEBUF_BITS + bool m_bBitsWriting; + bool m_bBitsReading; + + bf_read_t m_BFRead; + bf_write_t m_BFWrite; +#endif // SIZEBUF_BITS + + inline void ensureNoBitsOp() { +#if defined SIZEBUF_BITS && !defined NDEBUG + if (m_bBitsWriting || m_bBitsReading) { + util_syserror("Invalid BitsWriting/BitsReading mode"); + } +#endif + } + + inline void ensureBitsWriting() { +#if defined SIZEBUF_BITS && !defined NDEBUG + if (!m_bBitsWriting || m_bBitsReading) { + util_syserror("Invalid BitsWriting/BitsReading mode"); + } +#endif + } + + inline void ensureBitsReading() { +#if defined SIZEBUF_BITS && !defined NDEBUG + if (m_bBitsWriting || !m_bBitsReading) { + util_syserror("Invalid BitsWriting/BitsReading mode"); + } +#endif + } + + template inline bool WritePrimitive(T val) { + ensureNoBitsOp(); + T* buf = (T*)GetSpace(sizeof(T)); + if (!buf) + return false; + + *buf = val; + return true; + } + + template inline T ReadPrimitive() { + ensureNoBitsOp(); + T res; + if (!m_bBadRead && m_ReadCount + sizeof(T) <= m_CurSize) + { + res = *(T *)(m_Data + m_ReadCount); + m_ReadCount += sizeof(T); + } else { + m_bBadRead = true; + res = (T) -1; + } + + return res; + } + +public: + CSizeBuf(const uint8* buf, unsigned int maxSize, unsigned int curSize = 0); + + uint8* GetSpace(unsigned int len); + bool Write(const void *data, unsigned int length); + bool Print(const char *data); + + bool WriteChar(int8 val); + bool WriteByte(uint8 val); + bool WriteShort(int16 val); + bool WriteWord(uint16 val); + bool WriteDWord(uint32 val); + bool WriteUint64(uint64 val); + bool WriteLong(int32 val); + bool WriteFloat(float val); + bool WriteString(const char* s); + +#ifdef SIZEBUF_BITS + void StartBitWriting(); + void EndBitWriting(); + void WriteOneBit(int val); + void WriteBits(uint32 data, unsigned int numbits); + void WriteSBits(int data, unsigned int numbits); + void WriteBitString(const char *p); + void WriteBitData(void *src, unsigned int length); +#endif // SIZEBUF_BITS + + void StartBitReading(); + void EndBitReading(); + int CurrentBit(); + int ReadOneBit(); + uint32 ReadBits(unsigned int numbits); + int ReadSBits(unsigned int numbits); + + int8 ReadChar(); + uint8 ReadByte(); + int16 ReadShort(); + uint16 ReadWord(); + uint32 ReadDWord(); + uint64 ReadUint64(); + int32 ReadLong(); + char* ReadString(); + char* ReadStringLine(); + + + void Clear(); + void Cut(unsigned int cutpos, unsigned int cutlen); + + bool IsOverflowed() { return m_bOverflowed; } + bool IsBadRead() { return m_bBadRead; } + unsigned int GetCurSize() { return m_CurSize; } + uint8* GetData() { return m_Data; } + unsigned int GetMaxSize() { return m_MaxSize; } + uint8* GetReadPtr() { return m_Data + m_ReadCount; } + unsigned int GetReadPos() { return m_ReadCount; } + unsigned int RemainingReadBytes() { return m_CurSize - m_ReadCount; } + bool HasSomethingToRead() { return m_ReadCount < m_CurSize; } +}; diff --git a/reunion/src/client_auth.cpp b/reunion/src/client_auth.cpp new file mode 100644 index 0000000..20b88c4 --- /dev/null +++ b/reunion/src/client_auth.cpp @@ -0,0 +1,573 @@ +#include "precompiled.h" + +client_auth_context_t* g_CurrentAuthContext = nullptr; + +cvar_t cv_dp_rejmsg_steam = { "dp_rejmsg_steam", "Sorry, legit clients are not allowed on this server", FCVAR_EXTDLL, 0, NULL }; +cvar_t cv_dp_rejmsg_nosteam47 = { "dp_rejmsg_nosteam47", "Sorry, no-steam p47 clients are not allowed on this server", FCVAR_EXTDLL, 0, NULL }; +cvar_t cv_dp_rejmsg_nosteam48 = { "dp_rejmsg_nosteam48", "Sorry, no-steam p48 clients are not allowed on this server", FCVAR_EXTDLL, 0, NULL }; +cvar_t cv_dp_rejmsg_hltv = { "dp_rejmsg_hltv", "Sorry, HLTV is not allowed on this server", FCVAR_EXTDLL, 0, NULL }; +cvar_t cv_dp_rejmsg_pending = { "dp_rejmsg_pending", "Sorry, unauthorized clients are not allowed on this server", FCVAR_EXTDLL, 0, NULL }; +cvar_t cv_dp_rejmsg_revemu = { "dp_rejmsg_revemu", "Sorry, RevEmu clients are not allowed on this server", FCVAR_EXTDLL, 0, NULL }; +cvar_t cv_dp_rejmsg_revemu2013 = { "dp_rejmsg_revemu2013", "Sorry, RevEmu2013 clients are not allowed on this server", FCVAR_EXTDLL, 0, NULL }; +cvar_t cv_dp_rejmsg_steamemu = { "dp_rejmsg_steamemu", "Sorry, SteamEmu clients are not allowed on this server", FCVAR_EXTDLL, 0, NULL }; +cvar_t cv_dp_rejmsg_oldrevemu = { "dp_rejmsg_oldrevemu", "Sorry, Old RevEmu clients are not allowed on this server", FCVAR_EXTDLL, 0, NULL }; +cvar_t cv_dp_rejmsg_avsmp = { "dp_rejmsg_avsmp", "Sorry, AVSMP clients are not allowed on this server", FCVAR_EXTDLL, 0, NULL }; +cvar_t cv_dp_rejmsg_revemu_sc2009 = { "dp_rejmsg_revemu_sc2009", "Sorry, revEmu/SC2009 clients are not allowed on this server", FCVAR_EXTDLL, 0, NULL }; +cvar_t cv_dp_rejmsg_sxei = { "dp_rejmsg_sxei", "Sorry, sXe Injected clients are not allowed on this server", FCVAR_EXTDLL, 0, NULL }; + +cvar_t *pcv_dp_rejmsg_steam; +cvar_t *pcv_dp_rejmsg_nosteam47; +cvar_t *pcv_dp_rejmsg_nosteam48; +cvar_t *pcv_dp_rejmsg_hltv; +cvar_t *pcv_dp_rejmsg_pending; +cvar_t *pcv_dp_rejmsg_revemu; +cvar_t *pcv_dp_rejmsg_steamemu; +cvar_t *pcv_dp_rejmsg_oldrevemu; +cvar_t *pcv_dp_rejmsg_avsmp; +cvar_t *pcv_dp_rejmsg_revemu_sc2009; +cvar_t *pcv_dp_rejmsg_revemu2013; +cvar_t *pcv_dp_rejmsg_sxei; + +cvar_t *pcv_sv_contact; + +void Reunion_Reject_Deprecated(client_auth_kind authkind) { + const char* kickMessage; + + switch (authkind) { + case CA_HLTV: kickMessage = pcv_dp_rejmsg_hltv->string; break; + case CA_NO_STEAM_47: kickMessage = pcv_dp_rejmsg_nosteam47->string; break; + case CA_NO_STEAM_48: kickMessage = pcv_dp_rejmsg_nosteam48->string; break; + case CA_SETTI: kickMessage = "Setti scanner is not allowed there"; break; + case CA_STEAM: kickMessage = pcv_dp_rejmsg_steam->string; break; + case CA_STEAM_PENDING: kickMessage = pcv_dp_rejmsg_pending->string; break; + case CA_STEAM_EMU: kickMessage = pcv_dp_rejmsg_steamemu->string; break; + case CA_OLD_REVEMU: kickMessage = pcv_dp_rejmsg_oldrevemu->string; break; + case CA_REVEMU: kickMessage = pcv_dp_rejmsg_revemu->string; break; + case CA_STEAMCLIENT_2009: kickMessage = pcv_dp_rejmsg_revemu_sc2009->string; break; + case CA_REVEMU_2013: kickMessage = pcv_dp_rejmsg_revemu2013->string; break; + case CA_AVSMP: kickMessage = pcv_dp_rejmsg_avsmp->string; break; + case CA_SXEI: kickMessage = pcv_dp_rejmsg_sxei->string; break; + default: + kickMessage = "Unknown client type"; + break; + } + + g_RehldsFuncs->RejectConnection(g_CurrentAuthContext->adr, "%s", kickMessage); +} + +void SaltSteamId(authdata_t* authdata) { + // We hash [steamid + raw ticket data + salt] + // This makes impossible to substitute exact id if you know only old, not hashed id + byte buf[MAX_HASHDATA_LEN]; + CSizeBuf szbuf(buf, sizeof buf); + + if (g_ReunionConfig->getAuthVersion() < av_reunion2018) + szbuf.WriteLong(authdata->steamId); + if (g_ReunionConfig->getAuthVersion() > av_dproto) + szbuf.Write(authdata->authKey, authdata->authKeyLen); + + szbuf.Write(g_ReunionConfig->getSteamIdSalt(), g_ReunionConfig->getSteamIdSaltLen()); + + // Hash + sha2 hSha; + hSha.Init(sha2::enuSHA256); + hSha.Update(szbuf.GetData(), szbuf.GetCurSize()); + hSha.End(); + + // Get hash + int shaLen; + const char *hash = hSha.RawHash(shaLen); + + // Set new SteamID + authdata->steamId = *(unsigned int *)(hash + 8); +} + +uint64_t SteamByIp(uint32_t ip) +{ + uint32_t accId; + + if (g_ReunionConfig->getAuthVersion() >= av_reunion2018) + MurmurHash3_x86_32(&ip, sizeof(ip), IPGEN_KEY, &accId); + else + accId = ip ^ IPGEN_KEY; + + return CSteamID(accId, k_unSteamUserDesktopInstance, k_EUniversePublic, k_EAccountTypeIndividual).ConvertToUint64(); +} + +bool Reunion_FinishClientAuth(CReunionPlayer* reunionPlr, USERID_t* userid, client_auth_context_t* ctx) +{ + client_auth_kind authkind; + + if (!ctx->authentificatedInSteam) { + // native auth failed, try authorize by emulators + authdata_t authdata; + authdata.authTicket = ctx->authTicket; + authdata.ticketLen = ctx->authTicketLen; + authdata.protinfo = ctx->protinfo; + authdata.protocol = ctx->protocol; + authdata.userinfo = ctx->userinfo; + authdata.ipaddr = ctx->ipaddr; + authdata.port = bswap(ctx->adr->port); + + authkind = Reunion_Authorize_Client(&authdata); + if (authkind == CA_UNKNOWN) { + g_RehldsFuncs->RejectConnection(ctx->adr, "Client authorization failed"); + reunionPlr->clear(); + return false; + } + + LCPrintf(false, "%s (%s) authorized as %s\n", g_engfuncs.pfnInfoKeyValue(ctx->userinfo, "name"), util_adr_to_string(authdata.ipaddr, authdata.port), Reunion_GetAuthorizerName(authkind)); + + uint32_t steamId = authdata.steamId; + if (IsNumericAuthKind(authkind)) { + // check for pending id + if (!IsValidId(authdata.steamId)) { + authkind = CA_STEAM_PENDING; + } + else { + // salt steamid + if (g_ReunionConfig->getSteamIdSaltLen()) { + SaltSteamId(&authdata); + + // set second prefix + if (g_ReunionConfig->getEnableGenPrefix2()) + authdata.steamId = rotl(authdata.steamId, 1); + else + authdata.steamId <<= 1; + } + } + } + + reunionPlr->setRawAuthData(authdata.authKeyKind, authdata.authKey, authdata.authKeyLen); + + userid->idtype = authdata.idtype; + userid->m_SteamID = CSteamID(authdata.steamId, k_unSteamUserDesktopInstance, k_EUniversePublic, k_EAccountTypeGameServer).ConvertToUint64(); + userid->clientip = authdata.ipaddr; + + USERID_t storageId; + storageId.idtype = authdata.idtype; + storageId.m_SteamID = CSteamID(steamId, k_unSteamUserDesktopInstance, k_EUniversePublic, k_EAccountTypeGameServer).ConvertToUint64(); + storageId.clientip = authdata.ipaddr; + + reunionPlr->setStorageId(&storageId); + + } else { + authkind = CA_STEAM; + reunionPlr->setRawAuthData(AK_STEAM, nullptr, 0); + } + + // check for pending id + if (IsNumericAuthKind(authkind) && !IsValidId(userid->m_SteamID)) { + authkind = CA_STEAM_PENDING; + } + + // add prefix + client_id_kind idkind = g_ReunionConfig->getIdGenOptions(authkind)->id_kind; + switch (idkind) { + // check for deprecation + case CI_DEPRECATED: + // allow HLTV from configured port + if (authkind == CA_HLTV && ctx->ipaddr == g_ReunionConfig->getHLTVExceptIP()) { + idkind = CI_HLTV; + } + else { + if (ctx->authentificatedInSteam) { + g_ISteamGameServer->SendUserDisconnect(userid->m_SteamID); + ctx->authentificatedInSteam = false; + } + Reunion_Reject_Deprecated(authkind); + reunionPlr->clear(); + return false; + } + break; + + // check for auth by ip + case CI_VALVE_BY_IP: + userid->idtype = AUTH_IDTYPE_VALVE; + case CI_STEAM_BY_IP: + userid->m_SteamID = SteamByIp(ctx->ipaddr); + break; + + case CI_REAL_VALVE: + case CI_VALVE_ID_LAN: + case CI_VALVE_ID_PENDING: + userid->idtype = AUTH_IDTYPE_VALVE; + break; + + default: + break; + } + + // set reunion_player's values + reunionPlr->authenticated(ctx->protocol, idkind, authkind, userid); + + if (IsValidId(userid->m_SteamID) && IsUniqueIdKind(idkind)) { + // check for duplicate steamid + if (!ctx->authentificatedInSteam) { + if (Reunion_IsSteamIdInUse(reunionPlr)) { + util_connect_and_kick(*ctx->adr, "Your SteamID is already in use on this server\n"); + reunionPlr->clear(); + return false; + } + } + else { + // remove nosteamers with the same id + Reunion_RemoveDuplicateSteamIds(reunionPlr); + } + + // check if client being connected is banned + if (g_RehldsFuncs->FilterUser(userid)) { + // disconnect from steam if authorized + if (ctx->authentificatedInSteam) { + g_ISteamGameServer->SendUserDisconnect(userid->m_SteamID); + ctx->authentificatedInSteam = false; + } + + // kick + util_connect_and_kick(*ctx->adr, "You have been banned from this server.\n"); + reunionPlr->clear(); + return false; + } + } + + // notify steam that someone has joined the server (if native auth was failed) + if (!ctx->authentificatedInSteam) { + uint64 steamUnauthenticatedIDUser = g_ISteamGameServer->CreateUnauthenticatedUserConnection().ConvertToUint64(); + reunionPlr->setUnauthenticatedId(steamUnauthenticatedIDUser); + ctx->unauthenticatedConnection = true; + } + + return true; +} + +void SV_ConnectClient_hook(IRehldsHook_SV_ConnectClient* chain) { +#ifndef NDEBUG + if (g_CurrentAuthContext != NULL) { + LCPrintf(true, "WARNING: %s: recursive call\n", __FUNCTION__); + chain->callNext(); + return; + } +#endif + + client_auth_context_t ctx; + + if (!g_ISteamGameServer) + g_ISteamGameServer = g_RehldsApi->GetServerData()->GetSteamGameServer(); + + g_CurrentAuthContext = &ctx; + chain->callNext(); + g_CurrentAuthContext = nullptr; +} + +// #1 Hook in SV_ConnectClient +int SV_CheckProtocol_hook(IRehldsHook_SV_CheckProtocol* chain, netadr_t *adr, int nProtocol) +{ +#ifndef NDEBUG + if (g_CurrentAuthContext == NULL) { + LCPrintf(true, "WARNING: %s is called outside auth context\n", __FUNCTION__); + return chain->callNext(adr, nProtocol); + } +#endif + + if (adr == NULL) { + return chain->callNext(adr, nProtocol); + } + + g_CurrentAuthContext->adr = adr; + g_CurrentAuthContext->ipaddr = *(uint32 *)&adr->ip[0]; + g_CurrentAuthContext->protocol = nProtocol; + + if (nProtocol < 47) { + g_RehldsFuncs->RejectConnection( + adr, + "This server is using a newer protocol ( %i ) than your client ( %i ). You should check for updates to your client.\n", + 48, + nProtocol); + + return FALSE; + } + + if (nProtocol > 48) { + const char *contact = (pcv_sv_contact->string[0] != '\0') ? pcv_sv_contact->string : "(no email address specified)"; + + g_RehldsFuncs->RejectConnection( + adr, + "This server is using an older protocol ( %i ) than your client ( %i ). If you believe this server is outdated, you can contact the server administrator at %s.\n", + 48, + nProtocol, + contact); + + return FALSE; + } + + return TRUE; +} + +// #2 Hook in SV_ConnectClient +int SV_CheckKeyInfo_hook(IRehldsHook_SV_CheckKeyInfo* chain, netadr_t *adr, char *protinfo, short unsigned int *port, int *pAuthProtocol, char *pszRaw, char *cdkey) +{ +#ifndef NDEBUG + if (g_CurrentAuthContext == NULL) { + LCPrintf(true, "WARNING: %s is called outside auth context\n",__FUNCTION__); + return chain->callNext(adr, protinfo, port, pAuthProtocol, pszRaw, cdkey); + } +#endif + + g_CurrentAuthContext->protinfo = protinfo; + g_CurrentAuthContext->pAuthProto = pAuthProtocol; + + int authProto = atoi(g_engfuncs.pfnInfoKeyValue(protinfo, "prot")); + if (authProto <= 0 || authProto > 4) { + g_RehldsFuncs->RejectConnection(adr, "Invalid connection.\n"); + return FALSE; + } + + *port = PORT_CLIENT; + *pAuthProtocol = PROTOCOL_STEAM; // we want to Steam_NotifyClientConnect be called for every client + + strncpy(pszRaw, g_engfuncs.pfnInfoKeyValue(protinfo, "raw"), 32); + pszRaw[33] = '\0'; + + strncpy(cdkey, g_engfuncs.pfnInfoKeyValue(protinfo, "cdkey"), 32); + cdkey[33] = '\0'; + + return TRUE; +} + +// #3 Hook in SV_ConnectClient +int SV_FinishCertificateCheck_hook(IRehldsHook_SV_FinishCertificateCheck* chain, netadr_t *adr, int nAuthProtocol, char *szRawCertificate, char *userinfo) +{ +#ifndef NDEBUG + if (g_CurrentAuthContext == NULL) { + LCPrintf(true, "WARNING: %s is called outside auth context\n", __FUNCTION__); + return chain->callNext(adr, nAuthProtocol, szRawCertificate, userinfo); + } +#endif + + g_CurrentAuthContext->userinfo = userinfo; + + sizebuf_t* pNetMessage = g_RehldsFuncs->GetNetMessage(); + int* pMsgReadCount = g_RehldsFuncs->GetMsgReadCount(); + + // avoid "invalid steam certificate length" error + if (*pMsgReadCount == pNetMessage->cursize) { + pNetMessage->cursize += 1; + } + + return TRUE; +} + +// #4 Hook in SV_ConnectClient +qboolean Steam_NotifyClientConnect_hook(IRehldsHook_Steam_NotifyClientConnect* chain, IGameClient *cl, const void *pvSteam2Key, unsigned int ucbSteam2Key) +{ +#ifndef NDEBUG + if (g_CurrentAuthContext == NULL) { + LCPrintf(true, "WARNING: %s is called outside auth context\n", __FUNCTION__); + return chain->callNext(cl, pvSteam2Key, ucbSteam2Key); + } +#endif + + uint8* ticket = (uint8 *)pvSteam2Key; + g_CurrentAuthContext->authTicket = ticket; + g_CurrentAuthContext->authTicketLen = ucbSteam2Key; + + // fast no-steam check + bool authRes = IsValidSteamTicket(ticket, ucbSteam2Key); + + // try authorize in steam + if (authRes) { + authRes = chain->callNext(cl, pvSteam2Key, ucbSteam2Key) ? true : false; + } + + g_CurrentAuthContext->authentificatedInSteam = authRes; + + return Reunion_FinishClientAuth(GetReunionPlayerByClientPtr(cl), cl->GetNetworkUserID(), g_CurrentAuthContext) ? TRUE : FALSE; +} + +// Replace protocol number in svc_serverinfo +void SV_SendServerinfo_hook(IRehldsHook_SV_SendServerinfo* chain, sizebuf_t *msg, IGameClient* cl) +{ + int startWritePos = msg->cursize; + chain->callNext(msg, cl); + + for (int i = startWritePos; i < msg->maxsize - 1; i++) { + if (msg->data[i] == svc_serverinfo) { + msg->data[i + 1] = (uint8)GetReunionPlayerByClientPtr(cl)->getProcotol(); + break; + } + } +} + +// Used mostly in id bans stuff +char *SV_GetIDString_hook(IRehldsHook_SV_GetIDString* chain, USERID_t *id) +{ + static char idstring[64]; + + CReunionPlayer* plr = GetReunionPlayerByUserIdPtr(id); + if (plr) + return plr->GetSteamId(); + + uint32 accId = (uint32)id->m_SteamID; + switch (id->idtype) { + case AUTH_IDTYPE_STEAM: + if (accId == 0) { + strcpy(idstring, "STEAM_ID_LAN"); + } + else if (accId == 1) { + strcpy(idstring, "STEAM_ID_PENDING"); + } + else { + sprintf(idstring, "STEAM_%u:%u:%u", 0, accId & 1, accId >> 1); + } + break; + + case AUTH_IDTYPE_VALVE: + if (accId == 0) { + strcpy(idstring, "VALVE_ID_LAN"); + } + else if (accId == 1) { + strcpy(idstring, "VALVE_ID_PENDING"); + } + else { + sprintf(idstring, "VALVE_%u:%u:%u", 0, accId & 1, accId >> 1); + } + break; + + case AUTH_IDTYPE_LOCAL: + return "HLTV"; + + default: + return "UNKNOWN"; + } + + return idstring; +} + +// Used in id bans stuff and for detecting steamid duplicates +qboolean SV_CompareUserID_hook(IRehldsHook_SV_CompareUserID* chain, USERID_t *id1, USERID_t *id2) +{ + CReunionPlayer* plr1 = GetReunionPlayerByUserIdPtr(id1); + CReunionPlayer* plr2 = GetReunionPlayerByUserIdPtr(id2); + + if (plr1) { + id1 = plr1->getSerializedId(); + } + + if (plr2) { + id2 = plr2->getSerializedId(); + } + + return chain->callNext(id1, id2); // both IDs are serialized +} + +void SerializeSteamId_hook(IRehldsHook_SerializeSteamId* chain, USERID_t* id, USERID_t* serialized) +{ + CReunionPlayer* plr = GetReunionPlayerByUserIdPtr(id); + + if (plr) { + id = plr->getSerializedId(); + } + + chain->callNext(id, serialized); +} + +void Steam_NotifyClientDisconnect_hook(IRehldsHook_Steam_NotifyClientDisconnect* chain, IGameClient* cl) +{ + USERID_t *userid = cl->GetNetworkUserID(); + uint64 steamIDUser = userid->m_SteamID; + + CReunionPlayer *player = GetReunionPlayerByClientPtr(cl); + bool isUnauthenticatedId = player->isUnauthenticatedId(); + if (isUnauthenticatedId) { + userid->m_SteamID = player->getUnauthenticatedId(); + } + + chain->callNext(cl); + + if (isUnauthenticatedId) { + userid->m_SteamID = steamIDUser; + } + + player->clear(); +} + +bool Steam_GSBUpdateUserData_hook(IRehldsHook_Steam_GSBUpdateUserData* chain, uint64 steamIDUser, const char* pchPlayerName, uint32 uScore) +{ + CReunionPlayer *plr = GetReunionPlayerBySteamdId(steamIDUser); + if (plr && plr->isUnauthenticatedId()) + steamIDUser = plr->getUnauthenticatedId(); + + return chain->callNext(steamIDUser, pchPlayerName, uScore); +} + +uint64 Steam_GSGetSteamID() +{ + return GAMESERVER_STEAMID; // not NULL +// return g_ISteamGameServer->GetSteamID().ConvertToUint64(); +} + +uint64 Steam_GSGetSteamID_hook(IRehldsHook_Steam_GSGetSteamID* chain) +{ + return Steam_GSGetSteamID(); +} + +void SV_Frame_hook(IRehldsHook_SV_Frame* chain) { + chain->callNext(); + g_ServerInfo->startFrame(); +} + +bool Reunion_Auth_Init() { + + // + // Cvars + // + g_engfuncs.pfnCvar_RegisterVariable(&cv_dp_rejmsg_steam); + g_engfuncs.pfnCvar_RegisterVariable(&cv_dp_rejmsg_nosteam47); + g_engfuncs.pfnCvar_RegisterVariable(&cv_dp_rejmsg_nosteam48); + g_engfuncs.pfnCvar_RegisterVariable(&cv_dp_rejmsg_hltv); + g_engfuncs.pfnCvar_RegisterVariable(&cv_dp_rejmsg_pending); + g_engfuncs.pfnCvar_RegisterVariable(&cv_dp_rejmsg_revemu); + g_engfuncs.pfnCvar_RegisterVariable(&cv_dp_rejmsg_revemu2013); + g_engfuncs.pfnCvar_RegisterVariable(&cv_dp_rejmsg_steamemu); + g_engfuncs.pfnCvar_RegisterVariable(&cv_dp_rejmsg_oldrevemu); + g_engfuncs.pfnCvar_RegisterVariable(&cv_dp_rejmsg_avsmp); + g_engfuncs.pfnCvar_RegisterVariable(&cv_dp_rejmsg_revemu_sc2009); + g_engfuncs.pfnCvar_RegisterVariable(&cv_dp_rejmsg_sxei); + + pcv_dp_rejmsg_steam = g_engfuncs.pfnCVarGetPointer(cv_dp_rejmsg_steam.name); + pcv_dp_rejmsg_nosteam47 = g_engfuncs.pfnCVarGetPointer(cv_dp_rejmsg_nosteam47.name); + pcv_dp_rejmsg_nosteam48 = g_engfuncs.pfnCVarGetPointer(cv_dp_rejmsg_nosteam48.name); + pcv_dp_rejmsg_hltv = g_engfuncs.pfnCVarGetPointer(cv_dp_rejmsg_hltv.name); + pcv_dp_rejmsg_pending = g_engfuncs.pfnCVarGetPointer(cv_dp_rejmsg_pending.name); + pcv_dp_rejmsg_revemu = g_engfuncs.pfnCVarGetPointer(cv_dp_rejmsg_revemu.name); + pcv_dp_rejmsg_revemu2013 = g_engfuncs.pfnCVarGetPointer(cv_dp_rejmsg_revemu2013.name); + pcv_dp_rejmsg_steamemu = g_engfuncs.pfnCVarGetPointer(cv_dp_rejmsg_steamemu.name); + pcv_dp_rejmsg_oldrevemu = g_engfuncs.pfnCVarGetPointer(cv_dp_rejmsg_oldrevemu.name); + pcv_dp_rejmsg_avsmp = g_engfuncs.pfnCVarGetPointer(cv_dp_rejmsg_avsmp.name); + pcv_dp_rejmsg_revemu_sc2009 = g_engfuncs.pfnCVarGetPointer(cv_dp_rejmsg_revemu_sc2009.name); + pcv_dp_rejmsg_sxei = g_engfuncs.pfnCVarGetPointer(cv_dp_rejmsg_sxei.name); + + pcv_sv_contact = g_engfuncs.pfnCVarGetPointer("sv_contact"); + + // + // Install hooks + // + g_RehldsHookchains->SV_ConnectClient()->registerHook(&SV_ConnectClient_hook); + g_RehldsHookchains->SV_CheckProtocol()->registerHook(&SV_CheckProtocol_hook); + g_RehldsHookchains->SV_SendServerinfo()->registerHook(&SV_SendServerinfo_hook); + g_RehldsHookchains->SV_CheckKeyInfo()->registerHook(&SV_CheckKeyInfo_hook); + g_RehldsHookchains->SV_FinishCertificateCheck()->registerHook(&SV_FinishCertificateCheck_hook); + g_RehldsHookchains->Steam_NotifyClientConnect()->registerHook(&Steam_NotifyClientConnect_hook); + + g_RehldsHookchains->SV_GetIDString()->registerHook(&SV_GetIDString_hook); + g_RehldsHookchains->SV_CompareUserID()->registerHook(&SV_CompareUserID_hook); + g_RehldsHookchains->SerializeSteamId()->registerHook(&SerializeSteamId_hook); + + g_RehldsHookchains->Steam_NotifyClientDisconnect()->registerHook(&Steam_NotifyClientDisconnect_hook, HC_PRIORITY_LOW); + g_RehldsHookchains->Steam_GSBUpdateUserData()->registerHook(&Steam_GSBUpdateUserData_hook, HC_PRIORITY_LOW); + g_RehldsHookchains->Steam_GSGetSteamID()->registerHook(&Steam_GSGetSteamID_hook); + + g_RehldsHookchains->SV_Frame()->registerHook(&SV_Frame_hook); + + return true; +} diff --git a/reunion/src/client_auth.h b/reunion/src/client_auth.h new file mode 100644 index 0000000..6eb9d20 --- /dev/null +++ b/reunion/src/client_auth.h @@ -0,0 +1,19 @@ +#pragma once + +struct client_auth_context_t { + int protocol = 0; + bool authentificatedInSteam = false; + bool unauthenticatedConnection = false; + unsigned char* authTicket = nullptr; + unsigned int authTicketLen = 0; + char* userinfo = nullptr; + char* protinfo = nullptr; + netadr_t* adr = nullptr; + uint32 ipaddr = 0; + int* pAuthProto = nullptr; +}; + +extern client_auth_context_t* g_CurrentAuthContext; +extern bool Reunion_Auth_Init(); + +extern uint64 Steam_GSGetSteamID(); diff --git a/reunion/src/dllapi.cpp b/reunion/src/dllapi.cpp new file mode 100644 index 0000000..653e750 --- /dev/null +++ b/reunion/src/dllapi.cpp @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2001-2003 Will Day + * + * This file is part of Metamod. + * + * Metamod 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 2 of the License, or (at + * your option) any later version. + * + * Metamod 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 Metamod; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, the author gives permission to + * link the code of this program with the Half-Life Game Engine ("HL + * Engine") and Modified Game Libraries ("MODs") developed by Valve, + * L.L.C ("Valve"). You must obey the GNU General Public License in all + * respects for all of the code used other than the HL Engine and MODs + * from Valve. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. + * + */ + +#include "precompiled.h" + +void ServerActivate(edict_t *pEdictList, int edictCount, int clientMax) +{ + g_ServerInfo->serverActivate(pEdictList, clientMax); + RETURN_META(MRES_IGNORED); +} + +static DLL_FUNCTIONS gFunctionTable = +{ + NULL, // pfnGameInit + NULL, // pfnSpawn + NULL, // pfnThink + NULL, // pfnUse + NULL, // pfnTouch + NULL, // pfnBlocked + NULL, // pfnKeyValue + NULL, // pfnSave + NULL, // pfnRestore + NULL, // pfnSetAbsBox + + NULL, // pfnSaveWriteFields + NULL, // pfnSaveReadFields + + NULL, // pfnSaveGlobalState + NULL, // pfnRestoreGlobalState + NULL, // pfnResetGlobalState + + NULL, // pfnClientConnect + NULL, // pfnClientDisconnect + NULL, // pfnClientKill + NULL, // pfnClientPutInServer + NULL, // pfnClientCommand + NULL, // pfnClientUserInfoChanged + &ServerActivate, // pfnServerActivate + NULL, // pfnServerDeactivate + + NULL, // pfnPlayerPreThink + NULL, // pfnPlayerPostThink + + NULL, // pfnStartFrame + NULL, // pfnParmsNewLevel + NULL, // pfnParmsChangeLevel + + NULL, // pfnGetGameDescription + NULL, // pfnPlayerCustomization + + NULL, // pfnSpectatorConnect + NULL, // pfnSpectatorDisconnect + NULL, // pfnSpectatorThink + + NULL, // pfnSys_Error + + NULL, // pfnPM_Move + NULL, // pfnPM_Init + NULL, // pfnPM_FindTextureType + + NULL, // pfnSetupVisibility + NULL, // pfnUpdateClientData + NULL, // pfnAddToFullPack + NULL, // pfnCreateBaseline + NULL, // pfnRegisterEncoders + NULL, // pfnGetWeaponData + NULL, // pfnCmdStart + NULL, // pfnCmdEnd + NULL, // pfnConnectionlessPacket + NULL, // pfnGetHullBounds + NULL, // pfnCreateInstancedBaselines + NULL, // pfnInconsistentFile + NULL, // pfnAllowLagCompensation +}; + +C_DLLEXPORT int GetEntityAPI2(DLL_FUNCTIONS *pFunctionTable, int *interfaceVersion) +{ + if(!pFunctionTable) { + UTIL_LogPrintf("GetEntityAPI2 called with null pFunctionTable"); + return(FALSE); + } + else if(*interfaceVersion != INTERFACE_VERSION) { + UTIL_LogPrintf("GetEntityAPI2 version mismatch; requested=%d ours=%d", *interfaceVersion, INTERFACE_VERSION); + //! Tell metamod what version we had, so it can figure out who is out of date. + *interfaceVersion = INTERFACE_VERSION; + return(FALSE); + } + memcpy(pFunctionTable, &gFunctionTable, sizeof(DLL_FUNCTIONS)); + return(TRUE); +} diff --git a/reunion/src/engine_api.cpp b/reunion/src/engine_api.cpp new file mode 100644 index 0000000..66cc00a --- /dev/null +++ b/reunion/src/engine_api.cpp @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2001-2003 Will Day + * + * This file is part of Metamod. + * + * Metamod 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 2 of the License, or (at + * your option) any later version. + * + * Metamod 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 Metamod; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, the author gives permission to + * link the code of this program with the Half-Life Game Engine ("HL + * Engine") and Modified Game Libraries ("MODs") developed by Valve, + * L.L.C ("Valve"). You must obey the GNU General Public License in all + * respects for all of the code used other than the HL Engine and MODs + * from Valve. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. + * + */ + +#include "precompiled.h" + +enginefuncs_t meta_engfuncs = +{ + NULL, // pfnPrecacheModel() + NULL, // pfnPrecacheSound() + NULL, // pfnSetModel() + NULL, // pfnModelIndex() + NULL, // pfnModelFrames() + + NULL, // pfnSetSize() + NULL, // pfnChangeLevel() + NULL, // pfnGetSpawnParms() + NULL, // pfnSaveSpawnParms() + + NULL, // pfnVecToYaw() + NULL, // pfnVecToAngles() + NULL, // pfnMoveToOrigin() + NULL, // pfnChangeYaw() + NULL, // pfnChangePitch() + + NULL, // pfnFindEntityByString() + NULL, // pfnGetEntityIllum() + NULL, // pfnFindEntityInSphere() + NULL, // pfnFindClientInPVS() + NULL, // pfnEntitiesInPVS() + + NULL, // pfnMakeVectors() + NULL, // pfnAngleVectors() + + NULL, // pfnCreateEntity() + NULL, // pfnRemoveEntity() + NULL, // pfnCreateNamedEntity() + + NULL, // pfnMakeStatic() + NULL, // pfnEntIsOnFloor() + NULL, // pfnDropToFloor() + + NULL, // pfnWalkMove() + NULL, // pfnSetOrigin() + + NULL, // pfnEmitSound() + NULL, // pfnEmitAmbientSound() + + NULL, // pfnTraceLine() + NULL, // pfnTraceToss() + NULL, // pfnTraceMonsterHull() + NULL, // pfnTraceHull() + NULL, // pfnTraceModel() + NULL, // pfnTraceTexture() + NULL, // pfnTraceSphere() + NULL, // pfnGetAimVector() + + NULL, // pfnServerCommand() + NULL, // pfnServerExecute() + NULL, // pfnClientCommand() + + NULL, // pfnParticleEffect() + NULL, // pfnLightStyle() + NULL, // pfnDecalIndex() + NULL, // pfnPointContents() + + NULL, // pfnMessageBegin() + NULL, // pfnMessageEnd() + + NULL, // pfnWriteByte() + NULL, // pfnWriteChar() + NULL, // pfnWriteShort() + NULL, // pfnWriteLong() + NULL, // pfnWriteAngle() + NULL, // pfnWriteCoord() + NULL, // pfnWriteString() + NULL, // pfnWriteEntity() + + NULL, // pfnCVarRegister() + NULL, // pfnCVarGetFloat() + NULL, // pfnCVarGetString() + NULL, // pfnCVarSetFloat() + NULL, // pfnCVarSetString() + + NULL, // pfnAlertMessage() + NULL, // pfnEngineFprintf() + + NULL, // pfnPvAllocEntPrivateData() + NULL, // pfnPvEntPrivateData() + NULL, // pfnFreeEntPrivateData() + + NULL, // pfnSzFromIndex() + NULL, // pfnAllocString() + + NULL, // pfnGetVarsOfEnt() + NULL, // pfnPEntityOfEntOffset() + NULL, // pfnEntOffsetOfPEntity() + NULL, // pfnIndexOfEdict() + NULL, // pfnPEntityOfEntIndex() + NULL, // pfnFindEntityByVars() + NULL, // pfnGetModelPtr() + + NULL, // pfnRegUserMsg() + + NULL, // pfnAnimationAutomove() + NULL, // pfnGetBonePosition() + + NULL, // pfnFunctionFromName() + NULL, // pfnNameForFunction() + + NULL, // pfnClientPrintf() + NULL, // pfnServerPrint() + + NULL, // pfnCmd_Args() + NULL, // pfnCmd_Argv() + NULL, // pfnCmd_Argc() + + NULL, // pfnGetAttachment() + + NULL, // pfnCRC32_Init() + NULL, // pfnCRC32_ProcessBuffer() + NULL, // pfnCRC32_ProcessByte() + NULL, // pfnCRC32_Final() + + NULL, // pfnRandomLong() + NULL, // pfnRandomFloat() + + NULL, // pfnSetView() + NULL, // pfnTime() + NULL, // pfnCrosshairAngle() + + NULL, // pfnLoadFileForMe() + NULL, // pfnFreeFile() + + NULL, // pfnEndSection() + NULL, // pfnCompareFileTime() + NULL, // pfnGetGameDir() + NULL, // pfnCvar_RegisterVariable() + NULL, // pfnFadeClientVolume() + NULL, // pfnSetClientMaxspeed() + NULL, // pfnCreateFakeClient() + NULL, // pfnRunPlayerMove() + NULL, // pfnNumberOfEntities() + + NULL, // pfnGetInfoKeyBuffer() + NULL, // pfnInfoKeyValue() + NULL, // pfnSetKeyValue() + NULL, // pfnSetClientKeyValue() + + NULL, // pfnIsMapValid() + NULL, // pfnStaticDecal() + NULL, // pfnPrecacheGeneric() + NULL, // pfnGetPlayerUserId() + NULL, // pfnBuildSoundMsg() + NULL, // pfnIsDedicatedServer() + NULL, // pfnCVarGetPointer() + NULL, // pfnGetPlayerWONId() + + NULL, // pfnInfo_RemoveKey() + NULL, // pfnGetPhysicsKeyValue() + NULL, // pfnSetPhysicsKeyValue() + NULL, // pfnGetPhysicsInfoString() + NULL, // pfnPrecacheEvent() + NULL, // pfnPlaybackEvent() + + NULL, // pfnSetFatPVS() + NULL, // pfnSetFatPAS() + + NULL, // pfnCheckVisibility() + + NULL, // pfnDeltaSetField() + NULL, // pfnDeltaUnsetField() + NULL, // pfnDeltaAddEncoder() + NULL, // pfnGetCurrentPlayer() + NULL, // pfnCanSkipPlayer() + NULL, // pfnDeltaFindField() + NULL, // pfnDeltaSetFieldByIndex() + NULL, // pfnDeltaUnsetFieldByIndex() + + NULL, // pfnSetGroupMask() + + NULL, // pfnCreateInstancedBaseline() + NULL, // pfnCvar_DirectSet() + + NULL, // pfnForceUnmodified() + + NULL, // pfnGetPlayerStats() + + NULL, // pfnAddServerCommand() + + // Added in SDK 2.2: + NULL, // pfnVoice_GetClientListening() + NULL, // pfnVoice_SetClientListening() + + // Added for HL 1109 (no SDK update): + NULL, // pfnGetPlayerAuthId() + + // Added 2003-11-10 (no SDK update): + NULL, // pfnSequenceGet() + NULL, // pfnSequencePickSentence() + NULL, // pfnGetFileSize() + NULL, // pfnGetApproxWavePlayLen() + NULL, // pfnIsCareerMatch() + NULL, // pfnGetLocalizedStringLength() + NULL, // pfnRegisterTutorMessageShown() + NULL, // pfnGetTimesTutorMessageShown() + NULL, // pfnProcessTutorMessageDecayBuffer() + NULL, // pfnConstructTutorMessageDecayBuffer() + NULL, // pfnResetTutorMessageDecayData() + + // Added Added 2005-08-11 (no SDK update) + NULL, // pfnQueryClientCvarValue() + // Added Added 2005-11-22 (no SDK update) + NULL, // pfnQueryClientCvarValue2() +}; + +C_DLLEXPORT int GetEngineFunctions(enginefuncs_t *pengfuncsFromEngine, int *interfaceVersion) +{ + if(!pengfuncsFromEngine) { + UTIL_LogPrintf("GetEngineFunctions called with null pengfuncsFromEngine"); + return(FALSE); + } + else if(*interfaceVersion != ENGINE_INTERFACE_VERSION) { + UTIL_LogPrintf("GetEngineFunctions version mismatch; requested=%d ours=%d", *interfaceVersion, ENGINE_INTERFACE_VERSION); + // Tell metamod what version we had, so it can figure out who is out of date. + *interfaceVersion = ENGINE_INTERFACE_VERSION; + return(FALSE); + } + memcpy(pengfuncsFromEngine, &meta_engfuncs, sizeof(enginefuncs_t)); + return(TRUE); +} diff --git a/reunion/src/h_export.cpp b/reunion/src/h_export.cpp new file mode 100644 index 0000000..5c9ca56 --- /dev/null +++ b/reunion/src/h_export.cpp @@ -0,0 +1,40 @@ +// From SDK dlls/h_export.cpp: + +/*** +* +* Copyright (c) 1999, 2000 Valve LLC. All rights reserved. +* +* This product contains software technology licensed from Id +* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc. +* All Rights Reserved. +* +* Use, distribution, and modification of this source code and/or resulting +* object code is restricted to non-commercial enhancements to products from +* Valve LLC. All other use, distribution, or modification is prohibited +* without written permission from Valve LLC. +* +****/ +/* + +===== h_export.cpp ======================================================== + + Entity classes exported by Halflife. + +*/ + +#include "precompiled.h" + +// From SDK dlls/h_export.cpp: + +//! Holds engine functionality callbacks +enginefuncs_t g_engfuncs; +globalvars_t *gpGlobals; + +// Receive engine function table from engine. +// This appears to be the _first_ DLL routine called by the engine, so we +// do some setup operations here. +C_DLLEXPORT void WINAPI GiveFnptrsToDll(enginefuncs_t* pengfuncsFromEngine, globalvars_t *pGlobals) +{ + memcpy(&g_engfuncs, pengfuncsFromEngine, sizeof(enginefuncs_t)); + gpGlobals = pGlobals; +} diff --git a/reunion/src/meta_api.cpp b/reunion/src/meta_api.cpp new file mode 100644 index 0000000..935a337 --- /dev/null +++ b/reunion/src/meta_api.cpp @@ -0,0 +1,144 @@ +// meta_api.cpp - minimal implementation of metamod's plugin interface + +// This is intended to illustrate the (more or less) bare minimum code +// required for a valid metamod plugin, and is targeted at those who want +// to port existing HL/SDK DLL code to run as a metamod plugin. + +/* + * Copyright (c) 2001-2003 Will Day + * + * This file is part of Metamod. + * + * Metamod 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 2 of the License, or (at + * your option) any later version. + * + * Metamod 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 Metamod; if not, write to the Free Software Foundation, + * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * In addition, as a special exception, the author gives permission to + * link the code of this program with the Half-Life Game Engine ("HL + * Engine") and Modified Game Libraries ("MODs") developed by Valve, + * L.L.C ("Valve"). You must obey the GNU General Public License in all + * respects for all of the code used other than the HL Engine and MODs + * from Valve. If you modify this file, you may extend this exception + * to your version of the file, but you are not obligated to do so. If + * you do not wish to do so, delete this exception statement from your + * version. + * + */ + +#include "precompiled.h" + +// Description of plugin +plugin_info_t Plugin_info = { + META_INTERFACE_VERSION, // ifvers + "Reunion", // name + APP_VERSION, // version + APP_COMMIT_DATE, // date + "The Legion", // author + "", // url + "REUNION", // logtag, all caps please + PT_STARTUP, // (when) loadable + PT_NEVER, // (when) unloadable +}; + +// Global vars from metamod: +meta_globals_t *gpMetaGlobals; // metamod globals +gamedll_funcs_t *gpGamedllFuncs; // gameDLL function tables +mutil_funcs_t *gpMetaUtilFuncs; // metamod utility functions + +// Metamod requesting info about this plugin: +// ifvers (given) interface_version metamod is using +// pPlugInfo (requested) struct with info about plugin +// pMetaUtilFuncs (given) table of utility functions provided by metamod +C_DLLEXPORT int Meta_Query(char *ifvers, plugin_info_t **pPlugInfo, mutil_funcs_t *pMetaUtilFuncs) +{ + // Give metamod our plugin_info struct + *pPlugInfo = &Plugin_info; + + // Get metamod utility function table. + gpMetaUtilFuncs = pMetaUtilFuncs; + return TRUE; +} + +// Must provide at least one of these.. +static META_FUNCTIONS gMetaFunctionTable = { + NULL, // pfnGetEntityAPI HL SDK; called before game DLL + NULL, // pfnGetEntityAPI_Post META; called after game DLL + &GetEntityAPI2, // pfnGetEntityAPI2 HL SDK2; called before game DLL + NULL, // pfnGetEntityAPI2_Post META; called after game DLL + NULL, // pfnGetNewDLLFunctions HL SDK2; called before game DLL + NULL, // pfnGetNewDLLFunctions_Post META; called after game DLL + NULL, // pfnGetEngineFunctions META; called before HL engine + NULL, // pfnGetEngineFunctions_Post META; called after HL engine +}; + +// Metamod attaching plugin to the server. +// now (given) current phase, ie during map, during changelevel, or at startup +// pFunctionTable (requested) table of function tables this plugin catches +// pMGlobals (given) global vars from metamod +// pGamedllFuncs (given) copy of function tables from game dll +C_DLLEXPORT int Meta_Attach(PLUG_LOADTIME now, META_FUNCTIONS *pFunctionTable, meta_globals_t *pMGlobals, gamedll_funcs_t *pGamedllFuncs) +{ + if (!pMGlobals) { + LOG_ERROR(PLID, "Meta_Attach called with null pMGlobals"); + return FALSE; + } + + gpMetaGlobals = pMGlobals; + + if (!pFunctionTable) { + LOG_ERROR(PLID, "Meta_Attach called with null pFunctionTable"); + return FALSE; + } + + memcpy(pFunctionTable, &gMetaFunctionTable, sizeof(META_FUNCTIONS)); + gpGamedllFuncs = pGamedllFuncs; + + return Reunion_Load() ? TRUE : FALSE; +} + +// Metamod detaching plugin from the server. +// now (given) current phase, ie during map, etc +// reason (given) why detaching (refresh, console unload, forced unload, etc) +C_DLLEXPORT int Meta_Detach(PLUG_LOADTIME now, PL_UNLOAD_REASON reason) +{ + Reunion_Free_Players(); + return TRUE; +} + +bool Reunion_Load() { + if (!Reunion_Utils_Init()) + return false; + + if (!Reunion_Cfg_LoadDefault()) + return false; + + if (!Reunion_RehldsApi_Init()) { + LCPrintf(true, "Failed to locate REHLDS API\n"); + return false; + } + + if (!Reunion_Init_Players()) { + LCPrintf(true, "Failed to initialize players\n"); + return false; + } + + Reunion_Init_Authorizers(); + Reunion_Init_ServerInfo(); + + if (!Reunion_Auth_Init()) { + LCPrintf(true, "Reunion_Auth_Init failed\n"); + } + + Reunion_Api_Init(); + return true; +} diff --git a/reunion/src/murmur3.cpp b/reunion/src/murmur3.cpp new file mode 100644 index 0000000..0280ba0 --- /dev/null +++ b/reunion/src/murmur3.cpp @@ -0,0 +1,302 @@ +//----------------------------------------------------------------------------- +// MurmurHash3 was written by Austin Appleby, and is placed in the public +// domain. The author hereby disclaims copyright to this source code. + +// Note - The x86 and x64 versions do _not_ produce the same results, as the +// algorithms are optimized for their respective platforms. You can still +// compile and run any of them on any platform, but your performance with the +// non-native version will be less than optimal. + +#include "precompiled.h" + +//----------------------------------------------------------------------------- +// Platform-specific functions and macros + +#ifdef __GNUC__ +#define FORCE_INLINE __attribute__((always_inline)) inline +#else +#ifdef _MSC_VER +#define FORCE_INLINE __forceinline +#else +#define FORCE_INLINE inline +#endif +#endif + +#define ROTL32(x,y) rotl(x,y) +#define ROTL64(x,y) rotl64(x,y) + +#define BIG_CONSTANT(x) (x##ULL) + +//----------------------------------------------------------------------------- +// Block read - if your platform needs to do endian-swapping or can only +// handle aligned reads, do the conversion here + +#define getblock(p, i) (p[i]) + +//----------------------------------------------------------------------------- +// Finalization mix - force all bits of a hash block to avalanche + +static FORCE_INLINE uint32 fmix32(uint32 h) +{ + h ^= h >> 16; + h *= 0x85ebca6b; + h ^= h >> 13; + h *= 0xc2b2ae35; + h ^= h >> 16; + + return h; +} + +//---------- + +static FORCE_INLINE uint64 fmix64(uint64 k) +{ + k ^= k >> 33; + k *= BIG_CONSTANT(0xff51afd7ed558ccd); + k ^= k >> 33; + k *= BIG_CONSTANT(0xc4ceb9fe1a85ec53); + k ^= k >> 33; + + return k; +} + +//----------------------------------------------------------------------------- + +void MurmurHash3_x86_32(const void *key, int len, uint32 seed, void *out) +{ + const uint8 *data = (const uint8*)key; + const int nblocks = len / 4; + int i; + + uint32 h1 = seed; + + uint32 c1 = 0xcc9e2d51; + uint32 c2 = 0x1b873593; + + //---------- + // body + + const uint32 *blocks = (const uint32 *)(data + nblocks*4); + + for(i = -nblocks; i; i++) + { + uint32 k1 = getblock(blocks,i); + + k1 *= c1; + k1 = ROTL32(k1,15); + k1 *= c2; + + h1 ^= k1; + h1 = ROTL32(h1,13); + h1 = h1*5+0xe6546b64; + } + + //---------- + // tail + + const uint8 *tail = (const uint8*)(data + nblocks*4); + + uint32 k1 = 0; + + switch(len & 3) + { + case 3: k1 ^= tail[2] << 16; + case 2: k1 ^= tail[1] << 8; + case 1: k1 ^= tail[0]; + k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1; + }; + + //---------- + // finalization + + h1 ^= len; + h1 = fmix32(h1); + + *(uint32*)out = h1; +} + +//----------------------------------------------------------------------------- + +void MurmurHash3_x86_128(const void *key, const int len, uint32 seed, void *out) +{ + const uint8 *data = (const uint8*)key; + const int nblocks = len / 16; + int i; + + uint32 h1 = seed; + uint32 h2 = seed; + uint32 h3 = seed; + uint32 h4 = seed; + + uint32 c1 = 0x239b961b; + uint32 c2 = 0xab0e9789; + uint32 c3 = 0x38b34ae5; + uint32 c4 = 0xa1e38b93; + + //---------- + // body + + const uint32 *blocks = (const uint32 *)(data + nblocks*16); + + for(i = -nblocks; i; i++) + { + uint32 k1 = getblock(blocks,i*4+0); + uint32 k2 = getblock(blocks,i*4+1); + uint32 k3 = getblock(blocks,i*4+2); + uint32 k4 = getblock(blocks,i*4+3); + + k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1; + + h1 = ROTL32(h1,19); h1 += h2; h1 = h1*5+0x561ccd1b; + + k2 *= c2; k2 = ROTL32(k2,16); k2 *= c3; h2 ^= k2; + + h2 = ROTL32(h2,17); h2 += h3; h2 = h2*5+0x0bcaa747; + + k3 *= c3; k3 = ROTL32(k3,17); k3 *= c4; h3 ^= k3; + + h3 = ROTL32(h3,15); h3 += h4; h3 = h3*5+0x96cd1c35; + + k4 *= c4; k4 = ROTL32(k4,18); k4 *= c1; h4 ^= k4; + + h4 = ROTL32(h4,13); h4 += h1; h4 = h4*5+0x32ac3b17; + } + + //---------- + // tail + + const uint8 *tail = (const uint8*)(data + nblocks*16); + + uint32 k1 = 0; + uint32 k2 = 0; + uint32 k3 = 0; + uint32 k4 = 0; + + switch(len & 15) + { + case 15: k4 ^= tail[14] << 16; + case 14: k4 ^= tail[13] << 8; + case 13: k4 ^= tail[12] << 0; + k4 *= c4; k4 = ROTL32(k4,18); k4 *= c1; h4 ^= k4; + + case 12: k3 ^= tail[11] << 24; + case 11: k3 ^= tail[10] << 16; + case 10: k3 ^= tail[ 9] << 8; + case 9: k3 ^= tail[ 8] << 0; + k3 *= c3; k3 = ROTL32(k3,17); k3 *= c4; h3 ^= k3; + + case 8: k2 ^= tail[ 7] << 24; + case 7: k2 ^= tail[ 6] << 16; + case 6: k2 ^= tail[ 5] << 8; + case 5: k2 ^= tail[ 4] << 0; + k2 *= c2; k2 = ROTL32(k2,16); k2 *= c3; h2 ^= k2; + + case 4: k1 ^= tail[ 3] << 24; + case 3: k1 ^= tail[ 2] << 16; + case 2: k1 ^= tail[ 1] << 8; + case 1: k1 ^= tail[ 0] << 0; + k1 *= c1; k1 = ROTL32(k1,15); k1 *= c2; h1 ^= k1; + }; + + //---------- + // finalization + + h1 ^= len; h2 ^= len; h3 ^= len; h4 ^= len; + + h1 += h2; h1 += h3; h1 += h4; + h2 += h1; h3 += h1; h4 += h1; + + h1 = fmix32(h1); + h2 = fmix32(h2); + h3 = fmix32(h3); + h4 = fmix32(h4); + + h1 += h2; h1 += h3; h1 += h4; + h2 += h1; h3 += h1; h4 += h1; + + ((uint32*)out)[0] = h1; + ((uint32*)out)[1] = h2; + ((uint32*)out)[2] = h3; + ((uint32*)out)[3] = h4; +} + +//----------------------------------------------------------------------------- + +void MurmurHash3_x64_128(const void *key, const int len, const uint32 seed, void *out) +{ + const uint8 *data = (const uint8*)key; + const int nblocks = len / 16; + int i; + + uint64 h1 = seed; + uint64 h2 = seed; + + uint64 c1 = BIG_CONSTANT(0x87c37b91114253d5); + uint64 c2 = BIG_CONSTANT(0x4cf5ad432745937f); + + //---------- + // body + + const uint64 *blocks = (const uint64 *)(data); + + for(i = 0; i < nblocks; i++) + { + uint64 k1 = getblock(blocks,i*2+0); + uint64 k2 = getblock(blocks,i*2+1); + + k1 *= c1; k1 = ROTL64(k1,31); k1 *= c2; h1 ^= k1; + + h1 = ROTL64(h1,27); h1 += h2; h1 = h1*5+0x52dce729; + + k2 *= c2; k2 = ROTL64(k2,33); k2 *= c1; h2 ^= k2; + + h2 = ROTL64(h2,31); h2 += h1; h2 = h2*5+0x38495ab5; + } + + //---------- + // tail + + const uint8 *tail = (const uint8*)(data + nblocks*16); + + uint64 k1 = 0; + uint64 k2 = 0; + + switch(len & 15) + { + case 15: k2 ^= (uint64)(tail[14]) << 48; + case 14: k2 ^= (uint64)(tail[13]) << 40; + case 13: k2 ^= (uint64)(tail[12]) << 32; + case 12: k2 ^= (uint64)(tail[11]) << 24; + case 11: k2 ^= (uint64)(tail[10]) << 16; + case 10: k2 ^= (uint64)(tail[ 9]) << 8; + case 9: k2 ^= (uint64)(tail[ 8]) << 0; + k2 *= c2; k2 = ROTL64(k2,33); k2 *= c1; h2 ^= k2; + + case 8: k1 ^= (uint64)(tail[ 7]) << 56; + case 7: k1 ^= (uint64)(tail[ 6]) << 48; + case 6: k1 ^= (uint64)(tail[ 5]) << 40; + case 5: k1 ^= (uint64)(tail[ 4]) << 32; + case 4: k1 ^= (uint64)(tail[ 3]) << 24; + case 3: k1 ^= (uint64)(tail[ 2]) << 16; + case 2: k1 ^= (uint64)(tail[ 1]) << 8; + case 1: k1 ^= (uint64)(tail[ 0]) << 0; + k1 *= c1; k1 = ROTL64(k1,31); k1 *= c2; h1 ^= k1; + }; + + //---------- + // finalization + + h1 ^= len; h2 ^= len; + + h1 += h2; + h2 += h1; + + h1 = fmix64(h1); + h2 = fmix64(h2); + + h1 += h2; + h2 += h1; + + ((uint64*)out)[0] = h1; + ((uint64*)out)[1] = h2; +} diff --git a/reunion/src/murmur3.h b/reunion/src/murmur3.h new file mode 100644 index 0000000..290ebfe --- /dev/null +++ b/reunion/src/murmur3.h @@ -0,0 +1,18 @@ +//----------------------------------------------------------------------------- +// MurmurHash3 was written by Austin Appleby, and is placed in the +// public domain. The author hereby disclaims copyright to this source +// code. + +#pragma once + +#include "reunion_shared.h" + +//----------------------------------------------------------------------------- + +void MurmurHash3_x86_32 (const void *key, int len, uint32 seed, void *out); + +void MurmurHash3_x86_128(const void *key, const int len, uint32 seed, void *out); + +void MurmurHash3_x64_128(const void *key, const int len, const uint32 seed, void *out); + +//----------------------------------------------------------------------------- diff --git a/reunion/src/osconf.h b/reunion/src/osconf.h new file mode 100644 index 0000000..5c4431a --- /dev/null +++ b/reunion/src/osconf.h @@ -0,0 +1,51 @@ +#pragma once + +#include "version/appversion.h" + +#ifdef WIN32 + #define WIN32_LEAN_AND_MEAN + #include + #include + #include + #include + #include + #define NOINLINE __declspec(noinline) + + #define snprintf _snprintf + #define strcasecmp _stricmp + #define rotl _rotl + #define rotr _rotr + #define rotl64 _rotl64 + #define rotr64 _rotr64 + +#else //WIN32 + #include + #include + #include + #include + #include + #include + #include + #define NOINLINE __attribute__((noinline)) + + inline uint32_t rotl(uint32_t x, int r) + { + return (x << r) | (x >> (32 - r)); + } + + inline uint32_t rotr(uint32_t x, int r) + { + return (x >> r) | (x << (32 - r)); + } + + inline uint64_t rotl64(uint64_t x, int r) + { + return (x << r) | (x >> (64 - r)); + } + + inline uint64_t rotr64(uint64_t x, int r) + { + return (x >> r) | (x << (64 - r)); + } + +#endif //WIN32 diff --git a/reunion/src/precompiled.cpp b/reunion/src/precompiled.cpp new file mode 100644 index 0000000..5f656a4 --- /dev/null +++ b/reunion/src/precompiled.cpp @@ -0,0 +1 @@ +#include "precompiled.h" diff --git a/reunion/src/precompiled.h b/reunion/src/precompiled.h new file mode 100644 index 0000000..b97b3e8 --- /dev/null +++ b/reunion/src/precompiled.h @@ -0,0 +1,39 @@ +#pragma once + +#include "osconf.h" +#include +#include +#include + +#include +#include + +#define _ITERATOR_DEBUG_LEVEL 0 +#include + +#include +#include +#include +#include + +#include "rehlds_api.h" +#include "interface.h" +#include "strtools.h" + +#include "sha2.h" +#include "murmur3.h" +#include "Rijndael.h" +#include "RijndaelChanged.h" + +#include "client_auth.h" +#include "reunion_authorizers.h" +#include "reunion_cfg.h" +#include "reunion_api.h" +#include "reunion_player.h" +#include "reunion_rehlds_api.h" +#include "reunion_shared.h" +#include "reunion_utils.h" +#include "Sizebuf.h" + +#include "protocol.h" +#include "server_info.h" diff --git a/reunion/src/protocol.h b/reunion/src/protocol.h new file mode 100644 index 0000000..94ea21a --- /dev/null +++ b/reunion/src/protocol.h @@ -0,0 +1,154 @@ +#pragma once + +#define STEAM_MAX_PACKET_SIZE 1400 +#define NETWORK_HEADERS_SIZE 42 // ip header + udp header + +#define GAMESERVER_STEAMID 0x01 // not NULL + +// Extra Data Flags +// https://developer.valvesoftware.com/wiki/Server_queries#Response_Format +#define EDF_FLAG_PORT 0x80 // The server's game port number +#define EDF_FLAG_STEAMID 0x10 // Server's SteamID +#define EDF_FLAG_SOURCE_TV 0x40 // Spectator port number and Name of spectator server for SourceTV +#define EDF_FLAG_GAME_TAGS 0x20 // Tags that describe the game according to the server +#define EDF_FLAG_GAMEID 0x1 // The server's 64-bit GameID. If this is present, a more accurate AppID is present in the low 24 bits. + // The earlier AppID could have been truncated as it was forced into 16-bit storage. + +#define CONNECTIONLESS_HEADER -1 +#define MULTIPACKET_HEADER -2 + +// +#define PORT_MODMASTER 27011 // Default mod-master port, UDP +#define PORT_CLIENT 27005 // Default client port, UDP +#define PORT_SERVER 27015 // Default server port, UDP +#define PORT_RCON 27015 // Default RCON port, UDP + +#define PROTOCOL_AUTHCERTIFICATE 0x01 // Connection from client is using a WON authenticated certificate +#define PROTOCOL_HASHEDCDKEY 0x02 // Connection from client is using hashed CD key because WON comm. channel was unreachable +#define PROTOCOL_STEAM 0x03 // Steam certificates +#define PROTOCOL_UNKNOWN 0x04 // Unknown protocol +#define PROTOCOL_LASTVALID 0x04 // Last valid protocol + +// M = master, S = server, C = client, A = any +// the second character will allways be \n if the message isn't a single +// byte long (?? not true anymore?) + +// Client connection is initiated by requesting a challenge value +// the server sends this value back +#define S2C_CHALLENGE 'A' // + challenge value + +// Response to source query +#define S2A_INFO 'I' + +// Send a userid, client remote address, is this server secure and engine build number +#define S2C_CONNECTION 'B' + +// HLMaster rejected a server's connection because the server needs to be updated +#define M2S_REQUESTRESTART 'O' + +// Response details about each player on the server +#define S2A_PLAYERS 'D' + +// Number of rules + string key and string value pairs +#define S2A_RULES 'E' + +// info request +#define S2A_INFO_OLD 'C' // deprecated goldsrc response + +// New Query protocol, returns dedicated or not, + other performance info. +#define S2A_INFO_DETAILED 'm' + +// Send a log event as key value +#define S2A_LOGSTRING 'R' + +// Send a log string +#define S2A_LOGKEY 'S' + +// Basic information about the server +#define A2S_INFO 'T' + +// Details about each player on the server +#define A2S_PLAYER 'U' + +// The rules the server is using +#define A2S_RULES 'V' + +// Another user is requesting a challenge value from this machine +#define A2A_GETCHALLENGE 'W' // Request challenge # from another machine + +// Generic Ping Request +#define A2A_PING 'i' // respond with an A2A_ACK + +// Generic Ack +#define A2A_ACK 'j' // general acknowledgement without info + +// Print to client console +#define A2A_PRINT 'l' // print a message on client + +// Challenge response from master +#define M2A_CHALLENGE 's' // + challenge value + +typedef enum svc_commands_e +{ + svc_bad, + svc_nop, + svc_disconnect, + svc_event, + svc_version, + svc_setview, + svc_sound, + svc_time, + svc_print, + svc_stufftext, + svc_setangle, + svc_serverinfo, + svc_lightstyle, + svc_updateuserinfo, + svc_deltadescription, + svc_clientdata, + svc_stopsound, + svc_pings, + svc_particle, + svc_damage, + svc_spawnstatic, + svc_event_reliable, + svc_spawnbaseline, + svc_temp_entity, + svc_setpause, + svc_signonnum, + svc_centerprint, + svc_killedmonster, + svc_foundsecret, + svc_spawnstaticsound, + svc_intermission, + svc_finale, + svc_cdtrack, + svc_restore, + svc_cutscene, + svc_weaponanim, + svc_decalname, + svc_roomtype, + svc_addangle, + svc_newusermsg, + svc_packetentities, + svc_deltapacketentities, + svc_choke, + svc_resourcelist, + svc_newmovevars, + svc_resourcerequest, + svc_customization, + svc_crosshairangle, + svc_soundfade, + svc_filetxferfailed, + svc_hltv, + svc_director, + svc_voiceinit, + svc_voicedata, + svc_sendextrainfo, + svc_timescale, + svc_resourcelocation, + svc_sendcvarvalue, + svc_sendcvarvalue2, + svc_startofusermessages = svc_sendcvarvalue2, + svc_endoflist = 255, +} svc_commands_t; diff --git a/reunion/src/public_amalgamation.cpp b/reunion/src/public_amalgamation.cpp new file mode 100644 index 0000000..d3e05c7 --- /dev/null +++ b/reunion/src/public_amalgamation.cpp @@ -0,0 +1,5 @@ +#include "precompiled.h" + +#include "sys_shared.cpp" +#include "interface.cpp" +#include "crc32c.cpp" diff --git a/reunion/src/query_banlist.cpp b/reunion/src/query_banlist.cpp new file mode 100644 index 0000000..269d2d6 --- /dev/null +++ b/reunion/src/query_banlist.cpp @@ -0,0 +1,54 @@ +#include "precompiled.h" + +void CQueryBanlist::addBan(uint32_t ip, uint32_t time, int pps) +{ + m_bans.push_back({ ip, (uint32_t)g_ServerInfo->getRealTime() + time * 60, pps }); + const char* ipstr = util_adr_to_string(ip); + LCPrintf(true, "ip %s banned for %i minutes for query flooding (PPS: %i)\n", ipstr, time, pps); +} + +void CQueryBanlist::addBan(uint32_t ip, uint32_t time) +{ + m_bans.push_back({ ip, (uint32_t)g_ServerInfo->getRealTime() + time * 60, 0 }); + util_console_print("ReuBans: ip %s banned for %i minutes from console\n", util_adr_to_string(ip), time); +} + +bool CQueryBanlist::removeBan(uint32_t ip) +{ + std::vector::iterator ban = std::find_if(m_bans.begin(), m_bans.end(), [ip](ban_t& ban) { return ban.ip == ip; }); + if (ban != m_bans.end()) { + util_console_print("ReuBans: removed ban of %s\n", util_adr_to_string(ip)); + m_bans.erase(ban); + return true; + } + + util_console_print("ReuBans: ip %s is not banned\n", util_adr_to_string(ip)); + return false; +} + +bool CQueryBanlist::isBanned(uint32_t ip) const +{ + for (const ban_t &ban : m_bans) { + if (ban.ip == ip) + return true; + } + + return false; +} + +void CQueryBanlist::removeExpired(uint32_t realtime) +{ + if (!m_bans.empty()) { + m_bans.erase(std::remove_if(m_bans.begin(), m_bans.end(), [&](ban_t& ban) { return ban.end < realtime; }), m_bans.end()); + } +} + +void CQueryBanlist::print() +{ + util_console_print("%-16s\t%-8s\tExpire time\n", "IP", "pps"); + + for (const ban_t &ban : m_bans) { + uint32_t exp = ban.end - (uint32_t)g_ServerInfo->getRealTime(); + util_console_print("%-16s\t%-8u\t%u:%.2u\n", util_adr_to_string(ban.ip), ban.pps, exp / 60, exp % 60); + } +} diff --git a/reunion/src/query_banlist.h b/reunion/src/query_banlist.h new file mode 100644 index 0000000..7ee02dc --- /dev/null +++ b/reunion/src/query_banlist.h @@ -0,0 +1,22 @@ +#pragma once + +struct ban_t +{ + uint32_t ip; + uint32_t end; + int pps; +}; + +class CQueryBanlist +{ +public: + void addBan(uint32_t ip, uint32_t time, int pps); + void addBan(uint32_t ip, uint32_t time); + bool removeBan(uint32_t ip); + bool isBanned(uint32_t ip) const; + void removeExpired(uint32_t realtime); + void print(); + +private: + std::vector m_bans; +}; diff --git a/reunion/src/query_bugfix.cpp b/reunion/src/query_bugfix.cpp new file mode 100644 index 0000000..38a0d6e --- /dev/null +++ b/reunion/src/query_bugfix.cpp @@ -0,0 +1,31 @@ +#include "precompiled.h" + +CBuggedQueryFix::CBuggedQueryFix() +{ + reset(); +} + +bool CBuggedQueryFix::isBuggedQuery(const netadr_t& from) +{ + double realtime = g_ServerInfo->getRealTime(); + uint32 ip = *(uint32 *)from.ip; + + for (last_query_t& q : m_lastQueries) { + if (q.ip == ip) { + double delta = realtime - q.time; + q.time = realtime; + return delta < BUGGED_QUERY_FIX_MAXDELTA; + } + } + + last_query_t& q = m_lastQueries[m_seq++ & (BUGGED_QUERY_FIX_MAXIPS - 1)]; + q.ip = ip; + q.time = realtime; + return false; +} + +void CBuggedQueryFix::reset() +{ + memset(m_lastQueries, 0, sizeof m_lastQueries); + m_seq = 0; +} diff --git a/reunion/src/query_bugfix.h b/reunion/src/query_bugfix.h new file mode 100644 index 0000000..53b63dc --- /dev/null +++ b/reunion/src/query_bugfix.h @@ -0,0 +1,23 @@ +#pragma once + +#define BUGGED_QUERY_FIX_MAXIPS 16 // max stored ips for detecting a several queries row +#define BUGGED_QUERY_FIX_MAXDELTA 0.05 + +class CBuggedQueryFix +{ +public: + CBuggedQueryFix(); + + bool isBuggedQuery(const netadr_t& from); + void reset(); + +private: + struct last_query_t + { + uint32 ip; + double time; + }; + + last_query_t m_lastQueries[BUGGED_QUERY_FIX_MAXIPS]; + size_t m_seq; +}; diff --git a/reunion/src/query_limiter.cpp b/reunion/src/query_limiter.cpp new file mode 100644 index 0000000..228684c --- /dev/null +++ b/reunion/src/query_limiter.cpp @@ -0,0 +1,155 @@ +#include "precompiled.h" + +CQueryLimiter::CQueryLimiter() +{ + m_totalIncomingSize = 0; + m_totalPackets = 0; + m_totalQueries = 0; + m_uniqueQueries = 0; + m_useGlobalRateLimit = false; + m_lastAdded = -1; + memset(m_lastQueries, 0, sizeof m_lastQueries); + + if ((MAX_STORED_QUERIES & (MAX_STORED_QUERIES - 1)) != 0) + util_syserror("MAX_STORED_QUERIES must be power of 2"); + if ((BUGGED_QUERY_FIX_MAXIPS & (BUGGED_QUERY_FIX_MAXIPS - 1)) != 0) + util_syserror("BUGGED_QUERY_FIX_MAXIPS must be power of 2"); +} + +bool CQueryLimiter::allowQuery(const netadr_t& adr, bool critical) +{ + if (!g_ReunionConfig->enableQueryLimiter()) + return true; + + if (allowForExcept(*(uint32_t *)adr.ip, ntohs(adr.port))) + return true; + + for (size_t i = 0; i < MAX_STORED_QUERIES; i++) + { + if (m_lastQueries[i].ip != *(uint32 *)adr.ip) { + continue; + } + + if (critical && m_lastQueries[i].rate < MIN_HP_QUERIES_RATE) { + m_lastQueries[i].rate = MIN_HP_QUERIES_RATE; + return true; + } + + // check flood from addr + return ++m_lastQueries[i].rate <= uint32(critical ? MAX_HP_QUERIES_RATE : MAX_LP_QUERIES_RATE); + } + + // flood from many new ips + if (++m_uniqueQueries > MAX_STORED_QUERIES) { + checkForGlobalRateLimit(); + return false; + } + + // save new addr + size_t id = ++m_lastAdded & (MAX_STORED_QUERIES - 1); + m_lastQueries[id].ip = *(uint32 *)adr.ip; + m_lastQueries[id].rate = 1; + return true; +} + +void CQueryLimiter::addExceptIPs(std::vector& exceptIPs) +{ + std::move(exceptIPs.begin(), exceptIPs.end(), std::back_inserter(m_exceptIPs)); + exceptIPs.clear(); +} + +bool CQueryLimiter::allowForExcept(uint32_t ip, uint16_t port) const +{ + for (const ipv4_t &e : m_exceptIPs) + { + if (e.ip == ip && + (e.port == 0 || e.port == port)) { + return true; + } + } + + return false; + +} + +bool CQueryLimiter::isUnderFlood() const +{ + return m_uniqueQueries >= MAX_STORED_QUERIES; +} + +void CQueryLimiter::checkRates(float currentTime, float delta, CQueryBanlist& banlist) +{ + for (size_t i = 0; i < MAX_STORED_QUERIES; i++) + { + const int rate = m_lastQueries[i].rate; + + if (rate) + { + const int bantime = g_ReunionConfig->getFloodBanTime(); + const int pps = int(double(rate) / delta); + + // ban sender if query rate exceeds limit + if (bantime != 0 && pps > g_ReunionConfig->getQueriesBanLevel()) + { + banlist.addBan(m_lastQueries[i].ip, bantime, pps); + m_lastQueries[i].rate = 0; + continue; + } + + // gradually reduce rate + if (rate <= MAX_LP_QUERIES_RATE * 2) + m_lastQueries[i].rate = 0; + else + m_lastQueries[i].rate = max(MAX_LP_QUERIES_RATE / 2, rate - int(g_ReunionConfig->getQueriesBanLevel() * delta)); + } + } + + // check for high-pps flood + checkForGlobalRateLimit(); + + // log flood from many ips + if (isUnderFlood() && currentTime - m_lastFloodLog > QUERY_FLOOD_LOG_INTERVAL) + { + m_lastFloodLog = currentTime; + + const int globalPps = int(double(m_totalPackets) / delta); + const float globalMbps = (m_totalIncomingSize * 8.0 / 1000000.0) / delta; + LCPrintf(true, "Query flood blocking: %i pps (%.3f mbps) from %i+ IPs\n", globalPps, globalMbps, MAX_STORED_QUERIES); + } + + // reduce global query rate + m_totalIncomingSize = 0; + m_totalPackets = 0; + m_totalQueries = 0; + + if (m_uniqueQueries <= MAX_STORED_QUERIES * 3/4) + m_uniqueQueries = 0; + else + m_uniqueQueries = max(MAX_STORED_QUERIES * 3/4, m_uniqueQueries - MAX_STORED_QUERIES); +} + +void CQueryLimiter::incomingPacket(size_t bytes) +{ + m_totalIncomingSize += bytes; + m_totalPackets++; +} + +void CQueryLimiter::incomingQuery() +{ + m_totalQueries++; +} + +void CQueryLimiter::checkForGlobalRateLimit() +{ + m_useGlobalRateLimit = m_uniqueQueries > MAX_UNIQUE_QUERIES_FILTER || m_totalQueries > MAX_TOTAL_QUERIES_FILTER; +} + +bool CQueryLimiter::getUseGlobalRateLimit() const +{ + return m_useGlobalRateLimit; +} + +bool CQueryLimiter::allowGlobalQuery() const +{ + return m_totalQueries < MAX_STORED_QUERIES; +} diff --git a/reunion/src/query_limiter.h b/reunion/src/query_limiter.h new file mode 100644 index 0000000..323f68e --- /dev/null +++ b/reunion/src/query_limiter.h @@ -0,0 +1,56 @@ +#pragma once + +#define MAX_LP_QUERIES_RATE 2 // maximum low-priority queries from player between flood checks +#define MAX_HP_QUERIES_RATE 11 // maximum high-priority queries from player between flood checks +#define MIN_HP_QUERIES_RATE 9 // minimal rate for high-priority queries + +#define MAX_STORED_QUERIES 64 // maximum number of ips for individual filtering +#define MAX_UNIQUE_QUERIES_FILTER (MAX_STORED_QUERIES * 3) // filter ip's separately when unique queries rate <= limit +#define MAX_TOTAL_QUERIES_FILTER (MAX_STORED_QUERIES * MAX_HP_QUERIES_RATE) // filter ip's separately when total queries rate <= limit + +#define PACKET_HEADER_SIZE 42 + +// Query flood limiter +#define QUERY_CHECK_INTERVAL 0.25f // time interval between flood checks +#define QUERY_FLOOD_DEFAULT_BANTIME 10.0f +#define QUERY_FLOOD_LOG_INTERVAL 3.0f + +class CQueryLimiter +{ +public: + CQueryLimiter(); + + void addExceptIPs(std::vector& exceptIPs); + + bool allowQuery(const netadr_t& adr, bool critical = false); + bool allowForExcept(uint32_t ip, uint16_t port) const; + bool isUnderFlood() const; + + void checkRates(float currentTime, float delta, CQueryBanlist& banlist); + + void incomingPacket(size_t bytes); + void incomingQuery(); + void checkForGlobalRateLimit(); + bool getUseGlobalRateLimit() const; + bool allowGlobalQuery() const; + +private: + struct last_query_t + { + uint32 ip; + uint32 rate; + }; + + size_t m_totalIncomingSize; + size_t m_totalPackets; + size_t m_totalQueries; + int m_uniqueQueries; + double m_lastFloodLog; + + bool m_useGlobalRateLimit; + + std::vector m_exceptIPs; + + size_t m_lastAdded; + last_query_t m_lastQueries[MAX_STORED_QUERIES]; +}; diff --git a/reunion/src/reunion_api.cpp b/reunion/src/reunion_api.cpp new file mode 100644 index 0000000..d577952 --- /dev/null +++ b/reunion/src/reunion_api.cpp @@ -0,0 +1,298 @@ +#include "precompiled.h" + +cvar_t cv_dp_r_protocol = {"dp_r_protocol", "0", FCVAR_EXTDLL, 0, NULL}; +cvar_t cv_dp_r_id_provider = {"dp_r_id_provider", "0", FCVAR_EXTDLL, 0, NULL}; +cvar_t cv_reunion_api = {"reunion_api", "0", FCVAR_EXTDLL, 0, NULL}; + +cvar_t *pcv_dp_r_protocol; +cvar_t *pcv_dp_r_id_provider; +cvar_t *pcv_reunion_api; + +class CReunionApiImpl : public IReunionApi +{ +public: + CReunionApiImpl(); + + int GetMajorVersion() override; + int GetMinorVersion() override; + + int GetClientProtocol(int index) override; + dp_authkind_e GetClientAuthtype(int index) override; + + size_t GetClientAuthdata(int index, void *data, int maxlen) override; + const char *GetClientAuthdataString(int index, char *data, int maxlen) override; + + void GetLongAuthId(int index, unsigned char (&authId)[LONG_AUTHID_LEN]) override; + reu_authkey_kind GetAuthKeyKind(int index) override; + + void SetConnectTime(int index, double time) override; + USERID_t *GetSerializedId(int index) const override; + USERID_t *GetStorageId(int index) const override; + uint64 GetDisplaySteamId(int index) const override; + +protected: + // Safe checks + // Just make sure that a reunion will never cause segfault + bool IsValidIndex(int index) const; + +private: + int version_major = REUNION_API_VERSION_MAJOR; + int version_minor = REUNION_API_VERSION_MINOR; +}; + +CReunionApiImpl g_ReunionApi; + +int CReunionApiImpl::GetMajorVersion() +{ + return version_major; +} + +int CReunionApiImpl::GetMinorVersion() +{ + return version_minor; +} + +dp_authkind_e Reunion_GetPlayerAuthkind(CReunionPlayer* plr) +{ + dp_authkind_e dpAuthKind; + + switch (plr->GetAuthKind()) + { + case CA_HLTV: + dpAuthKind = DP_AUTH_HLTV; + break; + + case CA_NO_STEAM_47: + case CA_NO_STEAM_48: + case CA_SETTI: + dpAuthKind = DP_AUTH_DPROTO; + break; + + case CA_STEAM: + case CA_STEAM_PENDING: + dpAuthKind = DP_AUTH_STEAM; + break; + + case CA_STEAM_EMU: + dpAuthKind = DP_AUTH_STEAMEMU; + break; + + case CA_OLD_REVEMU: + dpAuthKind = DP_AUTH_OLDREVEMU; + break; + + case CA_REVEMU: + dpAuthKind = DP_AUTH_REVEMU; + break; + + case CA_STEAMCLIENT_2009: + dpAuthKind = DP_AUTH_SC2009; + break; + + case CA_REVEMU_2013: + dpAuthKind = DP_AUTH_REVEMU2013; + break; + + case CA_AVSMP: + dpAuthKind = DP_AUTH_AVSMP; + break; + + case CA_SXEI: + dpAuthKind = DP_AUTH_SXEI; + break; + + default: + dpAuthKind = DP_AUTH_NONE; + break; + } + + return dpAuthKind; +} + +CReunionApiImpl::CReunionApiImpl() +{ + +} + +int CReunionApiImpl::GetClientProtocol(int index) +{ + if (!IsValidIndex(index)) return 0; + return g_Players[index]->getProcotol(); +} + +dp_authkind_e CReunionApiImpl::GetClientAuthtype(int index) +{ + if (!IsValidIndex(index)) return DP_AUTH_NONE; + return Reunion_GetPlayerAuthkind(g_Players[index]); +} + +size_t CReunionApiImpl::GetClientAuthdata(int index, void *data, int maxlen) +{ + if (!IsValidIndex(index)) return 0; + return g_Players[index]->getRawAuthData(data, maxlen); +} + +const char *CReunionApiImpl::GetClientAuthdataString(int index, char *data, int maxlen) +{ + if (!IsValidIndex(index)) return ""; // better nullptr? + + auto* plr = g_Players[index]; + char raw[MAX_AUTHKEY_LEN]; + size_t rawlen; + + rawlen = plr->getRawAuthData(raw, sizeof raw); + + switch (plr->GetAuthKind()) + { + /*case CA_HLTV: + case CA_NO_STEAM_47: + case CA_NO_STEAM_48: + case CA_SETTI: + case CA_STEAM: + case CA_STEAM_PENDING:*/ + + case CA_STEAM_EMU: + case CA_OLD_REVEMU: + case CA_AVSMP: + snprintf(data, maxlen, "%u", *(uint32 *)raw); + break; + + case CA_REVEMU: + case CA_STEAMCLIENT_2009: + case CA_REVEMU_2013: + case CA_SXEI: + snprintf(data, maxlen, "%.*s", rawlen, raw); + break; + + default: + if (maxlen != 0) + data[0] = '\0'; + break; + } + + return data; +} + +void CReunionApiImpl::GetLongAuthId(int index, unsigned char (&authId)[LONG_AUTHID_LEN]) +{ + auto player = g_Players[index]; + + sha_byte raw[256]; + size_t len = player->getRawAuthData(raw, sizeof raw); + + if (!len) { + uint32_t* uptr = (uint32_t *)raw; + uptr[0] = player->GetAuthKind(); + uptr[1] = player->getDisplaySteamId().GetAccountID(); + len = sizeof(uint32_t) * 2; + } + + sha2 hSha; + hSha.Init(sha2::enuSHA256); + hSha.Update(raw, len); + hSha.End(); + + int shaLen; + memcpy(authId, hSha.RawHash(shaLen), LONG_AUTHID_LEN); +} + +reu_authkey_kind CReunionApiImpl::GetAuthKeyKind(int index) +{ + return REU_AK_UNKNOWN; +} + +USERID_t *CReunionApiImpl::GetSerializedId(int index) const { + if (!IsValidIndex(index)) return NULL; + return g_Players[index]->getSerializedId(); +} + +USERID_t *CReunionApiImpl::GetStorageId(int index) const { + if (!IsValidIndex(index)) return NULL; + return g_Players[index]->getStorageId(); +} + +uint64 CReunionApiImpl::GetDisplaySteamId(int index) const { + if (!IsValidIndex(index)) return 0; + return g_Players[index]->getDisplaySteamId().ConvertToUint64(); +} + +void CReunionApiImpl::SetConnectTime(int index, double time) { + if (!IsValidIndex(index)) return; + g_Players[index]->setConnectionTime(time); +} + +bool CReunionApiImpl::IsValidIndex(int index) const +{ + if (index < 0 || index >= g_RehldsSvs->GetMaxClientsLimit()) { + LCPrintf(false, "Invalid player index expected 0-%d, real %d\n", g_RehldsSvs->GetMaxClientsLimit() - 1, index); + return false; + } + + return true; +} + +void Cmd_dp_ClientInfo() +{ + int ArgCount = g_engfuncs.pfnCmd_Argc(); + if (ArgCount > 1) { + int clientId = atoi(g_engfuncs.pfnCmd_Argv(1)) - 1; + if (clientId >= 0 && clientId < g_ServerInfo->getMaxPlayers()) { + CReunionPlayer* plr = g_Players[clientId]; + + if (plr->getClient()->IsConnected()) { + char buf[32]; + + sprintf(buf, "%d", plr->getProcotol()); + g_engfuncs.pfnCvar_DirectSet(pcv_dp_r_protocol, buf); + + sprintf(buf, "%d", Reunion_GetPlayerAuthkind(plr)); + g_engfuncs.pfnCvar_DirectSet(pcv_dp_r_id_provider, buf); + } + else { + g_engfuncs.pfnCvar_DirectSet(pcv_dp_r_protocol, "0"); + g_engfuncs.pfnCvar_DirectSet(pcv_dp_r_id_provider, "0"); + } + } + } + else { + g_engfuncs.pfnCvar_DirectSet(pcv_dp_r_protocol, "-1"); + g_engfuncs.pfnCvar_DirectSet(pcv_dp_r_id_provider, "-1"); + } +} + +void Cmd_reu_Ban() +{ + if (CMD_ARGC() == 3) + g_ServerInfo->banAddress(CMD_ARGV(1), strtoul(CMD_ARGV(2), nullptr, 10)); + else + util_console_print("Usage: reu_ban