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 <noreply@anthropic.com>
This commit is contained in:
NotRexed
2026-11-20 15:22:16 -05:00
commit db0dc8bd5e
50 changed files with 8878 additions and 0 deletions

4
.gitattributes vendored Normal file
View File

@ -0,0 +1,4 @@
* text=auto eol=lf
*.ps1 text eol=crlf
*.cmd text eol=crlf
*.sln text eol=crlf

26
.github/workflows/ci.yml vendored Normal file
View File

@ -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

33
.gitignore vendored Normal file
View File

@ -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/

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "third_party/rpf9-explorer"]
path = third_party/rpf9-explorer
url = https://github.com/breadbbbb/rpf9-explorer

19
CONTRIBUTING.md Normal file
View File

@ -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.

674
LICENSE Normal file
View File

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

121
README.md Normal file
View File

@ -0,0 +1,121 @@
<h1 align="center">
<br>
<b>Leonida</b>
<br>
</h1>
<h4 align="center">Grand Theft Auto VI (Xbox Series) running natively on Windows, built on your PC from your own copy.
</h4>
<p align="center">
<a href="#project-status">Status</a> |
<a href="#how-to-build">How to build</a> |
<a href="#how-it-works">How it works</a> |
<a href="#want-to-help">Want to help?</a> |
<a href="#credits">Credits</a> |
<a href="#license">License</a>
</p>
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/<you>/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.

231
docs/design.md Normal file
View File

@ -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>\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 <exe>` 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\<archive>\`, `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\<archive>\models\` |
| Texture dictionaries | Same tool: TXD resources become DDS per texture. | `G:\gta6-work\assets\<archive>\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_<assetkey>`); models reference textures by asset key. Some rows are skipped (BCPack or unmapped shards). | `G:\gta6-work\assets\ttpf\<pool>\` + `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 <archive.rpf> G:\gta6-work\assets
rpf9dump ttpf <pool.ttpf> G:\gta6-work\assets\ttpf
rpf9dump audio <audio.rpf> 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 <exe>` 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 <repo>/tools/shader_disasm.py <work>/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 <game>` 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.

439
game/xbox-1.0.2.1.json Normal file
View File

@ -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"
}

233
make_game.py Normal file
View File

@ -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/<version>.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 <out>/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())

22
runtime/CMakeLists.txt Normal file
View File

@ -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)

View File

@ -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 <windows.h>
#include <cstdio>
#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<SerializeFn>(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<DeserializerFn>(host("D3D12CreateRootSignatureDeserializer"));
return fn ? fn(data, size, iid, out) : E_NOTIMPL;
}
} // namespace
SHIM_TABLE(d3d12_xs,
{"d3d12_xs.dll", "D3D12SerializeVersionedRootSignature", reinterpret_cast<void*>(&D3D12SerializeVersionedRootSignature)},
{"d3d12_xs.dll", "D3D12CreateRootSignatureDeserializer", reinterpret_cast<void*>(&D3D12CreateRootSignatureDeserializer)},
);

View File

@ -0,0 +1,81 @@
#include <windows.h>
#include <cstdio>
#include <cstring>
#include <map>
#include <mutex>
#include <set>
#include <string>
#include "shims.h"
namespace rt::shims {
namespace {
std::map<std::string, void*>& table() {
static std::map<std::string, void*> t; // "dll!name"
return t;
}
std::mutex g_called_mutex;
std::set<std::string> 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 <imm64> mov rcx, what
// 48 B8 <imm64> 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<uint8_t*>(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<uint64_t>(what), f = reinterpret_cast<uint64_t>(&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

31
runtime/shims/shims.h Normal file
View File

@ -0,0 +1,31 @@
// Shim registry: reimplementations of console-only imports.
// Add a DLL by writing a shims/<dll>.cpp with a SHIM_TABLE and listing it in CMakeLists.txt.
#pragma once
#include <string>
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]))

48
runtime/shims/xmem.cpp Normal file
View File

@ -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 <windows.h>
#include <malloc.h>
#include <psapi.h>
#include <cstdint>
#include <cstring>
#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<long>(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<void*>(&XMemAlloc)},
{"xmem.dll", "XMemFree", reinterpret_cast<void*>(&XMemFree)},
{"xmem.dll", "XMemVirtualQuery", reinterpret_cast<void*>(&XMemVirtualQuery)},
{"xmem.dll", "XMemGetWorkingSetStatistics", reinterpret_cast<void*>(&XMemGetWorkingSetStatistics)},
);

72
runtime/src/main.cpp Normal file
View File

@ -0,0 +1,72 @@
// gta6rt: native runtime for the Xbox Series build.
//
// gta6rt --dry-run <image> [--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 <windows.h>
#include <cstdio>
#include <map>
#include <string>
#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 <image> [--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<rt::Binding, int> 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;
}
}

207
runtime/src/pe_loader.cpp Normal file
View File

