commit db0dc8bd5ebce6e2bc27d47085f7f104eb3037d3 Author: NotRexed Date: Fri Nov 20 15:22:16 2026 -0500 Initial commit: Leonida, build-it-yourself PC port groundwork Shader pipeline (carve, FSSM unpack, gfx1013 disassembly, RDNA2 to SPIR-V), asset export via rpf9-explorer's Core (submodule), PE loader and shim skeleton, and make_game.py, which builds from the user's own copy of the game. No game data, keys or executables are included. Co-Authored-By: Claude Opus 5.5 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 000000000..6980b020e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,4 @@ +* text=auto eol=lf +*.ps1 text eol=crlf +*.cmd text eol=crlf +*.sln text eol=crlf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..63221ea5e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,26 @@ +name: CI +on: [push, pull_request] +jobs: + check: + runs-on: windows-latest + steps: + - uses: actions/checkout@v4 + with: + submodules: recursive + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - uses: actions/setup-dotnet@v4 + with: + dotnet-version: "8.0.x" + - name: Python tools compile + run: python -m compileall -q make_game.py tools + - name: make_game.py help + run: python -I make_game.py --help + - name: Build rpf9dump + run: dotnet build tools/rpf9dump/rpf9dump.csproj -c Release + - name: No game data tracked + shell: bash + run: | + bad=$(git ls-files | grep -iE '\.(rpf|ttpf|xvd|dxbc|fssm|spv|spvasm|dds|bk2|awc|exe|dll)$' || true) + if [ -n "$bad" ]; then echo "Game or binary files tracked:"; echo "$bad"; exit 1; fi diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..f28e4fe6c --- /dev/null +++ b/.gitignore @@ -0,0 +1,33 @@ +# ---- never commit the game or anything made from it ---- +# (archives, executables, carved files, shaders, textures, models, audio, reports that quote game data) +reports/ +work/ +assets/ +carve/ +*.rpf +*.ttpf +*.xvd +*.msixvc +*.dxbc +*.fssm +*.spv +*.spvasm +*.dds +*.bk2 +*.awc +*.r9modeldata + +# ---- build output and caches ---- +build/ +bin/ +obj/ +__pycache__/ +*.pyc +*.exe +*.dll +*.pdb +*.ilk +*.lib +*.exp +*.log +.vs/ diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 000000000..a60defcd2 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "third_party/rpf9-explorer"] + path = third_party/rpf9-explorer + url = https://github.com/breadbbbb/rpf9-explorer diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..82971841d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,19 @@ +# Contributing + +Thanks for helping. A few rules keep the project safe to host: + +- **No game data, ever.** That covers archives, the executable, carved files, shaders (DXBC, FSSM, disassembly, + SPIR-V), textures, models, audio, videos, and reports or logs that quote them. `.gitignore` blocks the common + types; check `git status` before you commit anyway. +- **No keys, decryption or protection workarounds**, and no links to where to get them. The tools only read files + that are already plain on disk. +- Short excerpts needed to explain a format (a few header bytes, one instruction sequence) are fine in docs and + comments. + +## Working on the code + +- Python tools run with `python -I` and use only the standard library unless a file says otherwise. +- `tools/rpf9dump` needs the submodule: `git submodule update --init`. +- A new shader-translator rule goes into the contract table in `docs/design.md`, with how it was confirmed: a GPU + test, a Mesa/LLVM reference, or a count over the corpus. +- Say what you tested and on which GPU in the pull request. diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..f288702d2 --- /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 000000000..663c31dc7 --- /dev/null +++ b/README.md @@ -0,0 +1,121 @@ +

+
+ Leonida +
+

+ +

Grand Theft Auto VI (Xbox Series) running natively on Windows, built on your PC from your own copy. +

+ +

+ Status | + How to build | + How it works | + Want to help? | + Credits | + License +

+ +Leonida is a static recompilation project. The Xbox Series CPU is x86-64 like a PC, so the game's code is loaded +and run natively, and the console's system software is reimplemented. The console's precompiled RDNA2 GPU programs +are translated to SPIR-V for Vulkan. The game's models, textures and audio are read from your package. All of this +happens **on your PC, from your own copy of the game**. + +> [!IMPORTANT] +> This repository **does not contain the game, keys or an executable**, and it does not explain how to get them. You +> need your own copy, with its files already readable on disk. Nothing here decrypts or works around any protection. +> Everything the build creates (the generated shaders, extracted assets, the runtime folder and your saves) comes +> from your game and stays on your PC. Never share those files. + +## Project status + +**Early. The game does not boot yet.** Everything that can be done without the game's executable is in place, so +work on booting can start as soon as one is available to a developer. + +| What | Status | +|---|---| +| Version check of your copy (Xbox Series 1.0.2.1) | ✅ Works | +| Shaders: carve, unpack native RDNA2 code, disassemble | ✅ All 26,503 | +| Shaders: RDNA2 → SPIR-V translation | ⚠️ ~97% of vertex/pixel shaders pass `spirv-val`. Compute, mesh and geometry shaders not yet translated | +| Shader translator checked on a real GPU | ⚠️ Vertex fetch, texture sampling, exports and ALU ops checked on one GPU | +| Models (OBJ with real names, UVs, material references) | ✅ Exported. Not all layouts are decoded yet | +| Texture dictionaries and world texture pools (DDS) | ✅ Exported. Some pool entries (BCPack) are skipped | +| Audio banks (AWC: Opus, XMA2) | ✅ Exported whole. Decoding to WAV is not done yet | +| PE loader and import shims | ⚠️ Skeleton. Untested against the real executable | +| Xbox D3D12 → Vulkan | ❌ Not started | +| Booting, story mode, anything playable | ❌ No | + +## How to build + +You need: + +- **Your own copy** of the Xbox Series package, version 1.0.2.1, as plain files in a folder. +- **Windows 10/11 x64**, about **400 GB** free for intermediate files. +- [Python 3.11+](https://www.python.org/), the [.NET 8 SDK](https://dotnet.microsoft.com/download/dotnet/8.0) + and the [Vulkan SDK](https://vulkan.lunarg.com/) (for `spirv-as` / `spirv-val`). +- [LLVM 21+](https://github.com/llvm/llvm-project/releases) with `llvm-mc` on PATH (or set `LLVM_MC`). +- Visual Studio 2022 with **Desktop development with C++**, for the runtime stage. + +Clone with the submodule: + +```powershell +git clone --recursive https://github.com//Leonida +cd Leonida +``` + +Check your copy (reads names and sizes only, takes a second): + +```powershell +python -I make_game.py --game "D:\path\to\your\package" --check +``` + +Build: + +```powershell +python -I make_game.py --game "D:\path\to\your\package" --out "D:\Games\Leonida" +``` + +Stages run in order: `check`, `shaders`, `assets`, `runtime`. Pick some with `--stages shaders,assets`. Put +intermediate files on another drive with `--work`. A stopped build continues where it left off. The shader +translation is the longest step: several hours on one core for now. + +## How it works + +| Piece | What it does | Where | +|---|---|---| +| Version check | Every package file's name, size and SHA-256 for each supported version | `game/`, `make_game.py` | +| Shader pipeline | Carves DXBC containers from `shaders.rpf` without its encrypted table of contents. Unpacks the `XBCH` → `FSSM` native RDNA2 program, disassembles it with LLVM (`gfx1013`) and translates it to SPIR-V | `tools/shader_carve.py`, `fssm_unpack.py`, `shader_disasm.py`, `rdna2spirv.py` | +| Asset export | Finds validated resources inside RPF9 archives and the loose `.ttpf` texture pools | `tools/rpf9dump` (on rpf9-explorer's Core) | +| Runtime | Maps the PE image, resolves imports to shims (GDK, XMem, `d3d12_xs`) | `runtime/` | +| Research tools | PE/RTTI inspection, raw carving, texture tiling probes, GPU test harnesses | `tools/`, `runtime/test/` | + +The translator's runtime contract (user SGPRs, push constants, memory model, bindless images, vertex fetch, +system values) and all the format notes are in [docs/design.md](docs/design.md). + +## Want to help? + +The biggest open pieces: + +- **Compute, mesh and geometry shaders**: their per-stage system-value register layout. +- **Xbox D3D12 → Vulkan**: the `d3d12_xs` command list and descriptor heap model. +- **Audio decoding**: Opus/XMA2 streams in AWC banks to PCM. +- **Model layouts** the decoder rejects today. + +See [CONTRIBUTING.md](CONTRIBUTING.md). Never attach game files, extracted assets or generated shaders to issues or +pull requests. + +## Credits + +- [rpf9-explorer](https://github.com/breadbbbb/rpf9-explorer) by breadbbbb: the RPF9 model, texture-pool and AWC + decoders used by `tools/rpf9dump` (git submodule). +- [Mesa](https://gitlab.freedesktop.org/mesa/mesa) (MIT): GFX10 resource-descriptor layout (`tools/gfx10_formats.json`), + and the ACO/RADV rules used as reference for 16-bit results and shader system registers. +- [LLVM](https://llvm.org/): AMDGPU disassembler. +- [SPIRV-Tools](https://github.com/KhronosGroup/SPIRV-Tools): assembly and validation. + +Grand Theft Auto and all related names are trademarks of their owners. This project is not affiliated with or +endorsed by them. + +## License + +GPLv3 (or any later version). See [LICENSE](LICENSE). Third-party code keeps its own license. diff --git a/docs/design.md b/docs/design.md new file mode 100644 index 000000000..17a78f2bb --- /dev/null +++ b/docs/design.md @@ -0,0 +1,231 @@ +# Design notes + +Groundwork for running the Xbox Series build of GTA VI natively on Windows. It's set up now so the work can start +as soon as `game_scarlett_master.exe` is available. + +## Ground rules + +- Everything here runs from **your own copy** and stays on **your PC**. Game files, generated code, shader caches and + reports that quote game data are never committed, uploaded or shared. `reports/` is git-ignored for this reason. +- Nothing in this folder decrypts, unpacks or works around Xbox package protection. The tools only read files that + are already plain on disk. + +## Why a loader before a recompiler + +The Xbox Series CPU is x86-64, the same as a PC. Unlike Hookshot, where ARM64 code has to be +translated, most of the game's code can run as-is. The work is everything around it: + +| Layer | Approach | Folder | +|---|---|---| +| CPU code | Map the PE image and run it natively. Patch only what can't run on desktop (privileged instructions, console-only intrinsics). | `runtime/src` | +| Imports (GameOS / GDK / Xbox DLLs) | Every imported `dll!function` goes to a shim. Unimplemented ones log once and return a failure, so the missing surface shows up at runtime. | `runtime/shims` | +| Graphics | Xbox D3D12 (`d3d12_xs`) to Vulkan. Shaders ship as compiled RDNA2 machine code, so they need a translator from RDNA2 ISA to SPIR-V. **Largest single piece.** | later | +| Assets | `.rpf` archives (RPF9) read through the runtime's file layer. | later | + +## Layout + +``` +tools/ Python analysis tools (no game data inside) + pe_inspect.py PE headers, sections, entropy, imports sorted by where they resolve, .pdata, TLS + rpf_probe.py RPF header survey of a game folder + manifest.py SHA-256 manifest of a game folder, plus a --verify mode +scripts/ + first_look.ps1 run once the exe arrives: the full report set for it +runtime/ C++ native loader (CMake + Ninja, MSVC) + src/ PE mapper, relocations, import binding, TLS + shims/ per-DLL shim tables +reports/ generated output (git-ignored) +docs/ notes +``` + +## Day one, when the exe is here + +```powershell +.\scripts\first_look.ps1 -Exe "\game_scarlett_master.exe" +``` + +This writes `reports/exe/` (JSON plus a readable summary). Check it in this order: + +1. **Section entropy.** Sections near 8.0 bits/byte are still encrypted or compressed. If `.text` is one of them, + nothing else can be done yet. +2. **Import table.** Each DLL is marked `bundled` (in the game folder), `system` (present on this Windows), or + `shim` (needs a reimplementation). The `shim` list is the real to-do list. +3. **.pdata function count.** This gives function boundaries for patching and later analysis. + +Then `runtime\build\gta6rt.exe --dry-run ` maps the image and binds every import to the shim table without +running any game code. It reports what it couldn't bind. + +## Build the runtime + +```powershell +.\scripts\build_runtime.ps1 +``` + +It sets up MSVC through `vcvars64.bat` and builds at BelowNormal priority on half the cores, writing to `runtime\build\`. +If VS's "C++ CMake tools" component is installed, it uses CMake and Ninja. Otherwise it calls `cl` directly. That +component may not be installed, and the devkitPro MSYS `cmake` on PATH can't build MSVC projects. When you +add a source file, add it to `runtime\CMakeLists.txt` and to the file list in `build_runtime.ps1`. + +## Asset status (no exe needed) + +| Asset | State | Where | +|---|---|---| +| Archive data | Carved without the encrypted tables of contents. Most archives are 93–99% plain zlib (`levels.rpf` 98.3%, 1.1M files). Not zlib: `audio.rpf` (99.9%), about half of `story000.rpf` and `shared_minigame000.rpf`. | `G:\gta6-work\carve\\`, `coverage.json` | +| Videos | 797 Bink 2 files (`KB2n`), cut out whole. | `*.bk2` in the carve folders | +| Shaders | 26,503 carved from `shaders.rpf`, native RDNA2 code unpacked (`FSSM`), and disassembly working. | `G:\gta6-work\shaders\` (`.dxbc`, `fssm\`, `disasm\`) | +| Textures | **Solved.** Headers are in CPU segments: GPU pointer at q[k], u16 width/height/depth and DXGI format at q[k+4], mip count at byte 2 of q[k+5]. Data is AMD `SW_4K_S` tiled, largest mip first. The GPU segment is the blob run after the CPU blob. On 200 samples, 173 decode at least 1.5× smoother detiled than untiled (median 2.56×). Exports the top mip, slice 0, as DDS. **22,342 exported (1.23 GiB)**: every header whose GPU data follows its CPU blob. World and model textures in `levels.rpf` have the same blocker as meshes. GPU offsets must be 256-byte aligned, which drops the false headers in `navmeshes`/`anim`. | `tools\tex_headers.py`, `tools\tex_export.py`, `G:\gta6-work\textures\` | +| Models | **Exporting** with `tools\rpf9dump` (built on breadbbbb/rpf9-explorer's Core; see below). Resources are found at page offset +16 after 16 zero bytes, followed by a zlib system blob with a drawable/fragment header and then the following zlib blocks as graphics data. Positions are quantized: `bias + scale * ((q >> 8) & 0xFFFFFF)`. Output is OBJ (positions, UVs, indices) plus a manifest with real model names (e.g. `cvar_int_grg2b_toys_1`), bounds, per-mesh shader index and material texture references (parameter hash, name hash, 64-bit asset key). My earlier `0x1380`/`0x1601` descriptor notes stand, but the "data not located" blocker was wrong. | `G:\gta6-work\assets\\models\` | +| Texture dictionaries | Same tool: TXD resources become DDS per texture. | `G:\gta6-work\assets\\textures\` | +| World textures (TTPF) | `data\ttdb\**\*.ttpf` (57 pools, 58 GiB) are loose RDS5 texture pools, **not** inside RPFs. rpf9-explorer's `TtpfReader` reads the catalog and detiles them; checked visually (`ttdb_graphics`: scope reticles, clean lines). Names are generated (`texture_N_`); models reference textures by asset key. Some rows are skipped (BCPack or unmapped shards). | `G:\gta6-work\assets\ttpf\\` + `manifest.json` | +| Audio | `audio.rpf` holds raw (not zlib) **AWC** banks: Opus (codec 0x0B) and XMA2 streams. Exported as whole `.awc` files plus `audio_manifest.json` (stream ids, codec, channels, rate, duration). **Done: 7,162 banks, 27 GiB, 1,603,231 streams, about 1,324 hours** (codec 0x0B Opus 1,601,167; 5: 1,818; 2: 227; 0 PCM: 19). Decoding to WAV is a later step. | `G:\gta6-work\assets\audio\awc\` | + +### rpf9dump (bulk export) + +`tools\rpf9dump` is a small CLI over the Core library from https://github.com/breadbbbb/rpf9-explorer (a friend's tool; source at `G:\ref\rpf9-explorer-src`, audited: no keys, no network, no custom build targets). It decrypts nothing. It carves validated resources, as `rpf9_carve.py` does, but with working model and texture decoders. + +``` +dotnet build tools\rpf9dump\rpf9dump.csproj -c Release -o G:\gta6-work\tools\rpf9dump +rpf9dump models|textures G:\gta6-work\assets +rpf9dump ttpf G:\gta6-work\assets\ttpf +rpf9dump audio G:\gta6-work\assets +bash scripts/dump_assets.sh # everything, log in G:\gta6-work\assets\dump.log +``` + +Full-scan indexes are also saved to `%LOCALAPPDATA%\RpfPreview\Indexes`, so the rpf9-explorer GUI opens these archives with complete listings instead of its 16 MiB preview scan. + +## Other prepared pieces + +- `tools\shader_profile.py`: across the corpus there are 551 distinct RDNA mnemonics, and 204 of them cover 99% of + all instructions (`G:\gta6-work\shaders\profile.json`). +- `tools\shader_ir.py`: parses every disassembled instruction into opcode, typed operands (s/v registers and + ranges, NSA register lists, constants, literals, export targets, interpolation attributes), modifiers and + encoding bytes. On 1,000 shaders, 12 of 2.2M operands were left untyped before the last fix. This is the front end + for an RDNA→SPIR-V translator. +- `tools\rtti_scan.py`: MSVC x64 RTTI scanner (class names, bases, vtables). Tested on the bundled DLLs; run it on + the exe first. +- `tools\hashdict.py`: joaat hash→name dictionary (`G:\gta6-work\hashes.json`, 1.9M entries, checked against + `adder` = 0xB779A091). On day one, rerun with `--extra ` so PSO field and type names resolve. Without the exe + only about 1% do. +- Runtime shims: all of `xmem.dll` is shimmed (`XMemAlloc`, `XMemFree`, `XMemVirtualQuery`, + `XMemGetWorkingSetStatistics`). The only imports the bundled DLLs still can't bind are two `d3d12_xs` + root-signature calls. +- PSO metadata is a new variant (`PSIN`, `LSCH` schema, `LENM`, `LSNS`, `LGID`, `LRSC`, `CHKS`, little-endian). + CodeWalker's parser reads the container but not the new schema; dump it once the exe gives the field names. + +## Shader translation (RDNA → SPIR-V) + +`tools\rdna2spirv.py` (needs `spirv-as`/`spirv-val` on PATH: Vulkan SDK, or `spirv-tools` in WSL) translates parsed RDNA +code to SPIR-V assembly, assembles it with `spirv-as`, and validates it with `spirv-val` (Vulkan 1.2). Version 0 +runs one lane per invocation, keeps VGPRs and SGPRs as uint arrays with exact bit patterns, treats EXEC as +all-ones, and covers branch-free vertex and pixel shaders with no memory loads: common float and integer ALU ops +and exports to `gl_Position`, params and MRTs. Unsupported instructions are reported by name, never guessed. +`VS_Passthrough` and `VS_BlurFilter` translate and validate. Coverage across the corpus and the blocking +instructions are in `G:\gta6-work\shaders\spirv_run.log`. The next steps are structured branches (EXEC masks) and +the descriptor/binding model for `s_load`, `s_buffer_load`, `buffer_*` and `image_*`. + +Also handled now: 64-bit scalar moves, EXEC reads (all-ones), whole-quad mode on EXEC, `m0`, SCC, vector and scalar +compares, `v_mul_hi_u32`, `v_cvt_pkrtz_f16_f32` (rounds to nearest instead of toward zero, so it can be off by one +f16 ulp), and pixel interpolation (`v_interp_p1/p2/mov` become fragment inputs at their attribute's location). The +float MODE register (`s_setreg`) is skipped, so Vulkan's default denormal and rounding behaviour applies. + +### GPU tests (RTX 4060 Ti) + +`runtime\test\vk_harness.cpp` (build: `runtime\build\test\build_harness.cmd`, MSVC + the Vulkan 1.4 headers from +Hookshot's CPM cache, loading `vulkan-1.dll` at runtime) draws one triangle with a given VS + FS into an RGBA32F +target and dumps the floats. Test shaders are in `G:\gta6-work\gputest`. + +- **`VS_Passthrough` (translated) is bit-exact.** All 64×64 pixels are written, and `param0.xy` = (u, 1 − v) with max + error **0**, with zw = (0, 1) as exported. This covers the VertexIndex input, integer/float ALU, inline constants, + and position/param exports. +- **400 arithmetic-only translated pixel shaders** (no buffers, descriptors or subgroup ops), driven by a generic + full-screen VS feeding locations 0–15: the driver compiled every pipeline, every draw completed, and every output + was finite. This is a stability check, not a value check (there's no reference for these). +- **Texture path is exact** (`runtime\test\vk_texture_test.cpp`): translated `PS_PassthroughCopy` gives max error + **0.0** over all 64×64 pixels against the expected nearest-sampled 8×8 test texture. That covers push-constant + user data, a heap-relative `s_load_dwordx8` of the T#, the hash-table lookup of the T# and of the shader's + literal S#, bindless sampling, `v_interp`, and the f16 compressed export. **It also caught a translator bug** + that validation can't: compressed exports read the wrong register pair (LLVM prints `v4, v4, v5, v5`), giving + (r,g,r,g). That's fixed. +- After the export fix, 2 of the 400 smoke-test shaders (`PS_ImposterShadow` variants) gave non-finite red values. + The cause was round-to-nearest `pkrtz` overflowing to inf, fixed with exact RTZ. One variant is now fully finite. + The other still has 1 inf and 4 NaN in red, and RTZ can't create those from finite values, so they come from the + shader's own maths on the synthetic test inputs (hardware would pass them through too). That's consistent with + hardware, but unconfirmed without a reference. + +### Translator status and runtime contract + +Full corpus (verified pixel-shader inputs incl. front face, ACO-confirmed 16-bit semantics, `vcc_hi` as an SGPR, +code-embedded data via `s_getpc_b64`, global memory, exact packed-f16 modifiers): **13,925 of 26,503 shaders +translated, all passing `spirv-val`** (Vulkan 1.2). That's **97.1% of all vertex and pixel shaders** (13,925 of +14,337). The remaining ~410 VS/PS: 321 PS with unexplained system inputs (rejected on purpose), 14 `v_med3_f16`, +14 `v_movrels_b32` (relative register indexing), 10 whose embedded data can't be re-anchored, and a few rare +operands. GPU re-test on the final SPIR-V: `VS_Passthrough` exact, texture test within RTZ f16 rounding, 400/400 +arithmetic-only PS finite and deterministic. 319 pixel shaders are deliberately rejected because they read unexplained system-input registers (raw +barycentrics and so on). GPU re-test against the final SPIR-V: `VS_Passthrough` exact, texture test within RTZ f16 +rounding (1.3e-5), and **400/400** arithmetic-only PS finite and identical across two runs. Mesh (9,282), compute (2,689) and geometry (195) shaders aren't +attempted yet. Of the remaining ~580 VS/PS: 288 use 16-bit shifts (`v_lshrrev_b16`, and whether the destination's +high half is kept or cleared needs confirming), 155 contain words LLVM can't decode, and 62 write `vcc_hi`. Output: +`G:\gta6-work\shaders\spirv\` (`.spvasm` + `.spv`), and the log is `G:\gta6-work\shaders\spirv_run.log`. + +How the generated SPIR-V expects the runtime to work: + +| Piece | Contract | +|---|---| +| Execution model | One invocation = one lane. A wave = a subgroup, so cross-lane ops (`ds_swizzle`, `v_permlane*`, `v_readlane`/`v_writelane`, `v_mbcnt`) become subgroup shuffles. **Requires subgroup size == wave size** (wave32 maps directly onto NVIDIA GPUs; wave64 shaders need a 64-wide subgroup or emulation). | +| EXEC | A per-invocation `active` flag. VALU writes and exports are masked by it, scalar ops aren't, and `v_cmpx`, saveexec and EXEC writes update it. A pixel lane still inactive at the end is discarded. | +| Control flow | Any CFG becomes a dispatch loop (`pc` variable + `switch`), which is valid structured SPIR-V. | +| User data | **Push constants, 144 bytes:** dwords 0–31 = initial s0–s31 (the user SGPRs the console driver loads from the root signature: descriptor-table pointers, constants and so on), dwords 32–33 = the 64-bit **heap base**, dwords 34–35 = the **code base**: the Xbox VA where the runtime uploaded this shader's whole FSSM blob. The runtime has to reproduce the console driver's root-signature-to-user-SGPR mapping; that comes from the exe or driver behaviour. | +| Xbox GPU addresses | Shaders build Xbox GPU virtual addresses, and some force the high dword to 0 (descriptor tables in the low 4 GB). Every memory access goes to **heap base + Xbox VA**, so the runtime maps the console's GPU address window into one host buffer-device-address allocation. | +| Code-embedded data | 155 VS/PS had "undecodable words". They're **constant tables inside the code range** (float values like 0x3EF7…, plus zeros), read through `s_getpc_b64` + `s_add_u32`/`s_addc_u32` + `s_load` (147 of 155). The translator re-anchors each instruction to its true FSSM offset by matching encodings, translates only code reachable from entry (a branch into data is rejected), and turns `s_getpc_b64` into code base + next-instruction offset. **The runtime uploads each shader's FSSM blob into the heap and passes that VA as the code base.** 132 of 155 now translate. | +| Global memory | `global_load/store_dword*`: address = (64-bit SGPR base + zero-extended 32-bit VGPR offset, or a 64-bit VGPR address) + signed 12-bit offset, translated through the heap base. Inactive lanes don't access memory, and loads merge their previous values with OpPhi. | +| Literal samplers | Some shaders build their S# from immediates (for example `0x92, 0xC00000, 0x14500000, 0`). The runtime registers those in the descriptor hash table too, by scanning the translated shaders' constant S# values, not only S#s the game binds. | +| Scalar/buffer memory | `s_load*`, `s_buffer_load*`, `buffer_load*` and `buffer_store*` use buffer device addresses (`PhysicalStorageBuffer64`). The base comes from the 64-bit SGPR pointer or the V# (dword0 \| dword1[15:0] << 32), and the stride is V# dword1[29:16]. **The runtime must put the game's GPU heap in buffer-device-addressable memory at the same addresses the game writes into descriptors** (or remap them). `num_records` bounds checks aren't modelled. | +| Typed buffer loads | The format is V# word3[18:12] (GFX10_FORMAT, from Mesa's `gfx10-rsrc.json`, saved as `tools\gfx10_formats.json`). Supported: f32 ×1–4, u32 ×1/2/4, f16 ×1/2/4, unorm8 ×1/2/4, snorm8 ×4, uint8 ×4, unorm16 ×1/2/4, snorm16 ×2/4, 10-10-10-2 and 2-10-10-10 unorm. Others give 0. DST_SEL swizzle is applied. | +| Images and samplers | Bindless. Set 0: binding 0 = 2D sampled images, 1 = samplers, 2 = descriptor hash table (storage buffer), 3 = 2D-array images (**cube textures are bound here as 6-layer 2D-array views**: the shader already selected the face with `v_cube*`), 4 = r32ui storage images, 5 = 1D, 6 = 3D. | +| Descriptor hash table | `uint mask; entries[mask+1] of 10 uints: key[0..7], index, pad`. Key = the raw T# (8 dwords), or the S# (4 dwords) followed by four 0xFFFFFFFF. Hash = FNV-1a over the 8 key dwords, probed linearly for 8 slots. A miss gives index 0, so **the runtime keeps a fallback texture and sampler at index 0**. As the game binds descriptors, the runtime inserts each T#/S# with the bindless index of the Vulkan image view or sampler it created for it. | +| Vertex fetch | `s_swappc_b64` at the start of a VS calls a driver-generated fetch program that isn't in the blob. It's replaced by Vulkan vertex inputs: each `ISG1` input-signature element (DXBC container) becomes an input at **location = its D3D input register**, typed by its component type, and is written to **v(4 + 4·register + component)**. That rule was checked over all 788 fetch-calling shaders: in 783 every read-before-write VGPR is predicted by it (715 exact). The other 5 are rejected. **The runtime must bind vertex buffers by the game's D3D12 input layout, location = input register.** | +| PS system inputs | v0–v1 = barycentrics (consumed by `v_interp`, which becomes attribute inputs). **v2.. = the `SV_Position` components the shader reads, packed in order**. Verified on 2,531 of 3,000 PS: the VGPRs they read before writing equal exactly the position components their input signature reads. Filled from `FragCoord`: xy/z directly, and **w directly too**, because AMD's position-w register holds 1/w (Mesa lowers `load_frag_coord_w_rcp` straight to `frag_pos[3]`, `ac_nir_lower_intrinsics_to_args.c`), the same as Vulkan's `FragCoord.w`. **Front face** follows the used position components when the signature declares `SV_IsFrontFace`, as ±1.0 (Mesa: `load_front_face` = `front_face > 0`). Only enabled inputs are packed, in hardware order (Mesa `radv_shader_args.c`: barycentric pairs, POS_X/Y/Z/W, FRONT_FACE, ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT). That explains the earlier "unverified" shaders: 102 read pos.xy + front face, and 76 read pos.x/y/w + front face. A PS that reads an unexplained register *inside* the system-input range (for example a raw barycentric) is **rejected** (about 21 of 3,000). Reads past the last hardware input are values undefined on some path, so zero stands in for them. All register arrays start at zero, so translated shaders are deterministic. | +| Inputs and outputs | VS: `v0` = `VertexIndex` (**unverified**: if the console runs vertex shaders as NGG, the input VGPR layout differs). `exp pos0` → `Position`, `exp paramN` → location N. PS: `v_interp_*` attribute N → input location N. `exp mrtN` → location N, `exp mrtz` x → `FragDepth`. | +| 16-bit results | From Mesa ACO (`aco_ir.cpp`: `instr_is_16bit`, `can_use_opsel`) for GFX10: **f16 VOP1/VOP2 ops** (`v_add/sub/mul/max/min_f16`, `v_fmac_f16`, `v_cvt_f16_f32`, f16 unary) and **opsel-capable VOP3 ops** (`v_fma_f16`, `_e64` forms of the 16-bit integer ops) are **partial writes that keep the high half**. The **VOP2 (`_e32`) 16-bit integer ops** (`v_lshrrev_b16`…) define the whole register, so the high half is modelled as zero. An op_sel destination bit writes the high half. The translator used to clear the high half on f16 ops; that's fixed. | +| Known approximations | `v_cvt_pkrtz_f16_f32` is now **exact round-toward-zero** (finite overflow gives ±65504, not inf). The GPU smoke test caught the old round-to-nearest version producing inf in `PS_ImposterShadow`. The other f16 packs (`v_cvt_f16_f32`, d16 results, mix ops) round to nearest, which matches the default mode. The MODE register (`s_setreg`) is ignored, so denormal and rounding behaviour is Vulkan's default. Whole-quad mode on non-EXEC masks is the identity. `v_mul_legacy_f32` is a plain multiply, while `v_mad_legacy_f32` keeps the 0×anything = 0 rule. | +| Mesh/compute input registers (measured, not yet usable) | Read-before-write analysis over all compute and mesh shaders. **Compute:** v0 (880), v0–v1 (614), v0–v2 (50), consistent with AMD's local thread ID x/y/z in v0/v1/v2. Scalar inputs centre on a pointer at s[4:5] and arithmetic registers s6/s7 (likely workgroup IDs). **Mesh:** every one of 2,969 reads exactly **v5**, plus s3 (always arithmetic), a pointer pair s[16:17], and s19–s23. Cross-check against FSSM header 0x13C as the group width: 82 match, 151 don't, 1,447 have no simple multiply. So **0x13C isn't the group width, and the workgroup-ID registers are unconfirmed**. The real thread-group sizes are in each container's `PSV0` part (runtime info v2, NumThreadsX/Y/Z: 32×1×1 for 1,253, 8×8×1 for 416, …). Against those, the first SGPR multiply matches NumThreadsX in only 82 shaders, with 150 others, so the first multiply isn't a reliable workgroup-ID marker. The matching register varies by shader (s6/s10/s7/s9…), which fits AMD's layout of workgroup IDs right after a **per-shader user-SGPR count**. That count comes from the console's register setup (exe/driver), so compute stays untranslated until it's known. Mesh and compute stay untranslated until the exe's dispatch setup, or a correctly decoded register block in the FSSM metadata, confirms them. | +| Not yet translated | Mesh (9,282), geometry and compute stages; `s_swappc_b64` (call to the vertex-fetch program); `tbuffer_*`; a few rare ops. Mesh, geometry and compute, plus the vertex-fetch call, need the per-stage hardware register setup (user-SGPR layout, system-value VGPRs). Get that from the FSSM metadata or the exe before translating them. | + +**Main blocker (before descriptor support was added): descriptor loads.** On a 3,000-shader sample, `s_load_dwordx4`/`x8` stop over half of them. Shaders +load texture, buffer and sampler descriptors through user-data SGPR pointers, and how the game's root signatures +map onto those SGPRs is set up by game code. Read that mapping from the exe (root signature creation plus the +FSSM user-data metadata) before building the binding layer; guessing it would give silent rendering bugs. The +other blockers are mesh shaders (9,282, which need a mesh-stage entry model), the vertex-fetch subroutine call +(`s_swappc_b64`), geometry and compute stages, and compressed exports. + +## Day one, in order + +1. `scripts\first_look.ps1 -Exe ...` checks the exe is plain, lists the imports to shim, and does a dry run. +2. Find the RPF9 table-of-contents key and decryption in the exe, then add a table reader to `rpf9_carve.py`. Carved + blobs then get real names and types, and the remaining unread data shows what it is. +3. Find the texture and mesh resource structures in the exe (their loaders give exact field layouts), which turns + carved blobs into named textures and meshes. +4. Shader translation: RDNA2 disassembly to SPIR-V, starting with the most-used shaders. + +## Disassembling shaders + +The AMDGPU disassembler needs LLVM 21+ (`llvm-mc`; e.g. the `llvm-21` package in WSL, `/usr/lib/llvm-21/bin/llvm-mc`). The +official Windows LLVM build has no AMDGPU target. Run it inside WSL: + +``` +LLVM_MC=/usr/lib/llvm-21/bin/llvm-mc python3 -I /tools/shader_disasm.py /shaders/fssm +``` + +Code starts at the u32 at FSSM offset 0xC0, plus 0x28, and ends at the last `s_endpgm`. Use `--mcpu gfx1013`. On +300 random shaders it decoded 284 cleanly (134 invalid words in total), against 201 clean and 6,560 invalid for +gfx1030 and 283 clean for gfx1010–1012. + +## Baseline already recorded + +- `reports/manifest.json`: SHA-256 of all 108 files in `Documents\GTA6` (208.5 GiB). Run + `python -I tools\manifest.py verify ` to check a copy against it. +- `reports/rpf_probe.json`: all 22 archives are **RPF9**. Five have tables that look packed or encrypted (`levels`, + `movies`, `core_bvh4`, `navmeshes`, `data`). +- `reports/pe/`: the 16 bundled DLLs are plain x86-64 PE with no encrypted sections. Through the loader they need + only `xmem.dll` (`XMemAlloc` and `XMemFree` are shimmed; `XMemVirtualQuery` and `XMemGetWorkingSetStatistics` aren't + yet) and two `d3d12_xs.dll` root-signature calls. Every other import resolves on desktop Windows. diff --git a/game/xbox-1.0.2.1.json b/game/xbox-1.0.2.1.json new file mode 100644 index 000000000..028aa25e4 --- /dev/null +++ b/game/xbox-1.0.2.1.json @@ -0,0 +1,439 @@ +{ + "title": "Xbox Series package", + "version": "1.0.2.1", + "files": { + "Bink2Scarlett.dll": { + "size": 255488, + "sha256": "9eaf045d004cd7d6a8382aaff0c6ea23a29fec4ef8bfacd726b54f5bc26fafd0" + }, + "Catalog000.bin": { + "size": 815104, + "sha256": "4afbdbe22aad2bc338a5ba1ffe83cccb96e072eb4e92f6a5dd90b49b2e227c59" + }, + "MicrosoftGame.Config": { + "size": 2542, + "sha256": "d0d5e4777460045916046619cd0fd433aa251d4a74f4d91e83987588f907f80c" + }, + "Update.alignmentchunk": { + "size": 1, + "sha256": "5feceb66ffc86f38d952786c6d696c79c2dbc239dd4e91b46729d73a27fb57e9" + }, + "XCurl.dll": { + "size": 199152, + "sha256": "d11ba4e4a07f42f8d80c48553c5c2588ab4114ecdbe023305f5f8fa8262131f8" + }, + "XboxBvhBuilder.dll": { + "size": 884224, + "sha256": "99f803ac22c01ef329dddb1d40be67238d2a812d01e8d040b3cb5135bc23707e" + }, + "amd_fidelityfx_loader_xbox.dll": { + "size": 13312, + "sha256": "431bdd2e26c0c8214fd7601140eb9fe6d8a249f5000539453a9a9b6a0b7c0ee8" + }, + "amd_fidelityfx_upscaler_xbox.dll": { + "size": 786432, + "sha256": "faff02f294a7e9149ce079dffe3dedbcabe99b1f180ab14222aa8689e00a75fa" + }, + "anim.rpf": { + "size": 4407626384, + "sha256": "7f5c53162ab66a8915dfc95ddf22aad9055635b6ddd3cffc40f431e24ea1c189" + }, + "appdata0.rpf": { + "size": 8880, + "sha256": "d9d4d2ddcd23e73a8862fbb5d5b53ca259e454f90319910d88f3a5c8da212535" + }, + "appxmanifest.xml": { + "size": 3394, + "sha256": "662a05d05f8449b94b2ffc052f2a9ad2c090b3708d5a274fc9b2db0e14b03a34" + }, + "audio.rpf": { + "size": 28543454672, + "sha256": "883581135f2fb0ba7ec5068da6f89363951400d4d3f9c0b99c06ac7eef24134a" + }, + "common.rpf": { + "size": 6642192, + "sha256": "31dc6aa5394dd8cd3c83b90c9661f37325f22851cc6d5d7150e11041c7618ced" + }, + "concrt140.dll": { + "size": 298992, + "sha256": "554168b99726cbe982b542ec97c493f48483b20a4ea4e54e102ba3a0d098e75f" + }, + "data.rpf": { + "size": 481544304, + "sha256": "e5af629ef458bb7be55cae3dc890c69613c8028060ac765d54a4ccd73991640c" + }, + "data/ttdb/graphics/ttdb_graphics.ttpf": { + "size": 34411776, + "sha256": "0b23f3f4ea9f63d8bb8abd835fb15b584fbc63a2b2f9cdbb6f675d78db16cb7e" + }, + "data/ttdb/interiors/ttdb_interiors_0_3.ttpf": { + "size": 883202048, + "sha256": "5f109fcd493235e271c0106c9da92a27de1e48d809a18a5d2af8c2183bb23516" + }, + "data/ttdb/interiors/ttdb_interiors_1_3.ttpf": { + "size": 898113536, + "sha256": "3598c14ad6b1df887b21b3f8685be2ab8a060264ca3f8db3829d3f4bc0863b8c" + }, + "data/ttdb/interiors/ttdb_interiors_2_3.ttpf": { + "size": 881431552, + "sha256": "b8616380028bb8fe027c46c0a225793e5814a6639afb9d90dede4acabfde2004" + }, + "data/ttdb/interiors/ttdb_interiors_3_3.ttpf": { + "size": 900875008, + "sha256": "d284d983873bc726b68c36ea85d0fd8c3a7c8ae58be049c981218eed00f614ba" + }, + "data/ttdb/lighting/lighting.ttpf": { + "size": 151531776, + "sha256": "87727791b5026439d8f0b3bcceeae02b074fda9670270cac9bc248ffac16e3ca" + }, + "data/ttdb/maps/ttdb_maps_0_7.ttpf": { + "size": 1765679616, + "sha256": "d672e99c248b943c3a3acb694eb16fe6236d3d9d04c86451cf68259ca68d4409" + }, + "data/ttdb/maps/ttdb_maps_1_7.ttpf": { + "size": 1746187776, + "sha256": "df9f32bb42168ac0abf9e44573d837186107d5d3dc926a0cf597750f6cae112f" + }, + "data/ttdb/maps/ttdb_maps_2_7.ttpf": { + "size": 1818806528, + "sha256": "2ca6dd82a842990b6a2c3440936b443808a6d98bf6b540048978591bdc23b7c0" + }, + "data/ttdb/maps/ttdb_maps_3_7.ttpf": { + "size": 1787349760, + "sha256": "f90577103ef7986ba7ae4d190782bf73378d4e0e5be6f9664ea3fc3f3088255e" + }, + "data/ttdb/maps/ttdb_maps_4_7.ttpf": { + "size": 1791670784, + "sha256": "ccc48a1662467b78423d3f83220e3bc4f4ae36c32a873d09344d48c1faab9760" + }, + "data/ttdb/maps/ttdb_maps_5_7.ttpf": { + "size": 1840029440, + "sha256": "16229da15fb88d8a76dceadfb0cacb852144878960a7584b3345051d351c9c3c" + }, + "data/ttdb/maps/ttdb_maps_6_7.ttpf": { + "size": 1745923072, + "sha256": "b852c332f5474a3631e13c708f2233b27668065d8a9ee751155efb98e27a3a6e" + }, + "data/ttdb/maps/ttdb_maps_7_7.ttpf": { + "size": 1755748608, + "sha256": "27be3cf33f23326b9dec29692788e8ee75f73ce0050c23307600dbd067964de5" + }, + "data/ttdb/peds/decorations_0_3.ttpf": { + "size": 494316032, + "sha256": "31246c91ea208b2b58809cb5bd82c5e0c044c88ae4198831aab727584675b0f3" + }, + "data/ttdb/peds/decorations_1_3.ttpf": { + "size": 510001152, + "sha256": "baf71941408cf65f9aed0335a737783f62ca1899f863322d89f9a990bcb7f0e3" + }, + "data/ttdb/peds/decorations_2_3.ttpf": { + "size": 491507456, + "sha256": "5c622d5a00f0f84125edc3c84061a4f97d57dd695ec6a286657f7135445cb3c6" + }, + "data/ttdb/peds/decorations_3_3.ttpf": { + "size": 497391360, + "sha256": "aeabd38813f8af5582aad43e84b0a0262ef187d03115483764433ad5b1f848df" + }, + "data/ttdb/peds/peds_loose.ttpf": { + "size": 135676160, + "sha256": "0c7ad96cf458be86c38f1cbdbc067f93ea444eda4a88c72b16d0ecdfcc91e311" + }, + "data/ttdb/peds/ttdb_peds_0_3.ttpf": { + "size": 953116416, + "sha256": "73891cde5598e26e4dda53971d45d91c749e3d54dc2afe93bee9885344ea3dde" + }, + "data/ttdb/peds/ttdb_peds_1_3.ttpf": { + "size": 965556736, + "sha256": "b37dcb845e9143409879de2b7fddf82d38a736d07041082648a7f718f9583faa" + }, + "data/ttdb/peds/ttdb_peds_2_3.ttpf": { + "size": 937699072, + "sha256": "8ebca98d174266f5cf18cb50cc3c5ca5e7ecdbc84604f352bb6ff4fb05f9c2ef" + }, + "data/ttdb/peds/ttdb_peds_3_3.ttpf": { + "size": 957291520, + "sha256": "3f9d03d67978f5454a927266c7f866f20c700bb753a83f5cbc7182a398618eeb" + }, + "data/ttdb/props/octa_imposters.ttpf": { + "size": 983620352, + "sha256": "03a7d6dd60da98871228b1ec06a93d4a00387143dd20f123c0408087385f203c" + }, + "data/ttdb/props/ttdb_props_0_3.ttpf": { + "size": 1304458240, + "sha256": "8e620456a4a296faf8be5632a8d929df590be1efeee7d5ce34059726a0ac65f4" + }, + "data/ttdb/props/ttdb_props_1_3.ttpf": { + "size": 1256908800, + "sha256": "3cba53b0fa123e39597e8331fe4b432294fcf32baebb94f9db47a52f1b46ac4d" + }, + "data/ttdb/props/ttdb_props_2_3.ttpf": { + "size": 1239990784, + "sha256": "6999079496270431dfb6df46a6406f721cfb4331e418bab6c6facb962f4d288f" + }, + "data/ttdb/props/ttdb_props_3_3.ttpf": { + "size": 1328911616, + "sha256": "7633d784b6e77258f8d576777633fc72eebbff004c1640ee27d53773ced83639" + }, + "data/ttdb/terrain/ttdb_terrain_0_7.ttpf": { + "size": 2775084288, + "sha256": "6de6efac9d3d7b862548b3d0aee352b086c2e01ebcf8cda8ede617afb495187f" + }, + "data/ttdb/terrain/ttdb_terrain_1_7.ttpf": { + "size": 2739444480, + "sha256": "e1f5139ed75d6781754737cf277981aa5c3afea5d2d06e7dcd57a36fb4ff505c" + }, + "data/ttdb/terrain/ttdb_terrain_2_7.ttpf": { + "size": 2780145920, + "sha256": "40b157a43413359fafef667aab1a6ec53d2c078c50fe24292678c3d1b33ede9a" + }, + "data/ttdb/terrain/ttdb_terrain_3_7.ttpf": { + "size": 2718679808, + "sha256": "5799083008834d706e6b3606b647abfbfa6068574c96f3803ad957013bb4eb1a" + }, + "data/ttdb/terrain/ttdb_terrain_4_7.ttpf": { + "size": 2741339648, + "sha256": "18c6ce167de25a1cea110401da7c2ce679106f7766df0b7af2668cba7a1ab25b" + }, + "data/ttdb/terrain/ttdb_terrain_5_7.ttpf": { + "size": 2674379008, + "sha256": "60bcba6a7f3a658cec51232cc48098cf86a6e54d37f21ab9401b2a76e2a6ea53" + }, + "data/ttdb/terrain/ttdb_terrain_6_7.ttpf": { + "size": 2688808960, + "sha256": "553961eff42fb8deb7cf7330d303e843b88ab29c87ab30b85cdd0c0501d1fc14" + }, + "data/ttdb/terrain/ttdb_terrain_7_7.ttpf": { + "size": 2828296704, + "sha256": "dc887908067d49d9bd05c40029f7248a6bbf76fe79f34abea0199dd6a7edf244" + }, + "data/ttdb/terrain/ttdb_terrain_image_based_0_1.ttpf": { + "size": 1946070528, + "sha256": "30a3020d15d4d159b06aa9fd31508a534c79d9990de215bf20d2572ec2713995" + }, + "data/ttdb/terrain/ttdb_terrain_image_based_1_1.ttpf": { + "size": 1890978048, + "sha256": "1e0afca572034adebc2899e733546fb12a620acd10b32a4c21fbcc5926abed69" + }, + "data/ttdb/ui/platform.ttpf": { + "size": 222976, + "sha256": "3e64d01e062ed55d290aaf3a7b9694d562a8591cf461e638dd135d388d4b5e5c" + }, + "data/ttdb/ui/ttdb_ui.ttpf": { + "size": 845115648, + "sha256": "dc983ed7f6b78d1693fa5757f17c03bafb790e851594fdf4d412579b61d867f6" + }, + "data/ttdb/vehicles/ttdb_vehicles.ttpf": { + "size": 195418624, + "sha256": "02add8dc1c4f8f485ef8abc5b4480b746e24fa4a546eb488ec37ff1b4d3c4e34" + }, + "data/ttdb/vehicles/ttdb_vehicles_loose_0_1.ttpf": { + "size": 838474496, + "sha256": "0e90a8dbda5e32fb6c47a4ecabf821451a59abd349755c8030c380d4a9e9f834" + }, + "data/ttdb/vehicles/ttdb_vehicles_loose_1_1.ttpf": { + "size": 890206208, + "sha256": "a3aae83237fedd1f7c32e8ab2adc8bf9a87d8b019a2242c5181547714b00f8cc" + }, + "data/ttdb/vfx/ttdb_vfx.ttpf": { + "size": 238897664, + "sha256": "7625184c4e9c899f3b708b88d61fa2e12b836db63640385cecd750cb30c8f26e" + }, + "data/ttdb/weapons/ttdb_weapons.ttpf": { + "size": 1421518080, + "sha256": "41c4fc92143fc26e44dcb4ca93142b914f9ac1188f9b53cbf8db27c6a97b6d4c" + }, + "data/ttdb/weapons/weapon_liveries.ttpf": { + "size": 739758848, + "sha256": "7cae5a1ce890e7a4d452387f4dcb4ebde8e3e3b905409d7ed33903203a348ba5" + }, + "gameos.xvd": { + "size": 348069888, + "sha256": "d02ff50ae9164e540ce55b60b2f128b5c78bab6bace6e5eee46e584438d9af36" + }, + "layout_3202719e-b4b4-421c-9f8f-70d1c4a7d60b_xs.xml": { + "size": 13698, + "sha256": "2eeb9b05047f83c8bc82fcee7646e7d675266f4545f940593a6b56e92358663d" + }, + "levels.rpf": { + "size": 76155065056, + "sha256": "9d1b1bd70659a32dc6259fc890dbc3e167dd3f9253f41000a3c9aa7c17539c47" + }, + "libHttpClient.GDK.dll": { + "size": 975856, + "sha256": "14d97b3d071e0ce461e758dbcf1511941ae5c0bdd6e32ed33cb87aaae0414d3a" + }, + "microsoft_gameconfig.bin": { + "size": 8192, + "sha256": "27735d6ca90ff4eb8f432e3d3e701fd85f75303f1adade2cdbc4bef165159a0a" + }, + "movies.rpf": { + "size": 8832481776, + "sha256": "a0647c0325333dd42b25b00d85ee9b3915a55ce99127b97ef00662ef4866cba4" + }, + "msvcp140.dll": { + "size": 565232, + "sha256": "6036fdb3ee3a5813ef0b17462219ebcee5f06b46ef738bacde07aa797e6d2b75" + }, + "msvcp140_1.dll": { + "size": 26104, + "sha256": "c56b530e0894d9c4d11b12d389786fef40463dbd81d4438b8414f909d6226211" + }, + "msvcp140_2.dll": { + "size": 187888, + "sha256": "276813083c55c079120e0db49898088bb0c8d1c912ed59ec0d00fedf56a694a8" + }, + "msvcp140_atomic_wait.dll": { + "size": 57312, + "sha256": "b7f879662095f71dc08efcbc0d24ac3c0ff2dde8d475f92f5c5646a39bf8f2c3" + }, + "msvcp140_codecvt_ids.dll": { + "size": 22008, + "sha256": "89cf5b07b98709277e8511d9a402ce72279e8df3ae24a8dd641ab0265c799a0c" + }, + "navmeshes.rpf": { + "size": 6707512496, + "sha256": "30f8d4ebc0fd1d9f786cd50627a7bd3bd537288707606a18815a6440da8e3109" + }, + "pack/core_bvh4/core_bvh4.rpf": { + "size": 8297921520, + "sha256": "a316887568569127e4ebb0053de11b9cefa4305ce6199fb85b5acc62bfa2ff5a" + }, + "pack/core_licenses/core_licenses_data.rpf": { + "size": 13536, + "sha256": "6ca2574aa699b4583f110c6b3e3ae605a6a0ca8c36d65769f76e3beb58e93751" + }, + "pack/core_restofworld/core_restofworld.rpf": { + "size": 1295760752, + "sha256": "a28e53eee58e0b7541bee699ca0136d7a8402934984fe1d12d573905a24da5f0" + }, + "pack/core_restofworld/data/ttdb/peds/ttdb_peds.ttpf": { + "size": 24529408, + "sha256": "b3514f9b1fe258141f7b5d840fc753e980a2af59749a1f8d4de0867e93cf5c97" + }, + "pack/core_restofworld/data/ttdb/props/ttdb_props.ttpf": { + "size": 35286784, + "sha256": "eaf45801f0a0b0407ff41d5e840a27f9cfce144e1a4798ca293003a484e2c0ee" + }, + "pack/core_restofworld/data/ttdb/textures_loose.ttpf": { + "size": 21081856, + "sha256": "81da4d1904dd038ea59fb5d7b851e2a15b1906a5ff3017f1bd15dd617d46c3dc" + }, + "pack/core_restofworld/data/ttdb/ui/ttdb_ui.ttpf": { + "size": 4729600, + "sha256": "9df804569a50dfe7d1a0f8ef71fa9a117a370616159489e9028f5acfd5118d66" + }, + "pack/core_restofworld/data/ttdb/vfx/ttdb_vfx.ttpf": { + "size": 3129600, + "sha256": "6434287056329e60a4ca7ae26fabf91dc3ccf3b738130033400fb88ab42da8cf" + }, + "pack/core_restofworld001/core_restofworld001.rpf": { + "size": 791984, + "sha256": "6eb47c010bb6bf69f50d69675e50415d345468f3a1193fdf7ab4e54a4d7d6c56" + }, + "pack/core_restofworld001/data/ttdb/ui/ttdb_ui.ttpf": { + "size": 38656, + "sha256": "9bfb5f4b85be2f6d1d93b2ed83df94a2021346448816b61fd9c08d7d05b8a43c" + }, + "pack/shared_minigame000/data/ttdb/maps/ttdb_maps.ttpf": { + "size": 193522176, + "sha256": "873a8c7634eacaa062a1bc48888908f3e2d3196159b9fa39e83eb6cfc18dbb06" + }, + "pack/shared_minigame000/data/ttdb/terrain/ttdb_terrain_image_based.ttpf": { + "size": 1427712, + "sha256": "0354565963b8472bf2f606dc1a4089c14f45cb5ecd416984f5e4212009eb7e74" + }, + "pack/shared_minigame000/shared_minigame000.rpf": { + "size": 810581008, + "sha256": "badd8f4b3a4e65bc492d2933d0c82239653467317c606c483e616979a5ec5967" + }, + "pack/shared_minigame000_bvh4/shared_minigame000_bvh4.rpf": { + "size": 61987040, + "sha256": "9525a81d18b922ba5859643883d466f08442f779b7c92a7eaaefde3766292a96" + }, + "pack/story000/data/ttdb/maps/ttdb_maps.ttpf": { + "size": 697378560, + "sha256": "8e362c1f39383d6ff97eeffbf963602e9ed2e2b97b707e54a3884fe7c8dd408d" + }, + "pack/story000/data/ttdb/terrain/ttdb_terrain_image_based.ttpf": { + "size": 222333440, + "sha256": "4794cbff80790c7a0b3d2959f3831b53e90c5b56b9bdb61814f98f29a4e4157f" + }, + "pack/story000/data/ttdb/vfx/ttdb_vfx.ttpf": { + "size": 3357184, + "sha256": "79612738f51faa724cb6d30ad5465419f3038d4b3498115ec1306b0ad7d71f1c" + }, + "pack/story000/story000.rpf": { + "size": 20022508672, + "sha256": "4d7f87158a1be7e5e4f15ef195ddaa804be94d2ecaafaa9172150f7b6b8abf94" + }, + "pack/story000/story000_script.rpf": { + "size": 78023728, + "sha256": "fb30232fd94ccfdb2b85bb8deae860b7c449348f2b4a8c38d9395de1ad00b8fb" + }, + "pack/story000_bvh4/story000_bvh4.rpf": { + "size": 5632, + "sha256": "b9f86219f835c769ca86274f933ab35423af45dad33f130d5c5e4727450ffd24" + }, + "pack/story000_restofworld/story000_restofworld.rpf": { + "size": 198354992, + "sha256": "f972251e4369d634419e33d2b2b6196f310e70af521dd0c9f00025d0c1c0e6ca" + }, + "packs.rpf": { + "size": 4798213264, + "sha256": "ed6c55c60112704f7e551cfbb2446f7f069bfd7caa1c257bc427595cf7434651" + }, + "resources.pri": { + "size": 1152, + "sha256": "1a91d1a8de2fa9bffafcfbdb0f4c1a8a02294647eec71385baa70b8d1e4a165e" + }, + "script.rpf": { + "size": 4358960, + "sha256": "c4d7e75f867c8527eee75135cd400e22f7c770c159c6bc2c3f80ec0f6e6a8dbb" + }, + "shaders.rpf": { + "size": 411695600, + "sha256": "0bc1634594e51ca8e7ef5f2bc6f5b32b081ce779ac094d686de08ecb75dc24a8" + }, + "textures.rpf": { + "size": 192585024, + "sha256": "dc1957ec85d89b1b55cd1fdc5c3997f48d1e0bff9020ec2842120ab34e71c83e" + }, + "vccorlib140.dll": { + "size": 336888, + "sha256": "79ee6fa49aa2c6f0dfbc1279273fd619e1a9285995ff53a8bc183000c8895b91" + }, + "vcomp140.dll": { + "size": 72176, + "sha256": "91e249c0f66f827bcacd0be4931b1cec3e4907cc05ea0a5bcd83696c70908963" + }, + "vcruntime140.dll": { + "size": 97776, + "sha256": "9385104cc3e031dbbcb63f156134a0f6afff455e0ff6887f5a9e1c5f7e2706b0" + }, + "vcruntime140_1.dll": { + "size": 37848, + "sha256": "0dbd6859f825ab8acab1fa25b6bd1a091d35ca2dbe3185c1187192f2d2ac8154" + }, + "xbs_logo_150.png": { + "size": 54536, + "sha256": "21a652895663671afef4e947cc8ced47ca66ec00f4b27059c17bef6965a506ca" + }, + "xbs_logo_44.png": { + "size": 7102, + "sha256": "072c08f82513a8f6a392dd8be371378333191a4aabbc5b6a1fedfe7dbc850916" + }, + "xbs_logo_480.png": { + "size": 404663, + "sha256": "b5ac80b8d43bc23c9de0593fad04a7eafa5106ed405eeb5db40ad9b37642d535" + }, + "xbs_logo_store.png": { + "size": 29356, + "sha256": "006999d45faf184bf669610f364b9551874d0fdb154e36ce34e622a300d025da" + }, + "xbs_splash.png": { + "size": 2507194, + "sha256": "0fa110ecac0a5fac8294921132cc8322440bdf93e74e723eb63eae0143d58e58" + } + }, + "expected_exe": "game_scarlett_master.exe" +} \ No newline at end of file diff --git a/make_game.py b/make_game.py new file mode 100644 index 000000000..4aa73b2ca --- /dev/null +++ b/make_game.py @@ -0,0 +1,233 @@ +"""Build the PC port from your own copy of the game. + + python -I make_game.py --game "D:\\path\\to\\your\\package" --out "D:\\Games\\Leonida" + python -I make_game.py --game "..." --check # only check the copy, build nothing + python -I make_game.py --game "..." --out "..." --stages shaders,assets + +The game folder is your own Xbox Series package, version 1.0.2.1, with its files already readable on disk +(see game/xbox-1.0.2.1.json for the file list). This script never decrypts, downloads or works around anything: +it reads plain files and writes everything it makes under --out. Never share what it makes. + +Stages, in order (each skips work that is already done, so a stopped build continues where it left off): + check file names and sizes against game/.json (add --full-check for SHA-256, slow) + shaders carve shaders.rpf, unpack the native RDNA2 code, disassemble, translate to SPIR-V + assets models (OBJ), texture dictionaries and texture pools (DDS), audio banks (AWC) + runtime build the loader (needs the game's executable to run, not to build) +""" +import argparse +import json +import os +import shutil +import subprocess +import sys +import time + +ROOT = os.path.dirname(os.path.abspath(__file__)) +TOOLS = os.path.join(ROOT, "tools") +VERSIONS = os.path.join(ROOT, "game") +STAGES = ["check", "shaders", "assets", "runtime"] +# Archives scanned for models and texture dictionaries, small to large. +MODEL_ARCHIVES = [ + "common.rpf", "textures.rpf", "data.rpf", + "pack/story000_restofworld/story000_restofworld.rpf", "pack/shared_minigame000/shared_minigame000.rpf", + "pack/core_restofworld/core_restofworld.rpf", "pack/core_restofworld001/core_restofworld001.rpf", + "packs.rpf", "pack/story000/story000.rpf", "levels.rpf", +] + + +def log(msg: str) -> None: + print(f"{time.strftime('%H:%M:%S')} {msg}", flush=True) + + +def fail(msg: str) -> "None": + print(f"\nERROR: {msg}", file=sys.stderr) + sys.exit(1) + + +def below_normal() -> None: + """Keep the PC usable while a long build runs.""" + if os.name == "nt": + import ctypes + k32 = ctypes.windll.kernel32 + k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00004000) + + +def run(args: list, **kw) -> None: + log(" " + " ".join(os.path.basename(str(a)) if i == 0 else str(a) for i, a in enumerate(args))) + r = subprocess.run([str(a) for a in args], **kw) + if r.returncode != 0: + fail(f"{os.path.basename(str(args[0]))} exited with {r.returncode}") + + +def py(tool: str, *args) -> None: + run([sys.executable, "-I", os.path.join(TOOLS, tool), *args]) + + +def need(exe: str, hint: str) -> str: + path = shutil.which(exe) + if not path: + fail(f"'{exe}' was not found on PATH. {hint}") + return path + + +# ---------------------------------------------------------------- check +def load_version(game: str) -> dict: + for name in sorted(os.listdir(VERSIONS)): + if not name.endswith(".json"): + continue + with open(os.path.join(VERSIONS, name), encoding="utf-8") as f: + v = json.load(f) + probe = "MicrosoftGame.Config" + p = os.path.join(game, probe) + if probe in v["files"] and os.path.isfile(p) and os.path.getsize(p) == v["files"][probe]["size"]: + return v + fail("This doesn't look like a supported version of the game. Supported: " + + ", ".join(n[:-5] for n in os.listdir(VERSIONS) if n.endswith(".json"))) + + +def check(game: str, full: bool) -> dict: + if not os.path.isdir(game): + fail(f"Game folder not found: {game}") + v = load_version(game) + log(f"check: {v['title']} {v['version']}, {len(v['files'])} files") + bad = 0 + for rel, info in v["files"].items(): + p = os.path.join(game, rel) + if not os.path.isfile(p): + print(f" missing {rel}"); bad += 1 + elif os.path.getsize(p) != info["size"]: + print(f" wrong size {rel}"); bad += 1 + if bad: + fail(f"{bad} file(s) missing or different. Use a complete, unmodified copy of version {v['version']}.") + if full: + py("manifest.py", "verify", game, "--manifest", os.path.join(VERSIONS, f"xbox-{v['version']}.json")) + exe = os.path.join(game, v["expected_exe"]) + log(f"check: all files present{' and hashes match' if full else ''}. " + + ("Executable found." if os.path.isfile(exe) else + f"{v['expected_exe']} is not in the folder: the runtime stage can be built but not run.")) + return v + + +# ---------------------------------------------------------------- shaders +def shaders(game: str, work: str, jobs: int) -> None: + src = os.path.join(game, "shaders.rpf") + sh = os.path.join(work, "shaders") + dxbc = os.path.join(sh, "dxbc") + if not os.path.isfile(os.path.join(dxbc, "index.json")): + log("shaders: carving shaders.rpf") + py("shader_carve.py", src, dxbc) + if not os.path.isdir(os.path.join(dxbc, "fssm")): + log("shaders: unpacking native code") + py("fssm_unpack.py", dxbc) + disasm = os.path.join(sh, "disasm") + if not os.path.isdir(disasm) or len(os.listdir(disasm)) < 1000: + need(os.environ.get("LLVM_MC", "llvm-mc"), + "Install LLVM 21 or newer with the AMDGPU target, or set LLVM_MC to llvm-mc's full path.") + log("shaders: disassembling (gfx1013)") + py("shader_disasm.py", os.path.join(dxbc, "fssm"), "--out", disasm, "--mcpu", "gfx1013", "--jobs", jobs) + spirv = os.path.join(sh, "spirv") + if not os.path.isdir(spirv) or len(os.listdir(spirv)) < 1000: + need("spirv-as", "Install the Vulkan SDK (it includes spirv-as and spirv-val) and reopen the terminal.") + need("spirv-val", "Install the Vulkan SDK and reopen the terminal.") + log("shaders: translating RDNA2 to SPIR-V (the longest step)") + py("rdna2spirv.py", disasm, "--out", spirv) + log("shaders: done") + + +# ---------------------------------------------------------------- assets +def rpf9dump(work: str) -> str: + exe = os.path.join(work, "tools", "rpf9dump", "rpf9dump.exe" if os.name == "nt" else "rpf9dump") + if not os.path.isfile(exe): + core = os.path.join(ROOT, "third_party", "rpf9-explorer", "Core") + if not os.path.isdir(core): + fail("third_party/rpf9-explorer is empty. Run: git submodule update --init") + need("dotnet", "Install the .NET 8 SDK.") + log("assets: building rpf9dump") + run(["dotnet", "build", os.path.join(TOOLS, "rpf9dump", "rpf9dump.csproj"), "-c", "Release", + "-o", os.path.dirname(exe), "--nologo", "-v", "q"]) + return exe + + +def assets(game: str, work: str) -> None: + exe = rpf9dump(work) + out = os.path.join(work, "assets") + for rel in MODEL_ARCHIVES: + src = os.path.join(game, rel) + name = os.path.splitext(os.path.basename(rel))[0] + for mode in ("models", "textures"): + if os.path.isfile(os.path.join(out, name, mode, "manifest.json")): + continue + log(f"assets: {mode} from {rel}") + run([exe, mode, src, out]) + pools = [] + for root, _, files in os.walk(os.path.join(game, "data", "ttdb")): + pools += [os.path.join(root, f) for f in files if f.lower().endswith(".ttpf")] + for p in sorted(pools, key=os.path.getsize): + name = os.path.splitext(os.path.basename(p))[0] + if os.path.isfile(os.path.join(out, "ttpf", name, "manifest.json")): + continue + log(f"assets: texture pool {os.path.relpath(p, game)}") + run([exe, "ttpf", p, os.path.join(out, "ttpf")]) + if not os.path.isfile(os.path.join(out, "audio", "audio_manifest.json")): + log("assets: audio banks") + run([exe, "audio", os.path.join(game, "audio.rpf"), out]) + log("assets: done") + + +# ---------------------------------------------------------------- runtime +def runtime(game: str, out: str, v: dict) -> None: + if os.name != "nt": + fail("The runtime builds on Windows only for now.") + log("runtime: building") + run(["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", + os.path.join(ROOT, "scripts", "build_runtime.ps1")]) + built = os.path.join(ROOT, "runtime", "build", "gta6rt.exe") + os.makedirs(out, exist_ok=True) + shutil.copy2(built, os.path.join(out, "gta6rt.exe")) + with open(os.path.join(out, "game_path.txt"), "w", encoding="utf-8") as f: + f.write(os.path.abspath(game)) + if not os.path.isfile(os.path.join(game, v["expected_exe"])): + log(f"runtime: built, but {v['expected_exe']} is missing from your copy, so there is nothing to run yet.") + else: + log(f"runtime: done. Start {os.path.join(out, 'gta6rt.exe')}") + + +def main() -> int: + ap = argparse.ArgumentParser(description="Build the PC port from your own copy of the game.") + ap.add_argument("--game", required=True, help="your package folder") + ap.add_argument("--out", help="folder for the finished port (and its work files unless --work is given)") + ap.add_argument("--work", help="folder for intermediate files (hundreds of GB; default /work)") + ap.add_argument("--stages", default=",".join(STAGES), help="comma list from: " + ",".join(STAGES)) + ap.add_argument("--check", action="store_true", help="only check the game files") + ap.add_argument("--full-check", action="store_true", help="also compare SHA-256 of every file (slow)") + ap.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 2) // 2)) + a = ap.parse_args() + below_normal() + game = os.path.abspath(a.game) + v = check(game, a.full_check) + if a.check: + return 0 + if not a.out: + fail("--out is required to build.") + out = os.path.abspath(a.out) + work = os.path.abspath(a.work or os.path.join(out, "work")) + if os.path.commonpath([out, game]) == game or os.path.commonpath([work, game]) == game: + fail("--out and --work must be outside the game folder.") + stages = [s.strip() for s in a.stages.split(",") if s.strip()] + for s in stages: + if s not in STAGES: + fail(f"unknown stage '{s}'") + os.makedirs(work, exist_ok=True) + t0 = time.time() + if "shaders" in stages: + shaders(game, work, a.jobs) + if "assets" in stages: + assets(game, work) + if "runtime" in stages: + runtime(game, out, v) + log(f"finished in {(time.time() - t0) / 60:.0f} min") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt new file mode 100644 index 000000000..c450621b4 --- /dev/null +++ b/runtime/CMakeLists.txt @@ -0,0 +1,22 @@ +cmake_minimum_required(VERSION 3.24) +project(gta6rt LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +if(NOT CMAKE_SIZEOF_VOID_P EQUAL 8) + message(FATAL_ERROR "gta6rt must be built for x64 (run from an x64 Native Tools prompt or vcvars64.bat)") +endif() + +add_executable(gta6rt + src/main.cpp + src/pe_loader.cpp + shims/registry.cpp + shims/xmem.cpp + shims/d3d12_xs.cpp +) +target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) +target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8) +# Static shim tables register themselves at startup; keep the linker from dropping their objects. +target_link_options(gta6rt PRIVATE /OPT:NOREF) +target_link_libraries(gta6rt PRIVATE psapi) diff --git a/runtime/shims/d3d12_xs.cpp b/runtime/shims/d3d12_xs.cpp new file mode 100644 index 000000000..ab1e2d88d --- /dev/null +++ b/runtime/shims/d3d12_xs.cpp @@ -0,0 +1,39 @@ +// d3d12_xs.dll: the Xbox Series build of D3D12. Only the free functions the bundled DLLs import are here. +// +// ASSUMPTION (verify against the exe's call sites): root-signature descriptions and blobs have the same layout as +// desktop D3D12, so these forward to the PC d3d12.dll. Device/command-list interfaces are a separate, much larger +// job (Xbox-only methods, placement and ESRAM-era extensions) and aren't shimmed here. +#include + +#include + +#include "shims.h" + +namespace { + +FARPROC host(const char* name) { + static HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + FARPROC p = d3d12 ? GetProcAddress(d3d12, name) : nullptr; + if (!p) std::fprintf(stderr, "[rt] d3d12_xs: host d3d12.dll has no %s\n", name); + return p; +} + +using SerializeFn = HRESULT(WINAPI*)(const void*, void**, void**); +using DeserializerFn = HRESULT(WINAPI*)(const void*, SIZE_T, const GUID*, void**); + +HRESULT WINAPI D3D12SerializeVersionedRootSignature(const void* desc, void** blob, void** error) { + static auto fn = reinterpret_cast(host("D3D12SerializeVersionedRootSignature")); + return fn ? fn(desc, blob, error) : E_NOTIMPL; +} + +HRESULT WINAPI D3D12CreateRootSignatureDeserializer(const void* data, SIZE_T size, const GUID* iid, void** out) { + static auto fn = reinterpret_cast(host("D3D12CreateRootSignatureDeserializer")); + return fn ? fn(data, size, iid, out) : E_NOTIMPL; +} + +} // namespace + +SHIM_TABLE(d3d12_xs, + {"d3d12_xs.dll", "D3D12SerializeVersionedRootSignature", reinterpret_cast(&D3D12SerializeVersionedRootSignature)}, + {"d3d12_xs.dll", "D3D12CreateRootSignatureDeserializer", reinterpret_cast(&D3D12CreateRootSignatureDeserializer)}, +); diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp new file mode 100644 index 000000000..e10ccb051 --- /dev/null +++ b/runtime/shims/registry.cpp @@ -0,0 +1,81 @@ +#include + +#include +#include +#include +#include +#include +#include + +#include "shims.h" + +namespace rt::shims { +namespace { + +std::map& table() { + static std::map t; // "dll!name" + return t; +} + +std::mutex g_called_mutex; +std::set g_called; + +// Called by the thunks with the import's "dll!name" string. +extern "C" uint64_t rt_unimplemented(const char* what) { + std::lock_guard lock(g_called_mutex); + if (g_called.insert(what).second) std::fprintf(stderr, "[rt] unimplemented: %s\n", what); + return 0; +} + +// Thunk layout (x86-64): +// 48 B9 mov rcx, what +// 48 B8 mov rax, rt_unimplemented +// 0F 57 C0 xorps xmm0, xmm0 +// FF E0 jmp rax (tail call: returns straight to the game's caller) +constexpr size_t kThunkSize = 32; + +uint8_t* g_pool = nullptr; +size_t g_pool_used = 0, g_pool_size = 0; +std::mutex g_pool_mutex; + +} // namespace + +Table::Table(const Entry* entries, size_t count) { + for (size_t i = 0; i < count; ++i) table()[std::string(entries[i].dll) + "!" + entries[i].name] = entries[i].fn; +} + +void* find(const std::string& dll_lower, const std::string& name) { + auto it = table().find(dll_lower + "!" + name); + return it == table().end() ? nullptr : it->second; +} + +void* make_unimplemented_thunk(const std::string& dll, const std::string& name) { + std::lock_guard lock(g_pool_mutex); + if (!g_pool || g_pool_used + kThunkSize > g_pool_size) { + g_pool_size = 1 << 20; + g_pool = static_cast(VirtualAlloc(nullptr, g_pool_size, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE)); + g_pool_used = 0; + if (!g_pool) return nullptr; + } + const char* what = _strdup((dll + "!" + name).c_str()); // lives for the process + uint8_t* t = g_pool + g_pool_used; + g_pool_used += kThunkSize; + uint64_t a = reinterpret_cast(what), f = reinterpret_cast(&rt_unimplemented); + uint8_t code[kThunkSize] = {0x48, 0xB9}; + std::memcpy(code + 2, &a, 8); + code[10] = 0x48; code[11] = 0xB8; + std::memcpy(code + 12, &f, 8); + code[20] = 0x0F; code[21] = 0x57; code[22] = 0xC0; + code[23] = 0xFF; code[24] = 0xE0; + std::memset(code + 25, 0xCC, kThunkSize - 25); + std::memcpy(t, code, kThunkSize); + FlushInstructionCache(GetCurrentProcess(), t, kThunkSize); + return t; +} + +void report_called_unimplemented() { + std::lock_guard lock(g_called_mutex); + for (auto& s : g_called) std::fprintf(stderr, " called: %s\n", s.c_str()); +} + +} // namespace rt::shims diff --git a/runtime/shims/shims.h b/runtime/shims/shims.h new file mode 100644 index 000000000..5654d17a6 --- /dev/null +++ b/runtime/shims/shims.h @@ -0,0 +1,31 @@ +// Shim registry: reimplementations of console-only imports. +// Add a DLL by writing a shims/.cpp with a SHIM_TABLE and listing it in CMakeLists.txt. +#pragma once +#include + +namespace rt::shims { + +struct Entry { + const char* dll; // lower-case, with .dll + const char* name; // export name, or "#ordinal" + void* fn; +}; + +// Registers a static table at startup. +struct Table { + Table(const Entry* entries, size_t count); +}; + +void* find(const std::string& dll_lower, const std::string& name); + +// Makes a small thunk that logs "dll!name" once and returns 0 (in rax and xmm0). +void* make_unimplemented_thunk(const std::string& dll, const std::string& name); + +// Prints every unimplemented import that has been called. +void report_called_unimplemented(); + +} // namespace rt::shims + +#define SHIM_TABLE(id, ...) \ + static const ::rt::shims::Entry id##_entries[] = {__VA_ARGS__}; \ + static ::rt::shims::Table id##_table(id##_entries, sizeof(id##_entries) / sizeof(id##_entries[0])) diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp new file mode 100644 index 000000000..d8fd76568 --- /dev/null +++ b/runtime/shims/xmem.cpp @@ -0,0 +1,48 @@ +// xmem.dll: the GDK's tracked allocator. Mapped onto the CRT's aligned heap and VirtualQuery. +// +// TODO: decode the XALLOC_ATTRIBUTES alignment and memory-type fields. Until that's checked against real call +// sites, every block is 64-byte aligned, which covers cache-line and SIMD alignment. +#include +#include +#include + +#include +#include + +#include "shims.h" + +namespace { + +constexpr size_t kAlign = 64; + +void* __stdcall XMemAlloc(size_t size, uint64_t /*attributes*/) { return _aligned_malloc(size ? size : 1, kAlign); } + +void __stdcall XMemFree(void* p, uint64_t /*attributes*/) { _aligned_free(p); } + +// Same shape as VirtualQuery on the console (MEMORY_BASIC_INFORMATION out, returns bytes written). +SIZE_T __stdcall XMemVirtualQuery(const void* address, MEMORY_BASIC_INFORMATION* info, SIZE_T length) { + return VirtualQuery(address, info, length); +} + +// GDK: HRESULT XMemGetWorkingSetStatistics(XMEM_WORKING_SET_STATISTICS*). The struct's exact layout isn't known +// yet, so it's zeroed up to a conservative size and filled with the process's working set in the first field. +// Revisit once the exe's call sites show which fields are read. +long __stdcall XMemGetWorkingSetStatistics(void* stats) { + if (!stats) return static_cast(0x80070057); // E_INVALIDARG + std::memset(stats, 0, 32); + PROCESS_MEMORY_COUNTERS pmc{}; + if (GetProcessMemoryInfo(GetCurrentProcess(), &pmc, sizeof(pmc))) { + uint64_t ws = pmc.WorkingSetSize; + std::memcpy(stats, &ws, sizeof(ws)); + } + return 0; // S_OK +} + +} // namespace + +SHIM_TABLE(xmem, + {"xmem.dll", "XMemAlloc", reinterpret_cast(&XMemAlloc)}, + {"xmem.dll", "XMemFree", reinterpret_cast(&XMemFree)}, + {"xmem.dll", "XMemVirtualQuery", reinterpret_cast(&XMemVirtualQuery)}, + {"xmem.dll", "XMemGetWorkingSetStatistics", reinterpret_cast(&XMemGetWorkingSetStatistics)}, +); diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp new file mode 100644 index 000000000..e69906c14 --- /dev/null +++ b/runtime/src/main.cpp @@ -0,0 +1,72 @@ +// gta6rt: native runtime for the Xbox Series build. +// +// gta6rt --dry-run [--game-dir DIR] +// Maps the image and its bundled modules, applies relocations, binds every import and prints a report. +// No code from the image runs. +#include + +#include +#include +#include + +#include "pe_loader.h" + +namespace { + +const char* binding_name(rt::Binding b) { + switch (b) { + case rt::Binding::Shim: return "shim"; + case rt::Binding::Host: return "host"; + case rt::Binding::Module: return "module"; + default: return "UNIMPLEMENTED"; + } +} + +int usage() { + std::fprintf(stderr, "usage: gta6rt --dry-run [--game-dir DIR]\n"); + return 2; +} + +} // namespace + +int wmain(int argc, wchar_t** argv) { + std::filesystem::path image, game_dir; + bool dry_run = false; + for (int i = 1; i < argc; ++i) { + std::wstring a = argv[i]; + if (a == L"--dry-run") dry_run = true; + else if (a == L"--game-dir" && i + 1 < argc) game_dir = argv[++i]; + else if (image.empty()) image = a; + else return usage(); + } + if (image.empty()) return usage(); + if (!dry_run) { + std::fprintf(stderr, "Only --dry-run exists so far: running game code needs the shims listed by it first.\n"); + return 2; + } + if (game_dir.empty()) game_dir = image.parent_path(); + + try { + rt::Loader loader(game_dir); + loader.load(image); + int unimplemented = 0; + for (auto* m : loader.modules()) { + std::map counts; + for (auto& r : m->imports) counts[r.binding]++; + std::printf("%-36s base=%p%s size=%u entry=+%#x shim=%d host=%d module=%d unimplemented=%d\n", + m->name.c_str(), m->base, m->relocated ? " (relocated)" : "", m->size, m->entry_rva, + counts[rt::Binding::Shim], counts[rt::Binding::Host], counts[rt::Binding::Module], + counts[rt::Binding::Unimplemented]); + for (auto& r : m->imports) + if (r.binding == rt::Binding::Unimplemented || r.binding == rt::Binding::Shim) { + std::printf(" %-13s %s!%s\n", binding_name(r.binding), r.dll.c_str(), r.name.c_str()); + unimplemented += r.binding == rt::Binding::Unimplemented; + } + } + std::printf("%zu module(s) mapped, %d unimplemented import(s)\n", loader.modules().size(), unimplemented); + return 0; + } catch (const std::exception& e) { + std::fprintf(stderr, "error: %s\n", e.what()); + return 1; + } +} diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp new file mode 100644 index 000000000..f27060b94 --- /dev/null +++ b/runtime/src/pe_loader.cpp @@ -0,0 +1,207 @@ +#include "pe_loader.h" + +#include + +#include +#include +#include +#include + +#include "../shims/shims.h" + +namespace rt { + +std::string lower(std::string s) { + std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return (char)std::tolower(c); }); + return s; +} + +namespace { + +std::vector read_file(const std::filesystem::path& p) { + std::ifstream f(p, std::ios::binary); + if (!f) throw std::runtime_error("cannot open " + p.string()); + return {std::istreambuf_iterator(f), {}}; +} + +template +T* at(uint8_t* base, uint32_t rva) { return reinterpret_cast(base + rva); } + +// The Xbox builds of the MSVC runtime import the same CRT the desktop does, so the host's own copies are used. +bool prefer_host_copy(const std::string& dll) { + static const char* names[] = {"vcruntime140.dll", "vcruntime140_1.dll", "msvcp140.dll", "msvcp140_1.dll", + "msvcp140_2.dll", "msvcp140_atomic_wait.dll", "msvcp140_codecvt_ids.dll", + "concrt140.dll", "vccorlib140.dll", "vcomp140.dll"}; + for (auto* n : names) + if (dll == n) return true; + return false; +} + +} // namespace + +Loader::~Loader() { + for (auto* m : order_) { + if (m->base) VirtualFree(m->base, 0, MEM_RELEASE); + delete m; + } +} + +Module& Loader::load(const std::filesystem::path& image) { + std::string key = lower(image.filename().string()); + if (auto it = by_name_.find(key); it != by_name_.end()) return *it->second; + Module& m = map_image(image); + bind_imports(m); + protect_sections(m); + return m; +} + +Module& Loader::map_image(const std::filesystem::path& path) { + auto file = read_file(path); + auto* dos = reinterpret_cast(file.data()); + if (file.size() < sizeof(IMAGE_DOS_HEADER) || dos->e_magic != IMAGE_DOS_SIGNATURE) + throw std::runtime_error(path.string() + ": not an MZ image"); + auto* nt = reinterpret_cast(file.data() + dos->e_lfanew); + if (nt->Signature != IMAGE_NT_SIGNATURE || nt->FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64) + throw std::runtime_error(path.string() + ": not an x86-64 PE"); + auto& oh = nt->OptionalHeader; + + auto* m = new Module; + m->name = path.filename().string(); + m->path = path; + m->preferred_base = oh.ImageBase; + m->size = oh.SizeOfImage; + m->entry_rva = oh.AddressOfEntryPoint; + by_name_[lower(m->name)] = m; + order_.push_back(m); + + m->base = static_cast( + VirtualAlloc(reinterpret_cast(oh.ImageBase), oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!m->base) { + auto& relocs = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; + if (!relocs.Size) + throw std::runtime_error(m->name + ": preferred base is taken and the image has no relocations"); + m->base = static_cast(VirtualAlloc(nullptr, oh.SizeOfImage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + if (!m->base) throw std::runtime_error(m->name + ": VirtualAlloc failed"); + } + + std::memcpy(m->base, file.data(), oh.SizeOfHeaders); + auto* sec = IMAGE_FIRST_SECTION(nt); + for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { + uint32_t n = std::min(sec->SizeOfRawData, sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData); + if (n && sec->PointerToRawData + n <= file.size()) + std::memcpy(m->base + sec->VirtualAddress, file.data() + sec->PointerToRawData, n); + } + + int64_t delta = reinterpret_cast(m->base) - static_cast(oh.ImageBase); + if (delta) { + m->relocated = true; + auto& dir = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC]; + auto* block = at(m->base, dir.VirtualAddress); + auto* end = reinterpret_cast(block) + dir.Size; + while (reinterpret_cast(block) < end && block->SizeOfBlock) { + auto* entries = reinterpret_cast(block + 1); + size_t count = (block->SizeOfBlock - sizeof(IMAGE_BASE_RELOCATION)) / 2; + for (size_t i = 0; i < count; ++i) { + uint16_t type = entries[i] >> 12, off = entries[i] & 0xFFF; + if (type == IMAGE_REL_BASED_DIR64) + *at(m->base, block->VirtualAddress + off) += delta; + else if (type != IMAGE_REL_BASED_ABSOLUTE) + throw std::runtime_error(m->name + ": unsupported relocation type " + std::to_string(type)); + } + block = reinterpret_cast(reinterpret_cast(block) + block->SizeOfBlock); + } + } + parse_exports(*m); + return *m; +} + +void Loader::parse_exports(Module& m) { + auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); + auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; + if (!dir.Size) return; + auto* ed = at(m.base, dir.VirtualAddress); + auto* funcs = at(m.base, ed->AddressOfFunctions); + auto* names = at(m.base, ed->AddressOfNames); + auto* ords = at(m.base, ed->AddressOfNameOrdinals); + for (uint32_t i = 0; i < ed->NumberOfFunctions; ++i) + if (funcs[i]) m.exports["#" + std::to_string(ed->Base + i)] = m.base + funcs[i]; + for (uint32_t i = 0; i < ed->NumberOfNames; ++i) + m.exports[at(m.base, names[i])] = m.base + funcs[ords[i]]; + // Forwarded exports (RVA inside the export directory) aren't followed yet; none of the bundled DLLs use them. +} + +void* Loader::resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal) { + std::string key = lower(dll); + std::string sym = by_ordinal ? "#" + std::to_string(ordinal) : name; + + if (void* p = shims::find(key, sym)) { + m.imports.push_back({dll, sym, Binding::Shim}); + return p; + } + // Bundled game module (an Xbox build that ships beside the game)? + auto bundled = game_dir_ / dll; + if (!prefer_host_copy(key) && std::filesystem::exists(bundled)) { + Module& dep = load(bundled); + if (auto it = dep.exports.find(sym); it != dep.exports.end()) { + m.imports.push_back({dll, sym, Binding::Module}); + return it->second; + } + } + // Host Windows: system DLLs and API sets. LOAD_LIBRARY_SEARCH_SYSTEM32 keeps the game folder out of the search. + if (HMODULE h = LoadLibraryExA(dll.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)) { + FARPROC p = GetProcAddress(h, by_ordinal ? MAKEINTRESOURCEA(ordinal) : name.c_str()); + if (p) { + m.imports.push_back({dll, sym, Binding::Host}); + return reinterpret_cast(p); + } + } + m.imports.push_back({dll, sym, Binding::Unimplemented}); + return shims::make_unimplemented_thunk(dll, sym); +} + +void Loader::bind_imports(Module& m) { + auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); + + auto bind_thunks = [&](const std::string& dll, IMAGE_THUNK_DATA64* lookup, IMAGE_THUNK_DATA64* iat) { + for (; lookup->u1.AddressOfData; ++lookup, ++iat) { + bool by_ord = IMAGE_SNAP_BY_ORDINAL64(lookup->u1.Ordinal); + uint16_t ord = by_ord ? (uint16_t)IMAGE_ORDINAL64(lookup->u1.Ordinal) : 0; + std::string name = by_ord ? "" : at(m.base, (uint32_t)lookup->u1.AddressOfData)->Name; + iat->u1.Function = reinterpret_cast(resolve(m, dll, name, ord, by_ord)); + } + }; + + auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + if (dir.Size) { + for (auto* d = at(m.base, dir.VirtualAddress); d->Name; ++d) { + std::string dll = at(m.base, d->Name); + uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk; + bind_thunks(dll, at(m.base, lookup), at(m.base, d->FirstThunk)); + } + } + // Delay imports are bound eagerly: simpler, and the full import surface shows up in --dry-run. + auto& ddir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT]; + if (ddir.Size) { + for (auto* d = at(m.base, ddir.VirtualAddress); d->DllNameRVA; ++d) { + std::string dll = at(m.base, d->DllNameRVA); + bind_thunks(dll, at(m.base, d->ImportNameTableRVA), + at(m.base, d->ImportAddressTableRVA)); + } + } +} + +void Loader::protect_sections(Module& m) { + auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); + DWORD old; + VirtualProtect(m.base, nt->OptionalHeader.SizeOfHeaders, PAGE_READONLY, &old); + auto* sec = IMAGE_FIRST_SECTION(nt); + for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { + bool x = sec->Characteristics & IMAGE_SCN_MEM_EXECUTE, w = sec->Characteristics & IMAGE_SCN_MEM_WRITE; + DWORD prot = x ? (w ? PAGE_EXECUTE_READWRITE : PAGE_EXECUTE_READ) : (w ? PAGE_READWRITE : PAGE_READONLY); + SIZE_T size = sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData; + if (size) VirtualProtect(m.base + sec->VirtualAddress, size, prot, &old); + } + FlushInstructionCache(GetCurrentProcess(), m.base, m.size); +} + +} // namespace rt diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h new file mode 100644 index 000000000..5d3218f81 --- /dev/null +++ b/runtime/src/pe_loader.h @@ -0,0 +1,57 @@ +// Native PE mapper for Xbox Series (x86-64) images. +// Maps an image, applies relocations and binds every import through the shim registry. +// It never runs code from the image: DllMain, TLS callbacks and the entry point are left to the caller. +#pragma once +#include +#include +#include +#include +#include + +namespace rt { + +enum class Binding { Shim, Host, Module, Unimplemented }; + +struct ImportRecord { + std::string dll; + std::string name; // "#123" for ordinals + Binding binding; +}; + +struct Module { + std::string name; + std::filesystem::path path; + uint8_t* base = nullptr; + uint64_t preferred_base = 0; + uint32_t size = 0; + uint32_t entry_rva = 0; + bool relocated = false; + std::vector imports; + std::map exports; // by name, plus "#ordinal" +}; + +class Loader { +public: + explicit Loader(std::filesystem::path game_dir) : game_dir_(std::move(game_dir)) {} + ~Loader(); + + // Loads an image and (recursively) the bundled modules it imports. Throws std::runtime_error on failure. + Module& load(const std::filesystem::path& image); + + const std::vector& modules() const { return order_; } + +private: + Module& map_image(const std::filesystem::path& path); + void bind_imports(Module& m); + void* resolve(Module& m, const std::string& dll, const std::string& name, uint16_t ordinal, bool by_ordinal); + void parse_exports(Module& m); + void protect_sections(Module& m); + + std::filesystem::path game_dir_; + std::map by_name_; // lower-case file name + std::vector order_; +}; + +std::string lower(std::string s); + +} // namespace rt diff --git a/runtime/test/vk_harness.cpp b/runtime/test/vk_harness.cpp new file mode 100644 index 000000000..c08dacb42 --- /dev/null +++ b/runtime/test/vk_harness.cpp @@ -0,0 +1,194 @@ +// Headless Vulkan harness: draws one triangle (3 vertices, no vertex buffers) with a given VS + FS into a +// W x H RGBA32F image and writes the raw floats to a file. Used to check translated shaders on the real GPU. +// +// vk_harness [width height] +// +// Vulkan is loaded at runtime from vulkan-1.dll (no SDK import library needed). +#define VK_NO_PROTOTYPES +#include +#include + +#include +#include +#include +#include + +static PFN_vkGetInstanceProcAddr gipa; +#define LOADI(name) auto name = reinterpret_cast(gipa(inst, #name)) +#define CHECK(x) \ + do { \ + VkResult r_ = (x); \ + if (r_ != VK_SUCCESS) { \ + std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, r_, __LINE__); \ + return 1; \ + } \ + } while (0) + +static std::vector read_spv(const char* path) { + std::ifstream f(path, std::ios::binary); + std::vector b((std::istreambuf_iterator(f)), {}); + std::vector w(b.size() / 4); + std::memcpy(w.data(), b.data(), w.size() * 4); + return w; +} + +int main(int argc, char** argv) { + if (argc < 4) { + std::fprintf(stderr, "usage: vk_harness vs.spv fs.spv out.raw [w h]\n"); + return 2; + } + uint32_t W = argc > 5 ? atoi(argv[4]) : 64, H = argc > 5 ? atoi(argv[5]) : 64; + HMODULE lib = LoadLibraryA("vulkan-1.dll"); + if (!lib) { std::fprintf(stderr, "no vulkan-1.dll\n"); return 1; } + gipa = reinterpret_cast(GetProcAddress(lib, "vkGetInstanceProcAddr")); + VkInstance inst = VK_NULL_HANDLE; + LOADI(vkCreateInstance); + VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; + app.apiVersion = VK_API_VERSION_1_2; + VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; + ici.pApplicationInfo = &app; + CHECK(vkCreateInstance(&ici, nullptr, &inst)); + LOADI(vkEnumeratePhysicalDevices); LOADI(vkGetPhysicalDeviceProperties); + LOADI(vkGetPhysicalDeviceQueueFamilyProperties); LOADI(vkGetPhysicalDeviceMemoryProperties); + LOADI(vkCreateDevice); LOADI(vkGetDeviceProcAddr); + uint32_t n = 0; + vkEnumeratePhysicalDevices(inst, &n, nullptr); + std::vector pds(n); + vkEnumeratePhysicalDevices(inst, &n, pds.data()); + VkPhysicalDevice pd = VK_NULL_HANDLE; + for (auto d : pds) { // prefer the discrete GPU + VkPhysicalDeviceProperties p; vkGetPhysicalDeviceProperties(d, &p); + if (p.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU || !pd) pd = d; + } + VkPhysicalDeviceProperties props; vkGetPhysicalDeviceProperties(pd, &props); + std::fprintf(stderr, "device: %s\n", props.deviceName); + uint32_t qn = 0; + vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); + std::vector qf(qn); + vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data()); + uint32_t qi = 0; + while (qi < qn && !(qf[qi].queueFlags & VK_QUEUE_GRAPHICS_BIT)) qi++; + float prio = 1; + VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; + qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio; + VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; + dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; + VkDevice dev; + CHECK(vkCreateDevice(pd, &dci, nullptr, &dev)); +#define LOADD(name) auto name = reinterpret_cast(vkGetDeviceProcAddr(dev, #name)) + LOADD(vkGetDeviceQueue); LOADD(vkCreateImage); LOADD(vkGetImageMemoryRequirements); LOADD(vkAllocateMemory); + LOADD(vkBindImageMemory); LOADD(vkCreateImageView); LOADD(vkCreateRenderPass); LOADD(vkCreateFramebuffer); + LOADD(vkCreateShaderModule); LOADD(vkCreatePipelineLayout); LOADD(vkCreateGraphicsPipelines); + LOADD(vkCreateCommandPool); LOADD(vkAllocateCommandBuffers); LOADD(vkBeginCommandBuffer); + LOADD(vkCmdBeginRenderPass); LOADD(vkCmdBindPipeline); LOADD(vkCmdDraw); LOADD(vkCmdEndRenderPass); + LOADD(vkCmdCopyImageToBuffer); LOADD(vkEndCommandBuffer); LOADD(vkQueueSubmit); LOADD(vkQueueWaitIdle); + LOADD(vkCreateBuffer); LOADD(vkGetBufferMemoryRequirements); LOADD(vkBindBufferMemory); LOADD(vkMapMemory); + VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q); + VkPhysicalDeviceMemoryProperties mp; vkGetPhysicalDeviceMemoryProperties(pd, &mp); + auto memtype = [&](uint32_t bits, VkMemoryPropertyFlags want) { + for (uint32_t i = 0; i < mp.memoryTypeCount; i++) + if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i; + return 0u; + }; + const VkFormat fmt = VK_FORMAT_R32G32B32A32_SFLOAT; + VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + ii.imageType = VK_IMAGE_TYPE_2D; ii.format = fmt; ii.extent = {W, H, 1}; ii.mipLevels = 1; ii.arrayLayers = 1; + ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; + ii.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + VkImage img; CHECK(vkCreateImage(dev, &ii, nullptr, &img)); + VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, img, &mr); + VkMemoryAllocateInfo mai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + mai.allocationSize = mr.size; mai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VkDeviceMemory imem; CHECK(vkAllocateMemory(dev, &mai, nullptr, &imem)); + CHECK(vkBindImageMemory(dev, img, imem, 0)); + VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + vi.image = img; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = fmt; + vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + VkImageView view; CHECK(vkCreateImageView(dev, &vi, nullptr, &view)); + VkAttachmentDescription ad{}; + ad.format = fmt; ad.samples = VK_SAMPLE_COUNT_1_BIT; ad.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; + ad.storeOp = VK_ATTACHMENT_STORE_OP_STORE; ad.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; + ad.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; ad.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; + ad.finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + VkAttachmentReference ar{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; + VkSubpassDescription sd{}; sd.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; + sd.colorAttachmentCount = 1; sd.pColorAttachments = &ar; + VkRenderPassCreateInfo rpi{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; + rpi.attachmentCount = 1; rpi.pAttachments = &ad; rpi.subpassCount = 1; rpi.pSubpasses = &sd; + VkRenderPass rp; CHECK(vkCreateRenderPass(dev, &rpi, nullptr, &rp)); + VkFramebufferCreateInfo fbi{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; + fbi.renderPass = rp; fbi.attachmentCount = 1; fbi.pAttachments = &view; fbi.width = W; fbi.height = H; fbi.layers = 1; + VkFramebuffer fb; CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &fb)); + auto module = [&](const char* p, VkShaderModule* m) { + auto code = read_spv(p); + VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + smi.codeSize = code.size() * 4; smi.pCode = code.data(); + return vkCreateShaderModule(dev, &smi, nullptr, m); + }; + VkShaderModule vs, fs; + CHECK(module(argv[1], &vs)); CHECK(module(argv[2], &fs)); + VkPipelineShaderStageCreateInfo stages[2]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, + {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}}; + stages[0].stage = VK_SHADER_STAGE_VERTEX_BIT; stages[0].module = vs; stages[0].pName = "main"; + stages[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; stages[1].module = fs; stages[1].pName = "main"; + VkPipelineVertexInputStateCreateInfo vin{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; + VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; + ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + VkViewport vp{0, 0, float(W), float(H), 0, 1}; VkRect2D sc{{0, 0}, {W, H}}; + VkPipelineViewportStateCreateInfo vps{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; + vps.viewportCount = 1; vps.pViewports = &vp; vps.scissorCount = 1; vps.pScissors = ≻ + VkPipelineRasterizationStateCreateInfo rs{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; + rs.cullMode = VK_CULL_MODE_NONE; rs.lineWidth = 1; + VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; + ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + VkPipelineColorBlendAttachmentState cba{}; cba.colorWriteMask = 0xF; + VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; + cb.attachmentCount = 1; cb.pAttachments = &cba; + // Translated shaders declare a 136-byte push-constant block (user SGPRs + heap base); zeros here. + VkPushConstantRange pcr{VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, 144}; + VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; + VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); + VkGraphicsPipelineCreateInfo gpi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; + gpi.stageCount = 2; gpi.pStages = stages; gpi.pVertexInputState = &vin; gpi.pInputAssemblyState = &ia; + gpi.pViewportState = &vps; gpi.pRasterizationState = &rs; gpi.pMultisampleState = &ms; gpi.pColorBlendState = &cb; + gpi.layout = pl; gpi.renderPass = rp; + VkPipeline pipe; CHECK(vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipe)); + VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + bi.size = VkDeviceSize(W) * H * 16; bi.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; + VkBuffer buf; CHECK(vkCreateBuffer(dev, &bi, nullptr, &buf)); + VkMemoryRequirements br; vkGetBufferMemoryRequirements(dev, buf, &br); + VkMemoryAllocateInfo bai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; + bai.allocationSize = br.size; + bai.memoryTypeIndex = memtype(br.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + VkDeviceMemory bmem; CHECK(vkAllocateMemory(dev, &bai, nullptr, &bmem)); + CHECK(vkBindBufferMemory(dev, buf, bmem, 0)); + VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cpi.queueFamilyIndex = qi; + VkCommandPool pool; CHECK(vkCreateCommandPool(dev, &cpi, nullptr, &pool)); + VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; + cai.commandPool = pool; cai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cai.commandBufferCount = 1; + VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); + VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; + CHECK(vkBeginCommandBuffer(cmd, &cbi)); + VkClearValue clear{}; clear.color.float32[0] = -1; clear.color.float32[1] = -1; // marks untouched pixels + clear.color.float32[2] = -1; clear.color.float32[3] = -1; + VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; + rbi.renderPass = rp; rbi.framebuffer = fb; rbi.renderArea = sc; rbi.clearValueCount = 1; rbi.pClearValues = &clear; + vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE); + vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe); + uint32_t zeros[36] = {}; + reinterpret_cast(vkGetDeviceProcAddr(dev, "vkCmdPushConstants"))( + cmd, pl, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, sizeof(zeros), zeros); + vkCmdDraw(cmd, 3, 1, 0, 0); + vkCmdEndRenderPass(cmd); + VkBufferImageCopy reg{}; reg.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; reg.imageExtent = {W, H, 1}; + vkCmdCopyImageToBuffer(cmd, img, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, buf, 1, ®); + CHECK(vkEndCommandBuffer(cmd)); + VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd; + CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); + CHECK(vkQueueWaitIdle(q)); + void* p; CHECK(vkMapMemory(dev, bmem, 0, bi.size, 0, &p)); + std::ofstream(argv[3], std::ios::binary).write(static_cast(p), std::streamsize(bi.size)); + std::fprintf(stderr, "ok %ux%u -> %s\n", W, H, argv[3]); + return 0; +} diff --git a/runtime/test/vk_texture_test.cpp b/runtime/test/vk_texture_test.cpp new file mode 100644 index 000000000..75735ba62 --- /dev/null +++ b/runtime/test/vk_texture_test.cpp @@ -0,0 +1,290 @@ +// GPU test for translated texture-sampling pixel shaders, using the translator's runtime contract: +// push constants: s0..s31 user data, then the 64-bit heap base (host BDA of the Xbox GPU VA window) +// set 0: binding 0 = 2D images[], 1 = samplers[], 2 = descriptor hash table (storage buffer) +// The test puts a T# (8 dwords) at Xbox VA `tsharp_va` inside the heap, points user SGPR s[ptr_sgpr] at it, +// registers that T# -> image index 1 and the shader's literal S# -> sampler index 1, binds an 8x8 gradient at +// index 1 and a magenta fallback at index 0, draws a full-screen triangle and dumps the RGBA32F result. +// +// vk_texture_test (S# words as hex) +#define VK_NO_PROTOTYPES +#include +#include + +#include +#include +#include +#include +#include + +static PFN_vkGetInstanceProcAddr gipa; +#define CHECK(x) \ + do { \ + VkResult r_ = (x); \ + if (r_ != VK_SUCCESS) { \ + std::fprintf(stderr, "FAILED %s -> %d (line %d)\n", #x, r_, __LINE__); \ + return 1; \ + } \ + } while (0) + +static std::vector read_spv(const char* p) { + std::ifstream f(p, std::ios::binary); + std::vector b((std::istreambuf_iterator(f)), {}); + std::vector w(b.size() / 4); + std::memcpy(w.data(), b.data(), w.size() * 4); + return w; +} + +// Same hash as the translator's desc_lookup: FNV-1a over the 8 key dwords (whole dwords, not bytes). +static uint32_t key_hash(const uint32_t k[8]) { + uint32_t h = 2166136261u; + for (int i = 0; i < 8; i++) h = (h ^ k[i]) * 16777619u; + return h; +} +static void table_insert(std::vector& t, const uint32_t key[8], uint32_t index) { + uint32_t mask = t[0], h = key_hash(key); + for (uint32_t k = 0; k < 8; k++) { + uint32_t slot = (h + k) & mask, base = slot * 10; + if (t[base + 10] == 0xA11CA7ED) continue; // pad dword marks a used slot (host-side only) + for (int j = 0; j < 8; j++) t[base + 1 + j] = key[j]; + t[base + 9] = index; + t[base + 10] = 0xA11CA7ED; + return; + } +} + +int main(int argc, char** argv) { + if (argc < 9) { std::fprintf(stderr, "usage: vk_texture_test vs fs out ptr_sgpr s0 s1 s2 s3\n"); return 2; } + const uint32_t W = 64, H = 64, TW = 8; + int ptr_sgpr = atoi(argv[4]); + uint32_t ssharp[8] = {(uint32_t)strtoul(argv[5], 0, 16), (uint32_t)strtoul(argv[6], 0, 16), + (uint32_t)strtoul(argv[7], 0, 16), (uint32_t)strtoul(argv[8], 0, 16), + 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}; + uint32_t tsharp[8] = {0x11111111, 0x22222222, 0x33333333, 0x44444444, + 0x55555555, 0x66666666, 0x77777777, 0x88888888}; // any 8 dwords; only the key matters + const uint32_t tsharp_va = 256; + + HMODULE lib = LoadLibraryA("vulkan-1.dll"); + gipa = reinterpret_cast(GetProcAddress(lib, "vkGetInstanceProcAddr")); + VkInstance inst = VK_NULL_HANDLE; +#define LI(n) auto n = reinterpret_cast(gipa(inst, #n)) + LI(vkCreateInstance); + VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO}; app.apiVersion = VK_API_VERSION_1_2; + VkInstanceCreateInfo ici{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO}; ici.pApplicationInfo = &app; + CHECK(vkCreateInstance(&ici, nullptr, &inst)); + LI(vkEnumeratePhysicalDevices); LI(vkGetPhysicalDeviceProperties); LI(vkGetPhysicalDeviceQueueFamilyProperties); + LI(vkGetPhysicalDeviceMemoryProperties); LI(vkCreateDevice); LI(vkGetDeviceProcAddr); + uint32_t n = 0; vkEnumeratePhysicalDevices(inst, &n, nullptr); + std::vector pds(n); vkEnumeratePhysicalDevices(inst, &n, pds.data()); + VkPhysicalDevice pd = pds[0]; + for (auto d : pds) { VkPhysicalDeviceProperties p; vkGetPhysicalDeviceProperties(d, &p); + if (p.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) pd = d; } + uint32_t qn = 0; vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, nullptr); + std::vector qf(qn); vkGetPhysicalDeviceQueueFamilyProperties(pd, &qn, qf.data()); + uint32_t qi = 0; while (!(qf[qi].queueFlags & VK_QUEUE_GRAPHICS_BIT)) qi++; + float prio = 1; + VkDeviceQueueCreateInfo qci{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO}; + qci.queueFamilyIndex = qi; qci.queueCount = 1; qci.pQueuePriorities = &prio; + VkPhysicalDeviceVulkan12Features f12{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_1_2_FEATURES}; + f12.bufferDeviceAddress = VK_TRUE; f12.runtimeDescriptorArray = VK_TRUE; f12.descriptorIndexing = VK_TRUE; + VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.pNext = &f12; + f2.features.shaderInt64 = VK_TRUE; + VkDeviceCreateInfo dci{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO}; + dci.pNext = &f2; dci.queueCreateInfoCount = 1; dci.pQueueCreateInfos = &qci; + VkDevice dev; CHECK(vkCreateDevice(pd, &dci, nullptr, &dev)); +#define LD(n) auto n = reinterpret_cast(vkGetDeviceProcAddr(dev, #n)) + LD(vkGetDeviceQueue); LD(vkCreateImage); LD(vkGetImageMemoryRequirements); LD(vkAllocateMemory); + LD(vkBindImageMemory); LD(vkCreateImageView); LD(vkCreateRenderPass); LD(vkCreateFramebuffer); + LD(vkCreateShaderModule); LD(vkCreatePipelineLayout); LD(vkCreateGraphicsPipelines); LD(vkCreateCommandPool); + LD(vkAllocateCommandBuffers); LD(vkBeginCommandBuffer); LD(vkCmdBeginRenderPass); LD(vkCmdBindPipeline); + LD(vkCmdDraw); LD(vkCmdEndRenderPass); LD(vkCmdCopyImageToBuffer); LD(vkCmdCopyBufferToImage); + LD(vkEndCommandBuffer); LD(vkQueueSubmit); LD(vkQueueWaitIdle); LD(vkCreateBuffer); + LD(vkGetBufferMemoryRequirements); LD(vkBindBufferMemory); LD(vkMapMemory); LD(vkGetBufferDeviceAddress); + LD(vkCreateSampler); LD(vkCreateDescriptorSetLayout); LD(vkCreateDescriptorPool); LD(vkAllocateDescriptorSets); + LD(vkUpdateDescriptorSets); LD(vkCmdBindDescriptorSets); LD(vkCmdPushConstants); LD(vkCmdPipelineBarrier); + VkQueue q; vkGetDeviceQueue(dev, qi, 0, &q); + VkPhysicalDeviceMemoryProperties mp; vkGetPhysicalDeviceMemoryProperties(pd, &mp); + auto memtype = [&](uint32_t bits, VkMemoryPropertyFlags want) { + for (uint32_t i = 0; i < mp.memoryTypeCount; i++) + if ((bits & (1u << i)) && (mp.memoryTypes[i].propertyFlags & want) == want) return i; + return 0u; + }; + auto make_buffer = [&](VkDeviceSize size, VkBufferUsageFlags usage, VkBuffer* b, VkDeviceMemory* m, void** map) { + VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; bi.size = size; bi.usage = usage; + VkResult r = vkCreateBuffer(dev, &bi, nullptr, b); if (r) return r; + VkMemoryRequirements mr; vkGetBufferMemoryRequirements(dev, *b, &mr); + VkMemoryAllocateFlagsInfo fi{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO}; + fi.flags = VK_MEMORY_ALLOCATE_DEVICE_ADDRESS_BIT; + VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.pNext = &fi; ai.allocationSize = mr.size; + ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT); + r = vkAllocateMemory(dev, &ai, nullptr, m); if (r) return r; + r = vkBindBufferMemory(dev, *b, *m, 0); if (r) return r; + return vkMapMemory(dev, *m, 0, size, 0, map); + }; + // Heap (the Xbox GPU VA window) with the T# at tsharp_va. + VkBuffer heap; VkDeviceMemory heapm; void* heapp; + CHECK(make_buffer(65536, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT, &heap, &heapm, &heapp)); + std::memset(heapp, 0, 65536); + std::memcpy(static_cast(heapp) + tsharp_va, tsharp, 32); + VkBufferDeviceAddressInfo bdai{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; bdai.buffer = heap; + VkDeviceAddress heap_base = vkGetBufferDeviceAddress(dev, &bdai); + // Descriptor hash table: 16 slots. + std::vector table(1 + 16 * 10 + 10, 0); + table[0] = 15; + table_insert(table, tsharp, 1); + table_insert(table, ssharp, 1); + for (uint32_t s = 0; s <= 16; s++) if (s * 10 + 10 < table.size() && table[s * 10 + 10] == 0xA11CA7ED) table[s * 10 + 10] = 0; + VkBuffer tb; VkDeviceMemory tbm; void* tbp; + CHECK(make_buffer(table.size() * 4, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &tb, &tbm, &tbp)); + std::memcpy(tbp, table.data(), table.size() * 4); + // Textures: index 0 = 1x1 magenta fallback, index 1 = 8x8 gradient (r = x/8, g = y/8, b = 0.5, a = 1). + auto make_tex = [&](uint32_t w, uint32_t h, const std::vector& rgba, VkImage* img, VkImageView* view) { + VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + ii.imageType = VK_IMAGE_TYPE_2D; ii.format = VK_FORMAT_R8G8B8A8_UNORM; ii.extent = {w, h, 1}; + ii.mipLevels = 1; ii.arrayLayers = 1; ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; + ii.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; + VkResult r = vkCreateImage(dev, &ii, nullptr, img); if (r) return r; + VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, *img, &mr); + VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.allocationSize = mr.size; + ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VkDeviceMemory m; r = vkAllocateMemory(dev, &ai, nullptr, &m); if (r) return r; + vkBindImageMemory(dev, *img, m, 0); + VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + vi.image = *img; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = ii.format; + vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + return vkCreateImageView(dev, &vi, nullptr, view); + }; + std::vector magenta{0xFFFF00FFu}, grad(TW * TW); + for (uint32_t y = 0; y < TW; y++) + for (uint32_t x = 0; x < TW; x++) + grad[y * TW + x] = (x * 32u) | ((y * 32u) << 8) | (128u << 16) | (255u << 24); + VkImage timg[2]; VkImageView tview[2]; + CHECK(make_tex(1, 1, magenta, &timg[0], &tview[0])); + CHECK(make_tex(TW, TW, grad, &timg[1], &tview[1])); + VkBuffer up; VkDeviceMemory upm; void* upp; + CHECK(make_buffer(4096, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, &up, &upm, &upp)); + std::memcpy(upp, magenta.data(), 4); + std::memcpy(static_cast(upp) + 256, grad.data(), grad.size() * 4); + VkSamplerCreateInfo sci{VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO}; + sci.magFilter = sci.minFilter = VK_FILTER_NEAREST; + sci.addressModeU = sci.addressModeV = sci.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE; + VkSampler smp[2]; CHECK(vkCreateSampler(dev, &sci, nullptr, &smp[0])); CHECK(vkCreateSampler(dev, &sci, nullptr, &smp[1])); + // Render target. + const VkFormat fmt = VK_FORMAT_R32G32B32A32_SFLOAT; + VkImage rt; VkImageView rtv; + { + VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; + ii.imageType = VK_IMAGE_TYPE_2D; ii.format = fmt; ii.extent = {W, H, 1}; ii.mipLevels = 1; ii.arrayLayers = 1; + ii.samples = VK_SAMPLE_COUNT_1_BIT; ii.tiling = VK_IMAGE_TILING_OPTIMAL; + ii.usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + CHECK(vkCreateImage(dev, &ii, nullptr, &rt)); + VkMemoryRequirements mr; vkGetImageMemoryRequirements(dev, rt, &mr); + VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; ai.allocationSize = mr.size; + ai.memoryTypeIndex = memtype(mr.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); + VkDeviceMemory m; CHECK(vkAllocateMemory(dev, &ai, nullptr, &m)); vkBindImageMemory(dev, rt, m, 0); + VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; + vi.image = rt; vi.viewType = VK_IMAGE_VIEW_TYPE_2D; vi.format = fmt; vi.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; + CHECK(vkCreateImageView(dev, &vi, nullptr, &rtv)); + } + VkAttachmentDescription ad{}; ad.format = fmt; ad.samples = VK_SAMPLE_COUNT_1_BIT; + ad.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR; ad.storeOp = VK_ATTACHMENT_STORE_OP_STORE; + ad.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE; ad.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE; + ad.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; ad.finalLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; + VkAttachmentReference ar{0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; + VkSubpassDescription sd{}; sd.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; sd.colorAttachmentCount = 1; sd.pColorAttachments = &ar; + VkRenderPassCreateInfo rpi{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; + rpi.attachmentCount = 1; rpi.pAttachments = &ad; rpi.subpassCount = 1; rpi.pSubpasses = &sd; + VkRenderPass rp; CHECK(vkCreateRenderPass(dev, &rpi, nullptr, &rp)); + VkFramebufferCreateInfo fbi{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; + fbi.renderPass = rp; fbi.attachmentCount = 1; fbi.pAttachments = &rtv; fbi.width = W; fbi.height = H; fbi.layers = 1; + VkFramebuffer fb; CHECK(vkCreateFramebuffer(dev, &fbi, nullptr, &fb)); + // Descriptor set: binding 0 images[2], 1 samplers[2], 2 hash table. + VkDescriptorSetLayoutBinding b[3]{}; + b[0] = {0, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; + b[1] = {1, VK_DESCRIPTOR_TYPE_SAMPLER, 2, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; + b[2] = {2, VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, nullptr}; + VkDescriptorSetLayoutCreateInfo dli{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; dli.bindingCount = 3; dli.pBindings = b; + VkDescriptorSetLayout dsl; CHECK(vkCreateDescriptorSetLayout(dev, &dli, nullptr, &dsl)); + VkDescriptorPoolSize ps[3]{{VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 2}, {VK_DESCRIPTOR_TYPE_SAMPLER, 2}, {VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 1}}; + VkDescriptorPoolCreateInfo dpi{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; dpi.maxSets = 1; dpi.poolSizeCount = 3; dpi.pPoolSizes = ps; + VkDescriptorPool dp; CHECK(vkCreateDescriptorPool(dev, &dpi, nullptr, &dp)); + VkDescriptorSetAllocateInfo dai{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; dai.descriptorPool = dp; dai.descriptorSetCount = 1; dai.pSetLayouts = &dsl; + VkDescriptorSet ds; CHECK(vkAllocateDescriptorSets(dev, &dai, &ds)); + VkDescriptorImageInfo ii2[2]{{VK_NULL_HANDLE, tview[0], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}, + {VK_NULL_HANDLE, tview[1], VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}}; + VkDescriptorImageInfo si2[2]{{smp[0]}, {smp[1]}}; + VkDescriptorBufferInfo tbi{tb, 0, VK_WHOLE_SIZE}; + VkWriteDescriptorSet wr[3]{}; + for (auto& w : wr) { w.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; w.dstSet = ds; } + wr[0].dstBinding = 0; wr[0].descriptorCount = 2; wr[0].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE; wr[0].pImageInfo = ii2; + wr[1].dstBinding = 1; wr[1].descriptorCount = 2; wr[1].descriptorType = VK_DESCRIPTOR_TYPE_SAMPLER; wr[1].pImageInfo = si2; + wr[2].dstBinding = 2; wr[2].descriptorCount = 1; wr[2].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER; wr[2].pBufferInfo = &tbi; + vkUpdateDescriptorSets(dev, 3, wr, 0, nullptr); + // Pipeline. + auto module = [&](const char* p, VkShaderModule* m) { + auto code = read_spv(p); + VkShaderModuleCreateInfo smi{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; smi.codeSize = code.size() * 4; smi.pCode = code.data(); + return vkCreateShaderModule(dev, &smi, nullptr, m); + }; + VkShaderModule vs, fs; CHECK(module(argv[1], &vs)); CHECK(module(argv[2], &fs)); + VkPipelineShaderStageCreateInfo st[2]{{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}, {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}}; + st[0].stage = VK_SHADER_STAGE_VERTEX_BIT; st[0].module = vs; st[0].pName = "main"; + st[1].stage = VK_SHADER_STAGE_FRAGMENT_BIT; st[1].module = fs; st[1].pName = "main"; + VkPushConstantRange pcr{VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, 144}; + VkPipelineLayoutCreateInfo pli{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + pli.setLayoutCount = 1; pli.pSetLayouts = &dsl; pli.pushConstantRangeCount = 1; pli.pPushConstantRanges = &pcr; + VkPipelineLayout pl; CHECK(vkCreatePipelineLayout(dev, &pli, nullptr, &pl)); + VkPipelineVertexInputStateCreateInfo vin{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO}; + VkPipelineInputAssemblyStateCreateInfo ia{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; ia.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + VkViewport vp{0, 0, float(W), float(H), 0, 1}; VkRect2D sc{{0, 0}, {W, H}}; + VkPipelineViewportStateCreateInfo vps{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO}; + vps.viewportCount = 1; vps.pViewports = &vp; vps.scissorCount = 1; vps.pScissors = ≻ + VkPipelineRasterizationStateCreateInfo rs{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO}; rs.cullMode = VK_CULL_MODE_NONE; rs.lineWidth = 1; + VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO}; ms.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT; + VkPipelineColorBlendAttachmentState cba{}; cba.colorWriteMask = 0xF; + VkPipelineColorBlendStateCreateInfo cb{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO}; cb.attachmentCount = 1; cb.pAttachments = &cba; + VkGraphicsPipelineCreateInfo gpi{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO}; + gpi.stageCount = 2; gpi.pStages = st; gpi.pVertexInputState = &vin; gpi.pInputAssemblyState = &ia; gpi.pViewportState = &vps; + gpi.pRasterizationState = &rs; gpi.pMultisampleState = &ms; gpi.pColorBlendState = &cb; gpi.layout = pl; gpi.renderPass = rp; + VkPipeline pipe; CHECK(vkCreateGraphicsPipelines(dev, VK_NULL_HANDLE, 1, &gpi, nullptr, &pipe)); + VkBuffer rb; VkDeviceMemory rbm; void* rbp; + CHECK(make_buffer(VkDeviceSize(W) * H * 16, VK_BUFFER_USAGE_TRANSFER_DST_BIT, &rb, &rbm, &rbp)); + // Commands: upload textures, draw, read back. + VkCommandPoolCreateInfo cpi{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO}; cpi.queueFamilyIndex = qi; + VkCommandPool pool; CHECK(vkCreateCommandPool(dev, &cpi, nullptr, &pool)); + VkCommandBufferAllocateInfo cai{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO}; cai.commandPool = pool; cai.commandBufferCount = 1; + VkCommandBuffer cmd; CHECK(vkAllocateCommandBuffers(dev, &cai, &cmd)); + VkCommandBufferBeginInfo cbi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO}; CHECK(vkBeginCommandBuffer(cmd, &cbi)); + for (int t = 0; t < 2; t++) { + VkImageMemoryBarrier ib{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; + ib.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; ib.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib.image = timg[t]; + ib.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; ib.dstAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; + ib.srcQueueFamilyIndex = ib.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, nullptr, 0, nullptr, 1, &ib); + VkBufferImageCopy c{}; c.bufferOffset = t ? 256 : 0; c.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; + c.imageExtent = {t ? TW : 1u, t ? TW : 1u, 1}; + vkCmdCopyBufferToImage(cmd, up, timg[t], VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &c); + ib.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; ib.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; + ib.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; ib.dstAccessMask = VK_ACCESS_SHADER_READ_BIT; + vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &ib); + } + VkClearValue clear{}; for (int i = 0; i < 4; i++) clear.color.float32[i] = -1; + VkRenderPassBeginInfo rbi{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; + rbi.renderPass = rp; rbi.framebuffer = fb; rbi.renderArea = sc; rbi.clearValueCount = 1; rbi.pClearValues = &clear; + vkCmdBeginRenderPass(cmd, &rbi, VK_SUBPASS_CONTENTS_INLINE); + vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe); + vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pl, 0, 1, &ds, 0, nullptr); + uint32_t pc[36] = {}; + pc[ptr_sgpr] = tsharp_va; // pointer to the T# (low dword; the shader forces the high dword to 0) + pc[32] = uint32_t(heap_base); pc[33] = uint32_t(heap_base >> 32); + vkCmdPushConstants(cmd, pl, VK_SHADER_STAGE_FRAGMENT_BIT | VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(pc), pc); + vkCmdDraw(cmd, 3, 1, 0, 0); + vkCmdEndRenderPass(cmd); + VkBufferImageCopy rc{}; rc.imageSubresource = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1}; rc.imageExtent = {W, H, 1}; + vkCmdCopyImageToBuffer(cmd, rt, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, rb, 1, &rc); + CHECK(vkEndCommandBuffer(cmd)); + VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO}; si.commandBufferCount = 1; si.pCommandBuffers = &cmd; + CHECK(vkQueueSubmit(q, 1, &si, VK_NULL_HANDLE)); CHECK(vkQueueWaitIdle(q)); + std::ofstream(argv[3], std::ios::binary).write(static_cast(rbp), std::streamsize(W) * H * 16); + std::fprintf(stderr, "ok -> %s (heap base 0x%llx)\n", argv[3], (unsigned long long)heap_base); + return 0; +} diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 new file mode 100644 index 000000000..ffca056fd --- /dev/null +++ b/scripts/build_runtime.ps1 @@ -0,0 +1,46 @@ +# Builds runtime\build\gta6rt.exe with MSVC at BelowNormal priority, on half the cores. +# Uses VS's CMake + Ninja when the "C++ CMake tools" component is installed, otherwise calls cl.exe directly. +param([switch]$Debug) +$ErrorActionPreference = "Stop" + +$root = Split-Path $PSScriptRoot -Parent +$installer = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer" +$vs = & "$installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath +if (-not $vs) { throw "Visual Studio with the C++ x64 tools wasn't found." } +$vcvars = Join-Path $vs "VC\Auxiliary\Build\vcvars64.bat" +$jobs = [Math]::Max(1, [int]([Environment]::ProcessorCount / 2)) + +$src = Join-Path $root "runtime" +$out = Join-Path $src "build" +New-Item -ItemType Directory -Force $out | Out-Null + +$cmakeDir = Join-Path $vs "Common7\IDE\CommonExtensions\Microsoft\CMake" +$cmake = Join-Path $cmakeDir "CMake\bin\cmake.exe" +$ninja = Join-Path $cmakeDir "Ninja\ninja.exe" +$cfg = if ($Debug) { "Debug" } else { "RelWithDebInfo" } + +if ((Test-Path $cmake) -and (Test-Path $ninja)) { + $body = @" +"$cmake" -S "$src" -B "$out" -G Ninja "-DCMAKE_MAKE_PROGRAM=$ninja" -DCMAKE_BUILD_TYPE=$cfg || exit /b 1 +"$cmake" --build "$out" -j $jobs || exit /b 1 +"@ +} else { + # Keep this list in step with runtime\CMakeLists.txt. + $files = "src\main.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\xmem.cpp", "shims\d3d12_xs.cpp" | ForEach-Object { "`"$src\$_`"" } + $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } + $body = @" +cd /d "$out" || exit /b 1 +cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE $($files -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF psapi.lib || exit /b 1 +"@ +} + +# A .cmd file avoids cmd.exe's quote stripping on paths with spaces. +$bat = Join-Path $out "_build.cmd" +"@echo off`r`nset `"PATH=$installer;%PATH%`"`r`ncall `"$vcvars`" >nul || exit /b 1`r`n$body" | Set-Content -Encoding ascii $bat + +$p = Start-Process cmd.exe -ArgumentList "/c", "`"$bat`"" -NoNewWindow -PassThru +$null = $p.Handle # keeps the exit code readable after WaitForExit +try { $p.PriorityClass = "BelowNormal" } catch {} +$p.WaitForExit() +if ($p.ExitCode -ne 0) { throw "build failed ($($p.ExitCode))" } +Write-Host "built $out\gta6rt.exe" diff --git a/scripts/carve_all.ps1 b/scripts/carve_all.ps1 new file mode 100644 index 000000000..c70aab30a --- /dev/null +++ b/scripts/carve_all.ps1 @@ -0,0 +1,20 @@ +# Carves every .rpf in the game folder into \, smallest first (research tool; the +# build itself doesn't need it). Skips archives that already have an index.json. Summary: \coverage.json +param([Parameter(Mandatory)][string]$Game, [Parameter(Mandatory)][string]$Out) +$root = Split-Path $PSScriptRoot -Parent +$tool = Join-Path $root "tools\rpf9_carve.py" +$rows = @() +foreach ($f in Get-ChildItem $Game -Recurse -Filter *.rpf | Sort-Object Length) { + $rel = $f.FullName.Substring($Game.Length + 1) + $dest = Join-Path $Out ([IO.Path]::GetFileNameWithoutExtension(($rel -replace "[\\/]", "_"))) + if (-not (Test-Path (Join-Path $dest "index.json"))) { + Write-Host ("{0:HH:mm:ss} carving {1} ({2:N1} GiB)" -f (Get-Date), $rel, ($f.Length / 1GB)) + python -I $tool $f.FullName $dest | Select-Object -Last 1 + } + $s = (Get-Content (Join-Path $dest "index.json") -Raw | ConvertFrom-Json).summary + $rows += [pscustomobject]@{ archive = $rel; files = $s.files; bink2 = $s.bink2_files; span = $s.span + readable = [math]::Round(($s.compressed_bytes) / $s.span, 4) + unread = [math]::Round($s.unread_bytes / $s.span, 4); inflated = $s.inflated_bytes } +} +$rows | ConvertTo-Json | Set-Content -Encoding utf8 (Join-Path $Out "coverage.json") +$rows | Format-Table archive, files, bink2, @{n = "GiB"; e = { [math]::Round($_.span / 1GB, 2) } }, readable, unread -AutoSize | Out-String -Width 200 diff --git a/scripts/first_look.ps1 b/scripts/first_look.ps1 new file mode 100644 index 000000000..913b0a9c3 --- /dev/null +++ b/scripts/first_look.ps1 @@ -0,0 +1,41 @@ +# Day-one report for the game executable: PE inspection, encryption check, import surface and a loader dry run. +# Reads the exe only; no game code runs. +param( + [Parameter(Mandatory)][string]$Exe, + [string]$GameDir = (Split-Path $Exe -Parent) +) +$ErrorActionPreference = "Stop" +$root = Split-Path $PSScriptRoot -Parent +$name = [IO.Path]::GetFileNameWithoutExtension($Exe) +$out = Join-Path $root "reports\exe\$name" +New-Item -ItemType Directory -Force $out | Out-Null + +if (-not (Test-Path $Exe)) { throw "$Exe not found" } +$fs = [IO.File]::OpenRead($Exe); $mz = New-Object byte[] 2; [void]$fs.Read($mz, 0, 2); $fs.Close() +if ([Text.Encoding]::ASCII.GetString($mz) -ne "MZ") { + throw "$Exe doesn't start with an MZ header. It's still packaged or encrypted, so there's nothing to inspect." +} + +$size = (Get-Item $Exe).Length +$hash = (Get-FileHash $Exe -Algorithm SHA256).Hash.ToLower() +"sha256 $hash size $size" | Tee-Object (Join-Path $out "hash.txt") + +Write-Host "`n== PE inspection" +python -I (Join-Path $root "tools\pe_inspect.py") $Exe --game-dir $GameDir --out $out +if ($LASTEXITCODE -ne 0) { throw "pe_inspect failed" } + +$rt = Join-Path $root "runtime\build\gta6rt.exe" +if (-not (Test-Path $rt)) { & (Join-Path $PSScriptRoot "build_runtime.ps1") } +Write-Host "`n== Loader dry run (map, relocate, bind imports; nothing executes)" +& $rt --dry-run $Exe --game-dir $GameDir 2>&1 | Tee-Object (Join-Path $out "dryrun.txt") | Select-Object -Last 40 + +# Shim to-do list, grouped by DLL, most functions first. +$report = Get-Content (Join-Path $out "$name.json") -Raw | ConvertFrom-Json +$todo = $report.imports | Where-Object { $_.where -eq "shim" } | Sort-Object { -$_.functions.Count } +$lines = foreach ($t in $todo) { "{0,-40} {1,5}" -f $t.dll, $t.functions.Count } +$lines | Set-Content (Join-Path $out "shim-todo.txt") +Write-Host "`n== Shim to-do (DLL, function count)" +$lines +$enc = $report.sections | Where-Object { $_.looks_encrypted } | ForEach-Object { $_.name } +if ($enc) { Write-Warning "High-entropy sections (still encrypted or packed): $($enc -join ', ')" } +Write-Host "`nReports: $out" diff --git a/scripts/meta_to_xml.ps1 b/scripts/meta_to_xml.ps1 new file mode 100644 index 000000000..cdef1be86 --- /dev/null +++ b/scripts/meta_to_xml.ps1 @@ -0,0 +1,52 @@ +# Converts carved PSO ('PSIN') and RBF ('RBF0') metadata blobs to XML with CodeWalker.Core's parsers. +# Run in Windows PowerShell 5.1. +# .\meta_to_xml.ps1 -Carve G:\gta6-work\carve -Out G:\gta6-work\meta [-Limit N] +# Each blob becomes \\.xml. Failures go to \failures.txt with the parser's message. +param( + [string]$Carve = "G:\gta6-work\carve", + [string]$Out = "G:\gta6-work\meta", + [string]$CodeWalker = "G:\ref\codewalker-gen9", + [int]$Limit = 0 +) +$ErrorActionPreference = "Stop" +try { (Get-Process -Id $PID).PriorityClass = "BelowNormal" } catch {} +Add-Type -Path "$CodeWalker\SharpDX.dll"; Add-Type -Path "$CodeWalker\SharpDX.Mathematics.dll" +[void][Reflection.Assembly]::LoadFrom("$CodeWalker\CodeWalker.Core.dll") +New-Item -ItemType Directory -Force $Out | Out-Null +$fail = Join-Path $Out "failures.txt" +"" | Set-Content $fail +$ok = @{ pso = 0; rbf = 0 }; $bad = @{ pso = 0; rbf = 0 }; $n = 0 + +foreach ($dir in Get-ChildItem $Carve -Directory) { + $idx = Join-Path $dir.FullName "index.json" + if (-not (Test-Path $idx)) { continue } + $files = (Get-Content $idx -Raw | ConvertFrom-Json).files | + Where-Object { $_.head.StartsWith("5053494e") -or $_.head.StartsWith("52424630") } + if (-not $files) { continue } + $dest = Join-Path $Out $dir.Name + New-Item -ItemType Directory -Force $dest | Out-Null + foreach ($r in $files) { + if ($Limit -and $n -ge $Limit) { break } + $n++ + $name = "{0:x12}" -f [int64]$r.off + $bytes = [IO.File]::ReadAllBytes((Join-Path $dir.FullName "$name.bin")) + $kind = if ($r.head.StartsWith("5053494e")) { "pso" } else { "rbf" } + try { + if ($kind -eq "pso") { + $f = New-Object CodeWalker.GameFiles.PsoFile; $f.Load($bytes) + $xml = [CodeWalker.GameFiles.PsoXml]::GetXml($f) + } else { + $f = New-Object CodeWalker.GameFiles.RbfFile; $f.Load($bytes) + $xml = [CodeWalker.GameFiles.RbfXml]::GetXml($f) + } + [IO.File]::WriteAllText((Join-Path $dest "$name.$kind.xml"), $xml) + $ok[$kind]++ + } catch { + $bad[$kind]++ + $msg = $_.Exception.InnerException; if (-not $msg) { $msg = $_.Exception } + "$($dir.Name)\$name $kind : $($msg.Message)" | Add-Content $fail + } + } + if ($Limit -and $n -ge $Limit) { break } +} +"pso ok $($ok.pso) failed $($bad.pso); rbf ok $($ok.rbf) failed $($bad.rbf) -> $Out" diff --git a/third_party/rpf9-explorer b/third_party/rpf9-explorer new file mode 160000 index 000000000..48557ead0 --- /dev/null +++ b/third_party/rpf9-explorer @@ -0,0 +1 @@ +Subproject commit 48557ead00601d3757ba12b894f2595c4faad2a5 diff --git a/tools/amd_swizzle.py b/tools/amd_swizzle.py new file mode 100644 index 000000000..ec262c7ae --- /dev/null +++ b/tools/amd_swizzle.py @@ -0,0 +1,156 @@ +"""AMD GFX10/RDNA2 texture detiling from addrlib's published swizzle patterns. + +Reads gfx10SwizzlePattern.h (Mesa's addrlib, MIT licence) and builds, for a swizzle mode and pipe/packer +configuration, the equation that maps an element's (x, y) to its byte offset. 64 KB macro blocks are laid out +row-major; inside a block every address bit is an XOR of x and y bits (including bits above the block, which is +how the XOR modes spread neighbouring blocks across pipes). + +As a tool: + python -I amd_swizzle.py --bpe 8 --width 2048 --height 2048 [--offset N] [--modes 64K] [--out best.png] +tries every 64 KB pattern table and configuration for that element size, scores each by image smoothness, and +renders the best. As a module, `detile(data, pattern, bpe, wb, hb)` returns linear blocks. +""" +import argparse +import os +import re +import sys + +import numpy as np + +HEADER = os.environ.get("AMD_SWIZZLE_HEADER", r"G:\ref\mesa-addrlib\gfx10SwizzlePattern.h") +BPE_INDEX = {1: 0, 2: 1, 4: 2, 8: 3, 16: 4} + + +def _symbols(): + env = {} + for i in range(16): + env[f"X{i}"] = 1 << i + env[f"Y{i}"] = 1 << (16 + i) + env[f"Z{i}"] = 1 << (32 + i) + env[f"S{i}"] = 1 << (48 + i) + return env + + +def load(path=HEADER): + text = open(path, encoding="utf-8", errors="replace").read() + env = _symbols() + nibbles = {} + for name in ("NIBBLE01", "NIBBLE2", "NIBBLE3", "NIBBLE4"): + m = re.search(r"GFX10_SW_PATTERN_" + name + r"\[\]\[\d+\]\s*=\s*\{(.*?)\n\};", text, re.S) + rows = re.findall(r"\{([^{}]*)\}", m.group(1)) + nibbles[name] = [[eval(t.strip() or "0", {}, env) for t in r.split(",") if t.strip()] for r in rows] # noqa: S307 + tables = {} + for m in re.finditer(r"const ADDR_SW_PATINFO (GFX10_SW_\w+_PATINFO)\[\]\s*=\s*\{(.*?)\n\};", text, re.S): + entries = [] + for row in m.group(2).splitlines(): + mm = re.match(r"\s*\{\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+),\s*(\d+),\s*\}\s*,\s*//\s*(.*)", row) + if mm: + entries.append(tuple(int(v) for v in mm.groups()[:5]) + (mm.group(6).strip(),)) + tables[m.group(1)] = entries + return nibbles, tables + + +def equation(nibbles, entry, block_bits): + """Per address bit, (x mask, y mask) for the given pattern entry, for the first `block_bits` bits.""" + _, n01, n2, n3, n4, _ = entry + bits = list(nibbles["NIBBLE01"][n01]) + list(nibbles["NIBBLE2"][n2]) + list(nibbles["NIBBLE3"][n3]) + \ + list(nibbles["NIBBLE4"][n4]) + return [(v & 0xFFFF, (v >> 16) & 0xFFFF) for v in bits[:block_bits]] + + +def _parity(a): + a = a ^ (a >> 8) + a = a ^ (a >> 4) + a = a ^ (a >> 2) + a = a ^ (a >> 1) + return a & 1 + + +def offsets(eq, bpe, wb, hb, block_bytes=65536): + """Byte offset of every element (row-major y, x) for a wb x hb element grid.""" + y, x = np.mgrid[0:hb, 0:wb].astype(np.int64) + off = np.zeros_like(x) + for bit, (mx, my) in enumerate(eq): + if mx or my: + off |= (_parity(x & mx) ^ _parity(y & my)) << bit + # Macro-block size in elements, from which coordinate bits the equation uses below block_bytes. + xb = max((mx.bit_length() for mx, _ in eq if mx), default=0) + yb = max((my.bit_length() for _, my in eq if my), default=0) + # The block's own extent: the x/y bits that appear as the *sole* term of some address bit. + solo_x = [mx.bit_length() for mx, my in eq if mx and not my and mx & (mx - 1) == 0] + solo_y = [my.bit_length() for mx, my in eq if my and not mx and my & (my - 1) == 0] + bw = 1 << max(solo_x + [0]) + bh = 1 << max(solo_y + [0]) + blocks_x = (wb + bw - 1) // bw + block = (y // bh) * blocks_x + (x // bw) + return off + block * block_bytes, (bw, bh, xb, yb) + + +def detile(data, eq, bpe, wb, hb): + off, _ = offsets(eq, bpe, wb, hb) + idx = off // bpe + raw = np.frombuffer(data[: len(data) // bpe * bpe], np.uint8).reshape(-1, bpe) + if idx.max() >= len(raw): + return None + return raw[idx.reshape(-1)] + + +def main(): + sys.path.insert(0, os.path.dirname(__file__)) + from tile_probe import block_feature, score + from swizzle_search import render # noqa: F401 + ap = argparse.ArgumentParser() + ap.add_argument("blob") + ap.add_argument("--bpe", type=int, default=8) + ap.add_argument("--width", type=int, required=True) + ap.add_argument("--height", type=int, required=True) + ap.add_argument("--offset", type=int, default=0) + ap.add_argument("--modes", default="_64K_") + ap.add_argument("--out") + a = ap.parse_args() + nibbles, tables = load() + data = open(a.blob, "rb").read()[a.offset:] + wb, hb = a.width // 4, a.height // 4 + res = [] + for tname, entries in tables.items(): + if a.modes not in tname: + continue + for e in entries: + if f" {a.bpe} bpe" not in e[5]: + continue + eq = equation(nibbles, e, 16) + lin = detile(data, eq, a.bpe, wb, hb) + if lin is None: + continue + img = block_feature(lin, a.bpe).reshape(hb, wb, 3) + res.append((score(img), tname, e[5], e)) + res.sort(key=lambda r: r[0]) + seen = set() + for s, t, c, _ in res: + if (t, c) in seen: + continue + seen.add((t, c)) + print(f"{s:8.2f} {t:40} {c}") + if len(seen) >= 10: + break + if a.out and res: + import io + import struct + from PIL import Image + lin = detile(data, equation(nibbles, res[0][3], 16), a.bpe, wb, hb) + hdr = bytearray(128) + hdr[0:4] = b"DDS " + struct.pack_into("", a.out) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/bc_feature.py b/tools/bc_feature.py new file mode 100644 index 000000000..f158f6c8d --- /dev/null +++ b/tools/bc_feature.py @@ -0,0 +1,37 @@ +"""Exact per-block average colour for BC1 (8-byte) and BC3 (16-byte, colour half) blocks, vectorised.""" +import numpy as np + + +def _565(c): + r = ((c >> 11) & 31).astype(np.float32) * (255 / 31) + g = ((c >> 5) & 63).astype(np.float32) * (255 / 63) + b = (c & 31).astype(np.float32) * (255 / 31) + return np.stack([r, g, b], -1) + + +def bc1_average(blocks: np.ndarray) -> np.ndarray: + """blocks: (N, 8) uint8 -> (N, 3) float average colour of the 16 decoded pixels.""" + c0 = blocks[:, 0].astype(np.uint32) | (blocks[:, 1].astype(np.uint32) << 8) + c1 = blocks[:, 2].astype(np.uint32) | (blocks[:, 3].astype(np.uint32) << 8) + p0, p1 = _565(c0), _565(c1) + four = (c0 > c1)[:, None] + p2 = np.where(four, (2 * p0 + p1) / 3, (p0 + p1) / 2) + p3 = np.where(four, (p0 + 2 * p1) / 3, 0) + idx = blocks[:, 4:8].astype(np.uint32) + bits = idx[:, 0] | (idx[:, 1] << 8) | (idx[:, 2] << 16) | (idx[:, 3] << 24) + counts = np.zeros((len(blocks), 4), np.float32) + for k in range(16): + sel = (bits >> (2 * k)) & 3 + counts[np.arange(len(blocks)), sel] += 1 + pal = np.stack([p0, p1, p2, p3], 1) # (N, 4, 3) + return (pal * counts[:, :, None]).sum(1) / 16 + + +def block_average(blocks: np.ndarray, bpe: int) -> np.ndarray: + return bc1_average(blocks if bpe == 8 else blocks[:, 8:16]) + + +def smoothness(img: np.ndarray) -> float: + """Neighbour difference relative to the image's own spread (lower = more coherent).""" + d = np.abs(np.diff(img, axis=0)).mean() + np.abs(np.diff(img, axis=1)).mean() + return float(d / (img.std() + 1e-6)) diff --git a/tools/classify_carve.py b/tools/classify_carve.py new file mode 100644 index 000000000..ffd23f05d --- /dev/null +++ b/tools/classify_carve.py @@ -0,0 +1,61 @@ +"""Group every carved file by signature, using only the per-archive index.json (no file reads). + +Classes: + bink2 Bink 2 video (KB2x) + rbf0 Rockstar binary metadata ('RBF0', carries its own field names) + respage resource page ('42 40 00 00': tagged-pointer structures for textures/meshes/etc.) + gpu-zerohdr starts with 16+ zero bytes (GPU data: textures, vertex/index buffers) + other: anything else, keyed by its first 4 bytes + +Usage: + python -I classify_carve.py G:\\gta6-work\\carve +Writes types.json (per archive and overall counts/bytes per class, plus size stats) and prints a summary. +""" +import json +import os +import sys +from collections import Counter, defaultdict + + +def classify(r): + if r.get("type") == "bink2": + return "bink2" + h = r["head"] + if h.startswith("52424630"): + return "rbf0" + if h.startswith("42400000"): + return "respage" + if h.startswith("00000000000000000000000000000000"): + return "gpu-zerohdr" + return "other:" + h[:8] + + +def main(): + root = sys.argv[1] + per = {} + total = defaultdict(lambda: [0, 0]) + for name in sorted(os.listdir(root)): + p = os.path.join(root, name, "index.json") + if not os.path.isfile(p): + continue + files = json.load(open(p, encoding="utf-8"))["files"] + c = defaultdict(lambda: [0, 0]) + for r in files: + k = classify(r) + c[k][0] += 1 + c[k][1] += r["size"] + total[k][0] += 1 + total[k][1] += r["size"] + per[name] = {k: {"files": v[0], "bytes": v[1]} for k, v in sorted(c.items(), key=lambda kv: -kv[1][1])} + top = sorted(total.items(), key=lambda kv: -kv[1][1]) + out = {"overall": {k: {"files": v[0], "bytes": v[1]} for k, v in top}, "per_archive": per} + with open(os.path.join(root, "types.json"), "w", encoding="utf-8") as f: + json.dump(out, f, indent=1) + print(f"{'class':24} {'files':>10} {'GiB':>8}") + for k, v in top[:25]: + print(f"{k:24} {v[0]:>10} {v[1] / 2**30:8.2f}") + print(f"{len(top)} classes in total") + + +if __name__ == "__main__": + main() diff --git a/tools/fssm_unpack.py b/tools/fssm_unpack.py new file mode 100644 index 000000000..17b10b56a --- /dev/null +++ b/tools/fssm_unpack.py @@ -0,0 +1,97 @@ +"""Unpack the native GPU program from each carved shader container. + +Layout found in GTA VI's Xbox shaders (shader model 6.6 containers): + + DXBC + DXIL part = DxilProgramHeader (stub) + XDAT + XDAT = 'XDAT' u32 count, u32 header_size, then count x {u32 tag, u32 offset, u32 size} + (offsets are relative to the DXIL part) + tag 0x12 16-byte hash + tag 0x0d 'XBCH' u32 ?, u32 stored, u32 0, u32 unpacked, u32 0, then zlib -> 'FSSM' blob + tag 0x07 DxilProgramHeader with 'NOBC' (no LLVM bitcode is shipped) + PRIV part = Xbox private metadata + +The FSSM blob is the precompiled RDNA2 program plus its metadata. It contains the s_endpgm (0xBF810000) that ends +the code. + +Usage: + python -I fssm_unpack.py (writes /fssm/.fssm and fssm_index.json) +""" +import json +import os +import struct +import sys +import zlib +from collections import Counter + + +def parts(d: bytes) -> dict: + out = {} + for k in range(struct.unpack_from(" dict: + x = dxil.find(b"XDAT") + if x < 0: + return {} + count, hdr = struct.unpack_from(" int: + src = sys.argv[1] + out = os.path.join(src, "fssm") + os.makedirs(out, exist_ok=True) + rows, problems = [], Counter() + for name in sorted(os.listdir(src)): + if not name.endswith(".dxbc"): + continue + with open(os.path.join(src, name), "rb") as f: + d = f.read() + try: + fssm, ents = unpack(d) + except Exception as e: # noqa: BLE001 + problems[type(e).__name__] += 1 + continue + if fssm is None: + problems["no XBCH"] += 1 + continue + stem = name[:-5] + with open(os.path.join(out, stem + ".fssm"), "wb") as f: + f.write(fssm) + ends = [i for i in range(0, len(fssm) - 3, 4) if fssm[i:i + 4] == b"\x00\x00\x81\xbf"] + rows.append({"name": stem, "size": len(fssm), "magic": fssm[:4].decode("latin-1"), + "version": struct.unpack_from(" string dictionary from every string we can find. + +Sources: printable runs in carved blobs (selected archives fully; PSO/RBF blobs everywhere), shader names, and +any extra text/binary files given (e.g. the exe once it arrives: run with --extra path\\to\\exe). + +Usage: + python -I hashdict.py --out hashes.json [--archives a,b] [--extra f1 f2 ...] [--min 3] + python -I hashdict.py --lookup 0x28cca8df ... +""" +import argparse +import json +import os +import re +import sys + +STR = re.compile(rb"[A-Za-z_][A-Za-z0-9_./:\\-]{2,200}") + + +def joaat(s: str) -> int: + h = 0 + for c in s.lower().encode("latin-1", "replace"): + h = (h + c) & 0xFFFFFFFF + h = (h + (h << 10)) & 0xFFFFFFFF + h ^= h >> 6 + h = (h + (h << 3)) & 0xFFFFFFFF + h ^= h >> 11 + return (h + (h << 15)) & 0xFFFFFFFF + + +def harvest(data: bytes, out: set, minlen: int): + for m in STR.finditer(data): + s = m.group(0).decode("latin-1") + if len(s) >= minlen: + out.add(s) + # also the pieces of paths and dotted names, which are hashed on their own + for part in re.split(r"[./:\\]", s): + if len(part) >= minlen: + out.add(part) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("carve", nargs="?") + ap.add_argument("--out", default="hashes.json") + ap.add_argument("--archives", default="common,data,script,pack_story000_story000_script,textures") + ap.add_argument("--extra", nargs="*", default=[]) + ap.add_argument("--min", type=int, default=3) + ap.add_argument("--lookup", nargs="+") + a = ap.parse_args() + if a.lookup: + d = json.load(open(a.lookup[0], encoding="utf-8")) + for h in a.lookup[1:]: + print(h, d.get(f"{int(h, 16):08x}", "?")) + return 0 + strings = set() + full = set(a.archives.split(",")) + for arch in sorted(os.listdir(a.carve)): + p = os.path.join(a.carve, arch, "index.json") + if not os.path.isfile(p): + continue + for r in json.load(open(p, encoding="utf-8"))["files"]: + if r.get("type") == "bink2": + continue + meta = r["head"].startswith("5053494e") or r["head"].startswith("52424630") + if arch in full or meta: + with open(os.path.join(a.carve, arch, f"{r['off']:012x}.bin"), "rb") as f: + harvest(f.read(), strings, a.min) + print(f"{arch}: {len(strings)} strings so far", flush=True) + for x in a.extra: + if os.path.isdir(x): + for root, _, files in os.walk(x): + for fn in files: + strings.add(os.path.splitext(fn)[0]) + elif os.path.isfile(x): + harvest(open(x, "rb").read(), strings, a.min) + d = {} + for s in strings: + d.setdefault(f"{joaat(s):08x}", s) + with open(a.out, "w", encoding="utf-8") as f: + json.dump(d, f) + print(f"{len(strings)} strings -> {len(d)} hashes -> {a.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/manifest.py b/tools/manifest.py new file mode 100644 index 000000000..8263cae28 --- /dev/null +++ b/tools/manifest.py @@ -0,0 +1,92 @@ +"""SHA-256 manifest of a game folder, so later copies (and the exe, when it arrives) can be checked. + +Usage: + python -I manifest.py create [--out FILE] + python -I manifest.py verify [--manifest FILE] + +On Windows it lowers its own priority to BelowNormal so the PC stays usable. +""" +import argparse +import hashlib +import json +import os +import sys +import time + +CHUNK = 8 * 1024 * 1024 +DEFAULT = os.path.join(os.path.dirname(__file__), "..", "reports", "manifest.json") + + +def below_normal() -> None: + if os.name == "nt": + import ctypes + k32 = ctypes.windll.kernel32 + k32.SetPriorityClass(k32.GetCurrentProcess(), 0x00004000) # BELOW_NORMAL_PRIORITY_CLASS + + +def sha256(path: str) -> str: + h = hashlib.sha256() + with open(path, "rb", buffering=0) as f: + while chunk := f.read(CHUNK): + h.update(chunk) + return h.hexdigest() + + +def walk(game_dir: str): + for root, _, files in os.walk(game_dir): + for name in sorted(files): + p = os.path.join(root, name) + yield os.path.relpath(p, game_dir).replace("\\", "/"), p + + +def create(game_dir: str, out: str) -> int: + entries = {} + total = sum(os.path.getsize(p) for _, p in walk(game_dir)) + done, t0 = 0, time.time() + for rel, p in walk(game_dir): + size = os.path.getsize(p) + entries[rel] = {"size": size, "sha256": sha256(p)} + done += size + rate = done / max(time.time() - t0, 1e-6) / 2**20 + print(f"[{done / total:6.1%}] {rate:7.0f} MiB/s {rel}", flush=True) + os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True) + with open(out, "w", encoding="utf-8") as f: + json.dump({"created": time.strftime("%Y-%m-%d %H:%M:%S"), "files": entries}, f, indent=1) + print(f"{len(entries)} files, {total / 2**30:.1f} GiB -> {out}") + return 0 + + +def verify(game_dir: str, manifest: str) -> int: + with open(manifest, encoding="utf-8") as f: + want = json.load(f)["files"] + have = dict(walk(game_dir)) + bad = 0 + for rel, info in want.items(): + p = have.get(rel) + if p is None: + print(f"MISSING {rel}") + bad += 1 + elif os.path.getsize(p) != info["size"]: + print(f"SIZE {rel}") + bad += 1 + elif sha256(p) != info["sha256"]: + print(f"CHANGED {rel}") + bad += 1 + for rel in sorted(set(have) - set(want)): + print(f"NEW {rel}") + print("OK" if not bad else f"{bad} problem(s)") + return 1 if bad else 0 + + +def main() -> int: + ap = argparse.ArgumentParser() + sub = ap.add_subparsers(dest="cmd", required=True) + c = sub.add_parser("create"); c.add_argument("game_dir"); c.add_argument("--out", default=DEFAULT) + v = sub.add_parser("verify"); v.add_argument("game_dir"); v.add_argument("--manifest", default=DEFAULT) + a = ap.parse_args() + below_normal() + return create(a.game_dir, a.out) if a.cmd == "create" else verify(a.game_dir, a.manifest) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/pe_inspect.py b/tools/pe_inspect.py new file mode 100644 index 000000000..381e10ec4 --- /dev/null +++ b/tools/pe_inspect.py @@ -0,0 +1,198 @@ +"""Inspect a PE image (exe or dll) for porting work. + +Usage: + python -I pe_inspect.py [--game-dir DIR] [--out DIR] + +Writes /.json and /.md. Reads the file only; never runs it. +""" +import argparse +import json +import math +import os +import sys +from collections import Counter + +import pefile + +SYSTEM32 = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32") + +MACHINES = {0x8664: "x86-64", 0x14C: "x86", 0xAA64: "ARM64"} +SUBSYSTEMS = {2: "GUI", 3: "Console", 14: "Xbox"} + + +def entropy(data: bytes) -> float: + if not data: + return 0.0 + n = len(data) + return -sum(c / n * math.log2(c / n) for c in Counter(data).values()) + + +_apiset_cache: dict[str, bool] = {} + + +def _apiset_resolves(name: str) -> bool: + """True if this Windows' API-set schema maps the contract to a host DLL (ntdll query; nothing is loaded).""" + if name not in _apiset_cache: + import ctypes + from ctypes import wintypes + + class UNICODE_STRING(ctypes.Structure): + _fields_ = [("Length", wintypes.USHORT), ("MaximumLength", wintypes.USHORT), ("Buffer", wintypes.LPWSTR)] + + query = ctypes.WinDLL("ntdll").ApiSetQueryApiSetPresence + query.argtypes = [ctypes.POINTER(UNICODE_STRING), ctypes.POINTER(ctypes.c_ubyte)] + query.restype = ctypes.c_long + base = name[:-4] if name.lower().endswith(".dll") else name + buf = ctypes.create_unicode_buffer(base) + us = UNICODE_STRING(len(base) * 2, (len(base) + 1) * 2, ctypes.cast(buf, wintypes.LPWSTR)) + present = ctypes.c_ubyte(0) + status = query(ctypes.byref(us), ctypes.byref(present)) + _apiset_cache[name] = status == 0 and bool(present.value) + return _apiset_cache[name] + + +def classify_dll(name: str, game_dir: str | None) -> str: + """bundled = ships beside the game, system = present on this Windows, shim = must be reimplemented.""" + if game_dir and os.path.isfile(os.path.join(game_dir, name)): + return "bundled" + low = name.lower() + if low.startswith("api-ms-win-") or low.startswith("ext-ms-win-"): + # API sets resolve through the OS schema: ask this Windows whether it knows the contract. + return "system" if _apiset_resolves(name) else "shim" + if os.path.isfile(os.path.join(SYSTEM32, name)): + return "system" + return "shim" + + +def inspect(path: str, game_dir: str | None) -> dict: + pe = pefile.PE(path, fast_load=True) + pe.parse_data_directories(directories=[ + pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_IMPORT"], + pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT"], + pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_EXPORT"], + pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_TLS"], + pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_EXCEPTION"], + pefile.DIRECTORY_ENTRY["IMAGE_DIRECTORY_ENTRY_BASERELOC"], + ]) + fh, oh = pe.FILE_HEADER, pe.OPTIONAL_HEADER + + sections = [] + for s in pe.sections: + data = s.get_data() + e = entropy(data) + sections.append({ + "name": s.Name.rstrip(b"\0").decode(errors="replace"), + "rva": s.VirtualAddress, "vsize": s.Misc_VirtualSize, "rawsize": s.SizeOfRawData, + "exec": bool(s.Characteristics & 0x20000000), + "write": bool(s.Characteristics & 0x80000000), + "entropy": round(e, 3), + "looks_encrypted": e > 7.9 and len(data) > 4096, + }) + + imports = [] + for kind, attr in (("normal", "DIRECTORY_ENTRY_IMPORT"), ("delay", "DIRECTORY_ENTRY_DELAY_IMPORT")): + for entry in getattr(pe, attr, []): + dll = entry.dll.decode(errors="replace") + funcs = [(i.name.decode(errors="replace") if i.name else f"#{i.ordinal}") for i in entry.imports] + imports.append({"dll": dll, "kind": kind, "where": classify_dll(dll, game_dir), "functions": funcs}) + + exports = [] + if hasattr(pe, "DIRECTORY_ENTRY_EXPORT"): + exports = [(e.name.decode(errors="replace") if e.name else f"#{e.ordinal}") for e in pe.DIRECTORY_ENTRY_EXPORT.symbols] + + pdata = len(getattr(pe, "DIRECTORY_ENTRY_EXCEPTION", [])) + tls_callbacks = 0 + if hasattr(pe, "DIRECTORY_ENTRY_TLS"): + cb = pe.DIRECTORY_ENTRY_TLS.struct.AddressOfCallBacks + if cb: + rva = cb - oh.ImageBase + while True: + try: + ptr = pe.get_qword_at_rva(rva) + except Exception: + break + if not ptr: + break + tls_callbacks += 1 + rva += 8 + + return { + "file": os.path.basename(path), + "size": os.path.getsize(path), + "machine": MACHINES.get(fh.Machine, hex(fh.Machine)), + "timestamp": fh.TimeDateStamp, + "is_dll": bool(fh.Characteristics & 0x2000), + "subsystem": SUBSYSTEMS.get(oh.Subsystem, oh.Subsystem), + "image_base": hex(oh.ImageBase), + "size_of_image": oh.SizeOfImage, + "entry_rva": hex(oh.AddressOfEntryPoint), + "has_relocs": hasattr(pe, "DIRECTORY_ENTRY_BASERELOC"), + "dynamic_base": bool(oh.DllCharacteristics & 0x40), + "sections": sections, + "imports": imports, + "export_count": len(exports), + "exports": exports, + "pdata_functions": pdata, + "tls_callbacks": tls_callbacks, + } + + +def to_markdown(r: dict) -> str: + out = [f"# {r['file']}", "", + f"- {r['machine']}, {'DLL' if r['is_dll'] else 'EXE'}, subsystem {r['subsystem']}, {r['size']:,} bytes", + f"- image base {r['image_base']}, size {r['size_of_image']:,}, entry RVA {r['entry_rva']}", + f"- relocations: {'yes' if r['has_relocs'] else 'NO (must load at preferred base)'}; " + f"ASLR flag: {r['dynamic_base']}", + f"- .pdata functions: {r['pdata_functions']:,}; TLS callbacks: {r['tls_callbacks']}; exports: {r['export_count']}", + "", "## Sections", "", "| name | rva | vsize | exec | write | entropy | |", "|---|---|---|---|---|---|---|"] + for s in r["sections"]: + flag = "**encrypted?**" if s["looks_encrypted"] else "" + out.append(f"| {s['name']} | {s['rva']:#x} | {s['vsize']:,} | {s['exec']} | {s['write']} | {s['entropy']} | {flag} |") + out += ["", "## Imports", ""] + by_where = Counter() + for imp in r["imports"]: + by_where[imp["where"]] += len(imp["functions"]) + out.append(", ".join(f"{k}: {v}" for k, v in sorted(by_where.items())) or "none") + out += ["", "| dll | kind | resolves | functions |", "|---|---|---|---|"] + for imp in sorted(r["imports"], key=lambda i: (i["where"] != "shim", i["dll"].lower())): + out.append(f"| {imp['dll']} | {imp['kind']} | {imp['where']} | {len(imp['functions'])} |") + shims = [i for i in r["imports"] if i["where"] in ("shim", "apiset")] + if shims: + out += ["", "## Needs checking or a shim", ""] + for imp in shims: + out.append(f"### {imp['dll']} ({imp['where']})") + out.append("") + out.append(", ".join(f"`{f}`" for f in imp["functions"])) + out.append("") + return "\n".join(out) + "\n" + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("image", nargs="+") + ap.add_argument("--game-dir") + ap.add_argument("--out", default=os.path.join(os.path.dirname(__file__), "..", "reports", "pe")) + a = ap.parse_args() + os.makedirs(a.out, exist_ok=True) + rc = 0 + for img in a.image: + try: + r = inspect(img, a.game_dir or os.path.dirname(os.path.abspath(img))) + except pefile.PEFormatError as e: + print(f"{img}: not a PE image ({e})", file=sys.stderr) + rc = 1 + continue + stem = os.path.join(a.out, os.path.splitext(r["file"])[0]) + with open(stem + ".json", "w", encoding="utf-8") as f: + json.dump(r, f, indent=1) + with open(stem + ".md", "w", encoding="utf-8") as f: + f.write(to_markdown(r)) + enc = [s["name"] for s in r["sections"] if s["looks_encrypted"]] + shim = sum(len(i["functions"]) for i in r["imports"] if i["where"] == "shim") + print(f"{r['file']:<40} {r['machine']:<7} subsys={r['subsystem']!s:<7} pdata={r['pdata_functions']:<7} " + f"shim-imports={shim:<5} encrypted={','.join(enc) or '-'}") + return rc + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/rdna2spirv.py b/tools/rdna2spirv.py new file mode 100644 index 000000000..03e594c8e --- /dev/null +++ b/tools/rdna2spirv.py @@ -0,0 +1,3245 @@ +"""RDNA (gfx10) shader -> SPIR-V assembly, version 0. + +Model: one SPIR-V invocation runs one lane. VGPRs and SGPRs are Function-scope uint arrays; float ops bitcast, +so register contents keep exact bit patterns. EXEC is treated as all-ones (valid for branch-free code). + +Supported in v0 (anything else is reported, never guessed): + vector ALU v_mov_b32 v_add/sub/subrev/mul/mul_legacy/fma/fmac/fmaak/fmamk/mac/max/min_f32 v_rcp/rsq/sqrt/ + exp/log/floor/fract/ceil/trunc_f32 v_cvt_f32_u32/i32/ubyte0..3 v_cvt_u32/i32_f32 + v_add/sub_nc_u32 v_and/or/xor_b32 v_lshlrev/lshrrev/ashrrev_i32 v_cndmask_b32 v_mul_u32_u24 + v_bfe_u32 v_med3_f32 v_mad_u32_u24 + scalar s_mov_b32 s_add_u32 s_and_b32 s_or_b32 s_lshl_b32 s_lshr_b32 s_mul_i32 + no-ops s_waitcnt* s_nop s_inst_prefetch s_endpgm s_setprio s_clause s_delay_alu + export exp pos0..3 / param0..31 (vertex) and mrt0..7 (pixel) +Vertex inputs: v0 = VertexIndex (the full-screen-triangle shaders read only that). + +Usage (needs spirv-as/spirv-val on PATH, from the Vulkan SDK or spirv-tools): + python3 -I rdna2spirv.py --out DIR [--limit N] +Writes .spvasm and .spv for each translated shader and prints coverage + validation results. +""" +import argparse +import os +import struct +import subprocess +import sys +from collections import Counter + +sys.path.insert(0, os.path.dirname(__file__)) +from shader_ir import parse_file # noqa: E402 + +# GFX10 buffer format codes (Mesa src/amd/registers/gfx10-rsrc.json, enum GFX10_FORMAT). +import json as _json # noqa: E402 +GFX10_FORMATS = {int(k): v for k, v in _json.load(open(os.path.join(os.path.dirname(__file__), "gfx10_formats.json"))).items()} + +# User SGPRs s0..s(USER_SGPRS-1) are initialised from push constants (128 bytes = Vulkan's guaranteed minimum). +USER_SGPRS = 32 + +NOOPS = {"v_nop", "s_nop", "s_inst_prefetch", "s_endpgm", "s_setprio", "s_clause", "s_delay_alu", "s_waitcnt", + "s_waitcnt_vscnt", "s_waitcnt_vmcnt", "s_waitcnt_expcnt", "s_waitcnt_lgkmcnt", "s_waitcnt_depctr"} + +F2 = {"v_add_f32": "OpFAdd", "v_sub_f32": "OpFSub", "v_mul_f32": "OpFMul", "v_mul_legacy_f32": "OpFMul", + "v_max_f32": "max", "v_min_f32": "min"} +U2 = {"v_add_nc_u32": "OpIAdd", "v_sub_nc_u32": "OpISub", "v_and_b32": "OpBitwiseAnd", "v_or_b32": "OpBitwiseOr", + "v_xor_b32": "OpBitwiseXor", "v_mul_u32_u24": "mul24"} +SHIFT_REV = {"v_lshlrev_b32": "OpShiftLeftLogical", "v_lshrrev_b32": "OpShiftRightLogical", + "v_ashrrev_i32": "OpShiftRightArithmetic"} +F1 = {"v_rcp_f32": "rcp", "v_rsq_f32": "InverseSqrt", "v_sqrt_f32": "Sqrt", "v_exp_f32": "Exp2", + "v_log_f32": "Log2", "v_floor_f32": "Floor", "v_fract_f32": "Fract", "v_ceil_f32": "Ceil", + "v_trunc_f32": "Trunc"} +S2 = {"s_and_b32": "OpBitwiseAnd", "s_or_b32": "OpBitwiseOr", + "s_lshl_b32": "OpShiftLeftLogical", "s_lshr_b32": "OpShiftRightLogical", "s_mul_i32": "OpIMul"} + + +def base_op(op): + for suf in ("_e32", "_e64", "_sdwa", "_dpp"): + if op.endswith(suf): + return op[: -len(suf)] + return op + + +class Unsupported(Exception): + pass + + +class Gen: + def __init__(self, stage): + self.stage = stage + self.body = [] + self.consts = {} + self.n = 0 + self.outputs = {} + self.inputs = {} + self.uses_psb = False + self.uses_active = False + self.uses_tex = False + self.uses_subgroup = False + self.uses_tex_array = False + self.uses_storage = False + self.uses_query = False + self.uses_tex_1d = False + self.uses_tex_3d = False + self.uses_v4uint = False + self.writes_depth = False + self.uses_smul = False + self.uses_minlod = False + self.uses_storage3d = False + self.uses_heap = False + self.uses_codebase = False + self.uses_long = False + self.vertex_inputs = [] # (D3D input register, component type 1=uint 2=sint 3=float) for fetch-calling VS + self.frag_inputs = {} # PS: VGPR -> gl_FragCoord component, from the verified system-VGPR layout + self.blocks = [] # per basic block: list of SPIR-V lines (dispatch-loop form), empty = straight-line + self.block_label = "%entry" # label of the SPIR-V block the current instruction starts in + + def tmp(self): + self.n += 1 + return f"%t{self.n}" + + def cu(self, v): + v &= 0xFFFFFFFF + if v not in self.consts: + self.consts[v] = f"%c{v:x}" + return self.consts[v] + + def emit(self, s): + self.body.append(" " + s) + + # ---- register access ---- + def load_reg(self, kind, r): + arr = "%vgpr" if kind == "vgpr" else "%sgpr" + p, t = self.tmp(), self.tmp() + self.emit(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {self.cu(r)}") + self.emit(f"{t} = OpLoad %uint {p}") + return t + + def store_reg(self, kind, r, val): + arr = "%vgpr" if kind == "vgpr" else "%sgpr" + p = self.tmp() + self.emit(f"{p} = OpAccessChain %_ptr_Function_uint {arr} {self.cu(r)}") + self.emit(f"OpStore {p} {val}") + + def src_u(self, a): + k = a["k"] + if k in ("vgpr", "sgpr"): + if a.get("n", 1) != 1: + raise Unsupported("64-bit operand") + v = self.load_reg(k, a["r"]) + elif k == "special" and a["t"] == "null": + v = self.cu(0) # RDNA 'null' source reads as zero (e.g. soffset) + elif k == "special" and a["t"] in ("exec_lo", "exec", "exec_hi"): + v = self.exec_value() + elif k == "special" and a["t"] == "m0": + v = self.tmp() + self.emit(f"{v} = OpLoad %uint %m0") + elif k == "special" and a["t"] == "vcc_hi": + # wave32: vcc_hi is an ordinary SGPR (the lane mask lives in vcc_lo). + v = self.tmp() + self.emit(f"{v} = OpLoad %uint %vcc_hi") + elif k == "special" and a["t"] == "scc": + v = self.tmp() + self.emit(f"{v} = OpLoad %uint %scc") + elif k == "imm": + v = self.cu(a["v"]) + elif k == "fimm": + v = self.cu(struct.unpack(" f16 bits (low 16) with round-toward-zero, as v_cvt_pkrtz does: pack to nearest, and if that + rounded away from zero (|half| > |x|), step one f16 ulp back toward zero. Inf/NaN inputs keep the nearest + result (inf/NaN). Finite values above the f16 range become +-65504, never inf.""" + v2, p, lo, back2, back, ab, ax, gt, fin, nz, dec, r = (self.tmp() for _ in range(12)) + self.emit(f"{v2} = OpCompositeConstruct %v2float {f} %f0") + self.emit(f"{p} = OpExtInst %uint %glsl PackHalf2x16 {v2}") + self.emit(f"{lo} = OpBitwiseAnd %uint {p} {self.cu(0xFFFF)}") + self.emit(f"{back2} = OpExtInst %v2float %glsl UnpackHalf2x16 {lo}") + self.emit(f"{back} = OpCompositeExtract %float {back2} 0") + self.emit(f"{ab} = OpExtInst %float %glsl FAbs {back}") + self.emit(f"{ax} = OpExtInst %float %glsl FAbs {f}") + self.emit(f"{gt} = OpFOrdGreaterThan %bool {ab} {ax}") # false for NaN + isinf, isnan = self.tmp(), self.tmp() + self.emit(f"{isinf} = OpIsInf %bool {f}") + self.emit(f"{isnan} = OpIsNan %bool {f}") + special = self.tmp() + self.emit(f"{special} = OpLogicalOr %bool {isinf} {isnan}") + self.emit(f"{fin} = OpLogicalNot %bool {special}") + self.emit(f"{nz} = OpLogicalAnd %bool {gt} {fin}") + self.emit(f"{dec} = OpISub %uint {lo} {self.cu(1)}") # magnitude bits - 1 = one ulp toward zero + self.emit(f"{r} = OpSelect %uint {nz} {dec} {lo}") + return r + + def modify_f(self, f, a): + return self.tof(self.modify(self.tou(f), a)) + + def host_addr(self, xbox_va): + """Xbox GPU virtual address (ulong id) -> host buffer device address: heap base (push constant + dwords 32..33) + VA. The runtime maps the console's GPU address window into one host buffer.""" + lo, hi, l64, h64, sh, base, r = (self.tmp() for _ in range(7)) + self.emit(f"{lo} = OpLoad %uint %ud_base_lo_p") + self.emit(f"{hi} = OpLoad %uint %ud_base_hi_p") + self.emit(f"{l64} = OpUConvert %ulong {lo}") + self.emit(f"{h64} = OpUConvert %ulong {hi}") + self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") + self.emit(f"{base} = OpBitwiseOr %ulong {sh} {l64}") + self.emit(f"{r} = OpIAdd %ulong {base} {xbox_va}") + self.uses_heap = True + self.cu(1), self.cu(2) # member indices of the push-constant block, declared before assembly + return r + + def tof(self, u): + f = self.tmp() + self.emit(f"{f} = OpBitcast %float {u}") + return f + + def tou(self, f): + u = self.tmp() + self.emit(f"{u} = OpBitcast %uint {f}") + return u + + def src_f(self, a): + return self.tof(self.src_u(a)) + + # ---- EXEC (this lane's active bit) ---- + def active_b(self): + b = self.tmp() + self.emit(f"{b} = OpLoad %bool %active") + return b + + def exec_value(self): + """EXEC as a lane mask for this invocation: all-ones if active, else 0.""" + r = self.tmp() + self.emit(f"{r} = OpSelect %uint {self.active_b()} {self.cu(0xFFFFFFFF)} {self.cu(0)}") + return r + + def set_exec(self, mask_u): + self.emit(f"OpStore %active {self.tmp_bool_nz(mask_u)}") + self.uses_active = True + + def dst(self, a, val): + if a["k"] == "special" and a["t"] == "null": + return # result discarded + if a["k"] == "special" and a["t"] in ("exec_lo", "exec"): + self.set_exec(val) + return + if a["k"] == "vgpr" and a.get("n", 1) == 1: + # VALU writes only land in active lanes. + p, old, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{p} = OpAccessChain %_ptr_Function_uint %vgpr {self.cu(a['r'])}") + self.emit(f"{old} = OpLoad %uint {p}") + self.emit(f"{r} = OpSelect %uint {self.active_b()} {val} {old}") + self.emit(f"OpStore {p} {r}") + elif a["k"] == "sgpr" and a.get("n", 1) == 1: + self.store_reg(a["k"], a["r"], val) + elif a["k"] == "special" and a["t"] in ("vcc_lo", "vcc"): + self.emit(f"OpStore %vcc {val}") + elif a["k"] == "special" and a["t"] == "m0": + self.emit(f"OpStore %m0 {val}") + elif a["k"] == "special" and a["t"] == "vcc_hi": + self.emit(f"OpStore %vcc_hi {val}") + elif a["k"] == "special" and a["t"] == "scc": + self.emit(f"OpStore %scc {val}") + else: + raise Unsupported(f"destination {a.get('t', a['k'])}") + + def mov64(self, d, s): + """64-bit scalar move, including EXEC save/restore (EXEC = this lane's active bit).""" + if d["k"] == "special" and d["t"] == "exec": + self.set_exec(self.mask_src(s)) + return + if d["k"] == "special" and d["t"] in ("vcc", "vcc_lo"): + self.emit(f"OpStore %vcc {self.mask_src(s)}") + return + if d["k"] != "sgpr" or d.get("n") != 2: + raise Unsupported("s_mov_b64 destination") + if s["k"] == "special" and s["t"] == "exec": + lo = hi = self.exec_value() + elif s["k"] == "sgpr" and s.get("n") == 2: + lo, hi = self.load_reg("sgpr", s["r"]), self.load_reg("sgpr", s["r"] + 1) + elif s["k"] == "imm": + v = s["v"] & 0xFFFFFFFFFFFFFFFF + if s["v"] < 0: + v = s["v"] & 0xFFFFFFFFFFFFFFFF + lo, hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) + elif s["k"] == "special" and s["t"] == "vcc": + lo = self.tmp() + self.emit(f"{lo} = OpLoad %uint %vcc") + hi = self.cu(0) + else: + raise Unsupported("s_mov_b64 source") + self.store_reg("sgpr", d["r"], lo) + self.store_reg("sgpr", d["r"] + 1, hi) + + def compare(self, op, a, scalar, exec_only=False): + """v_cmp_* / s_cmp_*: lane result into VCC/SGPR mask (vector), SCC (scalar), or EXEC (v_cmpx).""" + parts = op.split("_") # v_cmp_lt_f32 / s_cmp_eq_u32 + cond, ty = parts[2], parts[3] + srcs = a[0:2] if scalar else a[-2:] + dst = None if (scalar or exec_only) else a[0] + if ty in ("f32", "f16"): + if ty == "f32": + x, y = self.src_f(srcs[0]), self.src_f(srcs[1]) + else: # f16 compare: the low half of each source, compared as f32 (exact for f16 values) + vals = [] + for s in srcs: + u = self.src_u({**s, "neg": False, "abs": False}) + v2, f = self.tmp(), self.tmp() + self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") + self.emit(f"{f} = OpCompositeExtract %float {v2} 0") + vals.append(self.modify_f(f, s)) + x, y = vals + ops = {"lt": "OpFOrdLessThan", "le": "OpFOrdLessThanEqual", "gt": "OpFOrdGreaterThan", + "ge": "OpFOrdGreaterThanEqual", "eq": "OpFOrdEqual", "neq": "OpFUnordNotEqual", + "lg": "OpFOrdNotEqual", "nlt": "OpFUnordGreaterThanEqual", "ngt": "OpFUnordLessThanEqual", + "nle": "OpFUnordGreaterThan", "nge": "OpFUnordLessThan"} + elif ty in ("u32", "i32"): + x, y = self.src_u(srcs[0]), self.src_u(srcs[1]) + if ty == "i32": + x, y = self.as_int(x), self.as_int(y) + s = ty == "i32" + ops = {"lt": "OpSLessThan" if s else "OpULessThan", "le": "OpSLessThanEqual" if s else "OpULessThanEqual", + "gt": "OpSGreaterThan" if s else "OpUGreaterThan", + "ge": "OpSGreaterThanEqual" if s else "OpUGreaterThanEqual", + "eq": "OpIEqual", "ne": "OpINotEqual", "lg": "OpINotEqual"} + else: + raise Unsupported(op) + if cond not in ops: + raise Unsupported(op) + b, r = self.tmp(), self.tmp() + self.emit(f"{b} = {ops[cond]} %bool {x} {y}") + # Lane masks are all-ones/zero per invocation (one lane), SCC is 1/0. + self.emit(f"{r} = OpSelect %uint {b} {self.cu(1 if scalar else 0xFFFFFFFF)} {self.cu(0)}") + if scalar: + self.emit(f"OpStore %scc {r}") + elif dst is None: # v_cmpx: EXEC &= cond + a2 = self.tmp() + self.emit(f"{a2} = OpLoad %bool %active") + a3 = self.tmp() + self.emit(f"{a3} = OpLogicalAnd %bool {a2} {b}") + self.emit(f"OpStore %active {a3}") + self.uses_active = True + elif dst["k"] == "special" and dst["t"] in ("vcc", "vcc_lo"): + self.emit(f"OpStore %vcc {r}") + elif dst["k"] == "sgpr": + self.store_reg("sgpr", dst["r"], r) + if dst.get("n") == 2: + self.store_reg("sgpr", dst["r"] + 1, r) + else: + raise Unsupported("v_cmp destination") + + def compare_x(self, op, a): + """v_cmpx_*: like v_cmp but the result ANDs into EXEC. e32 form has only the two sources; e64 also names + a destination (vcc/sgpr) which gets the compare result too.""" + srcs = a[-2:] + self.compare("v_cmp_" + op[len("v_cmpx_"):], [None] + list(srcs), scalar=False, exec_only=True) + + def swizzle(self, a, mods, ins): + """ds_swizzle_b32 vD, vS offset:swizzle(...): a subgroup shuffle (one invocation per lane).""" + line = " ".join(m for m in mods) + " " + " ".join(x.get("t", "") for x in a if x["k"] in ("special", "raw")) + import re as _re + m = _re.search(r"swizzle\((\w+)((?:,\s*\d+)*)\)", line + " " + str(ins.get("raw", ""))) + if not m: + raise Unsupported("ds_swizzle pattern") + kind = m.group(1) + args = [int(x) for x in m.group(2).split(",")[1:]] if m.group(2) else [] + self.uses_subgroup = True + lane = self.tmp() + self.emit(f"{lane} = OpLoad %uint %sg_lane") + if kind == "QUAD_PERM": + sel, base, src = self.tmp(), self.tmp(), self.cu(0) + self.emit(f"{sel} = OpBitwiseAnd %uint {lane} {self.cu(3)}") + self.emit(f"{base} = OpBitwiseAnd %uint {lane} {self.cu(0xFFFFFFFC)}") + pick = self.cu(args[0]) + for i in (1, 2, 3): + e, nxt = self.tmp(), self.tmp() + self.emit(f"{e} = OpIEqual %bool {sel} {self.cu(i)}") + self.emit(f"{nxt} = OpSelect %uint {e} {self.cu(args[i])} {pick}") + pick = nxt + src = self.tmp() + self.emit(f"{src} = OpBitwiseOr %uint {base} {pick}") + elif kind == "SWAP": + src = self.tmp() + self.emit(f"{src} = OpBitwiseXor %uint {lane} {self.cu(args[0])}") + elif kind == "REVERSE": + src = self.tmp() + self.emit(f"{src} = OpBitwiseXor %uint {lane} {self.cu(args[0] - 1)}") + elif kind == "BROADCAST": + src, keep = self.tmp(), self.tmp() + self.emit(f"{keep} = OpBitwiseAnd %uint {lane} {self.cu(~(args[0] - 1) & 0xFFFFFFFF)}") + self.emit(f"{src} = OpBitwiseOr %uint {keep} {self.cu(args[1])}") + else: + raise Unsupported("ds_swizzle " + kind) + v, r = self.src_u(a[1]), self.tmp() + self.emit(f"{r} = OpGroupNonUniformShuffle %uint %c3 {v} {src}") + self.dst(a[0], r) + + def buffer_load(self, op, a, mods): + """buffer_load_dword[xN] vD, vaddr, s[V#], soffset [offen|idxen] offset:N -> buffer-device-address loads. + addr = V#.base + soffset + inst_offset + (offen ? vaddr : 0) + (idxen ? vindex * V#.stride : 0).""" + if any(m in mods for m in ("lds", "tfe")) or "format" in op: + raise Unsupported(op + " form") + n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) + vd, vaddr, rsrc, soff = a[0], a[1], a[2], a[3] if len(a) > 3 else {"k": "imm", "v": 0} + if rsrc["k"] != "sgpr" or rsrc.get("n") != 4: + raise Unsupported("buffer_load V#") + d0, d1 = self.load_reg("sgpr", rsrc["r"]), self.load_reg("sgpr", rsrc["r"] + 1) + hi, stride = self.tmp(), self.tmp() + self.emit(f"{hi} = OpBitwiseAnd %uint {d1} {self.cu(0xFFFF)}") + self.emit(f"{stride} = OpBitFieldUExtract %uint {d1} {self.cu(16)} {self.cu(14)}") + off = self.src_u(soff) + inst = next((int(m.split(":")[1], 0) for m in mods if m.startswith("offset:")), 0) + total = self.tmp() + self.emit(f"{total} = OpIAdd %uint {off} {self.cu(inst)}") + offen, idxen = "offen" in mods, "idxen" in mods + vregs = [] if vaddr["k"] == "special" else [vaddr["r"] + i for i in range(vaddr.get("n", 1))] + if idxen: + idx = self.load_reg("vgpr", vregs[0]) + m, t = self.tmp(), self.tmp() + self.emit(f"{m} = OpIMul %uint {idx} {stride}") + self.emit(f"{t} = OpIAdd %uint {total} {m}") + total = t + if offen: + o = self.load_reg("vgpr", vregs[1] if idxen else vregs[0]) + t = self.tmp() + self.emit(f"{t} = OpIAdd %uint {total} {o}") + total = t + l64, h64, sh, addr, o64, full, ptr = (self.tmp() for _ in range(7)) + self.emit(f"{l64} = OpUConvert %ulong {d0}") + self.emit(f"{h64} = OpUConvert %ulong {hi}") + self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") + self.emit(f"{addr} = OpBitwiseOr %ulong {sh} {l64}") + self.emit(f"{o64} = OpUConvert %ulong {total}") + self.emit(f"{full} = OpIAdd %ulong {addr} {o64}") + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") + self.uses_psb = True + for i in range(n): + p, v = self.tmp(), self.tmp() + self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") + self.emit(f"{v} = OpLoad %uint {p} Aligned 4") + self.dst({"k": "vgpr", "r": vd["r"] + i, "n": 1}, v) + + # GFX10 buffer formats (from Mesa src/amd/registers/gfx10-rsrc.json, GFX10_FORMAT): + # code: (bytes, kind, component bit widths) + FORMATS = {22: (4, "f32", (32,)), 64: (8, "f32", (32, 32)), 74: (12, "f32", (32, 32, 32)), + 77: (16, "f32", (32, 32, 32, 32)), 20: (4, "u32", (32,)), 62: (8, "u32", (32, 32)), + 75: (16, "u32", (32, 32, 32, 32)), 13: (2, "f16", (16,)), 29: (4, "f16", (16, 16)), + 71: (8, "f16", (16, 16, 16, 16)), 1: (1, "unorm", (8,)), 14: (2, "unorm", (8, 8)), + 56: (4, "unorm", (8, 8, 8, 8)), 57: (4, "snorm", (8, 8, 8, 8)), 60: (4, "uint", (8, 8, 8, 8)), + 7: (2, "unorm", (16,)), 23: (4, "unorm", (16, 16)), 24: (4, "snorm", (16, 16)), + 65: (8, "unorm", (16, 16, 16, 16)), 66: (8, "snorm", (16, 16, 16, 16)), + 44: (4, "unorm", (10, 10, 10, 2)), 50: (4, "unorm", (2, 10, 10, 10)), + 69: (8, "uint", (16, 16, 16, 16)), 27: (4, "uint", (16, 16))} + + def decode_format(self, words, code): + """Decode one element of format `code` from raw dwords -> 4 uint ids holding f32 bits (or uint for *_UINT/uint).""" + size, kind, widths = self.FORMATS[code] + if kind in ("f32", "u32"): + vals = list(words[:len(widths)]) + if kind == "u32": + vals = vals # integers are passed through as their bits + return vals + [self.cu(0)] * (3 - len(vals) + 1 if len(vals) < 4 else 0) + out, bit = [], 0 + for w in widths: + src = words[bit // 32] + f = self.tmp() + self.emit(f"{f} = OpBitFieldUExtract %uint {src} {self.cu(bit % 32)} {self.cu(w)}") + if kind == "f16": + v2, x = self.tmp(), self.tmp() + self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {f}") + self.emit(f"{x} = OpCompositeExtract %float {v2} 0") + out.append(self.tou(x)) + elif kind == "unorm": + c, x = self.tmp(), self.tmp() + self.emit(f"{c} = OpConvertUToF %float {f}") + self.emit(f"{x} = OpFMul %float {c} {self.fconst(1.0 / ((1 << w) - 1))}") + out.append(self.tou(x)) + elif kind == "snorm": + si, c, x, cl = self.tmp(), self.tmp(), self.tmp(), self.tmp() + self.emit(f"{si} = OpBitFieldSExtract %int {self.as_int(src)} {self.cu(bit % 32)} {self.cu(w)}") + self.emit(f"{c} = OpConvertSToF %float {si}") + self.emit(f"{x} = OpFMul %float {c} {self.fconst(1.0 / ((1 << (w - 1)) - 1))}") + self.emit(f"{cl} = OpExtInst %float %glsl FMax {x} {self.fconst(-1.0)}") + out.append(self.tou(cl)) + else: # uint: raw integer + out.append(f) + bit += w + one = self.cu(0x3F800000) if kind in ("f16", "unorm", "snorm") else self.cu(1) + while len(out) < 4: + out.append(self.cu(0) if len(out) < 3 else one) + return out + + BUF_ATOMICS = {"add": ("OpAtomicIAdd", 0), "sub": ("OpAtomicISub", 0), "umin": ("OpAtomicUMin", 0xFFFFFFFF), + "umax": ("OpAtomicUMax", 0), "smin": ("OpAtomicSMin", 0x7FFFFFFF), "smax": ("OpAtomicSMax", 0x80000000), + "and": ("OpAtomicAnd", 0xFFFFFFFF), "or": ("OpAtomicOr", 0), "xor": ("OpAtomicXor", 0), + "swap": ("OpAtomicExchange", None), "cmpswap": ("OpAtomicCompareExchange", None)} + + def buffer_atomic(self, op, a, mods): + """buffer_atomic_ vdata, vaddr, s[V#], soffset ...: 32-bit atomic at the element address (buffer device + address). With 'glc' the pre-op value is returned in vdata. Inactive lanes don't touch memory.""" + kind = op[len("buffer_atomic_"):] + if kind not in self.BUF_ATOMICS or "x2" in kind: + raise Unsupported(op) + spv, neutral = self.BUF_ATOMICS[kind] + addr, _ = self.buffer_address(a, mods) + vd = a[0] + ptr, p = self.tmp(), self.tmp() + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") + self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") + val = self.load_reg("vgpr", vd["r"]) + act = self.active_b() + if neutral is not None: + safe, old = self.tmp(), self.tmp() + self.emit(f"{safe} = OpSelect %uint {act} {val} {self.cu(neutral)}") + self.emit(f"{old} = {spv} %uint {p} {self.cu(1)} {self.cu(0)} {safe}") + else: + # swap/cmpswap have no neutral operand: guard with a structured if and merge the result. + lbl_do, lbl_end, res_do, old = self.tmp() + "_do", self.tmp() + "_end", self.tmp(), self.tmp() + cur = self.tmp() + self.emit(f"{cur} = OpLoad %uint {p} Aligned 4") + self.emit(f"OpSelectionMerge {lbl_end} None") + self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") + pre_label = self.current_label_placeholder() + self.emit(f"{lbl_do} = OpLabel") + if kind == "cmpswap": + cmp = self.load_reg("vgpr", vd["r"] + 1) + self.emit(f"{res_do} = OpAtomicCompareExchange %uint {p} {self.cu(1)} {self.cu(0)} {self.cu(0)} {val} {cmp}") + else: + self.emit(f"{res_do} = OpAtomicExchange %uint {p} {self.cu(1)} {self.cu(0)} {val}") + self.emit(f"OpBranch {lbl_end}") + self.emit(f"{lbl_end} = OpLabel") + self.emit(f"{old} = OpPhi %uint {res_do} {lbl_do} {cur} {pre_label}") + if "glc" in mods: + self.dst({"k": "vgpr", "r": vd["r"], "n": 1}, old) + + def current_label_placeholder(self): + """Label of the block currently being emitted (needed for OpPhi). Blocks are opened by OpLabel lines.""" + for line in reversed(self.body): + s = line.strip() + if s.endswith("= OpLabel"): + return s.split(" = ")[0] + return self.block_label + + def image_get_lod(self, a, mods): + """image_get_lod vD, vaddr, T#, S#: (clamped lod, unclamped lod) like OpImageQueryLod (2D).""" + dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D") + if dim != "dim:SQ_RSRC_IMG_2D" or self.stage != "ps" or "a16" in mods: + raise Unsupported("image_get_lod form") + dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x3") + dmask = int(dm.split(":")[1], 0) + vdata, addr = a[0], self.addr_regs(a[1]) + img_idx = self.desc_lookup(self.sgpr_words(a[2], 8)) + smp_idx = self.desc_lookup(self.sgpr_words(a[3], 4) + [self.cu(0xFFFFFFFF)] * 4) + ip, img, sp, smp, si = (self.tmp() for _ in range(5)) + self.emit(f"{ip} = OpAccessChain %_ptr_UC_img %images {img_idx}") + self.emit(f"{img} = OpLoad %img2d {ip}") + self.emit(f"{sp} = OpAccessChain %_ptr_UC_smp %samplers {smp_idx}") + self.emit(f"{smp} = OpLoad %smp {sp}") + self.emit(f"{si} = OpSampledImage %simg2d {img} {smp}") + f = [self.tof(self.load_reg("vgpr", r)) for r in addr[:2]] + uv, lod = self.tmp(), self.tmp() + self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") + self.emit(f"{lod} = OpImageQueryLod %v2float {si} {uv}") + self.uses_query = True + out = 0 + for c in range(2): + if dmask >> c & 1: + comp = self.tmp() + self.emit(f"{comp} = OpCompositeExtract %float {lod} {c}") + self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, self.tou(comp)) + out += 1 + + def buffer_load_format(self, op, a, mods, fixed_fmt=None): + """buffer_load_format_[x|xy|xyz|xyzw]: element at V#.base + offsets, decoded per the V# FORMAT field + (word3 bits 12-18), then swizzled by DST_SEL_X/Y/Z/W (word3 bits 0-11: 0=0, 1=1, 4..7 = X..W). + Formats outside FORMATS decode to 0. num_records bounds checking isn't modelled.""" + if any(m in mods for m in ("lds", "tfe", "d16")): + raise Unsupported(op + " form") + ncomp = len(op.rsplit("_", 1)[1]) + vd, vaddr, rsrc = a[0], a[1], a[2] + soff = a[3] if len(a) > 3 else {"k": "imm", "v": 0} + if rsrc["k"] != "sgpr" or rsrc.get("n") != 4: + raise Unsupported("buffer_load_format V#") + d0, d1, d3 = (self.load_reg("sgpr", rsrc["r"] + i) for i in (0, 1, 3)) + hi, stride = self.tmp(), self.tmp() + self.emit(f"{hi} = OpBitwiseAnd %uint {d1} {self.cu(0xFFFF)}") + self.emit(f"{stride} = OpBitFieldUExtract %uint {d1} {self.cu(16)} {self.cu(14)}") + if fixed_fmt is not None: + fmt = self.cu(fixed_fmt) # tbuffer: format from the instruction + else: + fmt = self.tmp() + self.emit(f"{fmt} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}") + inst = next((int(m.split(":")[1], 0) for m in mods if m.startswith("offset:")), 0) + total = self.tmp() + self.emit(f"{total} = OpIAdd %uint {self.src_u(soff)} {self.cu(inst)}") + vregs = [] if vaddr["k"] == "special" else [vaddr["r"] + i for i in range(vaddr.get("n", 1))] + if "idxen" in mods: + idx = self.load_reg("vgpr", vregs[0]) + m, t = self.tmp(), self.tmp() + self.emit(f"{m} = OpIMul %uint {idx} {stride}") + self.emit(f"{t} = OpIAdd %uint {total} {m}") + total = t + if "offen" in mods: + o = self.load_reg("vgpr", vregs[1] if "idxen" in mods else vregs[0]) + t = self.tmp() + self.emit(f"{t} = OpIAdd %uint {total} {o}") + total = t + self.uses_psb = True + l64, h64, sh, base = self.tmp(), self.tmp(), self.tmp(), self.tmp() + self.emit(f"{l64} = OpUConvert %ulong {d0}") + self.emit(f"{h64} = OpUConvert %ulong {hi}") + self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") + self.emit(f"{base} = OpBitwiseOr %ulong {sh} {l64}") + # Byte address of the element, split into a dword-aligned address and a byte shift (for 1/2-byte formats). + o64, addr, alo = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{o64} = OpUConvert %ulong {total}") + self.emit(f"{addr} = OpIAdd %ulong {base} {o64}") + self.emit(f"{alo} = OpUConvert %uint {addr}") + bsh, al64, aligned = self.tmp(), self.tmp(), self.tmp() + b3 = self.tmp() + self.emit(f"{b3} = OpBitwiseAnd %uint {alo} {self.cu(3)}") + self.emit(f"{bsh} = OpIMul %uint {b3} {self.cu(8)}") + self.emit(f"{al64} = OpUConvert %ulong {b3}") + self.emit(f"{aligned} = OpISub %ulong {addr} {al64}") + # How many dwords this element needs, by format (others: 1). Extra loads re-read dword 0, so a load never + # goes past the element (the last element of a buffer stays in bounds). + need = self.cu(1) + for code, (size, _, _) in self.FORMATS.items(): + e, n2 = self.tmp(), self.tmp() + self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}") + self.emit(f"{n2} = OpSelect %uint {e} {self.cu(max(1, (size + 3) // 4))} {need}") + need = n2 + ptr = self.tmp() + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(aligned)}") + words = [] + for i in range(4): + ok, idx, p, v = self.tmp(), self.tmp(), self.tmp(), self.tmp() + self.emit(f"{ok} = OpULessThan %bool {self.cu(i)} {need}") + self.emit(f"{idx} = OpSelect %uint {ok} {self.cu(i)} {self.cu(0)}") + self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {idx}") + self.emit(f"{v} = OpLoad %uint {p} Aligned 4") + words.append(v) + # Sub-dword formats start at the byte shift inside dword 0 (and may spill into dword 1). + w0s, w1s, nz, w1sh, merged, bw0 = (self.tmp() for _ in range(6)) + self.emit(f"{w0s} = OpShiftRightLogical %uint {words[0]} {bsh}") + self.emit(f"{w1sh} = OpISub %uint {self.cu(32)} {bsh}") + self.emit(f"{w1s} = OpShiftLeftLogical %uint {words[1]} {w1sh}") + self.emit(f"{nz} = OpINotEqual %bool {bsh} {self.cu(0)}") + self.emit(f"{merged} = OpBitwiseOr %uint {w0s} {w1s}") + self.emit(f"{bw0} = OpSelect %uint {nz} {merged} {words[0]}") + words = [bw0] + words[1:] + # Decode every supported format, then pick by FORMAT. + comps = [self.cu(0)] * 4 + for code in self.FORMATS: + dec = self.decode_format(words, code) + e = self.tmp() + self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}") + nxt = [] + for c in range(4): + s = self.tmp() + self.emit(f"{s} = OpSelect %uint {e} {dec[c]} {comps[c]}") + nxt.append(s) + comps = nxt + # DST_SEL swizzle: 0 -> 0, 1 -> 1.0, 4..7 -> X..W. + for c in range(ncomp): + sel = self.tmp() + self.emit(f"{sel} = OpBitFieldUExtract %uint {d3} {self.cu(3 * c)} {self.cu(3)}") + r = self.cu(0) + for code_v, src in ((1, self.cu(0x3F800000)), (4, comps[0]), (5, comps[1]), (6, comps[2]), (7, comps[3])): + e, s = self.tmp(), self.tmp() + self.emit(f"{e} = OpIEqual %bool {sel} {self.cu(code_v)}") + self.emit(f"{s} = OpSelect %uint {e} {src} {r}") + r = s + self.dst({"k": "vgpr", "r": vd["r"] + c, "n": 1}, r) + + def global_mem(self, op, a, mods): + """global_load_dword[xN] vD, vaddr, saddr|off offset:N / global_store_dword[xN] vaddr, vD, saddr|off. + Address = (saddr: 64-bit SGPR pair + zero-extended 32-bit vaddr | off: 64-bit VGPR pair) + offset, + an Xbox GPU VA translated through the heap base. Stores and loads only take effect in active lanes.""" + load = op.startswith("global_load") + if any(m in mods for m in ("lds", "tfe", "d16")): + raise Unsupported(op + " form") + n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) + data, vaddr, saddr = (a[0], a[1], a[2]) if load else (a[1], a[0], a[2]) + inst = next((int(m.split(":")[1], 0) for m in mods if m.startswith("offset:")), 0) + if inst & 0x800: + inst -= 0x1000 # 12-bit signed offset + if saddr["k"] == "sgpr" and saddr.get("n") == 2: + lo, hi = self.load_reg("sgpr", saddr["r"]), self.load_reg("sgpr", saddr["r"] + 1) + voff = self.load_reg("vgpr", vaddr["r"]) + l64, h64, sh, base, v64, va = (self.tmp() for _ in range(6)) + self.emit(f"{l64} = OpUConvert %ulong {lo}") + self.emit(f"{h64} = OpUConvert %ulong {hi}") + self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") + self.emit(f"{base} = OpBitwiseOr %ulong {sh} {l64}") + self.emit(f"{v64} = OpUConvert %ulong {voff}") + self.emit(f"{va} = OpIAdd %ulong {base} {v64}") + elif saddr["k"] == "special" and saddr["t"] == "off" and vaddr["k"] == "vgpr" and vaddr.get("n") == 2: + lo, hi = self.load_reg("vgpr", vaddr["r"]), self.load_reg("vgpr", vaddr["r"] + 1) + l64, h64, sh, va = (self.tmp() for _ in range(4)) + self.emit(f"{l64} = OpUConvert %ulong {lo}") + self.emit(f"{h64} = OpUConvert %ulong {hi}") + self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") + self.emit(f"{va} = OpBitwiseOr %ulong {sh} {l64}") + else: + raise Unsupported(op + " addressing") + self.uses_psb = True + off64, full = self.tmp(), self.tmp() + ioff = self.tmp() + self.emit(f"{ioff} = OpBitcast %uint {self.as_int(self.cu(inst & 0xFFFFFFFF))}") + self.emit(f"{off64} = OpSConvert %long {self.as_int(ioff)}") + o2 = self.tmp() + self.emit(f"{o2} = OpBitcast %ulong {off64}") + self.emit(f"{full} = OpIAdd %ulong {va} {o2}") + self.uses_long = True + act = self.active_b() + lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" + if load: + # Inactive lanes don't load (and keep their registers): guard the access, merge with OpPhi per dword. + olds = [self.load_reg("vgpr", data["r"] + i) for i in range(n)] + pre = self.current_label_placeholder() + self.emit(f"OpSelectionMerge {lbl_end} None") + self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") + self.emit(f"{lbl_do} = OpLabel") + ptr = self.tmp() + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") + vals = [] + for i in range(n): + p, v = self.tmp(), self.tmp() + self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") + self.emit(f"{v} = OpLoad %uint {p} Aligned 4") + vals.append(v) + self.emit(f"OpBranch {lbl_end}") + self.emit(f"{lbl_end} = OpLabel") + phis = [] + for i in range(n): # all OpPhi first: they must open the merge block + ph = self.tmp() + self.emit(f"{ph} = OpPhi %uint {vals[i]} {lbl_do} {olds[i]} {pre}") + phis.append(ph) + for i, ph in enumerate(phis): + self.store_reg("vgpr", data["r"] + i, ph) + else: + vals = [self.load_reg("vgpr", data["r"] + i) for i in range(n)] + self.emit(f"OpSelectionMerge {lbl_end} None") + self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") + self.emit(f"{lbl_do} = OpLabel") + ptr = self.tmp() + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") + for i in range(n): + p = self.tmp() + self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") + self.emit(f"OpStore {p} {vals[i]} Aligned 4") + self.emit(f"OpBranch {lbl_end}") + self.emit(f"{lbl_end} = OpLabel") + + def buffer_address(self, a, mods): + """(64-bit element address id, V# word3 id) for a MUBUF instruction: vdata, vaddr, srsrc, soffset.""" + vaddr, rsrc = a[1], a[2] + soff = a[3] if len(a) > 3 else {"k": "imm", "v": 0} + if rsrc["k"] != "sgpr" or rsrc.get("n") != 4: + raise Unsupported("buffer V#") + d0, d1, d3 = (self.load_reg("sgpr", rsrc["r"] + i) for i in (0, 1, 3)) + hi, stride = self.tmp(), self.tmp() + self.emit(f"{hi} = OpBitwiseAnd %uint {d1} {self.cu(0xFFFF)}") + self.emit(f"{stride} = OpBitFieldUExtract %uint {d1} {self.cu(16)} {self.cu(14)}") + inst = next((int(m.split(":")[1], 0) for m in mods if m.startswith("offset:")), 0) + total = self.tmp() + self.emit(f"{total} = OpIAdd %uint {self.src_u(soff)} {self.cu(inst)}") + vregs = [] if vaddr["k"] == "special" else [vaddr["r"] + i for i in range(vaddr.get("n", 1))] + if "idxen" in mods: + idx = self.load_reg("vgpr", vregs[0]) + m, t = self.tmp(), self.tmp() + self.emit(f"{m} = OpIMul %uint {idx} {stride}") + self.emit(f"{t} = OpIAdd %uint {total} {m}") + total = t + if "offen" in mods: + o = self.load_reg("vgpr", vregs[1] if "idxen" in mods else vregs[0]) + t = self.tmp() + self.emit(f"{t} = OpIAdd %uint {total} {o}") + total = t + self.uses_psb = True + l64, h64, sh, base, o64, addr = (self.tmp() for _ in range(6)) + self.emit(f"{l64} = OpUConvert %ulong {d0}") + self.emit(f"{h64} = OpUConvert %ulong {hi}") + self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") + self.emit(f"{base} = OpBitwiseOr %ulong {sh} {l64}") + self.emit(f"{o64} = OpUConvert %ulong {total}") + self.emit(f"{addr} = OpIAdd %ulong {base} {o64}") + return addr, d3 + + def buffer_store(self, op, a, mods): + """buffer_store_dword[xN] (raw) and buffer_store_format_* (f32 formats stored raw, f16x2/x4, unorm8x4). + Only active lanes store, inside a structured if.""" + if any(m in mods for m in ("lds", "tfe", "d16")): + raise Unsupported(op + " form") + vd = a[0] + addr, d3 = self.buffer_address(a, mods) + if op.startswith("buffer_store_dword"): + n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) + words = [self.load_reg("vgpr", vd["r"] + i) for i in range(n)] + plans = None + else: + n = len(op.rsplit("_", 1)[1]) + comps = [self.load_reg("vgpr", vd["r"] + i) for i in range(n)] + fmt = self.tmp() + self.emit(f"{fmt} = OpBitFieldUExtract %uint {d3} {self.cu(12)} {self.cu(7)}") + # Encodings for the formats that appear in store-heavy shaders; others store nothing. + f32 = {22: 1, 64: 2, 74: 3, 77: 4} + # Float views of the components, computed before any branch so every branch can use them. + fl = [self.tof(c) for c in comps] + ["%f0"] * (4 - len(comps)) + plans = (fmt, comps, f32, fl) + words = None + act = self.active_b() + lbl_do, lbl_end = self.tmp() + "_do", self.tmp() + "_end" + self.emit(f"OpSelectionMerge {lbl_end} None") + self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") + self.emit(f"{lbl_do} = OpLabel") + ptr = self.tmp() + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(addr)}") + if words is not None: + for i, w in enumerate(words): + p = self.tmp() + self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") + self.emit(f"OpStore {p} {w} Aligned 4") + else: + fmt, comps, f32, fl = plans + # f32 formats: store min(n, format components) raw dwords; f16x4 (71) packs pairs; unorm8x4 (56) packs. + for code, cnt in f32.items(): + e = self.tmp() + self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(code)}") + ld, le = self.tmp() + "_f", self.tmp() + "_fe" + self.emit(f"OpSelectionMerge {le} None") + self.emit(f"OpBranchConditional {e} {ld} {le}") + self.emit(f"{ld} = OpLabel") + for i in range(min(cnt, len(comps))): + p = self.tmp() + self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") + self.emit(f"OpStore {p} {comps[i]} Aligned 4") + self.emit(f"OpBranch {le}") + self.emit(f"{le} = OpLabel") + e = self.tmp() + self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(71)}") + ld, le = self.tmp() + "_h", self.tmp() + "_he" + self.emit(f"OpSelectionMerge {le} None") + self.emit(f"OpBranchConditional {e} {ld} {le}") + self.emit(f"{ld} = OpLabel") + for i in range(2): + v, pk, p = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{v} = OpCompositeConstruct %v2float {fl[2 * i]} {fl[2 * i + 1]}") + self.emit(f"{pk} = OpExtInst %uint %glsl PackHalf2x16 {v}") + self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") + self.emit(f"OpStore {p} {pk} Aligned 4") + self.emit(f"OpBranch {le}") + self.emit(f"{le} = OpLabel") + e = self.tmp() + self.emit(f"{e} = OpIEqual %bool {fmt} {self.cu(56)}") + ld, le = self.tmp() + "_u", self.tmp() + "_ue" + self.emit(f"OpSelectionMerge {le} None") + self.emit(f"OpBranchConditional {e} {ld} {le}") + self.emit(f"{ld} = OpLabel") + v4, pk, p = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{v4} = OpCompositeConstruct %v4float {' '.join(fl[:4])}") + self.emit(f"{pk} = OpExtInst %uint %glsl PackUnorm4x8 {v4}") + self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(0)}") + self.emit(f"OpStore {p} {pk} Aligned 4") + self.emit(f"OpBranch {le}") + self.emit(f"{le} = OpLabel") + self.emit(f"OpBranch {lbl_end}") + self.emit(f"{lbl_end} = OpLabel") + + def cmp_class(self, a): + """v_cmp_class_f32 dst, x, mask: true if x's class bit is set in mask. + Bits: 0 sNaN, 1 qNaN, 2 -inf, 3 -normal, 4 -denormal, 5 -0, 6 +0, 7 +denormal, 8 +normal, 9 +inf.""" + x, mask = self.src_f(a[-2]), self.src_u(a[-1]) + u = self.tou(x) + sign, absu = self.tmp(), self.tmp() + self.emit(f"{sign} = OpShiftRightLogical %uint {u} {self.cu(31)}") + self.emit(f"{absu} = OpBitwiseAnd %uint {u} {self.cu(0x7FFFFFFF)}") + exp_, man = self.tmp(), self.tmp() + self.emit(f"{exp_} = OpShiftRightLogical %uint {absu} {self.cu(23)}") + self.emit(f"{man} = OpBitwiseAnd %uint {absu} {self.cu(0x7FFFFF)}") + neg = self.tmp_bool_nz(sign) + + def b(cond_line): + t = self.tmp() + self.emit(f"{t} = {cond_line}") + return t + is_zero = b(f"OpIEqual %bool {absu} {self.cu(0)}") + exp0 = b(f"OpIEqual %bool {exp_} {self.cu(0)}") + expmax = b(f"OpIEqual %bool {exp_} {self.cu(255)}") + man0 = b(f"OpIEqual %bool {man} {self.cu(0)}") + man_nz = b(f"OpLogicalNot %bool {man0}") + is_inf = b(f"OpLogicalAnd %bool {expmax} {man0}") + is_nan = b(f"OpLogicalAnd %bool {expmax} {man_nz}") + quiet = b(f"OpUGreaterThanEqual %bool {man} {self.cu(0x400000)}") + snan = b(f"OpLogicalAnd %bool {is_nan} " + b(f"OpLogicalNot %bool {quiet}")) + qnan = b(f"OpLogicalAnd %bool {is_nan} {quiet}") + denorm = b(f"OpLogicalAnd %bool {exp0} {man_nz}") + normal = b(f"OpLogicalAnd %bool " + b(f"OpLogicalNot %bool {exp0}") + " " + b(f"OpLogicalNot %bool {expmax}")) + pos = b(f"OpLogicalNot %bool {neg}") + classes = [snan, qnan, b(f"OpLogicalAnd %bool {is_inf} {neg}"), b(f"OpLogicalAnd %bool {normal} {neg}"), + b(f"OpLogicalAnd %bool {denorm} {neg}"), b(f"OpLogicalAnd %bool {is_zero} {neg}"), + b(f"OpLogicalAnd %bool {is_zero} {pos}"), b(f"OpLogicalAnd %bool {denorm} {pos}"), + b(f"OpLogicalAnd %bool {normal} {pos}"), b(f"OpLogicalAnd %bool {is_inf} {pos}")] + acc = "%false" + for i, c in enumerate(classes): + bit = b(f"OpBitwiseAnd %uint {mask} {self.cu(1 << i)}") + on = b(f"OpINotEqual %bool {bit} {self.cu(0)}") + hit = b(f"OpLogicalAnd %bool {on} {c}") + acc = b(f"OpLogicalOr %bool {acc} {hit}") + r = b(f"OpSelect %uint {acc} {self.cu(0xFFFFFFFF)} {self.cu(0)}") + d = a[0] + if len(a) == 2 or (d["k"] == "special" and d["t"] in ("vcc", "vcc_lo")): + self.emit(f"OpStore %vcc {r}") + else: + self.mask_dst(d, r) + + def tmp_bool_nz(self, v): + b = self.tmp() + self.emit(f"{b} = OpINotEqual %bool {v} {self.cu(0)}") + return b + + def mask_src(self, a): + """A lane mask operand (sgpr pair, vcc, exec, imm) as one uint for this lane.""" + if a["k"] == "sgpr": + return self.load_reg("sgpr", a["r"]) + if a["k"] == "special" and a["t"] in ("vcc", "vcc_lo"): + v = self.tmp() + self.emit(f"{v} = OpLoad %uint %vcc") + return v + if a["k"] == "special" and a["t"] in ("exec", "exec_lo"): + return self.exec_value() + if a["k"] == "imm": + return self.cu(0xFFFFFFFF if a["v"] & 1 else 0) + raise Unsupported("mask operand") + + def mask_dst(self, d, v): + if d["k"] == "special" and d["t"] in ("exec", "exec_lo"): + self.set_exec(v) + elif d["k"] == "sgpr": + self.store_reg("sgpr", d["r"], v) + if d.get("n") == 2: + self.store_reg("sgpr", d["r"] + 1, v) + elif d["k"] == "special" and d["t"] in ("vcc", "vcc_lo"): + self.emit(f"OpStore %vcc {v}") + else: + raise Unsupported("mask destination") + + def clamp_mods(self, v, mods): + # Output modifier (mul:2 / mul:4 / div:2) is applied before clamp, as on hardware. + for m in mods: + if m in ("mul:2", "mul:4", "div:2"): + k = {"mul:2": "2", "mul:4": "4", "div:2": "0.5"}[m] + c = self.fconst(float(k)) + g = self.tmp() + self.emit(f"{g} = OpFMul %float {v} {c}") + v = g + if "clamp" in mods: + g = self.tmp() + self.emit(f"{g} = OpExtInst %float %glsl FClamp {v} %f0 %f1") + return g + return v + + def fconst(self, x): + bits = struct.unpack("= GFX10). + x = self.src_f(a[1]) + v, p, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{v} = OpCompositeConstruct %v2float {x} %f0") + self.emit(f"{p} = OpExtInst %uint %glsl PackHalf2x16 {v}") + self.emit(f"{r} = OpBitwiseAnd %uint {p} {self.cu(0xFFFF)}") + self.write_lo16(a[0], r) + elif op == "s_mulk_i32": + v = a[1]["v"] & 0xFFFF + k = v - 0x10000 if v & 0x8000 else v + x = self.load_reg("sgpr", a[0]["r"]) + r = self.tmp() + self.emit(f"{r} = OpIMul %uint {x} {self.cu(k)}") + self.dst(a[0], r) + elif op == "v_readfirstlane_b32": + self.dst(a[0], self.src_u(a[1])) # one lane per invocation: the first lane is this lane + elif op in ("image_sample", "image_sample_lz", "image_sample_l", "image_sample_b", "image_sample_c_lz", + "image_sample_d", "image_sample_d_cl", "image_load", "image_gather4_lz"): + self.image_op(op, a, mods) + elif op in ("v_sin_f32", "v_cos_f32"): + # RDNA takes the angle in turns: sin(x * 2*pi). + x = self.src_f(a[1]) + t, r = self.tmp(), self.tmp() + self.emit(f"{t} = OpFMul %float {x} {self.fconst(6.283185307179586)}") + self.emit(f"{r} = OpExtInst %float %glsl {'Sin' if 'sin' in op else 'Cos'} {t}") + self.dst(a[0], self.tou(self.clamp_mods(r, mods))) + elif op == "v_rndne_f32": + x = self.src_f(a[1]) + r = self.tmp() + self.emit(f"{r} = OpExtInst %float %glsl RoundEven {x}") + self.dst(a[0], self.tou(self.clamp_mods(r, mods))) + elif op in ("v_madak_f32", "v_madmk_f32"): + if op == "v_madak_f32": + x, y, z = self.src_f(a[1]), self.src_f(a[2]), self.src_f(a[3]) + else: + x, y, z = self.src_f(a[1]), self.src_f(a[3]), self.src_f(a[2]) + m, r = self.tmp(), self.tmp() + self.emit(f"{m} = OpFMul %float {x} {y}") + self.emit(f"{r} = OpFAdd %float {m} {z}") + self.dst(a[0], self.tou(r)) + elif op in ("v_bfi_b32", "v_lshl_or_b32", "v_lshl_add_u32", "v_add_lshl_u32", "v_or3_b32", "v_xor3_b32", + "v_add3_u32", "v_and_or_b32_"): + x, y, z = (self.src_u(t) for t in a[1:4]) + r = self.tmp() + if op == "v_bfi_b32": + p, n, q = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{p} = OpBitwiseAnd %uint {x} {y}") + self.emit(f"{n} = OpNot %uint {x}") + self.emit(f"{q} = OpBitwiseAnd %uint {n} {z}") + self.emit(f"{r} = OpBitwiseOr %uint {p} {q}") + elif op in ("v_lshl_or_b32", "v_lshl_add_u32"): + s, m = self.tmp(), self.tmp() + self.emit(f"{m} = OpBitwiseAnd %uint {y} {self.cu(31)}") + self.emit(f"{s} = OpShiftLeftLogical %uint {x} {m}") + self.emit(f"{r} = {'OpBitwiseOr' if op == 'v_lshl_or_b32' else 'OpIAdd'} %uint {s} {z}") + elif op == "v_add_lshl_u32": + s, m = self.tmp(), self.tmp() + self.emit(f"{s} = OpIAdd %uint {x} {y}") + self.emit(f"{m} = OpBitwiseAnd %uint {z} {self.cu(31)}") + self.emit(f"{r} = OpShiftLeftLogical %uint {s} {m}") + else: + k = {"v_or3_b32": "OpBitwiseOr", "v_xor3_b32": "OpBitwiseXor", "v_add3_u32": "OpIAdd"}[op] + s = self.tmp() + self.emit(f"{s} = {k} %uint {x} {y}") + self.emit(f"{r} = {k} %uint {s} {z}") + self.dst(a[0], r) + elif op == "v_pack_b32_f16": + # dst = f16(src0) | f16(src1) << 16, each taken from the low half (op_sel picks high halves). + sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]") + sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] + halves = [] + for i, src in enumerate(a[1:3]): + u = self.src_u({**src, "neg": False, "abs": False}) + if sb[i]: + s = self.tmp() + self.emit(f"{s} = OpShiftRightLogical %uint {u} {self.cu(16)}") + u = s + m = self.tmp() + self.emit(f"{m} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}") + halves.append(m) + if any(src.get("neg") or src.get("abs") for src in a[1:3]): + raise Unsupported("v_pack_b32_f16 modifiers") + hi, r = self.tmp(), self.tmp() + self.emit(f"{hi} = OpShiftLeftLogical %uint {halves[1]} {self.cu(16)}") + self.emit(f"{r} = OpBitwiseOr %uint {halves[0]} {hi}") + self.dst(a[0], r) + elif op == "v_cmp_class_f32": + self.cmp_class(a) + elif op in ("v_ffbl_b32", "v_ffbh_u32", "s_ff1_i32_b32", "s_flbit_i32_b32"): + x = self.src_u(a[1]) + r = self.tmp() + if op in ("v_ffbl_b32", "s_ff1_i32_b32"): + # Index of lowest set bit, -1 (0xFFFFFFFF) if none: FindILsb has the same convention. + ri = self.tmp() + self.emit(f"{ri} = OpExtInst %int %glsl FindILsb {self.as_int(x)}") + self.emit(f"{r} = OpBitcast %uint {ri}") + else: + # Leading-zero count from the MSB side, -1 if zero: 31 - FindUMsb(x), with FindUMsb(0) = -1. + m, z, d = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{m} = OpExtInst %int %glsl FindUMsb {x}") + mu = self.tmp() + self.emit(f"{mu} = OpBitcast %uint {m}") + self.emit(f"{d} = OpISub %uint {self.cu(31)} {mu}") + self.emit(f"{z} = OpIEqual %bool {x} {self.cu(0)}") + self.emit(f"{r} = OpSelect %uint {z} {self.cu(0xFFFFFFFF)} {d}") + self.dst(a[0], r) + elif op in ("image_get_resinfo", "image_load_mip", "image_store") or op in self.IMG_ATOMICS: + self.image_misc(op, a, mods) + elif op in ("v_cubema_f32", "v_cubeid_f32", "v_cubesc_f32", "v_cubetc_f32"): + # Cube face selection (standard table): major axis Z if |z|>=|x| and |z|>=|y|, else Y if |y|>=|x|, + # else X. face: +X0 -X1 +Y2 -Y3 +Z4 -Z5 + # +X: sc=-z tc=-y -X: sc=+z tc=-y +Y: sc=+x tc=+z -Y: sc=+x tc=-z +Z: sc=+x tc=-y -Z: sc=-x tc=-y + # cubema = 2 * (signed major-axis coordinate) + x, y, z = (self.src_f(t) for t in a[1:4]) + ax, ay, az = (self.tmp() for _ in range(3)) + for t, s in ((ax, x), (ay, y), (az, z)): + self.emit(f"{t} = OpExtInst %float %glsl FAbs {s}") + zx, zy, zmaj, yx, ymaj = (self.tmp() for _ in range(5)) + self.emit(f"{zx} = OpFOrdGreaterThanEqual %bool {az} {ax}") + self.emit(f"{zy} = OpFOrdGreaterThanEqual %bool {az} {ay}") + self.emit(f"{zmaj} = OpLogicalAnd %bool {zx} {zy}") + self.emit(f"{yx} = OpFOrdGreaterThanEqual %bool {ay} {ax}") + nz = self.tmp() + self.emit(f"{nz} = OpLogicalNot %bool {zmaj}") + self.emit(f"{ymaj} = OpLogicalAnd %bool {nz} {yx}") + + def neg(v): + n = self.tmp() + self.emit(f"{n} = OpFNegate %float {v}") + return n + + def lt0(v): + b = self.tmp() + self.emit(f"{b} = OpFOrdLessThan %bool {v} %f0") + return b + + def pick(zv, yv, xv): + t1, t2 = self.tmp(), self.tmp() + self.emit(f"{t1} = OpSelect %float {ymaj} {yv} {xv}") + self.emit(f"{t2} = OpSelect %float {zmaj} {zv} {t1}") + return t2 + + def sel(c, t, f): + r = self.tmp() + self.emit(f"{r} = OpSelect %float {c} {t} {f}") + return r + xn, yn, zn = lt0(x), lt0(y), lt0(z) + if op == "v_cubema_f32": + m = pick(z, y, x) + r = self.tmp() + self.emit(f"{r} = OpFMul %float {m} {self.fconst(2.0)}") + elif op == "v_cubeid_f32": + r = pick(sel(zn, self.fconst(5.0), self.fconst(4.0)), sel(yn, self.fconst(3.0), self.fconst(2.0)), + sel(xn, self.fconst(1.0), self.fconst(0.0))) + elif op == "v_cubesc_f32": + r = pick(sel(zn, neg(x), x), x, sel(xn, z, neg(z))) + else: + r = pick(neg(y), sel(yn, neg(z), z), neg(y)) + self.dst(a[0], self.tou(self.clamp_mods(r, mods))) + elif op in ("v_mbcnt_lo_u32_b32", "v_mbcnt_hi_u32_b32"): + # Count of set bits in the mask for lanes below this one (lo: lanes 0-31, hi: lanes 32-63), plus src1. + self.uses_subgroup = True + mask, acc = self.src_u(a[1]), self.src_u(a[2]) + lane, rel, below, inrange, one, m1, cnt, r = (self.tmp() for _ in range(8)) + self.emit(f"{lane} = OpLoad %uint %sg_lane") + if op.endswith("lo_u32_b32"): + self.emit(f"{rel} = OpCopyObject %uint {lane}") + else: + self.emit(f"{rel} = OpISub %uint {lane} {self.cu(32)}") + # bits below `rel`, clamped to [0, 32] + self.emit(f"{inrange} = OpULessThan %bool {rel} {self.cu(32)}") + self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {rel}") + self.emit(f"{m1} = OpISub %uint {one} {self.cu(1)}") + big = self.tmp() + # lo: lanes >= 32 count all 32 bits; hi: lanes < 32 count none (rel wraps above 32). + self.emit(f"{big} = OpSelect %uint {inrange} {m1} " + f"{self.cu(0xFFFFFFFF) if op.endswith('lo_u32_b32') else self.cu(0)}") + if op.endswith("hi_u32_b32"): + lt32, fixed = self.tmp(), self.tmp() + self.emit(f"{lt32} = OpULessThan %bool {lane} {self.cu(32)}") + self.emit(f"{fixed} = OpSelect %uint {lt32} {self.cu(0)} {big}") + big = fixed + self.emit(f"{below} = OpBitwiseAnd %uint {mask} {big}") + self.emit(f"{cnt} = OpBitCount %uint {below}") + self.emit(f"{r} = OpIAdd %uint {cnt} {acc}") + self.dst(a[0], r) + elif op == "v_bfrev_b32": + x = self.src_u(a[1]) + r = self.tmp() + self.emit(f"{r} = OpBitReverse %uint {x}") + self.dst(a[0], r) + elif op == "v_bfm_b32": + w, o = self.src_u(a[1]), self.src_u(a[2]) + wm, om, one, m1, r = (self.tmp() for _ in range(5)) + self.emit(f"{wm} = OpBitwiseAnd %uint {w} {self.cu(31)}") + self.emit(f"{om} = OpBitwiseAnd %uint {o} {self.cu(31)}") + self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {wm}") + self.emit(f"{m1} = OpISub %uint {one} {self.cu(1)}") + self.emit(f"{r} = OpShiftLeftLogical %uint {m1} {om}") + self.dst(a[0], r) + elif op in ("s_bcnt1_i32_b64", "s_bcnt1_i32_b32"): + if op.endswith("b64") and a[1]["k"] == "sgpr" and a[1].get("n") == 2: + lo, hi = self.load_reg("sgpr", a[1]["r"]), self.load_reg("sgpr", a[1]["r"] + 1) + else: + lo, hi = (self.mask_src(a[1]), self.cu(0)) if op.endswith("b64") else (self.src_u(a[1]), self.cu(0)) + c1, c2, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{c1} = OpBitCount %uint {lo}") + self.emit(f"{c2} = OpBitCount %uint {hi}") + self.emit(f"{r} = OpIAdd %uint {c1} {c2}") + self.dst(a[0], r) + z = self.tmp() + self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {z}") + elif op == "v_subrev_nc_u32": + x, y = self.src_u(a[1]), self.src_u(a[2]) + r = self.tmp() + self.emit(f"{r} = OpISub %uint {y} {x}") + self.dst(a[0], r) + elif op == "s_ff1_i32_b64": + # Lowest set bit of a 64-bit mask, -1 if none. + if a[1]["k"] != "sgpr" or a[1].get("n") != 2: + lo, hi = self.mask_src(a[1]), self.cu(0) + else: + lo, hi = self.load_reg("sgpr", a[1]["r"]), self.load_reg("sgpr", a[1]["r"] + 1) + l, h, hp, lz, r = (self.tmp() for _ in range(5)) + self.emit(f"{l} = OpExtInst %int %glsl FindILsb {self.as_int(lo)}") + self.emit(f"{h} = OpExtInst %int %glsl FindILsb {self.as_int(hi)}") + hu = self.tmp() + self.emit(f"{hu} = OpBitcast %uint {h}") + hz = self.tmp() + self.emit(f"{hz} = OpIEqual %bool {hi} {self.cu(0)}") + self.emit(f"{hp} = OpIAdd %uint {hu} {self.cu(32)}") + hsel = self.tmp() + self.emit(f"{hsel} = OpSelect %uint {hz} {self.cu(0xFFFFFFFF)} {hp}") + self.emit(f"{lz} = OpIEqual %bool {lo} {self.cu(0)}") + lu = self.tmp() + self.emit(f"{lu} = OpBitcast %uint {l}") + self.emit(f"{r} = OpSelect %uint {lz} {hsel} {lu}") + self.dst(a[0], r) + elif op == "ds_swizzle_b32": + self.swizzle(a, mods, ins) + elif op == "v_readlane_b32": + # sD = vS[lane]: a subgroup shuffle from that lane (the result is uniform). + self.uses_subgroup = True + v, ln = self.src_u(a[1]), self.src_u(a[2]) + m, r = self.tmp(), self.tmp() + self.emit(f"{m} = OpBitwiseAnd %uint {ln} {self.cu(63)}") + self.emit(f"{r} = OpGroupNonUniformShuffle %uint %c3 {v} {m}") + self.dst(a[0], r) + elif op == "v_writelane_b32": + # vD[lane] = sS: only the named lane changes (independent of EXEC, as on hardware). + self.uses_subgroup = True + val, ln = self.src_u(a[1]), self.src_u(a[2]) + me, m, eq, old, r = (self.tmp() for _ in range(5)) + self.emit(f"{me} = OpLoad %uint %sg_lane") + self.emit(f"{m} = OpBitwiseAnd %uint {ln} {self.cu(63)}") + self.emit(f"{eq} = OpIEqual %bool {me} {m}") + p = self.tmp() + self.emit(f"{p} = OpAccessChain %_ptr_Function_uint %vgpr {self.cu(a[0]['r'])}") + self.emit(f"{old} = OpLoad %uint {p}") + self.emit(f"{r} = OpSelect %uint {eq} {val} {old}") + self.emit(f"OpStore {p} {r}") + elif op.startswith("buffer_store_dword") or op in ("buffer_store_format_x", "buffer_store_format_xy", + "buffer_store_format_xyz", "buffer_store_format_xyzw"): + self.buffer_store(op, a, mods) + elif op in ("v_permlanex16_b32", "v_permlane16_b32"): + # Lane l reads lane sel[l & 15] of (x16: the other 16-lane half of its row; plain: the same half). + # The 4-bit selectors for lanes 0-7 are in src1, for lanes 8-15 in src2. + self.uses_subgroup = True + v, s1, s2 = self.src_u(a[1]), self.src_u(a[2]), self.src_u(a[3]) + lane, within, hi8, sh, nib1, nib2, nib, row, src = (self.tmp() for _ in range(9)) + self.emit(f"{lane} = OpLoad %uint %sg_lane") + self.emit(f"{within} = OpBitwiseAnd %uint {lane} {self.cu(15)}") + self.emit(f"{hi8} = OpUGreaterThanEqual %bool {within} {self.cu(8)}") + w7 = self.tmp() + self.emit(f"{w7} = OpBitwiseAnd %uint {within} {self.cu(7)}") + self.emit(f"{sh} = OpIMul %uint {w7} {self.cu(4)}") + self.emit(f"{nib1} = OpBitFieldUExtract %uint {s1} {sh} {self.cu(4)}") + self.emit(f"{nib2} = OpBitFieldUExtract %uint {s2} {sh} {self.cu(4)}") + self.emit(f"{nib} = OpSelect %uint {hi8} {nib2} {nib1}") + half = self.tmp() + self.emit(f"{half} = OpBitwiseAnd %uint {lane} {self.cu(0xFFFFFFF0)}") + if op == "v_permlanex16_b32": + self.emit(f"{row} = OpBitwiseXor %uint {half} {self.cu(16)}") + else: + self.emit(f"{row} = OpCopyObject %uint {half}") + self.emit(f"{src} = OpBitwiseOr %uint {row} {nib}") + r = self.tmp() + self.emit(f"{r} = OpGroupNonUniformShuffle %uint %c3 {v} {src}") + self.dst(a[0], r) + elif op.startswith("buffer_load_dword"): + self.buffer_load(op, a, mods) + elif op in ("buffer_load_format_x", "buffer_load_format_xy", "buffer_load_format_xyz", + "buffer_load_format_xyzw"): + self.buffer_load_format(op, a, mods) + elif op in ("tbuffer_load_format_x", "tbuffer_load_format_xy", "tbuffer_load_format_xyz", + "tbuffer_load_format_xyzw"): + # Typed load with the format in the instruction (format:[BUF_FMT_...]) instead of the V#. + fm = next((m for m in mods if m.startswith("format:")), None) + if fm is None: + raise Unsupported(op + " without format") + name = "GFX10_FORMAT_" + fm.split("BUF_FMT_")[-1].rstrip("]") + code = next((c for c, n in GFX10_FORMATS.items() if n == name), None) + if code is None or code not in self.FORMATS: + raise Unsupported(op + " " + name) + self.buffer_load_format(op[1:], a, mods, fixed_fmt=code) + elif op == "s_bitset1_b32": + # sD |= 1 << (src & 31) (sD is both source and destination) + b = self.src_u(a[1]) + m, sh, old, r = (self.tmp() for _ in range(4)) + self.emit(f"{m} = OpBitwiseAnd %uint {b} {self.cu(31)}") + self.emit(f"{sh} = OpShiftLeftLogical %uint {self.cu(1)} {m}") + self.emit(f"{old} = OpCopyObject %uint {self.load_reg('sgpr', a[0]['r'])}") + self.emit(f"{r} = OpBitwiseOr %uint {old} {sh}") + self.dst(a[0], r) + elif op == "v_alignbit_b32": + # (({src0, src1} as 64 bits) >> (src2 & 31)) low 32 bits + hi_, lo_, sh = (self.src_u(t) for t in a[1:4]) + m, inv, a1, b1, nz, r0, r = (self.tmp() for _ in range(7)) + self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}") + self.emit(f"{inv} = OpISub %uint {self.cu(32)} {m}") + self.emit(f"{a1} = OpShiftRightLogical %uint {lo_} {m}") + self.emit(f"{b1} = OpShiftLeftLogical %uint {hi_} {inv}") + self.emit(f"{r0} = OpBitwiseOr %uint {a1} {b1}") + self.emit(f"{nz} = OpINotEqual %bool {m} {self.cu(0)}") + self.emit(f"{r} = OpSelect %uint {nz} {r0} {lo_}") + self.dst(a[0], r) + elif op == "v_lshlrev_b64": + # v[d:d+1] = v[s:s+1] << (src0 & 63) + sh, src = a[1], a[2] + if a[0].get("n") != 2: + raise Unsupported(op + " operands") + if src["k"] in ("vgpr", "sgpr") and src.get("n") == 2: + lo, hi = self.load_reg(src["k"], src["r"]), self.load_reg(src["k"], src["r"] + 1) + elif src["k"] == "imm": + # 64-bit inline/literal constant: sign-extended from 32 bits. + v = src["v"] & 0xFFFFFFFFFFFFFFFF + lo, hi = self.cu(v & 0xFFFFFFFF), self.cu((v >> 32) & 0xFFFFFFFF) + else: + raise Unsupported(op + " operands") + s = self.src_u(sh) + l64, h64, x, sh64, m, res, rlo, rhi, t = (self.tmp() for _ in range(9)) + self.emit(f"{l64} = OpUConvert %ulong {lo}") + self.emit(f"{h64} = OpUConvert %ulong {hi}") + self.emit(f"{t} = OpShiftLeftLogical %ulong {h64} %c64_32") + self.emit(f"{x} = OpBitwiseOr %ulong {t} {l64}") + self.emit(f"{m} = OpBitwiseAnd %uint {s} {self.cu(63)}") + self.emit(f"{sh64} = OpUConvert %ulong {m}") + self.emit(f"{res} = OpShiftLeftLogical %ulong {x} {sh64}") + self.emit(f"{rlo} = OpUConvert %uint {res}") + hs = self.tmp() + self.emit(f"{hs} = OpShiftRightLogical %ulong {res} %c64_32") + self.emit(f"{rhi} = OpUConvert %uint {hs}") + self.uses_psb = True # needs Int64 (declared with the PSB types) + self.dst({"k": "vgpr", "r": a[0]["r"], "n": 1}, rlo) + self.dst({"k": "vgpr", "r": a[0]["r"] + 1, "n": 1}, rhi) + elif op == "v_fmac_f16": + if any(m.startswith("op_sel") for m in mods): + raise Unsupported(op + " op_sel") + vals = [] + for s in (a[1], a[2], a[0]): + u = self.src_u({**s, "neg": False, "abs": False}) + v2, f = self.tmp(), self.tmp() + self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") + self.emit(f"{f} = OpCompositeExtract %float {v2} 0") + vals.append(self.modify_f(f, s)) + r, v2, p, old, keep, newv = (self.tmp() for _ in range(6)) + self.emit(f"{r} = OpExtInst %float %glsl Fma {vals[0]} {vals[1]} {vals[2]}") + self.emit(f"{v2} = OpCompositeConstruct %v2float {r} %f0") + self.emit(f"{p} = OpExtInst %uint %glsl PackHalf2x16 {v2}") + lo = self.tmp() + self.emit(f"{lo} = OpBitwiseAnd %uint {p} {self.cu(0xFFFF)}") + self.write_lo16(a[0], lo) # GFX10: f16 ops keep the high half + elif op in ("v_lshrrev_b16", "v_lshlrev_b16", "v_ashrrev_i16", "v_add_u16", "v_sub_u16", "v_subrev_u16", + "v_mul_lo_u16", "v_max_u16", "v_min_u16", "v_max_i16", "v_min_i16", "v_and_b16", "v_or_b16", + "v_xor_b16"): + # 16-bit integer ops on the low halves (op_sel picks high halves in the VOP3 form). Per Mesa ACO + # (can_use_opsel): the opsel-capable VOP3 (_e64) forms are partial writes that keep the high half, + # and the VOP2 (_e32) forms define the whole register (high half modelled as zero). + e64 = ins["op"].endswith("_e64") + sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]") + sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] + [0, 0, 0] + if not e64 and sb[:2] != [0, 0]: + raise Unsupported(op + " op_sel") + halves = [] + for k, s in enumerate(a[1:3]): + u = self.src_u(s) + if sb[k]: + t = self.tmp() + self.emit(f"{t} = OpShiftRightLogical %uint {u} {self.cu(16)}") + u = t + h = self.tmp() + self.emit(f"{h} = OpBitwiseAnd %uint {u} {self.cu(0xFFFF)}") + halves.append(h) + x, y = halves + r = self.tmp() + if op in ("v_lshrrev_b16", "v_lshlrev_b16", "v_ashrrev_i16"): + sh = self.tmp() # shift amount is src0 (reversed operand order), low 4 bits + self.emit(f"{sh} = OpBitwiseAnd %uint {x} {self.cu(15)}") + if op == "v_lshrrev_b16": + self.emit(f"{r} = OpShiftRightLogical %uint {y} {sh}") + elif op == "v_lshlrev_b16": + self.emit(f"{r} = OpShiftLeftLogical %uint {y} {sh}") + else: + yi, ri = self.tmp(), self.tmp() + self.emit(f"{yi} = OpBitFieldSExtract %int {self.as_int(y)} {self.cu(0)} {self.cu(16)}") + self.emit(f"{ri} = OpShiftRightArithmetic %int {yi} {sh}") + self.emit(f"{r} = OpBitcast %uint {ri}") + elif op in ("v_max_i16", "v_min_i16"): + xi, yi, ri = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{xi} = OpBitFieldSExtract %int {self.as_int(x)} {self.cu(0)} {self.cu(16)}") + self.emit(f"{yi} = OpBitFieldSExtract %int {self.as_int(y)} {self.cu(0)} {self.cu(16)}") + self.emit(f"{ri} = OpExtInst %int %glsl {'SMax' if 'max' in op else 'SMin'} {xi} {yi}") + self.emit(f"{r} = OpBitcast %uint {ri}") + else: + k = {"v_add_u16": "OpIAdd", "v_sub_u16": "OpISub", "v_mul_lo_u16": "OpIMul", "v_and_b16": "OpBitwiseAnd", + "v_or_b16": "OpBitwiseOr", "v_xor_b16": "OpBitwiseXor"}.get(op) + if op == "v_subrev_u16": + self.emit(f"{r} = OpISub %uint {y} {x}") + elif k: + self.emit(f"{r} = {k} %uint {x} {y}") + else: + self.emit(f"{r} = OpExtInst %uint %glsl {'UMax' if 'max' in op else 'UMin'} {x} {y}") + lo = self.tmp() + self.emit(f"{lo} = OpBitwiseAnd %uint {r} {self.cu(0xFFFF)}") + if e64 and sb[2]: + # op_sel destination bit: the result goes to the high half, the low half is kept. + old, keep, sh16, v = (self.tmp() for _ in range(4)) + self.emit(f"{old} = OpCopyObject %uint {self.load_reg('vgpr', a[0]['r'])}") + self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}") + self.emit(f"{sh16} = OpShiftLeftLogical %uint {lo} {self.cu(16)}") + self.emit(f"{v} = OpBitwiseOr %uint {keep} {sh16}") + self.dst(a[0], v) + else: + self.write_lo16(a[0], lo, preserve_high=e64) + elif op == "v_bcnt_u32_b32": + x, acc = self.src_u(a[1]), self.src_u(a[2]) + c, r = self.tmp(), self.tmp() + self.emit(f"{c} = OpBitCount %uint {x}") + self.emit(f"{r} = OpIAdd %uint {c} {acc}") + self.dst(a[0], r) + elif op == "s_bitset0_b32": + b = self.src_u(a[1]) + m, sh, n, r = (self.tmp() for _ in range(4)) + self.emit(f"{m} = OpBitwiseAnd %uint {b} {self.cu(31)}") + self.emit(f"{sh} = OpShiftLeftLogical %uint {self.cu(1)} {m}") + self.emit(f"{n} = OpNot %uint {sh}") + self.emit(f"{r} = OpBitwiseAnd %uint {self.load_reg('sgpr', a[0]['r'])} {n}") + self.dst(a[0], r) + elif op in ("s_min_i32", "s_max_i32"): + x, y = self.src_u(a[1]), self.src_u(a[2]) + r = self.tmp() + self.emit(f"{r} = OpExtInst %uint %glsl {'SMin' if 'min' in op else 'SMax'} {x} {y}") + self.dst(a[0], r) + # SCC = (src0 selected) per ISA; select-src0 iff src0 <= src1 (min) / >= (max) + c, z = self.tmp(), self.tmp() + xi, yi = self.as_int(x), self.as_int(y) + self.emit(f"{c} = {'OpSLessThanEqual' if 'min' in op else 'OpSGreaterThanEqual'} %bool {xi} {yi}") + self.emit(f"{z} = OpSelect %uint {c} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {z}") + elif op == "v_fma_f16": + if any(m.startswith("op_sel") for m in mods): + raise Unsupported(op + " op_sel") + vals = [] + for s in a[1:4]: + u = self.src_u({**s, "neg": False, "abs": False}) + v2, f = self.tmp(), self.tmp() + self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") + self.emit(f"{f} = OpCompositeExtract %float {v2} 0") + vals.append(self.modify_f(f, s)) + r, w2, p, lo = (self.tmp() for _ in range(4)) + self.emit(f"{r} = OpExtInst %float %glsl Fma {vals[0]} {vals[1]} {vals[2]}") + r = self.clamp_mods(r, mods) + self.emit(f"{w2} = OpCompositeConstruct %v2float {r} %f0") + self.emit(f"{p} = OpExtInst %uint %glsl PackHalf2x16 {w2}") + self.emit(f"{lo} = OpBitwiseAnd %uint {p} {self.cu(0xFFFF)}") + self.write_lo16(a[0], lo) # GFX10: f16 ops keep the high half + elif op in ("v_pk_add_f16", "v_pk_mul_f16", "v_pk_max_f16", "v_pk_min_f16"): + # Packed f16x2 (VOP3P). Result lo: source i takes its half from op_sel[i] (0 = lo, 1 = hi), negated by + # neg_lo[i]. Result hi: half from op_sel_hi[i], negated by neg_hi[i]. Defaults: op_sel [0,0], + # op_sel_hi [1,1], no negation. + def bits(name, default): + m = next((m for m in mods if m.startswith(name + ":")), None) + return [int(v) for v in m.split("[")[1].rstrip("]").split(",")] if m else default + sel, selhi = bits("op_sel", [0, 0]), bits("op_sel_hi", [1, 1]) + nlo, nhi = bits("neg_lo", [0, 0]), bits("neg_hi", [0, 0]) + srcs = [] + for i in range(2): + u = self.src_u({**a[1 + i], "neg": False, "abs": False}) + v2 = self.tmp() + self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") + comps = [] + for half_sel, neg in ((sel[i], nlo[i]), (selhi[i], nhi[i])): + c = self.tmp() + self.emit(f"{c} = OpCompositeExtract %float {v2} {half_sel}") + if neg: + n2 = self.tmp() + self.emit(f"{n2} = OpFNegate %float {c}") + c = n2 + comps.append(c) + vv = self.tmp() + self.emit(f"{vv} = OpCompositeConstruct %v2float {comps[0]} {comps[1]}") + srcs.append(vv) + vx, vy = srcs + r, p = self.tmp(), self.tmp() + if op in ("v_pk_add_f16", "v_pk_mul_f16"): + self.emit(f"{r} = {'OpFAdd' if 'add' in op else 'OpFMul'} %v2float {vx} {vy}") + else: + self.emit(f"{r} = OpExtInst %v2float %glsl {'FMax' if 'max' in op else 'FMin'} {vx} {vy}") + if "clamp" in mods: + c = self.tmp() + z2, o2 = self.tmp(), self.tmp() + self.emit(f"{z2} = OpCompositeConstruct %v2float %f0 %f0") + self.emit(f"{o2} = OpCompositeConstruct %v2float %f1 %f1") + self.emit(f"{c} = OpExtInst %v2float %glsl FClamp {r} {z2} {o2}") + r = c + self.emit(f"{p} = OpExtInst %uint %glsl PackHalf2x16 {r}") + self.dst(a[0], p) + elif op in ("v_movrels_b32", "v_movreld_b32", "v_movrelsd_b32"): + # Relative VGPR indexing through M0: movrels reads VGPR[src + M0], movreld writes VGPR[dst + M0], + # movrelsd does both. The register file is an array, so these become dynamic array accesses. + d, s = a[0], a[1] + if d["k"] != "vgpr" or s["k"] != "vgpr": + raise Unsupported(op + " operands") + m0 = self.tmp() + self.emit(f"{m0} = OpLoad %uint %m0") + if op in ("v_movrels_b32", "v_movrelsd_b32"): + si, sp, v = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{si} = OpIAdd %uint {self.cu(s['r'])} {m0}") + self.emit(f"{sp} = OpAccessChain %_ptr_Function_uint %vgpr {si}") + self.emit(f"{v} = OpLoad %uint {sp}") + else: + v = self.load_reg("vgpr", s["r"]) + if op in ("v_movreld_b32", "v_movrelsd_b32"): + di, dp, old, sel = (self.tmp() for _ in range(4)) + self.emit(f"{di} = OpIAdd %uint {self.cu(d['r'])} {m0}") + self.emit(f"{dp} = OpAccessChain %_ptr_Function_uint %vgpr {di}") + self.emit(f"{old} = OpLoad %uint {dp}") + self.emit(f"{sel} = OpSelect %uint {self.active_b()} {v} {old}") + self.emit(f"OpStore {dp} {sel}") + else: + self.dst(d, v) + elif op == "v_med3_f16": + if any(m.startswith("op_sel") for m in mods): + raise Unsupported(op + " op_sel") + vals = [] + for s in a[1:4]: + u = self.src_u({**s, "neg": False, "abs": False}) + v2, f = self.tmp(), self.tmp() + self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") + self.emit(f"{f} = OpCompositeExtract %float {v2} 0") + vals.append(self.modify_f(f, s)) + lo_, hi_, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{lo_} = OpExtInst %float %glsl FMin {vals[0]} {vals[1]}") + self.emit(f"{hi_} = OpExtInst %float %glsl FMax {vals[0]} {vals[1]}") + self.emit(f"{r} = OpExtInst %float %glsl FClamp {vals[2]} {lo_} {hi_}") + r = self.clamp_mods(r, mods) + w2, p, lo = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{w2} = OpCompositeConstruct %v2float {r} %f0") + self.emit(f"{p} = OpExtInst %uint %glsl PackHalf2x16 {w2}") + self.emit(f"{lo} = OpBitwiseAnd %uint {p} {self.cu(0xFFFF)}") + self.write_lo16(a[0], lo) # opsel-capable VOP3: keeps the high half (Mesa ACO can_use_opsel) + elif op == "v_xad_u32": + x, y, z = (self.src_u(t) for t in a[1:4]) + t, r = self.tmp(), self.tmp() + self.emit(f"{t} = OpBitwiseXor %uint {x} {y}") + self.emit(f"{r} = OpIAdd %uint {t} {z}") + self.dst(a[0], r) + elif op == "s_not_b64": + v = self.mask_src(a[1]) + r = self.tmp() + self.emit(f"{r} = OpNot %uint {v}") + self.mask_dst(a[0], r) + z = self.tmp() + self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {z}") + elif op in ("v_rsq_f16", "v_rcp_f16", "v_sqrt_f16", "v_exp_f16", "v_log_f16", "v_floor_f16", "v_fract_f16", + "v_ceil_f16", "v_trunc_f16", "v_rndne_f16"): + # f16 unary on the low half; result in the low half, high half cleared (non-op_sel form). + if any(m.startswith("op_sel") for m in mods): + raise Unsupported(op + " op_sel") + u = self.src_u({**a[1], "neg": False, "abs": False}) + v2, f = self.tmp(), self.tmp() + self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") + self.emit(f"{f} = OpCompositeExtract %float {v2} 0") + f = self.modify_f(f, a[1]) + r = self.tmp() + fn = {"v_rsq_f16": "InverseSqrt", "v_sqrt_f16": "Sqrt", "v_exp_f16": "Exp2", "v_log_f16": "Log2", + "v_floor_f16": "Floor", "v_fract_f16": "Fract", "v_ceil_f16": "Ceil", "v_trunc_f16": "Trunc", + "v_rndne_f16": "RoundEven"}.get(op) + if fn: + self.emit(f"{r} = OpExtInst %float %glsl {fn} {f}") + else: + self.emit(f"{r} = OpFDiv %float %f1 {f}") + r = self.clamp_mods(r, mods) + w2, p, lo = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{w2} = OpCompositeConstruct %v2float {r} %f0") + self.emit(f"{p} = OpExtInst %uint %glsl PackHalf2x16 {w2}") + self.emit(f"{lo} = OpBitwiseAnd %uint {p} {self.cu(0xFFFF)}") + self.write_lo16(a[0], lo) # GFX10: f16 ops keep the high half + elif op == "v_not_b32": + x = self.src_u(a[1]) + r = self.tmp() + self.emit(f"{r} = OpNot %uint {x}") + self.dst(a[0], r) + elif op == "v_mul_hi_i32": + x, y = self.as_int(self.src_u(a[1])), self.as_int(self.src_u(a[2])) + s, hi, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{s} = OpSMulExtended %smul {x} {y}") + self.emit(f"{hi} = OpCompositeExtract %int {s} 1") + self.emit(f"{r} = OpBitcast %uint {hi}") + self.uses_smul = True + self.dst(a[0], r) + elif op in ("v_add_f16", "v_sub_f16", "v_mul_f16", "v_max_f16", "v_min_f16"): + # f16 math on the low halves; the result's high half is cleared (non-op_sel form). + if any(m.startswith("op_sel") for m in mods): + raise Unsupported(op + " op_sel") + vals = [] + for s in a[1:3]: + u = self.src_u({**s, "neg": False, "abs": False}) + v2, f = self.tmp(), self.tmp() + self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") + self.emit(f"{f} = OpCompositeExtract %float {v2} 0") + vals.append(self.modify_f(f, s)) + r = self.tmp() + k = {"v_add_f16": "OpFAdd", "v_sub_f16": "OpFSub", "v_mul_f16": "OpFMul"}.get(op) + if k: + self.emit(f"{r} = {k} %float {vals[0]} {vals[1]}") + else: + self.emit(f"{r} = OpExtInst %float %glsl {'FMax' if 'max' in op else 'FMin'} {vals[0]} {vals[1]}") + r = self.clamp_mods(r, mods) + v2, p, lo = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{v2} = OpCompositeConstruct %v2float {r} %f0") + self.emit(f"{p} = OpExtInst %uint %glsl PackHalf2x16 {v2}") + self.emit(f"{lo} = OpBitwiseAnd %uint {p} {self.cu(0xFFFF)}") + self.write_lo16(a[0], lo) # GFX10: f16 ops keep the high half + elif op.startswith("v_cmp_") and op.endswith(("_u64", "_i64")) and op.split("_")[2] in ("eq", "ne", "lg"): + # 64-bit equality compare: both halves of the register pairs. + d, x, y = a[0], a[1], a[2] + def pair(s): + if s["k"] in ("vgpr", "sgpr") and s.get("n") == 2: + return self.load_reg(s["k"], s["r"]), self.load_reg(s["k"], s["r"] + 1) + if s["k"] == "imm": + v = s["v"] & 0xFFFFFFFFFFFFFFFF + return self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) + raise Unsupported(op + " operand") + (x0, x1), (y0, y1) = pair(x), pair(y) + e0, e1, eq, r = (self.tmp() for _ in range(4)) + self.emit(f"{e0} = OpIEqual %bool {x0} {y0}") + self.emit(f"{e1} = OpIEqual %bool {x1} {y1}") + self.emit(f"{eq} = OpLogicalAnd %bool {e0} {e1}") + if op.split("_")[2] != "eq": + ne = self.tmp() + self.emit(f"{ne} = OpLogicalNot %bool {eq}") + eq = ne + self.emit(f"{r} = OpSelect %uint {eq} {self.cu(0xFFFFFFFF)} {self.cu(0)}") + if d["k"] == "special" and d["t"] in ("vcc", "vcc_lo"): + self.emit(f"OpStore %vcc {r}") + else: + self.mask_dst(d, r) + elif op == "s_not_b32": + x = self.src_u(a[1]) + r = self.tmp() + self.emit(f"{r} = OpNot %uint {x}") + self.dst(a[0], r) + z = self.tmp() + self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {z}") + elif op in ("s_cmp_eq_u64", "s_cmp_lg_u64"): + # 64-bit compare of masks/pointers: equal iff both halves are equal. + def halves(s): + if s["k"] == "sgpr" and s.get("n") == 2: + return self.load_reg("sgpr", s["r"]), self.load_reg("sgpr", s["r"] + 1) + if s["k"] == "imm": + v = s["v"] & 0xFFFFFFFFFFFFFFFF + return self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) + m = self.mask_src(s) + return m, m + (x0, x1), (y0, y1) = halves(a[0]), halves(a[1]) + e0, e1, eq, r = (self.tmp() for _ in range(4)) + self.emit(f"{e0} = OpIEqual %bool {x0} {y0}") + self.emit(f"{e1} = OpIEqual %bool {x1} {y1}") + self.emit(f"{eq} = OpLogicalAnd %bool {e0} {e1}") + if op == "s_cmp_lg_u64": + ne = self.tmp() + self.emit(f"{ne} = OpLogicalNot %bool {eq}") + eq = ne + self.emit(f"{r} = OpSelect %uint {eq} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {r}") + elif op.startswith("buffer_atomic_"): + self.buffer_atomic(op, a, mods) + elif op == "image_get_lod": + self.image_get_lod(a, mods) + elif op == "s_addk_i32": + v = a[1]["v"] & 0xFFFF + k = v - 0x10000 if v & 0x8000 else v + x = self.load_reg("sgpr", a[0]["r"]) + r = self.tmp() + self.emit(f"{r} = OpIAdd %uint {x} {self.cu(k)}") + self.dst(a[0], r) + elif op in ("v_add_co_u32", "v_add_co_ci_u32", "v_sub_co_u32", "v_sub_co_ci_u32", "v_subrev_co_u32"): + # Lane masks are all-ones/zero: carry in = (vcc or the named mask) != 0, carry out stored the same way. + vd, cd = a[0], a[1] + srcs = a[2:] + x, y = self.src_u(srcs[0]), self.src_u(srcs[1]) + if op == "v_subrev_co_u32": + x, y = y, x + sub = "sub" in op + if op.endswith("ci_u32"): + cin_m = self.mask_src(srcs[2]) if len(srcs) > 2 else self.mask_src({"k": "special", "t": "vcc"}) + cin = self.tmp() + self.emit(f"{cin} = OpSelect %uint {self.tmp_bool_nz(cin_m)} {self.cu(1)} {self.cu(0)}") + else: + cin = self.cu(0) + s1, c1, s2, c2, r, carry = (self.tmp() for _ in range(6)) + if sub: + self.emit(f"{s1} = OpISubBorrow %umul {x} {y}") + else: + self.emit(f"{s1} = OpIAddCarry %umul {x} {y}") + r1 = self.tmp() + self.emit(f"{r1} = OpCompositeExtract %uint {s1} 0") + self.emit(f"{c1} = OpCompositeExtract %uint {s1} 1") + self.emit(f"{s2} = {'OpISubBorrow' if sub else 'OpIAddCarry'} %umul {r1} {cin}") + self.emit(f"{r} = OpCompositeExtract %uint {s2} 0") + self.emit(f"{c2} = OpCompositeExtract %uint {s2} 1") + self.emit(f"{carry} = OpBitwiseOr %uint {c1} {c2}") + self.dst(vd, r) + m = self.tmp() + self.emit(f"{m} = OpSelect %uint {self.tmp_bool_nz(carry)} {self.cu(0xFFFFFFFF)} {self.cu(0)}") + if not (cd["k"] == "special" and cd["t"] == "null"): + self.mask_dst(cd, m) + elif op == "v_mad_legacy_f32": + # Legacy multiply treats 0 * anything (inf/NaN included) as 0. + x, y, z = (self.src_f(t) for t in a[1:4]) + m, zx, zy, either, sel, r = (self.tmp() for _ in range(6)) + self.emit(f"{m} = OpFMul %float {x} {y}") + self.emit(f"{zx} = OpFOrdEqual %bool {x} %f0") + self.emit(f"{zy} = OpFOrdEqual %bool {y} %f0") + self.emit(f"{either} = OpLogicalOr %bool {zx} {zy}") + self.emit(f"{sel} = OpSelect %float {either} %f0 {m}") + self.emit(f"{r} = OpFAdd %float {sel} {z}") + self.dst(a[0], self.tou(self.clamp_mods(r, mods))) + elif op in ("v_med3_i32", "v_med3_u32"): + x, y, z = (self.src_u(t) for t in a[1:4]) + s = "S" if op.endswith("i32") else "U" + lo, hi, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{lo} = OpExtInst %uint %glsl {s}Min {x} {y}") + self.emit(f"{hi} = OpExtInst %uint %glsl {s}Max {x} {y}") + self.emit(f"{r} = OpExtInst %uint %glsl {s}Clamp {z} {lo} {hi}") + self.dst(a[0], r) + elif op.startswith("s_load_dword") or op.startswith("s_buffer_load_dword"): + self.scalar_load(op, a, ins["mods"]) + elif op in ("s_lshl_b64", "s_lshr_b64"): + # 64-bit shift of an SGPR pair by (src1 & 63); SCC = result != 0. + d, x = a[0], a[1] + if d["k"] != "sgpr" or d.get("n") != 2: + raise Unsupported(op + " destination") + if x["k"] == "sgpr" and x.get("n") == 2: + lo, hi = self.load_reg("sgpr", x["r"]), self.load_reg("sgpr", x["r"] + 1) + elif x["k"] == "imm": + v = x["v"] & 0xFFFFFFFFFFFFFFFF + lo, hi = self.cu(v & 0xFFFFFFFF), self.cu(v >> 32) + else: + raise Unsupported(op + " source") + sh = self.src_u(a[2]) + l64, h64, t, v64, m, s64, r, rlo, rh, rhi = (self.tmp() for _ in range(10)) + self.emit(f"{l64} = OpUConvert %ulong {lo}") + self.emit(f"{h64} = OpUConvert %ulong {hi}") + self.emit(f"{t} = OpShiftLeftLogical %ulong {h64} %c64_32") + self.emit(f"{v64} = OpBitwiseOr %ulong {t} {l64}") + self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(63)}") + self.emit(f"{s64} = OpUConvert %ulong {m}") + self.emit(f"{r} = {'OpShiftLeftLogical' if op == 's_lshl_b64' else 'OpShiftRightLogical'} %ulong {v64} {s64}") + self.emit(f"{rlo} = OpUConvert %uint {r}") + self.emit(f"{rh} = OpShiftRightLogical %ulong {r} %c64_32") + self.emit(f"{rhi} = OpUConvert %uint {rh}") + self.store_reg("sgpr", d["r"], rlo) + self.store_reg("sgpr", d["r"] + 1, rhi) + nz, z = self.tmp(), self.tmp() + orr = self.tmp() + self.emit(f"{orr} = OpBitwiseOr %uint {rlo} {rhi}") + self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(orr)} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {z}") + self.uses_psb = True # Int64 capability and %ulong come with the PSB declarations + elif op == "s_ashr_i32": + x, sh = self.src_u(a[1]), self.src_u(a[2]) + m, xi, ri, r = (self.tmp() for _ in range(4)) + self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}") + self.emit(f"{xi} = OpBitcast %int {x}") + self.emit(f"{ri} = OpShiftRightArithmetic %int {xi} {m}") + self.emit(f"{r} = OpBitcast %uint {ri}") + self.dst(a[0], r) + z = self.tmp() + self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {z}") + elif op.startswith(("global_load_dword", "global_store_dword")): + self.global_mem(op, a, mods) + elif op in ("s_add_u32", "s_addc_u32", "s_sub_u32", "s_subb_u32"): + # 32-bit add/sub with carry/borrow through SCC (used for 64-bit address arithmetic, e.g. s_getpc + offset). + x, y = self.src_u(a[1]), self.src_u(a[2]) + sub = op.startswith("s_sub") + s1, r1, c1 = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{s1} = {'OpISubBorrow' if sub else 'OpIAddCarry'} %umul {x} {y}") + self.emit(f"{r1} = OpCompositeExtract %uint {s1} 0") + self.emit(f"{c1} = OpCompositeExtract %uint {s1} 1") + r, carry = r1, c1 + if op in ("s_addc_u32", "s_subb_u32"): + cin, s2, r2, c2, cc = (self.tmp() for _ in range(5)) + self.emit(f"{cin} = OpLoad %uint %scc") + self.emit(f"{s2} = {'OpISubBorrow' if sub else 'OpIAddCarry'} %umul {r1} {cin}") + self.emit(f"{r2} = OpCompositeExtract %uint {s2} 0") + self.emit(f"{c2} = OpCompositeExtract %uint {s2} 1") + self.emit(f"{cc} = OpBitwiseOr %uint {c1} {c2}") + r, carry = r2, cc + self.dst(a[0], r) + self.emit(f"OpStore %scc {carry}") + elif op == "s_getpc_b64": + # Address of the next instruction: code base (push constants 34-35: where the runtime put this shader's + # FSSM blob in the Xbox VA window) + offset of the next instruction within the blob. + if a[0]["k"] != "sgpr" or a[0].get("n") != 2: + raise Unsupported("s_getpc_b64 destination") + nxt = ins["pc"] + len(ins["enc"]) // 2 + lo, hi, s, rlo, c, rhi = (self.tmp() for _ in range(6)) + self.emit(f"{lo} = OpLoad %uint %ud_code_lo_p") + self.emit(f"{hi} = OpLoad %uint %ud_code_hi_p") + self.emit(f"{s} = OpIAddCarry %umul {lo} {self.cu(nxt)}") + self.emit(f"{rlo} = OpCompositeExtract %uint {s} 0") + self.emit(f"{c} = OpCompositeExtract %uint {s} 1") + self.emit(f"{rhi} = OpIAdd %uint {hi} {c}") + self.store_reg("sgpr", a[0]["r"], rlo) + self.store_reg("sgpr", a[0]["r"] + 1, rhi) + self.uses_codebase = True + self.cu(3), self.cu(4) + elif op in ("s_add_i32", "s_sub_i32", "s_min_u32", "s_max_u32", "s_xor_b32", "s_andn2_b32", + "s_cselect_b32"): + x, y = self.src_u(a[1]), self.src_u(a[2]) + r = self.tmp() + if op == "s_cselect_b32": + c, b = self.tmp(), self.tmp() + self.emit(f"{c} = OpLoad %uint %scc") + self.emit(f"{b} = OpINotEqual %bool {c} {self.cu(0)}") + self.emit(f"{r} = OpSelect %uint {b} {x} {y}") + elif op == "s_andn2_b32": + n = self.tmp() + self.emit(f"{n} = OpNot %uint {y}") + self.emit(f"{r} = OpBitwiseAnd %uint {x} {n}") + elif op in ("s_min_u32", "s_max_u32"): + self.emit(f"{r} = OpExtInst %uint %glsl {'UMin' if 'min' in op else 'UMax'} {x} {y}") + else: + k = {"s_add_i32": "OpIAdd", "s_sub_i32": "OpISub", "s_sub_u32": "OpISub", + "s_xor_b32": "OpBitwiseXor"}[op] + self.emit(f"{r} = {k} %uint {x} {y}") + self.dst(a[0], r) + elif op in ("s_wqm_b64", "s_wqm_b32"): + # Whole-quad mode: a lane becomes active if any lane of its 2x2 quad is. One lane per invocation can't + # see its neighbours, so this is the identity (APPROXIMATION: helper lanes stay as they were). + v = self.mask_src(a[1]) + self.mask_dst(a[0], v) + z = self.tmp() + self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(v)} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {z}") + elif op == "v_fma_mix_f32": + # Each source is f32, or (op_sel_hi bit set) an f16 from the low/high half chosen by op_sel. + sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]") + selhi = next((m for m in mods if m.startswith("op_sel_hi:")), "op_sel_hi:[0,0,0]") + sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] + hb = [int(x) for x in selhi.split("[")[1].rstrip("]").split(",")] + vals = [] + for i, src in enumerate(a[1:4]): + if hb[i]: + u = self.src_u({**src, "neg": False, "abs": False}) + v2, f = self.tmp(), self.tmp() + self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") + self.emit(f"{f} = OpCompositeExtract %float {v2} {sb[i]}") + f = self.tof(self.modify(self.tou(f), src)) + vals.append(f) + else: + vals.append(self.src_f(src)) + r = self.tmp() + self.emit(f"{r} = OpExtInst %float %glsl Fma {vals[0]} {vals[1]} {vals[2]}") + self.dst(a[0], self.tou(self.clamp_mods(r, mods))) + elif op == "v_mad_f32": + x, y, z = (self.src_f(t) for t in a[1:4]) + m, r = self.tmp(), self.tmp() + self.emit(f"{m} = OpFMul %float {x} {y}") + self.emit(f"{r} = OpFAdd %float {m} {z}") + self.dst(a[0], self.tou(self.clamp_mods(r, mods))) + elif op in ("v_mul_lo_u32", "v_min_u32", "v_max_u32", "v_min_i32", "v_max_i32"): + x, y = self.src_u(a[1]), self.src_u(a[2]) + r = self.tmp() + if op == "v_mul_lo_u32": + self.emit(f"{r} = OpIMul %uint {x} {y}") + else: + f = {"v_min_u32": "UMin", "v_max_u32": "UMax", "v_min_i32": "SMin", "v_max_i32": "SMax"}[op] + self.emit(f"{r} = OpExtInst %uint %glsl {f} {x} {y}") + self.dst(a[0], r) + elif op == "v_cvt_f32_f16": + u = self.src_u({**a[1], "neg": False, "abs": False}) + v2, f = self.tmp(), self.tmp() + self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") + self.emit(f"{f} = OpCompositeExtract %float {v2} 0") + self.dst(a[0], self.tou(self.modify_f(f, a[1]))) + elif op in ("v_interp_p1_f32", "v_interp_p2_f32", "v_interp_mov_f32"): + # Single-lane model: the barycentric p1/p2 pair (and the flat mov) both yield the attribute value. + attr = next((x for x in a if x["k"] == "attr"), None) + if attr is None or self.stage != "ps": + raise Unsupported(op + " form") + self.dst(a[0], self.tou(self.attribute(attr["a"], attr["c"]))) + elif op == "s_movk_i32": + v = a[1]["v"] & 0xFFFF + self.dst(a[0], self.cu(v - 0x10000 if v & 0x8000 else v)) + elif op.startswith("v_cmp_") and not op.startswith("v_cmp_class"): + self.compare(op, a, scalar=False) + elif op.startswith("v_cmpx_") and not op.startswith("v_cmpx_class"): + self.compare_x(op, a) + elif op in ("s_and_saveexec_b64", "s_or_saveexec_b64", "s_andn2_saveexec_b64", "s_and_saveexec_b32", + "s_or_saveexec_b32", "s_andn2_saveexec_b32"): + saved = self.exec_value() + src = self.mask_src(a[1]) + r = self.tmp() + kind = op[2:].split("_saveexec")[0] + if kind == "andn2": + n = self.tmp() + self.emit(f"{n} = OpNot %uint {saved}") + self.emit(f"{r} = OpBitwiseAnd %uint {src} {n}") + else: + self.emit(f"{r} = {'OpBitwiseAnd' if kind == 'and' else 'OpBitwiseOr'} %uint {src} {saved}") + self.mask_dst(a[0], saved) + self.set_exec(r) + z = self.tmp() + self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {z}") + elif op in ("s_andn2_wrexec_b64", "s_andn2_wrexec_b32"): + # RDNA ISA: EXEC = S0 & ~EXEC; D = EXEC; SCC = (EXEC != 0). Two operands: sdst, ssrc0. + x, y = self.mask_src(a[1]), self.exec_value() + n, r = self.tmp(), self.tmp() + self.emit(f"{n} = OpNot %uint {y}") + self.emit(f"{r} = OpBitwiseAnd %uint {x} {n}") + self.set_exec(r) + self.mask_dst(a[0], r) + z = self.tmp() + self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {z}") + elif op in ("s_bfe_u32", "s_bfe_i32"): + # src1 packs offset in bits [4:0] and width in bits [22:16]. + x, ctl = self.src_u(a[1]), self.src_u(a[2]) + off, wid, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{off} = OpBitwiseAnd %uint {ctl} {self.cu(31)}") + self.emit(f"{wid} = OpBitFieldUExtract %uint {ctl} {self.cu(16)} {self.cu(7)}") + if op == "s_bfe_u32": + self.emit(f"{r} = OpBitFieldUExtract %uint {x} {off} {wid}") + else: + xi, ri = self.as_int(x), self.tmp() + self.emit(f"{ri} = OpBitFieldSExtract %int {xi} {off} {wid}") + self.emit(f"{r} = OpBitcast %uint {ri}") + self.dst(a[0], r) + z = self.tmp() + self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {z}") + elif op == "v_perm_b32": + # Byte permute: result byte i = selector byte i picks from the 8 bytes {src0, src1} (src1 is low). + # Selector values 0-7 pick a byte; 12 -> 0x00, >=13 -> 0xFF (sign/other cases not used here are 0). + s0, s1, sel = (self.src_u(t) for t in a[1:4]) + out = self.cu(0) + for i in range(4): + sb, lo_pick, hi_pick, k, b, lo_sh, hi_sh, chosen, inrange, val, shifted, acc = \ + (self.tmp() for _ in range(12)) + self.emit(f"{sb} = OpBitFieldUExtract %uint {sel} {self.cu(8 * i)} {self.cu(8)}") + self.emit(f"{k} = OpBitwiseAnd %uint {sb} {self.cu(7)}") + self.emit(f"{b} = OpULessThan %bool {k} {self.cu(4)}") + self.emit(f"{lo_sh} = OpIMul %uint {k} {self.cu(8)}") + self.emit(f"{lo_pick} = OpShiftRightLogical %uint {s1} {lo_sh}") + self.emit(f"{hi_sh} = OpISub %uint {lo_sh} {self.cu(32)}") + self.emit(f"{hi_pick} = OpShiftRightLogical %uint {s0} {hi_sh}") + self.emit(f"{chosen} = OpSelect %uint {b} {lo_pick} {hi_pick}") + self.emit(f"{inrange} = OpULessThan %bool {sb} {self.cu(8)}") + ff, big = self.tmp(), self.tmp() + self.emit(f"{big} = OpUGreaterThanEqual %bool {sb} {self.cu(13)}") + self.emit(f"{ff} = OpSelect %uint {big} {self.cu(0xFF)} {self.cu(0)}") + self.emit(f"{val} = OpSelect %uint {inrange} {chosen} {ff}") + m8 = self.tmp() + self.emit(f"{m8} = OpBitwiseAnd %uint {val} {self.cu(0xFF)}") + self.emit(f"{shifted} = OpShiftLeftLogical %uint {m8} {self.cu(8 * i)}") + self.emit(f"{acc} = OpBitwiseOr %uint {out} {shifted}") + out = acc + self.dst(a[0], out) + elif op in ("s_and_b64", "s_or_b64", "s_xor_b64", "s_andn2_b64", "s_orn2_b64", + "s_and_b32_mask", "s_or_b32_mask"): + x, y = self.mask_src(a[1]), self.mask_src(a[2]) + r = self.tmp() + if op.endswith("n2_b64"): + n = self.tmp() + self.emit(f"{n} = OpNot %uint {y}") + y = n + k = {"and": "OpBitwiseAnd", "or": "OpBitwiseOr", "xor": "OpBitwiseXor", "andn2": "OpBitwiseAnd", + "orn2": "OpBitwiseOr"}[op[2:].rsplit("_", 1)[0]] + self.emit(f"{r} = {k} %uint {x} {y}") + self.mask_dst(a[0], r) + z = self.tmp() + self.emit(f"{z} = OpSelect %uint {self.tmp_bool_nz(r)} {self.cu(1)} {self.cu(0)}") + self.emit(f"OpStore %scc {z}") + elif op == "s_cselect_b64": + x, y = self.mask_src(a[1]), self.mask_src(a[2]) + c, b, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{c} = OpLoad %uint %scc") + self.emit(f"{b} = OpINotEqual %bool {c} {self.cu(0)}") + self.emit(f"{r} = OpSelect %uint {b} {x} {y}") + self.mask_dst(a[0], r) + elif op in ("v_interp_p1ll_f16", "v_interp_p1lv_f16", "v_interp_p2_f16"): + attr = next((x for x in a if x["k"] == "attr"), None) + if attr is None or self.stage != "ps": + raise Unsupported(op + " form") + f = self.attribute(attr["a"], attr["c"]) + if op == "v_interp_p2_f16": + v, p, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{v} = OpCompositeConstruct %v2float {f} %f0") + self.emit(f"{p} = OpExtInst %uint %glsl PackHalf2x16 {v}") + self.emit(f"{r} = OpBitwiseAnd %uint {p} {self.cu(0xFFFF)}") + self.dst(a[0], r) + else: # p1ll/p1lv produce the f32 intermediate consumed by p2_f16 + self.dst(a[0], self.tou(f)) + elif op.startswith("s_cmp_"): + self.compare(op, a, scalar=True) + elif op.startswith("s_cmpk_"): + # s_cmpk__ sX, imm16: zero-extended for u32, sign-extended for i32. + ty = op.rsplit("_", 1)[1] + v = a[1]["v"] & 0xFFFF + if ty == "i32" and v & 0x8000: + v -= 0x10000 + self.compare("s_cmp_" + op[len("s_cmpk_"):], [a[0], {"k": "imm", "v": v}], scalar=True) + elif op == "s_bfm_b32": + # Bitfield mask: ((1 << width) - 1) << offset, width/offset from the low 5 bits of the sources. + w, o = self.src_u(a[1]), self.src_u(a[2]) + wm, om, one, m1, r = (self.tmp() for _ in range(5)) + self.emit(f"{wm} = OpBitwiseAnd %uint {w} {self.cu(31)}") + self.emit(f"{om} = OpBitwiseAnd %uint {o} {self.cu(31)}") + self.emit(f"{one} = OpShiftLeftLogical %uint {self.cu(1)} {wm}") + self.emit(f"{m1} = OpISub %uint {one} {self.cu(1)}") + self.emit(f"{r} = OpShiftLeftLogical %uint {m1} {om}") + self.dst(a[0], r) + elif op == "s_mul_hi_u32": + x, y = self.src_u(a[1]), self.src_u(a[2]) + s, r = self.tmp(), self.tmp() + self.emit(f"{s} = OpUMulExtended %umul {x} {y}") + self.emit(f"{r} = OpCompositeExtract %uint {s} 1") + self.dst(a[0], r) + elif op in ("v_fma_mixlo_f16", "v_fma_mixhi_f16"): + sel = next((m for m in mods if m.startswith("op_sel:")), "op_sel:[0,0,0]") + selhi = next((m for m in mods if m.startswith("op_sel_hi:")), "op_sel_hi:[0,0,0]") + sb = [int(x) for x in sel.split("[")[1].rstrip("]").split(",")] + hb = [int(x) for x in selhi.split("[")[1].rstrip("]").split(",")] + vals = [] + for i, src in enumerate(a[1:4]): + if hb[i]: + u = self.src_u({**src, "neg": False, "abs": False}) + v2, f = self.tmp(), self.tmp() + self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") + self.emit(f"{f} = OpCompositeExtract %float {v2} {sb[i]}") + vals.append(self.modify_f(f, src)) + else: + vals.append(self.src_f(src)) + r, v, p, h16 = self.tmp(), self.tmp(), self.tmp(), self.tmp() + self.emit(f"{r} = OpExtInst %float %glsl Fma {vals[0]} {vals[1]} {vals[2]}") + r = self.clamp_mods(r, mods) + self.emit(f"{v} = OpCompositeConstruct %v2float {r} %f0") + self.emit(f"{p} = OpExtInst %uint %glsl PackHalf2x16 {v}") + self.emit(f"{h16} = OpBitwiseAnd %uint {p} {self.cu(0xFFFF)}") + old = self.load_reg("vgpr", a[0]["r"]) + keep, newv = self.tmp(), self.tmp() + if op == "v_fma_mixlo_f16": + self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF0000)}") + self.emit(f"{newv} = OpBitwiseOr %uint {keep} {h16}") + else: + sh = self.tmp() + self.emit(f"{keep} = OpBitwiseAnd %uint {old} {self.cu(0xFFFF)}") + self.emit(f"{sh} = OpShiftLeftLogical %uint {h16} {self.cu(16)}") + self.emit(f"{newv} = OpBitwiseOr %uint {keep} {sh}") + self.dst(a[0], newv) + elif op == "v_cvt_pk_u8_f32": + # Convert src0 to u8 (round to nearest even, clamp) and insert it at byte src1 of src2. + x, byte, base = self.src_f(a[1]), self.src_u(a[2]), self.src_u(a[3]) + c, rn, u, sh, mask, nmask, keep, ins_, r = (self.tmp() for _ in range(9)) + self.emit(f"{c} = OpExtInst %float %glsl FClamp {x} %f0 {self.fconst(255.0)}") + self.emit(f"{rn} = OpExtInst %float %glsl RoundEven {c}") + self.emit(f"{u} = OpConvertFToU %uint {rn}") + b3 = self.tmp() + self.emit(f"{b3} = OpBitwiseAnd %uint {byte} {self.cu(3)}") + self.emit(f"{sh} = OpIMul %uint {b3} {self.cu(8)}") + self.emit(f"{mask} = OpShiftLeftLogical %uint {self.cu(0xFF)} {sh}") + self.emit(f"{nmask} = OpNot %uint {mask}") + self.emit(f"{keep} = OpBitwiseAnd %uint {base} {nmask}") + self.emit(f"{ins_} = OpShiftLeftLogical %uint {u} {sh}") + self.emit(f"{r} = OpBitwiseOr %uint {keep} {ins_}") + self.dst(a[0], r) + elif op == "v_mul_hi_u32": + x, y = self.src_u(a[1]), self.src_u(a[2]) + s, r = self.tmp(), self.tmp() + self.emit(f"{s} = OpUMulExtended %umul {x} {y}") + self.emit(f"{r} = OpCompositeExtract %uint {s} 1") + self.dst(a[0], r) + elif op == "v_cvt_pkrtz_f16_f32": + # Packs two f32 as f16 into one dword with round-toward-zero (exact, see f16_rtz). The earlier + # round-to-nearest version produced inf where hardware gives 65504 (found by the GPU smoke test). + x, y = self.src_f(a[1]), self.src_f(a[2]) + lo, hi = self.f16_rtz(x), self.f16_rtz(y) + sh, r = self.tmp(), self.tmp() + self.emit(f"{sh} = OpShiftLeftLogical %uint {hi} {self.cu(16)}") + self.emit(f"{r} = OpBitwiseOr %uint {lo} {sh}") + self.dst(a[0], r) + elif op == "v_rcp_iflag_f32": + x = self.src_f(a[1]) + r = self.tmp() + self.emit(f"{r} = OpFDiv %float %f1 {x}") + self.dst(a[0], self.tou(r)) + elif op in F2: + x, y = self.src_f(a[1]), self.src_f(a[2]) + r = self.tmp() + if F2[op] in ("max", "min"): + self.emit(f"{r} = OpExtInst %float %glsl {'FMax' if F2[op] == 'max' else 'FMin'} {x} {y}") + else: + self.emit(f"{r} = {F2[op]} %float {x} {y}") + self.dst(a[0], self.tou(self.clamp_mods(r, mods))) + elif op == "v_subrev_f32": + x, y = self.src_f(a[1]), self.src_f(a[2]) + r = self.tmp() + self.emit(f"{r} = OpFSub %float {y} {x}") + self.dst(a[0], self.tou(self.clamp_mods(r, mods))) + elif op in ("v_fma_f32", "v_fmac_f32", "v_mac_f32", "v_fmaak_f32", "v_fmamk_f32", "v_med3_f32"): + if op == "v_fma_f32": + x, y, z = (self.src_f(t) for t in a[1:4]) + elif op in ("v_fmac_f32", "v_mac_f32"): + x, y, z = self.src_f(a[1]), self.src_f(a[2]), self.src_f(a[0]) + elif op == "v_fmaak_f32": + x, y, z = self.src_f(a[1]), self.src_f(a[2]), self.src_f(a[3]) + elif op == "v_fmamk_f32": + x, y, z = self.src_f(a[1]), self.src_f(a[3]), self.src_f(a[2]) + else: + x, y, z = (self.src_f(t) for t in a[1:4]) + lo, hi, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{lo} = OpExtInst %float %glsl FMin {x} {y}") + self.emit(f"{hi} = OpExtInst %float %glsl FMax {x} {y}") + self.emit(f"{r} = OpExtInst %float %glsl FClamp {z} {lo} {hi}") + self.dst(a[0], self.tou(r)) + return + r = self.tmp() + self.emit(f"{r} = OpExtInst %float %glsl Fma {x} {y} {z}") + self.dst(a[0], self.tou(self.clamp_mods(r, mods))) + elif op in F1: + x = self.src_f(a[1]) + r = self.tmp() + if F1[op] == "rcp": + self.emit(f"{r} = OpFDiv %float %f1 {x}") + else: + self.emit(f"{r} = OpExtInst %float %glsl {F1[op]} {x}") + self.dst(a[0], self.tou(self.clamp_mods(r, mods))) + elif op in ("v_cvt_f32_u32", "v_cvt_f32_i32"): + x = self.src_u(a[1]) + r = self.tmp() + self.emit(f"{r} = {'OpConvertUToF' if op.endswith('u32') else 'OpConvertSToF'} %float " + f"{x if op.endswith('u32') else self.as_int(x)}") + self.dst(a[0], self.tou(r)) + elif op.startswith("v_cvt_f32_ubyte"): + n = int(op[-1]) + x = self.src_u(a[1]) + s, m, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{s} = OpShiftRightLogical %uint {x} {self.cu(8 * n)}") + self.emit(f"{m} = OpBitwiseAnd %uint {s} {self.cu(0xFF)}") + self.emit(f"{r} = OpConvertUToF %float {m}") + self.dst(a[0], self.tou(r)) + elif op in ("v_cvt_u32_f32", "v_cvt_i32_f32"): + x = self.src_f(a[1]) + r = self.tmp() + if op == "v_cvt_u32_f32": + self.emit(f"{r} = OpConvertFToU %uint {x}") + else: + i = self.tmp() + self.emit(f"{i} = OpConvertFToS %int {x}") + self.emit(f"{r} = OpBitcast %uint {i}") + self.dst(a[0], r) + elif op in U2 or op in S2: + x, y = self.src_u(a[1]), self.src_u(a[2]) + r = self.tmp() + kind = U2.get(op) or S2.get(op) + if kind == "mul24": + xm, ym = self.tmp(), self.tmp() + self.emit(f"{xm} = OpBitwiseAnd %uint {x} {self.cu(0xFFFFFF)}") + self.emit(f"{ym} = OpBitwiseAnd %uint {y} {self.cu(0xFFFFFF)}") + self.emit(f"{r} = OpIMul %uint {xm} {ym}") + else: + self.emit(f"{r} = {kind} %uint {x} {y}") + self.dst(a[0], r) + elif op in SHIFT_REV: + sh, x = self.src_u(a[1]), self.src_u(a[2]) + m, r = self.tmp(), self.tmp() + self.emit(f"{m} = OpBitwiseAnd %uint {sh} {self.cu(31)}") + self.emit(f"{r} = {SHIFT_REV[op]} %uint {x} {m}") + self.dst(a[0], r) + elif op == "v_bfe_u32": + x, o, w = (self.src_u(t) for t in a[1:4]) + om, wm, r = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{om} = OpBitwiseAnd %uint {o} {self.cu(31)}") + self.emit(f"{wm} = OpBitwiseAnd %uint {w} {self.cu(31)}") + self.emit(f"{r} = OpBitFieldUExtract %uint {x} {om} {wm}") + self.dst(a[0], r) + elif op == "v_mad_u32_u24": + x, y, z = (self.src_u(t) for t in a[1:4]) + xm, ym, p, r = self.tmp(), self.tmp(), self.tmp(), self.tmp() + self.emit(f"{xm} = OpBitwiseAnd %uint {x} {self.cu(0xFFFFFF)}") + self.emit(f"{ym} = OpBitwiseAnd %uint {y} {self.cu(0xFFFFFF)}") + self.emit(f"{p} = OpIMul %uint {xm} {ym}") + self.emit(f"{r} = OpIAdd %uint {p} {z}") + self.dst(a[0], r) + elif op == "v_cndmask_b32": + # e32: dst, src0, src1 (vcc) ; e64: dst, src0, src1, sN[:N+1]/vcc + x, y = self.src_u(a[1]), self.src_u(a[2]) + c = self.mask_src(a[3]) if len(a) > 3 else self.mask_src({"k": "special", "t": "vcc"}) + b, r = self.tmp(), self.tmp() + self.emit(f"{b} = OpINotEqual %bool {c} {self.cu(0)}") + self.emit(f"{r} = OpSelect %uint {b} {y} {x}") + self.dst(a[0], r) + elif op == "exp": + self.export(ins) + else: + raise Unsupported(op) + + def scalar_load(self, op, a, mods): + """s_load_dwordxN sD, s[p:p+1], off -> N dwords at (64-bit pointer + off) + s_buffer_load_dwordxN sD, s[v:v+3], off -> N dwords at (V# base address + off) + Both become PhysicalStorageBuffer loads (Vulkan buffer device address). V# base = dword0 | (dword1 & 0xFFFF) << 32 + (AMD RDNA ISA, buffer resource descriptor).""" + n = 1 if op.endswith("dword") else int(op.rsplit("x", 1)[1]) + d, base = a[0], a[1] + if d["k"] != "sgpr" or base["k"] != "sgpr": + raise Unsupported(op + " operands") + lo, hi = self.load_reg("sgpr", base["r"]), self.load_reg("sgpr", base["r"] + 1) + if op.startswith("s_buffer"): + if base.get("n") != 4: + raise Unsupported("s_buffer_load without V#") + m = self.tmp() + self.emit(f"{m} = OpBitwiseAnd %uint {hi} {self.cu(0xFFFF)}") + hi = m + else: + if base.get("n") != 2: + raise Unsupported("s_load without 64-bit pointer") + off = a[2] if len(a) > 2 else {"k": "imm", "v": 0} + offv = self.src_u(off) + l64, h64, sh, addr, o64, full = (self.tmp() for _ in range(6)) + self.emit(f"{l64} = OpUConvert %ulong {lo}") + self.emit(f"{h64} = OpUConvert %ulong {hi}") + self.emit(f"{sh} = OpShiftLeftLogical %ulong {h64} %c64_32") + self.emit(f"{addr} = OpBitwiseOr %ulong {sh} {l64}") + self.emit(f"{o64} = OpUConvert %ulong {offv}") + self.emit(f"{full} = OpIAdd %ulong {addr} {o64}") + ptr = self.tmp() + self.emit(f"{ptr} = OpConvertUToPtr %_ptr_PSB_arr {self.host_addr(full)}") + self.uses_psb = True + for i in range(n): + p, v = self.tmp(), self.tmp() + self.emit(f"{p} = OpAccessChain %_ptr_PSB_uint {ptr} {self.cu(i)}") + self.emit(f"{v} = OpLoad %uint {p} Aligned 4") + self.store_reg("sgpr", d["r"] + i, v) + + # ---- images: T#/S# -> bindless index through a runtime-filled hash table ---- + # Table layout (storage buffer, set 0 binding 2): uint mask; then entries of 10 uints: + # key[0..7] (descriptor dwords; S# uses key[0..3] and key[4..7] = 0xFFFFFFFF), index, pad. + # Probes 8 slots from hash(key) & mask; a miss yields index 0 (the runtime puts a fallback there). + PROBES = 8 + + def desc_lookup(self, words): + """words: 8 uint ids. Returns a uint id with the bindless index.""" + self.uses_tex = True + h = self.cu(2166136261) + for w in words: # FNV-1a over the 8 dwords + x, m = self.tmp(), self.tmp() + self.emit(f"{x} = OpBitwiseXor %uint {h} {w}") + self.emit(f"{m} = OpIMul %uint {x} {self.cu(16777619)}") + h = m + mp, mask = self.tmp(), self.tmp() + self.emit(f"{mp} = OpAccessChain %_ptr_SB_uint %desc_map %c0 %c0") + self.emit(f"{mask} = OpLoad %uint {mp}") + found, idx = "%false", self.cu(0) + for k in range(self.PROBES): + s, slot, base = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{s} = OpIAdd %uint {h} {self.cu(k)}") + self.emit(f"{slot} = OpBitwiseAnd %uint {s} {mask}") + self.emit(f"{base} = OpIMul %uint {slot} {self.cu(10)}") + match = "%true" + for j, w in enumerate(words): + o, p, v, e, m2 = self.tmp(), self.tmp(), self.tmp(), self.tmp(), self.tmp() + self.emit(f"{o} = OpIAdd %uint {base} {self.cu(1 + j)}") + self.emit(f"{p} = OpAccessChain %_ptr_SB_uint %desc_map %c0 {o}") + self.emit(f"{v} = OpLoad %uint {p}") + self.emit(f"{e} = OpIEqual %bool {v} {w}") + self.emit(f"{m2} = OpLogicalAnd %bool {match} {e}") + match = m2 + o, p, v = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{o} = OpIAdd %uint {base} {self.cu(9)}") + self.emit(f"{p} = OpAccessChain %_ptr_SB_uint %desc_map %c0 {o}") + self.emit(f"{v} = OpLoad %uint {p}") + nf, take, nidx, nfound = self.tmp(), self.tmp(), self.tmp(), self.tmp() + self.emit(f"{nf} = OpLogicalNot %bool {found}") + self.emit(f"{take} = OpLogicalAnd %bool {nf} {match}") + self.emit(f"{nidx} = OpSelect %uint {take} {v} {idx}") + self.emit(f"{nfound} = OpLogicalOr %bool {found} {match}") + idx, found = nidx, nfound + return idx + + def sgpr_words(self, a, n): + if a["k"] != "sgpr" or a.get("n", 1) < n: + raise Unsupported("descriptor operand") + return [self.load_reg("sgpr", a["r"] + i) for i in range(n)] + + def addr_regs(self, a): + """Image address operand: contiguous v[x:y] or an NSA list.""" + if a["k"] == "vgpr": + return [a["r"] + i for i in range(a.get("n", 1))] + if a["k"] == "vlist": + return a["r"] + raise Unsupported("image address operand") + + def image_op(self, op, a, mods): + a16 = "a16" in mods + d16 = "d16" in mods + dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D") + kinds = {"dim:SQ_RSRC_IMG_2D": ("img2d", "%images", "simg2d", 2, "_ptr_UC_img"), + "dim:SQ_RSRC_IMG_2D_ARRAY": ("img2da", "%images_arr", "simg2da", 3, "_ptr_UC_imga"), + # Cube: the shader already did face selection (v_cube*), so (s, t, face) samples a 6-layer + # 2D array view of the cube. The runtime binds cube textures as 2D-array views. + "dim:SQ_RSRC_IMG_CUBE": ("img2da", "%images_arr", "simg2da", 3, "_ptr_UC_imga"), + "dim:SQ_RSRC_IMG_1D": ("img1d", "%images_1d", "simg1d", 1, "_ptr_UC_img1"), + "dim:SQ_RSRC_IMG_3D": ("img3d", "%images_3d", "simg3d", -3, "_ptr_UC_img3")} + if dim not in kinds: + raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) + itype, iarr, stype, ncoord, iptr = kinds[dim] + is3d = ncoord == -3 # 3D: three real coordinates (and 3-component gradients) + if is3d: + ncoord = 3 + self.uses_tex_3d = True + elif ncoord == 3: + self.uses_tex_array = True + if ncoord == 1: + self.uses_tex_1d = True + if is3d and op.endswith("_d"): + raise Unsupported(op + " 3D gradients") + dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") + dmask = int(dm.split(":")[1], 0) + vdata, addr = a[0], self.addr_regs(a[1]) + t = self.sgpr_words(a[2], 8) + img_idx = self.desc_lookup(t) + ip, img = self.tmp(), self.tmp() + self.emit(f"{ip} = OpAccessChain %{iptr} {iarr} {img_idx}") + self.emit(f"{img} = OpLoad %{itype} {ip}") + coords = [self.load_reg("vgpr", r) for r in addr] + if a16: + # 16-bit addresses: each register packs two f16 coordinates (low half first). + unpacked = [] + for c in coords: + v2 = self.tmp() + self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {c}") + for k in (0, 1): + f = self.tmp() + self.emit(f"{f} = OpCompositeExtract %float {v2} {k}") + unpacked.append(self.tou(f)) + coords = unpacked + if op == "image_load": + # 16-bit integer coordinates: each half is an unsigned 16-bit int, not an f16. + ints = [] + for c in [self.load_reg("vgpr", r) for r in addr]: + lo, hi = self.tmp(), self.tmp() + self.emit(f"{lo} = OpBitwiseAnd %uint {c} {self.cu(0xFFFF)}") + self.emit(f"{hi} = OpShiftRightLogical %uint {c} {self.cu(16)}") + ints += [lo, hi] + coords = ints + if op == "image_load": + if len(coords) < ncoord: + raise Unsupported("image_load coords") + ints = [self.as_int(c) for c in coords[:ncoord]] + if ncoord == 1: + iv = ints[0] + else: + iv = self.tmp() + self.emit(f"{iv} = OpCompositeConstruct {'%v2int' if ncoord == 2 else '%v3int'} {' '.join(ints)}") + res = self.tmp() + self.emit(f"{res} = OpImageFetch %v4float {img} {iv} Lod {self.cu(0)}") + ncomp = bin(dmask).count("1") + else: + s = self.sgpr_words(a[3], 4) + smp_idx = self.desc_lookup(s + [self.cu(0xFFFFFFFF)] * 4) + sp, smp, si = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{sp} = OpAccessChain %_ptr_UC_smp %samplers {smp_idx}") + self.emit(f"{smp} = OpLoad %smp {sp}") + self.emit(f"{si} = OpSampledImage %{stype} {img} {smp}") + f = [self.tof(c) for c in coords] + if op == "image_gather4_lz": + # Gather the 2x2 footprint of one channel (dmask picks it) at mip 0 -> 4 results. + if bin(dmask).count("1") != 1 or ncoord != 2: + raise Unsupported("image_gather4_lz form") + uv, res = self.tmp(), self.tmp() + self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") + self.emit(f"{res} = OpImageGather %v4float {si} {uv} {self.cu(dmask.bit_length() - 1)}") + comps = [] + for c in range(4): + comp = self.tmp() + self.emit(f"{comp} = OpCompositeExtract %float {res} {c}") + comps.append(comp) + if d16: + for i in range(0, 4, 2): + v, p = self.tmp(), self.tmp() + self.emit(f"{v} = OpCompositeConstruct %v2float {comps[i]} {comps[i + 1]}") + self.emit(f"{p} = OpExtInst %uint %glsl PackHalf2x16 {v}") + self.dst({"k": "vgpr", "r": vdata["r"] + i // 2, "n": 1}, p) + else: + for i, comp in enumerate(comps): + self.dst({"k": "vgpr", "r": vdata["r"] + i, "n": 1}, self.tou(comp)) + return + kind = op[len("image_sample"):] # '', '_lz', '_l', '_b', '_c_lz', '_d', '_d_cl' + minlod = None + if kind == "_d_cl": + # Same as _d plus a trailing min-LOD clamp coordinate. + minlod, f, kind = f[-1], f[:-1], "_d" + self.uses_minlod = True + ref = None + if kind.startswith("_c"): + ref, f = f[0], f[1:] + bias = None + if kind in ("_b", "_c_b"): + bias, f = f[0], f[1:] + grads = None + if kind == "_d": + # Address: gradients first, then coords. 2D and 2D-array have 2-component gradients (the array + # layer has none): ds/dx, dt/dx, ds/dy, dt/dy. 1D has scalar ds/dx, ds/dy. + if ncoord == 1: + if len(f) < 3: + raise Unsupported(op + " coords") + grads, f = (f[0], f[1]), f[2:] + else: + if len(f) < 4 + ncoord: + raise Unsupported(op + " coords") + gx, gy = self.tmp(), self.tmp() + self.emit(f"{gx} = OpCompositeConstruct %v2float {f[0]} {f[1]}") + self.emit(f"{gy} = OpCompositeConstruct %v2float {f[2]} {f[3]}") + grads, f = (gx, gy), f[4:] + if len(f) < ncoord: + raise Unsupported(op + " coords") + if ncoord == 1: + uv = f[0] + elif ncoord == 3: + # The array layer arrives as a float coordinate; Vulkan rounds it the same way. + uv = self.tmp() + self.emit(f"{uv} = OpCompositeConstruct %v3float {f[0]} {f[1]} {f[2]}") + else: + uv = self.tmp() + self.emit(f"{uv} = OpCompositeConstruct %v2float {f[0]} {f[1]}") + res = self.tmp() + if kind == "_d": + if minlod is not None: + self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad|MinLod {grads[0]} {grads[1]} {minlod}") + else: + self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Grad {grads[0]} {grads[1]}") + elif kind == "": + self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv}" if self.stage == "ps" else + f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Lod %f0") + elif kind == "_lz": + self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Lod %f0") + elif kind == "_l": + self.emit(f"{res} = OpImageSampleExplicitLod %v4float {si} {uv} Lod {f[2] if len(f) > 2 else '%f0'}") + elif kind == "_b" and self.stage == "ps": + self.emit(f"{res} = OpImageSampleImplicitLod %v4float {si} {uv} Bias {bias}") + elif kind == "_c_lz": + d = self.tmp() + self.emit(f"{d} = OpImageSampleDrefExplicitLod %float {si} {uv} {ref} Lod %f0") + self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, self.tou(d)) + return + else: + raise Unsupported(op) + ncomp = bin(dmask).count("1") + comps = [] + for c in range(4): + if dmask >> c & 1: + comp = self.tmp() + self.emit(f"{comp} = OpCompositeExtract %float {res} {c}") + comps.append(comp) + if len(comps) != ncomp: + raise Unsupported("dmask") + if d16: + # d16: components are packed two per register as f16 (x|y<<16, z|w<<16). + for i in range(0, len(comps), 2): + second = comps[i + 1] if i + 1 < len(comps) else "%f0" + v, p = self.tmp(), self.tmp() + self.emit(f"{v} = OpCompositeConstruct %v2float {comps[i]} {second}") + self.emit(f"{p} = OpExtInst %uint %glsl PackHalf2x16 {v}") + self.dst({"k": "vgpr", "r": vdata["r"] + i // 2, "n": 1}, p) + else: + for i, comp in enumerate(comps): + self.dst({"k": "vgpr", "r": vdata["r"] + i, "n": 1}, self.tou(comp)) + + # image atomic -> (SPIR-V op, value that leaves memory unchanged, used for inactive lanes) + IMG_ATOMICS = {"image_atomic_umin": ("OpAtomicUMin", 0xFFFFFFFF), "image_atomic_umax": ("OpAtomicUMax", 0), + "image_atomic_smin": ("OpAtomicSMin", 0x7FFFFFFF), "image_atomic_smax": ("OpAtomicSMax", 0x80000000), + "image_atomic_or": ("OpAtomicOr", 0), "image_atomic_xor": ("OpAtomicXor", 0), + "image_atomic_and": ("OpAtomicAnd", 0xFFFFFFFF), "image_atomic_add": ("OpAtomicIAdd", 0), + "image_atomic_sub": ("OpAtomicISub", 0)} + + def image_misc(self, op, a, mods): + """image_get_resinfo / image_load_mip on 2D sampled images, image_atomic_umin on 2D r32ui storage images.""" + dim = next((m for m in mods if m.startswith("dim:")), "dim:SQ_RSRC_IMG_2D") + is3d_atomic = dim == "dim:SQ_RSRC_IMG_3D" and op in self.IMG_ATOMICS + if (dim != "dim:SQ_RSRC_IMG_2D" and not is3d_atomic) or "d16" in mods or "a16" in mods: + raise Unsupported(op + " " + dim.split("SQ_RSRC_IMG_")[-1]) + vdata, addr = a[0], self.addr_regs(a[1]) + t = self.sgpr_words(a[2], 8) + idx = self.desc_lookup(t) + if is3d_atomic: + # 3D r32ui storage image atomics (binding 7). + self.uses_storage3d = True + coords = [self.as_int(self.load_reg("vgpr", r)) for r in addr[:3]] + if len(coords) < 3: + raise Unsupported(op + " coords") + iv, ip, tp, old, safe = (self.tmp() for _ in range(5)) + self.emit(f"{iv} = OpCompositeConstruct %v3int {coords[0]} {coords[1]} {coords[2]}") + self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg3 %simages3d {idx}") + val = self.load_reg("vgpr", vdata["r"]) + spv, neutral = self.IMG_ATOMICS[op] + self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}") + self.emit(f"{safe} = OpSelect %uint {self.active_b()} {val} {self.cu(neutral)}") + self.emit(f"{old} = {spv} %uint {tp} {self.cu(1)} {self.cu(0)} {safe}") + if "glc" in mods: + self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, old) + return + if op in self.IMG_ATOMICS or op == "image_store": + # Storage image (2D r32ui). Atomics: vdata holds the operand; with 'glc' the pre-op value comes back. + self.uses_storage = True + coords = [self.as_int(self.load_reg("vgpr", r)) for r in addr[:2]] + iv = self.tmp() + self.emit(f"{iv} = OpCompositeConstruct %v2int {coords[0]} {coords[1]}") + ip = self.tmp() + self.emit(f"{ip} = OpAccessChain %_ptr_UC_simg %simages {idx}") + val = self.load_reg("vgpr", vdata["r"]) + if op == "image_store": + # Writes dmask component 0 as r32ui; only active lanes store. + img, lbl_do, lbl_end = self.tmp(), self.tmp() + "_do", self.tmp() + "_end" + self.emit(f"{img} = OpLoad %simg2d_u {ip}") + v4 = self.tmp() + self.emit(f"{v4} = OpCompositeConstruct %v4uint {val} {self.cu(0)} {self.cu(0)} {self.cu(0)}") + act = self.active_b() # must be computed before OpSelectionMerge (merge directly precedes branch) + self.emit(f"OpSelectionMerge {lbl_end} None") + self.emit(f"OpBranchConditional {act} {lbl_do} {lbl_end}") + self.emit(f"{lbl_do} = OpLabel") + self.emit(f"OpImageWrite {img} {iv} {v4}") + self.emit(f"OpBranch {lbl_end}") + self.emit(f"{lbl_end} = OpLabel") + self.uses_v4uint = True + return + spv, neutral = self.IMG_ATOMICS[op] + tp, old, safe = self.tmp(), self.tmp(), self.tmp() + self.emit(f"{tp} = OpImageTexelPointer %_ptr_Image_uint {ip} {iv} {self.cu(0)}") + self.emit(f"{safe} = OpSelect %uint {self.active_b()} {val} {self.cu(neutral)}") + self.emit(f"{old} = {spv} %uint {tp} {self.cu(1)} {self.cu(0)} {safe}") + if "glc" in mods: + self.dst({"k": "vgpr", "r": vdata["r"], "n": 1}, old) + return + ip, img = self.tmp(), self.tmp() + self.emit(f"{ip} = OpAccessChain %_ptr_UC_img %images {idx}") + self.emit(f"{img} = OpLoad %img2d {ip}") + dm = next((m for m in mods if m.startswith("dmask:")), "dmask:0x1") + dmask = int(dm.split(":")[1], 0) + self.uses_query = True + if op == "image_get_resinfo": + lod = self.as_int(self.load_reg("vgpr", addr[0])) + sz, lv = self.tmp(), self.tmp() + self.emit(f"{sz} = OpImageQuerySizeLod %v2int {img} {lod}") + self.emit(f"{lv} = OpImageQueryLevels %int {img}") + w, h = self.tmp(), self.tmp() + self.emit(f"{w} = OpCompositeExtract %int {sz} 0") + self.emit(f"{h} = OpCompositeExtract %int {sz} 1") + vals = [w, h, self.as_int(self.cu(1)), lv] # x=width, y=height, z=depth(1), w=mip levels + out = 0 + for c in range(4): + if dmask >> c & 1: + u = self.tmp() + self.emit(f"{u} = OpBitcast %uint {vals[c]}") + self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, u) + out += 1 + return + # image_load_mip: x, y, mip + if len(addr) < 3: + raise Unsupported("image_load_mip coords") + xs = [self.as_int(self.load_reg("vgpr", r)) for r in addr[:3]] + iv, res = self.tmp(), self.tmp() + self.emit(f"{iv} = OpCompositeConstruct %v2int {xs[0]} {xs[1]}") + self.emit(f"{res} = OpImageFetch %v4float {img} {iv} Lod {xs[2]}") + out = 0 + for c in range(4): + if dmask >> c & 1: + comp = self.tmp() + self.emit(f"{comp} = OpCompositeExtract %float {res} {c}") + self.dst({"k": "vgpr", "r": vdata["r"] + out, "n": 1}, self.tou(comp)) + out += 1 + + def attribute(self, n, comp): + """Component `comp` of fragment input attribute n (declared as a vec4 Input at Location n).""" + name = f"%in_attr{n}" + self.inputs[name] = n + p, v = self.tmp(), self.tmp() + self.emit(f"{p} = OpAccessChain %_ptr_Input_float {name} {self.cu(comp)}") + self.emit(f"{v} = OpLoad %float {p}") + return v + + def as_int(self, u): + i = self.tmp() + self.emit(f"{i} = OpBitcast %int {u}") + return i + + def export(self, ins): + a = ins["args"] + tgt = a[0]["t"] if a and a[0]["k"] in ("target", "special") else None + if tgt is None or tgt == "null": + return + comps = [] + if "compr" in ins["mods"]: + # Compressed export: two registers, each holding two f16 values (x,y) and (z,w). LLVM lists each register + # twice (one slot per half): 'exp mrt0 v4, v4, v5, v5 compr', so the pair is slots 1 and 3. + # (Found by the GPU texture test: taking the first two operands exported (r,g,r,g).) + srcs = a[1:5] + regs = [srcs[0], srcs[2]] if len(srcs) >= 3 else srcs[:1] + for x in regs: + if x["k"] == "special" and x["t"] == "off": + comps += ["%f0", "%f0"] + continue + u = self.src_u(x) + v2 = self.tmp() + self.emit(f"{v2} = OpExtInst %v2float %glsl UnpackHalf2x16 {u}") + for c in (0, 1): + f = self.tmp() + self.emit(f"{f} = OpCompositeExtract %float {v2} {c}") + comps.append(f) + else: + for x in a[1:5]: + if x["k"] == "special" and x["t"] == "off": + comps.append("%f0") + else: + comps.append(self.src_f(x)) + while len(comps) < 4: + comps.append("%f0") + comps = comps[:4] + v = self.tmp() + self.emit(f"{v} = OpCompositeConstruct %v4float {' '.join(comps)}") + name = {"pos0": "%out_pos"}.get(tgt) + if tgt == "mrtz" and self.stage == "ps": + # Depth export: component x is the fragment depth (stencil/mask exports aren't modelled). + self.writes_depth = True + old, sel = self.tmp(), self.tmp() + self.emit(f"{old} = OpLoad %float %out_depth") + self.emit(f"{sel} = OpSelect %float {self.active_b()} {comps[0]} {old}") + self.emit(f"OpStore %out_depth {sel}") + return + if name is None: + if tgt.startswith("param") and self.stage == "vs": + name = f"%out_param{int(tgt[5:])}" + elif tgt.startswith("mrt") and tgt != "mrtz" and self.stage == "ps": + name = f"%out_mrt{int(tgt[3:])}" + elif tgt.startswith("pos"): + return # pos1+ (clip/cull/point size): ignored in v0 + else: + raise Unsupported(f"export {tgt}") + self.outputs[name] = tgt + # Exports from inactive lanes don't happen: keep the previous output value. + old, sel = self.tmp(), self.tmp() + self.emit(f"{old} = OpLoad %v4float {name}") + self.emit(f"{sel} = OpSelect %v4float {self.active_b()} {v} {old}") + self.emit(f"OpStore {name} {sel}") + + +def assemble(gen): + vs = gen.stage == "vs" + model = "Vertex" if vs else "Fragment" + iface = list(gen.outputs) + list(gen.inputs) + (["%vertex_index"] if vs else []) + psb = gen.uses_psb + tex = gen.uses_tex + sg = gen.uses_subgroup + if tex: + iface += ["%images", "%samplers", "%desc_map"] + (["%images_arr"] if gen.uses_tex_array else []) + \ + (["%simages"] if gen.uses_storage else []) + (["%images_1d"] if gen.uses_tex_1d else []) + \ + (["%images_3d"] if gen.uses_tex_3d else []) + (["%simages3d"] if gen.uses_storage3d else []) + if sg: + iface += ["%sg_lane"] + if gen.writes_depth: + iface += ["%out_depth"] + iface += [f"%vin{reg}" for reg, _ in gen.vertex_inputs] + ["%user_data"] + if gen.frag_inputs: + iface += ["%frag_coord"] + (["%front_facing"] if "front" in gen.frag_inputs.values() else []) + for i in range(USER_SGPRS): # index constants for the user-data copy at entry + gen.cu(i) + # SPIR-V module layout: every OpCapability, then every OpExtension, then imports. + caps = ["Shader"] + (["Int64", "PhysicalStorageBufferAddresses"] if psb else []) + \ + (["RuntimeDescriptorArray"] if tex else []) + (["GroupNonUniform", "GroupNonUniformShuffle"] if sg else []) + \ + (["ImageQuery"] if gen.uses_query else []) + (["Sampled1D"] if gen.uses_tex_1d else []) + \ + (["MinLod"] if gen.uses_minlod else []) + exts = (["SPV_KHR_physical_storage_buffer"] if psb else []) + (["SPV_EXT_descriptor_indexing"] if tex else []) + hdr = [f"OpCapability {c}" for c in caps] + [f'OpExtension "{e}"' for e in exts] + \ + ['%glsl = OpExtInstImport "GLSL.std.450"', + f"OpMemoryModel {'PhysicalStorageBuffer64' if psb else 'Logical'} GLSL450", + f"OpEntryPoint {model} %main \"main\" {' '.join(iface)}"] + if not vs: + hdr.append("OpExecutionMode %main OriginUpperLeft") + if gen.writes_depth: + hdr.append("OpExecutionMode %main DepthReplacing") + dec = [] + if vs: + dec.append("OpDecorate %vertex_index BuiltIn VertexIndex") + for name, tgt in gen.outputs.items(): + if name == "%out_pos": + dec.append("OpDecorate %out_pos BuiltIn Position") + else: + dec.append(f"OpDecorate {name} Location {int(''.join(ch for ch in tgt if ch.isdigit()))}") + for name, n in gen.inputs.items(): + dec.append(f"OpDecorate {name} Location {n}") + types = ["%void = OpTypeVoid", "%fn = OpTypeFunction %void", "%bool = OpTypeBool", "%uint = OpTypeInt 32 0", + "%int = OpTypeInt 32 1", "%float = OpTypeFloat 32", "%v4float = OpTypeVector %float 4", + "%v2float = OpTypeVector %float 2", "%umul = OpTypeStruct %uint %uint", + "%smul = OpTypeStruct %int %int", + "%n256 = OpConstant %uint 256", "%n128 = OpConstant %uint 128", + "%arr_v = OpTypeArray %uint %n256", "%arr_s = OpTypeArray %uint %n128", + "%null_v = OpConstantNull %arr_v", "%null_s = OpConstantNull %arr_s", + "%_ptr_Function_arr_v = OpTypePointer Function %arr_v", "%_ptr_Function_arr_s = OpTypePointer Function %arr_s", + "%_ptr_Function_uint = OpTypePointer Function %uint", "%_ptr_Output_v4 = OpTypePointer Output %v4float", + "%_ptr_Input_int = OpTypePointer Input %int", "%_ptr_Input_v4 = OpTypePointer Input %v4float", + "%_ptr_Input_float = OpTypePointer Input %float", + "%f0 = OpConstant %float 0", "%f1 = OpConstant %float 1", "%true = OpConstantTrue %bool", + "%false = OpConstantFalse %bool", + "%_ptr_Function_bool = OpTypePointer Function %bool"] + if psb: + types += ["%ulong = OpTypeInt 64 0", "%c64_32 = OpConstant %ulong 32", "%long = OpTypeInt 64 1", + "%rt_uint = OpTypeRuntimeArray %uint", "%_ptr_PSB_arr = OpTypePointer PhysicalStorageBuffer %rt_uint", + "%_ptr_PSB_uint = OpTypePointer PhysicalStorageBuffer %uint"] + dec.append("OpDecorate %rt_uint ArrayStride 4") + if tex: + # Bindless set 0: images (binding 0), samplers (binding 1), descriptor hash table (binding 2). + types += ["%img2d = OpTypeImage %float 2D 0 0 0 1 Unknown", "%smp = OpTypeSampler", + "%simg2d = OpTypeSampledImage %img2d", "%v2int = OpTypeVector %int 2", + "%rt_img = OpTypeRuntimeArray %img2d", "%rt_smp = OpTypeRuntimeArray %smp", + "%_ptr_UC_rt_img = OpTypePointer UniformConstant %rt_img", + "%_ptr_UC_rt_smp = OpTypePointer UniformConstant %rt_smp", + "%_ptr_UC_img = OpTypePointer UniformConstant %img2d", "%_ptr_UC_smp = OpTypePointer UniformConstant %smp", + "%rt_map = OpTypeRuntimeArray %uint", "%DescMap = OpTypeStruct %rt_map", + "%_ptr_SB_DescMap = OpTypePointer StorageBuffer %DescMap", "%_ptr_SB_uint = OpTypePointer StorageBuffer %uint"] + dec += ["OpDecorate %images DescriptorSet 0", "OpDecorate %images Binding 0", + "OpDecorate %samplers DescriptorSet 0", "OpDecorate %samplers Binding 1", + "OpDecorate %desc_map DescriptorSet 0", "OpDecorate %desc_map Binding 2", + "OpDecorate %DescMap Block", "OpMemberDecorate %DescMap 0 Offset 0", + "OpDecorate %rt_map ArrayStride 4", "OpDecorate %desc_map NonWritable"] + types += ["%v3float = OpTypeVector %float 3", "%v3int = OpTypeVector %int 3"] + if gen.uses_tex_array: + types += ["%img2da = OpTypeImage %float 2D 0 1 0 1 Unknown", "%simg2da = OpTypeSampledImage %img2da", + "%rt_imga = OpTypeRuntimeArray %img2da", + "%_ptr_UC_rt_imga = OpTypePointer UniformConstant %rt_imga", + "%_ptr_UC_imga = OpTypePointer UniformConstant %img2da"] + dec += ["OpDecorate %images_arr DescriptorSet 0", "OpDecorate %images_arr Binding 3"] + if gen.uses_storage3d: + types += ["%simg3d_u = OpTypeImage %uint 3D 0 0 0 2 R32ui", "%rt_simg3 = OpTypeRuntimeArray %simg3d_u", + "%_ptr_UC_rt_simg3 = OpTypePointer UniformConstant %rt_simg3", + "%_ptr_UC_simg3 = OpTypePointer UniformConstant %simg3d_u"] + if not gen.uses_storage: + types += ["%_ptr_Image_uint = OpTypePointer Image %uint"] + dec += ["OpDecorate %simages3d DescriptorSet 0", "OpDecorate %simages3d Binding 7"] + if gen.uses_tex_3d: + types += ["%img3d = OpTypeImage %float 3D 0 0 0 1 Unknown", "%simg3d = OpTypeSampledImage %img3d", + "%rt_img3 = OpTypeRuntimeArray %img3d", + "%_ptr_UC_rt_img3 = OpTypePointer UniformConstant %rt_img3", + "%_ptr_UC_img3 = OpTypePointer UniformConstant %img3d"] + dec += ["OpDecorate %images_3d DescriptorSet 0", "OpDecorate %images_3d Binding 6"] + if gen.uses_tex_1d: + types += ["%img1d = OpTypeImage %float 1D 0 0 0 1 Unknown", "%simg1d = OpTypeSampledImage %img1d", + "%rt_img1 = OpTypeRuntimeArray %img1d", + "%_ptr_UC_rt_img1 = OpTypePointer UniformConstant %rt_img1", + "%_ptr_UC_img1 = OpTypePointer UniformConstant %img1d"] + dec += ["OpDecorate %images_1d DescriptorSet 0", "OpDecorate %images_1d Binding 5"] + if gen.uses_storage: + types += ["%simg2d_u = OpTypeImage %uint 2D 0 0 0 2 R32ui", "%rt_simg = OpTypeRuntimeArray %simg2d_u", + "%_ptr_UC_rt_simg = OpTypePointer UniformConstant %rt_simg", + "%_ptr_UC_simg = OpTypePointer UniformConstant %simg2d_u", + "%_ptr_Image_uint = OpTypePointer Image %uint", "%v4uint = OpTypeVector %uint 4"] + dec += ["OpDecorate %simages DescriptorSet 0", "OpDecorate %simages Binding 4"] + if sg: + types += ["%_ptr_Input_uint = OpTypePointer Input %uint"] + dec += ["OpDecorate %sg_lane BuiltIn SubgroupLocalInvocationId"] + if not vs: + dec += ["OpDecorate %sg_lane Flat"] + gen.consts.setdefault(3, "%c3") + gen.consts.setdefault(0, "%c0") + for v, name in sorted(gen.consts.items()): + types.append(f"{name} = OpConstant %uint {v}") + gvars = [f"{n} = OpVariable %_ptr_Output_v4 Output" for n in gen.outputs] + # Push constants: s0..s31 user data, then the 64-bit host address of the Xbox GPU VA window (heap base). + types += [f"%n_ud = OpConstant %uint {USER_SGPRS}", "%arr_ud = OpTypeArray %uint %n_ud", + "%UserData = OpTypeStruct %arr_ud %uint %uint %uint %uint", + "%_ptr_PC_UserData = OpTypePointer PushConstant %UserData", + "%_ptr_PC_uint = OpTypePointer PushConstant %uint"] + dec += ["OpDecorate %arr_ud ArrayStride 4", "OpDecorate %UserData Block", "OpMemberDecorate %UserData 0 Offset 0", + f"OpMemberDecorate %UserData 1 Offset {4 * USER_SGPRS}", + f"OpMemberDecorate %UserData 2 Offset {4 * USER_SGPRS + 4}", + f"OpMemberDecorate %UserData 3 Offset {4 * USER_SGPRS + 8}", + f"OpMemberDecorate %UserData 4 Offset {4 * USER_SGPRS + 12}"] + gvars += ["%user_data = OpVariable %_ptr_PC_UserData PushConstant"] + if gen.frag_inputs: + dec += ["OpDecorate %frag_coord BuiltIn FragCoord"] + gvars += ["%frag_coord = OpVariable %_ptr_Input_v4 Input"] + if "front" in gen.frag_inputs.values(): + types += ["%_ptr_Input_bool = OpTypePointer Input %bool"] + dec += ["OpDecorate %front_facing BuiltIn FrontFacing"] + gvars += ["%front_facing = OpVariable %_ptr_Input_bool Input"] + if gen.vertex_inputs: + types += ["%v4uint_in = OpTypeVector %uint 4", "%v4int_in = OpTypeVector %int 4", + "%_ptr_Input_v4u = OpTypePointer Input %v4uint_in", "%_ptr_Input_v4i = OpTypePointer Input %v4int_in"] + for reg, ctype in gen.vertex_inputs: + dec.append(f"OpDecorate %vin{reg} Location {reg}") + if gen.writes_depth: + types += ["%_ptr_Output_float = OpTypePointer Output %float"] + dec += ["OpDecorate %out_depth BuiltIn FragDepth"] + gvars += ["%out_depth = OpVariable %_ptr_Output_float Output"] + gvars += [f"{n} = OpVariable %_ptr_Input_v4 Input" for n in gen.inputs] + if sg: + gvars += ["%sg_lane = OpVariable %_ptr_Input_uint Input"] + if tex: + gvars += ["%images = OpVariable %_ptr_UC_rt_img UniformConstant", + "%samplers = OpVariable %_ptr_UC_rt_smp UniformConstant", + "%desc_map = OpVariable %_ptr_SB_DescMap StorageBuffer"] + if gen.uses_tex_array: + gvars += ["%images_arr = OpVariable %_ptr_UC_rt_imga UniformConstant"] + if gen.uses_storage: + gvars += ["%simages = OpVariable %_ptr_UC_rt_simg UniformConstant"] + if gen.uses_tex_1d: + gvars += ["%images_1d = OpVariable %_ptr_UC_rt_img1 UniformConstant"] + if gen.uses_tex_3d: + gvars += ["%images_3d = OpVariable %_ptr_UC_rt_img3 UniformConstant"] + if gen.uses_storage3d: + gvars += ["%simages3d = OpVariable %_ptr_UC_rt_simg3 UniformConstant"] + if vs: + gvars.append("%vertex_index = OpVariable %_ptr_Input_int Input") + for reg, ctype in gen.vertex_inputs: + ptr = {1: "%_ptr_Input_v4u", 2: "%_ptr_Input_v4i"}.get(ctype, "%_ptr_Input_v4") + gvars.append(f"%vin{reg} = OpVariable {ptr} Input") + fn = ["%main = OpFunction %void None %fn", "%entry = OpLabel", + # Registers start at zero (deterministic); real inputs are written explicitly at entry. + "%vgpr = OpVariable %_ptr_Function_arr_v Function %null_v", + "%sgpr = OpVariable %_ptr_Function_arr_s Function %null_s", + "%vcc = OpVariable %_ptr_Function_uint Function %c0", "%m0 = OpVariable %_ptr_Function_uint Function %c0", + "%vcc_hi = OpVariable %_ptr_Function_uint Function %c0", + "%scc = OpVariable %_ptr_Function_uint Function %c0", + "%active = OpVariable %_ptr_Function_bool Function %true"] + # User data: s0..s31 are loaded at entry from a push-constant block (the driver's user-SGPR setup). + if gen.uses_heap: + gen.consts.setdefault(1, "%c1") + gen.consts.setdefault(2, "%c2") + fn += ["%ud_base_lo_p = OpAccessChain %_ptr_PC_uint %user_data %c1", + "%ud_base_hi_p = OpAccessChain %_ptr_PC_uint %user_data %c2"] + if gen.uses_codebase: + fn += ["%ud_code_lo_p = OpAccessChain %_ptr_PC_uint %user_data %c3", + "%ud_code_hi_p = OpAccessChain %_ptr_PC_uint %user_data %c4"] + for i in range(USER_SGPRS): + fn += [f"%ud{i}p = OpAccessChain %_ptr_PC_uint %user_data %c0 {gen.cu(i)}", + f"%ud{i} = OpLoad %uint %ud{i}p", + f"%ud{i}s = OpAccessChain %_ptr_Function_uint %sgpr {gen.cu(i)}", + f"OpStore %ud{i}s %ud{i}"] + if vs: + fn += ["%vi = OpLoad %int %vertex_index", "%viu = OpBitcast %uint %vi", + "%v0p = OpAccessChain %_ptr_Function_uint %vgpr %c0", "OpStore %v0p %viu"] + if gen.frag_inputs: + fn += ["%fc = OpLoad %v4float %frag_coord"] + for r, c in gen.frag_inputs.items(): + if c == "front": + fn += ["%ff = OpLoad %bool %front_facing", "%ffm1 = OpFNegate %float %f1", + "%ffv = OpSelect %float %ff %f1 %ffm1", "%ffu = OpBitcast %uint %ffv", + f"%ffp = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(r)}", "OpStore %ffp %ffu"] + continue + fn += [f"%fc{c} = OpCompositeExtract %float %fc {c}", f"%fcu{c} = OpBitcast %uint %fc{c}", + f"%fcp{c} = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(r)}", f"OpStore %fcp{c} %fcu{c}"] + for reg, ctype in gen.vertex_inputs: + vt = {1: "%v4uint_in", 2: "%v4int_in"}.get(ctype, "%v4float") + st = {1: "%uint", 2: "%int"}.get(ctype, "%float") + fn.append(f"%vinv{reg} = OpLoad {vt} %vin{reg}") + for c in range(4): + vg = 4 + 4 * reg + c + fn += [f"%vinc{reg}_{c} = OpCompositeExtract {st} %vinv{reg} {c}", + f"%vinb{reg}_{c} = OpBitcast %uint %vinc{reg}_{c}" if ctype != 1 else + f"%vinb{reg}_{c} = OpCopyObject %uint %vinc{reg}_{c}", + f"%vinp{reg}_{c} = OpAccessChain %_ptr_Function_uint %vgpr {gen.cu(vg)}", + f"OpStore %vinp{reg}_{c} %vinb{reg}_{c}"] + out = hdr + dec + types + gvars + fn + if gen.blocks: + # Dispatch loop: any CFG (forward/backward branches) in structured SPIR-V form. + n = len(gen.blocks) + lines = ["%pc = OpVariable %_ptr_Function_uint Function %c0", + "%done = OpVariable %_ptr_Function_bool Function %false", + "OpBranch %loop_head", "%loop_head = OpLabel", "OpLoopMerge %loop_exit %loop_cont None", + "OpBranch %dispatch", "%dispatch = OpLabel", "%pcv = OpLoad %uint %pc", + "OpSelectionMerge %sw_merge None", + "OpSwitch %pcv %sw_default " + " ".join(f"{i} %blk{i}" for i in range(n))] + body = [] + for i, blines in enumerate(gen.blocks): + body.append(f"%blk{i} = OpLabel") + body += blines + body.append("OpBranch %sw_merge") + body += ["%sw_default = OpLabel", "OpStore %done %true", "OpBranch %sw_merge", + "%sw_merge = OpLabel", "OpBranch %loop_cont", "%loop_cont = OpLabel", + "%dn = OpLoad %bool %done", "OpBranchConditional %dn %loop_exit %loop_head", + "%loop_exit = OpLabel"] + # %pc/%done must be declared with the other Function variables, at the top of the entry block, + # before the vertex-shader prologue. + fn_vars = lines[:2] + flow = lines[2:] + last_var = max(i for i, l in enumerate(fn) if " = OpVariable " in l) + fn = fn[:last_var + 1] + fn_vars + fn[last_var + 1:] + out = hdr + dec + types + gvars + fn + gen.body = [" " + l if not (l.startswith("%") and " = OpLabel" in l) else l for l in flow + body] + if gen.uses_active and not vs: + # A pixel lane switched off by v_cmpx at the final export writes nothing: equivalent to discard. + tail = (" %act_end = OpLoad %bool %active\n" + " OpSelectionMerge %live None\n" + " OpBranchConditional %act_end %live %dead\n" + "%dead = OpLabel\n OpKill\n" + "%live = OpLabel\n OpReturn\n OpFunctionEnd\n") + else: + tail = " OpReturn\n OpFunctionEnd\n" + return "\n".join(" " + l if not l.startswith("%") or " = " not in l else l for l in out) + "\n" + \ + "\n".join(gen.body) + "\n" + tail + + +_STAGES = None + + +def stage_of(name, path): + """Shader stage from the carve index (the DXIL program header in each container), not the name.""" + global _STAGES + if _STAGES is None: + import json + idx = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), "index.json") + _STAGES = {} + if os.path.isfile(idx): + for e in json.load(open(idx, encoding="utf-8")): + _STAGES[e["file"][:-5]] = e["stage"] + return _STAGES.get(name) or (name[:2].lower() if name[2:3] == "_" else "?") + + +def reachable_code(insns): + """Instructions reachable from the first one, following fall-through and branch targets. Fall-through stops + after s_endpgm, s_branch and s_setpc_b64. Raises Unsupported if a branch target isn't an instruction start.""" + by_pc = {i["pc"]: k for k, i in enumerate(insns)} + seen, work = set(), [0] + while work: + k = work.pop() + while k is not None and k < len(insns) and k not in seen: + seen.add(k) + ins = insns[k] + op = base_op(ins["op"]) + nxt = ins["pc"] + len(ins["enc"]) // 2 + if op in BRANCHES: + imm = next((x for x in ins["args"] if x["k"] == "imm"), None) + v = (imm["v"] & 0xFFFF) if imm else 0 + tgt = nxt + 4 * (v - 0x10000 if v & 0x8000 else v) + if tgt not in by_pc: + raise Unsupported("branch into data") + work.append(by_pc[tgt]) + if op == "s_branch": + break + if op in ("s_endpgm", "s_setpc_b64"): + break + k = by_pc.get(nxt) + if k is None and op not in ("s_endpgm",): + break + return [insns[k] for k in sorted(seen)] + + +def read_before_write_vgprs(insns): + """VGPRs a shader reads before writing them: for a fetch-calling VS these are the fetched attributes.""" + written, first = set(), [] + for ins in insns: + a, op = ins["args"], ins["op"] + if not a: + continue + reads_all = op.startswith(("exp", "buffer_store", "image_store", "v_cmp", "v_cmpx", "ds_write", "global_store")) + regs = [] + for x in (a if reads_all else a[1:]): + if x["k"] == "vgpr": + regs += range(x["r"], x["r"] + x.get("n", 1)) + elif x["k"] == "vlist": + regs += x["r"] + if base_op(op) in ("v_fmac_f32", "v_mac_f32", "v_fmac_f16") and a[0]["k"] == "vgpr": + regs.append(a[0]["r"]) + for r in regs: + if r not in written and r not in first: + first.append(r) + if not reads_all and a[0]["k"] == "vgpr": + written.update(range(a[0]["r"], a[0]["r"] + a[0].get("n", 1))) + return set(first) + + +def input_signature_full(path, name): + """ISG1 elements as (system value, declared mask, read/write mask).""" + dxbc = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(path))), name + ".dxbc") + d = open(dxbc, "rb").read() + for k in range(struct.unpack_from(" 4096 or pos >= len(blob): + raise Unsupported("undecodable words (cannot re-anchor)") + ins["pc"] = pos + pos += len(enc) + insns = reachable_code(insns) + g = Gen(stage) + if stage == "ps": + # Pixel-shader system VGPRs (verified on 2,531 of 3,000 PS): v0-v1 = barycentrics (modelled through + # v_interp -> attributes), then v2.. = the SV_Position components the shader reads, packed in order. + # Anything else a PS reads before writing is an input layout we haven't confirmed: reject it. + sig = input_signature_full(path, info["name"]) + pos = [rw for sv, m, rw in sig if sv == 1] + used = pos[0] if pos else 0 + # Position w: AMD's POS_W_FLOAT input holds 1/w. Mesa (src/amd/common/nir/ac_nir_lower_intrinsics_to_args.c) + # lowers nir_intrinsic_load_frag_coord_w_rcp straight to frag_pos[3]. That's the same value as Vulkan's + # FragCoord.w, so all four components map directly. + # Hardware order (Mesa src/amd/vulkan/radv_shader_args.c): barycentric pairs, ..., POS_X/Y/Z/W, FRONT_FACE, + # ANCILLARY, SAMPLE_COVERAGE, POS_FIXED_PT. Only enabled inputs are packed. Front face is a float whose + # sign gives facing (Mesa: load_front_face = front_face > 0; load_front_face_fsign = the raw value). + layout = {} + nxt = 2 + for c in range(4): + if used >> c & 1: + layout[nxt] = c + nxt += 1 + if any(sv == 9 for sv, _, _ in sig): # D3D_NAME_IS_FRONT_FACE + layout[nxt] = "front" + nxt += 1 + no_bary = [dict(i, args=[x for k, x in enumerate(i["args"]) + if not (i["op"].startswith("v_interp") and x["k"] == "vgpr" and k != 0)]) + for i in insns] + reads = read_before_write_vgprs(no_bary) + # Reads inside the system-input range that aren't in the layout (raw barycentrics, unknown inputs): reject. + # Reads past the last hardware input can't be hardware inputs: they're values undefined on some path, and + # the zero-initialised registers stand in for them. + unexplained = {r for r in reads if r < nxt and r not in layout} + if unexplained: + raise Unsupported("PS system inputs") + g.frag_inputs = layout + for r in layout: + g.cu(r) + if stage == "vs" and any(base_op(i["op"]) == "s_swappc_b64" for i in insns): + # The call goes to a driver-generated fetch program (not in the blob). Verified rule over 788 shaders: + # input-signature register r, component c is fetched into v(4 + 4r + c). Replace the call with Vulkan + # vertex inputs (location = register) written into those VGPRs at entry. + sig = [s for s in input_signature(path, info["name"]) if s[2] == 0] + predicted = {4 + 4 * reg + c for reg, mask, _, _ in sig for c in range(4) if mask >> c & 1} + reads = {r for r in read_before_write_vgprs(insns) if r >= 4} + if not reads <= predicted: + raise Unsupported("fetch mapping") + g.vertex_inputs = [(reg, ctype) for reg, _, _, ctype in sig] + for reg, _ in g.vertex_inputs: # register the VGPR index constants before assembly + for c in range(4): + g.cu(4 + 4 * reg + c) + insns = [i for i in insns if base_op(i["op"]) != "s_swappc_b64"] + branchy = any(base_op(i["op"]) in BRANCHES for i in insns) + if not branchy: + for ins in insns: + if base_op(ins["op"]) == "s_endpgm": + break + g.insn(ins) + return assemble(g) + + # ---- basic blocks ---- + def next_pc(ins): + return ins["pc"] + len(ins["enc"]) // 2 + + def target(ins): + imm = next((x for x in ins["args"] if x["k"] == "imm"), None) + if imm is None: + raise Unsupported("branch without offset") + v = imm["v"] & 0xFFFF + return next_pc(ins) + 4 * (v - 0x10000 if v & 0x8000 else v) + + leaders = {insns[0]["pc"]} + for ins in insns: + if base_op(ins["op"]) in BRANCHES: + leaders.add(target(ins)) + leaders.add(next_pc(ins)) + starts = sorted(p for p in leaders if any(i["pc"] == p for i in insns)) + if any(p not in starts for p in (target(i) for i in insns if base_op(i["op"]) in BRANCHES)): + raise Unsupported("branch target outside code") + index = {p: n for n, p in enumerate(starts)} + blocks = [[] for _ in starts] + cur = -1 + for ins in insns: + if ins["pc"] in index: + cur = index[ins["pc"]] + blocks[cur].append(ins) + + for n, blk in enumerate(blocks): + g.body = [] + g.block_label = f"%blk{n}" + term = None + for ins in blk: + op = base_op(ins["op"]) + if op == "s_endpgm": + term = ("end",) + break + if op in BRANCHES: + term = ("br", op, index[target(ins)]) + break + g.insn(ins) + fall = n + 1 if n + 1 < len(blocks) else None + if term is None: + g.emit(f"OpStore %pc {g.cu(fall)}" if fall is not None else "OpStore %done %true") + elif term[0] == "end": + g.emit("OpStore %done %true") + else: + _, op, tgt = term + if op == "s_branch": + g.emit(f"OpStore %pc {g.cu(tgt)}") + else: + cond = branch_condition(g, op) + alt = g.cu(fall) if fall is not None else g.cu(len(blocks)) # past the end = default -> done + r = g.tmp() + g.emit(f"{r} = OpSelect %uint {cond} {g.cu(tgt)} {alt}") + g.emit(f"OpStore %pc {r}") + g.blocks.append([l.strip() for l in g.body]) + g.body = [] + return assemble(g) + + +BRANCHES = {"s_branch", "s_cbranch_scc0", "s_cbranch_scc1", "s_cbranch_vccz", "s_cbranch_vccnz", + "s_cbranch_execz", "s_cbranch_execnz"} + + +def branch_condition(g, op): + """Boolean SPIR-V id: whether the branch is taken for this lane.""" + if op in ("s_cbranch_scc0", "s_cbranch_scc1"): + s = g.tmp() + g.emit(f"{s} = OpLoad %uint %scc") + b = g.tmp() + g.emit(f"{b} = {'OpIEqual' if op.endswith('0') else 'OpINotEqual'} %bool {s} {g.cu(0)}") + return b + if op in ("s_cbranch_vccz", "s_cbranch_vccnz"): + s = g.tmp() + g.emit(f"{s} = OpLoad %uint %vcc") + b = g.tmp() + g.emit(f"{b} = {'OpIEqual' if op.endswith('vccz') else 'OpINotEqual'} %bool {s} {g.cu(0)}") + return b + a = g.active_b() + if op == "s_cbranch_execnz": + return a + b = g.tmp() + g.emit(f"{b} = OpLogicalNot %bool {a}") + return b + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("src") + ap.add_argument("--out", required=True) + ap.add_argument("--limit", type=int) + a = ap.parse_args() + files = [a.src] if a.src.endswith(".s") else sorted(os.path.join(a.src, f) for f in os.listdir(a.src) if f.endswith(".s")) + files = files[: a.limit] if a.limit else files + os.makedirs(a.out, exist_ok=True) + why, ok, valid = Counter(), 0, 0 + for p in files: + name = os.path.splitext(os.path.basename(p))[0] + try: + asm = translate(p) + except Unsupported as e: + why[str(e)] += 1 + continue + except (IndexError, KeyError, ValueError) as e: + why[f"translator error {type(e).__name__}"] += 1 + continue + ok += 1 + sa = os.path.join(a.out, name + ".spvasm") + sv = os.path.join(a.out, name + ".spv") + with open(sa, "w") as f: + f.write(asm) + r = subprocess.run(["spirv-as", sa, "-o", sv, "--target-env", "vulkan1.2"], capture_output=True, text=True) + if r.returncode == 0: + r = subprocess.run(["spirv-val", "--target-env", "vulkan1.2", sv], capture_output=True, text=True) + if r.returncode == 0: + valid += 1 + else: + why["INVALID: " + (r.stderr.strip().splitlines() or ["?"])[0][:90]] += 1 + print(f"{len(files)} shaders: {ok} translated, {valid} pass spirv-val") + for k, v in why.most_common(25): + print(f" {v:6} {k}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/rpf9_carve.py b/tools/rpf9_carve.py new file mode 100644 index 000000000..ca44c772d --- /dev/null +++ b/tools/rpf9_carve.py @@ -0,0 +1,122 @@ +"""Carve the zlib-compressed files out of an RPF9 archive without its (encrypted) table of contents. + +The data area is mostly zlib streams laid end to end, separated by zero padding. This walks the archive, inflates +every stream that decodes cleanly to the end, and writes each one as .bin. It also records which byte +ranges it couldn't read, so coverage is measurable. + +Usage: + python -I rpf9_carve.py [--start N] [--limit BYTES] [--index-only] +""" +import argparse +import json +import mmap +import os +import re +import struct +import sys +import time +import zlib + +# zlib stream start, or a Bink 2 video ('KB2' + revision letter, then u32 size-8). +ZHDR = re.compile(rb"\x78[\x01\x5e\x9c\xda]|KB2[a-z]") + + +def below_normal(): + if os.name == "nt": + import ctypes + k = ctypes.windll.kernel32 + k.SetPriorityClass(k.GetCurrentProcess(), 0x00004000) + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("archive") + ap.add_argument("out") + ap.add_argument("--start", type=int) + ap.add_argument("--limit", type=int) + ap.add_argument("--index-only", action="store_true") + a = ap.parse_args() + below_normal() + os.makedirs(a.out, exist_ok=True) + with open(a.archive, "rb") as fh: + m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) + size = len(m) + pos = a.start if a.start is not None else struct.unpack_from(" "); return 2; } +string mode = args[0], src = Path.GetFullPath(args[1]), outRoot = Path.GetFullPath(args[2]); +var json = new JsonSerializerOptions { WriteIndented = true }; +var sw = Stopwatch.StartNew(); +string baseName = Path.GetFileNameWithoutExtension(src); +string outDir = Path.Combine(outRoot, baseName); Directory.CreateDirectory(outDir); +long length = new FileInfo(src).Length; +int ok = 0, fail = 0, skip = 0; + +if (mode == "ttpf") +{ + var info = TtpfReader.Inspect(src); + var rows = new List(); + foreach (var t in info.Textures) + { + string name = $"{t.Index:D6}_{Util.Safe(Path.GetFileNameWithoutExtension(t.Name))}.dds"; + rows.Add(new { t.Index, t.Name, t.Id, AssetKey = t.AssetKey.ToString("X16"), t.Width, t.Height, t.DxgiFormat, t.Mips, t.SourceMips, t.BaseMipLevel, t.Limitation, File = t.CanExtract ? name : null }); + if (!t.CanExtract) { skip++; continue; } + string path = Path.Combine(outDir, name); + if (File.Exists(path)) { ok++; continue; } + try { File.WriteAllBytes(path, TtpfReader.CreateDds(src, t.Index)); ok++; } + catch (Exception e) { fail++; if (fail <= 5) Console.WriteLine($" fail {t.Index}: {e.GetType().Name} {e.Message}"); } + if ((ok + fail) % 5000 == 0) Console.WriteLine($" {ok + fail}/{info.Textures.Count}"); + } + File.WriteAllText(Path.Combine(outDir, "manifest.json"), JsonSerializer.Serialize(new { src, info.Version, Count = info.Textures.Count, info.Metadata, Textures = rows }, json)); +} +else if (mode == "audio") +{ + if (!AwcRecovery.HasCompleteCache(src)) + { + long last = -1; + var prog = new Progress(p => { long s = p / (4L << 30); if (s != last) { last = s; Console.WriteLine($" awc scan {100.0 * p / length:0.0}%"); } }); + var found = AwcRecovery.RecoverFull(src, prog); + AwcRecovery.WriteCache(src, found); + Console.WriteLine($" {found.Count:N0} AWC banks ({sw.Elapsed.TotalSeconds:0}s)"); + } + var doc = ArchiveReader.Open(src); + var banks = doc.Entries.Where(e => e.Extension == ".awc" && e.CanExtract).ToList(); + string sub = Path.Combine(outDir, "awc"); + var todo = banks.Where(e => !File.Exists(ArchiveReader.SafeDestination(sub, e.Path))).ToList(); + Console.WriteLine($" {banks.Count:N0} banks, {todo.Count:N0} to write"); + for (int i = 0; i < todo.Count; i += 500) + doc.ExtractAsync(todo.Skip(i).Take(500), sub).GetAwaiter().GetResult(); + ok = banks.Count; + var rows = banks.Select(e => { var info = AwcInfo.Inspect(src, e.Offset, e.Size); + return new { e.Path, e.Offset, e.Size, Streams = info?.Streams.Select(s => new { s.Index, Id = s.Id.ToString("X8"), s.Codec, s.Channels, s.SampleRate, s.DurationSeconds, s.IsStreamed }) }; }).ToList(); + File.WriteAllText(Path.Combine(outDir, "audio_manifest.json"), JsonSerializer.Serialize(new { src, Count = banks.Count, Banks = rows }, json)); +} +else if (mode is "models" or "textures") +{ + byte[] header; using (var f = File.OpenRead(src)) { header = new byte[64]; f.ReadExactly(header); } + var cached = RecoveryIndexCache.Load(mode, src, length, header); + if (cached == null) + { + long last = -1; + var prog = new Progress(p => { long s = p / (4L << 30); if (s != last) { last = s; Console.WriteLine($" scan {100.0 * p / length:0.0}%"); } }); + var cands = mode == "models" ? Rpf9ModelRecovery.FindCandidateOffsets(src, progress: prog) : Rpf9TextureRecovery.FindCandidateOffsets(src, progress: prog); + Console.WriteLine($" candidates {cands.Count:N0} ({sw.Elapsed.TotalSeconds:0}s)"); + var entries = new List(); + for (int i = 0; i < cands.Count; i += 32) + { + var chunk = cands.Skip(i).Take(32).ToArray(); + var got = mode == "models" ? Rpf9ModelRecovery.RecoverAtOffsets(src, length, chunk, entries.Count) : Rpf9TextureRecovery.RecoverAtOffsets(src, length, chunk, entries.Count); + entries.AddRange(got); + if ((i / 32) % 200 == 0) Console.WriteLine($" validated {i + chunk.Length:N0}/{cands.Count:N0} -> {entries.Count:N0} ({sw.Elapsed.TotalSeconds:0}s)"); + } + entries = entries.OrderBy(e => e.Offset).Select((e, k) => e with { Index = k }).ToList(); + RecoveryIndexCache.Save(mode, src, entries, $"rpf9dump full scan, {cands.Count:N0} candidates, {entries.Count:N0} recovered"); + } + var doc = ArchiveReader.Open(src); + string want = mode == "models" ? "Recovered model" : "Recovered texture dictionary"; + var list = doc.Entries.Where(e => e.Compression == want).ToList(); + Console.WriteLine($" {list.Count:N0} {mode} entries ({sw.Elapsed.TotalSeconds:0}s)"); + string sub = Path.Combine(outDir, mode); Directory.CreateDirectory(sub); + var rows = new List(); + int embedded = 0; + foreach (var e in list) + { + string stem = Util.Safe(Path.GetFileNameWithoutExtension(e.Name)); + try + { + var data = ArchiveReader.ReadResourceData(doc, e); + int split = e.ResourceSystemBytes ?? checked((int)e.Segments![0].Size); + var sys = data.AsSpan(0, split); var gfx = data.AsSpan(split); + if (mode == "models") + { + var m = RageModelDecoder.Decode(sys, gfx); + if (m == null) { fail++; continue; } + string obj = Path.Combine(sub, stem + ".obj"); + if (!File.Exists(obj)) File.WriteAllText(obj, RageModelDecoder.CreateObj(m)); + if (m.EmbeddedTextures != null && m.EmbeddedTextureDictionaryOffset is int dOff) + { + string td = Path.Combine(sub, stem + "_tex"); Directory.CreateDirectory(td); + foreach (var t in m.EmbeddedTextures) + { + string p = Path.Combine(td, $"{t.Index:D3}_{Util.Safe(t.Name)}.dds"); + if (File.Exists(p)) { embedded++; continue; } + try { File.WriteAllBytes(p, Util.BgraDds(RageTextureDecoder.DecodeEmbeddedTexturePixels(sys, gfx, dOff, t.Index))); embedded++; } catch { } + } + } + rows.Add(new { e.Offset, File = stem + ".obj", m.Name, Meshes = m.Meshes.Count, Verts = m.Meshes.Sum(x => x.Positions.Count), Tris = m.Meshes.Sum(x => x.Indices.Count) / 3, m.IsFragment, m.HasBoneBindings, + Min = new[] { m.BoundsMin.X, m.BoundsMin.Y, m.BoundsMin.Z }, Max = new[] { m.BoundsMax.X, m.BoundsMax.Y, m.BoundsMax.Z }, + MeshShaders = m.Meshes.Select(x => x.ShaderIndex), + Embedded = m.EmbeddedTextures?.Select(t => new { t.Index, t.Name, t.Width, t.Height, t.Format, Hash = t.NameHash.ToString("X8"), Key = t.AssetKey?.ToString("X16") }), + Materials = m.Materials?.Select(x => new { x.ShaderIndex, Shader = x.ShaderHash.ToString("X8"), Preset = x.PresetHash.ToString("X8"), x.RenderBucket, + Textures = x.Textures.Select(r => new { Param = r.ParameterHash.ToString("X8"), r.TextureIndex, Name = r.NameHash.ToString("X8"), Id64 = r.OpaqueId64.ToString("X16"), Tag = r.Tag.ToString("X8") }) }) }); + ok++; + } + else + { + var dict = RageTextureDecoder.Inspect(sys, gfx); + if (dict == null) { fail++; continue; } + string td = Path.Combine(sub, stem); Directory.CreateDirectory(td); + foreach (var t in dict.Textures) + { + string p = Path.Combine(td, $"{t.Index:D3}_{Util.Safe(t.Name)}.dds"); + try { if (!File.Exists(p)) File.WriteAllBytes(p, RageTextureDecoder.CreateDds(sys, gfx, t.Index)); ok++; } catch { fail++; } + } + rows.Add(new { e.Offset, Dir = stem, Textures = dict.Textures.Select(t => new { t.Index, t.Name, t.Width, t.Height, t.Format, t.MipCount, Hash = t.NameHash.ToString("X8"), Key = t.AssetKey?.ToString("X16") }) }); + } + } + catch (Exception ex) { fail++; if (fail <= 5) Console.WriteLine($" fail {e.Name}: {ex.GetType().Name} {ex.Message}"); } + if ((ok + fail) % 1000 == 0) Console.WriteLine($" exported {ok + fail:N0}/{list.Count:N0}"); + } + if (mode == "models") Console.WriteLine($" embedded textures {embedded:N0}"); + File.WriteAllText(Path.Combine(sub, "manifest.json"), JsonSerializer.Serialize(new { src, Count = list.Count, Items = rows }, json)); +} +Console.WriteLine($"{mode} {baseName}: ok={ok} fail={fail} skip={skip} in {sw.Elapsed.TotalSeconds:0}s"); +return 0; + +static class Util +{ + public static string Safe(string s) + { + var bad = Path.GetInvalidFileNameChars(); + var c = s.Select(ch => bad.Contains(ch) || char.IsControl(ch) ? '_' : ch).ToArray(); + var v = new string(c).Trim(' ', '.'); return v.Length == 0 ? "x" : v[..Math.Min(120, v.Length)]; + } + // Uncompressed 32-bit BGRA DDS (legacy header, A8R8G8B8 masks). + public static byte[] BgraDds(RageTexturePixels px) + { + var o = new byte[128 + px.Bgra32.Length]; + void U(int at, uint v) => BitConverter.TryWriteBytes(o.AsSpan(at), v); + U(0, 0x20534444); U(4, 124); U(8, 0x100F); U(12, (uint)px.Height); U(16, (uint)px.Width); U(20, (uint)(px.Width * 4)); + U(76, 32); U(80, 0x41); U(88, 32); U(92, 0x00FF0000); U(96, 0x0000FF00); U(100, 0x000000FF); U(104, 0xFF000000); U(108, 0x1000); + px.Bgra32.CopyTo(o, 128); return o; + } +} diff --git a/tools/rpf9dump/rpf9dump.csproj b/tools/rpf9dump/rpf9dump.csproj new file mode 100644 index 000000000..7a77370de --- /dev/null +++ b/tools/rpf9dump/rpf9dump.csproj @@ -0,0 +1,5 @@ + + Exenet8.0enableenabletrue + + + diff --git a/tools/rpf_probe.py b/tools/rpf_probe.py new file mode 100644 index 000000000..c8852b86b --- /dev/null +++ b/tools/rpf_probe.py @@ -0,0 +1,66 @@ +"""Survey the .rpf archives in a game folder: version magic, header words, and whether the table looks encrypted. + +Usage: + python -I rpf_probe.py [--out FILE] + +Reads the first 64 KiB of each archive only. It doesn't decrypt or extract anything. +""" +import argparse +import json +import math +import os +import struct +import sys +from collections import Counter + + +def entropy(b: bytes) -> float: + if not b: + return 0.0 + n = len(b) + return -sum(c / n * math.log2(c / n) for c in Counter(b).values()) + + +def probe(path: str) -> dict: + with open(path, "rb") as f: + head = f.read(0x10000) + magic = head[:4] + # Little-endian 'RPFn' is stored as bytes 'nFPR'. + version = magic[::-1].decode("latin-1") if magic[1:] == b"FPR" else None + words = list(struct.unpack_from("<4I", head, 4)) if len(head) >= 20 else [] + body = head[16:] + return { + "file": path, + "size": os.path.getsize(path), + "version": version, + "header_words": [hex(w) for w in words], + "head_entropy": round(entropy(body), 3), + "looks_encrypted": entropy(body) > 7.9, + } + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("game_dir") + ap.add_argument("--out", default=os.path.join(os.path.dirname(__file__), "..", "reports", "rpf_probe.json")) + a = ap.parse_args() + rows = [] + for root, _, files in os.walk(a.game_dir): + for name in files: + if name.lower().endswith(".rpf"): + rows.append(probe(os.path.join(root, name))) + rows.sort(key=lambda r: -r["size"]) + os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True) + with open(a.out, "w", encoding="utf-8") as f: + json.dump(rows, f, indent=1) + versions = Counter(r["version"] for r in rows) + print(f"{len(rows)} archives, {sum(r['size'] for r in rows) / 2**30:.1f} GiB, versions {dict(versions)}") + for r in rows: + rel = os.path.relpath(r["file"], a.game_dir) + print(f"{rel:<52} {r['size'] / 2**30:7.2f} GiB {r['version']} {' '.join(r['header_words'])} " + f"H={r['head_entropy']}{' packed/encrypted' if r['looks_encrypted'] else ''}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/rtti_scan.py b/tools/rtti_scan.py new file mode 100644 index 000000000..01fab1e1f --- /dev/null +++ b/tools/rtti_scan.py @@ -0,0 +1,120 @@ +"""Recover C++ class names, hierarchies and vtables from an x64 MSVC PE via RTTI. + +x64 RTTI uses image-relative (RVA) fields: + TypeDescriptor { u64 pVFTable; u64 spare; char name[] = ".?AVClass@ns@@" } + CompleteObjectLocator { u32 signature(=1); u32 offset; u32 cdOffset; u32 rvaTypeDescriptor; + u32 rvaClassHierarchy; u32 rvaSelf } + ClassHierarchyDescriptor { u32 signature; u32 attributes; u32 numBaseClasses; u32 rvaBaseClassArray } + BaseClassDescriptor { u32 rvaTypeDescriptor; u32 numContainedBases; i32 mdisp, pdisp, vdisp; u32 attrs; + u32 rvaClassHierarchy } +A vtable is preceded (at -8) by a pointer to its CompleteObjectLocator. + +Usage: + python -I rtti_scan.py [--out file.json] +Output: classes (demangled-ish name, type descriptor RVA, base classes) and vtables (RVA, class, offset in the +complete object, number of slots that point into executable sections). +""" +import argparse +import json +import re +import struct +import sys + +import pefile + + +def simple_name(mangled: str) -> str: + """'.?AVFoo@bar@@' -> 'bar::Foo' (enough to read; full demangling isn't needed here).""" + m = re.match(r"\.\?A[VUW](.*)@@$", mangled) + if not m: + return mangled + parts = [p for p in m.group(1).split("@") if p] + return "::".join(reversed(parts)) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("image") + ap.add_argument("--out") + a = ap.parse_args() + pe = pefile.PE(a.image, fast_load=True) + base = pe.OPTIONAL_HEADER.ImageBase + img = pe.get_memory_mapped_image() + exec_ranges = [(s.VirtualAddress, s.VirtualAddress + s.Misc_VirtualSize) for s in pe.sections + if s.Characteristics & 0x20000000] + + def is_exec(rva): + return any(lo <= rva < hi for lo, hi in exec_ranges) + + def u32(rva): + return struct.unpack_from("= 0: + tds[rva] = m.group(0)[:-1].decode("latin-1") + + # 2. Complete object locators: signature 1 and rvaSelf == own RVA. + cols = {} + for m in re.finditer(rb"\x01\x00\x00\x00", img): + rva = m.start() + if rva % 4 or rva + 24 > len(img): + continue + sig, off, cd, rtd, rchd, rself = struct.unpack_from("<6I", img, rva) + if rself == rva and rtd in tds: + cols[rva] = {"offset": off, "td": rtd, "chd": rchd} + + # 3. Class hierarchies. + classes = {} + for rva, col in cols.items(): + td = col["td"] + if td in classes: + continue + chd = col["chd"] + try: + _, attrs, nbase, rarr = struct.unpack_from("<4I", img, chd) + bases = [] + for i in range(1, min(nbase, 256)): + bcd = u32(rarr + 4 * i) + btd = u32(bcd) + if btd in tds: + bases.append(simple_name(tds[btd])) + except struct.error: + attrs, bases = 0, [] + classes[td] = {"name": simple_name(tds[td]), "mangled": tds[td], "td_rva": td, + "multiple": bool(attrs & 1), "virtual": bool(attrs & 2), "bases": bases} + + # 4. Vtables: a qword equal to (image base + COL rva), followed by code pointers. + vtables = [] + col_vas = {base + rva: rva for rva in cols} + for sec in pe.sections: + if sec.Characteristics & 0x20000000: + continue + lo, hi = sec.VirtualAddress, sec.VirtualAddress + sec.Misc_VirtualSize + for p in range(lo - lo % 8, hi - 8, 8): + q = struct.unpack_from(" {path}") + for c in out["classes"][:5]: + print(" ", c["name"], "<-", ", ".join(c["bases"][:4])) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/shader_carve.py b/tools/shader_carve.py new file mode 100644 index 000000000..72cf4cd18 --- /dev/null +++ b/tools/shader_carve.py @@ -0,0 +1,85 @@ +"""Carve shader containers out of an RPF9 archive without reading its (encrypted) table of contents. + +Each shader in shaders.rpf is stored as: + + 00 + +and inflates to a DXBC container (`size` bytes) holding DXIL plus an Xbox PRIV part. + +Usage: + python -I shader_carve.py + +Writes /.dxbc and /index.json (name, offset, stage, shader model, parts). +""" +import json +import mmap +import os +import re +import struct +import sys +import zlib + +ENTRY = re.compile(rb"([\x21-\x7e]{3,200})\x00(.)(....)(....)\3(....)", re.DOTALL) +STAGES = {0: "ps", 1: "vs", 2: "gs", 3: "hs", 4: "ds", 5: "cs", 6: "lib", 13: "ms", 14: "as"} + + +def parts(dxbc: bytes) -> dict: + n = struct.unpack_from("> 4}.{ver & 0xF}" + + +def main() -> int: + src, out = sys.argv[1], sys.argv[2] + os.makedirs(out, exist_ok=True) + index, seen, bad = [], {}, 0 + with open(src, "rb") as fh: + m = mmap.mmap(fh.fileno(), 0, access=mmap.ACCESS_READ) + for mt in ENTRY.finditer(m): + name = mt.group(1).decode("latin-1") + stored = struct.unpack(":"/\\|?*]', "_", name) + (f"~{n}" if n else "") + ".dxbc" + with open(os.path.join(out, fname), "wb") as f: + f.write(data) + index.append({"name": name, "file": fname, "offset": mt.start(), "kind": mt.group(2)[0], + "stage": stage, "sm": sm, "size": size, "parts": {k: v[1] for k, v in p.items()}}) + with open(os.path.join(out, "index.json"), "w", encoding="utf-8") as f: + json.dump(index, f, indent=1) + from collections import Counter + print(f"{len(index)} shaders carved, {bad} candidates rejected") + print("stages:", dict(Counter(e["stage"] for e in index))) + print("shader models:", dict(Counter(e["sm"] for e in index))) + print("parts:", dict(Counter(k for e in index for k in e["parts"]))) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/shader_disasm.py b/tools/shader_disasm.py new file mode 100644 index 000000000..0c0f24d0d --- /dev/null +++ b/tools/shader_disasm.py @@ -0,0 +1,93 @@ +"""Disassemble the native RDNA2 code in unpacked FSSM shader blobs with LLVM's AMDGPU disassembler. + +FSSM header (little-endian qwords at 0x00..): 'FSSM' 01 01, blob size, ..., then a table where the +code range appears as (offset, size) = qword[6], qword[7] in every blob checked so far (e.g. 0x2f8, 0x100). +The code ends with s_endpgm (0xBF810000). If the header guess doesn't hold for a blob, the tool falls back to +scanning back from the first s_endpgm to the start that decodes with no invalid instructions. + +Usage: + python -I shader_disasm.py [--out DIR] [--mcpu gfx1013] [--limit N] +Writes /.s and prints a summary (decoded cleanly / with invalid words / failed). +""" +import argparse +import os +import struct +import subprocess +import sys +from concurrent.futures import ThreadPoolExecutor + +LLVM_MC = os.environ.get("LLVM_MC", "llvm-mc") +ENDPGM = b"\x00\x00\x81\xbf" + + +def disasm(code: bytes, mcpu: str): + text = " ".join(f"0x{b:02x}" for b in code) + p = subprocess.run([LLVM_MC, "--disassemble", "-triple=amdgcn--amdpal", f"-mcpu={mcpu}", "-show-encoding"], + input=text, capture_output=True, text=True, + creationflags=getattr(subprocess, "BELOW_NORMAL_PRIORITY_CLASS", 0)) + bad = p.stderr.count("invalid instruction encoding") + return p.stdout, bad, p.stderr + + +def code_range(b: bytes): + """The code section offset is the u32 at 0xC0; instructions start 0x28 bytes into it and run to the last + 4-byte-aligned s_endpgm in the blob (some blobs hold several programs). Found by correlating against + clean decodes of 154 random shaders.""" + off = struct.unpack_from("= 0 and (last - start) % 4: + last = b.rfind(ENDPGM, start, last) + if last >= 0: + return start, last + 4, "header" + end = b.find(ENDPGM) + return None, end + 4 if end >= 0 else None, "scan" + + +def one(path, out, mcpu): + b = open(path, "rb").read() + start, end, how = code_range(b) + if end is None: + return "no s_endpgm" + if start is None: + # Walk back in 4-byte steps from the end and keep the longest clean decode. + start, best = end - 4, None + for s in range(end - 4, max(0x100, end - 0x4000) - 1, -4): + _, bad, _ = disasm(b[s:end], mcpu) + if bad == 0: + best = s + if best is None: + return "scan failed" + start = best + asm, bad, err = disasm(b[start:end], mcpu) + name = os.path.splitext(os.path.basename(path))[0] + with open(os.path.join(out, name + ".s"), "w", encoding="utf-8") as f: + f.write(f"; {name} code 0x{start:x}..0x{end:x} ({how}), {mcpu}, {bad} invalid words\n") + f.write(asm) + if err.strip(): + f.write("\n; --- llvm-mc messages ---\n; " + err.strip().replace("\n", "\n; ") + "\n") + return "clean" if bad == 0 else "invalid words" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("src") + ap.add_argument("--out") + ap.add_argument("--mcpu", default="gfx1013") + ap.add_argument("--limit", type=int) + ap.add_argument("--jobs", type=int, default=max(1, (os.cpu_count() or 2) // 2)) + a = ap.parse_args() + files = [a.src] if os.path.isfile(a.src) else sorted( + os.path.join(a.src, f) for f in os.listdir(a.src) if f.endswith(".fssm")) + files = files[: a.limit] if a.limit else files + out = a.out or os.path.join(os.path.dirname(files[0]), "..", "disasm") + os.makedirs(out, exist_ok=True) + from collections import Counter + with ThreadPoolExecutor(a.jobs) as ex: + res = Counter(ex.map(lambda p: one(p, out, a.mcpu), files)) + print(f"{len(files)} shaders -> {os.path.abspath(out)}: {dict(res)}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/shader_ir.py b/tools/shader_ir.py new file mode 100644 index 000000000..9c2f136a4 --- /dev/null +++ b/tools/shader_ir.py @@ -0,0 +1,160 @@ +"""Parse LLVM AMDGPU disassembly (.s from shader_disasm.py) into a structured instruction list. + +Each instruction: {"op": mnemonic, "args": [operand...], "mods": [modifier...], "enc": bytes, "pc": byte offset} +Operand kinds: sgpr s5 / s[4:7], vgpr v3 / v[0:3], special (vcc, exec, m0, scc...), inline constant, literal, +label/offset (for branches), hw register, and raw text for anything else. + +As a module: parse_file(path) -> {"name", "code_start", "insns": [...], "invalid": [pc...]} +As a tool: python -I shader_ir.py [--limit N] (parses everything and reports coverage) +""" +import os +import re +import sys +from collections import Counter + +ENC = re.compile(r";\s*encoding:\s*\[([^\]]*)\]") +HDR = re.compile(r"^;\s*(\S+)\s+code 0x([0-9a-f]+)\.\.0x([0-9a-f]+)") +SPECIAL = {"vcc", "vcc_lo", "vcc_hi", "exec", "exec_lo", "exec_hi", "m0", "scc", "null", "off", "src_scc", + "src_execz", "src_vccz", "src_lds_direct", "src_shared_base", "src_shared_limit", + "src_private_base", "src_private_limit", "src_pops_exiting_wave_id", "lds", "flat_scratch", + "flat_scratch_lo", "flat_scratch_hi", "ttmp", "tba", "tma"} + + +def operand(tok): + t = tok.strip() + neg = t.startswith("-") + core = t[1:] if neg else t + absm = core.startswith("|") and core.endswith("|") + if absm: + core = core[1:-1] + m = re.fullmatch(r"([sv])(\d+)", core) + if m: + return {"k": m.group(1) + "gpr", "r": int(m.group(2)), "n": 1, "neg": neg, "abs": absm} + m = re.fullmatch(r"([sv])\[(\d+):(\d+)\]", core) + if m: + lo, hi = int(m.group(2)), int(m.group(3)) + return {"k": m.group(1) + "gpr", "r": lo, "n": hi - lo + 1, "neg": neg, "abs": absm} + m = re.fullmatch(r"ttmp(\d+)|ttmp\[(\d+):(\d+)\]", core) + if m: + return {"k": "ttmp", "t": core} + m = re.fullmatch(r"\[(v\d+(?:,\s*v\d+)+)\]", core) + if m: # NSA image address: non-contiguous VGPR list + return {"k": "vlist", "r": [int(x.strip()[1:]) for x in m.group(1).split(",")]} + m = re.fullmatch(r"attr(\d+)\.([xyzw])", core) + if m: + return {"k": "attr", "a": int(m.group(1)), "c": "xyzw".index(m.group(2))} + if core in ("p0", "p10", "p20"): + return {"k": "interp", "t": core} + m = re.fullmatch(r"(pos|param|mrt|mrtz|null|prim)(\d*)", core) + if m and core not in ("null",): + return {"k": "target", "t": core} + if core in SPECIAL: + return {"k": "special", "t": core, "neg": neg, "abs": absm} + if re.fullmatch(r"-?(0x[0-9a-fA-F]+|\d+)", core): + v = int(core, 0) + return {"k": "imm", "v": -v if neg else v} + if re.fullmatch(r"-?\d+\.\d+(e[+-]?\d+)?", core): + return {"k": "fimm", "v": float(core) * (-1 if neg else 1), "abs": absm} + if core.startswith("hwreg(") or core.startswith("sendmsg(") or core.startswith("vmcnt(") or \ + core.startswith("expcnt(") or core.startswith("lgkmcnt(") or core.startswith("vscnt(") or \ + core.startswith("depctr") or core.startswith("instid") or core.startswith("quad_perm") or \ + core.startswith("row_") or core.startswith("dpp") or core.startswith("sel:") or "(" in core: + return {"k": "special", "t": core} + return {"k": "raw", "t": t} + + +def split_args(s): + out, depth, cur = [], 0, "" + for ch in s: + if ch in "([": + depth += 1 + elif ch in ")]": + depth -= 1 + if ch == "," and depth == 0: + out.append(cur) + cur = "" + else: + cur += ch + if cur.strip(): + out.append(cur) + return out + + +SENDMSG = re.compile(r"sendmsg\([^)]*\)") + +MODWORDS = re.compile(r"\b(offset:\S+|offen|idxen|glc|slc|dlc|lds|tfe|unorm|da|d16|a16|nv|r128|lwe|clamp|" + r"mul:\d+|div:\d+|op_sel(?:_hi)?:\[[^\]]*\]|neg_lo:\[[^\]]*\]|neg_hi:\[[^\]]*\]|" + r"dmask:\S+|dim:\S+|format:\S+|done|vm|compr|row_mask:\S+|bank_mask:\S+|" + r"bound_ctrl:\S+|fi:\S+|offset0:\S+|offset1:\S+|gds|inst_offset:\S+|" + r"dst_sel:\S+|dst_unused:\S+|src0_sel:\S+|src1_sel:\S+|high|dpp8:\[[^\]]*\]|" + r"row_mirror|row_half_mirror|row_shl:\d+|row_shr:\d+|row_ror:\d+|row_share:\d+|" + r"row_xmask:\d+|quad_perm:\[[^\]]*\])(?=\s|,|$)") + + +def parse_line(line): + code, _, comment = line.partition(";") + enc = None + m = ENC.search(line) + if m: + enc = bytes(int(x, 16) for x in m.group(1).split(",") if x.strip()) + code = code.strip() + if not code: + return None + op, _, rest = code.partition(" ") + # sendmsg(MSG_GS, GS_OP_NOP) contains a comma: keep it as one operand. + rest = SENDMSG.sub(lambda m: m.group(0).replace(", ", "|").replace(",", "|"), rest) + mods = MODWORDS.findall(rest) + rest = MODWORDS.sub("", rest) + parts = [a for a in split_args(rest) if a.strip()] + # 'exp pos0 v3, ...' / 'exp null off, ...': the target is space-separated from the first operand. + if parts and len(parts[0].split()) == 2: + parts = parts[0].split() + parts[1:] + args = [operand(a) for a in parts] + return {"op": op, "args": args, "mods": mods, "enc": enc.hex() if enc else None} + + +def parse_file(path): + with open(path, encoding="utf-8", errors="replace") as f: + lines = f.read().splitlines() + info = {"name": os.path.splitext(os.path.basename(path))[0], "insns": [], "invalid": 0} + m = HDR.match(lines[0]) if lines else None + pc = int(m.group(2), 16) if m else 0 + info["code_start"] = pc + for ln in lines[1:]: + if ln.startswith("; ---"): + break + if not ln.startswith("\t"): + continue + ins = parse_line(ln) + if not ins: + continue + ins["pc"] = pc + if ins["enc"]: + pc += len(ins["enc"]) // 2 + info["insns"].append(ins) + tail = "\n".join(lines) + info["invalid"] = tail.count("invalid instruction encoding") + return info + + +def main(): + src = sys.argv[1] + limit = int(sys.argv[3]) if len(sys.argv) > 3 and sys.argv[2] == "--limit" else None + files = sorted(f for f in os.listdir(src) if f.endswith(".s"))[:limit] + kinds, raw, n_ins, no_enc = Counter(), Counter(), 0, 0 + for f in files: + info = parse_file(os.path.join(src, f)) + for ins in info["insns"]: + n_ins += 1 + no_enc += ins["enc"] is None + for a in ins["args"]: + kinds[a["k"]] += 1 + if a["k"] == "raw": + raw[a["t"]] += 1 + print(f"{len(files)} shaders, {n_ins:,} instructions, {no_enc} without encoding bytes") + print("operand kinds:", dict(kinds.most_common())) + print("unparsed (raw) operands:", raw.most_common(15)) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/shader_profile.py b/tools/shader_profile.py new file mode 100644 index 000000000..799b56c32 --- /dev/null +++ b/tools/shader_profile.py @@ -0,0 +1,79 @@ +"""Profile the disassembled shader corpus: which RDNA instructions the translator must support. + +Usage: + python -I shader_profile.py [--out profile.json] + +Counts each mnemonic (number of shaders using it and total occurrences), groups them by encoding family, and +lists the dwords LLVM couldn't decode (likely Xbox-specific instructions) with how many shaders contain them. +""" +import argparse +import json +import os +import re +import sys +from collections import Counter, defaultdict + +FAMILIES = [("s_buffer_", "smem"), ("s_load", "smem"), ("s_", "scalar"), ("v_", "vector"), ("ds_", "lds"), + ("buffer_", "buffer"), ("tbuffer_", "buffer"), ("image_", "image"), ("global_", "global"), + ("flat_", "flat"), ("scratch_", "scratch"), ("exp", "export")] + + +def family(m): + for p, f in FAMILIES: + if m.startswith(p): + return f + return "other" + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("src") + ap.add_argument("--out") + a = ap.parse_args() + occ, users = Counter(), Counter() + invalid_users = Counter() + per_stage = defaultdict(Counter) + n = 0 + for name in os.listdir(a.src): + if not name.endswith(".s"): + continue + n += 1 + stage = name[:2].lower() if name[2:3] == "_" else "?" + seen = set() + with open(os.path.join(a.src, name), encoding="utf-8", errors="replace") as f: + text = f.read() + for line in text.splitlines(): + if not line.startswith("\t"): + continue + m = line.split()[0] + occ[m] += 1 + seen.add(m) + for m in seen: + users[m] += 1 + per_stage[stage][m] += 1 + for w in set(re.findall(r":\d+:\d+: warning: invalid instruction encoding\n; (0x[0-9a-f]{2}(?: 0x[0-9a-f]{2}){3})", text)): + invalid_users[w] += 1 + fam = defaultdict(lambda: [0, 0]) + for m, c in occ.items(): + fam[family(m)][0] += 1 + fam[family(m)][1] += c + out = {"shaders": n, "mnemonics": len(occ), + "families": {k: {"mnemonics": v[0], "occurrences": v[1]} for k, v in sorted(fam.items())}, + "by_mnemonic": [{"m": m, "shaders": users[m], "count": occ[m]} for m, _ in users.most_common()]} + path = a.out or os.path.join(a.src, "..", "profile.json") + with open(path, "w", encoding="utf-8") as f: + json.dump(out, f, indent=1) + print(f"{n} shaders, {len(occ)} distinct mnemonics -> {os.path.abspath(path)}") + for k, v in sorted(fam.items(), key=lambda kv: -kv[1][1]): + print(f" {k:8} {v[0]:4} mnemonics {v[1]:>12,} uses") + cum, total = 0, sum(occ.values()) + for i, (m, c) in enumerate(occ.most_common(), 1): + cum += c + if cum / total >= 0.99: + print(f" {i} mnemonics cover 99% of all instructions") + break + print(" most widespread:", ", ".join(f"{m} ({users[m]})" for m, _ in users.most_common(12))) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/swizzle_search.py b/tools/swizzle_search.py new file mode 100644 index 000000000..2df08ca89 --- /dev/null +++ b/tools/swizzle_search.py @@ -0,0 +1,111 @@ +"""Search for the in-tile swizzle of a GPU texture by brute force. + +Within a tile of 2^B blocks, each address bit maps to one x or one y bit. Every ordering with the right +x/y split is tried (bit k goes to the next free x or y bit), tiles are laid out row-major, and the ordering +whose block-endpoint image is smoothest wins. + +Usage: + python -I swizzle_search.py --bpe 8 --tile 65536 [--widths 1024,2048] [--tiles 48] [--out preview.png] +""" +import argparse +import itertools +import sys + +import numpy as np + +sys.path.insert(0, __import__("os").path.dirname(__file__)) +from tile_probe import block_feature, score # noqa: E402 + + +def positions(seq, nblocks, tw, th, wblocks): + idx = np.arange(nblocks, dtype=np.int64) + per = tw * th + tile, inner = idx // per, idx % per + x = np.zeros_like(idx) + y = np.zeros_like(idx) + xi = yi = 0 + for k, c in enumerate(seq): + bit = (inner >> k) & 1 + if c == "x": + x |= bit << xi + xi += 1 + else: + y |= bit << yi + yi += 1 + tiles_x = wblocks // tw + return ((tile // tiles_x) * th + y) * wblocks + (tile % tiles_x) * tw + x + + +def search(data, bpe, tile_bytes, widths, ntiles): + raw = np.frombuffer(data[: len(data) // bpe * bpe], np.uint8).reshape(-1, bpe) + feat = block_feature(raw, bpe) + bits = int(np.log2(tile_bytes // bpe)) + results = [] + for xbits in sorted({bits // 2, (bits + 1) // 2}): + tw, th = 1 << xbits, 1 << (bits - xbits) + for wpx in widths: + wb = wpx // 4 + if wb % tw: + continue + tiles_x = wb // tw + rows = max(1, ntiles // tiles_x) + n = tiles_x * rows * tw * th + if n > len(raw): + continue + for xs in itertools.combinations(range(bits), xbits): + seq = ["x" if k in xs else "y" for k in range(bits)] + pos = positions(seq, n, tw, th, wb) + img = np.zeros((n, 3), np.float32) + img[pos] = feat[:n] + results.append((score(img.reshape(-1, wb, 3)), wpx, "".join(seq))) + results.sort() + return results + + +def render(data, bpe, tile_bytes, wpx, seq, out): + import io + import struct + from PIL import Image + raw = np.frombuffer(data[: len(data) // bpe * bpe], np.uint8).reshape(-1, bpe) + bits = len(seq) + xbits = seq.count("x") + tw, th = 1 << xbits, 1 << (bits - xbits) + wb = wpx // 4 + hb = min(len(raw) // wb // th * th, wb // th * th or th) + n = wb * hb + pos = positions(list(seq), n, tw, th, wb) + lin = np.zeros((n, bpe), np.uint8) + lin[pos] = raw[:n] + hdr = bytearray(128) + hdr[0:4] = b"DDS " + struct.pack_into("high) {seq}") + if a.out: + render(data, a.bpe, a.tile, res[0][1], res[0][2], a.out) + print("preview ->", a.out) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/tex_export.py b/tools/tex_export.py new file mode 100644 index 000000000..166f4bc0c --- /dev/null +++ b/tools/tex_export.py @@ -0,0 +1,158 @@ +"""Export textures found by tex_headers.py as standard DDS files (top mip, slice 0), detiled from AMD SW_4K_S. + +For each texture: + - element size from the DXGI format (BC: 8/16 bytes per 4x4 block; uncompressed: bytes per pixel) + - the top mip is either at the data offset or at the end of the mip chain (GFX10 stores mips smallest first); + both are detiled and the smoother one wins (scored on the decoded image where Pillow can decode the format, + otherwise on raw element bytes) + - writes //___.dds and records the choice in export_log.json + +Usage: + python -I tex_export.py [--limit N] [--png] +""" +import argparse +import io +import json +import os +import struct +import sys +from collections import Counter + +import numpy as np + +sys.path.insert(0, os.path.dirname(__file__)) +from amd_swizzle import _parity, equation, load # noqa: E402 + +# DXGI format -> (bytes per element, block dimension) +FMT = {71: (8, 4), 72: (8, 4), 80: (8, 4), 81: (8, 4), 74: (16, 4), 77: (16, 4), 78: (16, 4), 83: (16, 4), + 84: (16, 4), 95: (16, 4), 96: (16, 4), 98: (16, 4), 99: (16, 4), 28: (4, 1), 29: (4, 1), 87: (4, 1), + 91: (4, 1), 24: (4, 1), 26: (4, 1), 41: (4, 1), 34: (4, 1), 10: (8, 1), 2: (16, 1), 56: (2, 1), 54: (2, 1), + 49: (2, 1), 61: (1, 1)} +PILLOW_OK = {71, 72, 74, 77, 78, 80, 81, 83, 84, 98, 99, 28, 29, 87, 91} +# Pillow can't open sRGB DXGI codes; the bytes are identical to the UNORM twin, so decode with that for scoring. +DECODE_AS = {72: 71, 78: 77, 99: 98, 29: 28, 91: 87} + +_NIB, _TAB = load() +_EQ = {} + + +def eq4k(bpe): + if bpe not in _EQ: + e = [e for e in _TAB["GFX10_SW_4K_S_PATINFO"] if f" {bpe} bpe" in e[5]][0] + _EQ[bpe] = equation(_NIB, e, 12) + return _EQ[bpe] + + +def detile_offsets(bpe, we, he): + eq = eq4k(bpe) + elems = 4096 // bpe + lb = elems.bit_length() - 1 + bw = 1 << ((lb + 1) // 2) + bh = elems // bw + y, x = np.mgrid[0:he, 0:we].astype(np.int64) + o = np.zeros_like(x) + for bit, (mx, my) in enumerate(eq): + if mx or my: + o |= (_parity(x & mx) ^ _parity(y & my)) << bit + nbx = (we + bw - 1) // bw + return ((o + ((y // bh) * nbx + x // bw) * 4096) // bpe).reshape(-1), bw, bh + + +def level_bytes(we, he, bpe, bw, bh): + return ((we + bw - 1) // bw) * ((he + bh - 1) // bh) * 4096 + + +def dds_bytes(w, h, fmt, payload): + hdr = bytearray(128) + hdr[0:4] = b"DDS " + struct.pack_into("= 64 else im, np.float32) + else: + a = np.frombuffer(payload, np.uint8).reshape(-1, bpe)[:, :4].astype(np.float32) + a = a.reshape(-1, max(1, (w + 3) // 4 if bpe >= 8 and FMT[fmt][1] == 4 else w), 4) + d = np.abs(np.diff(a, axis=0)).mean() + np.abs(np.diff(a, axis=1)).mean() + return float(d / (a.std() + 1e-6)) + + +def export_one(t, carve, out, blob_cache): + fmt = t["fmt"] + if fmt not in FMT: + return "unsupported format" + bpe, blk = FMT[fmt] + w, h = t["w"], t["h"] + we, he = (w + blk - 1) // blk, (h + blk - 1) // blk + key = (t["archive"], t["gpu"]) + if key not in blob_cache: + blob_cache.clear() + parts = [] + for off, _ in t.get("gpu_chain") or [[t["gpu"], t["gpu_size"]]]: + with open(os.path.join(carve, t["archive"], f"{off:012x}.bin"), "rb") as f: + parts.append(f.read()) + blob_cache[key] = b"".join(parts) + G = blob_cache[key] + offs, bw, bh = detile_offsets(bpe, we, he) + need = (int(offs.max()) + 1) * bpe + top = level_bytes(we, he, bpe, bw, bh) + chain = sum(level_bytes(max(1, (max(1, w >> i) + blk - 1) // blk), max(1, (max(1, h >> i) + blk - 1) // blk), bpe, bw, bh) + for i in range(max(1, t["mips"]))) + cands = [] + for place, start in (("first", t["data_off"]), ("last", t["data_off"] + chain - top)): + if start < 0 or start + need > len(G): + continue + raw = np.frombuffer(G[start:start + need], np.uint8).reshape(-1, bpe) + payload = raw[offs].tobytes() + try: + s = score_image(w, h, fmt, payload, bpe) + except Exception: # noqa: BLE001 + s = 9e9 + cands.append((s, place, payload)) + if not cands: + return "data outside GPU blob" + cands.sort(key=lambda c: c[0]) + s, place, payload = cands[0] + name = f"{t['cpu']:012x}_{t['q_index']}_{w}x{h}_{t['fmt_name']}.dds" + d = os.path.join(out, t["archive"]) + os.makedirs(d, exist_ok=True) + with open(os.path.join(d, name), "wb") as f: + f.write(dds_bytes(w, h, fmt, payload)) + t["export"] = {"file": name, "place": place, "score": round(s, 4)} + return "ok:" + place + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("index") + ap.add_argument("carve") + ap.add_argument("out") + ap.add_argument("--limit", type=int) + a = ap.parse_args() + texs = json.load(open(a.index, encoding="utf-8")) + texs.sort(key=lambda t: (t["archive"], t["gpu"])) + if a.limit: + texs = texs[: a.limit] + os.makedirs(a.out, exist_ok=True) + res, cache = Counter(), {} + for i, t in enumerate(texs, 1): + try: + r = export_one(t, a.carve, a.out, cache) + except Exception as e: # noqa: BLE001 + r = "error:" + type(e).__name__ + res[r] += 1 + if i % 2000 == 0: + print(f"[{i}/{len(texs)}] {dict(res)}", flush=True) + with open(os.path.join(a.out, "export_log.json"), "w", encoding="utf-8") as f: + json.dump(texs, f) + print(f"{len(texs)} textures: {dict(res)} -> {a.out}") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/tex_headers.py b/tools/tex_headers.py new file mode 100644 index 000000000..e3c07557a --- /dev/null +++ b/tools/tex_headers.py @@ -0,0 +1,96 @@ +"""Find texture headers in carved CPU-segment blobs and pair them with their GPU blob. + +Texture descriptor layout (qwords, found in GTA VI's resource CPU segments): + q[k-2] packed u64 (unknown: size/flags) + q[k-1] 0x980 (descriptor type) + q[k] 0x60000000 + offset (GPU data pointer into the resource's GPU segment) + q[k+4] u16 width, u16 height, u16 depth/array, u8 ?, u8 DXGI format + q[k+5] tiling / flags (0x0001 = AMD SW_4K_S verified on an R16 texture) +The GPU segment is the carved blob that follows the CPU blob. + +Usage: + python -I tex_headers.py [--archives a,b] [--out textures_index.json] +""" +import argparse +import json +import os +import sys +from collections import Counter + +import numpy as np + +DXGI = {28: "R8G8B8A8_UNORM", 29: "R8G8B8A8_UNORM_SRGB", 56: "R16_UNORM", 61: "R8_UNORM", 71: "BC1_UNORM", + 72: "BC1_UNORM_SRGB", 74: "BC2_UNORM", 77: "BC3_UNORM", 78: "BC3_UNORM_SRGB", 80: "BC4_UNORM", + 81: "BC4_SNORM", 83: "BC5_UNORM", 84: "BC5_SNORM", 87: "B8G8R8A8_UNORM", 91: "B8G8R8A8_UNORM_SRGB", + 95: "BC6H_UF16", 96: "BC6H_SF16", 98: "BC7_UNORM", 99: "BC7_UNORM_SRGB", 10: "R16G16B16A16_FLOAT", + 2: "R32G32B32A32_FLOAT", 41: "R32_FLOAT", 54: "R16_FLOAT", 34: "R16G16_FLOAT", 24: "R10G10B10A2_UNORM", + 26: "R11G11B10_FLOAT", 49: "R8G8_UNORM"} + + +def scan_archive(carve, arch): + files = sorted(json.load(open(os.path.join(carve, arch, "index.json"), encoding="utf-8"))["files"], + key=lambda r: r["off"]) + out = [] + for i in range(len(files) - 1): + v, g = files[i], files[i + 1] + # CPU segment: starts with a zero qword but isn't zero-padded GPU data. The GPU segment is whatever + # blob follows it (texture data often starts directly with BC blocks, not a zero header). + if not (v["head"][:16] == "0" * 16 and not v["head"].startswith("0" * 32)): + continue + if g["head"].startswith("42400000") or g.get("type") == "bink2": + continue + # The GPU segment can span several consecutive blobs: everything up to the next CPU/header blob. + chain = [] + for j in range(i + 1, min(len(files), i + 257)): + r = files[j] + if r["head"].startswith("42400000") or r.get("type") == "bink2" or ( + r["head"][:16] == "0" * 16 and not r["head"].startswith("0" * 32) and chain): + break + chain.append([r["off"], r["size"]]) + with open(os.path.join(carve, arch, f"{v['off']:012x}.bin"), "rb") as f: + V = f.read() + q = np.frombuffer(V[: len(V) // 8 * 8], "> 28) == 6) & ((q >> 32) == 0))[0]: + k = int(k) + if k < 2 or k + 5 >= len(q): + continue + d = int(q[k + 4]).to_bytes(8, "little") + w, h, depth = int.from_bytes(d[0:2], "little"), int.from_bytes(d[2:4], "little"), int.from_bytes(d[4:6], "little") + fmt = d[7] + if fmt not in DXGI or not (4 <= w <= 16384 and 4 <= h <= 16384 and 1 <= depth <= 2048): + continue + # Real texture data is 256-byte aligned (4 KB in every verified case); unaligned hits are other structs. + if (int(q[k]) & 0xFF) != 0: + continue + out.append({"archive": arch, "cpu": v["off"], "gpu": g["off"], "gpu_size": g["size"], "gpu_chain": chain, + "data_off": int(q[k]) & 0x0FFFFFFF, "w": w, "h": h, "depth": depth, "b6": d[6], "fmt": fmt, + "fmt_name": DXGI.get(fmt, f"dxgi{fmt}"), "flags": int(q[k + 5]), "packed": int(q[k - 2]), + "dtype": int(q[k - 1]), "mips": (int(q[k + 5]) >> 16) & 0xFF, "q_index": k}) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("carve") + ap.add_argument("--archives") + ap.add_argument("--out") + a = ap.parse_args() + archs = a.archives.split(",") if a.archives else sorted( + d for d in os.listdir(a.carve) if os.path.isfile(os.path.join(a.carve, d, "index.json"))) + allt = [] + for arch in archs: + t = scan_archive(a.carve, arch) + print(f"{arch}: {len(t)} texture headers", flush=True) + allt += t + path = a.out or os.path.join(a.carve, "textures_index.json") + with open(path, "w", encoding="utf-8") as f: + json.dump(allt, f) + print(f"{len(allt)} textures -> {path}") + print("formats:", Counter(t["fmt_name"] for t in allt).most_common(12)) + print("flags (low 16 bits):", Counter(hex(t["flags"] & 0xFFFF) for t in allt).most_common(10)) + print("byte6:", Counter(t["b6"] for t in allt).most_common(8)) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/tex_mode_probe.py b/tools/tex_mode_probe.py new file mode 100644 index 000000000..0a02e8c96 --- /dev/null +++ b/tools/tex_mode_probe.py @@ -0,0 +1,101 @@ +"""For textures with known size/format/mips, find which AMD swizzle mode and top-mip placement decodes cleanly. + +Candidates: every addrlib 4K/64K pattern for the element size, crossed with two placements of the top mip +(at the texture's data offset, or at the end of its mip chain, since GFX10 stores mips smallest first). +Scored with exact BC1/BC3 block averages (smoothness relative to the image's own spread). + +Usage: + python -I tex_mode_probe.py [--fmt BC1] [--n 12] +""" +import argparse +import json +import os +import sys +from collections import Counter + +import numpy as np + +sys.path.insert(0, os.path.dirname(__file__)) +from amd_swizzle import _parity, equation, load # noqa: E402 +from bc_feature import block_average, smoothness # noqa: E402 + +BPE = {"BC1": 8, "BC4": 8, "BC2": 16, "BC3": 16, "BC5": 16, "BC6H": 16, "BC7": 16} + + +def bc_bpe(fmt_name): + for k, v in BPE.items(): + if fmt_name.startswith(k): + return v + return None + + +def mip_bytes(w, h, bpe, align): + bw, bh = max(1, (w + 3) // 4), max(1, (h + 3) // 4) + n = bw * bh * bpe + return (n + align - 1) // align * align + + +def offsets_for(eq, bb, bpe, wb, hb): + elems = (1 << bb) // bpe + lb = elems.bit_length() - 1 + bw = 1 << ((lb + 1) // 2) + bh = elems // bw + y, x = np.mgrid[0:hb, 0:wb].astype(np.int64) + o = np.zeros_like(x) + for bit, (mx, my) in enumerate(eq): + if mx or my: + o |= (_parity(x & mx) ^ _parity(y & my)) << bit + nbx = (wb + bw - 1) // bw + return (o + ((y // bh) * nbx + x // bw) * (1 << bb)) // bpe + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("index") + ap.add_argument("carve") + ap.add_argument("--fmt", default="BC1") + ap.add_argument("--n", type=int, default=12) + a = ap.parse_args() + nib, tab = load() + texs = [t for t in json.load(open(a.index)) if t["fmt_name"].startswith(a.fmt) and t["w"] >= 256 and t["h"] >= 256] + texs = texs[: a.n] + cands = {} + for tname, ents in tab.items(): + for size, bb in (("_64K_", 16), ("_4K_", 12)): + if size in tname and ("_S" in tname or "_D" in tname or "_R_X_1xaa" in tname): + for e in ents: + if f" {bc_bpe(a.fmt)} bpe" in e[5]: + eq = equation(nib, e, bb) + cands.setdefault((bb, tuple(eq)), f"{tname.replace('GFX10_SW_', '').replace('_PATINFO', '')} {e[5][:22]}") + wins = Counter() + for t in texs: + bpe = bc_bpe(t["fmt_name"]) + with open(os.path.join(a.carve, t["archive"], f"{t['gpu']:012x}.bin"), "rb") as f: + G = f.read() + wb, hb = (t["w"] + 3) // 4, (t["h"] + 3) // 4 + mips = (t["flags"] >> 16) & 0xFF + res = [] + for (bb, eq), label in cands.items(): + align = 1 << bb + top = mip_bytes(t["w"], t["h"], bpe, align) + chain = sum(mip_bytes(max(1, t["w"] >> i), max(1, t["h"] >> i), bpe, align) for i in range(max(1, mips))) + for place, start in (("first", t["data_off"]), ("last", t["data_off"] + chain - top)): + o = offsets_for(list(eq), bb, bpe, wb, hb) + seg = G[start:start + (int(o.max()) + 1) * bpe] + if len(seg) < (int(o.max()) + 1) * bpe: + continue + raw = np.frombuffer(seg, np.uint8).reshape(-1, bpe) + img = block_average(raw[o.reshape(-1)], bpe).reshape(hb, wb, 3) + res.append((smoothness(img), label, place)) + res.sort() + if res: + lin_raw = np.frombuffer(G[t["data_off"]:t["data_off"] + wb * hb * bpe], np.uint8) + lin = smoothness(block_average(lin_raw.reshape(-1, bpe), bpe).reshape(hb, wb, 3)) if len(lin_raw) == wb * hb * bpe else -1 + print(f"{t['w']}x{t['h']} {t['fmt_name']} mips={mips} gpu={t['gpu_size']} best {res[0][0]:.4f} {res[0][1]} [{res[0][2]}]" + f" 2nd {res[1][0]:.4f} {res[1][1]} [{res[1][2]}] linear {lin:.4f}") + wins[(res[0][1].split(' ')[0], res[0][2])] += 1 + print("winners:", wins.most_common()) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/tile_probe.py b/tools/tile_probe.py new file mode 100644 index 000000000..72767fa2b --- /dev/null +++ b/tools/tile_probe.py @@ -0,0 +1,150 @@ +"""Find the memory layout of a GPU texture blob empirically. + +For each candidate (block size 8 or 16 bytes, linear or tiled with a Z-order inside 4 KB / 64 KB tiles, and a range +of widths), it reorders the compressed blocks, builds a small image from each block's colour endpoint, and scores +how smooth that image is. Real textures are spatially coherent, so the right layout scores best. + +Usage: + python -I tile_probe.py [--out preview.png] [--offset N] +""" +import argparse +import sys + +import numpy as np + + +def morton_decode(i, bits): + """Split a Z-order index into (x, y), x taking the even bits.""" + x = np.zeros_like(i) + y = np.zeros_like(i) + for b in range(bits): + x |= ((i >> (2 * b)) & 1) << b + y |= ((i >> (2 * b + 1)) & 1) << b + return x, y + + +def tile_dims(tile_bytes, bpe): + n = tile_bytes // bpe # blocks per tile + bits = int(np.log2(n)) + tw = 1 << ((bits + 1) // 2) # wider than tall when bits is odd + return tw, n // tw, bits + + +def block_feature(blocks, bpe): + """One RGB value per compressed block, from its first colour endpoint.""" + if bpe == 8: + c = blocks[:, 0].astype(np.uint32) | (blocks[:, 1].astype(np.uint32) << 8) # BC1 color0 (565) + else: + c = blocks[:, 8].astype(np.uint32) | (blocks[:, 9].astype(np.uint32) << 8) # BC3 color0 (565) + r = ((c >> 11) & 31) * 255 // 31 + g = ((c >> 5) & 63) * 255 // 63 + b = (c & 31) * 255 // 31 + if bpe == 16: + # BC5/BC7 have no 565 endpoint there; mix in the first byte (BC5 red0 / BC7 mode+endpoint bits). + r = (r + blocks[:, 0]) // 2 + return np.stack([r, g, b], -1).astype(np.float32) + + +def layout(nblocks, wblocks, mode, bpe): + """Linear position (y * wblocks + x) for each stored block, or None if the layout doesn't fit.""" + idx = np.arange(nblocks, dtype=np.int64) + if mode == "linear": + x, y = idx % wblocks, idx // wblocks + else: + tb = 4096 if mode == "4k" else 65536 + tw, th, bits = tile_dims(tb, bpe) + if wblocks % tw: + return None + per = tw * th + if nblocks % (wblocks * th): + return None + tile, inner = idx // per, idx % per + # x takes the even bits, y the odd ones; with an odd bit count x gets the extra top bit. + ix, iy = morton_decode(inner, (bits + 1) // 2) + tiles_x = wblocks // tw + x = (tile % tiles_x) * tw + ix + y = (tile // tiles_x) * th + iy + return y * wblocks + x + + +def score(img): + dx = np.abs(np.diff(img, axis=1)).mean() + dy = np.abs(np.diff(img, axis=0)).mean() + return dx + dy + + +def probe(data: bytes, offset=0): + best = [] + for bpe in (8, 16): + raw = np.frombuffer(data[offset:offset + (len(data) - offset) // bpe * bpe], np.uint8).reshape(-1, bpe) + feat = block_feature(raw, bpe) + for wpx in (256, 512, 1024, 2048, 4096): + wb = wpx // 4 + hb0 = min(len(raw) // wb, wb) # top mip assumed square or wider + for mode in ("linear", "4k", "64k"): + hb = hb0 + if mode != "linear": + th = tile_dims(4096 if mode == "4k" else 65536, bpe)[1] + hb = hb0 // th * th + if hb < 16: + continue + n = wb * hb + pos = layout(n, wb, mode, bpe) + if pos is None: + continue + img = np.zeros((hb * wb, 3), np.float32) + img[pos] = feat[:n] + s = score(img.reshape(hb, wb, 3)) + best.append((s, bpe, wpx, mode)) + best.sort() + return best + + +def render(data, offset, bpe, wpx, mode, out): + """Full BC decode of the reordered top mip through Pillow (BC1 for 8-byte blocks, BC7 for 16-byte).""" + import io + import struct + from PIL import Image + wb = wpx // 4 + raw = np.frombuffer(data[offset:offset + (len(data) - offset) // bpe * bpe], np.uint8).reshape(-1, bpe) + hb = min(len(raw) // wb, wb) + if mode != "linear": + th = tile_dims(4096 if mode == "4k" else 65536, bpe)[1] + hb = hb // th * th + n = wb * hb + pos = layout(n, wb, mode, bpe) + lin = np.zeros((n, bpe), np.uint8) + lin[pos] = raw[:n] + w, h = wb * 4, hb * 4 + hdr = bytearray(128) + hdr[0:4] = b"DDS " + struct.pack_into("", a.out) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/viewer/index.html b/viewer/index.html new file mode 100644 index 000000000..471430dd3 --- /dev/null +++ b/viewer/index.html @@ -0,0 +1,213 @@ + + + + + +Map Viewer + + + +
+ +
+ W A S D move · Q/E down/up · Shift fast · Ctrl slow · wheel: speed
+ F wireframe · G chunk bounds · R back to spawn · Esc release mouse +
+
Click to fly
+ + + + + diff --git a/viewer/serve.py b/viewer/serve.py new file mode 100644 index 000000000..3ab90ca78 --- /dev/null +++ b/viewer/serve.py @@ -0,0 +1,47 @@ +"""Serve the map viewer on http://127.0.0.1:8765 (local only). + +Usage: + python -I serve.py [--world DIR] [--port 8765] + +`--world` is the folder holding world.json and the .glb chunks (default G:\\gta6-work\\world). It's served at +/world/ so game-derived files never need to live in this repo. Without it, the viewer shows test terrain. +""" +import argparse +import functools +import http.server +import os + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +class Handler(http.server.SimpleHTTPRequestHandler): + world = None + + def translate_path(self, path): + clean = path.split("?", 1)[0].split("#", 1)[0] + if self.world and clean.startswith("/world/"): + rel = os.path.normpath(clean[len("/world/"):]).lstrip("\\/") + if rel.startswith(".."): + return os.path.join(self.world, "__denied__") + return os.path.join(self.world, rel) + return super().translate_path(path) + + def end_headers(self): + self.send_header("Cache-Control", "no-store") + super().end_headers() + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--world", default=r"G:\gta6-work\world") + ap.add_argument("--port", type=int, default=8765) + a = ap.parse_args() + Handler.world = a.world if os.path.isdir(a.world) else None + Handler.extensions_map[".glb"] = "model/gltf-binary" + srv = http.server.ThreadingHTTPServer(("127.0.0.1", a.port), functools.partial(Handler, directory=HERE)) + print(f"viewer: http://127.0.0.1:{a.port}/ world: {Handler.world or '(none: test terrain)'}", flush=True) + srv.serve_forever() + + +if __name__ == "__main__": + main()