deppth2 0.1.5.0__py3-none-any.whl

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.
deppth2/__init__.py ADDED
File without changes
deppth2/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ """__main__: executed when deppth2 directory is called as a script."""
2
+
3
+ from .deppth2 import main
4
+ main()
deppth2/cli.py ADDED
@@ -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))
deppth2/compression.py ADDED
@@ -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')
deppth2/deppth2.py ADDED
@@ -0,0 +1,205 @@
1
+ """Top-level API exposure of package actions"""
2
+
3
+ __version__ = "0.1.5.0"
4
+
5
+ import os
6
+ import sys
7
+ import fnmatch
8
+ import subprocess
9
+
10
+ from importlib import resources
11
+ from .sggpio import PackageWithManifestReader, PackageWithManifestWriter, PackageReader, PackageWriter
12
+ from .entries import AtlasEntry, TextureEntry
13
+
14
+ def list_contents(name, *patterns, logger=lambda s: None):
15
+ with PackageWithManifestReader(name) as f:
16
+ for entry in f:
17
+ if not _entry_match(patterns, entry):
18
+ continue
19
+
20
+ logger(f'{entry.name}')
21
+
22
+ atlas = entry.manifest_entry
23
+ if atlas and hasattr(atlas, 'subAtlases'):
24
+ for subatlas in atlas.subAtlases:
25
+ subname = subatlas['name']
26
+ logger(f' {subname}')
27
+
28
+ def extract(package, target_dir, *entries, subtextures=False, logger=lambda s: None):
29
+ includes = []
30
+
31
+ if len(target_dir) == 0:
32
+ target_dir = os.path.splitext(package)[0]
33
+
34
+ os.makedirs(target_dir, exist_ok=True)
35
+ with PackageWithManifestReader(package) as f:
36
+ if f.manifest is None and subtextures:
37
+ logger('Exporting subtextures requires a manifest. --subtextures flag ignored')
38
+ subtextures=False
39
+
40
+ for entry in f:
41
+ if not _entry_match(entries, entry):
42
+ continue
43
+
44
+ logger(f'Extracting entry {entry.name}')
45
+ allow_subtextures = subtextures
46
+ if subtextures and entry.manifest_entry is None:
47
+ allow_subtextures = False
48
+ logger(f'No atlas for subtextures found. Subtextures for this entry will not be extracted.')
49
+ entry.extract(target_dir, subtextures=allow_subtextures)
50
+
51
+ if not f.manifest is None:
52
+ for entry in f.manifest.values():
53
+ if not _entry_match(entries, entry):
54
+ continue
55
+
56
+ logger(f'Extracting manifest entry {entry.name}')
57
+ entry.extract(target_dir, subtextures=subtextures, includes=includes)
58
+
59
+ if len(includes) > 0:
60
+ include_dir = os.path.join(target_dir, 'manifest')
61
+ os.makedirs(include_dir, exist_ok=True)
62
+ with open(os.path.join(include_dir, 'includes.txt'), 'w') as inc_f:
63
+ logger(f'Writing includes to {inc_f.name}')
64
+ for include in includes:
65
+ inc_f.write(include)
66
+ inc_f.write('\n')
67
+
68
+ def pack(source_dir, package, *entries, subtextures=False, logger=lambda s: None, codec='RGBA'):
69
+ curdir = os.getcwd()
70
+ source = os.path.join(curdir, source_dir)
71
+ target = package
72
+
73
+ if len(target) == 0:
74
+ target = f'{os.path.basename(source)}.pkg'
75
+
76
+ logger(f'Packing {source} to target package {target}')
77
+
78
+ if subtextures:
79
+ temp_dir = source + '_temp'
80
+ logger('Creating Texture Atlases...')
81
+ pack_subtextures(os.path.join(source, 'textures'), temp_dir, f'{os.path.splitext(target)[0]}_Textures', width=4096, height=4096)
82
+ logger('Success!')
83
+ source = temp_dir
84
+
85
+ texconv = False
86
+ if codec.lower() == 'bc7':
87
+ texconv = True
88
+ texconvformat = 'BC7_UNORM'
89
+
90
+ if texconv:
91
+ # All png atlases, chosen format, overwrite, no mipmap levels
92
+ do_texconv(os.path.join(source, 'textures', 'atlases'), texconvformat)
93
+
94
+ manifest_dir = os.path.join(source, 'manifest')
95
+ manifest_entries = []
96
+ logger('Scanning Manifest')
97
+ for filename in os.listdir(manifest_dir):
98
+ if filename.endswith('.json'):
99
+ entry = _load_manifest_entry(os.path.join(manifest_dir, filename))
100
+ if not _entry_match(entries, entry):
101
+ continue
102
+ logger(entry.name)
103
+ manifest_entries.append(entry)
104
+
105
+ with PackageWriter(target, compressor='lz4') as pkg_writer, PackageWriter(f'{target}_manifest') as manifest_writer:
106
+ for manifest_entry in manifest_entries:
107
+ entry_name = os.path.basename(manifest_entry.name)
108
+ entry_sheet_path = os.path.join(source, 'textures', 'atlases', f'{entry_name}.DDS')
109
+ if not os.path.exists(entry_sheet_path):
110
+ entry_sheet_path = os.path.join(source, 'textures', 'atlases', f'{entry_name}.png')
111
+ if os.path.exists(entry_sheet_path):
112
+ logger(f'Packing {entry_sheet_path}')
113
+ manifest_writer.write_entry(manifest_entry)
114
+ texture_entry = TextureEntry()
115
+ texture_entry.name = manifest_entry.referencedTextureName
116
+ texture_entry.import_file(entry_sheet_path)
117
+ pkg_writer.write_entry(texture_entry)
118
+ else:
119
+ logger(f'Could not find atlas image for {entry_sheet_path}. Entry will be skipped.')
120
+
121
+ def patch(name, *patches, logger=lambda s : None):
122
+ # Rename existing package/manifest so we can edit in place
123
+ package_old_path = f'{name}.old'
124
+ os.replace(name, package_old_path)
125
+ manifest_path = f'{name}_manifest'
126
+ manifest_old_path = f'{package_old_path}_manifest'
127
+ os.replace(manifest_path, manifest_old_path)
128
+
129
+ # Get the entries to replace in the package from the patches
130
+ patch_entries = {}
131
+ for patch in patches:
132
+ for entry in PackageWithManifestReader(patch):
133
+ patch_entries[entry.name] = entry
134
+
135
+ # Open the old package for reading and a new package for writing
136
+ with PackageWithManifestReader(package_old_path) as source, PackageWithManifestWriter(name, compressor=source.compressor, version=source.version) as target:
137
+ # Scan source package, replacing entries with the patched versions if present
138
+ for entry in source:
139
+ if entry.name in patch_entries:
140
+ # Write the entry from the patches
141
+ logger(f'Applying patch to entry {entry.name}')
142
+ target.write_entry_with_manifest(patch_entries.pop(entry.name))
143
+ else:
144
+ # No matching entry in patches, so just write the original entry
145
+ logger(f'No patch for entry {entry.name}, using original entry')
146
+ target.write_entry_with_manifest(entry)
147
+
148
+ # Append any entries in patches that weren't in the source
149
+ for entry in patch_entries.values():
150
+ logger(f'Appending entry {entry.name}')
151
+ target.write_entry_with_manifest(entry)
152
+
153
+ # Delete the old files
154
+ os.remove(package_old_path)
155
+ os.remove(manifest_old_path)
156
+
157
+ def _load_manifest_entry(filename):
158
+ if filename.endswith(".atlas.json"):
159
+ entry = AtlasEntry()
160
+ entry.import_file(filename)
161
+ return entry
162
+ else:
163
+ raise NotImplementedError('Unsupported manifest file type')
164
+
165
+ def _entry_match(patterns, entry):
166
+ if patterns is None or len(patterns) == 0:
167
+ return True
168
+ else:
169
+ for pattern in patterns:
170
+ if fnmatch.fnmatch(entry.short_name(), pattern):
171
+ return True
172
+ return False
173
+
174
+ def pack_subtextures(source_dir, target_dir, basename, width=4096, height=4096, include_hulls=False):
175
+ from .texpacking import build_atlases, transform_atlas
176
+
177
+ tex_dir = os.path.join(target_dir, 'textures', 'atlases')
178
+ atlas_dir = os.path.join(target_dir, 'manifest')
179
+
180
+ os.makedirs(tex_dir, exist_ok=True)
181
+ os.makedirs(atlas_dir, exist_ok=True)
182
+
183
+ hulls, namemap = build_atlases(source_dir, tex_dir, basename, (width, height), include_hulls=include_hulls)
184
+
185
+ # Switch working directory to where the textures and base atlases are
186
+ wd = os.getcwd()
187
+ os.chdir(tex_dir)
188
+
189
+ index = 0
190
+ target_dir = os.path.join('..','..','manifest')
191
+ while os.path.exists(f'{basename}{index}.json'):
192
+ transform_atlas(f'{basename}{index}.json', namemap, hulls, source_dir, target_dir)
193
+ index += 1
194
+
195
+ # Restore old working directory
196
+ os.chdir(wd)
197
+
198
+ def get_texconv_path():
199
+ # Returns the absolute path to texconv.exe inside the package
200
+ return str(resources.files("deppth2").joinpath("texconv/texconv.exe"))
201
+
202
+ def do_texconv(source_dir, format):
203
+ texconv_exe = get_texconv_path()
204
+ subprocess.run([texconv_exe, "-r", os.path.join(source_dir, "*.png"),
205
+ "-f", format, "-y", "-m", "1", "-o", source_dir])