@ -0,0 +1,207 @@
#include "pe_loader.h"
#include <windows.h>
#include <algorithm>
#include <cstring>
#include <fstream>
#include <stdexcept>
#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<uint8_t> 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<char>(f), {}};
}
template <class T>
T* at(uint8_t* base, uint32_t rva) { return reinterpret_cast<T*>(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<IMAGE_DOS_HEADER*>(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<IMAGE_NT_HEADERS64*>(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<uint8_t*>(
VirtualAlloc(reinterpret_cast<void*>(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<uint8_t*>(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<int64_t>(m->base) - static_cast<int64_t>(oh.ImageBase);
if (delta) {
m->relocated = true;
auto& dir = oh.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC];
auto* block = at<IMAGE_BASE_RELOCATION>(m->base, dir.VirtualAddress);
auto* end = reinterpret_cast<uint8_t*>(block) + dir.Size;
while (reinterpret_cast<uint8_t*>(block) < end && block->SizeOfBlock) {
auto* entries = reinterpret_cast<uint16_t*>(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<uint64_t>(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<IMAGE_BASE_RELOCATION*>(reinterpret_cast<uint8_t*>(block) + block->SizeOfBlock);
}
}
parse_exports(*m);
return *m;
}
void Loader::parse_exports(Module& m) {
auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(m.base)->e_lfanew);
auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT];
if (!dir.Size) return;
auto* ed = at<IMAGE_EXPORT_DIRECTORY>(m.base, dir.VirtualAddress);
auto* funcs = at<uint32_t>(m.base, ed->AddressOfFunctions);
auto* names = at<uint32_t>(m.base, ed->AddressOfNames);
auto* ords = at<uint16_t>(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<char>(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<void*>(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<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(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<IMAGE_IMPORT_BY_NAME>(m.base, (uint32_t)lookup->u1.AddressOfData)->Name;
iat->u1.Function = reinterpret_cast<uint64_t>(resolve(m, dll, name, ord, by_ord));
}
};
auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT];
if (dir.Size) {
for (auto* d = at<IMAGE_IMPORT_DESCRIPTOR>(m.base, dir.VirtualAddress); d->Name; ++d) {
std::string dll = at<char>(m.base, d->Name);
uint32_t lookup = d->OriginalFirstThunk ? d->OriginalFirstThunk : d->FirstThunk;
bind_thunks(dll, at<IMAGE_THUNK_DATA64>(m.base, lookup), at<IMAGE_THUNK_DATA64>(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<IMAGE_DELAYLOAD_DESCRIPTOR>(m.base, ddir.VirtualAddress); d->DllNameRVA; ++d) {
std::string dll = at<char>(m.base, d->DllNameRVA);
bind_thunks(dll, at<IMAGE_THUNK_DATA64>(m.base, d->ImportNameTableRVA),
at<IMAGE_THUNK_DATA64>(m.base, d->ImportAddressTableRVA));
}
}
}
void Loader::protect_sections(Module& m) {
auto* nt = at<IMAGE_NT_HEADERS64>(m.base, reinterpret_cast<IMAGE_DOS_HEADER*>(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

57
runtime/src/pe_loader.h Normal file
View File

@ -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 <cstdint>
#include <filesystem>
#include <map>
#include <string>
#include <vector>
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<ImportRecord> imports;
std::map<std::string, void*> 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<Module*>& 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<std::string, Module*> by_name_; // lower-case file name
std::vector<Module*> order_;
};
std::string lower(std::string s);
} // namespace rt

194
runtime/test/vk_harness.cpp Normal file
View File

@ -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 <vs.spv> <fs.spv> <out.raw> [width height]
//
// Vulkan is loaded at runtime from vulkan-1.dll (no SDK import library needed).
#define VK_NO_PROTOTYPES
#include <vulkan/vulkan.h>
#include <windows.h>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <vector>
static PFN_vkGetInstanceProcAddr gipa;
#define LOADI(name) auto name = reinterpret_cast<PFN_##name>(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<uint32_t> read_spv(const char* path) {
std::ifstream f(path, std::ios::binary);
std::vector<char> b((std::istreambuf_iterator<char>(f)), {});
std::vector<uint32_t> 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<PFN_vkGetInstanceProcAddr>(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<VkPhysicalDevice> 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<VkQueueFamilyProperties> 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<PFN_##name>(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 = &sc;
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<PFN_vkCmdPushConstants>(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, &reg);
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<const char*>(p), std::streamsize(bi.size));
std::fprintf(stderr, "ok %ux%u -> %s\n", W, H, argv[3]);
return 0;
}

View File

@ -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 <vs.spv> <fs.spv> <out.raw> <ptr_sgpr> <s0> <s1> <s2> <s3> (S# words as hex)
#define VK_NO_PROTOTYPES
#include <vulkan/vulkan.h>
#include <windows.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <vector>
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<uint32_t> read_spv(const char* p) {
std::ifstream f(p, std::ios::binary);
std::vector<char> b((std::istreambuf_iterator<char>(f)), {});
std::vector<uint32_t> 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<uint32_t>& 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<PFN_vkGetInstanceProcAddr>(GetProcAddress(lib, "vkGetInstanceProcAddr"));
VkInstance inst = VK_NULL_HANDLE;
#define LI(n) auto n = reinterpret_cast<PFN_##n>(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<VkPhysicalDevice> 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<VkQueueFamilyProperties> 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<PFN_##n>(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<char*>(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<uint32_t> 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<uint32_t>& 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<uint32_t> 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<char*>(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 = &sc;
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<const char*>(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;
}

46
scripts/build_runtime.ps1 Normal file
View File

@ -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"

20
scripts/carve_all.ps1 Normal file
View File

@ -0,0 +1,20 @@
# Carves every .rpf in the game folder into <Out>\<archive path with _>, smallest first (research tool; the
# build itself doesn't need it). Skips archives that already have an index.json. Summary: <Out>\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

41
scripts/first_look.ps1 Normal file
View File

@ -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"

52
scripts/meta_to_xml.ps1 Normal file
View File

@ -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 <Out>\<archive>\<offset>.xml. Failures go to <Out>\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"

1
third_party/rpf9-explorer vendored Submodule

156
tools/amd_swizzle.py Normal file
View File

@ -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 <blob> --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("<IIIIIII", hdr, 4, 124, 0x1007, a.height, a.width, lin.size, 0, 1)
struct.pack_into("<I", hdr, 108, 0x1000)
if a.bpe == 8:
struct.pack_into("<II4s", hdr, 76, 32, 4, b"DXT1")
body = bytes(hdr)
else:
struct.pack_into("<II4s", hdr, 76, 32, 4, b"DX10")
body = bytes(hdr) + struct.pack("<IIIII", 98, 3, 0, 1, 0)
Image.open(io.BytesIO(body + lin.tobytes())).convert("RGB").save(a.out)
print("best ->", a.out)
if __name__ == "__main__":
sys.exit(main())

37
tools/bc_feature.py Normal file
View File

@ -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))

61
tools/classify_carve.py Normal file
View File

@ -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:<hex> 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()

97
tools/fssm_unpack.py Normal file
View File

@ -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 <carved_shader_dir> (writes <dir>/fssm/<name>.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("<I", d, 28)[0]):
off = struct.unpack_from("<I", d, 32 + 4 * k)[0]
out[d[off:off + 4]] = d[off + 8:off + 8 + struct.unpack_from("<I", d, off + 4)[0]]
return out
def xdat_entries(dxil: bytes) -> dict:
x = dxil.find(b"XDAT")
if x < 0:
return {}
count, hdr = struct.unpack_from("<II", dxil, x + 4)
ents = {}
for k in range(count):
tag, off, size = struct.unpack_from("<III", dxil, x + 12 + 12 * k)
ents[tag] = dxil[off:off + size]
return ents
def unpack(dxbc: bytes):
p = parts(dxbc)
ents = xdat_entries(p.get(b"DXIL", b""))
blob = ents.get(0x0D)
if not blob or blob[:4] != b"XBCH":
return None, ents
unpacked = struct.unpack_from("<I", blob, 16)[0]
data = zlib.decompress(blob[24:])
if len(data) != unpacked:
raise ValueError(f"size mismatch {len(data)} != {unpacked}")
return data, ents
def main() -> 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("<H", fssm, 4)[0], "endpgm": ends,
"tags": sorted(hex(t) for t in ents)})
with open(os.path.join(src, "fssm_index.json"), "w", encoding="utf-8") as f:
json.dump(rows, f)
print(f"{len(rows)} FSSM blobs, problems: {dict(problems)}")
print("magic:", dict(Counter(r["magic"] for r in rows)))
print("s_endpgm per blob:", dict(Counter(len(r["endpgm"]) for r in rows)))
sizes = sorted(r["size"] for r in rows)
print(f"size min {sizes[0]}, median {sizes[len(sizes) // 2]}, max {sizes[-1]}, total {sum(sizes) / 2**20:.0f} MiB")
return 0
if __name__ == "__main__":
sys.exit(main())

162
tools/gfx10_formats.json Normal file
View File

@ -0,0 +1,162 @@
{
"0": "GFX10_FORMAT_INVALID",
"1": "GFX10_FORMAT_8_UNORM",
"2": "GFX10_FORMAT_8_SNORM",
"3": "GFX10_FORMAT_8_USCALED",
"4": "GFX10_FORMAT_8_SSCALED",
"5": "GFX10_FORMAT_8_UINT",
"6": "GFX10_FORMAT_8_SINT",
"7": "GFX10_FORMAT_16_UNORM",
"8": "GFX10_FORMAT_16_SNORM",
"9": "GFX10_FORMAT_16_USCALED",
"10": "GFX10_FORMAT_16_SSCALED",
"11": "GFX10_FORMAT_16_UINT",
"12": "GFX10_FORMAT_16_SINT",
"13": "GFX10_FORMAT_16_FLOAT",
"14": "GFX10_FORMAT_8_8_UNORM",
"15": "GFX10_FORMAT_8_8_SNORM",
"16": "GFX10_FORMAT_8_8_USCALED",
"17": "GFX10_FORMAT_8_8_SSCALED",
"18": "GFX10_FORMAT_8_8_UINT",
"19": "GFX10_FORMAT_8_8_SINT",
"20": "GFX10_FORMAT_32_UINT",
"21": "GFX10_FORMAT_32_SINT",
"22": "GFX10_FORMAT_32_FLOAT",
"23": "GFX10_FORMAT_16_16_UNORM",
"24": "GFX10_FORMAT_16_16_SNORM",
"25": "GFX10_FORMAT_16_16_USCALED",
"26": "GFX10_FORMAT_16_16_SSCALED",
"27": "GFX10_FORMAT_16_16_UINT",
"28": "GFX10_FORMAT_16_16_SINT",
"29": "GFX10_FORMAT_16_16_FLOAT",
"30": "GFX10_FORMAT_10_11_11_UNORM",
"31": "GFX10_FORMAT_10_11_11_SNORM",
"32": "GFX10_FORMAT_10_11_11_USCALED",
"33": "GFX10_FORMAT_10_11_11_SSCALED",
"34": "GFX10_FORMAT_10_11_11_UINT",
"35": "GFX10_FORMAT_10_11_11_SINT",
"36": "GFX10_FORMAT_10_11_11_FLOAT",
"37": "GFX10_FORMAT_11_11_10_UNORM",
"38": "GFX10_FORMAT_11_11_10_SNORM",
"39": "GFX10_FORMAT_11_11_10_USCALED",
"40": "GFX10_FORMAT_11_11_10_SSCALED",
"41": "GFX10_FORMAT_11_11_10_UINT",
"42": "GFX10_FORMAT_11_11_10_SINT",
"43": "GFX10_FORMAT_11_11_10_FLOAT",
"44": "GFX10_FORMAT_10_10_10_2_UNORM",
"45": "GFX10_FORMAT_10_10_10_2_SNORM",
"46": "GFX10_FORMAT_10_10_10_2_USCALED",
"47": "GFX10_FORMAT_10_10_10_2_SSCALED",
"48": "GFX10_FORMAT_10_10_10_2_UINT",
"49": "GFX10_FORMAT_10_10_10_2_SINT",
"50": "GFX10_FORMAT_2_10_10_10_UNORM",
"51": "GFX10_FORMAT_2_10_10_10_SNORM",
"52": "GFX10_FORMAT_2_10_10_10_USCALED",
"53": "GFX10_FORMAT_2_10_10_10_SSCALED",
"54": "GFX10_FORMAT_2_10_10_10_UINT",
"55": "GFX10_FORMAT_2_10_10_10_SINT",
"56": "GFX10_FORMAT_8_8_8_8_UNORM",
"57": "GFX10_FORMAT_8_8_8_8_SNORM",
"58": "GFX10_FORMAT_8_8_8_8_USCALED",
"59": "GFX10_FORMAT_8_8_8_8_SSCALED",
"60": "GFX10_FORMAT_8_8_8_8_UINT",
"61": "GFX10_FORMAT_8_8_8_8_SINT",
"62": "GFX10_FORMAT_32_32_UINT",
"63": "GFX10_FORMAT_32_32_SINT",
"64": "GFX10_FORMAT_32_32_FLOAT",
"65": "GFX10_FORMAT_16_16_16_16_UNORM",
"66": "GFX10_FORMAT_16_16_16_16_SNORM",
"67": "GFX10_FORMAT_16_16_16_16_USCALED",
"68": "GFX10_FORMAT_16_16_16_16_SSCALED",
"69": "GFX10_FORMAT_16_16_16_16_UINT",
"70": "GFX10_FORMAT_16_16_16_16_SINT",
"71": "GFX10_FORMAT_16_16_16_16_FLOAT",
"72": "GFX10_FORMAT_32_32_32_UINT",
"73": "GFX10_FORMAT_32_32_32_SINT",
"74": "GFX10_FORMAT_32_32_32_FLOAT",
"75": "GFX10_FORMAT_32_32_32_32_UINT",
"76": "GFX10_FORMAT_32_32_32_32_SINT",
"77": "GFX10_FORMAT_32_32_32_32_FLOAT",
"128": "GFX10_FORMAT_8_SRGB",
"129": "GFX10_FORMAT_8_8_SRGB",
"130": "GFX10_FORMAT_8_8_8_8_SRGB",
"131": "GFX10_FORMAT_6E4_FLOAT",
"132": "GFX10_FORMAT_5_9_9_9_FLOAT",
"133": "GFX10_FORMAT_5_6_5_UNORM",
"134": "GFX10_FORMAT_1_5_5_5_UNORM",
"135": "GFX10_FORMAT_5_5_5_1_UNORM",
"136": "GFX10_FORMAT_4_4_4_4_UNORM",
"137": "GFX10_FORMAT_4_4_UNORM",
"138": "GFX10_FORMAT_1_UNORM",
"139": "GFX10_FORMAT_1_REVERSED_UNORM",
"140": "GFX10_FORMAT_32_FLOAT_CLAMP",
"141": "GFX10_FORMAT_8_24_UNORM",
"142": "GFX10_FORMAT_8_24_UINT",
"143": "GFX10_FORMAT_24_8_UNORM",
"144": "GFX10_FORMAT_24_8_UINT",
"145": "GFX10_FORMAT_X24_8_32_UINT",
"146": "GFX10_FORMAT_X24_8_32_FLOAT",
"147": "GFX10_FORMAT_GB_GR_UNORM",
"148": "GFX10_FORMAT_GB_GR_SNORM",
"149": "GFX10_FORMAT_GB_GR_UINT",
"150": "GFX10_FORMAT_GB_GR_SRGB",
"151": "GFX10_FORMAT_BG_RG_UNORM",
"152": "GFX10_FORMAT_BG_RG_SNORM",
"153": "GFX10_FORMAT_BG_RG_UINT",
"154": "GFX10_FORMAT_BG_RG_SRGB",
"156": "GFX10_FORMAT_FMASK8_S2_F1",
"157": "GFX10_FORMAT_FMASK8_S4_F1",
"158": "GFX10_FORMAT_FMASK8_S8_F1",
"159": "GFX10_FORMAT_FMASK8_S2_F2",
"160": "GFX10_FORMAT_FMASK8_S4_F2",
"161": "GFX10_FORMAT_FMASK8_S4_F4",
"162": "GFX10_FORMAT_FMASK16_S16_F1",
"163": "GFX10_FORMAT_FMASK16_S8_F2",
"164": "GFX10_FORMAT_FMASK32_S16_F2",
"165": "GFX10_FORMAT_FMASK32_S8_F4",
"166": "GFX10_FORMAT_FMASK32_S8_F8",
"167": "GFX10_FORMAT_FMASK64_S16_F4",
"168": "GFX10_FORMAT_FMASK64_S16_F8",
"169": "GFX10_FORMAT_BC1_UNORM",
"170": "GFX10_FORMAT_BC1_SRGB",
"171": "GFX10_FORMAT_BC2_UNORM",
"172": "GFX10_FORMAT_BC2_SRGB",
"173": "GFX10_FORMAT_BC3_UNORM",
"174": "GFX10_FORMAT_BC3_SRGB",
"175": "GFX10_FORMAT_BC4_UNORM",
"176": "GFX10_FORMAT_BC4_SNORM",
"177": "GFX10_FORMAT_BC5_UNORM",
"178": "GFX10_FORMAT_BC5_SNORM",
"179": "GFX10_FORMAT_BC6_UFLOAT",
"180": "GFX10_FORMAT_BC6_SFLOAT",
"181": "GFX10_FORMAT_BC7_UNORM",
"182": "GFX10_FORMAT_BC7_SRGB",
"265": "GFX10_FORMAT_MM_8_UNORM",
"266": "GFX10_FORMAT_MM_8_UINT",
"267": "GFX10_FORMAT_MM_8_8_UNORM",
"268": "GFX10_FORMAT_MM_8_8_UINT",
"269": "GFX10_FORMAT_MM_8_8_8_8_UNORM",
"270": "GFX10_FORMAT_MM_8_8_8_8_UINT",
"271": "GFX10_FORMAT_MM_VYUY8_UNORM",
"272": "GFX10_FORMAT_MM_VYUY8_UINT",
"273": "GFX10_FORMAT_MM_10_11_11_UNORM",
"274": "GFX10_FORMAT_MM_10_11_11_UINT",
"275": "GFX10_FORMAT_MM_2_10_10_10_UNORM",
"276": "GFX10_FORMAT_MM_2_10_10_10_UINT",
"277": "GFX10_FORMAT_MM_16_16_16_16_UNORM",
"278": "GFX10_FORMAT_MM_16_16_16_16_UINT",
"279": "GFX10_FORMAT_MM_10_IN_16_UNORM",
"280": "GFX10_FORMAT_MM_10_IN_16_UINT",
"281": "GFX10_FORMAT_MM_10_IN_16_16_UNORM",
"282": "GFX10_FORMAT_MM_10_IN_16_16_UINT",
"283": "GFX10_FORMAT_MM_10_IN_16_16_16_16_UNORM ",
"284": "GFX10_FORMAT_MM_10_IN_16_16_16_16_UINT",
"285": "GFX10_FORMAT_7E3_FLOAT",
"286": "GFX10_FORMAT_YCBCR_UNORM",
"287": "GFX10_FORMAT_YCBCR_SNORM",
"288": "GFX10_FORMAT_YCBCR_USCALED",
"289": "GFX10_FORMAT_YCBCR_SSCALED",
"290": "GFX10_FORMAT_YCBCR_UINT",
"291": "GFX10_FORMAT_YCBCR_SINT",
"292": "GFX10_FORMAT_YCBCR_SRGB"
}

86
tools/hashdict.py Normal file
View File

@ -0,0 +1,86 @@
"""Build a joaat (Jenkins one-at-a-time, lowercased) hash -> 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 <carve dir> --out hashes.json [--archives a,b] [--extra f1 f2 ...] [--min 3]
python -I hashdict.py --lookup <hashes.json> 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())

92
tools/manifest.py Normal file
View File

@ -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 <game_dir> [--out FILE]
python -I manifest.py verify <game_dir> [--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())

198
tools/pe_inspect.py Normal file
View File

@ -0,0 +1,198 @@
"""Inspect a PE image (exe or dll) for porting work.
Usage:
python -I pe_inspect.py <image> [--game-dir DIR] [--out DIR]
Writes <out>/<name>.json and <out>/<name>.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())

3245
tools/rdna2spirv.py Normal file

File diff suppressed because it is too large Load Diff

122
tools/rpf9_carve.py Normal file
View File

@ -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 <offset>.bin. It also records which byte
ranges it couldn't read, so coverage is measurable.
Usage:
python -I rpf9_carve.py <archive.rpf> <out_dir> [--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("<I", m, 4)[0]
end = min(size, pos + a.limit) if a.limit else size
rows, last, unread, zero = [], pos, 0, 0
t0 = time.time()
while pos < end:
mt = ZHDR.search(m, pos, end)
if not mt:
break
s = mt.start()
if m[s:s + 3] == b"KB2":
blen = struct.unpack_from("<I", m, s + 4)[0] + 8
w, h = struct.unpack_from("<II", m, s + 0x14)
if not (64 <= blen <= size - s and 16 <= w <= 8192 and 16 <= h <= 8192):
pos = s + 1
continue
gap = m[last:s]
if gap.count(0) == len(gap):
zero += len(gap)
else:
unread += len(gap)
rows.append({"off": s, "stored": blen, "size": blen, "type": "bink2", "w": w, "h": h,
"frames": struct.unpack_from("<I", m, s + 8)[0], "pre": "", "head": m[s:s + 16].hex()})
if not a.index_only:
with open(os.path.join(a.out, f"{s:012x}.bk2"), "wb") as f:
f.write(m[s:s + blen])
last = pos = s + blen
continue
d = zlib.decompressobj()
try:
chunks, p = [], s
while not d.eof and p < size:
chunks.append(d.decompress(m[p:p + (1 << 20)]))
p += 1 << 20
if d.unused_data or d.eof:
break
out = b"".join(chunks) + d.flush()
except zlib.error:
pos = s + 1
continue
if not d.eof or len(out) < 64:
pos = s + 1
continue
used = p - s - len(d.unused_data)
gap = m[last:s]
if gap.count(0) == len(gap):
zero += len(gap)
else:
unread += len(gap)
rows.append({"off": s, "stored": used, "size": len(out), "pre": m[max(0, s - 16):s].hex(),
"head": out[:16].hex()})
if not a.index_only:
with open(os.path.join(a.out, f"{s:012x}.bin"), "wb") as f:
f.write(out)
last = pos = s + used
if len(rows) % 2000 == 0:
done = (pos - (a.start or 0)) / max(1, end - (a.start or 0))
print(f"[{done:6.1%}] {len(rows)} files, {time.time() - t0:.0f}s", flush=True)
tail = m[last:end]
if tail.count(0) == len(tail):
zero += len(tail)
else:
unread += len(tail)
total = sum(r["stored"] for r in rows)
bink = sum(r["stored"] for r in rows if r.get("type") == "bink2")
span = end - (a.start if a.start is not None else struct.unpack_from("<I", open(a.archive, "rb").read(8), 4)[0])
summary = {"archive": a.archive, "files": len(rows), "compressed_bytes": total,
"inflated_bytes": sum(r["size"] for r in rows), "bink2_bytes": bink,
"bink2_files": sum(1 for r in rows if r.get("type") == "bink2"),
"zero_padding": zero, "unread_bytes": unread,
"span": span}
with open(os.path.join(a.out, "index.json"), "w", encoding="utf-8") as f:
json.dump({"summary": summary, "files": rows}, f)
print(json.dumps(summary, indent=1))
print(f"readable: {total / span:.1%}, zero padding {zero / span:.1%}, unread {unread / span:.1%}")
return 0
if __name__ == "__main__":
sys.exit(main())

154
tools/rpf9dump/Program.cs Normal file
View File

@ -0,0 +1,154 @@
// Bulk exporter around rpf9-explorer's Core (github.com/breadbbbb/rpf9-explorer).
// Local use only: writes OBJ/DDS/JSON from the user's own package. No keys, no TOC decryption.
using System.Diagnostics;
using System.Text.Json;
using RpfPreview.Core;
if (args.Length < 3) { Console.WriteLine("usage: rpf9dump ttpf|models|textures <source> <outdir>"); 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<object>();
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<long>(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<long>(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<ArchiveEntry>();
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<object>();
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;
}
}

View File

@ -0,0 +1,5 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><ServerGarbageCollection>true</ServerGarbageCollection></PropertyGroup>
<!-- third_party/rpf9-explorer is a git submodule (git submodule update, with the init option) -->
<ItemGroup><ProjectReference Include="..\..\third_party\rpf9-explorer\Core\RpfPreview.Core.csproj" /></ItemGroup>
</Project>

66
tools/rpf_probe.py Normal file
View File

@ -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 <game_dir> [--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())

120
tools/rtti_scan.py Normal file
View File

@ -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 <image> [--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("<I", img, rva)[0]
# 1. Type descriptors: '.?AV' / '.?AU' strings, 16 bytes after the descriptor start.
tds = {}
for m in re.finditer(rb"\.\?A[VUW][\x21-\x7e]{1,2000}?@@\x00", img):
rva = m.start() - 16
if rva >= 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("<Q", img, p)[0]
if q in col_vas:
vt = p + 8
n = 0
while vt + 8 * (n + 1) <= len(img):
f = struct.unpack_from("<Q", img, vt + 8 * n)[0] - base
if not (0 <= f < len(img) and is_exec(f)):
break
n += 1
col = cols[col_vas[q]]
vtables.append({"rva": vt, "class": classes.get(col["td"], {}).get("name", "?"),
"offset_in_object": col["offset"], "slots": n})
out = {"image": a.image, "type_descriptors": len(tds), "classes": sorted(classes.values(), key=lambda c: c["name"]),
"vtables": sorted(vtables, key=lambda v: v["rva"])}
path = a.out or re.sub(r"\.(exe|dll)$", "", a.image, flags=re.I) + ".rtti.json"
with open(path, "w", encoding="utf-8") as f:
json.dump(out, f, indent=1)
print(f"{a.image}: {len(tds)} type descriptors, {len(classes)} classes with RTTI, {len(vtables)} vtables -> {path}")
for c in out["classes"][:5]:
print(" ", c["name"], "<-", ", ".join(c["bases"][:4]))
if __name__ == "__main__":
sys.exit(main())

85
tools/shader_carve.py Normal file
View File

@ -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:
<name> 00 <u8 kind> <u32 stored> <u32 id> <u32 stored> <u32 size> <raw deflate, `stored` bytes>
and inflates to a DXBC container (`size` bytes) holding DXIL plus an Xbox PRIV part.
Usage:
python -I shader_carve.py <archive.rpf> <out_dir>
Writes <out_dir>/<name>.dxbc and <out_dir>/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("<I", dxbc, 28)[0]
out = {}
for k in range(n):
off = struct.unpack_from("<I", dxbc, 32 + 4 * k)[0]
out[dxbc[off:off + 4].decode("latin-1")] = (off + 8, struct.unpack_from("<I", dxbc, off + 4)[0])
return out
def shader_model(dxbc: bytes, p: dict):
if "DXIL" not in p:
return None, None
off, _ = p["DXIL"]
ver, kind = struct.unpack_from("<HH", dxbc, off)
return STAGES.get(kind, str(kind)), f"{ver >> 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("<I", mt.group(3))[0]
size = struct.unpack("<I", mt.group(5))[0]
if not (16 < stored < 64 << 20 and 32 < size < 256 << 20):
continue
start = mt.end()
try:
data = zlib.decompressobj(-15).decompress(m[start:start + stored], size + 1)
except zlib.error:
bad += 1
continue
if data[:4] != b"DXBC" or len(data) != size:
bad += 1
continue
p = parts(data)
stage, sm = shader_model(data, p)
# Same name twice means distinct variants; keep both.
n = seen.get(name, 0)
seen[name] = n + 1
fname = re.sub(r'[<>:"/\\|?*]', "_", 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())

93
tools/shader_disasm.py Normal file
View File

@ -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 <fssm dir or file> [--out DIR] [--mcpu gfx1013] [--limit N]
Writes <out>/<name>.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("<I", b, 0xC0)[0]
start = off + 0x28
if 0 < off and start < len(b):
last = b.rfind(ENDPGM, start)
while last >= 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())

160
tools/shader_ir.py Normal file
View File

@ -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 <disasm dir> [--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())

79
tools/shader_profile.py Normal file
View File

@ -0,0 +1,79 @@
"""Profile the disassembled shader corpus: which RDNA instructions the translator must support.
Usage:
python -I shader_profile.py <disasm dir> [--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"<stdin>:\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())

111
tools/swizzle_search.py Normal file
View File

@ -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 <blob> --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("<IIIIIII", hdr, 4, 124, 0x1007, hb * 4, wb * 4, n * bpe, 0, 1)
struct.pack_into("<I", hdr, 108, 0x1000)
if bpe == 8:
struct.pack_into("<II4s", hdr, 76, 32, 4, b"DXT1")
body = bytes(hdr)
else:
struct.pack_into("<II4s", hdr, 76, 32, 4, b"DX10")
body = bytes(hdr) + struct.pack("<IIIII", 98, 3, 0, 1, 0)
Image.open(io.BytesIO(body + lin.tobytes())).convert("RGB").save(out)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("blob")
ap.add_argument("--bpe", type=int, default=8)
ap.add_argument("--tile", type=int, default=65536)
ap.add_argument("--widths", default="1024,2048")
ap.add_argument("--tiles", type=int, default=48)
ap.add_argument("--out")
a = ap.parse_args()
data = open(a.blob, "rb").read()
res = search(data, a.bpe, a.tile, [int(w) for w in a.widths.split(",")], a.tiles)
for s, w, seq in res[:8]:
print(f"score {s:7.2f} width {w:5} bits(low->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())

158
tools/tex_export.py Normal file
View File

@ -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 <out>/<archive>/<cpu blob>_<q index>_<WxH>_<format>.dds and records the choice in export_log.json
Usage:
python -I tex_export.py <textures_index.json> <carve dir> <out dir> [--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("<IIIIIII", hdr, 4, 124, 0x1007 | 0x80000, h, w, len(payload), 0, 1)
struct.pack_into("<II4s", hdr, 76, 32, 4, b"DX10")
struct.pack_into("<I", hdr, 108, 0x1000)
return bytes(hdr) + struct.pack("<IIIII", fmt, 3, 0, 1, 0) + payload
def score_image(w, h, fmt, payload, bpe):
if fmt in PILLOW_OK:
from PIL import Image
im = Image.open(io.BytesIO(dds_bytes(w, h, DECODE_AS.get(fmt, fmt), payload))).convert("RGB")
a = np.asarray(im.reduce(4) if min(w, h) >= 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())

96
tools/tex_headers.py Normal file
View File

@ -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 <carve dir> [--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], "<u8")
# Any GPU pointer whose header (4 qwords later) decodes to sane dimensions and a known DXGI format.
for k in np.nonzero(((q >> 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())

101
tools/tex_mode_probe.py Normal file
View File

@ -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 <textures_index.json> <carve dir> [--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())

150
tools/tile_probe.py Normal file
View File

@ -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 <blob> [--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("<IIIIIII", hdr, 4, 124, 0x1007, h, w, n * bpe, 0, 1)
if bpe == 8:
struct.pack_into("<II4s", hdr, 76, 32, 4, b"DXT1")
body = bytes(hdr)
else:
struct.pack_into("<II4s", hdr, 76, 32, 4, b"DX10")
body = bytes(hdr) + struct.pack("<IIIII", 98, 3, 0, 1, 0) # BC7_UNORM, TEXTURE2D
struct.pack_into("<I", hdr, 108, 0x1000)
im = Image.open(io.BytesIO(body + lin.tobytes())).convert("RGB")
im.save(out)
return im.size
def main():
ap = argparse.ArgumentParser()
ap.add_argument("blob")
ap.add_argument("--offset", type=int, default=0)
ap.add_argument("--out")
a = ap.parse_args()
data = open(a.blob, "rb").read()
res = probe(data, a.offset)
for s, bpe, wpx, mode in res[:6]:
print(f"score {s:8.2f} {bpe}-byte blocks width {wpx:5} {mode}")
if a.out and res:
_, bpe, wpx, mode = res[0]
print("preview", render(data, a.offset, bpe, wpx, mode, a.out), "->", a.out)
if __name__ == "__main__":
sys.exit(main())

213
viewer/index.html Normal file
View File

@ -0,0 +1,213 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Map Viewer</title>
<style>
:root { --bg: #0d1014; --fg: #e6e8eb; --dim: #8b929b; --accent: #5fb3ff; --warn: #ffb454; --panel: rgba(13,16,20,.82); }
html, body { margin: 0; height: 100%; background: var(--bg); color: var(--fg); font: 13px/1.45 ui-monospace, Consolas, monospace; overflow: hidden; }
canvas { display: block; }
#hud { position: fixed; top: 12px; left: 12px; background: var(--panel); padding: 10px 12px; border-radius: 8px; min-width: 250px; pointer-events: none; }
#hud b { color: var(--accent); font-weight: 600; }
#banner { position: fixed; top: 12px; right: 12px; max-width: 360px; background: var(--panel); border-left: 3px solid var(--warn); padding: 10px 12px; border-radius: 8px; }
#banner.hidden { display: none; }
#help { position: fixed; bottom: 12px; left: 12px; background: var(--panel); padding: 10px 12px; border-radius: 8px; color: var(--dim); }
#help kbd { color: var(--fg); background: #1c2129; padding: 0 5px; border-radius: 3px; }
#start { position: fixed; inset: 0; display: grid; place-items: center; background: rgba(0,0,0,.45); cursor: pointer; font-size: 15px; }
#start.hidden { display: none; }
@media (max-width: 760px) {
#hud { right: 12px; min-width: 0; }
#banner { top: auto; bottom: 104px; left: 12px; max-width: none; }
#help { right: 12px; }
}
</style>
</head>
<body>
<div id="hud"></div>
<div id="banner"></div>
<div id="help">
<kbd>W A S D</kbd> move · <kbd>Q</kbd>/<kbd>E</kbd> down/up · <kbd>Shift</kbd> fast · <kbd>Ctrl</kbd> slow · wheel: speed<br>
<kbd>F</kbd> wireframe · <kbd>G</kbd> chunk bounds · <kbd>R</kbd> back to spawn · <kbd>Esc</kbd> release mouse
</div>
<div id="start">Click to fly</div>
<script type="importmap">
{ "imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/"
} }
</script>
<script type="module">
import * as THREE from "three";
import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
// ---------- world description ----------
// world/world.json: { "spawn": [x,y,z], "chunks": [ { "id", "url", "bounds": [minx,miny,minz,maxx,maxy,maxz] } ] }
// Each chunk is a .glb in world space (Y up, metres). When no world.json exists the viewer
// generates TEST terrain locally and says so on screen.
async function loadWorld() {
if (new URLSearchParams(location.search).has("test")) return testWorld();
try {
const r = await fetch("world/world.json", { cache: "no-store" });
if (!r.ok) throw new Error(r.status);
const w = await r.json();
w.test = false;
return w;
} catch { return testWorld(); }
}
function testWorld() {
const size = 256, n = 24, chunks = [];
for (let z = -n / 2; z < n / 2; z++)
for (let x = -n / 2; x < n / 2; x++)
chunks.push({ id: `test_${x}_${z}`, test: [x, z, size],
bounds: [x * size, -50, z * size, (x + 1) * size, 200, (z + 1) * size] });
return { test: true, spawn: [0, 120, 0], chunks };
}
// Deterministic test terrain: rolling hills plus a grid of boxes. Nothing here comes from the game.
function hash(x, z) { const s = Math.sin(x * 127.1 + z * 311.7) * 43758.5453; return s - Math.floor(s); }
function noise(x, z) {
const xi = Math.floor(x), zi = Math.floor(z), xf = x - xi, zf = z - zi;
const u = xf * xf * (3 - 2 * xf), v = zf * zf * (3 - 2 * zf);
const a = hash(xi, zi), b = hash(xi + 1, zi), c = hash(xi, zi + 1), d = hash(xi + 1, zi + 1);
return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v;
}
function height(x, z) {
return 60 * noise(x / 900, z / 900) + 18 * noise(x / 210, z / 210) + 4 * noise(x / 40, z / 40) - 30;
}
function buildTestChunk([cx, cz, size]) {
const g = new THREE.Group(), seg = 32;
const geo = new THREE.PlaneGeometry(size, size, seg, seg);
geo.rotateX(-Math.PI / 2);
const pos = geo.attributes.position, col = [];
for (let i = 0; i < pos.count; i++) {
const x = pos.getX(i) + cx * size + size / 2, z = pos.getZ(i) + cz * size + size / 2, y = height(x, z);
pos.setXYZ(i, x, y, z);
const t = THREE.MathUtils.clamp((y + 30) / 90, 0, 1);
col.push(0.22 + 0.35 * t, 0.36 + 0.25 * t, 0.24 + 0.1 * t);
}
geo.setAttribute("color", new THREE.Float32BufferAttribute(col, 3));
geo.computeVertexNormals();
g.add(new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.95 })));
const box = new THREE.BoxGeometry(1, 1, 1); box.translate(0, 0.5, 0);
const count = 18, inst = new THREE.InstancedMesh(box, new THREE.MeshStandardMaterial({ color: 0x9aa4b1, roughness: 0.7 }), count);
const m = new THREE.Matrix4();
for (let i = 0; i < count; i++) {
const x = cx * size + hash(cx * 31 + i, cz) * size, z = cz * size + hash(cx, cz * 17 + i) * size;
const w = 8 + 22 * hash(i, cx + cz), h = 6 + 70 * hash(cz + i, cx) ** 3;
m.compose(new THREE.Vector3(x, height(x, z) - 1, z), new THREE.Quaternion(), new THREE.Vector3(w, h, w));
inst.setMatrixAt(i, m);
}
g.add(inst);
return g;
}
// ---------- scene ----------
const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
renderer.setPixelRatio(Math.min(devicePixelRatio, 1.5));
renderer.setSize(innerWidth, innerHeight);
document.body.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x9cc3e6);
scene.fog = new THREE.Fog(0x9cc3e6, 900, 2600);
const camera = new THREE.PerspectiveCamera(70, innerWidth / innerHeight, 0.5, 6000);
scene.add(new THREE.HemisphereLight(0xdfefff, 0x4a4030, 1.1));
const sun = new THREE.DirectionalLight(0xfff2dd, 1.6); sun.position.set(0.4, 1, 0.3); scene.add(sun);
addEventListener("resize", () => { camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); renderer.setSize(innerWidth, innerHeight); });
// ---------- freecam ----------
const keys = new Set(); let yaw = 0, pitch = -0.25, speed = 40, locked = false;
// Pointer lock when the browser allows it; embedded views (iframes, preview panes) fall back to drag-to-look.
const start = document.getElementById("start");
let dragLook = false, dragging = false;
start.onclick = async () => {
try { await renderer.domElement.requestPointerLock(); }
catch { dragLook = true; start.classList.add("hidden"); document.getElementById("help").insertAdjacentHTML("beforeend", "<br>mouse lock unavailable here: drag to look"); }
};
document.addEventListener("pointerlockchange", () => { locked = document.pointerLockElement === renderer.domElement; start.classList.toggle("hidden", locked || dragLook); });
renderer.domElement.addEventListener("mousedown", () => { dragging = true; });
addEventListener("mouseup", () => { dragging = false; });
addEventListener("mousemove", e => {
if (!locked && !(dragLook && dragging)) return;
yaw -= e.movementX * 0.0022; pitch = THREE.MathUtils.clamp(pitch - e.movementY * 0.0022, -1.55, 1.55);
});
addEventListener("wheel", e => { speed = THREE.MathUtils.clamp(speed * (e.deltaY < 0 ? 1.15 : 1 / 1.15), 1, 3000); }, { passive: true });
addEventListener("keydown", e => {
keys.add(e.code);
if (e.code === "KeyF") wire = !wire, applyWire();
if (e.code === "KeyG") showBounds = !showBounds, boundsGroup.visible = showBounds;
if (e.code === "KeyR") camera.position.fromArray(world.spawn);
});
addEventListener("keyup", e => keys.delete(e.code));
addEventListener("blur", () => keys.clear());
// ---------- chunk streaming ----------
const LOAD_R = 1400, UNLOAD_R = 2000, MAX_INFLIGHT = 4;
const loader = new GLTFLoader();
const live = new Map(); let inflight = 0, wire = false, showBounds = false, failed = 0;
const boundsGroup = new THREE.Group(); boundsGroup.visible = false; scene.add(boundsGroup);
function applyWire(root) {
(root ? [root] : [...live.values()].map(c => c.obj).filter(Boolean)).forEach(o =>
o.traverse(n => { if (n.material) [].concat(n.material).forEach(m => m.wireframe = wire); }));
}
function dist(c, p) {
const b = c.bounds;
const dx = Math.max(b[0] - p.x, 0, p.x - b[3]), dy = Math.max(b[1] - p.y, 0, p.y - b[4]), dz = Math.max(b[2] - p.z, 0, p.z - b[5]);
return Math.hypot(dx, dy, dz);
}
function drop(id) {
const c = live.get(id); if (!c) return;
if (c.obj) { scene.remove(c.obj); c.obj.traverse(n => { n.geometry?.dispose(); [].concat(n.material || []).forEach(m => { m.map?.dispose(); m.dispose(); }); }); }
live.delete(id);
}
function stream() {
const p = camera.position;
for (const [id, c] of live) if (c.obj && dist(c.def, p) > UNLOAD_R) drop(id);
const want = world.chunks.filter(c => !live.has(c.id) && dist(c, p) < LOAD_R).sort((a, b) => dist(a, p) - dist(b, p));
for (const def of want) {
if (inflight >= MAX_INFLIGHT) break;
const entry = { def, obj: null }; live.set(def.id, entry);
if (def.test) { entry.obj = buildTestChunk(def.test); scene.add(entry.obj); applyWire(entry.obj); continue; }
inflight++;
loader.load(def.url, g => { inflight--; if (live.get(def.id) !== entry) return; entry.obj = g.scene; scene.add(g.scene); applyWire(g.scene); },
undefined, () => { inflight--; failed++; });
}
}
// ---------- main loop ----------
const world = await loadWorld();
camera.position.fromArray(world.spawn);
const banner = document.getElementById("banner");
if (world.test) banner.innerHTML = "<b>TEST TERRAIN</b>: generated in the browser. No game geometry has been decoded yet. " +
"Put <code>world/world.json</code> and .glb chunks beside this page to view real data.";
else banner.classList.add("hidden");
for (const c of world.chunks) {
const b = c.bounds, box = new THREE.Box3(new THREE.Vector3(b[0], b[1], b[2]), new THREE.Vector3(b[3], b[4], b[5]));
boundsGroup.add(new THREE.Box3Helper(box, 0x5fb3ff));
}
const hud = document.getElementById("hud"), clock = new THREE.Clock();
let fpsT = 0, fpsN = 0, fps = 0;
const fwd = new THREE.Vector3(), right = new THREE.Vector3(), up = new THREE.Vector3(0, 1, 0);
renderer.setAnimationLoop(() => {
const dt = Math.min(clock.getDelta(), 0.1);
camera.quaternion.setFromEuler(new THREE.Euler(pitch, yaw, 0, "YXZ"));
camera.getWorldDirection(fwd); right.crossVectors(fwd, up).normalize();
const v = new THREE.Vector3(), s = speed * (keys.has("ShiftLeft") || keys.has("ShiftRight") ? 5 : 1) * (keys.has("ControlLeft") ? 0.2 : 1);
if (keys.has("KeyW")) v.add(fwd); if (keys.has("KeyS")) v.sub(fwd);
if (keys.has("KeyD")) v.add(right); if (keys.has("KeyA")) v.sub(right);
if (keys.has("KeyE")) v.y += 1; if (keys.has("KeyQ")) v.y -= 1;
if (v.lengthSq()) camera.position.addScaledVector(v.normalize(), s * dt);
stream();
renderer.render(scene, camera);
fpsN++; fpsT += dt; if (fpsT > 0.5) { fps = fpsN / fpsT; fpsN = 0; fpsT = 0; }
const p = camera.position, loaded = [...live.values()].filter(c => c.obj).length;
hud.innerHTML = `<b>${world.test ? "test terrain" : "world"}</b><br>pos ${p.x.toFixed(1)}, ${p.y.toFixed(1)}, ${p.z.toFixed(1)}<br>` +
`speed ${speed.toFixed(0)} m/s · ${fps.toFixed(0)} fps<br>chunks ${loaded}/${world.chunks.length} loaded, ${inflight} loading` +
(failed ? `, <span style="color:var(--warn)">${failed} failed</span>` : "") +
`<br>draw calls ${renderer.info.render.calls}, tris ${(renderer.info.render.triangles / 1000).toFixed(0)}k`;
});
</script>
</body>
</html>

47
viewer/serve.py Normal file
View File

@ -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()