├── .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 | 
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="