convert_image.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. #!/usr/bin/python
  2. # Copyright (C) 2009-2016, Panagiotis Christopoulos Charitos and contributors.
  3. # All rights reserved.
  4. # Code licensed under the BSD License.
  5. # http://www.anki3d.org/LICENSE
  6. import argparse
  7. import subprocess
  8. import re
  9. import os
  10. import struct
  11. import copy
  12. import tempfile
  13. import shutil
  14. #
  15. # Config
  16. #
  17. class Config:
  18. in_files = []
  19. out_file = ""
  20. fast = False
  21. type = 0
  22. normal = False
  23. convert_path = ""
  24. no_alpha = False
  25. store_compressed = False
  26. store_uncompressed = True
  27. to_linear_rgb = False
  28. tmp_dir = ""
  29. #
  30. # AnKi texture
  31. #
  32. # Texture type
  33. TT_NONE = 0
  34. TT_2D = 1
  35. TT_CUBE = 2
  36. TT_3D = 3
  37. TT_2D_ARRAY = 4
  38. # Color format
  39. CF_NONE = 0
  40. CF_RGB8 = 1
  41. CF_RGBA8 = 2
  42. # Data compression
  43. DC_NONE = 0
  44. DC_RAW = 1 << 0
  45. DC_ETC2 = 1 << 1
  46. DC_S3TC = 1 << 2
  47. # Texture filtering
  48. TF_DEFAULT = 0
  49. TF_LINEAR = 1
  50. TF_NEAREST = 2
  51. #
  52. # DDS
  53. #
  54. # dwFlags of DDSURFACEDESC2
  55. DDSD_CAPS = 0x00000001
  56. DDSD_HEIGHT = 0x00000002
  57. DDSD_WIDTH = 0x00000004
  58. DDSD_PITCH = 0x00000008
  59. DDSD_PIXELFORMAT = 0x00001000
  60. DDSD_MIPMAPCOUNT = 0x00020000
  61. DDSD_LINEARSIZE = 0x00080000
  62. DDSD_DEPTH = 0x00800000
  63. # ddpfPixelFormat of DDSURFACEDESC2
  64. DDPF_ALPHAPIXELS = 0x00000001
  65. DDPF_FOURCC = 0x00000004
  66. DDPF_RGB = 0x00000040
  67. # dwCaps1 of DDSCAPS2
  68. DDSCAPS_COMPLEX = 0x00000008
  69. DDSCAPS_TEXTURE = 0x00001000
  70. DDSCAPS_MIPMAP = 0x00400000
  71. # dwCaps2 of DDSCAPS2
  72. DDSCAPS2_CUBEMAP = 0x00000200
  73. DDSCAPS2_CUBEMAP_POSITIVEX = 0x00000400
  74. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x00000800
  75. DDSCAPS2_CUBEMAP_POSITIVEY = 0x00001000
  76. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x00002000
  77. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x00004000
  78. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x00008000
  79. DDSCAPS2_VOLUME = 0x00200000
  80. class DdsHeader:
  81. """ The header of a dds file """
  82. _fields = [
  83. ('dwMagic', '4s'),
  84. ('dwSize', 'I'),
  85. ('dwFlags', 'I'),
  86. ('dwHeight', 'I'),
  87. ('dwWidth', 'I'),
  88. ('dwPitchOrLinearSize', 'I'),
  89. ('dwDepth', 'I'),
  90. ('dwMipMapCount', 'I'),
  91. ('dwReserved1', '44s'),
  92. # Pixel format
  93. ('dwSize', 'I'),
  94. ('dwFlags', 'I'),
  95. ('dwFourCC', '4s'),
  96. ('dwRGBBitCount', 'I'),
  97. ('dwRBitMask', 'I'),
  98. ('dwGBitMask', 'I'),
  99. ('dwBBitMask', 'I'),
  100. ('dwRGBAlphaBitMask', 'I'),
  101. ('dwCaps1', 'I'),
  102. ('dwCaps2', 'I'),
  103. ('dwCapsReserved', '8s'),
  104. ('dwReserved2', 'I')]
  105. def __init__(self, buff):
  106. buff_format = self.get_format()
  107. items = struct.unpack(buff_format, buff)
  108. for field, value in map(None, self._fields, items):
  109. setattr(self, field[0], value)
  110. @classmethod
  111. def get_format(cls):
  112. return '<' + ''.join([f[1] for f in cls._fields])
  113. @classmethod
  114. def get_size(cls):
  115. return struct.calcsize(cls.get_format())
  116. #
  117. # ETC2
  118. #
  119. class PkmHeader:
  120. """ The header of a pkm file """
  121. _fields = [
  122. ("magic", "6s"),
  123. ("type", "H"),
  124. ("width", "H"),
  125. ("height", "H"),
  126. ("origWidth", "H"),
  127. ("origHeight", "H")]
  128. def __init__(self, buff):
  129. buff_format = self.get_format()
  130. items = struct.unpack(buff_format, buff)
  131. for field, value in map(None, self._fields, items):
  132. setattr(self, field[0], value)
  133. @classmethod
  134. def get_format(cls):
  135. return ">" + "".join([f[1] for f in cls._fields])
  136. @classmethod
  137. def get_size(cls):
  138. return struct.calcsize(cls.get_format())
  139. #
  140. # Functions
  141. #
  142. def printi(s):
  143. print("[I] %s" % s)
  144. def printw(s):
  145. print("[W] %s" % s)
  146. def is_power2(num):
  147. """ Returns true if a number is a power of two """
  148. return num != 0 and ((num & (num - 1)) == 0)
  149. def get_base_fname(path):
  150. """ From path/to/a/file.ext return the "file" """
  151. return os.path.splitext(os.path.basename(path))[0]
  152. def parse_commandline():
  153. """ Parse the command line arguments """
  154. parser = argparse.ArgumentParser(description = "This program converts a single image or a number " \
  155. "of images (for 3D and 2DArray textures) to AnKi texture format." \
  156. " It requires 4 different applications/executables to " \
  157. "operate: convert, identify, nvcompress and etcpack. These " \
  158. "applications should be in PATH except the convert where you " \
  159. "need to define the executable explicitly",
  160. formatter_class = argparse.ArgumentDefaultsHelpFormatter)
  161. parser.add_argument("-i", "--input", nargs = "+", required = True,
  162. help = "specify the image(s) to convert. Seperate with space")
  163. parser.add_argument("-o", "--output", required = True, help = "specify output AnKi image.")
  164. parser.add_argument("-t", "--type", default = "2D", choices = ["2D", "3D", "2DArray"],
  165. help = "type of the image (2D or cube or 3D or 2DArray)")
  166. parser.add_argument("-f", "--fast", type = int, default = 0, help = "run the fast version of the converters")
  167. parser.add_argument("-n", "--normal", type = int, default = 0, help = "assume the texture is normal")
  168. parser.add_argument("-c", "--convert-path", default = "/usr/bin/convert",
  169. help = "the executable where convert tool is located. Stupid etcpack cannot get it from PATH")
  170. parser.add_argument("--no-alpha", type = int, default = 0, help = "remove alpha channel")
  171. parser.add_argument("--store-uncompressed", type = int, default = 0, help = "store or not uncompressed data")
  172. parser.add_argument("--store-compressed", type = int, default = 1, help = "store or not compressed data")
  173. parser.add_argument("--to-linear-rgb", type = int, default = 0,
  174. help = "assume the input textures are sRGB. If this option is true then convert them to linear RGB")
  175. parser.add_argument("--filter", default = "default", choices = ["default", "linear", "nearest"],
  176. help = "texture filtering. Can be: default, linear, nearest")
  177. parser.add_argument("--mips-count", type = int, default = 0xFFFF, help = "Max number of mipmaps")
  178. args = parser.parse_args()
  179. if args.type == "2D":
  180. typ = TT_2D
  181. elif args.type == "cube":
  182. typ = TT_CUBE
  183. elif args.type == "3D":
  184. typ = TT_3D
  185. elif args.type == "2DArray":
  186. typ = TT_2D_ARRAY
  187. else:
  188. assert 0, "See file"
  189. if args.filter == "default":
  190. filter = TF_DEFAULT
  191. elif args.filter == "linear":
  192. filter = TF_LINEAR
  193. elif args.filter == "nearest":
  194. filter = TF_NEAREST
  195. else:
  196. assert 0, "See file"
  197. if not args.store_uncompressed and not args.store_compressed:
  198. parser.error("One of --store-compressed and --store-uncompressed should be True")
  199. if args.mips_count <= 0:
  200. parser.error("Wrong number of mipmaps")
  201. config = Config()
  202. config.in_files = args.input
  203. config.out_file = args.output
  204. config.fast = args.fast
  205. config.type = typ
  206. config.normal = args.normal
  207. config.convert_path = args.convert_path
  208. config.no_alpha = args.no_alpha
  209. config.store_uncompressed = args.store_uncompressed
  210. config.store_compressed = args.store_compressed
  211. config.to_linear_rgb = args.to_linear_rgb
  212. config.filter = filter
  213. config.mips_count = args.mips_count
  214. print(config)
  215. return config
  216. def identify_image(in_file):
  217. """ Return the size of the input image and the internal format """
  218. color_format = CF_NONE
  219. width = 0
  220. height = 0
  221. proc = subprocess.Popen(["identify", "-verbose" , in_file], stdout=subprocess.PIPE)
  222. stdout_str = proc.stdout.read()
  223. # Make sure the colorspace is what we want
  224. """reg = re.search(r"Colorspace: (.*)", stdout_str)
  225. if not reg or reg.group(1) != "RGB":
  226. raise Exception("Something is wrong with the colorspace")"""
  227. # Get the size of the iamge
  228. reg = re.search(r"Geometry: ([0-9]*)x([0-9]*)\+", stdout_str)
  229. if not reg:
  230. raise Exception("Cannot extract size")
  231. # Identify the color space
  232. """if not re.search(r"red: 8-bit", stdout_str) \
  233. or not re.search(r"green: 8-bit", stdout_str) \
  234. or not re.search(r"blue: 8-bit", stdout_str): \
  235. raise Exception("Incorrect channel depths")"""
  236. if re.search(r"alpha: 8-bit", stdout_str):
  237. color_format = CF_RGBA8
  238. color_format_str = "RGBA"
  239. else:
  240. color_format = CF_RGB8
  241. color_format_str = "RGB"
  242. # print some stuff and return
  243. printi("width: %s, height: %s color format: %s" % \
  244. (reg.group(1), reg.group(2), color_format_str))
  245. return (color_format, int(reg.group(1)), int(reg.group(2)))
  246. def create_mipmaps(in_file, tmp_dir, width_, height_, color_format, to_linear_rgb, max_mip_count):
  247. """ Create a number of images for all mipmaps """
  248. printi("Generate mipmaps")
  249. width = width_
  250. height = height_
  251. mips_fnames = []
  252. while width >= 4 and height >= 4:
  253. size_str = "%dx%d" % (width, height)
  254. out_file_str = os.path.join(tmp_dir, get_base_fname(in_file)) + "." + size_str
  255. printi(" %s.tga" % out_file_str)
  256. mips_fnames.append(out_file_str)
  257. args = ["convert", in_file]
  258. # to linear
  259. if to_linear_rgb:
  260. if color_format != CF_RGB8:
  261. raise Exception("to linear RGB only supported for RGB textures")
  262. args.append("-set")
  263. args.append("colorspace")
  264. args.append("sRGB")
  265. args.append("-colorspace")
  266. args.append("RGB")
  267. # resize
  268. args.append("-resize")
  269. args.append(size_str)
  270. # alpha
  271. args.append("-alpha")
  272. if color_format == CF_RGB8:
  273. args.append("deactivate")
  274. else:
  275. args.append("activate")
  276. args.append(out_file_str + ".tga")
  277. subprocess.check_call(args)
  278. if(len(mips_fnames) == max_mip_count):
  279. break;
  280. width = width / 2
  281. height = height / 2
  282. return mips_fnames
  283. def create_etc_images(mips_fnames, tmp_dir, fast, color_format, convert_path):
  284. """ Create the etc files """
  285. printi("Creating ETC images")
  286. # Copy the convert tool to the working dir so that etcpack will see it
  287. shutil.copy2(convert_path, \
  288. os.path.join(tmp_dir, os.path.basename(convert_path)))
  289. for fname in mips_fnames:
  290. # Unfortunately we need to flip the image. Use convert again
  291. in_fname = fname + ".tga"
  292. flipped_fname = fname + "_flip.tga"
  293. args = ["convert", in_fname, "-flip", flipped_fname]
  294. subprocess.check_call(args)
  295. in_fname = flipped_fname
  296. printi(" %s" % in_fname)
  297. args = ["etcpack", in_fname, tmp_dir, "-c", "etc2"]
  298. if fast:
  299. args.append("-s")
  300. args.append("fast")
  301. args.append("-f")
  302. if color_format == CF_RGB8:
  303. args.append("RGB")
  304. else:
  305. args.append("RGBA")
  306. # Call the executable AND change the working directory so that etcpack will find convert
  307. subprocess.check_call(args, stdout = subprocess.PIPE, cwd = tmp_dir)
  308. def create_dds_images(mips_fnames, tmp_dir, fast, color_format, normal):
  309. """ Create the dds files """
  310. printi("Creating DDS images")
  311. for fname in mips_fnames:
  312. # Unfortunately we need to flip the image. Use convert again
  313. in_fname = fname + ".tga"
  314. flipped_fname = fname + "_flip.tga"
  315. args = ["convert", in_fname, "-flip", flipped_fname]
  316. subprocess.check_call(args)
  317. in_fname = flipped_fname
  318. # Continue
  319. out_fname = os.path.join(tmp_dir, os.path.basename(fname) + ".dds")
  320. printi(" %s" % out_fname)
  321. args = ["nvcompress", "-silent", "-nomips"]
  322. if fast:
  323. args.append("-fast")
  324. if color_format == CF_RGB8:
  325. if not normal:
  326. args.append("-bc1")
  327. else:
  328. args.append("-bc1n")
  329. elif color_format == CF_RGBA8:
  330. args.append("-alpha")
  331. if not normal:
  332. args.append("-bc3")
  333. else:
  334. args.append("-bc3n")
  335. args.append(in_fname)
  336. args.append(out_fname)
  337. subprocess.check_call(args, stdout = subprocess.PIPE)
  338. def write_raw(tex_file, fname, width, height, color_format):
  339. """ Append raw data to the AnKi texture file """
  340. printi(" Appending %s" % fname)
  341. # Read and check the header
  342. uncompressed_tga_header = struct.pack("BBBBBBBBBBBB", 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0)
  343. in_file = open(fname, "rb")
  344. tga_header = in_file.read(12)
  345. if len(tga_header) != 12:
  346. raise Exception("Failed reading TGA header")
  347. if uncompressed_tga_header != tga_header:
  348. raise Exception("Incorrect TGA header")
  349. # Read the size and bpp
  350. header6_buff = in_file.read(6)
  351. if len(header6_buff) != 6:
  352. raise Exception("Failed reading TGA header #2")
  353. header6 = struct.unpack("BBBBBB", header6_buff)
  354. img_width = header6[1] * 256 + header6[0]
  355. img_height = header6[3] * 256 + header6[2]
  356. img_bpp = header6[4];
  357. if (color_format != CF_RGB8 or img_bpp != 24) and (color_format != CF_RGBA8 or img_bpp != 32):
  358. raise Exception("Unexpected bpp")
  359. if img_width != width or img_height != height:
  360. raise Exception("Unexpected width or height")
  361. # Read the data
  362. data_size = width * height
  363. if color_format == CF_RGB8:
  364. data_size *= 3
  365. else:
  366. data_size *= 4
  367. data = bytearray(in_file.read(data_size))
  368. if len(data) != data_size:
  369. raise Exception("Failed to read all data")
  370. tmp = in_file.read(128)
  371. if len(tmp) != 0:
  372. printw(" File shouldn't contain more data")
  373. # Swap colors
  374. bpp = img_bpp / 8
  375. for i in xrange(0, data_size, bpp):
  376. temp = data[i];
  377. data[i] = data[i + 2];
  378. data[i + 2] = temp;
  379. # Write data to tex_file
  380. tex_file.write(data)
  381. def write_s3tc(out_file, fname, width, height, color_format):
  382. """ Append s3tc data to the AnKi texture file """
  383. # Read header
  384. printi(" Appending %s" % fname)
  385. in_file = open(fname, "rb")
  386. header = in_file.read(DdsHeader.get_size())
  387. if len(header) != DdsHeader.get_size():
  388. raise Exception("Failed to read DDS header")
  389. dds_header = DdsHeader(header)
  390. if dds_header.dwWidth != width or dds_header.dwHeight != height:
  391. raise Exception("Incorrect width")
  392. if color_format == CF_RGB8 and dds_header.dwFourCC != "DXT1":
  393. raise Exception("Incorrect format. Expecting DXT1")
  394. if color_format == CF_RGBA8 and dds_header.dwFourCC != "DXT5":
  395. raise Exception("Incorrect format. Expecting DXT5")
  396. # Read and write the data
  397. if color_format == CF_RGB8:
  398. block_size = 8
  399. else:
  400. block_size = 16
  401. data_size = (width / 4) * (height / 4) * block_size
  402. data = in_file.read(data_size)
  403. if len(data) != data_size:
  404. raise Exception("Failed to read DDS data")
  405. # Make sure that the file doesn't contain any more data
  406. tmp = in_file.read(1)
  407. if len(tmp) != 0:
  408. printw(" File shouldn't contain more data")
  409. out_file.write(data)
  410. def write_etc(out_file, fname, width, height, color_format):
  411. """ Append etc2 data to the AnKi texture file """
  412. printi(" Appending %s" % fname)
  413. # Read header
  414. in_file = open(fname, "rb")
  415. header = in_file.read(PkmHeader.get_size())
  416. if len(header) != PkmHeader.get_size():
  417. raise Exception("Failed to read PKM header")
  418. pkm_header = PkmHeader(header)
  419. if pkm_header.magic != "PKM 20":
  420. raise Exception("Incorrect PKM header")
  421. if width != pkm_header.width or height != pkm_header.height:
  422. raise Exception("Incorrect PKM width or height")
  423. # Read and write the data
  424. data_size = (pkm_header.width / 4) * (pkm_header.height / 4) * 8
  425. data = in_file.read(data_size)
  426. if len(data) != data_size:
  427. raise Exception("Failed to read PKM data")
  428. # Make sure that the file doesn't contain any more data
  429. tmp = in_file.read(1)
  430. if len(tmp) != 0:
  431. printw(" File shouldn't contain more data")
  432. out_file.write(data)
  433. def convert(config):
  434. """ This is the function that does all the work """
  435. # Invoke app named "identify" to get internal format and width and height
  436. (color_format, width, height) = identify_image(config.in_files[0])
  437. if not is_power2(width) or not is_power2(height):
  438. raise Exception("Image width and height should power of 2")
  439. if color_format == CF_RGBA8 and config.normal:
  440. raise Exception("RGBA image and normal does not make much sense")
  441. for i in range(1, len(config.in_files)):
  442. (color_format_2, width_2, height_2) = identify_image(config.in_files[i])
  443. if width != width_2 or height != height_2 \
  444. or color_format != color_format_2:
  445. raise Exception("Images are not same size and color space")
  446. if config.no_alpha:
  447. color_format = CF_RGB8
  448. # Create images
  449. for in_file in config.in_files:
  450. mips_fnames = create_mipmaps(in_file, config.tmp_dir, width, height, color_format, config.to_linear_rgb,
  451. config.mips_count)
  452. # Create etc images
  453. create_etc_images(mips_fnames, config.tmp_dir, config.fast, color_format, config.convert_path)
  454. # Create dds images
  455. create_dds_images(mips_fnames, config.tmp_dir, config.fast, color_format, config.normal)
  456. # Open file
  457. fname = config.out_file
  458. printi("Writing %s" % fname)
  459. tex_file = open(fname, "wb")
  460. # Write header
  461. ak_format = "8sIIIIIIII"
  462. data_compression = 0
  463. if config.store_compressed:
  464. data_compression = data_compression | DC_S3TC | DC_ETC2
  465. if config.store_uncompressed:
  466. data_compression = data_compression | DC_RAW
  467. buff = struct.pack(ak_format,
  468. b"ANKITEX1",
  469. width,
  470. height,
  471. len(config.in_files),
  472. config.type,
  473. color_format,
  474. data_compression,
  475. config.normal,
  476. len(mips_fnames))
  477. tex_file.write(buff)
  478. # Write header padding
  479. header_padding_size = 128 - struct.calcsize(ak_format)
  480. if header_padding_size != 88:
  481. raise Exception("Check the header")
  482. for i in range(0, header_padding_size):
  483. tex_file.write('\0')
  484. # For each compression
  485. for compression in range(0, 3):
  486. tmp_width = width
  487. tmp_height = height
  488. # For each level
  489. for i in range(0, len(mips_fnames)):
  490. # For each image
  491. for in_file in config.in_files:
  492. size_str = "%dx%d" % (tmp_width, tmp_height)
  493. in_base_fname = os.path.join(config.tmp_dir, get_base_fname(in_file)) + "." + size_str
  494. # Write RAW
  495. if compression == 0 and config.store_uncompressed:
  496. write_raw(tex_file, in_base_fname + ".tga", tmp_width, tmp_height, color_format)
  497. # Write S3TC
  498. elif compression == 1 and config.store_compressed:
  499. write_s3tc(tex_file, in_base_fname + ".dds", tmp_width, tmp_height, color_format)
  500. # Write ETC
  501. elif compression == 2 and config.store_compressed:
  502. write_etc(tex_file, in_base_fname + "_flip.pkm", tmp_width, tmp_height, color_format)
  503. tmp_width = tmp_width / 2
  504. tmp_height = tmp_height / 2
  505. def main():
  506. """ The main """
  507. # Parse cmd line args
  508. config = parse_commandline();
  509. if config.type == TT_CUBE and len(config.in_files) != 6:
  510. raise Exception("Not enough images for cube generation")
  511. if (config.type == TT_3D or config.type == TT_2D_ARRAY) and len(config.in_files) < 2:
  512. #raise Exception("Not enough images for 2DArray/3D texture")
  513. printw("Not enough images for 2DArray/3D texture")
  514. if config.type == TT_2D and len(config.in_files) != 1:
  515. raise Exception("Only one image for 2D textures needed")
  516. if not os.path.isfile(config.convert_path):
  517. raise Exception("Tool convert not found: " + config.convert_path)
  518. # Setup the temp dir
  519. config.tmp_dir = tempfile.mkdtemp("_ankitex")
  520. # Do the work
  521. try:
  522. convert(config)
  523. finally:
  524. shutil.rmtree(config.tmp_dir)
  525. # Done
  526. printi("Done!")
  527. if __name__ == "__main__":
  528. main()