diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000000..e8422f2e75
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,99 @@
+root = true
+
+# All Files
+[*]
+charset = utf-8
+indent_style = space
+indent_size = 4
+tab_width = 4
+insert_final_newline = true
+trim_trailing_whitespace = true
+
+[*.txt]
+insert_final_newline = false
+
+# XML Project Files
+[*.{slnx,csproj}]
+indent_size = 2
+tab_width = 2
+
+# Code Files
+[*.{cs,vb}]
+end_of_line = crlf
+
+dotnet_diagnostic.IDE0047.severity = none
+dotnet_diagnostic.IDE0048.severity = none
+dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:suggest
+dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:suggest
+dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:suggest
+dotnet_style_parentheses_in_other_operators = always_for_clarity:suggest
+
+csharp_indent_labels = one_less_than_current
+csharp_prefer_braces = when_multiline:warning
+csharp_prefer_simple_using_statement = true:suggestion
+csharp_prefer_system_threading_lock = true:suggestion
+csharp_style_namespace_declarations = block_scoped:silent
+csharp_style_prefer_method_group_conversion = true:silent
+csharp_style_prefer_top_level_statements = true:silent
+csharp_style_prefer_primary_constructors = true:suggestion
+csharp_style_expression_bodied_methods = false:silent
+csharp_style_expression_bodied_constructors = false:silent
+csharp_style_expression_bodied_operators = false:silent
+csharp_style_expression_bodied_properties = true:silent
+csharp_style_expression_bodied_indexers = true:silent
+csharp_style_expression_bodied_accessors = true:silent
+csharp_style_expression_bodied_lambdas = true:silent
+csharp_style_expression_bodied_local_functions = false:silent
+csharp_using_directive_placement = outside_namespace:silent
+
+dotnet_style_operator_placement_when_wrapping = beginning_of_line
+dotnet_style_coalesce_expression = true:suggestion
+dotnet_style_null_propagation = true:suggestion
+dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion
+dotnet_style_prefer_auto_properties = true:silent
+dotnet_style_object_initializer = true:suggestion
+dotnet_style_collection_initializer = true:suggestion
+dotnet_style_prefer_simplified_boolean_expressions = true:suggestion
+dotnet_style_prefer_conditional_expression_over_assignment = true:silent
+dotnet_style_prefer_conditional_expression_over_return = true:silent
+dotnet_style_explicit_tuple_names = true:suggestion
+
+#### Naming styles ####
+
+# Naming rules
+
+dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
+dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
+dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
+
+dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
+dotnet_naming_rule.types_should_be_pascal_case.symbols = types
+dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
+
+dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
+dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
+dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
+
+# Symbol specifications
+
+dotnet_naming_symbols.interface.applicable_kinds = interface
+dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
+
+dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
+dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
+
+dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
+dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
+
+# Naming styles
+
+dotnet_naming_style.begins_with_i.required_prefix = I
+dotnet_naming_style.begins_with_i.capitalization = pascal_case
+
+dotnet_naming_style.pascal_case.capitalization = pascal_case
+
+# IDE0130: Namespace does not match folder structure
+dotnet_diagnostic.IDE0130.severity = none
+
+# WFO1000: Property does not configure the code serialization for its property content.
+dotnet_diagnostic.WFO1000.severity = none
\ No newline at end of file
diff --git a/Directory.Build.props b/Directory.Build.props
new file mode 100644
index 0000000000..1ed906c363
--- /dev/null
+++ b/Directory.Build.props
@@ -0,0 +1,11 @@
+
+
+ latest
+ en
+ pk3DS
+ Project Pokémon
+ Kaphotics
+ Kaphotics
+ $([System.DateTime]::UtcNow.ToString("yyMMddHHmmss"))
+
+
diff --git a/LICENSE.md b/LICENSE.md
new file mode 100644
index 0000000000..16d89e0a34
--- /dev/null
+++ b/LICENSE.md
@@ -0,0 +1,596 @@
+GNU GENERAL PUBLIC LICENSE
+==========================
+
+Version 3, 29 June 2007
+
+Copyright © 2007 Free Software Foundation, Inc. <>
+
+Everyone is permitted to copy and distribute verbatim copies of this license
+document, but changing it is not allowed.
+
+## Preamble
+
+The GNU General Public License is a free, copyleft license for software and other
+kinds of works.
+
+The licenses for most software and other practical works are designed to take away
+your freedom to share and change the works. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change all versions of a
+program--to make sure it remains free software for all its users. We, the Free
+Software Foundation, use the GNU General Public License for most of our software; it
+applies also to any other work released this way by its authors. You can apply it to
+your programs, too.
+
+When we speak of free software, we are referring to freedom, not price. Our General
+Public Licenses are designed to make sure that you have the freedom to distribute
+copies of free software (and charge for them if you wish), that you receive source
+code or can get it if you want it, that you can change the software or use pieces of
+it in new free programs, and that you know you can do these things.
+
+To protect your rights, we need to prevent others from denying you these rights or
+asking you to surrender the rights. Therefore, you have certain responsibilities if
+you distribute copies of the software, or if you modify it: responsibilities to
+respect the freedom of others.
+
+For example, if you distribute copies of such a program, whether gratis or for a fee,
+you must pass on to the recipients the same freedoms that you received. You must make
+sure that they, too, receive or can get the source code. And you must show them these
+terms so they know their rights.
+
+Developers that use the GNU GPL protect your rights with two steps: (1) assert
+copyright on the software, and (2) offer you this License giving you legal permission
+to copy, distribute and/or modify it.
+
+For the developers' and authors' protection, the GPL clearly explains that there is
+no warranty for this free software. For both users' and authors' sake, the GPL
+requires that modified versions be marked as changed, so that their problems will not
+be attributed erroneously to authors of previous versions.
+
+Some devices are designed to deny users access to install or run modified versions of
+the software inside them, although the manufacturer can do so. This is fundamentally
+incompatible with the aim of protecting users' freedom to change the software. The
+systematic pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we have designed
+this version of the GPL to prohibit the practice for those products. If such problems
+arise substantially in other domains, we stand ready to extend this provision to
+those domains in future versions of the GPL, as needed to protect the freedom of
+users.
+
+Finally, every program is threatened constantly by software patents. States should
+not allow patents to restrict development and use of software on general-purpose
+computers, but in those that do, we wish to avoid the special danger that patents
+applied to a free program could make it effectively proprietary. To prevent this, the
+GPL assures that patents cannot be used to render the program non-free.
+
+The precise terms and conditions for copying, distribution and modification follow.
+
+## TERMS AND CONDITIONS
+
+### 0. Definitions.
+
+“This License” refers to version 3 of the GNU General Public License.
+
+“Copyright” also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+“The Program” refers to any copyrightable work licensed under this
+License. Each licensee is addressed as “you”. “Licensees” and
+“recipients” may be individuals or organizations.
+
+To “modify” a work means to copy from or adapt all or part of the work in
+a fashion requiring copyright permission, other than the making of an exact copy. The
+resulting work is called a “modified version” of the earlier work or a
+work “based on” the earlier work.
+
+A “covered work” means either the unmodified Program or a work based on
+the Program.
+
+To “propagate” a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for infringement under
+applicable copyright law, except executing it on a computer or modifying a private
+copy. Propagation includes copying, distribution (with or without modification),
+making available to the public, and in some countries other activities as well.
+
+To “convey” a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through a computer
+network, with no transfer of a copy, is not conveying.
+
+An interactive user interface displays “Appropriate Legal Notices” to the
+extent that it includes a convenient and prominently visible feature that (1)
+displays an appropriate copyright notice, and (2) tells the user that there is no
+warranty for the work (except to the extent that warranties are provided), that
+licensees may convey the work under this License, and how to view a copy of this
+License. If the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+### 1. Source Code.
+
+The “source code” for a work means the preferred form of the work for
+making modifications to it. “Object code” means any non-source form of a
+work.
+
+A “Standard Interface” means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of interfaces
+specified for a particular programming language, one that is widely used among
+developers working in that language.
+
+The “System Libraries” of an executable work include anything, other than
+the work as a whole, that (a) is included in the normal form of packaging a Major
+Component, but which is not part of that Major Component, and (b) serves only to
+enable use of the work with that Major Component, or to implement a Standard
+Interface for which an implementation is available to the public in source code form.
+A “Major Component”, in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system (if any) on which
+the executable work runs, or a compiler used to produce the work, or an object code
+interpreter used to run it.
+
+The “Corresponding Source” for a work in object code form means all the
+source code needed to generate, install, and (for an executable work) run the object
+code and to modify the work, including scripts to control those activities. However,
+it does not include the work's System Libraries, or general-purpose tools or
+generally available free programs which are used unmodified in performing those
+activities but which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for the work, and
+the source code for shared libraries and dynamically linked subprograms that the work
+is specifically designed to require, such as by intimate data communication or
+control flow between those subprograms and other parts of the work.
+
+The Corresponding Source need not include anything that users can regenerate
+automatically from other parts of the Corresponding Source.
+
+The Corresponding Source for a work in source code form is that same work.
+
+### 2. Basic Permissions.
+
+All rights granted under this License are granted for the term of copyright on the
+Program, and are irrevocable provided the stated conditions are met. This License
+explicitly affirms your unlimited permission to run the unmodified Program. The
+output from running a covered work is covered by this License only if the output,
+given its content, constitutes a covered work. This License acknowledges your rights
+of fair use or other equivalent, as provided by copyright law.
+
+You may make, run and propagate covered works that you do not convey, without
+conditions so long as your license otherwise remains in force. You may convey covered
+works to others for the sole purpose of having them make modifications exclusively
+for you, or provide you with facilities for running those works, provided that you
+comply with the terms of this License in conveying all material for which you do not
+control copyright. Those thus making or running the covered works for you must do so
+exclusively on your behalf, under your direction and control, on terms that prohibit
+them from making any copies of your copyrighted material outside their relationship
+with you.
+
+Conveying under any other circumstances is permitted solely under the conditions
+stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
+
+### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+No covered work shall be deemed part of an effective technological measure under any
+applicable law fulfilling obligations under article 11 of the WIPO copyright treaty
+adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention
+of such measures.
+
+When you convey a covered work, you waive any legal power to forbid circumvention of
+technological measures to the extent such circumvention is effected by exercising
+rights under this License with respect to the covered work, and you disclaim any
+intention to limit operation or modification of the work as a means of enforcing,
+against the work's users, your or third parties' legal rights to forbid circumvention
+of technological measures.
+
+### 4. Conveying Verbatim Copies.
+
+You may convey verbatim copies of the Program's source code as you receive it, in any
+medium, provided that you conspicuously and appropriately publish on each copy an
+appropriate copyright notice; keep intact all notices stating that this License and
+any non-permissive terms added in accord with section 7 apply to the code; keep
+intact all notices of the absence of any warranty; and give all recipients a copy of
+this License along with the Program.
+
+You may charge any price or no price for each copy that you convey, and you may offer
+support or warranty protection for a fee.
+
+### 5. Conveying Modified Source Versions.
+
+You may convey a work based on the Program, or the modifications to produce it from
+the Program, in the form of source code under the terms of section 4, provided that
+you also meet all of these conditions:
+
+* **a)** The work must carry prominent notices stating that you modified it, and giving a
+relevant date.
+* **b)** The work must carry prominent notices stating that it is released under this
+License and any conditions added under section 7. This requirement modifies the
+requirement in section 4 to “keep intact all notices”.
+* **c)** You must license the entire work, as a whole, under this License to anyone who
+comes into possession of a copy. This License will therefore apply, along with any
+applicable section 7 additional terms, to the whole of the work, and all its parts,
+regardless of how they are packaged. This License gives no permission to license the
+work in any other way, but it does not invalidate such permission if you have
+separately received it.
+* **d)** If the work has interactive user interfaces, each must display Appropriate Legal
+Notices; however, if the Program has interactive interfaces that do not display
+Appropriate Legal Notices, your work need not make them do so.
+
+A compilation of a covered work with other separate and independent works, which are
+not by their nature extensions of the covered work, and which are not combined with
+it such as to form a larger program, in or on a volume of a storage or distribution
+medium, is called an “aggregate” if the compilation and its resulting
+copyright are not used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work in an aggregate
+does not cause this License to apply to the other parts of the aggregate.
+
+### 6. Conveying Non-Source Forms.
+
+You may convey a covered work in object code form under the terms of sections 4 and
+5, provided that you also convey the machine-readable Corresponding Source under the
+terms of this License, in one of these ways:
+
+* **a)** Convey the object code in, or embodied in, a physical product (including a
+physical distribution medium), accompanied by the Corresponding Source fixed on a
+durable physical medium customarily used for software interchange.
+* **b)** Convey the object code in, or embodied in, a physical product (including a
+physical distribution medium), accompanied by a written offer, valid for at least
+three years and valid for as long as you offer spare parts or customer support for
+that product model, to give anyone who possesses the object code either (1) a copy of
+the Corresponding Source for all the software in the product that is covered by this
+License, on a durable physical medium customarily used for software interchange, for
+a price no more than your reasonable cost of physically performing this conveying of
+source, or (2) access to copy the Corresponding Source from a network server at no
+charge.
+* **c)** Convey individual copies of the object code with a copy of the written offer to
+provide the Corresponding Source. This alternative is allowed only occasionally and
+noncommercially, and only if you received the object code with such an offer, in
+accord with subsection 6b.
+* **d)** Convey the object code by offering access from a designated place (gratis or for
+a charge), and offer equivalent access to the Corresponding Source in the same way
+through the same place at no further charge. You need not require recipients to copy
+the Corresponding Source along with the object code. If the place to copy the object
+code is a network server, the Corresponding Source may be on a different server
+(operated by you or a third party) that supports equivalent copying facilities,
+provided you maintain clear directions next to the object code saying where to find
+the Corresponding Source. Regardless of what server hosts the Corresponding Source,
+you remain obligated to ensure that it is available for as long as needed to satisfy
+these requirements.
+* **e)** Convey the object code using peer-to-peer transmission, provided you inform
+other peers where the object code and Corresponding Source of the work are being
+offered to the general public at no charge under subsection 6d.
+
+A separable portion of the object code, whose source code is excluded from the
+Corresponding Source as a System Library, need not be included in conveying the
+object code work.
+
+A “User Product” is either (1) a “consumer product”, which
+means any tangible personal property which is normally used for personal, family, or
+household purposes, or (2) anything designed or sold for incorporation into a
+dwelling. In determining whether a product is a consumer product, doubtful cases
+shall be resolved in favor of coverage. For a particular product received by a
+particular user, “normally used” refers to a typical or common use of
+that class of product, regardless of the status of the particular user or of the way
+in which the particular user actually uses, or expects or is expected to use, the
+product. A product is a consumer product regardless of whether the product has
+substantial commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+“Installation Information” for a User Product means any methods,
+procedures, authorization keys, or other information required to install and execute
+modified versions of a covered work in that User Product from a modified version of
+its Corresponding Source. The information must suffice to ensure that the continued
+functioning of the modified object code is in no case prevented or interfered with
+solely because modification has been made.
+
+If you convey an object code work under this section in, or with, or specifically for
+use in, a User Product, and the conveying occurs as part of a transaction in which
+the right of possession and use of the User Product is transferred to the recipient
+in perpetuity or for a fixed term (regardless of how the transaction is
+characterized), the Corresponding Source conveyed under this section must be
+accompanied by the Installation Information. But this requirement does not apply if
+neither you nor any third party retains the ability to install modified object code
+on the User Product (for example, the work has been installed in ROM).
+
+The requirement to provide Installation Information does not include a requirement to
+continue to provide support service, warranty, or updates for a work that has been
+modified or installed by the recipient, or for the User Product in which it has been
+modified or installed. Access to a network may be denied when the modification itself
+materially and adversely affects the operation of the network or violates the rules
+and protocols for communication across the network.
+
+Corresponding Source conveyed, and Installation Information provided, in accord with
+this section must be in a format that is publicly documented (and with an
+implementation available to the public in source code form), and must require no
+special password or key for unpacking, reading or copying.
+
+### 7. Additional Terms.
+
+“Additional permissions” are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions. Additional
+permissions that are applicable to the entire Program shall be treated as though they
+were included in this License, to the extent that they are valid under applicable
+law. If additional permissions apply only to part of the Program, that part may be
+used separately under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+When you convey a copy of a covered work, you may at your option remove any
+additional permissions from that copy, or from any part of it. (Additional
+permissions may be written to require their own removal in certain cases when you
+modify the work.) You may place additional permissions on material, added by you to a
+covered work, for which you have or can give appropriate copyright permission.
+
+Notwithstanding any other provision of this License, for material you add to a
+covered work, you may (if authorized by the copyright holders of that material)
+supplement the terms of this License with terms:
+
+* **a)** Disclaiming warranty or limiting liability differently from the terms of
+sections 15 and 16 of this License; or
+* **b)** Requiring preservation of specified reasonable legal notices or author
+attributions in that material or in the Appropriate Legal Notices displayed by works
+containing it; or
+* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that
+modified versions of such material be marked in reasonable ways as different from the
+original version; or
+* **d)** Limiting the use for publicity purposes of names of licensors or authors of the
+material; or
+* **e)** Declining to grant rights under trademark law for use of some trade names,
+trademarks, or service marks; or
+* **f)** Requiring indemnification of licensors and authors of that material by anyone
+who conveys the material (or modified versions of it) with contractual assumptions of
+liability to the recipient, for any liability that these contractual assumptions
+directly impose on those licensors and authors.
+
+All other non-permissive additional terms are considered “further
+restrictions” within the meaning of section 10. If the Program as you received
+it, or any part of it, contains a notice stating that it is governed by this License
+along with a term that is a further restriction, you may remove that term. If a
+license document contains a further restriction but permits relicensing or conveying
+under this License, you may add to a covered work material governed by the terms of
+that license document, provided that the further restriction does not survive such
+relicensing or conveying.
+
+If you add terms to a covered work in accord with this section, you must place, in
+the relevant source files, a statement of the additional terms that apply to those
+files, or a notice indicating where to find the applicable terms.
+
+Additional terms, permissive or non-permissive, may be stated in the form of a
+separately written license, or stated as exceptions; the above requirements apply
+either way.
+
+### 8. Termination.
+
+You may not propagate or modify a covered work except as expressly provided under
+this License. Any attempt otherwise to propagate or modify it is void, and will
+automatically terminate your rights under this License (including any patent licenses
+granted under the third paragraph of section 11).
+
+However, if you cease all violation of this License, then your license from a
+particular copyright holder is reinstated (a) provisionally, unless and until the
+copyright holder explicitly and finally terminates your license, and (b) permanently,
+if the copyright holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+Moreover, your license from a particular copyright holder is reinstated permanently
+if the copyright holder notifies you of the violation by some reasonable means, this
+is the first time you have received notice of violation of this License (for any
+work) from that copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+Termination of your rights under this section does not terminate the licenses of
+parties who have received copies or rights from you under this License. If your
+rights have been terminated and not permanently reinstated, you do not qualify to
+receive new licenses for the same material under section 10.
+
+### 9. Acceptance Not Required for Having Copies.
+
+You are not required to accept this License in order to receive or run a copy of the
+Program. Ancillary propagation of a covered work occurring solely as a consequence of
+using peer-to-peer transmission to receive a copy likewise does not require
+acceptance. However, nothing other than this License grants you permission to
+propagate or modify any covered work. These actions infringe copyright if you do not
+accept this License. Therefore, by modifying or propagating a covered work, you
+indicate your acceptance of this License to do so.
+
+### 10. Automatic Licensing of Downstream Recipients.
+
+Each time you convey a covered work, the recipient automatically receives a license
+from the original licensors, to run, modify and propagate that work, subject to this
+License. You are not responsible for enforcing compliance by third parties with this
+License.
+
+An “entity transaction” is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an organization, or
+merging organizations. If propagation of a covered work results from an entity
+transaction, each party to that transaction who receives a copy of the work also
+receives whatever licenses to the work the party's predecessor in interest had or
+could give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if the predecessor
+has it or can get it with reasonable efforts.
+
+You may not impose any further restrictions on the exercise of the rights granted or
+affirmed under this License. For example, you may not impose a license fee, royalty,
+or other charge for exercise of rights granted under this License, and you may not
+initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging
+that any patent claim is infringed by making, using, selling, offering for sale, or
+importing the Program or any portion of it.
+
+### 11. Patents.
+
+A “contributor” is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The work thus
+licensed is called the contributor's “contributor version”.
+
+A contributor's “essential patent claims” are all patent claims owned or
+controlled by the contributor, whether already acquired or hereafter acquired, that
+would be infringed by some manner, permitted by this License, of making, using, or
+selling its contributor version, but do not include claims that would be infringed
+only as a consequence of further modification of the contributor version. For
+purposes of this definition, “control” includes the right to grant patent
+sublicenses in a manner consistent with the requirements of this License.
+
+Each contributor grants you a non-exclusive, worldwide, royalty-free patent license
+under the contributor's essential patent claims, to make, use, sell, offer for sale,
+import and otherwise run, modify and propagate the contents of its contributor
+version.
+
+In the following three paragraphs, a “patent license” is any express
+agreement or commitment, however denominated, not to enforce a patent (such as an
+express permission to practice a patent or covenant not to sue for patent
+infringement). To “grant” such a patent license to a party means to make
+such an agreement or commitment not to enforce a patent against the party.
+
+If you convey a covered work, knowingly relying on a patent license, and the
+Corresponding Source of the work is not available for anyone to copy, free of charge
+and under the terms of this License, through a publicly available network server or
+other readily accessible means, then you must either (1) cause the Corresponding
+Source to be so available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner consistent with
+the requirements of this License, to extend the patent license to downstream
+recipients. “Knowingly relying” means you have actual knowledge that, but
+for the patent license, your conveying the covered work in a country, or your
+recipient's use of the covered work in a country, would infringe one or more
+identifiable patents in that country that you have reason to believe are valid.
+
+If, pursuant to or in connection with a single transaction or arrangement, you
+convey, or propagate by procuring conveyance of, a covered work, and grant a patent
+license to some of the parties receiving the covered work authorizing them to use,
+propagate, modify or convey a specific copy of the covered work, then the patent
+license you grant is automatically extended to all recipients of the covered work and
+works based on it.
+
+A patent license is “discriminatory” if it does not include within the
+scope of its coverage, prohibits the exercise of, or is conditioned on the
+non-exercise of one or more of the rights that are specifically granted under this
+License. You may not convey a covered work if you are a party to an arrangement with
+a third party that is in the business of distributing software, under which you make
+payment to the third party based on the extent of your activity of conveying the
+work, and under which the third party grants, to any of the parties who would receive
+the covered work from you, a discriminatory patent license (a) in connection with
+copies of the covered work conveyed by you (or copies made from those copies), or (b)
+primarily for and in connection with specific products or compilations that contain
+the covered work, unless you entered into that arrangement, or that patent license
+was granted, prior to 28 March 2007.
+
+Nothing in this License shall be construed as excluding or limiting any implied
+license or other defenses to infringement that may otherwise be available to you
+under applicable patent law.
+
+### 12. No Surrender of Others' Freedom.
+
+If conditions are imposed on you (whether by court order, agreement or otherwise)
+that contradict the conditions of this License, they do not excuse you from the
+conditions of this License. If you cannot convey a covered work so as to satisfy
+simultaneously your obligations under this License and any other pertinent
+obligations, then as a consequence you may not convey it at all. For example, if you
+agree to terms that obligate you to collect a royalty for further conveying from
+those to whom you convey the Program, the only way you could satisfy both those terms
+and this License would be to refrain entirely from conveying the Program.
+
+### 13. Use with the GNU Affero General Public License.
+
+Notwithstanding any other provision of this License, you have permission to link or
+combine any covered work with a work licensed under version 3 of the GNU Affero
+General Public License into a single combined work, and to convey the resulting work.
+The terms of this License will continue to apply to the part which is the covered
+work, but the special requirements of the GNU Affero General Public License, section
+13, concerning interaction through a network will apply to the combination as such.
+
+### 14. Revised Versions of this License.
+
+The Free Software Foundation may publish revised and/or new versions of the GNU
+General Public License from time to time. Such new versions will be similar in spirit
+to the present version, but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program specifies that
+a certain numbered version of the GNU General Public License “or any later
+version” applies to it, you have the option of following the terms and
+conditions either of that numbered version or of any later version published by the
+Free Software Foundation. If the Program does not specify a version number of the GNU
+General Public License, you may choose any version ever published by the Free
+Software Foundation.
+
+If the Program specifies that a proxy can decide which future versions of the GNU
+General Public License can be used, that proxy's public statement of acceptance of a
+version permanently authorizes you to choose that version for the Program.
+
+Later license versions may give you additional or different permissions. However, no
+additional obligations are imposed on any author or copyright holder as a result of
+your choosing to follow a later version.
+
+### 15. Disclaimer of Warranty.
+
+THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER
+EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
+QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
+DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+### 16. Limitation of Liability.
+
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
+COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS
+PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
+INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE
+OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE
+WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+### 17. Interpretation of Sections 15 and 16.
+
+If the disclaimer of warranty and limitation of liability provided above cannot be
+given local legal effect according to their terms, reviewing courts shall apply local
+law that most closely approximates an absolute waiver of all civil liability in
+connection with the Program, unless a warranty or assumption of liability accompanies
+a copy of the Program in return for a fee.
+
+END OF TERMS AND CONDITIONS
+
+## How to Apply These Terms to Your New Programs
+
+If you develop a new program, and you want it to be of the greatest possible use to
+the public, the best way to achieve this is to make it free software which everyone
+can redistribute and change under these terms.
+
+To do so, attach the following notices to the program. It is safest to attach them
+to the start of each source file to most effectively state the exclusion of warranty;
+and each file should have at least the “copyright” line and a pointer to
+where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program does terminal interaction, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type 'show c' for details.
+
+The hypothetical commands 'show w' and 'show c' should show the appropriate parts of
+the General Public License. Of course, your program's commands might be different;
+for a GUI interface, you would use an “about box”.
+
+You should also get your employer (if you work as a programmer) or school, if any, to
+sign a “copyright disclaimer” for the program, if necessary. For more
+information on this, and how to apply and follow the GNU GPL, see
+<>.
+
+The GNU General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may consider it
+more useful to permit linking proprietary applications with the library. If this is
+what you want to do, use the GNU Lesser General Public License instead of this
+License. But first, please read
+<>.
\ No newline at end of file
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000000..cc04662ae5
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,37 @@
+# GNU Make makefile for building with Mono
+
+MONO = mono
+MSBUILD = msbuild
+
+#CONFIG = Debug
+CONFIG = Release
+
+PK3DS_EXE = pk3DS/bin/$(CONFIG)/pk3DS.exe
+
+# Note: The Mono compiler seems to dump some detritus by default in
+# /tmp, so we set TMPDIR to a more suitable location
+
+$(PK3DS_EXE): pk3DS.sln
+ mkdir -p tmp
+ TMPDIR=$(shell pwd)/tmp $(MSBUILD) /p:Configuration=$(CONFIG) $<
+
+install: $(PK3DS_EXE)
+ rm -rf pk3ds-install
+ mkdir pk3ds-install
+ cp -np */bin/$(CONFIG)/*.dll pk3ds-install
+ cp -np */bin/$(CONFIG)/*.exe pk3ds-install
+
+run: $(PK3DS_EXE)
+ $(MONO) $<
+
+run-install: pk3ds-install/SPICA.exe
+ $(MONO) $<
+
+clean:
+ rm -rf pk3DS*/bin pk3DS*/obj
+ rm -rf pk3ds-install
+ rm -rf tmp
+
+.PHONY: clean install run run-install
+
+# EOF
diff --git a/README.md b/README.md
index d0db0014f7..64c23f3d9c 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,54 @@
-# pk3DS
-pk3DS: A package of Pokémon (3DS) ROM Editing Tools by various contributors.
+
-
-
-
+pk3DS
+
+
+
+pk3DS is a ROM editor for all 3DS Pokémon games that utilizes a variety of tools developed by a large group of contributors. pk3DS was created
+using C# and primarily focuses on its randomizer to provide users with a fresh and new experience in the beloved Pokémon games.
+
+## Table of contents
+
+- [Features](#features)
+- [Installation](#installation)
+- [Usage](#usage)
+- [Support](#support)
+
+## Features
+
+Our editor features a vast variety of randomizers to make every run as unique as possible. The Randomizers currently available are:
+
+- Trainer Battles (Pokemon / Items / Moves / Abilities / Difficulty / Classes)
+- Wild Encounters (Species, Level, Gen/Legend Specific, ORAS DexNav won't crash!)
+- Personal Data (Pokemon Types / Stats / Abilities / TM Learnset)
+- Move Randomizer (Type / Damage Category)
+- Move Learnset (Level Up / Egg Move)
+- Evolutions
+- TM Moves
+- Special Mart Inventory
+
+## Installation
+
+To download pk3DS, all you need to do is go into our [forum page](https://projectpokemon.org/home/forums/topic/34377-pk3ds-pok%C3%A9mon-3ds-rom-editor-and-randomizer/) and following the instructions there.
+
+## Usage
+
+To begin using pk3DS you must first download the pk3DS editor zip file. Once you've downloaded the zip file for the editor, dump your ROM from the 3DS Pokémon game of your choosing.
+
+Place the files in the same folder then simply run the pk3DS.exe file.
+Once you open up the executable you can begin having fun with our editor and randomizing all the attributes and characteristics of the game to your liking.
+Below are some images of how the editor should look when you run it.
+
+
+
+
+## Building
+
+pk3DS is a Windows Forms application which requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0).
+
+The executable can be built with any compiler that supports C# 14.
+
+## Support
+
+If any bugs or errors are caught or experienced come to our [forum page](https://projectpokemon.org/home/forums/topic/34377-pk3ds-pok%C3%A9mon-3ds-rom-editor-and-randomizer/) and communicate with us on what the issue is.
+Many community members as well as contributors are active and can be found there.
diff --git a/pk3DS.Core/CTR/AES.cs b/pk3DS.Core/CTR/AES.cs
index 9aafd90930..ea77fa6fa1 100644
--- a/pk3DS.Core/CTR/AES.cs
+++ b/pk3DS.Core/CTR/AES.cs
@@ -1,97 +1,96 @@
using System;
+using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
-namespace pk3DS.Core.CTR
+namespace pk3DS.Core.CTR;
+
+public class AesCtr
{
- public class AesCtr
- {
- private readonly AesManaged Aes = new AesManaged();
- private readonly ICryptoTransform Encryptor;
- private readonly AesCounter Counter;
+ private readonly Aes Aes = Aes.Create();
+ private readonly ICryptoTransform Encryptor;
+ private readonly AesCounter Counter;
- public AesCtr(byte[] key, byte[] iv)
- {
- Aes.Key = key;
- Aes.Mode = CipherMode.ECB;
- Aes.Padding = PaddingMode.None;
- Counter = new AesCounter(iv);
- Encryptor = Aes.CreateEncryptor();
- }
+ public AesCtr(byte[] key, byte[] iv)
+ {
+ Aes.Key = key;
+ Aes.Mode = CipherMode.ECB;
+ Aes.Padding = PaddingMode.None;
+ Counter = new AesCounter(iv);
+ Encryptor = Aes.CreateEncryptor();
+ }
- public AesCtr(byte[] key, ulong PartitionID, ulong InitialCount)
- {
- Aes.Key = key;
- Aes.Mode = CipherMode.ECB;
- Aes.Padding = PaddingMode.None;
- Counter = new AesCounter(PartitionID, InitialCount);
- Encryptor = Aes.CreateEncryptor();
- }
+ public AesCtr(byte[] key, ulong PartitionID, ulong InitialCount)
+ {
+ Aes.Key = key;
+ Aes.Mode = CipherMode.ECB;
+ Aes.Padding = PaddingMode.None;
+ Counter = new AesCounter(PartitionID, InitialCount);
+ Encryptor = Aes.CreateEncryptor();
+ }
- public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
+ public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
+ {
+ int BlockLength;
+ for (int i = 0; i < inputCount; i += BlockLength)
{
- int BlockLength;
- for (int i = 0; i < inputCount; i += BlockLength)
+ BlockLength = inputCount - i > AesCounter.BufferSize ? AesCounter.BufferSize : inputCount - i;
+ Encryptor.TransformBlock(Counter.ManageBufferCounters(BlockLength), 0, BlockLength, outputBuffer, outputOffset + i);
+ for (int BlockWalker = i; BlockWalker < i + BlockLength; BlockWalker += 8)
{
- BlockLength = inputCount - i > AesCounter.BufferSize ? AesCounter.BufferSize : inputCount - i;
- Encryptor.TransformBlock(Counter.ManageBufferCounters(BlockLength), 0, BlockLength, outputBuffer, outputOffset + i);
- for (int BlockWalker = i; BlockWalker < i + BlockLength; BlockWalker += 8)
- {
- Array.Copy(BitConverter.GetBytes(BitConverter.ToInt64(outputBuffer, outputOffset + BlockWalker) ^ BitConverter.ToInt64(inputBuffer, inputOffset + BlockWalker)), 0, outputBuffer, outputOffset + BlockWalker, 8);
- }
+ Array.Copy(BitConverter.GetBytes(BitConverter.ToInt64(outputBuffer, outputOffset + BlockWalker) ^ BitConverter.ToInt64(inputBuffer, inputOffset + BlockWalker)), 0, outputBuffer, outputOffset + BlockWalker, 8);
}
- return inputCount;
}
+ return inputCount;
}
- public class AesCounter
- {
- public const int BufferSize = 0x400000; //4 MB Buffer
- private readonly byte[] Counter = new byte[0x10];
- private readonly byte[] Buffer = new byte[BufferSize];
+}
- public AesCounter(ulong high, ulong low)
- {
- Array.Copy(BitConverter.GetBytes(high).Reverse().ToArray(), Counter, 0x8);
- Array.Copy(BitConverter.GetBytes(low).Reverse().ToArray(), 0, Counter, 0x8, 0x8);
- }
+public class AesCounter
+{
+ public const int BufferSize = 0x400000; //4 MB Buffer
+ private readonly byte[] Counter = new byte[0x10];
+ private readonly byte[] Buffer = new byte[BufferSize];
- public AesCounter(byte[] iv)
- {
- Array.Copy(BitConverter.GetBytes(BitConverter.ToUInt64(iv, 0)).Reverse().ToArray(), Counter, 0x10);
- }
+ public AesCounter(ulong high, ulong low)
+ {
+ Array.Copy(((IEnumerable)BitConverter.GetBytes(high)).Reverse().ToArray(), Counter, 0x8);
+ Array.Copy(((IEnumerable)BitConverter.GetBytes(low)).Reverse().ToArray(), 0, Counter, 0x8, 0x8);
+ }
- public void Increment()
- {
- for (int i = Counter.Length - 1; i >= 0; i--)
- {
- if (++Counter[i] != 0)
- return;
- }
- }
+ public AesCounter(byte[] iv)
+ {
+ Array.Copy(((IEnumerable)BitConverter.GetBytes(BitConverter.ToUInt64(iv, 0))).Reverse().ToArray(), Counter, 0x10);
+ }
- public byte[] ManageBufferCounters(int size)
+ public void Increment()
+ {
+ for (int i = Counter.Length - 1; i >= 0; i--)
{
- for (int i = 0; i < size; i += 0x10)
- {
- Array.Copy(Counter, 0, Buffer, i, 0x10);
- Increment();
- }
- return Buffer;
+ if (++Counter[i] != 0)
+ return;
}
+ }
- public ulong SwapBytes(ulong value)
+ public byte[] ManageBufferCounters(int size)
+ {
+ for (int i = 0; i < size; i += 0x10)
{
- ulong uvalue = value;
- ulong swapped =
- 0x00000000000000FF & (uvalue >> 56)
- | 0x000000000000FF00 & (uvalue >> 40)
- | 0x0000000000FF0000 & (uvalue >> 24)
- | 0x00000000FF000000 & (uvalue >> 8)
- | 0x000000FF00000000 & (uvalue << 8)
- | 0x0000FF0000000000 & (uvalue << 24)
- | 0x00FF000000000000 & (uvalue << 40)
- | 0xFF00000000000000 & (uvalue << 56);
- return swapped;
+ Array.Copy(Counter, 0, Buffer, i, 0x10);
+ Increment();
}
+ return Buffer;
}
-}
+
+ public static ulong SwapBytes(ulong value)
+ {
+ ulong uvalue = value;
+ return (0x00000000000000FF & (uvalue >> 56))
+ | (0x000000000000FF00 & (uvalue >> 40))
+ | (0x0000000000FF0000 & (uvalue >> 24))
+ | (0x00000000FF000000 & (uvalue >> 8))
+ | (0x000000FF00000000 & (uvalue << 8))
+ | (0x0000FF0000000000 & (uvalue << 24))
+ | (0x00FF000000000000 & (uvalue << 40))
+ | (0xFF00000000000000 & (uvalue << 56));
+ }
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/ALYT.cs b/pk3DS.Core/CTR/ALYT.cs
index a61734c6cf..dc720c4ca2 100644
--- a/pk3DS.Core/CTR/ALYT.cs
+++ b/pk3DS.Core/CTR/ALYT.cs
@@ -1,12 +1,242 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
+using System.Collections.Generic;
+using System.IO;
using System.Text;
-namespace CTR
+namespace pk3DS.Core.CTR;
+
+///
+/// Archive LaYouT container
+///
+/// File length is padded to nearest 0x80
+public class ALYT
{
- public class ALYT
+ private const string Identifier = nameof(ALYT);
+ public string Magic; // 0x00
+ public short unk4; // 0x04
+ public short unk6; // 0x06
+ public int LTBLOffset; // 0x08
+ public int LTBLSize; // 0x0C
+ public int LMTLOffset; // 0x10
+ public int LMTLSize; // 0x14
+ public int LFNLOffset; // 0x18
+ public int LFNLSize; // 0x1C
+
+ public int DataOffset; // 0x20
+ public int DataSize; // 0x24
+
+ public LTBL LTBL;
+ public LMTL LMTL;
+ public LFNL LFNL;
+ public Contents Content;
+ public byte[] Data;
+
+ public string FileName { get; }
+ public string FilePath { get; }
+ public string Extension { get; }
+ public bool SigMatches => Magic == Identifier;
+
+ public ALYT(string path)
+ {
+ FileName = Path.GetFileNameWithoutExtension(path);
+ FilePath = Path.GetDirectoryName(path);
+ Extension = Path.GetExtension(path);
+
+ using var br = new BinaryReader(File.OpenRead(path));
+ ReadALYT(br);
+ }
+
+ public ALYT(byte[] data)
+ {
+ using var ms = new MemoryStream(data);
+ using var br = new BinaryReader(ms);
+ ReadALYT(br);
+ }
+
+ public ALYT(Stream ms)
+ {
+ using var br = new BinaryReader(ms);
+ ReadALYT(br);
+ }
+
+ private void ReadALYT(BinaryReader br)
{
+ ReadHeader(br);
+ LTBL = new LTBL(br, (LTBLSize - 8) / 4);
+ LMTL = new LMTL(br, (LMTLSize - 8) / 4);
+ LFNL = new LFNL(br, (LFNLSize - 8) / 4);
+ Content = new Contents(br, this);
+ }
+ private void ReadHeader(BinaryReader br)
+ {
+ Magic = new string(br.ReadChars(4));
+ if (!SigMatches)
+ return;
+ unk4 = br.ReadInt16();
+ unk6 = br.ReadInt16();
+ LTBLOffset = br.ReadInt32();
+ LTBLSize = br.ReadInt32();
+ LMTLOffset = br.ReadInt32();
+ LMTLSize = br.ReadInt32();
+ LFNLOffset = br.ReadInt32();
+ LFNLSize = br.ReadInt32();
+ DataOffset = br.ReadInt32();
+ DataSize = br.ReadInt32();
+ }
+
+ public class Contents
+ {
+ public readonly string[] Labels;
+ public readonly string[] Symbols;
+
+ public Contents(BinaryReader br, ALYT alyt)
+ {
+ br.BaseStream.Position = alyt.DataOffset;
+ Labels = new string[br.ReadInt32()];
+ for (int i = 0; i < Labels.Length; i++)
+ Labels[i] = ReadString(br, 0x40);
+
+ Symbols = new string[br.ReadInt32()];
+ for (int i = 0; i < Symbols.Length; i++)
+ Symbols[i] = ReadString(br, 0x20);
+
+ // skip to end of section
+ // this is bad
+ while (br.PeekChar() == 0)
+ br.ReadByte();
+
+ int len = (int)br.BaseStream.Position - alyt.DataOffset;
+ len = alyt.DataSize - len;
+ alyt.Data = br.ReadBytes(len);
+ }
+
+ public static string ReadString(BinaryReader br, int skip)
+ {
+ var sb = new StringBuilder();
+ var ofs = br.BaseStream.Position;
+ while (true)
+ {
+ var c = (char)br.ReadByte();
+ if (c == 0)
+ {
+ br.BaseStream.Position = ofs + skip;
+ return sb.ToString();
+ }
+ sb.Append(c);
+ }
+ }
+ }
+
+ ///
+ /// Rips out the data portion of the ALYT, assuming the ALYT is partially valid.
+ ///
+ public static byte[] GetData(string path)
+ {
+ using var br = new BinaryReader(File.OpenRead(path));
+ return GetData(br);
+ }
+
+ ///
+ /// Rips out the data portion of the ALYT, assuming the ALYT is partially valid.
+ ///
+ public static byte[] GetData(byte[] data)
+ {
+ using var ms = new MemoryStream(data);
+ using var br = new BinaryReader(ms);
+ return GetData(br);
+ }
+
+ ///
+ /// Rips out the data portion of the ALYT, assuming the ALYT is partially valid.
+ ///
+ public static byte[] GetData(Stream ms)
+ {
+ using var br = new BinaryReader(ms);
+ return GetData(br);
+ }
+
+ private static byte[] GetData(BinaryReader br)
+ {
+ if (br.BaseStream.Length <= 0x80)
+ return null;
+ if (Identifier != new string(br.ReadChars(4)))
+ return null; // not ALYT
+
+ br.BaseStream.Position = 0x20; // DataOffset
+ int start = br.ReadInt32();
+ int length = br.ReadInt32();
+
+ br.BaseStream.Position = start;
+ int count40 = br.ReadInt32();
+ br.BaseStream.Position += count40 * 0x40;
+
+ int count20 = br.ReadInt32();
+ br.BaseStream.Position += count20 * 0x20;
+
+ // skip to end of section
+ // this is bad
+ while (br.PeekChar() == 0)
+ br.ReadByte();
+
+ int len = (int)br.BaseStream.Position - start;
+ len = length - len;
+ return br.ReadBytes(len);
}
}
+
+public class LTBL
+{
+ private const string Identifier = nameof(LTBL);
+ public string Magic; // 0x00
+ public short unk4; // 0x04
+ public short unk6; // 0x06
+ public List Values;
+
+ public LTBL(BinaryReader br, int count)
+ {
+ Magic = new string(br.ReadChars(Identifier.Length));
+ unk4 = br.ReadInt16();
+ unk6 = br.ReadInt16();
+ Values = new List(count);
+ for (int i = 0; i < count; i++)
+ Values.Add((short)br.ReadInt32());
+ }
+}
+
+public class LMTL
+{
+ private const string Identifier = nameof(LMTL);
+ public string Magic; // 0x00
+ public short unk4; // 0x04
+ public short unk6; // 0x06
+ public List Values;
+
+ public LMTL(BinaryReader br, int count)
+ {
+ Magic = new string(br.ReadChars(Identifier.Length));
+ unk4 = br.ReadInt16();
+ unk6 = br.ReadInt16();
+ Values = new List(count);
+ for (int i = 0; i < count; i++)
+ Values.Add((short)br.ReadInt32());
+ }
+}
+
+public class LFNL
+{
+ private const string Identifier = nameof(LFNL);
+ public string Magic; // 0x00
+ public short unk4; // 0x04
+ public short unk6; // 0x06
+ public List Values;
+
+ public LFNL(BinaryReader br, int count)
+ {
+ Magic = new string(br.ReadChars(Identifier.Length));
+ unk4 = br.ReadInt16();
+ unk6 = br.ReadInt16();
+ Values = new List(count);
+ for (int i = 0; i < count; i++)
+ Values.Add((short)br.ReadInt32());
+ }
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/BCLIM.cs b/pk3DS.Core/CTR/BCLIM.cs
deleted file mode 100644
index 5cc4942472..0000000000
--- a/pk3DS.Core/CTR/BCLIM.cs
+++ /dev/null
@@ -1,901 +0,0 @@
-using System;
-using System.Drawing;
-using System.Drawing.Imaging;
-using System.IO;
-using System.Runtime.InteropServices;
-using pk3DS.Core.Properties; // For other projects, replace this line with the namespace that contains your ETC1Lib.dll resource.
-
-namespace pk3DS.Core.CTR
-{
- public static class BCLIM
- {
- public static void openFile(string path, bool autosave = false, bool crop = true, char format = 'X')
- {
- // Handle file
- if (!File.Exists(path)) throw new Exception("Can only accept files, not folders");
- string ext = Path.GetExtension(path);
- if (ext == ".png")
- makeBCLIM(path, format);
- else if (ext == ".bin" || ext == ".bclim")
- makeBMP(path, autosave, crop);
- }
-
- public static byte[] IMGToBCLIM(Image img, char fc)
- {
- Bitmap mBitmap = new Bitmap(img);
- MemoryStream ms = new MemoryStream();
- int bclimformat = 7; // Init to default (for X)
-
- if (fc == 'X')
- write16BitColorPalette(mBitmap, ref ms);
- else
- {
- bclimformat = Convert.ToInt16(fc.ToString(), 16);
- try
- {
- writeGeneric(bclimformat, mBitmap, ref ms);
- }
- catch (Exception e)
- {
- System.Media.SystemSounds.Beep.Play();
- System.Diagnostics.Debug.WriteLine(e.ToString());
- }
- }
-
- long datalength = ms.Length;
- // Write the CLIM + imag data.
- using (BinaryWriter bw = new BinaryWriter(ms))
- {
- bw.Write((uint)0x4D494C43); // CLIM
- bw.Write((ushort)0xFEFF); // BOM
- bw.Write((uint)0x14);
- bw.Write((ushort)0x0202); // 2 2
- bw.Write((uint)(datalength + 0x28));
- bw.Write((uint)1);
- bw.Write((uint)0x67616D69);
- bw.Write((uint)0x10);
- bw.Write((ushort)mBitmap.Width);
- bw.Write((ushort)mBitmap.Height);
- bw.Write((uint)bclimformat);
- bw.Write((uint)datalength);
- }
- return ms.ToArray();
- }
- public static byte[] getBCLIM(string path, char fc)
- {
- byte[] byteArray = File.ReadAllBytes(path);
- using (Stream BitmapStream = new MemoryStream(byteArray)) // Open the file, even if it is in use.
- {
- Image img = Image.FromStream(BitmapStream);
- return IMGToBCLIM(img, fc);
- }
- }
- public static Image makeBCLIM(string path, char fc)
- {
- byte[] bclim = getBCLIM(path, fc);
- string fp = Path.GetFileNameWithoutExtension(path);
- fp = "new_" + fp.Substring(fp.IndexOf('_') + 1);
- string pp = Path.GetDirectoryName(path);
- string newPath = Path.Combine(pp, fp + ".bclim");
- File.WriteAllBytes(newPath, bclim);
-
- return makeBMP(newPath);
- }
- public static Image makeBMP(string path, bool autosave = false, bool crop = true)
- {
- CLIM bclim = analyze(path);
- if (bclim.Magic != 0x4D494C43)
- {
- System.Media.SystemSounds.Beep.Play();
- return null;
- }
-
- // Interpret data.
- int f = bclim.FileFormat;
- if (f > 13)
- {
- System.Media.SystemSounds.Exclamation.Play();
- return null;
- }
-
- Bitmap img;
- if (f == 7 && BitConverter.ToUInt16(bclim.Data, 0) == 2)
- // PKM XY Format 7 (Color Palette)
- img = getIMG_XY7(bclim);
- else if (f == 10 || f == 11)
- img = getIMG_ETC(bclim);
- else
- img = getIMG(bclim);
-
- if (img == null) return null;
- Rectangle cropRect = new Rectangle(0, 0, bclim.Width, bclim.Height);
- Bitmap CropBMP = new Bitmap(cropRect.Width, cropRect.Height);
- using (Graphics g = Graphics.FromImage(CropBMP))
- {
- g.DrawImage(img,
- new Rectangle(0, 0, CropBMP.Width, CropBMP.Height),
- cropRect,
- GraphicsUnit.Pixel);
- }
- if (!autosave) return !crop ? img : CropBMP;
-
- using (MemoryStream ms = new MemoryStream())
- {
- //error will throw from here
- CropBMP.Save(ms, ImageFormat.Png);
- byte[] data = ms.ToArray();
- File.WriteAllBytes(bclim.FilePath + "\\" + bclim.FileName + ".png", data);
- }
- return !crop ? img : CropBMP;
- }
- // Bitmap Data Writing
- public static Bitmap getIMG(int width, int height, byte[] bytes, int f)
- {
- Bitmap img = new Bitmap(width, height);
- int area = img.Width * img.Height;
- // Tiles Per Width
- int p = gcm(img.Width, 8) / 8;
- if (p == 0) p = 1;
- using (Stream BitmapStream = new MemoryStream(bytes))
- using (BinaryReader br = new BinaryReader(BitmapStream))
- for (uint i = 0; i < area; i++) // for every pixel
- {
- uint x;
- uint y;
- d2xy(i % 64, out x, out y);
- uint tile = i / 64;
-
- // Shift Tile Coordinate into Tilemap
- x += (uint)(tile % p) * 8;
- y += (uint)(tile / p) * 8;
-
- // Get Color
- Color c;
- switch (f)
- {
- case 0x0: // L8 // 8bit/1 byte
- case 0x1: // A8
- case 0x2: // LA4
- c = DecodeColor(br.ReadByte(), f);
- break;
- case 0x3: // LA8 // 16bit/2 byte
- case 0x4: // HILO8
- case 0x5: // RGB565
- case 0x8: // RGBA4444
- case 0x7: // RGBA5551
- c = DecodeColor(br.ReadUInt16(), f);
- break;
- case 0x6: // RGB8: // 24bit
- byte[] data = br.ReadBytes(3); Array.Resize(ref data, 4);
- c = DecodeColor(BitConverter.ToUInt32(data, 0), f);
- break;
- case 0x9: // RGBA8888
- c = DecodeColor(br.ReadUInt32(), f);
- break;
- case 0xC: // L4
- case 0xD: // A4 // 4bit - Do 2 pixels at a time.
- uint val = br.ReadByte();
- img.SetPixel((int)x, (int)y, DecodeColor(val & 0xF, f)); // lowest bits for the low pixel
- i++; x++;
- c = DecodeColor(val >> 4, f); // highest bits for the high pixel
- break;
- default: throw new Exception("Invalid FileFormat.");
- }
- img.SetPixel((int)x, (int)y, c);
- }
- return img;
- }
- public static Bitmap getIMG(CLIM bclim)
- {
- if (bclim.FileFormat == 7 && BitConverter.ToUInt16(bclim.Data, 0) == 2) // XY7
- return getIMG_XY7(bclim);
- if (bclim.FileFormat == 10 || bclim.FileFormat == 11) // Use ETC1 to get image instead.
- return getIMG_ETC(bclim);
- // New Image
- int w = nlpo2(gcm(bclim.Width, 8));
- int h = nlpo2(gcm(bclim.Height, 8));
- int f = bclim.FileFormat;
- int area = w * h;
- if (f == 9 && area > bclim.Data.Length / 4)
- {
- w = gcm(bclim.Width, 8);
- h = gcm(bclim.Height, 8);
- }
- // Build Image
- return getIMG(w, h, bclim.Data, f);
- }
- public static Bitmap getIMG_XY7(CLIM bclim)
- {
- Bitmap img = new Bitmap(bclim.BaseSize, bclim.BaseSize);
- using (Stream BitmapStream = new MemoryStream(bclim.Data))
- using (BinaryReader br = new BinaryReader(BitmapStream))
- {
- // Fetch Color stuff.
- if (br.ReadUInt16() != 2) return null;
- ushort colors = br.ReadUInt16();
- Color[] ca = new Color[colors];
- for (int i = 0; i < colors; i++)
- ca[i] = DecodeColor(br.ReadUInt16(), 7);
-
- // Coordinates
- // Colors
- // Tiles Per Width
- int p = gcm(img.Width, 8) / 8;
- if (p == 0) p = 1;
-
- for (uint i = 0; i < bclim.BaseSize * bclim.BaseSize; i++) // for every pixel
- {
- uint x;
- uint y;
- d2xy(i % 64, out x, out y);
- uint tile = i / 64;
-
- // Shift Tile Coordinate into Tilemap
- x += (uint)(tile % p) * 8;
- y += (uint)(tile / p) * 8;
-
- byte val = br.ReadByte();
- if (colors <= 0x10) // Handle 2 pixels at a time
- {
- img.SetPixel((int)x, (int)y, ca[val >> 4]);
- x++; i++; val &= 0xF;
- img.SetPixel((int)x, (int)y, ca[val]);
- }
- else //1bpp instead of .5, handle 2 pixels at a time the same way for no reason
- {
- img.SetPixel((int)x, (int)y, ca[val]);
- x++; i++; val = br.ReadByte();
- img.SetPixel((int)x, (int)y, ca[val]);
- }
- }
- }
- return img;
- }
- public static Bitmap getIMG_ETC(CLIM bclim)
- {
- Bitmap img = new Bitmap(Math.Max(nlpo2(bclim.Width), 16), Math.Max(nlpo2(bclim.Height), 16));
- string dllpath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\ETC1Lib.dll";
- if (!File.Exists(dllpath)) File.WriteAllBytes(dllpath, Resources.ETC1Lib);
-
- try
- {
- /* http://jul.rustedlogic.net/thread.php?id=17312
- * Much of this code is taken/modified from Tharsis. Thank you to Tharsis's creator, xdaniel.
- * https://github.com/xdanieldzd/Tharsis
- */
-
- /* Get compressed data & handle to it */
- byte[] textureData = bclim.Data;
- //textureData = switchEndianness(textureData, 0x10);
- ushort[] input = new ushort[textureData.Length/sizeof (ushort)];
- Buffer.BlockCopy(textureData, 0, input, 0, textureData.Length);
- GCHandle pInput = GCHandle.Alloc(input, GCHandleType.Pinned);
-
- /* Marshal data around, invoke ETC1.dll for conversion, etc */
- uint size1 = 0;
- UInt16 w = (ushort)img.Width, h = (ushort)img.Height;
-
- ETC1.ConvertETC1(IntPtr.Zero, ref size1, IntPtr.Zero, w, h, bclim.FileFormat == 0xB); // true = etc1a4, false = etc1
- // System.Diagnostics.Debug.WriteLine(size1);
- uint[] output = new uint[size1];
- GCHandle pOutput = GCHandle.Alloc(output, GCHandleType.Pinned);
- ETC1.ConvertETC1(pOutput.AddrOfPinnedObject(), ref size1, pInput.AddrOfPinnedObject(), w, h, bclim.FileFormat == 0xB);
- pOutput.Free();
- pInput.Free();
-
-
- /* Unscramble if needed // could probably be done in ETC1Lib.dll, it's probably pretty ugly, but whatever... */
- /* Non-square code blocks could need some cleanup, verification, etc. as well... */
- uint[] finalized = new uint[output.Length];
-
- // Act if it's square because BCLIM swizzling is stupid
- Buffer.BlockCopy(output, 0, finalized, 0, finalized.Length);
-
- byte[] tmp = new byte[finalized.Length];
- Buffer.BlockCopy(finalized, 0, tmp, 0, tmp.Length);
- byte[] imgData = tmp;
-
- for (int i = 0; i < w; i++)
- {
- for (int j = 0; j < h; j++)
- {
- int k = (j + i*img.Height)*4;
- img.SetPixel(i, j, Color.FromArgb(imgData[k + 3], imgData[k], imgData[k + 1], imgData[k + 2]));
- }
- }
- // Image is 13 instead of 12
- // 24 34
- img.RotateFlip(RotateFlipType.Rotate90FlipX);
- if (w > h)
- {
- // Image is now in appropriate order, but the shifting is messed up. Let's fix that.
- Bitmap img2 = new Bitmap(Math.Max(nlpo2(bclim.Width), 16), Math.Max(nlpo2(bclim.Height), 16));
- for (int y = 0; y < Math.Max(nlpo2(bclim.Width), 16); y += 8)
- {
- for (int x = 0; x < Math.Max(nlpo2(bclim.Height), 16); x++)
- {
- for (int j = 0; j < 8; j++)
- // Treat every 8 vertical pixels as 1 pixel for purposes of calculation, add to offset later.
- {
- int x1 = (x + y/8*h)%img2.Width; // Reshift x
- int y1 = (x + y/8*h)/img2.Width*8; // Reshift y
- img2.SetPixel(x1, y1 + j, img.GetPixel(x, y + j)); // Reswizzle
- }
- }
- }
- img = img2;
- }
- else if (h > w)
- {
- Bitmap img2 = new Bitmap(Math.Max(nlpo2(bclim.Width), 16), Math.Max(nlpo2(bclim.Height), 16));
- for (int y = 0; y < Math.Max(nlpo2(bclim.Width), 16); y += 8)
- {
- for (int x = 0; x < Math.Max(nlpo2(bclim.Height), 16); x++)
- {
- for (int j = 0; j < 8; j++)
- // Treat every 8 vertical pixels as 1 pixel for purposes of calculation, add to offset later.
- {
- int x1 = x%img2.Width; // Reshift x
- int y1 = (x + y/8*h)/img2.Width*8; // Reshift y
- img2.SetPixel(x1, y1 + j, img.GetPixel(x, y + j)); // Reswizzle
- }
- }
- }
- img = img2;
- }
- }
- catch { }
- return img;
- }
-
- // BCLIM Data Writing
- public static int write16BitColorPalette(Bitmap img, ref MemoryStream ms)
- {
- using (Stream pixelcolors = new MemoryStream())
- using (BinaryWriter bz = new BinaryWriter(pixelcolors))
- {
- // Set up our basis.
- bool under16colors = false;
- int colors = getColorCount(img);
- Color[] pcs = new Color[colors];
- if (colors < 16) under16colors = true;
- uint div = 1;
- if (under16colors)
- div = 2;
-
- if (colors > 70) throw new Exception("Too many colors");
-
- // Set up a new reverse image to build into.
- int w = gcm(img.Width, 8);
- int h = gcm(img.Height, 8);
- w = Math.Max(nlpo2(w), nlpo2(h));
- h = w;
- byte[] pixelarray = new Byte[w * h];
-
- const int colorformat = 2;
- int ctr = 1;
-
- pcs[0] = Color.FromArgb(0, 0xFF, 0xFF, 0xFF);
-
- int p = gcm(w, 8) / 8;
- if (p == 0) p = 1;
- int d = 0;
- for (uint i = 0; i < pixelarray.Length; i++)
- {
- d = (int)(i / div);
- // Get Tile Coordinate
- uint x;
- uint y;
- d2xy(i % 64, out x, out y);
-
- // Get Shift Tile
- uint tile = i / 64;
-
- // Shift Tile Coordinate into Tilemap
- x += (uint)(tile % p) * 8;
- y += (uint)(tile / p) * 8;
- if (x >= img.Width || y >= img.Height) // Don't try to access any pixel data outside of our bounds.
- { i++; continue; } // Goto next tile.
-
- // Get Color of Pixel
- Color c = img.GetPixel((int)x, (int)y);
-
- // Color Table Building Logic
- int index = Array.IndexOf(pcs, c);
- if (c.A == 0) index = 0;
- if (index < 0) // If new color
- { pcs[ctr] = c; index = ctr; ctr++; } // Add it to color list
-
- // Add pixel to pixeldata
- if (under16colors) index = index << 4;
- pixelarray[i / div] = (byte)index;
- if (!under16colors) continue;
-
- c = img.GetPixel((int)x + 1, (int)y);
- index = Array.IndexOf(pcs, c);
- if (c.A == 0) index = 0;
- if (index < 0) // If new color
- { pcs[ctr] = c; index = ctr; ctr++; }
- pixelarray[i / div] |= (byte)index;
- i++;
- }
-
- // Write Intro
- bz.Write((ushort)colorformat); bz.Write((ushort)ctr);
- // Write Colors
- for (int i = 0; i < ctr; i++)
- bz.Write(GetRGBA5551(pcs[i])); // Write byte array.
- // Write Pixel Data
- for (uint i = 0; i < d; i++)
- bz.Write(pixelarray[i]);
- // Write Padding
- while (pixelcolors.Length < nlpo2((int)pixelcolors.Length))
- bz.Write((byte)0);
- // Copy to main CLIM.
- pixelcolors.Position = 0; pixelcolors.CopyTo(ms);
- }
- return 7;
- }
- public static void writeGeneric(int format, Bitmap img, ref MemoryStream ms, bool rectangle = true)
- {
- BinaryWriter bz = new BinaryWriter(ms);
- bz.Write(getPixelData(img, format, rectangle));
- bz.Flush();
- }
-
- public static byte[] getPixelData(Bitmap img, int format, bool rectangle = true)
- {
- int w = img.Width;
- int h = img.Height;
-
- bool perfect = w == h && w != 0 && (w & (w - 1)) == 0;
- if (!perfect) // Check if square power of two, else resize
- {
- // Square Format Checks
- if (rectangle && Math.Min(img.Width, img.Height) < 32)
- {
- w = nlpo2(img.Width);
- h = nlpo2(img.Height);
- }
- else
- {
- w = h = Math.Max(nlpo2(w), nlpo2(h)); // else resize
- }
- }
-
- using (MemoryStream mz = new MemoryStream())
- using (BinaryWriter bz = new BinaryWriter(mz))
- {
- int p = gcm(w, 8) / 8;
- if (p == 0) p = 1;
- for (uint i = 0; i < w * h; i++)
- {
- uint x;
- uint y;
- d2xy(i % 64, out x, out y);
-
- // Get Shift Tile
- uint tile = i / 64;
-
- // Shift Tile Coordinate into Tilemap
- x += (uint)(tile % p) * 8;
- y += (uint)(tile / p) * 8;
-
- // Don't write data
- Color c;
- if (x >= img.Width || y >= img.Height)
- { c = Color.FromArgb(0, 0, 0, 0); }
- else
- { c = img.GetPixel((int)x, (int)y); if (c.A == 0) c = Color.FromArgb(0, 86, 86, 86); }
-
- switch (format)
- {
- case 0: bz.Write(GetL8(c)); break; // L8
- case 1: bz.Write(GetA8(c)); break; // A8
- case 2: bz.Write(GetLA4(c)); break; // LA4(4)
- case 3: bz.Write(GetLA8(c)); break; // LA8(8)
- case 4: bz.Write(GetHILO8(c)); break; // HILO8
- case 5: bz.Write(GetRGB565(c)); break; // RGB565
- case 6:
- {
- bz.Write(c.B);
- bz.Write(c.G);
- bz.Write(c.R); break;
- }
- case 7: bz.Write(GetRGBA5551(c)); break; // RGBA5551
- case 8: bz.Write(GetRGBA4444(c)); break; // RGBA4444
- case 9: bz.Write(GetRGBA8888(c)); break; // RGBA8
- case 10: throw new Exception("ETC1 not supported.");
- case 11: throw new Exception("ETC1A4 not supported.");
- case 12:
- {
- byte val = (byte)(GetL8(c) / 0x11); // First Pix // L4
- { c = img.GetPixel((int)x, (int)y); if (c.A == 0) c = Color.FromArgb(0, 0, 0, 0); }
- val |= (byte)((GetL8(c) / 0x11) << 4); i++;
- bz.Write(val); break;
- }
- case 13:
- {
- byte val = (byte)(GetA8(c) / 0x11); // First Pix // L4
- { c = img.GetPixel((int)x, (int)y); }
- val |= (byte)((GetA8(c) / 0x11) << 4); i++;
- bz.Write(val); break;
- }
- }
- }
- if (!perfect)
- while (mz.Length < nlpo2((int)mz.Length)) // pad
- bz.Write((byte)0);
- return mz.ToArray();
- }
- }
- public static int getColorCount(Bitmap img)
- {
- Color[] colors = new Color[img.Width * img.Height];
- int colorct = 1;
-
- for (int i = 0; i < colors.Length; i++)
- {
- Color c = img.GetPixel(i % img.Width, i / img.Width);
- int index = Array.IndexOf(colors, c);
- if (c.A == 0) index = 0;
- if (index >= 0) continue;
-
- colors[colorct] = c;
- colorct++;
- }
- return colorct;
- }
-
-
- internal static readonly int[] Convert5To8 = { 0x00,0x08,0x10,0x18,0x20,0x29,0x31,0x39,
- 0x41,0x4A,0x52,0x5A,0x62,0x6A,0x73,0x7B,
- 0x83,0x8B,0x94,0x9C,0xA4,0xAC,0xB4,0xBD,
- 0xC5,0xCD,0xD5,0xDE,0xE6,0xEE,0xF6,0xFF };
-
- private static Color DecodeColor(uint val, int format)
- {
- int alpha = 0xFF, red, green, blue;
- switch (format)
- {
- case 0: // L8
- return Color.FromArgb(alpha, (byte)val, (byte)val, (byte)val);
- case 1: // A8
- return Color.FromArgb((byte)val, alpha, alpha, alpha);
- case 2: // LA4
- red = (byte)(val >> 4);
- alpha = (byte)(val & 0x0F);
- return Color.FromArgb(alpha, red, red, red);
- case 3: // LA8
- red = (byte)(val >> 8 & 0xFF);
- alpha = (byte)(val & 0xFF);
- return Color.FromArgb(alpha, red, red, red);
- case 4: // HILO8
- red = (byte)(val >> 8);
- green = (byte)(val & 0xFF);
- return Color.FromArgb(alpha, red, green, 0xFF);
- case 5: // RGB565
- red = Convert5To8[(val >> 11) & 0x1F];
- green = (byte)(((val >> 5) & 0x3F) * 4);
- blue = Convert5To8[val & 0x1F];
- return Color.FromArgb(alpha, red, green, blue);
- case 6: // RGB8
- red = (byte)((val >> 16) & 0xFF);
- green = (byte)((val >> 8) & 0xFF);
- blue = (byte)(val & 0xFF);
- return Color.FromArgb(alpha, red, green, blue);
- case 7: // RGBA5551
- red = Convert5To8[(val >> 11) & 0x1F];
- green = Convert5To8[(val >> 6) & 0x1F];
- blue = Convert5To8[(val >> 1) & 0x1F];
- alpha = (val & 0x0001) == 1 ? 0xFF : 0x00;
- return Color.FromArgb(alpha, red, green, blue);
- case 8: // RGBA4444
- alpha = (byte)(0x11 * (val & 0xf));
- red = (byte)(0x11 * ((val >> 12) & 0xf));
- green = (byte)(0x11 * ((val >> 8) & 0xf));
- blue = (byte)(0x11 * ((val >> 4) & 0xf));
- return Color.FromArgb(alpha, red, green, blue);
- case 9: // RGBA8888
- red = (byte)((val >> 24) & 0xFF);
- green = (byte)((val >> 16) & 0xFF);
- blue = (byte)((val >> 8) & 0xFF);
- alpha = (byte)(val & 0xFF);
- return Color.FromArgb(alpha, red, green, blue);
- // case 10:
- // case 11:
- case 12: // L4
- return Color.FromArgb(alpha, (byte)(val * 0x11), (byte)(val * 0x11), (byte)(val * 0x11));
- case 13: // A4
- return Color.FromArgb((byte)(val * 0x11), alpha, alpha, alpha);
- default:
- return Color.White;
- }
- }
-
- // Color Conversion
- internal static byte GetL8(Color c)
- {
- byte red = c.R;
- byte green = c.G;
- byte blue = c.B;
- // Luma (Y’) = 0.299 R’ + 0.587 G’ + 0.114 B’ from wikipedia
- return (byte)(((0x4CB2 * red + 0x9691 * green + 0x1D3E * blue) >> 16) & 0xFF);
- } // L8
- internal static byte GetA8(Color c)
- {
- return c.A;
- } // A8
- internal static byte GetLA4(Color c)
- {
- return (byte)(c.A / 0x11 + c.R / 0x11 << 4);
- } // LA4
- internal static ushort GetLA8(Color c)
- {
- return (ushort)(c.A + (c.R << 8));
- } // LA8
- internal static ushort GetHILO8(Color c)
- {
- return (ushort)(c.G + (c.R << 8));
- } // HILO8
- internal static ushort GetRGB565(Color c)
- {
- int val = 0;
- // val += c.A >> 8; // unused
- val += convert8to5(c.B) >> 3;
- val += (c.G >> 2) << 5;
- val += convert8to5(c.R) << 10;
- return (ushort)val;
- } // RGB565
- // RGB8
- internal static ushort GetRGBA5551(Color c)
- {
- int val = 0;
- val += (byte)(c.A > 0x80 ? 1 : 0);
- val += convert8to5(c.R) << 11;
- val += convert8to5(c.G) << 6;
- val += convert8to5(c.B) << 1;
- ushort v = (ushort)val;
-
- return v;
- }// RGBA5551
- internal static ushort GetRGBA4444(Color c)
- {
- int val = 0;
- val += c.A / 0x11;
- val += (c.B / 0x11) << 4;
- val += (c.G / 0x11) << 8;
- val += (c.R / 0x11) << 12;
- return (ushort)val;
- }// RGBA4444
- internal static uint GetRGBA8888(Color c) // RGBA8888
- {
- uint val = 0;
- val += c.A;
- val += (uint)(c.B << 8);
- val += (uint)(c.G << 16);
- val += (uint)(c.R << 24);
- return val;
- }
-
- // Unit Conversion
- internal static byte convert8to5(int colorval)
- {
-
- byte[] Convert8to5 = { 0x00,0x08,0x10,0x18,0x20,0x29,0x31,0x39,
- 0x41,0x4A,0x52,0x5A,0x62,0x6A,0x73,0x7B,
- 0x83,0x8B,0x94,0x9C,0xA4,0xAC,0xB4,0xBD,
- 0xC5,0xCD,0xD5,0xDE,0xE6,0xEE,0xF6,0xFF };
- byte i = 0;
- while (colorval > Convert8to5[i]) i++;
- return i;
- }
- internal static uint DM2X(uint code)
- {
- return C11(code >> 0);
- }
- internal static uint DM2Y(uint code)
- {
- return C11(code >> 1);
- }
- internal static uint C11(uint x)
- {
- x &= 0x55555555; // x = -f-e -d-c -b-a -9-8 -7-6 -5-4 -3-2 -1-0
- x = (x ^ (x >> 1)) & 0x33333333; // x = --fe --dc --ba --98 --76 --54 --32 --10
- x = (x ^ (x >> 2)) & 0x0f0f0f0f; // x = ---- fedc ---- ba98 ---- 7654 ---- 3210
- x = (x ^ (x >> 4)) & 0x00ff00ff; // x = ---- ---- fedc ba98 ---- ---- 7654 3210
- x = (x ^ (x >> 8)) & 0x0000ffff; // x = ---- ---- ---- ---- fedc ba98 7654 3210
- return x;
- }
-
- ///
- /// Greatest common multiple (to round up)
- ///
- /// Number to round-up.
- /// Multiple to round-up to.
- /// Rounded up number.
- internal static int gcm(int n, int m)
- {
- return (n + m - 1) / m * m;
- }
- ///
- /// Next Largest Power of 2
- ///
- /// Input to round up to next 2^n
- /// 2^n > x && x > 2^(n-1)
- internal static int nlpo2(int x)
- {
- x--; // comment out to always take the next biggest power of two, even if x is already a power of two
- x |= x >> 1;
- x |= x >> 2;
- x |= x >> 4;
- x |= x >> 8;
- x |= x >> 16;
- return x+1;
- }
-
- // Morton Translation
- ///
- /// Combines X/Y Coordinates to a decimal ordinate.
- ///
- ///
- ///
- ///
- internal static uint xy2d(uint x, uint y)
- {
- x &= 0x0000ffff;
- y &= 0x0000ffff;
- x |= x << 8;
- y |= y << 8;
- x &= 0x00ff00ff;
- y &= 0x00ff00ff;
- x |= x << 4;
- y |= y << 4;
- x &= 0x0f0f0f0f;
- y &= 0x0f0f0f0f;
- x |= x << 2;
- y |= y << 2;
- x &= 0x33333333;
- y &= 0x33333333;
- x |= x << 1;
- y |= y << 1;
- x &= 0x55555555;
- y &= 0x55555555;
- return x | (y << 1);
- }
- ///
- /// Decimal Ordinate In to X / Y Coordinate Out
- ///
- /// Loop integer which will be decoded to X/Y
- /// Output X coordinate
- /// Output Y coordinate
- internal static void d2xy(uint d, out uint x, out uint y)
- {
- x = d;
- y = x >> 1;
- x &= 0x55555555;
- y &= 0x55555555;
- x |= x >> 1;
- y |= y >> 1;
- x &= 0x33333333;
- y &= 0x33333333;
- x |= x >> 2;
- y |= y >> 2;
- x &= 0x0f0f0f0f;
- y &= 0x0f0f0f0f;
- x |= x >> 4;
- y |= y >> 4;
- x &= 0x00ff00ff;
- y &= 0x00ff00ff;
- x |= x >> 8;
- y |= y >> 8;
- x &= 0x0000ffff;
- y &= 0x0000ffff;
- }
-
- public static CLIM analyze(byte[] data, string shortPath)
- {
- CLIM bclim = new CLIM
- {
- FileName = Path.GetFileNameWithoutExtension(shortPath),
- FilePath = Path.GetDirectoryName(shortPath),
- Extension = Path.GetExtension(shortPath)
- };
- byte[] byteArray = data;
- using (BinaryReader br = new BinaryReader(new MemoryStream(byteArray)))
- {
- br.BaseStream.Seek(br.BaseStream.Length - 0x28, SeekOrigin.Begin);
- bclim.Magic = br.ReadUInt32();
-
- bclim.BOM = br.ReadUInt16();
- bclim.CLIMLength = br.ReadUInt32();
- bclim.TileWidth = 2 << br.ReadByte();
- bclim.TileHeight = 2 << br.ReadByte();
- bclim.totalLength = br.ReadUInt32();
- bclim.Count = br.ReadUInt32();
-
- bclim.imag = br.ReadChars(4);
- bclim.imagLength = br.ReadUInt32();
- bclim.Width = br.ReadUInt16();
- bclim.Height = br.ReadUInt16();
- bclim.FileFormat = br.ReadInt32();
- bclim.dataLength = br.ReadUInt32();
-
- bclim.BaseSize = Math.Max(nlpo2(bclim.Width), nlpo2(bclim.Height));
-
- br.BaseStream.Seek(0, SeekOrigin.Begin);
- bclim.Data = br.ReadBytes((int)bclim.dataLength);
-
- return bclim;
- }
- }
- public static CLIM analyze(string path)
- {
- CLIM bclim = new CLIM
- {
- FileName = Path.GetFileNameWithoutExtension(path),
- FilePath = Path.GetDirectoryName(path),
- Extension = Path.GetExtension(path)
- };
- byte[] byteArray = File.ReadAllBytes(path);
- using (BinaryReader br = new BinaryReader(new MemoryStream(byteArray)))
- {
- br.BaseStream.Seek(br.BaseStream.Length - 0x28, SeekOrigin.Begin);
- bclim.Magic = br.ReadUInt32();
-
- bclim.BOM = br.ReadUInt16();
- bclim.CLIMLength = br.ReadUInt32();
- bclim.TileWidth = 2 << br.ReadByte();
- bclim.TileHeight = 2 << br.ReadByte();
- bclim.totalLength = br.ReadUInt32();
- bclim.Count = br.ReadUInt32();
-
- bclim.imag = br.ReadChars(4);
- bclim.imagLength = br.ReadUInt32();
- bclim.Width = br.ReadUInt16();
- bclim.Height = br.ReadUInt16();
- bclim.FileFormat = br.ReadInt32();
- bclim.dataLength = br.ReadUInt32();
-
- bclim.BaseSize = Math.Max(nlpo2(bclim.Width), nlpo2(bclim.Height));
-
- br.BaseStream.Seek(0, SeekOrigin.Begin);
- bclim.Data = br.ReadBytes((int)bclim.dataLength);
-
- return bclim;
- }
- }
- public struct CLIM
- {
- public uint Magic; // CLIM = 0x4D494C43
- public UInt16 BOM; // 0xFFFE
- public uint CLIMLength; // HeaderLength - 14
- public int TileWidth; // 1<<[[n]]
- public int TileHeight; // 1<<[[n]]
- public uint totalLength; // Total Length of file
- public uint Count; // "1" , guessing it's just Count.
-
- public char[] imag; // imag = 0x67616D69
- public uint imagLength; // HeaderLength - 10
- public UInt16 Width; // Final Dimensions
- public UInt16 Height; // Final Dimensions
- public int FileFormat; // ??
- public uint dataLength; // Pixel Data Region Length
-
- public byte[] Data;
-
- public int BaseSize;
-
- //// Contained Data
- //public int ColorFormat;
- //public int ColorCount;
- //public Color[] Colors;
-
- //public int[] Pixels;
-
- public string FileName;
- public string FilePath;
- public string Extension;
- }
- }
-}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/BLZ.cs b/pk3DS.Core/CTR/BLZ.cs
index 5b98f458b5..86a9fd26c2 100644
--- a/pk3DS.Core/CTR/BLZ.cs
+++ b/pk3DS.Core/CTR/BLZ.cs
@@ -24,489 +24,497 @@
using System.IO;
using System.Windows.Forms;
-namespace pk3DS.Core.CTR
+namespace pk3DS.Core.CTR;
+
+public class BLZCoder
{
- public class BLZCoder
+ private const int CMD_DECODE = 0;
+ private const int CMD_ENCODE = 1;
+
+ private const int BLZ_NORMAL = 0;
+ private const int BLZ_BEST = 1;
+ private const int BLZ_SHIFT = 1;
+ private const int BLZ_MASK = 0x80;
+ private const int BLZ_THRESHOLD = 2;
+ private const int BLZ_N = 0x1002;
+ private const int BLZ_F = 0x12;
+ private const int BLZ_MAXIM = 0x01400000;
+ private const int RAW_MAXIM = 0x00FFFFFF;
+
+ private readonly bool arm9;
+ private int new_len;
+
+ private readonly ProgressBar pBar1;
+
+ private void InitProgress(int max)
{
- private const int CMD_DECODE = 0;
- private const int CMD_ENCODE = 1;
-
- private const int BLZ_NORMAL = 0;
- private const int BLZ_BEST = 1;
- private const int BLZ_SHIFT = 1;
- private const int BLZ_MASK = 0x80;
- private const int BLZ_THRESHOLD = 2;
- private const int BLZ_N = 0x1002;
- private const int BLZ_F = 0x12;
- private const int BLZ_MAXIM = 0x01400000;
- private const int RAW_MAXIM = 0x00FFFFFF;
-
- private readonly bool arm9;
- private int new_len;
-
- private readonly ProgressBar pBar1;
- private void initpBar(int max)
+ if (pBar1.InvokeRequired)
{
- if (pBar1.InvokeRequired)
- pBar1.Invoke((MethodInvoker)delegate { pBar1.Minimum = 0; pBar1.Step = 1; pBar1.Value = 0; pBar1.Maximum = max; });
- else { pBar1.Minimum = 0; pBar1.Step = 1; pBar1.Value = 0; pBar1.Maximum = max; }
- }
- private void setpBarPos(int pos)
- {
- if (pBar1.InvokeRequired)
- pBar1.Invoke((MethodInvoker)delegate { pBar1.Value = pos; });
- else { pBar1.Value = pos; }
+ pBar1.Invoke((MethodInvoker)delegate { pBar1.Minimum = 0; pBar1.Step = 1; pBar1.Value = 0; pBar1.Maximum = max; });
}
+ else { pBar1.Minimum = 0; pBar1.Step = 1; pBar1.Value = 0; pBar1.Maximum = max; }
+ }
- public BLZCoder(string[] args, ProgressBar pBar = null)
+ private void SetProgressPosition(int pos)
+ {
+ if (pBar1.InvokeRequired)
{
- int cmd, mode = 0;
- if (pBar == null) pBar1 = new ProgressBar();
- pBar1 = pBar;
-
- // Title();
+ pBar1.Invoke((MethodInvoker)delegate { pBar1.Value = pos; });
+ }
+ else { pBar1.Value = pos; }
+ }
- if (args == null || args.Length != 2)
- throw new Exception("No arguments supplied to BLZ");
+ public BLZCoder(string[] args, ProgressBar pBar = null)
+ {
+ int cmd, mode = 0;
+ if (pBar == null) pBar1 = new ProgressBar();
+ pBar1 = pBar;
- if (args[0].Equals("-d"))
- cmd = CMD_DECODE;
+ // Title();
- else if (args[0].Equals("-en") || args[0].Equals("-en9"))
- {
- cmd = CMD_ENCODE;
- mode = BLZ_NORMAL;
- }
- else if (args[0].Equals("-eo") || args[0].Equals("-eo9"))
- {
- cmd = CMD_ENCODE;
- mode = BLZ_BEST;
- }
- else { Console.Write("Command not supported" + Environment.NewLine); return; }
+ if (args == null || args.Length != 2)
+ throw new Exception("No arguments supplied to BLZ");
- if (args.Length < 2)
- Console.Write("Filename not specified" + Environment.NewLine);
- else
- {
- int arg;
- switch (cmd)
- {
- case 0:
- for (arg = 1; arg < args.Length; arg++)
- BLZ_Decode(args[arg]);
- break;
- case 1:
- arm9 = args[0].Length > 3 && args[0][3] == '9';
- for (arg = 1; arg < args.Length; arg++)
- BLZ_Encode(args[arg], mode);
- break;
- }
- }
+ if (args[0].Equals("-d"))
+ {
+ cmd = CMD_DECODE;
+ }
+ else if (args[0].Equals("-en") || args[0].Equals("-en9"))
+ {
+ cmd = CMD_ENCODE;
+ mode = BLZ_NORMAL;
+ }
+ else if (args[0].Equals("-eo") || args[0].Equals("-eo9"))
+ {
+ cmd = CMD_ENCODE;
+ mode = BLZ_BEST;
+ }
+ else { Console.Write("Command not supported" + Environment.NewLine); return; }
- Console.Write(Environment.NewLine + "Done" + Environment.NewLine);
+ if (args.Length < 2)
+ {
+ Console.Write("Filename not specified" + Environment.NewLine);
}
- private static void Save(string filename, byte[] buffer, int length)
+ else
{
- Array.Resize(ref buffer, length);
- try
- { File.WriteAllBytes(filename, buffer); }
- catch (IOException e)
+ int arg;
+ switch (cmd)
{
- Console.Write(Environment.NewLine + "File write error" + Environment.NewLine + e + Environment.NewLine);
- File.WriteAllBytes("blz.bin", buffer);
- Console.Write(Environment.NewLine + "Wrote to 'blz.bin' instead." + Environment.NewLine);
+ case 0:
+ for (arg = 1; arg < args.Length; arg++)
+ BLZ_Decode(args[arg]);
+ break;
+ case 1:
+ arm9 = args[0].Length > 3 && args[0][3] == '9';
+ for (arg = 1; arg < args.Length; arg++)
+ BLZ_Encode(args[arg], mode);
+ break;
}
}
- private static void BLZ_Decode(string filename)
+
+ Console.Write(Environment.NewLine + "Done" + Environment.NewLine);
+ }
+
+ private static void Save(string filename, byte[] buffer, int length)
+ {
+ Array.Resize(ref buffer, length);
+ try
+ { File.WriteAllBytes(filename, buffer); }
+ catch (IOException e)
{
- try
- {
- Console.Write($"- decoding '{filename}'");
- long startTime = DateTime.Now.Millisecond;
- byte[] buf = File.ReadAllBytes(filename);
- BLZResult result = BLZ_Decode(buf);
- if (result != null)
- Save(filename, result.buffer, result.length);
- Console.Write(" - done, time="
- + (DateTime.Now.Millisecond - startTime) + "ms");
- Console.Write(Environment.NewLine + "");
- }
- catch (IOException e)
- { Console.Write(Environment.NewLine + "File read error" + Environment.NewLine + e); }
+ Console.Write(Environment.NewLine + "File write error" + Environment.NewLine + e + Environment.NewLine);
+ File.WriteAllBytes("blz.bin", buffer);
+ Console.Write(Environment.NewLine + "Wrote to 'blz.bin' instead." + Environment.NewLine);
}
- private static BLZResult BLZ_Decode(byte[] data)
+ }
+
+ private static void BLZ_Decode(string filename)
+ {
+ try
{
- int raw_len, len;
- int enc_len, dec_len;
- int flags = 0;
+ Console.Write($"- decoding '{filename}'");
+ long startTime = DateTime.Now.Millisecond;
+ byte[] buf = File.ReadAllBytes(filename);
+ BLZResult result = BLZ_Decode(buf);
+ if (result != null)
+ Save(filename, result.buffer, result.length);
+ Console.Write(" - done, time="
+ + (DateTime.Now.Millisecond - startTime) + "ms");
+ Console.Write(Environment.NewLine + "");
+ }
+ catch (IOException e)
+ { Console.Write(Environment.NewLine + "File read error" + Environment.NewLine + e); }
+ }
+
+ private static BLZResult BLZ_Decode(byte[] data)
+ {
+ int raw_len;
+ int len;
+ int dec_len;
+ int flags = 0;
- byte[] pak_buffer = prepareData(data);
- int pak_len = pak_buffer.Length - 3;
+ byte[] pak_buffer = PrepareData(data);
+ int pak_len = pak_buffer.Length - 3;
- int inc_len = BitConverter.ToInt32(pak_buffer, pak_len - 4);
- if (inc_len < 1)
+ int inc_len = BitConverter.ToInt32(pak_buffer, pak_len - 4);
+ if (inc_len < 1)
+ {
+ Console.Write(", WARNING: not coded file!");
+ dec_len = pak_len;
+ pak_len = 0;
+ raw_len = dec_len;
+ }
+ else
+ {
+ if (pak_len < 8)
{
- Console.Write(", WARNING: not coded file!");
- enc_len = 0;
- dec_len = pak_len;
- pak_len = 0;
- raw_len = dec_len;
+ Console.Write(Environment.NewLine + "File has a bad header" + Environment.NewLine);
+ return null;
}
- else
+ int hdr_len = pak_buffer[pak_len - 5];
+ if (hdr_len is < 8 or > 0xB)
{
- if (pak_len < 8)
- {
- Console.Write(Environment.NewLine + "File has a bad header" + Environment.NewLine);
- return null;
- }
- int hdr_len = pak_buffer[pak_len - 5];
- if (hdr_len < 8 || hdr_len > 0xB)
- {
- Console.Write(Environment.NewLine + "Bad header length" + Environment.NewLine);
- return null;
- }
- if (pak_len <= hdr_len)
- {
- Console.Write(Environment.NewLine + "Bad length" + Environment.NewLine);
- return null;
- }
- enc_len = (int)(BitConverter.ToUInt32(pak_buffer, pak_len - 8) & 0x00FFFFFF);
- dec_len = pak_len - enc_len;
- pak_len = enc_len - hdr_len;
- raw_len = dec_len + enc_len + inc_len;
- if (raw_len > RAW_MAXIM)
- {
- Console.Write(Environment.NewLine + "Bad decoded length" + Environment.NewLine);
- return null;
- }
+ Console.Write(Environment.NewLine + "Bad header length" + Environment.NewLine);
+ return null;
+ }
+ if (pak_len <= hdr_len)
+ {
+ Console.Write(Environment.NewLine + "Bad length" + Environment.NewLine);
+ return null;
+ }
+ var enc_len = (int)(BitConverter.ToUInt32(pak_buffer, pak_len - 8) & 0x00FFFFFF);
+ dec_len = pak_len - enc_len;
+ pak_len = enc_len - hdr_len;
+ raw_len = dec_len + enc_len + inc_len;
+ if (raw_len > RAW_MAXIM)
+ {
+ Console.Write(Environment.NewLine + "Bad decoded length" + Environment.NewLine);
+ return null;
}
+ }
- byte[] raw_buffer = new byte[raw_len];
+ byte[] raw_buffer = new byte[raw_len];
- int pak = 0;
- int raw = 0;
- int pak_end = dec_len + pak_len;
- int raw_end = raw_len;
+ int pak = 0;
+ int raw = 0;
+ int pak_end = dec_len + pak_len;
+ int raw_end = raw_len;
- for (len = 0; len < dec_len; len++)
- raw_buffer[raw++] = pak_buffer[pak++];
+ for (len = 0; len < dec_len; len++)
+ raw_buffer[raw++] = pak_buffer[pak++];
- BLZ_Invert(pak_buffer, dec_len, pak_len);
+ BLZ_Invert(pak_buffer, dec_len, pak_len);
- int mask = 0;
+ int mask = 0;
- while (raw < raw_end)
+ while (raw < raw_end)
+ {
+ if ((mask >>>= BLZ_SHIFT) == 0)
{
- if ((mask = (int)((uint)mask >> BLZ_SHIFT)) == 0)
- {
- if (pak == pak_end)
- break;
+ if (pak == pak_end)
+ break;
- flags = pak_buffer[pak++];
- mask = BLZ_MASK;
- }
+ flags = pak_buffer[pak++];
+ mask = BLZ_MASK;
+ }
- if ((flags & mask) == 0)
- {
- if (pak == pak_end)
- break;
+ if ((flags & mask) == 0)
+ {
+ if (pak == pak_end)
+ break;
- raw_buffer[raw++] = pak_buffer[pak++];
+ raw_buffer[raw++] = pak_buffer[pak++];
+ }
+ else
+ {
+ if (pak + 1 >= pak_end)
+ break;
+
+ int pos = pak_buffer[pak++] << 8;
+ pos |= pak_buffer[pak++];
+ len = (pos >>> 12) + BLZ_THRESHOLD + 1;
+ if (raw + len > raw_end)
+ {
+ Console.Write(", WARNING: wrong decoded length!");
+ len = raw_end - raw;
}
- else
+ pos = (pos & 0xFFF) + 3;
+ while (len-- > 0)
{
- if (pak + 1 >= pak_end)
- break;
-
- int pos = pak_buffer[pak++] << 8;
- pos |= pak_buffer[pak++];
- len = (int)((uint)pos >> 12) + BLZ_THRESHOLD + 1;
- if (raw + len > raw_end)
- {
- Console.Write(", WARNING: wrong decoded length!");
- len = raw_end - raw;
- }
- pos = (pos & 0xFFF) + 3;
- while (len-- > 0)
- {
- int charHere = raw_buffer[raw - pos];
- raw_buffer[raw++] = (byte)charHere;
- }
+ int charHere = raw_buffer[raw - pos];
+ raw_buffer[raw++] = (byte)charHere;
}
}
+ }
- BLZ_Invert(raw_buffer, dec_len, raw_len - dec_len);
+ BLZ_Invert(raw_buffer, dec_len, raw_len - dec_len);
- raw_len = raw;
+ raw_len = raw;
- if (raw != raw_end)
- Console.Write(", WARNING: unexpected end of encoded file!");
+ if (raw != raw_end)
+ Console.Write(", WARNING: unexpected end of encoded file!");
- return new BLZResult(raw_buffer, raw_len);
- }
- private BLZResult BLZ_Encode(byte[] data, int mode)
- {
- new_len = 0;
+ return new BLZResult(raw_buffer, raw_len);
+ }
- byte[] raw_buffer = prepareData(data);
- int raw_len = raw_buffer.Length - 3;
+ private BLZResult BLZ_Encode(byte[] data, int mode)
+ {
+ new_len = 0;
- byte[] pak_buffer = null;
- int pak_len = BLZ_MAXIM + 1;
+ byte[] raw_buffer = PrepareData(data);
+ int raw_len = raw_buffer.Length - 3;
- byte[] new_buffer = BLZ_Code(raw_buffer, raw_len, mode);
+ byte[] pak_buffer = null;
+ int pak_len = BLZ_MAXIM + 1;
- if (new_len < pak_len)
- {
- pak_buffer = new_buffer;
- pak_len = new_len;
- }
- return new BLZResult(pak_buffer, pak_len);
- }
- private static byte[] prepareData(byte[] data)
- {
- int fs = data.Length;
- byte[] fb = new byte[fs + 3];
- for (int i = 0; i < fs; i++)
- fb[i] = data[i];
+ byte[] new_buffer = BLZ_Code(raw_buffer, raw_len, mode);
- return fb;
- }
- private static void writeUnsigned(byte[] buffer, int offset, int value)
+ if (new_len < pak_len)
{
- buffer[offset] = (byte)(value & 0xFF);
- buffer[offset + 1] = (byte)((value >> 8) & 0xFF);
- buffer[offset + 2] = (byte)((value >> 16) & 0xFF);
- buffer[offset + 3] = (byte)((value >> 24) & 0x7F);
+ pak_buffer = new_buffer;
+ pak_len = new_len;
}
- private void BLZ_Encode(string filename, int mode)
+ return new BLZResult(pak_buffer, pak_len);
+ }
+
+ private static byte[] PrepareData(byte[] data)
+ {
+ int fs = data.Length;
+ byte[] fb = new byte[fs + 3];
+ for (int i = 0; i < fs; i++)
+ fb[i] = data[i];
+
+ return fb;
+ }
+
+ private static void WriteUnsigned(byte[] buffer, int offset, int value)
+ {
+ buffer[offset] = (byte)(value & 0xFF);
+ buffer[offset + 1] = (byte)((value >> 8) & 0xFF);
+ buffer[offset + 2] = (byte)((value >> 16) & 0xFF);
+ buffer[offset + 3] = (byte)((value >> 24) & 0x7F);
+ }
+
+ private void BLZ_Encode(string filename, int mode)
+ {
+ try
{
- try
- {
- Console.Write("Now encoding {0}", filename);
- var stopwatch = new Stopwatch();
- stopwatch.Start();
+ Console.Write("Now encoding {0}", filename);
+ var stopwatch = new Stopwatch();
+ stopwatch.Start();
- byte[] buf = File.ReadAllBytes(filename);
- BLZResult result = BLZ_Encode(buf, mode);
- if (result != null)
- Save(filename, result.buffer, result.length);
+ byte[] buf = File.ReadAllBytes(filename);
+ BLZResult result = BLZ_Encode(buf, mode);
+ if (result != null)
+ Save(filename, result.buffer, result.length);
- stopwatch.Stop();
- Console.Write(Environment.NewLine + "Done, time elapsed = " + stopwatch.ElapsedMilliseconds + "ms" + Environment.NewLine);
- }
- catch (IOException e)
- { Console.Write(Environment.NewLine + "File read error" + Environment.NewLine + e + Environment.NewLine); }
+ stopwatch.Stop();
+ Console.Write(Environment.NewLine + "Done, time elapsed = " + stopwatch.ElapsedMilliseconds + "ms" + Environment.NewLine);
}
- private byte[] BLZ_Code(byte[] raw_buffer, int raw_len, int best)
- {
- int flg = 0;
- int pos_best = 0;
- int pos_next = 0;
- int pos_post = 0;
+ catch (IOException e)
+ { Console.Write(Environment.NewLine + "File read error" + Environment.NewLine + e + Environment.NewLine); }
+ }
- int pak_tmp = 0;
- int raw_tmp = raw_len;
+ private byte[] BLZ_Code(byte[] raw_buffer, int raw_len, int best)
+ {
+ int flg = 0;
+ int pos_best = 0;
+ int pos_next = 0;
+ int pos_post = 0;
- int pak_len = raw_len + (raw_len + 7) / 8 + 11;
- byte[] pak_buffer = new byte[pak_len];
+ int pak_tmp = 0;
+ int raw_tmp = raw_len;
- int raw_new = raw_len;
+ int pak_len = raw_len + ((raw_len + 7) / 8) + 11;
+ byte[] pak_buffer = new byte[pak_len];
- // We don't do any of the checks here
- // Presume that we actually are using an arm9
- if (arm9)
- raw_new -= 0x4000;
+ int raw_new = raw_len;
- BLZ_Invert(raw_buffer, 0, raw_len);
+ // We don't do any of the checks here
+ // Presume that we actually are using an arm9
+ if (arm9)
+ raw_new -= 0x4000;
- int pak = 0;
- int raw = 0;
- int raw_end = raw_new;
+ BLZ_Invert(raw_buffer, 0, raw_len);
- int mask = 0;
- initpBar(raw_end);
- while (raw < raw_end)
+ int pak = 0;
+ int raw = 0;
+ int raw_end = raw_new;
+
+ int mask = 0;
+ InitProgress(raw_end);
+ while (raw < raw_end)
+ {
+ SetProgressPosition(raw);
+ if ((mask >>>= BLZ_SHIFT) == 0)
{
- setpBarPos(raw);
- if ((mask = (int)((uint)mask >> BLZ_SHIFT)) == 0)
- {
- pak_buffer[flg = pak++] = 0;
- mask = BLZ_MASK;
- }
+ pak_buffer[flg = pak++] = 0;
+ mask = BLZ_MASK;
+ }
- SearchPair sl1 = SEARCH(pos_best, raw_buffer, raw, raw_end);
- int len_best = sl1.l;
- pos_best = sl1.p;
+ SearchPair sl1 = SEARCH(pos_best, raw_buffer, raw, raw_end);
+ int len_best = sl1.l;
+ pos_best = sl1.p;
- // LZ-CUE optimization start
- if (best == BLZ_BEST)
+ // LZ-CUE optimization start
+ if (best == BLZ_BEST)
+ {
+ if (len_best > BLZ_THRESHOLD)
{
- if (len_best > BLZ_THRESHOLD)
+ if (raw + len_best < raw_end)
{
- if (raw + len_best < raw_end)
- {
- raw += len_best;
- SearchPair sl2 = SEARCH(pos_next, raw_buffer, raw,
- raw_end);
- int len_next = sl2.l;
- pos_next = sl2.p;
- raw -= len_best - 1;
- SearchPair sl3 = SEARCH(pos_post, raw_buffer, raw,
- raw_end);
- int len_post = sl3.l;
- pos_post = sl3.p;
- raw--;
-
- if (len_next <= BLZ_THRESHOLD)
- len_next = 1;
- if (len_post <= BLZ_THRESHOLD)
- len_post = 1;
- if (len_best + len_next <= 1 + len_post)
- len_best = 1;
- }
+ raw += len_best;
+ SearchPair sl2 = SEARCH(pos_next, raw_buffer, raw,
+ raw_end);
+ int len_next = sl2.l;
+ pos_next = sl2.p;
+ raw -= len_best - 1;
+ SearchPair sl3 = SEARCH(pos_post, raw_buffer, raw,
+ raw_end);
+ int len_post = sl3.l;
+ pos_post = sl3.p;
+ raw--;
+
+ if (len_next <= BLZ_THRESHOLD)
+ len_next = 1;
+ if (len_post <= BLZ_THRESHOLD)
+ len_post = 1;
+ if (len_best + len_next <= 1 + len_post)
+ len_best = 1;
}
}
- // LZ-CUE optimization end
- pak_buffer[flg] = (byte)(pak_buffer[flg] << 1);
- if (len_best > BLZ_THRESHOLD)
- {
- raw += len_best;
- pak_buffer[flg] |= 1;
- pak_buffer[pak++] = (byte)((byte)((len_best - (BLZ_THRESHOLD + 1)) << 4) | ((uint)(pos_best - 3) >> 8));
- pak_buffer[pak++] = (byte)(pos_best - 3);
- }
- else
- pak_buffer[pak++] = raw_buffer[raw++];
-
- if (pak + raw_len - raw >= pak_tmp + raw_tmp)
- continue;
-
- pak_tmp = pak;
- raw_tmp = raw_len - raw;
}
-
- while (mask > 0 && mask != 1)
+ // LZ-CUE optimization end
+ pak_buffer[flg] = (byte)(pak_buffer[flg] << 1);
+ if (len_best > BLZ_THRESHOLD)
+ {
+ raw += len_best;
+ pak_buffer[flg] |= 1;
+ pak_buffer[pak++] = (byte)((byte)((len_best - (BLZ_THRESHOLD + 1)) << 4) | ((uint)(pos_best - 3) >> 8));
+ pak_buffer[pak++] = (byte)(pos_best - 3);
+ }
+ else
{
- mask = (int)((uint)mask >> BLZ_SHIFT);
- pak_buffer[flg] = (byte)(pak_buffer[flg] << 1);
+ pak_buffer[pak++] = raw_buffer[raw++];
}
- pak_len = pak;
+ if (pak + raw_len - raw >= pak_tmp + raw_tmp)
+ continue;
- BLZ_Invert(raw_buffer, 0, raw_len);
- BLZ_Invert(pak_buffer, 0, pak_len);
+ pak_tmp = pak;
+ raw_tmp = raw_len - raw;
+ }
- if (pak_tmp == 0 || raw_len + 4 < ((pak_tmp + raw_tmp + 3) & 0xFFFFFFFC) + 8)
- {
- pak = 0;
- raw = 0;
- raw_end = raw_len;
+ while (mask > 0 && mask != 1)
+ {
+ mask >>>= BLZ_SHIFT;
+ pak_buffer[flg] = (byte)(pak_buffer[flg] << 1);
+ }
- while (raw < raw_end)
- pak_buffer[pak++] = raw_buffer[raw++];
+ pak_len = pak;
- while ((pak & 3) > 0)
- pak_buffer[pak++] = 0;
+ BLZ_Invert(raw_buffer, 0, raw_len);
+ BLZ_Invert(pak_buffer, 0, pak_len);
- pak_buffer[pak++] = 0;
- pak_buffer[pak++] = 0;
- pak_buffer[pak++] = 0;
- pak_buffer[pak++] = 0;
- }
- else
- {
- byte[] tmp = new byte[raw_tmp + pak_tmp + 11];
+ if (pak_tmp == 0 || raw_len + 4 < ((pak_tmp + raw_tmp + 3) & 0xFFFFFFFC) + 8)
+ {
+ pak = 0;
+ raw = 0;
+ raw_end = raw_len;
- int len;
- for (len = 0; len < raw_tmp; len++)
- tmp[len] = raw_buffer[len];
+ while (raw < raw_end)
+ pak_buffer[pak++] = raw_buffer[raw++];
+
+ while ((pak & 3) > 0)
+ pak_buffer[pak++] = 0;
- for (len = 0; len < pak_tmp; len++)
- tmp[raw_tmp + len] = pak_buffer[len + pak_len - pak_tmp];
-
- pak_buffer = tmp;
- pak = raw_tmp + pak_tmp;
+ pak_buffer[pak++] = 0;
+ pak_buffer[pak++] = 0;
+ pak_buffer[pak++] = 0;
+ pak_buffer[pak++] = 0;
+ }
+ else
+ {
+ byte[] tmp = new byte[raw_tmp + pak_tmp + 11];
- int enc_len = pak_tmp;
- int hdr_len = 8;
- int inc_len = raw_len - pak_tmp - raw_tmp;
+ int len;
+ for (len = 0; len < raw_tmp; len++)
+ tmp[len] = raw_buffer[len];
- while ((pak & 3) > 0)
- {
- pak_buffer[pak++] = 0xFF;
- hdr_len++;
- }
+ for (len = 0; len < pak_tmp; len++)
+ tmp[raw_tmp + len] = pak_buffer[len + pak_len - pak_tmp];
- writeUnsigned(pak_buffer, pak, enc_len + hdr_len);
- pak += 3;
- pak_buffer[pak++] = (byte)hdr_len;
- writeUnsigned(pak_buffer, pak, inc_len - hdr_len);
- pak += 4;
- }
- new_len = pak;
- return pak_buffer;
- }
+ pak_buffer = tmp;
+ pak = raw_tmp + pak_tmp;
- private class SearchPair
- {
- public readonly int l;
- public readonly int p;
+ int enc_len = pak_tmp;
+ int hdr_len = 8;
+ int inc_len = raw_len - pak_tmp - raw_tmp;
- public SearchPair(int l, int p)
+ while ((pak & 3) > 0)
{
- this.l = l;
- this.p = p;
+ pak_buffer[pak++] = 0xFF;
+ hdr_len++;
}
+
+ WriteUnsigned(pak_buffer, pak, enc_len + hdr_len);
+ pak += 3;
+ pak_buffer[pak++] = (byte)hdr_len;
+ WriteUnsigned(pak_buffer, pak, inc_len - hdr_len);
+ pak += 4;
}
- private static SearchPair SEARCH(int p, IList raw_buffer, int raw, int raw_end)
+ new_len = pak;
+ return pak_buffer;
+ }
+
+ private class SearchPair(int l, int p)
+ {
+ public readonly int l = l;
+ public readonly int p = p;
+ }
+
+ private static SearchPair SEARCH(int p, IList raw_buffer, int raw, int raw_end)
+ {
+ int l = BLZ_THRESHOLD;
+ int max = raw >= BLZ_N ? BLZ_N : raw;
+ for (int pos = 3; pos <= max; pos++)
{
- int l = BLZ_THRESHOLD;
- int max = raw >= BLZ_N ? BLZ_N : raw;
- for (int pos = 3; pos <= max; pos++)
+ int len;
+ for (len = 0; len < BLZ_F; len++)
{
- int len;
- for (len = 0; len < BLZ_F; len++)
- {
- if (raw + len == raw_end)
- break;
-
- if (len >= pos)
- break;
+ if (raw + len == raw_end)
+ break;
- if (raw_buffer[raw + len] != raw_buffer[raw + len - pos])
- break;
- }
+ if (len >= pos)
+ break;
- if (len <= l) continue;
- p = pos;
- if ((l = len) == BLZ_F)
+ if (raw_buffer[raw + len] != raw_buffer[raw + len - pos])
break;
}
- return new SearchPair(l, p);
+
+ if (len <= l) continue;
+ p = pos;
+ if ((l = len) == BLZ_F)
+ break;
}
+ return new SearchPair(l, p);
+ }
- private class BLZResult
- {
- public BLZResult(byte[] raw_buffer, int raw_len)
- {
- buffer = raw_buffer;
- length = raw_len;
- }
+ private class BLZResult(byte[] raw_buffer, int raw_len)
+ {
+ public readonly byte[] buffer = raw_buffer;
+ public readonly int length = raw_len;
+ }
- public readonly byte[] buffer;
- public readonly int length;
- }
- private static void BLZ_Invert(byte[] buffer, int offset, int length)
- {
- int bottom = offset + length - 1;
+ private static void BLZ_Invert(byte[] buffer, int offset, int length)
+ {
+ int bottom = offset + length - 1;
- while (offset < bottom)
- {
- int ch = buffer[offset];
- buffer[offset++] = buffer[bottom];
- buffer[bottom--] = (byte)ch;
- }
+ while (offset < bottom)
+ {
+ int ch = buffer[offset];
+ buffer[offset++] = buffer[bottom];
+ buffer[bottom--] = (byte)ch;
}
}
}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/CRO.cs b/pk3DS.Core/CTR/CRO.cs
index 3fc706e6a9..81a9d5f0df 100644
--- a/pk3DS.Core/CTR/CRO.cs
+++ b/pk3DS.Core/CTR/CRO.cs
@@ -5,237 +5,245 @@
using System.Security.Cryptography;
using System.Windows.Forms;
-namespace pk3DS.Core.CTR
+namespace pk3DS.Core.CTR;
+
+public class CRO(byte[] data)
{
- public class CRO
+ // Utility
+ internal static void UpdateTB(RichTextBox RTB, string progress)
{
- // Utility
- internal static void updateTB(RichTextBox RTB, string progress)
+ try
{
- try
+ if (RTB.InvokeRequired)
{
- if (RTB.InvokeRequired)
- RTB.Invoke((MethodInvoker)delegate
- {
- RTB.AppendText(Environment.NewLine + progress);
- RTB.SelectionStart = RTB.Text.Length;
- RTB.ScrollToCaret();
- });
- else
+ RTB.Invoke((MethodInvoker)delegate
{
+ RTB.AppendText(Environment.NewLine + progress);
RTB.SelectionStart = RTB.Text.Length;
RTB.ScrollToCaret();
- RTB.AppendText(progress + Environment.NewLine);
- }
+ });
+ }
+ else
+ {
+ RTB.SelectionStart = RTB.Text.Length;
+ RTB.ScrollToCaret();
+ RTB.AppendText(progress + Environment.NewLine);
}
- catch { }
}
- internal static int IndexOfBytes(byte[] array, byte[] pattern, int startIndex, int count)
+ catch { }
+ }
+
+ internal static int IndexOfBytes(byte[] array, byte[] pattern, int startIndex, int count)
+ {
+ int i = startIndex;
+ int endIndex = count > 0 ? startIndex + count : array.Length;
+ int fidx = 0;
+
+ while (i++ != endIndex - 1)
{
- int i = startIndex;
- int endIndex = count > 0 ? startIndex + count : array.Length;
- int fidx = 0;
+ if (array[i] != pattern[fidx]) i -= fidx;
+ fidx = array[i] == pattern[fidx] ? ++fidx : 0;
+ if (fidx == pattern.Length)
+ return i - fidx + 1;
+ }
+ return -1;
+ }
- while (i++ != endIndex - 1)
- {
- if (array[i] != pattern[fidx]) i -= fidx;
- fidx = array[i] == pattern[fidx] ? ++fidx : 0;
- if (fidx == pattern.Length)
- return i - fidx + 1;
- }
- return -1;
+ internal static string GetHexString(byte[] data)
+ {
+ return BitConverter.ToString(data).Replace("-", "");
+ }
+
+ internal static byte[] StringToByteArray(string hex)
+ {
+ return Enumerable.Range(0, hex.Length)
+ .Where(x => x % 2 == 0)
+ .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
+ .ToArray();
+ }
+
+ // Checking
+ internal static string[] VerifyCRR(string PATH_CRR, string PATH_CRO)
+ {
+ // Get CRO files
+ string[] CROFiles = Directory.GetFiles(PATH_CRO);
+
+ // Weed out anything that isn't a .cro
+ var cros = new List();
+ for (int i = 0; i < CROFiles.Length; i++)
+ {
+ if (Path.GetExtension(cros[i]) == ".cro")
+ cros.Add(cros[i]);
}
- internal static string getHexString(byte[] data)
+
+ CROFiles = [.. cros];
+
+ // Store Hashes as Strings (hacky way to sort byte[]'s against eachother
+ string[] hashes = new string[CROFiles.Length];
+ for (int i = 0; i < hashes.Length; i++)
{
- return BitConverter.ToString(data).Replace("-", "");
+ byte[] data = File.ReadAllBytes(CROFiles[i]);
+ byte[] hash = HashCRO(ref data);
+ hashes[i] = GetHexString(hash).ToUpper();
}
- internal static byte[] StringToByteArray(string hex)
+ Array.Sort(hashes, string.Compare);
+ // Convert Hash Strings to Bytes
+ byte[][] hashData = new byte[hashes.Length][];
+ for (int i = 0; i < hashes.Length; i++)
+ hashData[i] = StringToByteArray(hashes[i]);
+
+ // Open the CRR
+ byte[] CRR = File.ReadAllBytes(PATH_CRR);
+ int hashTableOffset = BitConverter.ToInt32(CRR, 0x350);
+ int hashCount = BitConverter.ToInt32(CRR, 0x354);
+
+ // A little validation...
+ if (hashCount != hashData.Length)
+ throw new Exception($"Amount of input file-hashes does not equal the hash count in CRR. Expected {hashCount}, got {hashData.Length}.");
+
+ string[] results = new string[hashData.Length];
+ // Store Hashes in CRR
+ for (int i = 0; i < hashData.Length; i++)
{
- return Enumerable.Range(0, hex.Length)
- .Where(x => x % 2 == 0)
- .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
- .ToArray();
+ byte[] crrEntryHash = new byte[0x20];
+ Array.Copy(CRR, (i * 0x20) + hashTableOffset, crrEntryHash, 0, 0x20);
+ results[i] = "Hash @ {0} is " + (crrEntryHash.SequenceEqual(hashData[i]) ? "valid." : "invalid.");
+ Array.Copy(hashData, 0, CRR, hashTableOffset + (0x20 * i), 0x20);
}
+ return results;
+ }
- // Checking
- internal static string[] verifyCRR(string PATH_CRR, string PATH_CRO)
+ public static bool E_HashCRR(string PATH_CRR, string PATH_CRO, bool saveCRO = true, bool saveCRR = true, RichTextBox TB_Progress = null, ProgressBar PB_Show = null)
+ {
+ // Get CRO files
+ string[] CROFiles = Directory.GetFiles(PATH_CRO);
+
+ // Weed out anything that isn't a .cro
+ CROFiles = CROFiles.Where(t => Path.GetExtension(t) == ".cro").ToArray();
+ // Open the CRR
+ byte[] CRR = File.ReadAllBytes(PATH_CRR);
+ int hashTableOffset = BitConverter.ToInt32(CRR, 0x350);
+ int hashCount = BitConverter.ToInt32(CRR, 0x354);
+
+ // A little validation...
+ if (hashCount != CROFiles.Length)
{
- // Get CRO files
- string[] CROFiles = Directory.GetFiles(PATH_CRO);
-
- // Weed out anything that isn't a .cro
- List cros = new List();
- for (int i = 0; i < CROFiles.Length; i++)
- if (Path.GetExtension(cros[i]) == ".cro")
- cros.Add(cros[i]);
- CROFiles = cros.ToArray();
-
- // Store Hashes as Strings (hacky way to sort byte[]'s against eachother
- string[] hashes = new string[CROFiles.Length];
- for (int i = 0; i < hashes.Length; i++)
- {
- byte[] data = File.ReadAllBytes(CROFiles[i]);
- byte[] hash = hashCRO(ref data);
- hashes[i] = getHexString(hash).ToUpper();
- }
- Array.Sort(hashes, string.Compare);
- // Convert Hash Strings to Bytes
- byte[][] hashData = new byte[hashes.Length][];
- for (int i = 0; i < hashes.Length; i++)
- hashData[i] = StringToByteArray(hashes[i]);
-
- // Open the CRR
- byte[] CRR = File.ReadAllBytes(PATH_CRR);
- int hashTableOffset = BitConverter.ToInt32(CRR, 0x350);
- int hashCount = BitConverter.ToInt32(CRR, 0x354);
-
- // A little validation...
- if (hashCount != hashData.Length)
- throw new Exception(
- $"Amount of input file-hashes does not equal the hash count in CRR. Expected {hashCount}, got {hashData.Length}.");
-
- string[] results = new string[hashData.Length];
- // Store Hashes in CRR
- for (int i = 0; i < hashData.Length; i++)
- {
- byte[] crrEntryHash = new byte[0x20];
- Array.Copy(CRR, i * 0x20 + hashTableOffset, crrEntryHash, 0, 0x20);
- results[i] = "Hash @ {0} is " + (crrEntryHash.SequenceEqual(hashData[i]) ? "valid." : "invalid.");
- Array.Copy(hashData, 0, CRR, hashTableOffset + 0x20 * i, 0x20);
- }
- return results;
+ UpdateTB(TB_Progress,
+ $"Amount of input file-hashes does not equal the hash count in CRR. Expected {hashCount}, got {CROFiles.Length}.");
+ UpdateTB(TB_Progress, "Did not modify files. Aborting.");
+ return false;
}
- public static bool rehashCRR(string PATH_CRR, string PATH_CRO, bool saveCRO = true, bool saveCRR = true, RichTextBox TB_Progress = null, ProgressBar PB_Show = null)
+
+ // Initialize Update Display
+ TB_Progress ??= new RichTextBox();
+ PB_Show ??= new ProgressBar();
+ if (PB_Show.InvokeRequired)
{
- // Get CRO files
- string[] CROFiles = Directory.GetFiles(PATH_CRO);
-
- // Weed out anything that isn't a .cro
- CROFiles = CROFiles.Where(t => Path.GetExtension(t) == ".cro").ToArray();
- // Open the CRR
- byte[] CRR = File.ReadAllBytes(PATH_CRR);
- int hashTableOffset = BitConverter.ToInt32(CRR, 0x350);
- int hashCount = BitConverter.ToInt32(CRR, 0x354);
-
- // A little validation...
- if (hashCount != CROFiles.Length)
- {
- updateTB(TB_Progress,
- $"Amount of input file-hashes does not equal the hash count in CRR. Expected {hashCount}, got {CROFiles.Length}.");
- updateTB(TB_Progress, "Did not modify files. Aborting.");
- return false;
- }
+ PB_Show.Invoke((MethodInvoker)delegate { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = CROFiles.Length; });
+ }
+ else { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = CROFiles.Length; }
+ UpdateTB(TB_Progress, "");
+ UpdateTB(TB_Progress, "Computing hashes for " + CROFiles.Length + " CRO files.");
+
+ // Store Hashes as Strings (hacky way to sort byte[]'s against eachother
+ string[] hashes = new string[CROFiles.Length];
+ for (int i = 0; i < hashes.Length; i++)
+ {
+ byte[] data = File.ReadAllBytes(CROFiles[i]);
+ byte[] hash = HashCRO(ref data);
+ hashes[i] = GetHexString(hash).ToUpper();
+ if (saveCRO)
+ File.WriteAllBytes(CROFiles[i], data);
- // Initialize Update Display
- if (TB_Progress == null) TB_Progress = new RichTextBox();
- if (PB_Show == null) PB_Show = new ProgressBar();
if (PB_Show.InvokeRequired)
- PB_Show.Invoke((MethodInvoker)delegate { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = CROFiles.Length; });
- else { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = CROFiles.Length; }
- updateTB(TB_Progress, "");
- updateTB(TB_Progress, "Computing hashes for " + CROFiles.Length + " CRO files.");
-
- // Store Hashes as Strings (hacky way to sort byte[]'s against eachother
- string[] hashes = new string[CROFiles.Length];
- for (int i = 0; i < hashes.Length; i++)
{
- byte[] data = File.ReadAllBytes(CROFiles[i]);
- byte[] hash = hashCRO(ref data);
- hashes[i] = getHexString(hash).ToUpper();
- if (saveCRO)
- File.WriteAllBytes(CROFiles[i], data);
-
- if (PB_Show.InvokeRequired)
- PB_Show.Invoke((MethodInvoker)(() => PB_Show.PerformStep()));
- else { PB_Show.PerformStep(); }
+ PB_Show.Invoke((MethodInvoker)(() => PB_Show.PerformStep()));
}
- updateTB(TB_Progress, "Hashes computed, now sorting."); // Don't need to fiddle the ProgressBar because this should be quite quick.
- string[] hashCopy = (string[])hashes.Clone(); // Store an unsorted list for later.
- Array.Sort(hashes, string.Compare);
- // Convert Hash Strings to Bytes
- byte[][] hashData = new byte[hashes.Length][];
- for (int i = 0; i < hashes.Length; i++)
- hashData[i] = StringToByteArray(hashes[i]);
-
- updateTB(TB_Progress, "Hashes sorted, writing hashes to CRR.");
-
- // Loop to check which CROs have to be updated. Do this separate from overwriting so we don't overwrite hashes for other CROs (yet).
- int updatedCTR = 0;
- for (int i = 0; i < hashData.Length; i++)
+ else { PB_Show.PerformStep(); }
+ }
+ UpdateTB(TB_Progress, "Hashes computed, now sorting."); // Don't need to fiddle the ProgressBar because this should be quite quick.
+ string[] hashCopy = (string[])hashes.Clone(); // Store an unsorted list for later.
+ Array.Sort(hashes, string.Compare);
+ // Convert Hash Strings to Bytes
+ byte[][] hashData = new byte[hashes.Length][];
+ for (int i = 0; i < hashes.Length; i++)
+ hashData[i] = StringToByteArray(hashes[i]);
+
+ UpdateTB(TB_Progress, "Hashes sorted, writing hashes to CRR.");
+
+ // Loop to check which CROs have to be updated. Do this separate from overwriting so we don't overwrite hashes for other CROs (yet).
+ int updatedCTR = 0;
+ for (int i = 0; i < hashData.Length; i++)
+ {
+ // Check to see if the hash is currently in the table already.
+ int index = IndexOfBytes(CRR, hashData[i], 0, CRR.Length);
+ if (index < 0)
{
- // Check to see if the hash is currently in the table already.
- int index = IndexOfBytes(CRR, hashData[i], 0, CRR.Length);
- if (index < 0)
- {
- // CRO was updated.
- string file = CROFiles[Array.IndexOf(hashCopy, hashes[i])];
- updateTB(TB_Progress, $"{Path.GetFileName(file)} hash has been updated.");
- updatedCTR++;
- }
+ // CRO was updated.
+ string file = CROFiles[Array.IndexOf(hashCopy, hashes[i])];
+ UpdateTB(TB_Progress, $"{Path.GetFileName(file)} hash has been updated.");
+ updatedCTR++;
}
- // Store Hashes in CRR
- for (int i = 0; i < hashData.Length; i++)
- Array.Copy(hashData[i], 0, CRR, hashTableOffset + 0x20 * i, 0x20);
+ }
+ // Store Hashes in CRR
+ for (int i = 0; i < hashData.Length; i++)
+ Array.Copy(hashData[i], 0, CRR, hashTableOffset + (0x20 * i), 0x20);
- updateTB(TB_Progress,
- updatedCTR > 0
- ? $"{updatedCTR} hashes have been updated."
- : "CRR is fine. No modifications are necessary.");
+ UpdateTB(TB_Progress,
+ updatedCTR > 0
+ ? $"{updatedCTR} hashes have been updated."
+ : "CRR is fine. No modifications are necessary.");
- // Save File
- if (saveCRR && updatedCTR > 0)
- {
- File.WriteAllBytes(PATH_CRR, CRR);
- updateTB(TB_Progress, "Wrote CRR.");
- }
- else
- {
- updateTB(TB_Progress, "CRR has not been updated.");
- }
- return true;
+ // Save File
+ if (saveCRR && updatedCTR > 0)
+ {
+ File.WriteAllBytes(PATH_CRR, CRR);
+ UpdateTB(TB_Progress, "Wrote CRR.");
}
- internal static byte[] hashCRO(ref byte[] CRO)
+ else
{
- // Allocate new byte array to store modified CRO
- SHA256 mySHA = SHA256.Create();
-
- // Compute the hashes
- byte[] hashH = mySHA.ComputeHash(CRO, 0x80, 0x100);
- byte[] hash0 = mySHA.ComputeHash(CRO, BitConverter.ToInt32(CRO, 0xB0), BitConverter.ToInt32(CRO, 0xB4));
- byte[] hash1 = mySHA.ComputeHash(CRO, BitConverter.ToInt32(CRO, 0xC0), BitConverter.ToInt32(CRO, 0xB8) - BitConverter.ToInt32(CRO, 0xC0));
- byte[] hash2 = mySHA.ComputeHash(CRO, BitConverter.ToInt32(CRO, 0xB8), BitConverter.ToInt32(CRO, 0xBC));
-
- // Set the hashes
- Array.Copy(hashH, 0, CRO, 0x00, 0x20);
- Array.Copy(hash0, 0, CRO, 0x20, 0x20);
- Array.Copy(hash1, 0, CRO, 0x40, 0x20);
- Array.Copy(hash2, 0, CRO, 0x60, 0x20);
-
- // Return the fixed overall hash
- return mySHA.ComputeHash(CRO, 0, 0x80);
+ UpdateTB(TB_Progress, "CRR has not been updated.");
}
+ return true;
+ }
+
+ internal static byte[] HashCRO(ref byte[] CRO)
+ {
+ // Allocate new byte array to store modified CRO
+
+ // Compute the hashes
+ byte[] hashH = SHA256.HashData(CRO.AsSpan(0x80, 0x100));
+ byte[] hash0 = SHA256.HashData(CRO.AsSpan(BitConverter.ToInt32(CRO, 0xB0), BitConverter.ToInt32(CRO, 0xB4)));
+ byte[] hash1 = SHA256.HashData(CRO.AsSpan(BitConverter.ToInt32(CRO, 0xC0), BitConverter.ToInt32(CRO, 0xB8) - BitConverter.ToInt32(CRO, 0xC0)));
+ byte[] hash2 = SHA256.HashData(CRO.AsSpan(BitConverter.ToInt32(CRO, 0xB8), BitConverter.ToInt32(CRO, 0xBC)));
+
+ // Set the hashes
+ Array.Copy(hashH, 0, CRO, 0x00, 0x20);
+ Array.Copy(hash0, 0, CRO, 0x20, 0x20);
+ Array.Copy(hash1, 0, CRO, 0x40, 0x20);
+ Array.Copy(hash2, 0, CRO, 0x60, 0x20);
+
+ // Return the fixed overall hash
+ return SHA256.HashData(CRO.AsSpan(0, 0x80));
+ }
+ private readonly byte[] Data = (byte[])data.Clone();
- public CRO(byte[] data)
+ public byte[] HashSHA2
+ {
+ get
{
- Data = (byte[])data.Clone();
+ byte[] hashData = new byte[0x80];
+ Array.Copy(Data, hashData, 0x80);
+ return hashData;
}
- private readonly byte[] Data;
- private byte[] sha2Hash
+ set
{
- get
- {
- byte[] hashData = new byte[0x80];
- Array.Copy(Data, hashData, 0x80);
- return hashData;
- }
- set
- {
- if (value.Length != 0x80)
- throw new ArgumentOutOfRangeException(value.Length.ToString("X5"));
- Array.Copy(value, Data, value.Length);
- }
+ if (value.Length != 0x80)
+ throw new ArgumentOutOfRangeException(value.Length.ToString("X5"));
+ Array.Copy(value, Data, value.Length);
}
- private string Magic => new string(Data.Skip(0x80).Take(4).Select(c => (char)c).ToArray());
}
-}
+
+ public string Magic => new(Data.Skip(0x80).Take(4).Select(c => (char)c).ToArray());
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/CTR.cs b/pk3DS.Core/CTR/CTR.cs
index bbf85bbc23..75db11303e 100644
--- a/pk3DS.Core/CTR/CTR.cs
+++ b/pk3DS.Core/CTR/CTR.cs
@@ -1,5 +1,4 @@
using System;
-using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
@@ -7,351 +6,370 @@
using System.Windows.Forms;
using pk3DS.Core.Properties;
-namespace pk3DS.Core.CTR
+namespace pk3DS.Core.CTR;
+
+public static class CTRUtil
{
- public class CTRUtil
+ internal const uint MEDIA_UNIT_SIZE = 0x200;
+
+ // Main wrapper that assembles the ROM based on the following specifications:
+ public static bool BuildROM(bool Card2, string LOGO_NAME,
+ string EXEFS_PATH, string ROMFS_PATH, string EXHEADER_PATH,
+ string SERIAL_TEXT, string SAVE_PATH,
+ bool trimmed = false, ProgressBar PB_Show = null, RichTextBox TB_Progress = null)
{
- internal const uint MEDIA_UNIT_SIZE = 0x200;
+ PB_Show ??= new ProgressBar();
+ TB_Progress ??= new RichTextBox();
- // Main wrapper that assembles the ROM based on the following specifications:
- public static bool buildROM(bool Card2, string LOGO_NAME,
- string EXEFS_PATH, string ROMFS_PATH, string EXHEADER_PATH,
- string SERIAL_TEXT, string SAVE_PATH,
- ProgressBar PB_Show = null, RichTextBox TB_Progress = null)
+ // Sanity check the input files.
+ if (!
+ ((File.Exists(EXEFS_PATH) || Directory.Exists(EXEFS_PATH))
+ && (File.Exists(ROMFS_PATH) || Directory.Exists(ROMFS_PATH))
+ && File.Exists(EXHEADER_PATH)))
{
- PB_Show = PB_Show ?? new ProgressBar();
- TB_Progress = TB_Progress ?? new RichTextBox();
+ return false;
+ }
- // Sanity check the input files.
- if (!
- ((File.Exists(EXEFS_PATH) || Directory.Exists(EXEFS_PATH))
- && (File.Exists(ROMFS_PATH) || Directory.Exists(ROMFS_PATH))
- && File.Exists(EXHEADER_PATH)))
- return false;
+ // If ExeFS and RomFS are not built, build.
+ if (!File.Exists(EXEFS_PATH) && Directory.Exists(EXEFS_PATH))
+ ExeFS.PackExeFS(Directory.GetFiles(EXEFS_PATH), EXEFS_PATH = "exefs.bin");
+ if (!File.Exists(ROMFS_PATH) && Directory.Exists(ROMFS_PATH))
+ RomFS.BuildRomFS(ROMFS_PATH, ROMFS_PATH = "romfs.bin", TB_Progress, PB_Show);
- // If ExeFS and RomFS are not built, build.
- if (!File.Exists(EXEFS_PATH) && Directory.Exists(EXEFS_PATH))
- ExeFS.set(Directory.GetFiles(EXEFS_PATH), EXEFS_PATH = "exefs.bin");
- if (!File.Exists(ROMFS_PATH) && Directory.Exists(ROMFS_PATH))
- RomFS.BuildRomFS(ROMFS_PATH, ROMFS_PATH = "romfs.bin", TB_Progress, PB_Show);
+ NCCH NCCH = SetNCCH(EXEFS_PATH, ROMFS_PATH, EXHEADER_PATH, SERIAL_TEXT, LOGO_NAME, TB_Progress);
+ NCSD NCSD = SetNCSD(NCCH, Card2, TB_Progress);
+ bool success = WriteROM(NCSD, SAVE_PATH, trimmed, PB_Show, TB_Progress);
+ return success;
+ }
- NCCH NCCH = setNCCH(EXEFS_PATH, ROMFS_PATH, EXHEADER_PATH, SERIAL_TEXT, LOGO_NAME, PB_Show, TB_Progress);
- NCSD NCSD = setNCSD(NCCH, Card2, PB_Show, TB_Progress);
- bool success = writeROM(NCSD, SAVE_PATH, PB_Show, TB_Progress);
- return success;
- }
+ // Sub methods that drive the operation
+ internal static NCCH SetNCCH(string EXEFS_PATH, string ROMFS_PATH, string EXHEADER_PATH, string TB_Serial, string LOGO_NAME, RichTextBox TB_Progress = null)
+ {
+ TB_Progress ??= new RichTextBox();
- // Sub methods that drive the operation
- internal static NCCH setNCCH(string EXEFS_PATH, string ROMFS_PATH, string EXHEADER_PATH, string TB_Serial, string LOGO_NAME,
- ProgressBar PB_Show = null, RichTextBox TB_Progress = null)
+ UpdateTB(TB_Progress, "Creating NCCH...");
+ UpdateTB(TB_Progress, "Adding Exheader...");
+ var NCCH = new NCCH
{
- PB_Show = PB_Show ?? new ProgressBar();
- TB_Progress = TB_Progress ?? new RichTextBox();
+ Exheader = new Exheader(EXHEADER_PATH),
+ plainregion = [],
+ };
+ if (NCCH.Exheader.IsSupported())
+ {
+ UpdateTB(TB_Progress, "Detected Pokemon Game. Adding Plain Region...");
+ if (NCCH.Exheader.IsXY())
+ NCCH.plainregion = Resources.XY;
+ else if (NCCH.Exheader.IsORAS())
+ NCCH.plainregion = Resources.ORAS;
+ else if (NCCH.Exheader.IsSM())
+ NCCH.plainregion = Resources.SuMo;
+ else if (NCCH.Exheader.IsUSUM())
+ NCCH.plainregion = Resources.USUM;
+ }
+ UpdateTB(TB_Progress, "Adding ExeFS...");
+ NCCH.ExeFS = new ExeFS(EXEFS_PATH);
+ UpdateTB(TB_Progress, "Adding RomFS...");
+ NCCH.RomFS = new RomFS(ROMFS_PATH);
- updateTB(TB_Progress, "Creating NCCH...");
- updateTB(TB_Progress, "Adding Exheader...");
- NCCH NCCH = new NCCH
- {
- exheader = new Exheader(EXHEADER_PATH),
- plainregion = new byte[0]
- };
- if (NCCH.exheader.isPokemon())
- {
- updateTB(TB_Progress, "Detected Pokemon Game. Adding Plain Region...");
- if (NCCH.exheader.isXY())
- NCCH.plainregion = (byte[])Resources.ResourceManager.GetObject("XY");
- else if (NCCH.exheader.isORAS())
- NCCH.plainregion = (byte[])Resources.ResourceManager.GetObject("ORAS");
- }
- updateTB(TB_Progress, "Adding ExeFS...");
- NCCH.exefs = new ExeFS(EXEFS_PATH);
- updateTB(TB_Progress, "Adding RomFS...");
- NCCH.romfs = new RomFS(ROMFS_PATH);
+ UpdateTB(TB_Progress, "Adding Logo...");
+ NCCH.logo = (byte[])Resources.ResourceManager.GetObject(LOGO_NAME);
+ UpdateTB(TB_Progress, "Assembling NCCH Header...");
+ ulong Len = 0x200; //NCCH Signature + NCCH Header
+ NCCH.Header = new NCCH.NCCHHeader { Signature = new byte[0x100], Magic = 0x4843434E };
+ NCCH.Header.TitleId = NCCH.Header.ProgramId = NCCH.Exheader.TitleID;
+ NCCH.Header.MakerCode = 0x3130; //01
+ NCCH.Header.FormatVersion = 0x2; //Default
+ NCCH.Header.LogoHash = SHA256.HashData(NCCH.logo);
+ NCCH.Header.ProductCode = Encoding.ASCII.GetBytes(TB_Serial);
+ Array.Resize(ref NCCH.Header.ProductCode, 0x10);
+ NCCH.Header.ExheaderHash = NCCH.Exheader.GetSuperBlockHash();
+ NCCH.Header.ExheaderSize = (uint)NCCH.Exheader.Data.Length;
+ Len += NCCH.Header.ExheaderSize + (uint)NCCH.Exheader.AccessDescriptor.Length;
+ NCCH.Header.Flags = new byte[0x8];
+ //FLAGS
+ NCCH.Header.Flags[3] = 0; // Crypto: 0 = <7.x, 1=7.x;
+ NCCH.Header.Flags[4] = 1; // Content Platform: 1 = CTR;
+ NCCH.Header.Flags[5] = 0x3; // Content Type Bitflags: 1=Data, 2=Executable, 4=SysUpdate, 8=Manual, 0x10=Trial;
+ NCCH.Header.Flags[6] = 0; // MEDIA_UNIT_SIZE = 0x200*Math.Pow(2, Content.header.Flags[6]);
+ NCCH.Header.Flags[7] = 1; // FixedCrypto = 1, NoMountRomfs = 2; NoCrypto=4;
+ NCCH.Header.LogoOffset = (uint)(Len / MEDIA_UNIT_SIZE);
+ NCCH.Header.LogoSize = (uint)(NCCH.logo.Length / MEDIA_UNIT_SIZE);
+ Len += (uint)NCCH.logo.Length;
+ NCCH.Header.PlainRegionOffset = (uint)(NCCH.plainregion.Length > 0 ? Len / MEDIA_UNIT_SIZE : 0);
+ NCCH.Header.PlainRegionSize = (uint)NCCH.plainregion.Length / MEDIA_UNIT_SIZE;
+ Len += (uint)NCCH.plainregion.Length;
+ NCCH.Header.ExefsOffset = (uint)(Len / MEDIA_UNIT_SIZE);
+ NCCH.Header.ExefsSize = (uint)(NCCH.ExeFS.Data.Length / MEDIA_UNIT_SIZE);
+ NCCH.Header.ExefsSuperBlockSize = 0x200 / MEDIA_UNIT_SIZE; //Static 0x200 for exefs superblock
+ Len += (uint)NCCH.ExeFS.Data.Length;
+ Len = (uint)Align(Len, 0x1000); //Romfs Start is aligned to 0x1000
+ NCCH.Header.RomfsOffset = (uint)(Len / MEDIA_UNIT_SIZE);
+ NCCH.Header.RomfsSize = (uint)(new FileInfo(NCCH.RomFS.FileName).Length / MEDIA_UNIT_SIZE);
+ NCCH.Header.RomfsSuperBlockSize = NCCH.RomFS.SuperBlockLen / MEDIA_UNIT_SIZE;
+ Len += NCCH.Header.RomfsSize * MEDIA_UNIT_SIZE;
+ NCCH.Header.ExefsHash = NCCH.ExeFS.SuperBlockHash;
+ NCCH.Header.RomfsHash = NCCH.RomFS.SuperBlockHash;
+ NCCH.Header.Size = (uint)(Len / MEDIA_UNIT_SIZE);
+ //Build the Header byte[].
+ UpdateTB(TB_Progress, "Building NCCH Header...");
+ NCCH.Header.BuildHeader();
- updateTB(TB_Progress, "Adding Logo...");
- NCCH.logo = (byte[])Resources.ResourceManager.GetObject(LOGO_NAME);
- updateTB(TB_Progress, "Assembling NCCH Header...");
- ulong Len = 0x200; //NCCH Signature + NCCH Header
- NCCH.header = new NCCH.Header { Signature = new byte[0x100], Magic = 0x4843434E };
- NCCH.header.TitleId = NCCH.header.ProgramId = NCCH.exheader.TitleID;
- NCCH.header.MakerCode = 0x3130; //01
- NCCH.header.FormatVersion = 0x2; //Default
- NCCH.header.LogoHash = new SHA256Managed().ComputeHash(NCCH.logo);
- NCCH.header.ProductCode = Encoding.ASCII.GetBytes(TB_Serial);
- Array.Resize(ref NCCH.header.ProductCode, 0x10);
- NCCH.header.ExheaderHash = NCCH.exheader.GetSuperBlockHash();
- NCCH.header.ExheaderSize = (uint)NCCH.exheader.Data.Length;
- Len += NCCH.header.ExheaderSize + (uint)NCCH.exheader.AccessDescriptor.Length;
- NCCH.header.Flags = new byte[0x8];
- //FLAGS
- NCCH.header.Flags[3] = 0; // Crypto: 0 = <7.x, 1=7.x;
- NCCH.header.Flags[4] = 1; // Content Platform: 1 = CTR;
- NCCH.header.Flags[5] = 0x3; // Content Type Bitflags: 1=Data, 2=Executable, 4=SysUpdate, 8=Manual, 0x10=Trial;
- NCCH.header.Flags[6] = 0; // MEDIA_UNIT_SIZE = 0x200*Math.Pow(2, Content.header.Flags[6]);
- NCCH.header.Flags[7] = 1; // FixedCrypto = 1, NoMountRomfs = 2; NoCrypto=4;
- NCCH.header.LogoOffset = (uint)(Len / MEDIA_UNIT_SIZE);
- NCCH.header.LogoSize = (uint)(NCCH.logo.Length / MEDIA_UNIT_SIZE);
- Len += (uint)NCCH.logo.Length;
- NCCH.header.PlainRegionOffset = (uint)(NCCH.plainregion.Length > 0 ? Len / MEDIA_UNIT_SIZE : 0);
- NCCH.header.PlainRegionSize = (uint)NCCH.plainregion.Length / MEDIA_UNIT_SIZE;
- Len += (uint)NCCH.plainregion.Length;
- NCCH.header.ExefsOffset = (uint)(Len / MEDIA_UNIT_SIZE);
- NCCH.header.ExefsSize = (uint)(NCCH.exefs.Data.Length / MEDIA_UNIT_SIZE);
- NCCH.header.ExefsSuperBlockSize = 0x200 / MEDIA_UNIT_SIZE; //Static 0x200 for exefs superblock
- Len += (uint)NCCH.exefs.Data.Length;
- Len = (uint)Align(Len, 0x1000); //Romfs Start is aligned to 0x1000
- NCCH.header.RomfsOffset = (uint)(Len / MEDIA_UNIT_SIZE);
- NCCH.header.RomfsSize = (uint)(new FileInfo(NCCH.romfs.FileName).Length / MEDIA_UNIT_SIZE);
- NCCH.header.RomfsSuperBlockSize = NCCH.romfs.SuperBlockLen / MEDIA_UNIT_SIZE;
- Len += NCCH.header.RomfsSize * MEDIA_UNIT_SIZE;
- NCCH.header.ExefsHash = NCCH.exefs.SuperBlockHash;
- NCCH.header.RomfsHash = NCCH.romfs.SuperBlockHash;
- NCCH.header.Size = (uint)(Len / MEDIA_UNIT_SIZE);
- //Build the Header byte[].
- updateTB(TB_Progress, "Building NCCH Header...");
- NCCH.header.BuildHeader();
+ return NCCH;
+ }
- return NCCH;
+ internal static NCSD SetNCSD(NCCH NCCH, bool Card2, RichTextBox TB_Progress = null)
+ {
+ TB_Progress ??= new RichTextBox();
+ UpdateTB(TB_Progress, "Building NCSD Header...");
+ var NCSD = new NCSD
+ {
+ NCCH_Array = [NCCH],
+ Card2 = Card2,
+ Header = new NCSD.NCSDHeader { Signature = new byte[0x100], Magic = 0x4453434E },
+ };
+ ulong Length = 0x80 * 0x100000; // 128 MB
+ while (Length <= (NCCH.Header.Size * MEDIA_UNIT_SIZE) + 0x400000) //Extra 4 MB for potential save data
+ {
+ Length *= 2;
}
- internal static NCSD setNCSD(NCCH NCCH, bool Card2,
- ProgressBar PB_Show = null, RichTextBox TB_Progress = null)
+ NCSD.Header.MediaSize = (uint)(Length / MEDIA_UNIT_SIZE);
+ NCSD.Header.TitleId = NCCH.Exheader.TitleID;
+ NCSD.Header.OffsetSizeTable = new NCSD.NCCH_Meta[8];
+ ulong OSOfs = 0x4000;
+ for (int i = 0; i < NCSD.Header.OffsetSizeTable.Length; i++)
{
- PB_Show = PB_Show ?? new ProgressBar();
- TB_Progress = TB_Progress ?? new RichTextBox();
- updateTB(TB_Progress, "Building NCSD Header...");
- NCSD NCSD = new NCSD
- {
- NCCH_Array = new List {NCCH},
- Card2 = Card2,
- header = new NCSD.Header {Signature = new byte[0x100], Magic = 0x4453434E}
- };
- ulong Length = 0x80 * 0x100000; // 128 MB
- while (Length <= NCCH.header.Size * MEDIA_UNIT_SIZE + 0x400000) //Extra 4 MB for potential save data
+ var ncchm = new NCSD.NCCH_Meta();
+ if (i < NCSD.NCCH_Array.Count)
{
- Length *= 2;
+ ncchm.Offset = (uint)(OSOfs / MEDIA_UNIT_SIZE);
+ ncchm.Size = NCSD.NCCH_Array[i].Header.Size;
}
- NCSD.header.MediaSize = (uint)(Length / MEDIA_UNIT_SIZE);
- NCSD.header.TitleId = NCCH.exheader.TitleID;
- NCSD.header.OffsetSizeTable = new NCSD.NCCH_Meta[8];
- ulong OSOfs = 0x4000;
- for (int i = 0; i < NCSD.header.OffsetSizeTable.Length; i++)
- {
- NCSD.NCCH_Meta ncchm = new NCSD.NCCH_Meta();
- if (i < NCSD.NCCH_Array.Count)
- {
- ncchm.Offset = (uint)(OSOfs / MEDIA_UNIT_SIZE);
- ncchm.Size = NCSD.NCCH_Array[i].header.Size;
- }
- else
- {
- ncchm.Offset = 0;
- ncchm.Size = 0;
- }
- NCSD.header.OffsetSizeTable[i] = ncchm;
- OSOfs += ncchm.Size * MEDIA_UNIT_SIZE;
- }
- NCSD.header.flags = new byte[0x8];
- NCSD.header.flags[0] = 0; // 0-255 seconds of waiting for save writing.
- NCSD.header.flags[3] = (byte)(NCSD.Card2 ? 2 : 1); // Media Card Device: 1 = NOR Flash, 2 = None, 3 = BT
- NCSD.header.flags[4] = 1; // Media Platform Index: 1 = CTR
- NCSD.header.flags[5] = (byte)(NCSD.Card2 ? 2 : 1); // Media Type Index: 0 = Inner Device, 1 = Card1, 2 = Card2, 3 = Extended Device
- NCSD.header.flags[6] = 0; // Media Unit Size. Same as NCCH.
- NCSD.header.flags[7] = 0; // Old Media Card Device.
- NCSD.header.NCCHIdTable = new ulong[8];
- for (int i = 0; i < NCSD.NCCH_Array.Count; i++)
+ else
{
- NCSD.header.NCCHIdTable[i] = NCSD.NCCH_Array[i].header.TitleId;
+ ncchm.Offset = 0;
+ ncchm.Size = 0;
}
- NCSD.cardinfoheader = new NCSD.CardInfoHeader
+ NCSD.Header.OffsetSizeTable[i] = ncchm;
+ OSOfs += ncchm.Size * MEDIA_UNIT_SIZE;
+ }
+ NCSD.Header.flags = new byte[0x8];
+ NCSD.Header.flags[0] = 0; // 0-255 seconds of waiting for save writing.
+ NCSD.Header.flags[3] = NCSD.Card2 ? (byte)2 : (byte)1; // Media Card Device: 1 = NOR Flash, 2 = None, 3 = BT
+ NCSD.Header.flags[4] = 1; // Media Platform Index: 1 = CTR
+ NCSD.Header.flags[5] = NCSD.Card2 ? (byte)2 : (byte)1; // Media Type Index: 0 = Inner Device, 1 = Card1, 2 = Card2, 3 = Extended Device
+ NCSD.Header.flags[6] = 0; // Media Unit Size. Same as NCCH.
+ NCSD.Header.flags[7] = 0; // Old Media Card Device.
+ NCSD.Header.NCCHIdTable = new ulong[8];
+ for (int i = 0; i < NCSD.NCCH_Array.Count; i++)
+ {
+ NCSD.Header.NCCHIdTable[i] = NCSD.NCCH_Array[i].Header.TitleId;
+ }
+ NCSD.cardinfoheader = new NCSD.CardInfoHeader
+ {
+ WritableAddress = (uint)NCSD.GetWritableAddress(),
+ CardInfoBitmask = 0,
+ CIN = new NCSD.CardInfoHeader.CardInfoNotes
{
- WritableAddress = (uint)NCSD.GetWritableAddress(),
- CardInfoBitmask = 0,
- CIN = new NCSD.CardInfoHeader.CardInfoNotes
- {
- Reserved0 = new byte[0xF8],
- MediaSizeUsed = OSOfs,
- Reserved1 = 0,
- Unknown = 0,
- Reserved2 = new byte[0xC],
- CVerTitleId = 0,
- CVerTitleVersion = 0,
- Reserved3 = new byte[0xCD6]
- },
- NCCH0TitleId = NCSD.NCCH_Array[0].header.TitleId,
- Reserved0 = 0,
- InitialData = new byte[0x30]
- };
- RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
- byte[] randbuffer = new byte[0x2C];
- rng.GetBytes(randbuffer);
- Array.Copy(randbuffer, NCSD.cardinfoheader.InitialData, randbuffer.Length);
- NCSD.cardinfoheader.Reserved1 = new byte[0xC0];
- NCSD.cardinfoheader.NCCH0Header = new byte[0x100];
- Array.Copy(NCSD.NCCH_Array[0].header.Data, 0x100, NCSD.cardinfoheader.NCCH0Header, 0, 0x100);
+ Reserved0 = new byte[0xF8],
+ MediaSizeUsed = OSOfs,
+ Reserved1 = 0,
+ Unknown = 0,
+ Reserved2 = new byte[0xC],
+ CVerTitleId = 0,
+ CVerTitleVersion = 0,
+ Reserved3 = new byte[0xCD6],
+ },
+ NCCH0TitleId = NCSD.NCCH_Array[0].Header.TitleId,
+ Reserved0 = 0,
+ InitialData = new byte[0x30],
+ };
+ byte[] randbuffer = new byte[0x2C];
+ Random.Shared.NextBytes(randbuffer);
+ Array.Copy(randbuffer, NCSD.cardinfoheader.InitialData, randbuffer.Length);
+ NCSD.cardinfoheader.Reserved1 = new byte[0xC0];
+ NCSD.cardinfoheader.NCCH0Header = new byte[0x100];
+ Array.Copy(NCSD.NCCH_Array[0].Header.Data, 0x100, NCSD.cardinfoheader.NCCH0Header, 0, 0x100);
- NCSD.BuildHeader();
+ NCSD.BuildHeader();
- //NCSD is Initialized
- return NCSD;
- }
- internal static bool writeROM(NCSD NCSD, string SAVE_PATH,
- ProgressBar PB_Show = null, RichTextBox TB_Progress = null)
+ //NCSD is Initialized
+ return NCSD;
+ }
+
+ internal static bool WriteROM(NCSD NCSD, string SAVE_PATH, bool trimmed = false,
+ ProgressBar PB_Show = null, RichTextBox TB_Progress = null)
+ {
+ PB_Show ??= new ProgressBar();
+ TB_Progress ??= new RichTextBox();
+ using (var OutFileStream = new FileStream(SAVE_PATH, FileMode.Create))
{
- PB_Show = PB_Show ?? new ProgressBar();
- TB_Progress = TB_Progress ?? new RichTextBox();
- using (FileStream OutFileStream = new FileStream(SAVE_PATH, FileMode.Create))
+ UpdateTB(TB_Progress, "Writing NCSD Header...");
+ OutFileStream.Write(NCSD.Data, 0, NCSD.Data.Length);
+ UpdateTB(TB_Progress, "Writing NCCH...");
+ OutFileStream.Write(NCSD.NCCH_Array[0].Header.Data, 0, NCSD.NCCH_Array[0].Header.Data.Length); //Write NCCH header
+ //AES time.
+ byte[] key = new byte[0x10]; //Fixed-Crypto key is all zero.
+ for (int i = 0; i < 3; i++)
{
- updateTB(TB_Progress, "Writing NCSD Header...");
- OutFileStream.Write(NCSD.Data, 0, NCSD.Data.Length);
- updateTB(TB_Progress, "Writing NCCH...");
- OutFileStream.Write(NCSD.NCCH_Array[0].header.Data, 0, NCSD.NCCH_Array[0].header.Data.Length); //Write NCCH header
- //AES time.
- byte[] key = new byte[0x10]; //Fixed-Crypto key is all zero.
- for (int i = 0; i < 3; i++)
+ var aesctr = new AesCtr(key, NCSD.NCCH_Array[0].Header.ProgramId, (ulong)(i + 1) << 56); //CTR is ProgramID, section id<<88
+ switch (i)
{
- AesCtr aesctr = new AesCtr(key, NCSD.NCCH_Array[0].header.ProgramId, (ulong)(i + 1) << 56); //CTR is ProgramID, section id<<88
- switch (i)
- {
- case 0: //Exheader + AccessDesc
- updateTB(TB_Progress, "Writing Exheader...");
- byte[] inEncExheader = new byte[NCSD.NCCH_Array[0].exheader.Data.Length + NCSD.NCCH_Array[0].exheader.AccessDescriptor.Length];
- byte[] outEncExheader = new byte[NCSD.NCCH_Array[0].exheader.Data.Length + NCSD.NCCH_Array[0].exheader.AccessDescriptor.Length];
- Array.Copy(NCSD.NCCH_Array[0].exheader.Data, inEncExheader, NCSD.NCCH_Array[0].exheader.Data.Length);
- Array.Copy(NCSD.NCCH_Array[0].exheader.AccessDescriptor, 0, inEncExheader, NCSD.NCCH_Array[0].exheader.Data.Length, NCSD.NCCH_Array[0].exheader.AccessDescriptor.Length);
- aesctr.TransformBlock(inEncExheader, 0, inEncExheader.Length, outEncExheader, 0);
- OutFileStream.Write(outEncExheader, 0, outEncExheader.Length); // Write Exheader
- break;
- case 1: //Exefs
- updateTB(TB_Progress, "Writing Exefs...");
- OutFileStream.Seek(0x4000 + NCSD.NCCH_Array[0].header.ExefsOffset * MEDIA_UNIT_SIZE, SeekOrigin.Begin);
- byte[] OutExefs = new byte[NCSD.NCCH_Array[0].exefs.Data.Length];
- aesctr.TransformBlock(NCSD.NCCH_Array[0].exefs.Data, 0, NCSD.NCCH_Array[0].exefs.Data.Length, OutExefs, 0);
- OutFileStream.Write(OutExefs, 0, OutExefs.Length);
- break;
- case 2: //Romfs
- updateTB(TB_Progress, "Writing Romfs...");
- OutFileStream.Seek(0x4000 + NCSD.NCCH_Array[0].header.RomfsOffset * MEDIA_UNIT_SIZE, SeekOrigin.Begin);
- using (FileStream InFileStream = new FileStream(NCSD.NCCH_Array[0].romfs.FileName, FileMode.Open, FileAccess.Read))
+ case 0: //Exheader + AccessDesc
+ UpdateTB(TB_Progress, "Writing Exheader...");
+ byte[] inEncExheader = new byte[NCSD.NCCH_Array[0].Exheader.Data.Length + NCSD.NCCH_Array[0].Exheader.AccessDescriptor.Length];
+ byte[] outEncExheader = new byte[NCSD.NCCH_Array[0].Exheader.Data.Length + NCSD.NCCH_Array[0].Exheader.AccessDescriptor.Length];
+ Array.Copy(NCSD.NCCH_Array[0].Exheader.Data, inEncExheader, NCSD.NCCH_Array[0].Exheader.Data.Length);
+ Array.Copy(NCSD.NCCH_Array[0].Exheader.AccessDescriptor, 0, inEncExheader, NCSD.NCCH_Array[0].Exheader.Data.Length, NCSD.NCCH_Array[0].Exheader.AccessDescriptor.Length);
+ aesctr.TransformBlock(inEncExheader, 0, inEncExheader.Length, outEncExheader, 0);
+ OutFileStream.Write(outEncExheader, 0, outEncExheader.Length); // Write Exheader
+ break;
+ case 1: //Exefs
+ UpdateTB(TB_Progress, "Writing Exefs...");
+ OutFileStream.Seek(0x4000 + (NCSD.NCCH_Array[0].Header.ExefsOffset * MEDIA_UNIT_SIZE), SeekOrigin.Begin);
+ byte[] OutExefs = new byte[NCSD.NCCH_Array[0].ExeFS.Data.Length];
+ aesctr.TransformBlock(NCSD.NCCH_Array[0].ExeFS.Data, 0, NCSD.NCCH_Array[0].ExeFS.Data.Length, OutExefs, 0);
+ OutFileStream.Write(OutExefs, 0, OutExefs.Length);
+ break;
+ case 2: //Romfs
+ UpdateTB(TB_Progress, "Writing Romfs...");
+ OutFileStream.Seek(0x4000 + (NCSD.NCCH_Array[0].Header.RomfsOffset * MEDIA_UNIT_SIZE), SeekOrigin.Begin);
+ using (var InFileStream = new FileStream(NCSD.NCCH_Array[0].RomFS.FileName, FileMode.Open, FileAccess.Read))
+ {
+ uint BUFFER_SIZE;
+ ulong RomfsLen = NCSD.NCCH_Array[0].Header.RomfsSize * MEDIA_UNIT_SIZE;
+ PB_Show.Invoke(() =>
+ {
+ PB_Show.Minimum = 0;
+ PB_Show.Maximum = (int)(RomfsLen / 0x400000);
+ PB_Show.Value = 0;
+ PB_Show.Step = 1;
+ });
+ for (ulong j = 0; j < RomfsLen; j += BUFFER_SIZE)
{
- uint BUFFER_SIZE;
- ulong RomfsLen = NCSD.NCCH_Array[0].header.RomfsSize * MEDIA_UNIT_SIZE;
- PB_Show.Invoke((Action)(() =>
- {
- PB_Show.Minimum = 0;
- PB_Show.Maximum = (int)(RomfsLen / 0x400000);
- PB_Show.Value = 0;
- PB_Show.Step = 1;
- }));
- for (ulong j = 0; j < RomfsLen; j += BUFFER_SIZE)
- {
- BUFFER_SIZE = RomfsLen - j > 0x400000 ? 0x400000 : (uint)(RomfsLen - j);
- byte[] buf = new byte[BUFFER_SIZE];
- byte[] outbuf = new byte[BUFFER_SIZE];
- InFileStream.Read(buf, 0, (int)BUFFER_SIZE);
- aesctr.TransformBlock(buf, 0, (int)BUFFER_SIZE, outbuf, 0);
- OutFileStream.Write(outbuf, 0, (int)BUFFER_SIZE);
- PB_Show.Invoke((Action)PB_Show.PerformStep);
- }
+ BUFFER_SIZE = RomfsLen - j > 0x400000 ? 0x400000 : (uint)(RomfsLen - j);
+ byte[] buf = new byte[BUFFER_SIZE];
+ byte[] outbuf = new byte[BUFFER_SIZE];
+ InFileStream.Read(buf, 0, (int)BUFFER_SIZE);
+ aesctr.TransformBlock(buf, 0, (int)BUFFER_SIZE, outbuf, 0);
+ OutFileStream.Write(outbuf, 0, (int)BUFFER_SIZE);
+ PB_Show.Invoke(PB_Show.PerformStep);
}
- break;
- }
- }
- updateTB(TB_Progress, "Writing Logo...");
- OutFileStream.Seek(0x4000 + NCSD.NCCH_Array[0].header.LogoOffset * MEDIA_UNIT_SIZE, SeekOrigin.Begin);
- OutFileStream.Write(NCSD.NCCH_Array[0].logo, 0, NCSD.NCCH_Array[0].logo.Length);
- if (NCSD.NCCH_Array[0].plainregion.Length > 0)
- {
- updateTB(TB_Progress, "Writing Plain Region...");
- OutFileStream.Seek(0x4000 + NCSD.NCCH_Array[0].header.PlainRegionOffset * MEDIA_UNIT_SIZE, SeekOrigin.Begin);
- OutFileStream.Write(NCSD.NCCH_Array[0].plainregion, 0, NCSD.NCCH_Array[0].plainregion.Length);
+ }
+ break;
}
+ }
+ UpdateTB(TB_Progress, "Writing Logo...");
+ OutFileStream.Seek(0x4000 + (NCSD.NCCH_Array[0].Header.LogoOffset * MEDIA_UNIT_SIZE), SeekOrigin.Begin);
+ OutFileStream.Write(NCSD.NCCH_Array[0].logo, 0, NCSD.NCCH_Array[0].logo.Length);
+ if (NCSD.NCCH_Array[0].plainregion.Length > 0)
+ {
+ UpdateTB(TB_Progress, "Writing Plain Region...");
+ OutFileStream.Seek(0x4000 + (NCSD.NCCH_Array[0].Header.PlainRegionOffset * MEDIA_UNIT_SIZE), SeekOrigin.Begin);
+ OutFileStream.Write(NCSD.NCCH_Array[0].plainregion, 0, NCSD.NCCH_Array[0].plainregion.Length);
+ }
- //NCSD Padding
- OutFileStream.Seek(NCSD.header.OffsetSizeTable[NCSD.NCCH_Array.Count - 1].Offset * MEDIA_UNIT_SIZE + NCSD.header.OffsetSizeTable[NCSD.NCCH_Array.Count - 1].Size * MEDIA_UNIT_SIZE, SeekOrigin.Begin);
- ulong TotalLen = NCSD.header.MediaSize * MEDIA_UNIT_SIZE;
+ //NCSD Padding
+ if (!trimmed)
+ {
+ OutFileStream.Seek((NCSD.Header.OffsetSizeTable[NCSD.NCCH_Array.Count - 1].Offset * MEDIA_UNIT_SIZE) + (NCSD.Header.OffsetSizeTable[NCSD.NCCH_Array.Count - 1].Size * MEDIA_UNIT_SIZE), SeekOrigin.Begin);
+ ulong TotalLen = NCSD.Header.MediaSize * MEDIA_UNIT_SIZE;
byte[] Buffer = Enumerable.Repeat((byte)0xFF, 0x400000).ToArray();
- updateTB(TB_Progress, "Writing NCSD Padding...");
+ UpdateTB(TB_Progress, "Writing NCSD Padding...");
while ((ulong)OutFileStream.Position < TotalLen)
{
int BUFFER_LEN = TotalLen - (ulong)OutFileStream.Position < 0x400000 ? (int)(TotalLen - (ulong)OutFileStream.Position) : 0x400000;
OutFileStream.Write(Buffer, 0, BUFFER_LEN);
}
}
+ }
- //Delete Temporary Romfs File
- if (NCSD.NCCH_Array[0].romfs.isTempFile)
- File.Delete(NCSD.NCCH_Array[0].romfs.FileName);
+ //Delete Temporary Romfs File
+ if (NCSD.NCCH_Array[0].RomFS.isTempFile)
+ File.Delete(NCSD.NCCH_Array[0].RomFS.FileName);
- updateTB(TB_Progress, "Done!");
- return true;
- }
+ UpdateTB(TB_Progress, "Done!");
+ return true;
+ }
- // Utility
- internal static bool isValid(string exeFS, string romFS, string exeheader, string path, string serial, bool Card2)
+ // Utility
+ internal static bool IsValid(string exeFS, string romFS, string exeheader, string path, string serial, bool Card2)
+ {
+ bool isSerialValid = true;
+ if (serial.Length == 10)
{
- bool isSerialValid = true;
- if (serial.Length == 10)
+ string[] subs = serial.Split('-');
+ if (subs.Length != 3)
+ {
+ isSerialValid = false;
+ }
+ else
{
- string[] subs = serial.Split('-');
- if (subs.Length != 3)
+ if (subs[0].Length != 3 || subs[1].Length != 1 || subs[2].Length != 4)
+ {
+ isSerialValid = false;
+ }
+ else if (subs[0] != "CTR" && subs[0] != "KTR")
+ {
isSerialValid = false;
+ }
+ else if (subs[1] != "P" && subs[1] != "N" && subs[2] != "U")
+ {
+ isSerialValid = false;
+ }
else
{
- if (subs[0].Length != 3 || subs[1].Length != 1 || subs[2].Length != 4)
+ if (subs[2].Any(c => !char.IsLetterOrDigit(c)))
isSerialValid = false;
- else if (subs[0] != "CTR" && subs[0] != "KTR")
- isSerialValid = false;
- else if (subs[1] != "P" && subs[1] != "N" && subs[2] != "U")
- isSerialValid = false;
- else
- {
- foreach (char c in subs[2].Where(c => !Char.IsLetterOrDigit(c)))
- isSerialValid = false;
- }
}
}
- else
- {
- isSerialValid = false;
- }
- if (exeFS == string.Empty
- || romFS == string.Empty
- || exeheader == string.Empty
- || path == string.Empty
- || !isSerialValid)
- return false;
-
- Exheader exh = new Exheader(exeheader);
- return !exh.isPokemon() || Card2;
}
- internal static void updateTB(RichTextBox RTB, string progress)
+ else
+ {
+ isSerialValid = false;
+ }
+ if (string.IsNullOrEmpty(exeFS)
+ || string.IsNullOrEmpty(romFS)
+ || string.IsNullOrEmpty(exeheader)
+ || string.IsNullOrEmpty(path)
+ || !isSerialValid)
+ {
+ return false;
+ }
+
+ var exh = new Exheader(exeheader);
+ return !exh.IsSupported() || Card2;
+ }
+
+ internal static void UpdateTB(RichTextBox RTB, string progress)
+ {
+ try
{
- try
+ if (RTB.InvokeRequired)
{
- if (RTB.InvokeRequired)
- RTB.Invoke((MethodInvoker)delegate
- {
- RTB.AppendText(Environment.NewLine + progress);
- RTB.SelectionStart = RTB.Text.Length;
- RTB.ScrollToCaret();
- });
- else
+ RTB.Invoke((MethodInvoker)delegate
{
+ RTB.AppendText(Environment.NewLine + progress);
RTB.SelectionStart = RTB.Text.Length;
RTB.ScrollToCaret();
- RTB.AppendText(progress + Environment.NewLine);
- }
+ });
}
- catch { }
- }
- internal static ulong Align(ulong input, ulong alignsize)
- {
- ulong output = input;
- if (output % alignsize != 0)
+ else
{
- output += alignsize - output % alignsize;
+ RTB.SelectionStart = RTB.Text.Length;
+ RTB.ScrollToCaret();
+ RTB.AppendText(progress + Environment.NewLine);
}
- return output;
}
+ catch { }
+ }
+
+ internal static ulong Align(ulong input, ulong alignsize)
+ {
+ ulong output = input;
+ if (output % alignsize != 0)
+ {
+ output += alignsize - (output % alignsize);
+ }
+ return output;
}
-}
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/DARC.cs b/pk3DS.Core/CTR/DARC.cs
index c37247479a..6159d3478b 100644
--- a/pk3DS.Core/CTR/DARC.cs
+++ b/pk3DS.Core/CTR/DARC.cs
@@ -4,369 +4,371 @@
using System.Linq;
using System.Text;
-namespace pk3DS.Core.CTR
+namespace pk3DS.Core.CTR;
+
+public class DARC
{
- public class DARC
- {
- public byte[] Data;
- public DARCHeader Header;
- public FileTableEntry[] Entries;
- public NameTableEntry[] FileNameTable;
+ public byte[] Data;
+ public DARCHeader Header;
+ public FileTableEntry[] Entries;
+ public NameTableEntry[] FileNameTable;
- public DARC(byte[] Data = null)
+ public DARC(byte[] Data = null)
+ {
+ if (Data == null) return;
+ using var br = new BinaryReader(new MemoryStream(Data));
+ try
{
- if (Data == null) return;
- using (BinaryReader br = new BinaryReader(new MemoryStream(Data)))
- try
+ Header = new DARCHeader(br);
+ br.BaseStream.Position = Header.FileTableOffset;
+ var root = new FileTableEntry(br);
+ Entries = new FileTableEntry[root.DataLength];
+ Entries[0] = root;
+ for (int i = 1; i < root.DataLength; i++) Entries[i] = new FileTableEntry(br);
+ FileNameTable = new NameTableEntry[root.DataLength];
+ uint offs = 0;
+ for (int i = 0; i < root.DataLength; i++)
{
- Header = new DARCHeader(br);
- br.BaseStream.Position = Header.FileTableOffset;
- FileTableEntry root = new FileTableEntry(br);
- Entries = new FileTableEntry[root.DataLength];
- Entries[0] = root;
- for (int i = 1; i < root.DataLength; i++) Entries[i] = new FileTableEntry(br);
- FileNameTable = new NameTableEntry[root.DataLength];
- uint offs = 0;
- for (int i = 0; i < root.DataLength; i++)
- {
- char c; string s = string.Empty;
- while ((c = (char) br.ReadUInt16()) > 0) s += c;
+ char c; string s = string.Empty;
+ while ((c = (char)br.ReadUInt16()) > 0) s += c;
- FileNameTable[i] = new NameTableEntry(offs, s);
- offs += (uint)s.Length * 2 + 2;
- }
- br.BaseStream.Position = Header.FileDataOffset;
- this.Data = br.ReadBytes((int)(Header.FileSize - Header.FileDataOffset));
+ FileNameTable[i] = new NameTableEntry(offs, s);
+ offs += ((uint)s.Length * 2) + 2;
}
- catch (Exception)
- { br.Close(); }
+ br.BaseStream.Position = Header.FileDataOffset;
+ this.Data = br.ReadBytes((int)(Header.FileSize - Header.FileDataOffset));
}
+ catch (Exception)
+ { br.Close(); }
+ }
- public class DARCHeader
+ public class DARCHeader
+ {
+ public DARCHeader(BinaryReader br = null)
{
- public DARCHeader(BinaryReader br = null)
- {
- if (br == null) return;
- Signature = new string(br.ReadChars(4));
- if (Signature != "darc") throw new Exception(Signature);
- Endianness = br.ReadUInt16();
- HeaderSize = br.ReadUInt16();
- Version = br.ReadUInt32();
- FileSize = br.ReadUInt32();
- FileTableOffset = br.ReadUInt32();
- FileTableLength = br.ReadUInt32();
- FileDataOffset = br.ReadUInt32();
- }
- public string Signature;
- public ushort Endianness;
- public ushort HeaderSize;
- public uint Version;
- public uint FileSize;
- public uint FileTableOffset;
- public uint FileTableLength;
- public uint FileDataOffset;
+ if (br == null) return;
+ Signature = new string(br.ReadChars(4));
+ if (Signature != "darc") throw new Exception(Signature);
+ Endianness = br.ReadUInt16();
+ HeaderSize = br.ReadUInt16();
+ Version = br.ReadUInt32();
+ FileSize = br.ReadUInt32();
+ FileTableOffset = br.ReadUInt32();
+ FileTableLength = br.ReadUInt32();
+ FileDataOffset = br.ReadUInt32();
}
- public class FileTableEntry
+
+ public string Signature;
+ public ushort Endianness;
+ public ushort HeaderSize;
+ public uint Version;
+ public uint FileSize;
+ public uint FileTableOffset;
+ public uint FileTableLength;
+ public uint FileDataOffset;
+ }
+
+ public class FileTableEntry
+ {
+ public FileTableEntry(BinaryReader br = null)
{
- public FileTableEntry(BinaryReader br = null)
- {
- if (br == null) return;
- NameOffset = br.ReadUInt32();
- IsFolder = NameOffset >> 24 == 1;
- NameOffset &= 0xFFFFFF;
- DataOffset = br.ReadUInt32();
- DataLength = br.ReadUInt32();
- }
- public uint NameOffset;
- public bool IsFolder;
- public uint DataOffset; // FOLDER: Parent Entry Index
- public uint DataLength; // FOLDER: Next Folder Index
+ if (br == null) return;
+ NameOffset = br.ReadUInt32();
+ IsFolder = NameOffset >> 24 == 1;
+ NameOffset &= 0xFFFFFF;
+ DataOffset = br.ReadUInt32();
+ DataLength = br.ReadUInt32();
}
- public class NameTableEntry
+
+ public uint NameOffset;
+ public bool IsFolder;
+ public uint DataOffset; // FOLDER: Parent Entry Index
+ public uint DataLength; // FOLDER: Next Folder Index
+ }
+
+ public class NameTableEntry(uint offset, string fileName)
+ {
+ public uint NameOffset = offset;
+ public string FileName = fileName;
+ }
+
+ // DARC r/w
+ public static byte[] SetDARC(DARC darc)
+ {
+ // Package DARC into a writable array.
+ using var ms = new MemoryStream();
+ using var bw = new BinaryWriter(ms);
+ // Write Header
+ bw.Write(Encoding.ASCII.GetBytes(darc.Header.Signature));
+ bw.Write(darc.Header.Endianness);
+ bw.Write(darc.Header.HeaderSize);
+ bw.Write(darc.Header.Version);
+ bw.Write(darc.Header.FileSize);
+ bw.Write(darc.Header.FileTableOffset);
+ bw.Write(darc.Header.FileTableLength);
+ bw.Write(darc.Header.FileDataOffset);
+ // Write FileTableEntries
+ foreach (FileTableEntry entry in darc.Entries)
{
- public uint NameOffset;
- public string FileName;
- public NameTableEntry(uint offset, string fileName)
- {
- NameOffset = offset;
- FileName = fileName;
- }
+ bw.Write(entry.NameOffset | (entry.IsFolder ? (uint)1 << 24 : 0));
+ bw.Write(entry.DataOffset);
+ bw.Write(entry.DataLength);
}
-
- // DARC r/w
- public static byte[] setDARC(DARC darc)
+ foreach (NameTableEntry entry in darc.FileNameTable)
{
- // Package DARC into a writable array.
- using (MemoryStream ms = new MemoryStream())
- using (BinaryWriter bw = new BinaryWriter(ms))
- {
- // Write Header
- bw.Write(Encoding.ASCII.GetBytes(darc.Header.Signature));
- bw.Write(darc.Header.Endianness);
- bw.Write(darc.Header.HeaderSize);
- bw.Write(darc.Header.Version);
- bw.Write(darc.Header.FileSize);
- bw.Write(darc.Header.FileTableOffset);
- bw.Write(darc.Header.FileTableLength);
- bw.Write(darc.Header.FileDataOffset);
- // Write FileTableEntries
- foreach (FileTableEntry entry in darc.Entries)
- {
- bw.Write(entry.NameOffset | (entry.IsFolder ? (uint)1 << 24 : 0));
- bw.Write(entry.DataOffset);
- bw.Write(entry.DataLength);
- }
- foreach (NameTableEntry entry in darc.FileNameTable)
- {
- bw.Write(Encoding.Unicode.GetBytes(entry.FileName + "\0"));
- }
- while (bw.BaseStream.Position < darc.Header.FileDataOffset)
- bw.Write((byte)0);
+ bw.Write(Encoding.Unicode.GetBytes(entry.FileName + "\0"));
+ }
+ while (bw.BaseStream.Position < darc.Header.FileDataOffset)
+ bw.Write((byte)0);
- // Write Data
- bw.Write(darc.Data);
+ // Write Data
+ bw.Write(darc.Data);
- return ms.ToArray();
- }
- }
- public static DARC getDARC(string folderName)
+ return ms.ToArray();
+ }
+
+ public static DARC GetDARC(string folderName)
+ {
+ // Package Folder into a DARC.
+ List EntryList = [];
+ List NameList = [];
+ byte[] Data = [];
+ uint nameOffset = 6; // 00 00 + 00 2E 00 00
+ #region Build FileTable/NameTables
{
- // Package Folder into a DARC.
- List EntryList = new List();
- List NameList = new List();
- byte[] Data = new byte[0];
- uint nameOffset = 6; // 00 00 + 00 2E 00 00
- #region Build FileTable/NameTables
+ // Null First File
{
- // Null First File
- {
- EntryList.Add(new FileTableEntry {DataOffset = 0, DataLength = 0, IsFolder = true, NameOffset = 0});
- NameList.Add(new NameTableEntry(0, ""));
- }
- // "." Second File
+ EntryList.Add(new FileTableEntry { DataOffset = 0, DataLength = 0, IsFolder = true, NameOffset = 0 });
+ NameList.Add(new NameTableEntry(0, ""));
+ }
+ // "." Second File
+ {
+ EntryList.Add(new FileTableEntry { DataOffset = 0, DataLength = 0, IsFolder = true, NameOffset = 2 });
+ NameList.Add(new NameTableEntry(6, "."));
+ }
+ foreach (string folder in Directory.GetDirectories(folderName))
+ {
+ string parentName = new DirectoryInfo(folder).Name;
+ string[] files = Directory.GetFiles(folder);
+ NameList.Add(new NameTableEntry(nameOffset, parentName));
+ EntryList.Add(new FileTableEntry
{
- EntryList.Add(new FileTableEntry {DataOffset = 0, DataLength = 0, IsFolder = true, NameOffset = 2});
- NameList.Add(new NameTableEntry(6, "."));
- }
- foreach (string folder in Directory.GetDirectories(folderName))
+ DataOffset = 1,
+ DataLength = (uint)(files.Length + EntryList.Count),
+ IsFolder = true,
+ NameOffset = nameOffset,
+ });
+ nameOffset += (uint)parentName.Length + 2; // Account for null terminator
+
+ foreach (string file in files)
{
- string parentName = new DirectoryInfo(folder).Name;
- string[] files = Directory.GetFiles(folder);
+ var fi = new FileInfo(file);
+ string fileName = fi.Name;
NameList.Add(new NameTableEntry(nameOffset, parentName));
+
EntryList.Add(new FileTableEntry
{
- DataOffset = 1,
- DataLength = (uint) (files.Length + EntryList.Count),
- IsFolder = true,
- NameOffset = nameOffset
+ DataOffset = (uint)Data.Length,
+ DataLength = (uint)fi.Length,
+ IsFolder = false,
+ NameOffset = nameOffset,
});
- nameOffset += (uint) parentName.Length + 2; // Account for null terminator
-
- foreach (string file in files)
- {
- FileInfo fi = new FileInfo(file);
- string fileName = fi.Name;
- NameList.Add(new NameTableEntry(nameOffset, parentName));
-
-
- EntryList.Add(new FileTableEntry
- {
- DataOffset = (uint) Data.Length,
- DataLength = (uint) fi.Length,
- IsFolder = false,
- NameOffset = nameOffset
- });
- Data = Data.Concat(File.ReadAllBytes(file)).ToArray();
- nameOffset += (uint) fileName.Length + 2; // Account for null terminator
- }
+ Data = [.. Data, .. File.ReadAllBytes(file)];
+ nameOffset += (uint)fileName.Length + 2; // Account for null terminator
}
}
- #endregion
-
- // Compute Necessary DARC information
- int darcFileCount = NameList.Count;
- int NameListOffset = darcFileCount * 0xC;
- int NameListLength = (int)(nameOffset + NameListOffset);
- int DataOffset = NameListLength % 4 == 0 ? NameListLength : NameListLength + (4 - NameListLength % 4);
- Array.Resize(ref Data, Data.Length % 4 == 0 ? Data.Length : Data.Length + 4 - Data.Length % 4);
- int FinalSize = DataOffset + Data.Length;
-
- // Create New DARC
- DARC darc = new DARC
- {
- Header =
- {
- Signature = "darc",
- Endianness = 0xFEFF,
- HeaderSize = 0x1C,
- Version = 1,
- FileSize = (uint)FinalSize,
- FileTableOffset = 0x1C,
- FileTableLength = (uint)NameListLength,
- FileDataOffset = (uint)DataOffset,
- },
- Entries = EntryList.ToArray(),
- FileNameTable = NameList.ToArray(),
- Data = Data,
- };
- // Fix the First two folders to specify the number of files
- darc.Entries[0].DataLength = (uint)darcFileCount;
- darc.Entries[1].DataLength = (uint)darcFileCount;
-
- // Fix the Data Offset of the files to point to actual destination
- foreach (FileTableEntry f in darc.Entries.Where(x => !x.IsFolder))
- f.DataOffset += darc.Header.FileDataOffset;
- return darc;
}
+ #endregion
- public static bool darc2files(string path, string folderName)
+ // Compute Necessary DARC information
+ int darcFileCount = NameList.Count;
+ int NameListOffset = darcFileCount * 0xC;
+ int NameListLength = (int)(nameOffset + NameListOffset);
+ int DataOffset = NameListLength % 4 == 0 ? NameListLength : NameListLength + (4 - (NameListLength % 4));
+ Array.Resize(ref Data, Data.Length % 4 == 0 ? Data.Length : Data.Length + 4 - (Data.Length % 4));
+ int FinalSize = DataOffset + Data.Length;
+
+ // Create New DARC
+ var darc = new DARC
{
- try { return darc2files(File.ReadAllBytes(path), folderName); }
- catch (Exception) { return false; }
- }
- public static bool darc2files(byte[] darc, string folderName)
+ Header =
+ {
+ Signature = "darc",
+ Endianness = 0xFEFF,
+ HeaderSize = 0x1C,
+ Version = 1,
+ FileSize = (uint)FinalSize,
+ FileTableOffset = 0x1C,
+ FileTableLength = (uint)NameListLength,
+ FileDataOffset = (uint)DataOffset,
+ },
+ Entries = [.. EntryList],
+ FileNameTable = [.. NameList],
+ Data = Data,
+ };
+ // Fix the First two folders to specify the number of files
+ darc.Entries[0].DataLength = (uint)darcFileCount;
+ darc.Entries[1].DataLength = (uint)darcFileCount;
+
+ // Fix the Data Offset of the files to point to actual destination
+ foreach (FileTableEntry f in darc.Entries.Where(x => !x.IsFolder))
+ f.DataOffset += darc.Header.FileDataOffset;
+ return darc;
+ }
+
+ public static bool Darc2files(string path, string folderName)
+ {
+ try { return Darc2files(File.ReadAllBytes(path), folderName); }
+ catch (Exception) { return false; }
+ }
+
+ public static bool Darc2files(byte[] darc, string folderName)
+ {
+ // Save all contents of a DARC to a folder, assuming there's only 1 layer of folders.
+ try
{
- // Save all contents of a DARC to a folder, assuming there's only 1 layer of folders.
- try
+ // Clear existing contents
+ string root = folderName;
+ if (Directory.Exists(root))
+ Directory.Delete(root, true);
+
+ // Create new DARC object from input data
+ var DARC = new DARC(darc);
+
+ // Output data
+ for (int i = 2; i < DARC.FileNameTable.Length;)
{
- // Clear existing contents
- string root = folderName;
- if (Directory.Exists(root))
- Directory.Delete(root, true);
+ bool isFolder = DARC.Entries[i].IsFolder;
+ if (!isFolder)
+ return false;
+ // uint level = DARC.Entries[i].DataOffset; Only assuming 1 layer of folders.
+ string parentName = DARC.FileNameTable[i].FileName;
+ Directory.CreateDirectory(Path.Combine(root, parentName));
- // Create new DARC object from input data
- DARC DARC = new DARC(darc);
+ int nextFolder = (int)DARC.Entries[i++].DataLength;
- // Output data
- for (int i = 2; i < DARC.FileNameTable.Length;)
+ // Extract all Contents of said folder
+ while (i < nextFolder)
{
- bool isFolder = DARC.Entries[i].IsFolder;
- if (!isFolder)
- return false;
- // uint level = DARC.Entries[i].DataOffset; Only assuming 1 layer of folders.
- string parentName = DARC.FileNameTable[i].FileName;
- Directory.CreateDirectory(Path.Combine(root, parentName));
-
- int nextFolder = (int)DARC.Entries[i++].DataLength;
+ string fileName = DARC.FileNameTable[i].FileName;
+ int offset = (int)DARC.Entries[i].DataOffset;
+ int length = (int)DARC.Entries[i].DataLength;
+ byte[] data = DARC.Data.Skip((int)(offset - DARC.Header.FileDataOffset)).Take(length).ToArray();
- // Extract all Contents of said folder
- while (i < nextFolder)
- {
- string fileName = DARC.FileNameTable[i].FileName;
- int offset = (int)DARC.Entries[i].DataOffset;
- int length = (int)DARC.Entries[i].DataLength;
- byte[] data = DARC.Data.Skip((int)(offset - DARC.Header.FileDataOffset)).Take(length).ToArray();
-
- string outPath = Path.Combine(root, parentName, fileName);
- File.WriteAllBytes(outPath, data);
- i++; // Advance to next Entry
- }
+ string outPath = Path.Combine(root, parentName, fileName);
+ File.WriteAllBytes(outPath, data);
+ i++; // Advance to next Entry
}
- return true;
}
- catch (Exception) { return false; }
+ return true;
}
- public static bool files2darc(string folderName, bool delete = false, string originalDARC = null, string outFile = null)
+ catch (Exception) { return false; }
+ }
+
+ public static bool Files2darc(string folderName, bool delete = false, string originalDARC = null, string outFile = null)
+ {
+ // Save all contents of a folder to a darc.
+ try
{
- // Save all contents of a folder to a darc.
- try
+ byte[] darcData;
+ DARC orig;
+ string root = folderName;
+ if (originalDARC != null)
{
- byte[] darcData;
- DARC orig;
- string root = folderName;
- if (originalDARC != null)
- {
- // Fetch offset of DARC within file.
- byte[] darc = File.ReadAllBytes(originalDARC);
- int darcPos = getDARCposition(darc);
- if (darcPos < 0) return false;
- byte[] origData = darc.Skip(darcPos).ToArray();
-
- orig = new DARC(origData);
- orig = insertFiles(orig, folderName);
- byte[] newDARC = setDARC(orig);
- darcData = darc.Take(darcPos).Concat(newDARC).ToArray();
- }
- else // no existing darc to get
- {
- orig = getDARC(folderName);
- darcData = setDARC(orig);
- }
+ // Fetch offset of DARC within file.
+ byte[] darc = File.ReadAllBytes(originalDARC);
+ int darcPos = GetDARCposition(darc);
+ if (darcPos < 0) return false;
+ byte[] origData = darc.Skip(darcPos).ToArray();
- // Fetch final name if not specified
- outFile = outFile ?? originalDARC ?? new DirectoryInfo(folderName).Name.Replace("_d", "") + ".darc";
+ orig = new DARC(origData);
+ orig = InsertFiles(orig, folderName);
+ byte[] newDARC = SetDARC(orig);
+ darcData = darc.Take(darcPos).Concat(newDARC).ToArray();
+ }
+ else // no existing darc to get
+ {
+ orig = GetDARC(folderName);
+ darcData = SetDARC(orig);
+ }
- if (darcData == null) return false;
- File.WriteAllBytes(outFile, darcData);
+ // Fetch final name if not specified
+ outFile ??= originalDARC ?? new DirectoryInfo(folderName).Name.Replace("_d", "") + ".darc";
- if (Directory.Exists(root) && delete)
- Directory.Delete(root, true);
- return true;
- } catch (Exception) { return false; }
- }
+ if (darcData == null) return false;
+ File.WriteAllBytes(outFile, darcData);
- // DARC Utility
- public static int getDARCposition(byte[] data)
- {
- int pos = 0;
- while (BitConverter.ToUInt32(data, pos) != 0x63726164)
- { pos += 4; if (pos >= data.Length) return -1; }
- return pos;
- }
- public static bool insertFile(ref DARC orig, int index, string path)
- {
- try { return insertFile(ref orig, index, File.ReadAllBytes(path)); }
- catch (Exception) { return false; }
+ if (Directory.Exists(root) && delete)
+ Directory.Delete(root, true);
+ return true;
}
- public static bool insertFile(ref DARC orig, int index, byte[] data)
+ catch (Exception) { return false; }
+ }
+
+ // DARC Utility
+ public static int GetDARCposition(byte[] data)
+ {
+ int pos = 0;
+ while (BitConverter.ToUInt32(data, pos) != 0x63726164)
+ { pos += 4; if (pos >= data.Length) return -1; }
+ return pos;
+ }
+
+ public static bool InsertFile(ref DARC orig, int index, string path)
+ {
+ try { return InsertFile(ref orig, index, File.ReadAllBytes(path)); }
+ catch (Exception) { return false; }
+ }
+
+ public static bool InsertFile(ref DARC orig, int index, byte[] data)
+ {
+ if (index < 0) return false;
+
+ try
{
- if (index < 0) return false;
+ uint oldLength = orig.Entries[index].DataLength;
+ uint offset = orig.Entries[index].DataOffset - orig.Header.FileDataOffset;
+ int diff = (int)(data.Length - oldLength);
- try
- {
- uint oldLength = orig.Entries[index].DataLength;
- uint offset = orig.Entries[index].DataOffset - orig.Header.FileDataOffset;
- int diff = (int) (data.Length - oldLength);
-
- // Insert into Data Block
- byte[] pre = orig.Data.Take((int) offset).ToArray();
- byte[] post = orig.Data.Skip((int) (offset + oldLength)).ToArray();
-
- // Reassemble data
- orig.Data = pre.Concat(data).Concat(post).ToArray();
-
- // Fix Offset references of other files
- foreach (var x in orig.Entries.Where(x => x.DataOffset >= offset + oldLength))
- x.DataOffset += (uint) diff;
- orig.Entries[index].DataLength = (uint)data.Length;
- orig.Header.FileSize += (uint)diff;
- return true;
- }
- catch (Exception) { return false; }
+ // Insert into Data Block
+ byte[] pre = orig.Data.Take((int)offset).ToArray();
+ byte[] post = orig.Data.Skip((int)(offset + oldLength)).ToArray();
+
+ // Reassemble data
+ orig.Data = [.. pre, .. data, .. post];
+
+ // Fix Offset references of other files
+ foreach (var x in orig.Entries.Where(x => x.DataOffset >= offset + oldLength))
+ x.DataOffset += (uint)diff;
+ orig.Entries[index].DataLength = (uint)data.Length;
+ orig.Header.FileSize += (uint)diff;
+ return true;
}
- public static DARC insertFiles(DARC orig, string folderName)
- {
- string[] fileNames = new string[orig.Entries.Length];
- for (int i = 0; i < fileNames.Length; i++)
- fileNames[i] = orig.FileNameTable[i].FileName;
+ catch (Exception) { return false; }
+ }
- string[] files = Directory.GetFiles(folderName, "*", SearchOption.AllDirectories);
- foreach (string file in files)
- {
- FileInfo fi = new FileInfo(file);
- string FileName = fi.Name;
+ public static DARC InsertFiles(DARC orig, string folderName)
+ {
+ string[] fileNames = new string[orig.Entries.Length];
+ for (int i = 0; i < fileNames.Length; i++)
+ fileNames[i] = orig.FileNameTable[i].FileName;
- // Get Index of file
- int index = Array.IndexOf(fileNames, FileName);
- if (orig.Entries[index].IsFolder)
- throw new Exception(file + " is not a valid file to reinsert!");
+ string[] files = Directory.GetFiles(folderName, "*", SearchOption.AllDirectories);
+ foreach (string file in files)
+ {
+ var fi = new FileInfo(file);
+ string FileName = fi.Name;
- insertFile(ref orig, index, file);
- }
- // Fix Data layout
- Array.Resize(ref orig.Data, orig.Data.Length % 4 == 0 ? orig.Data.Length : orig.Data.Length + 4 - orig.Data.Length % 4);
- orig.Header.FileSize = (uint)(orig.Data.Length + orig.Header.FileDataOffset);
- return orig;
+ // Get Index of file
+ int index = Array.IndexOf(fileNames, FileName);
+ if (orig.Entries[index].IsFolder)
+ throw new Exception(file + " is not a valid file to reinsert!");
+
+ InsertFile(ref orig, index, file);
}
+ // Fix Data layout
+ Array.Resize(ref orig.Data, orig.Data.Length % 4 == 0 ? orig.Data.Length : orig.Data.Length + 4 - (orig.Data.Length % 4));
+ orig.Header.FileSize = (uint)(orig.Data.Length + orig.Header.FileDataOffset);
+ return orig;
}
-}
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/ETC1.cs b/pk3DS.Core/CTR/ETC1.cs
index 2a940de73d..97d3d7b125 100644
--- a/pk3DS.Core/CTR/ETC1.cs
+++ b/pk3DS.Core/CTR/ETC1.cs
@@ -1,11 +1,22 @@
using System;
+using System.IO;
+using System.Reflection;
using System.Runtime.InteropServices;
+using pk3DS.Core.Properties;
-namespace pk3DS.Core.CTR
+namespace pk3DS.Core.CTR;
+
+internal static partial class ETC1
{
- internal static class ETC1
+ [LibraryImport("ETC1Lib.dll", EntryPoint = "ConvertETC1")]
+ [UnmanagedCallConv(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])]
+ public static partial void ConvertETC1(IntPtr dataOut, ref uint dataOutSize, IntPtr dataIn, ushort width, ushort height, [MarshalAs(UnmanagedType.Bool)] bool alpha);
+
+ public static void CheckETC1Lib()
{
- [DllImport("ETC1Lib.dll", EntryPoint = "ConvertETC1", CallingConvention = CallingConvention.Cdecl)]
- public static extern void ConvertETC1(IntPtr dataOut, ref uint dataOutSize, IntPtr dataIn, ushort width, ushort height, bool alpha);
+ var loc = Assembly.GetEntryAssembly()?.Location ?? typeof(ETC1).Assembly.Location;
+ string dllpath = Path.GetDirectoryName(loc) + "\\ETC1Lib.dll";
+ if (!File.Exists(dllpath))
+ File.WriteAllBytes(dllpath, Resources.ETC1Lib);
}
}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/ExeFS.cs b/pk3DS.Core/CTR/ExeFS.cs
index a9ea1e2307..3d14821a4a 100644
--- a/pk3DS.Core/CTR/ExeFS.cs
+++ b/pk3DS.Core/CTR/ExeFS.cs
@@ -4,111 +4,67 @@
using System.Text;
using System.Security.Cryptography;
-namespace pk3DS.Core.CTR
+namespace pk3DS.Core.CTR;
+
+public class ExeFS
{
- public class ExeFS
- {
- public byte[] Data;
- public byte[] SuperBlockHash;
+ public byte[] Data;
+ public readonly byte[] SuperBlockHash;
- // Return an object with data stored in a byte array
- public ExeFS(string EXEFS_PATH)
+ // Return an object with data stored in a byte array
+ public ExeFS(string path)
+ {
+ if (Directory.Exists(path))
{
- if (Directory.Exists(EXEFS_PATH))
- {
- var files = new DirectoryInfo(EXEFS_PATH).GetFiles().Select(f => f.FullName).ToArray();
- setData(files);
- }
- else
- {
- Data = File.ReadAllBytes(EXEFS_PATH);
- }
- getSuperBlockHash();
+ var files = new DirectoryInfo(path).GetFiles().Select(f => f.FullName).ToArray();
+ SetData(files);
}
-
- public void getSuperBlockHash()
+ else if (File.Exists(path))
{
- using (SHA256Managed sha = new SHA256Managed())
- SuperBlockHash = sha.ComputeHash(Data, 0, 0x200);
+ Data = File.ReadAllBytes(path);
}
-
- // Overall R/W files (wrapped)
- public static bool get(string inFile, string outPath)
+ else
{
- try
- {
- byte[] data = File.ReadAllBytes(inFile);
- if (!Directory.Exists(outPath)) Directory.CreateDirectory(outPath);
- for (int i = 0; i < 10; i++)
- {
- // Get File Name String; if exists we have a file to extract.
- string fileName = Encoding.ASCII.GetString(data.Skip(0x10 * i).Take(0x8).ToArray()).TrimEnd((char)0);
- if (fileName.Length > 0)
- File.WriteAllBytes(
- // New File Path
- outPath + Path.DirectorySeparatorChar + fileName + ".bin",
- // Get New Data from Offset after 0x200 Header.
- data.Skip(0x200 + BitConverter.ToInt32(data, 0x8 + 0x10 * i)).Take(BitConverter.ToInt32(data, 0xC + 0x10 * i)).ToArray()
- );
- }
- return true;
- }
- catch { return false; }
+ throw new FileNotFoundException("File not found.", path);
}
- public static bool set(string[] files, string outFile)
- {
- if (files.Length > 10) { Console.WriteLine("Cannot package more than 10 files to exefs."); return false; }
+ SuperBlockHash = SHA256.HashData(Data.AsSpan(0, 200));
+ }
- try
+ // Overall R/W files (wrapped)
+ public static bool UnpackExeFS(string inFile, string outPath)
+ {
+ try
+ {
+ byte[] data = File.ReadAllBytes(inFile);
+ if (!Directory.Exists(outPath)) Directory.CreateDirectory(outPath);
+ for (int i = 0; i < 10; i++)
{
- // Set up the Header
- byte[] headerData = new byte[0x200];
- uint offset = 0;
- SHA256 sha = SHA256.Create();
-
- // Get the Header
- for (int i = 0; i < files.Length; i++)
- {
- // Do the Top (File Info)
- string fileName = Path.GetFileNameWithoutExtension(files[i]);
- byte[] nameData = Encoding.ASCII.GetBytes(fileName); Array.Resize(ref nameData, 0x8);
- Array.Copy(nameData, 0, headerData, i * 0x10, 0x8);
-
- FileInfo fi = new FileInfo(files[i]);
- uint size = (uint)fi.Length;
- Array.Copy(BitConverter.GetBytes(offset), 0, headerData, 0x8 + i * 0x10, 0x4);
- Array.Copy(BitConverter.GetBytes(size), 0, headerData, 0xC + i * 0x10, 0x4);
- offset += 0x200 - size % 0x200 + size;
-
- // Do the Bottom (Hashes)
- byte[] hash = sha.ComputeHash(File.ReadAllBytes(files[i]));
- Array.Copy(hash, 0, headerData, 0x200 - 0x20 * (i + 1), 0x20);
- }
-
- // Set in the Data
- using (MemoryStream newFile = new MemoryStream())
+ // Get File Name String; if exists we have a file to extract.
+ string fileName = Encoding.ASCII.GetString(data.Skip(0x10 * i).Take(0x8).ToArray()).TrimEnd((char)0);
+ if (fileName.Length > 0)
{
- new MemoryStream(headerData).CopyTo(newFile);
- foreach (string s in files)
- {
- using (MemoryStream loadFile = new MemoryStream(File.ReadAllBytes(s)))
- loadFile.CopyTo(newFile);
- new MemoryStream(new byte[0x200 - newFile.Length % 0x200]).CopyTo(newFile);
- }
-
- File.WriteAllBytes(outFile, newFile.ToArray());
+ File.WriteAllBytes(
+ // New File Path
+ outPath + Path.DirectorySeparatorChar + fileName + ".bin",
+ // Get New Data from Offset after 0x200 Header.
+ data.Skip(0x200 + BitConverter.ToInt32(data, 0x8 + (0x10 * i))).Take(BitConverter.ToInt32(data, 0xC + (0x10 * i))).ToArray()
+ );
}
- return true;
}
- catch { return false; }
+ return true;
}
+ catch { return false; }
+ }
+
+ public static bool PackExeFS(string[] files, string outFile)
+ {
+ if (files.Length > 10) { Console.WriteLine("Cannot package more than 10 files to exefs."); return false; }
- public void setData(string[] files)
+ try
{
// Set up the Header
byte[] headerData = new byte[0x200];
uint offset = 0;
- SHA256 sha = SHA256.Create();
// Get the Header
for (int i = 0; i < files.Length; i++)
@@ -118,30 +74,70 @@ public void setData(string[] files)
byte[] nameData = Encoding.ASCII.GetBytes(fileName); Array.Resize(ref nameData, 0x8);
Array.Copy(nameData, 0, headerData, i * 0x10, 0x8);
- FileInfo fi = new FileInfo(files[i]);
+ var fi = new FileInfo(files[i]);
uint size = (uint)fi.Length;
- Array.Copy(BitConverter.GetBytes(offset), 0, headerData, 0x8 + i * 0x10, 0x4);
- Array.Copy(BitConverter.GetBytes(size), 0, headerData, 0xC + i * 0x10, 0x4);
- offset += 0x200 - size % 0x200 + size;
+ Array.Copy(BitConverter.GetBytes(offset), 0, headerData, 0x8 + (i * 0x10), 0x4);
+ Array.Copy(BitConverter.GetBytes(size), 0, headerData, 0xC + (i * 0x10), 0x4);
+ offset += 0x200 - (size % 0x200) + size;
// Do the Bottom (Hashes)
- byte[] hash = sha.ComputeHash(File.ReadAllBytes(files[i]));
- Array.Copy(hash, 0, headerData, 0x200 - 0x20 * (i + 1), 0x20);
+ byte[] hash = SHA256.HashData(File.ReadAllBytes(files[i]));
+ Array.Copy(hash, 0, headerData, 0x200 - (0x20 * (i + 1)), 0x20);
}
// Set in the Data
- using (MemoryStream newFile = new MemoryStream())
+ using var newFile = new MemoryStream();
+ newFile.Write(headerData);
+ foreach (string s in files)
{
- new MemoryStream(headerData).CopyTo(newFile);
- foreach (string s in files)
- {
- using (MemoryStream loadFile = new MemoryStream(File.ReadAllBytes(s)))
- loadFile.CopyTo(newFile);
- new MemoryStream(new byte[0x200 - newFile.Length % 0x200]).CopyTo(newFile);
- }
-
- Data = newFile.ToArray();
+ using (var loadFile = new MemoryStream(File.ReadAllBytes(s)))
+ loadFile.CopyTo(newFile);
+ var tail = new byte[0x200 - (newFile.Length % 0x200)];
+ newFile.Write(tail);
}
+
+ File.WriteAllBytes(outFile, newFile.ToArray());
+ return true;
}
+ catch { return false; }
+ }
+
+ public void SetData(string[] files)
+ {
+ // Set up the Header
+ byte[] headerData = new byte[0x200];
+ uint offset = 0;
+
+ // Get the Header
+ for (int i = 0; i < files.Length; i++)
+ {
+ // Do the Top (File Info)
+ string fileName = Path.GetFileNameWithoutExtension(files[i]);
+ byte[] nameData = Encoding.ASCII.GetBytes(fileName); Array.Resize(ref nameData, 0x8);
+ Array.Copy(nameData, 0, headerData, i * 0x10, 0x8);
+
+ var fi = new FileInfo(files[i]);
+ uint size = (uint)fi.Length;
+ Array.Copy(BitConverter.GetBytes(offset), 0, headerData, 0x8 + (i * 0x10), 0x4);
+ Array.Copy(BitConverter.GetBytes(size), 0, headerData, 0xC + (i * 0x10), 0x4);
+ offset += 0x200 - (size % 0x200) + size;
+
+ // Do the Bottom (Hashes)
+ byte[] hash = SHA256.HashData(File.ReadAllBytes(files[i]));
+ Array.Copy(hash, 0, headerData, 0x200 - (0x20 * (i + 1)), 0x20);
+ }
+
+ // Set in the Data
+ using var newFile = new MemoryStream();
+ newFile.Write(headerData);
+ foreach (string s in files)
+ {
+ using var loadFile = File.OpenRead(s);
+ loadFile.CopyTo(newFile);
+ var tail = new byte[0x200 - (newFile.Length % 0x200)];
+ newFile.Write(tail);
+ }
+
+ Data = newFile.ToArray();
}
-}
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/Exheader.cs b/pk3DS.Core/CTR/Exheader.cs
index f91ebb96c5..9613e64079 100644
--- a/pk3DS.Core/CTR/Exheader.cs
+++ b/pk3DS.Core/CTR/Exheader.cs
@@ -5,90 +5,95 @@
using System.Security.Cryptography;
using pk3DS.Core.Properties;
-namespace pk3DS.Core.CTR
+namespace pk3DS.Core.CTR;
+
+public class Exheader
{
- public class Exheader
+ public readonly byte[] Data;
+ public readonly byte[] AccessDescriptor;
+ public readonly ulong TitleID;
+
+ public Exheader(string EXHEADER_PATH)
{
- public readonly byte[] Data;
- public readonly byte[] AccessDescriptor;
- public readonly ulong TitleID;
+ Data = File.ReadAllBytes(EXHEADER_PATH);
+ AccessDescriptor = Data.Skip(0x400).Take(0x400).ToArray();
+ Data = Data.Take(0x400).ToArray();
+ TitleID = BitConverter.ToUInt64(Data, 0x200);
+ }
- public Exheader(string EXHEADER_PATH)
- {
- Data = File.ReadAllBytes(EXHEADER_PATH);
- AccessDescriptor = Data.Skip(0x400).Take(0x400).ToArray();
- Data = Data.Take(0x400).ToArray();
- TitleID = BitConverter.ToUInt64(Data, 0x200);
- }
+ public byte[] GetSuperBlockHash()
+ {
+ return SHA256.HashData(Data.AsSpan(0, 0x400));
+ }
- public byte[] GetSuperBlockHash()
- {
- SHA256Managed sha = new SHA256Managed();
- return sha.ComputeHash(Data, 0, 0x400);
- }
- public string GetSerial()
- {
- const string output = "CTR-P-";
+ public string GetSerial()
+ {
+ const string output = "CTR-P-";
- var RecognizedGames = new Dictionary();
- string[] lines = Resources.ResourceManager.GetString("_3dsgames").Split('\n').ToArray();
- foreach (string l in lines)
+ var RecognizedGames = new Dictionary();
+ var lines = Resources.ResourceManager.GetString("_3dsgames").Split('\n').ToArray();
+ foreach (string l in lines)
+ {
+ string[] vars = l.Split('\t');
+ ulong titleid = Convert.ToUInt64(vars[0], 16);
+ if (RecognizedGames.TryGetValue(titleid, out var value))
{
- string[] vars = l.Split('\t').ToArray();
- ulong titleid = Convert.ToUInt64(vars[0], 16);
- if (RecognizedGames.ContainsKey(titleid))
- {
- char lc = RecognizedGames[titleid].ToArray()[0].ToCharArray()[3];
- char lc2 = vars[1].ToCharArray()[3];
- if (lc2 == 'A' || lc2 == 'E' || lc2 == 'P' && lc == 'J') //Prefer games in order US, PAL, JP
- {
- RecognizedGames[titleid] = vars.Skip(1).Take(2).ToArray();
- }
- }
- else
+ char lc = value.ToArray()[0][3];
+ char lc2 = vars[1][3];
+ if (lc2 == 'A' || lc2 == 'E' || (lc2 == 'P' && lc == 'J')) //Prefer games in order US, PAL, JP
{
- RecognizedGames.Add(titleid, vars.Skip(1).Take(2).ToArray());
+ RecognizedGames[titleid] = vars.Skip(1).Take(2).ToArray();
}
}
- return output + RecognizedGames[TitleID][0];
- }
-
- public bool isPokemon()
- {
- return isORAS() || isXY();
- }
- public bool isORAS()
- {
- return (TitleID & 0xFFFFFFFF) >> 8 == 0x11C5 || (TitleID & 0xFFFFFFFF) >> 8 == 0x11C4;
- }
- public bool isXY()
- {
- return (TitleID & 0xFFFFFFFF) >> 8 == 0x55D || (TitleID & 0xFFFFFFFF) >> 8 == 0x55E;
- }
- public string GetPokemonSerial()
- {
- if (!isPokemon())
- return "CTR-P-XXXX";
- string name;
- switch ((TitleID & 0xFFFFFFFF) >> 8)
+ else
{
- case 0x11C5: //Alpha Sapphire
- name = "ECLA";
- break;
- case 0x11C4: //Omega Ruby
- name = "ECRA";
- break;
- case 0x55D: //X
- name = "EKJA";
- break;
- case 0x55E: //Y
- name = "EK2A";
- break;
- default:
- name = "XXXX";
- break;
+ RecognizedGames.Add(titleid, vars.Skip(1).Take(2).ToArray());
}
- return "CTR-P-" + name;
}
+ return output + RecognizedGames[TitleID][0];
+ }
+
+ public bool IsSupported()
+ {
+ return IsORAS() || IsXY() || IsUSUM() || IsSM();
+ }
+
+ public bool IsUSUM()
+ {
+ return (TitleID & 0xFFFFFFFF) >> 8 == 0x1B50 || (TitleID & 0xFFFFFFFF) >> 8 == 0x1B51;
+ }
+
+ public bool IsSM()
+ {
+ return (TitleID & 0xFFFFFFFF) >> 8 == 0x1648 || (TitleID & 0xFFFFFFFF) >> 8 == 0x175E;
+ }
+
+ public bool IsORAS()
+ {
+ return (TitleID & 0xFFFFFFFF) >> 8 == 0x11C5 || (TitleID & 0xFFFFFFFF) >> 8 == 0x11C4;
+ }
+
+ public bool IsXY()
+ {
+ return (TitleID & 0xFFFFFFFF) >> 8 == 0x55D || (TitleID & 0xFFFFFFFF) >> 8 == 0x55E;
+ }
+
+ public string GetPokemonSerial()
+ {
+ if (!IsSupported())
+ return "CTR-P-XXXX";
+ string name = ((TitleID & 0xFFFFFFFF) >> 8) switch
+ {
+ 0x1B51 => "A2BA", // Ultra Moon
+ 0x1B50 => "A2AA", // Ultra Sun
+ 0x175E => "BNEA", // Moon
+ 0x1648 => "BNDA", // Sun
+ 0x11C5 => "ECLA", // Alpha Sapphire
+ 0x11C4 => "ECRA", // Omega Ruby
+ 0x055D => "EKJA", // X
+ 0x055E => "EK2A", // Y
+ _ => "XXXX",
+ };
+ return "CTR-P-" + name;
}
-}
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/FileFormat.cs b/pk3DS.Core/CTR/FileFormat.cs
index 78948aa1c2..5022f3322a 100644
--- a/pk3DS.Core/CTR/FileFormat.cs
+++ b/pk3DS.Core/CTR/FileFormat.cs
@@ -4,182 +4,185 @@
using System.Text;
using System.Text.RegularExpressions;
-namespace pk3DS.Core.CTR
+namespace pk3DS.Core.CTR;
+
+public static partial class FileFormat
{
- public static class FileFormat
+ internal const string defaultExtension = "bin";
+ internal static readonly string[] validEXT = ["BCH"];
+
+ public static string Guess(string path)
{
- internal const string defaultExtension = "bin";
- internal static readonly string[] validEXT = {"BCH",};
+ using var br = new BinaryReader(File.OpenRead(path));
+ return Guess(br);
+ }
- public static string Guess(string path)
- {
- string ext;
- using (BinaryReader br = new BinaryReader(File.OpenRead(path)))
- ext = Guess(br);
- return ext;
- }
- public static string Guess(byte[] data)
+ public static string Guess(byte[] data)
+ {
+ using var br = new BinaryReader(new MemoryStream(data));
+ return Guess(br);
+ }
+
+ public static string Guess(MemoryStream ms, bool start = true)
+ {
+ using var br = new BinaryReader(ms);
+ return Guess(br, start);
+ }
+
+ public static string Guess(BinaryReader br, bool start = true)
+ {
+ long position = br.BaseStream.Position; // Store current position to reset after.
+
+ if (start) // Seek to top of stream if requested
+ br.BaseStream.Position = 0;
+
+ // Guess Extension
+ if (GuessMini(br, out var ext))
+ Console.WriteLine("Mini Packed File detected, extension type " + ext);
+ else if (GuessHeaderedDARC(br, out ext))
+ Console.WriteLine("Headered DARC File detected, extension type " + ext);
+ else if (GuessBCLIM(br, out ext))
+ Console.WriteLine("BCLIM File detected, extension type " + ext);
+ else if (GuessLZ11(br, out ext))
+ Console.WriteLine("LZ11 Compressed File detected, extension type " + ext);
+ else if (Guess4CHAR(br, out ext))
+ Console.WriteLine("4CHAR File detected, extension type " + ext);
+ else if (Guess3CHAR(br, out ext))
+ Console.WriteLine("3CHAR File detected, extension type " + ext);
+ else ext = defaultExtension; // default
+
+ // Return BaseStream position to the start.
+ br.BaseStream.Position = position;
+ return "." + ext;
+ }
+
+ public static bool GuessMini(BinaryReader br, out string ext)
+ {
+ long position = br.BaseStream.Position; // Store current position to reset after.
+ ext = ""; // Reset extension
+ try
{
- string ext;
- using (BinaryReader br = new BinaryReader(new MemoryStream(data)))
- ext = Guess(br);
- return ext;
+ // check for 2char container extensions
+ ushort magic = br.ReadUInt16();
+ ushort count = br.ReadUInt16();
+ br.BaseStream.Position = 4 + (4 * count);
+ if (br.ReadUInt32() == br.BaseStream.Length)
+ {
+ ext += (char)magic & 0xFF;
+ ext += (char)magic << 8;
+ }
}
- public static string Guess(MemoryStream ms, bool start = true)
+ catch { }
+ // Return BaseStream position to the start.
+ br.BaseStream.Position = position;
+
+ return ext.Length > 0;
+ }
+
+ public static bool GuessHeaderedDARC(BinaryReader br, out string ext)
+ {
+ long position = br.BaseStream.Position; // Store current position to reset after.
+ ext = ""; // Reset extension
+ try
{
- string ext;
- using (BinaryReader br = new BinaryReader(ms))
- ext = Guess(br, start);
- return ext;
+ byte[] magic = Encoding.ASCII.GetBytes(br.ReadChars(4));
+ int count = BitConverter.ToUInt16(magic, 0);
+ br.BaseStream.Position = position + 4 + (0x40 * count);
+ uint tableval = br.ReadUInt32();
+ br.BaseStream.Position += 0x20 * tableval;
+ while (br.PeekChar() == 0) // seek forward
+ br.ReadByte();
+ if (br.ReadUInt32() == 0x63726164)
+ ext = "darc";
}
- public static string Guess(BinaryReader br, bool start = true)
- {
- long position = br.BaseStream.Position; // Store current position to reset after.
-
- if (start) // Seek to top of stream if requested
- br.BaseStream.Position = 0;
-
- // Guess Extension
- string ext;
- if (GuessMini(br, out ext))
- Console.WriteLine("Mini Packed File detected, extension type " + ext);
- else if (GuessHeaderedDARC(br, out ext))
- Console.WriteLine("Headered DARC File detected, extension type " + ext);
- else if (GuessBCLIM(br, out ext))
- Console.WriteLine("BCLIM File detected, extension type " + ext);
- else if (GuessLZ11(br, out ext))
- Console.WriteLine("LZ11 Compressed File detected, extension type " + ext);
- else if (Guess4CHAR(br, out ext))
- Console.WriteLine("4CHAR File detected, extension type " + ext);
- else if (Guess3CHAR(br, out ext))
- Console.WriteLine("3CHAR File detected, extension type " + ext);
- else ext = defaultExtension; // default
+ catch { }
+ // Return BaseStream position to the start.
+ br.BaseStream.Position = position;
- // Return BaseStream position to the start.
- br.BaseStream.Position = position;
- return "." + ext;
- }
+ return ext.Length > 0;
+ }
- public static bool GuessMini(BinaryReader br, out string ext)
+ public static bool GuessBCLIM(BinaryReader br, out string ext)
+ {
+ long position = br.BaseStream.Position; // Store current position to reset after.
+ ext = ""; // Reset extension
+ try
{
- long position = br.BaseStream.Position; // Store current position to reset after.
- ext = ""; // Reset extension
- try
+ br.BaseStream.Position = br.BaseStream.Length - 0x28;
+ if (br.ReadUInt32() == 0x4D494C43)
{
- // check for 2char container extensions
- ushort magic = br.ReadUInt16();
- ushort count = br.ReadUInt16();
- br.BaseStream.Position = 4 + 4 * count;
- if (br.ReadUInt32() == br.BaseStream.Length)
- {
- ext += (char)magic & 0xFF;
- ext += (char)magic << 8;
- }
+ br.BaseStream.Position = br.BaseStream.Length - 0x4;
+ if (br.ReadUInt32() == br.BaseStream.Length - 0x28)
+ ext = "bclim";
}
- catch { }
- // Return BaseStream position to the start.
- br.BaseStream.Position = position;
-
- return ext.Length > 0;
}
- public static bool GuessHeaderedDARC(BinaryReader br, out string ext)
+ catch { }
+ // Return BaseStream position to the start.
+ br.BaseStream.Position = position;
+
+ return ext.Length > 0;
+ }
+
+ public static bool GuessLZ11(BinaryReader br, out string ext)
+ {
+ long position = br.BaseStream.Position; // Store current position to reset after.
+ ext = ""; // Reset extension
+ try
{
- long position = br.BaseStream.Position; // Store current position to reset after.
- ext = ""; // Reset extension
- try
- {
- byte[] magic = Encoding.ASCII.GetBytes(br.ReadChars(4));
- int count = BitConverter.ToUInt16(magic, 0);
- br.BaseStream.Position = position + 4 + 0x40 * count;
- uint tableval = br.ReadUInt32();
- br.BaseStream.Position += 0x20 * tableval;
- while (br.PeekChar() == 0) // seek forward
- br.ReadByte();
- if (br.ReadUInt32() == 0x63726164)
- ext = "darc";
- }
- catch { }
- // Return BaseStream position to the start.
- br.BaseStream.Position = position;
+ int type = br.PeekChar();
+ if (type != 0x11)
+ return false;
+ byte[] sizeBytes = new byte[3];
+ br.Read(sizeBytes, 0, 3);
- return ext.Length > 0;
+ int decompressedSize = sizeBytes[0] | sizeBytes[1] << 8 | sizeBytes[2];
+ if (decompressedSize > br.BaseStream.Length && decompressedSize < br.BaseStream.Length * 10) // assuming 10x compression isn't feasible
+ ext = "lz"; // really weak LZ detection, at most 16MB
}
- public static bool GuessBCLIM(BinaryReader br, out string ext)
+ catch { }
+ br.BaseStream.Position = position;
+ return ext.Length > 0;
+ }
+
+ public static bool Guess4CHAR(BinaryReader br, out string ext)
+ {
+ long position = br.BaseStream.Position; // Store current position to reset after.
+ ext = ""; // Reset extension
+ try
{
- long position = br.BaseStream.Position; // Store current position to reset after.
- ext = ""; // Reset extension
- try
- {
- br.BaseStream.Position = br.BaseStream.Length - 0x28;
- if (br.ReadUInt32() == 0x4D494C43)
- {
- br.BaseStream.Position = br.BaseStream.Length - 0x4;
- if (br.ReadUInt32() == br.BaseStream.Length - 0x28)
- ext = "bclim";
- }
- }
- catch { }
+ byte[] magic = Encoding.ASCII.GetBytes(br.ReadChars(4));
+
+ Regex r = PatternAZ09();
+ ext = Encoding.ASCII.GetString(magic);
// Return BaseStream position to the start.
br.BaseStream.Position = position;
- return ext.Length > 0;
+ return r.IsMatch(ext) && ext.Length == 4;
}
- public static bool GuessLZ11(BinaryReader br, out string ext)
- {
- long position = br.BaseStream.Position; // Store current position to reset after.
- ext = ""; // Reset extension
- try
- {
- int type = br.PeekChar();
- if (type != 0x11)
- return false;
- byte[] sizeBytes = new byte[3];
- br.Read(sizeBytes, 0, 3);
-
- int decompressedSize = sizeBytes[0] | sizeBytes[1] << 8 | sizeBytes[2];
- if (decompressedSize > br.BaseStream.Length && decompressedSize < br.BaseStream.Length * 10) // assuming 10x compression isn't feasible
- ext = "lz"; // really weak LZ detection, at most 16MB
- }
- catch { }
- br.BaseStream.Position = position;
- return ext.Length > 0;
- }
- public static bool Guess4CHAR(BinaryReader br, out string ext)
- {
- long position = br.BaseStream.Position; // Store current position to reset after.
- ext = ""; // Reset extension
- try
- {
- byte[] magic = Encoding.ASCII.GetBytes(br.ReadChars(4));
-
- Regex r = new Regex("^[a-zA-Z0-9]*$");
- ext = Encoding.ASCII.GetString(magic);
- // Return BaseStream position to the start.
- br.BaseStream.Position = position;
+ catch { }
+ br.BaseStream.Position = position;
+ return false;
+ }
- return r.IsMatch(ext) && ext.Length == 4;
- }
- catch { }
- br.BaseStream.Position = position;
- return false;
- }
- public static bool Guess3CHAR(BinaryReader br, out string ext)
+ public static bool Guess3CHAR(BinaryReader br, out string ext)
+ {
+ long position = br.BaseStream.Position; // Store current position to reset after.
+ ext = ""; // Reset extension
+ try
{
- long position = br.BaseStream.Position; // Store current position to reset after.
- ext = ""; // Reset extension
- try
- {
- byte[] magic = Encoding.ASCII.GetBytes(br.ReadChars(3));
-
- ext = Encoding.ASCII.GetString(magic);
- // Return BaseStream position to the start.
- br.BaseStream.Position = position;
+ byte[] magic = Encoding.ASCII.GetBytes(br.ReadChars(3));
- return validEXT.Contains(ext);
- }
- catch { }
+ ext = Encoding.ASCII.GetString(magic);
+ // Return BaseStream position to the start.
br.BaseStream.Position = position;
- return false;
+
+ return validEXT.Contains(ext);
}
+ catch { }
+ br.BaseStream.Position = position;
+ return false;
}
-}
+
+ [GeneratedRegex("^[a-zA-Z0-9]*$")]
+ private static partial Regex PatternAZ09();
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/GARC.cs b/pk3DS.Core/CTR/GARC.cs
index 200ecb59d7..5a6c98c23e 100644
--- a/pk3DS.Core/CTR/GARC.cs
+++ b/pk3DS.Core/CTR/GARC.cs
@@ -2,141 +2,176 @@
using System.IO;
using System.Linq;
-namespace pk3DS.Core.CTR
+namespace pk3DS.Core.CTR;
+
+#region GARC Class & Struct
+public static class GARC
{
- #region GARC Class & Struct
- public static class GARC
+ public const ushort VER_6 = 0x0600;
+ public const ushort VER_4 = 0x0400;
+
+ public class FileCountDeterminedEventArgs : EventArgs
{
- public const ushort VER_6 = 0x0600;
- public const ushort VER_4 = 0x0400;
+ public int Total { get; set; }
+ }
- public class FileCountDeterminedEventArgs : EventArgs
- {
- public int Total { get; set; }
- }
+ public class PackProgressedEventArgs : EventArgs
+ {
+ public int Current { get; set; }
+ public int Total { get; set; }
+ public string CurrentFile { get; set; }
+ }
- public class PackProgressedEventArgs : EventArgs
- {
- public int Current { get; set; }
- public int Total { get; set; }
- public string CurrentFile { get; set; }
- }
+ public class UnpackProgressedEventArgs : EventArgs
+ {
+ public int Current { get; set; }
+ public int Total { get; set; }
+ }
- public class UnpackProgressedEventArgs : EventArgs
- {
- public int Current { get; set; }
- public int Total { get; set; }
- }
+ public static event EventHandler FileCountDetermined;
+ public static event EventHandler PackProgressed;
+ public static event EventHandler UnpackProgressed;
+
+ public static int PackGARC(string folderPath, string garcPath, int version, int bytesPadding)
+ {
+ // Check to see if our input folder exists.
+ if (!new DirectoryInfo(folderPath).Exists) throw new DirectoryNotFoundException("Folder does not exist");
+ if (version != VER_4 && version != VER_6)
+ throw new FormatException("Invalid GARC Version: 0x" + version.ToString("X4"));
- public static event EventHandler FileCountDetermined;
- public static event EventHandler PackProgressed;
- public static event EventHandler UnpackProgressed;
+ // Okay some basic proofing is done. Proceed.
+ int filectr = 0;
+ // Get the paths of the files to pack up.
+ string[] files = Directory.GetFiles(folderPath);
+ string[] folders = Directory.GetDirectories(folderPath, "*.*", SearchOption.TopDirectoryOnly);
- public static int garcPackMS(string folderPath, string garcPath, int version, int bytesPadding)
+ string[] packOrder = new string[files.Length + folders.Length];
+ #region Reassemble a list of filenames.
+ try
{
- // Check to see if our input folder exists.
- if (!new DirectoryInfo(folderPath).Exists) throw new DirectoryNotFoundException("Folder does not exist");
+ foreach (string f in files)
+ {
+ string fn = Path.GetFileNameWithoutExtension(f);
+ int compressed = fn.IndexOf("dec_", StringComparison.Ordinal);
+ int fileNumber = compressed < 0
+ ? int.Parse(fn)
+ : int.Parse(fn[(compressed + 4)..]);
+
+ packOrder[fileNumber] = f;
+ filectr++;
+ }
+ foreach (string f in folders)
+ {
+ packOrder[int.Parse(new DirectoryInfo(f).Name)] = f;
+ filectr += Directory.GetFiles(f).Length;
+ }
+ }
+ catch (Exception e) { throw new Exception("Invalid packing filenames", e); }
- if (version != VER_4 && version != VER_6)
- throw new FormatException("Invalid GARC Version: 0x" + version.ToString("X4"));
+ FileCountDetermined?.Invoke(null, new FileCountDeterminedEventArgs { Total = filectr });
+ #endregion
- // Okay some basic proofing is done. Proceed.
- int filectr = 0;
- // Get the paths of the files to pack up.
- string[] files = Directory.GetFiles(folderPath);
- string[] folders = Directory.GetDirectories(folderPath, "*.*", SearchOption.TopDirectoryOnly);
+ // Set Up the GARC template.
+ var garc = new GARCFile
+ {
+ ContentPadToNearest = 4,
+ fato =
+ {
+ // Magic = new[] { 'O', 'T', 'A', 'F' },
+ Entries = new FATO_Entry[packOrder.Length],
+ EntryCount = (ushort) packOrder.Length,
+ HeaderSize = 0xC + (packOrder.Length*4),
+ Padding = 0xFFFF,
+ },
+ fatb =
+ {
+ // Magic = new[] { 'B', 'T', 'A', 'F' },
+ Entries = new FATB_Entry[packOrder.Length],
+ FileCount = filectr,
+ },
+ };
+ if (version == VER_6)
+ {
+ // Some files have larger bytes-to-pad values (ex/ 0x80 for a109)
+ // Hopefully there's no problems defining this with a constant number.
+ garc.ContentPadToNearest = 4;
+ }
- string[] packOrder = new string[files.Length + folders.Length];
- #region Reassemble a list of filenames.
- try
+ #region Start Reassembling the FAT* tables.
+ {
+ int op = 0;
+ int od = 0;
+ int v = 0;
+ int index = 0;
+ for (int i = 0; i < garc.fatb.Entries.Length; i++)
{
- foreach (string f in files)
+ garc.fato.Entries[i].Offset = op; // FATO offset
+ garc.fatb.Entries[i].SubEntries = new FATB_SubEntry[32];
+ op += 4; // Vector
+ if (!Directory.Exists(packOrder[i])) // is not folder
{
- string fn = Path.GetFileNameWithoutExtension(f);
+ garc.fatb.Entries[i].IsFolder = false;
+ garc.fatb.Entries[i].SubEntries[0].Exists = true;
+
+ string fn = Path.GetFileNameWithoutExtension(packOrder[i]);
int compressed = fn.IndexOf("dec_", StringComparison.Ordinal);
int fileNumber = compressed < 0
? int.Parse(fn)
- : int.Parse(fn.Substring(compressed + 4));
+ : int.Parse(fn[(compressed + 4)..]);
- packOrder[fileNumber] = f;
- filectr++;
- }
- foreach (string f in folders)
- {
- packOrder[int.Parse(new DirectoryInfo(f).Name)] = f;
- filectr += Directory.GetFiles(f).Length;
- }
- }
- catch (Exception e) { throw new Exception("Invalid packing filenames", e); }
+ if (compressed >= 0)
+ {
+ string old = packOrder[i];
+ LZSS.Compress(packOrder[i], packOrder[i] = Path.Combine(Path.GetDirectoryName(packOrder[i]), fileNumber.ToString()));
+ File.Delete(old);
+ }
- FileCountDetermined?.Invoke(null, new FileCountDeterminedEventArgs { Total = filectr });
- #endregion
+ // Assemble Vector
+ v = 1;
- // Set Up the GARC template.
- GARCFile garc = new GARCFile
- {
- ContentPadToNearest = 4,
- fato =
- {
- // Magic = new[] { 'O', 'T', 'A', 'F' },
- Entries = new FATO_Entry[packOrder.Length],
- EntryCount = (ushort) packOrder.Length,
- HeaderSize = 0xC + packOrder.Length*4,
- Padding = 0xFFFF
- },
- fatb =
- {
- // Magic = new[] { 'B', 'T', 'A', 'F' },
- Entries = new FATB_Entry[packOrder.Length],
- FileCount = filectr
- }
- };
- if (version == VER_6)
- {
- // Some files have larger bytes-to-pad values (ex/ 0x80 for a109)
- // Hopefully there's no problems defining this with a constant number.
- garc.ContentPadToNearest = 4;
- }
+ // Assemble Entry
+ var fi = new FileInfo(packOrder[i]);
+ int actualLength = (int)(fi.Length % 4 == 0 ? fi.Length : fi.Length + 4 - (fi.Length % 4));
+ garc.fatb.Entries[i].SubEntries[0].Start = od;
+ garc.fatb.Entries[i].SubEntries[0].End = actualLength + garc.fatb.Entries[i].SubEntries[0].Start;
+ garc.fatb.Entries[i].SubEntries[0].Length = (int)fi.Length;
+ od += actualLength;
- #region Start Reassembling the FAT* tables.
- {
- int op = 0;
- int od = 0;
- int v = 0;
- int index = 0;
- for (int i = 0; i < garc.fatb.Entries.Length; i++)
+ op += 12;
+
+ // Step
+ PackProgressed?.Invoke(null, new PackProgressedEventArgs { Current = index++, Total = filectr, CurrentFile = packOrder[i] });
+ }
+ else
{
- garc.fato.Entries[i].Offset = op; // FATO offset
- garc.fatb.Entries[i].SubEntries = new FATB_SubEntry[32];
- op += 4; // Vector
- if (!Directory.Exists(packOrder[i])) // is not folder
+ garc.fatb.Entries[i].IsFolder = true;
+ string[] subFiles = Directory.GetFiles(packOrder[i]);
+ foreach (string f in subFiles)
{
- garc.fatb.Entries[i].IsFolder = false;
- garc.fatb.Entries[i].SubEntries[0].Exists = true;
-
- string fn = Path.GetFileNameWithoutExtension(packOrder[i]);
+ string s = f;
+ string fn = Path.GetFileNameWithoutExtension(f);
int compressed = fn.IndexOf("dec_", StringComparison.Ordinal);
int fileNumber = compressed < 0
? int.Parse(fn)
- : int.Parse(fn.Substring(compressed + 4));
+ : int.Parse(fn[(compressed + 4)..]);
+ garc.fatb.Entries[i].SubEntries[fileNumber].Exists = true;
if (compressed >= 0)
{
- string old = packOrder[i];
- LZSS.Compress(packOrder[i], packOrder[i] = Path.Combine(Path.GetDirectoryName(packOrder[i]), fileNumber.ToString()));
- File.Delete(old);
+ LZSS.Compress(f, s = Path.Combine(Path.GetDirectoryName(f), fileNumber.ToString()));
+ File.Delete(f);
}
// Assemble Vector
- v = 1;
+ v |= 1 << fileNumber;
// Assemble Entry
- FileInfo fi = new FileInfo(packOrder[i]);
- int actualLength = (int)(fi.Length % 4 == 0 ? fi.Length : fi.Length + 4 - fi.Length % 4);
- garc.fatb.Entries[i].SubEntries[0].Start = od;
- garc.fatb.Entries[i].SubEntries[0].End = actualLength + garc.fatb.Entries[i].SubEntries[0].Start;
- garc.fatb.Entries[i].SubEntries[0].Length = (int)fi.Length;
+ var fi = new FileInfo(s);
+ int actualLength = (int)(fi.Length % 4 == 0 ? fi.Length : fi.Length + 4 - (fi.Length % 4));
+ garc.fatb.Entries[i].SubEntries[fileNumber].Start = od;
+ garc.fatb.Entries[i].SubEntries[fileNumber].End = actualLength + garc.fatb.Entries[i].SubEntries[fileNumber].Start;
+ garc.fatb.Entries[i].SubEntries[fileNumber].Length = (int)fi.Length;
od += actualLength;
op += 12;
@@ -144,756 +179,715 @@ public static int garcPackMS(string folderPath, string garcPath, int version, in
// Step
PackProgressed?.Invoke(null, new PackProgressedEventArgs { Current = index++, Total = filectr, CurrentFile = packOrder[i] });
}
- else
- {
- garc.fatb.Entries[i].IsFolder = true;
- string[] subFiles = Directory.GetFiles(packOrder[i]);
- foreach (string f in subFiles)
- {
- string s = f;
- string fn = Path.GetFileNameWithoutExtension(f);
- int compressed = fn.IndexOf("dec_", StringComparison.Ordinal);
- int fileNumber = compressed < 0
- ? int.Parse(fn)
- : int.Parse(fn.Substring(compressed + 4));
- garc.fatb.Entries[i].SubEntries[fileNumber].Exists = true;
-
- if (compressed >= 0)
- {
- LZSS.Compress(f, s = Path.Combine(Path.GetDirectoryName(f), fileNumber.ToString()));
- File.Delete(f);
- }
-
- // Assemble Vector
- v |= 1 << fileNumber;
-
- // Assemble Entry
- FileInfo fi = new FileInfo(s);
- int actualLength = (int)(fi.Length % 4 == 0 ? fi.Length : fi.Length + 4 - fi.Length % 4);
- garc.fatb.Entries[i].SubEntries[fileNumber].Start = od;
- garc.fatb.Entries[i].SubEntries[fileNumber].End = actualLength + garc.fatb.Entries[i].SubEntries[fileNumber].Start;
- garc.fatb.Entries[i].SubEntries[fileNumber].Length = (int)fi.Length;
- od += actualLength;
-
- op += 12;
-
- // Step
- PackProgressed?.Invoke(null, new PackProgressedEventArgs { Current = index++, Total = filectr, CurrentFile = packOrder[i] });
- }
- }
- garc.fatb.Entries[i].Vector = (uint)v;
}
- garc.fatb.HeaderSize = 0xC + op;
+ garc.fatb.Entries[i].Vector = (uint)v;
}
- #endregion
-
- // Delete the old garc if it exists, then begin writing our new one
- try { File.Delete(garcPath); }
- catch { }
-
- // Set up the Header Info
- using (var newGARC = new FileStream(garcPath, FileMode.Create))
- using (BinaryWriter gw = new BinaryWriter(newGARC))
- {
- #region Write GARC Headers
- // Write GARC
- gw.Write((uint)0x47415243); // GARC
- gw.Write((uint)(version == VER_6 ? 0x24 : 0x1C)); // Header Length
- gw.Write((ushort)0xFEFF); // Endianness BOM
- gw.Write((ushort)version); // Version
- gw.Write((uint)0x00000004); // Section Count (4)
- gw.Write((uint)0x00000000); // Data Offset (temp)
- gw.Write((uint)0x00000000); // File Length (temp)
- gw.Write((uint)0x00000000); // Largest File Size (temp)
-
- if (version == VER_6)
- {
- gw.Write((uint)0x0);
- gw.Write((uint)0x0);
- }
-
- // Write FATO
- gw.Write((uint)0x4641544F); // FATO
- gw.Write(garc.fato.HeaderSize); // Header Size
- gw.Write(garc.fato.EntryCount); // Entry Count
- gw.Write(garc.fato.Padding); // Padding
- for (int i = 0; i < garc.fato.Entries.Length; i++)
- gw.Write((uint)garc.fato.Entries[i].Offset);
-
- // Write FATB
- gw.Write((uint)0x46415442); // FATB
- gw.Write(garc.fatb.HeaderSize); // Header Size
- gw.Write(garc.fatb.FileCount); // File Count
- foreach (var e in garc.fatb.Entries)
- {
- gw.Write(e.Vector);
- foreach (var s in e.SubEntries.Where(s => s.Exists))
- { gw.Write((uint)s.Start); gw.Write((uint)s.End); gw.Write((uint)s.Length); }
- }
+ garc.fatb.HeaderSize = 0xC + op;
+ }
+ #endregion
+
+ // Delete the old garc if it exists, then begin writing our new one
+ try { File.Delete(garcPath); }
+ catch { }
+
+ // Set up the Header Info
+ using var newGARC = new FileStream(garcPath, FileMode.Create);
+ using var gw = new BinaryWriter(newGARC);
+
+ #region Write GARC Headers
+ // Write GARC
+ gw.Write((uint)0x47415243); // GARC
+ gw.Write((uint)(version == VER_6 ? 0x24 : 0x1C)); // Header Length
+ gw.Write((ushort)0xFEFF); // Endianness BOM
+ gw.Write((ushort)version); // Version
+ gw.Write((uint)0x00000004); // Section Count (4)
+ gw.Write((uint)0x00000000); // Data Offset (temp)
+ gw.Write((uint)0x00000000); // File Length (temp)
+ gw.Write((uint)0x00000000); // Largest File Size (temp)
+
+ if (version == VER_6)
+ {
+ gw.Write((uint)0x0);
+ gw.Write((uint)0x0);
+ }
- // Write FIMB
- gw.Write((uint)0x46494D42); // FIMB
- gw.Write((uint)0x0000000C); // Header Length
- var dataLen = gw.BaseStream.Position;
- gw.Write((uint)0); // Data Length - TEMP
+ // Write FATO
+ gw.Write((uint)0x4641544F); // FATO
+ gw.Write(garc.fato.HeaderSize); // Header Size
+ gw.Write(garc.fato.EntryCount); // Entry Count
+ gw.Write(garc.fato.Padding); // Padding
+ foreach (var t in garc.fato.Entries)
+ gw.Write((uint)t.Offset);
+
+ // Write FATB
+ gw.Write((uint)0x46415442); // FATB
+ gw.Write(garc.fatb.HeaderSize); // Header Size
+ gw.Write(garc.fatb.FileCount); // File Count
+ foreach (var e in garc.fatb.Entries)
+ {
+ gw.Write(e.Vector);
+ foreach (var s in e.SubEntries.Where(s => s.Exists))
+ { gw.Write((uint)s.Start); gw.Write((uint)s.End); gw.Write((uint)s.Length); }
+ }
- gw.Seek(0x10, SeekOrigin.Begin); // Goto the start of the un-set 0 data we set earlier and set it.
- var hdrLen = gw.BaseStream.Position;
- gw.Write((uint)0); // Write Data Offset - TEMP
- gw.Write((uint)0); // Write total GARC Length - TEMP
+ // Write FIMB
+ gw.Write((uint)0x46494D42); // FIMB
+ gw.Write((uint)0x0000000C); // Header Length
+ var dataLen = gw.BaseStream.Position;
+ gw.Write((uint)0); // Data Length - TEMP
- // Write Handling information
- if (version == VER_4)
- {
- gw.Write(garc.ContentLargestUnpadded); // Write Largest File stat
- }
- else if (version == VER_6)
- {
- gw.Write(garc.ContentLargestPadded); // Write Largest With Padding
- gw.Write(garc.ContentLargestUnpadded); // Write Largest Without Padding
- gw.Write(garc.ContentPadToNearest);
- }
+ gw.Seek(0x10, SeekOrigin.Begin); // Goto the start of the un-set 0 data we set earlier and set it.
+ var hdrLen = gw.BaseStream.Position;
+ gw.Write((uint)0); // Write Data Offset - TEMP
+ gw.Write((uint)0); // Write total GARC Length - TEMP
- newGARC.Seek(0, SeekOrigin.End); // Goto the end so we can copy the filedata after the GARC headers.
-
- #endregion
+ // Write Handling information
+ if (version == VER_4)
+ {
+ gw.Write(garc.ContentLargestUnpadded); // Write Largest File stat
+ }
+ else if (version == VER_6)
+ {
+ gw.Write(garc.ContentLargestPadded); // Write Largest With Padding
+ gw.Write(garc.ContentLargestUnpadded); // Write Largest Without Padding
+ gw.Write(garc.ContentPadToNearest);
+ }
- #region Write Files
- var ghLength = gw.BaseStream.Length;
+ newGARC.Seek(0, SeekOrigin.End); // Goto the end so we can copy the filedata after the GARC headers.
- long largestSize = 0; // Required memory to allocate to handle the largest file
- long largestPadded = 0; // Required memory to allocate to handle the largest PADDED file (Ver6 only)
- foreach (string e in packOrder)
- {
- string[] fa = Directory.Exists(e) ? Directory.GetFiles(e) : new[] { e };
- foreach (string f in fa)
- {
- // Update largest file length if necessary
- long len = new FileInfo(f).Length;
- int padding = (int)(len % bytesPadding);
- if (padding != 0) padding = bytesPadding - padding;
- bool largest = len > largestSize;
- if (largest)
- {
- largestSize = len;
- largestPadded = len + padding;
- }
+ #endregion
- // Write to FIMB
- using (var x = File.OpenRead(f))
- x.CopyTo(newGARC);
+ #region Write Files
+ var ghLength = gw.BaseStream.Length;
- // While length is not divisible by 4, pad with FF (unused byte)
- while (padding-- > 0)
- gw.Write((byte)0xFF);
- }
+ long largestSize = 0; // Required memory to allocate to handle the largest file
+ long largestPadded = 0; // Required memory to allocate to handle the largest PADDED file (Ver6 only)
+ foreach (string e in packOrder)
+ {
+ string[] fa = Directory.Exists(e) ? Directory.GetFiles(e) : [e];
+ foreach (string f in fa)
+ {
+ // Update largest file length if necessary
+ long len = new FileInfo(f).Length;
+ int padding = (int)(len % bytesPadding);
+ if (padding != 0) padding = bytesPadding - padding;
+ bool largest = len > largestSize;
+ if (largest)
+ {
+ largestSize = len;
+ largestPadded = len + padding;
}
- garc.ContentLargestUnpadded = (uint)largestSize;
- garc.ContentLargestPadded = (uint)largestPadded;
- var gdLength = gw.BaseStream.Length - ghLength;
- #endregion
- gw.Seek((int)dataLen, SeekOrigin.Begin);
- gw.Write((uint)gdLength); // Data Length
- gw.Seek((int)hdrLen, SeekOrigin.Begin);
- gw.Write((uint)ghLength); // Write Data Offset
- gw.Write((uint)gw.BaseStream.Length); // Write total GARC Length
+ // Write to FIMB
+ using (var x = File.OpenRead(f))
+ x.CopyTo(newGARC);
- // Write Handling information
- if (version == VER_4)
- {
- gw.Write(garc.ContentLargestUnpadded); // Write Largest File stat
- }
- else if (version == VER_6)
- {
- gw.Write(garc.ContentLargestPadded); // Write Largest With Padding
- gw.Write(garc.ContentLargestUnpadded); // Write Largest Without Padding
- gw.Write(garc.ContentPadToNearest);
- }
-
- return filectr;
+ // While length is not divisible by 4, pad with FF (unused byte)
+ while (padding-- > 0)
+ gw.Write((byte)0xFF);
}
}
- public static int garcUnpack(string garcPath, string outPath, bool skipDecompression)
+ garc.ContentLargestUnpadded = (uint)largestSize;
+ garc.ContentLargestPadded = (uint)largestPadded;
+ var gdLength = gw.BaseStream.Length - ghLength;
+ #endregion
+
+ gw.Seek((int)dataLen, SeekOrigin.Begin);
+ gw.Write((uint)gdLength); // Data Length
+ gw.Seek((int)hdrLen, SeekOrigin.Begin);
+ gw.Write((uint)ghLength); // Write Data Offset
+ gw.Write((uint)gw.BaseStream.Length); // Write total GARC Length
+
+ // Write Handling information
+ if (version == VER_4)
{
- if (!File.Exists(garcPath)) throw new FileNotFoundException("File does not exist");
+ gw.Write(garc.ContentLargestUnpadded); // Write Largest File stat
+ }
+ else if (version == VER_6)
+ {
+ gw.Write(garc.ContentLargestPadded); // Write Largest With Padding
+ gw.Write(garc.ContentLargestUnpadded); // Write Largest Without Padding
+ gw.Write(garc.ContentPadToNearest);
+ }
- // Unpack the GARC
- GARCFile garc = unpackGARC(garcPath);
- const string ext = "bin"; // Default Extension Name
- int fileCount = garc.fatb.FileCount;
- string format = "D" + Math.Ceiling(Math.Log10(fileCount));
- if (outPath == "gametext")
- format = "D3";
+ return filectr;
+ }
- FileCountDetermined?.Invoke(null, new FileCountDeterminedEventArgs { Total = fileCount });
+ public static int GarcUnpack(string garcPath, string outPath, bool skipDecompression)
+ {
+ if (!File.Exists(garcPath)) throw new FileNotFoundException("File does not exist");
+
+ // Unpack the GARC
+ GARCFile garc = UnpackGARC(garcPath);
+ const string ext = "bin"; // Default Extension Name
+ int fileCount = garc.fatb.FileCount;
+ string format = "D" + Math.Ceiling(Math.Log10(fileCount));
+ if (outPath == "gametext")
+ format = "D3";
+
+ FileCountDetermined?.Invoke(null, new FileCountDeterminedEventArgs { Total = fileCount });
+
+ using var br = new BinaryReader(File.OpenRead(garcPath));
+ // Create Extraction folder if it does not exist.
+ if (!Directory.Exists(outPath))
+ Directory.CreateDirectory(outPath);
+
+ int filectr = 0;
+ // Pull out all the files
+ for (int o = 0; o < garc.fato.EntryCount; o++)
+ {
+ var Entry = garc.fatb.Entries[o];
+ // Set Entry File Name
+ string fileName = o.ToString(format);
+
+ #region OutDirectory Determination
+ string parentFolder = Entry.IsFolder ? Path.Combine(outPath, fileName) : outPath;
+ if (Entry.IsFolder) // Process Folder
+ Directory.CreateDirectory(parentFolder);
+ #endregion
- using (BinaryReader br = new BinaryReader(File.OpenRead(garcPath)))
+ uint vector = Entry.Vector;
+ for (int i = 0; i < 32; i++) // For each bit in vector
{
- // Create Extraction folder if it does not exist.
- if (!Directory.Exists(outPath))
- Directory.CreateDirectory(outPath);
-
- int filectr = 0;
- // Pull out all the files
- for (int o = 0; o < garc.fato.EntryCount; o++)
- {
+ var SubEntry = Entry.SubEntries[i];
+ if (!SubEntry.Exists) continue;
- var Entry = garc.fatb.Entries[o];
- // Set Entry File Name
- string fileName = o.ToString(format);
+ // Seek to Offset
+ br.BaseStream.Position = SubEntry.Start + garc.DataOffset;
- #region OutDirectory Determination
- string parentFolder = Entry.IsFolder ? Path.Combine(outPath, fileName) : outPath;
- if (Entry.IsFolder) // Process Folder
- Directory.CreateDirectory(parentFolder);
- #endregion
+ // Check if Compressed
+ bool compressed = false;
+ if (!skipDecompression)
+ {
+ try { compressed = (byte)br.PeekChar() == 0x11; }
+ catch { }
+ }
- uint vector = Entry.Vector;
- for (int i = 0; i < 32; i++) // For each bit in vector
+ // Write File
+ string fileOut = Path.Combine(parentFolder, (Entry.IsFolder ? i.ToString("00") : fileName) + "." + ext);
+ using (var bw = new BinaryWriter(File.OpenWrite(fileOut)))
+ {
+ // Write out the data for the file
+ br.BaseStream.Position = SubEntry.Start + garc.DataOffset;
+ bw.Write(br.ReadBytes(SubEntry.Length));
+ filectr++;
+ }
+ if (compressed)
+ #region Decompression
+ {
+ string decout = Path.Combine(Path.GetDirectoryName(fileOut), "dec_" + Path.GetFileName(fileOut));
+ try
+ {
+ LZSS.Decompress(fileOut, decout);
+ try { File.Delete(fileOut); }
+ catch (Exception e) { throw new Exception("A compressed file could not be deleted: " + fileOut, e); }
+ }
+ catch
{
- var SubEntry = Entry.SubEntries[i];
- if (!SubEntry.Exists) continue;
+ // File is really not encrypted.
+ File.Delete(decout);
+ }
+ }
+ #endregion
- // Seek to Offset
- br.BaseStream.Position = SubEntry.Start + garc.DataOffset;
+ UnpackProgressed?.Invoke(null, new UnpackProgressedEventArgs { Current = filectr, Total = fileCount });
- // Check if Compressed
- bool compressed = false;
- if (!skipDecompression)
- try { compressed = (byte)br.PeekChar() == 0x11; }
- catch { }
+ if ((vector >>= 1) == 0) break;
+ }
+ }
- // Write File
- string fileOut = Path.Combine(parentFolder, (Entry.IsFolder ? i.ToString("00") : fileName) + "." + ext);
- using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(fileOut)))
- {
- // Write out the data for the file
- br.BaseStream.Position = SubEntry.Start + garc.DataOffset;
- bw.Write(br.ReadBytes(SubEntry.Length));
- filectr++;
- }
- if (compressed)
- #region Decompression
- {
- string decout = Path.Combine(Path.GetDirectoryName(fileOut), "dec_" + Path.GetFileName(fileOut));
- try
- {
- LZSS.Decompress(fileOut, decout);
- try { File.Delete(fileOut); }
- catch (Exception e) { throw new Exception("A compressed file could not be deleted: " + fileOut, e); }
- }
- catch
- {
- // File is really not encrypted.
- File.Delete(decout);
- }
- }
- #endregion
+ return fileCount;
+ }
- UnpackProgressed?.Invoke(null, new UnpackProgressedEventArgs { Current = filectr, Total = fileCount });
+ public static GARCFile UnpackGARC(string path)
+ {
+ return UnpackGARC(File.OpenRead(path));
+ }
- if ((vector >>= 1) == 0) break;
- }
- }
- }
- return fileCount;
- }
+ private static GARCFile UnpackGARC(byte[] data)
+ {
+ using var gd = new MemoryStream(data);
+ return UnpackGARC(gd);
+ }
- public static GARCFile unpackGARC(string path)
+ private static GARCFile UnpackGARC(Stream stream)
+ {
+ using var br = new BinaryReader(stream);
+ var garc = new GARCFile
{
- return unpackGARC(File.OpenRead(path));
+ Magic = br.ReadChars(4),
+ HeaderSize = br.ReadUInt32(),
+ Endianess = br.ReadUInt16(),
+ Version = br.ReadUInt16(),
+ ChunkCount = br.ReadUInt32(),
+ DataOffset = br.ReadUInt32(),
+ FileSize = br.ReadUInt32(),
+ };
+ // GARC Header
+
+ if (garc.Version == VER_4)
+ {
+ garc.ContentLargestUnpadded = br.ReadUInt32();
+ garc.ContentPadToNearest = 4;
}
- private static GARCFile unpackGARC(byte[] data)
+ else if (garc.Version == VER_6)
{
- GARCFile garc;
- using (var gd = new MemoryStream(data))
- garc = unpackGARC(gd);
- return garc;
+ garc.ContentLargestPadded = br.ReadUInt32();
+ garc.ContentLargestUnpadded = br.ReadUInt32();
+ garc.ContentPadToNearest = br.ReadUInt32();
}
- private static GARCFile unpackGARC(Stream stream)
+ else
{
- GARCFile garc = new GARCFile();
- using (BinaryReader br = new BinaryReader(stream))
- {
- // GARC Header
- garc.Magic = br.ReadChars(4);
- garc.HeaderSize = br.ReadUInt32();
- garc.Endianess = br.ReadUInt16();
- garc.Version = br.ReadUInt16();
- garc.ChunkCount = br.ReadUInt32();
-
- garc.DataOffset = br.ReadUInt32();
- garc.FileSize = br.ReadUInt32();
- if (garc.Version == VER_4)
- {
- garc.ContentLargestUnpadded = br.ReadUInt32();
- garc.ContentPadToNearest = 4;
- }
- else if (garc.Version == VER_6)
- {
- garc.ContentLargestPadded = br.ReadUInt32();
- garc.ContentLargestUnpadded = br.ReadUInt32();
- garc.ContentPadToNearest = br.ReadUInt32();
- }
- else
- throw new FormatException("Invalid GARC Version: 0x" + garc.Version.ToString("X4"));
- if (garc.ChunkCount != 4)
- throw new FormatException("Invalid GARC Chunk Count: " + garc.ChunkCount);
-
- // FATO (File Allocation Table Offsets)
- garc.fato.Magic = br.ReadChars(4);
- garc.fato.HeaderSize = br.ReadInt32();
- garc.fato.EntryCount = br.ReadUInt16();
- garc.fato.Padding = br.ReadUInt16();
-
- garc.fato.Entries = new FATO_Entry[garc.fato.EntryCount];
- for (int i = 0; i < garc.fato.EntryCount; i++)
- garc.fato.Entries[i].Offset = br.ReadInt32();
-
- // FATB (File Allocation Table Bits)
- garc.fatb.Magic = br.ReadChars(4);
- garc.fatb.HeaderSize = br.ReadInt32();
- garc.fatb.FileCount = br.ReadInt32();
-
- garc.fatb.Entries = new FATB_Entry[garc.fato.EntryCount];
- for (int i = 0; i < garc.fato.EntryCount; i++) // Loop through all FATO entries
- {
- garc.fatb.Entries[i].Vector = br.ReadUInt32();
- garc.fatb.Entries[i].SubEntries = new FATB_SubEntry[32];
- uint bitvector = garc.fatb.Entries[i].Vector;
- int ctr = 0;
- for (int b = 0; b < 32; b++)
- {
- garc.fatb.Entries[i].SubEntries[b].Exists = (bitvector & 1) == 1;
- bitvector >>= 1;
- if (!garc.fatb.Entries[i].SubEntries[b].Exists) continue;
- garc.fatb.Entries[i].SubEntries[b].Start = br.ReadInt32();
- garc.fatb.Entries[i].SubEntries[b].End = br.ReadInt32();
- garc.fatb.Entries[i].SubEntries[b].Length = br.ReadInt32();
- ctr++;
- }
- garc.fatb.Entries[i].IsFolder = ctr > 1;
- }
+ throw new FormatException("Invalid GARC Version: 0x" + garc.Version.ToString("X4"));
+ }
+
+ if (garc.ChunkCount != 4)
+ throw new FormatException("Invalid GARC Chunk Count: " + garc.ChunkCount);
+
+ // FATO (File Allocation Table Offsets)
+ garc.fato.Magic = br.ReadChars(4);
+ garc.fato.HeaderSize = br.ReadInt32();
+ garc.fato.EntryCount = br.ReadUInt16();
+ garc.fato.Padding = br.ReadUInt16();
- // FIMB (File IMage Bytes)
- garc.fimg.Magic = br.ReadChars(4);
- garc.fimg.HeaderSize = br.ReadInt32();
- garc.fimg.DataSize = br.ReadInt32();
+ garc.fato.Entries = new FATO_Entry[garc.fato.EntryCount];
+ for (int i = 0; i < garc.fato.EntryCount; i++)
+ garc.fato.Entries[i].Offset = br.ReadInt32();
- // Files data
- // Oftentimes too large to toss into a byte array. Fetch as needed with a BinaryReader.
+ // FATB (File Allocation Table Bits)
+ garc.fatb.Magic = br.ReadChars(4);
+ garc.fatb.HeaderSize = br.ReadInt32();
+ garc.fatb.FileCount = br.ReadInt32();
+
+ garc.fatb.Entries = new FATB_Entry[garc.fato.EntryCount];
+ for (int i = 0; i < garc.fato.EntryCount; i++) // Loop through all FATO entries
+ {
+ garc.fatb.Entries[i].Vector = br.ReadUInt32();
+ garc.fatb.Entries[i].SubEntries = new FATB_SubEntry[32];
+ uint bitvector = garc.fatb.Entries[i].Vector;
+ int ctr = 0;
+ for (int b = 0; b < 32; b++)
+ {
+ garc.fatb.Entries[i].SubEntries[b].Exists = (bitvector & 1) == 1;
+ bitvector >>= 1;
+ if (!garc.fatb.Entries[i].SubEntries[b].Exists) continue;
+ garc.fatb.Entries[i].SubEntries[b].Start = br.ReadInt32();
+ garc.fatb.Entries[i].SubEntries[b].End = br.ReadInt32();
+ garc.fatb.Entries[i].SubEntries[b].Length = br.ReadInt32();
+ ctr++;
}
- return garc;
+ garc.fatb.Entries[i].IsFolder = ctr > 1;
}
- public static MemGARC packGARC(byte[][] data, int version, int contentpadnearest)
+ // FIMB (File IMage Bytes)
+ garc.fimg.Magic = br.ReadChars(4);
+ garc.fimg.HeaderSize = br.ReadInt32();
+ garc.fimg.DataSize = br.ReadInt32();
+
+ // Files data
+ // Oftentimes too large to toss into a byte array. Fetch as needed with a BinaryReader.
+ return garc;
+ }
+
+ public static MemGARC PackGARC(byte[][] data, int version, int contentpadnearest)
+ {
+ if (contentpadnearest < 0)
+ contentpadnearest = 4;
+ // Set Up the GARC template.
+ var garc = new GARCFile
{
- if (contentpadnearest < 0)
- contentpadnearest = 4;
- // Set Up the GARC template.
- GARCFile garc = new GARCFile
+ ContentPadToNearest = (uint)contentpadnearest,
+ fato =
{
- ContentPadToNearest = (uint)contentpadnearest,
- fato =
- {
- // Magic = new[] { 'O', 'T', 'A', 'F' },
- Entries = new FATO_Entry[data.Length],
- EntryCount = (ushort) data.Length,
- HeaderSize = 0xC + data.Length*4,
- Padding = 0xFFFF
- },
- fatb =
- {
- // Magic = new[] { 'B', 'T', 'A', 'F' },
- Entries = new FATB_Entry[data.Length],
- FileCount = data.Length
- }
- };
+ // Magic = new[] { 'O', 'T', 'A', 'F' },
+ Entries = new FATO_Entry[data.Length],
+ EntryCount = (ushort) data.Length,
+ HeaderSize = 0xC + (data.Length*4),
+ Padding = 0xFFFF,
+ },
+ fatb =
+ {
+ // Magic = new[] { 'B', 'T', 'A', 'F' },
+ Entries = new FATB_Entry[data.Length],
+ FileCount = data.Length,
+ },
+ };
+
+ if (version == VER_6)
+ garc.ContentPadToNearest = 4;
+
+ int op = 0;
+ int od = 0;
+ for (int i = 0; i < garc.fatb.Entries.Length; i++)
+ {
+ garc.fato.Entries[i].Offset = op; // FATO offset
+ garc.fatb.Entries[i].SubEntries = new FATB_SubEntry[32];
+ op += 4; // Vector
+ garc.fatb.Entries[i].IsFolder = false;
+ garc.fatb.Entries[i].SubEntries[0].Exists = true;
+
+ // Assemble Entry
+ var paddingRequired = data[i].Length % garc.ContentPadToNearest;
+ if (paddingRequired != 0) paddingRequired = garc.ContentPadToNearest - paddingRequired;
+ int actualLength = data[i].Length + (int)paddingRequired;
+ garc.fatb.Entries[i].SubEntries[0].Start = od;
+ garc.fatb.Entries[i].SubEntries[0].End = actualLength + garc.fatb.Entries[i].SubEntries[0].Start;
+ garc.fatb.Entries[i].SubEntries[0].Length = data[i].Length;
+ garc.fatb.Entries[i].SubEntries[0].Padding = (int)paddingRequired;
+ od += actualLength;
+
+ op += 12;
+ garc.fatb.Entries[i].Vector = 1;
+ }
+ garc.fatb.HeaderSize = 0xC + op;
- if (version == VER_6)
- garc.ContentPadToNearest = 4;
+ // Set up the Header Info
+ string tempFile = Path.GetTempFileName();
+ using (var newGARC = new FileStream(tempFile, FileMode.Create))
+ using (var gw = new BinaryWriter(newGARC))
+ {
+ #region Write GARC Headers
+
+ // Write GARC
+ gw.Write((uint)0x47415243); // GARC
+ gw.Write((uint)(version == VER_6 ? 0x24 : 0x1C)); // Header Length
+ gw.Write((ushort)0xFEFF); // Endianness BOM
+ gw.Write((ushort)version); // Version
+ gw.Write((uint)0x00000004); // Section Count (4)
+ gw.Write((uint)0x00000000); // Data Offset (temp)
+ gw.Write((uint)0x00000000); // File Length (temp)
+ gw.Write((uint)0x00000000); // Largest File Size (temp)
- int op = 0;
- int od = 0;
- for (int i = 0; i < garc.fatb.Entries.Length; i++)
+ if (version == VER_6)
{
- garc.fato.Entries[i].Offset = op; // FATO offset
- garc.fatb.Entries[i].SubEntries = new FATB_SubEntry[32];
- op += 4; // Vector
- garc.fatb.Entries[i].IsFolder = false;
- garc.fatb.Entries[i].SubEntries[0].Exists = true;
-
- // Assemble Entry
- var paddingRequired = data[i].Length%garc.ContentPadToNearest;
- if (paddingRequired != 0) paddingRequired = garc.ContentPadToNearest - paddingRequired;
- int actualLength = data[i].Length + (int)paddingRequired;
- garc.fatb.Entries[i].SubEntries[0].Start = od;
- garc.fatb.Entries[i].SubEntries[0].End = actualLength + garc.fatb.Entries[i].SubEntries[0].Start;
- garc.fatb.Entries[i].SubEntries[0].Length = data[i].Length;
- garc.fatb.Entries[i].SubEntries[0].Padding = (int)paddingRequired;
- od += actualLength;
-
- op += 12;
- garc.fatb.Entries[i].Vector = 1;
+ gw.Write((uint)0x0);
+ gw.Write((uint)0x0);
}
- garc.fatb.HeaderSize = 0xC + op;
- // Set up the Header Info
- string tempFile = Path.GetTempFileName();
- using (var newGARC = new FileStream(tempFile, FileMode.Create))
- using (BinaryWriter gw = new BinaryWriter(newGARC))
+ // Write FATO
+ gw.Write((uint)0x4641544F); // FATO
+ gw.Write(garc.fato.HeaderSize); // Header Size
+ gw.Write(garc.fato.EntryCount); // Entry Count
+ gw.Write(garc.fato.Padding); // Padding
+ foreach (var t in garc.fato.Entries)
+ gw.Write((uint)t.Offset);
+
+ // Write FATB
+ gw.Write((uint)0x46415442); // FATB
+ gw.Write(garc.fatb.HeaderSize); // Header Size
+ gw.Write(garc.fatb.FileCount); // File Count
+ foreach (var e in garc.fatb.Entries)
{
- #region Write GARC Headers
-
- // Write GARC
- gw.Write((uint) 0x47415243); // GARC
- gw.Write((uint) (version == VER_6 ? 0x24 : 0x1C)); // Header Length
- gw.Write((ushort) 0xFEFF); // Endianness BOM
- gw.Write((ushort) version); // Version
- gw.Write((uint) 0x00000004); // Section Count (4)
- gw.Write((uint) 0x00000000); // Data Offset (temp)
- gw.Write((uint) 0x00000000); // File Length (temp)
- gw.Write((uint) 0x00000000); // Largest File Size (temp)
-
- if (version == VER_6)
+ gw.Write(e.Vector);
+ foreach (var s in e.SubEntries.Where(s => s.Exists))
{
- gw.Write((uint) 0x0);
- gw.Write((uint) 0x0);
+ gw.Write((uint)s.Start);
+ gw.Write((uint)s.End);
+ gw.Write((uint)s.Length);
}
+ }
- // Write FATO
- gw.Write((uint) 0x4641544F); // FATO
- gw.Write(garc.fato.HeaderSize); // Header Size
- gw.Write(garc.fato.EntryCount); // Entry Count
- gw.Write(garc.fato.Padding); // Padding
- for (int i = 0; i < garc.fato.Entries.Length; i++)
- gw.Write((uint) garc.fato.Entries[i].Offset);
-
- // Write FATB
- gw.Write((uint) 0x46415442); // FATB
- gw.Write(garc.fatb.HeaderSize); // Header Size
- gw.Write(garc.fatb.FileCount); // File Count
- foreach (var e in garc.fatb.Entries)
- {
- gw.Write(e.Vector);
- foreach (var s in e.SubEntries.Where(s => s.Exists))
- {
- gw.Write((uint) s.Start);
- gw.Write((uint) s.End);
- gw.Write((uint) s.Length);
- }
- }
+ gw.Write((uint)0x46494D42); // FIMB
+ gw.Write((uint)0x0000000C); // Header Length
+ var dataLen = gw.BaseStream.Position;
+ gw.Write((uint)0); // Data Length - TEMP
- gw.Write((uint) 0x46494D42); // FIMB
- gw.Write((uint) 0x0000000C); // Header Length
- var dataLen = gw.BaseStream.Position;
- gw.Write((uint) 0); // Data Length - TEMP
+ gw.Seek(0x10, SeekOrigin.Begin); // Goto the start of the un-set 0 data we set earlier and set it.
+ var hdrLen = gw.BaseStream.Position;
+ gw.Write((uint)0); // Write Data Offset - TEMP
+ gw.Write((uint)0); // Write total GARC Length - TEMP
- gw.Seek(0x10, SeekOrigin.Begin); // Goto the start of the un-set 0 data we set earlier and set it.
- var hdrLen = gw.BaseStream.Position;
- gw.Write((uint) 0); // Write Data Offset - TEMP
- gw.Write((uint) 0); // Write total GARC Length - TEMP
+ // Write Handling information
+ if (version == VER_4)
+ {
+ gw.Write(garc.ContentLargestUnpadded); // Write Largest File stat
+ }
+ else if (version == VER_6)
+ {
+ gw.Write(garc.ContentLargestPadded); // Write Largest With Padding
+ gw.Write(garc.ContentLargestUnpadded); // Write Largest Without Padding
+ gw.Write(garc.ContentPadToNearest);
+ }
- // Write Handling information
- if (version == VER_4)
- {
- gw.Write(garc.ContentLargestUnpadded); // Write Largest File stat
- }
- else if (version == VER_6)
- {
- gw.Write(garc.ContentLargestPadded); // Write Largest With Padding
- gw.Write(garc.ContentLargestUnpadded); // Write Largest Without Padding
- gw.Write(garc.ContentPadToNearest);
- }
+ newGARC.Seek(0, SeekOrigin.End); // Goto the end so we can copy the filedata after the GARC headers.
- newGARC.Seek(0, SeekOrigin.End); // Goto the end so we can copy the filedata after the GARC headers.
+ #endregion
- #endregion
+ #region Write Files
- #region Write Files
+ var ghLength = gw.BaseStream.Length;
- var ghLength = gw.BaseStream.Length;
+ long largestSize = 0; // Required memory to allocate to handle the largest file
+ long largestPadded = 0; // Required memory to allocate to handle the largest PADDED file (Ver6 only)
+ for (int i = 0; i < data.Length; i++)
+ {
+ byte[] e = data[i];
- long largestSize = 0; // Required memory to allocate to handle the largest file
- long largestPadded = 0; // Required memory to allocate to handle the largest PADDED file (Ver6 only)
- for (int i = 0; i < data.Length; i++)
+ // Update largest file length if necessary
+ int len = e.Length;
+ int padding = garc.fatb.Entries[i].SubEntries[0].Padding;
+ bool largest = len > largestSize;
+ if (largest)
{
- byte[] e = data[i];
-
- // Update largest file length if necessary
- int len = e.Length;
- int padding = garc.fatb.Entries[i].SubEntries[0].Padding;
- bool largest = len > largestSize;
- if (largest)
- {
- largestSize = len;
- largestPadded = len + padding;
- }
-
- // Write to FIMB
- gw.Write(e);
-
- // Pad with FF (unused byte)
- while (padding-- > 0)
- gw.Write((byte)0xFF);
+ largestSize = len;
+ largestPadded = len + padding;
}
- garc.ContentLargestUnpadded = (uint)largestSize;
- garc.ContentLargestPadded = (uint)largestPadded;
- var gdLength = gw.BaseStream.Length - ghLength;
-
- #endregion
- gw.Seek((int)dataLen, SeekOrigin.Begin);
- gw.Write((uint)gdLength); // Data Length
- gw.Seek((int)hdrLen, SeekOrigin.Begin);
- gw.Write((uint)ghLength); // Write Data Offset
- gw.Write((uint)gw.BaseStream.Length); // Write total GARC Length
+ // Write to FIMB
+ gw.Write(e);
- if (version == VER_4)
- {
- gw.Write(garc.ContentLargestUnpadded); // Write Largest File stat
- }
- else if (version == VER_6)
- {
- gw.Write(garc.ContentLargestPadded); // Write Largest With Padding
- gw.Write(garc.ContentLargestUnpadded); // Write Largest Without Padding
- gw.Write(garc.ContentPadToNearest);
- }
+ // Pad with FF (unused byte)
+ while (padding-- > 0)
+ gw.Write((byte)0xFF);
}
+ garc.ContentLargestUnpadded = (uint)largestSize;
+ garc.ContentLargestPadded = (uint)largestPadded;
+ var gdLength = gw.BaseStream.Length - ghLength;
- byte[] GARCdata = File.ReadAllBytes(tempFile);
- File.Delete(tempFile);
- return new MemGARC(GARCdata);
- }
+ #endregion
- public class MemGARC
- {
- internal GARCFile garc;
- internal byte[] Data;
- public int FileCount => garc.fato.EntryCount;
+ gw.Seek((int)dataLen, SeekOrigin.Begin);
+ gw.Write((uint)gdLength); // Data Length
+ gw.Seek((int)hdrLen, SeekOrigin.Begin);
+ gw.Write((uint)ghLength); // Write Data Offset
+ gw.Write((uint)gw.BaseStream.Length); // Write total GARC Length
- public MemGARC(byte[] data)
+ if (version == VER_4)
{
- Data = data;
- garc = unpackGARC(data);
+ gw.Write(garc.ContentLargestUnpadded); // Write Largest File stat
}
+ else if (version == VER_6)
+ {
+ gw.Write(garc.ContentLargestPadded); // Write Largest With Padding
+ gw.Write(garc.ContentLargestUnpadded); // Write Largest Without Padding
+ gw.Write(garc.ContentPadToNearest);
+ }
+ }
+
+ byte[] GARCdata = File.ReadAllBytes(tempFile);
+ File.Delete(tempFile);
+ return new MemGARC(GARCdata);
+ }
- // Returns an individual file
- public byte[] getFile(int file, int subfile = 0)
+ public class MemGARC(byte[] data)
+ {
+ internal GARCFile garc = UnpackGARC(data);
+ internal byte[] Data = data;
+ public int FileCount => garc.fato.EntryCount;
+
+ // Returns an individual file
+ public byte[] GetFile(int file, int subfile = 0)
+ {
+ var Entry = garc.fatb.Entries[file];
+ var SubEntry = Entry.SubEntries[subfile];
+ if (!SubEntry.Exists)
+ throw new ArgumentException("SubFile does not exist.");
+ var offset = SubEntry.Start + garc.DataOffset;
+ byte[] data = new byte[SubEntry.Length];
+ Array.Copy(Data, offset, data, 0, data.Length);
+ return data;
+ }
+
+ // Returns all files (excluding language vectorized)
+ public byte[][] Files
+ {
+ get
{
- var Entry = garc.fatb.Entries[file];
- var SubEntry = Entry.SubEntries[subfile];
- if (!SubEntry.Exists)
- throw new ArgumentException("SubFile does not exist.");
- var offset = SubEntry.Start + garc.DataOffset;
- byte[] data = new byte[SubEntry.Length];
- Array.Copy(Data, offset, data, 0, data.Length);
+ byte[][] data = new byte[FileCount][];
+ for (int i = 0; i < data.Length; i++)
+ data[i] = GetFile(i);
return data;
}
-
- // Returns all files (excluding language vectorized)
- public byte[][] Files
+ set
{
- get
- {
- byte[][] data = new byte[FileCount][];
- for (int i = 0; i < data.Length; i++)
- data[i] = getFile(i);
- return data;
- }
- set
- {
- if (value == null || value.Length != FileCount)
- throw new ArgumentException();
+ if (value == null || value.Length != FileCount)
+ throw new ArgumentException();
- var ng = packGARC(value, garc.Version, (int)garc.ContentPadToNearest);
- garc = ng.garc;
- Data = ng.Data;
- }
+ var ng = PackGARC(value, garc.Version, (int)garc.ContentPadToNearest);
+ garc = ng.garc;
+ Data = ng.Data;
}
}
+ }
- ///
- /// GARC Class that is heavier on OOP to allow for compression tracking for faster edits
- ///
- public class lzGARC
- {
- private GARCFile garc;
- private byte[] Data;
- public int FileCount => garc.fato.EntryCount;
+ ///
+ /// GARC Class that is heavier on OOP to allow for compression tracking for faster edits
+ ///
+ public class LazyGARC
+ {
+ private GARCFile garc;
+ private byte[] Data;
+ public int FileCount => garc.fato.EntryCount;
- public lzGARC(byte[] data)
- {
- Data = data;
- garc = unpackGARC(data);
- Storage = new GARCEntry[FileCount];
- }
+ public LazyGARC(byte[] data)
+ {
+ Data = data;
+ garc = UnpackGARC(data);
+ Storage = new GARCEntry[FileCount];
+ }
- private readonly GARCEntry[] Storage;
- private class GARCEntry
- {
- public bool Accessed;
- public bool Saved;
- public byte[] Data;
- public readonly bool WasCompressed;
+ private readonly GARCEntry[] Storage;
- public GARCEntry() { }
- public GARCEntry(byte[] data)
- {
- Data = data;
- Accessed = true;
+ private class GARCEntry
+ {
+ public bool Saved;
+ public byte[] Data;
+ private readonly bool WasCompressed;
- if (data.Length == 0)
- return;
+ public GARCEntry(byte[] data)
+ {
+ Data = data;
- if (data[0] != 0x11)
- return;
+ if (data.Length == 0)
+ return;
- try
- {
- using (MemoryStream newMS = new MemoryStream())
- {
- LZSS.Decompress(new MemoryStream(data), data.Length, newMS);
- Data = newMS.ToArray();
- }
- WasCompressed = true;
- }
- catch { }
- }
+ if (data[0] != 0x11)
+ return;
- public byte[] Save()
+ try
{
- if (!WasCompressed)
- return Data;
-
- byte[] data;
- try
+ using (var newMS = new MemoryStream())
{
- using (MemoryStream newMS = new MemoryStream())
- {
- LZSS.Compress(new MemoryStream(Data), Data.Length, newMS, original: true);
- data = newMS.ToArray();
- }
+ LZSS.Decompress(new MemoryStream(data), data.Length, newMS);
+ Data = newMS.ToArray();
}
- catch { data = new byte[0]; }
- return data;
+ WasCompressed = true;
}
+ catch { }
}
- private byte[] getFile(int file, int subfile = 0)
- {
- var Entry = garc.fatb.Entries[file];
- var SubEntry = Entry.SubEntries[subfile];
- if (!SubEntry.Exists)
- throw new ArgumentException("SubFile does not exist.");
- var offset = SubEntry.Start + garc.DataOffset;
- byte[] data = new byte[SubEntry.Length];
- Array.Copy(Data, offset, data, 0, data.Length);
- return data;
- }
- public byte[] this[int file]
- {
- get
- {
- if (file > FileCount)
- throw new ArgumentException();
-
- if (Storage[file] == null)
- Storage[file] = new GARCEntry(getFile(file, 0));
- return Storage[file].Data;
- }
- set
- {
- if (Storage[file] == null)
- Storage[file] = new GARCEntry(value);
- Storage[file].Data = value;
- Storage[file].Saved = true;
- }
- }
public byte[] Save()
{
- byte[][] data = new byte[FileCount][];
- for (int i = 0; i < data.Length; i++)
+ if (!WasCompressed)
+ return Data;
+
+ byte[] data;
+ try
{
- if (Storage[i] == null || !Storage[i].Saved) // retrieve original
- data[i] = getFile(i, 0);
- else // use modified
- data[i] = Storage[i].Save();
+ using var newMS = new MemoryStream();
+ LZSS.Compress(new MemoryStream(Data), Data.Length, newMS, original: true);
+ data = newMS.ToArray();
}
-
- var ng = packGARC(data, garc.Version, (int)garc.ContentPadToNearest);
- garc = ng.garc;
- Data = ng.Data;
- return Data;
+ catch { data = []; }
+ return data;
}
}
- public struct GARCFile
+ private byte[] GetFile(int file, int subfile = 0)
{
- public char[] Magic; // Always GARC = 0x4E415243
- public uint HeaderSize; // Always 0x001C
- public ushort Endianess; // 0xFFFE
- public ushort Version; // 4: gen6, 6: gen7
- public uint ChunkCount; // Always 0x0400 chunk count
-
- public uint DataOffset;
- public uint FileSize;
-
- public uint ContentLargestPadded; // Format 6 Only
- public uint ContentLargestUnpadded;
- public uint ContentPadToNearest; // Format 6 Only (4 bytes is standard in VER_4, and is not stored)
-
- public FATO fato;
- public FATB fatb;
- public FIMG fimg;
+ var Entry = garc.fatb.Entries[file];
+ var SubEntry = Entry.SubEntries[subfile];
+ if (!SubEntry.Exists)
+ throw new ArgumentException("SubFile does not exist.");
+ var offset = SubEntry.Start + garc.DataOffset;
+ byte[] data = new byte[SubEntry.Length];
+ Array.Copy(Data, offset, data, 0, data.Length);
+ return data;
}
- public struct FATO
+ public byte[] this[int file]
{
- public char[] Magic;
- public int HeaderSize;
- public ushort EntryCount;
- public ushort Padding;
+ get
+ {
+ if (file > FileCount)
+ throw new ArgumentException();
- public FATO_Entry[] Entries;
- }
- public struct FATO_Entry
- {
- public int Offset;
+ Storage[file] ??= new GARCEntry(GetFile(file, 0));
+ return Storage[file].Data;
+ }
+ set
+ {
+ Storage[file] ??= new GARCEntry(value);
+ Storage[file].Data = value;
+ Storage[file].Saved = true;
+ }
}
- public struct FATB
+ public byte[] Save()
{
- public char[] Magic;
- public int HeaderSize;
- public int FileCount;
+ byte[][] data = new byte[FileCount][];
+ for (int i = 0; i < data.Length; i++)
+ {
+ if (Storage[i]?.Saved != true) // retrieve original
+ data[i] = GetFile(i, 0);
+ else // use modified
+ data[i] = Storage[i].Save();
+ }
- public FATB_Entry[] Entries;
+ var ng = PackGARC(data, garc.Version, (int)garc.ContentPadToNearest);
+ garc = ng.garc;
+ Data = ng.Data;
+ return Data;
}
- public struct FATB_Entry
- {
- public uint Vector;
- public bool IsFolder;
- public FATB_SubEntry[] SubEntries;
- }
- public struct FATB_SubEntry
- {
- public bool Exists;
- public int Start;
- public int End;
- public int Length;
+ }
- // Unsaved Properties
- public int Padding { get; set; }
- }
+ public struct GARCFile
+ {
+ public char[] Magic; // Always GARC = 0x4E415243
+ public uint HeaderSize; // Always 0x001C
+ public ushort Endianess; // 0xFFFE
+ public ushort Version; // 4: gen6, 6: gen7
+ public uint ChunkCount; // Always 0x0400 chunk count
+
+ public uint DataOffset;
+ public uint FileSize;
+
+ public uint ContentLargestPadded; // Format 6 Only
+ public uint ContentLargestUnpadded;
+ public uint ContentPadToNearest; // Format 6 Only (4 bytes is standard in VER_4, and is not stored)
+
+ public FATO fato;
+ public FATB fatb;
+ public FIMG fimg;
+ }
- public struct FIMG
- {
- public char[] Magic;
- public int HeaderSize;
- public int DataSize;
- }
+ public struct FATO
+ {
+ public char[] Magic;
+ public int HeaderSize;
+ public ushort EntryCount;
+ public ushort Padding;
+
+ public FATO_Entry[] Entries;
+ }
+
+ public struct FATO_Entry
+ {
+ public int Offset;
+ }
+
+ public struct FATB
+ {
+ public char[] Magic;
+ public int HeaderSize;
+ public int FileCount;
+
+ public FATB_Entry[] Entries;
+ }
+
+ public struct FATB_Entry
+ {
+ public uint Vector;
+ public bool IsFolder;
+ public FATB_SubEntry[] SubEntries;
+ }
+
+ public struct FATB_SubEntry
+ {
+ public bool Exists;
+ public int Start;
+ public int End;
+ public int Length;
+
+ // Unsaved Properties
+ public int Padding { get; set; }
+ }
+
+ public struct FIMG
+ {
+ public char[] Magic;
+ public int HeaderSize;
+ public int DataSize;
}
- #endregion
-}
\ No newline at end of file
+}
+#endregion
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/Images/BCLIM.cs b/pk3DS.Core/CTR/Images/BCLIM.cs
new file mode 100644
index 0000000000..4a5ad09ca3
--- /dev/null
+++ b/pk3DS.Core/CTR/Images/BCLIM.cs
@@ -0,0 +1,474 @@
+using System;
+using System.Drawing;
+using System.IO;
+using pk3DS.Core.CTR.Images;
+
+namespace pk3DS.Core.CTR;
+
+public class BCLIM : BXLIM
+{
+ public BCLIM(Stream data) => ReadBCLIM(data);
+
+ public BCLIM(byte[] data)
+ {
+ using var ms = new MemoryStream(data);
+ ReadBCLIM(ms);
+ }
+
+ public BCLIM(string path)
+ {
+ var data = File.ReadAllBytes(path);
+ using var ms = new MemoryStream(data);
+ ReadBCLIM(ms);
+ }
+
+ private void ReadBCLIM(Stream ms)
+ {
+ PixelData = new byte[ms.Length - FLIMHeader.SIZE];
+ _ = ms.Read(PixelData, 0, PixelData.Length);
+ var footer = new byte[FLIMHeader.SIZE];
+ _ = ms.Read(footer, 0, footer.Length);
+ Footer = footer.ToStructure();
+ }
+
+ public override uint[] GetPixels()
+ {
+ if (Format == XLIMEncoding.RGB5A1 && BitConverter.ToUInt16(PixelData, 0) == 2) // Gen6 Palette
+ return GetPixelsViaPalette();
+ return base.GetPixels();
+ }
+
+ private uint[] GetPixelsViaPalette()
+ {
+ using var ms = new MemoryStream(PixelData);
+ using var br = new BinaryReader(ms);
+ if (br.ReadUInt16() != 2) return null;
+
+ // read palette
+ int count = br.ReadUInt16();
+ uint[] colors = new uint[count];
+ for (int i = 0; i < colors.Length; i++)
+ colors[i] = PixelConverter.GetDecodedPixelValue(br.ReadUInt16(), XLIMEncoding.RGB565);
+
+ // read pixels
+ bool half = colors.Length < 0x10;
+ uint[] pixels = new uint[BaseSize * BaseSize];
+ for (int i = 0; i < pixels.Length; i++)
+ {
+ var b = br.ReadByte();
+ if (!half)
+ {
+ pixels[i] = colors[b];
+ }
+ else
+ {
+ pixels[i++] = colors[b & 0xF];
+ pixels[i] = colors[b >> 4];
+ }
+ }
+ return pixels;
+ }
+
+ // todo: move System.Drawing utilization out, make encoding generic for bflim
+ public static byte[] IMGToBCLIM(Image img, char fc)
+ {
+ var mBitmap = new Bitmap(img);
+ var ms = new MemoryStream();
+ int bclimformat = 7; // Init to default (for X)
+
+ if (fc == 'X')
+ {
+ Write16BitColorPalette(mBitmap, ms);
+ }
+ else
+ {
+ bclimformat = Convert.ToInt16(fc.ToString(), 16);
+ try
+ {
+ WriteGeneric(bclimformat, mBitmap, ms);
+ }
+ catch (Exception e)
+ {
+ System.Media.SystemSounds.Beep.Play();
+ System.Diagnostics.Debug.WriteLine(e.ToString());
+ }
+ }
+
+ long datalength = ms.Length;
+ // Write the CLIM + imag data.
+ using (var bw = new BinaryWriter(ms))
+ {
+ bw.Write((uint)0x4D494C43); // CLIM
+ bw.Write((ushort)0xFEFF); // BOM
+ bw.Write((uint)0x14);
+ bw.Write((ushort)0x0202); // 2 2
+ bw.Write((uint)(datalength + 0x28));
+ bw.Write((uint)1);
+ bw.Write((uint)0x67616D69);
+ bw.Write((uint)0x10);
+ bw.Write((ushort)mBitmap.Width);
+ bw.Write((ushort)mBitmap.Height);
+ bw.Write((uint)bclimformat);
+ bw.Write((uint)datalength);
+ }
+ return ms.ToArray();
+ }
+
+ public static byte[] GetBCLIM(string path, char fc)
+ {
+ byte[] byteArray = File.ReadAllBytes(path);
+ using Stream BitmapStream = new MemoryStream(byteArray);
+ Image img = Image.FromStream(BitmapStream);
+ return IMGToBCLIM(img, fc);
+ }
+
+ public static Image MakeBCLIM(string path, char fc)
+ {
+ byte[] bclim = GetBCLIM(path, fc);
+ string fp = Path.GetFileNameWithoutExtension(path);
+ fp = "new_" + fp[(fp.IndexOf('_') + 1)..];
+ string pp = Path.GetDirectoryName(path);
+ string newPath = Path.Combine(pp, fp + ".bclim");
+ File.WriteAllBytes(newPath, bclim);
+
+ return MakeBMP(newPath);
+ }
+
+ public static Image MakeBMP(string path, bool autosave = false, bool crop = true)
+ {
+ BCLIM bclim = Analyze(path);
+ if (bclim.Magic != 0x4D494C43)
+ {
+ System.Media.SystemSounds.Beep.Play();
+ return null;
+ }
+
+ Bitmap img = bclim.GetBitmap(crop);
+ if (img == null)
+ return null;
+ if (crop)
+ img = ImageUtil.CropBMP(bclim, img);
+ if (autosave)
+ img.Save(Path.Combine(bclim.FilePath, $"{bclim.FileName}.png"));
+ return img;
+ }
+
+ // BCLIM Data Writing
+ public static int Write16BitColorPalette(Bitmap img, MemoryStream ms)
+ {
+ using var pixelcolors = new MemoryStream();
+ using var bz = new BinaryWriter(pixelcolors);
+ // Set up our basis.
+ bool under16colors = false;
+ int colors = GetColorCount(img);
+ Color[] pcs = new Color[colors];
+ if (colors < 16) under16colors = true;
+ uint div = 1;
+ if (under16colors)
+ div = 2;
+
+ if (colors > 70) throw new Exception("Too many colors");
+
+ // Set up a new reverse image to build into.
+ int w = XLIMUtil.GreatestCommonMultiple(img.Width, 8);
+ int h = XLIMUtil.GreatestCommonMultiple(img.Height, 8);
+ w = Math.Max(XLIMUtil.NextLargestPow2(w), XLIMUtil.NextLargestPow2(h));
+ h = w;
+ byte[] pixelarray = new byte[w * h];
+
+ const int colorformat = 2;
+ int ctr = 1;
+
+ pcs[0] = Color.FromArgb(0, 0xFF, 0xFF, 0xFF);
+
+ int p = XLIMUtil.GreatestCommonMultiple(w, 8) / 8;
+ if (p == 0) p = 1;
+ int d = 0;
+ for (uint i = 0; i < pixelarray.Length; i++)
+ {
+ d = (int)(i / div);
+ // Get Tile Coordinate
+ XLIMOrienter.DecimalToCartesian(i % 64, out var x, out var y);
+
+ // Get Shift Tile
+ uint tile = i / 64;
+
+ // Shift Tile Coordinate into Tilemap
+ x += (uint)(tile % p) * 8;
+ y += (uint)(tile / p) * 8;
+ if (x >= img.Width || y >= img.Height) // Don't try to access any pixel data outside of our bounds.
+ { i++; continue; } // Goto next tile.
+
+ // Get Color of Pixel
+ Color c = img.GetPixel((int)x, (int)y);
+
+ // Color Table Building Logic
+ int index = Array.IndexOf(pcs, c);
+ if (c.A == 0) index = 0;
+ if (index < 0) // If new color
+ { pcs[ctr] = c; index = ctr; ctr++; } // Add it to color list
+
+ // Add pixel to pixeldata
+ if (under16colors) index <<= 4;
+ pixelarray[i / div] = (byte)index;
+ if (!under16colors) continue;
+
+ c = img.GetPixel((int)x + 1, (int)y);
+ index = Array.IndexOf(pcs, c);
+ if (c.A == 0) index = 0;
+ if (index < 0) // If new color
+ { pcs[ctr] = c; index = ctr; ctr++; }
+ pixelarray[i / div] |= (byte)index;
+ i++;
+ }
+
+ // Write Intro
+ bz.Write((ushort)colorformat); bz.Write((ushort)ctr);
+ // Write Colors
+ for (int i = 0; i < ctr; i++)
+ bz.Write(GetRGBA5551(pcs[i])); // Write byte array.
+ // Write Pixel Data
+ for (uint i = 0; i < d; i++)
+ bz.Write(pixelarray[i]);
+ // Write Padding
+ while (pixelcolors.Length < XLIMUtil.NextLargestPow2((int)pixelcolors.Length))
+ bz.Write((byte)0);
+ // Copy to main CLIM.
+ pixelcolors.Position = 0; pixelcolors.CopyTo(ms);
+ return 7;
+ }
+
+ public static void WriteGeneric(int format, Bitmap img, MemoryStream ms, bool rectangle = true)
+ {
+ var bz = new BinaryWriter(ms); // no using, as we need to reuse ms later.
+ bz.Write(GetPixelData(img, format, rectangle));
+ bz.Flush();
+ }
+
+ public static byte[] MakePixelData(byte[] input, ref int w, ref int h, XLIMOrientation x = XLIMOrientation.None)
+ {
+ int width = w;
+ w = XLIMUtil.NextLargestPow2(w);
+ h = XLIMUtil.NextLargestPow2(h);
+ if (Math.Min(w, h) >= 32)
+ w = h = Math.Max(w, h); // resize
+
+ byte[] pixels = new byte[w * h * 4];
+ var orienter = new XLIMOrienter(w, h, x);
+ for (uint i = 0; i < pixels.Length / 4; i++)
+ {
+ var c = orienter.Get(i);
+ var offset = (c.X * 4) + (c.Y * width);
+ Array.Copy(input, offset, pixels, i * 4, 4);
+ }
+ return pixels;
+ }
+
+ public static byte[] GetPixelData(Bitmap img, int format, bool rectangle = true)
+ {
+ int w = img.Width;
+ int h = img.Height;
+
+ bool perfect = w == h && w != 0 && (w & (w - 1)) == 0;
+ if (!perfect) // Check if square power of two, else resize
+ {
+ // Square Format Checks
+ if (rectangle && Math.Min(img.Width, img.Height) < 32)
+ {
+ w = XLIMUtil.NextLargestPow2(img.Width);
+ h = XLIMUtil.NextLargestPow2(img.Height);
+ }
+ else
+ {
+ w = h = Math.Max(XLIMUtil.NextLargestPow2(w), XLIMUtil.NextLargestPow2(h)); // else resize
+ }
+ }
+
+ using var mz = new MemoryStream();
+ using var bz = new BinaryWriter(mz);
+ int p = XLIMUtil.GreatestCommonMultiple(w, 8) / 8;
+ if (p == 0) p = 1;
+ for (uint i = 0; i < w * h; i++)
+ {
+ XLIMOrienter.DecimalToCartesian(i % 64, out uint x, out uint y);
+
+ // Get Shift Tile
+ uint tile = i / 64;
+
+ // Shift Tile Coordinate into Tilemap
+ x += (uint)(tile % p) * 8;
+ y += (uint)(tile / p) * 8;
+
+ // Don't write data
+ Color c;
+ if (x >= img.Width || y >= img.Height)
+ { c = Color.FromArgb(0, 0, 0, 0); }
+ else
+ { c = img.GetPixel((int)x, (int)y); if (c.A == 0) c = Color.FromArgb(0, 86, 86, 86); }
+
+ switch (format)
+ {
+ case 0: bz.Write(GetL8(c)); break; // L8
+ case 1: bz.Write(GetA8(c)); break; // A8
+ case 2: bz.Write(GetLA4(c)); break; // LA4(4)
+ case 3: bz.Write(GetLA8(c)); break; // LA8(8)
+ case 4: bz.Write(GetHILO8(c)); break; // HILO8
+ case 5: bz.Write(GetRGB565(c)); break; // RGB565
+ case 6:
+ {
+ bz.Write(c.B);
+ bz.Write(c.G);
+ bz.Write(c.R); break;
+ }
+ case 7: bz.Write(GetRGBA5551(c)); break; // RGBA5551
+ case 8: bz.Write(GetRGBA4444(c)); break; // RGBA4444
+ case 9: bz.Write(GetRGBA8888(c)); break; // RGBA8
+ case 10: throw new Exception("ETC1 not supported.");
+ case 11: throw new Exception("ETC1A4 not supported.");
+ case 12:
+ {
+ byte val = (byte)(GetL8(c) / 0x11); // First Pix // L4
+ { c = img.GetPixel((int)x, (int)y); if (c.A == 0) c = Color.FromArgb(0, 0, 0, 0); }
+ val |= (byte)((GetL8(c) / 0x11) << 4); i++;
+ bz.Write(val); break;
+ }
+ case 13:
+ {
+ byte val = (byte)(GetA8(c) / 0x11); // First Pix // L4
+ { c = img.GetPixel((int)x, (int)y); }
+ val |= (byte)((GetA8(c) / 0x11) << 4); i++;
+ bz.Write(val); break;
+ }
+ }
+ }
+ if (!perfect)
+ {
+ while (mz.Length < XLIMUtil.NextLargestPow2((int)mz.Length)) // pad
+ bz.Write((byte)0);
+ }
+
+ return mz.ToArray();
+ }
+
+ public static int GetColorCount(Bitmap img)
+ {
+ Color[] colors = new Color[img.Width * img.Height];
+ int colorct = 1;
+
+ for (int i = 0; i < colors.Length; i++)
+ {
+ Color c = img.GetPixel(i % img.Width, i / img.Width);
+ int index = Array.IndexOf(colors, c);
+ if (c.A == 0) index = 0;
+ if (index >= 0) continue;
+
+ colors[colorct] = c;
+ colorct++;
+ }
+ return colorct;
+ }
+
+ // Color Conversion
+ internal static byte GetL8(Color c)
+ {
+ byte red = c.R;
+ byte green = c.G;
+ byte blue = c.B;
+ // Luma (Y’) = 0.299 R’ + 0.587 G’ + 0.114 B’ from wikipedia
+ return (byte)((((0x4CB2 * red) + (0x9691 * green) + (0x1D3E * blue)) >> 16) & 0xFF);
+ } // L8
+
+ internal static byte GetA8(Color c)
+ {
+ return c.A;
+ } // A8
+
+ internal static byte GetLA4(Color c)
+ {
+ return (byte)((c.A / 0x11) + (c.R / 0x11) << 4);
+ } // LA4
+
+ internal static ushort GetLA8(Color c)
+ {
+ return (ushort)(c.A + (c.R << 8));
+ } // LA8
+
+ internal static ushort GetHILO8(Color c)
+ {
+ return (ushort)(c.G + (c.R << 8));
+ } // HILO8
+
+ internal static ushort GetRGB565(Color c)
+ {
+ int val = 0;
+ // val += c.A >> 8; // unused
+ val += Convert8to5(c.B) >> 3;
+ val += (c.G >> 2) << 5;
+ val += Convert8to5(c.R) << 10;
+ return (ushort)val;
+ } // RGB565
+ // RGB8
+ internal static ushort GetRGBA5551(Color c)
+ {
+ int val = 0;
+ val += c.A > 0x80 ? 1 : 0;
+ val += Convert8to5(c.R) << 11;
+ val += Convert8to5(c.G) << 6;
+ val += Convert8to5(c.B) << 1;
+ ushort v = (ushort)val;
+
+ return v;
+ }// RGBA5551
+
+ internal static ushort GetRGBA4444(Color c)
+ {
+ int val = 0;
+ val += c.A / 0x11;
+ val += (c.B / 0x11) << 4;
+ val += (c.G / 0x11) << 8;
+ val += (c.R / 0x11) << 12;
+ return (ushort)val;
+ }// RGBA4444
+
+ internal static uint GetRGBA8888(Color c) // RGBA8888
+ {
+ uint val = 0;
+ val += c.A;
+ val += (uint)(c.B << 8);
+ val += (uint)(c.G << 16);
+ val += (uint)(c.R << 24);
+ return val;
+ }
+
+ // Unit Conversion
+ internal static byte Convert8to5(int colorval)
+ {
+ byte[] Convert8to5 =
+ [
+ 0x00,0x08,0x10,0x18,0x20,0x29,0x31,0x39,
+ 0x41,0x4A,0x52,0x5A,0x62,0x6A,0x73,0x7B,
+ 0x83,0x8B,0x94,0x9C,0xA4,0xAC,0xB4,0xBD,
+ 0xC5,0xCD,0xD5,0xDE,0xE6,0xEE,0xF6,0xFF,
+ ];
+ byte i = 0;
+ while (colorval > Convert8to5[i]) i++;
+ return i;
+ }
+
+ public static BCLIM Analyze(byte[] data, string shortPath)
+ {
+ var bclim = new BCLIM(data)
+ {
+ FileName = Path.GetFileNameWithoutExtension(shortPath),
+ FilePath = Path.GetDirectoryName(shortPath),
+ Extension = Path.GetExtension(shortPath),
+ };
+ return bclim;
+ }
+
+ public static BCLIM Analyze(string path)
+ {
+ byte[] data = File.ReadAllBytes(path);
+ return Analyze(data, path);
+ }
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/Images/BFLIM.cs b/pk3DS.Core/CTR/Images/BFLIM.cs
new file mode 100644
index 0000000000..74ebb479da
--- /dev/null
+++ b/pk3DS.Core/CTR/Images/BFLIM.cs
@@ -0,0 +1,31 @@
+using System.IO;
+using pk3DS.Core.CTR.Images;
+
+namespace pk3DS.Core.CTR;
+
+public class BFLIM : BXLIM
+{
+ public BFLIM(Stream data) => ReadBFLIM(data);
+
+ public BFLIM(byte[] data)
+ {
+ using var ms = new MemoryStream(data);
+ ReadBFLIM(ms);
+ }
+
+ public BFLIM(string path)
+ {
+ var data = File.ReadAllBytes(path);
+ using var ms = new MemoryStream(data);
+ ReadBFLIM(ms);
+ }
+
+ private void ReadBFLIM(Stream ms)
+ {
+ PixelData = new byte[ms.Length - FLIMHeader.SIZE];
+ ms.Read(PixelData, 0, PixelData.Length);
+ var footer = new byte[FLIMHeader.SIZE];
+ ms.Read(footer, 0, footer.Length);
+ Footer = footer.ToStructure();
+ }
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/Images/BXLIM.cs b/pk3DS.Core/CTR/Images/BXLIM.cs
new file mode 100644
index 0000000000..93f0b9628c
--- /dev/null
+++ b/pk3DS.Core/CTR/Images/BXLIM.cs
@@ -0,0 +1,67 @@
+using System;
+using System.Linq;
+
+namespace pk3DS.Core.CTR.Images;
+
+public abstract class BXLIM : IXLIMHeader
+{
+ public byte[] PixelData;
+ public IXLIMHeader Footer { get; protected set; }
+
+ public uint Magic { get => Footer.Magic; set => Footer.Magic = value; }
+ public ushort Width { get => Footer.Width; set => Footer.Width = value; }
+ public ushort Height { get => Footer.Height; set => Footer.Height = value; }
+ public XLIMEncoding Format { get => Footer.Format; set => Footer.Format = value; }
+ public XLIMOrientation Orientation { get => Footer.Orientation; set => Footer.Orientation = value; }
+ public bool Valid => Footer.Valid && PixelData != null;
+
+ public string FileName { get; set; }
+ public string FilePath { get; set; }
+ public string Extension { get; set; }
+ public int BaseSize => Math.Max(XLIMUtil.NextLargestPow2(Width), XLIMUtil.NextLargestPow2(Height));
+
+ ///
+ /// ARGB 32bpp
+ ///
+ public byte[] GetImageData(bool crop = true)
+ {
+ var orienter = new XLIMOrienter(Footer.Width, Footer.Height, Footer.Orientation);
+ uint[] pixels = GetPixels();
+
+ if (!crop)
+ {
+ Footer.Width = (ushort)orienter.Width;
+ Footer.Height = (ushort)orienter.Height;
+ }
+
+ // uint[] -> byte[]
+ byte[] array = new byte[Footer.Width * Footer.Height * 4];
+ for (uint i = 0; i < pixels.Length; i++)
+ {
+ var coord = orienter.Get(i);
+ if (coord.X >= Footer.Width || coord.Y >= Footer.Height)
+ continue;
+
+ var val = pixels[i];
+ uint o = 4 * (coord.X + (coord.Y * Footer.Width));
+ array[o + 0] = (byte)(val & 0xFF);
+ array[o + 1] = (byte)(val >> 8 & 0xFF);
+ array[o + 2] = (byte)(val >> 16 & 0xFF);
+ array[o + 3] = (byte)(val >> 24 & 0xFF);
+ }
+ return array;
+ }
+
+ public virtual uint[] GetPixels()
+ {
+ return PixelConverter.GetPixels(PixelData, Footer.Format).ToArray();
+ }
+
+ public byte[] GetPixelsRaw()
+ {
+ var pix = GetPixels();
+ byte[] raw = new byte[pix.Length * 4];
+ Buffer.BlockCopy(pix, 0, raw, 0, raw.Length);
+ return raw;
+ }
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/Images/CLIMHeader.cs b/pk3DS.Core/CTR/Images/CLIMHeader.cs
new file mode 100644
index 0000000000..2549e14656
--- /dev/null
+++ b/pk3DS.Core/CTR/Images/CLIMHeader.cs
@@ -0,0 +1,30 @@
+using System.Runtime.InteropServices;
+
+namespace pk3DS.Core.CTR;
+
+[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
+public struct CLIMHeader : IXLIMHeader
+{
+ public const int SIZE = 40;
+ public const string Identifier = "CLIM";
+ public readonly bool Valid => LittleEndian && Magic == 0x4D_49_4C_43; // CLIM
+ public readonly bool LittleEndian => BOM == 0xFEFF;
+ public readonly bool BigEndian => BOM == 0xFFFE;
+
+ public uint Magic { get; set; }// CLIM = 0x4D494C43
+ public ushort BOM; // 0xFFFE
+ public uint HeaderLength; // always 0x14
+ public byte TileWidth; // 1<<[[n]]
+ public byte TileHeight; // 1<<[[n]]
+ public uint totalLength; // Total Length of file
+ public uint Count; // "1" , guessing it's just Count.
+
+ public uint imag; // imag = 0x67616D69
+ public uint imagLength; // HeaderLength - 10
+ public ushort Width { get; set; } // Final Dimensions
+ public ushort Height { get; set; } // Final Dimensions
+ public XLIMEncoding Format { get; set; }
+ public XLIMOrientation Orientation { get; set; } // unused
+ public short Alignment; // unused
+ public uint DataSize; // Pixel Data Region Length
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/Images/Coordinate.cs b/pk3DS.Core/CTR/Images/Coordinate.cs
new file mode 100644
index 0000000000..e871d51565
--- /dev/null
+++ b/pk3DS.Core/CTR/Images/Coordinate.cs
@@ -0,0 +1,16 @@
+namespace pk3DS.Core.CTR;
+
+public struct Coordinate(uint x, uint y)
+{
+ public uint X { get; private set; } = x;
+ public uint Y { get; private set; } = y;
+
+ public void Transpose() => (X, Y) = (Y, X);
+
+ public void Rotate90(uint height)
+ {
+ var tmp = X;
+ X = Y;
+ Y = height - 1 - tmp;
+ }
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/Images/FLIMHeader.cs b/pk3DS.Core/CTR/Images/FLIMHeader.cs
new file mode 100644
index 0000000000..e32024fc6b
--- /dev/null
+++ b/pk3DS.Core/CTR/Images/FLIMHeader.cs
@@ -0,0 +1,29 @@
+using System.Runtime.InteropServices;
+
+namespace pk3DS.Core.CTR;
+
+[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
+public struct FLIMHeader : IXLIMHeader
+{
+ public const int SIZE = 40;
+ public const string Identifier = "FLIM";
+ public readonly bool Valid => LittleEndian && Magic == 0x4D_49_4C_46; // FLIM
+ public readonly bool LittleEndian => BOM == 0xFEFF;
+ public readonly bool BigEndian => BOM == 0xFFFE;
+
+ public uint Magic { get; set; } // FLIM
+ public ushort BOM; // 0xFFFE
+ public ushort HeaderLength; // always 0x14
+ public int Version;
+ public uint TotalLength;
+ public uint Count;
+
+ public uint imag; // imag = 67616D69
+ public uint imagLength; // always 0x10
+ public ushort Width { get; set; }
+ public ushort Height { get; set; }
+ public short Alignment;
+ public XLIMEncoding Format { get; set; }
+ public XLIMOrientation Orientation { get; set; }
+ public uint DataSize;
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/Images/IXLIMHeader.cs b/pk3DS.Core/CTR/Images/IXLIMHeader.cs
new file mode 100644
index 0000000000..f7d1d59197
--- /dev/null
+++ b/pk3DS.Core/CTR/Images/IXLIMHeader.cs
@@ -0,0 +1,15 @@
+namespace pk3DS.Core.CTR;
+
+///
+/// and header interface.
+///
+public interface IXLIMHeader
+{
+ uint Magic { get; set; }
+ ushort Width { get; set; }
+ ushort Height { get; set; }
+ XLIMEncoding Format { get; set; }
+ XLIMOrientation Orientation { get; set; }
+
+ bool Valid { get; }
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/Images/PixelConverter.cs b/pk3DS.Core/CTR/Images/PixelConverter.cs
new file mode 100644
index 0000000000..7d5e599ba6
--- /dev/null
+++ b/pk3DS.Core/CTR/Images/PixelConverter.cs
@@ -0,0 +1,175 @@
+using System;
+using System.Collections.Generic;
+
+namespace pk3DS.Core.CTR;
+
+public static class PixelConverter
+{
+ private const int BPP_32 = 32;
+ private const int BPP_24 = 24;
+ private const int BPP_16 = 16;
+ private const int BPP_8 = 8;
+ private const int BPP_4 = 4;
+
+ internal static readonly byte[] Convert5To8 =
+ [
+ 0x00,0x08,0x10,0x18,0x20,0x29,0x31,0x39,
+ 0x41,0x4A,0x52,0x5A,0x62,0x6A,0x73,0x7B,
+ 0x83,0x8B,0x94,0x9C,0xA4,0xAC,0xB4,0xBD,
+ 0xC5,0xCD,0xD5,0xDE,0xE6,0xEE,0xF6,0xFF,
+ ];
+
+ public static IEnumerable GetPixels(byte[] raw, XLIMEncoding e)
+ {
+ int bpp = e.GetBitsPerPixel();
+ if (bpp == BPP_4)
+ {
+ foreach (byte b in raw)
+ {
+ byte _0 = (byte)(b & 0xF);
+ byte _1 = (byte)(b >> 4);
+ yield return GetDecodedPixelValue(_0, e);
+ yield return GetDecodedPixelValue(_1, e);
+ }
+ yield break;
+ }
+
+ for (int i = 0; i < raw.Length; i += bpp / 8)
+ {
+ uint val = GetEncodedPixelValue(raw, i, bpp);
+ yield return GetDecodedPixelValue(val, e);
+ }
+ }
+
+ internal static uint GetDecodedPixelValue(uint val, XLIMEncoding e)
+ {
+ byte a = byte.MaxValue, r, g, b;
+ switch (e)
+ {
+ case XLIMEncoding.L4:
+ case XLIMEncoding.L8:
+ {
+ r = g = b = (byte)val;
+ break;
+ }
+ case XLIMEncoding.A4:
+ case XLIMEncoding.A8:
+ {
+ r = g = b = 0xFF;
+ a = (byte)val;
+ break;
+ }
+ case XLIMEncoding.HILO8:
+ {
+ r = (byte)(val >> 8);
+ g = (byte)(val & 0xFF);
+ b = byte.MaxValue;
+ break;
+ }
+ case XLIMEncoding.LA4:
+ {
+ r = g = b = (byte)(val >> 4);
+ a = (byte)(val & 0x0F);
+ break;
+ }
+ case XLIMEncoding.LA8:
+ {
+ r = g = b = (byte)(val >> 8);
+ a = (byte)val;
+ break;
+ }
+ case XLIMEncoding.RGBX8:
+ {
+ r = (byte)(val >> 16);
+ g = (byte)(val >> 8);
+ b = (byte)(val >> 0);
+ break;
+ }
+ case XLIMEncoding.RGBA8:
+ {
+ r = (byte)(val >> 24);
+ g = (byte)(val >> 16);
+ b = (byte)(val >> 8);
+ a = (byte)val;
+ break;
+ }
+ case XLIMEncoding.RGBA4:
+ {
+ a = (byte)(0x11 * (val & 0xf));
+ r = (byte)(0x11 * ((val >> 12) & 0xf));
+ g = (byte)(0x11 * ((val >> 8) & 0xf));
+ b = (byte)(0x11 * ((val >> 4) & 0xf));
+ break;
+ }
+ case XLIMEncoding.RGB565:
+ {
+ r = Convert5To8[(val >> 11) & 0x1F];
+ g = (byte)(((val >> 5) & 0x3F) * 4);
+ b = Convert5To8[val & 0x1F];
+ break;
+ }
+ case XLIMEncoding.RGB5A1:
+ {
+ r = Convert5To8[(val >> 11) & 0x1F];
+ g = Convert5To8[(val >> 6) & 0x1F];
+ b = Convert5To8[(val >> 1) & 0x1F];
+ a = (val & 1) == 1 ? byte.MaxValue : byte.MinValue;
+ break;
+ }
+ default:
+ throw new FormatException($"Unsupported {nameof(XLIMEncoding)} value = {e}");
+ }
+ return (uint)((a << 24) | (r << 16) | (g << 8) | b);
+ }
+
+ public static uint GetEncodedPixelValue(byte[] raw, int offset, int size)
+ {
+ return size switch
+ {
+ BPP_32 => BitConverter.ToUInt32(raw, offset),
+ BPP_24 => BitConverter.ToUInt32(raw, offset) & 0x00FFFFFF,
+ BPP_16 => BitConverter.ToUInt16(raw, offset),
+ _ => raw[offset],
+ };
+ }
+
+ public static int GetBitsPerPixel(this XLIMEncoding e)
+ {
+ if (_32.Contains(e))
+ return BPP_32;
+ if (_24.Contains(e))
+ return BPP_24;
+ if (_16.Contains(e))
+ return BPP_16;
+ if (_8.Contains(e))
+ return BPP_8;
+ return BPP_4;
+ }
+
+ private static readonly HashSet _32 =
+ [
+ XLIMEncoding.RGBA8,
+ ];
+
+ private static readonly HashSet _24 =
+ [
+ XLIMEncoding.RGBX8,
+ ];
+
+ private static readonly HashSet _16 =
+ [
+ XLIMEncoding.LA8,
+ XLIMEncoding.HILO8,
+ XLIMEncoding.RGB565,
+ XLIMEncoding.RGB5A1,
+ XLIMEncoding.RGBA4,
+ ];
+
+ private static readonly HashSet _8 =
+ [
+ XLIMEncoding.L8,
+ XLIMEncoding.A8,
+ XLIMEncoding.LA4,
+ XLIMEncoding.ETC1A4,
+ ];
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/Images/XLIMEncoding.cs b/pk3DS.Core/CTR/Images/XLIMEncoding.cs
new file mode 100644
index 0000000000..b647f2ca24
--- /dev/null
+++ b/pk3DS.Core/CTR/Images/XLIMEncoding.cs
@@ -0,0 +1,19 @@
+namespace pk3DS.Core.CTR;
+
+public enum XLIMEncoding : byte
+{
+ L8 = 0x00, // 8 Luminance
+ A8 = 0x01, // 8 Alpha
+ LA4 = 0x02, // 8 Luminance + Alpha
+ LA8 = 0x03, // 16 Luminance + Alpha
+ HILO8 = 0x04, // 16 ?
+ RGB565 = 0x05, // 16 Color
+ RGBX8 = 0x06, // 24 Color
+ RGB5A1 = 0x07, // 16 Color + Alpha
+ RGBA4 = 0x08, // 16 Color + Alpha
+ RGBA8 = 0x09, // 32 Color + Alpha
+ ETC1 = 0x0A, // 4 Color
+ ETC1A4 = 0x0B, // 8 Color + Alpha
+ L4 = 0x0C, // 4 Luminance
+ A4 = 0x0D, // 4 Alpha
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/Images/XLIMOrientation.cs b/pk3DS.Core/CTR/Images/XLIMOrientation.cs
new file mode 100644
index 0000000000..d20801e876
--- /dev/null
+++ b/pk3DS.Core/CTR/Images/XLIMOrientation.cs
@@ -0,0 +1,19 @@
+using System;
+
+namespace pk3DS.Core.CTR;
+
+[Flags]
+public enum XLIMOrientation : byte
+{
+ None = 0,
+ Rotate90 = 4,
+ Transpose = 8,
+}
+
+public static class XlimOrientationExtensions
+{
+ public static bool HasFlagFast(this XLIMOrientation value, XLIMOrientation flag)
+ {
+ return (value & flag) != 0;
+ }
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/Images/XLIMOrienter.cs b/pk3DS.Core/CTR/Images/XLIMOrienter.cs
new file mode 100644
index 0000000000..f67fb39b1f
--- /dev/null
+++ b/pk3DS.Core/CTR/Images/XLIMOrienter.cs
@@ -0,0 +1,111 @@
+using static pk3DS.Core.CTR.Images.XLIMUtil;
+
+namespace pk3DS.Core.CTR;
+
+public class XLIMOrienter
+{
+ private readonly XLIMOrientation _orientation;
+
+ public uint Width { get; }
+ public uint Height { get; }
+ public uint PanelsPerWidth { get; }
+
+ public XLIMOrienter(int width, int height, XLIMOrientation orientation)
+ {
+ Width = (uint)NextLargestPow2(GreatestCommonMultiple(width, 8));
+ Height = (uint)NextLargestPow2(GreatestCommonMultiple(height, 8));
+
+ uint stride = orientation == XLIMOrientation.None ? Width : Height;
+ PanelsPerWidth = (uint)GreatestCommonMultiple((int)stride, 8) / 8;
+
+ _orientation = orientation;
+ }
+
+ public Coordinate Get(uint i)
+ {
+ DecimalToCartesian(i & 0x3F, out uint x, out uint y);
+
+ // Shift Tile Coordinate into Tilemap
+ var tile = i >> 6;
+ x |= (tile % PanelsPerWidth) << 3;
+ y |= (tile / PanelsPerWidth) << 3;
+
+ var coord = new Coordinate(x, y);
+ if (_orientation.HasFlagFast(XLIMOrientation.Rotate90))
+ coord.Rotate90(Height);
+ if (_orientation.HasFlagFast(XLIMOrientation.Transpose))
+ coord.Transpose();
+ return coord;
+ }
+
+ internal static uint C11(uint x)
+ {
+ x &= 0x55555555; // x = -f-e -d-c -b-a -9-8 -7-6 -5-4 -3-2 -1-0
+ x = (x ^ (x >> 1)) & 0x33333333; // x = --fe --dc --ba --98 --76 --54 --32 --10
+ x = (x ^ (x >> 2)) & 0x0f0f0f0f; // x = ---- fedc ---- ba98 ---- 7654 ---- 3210
+ x = (x ^ (x >> 4)) & 0x00ff00ff; // x = ---- ---- fedc ba98 ---- ---- 7654 3210
+ x = (x ^ (x >> 8)) & 0x0000ffff; // x = ---- ---- ---- ---- fedc ba98 7654 3210
+ return x;
+ }
+
+ // Morton Translation
+
+ ///
+ /// Combines X/Y Coordinates to a decimal ordinate.
+ ///
+ ///
+ ///
+ ///
+ internal static uint CartesianToDecimal(uint x, uint y)
+ {
+ x &= 0x0000ffff;
+ y &= 0x0000ffff;
+ x |= x << 8;
+ y |= y << 8;
+ x &= 0x00ff00ff;
+ y &= 0x00ff00ff;
+ x |= x << 4;
+ y |= y << 4;
+ x &= 0x0f0f0f0f;
+ y &= 0x0f0f0f0f;
+ x |= x << 2;
+ y |= y << 2;
+ x &= 0x33333333;
+ y &= 0x33333333;
+ x |= x << 1;
+ y |= y << 1;
+ x &= 0x55555555;
+ y &= 0x55555555;
+ return x | (y << 1);
+ }
+
+ ///
+ /// Decimal Ordinate In to X / Y Coordinate Out
+ ///
+ /// Loop integer which will be decoded to X/Y
+ /// Output X coordinate
+ /// Output Y coordinate
+ internal static void DecimalToCartesian(uint d, out uint x, out uint y)
+ {
+ x = d;
+ y = x >> 1;
+ x &= 0x55555555;
+ y &= 0x55555555;
+ x |= x >> 1;
+ y |= y >> 1;
+ x &= 0x33333333;
+ y &= 0x33333333;
+ x |= x >> 2;
+ y |= y >> 2;
+ x &= 0x0f0f0f0f;
+ y &= 0x0f0f0f0f;
+ x |= x >> 4;
+ y |= y >> 4;
+ x &= 0x00ff00ff;
+ y &= 0x00ff00ff;
+ x |= x >> 8;
+ y |= y >> 8;
+ x &= 0x0000ffff;
+ y &= 0x0000ffff;
+ }
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/Images/XLIMUtil.cs b/pk3DS.Core/CTR/Images/XLIMUtil.cs
new file mode 100644
index 0000000000..1091473f22
--- /dev/null
+++ b/pk3DS.Core/CTR/Images/XLIMUtil.cs
@@ -0,0 +1,31 @@
+namespace pk3DS.Core.CTR.Images;
+
+public static class XLIMUtil
+{
+ ///
+ /// Greatest common multiple (to round up)
+ ///
+ /// Number to round-up.
+ /// Multiple to round-up to.
+ /// Rounded up number.
+ internal static int GreatestCommonMultiple(int n, int m)
+ {
+ return (n + m - 1) / m * m;
+ }
+
+ ///
+ /// Next Largest Power of 2
+ ///
+ /// Input to round up to next 2^n
+ /// 2^n > x && x > 2^(n-1)
+ internal static int NextLargestPow2(int x)
+ {
+ x--; // comment out to always take the next biggest power of two, even if x is already a power of two
+ x |= x >> 1;
+ x |= x >> 2;
+ x |= x >> 4;
+ x |= x >> 8;
+ x |= x >> 16;
+ return x + 1;
+ }
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/LZSS.cs b/pk3DS.Core/CTR/LZSS.cs
index b81b5e53dc..73a1db0a7f 100644
--- a/pk3DS.Core/CTR/LZSS.cs
+++ b/pk3DS.Core/CTR/LZSS.cs
@@ -1,772 +1,833 @@
using System;
using System.IO;
-namespace pk3DS.Core.CTR
+namespace pk3DS.Core.CTR;
+
+// LZSS (de)compression, heavily taken from dsdecmp
+public static class LZSS
{
- // LZSS (de)compression, heavily taken from dsdecmp
- public static class LZSS
+ public static long Decompress(string infile, string outfile)
{
- public static long Decompress(string infile, string outfile)
+ // make sure the output directory exists
+ string outDirectory = Path.GetDirectoryName(outfile);
+ if (!Directory.Exists(outDirectory))
+ Directory.CreateDirectory(outDirectory);
+ // open the two given files, and delegate to the format-specific code.
+ using FileStream inStream = new(infile, FileMode.Open),
+ outStream = new(outfile, FileMode.Create);
+ return Decompress(inStream, inStream.Length, outStream);
+ }
+
+ ///
+ /// Decompresses the given stream, writing the decompressed data to the given output stream.
+ /// Assumes Supports(instream) returns true.
+ /// After this call, the input stream will be positioned at the end of the compressed stream,
+ /// or at the initial position + inLength, whichever comes first.
+ ///
+ /// The stream to decompress. At the end of this method, the position
+ /// of this stream is directly after the compressed data.
+ /// The length of the input data. Not necessarily all of the
+ /// input data may be read (if there is padding, for example), however never more than
+ /// this number of bytes is read from the input stream.
+ /// The stream to write the decompressed data to.
+ /// The length of the output data.
+ /// When the given length of the input data
+ /// is not enough to properly decompress the input.
+ public static long Decompress(Stream instream, long inLength, Stream outstream)
+ {
+ #region Format definition in NDSTEK style
+ /* Data header (32bit)
+ Bit 0-3 Reserved
+ Bit 4-7 Compressed type (must be 1 for LZ77)
+ Bit 8-31 Size of decompressed data. if 0, the next 4 bytes are decompressed length
+ Repeat below. Each Flag Byte followed by eight Blocks.
+ Flag data (8bit)
+ Bit 0-7 Type Flags for next 8 Blocks, MSB first
+ Block Type 0 - Uncompressed - Copy 1 Byte from Source to Dest
+ Bit 0-7 One data byte to be copied to dest
+ Block Type 1 - Compressed - Copy LEN Bytes from Dest-Disp-1 to Dest
+ If Reserved is 0: - Default
+ Bit 0-3 Disp MSBs
+ Bit 4-7 LEN - 3
+ Bit 8-15 Disp LSBs
+ If Reserved is 1: - Higher compression rates for files with (lots of) long repetitions
+ Bit 4-7 Indicator
+ If Indicator > 1:
+ Bit 0-3 Disp MSBs
+ Bit 4-7 LEN - 1 (same bits as Indicator)
+ Bit 8-15 Disp LSBs
+ If Indicator is 1: A(B CD E)(F GH)
+ Bit 0-3 (LEN - 0x111) MSBs
+ Bit 4-7 Indicator; unused
+ Bit 8-15 (LEN- 0x111) 'middle'-SBs
+ Bit 16-19 Disp MSBs
+ Bit 20-23 (LEN - 0x111) LSBs
+ Bit 24-31 Disp LSBs
+ If Indicator is 0:
+ Bit 0-3 (LEN - 0x11) MSBs
+ Bit 4-7 Indicator; unused
+ Bit 8-11 Disp MSBs
+ Bit 12-15 (LEN - 0x11) LSBs
+ Bit 16-23 Disp LSBs
+ */
+ #endregion
+
+ long readBytes = 0;
+
+ byte type = (byte)instream.ReadByte();
+ if (type != 0x11)
+ throw new InvalidDataException($"The provided stream is not a valid LZ-0x11 compressed stream (invalid type 0x{type:X})");
+ byte[] sizeBytes = new byte[3];
+ instream.Read(sizeBytes, 0, 3);
+ int decompressedSize = IOUtils.ToNDSu24(sizeBytes, 0);
+ readBytes += 4;
+ if (decompressedSize == 0)
{
- // make sure the output directory exists
- string outDirectory = Path.GetDirectoryName(outfile);
- if (!Directory.Exists(outDirectory))
- Directory.CreateDirectory(outDirectory);
- // open the two given files, and delegate to the format-specific code.
- using (FileStream inStream = new FileStream(infile, FileMode.Open),
- outStream = new FileStream(outfile, FileMode.Create))
- {
- return Decompress(inStream, inStream.Length, outStream);
- }
+ sizeBytes = new byte[4];
+ instream.Read(sizeBytes, 0, 4);
+ decompressedSize = IOUtils.ToNDSs32(sizeBytes, 0);
+ readBytes += 4;
}
- ///
- /// Decompresses the given stream, writing the decompressed data to the given output stream.
- /// Assumes Supports(instream) returns true.
- /// After this call, the input stream will be positioned at the end of the compressed stream,
- /// or at the initial position + inLength, whichever comes first.
- ///
- /// The stream to decompress. At the end of this method, the position
- /// of this stream is directly after the compressed data.
- /// The length of the input data. Not necessarily all of the
- /// input data may be read (if there is padding, for example), however never more than
- /// this number of bytes is read from the input stream.
- /// The stream to write the decompressed data to.
- /// The length of the output data.
- /// When the given length of the input data
- /// is not enough to properly decompress the input.
- public static long Decompress(Stream instream, long inLength, Stream outstream)
- {
- #region Format definition in NDSTEK style
- /* Data header (32bit)
- Bit 0-3 Reserved
- Bit 4-7 Compressed type (must be 1 for LZ77)
- Bit 8-31 Size of decompressed data. if 0, the next 4 bytes are decompressed length
- Repeat below. Each Flag Byte followed by eight Blocks.
- Flag data (8bit)
- Bit 0-7 Type Flags for next 8 Blocks, MSB first
- Block Type 0 - Uncompressed - Copy 1 Byte from Source to Dest
- Bit 0-7 One data byte to be copied to dest
- Block Type 1 - Compressed - Copy LEN Bytes from Dest-Disp-1 to Dest
- If Reserved is 0: - Default
- Bit 0-3 Disp MSBs
- Bit 4-7 LEN - 3
- Bit 8-15 Disp LSBs
- If Reserved is 1: - Higher compression rates for files with (lots of) long repetitions
- Bit 4-7 Indicator
- If Indicator > 1:
- Bit 0-3 Disp MSBs
- Bit 4-7 LEN - 1 (same bits as Indicator)
- Bit 8-15 Disp LSBs
- If Indicator is 1: A(B CD E)(F GH)
- Bit 0-3 (LEN - 0x111) MSBs
- Bit 4-7 Indicator; unused
- Bit 8-15 (LEN- 0x111) 'middle'-SBs
- Bit 16-19 Disp MSBs
- Bit 20-23 (LEN - 0x111) LSBs
- Bit 24-31 Disp LSBs
- If Indicator is 0:
- Bit 0-3 (LEN - 0x11) MSBs
- Bit 4-7 Indicator; unused
- Bit 8-11 Disp MSBs
- Bit 12-15 (LEN - 0x11) LSBs
- Bit 16-23 Disp LSBs
- */
- #endregion
- long readBytes = 0;
+ // the maximum 'DISP-1' is still 0xFFF.
+ const int bufferLength = 0x1000;
+ byte[] buffer = new byte[bufferLength];
+ int bufferOffset = 0;
- byte type = (byte)instream.ReadByte();
- if (type != 0x11)
- throw new InvalidDataException("The provided stream is not a valid LZ-0x11 "
- + "compressed stream (invalid type 0x" + type.ToString("X") + ")");
- byte[] sizeBytes = new byte[3];
- instream.Read(sizeBytes, 0, 3);
- int decompressedSize = IOUtils.ToNDSu24(sizeBytes, 0);
- readBytes += 4;
- if (decompressedSize == 0)
+ int currentOutSize = 0;
+ int flags = 0, mask = 1;
+ while (currentOutSize < decompressedSize)
+ {
+ // (throws when requested new flags byte is not available)
+ #region Update the mask. If all flag bits have been read, get a new set.
+ // the current mask is the mask used in the previous run. So if it masks the
+ // last flag bit, get a new flags byte.
+ if (mask == 1)
{
- sizeBytes = new byte[4];
- instream.Read(sizeBytes, 0, 4);
- decompressedSize = IOUtils.ToNDSs32(sizeBytes, 0);
- readBytes += 4;
+ if (readBytes >= inLength)
+ throw new NotEnoughDataException(currentOutSize, decompressedSize);
+ flags = instream.ReadByte(); readBytes++;
+ if (flags < 0)
+ throw new StreamTooShortException();
+ mask = 0x80;
}
+ else
+ {
+ mask >>= 1;
+ }
+ #endregion
- // the maximum 'DISP-1' is still 0xFFF.
- const int bufferLength = 0x1000;
- byte[] buffer = new byte[bufferLength];
- int bufferOffset = 0;
-
- int currentOutSize = 0;
- int flags = 0, mask = 1;
- while (currentOutSize < decompressedSize)
+ // bit = 1 <=> compressed.
+ if ((flags & mask) > 0)
{
- // (throws when requested new flags byte is not available)
- #region Update the mask. If all flag bits have been read, get a new set.
- // the current mask is the mask used in the previous run. So if it masks the
- // last flag bit, get a new flags byte.
- if (mask == 1)
- {
- if (readBytes >= inLength)
- throw new NotEnoughDataException(currentOutSize, decompressedSize);
- flags = instream.ReadByte(); readBytes++;
- if (flags < 0)
- throw new StreamTooShortException();
- mask = 0x80;
- }
- else
+ // (throws when not enough bytes are available)
+ #region Get length and displacement('disp') values from next 2, 3 or 4 bytes
+
+ // read the first byte first, which also signals the size of the compressed block
+ if (readBytes >= inLength)
+ throw new NotEnoughDataException(currentOutSize, decompressedSize);
+ int byte1 = instream.ReadByte(); readBytes++;
+ if (byte1 < 0)
+ throw new StreamTooShortException();
+
+ int length = byte1 >> 4;
+ int disp;
+ if (length == 0)
{
- mask >>= 1;
- }
- #endregion
+ #region case 0; 0(B C)(D EF) + (0x11)(0x1) = (LEN)(DISP)
- // bit = 1 <=> compressed.
- if ((flags & mask) > 0)
- {
- // (throws when not enough bytes are available)
- #region Get length and displacement('disp') values from next 2, 3 or 4 bytes
+ // case 0:
+ // data = AB CD EF (with A=0)
+ // LEN = ABC + 0x11 == BC + 0x11
+ // DISP = DEF + 1
- // read the first byte first, which also signals the size of the compressed block
- if (readBytes >= inLength)
+ // we need two more bytes available
+ if (readBytes + 1 >= inLength)
throw new NotEnoughDataException(currentOutSize, decompressedSize);
- int byte1 = instream.ReadByte(); readBytes++;
- if (byte1 < 0)
+ int byte2 = instream.ReadByte(); readBytes++;
+ int byte3 = instream.ReadByte(); readBytes++;
+ if (byte3 < 0)
throw new StreamTooShortException();
- int length = byte1 >> 4;
- int disp;
- if (length == 0)
- {
- #region case 0; 0(B C)(D EF) + (0x11)(0x1) = (LEN)(DISP)
-
- // case 0:
- // data = AB CD EF (with A=0)
- // LEN = ABC + 0x11 == BC + 0x11
- // DISP = DEF + 1
-
- // we need two more bytes available
- if (readBytes + 1 >= inLength)
- throw new NotEnoughDataException(currentOutSize, decompressedSize);
- int byte2 = instream.ReadByte(); readBytes++;
- int byte3 = instream.ReadByte(); readBytes++;
- if (byte3 < 0)
- throw new StreamTooShortException();
+ length = (((byte1 & 0x0F) << 4) | (byte2 >> 4)) + 0x11;
+ disp = (((byte2 & 0x0F) << 8) | byte3) + 0x1;
- length = (((byte1 & 0x0F) << 4) | (byte2 >> 4)) + 0x11;
- disp = (((byte2 & 0x0F) << 8) | byte3) + 0x1;
-
- #endregion
- }
- else if (length == 1)
- {
- #region case 1: 1(B CD E)(F GH) + (0x111)(0x1) = (LEN)(DISP)
-
- // case 1:
- // data = AB CD EF GH (with A=1)
- // LEN = BCDE + 0x111
- // DISP = FGH + 1
-
- // we need three more bytes available
- if (readBytes + 2 >= inLength)
- throw new NotEnoughDataException(currentOutSize, decompressedSize);
- int byte2 = instream.ReadByte(); readBytes++;
- int byte3 = instream.ReadByte(); readBytes++;
- int byte4 = instream.ReadByte(); readBytes++;
- if (byte4 < 0)
- throw new StreamTooShortException();
-
- length = (((byte1 & 0x0F) << 12) | (byte2 << 4) | (byte3 >> 4)) + 0x111;
- disp = (((byte3 & 0x0F) << 8) | byte4) + 0x1;
-
- #endregion
- }
- else
- {
- #region case > 1: (A)(B CD) + (0x1)(0x1) = (LEN)(DISP)
-
- // case other:
- // data = AB CD
- // LEN = A + 1
- // DISP = BCD + 1
+ #endregion
+ }
+ else if (length == 1)
+ {
+ #region case 1: 1(B CD E)(F GH) + (0x111)(0x1) = (LEN)(DISP)
- // we need only one more byte available
- if (readBytes >= inLength)
- throw new NotEnoughDataException(currentOutSize, decompressedSize);
- int byte2 = instream.ReadByte(); readBytes++;
- if (byte2 < 0)
- throw new StreamTooShortException();
+ // case 1:
+ // data = AB CD EF GH (with A=1)
+ // LEN = BCDE + 0x111
+ // DISP = FGH + 1
- length = ((byte1 & 0xF0) >> 4) + 0x1;
- disp = (((byte1 & 0x0F) << 8) | byte2) + 0x1;
+ // we need three more bytes available
+ if (readBytes + 2 >= inLength)
+ throw new NotEnoughDataException(currentOutSize, decompressedSize);
+ int byte2 = instream.ReadByte(); readBytes++;
+ int byte3 = instream.ReadByte(); readBytes++;
+ int byte4 = instream.ReadByte(); readBytes++;
+ if (byte4 < 0)
+ throw new StreamTooShortException();
- #endregion
- }
+ length = (((byte1 & 0x0F) << 12) | (byte2 << 4) | (byte3 >> 4)) + 0x111;
+ disp = (((byte3 & 0x0F) << 8) | byte4) + 0x1;
- if (disp > currentOutSize)
- throw new InvalidDataException("Cannot go back more than already written. "
- + "DISP = " + disp + ", #written bytes = 0x" + currentOutSize.ToString("X")
- + " before 0x" + instream.Position.ToString("X") + " with indicator 0x"
- + (byte1 >> 4).ToString("X"));
#endregion
-
- int bufIdx = bufferOffset + bufferLength - disp;
- for (int i = 0; i < length; i++)
- {
- byte next = buffer[bufIdx % bufferLength];
- bufIdx++;
- outstream.WriteByte(next);
- buffer[bufferOffset] = next;
- bufferOffset = (bufferOffset + 1) % bufferLength;
- }
- currentOutSize += length;
}
else
{
+ #region case > 1: (A)(B CD) + (0x1)(0x1) = (LEN)(DISP)
+
+ // case other:
+ // data = AB CD
+ // LEN = A + 1
+ // DISP = BCD + 1
+
+ // we need only one more byte available
if (readBytes >= inLength)
throw new NotEnoughDataException(currentOutSize, decompressedSize);
- int next = instream.ReadByte(); readBytes++;
- if (next < 0)
+ int byte2 = instream.ReadByte(); readBytes++;
+ if (byte2 < 0)
throw new StreamTooShortException();
- outstream.WriteByte((byte)next); currentOutSize++;
- buffer[bufferOffset] = (byte)next;
+ length = ((byte1 & 0xF0) >> 4) + 0x1;
+ disp = (((byte1 & 0x0F) << 8) | byte2) + 0x1;
+
+ #endregion
+ }
+
+ if (disp > currentOutSize)
+ {
+ throw new InvalidDataException($"Cannot go back more than already written. DISP = {disp}, #written bytes = 0x{currentOutSize:X} before 0x{instream.Position:X} with indicator 0x{byte1 >> 4:X}");
+ }
+
+ #endregion
+
+ int bufIdx = bufferOffset + bufferLength - disp;
+ for (int i = 0; i < length; i++)
+ {
+ byte next = buffer[bufIdx % bufferLength];
+ bufIdx++;
+ outstream.WriteByte(next);
+ buffer[bufferOffset] = next;
bufferOffset = (bufferOffset + 1) % bufferLength;
}
+ currentOutSize += length;
}
-
- if (readBytes < inLength)
+ else
{
- // the input may be 4-byte aligned.
- if ((readBytes ^ (readBytes & 3)) + 4 < inLength)
- throw new TooMuchInputException(readBytes, inLength);
+ if (readBytes >= inLength)
+ throw new NotEnoughDataException(currentOutSize, decompressedSize);
+ int next = instream.ReadByte(); readBytes++;
+ if (next < 0)
+ throw new StreamTooShortException();
+
+ outstream.WriteByte((byte)next); currentOutSize++;
+ buffer[bufferOffset] = (byte)next;
+ bufferOffset = (bufferOffset + 1) % bufferLength;
}
-
- return decompressedSize;
}
- public static int Compress(string infile, string outfile)
+ if (readBytes < inLength)
{
- // make sure the output directory exists
- string outDirectory = Path.GetDirectoryName(outfile);
- if (!Directory.Exists(outDirectory))
- Directory.CreateDirectory(outDirectory);
- // open the proper Streams, and delegate to the format-specific code.
- using (FileStream inStream = File.Open(infile, FileMode.Open),
- outStream = File.Create(outfile))
- {
- if (inStream.Length == 0) // empty file 'compression' to lzss container
- {
- byte[] blank = {0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
- outStream.Write(blank, 0, blank.Length);
- return blank.Length;
- }
+ // the input may be 4-byte aligned.
+ if ((readBytes ^ (readBytes & 3)) + 4 < inLength)
+ throw new TooMuchInputException(readBytes, inLength);
+ }
- return Compress(inStream, inStream.Length, outStream, true);
- }
+ return decompressedSize;
+ }
+
+ public static int Compress(string infile, string outfile)
+ {
+ // make sure the output directory exists
+ string outDirectory = Path.GetDirectoryName(outfile);
+ if (!Directory.Exists(outDirectory))
+ Directory.CreateDirectory(outDirectory);
+ // open the proper Streams, and delegate to the format-specific code.
+ using FileStream inStream = File.Open(infile, FileMode.Open),
+ outStream = File.Create(outfile);
+ if (inStream.Length == 0) // empty file 'compression' to lzss container
+ {
+ byte[] blank = [0x11, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
+ outStream.Write(blank, 0, blank.Length);
+ return blank.Length;
}
- #region Original compression method
- ///
- /// Compresses the input using the 'original', unoptimized compression algorithm.
- /// This algorithm should yield files that are the same as those found in the games.
- /// (delegates to the optimized method if LookAhead is set)
- ///
- internal static unsafe int Compress(Stream instream, long inLength, Stream outstream, bool original)
+
+ return Compress(inStream, inStream.Length, outStream, true);
+ }
+ #region Original compression method
+ ///
+ /// Compresses the input using the 'original', unoptimized compression algorithm.
+ /// This algorithm should yield files that are the same as those found in the games.
+ /// (delegates to the optimized method if LookAhead is set)
+ ///
+ internal static unsafe int Compress(Stream instream, long inLength, Stream outstream, bool original)
+ {
+ // make sure the decompressed size fits in 3 bytes.
+ // There should be room for four bytes, however I'm not 100% sure if that can be used
+ // in every game, as it may not be a built-in function.
+ if (inLength > 0xFFFFFF)
+ throw new InputTooLargeException();
+
+ // use the other method if lookahead is enabled
+ if (!original)
{
- // make sure the decompressed size fits in 3 bytes.
- // There should be room for four bytes, however I'm not 100% sure if that can be used
- // in every game, as it may not be a built-in function.
- if (inLength > 0xFFFFFF)
- throw new InputTooLargeException();
-
- // use the other method if lookahead is enabled
- if (!original)
- {
- return CompressWithLA(instream, inLength, outstream);
- }
+ return CompressWithLA(instream, inLength, outstream);
+ }
- // save the input data in an array to prevent having to go back and forth in a file
- byte[] indata = new byte[inLength];
- int numReadBytes = instream.Read(indata, 0, (int)inLength);
- if (numReadBytes != inLength)
- throw new StreamTooShortException();
+ // save the input data in an array to prevent having to go back and forth in a file
+ byte[] indata = new byte[inLength];
+ int numReadBytes = instream.Read(indata, 0, (int)inLength);
+ if (numReadBytes != inLength)
+ throw new StreamTooShortException();
- // write the compression header first
- outstream.WriteByte(0x11);
- outstream.WriteByte((byte)(inLength & 0xFF));
- outstream.WriteByte((byte)((inLength >> 8) & 0xFF));
- outstream.WriteByte((byte)((inLength >> 16) & 0xFF));
+ // write the compression header first
+ outstream.WriteByte(0x11);
+ outstream.WriteByte((byte)(inLength & 0xFF));
+ outstream.WriteByte((byte)((inLength >> 8) & 0xFF));
+ outstream.WriteByte((byte)((inLength >> 16) & 0xFF));
- int compressedLength = 4;
+ int compressedLength = 4;
- fixed (byte* instart = &indata[0])
+ fixed (byte* instart = &indata[0])
+ {
+ // we do need to buffer the output, as the first byte indicates which blocks are compressed.
+ // this version does not use a look-ahead, so we do not need to buffer more than 8 blocks at a time.
+ // (a block is at most 4 bytes long)
+ byte[] outbuffer = new byte[(8 * 4) + 1];
+ outbuffer[0] = 0;
+ int bufferlength = 1, bufferedBlocks = 0;
+ int readBytes = 0;
+ while (readBytes < inLength)
{
- // we do need to buffer the output, as the first byte indicates which blocks are compressed.
- // this version does not use a look-ahead, so we do not need to buffer more than 8 blocks at a time.
- // (a block is at most 4 bytes long)
- byte[] outbuffer = new byte[8 * 4 + 1];
- outbuffer[0] = 0;
- int bufferlength = 1, bufferedBlocks = 0;
- int readBytes = 0;
- while (readBytes < inLength)
+ #region If 8 blocks are bufferd, write them and reset the buffer
+ // we can only buffer 8 blocks at a time.
+ if (bufferedBlocks == 8)
{
- #region If 8 blocks are bufferd, write them and reset the buffer
- // we can only buffer 8 blocks at a time.
- if (bufferedBlocks == 8)
- {
- outstream.Write(outbuffer, 0, bufferlength);
- compressedLength += bufferlength;
- // reset the buffer
- outbuffer[0] = 0;
- bufferlength = 1;
- bufferedBlocks = 0;
- }
- #endregion
+ outstream.Write(outbuffer, 0, bufferlength);
+ compressedLength += bufferlength;
+ // reset the buffer
+ outbuffer[0] = 0;
+ bufferlength = 1;
+ bufferedBlocks = 0;
+ }
+ #endregion
+
+ // determine if we're dealing with a compressed or raw block.
+ // it is a compressed block when the next 3 or more bytes can be copied from
+ // somewhere in the set of already compressed bytes.
+ int oldLength = Math.Min(readBytes, 0x1000);
+ int length = LZUtil.GetOccurrenceLength(instart + readBytes, (int)Math.Min(inLength - readBytes, 0x10110),
+ instart + readBytes - oldLength, oldLength, out var disp);
+
+ // length not 3 or more? next byte is raw data
+ if (length < 3)
+ {
+ outbuffer[bufferlength++] = *(instart + readBytes++);
+ }
+ else
+ {
+ // 3 or more bytes can be copied? next (length) bytes will be compressed into 2 bytes
+ readBytes += length;
- // determine if we're dealing with a compressed or raw block.
- // it is a compressed block when the next 3 or more bytes can be copied from
- // somewhere in the set of already compressed bytes.
- int disp;
- int oldLength = Math.Min(readBytes, 0x1000);
- int length = LZUtil.GetOccurrenceLength(instart + readBytes, (int)Math.Min(inLength - readBytes, 0x10110),
- instart + readBytes - oldLength, oldLength, out disp);
+ // mark the next block as compressed
+ outbuffer[0] |= (byte)(1 << (7 - bufferedBlocks));
- // length not 3 or more? next byte is raw data
- if (length < 3)
+ if (length > 0x110)
{
- outbuffer[bufferlength++] = *(instart + readBytes++);
+ // case 1: 1(B CD E)(F GH) + (0x111)(0x1) = (LEN)(DISP)
+ outbuffer[bufferlength] = 0x10;
+ outbuffer[bufferlength] |= (byte)(((length - 0x111) >> 12) & 0x0F);
+ bufferlength++;
+ outbuffer[bufferlength] = (byte)(((length - 0x111) >> 4) & 0xFF);
+ bufferlength++;
+ outbuffer[bufferlength] = (byte)(((length - 0x111) << 4) & 0xF0);
}
- else
+ else if (length > 0x10)
{
- // 3 or more bytes can be copied? next (length) bytes will be compressed into 2 bytes
- readBytes += length;
-
- // mark the next block as compressed
- outbuffer[0] |= (byte)(1 << (7 - bufferedBlocks));
-
- if (length > 0x110)
- {
- // case 1: 1(B CD E)(F GH) + (0x111)(0x1) = (LEN)(DISP)
- outbuffer[bufferlength] = 0x10;
- outbuffer[bufferlength] |= (byte)(((length - 0x111) >> 12) & 0x0F);
- bufferlength++;
- outbuffer[bufferlength] = (byte)(((length - 0x111) >> 4) & 0xFF);
- bufferlength++;
- outbuffer[bufferlength] = (byte)(((length - 0x111) << 4) & 0xF0);
- }
- else if (length > 0x10)
- {
- // case 0; 0(B C)(D EF) + (0x11)(0x1) = (LEN)(DISP)
- outbuffer[bufferlength] = 0x00;
- outbuffer[bufferlength] |= (byte)(((length - 0x111) >> 4) & 0x0F);
- bufferlength++;
- outbuffer[bufferlength] = (byte)(((length - 0x111) << 4) & 0xF0);
- }
- else
- {
- // case > 1: (A)(B CD) + (0x1)(0x1) = (LEN)(DISP)
- outbuffer[bufferlength] = (byte)(((length - 1) << 4) & 0xF0);
- }
- // the last 1.5 bytes are always the disp
- outbuffer[bufferlength] |= (byte)(((disp - 1) >> 8) & 0x0F);
- bufferlength++;
- outbuffer[bufferlength] = (byte)((disp - 1) & 0xFF);
+ // case 0; 0(B C)(D EF) + (0x11)(0x1) = (LEN)(DISP)
+ outbuffer[bufferlength] = 0x00;
+ outbuffer[bufferlength] |= (byte)(((length - 0x111) >> 4) & 0x0F);
bufferlength++;
+ outbuffer[bufferlength] = (byte)(((length - 0x111) << 4) & 0xF0);
}
- bufferedBlocks++;
- }
-
- // copy the remaining blocks to the output
- if (bufferedBlocks > 0)
- {
- outstream.Write(outbuffer, 0, bufferlength);
- compressedLength += bufferlength;
- /*/ make the compressed file 4-byte aligned.
- while ((compressedLength % 4) != 0)
+ else
{
- outstream.WriteByte(0);
- compressedLength++;
- }/**/
+ // case > 1: (A)(B CD) + (0x1)(0x1) = (LEN)(DISP)
+ outbuffer[bufferlength] = (byte)(((length - 1) << 4) & 0xF0);
+ }
+ // the last 1.5 bytes are always the disp
+ outbuffer[bufferlength] |= (byte)(((disp - 1) >> 8) & 0x0F);
+ bufferlength++;
+ outbuffer[bufferlength] = (byte)((disp - 1) & 0xFF);
+ bufferlength++;
}
+ bufferedBlocks++;
}
- return compressedLength;
+ // copy the remaining blocks to the output
+ if (bufferedBlocks > 0)
+ {
+ outstream.Write(outbuffer, 0, bufferlength);
+ compressedLength += bufferlength;
+ /*/ make the compressed file 4-byte aligned.
+ while ((compressedLength % 4) != 0)
+ {
+ outstream.WriteByte(0);
+ compressedLength++;
+ }/**/
+ }
}
- #region Dynamic Programming compression method
- ///
- /// Variation of the original compression method, making use of Dynamic Programming to 'look ahead'
- /// and determine the optimal 'length' values for the compressed blocks. Is not 100% optimal,
- /// as the flag-bytes are not taken into account.
- ///
- internal static unsafe int CompressWithLA(Stream instream, long inLength, Stream outstream)
- {
- // save the input data in an array to prevent having to go back and forth in a file
- byte[] indata = new byte[inLength];
- int numReadBytes = instream.Read(indata, 0, (int)inLength);
- if (numReadBytes != inLength)
- throw new StreamTooShortException();
- // write the compression header first
- outstream.WriteByte(0x11);
- outstream.WriteByte((byte)(inLength & 0xFF));
- outstream.WriteByte((byte)((inLength >> 8) & 0xFF));
- outstream.WriteByte((byte)((inLength >> 16) & 0xFF));
+ return compressedLength;
+ }
+ #region Dynamic Programming compression method
+ ///
+ /// Variation of the original compression method, making use of Dynamic Programming to 'look ahead'
+ /// and determine the optimal 'length' values for the compressed blocks. Is not 100% optimal,
+ /// as the flag-bytes are not taken into account.
+ ///
+ internal static unsafe int CompressWithLA(Stream instream, long inLength, Stream outstream)
+ {
+ // save the input data in an array to prevent having to go back and forth in a file
+ byte[] indata = new byte[inLength];
+ int numReadBytes = instream.Read(indata, 0, (int)inLength);
+ if (numReadBytes != inLength)
+ throw new StreamTooShortException();
+
+ // write the compression header first
+ outstream.WriteByte(0x11);
+ outstream.WriteByte((byte)(inLength & 0xFF));
+ outstream.WriteByte((byte)((inLength >> 8) & 0xFF));
+ outstream.WriteByte((byte)((inLength >> 16) & 0xFF));
- int compressedLength = 4;
+ int compressedLength = 4;
- fixed (byte* instart = &indata[0])
+ fixed (byte* instart = &indata[0])
+ {
+ // we do need to buffer the output, as the first byte indicates which blocks are compressed.
+ // this version does not use a look-ahead, so we do not need to buffer more than 8 blocks at a time.
+ // blocks are at most 4 bytes long.
+ byte[] outbuffer = new byte[(8 * 4) + 1];
+ outbuffer[0] = 0;
+ int bufferlength = 1, bufferedBlocks = 0;
+ int readBytes = 0;
+
+ // get the optimal choices for len and disp
+ GetOptimalCompressionLengths(instart, indata.Length, out var lengths, out var disps);
+ while (readBytes < inLength)
{
- // we do need to buffer the output, as the first byte indicates which blocks are compressed.
- // this version does not use a look-ahead, so we do not need to buffer more than 8 blocks at a time.
- // blocks are at most 4 bytes long.
- byte[] outbuffer = new byte[8 * 4 + 1];
- outbuffer[0] = 0;
- int bufferlength = 1, bufferedBlocks = 0;
- int readBytes = 0;
-
- // get the optimal choices for len and disp
- int[] lengths, disps;
- GetOptimalCompressionLengths(instart, indata.Length, out lengths, out disps);
- while (readBytes < inLength)
+ // we can only buffer 8 blocks at a time.
+ if (bufferedBlocks == 8)
{
- // we can only buffer 8 blocks at a time.
- if (bufferedBlocks == 8)
- {
- outstream.Write(outbuffer, 0, bufferlength);
- compressedLength += bufferlength;
- // reset the buffer
- outbuffer[0] = 0;
- bufferlength = 1;
- bufferedBlocks = 0;
- }
+ outstream.Write(outbuffer, 0, bufferlength);
+ compressedLength += bufferlength;
+ // reset the buffer
+ outbuffer[0] = 0;
+ bufferlength = 1;
+ bufferedBlocks = 0;
+ }
+ if (lengths[readBytes] == 1)
+ {
+ outbuffer[bufferlength++] = *(instart + readBytes++);
+ }
+ else
+ {
+ // mark the next block as compressed
+ outbuffer[0] |= (byte)(1 << (7 - bufferedBlocks));
- if (lengths[readBytes] == 1)
+ if (lengths[readBytes] > 0x110)
{
- outbuffer[bufferlength++] = *(instart + readBytes++);
+ // case 1: 1(B CD E)(F GH) + (0x111)(0x1) = (LEN)(DISP)
+ outbuffer[bufferlength] = 0x10;
+ outbuffer[bufferlength] |= (byte)(((lengths[readBytes] - 0x111) >> 12) & 0x0F);
+ bufferlength++;
+ outbuffer[bufferlength] = (byte)(((lengths[readBytes] - 0x111) >> 4) & 0xFF);
+ bufferlength++;
+ outbuffer[bufferlength] = (byte)(((lengths[readBytes] - 0x111) << 4) & 0xF0);
}
- else
+ else if (lengths[readBytes] > 0x10)
{
- // mark the next block as compressed
- outbuffer[0] |= (byte)(1 << (7 - bufferedBlocks));
-
- if (lengths[readBytes] > 0x110)
- {
- // case 1: 1(B CD E)(F GH) + (0x111)(0x1) = (LEN)(DISP)
- outbuffer[bufferlength] = 0x10;
- outbuffer[bufferlength] |= (byte)(((lengths[readBytes] - 0x111) >> 12) & 0x0F);
- bufferlength++;
- outbuffer[bufferlength] = (byte)(((lengths[readBytes] - 0x111) >> 4) & 0xFF);
- bufferlength++;
- outbuffer[bufferlength] = (byte)(((lengths[readBytes] - 0x111) << 4) & 0xF0);
- }
- else if (lengths[readBytes] > 0x10)
- {
- // case 0; 0(B C)(D EF) + (0x11)(0x1) = (LEN)(DISP)
- outbuffer[bufferlength] = 0x00;
- outbuffer[bufferlength] |= (byte)(((lengths[readBytes] - 0x111) >> 4) & 0x0F);
- bufferlength++;
- outbuffer[bufferlength] = (byte)(((lengths[readBytes] - 0x111) << 4) & 0xF0);
- }
- else
- {
- // case > 1: (A)(B CD) + (0x1)(0x1) = (LEN)(DISP)
- outbuffer[bufferlength] = (byte)(((lengths[readBytes] - 1) << 4) & 0xF0);
- }
- // the last 1.5 bytes are always the disp
- outbuffer[bufferlength] |= (byte)(((disps[readBytes] - 1) >> 8) & 0x0F);
+ // case 0; 0(B C)(D EF) + (0x11)(0x1) = (LEN)(DISP)
+ outbuffer[bufferlength] = 0x00;
+ outbuffer[bufferlength] |= (byte)(((lengths[readBytes] - 0x111) >> 4) & 0x0F);
bufferlength++;
- outbuffer[bufferlength] = (byte)((disps[readBytes] - 1) & 0xFF);
- bufferlength++;
-
- readBytes += lengths[readBytes];
+ outbuffer[bufferlength] = (byte)(((lengths[readBytes] - 0x111) << 4) & 0xF0);
}
+ else
+ {
+ // case > 1: (A)(B CD) + (0x1)(0x1) = (LEN)(DISP)
+ outbuffer[bufferlength] = (byte)(((lengths[readBytes] - 1) << 4) & 0xF0);
+ }
+ // the last 1.5 bytes are always the disp
+ outbuffer[bufferlength] |= (byte)(((disps[readBytes] - 1) >> 8) & 0x0F);
+ bufferlength++;
+ outbuffer[bufferlength] = (byte)((disps[readBytes] - 1) & 0xFF);
+ bufferlength++;
-
- bufferedBlocks++;
+ readBytes += lengths[readBytes];
}
- // copy the remaining blocks to the output
- if (bufferedBlocks > 0)
- {
- outstream.Write(outbuffer, 0, bufferlength);
- compressedLength += bufferlength;
- /*/ make the compressed file 4-byte aligned.
- while ((compressedLength % 4) != 0)
- {
- outstream.WriteByte(0);
- compressedLength++;
- }/**/
- }
+ bufferedBlocks++;
}
- return compressedLength;
+ // copy the remaining blocks to the output
+ if (bufferedBlocks > 0)
+ {
+ outstream.Write(outbuffer, 0, bufferlength);
+ compressedLength += bufferlength;
+ /*/ make the compressed file 4-byte aligned.
+ while ((compressedLength % 4) != 0)
+ {
+ outstream.WriteByte(0);
+ compressedLength++;
+ }/**/
+ }
}
- #endregion
- #region DP compression helper method; GetOptimalCompressionLengths
- ///
- /// Gets the optimal compression lengths for each start of a compressed block using Dynamic Programming.
- /// This takes O(n^2) time, although in practice it will often be O(n^3) since one of the constants is 0x10110
- /// (the maximum length of a compressed block)
- ///
- /// The data to compress.
- /// The length of the data to compress.
- /// The optimal 'length' of the compressed blocks. For each byte in the input data,
- /// this value is the optimal 'length' value. If it is 1, the block should not be compressed.
- /// The 'disp' values of the compressed blocks. May be 0, in which case the
- /// corresponding length will never be anything other than 1.
- internal static unsafe void GetOptimalCompressionLengths(byte* indata, int inLength, out int[] lengths, out int[] disps)
- {
- lengths = new int[inLength];
- disps = new int[inLength];
- int[] minLengths = new int[inLength];
+ return compressedLength;
+ }
+ #endregion
- for (int i = inLength - 1; i >= 0; i--)
+ #region DP compression helper method; GetOptimalCompressionLengths
+ ///
+ /// Gets the optimal compression lengths for each start of a compressed block using Dynamic Programming.
+ /// This takes O(n^2) time, although in practice it will often be O(n^3) since one of the constants is 0x10110
+ /// (the maximum length of a compressed block)
+ ///
+ /// The data to compress.
+ /// The length of the data to compress.
+ /// The optimal 'length' of the compressed blocks. For each byte in the input data,
+ /// this value is the optimal 'length' value. If it is 1, the block should not be compressed.
+ /// The 'disp' values of the compressed blocks. May be 0, in which case the
+ /// corresponding length will never be anything other than 1.
+ internal static unsafe void GetOptimalCompressionLengths(byte* indata, int inLength, out int[] lengths, out int[] disps)
+ {
+ lengths = new int[inLength];
+ disps = new int[inLength];
+ int[] minLengths = new int[inLength];
+
+ for (int i = inLength - 1; i >= 0; i--)
+ {
+ // first get the compression length when the next byte is not compressed
+ minLengths[i] = int.MaxValue;
+ lengths[i] = 1;
+ if (i + 1 >= inLength)
+ minLengths[i] = 1;
+ else
+ minLengths[i] = 1 + minLengths[i + 1];
+ // then the optimal compressed length
+ int oldLength = Math.Min(0x1000, i);
+ // get the appropriate disp while at it. Takes at most O(n) time if oldLength is considered O(n) and 0x10110 constant.
+ // however since a lot of files will not be larger than 0x10110, this will often take ~O(n^2) time.
+ // be sure to bound the input length with 0x10110, as that's the maximum length for LZ-11 compressed blocks.
+ int maxLen = LZUtil.GetOccurrenceLength(indata + i, Math.Min(inLength - i, 0x10110),
+ indata + i - oldLength, oldLength, out disps[i]);
+ if (disps[i] > i)
+ throw new Exception("disp is too large");
+ for (int j = 3; j <= maxLen; j++)
{
- // first get the compression length when the next byte is not compressed
- minLengths[i] = int.MaxValue;
- lengths[i] = 1;
- if (i + 1 >= inLength)
- minLengths[i] = 1;
+ int blocklen;
+ if (j > 0x110)
+ blocklen = 4;
+ else if (j > 0x10)
+ blocklen = 3;
else
- minLengths[i] = 1 + minLengths[i + 1];
- // then the optimal compressed length
- int oldLength = Math.Min(0x1000, i);
- // get the appropriate disp while at it. Takes at most O(n) time if oldLength is considered O(n) and 0x10110 constant.
- // however since a lot of files will not be larger than 0x10110, this will often take ~O(n^2) time.
- // be sure to bound the input length with 0x10110, as that's the maximum length for LZ-11 compressed blocks.
- int maxLen = LZUtil.GetOccurrenceLength(indata + i, Math.Min(inLength - i, 0x10110),
- indata + i - oldLength, oldLength, out disps[i]);
- if (disps[i] > i)
- throw new Exception("disp is too large");
- for (int j = 3; j <= maxLen; j++)
+ blocklen = 2;
+ int newCompLen;
+ if (i + j >= inLength)
+ newCompLen = blocklen;
+ else
+ newCompLen = blocklen + minLengths[i + j];
+ if (newCompLen < minLengths[i])
{
- int blocklen;
- if (j > 0x110)
- blocklen = 4;
- else if (j > 0x10)
- blocklen = 3;
- else
- blocklen = 2;
- int newCompLen;
- if (i + j >= inLength)
- newCompLen = blocklen;
- else
- newCompLen = blocklen + minLengths[i + j];
- if (newCompLen < minLengths[i])
- {
- lengths[i] = j;
- minLengths[i] = newCompLen;
- }
+ lengths[i] = j;
+ minLengths[i] = newCompLen;
}
}
-
- // we could optimize this further to also optimize it with regard to the flag-bytes, but that would require 8 times
- // more space and time (one for each position in the block) for only a potentially tiny increase in compression ratio.
}
- #endregion
- #endregion
+
+ // we could optimize this further to also optimize it with regard to the flag-bytes, but that would require 8 times
+ // more space and time (one for each position in the block) for only a potentially tiny increase in compression ratio.
}
- #region Exceptions
+ #endregion
+ #endregion
+}
+#region Exceptions
+///
+/// An exception indicating that the file cannot be compressed, because the decompressed size
+/// cannot be represented in the current compression format.
+///
+[Serializable]
+public class InputTooLargeException : Exception
+{
///
- /// An exception indicating that the file cannot be compressed, because the decompressed size
- /// cannot be represented in the current compression format.
+ /// Creates a new exception that indicates that the input is too big to be compressed.
///
- public class InputTooLargeException : Exception
+ public InputTooLargeException()
+ : base("The compression ratio is not high enough to fit the input "
+ + "in a single compressed file.")
+ { }
+
+ public InputTooLargeException(string message) : base(message)
{
- ///
- /// Creates a new exception that indicates that the input is too big to be compressed.
- ///
- public InputTooLargeException()
- : base("The compression ratio is not high enough to fit the input "
- + "in a single compressed file.") { }
}
+
+ public InputTooLargeException(string message, Exception innerException) : base(message, innerException)
+ {
+ }
+
+ protected InputTooLargeException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext)
+ {
+ }
+}
+
+///
+/// An exception that is thrown by the decompression functions when there
+/// is not enough data available in order to properly decompress the input.
+///
+[Serializable]
+public class NotEnoughDataException : IOException
+{
+ ///
+ /// Gets the actual number of written bytes.
+ ///
+ public long WrittenLength { get; }
+
///
- /// An exception that is thrown by the decompression functions when there
- /// is not enough data available in order to properly decompress the input.
+ /// Gets the number of bytes that was supposed to be written.
///
- public class NotEnoughDataException : IOException
+ public long DesiredLength { get; }
+
+ ///
+ /// Creates a new NotEnoughDataException.
+ ///
+ /// The actual number of written bytes.
+ /// The desired number of written bytes.
+ public NotEnoughDataException(long currentOutSize, long totalOutSize)
+ : base("Not enough data available; 0x" + currentOutSize.ToString("X")
+ + " of " + (totalOutSize < 0 ? "???" : "0x" + totalOutSize.ToString("X"))
+ + " bytes written.")
+ {
+ WrittenLength = currentOutSize;
+ DesiredLength = totalOutSize;
+ }
+
+ public NotEnoughDataException()
+ {
+ }
+
+ public NotEnoughDataException(string message) : base(message)
+ {
+ }
+
+ public NotEnoughDataException(string message, Exception innerException) : base(message, innerException)
+ {
+ }
+
+ public NotEnoughDataException(string message, int hresult) : base(message, hresult)
+ {
+ }
+
+ protected NotEnoughDataException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext)
{
- ///
- /// Gets the actual number of written bytes.
- ///
- public long WrittenLength { get; }
-
- ///
- /// Gets the number of bytes that was supposed to be written.
- ///
- public long DesiredLength { get; }
-
- ///
- /// Creates a new NotEnoughDataException.
- ///
- /// The actual number of written bytes.
- /// The desired number of written bytes.
- public NotEnoughDataException(long currentOutSize, long totalOutSize)
- : base("Not enough data availble; 0x" + currentOutSize.ToString("X")
- + " of " + (totalOutSize < 0 ? "???" : "0x" + totalOutSize.ToString("X"))
- + " bytes written.")
- {
- WrittenLength = currentOutSize;
- DesiredLength = totalOutSize;
- }
}
+}
+
+///
+/// An exception thrown by the compression or decompression function, indicating that the
+/// given input length was too large for the given input stream.
+///
+[Serializable]
+public class StreamTooShortException : EndOfStreamException
+{
///
- /// An exception thrown by the compression or decompression function, indicating that the
- /// given input length was too large for the given input stream.
+ /// Creates a new exception that indicates that the stream was shorter than the given input length.
///
- public class StreamTooShortException : EndOfStreamException
+ public StreamTooShortException()
+ : base("The end of the stream was reached "
+ + "before the given amount of data was read.")
+ { }
+
+ public StreamTooShortException(string message) : base(message)
{
- ///
- /// Creates a new exception that indicates that the stream was shorter than the given input length.
- ///
- public StreamTooShortException()
- : base("The end of the stream was reached "
- + "before the given amout of data was read.")
- { }
}
+
+ public StreamTooShortException(string message, Exception innerException) : base(message, innerException)
+ {
+ }
+
+ protected StreamTooShortException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext)
+ {
+ }
+}
+
+///
+/// An exception indication that the input has more data than required in order
+/// to decompress it. This may indicate that more sub-files are present in the file.
+///
+[Serializable]
+public class TooMuchInputException : Exception
+{
///
- /// An exception indication that the input has more data than required in order
- /// to decompress it. This may indicate that more sub-files are present in the file.
+ /// Gets the number of bytes read by the decompressed to decompress the stream.
///
- public class TooMuchInputException : Exception
+ public long ReadBytes { get; }
+
+ ///
+ /// Creates a new exception indicating that the input has more data than necessary for
+ /// decompressing th stream. It may indicate that other data is present after the compressed
+ /// stream.
+ ///
+ /// The number of bytes read by the decompressor.
+ /// The indicated length of the input stream.
+ public TooMuchInputException(long readBytes, long totLength)
+ : base("The input contains more data than necessary. Only used 0x"
+ + readBytes.ToString("X") + " of 0x" + totLength.ToString("X") + " bytes")
{
- ///
- /// Gets the number of bytes read by the decompressed to decompress the stream.
- ///
- public long ReadBytes { get; private set; }
-
- ///
- /// Creates a new exception indicating that the input has more data than necessary for
- /// decompressing th stream. It may indicate that other data is present after the compressed
- /// stream.
- ///
- /// The number of bytes read by the decompressor.
- /// The indicated length of the input stream.
- public TooMuchInputException(long readBytes, long totLength)
- : base("The input contains more data than necessary. Only used 0x"
- + readBytes.ToString("X") + " of 0x" + totLength.ToString("X") + " bytes")
- {
- ReadBytes = readBytes;
- }
+ ReadBytes = readBytes;
}
- #endregion
- #region Supplementary
+
+ public TooMuchInputException()
+ {
+ }
+
+ public TooMuchInputException(string message) : base(message)
+ {
+ }
+
+ public TooMuchInputException(string message, Exception innerException) : base(message, innerException)
+ {
+ }
+
+ protected TooMuchInputException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext)
+ {
+ }
+}
+#endregion
+#region Supplementary
+///
+/// Class for I/O-related utility methods.
+///
+public static class LZUtil
+{
///
- /// Class for I/O-related utility methods.
+ /// Determine the maximum size of a LZ-compressed block starting at newPtr, using the already compressed data
+ /// starting at oldPtr. Takes O(inLength * oldLength) = O(n^2) time.
///
- public static class LZUtil
+ /// The start of the data that needs to be compressed.
+ /// The number of bytes that still need to be compressed.
+ /// (or: the maximum number of bytes that _may_ be compressed into one block)
+ /// The start of the raw file.
+ /// The number of bytes already compressed.
+ /// The offset of the start of the longest block to refer to.
+ /// The minimum allowed value for 'disp'.
+ /// The length of the longest sequence of bytes that can be copied from the already decompressed data.
+ public static unsafe int GetOccurrenceLength(byte* newPtr, int newLength, byte* oldPtr, int oldLength, out int disp, int minDisp = 1)
{
- ///
- /// Determine the maximum size of a LZ-compressed block starting at newPtr, using the already compressed data
- /// starting at oldPtr. Takes O(inLength * oldLength) = O(n^2) time.
- ///
- /// The start of the data that needs to be compressed.
- /// The number of bytes that still need to be compressed.
- /// (or: the maximum number of bytes that _may_ be compressed into one block)
- /// The start of the raw file.
- /// The number of bytes already compressed.
- /// The offset of the start of the longest block to refer to.
- /// The minimum allowed value for 'disp'.
- /// The length of the longest sequence of bytes that can be copied from the already decompressed data.
- public static unsafe int GetOccurrenceLength(byte* newPtr, int newLength, byte* oldPtr, int oldLength, out int disp, int minDisp = 1)
+ disp = 0;
+ if (newLength == 0)
+ return 0;
+ int maxLength = 0;
+ // try every possible 'disp' value (disp = oldLength - i)
+ for (int i = 0; i < oldLength - minDisp; i++)
{
- disp = 0;
- if (newLength == 0)
- return 0;
- int maxLength = 0;
- // try every possible 'disp' value (disp = oldLength - i)
- for (int i = 0; i < oldLength - minDisp; i++)
+ // work from the start of the old data to the end, to mimic the original implementation's behaviour
+ // (and going from start to end or from end to start does not influence the compression ratio anyway)
+ byte* currentOldStart = oldPtr + i;
+ int currentLength = 0;
+ // determine the length we can copy if we go back (oldLength - i) bytes
+ // always check the next 'newLength' bytes, and not just the available 'old' bytes,
+ // as the copied data can also originate from what we're currently trying to compress.
+ for (int j = 0; j < newLength; j++)
{
- // work from the start of the old data to the end, to mimic the original implementation's behaviour
- // (and going from start to end or from end to start does not influence the compression ratio anyway)
- byte* currentOldStart = oldPtr + i;
- int currentLength = 0;
- // determine the length we can copy if we go back (oldLength - i) bytes
- // always check the next 'newLength' bytes, and not just the available 'old' bytes,
- // as the copied data can also originate from what we're currently trying to compress.
- for (int j = 0; j < newLength; j++)
- {
- // stop when the bytes are no longer the same
- if (*(currentOldStart + j) != *(newPtr + j))
- break;
- currentLength++;
- }
+ // stop when the bytes are no longer the same
+ if (*(currentOldStart + j) != *(newPtr + j))
+ break;
+ currentLength++;
+ }
- // update the optimal value
- if (currentLength > maxLength)
- {
- maxLength = currentLength;
- disp = oldLength - i;
+ // update the optimal value
+ if (currentLength > maxLength)
+ {
+ maxLength = currentLength;
+ disp = oldLength - i;
- // if we cannot do better anyway, stop trying.
- if (maxLength == newLength)
- break;
- }
+ // if we cannot do better anyway, stop trying.
+ if (maxLength == newLength)
+ break;
}
- return maxLength;
}
+ return maxLength;
}
- public static class IOUtils
+}
+
+public static class IOUtils
+{
+ #region byte[] <-> (u)int
+ ///
+ /// Returns a 4-byte unsigned integer as used on the NDS converted from four bytes
+ /// at a specified position in a byte array.
+ ///
+ /// The source of the data.
+ /// The location of the data in the source.
+ /// The indicated 4 bytes converted to uint
+ public static uint ToNDSu32(byte[] buffer, int offset)
{
- #region byte[] <-> (u)int
- ///
- /// Returns a 4-byte unsigned integer as used on the NDS converted from four bytes
- /// at a specified position in a byte array.
- ///
- /// The source of the data.
- /// The location of the data in the source.
- /// The indicated 4 bytes converted to uint
- public static uint ToNDSu32(byte[] buffer, int offset)
- {
- return (uint)(buffer[offset]
- | (buffer[offset + 1] << 8)
- | (buffer[offset + 2] << 16)
- | (buffer[offset + 3] << 24));
- }
+ return (uint)(buffer[offset]
+ | (buffer[offset + 1] << 8)
+ | (buffer[offset + 2] << 16)
+ | (buffer[offset + 3] << 24));
+ }
- ///
- /// Returns a 4-byte signed integer as used on the NDS converted from four bytes
- /// at a specified position in a byte array.
- ///
- /// The source of the data.
- /// The location of the data in the source.
- /// The indicated 4 bytes converted to int
- public static int ToNDSs32(byte[] buffer, int offset)
- {
- return buffer[offset]
- | (buffer[offset + 1] << 8)
- | (buffer[offset + 2] << 16)
- | (buffer[offset + 3] << 24);
- }
+ ///
+ /// Returns a 4-byte signed integer as used on the NDS converted from four bytes
+ /// at a specified position in a byte array.
+ ///
+ /// The source of the data.
+ /// The location of the data in the source.
+ /// The indicated 4 bytes converted to int
+ public static int ToNDSs32(byte[] buffer, int offset)
+ {
+ return buffer[offset]
+ | (buffer[offset + 1] << 8)
+ | (buffer[offset + 2] << 16)
+ | (buffer[offset + 3] << 24);
+ }
- ///
- /// Converts a u32 value into a sequence of bytes that would make ToNDSu32 return
- /// the given input value.
- ///
- public static byte[] FromNDSu32(uint value)
- {
- return new[] {
- (byte)(value & 0xFF),
- (byte)((value >> 8) & 0xFF),
- (byte)((value >> 16) & 0xFF),
- (byte)((value >> 24) & 0xFF)
- };
- }
+ ///
+ /// Converts a u32 value into a sequence of bytes that would make ToNDSu32 return
+ /// the given input value.
+ ///
+ public static byte[] FromNDSu32(uint value)
+ {
+ return
+ [
+ (byte)(value & 0xFF),
+ (byte)((value >> 8) & 0xFF),
+ (byte)((value >> 16) & 0xFF),
+ (byte)((value >> 24) & 0xFF),
+ ];
+ }
- ///
- /// Returns a 3-byte integer as used in the built-in compression
- /// formats in the DS, converted from three bytes at a specified position in a byte array,
- ///
- /// The source of the data.
- /// The location of the data in the source.
- /// The indicated 3 bytes converted to an integer.
- public static int ToNDSu24(byte[] buffer, int offset)
- {
- return buffer[offset]
- | (buffer[offset + 1] << 8)
- | (buffer[offset + 2] << 16);
- }
- #endregion
+ ///
+ /// Returns a 3-byte integer as used in the built-in compression
+ /// formats in the DS, converted from three bytes at a specified position in a byte array,
+ ///
+ /// The source of the data.
+ /// The location of the data in the source.
+ /// The indicated 3 bytes converted to an integer.
+ public static int ToNDSu24(byte[] buffer, int offset)
+ {
+ return buffer[offset]
+ | (buffer[offset + 1] << 8)
+ | (buffer[offset + 2] << 16);
}
#endregion
}
+#endregion
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/NCCH.cs b/pk3DS.Core/CTR/NCCH.cs
index 4327d13ad3..69688512ce 100644
--- a/pk3DS.Core/CTR/NCCH.cs
+++ b/pk3DS.Core/CTR/NCCH.cs
@@ -1,78 +1,255 @@
using System;
+using System.IO;
+using System.Windows.Forms;
-namespace pk3DS.Core.CTR
+namespace pk3DS.Core.CTR;
+
+public class NCCH
{
- public class NCCH
+ public NCCHHeader Header;
+ public ExeFS ExeFS;
+ public RomFS RomFS;
+ public Exheader Exheader;
+ public byte[] logo;
+ public byte[] plainregion;
+ public const uint MEDIA_UNIT_SIZE = 0x200;
+
+ public class NCCHHeader
{
- public Header header;
- public ExeFS exefs;
- public RomFS romfs;
- public Exheader exheader;
- public byte[] logo;
- public byte[] plainregion;
- public const uint MEDIA_UNIT_SIZE = 0x200;
-
- public class Header
+ public byte[] Signature; //Size: 0x100
+ public uint Magic;
+ public uint Size;
+ public ulong TitleId;
+ public ushort MakerCode;
+ public ushort FormatVersion;
+ //public uint padding0;
+ public ulong ProgramId;
+ //public byte[0x10] padding1;
+ public byte[] LogoHash; // Size: 0x20
+ public byte[] ProductCode; // Size: 0x10
+ public byte[] ExheaderHash; // Size: 0x20
+ public uint ExheaderSize;
+ //public uint padding2;
+ public byte[] Flags; // Size: 8
+ public uint PlainRegionOffset;
+ public uint PlainRegionSize;
+ public uint LogoOffset;
+ public uint LogoSize;
+ public uint ExefsOffset;
+ public uint ExefsSize;
+ public uint ExefsSuperBlockSize;
+ //public uint padding4;
+ public uint RomfsOffset;
+ public uint RomfsSize;
+ public uint RomfsSuperBlockSize;
+ //public uint padding5;
+ public byte[] ExefsHash; // Size: 0x20
+ public byte[] RomfsHash; // Size: 0x20
+
+ public byte[] Data;
+
+ public void BuildHeader()
{
- public byte[] Signature; //Size: 0x100
- public uint Magic;
- public uint Size;
- public ulong TitleId;
- public ushort MakerCode;
- public ushort FormatVersion;
- //public uint padding0;
- public ulong ProgramId;
- //public byte[0x10] padding1;
- public byte[] LogoHash; // Size: 0x20
- public byte[] ProductCode; // Size: 0x10
- public byte[] ExheaderHash; // Size: 0x20
- public uint ExheaderSize;
- //public uint padding2;
- public byte[] Flags; // Size: 8
- public uint PlainRegionOffset;
- public uint PlainRegionSize;
- public uint LogoOffset;
- public uint LogoSize;
- public uint ExefsOffset;
- public uint ExefsSize;
- public uint ExefsSuperBlockSize;
- //public uint padding4;
- public uint RomfsOffset;
- public uint RomfsSize;
- public uint RomfsSuperBlockSize;
- //public uint padding5;
- public byte[] ExefsHash; // Size: 0x20
- public byte[] RomfsHash; // Size: 0x20
-
- public byte[] Data;
-
- public void BuildHeader()
+ Data = new byte[0x200];
+ Array.Copy(Signature, Data, 0x100);
+ Array.Copy(BitConverter.GetBytes(Magic), 0, Data, 0x100, 4);
+ Array.Copy(BitConverter.GetBytes(Size), 0, Data, 0x104, 4);
+ Array.Copy(BitConverter.GetBytes(TitleId), 0, Data, 0x108, 8);
+ Array.Copy(BitConverter.GetBytes(MakerCode), 0, Data, 0x110, 2);
+ Array.Copy(BitConverter.GetBytes(FormatVersion), 0, Data, 0x112, 2);
+ //4 Byte Padding
+ Array.Copy(BitConverter.GetBytes(ProgramId), 0, Data, 0x118, 8);
+ //0x10 Byte Padding
+ Array.Copy(LogoHash, 0, Data, 0x130, 0x20);
+ Array.Copy(ProductCode, 0, Data, 0x150, 0x10);
+ Array.Copy(ExheaderHash, 0, Data, 0x160, 0x20);
+ Array.Copy(BitConverter.GetBytes(ExheaderSize), 0, Data, 0x180, 4);
+ //4 Byte Padding
+ Array.Copy(Flags, 0, Data, 0x188, 0x8);
+ uint ofs = 0x190;
+ foreach (uint val in new uint[] { PlainRegionOffset, PlainRegionSize, LogoOffset, LogoSize, ExefsOffset, ExefsSize, ExefsSuperBlockSize, 0, RomfsOffset, RomfsSize, RomfsSuperBlockSize, 0 })
{
- Data = new byte[0x200];
- Array.Copy(Signature, Data, 0x100);
- Array.Copy(BitConverter.GetBytes(Magic), 0, Data, 0x100, 4);
- Array.Copy(BitConverter.GetBytes(Size), 0, Data, 0x104, 4);
- Array.Copy(BitConverter.GetBytes(TitleId), 0, Data, 0x108, 8);
- Array.Copy(BitConverter.GetBytes(MakerCode), 0, Data, 0x110, 2);
- Array.Copy(BitConverter.GetBytes(FormatVersion), 0, Data, 0x112, 2);
- //4 Byte Padding
- Array.Copy(BitConverter.GetBytes(ProgramId), 0, Data, 0x118, 8);
- //0x10 Byte Padding
- Array.Copy(LogoHash, 0, Data, 0x130, 0x20);
- Array.Copy(ProductCode, 0, Data, 0x150, 0x10);
- Array.Copy(ExheaderHash, 0, Data, 0x160, 0x20);
- Array.Copy(BitConverter.GetBytes(ExheaderSize), 0, Data, 0x180, 4);
- //4 Byte Padding
- Array.Copy(Flags, 0, Data, 0x188, 0x8);
- uint ofs = 0x190;
- foreach (uint val in new uint[] { PlainRegionOffset, PlainRegionSize, LogoOffset, LogoSize, ExefsOffset, ExefsSize, ExefsSuperBlockSize, 0, RomfsOffset, RomfsSize, RomfsSuperBlockSize, 0 })
+ Array.Copy(BitConverter.GetBytes(val), 0, Data, ofs, 4);
+ ofs += 4;
+ }
+ Array.Copy(ExefsHash, 0, Data, 0x1C0, 0x20);
+ Array.Copy(RomfsHash, 0, Data, 0x1E0, 0x20);
+ }
+
+ public void BuildHeaderFromBytes(byte[] data)
+ {
+ Data = data;
+ Signature = new byte[0x100];
+ Array.Copy(data, Signature, 0x100);
+ Magic = BitConverter.ToUInt32(data, 0x100);
+ Size = BitConverter.ToUInt32(data, 0x104);
+ TitleId = BitConverter.ToUInt64(data, 0x108);
+ MakerCode = BitConverter.ToUInt16(data, 0x110);
+ FormatVersion = BitConverter.ToUInt16(data, 0x112);
+ //4 Byte Padding
+ ProgramId = BitConverter.ToUInt64(data, 0x118);
+ //0x10 Byte Padding
+ LogoHash = new byte[0x20];
+ Array.Copy(data, 0x130, LogoHash, 0x0, 0x20);
+ ProductCode = new byte[0x10];
+ Array.Copy(data, 0x150, ProductCode, 0x0, 0x10);
+ ExheaderHash = new byte[0x20];
+ Array.Copy(data, 0x160, ExheaderHash, 0x0, 0x20);
+ ExheaderSize = BitConverter.ToUInt32(data, 0x180);
+ //4 Byte Padding
+ Flags = new byte[0x8];
+ Array.Copy(data, 0x188, Flags, 0, 0x8);
+ PlainRegionOffset = BitConverter.ToUInt32(data, 0x190);
+ PlainRegionSize = BitConverter.ToUInt32(data, 0x194);
+ LogoOffset = BitConverter.ToUInt32(data, 0x198);
+ LogoSize = BitConverter.ToUInt32(data, 0x19C);
+ ExefsOffset = BitConverter.ToUInt32(data, 0x1A0);
+ ExefsSize = BitConverter.ToUInt32(data, 0x1A4);
+ ExefsSuperBlockSize = BitConverter.ToUInt32(data, 0x1A8);
+ //4 Byte Padding
+ RomfsOffset = BitConverter.ToUInt32(data, 0x1B0);
+ RomfsSize = BitConverter.ToUInt32(data, 0x1B4);
+ RomfsSuperBlockSize = BitConverter.ToUInt32(data, 0x1B8);
+ //4 Byte Padding
+ ExefsHash = new byte[0x20];
+ Array.Copy(data, 0x1C0, ExefsHash, 0x0, 0x20);
+ RomfsHash = new byte[0x20];
+ Array.Copy(data, 0x1E0, RomfsHash, 0x0, 0x20);
+ }
+ }
+
+ public void ExtractNCCHFromFile(string NCCH_PATH, string outputDirectory, RichTextBox TB_Progress = null, ProgressBar PB_Show = null)
+ {
+ if (!Directory.Exists(outputDirectory))
+ Directory.CreateDirectory(outputDirectory);
+
+ byte[] headerBytes = new byte[0x200];
+ using (var fs = new FileStream(NCCH_PATH, FileMode.Open, FileAccess.Read))
+ {
+ _ = fs.Read(headerBytes, 0, headerBytes.Length);
+ Header = new NCCHHeader();
+ Header.BuildHeaderFromBytes(headerBytes);
+
+ logo = new byte[Header.LogoSize * MEDIA_UNIT_SIZE];
+ fs.Seek(Convert.ToInt32(Header.LogoOffset * MEDIA_UNIT_SIZE), SeekOrigin.Begin);
+ _ = fs.Read(logo, 0, logo.Length);
+
+ plainregion = new byte[Header.PlainRegionSize * MEDIA_UNIT_SIZE];
+ fs.Seek(Convert.ToInt32(Header.PlainRegionOffset * MEDIA_UNIT_SIZE), SeekOrigin.Begin);
+ _ = fs.Read(plainregion, 0, plainregion.Length);
+ }
+
+ ExtractExheader(NCCH_PATH, outputDirectory, TB_Progress);
+ ExtractExeFS(NCCH_PATH, outputDirectory, TB_Progress);
+ ExtractRomFS(NCCH_PATH, outputDirectory, TB_Progress, PB_Show);
+ }
+
+ private void ExtractExheader(string NCCH_PATH, string outputDirectory, RichTextBox TB_Progress = null)
+ {
+ string exheaderpath = Path.Combine(outputDirectory, "exheader.bin");
+ UpdateTB(TB_Progress, "Extracting exheader.bin from CXI...");
+ byte[] exheaderbytes = new byte[Header.ExheaderSize * 2];
+
+ using (var fs = new FileStream(NCCH_PATH, FileMode.Open, FileAccess.Read))
+ {
+ fs.Seek(Convert.ToInt32(0x200), SeekOrigin.Begin);
+ _ = fs.Read(exheaderbytes, 0, exheaderbytes.Length);
+ }
+
+ File.WriteAllBytes(exheaderpath, exheaderbytes);
+ Exheader = new Exheader(exheaderpath);
+ }
+
+ private void ExtractExeFS(string NCCH_PATH, string outputDirectory, RichTextBox TB_Progress = null)
+ {
+ string exefsbinpath = Path.Combine(outputDirectory, "exefs.bin");
+ string exefspath = Path.Combine(outputDirectory, "exefs");
+ UpdateTB(TB_Progress, "Extracting exefs.bin from CXI...");
+ byte[] exefsbytes = new byte[Header.ExefsSize * MEDIA_UNIT_SIZE];
+
+ using (var fs = new FileStream(NCCH_PATH, FileMode.Open, FileAccess.Read))
+ {
+ fs.Seek(Convert.ToInt32(Header.ExefsOffset * MEDIA_UNIT_SIZE), SeekOrigin.Begin);
+ _ = fs.Read(exefsbytes, 0, exefsbytes.Length);
+ }
+
+ File.WriteAllBytes(exefsbinpath, exefsbytes);
+ ExeFS.UnpackExeFS(exefsbinpath, exefspath);
+ File.Delete(exefsbinpath);
+ }
+
+ private void ExtractRomFS(string NCCH_PATH, string outputDirectory, RichTextBox TB_Progress = null, ProgressBar PB_Show = null)
+ {
+ UpdateTB(TB_Progress, "Extracting romfs.bin from CXI...");
+ string romfsbinpath = Path.Combine(outputDirectory, "romfs.bin");
+ string romfspath = Path.Combine(outputDirectory, "romfs");
+ byte[] romfsBytes = new byte[MEDIA_UNIT_SIZE];
+
+ using (FileStream ncchstream = new(NCCH_PATH, FileMode.Open, FileAccess.Read),
+ romfsstream = new(romfsbinpath, FileMode.Append, FileAccess.Write))
+ {
+ ncchstream.Seek(Convert.ToInt32(Header.RomfsOffset * MEDIA_UNIT_SIZE), SeekOrigin.Begin);
+ if (PB_Show.InvokeRequired)
+ {
+ PB_Show.Invoke((MethodInvoker)delegate { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = Convert.ToInt32(Header.RomfsSize); });
+ }
+ else { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = Convert.ToInt32(Header.RomfsSize); }
+ for (int i = 0; i < Header.RomfsSize; i++)
+ {
+ _ = ncchstream.Read(romfsBytes, 0, romfsBytes.Length);
+ romfsstream.Write(romfsBytes, 0, romfsBytes.Length);
+ if (PB_Show.InvokeRequired)
{
- Array.Copy(BitConverter.GetBytes(val), 0, Data, ofs, 4);
- ofs += 4;
+ PB_Show.Invoke((MethodInvoker)PB_Show.PerformStep);
}
- Array.Copy(ExefsHash, 0, Data, 0x1C0, 0x20);
- Array.Copy(RomfsHash, 0, Data, 0x1E0, 0x20);
+ else { PB_Show.PerformStep(); }
+ }
+ }
+
+ var romfs = new RomFS(romfsbinpath);
+ romfs.ExtractRomFS(romfspath, TB_Progress, PB_Show);
+ File.Delete(romfsbinpath);
+ }
+
+ public void WriteHeaderToFile(string outputDirectory, RichTextBox TB_Progress)
+ {
+ UpdateTB(TB_Progress, "Extracting ncchheader.bin from CXI...");
+ string headerParth = Path.Combine(outputDirectory, "ncchheader.bin");
+ using FileStream headerStream = new(headerParth, FileMode.OpenOrCreate, FileAccess.Write);
+ headerStream.Write(Header.Data, 0, Header.Data.Length);
+ }
+
+ public void WritePlainRegionAndLogo(string outputDirectory, RichTextBox TB_Progress)
+ {
+ string plainRegionPath = Path.Combine(outputDirectory, "plain.bin");
+ string logoPath = Path.Combine(outputDirectory, "logo.bcma.lz");
+ UpdateTB(TB_Progress, "Extracting plain.bin and logo.bcma.lz from CXI...");
+ using FileStream plainStream = new(plainRegionPath, FileMode.OpenOrCreate, FileAccess.Write);
+ using FileStream logoStream = new(logoPath, FileMode.OpenOrCreate, FileAccess.Write);
+ plainStream.Write(plainregion, 0, plainregion.Length);
+ logoStream.Write(logo, 0, logo.Length);
+ }
+
+ internal static void UpdateTB(RichTextBox RTB, string progress)
+ {
+ try
+ {
+ if (RTB.InvokeRequired)
+ {
+ RTB.Invoke((MethodInvoker)delegate
+ {
+ RTB.AppendText(Environment.NewLine + progress);
+ RTB.SelectionStart = RTB.Text.Length;
+ RTB.ScrollToCaret();
+ });
+ }
+ else
+ {
+ RTB.SelectionStart = RTB.Text.Length;
+ RTB.ScrollToCaret();
+ RTB.AppendText(progress + Environment.NewLine);
}
}
+ catch { }
}
-}
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/NCSD.cs b/pk3DS.Core/CTR/NCSD.cs
index e3715246cc..9de237f611 100644
--- a/pk3DS.Core/CTR/NCSD.cs
+++ b/pk3DS.Core/CTR/NCSD.cs
@@ -1,110 +1,216 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
+using System.Windows.Forms;
-namespace pk3DS.Core.CTR
+namespace pk3DS.Core.CTR;
+
+public class NCSD
{
- public class NCSD
+ public NCSDHeader Header;
+ public CardInfoHeader cardinfoheader;
+ public List NCCH_Array;
+ public bool Card2;
+ public byte[] Data;
+
+ public class NCSDHeader
+ {
+ public byte[] Signature; //Size 0x100;
+ public uint Magic;
+ public uint MediaSize;
+ public ulong TitleId;
+ //public byte[] padding; //Size: 0x10
+ public NCCH_Meta[] OffsetSizeTable; //Size: 8
+ //public byte[] padding; //Size: 0x28
+ public byte[] flags; //Size: 0x8
+ public ulong[] NCCHIdTable; //Size: 0x8;
+ //public byte[] Padding2; //Size: 0x30;
+ }
+
+ public class CardInfoHeader
+ {
+ public uint WritableAddress;
+ public uint CardInfoBitmask;
+ public CardInfoNotes CIN;
+ public ulong NCCH0TitleId;
+ public ulong Reserved0;
+ public byte[] InitialData; // Size: 0x30
+ public byte[] Reserved1; // Size: 0xC0
+ public byte[] NCCH0Header; // Size: 0x100
+
+ public class CardInfoNotes
+ {
+ public byte[] Reserved0; // Size: 0xF8;
+ public ulong MediaSizeUsed;
+ public ulong Reserved1;
+ public uint Unknown;
+ public byte[] Reserved2; //Size: 0xC;
+ public ulong CVerTitleId;
+ public ushort CVerTitleVersion;
+ public byte[] Reserved3; //Size: 0xCD6;
+ }
+ }
+
+ public class NCCH_Meta
+ {
+ public uint Offset;
+ public uint Size;
+ }
+
+ private const ulong MEDIA_UNIT_SIZE = 0x200;
+
+ public ulong GetWritableAddress()
{
- public Header header;
- public CardInfoHeader cardinfoheader;
- public List NCCH_Array;
- public bool Card2;
- public byte[] Data;
+ return Card2
+ ? Align((Header.OffsetSizeTable[NCCH_Array.Count - 1].Offset * NCCH.MEDIA_UNIT_SIZE)
+ + (Header.OffsetSizeTable[NCCH_Array.Count - 1].Size * NCCH.MEDIA_UNIT_SIZE) + 0x1000, 0x10000) / MEDIA_UNIT_SIZE
+ : 0x00000000FFFFFFFF;
+ }
- public class Header
+ public void BuildHeader()
+ {
+ Data = new byte[0x4000];
+ Array.Copy(Header.Signature, Data, 0x100);
+ Array.Copy(BitConverter.GetBytes(Header.Magic), 0, Data, 0x100, 4);
+ Array.Copy(BitConverter.GetBytes(Header.MediaSize), 0, Data, 0x104, 4);
+ Array.Copy(BitConverter.GetBytes(Header.TitleId), 0, Data, 0x108, 8);
+ for (int i = 0; i < Header.OffsetSizeTable.Length; i++)
+ {
+ Array.Copy(BitConverter.GetBytes(Header.OffsetSizeTable[i].Offset), 0, Data, 0x120 + (8 * i), 4);
+ Array.Copy(BitConverter.GetBytes(Header.OffsetSizeTable[i].Size), 0, Data, 0x124 + (8 * i), 4);
+ }
+ Array.Copy(Header.flags, 0, Data, 0x188, Header.flags.Length);
+ for (int i = 0; i < Header.NCCHIdTable.Length; i++)
{
- public byte[] Signature; //Size 0x100;
- public uint Magic;
- public uint MediaSize;
- public ulong TitleId;
- //public byte[] padding; //Size: 0x10
- public NCCH_Meta[] OffsetSizeTable; //Size: 8
- //public byte[] padding; //Size: 0x28
- public byte[] flags; //Size: 0x8
- public ulong[] NCCHIdTable; //Size: 0x8;
- //public byte[] Padding2; //Size: 0x30;
+ Array.Copy(BitConverter.GetBytes(Header.NCCHIdTable[i]), 0, Data, 0x190 + (8 * i), 8);
}
- public class CardInfoHeader
+ //CardInfoHeader
+ Array.Copy(BitConverter.GetBytes(cardinfoheader.WritableAddress), 0, Data, 0x200, 4);
+ Array.Copy(BitConverter.GetBytes(cardinfoheader.CardInfoBitmask), 0, Data, 0x204, 4);
+ Array.Copy(cardinfoheader.CIN.Reserved0, 0, Data, 0x208, cardinfoheader.CIN.Reserved0.Length);
+ Array.Copy(BitConverter.GetBytes(cardinfoheader.CIN.MediaSizeUsed), 0, Data, 0x300, 8);
+ Array.Copy(BitConverter.GetBytes(cardinfoheader.CIN.Reserved1), 0, Data, 0x308, 8);
+ Array.Copy(BitConverter.GetBytes(cardinfoheader.CIN.Unknown), 0, Data, 0x310, 4);
+ Array.Copy(cardinfoheader.CIN.Reserved2, 0, Data, 0x314, cardinfoheader.CIN.Reserved2.Length);
+ Array.Copy(BitConverter.GetBytes(cardinfoheader.CIN.CVerTitleId), 0, Data, 0x320, 8);
+ Array.Copy(BitConverter.GetBytes(cardinfoheader.CIN.CVerTitleVersion), 0, Data, 0x328, 2);
+ Array.Copy(cardinfoheader.CIN.Reserved3, 0, Data, 0x32A, cardinfoheader.CIN.Reserved3.Length);
+ Array.Copy(BitConverter.GetBytes(cardinfoheader.NCCH0TitleId), 0, Data, 0x1000, 8);
+ Array.Copy(BitConverter.GetBytes(cardinfoheader.Reserved0), 0, Data, 0x1008, 8);
+ Array.Copy(cardinfoheader.InitialData, 0, Data, 0x1010, cardinfoheader.InitialData.Length);
+ Array.Copy(cardinfoheader.Reserved1, 0, Data, 0x1040, cardinfoheader.Reserved1.Length);
+ Array.Copy(cardinfoheader.NCCH0Header, 0, Data, 0x1100, cardinfoheader.NCCH0Header.Length);
+ Array.Copy(Enumerable.Repeat((byte)0xFF, 0x2E00).ToArray(), 0, Data, 0x1200, 0x2E00);
+ }
+
+ public NCSDHeader CreateHeaderFromBytes(byte[] data)
+ {
+ Data = data;
+ var header = new NCSDHeader
+ {
+ Signature = new byte[0x100],
+ Magic = BitConverter.ToUInt32(data, 0x100),
+ MediaSize = BitConverter.ToUInt32(data, 0x104),
+ TitleId = BitConverter.ToUInt64(data, 0x108),
+ OffsetSizeTable = new NCCH_Meta[8],
+ };
+ Array.Copy(data, header.Signature, 0x100);
+ for (int i = 0; i < 8; i++)
{
- public uint WritableAddress;
- public uint CardInfoBitmask;
- public CardInfoNotes CIN;
- public ulong NCCH0TitleId;
- public ulong Reserved0;
- public byte[] InitialData; // Size: 0x30
- public byte[] Reserved1; // Size: 0xC0
- public byte[] NCCH0Header; // Size: 0x100
-
- public class CardInfoNotes
+ header.OffsetSizeTable[i] = new NCCH_Meta
{
- public byte[] Reserved0; // Size: 0xF8;
- public ulong MediaSizeUsed;
- public ulong Reserved1;
- public uint Unknown;
- public byte[] Reserved2; //Size: 0xC;
- public ulong CVerTitleId;
- public ushort CVerTitleVersion;
- public byte[] Reserved3; //Size: 0xCD6;
- }
+ Offset = BitConverter.ToUInt32(data, 0x120 + (8 * i)),
+ Size = BitConverter.ToUInt32(data, 0x124 + (8 * i)),
+ };
}
- public class NCCH_Meta
+ header.flags = new byte[8];
+ Array.Copy(data, 0x188, header.flags, 0, 8);
+ header.NCCHIdTable = new ulong[8];
+ for (int i = 0; i < 8; i++)
{
- public uint Offset;
- public uint Size;
+ header.NCCHIdTable[i] = BitConverter.ToUInt64(data, 0x190 + (8 * i));
+ }
+ return header;
+ }
+
+ public void ExtractFilesFromNCSD(string NCSD_PATH, string outputDirectory, RichTextBox TB_Progress = null, ProgressBar PB_Show = null)
+ {
+ if (!Directory.Exists(outputDirectory))
+ Directory.CreateDirectory(outputDirectory);
+
+ UpdateTB(TB_Progress, "Extracting game data (CXI) from .3DS file...");
+ byte[] headerBytes = new byte[0x200];
+ using (var fs = new FileStream(NCSD_PATH, FileMode.Open, FileAccess.Read))
+ {
+ _ = fs.Read(headerBytes, 0, headerBytes.Length);
}
- public ulong GetWritableAddress()
+ Header = CreateHeaderFromBytes(headerBytes);
+ string ncchPath = ExtractCXIfromNCSD(NCSD_PATH, outputDirectory, Header.OffsetSizeTable[0].Size, PB_Show);
+ UpdateTB(TB_Progress, "CXI extracted, extracting files from CXI...");
+ var ncch = new NCCH();
+ ncch.ExtractNCCHFromFile(ncchPath, outputDirectory, TB_Progress, PB_Show);
+ File.Delete(ncchPath);
+ }
+
+ private static string ExtractCXIfromNCSD(string NCSD_PATH, string outputDirectory, uint ncchSize, ProgressBar PB_Show = null)
+ {
+ byte[] buffer = new byte[MEDIA_UNIT_SIZE * 10];
+ string outputFile = Path.Combine(outputDirectory, "game.cxi");
+ if (PB_Show.InvokeRequired)
{
- const ulong MEDIA_UNIT_SIZE = 0x200;
- return Card2
- ? Align(header.OffsetSizeTable[NCCH_Array.Count - 1].Offset * NCCH.MEDIA_UNIT_SIZE
- + header.OffsetSizeTable[NCCH_Array.Count - 1].Size * NCCH.MEDIA_UNIT_SIZE + 0x1000, 0x10000) / MEDIA_UNIT_SIZE
- : 0x00000000FFFFFFFF;
+ PB_Show.Invoke((MethodInvoker)delegate { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = Convert.ToInt32(ncchSize); });
}
- public void BuildHeader()
+ else { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = Convert.ToInt32(ncchSize); }
+
+ using FileStream inputFileStream = new(NCSD_PATH, FileMode.Open, FileAccess.Read),
+ outputFileStream = new(outputFile, FileMode.Append, FileAccess.Write);
+ inputFileStream.Seek(0x4000, SeekOrigin.Begin);
+ for (int i = 0; i < ncchSize; i++)
{
- Data = new byte[0x4000];
- Array.Copy(header.Signature, Data, 0x100);
- Array.Copy(BitConverter.GetBytes(header.Magic), 0, Data, 0x100, 4);
- Array.Copy(BitConverter.GetBytes(header.MediaSize), 0, Data, 0x104, 4);
- Array.Copy(BitConverter.GetBytes(header.TitleId), 0, Data, 0x108, 8);
- for (int i = 0; i < header.OffsetSizeTable.Length; i++)
- {
- Array.Copy(BitConverter.GetBytes(header.OffsetSizeTable[i].Offset), 0, Data, 0x120 + 8 * i, 4);
- Array.Copy(BitConverter.GetBytes(header.OffsetSizeTable[i].Size), 0, Data, 0x124 + 8 * i, 4);
- }
- Array.Copy(header.flags, 0, Data, 0x188, header.flags.Length);
- for (int i = 0; i < header.NCCHIdTable.Length; i++)
+ inputFileStream.Read(buffer, 0, buffer.Length);
+ outputFileStream.Write(buffer, 0, buffer.Length);
+ if (PB_Show.InvokeRequired)
{
- Array.Copy(BitConverter.GetBytes(header.NCCHIdTable[i]), 0, Data, 0x190 + 8 * i, 8);
+ PB_Show.Invoke((MethodInvoker)PB_Show.PerformStep);
}
- //CardInfoHeader
- Array.Copy(BitConverter.GetBytes(cardinfoheader.WritableAddress), 0, Data, 0x200, 4);
- Array.Copy(BitConverter.GetBytes(cardinfoheader.CardInfoBitmask), 0, Data, 0x204, 4);
- Array.Copy(cardinfoheader.CIN.Reserved0, 0, Data, 0x208, cardinfoheader.CIN.Reserved0.Length);
- Array.Copy(BitConverter.GetBytes(cardinfoheader.CIN.MediaSizeUsed), 0, Data, 0x300, 8);
- Array.Copy(BitConverter.GetBytes(cardinfoheader.CIN.Reserved1), 0, Data, 0x308, 8);
- Array.Copy(BitConverter.GetBytes(cardinfoheader.CIN.Unknown), 0, Data, 0x310, 4);
- Array.Copy(cardinfoheader.CIN.Reserved2, 0, Data, 0x314, cardinfoheader.CIN.Reserved2.Length);
- Array.Copy(BitConverter.GetBytes(cardinfoheader.CIN.CVerTitleId), 0, Data, 0x320, 8);
- Array.Copy(BitConverter.GetBytes(cardinfoheader.CIN.CVerTitleVersion), 0, Data, 0x328, 2);
- Array.Copy(cardinfoheader.CIN.Reserved3, 0, Data, 0x32A, cardinfoheader.CIN.Reserved3.Length);
- Array.Copy(BitConverter.GetBytes(cardinfoheader.NCCH0TitleId), 0, Data, 0x1000, 8);
- Array.Copy(BitConverter.GetBytes(cardinfoheader.Reserved0), 0, Data, 0x1008, 8);
- Array.Copy(cardinfoheader.InitialData, 0, Data, 0x1010, cardinfoheader.InitialData.Length);
- Array.Copy(cardinfoheader.Reserved1, 0, Data, 0x1040, cardinfoheader.Reserved1.Length);
- Array.Copy(cardinfoheader.NCCH0Header, 0, Data, 0x1100, cardinfoheader.NCCH0Header.Length);
- Array.Copy(Enumerable.Repeat((byte)0xFF, 0x2E00).ToArray(), 0, Data, 0x1200, 0x2E00);
+ else { PB_Show.PerformStep(); }
}
- internal static ulong Align(ulong input, ulong alignsize)
+
+ return outputFile;
+ }
+
+ internal static ulong Align(ulong input, ulong alignsize)
+ {
+ ulong output = input;
+ if (output % alignsize != 0)
{
- ulong output = input;
- if (output % alignsize != 0)
+ output += alignsize - (output % alignsize);
+ }
+ return output;
+ }
+
+ internal static void UpdateTB(RichTextBox RTB, string progress)
+ {
+ try
+ {
+ if (RTB.InvokeRequired)
+ {
+ RTB.Invoke((MethodInvoker)delegate
+ {
+ RTB.AppendText(Environment.NewLine + progress);
+ RTB.SelectionStart = RTB.Text.Length;
+ RTB.ScrollToCaret();
+ });
+ }
+ else
{
- output += alignsize - output % alignsize;
+ RTB.SelectionStart = RTB.Text.Length;
+ RTB.ScrollToCaret();
+ RTB.AppendText(progress + Environment.NewLine);
}
- return output;
}
+ catch { }
}
-}
+}
\ No newline at end of file
diff --git a/pk3DS.Core/CTR/RomFS.cs b/pk3DS.Core/CTR/RomFS.cs
index f66c860bb9..1143b19b58 100644
--- a/pk3DS.Core/CTR/RomFS.cs
+++ b/pk3DS.Core/CTR/RomFS.cs
@@ -5,785 +5,1025 @@
using System.Text;
using System.Windows.Forms;
-namespace pk3DS.Core.CTR
+namespace pk3DS.Core.CTR;
+
+public class RomFS
{
- public class RomFS
+ // Get Info
+ public readonly string FileName;
+ public readonly bool isTempFile;
+ public readonly byte[] SuperBlockHash;
+ public readonly uint SuperBlockLen;
+
+ public RomFS(string fn)
{
- // Get Info
- public readonly string FileName;
- public readonly bool isTempFile;
- public readonly byte[] SuperBlockHash;
- public readonly uint SuperBlockLen;
+ FileName = fn;
+ isTempFile = true;
+ using var fs = File.OpenRead(fn);
+ fs.Seek(0x8, SeekOrigin.Begin);
+ uint mhlen = (uint)(fs.ReadByte() | (fs.ReadByte() << 8) | (fs.ReadByte() << 16) | (fs.ReadByte() << 24));
+ SuperBlockLen = mhlen + 0x50;
+ if (SuperBlockLen % 0x200 != 0)
+ SuperBlockLen += 0x200 - (SuperBlockLen % 0x200);
+ byte[] superblock = new byte[SuperBlockLen];
+ fs.Seek(0, SeekOrigin.Begin);
+ fs.Read(superblock, 0, superblock.Length);
+ SuperBlockHash = SHA256.HashData(superblock);
+ }
- public RomFS(string fn)
+ // Build
+ internal const int PADDING_ALIGN = 16;
+ internal static string ROOT_DIR;
+ internal const string TempFile = "tempRomFS.bin";
+ internal static string OutFile;
+ internal const uint ROMFS_UNUSED_ENTRY = 0xFFFFFFFF;
+
+ internal static void UpdateTB(RichTextBox RTB, string progress)
+ {
+ try
{
- FileName = fn;
- isTempFile = true;
- using (var fs = File.OpenRead(fn))
+ if (RTB.InvokeRequired)
{
- fs.Seek(0x8, SeekOrigin.Begin);
- uint mhlen = (uint)(fs.ReadByte() | (fs.ReadByte() << 8) | (fs.ReadByte() << 16) | (fs.ReadByte() << 24));
- SuperBlockLen = mhlen + 0x50;
- if (SuperBlockLen % 0x200 != 0)
- SuperBlockLen += 0x200 - SuperBlockLen % 0x200;
- byte[] superblock = new byte[SuperBlockLen];
- fs.Seek(0, SeekOrigin.Begin);
- fs.Read(superblock, 0, superblock.Length);
- using (SHA256 sha = SHA256.Create())
+ RTB.Invoke((MethodInvoker)delegate
{
- SuperBlockHash = sha.ComputeHash(superblock);
- }
+ RTB.AppendText(Environment.NewLine + progress);
+ RTB.SelectionStart = RTB.Text.Length;
+ RTB.ScrollToCaret();
+ });
+ }
+ else
+ {
+ RTB.SelectionStart = RTB.Text.Length;
+ RTB.ScrollToCaret();
+ RTB.AppendText(progress + Environment.NewLine);
}
}
+ catch { }
+ }
- // Build
- internal const int PADDING_ALIGN = 16;
- internal static string ROOT_DIR;
- internal const string TempFile = "tempRomFS.bin";
- internal static string OutFile;
- internal const uint ROMFS_UNUSED_ENTRY = 0xFFFFFFFF;
+ public void ExtractRomFS(string outputDirectory, RichTextBox TB_Progress = null, ProgressBar PB_Show = null)
+ {
+ byte[] ivfcHeaderBytes = new byte[0x5C];
+ using (var file = new FileStream(FileName, FileMode.Open, FileAccess.Read))
+ {
+ _ = file.Read(ivfcHeaderBytes, 0, ivfcHeaderBytes.Length);
+ }
+ var ivfc = GetIVFCInfoFromBytes(ivfcHeaderBytes);
- internal static void updateTB(RichTextBox RTB, string progress)
+ ulong romfsDataOffset = Align(ivfc.Levels[0].HashOffset + ivfc.MasterHashSize, ivfc.Levels[2].BlockSize);
+ byte[] romfsInfoHeaderBytes = new byte[0x28];
+ using (var file = new FileStream(FileName, FileMode.Open, FileAccess.Read))
{
- try
- {
- if (RTB.InvokeRequired)
- RTB.Invoke((MethodInvoker)delegate
- {
- RTB.AppendText(Environment.NewLine + progress);
- RTB.SelectionStart = RTB.Text.Length;
- RTB.ScrollToCaret();
- });
- else
- {
- RTB.SelectionStart = RTB.Text.Length;
- RTB.ScrollToCaret();
- RTB.AppendText(progress + Environment.NewLine);
- }
- }
- catch { }
+ file.Seek(Convert.ToInt64(romfsDataOffset), SeekOrigin.Begin);
+ _ = file.Read(romfsInfoHeaderBytes, 0, romfsInfoHeaderBytes.Length);
}
- public static void BuildRomFS(string infile, string outfile, RichTextBox TB_Progress = null, ProgressBar PB_Show = null)
+ Romfs_InfoHeader infoHeader = GetRomfsInfoHeaderFromBytes(romfsInfoHeaderBytes, Convert.ToUInt32(romfsDataOffset));
+
+ byte[] directoryMetadataBlock = new byte[infoHeader.Sections[1].Size];
+ byte[] fileMetadataBlock = new byte[infoHeader.Sections[3].Size];
+ using (var file = new FileStream(FileName, FileMode.Open, FileAccess.Read))
{
- OutFile = outfile;
- ROOT_DIR = infile;
- if (File.Exists(TempFile)) File.Delete(TempFile);
+ file.Seek(Convert.ToInt64(infoHeader.Sections[1].Offset), SeekOrigin.Begin);
+ _ = file.Read(directoryMetadataBlock, 0, directoryMetadataBlock.Length);
+
+ file.Seek(Convert.ToInt64(infoHeader.Sections[3].Offset), SeekOrigin.Begin);
+ _ = file.Read(fileMetadataBlock, 0, fileMetadataBlock.Length);
+ }
- FileNameTable FNT = new FileNameTable(ROOT_DIR);
- RomfsFile[] RomFiles = new RomfsFile[FNT.NumFiles];
- LayoutManager.Input[] In = new LayoutManager.Input[FNT.NumFiles];
- updateTB(TB_Progress, "Creating Layout...");
- for (int i = 0; i < FNT.NumFiles; i++)
+ if (!Directory.Exists(outputDirectory))
+ {
+ Directory.CreateDirectory(outputDirectory);
+ }
+
+ VisitDirectory(0, outputDirectory, directoryMetadataBlock, fileMetadataBlock, infoHeader.DataOffset, TB_Progress, PB_Show);
+ }
+
+ private static IVFCInfo GetIVFCInfoFromBytes(byte[] headerBytes)
+ {
+ var ivfc = new IVFCInfo();
+ uint magic1 = BitConverter.ToUInt32(headerBytes, 0x00);
+ uint magic2 = BitConverter.ToUInt32(headerBytes, 0x04);
+ if (magic1 != 0x43465649 || magic2 != 0x10000)
+ {
+ throw new ArgumentException("Bad IVFC Header");
+ }
+ ivfc.MasterHashSize = BitConverter.ToUInt32(headerBytes, 0x08);
+ ivfc.Levels = new IVFCLevel[3];
+ for (int i = 0; i < 3; i++)
+ {
+ ivfc.Levels[i] = new IVFCLevel
{
- In[i] = new LayoutManager.Input { FilePath = FNT.NameEntryTable[i].FullName, AlignmentSize = 0x10 };
- }
- LayoutManager.Output[] Out = LayoutManager.Create(In);
- for (int i = 0; i < Out.Length; i++)
+ HashOffset = BitConverter.ToUInt64(headerBytes, 0x0C + (i * 0x18)),
+ DataLength = BitConverter.ToUInt64(headerBytes, 0x14 + (i * 0x18)),
+ BlockSize = 1U << BitConverter.ToInt32(headerBytes, 0x1C + (i * 0x18)),
+ };
+ }
+ return ivfc;
+ }
+
+ private static Romfs_InfoHeader GetRomfsInfoHeaderFromBytes(byte[] headerBytes, uint bodyOffset)
+ {
+ var infoHeader = new Romfs_InfoHeader
+ {
+ HeaderLength = BitConverter.ToUInt32(headerBytes, 0x00),
+ Sections = new Romfs_SectionHeader[4],
+ };
+ for (int i = 0; i < 4; i++)
+ {
+ infoHeader.Sections[i] = new Romfs_SectionHeader
{
- RomFiles[i] = new RomfsFile
- {
- Offset = Out[i].Offset,
- PathName = Out[i].FilePath.Replace(Path.GetFullPath(ROOT_DIR), "").Replace("\\", "/"),
- FullName = Out[i].FilePath,
- Size = Out[i].Size
- };
- }
- using (MemoryStream memoryStream = new MemoryStream())
+ Offset = BitConverter.ToUInt32(headerBytes, 0x04 + (i * 0x08)) + bodyOffset,
+ Size = BitConverter.ToUInt32(headerBytes, 0x08 + (i * 0x08)),
+ };
+ }
+ infoHeader.DataOffset = BitConverter.ToUInt32(headerBytes, 0x24) + bodyOffset;
+ return infoHeader;
+ }
+
+ private void VisitDirectory(
+ uint directoryOffset,
+ string rootPath,
+ byte[] directoryMetadataBlock,
+ byte[] fileMetadataBlock,
+ ulong dataOffset,
+ RichTextBox TB_Progress = null,
+ ProgressBar PB_Show = null)
+ {
+ Romfs_DirEntry entry = GetDirEntryFromMetadataBytes(directoryMetadataBlock, Convert.ToInt32(directoryOffset));
+
+ string currentPath = Path.Combine(rootPath, entry.Name);
+ Directory.CreateDirectory(currentPath);
+
+ if (entry.FileOffset != 0xFFFFFFFF)
+ {
+ VisitFile(entry.FileOffset, currentPath, fileMetadataBlock, dataOffset, TB_Progress, PB_Show);
+ }
+
+ if (entry.ChildOffset != 0xFFFFFFFF)
+ {
+ VisitDirectory(entry.ChildOffset, currentPath, directoryMetadataBlock, fileMetadataBlock, dataOffset, TB_Progress, PB_Show);
+ }
+
+ if (entry.SiblingOffset != 0xFFFFFFFF)
+ {
+ VisitDirectory(entry.SiblingOffset, rootPath, directoryMetadataBlock, fileMetadataBlock, dataOffset, TB_Progress, PB_Show);
+ }
+ }
+
+ private void VisitFile(
+ uint fileOffset,
+ string rootPath,
+ byte[] fileMetadataBlock,
+ ulong dataOffset,
+ RichTextBox TB_Progress = null,
+ ProgressBar PB_Show = null)
+ {
+ Romfs_FileEntry entry = GetFileEntryFromMetadataBytes(fileMetadataBlock, Convert.ToInt32(fileOffset));
+ string currentPath = Path.Combine(rootPath, entry.Name);
+ UpdateTB_Progress($"Extracting {currentPath} from romfs", TB_Progress);
+ ExtractFileFromRomFS(entry, currentPath, dataOffset, PB_Show);
+
+ if (entry.SiblingOffset != 0xFFFFFFFF)
+ {
+ VisitFile(entry.SiblingOffset, rootPath, fileMetadataBlock, dataOffset, TB_Progress, PB_Show);
+ }
+ }
+
+ private static Romfs_DirEntry GetDirEntryFromMetadataBytes(byte[] directoryMetadataBlock, int directoryOffset)
+ {
+ var entry = new Romfs_DirEntry
+ {
+ ParentOffset = BitConverter.ToUInt32(directoryMetadataBlock, directoryOffset),
+ SiblingOffset = BitConverter.ToUInt32(directoryMetadataBlock, directoryOffset + 0x04),
+ ChildOffset = BitConverter.ToUInt32(directoryMetadataBlock, directoryOffset + 0x08),
+ FileOffset = BitConverter.ToUInt32(directoryMetadataBlock, directoryOffset + 0x0C),
+ };
+ uint nameLength = BitConverter.ToUInt32(directoryMetadataBlock, directoryOffset + 0x14);
+ entry.Name = "";
+ if (nameLength != 0xFFFFFFFF)
+ {
+ byte[] fileNameBytes = new byte[nameLength];
+ Array.Copy(directoryMetadataBlock, directoryOffset + 0x18, fileNameBytes, 0, fileNameBytes.Length);
+ entry.Name = Encoding.Unicode.GetString(fileNameBytes);
+ }
+ return entry;
+ }
+
+ private static Romfs_FileEntry GetFileEntryFromMetadataBytes(byte[] fileMetadataBlock, int fileOffset)
+ {
+ var entry = new Romfs_FileEntry
+ {
+ ParentDirOffset = BitConverter.ToUInt32(fileMetadataBlock, fileOffset),
+ SiblingOffset = BitConverter.ToUInt32(fileMetadataBlock, fileOffset + 0x04),
+ DataOffset = BitConverter.ToUInt64(fileMetadataBlock, fileOffset + 0x08),
+ DataSize = BitConverter.ToUInt64(fileMetadataBlock, fileOffset + 0x10),
+ NameSize = BitConverter.ToUInt32(fileMetadataBlock, fileOffset + 0x1C),
+ Name = "",
+ };
+ if (entry.NameSize != 0xFFFFFFFF)
+ {
+ byte[] fileNameBytes = new byte[entry.NameSize];
+ Array.Copy(fileMetadataBlock, fileOffset + 0x20, fileNameBytes, 0, fileNameBytes.Length);
+ entry.Name = Encoding.Unicode.GetString(fileNameBytes);
+ }
+ return entry;
+ }
+
+ private void ExtractFileFromRomFS(Romfs_FileEntry entry, string path, ulong dataOffset, ProgressBar PB_Show = null)
+ {
+ ulong offsetInRomFS = dataOffset + entry.DataOffset;
+ byte[] buffer = new byte[0x2000];
+
+ using FileStream romfsFileStream = new(FileName, FileMode.Open, FileAccess.Read),
+ outputFileStream = new(path, FileMode.Append, FileAccess.Write);
+ romfsFileStream.Seek(Convert.ToInt64(offsetInRomFS), SeekOrigin.Begin);
+ int remainingSize = Convert.ToInt32(entry.DataSize);
+ var max = remainingSize / buffer.Length;
+ if (PB_Show.InvokeRequired)
+ {
+ PB_Show.Invoke((MethodInvoker)delegate { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = max; });
+ }
+ else { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = max; }
+
+ while (remainingSize > 0)
+ {
+ int sizeToReadWrite = buffer.Length > remainingSize ? remainingSize : buffer.Length;
+ romfsFileStream.Read(buffer, 0, sizeToReadWrite);
+ outputFileStream.Write(buffer, 0, sizeToReadWrite);
+ remainingSize -= sizeToReadWrite;
+ if (PB_Show.InvokeRequired)
{
- updateTB(TB_Progress, "Creating RomFS MetaData...");
- BuildRomFSHeader(memoryStream, RomFiles, ROOT_DIR);
- MakeRomFSData(RomFiles, memoryStream, TB_Progress, PB_Show);
+ PB_Show.Invoke((MethodInvoker)PB_Show.PerformStep);
}
+ else { PB_Show.PerformStep(); }
}
+ }
- internal static ulong Align(ulong input, ulong alignsize)
+ public static void BuildRomFS(string infile, string outfile, RichTextBox TB_Progress = null, ProgressBar PB_Show = null)
+ {
+ OutFile = outfile;
+ ROOT_DIR = infile;
+ if (File.Exists(TempFile)) File.Delete(TempFile);
+
+ var FNT = new FileNameTable(ROOT_DIR);
+ var RomFiles = new RomfsFile[FNT.NumFiles];
+ var In = new LayoutManager.Input[FNT.NumFiles];
+ UpdateTB(TB_Progress, "Creating Layout...");
+ for (int i = 0; i < FNT.NumFiles; i++)
{
- ulong output = input;
- if (output % alignsize != 0)
+ In[i] = new LayoutManager.Input { FilePath = FNT.NameEntryTable[i].FullName, AlignmentSize = 0x10 };
+ }
+ var Out = LayoutManager.Create(In);
+ for (int i = 0; i < Out.Length; i++)
+ {
+ RomFiles[i] = new RomfsFile
{
- output += alignsize - output % alignsize;
- }
- return output;
+ Offset = Out[i].Offset,
+ PathName = Out[i].FilePath.Replace(Path.GetFullPath(ROOT_DIR), "").Replace("\\", "/"),
+ FullName = Out[i].FilePath,
+ Size = Out[i].Size,
+ };
+ }
+
+ using var memoryStream = new MemoryStream();
+ UpdateTB(TB_Progress, "Creating RomFS MetaData...");
+ BuildRomFSHeader(memoryStream, RomFiles, ROOT_DIR);
+ MakeRomFSData(RomFiles, memoryStream, TB_Progress, PB_Show);
+ }
+
+ internal static ulong Align(ulong input, ulong alignsize)
+ {
+ ulong output = input;
+ if (output % alignsize != 0)
+ {
+ output += alignsize - (output % alignsize);
}
- internal static void MakeRomFSData(RomfsFile[] RomFiles, MemoryStream metadata, RichTextBox TB_Progress = null, ProgressBar PB_Show = null)
+ return output;
+ }
+
+ internal static void MakeRomFSData(RomfsFile[] RomFiles, MemoryStream metadata, RichTextBox TB_Progress = null, ProgressBar PB_Show = null)
+ {
+ UpdateTB(TB_Progress, "Computing IVFC Header Data...");
+ var ivfc = new IVFCInfo { Levels = new IVFCLevel[3] };
+ for (int i = 0; i < ivfc.Levels.Length; i++)
{
- updateTB(TB_Progress, "Computing IVFC Header Data...");
- IVFCInfo ivfc = new IVFCInfo { Levels = new IVFCLevel[3] };
- for (int i = 0; i < ivfc.Levels.Length; i++)
+ ivfc.Levels[i] = new IVFCLevel { BlockSize = 0x1000 };
+ }
+ ivfc.Levels[2].DataLength = RomfsFile.GetDataBlockLength(RomFiles, (ulong)metadata.Length);
+ ivfc.Levels[1].DataLength = Align(ivfc.Levels[2].DataLength, ivfc.Levels[2].BlockSize) / ivfc.Levels[2].BlockSize * 0x20; //0x20 per SHA256 hash
+ ivfc.Levels[0].DataLength = Align(ivfc.Levels[1].DataLength, ivfc.Levels[1].BlockSize) / ivfc.Levels[1].BlockSize * 0x20; //0x20 per SHA256 hash
+ ulong MasterHashLen = Align(ivfc.Levels[0].DataLength, ivfc.Levels[0].BlockSize) / ivfc.Levels[0].BlockSize * 0x20;
+ ulong lofs = 0;
+ foreach (IVFCLevel t in ivfc.Levels)
+ {
+ t.HashOffset = lofs;
+ lofs += Align(t.DataLength, t.BlockSize);
+ }
+ const uint IVFC_MAGIC = 0x43465649; //IVFC
+ const uint RESERVED = 0x0;
+ const uint HeaderLen = 0x5C;
+ const uint MEDIA_UNIT_SIZE = 0x200;
+ var OutFileStream = new FileStream(TempFile, FileMode.Create, FileAccess.ReadWrite);
+ try
+ {
+ OutFileStream.Seek(0, SeekOrigin.Begin);
+ OutFileStream.Write(BitConverter.GetBytes(IVFC_MAGIC), 0, 0x4);
+ OutFileStream.Write(BitConverter.GetBytes(0x10000), 0, 0x4);
+ OutFileStream.Write(BitConverter.GetBytes(MasterHashLen), 0, 0x4);
+ foreach (IVFCLevel t in ivfc.Levels)
{
- ivfc.Levels[i] = new IVFCLevel { BlockSize = 0x1000 };
+ OutFileStream.Write(BitConverter.GetBytes(t.HashOffset), 0, 0x8);
+ OutFileStream.Write(BitConverter.GetBytes(t.DataLength), 0, 0x8);
+ OutFileStream.Write(BitConverter.GetBytes((int)Math.Log(t.BlockSize, 2)), 0, 0x4);
+ OutFileStream.Write(BitConverter.GetBytes(RESERVED), 0, 0x4);
}
- ivfc.Levels[2].DataLength = RomfsFile.GetDataBlockLength(RomFiles, (ulong)metadata.Length);
- ivfc.Levels[1].DataLength = Align(ivfc.Levels[2].DataLength, ivfc.Levels[2].BlockSize) / ivfc.Levels[2].BlockSize * 0x20; //0x20 per SHA256 hash
- ivfc.Levels[0].DataLength = Align(ivfc.Levels[1].DataLength, ivfc.Levels[1].BlockSize) / ivfc.Levels[1].BlockSize * 0x20; //0x20 per SHA256 hash
- ulong MasterHashLen = Align(ivfc.Levels[0].DataLength, ivfc.Levels[0].BlockSize) / ivfc.Levels[0].BlockSize * 0x20;
- ulong lofs = 0;
- foreach (IVFCLevel t in ivfc.Levels)
+ OutFileStream.Write(BitConverter.GetBytes(HeaderLen), 0, 0x4);
+ //IVFC Header is Written.
+ OutFileStream.Seek((long)Align(MasterHashLen + 0x60, ivfc.Levels[0].BlockSize), SeekOrigin.Begin);
+ byte[] metadataArray = metadata.ToArray();
+ OutFileStream.Write(metadataArray, 0, metadataArray.Length);
+ long baseOfs = OutFileStream.Position;
+ UpdateTB(TB_Progress, "Writing Level 2 Data...");
+ if (PB_Show.InvokeRequired)
{
- t.HashOffset = lofs;
- lofs += Align(t.DataLength, t.BlockSize);
+ PB_Show.Invoke((MethodInvoker)delegate { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = RomFiles.Length; });
}
- const uint IVFC_MAGIC = 0x43465649; //IVFC
- const uint RESERVED = 0x0;
- const uint HeaderLen = 0x5C;
- const uint MEDIA_UNIT_SIZE = 0x200;
- byte[] SuperBlockHash = new byte[0x20];
- FileStream OutFileStream = new FileStream(TempFile, FileMode.Create, FileAccess.ReadWrite);
- try
+ else { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = RomFiles.Length; }
+
+ foreach (RomfsFile t in RomFiles)
{
- OutFileStream.Seek(0, SeekOrigin.Begin);
- OutFileStream.Write(BitConverter.GetBytes(IVFC_MAGIC), 0, 0x4);
- OutFileStream.Write(BitConverter.GetBytes(0x10000), 0, 0x4);
- OutFileStream.Write(BitConverter.GetBytes(MasterHashLen), 0, 0x4);
- foreach (IVFCLevel t in ivfc.Levels)
+ OutFileStream.Seek(baseOfs + (long)t.Offset, SeekOrigin.Begin);
+ using (var inStream = new FileStream(t.FullName, FileMode.Open, FileAccess.Read))
{
- OutFileStream.Write(BitConverter.GetBytes(t.HashOffset), 0, 0x8);
- OutFileStream.Write(BitConverter.GetBytes(t.DataLength), 0, 0x8);
- OutFileStream.Write(BitConverter.GetBytes((int)Math.Log(t.BlockSize, 2)), 0, 0x4);
- OutFileStream.Write(BitConverter.GetBytes(RESERVED), 0, 0x4);
+ while (inStream.Position < inStream.Length)
+ {
+ byte[] buffer = new byte[inStream.Length - inStream.Position > 0x100000 ? 0x100000 : inStream.Length - inStream.Position];
+ _ = inStream.Read(buffer, 0, buffer.Length);
+ OutFileStream.Write(buffer, 0, buffer.Length);
+ }
}
- OutFileStream.Write(BitConverter.GetBytes(HeaderLen), 0, 0x4);
- //IVFC Header is Written.
- OutFileStream.Seek((long)Align(MasterHashLen + 0x60, ivfc.Levels[0].BlockSize), SeekOrigin.Begin);
- byte[] metadataArray = metadata.ToArray();
- OutFileStream.Write(metadataArray, 0, metadataArray.Length);
- long baseOfs = OutFileStream.Position;
- updateTB(TB_Progress, "Writing Level 2 Data...");
if (PB_Show.InvokeRequired)
- PB_Show.Invoke((MethodInvoker)delegate { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = RomFiles.Length; });
- else { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = RomFiles.Length; }
-
- foreach (RomfsFile t in RomFiles)
{
- OutFileStream.Seek(baseOfs + (long)t.Offset, SeekOrigin.Begin);
- using (FileStream inStream = new FileStream(t.FullName, FileMode.Open, FileAccess.Read))
- {
- while (inStream.Position < inStream.Length)
- {
- byte[] buffer = new byte[inStream.Length - inStream.Position > 0x100000 ? 0x100000 : inStream.Length - inStream.Position];
- inStream.Read(buffer, 0, buffer.Length);
- OutFileStream.Write(buffer, 0, buffer.Length);
- }
- }
- if (PB_Show.InvokeRequired)
- PB_Show.Invoke((MethodInvoker)PB_Show.PerformStep);
- else { PB_Show.PerformStep(); }
+ PB_Show.Invoke((MethodInvoker)PB_Show.PerformStep);
}
- long hashBaseOfs = (long)Align((ulong)OutFileStream.Position, ivfc.Levels[2].BlockSize);
- long hOfs = (long)Align(MasterHashLen, ivfc.Levels[0].BlockSize);
- long cOfs = hashBaseOfs + (long)ivfc.Levels[1].HashOffset;
- SHA256Managed sha = new SHA256Managed();
- for (int i = ivfc.Levels.Length - 1; i >= 0; i--)
+ else { PB_Show.PerformStep(); }
+ }
+ long hashBaseOfs = (long)Align((ulong)OutFileStream.Position, ivfc.Levels[2].BlockSize);
+ long hOfs = (long)Align(MasterHashLen, ivfc.Levels[0].BlockSize);
+ long cOfs = hashBaseOfs + (long)ivfc.Levels[1].HashOffset;
+ for (int i = ivfc.Levels.Length - 1; i >= 0; i--)
+ {
+ UpdateTB(TB_Progress, "Computing Level " + i + " Hashes...");
+ byte[] buffer = new byte[(int)ivfc.Levels[i].BlockSize];
+
+ var count = (int)(ivfc.Levels[i].DataLength / ivfc.Levels[i].BlockSize);
+ if (PB_Show.InvokeRequired)
{
- updateTB(TB_Progress, "Computing Level " + i + " Hashes...");
- byte[] buffer = new byte[(int)ivfc.Levels[i].BlockSize];
+ PB_Show.Invoke((MethodInvoker)delegate { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = count; });
+ }
+ else { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = count; }
- var count = (int) (ivfc.Levels[i].DataLength/ivfc.Levels[i].BlockSize);
+ for (long ofs = 0; ofs < (long)ivfc.Levels[i].DataLength; ofs += ivfc.Levels[i].BlockSize)
+ {
+ OutFileStream.Seek(hOfs, SeekOrigin.Begin);
+ OutFileStream.Read(buffer, 0, (int)ivfc.Levels[i].BlockSize);
+ hOfs = OutFileStream.Position;
+ byte[] hash = SHA256.HashData(buffer);
+ OutFileStream.Seek(cOfs, SeekOrigin.Begin);
+ OutFileStream.Write(hash, 0, hash.Length);
+ cOfs = OutFileStream.Position;
if (PB_Show.InvokeRequired)
- PB_Show.Invoke((MethodInvoker)delegate { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = count; });
- else { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = count; }
-
- for (long ofs = 0; ofs < (long)ivfc.Levels[i].DataLength; ofs += ivfc.Levels[i].BlockSize)
- {
- OutFileStream.Seek(hOfs, SeekOrigin.Begin);
- OutFileStream.Read(buffer, 0, (int)ivfc.Levels[i].BlockSize);
- hOfs = OutFileStream.Position;
- byte[] hash = sha.ComputeHash(buffer);
- OutFileStream.Seek(cOfs, SeekOrigin.Begin);
- OutFileStream.Write(hash, 0, hash.Length);
- cOfs = OutFileStream.Position;
- if (PB_Show.InvokeRequired)
- PB_Show.Invoke((MethodInvoker)PB_Show.PerformStep);
- else { PB_Show.PerformStep(); }
- }
-
- if (i <= 0)
- continue;
-
- if (i == 2)
{
- long len = OutFileStream.Position;
- if (len % 0x1000 != 0)
- {
- len = (long)Align((ulong)len, 0x1000);
- byte[] buf = new byte[len - OutFileStream.Position];
- OutFileStream.Write(buf, 0, buf.Length);
- }
+ PB_Show.Invoke((MethodInvoker)PB_Show.PerformStep);
}
-
- hOfs = hashBaseOfs + (long)ivfc.Levels[i - 1].HashOffset;
- if (i > 1)
- cOfs = hashBaseOfs + (long)ivfc.Levels[i - 2].HashOffset;
- else
- cOfs = (long)Align(HeaderLen, PADDING_ALIGN);
+ else { PB_Show.PerformStep(); }
}
- OutFileStream.Seek(0, SeekOrigin.Begin);
- uint SuperBlockLen = (uint)Align(MasterHashLen + 0x60, MEDIA_UNIT_SIZE);
- byte[] MasterHashes = new byte[SuperBlockLen];
- OutFileStream.Read(MasterHashes, 0, (int)SuperBlockLen);
- SuperBlockHash = sha.ComputeHash(MasterHashes);
- }
- finally
- {
- OutFileStream.Dispose();
- }
- if (OutFile == TempFile)
- return;
- if (File.Exists(OutFile)) File.Delete(OutFile);
- File.Move(TempFile, OutFile);
- }
- internal static void WriteBinary(string tempFile, string outFile, RichTextBox TB_Progress = null, ProgressBar PB_Show = null)
- {
- using (FileStream fs = new FileStream(outFile, FileMode.Create))
- {
- using (BinaryWriter writer = new BinaryWriter(fs))
+ if (i <= 0)
+ continue;
+
+ if (i == 2)
{
- using (FileStream fileStream = new FileStream(tempFile, FileMode.Open, FileAccess.Read))
+ long len = OutFileStream.Position;
+ if (len % 0x1000 != 0)
{
- const uint BUFFER_SIZE = 0x400000; // 4MB Buffer
- var steps = (int)(fileStream.Length / BUFFER_SIZE);
- if (PB_Show.InvokeRequired)
- PB_Show.Invoke((MethodInvoker)delegate { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = steps; });
- else { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = steps; }
-
- byte[] buffer = new byte[BUFFER_SIZE];
- while (true)
- {
- int count = fileStream.Read(buffer, 0, buffer.Length);
- if (count != 0)
- {
- writer.Write(buffer, 0, count);
- if (PB_Show.InvokeRequired)
- PB_Show.Invoke((MethodInvoker)PB_Show.PerformStep);
- else { PB_Show.PerformStep(); }
- }
- else
- break;
- }
+ len = (long)Align((ulong)len, 0x1000);
+ byte[] buf = new byte[len - OutFileStream.Position];
+ OutFileStream.Write(buf, 0, buf.Length);
}
- writer.Flush();
}
- }
- File.Delete(TempFile);
- updateTB(TB_Progress, "Wrote RomFS to path:" + Environment.NewLine + outFile);
- }
- internal static string ByteArrayToString(IEnumerable input)
- {
- StringBuilder sb = new StringBuilder();
- foreach (byte b in input)
- sb.Append(b.ToString("X2") + " ");
- return sb.ToString();
- }
-
- internal static void UpdateTB_Progress(string text, RichTextBox TB_Progress = null)
- {
- TB_Progress.Text += text + Environment.NewLine;
- }
- internal static void BuildRomFSHeader(MemoryStream romfs_stream, RomfsFile[] Entries, string DIR)
- {
- ROOT_DIR = DIR;
- Romfs_MetaData MetaData = new Romfs_MetaData();
+ hOfs = hashBaseOfs + (long)ivfc.Levels[i - 1].HashOffset;
+ if (i > 1)
+ cOfs = hashBaseOfs + (long)ivfc.Levels[i - 2].HashOffset;
+ else
+ cOfs = (long)Align(HeaderLen, PADDING_ALIGN);
+ }
+ OutFileStream.Seek(0, SeekOrigin.Begin);
+ uint SuperBlockLen = (uint)Align(MasterHashLen + 0x60, MEDIA_UNIT_SIZE);
+ byte[] MasterHashes = new byte[SuperBlockLen];
+ OutFileStream.Read(MasterHashes, 0, (int)SuperBlockLen);
- InitializeMetaData(MetaData);
- CalcRomfsSize(MetaData);
- PopulateRomfs(MetaData, Entries);
- WriteMetaDataToStream(MetaData, romfs_stream);
+ //var SuperBlockHash = sha.ComputeHash(MasterHashes);
+ //Console.WriteLine(SuperBlockHash);
}
- internal static void InitializeMetaData(Romfs_MetaData MetaData)
+ finally
{
- MetaData.InfoHeader = new Romfs_InfoHeader();
- MetaData.DirTable = new Romfs_DirTable();
- MetaData.DirTableLen = 0;
- MetaData.M_DirTableLen = 0;
- MetaData.FileTable = new Romfs_FileTable();
- MetaData.FileTableLen = 0;
- MetaData.DirTable.DirectoryTable = new List();
- MetaData.FileTable.FileTable = new List();
- MetaData.InfoHeader.HeaderLength = 0x28;
- MetaData.InfoHeader.Sections = new Romfs_SectionHeader[4];
- MetaData.DirHashTable = new List();
- MetaData.FileHashTable = new List();
+ OutFileStream.Dispose();
}
- internal static void CalcRomfsSize(Romfs_MetaData MetaData)
- {
- MetaData.DirNum = 1;
- DirectoryInfo Root_DI = new DirectoryInfo(ROOT_DIR);
- CalcDirSize(MetaData, Root_DI);
- MetaData.M_DirHashTableEntry = GetHashTableEntryCount(MetaData.DirNum);
- MetaData.M_FileHashTableEntry = GetHashTableEntryCount(MetaData.FileNum);
+ if (OutFile == TempFile)
+ return;
+ if (File.Exists(OutFile)) File.Delete(OutFile);
+ File.Move(TempFile, OutFile);
+ }
- uint MetaDataSize = (uint)Align(0x28 + MetaData.M_DirHashTableEntry * 4 + MetaData.M_DirTableLen + MetaData.M_FileHashTableEntry * 4 + MetaData.M_FileTableLen, PADDING_ALIGN);
- for (int i = 0; i < MetaData.M_DirHashTableEntry; i++)
- MetaData.DirHashTable.Add(ROMFS_UNUSED_ENTRY);
+ internal static void WriteBinary(string tempFile, string outFile, RichTextBox TB_Progress = null, ProgressBar PB_Show = null)
+ {
+ using var fs = new FileStream(outFile, FileMode.Create);
+ using var writer = new BinaryWriter(fs);
+ using var fileStream = new FileStream(tempFile, FileMode.Open, FileAccess.Read);
- for (int i = 0; i < MetaData.M_FileHashTableEntry; i++)
- MetaData.FileHashTable.Add(ROMFS_UNUSED_ENTRY);
+ const uint BUFFER_SIZE = 0x400000; // 4MB Buffer
+ var steps = (int)(fileStream.Length / BUFFER_SIZE);
+ if (PB_Show.InvokeRequired)
+ {
+ PB_Show.Invoke((MethodInvoker)delegate { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = steps; });
+ }
+ else { PB_Show.Minimum = 0; PB_Show.Step = 1; PB_Show.Value = 0; PB_Show.Maximum = steps; }
- uint Pos = MetaData.InfoHeader.HeaderLength;
- for (int i = 0; i < 4; i++)
+ byte[] buffer = new byte[BUFFER_SIZE];
+ while (true)
+ {
+ int count = fileStream.Read(buffer, 0, buffer.Length);
+ if (count != 0)
{
- MetaData.InfoHeader.Sections[i].Offset = Pos;
- uint size = 0;
- switch (i)
+ writer.Write(buffer, 0, count);
+ if (PB_Show.InvokeRequired)
{
- case 0:
- size = MetaData.M_DirHashTableEntry * 4;
- break;
- case 1:
- size = MetaData.M_DirTableLen;
- break;
- case 2:
- size = MetaData.M_FileHashTableEntry * 4;
- break;
- case 3:
- size = MetaData.M_FileTableLen;
- break;
+ PB_Show.Invoke((MethodInvoker)PB_Show.PerformStep);
}
- MetaData.InfoHeader.Sections[i].Size = size;
- Pos += size;
+ else { PB_Show.PerformStep(); }
}
- MetaData.InfoHeader.DataOffset = MetaDataSize;
- }
- internal static uint GetHashTableEntryCount(uint Entries)
- {
- uint count = Entries;
- if (Entries < 3)
- count = 3;
- else if (count < 19)
- count |= 1;
else
{
- while (count % 2 == 0 || count % 3 == 0 || count % 5 == 0 || count % 7 == 0 || count % 11 == 0 || count % 13 == 0 || count % 17 == 0)
- {
- count++;
- }
+ break;
}
- return count;
}
- internal static void CalcDirSize(Romfs_MetaData MetaData, DirectoryInfo dir)
- {
- if (MetaData.M_DirTableLen == 0)
- MetaData.M_DirTableLen = 0x18;
- else
- MetaData.M_DirTableLen += 0x18 + (uint)Align((ulong)dir.Name.Length * 2, 4);
- FileInfo[] files = dir.GetFiles();
- foreach (FileInfo t in files)
- MetaData.M_FileTableLen += 0x20 + (uint)Align((ulong)t.Name.Length * 2, 4);
+ writer.Flush();
+ File.Delete(TempFile);
+ UpdateTB(TB_Progress, "Wrote RomFS to path:" + Environment.NewLine + outFile);
+ }
- DirectoryInfo[] SubDirectories = dir.GetDirectories();
- foreach (DirectoryInfo t in SubDirectories)
- CalcDirSize(MetaData, t);
+ internal static string ByteArrayToString(IEnumerable input)
+ {
+ var sb = new StringBuilder();
+ foreach (byte b in input)
+ sb.Append(b.ToString("X2")).Append(' ');
+
+ return sb.ToString();
+ }
- MetaData.FileNum += (uint)files.Length;
- MetaData.DirNum += (uint)SubDirectories.Length;
+ internal static void UpdateTB_Progress(string text, RichTextBox TB_Progress = null)
+ {
+ if (TB_Progress.InvokeRequired)
+ {
+ TB_Progress.Invoke((MethodInvoker)delegate
+ {
+ TB_Progress.Text += text + Environment.NewLine;
+ });
}
- internal static void PopulateRomfs(Romfs_MetaData MetaData, RomfsFile[] Entries)
+ else
{
- //Recursively Add All Directories to DirectoryTable
- AddDir(MetaData, new DirectoryInfo(ROOT_DIR), 0, ROMFS_UNUSED_ENTRY);
+ TB_Progress.Text += text + Environment.NewLine;
+ }
+ }
- //Iteratively Add All Files to FileTable
- AddFiles(MetaData, Entries);
+ internal static void BuildRomFSHeader(MemoryStream romfs_stream, RomfsFile[] Entries, string DIR)
+ {
+ ROOT_DIR = DIR;
+ var MetaData = new Romfs_MetaData();
- //Set Weird Offsets, Build HashKeyPointers, Build HashTables
- PopulateHashTables(MetaData);
+ InitializeMetaData(MetaData);
+ CalcRomfsSize(MetaData);
+ PopulateRomfs(MetaData, Entries);
+ WriteMetaDataToStream(MetaData, romfs_stream);
+ }
- //Thats it.
- }
- internal static void PopulateHashTables(Romfs_MetaData MetaData)
+ internal static void InitializeMetaData(Romfs_MetaData MetaData)
+ {
+ MetaData.InfoHeader = new();
+ MetaData.DirTable = new();
+ MetaData.DirTableLen = 0;
+ MetaData.M_DirTableLen = 0;
+ MetaData.FileTable = new();
+ MetaData.FileTableLen = 0;
+ MetaData.DirTable.DirectoryTable = [];
+ MetaData.FileTable.FileTable = [];
+ MetaData.InfoHeader.HeaderLength = 0x28;
+ MetaData.InfoHeader.Sections = new Romfs_SectionHeader[4];
+ MetaData.DirHashTable = [];
+ MetaData.FileHashTable = [];
+ }
+
+ internal static void CalcRomfsSize(Romfs_MetaData MetaData)
+ {
+ MetaData.DirNum = 1;
+ var Root_DI = new DirectoryInfo(ROOT_DIR);
+ CalcDirSize(MetaData, Root_DI);
+
+ MetaData.M_DirHashTableEntry = GetHashTableEntryCount(MetaData.DirNum);
+ MetaData.M_FileHashTableEntry = GetHashTableEntryCount(MetaData.FileNum);
+
+ uint MetaDataSize = (uint)Align(0x28 + (MetaData.M_DirHashTableEntry * 4) + MetaData.M_DirTableLen + (MetaData.M_FileHashTableEntry * 4) + MetaData.M_FileTableLen, PADDING_ALIGN);
+ for (int i = 0; i < MetaData.M_DirHashTableEntry; i++)
+ MetaData.DirHashTable.Add(ROMFS_UNUSED_ENTRY);
+
+ for (int i = 0; i < MetaData.M_FileHashTableEntry; i++)
+ MetaData.FileHashTable.Add(ROMFS_UNUSED_ENTRY);
+
+ uint Pos = MetaData.InfoHeader.HeaderLength;
+ for (int i = 0; i < 4; i++)
{
- for (int i = 0; i < MetaData.DirTable.DirectoryTable.Count; i++)
- AddDirHashKey(MetaData, i);
- for (int i = 0; i < MetaData.FileTable.FileTable.Count; i++)
- AddFileHashKey(MetaData, i);
+ MetaData.InfoHeader.Sections[i].Offset = Pos;
+ uint size = i switch
+ {
+ 0 => MetaData.M_DirHashTableEntry * 4,
+ 1 => MetaData.M_DirTableLen,
+ 2 => MetaData.M_FileHashTableEntry * 4,
+ 3 => MetaData.M_FileTableLen,
+ _ => 0
+ };
+ MetaData.InfoHeader.Sections[i].Size = size;
+ Pos += size;
}
+ MetaData.InfoHeader.DataOffset = MetaDataSize;
+ }
- internal static void AddDirHashKey(Romfs_MetaData MetaData, int index)
+ internal static uint GetHashTableEntryCount(uint Entries)
+ {
+ uint count = Entries;
+ if (Entries < 3)
{
- uint parent = MetaData.DirTable.DirectoryTable[index].ParentOffset;
- string Name = MetaData.DirTable.DirectoryTable[index].Name;
- byte[] NArr = index == 0 ? Encoding.Unicode.GetBytes("") : Encoding.Unicode.GetBytes(Name);
- uint hash = CalcPathHash(parent, NArr, 0, NArr.Length);
- int ind2 = (int)(hash % MetaData.M_DirHashTableEntry);
- if (MetaData.DirHashTable[ind2] == ROMFS_UNUSED_ENTRY)
- {
- MetaData.DirHashTable[ind2] = MetaData.DirTable.DirectoryTable[index].Offset;
- }
- else
- {
- int i = GetRomfsDirEntry(MetaData, MetaData.DirHashTable[ind2]);
- int tempindex = index;
- MetaData.DirHashTable[ind2] = MetaData.DirTable.DirectoryTable[index].Offset;
- while (true)
- {
- if (MetaData.DirTable.DirectoryTable[tempindex].HashKeyPointer == ROMFS_UNUSED_ENTRY)
- {
- MetaData.DirTable.DirectoryTable[tempindex].HashKeyPointer = MetaData.DirTable.DirectoryTable[i].Offset;
- break;
- }
- i = tempindex;
- tempindex = GetRomfsDirEntry(MetaData, MetaData.DirTable.DirectoryTable[i].HashKeyPointer);
- }
- }
+ count = 3;
}
- internal static void AddFileHashKey(Romfs_MetaData MetaData, int index)
+ else if (count < 19)
{
- uint parent = MetaData.FileTable.FileTable[index].ParentDirOffset;
- string Name = MetaData.FileTable.FileTable[index].Name;
- byte[] NArr = Encoding.Unicode.GetBytes(Name);
- uint hash = CalcPathHash(parent, NArr, 0, NArr.Length);
- int ind2 = (int)(hash % MetaData.M_FileHashTableEntry);
- if (MetaData.FileHashTable[ind2] == ROMFS_UNUSED_ENTRY)
- {
- MetaData.FileHashTable[ind2] = MetaData.FileTable.FileTable[index].Offset;
- }
- else
- {
- int i = GetRomfsFileEntry(MetaData, MetaData.FileHashTable[ind2]);
- int tempindex = index;
- MetaData.FileHashTable[ind2] = MetaData.FileTable.FileTable[index].Offset;
- while (true)
- {
- if (MetaData.FileTable.FileTable[tempindex].HashKeyPointer == ROMFS_UNUSED_ENTRY)
- {
- MetaData.FileTable.FileTable[tempindex].HashKeyPointer = MetaData.FileTable.FileTable[i].Offset;
- break;
- }
- i = tempindex;
- tempindex = GetRomfsFileEntry(MetaData, MetaData.FileTable.FileTable[i].HashKeyPointer);
- }
- }
+ count |= 1;
}
-
- internal static uint CalcPathHash(uint ParentOffset, byte[] NameArray, int start, int len)
+ else
{
- uint hash = ParentOffset ^ 123456789;
- for (int i = 0; i < NameArray.Length; i += 2)
+ while (count % 2 == 0 || count % 3 == 0 || count % 5 == 0 || count % 7 == 0 || count % 11 == 0 || count % 13 == 0 || count % 17 == 0)
{
- hash = (hash >> 5) | (hash << 27);
- hash ^= (ushort)(NameArray[start + i] | (NameArray[start + i + 1] << 8));
+ count++;
}
- return hash;
}
+ return count;
+ }
+
+ internal static void CalcDirSize(Romfs_MetaData MetaData, DirectoryInfo dir)
+ {
+ if (MetaData.M_DirTableLen == 0)
+ MetaData.M_DirTableLen = 0x18;
+ else
+ MetaData.M_DirTableLen += 0x18 + (uint)Align((ulong)dir.Name.Length * 2, 4);
+
+ FileInfo[] files = dir.GetFiles();
+ foreach (FileInfo t in files)
+ MetaData.M_FileTableLen += 0x20 + (uint)Align((ulong)t.Name.Length * 2, 4);
+
+ DirectoryInfo[] SubDirectories = dir.GetDirectories();
+ foreach (DirectoryInfo t in SubDirectories)
+ CalcDirSize(MetaData, t);
+
+ MetaData.FileNum += (uint)files.Length;
+ MetaData.DirNum += (uint)SubDirectories.Length;
+ }
+
+ internal static void PopulateRomfs(Romfs_MetaData MetaData, RomfsFile[] Entries)
+ {
+ //Recursively Add All Directories to DirectoryTable
+ AddDir(MetaData, new DirectoryInfo(ROOT_DIR), 0, ROMFS_UNUSED_ENTRY);
+
+ //Iteratively Add All Files to FileTable
+ AddFiles(MetaData, Entries);
+
+ //Set Weird Offsets, Build HashKeyPointers, Build HashTables
+ PopulateHashTables(MetaData);
+
+ //Thats it.
+ }
+
+ internal static void PopulateHashTables(Romfs_MetaData MetaData)
+ {
+ for (int i = 0; i < MetaData.DirTable.DirectoryTable.Count; i++)
+ AddDirHashKey(MetaData, i);
+ for (int i = 0; i < MetaData.FileTable.FileTable.Count; i++)
+ AddFileHashKey(MetaData, i);
+ }
- internal static void AddDir(Romfs_MetaData MetaData, DirectoryInfo Dir, uint parent, uint sibling)
+ internal static void AddDirHashKey(Romfs_MetaData MetaData, int index)
+ {
+ uint parent = MetaData.DirTable.DirectoryTable[index].ParentOffset;
+ string Name = MetaData.DirTable.DirectoryTable[index].Name;
+ byte[] NArr = index == 0 ? Encoding.Unicode.GetBytes("") : Encoding.Unicode.GetBytes(Name);
+ uint hash = CalcPathHash(parent, NArr, 0);
+ int ind2 = (int)(hash % MetaData.M_DirHashTableEntry);
+ if (MetaData.DirHashTable[ind2] == ROMFS_UNUSED_ENTRY)
{
- AddDir(MetaData, Dir, parent, sibling, false);
- AddDir(MetaData, Dir, parent, sibling, true);
+ MetaData.DirHashTable[ind2] = MetaData.DirTable.DirectoryTable[index].Offset;
}
-
- internal static void AddDir(Romfs_MetaData MetaData, DirectoryInfo Dir, uint parent, uint sibling, bool DoSubs)
+ else
{
- DirectoryInfo[] SubDirectories = Dir.GetDirectories();
- if (!DoSubs)
- {
- uint CurrentDir = MetaData.DirTableLen;
- Romfs_DirEntry Entry = new Romfs_DirEntry { ParentOffset = parent };
- Entry.ChildOffset = Entry.HashKeyPointer = Entry.FileOffset = ROMFS_UNUSED_ENTRY;
- Entry.SiblingOffset = sibling;
- Entry.FullName = Dir.FullName;
- Entry.Name = Entry.FullName == ROOT_DIR ? "" : Dir.Name;
- Entry.Offset = CurrentDir;
- MetaData.DirTable.DirectoryTable.Add(Entry);
- MetaData.DirTableLen += CurrentDir == 0 ? 0x18 : 0x18 + (uint)Align((ulong)Dir.Name.Length * 2, 4);
- // int ParentIndex = GetRomfsDirEntry(MetaData, Dir.FullName);
- // uint poff = MetaData.DirTable.DirectoryTable[ParentIndex].Offset;
- }
- else
+ int i = GetRomfsDirEntry(MetaData, MetaData.DirHashTable[ind2]);
+ int tempindex = index;
+ MetaData.DirHashTable[ind2] = MetaData.DirTable.DirectoryTable[index].Offset;
+ while (true)
{
- int CurIndex = GetRomfsDirEntry(MetaData, Dir.FullName);
- uint CurrentDir = MetaData.DirTable.DirectoryTable[CurIndex].Offset;
- for (int i = 0; i < SubDirectories.Length; i++)
+ if (MetaData.DirTable.DirectoryTable[tempindex].HashKeyPointer == ROMFS_UNUSED_ENTRY)
{
- AddDir(MetaData, SubDirectories[i], CurrentDir, sibling, false);
- if (i <= 0)
- continue;
-
- string PrevFullName = SubDirectories[i - 1].FullName;
- string ThisName = SubDirectories[i].FullName;
- int PrevIndex = GetRomfsDirEntry(MetaData, PrevFullName);
- int ThisIndex = GetRomfsDirEntry(MetaData, ThisName);
- MetaData.DirTable.DirectoryTable[PrevIndex].SiblingOffset =
- MetaData.DirTable.DirectoryTable[ThisIndex].Offset;
+ MetaData.DirTable.DirectoryTable[tempindex].HashKeyPointer = MetaData.DirTable.DirectoryTable[i].Offset;
+ break;
}
- foreach (DirectoryInfo t in SubDirectories)
- AddDir(MetaData, t, CurrentDir, sibling, true);
+ i = tempindex;
+ tempindex = GetRomfsDirEntry(MetaData, MetaData.DirTable.DirectoryTable[i].HashKeyPointer);
}
+ }
+ }
- if (SubDirectories.Length <= 0)
- return;
-
- int curindex = GetRomfsDirEntry(MetaData, Dir.FullName);
- int childindex = GetRomfsDirEntry(MetaData, SubDirectories[0].FullName);
- if (curindex > -1 && childindex > -1)
- MetaData.DirTable.DirectoryTable[curindex].ChildOffset =
- MetaData.DirTable.DirectoryTable[childindex].Offset;
+ internal static void AddFileHashKey(Romfs_MetaData MetaData, int index)
+ {
+ uint parent = MetaData.FileTable.FileTable[index].ParentDirOffset;
+ string Name = MetaData.FileTable.FileTable[index].Name;
+ byte[] NArr = Encoding.Unicode.GetBytes(Name);
+ uint hash = CalcPathHash(parent, NArr, 0);
+ int ind2 = (int)(hash % MetaData.M_FileHashTableEntry);
+ if (MetaData.FileHashTable[ind2] == ROMFS_UNUSED_ENTRY)
+ {
+ MetaData.FileHashTable[ind2] = MetaData.FileTable.FileTable[index].Offset;
}
- internal static void AddFiles(Romfs_MetaData MetaData, RomfsFile[] Entries)
+ else
{
- string PrevDirPath = "";
- for (int i = 0; i < Entries.Length; i++)
+ int i = GetRomfsFileEntry(MetaData, MetaData.FileHashTable[ind2]);
+ int tempindex = index;
+ MetaData.FileHashTable[ind2] = MetaData.FileTable.FileTable[index].Offset;
+ while (true)
{
- FileInfo file = new FileInfo(Entries[i].FullName);
- Romfs_FileEntry Entry = new Romfs_FileEntry();
- string DirPath = Path.GetDirectoryName(Entries[i].FullName);
- int ParentIndex = GetRomfsDirEntry(MetaData, DirPath);
- Entry.FullName = Entries[i].FullName;
- Entry.Offset = MetaData.FileTableLen;
- Entry.ParentDirOffset = MetaData.DirTable.DirectoryTable[ParentIndex].Offset;
- Entry.SiblingOffset = ROMFS_UNUSED_ENTRY;
- if (DirPath == PrevDirPath)
+ if (MetaData.FileTable.FileTable[tempindex].HashKeyPointer == ROMFS_UNUSED_ENTRY)
{
- MetaData.FileTable.FileTable[i - 1].SiblingOffset = Entry.Offset;
+ MetaData.FileTable.FileTable[tempindex].HashKeyPointer = MetaData.FileTable.FileTable[i].Offset;
+ break;
}
- if (MetaData.DirTable.DirectoryTable[ParentIndex].FileOffset == ROMFS_UNUSED_ENTRY)
- {
- MetaData.DirTable.DirectoryTable[ParentIndex].FileOffset = Entry.Offset;
- }
- Entry.HashKeyPointer = ROMFS_UNUSED_ENTRY;
- Entry.NameSize = (uint)file.Name.Length * 2;
- Entry.Name = file.Name;
- Entry.DataOffset = Entries[i].Offset;
- Entry.DataSize = Entries[i].Size;
- MetaData.FileTable.FileTable.Add(Entry);
- MetaData.FileTableLen += 0x20 + (uint)Align((ulong)file.Name.Length * 2, 4);
- PrevDirPath = DirPath;
+ i = tempindex;
+ tempindex = GetRomfsFileEntry(MetaData, MetaData.FileTable.FileTable[i].HashKeyPointer);
}
}
+ }
- internal static void WriteMetaDataToStream(Romfs_MetaData MetaData, MemoryStream stream)
+ internal static uint CalcPathHash(uint ParentOffset, byte[] NameArray, int start)
+ {
+ uint hash = ParentOffset ^ 123456789;
+ for (int i = 0; i < NameArray.Length; i += 2)
{
- //First, InfoHeader.
- stream.Write(BitConverter.GetBytes(MetaData.InfoHeader.HeaderLength), 0, 4);
- foreach (Romfs_SectionHeader SH in MetaData.InfoHeader.Sections)
- {
- stream.Write(BitConverter.GetBytes(SH.Offset), 0, 4);
- stream.Write(BitConverter.GetBytes(SH.Size), 0, 4);
- }
- stream.Write(BitConverter.GetBytes(MetaData.InfoHeader.DataOffset), 0, 4);
+ hash = (hash >> 5) | (hash << 27);
+ hash ^= (ushort)(NameArray[start + i] | (NameArray[start + i + 1] << 8));
+ }
+ return hash;
+ }
- //DirHashTable
- foreach (uint u in MetaData.DirHashTable)
- {
- stream.Write(BitConverter.GetBytes(u), 0, 4);
- }
+ internal static void AddDir(Romfs_MetaData MetaData, DirectoryInfo Dir, uint parent, uint sibling)
+ {
+ AddDir(MetaData, Dir, parent, sibling, false);
+ AddDir(MetaData, Dir, parent, sibling, true);
+ }
- //DirTable
- foreach (Romfs_DirEntry dir in MetaData.DirTable.DirectoryTable)
+ internal static void AddDir(Romfs_MetaData MetaData, DirectoryInfo Dir, uint parent, uint sibling, bool DoSubs)
+ {
+ DirectoryInfo[] SubDirectories = Dir.GetDirectories();
+ if (!DoSubs)
+ {
+ uint CurrentDir = MetaData.DirTableLen;
+ var Entry = new Romfs_DirEntry { ParentOffset = parent };
+ Entry.ChildOffset = Entry.HashKeyPointer = Entry.FileOffset = ROMFS_UNUSED_ENTRY;
+ Entry.SiblingOffset = sibling;
+ Entry.FullName = Dir.FullName;
+ Entry.Name = Entry.FullName == ROOT_DIR ? "" : Dir.Name;
+ Entry.Offset = CurrentDir;
+ MetaData.DirTable.DirectoryTable.Add(Entry);
+ MetaData.DirTableLen += CurrentDir == 0 ? 0x18 : 0x18 + (uint)Align((ulong)Dir.Name.Length * 2, 4);
+ // int ParentIndex = GetRomfsDirEntry(MetaData, Dir.FullName);
+ // uint poff = MetaData.DirTable.DirectoryTable[ParentIndex].Offset;
+ }
+ else
+ {
+ int CurIndex = GetRomfsDirEntry(MetaData, Dir.FullName);
+ uint CurrentDir = MetaData.DirTable.DirectoryTable[CurIndex].Offset;
+ for (int i = 0; i < SubDirectories.Length; i++)
{
- stream.Write(BitConverter.GetBytes(dir.ParentOffset), 0, 4);
- stream.Write(BitConverter.GetBytes(dir.SiblingOffset), 0, 4);
- stream.Write(BitConverter.GetBytes(dir.ChildOffset), 0, 4);
- stream.Write(BitConverter.GetBytes(dir.FileOffset), 0, 4);
- stream.Write(BitConverter.GetBytes(dir.HashKeyPointer), 0, 4);
- uint nlen = (uint)dir.Name.Length * 2;
- stream.Write(BitConverter.GetBytes(nlen), 0, 4);
- byte[] NameArray = new byte[(int)Align(nlen, 4)];
- Array.Copy(Encoding.Unicode.GetBytes(dir.Name), 0, NameArray, 0, nlen);
- stream.Write(NameArray, 0, NameArray.Length);
+ AddDir(MetaData, SubDirectories[i], CurrentDir, sibling, false);
+ if (i <= 0)
+ continue;
+
+ string PrevFullName = SubDirectories[i - 1].FullName;
+ string ThisName = SubDirectories[i].FullName;
+ int PrevIndex = GetRomfsDirEntry(MetaData, PrevFullName);
+ int ThisIndex = GetRomfsDirEntry(MetaData, ThisName);
+ MetaData.DirTable.DirectoryTable[PrevIndex].SiblingOffset =
+ MetaData.DirTable.DirectoryTable[ThisIndex].Offset;
}
+ foreach (DirectoryInfo t in SubDirectories)
+ AddDir(MetaData, t, CurrentDir, sibling, true);
+ }
+
+ if (SubDirectories.Length == 0)
+ return;
+
+ int curindex = GetRomfsDirEntry(MetaData, Dir.FullName);
+ int childindex = GetRomfsDirEntry(MetaData, SubDirectories[0].FullName);
+ if (curindex > -1 && childindex > -1)
+ MetaData.DirTable.DirectoryTable[curindex].ChildOffset = MetaData.DirTable.DirectoryTable[childindex].Offset;
+ }
- //FileHashTable
- foreach (uint u in MetaData.FileHashTable)
+ internal static void AddFiles(Romfs_MetaData MetaData, RomfsFile[] Entries)
+ {
+ string PrevDirPath = "";
+ for (int i = 0; i < Entries.Length; i++)
+ {
+ var file = new FileInfo(Entries[i].FullName);
+ var Entry = new Romfs_FileEntry();
+ string DirPath = Path.GetDirectoryName(Entries[i].FullName);
+ int ParentIndex = GetRomfsDirEntry(MetaData, DirPath);
+ Entry.FullName = Entries[i].FullName;
+ Entry.Offset = MetaData.FileTableLen;
+ Entry.ParentDirOffset = MetaData.DirTable.DirectoryTable[ParentIndex].Offset;
+ Entry.SiblingOffset = ROMFS_UNUSED_ENTRY;
+ if (DirPath == PrevDirPath)
{
- stream.Write(BitConverter.GetBytes(u), 0, 4);
+ MetaData.FileTable.FileTable[i - 1].SiblingOffset = Entry.Offset;
}
-
- //FileTable
- foreach (Romfs_FileEntry file in MetaData.FileTable.FileTable)
+ if (MetaData.DirTable.DirectoryTable[ParentIndex].FileOffset == ROMFS_UNUSED_ENTRY)
{
- stream.Write(BitConverter.GetBytes(file.ParentDirOffset), 0, 4);
- stream.Write(BitConverter.GetBytes(file.SiblingOffset), 0, 4);
- stream.Write(BitConverter.GetBytes(file.DataOffset), 0, 8);
- stream.Write(BitConverter.GetBytes(file.DataSize), 0, 8);
- stream.Write(BitConverter.GetBytes(file.HashKeyPointer), 0, 4);
- uint nlen = (uint)file.Name.Length * 2;
- stream.Write(BitConverter.GetBytes(nlen), 0, 4);
- byte[] NameArray = new byte[(int)Align(nlen, 4)];
- Array.Copy(Encoding.Unicode.GetBytes(file.Name), 0, NameArray, 0, nlen);
- stream.Write(NameArray, 0, NameArray.Length);
+ MetaData.DirTable.DirectoryTable[ParentIndex].FileOffset = Entry.Offset;
}
-
- //Padding
- while (stream.Position % PADDING_ALIGN != 0)
- stream.Write(new byte[PADDING_ALIGN - stream.Position % 0x10], 0, (int)(PADDING_ALIGN - stream.Position % 0x10));
- //All Done.
+ Entry.HashKeyPointer = ROMFS_UNUSED_ENTRY;
+ Entry.NameSize = (uint)file.Name.Length * 2;
+ Entry.Name = file.Name;
+ Entry.DataOffset = Entries[i].Offset;
+ Entry.DataSize = Entries[i].Size;
+ MetaData.FileTable.FileTable.Add(Entry);
+ MetaData.FileTableLen += 0x20 + (uint)Align((ulong)file.Name.Length * 2, 4);
+ PrevDirPath = DirPath;
}
+ }
- //GetRomfs[...]Entry Functions are all O(n)
- internal static int GetRomfsDirEntry(Romfs_MetaData MetaData, string FullName)
+ internal static void WriteMetaDataToStream(Romfs_MetaData MetaData, MemoryStream stream)
+ {
+ //First, InfoHeader.
+ stream.Write(BitConverter.GetBytes(MetaData.InfoHeader.HeaderLength), 0, 4);
+ foreach (Romfs_SectionHeader SH in MetaData.InfoHeader.Sections)
{
- for (int i = 0; i < MetaData.DirTable.DirectoryTable.Count; i++)
- if (MetaData.DirTable.DirectoryTable[i].FullName == FullName)
- return i;
-
- return -1;
+ stream.Write(BitConverter.GetBytes(SH.Offset), 0, 4);
+ stream.Write(BitConverter.GetBytes(SH.Size), 0, 4);
}
- internal static int GetRomfsDirEntry(Romfs_MetaData MetaData, uint Offset)
- {
- for (int i = 0; i < MetaData.DirTable.DirectoryTable.Count; i++)
- if (MetaData.DirTable.DirectoryTable[i].Offset == Offset)
- return i;
+ stream.Write(BitConverter.GetBytes(MetaData.InfoHeader.DataOffset), 0, 4);
- return -1;
- }
- internal static int GetRomfsFileEntry(Romfs_MetaData MetaData, uint Offset)
+ //DirHashTable
+ foreach (uint u in MetaData.DirHashTable)
{
- for (int i = 0; i < MetaData.FileTable.FileTable.Count; i++)
- if (MetaData.FileTable.FileTable[i].Offset == Offset)
- return i;
-
- return -1;
+ stream.Write(BitConverter.GetBytes(u), 0, 4);
}
- #region Support Class/Struct
- public class Romfs_MetaData
+ //DirTable
+ foreach (Romfs_DirEntry dir in MetaData.DirTable.DirectoryTable)
{
- public Romfs_InfoHeader InfoHeader;
- public uint DirNum;
- public uint FileNum;
- public List DirHashTable;
- public uint M_DirHashTableEntry;
- public Romfs_DirTable DirTable;
- public uint DirTableLen;
- public uint M_DirTableLen;
- public List FileHashTable;
- public uint M_FileHashTableEntry;
- public Romfs_FileTable FileTable;
- public uint FileTableLen;
- public uint M_FileTableLen;
+ stream.Write(BitConverter.GetBytes(dir.ParentOffset), 0, 4);
+ stream.Write(BitConverter.GetBytes(dir.SiblingOffset), 0, 4);
+ stream.Write(BitConverter.GetBytes(dir.ChildOffset), 0, 4);
+ stream.Write(BitConverter.GetBytes(dir.FileOffset), 0, 4);
+ stream.Write(BitConverter.GetBytes(dir.HashKeyPointer), 0, 4);
+ uint nlen = (uint)dir.Name.Length * 2;
+ stream.Write(BitConverter.GetBytes(nlen), 0, 4);
+ byte[] NameArray = new byte[(int)Align(nlen, 4)];
+ Array.Copy(Encoding.Unicode.GetBytes(dir.Name), 0, NameArray, 0, nlen);
+ stream.Write(NameArray, 0, NameArray.Length);
}
- public struct Romfs_SectionHeader
- {
- public uint Offset;
- public uint Size;
- }
- public struct Romfs_InfoHeader
+
+ //FileHashTable
+ foreach (uint u in MetaData.FileHashTable)
{
- public uint HeaderLength;
- public Romfs_SectionHeader[] Sections;
- public uint DataOffset;
+ stream.Write(BitConverter.GetBytes(u), 0, 4);
}
- public class Romfs_DirTable
+
+ //FileTable
+ foreach (Romfs_FileEntry file in MetaData.FileTable.FileTable)
{
- public List DirectoryTable;
+ stream.Write(BitConverter.GetBytes(file.ParentDirOffset), 0, 4);
+ stream.Write(BitConverter.GetBytes(file.SiblingOffset), 0, 4);
+ stream.Write(BitConverter.GetBytes(file.DataOffset), 0, 8);
+ stream.Write(BitConverter.GetBytes(file.DataSize), 0, 8);
+ stream.Write(BitConverter.GetBytes(file.HashKeyPointer), 0, 4);
+ uint nlen = (uint)file.Name.Length * 2;
+ stream.Write(BitConverter.GetBytes(nlen), 0, 4);
+ byte[] NameArray = new byte[(int)Align(nlen, 4)];
+ Array.Copy(Encoding.Unicode.GetBytes(file.Name), 0, NameArray, 0, nlen);
+ stream.Write(NameArray, 0, NameArray.Length);
}
- public class Romfs_FileTable
+
+ //Padding
+ while (stream.Position % PADDING_ALIGN != 0)
+ stream.Write(new byte[PADDING_ALIGN - (stream.Position % 0x10)], 0, (int)(PADDING_ALIGN - (stream.Position % 0x10)));
+ //All Done.
+ }
+
+ //GetRomfs[...]Entry Functions are all O(n)
+ internal static int GetRomfsDirEntry(Romfs_MetaData MetaData, string FullName)
+ {
+ for (int i = 0; i < MetaData.DirTable.DirectoryTable.Count; i++)
{
- public List FileTable;
+ if (MetaData.DirTable.DirectoryTable[i].FullName == FullName)
+ return i;
}
- public class Romfs_DirEntry
+
+ return -1;
+ }
+
+ internal static int GetRomfsDirEntry(Romfs_MetaData MetaData, uint Offset)
+ {
+ for (int i = 0; i < MetaData.DirTable.DirectoryTable.Count; i++)
{
- public uint ParentOffset;
- public uint SiblingOffset;
- public uint ChildOffset;
- public uint FileOffset;
- public uint HashKeyPointer;
- public string Name;
- public string FullName;
- public uint Offset;
+ if (MetaData.DirTable.DirectoryTable[i].Offset == Offset)
+ return i;
}
- public class Romfs_FileEntry
+
+ return -1;
+ }
+
+ internal static int GetRomfsFileEntry(Romfs_MetaData MetaData, uint Offset)
+ {
+ for (int i = 0; i < MetaData.FileTable.FileTable.Count; i++)
{
- public uint ParentDirOffset;
- public uint SiblingOffset;
- public ulong DataOffset;
- public ulong DataSize;
- public uint HashKeyPointer;
- public uint NameSize;
- public string Name;
- public string FullName;
- public uint Offset;
+ if (MetaData.FileTable.FileTable[i].Offset == Offset)
+ return i;
}
- public class RomfsFile
- {
- public string PathName;
- public ulong Offset;
- public ulong Size;
- public string FullName;
+ return -1;
+ }
- public static ulong GetDataBlockLength(RomfsFile[] files, ulong PreData)
- {
- return files.Length == 0 ? PreData : PreData + files[files.Length - 1].Offset + files[files.Length - 1].Size;
- }
- }
- public class IVFCInfo
+ #region Support Class/Struct
+ public class Romfs_MetaData
+ {
+ public Romfs_InfoHeader InfoHeader;
+ public uint DirNum;
+ public uint FileNum;
+ public List DirHashTable;
+ public uint M_DirHashTableEntry;
+ public Romfs_DirTable DirTable;
+ public uint DirTableLen;
+ public uint M_DirTableLen;
+ public List FileHashTable;
+ public uint M_FileHashTableEntry;
+ public Romfs_FileTable FileTable;
+ public uint FileTableLen;
+ public uint M_FileTableLen;
+ }
+
+ public struct Romfs_SectionHeader
+ {
+ public uint Offset;
+ public uint Size;
+ }
+
+ public struct Romfs_InfoHeader
+ {
+ public uint HeaderLength;
+ public Romfs_SectionHeader[] Sections;
+ public uint DataOffset;
+ }
+
+ public class Romfs_DirTable
+ {
+ public List DirectoryTable;
+ }
+
+ public class Romfs_FileTable
+ {
+ public List FileTable;
+ }
+
+ public class Romfs_DirEntry
+ {
+ public uint ParentOffset;
+ public uint SiblingOffset;
+ public uint ChildOffset;
+ public uint FileOffset;
+ public uint HashKeyPointer;
+ public string Name;
+ public string FullName;
+ public uint Offset;
+ }
+
+ public class Romfs_FileEntry
+ {
+ public uint ParentDirOffset;
+ public uint SiblingOffset;
+ public ulong DataOffset;
+ public ulong DataSize;
+ public uint HashKeyPointer;
+ public uint NameSize;
+ public string Name;
+ public string FullName;
+ public uint Offset;
+ }
+
+ public class RomfsFile
+ {
+ public string PathName;
+ public ulong Offset;
+ public ulong Size;
+ public string FullName;
+
+ public static ulong GetDataBlockLength(RomfsFile[] files, ulong PreData)
{
- public IVFCLevel[] Levels;
+ return files.Length == 0 ? PreData : PreData + files[^1].Offset + files[^1].Size;
}
- public class IVFCLevel
+ }
+
+ public class IVFCInfo
+ {
+ public uint MasterHashSize;
+ public IVFCLevel[] Levels;
+ }
+
+ public class IVFCLevel
+ {
+ public ulong HashOffset;
+ public ulong DataLength;
+ public uint BlockSize;
+ }
+
+ public class FileNameTable
+ {
+ public List NameEntryTable { get; }
+ public int NumFiles => NameEntryTable.Count;
+
+ internal FileNameTable(string rootPath)
{
- public ulong HashOffset;
- public ulong DataLength;
- public uint BlockSize;
+ NameEntryTable = [];
+ AddDirectory(new DirectoryInfo(rootPath));
}
- public class FileNameTable
- {
- public List NameEntryTable { get; }
- public int NumFiles => NameEntryTable.Count;
- internal FileNameTable(string rootPath)
+ internal void AddDirectory(DirectoryInfo dir)
+ {
+ NameEntryTable.AddRange(dir.GetFiles());
+ foreach (DirectoryInfo subdir in dir.GetDirectories())
{
- NameEntryTable = new List();
- AddDirectory(new DirectoryInfo(rootPath));
+ AddDirectory(subdir);
}
+ }
+ }
- internal void AddDirectory(DirectoryInfo dir)
+ public static class LayoutManager
+ {
+ public static Output[] Create(IEnumerable Input)
+ {
+ List