|
| 1 | +from pathlib import Path |
| 2 | + |
| 3 | +from ._common import bin_dir, get_executable_path, run |
| 4 | +from .exceptions import ToolNotFoundException |
| 5 | + |
| 6 | +_toktx_cli_name = "toktx" |
| 7 | +_toktx_cli_path = get_executable_path(bin_dir / _toktx_cli_name, _toktx_cli_name) |
| 8 | + |
| 9 | +_ktx_cli_name = "ktx" |
| 10 | +_ktx_cli_path = get_executable_path(bin_dir / _ktx_cli_name, _ktx_cli_name) |
| 11 | + |
| 12 | +_ktx2ktx2_cli_name = "ktx2ktx2" |
| 13 | +_ktx2ktx2_cli_path = get_executable_path( |
| 14 | + bin_dir / _ktx2ktx2_cli_name, _ktx2ktx2_cli_name |
| 15 | +) |
| 16 | + |
| 17 | + |
| 18 | +class KhronosKtxTool: |
| 19 | + @classmethod |
| 20 | + def is_available(cls) -> bool: |
| 21 | + return ( |
| 22 | + _ktx_cli_path is not None |
| 23 | + and _ktx2ktx2_cli_path is not None |
| 24 | + and _toktx_cli_path is not None |
| 25 | + ) |
| 26 | + |
| 27 | + @classmethod |
| 28 | + def convert_ktx_to_png( |
| 29 | + cls, filepath: Path, output_folder: Path | None = None |
| 30 | + ) -> Path: |
| 31 | + cls._ensure_tool_installed() |
| 32 | + |
| 33 | + ktx2_filepath = filepath.with_suffix(".ktx2") |
| 34 | + output_filepath = filepath.with_suffix(".png") |
| 35 | + if output_folder is not None: |
| 36 | + output_filepath = output_folder / output_filepath.name |
| 37 | + |
| 38 | + run(f"{_ktx2ktx2_cli_path} {filepath!s}") |
| 39 | + run(f"{_ktx_cli_path} extract {ktx2_filepath!s} {output_filepath!s}") |
| 40 | + |
| 41 | + return output_filepath |
| 42 | + |
| 43 | + @classmethod |
| 44 | + def convert_png_to_ktx( |
| 45 | + cls, filepath: Path, output_folder: Path | None = None |
| 46 | + ) -> Path: |
| 47 | + cls._ensure_tool_installed() |
| 48 | + |
| 49 | + output_filepath = filepath.with_suffix(".ktx") |
| 50 | + if output_folder is not None: |
| 51 | + output_filepath = output_folder / output_filepath.name |
| 52 | + |
| 53 | + run( |
| 54 | + f"{_toktx_cli_path} --encode etc1s --genmipmap {output_filepath!s} {filepath!s}" |
| 55 | + ) |
| 56 | + |
| 57 | + return output_filepath |
| 58 | + |
| 59 | + @classmethod |
| 60 | + def _ensure_tool_installed(cls): |
| 61 | + if cls.is_available(): |
| 62 | + return |
| 63 | + |
| 64 | + raise ToolNotFoundException("ktx-tool not found.") |
0 commit comments