tgautil.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. '''
  2. Copyright 2020 Electronic Arts Inc.
  3. This program is is free software: you can redistribute it and/or modify it under the terms of
  4. the GNU General Public License as published by the Free Software Foundation,
  5. either version 3 of the License, or (at your option) any later version.
  6. This program is is distributed in the hope that it will be useful, but with permitted additional restrictions
  7. under Section 7 of the GPL. See the GNU General Public License in LICENSE.TXT
  8. distributed with this program. You should have received a copy of the
  9. GNU General Public License along with permitted additional restrictions
  10. with this program. If not, see https://github.com/electronicarts/CnC_Remastered_Collection
  11. '''
  12. import argparse
  13. import io
  14. import json
  15. from PIL import Image
  16. import os
  17. import StringIO
  18. import sys
  19. import zipfile
  20. def overwrite_prompt(question, default=False):
  21. prompt = " [Y/n] " if default else " [y/N] "
  22. while True:
  23. sys.stdout.write(question + prompt)
  24. choice = raw_input().lower()
  25. if choice == '':
  26. return default
  27. elif choice == 'y':
  28. return True
  29. elif choice == 'n':
  30. return False
  31. else:
  32. sys.stdout.write("\n")
  33. def crop(tga_file):
  34. with Image.open(tga_file) as image:
  35. image = image.convert('RGBA')
  36. alpha = image.split()[-1]
  37. left, top, right, bottom = 0, 0, image.width, image.height
  38. found_left, found_top, found_right, found_bottom = False, False, False, False
  39. for y in range(0, image.height):
  40. if found_top and found_bottom:
  41. break
  42. for x in range(0, image.width):
  43. if found_top and found_bottom:
  44. break
  45. if not found_top and alpha.getpixel((x, y)) != 0:
  46. top = y
  47. found_top = True
  48. if not found_bottom and alpha.getpixel((x, image.height - y - 1)) != 0:
  49. bottom = image.height - y
  50. found_bottom = True
  51. for x in range(0, image.width):
  52. if found_left and found_right:
  53. break
  54. for y in range(top, bottom):
  55. if found_left and found_right:
  56. break
  57. if not found_left and alpha.getpixel((x, y)) != 0:
  58. left = x
  59. found_left = True
  60. if not found_right and alpha.getpixel((image.width - x - 1, y)) != 0:
  61. right = image.width - x
  62. found_right = True
  63. tga_data = StringIO.StringIO()
  64. meta = None
  65. if left == 0 and top == 0 and right == image.width and bottom == image.height:
  66. image.save(tga_data, 'TGA')
  67. else:
  68. image.crop((left, top, right, bottom)).save(tga_data, 'TGA')
  69. meta = json.dumps({
  70. 'size': [image.width, image.height],
  71. 'crop': [left, top, right, bottom]
  72. }, separators=(',',':'))
  73. return (tga_data.getvalue(), meta)
  74. def expand(tga_data, meta, tga_file):
  75. with Image.open(io.BytesIO(tga_data)) as image:
  76. if meta:
  77. crop = meta['crop']
  78. image_size = (crop[2] - crop[0], crop[3] - crop[1])
  79. image = image.resize(image_size)
  80. expanded_crop = (crop[0], crop[1], crop[2], crop[3])
  81. expanded_size = (meta['size'][0], meta['size'][1])
  82. with Image.new('RGBA', expanded_size, (0, 0, 0, 0)) as expanded:
  83. expanded.paste(image, expanded_crop)
  84. expanded.save(tga_file)
  85. else:
  86. image.save(tga_file)
  87. def zip(args):
  88. if not os.path.isdir(args.directory):
  89. print >> sys.stderr, '\'{}\' does not exist or is not a directory\n'.format(args.directory)
  90. sys.exit(1)
  91. tga_files = [f for f in os.listdir(args.directory) if os.path.isfile(os.path.join(args.directory, f)) and os.path.splitext(f)[1].lower() == '.tga']
  92. if not tga_files:
  93. print >> sys.stderr, '\'{}\' does not contain any TGA files\n'.format(args.directory)
  94. sys.exit(1)
  95. out_file = os.path.basename(os.path.normpath(args.directory)).upper() + '.ZIP'
  96. if os.path.exists(out_file):
  97. if not os.path.isfile(out_file):
  98. print >> sys.stderr, '\'{}\' already exists and is not a file\n'.format(out_file)
  99. sys.exit(1)
  100. if not args.yes and not overwrite_prompt('\'{}\' already exists, overwrite?'.format(out_file)):
  101. sys.exit(0)
  102. with zipfile.ZipFile(out_file, 'w', zipfile.ZIP_DEFLATED) as zip:
  103. for tga_file in tga_files:
  104. tga_data, meta = crop(os.path.join(args.directory, tga_file))
  105. zip.writestr(tga_file, tga_data)
  106. if meta:
  107. zip.writestr(os.path.splitext(tga_file)[0] + '.meta', meta)
  108. print 'Wrote ZIP archive \'{}\''.format(out_file)
  109. def unzip(args):
  110. if not os.path.isfile(args.archive):
  111. print >> sys.stderr, '\'{}\' does not exist or is not a file\n'.format(args.archive)
  112. sys.exit(1)
  113. out_dir = os.path.normpath(os.path.splitext(args.archive)[0])
  114. if os.path.exists(out_dir):
  115. if not os.path.isdir(out_dir):
  116. print >> sys.stderr, '\'{}\' already exists and is not a directory\n'.format(out_dir)
  117. sys.exit(1)
  118. if len(os.listdir(out_dir)) > 0:
  119. if not args.yes and not overwrite_prompt('\'{}\' is not empty, overwrite?'.format(out_dir)):
  120. sys.exit(0)
  121. else:
  122. os.mkdir(out_dir)
  123. files = {}
  124. with zipfile.ZipFile(args.archive, 'r', zipfile.ZIP_DEFLATED) as zip:
  125. for filename in zip.namelist():
  126. fileparts = os.path.splitext(filename)
  127. name, ext = fileparts[0].lower(), fileparts[1].lower()
  128. data = files.setdefault(name, {'tga': None, 'meta': None})
  129. if data['tga'] is None and ext == '.tga':
  130. data['tga'] = zip.read(filename)
  131. elif data['meta'] is None and ext == '.meta':
  132. data['meta'] = json.loads(zip.read(filename).decode('ascii'))
  133. if data['tga'] is not None and data['meta'] is not None:
  134. expand(data['tga'], data['meta'], os.path.join(out_dir, name) + '.tga')
  135. del files[name]
  136. for name, data in files.items():
  137. expand(data['tga'], None, os.path.join(out_dir, name) + '.tga')
  138. print 'Extracted files to \'{}\''.format(out_dir)
  139. parser = argparse.ArgumentParser(description='TGA archive utility.')
  140. subparsers = parser.add_subparsers()
  141. parser_zip = subparsers.add_parser('z', help='Build a ZIP archive from a directory of TGA files.')
  142. parser_zip.add_argument('directory', help='Directory of TGA files.')
  143. parser_zip.add_argument('-o', '--out', nargs='?', help='Output archive path (defaults to input directory name with ZIP extension in the current path).')
  144. parser_zip.add_argument('-y', '--yes', action='store_true', help='Confirm overwrite of existing ZIP archives.')
  145. parser_zip.set_defaults(func=zip)
  146. parser_unzip = subparsers.add_parser('u', help='Extract a ZIP archive of TGA files to a directory.')
  147. parser_unzip.add_argument('archive', help='ZIP archive of TGA files.')
  148. parser_unzip.add_argument('-o', '--out', nargs='?', help='Output directory (defaults to directory with name of the ZIP archive in the current path).')
  149. parser_unzip.add_argument('-y', '--yes', action='store_true', help='Confirm overwrite of files in output directory.')
  150. parser_unzip.set_defaults(func=unzip)
  151. args = parser.parse_args()
  152. args.func(args)