├── .github └── workflows │ └── test.yml ├── .gitignore ├── LICENSE ├── README.md ├── __init__.py ├── assetbuilder.py ├── examples ├── pulse │ ├── pulse_struct.json │ ├── pulsesample.vpulse │ └── pulsesample_redi.kv3 ├── responserules │ ├── RED2_responserule.kv3 │ ├── responserule.vrr │ └── vrr_struct.json └── typescript │ ├── sourcets.vts │ ├── sourcets_redi.kv3 │ ├── sourcets_stat.kv3 │ └── typescript_struct.json ├── img └── asset_hex.png ├── requirements.txt └── tests ├── files ├── asset1.vts_c ├── asset2.vmat_c ├── asset_minimal.vts_c ├── rerlblock.bin ├── rerltest.txt └── samples │ ├── data.kv3 │ ├── data_witharrays.kv3 │ ├── data_withblobs.kv3 │ ├── data_withflags.kv3 │ ├── edited.kv3 │ ├── file.vpulse_c │ ├── red2.kv3 │ └── struct.json ├── test_general.py ├── test_readers.py ├── test_schema.py ├── test_usage.py └── test_writers.py /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: [pull_request, push] 4 | 5 | env: 6 | DECOMPILER_VERSION: 11.1 7 | permissions: 8 | contents: read 9 | 10 | jobs: 11 | recomp_test: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | - name: Set up Python 3.12.5 16 | uses: actions/setup-python@v5 17 | with: 18 | python-version: "3.12.5" 19 | cache: "pip" 20 | - name: Install dependencies 21 | run: | 22 | python -m pip install --upgrade pip 23 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 24 | pip install pytest 25 | - name: Cache decompiler 26 | id: cache-decompiler 27 | uses: actions/cache@v3 28 | with: 29 | path: ./Decompiler 30 | key: ${{ runner.os }}-test-decompiler-${{ env.DECOMPILER_VERSION }} 31 | 32 | - if: ${{ steps.cache-decompiler.outputs.cache-hit != 'true' }} 33 | name: Download decompiler 34 | uses: robinraju/release-downloader@v1 35 | with: 36 | repository: 'ValveResourceFormat/ValveResourceFormat' 37 | tag: ${{ env.DECOMPILER_VERSION }} 38 | fileName: 'Decompiler-linux-x64.zip' 39 | zipBall: true 40 | extract: true 41 | token: ${{ secrets.GH_TOKEN }} 42 | - name: Run test 43 | run: | 44 | export PYTHONPATH=$(pwd) 45 | chmod +x ./Decompiler 46 | pytest 47 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .venv 2 | .vscode 3 | .test 4 | .pytest_cache/ 5 | __pycache__/ 6 | localtests -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | A tool to compile Source 2 assets manually. 2 | 3 | ## What's the use for this tool? 4 | Many assets in Source 2 games still don't have a way to be compiled, or are tied to systems that are still work in progress which means that their compilers are just not shared to the public yet by Valve. 5 | 6 | As a good chunk of assets are text or KeyValues based, it's usually not too hard to read what they do, however they can't be modified easily as they are saved in a binary format. Some of the assets include: **Pulse Graphs**, **Response Rules** or **AnimGraphs in CS2** and more. 7 | 8 | This tool is meant to allow editing of such assets, or creating new ones from scratch, with completely custom block layout and the data inside them. The outputted files will be in already compiled format (with **_c** extension) ready to be used by the game engine. 9 | 10 | > [!NOTE] 11 | > This tool is still in an early development state and will not support every asset, such as models for example. The tool has been tested on a tiny subset of assets that exists, and it might generate invalid files in some cases. If that happens you're welcome to open an issue. Depending on the popularity, this tool will be devloped further to introduce more features. You are also welcome to contribute yourself! 12 | 13 | > [!WARNING] 14 | > This tool is meant for somewhat experienced modders. Assets created in this way have no easy way to be validated by the game, because they were not compiled by using their official compiler, which could properly verify it. This means that due to any, even tiny mistakes the asset might not work or cause crashes with very little or no explaination from the game. You're on your own here! 15 | 16 | ### TODO 17 | - [ ] Support more asset types / KV3 versions 18 | - [x] Allow binary data to be used as input 19 | - [ ] vxml layout content compiler 20 | - [ ] `--watch` parameter to recompile asset right after saving 21 | - [ ] filelist input 22 | 23 | ## Usage 24 | There are a few ways of using the asset builder. Files can either be created from scratch with a custom layout, or an existing asset can be edited by swapping out own provided block data. 25 | 26 | ## Creating Assets 27 | First one is to use a JSON 'Schematic' file that defines the structure of the asset and the files that go with it. The second one is to use a preset or a structure based on an existing asset, and provide the inputs manually. 28 | ### JSON Schema usage 29 | This is example of a JSON file usable with this tool. It defines the valid structure for a VPULSE asset. 30 | You can find more examples in the `examples` directory. 31 | ```json 32 | { 33 | "info": { 34 | "headerversion": 12, 35 | "version": 0 36 | }, 37 | "blocks": [ 38 | { 39 | "type": "kv3", 40 | "name": "RED2", 41 | "file": "eventhandler_redi.kv3" 42 | }, 43 | { 44 | "type": "kv3", 45 | "name": "DATA", 46 | "file": "eventhandler.kv3" 47 | } 48 | ] 49 | } 50 | ``` 51 | There's a few things going on here so let's explain: 52 | 53 | The `info` block contains the information stored at the very beginning of the asset. They usually determine the asset type as read by the game. `headerversion` (Marked yellow) is a 2 byte integer starting at 5th byte from the start, `version` (Marked blue) is also a 2 byte integer starting at the 7th byte. Both these values, are little-endian. 54 | 55 | ![](img/asset_hex.png) 56 | 57 | The `blocks` section contains an array of blocks that are part of the asset. Every object contains the following parameters: 58 | 59 | - `type` - type of data stored, supported values right now are: `kv3v4`, `kv3v3` or `kv3` (which will default to binary v4) plain text: `text`, resource external info (`rerl`) and generic binary data: `bin` 60 | - `name` - name of the block (as can be seen in Source 2 Viewer). It must be a **4 letter ASCII string**. 61 | - `file` - the source file to use for this block's data. File path is **relative** to the directory of the JSON file. 62 | 63 | To use a schema file for compilation use the `-s` or `--schema` parameter with the relative path and file name to the schema file. Like with every method, specifying the output file with `-o` or `--output` is also required. 64 | 65 | ### RERL source file 66 | Entries can be defined in the following format 67 | ` ` 68 | each next entry is separated by a newline 69 | 70 | ### Preset usage 71 | It's also possible to use a ready to go preset for some asset types. 72 | Currently supported (and tested) asset types include: 73 | 74 | | Preset name | Asset type | 75 | | ---- | ----------- | 76 | | `vpulse` | Pulse Graph | 77 | | `vrr` | Response Rules | 78 | | `cs2vanmgrph` | CS2 AnimGraph | 79 | | `smartptop` | Smart Prop | 80 | 81 | To compile using a preset use the `-p` or `--preset` flag, with the preset name from the table. The parameter also requires a certain number of input files depending on the type, provied one after another with `-f` or `--files` parameters. As always it also requires the `-o` or `--output` parameter with the filename. 82 | 83 | example: 84 | `python assetbuilder.py -p vpulse -f pulsefile_redi.kv3 pulsefile.vpulse -o pulsefile.vpulse_c` 85 | 86 | ### Using a existing asset as a base 87 | If there's no provided preset or you don't want to create a custom JSON file, instead of `-p/--preset` it's possible to use `-b/--base` argument and provide a compiled asset file, it will be used as a structure for the compiled asset. The usage is very similar as when using the presets (see above). 88 | **NOTE** Only more basic assets will be supported, as only text and kv3 data is supported at this moment. 89 | 90 | ## Editing assets 91 | More compilcated assets can be edited directly, by swapping out their 'blocks'. This might be useful for smaller changes, without having to recompile an asset if an ordinary recompilation of it is hard or impossible. To do so use the `-e` or `--edit` parameter, followed by an input file, and the blocks that you want swapped. Afterwards input the same order with the `-f` argument. 92 | 93 | example: swapping out the `DATA` block of a vmdl asset: 94 | `assetbuilder.py -e wraith.vmdl_c DATA -f wraith_data.kv3 -o wraith_new.vmdl_c` 95 | 96 | ## Installation 97 | Requirements: Python (preferably >= 3.12.5) and pip. 98 | It is a good idea to create a VENV, to isolate the dependencies, however it is not necessary. Read more here: 99 | https://docs.python.org/3/tutorial/venv.html 100 | 101 | Either in a virtual environment or in a global context run: 102 | `pip install -r requirements.txt`. After it's done you should be good to go. 103 | 104 | ## Contributing 105 | There are no hard set rules for contributing. Fixes or code improvements and refactorizations are very welcome. If you're planning on adding a new feature, it might be a good idea to discuss it first or to create a draft pull request **early** to get the idea across. 106 | I don't want you to waste your time working on a feature that might not be fitting for the vision of this software. 107 | 108 | ## Attributions 109 | Creating this was made hugely possible thanks to people behind ValveResourceFormat/Source2Viewer, and their work on reverse engineering the asset format. Some data structures were directly used from their software's code **MIT License | Copyright (c) 2015 ValveResourceFormat Contributors** -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- 1 | from assetbuilder import * -------------------------------------------------------------------------------- /assetbuilder.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import struct 3 | import json 4 | from enum import IntEnum 5 | from typing import Optional 6 | from dataclasses import dataclass, field 7 | from pathlib import Path 8 | from uuid import UUID 9 | import argparse 10 | import keyvalues3 as kv3 11 | import lz4.block 12 | import lz4.frame 13 | import os 14 | from copy import copy, deepcopy 15 | 16 | class AssetReadErrorGeneric(Exception): 17 | def __init__(self, message: str, filePath: Path | str): 18 | super().__init__(message) 19 | self.filePath = filePath 20 | 21 | class AssetReadError(AssetReadErrorGeneric): 22 | def __init__(self, message: str, filePath: Path | str): 23 | super().__init__(message, filePath) 24 | 25 | class FileFormattingError(Exception): 26 | def __init__(self, message: str, line: int): 27 | super().__init__(message) 28 | self.line = line 29 | 30 | class KVType(IntEnum): 31 | STRING_MULTI = 0, 32 | NULL = 1, 33 | BOOLEAN = 2, 34 | INT64 = 3, 35 | UINT64 = 4, 36 | DOUBLE = 5, 37 | STRING = 6, 38 | BINARY_BLOB = 7, 39 | ARRAY = 8, # generic array of mixed types. Every element has assigned type in types list. 40 | OBJECT = 9, # dict in Python 41 | ARRAY_TYPED = 10, # typed array with 4 byte length saved in data section 42 | INT32 = 11, 43 | UINT32 = 12, 44 | BOOLEAN_TRUE = 13, 45 | BOOLEAN_FALSE = 14, 46 | INT64_ZERO = 15, 47 | INT64_ONE = 16, 48 | DOUBLE_ZERO = 17, 49 | DOUBLE_ONE = 18, 50 | FLOAT = 19, 51 | INT16 = 20, 52 | UINT16 = 21, 53 | UNKNOWN_22 = 22, 54 | INT32_AS_BYTE = 23, 55 | ARRAY_TYPE_BYTE_LENGTH = 24 # typed array with length <= 256. Saved as 1 byte in binaryBytes section 56 | 57 | @dataclass 58 | class FileHeaderInfo: 59 | size: int = 0 60 | offset: int = 0 61 | 62 | @dataclass 63 | class FileBlock: 64 | type: str 65 | name: str 66 | dataProcessed: bool = False 67 | data: bytes = None 68 | 69 | @dataclass 70 | class KVBaseData: 71 | strings: list[str] = field(default_factory=list) 72 | types: list[bytes] = field(default_factory=list) 73 | binaryBytes: list[bytes] = field(default_factory=list) # this list sits at almost the beginning of kv data. 74 | doubles: list[float] = field(default_factory=list) 75 | uncompressedBlockLengthArray: list[int] = field(default_factory=list) 76 | uncompressedByteArrays: list[bytearray] = field(default_factory=list) 77 | blockCount: int = 0 78 | countOfIntegers: int = 0 79 | countOfEightByteValues: int = 0 80 | stringAndTypesBufferSize: int = 0 81 | countOfStrings: int = 0 82 | countOfBinaryBytes: int = 0 83 | 84 | # small function to return the amount of bytes needed to add for alignment so that: fileSize % mod == 0 85 | def alignToBytes(mod: int, fileSize: int) -> tuple[bytes, int]: 86 | bytesAmount = (-fileSize) % mod 87 | return (b'\x00' * bytesAmount, bytesAmount) 88 | 89 | def buildFileData(version: int, headerVersion: int, blocks: list[FileBlock]) -> bytes: 90 | fileSize = 0 # byte 0 (4 bytes) 91 | printDebug(f"version: {version}\nheader version: {headerVersion}\nblock count: {len(blocks)}\n") 92 | headerVersion = headerVersion.to_bytes(2, 'little') # byte 4 (2 bytes) 93 | version = version.to_bytes(2, 'little') # byte 6 (2 bytes) 94 | 95 | blockOffset = 8 # where the block info starts, should really always be the same. 96 | blockOffset = blockOffset.to_bytes(4, 'little') # byte 12 (4 bytes) 97 | blockCount = len(blocks) # amount of blocks 98 | blockCount = blockCount.to_bytes(4, 'little') # byte 16 (4 bytes) 99 | 100 | combinedBlockHeaderData = b'' 101 | assetHeaderSize = (16 + 12*len(blocks)) # 16 is the size of the header, 12 is the size of each block header (name, offset, size) 102 | headerPadAmount = -assetHeaderSize % 16 103 | assetHeaderSize += headerPadAmount # the data is also padded with 0s to align to 16 bytes. 104 | 105 | fileSize = assetHeaderSize 106 | 107 | # the offsets are relative to where they are placed in the file. 108 | # We should know the first one's value, since the first block of data is right after the header. 109 | # first offset: 8 is the offset to another block info, every block info is 12 bytes long. 110 | currentOffset = 8 + ((len(blocks) - 1) * 12) + headerPadAmount 111 | dataBlocks = [] 112 | for idx, block in enumerate(blocks): 113 | printDebug(f"Processing block {idx+1} (name: {block.name} type: {block.type})") 114 | blockData: bytes = b'' 115 | dataSize = 0 116 | usingExistingData = True 117 | blockHeaderInfo = FileHeaderInfo() 118 | if block.dataProcessed == False: 119 | usingExistingData = False 120 | if block.type == "kv3" or block.type == "kv3v4": 121 | blockUUID: UUID = block.data.format.version 122 | blockData = buildKVBlock(block.data, blockUUID.bytes_le, blockHeaderInfo, 4, visualName=block.name) 123 | elif block.type == "kv3v3": 124 | blockUUID: UUID = block.data.format.version 125 | blockData = buildKVBlock(block.data, blockUUID.bytes_le, blockHeaderInfo, 3, visualName=block.name) 126 | elif block.type == "text": 127 | blockData = buildTextBlock(block.data, blockHeaderInfo, visualName=block.name) 128 | elif block.type == "rerl": 129 | blockData = buildRERLBlock(block.data, visualName=block.name) 130 | blockHeaderInfo.size = len(blockData) 131 | else: 132 | usingExistingData = True 133 | blockData = block.data 134 | block.dataProcessed = True 135 | else: 136 | blockData = block.data 137 | 138 | if usingExistingData == False: 139 | dataSize = blockHeaderInfo.size 140 | else: 141 | dataSize = len(blockData) 142 | # fill with 0 bytes to align to 16 bytes 143 | additionalOffset = 0 144 | if idx != len(blocks)-1: 145 | alignBytes = alignToBytes(16, fileSize + dataSize) 146 | blockData += alignBytes[0] 147 | fileSize += alignBytes[1] 148 | additionalOffset = alignBytes[1] 149 | fileSize += dataSize 150 | dataBlocks.append(blockData) 151 | 152 | combinedBlockHeaderData += b''.join([block.name.encode('ascii'), currentOffset.to_bytes(4, 'little'), dataSize.to_bytes(4, 'little')]) 153 | currentOffset += dataSize + additionalOffset 154 | currentOffset -= 12 # -12 because we need to account for where the next offset value is placed. 155 | 156 | binData = b''.join([fileSize.to_bytes(4, 'little'), headerVersion, version, blockOffset, blockCount, # FILE HEADER (16 bytes) 157 | combinedBlockHeaderData, (b'\x00'*headerPadAmount)]) # HEADER DATA FOR BLOCKS + PADDING 158 | for block in dataBlocks: 159 | binData += block # DATA BLOCKS 160 | printDebug(f"Final file size: {fileSize} bytes") 161 | return binData 162 | 163 | KV3_FORMAT_GUID = b'\x7C\x16\x12\x74\xE9\x06\x98\x46\xAF\xF2\xE6\x3E\xB5\x90\x37\xE7' 164 | 165 | def buildRERLBlock(rerlData: list[tuple[int, str]], visualName: str = "RERL") -> bytes: 166 | offset = 8 # seems to be always the same 167 | size = len(rerlData) 168 | idDataSize = 8 + 16 * size 169 | binStrings: bytes = b'' 170 | currentStringOffset = idDataSize - 16 171 | 172 | baseData = b''.join([offset.to_bytes(4, 'little'), size.to_bytes(4, 'little')]) 173 | for idx, entry in enumerate(rerlData): 174 | baseData += entry[0].to_bytes(8, "little") + currentStringOffset.to_bytes(8, "little") 175 | currentStringOffset += len(entry[1]) + 1 - 16 # null terminator, and accounting for the placment of the value itself in file. 176 | binStrings += entry[1].encode('ascii') + b'\x00' 177 | 178 | printDebug(f"Stats for {visualName} block") 179 | printDebug(f"Entry count: {size}") 180 | printDebug(f"IDs and offsets size: {idDataSize}") 181 | printDebug(f"Strings size: {len(binStrings)}") 182 | printDebug(f"Final block size: {len(baseData) + len(binStrings)}") 183 | 184 | return b''.join([baseData, binStrings]) 185 | 186 | def buildTextBlock(textData, textHeaderInfo, visualName: str = "unnamed block") -> bytes: 187 | textHeaderInfo.size = len(textData) 188 | printDebug(f"Stats for {visualName} block") 189 | printDebug(f"Text size: {textHeaderInfo.size}\n") 190 | return textData 191 | 192 | def buildKVBlock(block_data, guid, header_info, kv3version: int = 4, visualName: str = "unnamed block") -> bytes: 193 | # The definitions at the beginning here are useless in terms of the functionality 194 | # However I decided to keep them here in approperiate order to make it easier to understand the structure of the KV3 data. 195 | if kv3version != 4 and kv3version != 3: 196 | raise NotImplementedError("Unsupported KV3 version.") 197 | headerData = KVBaseData() 198 | kv3ver = kv3version.to_bytes(1) 199 | constantsAfterGUID = b'\x01\x00\x00\x00\x00\x00' # contains compressionMethod, compressionDictionaryID 200 | compressionFrameSize = 16384 201 | headerData.countOfBinaryBytes = 0 202 | headerData.countOfIntegers = 1 # All of the actual kv Data plus countOfStrings, which is always here, so we start from one. 203 | headerData.countOfEightByteValues = 0 204 | headerData.stringAndTypesBufferSize = 0 # length of strings + length of types combined 205 | preallocValues = b'\xFF\xFF\xFF\xFF' #! Apparently these are used to preallocate something, for safety I'll put in FFFF, it seems to be working fine so far. 206 | headerData.uncompressedSize = 0 # decompressed kv3 block size 207 | headerData.compressedSize = 0 # compressed kv3 block size 208 | headerData.blockCount = 0 # always the same 209 | blockTotalSize: int = 0 # always the same 210 | # KV3v4 specific values 211 | countOfTwoByteValues: int = 0 # we don't use 16 bit values when building. Is this necessary for some assets to work? 212 | unknown: int = 0 # can ignore for now. 213 | # after all this we finally have actual kv data... 214 | 215 | # ------ DATA LATER IS LZ4 COMPRESSED! ------- 216 | headerData.binaryBytes = [] # length is count of binary bytes 217 | headerData.countOfStrings = 0 218 | # after countOfStrings we have data about the structure, mostly because the data is actually just integers that references stuff. 219 | kvData = b'' 220 | headerData.doubles = [] 221 | doublesBytes = b"" # transformed for appending 222 | # after list of doubles we have a list of null terminated strings: 223 | headerData.strings = [] # add strings here as we go parsing the kv text data. 224 | stringsBytesList: list[bytes] = [] # transformed for appending 225 | # after strings there is list of types, each one is one byte, the length is amount of types that we get from substracting string length from 'stringAndTypesLength' 226 | headerData.types = [] 227 | blockEndTrailer = b'\x00\xDD\xEE\xFF' 228 | # write the binary kv data, and output all stats into headerData 229 | kvData = buildKVStructure(block_data.value, headerData, False, kv3version == 4) 230 | headerData.countOfStrings = len(headerData.strings) 231 | headerData.countOfBinaryBytes = len(headerData.binaryBytes) 232 | # null terminate all strings 233 | for s in headerData.strings: 234 | stringsBytesList.append(bytes(s, "ascii") + b'\x00') 235 | headerData.stringAndTypesBufferSize = len(headerData.types) + len(b''.join(stringsBytesList)) 236 | headerData.binaryBytes = bytes(headerData.binaryBytes) 237 | headerData.binaryBytes += b'\x00' * (-len(headerData.binaryBytes) % 4) # align to 4 bytes 238 | for v in headerData.doubles: 239 | if isinstance(v, float): 240 | doublesBytes += struct.pack(" int: 310 | if useLinearTypes: 311 | # we need to skip over multiline string flag, that's why we don't use enums directly. 312 | match flag: 313 | case kv3.Flag.resource: 314 | return 1 315 | case kv3.Flag.resource_name: 316 | return 2 317 | case kv3.Flag.panorama: 318 | return 3 319 | case kv3.Flag.soundevent: 320 | return 4 321 | case kv3.Flag.subclass: 322 | return 5 323 | case _: 324 | return 0 325 | else: 326 | match flag: 327 | case kv3.Flag.resource: 328 | return 1 329 | case kv3.Flag.resource_name: 330 | return 2 331 | case kv3.Flag.panorama: 332 | return 8 333 | case kv3.Flag.soundevent: 334 | return 16 335 | case kv3.Flag.subclass: 336 | return 32 337 | case _: 338 | return 0 339 | # special types like DOUBLE_ZERO, INT64_ONE can't exist in typed arrays, so we use default types 340 | def getKVTypeFromInstance(obj, inTypedArray: bool = False): 341 | if type(obj) is list: 342 | if len(obj) == 0: 343 | return KVType.ARRAY 344 | # check if all elements are the same, if so use a typed array 345 | previousElementClass = getKVTypeFromInstance(obj[0], True) # TODO account for _ONE and _ZERO types 346 | useTypedArray = True 347 | for element in obj: 348 | currType = getKVTypeFromInstance(element, True) 349 | if currType != previousElementClass: 350 | useTypedArray = False 351 | break 352 | previousElementClass = currType 353 | if useTypedArray: 354 | if(len(obj) < 256): 355 | return KVType.ARRAY_TYPE_BYTE_LENGTH 356 | else: 357 | return KVType.ARRAY_TYPED 358 | else: 359 | return KVType.ARRAY 360 | elif type(obj) is dict: 361 | return KVType.OBJECT 362 | elif type(obj) is str: 363 | return KVType.STRING 364 | elif isinstance(obj, bool): 365 | if obj == True: 366 | return KVType.BOOLEAN_TRUE 367 | else: 368 | return KVType.BOOLEAN_FALSE 369 | elif isinstance(obj, int): 370 | if obj == 0 and inTypedArray == False: 371 | return KVType.INT64_ZERO 372 | elif obj == 1 and inTypedArray == False: 373 | return KVType.INT64_ONE 374 | else: 375 | # it seems not all values that are above or equal 0 are marked as unsigned in official assets. 376 | # however in this case if we know that we can't fit a unsigned value into 32bit signed int, so we use uint32 377 | if obj.bit_length() <= 32: 378 | if obj > 2147483647: 379 | return KVType.UINT32 380 | else: 381 | return KVType.INT32 382 | else: 383 | if obj > 9223372036854775807: 384 | return KVType.UINT64 385 | else: 386 | return KVType.INT64 387 | 388 | elif isinstance(obj, float): 389 | if obj == 0.0 and inTypedArray == False: 390 | return KVType.DOUBLE_ZERO 391 | elif obj == 1.0 and inTypedArray == False: 392 | return KVType.DOUBLE_ONE 393 | else: 394 | return KVType.DOUBLE 395 | elif obj is None: 396 | return KVType.NULL 397 | elif isinstance(obj, kv3.flagged_value): # assuming string value 398 | return KVType.STRING | 0x80 399 | elif isinstance(obj, bytearray): 400 | return KVType.BINARY_BLOB 401 | else: 402 | raise ValueError("KV3: Unhandled type: " + type(obj).__name__) 403 | 404 | def buildKVStructure(obj, header: KVBaseData, inTypedArray, useLinearFlagTypes = False, subType: Optional[KVType] = None) -> bytes: 405 | #global types, countOfIntegers, countOfEightByteValues, countOfStrings, binaryBytes, countOfBinaryBytes 406 | data: list[bytes] = [] 407 | currentType = getKVTypeFromInstance(obj, inTypedArray) 408 | if type(obj) is dict: 409 | if inTypedArray == False: 410 | header.types += currentType.to_bytes(1) 411 | length: int = len(obj) 412 | data += length.to_bytes(4, "little") # for dicts append length at start! 413 | header.countOfIntegers += 1 414 | for key, value in obj.items(): 415 | if type(key) is str: # keys don't get types since they're always strings 416 | stringID = len(header.strings) 417 | if key in header.strings: 418 | stringID = header.strings.index(key) 419 | else: 420 | header.strings.append(key) 421 | header.countOfStrings += 1 422 | data += stringID.to_bytes(4, "little") 423 | header.countOfIntegers += 1 424 | else: 425 | raise ValueError("KV3: Keys must be strings.") 426 | data += buildKVStructure(value, header, False, useLinearFlagTypes) 427 | elif type(obj) is list: 428 | # inside typed arrays we only add the type once (already done up in the call stack in this case) 429 | useTypedArray = True 430 | if currentType == KVType.ARRAY: 431 | useTypedArray = False 432 | if inTypedArray == False: 433 | header.types += currentType.to_bytes(1) 434 | 435 | if currentType == KVType.ARRAY_TYPE_BYTE_LENGTH: 436 | header.binaryBytes += len(obj).to_bytes(1) 437 | header.countOfBinaryBytes += 1 438 | else: # length bigger than 1 byte 439 | data += len(obj).to_bytes(4, "little") 440 | header.countOfIntegers += 1 441 | 442 | if len(obj) > 0: 443 | # if there's mixed "optimized" types in the array then we use the least specific one. That's why we iterate. 444 | # eg. we know that arrays of 0 length get the ARRAY type and ARRAY_TYPE_BYTE_LENGTH type is used for arrays with 1-255 elements. 445 | # if there's at least one empty array, then we assume every element as ARRAY type. 446 | # TODO: does this only affect arrays or other types? Knowing this is not strictly necessary to output a valid file though. 447 | lastValue = obj[0] 448 | subType = getKVTypeFromInstance(lastValue, True) 449 | if useTypedArray: # is using typed array, add the types once here 450 | header.types += subType.to_bytes(1) 451 | if(subType & 0x80 > 0): # flagged string 452 | header.types += getKV3MappedFlag(lastValue.flags, useLinearFlagTypes).to_bytes(1) 453 | 454 | for val in obj: 455 | # we set the last array type here as arrays that contain the same type only save their type ONCE. 456 | # this is known to be done for a few types described below. Explicit types like DOUBLE_ZERO or INT64_ONE 457 | # seem to be only saved in non-typed arrays for each element. 458 | # if we're not in a typed array we add the types right before and note that we are inside an array, so we don't add the type again. 459 | 460 | data += buildKVStructure(val, header, useTypedArray, useLinearFlagTypes, subType) 461 | elif isinstance(obj, bytearray): 462 | if inTypedArray == False: 463 | header.types += currentType.to_bytes(1) 464 | arrLength = len(obj) 465 | header.uncompressedBlockLengthArray.append(arrLength) 466 | header.uncompressedByteArrays.append(obj) 467 | header.blockCount += 1 468 | # I think only strings can have flags attached to them. 469 | elif type(obj) is str or isinstance(obj, kv3.flagged_value): 470 | strVal = obj 471 | if isinstance(obj, kv3.flagged_value): 472 | strVal = obj.value 473 | stringID = len(header.strings) # we will be adding 1 if we're adding a string so this will actually point at the last element. 474 | if strVal in header.strings: 475 | stringID = header.strings.index(strVal) # Reuse existing id 476 | elif len(strVal) == 0: 477 | stringID = -1 478 | else: 479 | header.strings.append(strVal) 480 | header.countOfStrings += 1 481 | data += stringID.to_bytes(4, "little", signed=True) 482 | if inTypedArray == False: 483 | header.types += currentType.to_bytes(1) 484 | if isinstance(obj, kv3.flagged_value): 485 | header.types += getKV3MappedFlag(obj.flags, useLinearFlagTypes).to_bytes(1) 486 | header.countOfIntegers += 1 487 | elif isinstance(obj, bool): 488 | if inTypedArray == False: 489 | header.types += currentType.to_bytes(1) 490 | # no additional data... 491 | elif isinstance(obj, int): 492 | # 1s and 0s don't get special types in arrays, trying to use them will confuse the game with array size. 493 | if (obj == 0 or obj == 1) and inTypedArray == False: 494 | header.types += currentType.to_bytes(1) 495 | else: 496 | currentIntegerType = subType 497 | if inTypedArray == False: 498 | currentIntegerType = currentType 499 | header.types += currentType.to_bytes(1) 500 | 501 | if currentIntegerType == KVType.INT64 or currentIntegerType == KVType.UINT64: 502 | header.doubles.append(obj) 503 | header.countOfEightByteValues += 1 504 | elif currentIntegerType == KVType.INT32 or currentIntegerType == KVType.UINT32: 505 | data += obj.to_bytes(4, "little", signed=True if obj < 0 else False) 506 | header.countOfIntegers += 1 507 | elif isinstance(obj, float): 508 | if (obj == 0.0 or obj == 1.0) and inTypedArray == False: 509 | header.types += currentType.to_bytes(1) 510 | else: 511 | if inTypedArray == False: 512 | header.types += currentType.to_bytes(1) 513 | header.doubles.append(obj) 514 | header.countOfEightByteValues += 1 515 | elif obj is None: 516 | header.types += currentType.to_bytes(1) 517 | else: 518 | print("unhandled type detected: " + type(obj).__name__) 519 | return data 520 | 521 | @dataclass 522 | class AssetInfo: 523 | version: int 524 | headerVersion: int 525 | blocks: list[FileBlock] # will not contain data, only type and name. 526 | 527 | def readRERLTextFile(content: str) -> list[tuple[int, str]]: 528 | entries = [] 529 | currentLine = 0 530 | try: 531 | for idx, line in enumerate(content.splitlines()): 532 | currentLine = idx + 1 533 | line = line.strip() 534 | if not line: 535 | continue 536 | parts = line.split(maxsplit=1) 537 | if len(parts) == 2: 538 | id = int(parts[0]) 539 | if id < 0: 540 | raise FileFormattingError(f"RERL: ID must be a positive integer", currentLine) 541 | asset = parts[1] 542 | entries.append((id, asset)) 543 | else: 544 | raise FileFormattingError(f"RERL: Invalid line format (expected )", currentLine) 545 | except FileFormattingError as e: 546 | raise e 547 | except ValueError as e: # catch int conversion error 548 | raise FileFormattingError(f"RERL: First value in a line must be an integer", currentLine) 549 | return entries 550 | 551 | def readBytesFromFile(file: Path | str, type: str) -> bytes: 552 | try: 553 | fileData: bytes = None 554 | if type == "kv3" or type == "kv3v4" or type == "kv3v3": 555 | fileData = kv3.read(file) 556 | elif type == "text": 557 | with open(file, "r", encoding="utf-8") as f: 558 | fileData = bytes(f.read(), 'utf-8') 559 | elif type == "bin": 560 | with open(file, "rb") as f: 561 | fileData = f.read() 562 | elif type == "rerl": 563 | with open(file, "r") as f: 564 | fileData = readRERLTextFile(f.read()) 565 | else: 566 | raise ValueError("Unsupported file type: " + type) 567 | return fileData 568 | except (kv3.KV3DecodeError, kv3.InvalidKV3Magic, FileNotFoundError, ValueError) as e: 569 | raise AssetReadErrorGeneric(f"{e}", file) 570 | except (FileFormattingError) as e: 571 | raise AssetReadError(f"Failed to read file: {e} at line {e.line}", file) 572 | 573 | # Not the prettiest, we might switch to a library later on. 574 | SUPPORTED_TYPES = ["kv3", "kv3v3", "kv3v4", "text", "bin", "rerl"] 575 | def validateJsonStructure(loadedData): 576 | if loadedData is None: 577 | raise ValueError("empty or invalid.") 578 | if 'info' not in loadedData: 579 | raise ValueError("missing 'info' section.") 580 | if 'version' not in loadedData['info']: 581 | raise ValueError("missing 'version' in 'info' section.") 582 | else: 583 | version = loadedData['info']['version'] 584 | if not isinstance(version, int): 585 | raise ValueError("'version' value must be an integer") 586 | if version < 0 or version > 65535: 587 | raise ValueError("invalid version number.") 588 | # TODO: DRY 589 | if 'headerversion' not in loadedData['info']: 590 | raise ValueError("missing 'headerversion' in 'info' section.") 591 | else: 592 | version = loadedData['info']['headerversion'] 593 | if not isinstance(version, int): 594 | raise ValueError("'headerversion' value must be an integer") 595 | if version < 0 or version > 65535: 596 | raise ValueError("invalid headerversion number.") 597 | 598 | if 'blocks' not in loadedData: 599 | raise ValueError("missing 'blocks' section.") 600 | else: 601 | blocks = loadedData['blocks'] 602 | if not isinstance(blocks, list): 603 | raise ValueError("'blocks' must be a list.") 604 | if len(blocks) == 0: 605 | raise ValueError("empty 'blocks' list") 606 | for idx, block in enumerate(blocks): 607 | if 'type' not in block: 608 | raise ValueError("missing 'type' key in block no. " + str(idx+1)) 609 | if not isinstance(block['type'], str): 610 | raise ValueError("'type' must be a string, in block no. " + str(idx+1)) 611 | if block['type'] not in SUPPORTED_TYPES: 612 | raise ValueError(f"'type' must be in: {SUPPORTED_TYPES}, in block no. " + str(idx+1)) 613 | if 'name' not in block: 614 | raise ValueError("missing 'name' key in block no. " + str(idx+1)) 615 | if not isinstance(block['name'], str): 616 | raise ValueError("'name' must be a string, in block no. " + str(idx+1)) 617 | if len(block['name']) != 4: 618 | raise ValueError("'name' must be a 4 character string, in block no. " + str(idx+1)) 619 | if 'file' not in block: 620 | raise ValueError("missing 'file' key in block no. " + str(idx+1)) 621 | if not isinstance(block['file'], str): 622 | raise ValueError("'file' must be a string, in block no. " + str(idx+1)) 623 | 624 | def parseJsonStructure(data: str, sourcePath: Path) -> AssetInfo: 625 | currentBlock = 1 # for error messages 626 | try: 627 | validateJsonStructure(data) # will raise errors if something is wrong. 628 | version = data['info']['version'] 629 | headerVersion = data['info']['headerversion'] 630 | blocks = [] 631 | 632 | for block in data['blocks']: 633 | block['type'] = block['type'].lower() 634 | fileData = None 635 | # search relative to the JSON file 636 | fullPath = (sourcePath / Path(block['file'])).resolve() 637 | fileData = readBytesFromFile(fullPath, block['type']) 638 | blocks.append(FileBlock(data=fileData, type=block['type'], name=block['name'], dataProcessed=False)) 639 | currentBlock += 1 640 | return AssetInfo(version, headerVersion, blocks) 641 | except FileNotFoundError as e: 642 | raise FileNotFoundError(f"Failed to open file defined in JSON block {str(currentBlock)}: {e}") 643 | except json.JSONDecodeError as e: 644 | raise json.JSONDecodeError("Failed to parse JSON structure file: "+str(e)) 645 | except ValueError as e: 646 | raise ValueError("JSON structure file " + str(e)) 647 | except (AssetReadError, AssetReadErrorGeneric) as e: 648 | raise e 649 | 650 | assetPresetInfo = { 651 | "vpulse": AssetInfo(version=0, headerVersion=12, blocks=[ 652 | FileBlock(type="kv3", name="RED2"), 653 | FileBlock(type="kv3", name="DATA") 654 | ]), 655 | "vrr": AssetInfo(version=9, headerVersion=12, blocks=[ 656 | FileBlock(type="kv3", name="RED2"), 657 | FileBlock(type="kv3", name="DATA") 658 | ]), 659 | "cs2vanmgrph": AssetInfo(version=0, headerVersion=12, blocks=[ 660 | FileBlock(type="kv3", name="RED2"), 661 | FileBlock(type="kv3", name="DATA") 662 | ]), 663 | "smartprop": AssetInfo(version=0, headerVersion=12, blocks=[ 664 | FileBlock(type="kv3v3", name="RED2"), 665 | FileBlock(type="kv3v3", name="DATA") 666 | ]), 667 | "vents": AssetInfo(version=0, headerVersion=12, blocks=[ 668 | FileBlock(type="kv3", name="RED2"), 669 | FileBlock(type="kv3", name="DATA") 670 | ]), 671 | } 672 | # This section should probably be redone and reuse pre-defined JSONs as templates. 673 | def buildAssetFromPreset(preset: str, files: list[str]) -> bytes: 674 | if preset not in assetPresetInfo: 675 | raise ValueError("Unsupported preset: " + preset) 676 | requiredFileCount = len(assetPresetInfo[preset].blocks) 677 | try: 678 | if files is None or len(files) != requiredFileCount: 679 | raise ValueError(f"Preset '{preset}' requires -f flag with {requiredFileCount} files.") 680 | assetInfoAndData = deepcopy(assetPresetInfo[preset]) 681 | for idx, block in enumerate(assetInfoAndData.blocks): 682 | fullPath = Path(files[idx]).resolve() 683 | block.data = readBytesFromFile(fullPath, block.type) 684 | return buildFileData(assetInfoAndData.version, assetInfoAndData.headerVersion, assetInfoAndData.blocks) 685 | except (kv3.KV3DecodeError, ValueError, AssetReadError, AssetReadErrorGeneric) as e: 686 | raise e 687 | except FileNotFoundError as e: 688 | raise FileNotFoundError(f"One of the specified files doesn't exist: {e}") 689 | 690 | def editAssetFile(file: Path | str, replacementData: list[FileBlock]) -> AssetInfo: 691 | try: 692 | assetInfo = readAssetFile(file, True) 693 | for idx, block in enumerate(assetInfo.blocks): 694 | if block.name == replacementData[idx].name: 695 | block.data = replacementData[idx].data 696 | return assetInfo 697 | except FileNotFoundError as e: 698 | raise FileNotFoundError(f"Failed to open file: {e}") 699 | 700 | cachedReadData: bytes = b'' 701 | def getFileType(file, size) -> str: 702 | # first of all we can just easily check if it's a kv3 file... 703 | startPos = file.tell() 704 | if(size >= 4): 705 | magic = struct.unpack(" AssetInfo: 721 | try: 722 | assetInfo: AssetInfo = AssetInfo(0, 0, []) 723 | with open(file, "rb") as f: 724 | fileSize = struct.unpack(" int: 762 | userBlockIndex = -1 # -1 means that user didn't provide the index, we may have to warn in this case. 763 | if(len(blockStr) > 4): 764 | # try to extract the block index 765 | try: 766 | userBlockIndex = int(blockStr[4:]) 767 | if userBlockIndex < 0: 768 | raise ValueError("Invalid block index provided.") 769 | blockStr = blockStr[:4] 770 | except ValueError as e: 771 | raise ValueError(f"Invalid block name syntax provided: '{blockStr}' a number was expected after the 4 letter block name.") 772 | blockIdx: int = -1 773 | matchCount = 0 774 | for currIdx, block in enumerate(assetInfo.blocks): 775 | if block.name != blockStr: 776 | continue 777 | if userBlockIndex >= 0: 778 | if userBlockIndex == matchCount: 779 | blockIdx = currIdx 780 | break 781 | else: 782 | blockIdx = currIdx 783 | matchCount += 1 784 | if matchCount > 1 and userBlockIndex < 0: 785 | raise ValueError(f"Block {blockStr} exists multiple times, an index number must be provided after the name to target a specific block\n" 786 | f"Example: {blockStr}0 to target the first one {blockStr}1 for second one, and so on.") 787 | if blockIdx == -1: 788 | raise ValueError(f"Block {blockStr}" + (f" (idx={userBlockIndex})" if userBlockIndex > 0 else "") + " was not found in the input file.") 789 | printDebug("matched input block index: " + str(blockIdx)) 790 | return blockIdx 791 | 792 | def tryGetGameDirectoryFromContent(path: Path) -> Path | None: 793 | if "content" not in path.parts: 794 | return None 795 | 796 | contentIdx = path.parts.index("content") 797 | if contentIdx + 1 >= len(path.parts): # if there's not another folder after the content one 798 | return None 799 | 800 | partList = list(path.parts) 801 | addonName = partList[contentIdx + 1] 802 | reducedDir = partList[:contentIdx + 1] 803 | reducedDir[contentIdx] = "game" 804 | gameDir = Path(*reducedDir, addonName) 805 | if not gameDir.exists(): 806 | return None 807 | # if valid game directory exists then resolve the full path. 808 | partList[contentIdx] = "game" 809 | fullPath = Path(*partList) 810 | fullPath.mkdir(parents=True, exist_ok=True) 811 | return fullPath 812 | 813 | 814 | g_isVerbose = False 815 | def printDebug(msg): 816 | if g_isVerbose: 817 | print(msg) 818 | 819 | if __name__ == "__main__": 820 | example = '''example: 821 | 822 | %(prog)s -s pulse_schema.json -o output.vpulse_c 823 | %(prog)s -p vrr -f vrr_redi.kv3 vrr_data.kv3 -o output.vrr_c''' 824 | parser = argparse.ArgumentParser(description="Tool to assemble Source 2 assets manually.", epilog=example, 825 | formatter_class=argparse.RawDescriptionHelpFormatter) 826 | parser.add_argument("-v", "--verbose", help="Enable verbose output", action="store_true") 827 | input_group = parser.add_mutually_exclusive_group(required=True) 828 | input_group.add_argument("-b", "--base", 829 | help="Use a compiled file as a base for the stucture of the file to compile", 830 | type=str, metavar="") 831 | input_group.add_argument("-s", "--schema", 832 | help="Use a JSON file with the definition of the file structure to compile (see README for an example)", 833 | type=str, metavar="") 834 | input_group.add_argument("-p", "--preset", 835 | help="Use a preset for the file structure, supported presets: " + ', '.join(list(assetPresetInfo.keys())), 836 | type=str, metavar="") 837 | input_group.add_argument("-e", "--edit", 838 | help="Edit an existing asset file, requires -f flag with the same amount of files as the base file.", 839 | type=str, nargs="+", metavar=" ...") 840 | parser.add_argument("-f", "--files", 841 | help="List of files to use, only to be used with -b or -p, amount of files depends on the structure of the base file/preset that was specified", 842 | type=str, nargs="+", metavar=" ...") 843 | parser.add_argument("-o", "--output", 844 | help="Output file name or path", 845 | type=str, metavar="", required=True) 846 | 847 | args = parser.parse_args() 848 | if args.verbose: 849 | g_isVerbose = True 850 | binaryData = None 851 | try: 852 | if args.schema is not None: # we are using a schema JSON file 853 | f = open(args.schema, "r") 854 | data = json.load(f) 855 | f.close() 856 | structure = parseJsonStructure(data, Path(args.schema).parents[0]) 857 | printDebug(f"Using schema file: {args.schema}") 858 | binaryData = buildFileData(structure.version, structure.headerVersion, structure.blocks) 859 | elif args.preset is not None: 860 | if args.preset.lower() not in list(assetPresetInfo.keys()): 861 | print("Unsupported preset: "+args.preset) 862 | sys.exit(1) 863 | printDebug(f"Using preset: {args.preset}") 864 | binaryData = buildAssetFromPreset(args.preset, args.files) 865 | elif args.base is not None: 866 | if(args.base.endswith("_c") == False): 867 | print("--base argument requires a compiled asset file.") 868 | sys.exit(1) 869 | assetInfo = readAssetFile(args.base) 870 | if len(assetInfo.blocks) != len(args.files): 871 | print(f"Amount of files provided ({len(args.files)}) doesn't match the amount of blocks in the input file ({len(assetInfo.blocks)}).") 872 | sys.exit(1) 873 | for idx, file in enumerate(args.files): 874 | fullPath = Path(file).resolve() 875 | assetInfo.blocks[idx].data = readBytesFromFile(fullPath, assetInfo.blocks[idx].type) 876 | binaryData = buildFileData(assetInfo.version, assetInfo.headerVersion, assetInfo.blocks) 877 | elif args.edit is not None: 878 | if(args.edit[0].endswith("_c") == False): 879 | print("--edit argument requires a compiled asset file.") 880 | sys.exit(1) 881 | assetInfo: AssetInfo = readAssetFile(args.edit[0], True) 882 | maxBlocks: int = len(args.edit) - 1 883 | for idx, file in enumerate(args.files): 884 | currBlock = args.edit[idx+1] 885 | fullPath = Path(file).resolve() 886 | blockIdx = matchBlockIndexFromString(assetInfo, currBlock) 887 | assetInfo.blocks[blockIdx].data = readBytesFromFile(fullPath, assetInfo.blocks[blockIdx].type) 888 | assetInfo.blocks[blockIdx].dataProcessed = False # we need to reprocess the data. 889 | binaryData = buildFileData(assetInfo.version, assetInfo.headerVersion, assetInfo.blocks) 890 | else: 891 | print("One of the following flags is required to compile an asset: -s, -p, -b, -e Use -h for help.") 892 | sys.exit(0) 893 | except (FileNotFoundError, ValueError) as e: # let's not handle json and kv3 errors, it might be useful to get a full call stack. 894 | print("ERROR: " + str(e) + "\nAsset was not processed.") 895 | sys.exit(1) 896 | except AssetReadErrorGeneric as e: 897 | print(f"ERROR: Failed to read input file \"{e.filePath}\":\n\t {e}") 898 | print("It is possible that the file does not match the block data type.") 899 | sys.exit(1) 900 | except AssetReadError as e: 901 | print(f"ERROR: {e}\n...in file {e.filePath}") 902 | sys.exit(1) 903 | try: 904 | outFile: str = "" 905 | # we will check if any path was provided (even './'), if not, we will try to automatically grab the game directory, and use the provided filename. 906 | # otherwise we will use the full provided path for the output. 907 | fullPath = Path(args.output) 908 | if args.output == fullPath.as_posix(): 909 | outDir = tryGetGameDirectoryFromContent(Path(os.getcwd())) 910 | # if only filename given, but not in a valid content dir, then output to CWD 911 | if(outDir is None): 912 | outFile = Path(os.getcwd()) / args.output 913 | else: 914 | outFile = outDir / args.output 915 | else: 916 | outFile = args.output 917 | with open(outFile, "wb") as f: 918 | print(f"Writing output file: {outFile}") 919 | f.write(binaryData) 920 | except Exception as e: 921 | print("Failed to write output file: " + str(e)) 922 | sys.exit(1) -------------------------------------------------------------------------------- /examples/pulse/pulse_struct.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "headerversion": 12, 4 | "version": 0 5 | }, 6 | "blocks": [ 7 | { 8 | "type": "kv3", 9 | "name": "RED2", 10 | "file": "eventhandler_redi.kv3" 11 | }, 12 | { 13 | "type": "kv3", 14 | "name": "DATA", 15 | "file": "eventhandler.kv3" 16 | } 17 | ] 18 | } -------------------------------------------------------------------------------- /examples/pulse/pulsesample.vpulse: -------------------------------------------------------------------------------- 1 | 2 | { 3 | m_Cells = 4 | [ 5 | 6 | { 7 | _class = "CPulseCell_Inflow_Method" 8 | m_nEditorNodeID = -1 9 | m_EntryChunk = 0 10 | m_RegisterMap = 11 | { 12 | m_Inparams = null 13 | m_Outparams = 14 | { 15 | arg1 = 0 16 | } 17 | } 18 | m_MethodName = "Message" 19 | m_Description = "" 20 | m_bIsPublic = true 21 | m_ReturnType = "PVAL_INVALID" 22 | m_Args = 23 | [ 24 | 25 | { 26 | m_Name = "arg1" 27 | m_Description = "" 28 | m_Type = "PVAL_STRING" 29 | }, 30 | ] 31 | }, 32 | 33 | { 34 | _class = "CPulseCell_Value_FindEntByName" 35 | m_nEditorNodeID = -1 36 | m_EntityType = "prop_dynamic" 37 | }, 38 | ] 39 | m_DomainIdentifier = "ServerPointEntity" 40 | m_ParentMapName = "maps/test.vmap" 41 | m_ParentXmlName = "" 42 | m_vecGameBlackboards = 43 | [ 44 | ] 45 | m_BlackboardReferences = 46 | [ 47 | ] 48 | m_Chunks = 49 | [ 50 | 51 | { 52 | m_Instructions = 53 | [ 54 | 55 | { 56 | m_nCode = "GET_DOMAIN_VALUE" 57 | m_nVar = -1 58 | m_nReg0 = 1 59 | m_nReg1 = -1 60 | m_nReg2 = -1 61 | m_nInvokeBindingIndex = -1 62 | m_nChunk = -1 63 | m_nDestInstruction = 0 64 | m_nCallInfoIndex = -1 65 | m_nConstIdx = -1 66 | m_nDomainValueIdx = 0 67 | m_nBlackboardReferenceIdx = -1 68 | }, 69 | 70 | { 71 | m_nCode = "CELL_INVOKE" 72 | m_nVar = -1 73 | m_nReg0 = -1 74 | m_nReg1 = -1 75 | m_nReg2 = -1 76 | m_nInvokeBindingIndex = 0 77 | m_nChunk = -1 78 | m_nDestInstruction = 0 79 | m_nCallInfoIndex = -1 80 | m_nConstIdx = -1 81 | m_nDomainValueIdx = -1 82 | m_nBlackboardReferenceIdx = -1 83 | }, 84 | 85 | { 86 | m_nCode = "GET_CONST" 87 | m_nVar = -1 88 | m_nReg0 = 3 89 | m_nReg1 = -1 90 | m_nReg2 = -1 91 | m_nInvokeBindingIndex = -1 92 | m_nChunk = -1 93 | m_nDestInstruction = 0 94 | m_nCallInfoIndex = -1 95 | m_nConstIdx = 0 96 | m_nDomainValueIdx = -1 97 | m_nBlackboardReferenceIdx = -1 98 | }, 99 | 100 | { 101 | m_nCode = "GET_CONST" 102 | m_nVar = -1 103 | m_nReg0 = 4 104 | m_nReg1 = -1 105 | m_nReg2 = -1 106 | m_nInvokeBindingIndex = -1 107 | m_nChunk = -1 108 | m_nDestInstruction = 0 109 | m_nCallInfoIndex = -1 110 | m_nConstIdx = 1 111 | m_nDomainValueIdx = -1 112 | m_nBlackboardReferenceIdx = -1 113 | }, 114 | 115 | { 116 | m_nCode = "GET_CONST" 117 | m_nVar = -1 118 | m_nReg0 = 5 119 | m_nReg1 = -1 120 | m_nReg2 = -1 121 | m_nInvokeBindingIndex = -1 122 | m_nChunk = -1 123 | m_nDestInstruction = 0 124 | m_nCallInfoIndex = -1 125 | m_nConstIdx = 2 126 | m_nDomainValueIdx = -1 127 | m_nBlackboardReferenceIdx = -1 128 | }, 129 | 130 | { 131 | m_nCode = "GET_CONST" 132 | m_nVar = -1 133 | m_nReg0 = 6 134 | m_nReg1 = -1 135 | m_nReg2 = -1 136 | m_nInvokeBindingIndex = -1 137 | m_nChunk = -1 138 | m_nDestInstruction = 0 139 | m_nCallInfoIndex = -1 140 | m_nConstIdx = 3 141 | m_nDomainValueIdx = -1 142 | m_nBlackboardReferenceIdx = -1 143 | }, 144 | 145 | { 146 | m_nCode = "GET_CONST" 147 | m_nVar = -1 148 | m_nReg0 = 7 149 | m_nReg1 = -1 150 | m_nReg2 = -1 151 | m_nInvokeBindingIndex = -1 152 | m_nChunk = -1 153 | m_nDestInstruction = 0 154 | m_nCallInfoIndex = -1 155 | m_nConstIdx = 4 156 | m_nDomainValueIdx = -1 157 | m_nBlackboardReferenceIdx = -1 158 | }, 159 | 160 | { 161 | m_nCode = "GET_VAR" 162 | m_nVar = 0 163 | m_nReg0 = 8 164 | m_nReg1 = -1 165 | m_nReg2 = -1 166 | m_nInvokeBindingIndex = -1 167 | m_nChunk = -1 168 | m_nDestInstruction = 0 169 | m_nCallInfoIndex = -1 170 | m_nConstIdx = -1 171 | m_nDomainValueIdx = -1 172 | m_nBlackboardReferenceIdx = -1 173 | }, 174 | 175 | { 176 | m_nCode = "GET_CONST" 177 | m_nVar = -1 178 | m_nReg0 = 9 179 | m_nReg1 = -1 180 | m_nReg2 = -1 181 | m_nInvokeBindingIndex = -1 182 | m_nChunk = -1 183 | m_nDestInstruction = 0 184 | m_nCallInfoIndex = -1 185 | m_nConstIdx = 6 186 | m_nDomainValueIdx = -1 187 | m_nBlackboardReferenceIdx = -1 188 | }, 189 | 190 | { 191 | m_nCode = "LIBRARY_INVOKE" 192 | m_nVar = -1 193 | m_nReg0 = -1 194 | m_nReg1 = -1 195 | m_nReg2 = -1 196 | m_nInvokeBindingIndex = 1 197 | m_nChunk = -1 198 | m_nDestInstruction = 0 199 | m_nCallInfoIndex = -1 200 | m_nConstIdx = -1 201 | m_nDomainValueIdx = -1 202 | m_nBlackboardReferenceIdx = -1 203 | }, 204 | ] 205 | m_Registers = 206 | [ 207 | 208 | { 209 | m_nReg = 0 210 | m_Type = "PVAL_STRING" 211 | m_OriginName = "0:null" 212 | m_nWrittenByInstruction = 0 213 | m_nLastReadByInstruction = -1 214 | }, 215 | 216 | { 217 | m_nReg = 1 218 | m_Type = "PVAL_ENTITY_NAME" 219 | m_OriginName = "0:null" 220 | m_nWrittenByInstruction = 0 221 | m_nLastReadByInstruction = -1 222 | }, 223 | 224 | { 225 | m_nReg = 2 226 | m_Type = "PVAL_EHANDLE:prop_dynamic" 227 | m_OriginName = "0:null" 228 | m_nWrittenByInstruction = 1 229 | m_nLastReadByInstruction = -1 230 | }, 231 | 232 | { 233 | m_nReg = 3 234 | m_Type = "PVAL_INT" 235 | m_OriginName = "0:null" 236 | m_nWrittenByInstruction = 2 237 | m_nLastReadByInstruction = -1 238 | }, 239 | 240 | { 241 | m_nReg = 4 242 | m_Type = "PVAL_FLOAT" 243 | m_OriginName = "0:null" 244 | m_nWrittenByInstruction = 3 245 | m_nLastReadByInstruction = -1 246 | }, 247 | 248 | { 249 | m_nReg = 5 250 | m_Type = "PVAL_FLOAT" 251 | m_OriginName = "0:null" 252 | m_nWrittenByInstruction = 4 253 | m_nLastReadByInstruction = -1 254 | }, 255 | 256 | { 257 | m_nReg = 6 258 | m_Type = "PVAL_COLOR_RGB" 259 | m_OriginName = "0:null" 260 | m_nWrittenByInstruction = 5 261 | m_nLastReadByInstruction = -1 262 | }, 263 | 264 | { 265 | m_nReg = 7 266 | m_Type = "PVAL_FLOAT" 267 | m_OriginName = "0:null" 268 | m_nWrittenByInstruction = 6 269 | m_nLastReadByInstruction = -1 270 | }, 271 | 272 | { 273 | m_nReg = 8 274 | m_Type = "PVAL_FLOAT" 275 | m_OriginName = "0:null" 276 | m_nWrittenByInstruction = 7 277 | m_nLastReadByInstruction = -1 278 | }, 279 | 280 | { 281 | m_nReg = 9 282 | m_Type = "PVAL_BOOL" 283 | m_OriginName = "0:null" 284 | m_nWrittenByInstruction = 8 285 | m_nLastReadByInstruction = -1 286 | }, 287 | ] 288 | m_InstructionEditorIDs = 289 | [ 290 | -1, 291 | -1, 292 | -1, 293 | -1, 294 | -1, 295 | -1, 296 | -1, 297 | -1, 298 | -1, 299 | -1, 300 | ] 301 | }, 302 | ] 303 | m_DomainValues = 304 | [ 305 | 306 | { 307 | m_nType = "ENTITY_NAME" 308 | m_Value = "randomprop" 309 | m_ExpectedRuntimeType = "" 310 | }, 311 | ] 312 | m_Vars = 313 | [ 314 | 315 | { 316 | m_Name = "text_size" 317 | m_Description = "Size of the text" 318 | m_Type = "PVAL_FLOAT" 319 | m_DefaultValue = 0.000000 320 | m_bIsPublic = true 321 | m_bIsObservable = false 322 | m_nEditorNodeID = -1 323 | }, 324 | ] 325 | m_Constants = 326 | [ 327 | 328 | { 329 | m_Type = "PVAL_INT" 330 | m_Value = 0 331 | }, 332 | 333 | { 334 | m_Type = "PVAL_FLOAT" 335 | m_Value = 5.000000 336 | }, 337 | 338 | { 339 | m_Type = "PVAL_FLOAT" 340 | m_Value = 20.000000 341 | }, 342 | 343 | { 344 | m_Type = "PVAL_COLOR_RGB" 345 | m_Value = 346 | [ 347 | 255, 348 | 0, 349 | 0, 350 | ] 351 | }, 352 | 353 | { 354 | m_Type = "PVAL_FLOAT" 355 | m_Value = 1.000000 356 | }, 357 | 358 | { 359 | m_Type = "PVAL_FLOAT" 360 | m_Value = 10.000000 361 | }, 362 | 363 | { 364 | m_Type = "PVAL_BOOL" 365 | m_Value = false 366 | }, 367 | ] 368 | m_PublicOutputs = 369 | [ 370 | ] 371 | m_OutputConnections = 372 | [ 373 | ] 374 | m_InvokeBindings = 375 | [ 376 | 377 | { 378 | m_RegisterMap = 379 | { 380 | m_Inparams = 381 | { 382 | pName = 1 383 | } 384 | m_Outparams = 385 | { 386 | retval = 2 387 | } 388 | } 389 | m_FuncName = "Eval" 390 | m_nCellIndex = 1 391 | m_nSrcChunk = 0 392 | m_nSrcInstruction = 1 393 | }, 394 | 395 | { 396 | m_RegisterMap = 397 | { 398 | m_Inparams = 399 | { 400 | hEntity = 2 401 | nTextOffset = 3 402 | pMessage = 0 403 | flDuration = 4 404 | flVerticalOffset = 5 405 | bAttached = 9 406 | color = 6 407 | flAlpha = 7 408 | flScale = 8 409 | } 410 | m_Outparams = null 411 | } 412 | m_FuncName = "CPulseServerFuncs!DebugWorldText" 413 | m_nCellIndex = -1 414 | m_nSrcChunk = -1 415 | m_nSrcInstruction = -1 416 | }, 417 | ] 418 | m_CallInfos = 419 | [ 420 | ] 421 | } -------------------------------------------------------------------------------- /examples/pulse/pulsesample_redi.kv3: -------------------------------------------------------------------------------- 1 | 2 | { 3 | m_InputDependencies = 4 | [ 5 | 6 | { 7 | m_RelativeFilename = "pulse/maingraph.vpulse" 8 | m_SearchPath = "csgo_addons/test" 9 | m_nFileCRC = 1936901886 10 | m_bOptional = false 11 | m_bFileExists = true 12 | m_bIsGameFile = false 13 | }, 14 | ] 15 | m_AdditionalInputDependencies = 16 | [ 17 | ] 18 | m_ArgumentDependencies = 19 | [ 20 | 21 | { 22 | m_ParameterName = "___OverrideInputData___" 23 | m_ParameterType = "BinaryBlobArg" 24 | m_nFingerprint = 0 25 | m_nFingerprintDefault = 0 26 | }, 27 | ] 28 | m_SpecialDependencies = 29 | [ 30 | 31 | { 32 | m_String = "KV3 Compiler Version" 33 | m_CompilerIdentifier = "CompilePulseGraphDef" 34 | m_nFingerprint = 2 35 | m_nUserData = 0 36 | }, 37 | 38 | { 39 | m_String = "PulseGraphDef Compiler Version" 40 | m_CompilerIdentifier = "CompilePulseGraphDef" 41 | m_nFingerprint = 13 42 | m_nUserData = 0 43 | }, 44 | ] 45 | m_AdditionalRelatedFiles = 46 | [ 47 | ] 48 | m_ChildResourceList = 49 | [ 50 | ] 51 | m_WeakReferenceList = 52 | [ 53 | ] 54 | m_SearchableUserData = 55 | { 56 | pulse_domain = "ServerPointEntity" 57 | IsChildResource = 0 58 | } 59 | m_SubassetReferences = null 60 | m_SubassetDefinitions = null 61 | } -------------------------------------------------------------------------------- /examples/responserules/RED2_responserule.kv3: -------------------------------------------------------------------------------- 1 | 2 | { 3 | m_InputDependencies = 4 | [ 5 | { 6 | m_RelativeFilename = "scripts/talker/responserule.vrr" 7 | m_SearchPath = "csgo" 8 | m_nFileCRC = 0 9 | m_bOptional = false 10 | m_bFileExists = true 11 | m_bIsGameFile = false 12 | }, 13 | ] 14 | m_AdditionalInputDependencies = 15 | [ 16 | ] 17 | m_ArgumentDependencies = 18 | [ 19 | 20 | { 21 | m_ParameterName = "___OverrideInputData___" 22 | m_ParameterType = "BinaryBlobArg" 23 | m_nFingerprint = 0 24 | m_nFingerprintDefault = 0 25 | }, 26 | ] 27 | m_SpecialDependencies = 28 | [ 29 | 30 | { 31 | m_String = "Response Rules Version" 32 | m_CompilerIdentifier = "CompileResponseRules" 33 | m_nFingerprint = 9 34 | m_nUserData = 0 35 | }, 36 | ] 37 | m_AdditionalRelatedFiles = 38 | [ 39 | ] 40 | m_ChildResourceList = 41 | [ 42 | ] 43 | m_WeakReferenceList = 44 | [ 45 | ] 46 | m_SearchableUserData = 47 | { 48 | IsChildResource = 0 49 | } 50 | m_SubassetReferences = null 51 | m_SubassetDefinitions = null 52 | } -------------------------------------------------------------------------------- /examples/responserules/responserule.vrr: -------------------------------------------------------------------------------- 1 | 2 | { 3 | m_Includes = 4 | [ 5 | "scripts/talker/shared.vrr", 6 | ] 7 | m_SoundEventScripts = 8 | [ 9 | "soundevents/vo/agents/vo_hero_char.vsndevts", 10 | ] 11 | m_ResponseGroups = 12 | [ 13 | { 14 | m_name = "AffirmativeYesChar" 15 | m_notes = "Radio" 16 | m_responses = 17 | [ 18 | 19 | { 20 | m_type = "SPEAK" 21 | m_value = "char.affirmative01" 22 | }, 23 | 24 | { 25 | m_type = "SPEAK" 26 | m_value = "char.affirmative02" 27 | }, 28 | 29 | { 30 | m_type = "SPEAK" 31 | m_value = "char.affirmative03" 32 | }, 33 | 34 | ] 35 | m_pEmbeddedRule = 36 | { 37 | m_name = "AffirmativeYesChar" 38 | m_Requirements = 39 | [ 40 | "TLK_Affirmative", 41 | "IsChar", 42 | "IsTalkChar", 43 | ] 44 | m_context = "Talkchar:1:1" 45 | m_bApplyContextToWorld = true 46 | } 47 | }, 48 | ] 49 | m_Requirements = 50 | [ 51 | { 52 | m_name = "IsChar" 53 | m_notes = "Win responses" 54 | m_matchKey = "model" 55 | m_matchExpr = "my_char" 56 | m_bRequired = true 57 | }, 58 | ] 59 | m_speakerType = "player" 60 | } -------------------------------------------------------------------------------- /examples/responserules/vrr_struct.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "headerversion": 12, 4 | "version": 9 5 | }, 6 | "blocks": [ 7 | { 8 | "type": "kv3", 9 | "name": "RED2", 10 | "file": "RED2_responserule.kv3" 11 | }, 12 | { 13 | "type": "kv3", 14 | "name": "DATA", 15 | "file": "responserule.kv3" 16 | } 17 | ] 18 | } -------------------------------------------------------------------------------- /examples/typescript/sourcets.vts: -------------------------------------------------------------------------------- 1 | import { Instance } from "serverpointentity"; 2 | 3 | Instance.InitialActivate(() => { 4 | Instance.Msg("hello there!"); 5 | Instance.Msg(Instance.DebugScreenText.toString()) 6 | Instance.DebugScreenText("Test text hi there!", 1500.0, 10.0, 40, 100.0, "#ff0000"); 7 | }); 8 | 9 | const printObj = function(_obj) 10 | { 11 | let result = []; 12 | let obj = _obj; 13 | do { 14 | result.push(...Object.getOwnPropertyNames(obj)); 15 | } while (obj = Object.getPrototypeOf(obj)); 16 | Instance.Msg(result); 17 | } 18 | 19 | Instance.PublicMethod("printInfo", function() { 20 | Instance.msg("printInfo called"); 21 | Instance.Msg(Instance.__proto__); 22 | let pawn = Instance.GetPlayerPawn(0); 23 | let controller = pawn.GetCurrentController(); 24 | printObj(controller); 25 | let wep = pawn.GetActiveWeapon(); 26 | printObj(wep); 27 | }); -------------------------------------------------------------------------------- /examples/typescript/sourcets_redi.kv3: -------------------------------------------------------------------------------- 1 | 2 | { 3 | m_InputDependencies = 4 | [ 5 | 6 | { 7 | m_RelativeFilename = "source_ts/sourcetest.ts" 8 | m_SearchPath = "csgo" 9 | m_nFileCRC = 0 10 | m_bOptional = true 11 | m_bFileExists = false 12 | m_bIsGameFile = false 13 | }, 14 | 15 | { 16 | m_RelativeFilename = "source_ts/sourcetest.vts" 17 | m_SearchPath = "csgo" 18 | m_nFileCRC = 0 19 | m_bOptional = true 20 | m_bFileExists = true 21 | m_bIsGameFile = false 22 | }, 23 | ] 24 | m_AdditionalInputDependencies = 25 | [ 26 | ] 27 | m_ArgumentDependencies = 28 | [ 29 | 30 | { 31 | m_ParameterName = "___OverrideInputData___" 32 | m_ParameterType = "BinaryBlobArg" 33 | m_nFingerprint = 0 34 | m_nFingerprintDefault = 0 35 | }, 36 | ] 37 | m_SpecialDependencies = 38 | [ 39 | 40 | { 41 | m_String = "Panorama Preprocessor Presence/Version" 42 | m_CompilerIdentifier = "CompileTypeScript" 43 | m_nFingerprint = 0 44 | m_nUserData = 0 45 | }, 46 | 47 | { 48 | m_String = "TypeScript Compiler Version" 49 | m_CompilerIdentifier = "CompileTypeScript" 50 | m_nFingerprint = 3 51 | m_nUserData = 0 52 | }, 53 | ] 54 | m_AdditionalRelatedFiles = 55 | [ 56 | ] 57 | m_ChildResourceList = 58 | [ 59 | ] 60 | m_WeakReferenceList = 61 | [ 62 | ] 63 | m_SearchableUserData = 64 | { 65 | IsChildResource = 0 66 | } 67 | m_SubassetReferences = null 68 | m_SubassetDefinitions = null 69 | } -------------------------------------------------------------------------------- /examples/typescript/sourcets_stat.kv3: -------------------------------------------------------------------------------- 1 | 2 | { 3 | publicMethods = 4 | { 5 | printInfo = "none" 6 | } 7 | } -------------------------------------------------------------------------------- /examples/typescript/typescript_struct.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "headerversion": 12, 4 | "version": 2 5 | }, 6 | "blocks": [ 7 | { 8 | "type": "kv3", 9 | "name": "RED2", 10 | "file": "sourcets_redi.kv3" 11 | }, 12 | { 13 | "type": "text", 14 | "name": "DATA", 15 | "file": "sourcets.vts" 16 | }, 17 | { 18 | "type": "kv3", 19 | "name": "STAT", 20 | "file": "sourcets_stat.kv3" 21 | } 22 | ] 23 | } -------------------------------------------------------------------------------- /img/asset_hex.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LionDoge/source2-asset-assembler/d62622ffeb480c83e3b181d65eae9894da2d24b6/img/asset_hex.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | keyvalues3==0.1 2 | lz4==4.3.3 3 | parsimonious==0.10.0 4 | regex==2024.7.24 -------------------------------------------------------------------------------- /tests/files/asset1.vts_c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LionDoge/source2-asset-assembler/d62622ffeb480c83e3b181d65eae9894da2d24b6/tests/files/asset1.vts_c -------------------------------------------------------------------------------- /tests/files/asset2.vmat_c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LionDoge/source2-asset-assembler/d62622ffeb480c83e3b181d65eae9894da2d24b6/tests/files/asset2.vmat_c -------------------------------------------------------------------------------- /tests/files/asset_minimal.vts_c: -------------------------------------------------------------------------------- 1 | d RED2,DATA0STAT43VKdataaa3VK -------------------------------------------------------------------------------- /tests/files/rerlblock.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LionDoge/source2-asset-assembler/d62622ffeb480c83e3b181d65eae9894da2d24b6/tests/files/rerlblock.bin -------------------------------------------------------------------------------- /tests/files/rerltest.txt: -------------------------------------------------------------------------------- 1 | 4028879694858690263 materials/default/default_ao_tga_559f1ac6.vtex 2 | 3981026097612531816 materials/default/default_metal_tga_af1d7118.vtex 3 | 16991945667032608603 materials/default/default_normal_tga_4c6e7391.vtex -------------------------------------------------------------------------------- /tests/files/samples/data.kv3: -------------------------------------------------------------------------------- 1 | 2 | { 3 | m_DomainIdentifier = "ServerPointEntity" 4 | m_ParentMapName = "maps/fronttest2.vmap" 5 | m_ParentXmlName = "" 6 | m_vecGameBlackboards = 7 | [ 8 | ] 9 | m_Chunks = 10 | [ 11 | 12 | { 13 | m_Instructions = 14 | [ 15 | 16 | { 17 | m_nCode = "NOP" 18 | m_nVar = -1 19 | m_nReg0 = -1 20 | m_nReg1 = -1 21 | m_nReg2 = -1 22 | m_nInvokeBindingIndex = -1 23 | m_nChunk = -1 24 | m_nDestInstruction = 0 25 | m_nCallInfoIndex = -1 26 | m_nConstIdx = -1 27 | m_nDomainValueIdx = -1 28 | m_nBlackboardReferenceIdx = -1 29 | }, 30 | 31 | { 32 | m_nCode = "GET_CONST" 33 | m_nVar = -1 34 | m_nReg0 = 0 35 | m_nReg1 = -1 36 | m_nReg2 = -1 37 | m_nInvokeBindingIndex = -1 38 | m_nChunk = -1 39 | m_nDestInstruction = 0 40 | m_nCallInfoIndex = -1 41 | m_nConstIdx = 0 42 | m_nDomainValueIdx = -1 43 | m_nBlackboardReferenceIdx = -1 44 | }, 45 | 46 | { 47 | m_nCode = "GET_CONST" 48 | m_nVar = -1 49 | m_nReg0 = 1 50 | m_nReg1 = -1 51 | m_nReg2 = -1 52 | m_nInvokeBindingIndex = -1 53 | m_nChunk = -1 54 | m_nDestInstruction = 0 55 | m_nCallInfoIndex = -1 56 | m_nConstIdx = 1 57 | m_nDomainValueIdx = -1 58 | m_nBlackboardReferenceIdx = -1 59 | }, 60 | 61 | { 62 | m_nCode = "GET_CONST" 63 | m_nVar = -1 64 | m_nReg0 = 2 65 | m_nReg1 = -1 66 | m_nReg2 = -1 67 | m_nInvokeBindingIndex = -1 68 | m_nChunk = -1 69 | m_nDestInstruction = 0 70 | m_nCallInfoIndex = -1 71 | m_nConstIdx = 2 72 | m_nDomainValueIdx = -1 73 | m_nBlackboardReferenceIdx = -1 74 | }, 75 | 76 | { 77 | m_nCode = "GET_CONST" 78 | m_nVar = -1 79 | m_nReg0 = 7 80 | m_nReg1 = -1 81 | m_nReg2 = -1 82 | m_nInvokeBindingIndex = -1 83 | m_nChunk = -1 84 | m_nDestInstruction = 0 85 | m_nCallInfoIndex = -1 86 | m_nConstIdx = 7 87 | m_nDomainValueIdx = -1 88 | m_nBlackboardReferenceIdx = -1 89 | }, 90 | 91 | { 92 | m_nCode = "GET_CONST" 93 | m_nVar = -1 94 | m_nReg0 = 8 95 | m_nReg1 = -1 96 | m_nReg2 = -1 97 | m_nInvokeBindingIndex = -1 98 | m_nChunk = -1 99 | m_nDestInstruction = 0 100 | m_nCallInfoIndex = -1 101 | m_nConstIdx = 8 102 | m_nDomainValueIdx = -1 103 | m_nBlackboardReferenceIdx = -1 104 | }, 105 | 106 | { 107 | m_nCode = "CELL_INVOKE" 108 | m_nVar = -1 109 | m_nReg0 = 3 110 | m_nReg1 = -1 111 | m_nReg2 = -1 112 | m_nInvokeBindingIndex = 1 113 | m_nChunk = -1 114 | m_nDestInstruction = 0 115 | m_nCallInfoIndex = -1 116 | m_nConstIdx = 3 117 | m_nDomainValueIdx = -1 118 | m_nBlackboardReferenceIdx = -1 119 | }, 120 | 121 | { 122 | m_nCode = "GET_CONST" 123 | m_nVar = -1 124 | m_nReg0 = 4 125 | m_nReg1 = -1 126 | m_nReg2 = -1 127 | m_nInvokeBindingIndex = -1 128 | m_nChunk = -1 129 | m_nDestInstruction = 0 130 | m_nCallInfoIndex = -1 131 | m_nConstIdx = 4 132 | m_nDomainValueIdx = -1 133 | m_nBlackboardReferenceIdx = -1 134 | }, 135 | 136 | { 137 | m_nCode = "GET_CONST" 138 | m_nVar = -1 139 | m_nReg0 = 5 140 | m_nReg1 = -1 141 | m_nReg2 = -1 142 | m_nInvokeBindingIndex = -1 143 | m_nChunk = -1 144 | m_nDestInstruction = 0 145 | m_nCallInfoIndex = -1 146 | m_nConstIdx = 5 147 | m_nDomainValueIdx = -1 148 | m_nBlackboardReferenceIdx = -1 149 | }, 150 | 151 | { 152 | m_nCode = "GET_CONST" 153 | m_nVar = -1 154 | m_nReg0 = 6 155 | m_nReg1 = -1 156 | m_nReg2 = -1 157 | m_nInvokeBindingIndex = -1 158 | m_nChunk = -1 159 | m_nDestInstruction = 0 160 | m_nCallInfoIndex = -1 161 | m_nConstIdx = 6 162 | m_nDomainValueIdx = -1 163 | m_nBlackboardReferenceIdx = -1 164 | }, 165 | 166 | { 167 | m_nCode = "LIBRARY_INVOKE" 168 | m_nVar = -1 169 | m_nReg0 = -1 170 | m_nReg1 = -1 171 | m_nReg2 = -1 172 | m_nInvokeBindingIndex = 0 173 | m_nChunk = -1 174 | m_nDestInstruction = 0 175 | m_nCallInfoIndex = -1 176 | m_nConstIdx = -1 177 | m_nDomainValueIdx = -1 178 | m_nBlackboardReferenceIdx = -1 179 | }, 180 | 181 | { 182 | m_nCode = "RETURN_VALUE" 183 | m_nVar = -1 184 | m_nReg0 = 0 185 | m_nReg1 = -1 186 | m_nReg2 = -1 187 | m_nInvokeBindingIndex = -1 188 | m_nChunk = -1 189 | m_nDestInstruction = 0 190 | m_nCallInfoIndex = -1 191 | m_nConstIdx = -1 192 | m_nDomainValueIdx = -1 193 | m_nBlackboardReferenceIdx = -1 194 | }, 195 | ] 196 | m_Registers = 197 | [ 198 | 199 | { 200 | m_nReg = 0 201 | m_Type = "PVAL_STRING" 202 | m_OriginName = "1:pMessage" 203 | m_nWrittenByInstruction = 1 204 | m_nLastReadByInstruction = -1 205 | }, 206 | 207 | { 208 | m_nReg = 1 209 | m_Type = "PVAL_FLOAT" 210 | m_OriginName = "1:flScreenX" 211 | m_nWrittenByInstruction = 2 212 | m_nLastReadByInstruction = -1 213 | }, 214 | 215 | { 216 | m_nReg = 2 217 | m_Type = "PVAL_FLOAT" 218 | m_OriginName = "1:flScreenY" 219 | m_nWrittenByInstruction = 3 220 | m_nLastReadByInstruction = -1 221 | }, 222 | 223 | { 224 | m_nReg = 3 225 | m_Type = "PVAL_INT" 226 | m_OriginName = "1:nTextOffset" 227 | m_nWrittenByInstruction = 6 228 | m_nLastReadByInstruction = -1 229 | }, 230 | 231 | { 232 | m_nReg = 4 233 | m_Type = "PVAL_FLOAT" 234 | m_OriginName = "1:flDuration" 235 | m_nWrittenByInstruction = 7 236 | m_nLastReadByInstruction = -1 237 | }, 238 | 239 | { 240 | m_nReg = 5 241 | m_Type = "PVAL_VEC3" 242 | m_OriginName = "1:color" 243 | m_nWrittenByInstruction = 8 244 | m_nLastReadByInstruction = -1 245 | }, 246 | 247 | { 248 | m_nReg = 6 249 | m_Type = "PVAL_FLOAT" 250 | m_OriginName = "1:flAlpha" 251 | m_nWrittenByInstruction = 9 252 | m_nLastReadByInstruction = -1 253 | }, 254 | 255 | { 256 | m_nReg = 7 257 | m_Type = "PVAL_FLOAT" 258 | m_OriginName = "1:flAlpha" 259 | m_nWrittenByInstruction = 4 260 | m_nLastReadByInstruction = -1 261 | }, 262 | 263 | { 264 | m_nReg = 8 265 | m_Type = "PVAL_FLOAT" 266 | m_OriginName = "1:flAlpha" 267 | m_nWrittenByInstruction = 5 268 | m_nLastReadByInstruction = -1 269 | }, 270 | ] 271 | m_InstructionEditorIDs = 272 | [ 273 | 1, 274 | -1, 275 | -1, 276 | -1, 277 | -1, 278 | -1, 279 | -1, 280 | -1, 281 | -1, 282 | ] 283 | }, 284 | 285 | { 286 | m_Instructions = 287 | [ 288 | 289 | { 290 | m_nCode = "NOP" 291 | m_nVar = -1 292 | m_nReg0 = -1 293 | m_nReg1 = -1 294 | m_nReg2 = -1 295 | m_nInvokeBindingIndex = -1 296 | m_nChunk = -1 297 | m_nDestInstruction = 0 298 | m_nCallInfoIndex = -1 299 | m_nConstIdx = -1 300 | m_nDomainValueIdx = -1 301 | m_nBlackboardReferenceIdx = -1 302 | }, 303 | 304 | { 305 | m_nCode = "RETURN_VALUE" 306 | m_nVar = -1 307 | m_nReg0 = 0 308 | m_nReg1 = -1 309 | m_nReg2 = -1 310 | m_nInvokeBindingIndex = -1 311 | m_nChunk = -1 312 | m_nDestInstruction = 0 313 | m_nCallInfoIndex = -1 314 | m_nConstIdx = -1 315 | m_nDomainValueIdx = -1 316 | m_nBlackboardReferenceIdx = -1 317 | }, 318 | ] 319 | m_Registers = 320 | [ 321 | 322 | { 323 | m_nReg = 0 324 | m_Type = "PVAL_EHANDLE" 325 | m_OriginName = "1:userid" 326 | m_nWrittenByInstruction = 1 327 | m_nLastReadByInstruction = -1 328 | }, 329 | ] 330 | m_InstructionEditorIDs = 331 | [ 332 | 1, 333 | -1, 334 | ] 335 | }, 336 | ] 337 | m_Vars = 338 | [ 339 | ] 340 | m_Cells = 341 | [ 342 | 343 | { 344 | _class = "CPulseCell_Inflow_Method" 345 | m_nEditorNodeID = 2 346 | m_EntryChunk = 0 347 | m_RegisterMap = 348 | { 349 | m_Inparams = 350 | { 351 | arg1 = 0 352 | } 353 | m_Outparams = 354 | { 355 | arg1 = 0 356 | } 357 | } 358 | m_MethodName = "TriggerCheckPulse" 359 | m_Description = "sample description" 360 | m_bIsPublic = true 361 | m_ReturnType = "PVAL_INVALID" 362 | m_Args = 363 | [ 364 | 365 | { 366 | m_Name = "arg1" 367 | m_Description = "Argument1" 368 | m_Type = "PVAL_STRING" 369 | }, 370 | ] 371 | }, 372 | 373 | { 374 | _class = "CPulseCell_Inflow_EventHandler" 375 | m_nEditorNodeID = 35 376 | m_EntryChunk = 1 377 | m_RegisterMap = 378 | { 379 | m_Inparams = 380 | { 381 | } 382 | m_Outparams = 383 | { 384 | } 385 | } 386 | m_EventName = "player_death" 387 | }, 388 | ] 389 | m_PublicOutputs = 390 | [ 391 | ] 392 | m_InvokeBindings = 393 | [ 394 | 395 | { 396 | m_RegisterMap = 397 | { 398 | m_Inparams = 399 | { 400 | pMessage = 0 401 | flScreenX = 1 402 | flScreenY = 2 403 | nTextOffset = 3 404 | flDuration = 4 405 | color = 5 406 | flAlpha = 6 407 | } 408 | m_Outparams = null 409 | } 410 | m_FuncName = "CPulseServerFuncs!DebugScreenText" 411 | m_nCellIndex = -1 412 | m_nSrcChunk = 0 413 | m_nSrcInstruction = 10 414 | }, 415 | 416 | { 417 | m_RegisterMap = 418 | { 419 | m_Inparams = 420 | { 421 | min = 7 422 | max = 8 423 | } 424 | m_Outparams = 425 | { 426 | retval = 3 427 | } 428 | } 429 | m_FuncName = "CPulseTurtleGraphicsCursor!Turn" 430 | m_nCellIndex = 1 431 | m_nSrcChunk = 0 432 | m_nSrcInstruction = 6 433 | }, 434 | ] 435 | m_CallInfos = 436 | [ 437 | 438 | { 439 | m_PortName = "Call" 440 | m_nEditorNodeID = 183 441 | m_RegisterMap = 442 | { 443 | m_Inparams = null 444 | m_Outparams = null 445 | } 446 | m_CallMethodID = 71 447 | m_nSrcChunk = 0 448 | m_nSrcInstruction = 18 449 | }, 450 | ] 451 | m_Constants = 452 | [ 453 | 454 | { 455 | m_Type = "PVAL_STRING" 456 | m_Value = "THIS MAP NEEDS TO BE RAN ON A SERVER" 457 | }, 458 | 459 | { 460 | m_Type = "PVAL_FLOAT" 461 | m_Value = 500.000000 462 | }, 463 | 464 | { 465 | m_Type = "PVAL_FLOAT" 466 | m_Value = 0.000000 467 | }, 468 | 469 | { 470 | m_Type = "PVAL_INT" 471 | m_Value = 20 472 | }, 473 | 474 | { 475 | m_Type = "PVAL_FLOAT" 476 | m_Value = 10 477 | }, 478 | 479 | { 480 | m_Type = "PVAL_VEC3" 481 | m_Value = 482 | [ 483 | 255.000000, 484 | 0.000000, 485 | 0.000000, 486 | ] 487 | }, 488 | 489 | { 490 | m_Type = "PVAL_FLOAT" 491 | m_Value = 1 492 | }, 493 | 494 | { 495 | m_Type = "PVAL_INt" 496 | m_Value = 1 497 | }, 498 | 499 | { 500 | m_Type = "PVAL_INt" 501 | m_Value = 200 502 | }, 503 | ] 504 | m_DomainValues = 505 | [ 506 | ] 507 | m_BlackboardReferences = 508 | [ 509 | ] 510 | m_OutputConnections = 511 | [ 512 | 513 | { 514 | m_SourceOutput = "logic_relay" 515 | m_TargetEntity = "logic_relay" 516 | m_TargetInput = "Trigger" 517 | m_Param = "" 518 | }, 519 | ] 520 | } -------------------------------------------------------------------------------- /tests/files/samples/data_witharrays.kv3: -------------------------------------------------------------------------------- 1 | 2 | { 3 | a = [ 4 | true, 5 | true, 6 | true, 7 | ] 8 | b = [ 9 | true, 10 | true, 11 | false, 12 | ] 13 | c = [ 14 | 0.0, 15 | 0.0, 16 | 0.0, 17 | ] 18 | d = [ 19 | 0.0, 20 | 0.0, 21 | 1.0, 22 | 0.0, 23 | ] 24 | e = [ 25 | "str1", 26 | "str2", 27 | "str3", 28 | ] 29 | f = [ 30 | "str1", 31 | "str2", 32 | resource_name:"str3", 33 | ] 34 | g = [ 35 | 1, 36 | 1, 37 | 1, 38 | 1, 39 | ] 40 | h = [ 41 | ] 42 | i = [ 43 | {}, 44 | {}, 45 | {}, 46 | ] 47 | } -------------------------------------------------------------------------------- /tests/files/samples/data_withblobs.kv3: -------------------------------------------------------------------------------- 1 | 2 | { 3 | a = #[ 4 | DE AD BE EF DE AD C0 DE 5 | ] 6 | 7 | b = #[] 8 | 9 | c = #[ 10 | AC CE 55 BA BE FA CE B0 55 DE ED 5E ED 11 | ] 12 | } -------------------------------------------------------------------------------- /tests/files/samples/data_withflags.kv3: -------------------------------------------------------------------------------- 1 | 2 | { 3 | a = resource:"resource" 4 | b = resource_name:"resource_name" 5 | c = panorama:"panorama" 6 | d = soundevent:"soundevent" 7 | e = subclass:"subclass" 8 | } -------------------------------------------------------------------------------- /tests/files/samples/edited.kv3: -------------------------------------------------------------------------------- 1 | 2 | { 3 | m_DomainIdentifier = "ServerPointEntity" 4 | m_ParentMapName = "maps/fronttest2.vmap" 5 | m_ParentXmlName = "" 6 | } -------------------------------------------------------------------------------- /tests/files/samples/file.vpulse_c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LionDoge/source2-asset-assembler/d62622ffeb480c83e3b181d65eae9894da2d24b6/tests/files/samples/file.vpulse_c -------------------------------------------------------------------------------- /tests/files/samples/red2.kv3: -------------------------------------------------------------------------------- 1 | 2 | { 3 | m_InputDependencies = 4 | [ 5 | 6 | { 7 | m_RelativeFilename = "pulse2/test.vpulse" 8 | m_SearchPath = "csgo" 9 | m_nFileCRC = 0 10 | m_bOptional = false 11 | m_bFileExists = true 12 | m_bIsGameFile = false 13 | }, 14 | ] 15 | m_AdditionalInputDependencies = 16 | [ 17 | ] 18 | m_ArgumentDependencies = 19 | [ 20 | 21 | { 22 | m_ParameterName = "___OverrideInputData___" 23 | m_ParameterType = "BinaryBlobArg" 24 | m_nFingerprint = 0 25 | m_nFingerprintDefault = 0 26 | }, 27 | ] 28 | m_SpecialDependencies = 29 | [ 30 | 31 | { 32 | m_String = "KV3 Compiler Version" 33 | m_CompilerIdentifier = "CompilePulseGraphDef" 34 | m_nFingerprint = 2 35 | m_nUserData = 0 36 | }, 37 | 38 | { 39 | m_String = "PulseGraphDef Compiler Version" 40 | m_CompilerIdentifier = "CompilePulseGraphDef" 41 | m_nFingerprint = 6 42 | m_nUserData = 0 43 | }, 44 | ] 45 | m_AdditionalRelatedFiles = 46 | [ 47 | ] 48 | m_ChildResourceList = 49 | [ 50 | ] 51 | m_WeakReferenceList = 52 | [ 53 | ] 54 | m_SearchableUserData = 55 | { 56 | pulse_domain = "ServerPointEntity" 57 | IsChildResource = 0 58 | } 59 | m_SubassetReferences = null 60 | m_SubassetDefinitions = null 61 | } -------------------------------------------------------------------------------- /tests/files/samples/struct.json: -------------------------------------------------------------------------------- 1 | { 2 | "info": { 3 | "headerversion": 12, 4 | "version": 0 5 | }, 6 | "blocks": [ 7 | { 8 | "type": "kv3", 9 | "name": "RED2", 10 | "file": "red2.kv3" 11 | }, 12 | { 13 | "type": "kv3", 14 | "name": "DATA", 15 | "file": "data.kv3" 16 | } 17 | ] 18 | } -------------------------------------------------------------------------------- /tests/test_general.py: -------------------------------------------------------------------------------- 1 | from assetbuilder import AssetInfo, FileBlock, matchBlockIndexFromString, getFileType, tryGetGameDirectoryFromContent 2 | import pytest 3 | from pathlib import Path 4 | @pytest.fixture 5 | def example_assetDataWithSameBlockNames(): 6 | return AssetInfo(version=2, headerVersion=12, blocks=[ 7 | FileBlock(type="kv3v4", name="RED2"), 8 | FileBlock(type="text", name="DATA"), 9 | FileBlock(type="kv3v4", name="STAT"), 10 | FileBlock(type="kv3v4", name="DATA"), 11 | ]) 12 | 13 | @pytest.mark.parametrize("blockstring,expected", [ 14 | ("DATA1", 3), 15 | ("STAT", 2) 16 | ]) 17 | def test_matchBlockIndexFromString(example_assetDataWithSameBlockNames, blockstring, expected): 18 | assert matchBlockIndexFromString(example_assetDataWithSameBlockNames, blockstring) == expected 19 | 20 | @pytest.mark.parametrize("invalidblockstring", [ 21 | "DATA2", 22 | "DATS", 23 | "DATAx", 24 | "DATA-1" 25 | ]) 26 | 27 | def test_matchBlockIndexFromString_noMatch(example_assetDataWithSameBlockNames, invalidblockstring): 28 | with pytest.raises(ValueError): 29 | matchBlockIndexFromString(example_assetDataWithSameBlockNames, invalidblockstring) 30 | 31 | 32 | def test_guessBinaryFileTypeFromContents(tmp_path): 33 | contents = b'\x00\xFF\x00\xAB\xCD\xEF' # code looks for 0x0 or 0xFF to determine binary file. 34 | with open(tmp_path / "file", "wb") as f: 35 | f.write(contents) 36 | with open(tmp_path / "file", "rb") as f: 37 | assert getFileType(f, len(contents)) == "bin" 38 | 39 | def test_guessTextFileTypeFromContents(tmp_path): 40 | contents = "This is text, I promise 💗" 41 | with open(tmp_path / "file", "w", encoding="utf-8") as f: 42 | f.write(contents) 43 | with open(tmp_path / "file", "rb") as f: 44 | assert getFileType(f, len(contents)) == "text" 45 | 46 | def test_contentCWDOutputsToGameDir(tmp_path): 47 | p1 = Path(tmp_path / "content" / "citadel" / "something") 48 | p1.mkdir(parents=True) 49 | p2 = Path(tmp_path / "game" / "citadel") 50 | p2.mkdir(parents=True) 51 | assert tryGetGameDirectoryFromContent(p1) == p2 / "something" 52 | 53 | def test_contentCWDWithoutValidGameDir(tmp_path): 54 | p1 = Path(tmp_path / "content" / "citadel" / "something") 55 | p1.mkdir(parents=True) 56 | p2 = Path(tmp_path / "game" ) 57 | p2.mkdir(parents=True) 58 | assert tryGetGameDirectoryFromContent(p1) == None 59 | 60 | def test_invalidContentCWDWithValidGameDir(tmp_path): 61 | p1 = Path(tmp_path / "content") 62 | p1.mkdir(parents=True) 63 | p2 = Path(tmp_path / "game" / "citadel" ) 64 | p2.mkdir(parents=True) 65 | assert tryGetGameDirectoryFromContent(p1) == None 66 | 67 | def test_randomCWDandGameDir(tmp_path): 68 | p1 = Path(tmp_path / "something") 69 | p1.mkdir(parents=True) 70 | p2 = Path(tmp_path / "somethingelse" / "output" ) 71 | p2.mkdir(parents=True) 72 | assert tryGetGameDirectoryFromContent(p1) == None -------------------------------------------------------------------------------- /tests/test_readers.py: -------------------------------------------------------------------------------- 1 | from assetbuilder import readAssetFile, AssetInfo, FileBlock, readRERLTextFile, FileFormattingError, AssetReadError 2 | from test_writers import example_rerl_source 3 | import pytest 4 | 5 | @pytest.fixture 6 | def asset1Data(): 7 | return AssetInfo(version=2, headerVersion=12, blocks=[ 8 | FileBlock(type="kv3v4", name="RED2", data=b'\x04\x33\x56\x4B', dataProcessed=True), 9 | FileBlock(type="text", name="DATA", data=b'dataaa', dataProcessed=True), 10 | FileBlock(type="kv3v3", name="STAT", data=b'\x03\x33\x56\x4B', dataProcessed=True), 11 | ]) 12 | 13 | @pytest.fixture 14 | def asset2Data(): 15 | return AssetInfo(version=1, headerVersion=12, blocks=[ 16 | FileBlock(type="rerl", name="RERL"), 17 | FileBlock(type="kv3v4", name="RED2"), 18 | FileBlock(type="kv3v4", name="DATA"), 19 | FileBlock(type="kv3v4", name="INSG"), 20 | ]) 21 | 22 | @pytest.fixture 23 | def example_rerl_file(): 24 | with open("tests/files/rerltest.txt", "r") as f: 25 | return f.read() 26 | 27 | def test_readAssetFileBlockInfoAndData(asset1Data): 28 | assert readAssetFile("tests/files/asset_minimal.vts_c", True) == asset1Data 29 | 30 | def test_readAssetFileBlockInfoOnly(asset2Data): 31 | assert readAssetFile("tests/files/asset2.vmat_c", False) == asset2Data 32 | 33 | def test_readRerlData(example_rerl_file, example_rerl_source): 34 | assert readRERLTextFile(example_rerl_file) == example_rerl_source 35 | 36 | @pytest.mark.parametrize("invalidrerl", [ 37 | "1000a something", 38 | "-1 something", 39 | "0" 40 | ]) 41 | def test_is_invalidrerl(invalidrerl): 42 | with pytest.raises(FileFormattingError): 43 | readRERLTextFile(invalidrerl) -------------------------------------------------------------------------------- /tests/test_schema.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | from pathlib import Path 3 | import json 4 | from assetbuilder import parseJsonStructure, AssetInfo, FileBlock, AssetReadErrorGeneric 5 | 6 | SAMPLE_FILES_PATH = Path("tests/files/samples") 7 | class JsonDATA: 8 | def __init__(self, info, blocks): 9 | self.info = info 10 | self.blocks = blocks 11 | 12 | @pytest.fixture 13 | def example_assetInfo(): 14 | return AssetInfo(version=0, headerVersion=12, blocks=[ 15 | FileBlock(type="kv3v4", name="RED2"), 16 | FileBlock(type="kv3v4", name="DATA"), 17 | ]) 18 | # we will be slightly modifying this fixture in tests, as to not copy paste it. 19 | @pytest.fixture 20 | def example_structBase(): 21 | return { 22 | "info": { 23 | "headerversion": 12, 24 | "version": 0 25 | }, 26 | "blocks": [ 27 | { 28 | "type": "kv3v4", 29 | "name": "RED2", 30 | "file": "red2.kv3" 31 | }, 32 | { 33 | "type": "kv3v4", 34 | "name": "DATA", 35 | "file": "data.kv3" 36 | } 37 | ] 38 | } 39 | 40 | def createJsonString(data): 41 | return json.dumps(JsonDATA(**data).__dict__) 42 | 43 | def test_assetFromJsonStructure(example_structBase, example_assetInfo): 44 | result = parseJsonStructure(example_structBase, Path("tests/files/samples")) 45 | # intentionaly omitting the data value 46 | assert result.version == example_assetInfo.version 47 | assert result.headerVersion == example_assetInfo.headerVersion 48 | assert len(result.blocks) == len(example_assetInfo.blocks) 49 | for res_block, exp_block in zip(result.blocks, example_assetInfo.blocks): 50 | assert res_block.type == exp_block.type 51 | assert res_block.name == exp_block.name 52 | 53 | def test_validateJsonStructure_missing_infoSection(example_structBase): 54 | struct = example_structBase 55 | del struct["info"] 56 | with pytest.raises(ValueError, match="missing 'info' section"): 57 | parseJsonStructure(struct, SAMPLE_FILES_PATH) 58 | 59 | def test_validateJsonStructure_invalid_version(example_structBase): 60 | struct = example_structBase 61 | struct['info']['version'] = -1 62 | with pytest.raises(ValueError, match="invalid version number"): 63 | parseJsonStructure(struct, SAMPLE_FILES_PATH) 64 | 65 | def test_validateJsonStructure_invalid_headerVersion(example_structBase): 66 | struct = example_structBase 67 | struct['info']['headerversion'] = -1 68 | with pytest.raises(ValueError, match="invalid headerversion number"): 69 | parseJsonStructure(struct, SAMPLE_FILES_PATH) 70 | 71 | def test_validateJsonStructure_missing_blocks(example_structBase): 72 | struct = example_structBase 73 | del struct["blocks"] 74 | with pytest.raises(ValueError, match="missing 'blocks' section"): 75 | parseJsonStructure(struct, SAMPLE_FILES_PATH) 76 | 77 | 78 | def test_validateJsonStructure_unsupportedType(example_structBase): 79 | struct = example_structBase 80 | struct['blocks'][0]['type'] = "123" 81 | with pytest.raises(ValueError, match="'type' must be"): 82 | parseJsonStructure(struct, SAMPLE_FILES_PATH) 83 | 84 | def test_validateJsonStructure_invalid_block_name_length(example_structBase): 85 | struct = example_structBase 86 | struct['blocks'][0]['name'] = "TOOLONG" 87 | with pytest.raises(ValueError, match="'name' must be a 4 character string, in block no. 1"): 88 | parseJsonStructure(struct, SAMPLE_FILES_PATH) 89 | 90 | def test_parseJsonStructure_file_not_found(example_structBase): 91 | struct = example_structBase 92 | struct['blocks'][0]['file'] = "idontexist.kv3" 93 | with pytest.raises(AssetReadErrorGeneric): 94 | parseJsonStructure(struct, SAMPLE_FILES_PATH) 95 | 96 | def test_parseJsonStructure_emptyBlocksList(example_structBase): 97 | struct = example_structBase 98 | struct['blocks'] = [] 99 | with pytest.raises(ValueError, match="empty 'blocks' list"): 100 | parseJsonStructure(struct, SAMPLE_FILES_PATH) 101 | 102 | def test_parseJsonStructure_invalid_structure(example_structBase): 103 | struct = example_structBase 104 | struct['blocks'] = "not a list" 105 | with pytest.raises(ValueError, match="'blocks' must be a list."): 106 | parseJsonStructure(struct, SAMPLE_FILES_PATH) 107 | -------------------------------------------------------------------------------- /tests/test_usage.py: -------------------------------------------------------------------------------- 1 | from dataclasses import field 2 | import subprocess 3 | import pytest 4 | from pathlib import Path 5 | import keyvalues3 as kv3 6 | 7 | class Test: 8 | __test__ = False 9 | def __init__(self, launchArgs: list[str], expectedExitCode: int, compilerOutputFile: Path): 10 | self.launchArgs = launchArgs 11 | self.expectedExitCode = expectedExitCode 12 | self.compilerOutputFile = compilerOutputFile.absolute().as_posix() 13 | launchArgs: list[str] 14 | expectedExitCode: int 15 | compilerOutputFile: str 16 | 17 | def run(self): 18 | subprocess.run(["python", "assetbuilder.py", *self.launchArgs, "-o", self.compilerOutputFile], check=True) 19 | # add _d to the end of the file name and remove _c from the extension 20 | extensionPos = self.compilerOutputFile.rfind('.') 21 | decompiledName = self.compilerOutputFile[:extensionPos] + "_d" + self.compilerOutputFile[extensionPos:-2] 22 | subprocess.run(["./Decompiler", "-i", self.compilerOutputFile, '-o', decompiledName], check=True) 23 | return decompiledName 24 | 25 | def test_usageWithPreset(tmp_path): 26 | testInfo = Test( 27 | ["-p", "vpulse", "-f", 28 | "tests/files/samples/red2.kv3", 29 | "tests/files/samples/data.kv3"], 30 | 0, 31 | tmp_path / "pulsesample.vpulse_c" 32 | ) 33 | decompiledName = testInfo.run() 34 | originalFile = kv3.read("tests/files/samples/data.kv3") 35 | decompiledFile = kv3.read(decompiledName) 36 | assert originalFile == decompiledFile 37 | 38 | def test_usageWithStruct(tmp_path): 39 | testInfo = Test( 40 | ["-s", "tests/files/samples/struct.json"], 41 | 0, 42 | tmp_path / "pulsesample.vpulse_c" 43 | ) 44 | decompiledName = testInfo.run() 45 | originalFile = kv3.read("tests/files/samples/data.kv3") 46 | decompiledFile = kv3.read(decompiledName) 47 | assert originalFile == decompiledFile 48 | 49 | def test_usageWithBaseFileInput(tmp_path): 50 | testInfo = Test( 51 | ["-b", "tests/files/samples/file.vpulse_c", "-f", 52 | "tests/files/samples/red2.kv3", 53 | "tests/files/samples/data.kv3"], 54 | 0, 55 | tmp_path / "pulsesample.vpulse_c" 56 | ) 57 | decompiledName = testInfo.run() 58 | originalFile = kv3.read("tests/files/samples/data.kv3") 59 | decompiledFile = kv3.read(decompiledName) 60 | assert originalFile == decompiledFile 61 | 62 | def test_usageWithEdit(tmp_path): 63 | testInfo = Test( 64 | ["-e", "tests/files/samples/file.vpulse_c", "DATA", "-f" 65 | "tests/files/samples/edited.kv3"], 66 | 0, 67 | tmp_path / "pulsesample.vpulse_c" 68 | ) 69 | decompiledName = testInfo.run() 70 | originalFile = kv3.read("tests/files/samples/edited.kv3") 71 | decompiledFile = kv3.read(decompiledName) 72 | assert originalFile == decompiledFile 73 | 74 | # these are more specific to just testing kv3 files 75 | def test_kv3FlagsValidity(tmp_path): 76 | testInfo = Test( 77 | ["-p", "vpulse", "-f", 78 | "tests/files/samples/red2.kv3", 79 | "tests/files/samples/data_withflags.kv3"], 80 | 0, 81 | tmp_path / "pulsesample.vpulse_c" 82 | ) 83 | decompiledName = testInfo.run() 84 | originalFile = kv3.read("tests/files/samples/data_withflags.kv3") 85 | decompiledFile = kv3.read(decompiledName) 86 | assert originalFile == decompiledFile 87 | 88 | def test_kv3BlobsValidity(tmp_path): 89 | testInfo = Test( 90 | ["-p", "vpulse", "-f", 91 | "tests/files/samples/red2.kv3", 92 | "tests/files/samples/data_withblobs.kv3"], 93 | 0, 94 | tmp_path / "pulsesample.vpulse_c" 95 | ) 96 | decompiledName = testInfo.run() 97 | originalFile = kv3.read("tests/files/samples/data_withblobs.kv3") 98 | decompiledFile = kv3.read(decompiledName) 99 | assert originalFile == decompiledFile 100 | 101 | def test_kv3ArraysValidity(tmp_path): 102 | testInfo = Test( 103 | ["-p", "vpulse", "-f", 104 | "tests/files/samples/red2.kv3", 105 | "tests/files/samples/data_witharrays.kv3"], 106 | 0, 107 | tmp_path / "pulsesample.vpulse_c" 108 | ) 109 | decompiledName = testInfo.run() 110 | originalFile = kv3.read("tests/files/samples/data_witharrays.kv3") 111 | decompiledFile = kv3.read(decompiledName) 112 | assert originalFile == decompiledFile 113 | -------------------------------------------------------------------------------- /tests/test_writers.py: -------------------------------------------------------------------------------- 1 | from assetbuilder import buildRERLBlock 2 | import pytest 3 | 4 | @pytest.fixture 5 | def example_rerl_source() -> list[tuple[int, str]]: 6 | return [ 7 | (4028879694858690263, "materials/default/default_ao_tga_559f1ac6.vtex"), 8 | (3981026097612531816, "materials/default/default_metal_tga_af1d7118.vtex"), 9 | (16991945667032608603, "materials/default/default_normal_tga_4c6e7391.vtex") 10 | ] 11 | 12 | @pytest.fixture 13 | def example_rerl_data() -> bytes: 14 | data = b'' 15 | with open("tests/files/rerlblock.bin", "rb") as f: 16 | data = f.read() 17 | return data 18 | 19 | def test_buildRERLBlock(example_rerl_source, example_rerl_data): 20 | assert buildRERLBlock(example_rerl_source) == example_rerl_data --------------------------------------------------------------------------------