deppth2 0.1.5.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 quaerus
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ include LICENSE
@@ -0,0 +1,132 @@
1
+ Metadata-Version: 2.4
2
+ Name: deppth2
3
+ Version: 0.1.5.0
4
+ Summary: Decompress, Extract, and Pack for Pyre, Transistor, Hades, and Hades 2
5
+ Home-page:
6
+ Author: SGG Modding
7
+ Author-email: xiaoxiao921@hotmail.fr
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Dynamic: author
11
+ Dynamic: author-email
12
+ Dynamic: description
13
+ Dynamic: description-content-type
14
+ Dynamic: license-file
15
+ Dynamic: summary
16
+
17
+ # deppth2
18
+ Decompress, Extract, and Pack for Pyre, Transistor, Hades and Hades 2.
19
+
20
+ Deppth2 is a high-level I/O interface for package files in the games Transistor, Pyre, Hades and Hades 2. Deppth provides both command-line and programmer interfaces.
21
+
22
+ ## Installation
23
+
24
+ To install Deppth2, `pip install deppth2` or download the latest [wheel](https://github.com/SGG-Modding/deppth/releases) and `pip install` it. Then read the following instructions to install dependencies.
25
+
26
+ ### Dependencies
27
+
28
+ Deppth2 technically has no required dependencies outside of Python's core modules, but you may find its functionality very limited without also installing the following optional dependencies. If an optional dependency is missing, Deppth2 will abort an operation dependent on that module informing you of the missing module.
29
+
30
+ Packages primarily contain sprite sheets. Deppth2 uses Pillow to work with the image data within. If you plan to export/import sprite sheets to/from image files, you'll need to install that: `pip install pillow`.
31
+
32
+ Hades uses LZ4 compression on its packages. If you plan to work with these packages, you'll want to install the LZ4 module: `pip install lz4`.
33
+
34
+ Transistor and Pyre both use LZF compression on their packages. If you plan to work with these packages, you'll want to install the LZF module: `pip install lzf`. You may need to install C++ build tools to get this dependency to install correctly.
35
+
36
+ ## CLI Quick-Start
37
+
38
+ Let's say we want to edit a spritesheet in Launch.pkg. First, we'll want to **extract** the package to get the individual assets out.
39
+
40
+ deppth2 ex Launch.pkg
41
+
42
+ This will create a folder called Launch in the current working directory. The texture atlases will be in the textures/atlases directory within there.
43
+
44
+ Let's say I edit Launch_Textures02.png. Now, to rebuild the package, I'll want to **pack** this folder into a package again.
45
+
46
+ deppth2 pk -s Launch -t Launch.pkg
47
+
48
+ If I then replace the package file in the game files with this package file, it should use my updated asset. But, suppose I'm trying to distribute a mod. I probably only want to distribute my change to the package, not the entire package. In that case, you probably want to build a patch for someone else to apply.
49
+
50
+ To do this, you can use the **pack** command with the **entries** flag to only include any items you changed (this works similar to patterns in other CLI tools).
51
+
52
+ deppth2 pk -s Launch -t Launch_patch.pkg -e *Launch_Textures02*
53
+
54
+ I can then distribute Launch_patch.pkg and Launch_patch.pkg_manifest. To apply this patch to the actual package, one would need to place these files in the same folder and then use the **patch** command to perform the patching.
55
+
56
+ deppth2 pt Launch.pkg Launch_patch.pkg
57
+
58
+ This will replace any entries in the package with any matching entries in the patches and append any new entries in the patches. More than one patch can be applied at a time (later ones take precedence if there are conflicts).
59
+
60
+ ## Deppth2 API
61
+
62
+ The Deppth2 module exposes functions that perform the actions described above, plus a fourth (which is also part of the CLI) to list the contents of a package. It's basically just a programmer interface for the same things the CLI does -- the latter is just a wrapper for the former.
63
+ ```py
64
+ list(name, *patterns, logger=lambda s: None)
65
+ extract(package, target_dir, *entries, subtextures=False, logger=lambda s: None)
66
+ pack(source_dir, package, *entries, logger=lambda s: None)
67
+ patch(name, *patches, logger=lambda s : None)
68
+ ```
69
+
70
+ The logger kwarg allows for customization of output of these functions -- for example, you may want to write to a file instead of print to screen.
71
+
72
+ ## SGGPIO
73
+
74
+ The SGGPIO module is a lower-level interface for working with packages. The aim is to provide IO-esque streams to read and write package data. Most users won't need this, but for certain applications, using it could lead to better performance or more customizable behavior.
75
+
76
+ SGGPIO exports two functions, which really just wrap functionality in a variety of reader and writer classes. I recommend reading the docs on these classes if you're interested, but basic usage looks something like this.
77
+
78
+ from deppth import sggpio
79
+
80
+ # Copy Launch.pkg and corresponding manifest
81
+ with sggpio.open_package('Launch.pkg', 'rm') as pkg:
82
+ with sggpio.open_package('Launch_copy.pkg', 'wm') as pkg_out:
83
+ for entry in pkg:
84
+ pkg_out.write_entry_with_manifest(entry)
85
+
86
+ # Print manifest contents of copy to verify success
87
+ with sggpio.open_package('Launch_copy.pkg', 'rm') as pkg:
88
+ for entry in pkg.manifest:
89
+ print(entry)
90
+
91
+ ## Hades 2 Packing CLI Quick-Start
92
+
93
+ In order to pack your `.png` files to be used in Hades II, open the CLI in the parent folder containing the images you want to pack.
94
+ For example, here is a directory tree.
95
+
96
+ ```
97
+ ├ <deppth command line open here>
98
+ ├── NewDeppthPackage
99
+ │ ├── GUI
100
+ │ │ ├── image1.png
101
+ │ │ ├── image2.png
102
+ │ │ ├── image3.png
103
+ │ │ │ Icons
104
+ │ │ │ ├── Iconimage.png
105
+ ```
106
+
107
+ Using the command line in order to create your package for your mod, the package name must include the ``Mod-GUID`` (ThunderstoreTeamName-ModName) in order to work with Hell2Modding.
108
+
109
+ deppth2 hpk -s NewDeppthPackage -t ThunderstoreTeamName-NewIconPackage
110
+
111
+ This will generate a folder called ThunderstoreTeamName-NewIconPackage in the parent directory that will be correctly formatted for deppth2 packaging, as well as 2 package files to use for your mod.
112
+
113
+ This will also generate the paths needed to be used in the game.
114
+
115
+ ```
116
+ ThunderstoreTeamName-NewIconPackage/GUI/image1.png
117
+ ThunderstoreTeamName-NewIconPackage/GUI/image2.png
118
+ ThunderstoreTeamName-NewIconPackage/GUI/image3.png
119
+ and
120
+ ThunderstoreTeamName-NewIconPackage/GUI/Icons/Iconimage.png
121
+ ```
122
+
123
+ All image file paths will follow the file path inside the folder they were originally in, plus the package name appended to the start of it - in order to work with Hell2Modding.\
124
+ For example, if the package was in the folder by itself its file path in-game would just be the ``ThunderstoreTeamName-NewIconPackage\\{Name}``, but if its path was `NewIconPkg/GUI/Icons` then its file path in-game would be `ThunderstoreTeamName-NewIconPackage\\GUI\\Icons\\{Name}`
125
+
126
+ ### Args
127
+
128
+ -s or --source is the name of the folder in which to recursively search for images
129
+ -t or --target is the name of the resulting folder to be packed by deppth2, must be in the form of a mod GUID (ModAuthor-ModName).
130
+ -c or --codec is to specify the image codec to use for packing, default is RGBA, often used is BC7 because of max chunk size being 32MB.
131
+ -dp or --deppthpack (not used above) set to anything but "True" to disable automatic Deppth2 Packing.
132
+ -iH or --includehulls (not used above) set to anything but "False" to calculate hull points.
@@ -0,0 +1,116 @@
1
+ # deppth2
2
+ Decompress, Extract, and Pack for Pyre, Transistor, Hades and Hades 2.
3
+
4
+ Deppth2 is a high-level I/O interface for package files in the games Transistor, Pyre, Hades and Hades 2. Deppth provides both command-line and programmer interfaces.
5
+
6
+ ## Installation
7
+
8
+ To install Deppth2, `pip install deppth2` or download the latest [wheel](https://github.com/SGG-Modding/deppth/releases) and `pip install` it. Then read the following instructions to install dependencies.
9
+
10
+ ### Dependencies
11
+
12
+ Deppth2 technically has no required dependencies outside of Python's core modules, but you may find its functionality very limited without also installing the following optional dependencies. If an optional dependency is missing, Deppth2 will abort an operation dependent on that module informing you of the missing module.
13
+
14
+ Packages primarily contain sprite sheets. Deppth2 uses Pillow to work with the image data within. If you plan to export/import sprite sheets to/from image files, you'll need to install that: `pip install pillow`.
15
+
16
+ Hades uses LZ4 compression on its packages. If you plan to work with these packages, you'll want to install the LZ4 module: `pip install lz4`.
17
+
18
+ Transistor and Pyre both use LZF compression on their packages. If you plan to work with these packages, you'll want to install the LZF module: `pip install lzf`. You may need to install C++ build tools to get this dependency to install correctly.
19
+
20
+ ## CLI Quick-Start
21
+
22
+ Let's say we want to edit a spritesheet in Launch.pkg. First, we'll want to **extract** the package to get the individual assets out.
23
+
24
+ deppth2 ex Launch.pkg
25
+
26
+ This will create a folder called Launch in the current working directory. The texture atlases will be in the textures/atlases directory within there.
27
+
28
+ Let's say I edit Launch_Textures02.png. Now, to rebuild the package, I'll want to **pack** this folder into a package again.
29
+
30
+ deppth2 pk -s Launch -t Launch.pkg
31
+
32
+ If I then replace the package file in the game files with this package file, it should use my updated asset. But, suppose I'm trying to distribute a mod. I probably only want to distribute my change to the package, not the entire package. In that case, you probably want to build a patch for someone else to apply.
33
+
34
+ To do this, you can use the **pack** command with the **entries** flag to only include any items you changed (this works similar to patterns in other CLI tools).
35
+
36
+ deppth2 pk -s Launch -t Launch_patch.pkg -e *Launch_Textures02*
37
+
38
+ I can then distribute Launch_patch.pkg and Launch_patch.pkg_manifest. To apply this patch to the actual package, one would need to place these files in the same folder and then use the **patch** command to perform the patching.
39
+
40
+ deppth2 pt Launch.pkg Launch_patch.pkg
41
+
42
+ This will replace any entries in the package with any matching entries in the patches and append any new entries in the patches. More than one patch can be applied at a time (later ones take precedence if there are conflicts).
43
+
44
+ ## Deppth2 API
45
+
46
+ The Deppth2 module exposes functions that perform the actions described above, plus a fourth (which is also part of the CLI) to list the contents of a package. It's basically just a programmer interface for the same things the CLI does -- the latter is just a wrapper for the former.
47
+ ```py
48
+ list(name, *patterns, logger=lambda s: None)
49
+ extract(package, target_dir, *entries, subtextures=False, logger=lambda s: None)
50
+ pack(source_dir, package, *entries, logger=lambda s: None)
51
+ patch(name, *patches, logger=lambda s : None)
52
+ ```
53
+
54
+ The logger kwarg allows for customization of output of these functions -- for example, you may want to write to a file instead of print to screen.
55
+
56
+ ## SGGPIO
57
+
58
+ The SGGPIO module is a lower-level interface for working with packages. The aim is to provide IO-esque streams to read and write package data. Most users won't need this, but for certain applications, using it could lead to better performance or more customizable behavior.
59
+
60
+ SGGPIO exports two functions, which really just wrap functionality in a variety of reader and writer classes. I recommend reading the docs on these classes if you're interested, but basic usage looks something like this.
61
+
62
+ from deppth import sggpio
63
+
64
+ # Copy Launch.pkg and corresponding manifest
65
+ with sggpio.open_package('Launch.pkg', 'rm') as pkg:
66
+ with sggpio.open_package('Launch_copy.pkg', 'wm') as pkg_out:
67
+ for entry in pkg:
68
+ pkg_out.write_entry_with_manifest(entry)
69
+
70
+ # Print manifest contents of copy to verify success
71
+ with sggpio.open_package('Launch_copy.pkg', 'rm') as pkg:
72
+ for entry in pkg.manifest:
73
+ print(entry)
74
+
75
+ ## Hades 2 Packing CLI Quick-Start
76
+
77
+ In order to pack your `.png` files to be used in Hades II, open the CLI in the parent folder containing the images you want to pack.
78
+ For example, here is a directory tree.
79
+
80
+ ```
81
+ ├ <deppth command line open here>
82
+ ├── NewDeppthPackage
83
+ │ ├── GUI
84
+ │ │ ├── image1.png
85
+ │ │ ├── image2.png
86
+ │ │ ├── image3.png
87
+ │ │ │ Icons
88
+ │ │ │ ├── Iconimage.png
89
+ ```
90
+
91
+ Using the command line in order to create your package for your mod, the package name must include the ``Mod-GUID`` (ThunderstoreTeamName-ModName) in order to work with Hell2Modding.
92
+
93
+ deppth2 hpk -s NewDeppthPackage -t ThunderstoreTeamName-NewIconPackage
94
+
95
+ This will generate a folder called ThunderstoreTeamName-NewIconPackage in the parent directory that will be correctly formatted for deppth2 packaging, as well as 2 package files to use for your mod.
96
+
97
+ This will also generate the paths needed to be used in the game.
98
+
99
+ ```
100
+ ThunderstoreTeamName-NewIconPackage/GUI/image1.png
101
+ ThunderstoreTeamName-NewIconPackage/GUI/image2.png
102
+ ThunderstoreTeamName-NewIconPackage/GUI/image3.png
103
+ and
104
+ ThunderstoreTeamName-NewIconPackage/GUI/Icons/Iconimage.png
105
+ ```
106
+
107
+ All image file paths will follow the file path inside the folder they were originally in, plus the package name appended to the start of it - in order to work with Hell2Modding.\
108
+ For example, if the package was in the folder by itself its file path in-game would just be the ``ThunderstoreTeamName-NewIconPackage\\{Name}``, but if its path was `NewIconPkg/GUI/Icons` then its file path in-game would be `ThunderstoreTeamName-NewIconPackage\\GUI\\Icons\\{Name}`
109
+
110
+ ### Args
111
+
112
+ -s or --source is the name of the folder in which to recursively search for images
113
+ -t or --target is the name of the resulting folder to be packed by deppth2, must be in the form of a mod GUID (ModAuthor-ModName).
114
+ -c or --codec is to specify the image codec to use for packing, default is RGBA, often used is BC7 because of max chunk size being 32MB.
115
+ -dp or --deppthpack (not used above) set to anything but "True" to disable automatic Deppth2 Packing.
116
+ -iH or --includehulls (not used above) set to anything but "False" to calculate hull points.
File without changes
@@ -0,0 +1,4 @@
1
+ """__main__: executed when deppth2 directory is called as a script."""
2
+
3
+ from .deppth2 import main
4
+ main()
@@ -0,0 +1,100 @@
1
+ """Command-line interface for deppth2 functionality"""
2
+ import os
3
+ import argparse
4
+ import sys
5
+
6
+ from .deppth2 import list_contents, pack, patch, extract
7
+ from .texpacking import build_atlases_hades
8
+
9
+ def main():
10
+ parser = argparse.ArgumentParser(prog='deppth2', description='Decompress, Extract, Pack for Pyre, Transistor, and Hades')
11
+ subparsers = parser.add_subparsers(help='The action to perform', dest='action')
12
+
13
+ # List parser
14
+ list_parser = subparsers.add_parser('list', help='List the entries of a package', aliases=['ls'])
15
+ list_parser.add_argument('path', metavar='path', type=str, help='The path to the package to act on')
16
+ list_parser.add_argument('patterns', metavar='pattern', nargs='*', help='Patterns to search for')
17
+ list_parser.set_defaults(func=cli_list)
18
+
19
+ # Extract parser
20
+ extract_parser = subparsers.add_parser('extract', help='Extract assets from a package', aliases=['ex'])
21
+ extract_parser.add_argument('source', metavar='source', type=str, help='The path to extract')
22
+ extract_parser.add_argument('-t', '--target', metavar='target', default='', help='Where to extract the package')
23
+ extract_parser.add_argument('-e', '--entries', nargs='*', metavar='entry', help='One or more entry names to extract')
24
+ extract_parser.add_argument('-s', '--subtextures', action='store_true', default=False, help='Export subtextures instead of full atlases')
25
+ extract_parser.set_defaults(func=cli_extract)
26
+
27
+ # Pack parser
28
+ pack_parser = subparsers.add_parser('pack', help='Pack assets into a package', aliases=['pk'])
29
+ pack_parser.add_argument('-s', '--source', metavar='source', default='', type=str, help='Path to the folder to pack, default is current folder')
30
+ pack_parser.add_argument('-t', '--target', metavar='target', default='', help='Path of output file')
31
+ pack_parser.add_argument('-e', '--entries', nargs='*', metavar='entry', help='Only pack entries matching these patterns')
32
+ pack_parser.add_argument('-c', '--codec', metavar='codec', default='RGBA', help='Specify the image codec to use for packing, default is RGBA, often used is BC7 because of max chunk size being 32MB')
33
+ pack_parser.set_defaults(func=cli_pack)
34
+
35
+ # Patch parser
36
+ patch_parser = subparsers.add_parser('patch', help='Patch a package, replacing or adding entries from patches', aliases=['pt'])
37
+ patch_parser.add_argument('package', metavar='package', type=str, help='The package to patch')
38
+ patch_parser.add_argument('patches', metavar='patches', nargs='*', help='The patches to apply')
39
+ patch_parser.set_defaults(func=cli_patch)
40
+
41
+ # Pack textures
42
+ hadespack_parser = subparsers.add_parser('hadespack', help='Format images into an atlas and manifest for packing with deppth2', aliases=['hpk'])
43
+ hadespack_parser.add_argument('-s', '--source', metavar='source', default='MyPackage', type=str, help='The directory to recursively search for images in, default is current folder')
44
+ hadespack_parser.add_argument('-t', '--target', metavar='target', default='ThunderstoreTeamName-MyPackage', help='Filenames created will start with this plus a number')
45
+ hadespack_parser.add_argument('-c', '--codec', metavar='codec', default = "RGBA", help='Specify the image codec to use for packing, default is RGBA, often used is BC7 because of max chunk size being 32MB')
46
+ hadespack_parser.add_argument('-dP', '--deppthpack', metavar='deppthpack', default='True', help='Automatically Pack your images and Manifest using deppth2')
47
+ hadespack_parser.add_argument('-iH', '--includehulls', metavar='includehulls', default = "False", help='Set to anything if you want hull points computed and added')
48
+ hadespack_parser.set_defaults(func=cli_hadespack)
49
+
50
+ args = parser.parse_args()
51
+
52
+ # Print help if no arguments were provided
53
+ if not hasattr(args, 'func'):
54
+ parser.print_help()
55
+ sys.exit(1)
56
+
57
+ args.func(args)
58
+
59
+ def cli_list(args):
60
+ path = args.path
61
+ patterns = args.patterns
62
+
63
+ list_contents(path, *patterns, logger=lambda s: print(s))
64
+
65
+ def cli_extract(args):
66
+ source = args.source
67
+ target = args.target
68
+ entries = args.entries or []
69
+ subtextures = args.subtextures
70
+
71
+ extract(source, target, *entries, subtextures=subtextures, logger=lambda s: print(s))
72
+
73
+ def cli_pack(args):
74
+ curdir = os.getcwd()
75
+ source = os.path.join(curdir, args.source)
76
+ target = args.target
77
+ entries = args.entries or []
78
+ codec = args.codec
79
+
80
+ pack(source, target, *entries, logger=lambda s: print(s), codec=codec)
81
+
82
+ def cli_hadespack(args):
83
+ source = args.source
84
+ target = args.target
85
+ codec = args.codec
86
+
87
+ deppth2 = True
88
+ if args.deppthpack != "True":
89
+ deppth2 = False
90
+
91
+ hulls = False
92
+ if args.includehulls != "False":
93
+ hulls = True
94
+
95
+ build_atlases_hades(source, target, deppth2, hulls, codec=codec)
96
+
97
+ def cli_patch(args):
98
+ package = args.package
99
+ patches = args.patches
100
+ patch(package, *patches, logger=lambda s : print(s))
@@ -0,0 +1,216 @@
1
+ from abc import ABC, abstractmethod
2
+ from .utils import requires
3
+ import os
4
+
5
+ try: import lz4.block
6
+ except ImportError: pass
7
+ try: import lzf
8
+ except ImportError: pass
9
+
10
+ _chunk_processors = {} # Stores a mapping of possible chunk processors by byte code
11
+ _chunk_processors_by_name = {} # Stores a mapping of possible chunk processors by name
12
+
13
+ def chunkprocessor(typeName, typeCode):
14
+ """Decorates a subclass of ChunkProcessorBase to register its name and byte code.
15
+
16
+ This makes the class discoverable by the chunk reading code to find the
17
+ correct subclass to read and (possibly) decompress chunks of data from
18
+ the stream.
19
+ """
20
+ def decorate_entry(cls):
21
+ def class_wrapper(*args):
22
+ return cls(*args)
23
+ if typeCode:
24
+ _chunk_processors[typeCode] = class_wrapper
25
+ _chunk_processors_by_name[typeName] = class_wrapper
26
+ class_wrapper._typeCode = typeCode
27
+ cls._typeCode = typeCode
28
+ return class_wrapper
29
+ return decorate_entry
30
+
31
+ def validate_compressor_name(name):
32
+ return name in _chunk_processors_by_name
33
+
34
+ def get_chunkprocessor_by_name(name):
35
+ return _chunk_processors_by_name[name]()
36
+
37
+ def get_chunkprocessor(b):
38
+ return _chunk_processors[b]()
39
+
40
+ #region Chunk Processing
41
+ class _ChunkProcessorBase(ABC):
42
+ """Base class for a chunk processor.
43
+
44
+ What is a chunk processor? Well, in this case, it is an object which is responsible for
45
+ reading chunks of data from and writing chunks of data to packages. SuperGiant's packages
46
+ consist of a four-byte header followed by a series of chunks containing asset data.
47
+ The various subclasses of this class handle the variety of formats the chunks themselves
48
+ can be stored as.
49
+ """
50
+ @abstractmethod
51
+ def read_chunk(self, stream, chunk_size):
52
+ """Reads the next chunk of data from the stream.
53
+
54
+ This function is responsible for reading the next chunk of data, performing any needed
55
+ processing on the data (such as decompression), and ensuring the output is of the
56
+ indicated size.
57
+ """
58
+ pass
59
+
60
+ @abstractmethod
61
+ def write_chunk(self, stream, chunk):
62
+ """Writes a chunk of data to the stream.
63
+
64
+ This function is responsible for performing any needed processing on the chunk
65
+ (such as compression), and writing the processed data to the stream.
66
+ """
67
+ pass
68
+
69
+ @abstractmethod
70
+ def skip_chunk(self, stream, chunk_size):
71
+ """Skips past the next chunk of data from the stream.
72
+
73
+ This function should act similar to read_chunk in determining how much data
74
+ is in the next chunk, but should skip past it in the stream instead of
75
+ reading it. This function is used to faciliate random access IO functions
76
+ like seek().
77
+ """
78
+ pass
79
+
80
+
81
+ @chunkprocessor('uncompressed', b'\x00')
82
+ class _UncompressedChunkProcessor(_ChunkProcessorBase):
83
+ """Chunk processor for uncompressed packages."""
84
+ def read_chunk(self, stream, chunk_size):
85
+ """Reads the next chunk of data from the stream.
86
+
87
+ In this case, the data is assumed uncompressed, so this just reads unmodified data
88
+ from the stream.
89
+ """
90
+ return stream.read(chunk_size)
91
+
92
+ def write_chunk(self, stream, chunk):
93
+ """Writes a chunk of data to the stream.
94
+
95
+ In this case, the data is assumed uncompressed, so this just writes unmodified data
96
+ to the stream.
97
+ """
98
+ stream.write(chunk)
99
+
100
+ def skip_chunk(self, stream, chunk_size):
101
+ """Skips past the next chunk of data in the stream.
102
+
103
+ In this case, the data is assumed to be uncompressed, so this just skips bytes
104
+ equal to the size of the chunk.
105
+ """
106
+ stream.seek(chunk_size, os.SEEK_CUR)
107
+
108
+
109
+ class _CompressedChunkProcessor(_ChunkProcessorBase):
110
+ """Chunk processor for compressed packages.
111
+
112
+ Packages generally consist of compressed chunks. The purpose of this class is to
113
+ facilitate reading and writing package data one chunk at a time.
114
+ """
115
+ def read_chunk(self, stream, chunk_size):
116
+ """Reads the next chunk of data from the stream.
117
+
118
+ In this case, the data is likely compressed, so this will read the compressed data
119
+ from the stream, then call decompress to decompress it if it is indeed compressed.
120
+ The decompress function should return a chunk of the correct size by padding it with 0-bytes.
121
+ """
122
+ if stream.read(1) != 0:
123
+ # The chunk is compressed. Read it, then decompress it.
124
+ compSize = stream.read_int()
125
+ compressedData = stream.read(compSize)
126
+ return self.decompress(compressedData, chunk_size)
127
+ else:
128
+ # The chunk is not compressed. Just read it.
129
+ return stream.read(chunk_size)
130
+
131
+ def write_chunk(self, stream, chunk):
132
+ """Writes a chunk of data to the stream.
133
+
134
+ In this case, the data is assumed compressed, so this will compress the given chunk
135
+ of data, then write the compressed data to the stream.
136
+ """
137
+ compressedData = self.compress(chunk)
138
+ stream.write(bytes([1])) # The "1" indicates it's compressed
139
+ stream.write_int(len(compressedData)) # Then write the length of the compressed data
140
+ stream.write(compressedData) # Then write the compressed data itself
141
+
142
+ def skip_chunk(self, stream, chunk_size):
143
+ """Skips past the next chunk of data in the stream.
144
+
145
+ Compressed chunks encode the size of the compressed data as part of the chunk.
146
+ Therefore, this function will read in that size, but then just seek past the
147
+ actual chunk data.
148
+ """
149
+ if stream.read(1) != 0:
150
+ # The chunk is compressed. Read the size, then seek past it.
151
+ compSize = stream.read_int()
152
+ stream.seek(compSize, os.SEEK_CUR)
153
+ else:
154
+ # The chunk is not compressed. Just seek past it.
155
+ stream.seek(chunk_size, os.SEEK_CUR)
156
+
157
+ @abstractmethod
158
+ def compress(self, chunk):
159
+ """Compresses the given chunk."""
160
+ pass
161
+
162
+ @abstractmethod
163
+ def decompress(self, chunk, chunk_size):
164
+ """Decompresses the given chunk, zero-filling to chunk_size."""
165
+ pass
166
+
167
+ @requires('lz4')
168
+ @chunkprocessor('lz4', b'\x20')
169
+ class _Lz4ChunkProcessor(_CompressedChunkProcessor):
170
+ """Chunk processor for LZ4-compressed packages.
171
+
172
+ Packages in Hades are compressed using LZ4. The 'lz4' module
173
+ is required to use this chunk processor.
174
+ """
175
+ def compress(self, chunk):
176
+ """Compresses a block of data using LZ4 compression."""
177
+ return lz4.block.compress(chunk, mode='high_compression', store_size=False)
178
+
179
+ def decompress(self, chunk, chunk_size):
180
+ """Decompresses an LZ4-compressed block of data, zero-filling to chunk_size."""
181
+ return lz4.block.decompress(chunk, uncompressed_size=chunk_size).ljust(chunk_size, b'\x00')
182
+
183
+ @requires('lzf')
184
+ @chunkprocessor('lzf', b'\x40')
185
+ class _LzfChunkProcessor(_CompressedChunkProcessor):
186
+ """Chunk processor for LZF-compressed packages.
187
+
188
+ Packages in Transistor are compressed using LZF. The 'lzf' module
189
+ is required to use this chunk processor.
190
+ """
191
+ def compress(self, chunk):
192
+ """Compresses a block of data using LZF compression."""
193
+ return lzf.compress(chunk)
194
+
195
+ def decompress(self, chunk, chunk_size):
196
+ """Decompresses an LZF-compressed block of data, zero-filling to chunk_size."""
197
+ return lzf.decompress(chunk, chunk_size).ljust(chunk_size, b'\x00')
198
+ #endregion
199
+
200
+
201
+ @chunkprocessor('lzx', b'\x60')
202
+ class _LzxChunkProcessor(_CompressedChunkProcessor):
203
+ """Chunk processor for LZX-compressed data.
204
+
205
+ LZX is not actually used to compress packages, but can be used to compress
206
+ XNB data. This class is provided as a consistent interface for that compression.
207
+
208
+ This mode of compression is not yet implemented.
209
+ """
210
+ def compress(self, chunk):
211
+ """Compresses a block of data using LZX compression."""
212
+ raise NotImplementedError('LZX compression is not yet implemented')
213
+
214
+ def decompress(self, chunk, chunk_size):
215
+ """Decompresses an LZX-compressed block of data."""
216
+ raise NotImplementedError('LZX decompression is not yet implemented')