diff --git a/.github/scripts/bench-native-cpu.py b/.github/scripts/bench-native-cpu.py new file mode 100755 index 0000000..1c071af --- /dev/null +++ b/.github/scripts/bench-native-cpu.py @@ -0,0 +1,326 @@ +#!/usr/bin/env python3 +""" +Cross-platform zero-dependency native CPU ASTC benchmark runner (ctypes -> astc-encoder v5.7.1). +Works directly against the prebuilt Plugins/ binaries on Windows (SSE4.1 & AVX2), macOS (ARM64 NEON), +and Linux (SSE4.1 / AVX2), outputting structured JSON for CI summaries and README automation. +""" + +import argparse +import concurrent.futures +import ctypes +import datetime +import json +import math +import os +import platform +import statistics +import subprocess +import time + +ASTCENC_PRF_LDR = 1 +ASTCENC_TYPE_U8 = 0 +ASTCENC_FLG_DECOMPRESS_ONLY = 1 << 4 +ASTCENC_FLG_SELF_DECOMPRESS_ONLY = 1 << 5 + + +class AstcencSwizzle(ctypes.Structure): + _fields_ = [ + ("r", ctypes.c_int), + ("g", ctypes.c_int), + ("b", ctypes.c_int), + ("a", ctypes.c_int), + ] + + +class AstcencImage(ctypes.Structure): + _fields_ = [ + ("dim_x", ctypes.c_uint32), + ("dim_y", ctypes.c_uint32), + ("dim_z", ctypes.c_uint32), + ("data_type", ctypes.c_int), + ("data", ctypes.POINTER(ctypes.c_void_p)), + ] + + +class AstcNativeLib: + def __init__(self, path: str): + self.path = path + self.lib = ctypes.CDLL(path) + + self.config_init = self.lib.astcenc_config_init + self.config_init.argtypes = [ + ctypes.c_int, ctypes.c_uint32, ctypes.c_uint32, ctypes.c_uint32, + ctypes.c_float, ctypes.c_uint32, ctypes.c_void_p, + ] + self.config_init.restype = ctypes.c_int + + self.context_alloc = self.lib.astcenc_context_alloc + self.context_alloc.argtypes = [ + ctypes.c_void_p, ctypes.c_uint32, ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p, + ] + self.context_alloc.restype = ctypes.c_int + + self.compress_image = self.lib.astcenc_compress_image + self.compress_image.argtypes = [ + ctypes.c_void_p, ctypes.POINTER(AstcencImage), ctypes.POINTER(AstcencSwizzle), + ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32, + ] + self.compress_image.restype = ctypes.c_int + + self.compress_reset = self.lib.astcenc_compress_reset + self.compress_reset.argtypes = [ctypes.c_void_p] + self.compress_reset.restype = ctypes.c_int + + self.decompress_image = self.lib.astcenc_decompress_image + self.decompress_image.argtypes = [ + ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, + ctypes.POINTER(AstcencImage), ctypes.POINTER(AstcencSwizzle), ctypes.c_uint32, + ] + self.decompress_image.restype = ctypes.c_int + + self.decompress_reset = self.lib.astcenc_decompress_reset + self.decompress_reset.argtypes = [ctypes.c_void_p] + self.decompress_reset.restype = ctypes.c_int + + self.context_free = self.lib.astcenc_context_free + self.context_free.argtypes = [ctypes.c_void_p] + self.context_free.restype = None + + +def create_procedural_rgba8(width: int, height: int) -> bytearray: + buf = bytearray(width * height * 4) + pi = math.pi + w_den = max(1, width - 1) + h_den = max(1, height - 1) + w_q = width // 4 + h_q = height // 4 + idx = 0 + for y in range(height): + v = y / h_den + y_chk = y >> 3 + for x in range(width): + if x < w_q and y < h_q: + buf[idx] = 96 + buf[idx + 1] = 144 + buf[idx + 2] = 192 + buf[idx + 3] = 255 + else: + u = x / w_den + wave = 0.5 + 0.5 * math.sin((u * 18.0 + v * 12.0) * pi) + chk = 0.15 if (((x >> 3) + y_chk) & 1) == 0 else -0.15 + r = int(round((u * 0.7 + wave * 0.3 + chk) * 255.0)) + g = int(round((v * 0.7 + (1.0 - wave) * 0.3 - chk) * 255.0)) + b = int(round(((u + v) * 0.4 + wave * 0.2) * 255.0)) + a = int(round((0.2 + 0.8 * abs(math.sin((u - v) * 4.0 * pi))) * 255.0)) + buf[idx] = 0 if r < 0 else (255 if r > 255 else r) + buf[idx + 1] = 0 if g < 0 else (255 if g > 255 else g) + buf[idx + 2] = 0 if b < 0 else (255 if b > 255 else b) + buf[idx + 3] = 0 if a < 0 else (255 if a > 255 else a) + idx += 4 + return buf + + +def detect_cpu_model() -> str: + sys_name = platform.system() + try: + if sys_name == "Darwin": + return subprocess.check_output(["sysctl", "-n", "machdep.cpu.brand_string"], text=True).strip() + if sys_name == "Linux": + with open("/proc/cpuinfo", "r", encoding="utf-8") as f: + for line in f: + if line.startswith("model name"): + return line.split(":", 1)[1].strip() + if sys_name == "Windows": + out = subprocess.check_output( + ["powershell", "-NoProfile", "-Command", "(Get-CimInstance Win32_Processor).Name"], + text=True, + ).strip() + if out: + return out + except Exception: + pass + return platform.processor() or platform.machine() + + +def measure_fn(warmup: int, iterations: int, total_pixels: int, fn): + for _ in range(warmup): + fn() + samples = [] + for _ in range(iterations): + t0 = time.perf_counter() + fn() + t1 = time.perf_counter() + samples.append((t1 - t0) * 1000.0) + samples.sort() + median_ms = statistics.median(samples) + p95_idx = min(len(samples) - 1, max(0, math.ceil(len(samples) * 0.95) - 1)) + mpix_s = ((total_pixels / 1e6) / (median_ms / 1000.0)) if median_ms > 1e-6 else 0.0 + return { + "MinMs": round(samples[0], 3), + "MedianMs": round(median_ms, 3), + "MeanMs": round(sum(samples) / len(samples), 3), + "P95Ms": round(samples[p95_idx], 3), + "MaxMs": round(samples[-1], 3), + "ThroughputMPixPerSec": round(mpix_s, 3), + } + + +def run_lib_benchmarks(lib_path: str, isa_label: str, width: int, height: int, rgba_buf: bytearray, threads: int, warmup: int, iterations: int): + api = AstcNativeLib(lib_path) + src_arr = (ctypes.c_uint8 * len(rgba_buf)).from_buffer(rgba_buf) + src_ptr = ctypes.c_void_p(ctypes.addressof(src_arr)) + slices = (ctypes.c_void_p * 1)(src_ptr) + swz = AstcencSwizzle(0, 1, 2, 3) + + blocks = [("ASTC_4x4", 4), ("ASTC_6x6", 6), ("ASTC_8x8", 8), ("ASTC_12x12", 12)] + qualities = [("Fast", 10.0), ("Medium", 60.0)] + results = [] + + with concurrent.futures.ThreadPoolExecutor(max_workers=threads) as pool: + for bs_name, dim in blocks: + out_len = ((width + dim - 1) // dim) * ((height + dim - 1) // dim) * 16 + out_buf = (ctypes.c_uint8 * out_len)() + out_ptr = ctypes.c_void_p(ctypes.addressof(out_buf)) + + for q_name, q_val in qualities: + cfg = ctypes.create_string_buffer(256) + rc = api.config_init(ASTCENC_PRF_LDR, dim, dim, 1, q_val, ASTCENC_FLG_SELF_DECOMPRESS_ONLY, cfg) + if rc != 0: + raise RuntimeError(f"astcenc_config_init failed ({rc}) for {bs_name} {q_name}") + + ctx = ctypes.c_void_p() + rc = api.context_alloc(cfg, threads, ctypes.byref(ctx), None) + if rc != 0: + raise RuntimeError(f"astcenc_context_alloc failed ({rc}) for {bs_name} {q_name}") + + try: + def do_compress(): + if threads <= 1: + img = AstcencImage(width, height, 1, ASTCENC_TYPE_U8, slices) + api.compress_image(ctx, ctypes.byref(img), ctypes.byref(swz), out_ptr, out_len, 0) + else: + futs = [] + for t in range(threads): + def worker(ti=t): + img = AstcencImage(width, height, 1, ASTCENC_TYPE_U8, slices) + api.compress_image(ctx, ctypes.byref(img), ctypes.byref(swz), out_ptr, out_len, ti) + futs.append(pool.submit(worker)) + for f in futs: + f.result() + api.compress_reset(ctx) + + st = measure_fn(warmup, iterations, width * height, do_compress) + results.append({ + "Name": f"Native_{isa_label}_{width}_{bs_name}_{q_name}_{threads}T", + "Category": "Native_CPU", + "ISA": isa_label, + "Resolution": f"{width}x{height}", + "BlockSize": bs_name, + "Quality": q_name, + "Threads": threads, + "OutputBytes": out_len, + **st, + }) + finally: + api.context_free(ctx) + + # Decompression benchmark on ASTC_6x6 + dim = 6 + out_len = ((width + dim - 1) // dim) * ((height + dim - 1) // dim) * 16 + out_buf = (ctypes.c_uint8 * out_len)() + out_ptr = ctypes.c_void_p(ctypes.addressof(out_buf)) + dec_buf = (ctypes.c_uint8 * (width * height * 4))() + dec_slices = (ctypes.c_void_p * 1)(ctypes.c_void_p(ctypes.addressof(dec_buf))) + + cfg = ctypes.create_string_buffer(256) + api.config_init(ASTCENC_PRF_LDR, dim, dim, 1, 10.0, ASTCENC_FLG_SELF_DECOMPRESS_ONLY, cfg) + cctx = ctypes.c_void_p() + api.context_alloc(cfg, threads, ctypes.byref(cctx), None) + img = AstcencImage(width, height, 1, ASTCENC_TYPE_U8, slices) + api.compress_image(cctx, ctypes.byref(img), ctypes.byref(swz), out_ptr, out_len, 0) + api.context_free(cctx) + + dcfg = ctypes.create_string_buffer(256) + api.config_init(ASTCENC_PRF_LDR, dim, dim, 1, 0.0, ASTCENC_FLG_DECOMPRESS_ONLY, dcfg) + dctx = ctypes.c_void_p() + api.context_alloc(dcfg, threads, ctypes.byref(dctx), None) + try: + def do_decompress(): + if threads <= 1: + dimg = AstcencImage(width, height, 1, ASTCENC_TYPE_U8, dec_slices) + api.decompress_image(dctx, out_ptr, out_len, ctypes.byref(dimg), ctypes.byref(swz), 0) + else: + futs = [] + for t in range(threads): + def worker(ti=t): + dimg = AstcencImage(width, height, 1, ASTCENC_TYPE_U8, dec_slices) + api.decompress_image(dctx, out_ptr, out_len, ctypes.byref(dimg), ctypes.byref(swz), ti) + futs.append(pool.submit(worker)) + for f in futs: + f.result() + api.decompress_reset(dctx) + + st = measure_fn(warmup, max(iterations, 7), width * height, do_decompress) + results.append({ + "Name": f"Native_{isa_label}_Decompress_{width}_ASTC_6x6_{threads}T", + "Category": "Native_CPU_Decompress", + "ISA": isa_label, + "Resolution": f"{width}x{height}", + "BlockSize": "ASTC_6x6", + "Quality": "N/A", + "Threads": threads, + "OutputBytes": width * height * 4, + **st, + }) + finally: + api.context_free(dctx) + + return results + + +def main(): + parser = argparse.ArgumentParser(description="Native CPU astc-encoder benchmark runner") + parser.add_argument("--lib", action="append", required=True, help="ISA=PATH pair (e.g. AVX2=path/to/dll)") + parser.add_argument("--size", type=int, default=512, help="Square test texture dimension (default: 512)") + parser.add_argument("--threads", type=int, default=0, help="Worker thread count (0 = auto min(cores, 4))") + parser.add_argument("--warmup", type=int, default=1) + parser.add_argument("--iterations", type=int, default=5) + parser.add_argument("--out", required=True, help="Output JSON report path") + args = parser.parse_args() + + cores = os.cpu_count() or 1 + threads = args.threads if args.threads > 0 else max(1, min(cores, 4)) + rgba = create_procedural_rgba8(args.size, args.size) + + report = { + "SchemaVersion": "1.0", + "TimestampUtc": datetime.datetime.now(datetime.timezone.utc).isoformat(), + "GitCommit": os.environ.get("GITHUB_SHA", ""), + "Platform": f"{platform.system()} {platform.machine()}", + "CpuModel": detect_cpu_model(), + "CpuCores": cores, + "ThreadsUsed": threads, + "Results": [], + } + + for spec in args.lib: + if "=" not in spec: + raise ValueError(f"--lib expects ISA=PATH, got: {spec}") + isa, path = spec.split("=", 1) + if not os.path.exists(path): + raise FileNotFoundError(f"Native library not found: {path}") + print(f"[bench-native-cpu] Running {isa} ({path}) with {threads} threads on {args.size}x{args.size}...") + report["Results"].extend( + run_lib_benchmarks(path, isa, args.size, args.size, rgba, threads, args.warmup, args.iterations) + ) + + out_dir = os.path.dirname(os.path.abspath(args.out)) + if out_dir: + os.makedirs(out_dir, exist_ok=True) + with open(args.out, "w", encoding="utf-8") as f: + json.dump(report, f, indent=2) + print(f"[bench-native-cpu] Wrote {len(report['Results'])} results to {args.out}") + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/build-linux-astcenc.sh b/.github/scripts/build-linux-astcenc.sh new file mode 100755 index 0000000..ce28e68 --- /dev/null +++ b/.github/scripts/build-linux-astcenc.sh @@ -0,0 +1,161 @@ +#!/usr/bin/env bash +set -euo pipefail + +META_ONLY=false +if [[ "${1:-}" == "--meta-only" ]]; then + META_ONLY=true + shift +fi + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" +SUBMODULE_DIR="${REPO_ROOT}/ThirdParty/astc-encoder" +PLUGIN_ROOT="${1:-${REPO_ROOT}/Assets/ASTC Encoder/Plugins/Linux}" +TARGET_DIR="${PLUGIN_ROOT}/x86_64" +mkdir -p "${TARGET_DIR}" + +if [[ "${META_ONLY}" == "false" ]]; then + WORK_DIR="$(mktemp -d)" + + cleanup() { + rm -rf "${WORK_DIR}" + } + trap cleanup EXIT + + if [[ ! -f "${SUBMODULE_DIR}/CMakeLists.txt" ]]; then + echo "[build-linux-astcenc] Initializing ThirdParty/astc-encoder submodule..." + git -C "${REPO_ROOT}" submodule update --init --depth 1 ThirdParty/astc-encoder + fi + + echo "[build-linux-astcenc] Building Linux x86_64 libastcenc-sse4.1-shared.so from ThirdParty/astc-encoder..." + cmake -S "${SUBMODULE_DIR}" -B "${WORK_DIR}/build" \ + -DCMAKE_BUILD_TYPE=Release \ + -DASTCENC_CLI=OFF \ + -DASTCENC_SHAREDLIB=ON \ + -DASTCENC_ISA_SSE41=ON \ + -DASTCENC_WERROR=OFF + + cmake --build "${WORK_DIR}/build" --target astcenc-sse4.1-shared --parallel "$(nproc)" + + BUILT_SO="$(find "${WORK_DIR}/build" -name 'libastcenc-sse4.1-shared.so' | head -n 1)" + if [[ -z "${BUILT_SO}" || ! -f "${BUILT_SO}" ]]; then + echo "[build-linux-astcenc] ERROR: libastcenc-sse4.1-shared.so was not produced." >&2 + exit 1 + fi + + strip --strip-unneeded "${BUILT_SO}" + cp "${BUILT_SO}" "${TARGET_DIR}/libastcenc-sse4.1-shared.so" +fi + +cat > "${PLUGIN_ROOT}.meta" <<'EOF' +fileFormatVersion: 2 +guid: 8e4a1c9b6d5f4028fb3a95647d1c0e86 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: +EOF + +cat > "${TARGET_DIR}.meta" <<'EOF' +fileFormatVersion: 2 +guid: 9f5b2d0c7e6a4139ac4b06758e2d1f97 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: +EOF + +cat > "${TARGET_DIR}/libastcenc-sse4.1-shared.so.meta" <<'EOF' +fileFormatVersion: 2 +guid: a06c3e1d8f7b4240bd5c17869f3e2a08 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + : Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux64: 0 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 1 + Exclude iOS: 1 + - first: + Android: Android + second: + enabled: 0 + settings: + CPU: ARMv7 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: Linux + - first: + Standalone: Linux64 + second: + enabled: 1 + settings: + CPU: x86_64 + - first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Win64 + second: + enabled: 0 + settings: + CPU: None + - first: + iPhone: iOS + second: + enabled: 0 + settings: + AddToEmbeddedBinaries: false + CPU: AnyCPU + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: +EOF + +if [[ "${META_ONLY}" == "true" ]]; then + echo "[build-linux-astcenc] Generated Unity .meta files under ${PLUGIN_ROOT}" +else + echo "[build-linux-astcenc] Installed ${TARGET_DIR}/libastcenc-sse4.1-shared.so" + file "${TARGET_DIR}/libastcenc-sse4.1-shared.so" + nm -D --defined-only "${TARGET_DIR}/libastcenc-sse4.1-shared.so" | grep -E " T astcenc_" +fi diff --git a/.github/scripts/update-benchmark-docs.py b/.github/scripts/update-benchmark-docs.py new file mode 100755 index 0000000..c1a1eee --- /dev/null +++ b/.github/scripts/update-benchmark-docs.py @@ -0,0 +1,371 @@ +#!/usr/bin/env python3 +""" +Aggregates Unity Player (GPU + CPU) and Native CPU benchmark JSON reports, computes +regression/improvement deltas against docs/benchmarks/baseline.json, generates docs/Benchmarks.md, +writes GitHub Actions step summary, and updates blocks in README.md / README_CN.md. +""" + +import argparse +import datetime +import json +import os +import re +from typing import Any, Dict, List, Optional, Tuple + + +MARKER_START = "" +MARKER_END = "" + + +def load_json(path: Optional[str]) -> Optional[Dict[str, Any]]: + if not path or not os.path.exists(path): + return None + with open(path, "r", encoding="utf-8-sig") as f: + return json.load(f) + + +def fmt_delta(curr_ms: float, base_ms: Optional[float]) -> str: + if base_ms is None or base_ms <= 1e-6: + return "new" + pct = (curr_ms - base_ms) / base_ms * 100.0 + if pct <= -5.0: + return f"🚀 {pct:+.1f}%" + if pct >= 15.0: + return f"⚠️ {pct:+.1f}%" + return f"{pct:+.1f}%" + + +def vram_saved_pct(compressed_bytes: int, uncompressed_bytes: int) -> str: + if uncompressed_bytes <= 0 or compressed_bytes <= 0: + return "—" + saved = (1.0 - compressed_bytes / uncompressed_bytes) * 100.0 + return f"-{saved:.1f}%" + + +def index_results(report: Optional[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]: + if not report: + return {} + return {r["Name"]: r for r in report.get("Results", []) if "Name" in r} + + +def build_readme_block( + lang: str, + unity_report: Optional[Dict[str, Any]], + native_reports: List[Dict[str, Any]], + commit_sha: str, + run_url: str, +) -> str: + is_cn = lang == "cn" + lines: List[str] = [] + short_sha = commit_sha[:7] if commit_sha else "local" + date_str = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d") + u_idx = index_results(unity_report) + + if unity_report and u_idx: + gpu_model = unity_report.get("GpuModel", "Unknown GPU") + gfx_api = unity_report.get("GraphicsDeviceType", "") + cpu_model = unity_report.get("CpuModel", "Unknown CPU") + cpu_cores = unity_report.get("CpuCores", "?") + unity_ver = unity_report.get("UnityVersion", "") + + if is_cn: + lines.append( + f"以下数据由 GitHub Actions 在 **`{gpu_model}`({gfx_api})+ `{cpu_model}`({cpu_cores} 核) / Unity `{unity_ver}`** 上自动实测生成(无 Editor 开销的 Standalone Player,预热 + 多次采样中位数):" + ) + lines.append("") + lines.append("#### GPU Compute vs. CPU 编码对比(`1024×1024` RGBA8)") + lines.append("") + lines.append("| 块尺寸 | 质量 | GPU 耗时 (ms) | CPU 耗时 (ms) | GPU 加速比 | GPU / CPU PSNR | 显存节省 |") + lines.append("| :--- | :--- | ---: | ---: | ---: | ---: | ---: |") + else: + lines.append( + f"Measured automatically via GitHub Actions on **`{gpu_model}` ({gfx_api}) + `{cpu_model}` ({cpu_cores} cores) / Unity `{unity_ver}`** (Release Standalone Player, warmup + multi-iteration median):" + ) + lines.append("") + lines.append("#### GPU Compute vs. CPU Encoding (`1024×1024` RGBA8)") + lines.append("") + lines.append("| Block Size | Quality | GPU Median (ms) | CPU Median (ms) | GPU Speedup | GPU / CPU PSNR | VRAM Saved |") + lines.append("| :--- | :--- | ---: | ---: | ---: | ---: | ---: |") + + for bs in ["ASTC_4x4", "ASTC_6x6", "ASTC_8x8", "ASTC_12x12"]: + for q in ["Fast", "Medium"]: + g = u_idx.get(f"GPU_RGBA8_1024_{bs}_{q}") + c = u_idx.get(f"CPU_RGBA8_1024_{bs}_{q}") + if not g and not c: + continue + g_ms = f"{g['MedianMs']:.2f}" if g else "—" + c_ms = f"{c['MedianMs']:.2f}" if c else "—" + spd = f"**{c['MedianMs'] / g['MedianMs']:.1f}×**" if (g and c and g["MedianMs"] > 1e-6) else "—" + g_psnr = f"{g['RgbPsnrDb']:.1f}" if (g and g.get("RgbPsnrDb", 0) > 0) else "—" + c_psnr = f"{c['RgbPsnrDb']:.1f}" if (c and c.get("RgbPsnrDb", 0) > 0) else "—" + psnr_col = f"{g_psnr} / {c_psnr} dB" if (g_psnr != "—" or c_psnr != "—") else "—" + ref = g or c + saved = vram_saved_pct(ref.get("OutputBytes", 0), ref.get("UncompressedBytes", 0)) + bs_label = bs.replace("ASTC_", "ASTC ") + lines.append(f"| **{bs_label}** | `{q}` | {g_ms} | {c_ms} | {spd} | {psnr_col} | {saved} |") + + # Key Runtime Highlights table + highlights = [] + zr = u_idx.get("GPU_ZeroReadback_1024_6x6_Fast") + if zr: + highlights.append(( + "GPU 零回读 `CompressToTexture` (`1024×1024 6x6 Fast`)" if is_cn else "GPU Zero-Readback `CompressToTexture` (`1024×1024 6x6 Fast`)", + f"**{zr['MedianMs']:.2f} ms** ({zr['ThroughputMPixPerSec']:.1f} MP/s)", + f"{zr['GcAllocBytesPerOp'] / 1024.0:.1f} KB", + "直拷硬件 ASTC 纹理,无 CPU 回读" if is_cn else "Direct `CopyTexture`, zero CPU readback", + )) + zrm = u_idx.get("GPU_ZeroReadback_MipGen_1024_6x6_Fast") + if zrm: + highlights.append(( + "GPU 单 CommandBuffer MipGen + 编码 (`1024×1024+Mips`)" if is_cn else "Single-`CommandBuffer` GPU MipGen + Encode (`1024×1024+Mips`)", + f"**{zrm['MedianMs']:.2f} ms** ({zrm['ThroughputMPixPerSec']:.1f} MP/s)", + f"{zrm['GcAllocBytesPerOp'] / 1024.0:.1f} KB", + "11 级 Mip 生成与编码一体化完成" if is_cn else "Full 11-mip chain generated & encoded on GPU", + )) + gn = u_idx.get("GPU_Normal_512_6x6_Medium") + cn = u_idx.get("CPU_Normal_512_6x6_Medium") + if gn: + err_txt = f"GPU {gn.get('MeanNormalDeg', 0):.2f}°" + (f" vs CPU {cn.get('MeanNormalDeg', 0):.2f}°" if cn else "") + highlights.append(( + "法线贴图 GGGR 编码 (`512×512 6x6 Medium`)" if is_cn else "Normal Map GGGR Encoding (`512×512 6x6 Medium`)", + f"GPU **{gn['MedianMs']:.2f} ms**" + (f" vs CPU {cn['MedianMs']:.2f} ms" if cn else ""), + f"{gn['GcAllocBytesPerOp'] / 1024.0:.1f} KB", + f"平均角度误差:{err_txt}" if is_cn else f"Mean angular error: {err_txt}", + )) + rp = u_idx.get("CPU_CompressRawPixelsInto_512_6x6_Fast") + if rp: + highlights.append(( + "原始像素直压 `CompressRawPixelsInto` (`512×512 6x6 Fast`)" if is_cn else "Zero-Alloc `CompressRawPixelsInto` (`512×512 6x6 Fast`)", + f"**{rp['MedianMs']:.2f} ms** ({rp['ThroughputMPixPerSec']:.1f} MP/s)", + f"**{rp['GcAllocBytesPerOp']} B**", + "复用 NativeArray + `AstcContextPool`" if is_cn else "Caller-owned `NativeArray` + `AstcContextPool`", + )) + dc = u_idx.get("DiskCache_TryLoad_512_6x6_FullMips") + if dc: + highlights.append(( + "KTX 磁盘缓存秒开 `AstcDiskCache.TryLoad` (`512×512+Mips`)" if is_cn else "KTX Disk Cache `AstcDiskCache.TryLoad` (`512×512+Mips`)", + f"**{dc['MedianMs']:.2f} ms**", + f"{dc['GcAllocBytesPerOp'] / 1024.0:.1f} KB", + "一次压缩,后续启动直传 GPU" if is_cn else "Compress once, instant load on subsequent launches", + )) + + if highlights: + lines.append("") + if is_cn: + lines.append("#### 关键运行时特性实测") + lines.append("") + lines.append("| 场景 | 中位数耗时 / 吞吐 | GC 分配 | 说明 |") + lines.append("| :--- | :--- | ---: | :--- |") + else: + lines.append("#### Key Runtime Highlights") + lines.append("") + lines.append("| Scenario | Median / Throughput | GC Alloc | Notes |") + lines.append("| :--- | :--- | ---: | :--- |") + for sc, tm, gc, nt in highlights: + lines.append(f"| {sc} | {tm} | {gc} | {nt} |") + + # Cross-platform Native CPU SIMD table (Windows AVX2 vs SSE4.1, macOS NEON, Linux SSE4.1) + if native_reports: + lines.append("") + if is_cn: + lines.append("#### 跨平台原生 CPU 指令集实测(`astc-encoder v5.7.1`,`512×512` RGBA8 `ASTC_6x6`)") + lines.append("") + lines.append("| 平台 / CPU | 指令集(ISA) | 线程 | `Fast` (ms) | `Medium` (ms) | `Fast` 吞吐 | CPU 软解 (ms) |") + lines.append("| :--- | :--- | ---: | ---: | ---: | ---: | ---: |") + else: + lines.append("#### Cross-Platform Native CPU SIMD (`astc-encoder v5.7.1`, `512×512` RGBA8 `ASTC_6x6`)") + lines.append("") + lines.append("| Platform / CPU | ISA | Threads | `Fast` (ms) | `Medium` (ms) | `Fast` MP/s | Decompress (ms) |") + lines.append("| :--- | :--- | ---: | ---: | ---: | ---: | ---: |") + + for nr in native_reports: + plat = nr.get("Platform", "Unknown") + cpu = nr.get("CpuModel", "") + threads = nr.get("ThreadsUsed", "?") + by_isa: Dict[str, Dict[str, Dict[str, Any]]] = {} + for r in nr.get("Results", []): + isa = r.get("ISA", "Default") + by_isa.setdefault(isa, {}) + if r.get("Category") == "Native_CPU_Decompress": + by_isa[isa]["DECOMPRESS"] = r + elif r.get("BlockSize") == "ASTC_6x6": + by_isa[isa][r.get("Quality", "")] = r + + for isa, m in by_isa.items(): + fast = m.get("Fast") + med = m.get("Medium") + dec = m.get("DECOMPRESS") + f_ms = f"{fast['MedianMs']:.2f}" if fast else "—" + m_ms = f"{med['MedianMs']:.2f}" if med else "—" + f_mp = f"{fast['ThroughputMPixPerSec']:.2f}" if fast else "—" + d_ms = f"{dec['MedianMs']:.2f}" if dec else "—" + label = f"{plat} (`{cpu}`)" if cpu else plat + lines.append(f"| {label} | `{isa}` | {threads} | {f_ms} | {m_ms} | {f_mp} | {d_ms} |") + + lines.append("") + run_link = f" · [Actions Run]({run_url})" if run_url else "" + if is_cn: + lines.append( + f"> 基准溯源:Commit `{short_sha}` · {date_str} · [查看完整全矩阵与基线对比(docs/Benchmarks.md)](docs/Benchmarks.md){run_link}" + ) + else: + lines.append( + f"> Provenance: Commit `{short_sha}` · {date_str} · [Full Benchmark Matrix & Regression Baseline (docs/Benchmarks.md)](docs/Benchmarks.md){run_link}" + ) + + return "\n".join(lines) + + +def build_full_docs_markdown( + unity_report: Optional[Dict[str, Any]], + native_reports: List[Dict[str, Any]], + baseline: Optional[Dict[str, Any]], + commit_sha: str, + run_url: str, +) -> str: + base_unity = index_results((baseline or {}).get("unity")) + base_native: Dict[str, Dict[str, Any]] = {} + for nr in (baseline or {}).get("native", []): + plat = nr.get("Platform", "") + for r in nr.get("Results", []): + base_native[f"{plat}::{r['Name']}"] = r + + date_str = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M UTC") + short_sha = commit_sha[:7] if commit_sha else "local" + + lines = [ + "# Runtime ASTC Encoder — Performance Benchmarks & Regression Baseline", + "", + f"- **Updated**: `{date_str}` | **Commit**: `{short_sha}`" + (f" | [GitHub Actions Run]({run_url})" if run_url else ""), + "- **Baseline Comparison**: Deltas (`Δ vs Baseline`) compare each benchmark's median latency against the previous saved snapshot in `docs/benchmarks/baseline.json` (`🚀` ≥ 5% faster, `⚠️` ≥ 15% slower).", + "", + ] + + if unity_report: + lines.extend([ + "## 1. Unity Standalone Player (Real Hardware GPU + CPU)", + "", + f"- **GPU**: `{unity_report.get('GpuModel')}` (`{unity_report.get('GraphicsDeviceType')}`)", + f"- **CPU**: `{unity_report.get('CpuModel')}` ({unity_report.get('CpuCores')} cores)", + f"- **Unity**: `{unity_report.get('UnityVersion')}` | **Platform**: `{unity_report.get('Platform')}`", + f"- **GPU Direct CopyTexture**: `4x4={unity_report.get('SupportsDirectCopy4x4')}`, `6x6={unity_report.get('SupportsDirectCopy6x6')}`", + "", + "| Benchmark | Backend | Res | Block | Quality | Min (ms) | Median (ms) | P95 (ms) | MP/s | GC (KB) | RGB PSNR | Normal Err | Δ vs Baseline |", + "| :--- | :--- | :--- | :--- | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |", + ]) + + for r in unity_report.get("Results", []): + prev = base_unity.get(r["Name"]) + delta = fmt_delta(r["MedianMs"], prev["MedianMs"] if prev else None) + psnr = f"{r['RgbPsnrDb']:.2f} dB" if r.get("RgbPsnrDb", 0) > 0 else "—" + norm = f"{r['MeanNormalDeg']:.2f}°" if r.get("MeanNormalDeg", 0) > 0 else "—" + lines.append( + f"| `{r['Name']}` | {r['Backend']} | {r['Resolution']} | {r['BlockSize']} | {r['Quality']} " + f"| {r['MinMs']:.2f} | **{r['MedianMs']:.2f}** | {r['P95Ms']:.2f} | {r['ThroughputMPixPerSec']:.2f} " + f"| {r['GcAllocBytesPerOp'] / 1024.0:.1f} | {psnr} | {norm} | {delta} |" + ) + lines.append("") + + if native_reports: + lines.extend([ + "## 2. Cross-Platform Native CPU (`astc-encoder v5.7.1`)", + "", + "| Platform / CPU | Benchmark | ISA | Threads | Min (ms) | Median (ms) | P95 (ms) | MP/s | Δ vs Baseline |", + "| :--- | :--- | :--- | ---: | ---: | ---: | ---: | ---: | ---: |", + ]) + for nr in native_reports: + plat = nr.get("Platform", "") + cpu = nr.get("CpuModel", "") + plat_label = f"{plat} (`{cpu}`)" if cpu else plat + for r in nr.get("Results", []): + prev = base_native.get(f"{plat}::{r['Name']}") + delta = fmt_delta(r["MedianMs"], prev["MedianMs"] if prev else None) + lines.append( + f"| {plat_label} | `{r['Name']}` | `{r.get('ISA', '')}` | {r.get('Threads', '')} " + f"| {r['MinMs']:.2f} | **{r['MedianMs']:.2f}** | {r['P95Ms']:.2f} | {r['ThroughputMPixPerSec']:.2f} | {delta} |" + ) + lines.append("") + + return "\n".join(lines) + + +def replace_marker_block(file_path: str, new_content: str) -> bool: + if not os.path.exists(file_path): + return False + with open(file_path, "r", encoding="utf-8") as f: + text = f.read() + + pattern = re.compile( + re.escape(MARKER_START) + r".*?" + re.escape(MARKER_END), + flags=re.DOTALL, + ) + replacement = f"{MARKER_START}\n{new_content}\n{MARKER_END}" + if not pattern.search(text): + print(f"[update-benchmark-docs] WARNING: markers not found in {file_path}, skipping.") + return False + + updated = pattern.sub(replacement, text, count=1) + with open(file_path, "w", encoding="utf-8") as f: + f.write(updated) + return True + + +def main(): + parser = argparse.ArgumentParser(description="Generate benchmark docs, regression diff, and update READMEs") + parser.add_argument("--unity-report", help="Path to Unity Player benchmark JSON") + parser.add_argument("--native-report", action="append", default=[], help="Path(s) to native CPU benchmark JSON") + parser.add_argument("--baseline", default="docs/benchmarks/baseline.json", help="Previous baseline JSON path") + parser.add_argument("--write-baseline", default="docs/benchmarks/baseline.json", help="Output baseline JSON path") + parser.add_argument("--docs-out", default="docs/Benchmarks.md", help="Full benchmark markdown report path") + parser.add_argument("--readme-en", default="README.md") + parser.add_argument("--readme-cn", default="README_CN.md") + parser.add_argument("--step-summary", help="Optional path to append GitHub Actions step summary") + parser.add_argument("--commit", default=os.environ.get("GITHUB_SHA", "")) + parser.add_argument("--run-url", default="") + args = parser.parse_args() + + unity_report = load_json(args.unity_report) + native_reports = [r for r in (load_json(p) for p in args.native_report) if r is not None] + baseline = load_json(args.baseline) + + if not unity_report and not native_reports: + raise SystemExit("No benchmark reports provided.") + + full_md = build_full_docs_markdown(unity_report, native_reports, baseline, args.commit, args.run_url) + docs_dir = os.path.dirname(os.path.abspath(args.docs_out)) + if docs_dir: + os.makedirs(docs_dir, exist_ok=True) + with open(args.docs_out, "w", encoding="utf-8") as f: + f.write(full_md) + print(f"[update-benchmark-docs] Wrote {args.docs_out}") + + en_block = build_readme_block("en", unity_report, native_reports, args.commit, args.run_url) + cn_block = build_readme_block("cn", unity_report, native_reports, args.commit, args.run_url) + if replace_marker_block(args.readme_en, en_block): + print(f"[update-benchmark-docs] Updated {args.readme_en}") + if replace_marker_block(args.readme_cn, cn_block): + print(f"[update-benchmark-docs] Updated {args.readme_cn}") + + if args.write_baseline: + base_dir = os.path.dirname(os.path.abspath(args.write_baseline)) + if base_dir: + os.makedirs(base_dir, exist_ok=True) + new_baseline = { + "SchemaVersion": "1.0", + "TimestampUtc": datetime.datetime.now(datetime.timezone.utc).isoformat(), + "GitCommit": args.commit, + "unity": unity_report, + "native": native_reports, + } + with open(args.write_baseline, "w", encoding="utf-8") as f: + json.dump(new_baseline, f, indent=2) + print(f"[update-benchmark-docs] Saved baseline to {args.write_baseline}") + + if args.step_summary: + with open(args.step_summary, "a", encoding="utf-8") as f: + f.write(full_md + "\n") + print(f"[update-benchmark-docs] Appended summary to {args.step_summary}") + + +if __name__ == "__main__": + main() diff --git a/.github/scripts/verify-native-plugins.sh b/.github/scripts/verify-native-plugins.sh new file mode 100755 index 0000000..b2bc9bd --- /dev/null +++ b/.github/scripts/verify-native-plugins.sh @@ -0,0 +1,89 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/../.." && pwd)" +PLUGINS_DIR="${REPO_ROOT}/Assets/ASTC Encoder/Plugins" + +REQUIRED_SYMBOLS=( + "astcenc_config_init" + "astcenc_context_alloc" + "astcenc_compress_image" + "astcenc_compress_reset" + "astcenc_compress_cancel" + "astcenc_decompress_image" + "astcenc_decompress_reset" + "astcenc_context_free" +) + +check_not_lfs_pointer() { + local path="$1" + if [[ ! -f "${path}" ]]; then + echo "ERROR: Missing native plugin: ${path}" >&2 + exit 1 + fi + if head -n 1 "${path}" | grep -q "^version https://git-lfs.github.com/spec/v1"; then + echo "ERROR: Native plugin is still a Git LFS pointer (run 'git lfs pull'): ${path}" >&2 + exit 1 + fi +} + +check_elf_symbols() { + local path="$1" + local exports + exports="$(nm -D --defined-only "${path}")" + for sym in "${REQUIRED_SYMBOLS[@]}"; do + if ! grep -q " T ${sym}$" <<< "${exports}"; then + echo "ERROR: Missing exported symbol '${sym}' in ${path}" >&2 + exit 1 + fi + done +} + +check_binary_contains_symbols() { + local path="$1" + local dump + dump="$(strings "${path}")" + for sym in "${REQUIRED_SYMBOLS[@]}"; do + if ! grep -q "${sym}" <<< "${dump}"; then + echo "ERROR: Missing expected symbol reference '${sym}' in ${path}" >&2 + exit 1 + fi + done +} + +echo "[verify-native-plugins] Checking prebuilt native plugins..." + +WIN_SSE41="${PLUGINS_DIR}/x64/astcenc-sse4.1-shared.dll" +WIN_AVX2="${PLUGINS_DIR}/x64/astcenc-avx2-shared.dll" +MAC_DYLIB="${PLUGINS_DIR}/Mac/libastcenc-shared.dylib" +ANDROID_ARM64="${PLUGINS_DIR}/Android/arm64-v8a/libastcenc-neon-shared.so" +ANDROID_ARMV7="${PLUGINS_DIR}/Android/armeabi-v7a/libastcenc-none-shared.so" +IOS_STATIC="${PLUGINS_DIR}/iOS/libastcenc-neon-static.a" + +for f in "${WIN_SSE41}" "${WIN_AVX2}" "${MAC_DYLIB}" "${ANDROID_ARM64}" "${ANDROID_ARMV7}" "${IOS_STATIC}"; do + check_not_lfs_pointer "${f}" + file "${f}" +done + +file "${WIN_SSE41}" | grep -q "PE32+.*x86-64" +file "${WIN_AVX2}" | grep -q "PE32+.*x86-64" +file "${MAC_DYLIB}" | grep -q "Mach-O universal binary" +file "${ANDROID_ARM64}" | grep -q "ELF 64-bit.*ARM aarch64" +file "${ANDROID_ARMV7}" | grep -q "ELF 32-bit.*ARM" +file "${IOS_STATIC}" | grep -q "ar archive" + +check_elf_symbols "${ANDROID_ARM64}" +check_elf_symbols "${ANDROID_ARMV7}" +check_binary_contains_symbols "${WIN_SSE41}" +check_binary_contains_symbols "${WIN_AVX2}" +check_binary_contains_symbols "${MAC_DYLIB}" +check_binary_contains_symbols "${IOS_STATIC}" + +if [[ -f "${PLUGINS_DIR}/Linux/x86_64/libastcenc-sse4.1-shared.so" ]]; then + LINUX_SO="${PLUGINS_DIR}/Linux/x86_64/libastcenc-sse4.1-shared.so" + file "${LINUX_SO}" | grep -q "ELF 64-bit.*x86-64" + check_elf_symbols "${LINUX_SO}" +fi + +echo "[verify-native-plugins] All native plugin binaries and required P/Invoke symbols verified." diff --git a/.github/workflows/build-native-plugins.yml b/.github/workflows/build-native-plugins.yml new file mode 100644 index 0000000..532ded2 --- /dev/null +++ b/.github/workflows/build-native-plugins.yml @@ -0,0 +1,407 @@ +name: Build Native ASTC Encoder Plugins + +on: + workflow_dispatch: + inputs: + commit_binaries: + description: 'Commit built binaries directly into Assets/ASTC Encoder/Plugins/ on this branch' + required: false + default: false + type: boolean + push: + branches-ignore: + - master + paths: + - 'ThirdParty/astc-encoder' + - '.github/workflows/build-native-plugins.yml' + +permissions: + contents: read + +jobs: + build-windows-x64: + name: Windows x64 (SSE4.1 DLL) + runs-on: windows-2022 + steps: + - name: Checkout repository and astc-encoder submodule + uses: actions/checkout@v7 + with: + submodules: true + + - name: Configure CMake (Windows x64 SSE4.1) + shell: pwsh + run: | + cmake -S ThirdParty/astc-encoder -B build-win-x64 ` + -G "Visual Studio 17 2022" -A x64 ` + -DASTCENC_CLI=OFF ` + -DASTCENC_SHAREDLIB=ON ` + -DASTCENC_ISA_SSE41=ON ` + -DASTCENC_WERROR=OFF ` + -DCMAKE_MSVC_RUNTIME_LIBRARY="MultiThreaded" + + - name: Build astcenc-sse4.1-shared + shell: pwsh + run: | + cmake --build build-win-x64 --config Release --target astcenc-sse4.1-shared --parallel + + - name: Verify DLL output and exported symbols + shell: pwsh + run: | + $dll = "build-win-x64/Source/Release/astcenc-sse4.1-shared.dll" + if (-not (Test-Path $dll)) { + throw "Expected DLL not found: $dll" + } + Get-Item $dll | Select-Object Name, Length + $vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe" + $vcInstall = & $vswhere -latest -property installationPath + $dumpbin = Get-ChildItem -Path "$vcInstall\VC\Tools\MSVC" -Filter "dumpbin.exe" -Recurse | Where-Object { $_.FullName -like "*Hostx64\x64*" } | Select-Object -First 1 + if ($dumpbin) { + & $dumpbin.FullName /EXPORTS $dll | Select-String "astcenc_" + } + + - name: Upload Windows x64 artifact + uses: actions/upload-artifact@v7 + with: + name: plugin-windows-x64 + path: build-win-x64/Source/Release/astcenc-sse4.1-shared.dll + if-no-files-found: error + + build-windows-x64-avx2: + name: Windows x64 (AVX2 DLL) + runs-on: windows-2022 + steps: + - name: Checkout repository and astc-encoder submodule + uses: actions/checkout@v7 + with: + submodules: true + + - name: Configure CMake (Windows x64 AVX2) + shell: pwsh + run: | + cmake -S ThirdParty/astc-encoder -B build-win-x64-avx2 ` + -G "Visual Studio 17 2022" -A x64 ` + -DASTCENC_CLI=OFF ` + -DASTCENC_SHAREDLIB=ON ` + -DASTCENC_ISA_AVX2=ON ` + -DASTCENC_WERROR=OFF ` + -DCMAKE_MSVC_RUNTIME_LIBRARY="MultiThreaded" + + - name: Build astcenc-avx2-shared + shell: pwsh + run: | + cmake --build build-win-x64-avx2 --config Release --target astcenc-avx2-shared --parallel + + - name: Upload Windows x64 AVX2 artifact + uses: actions/upload-artifact@v7 + with: + name: plugin-windows-x64-avx2 + path: build-win-x64-avx2/Source/Release/astcenc-avx2-shared.dll + if-no-files-found: error + + build-linux-x64: + name: Linux x64 (SSE4.1 SO) + runs-on: ubuntu-22.04 + steps: + - name: Checkout repository and astc-encoder submodule + uses: actions/checkout@v7 + with: + submodules: true + + - name: Configure CMake (Linux x64 SSE4.1) + run: | + cmake -S ThirdParty/astc-encoder -B build-linux-x64 \ + -DCMAKE_BUILD_TYPE=Release \ + -DASTCENC_CLI=OFF \ + -DASTCENC_SHAREDLIB=ON \ + -DASTCENC_ISA_SSE41=ON \ + -DASTCENC_WERROR=OFF + + - name: Build astcenc-sse4.1-shared + run: | + cmake --build build-linux-x64 --target astcenc-sse4.1-shared --parallel + + - name: Strip and verify Linux shared library + run: | + SO="build-linux-x64/Source/libastcenc-sse4.1-shared.so" + test -f "$SO" + strip --strip-unneeded "$SO" + nm -D --defined-only "$SO" | grep "astcenc_config_init" + + - name: Upload Linux x64 artifact + uses: actions/upload-artifact@v7 + with: + name: plugin-linux-x64 + path: build-linux-x64/Source/libastcenc-sse4.1-shared.so + if-no-files-found: error + + build-macos-universal: + name: macOS Universal (x86_64 + x86_64h + arm64 dylib) + runs-on: macos-latest + steps: + - name: Checkout repository and astc-encoder submodule + uses: actions/checkout@v7 + with: + submodules: true + + - name: Configure CMake (macOS Universal) + run: | + cmake -S ThirdParty/astc-encoder -B build-macos \ + -G "Unix Makefiles" \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_OSX_DEPLOYMENT_TARGET=11.0 \ + -DASTCENC_CLI=OFF \ + -DASTCENC_SHAREDLIB=ON \ + -DASTCENC_UNIVERSAL_BUILD=ON \ + -DASTCENC_WERROR=OFF + + - name: Build universal libastcenc-shared.dylib + run: | + cmake --build build-macos --target astcenc-shared --parallel + + - name: Fix install_name and verify dylib + run: | + DYLIB="build-macos/Source/libastcenc-shared.dylib" + test -f "$DYLIB" + install_name_tool -id "@rpath/libastcenc-shared.dylib" "$DYLIB" + lipo -info "$DYLIB" + otool -L "$DYLIB" + nm -gU "$DYLIB" | grep "astcenc_config_init" + + - name: Upload macOS Universal artifact + uses: actions/upload-artifact@v7 + with: + name: plugin-macos-universal + path: build-macos/Source/libastcenc-shared.dylib + if-no-files-found: error + + build-ios-arm64: + name: iOS ARM64 & XCFramework (Device + Simulator) + runs-on: macos-latest + steps: + - name: Checkout repository and astc-encoder submodule + uses: actions/checkout@v7 + with: + submodules: true + + - name: Configure and build iOS Device (arm64 NEON) + run: | + cmake -S ThirdParty/astc-encoder -B build-ios-device \ + -G "Unix Makefiles" \ + -DCMAKE_SYSTEM_NAME=iOS \ + -DCMAKE_OSX_SYSROOT=iphoneos \ + -DCMAKE_OSX_ARCHITECTURES=arm64 \ + -DCMAKE_OSX_DEPLOYMENT_TARGET=12.0 \ + -DCMAKE_BUILD_TYPE=Release \ + -DASTCENC_CLI=OFF \ + -DASTCENC_SHAREDLIB=OFF \ + -DASTCENC_ISA_NEON=ON \ + -DASTCENC_WERROR=OFF + cmake --build build-ios-device --target astcenc-neon-static --parallel + + - name: Configure and build iOS Simulator (arm64 NEON + x86_64 SSE4.1) + run: | + cmake -S ThirdParty/astc-encoder -B build-ios-sim-arm64 \ + -G "Unix Makefiles" \ + -DCMAKE_SYSTEM_NAME=iOS \ + -DCMAKE_OSX_SYSROOT=iphonesimulator \ + -DCMAKE_OSX_ARCHITECTURES=arm64 \ + -DCMAKE_OSX_DEPLOYMENT_TARGET=12.0 \ + -DCMAKE_BUILD_TYPE=Release \ + -DASTCENC_CLI=OFF \ + -DASTCENC_SHAREDLIB=OFF \ + -DASTCENC_ISA_NEON=ON \ + -DASTCENC_WERROR=OFF + cmake --build build-ios-sim-arm64 --target astcenc-neon-static --parallel + + cmake -S ThirdParty/astc-encoder -B build-ios-sim-x64 \ + -G "Unix Makefiles" \ + -DCMAKE_SYSTEM_NAME=iOS \ + -DCMAKE_OSX_SYSROOT=iphonesimulator \ + -DCMAKE_OSX_ARCHITECTURES=x86_64 \ + -DCMAKE_OSX_DEPLOYMENT_TARGET=12.0 \ + -DCMAKE_BUILD_TYPE=Release \ + -DASTCENC_CLI=OFF \ + -DASTCENC_SHAREDLIB=OFF \ + -DASTCENC_ISA_SSE41=ON \ + -DASTCENC_WERROR=OFF + cmake --build build-ios-sim-x64 --target astcenc-sse4.1-static --parallel + + mkdir -p build-ios-sim + lipo -create \ + build-ios-sim-arm64/Source/libastcenc-neon-static.a \ + build-ios-sim-x64/Source/libastcenc-sse4.1-static.a \ + -output build-ios-sim/libastcenc-static.a + + - name: Create astcenc.xcframework and verify static library + run: | + DEV_LIB="build-ios-device/Source/libastcenc-neon-static.a" + SIM_LIB="build-ios-sim/libastcenc-static.a" + test -f "$DEV_LIB" + test -f "$SIM_LIB" + lipo -info "$DEV_LIB" + lipo -info "$SIM_LIB" + nm -gU "$DEV_LIB" | grep "astcenc_config_init" + xcodebuild -create-xcframework \ + -library "$DEV_LIB" \ + -library "$SIM_LIB" \ + -output build-ios-xcframework/astcenc.xcframework + + - name: Upload iOS ARM64 artifact + uses: actions/upload-artifact@v7 + with: + name: plugin-ios-arm64 + path: build-ios-device/Source/libastcenc-neon-static.a + if-no-files-found: error + + - name: Upload iOS XCFramework artifact + uses: actions/upload-artifact@v7 + with: + name: plugin-ios-xcframework + path: build-ios-xcframework/astcenc.xcframework + if-no-files-found: error + + build-android: + name: Android (${{ matrix.abi }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - abi: arm64-v8a + isa_flag: -DASTCENC_ISA_NEON=ON + target: astcenc-neon-shared + output_name: libastcenc-neon-shared.so + - abi: armeabi-v7a + isa_flag: -DASTCENC_ISA_NONE=ON + target: astcenc-none-shared + output_name: libastcenc-none-shared.so + steps: + - name: Checkout repository and astc-encoder submodule + uses: actions/checkout@v7 + with: + submodules: true + + - name: Locate Android NDK and configure CMake + run: | + NDK_DIR="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-${ANDROID_NDK_ROOT}}}" + if [ -z "$NDK_DIR" ] || [ ! -d "$NDK_DIR" ]; then + echo "Android NDK not found!" >&2 + exit 1 + fi + echo "NDK_DIR=$NDK_DIR" >> "$GITHUB_ENV" + echo "Using Android NDK: $NDK_DIR" + cmake -S ThirdParty/astc-encoder -B "build-android-${{ matrix.abi }}" \ + -DCMAKE_TOOLCHAIN_FILE="$NDK_DIR/build/cmake/android.toolchain.cmake" \ + -DANDROID_ABI="${{ matrix.abi }}" \ + -DANDROID_PLATFORM=android-21 \ + -DANDROID_STL=c++_static \ + -DCMAKE_BUILD_TYPE=Release \ + -DCMAKE_SHARED_LINKER_FLAGS="-Wl,-z,max-page-size=16384" \ + -DASTCENC_CLI=OFF \ + -DASTCENC_SHAREDLIB=ON \ + ${{ matrix.isa_flag }} \ + -DASTCENC_WERROR=OFF + + - name: Build ${{ matrix.target }} + run: | + cmake --build "build-android-${{ matrix.abi }}" --target "${{ matrix.target }}" --parallel + + - name: Strip and verify shared library + run: | + SO="build-android-${{ matrix.abi }}/Source/${{ matrix.output_name }}" + test -f "$SO" + LLVM_BIN="$NDK_DIR/toolchains/llvm/prebuilt/linux-x86_64/bin" + "$LLVM_BIN/llvm-strip" --strip-unneeded "$SO" + ls -lh "$SO" + file "$SO" + "$LLVM_BIN/llvm-readelf" -l "$SO" | grep LOAD + "$LLVM_BIN/llvm-nm" -D --defined-only "$SO" | grep "astcenc_config_init" + + - name: Upload Android ${{ matrix.abi }} artifact + uses: actions/upload-artifact@v7 + with: + name: plugin-android-${{ matrix.abi }} + path: build-android-${{ matrix.abi }}/Source/${{ matrix.output_name }} + if-no-files-found: error + + package-plugins: + name: Package Unity Native Plugins + runs-on: ubuntu-latest + needs: + - build-windows-x64 + - build-windows-x64-avx2 + - build-linux-x64 + - build-macos-universal + - build-ios-arm64 + - build-android + permissions: + contents: write + steps: + - name: Checkout repository (with LFS when committing) + uses: actions/checkout@v7 + with: + submodules: true + lfs: ${{ github.event_name == 'workflow_dispatch' && inputs.commit_binaries }} + + - name: Download all platform artifacts into Unity Plugins layout + uses: actions/download-artifact@v8 + with: + path: staging + + - name: Assemble Unity Plugins directory + run: | + mkdir -p \ + dist/Plugins/x64 \ + dist/Plugins/Linux/x86_64 \ + dist/Plugins/Mac \ + dist/Plugins/iOS \ + dist/Plugins/Android/arm64-v8a \ + dist/Plugins/Android/armeabi-v7a + + cp staging/plugin-windows-x64/astcenc-sse4.1-shared.dll dist/Plugins/x64/ + cp staging/plugin-windows-x64-avx2/astcenc-avx2-shared.dll dist/Plugins/x64/ + cp staging/plugin-linux-x64/libastcenc-sse4.1-shared.so dist/Plugins/Linux/x86_64/ + cp staging/plugin-macos-universal/libastcenc-shared.dylib dist/Plugins/Mac/ + cp staging/plugin-ios-arm64/libastcenc-neon-static.a dist/Plugins/iOS/ + mkdir -p dist/Plugins/iOS/astcenc.xcframework + cp -r staging/plugin-ios-xcframework/. dist/Plugins/iOS/astcenc.xcframework/ + cp staging/plugin-android-arm64-v8a/libastcenc-neon-shared.so dist/Plugins/Android/arm64-v8a/ + cp staging/plugin-android-armeabi-v7a/libastcenc-none-shared.so dist/Plugins/Android/armeabi-v7a/ + + VERSION=$(sed -n 's/^project(astcencoder VERSION \([^)]*\)).*/\1/p' ThirdParty/astc-encoder/CMakeLists.txt) + VERSION="${VERSION:-unknown}" + echo "ASTCENC_VERSION=$VERSION" >> "$GITHUB_ENV" + echo "Built astc-encoder version: $VERSION" + find dist/Plugins -type f -exec ls -lh {} + + + - name: Upload combined Unity Plugins artifact + uses: actions/upload-artifact@v7 + with: + name: astcenc-unity-plugins-${{ env.ASTCENC_VERSION }} + path: dist/Plugins/ + if-no-files-found: error + + - name: Commit updated binaries to branch (optional) + if: ${{ github.event_name == 'workflow_dispatch' && inputs.commit_binaries }} + run: | + mkdir -p "Assets/ASTC Encoder/Plugins/Linux/x86_64" + cp dist/Plugins/x64/astcenc-sse4.1-shared.dll "Assets/ASTC Encoder/Plugins/x64/" + cp dist/Plugins/x64/astcenc-avx2-shared.dll "Assets/ASTC Encoder/Plugins/x64/" + cp dist/Plugins/Linux/x86_64/libastcenc-sse4.1-shared.so "Assets/ASTC Encoder/Plugins/Linux/x86_64/" + chmod +x .github/scripts/build-linux-astcenc.sh + ./.github/scripts/build-linux-astcenc.sh --meta-only + cp dist/Plugins/Mac/libastcenc-shared.dylib "Assets/ASTC Encoder/Plugins/Mac/" + cp dist/Plugins/iOS/libastcenc-neon-static.a "Assets/ASTC Encoder/Plugins/iOS/" + cp dist/Plugins/Android/arm64-v8a/libastcenc-neon-shared.so "Assets/ASTC Encoder/Plugins/Android/arm64-v8a/" + cp dist/Plugins/Android/armeabi-v7a/libastcenc-none-shared.so "Assets/ASTC Encoder/Plugins/Android/armeabi-v7a/" + + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + + git add "Assets/ASTC Encoder/Plugins/" + if git diff --cached --quiet; then + echo "No binary changes detected." + else + git commit -m "Update prebuilt astc-encoder native plugins to ${ASTCENC_VERSION}" + git push origin "HEAD:${GITHUB_REF_NAME}" + fi diff --git a/.github/workflows/performance-benchmarks.yml b/.github/workflows/performance-benchmarks.yml new file mode 100644 index 0000000..2eb9b64 --- /dev/null +++ b/.github/workflows/performance-benchmarks.yml @@ -0,0 +1,283 @@ +name: Performance Benchmarks & README Sync + +on: + workflow_dispatch: + inputs: + commit_results: + description: "Commit updated README.md, README_CN.md, docs/Benchmarks.md, and docs/benchmarks/baseline.json" + required: false + default: false + type: boolean + unity_version: + description: "Unity Editor version on GameCI" + required: false + default: "2021.3.6f1" + type: string + iterations: + description: "Measured iterations per benchmark case" + required: false + default: "5" + type: string + +permissions: + contents: write + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + UNITY_VERSION: ${{ inputs.unity_version || '2021.3.6f1' }} + BENCH_ITERS: ${{ inputs.iterations || '5' }} + +jobs: + check-unity-license: + name: Check Unity License + runs-on: ubuntu-latest + outputs: + has_license: ${{ steps.check.outputs.has_license }} + steps: + - id: check + env: + UNITY_LICENSE: ${{ secrets.UNITY_LICENSE }} + UNITY_SERIAL: ${{ secrets.UNITY_SERIAL }} + run: | + if [[ -n "${UNITY_LICENSE}" || -n "${UNITY_SERIAL}" ]]; then + echo "has_license=true" >> "$GITHUB_OUTPUT" + else + echo "has_license=false" >> "$GITHUB_OUTPUT" + echo "::warning::UNITY_LICENSE not configured. Running cross-platform Native CPU benchmarks only." + fi + + native-cpu-bench: + name: Native CPU Bench (${{ matrix.label }}) + strategy: + fail-fast: false + matrix: + include: + - label: Windows-x64 + os: windows-latest + artifact: native-bench-windows + out: bench_native_windows.json + - label: macOS-ARM64 + os: macos-latest + artifact: native-bench-macos + out: bench_native_macos.json + - label: Linux-x64 + os: ubuntu-latest + artifact: native-bench-linux + out: bench_native_linux.json + runs-on: ${{ matrix.os }} + steps: + - name: Checkout repository (with Git LFS & submodules) + uses: actions/checkout@v4 + with: + lfs: true + submodules: ${{ matrix.os == 'ubuntu-latest' }} + + - name: Setup Python + uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Run Windows AVX2 vs SSE4.1 benchmark + if: matrix.os == 'windows-latest' + shell: pwsh + run: | + python .github/scripts/bench-native-cpu.py ` + --lib "AVX2=Assets/ASTC Encoder/Plugins/x64/astcenc-avx2-shared.dll" ` + --lib "SSE4.1=Assets/ASTC Encoder/Plugins/x64/astcenc-sse4.1-shared.dll" ` + --size 512 --warmup 1 --iterations "${{ env.BENCH_ITERS }}" ` + --out "${{ matrix.out }}" + + - name: Run macOS Apple Silicon NEON benchmark + if: matrix.os == 'macos-latest' + run: | + python3 .github/scripts/bench-native-cpu.py \ + --lib "ARM64_NEON=Assets/ASTC Encoder/Plugins/Mac/libastcenc-shared.dylib" \ + --size 512 --warmup 1 --iterations "${{ env.BENCH_ITERS }}" \ + --out "${{ matrix.out }}" + + - name: Build and run Linux x64 SSE4.1 benchmark + if: matrix.os == 'ubuntu-latest' + run: | + chmod +x .github/scripts/build-linux-astcenc.sh + ./.github/scripts/build-linux-astcenc.sh + python3 .github/scripts/bench-native-cpu.py \ + --lib "SSE4.1=Assets/ASTC Encoder/Plugins/Linux/x86_64/libastcenc-sse4.1-shared.so" \ + --size 512 --warmup 1 --iterations "${{ env.BENCH_ITERS }}" \ + --out "${{ matrix.out }}" + + - name: Upload native benchmark JSON + uses: actions/upload-artifact@v4 + with: + name: ${{ matrix.artifact }} + path: ${{ matrix.out }} + retention-days: 7 + + build-macos-bench-player: + name: Build StandaloneOSX Benchmark Player + needs: [check-unity-license] + if: needs.check-unity-license.outputs.has_license == 'true' + runs-on: ubuntu-latest + steps: + - name: Checkout repository (with Git LFS) + uses: actions/checkout@v4 + with: + lfs: true + + - name: Cache Unity Library + uses: actions/cache@v4 + with: + path: Library + key: Library-StandaloneOSX-${{ env.UNITY_VERSION }}-${{ hashFiles('Assets/**', 'Packages/**', 'ProjectSettings/**') }} + restore-keys: | + Library-StandaloneOSX-${{ env.UNITY_VERSION }}- + Library-StandaloneOSX- + + - name: Build macOS Universal Player + uses: game-ci/unity-builder@v4 + env: + UNITY_LICENSE: ${{ secrets.UNITY_LICENSE }} + UNITY_EMAIL: ${{ secrets.UNITY_EMAIL }} + UNITY_PASSWORD: ${{ secrets.UNITY_PASSWORD }} + UNITY_SERIAL: ${{ secrets.UNITY_SERIAL }} + with: + unityVersion: ${{ env.UNITY_VERSION }} + targetPlatform: StandaloneOSX + buildName: ASTCEncoder + versioning: None + allowDirtyBuild: true + buildMethod: Aperture.Astcenc.Editor.CIBuildScript.Build + customParameters: "-scriptingBackend Mono" + + - name: Upload macOS Player artifact + uses: actions/upload-artifact@v4 + with: + name: bench-player-macos + path: build/StandaloneOSX + retention-days: 1 + + unity-metal-gpu-bench: + name: Unity Real Metal GPU + CPU Bench (macOS Apple Silicon) + needs: [build-macos-bench-player] + runs-on: macos-latest + steps: + - name: Download macOS Player + uses: actions/download-artifact@v4 + with: + name: bench-player-macos + path: build/StandaloneOSX + + - name: Run Standalone Player Benchmarks on Apple Silicon Metal GPU + run: | + APP="$(find build/StandaloneOSX -maxdepth 2 -type d -name '*.app' | head -n 1)" + if [[ -z "${APP}" ]]; then + echo "ERROR: macOS .app bundle not found." >&2 + exit 1 + fi + BIN="$(find "${APP}/Contents/MacOS" -maxdepth 1 -type f | head -n 1)" + chmod +x "${BIN}" + xattr -dr com.apple.quarantine "${APP}" || true + + LOG_FILE="${PWD}/bench-macos-metal.log" + OUT_JSON="${PWD}/bench_unity_macos_metal.json" + + # Intentionally omit -nographics so the player executes on real Apple Silicon Metal GPU + # with hardware ASTC sampling and zero-readback CommandBuffer.CopyTexture. + set +e + "${BIN}" -batchmode -logfile "${LOG_FILE}" \ + -astc-benchmark \ + -astc-bench-out "${OUT_JSON}" \ + -astc-bench-warmup 2 \ + -astc-bench-iters "${BENCH_ITERS}" \ + -astc-bench-commit "${GITHUB_SHA}" + STATUS=$? + set -e + + cat "${LOG_FILE}" + if grep -q "ASTC_BENCH_FAILED" "${LOG_FILE}"; then + echo "ERROR: ASTC_BENCH_FAILED detected." >&2 + exit 1 + fi + grep -q "ASTC_BENCH_PASSED" "${LOG_FILE}" + if [[ "${STATUS}" -ne 0 || ! -f "${OUT_JSON}" ]]; then + echo "ERROR: Benchmark exited with status ${STATUS} or JSON missing." >&2 + exit 1 + fi + + - name: Upload Unity Metal GPU benchmark JSON + uses: actions/upload-artifact@v4 + with: + name: unity-bench-macos-metal + path: | + bench_unity_macos_metal.json + bench-macos-metal.log + retention-days: 14 + + publish-benchmark-report: + name: Aggregate Benchmarks, Regression Diff & Sync Docs + needs: [native-cpu-bench, unity-metal-gpu-bench] + if: always() && (needs.native-cpu-bench.result == 'success' || needs.unity-metal-gpu-bench.result == 'success') + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Download all benchmark JSON artifacts + uses: actions/download-artifact@v4 + with: + path: bench-artifacts + + - name: Generate docs/Benchmarks.md, Regression Diff & Update READMEs + run: | + ARGS=() + UNITY_JSON="$(find bench-artifacts -name 'bench_unity_macos_metal.json' | head -n 1 || true)" + if [[ -n "${UNITY_JSON}" ]]; then + ARGS+=(--unity-report "${UNITY_JSON}") + fi + for f in \ + "$(find bench-artifacts -name 'bench_native_windows.json' | head -n 1 || true)" \ + "$(find bench-artifacts -name 'bench_native_macos.json' | head -n 1 || true)" \ + "$(find bench-artifacts -name 'bench_native_linux.json' | head -n 1 || true)"; do + if [[ -n "${f}" && -f "${f}" ]]; then + ARGS+=(--native-report "${f}") + fi + done + + RUN_URL="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" + python3 .github/scripts/update-benchmark-docs.py \ + "${ARGS[@]}" \ + --baseline docs/benchmarks/baseline.json \ + --write-baseline docs/benchmarks/baseline.json \ + --docs-out docs/Benchmarks.md \ + --readme-en README.md \ + --readme-cn README_CN.md \ + --step-summary "${GITHUB_STEP_SUMMARY}" \ + --commit "${GITHUB_SHA}" \ + --run-url "${RUN_URL}" + + - name: Upload aggregated benchmark report artifact + uses: actions/upload-artifact@v4 + with: + name: astc-benchmark-report + path: | + docs/Benchmarks.md + docs/benchmarks/baseline.json + bench-artifacts + retention-days: 30 + + - name: Commit updated READMEs and baseline (when commit_results == true) + if: ${{ github.event_name == 'workflow_dispatch' && inputs.commit_results == true }} + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add README.md README_CN.md docs/Benchmarks.md docs/benchmarks/baseline.json + if git diff --cached --quiet; then + echo "No benchmark doc changes to commit." + exit 0 + fi + git commit -m "Update performance benchmarks and regression baseline [skip ci]" + git push diff --git a/.github/workflows/release-package.yml b/.github/workflows/release-package.yml new file mode 100644 index 0000000..89b2844 --- /dev/null +++ b/.github/workflows/release-package.yml @@ -0,0 +1,152 @@ +name: Release & Publish UPM Package + +on: + pull_request: + types: [closed] + branches: + - master + workflow_dispatch: + inputs: + tag_override: + description: "Optional tag override (e.g. v2.3.0). Defaults to v from package.json" + required: false + default: "" + type: string + +permissions: + contents: write + +jobs: + publish-release: + name: Tag Release & Publish UPM Package + runs-on: ubuntu-latest + if: >- + github.event_name == 'workflow_dispatch' || + (github.event.pull_request.merged == true && github.event.pull_request.head.ref == 'develop') + steps: + - name: Checkout master (with Git LFS binaries) + uses: actions/checkout@v4 + with: + ref: master + fetch-depth: 0 + lfs: true + + - name: Read package metadata and resolve release tag + id: meta + run: | + PKG_JSON="Assets/ASTC Encoder/package.json" + PKG_NAME="$(python3 -c 'import json; print(json.load(open("'"${PKG_JSON}"'", encoding="utf-8"))["name"])')" + PKG_VERSION="$(python3 -c 'import json; print(json.load(open("'"${PKG_JSON}"'", encoding="utf-8"))["version"])')" + TAG_INPUT="${{ inputs.tag_override }}" + TAG="${TAG_INPUT:-v${PKG_VERSION}}" + + echo "pkg_name=${PKG_NAME}" >> "$GITHUB_OUTPUT" + echo "pkg_version=${PKG_VERSION}" >> "$GITHUB_OUTPUT" + echo "tag=${TAG}" >> "$GITHUB_OUTPUT" + echo "Resolved package=${PKG_NAME}, version=${PKG_VERSION}, tag=${TAG}" + + if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then + echo "tag_exists=true" >> "$GITHUB_OUTPUT" + echo "::warning::Tag ${TAG} already exists on remote. Skipping duplicate release creation." + else + echo "tag_exists=false" >> "$GITHUB_OUTPUT" + fi + + - name: Verify prebuilt native plugins are resolved (not LFS pointers) + if: steps.meta.outputs.tag_exists == 'false' + run: | + chmod +x .github/scripts/verify-native-plugins.sh + ./.github/scripts/verify-native-plugins.sh + + - name: Package UPM tarball (.tgz) and Unity Assets archive (.zip) + if: steps.meta.outputs.tag_exists == 'false' + env: + PKG_NAME: ${{ steps.meta.outputs.pkg_name }} + PKG_VERSION: ${{ steps.meta.outputs.pkg_version }} + TAG: ${{ steps.meta.outputs.tag }} + run: | + mkdir -p release-dist/staging/package "release-dist/zip-staging/ASTC Encoder" + + # 1. Standard UPM tarball (root folder must be 'package/' for Unity Package Manager) + cp -a "Assets/ASTC Encoder/." release-dist/staging/package/ + TARBALL="${PKG_NAME}-${PKG_VERSION}.tgz" + tar -czf "release-dist/${TARBALL}" -C release-dist/staging package + + # 2. Direct Assets zip archive for non-UPM installation + cp -a "Assets/ASTC Encoder/." "release-dist/zip-staging/ASTC Encoder/" + ZIPFILE="Runtime-ASTC-Encoder-For-Unity-${TAG}.zip" + (cd release-dist/zip-staging && zip -qr "../${ZIPFILE}" "ASTC Encoder") + + # 3. SHA-256 checksums + (cd release-dist && sha256sum "${TARBALL}" "${ZIPFILE}" > SHA256SUMS.txt) + + echo "tarball=release-dist/${TARBALL}" >> "$GITHUB_OUTPUT" + echo "zipfile=release-dist/${ZIPFILE}" >> "$GITHUB_OUTPUT" + ls -lh release-dist/ + cat release-dist/SHA256SUMS.txt + + - name: Extract release notes from CHANGELOG.md + if: steps.meta.outputs.tag_exists == 'false' + env: + PKG_NAME: ${{ steps.meta.outputs.pkg_name }} + PKG_VERSION: ${{ steps.meta.outputs.pkg_version }} + TAG: ${{ steps.meta.outputs.tag }} + run: | + python3 - <<'EOF' + import os, re + + version = os.environ["PKG_VERSION"] + tag = os.environ["TAG"] + pkg_name = os.environ["PKG_NAME"] + changelog_path = "Assets/ASTC Encoder/CHANGELOG.md" + + section = "" + if os.path.exists(changelog_path): + txt = open(changelog_path, encoding="utf-8").read() + m = re.search(rf"^## \[{re.escape(version)}\][^\n]*\n(.*?)(?=^## \[|\Z)", txt, re.M | re.S) + if m: + section = m.group(1).strip() + + notes = [] + if section: + notes.append(section) + else: + notes.append(f"Release `{tag}` of `{pkg_name}`.") + + notes.append( + "\n---\n\n" + "### Installation\n\n" + "**Unity Package Manager (Git URL):**\n" + "```text\n" + f"https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity.git?path=/Assets/ASTC%20Encoder#{tag}\n" + "```\n\n" + "**UPM Local Tarball:** Download `" + f"{pkg_name}-{version}.tgz` from the assets below and use **Package Manager → `+` → Add package from tarball...**.\n\n" + "**Direct Assets Copy:** Download `" + f"Runtime-ASTC-Encoder-For-Unity-{tag}.zip` and extract into your project's `Assets/` folder.\n" + ) + + with open("release-dist/RELEASE_NOTES.md", "w", encoding="utf-8") as f: + f.write("\n".join(notes)) + EOF + + - name: Create Git Tag and publish GitHub Release + if: steps.meta.outputs.tag_exists == 'false' + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PKG_NAME: ${{ steps.meta.outputs.pkg_name }} + PKG_VERSION: ${{ steps.meta.outputs.pkg_version }} + TAG: ${{ steps.meta.outputs.tag }} + run: | + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + + git tag -a "${TAG}" -m "Release ${TAG}" + git push origin "refs/tags/${TAG}" + + gh release create "${TAG}" \ + "release-dist/${PKG_NAME}-${PKG_VERSION}.tgz" \ + "release-dist/Runtime-ASTC-Encoder-For-Unity-${TAG}.zip" \ + "release-dist/SHA256SUMS.txt" \ + --title "Runtime ASTC Encoder ${TAG}" \ + --notes-file "release-dist/RELEASE_NOTES.md" diff --git a/.github/workflows/unity-multiplatform-e2e.yml b/.github/workflows/unity-multiplatform-e2e.yml new file mode 100644 index 0000000..51faee4 --- /dev/null +++ b/.github/workflows/unity-multiplatform-e2e.yml @@ -0,0 +1,382 @@ +name: Unity Multi-Platform Build & E2E Tests + +on: + workflow_dispatch: + inputs: + unity_version: + description: "Unity Editor version on GameCI (international equivalent of 2021.3.6f1c1)" + required: false + default: "2021.3.6f1" + type: string + run_android_emulator: + description: "Run Android ARM64 emulator E2E test on macOS runner" + required: false + default: true + type: boolean + +permissions: + contents: read + checks: write + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + UNITY_VERSION: ${{ inputs.unity_version || '2021.3.6f1' }} + +jobs: + native-abi-check: + name: Native Plugins & Linux .so Build + runs-on: ubuntu-latest + steps: + - name: Checkout repository (with Git LFS & submodules) + uses: actions/checkout@v4 + with: + lfs: true + submodules: true + + - name: Build Linux x86_64 libastcenc-sse4.1-shared.so + run: | + chmod +x .github/scripts/build-linux-astcenc.sh .github/scripts/verify-native-plugins.sh + ./.github/scripts/build-linux-astcenc.sh + + - name: Verify all platform native plugins and exported symbols + run: ./.github/scripts/verify-native-plugins.sh + + - name: Upload Linux native plugin artifact + uses: actions/upload-artifact@v4 + with: + name: linux-astcenc-plugin + path: | + Assets/ASTC Encoder/Plugins/Linux + Assets/ASTC Encoder/Plugins/Linux.meta + retention-days: 1 + + check-unity-license: + name: Check Unity License Secrets + runs-on: ubuntu-latest + outputs: + has_license: ${{ steps.check.outputs.has_license }} + steps: + - name: Check configured Unity license secrets + id: check + env: + UNITY_LICENSE: ${{ secrets.UNITY_LICENSE }} + UNITY_SERIAL: ${{ secrets.UNITY_SERIAL }} + run: | + if [[ -n "${UNITY_LICENSE}" || -n "${UNITY_SERIAL}" ]]; then + echo "has_license=true" >> "$GITHUB_OUTPUT" + echo "Unity license secret detected. Running Unity Test Runner and multi-platform builds." >> "$GITHUB_STEP_SUMMARY" + else + echo "has_license=false" >> "$GITHUB_OUTPUT" + echo "::warning::UNITY_LICENSE (or UNITY_SERIAL) secret is not configured. Skipping Unity build/test jobs. See docs/CI_E2E_GUIDE.md." + { + echo "### Unity License Secret Not Configured" + echo "Skipped Unity Editor tests and multi-platform player builds because neither \`UNITY_LICENSE\` nor \`UNITY_SERIAL\` is configured in Repository Secrets." + echo "See \`docs/CI_E2E_GUIDE.md\` for setup instructions." + } >> "$GITHUB_STEP_SUMMARY" + fi + + unity-tests: + name: Unity Test Runner (EditMode) + needs: [native-abi-check, check-unity-license] + if: needs.check-unity-license.outputs.has_license == 'true' + runs-on: ubuntu-latest + steps: + - name: Checkout repository (with Git LFS) + uses: actions/checkout@v4 + with: + lfs: true + + - name: Download Linux native plugin + uses: actions/download-artifact@v4 + with: + name: linux-astcenc-plugin + path: Assets/ASTC Encoder/Plugins + + - name: Cache Unity Library + uses: actions/cache@v4 + with: + path: Library + key: Library-tests-${{ env.UNITY_VERSION }}-${{ hashFiles('Assets/**', 'Packages/**', 'ProjectSettings/**') }} + restore-keys: | + Library-tests-${{ env.UNITY_VERSION }}- + Library-tests- + + - name: Run Unity EditMode Tests + uses: game-ci/unity-test-runner@v4.3.2 + env: + UNITY_LICENSE: ${{ secrets.UNITY_LICENSE }} + UNITY_EMAIL: ${{ secrets.UNITY_EMAIL }} + UNITY_PASSWORD: ${{ secrets.UNITY_PASSWORD }} + UNITY_SERIAL: ${{ secrets.UNITY_SERIAL }} + with: + unityVersion: ${{ env.UNITY_VERSION }} + testMode: EditMode + customParameters: -nographics + artifactsPath: test-results + githubToken: ${{ secrets.GITHUB_TOKEN }} + + - name: Upload Unity test results + uses: actions/upload-artifact@v4 + if: always() + with: + name: unity-test-results + path: test-results + retention-days: 7 + + build-players: + name: Build (${{ matrix.targetPlatform }}) + needs: [native-abi-check, check-unity-license] + if: needs.check-unity-license.outputs.has_license == 'true' + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + include: + - targetPlatform: StandaloneLinux64 + customParameters: "-scriptingBackend Mono" + - targetPlatform: StandaloneWindows64 + customParameters: "-scriptingBackend Mono" + - targetPlatform: StandaloneOSX + customParameters: "-scriptingBackend Mono" + - targetPlatform: Android + customParameters: "-scriptingBackend IL2CPP -enableE2ESmoke" + - targetPlatform: iOS + customParameters: "-scriptingBackend IL2CPP -enableE2ESmoke" + steps: + - name: Checkout repository (with Git LFS) + uses: actions/checkout@v4 + with: + lfs: true + + - name: Download Linux native plugin + uses: actions/download-artifact@v4 + with: + name: linux-astcenc-plugin + path: Assets/ASTC Encoder/Plugins + + - name: Cache Unity Library + uses: actions/cache@v4 + with: + path: Library + key: Library-${{ matrix.targetPlatform }}-${{ env.UNITY_VERSION }}-${{ hashFiles('Assets/**', 'Packages/**', 'ProjectSettings/**') }} + restore-keys: | + Library-${{ matrix.targetPlatform }}-${{ env.UNITY_VERSION }}- + Library-${{ matrix.targetPlatform }}- + + - name: Build Unity Player for ${{ matrix.targetPlatform }} + uses: game-ci/unity-builder@v4 + env: + UNITY_LICENSE: ${{ secrets.UNITY_LICENSE }} + UNITY_EMAIL: ${{ secrets.UNITY_EMAIL }} + UNITY_PASSWORD: ${{ secrets.UNITY_PASSWORD }} + UNITY_SERIAL: ${{ secrets.UNITY_SERIAL }} + with: + unityVersion: ${{ env.UNITY_VERSION }} + targetPlatform: ${{ matrix.targetPlatform }} + buildName: ASTCEncoder + versioning: None + allowDirtyBuild: true + buildMethod: Aperture.Astcenc.Editor.CIBuildScript.Build + customParameters: ${{ matrix.customParameters }} + + - name: Upload ${{ matrix.targetPlatform }} build artifact + uses: actions/upload-artifact@v4 + with: + name: build-${{ matrix.targetPlatform }} + path: build/${{ matrix.targetPlatform }} + retention-days: 7 + + e2e-linux: + name: E2E Player (Linux x64) + needs: build-players + runs-on: ubuntu-latest + steps: + - name: Download Linux64 build + uses: actions/download-artifact@v4 + with: + name: build-StandaloneLinux64 + path: build/StandaloneLinux64 + + - name: Run headless Linux Player E2E smoke test + run: | + BIN="$(find build/StandaloneLinux64 -maxdepth 2 -type f \( -name 'ASTCEncoder.x86_64' -o -name 'ASTCEncoder' \) | head -n 1)" + if [[ -z "${BIN}" ]]; then + echo "ERROR: Linux player binary not found." >&2 + find build/StandaloneLinux64 -maxdepth 3 + exit 1 + fi + chmod +x "${BIN}" + LOG_FILE="${PWD}/e2e-linux.log" + set +e + timeout 120 "${BIN}" -batchmode -nographics -logfile "${LOG_FILE}" -astc-e2e + STATUS=$? + set -e + cat "${LOG_FILE}" + if grep -q "ASTC_E2E_FAILED" "${LOG_FILE}"; then + echo "ERROR: ASTC_E2E_FAILED detected in Linux E2E log." >&2 + exit 1 + fi + grep -q "ASTC_E2E_PASSED" "${LOG_FILE}" + if [[ "${STATUS}" -ne 0 && "${STATUS}" -ne 139 ]]; then + echo "ERROR: Linux player exited with unexpected status ${STATUS}" >&2 + exit "${STATUS}" + fi + + e2e-windows: + name: E2E Player (Windows x64) + needs: build-players + runs-on: windows-latest + steps: + - name: Download Windows64 build + uses: actions/download-artifact@v4 + with: + name: build-StandaloneWindows64 + path: build/StandaloneWindows64 + + - name: Run headless Windows Player E2E smoke test + shell: pwsh + run: | + $exe = Get-ChildItem -Path "build/StandaloneWindows64" -Filter "ASTCEncoder.exe" -Recurse | Select-Object -First 1 + if (-not $exe) { + Write-Error "Windows player executable ASTCEncoder.exe not found." + Get-ChildItem -Path "build/StandaloneWindows64" -Recurse + exit 1 + } + $logFile = Join-Path (Get-Location) "e2e-windows.log" + $proc = Start-Process -FilePath $exe.FullName -ArgumentList "-batchmode", "-nographics", "-logfile", $logFile, "-astc-e2e" -NoNewWindow -Wait -PassThru + if (Test-Path $logFile) { + Get-Content $logFile + } + if ($proc.ExitCode -ne 0) { + Write-Error "Windows player exited with code $($proc.ExitCode)" + exit $proc.ExitCode + } + if (-not (Select-String -Path $logFile -Pattern "ASTC_E2E_PASSED" -Quiet)) { + Write-Error "ASTC_E2E_PASSED marker not found in log." + exit 1 + } + + e2e-macos: + name: E2E Player (macOS Universal) + needs: build-players + runs-on: macos-latest + steps: + - name: Download macOS build + uses: actions/download-artifact@v4 + with: + name: build-StandaloneOSX + path: build/StandaloneOSX + + - name: Run headless macOS Player E2E smoke test + run: | + APP="$(find build/StandaloneOSX -maxdepth 2 -type d -name '*.app' | head -n 1)" + if [[ -z "${APP}" ]]; then + echo "ERROR: macOS .app bundle not found." >&2 + find build/StandaloneOSX -maxdepth 3 + exit 1 + fi + BIN="$(find "${APP}/Contents/MacOS" -maxdepth 1 -type f | head -n 1)" + chmod +x "${BIN}" + xattr -dr com.apple.quarantine "${APP}" || true + LOG_FILE="${PWD}/e2e-macos.log" + set +e + "${BIN}" -batchmode -nographics -logfile "${LOG_FILE}" -astc-e2e + STATUS=$? + set -e + cat "${LOG_FILE}" + if grep -q "ASTC_E2E_FAILED" "${LOG_FILE}"; then + echo "ERROR: ASTC_E2E_FAILED detected in macOS E2E log." >&2 + exit 1 + fi + grep -q "ASTC_E2E_PASSED" "${LOG_FILE}" + if [[ "${STATUS}" -ne 0 ]]; then + echo "ERROR: macOS player exited with status ${STATUS}" >&2 + exit "${STATUS}" + fi + + e2e-android: + name: E2E Player (Android ARM64) + needs: build-players + runs-on: macos-latest + steps: + - name: Download Android APK + uses: actions/download-artifact@v4 + with: + name: build-Android + path: build/Android + + - name: Verify APK native libraries (arm64-v8a) + run: | + APK="$(find build/Android -name '*.apk' | head -n 1)" + if [[ -z "${APK}" ]]; then + echo "ERROR: Android APK not found." >&2 + find build/Android -maxdepth 3 + exit 1 + fi + echo "APK_PATH=${APK}" >> "$GITHUB_ENV" + unzip -l "${APK}" | grep "lib/arm64-v8a/libastcenc-neon-shared.so" + unzip -l "${APK}" | grep "lib/arm64-v8a/libil2cpp.so" + + - name: Run APK on Android ARM64 Emulator + if: ${{ inputs.run_android_emulator != false }} + uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: 33 + arch: arm64-v8a + target: default + emulator-options: -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim + script: | + adb logcat -c + adb install -r "${APK_PATH}" + adb shell am start -n com.DefaultCompany.ASTCEncoder/com.unity3d.player.UnityPlayerActivity + for i in $(seq 1 45); do + LOGS="$(adb logcat -d -s Unity:V)" + if grep -q "ASTC_E2E_PASSED" <<< "${LOGS}"; then + echo "${LOGS}" + echo "Android ARM64 E2E passed!" + exit 0 + fi + if grep -q "ASTC_E2E_FAILED" <<< "${LOGS}"; then + echo "${LOGS}" + echo "ERROR: Android ARM64 E2E failed!" >&2 + exit 1 + fi + sleep 2 + done + echo "ERROR: Timed out waiting for ASTC_E2E_PASSED in adb logcat." >&2 + adb logcat -d -s Unity:V + exit 1 + + e2e-ios-xcodebuild: + name: E2E Link & Build (iOS Xcode ARM64) + needs: build-players + runs-on: macos-latest + steps: + - name: Download iOS Xcode project + uses: actions/download-artifact@v4 + with: + name: build-iOS + path: build/iOS + + - name: Verify iOS static library and compile with xcodebuild + run: | + XCODEPROJ="$(find build/iOS -maxdepth 3 -name 'Unity-iPhone.xcodeproj' | head -n 1)" + if [[ -z "${XCODEPROJ}" ]]; then + echo "ERROR: Unity-iPhone.xcodeproj not found." >&2 + find build/iOS -maxdepth 3 + exit 1 + fi + PROJECT_DIR="$(dirname "${XCODEPROJ}")" + find "${PROJECT_DIR}" -name 'libastcenc-neon-static.a' | grep -q 'libastcenc-neon-static.a' + xcodebuild \ + -project "${XCODEPROJ}" \ + -scheme Unity-iPhone \ + -sdk iphoneos \ + -configuration Release \ + CODE_SIGNING_ALLOWED=NO \ + CODE_SIGNING_REQUIRED=NO \ + CODE_SIGN_IDENTITY="" \ + build diff --git a/.github/workflows/verify-shaders-and-code.yml b/.github/workflows/verify-shaders-and-code.yml new file mode 100644 index 0000000..20803f7 --- /dev/null +++ b/.github/workflows/verify-shaders-and-code.yml @@ -0,0 +1,66 @@ +name: Verify Shaders and Unity Metadata + +on: + workflow_dispatch: + +permissions: + contents: read + +jobs: + verify-hlsl-and-meta: + name: Verify HLSL Shaders & Unity .meta Integrity + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Preprocess all HLSL block-size and Fast-only variants + run: | + set -e + SHADERS="Assets/ASTC Encoder/Runtime/Gpu/Shaders" + for bx in 4 5 6 8 10 12; do + clang -E -P -x c -I"$SHADERS" -DBLOCK_X=$bx -DBLOCK_Y=$bx "$SHADERS/AstcGpuCore.hlsl" > /dev/null + clang -E -P -x c -I"$SHADERS" -DBLOCK_X=$bx -DBLOCK_Y=$bx -DASTC_FAST_ONLY=1 "$SHADERS/AstcGpuCore.hlsl" > /dev/null + done + clang -E -P -x c "Assets/ASTC Encoder/Runtime/Resources/AstcGpuMipGenerator.compute" > /dev/null + echo "All HLSL shader variants preprocessed cleanly!" + + - name: Verify Unity .meta files and GUID uniqueness + run: | + python3 - <<'EOF' + import os, re, sys + + root = "Assets/ASTC Encoder" + guids = {} + missing = [] + for dirpath, dirnames, filenames in os.walk(root): + dirnames[:] = [d for d in dirnames if not d.endswith("~") and not d.startswith(".")] + for d in dirnames: + p = os.path.join(dirpath, d) + if not os.path.exists(p + ".meta"): + missing.append(p) + for f in filenames: + if f.endswith(".meta"): + mpath = os.path.join(dirpath, f) + txt = open(mpath, encoding="utf-8", errors="ignore").read() + m = re.search(r"^guid:\s*([0-9a-fA-F]{32})\s*$", txt, re.M) + if not m: + print(f"ERROR: Invalid or missing GUID in {mpath}") + sys.exit(1) + g = m.group(1).lower() + if g in guids: + print(f"ERROR: Duplicate GUID {g} in {mpath} and {guids[g]}") + sys.exit(1) + guids[g] = mpath + else: + p = os.path.join(dirpath, f) + if not os.path.exists(p + ".meta"): + missing.append(p) + + if missing: + print("ERROR: Missing .meta files for:") + for m in missing: + print(" -", m) + sys.exit(1) + print(f"OK: Verified {len(guids)} unique Unity .meta GUIDs with zero missing .meta files.") + EOF diff --git a/.gitignore b/.gitignore index 4da42b5..e89cfe8 100644 --- a/.gitignore +++ b/.gitignore @@ -65,3 +65,7 @@ Thumbs.db # Mac Finder Cache .DS_Store + +# Generated sample output +/Assets/outputTexture.astc +/Assets/outputTexture.astc.meta diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..4368114 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "ThirdParty/astc-encoder"] + path = ThirdParty/astc-encoder + url = https://github.com/ARM-software/astc-encoder.git diff --git a/Assets/ASTC Encoder/CHANGELOG.md b/Assets/ASTC Encoder/CHANGELOG.md new file mode 100644 index 0000000..26ea0bf --- /dev/null +++ b/Assets/ASTC Encoder/CHANGELOG.md @@ -0,0 +1,46 @@ +# Changelog + +All notable changes to `com.aperture.astcenc` (Runtime ASTC Encoder for Unity) are documented in this file. + +## [2.3.0] - 2026-11-28 + +### Added +- **Zero-Readback GPU Mipmap Generation + ASTC Encoding**: New `AstcGpuMipGenerator.compute` (`DownsampleColor` with linear/sRGB-aware premultiplied-alpha box filtering, odd-NPOT edge handling, and HDR NaN/Inf sanitization; `DownsampleNormal` with unit-vector renormalization) integrated via `AstcCompressOptions.GenerateMipmaps` into a single `CommandBuffer` with zero-readback `CommandBuffer.CopyTexture` across aligned and non-multiple block dimensions and full mip chains. +- **Standard KTX v1 Container & Persistent Disk Cache**: + - `AstcKtxContainer` (`Encode`, `TryDecode`, `LoadTexture`) + `Encoder.EncodeToKTX` / `EncodeToKTXAsync` / `LoadFromKTX` supporting full mipmap chains, exact UNorm/sRGB/HDR metadata, and automatic CPU decompression fallback on non-ASTC devices. + - `AstcDiskCache` (`TryLoad`, `TryLoadAsync`, `CompressAndSaveAsync`, `LoadOrCompressAsync`) with atomic `File.Replace` persistence. +- **Windows x64 Runtime AVX2 Auto-Dispatch**: Ships both `astcenc-avx2-shared.dll` and `astcenc-sse4.1-shared.dll` in `Plugins/x64/`, automatically selecting AVX2 via `IsProcessorFeaturePresent(40)` with seamless SSE4.1 fallback. +- **Frame-Budgeted Compression Queue & Global CPU Context Pool**: + - `AstcCompressionQueue` with `High`/`Normal`/`Low` priorities, configurable `MaxGpuTexelsPerFrame` & `MaxConcurrentCpuTasks`, single-`CommandBuffer` GPU batching per frame, and `CancellationToken` support. + - Thread-safe `AstcContextPool` shared across all static CPU entry points with `parentContext` lookup-table sharing and `Encoder.ReleaseCpuContextPool()`. +- **Extended Texture Dimensions & Zero-Alloc Raw Pixel APIs**: + - `sourceSlice` / `destSlice` parameters on `Encoder.Encode` for `Texture2DArray` and `Cubemap`, plus `Encoder.CompressCubemap` and `Encoder.CompressTexture2DArray`. + - `Encoder.CompressRawPixels` / `CompressRawPixelsAsync` (`NativeArray` & `byte[]`) and zero-allocation `Encoder.CompressRawPixelsInto`. +- **Unity Job System Scheduling**: Optional `AstcCompressOptions.UseUnityJobSystem` / `AstcContext.UseUnityJobSystem` dispatching synchronous CPU compression slices on Unity's native `IJobParallelFor` Worker Thread Pool. +- **Editor Quality Inspector & Automated Benchmark Suite**: + - `Window/ASTC Encoder/Benchmark & Inspector` (`Aperture.Astcenc.Editor`) comparing CPU vs GPU side-by-side with decoded previews, amplified error heatmaps, PSNR/RMSE, Normal Map mean/max angular error, timing, memory savings, and `.ktx`/`.astc` export. + - `AstcPerformanceBenchmarkRunner` (`Window/ASTC Encoder/Run Performance Benchmark Suite`), EditMode `[Category("Performance")]` tests (`AstcPerformanceBenchmarks`), and standalone player benchmark pipeline. +- **Golden EditMode Test Suite & Multi-Platform CI**: + - `Aperture.Astcenc.Tests` verifying `AstcHeader`, `AstcKtxContainer` round-trips, `CompressRawPixels`, `AstcContext` parent table sharing, `AstcCompressionQueue` cancellation, and CPU/GPU cross-decode PSNR & normal angular error. + - Linux x64 P/Invoke (`UNITY_EDITOR_LINUX` / `UNITY_STANDALONE_LINUX`), GitHub Actions native plugin builds (Windows AVX2/SSE4.1, macOS Universal, iOS `astcenc.xcframework`, Android, Linux x64), HLSL & `.meta` GUID integrity verification, multi-platform GameCI E2E tests, and hardware performance benchmarks. + +### Changed & Optimized +- **GPU Shader Throughput & Register Footprint**: + - Per-thread packed `RGBA8` pixel cache for `<= 6x6` LDR blocks and per-block `ASTC_MAX_GRID` sizing to cut VGPR usage. + - `[numthreads(8, 4, 1)]` occupancy tuning for `>= 8x8` blocks and zero-`pow()` fast `sqrt` sRGB approximation. + - Row-level early-exit candidate pruning, same-grid weight projection reuse, combined 1P error + worst-channel accumulation, merged 3-pass 2-Partition endpoint fitting, and loop-hoisted `AstcHash52`. +- **UPM Package Hygiene**: Moved repository-only `CIBuildScript` out of the UPM package to `Assets/Editor/` so host projects do not receive extra `Build/CI/*` menu items. + +### Fixed +- Canonicalized endpoints and flipped weights on endpoint swap during GPU candidate error evaluation, resolving PSNR degradation on `Medium`/`Thorough` and `6x6` blocks. +- Recognized 16-bit half-float (`R16G16B16A16_SFloat`) and UFloat HDR formats in the GPU backend and KTX software-decode fallback. +- Fixed Unity 2021.3 Metal shader compilation failure involving `reversebits`. +- Fixed NPOT odd-dimension mip filtering, guarded HDR mip generation on FP16 `LoadStore` support, and fixed HDR readable copy & GGGR normal-map unpacking in `AstcBenchmarkWindow`. +- Fixed `Cubemap` constructor argument order, `parentContext` use-after-free, post-await texture access, and `AstcRaw` leak in `AstcCompressionQueue`. +- Hardened `AstcKtxContainer.TryDecode`, `CompressRawPixelsAsync`, `CompressRawPixelsInto`, and decompression bitness/bounds/slice validation against integer overflows, malformed headers, and redundant allocations. + +## [2.0.0] - 2026-11-26 + +### Added +- **Unified Dual-Backend (`Cpu` / `Gpu` / `Auto`)**: Custom tableless HLSL Compute Shader ASTC encoder supporting `4x4`..`12x12`, LDR/sRGB/Normal/HDR (`CEM 11/14/15`), `ASTC_FAST_ONLY` kernels, dynamic-CCS Dual-Plane, anisotropic grids, angular-error normal encoding, post-quantization endpoint refit, and zero-readback `CommandBuffer.CopyTexture`. +- **CPU `astc-encoder v5.7.1`**: Software decompression (`Encoder.Decompress*`), `parentContext` lookup-table sharing, `UsePerceptual`, `AlphaScaleRadius`, compact async snapshots, and `AstcCompressOptions`. diff --git a/Assets/ASTC Encoder/CHANGELOG.md.meta b/Assets/ASTC Encoder/CHANGELOG.md.meta new file mode 100644 index 0000000..7c83ac3 --- /dev/null +++ b/Assets/ASTC Encoder/CHANGELOG.md.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 5e2a9d4c7b1840f3a615c9e8d2f47b01 +TextScriptImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Editor.meta b/Assets/ASTC Encoder/Editor.meta new file mode 100644 index 0000000..5fb93cb --- /dev/null +++ b/Assets/ASTC Encoder/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 7b9e3a41d8c24f50a1e6c9038b72d41e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Editor/Aperture.Astcenc.Editor.asmdef b/Assets/ASTC Encoder/Editor/Aperture.Astcenc.Editor.asmdef new file mode 100644 index 0000000..bd6df3f --- /dev/null +++ b/Assets/ASTC Encoder/Editor/Aperture.Astcenc.Editor.asmdef @@ -0,0 +1,18 @@ +{ + "name": "Aperture.Astcenc.Editor", + "rootNamespace": "Aperture.Astcenc.Editor", + "references": [ + "Aperture.Astcenc.Runtime" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": false, + "precompiledReferences": [], + "autoReferenced": true, + "defineConstraints": [], + "versionDefines": [], + "noEngineReferences": false +} diff --git a/Assets/ASTC Encoder/Editor/Aperture.Astcenc.Editor.asmdef.meta b/Assets/ASTC Encoder/Editor/Aperture.Astcenc.Editor.asmdef.meta new file mode 100644 index 0000000..05b95ec --- /dev/null +++ b/Assets/ASTC Encoder/Editor/Aperture.Astcenc.Editor.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 4f8c1d2e9a374b658c01e7f2a9b54d38 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Editor/AstcBenchmarkWindow.cs b/Assets/ASTC Encoder/Editor/AstcBenchmarkWindow.cs new file mode 100644 index 0000000..fadfa33 --- /dev/null +++ b/Assets/ASTC Encoder/Editor/AstcBenchmarkWindow.cs @@ -0,0 +1,594 @@ +using System; +using System.IO; +using Aperture.Astcenc.Runtime; +using UnityEditor; +using UnityEngine; +using UnityEngine.Experimental.Rendering; + +namespace Aperture.Astcenc.Editor +{ + /// + /// Unity Editor window for visually inspecting and benchmarking runtime ASTC compression + /// (CPU vs GPU side-by-side), computing PSNR / RMSE / Normal Angular Error, and viewing amplified error heatmaps. + /// + public class AstcBenchmarkWindow : EditorWindow + { + private enum BenchmarkMode + { + CompareCpuAndGpu, + GpuOnly, + CpuOnly + } + + private sealed class BenchmarkResult : IDisposable + { + public string Label; + public double EncodeMs; + public double MinMs; + public double P95Ms; + public double ThroughputMPixPerSec; + public long GcAllocBytesPerOp; + public int CompressedBytes; + public int UncompressedBytes; + public double RgbPsnrDb; + public double RgbaPsnrDb; + public double RgbRmse; + public double AlphaRmse; + public double MeanNormalDeg; + public double MaxNormalDeg; + public Texture2D DecodedPreview; + public Texture2D HeatmapPreview; + + public void Dispose() + { + if (DecodedPreview != null) + { + DestroyImmediate(DecodedPreview); + DecodedPreview = null; + } + if (HeatmapPreview != null) + { + DestroyImmediate(HeatmapPreview); + HeatmapPreview = null; + } + } + } + + private Texture2D m_SourceTexture; + private TextureType m_TextureType = TextureType.Default; + private BlockSize m_BlockSize = BlockSize.ASTC_6x6; + private CompressQuality m_Quality = CompressQuality.Fast; + private bool m_UseAlphaWeight; + private bool m_UsePerceptual; + private bool m_GenerateMipmaps; + private bool m_ReuseCpuContext = true; + private int m_WarmupRuns = 2; + private int m_Iterations = 5; + private BenchmarkMode m_Mode = BenchmarkMode.CompareCpuAndGpu; + private float m_HeatmapGain = 10f; + private bool m_ShowAlphaOnly; + private Vector2 m_ScrollPos; + + private Texture2D m_ReferencePreview; + private BenchmarkResult m_GpuResult; + private BenchmarkResult m_CpuResult; + private string m_StatusMessage; + + [MenuItem("Window/ASTC Encoder/Benchmark & Inspector")] + public static void OpenWindow() + { + var window = GetWindow("ASTC Benchmark"); + window.minSize = new Vector2(720f, 520f); + window.Show(); + } + + private void OnDisable() + { + ClearResults(); + } + + private void ClearResults() + { + if (m_ReferencePreview != null) + { + DestroyImmediate(m_ReferencePreview); + m_ReferencePreview = null; + } + m_GpuResult?.Dispose(); + m_GpuResult = null; + m_CpuResult?.Dispose(); + m_CpuResult = null; + } + + private void OnGUI() + { + m_ScrollPos = EditorGUILayout.BeginScrollView(m_ScrollPos); + + EditorGUILayout.LabelField("Runtime ASTC Encoder — Visual Benchmark & Quality Inspector", EditorStyles.boldLabel); + EditorGUILayout.Space(4f); + + using (new EditorGUILayout.VerticalScope("box")) + { + m_SourceTexture = (Texture2D)EditorGUILayout.ObjectField("Source Texture2D", m_SourceTexture, typeof(Texture2D), false); + m_Mode = (BenchmarkMode)EditorGUILayout.EnumPopup("Backend Mode", m_Mode); + m_TextureType = (TextureType)EditorGUILayout.EnumPopup("Texture Type", m_TextureType); + m_BlockSize = (BlockSize)EditorGUILayout.EnumPopup("Block Size", m_BlockSize); + m_Quality = (CompressQuality)EditorGUILayout.EnumPopup("Quality", m_Quality); + m_UseAlphaWeight = EditorGUILayout.Toggle("Use Alpha Weight", m_UseAlphaWeight); + m_UsePerceptual = EditorGUILayout.Toggle("Perceptual (CPU)", m_UsePerceptual); + m_GenerateMipmaps = EditorGUILayout.Toggle("Generate Mipmaps (GPU)", m_GenerateMipmaps); + m_ReuseCpuContext = EditorGUILayout.Toggle("Reuse CPU Context (Warm)", m_ReuseCpuContext); + m_WarmupRuns = EditorGUILayout.IntSlider("Warmup Runs", m_WarmupRuns, 0, 10); + m_Iterations = EditorGUILayout.IntSlider("Benchmark Iterations", m_Iterations, 1, 30); + m_HeatmapGain = EditorGUILayout.Slider("Error Heatmap Gain", m_HeatmapGain, 1f, 32f); + m_ShowAlphaOnly = EditorGUILayout.Toggle("Preview Alpha Channel", m_ShowAlphaOnly); + } + + EditorGUILayout.Space(6f); + + using (new EditorGUILayout.HorizontalScope()) + { + GUI.enabled = m_SourceTexture != null; + if (GUILayout.Button("Run Benchmark", GUILayout.Height(30f))) + { + RunBenchmark(); + } + if (GUILayout.Button("Export .ktx", GUILayout.Height(30f), GUILayout.Width(100f))) + { + ExportFile("ktx"); + } + if (GUILayout.Button("Export .astc", GUILayout.Height(30f), GUILayout.Width(100f))) + { + ExportFile("astc"); + } + GUI.enabled = true; + + if (GUILayout.Button("Run Full Suite", GUILayout.Height(30f), GUILayout.Width(120f))) + { + AstcBenchmarkReport report = AstcPerformanceBenchmarkRunner.RunFullSuite( + warmup: Math.Max(1, m_WarmupRuns), + iterations: Math.Max(3, m_Iterations), + exportReports: true, + out string exportDir); + m_StatusMessage = $"Full performance suite completed ({report.Results.Count} cases). Reports exported to: {exportDir}"; + Debug.Log($"{m_StatusMessage}\n{AstcPerformanceBenchmarkRunner.FormatMarkdownTable(report)}"); + } + } + + if (!string.IsNullOrEmpty(m_StatusMessage)) + { + EditorGUILayout.HelpBox(m_StatusMessage, MessageType.Info); + } + + if (m_GpuResult != null) + DrawResultSection(m_GpuResult); + + if (m_CpuResult != null) + DrawResultSection(m_CpuResult); + + EditorGUILayout.EndScrollView(); + } + + private void RunBenchmark() + { + ClearResults(); + m_StatusMessage = null; + + if (m_SourceTexture == null) + return; + + int width = m_SourceTexture.width; + int height = m_SourceTexture.height; + bool isHdr = IsHdrFormat(m_SourceTexture.graphicsFormat); + bool isSrgb = m_TextureType == TextureType.Default && GraphicsFormatUtility.IsSRGBFormat(m_SourceTexture.graphicsFormat); + + Texture2D readableSource = CreateReadableCopy(m_SourceTexture, isSrgb, isHdr); + try + { + Color[] refPixels = readableSource.GetPixels(0); + m_ReferencePreview = BuildPreviewTexture(refPixels, width, height, m_ShowAlphaOnly); + + if (m_Mode == BenchmarkMode.CompareCpuAndGpu || m_Mode == BenchmarkMode.GpuOnly) + { + if (Encoder.IsGpuSupported) + { + m_GpuResult = ExecuteBackend(readableSource, refPixels, EncodeBackend.Gpu, "GPU Compute", isSrgb, isHdr); + } + else + { + m_StatusMessage = "GPU Compute backend is not supported on the current graphics device."; + } + } + + if (m_Mode == BenchmarkMode.CompareCpuAndGpu || m_Mode == BenchmarkMode.CpuOnly) + { + m_CpuResult = ExecuteBackend(readableSource, refPixels, EncodeBackend.Cpu, "CPU Native (astcenc)", isSrgb, isHdr); + } + } + catch (Exception ex) + { + m_StatusMessage = $"Benchmark failed: {ex.Message}"; + Debug.LogException(ex); + } + finally + { + DestroyImmediate(readableSource); + } + } + + private BenchmarkResult ExecuteBackend( + Texture2D readableSource, + Color[] refPixels, + EncodeBackend backend, + string label, + bool isSrgb, + bool isHdr) + { + int width = readableSource.width; + int height = readableSource.height; + bool gpuGenMips = backend == EncodeBackend.Gpu && m_GenerateMipmaps; + int threadCount = Math.Max(1, Environment.ProcessorCount / 2); + + var options = new AstcCompressOptions + { + TextureType = m_TextureType, + BlockSize = m_BlockSize, + Quality = m_Quality, + IncludeMipmaps = gpuGenMips, + GenerateMipmaps = gpuGenMips, + UseAlphaWeight = m_UseAlphaWeight, + UsePerceptual = m_UsePerceptual, + ThreadCount = threadCount, + Backend = backend + }; + + long totalPixels = gpuGenMips + ? AstcPerformanceBenchmarkRunner.CalculateMipChainPixels(width, height) + : (long)width * height; + + AstcRaw lastRaw = null; + AstcContext warmContext = null; + AstcBenchmarkMetrics timing; + try + { + if (backend == EncodeBackend.Cpu && m_ReuseCpuContext) + { + warmContext = AstcContext.Create( + readableSource.graphicsFormat, + m_TextureType, + m_BlockSize, + m_Quality, + threadCount, + m_UseAlphaWeight, + m_UsePerceptual); + } + + string effectiveLabel = backend == EncodeBackend.Cpu + ? $"{label} ({(warmContext != null ? "Warm Context" : "Cold Context")}, {threadCount}T)" + : $"{label}{(gpuGenMips ? " (+MipGen)" : string.Empty)}"; + + timing = AstcBenchmarkSampler.Measure( + name: effectiveLabel, + category: "Interactive", + backend: backend.ToString(), + resolution: $"{width}x{height}", + blockSize: m_BlockSize.ToString(), + quality: m_Quality.ToString(), + totalPixels: totalPixels, + warmupRuns: m_WarmupRuns, + iterations: m_Iterations, + action: () => + { + lastRaw?.Dispose(); + lastRaw = warmContext != null + ? warmContext.CompressTexture(readableSource, m_TextureType) + : readableSource.CompressTexture(options); + return lastRaw != null ? lastRaw.Length : 0; + }); + + if (lastRaw == null) + { + m_StatusMessage = $"{effectiveLabel} returned null (backend unsupported or failed)."; + return null; + } + + // Software-decode mip 0 via native astcenc so metrics & previews work on any PC/Mac Editor. + byte[] decodedRgba = Encoder.Decompress(lastRaw, width, height, m_BlockSize, srgb: isSrgb, isHdr: isHdr, outputBitness: isHdr ? 32 : 8); + if (decodedRgba == null) + { + m_StatusMessage = $"{effectiveLabel} median {timing.MedianMs:F2} ms, but CPU software decompression failed."; + return null; + } + + Color[] decPixels = UnpackDecodedPixels(decodedRgba, width * height, isHdr); + if (m_TextureType == TextureType.Normal) + { + // ASTC Normal maps are encoded in GGGR layout (R/G/B = ny, A = nx); reconstruct tangent-space RGB for metrics & preview. + for (int i = 0; i < decPixels.Length; i++) + { + float nx = decPixels[i].a; + float ny = decPixels[i].g; + float vx = nx * 2f - 1f; + float vy = ny * 2f - 1f; + float vz = Mathf.Sqrt(Mathf.Max(0f, 1f - vx * vx - vy * vy)); + decPixels[i] = new Color(nx, ny, vz * 0.5f + 0.5f, 1f); + } + } + + var result = ComputeMetrics(refPixels, decPixels, width, height, m_TextureType == TextureType.Normal); + result.Label = effectiveLabel; + result.EncodeMs = timing.MedianMs; + result.MinMs = timing.MinMs; + result.P95Ms = timing.P95Ms; + result.ThroughputMPixPerSec = timing.ThroughputMPixPerSec; + result.GcAllocBytesPerOp = timing.GcAllocBytesPerOp; + result.CompressedBytes = lastRaw.Length; + result.UncompressedBytes = (int)Math.Min(int.MaxValue, totalPixels * (isHdr ? 16L : 4L)); + result.DecodedPreview = BuildPreviewTexture(decPixels, width, height, m_ShowAlphaOnly); + result.HeatmapPreview = BuildHeatmapTexture(refPixels, decPixels, width, height, m_HeatmapGain); + return result; + } + finally + { + lastRaw?.Dispose(); + warmContext?.Dispose(); + } + } + + private static bool IsHdrFormat(GraphicsFormat format) + { + return GraphicsFormatUtility.IsFloatFormat(format) + || GraphicsFormatUtility.IsHalfFormat(format) + || format == GraphicsFormat.B10G11R11_UFloatPack32 + || format == GraphicsFormat.E5B9G9R9_UFloatPack32 + || format == GraphicsFormat.RGB_BC6H_UFloat + || format == GraphicsFormat.RGB_BC6H_SFloat; + } + + private void ExportFile(string extension) + { + if (m_SourceTexture == null) + return; + + string defaultName = $"{m_SourceTexture.name}_{m_BlockSize}.{extension}"; + string path = EditorUtility.SaveFilePanel($"Export ASTC .{extension}", "", defaultName, extension); + if (string.IsNullOrEmpty(path)) + return; + + bool isHdr = IsHdrFormat(m_SourceTexture.graphicsFormat); + bool isSrgb = m_TextureType == TextureType.Default && GraphicsFormatUtility.IsSRGBFormat(m_SourceTexture.graphicsFormat); + Texture2D readableSource = CreateReadableCopy(m_SourceTexture, isSrgb, isHdr); + try + { + var options = new AstcCompressOptions + { + TextureType = m_TextureType, + BlockSize = m_BlockSize, + Quality = m_Quality, + IncludeMipmaps = extension == "ktx", + GenerateMipmaps = m_GenerateMipmaps && extension == "ktx", + UseAlphaWeight = m_UseAlphaWeight, + UsePerceptual = m_UsePerceptual, + Backend = m_Mode == BenchmarkMode.CpuOnly ? EncodeBackend.Cpu : EncodeBackend.Auto + }; + + byte[] bytes = extension == "ktx" + ? readableSource.EncodeToKTX(options) + : readableSource.EncodeToASTC(options); + + if (bytes != null) + { + File.WriteAllBytes(path, bytes); + m_StatusMessage = $"Exported {bytes.Length / 1024.0:F1} KB to {path}"; + } + } + finally + { + DestroyImmediate(readableSource); + } + } + + private void DrawResultSection(BenchmarkResult result) + { + EditorGUILayout.Space(8f); + using (new EditorGUILayout.VerticalScope("box")) + { + double savings = result.UncompressedBytes > 0 + ? (1.0 - (double)result.CompressedBytes / result.UncompressedBytes) * 100.0 + : 0.0; + + EditorGUILayout.LabelField(result.Label, EditorStyles.boldLabel); + EditorGUILayout.LabelField( + $"Median: {result.EncodeMs:F2} ms (Min {result.MinMs:F2} / P95 {result.P95Ms:F2}) | {result.ThroughputMPixPerSec:F1} MP/s | GC: {result.GcAllocBytesPerOp / 1024.0:F1} KB/op"); + EditorGUILayout.LabelField( + $"Size: {result.CompressedBytes / 1024.0:F1} KB ({savings:F1}% saved) | RGB PSNR: {result.RgbPsnrDb:F2} dB | RGBA PSNR: {result.RgbaPsnrDb:F2} dB"); + EditorGUILayout.LabelField( + $"RGB RMSE: {result.RgbRmse:F4} | Alpha RMSE: {result.AlphaRmse:F4}" + + (m_TextureType == TextureType.Normal + ? $" | Normal Error: mean {result.MeanNormalDeg:F2}°, max {result.MaxNormalDeg:F2}°" + : string.Empty)); + + EditorGUILayout.Space(4f); + float previewSize = Mathf.Clamp((position.width - 64f) / 3f, 128f, 280f); + using (new EditorGUILayout.HorizontalScope()) + { + DrawPreviewColumn("Original", m_ReferencePreview, previewSize); + DrawPreviewColumn("Decoded ASTC", result.DecodedPreview, previewSize); + DrawPreviewColumn($"Error Heatmap ({m_HeatmapGain:F0}x)", result.HeatmapPreview, previewSize); + } + } + } + + private static void DrawPreviewColumn(string title, Texture2D tex, float size) + { + using (new EditorGUILayout.VerticalScope(GUILayout.Width(size))) + { + EditorGUILayout.LabelField(title, EditorStyles.centeredGreyMiniLabel); + Rect rect = GUILayoutUtility.GetRect(size, size, GUILayout.ExpandWidth(false)); + if (tex != null) + { + EditorGUI.DrawPreviewTexture(rect, tex, null, ScaleMode.ScaleToFit); + } + } + } + + private static Texture2D CreateReadableCopy(Texture2D source, bool srgb, bool isHdr) + { + var rtFormat = isHdr ? RenderTextureFormat.ARGBFloat : RenderTextureFormat.ARGB32; + var readWrite = (!isHdr && srgb) ? RenderTextureReadWrite.sRGB : RenderTextureReadWrite.Linear; + var rt = RenderTexture.GetTemporary(source.width, source.height, 0, rtFormat, readWrite); + RenderTexture prev = RenderTexture.active; + try + { + Graphics.Blit(source, rt); + RenderTexture.active = rt; + var texFormat = isHdr ? TextureFormat.RGBAFloat : TextureFormat.RGBA32; + var copy = new Texture2D(source.width, source.height, texFormat, false, isHdr || !srgb); + copy.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0); + copy.Apply(false, false); + return copy; + } + finally + { + RenderTexture.active = prev; + RenderTexture.ReleaseTemporary(rt); + } + } + + private static Color[] UnpackDecodedPixels(byte[] rgbaBytes, int pixelCount, bool isHdr) + { + var colors = new Color[pixelCount]; + if (isHdr) + { + for (int i = 0; i < pixelCount; i++) + { + int o = i * 16; + colors[i] = new Color( + BitConverter.ToSingle(rgbaBytes, o), + BitConverter.ToSingle(rgbaBytes, o + 4), + BitConverter.ToSingle(rgbaBytes, o + 8), + BitConverter.ToSingle(rgbaBytes, o + 12)); + } + } + else + { + const float inv = 1f / 255f; + for (int i = 0; i < pixelCount; i++) + { + int o = i * 4; + colors[i] = new Color( + rgbaBytes[o] * inv, + rgbaBytes[o + 1] * inv, + rgbaBytes[o + 2] * inv, + rgbaBytes[o + 3] * inv); + } + } + return colors; + } + + private static BenchmarkResult ComputeMetrics(Color[] reference, Color[] decoded, int width, int height, bool isNormalMap) + { + int count = Math.Min(reference.Length, decoded.Length); + double rgbSqErr = 0.0; + double alphaSqErr = 0.0; + double normalDegSum = 0.0; + double normalDegMax = 0.0; + + for (int i = 0; i < count; i++) + { + Color a = reference[i]; + Color b = decoded[i]; + double dr = a.r - b.r; + double dg = a.g - b.g; + double db = a.b - b.b; + double da = a.a - b.a; + rgbSqErr += dr * dr + dg * dg + db * db; + alphaSqErr += da * da; + + if (isNormalMap) + { + Vector3 na = ReconstructNormal(a.r, a.g); + Vector3 nb = ReconstructNormal(b.r, b.g); + float dot = Mathf.Clamp(Vector3.Dot(na, nb), -1f, 1f); + double deg = Math.Acos(dot) * (180.0 / Math.PI); + normalDegSum += deg; + if (deg > normalDegMax) + normalDegMax = deg; + } + } + + double rgbMse = count > 0 ? rgbSqErr / (count * 3.0) : 0.0; + double rgbaMse = count > 0 ? (rgbSqErr + alphaSqErr) / (count * 4.0) : 0.0; + double alphaMse = count > 0 ? alphaSqErr / count : 0.0; + + return new BenchmarkResult + { + RgbRmse = Math.Sqrt(rgbMse), + AlphaRmse = Math.Sqrt(alphaMse), + RgbPsnrDb = rgbMse > 1e-12 ? 10.0 * Math.Log10(1.0 / rgbMse) : 99.99, + RgbaPsnrDb = rgbaMse > 1e-12 ? 10.0 * Math.Log10(1.0 / rgbaMse) : 99.99, + MeanNormalDeg = count > 0 ? normalDegSum / count : 0.0, + MaxNormalDeg = normalDegMax + }; + } + + private static Vector3 ReconstructNormal(float r, float g) + { + float nx = r * 2f - 1f; + float ny = g * 2f - 1f; + float nz = Mathf.Sqrt(Mathf.Max(0f, 1f - nx * nx - ny * ny)); + return new Vector3(nx, ny, nz).normalized; + } + + private static Texture2D BuildPreviewTexture(Color[] pixels, int width, int height, bool alphaOnly) + { + var tex = new Texture2D(width, height, TextureFormat.RGBA32, false, false); + if (!alphaOnly) + { + tex.SetPixels(pixels); + } + else + { + var mono = new Color[pixels.Length]; + for (int i = 0; i < pixels.Length; i++) + { + float a = pixels[i].a; + mono[i] = new Color(a, a, a, 1f); + } + tex.SetPixels(mono); + } + tex.Apply(false, false); + return tex; + } + + private static Texture2D BuildHeatmapTexture(Color[] reference, Color[] decoded, int width, int height, float gain) + { + int count = Math.Min(reference.Length, decoded.Length); + var heat = new Color[count]; + for (int i = 0; i < count; i++) + { + Color a = reference[i]; + Color b = decoded[i]; + float err = (Mathf.Abs(a.r - b.r) + Mathf.Abs(a.g - b.g) + Mathf.Abs(a.b - b.b) + Mathf.Abs(a.a - b.a)) * 0.25f; + float t = Mathf.Clamp01(err * gain); + heat[i] = EvaluateHeatColor(t); + } + + var tex = new Texture2D(width, height, TextureFormat.RGBA32, false, false); + tex.SetPixels(heat); + tex.Apply(false, false); + return tex; + } + + private static Color EvaluateHeatColor(float t) + { + if (t < 0.25f) + return Color.Lerp(new Color(0.05f, 0.05f, 0.20f, 1f), new Color(0.0f, 0.65f, 0.85f, 1f), t * 4f); + if (t < 0.5f) + return Color.Lerp(new Color(0.0f, 0.65f, 0.85f, 1f), new Color(0.2f, 0.9f, 0.2f, 1f), (t - 0.25f) * 4f); + if (t < 0.75f) + return Color.Lerp(new Color(0.2f, 0.9f, 0.2f, 1f), new Color(1.0f, 0.85f, 0.0f, 1f), (t - 0.5f) * 4f); + return Color.Lerp(new Color(1.0f, 0.85f, 0.0f, 1f), new Color(1.0f, 0.1f, 0.1f, 1f), (t - 0.75f) * 4f); + } + } +} diff --git a/Assets/ASTC Encoder/Editor/AstcBenchmarkWindow.cs.meta b/Assets/ASTC Encoder/Editor/AstcBenchmarkWindow.cs.meta new file mode 100644 index 0000000..1f84eae --- /dev/null +++ b/Assets/ASTC Encoder/Editor/AstcBenchmarkWindow.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9a2d5e7f1c4840b39e61a8d4f2c73b95 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Editor/AstcPerformanceBenchmarkRunner.cs b/Assets/ASTC Encoder/Editor/AstcPerformanceBenchmarkRunner.cs new file mode 100644 index 0000000..339b521 --- /dev/null +++ b/Assets/ASTC Encoder/Editor/AstcPerformanceBenchmarkRunner.cs @@ -0,0 +1,1114 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Text; +using System.Threading.Tasks; +using Aperture.Astcenc.Runtime; +using Unity.Collections; +using UnityEditor; +using UnityEngine; +using UnityEngine.Experimental.Rendering; +using Debug = UnityEngine.Debug; +using Encoder = Aperture.Astcenc.Runtime.Encoder; + +namespace Aperture.Astcenc.Editor +{ + [Serializable] + public sealed class AstcBenchmarkMetrics + { + public string Name; + public string Category; + public string Backend; + public string Resolution; + public string BlockSize; + public string Quality; + public int WarmupRuns; + public int Iterations; + public double MinMs; + public double MedianMs; + public double MeanMs; + public double P95Ms; + public double MaxMs; + public double ThroughputMPixPerSec; + public long GcAllocBytesPerOp; + public int OutputBytes; + public string Notes; + } + + [Serializable] + public sealed class AstcBenchmarkReport + { + public string TimestampUtc; + public string UnityVersion; + public string Platform; + public string CpuModel; + public int CpuCores; + public string GpuModel; + public string GraphicsDeviceType; + public bool GpuSupported; + public bool CpuSupported; + public List Results = new List(); + } + + /// + /// Statistical micro-benchmark sampler with warmup, percentile calculation (Min/Median/Mean/P95/Max), + /// throughput (MP/s), and managed GC allocation tracking. + /// + public static class AstcBenchmarkSampler + { + public static AstcBenchmarkMetrics Measure( + string name, + string category, + string backend, + string resolution, + string blockSize, + string quality, + long totalPixels, + int warmupRuns, + int iterations, + Func action, + string notes = "") + { + int effectiveWarmup = Math.Max(0, warmupRuns); + int effectiveIters = Math.Max(1, iterations); + + int lastBytes = 0; + for (int w = 0; w < effectiveWarmup; w++) + { + lastBytes = action(); + } + + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + + double[] samplesMs = new double[effectiveIters]; + long totalGcDelta = 0; + var sw = new Stopwatch(); + + for (int i = 0; i < effectiveIters; i++) + { + long memBefore = GC.GetTotalMemory(false); + sw.Restart(); + lastBytes = action(); + sw.Stop(); + long memAfter = GC.GetTotalMemory(false); + + samplesMs[i] = sw.Elapsed.TotalMilliseconds; + if (memAfter > memBefore) + { + totalGcDelta += (memAfter - memBefore); + } + } + + Array.Sort(samplesMs); + double sum = 0.0; + for (int i = 0; i < samplesMs.Length; i++) + sum += samplesMs[i]; + + double minMs = samplesMs[0]; + double maxMs = samplesMs[samplesMs.Length - 1]; + double meanMs = sum / samplesMs.Length; + double medianMs = (samplesMs.Length & 1) == 1 + ? samplesMs[samplesMs.Length / 2] + : 0.5 * (samplesMs[samplesMs.Length / 2 - 1] + samplesMs[samplesMs.Length / 2]); + + int p95Index = Math.Min(samplesMs.Length - 1, (int)Math.Ceiling(samplesMs.Length * 0.95) - 1); + double p95Ms = samplesMs[Math.Max(0, p95Index)]; + + double mpixPerSec = (medianMs > 1e-6 && totalPixels > 0) + ? (totalPixels / 1e6) / (medianMs / 1000.0) + : 0.0; + + return new AstcBenchmarkMetrics + { + Name = name, + Category = category, + Backend = backend, + Resolution = resolution, + BlockSize = blockSize, + Quality = quality, + WarmupRuns = effectiveWarmup, + Iterations = effectiveIters, + MinMs = minMs, + MedianMs = medianMs, + MeanMs = meanMs, + P95Ms = p95Ms, + MaxMs = maxMs, + ThroughputMPixPerSec = mpixPerSec, + GcAllocBytesPerOp = totalGcDelta / effectiveIters, + OutputBytes = lastBytes, + Notes = notes ?? string.Empty + }; + } + } + + /// + /// Automated performance benchmark suite for Runtime-ASTC-Encoder-For-Unity. + /// Runnable from Editor MenuItem, Unity Test Runner (AstcPerformanceBenchmarks), or CLI batchmode (-executeMethod). + /// + public static class AstcPerformanceBenchmarkRunner + { + public const string DefaultOutputDirectory = "Logs/AstcBenchmarks"; + + [MenuItem("Window/ASTC Encoder/Run Performance Benchmark Suite")] + public static void RunFromMenu() + { + AstcBenchmarkReport report = RunFullSuite(warmup: 2, iterations: 5, exportReports: true, out string exportDir); + Debug.Log($"[ASTC Benchmark] Completed {report.Results.Count} benchmarks. Reports saved to: {exportDir}\n{FormatMarkdownTable(report)}"); + } + + /// + /// Unity batchmode entrypoint: + /// Unity -batchmode -projectPath . -executeMethod Aperture.Astcenc.Editor.AstcPerformanceBenchmarkRunner.RunAllFromCli -quit + /// + public static void RunAllFromCli() + { + AstcBenchmarkReport report = RunFullSuite(warmup: 2, iterations: 5, exportReports: true, out string exportDir); + Debug.Log($"[ASTC Benchmark CLI] Completed {report.Results.Count} benchmarks. Output: {exportDir}\n{FormatMarkdownTable(report)}"); + } + + public static AstcBenchmarkReport CreateEmptyReport() + { + return new AstcBenchmarkReport + { + TimestampUtc = DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture), + UnityVersion = Application.unityVersion, + Platform = Application.platform.ToString(), + CpuModel = SystemInfo.processorType, + CpuCores = Environment.ProcessorCount, + GpuModel = SystemInfo.graphicsDeviceName, + GraphicsDeviceType = SystemInfo.graphicsDeviceType.ToString(), + GpuSupported = Encoder.IsGpuSupported, + CpuSupported = Encoder.IsCpuSupported + }; + } + + public static AstcBenchmarkReport RunFullSuite(int warmup, int iterations, bool exportReports, out string exportedDirectory) + { + exportedDirectory = null; + AstcBenchmarkReport report = CreateEmptyReport(); + + if (Encoder.IsGpuSupported) + { + report.Results.AddRange(RunGpuEncodingSuite(warmup, iterations)); + } + if (Encoder.IsCpuSupported) + { + report.Results.AddRange(RunCpuEncodingSuite(Math.Max(1, warmup), iterations)); + report.Results.AddRange(RunCpuRawPixelsSuite(Math.Max(1, warmup), iterations)); + report.Results.AddRange(RunDecompressionSuite(Math.Max(1, warmup), iterations)); + } + + report.Results.AddRange(RunContainerAndCacheSuite(Math.Max(1, warmup), iterations)); + report.Results.AddRange(RunQueueBatchSuite(1, Math.Max(2, iterations / 2))); + + if (exportReports) + { + exportedDirectory = ExportReport(report, DefaultOutputDirectory); + } + + return report; + } + + public static List RunGpuEncodingSuite(int warmup = 2, int iterations = 5) + { + var results = new List(); + if (!Encoder.IsGpuSupported) + return results; + + BlockSize[] blockSizes = { BlockSize.ASTC_4x4, BlockSize.ASTC_6x6, BlockSize.ASTC_8x8, BlockSize.ASTC_12x12 }; + foreach (BlockSize bs in blockSizes) + { + Encoder.PreloadGpu(bs); + } + + // 1. 512x512 RGBA8 matrix (Fast / Medium / Thorough across 4x4, 6x6, 8x8, 12x12) + Texture2D tex512 = CreateProceduralColorTexture(512, 512, srgb: false, withAlpha: true, withMipmaps: false); + Texture2D tex1024 = CreateProceduralColorTexture(1024, 1024, srgb: false, withAlpha: true, withMipmaps: false); + Texture2D tex512Srgb = CreateProceduralColorTexture(512, 512, srgb: true, withAlpha: false, withMipmaps: false); + Texture2D tex512Normal = CreateProceduralNormalTexture(512, 512); + Texture2D tex512Hdr = CreateProceduralHdrTexture(512, 512); + + try + { + CompressQuality[] qualities512 = { CompressQuality.Fast, CompressQuality.Medium, CompressQuality.Thorough }; + foreach (BlockSize bs in blockSizes) + { + foreach (CompressQuality q in qualities512) + { + var opt = AstcCompressOptions.Default; + opt.Backend = EncodeBackend.Gpu; + opt.BlockSize = bs; + opt.Quality = q; + opt.IncludeMipmaps = false; + + results.Add(AstcBenchmarkSampler.Measure( + name: $"GPU_RGBA8_512_{bs}_{q}", + category: "GPU_Encode", + backend: "GPU", + resolution: "512x512", + blockSize: bs.ToString(), + quality: q.ToString(), + totalPixels: 512L * 512L, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + using AstcRaw raw = tex512.CompressTexture(opt); + return raw != null ? raw.Length : 0; + })); + } + } + + // 2. 1024x1024 RGBA8 (Fast / Medium across 4x4, 6x6, 8x8, 12x12) + CompressQuality[] qualities1024 = { CompressQuality.Fast, CompressQuality.Medium }; + foreach (BlockSize bs in blockSizes) + { + foreach (CompressQuality q in qualities1024) + { + var opt = AstcCompressOptions.Default; + opt.Backend = EncodeBackend.Gpu; + opt.BlockSize = bs; + opt.Quality = q; + opt.IncludeMipmaps = false; + + results.Add(AstcBenchmarkSampler.Measure( + name: $"GPU_RGBA8_1024_{bs}_{q}", + category: "GPU_Encode", + backend: "GPU", + resolution: "1024x1024", + blockSize: bs.ToString(), + quality: q.ToString(), + totalPixels: 1024L * 1024L, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + using AstcRaw raw = tex1024.CompressTexture(opt); + return raw != null ? raw.Length : 0; + })); + } + } + + // 3. sRGB / Normal / HDR / GPU Mipmap Generation at 512x512 ASTC_6x6 + { + var srgbOpt = AstcCompressOptions.Default; + srgbOpt.Backend = EncodeBackend.Gpu; + srgbOpt.BlockSize = BlockSize.ASTC_6x6; + srgbOpt.Quality = CompressQuality.Fast; + srgbOpt.IncludeMipmaps = false; + + results.Add(AstcBenchmarkSampler.Measure( + name: "GPU_sRGB_512_6x6_Fast", + category: "GPU_Modes", + backend: "GPU", + resolution: "512x512", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: 512L * 512L, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + using AstcRaw raw = tex512Srgb.CompressTexture(srgbOpt); + return raw != null ? raw.Length : 0; + })); + + var normOpt = AstcCompressOptions.NormalMap; + normOpt.Backend = EncodeBackend.Gpu; + normOpt.BlockSize = BlockSize.ASTC_6x6; + normOpt.Quality = CompressQuality.Medium; + normOpt.IncludeMipmaps = false; + + results.Add(AstcBenchmarkSampler.Measure( + name: "GPU_Normal_512_6x6_Medium", + category: "GPU_Modes", + backend: "GPU", + resolution: "512x512", + blockSize: "ASTC_6x6", + quality: "Medium", + totalPixels: 512L * 512L, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + using AstcRaw raw = tex512Normal.CompressTexture(normOpt); + return raw != null ? raw.Length : 0; + })); + + var hdrOpt = AstcCompressOptions.Default; + hdrOpt.Backend = EncodeBackend.Gpu; + hdrOpt.BlockSize = BlockSize.ASTC_6x6; + hdrOpt.Quality = CompressQuality.Fast; + hdrOpt.IncludeMipmaps = false; + + results.Add(AstcBenchmarkSampler.Measure( + name: "GPU_HDR16F_512_6x6_Fast", + category: "GPU_Modes", + backend: "GPU", + resolution: "512x512", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: 512L * 512L, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + using AstcRaw raw = tex512Hdr.CompressTexture(hdrOpt); + return raw != null ? raw.Length : 0; + })); + + var mipOpt = AstcCompressOptions.Default; + mipOpt.Backend = EncodeBackend.Gpu; + mipOpt.BlockSize = BlockSize.ASTC_6x6; + mipOpt.Quality = CompressQuality.Fast; + mipOpt.IncludeMipmaps = true; + mipOpt.GenerateMipmaps = true; + + long mipPixels = CalculateMipChainPixels(512, 512); + results.Add(AstcBenchmarkSampler.Measure( + name: "GPU_MipGen_RGBA8_512_6x6_Fast", + category: "GPU_Modes", + backend: "GPU", + resolution: "512x512+Mips", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: mipPixels, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + using AstcRaw raw = tex512.CompressTexture(mipOpt); + return raw != null ? raw.Length : 0; + }, + notes: "GPU mipmap generation + encode")); + + // Direct CopyTexture vs Readback fallback for CompressToTexture (aligned 4x4 mip0 vs non-aligned 6x6 mip0) + var direct4x4Opt = AstcCompressOptions.Default; + direct4x4Opt.Backend = EncodeBackend.Gpu; + direct4x4Opt.BlockSize = BlockSize.ASTC_4x4; + direct4x4Opt.Quality = CompressQuality.Fast; + direct4x4Opt.IncludeMipmaps = false; + + results.Add(AstcBenchmarkSampler.Measure( + name: "GPU_CompressToTexture_512_4x4_Mip0", + category: "GPU_DirectCopy", + backend: "GPU", + resolution: "512x512", + blockSize: "ASTC_4x4", + quality: "Fast", + totalPixels: 512L * 512L, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + Texture2D outTex = tex512.CompressToTexture(direct4x4Opt); + int ok = outTex != null ? 1 : 0; + if (outTex != null) UnityEngine.Object.DestroyImmediate(outTex); + return ok; + }, + notes: Encoder.SupportsGpuDirectCopy(BlockSize.ASTC_4x4) ? "DirectCopy eligible" : "Readback fallback (no HW ASTC)")); + + var fallback6x6Opt = AstcCompressOptions.Default; + fallback6x6Opt.Backend = EncodeBackend.Gpu; + fallback6x6Opt.BlockSize = BlockSize.ASTC_6x6; + fallback6x6Opt.Quality = CompressQuality.Fast; + fallback6x6Opt.IncludeMipmaps = false; + + results.Add(AstcBenchmarkSampler.Measure( + name: "GPU_CompressToTexture_512_6x6_Mip0", + category: "GPU_DirectCopy", + backend: "GPU", + resolution: "512x512", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: 512L * 512L, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + Texture2D outTex = tex512.CompressToTexture(fallback6x6Opt); + int ok = outTex != null ? 1 : 0; + if (outTex != null) UnityEngine.Object.DestroyImmediate(outTex); + return ok; + }, + notes: "512%6!=0 -> Readback fallback")); + } + } + finally + { + UnityEngine.Object.DestroyImmediate(tex512); + UnityEngine.Object.DestroyImmediate(tex1024); + UnityEngine.Object.DestroyImmediate(tex512Srgb); + UnityEngine.Object.DestroyImmediate(tex512Normal); + UnityEngine.Object.DestroyImmediate(tex512Hdr); + } + + return results; + } + + public static List RunCpuEncodingSuite(int warmup = 1, int iterations = 5) + { + var results = new List(); + if (!Encoder.IsCpuSupported) + return results; + + Texture2D tex512 = CreateProceduralColorTexture(512, 512, srgb: false, withAlpha: true, withMipmaps: false); + try + { + BlockSize[] blockSizes = { BlockSize.ASTC_4x4, BlockSize.ASTC_6x6, BlockSize.ASTC_8x8, BlockSize.ASTC_12x12 }; + CompressQuality[] qualities = { CompressQuality.Fast, CompressQuality.Medium }; + int autoThreads = Math.Max(1, Math.Min(Environment.ProcessorCount, 4)); + + // 1. Cold (per-call AstcContext.Create) vs Warm (reused AstcContext) + foreach (BlockSize bs in blockSizes) + { + foreach (CompressQuality q in qualities) + { + var coldOpt = AstcCompressOptions.Default; + coldOpt.Backend = EncodeBackend.Cpu; + coldOpt.BlockSize = bs; + coldOpt.Quality = q; + coldOpt.IncludeMipmaps = false; + coldOpt.ThreadCount = autoThreads; + + results.Add(AstcBenchmarkSampler.Measure( + name: $"CPU_Cold_512_{bs}_{q}_{autoThreads}T", + category: "CPU_ColdVsWarm", + backend: "CPU", + resolution: "512x512", + blockSize: bs.ToString(), + quality: q.ToString(), + totalPixels: 512L * 512L, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + using AstcRaw raw = tex512.CompressTexture(coldOpt); + return raw != null ? raw.Length : 0; + }, + notes: "Includes AstcContext.Create/Dispose per call")); + + using AstcContext warmCtx = AstcContext.Create( + tex512.graphicsFormat, + TextureType.Default, + bs, + q, + threadCount: autoThreads); + + if (warmCtx != null) + { + results.Add(AstcBenchmarkSampler.Measure( + name: $"CPU_Warm_512_{bs}_{q}_{autoThreads}T", + category: "CPU_ColdVsWarm", + backend: "CPU", + resolution: "512x512", + blockSize: bs.ToString(), + quality: q.ToString(), + totalPixels: 512L * 512L, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + using AstcRaw raw = warmCtx.CompressTexture(tex512, TextureType.Default); + return raw != null ? raw.Length : 0; + }, + notes: "Reused AstcContext (steady-state)")); + } + } + } + + // 2. Threading scaling at 512x512 ASTC_6x6 Fast (1T, 4T/Auto, MaxCores, Unity JobSystem) + int[] threadCounts = { 1, autoThreads, Environment.ProcessorCount }; + foreach (int tc in threadCounts) + { + using AstcContext ctx = AstcContext.Create( + tex512.graphicsFormat, + TextureType.Default, + BlockSize.ASTC_6x6, + CompressQuality.Fast, + threadCount: tc, + useUnityJobSystem: false); + + if (ctx != null) + { + results.Add(AstcBenchmarkSampler.Measure( + name: $"CPU_ThreadPool_{tc}T_512_6x6_Fast", + category: "CPU_Threading", + backend: "CPU", + resolution: "512x512", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: 512L * 512L, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + using AstcRaw raw = ctx.CompressTexture(tex512, TextureType.Default); + return raw != null ? raw.Length : 0; + }, + notes: $".NET Parallel.For ({tc} threads)")); + } + } + + using AstcContext jobCtx = AstcContext.Create( + tex512.graphicsFormat, + TextureType.Default, + BlockSize.ASTC_6x6, + CompressQuality.Fast, + threadCount: autoThreads, + useUnityJobSystem: true); + + if (jobCtx != null) + { + results.Add(AstcBenchmarkSampler.Measure( + name: $"CPU_JobSystem_{autoThreads}T_512_6x6_Fast", + category: "CPU_Threading", + backend: "CPU", + resolution: "512x512", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: 512L * 512L, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + using AstcRaw raw = jobCtx.CompressTexture(tex512, TextureType.Default); + return raw != null ? raw.Length : 0; + }, + notes: $"Unity IJobParallelFor ({autoThreads} threads)")); + } + } + finally + { + UnityEngine.Object.DestroyImmediate(tex512); + } + + return results; + } + + public static List RunCpuRawPixelsSuite(int warmup = 1, int iterations = 5) + { + var results = new List(); + if (!Encoder.IsCpuSupported) + return results; + + const int w = 512; + const int h = 512; + int blocksX = (w + 5) / 6; + int blocksY = (h + 5) / 6; + int outCapacity = blocksX * blocksY * 16; + + using var srcRgba8 = new NativeArray(w * h * 4, Allocator.Persistent); + using var dstAstc = new NativeArray(outCapacity, Allocator.Persistent); + var srcWritable = srcRgba8; + for (int i = 0; i < srcWritable.Length; i++) + srcWritable[i] = (byte)((i * 37) & 0xFF); + + var opt = AstcCompressOptions.Default; + opt.Backend = EncodeBackend.Cpu; + opt.BlockSize = BlockSize.ASTC_6x6; + opt.Quality = CompressQuality.Fast; + opt.ThreadCount = 0; + + results.Add(AstcBenchmarkSampler.Measure( + name: "CPU_CompressRawPixels_512_6x6_Fast", + category: "CPU_RawPixels", + backend: "CPU", + resolution: "512x512", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: w * (long)h, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + using AstcRaw raw = Encoder.CompressRawPixels(srcRgba8, w, h, GraphicsFormat.R8G8B8A8_UNorm, opt); + return raw != null ? raw.Length : 0; + }, + notes: "Allocates AstcRaw per call")); + + results.Add(AstcBenchmarkSampler.Measure( + name: "CPU_CompressRawPixelsInto_512_6x6_Fast", + category: "CPU_RawPixels", + backend: "CPU", + resolution: "512x512", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: w * (long)h, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + bool ok = Encoder.CompressRawPixelsInto(srcRgba8, dstAstc, w, h, GraphicsFormat.R8G8B8A8_UNorm, opt, out int written); + return ok ? written : 0; + }, + notes: "Caller-owned destination NativeArray")); + + return results; + } + + public static List RunDecompressionSuite(int warmup = 1, int iterations = 5) + { + var results = new List(); + if (!Encoder.IsCpuSupported) + return results; + + const int w = 512; + const int h = 512; + Texture2D tex512 = CreateProceduralColorTexture(w, h, srgb: false, withAlpha: true, withMipmaps: false); + try + { + BlockSize[] blockSizes = { BlockSize.ASTC_4x4, BlockSize.ASTC_6x6, BlockSize.ASTC_8x8, BlockSize.ASTC_12x12 }; + int multiThreads = Math.Max(1, Math.Min(Environment.ProcessorCount, 4)); + + foreach (BlockSize bs in blockSizes) + { + var opt = AstcCompressOptions.Default; + opt.Backend = EncodeBackend.Cpu; + opt.BlockSize = bs; + opt.Quality = CompressQuality.Fast; + opt.IncludeMipmaps = false; + + using AstcRaw encoded = tex512.CompressTexture(opt); + if (encoded == null) + continue; + + results.Add(AstcBenchmarkSampler.Measure( + name: $"CPU_Decompress_1T_512_{bs}", + category: "CPU_Decompress", + backend: "CPU", + resolution: "512x512", + blockSize: bs.ToString(), + quality: "N/A", + totalPixels: w * (long)h, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + byte[] rgba = Encoder.Decompress(encoded, w, h, bs, srgb: false, isHdr: false, outputBitness: 8, threadCount: 1); + return rgba != null ? rgba.Length : 0; + }, + notes: "1 thread (includes CreateDecompressor)")); + + if (multiThreads > 1) + { + results.Add(AstcBenchmarkSampler.Measure( + name: $"CPU_Decompress_{multiThreads}T_512_{bs}", + category: "CPU_Decompress", + backend: "CPU", + resolution: "512x512", + blockSize: bs.ToString(), + quality: "N/A", + totalPixels: w * (long)h, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + byte[] rgba = Encoder.Decompress(encoded, w, h, bs, srgb: false, isHdr: false, outputBitness: 8, threadCount: multiThreads); + return rgba != null ? rgba.Length : 0; + }, + notes: $"{multiThreads} threads (includes CreateDecompressor)")); + } + } + } + finally + { + UnityEngine.Object.DestroyImmediate(tex512); + } + + return results; + } + + public static List RunContainerAndCacheSuite(int warmup = 1, int iterations = 5) + { + var results = new List(); + const int w = 512; + const int h = 512; + long mipPixels = CalculateMipChainPixels(w, h); + + Texture2D tex512Mip = CreateProceduralColorTexture(w, h, srgb: false, withAlpha: true, withMipmaps: true); + string tempKtxPath = Path.Combine(Path.GetTempPath(), $"astc_bench_{Guid.NewGuid():N}.ktx"); + + try + { + var opt = AstcCompressOptions.Default; + opt.Backend = Encoder.IsGpuSupported ? EncodeBackend.Gpu : EncodeBackend.Cpu; + opt.BlockSize = BlockSize.ASTC_6x6; + opt.Quality = CompressQuality.Fast; + opt.IncludeMipmaps = true; + + using AstcRaw raw = tex512Mip.CompressTexture(opt); + if (raw == null) + return results; + + int mipCount = tex512Mip.mipmapCount; + GraphicsFormat astcFmt = Encoder.GetTargetAstcFormat(tex512Mip.graphicsFormat, opt.BlockSize, opt.TextureType); + + byte[] ktxBytes = null; + results.Add(AstcBenchmarkSampler.Measure( + name: "KTX_Encode_512_6x6_FullMips", + category: "Container_Cache", + backend: "Managed", + resolution: "512x512+Mips", + blockSize: "ASTC_6x6", + quality: "N/A", + totalPixels: mipPixels, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + ktxBytes = AstcKtxContainer.Encode(raw, w, h, mipCount, astcFmt); + return ktxBytes != null ? ktxBytes.Length : 0; + })); + + if (ktxBytes != null) + { + results.Add(AstcBenchmarkSampler.Measure( + name: "KTX_TryDecode_512_6x6_FullMips", + category: "Container_Cache", + backend: "Managed", + resolution: "512x512+Mips", + blockSize: "ASTC_6x6", + quality: "N/A", + totalPixels: mipPixels, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + bool ok = AstcKtxContainer.TryDecode(ktxBytes, out KtxAstcData decoded); + return ok && decoded.RawAstcPayload != null ? decoded.RawAstcPayload.Length : 0; + }, + notes: "Watch GcAllocBytesPerOp for LOH payload copy")); + + File.WriteAllBytes(tempKtxPath, ktxBytes); + results.Add(AstcBenchmarkSampler.Measure( + name: "DiskCache_TryLoad_512_6x6_FullMips", + category: "Container_Cache", + backend: "Disk+GPU", + resolution: "512x512+Mips", + blockSize: "ASTC_6x6", + quality: "N/A", + totalPixels: mipPixels, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + Texture2D loaded = AstcDiskCache.TryLoad(tempKtxPath, makeNoLongerReadable: true); + int ok = loaded != null ? ktxBytes.Length : 0; + if (loaded != null) UnityEngine.Object.DestroyImmediate(loaded); + return ok; + })); + } + } + finally + { + UnityEngine.Object.DestroyImmediate(tex512Mip); + if (File.Exists(tempKtxPath)) + { + try { File.Delete(tempKtxPath); } catch { } + } + } + + return results; + } + + public static List RunQueueBatchSuite(int warmup = 1, int iterations = 3) + { + var results = new List(); + const int batchCount = 8; + const int size = 256; + long totalPixels = (long)batchCount * size * size; + + var textures = new Texture2D[batchCount]; + for (int i = 0; i < batchCount; i++) + textures[i] = CreateProceduralColorTexture(size, size, srgb: false, withAlpha: true, withMipmaps: false, seedOffset: i * 13); + + try + { + if (Encoder.IsCpuSupported) + { + using var cpuQueue = new AstcCompressionQueue + { + MaxConcurrentCpuTasks = Math.Max(1, Environment.ProcessorCount / 2) + }; + + var cpuOpt = AstcCompressOptions.Default; + cpuOpt.Backend = EncodeBackend.Cpu; + cpuOpt.BlockSize = BlockSize.ASTC_6x6; + cpuOpt.Quality = CompressQuality.Fast; + cpuOpt.IncludeMipmaps = false; + + results.Add(AstcBenchmarkSampler.Measure( + name: $"Queue_CPU_Burst_{batchCount}x{size}_6x6_Fast", + category: "Queue_Batch", + backend: "CPU_Queue", + resolution: $"{batchCount}x{size}x{size}", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: totalPixels, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + var tasks = new Task[batchCount]; + for (int i = 0; i < batchCount; i++) + tasks[i] = cpuQueue.EnqueueToRaw(textures[i], cpuOpt); + + while (cpuQueue.PendingCpuCount > 0 || cpuQueue.ActiveCpuCount > 0) + { + cpuQueue.ProcessFrame(); + System.Threading.Thread.Sleep(1); + } + Task.WaitAll(tasks); + + int totalBytes = 0; + for (int i = 0; i < batchCount; i++) + { + using AstcRaw r = tasks[i].Result; + if (r != null) totalBytes += r.Length; + } + return totalBytes; + }, + notes: "Pooled AstcContext with parent table sharing")); + } + + if (Encoder.IsGpuSupported) + { + Encoder.PreloadGpu(BlockSize.ASTC_4x4); + using var gpuQueue = new AstcCompressionQueue + { + MaxGpuTexelsPerFrame = totalPixels + }; + + var gpuOpt = AstcCompressOptions.Default; + gpuOpt.Backend = EncodeBackend.Gpu; + gpuOpt.BlockSize = BlockSize.ASTC_4x4; + gpuOpt.Quality = CompressQuality.Fast; + gpuOpt.IncludeMipmaps = false; + + results.Add(AstcBenchmarkSampler.Measure( + name: $"Queue_GPU_Burst_{batchCount}x{size}_4x4_Fast", + category: "Queue_Batch", + backend: "GPU_Queue", + resolution: $"{batchCount}x{size}x{size}", + blockSize: "ASTC_4x4", + quality: "Fast", + totalPixels: totalPixels, + warmupRuns: warmup, + iterations: iterations, + action: () => + { + var tasks = new Task[batchCount]; + for (int i = 0; i < batchCount; i++) + tasks[i] = gpuQueue.EnqueueToTexture(textures[i], gpuOpt); + + gpuQueue.ProcessFrame(); + + // Flush pending AsyncGPUReadback if fallback path was taken on non-ASTC desktop Editor. + int guard = 0; + while (!Task.WhenAll(tasks).IsCompleted && guard < 2000) + { + UnityEngine.Rendering.AsyncGPUReadback.WaitAllRequests(); + System.Threading.Thread.Sleep(1); + guard++; + } + + int created = 0; + for (int i = 0; i < batchCount; i++) + { + if (tasks[i].Status == TaskStatus.RanToCompletion && tasks[i].Result != null) + { + created++; + UnityEngine.Object.DestroyImmediate(tasks[i].Result); + } + } + return created; + }, + notes: "Single-frame CommandBuffer batch when DirectCopy supported")); + } + } + finally + { + for (int i = 0; i < batchCount; i++) + UnityEngine.Object.DestroyImmediate(textures[i]); + } + + return results; + } + + public static string ExportReport(AstcBenchmarkReport report, string outputDirectory = DefaultOutputDirectory) + { + string fullDir = Path.GetFullPath(outputDirectory); + Directory.CreateDirectory(fullDir); + + string stamp = DateTime.UtcNow.ToString("yyyyMMdd_HHmmss", CultureInfo.InvariantCulture); + string jsonPath = Path.Combine(fullDir, $"astc_benchmark_{stamp}.json"); + string csvPath = Path.Combine(fullDir, $"astc_benchmark_{stamp}.csv"); + string mdPath = Path.Combine(fullDir, $"astc_benchmark_{stamp}.md"); + + File.WriteAllText(jsonPath, JsonUtility.ToJson(report, true), Encoding.UTF8); + File.WriteAllText(csvPath, FormatCsv(report), Encoding.UTF8); + File.WriteAllText(mdPath, FormatMarkdownTable(report), Encoding.UTF8); + + return fullDir; + } + + public static string FormatMarkdownTable(AstcBenchmarkReport report) + { + var sb = new StringBuilder(); + sb.AppendLine($"# ASTC Performance Benchmark ({report.TimestampUtc})"); + sb.AppendLine($"- **Unity**: `{report.UnityVersion}` | **Platform**: `{report.Platform}`"); + sb.AppendLine($"- **CPU**: `{report.CpuModel}` ({report.CpuCores} cores) | **GPU**: `{report.GpuModel}` (`{report.GraphicsDeviceType}`)"); + sb.AppendLine(); + sb.AppendLine("| Benchmark | Backend | Resolution | Block | Quality | Min (ms) | Median (ms) | P95 (ms) | MP/s | GC Alloc (KB) | Notes |"); + sb.AppendLine("| :--- | :--- | :--- | :--- | :--- | ---: | ---: | ---: | ---: | ---: | :--- |"); + + foreach (AstcBenchmarkMetrics r in report.Results) + { + sb.AppendLine(string.Format( + CultureInfo.InvariantCulture, + "| {0} | {1} | {2} | {3} | {4} | {5:F2} | {6:F2} | {7:F2} | {8:F2} | {9:F1} | {10} |", + r.Name, r.Backend, r.Resolution, r.BlockSize, r.Quality, + r.MinMs, r.MedianMs, r.P95Ms, r.ThroughputMPixPerSec, + r.GcAllocBytesPerOp / 1024.0, r.Notes)); + } + return sb.ToString(); + } + + public static string FormatCsv(AstcBenchmarkReport report) + { + var sb = new StringBuilder(); + sb.AppendLine("Name,Category,Backend,Resolution,BlockSize,Quality,WarmupRuns,Iterations,MinMs,MedianMs,MeanMs,P95Ms,MaxMs,ThroughputMPixPerSec,GcAllocBytesPerOp,OutputBytes,Notes"); + foreach (AstcBenchmarkMetrics r in report.Results) + { + sb.AppendLine(string.Format( + CultureInfo.InvariantCulture, + "{0},{1},{2},{3},{4},{5},{6},{7},{8:F4},{9:F4},{10:F4},{11:F4},{12:F4},{13:F4},{14},{15},\"{16}\"", + r.Name, r.Category, r.Backend, r.Resolution, r.BlockSize, r.Quality, + r.WarmupRuns, r.Iterations, r.MinMs, r.MedianMs, r.MeanMs, r.P95Ms, r.MaxMs, + r.ThroughputMPixPerSec, r.GcAllocBytesPerOp, r.OutputBytes, + (r.Notes ?? string.Empty).Replace("\"", "\"\""))); + } + return sb.ToString(); + } + + public static long CalculateMipChainPixels(int width, int height) + { + long total = 0; + int w = width; + int h = height; + while (true) + { + total += (long)w * h; + if (w == 1 && h == 1) + break; + w = Math.Max(1, w >> 1); + h = Math.Max(1, h >> 1); + } + return total; + } + + /// + /// Deterministic procedural RGBA texture mixing flat blocks (Void-Extent), smooth gradients, + /// high-frequency edges, and alpha variation to exercise all encoder paths realistically. + /// + public static Texture2D CreateProceduralColorTexture(int width, int height, bool srgb, bool withAlpha, bool withMipmaps, int seedOffset = 0) + { + GraphicsFormat fmt = srgb ? GraphicsFormat.R8G8B8A8_SRGB : GraphicsFormat.R8G8B8A8_UNorm; + TextureCreationFlags flags = withMipmaps ? TextureCreationFlags.MipChain : TextureCreationFlags.None; + var tex = new Texture2D(width, height, fmt, flags); + + var pixels = new Color32[width * height]; + for (int y = 0; y < height; y++) + { + float v = height > 1 ? (float)y / (height - 1) : 0f; + for (int x = 0; x < width; x++) + { + float u = width > 1 ? (float)x / (width - 1) : 0f; + byte r, g, b, a; + + // Bottom-left quadrant: flat constant color (exercises Void-Extent fast path) + if (x < width / 4 && y < height / 4) + { + r = 96; + g = 144; + b = 192; + a = 255; + } + else + { + float wave = 0.5f + 0.5f * Mathf.Sin((u * 18f + v * 12f + seedOffset) * Mathf.PI); + float checker = (((x >> 3) + (y >> 3)) & 1) == 0 ? 0.15f : -0.15f; + r = (byte)Mathf.Clamp(Mathf.RoundToInt((u * 0.7f + wave * 0.3f + checker) * 255f), 0, 255); + g = (byte)Mathf.Clamp(Mathf.RoundToInt((v * 0.7f + (1f - wave) * 0.3f - checker) * 255f), 0, 255); + b = (byte)Mathf.Clamp(Mathf.RoundToInt(((u + v) * 0.4f + wave * 0.2f) * 255f), 0, 255); + a = withAlpha + ? (byte)Mathf.Clamp(Mathf.RoundToInt((0.2f + 0.8f * Mathf.Abs(Mathf.Sin((u - v) * 4f * Mathf.PI))) * 255f), 0, 255) + : (byte)255; + } + + pixels[y * width + x] = new Color32(r, g, b, a); + } + } + + tex.SetPixels32(pixels); + tex.Apply(updateMipmaps: withMipmaps, makeNoLongerReadable: false); + return tex; + } + + public static Texture2D CreateProceduralNormalTexture(int width, int height) + { + var tex = new Texture2D(width, height, GraphicsFormat.R8G8B8A8_UNorm, TextureCreationFlags.None); + var pixels = new Color32[width * height]; + for (int y = 0; y < height; y++) + { + float v = height > 1 ? (float)y / (height - 1) : 0f; + for (int x = 0; x < width; x++) + { + float u = width > 1 ? (float)x / (width - 1) : 0f; + float nx = Mathf.Sin(u * 16f * Mathf.PI) * 0.45f + (u - 0.5f) * 0.5f; + float ny = Mathf.Cos(v * 16f * Mathf.PI) * 0.45f + (v - 0.5f) * 0.5f; + float nz = Mathf.Sqrt(Mathf.Max(0.05f, 1f - nx * nx - ny * ny)); + Vector3 n = new Vector3(nx, ny, nz).normalized; + + pixels[y * width + x] = new Color32( + (byte)Mathf.Clamp(Mathf.RoundToInt((n.x * 0.5f + 0.5f) * 255f), 0, 255), + (byte)Mathf.Clamp(Mathf.RoundToInt((n.y * 0.5f + 0.5f) * 255f), 0, 255), + (byte)Mathf.Clamp(Mathf.RoundToInt((n.z * 0.5f + 0.5f) * 255f), 0, 255), + 255); + } + } + + tex.SetPixels32(pixels); + tex.Apply(updateMipmaps: false, makeNoLongerReadable: false); + return tex; + } + + public static Texture2D CreateProceduralHdrTexture(int width, int height) + { + var tex = new Texture2D(width, height, GraphicsFormat.R16G16B16A16_SFloat, TextureCreationFlags.None); + var pixels = new Color[width * height]; + for (int y = 0; y < height; y++) + { + float v = height > 1 ? (float)y / (height - 1) : 0f; + for (int x = 0; x < width; x++) + { + float u = width > 1 ? (float)x / (width - 1) : 0f; + float hotspot = Mathf.Exp(-((u - 0.5f) * (u - 0.5f) + (v - 0.5f) * (v - 0.5f)) * 24f); + float r = 0.1f + u * 2.0f + hotspot * 14.0f; + float g = 0.05f + v * 1.5f + hotspot * 10.0f; + float b = 0.2f + (1f - u) * 1.2f + hotspot * 6.0f; + pixels[y * width + x] = new Color(r, g, b, 1f); + } + } + + tex.SetPixels(pixels); + tex.Apply(updateMipmaps: false, makeNoLongerReadable: false); + return tex; + } + } +} diff --git a/Assets/ASTC Encoder/Editor/AstcPerformanceBenchmarkRunner.cs.meta b/Assets/ASTC Encoder/Editor/AstcPerformanceBenchmarkRunner.cs.meta new file mode 100644 index 0000000..7b4591d --- /dev/null +++ b/Assets/ASTC Encoder/Editor/AstcPerformanceBenchmarkRunner.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4f8c2a1e9b734d60a5e3c1f82d94b701 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Plugins/Android/arm64-v8a/libastcenc-neon-shared.so b/Assets/ASTC Encoder/Plugins/Android/arm64-v8a/libastcenc-neon-shared.so index 3954ba7..756f5a5 100644 --- a/Assets/ASTC Encoder/Plugins/Android/arm64-v8a/libastcenc-neon-shared.so +++ b/Assets/ASTC Encoder/Plugins/Android/arm64-v8a/libastcenc-neon-shared.so @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:730aed4dc146ec3d66ea129efc3fa416b9f64acfa69b86cb53523cafc0fc6a01 -size 2693832 +oid sha256:080614e904fa062ec36617e8ea263d687cfd2677a18a0d84325978f839f7d234 +size 372584 diff --git a/Assets/ASTC Encoder/Plugins/Android/armeabi-v7a/libastcenc-none-shared.so b/Assets/ASTC Encoder/Plugins/Android/armeabi-v7a/libastcenc-none-shared.so index 0e87137..07177e5 100644 --- a/Assets/ASTC Encoder/Plugins/Android/armeabi-v7a/libastcenc-none-shared.so +++ b/Assets/ASTC Encoder/Plugins/Android/armeabi-v7a/libastcenc-none-shared.so @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:0d6e1b55e838424ba6aa9533f8b863e7eba7dd082a4b59a9d65354d311986c9a -size 2438320 +oid sha256:7f6f494996bbc9bb9fff9767364eb5cd0731f186374d440ef3d18adcf0d88c0a +size 300552 diff --git a/Assets/ASTC Encoder/Plugins/Mac/libastcenc-shared.dylib b/Assets/ASTC Encoder/Plugins/Mac/libastcenc-shared.dylib index 42352f1..cf4976d 100644 --- a/Assets/ASTC Encoder/Plugins/Mac/libastcenc-shared.dylib +++ b/Assets/ASTC Encoder/Plugins/Mac/libastcenc-shared.dylib @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:4dab594946883ac56ff4252056dd7d2bc90ca7f78516aecf098fa5ec07610613 -size 773337 +oid sha256:cefb8b5648136d916e51e042f28cbf7033b6cfcf5f0dc3174dc899b6fbb8ff7a +size 741416 diff --git a/Assets/ASTC Encoder/Plugins/iOS/libastcenc-neon-static.a b/Assets/ASTC Encoder/Plugins/iOS/libastcenc-neon-static.a index 8a7dc21..820226a 100644 --- a/Assets/ASTC Encoder/Plugins/iOS/libastcenc-neon-static.a +++ b/Assets/ASTC Encoder/Plugins/iOS/libastcenc-neon-static.a @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:df2d7e354f76d0e0838d294c4a8bd7e2d3eebdd727d0375e4c6f88a387a6b41d -size 300784 +oid sha256:8f8d71457a918646588e1d62f8e708bd5b6cea0d8bcc8a6edc6163ce44f4f826 +size 214608 diff --git a/Assets/ASTC Encoder/Plugins/x64/astcenc-avx2-shared.dll b/Assets/ASTC Encoder/Plugins/x64/astcenc-avx2-shared.dll new file mode 100644 index 0000000..1d9c708 --- /dev/null +++ b/Assets/ASTC Encoder/Plugins/x64/astcenc-avx2-shared.dll @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b77db0b8cfa82954d13873a2208ace8785df321b30edc8c12383f5c8a1c74c08 +size 332800 diff --git a/Assets/ASTC Encoder/Plugins/x64/astcenc-avx2-shared.dll.meta b/Assets/ASTC Encoder/Plugins/x64/astcenc-avx2-shared.dll.meta new file mode 100644 index 0000000..8c4a938 --- /dev/null +++ b/Assets/ASTC Encoder/Plugins/x64/astcenc-avx2-shared.dll.meta @@ -0,0 +1,80 @@ +fileFormatVersion: 2 +guid: c8a4e91f3b2d47c8a5e01f6b9d3a82c1 +PluginImporter: + externalObjects: {} + serializedVersion: 2 + iconMap: {} + executionOrder: {} + defineConstraints: [] + isPreloaded: 0 + isOverridable: 0 + isExplicitlyReferenced: 0 + validateReferences: 1 + platformData: + - first: + : Any + second: + enabled: 0 + settings: + Exclude Android: 1 + Exclude Editor: 0 + Exclude Linux64: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 + Exclude Win64: 0 + Exclude iOS: 1 + - first: + Android: Android + second: + enabled: 0 + settings: + CPU: ARMv7 + - first: + Any: + second: + enabled: 0 + settings: {} + - first: + Editor: Editor + second: + enabled: 1 + settings: + CPU: x86_64 + DefaultValueInitialized: true + OS: Windows + - first: + Standalone: Linux64 + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: OSXUniversal + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Win + second: + enabled: 0 + settings: + CPU: None + - first: + Standalone: Win64 + second: + enabled: 1 + settings: + CPU: x86_64 + - first: + iPhone: iOS + second: + enabled: 0 + settings: + AddToEmbeddedBinaries: false + CPU: AnyCPU + CompileFlags: + FrameworkDependencies: + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Plugins/x64/astcenc-sse4.1-shared.dll b/Assets/ASTC Encoder/Plugins/x64/astcenc-sse4.1-shared.dll index f3d52dd..aaa2219 100644 --- a/Assets/ASTC Encoder/Plugins/x64/astcenc-sse4.1-shared.dll +++ b/Assets/ASTC Encoder/Plugins/x64/astcenc-sse4.1-shared.dll @@ -1,3 +1,3 @@ version https://git-lfs.github.com/spec/v1 -oid sha256:d7050224f13b39e9d7f71fe7417869b0f5b228629ea46bc50ac08db9d7da1d8b -size 188928 +oid sha256:0cf8d5fc766c0babaa90977953912421c2af51cdf0db73c88a3a486711e6ab68 +size 339456 diff --git a/Assets/ASTC Encoder/Plugins/x64/astcenc-sse4.1-shared.dll.meta b/Assets/ASTC Encoder/Plugins/x64/astcenc-sse4.1-shared.dll.meta index 46a9fd5..ee57949 100644 --- a/Assets/ASTC Encoder/Plugins/x64/astcenc-sse4.1-shared.dll.meta +++ b/Assets/ASTC Encoder/Plugins/x64/astcenc-sse4.1-shared.dll.meta @@ -18,9 +18,9 @@ PluginImporter: settings: Exclude Android: 1 Exclude Editor: 0 - Exclude Linux64: 0 - Exclude OSXUniversal: 0 - Exclude Win: 0 + Exclude Linux64: 1 + Exclude OSXUniversal: 1 + Exclude Win: 1 Exclude Win64: 0 Exclude iOS: 1 - first: @@ -45,19 +45,19 @@ PluginImporter: - first: Standalone: Linux64 second: - enabled: 1 + enabled: 0 settings: - CPU: AnyCPU + CPU: None - first: Standalone: OSXUniversal second: - enabled: 1 + enabled: 0 settings: - CPU: x86_64 + CPU: None - first: Standalone: Win second: - enabled: 1 + enabled: 0 settings: CPU: None - first: diff --git a/Assets/ASTC Encoder/Runtime/Aperture.Astcenc.Runtime.asmdef b/Assets/ASTC Encoder/Runtime/Aperture.Astcenc.Runtime.asmdef index fbbfb94..5a57fb7 100644 --- a/Assets/ASTC Encoder/Runtime/Aperture.Astcenc.Runtime.asmdef +++ b/Assets/ASTC Encoder/Runtime/Aperture.Astcenc.Runtime.asmdef @@ -4,7 +4,7 @@ "references": [], "includePlatforms": [], "excludePlatforms": [], - "allowUnsafeCode": false, + "allowUnsafeCode": true, "overrideReferences": false, "precompiledReferences": [], "autoReferenced": true, diff --git a/Assets/ASTC Encoder/Runtime/AstcCompressOptions.cs b/Assets/ASTC Encoder/Runtime/AstcCompressOptions.cs new file mode 100644 index 0000000..a3d2e68 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/AstcCompressOptions.cs @@ -0,0 +1,117 @@ +using System; + +namespace Aperture.Astcenc.Runtime +{ + /// + /// Configuration options for runtime ASTC texture compression. + /// Provides a single extensible entry point for basic and advanced encoder settings. + /// + [Serializable] + public struct AstcCompressOptions + { + /// Semantic texture type (Default color/data map or Normal map). + public TextureType TextureType; + + /// ASTC block footprint (larger blocks yield higher compression ratio). + public BlockSize BlockSize; + + /// Encoder search quality preset. + public CompressQuality Quality; + + /// Execution backend (Auto prefers GPU with automatic CPU fallback). + public EncodeBackend Backend; + + /// + /// Worker thread count for the CPU backend. + /// 1 = single-threaded, <= 0 = auto-select based on CPU cores. + /// + public int ThreadCount; + + /// + /// Weight RGB error by alpha transparency (recommended only for true transparency textures; + /// leave false for channel-packed maps such as ORM/MRAO). + /// + public bool UseAlphaWeight; + + /// + /// Radius for alpha-weight scaling in the CPU backend (defaults to 1 when is true + /// to minimize color bleed under bilinear filtering). + /// + public uint AlphaScaleRadius; + + /// + /// Enable perceptual error metrics in the CPU backend (optimizes for visual quality rather than pure PSNR). + /// + public bool UsePerceptual; + + /// Whether to encode all mipmap levels present on the input texture (ignored by single-level .astc export). + public bool IncludeMipmaps; + + /// + /// When true and using the GPU backend on a single-mip source texture, automatically generates a full + /// sRGB-aware / normal-renormalizing mipmap chain on the GPU and compresses all levels in one pass. + /// + public bool GenerateMipmaps; + + /// For in-place , whether to release CPU pixel memory after uploading. + public bool MakeNoLongerReadable; + + /// + /// When true on synchronous main-thread CPU compression calls, dispatches astcenc worker slices + /// via Unity's native Job System instead of .NET ThreadPool. + /// Ignored on background async tasks where Unity Job scheduling is disallowed. + /// + public bool UseUnityJobSystem; + + /// Default balanced runtime compression options (Default color, ASTC 6x6, Fast, Auto backend). + public static AstcCompressOptions Default => new AstcCompressOptions + { + TextureType = TextureType.Default, + BlockSize = BlockSize.ASTC_6x6, + Quality = CompressQuality.Fast, + Backend = EncodeBackend.Auto, + ThreadCount = 0, + UseAlphaWeight = false, + AlphaScaleRadius = 1u, + UsePerceptual = false, + IncludeMipmaps = true, + GenerateMipmaps = false, + MakeNoLongerReadable = true, + UseUnityJobSystem = false, + }; + + /// Preset configured for tangent-space normal maps (linear GGGR encoding). + public static AstcCompressOptions NormalMap => new AstcCompressOptions + { + TextureType = TextureType.Normal, + BlockSize = BlockSize.ASTC_6x6, + Quality = CompressQuality.Fast, + Backend = EncodeBackend.Auto, + ThreadCount = 0, + UseAlphaWeight = false, + AlphaScaleRadius = 0u, + UsePerceptual = false, + IncludeMipmaps = true, + GenerateMipmaps = false, + MakeNoLongerReadable = true, + UseUnityJobSystem = false, + }; + + /// Preset configured for alpha-blended transparent textures (UI, foliage, decals). + public static AstcCompressOptions Transparent => new AstcCompressOptions + { + TextureType = TextureType.Default, + BlockSize = BlockSize.ASTC_6x6, + Quality = CompressQuality.Fast, + Backend = EncodeBackend.Auto, + ThreadCount = 0, + UseAlphaWeight = true, + AlphaScaleRadius = 1u, + UsePerceptual = false, + IncludeMipmaps = true, + GenerateMipmaps = false, + MakeNoLongerReadable = true, + UseUnityJobSystem = false, + }; + } +} diff --git a/Assets/ASTC Encoder/Runtime/AstcCompressOptions.cs.meta b/Assets/ASTC Encoder/Runtime/AstcCompressOptions.cs.meta new file mode 100644 index 0000000..3f1d192 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/AstcCompressOptions.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8f3a2c4b9e1d47a6b5c8d0e2f1a3b7c9 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/AstcCompressionQueue.cs b/Assets/ASTC Encoder/Runtime/AstcCompressionQueue.cs new file mode 100644 index 0000000..d9527b8 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/AstcCompressionQueue.cs @@ -0,0 +1,656 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using UnityEngine; +using UnityEngine.Experimental.Rendering; + +namespace Aperture.Astcenc.Runtime +{ + /// + /// Scheduling priority for jobs. + /// + public enum AstcTaskPriority + { + Low = 0, + Normal = 1, + High = 2 + } + + /// + /// Frame-budgeted priority queue for runtime ASTC compression with pooled CPU + /// table sharing. Call once per frame from a MonoBehaviour Update() loop + /// to spread bursts of texture compressions smoothly across frames without frame-time spikes. + /// + public sealed class AstcCompressionQueue : IDisposable + { + private readonly struct ContextPoolKey : IEquatable + { + public readonly GraphicsFormat Format; + public readonly TextureType TextureType; + public readonly BlockSize BlockSize; + public readonly CompressQuality Quality; + public readonly int ThreadCount; + public readonly bool UseAlphaWeight; + public readonly bool UsePerceptual; + public readonly uint AlphaScaleRadius; + + public ContextPoolKey(GraphicsFormat format, AstcCompressOptions options) + { + Format = format; + TextureType = options.TextureType; + BlockSize = options.BlockSize; + Quality = options.Quality; + ThreadCount = options.ThreadCount; + UseAlphaWeight = options.UseAlphaWeight; + UsePerceptual = options.UsePerceptual; + AlphaScaleRadius = options.AlphaScaleRadius; + } + + public bool Equals(ContextPoolKey other) => + Format == other.Format && + TextureType == other.TextureType && + BlockSize == other.BlockSize && + Quality == other.Quality && + ThreadCount == other.ThreadCount && + UseAlphaWeight == other.UseAlphaWeight && + UsePerceptual == other.UsePerceptual && + AlphaScaleRadius == other.AlphaScaleRadius; + + public override bool Equals(object obj) => obj is ContextPoolKey other && Equals(other); + + public override int GetHashCode() + { + unchecked + { + int h = (int)Format; + h = (h * 397) ^ (int)TextureType; + h = (h * 397) ^ (int)BlockSize; + h = (h * 397) ^ (int)Quality; + h = (h * 397) ^ ThreadCount; + h = (h * 397) ^ (UseAlphaWeight ? 1 : 0); + h = (h * 397) ^ (UsePerceptual ? 1 : 0); + h = (h * 397) ^ (int)AlphaScaleRadius; + return h; + } + } + } + + private sealed class PendingJob + { + public Texture Source; + public AstcCompressOptions Options; + public AstcTaskPriority Priority; + public bool OutputTexture; + public long TexelCost; + public CancellationToken CancellationToken; + public TaskCompletionSource TextureTcs; + public TaskCompletionSource RawTcs; + + public void Cancel() + { + TextureTcs?.TrySetCanceled(); + RawTcs?.TrySetCanceled(); + } + + public void SetException(Exception ex) + { + TextureTcs?.TrySetException(ex); + RawTcs?.TrySetException(ex); + } + } + + private readonly Queue[] m_GpuQueues = + { + new Queue(), + new Queue(), + new Queue() + }; + + private readonly Queue[] m_CpuQueues = + { + new Queue(), + new Queue(), + new Queue() + }; + + private readonly object m_PoolLock = new object(); + private readonly Dictionary> m_ContextPool = new Dictionary>(); + private readonly Dictionary m_ParentContexts = new Dictionary(); + + private int m_ActiveCpuCount; + private int m_InFlightContextCount; + private bool m_Disposed; + + /// + /// Maximum number of GPU texels dispatched per call (default: 1024 x 1024). + /// At least one pending GPU job is always dispatched per frame even if it exceeds this budget. + /// + public long MaxGpuTexelsPerFrame { get; set; } = 1024L * 1024L; + + /// + /// Maximum number of concurrent background CPU compression jobs (default: half of logical cores, minimum 1). + /// + public int MaxConcurrentCpuTasks { get; set; } = Math.Max(1, Environment.ProcessorCount / 2); + + public int PendingGpuCount => m_GpuQueues[0].Count + m_GpuQueues[1].Count + m_GpuQueues[2].Count; + public int PendingCpuCount => m_CpuQueues[0].Count + m_CpuQueues[1].Count + m_CpuQueues[2].Count; + public int ActiveCpuCount => Volatile.Read(ref m_ActiveCpuCount); + + /// + /// Enqueues a texture to be compressed into a new ASTC on a future tick. + /// + public Task EnqueueToTexture( + Texture source, + AstcCompressOptions options, + AstcTaskPriority priority = AstcTaskPriority.Normal, + CancellationToken cancellationToken = default) + { + ThrowIfDisposed(); + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + if (cancellationToken.IsCancellationRequested) + { + tcs.SetCanceled(); + return tcs.Task; + } + if (source == null) + { + tcs.SetResult(null); + return tcs.Task; + } + + EnqueueJob(new PendingJob + { + Source = source, + Options = options, + Priority = priority, + OutputTexture = true, + TexelCost = Math.Max(1L, (long)source.width * source.height), + CancellationToken = cancellationToken, + TextureTcs = tcs + }); + return tcs.Task; + } + + /// + /// Enqueues a texture to be compressed into raw ASTC bytes () on a future tick. + /// Caller owns and must Dispose() the returned . + /// + public Task EnqueueToRaw( + Texture source, + AstcCompressOptions options, + AstcTaskPriority priority = AstcTaskPriority.Normal, + CancellationToken cancellationToken = default) + { + ThrowIfDisposed(); + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + if (cancellationToken.IsCancellationRequested) + { + tcs.SetCanceled(); + return tcs.Task; + } + if (source == null) + { + tcs.SetResult(null); + return tcs.Task; + } + + EnqueueJob(new PendingJob + { + Source = source, + Options = options, + Priority = priority, + OutputTexture = false, + TexelCost = Math.Max(1L, (long)source.width * source.height), + CancellationToken = cancellationToken, + RawTcs = tcs + }); + return tcs.Task; + } + + /// + /// Processes queued GPU jobs up to and starts queued CPU jobs + /// up to . Must be called from the Unity main thread. + /// + public void ProcessFrame() + { + if (m_Disposed) + return; + + // 1. Dispatch GPU jobs within the frame texel budget, batching direct-copy jobs into a single CommandBuffer. + long remainingBudget = Math.Max(1L, MaxGpuTexelsPerFrame); + bool dispatchedAnyGpu = false; + UnityEngine.Rendering.CommandBuffer batchCmd = null; + List<(PendingJob Job, Texture2D Result)> batchedResults = null; + + try + { + while (TryPeekHighestPriority(m_GpuQueues, out PendingJob nextGpu)) + { + if (nextGpu.CancellationToken.IsCancellationRequested) + { + DequeueHighestPriority(m_GpuQueues); + nextGpu.Cancel(); + continue; + } + + if (dispatchedAnyGpu && nextGpu.TexelCost > remainingBudget) + break; + + DequeueHighestPriority(m_GpuQueues); + dispatchedAnyGpu = true; + remainingBudget -= nextGpu.TexelCost; + + if (nextGpu.OutputTexture + && nextGpu.Source != null + && AstcGpuBackend.CanUseDirectCompress( + nextGpu.Source, + nextGpu.Options.TextureType, + nextGpu.Options.BlockSize, + nextGpu.Options.IncludeMipmaps, + nextGpu.Options.GenerateMipmaps, + out GraphicsFormat astcFormat, + out int mipCount, + out bool willGenMips)) + { +#if UNITY_2022_1_OR_NEWER + TextureCreationFlags flags = TextureCreationFlags.DontInitializePixels | TextureCreationFlags.DontUploadUponCreate; +#else + TextureCreationFlags flags = TextureCreationFlags.None; +#endif + if (mipCount > 1) + flags |= TextureCreationFlags.MipChain; + + var dst = new Texture2D(nextGpu.Source.width, nextGpu.Source.height, astcFormat, mipCount, flags); + try + { + dst.name = nextGpu.Source.name; + dst.Apply(false, true); + + if (batchCmd == null) + { + batchCmd = new UnityEngine.Rendering.CommandBuffer { name = "AstcQueueBatch" }; + batchedResults = new List<(PendingJob, Texture2D)>(); + } + + AstcGpuBackend.RecordDirectCompressToTexture( + batchCmd, + nextGpu.Source, + dst, + nextGpu.Options.TextureType, + nextGpu.Options.BlockSize, + nextGpu.Options.Quality, + mipCount, + nextGpu.Options.UseAlphaWeight, + willGenMips); + batchedResults.Add((nextGpu, dst)); + } + catch (Exception ex) + { + UnityEngine.Object.DestroyImmediate(dst); + nextGpu.SetException(ex); + } + } + else + { + RunGpuJob(nextGpu); + } + } + + if (batchCmd != null && batchedResults != null && batchedResults.Count > 0) + { + Graphics.ExecuteCommandBuffer(batchCmd); + for (int i = 0; i < batchedResults.Count; i++) + { + var (job, tex) = batchedResults[i]; + if (!job.TextureTcs.TrySetResult(tex) && tex != null) + { + UnityEngine.Object.DestroyImmediate(tex); + } + } + } + } + catch (Exception ex) + { + if (batchedResults != null) + { + for (int i = 0; i < batchedResults.Count; i++) + { + var (job, tex) = batchedResults[i]; + if (tex != null) UnityEngine.Object.DestroyImmediate(tex); + job.SetException(ex); + } + } + } + finally + { + batchCmd?.Release(); + } + + // 2. Dispatch CPU jobs up to MaxConcurrentCpuTasks + int maxCpu = Math.Max(1, MaxConcurrentCpuTasks); + while (Volatile.Read(ref m_ActiveCpuCount) < maxCpu && TryPeekHighestPriority(m_CpuQueues, out PendingJob nextCpu)) + { + DequeueHighestPriority(m_CpuQueues); + if (nextCpu.CancellationToken.IsCancellationRequested) + { + nextCpu.Cancel(); + continue; + } + + RunCpuJob(nextCpu); + } + } + + /// + /// Cancels all queued jobs that have not yet started executing. + /// + public void CancelAllPending() + { + DrainAndCancel(m_GpuQueues); + DrainAndCancel(m_CpuQueues); + } + + public void Dispose() + { + if (m_Disposed) + return; + + m_Disposed = true; + CancelAllPending(); + + lock (m_PoolLock) + { + foreach (var stack in m_ContextPool.Values) + { + while (stack.Count > 0) + { + stack.Pop().Dispose(); + } + } + m_ContextPool.Clear(); + + // astc-encoder 5.x parent contexts hold shared read-only tables referenced by child contexts. + // Only free parent contexts once every in-flight child context has been disposed. + if (m_InFlightContextCount == 0) + { + DisposeParentContextsLocked(); + } + } + } + + private void DisposeParentContextsLocked() + { + foreach (var parent in m_ParentContexts.Values) + { + parent.Dispose(); + } + m_ParentContexts.Clear(); + } + + private void EnqueueJob(PendingJob job) + { + bool useGpu = job.Options.Backend == EncodeBackend.Gpu || + (job.Options.Backend == EncodeBackend.Auto && Encoder.IsGpuSupported); + int bucket = ClampPriority(job.Priority); + if (useGpu) + m_GpuQueues[bucket].Enqueue(job); + else + m_CpuQueues[bucket].Enqueue(job); + } + + private async void RunGpuJob(PendingJob job) + { + try + { + if (job.Source == null) + { + job.TextureTcs?.TrySetResult(null); + job.RawTcs?.TrySetResult(null); + return; + } + + if (job.OutputTexture) + { + Texture2D tex = await job.Source.CompressToTextureAsync(job.Options, job.CancellationToken); + if (!job.TextureTcs.TrySetResult(tex) && tex != null) + { + UnityEngine.Object.DestroyImmediate(tex); + } + } + else + { + AstcRaw raw = await job.Source.CompressTextureAsync(job.Options, job.CancellationToken); + if (!job.RawTcs.TrySetResult(raw) && raw != null) + { + raw.Dispose(); + } + } + } + catch (OperationCanceledException) + { + job.Cancel(); + } + catch (Exception ex) + { + job.SetException(ex); + } + } + + private async void RunCpuJob(PendingJob job) + { + if (!(job.Source is Texture2D tex2d) || tex2d == null) + { + job.TextureTcs?.TrySetResult(null); + job.RawTcs?.TrySetResult(null); + return; + } + + // Capture texture metadata on the main thread before awaiting so destroying tex2d mid-flight is safe. + GraphicsFormat srcFormat = tex2d.graphicsFormat; + int width = tex2d.width; + int height = tex2d.height; + string texName = tex2d.name; + + Interlocked.Increment(ref m_ActiveCpuCount); + AstcContext rented = null; + var key = new ContextPoolKey(srcFormat, job.Options); + + try + { + rented = RentContext(key, job.Options); + if (rented == null) + { + job.TextureTcs?.TrySetResult(null); + job.RawTcs?.TrySetResult(null); + return; + } + + AstcRaw raw = await AstcCpuBackend.CompressTextureWithContextAsync(tex2d, rented, job.Options.TextureType, job.Options.IncludeMipmaps, job.CancellationToken); + if (!job.OutputTexture) + { + if (!job.RawTcs.TrySetResult(raw) && raw != null) + { + raw.Dispose(); + } + return; + } + + if (raw == null) + { + job.TextureTcs.TrySetResult(null); + return; + } + + using (raw) + { + GraphicsFormat targetFormat = Encoder.GetTargetAstcFormat(srcFormat, job.Options.BlockSize, job.Options.TextureType); + if (!Encoder.CanCreateAstcTexture(targetFormat)) + { + Debug.LogError($"ASTC texture format '{targetFormat}' is not supported on this device. Use EnqueueToRaw instead."); + job.TextureTcs.TrySetResult(null); + return; + } + + int mipCount = AstcKtxContainer.InferMipCount(raw.Length, width, height, job.Options.BlockSize); + TextureCreationFlags flags = mipCount > 1 ? TextureCreationFlags.MipChain : TextureCreationFlags.None; + var dst = new Texture2D(width, height, targetFormat, mipCount, flags); + try + { + dst.name = texName; + dst.LoadRawTextureData(raw.Data, raw.Length); + dst.Apply(false, job.Options.MakeNoLongerReadable); + if (!job.TextureTcs.TrySetResult(dst)) + { + UnityEngine.Object.DestroyImmediate(dst); + } + } + catch + { + UnityEngine.Object.DestroyImmediate(dst); + throw; + } + } + } + catch (OperationCanceledException) + { + job.Cancel(); + } + catch (Exception ex) + { + job.SetException(ex); + } + finally + { + ReturnContext(key, rented); + Interlocked.Decrement(ref m_ActiveCpuCount); + } + } + + private AstcContext RentContext(ContextPoolKey key, AstcCompressOptions options) + { + lock (m_PoolLock) + { + if (m_Disposed) + return null; + + if (m_ContextPool.TryGetValue(key, out Stack stack) && stack.Count > 0) + { + m_InFlightContextCount++; + return stack.Pop(); + } + + // Lazily create a parent context per BlockSize to share read-only astcenc 5.x lookup tables + if (!m_ParentContexts.TryGetValue(key.BlockSize, out AstcContext parent)) + { + parent = AstcContext.Create( + key.Format, + options.TextureType, + options.BlockSize, + options.Quality, + options.ThreadCount, + options.UseAlphaWeight, + options.UsePerceptual, + options.AlphaScaleRadius); + if (parent != null) + m_ParentContexts[key.BlockSize] = parent; + } + + AstcContext child = AstcContext.Create( + key.Format, + options.TextureType, + options.BlockSize, + options.Quality, + options.ThreadCount, + options.UseAlphaWeight, + options.UsePerceptual, + options.AlphaScaleRadius, + parent); + if (child != null) + m_InFlightContextCount++; + return child; + } + } + + private void ReturnContext(ContextPoolKey key, AstcContext ctx) + { + if (ctx == null) + return; + + lock (m_PoolLock) + { + if (m_Disposed) + { + ctx.Dispose(); + m_InFlightContextCount--; + if (m_InFlightContextCount <= 0) + { + m_InFlightContextCount = 0; + DisposeParentContextsLocked(); + } + return; + } + + m_InFlightContextCount--; + + if (!m_ContextPool.TryGetValue(key, out Stack stack)) + { + stack = new Stack(); + m_ContextPool[key] = stack; + } + + if (stack.Count < 4) + stack.Push(ctx); + else + ctx.Dispose(); + } + } + + private static int ClampPriority(AstcTaskPriority p) + { + int v = (int)p; + return v < 0 ? 0 : (v > 2 ? 2 : v); + } + + private static bool TryPeekHighestPriority(Queue[] queues, out PendingJob job) + { + for (int i = 2; i >= 0; i--) + { + if (queues[i].Count > 0) + { + job = queues[i].Peek(); + return true; + } + } + job = null; + return false; + } + + private static PendingJob DequeueHighestPriority(Queue[] queues) + { + for (int i = 2; i >= 0; i--) + { + if (queues[i].Count > 0) + return queues[i].Dequeue(); + } + return null; + } + + private static void DrainAndCancel(Queue[] queues) + { + for (int i = 0; i < queues.Length; i++) + { + while (queues[i].Count > 0) + { + queues[i].Dequeue().Cancel(); + } + } + } + + private void ThrowIfDisposed() + { + if (m_Disposed) + throw new ObjectDisposedException(nameof(AstcCompressionQueue)); + } + } +} diff --git a/Assets/ASTC Encoder/Runtime/AstcCompressionQueue.cs.meta b/Assets/ASTC Encoder/Runtime/AstcCompressionQueue.cs.meta new file mode 100644 index 0000000..c9c5c68 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/AstcCompressionQueue.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 3c7a91e4f5b248d0a6e1c3b9d8f4207a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/AstcContext.cs b/Assets/ASTC Encoder/Runtime/AstcContext.cs new file mode 100644 index 0000000..e013358 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/AstcContext.cs @@ -0,0 +1,426 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using Unity.Jobs; +using UnityEngine; +using UnityEngine.Experimental.Rendering; +using Aperture.Astcenc.Runtime.NativeAPI; + +namespace Aperture.Astcenc.Runtime +{ + /// + /// Reusable native astcenc codec context supporting single-threaded, multi-threaded, and async compression. + /// Reusing a context across multiple textures avoids repeated astcenc_context_alloc setup overhead. + /// + public sealed class AstcContext : IDisposable + { + private const int k_ParallelMinOutputBytes = 64 * 16; + + private readonly object m_SyncLock = new object(); + private IntPtr m_Context; + private int m_Disposed; + + public BlockSize BlockSize { get; } + public CompressQuality Quality { get; } + public int ThreadCount { get; } + + /// + /// When true, schedules multi-threaded astcenc work via Unity's native + /// Worker Thread Pool instead of .NET ThreadPool. Only enable when invoking from the Unity main thread. + /// + public bool UseUnityJobSystem { get; set; } + + internal uint BlockX { get; } + internal uint BlockY { get; } + internal astcenc_profile Profile { get; } + internal CodecFlags Flags { get; } + internal bool IsDecompressOnly => (Flags & CodecFlags.DecompressOnly) != 0; + + private unsafe struct AstcCompressParallelJob : IJobParallelFor + { + public IntPtr Context; + public astcenc_image Image; + public astcenc_swizzle Swizzle; + public IntPtr Output; + public UIntPtr OutputLength; + public IntPtr FirstErrorPtr; + + public void Execute(int threadIndex) + { + astcenc_image localImage = Image; + astcenc_swizzle localSwizzle = Swizzle; + astcenc_error threadStatus = astcenc_api.astcenc_compress_image( + Context, + ref localImage, + ref localSwizzle, + Output, + OutputLength, + (uint)threadIndex); + + if (threadStatus != astcenc_error.ASTCENC_SUCCESS) + { + Interlocked.CompareExchange(ref *(int*)FirstErrorPtr, (int)threadStatus, (int)astcenc_error.ASTCENC_SUCCESS); + } + } + } + + private AstcContext( + IntPtr context, + astcenc_profile profile, + BlockSize blockSize, + uint blockX, + uint blockY, + CompressQuality quality, + CodecFlags flags, + int threadCount, + bool useUnityJobSystem = false) + { + m_Context = context; + Profile = profile; + BlockSize = blockSize; + BlockX = blockX; + BlockY = blockY; + Quality = quality; + Flags = flags; + ThreadCount = threadCount; + UseUnityJobSystem = useUnityJobSystem; + m_Disposed = 0; + } + + ~AstcContext() + { + Dispose(false); + } + + /// + /// Creates a reusable ASTC compression context matching the given texture format and encoding settings. + /// Pass threadCount <= 0 to auto-select a sensible worker thread count based on CPU cores. + /// Optionally pass with matching block dimensions to share read-only lookup tables (astcenc 5.x). + /// + public static AstcContext Create( + GraphicsFormat graphicsFormat, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + int threadCount = 1, + bool useAlphaWeight = false, + bool usePerceptual = false, + uint alphaScaleRadius = 1u, + AstcContext parentContext = null, + bool useUnityJobSystem = false) + { + if (!AstcCpuBackend.IsSupported) + { + Debug.LogError("Native CPU ASTC compression library is not available on this platform."); + return null; + } + + if (!AstcCpuBackend.IsSupportGraphicFormat(graphicsFormat)) + { + Debug.LogError("Unsupported GraphicsFormat: " + graphicsFormat); + return null; + } + + if (!Encoder.GetBlockSize(blockSize, out uint blockX, out uint blockY, out uint blockZ)) + { + Debug.LogError("Unsupported ASTC block size: " + blockSize); + return null; + } + + IntPtr parentPtr = IntPtr.Zero; + if (parentContext != null) + { + parentContext.ThrowIfDisposed(); + if (parentContext.BlockX != blockX || parentContext.BlockY != blockY) + { + Debug.LogError($"Parent AstcContext block size ({parentContext.BlockSize}) does not match requested block size ({blockSize})."); + return null; + } + parentPtr = parentContext.m_Context; + } + + int resolvedThreads = threadCount <= 0 + ? Math.Max(1, Math.Min(Environment.ProcessorCount, 4)) + : threadCount; + + float qualityValue = AstcCpuBackend.GetQualityValue(quality); + astcenc_profile profile = AstcCpuBackend.GetColorProfile(graphicsFormat, textureType); + CodecFlags flags = AstcCpuBackend.GetFlags(textureType, graphicsFormat, useAlphaWeight, usePerceptual); + + astcenc_config config = new astcenc_config(); + astcenc_error status = astcenc_api.astcenc_config_init(profile, blockX, blockY, blockZ, qualityValue, (uint)flags, ref config); + if (status != astcenc_error.ASTCENC_SUCCESS) + { + Debug.LogError("Codec config init failed:" + status); + return null; + } + + if ((flags & CodecFlags.UseAlphaWeight) != 0) + { + config.a_scale_radius = alphaScaleRadius; + } + + IntPtr context = IntPtr.Zero; + status = parentPtr != IntPtr.Zero + ? astcenc_api.astcenc_context_alloc(IntPtr.Zero, (uint)resolvedThreads, ref context, parentPtr) + : astcenc_api.astcenc_context_alloc(ref config, (uint)resolvedThreads, ref context, IntPtr.Zero); + if (status != astcenc_error.ASTCENC_SUCCESS) + { + Debug.LogError("Codec context alloc failed:" + status); + return null; + } + + return new AstcContext(context, profile, blockSize, blockX, blockY, quality, flags, resolvedThreads, useUnityJobSystem); + } + + /// + /// Creates a lightweight decompression-only ASTC context for CPU decoding via ARM astc-encoder. + /// + public static AstcContext CreateDecompressor( + BlockSize blockSize, + bool srgb = false, + bool isHdr = false, + int threadCount = 1) + { + if (!AstcCpuBackend.IsSupported) + { + Debug.LogError("Native CPU ASTC library is not available on this platform."); + return null; + } + + if (!Encoder.GetBlockSize(blockSize, out uint blockX, out uint blockY, out uint blockZ)) + { + Debug.LogError("Unsupported ASTC block size: " + blockSize); + return null; + } + + int resolvedThreads = threadCount <= 0 + ? Math.Max(1, Math.Min(Environment.ProcessorCount, 4)) + : threadCount; + + astcenc_profile profile = isHdr + ? astcenc_profile.ASTCENC_PRF_HDR + : (srgb ? astcenc_profile.ASTCENC_PRF_LDR_SRGB : astcenc_profile.ASTCENC_PRF_LDR); + + CodecFlags flags = CodecFlags.DecompressOnly; + + astcenc_config config = new astcenc_config(); + astcenc_error status = astcenc_api.astcenc_config_init(profile, blockX, blockY, blockZ, 0.0f, (uint)flags, ref config); + if (status != astcenc_error.ASTCENC_SUCCESS) + { + Debug.LogError("Decompress codec config init failed:" + status); + return null; + } + + IntPtr context = IntPtr.Zero; + status = astcenc_api.astcenc_context_alloc(ref config, (uint)resolvedThreads, ref context, IntPtr.Zero); + if (status != astcenc_error.ASTCENC_SUCCESS) + { + Debug.LogError("Decompress codec context alloc failed:" + status); + return null; + } + + return new AstcContext(context, profile, blockSize, blockX, blockY, CompressQuality.Fastest, flags, resolvedThreads); + } + + public void ThrowIfDisposed() + { + if (Volatile.Read(ref m_Disposed) != 0) + throw new ObjectDisposedException(GetType().FullName); + } + + /// + /// Synchronously compresses a Texture2D reusing this codec context. + /// + public AstcRaw CompressTexture(Texture2D inputTexture, TextureType textureType = TextureType.Default) + { + ThrowIfDisposed(); + return AstcCpuBackend.CompressTextureWithContext(inputTexture, this, textureType, true); + } + + /// + /// Captures pixel data on the calling (main) thread and compresses asynchronously on background thread(s) reusing this context. + /// Caller must keep this AstcContext alive until the returned Task completes and dispose the returned AstcRaw after use. + /// + public Task CompressTextureAsync(Texture2D inputTexture, TextureType textureType = TextureType.Default, CancellationToken cancellationToken = default) + { + ThrowIfDisposed(); + return AstcCpuBackend.CompressTextureWithContextAsync(inputTexture, this, textureType, true, cancellationToken); + } + + internal bool IsCompatibleWith(GraphicsFormat graphicsFormat, TextureType textureType) + { + if (IsDecompressOnly) + return false; + + bool isNormalContext = (Flags & CodecFlags.MapNormal) != 0; + return AstcCpuBackend.GetColorProfile(graphicsFormat, textureType) == Profile + && isNormalContext == (textureType == TextureType.Normal); + } + + internal astcenc_error DecompressSingleImage(IntPtr compressedData, int compressedLength, ref astcenc_image imageOut, ref astcenc_swizzle swizzle) + { + lock (m_SyncLock) + { + ThrowIfDisposed(); + + astcenc_error status; + try + { + if (ThreadCount == 1 || compressedLength <= k_ParallelMinOutputBytes) + { + status = astcenc_api.astcenc_decompress_image( + m_Context, + compressedData, + new UIntPtr((uint)compressedLength), + ref imageOut, + ref swizzle, + 0); + } + else + { + astcenc_image imageCopy = imageOut; + astcenc_swizzle swizzleCopy = swizzle; + UIntPtr dataLen = new UIntPtr((uint)compressedLength); + int firstError = (int)astcenc_error.ASTCENC_SUCCESS; + + Parallel.For(0, ThreadCount, threadIndex => + { + astcenc_image localImage = imageCopy; + astcenc_swizzle localSwizzle = swizzleCopy; + astcenc_error threadStatus = astcenc_api.astcenc_decompress_image( + m_Context, + compressedData, + dataLen, + ref localImage, + ref localSwizzle, + (uint)threadIndex); + + if (threadStatus != astcenc_error.ASTCENC_SUCCESS) + { + Interlocked.CompareExchange(ref firstError, (int)threadStatus, (int)astcenc_error.ASTCENC_SUCCESS); + } + }); + + status = (astcenc_error)firstError; + } + } + finally + { + astcenc_api.astcenc_decompress_reset(m_Context); + } + + return status; + } + } + + internal astcenc_error CompressSingleImage(ref astcenc_image image, ref astcenc_swizzle swizzle, IntPtr output, int outputLength, CancellationToken cancellationToken = default) + { + lock (m_SyncLock) + { + ThrowIfDisposed(); + cancellationToken.ThrowIfCancellationRequested(); + + astcenc_error status; + using (CancellationTokenRegistration cancelRegistration = cancellationToken.CanBeCanceled + ? cancellationToken.Register(() => astcenc_api.astcenc_compress_cancel(m_Context)) + : default) + { + try + { + if (ThreadCount == 1 || outputLength <= k_ParallelMinOutputBytes) + { + status = astcenc_api.astcenc_compress_image(m_Context, ref image, ref swizzle, output, new UIntPtr((uint)outputLength), 0); + } + else if (UseUnityJobSystem) + { + int firstError = (int)astcenc_error.ASTCENC_SUCCESS; + unsafe + { + int* errPtr = &firstError; + var job = new AstcCompressParallelJob + { + Context = m_Context, + Image = image, + Swizzle = swizzle, + Output = output, + OutputLength = new UIntPtr((uint)outputLength), + FirstErrorPtr = (IntPtr)errPtr, + }; + job.Schedule(ThreadCount, 1).Complete(); + } + status = (astcenc_error)firstError; + } + else + { + astcenc_image imageCopy = image; + astcenc_swizzle swizzleCopy = swizzle; + UIntPtr dataLen = new UIntPtr((uint)outputLength); + int firstError = (int)astcenc_error.ASTCENC_SUCCESS; + + Parallel.For(0, ThreadCount, threadIndex => + { + astcenc_image localImage = imageCopy; + astcenc_swizzle localSwizzle = swizzleCopy; + astcenc_error threadStatus = astcenc_api.astcenc_compress_image( + m_Context, + ref localImage, + ref localSwizzle, + output, + dataLen, + (uint)threadIndex); + + if (threadStatus != astcenc_error.ASTCENC_SUCCESS) + { + Interlocked.CompareExchange(ref firstError, (int)threadStatus, (int)astcenc_error.ASTCENC_SUCCESS); + } + }); + + status = (astcenc_error)firstError; + } + } + finally + { + astcenc_api.astcenc_compress_reset(m_Context); + } + } + + cancellationToken.ThrowIfCancellationRequested(); + return status; + } + } + + private void Dispose(bool disposing) + { + if (disposing) + { + lock (m_SyncLock) + { + FreeNativeContext(); + } + } + else + { + FreeNativeContext(); + } + } + + private void FreeNativeContext() + { + if (Interlocked.Exchange(ref m_Disposed, 1) == 0) + { + IntPtr context = Interlocked.Exchange(ref m_Context, IntPtr.Zero); + if (context != IntPtr.Zero) + { + astcenc_api.astcenc_context_free(context); + } + } + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + } +} diff --git a/Assets/ASTC Encoder/Runtime/AstcContext.cs.meta b/Assets/ASTC Encoder/Runtime/AstcContext.cs.meta new file mode 100644 index 0000000..04501a5 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/AstcContext.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: c4a7f31e9b2d48f6a1e5c83b70d2f491 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/AstcDiskCache.cs b/Assets/ASTC Encoder/Runtime/AstcDiskCache.cs new file mode 100644 index 0000000..028e6b5 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/AstcDiskCache.cs @@ -0,0 +1,198 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using UnityEngine; +using UnityEngine.Experimental.Rendering; + +namespace Aperture.Astcenc.Runtime +{ + /// + /// Persistent on-disk ASTC texture cache backed by standard KTX v1 files (with full mipmap chains). + /// Enables "compress once, load instantly on subsequent launches" workflows for downloaded or procedural textures. + /// + public static class AstcDiskCache + { + /// + /// Attempts to load a cached KTX v1 ASTC texture from . + /// Returns null if the file does not exist or is corrupted. + /// + public static Texture2D TryLoad(string cachePath, bool makeNoLongerReadable = true, string textureName = null) + { + if (string.IsNullOrEmpty(cachePath) || !File.Exists(cachePath)) + return null; + + try + { + byte[] bytes = File.ReadAllBytes(cachePath); + return AstcKtxContainer.LoadTexture(bytes, makeNoLongerReadable, textureName); + } + catch (Exception ex) + { + Debug.LogError($"Failed to load cached ASTC KTX from '{cachePath}': {ex.Message}"); + return null; + } + } + + /// + /// Asynchronously loads a cached KTX v1 ASTC texture from disk (file I/O off the main thread, GPU upload on caller thread). + /// + public static async Task TryLoadAsync(string cachePath, bool makeNoLongerReadable = true, string textureName = null, CancellationToken cancellationToken = default) + { + if (string.IsNullOrEmpty(cachePath) || !File.Exists(cachePath)) + return null; + + try + { + byte[] bytes = await Task.Run(() => File.ReadAllBytes(cachePath), cancellationToken); + cancellationToken.ThrowIfCancellationRequested(); + return AstcKtxContainer.LoadTexture(bytes, makeNoLongerReadable, textureName); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + Debug.LogError($"Failed to asynchronously load cached ASTC KTX from '{cachePath}': {ex.Message}"); + return null; + } + } + + /// + /// Compresses asynchronously, saves the resulting KTX v1 file atomically to , + /// and returns the GPU-ready ASTC . + /// + public static async Task CompressAndSaveAsync( + Texture source, + string cachePath, + AstcCompressOptions options, + CancellationToken cancellationToken = default) + { + if (source == null) + return null; + + int width = source.width; + int height = source.height; + string texName = source.name; + GraphicsFormat targetFormat = Encoder.GetTargetAstcFormat(source.graphicsFormat, options.BlockSize, options.TextureType); + + using AstcRaw raw = await source.CompressTextureAsync(options, cancellationToken); + if (raw == null) + return null; + + cancellationToken.ThrowIfCancellationRequested(); + int mipCount = AstcKtxContainer.InferMipCount(raw.Length, width, height, options.BlockSize); + if (mipCount <= 0) + return null; + + byte[] ktxBytes = AstcKtxContainer.Encode(raw, width, height, mipCount, targetFormat); + + if (!string.IsNullOrEmpty(cachePath)) + { + await WriteFileAtomicAsync(cachePath, ktxBytes, cancellationToken); + } + + cancellationToken.ThrowIfCancellationRequested(); + + if (Encoder.CanCreateAstcTexture(targetFormat)) + { + TextureCreationFlags flags = mipCount > 1 ? TextureCreationFlags.MipChain : TextureCreationFlags.None; + var tex = new Texture2D(width, height, targetFormat, mipCount, flags); + try + { + if (!string.IsNullOrEmpty(texName)) + tex.name = texName; + tex.LoadRawTextureData(raw.Data, raw.Length); + tex.Apply(false, options.MakeNoLongerReadable); + return tex; + } + catch + { + UnityEngine.Object.DestroyImmediate(tex); + throw; + } + } + + return AstcKtxContainer.LoadTexture(ktxBytes, options.MakeNoLongerReadable, texName); + } + + /// + /// Loads the cached ASTC texture from if present and valid; + /// otherwise invokes , compresses to ASTC, saves atomically to disk, and returns the texture. + /// + public static async Task LoadOrCompressAsync( + string cachePath, + Func> sourceProvider, + AstcCompressOptions options, + bool destroySourceAfterCompress = false, + CancellationToken cancellationToken = default) + { + Texture2D cached = await TryLoadAsync(cachePath, options.MakeNoLongerReadable, null, cancellationToken); + if (cached != null) + return cached; + + if (sourceProvider == null) + return null; + + Texture source = await sourceProvider(); + if (source == null) + return null; + + try + { + return await CompressAndSaveAsync(source, cachePath, options, cancellationToken); + } + finally + { + if (destroySourceAfterCompress && source != null) + { + UnityEngine.Object.Destroy(source); + } + } + } + + private static Task WriteFileAtomicAsync(string path, byte[] data, CancellationToken cancellationToken) + { + return Task.Run(() => + { + cancellationToken.ThrowIfCancellationRequested(); + string dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir)) + { + Directory.CreateDirectory(dir); + } + + string tempPath = path + "." + Guid.NewGuid().ToString("N") + ".tmp"; + try + { + File.WriteAllBytes(tempPath, data); + if (File.Exists(path)) + { + File.Replace(tempPath, path, null); + } + else + { + try + { + File.Move(tempPath, path); + } + catch (IOException) when (File.Exists(path)) + { + // Another concurrent writer created the cache file first; replace atomically. + File.Replace(tempPath, path, null); + } + } + } + catch + { + if (File.Exists(tempPath)) + { + try { File.Delete(tempPath); } catch { } + } + throw; + } + }, cancellationToken); + } + } +} diff --git a/Assets/ASTC Encoder/Runtime/AstcDiskCache.cs.meta b/Assets/ASTC Encoder/Runtime/AstcDiskCache.cs.meta new file mode 100644 index 0000000..813884f --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/AstcDiskCache.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: e7c9a2b41f6348d5a3b0c4d6e8f19203 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/AstcHeader.cs b/Assets/ASTC Encoder/Runtime/AstcHeader.cs index 6e53e8c..41a6c23 100644 --- a/Assets/ASTC Encoder/Runtime/AstcHeader.cs +++ b/Assets/ASTC Encoder/Runtime/AstcHeader.cs @@ -1,63 +1,134 @@ -using System; -using System.Runtime.InteropServices; +using System; namespace Aperture.Astcenc.Runtime { public class AstcHeader : IDisposable { + public const int HeaderSize = 16; private const uint MAGIC_FILE_CONSTANT = 0x5CA1AB13; - internal IntPtr Data - { - get - { - return m_Data; - } - } - private IntPtr m_Data; - + private byte[] m_Bytes; private bool m_Disposed; + internal byte[] Bytes => m_Bytes; + public AstcHeader(byte[] data) { - m_Data = Marshal.AllocHGlobal(16); + if (data == null) + throw new ArgumentNullException(nameof(data)); + if (data.Length < HeaderSize) + throw new ArgumentException($"ASTC header requires at least {HeaderSize} bytes.", nameof(data)); - for(int i = 0; i < 16; i++) - { - Marshal.WriteByte(m_Data + i, data[i]); - } + m_Bytes = new byte[HeaderSize]; + Buffer.BlockCopy(data, 0, m_Bytes, 0, HeaderSize); m_Disposed = false; } public AstcHeader(uint dimX, uint dimY, uint dimZ, int sizeX, int sizeY, int sizeZ) { - m_Data = Marshal.AllocHGlobal(16); + m_Bytes = new byte[HeaderSize]; + WriteTo(m_Bytes, 0, dimX, dimY, dimZ, sizeX, sizeY, sizeZ); + m_Disposed = false; + } + + public static void WriteTo(byte[] buffer, int offset, uint dimX, uint dimY, uint dimZ, int sizeX, int sizeY, int sizeZ) + { + if (buffer == null) + throw new ArgumentNullException(nameof(buffer)); + if (offset < 0 || buffer.Length - offset < HeaderSize) + throw new ArgumentOutOfRangeException(nameof(offset)); + + buffer[offset + 0] = (byte)(MAGIC_FILE_CONSTANT & 0xFF); + buffer[offset + 1] = (byte)((MAGIC_FILE_CONSTANT >> 8) & 0xFF); + buffer[offset + 2] = (byte)((MAGIC_FILE_CONSTANT >> 16) & 0xFF); + buffer[offset + 3] = (byte)((MAGIC_FILE_CONSTANT >> 24) & 0xFF); + + buffer[offset + 4] = (byte)dimX; + buffer[offset + 5] = (byte)dimY; + buffer[offset + 6] = (byte)dimZ; + + buffer[offset + 7] = (byte)(sizeX & 0xFF); + buffer[offset + 8] = (byte)((sizeX >> 8) & 0xFF); + buffer[offset + 9] = (byte)((sizeX >> 16) & 0xFF); + + buffer[offset + 10] = (byte)(sizeY & 0xFF); + buffer[offset + 11] = (byte)((sizeY >> 8) & 0xFF); + buffer[offset + 12] = (byte)((sizeY >> 16) & 0xFF); + + buffer[offset + 13] = (byte)(sizeZ & 0xFF); + buffer[offset + 14] = (byte)((sizeZ >> 8) & 0xFF); + buffer[offset + 15] = (byte)((sizeZ >> 16) & 0xFF); + } + + /// + /// Parses a 16-byte standard .astc header from at . + /// Returns false if the buffer is too small, the magic constant does not match, or dimensions are zero. + /// + public static bool TryParse( + byte[] buffer, + int offset, + out uint dimX, + out uint dimY, + out uint dimZ, + out int sizeX, + out int sizeY, + out int sizeZ) + { + dimX = dimY = dimZ = 0; + sizeX = sizeY = sizeZ = 0; - Marshal.WriteByte(m_Data + 0, (byte)(MAGIC_FILE_CONSTANT & 0xFF)); - Marshal.WriteByte(m_Data + 1, (byte)((MAGIC_FILE_CONSTANT >> 8) & 0xFF)); - Marshal.WriteByte(m_Data + 2, (byte)((MAGIC_FILE_CONSTANT >> 16) & 0xFF)); - Marshal.WriteByte(m_Data + 3, (byte)((MAGIC_FILE_CONSTANT >> 24) & 0xFF)); + if (buffer == null || offset < 0 || buffer.Length - offset < HeaderSize) + return false; - Marshal.WriteByte(m_Data + 4, (byte)dimX); - Marshal.WriteByte(m_Data + 5, (byte)dimY); - Marshal.WriteByte(m_Data + 6, (byte)dimZ); + uint magic = (uint)buffer[offset + 0] + | ((uint)buffer[offset + 1] << 8) + | ((uint)buffer[offset + 2] << 16) + | ((uint)buffer[offset + 3] << 24); - Marshal.WriteByte(m_Data + 7, (byte)(sizeX & 0xFF)); - Marshal.WriteByte(m_Data + 8, (byte)((sizeX >> 8) & 0xFF)); - Marshal.WriteByte(m_Data + 9, (byte)((sizeX >> 16) & 0xFF)); + if (magic != MAGIC_FILE_CONSTANT) + return false; - Marshal.WriteByte(m_Data + 10, (byte)(sizeY & 0xFF)); - Marshal.WriteByte(m_Data + 11, (byte)((sizeY >> 8) & 0xFF)); - Marshal.WriteByte(m_Data + 12, (byte)((sizeY >> 16) & 0xFF)); + dimX = buffer[offset + 4]; + dimY = buffer[offset + 5]; + dimZ = buffer[offset + 6]; - Marshal.WriteByte(m_Data + 13, (byte)(sizeZ & 0xFF)); - Marshal.WriteByte(m_Data + 14, (byte)((sizeZ >> 8) & 0xFF)); - Marshal.WriteByte(m_Data + 15, (byte)((sizeZ >> 16) & 0xFF)); + sizeX = buffer[offset + 7] | (buffer[offset + 8] << 8) | (buffer[offset + 9] << 16); + sizeY = buffer[offset + 10] | (buffer[offset + 11] << 8) | (buffer[offset + 12] << 16); + sizeZ = buffer[offset + 13] | (buffer[offset + 14] << 8) | (buffer[offset + 15] << 16); + + return dimX > 0 && dimY > 0 && dimZ > 0 && sizeX > 0 && sizeY > 0 && sizeZ > 0; } - ~AstcHeader() + /// + /// Maps 2D ASTC block dimensions to the corresponding enum value. + /// + public static bool TryMapBlockSize(uint dimX, uint dimY, uint dimZ, out BlockSize blockSize) { - Dispose(false); + blockSize = BlockSize.ASTC_None; + if (dimZ != 1 || dimX != dimY) + return false; + + switch (dimX) + { + case 4: blockSize = BlockSize.ASTC_4x4; return true; + case 5: blockSize = BlockSize.ASTC_5x5; return true; + case 6: blockSize = BlockSize.ASTC_6x6; return true; + case 8: blockSize = BlockSize.ASTC_8x8; return true; + case 10: blockSize = BlockSize.ASTC_10x10; return true; + case 12: blockSize = BlockSize.ASTC_12x12; return true; + default: return false; + } + } + + public void CopyTo(byte[] destination, int destinationOffset = 0) + { + ThrowIfDisposed(); + if (destination == null) + throw new ArgumentNullException(nameof(destination)); + if (destinationOffset < 0 || destination.Length - destinationOffset < HeaderSize) + throw new ArgumentOutOfRangeException(nameof(destinationOffset)); + + Buffer.BlockCopy(m_Bytes, 0, destination, destinationOffset, HeaderSize); } public void ThrowIfDisposed() @@ -70,15 +141,7 @@ protected virtual void Dispose(bool disposing) { if (!m_Disposed) { - if (disposing) - { - - } - - if (m_Data != IntPtr.Zero) - Marshal.FreeHGlobal(m_Data); - - m_Data = IntPtr.Zero; + m_Bytes = null; m_Disposed = true; } } @@ -86,7 +149,6 @@ protected virtual void Dispose(bool disposing) public void Dispose() { Dispose(true); - GC.SuppressFinalize(this); } } } diff --git a/Assets/ASTC Encoder/Runtime/AstcKtxContainer.cs b/Assets/ASTC Encoder/Runtime/AstcKtxContainer.cs new file mode 100644 index 0000000..29d3fc2 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/AstcKtxContainer.cs @@ -0,0 +1,427 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using UnityEngine; +using UnityEngine.Experimental.Rendering; + +namespace Aperture.Astcenc.Runtime +{ + /// + /// Parsed metadata and raw ASTC payload extracted from a standard Khronos KTX v1 container. + /// + public readonly struct KtxAstcData + { + public readonly int Width; + public readonly int Height; + public readonly int MipCount; + public readonly BlockSize BlockSize; + public readonly GraphicsFormat GraphicsFormat; + public readonly byte[] RawAstcPayload; + + public KtxAstcData(int width, int height, int mipCount, BlockSize blockSize, GraphicsFormat graphicsFormat, byte[] rawAstcPayload) + { + Width = width; + Height = height; + MipCount = mipCount; + BlockSize = blockSize; + GraphicsFormat = graphicsFormat; + RawAstcPayload = rawAstcPayload; + } + } + + /// + /// Zero-dependency Khronos KTX v1 container encoder and decoder for runtime ASTC textures. + /// Supports full mipmap chains and preserves exact GraphicsFormat (LDR UNorm, LDR sRGB, and HDR UFloat). + /// + public static class AstcKtxContainer + { + private const int k_HeaderSize = 64; + private const int k_BytesPerBlock = 16; + private const uint k_Endianness = 0x04030201u; + private const uint k_GlRgba = 0x1908u; + + // Khronos GL_KHR_texture_compression_astc_ldr / hdr internal formats + private const uint k_GlAstc4x4Rgba = 0x93B0u; + private const uint k_GlAstc5x5Rgba = 0x93B2u; + private const uint k_GlAstc6x6Rgba = 0x93B4u; + private const uint k_GlAstc8x8Rgba = 0x93B7u; + private const uint k_GlAstc10x10Rgba = 0x93BBu; + private const uint k_GlAstc12x12Rgba = 0x93BDu; + + private const uint k_GlAstc4x4Srgb = 0x93D0u; + private const uint k_GlAstc5x5Srgb = 0x93D2u; + private const uint k_GlAstc6x6Srgb = 0x93D4u; + private const uint k_GlAstc8x8Srgb = 0x93D7u; + private const uint k_GlAstc10x10Srgb = 0x93DBu; + private const uint k_GlAstc12x12Srgb = 0x93DDu; + + private static readonly byte[] s_KtxIdentifier = + { + 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A + }; + + private static readonly byte[] s_HdrKvEntry = Encoding.ASCII.GetBytes("ASTC_PROFILE\0HDR\0"); + + /// + /// Encodes contiguous raw ASTC mipmap data () into a standard Khronos KTX v1 byte array. + /// + public static byte[] Encode(AstcRaw raw, int width, int height, int mipCount, GraphicsFormat astcFormat) + { + if (raw == null) + throw new ArgumentNullException(nameof(raw)); + raw.ThrowIfDisposed(); + + if (width <= 0 || height <= 0 || mipCount <= 0) + throw new ArgumentOutOfRangeException(nameof(width), "Width, height, and mipCount must be positive."); + + if (!TryMapGraphicsFormatToGl(astcFormat, out uint glInternalFormat, out BlockSize blockSize, out bool isHdr)) + throw new ArgumentException($"Unsupported ASTC GraphicsFormat for KTX v1: {astcFormat}", nameof(astcFormat)); + + if (!Encoder.GetBlockSize(blockSize, out uint bx, out uint by, out _)) + throw new ArgumentException($"Unsupported ASTC block size: {blockSize}"); + + int expectedPayloadBytes = 0; + for (int mip = 0; mip < mipCount; mip++) + { + int mipW = Math.Max(1, width >> mip); + int mipH = Math.Max(1, height >> mip); + int blocksX = (mipW + (int)bx - 1) / (int)bx; + int blocksY = (mipH + (int)by - 1) / (int)by; + expectedPayloadBytes += blocksX * blocksY * k_BytesPerBlock; + } + + if (raw.Length < expectedPayloadBytes) + throw new ArgumentException($"AstcRaw length ({raw.Length}) is smaller than required ({expectedPayloadBytes}) for {width}x{height} ({mipCount} mips)."); + + int kvBytes = 0; + if (isHdr) + { + int padded = (s_HdrKvEntry.Length + 3) & ~3; + kvBytes = 4 + padded; + } + + int totalSize = k_HeaderSize + kvBytes + mipCount * 4 + expectedPayloadBytes; + byte[] output = new byte[totalSize]; + + using (var ms = new MemoryStream(output, writable: true)) + using (var bw = new BinaryWriter(ms)) + { + bw.Write(s_KtxIdentifier); + bw.Write(k_Endianness); + bw.Write(0u); // glType = 0 (compressed) + bw.Write(1u); // glTypeSize = 1 + bw.Write(0u); // glFormat = 0 (compressed) + bw.Write(glInternalFormat); + bw.Write(k_GlRgba); + bw.Write((uint)width); + bw.Write((uint)height); + bw.Write(0u); // pixelDepth (2D) + bw.Write(0u); // numberOfArrayElements + bw.Write(1u); // numberOfFaces + bw.Write((uint)mipCount); + bw.Write((uint)kvBytes); + + if (isHdr) + { + bw.Write((uint)s_HdrKvEntry.Length); + bw.Write(s_HdrKvEntry); + int pad = ((s_HdrKvEntry.Length + 3) & ~3) - s_HdrKvEntry.Length; + for (int p = 0; p < pad; p++) bw.Write((byte)0); + } + + int srcOffset = 0; + for (int mip = 0; mip < mipCount; mip++) + { + int mipW = Math.Max(1, width >> mip); + int mipH = Math.Max(1, height >> mip); + int blocksX = (mipW + (int)bx - 1) / (int)bx; + int blocksY = (mipH + (int)by - 1) / (int)by; + int mipBytes = blocksX * blocksY * k_BytesPerBlock; + + bw.Write((uint)mipBytes); + int dstOffset = (int)ms.Position; + Marshal.Copy(raw.Data + srcOffset, output, dstOffset, mipBytes); + ms.Position = dstOffset + mipBytes; + srcOffset += mipBytes; + } + } + + return output; + } + + /// + /// Parses a Khronos KTX v1 byte array into contiguous ASTC mipmap data suitable for Unity's . + /// + public static bool TryDecode(byte[] ktxBytes, out KtxAstcData data) + { + data = default; + if (ktxBytes == null || ktxBytes.Length < k_HeaderSize) + return false; + + for (int i = 0; i < s_KtxIdentifier.Length; i++) + { + if (ktxBytes[i] != s_KtxIdentifier[i]) + return false; + } + + using (var ms = new MemoryStream(ktxBytes, writable: false)) + using (var br = new BinaryReader(ms)) + { + ms.Position = 12; + uint endianness = br.ReadUInt32(); + if (endianness != k_Endianness) + return false; + + uint glType = br.ReadUInt32(); + br.ReadUInt32(); // glTypeSize + uint glFormat = br.ReadUInt32(); + uint glInternalFormat = br.ReadUInt32(); + br.ReadUInt32(); // glBaseInternalFormat + uint pixelWidth = br.ReadUInt32(); + uint pixelHeight = br.ReadUInt32(); + uint pixelDepth = br.ReadUInt32(); + uint arrayElements = br.ReadUInt32(); + uint faces = br.ReadUInt32(); + uint mipLevels = br.ReadUInt32(); + uint kvBytes = br.ReadUInt32(); + + if (glType != 0 || glFormat != 0 || pixelWidth == 0 || pixelHeight == 0 || pixelWidth > 16384u || pixelHeight > 16384u || pixelDepth > 1 || arrayElements > 1 || faces != 1) + return false; + + int maxMips = AstcGpuBackend.CalculateFullMipCount((int)pixelWidth, (int)pixelHeight); + if (mipLevels > (uint)maxMips) + return false; + + int mipCount = (int)Math.Max(1u, mipLevels); + if (k_HeaderSize + (long)kvBytes > ktxBytes.Length) + return false; + + bool isHdr = false; + if (kvBytes > 0) + { + long kvEnd = k_HeaderSize + (long)kvBytes; + while (ms.Position + 4 <= kvEnd) + { + uint entryLen = br.ReadUInt32(); + if (ms.Position + (long)entryLen > kvEnd) + break; + + if (entryLen == (uint)s_HdrKvEntry.Length) + { + byte[] entry = br.ReadBytes((int)entryLen); + bool match = true; + for (int i = 0; i < s_HdrKvEntry.Length; i++) + { + if (entry[i] != s_HdrKvEntry[i]) + { + match = false; + break; + } + } + if (match) isHdr = true; + } + else + { + ms.Position += entryLen; + } + + long rem = (4 - (entryLen & 3)) & 3; + ms.Position = Math.Min(kvEnd, ms.Position + rem); + } + ms.Position = kvEnd; + } + + if (!TryMapGlToGraphicsFormat(glInternalFormat, isHdr, out BlockSize blockSize, out GraphicsFormat graphicsFormat)) + return false; + + if (!Encoder.GetBlockSize(blockSize, out uint bx, out uint by, out _)) + return false; + + long totalPayloadBytes = 0; + for (int mip = 0; mip < mipCount; mip++) + { + int mipW = Math.Max(1, (int)pixelWidth >> mip); + int mipH = Math.Max(1, (int)pixelHeight >> mip); + long blocksX = (mipW + (long)bx - 1L) / (long)bx; + long blocksY = (mipH + (long)by - 1L) / (long)by; + totalPayloadBytes += blocksX * blocksY * k_BytesPerBlock; + } + + if (totalPayloadBytes <= 0 || totalPayloadBytes > ktxBytes.Length - ms.Position) + return false; + + byte[] payload = new byte[(int)totalPayloadBytes]; + int dstOffset = 0; + for (int mip = 0; mip < mipCount; mip++) + { + if (ms.Position + 4 > ktxBytes.Length) + return false; + + uint imageSize = br.ReadUInt32(); + int mipW = Math.Max(1, (int)pixelWidth >> mip); + int mipH = Math.Max(1, (int)pixelHeight >> mip); + int expectedMipBytes = ((mipW + (int)bx - 1) / (int)bx) * ((mipH + (int)by - 1) / (int)by) * k_BytesPerBlock; + + if (imageSize < (uint)expectedMipBytes || ms.Position + (long)imageSize > ktxBytes.Length) + return false; + + Buffer.BlockCopy(ktxBytes, (int)ms.Position, payload, dstOffset, expectedMipBytes); + dstOffset += expectedMipBytes; + ms.Position += imageSize; + + long pad = (4 - (imageSize & 3)) & 3; + if (ms.Position + pad <= ktxBytes.Length) + ms.Position += pad; + } + + data = new KtxAstcData((int)pixelWidth, (int)pixelHeight, mipCount, blockSize, graphicsFormat, payload); + return true; + } + } + + /// + /// Decodes a KTX v1 byte array directly into a GPU-ready ASTC (with full mipmaps). + /// On devices without hardware ASTC sampling, falls back to CPU software decompression of mip 0 when available. + /// + public static Texture2D LoadTexture(byte[] ktxBytes, bool makeNoLongerReadable = true, string textureName = null) + { + if (!TryDecode(ktxBytes, out KtxAstcData data)) + { + Debug.LogError("Failed to decode KTX v1 ASTC container."); + return null; + } + + if (Encoder.CanCreateAstcTexture(data.GraphicsFormat)) + { + TextureCreationFlags flags = data.MipCount > 1 ? TextureCreationFlags.MipChain : TextureCreationFlags.None; + var tex = new Texture2D(data.Width, data.Height, data.GraphicsFormat, data.MipCount, flags); + try + { + if (!string.IsNullOrEmpty(textureName)) + tex.name = textureName; + tex.LoadRawTextureData(data.RawAstcPayload); + tex.Apply(false, makeNoLongerReadable); + return tex; + } + catch + { + UnityEngine.Object.DestroyImmediate(tex); + throw; + } + } + + // Fallback on non-ASTC platforms: software-decompress mip 0 via native CPU library. + if (!Encoder.GetBlockSize(data.BlockSize, out uint bx, out uint by, out _)) + return null; + + int mip0Bytes = ((data.Width + (int)bx - 1) / (int)bx) * ((data.Height + (int)by - 1) / (int)by) * k_BytesPerBlock; + if (mip0Bytes > data.RawAstcPayload.Length) + return null; + + bool srgb = GraphicsFormatUtility.IsSRGBFormat(data.GraphicsFormat); + bool isHdr = AstcGpuBackend.IsFloatingPointFormat(data.GraphicsFormat); + byte[] rgba = AstcCpuBackend.DecompressToBytes(data.RawAstcPayload, 0, mip0Bytes, data.Width, data.Height, data.BlockSize, srgb, isHdr, isHdr ? 16 : 8); + if (rgba == null) + return null; + + GraphicsFormat dstFmt = isHdr + ? GraphicsFormat.R16G16B16A16_SFloat + : (srgb ? GraphicsFormat.R8G8B8A8_SRGB : GraphicsFormat.R8G8B8A8_UNorm); + var fallback = new Texture2D(data.Width, data.Height, dstFmt, TextureCreationFlags.None); + try + { + if (!string.IsNullOrEmpty(textureName)) + fallback.name = textureName; + fallback.LoadRawTextureData(rgba); + fallback.Apply(false, makeNoLongerReadable); + return fallback; + } + catch + { + UnityEngine.Object.DestroyImmediate(fallback); + throw; + } + } + + internal static int InferMipCount(int payloadBytes, int width, int height, BlockSize blockSize) + { + if (payloadBytes <= 0 || width <= 0 || height <= 0 || !Encoder.GetBlockSize(blockSize, out uint bx, out uint by, out _)) + return 0; + + int maxMips = AstcGpuBackend.CalculateFullMipCount(width, height); + int total = 0; + for (int mip = 0; mip < maxMips; mip++) + { + int mipW = Math.Max(1, width >> mip); + int mipH = Math.Max(1, height >> mip); + int blocksX = (mipW + (int)bx - 1) / (int)bx; + int blocksY = (mipH + (int)by - 1) / (int)by; + total += blocksX * blocksY * k_BytesPerBlock; + if (total == payloadBytes) + return mip + 1; + if (total > payloadBytes) + return mip; + } + return maxMips; + } + + private static bool TryMapGraphicsFormatToGl(GraphicsFormat format, out uint glInternal, out BlockSize blockSize, out bool isHdr) + { + isHdr = false; + switch (format) + { + case GraphicsFormat.RGBA_ASTC4X4_UNorm: glInternal = k_GlAstc4x4Rgba; blockSize = BlockSize.ASTC_4x4; return true; + case GraphicsFormat.RGBA_ASTC5X5_UNorm: glInternal = k_GlAstc5x5Rgba; blockSize = BlockSize.ASTC_5x5; return true; + case GraphicsFormat.RGBA_ASTC6X6_UNorm: glInternal = k_GlAstc6x6Rgba; blockSize = BlockSize.ASTC_6x6; return true; + case GraphicsFormat.RGBA_ASTC8X8_UNorm: glInternal = k_GlAstc8x8Rgba; blockSize = BlockSize.ASTC_8x8; return true; + case GraphicsFormat.RGBA_ASTC10X10_UNorm: glInternal = k_GlAstc10x10Rgba; blockSize = BlockSize.ASTC_10x10; return true; + case GraphicsFormat.RGBA_ASTC12X12_UNorm: glInternal = k_GlAstc12x12Rgba; blockSize = BlockSize.ASTC_12x12; return true; + + case GraphicsFormat.RGBA_ASTC4X4_SRGB: glInternal = k_GlAstc4x4Srgb; blockSize = BlockSize.ASTC_4x4; return true; + case GraphicsFormat.RGBA_ASTC5X5_SRGB: glInternal = k_GlAstc5x5Srgb; blockSize = BlockSize.ASTC_5x5; return true; + case GraphicsFormat.RGBA_ASTC6X6_SRGB: glInternal = k_GlAstc6x6Srgb; blockSize = BlockSize.ASTC_6x6; return true; + case GraphicsFormat.RGBA_ASTC8X8_SRGB: glInternal = k_GlAstc8x8Srgb; blockSize = BlockSize.ASTC_8x8; return true; + case GraphicsFormat.RGBA_ASTC10X10_SRGB: glInternal = k_GlAstc10x10Srgb; blockSize = BlockSize.ASTC_10x10; return true; + case GraphicsFormat.RGBA_ASTC12X12_SRGB: glInternal = k_GlAstc12x12Srgb; blockSize = BlockSize.ASTC_12x12; return true; + + case GraphicsFormat.RGBA_ASTC4X4_UFloat: glInternal = k_GlAstc4x4Rgba; blockSize = BlockSize.ASTC_4x4; isHdr = true; return true; + case GraphicsFormat.RGBA_ASTC5X5_UFloat: glInternal = k_GlAstc5x5Rgba; blockSize = BlockSize.ASTC_5x5; isHdr = true; return true; + case GraphicsFormat.RGBA_ASTC6X6_UFloat: glInternal = k_GlAstc6x6Rgba; blockSize = BlockSize.ASTC_6x6; isHdr = true; return true; + case GraphicsFormat.RGBA_ASTC8X8_UFloat: glInternal = k_GlAstc8x8Rgba; blockSize = BlockSize.ASTC_8x8; isHdr = true; return true; + case GraphicsFormat.RGBA_ASTC10X10_UFloat: glInternal = k_GlAstc10x10Rgba; blockSize = BlockSize.ASTC_10x10; isHdr = true; return true; + case GraphicsFormat.RGBA_ASTC12X12_UFloat: glInternal = k_GlAstc12x12Rgba; blockSize = BlockSize.ASTC_12x12; isHdr = true; return true; + + default: + glInternal = 0; + blockSize = BlockSize.ASTC_None; + return false; + } + } + + private static bool TryMapGlToGraphicsFormat(uint glInternal, bool isHdr, out BlockSize blockSize, out GraphicsFormat format) + { + switch (glInternal) + { + case k_GlAstc4x4Rgba: blockSize = BlockSize.ASTC_4x4; format = isHdr ? GraphicsFormat.RGBA_ASTC4X4_UFloat : GraphicsFormat.RGBA_ASTC4X4_UNorm; return true; + case k_GlAstc5x5Rgba: blockSize = BlockSize.ASTC_5x5; format = isHdr ? GraphicsFormat.RGBA_ASTC5X5_UFloat : GraphicsFormat.RGBA_ASTC5X5_UNorm; return true; + case k_GlAstc6x6Rgba: blockSize = BlockSize.ASTC_6x6; format = isHdr ? GraphicsFormat.RGBA_ASTC6X6_UFloat : GraphicsFormat.RGBA_ASTC6X6_UNorm; return true; + case k_GlAstc8x8Rgba: blockSize = BlockSize.ASTC_8x8; format = isHdr ? GraphicsFormat.RGBA_ASTC8X8_UFloat : GraphicsFormat.RGBA_ASTC8X8_UNorm; return true; + case k_GlAstc10x10Rgba: blockSize = BlockSize.ASTC_10x10; format = isHdr ? GraphicsFormat.RGBA_ASTC10X10_UFloat : GraphicsFormat.RGBA_ASTC10X10_UNorm; return true; + case k_GlAstc12x12Rgba: blockSize = BlockSize.ASTC_12x12; format = isHdr ? GraphicsFormat.RGBA_ASTC12X12_UFloat : GraphicsFormat.RGBA_ASTC12X12_UNorm; return true; + + case k_GlAstc4x4Srgb: blockSize = BlockSize.ASTC_4x4; format = GraphicsFormat.RGBA_ASTC4X4_SRGB; return true; + case k_GlAstc5x5Srgb: blockSize = BlockSize.ASTC_5x5; format = GraphicsFormat.RGBA_ASTC5X5_SRGB; return true; + case k_GlAstc6x6Srgb: blockSize = BlockSize.ASTC_6x6; format = GraphicsFormat.RGBA_ASTC6X6_SRGB; return true; + case k_GlAstc8x8Srgb: blockSize = BlockSize.ASTC_8x8; format = GraphicsFormat.RGBA_ASTC8X8_SRGB; return true; + case k_GlAstc10x10Srgb: blockSize = BlockSize.ASTC_10x10; format = GraphicsFormat.RGBA_ASTC10X10_SRGB; return true; + case k_GlAstc12x12Srgb: blockSize = BlockSize.ASTC_12x12; format = GraphicsFormat.RGBA_ASTC12X12_SRGB; return true; + + default: + blockSize = BlockSize.ASTC_None; + format = GraphicsFormat.None; + return false; + } + } + } +} diff --git a/Assets/ASTC Encoder/Runtime/AstcKtxContainer.cs.meta b/Assets/ASTC Encoder/Runtime/AstcKtxContainer.cs.meta new file mode 100644 index 0000000..51b51bd --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/AstcKtxContainer.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: d4b8f1a39c524e67b2a9d1e3f5c7a802 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/AstcRaw.cs b/Assets/ASTC Encoder/Runtime/AstcRaw.cs index 0174b04..4456fac 100644 --- a/Assets/ASTC Encoder/Runtime/AstcRaw.cs +++ b/Assets/ASTC Encoder/Runtime/AstcRaw.cs @@ -1,5 +1,6 @@ -using System; +using System; using System.Runtime.InteropServices; +using System.Threading; namespace Aperture.Astcenc.Runtime { @@ -14,7 +15,7 @@ internal IntPtr Data } private IntPtr m_Data; - internal int Length + public int Length { get { @@ -23,13 +24,20 @@ internal int Length } private int m_Length; - private bool m_Disposed; + public bool IsDisposed + { + get + { + return Volatile.Read(ref m_Disposed) != 0; + } + } + private int m_Disposed; public AstcRaw(IntPtr data, int length) { m_Data = data; m_Length = length; - m_Disposed = false; + m_Disposed = 0; } ~AstcRaw() @@ -39,26 +47,48 @@ public AstcRaw(IntPtr data, int length) public void ThrowIfDisposed() { - if (m_Disposed) + if (IsDisposed) throw new ObjectDisposedException(GetType().FullName); } + public void CopyTo(byte[] destination, int destinationOffset = 0) + { + ThrowIfDisposed(); + if (destination == null) + throw new ArgumentNullException(nameof(destination)); + if (destinationOffset < 0 || destination.Length - destinationOffset < m_Length) + throw new ArgumentOutOfRangeException(nameof(destinationOffset)); + + IntPtr data = m_Data; + if (m_Length > 0 && data != IntPtr.Zero) + { + Marshal.Copy(data, destination, destinationOffset, m_Length); + } + } + + public byte[] ToArray() + { + ThrowIfDisposed(); + byte[] result = new byte[m_Length]; + IntPtr data = m_Data; + if (m_Length > 0 && data != IntPtr.Zero) + { + Marshal.Copy(data, result, 0, m_Length); + } + return result; + } + protected virtual void Dispose(bool disposing) { - if (!m_Disposed) + if (Interlocked.Exchange(ref m_Disposed, 1) == 0) { - if (disposing) + IntPtr data = Interlocked.Exchange(ref m_Data, IntPtr.Zero); + if (data != IntPtr.Zero) { - + Marshal.FreeHGlobal(data); } - if (m_Data != IntPtr.Zero) - Marshal.FreeHGlobal(m_Data); - - m_Data = IntPtr.Zero; m_Length = 0; - - m_Disposed = true; } } diff --git a/Assets/ASTC Encoder/Runtime/CodecFlags.cs b/Assets/ASTC Encoder/Runtime/CodecFlags.cs index ed31721..c243053 100644 --- a/Assets/ASTC Encoder/Runtime/CodecFlags.cs +++ b/Assets/ASTC Encoder/Runtime/CodecFlags.cs @@ -1,4 +1,4 @@ -using System; +using System; namespace Aperture.Astcenc.Runtime { @@ -15,6 +15,14 @@ public enum CodecFlags : uint * used by BC5n). */ MapNormal = 1 << 0, + /** + * @brief Enable compression heuristics that assume use of decode_unorm8 decode mode. + * + * The decode_unorm8 decode mode rounds differently to the decode_fp16 decode mode, so enabling this + * flag during compression will allow the compressor to use the correct rounding when selecting + * encodings. + */ + UseDecodeUnorm8 = 1 << 1, /** * @brief Enable alpha weighting. * diff --git a/Assets/ASTC Encoder/Runtime/Cpu.meta b/Assets/ASTC Encoder/Runtime/Cpu.meta new file mode 100644 index 0000000..33f46d8 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Cpu.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4e8f3c12a9d64b7e8123c5f09e7a1b34 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/Cpu/AstcContextPool.cs b/Assets/ASTC Encoder/Runtime/Cpu/AstcContextPool.cs new file mode 100644 index 0000000..1d6bd6e --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Cpu/AstcContextPool.cs @@ -0,0 +1,336 @@ +using System; +using System.Collections.Generic; +using UnityEngine; +using UnityEngine.Experimental.Rendering; + +namespace Aperture.Astcenc.Runtime +{ + /// + /// Thread-safe static pool of reusable native instances (both compressor and decompressor) + /// with astcenc 5.x parentContext read-only lookup-table sharing and safe deferred disposal. + /// Eliminates repeated astcenc_context_alloc / free overhead across all static CPU Encoder entry points. + /// + internal static class AstcContextPool + { + private const int k_MaxCachedPerKey = 4; + + internal readonly struct CompressorKey : IEquatable + { + public readonly GraphicsFormat Format; + public readonly TextureType TextureType; + public readonly BlockSize BlockSize; + public readonly CompressQuality Quality; + public readonly int ThreadCount; + public readonly bool UseAlphaWeight; + public readonly bool UsePerceptual; + public readonly uint AlphaScaleRadius; + + public CompressorKey( + GraphicsFormat format, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + int threadCount, + bool useAlphaWeight, + bool usePerceptual, + uint alphaScaleRadius) + { + Format = format; + TextureType = textureType; + BlockSize = blockSize; + Quality = quality; + ThreadCount = threadCount; + UseAlphaWeight = useAlphaWeight; + UsePerceptual = usePerceptual; + AlphaScaleRadius = alphaScaleRadius; + } + + public bool Equals(CompressorKey other) => + Format == other.Format && + TextureType == other.TextureType && + BlockSize == other.BlockSize && + Quality == other.Quality && + ThreadCount == other.ThreadCount && + UseAlphaWeight == other.UseAlphaWeight && + UsePerceptual == other.UsePerceptual && + AlphaScaleRadius == other.AlphaScaleRadius; + + public override bool Equals(object obj) => obj is CompressorKey other && Equals(other); + + public override int GetHashCode() + { + unchecked + { + int h = (int)Format; + h = (h * 397) ^ (int)TextureType; + h = (h * 397) ^ (int)BlockSize; + h = (h * 397) ^ (int)Quality; + h = (h * 397) ^ ThreadCount; + h = (h * 397) ^ (UseAlphaWeight ? 1 : 0); + h = (h * 397) ^ (UsePerceptual ? 1 : 0); + h = (h * 397) ^ (int)AlphaScaleRadius; + return h; + } + } + } + + internal readonly struct DecompressorKey : IEquatable + { + public readonly BlockSize BlockSize; + public readonly bool Srgb; + public readonly bool IsHdr; + public readonly int ThreadCount; + + public DecompressorKey(BlockSize blockSize, bool srgb, bool isHdr, int threadCount) + { + BlockSize = blockSize; + Srgb = srgb; + IsHdr = isHdr; + ThreadCount = threadCount; + } + + public bool Equals(DecompressorKey other) => + BlockSize == other.BlockSize && + Srgb == other.Srgb && + IsHdr == other.IsHdr && + ThreadCount == other.ThreadCount; + + public override bool Equals(object obj) => obj is DecompressorKey other && Equals(other); + + public override int GetHashCode() + { + unchecked + { + int h = (int)BlockSize; + h = (h * 397) ^ (Srgb ? 1 : 0); + h = (h * 397) ^ (IsHdr ? 1 : 0); + h = (h * 397) ^ ThreadCount; + return h; + } + } + } + + internal struct CompressorLease : IDisposable + { + private CompressorKey m_Key; + private AstcContext m_Context; + private int m_Generation; + + public AstcContext Context => m_Context; + + internal CompressorLease(CompressorKey key, AstcContext context, int generation) + { + m_Key = key; + m_Context = context; + m_Generation = generation; + } + + public void Dispose() + { + AstcContext ctx = m_Context; + m_Context = null; + if (ctx != null) + { + ReturnCompressor(m_Key, ctx, m_Generation); + } + } + } + + internal struct DecompressorLease : IDisposable + { + private DecompressorKey m_Key; + private AstcContext m_Context; + private int m_Generation; + + public AstcContext Context => m_Context; + + internal DecompressorLease(DecompressorKey key, AstcContext context, int generation) + { + m_Key = key; + m_Context = context; + m_Generation = generation; + } + + public void Dispose() + { + AstcContext ctx = m_Context; + m_Context = null; + if (ctx != null) + { + ReturnDecompressor(m_Key, ctx, m_Generation); + } + } + } + + private static readonly object s_Lock = new object(); + private static readonly Dictionary> s_Compressors = new Dictionary>(); + private static readonly Dictionary> s_Decompressors = new Dictionary>(); + private static readonly Dictionary s_Parents = new Dictionary(); + private static readonly List s_RetiredParents = new List(); + private static int s_Generation; + private static int s_InFlightCompressors; + + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] + private static void ResetStatics() + { + ReleaseAll(); + Application.quitting -= ReleaseAll; + Application.quitting += ReleaseAll; + } + + internal static CompressorLease RentCompressor( + GraphicsFormat format, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + int threadCount, + bool useAlphaWeight, + bool usePerceptual, + uint alphaScaleRadius, + bool useUnityJobSystem = false) + { + var key = new CompressorKey(format, textureType, blockSize, quality, threadCount, useAlphaWeight, usePerceptual, alphaScaleRadius); + var parentKey = new CompressorKey(format, textureType, blockSize, quality, 1, useAlphaWeight, usePerceptual, alphaScaleRadius); + lock (s_Lock) + { + int gen = s_Generation; + if (s_Compressors.TryGetValue(key, out Stack stack) && stack.Count > 0) + { + AstcContext pooled = stack.Pop(); + pooled.UseUnityJobSystem = useUnityJobSystem; + s_InFlightCompressors++; + return new CompressorLease(key, pooled, gen); + } + + if (!s_Parents.TryGetValue(parentKey, out AstcContext parent)) + { + parent = AstcContext.Create(format, textureType, blockSize, quality, 1, useAlphaWeight, usePerceptual, alphaScaleRadius); + if (parent != null) + s_Parents[parentKey] = parent; + } + + AstcContext created = AstcContext.Create( + format, + textureType, + blockSize, + quality, + threadCount, + useAlphaWeight, + usePerceptual, + alphaScaleRadius, + parent, + useUnityJobSystem); + if (created != null) + s_InFlightCompressors++; + return new CompressorLease(key, created, gen); + } + } + + internal static DecompressorLease RentDecompressor(BlockSize blockSize, bool srgb, bool isHdr, int threadCount) + { + var key = new DecompressorKey(blockSize, srgb, isHdr, threadCount); + lock (s_Lock) + { + int gen = s_Generation; + if (s_Decompressors.TryGetValue(key, out Stack stack) && stack.Count > 0) + { + return new DecompressorLease(key, stack.Pop(), gen); + } + + AstcContext created = AstcContext.CreateDecompressor(blockSize, srgb, isHdr, threadCount); + return new DecompressorLease(key, created, gen); + } + } + + private static void ReturnCompressor(CompressorKey key, AstcContext ctx, int generation) + { + lock (s_Lock) + { + s_InFlightCompressors = Math.Max(0, s_InFlightCompressors - 1); + + if (generation != s_Generation) + { + ctx.Dispose(); + if (s_InFlightCompressors == 0 && s_RetiredParents.Count > 0) + { + for (int i = 0; i < s_RetiredParents.Count; i++) + s_RetiredParents[i].Dispose(); + s_RetiredParents.Clear(); + } + return; + } + + if (!s_Compressors.TryGetValue(key, out Stack stack)) + { + stack = new Stack(); + s_Compressors[key] = stack; + } + + if (stack.Count < k_MaxCachedPerKey) + stack.Push(ctx); + else + ctx.Dispose(); + } + } + + private static void ReturnDecompressor(DecompressorKey key, AstcContext ctx, int generation) + { + lock (s_Lock) + { + if (generation != s_Generation) + { + ctx.Dispose(); + return; + } + + if (!s_Decompressors.TryGetValue(key, out Stack stack)) + { + stack = new Stack(); + s_Decompressors[key] = stack; + } + + if (stack.Count < k_MaxCachedPerKey) + stack.Push(ctx); + else + ctx.Dispose(); + } + } + + internal static void ReleaseAll() + { + lock (s_Lock) + { + s_Generation++; + + foreach (var stack in s_Compressors.Values) + { + while (stack.Count > 0) + stack.Pop().Dispose(); + } + s_Compressors.Clear(); + + foreach (var stack in s_Decompressors.Values) + { + while (stack.Count > 0) + stack.Pop().Dispose(); + } + s_Decompressors.Clear(); + + if (s_InFlightCompressors == 0) + { + foreach (var p in s_Parents.Values) + p.Dispose(); + for (int i = 0; i < s_RetiredParents.Count; i++) + s_RetiredParents[i].Dispose(); + s_RetiredParents.Clear(); + } + else + { + foreach (var p in s_Parents.Values) + s_RetiredParents.Add(p); + } + s_Parents.Clear(); + } + } + } +} diff --git a/Assets/ASTC Encoder/Runtime/Cpu/AstcContextPool.cs.meta b/Assets/ASTC Encoder/Runtime/Cpu/AstcContextPool.cs.meta new file mode 100644 index 0000000..0821133 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Cpu/AstcContextPool.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4a9c2e71f3b84d65a0e1b8c4d9f2367e +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/Cpu/AstcCpuBackend.cs b/Assets/ASTC Encoder/Runtime/Cpu/AstcCpuBackend.cs new file mode 100644 index 0000000..58d10ba --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Cpu/AstcCpuBackend.cs @@ -0,0 +1,1488 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; +using UnityEngine; +using UnityEngine.Experimental.Rendering; +using Aperture.Astcenc.Runtime.NativeAPI; + +namespace Aperture.Astcenc.Runtime +{ + /// + /// Native CPU ASTC compression backend powered by ARM astc-encoder (P/Invoke). + /// Supports single-threaded, multi-threaded, and async compression with reusable AstcContext. + /// + internal static class AstcCpuBackend + { + private const int k_BytePerBlock = 16; + + internal static bool IsSupported => astcenc_api.IsNativeLibraryAvailable; + + internal static bool IsSupportGraphicFormat(GraphicsFormat graphicsFormat) + { + switch (graphicsFormat) + { + // LDR + case GraphicsFormat.R8_UNorm: + case GraphicsFormat.R8_SRGB: + case GraphicsFormat.R8G8_UNorm: + case GraphicsFormat.R8G8_SRGB: + case GraphicsFormat.R8G8B8_UNorm: + case GraphicsFormat.R8G8B8_SRGB: + case GraphicsFormat.R8G8B8A8_UNorm: + case GraphicsFormat.R8G8B8A8_SRGB: + + case GraphicsFormat.B8G8R8_UNorm: + case GraphicsFormat.B8G8R8_SRGB: + case GraphicsFormat.B8G8R8A8_UNorm: + case GraphicsFormat.B8G8R8A8_SRGB: + + case GraphicsFormat.R16_UNorm: + case GraphicsFormat.R16G16_UNorm: + case GraphicsFormat.R16G16B16_UNorm: + case GraphicsFormat.R16G16B16A16_UNorm: + + // HDR + case GraphicsFormat.R16_SFloat: + case GraphicsFormat.R16G16_SFloat: + case GraphicsFormat.R16G16B16_SFloat: + case GraphicsFormat.R16G16B16A16_SFloat: + + case GraphicsFormat.R32_SFloat: + case GraphicsFormat.R32G32_SFloat: + case GraphicsFormat.R32G32B32_SFloat: + case GraphicsFormat.R32G32B32A32_SFloat: + return true; + } + return false; + } + + internal static bool IsInputSupported(Texture texture) + { + return texture is Texture2D && texture.isReadable && IsSupportGraphicFormat(texture.graphicsFormat); + } + + internal static float GetQualityValue(CompressQuality quality) + { + return quality switch + { + CompressQuality.Fastest => 0.0f, + CompressQuality.Fast => 10.0f, + CompressQuality.Medium => 60.0f, + CompressQuality.Thorough => 98.0f, + CompressQuality.VeryThorough => 99.0f, + CompressQuality.Exhaustive => 100.0f, + _ => throw new ArgumentException("Unknown type of a CompressQuality:", nameof(quality)), + }; + } + + internal static astcenc_profile GetColorProfile(GraphicsFormat graphicsFormat, TextureType textureType = TextureType.Default) + { + astcenc_profile profile = graphicsFormat switch + { + // LDR + GraphicsFormat.R8_UNorm => astcenc_profile.ASTCENC_PRF_LDR, + GraphicsFormat.R8_SRGB => astcenc_profile.ASTCENC_PRF_LDR_SRGB, + GraphicsFormat.R8G8_UNorm => astcenc_profile.ASTCENC_PRF_LDR, + GraphicsFormat.R8G8_SRGB => astcenc_profile.ASTCENC_PRF_LDR_SRGB, + GraphicsFormat.R8G8B8_UNorm => astcenc_profile.ASTCENC_PRF_LDR, + GraphicsFormat.R8G8B8_SRGB => astcenc_profile.ASTCENC_PRF_LDR_SRGB, + GraphicsFormat.R8G8B8A8_UNorm => astcenc_profile.ASTCENC_PRF_LDR, + GraphicsFormat.R8G8B8A8_SRGB => astcenc_profile.ASTCENC_PRF_LDR_SRGB, + GraphicsFormat.B8G8R8_UNorm => astcenc_profile.ASTCENC_PRF_LDR, + GraphicsFormat.B8G8R8_SRGB => astcenc_profile.ASTCENC_PRF_LDR_SRGB, + GraphicsFormat.B8G8R8A8_UNorm => astcenc_profile.ASTCENC_PRF_LDR, + GraphicsFormat.B8G8R8A8_SRGB => astcenc_profile.ASTCENC_PRF_LDR_SRGB, + + GraphicsFormat.R16_UNorm => astcenc_profile.ASTCENC_PRF_LDR, + GraphicsFormat.R16G16_UNorm => astcenc_profile.ASTCENC_PRF_LDR, + GraphicsFormat.R16G16B16_UNorm => astcenc_profile.ASTCENC_PRF_LDR, + GraphicsFormat.R16G16B16A16_UNorm => astcenc_profile.ASTCENC_PRF_LDR, + + // HDR + GraphicsFormat.R16_SFloat => astcenc_profile.ASTCENC_PRF_HDR, + GraphicsFormat.R16G16_SFloat => astcenc_profile.ASTCENC_PRF_HDR, + GraphicsFormat.R16G16B16_SFloat => astcenc_profile.ASTCENC_PRF_HDR, + GraphicsFormat.R16G16B16A16_SFloat => astcenc_profile.ASTCENC_PRF_HDR, + + GraphicsFormat.R32_SFloat => astcenc_profile.ASTCENC_PRF_HDR, + GraphicsFormat.R32G32_SFloat => astcenc_profile.ASTCENC_PRF_HDR, + GraphicsFormat.R32G32B32_SFloat => astcenc_profile.ASTCENC_PRF_HDR, + GraphicsFormat.R32G32B32A32_SFloat => astcenc_profile.ASTCENC_PRF_HDR, + _ => throw new NotSupportedException($"GraphicsFormat is not supported: {graphicsFormat}"), + }; + + if (textureType == TextureType.Normal) + { + // Tangent-space normal maps are always encoded as LDR linear regardless of sRGB or float source format. + return astcenc_profile.ASTCENC_PRF_LDR; + } + + return profile; + } + + private static bool HasAlphaChannel(GraphicsFormat graphicsFormat) + { + switch (graphicsFormat) + { + case GraphicsFormat.R8G8B8A8_UNorm: + case GraphicsFormat.R8G8B8A8_SRGB: + case GraphicsFormat.B8G8R8A8_UNorm: + case GraphicsFormat.B8G8R8A8_SRGB: + case GraphicsFormat.R16G16B16A16_UNorm: + case GraphicsFormat.R16G16B16A16_SFloat: + case GraphicsFormat.R32G32B32A32_SFloat: + return true; + default: + return false; + } + } + + internal static CodecFlags GetFlags(TextureType textureType, GraphicsFormat graphicsFormat, bool useAlphaWeight = false, bool usePerceptual = false) + { + if (textureType == TextureType.Normal) + { + return CodecFlags.MapNormal | CodecFlags.SelfDecompressOnly; + } + + CodecFlags flags = CodecFlags.SelfDecompressOnly; + + if (useAlphaWeight && HasAlphaChannel(graphicsFormat)) + { + flags |= CodecFlags.UseAlphaWeight; + } + + if (usePerceptual) + { + flags |= CodecFlags.UsePerceptual; + } + + return flags; + } + + private static bool IsBgrFormat(GraphicsFormat graphicsFormat) + { + switch (graphicsFormat) + { + case GraphicsFormat.B8G8R8_UNorm: + case GraphicsFormat.B8G8R8_SRGB: + case GraphicsFormat.B8G8R8A8_UNorm: + case GraphicsFormat.B8G8R8A8_SRGB: + return true; + default: + return false; + } + } + + private static astcenc_swizzle GetSwizzle(GraphicsFormat graphicsFormat, TextureType textureType) + { + bool isBgr = IsBgrFormat(graphicsFormat); + + if (textureType == TextureType.Normal) + { + return new astcenc_swizzle + { + r = astcenc_swz.ASTCENC_SWZ_G, + g = astcenc_swz.ASTCENC_SWZ_G, + b = astcenc_swz.ASTCENC_SWZ_G, + a = isBgr ? astcenc_swz.ASTCENC_SWZ_B : astcenc_swz.ASTCENC_SWZ_R, + }; + } + + if (isBgr) + { + return new astcenc_swizzle + { + r = astcenc_swz.ASTCENC_SWZ_B, + g = astcenc_swz.ASTCENC_SWZ_G, + b = astcenc_swz.ASTCENC_SWZ_R, + a = astcenc_swz.ASTCENC_SWZ_A, + }; + } + + return new astcenc_swizzle + { + r = astcenc_swz.ASTCENC_SWZ_R, + g = astcenc_swz.ASTCENC_SWZ_G, + b = astcenc_swz.ASTCENC_SWZ_B, + a = astcenc_swz.ASTCENC_SWZ_A, + }; + } + + private static int CalculateMipByteLength(int mipWidth, int mipHeight, uint blockX, uint blockY) + { + int blockCountX = (mipWidth + (int)blockX - 1) / (int)blockX; + int blockCountY = (mipHeight + (int)blockY - 1) / (int)blockY; + return blockCountX * blockCountY * k_BytePerBlock; + } + + private static bool CompressRawData(AstcContext context, astcenc_swizzle swizzle, NativeArray raw, int width, int height, int bitness, int mipCount, bool direct4Channel, out IntPtr output, out int size) where T : unmanaged, IRawData + { + uint blockX = context.BlockX; + uint blockY = context.BlockY; + + // Allocate total memory to hold all mipmaps + int total = 0; + for (int i = 0; i < mipCount; i++) + { + int mipmapWidth = Math.Max(1, width >> i); + int mipmapHeight = Math.Max(1, height >> i); + total += CalculateMipByteLength(mipmapWidth, mipmapHeight, blockX, blockY); + } + output = Marshal.AllocHGlobal(total); + size = total; + + int elementsRead = 0; + int bytesWritten = 0; + + try + { + for (int i = 0; i < mipCount; i++) + { + int mipmapWidth = Math.Max(1, width >> i); + int mipmapHeight = Math.Max(1, height >> i); + int length = CalculateMipByteLength(mipmapWidth, mipmapHeight, blockX, blockY); + + int count = mipmapWidth * mipmapHeight; + NativeSlice mipmapSlice = raw.Slice(elementsRead, count); + + astcenc_image image = new astcenc_image(); + try + { + if (direct4Channel) + { + image.LoadFromDirect(mipmapSlice, mipmapWidth, mipmapHeight, bitness); + } + else + { + image.LoadFrom(mipmapSlice, mipmapWidth, mipmapHeight, bitness); + } + + astcenc_error status = context.CompressSingleImage(ref image, ref swizzle, output + bytesWritten, length); + if (status != astcenc_error.ASTCENC_SUCCESS) + { + throw new Exception(status.ToString()); + } + } + finally + { + image.Release(ownsSliceMemory: !direct4Channel); + } + + elementsRead += count; + bytesWritten += length; + } + } + catch (Exception ex) + { + Debug.LogError("ASTC compress failed: " + ex.Message); + Marshal.FreeHGlobal(output); + + output = IntPtr.Zero; + size = 0; + + return false; + } + return true; + } + + /// + /// Compact raw pixel snapshot copied via a single memcpy on the main thread. + /// Format expansion to 4-channel RGBA happens lazily one mip at a time on the worker thread, + /// avoiding main-thread conversion stalls and reducing peak memory by up to 8x. + /// + private sealed class CompactTextureSnapshot : IDisposable + { + public IntPtr Buffer; + public GraphicsFormat Format; + public int Width; + public int Height; + public int MipCount; + + public void Dispose() + { + IntPtr ptr = Interlocked.Exchange(ref Buffer, IntPtr.Zero); + if (ptr != IntPtr.Zero) + { + Marshal.FreeHGlobal(ptr); + } + } + } + + private static int GetSourcePixelByteSize(GraphicsFormat format) + { + switch (format) + { + case GraphicsFormat.R8_UNorm: + case GraphicsFormat.R8_SRGB: + return 1; + case GraphicsFormat.R8G8_UNorm: + case GraphicsFormat.R8G8_SRGB: + case GraphicsFormat.R16_UNorm: + case GraphicsFormat.R16_SFloat: + return 2; + case GraphicsFormat.R8G8B8_UNorm: + case GraphicsFormat.R8G8B8_SRGB: + case GraphicsFormat.B8G8R8_UNorm: + case GraphicsFormat.B8G8R8_SRGB: + return 3; + case GraphicsFormat.R8G8B8A8_UNorm: + case GraphicsFormat.R8G8B8A8_SRGB: + case GraphicsFormat.B8G8R8A8_UNorm: + case GraphicsFormat.B8G8R8A8_SRGB: + case GraphicsFormat.R16G16_UNorm: + case GraphicsFormat.R16G16_SFloat: + case GraphicsFormat.R32_SFloat: + return 4; + case GraphicsFormat.R16G16B16_UNorm: + case GraphicsFormat.R16G16B16_SFloat: + return 6; + case GraphicsFormat.R16G16B16A16_UNorm: + case GraphicsFormat.R16G16B16A16_SFloat: + case GraphicsFormat.R32G32_SFloat: + return 8; + case GraphicsFormat.R32G32B32_SFloat: + return 12; + case GraphicsFormat.R32G32B32A32_SFloat: + return 16; + default: + return 0; + } + } + + private static unsafe CompactTextureSnapshot CaptureCompactSnapshot(Texture2D inputTexture, int mipCount) + { + GraphicsFormat format = inputTexture.graphicsFormat; + int pixelBytes = GetSourcePixelByteSize(format); + if (pixelBytes <= 0) + return null; + + int width = inputTexture.width; + int height = inputTexture.height; + long totalBytes = 0; + for (int i = 0; i < mipCount; i++) + { + int mipW = Math.Max(1, width >> i); + int mipH = Math.Max(1, height >> i); + totalBytes += (long)mipW * mipH * pixelBytes; + } + + NativeArray rawBytes = inputTexture.GetRawTextureData(); + if (totalBytes <= 0 || totalBytes > rawBytes.Length) + { + throw new InvalidOperationException($"Texture raw data length ({rawBytes.Length}) is smaller than required ({totalBytes})."); + } + + IntPtr buffer = Marshal.AllocHGlobal((IntPtr)totalBytes); + try + { + UnsafeUtility.MemCpy((void*)buffer, NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(rawBytes), totalBytes); + return new CompactTextureSnapshot + { + Buffer = buffer, + Format = format, + Width = width, + Height = height, + MipCount = mipCount, + }; + } + catch + { + Marshal.FreeHGlobal(buffer); + throw; + } + } + + private static unsafe AstcRaw CompressCompactTyped( + AstcContext context, + astcenc_swizzle swizzle, + CompactTextureSnapshot snapshot, + int bitness, + bool direct4Channel, + CancellationToken cancellationToken) where T : unmanaged, IRawData + { + uint blockX = context.BlockX; + uint blockY = context.BlockY; + int width = snapshot.Width; + int height = snapshot.Height; + int mipCount = snapshot.MipCount; + + int total = 0; + for (int i = 0; i < mipCount; i++) + { + int mipW = Math.Max(1, width >> i); + int mipH = Math.Max(1, height >> i); + total += CalculateMipByteLength(mipW, mipH, blockX, blockY); + } + + IntPtr output = Marshal.AllocHGlobal(total); + long elementsRead = 0; + int bytesWritten = 0; + T* basePtr = (T*)snapshot.Buffer; + + try + { + for (int i = 0; i < mipCount; i++) + { + cancellationToken.ThrowIfCancellationRequested(); + + int mipW = Math.Max(1, width >> i); + int mipH = Math.Max(1, height >> i); + int length = CalculateMipByteLength(mipW, mipH, blockX, blockY); + int count = mipW * mipH; + T* mipPtr = basePtr + elementsRead; + + astcenc_image image = new astcenc_image(); + try + { + if (direct4Channel) + { + image.LoadFromDirectPtr(mipPtr, mipW, mipH, bitness); + } + else + { + image.LoadFromPtr(mipPtr, mipW, mipH, bitness); + } + + astcenc_error status = context.CompressSingleImage(ref image, ref swizzle, output + bytesWritten, length, cancellationToken); + if (status != astcenc_error.ASTCENC_SUCCESS) + { + throw new Exception(status.ToString()); + } + } + finally + { + image.Release(ownsSliceMemory: !direct4Channel); + } + + elementsRead += count; + bytesWritten += length; + } + + return new AstcRaw(output, total); + } + catch (OperationCanceledException) + { + Marshal.FreeHGlobal(output); + throw; + } + catch (Exception ex) + { + Debug.LogError("ASTC async compress failed: " + ex.Message); + Marshal.FreeHGlobal(output); + return null; + } + } + + private static AstcRaw CompressCompactSnapshot(AstcContext context, astcenc_swizzle swizzle, CompactTextureSnapshot snapshot, CancellationToken cancellationToken) + { + switch (snapshot.Format) + { + case GraphicsFormat.R8_UNorm: + case GraphicsFormat.R8_SRGB: + return CompressCompactTyped(context, swizzle, snapshot, 8, false, cancellationToken); + case GraphicsFormat.R8G8_UNorm: + case GraphicsFormat.R8G8_SRGB: + return CompressCompactTyped(context, swizzle, snapshot, 8, false, cancellationToken); + case GraphicsFormat.R8G8B8_UNorm: + case GraphicsFormat.R8G8B8_SRGB: + case GraphicsFormat.B8G8R8_UNorm: + case GraphicsFormat.B8G8R8_SRGB: + return CompressCompactTyped(context, swizzle, snapshot, 8, false, cancellationToken); + case GraphicsFormat.R8G8B8A8_UNorm: + case GraphicsFormat.R8G8B8A8_SRGB: + case GraphicsFormat.B8G8R8A8_UNorm: + case GraphicsFormat.B8G8R8A8_SRGB: + return CompressCompactTyped(context, swizzle, snapshot, 8, true, cancellationToken); + case GraphicsFormat.R16_UNorm: + return CompressCompactTyped(context, swizzle, snapshot, 32, false, cancellationToken); + case GraphicsFormat.R16G16_UNorm: + return CompressCompactTyped(context, swizzle, snapshot, 32, false, cancellationToken); + case GraphicsFormat.R16G16B16_UNorm: + return CompressCompactTyped(context, swizzle, snapshot, 32, false, cancellationToken); + case GraphicsFormat.R16G16B16A16_UNorm: + return CompressCompactTyped(context, swizzle, snapshot, 32, false, cancellationToken); + case GraphicsFormat.R16_SFloat: + return CompressCompactTyped(context, swizzle, snapshot, 16, false, cancellationToken); + case GraphicsFormat.R16G16_SFloat: + return CompressCompactTyped(context, swizzle, snapshot, 16, false, cancellationToken); + case GraphicsFormat.R16G16B16_SFloat: + return CompressCompactTyped(context, swizzle, snapshot, 16, false, cancellationToken); + case GraphicsFormat.R16G16B16A16_SFloat: + return CompressCompactTyped(context, swizzle, snapshot, 16, true, cancellationToken); + case GraphicsFormat.R32_SFloat: + return CompressCompactTyped(context, swizzle, snapshot, 32, false, cancellationToken); + case GraphicsFormat.R32G32_SFloat: + return CompressCompactTyped(context, swizzle, snapshot, 32, false, cancellationToken); + case GraphicsFormat.R32G32B32_SFloat: + return CompressCompactTyped(context, swizzle, snapshot, 32, false, cancellationToken); + case GraphicsFormat.R32G32B32A32_SFloat: + return CompressCompactTyped(context, swizzle, snapshot, 32, true, cancellationToken); + default: + return null; + } + } + + private static bool CompressImage(Texture2D inputTexture, AstcContext context, astcenc_swizzle swizzle, int mipCount, out IntPtr output, out int size) + { + int width = inputTexture.width; + int height = inputTexture.height; + switch (inputTexture.graphicsFormat) + { + case GraphicsFormat.R8_UNorm: + case GraphicsFormat.R8_SRGB: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 8, mipCount, false, out output, out size); + } + case GraphicsFormat.R8G8_UNorm: + case GraphicsFormat.R8G8_SRGB: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 8, mipCount, false, out output, out size); + } + case GraphicsFormat.R8G8B8_UNorm: + case GraphicsFormat.R8G8B8_SRGB: + case GraphicsFormat.B8G8R8_UNorm: + case GraphicsFormat.B8G8R8_SRGB: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 8, mipCount, false, out output, out size); + } + case GraphicsFormat.R8G8B8A8_UNorm: + case GraphicsFormat.R8G8B8A8_SRGB: + case GraphicsFormat.B8G8R8A8_UNorm: + case GraphicsFormat.B8G8R8A8_SRGB: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 8, mipCount, true, out output, out size); + } + case GraphicsFormat.R16_UNorm: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 32, mipCount, false, out output, out size); + } + case GraphicsFormat.R16G16_UNorm: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 32, mipCount, false, out output, out size); + } + case GraphicsFormat.R16G16B16_UNorm: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 32, mipCount, false, out output, out size); + } + case GraphicsFormat.R16G16B16A16_UNorm: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 32, mipCount, false, out output, out size); + } + case GraphicsFormat.R16_SFloat: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 16, mipCount, false, out output, out size); + } + case GraphicsFormat.R16G16_SFloat: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 16, mipCount, false, out output, out size); + } + case GraphicsFormat.R16G16B16_SFloat: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 16, mipCount, false, out output, out size); + } + case GraphicsFormat.R16G16B16A16_SFloat: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 16, mipCount, true, out output, out size); + } + case GraphicsFormat.R32_SFloat: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 32, mipCount, false, out output, out size); + } + case GraphicsFormat.R32G32_SFloat: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 32, mipCount, false, out output, out size); + } + case GraphicsFormat.R32G32B32_SFloat: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 32, mipCount, false, out output, out size); + } + case GraphicsFormat.R32G32B32A32_SFloat: + { + NativeArray raw = inputTexture.GetRawTextureData(); + return CompressRawData(context, swizzle, raw, width, height, 32, mipCount, true, out output, out size); + } + } + + output = IntPtr.Zero; + size = 0; + + return false; + } + + internal static AstcRaw CompressTextureWithContext(Texture2D inputTexture, AstcContext context, TextureType textureType, bool includeMipmaps) + { + if (!IsSupported) + { + Debug.LogError("Native CPU ASTC compression library is not available on this platform."); + return null; + } + + if (!IsInputSupported(inputTexture)) + { + Debug.LogError("Texture format is not support or read/write is disabled."); + return null; + } + + if (context == null) + { + Debug.LogError("AstcContext is null."); + return null; + } + + context.ThrowIfDisposed(); + + if (!context.IsCompatibleWith(inputTexture.graphicsFormat, textureType)) + { + Debug.LogError("AstcContext profile or flags do not match the input texture format and type."); + return null; + } + + astcenc_swizzle swizzle = GetSwizzle(inputTexture.graphicsFormat, textureType); + int mipCount = includeMipmaps ? inputTexture.mipmapCount : 1; + + bool success = CompressImage(inputTexture, context, swizzle, mipCount, out IntPtr output, out int size); + if (!success || output == IntPtr.Zero || size <= 0) + { + if (output != IntPtr.Zero) + { + Marshal.FreeHGlobal(output); + } + return null; + } + + return new AstcRaw(output, size); + } + + internal static Task CompressTextureWithContextAsync(Texture2D inputTexture, AstcContext context, TextureType textureType, bool includeMipmaps, CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) + { + return Task.FromCanceled(cancellationToken); + } + + if (!IsSupported) + { + Debug.LogError("Native CPU ASTC compression library is not available on this platform."); + return Task.FromResult(null); + } + + if (!IsInputSupported(inputTexture)) + { + Debug.LogError("Texture format is not support or read/write is disabled."); + return Task.FromResult(null); + } + + if (context == null) + { + Debug.LogError("AstcContext is null."); + return Task.FromResult(null); + } + + context.ThrowIfDisposed(); + + if (!context.IsCompatibleWith(inputTexture.graphicsFormat, textureType)) + { + Debug.LogError("AstcContext profile or flags do not match the input texture format and type."); + return Task.FromResult(null); + } + + astcenc_swizzle swizzle = GetSwizzle(inputTexture.graphicsFormat, textureType); + int mipCount = includeMipmaps ? inputTexture.mipmapCount : 1; + + CompactTextureSnapshot snapshot; + try + { + snapshot = CaptureCompactSnapshot(inputTexture, mipCount); + } + catch (Exception ex) + { + Debug.LogError("Failed to snapshot texture mipmaps for async compression: " + ex.Message); + return Task.FromResult(null); + } + + if (snapshot == null) + { + return Task.FromResult(null); + } + + return Task.Run(() => + { + using (snapshot) + { + cancellationToken.ThrowIfCancellationRequested(); + return CompressCompactSnapshot(context, swizzle, snapshot, cancellationToken); + } + }); + } + + internal static AstcRaw CompressTextureSync( + Texture2D inputTexture, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + int threadCount = 1, + bool includeMipmaps = true, + bool useAlphaWeight = false, + bool usePerceptual = false, + uint alphaScaleRadius = 1u, + bool useUnityJobSystem = false) + { + if (!IsSupported) + { + Debug.LogError("Native CPU ASTC compression library is not available on this platform."); + return null; + } + + if (!IsInputSupported(inputTexture)) + { + Debug.LogError("Texture format is not support or read/write is disabled."); + return null; + } + + using AstcContextPool.CompressorLease lease = AstcContextPool.RentCompressor( + inputTexture.graphicsFormat, + textureType, + blockSize, + quality, + threadCount, + useAlphaWeight, + usePerceptual, + alphaScaleRadius, + useUnityJobSystem); + if (lease.Context == null) + { + return null; + } + + return CompressTextureWithContext(inputTexture, lease.Context, textureType, includeMipmaps); + } + + internal static Task CompressTextureAsync( + Texture2D inputTexture, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + int threadCount = 0, + bool includeMipmaps = true, + bool useAlphaWeight = false, + CancellationToken cancellationToken = default, + bool usePerceptual = false, + uint alphaScaleRadius = 1u) + { + if (cancellationToken.IsCancellationRequested) + { + return Task.FromCanceled(cancellationToken); + } + + if (!IsSupported) + { + Debug.LogError("Native CPU ASTC compression library is not available on this platform."); + return Task.FromResult(null); + } + + if (!IsInputSupported(inputTexture)) + { + Debug.LogError("Texture format is not support or read/write is disabled."); + return Task.FromResult(null); + } + + if (!Encoder.GetBlockSize(blockSize, out _, out _, out _)) + { + Debug.LogError("Unsupported ASTC block size: " + blockSize); + return Task.FromResult(null); + } + + GraphicsFormat graphicsFormat = inputTexture.graphicsFormat; + astcenc_swizzle swizzle = GetSwizzle(graphicsFormat, textureType); + int mipCount = includeMipmaps ? inputTexture.mipmapCount : 1; + + CompactTextureSnapshot snapshot; + try + { + snapshot = CaptureCompactSnapshot(inputTexture, mipCount); + } + catch (Exception ex) + { + Debug.LogError("Failed to snapshot texture mipmaps for async compression: " + ex.Message); + return Task.FromResult(null); + } + + if (snapshot == null) + { + return Task.FromResult(null); + } + + return Task.Run(() => + { + using (snapshot) + { + cancellationToken.ThrowIfCancellationRequested(); + using AstcContextPool.CompressorLease lease = AstcContextPool.RentCompressor( + graphicsFormat, + textureType, + blockSize, + quality, + threadCount, + useAlphaWeight, + usePerceptual, + alphaScaleRadius); + if (lease.Context == null) + { + return null; + } + + return CompressCompactSnapshot(lease.Context, swizzle, snapshot, cancellationToken); + } + }); + } + + internal static Texture2D CompressToTexture( + Texture2D inputTexture, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + bool includeMipmaps = true, + bool useAlphaWeight = false, + int threadCount = 0, + bool usePerceptual = false, + uint alphaScaleRadius = 1u, + bool useUnityJobSystem = false) + { + if (!IsSupported) + { + Debug.LogError("Native CPU ASTC compression library is not available on this platform."); + return null; + } + + if (!IsInputSupported(inputTexture)) + { + Debug.LogError("Texture format is not support or read/write is disabled."); + return null; + } + + GraphicsFormat astcFormat = Encoder.FitAstcGraphicsFormat(inputTexture.graphicsFormat, blockSize, textureType); + if (!Encoder.CanCreateAstcTexture(astcFormat)) + { + Debug.LogError($"ASTC texture format '{astcFormat}' is not supported on this device. Use CompressTexture or EncodeToASTC for raw ASTC data."); + return null; + } + + using AstcRaw raw = CompressTextureSync( + inputTexture, + textureType, + blockSize, + quality, + threadCount: threadCount, + includeMipmaps: includeMipmaps, + useAlphaWeight: useAlphaWeight, + usePerceptual: usePerceptual, + alphaScaleRadius: alphaScaleRadius, + useUnityJobSystem: useUnityJobSystem); + if (raw == null) + { + return null; + } + + int mipCount = includeMipmaps ? inputTexture.mipmapCount : 1; + TextureCreationFlags flags = mipCount > 1 ? TextureCreationFlags.MipChain : TextureCreationFlags.None; + var result = new Texture2D(inputTexture.width, inputTexture.height, astcFormat, mipCount, flags); + try + { + result.name = inputTexture.name; + result.LoadRawTextureData(raw); + result.Apply(false, true); + return result; + } + catch + { + UnityEngine.Object.DestroyImmediate(result); + throw; + } + } + + internal static async Task CompressToTextureAsync( + Texture2D inputTexture, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + bool includeMipmaps = true, + bool useAlphaWeight = false, + int threadCount = 0, + bool usePerceptual = false, + uint alphaScaleRadius = 1u, + CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(cancellationToken); + } + + if (!IsSupported) + { + Debug.LogError("Native CPU ASTC compression library is not available on this platform."); + return null; + } + + if (!IsInputSupported(inputTexture)) + { + Debug.LogError("Texture format is not support or read/write is disabled."); + return null; + } + + GraphicsFormat astcFormat = Encoder.FitAstcGraphicsFormat(inputTexture.graphicsFormat, blockSize, textureType); + if (!Encoder.CanCreateAstcTexture(astcFormat)) + { + Debug.LogError($"ASTC texture format '{astcFormat}' is not supported on this device. Use CompressTextureAsync or EncodeToASTCAsync for raw ASTC data."); + return null; + } + + int width = inputTexture.width; + int height = inputTexture.height; + int mipCount = includeMipmaps ? Math.Max(1, inputTexture.mipmapCount) : 1; + string texName = inputTexture.name; + + using AstcRaw raw = await CompressTextureAsync( + inputTexture, + textureType, + blockSize, + quality, + threadCount: threadCount, + includeMipmaps: includeMipmaps, + useAlphaWeight: useAlphaWeight, + cancellationToken: cancellationToken, + usePerceptual: usePerceptual, + alphaScaleRadius: alphaScaleRadius); + if (raw == null) + { + return null; + } + + cancellationToken.ThrowIfCancellationRequested(); + + TextureCreationFlags flags = mipCount > 1 ? TextureCreationFlags.MipChain : TextureCreationFlags.None; + var result = new Texture2D(width, height, astcFormat, mipCount, flags); + try + { + result.name = texName; + result.LoadRawTextureData(raw); + result.Apply(false, true); + return result; + } + catch + { + UnityEngine.Object.DestroyImmediate(result); + throw; + } + } + + internal static bool CompressInPlace( + Texture2D inputTexture, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + bool makeNoLongerReadable = true, + int threadCount = 1, + bool useAlphaWeight = false, + bool usePerceptual = false, + uint alphaScaleRadius = 1u, + bool useUnityJobSystem = false) + { + if (!IsSupported) + { + Debug.LogError("Native CPU ASTC compression library is not available on this platform."); + return false; + } + + if (!IsInputSupported(inputTexture)) + { + Debug.LogError("Texture format is not support or read/write is disabled."); + return false; + } + + GraphicsFormat graphicsFormat = Encoder.FitAstcGraphicsFormat(inputTexture.graphicsFormat, blockSize, textureType); + if (!Encoder.CanCreateAstcTexture(graphicsFormat)) + { + Debug.LogError($"ASTC texture format '{graphicsFormat}' is not supported on this device. Use CompressTexture or EncodeToASTC for raw ASTC data."); + return false; + } + + int mipCount = Math.Max(1, inputTexture.mipmapCount); + if (!Encoder.IsFullMipChain(inputTexture.width, inputTexture.height, mipCount)) + { + Debug.LogError($"In-place Compress does not support partial mipmap chains (mipmapCount={mipCount} for {inputTexture.width}x{inputTexture.height}) because Texture2D.Reinitialize allocates a full mipmap chain. Use CompressToTexture instead."); + return false; + } + + using AstcRaw raw = CompressTextureSync( + inputTexture, + textureType, + blockSize, + quality, + threadCount: threadCount, + includeMipmaps: true, + useAlphaWeight: useAlphaWeight, + usePerceptual: usePerceptual, + alphaScaleRadius: alphaScaleRadius, + useUnityJobSystem: useUnityJobSystem); + if (raw == null) + { + return false; + } + + raw.ThrowIfDisposed(); + + if (inputTexture.Reinitialize(inputTexture.width, inputTexture.height, graphicsFormat, inputTexture.mipmapCount > 1)) + { + inputTexture.LoadRawTextureData(raw); + inputTexture.Apply(false, makeNoLongerReadable); + return true; + } + + return false; + } + + internal static byte[] DecompressToBytes( + IntPtr compressedData, + int compressedLength, + int width, + int height, + BlockSize blockSize, + bool srgb, + bool isHdr, + int outputBitness, + int threadCount = 1) + { + if (!IsSupported) + { + Debug.LogError("Native CPU ASTC library is not available on this platform."); + return null; + } + + if (compressedData == IntPtr.Zero || compressedLength <= 0 || width <= 0 || height <= 0 || width > 16384 || height > 16384) + { + Debug.LogError("Invalid ASTC decompression input arguments."); + return null; + } + + if (outputBitness != 8 && outputBitness != 16 && outputBitness != 32) + { + Debug.LogError($"Unsupported ASTC decompression outputBitness: {outputBitness}. Expected 8, 16, or 32."); + return null; + } + + if (!Encoder.GetBlockSize(blockSize, out uint bx, out uint by, out _)) + { + Debug.LogError("Unsupported ASTC block size: " + blockSize); + return null; + } + + long requiredBytesLong = ((width + (long)bx - 1L) / (long)bx) * ((height + (long)by - 1L) / (long)by) * k_BytePerBlock; + if (requiredBytesLong <= 0 || requiredBytesLong > int.MaxValue || compressedLength < requiredBytesLong) + { + Debug.LogError($"Compressed ASTC buffer ({compressedLength} bytes) is smaller than required ({requiredBytesLong} bytes) for {width}x{height} {blockSize}."); + return null; + } + int requiredBytes = (int)requiredBytesLong; + + using AstcContextPool.DecompressorLease lease = AstcContextPool.RentDecompressor(blockSize, srgb, isHdr, threadCount); + if (lease.Context == null) + return null; + + astcenc_swizzle swizzle = new astcenc_swizzle + { + r = astcenc_swz.ASTCENC_SWZ_R, + g = astcenc_swz.ASTCENC_SWZ_G, + b = astcenc_swz.ASTCENC_SWZ_B, + a = astcenc_swz.ASTCENC_SWZ_A, + }; + + astcenc_image imageOut = new astcenc_image(); + try + { + imageOut.AllocateOutput(width, height, outputBitness, out IntPtr slicePtr, out int byteCount); + astcenc_error status = lease.Context.DecompressSingleImage(compressedData, requiredBytes, ref imageOut, ref swizzle); + if (status != astcenc_error.ASTCENC_SUCCESS) + { + Debug.LogError("ASTC decompress failed: " + status); + return null; + } + + byte[] result = new byte[byteCount]; + Marshal.Copy(slicePtr, result, 0, byteCount); + return result; + } + finally + { + imageOut.Release(ownsSliceMemory: true); + } + } + + internal static unsafe byte[] DecompressToBytes( + byte[] compressedBytes, + int offset, + int length, + int width, + int height, + BlockSize blockSize, + bool srgb, + bool isHdr, + int outputBitness, + int threadCount = 1) + { + if (compressedBytes == null || offset < 0 || length <= 0 || offset + length > compressedBytes.Length) + { + Debug.LogError("Invalid compressed byte array range."); + return null; + } + + fixed (byte* ptr = &compressedBytes[offset]) + { + return DecompressToBytes((IntPtr)ptr, length, width, height, blockSize, srgb, isHdr, outputBitness, threadCount); + } + } + + internal static Texture2D DecompressToTexture( + IntPtr compressedData, + int compressedLength, + int width, + int height, + BlockSize blockSize, + bool srgb, + bool isHdr, + int threadCount = 1, + bool makeNoLongerReadable = false) + { + int bitness = isHdr ? 16 : 8; + byte[] pixels = DecompressToBytes(compressedData, compressedLength, width, height, blockSize, srgb, isHdr, bitness, threadCount); + if (pixels == null) + return null; + + GraphicsFormat dstFormat = isHdr + ? GraphicsFormat.R16G16B16A16_SFloat + : (srgb ? GraphicsFormat.R8G8B8A8_SRGB : GraphicsFormat.R8G8B8A8_UNorm); + + var tex = new Texture2D(width, height, dstFormat, TextureCreationFlags.None); + try + { + tex.LoadRawTextureData(pixels); + tex.Apply(false, makeNoLongerReadable); + return tex; + } + catch + { + UnityEngine.Object.DestroyImmediate(tex); + throw; + } + } + + internal static unsafe Texture2D DecompressAstcFileToTexture( + byte[] astcFileBytes, + bool srgb = false, + bool isHdr = false, + int threadCount = 1, + bool makeNoLongerReadable = false) + { + if (!AstcHeader.TryParse(astcFileBytes, 0, out uint dimX, out uint dimY, out uint dimZ, out int width, out int height, out int depth)) + { + Debug.LogError("Invalid .astc file header."); + return null; + } + + if (depth != 1 || !AstcHeader.TryMapBlockSize(dimX, dimY, dimZ, out BlockSize blockSize)) + { + Debug.LogError($"Unsupported .astc block or texture dimensions: block={dimX}x{dimY}x{dimZ}, size={width}x{height}x{depth}."); + return null; + } + + int payloadLen = astcFileBytes.Length - AstcHeader.HeaderSize; + if (payloadLen <= 0) + { + Debug.LogError(".astc file contains no payload data."); + return null; + } + + fixed (byte* ptr = &astcFileBytes[AstcHeader.HeaderSize]) + { + return DecompressToTexture((IntPtr)ptr, payloadLen, width, height, blockSize, srgb, isHdr, threadCount, makeNoLongerReadable); + } + } + + internal static unsafe AstcRaw CompressRawPixels( + IntPtr pixelPtr, + int pixelByteLength, + int width, + int height, + GraphicsFormat sourceFormat, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + int threadCount, + bool useAlphaWeight, + bool usePerceptual, + uint alphaScaleRadius, + bool useUnityJobSystem = false) + { + if (!IsSupported) + { + Debug.LogError("Native CPU ASTC compression library is not available on this platform."); + return null; + } + + if (pixelPtr == IntPtr.Zero || width <= 0 || height <= 0) + { + Debug.LogError("Invalid raw pixel buffer or dimensions."); + return null; + } + + int bpp = GetSourcePixelByteSize(sourceFormat); + if (bpp <= 0 || !IsSupportGraphicFormat(sourceFormat)) + { + Debug.LogError($"Unsupported GraphicsFormat for raw pixel ASTC compression: {sourceFormat}"); + return null; + } + + long requiredBytes = (long)width * height * bpp; + if (pixelByteLength < requiredBytes) + { + Debug.LogError($"Raw pixel buffer ({pixelByteLength} bytes) is smaller than required ({requiredBytes} bytes) for {width}x{height} {sourceFormat}."); + return null; + } + + using AstcContextPool.CompressorLease lease = AstcContextPool.RentCompressor(sourceFormat, textureType, blockSize, quality, threadCount, useAlphaWeight, usePerceptual, alphaScaleRadius, useUnityJobSystem); + if (lease.Context == null) + return null; + + var snapshot = new CompactTextureSnapshot + { + Buffer = pixelPtr, + Format = sourceFormat, + Width = width, + Height = height, + MipCount = 1, + }; + + astcenc_swizzle swizzle = GetSwizzle(sourceFormat, textureType); + return CompressCompactSnapshot(lease.Context, swizzle, snapshot, CancellationToken.None); + } + + internal static unsafe Task CompressRawPixelsAsync( + IntPtr pixelPtr, + int pixelByteLength, + int width, + int height, + GraphicsFormat sourceFormat, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + int threadCount, + bool useAlphaWeight, + bool usePerceptual, + uint alphaScaleRadius, + CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) + return Task.FromCanceled(cancellationToken); + + if (!IsSupported) + { + Debug.LogError("Native CPU ASTC compression library is not available on this platform."); + return Task.FromResult(null); + } + + if (pixelPtr == IntPtr.Zero || width <= 0 || height <= 0) + { + Debug.LogError("Invalid raw pixel buffer or dimensions."); + return Task.FromResult(null); + } + + int bpp = GetSourcePixelByteSize(sourceFormat); + if (bpp <= 0 || !IsSupportGraphicFormat(sourceFormat)) + { + Debug.LogError($"Unsupported GraphicsFormat for raw pixel ASTC compression: {sourceFormat}"); + return Task.FromResult(null); + } + + long requiredBytes = (long)width * height * bpp; + if (requiredBytes <= 0 || requiredBytes > int.MaxValue || pixelByteLength < requiredBytes) + { + Debug.LogError($"Raw pixel buffer ({pixelByteLength} bytes) is invalid or smaller than required ({requiredBytes} bytes) for {width}x{height} {sourceFormat}."); + return Task.FromResult(null); + } + + // Copy caller-owned pixels once so the background task is safe even if the caller frees/reuses its buffer. + IntPtr copy = Marshal.AllocHGlobal((int)requiredBytes); + try + { + UnsafeUtility.MemCpy((void*)copy, (void*)pixelPtr, requiredBytes); + } + catch + { + Marshal.FreeHGlobal(copy); + throw; + } + + var snapshot = new CompactTextureSnapshot + { + Buffer = copy, + Format = sourceFormat, + Width = width, + Height = height, + MipCount = 1, + }; + + return Task.Run(() => + { + using (snapshot) + { + cancellationToken.ThrowIfCancellationRequested(); + using AstcContextPool.CompressorLease lease = AstcContextPool.RentCompressor(sourceFormat, textureType, blockSize, quality, threadCount, useAlphaWeight, usePerceptual, alphaScaleRadius); + if (lease.Context == null) + return null; + astcenc_swizzle swizzle = GetSwizzle(sourceFormat, textureType); + return CompressCompactSnapshot(lease.Context, swizzle, snapshot, cancellationToken); + } + }, cancellationToken); + } + + internal static unsafe bool CompressRawPixelsInto( + IntPtr pixelPtr, + int pixelByteLength, + IntPtr destPtr, + int destCapacity, + int width, + int height, + GraphicsFormat sourceFormat, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + int threadCount, + bool useAlphaWeight, + bool usePerceptual, + uint alphaScaleRadius, + bool useUnityJobSystem, + out int bytesWritten) + { + bytesWritten = 0; + if (!IsSupported || pixelPtr == IntPtr.Zero || destPtr == IntPtr.Zero || width <= 0 || height <= 0) + return false; + + int bpp = GetSourcePixelByteSize(sourceFormat); + if (bpp <= 0 || !IsSupportGraphicFormat(sourceFormat)) + return false; + + long requiredSrcBytes = (long)width * height * bpp; + if (requiredSrcBytes <= 0 || pixelByteLength < requiredSrcBytes) + return false; + + if (!Encoder.GetBlockSize(blockSize, out uint bx, out uint by, out _)) + return false; + + long expectedOutBytes = ((width + (long)bx - 1L) / (long)bx) * ((height + (long)by - 1L) / (long)by) * k_BytePerBlock; + if (expectedOutBytes <= 0 || expectedOutBytes > destCapacity) + return false; + + using AstcContextPool.CompressorLease lease = AstcContextPool.RentCompressor(sourceFormat, textureType, blockSize, quality, threadCount, useAlphaWeight, usePerceptual, alphaScaleRadius, useUnityJobSystem); + if (lease.Context == null) + return false; + + astcenc_swizzle swizzle = GetSwizzle(sourceFormat, textureType); + int bitness = GetBitness(sourceFormat); + bool direct4Channel = IsDirect4ChannelFormat(sourceFormat); + + if (!direct4Channel) + { + // Reuse the already-leased context directly without allocating a second AstcContext. + var snapshot = new CompactTextureSnapshot + { + Buffer = pixelPtr, + Format = sourceFormat, + Width = width, + Height = height, + MipCount = 1, + }; + using AstcRaw tmp = CompressCompactSnapshot(lease.Context, swizzle, snapshot, CancellationToken.None); + if (tmp == null || tmp.Length > destCapacity) + return false; + UnsafeUtility.MemCpy((void*)destPtr, (void*)tmp.Data, tmp.Length); + bytesWritten = tmp.Length; + return true; + } + + astcenc_image image = new astcenc_image(); + try + { + if (bitness == 8) image.LoadFromDirectPtr((RGBA8*)pixelPtr, width, height, 8); + else if (bitness == 16) image.LoadFromDirectPtr((RGBA16F*)pixelPtr, width, height, 16); + else image.LoadFromDirectPtr((RGBA32F*)pixelPtr, width, height, 32); + + astcenc_error status = lease.Context.CompressSingleImage(ref image, ref swizzle, destPtr, (int)expectedOutBytes, CancellationToken.None); + if (status != astcenc_error.ASTCENC_SUCCESS) + return false; + + bytesWritten = (int)expectedOutBytes; + return true; + } + finally + { + image.Release(ownsSliceMemory: false); + } + } + + private static bool IsDirect4ChannelFormat(GraphicsFormat format) + { + switch (format) + { + case GraphicsFormat.R8G8B8A8_UNorm: + case GraphicsFormat.R8G8B8A8_SRGB: + case GraphicsFormat.B8G8R8A8_UNorm: + case GraphicsFormat.B8G8R8A8_SRGB: + case GraphicsFormat.R16G16B16A16_SFloat: + case GraphicsFormat.R32G32B32A32_SFloat: + return true; + default: + return false; + } + } + + private static int GetBitness(GraphicsFormat format) + { + switch (format) + { + case GraphicsFormat.R16_SFloat: + case GraphicsFormat.R16G16_SFloat: + case GraphicsFormat.R16G16B16_SFloat: + case GraphicsFormat.R16G16B16A16_SFloat: + return 16; + case GraphicsFormat.R16_UNorm: + case GraphicsFormat.R16G16_UNorm: + case GraphicsFormat.R16G16B16_UNorm: + case GraphicsFormat.R16G16B16A16_UNorm: + case GraphicsFormat.R32_SFloat: + case GraphicsFormat.R32G32_SFloat: + case GraphicsFormat.R32G32B32_SFloat: + case GraphicsFormat.R32G32B32A32_SFloat: + return 32; + default: + return 8; + } + } + } +} diff --git a/Assets/ASTC Encoder/Runtime/Cpu/AstcCpuBackend.cs.meta b/Assets/ASTC Encoder/Runtime/Cpu/AstcCpuBackend.cs.meta new file mode 100644 index 0000000..e2d86dc --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Cpu/AstcCpuBackend.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9c2d7a41e5f843b6a019d8e24f6c3a57 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/EncodeBackend.cs b/Assets/ASTC Encoder/Runtime/EncodeBackend.cs new file mode 100644 index 0000000..2dc2bb0 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/EncodeBackend.cs @@ -0,0 +1,24 @@ +namespace Aperture.Astcenc.Runtime +{ + /// + /// Selects which execution backend is used for runtime ASTC texture compression. + /// + public enum EncodeBackend + { + /// + /// Native CPU compression via ARM astc-encoder (highest quality presets, requires readable Texture2D). + /// + Cpu = 0, + + /// + /// GPU Compute Shader compression (real-time speed, supports RenderTexture and non-readable Texture2D). + /// + Gpu = 1, + + /// + /// Prefers GPU Compute Shader when supported on the current device and input texture, + /// automatically falling back to CPU astc-encoder otherwise. + /// + Auto = 2, + } +} diff --git a/Assets/ASTC Encoder/Runtime/EncodeBackend.cs.meta b/Assets/ASTC Encoder/Runtime/EncodeBackend.cs.meta new file mode 100644 index 0000000..6ffdff1 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/EncodeBackend.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 4bf2de37c575d24863f47cb8a691f19c +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/Encoder.cs b/Assets/ASTC Encoder/Runtime/Encoder.cs index 0fc4dc3..6c7794c 100644 --- a/Assets/ASTC Encoder/Runtime/Encoder.cs +++ b/Assets/ASTC Encoder/Runtime/Encoder.cs @@ -1,16 +1,16 @@ -using System; +using System; using System.Runtime.InteropServices; -using Unity.Collections; +using System.Threading; +using System.Threading.Tasks; using UnityEngine; using UnityEngine.Experimental.Rendering; +using UnityEngine.Rendering; namespace Aperture.Astcenc.Runtime { public static class Encoder { - private const int k_BytePerBlock = 16; - - private static bool GetBlockSize(BlockSize size, out uint x, out uint y, out uint z) + internal static bool GetBlockSize(BlockSize size, out uint x, out uint y, out uint z) { switch (size) { @@ -43,172 +43,21 @@ private static bool GetBlockSize(BlockSize size, out uint x, out uint y, out uin return false; } - private static float GetQualityValue(CompressQuality quality) - { - return quality switch - { - CompressQuality.Fastest => 0.0f, - CompressQuality.Fast => 10.0f, - CompressQuality.Medium => 60.0f, - CompressQuality.Thorough => 98.0f, - CompressQuality.VeryThorough => 99.0f, - CompressQuality.Exhaustive => 100.0f, - _ => throw new ArgumentException("Unknown type of a CompressQuality:", nameof(quality)), - }; - } - - private static astcenc_profile GetColorProfile(GraphicsFormat graphicsFormat) - { - return graphicsFormat switch - { - //LDR - - GraphicsFormat.R8_UNorm => astcenc_profile.ASTCENC_PRF_LDR, - GraphicsFormat.R8_SRGB => astcenc_profile.ASTCENC_PRF_LDR_SRGB, - GraphicsFormat.R8G8_UNorm => astcenc_profile.ASTCENC_PRF_LDR, - GraphicsFormat.R8G8_SRGB => astcenc_profile.ASTCENC_PRF_LDR_SRGB, - GraphicsFormat.R8G8B8_UNorm => astcenc_profile.ASTCENC_PRF_LDR, - GraphicsFormat.R8G8B8_SRGB => astcenc_profile.ASTCENC_PRF_LDR_SRGB, - GraphicsFormat.R8G8B8A8_UNorm => astcenc_profile.ASTCENC_PRF_LDR, - GraphicsFormat.R8G8B8A8_SRGB => astcenc_profile.ASTCENC_PRF_LDR_SRGB, - GraphicsFormat.B8G8R8_UNorm => astcenc_profile.ASTCENC_PRF_LDR, - GraphicsFormat.B8G8R8_SRGB => astcenc_profile.ASTCENC_PRF_LDR_SRGB, - GraphicsFormat.B8G8R8A8_UNorm => astcenc_profile.ASTCENC_PRF_LDR, - GraphicsFormat.B8G8R8A8_SRGB => astcenc_profile.ASTCENC_PRF_LDR_SRGB, - - GraphicsFormat.R16_UNorm => astcenc_profile.ASTCENC_PRF_LDR, - GraphicsFormat.R16G16_UNorm => astcenc_profile.ASTCENC_PRF_LDR, - GraphicsFormat.R16G16B16_UNorm => astcenc_profile.ASTCENC_PRF_LDR, - GraphicsFormat.R16G16B16A16_UNorm => astcenc_profile.ASTCENC_PRF_LDR, - - //HDR - - GraphicsFormat.R16_SFloat => astcenc_profile.ASTCENC_PRF_HDR, - GraphicsFormat.R16G16_SFloat => astcenc_profile.ASTCENC_PRF_HDR, - GraphicsFormat.R16G16B16_SFloat => astcenc_profile.ASTCENC_PRF_HDR, - GraphicsFormat.R16G16B16A16_SFloat => astcenc_profile.ASTCENC_PRF_HDR, - - GraphicsFormat.R32_SFloat => astcenc_profile.ASTCENC_PRF_HDR, - GraphicsFormat.R32G32_SFloat => astcenc_profile.ASTCENC_PRF_HDR, - GraphicsFormat.R32G32B32_SFloat => astcenc_profile.ASTCENC_PRF_HDR, - GraphicsFormat.R32G32B32A32_SFloat => astcenc_profile.ASTCENC_PRF_HDR, - _ => throw new NotSupportedException("GraphicsFormat is not support:"), - }; - } - - private static CodecFlags GetFlags(TextureType textureType, GraphicsFormat graphicsFormat) + internal static GraphicsFormat FitAstcGraphicsFormat(GraphicsFormat graphicsFormat, BlockSize blockSize, TextureType textureType = TextureType.Default) { - CodecFlags flags = textureType == TextureType.Default ? CodecFlags.None : CodecFlags.MapNormal; - switch (graphicsFormat) { - //LDR - - case GraphicsFormat.R8_UNorm: case GraphicsFormat.R8_SRGB: - case GraphicsFormat.R8G8_UNorm: case GraphicsFormat.R8G8_SRGB: - case GraphicsFormat.R8G8B8_UNorm: case GraphicsFormat.R8G8B8_SRGB: - break; - case GraphicsFormat.R8G8B8A8_UNorm: case GraphicsFormat.R8G8B8A8_SRGB: - flags |= CodecFlags.UseAlphaWeight; - break; - - case GraphicsFormat.B8G8R8_UNorm: - case GraphicsFormat.B8G8R8_SRGB: - break; - case GraphicsFormat.B8G8R8A8_UNorm: - case GraphicsFormat.B8G8R8A8_SRGB: - flags |= CodecFlags.UseAlphaWeight; - break; - - case GraphicsFormat.R16_UNorm: - case GraphicsFormat.R16G16_UNorm: - case GraphicsFormat.R16G16B16_UNorm: - break; - case GraphicsFormat.R16G16B16A16_UNorm: - flags |= CodecFlags.UseAlphaWeight; - break; - - //HDR - - case GraphicsFormat.R16_SFloat: - case GraphicsFormat.R16G16_SFloat: - case GraphicsFormat.R16G16B16_SFloat: - break; - case GraphicsFormat.R16G16B16A16_SFloat: - flags |= CodecFlags.UseAlphaWeight; - break; - - case GraphicsFormat.R32_SFloat: - case GraphicsFormat.R32G32_SFloat: - case GraphicsFormat.R32G32B32_SFloat: - break; - case GraphicsFormat.R32G32B32A32_SFloat: - flags |= CodecFlags.UseAlphaWeight; - break; - } - - return flags; - } - private static astcenc_swizzle GetSwizzle(GraphicsFormat graphicsFormat, TextureType textureType) - { - if (textureType == TextureType.Normal) - { - astcenc_swizzle swizzle = new astcenc_swizzle - { - r = astcenc_swz.ASTCENC_SWZ_G, - g = astcenc_swz.ASTCENC_SWZ_G, - b = astcenc_swz.ASTCENC_SWZ_G, - a = astcenc_swz.ASTCENC_SWZ_R, - }; - return swizzle; - } - - switch (graphicsFormat) - { - case GraphicsFormat.B8G8R8_UNorm: case GraphicsFormat.B8G8R8_SRGB: - case GraphicsFormat.B8G8R8A8_UNorm: case GraphicsFormat.B8G8R8A8_SRGB: + if (textureType == TextureType.Normal) { - astcenc_swizzle swizzle = new astcenc_swizzle - { - r = astcenc_swz.ASTCENC_SWZ_B, - g = astcenc_swz.ASTCENC_SWZ_G, - b = astcenc_swz.ASTCENC_SWZ_R, - a = astcenc_swz.ASTCENC_SWZ_A, - }; - return swizzle; - } - default: - { - astcenc_swizzle swizzle = new astcenc_swizzle - { - r = astcenc_swz.ASTCENC_SWZ_R, - g = astcenc_swz.ASTCENC_SWZ_G, - b = astcenc_swz.ASTCENC_SWZ_B, - a = astcenc_swz.ASTCENC_SWZ_A, - }; - return swizzle; + goto case GraphicsFormat.R8G8B8A8_UNorm; } - } - } - - private static GraphicsFormat FitAstcGraphicsFormat(GraphicsFormat graphicsFormat, BlockSize blockSize) - { - switch (graphicsFormat) - { - case GraphicsFormat.R8_SRGB: - case GraphicsFormat.R8G8_SRGB: - case GraphicsFormat.R8G8B8_SRGB: - case GraphicsFormat.R8G8B8A8_SRGB: - - case GraphicsFormat.B8G8R8_SRGB: - case GraphicsFormat.B8G8R8A8_SRGB: { switch (blockSize) { @@ -263,6 +112,10 @@ private static GraphicsFormat FitAstcGraphicsFormat(GraphicsFormat graphicsForma case GraphicsFormat.R32G32_SFloat: case GraphicsFormat.R32G32B32_SFloat: case GraphicsFormat.R32G32B32A32_SFloat: + if (textureType == TextureType.Normal) + { + goto case GraphicsFormat.R8G8B8A8_UNorm; + } switch (blockSize) { case BlockSize.ASTC_4x4: @@ -280,283 +133,227 @@ private static GraphicsFormat FitAstcGraphicsFormat(GraphicsFormat graphicsForma } break; } - throw new ArgumentException(); + throw new ArgumentException($"Unsupported ASTC format mapping: GraphicsFormat={graphicsFormat}, BlockSize={blockSize}"); } - private static bool IsSupportGraphicFormat(GraphicsFormat graphicsFormat) + /// + /// Resolves the target ASTC for a given source format, block size, and texture type. + /// Normal maps always resolve to linear UNorm ASTC regardless of sRGB or float source format. + /// + public static GraphicsFormat GetTargetAstcFormat(GraphicsFormat sourceFormat, BlockSize blockSize, TextureType textureType = TextureType.Default) { - switch (graphicsFormat) - { - //LDR + return AstcGpuBackend.ResolveTargetAstcFormat(sourceFormat, textureType, blockSize, out _, out _); + } - case GraphicsFormat.R8_UNorm: - case GraphicsFormat.R8_SRGB: - case GraphicsFormat.R8G8_UNorm: - case GraphicsFormat.R8G8_SRGB: - case GraphicsFormat.R8G8B8_UNorm: - case GraphicsFormat.R8G8B8_SRGB: - case GraphicsFormat.R8G8B8A8_UNorm: - case GraphicsFormat.R8G8B8A8_SRGB: + internal static bool CanCreateAstcTexture(GraphicsFormat format) + { + if (Application.isEditor) + return true; + +#if UNITY_2023_2_OR_NEWER + return SystemInfo.IsFormatSupported(format, GraphicsFormatUsage.Sample); +#else + return SystemInfo.IsFormatSupported(format, FormatUsage.Sample); +#endif + } - case GraphicsFormat.B8G8R8_UNorm: - case GraphicsFormat.B8G8R8_SRGB: - case GraphicsFormat.B8G8R8A8_UNorm: - case GraphicsFormat.B8G8R8A8_SRGB: + internal static bool IsFullMipChain(int width, int height, int mipCount) + { + if (mipCount <= 1) + return true; - case GraphicsFormat.R16_UNorm: - case GraphicsFormat.R16G16_UNorm: - case GraphicsFormat.R16G16B16_UNorm: - case GraphicsFormat.R16G16B16A16_UNorm: + int maxDim = Math.Max(width, height); + int expectedMips = 1; + while (maxDim > 1) + { + maxDim >>= 1; + expectedMips++; + } + return mipCount == expectedMips; + } - //HDR + public static bool IsGpuSupported => AstcGpuBackend.IsSupported; + public static bool IsCpuSupported => AstcCpuBackend.IsSupported; - case GraphicsFormat.R16_SFloat: - case GraphicsFormat.R16G16_SFloat: - case GraphicsFormat.R16G16B16_SFloat: - case GraphicsFormat.R16G16B16A16_SFloat: + public static bool SupportsGpuDirectCopy(BlockSize blockSize, bool srgb = false, bool isHdr = false) + { + return AstcGpuBackend.SupportsDirectCopy(blockSize, srgb, isHdr); + } - case GraphicsFormat.R32_SFloat: - case GraphicsFormat.R32G32_SFloat: - case GraphicsFormat.R32G32B32_SFloat: - case GraphicsFormat.R32G32B32A32_SFloat: - return true; - } - return false; + public static void PreloadGpu(BlockSize blockSize = BlockSize.ASTC_6x6) + { + AstcGpuBackend.Preload(blockSize); + } + + public static void ReleaseGpuCache() + { + AstcGpuBackend.ReleaseCache(); } - public static bool IsSupport(Texture texture) + /// + /// Releases all cached native CPU instances held by the internal static pool. + /// Safe to call even while background CPU compressions are in flight (in-flight parent tables are retired lazily). + /// + public static void ReleaseCpuContextPool() { - return texture.isReadable && IsSupportGraphicFormat(texture.graphicsFormat); + AstcContextPool.ReleaseAll(); } - private static bool CompressRawData(IntPtr context, astcenc_swizzle swizzle, NativeArray raw, int width, int height, int bitness, int mipCount, uint blockX, uint blockY, out IntPtr output, out int size) where T : struct, IRawData + public static bool IsSupport(Texture texture, EncodeBackend backend = EncodeBackend.Auto) { - //alloc a total memory to hold all ths mipmaps - int total = 0; - for (int i = 0; i < mipCount; i++) + return backend switch { - int mipmapWidth = width / (1 << i); - int mipmapHeight = height / (1 << i); - int blockCountX = (mipmapWidth + (int)blockX - 1) / (int)blockX; - int blockCountY = (mipmapHeight + (int)blockY - 1) / (int)blockY; - int length = blockCountX * blockCountY * k_BytePerBlock; + EncodeBackend.Cpu => AstcCpuBackend.IsSupported && AstcCpuBackend.IsInputSupported(texture), + EncodeBackend.Gpu => AstcGpuBackend.IsSupported && AstcGpuBackend.IsInputSupported(texture), + EncodeBackend.Auto => (AstcGpuBackend.IsSupported && AstcGpuBackend.IsInputSupported(texture)) + || (AstcCpuBackend.IsSupported && AstcCpuBackend.IsInputSupported(texture)), + _ => false, + }; + } - total += length; - } - output = Marshal.AllocHGlobal(total); - size = total; + private static bool ShouldUseGpu(Texture texture, EncodeBackend backend) + { + return backend switch + { + EncodeBackend.Gpu => true, + EncodeBackend.Auto => AstcGpuBackend.IsSupported && AstcGpuBackend.IsInputSupported(texture), + _ => false, + }; + } - int elementReaded = 0; - int byteWrited = 0; + private static bool CanFallbackToCpu(Texture texture, EncodeBackend backend) + { + return backend == EncodeBackend.Auto + && AstcCpuBackend.IsSupported + && AstcCpuBackend.IsInputSupported(texture); + } - try + /// + /// Compress the inputTexture and return the compressed data by AstcRaw, you should call Dispose() for the AstcRaw after use. + /// + public static AstcRaw CompressTexture(this Texture2D inputTexture, TextureType textureType, BlockSize blockSize, CompressQuality quality, int threadCount = 1, bool useAlphaWeight = false, EncodeBackend backend = EncodeBackend.Auto) + { + if (ShouldUseGpu(inputTexture, backend)) { - for (int i = 0; i < mipCount; i++) - { - int mipmapWidth = width / (1 << i); - int mipmapHeight = height / (1 << i); - int blockCountX = (mipmapWidth + (int)blockX - 1) / (int)blockX; - int blockCountY = (mipmapHeight + (int)blockY - 1) / (int)blockY; - int length = blockCountX * blockCountY * k_BytePerBlock; - - int count = mipmapWidth * mipmapHeight; - NativeSlice mipmapSlice = raw.Slice(elementReaded, count); + AstcRaw gpuRaw = AstcGpuBackend.CompressTextureSync(inputTexture, textureType, blockSize, quality, includeMipmaps: true, useAlphaWeight: useAlphaWeight); + if (gpuRaw != null || !CanFallbackToCpu(inputTexture, backend)) + return gpuRaw; + } - astcenc_image image = new astcenc_image(); - try - { - image.LoadFrom(mipmapSlice, mipmapWidth, mipmapHeight, bitness); + return AstcCpuBackend.CompressTextureSync(inputTexture, textureType, blockSize, quality, threadCount: threadCount, includeMipmaps: true, useAlphaWeight: useAlphaWeight); + } - astcenc_error status = astcenc_api.astcenc_compress_image(context, ref image, ref swizzle, output + byteWrited, length, 0); - if (status != astcenc_error.ASTCENC_SUCCESS) - { - throw new Exception(status.ToString()); - } - } - catch - { - throw; - } - finally - { - image.Release(); - astcenc_api.astcenc_compress_reset(context); - } + /// + /// Compresses a Texture2D or RenderTexture using an configuration struct. + /// Call Dispose() on the returned AstcRaw after use. + /// + public static AstcRaw CompressTexture(this Texture inputTexture, AstcCompressOptions options) + { + if (inputTexture == null) + { + Debug.LogError("Input texture is null."); + return null; + } - elementReaded += count; - byteWrited += length; - } + if (ShouldUseGpu(inputTexture, options.Backend)) + { + AstcRaw gpuRaw = AstcGpuBackend.CompressTextureSync(inputTexture, options.TextureType, options.BlockSize, options.Quality, options.IncludeMipmaps, options.UseAlphaWeight, options.GenerateMipmaps); + if (gpuRaw != null || !CanFallbackToCpu(inputTexture, options.Backend)) + return gpuRaw; } - catch + + if (inputTexture is Texture2D tex2d) { - Marshal.FreeHGlobal(output); + return AstcCpuBackend.CompressTextureSync(tex2d, options.TextureType, options.BlockSize, options.Quality, options.ThreadCount, options.IncludeMipmaps, options.UseAlphaWeight, options.UsePerceptual, options.AlphaScaleRadius, options.UseUnityJobSystem); + } - output = IntPtr.Zero; - size = 0; + Debug.LogError("CPU backend only supports readable Texture2D. Use EncodeBackend.Gpu or EncodeBackend.Auto for RenderTexture inputs."); + return null; + } - return false; - } - return true; + /// + /// Compresses a RenderTexture on the GPU and returns raw ASTC bytes. Call Dispose() on the returned AstcRaw after use. + /// + public static AstcRaw CompressTexture(this RenderTexture inputTexture, TextureType textureType = TextureType.Default, BlockSize blockSize = BlockSize.ASTC_6x6, CompressQuality quality = CompressQuality.Fast, bool includeMipmaps = true, bool useAlphaWeight = false) + { + return AstcGpuBackend.CompressTextureSync(inputTexture, textureType, blockSize, quality, includeMipmaps, useAlphaWeight); } - private static bool CompressImage(Texture2D inputTexture, IntPtr context, astcenc_swizzle swizzle, uint blockX, uint blockY, out IntPtr output, out int size) + /// + /// Compresses a Texture2D asynchronously on GPU AsyncGPUReadback or CPU background thread(s) depending on backend. + /// You should call Dispose() on the returned AstcRaw after use. + /// + public static async Task CompressTextureAsync(this Texture2D inputTexture, TextureType textureType = TextureType.Default, BlockSize blockSize = BlockSize.ASTC_6x6, CompressQuality quality = CompressQuality.Fast, int threadCount = 0, bool useAlphaWeight = false, CancellationToken cancellationToken = default, EncodeBackend backend = EncodeBackend.Auto) { - switch (inputTexture.graphicsFormat) + if (cancellationToken.IsCancellationRequested) { - case GraphicsFormat.R8_UNorm: - case GraphicsFormat.R8_SRGB: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 8, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R8G8_UNorm: - case GraphicsFormat.R8G8_SRGB: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 8, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R8G8B8_UNorm: - case GraphicsFormat.R8G8B8_SRGB: - case GraphicsFormat.B8G8R8_UNorm: - case GraphicsFormat.B8G8R8_SRGB: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 8, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R8G8B8A8_UNorm: - case GraphicsFormat.R8G8B8A8_SRGB: - case GraphicsFormat.B8G8R8A8_UNorm: - case GraphicsFormat.B8G8R8A8_SRGB: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 8, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R16_UNorm: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 16, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R16G16_UNorm: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 16, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R16G16B16_UNorm: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 16, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R16G16B16A16_UNorm: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 16, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R16_SFloat: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 16, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R16G16_SFloat: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 16, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R16G16B16_SFloat: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 16, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R16G16B16A16_SFloat: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 16, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R32_SFloat: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 32, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R32G32_SFloat: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 32, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R32G32B32_SFloat: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 32, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } - case GraphicsFormat.R32G32B32A32_SFloat: - { - NativeArray raw = inputTexture.GetRawTextureData(); - return CompressRawData(context, swizzle, raw, inputTexture.width, inputTexture.height, 32, inputTexture.mipmapCount, blockX, blockY, out output, out size); - } + throw new OperationCanceledException(cancellationToken); } - output = IntPtr.Zero; - size = 0; + if (ShouldUseGpu(inputTexture, backend)) + { + AstcRaw gpuRaw = await AstcGpuBackend.CompressTextureAsync(inputTexture, textureType, blockSize, quality, includeMipmaps: true, useAlphaWeight: useAlphaWeight, cancellationToken: cancellationToken); + if (gpuRaw != null || !CanFallbackToCpu(inputTexture, backend)) + return gpuRaw; + } - return false; + return await AstcCpuBackend.CompressTextureAsync(inputTexture, textureType, blockSize, quality, threadCount: threadCount, includeMipmaps: true, useAlphaWeight: useAlphaWeight, cancellationToken: cancellationToken); } /// - /// Compress the inputTexture and return the compressed data by AstcRaw, you should call Dispose() for the AstcRaw after use. + /// Compresses a Texture2D or RenderTexture asynchronously using an configuration struct. + /// Call Dispose() on the returned AstcRaw after use. /// - /// inputTexture - /// output unmanaged data IntPtr - /// out put data size - /// Indicate that compress for color texture or notmal texture - /// Astc compress ratio - /// Compress quality setting - /// CompressedData - public static AstcRaw CompressTexture(this Texture2D inputTexture, TextureType textureType, BlockSize blockSize, CompressQuality quality) + public static async Task CompressTextureAsync(this Texture inputTexture, AstcCompressOptions options, CancellationToken cancellationToken = default) { - if (!IsSupport(inputTexture)) + if (cancellationToken.IsCancellationRequested) { - Debug.LogError("Texture format is not support or read/write is disabled."); - return null; + throw new OperationCanceledException(cancellationToken); } - uint threadCount = 1; - GetBlockSize(blockSize, out uint blockX, out uint blockY, out uint blockZ); - - float qualityValue = GetQualityValue(quality); - - astcenc_profile profile = GetColorProfile(inputTexture.graphicsFormat); - astcenc_swizzle swizzle = GetSwizzle(inputTexture.graphicsFormat, textureType); - - uint flags = (uint)GetFlags(textureType, inputTexture.graphicsFormat); - - astcenc_config config = new astcenc_config(); - astcenc_error status = astcenc_api.astcenc_config_init(profile, blockX, blockY, blockZ, qualityValue, flags, ref config); - if (status != astcenc_error.ASTCENC_SUCCESS) + if (inputTexture == null) { - Debug.LogError("Codec config init failed:" + status); + Debug.LogError("Input texture is null."); return null; } - IntPtr context = IntPtr.Zero; - status = astcenc_api.astcenc_context_alloc(ref config, threadCount, ref context); - if (status != astcenc_error.ASTCENC_SUCCESS) + if (ShouldUseGpu(inputTexture, options.Backend)) { - Debug.LogError("Codec context alloc failed:" + status); - return null; + AstcRaw gpuRaw = await AstcGpuBackend.CompressTextureAsync(inputTexture, options.TextureType, options.BlockSize, options.Quality, options.IncludeMipmaps, options.UseAlphaWeight, cancellationToken, options.GenerateMipmaps); + if (gpuRaw != null || !CanFallbackToCpu(inputTexture, options.Backend)) + return gpuRaw; } - CompressImage(inputTexture, context, swizzle, blockX, blockY, out IntPtr output, out int size); + if (inputTexture is Texture2D tex2d) + { + return await AstcCpuBackend.CompressTextureAsync(tex2d, options.TextureType, options.BlockSize, options.Quality, options.ThreadCount, options.IncludeMipmaps, options.UseAlphaWeight, cancellationToken, options.UsePerceptual, options.AlphaScaleRadius); + } - astcenc_api.astcenc_context_free(context); + Debug.LogError("CPU backend only supports readable Texture2D. Use EncodeBackend.Gpu or EncodeBackend.Auto for RenderTexture inputs."); + return null; + } - return new AstcRaw(output, size); + /// + /// Compresses a RenderTexture asynchronously on the GPU using AsyncGPUReadback without stalling the main thread. + /// Call Dispose() on the returned AstcRaw after use. + /// + public static Task CompressTextureAsync(this RenderTexture inputTexture, TextureType textureType = TextureType.Default, BlockSize blockSize = BlockSize.ASTC_6x6, CompressQuality quality = CompressQuality.Fast, bool includeMipmaps = true, bool useAlphaWeight = false, CancellationToken cancellationToken = default) + { + return AstcGpuBackend.CompressTextureAsync(inputTexture, textureType, blockSize, quality, includeMipmaps, useAlphaWeight, cancellationToken); } /// - /// Fills texture pixels with astc raw preformatted data. + /// Fills texture pixels with astc raw preformatted data. /// - /// Input texture must be uncompressed format and readable + /// Destination Texture2D initialized with matching ASTC format /// Astc raw data public static void LoadRawTextureData(this Texture2D inputTexture, AstcRaw raw) { + if (inputTexture == null) + { + throw new ArgumentNullException(nameof(inputTexture)); + } + if (raw != null) { raw.ThrowIfDisposed(); @@ -566,63 +363,723 @@ public static void LoadRawTextureData(this Texture2D inputTexture, AstcRaw raw) } /// - /// Compress texture at runtime to ASTC formats. + /// Compress texture in-place at runtime to ASTC format. /// - /// Input texture must be uncompressed format and readable - /// Indicate that compress for color texture or notmal texture - /// Astc compress ratio - /// Compress quality setting - /// When set to true, Unity discards the copy of pixel data in CPU-addressable memory after this operation. - /// Success or not - public static bool Compress(this Texture2D inputTexture, TextureType textureType = TextureType.Default, BlockSize blockSize = BlockSize.ASTC_6x6, CompressQuality quality = CompressQuality.Fast, bool makeNoLongerReadable = true) + public static bool Compress(this Texture2D inputTexture, TextureType textureType = TextureType.Default, BlockSize blockSize = BlockSize.ASTC_6x6, CompressQuality quality = CompressQuality.Fast, bool makeNoLongerReadable = true, int threadCount = 1, bool useAlphaWeight = false, EncodeBackend backend = EncodeBackend.Auto) { - using AstcRaw raw = inputTexture.CompressTexture(textureType, blockSize, quality); - - if (raw != null) + if (ShouldUseGpu(inputTexture, backend)) { - raw.ThrowIfDisposed(); - - GraphicsFormat graphicsFormat = FitAstcGraphicsFormat(inputTexture.graphicsFormat, blockSize); + bool ok = AstcGpuBackend.CompressInPlace(inputTexture, textureType, blockSize, quality, makeNoLongerReadable, useAlphaWeight); + if (ok || !CanFallbackToCpu(inputTexture, backend)) + return ok; + } - if(inputTexture.Reinitialize(inputTexture.width, inputTexture.height, graphicsFormat, inputTexture.mipmapCount > 0)) - { - inputTexture.LoadRawTextureData(raw); - inputTexture.Apply(true, makeNoLongerReadable); + return AstcCpuBackend.CompressInPlace(inputTexture, textureType, blockSize, quality, makeNoLongerReadable, threadCount, useAlphaWeight); + } - return true; - } + /// + /// Compresses a Texture2D in-place using an configuration struct. + /// + public static bool Compress(this Texture2D inputTexture, AstcCompressOptions options) + { + if (ShouldUseGpu(inputTexture, options.Backend)) + { + bool ok = AstcGpuBackend.CompressInPlace(inputTexture, options.TextureType, options.BlockSize, options.Quality, options.MakeNoLongerReadable, options.UseAlphaWeight, options.GenerateMipmaps); + if (ok || !CanFallbackToCpu(inputTexture, options.Backend)) + return ok; } - return false; + + return AstcCpuBackend.CompressInPlace(inputTexture, options.TextureType, options.BlockSize, options.Quality, options.MakeNoLongerReadable, options.ThreadCount, options.UseAlphaWeight, options.UsePerceptual, options.AlphaScaleRadius, options.UseUnityJobSystem); } /// - /// Encode texture2D to ASTC file with a astc header.(Not GC friendly) + /// Compresses any 2D Texture (Texture2D or RenderTexture, without requiring Read/Write on GPU) + /// into a newly allocated ASTC-compressed Texture2D. Uses zero-readback GPU CopyTexture when supported. /// - /// - /// - /// - /// - /// - public static byte[] EncodeToASTC(this Texture2D inputTexture, TextureType textureType = TextureType.Default, BlockSize blockSize = BlockSize.ASTC_6x6, CompressQuality quality = CompressQuality.Medium) + /// + /// Row 0 in the encoded ASTC output corresponds to texel y = 0 (bottom-up), matching Unity's Texture2D, + /// Graphics.CopyTexture, and standard .astc conventions. RenderTextures rendered by Unity cameras or Blit + /// already match this layout; RenderTextures populated by custom compute shaders with top-down coordinates + /// should be flipped vertically before encoding. + /// + public static Texture2D CompressToTexture( + this Texture source, + TextureType textureType = TextureType.Default, + BlockSize blockSize = BlockSize.ASTC_6x6, + CompressQuality quality = CompressQuality.Fast, + bool includeMipmaps = true, + bool useAlphaWeight = false, + EncodeBackend backend = EncodeBackend.Auto) { - using AstcRaw raw = inputTexture.CompressTexture(textureType, blockSize, quality); + if (source == null) + { + Debug.LogError("Source texture is null."); + return null; + } - if (raw != null) + if (ShouldUseGpu(source, backend)) { - raw.ThrowIfDisposed(); + Texture2D gpuTex = AstcGpuBackend.CompressToTexture(source, textureType, blockSize, quality, includeMipmaps, useAlphaWeight); + if (gpuTex != null || !CanFallbackToCpu(source, backend)) + return gpuTex; + } + + if (source is Texture2D tex2d) + { + return AstcCpuBackend.CompressToTexture(tex2d, textureType, blockSize, quality, includeMipmaps, useAlphaWeight); + } + + Debug.LogError("CPU backend only supports readable Texture2D. Use EncodeBackend.Gpu or EncodeBackend.Auto for RenderTexture inputs."); + return null; + } + + /// + /// Compresses any 2D Texture into a newly allocated ASTC-compressed Texture2D using an struct. + /// + public static Texture2D CompressToTexture(this Texture source, AstcCompressOptions options) + { + if (source == null) + { + Debug.LogError("Source texture is null."); + return null; + } + + if (ShouldUseGpu(source, options.Backend)) + { + Texture2D gpuTex = AstcGpuBackend.CompressToTexture(source, options.TextureType, options.BlockSize, options.Quality, options.IncludeMipmaps, options.UseAlphaWeight, options.GenerateMipmaps); + if (gpuTex != null || !CanFallbackToCpu(source, options.Backend)) + return gpuTex; + } + + if (source is Texture2D tex2d) + { + return AstcCpuBackend.CompressToTexture(tex2d, options.TextureType, options.BlockSize, options.Quality, options.IncludeMipmaps, options.UseAlphaWeight, options.ThreadCount, options.UsePerceptual, options.AlphaScaleRadius, options.UseUnityJobSystem); + } + + Debug.LogError("CPU backend only supports readable Texture2D. Use EncodeBackend.Gpu or EncodeBackend.Auto for RenderTexture inputs."); + return null; + } - byte[] output = new byte[16 + raw.Length]; + /// + /// Asynchronously compresses any 2D Texture (Texture2D or RenderTexture) into a newly allocated ASTC-compressed Texture2D + /// without blocking the main thread (uses zero-readback CopyTexture when aligned, AsyncGPUReadback on GPU, or background threads on CPU). + /// Must be called from the Unity main thread. + /// + public static async Task CompressToTextureAsync( + this Texture source, + TextureType textureType = TextureType.Default, + BlockSize blockSize = BlockSize.ASTC_6x6, + CompressQuality quality = CompressQuality.Fast, + bool includeMipmaps = true, + bool useAlphaWeight = false, + int threadCount = 0, + CancellationToken cancellationToken = default, + EncodeBackend backend = EncodeBackend.Auto) + { + if (cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(cancellationToken); + } + + if (source == null) + { + Debug.LogError("Source texture is null."); + return null; + } + + if (ShouldUseGpu(source, backend)) + { + Texture2D gpuTex = await AstcGpuBackend.CompressToTextureAsync(source, textureType, blockSize, quality, includeMipmaps, useAlphaWeight, cancellationToken); + if (gpuTex != null || !CanFallbackToCpu(source, backend)) + return gpuTex; + } + + if (source is Texture2D tex2d) + { + return await AstcCpuBackend.CompressToTextureAsync(tex2d, textureType, blockSize, quality, includeMipmaps, useAlphaWeight, threadCount, cancellationToken: cancellationToken); + } + + Debug.LogError("CPU backend only supports readable Texture2D. Use EncodeBackend.Gpu or EncodeBackend.Auto for RenderTexture inputs."); + return null; + } - GetBlockSize(blockSize, out uint dimX, out uint dimY, out uint dimZ); - using AstcHeader header = new AstcHeader(dimX, dimY, dimZ, inputTexture.width, inputTexture.height, 1); + /// + /// Asynchronously compresses any 2D Texture into a newly allocated ASTC-compressed Texture2D using an struct. + /// + public static async Task CompressToTextureAsync(this Texture source, AstcCompressOptions options, CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(cancellationToken); + } + + if (source == null) + { + Debug.LogError("Source texture is null."); + return null; + } - Marshal.Copy(header.Data, output, 0, 16); - Marshal.Copy(raw.Data, output, 16, raw.Length); + if (ShouldUseGpu(source, options.Backend)) + { + Texture2D gpuTex = await AstcGpuBackend.CompressToTextureAsync(source, options.TextureType, options.BlockSize, options.Quality, options.IncludeMipmaps, options.UseAlphaWeight, cancellationToken, options.GenerateMipmaps); + if (gpuTex != null || !CanFallbackToCpu(source, options.Backend)) + return gpuTex; + } - return output; + if (source is Texture2D tex2d) + { + return await AstcCpuBackend.CompressToTextureAsync(tex2d, options.TextureType, options.BlockSize, options.Quality, options.IncludeMipmaps, options.UseAlphaWeight, options.ThreadCount, options.UsePerceptual, options.AlphaScaleRadius, cancellationToken); } + + Debug.LogError("CPU backend only supports readable Texture2D. Use EncodeBackend.Gpu or EncodeBackend.Auto for RenderTexture inputs."); return null; } + + /// + /// Records a GPU ASTC compression dispatch and zero-readback CopyTexture into a CommandBuffer. + /// Ideal for batching, Async Compute queues, procedural textures, and virtual texture atlas tile updates. + /// + /// Destination X offset in texels (must be a non-negative multiple of the ASTC block width). + /// Destination Y offset in texels (must be a non-negative multiple of the ASTC block height). + /// + /// Row 0 is encoded at texel y = 0 without vertical flipping, matching Unity Texture2D and CopyTexture layout. + /// If is a RenderTexture written by a custom compute shader using top-down y, + /// flip it prior to encoding. + /// + public static void Encode( + CommandBuffer cmd, + Texture source, + Texture destination, + TextureType textureType = TextureType.Default, + BlockSize blockSize = BlockSize.ASTC_6x6, + CompressQuality quality = CompressQuality.Fast, + int sourceMip = 0, + int destMip = 0, + int destX = 0, + int destY = 0, + bool useAlphaWeight = false, + int sourceSlice = 0, + int destSlice = 0) + { + AstcGpuBackend.Encode(cmd, source, destination, textureType, blockSize, quality, sourceMip, destMip, destX, destY, useAlphaWeight, sourceSlice, destSlice); + } + + /// + /// Compresses all 6 faces (and optional mipmaps) of a into a new ASTC-compressed on the GPU with zero CPU readback. + /// + public static Cubemap CompressCubemap(this Cubemap source, AstcCompressOptions options) + { + if (source == null) + { + Debug.LogError("Source Cubemap is null."); + return null; + } + return AstcGpuBackend.CompressCubemap(source, options.TextureType, options.BlockSize, options.Quality, options.IncludeMipmaps, options.UseAlphaWeight); + } + + /// + /// Compresses all slices (and optional mipmaps) of a into a new ASTC-compressed on the GPU with zero CPU readback. + /// + public static Texture2DArray CompressTexture2DArray(this Texture2DArray source, AstcCompressOptions options) + { + if (source == null) + { + Debug.LogError("Source Texture2DArray is null."); + return null; + } + return AstcGpuBackend.CompressTexture2DArray(source, options.TextureType, options.BlockSize, options.Quality, options.IncludeMipmaps, options.UseAlphaWeight); + } + + /// + /// Compresses raw pixel bytes directly on the CPU without creating a Unity . + /// Ideal for webcam feeds, procedural generators, and background-thread pipelines. + /// Call Dispose() on the returned after use. + /// + public static unsafe AstcRaw CompressRawPixels( + Unity.Collections.NativeArray rawPixels, + int width, + int height, + GraphicsFormat sourceFormat, + AstcCompressOptions options) + { + void* ptr = Unity.Collections.LowLevel.Unsafe.NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(rawPixels); + return AstcCpuBackend.CompressRawPixels( + (IntPtr)ptr, + rawPixels.Length, + width, + height, + sourceFormat, + options.TextureType, + options.BlockSize, + options.Quality, + options.ThreadCount, + options.UseAlphaWeight, + options.UsePerceptual, + options.AlphaScaleRadius, + options.UseUnityJobSystem); + } + + /// + /// Compresses raw pixel bytes directly into a caller-owned + /// with zero unmanaged heap allocations for 4-channel formats (RGBA8/BGRA8/RGBA16F/RGBA32F). + /// Ideal for high-frequency webcam/streaming loops reusing a persistent destination buffer. + /// + public static unsafe bool CompressRawPixelsInto( + Unity.Collections.NativeArray rawPixels, + Unity.Collections.NativeArray destination, + int width, + int height, + GraphicsFormat sourceFormat, + AstcCompressOptions options, + out int bytesWritten) + { + void* srcPtr = Unity.Collections.LowLevel.Unsafe.NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(rawPixels); + void* dstPtr = Unity.Collections.LowLevel.Unsafe.NativeArrayUnsafeUtility.GetUnsafePtr(destination); + return AstcCpuBackend.CompressRawPixelsInto( + (IntPtr)srcPtr, + rawPixels.Length, + (IntPtr)dstPtr, + destination.Length, + width, + height, + sourceFormat, + options.TextureType, + options.BlockSize, + options.Quality, + options.ThreadCount, + options.UseAlphaWeight, + options.UsePerceptual, + options.AlphaScaleRadius, + options.UseUnityJobSystem, + out bytesWritten); + } + + /// + /// Compresses a managed raw pixel byte array directly on the CPU without creating a Unity . + /// Call Dispose() on the returned after use. + /// + public static unsafe AstcRaw CompressRawPixels( + byte[] rawPixels, + int width, + int height, + GraphicsFormat sourceFormat, + AstcCompressOptions options) + { + if (rawPixels == null || rawPixels.Length == 0) + { + Debug.LogError("Raw pixel array is null or empty."); + return null; + } + + fixed (byte* ptr = rawPixels) + { + return AstcCpuBackend.CompressRawPixels( + (IntPtr)ptr, + rawPixels.Length, + width, + height, + sourceFormat, + options.TextureType, + options.BlockSize, + options.Quality, + options.ThreadCount, + options.UseAlphaWeight, + options.UsePerceptual, + options.AlphaScaleRadius, + options.UseUnityJobSystem); + } + } + + /// + /// Asynchronously compresses raw pixel bytes on a background thread without creating a Unity . + /// The input buffer is snapshotted before returning, so the caller may safely reuse or dispose it immediately. + /// + public static unsafe Task CompressRawPixelsAsync( + Unity.Collections.NativeArray rawPixels, + int width, + int height, + GraphicsFormat sourceFormat, + AstcCompressOptions options, + CancellationToken cancellationToken = default) + { + void* ptr = Unity.Collections.LowLevel.Unsafe.NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(rawPixels); + return AstcCpuBackend.CompressRawPixelsAsync( + (IntPtr)ptr, + rawPixels.Length, + width, + height, + sourceFormat, + options.TextureType, + options.BlockSize, + options.Quality, + options.ThreadCount, + options.UseAlphaWeight, + options.UsePerceptual, + options.AlphaScaleRadius, + cancellationToken); + } + + /// + /// Asynchronously compresses a managed raw pixel byte array on a background thread without creating a Unity . + /// + public static unsafe Task CompressRawPixelsAsync( + byte[] rawPixels, + int width, + int height, + GraphicsFormat sourceFormat, + AstcCompressOptions options, + CancellationToken cancellationToken = default) + { + if (rawPixels == null || rawPixels.Length == 0) + { + Debug.LogError("Raw pixel array is null or empty."); + return Task.FromResult(null); + } + + fixed (byte* ptr = rawPixels) + { + return AstcCpuBackend.CompressRawPixelsAsync( + (IntPtr)ptr, + rawPixels.Length, + width, + height, + sourceFormat, + options.TextureType, + options.BlockSize, + options.Quality, + options.ThreadCount, + options.UseAlphaWeight, + options.UsePerceptual, + options.AlphaScaleRadius, + cancellationToken); + } + } + + /// + /// Encode any 2D Texture (Texture2D or RenderTexture) to ASTC file bytes with a 16-byte .astc header (mip 0 only). + /// + public static byte[] EncodeToASTC(this Texture inputTexture, TextureType textureType = TextureType.Default, BlockSize blockSize = BlockSize.ASTC_6x6, CompressQuality quality = CompressQuality.Medium, int threadCount = 1, bool useAlphaWeight = false, EncodeBackend backend = EncodeBackend.Auto) + { + if (inputTexture == null) + { + Debug.LogError("Input texture is null."); + return null; + } + + // Standard .astc file header describes a single image level (mip 0 only) + AstcRaw raw = null; + if (ShouldUseGpu(inputTexture, backend)) + { + raw = AstcGpuBackend.CompressTextureSync(inputTexture, textureType, blockSize, quality, includeMipmaps: false, useAlphaWeight: useAlphaWeight); + if (raw == null && CanFallbackToCpu(inputTexture, backend)) + { + raw = AstcCpuBackend.CompressTextureSync((Texture2D)inputTexture, textureType, blockSize, quality, threadCount: threadCount, includeMipmaps: false, useAlphaWeight: useAlphaWeight); + } + } + else if (inputTexture is Texture2D tex2d) + { + raw = AstcCpuBackend.CompressTextureSync(tex2d, textureType, blockSize, quality, threadCount: threadCount, includeMipmaps: false, useAlphaWeight: useAlphaWeight); + } + else + { + Debug.LogError("CPU backend only supports readable Texture2D. Use EncodeBackend.Gpu or EncodeBackend.Auto for RenderTexture inputs."); + return null; + } + + using (raw) + { + return BuildAstcFileBytes(raw, blockSize, inputTexture.width, inputTexture.height); + } + } + + /// + /// Encodes any 2D Texture to .astc file bytes (mip 0 only) using an struct. + /// + public static byte[] EncodeToASTC(this Texture inputTexture, AstcCompressOptions options) + { + if (inputTexture == null) + { + Debug.LogError("Input texture is null."); + return null; + } + + AstcRaw raw = null; + if (ShouldUseGpu(inputTexture, options.Backend)) + { + raw = AstcGpuBackend.CompressTextureSync(inputTexture, options.TextureType, options.BlockSize, options.Quality, includeMipmaps: false, useAlphaWeight: options.UseAlphaWeight); + if (raw == null && CanFallbackToCpu(inputTexture, options.Backend)) + { + raw = AstcCpuBackend.CompressTextureSync((Texture2D)inputTexture, options.TextureType, options.BlockSize, options.Quality, options.ThreadCount, includeMipmaps: false, options.UseAlphaWeight, options.UsePerceptual, options.AlphaScaleRadius); + } + } + else if (inputTexture is Texture2D tex2d) + { + raw = AstcCpuBackend.CompressTextureSync(tex2d, options.TextureType, options.BlockSize, options.Quality, options.ThreadCount, includeMipmaps: false, options.UseAlphaWeight, options.UsePerceptual, options.AlphaScaleRadius); + } + else + { + Debug.LogError("CPU backend only supports readable Texture2D. Use EncodeBackend.Gpu or EncodeBackend.Auto for RenderTexture inputs."); + return null; + } + + using (raw) + { + return BuildAstcFileBytes(raw, options.BlockSize, inputTexture.width, inputTexture.height); + } + } + + /// + /// Asynchronously encodes any 2D Texture (Texture2D or RenderTexture) to .astc file bytes (mip 0 only). + /// Uses AsyncGPUReadback on GPU backend or background thread(s) on CPU backend. + /// + public static async Task EncodeToASTCAsync( + this Texture inputTexture, + TextureType textureType = TextureType.Default, + BlockSize blockSize = BlockSize.ASTC_6x6, + CompressQuality quality = CompressQuality.Medium, + int threadCount = 0, + bool useAlphaWeight = false, + CancellationToken cancellationToken = default, + EncodeBackend backend = EncodeBackend.Auto) + { + if (cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(cancellationToken); + } + + if (inputTexture == null) + { + Debug.LogError("Input texture is null."); + return null; + } + + int width = inputTexture.width; + int height = inputTexture.height; + + AstcRaw raw; + if (ShouldUseGpu(inputTexture, backend)) + { + raw = await AstcGpuBackend.CompressTextureAsync(inputTexture, textureType, blockSize, quality, includeMipmaps: false, useAlphaWeight: useAlphaWeight, cancellationToken: cancellationToken); + if (raw == null && CanFallbackToCpu(inputTexture, backend)) + { + raw = await AstcCpuBackend.CompressTextureAsync((Texture2D)inputTexture, textureType, blockSize, quality, threadCount: threadCount, includeMipmaps: false, useAlphaWeight: useAlphaWeight, cancellationToken: cancellationToken); + } + } + else if (inputTexture is Texture2D tex2d) + { + raw = await AstcCpuBackend.CompressTextureAsync(tex2d, textureType, blockSize, quality, threadCount: threadCount, includeMipmaps: false, useAlphaWeight: useAlphaWeight, cancellationToken: cancellationToken); + } + else + { + Debug.LogError("CPU backend only supports readable Texture2D. Use EncodeBackend.Gpu or EncodeBackend.Auto for RenderTexture inputs."); + return null; + } + + using (raw) + { + return BuildAstcFileBytes(raw, blockSize, width, height); + } + } + + /// + /// Asynchronously encodes any 2D Texture to .astc file bytes (mip 0 only) using an struct. + /// + public static async Task EncodeToASTCAsync(this Texture inputTexture, AstcCompressOptions options, CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(cancellationToken); + } + + if (inputTexture == null) + { + Debug.LogError("Input texture is null."); + return null; + } + + int width = inputTexture.width; + int height = inputTexture.height; + + AstcRaw raw; + if (ShouldUseGpu(inputTexture, options.Backend)) + { + raw = await AstcGpuBackend.CompressTextureAsync(inputTexture, options.TextureType, options.BlockSize, options.Quality, includeMipmaps: false, useAlphaWeight: options.UseAlphaWeight, cancellationToken: cancellationToken); + if (raw == null && CanFallbackToCpu(inputTexture, options.Backend)) + { + raw = await AstcCpuBackend.CompressTextureAsync((Texture2D)inputTexture, options.TextureType, options.BlockSize, options.Quality, options.ThreadCount, includeMipmaps: false, options.UseAlphaWeight, cancellationToken, options.UsePerceptual, options.AlphaScaleRadius); + } + } + else if (inputTexture is Texture2D tex2d) + { + raw = await AstcCpuBackend.CompressTextureAsync(tex2d, options.TextureType, options.BlockSize, options.Quality, options.ThreadCount, includeMipmaps: false, options.UseAlphaWeight, cancellationToken, options.UsePerceptual, options.AlphaScaleRadius); + } + else + { + Debug.LogError("CPU backend only supports readable Texture2D. Use EncodeBackend.Gpu or EncodeBackend.Auto for RenderTexture inputs."); + return null; + } + + using (raw) + { + return BuildAstcFileBytes(raw, options.BlockSize, width, height); + } + } + + /// + /// Software-decompresses raw ASTC block data (mip 0) into 4-channel RGBA bytes using the native CPU astc-encoder library. + /// Set to 8 (RGBA8), 16 (RGBA16F), or 32 (RGBA32F). + /// + public static byte[] Decompress( + AstcRaw raw, + int width, + int height, + BlockSize blockSize, + bool srgb = false, + bool isHdr = false, + int outputBitness = 8, + int threadCount = 1) + { + if (raw == null) + return null; + + raw.ThrowIfDisposed(); + return AstcCpuBackend.DecompressToBytes(raw.Data, raw.Length, width, height, blockSize, srgb, isHdr, outputBitness, threadCount); + } + + /// + /// Software-decompresses raw ASTC block bytes (mip 0) into 4-channel RGBA bytes using the native CPU astc-encoder library. + /// Set to 8 (RGBA8), 16 (RGBA16F), or 32 (RGBA32F). + /// + public static byte[] Decompress( + byte[] compressedBytes, + int width, + int height, + BlockSize blockSize, + bool srgb = false, + bool isHdr = false, + int outputBitness = 8, + int threadCount = 1) + { + if (compressedBytes == null) + return null; + + return AstcCpuBackend.DecompressToBytes(compressedBytes, 0, compressedBytes.Length, width, height, blockSize, srgb, isHdr, outputBitness, threadCount); + } + + /// + /// Software-decompresses raw ASTC block data (mip 0) into an uncompressed RGBA (RGBA8 for LDR, RGBA16F for HDR). + /// Useful as a fallback on platforms without hardware ASTC support or for verification. + /// + public static Texture2D DecompressToTexture( + AstcRaw raw, + int width, + int height, + BlockSize blockSize, + bool srgb = false, + bool isHdr = false, + int threadCount = 1, + bool makeNoLongerReadable = false) + { + if (raw == null) + return null; + + raw.ThrowIfDisposed(); + return AstcCpuBackend.DecompressToTexture(raw.Data, raw.Length, width, height, blockSize, srgb, isHdr, threadCount, makeNoLongerReadable); + } + + /// + /// Parses a standard .astc file (16-byte header + ASTC blocks) and software-decompresses it into an uncompressed RGBA . + /// + public static Texture2D DecompressAstcFile( + byte[] astcFileBytes, + bool srgb = false, + bool isHdr = false, + int threadCount = 1, + bool makeNoLongerReadable = false) + { + return AstcCpuBackend.DecompressAstcFileToTexture(astcFileBytes, srgb, isHdr, threadCount, makeNoLongerReadable); + } + + /// + /// Encodes any 2D Texture (including optional mipmaps) into a standard Khronos KTX v1 container byte array. + /// Unlike , KTX v1 preserves full mipmap chains and exact sRGB/HDR metadata. + /// + public static byte[] EncodeToKTX(this Texture inputTexture, AstcCompressOptions options) + { + if (inputTexture == null) + { + Debug.LogError("Input texture is null."); + return null; + } + + int width = inputTexture.width; + int height = inputTexture.height; + GraphicsFormat targetFormat = GetTargetAstcFormat(inputTexture.graphicsFormat, options.BlockSize, options.TextureType); + + using AstcRaw raw = inputTexture.CompressTexture(options); + if (raw == null) + return null; + + int mipCount = AstcKtxContainer.InferMipCount(raw.Length, width, height, options.BlockSize); + if (mipCount <= 0) + return null; + + return AstcKtxContainer.Encode(raw, width, height, mipCount, targetFormat); + } + + /// + /// Asynchronously encodes any 2D Texture (including optional mipmaps) into a standard Khronos KTX v1 container byte array. + /// + public static async Task EncodeToKTXAsync(this Texture inputTexture, AstcCompressOptions options, CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) + throw new OperationCanceledException(cancellationToken); + + if (inputTexture == null) + { + Debug.LogError("Input texture is null."); + return null; + } + + int width = inputTexture.width; + int height = inputTexture.height; + GraphicsFormat targetFormat = GetTargetAstcFormat(inputTexture.graphicsFormat, options.BlockSize, options.TextureType); + + using AstcRaw raw = await inputTexture.CompressTextureAsync(options, cancellationToken); + if (raw == null) + return null; + + cancellationToken.ThrowIfCancellationRequested(); + int mipCount = AstcKtxContainer.InferMipCount(raw.Length, width, height, options.BlockSize); + if (mipCount <= 0) + return null; + + return AstcKtxContainer.Encode(raw, width, height, mipCount, targetFormat); + } + + /// + /// Loads a standard Khronos KTX v1 ASTC container into a GPU-ready (with full mipmap chain). + /// Automatically falls back to CPU software decompression on devices without hardware ASTC support. + /// + public static Texture2D LoadFromKTX(byte[] ktxBytes, bool makeNoLongerReadable = true, string textureName = null) + { + return AstcKtxContainer.LoadTexture(ktxBytes, makeNoLongerReadable, textureName); + } + + private static byte[] BuildAstcFileBytes(AstcRaw raw, BlockSize blockSize, int width, int height) + { + if (raw == null) + { + return null; + } + + raw.ThrowIfDisposed(); + + byte[] output = new byte[AstcHeader.HeaderSize + raw.Length]; + GetBlockSize(blockSize, out uint dimX, out uint dimY, out uint dimZ); + AstcHeader.WriteTo(output, 0, dimX, dimY, dimZ, width, height, 1); + Marshal.Copy(raw.Data, output, AstcHeader.HeaderSize, raw.Length); + return output; + } } } - diff --git a/Assets/ASTC Encoder/Runtime/Gpu.meta b/Assets/ASTC Encoder/Runtime/Gpu.meta new file mode 100644 index 0000000..3860cd8 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Gpu.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: b78598bd63708a7d2834c49d02094948 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/Gpu/AstcGpuBackend.cs b/Assets/ASTC Encoder/Runtime/Gpu/AstcGpuBackend.cs new file mode 100644 index 0000000..33c24bc --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Gpu/AstcGpuBackend.cs @@ -0,0 +1,1539 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; +using UnityEngine; +using UnityEngine.Experimental.Rendering; +using UnityEngine.Rendering; + +namespace Aperture.Astcenc.Runtime +{ + internal static class AstcGpuBackend + { + private const string k_ShaderResourcePath = "AstcGpuEncoder"; + private const string k_MipShaderResourcePath = "AstcGpuMipGenerator"; + private const int k_BytesPerBlock = 16; + + private const uint k_ModeLdrRgb = 0u; + private const uint k_ModeLdrRgba = 1u; + private const uint k_ModeLdrNormal = 2u; + private const uint k_ModeHdrRgb = 3u; + private const uint k_ModeHdrRgba = 4u; + + private static readonly int s_PropSourceTex = Shader.PropertyToID("_AstcSourceTex"); + private static readonly int s_PropDestTex = Shader.PropertyToID("_AstcDestTex"); + private static readonly int s_PropDestBuffer = Shader.PropertyToID("_AstcDestBuffer"); + private static readonly int s_PropSrcWidth = Shader.PropertyToID("_AstcSrcWidth"); + private static readonly int s_PropSrcHeight = Shader.PropertyToID("_AstcSrcHeight"); + private static readonly int s_PropMipLevel = Shader.PropertyToID("_AstcMipLevel"); + private static readonly int s_PropBlockCountX = Shader.PropertyToID("_AstcBlockCountX"); + private static readonly int s_PropBlockCountY = Shader.PropertyToID("_AstcBlockCountY"); + private static readonly int s_PropBufferBlockOffset = Shader.PropertyToID("_AstcBufferBlockOffset"); + private static readonly int s_PropMode = Shader.PropertyToID("_AstcMode"); + private static readonly int s_PropIsSRGB = Shader.PropertyToID("_AstcIsSRGB"); + private static readonly int s_PropUseAlphaWeight = Shader.PropertyToID("_AstcUseAlphaWeight"); + private static readonly int s_PropQuality = Shader.PropertyToID("_AstcQuality"); + + private static readonly int s_PropMipSrcTex = Shader.PropertyToID("_MipSrcTex"); + private static readonly int s_PropMipDstTex = Shader.PropertyToID("_MipDstTex"); + private static readonly int s_PropMipSrcWidth = Shader.PropertyToID("_MipSrcWidth"); + private static readonly int s_PropMipSrcHeight = Shader.PropertyToID("_MipSrcHeight"); + private static readonly int s_PropMipDstWidth = Shader.PropertyToID("_MipDstWidth"); + private static readonly int s_PropMipDstHeight = Shader.PropertyToID("_MipDstHeight"); + private static readonly int s_PropMipSrcLevel = Shader.PropertyToID("_MipSrcLevel"); + private static readonly int s_PropMipIsSRGBSrc = Shader.PropertyToID("_MipIsSRGBSrc"); + private static readonly int s_PropMipIsAlphaWeighted = Shader.PropertyToID("_MipIsAlphaWeighted"); + private static readonly int s_PropMipIsHdr = Shader.PropertyToID("_MipIsHdr"); + + private static ComputeShader s_Shader; + private static bool s_ShaderLoadAttempted; + private static int[] s_TexKernels; + private static int[] s_BufKernels; + private static int[] s_TexFastKernels; + private static int[] s_BufFastKernels; + + private static ComputeShader s_MipShader; + private static bool s_MipShaderLoadAttempted; + private static int s_MipKernelColor; + private static int s_MipKernelNormal; + + private static readonly int s_PropTempBlocksRT = Shader.PropertyToID("_AstcTempBlocksRT"); + private static readonly int s_PropTempSliceRT = Shader.PropertyToID("_AstcTempSliceRT"); + private static readonly int s_PropTempMipA = Shader.PropertyToID("_AstcTempMipA"); + private static readonly int s_PropTempMipB = Shader.PropertyToID("_AstcTempMipB"); + + private static bool IsLoadStoreSupported(GraphicsFormat format) + { +#if UNITY_2023_2_OR_NEWER + return SystemInfo.IsFormatSupported(format, GraphicsFormatUsage.LoadStore); +#else + return SystemInfo.IsFormatSupported(format, FormatUsage.LoadStore); +#endif + } + + internal static bool IsSampleSupported(GraphicsFormat format) + { +#if UNITY_2023_2_OR_NEWER + return SystemInfo.IsFormatSupported(format, GraphicsFormatUsage.Sample); +#else + return SystemInfo.IsFormatSupported(format, FormatUsage.Sample); +#endif + } + + internal static bool IsSupported + { + get + { + if (!SystemInfo.supportsComputeShaders) + return false; + + if (!IsLoadStoreSupported(GraphicsFormat.R32G32B32A32_UInt)) + return false; + + return EnsureShaderLoaded(); + } + } + + internal static bool IsInputSupported(Texture texture) + { + return IsInputSupportedCore(texture, allowSliced: false); + } + + internal static bool IsSliceableInputSupported(Texture texture) + { + return IsInputSupportedCore(texture, allowSliced: true); + } + + /// + /// Returns true for any floating-point / HDR (32-bit float, 16-bit half float, + /// packed unsigned float, or compressed HDR formats such as ASTC UFloat / BC6H). + /// Unity's only matches 32-bit float formats and returns + /// false for 16-bit half-float (R16*_SFloat) and packed/compressed UFloat formats. + /// + internal static bool IsFloatingPointFormat(GraphicsFormat format) + { + if (GraphicsFormatUtility.IsFloatFormat(format) || GraphicsFormatUtility.IsHalfFormat(format)) + return true; + + switch (format) + { + case GraphicsFormat.B10G11R11_UFloatPack32: + case GraphicsFormat.E5B9G9R9_UFloatPack32: + case GraphicsFormat.RGB_BC6H_UFloat: + case GraphicsFormat.RGB_BC6H_SFloat: + case GraphicsFormat.RGBA_ASTC4X4_UFloat: + case GraphicsFormat.RGBA_ASTC5X5_UFloat: + case GraphicsFormat.RGBA_ASTC6X6_UFloat: + case GraphicsFormat.RGBA_ASTC8X8_UFloat: + case GraphicsFormat.RGBA_ASTC10X10_UFloat: + case GraphicsFormat.RGBA_ASTC12X12_UFloat: + return true; + default: + return false; + } + } + + private static bool IsInputSupportedCore(Texture texture, bool allowSliced) + { + if (texture == null || texture.width <= 0 || texture.height <= 0) + return false; + + if (texture.dimension != TextureDimension.Tex2D) + { + if (!allowSliced || (texture.dimension != TextureDimension.Tex2DArray && texture.dimension != TextureDimension.Cube)) + return false; + } + + if (texture is RenderTexture rt && rt.antiAliasing > 1) + return false; + + GraphicsFormat format = texture.graphicsFormat; + if (format == GraphicsFormat.None) + return false; + + // _AstcSourceTex is bound as Texture2D; depth/stencil/integer formats cannot be loaded as float4, + // and signed normalized (SNorm) formats would have negative values silently clamped to 0 by UNorm ASTC. + if (GraphicsFormatUtility.IsDepthFormat(format) + || GraphicsFormatUtility.IsStencilFormat(format) + || GraphicsFormatUtility.IsIntegerFormat(format) + || (!IsFloatingPointFormat(format) && GraphicsFormatUtility.IsSignedFormat(format))) + { + return false; + } + + return true; + } + + internal static bool SupportsDirectCopy(BlockSize blockSize, bool srgb, bool isHdr) + { + if (!IsSupported) + return false; + + if ((SystemInfo.copyTextureSupport & CopyTextureSupport.RTToTexture) == 0) + return false; + + GraphicsFormat astcFormat = GetAstcGraphicsFormat(blockSize, srgb, isHdr); + return IsSampleSupported(astcFormat); + } + + internal static bool CanUseDirectCopy(int width, int height, int mipCount, BlockSize blockSize, GraphicsFormat astcFormat) + { + if (width <= 0 || height <= 0 || mipCount <= 0) + return false; + + if ((SystemInfo.copyTextureSupport & CopyTextureSupport.RTToTexture) == 0) + return false; + + if (!IsSampleSupported(astcFormat)) + return false; + + if (!Encoder.GetBlockSize(blockSize, out _, out _, out _)) + return false; + + // CommandBuffer.CopyTexture from R32G32B32A32_UInt (ceil(mipW/bx) x ceil(mipH/by)) to ASTC + // operates on physical block dimensions on Metal, Vulkan, D3D12, and OpenGL ES 3.1+, + // supporting ASTC_6x6 on POT textures and full mip chains down to 1x1 without CPU readback. + return true; + } + + internal static GraphicsFormat ResolveTargetAstcFormat(GraphicsFormat sourceFormat, TextureType textureType, BlockSize blockSize, out bool isSRGB, out bool isHdr) + { + if (textureType == TextureType.Normal) + { + // Tangent-space normal maps always emit linear UNorm ASTC regardless of sRGB or float source format. + isSRGB = false; + isHdr = false; + return GetAstcGraphicsFormat(blockSize, false, false); + } + + bool sourceIsSRGB = GraphicsFormatUtility.IsSRGBFormat(sourceFormat); + isHdr = !sourceIsSRGB && IsFloatingPointFormat(sourceFormat); + isSRGB = sourceIsSRGB; + return GetAstcGraphicsFormat(blockSize, isSRGB, isHdr); + } + + internal static GraphicsFormat GetAstcGraphicsFormat(BlockSize blockSize, bool srgb, bool isHdr) + { + if (isHdr) + { + return blockSize switch + { + BlockSize.ASTC_4x4 => GraphicsFormat.RGBA_ASTC4X4_UFloat, + BlockSize.ASTC_5x5 => GraphicsFormat.RGBA_ASTC5X5_UFloat, + BlockSize.ASTC_6x6 => GraphicsFormat.RGBA_ASTC6X6_UFloat, + BlockSize.ASTC_8x8 => GraphicsFormat.RGBA_ASTC8X8_UFloat, + BlockSize.ASTC_10x10 => GraphicsFormat.RGBA_ASTC10X10_UFloat, + BlockSize.ASTC_12x12 => GraphicsFormat.RGBA_ASTC12X12_UFloat, + _ => throw new ArgumentException($"Unsupported ASTC block size: {blockSize}", nameof(blockSize)), + }; + } + + if (srgb) + { + return blockSize switch + { + BlockSize.ASTC_4x4 => GraphicsFormat.RGBA_ASTC4X4_SRGB, + BlockSize.ASTC_5x5 => GraphicsFormat.RGBA_ASTC5X5_SRGB, + BlockSize.ASTC_6x6 => GraphicsFormat.RGBA_ASTC6X6_SRGB, + BlockSize.ASTC_8x8 => GraphicsFormat.RGBA_ASTC8X8_SRGB, + BlockSize.ASTC_10x10 => GraphicsFormat.RGBA_ASTC10X10_SRGB, + BlockSize.ASTC_12x12 => GraphicsFormat.RGBA_ASTC12X12_SRGB, + _ => throw new ArgumentException($"Unsupported ASTC block size: {blockSize}", nameof(blockSize)), + }; + } + + return blockSize switch + { + BlockSize.ASTC_4x4 => GraphicsFormat.RGBA_ASTC4X4_UNorm, + BlockSize.ASTC_5x5 => GraphicsFormat.RGBA_ASTC5X5_UNorm, + BlockSize.ASTC_6x6 => GraphicsFormat.RGBA_ASTC6X6_UNorm, + BlockSize.ASTC_8x8 => GraphicsFormat.RGBA_ASTC8X8_UNorm, + BlockSize.ASTC_10x10 => GraphicsFormat.RGBA_ASTC10X10_UNorm, + BlockSize.ASTC_12x12 => GraphicsFormat.RGBA_ASTC12X12_UNorm, + _ => throw new ArgumentException($"Unsupported ASTC block size: {blockSize}", nameof(blockSize)), + }; + } + + private static int BlockSizeToSlot(BlockSize blockSize) + { + return blockSize switch + { + BlockSize.ASTC_4x4 => 0, + BlockSize.ASTC_5x5 => 1, + BlockSize.ASTC_6x6 => 2, + BlockSize.ASTC_8x8 => 3, + BlockSize.ASTC_10x10 => 4, + BlockSize.ASTC_12x12 => 5, + _ => -1, + }; + } + + private static uint MapQualityTier(CompressQuality quality) + { + return quality switch + { + CompressQuality.Fastest => 0u, + CompressQuality.Fast => 0u, + CompressQuality.Medium => 1u, + CompressQuality.Thorough => 2u, + CompressQuality.VeryThorough => 2u, + CompressQuality.Exhaustive => 2u, + _ => 0u, + }; + } + + private static int GetDispatchGroupsY(int blockCountY, BlockSize blockSize) + { + return (blockSize == BlockSize.ASTC_8x8 || blockSize == BlockSize.ASTC_10x10 || blockSize == BlockSize.ASTC_12x12) + ? (blockCountY + 3) >> 2 + : (blockCountY + 7) >> 3; + } + + private static int GetTexKernel(int slot, uint qualityTier) + { + return qualityTier == 0u ? s_TexFastKernels[slot] : s_TexKernels[slot]; + } + + private static int GetBufKernel(int slot, uint qualityTier) + { + return qualityTier == 0u ? s_BufFastKernels[slot] : s_BufKernels[slot]; + } + + private static uint ResolveShaderMode(GraphicsFormat sourceFormat, TextureType textureType, out bool isSRGB, out bool isHdr) + { + isSRGB = GraphicsFormatUtility.IsSRGBFormat(sourceFormat); + + if (textureType == TextureType.Normal) + { + isHdr = false; + return k_ModeLdrNormal; + } + + isHdr = !isSRGB && IsFloatingPointFormat(sourceFormat); + bool hasAlpha = GraphicsFormatUtility.HasAlphaChannel(sourceFormat); + if (isHdr) + { + return hasAlpha ? k_ModeHdrRgba : k_ModeHdrRgb; + } + + return hasAlpha ? k_ModeLdrRgba : k_ModeLdrRgb; + } + + private static bool EnsureShaderLoaded() + { + if (s_Shader != null) + return true; + + if (s_ShaderLoadAttempted) + return false; + + s_ShaderLoadAttempted = true; + s_Shader = Resources.Load(k_ShaderResourcePath); + if (s_Shader == null) + { + Debug.LogError($"Failed to load ComputeShader from Resources/{k_ShaderResourcePath}.compute."); + return false; + } + + s_TexKernels = new int[6] + { + s_Shader.FindKernel("EncodeTex4x4"), + s_Shader.FindKernel("EncodeTex5x5"), + s_Shader.FindKernel("EncodeTex6x6"), + s_Shader.FindKernel("EncodeTex8x8"), + s_Shader.FindKernel("EncodeTex10x10"), + s_Shader.FindKernel("EncodeTex12x12"), + }; + + s_BufKernels = new int[6] + { + s_Shader.FindKernel("EncodeBuf4x4"), + s_Shader.FindKernel("EncodeBuf5x5"), + s_Shader.FindKernel("EncodeBuf6x6"), + s_Shader.FindKernel("EncodeBuf8x8"), + s_Shader.FindKernel("EncodeBuf10x10"), + s_Shader.FindKernel("EncodeBuf12x12"), + }; + + s_TexFastKernels = new int[6] + { + s_Shader.FindKernel("EncodeTex4x4Fast"), + s_Shader.FindKernel("EncodeTex5x5Fast"), + s_Shader.FindKernel("EncodeTex6x6Fast"), + s_Shader.FindKernel("EncodeTex8x8Fast"), + s_Shader.FindKernel("EncodeTex10x10Fast"), + s_Shader.FindKernel("EncodeTex12x12Fast"), + }; + + s_BufFastKernels = new int[6] + { + s_Shader.FindKernel("EncodeBuf4x4Fast"), + s_Shader.FindKernel("EncodeBuf5x5Fast"), + s_Shader.FindKernel("EncodeBuf6x6Fast"), + s_Shader.FindKernel("EncodeBuf8x8Fast"), + s_Shader.FindKernel("EncodeBuf10x10Fast"), + s_Shader.FindKernel("EncodeBuf12x12Fast"), + }; + + return true; + } + + private static RenderTextureDescriptor CreateBlockRTDescriptor(int blockW, int blockH) + { + return new RenderTextureDescriptor(blockW, blockH, GraphicsFormat.R32G32B32A32_UInt, 0) + { + enableRandomWrite = true, + useMipMap = false, + autoGenerateMips = false, + msaaSamples = 1, + }; + } + + internal static void Preload(BlockSize blockSize) + { + if (!IsSupported) + return; + + int slot = BlockSizeToSlot(blockSize); + if (slot < 0) + return; + + var dummySrc = new Texture2D(4, 4, GraphicsFormat.R8G8B8A8_UNorm, TextureCreationFlags.None); + RenderTexture rt = null; + ComputeBuffer buf = null; + try + { + rt = RenderTexture.GetTemporary(CreateBlockRTDescriptor(1, 1)); + rt.Create(); + buf = new ComputeBuffer(1, k_BytesPerBlock, ComputeBufferType.Structured); + + // Warm up both Fast and Full kernels for Texture and Buffer outputs to prevent first-use PSO stalls. + int texFastKernel = s_TexFastKernels[slot]; + s_Shader.SetTexture(texFastKernel, s_PropSourceTex, dummySrc); + s_Shader.SetTexture(texFastKernel, s_PropDestTex, rt); + SetCommonUniforms(s_Shader, 4, 4, 0, 1, 1, 0, k_ModeLdrRgb, false, false, 0u); + s_Shader.Dispatch(texFastKernel, 1, 1, 1); + + int bufFastKernel = s_BufFastKernels[slot]; + s_Shader.SetTexture(bufFastKernel, s_PropSourceTex, dummySrc); + s_Shader.SetBuffer(bufFastKernel, s_PropDestBuffer, buf); + SetCommonUniforms(s_Shader, 4, 4, 0, 1, 1, 0, k_ModeLdrRgb, false, false, 0u); + s_Shader.Dispatch(bufFastKernel, 1, 1, 1); + + int texKernel = s_TexKernels[slot]; + s_Shader.SetTexture(texKernel, s_PropSourceTex, dummySrc); + s_Shader.SetTexture(texKernel, s_PropDestTex, rt); + SetCommonUniforms(s_Shader, 4, 4, 0, 1, 1, 0, k_ModeLdrRgb, false, false, 1u); + s_Shader.Dispatch(texKernel, 1, 1, 1); + + int bufKernel = s_BufKernels[slot]; + s_Shader.SetTexture(bufKernel, s_PropSourceTex, dummySrc); + s_Shader.SetBuffer(bufKernel, s_PropDestBuffer, buf); + SetCommonUniforms(s_Shader, 4, 4, 0, 1, 1, 0, k_ModeLdrRgb, false, false, 1u); + s_Shader.Dispatch(bufKernel, 1, 1, 1); + + if (EnsureMipShaderLoaded()) + { + RenderTexture mipRt = RenderTexture.GetTemporary(CreateMipRTDescriptor(2, 2, useFloat16: false)); + try + { + mipRt.Create(); + s_MipShader.SetInt(s_PropMipSrcWidth, 4); + s_MipShader.SetInt(s_PropMipSrcHeight, 4); + s_MipShader.SetInt(s_PropMipDstWidth, 2); + s_MipShader.SetInt(s_PropMipDstHeight, 2); + s_MipShader.SetInt(s_PropMipSrcLevel, 0); + s_MipShader.SetInt(s_PropMipIsSRGBSrc, 0); + s_MipShader.SetInt(s_PropMipIsAlphaWeighted, 0); + s_MipShader.SetInt(s_PropMipIsHdr, 0); + + s_MipShader.SetTexture(s_MipKernelColor, s_PropMipSrcTex, dummySrc); + s_MipShader.SetTexture(s_MipKernelColor, s_PropMipDstTex, mipRt); + s_MipShader.Dispatch(s_MipKernelColor, 1, 1, 1); + + s_MipShader.SetTexture(s_MipKernelNormal, s_PropMipSrcTex, dummySrc); + s_MipShader.SetTexture(s_MipKernelNormal, s_PropMipDstTex, mipRt); + s_MipShader.Dispatch(s_MipKernelNormal, 1, 1, 1); + } + finally + { + RenderTexture.ReleaseTemporary(mipRt); + } + } + } + finally + { + if (buf != null) + buf.Release(); + if (rt != null) + RenderTexture.ReleaseTemporary(rt); + UnityEngine.Object.DestroyImmediate(dummySrc); + } + } + + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] + private static void ResetStatics() + { + ReleaseCache(); + Application.quitting -= ReleaseCache; + Application.quitting += ReleaseCache; + } + + /// + /// Drops the cached ComputeShader / kernel references so they are reloaded on next use. + /// Temporary block render targets are pooled per call (RenderTexture.GetTemporary / CommandBuffer.GetTemporaryRT), + /// so there is no long-lived GPU memory held by this backend. + /// + private static bool EnsureMipShaderLoaded() + { + if (s_MipShader != null) + return true; + + if (s_MipShaderLoadAttempted) + return false; + + s_MipShaderLoadAttempted = true; + s_MipShader = Resources.Load(k_MipShaderResourcePath); + if (s_MipShader == null) + { + Debug.LogError($"Failed to load ComputeShader from Resources/{k_MipShaderResourcePath}.compute."); + return false; + } + + s_MipKernelColor = s_MipShader.FindKernel("DownsampleColor"); + s_MipKernelNormal = s_MipShader.FindKernel("DownsampleNormal"); + return true; + } + + internal static int CalculateFullMipCount(int width, int height) + { + int maxDim = Math.Max(1, Math.Max(width, height)); + int count = 1; + while (maxDim > 1) + { + maxDim >>= 1; + count++; + } + return count; + } + + private static int ResolveEffectiveMipCount(Texture source, bool includeMipmaps, bool generateMipmaps, out bool willGenerateMips) + { + willGenerateMips = false; + int srcMips = Math.Max(1, source.mipmapCount); + if (generateMipmaps && srcMips <= 1 && (source.width > 1 || source.height > 1) && EnsureMipShaderLoaded()) + { + bool isHdrSrc = IsFloatingPointFormat(source.graphicsFormat); + if (!isHdrSrc || IsLoadStoreSupported(GraphicsFormat.R16G16B16A16_SFloat)) + { + willGenerateMips = true; + return CalculateFullMipCount(source.width, source.height); + } + } + + return includeMipmaps ? srcMips : 1; + } + + private static RenderTextureDescriptor CreateMipRTDescriptor(int width, int height, bool useFloat16) + { + GraphicsFormat fmt = useFloat16 && IsLoadStoreSupported(GraphicsFormat.R16G16B16A16_SFloat) + ? GraphicsFormat.R16G16B16A16_SFloat + : GraphicsFormat.R8G8B8A8_UNorm; + + return new RenderTextureDescriptor(width, height, fmt, 0) + { + enableRandomWrite = true, + useMipMap = false, + autoGenerateMips = false, + msaaSamples = 1, + }; + } + + internal static void ReleaseCache() + { + s_Shader = null; + s_ShaderLoadAttempted = false; + s_TexKernels = null; + s_BufKernels = null; + s_TexFastKernels = null; + s_BufFastKernels = null; + s_MipShader = null; + s_MipShaderLoadAttempted = false; + } + + private static void SetCommonUniforms( + ComputeShader shader, + int srcWidth, int srcHeight, int mipLevel, + int blockCountX, int blockCountY, int bufferBlockOffset, + uint mode, bool isSRGB, bool useAlphaWeight, uint qualityTier) + { + shader.SetInt(s_PropSrcWidth, srcWidth); + shader.SetInt(s_PropSrcHeight, srcHeight); + shader.SetInt(s_PropMipLevel, mipLevel); + shader.SetInt(s_PropBlockCountX, blockCountX); + shader.SetInt(s_PropBlockCountY, blockCountY); + shader.SetInt(s_PropBufferBlockOffset, bufferBlockOffset); + shader.SetInt(s_PropMode, (int)mode); + shader.SetInt(s_PropIsSRGB, isSRGB ? 1 : 0); + shader.SetInt(s_PropUseAlphaWeight, useAlphaWeight ? 1 : 0); + shader.SetInt(s_PropQuality, (int)qualityTier); + } + + private static void SetCommonUniforms( + CommandBuffer cmd, + ComputeShader shader, + int srcWidth, int srcHeight, int mipLevel, + int blockCountX, int blockCountY, int bufferBlockOffset, + uint mode, bool isSRGB, bool useAlphaWeight, uint qualityTier) + { + cmd.SetComputeIntParam(shader, s_PropSrcWidth, srcWidth); + cmd.SetComputeIntParam(shader, s_PropSrcHeight, srcHeight); + cmd.SetComputeIntParam(shader, s_PropMipLevel, mipLevel); + cmd.SetComputeIntParam(shader, s_PropBlockCountX, blockCountX); + cmd.SetComputeIntParam(shader, s_PropBlockCountY, blockCountY); + cmd.SetComputeIntParam(shader, s_PropBufferBlockOffset, bufferBlockOffset); + cmd.SetComputeIntParam(shader, s_PropMode, (int)mode); + cmd.SetComputeIntParam(shader, s_PropIsSRGB, isSRGB ? 1 : 0); + cmd.SetComputeIntParam(shader, s_PropUseAlphaWeight, useAlphaWeight ? 1 : 0); + cmd.SetComputeIntParam(shader, s_PropQuality, (int)qualityTier); + } + + private static int CalculateTotalBlocks(int width, int height, int mipCount, uint blockX, uint blockY) + { + int total = 0; + for (int i = 0; i < mipCount; i++) + { + int mipW = Math.Max(1, width >> i); + int mipH = Math.Max(1, height >> i); + int bx = (mipW + (int)blockX - 1) / (int)blockX; + int by = (mipH + (int)blockY - 1) / (int)blockY; + total += bx * by; + } + return total; + } + + private static ComputeBuffer DispatchAllMipsToBuffer( + Texture source, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + int mipCount, + bool useAlphaWeight, + bool generateMipmaps, + out int totalBytes) + { + totalBytes = 0; + if (!IsSupported || !IsInputSupported(source)) + return null; + + int slot = BlockSizeToSlot(blockSize); + if (slot < 0 || !Encoder.GetBlockSize(blockSize, out uint bx, out uint by, out _)) + return null; + + int totalBlocks = CalculateTotalBlocks(source.width, source.height, mipCount, bx, by); + if (totalBlocks <= 0) + return null; + + uint mode = ResolveShaderMode(source.graphicsFormat, textureType, out bool isSRGB, out bool isHdr); + uint qualityTier = MapQualityTier(quality); + int kernel = GetBufKernel(slot, qualityTier); + + bool useFloat16Mip = (isHdr || isSRGB) && textureType != TextureType.Normal; + int mipKernel = textureType == TextureType.Normal ? s_MipKernelNormal : s_MipKernelColor; + + var buffer = new ComputeBuffer(totalBlocks, k_BytesPerBlock, ComputeBufferType.Structured); + RenderTexture prevMipRT = null; + RenderTexture currMipRT = null; + try + { + int blockOffset = 0; + for (int mip = 0; mip < mipCount; mip++) + { + int mipW = Math.Max(1, source.width >> mip); + int mipH = Math.Max(1, source.height >> mip); + int blockCountX = (mipW + (int)bx - 1) / (int)bx; + int blockCountY = (mipH + (int)by - 1) / (int)by; + + Texture encodeSrc = source; + int encodeSrcMip = mip; + bool encodeIsSRGB = isSRGB; + + if (generateMipmaps && mip > 0) + { + int prevW = Math.Max(1, source.width >> (mip - 1)); + int prevH = Math.Max(1, source.height >> (mip - 1)); + Texture downSrc = (mip == 1) ? source : (Texture)prevMipRT; + bool downSrcIsSRGB = (mip == 1) && isSRGB; + + currMipRT = RenderTexture.GetTemporary(CreateMipRTDescriptor(mipW, mipH, useFloat16Mip)); + currMipRT.Create(); + + s_MipShader.SetTexture(mipKernel, s_PropMipSrcTex, downSrc); + s_MipShader.SetTexture(mipKernel, s_PropMipDstTex, currMipRT); + s_MipShader.SetInt(s_PropMipSrcWidth, prevW); + s_MipShader.SetInt(s_PropMipSrcHeight, prevH); + s_MipShader.SetInt(s_PropMipDstWidth, mipW); + s_MipShader.SetInt(s_PropMipDstHeight, mipH); + s_MipShader.SetInt(s_PropMipSrcLevel, 0); + s_MipShader.SetInt(s_PropMipIsSRGBSrc, downSrcIsSRGB ? 1 : 0); + s_MipShader.SetInt(s_PropMipIsAlphaWeighted, useAlphaWeight ? 1 : 0); + s_MipShader.SetInt(s_PropMipIsHdr, isHdr ? 1 : 0); + s_MipShader.Dispatch(mipKernel, (mipW + 7) >> 3, (mipH + 7) >> 3, 1); + + if (prevMipRT != null) + { + RenderTexture.ReleaseTemporary(prevMipRT); + } + prevMipRT = currMipRT; + currMipRT = null; + + encodeSrc = prevMipRT; + encodeSrcMip = 0; + // Normal downsampler outputs linear UNorm [0,1]; sRGB color downsampler keeps linear FP16 so encoder still converts to sRGB. + encodeIsSRGB = isSRGB && textureType != TextureType.Normal; + } + + s_Shader.SetTexture(kernel, s_PropSourceTex, encodeSrc); + s_Shader.SetBuffer(kernel, s_PropDestBuffer, buffer); + SetCommonUniforms(s_Shader, mipW, mipH, encodeSrcMip, blockCountX, blockCountY, blockOffset, mode, encodeIsSRGB, useAlphaWeight, qualityTier); + + int groupsX = (blockCountX + 7) >> 3; + int groupsY = GetDispatchGroupsY(blockCountY, blockSize); + s_Shader.Dispatch(kernel, groupsX, groupsY, 1); + + blockOffset += blockCountX * blockCountY; + } + + totalBytes = totalBlocks * k_BytesPerBlock; + return buffer; + } + catch + { + buffer.Release(); + throw; + } + finally + { + if (currMipRT != null) + RenderTexture.ReleaseTemporary(currMipRT); + if (prevMipRT != null) + RenderTexture.ReleaseTemporary(prevMipRT); + } + } + + [StructLayout(LayoutKind.Sequential, Size = k_BytesPerBlock)] + private struct AstcBlock128 + { + public uint W0; + public uint W1; + public uint W2; + public uint W3; + } + + internal static AstcRaw CompressTextureSync( + Texture source, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + bool includeMipmaps, + bool useAlphaWeight, + bool generateMipmaps = false) + { + if (!IsSupported) + { + Debug.LogError("GPU ASTC compression is not supported on this device."); + return null; + } + + if (!IsInputSupported(source)) + { + Debug.LogError("Input texture is null or not a valid 2D texture for GPU ASTC compression."); + return null; + } + + int mipCount = ResolveEffectiveMipCount(source, includeMipmaps, generateMipmaps, out bool willGenMips); + ComputeBuffer buffer = DispatchAllMipsToBuffer(source, textureType, blockSize, quality, mipCount, useAlphaWeight, willGenMips, out int totalBytes); + if (buffer == null || totalBytes <= 0) + return null; + + try + { + // Avoid LOH managed array allocation when AsyncGPUReadback is available. + if (SystemInfo.supportsAsyncGPUReadback) + { + AsyncGPUReadbackRequest req = AsyncGPUReadback.Request(buffer); + req.WaitForCompletion(); + if (req.hasError) + { + Debug.LogError("GPU ASTC readback failed."); + return null; + } + + NativeArray data = req.GetData(); + int byteLen = data.Length; + IntPtr unmanaged = Marshal.AllocHGlobal(byteLen); + try + { + unsafe + { + UnsafeUtility.MemCpy((void*)unmanaged, NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(data), byteLen); + } + return new AstcRaw(unmanaged, byteLen); + } + catch + { + Marshal.FreeHGlobal(unmanaged); + throw; + } + } + + int totalBlocks = totalBytes / k_BytesPerBlock; + var blocks = new AstcBlock128[totalBlocks]; + buffer.GetData(blocks); + + IntPtr fallbackUnmanaged = Marshal.AllocHGlobal(totalBytes); + try + { + unsafe + { + fixed (AstcBlock128* srcPtr = blocks) + { + UnsafeUtility.MemCpy((void*)fallbackUnmanaged, srcPtr, totalBytes); + } + } + return new AstcRaw(fallbackUnmanaged, totalBytes); + } + catch + { + Marshal.FreeHGlobal(fallbackUnmanaged); + throw; + } + } + finally + { + buffer.Release(); + } + } + + internal static Task CompressTextureAsync( + Texture source, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + bool includeMipmaps, + bool useAlphaWeight, + CancellationToken cancellationToken, + bool generateMipmaps = false) + { + if (cancellationToken.IsCancellationRequested) + return Task.FromCanceled(cancellationToken); + + if (!IsSupported) + { + Debug.LogError("GPU ASTC compression is not supported on this device."); + return Task.FromResult(null); + } + + if (!IsInputSupported(source)) + { + Debug.LogError("Input texture is null or not a valid 2D texture for GPU ASTC compression."); + return Task.FromResult(null); + } + + if (!SystemInfo.supportsAsyncGPUReadback) + { + return Task.FromResult(CompressTextureSync(source, textureType, blockSize, quality, includeMipmaps, useAlphaWeight, generateMipmaps)); + } + + int mipCount = ResolveEffectiveMipCount(source, includeMipmaps, generateMipmaps, out bool willGenMips); + ComputeBuffer buffer = DispatchAllMipsToBuffer(source, textureType, blockSize, quality, mipCount, useAlphaWeight, willGenMips, out int totalBytes); + if (buffer == null || totalBytes <= 0) + return Task.FromResult(null); + + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + CancellationTokenRegistration cancelReg = default; + if (cancellationToken.CanBeCanceled) + { + cancelReg = cancellationToken.Register(() => tcs.TrySetCanceled(cancellationToken)); + } + + try + { + AsyncGPUReadback.Request(buffer, request => + { + cancelReg.Dispose(); + try + { + if (cancellationToken.IsCancellationRequested || tcs.Task.IsCanceled) + { + tcs.TrySetCanceled(cancellationToken); + return; + } + + if (request.hasError) + { + Debug.LogError("GPU ASTC async readback failed."); + tcs.TrySetResult(null); + return; + } + + NativeArray data = request.GetData(); + int byteLen = data.Length; + IntPtr unmanaged = Marshal.AllocHGlobal(byteLen); + AstcRaw raw = null; + try + { + unsafe + { + UnsafeUtility.MemCpy((void*)unmanaged, NativeArrayUnsafeUtility.GetUnsafeReadOnlyPtr(data), byteLen); + } + + // Ownership of the unmanaged block moves to AstcRaw from here on; never free it directly again. + raw = new AstcRaw(unmanaged, byteLen); + if (!tcs.TrySetResult(raw)) + { + raw.Dispose(); + } + } + catch (Exception ex) + { + if (raw != null) + raw.Dispose(); + else + Marshal.FreeHGlobal(unmanaged); + tcs.TrySetException(ex); + } + } + finally + { + buffer.Release(); + } + }); + } + catch + { + cancelReg.Dispose(); + buffer.Release(); + throw; + } + + return tcs.Task; + } + + private static void ValidateSliceIndex(Texture texture, int slice, string paramName) + { + if (slice < 0) + throw new ArgumentOutOfRangeException(paramName, slice, $"{paramName} must be non-negative."); + + if (texture.dimension == TextureDimension.Tex2D && slice != 0) + throw new ArgumentOutOfRangeException(paramName, slice, $"{paramName} must be 0 for a 2D texture."); + + if (texture.dimension == TextureDimension.Cube && slice >= 6) + throw new ArgumentOutOfRangeException(paramName, slice, $"{paramName} must be in [0, 5] for a Cubemap."); + + if (texture is Texture2DArray texArray && slice >= texArray.depth) + throw new ArgumentOutOfRangeException(paramName, slice, $"{paramName} must be in [0, {texArray.depth - 1}] for Texture2DArray."); + } + + internal static void Encode( + CommandBuffer cmd, + Texture source, + Texture destination, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + int sourceMip, + int destMip, + int destX, + int destY, + bool useAlphaWeight, + int sourceSlice = 0, + int destSlice = 0) + { + if (cmd == null) + throw new ArgumentNullException(nameof(cmd)); + if (source == null) + throw new ArgumentNullException(nameof(source)); + if (destination == null) + throw new ArgumentNullException(nameof(destination)); + + ValidateSliceIndex(source, sourceSlice, nameof(sourceSlice)); + ValidateSliceIndex(destination, destSlice, nameof(destSlice)); + + if (!IsSupported) + throw new NotSupportedException("GPU ASTC compression is not supported on this device."); + + if ((SystemInfo.copyTextureSupport & CopyTextureSupport.RTToTexture) == 0) + throw new NotSupportedException("GPU direct CopyTexture from RenderTexture to Texture is not supported on this device."); + + if (!IsSliceableInputSupported(source)) + throw new ArgumentException("Source texture is not a supported 2D, Texture2DArray, or Cubemap texture for GPU ASTC encoding.", nameof(source)); + + int slot = BlockSizeToSlot(blockSize); + if (slot < 0 || !Encoder.GetBlockSize(blockSize, out uint bx, out uint by, out _)) + throw new ArgumentException($"Unsupported ASTC block size: {blockSize}", nameof(blockSize)); + + GraphicsFormat expectedFormat = ResolveTargetAstcFormat(source.graphicsFormat, textureType, blockSize, out _, out _); + GraphicsFormat dstFormat = destination.graphicsFormat; + if (dstFormat != expectedFormat) + { + throw new ArgumentException($"Destination texture format '{dstFormat}' does not match expected ASTC format '{expectedFormat}' for source format '{source.graphicsFormat}', textureType '{textureType}', and blockSize '{blockSize}'.", nameof(destination)); + } + + if (!IsSampleSupported(dstFormat)) + throw new NotSupportedException($"Destination ASTC format '{dstFormat}' is not natively supported by this GPU."); + + int srcMipCount = Math.Max(1, source.mipmapCount); + if (sourceMip < 0 || sourceMip >= srcMipCount) + throw new ArgumentOutOfRangeException(nameof(sourceMip), sourceMip, $"sourceMip must be in [0, {srcMipCount - 1}]."); + + int dstMipCount = Math.Max(1, destination.mipmapCount); + if (destMip < 0 || destMip >= dstMipCount) + throw new ArgumentOutOfRangeException(nameof(destMip), destMip, $"destMip must be in [0, {dstMipCount - 1}]."); + + int mipW = Math.Max(1, source.width >> sourceMip); + int mipH = Math.Max(1, source.height >> sourceMip); + int blockCountX = (mipW + (int)bx - 1) / (int)bx; + int blockCountY = (mipH + (int)by - 1) / (int)by; + + int dstMipW = Math.Max(1, destination.width >> destMip); + int dstMipH = Math.Max(1, destination.height >> destMip); + int alignedDstW = ((dstMipW + (int)bx - 1) / (int)bx) * (int)bx; + int alignedDstH = ((dstMipH + (int)by - 1) / (int)by) * (int)by; + + if (destX < 0 || (destX % (int)bx) != 0 || destX + blockCountX * (int)bx > alignedDstW) + throw new ArgumentOutOfRangeException(nameof(destX), destX, $"destX must be a non-negative multiple of {bx} and fit within destination mip width {dstMipW}."); + + if (destY < 0 || (destY % (int)by) != 0 || destY + blockCountY * (int)by > alignedDstH) + throw new ArgumentOutOfRangeException(nameof(destY), destY, $"destY must be a non-negative multiple of {by} and fit within destination mip height {dstMipH}."); + + uint mode = ResolveShaderMode(source.graphicsFormat, textureType, out bool isSRGB, out _); + uint qualityTier = MapQualityTier(quality); + int kernel = GetTexKernel(slot, qualityTier); + + // Temp RT lifetime is owned by the CommandBuffer, so it stays valid however late the buffer executes. + var tempRT = new RenderTargetIdentifier(s_PropTempBlocksRT); + cmd.GetTemporaryRT(s_PropTempBlocksRT, CreateBlockRTDescriptor(blockCountX, blockCountY), FilterMode.Point); + + bool needsSliceExtract = source.dimension != TextureDimension.Tex2D; + if (needsSliceExtract) + { + var sliceDesc = new RenderTextureDescriptor(mipW, mipH, source.graphicsFormat, 0) + { + enableRandomWrite = false, + useMipMap = false, + autoGenerateMips = false, + msaaSamples = 1, + }; + var tempSliceRT = new RenderTargetIdentifier(s_PropTempSliceRT); + cmd.GetTemporaryRT(s_PropTempSliceRT, sliceDesc, FilterMode.Point); + cmd.CopyTexture(source, sourceSlice, sourceMip, 0, 0, mipW, mipH, tempSliceRT, 0, 0, 0, 0); + cmd.SetComputeTextureParam(s_Shader, kernel, s_PropSourceTex, tempSliceRT); + SetCommonUniforms(cmd, s_Shader, mipW, mipH, 0, blockCountX, blockCountY, 0, mode, isSRGB, useAlphaWeight, qualityTier); + } + else + { + cmd.SetComputeTextureParam(s_Shader, kernel, s_PropSourceTex, source); + SetCommonUniforms(cmd, s_Shader, mipW, mipH, sourceMip, blockCountX, blockCountY, 0, mode, isSRGB, useAlphaWeight, qualityTier); + } + + cmd.SetComputeTextureParam(s_Shader, kernel, s_PropDestTex, tempRT); + + int groupsX = (blockCountX + 7) >> 3; + int groupsY = GetDispatchGroupsY(blockCountY, blockSize); + cmd.DispatchCompute(s_Shader, kernel, groupsX, groupsY, 1); + + cmd.CopyTexture(tempRT, 0, 0, 0, 0, blockCountX, blockCountY, destination, destSlice, destMip, destX, destY); + cmd.ReleaseTemporaryRT(s_PropTempBlocksRT); + if (needsSliceExtract) + { + cmd.ReleaseTemporaryRT(s_PropTempSliceRT); + } + } + + internal static Cubemap CompressCubemap( + Cubemap source, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + bool includeMipmaps, + bool useAlphaWeight) + { + if (!IsSupported || !IsSliceableInputSupported(source) || source.dimension != TextureDimension.Cube) + { + Debug.LogError("GPU ASTC Cubemap compression requires a valid Cubemap and GPU compute support."); + return null; + } + + GraphicsFormat astcFormat = ResolveTargetAstcFormat(source.graphicsFormat, textureType, blockSize, out _, out _); + int mipCount = includeMipmaps ? Math.Max(1, source.mipmapCount) : 1; + if (!CanUseDirectCopy(source.width, source.height, mipCount, blockSize, astcFormat)) + { + Debug.LogError($"GPU direct ASTC Cubemap compression requires hardware ASTC support and block-aligned dimensions for '{astcFormat}'."); + return null; + } + +#if UNITY_2022_1_OR_NEWER + TextureCreationFlags flags = TextureCreationFlags.DontInitializePixels | TextureCreationFlags.DontUploadUponCreate; +#else + TextureCreationFlags flags = TextureCreationFlags.None; +#endif + if (mipCount > 1) + flags |= TextureCreationFlags.MipChain; + + var dst = new Cubemap(source.width, astcFormat, flags, mipCount); + var cmd = new CommandBuffer { name = "AstcGpuCompressCubemap" }; + try + { + dst.name = source.name; + for (int face = 0; face < 6; face++) + { + for (int mip = 0; mip < mipCount; mip++) + { + Encode(cmd, source, dst, textureType, blockSize, quality, mip, mip, 0, 0, useAlphaWeight, face, face); + } + } + Graphics.ExecuteCommandBuffer(cmd); + return dst; + } + catch (Exception ex) + { + Debug.LogError($"GPU ASTC Cubemap compression failed: {ex.Message}"); + UnityEngine.Object.DestroyImmediate(dst); + return null; + } + finally + { + cmd.Release(); + } + } + + internal static Texture2DArray CompressTexture2DArray( + Texture2DArray source, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + bool includeMipmaps, + bool useAlphaWeight) + { + if (!IsSupported || !IsSliceableInputSupported(source) || source.dimension != TextureDimension.Tex2DArray) + { + Debug.LogError("GPU ASTC Texture2DArray compression requires a valid Texture2DArray and GPU compute support."); + return null; + } + + GraphicsFormat astcFormat = ResolveTargetAstcFormat(source.graphicsFormat, textureType, blockSize, out _, out _); + int mipCount = includeMipmaps ? Math.Max(1, source.mipmapCount) : 1; + if (!CanUseDirectCopy(source.width, source.height, mipCount, blockSize, astcFormat)) + { + Debug.LogError($"GPU direct ASTC Texture2DArray compression requires hardware ASTC support and block-aligned dimensions for '{astcFormat}'."); + return null; + } + +#if UNITY_2022_1_OR_NEWER + TextureCreationFlags flags = TextureCreationFlags.DontInitializePixels | TextureCreationFlags.DontUploadUponCreate; +#else + TextureCreationFlags flags = TextureCreationFlags.None; +#endif + if (mipCount > 1) + flags |= TextureCreationFlags.MipChain; + + int depth = source.depth; + var dst = new Texture2DArray(source.width, source.height, depth, astcFormat, flags, mipCount); + var cmd = new CommandBuffer { name = "AstcGpuCompressTexture2DArray" }; + try + { + dst.name = source.name; + for (int slice = 0; slice < depth; slice++) + { + for (int mip = 0; mip < mipCount; mip++) + { + Encode(cmd, source, dst, textureType, blockSize, quality, mip, mip, 0, 0, useAlphaWeight, slice, slice); + } + } + Graphics.ExecuteCommandBuffer(cmd); + return dst; + } + catch (Exception ex) + { + Debug.LogError($"GPU ASTC Texture2DArray compression failed: {ex.Message}"); + UnityEngine.Object.DestroyImmediate(dst); + return null; + } + finally + { + cmd.Release(); + } + } + + internal static void RecordDirectCompressToTexture( + CommandBuffer cmd, + Texture source, + Texture2D dst, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + int mipCount, + bool useAlphaWeight, + bool willGenMips) + { + if (!willGenMips) + { + for (int mip = 0; mip < mipCount; mip++) + { + Encode(cmd, source, dst, textureType, blockSize, quality, mip, mip, 0, 0, useAlphaWeight); + } + return; + } + + int slot = BlockSizeToSlot(blockSize); + if (slot < 0 || !Encoder.GetBlockSize(blockSize, out uint bx, out uint by, out _)) + throw new ArgumentException($"Unsupported ASTC block size: {blockSize}", nameof(blockSize)); + + uint mode = ResolveShaderMode(source.graphicsFormat, textureType, out bool isSRGB, out bool isHdr); + uint qualityTier = MapQualityTier(quality); + int kernel = GetTexKernel(slot, qualityTier); + bool useFloat16Mip = (isHdr || isSRGB) && textureType != TextureType.Normal; + int mipKernel = textureType == TextureType.Normal ? s_MipKernelNormal : s_MipKernelColor; + + // Mip 0: encode directly from source + Encode(cmd, source, dst, textureType, blockSize, quality, 0, 0, 0, 0, useAlphaWeight); + + int prevMipId = 0; + var tempBlocksRT = new RenderTargetIdentifier(s_PropTempBlocksRT); + + for (int mip = 1; mip < mipCount; mip++) + { + int prevW = Math.Max(1, source.width >> (mip - 1)); + int prevH = Math.Max(1, source.height >> (mip - 1)); + int mipW = Math.Max(1, source.width >> mip); + int mipH = Math.Max(1, source.height >> mip); + int blockCountX = (mipW + (int)bx - 1) / (int)bx; + int blockCountY = (mipH + (int)by - 1) / (int)by; + + int currMipId = (mip & 1) == 1 ? s_PropTempMipA : s_PropTempMipB; + var currMipRT = new RenderTargetIdentifier(currMipId); + cmd.GetTemporaryRT(currMipId, CreateMipRTDescriptor(mipW, mipH, useFloat16Mip), FilterMode.Point); + + if (mip == 1) + cmd.SetComputeTextureParam(s_MipShader, mipKernel, s_PropMipSrcTex, source); + else + cmd.SetComputeTextureParam(s_MipShader, mipKernel, s_PropMipSrcTex, new RenderTargetIdentifier(prevMipId)); + + cmd.SetComputeTextureParam(s_MipShader, mipKernel, s_PropMipDstTex, currMipRT); + cmd.SetComputeIntParam(s_MipShader, s_PropMipSrcWidth, prevW); + cmd.SetComputeIntParam(s_MipShader, s_PropMipSrcHeight, prevH); + cmd.SetComputeIntParam(s_MipShader, s_PropMipDstWidth, mipW); + cmd.SetComputeIntParam(s_MipShader, s_PropMipDstHeight, mipH); + cmd.SetComputeIntParam(s_MipShader, s_PropMipSrcLevel, 0); + cmd.SetComputeIntParam(s_MipShader, s_PropMipIsSRGBSrc, (mip == 1 && isSRGB) ? 1 : 0); + cmd.SetComputeIntParam(s_MipShader, s_PropMipIsAlphaWeighted, useAlphaWeight ? 1 : 0); + cmd.SetComputeIntParam(s_MipShader, s_PropMipIsHdr, isHdr ? 1 : 0); + cmd.DispatchCompute(s_MipShader, mipKernel, (mipW + 7) >> 3, (mipH + 7) >> 3, 1); + + if (prevMipId != 0) + { + cmd.ReleaseTemporaryRT(prevMipId); + } + + bool encodeIsSRGB = isSRGB && textureType != TextureType.Normal; + cmd.GetTemporaryRT(s_PropTempBlocksRT, CreateBlockRTDescriptor(blockCountX, blockCountY), FilterMode.Point); + cmd.SetComputeTextureParam(s_Shader, kernel, s_PropSourceTex, currMipRT); + cmd.SetComputeTextureParam(s_Shader, kernel, s_PropDestTex, tempBlocksRT); + SetCommonUniforms(cmd, s_Shader, mipW, mipH, 0, blockCountX, blockCountY, 0, mode, encodeIsSRGB, useAlphaWeight, qualityTier); + cmd.DispatchCompute(s_Shader, kernel, (blockCountX + 7) >> 3, GetDispatchGroupsY(blockCountY, blockSize), 1); + cmd.CopyTexture(tempBlocksRT, 0, 0, 0, 0, blockCountX, blockCountY, dst, 0, mip, 0, 0); + cmd.ReleaseTemporaryRT(s_PropTempBlocksRT); + + prevMipId = currMipId; + } + + if (prevMipId != 0) + { + cmd.ReleaseTemporaryRT(prevMipId); + } + } + + internal static bool CanUseDirectCompress(Texture source, TextureType textureType, BlockSize blockSize, bool includeMipmaps, bool generateMipmaps, out GraphicsFormat astcFormat, out int mipCount, out bool willGenMips) + { + astcFormat = GraphicsFormat.None; + mipCount = 1; + willGenMips = false; + if (!IsSupported || !IsInputSupported(source)) + return false; + + astcFormat = ResolveTargetAstcFormat(source.graphicsFormat, textureType, blockSize, out _, out _); + if (!Encoder.CanCreateAstcTexture(astcFormat)) + return false; + + mipCount = ResolveEffectiveMipCount(source, includeMipmaps, generateMipmaps, out willGenMips); + return CanUseDirectCopy(source.width, source.height, mipCount, blockSize, astcFormat); + } + + internal static Texture2D CompressToTexture( + Texture source, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + bool includeMipmaps, + bool useAlphaWeight, + bool generateMipmaps = false) + { + if (!IsSupported) + { + Debug.LogError("GPU ASTC compression is not supported on this device."); + return null; + } + + if (!IsInputSupported(source)) + { + Debug.LogError("Input texture is null or not a valid 2D texture for GPU ASTC compression."); + return null; + } + + GraphicsFormat astcFormat = ResolveTargetAstcFormat(source.graphicsFormat, textureType, blockSize, out _, out _); + if (!Encoder.CanCreateAstcTexture(astcFormat)) + { + Debug.LogError($"ASTC texture format '{astcFormat}' is not supported on this device. Use CompressTexture or EncodeToASTC for raw ASTC data."); + return null; + } + int mipCount = ResolveEffectiveMipCount(source, includeMipmaps, generateMipmaps, out bool willGenMips); + + // Fast zero-readback path (including GPU-generated mipmaps) when all mip dimensions align cleanly and GPU natively samples ASTC + if (CanUseDirectCopy(source.width, source.height, mipCount, blockSize, astcFormat)) + { +#if UNITY_2022_1_OR_NEWER + TextureCreationFlags flags = TextureCreationFlags.DontInitializePixels | TextureCreationFlags.DontUploadUponCreate; +#else + TextureCreationFlags flags = TextureCreationFlags.None; +#endif + if (mipCount > 1) + flags |= TextureCreationFlags.MipChain; + + var dst = new Texture2D(source.width, source.height, astcFormat, mipCount, flags); + var cmd = new CommandBuffer { name = "AstcGpuCompressToTexture" }; + try + { + dst.name = source.name; + dst.Apply(false, true); + + RecordDirectCompressToTexture(cmd, source, dst, textureType, blockSize, quality, mipCount, useAlphaWeight, willGenMips); + Graphics.ExecuteCommandBuffer(cmd); + return dst; + } + catch + { + UnityEngine.Object.DestroyImmediate(dst); + throw; + } + finally + { + cmd.Release(); + } + } + + // Universal GPU path for non-aligned dimensions, full 1x1 mip tails, or non-ASTC desktop Editors + using AstcRaw raw = CompressTextureSync(source, textureType, blockSize, quality, includeMipmaps, useAlphaWeight, generateMipmaps); + if (raw == null) + return null; + + TextureCreationFlags fallbackFlags = mipCount > 1 ? TextureCreationFlags.MipChain : TextureCreationFlags.None; + var fallbackTex = new Texture2D(source.width, source.height, astcFormat, mipCount, fallbackFlags); + try + { + fallbackTex.name = source.name; + fallbackTex.LoadRawTextureData(raw); + fallbackTex.Apply(false, true); + return fallbackTex; + } + catch + { + UnityEngine.Object.DestroyImmediate(fallbackTex); + throw; + } + } + + internal static async Task CompressToTextureAsync( + Texture source, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + bool includeMipmaps, + bool useAlphaWeight, + CancellationToken cancellationToken, + bool generateMipmaps = false) + { + if (cancellationToken.IsCancellationRequested) + { + throw new OperationCanceledException(cancellationToken); + } + + if (!IsSupported) + { + Debug.LogError("GPU ASTC compression is not supported on this device."); + return null; + } + + if (!IsInputSupported(source)) + { + Debug.LogError("Input texture is null or not a valid 2D texture for GPU ASTC compression."); + return null; + } + + GraphicsFormat astcFormat = ResolveTargetAstcFormat(source.graphicsFormat, textureType, blockSize, out _, out _); + if (!Encoder.CanCreateAstcTexture(astcFormat)) + { + Debug.LogError($"ASTC texture format '{astcFormat}' is not supported on this device. Use CompressTextureAsync or EncodeToASTCAsync for raw ASTC data."); + return null; + } + + int width = source.width; + int height = source.height; + int mipCount = ResolveEffectiveMipCount(source, includeMipmaps, generateMipmaps, out bool willGenMips); + string texName = source.name; + + // Zero-readback GPU-only path (including generated mipmaps) is already non-blocking on the CPU. + if (CanUseDirectCopy(width, height, mipCount, blockSize, astcFormat)) + { + return CompressToTexture(source, textureType, blockSize, quality, includeMipmaps, useAlphaWeight, generateMipmaps); + } + + // Non-blocking AsyncGPUReadback path for generated mipmaps, mipmapped, or non-block-aligned textures. + using AstcRaw raw = await CompressTextureAsync(source, textureType, blockSize, quality, includeMipmaps, useAlphaWeight, cancellationToken, generateMipmaps); + if (raw == null) + return null; + + cancellationToken.ThrowIfCancellationRequested(); + + TextureCreationFlags flags = mipCount > 1 ? TextureCreationFlags.MipChain : TextureCreationFlags.None; + var result = new Texture2D(width, height, astcFormat, mipCount, flags); + try + { + result.name = texName; + result.LoadRawTextureData(raw); + result.Apply(false, true); + return result; + } + catch + { + UnityEngine.Object.DestroyImmediate(result); + throw; + } + } + + internal static bool CompressInPlace( + Texture2D inputTexture, + TextureType textureType, + BlockSize blockSize, + CompressQuality quality, + bool makeNoLongerReadable, + bool useAlphaWeight, + bool generateMipmaps = false) + { + if (!IsSupported) + { + Debug.LogError("GPU ASTC compression is not supported on this device."); + return false; + } + + if (!IsInputSupported(inputTexture)) + { + Debug.LogError("Input Texture2D is null or invalid for GPU ASTC compression."); + return false; + } + + if (!inputTexture.isReadable) + { + Debug.LogError("In-place Compress requires Texture2D.isReadable == true (Unity Texture2D.Reinitialize/LoadRawTextureData requirement). Use CompressToTexture for non-readable textures."); + return false; + } + + GraphicsFormat astcFormat = ResolveTargetAstcFormat(inputTexture.graphicsFormat, textureType, blockSize, out _, out _); + if (!Encoder.CanCreateAstcTexture(astcFormat)) + { + Debug.LogError($"ASTC texture format '{astcFormat}' is not supported on this device. Use CompressTexture or EncodeToASTC for raw ASTC data."); + return false; + } + int width = inputTexture.width; + int height = inputTexture.height; + int mipCount = ResolveEffectiveMipCount(inputTexture, includeMipmaps: true, generateMipmaps, out bool willGenMips); + if (!Encoder.IsFullMipChain(width, height, mipCount)) + { + Debug.LogError($"In-place Compress does not support partial mipmap chains (mipmapCount={mipCount} for {width}x{height}) because Texture2D.Reinitialize allocates a full mipmap chain. Use CompressToTexture instead."); + return false; + } + + // Fast zero-readback path: encode into temporary per-mip RTs BEFORE Reinitialize wipes source pixels. + // Only valid when makeNoLongerReadable is true, because Graphics.CopyTexture writes GPU memory only + // and would otherwise leave a readable Texture2D with an uninitialized CPU pixel buffer. + if (!willGenMips + && makeNoLongerReadable + && CanUseDirectCopy(width, height, mipCount, blockSize, astcFormat) + && Encoder.GetBlockSize(blockSize, out uint bx, out uint by, out _)) + { + int slot = BlockSizeToSlot(blockSize); + uint mode = ResolveShaderMode(inputTexture.graphicsFormat, textureType, out bool isSRGB, out _); + uint qualityTier = MapQualityTier(quality); + int kernel = GetTexKernel(slot, qualityTier); + + var mipRTs = new RenderTexture[mipCount]; + try + { + for (int mip = 0; mip < mipCount; mip++) + { + int mipW = Math.Max(1, width >> mip); + int mipH = Math.Max(1, height >> mip); + int blockW = (mipW + (int)bx - 1) / (int)bx; + int blockH = (mipH + (int)by - 1) / (int)by; + + RenderTexture rt = RenderTexture.GetTemporary(CreateBlockRTDescriptor(blockW, blockH)); + rt.Create(); + mipRTs[mip] = rt; + + s_Shader.SetTexture(kernel, s_PropSourceTex, inputTexture); + s_Shader.SetTexture(kernel, s_PropDestTex, rt); + SetCommonUniforms(s_Shader, mipW, mipH, mip, blockW, blockH, 0, mode, isSRGB, useAlphaWeight, qualityTier); + s_Shader.Dispatch(kernel, (blockW + 7) >> 3, GetDispatchGroupsY(blockH, blockSize), 1); + } + + if (!inputTexture.Reinitialize(width, height, astcFormat, mipCount > 1)) + return false; + + inputTexture.Apply(false, makeNoLongerReadable); + + for (int mip = 0; mip < mipCount; mip++) + { + RenderTexture rt = mipRTs[mip]; + Graphics.CopyTexture(rt, 0, 0, 0, 0, rt.width, rt.height, inputTexture, 0, mip, 0, 0); + } + + return true; + } + finally + { + for (int mip = 0; mip < mipCount; mip++) + { + if (mipRTs[mip] != null) + RenderTexture.ReleaseTemporary(mipRTs[mip]); + } + } + } + + // Universal GPU fallback via ComputeBuffer + LoadRawTextureData + using AstcRaw raw = CompressTextureSync(inputTexture, textureType, blockSize, quality, mipCount > 1, useAlphaWeight, generateMipmaps); + if (raw == null) + return false; + + if (inputTexture.Reinitialize(width, height, astcFormat, mipCount > 1)) + { + inputTexture.LoadRawTextureData(raw); + inputTexture.Apply(false, makeNoLongerReadable); + return true; + } + + return false; + } + } +} diff --git a/Assets/ASTC Encoder/Runtime/Gpu/AstcGpuBackend.cs.meta b/Assets/ASTC Encoder/Runtime/Gpu/AstcGpuBackend.cs.meta new file mode 100644 index 0000000..bea86fc --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Gpu/AstcGpuBackend.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: ff056b2370fe797a07ba0501d8834c0a +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/Gpu/Shaders.meta b/Assets/ASTC Encoder/Runtime/Gpu/Shaders.meta new file mode 100644 index 0000000..60738b2 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Gpu/Shaders.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: c3bab8b5e44d42844a06baa2d7294cc5 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuBise.hlsl b/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuBise.hlsl new file mode 100644 index 0000000..cdf4227 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuBise.hlsl @@ -0,0 +1,475 @@ +#ifndef ASTC_GPU_BISE_HLSL +#define ASTC_GPU_BISE_HLSL + +// Pure-ALU ASTC Bounded Integer Sequence Encoding (BISE), Quantization/Unquantization, +// and 128-bit physical block assembly. +// Zero large static const tables to guarantee mobile GPU (Android Vulkan/GLES3.1 & iOS Metal) compatibility. + +#define ASTC_QUANT_2 0u +#define ASTC_QUANT_3 1u +#define ASTC_QUANT_4 2u +#define ASTC_QUANT_5 3u +#define ASTC_QUANT_6 4u +#define ASTC_QUANT_8 5u +#define ASTC_QUANT_10 6u +#define ASTC_QUANT_12 7u +#define ASTC_QUANT_16 8u +#define ASTC_QUANT_20 9u +#define ASTC_QUANT_24 10u +#define ASTC_QUANT_32 11u +#define ASTC_QUANT_40 12u +#define ASTC_QUANT_48 13u +#define ASTC_QUANT_64 14u +#define ASTC_QUANT_80 15u +#define ASTC_QUANT_96 16u +#define ASTC_QUANT_128 17u +#define ASTC_QUANT_160 18u +#define ASTC_QUANT_192 19u +#define ASTC_QUANT_256 20u + +// Color Endpoint Modes (CEM) +#define ASTC_CEM_LDR_LUM_ALPHA_DIRECT 4u // 4 endpoint values (used for GGGR Normal Maps) +#define ASTC_CEM_LDR_RGB_DIRECT 8u // 6 endpoint values +#define ASTC_CEM_HDR_RGB_DIRECT 11u // 6 endpoint values (HDR RGB, A = 1.0) +#define ASTC_CEM_LDR_RGBA_DIRECT 12u // 8 endpoint values +#define ASTC_CEM_HDR_RGB_LDR_ALPHA 14u // 8 endpoint values (HDR RGB + LDR A) +#define ASTC_CEM_HDR_RGBA_DIRECT 15u // 8 endpoint values (HDR RGB + HDR A) + +// Compact 21-entry packed LUT: rangeVal (bits 0..8) | bits (9..12) | trits (13) | quints (14) +static const uint kAstcQuantTable[21] = +{ + 2u | (1u << 9u), + 3u | (0u << 9u) | (1u << 13u), + 4u | (2u << 9u), + 5u | (0u << 9u) | (1u << 14u), + 6u | (1u << 9u) | (1u << 13u), + 8u | (3u << 9u), + 10u | (1u << 9u) | (1u << 14u), + 12u | (2u << 9u) | (1u << 13u), + 16u | (4u << 9u), + 20u | (2u << 9u) | (1u << 14u), + 24u | (3u << 9u) | (1u << 13u), + 32u | (5u << 9u), + 40u | (3u << 9u) | (1u << 14u), + 48u | (4u << 9u) | (1u << 13u), + 64u | (6u << 9u), + 80u | (4u << 9u) | (1u << 14u), + 96u | (5u << 9u) | (1u << 13u), + 128u | (7u << 9u), + 160u | (5u << 9u) | (1u << 14u), + 192u | (6u << 9u) | (1u << 13u), + 256u | (8u << 9u) +}; + +// Returns (range, bits, trits, quints) for a quantization mode 0..20. +void AstcGetQuantParams(uint q, out uint rangeVal, out uint bits, out uint trits, out uint quints) +{ + uint packed = kAstcQuantTable[min(q, 20u)]; + rangeVal = packed & 0x1FFu; + bits = (packed >> 9u) & 0xFu; + trits = (packed >> 13u) & 1u; + quints = (packed >> 14u) & 1u; +} + +uint AstcGetBiseBitCount(uint count, uint q) +{ + uint rangeVal, b, t, qu; + AstcGetQuantParams(q, rangeVal, b, t, qu); + uint total = count * b; + if (t != 0u) + { + total += (count * 8u + 4u) / 5u; + } + else if (qu != 0u) + { + total += (count * 7u + 2u) / 3u; + } + return total; +} + +// Pure-ALU BISE 5-trit packer -> 8-bit integer (exact match to Khronos ASTC spec). +uint AstcPack5Trits(uint t0, uint t1, uint t2, uint t3, uint t4) +{ + uint C; + if (t2 == 2u) + { + C = (t1 == 2u) ? ((3u << 2u) | t0) : ((t1 << 4u) | (t0 << 2u) | 3u); + } + else + { + C = (t2 << 4u) | (t1 << 2u) | t0; + } + + if (t4 == 2u) + { + return (t3 == 2u) + ? (((C >> 2u) << 5u) | (7u << 2u) | (C & 3u)) + : ((t3 << 7u) | (3u << 5u) | C); + } + return (t4 << 7u) | (t3 << 5u) | C; +} + +// Pure-ALU BISE 3-quint packer -> 7-bit integer (exact match to Khronos ASTC spec). +uint AstcPack3Quints(uint q0, uint q1, uint q2) +{ + if (q2 == 4u) + { + if (q1 == 4u) + { + return (q0 == 4u) ? 7u : ((1u << 5u) | (q0 << 3u) | 7u); + } + if (q0 == 4u) + { + return (1u << 5u) | (q1 << 3u) | 6u; + } + return ((3u - (q0 >> 1u)) << 5u) | (q1 << 3u) | 6u | (q0 & 1u); + } + if (q1 == 4u) + { + return (q0 == 4u) ? ((q2 << 3u) | 6u) : ((q2 << 5u) | (q0 << 3u) | 5u); + } + return (q2 << 5u) | (q1 << 3u) | q0; +} + +// Maps a monotonically ordered quantized level k in [0, range-1] to the ASTC BISE code. +uint AstcLinearToCode(uint k, uint q) +{ + uint rangeVal, b, t, qu; + AstcGetQuantParams(q, rangeVal, b, t, qu); + if ((t == 0u && qu == 0u) || b == 0u) + { + return k; + } + + uint halfR = rangeVal >> 1u; + uint baseVal = (t != 0u) ? 3u : 5u; + if (k < halfR) + { + uint d = k % baseVal; + uint m = k / baseVal; + return (d << b) | (m << 1u); + } + else + { + uint rk = (rangeVal - 1u) - k; + uint d = rk % baseVal; + uint m = rk / baseVal; + return (d << b) | (m << 1u) | 1u; + } +} + +// Exact Khronos ASTC color unquantization: BISE code v -> [0, 255]. +uint AstcUnquantizeColor(uint v, uint q) +{ + uint rangeVal, b, t, qu; + AstcGetQuantParams(q, rangeVal, b, t, qu); + + if (t == 0u && qu == 0u) + { + uint r = v << (8u - b); + if (b < 8u) r |= v >> max((int)b * 2 - 8, 0); + // Exact bit replication for b = 1..8: + // b=8: v, b=7: (v<<1)|(v>>6), b=6: (v<<2)|(v>>4), b=5: (v<<3)|(v>>2), + // b=4: (v<<4)|v, b=3: (v<<5)|(v<<2)|(v>>1), b=2: v*85, b=1: v*255 + if (b <= 3u) + { + r = (b == 3u) ? ((v << 5u) | (v << 2u) | (v >> 1u)) : ((b == 2u) ? (v * 85u) : (v * 255u)); + } + return r & 0xFFu; + } + + uint D = v >> b; + uint low = v & ((1u << b) - 1u); + uint A = ((low & 1u) != 0u) ? 0x1FFu : 0u; + uint m = low >> 1u; + + uint C = 0u; + uint B = 0u; + if (t != 0u) + { + C = (b == 1u) ? 204u : ((b == 2u) ? 93u : ((b == 3u) ? 44u : ((b == 4u) ? 22u : ((b == 5u) ? 11u : 5u)))); + B = (b == 1u) ? 0u + : (b == 2u) ? ((m << 8u) | (m << 4u) | (m << 2u) | (m << 1u)) + : (b == 3u) ? ((m << 7u) | (m << 2u) | m) + : (b == 4u) ? ((m << 6u) | m) + : (b == 5u) ? ((m << 5u) | (m >> 2u)) + : ((m << 4u) | (m >> 4u)); + } + else + { + C = (b == 1u) ? 113u : ((b == 2u) ? 54u : ((b == 3u) ? 26u : ((b == 4u) ? 13u : 6u))); + B = (b == 1u) ? 0u + : (b == 2u) ? ((m << 8u) | (m << 3u) | (m << 2u)) + : (b == 3u) ? ((m << 7u) | (m << 1u) | (m >> 1u)) + : (b == 4u) ? ((m << 6u) | (m >> 1u)) + : ((m << 5u) | (m >> 3u)); + } + + uint T = (D * C + B) ^ A; + return (A & 0x80u) | (T >> 2u); +} + +// Exact Khronos ASTC weight unquantization: BISE code v -> [0, 64]. +uint AstcUnquantizeWeight(uint v, uint q) +{ + uint rangeVal, b, t, qu; + AstcGetQuantParams(q, rangeVal, b, t, qu); + uint T = 0u; + + if (t == 0u && qu == 0u) + { + if (b == 1u) T = (v != 0u) ? 63u : 0u; + else if (b == 2u) T = v * 21u; + else if (b == 3u) T = (v << 3u) | v; + else if (b == 4u) T = (v << 2u) | (v >> 2u); + else T = (v << 1u) | (v >> 4u); + } + else if (t != 0u) + { + uint D = v >> b; + uint low = v & ((1u << b) - 1u); + if (b == 0u) + { + T = (D == 0u) ? 0u : ((D == 1u) ? 32u : 63u); + } + else + { + uint A = ((low & 1u) != 0u) ? 0x7Fu : 0u; + uint m = low >> 1u; + uint B = 0u; + uint C = 50u; + if (b == 2u) { C = 23u; B = (m << 6u) | (m << 2u) | m; } + else if (b == 3u) { C = 11u; B = (m << 5u) | m; } + T = (D * C + B) ^ A; + T = (A & 0x20u) | (T >> 2u); + } + } + else + { + uint D = v >> b; + uint low = v & ((1u << b) - 1u); + if (b == 0u) + { + if (D == 0u) T = 0u; + else if (D == 1u) T = 16u; + else if (D == 2u) T = 32u; + else if (D == 3u) T = 47u; + else T = 63u; + } + else + { + uint A = ((low & 1u) != 0u) ? 0x7Fu : 0u; + uint m = low >> 1u; + uint B = 0u; + uint C = 28u; + if (b == 2u) { C = 13u; B = (m << 6u) | (m << 1u); } + T = (D * C + B) ^ A; + T = (A & 0x20u) | (T >> 2u); + } + } + + if (T > 32u) T += 1u; + return T; +} + +// Quantizes an 8-bit endpoint value c8 in [0, 255] to the exact nearest BISE code for quant mode q. +// When min128 is true, constrains the unquantized value to >= 128 (HDR modeval/majcomp == 3 direct endpoints). +uint AstcQuantizeColorRange(uint c8, uint q, bool min128, out uint unquantOut) +{ + uint rangeVal, b, t, qu; + AstcGetQuantParams(q, rangeVal, b, t, qu); + if (min128) c8 = max(c8, 128u); + if (q == ASTC_QUANT_256) + { + unquantOut = c8; + return c8; + } + + int minK = min128 ? (int)(rangeVal >> 1u) : 0; + int maxK = (int)rangeVal - 1; + int kEst = clamp((int)floor((float)c8 * (float)maxK / 255.0 + 0.5), minK, maxK); + + uint bestCode = 0u; + uint bestUq = 0u; + int bestErr = 10000; + + [loop] for (int step = 0; step < 3; ++step) + { + int dk = (step == 0) ? 0 : ((step == 1) ? -1 : 1); + int k = kEst + dk; + if (k < minK || k > maxK) continue; + uint code = AstcLinearToCode((uint)k, q); + uint uq = AstcUnquantizeColor(code, q); + int err = abs((int)uq - (int)c8); + if (err < bestErr) { bestErr = err; bestCode = code; bestUq = uq; } + } + + unquantOut = bestUq; + return bestCode; +} + +uint AstcQuantizeColor(uint c8, uint q, out uint unquantOut) +{ + return AstcQuantizeColorRange(c8, q, false, unquantOut); +} + +uint AstcQuantizeColorMin128(uint c8, uint q, out uint unquantOut) +{ + return AstcQuantizeColorRange(c8, q, true, unquantOut); +} + +// Quantizes a normalized weight w01 in [0, 1] to the exact nearest BISE code and returns unquantized [0, 64]. +uint AstcQuantizeWeight(float w01, uint q, out uint unquantOut) +{ + uint rangeVal, b, t, qu; + AstcGetQuantParams(q, rangeVal, b, t, qu); + + float w64 = saturate(w01) * 64.0; + int maxK = (int)rangeVal - 1; + int kEst = clamp((int)floor(saturate(w01) * (float)maxK + 0.5), 0, maxK); + + uint bestCode = 0u; + uint bestUq = 0u; + float bestErr = 1e30; + + [loop] for (int step = 0; step < 3; ++step) + { + int dk = (step == 0) ? 0 : ((step == 1) ? -1 : 1); + int k = kEst + dk; + if (k < 0 || k > maxK) continue; + uint code = AstcLinearToCode((uint)k, q); + uint uq = AstcUnquantizeWeight(code, q); + float err = abs((float)uq - w64); + if (err < bestErr) { bestErr = err; bestCode = code; bestUq = uq; } + } + + unquantOut = bestUq; + return bestCode; +} + +// Writes up to 24 bits into a 128-bit block (little-endian uint4), branchless. +void AstcWriteBits128(inout uint4 blk, uint bitPos, uint numBits, uint val) +{ + uint mask = (numBits == 0u) ? 0u : ((numBits >= 32u) ? 0xFFFFFFFFu : ((1u << numBits) - 1u)); + val &= mask; + + uint wordIdx = bitPos >> 5u; + uint bitOff = bitPos & 31u; + + uint lo = val << bitOff; + uint hi = (bitOff > 0u && (bitOff + numBits > 32u)) ? (val >> (32u - bitOff)) : 0u; + + blk.x |= (wordIdx == 0u) ? lo : 0u; + blk.y |= ((wordIdx == 1u) ? lo : 0u) | ((wordIdx == 0u) ? hi : 0u); + blk.z |= ((wordIdx == 2u) ? lo : 0u) | ((wordIdx == 1u) ? hi : 0u); + blk.w |= ((wordIdx == 3u) ? lo : 0u) | ((wordIdx == 2u) ? hi : 0u); +} + +// Pure-integer SWAR 32-bit bit-reversal (avoids Unity 2021.3 HLSLcc Metal transpiler bug +// where vectorized reversebits(uint4) emits bitReverse(int4) assigned to float4). +uint AstcReverseBits32(uint x) +{ + x = ((x & 0x55555555u) << 1u) | ((x >> 1u) & 0x55555555u); + x = ((x & 0x33333333u) << 2u) | ((x >> 2u) & 0x33333333u); + x = ((x & 0x0F0F0F0Fu) << 4u) | ((x >> 4u) & 0x0F0F0F0Fu); + x = ((x & 0x00FF00FFu) << 8u) | ((x >> 8u) & 0x00FF00FFu); + return (x << 16u) | (x >> 16u); +} + +// Reverses all 128 bits of a uint4 (places BISE weight stream at MSB descending). +uint4 AstcReverse128(uint4 v) +{ + return uint4( + AstcReverseBits32(v.w), + AstcReverseBits32(v.z), + AstcReverseBits32(v.y), + AstcReverseBits32(v.x)); +} + +// Shared per-thread BISE symbol scratch buffer (eliminates array-by-value copies in FXC/HLSLcc/DXC). +static uint g_AstcBiseVals[64]; + +// Encodes up to 64 BISE symbols from g_AstcBiseVals[0..count-1] into a 128-bit block starting at startBit. +void AstcEncodeBise(inout uint4 dst, uint startBit, uint q, uint count) +{ + uint rangeVal, b, t, qu; + AstcGetQuantParams(q, rangeVal, b, t, qu); + uint bitPos = startBit; + + if (t == 0u && qu == 0u) + { + [loop] for (uint i = 0u; i < count; ++i) + { + AstcWriteBits128(dst, bitPos, b, g_AstcBiseVals[i]); + bitPos += b; + } + } + else if (t != 0u) + { + uint lowMask = (b > 0u) ? ((1u << b) - 1u) : 0u; + [loop] for (uint i = 0u; i < count; i += 5u) + { + uint v0 = g_AstcBiseVals[i]; + uint v1 = (i + 1u < count) ? g_AstcBiseVals[i + 1u] : 0u; + uint v2 = (i + 2u < count) ? g_AstcBiseVals[i + 2u] : 0u; + uint v3 = (i + 3u < count) ? g_AstcBiseVals[i + 3u] : 0u; + uint v4 = (i + 4u < count) ? g_AstcBiseVals[i + 4u] : 0u; + + uint T = AstcPack5Trits(v0 >> b, v1 >> b, v2 >> b, v3 >> b, v4 >> b); + + uint tOff = 0u; + [loop] for (uint j = 0u; j < 5u; ++j) + { + if (i + j >= count) break; + uint vj = g_AstcBiseVals[i + j]; + uint tBits = (j == 2u || j == 4u) ? 1u : 2u; + uint tMask = (tBits == 1u) ? 1u : 3u; + AstcWriteBits128(dst, bitPos, b, vj & lowMask); bitPos += b; + AstcWriteBits128(dst, bitPos, tBits, (T >> tOff) & tMask); bitPos += tBits; + tOff += tBits; + } + } + } + else + { + uint lowMask = (b > 0u) ? ((1u << b) - 1u) : 0u; + [loop] for (uint i = 0u; i < count; i += 3u) + { + uint v0 = g_AstcBiseVals[i]; + uint v1 = (i + 1u < count) ? g_AstcBiseVals[i + 1u] : 0u; + uint v2 = (i + 2u < count) ? g_AstcBiseVals[i + 2u] : 0u; + + uint Q = AstcPack3Quints(v0 >> b, v1 >> b, v2 >> b); + + uint qOff = 0u; + [loop] for (uint j = 0u; j < 3u; ++j) + { + if (i + j >= count) break; + uint vj = g_AstcBiseVals[i + j]; + uint qBits = (j == 0u) ? 3u : 2u; + uint qMask = (qBits == 3u) ? 7u : 3u; + AstcWriteBits128(dst, bitPos, b, vj & lowMask); bitPos += b; + AstcWriteBits128(dst, bitPos, qBits, (Q >> qOff) & qMask); bitPos += qBits; + qOff += qBits; + } + } + } +} + +// Encodes 2D LDR Void-Extent constant color block (UNorm16 per channel). +uint4 AstcEncodeVoidExtentLDR(uint4 rgba16) +{ + uint w2 = (rgba16.r & 0xFFFFu) | ((rgba16.g & 0xFFFFu) << 16u); + uint w3 = (rgba16.b & 0xFFFFu) | ((rgba16.a & 0xFFFFu) << 16u); + return uint4(0xFFFFFDFCu, 0xFFFFFFFFu, w2, w3); +} + +// Encodes 2D HDR Void-Extent constant color block (FP16 per channel). +uint4 AstcEncodeVoidExtentHDR(uint4 rgbaF16) +{ + uint w2 = (rgbaF16.r & 0xFFFFu) | ((rgbaF16.g & 0xFFFFu) << 16u); + uint w3 = (rgbaF16.b & 0xFFFFu) | ((rgbaF16.a & 0xFFFFu) << 16u); + return uint4(0xFFFFFFFCu, 0xFFFFFFFFu, w2, w3); +} + +#endif // ASTC_GPU_BISE_HLSL diff --git a/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuBise.hlsl.meta b/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuBise.hlsl.meta new file mode 100644 index 0000000..529214b --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuBise.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 11e5a799b3091fed5bbcca5459074b3b +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuColor.hlsl b/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuColor.hlsl new file mode 100644 index 0000000..0e3ff79 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuColor.hlsl @@ -0,0 +1,519 @@ +#ifndef ASTC_GPU_COLOR_HLSL +#define ASTC_GPU_COLOR_HLSL + +#include "AstcGpuBise.hlsl" + +// ============================================================================ +// Color Space & HDR LNS Conversions +// ============================================================================ + +float AstcLinearToSRGBScalar(float c) +{ + c = saturate(c); + float s1 = sqrt(c); + float s2 = sqrt(s1); + float s3 = sqrt(s2); + float hi = saturate(0.662002687 * s1 + 0.684122060 * s2 - 0.323583601 * s3 - 0.0225411470 * c); + return (c <= 0.0031308) ? (c * 12.92) : hi; +} + +float3 AstcLinearToSRGB(float3 rgb) +{ + float3 c = saturate(rgb); + float3 s1 = sqrt(c); + float3 s2 = sqrt(s1); + float3 s3 = sqrt(s2); + float3 hi = saturate(0.662002687 * s1 + 0.684122060 * s2 - 0.323583601 * s3 - 0.0225411470 * c); + return lerp(hi, c * 12.92, float3(c <= 0.0031308)); +} + +// Exact Khronos ASTC float4 -> 16-bit LNS [0, 65535] conversion (branchless vectorized). +// Negative values and NaNs clamp to 0; values >= 65536 clamp to 65535. +float4 AstcFloatToLns4(float4 c) +{ + float4 validPos = float4(c > (1.0 / 67108864.0)); + float4 tooLarge = float4(c >= 65536.0); + float4 safeC = lerp(float4(1.0, 1.0, 1.0, 1.0), min(c, 65536.0), validPos); + + uint4 ai = asuint(safeC); + int4 expVal = (int4)((ai >> 23u) & 0xFFu) - 126; + uint4 mantBits = (ai & 0x807FFFFFu) | 0x3F000000u; + float4 mant = asfloat(mantBits); + + float4 subnorm = float4(expVal < -13); + float4 scaled = lerp((mant - 0.5) * 4096.0, safeC * 33554432.0, subnorm); + float4 lnsExp = (1.0 - subnorm) * (float4)(expVal + 14); + + float4 isLo = float4(scaled < 384.0); + float4 isMid = float4(scaled <= 1408.0); + float4 lnsMant = lerp(lerp((scaled + 512.0) * (4.0 / 5.0), scaled + 128.0, isMid), scaled * (4.0 / 3.0), isLo); + + float4 res = clamp(lnsMant + lnsExp * 2048.0 + 1.0, 0.0, 65535.0); + res = lerp(res, float4(65535.0, 65535.0, 65535.0, 65535.0), tooLarge); + return res * validPos; +} + +uint AstcFloatToHalfU16(float x) +{ + // ASTC HDR UFloat profile encodes non-negative FP16 values in [0, 65504]. + float clamped = (x > 0.0) ? min(x, 65504.0) : 0.0; + return f32tof16(clamped) & 0xFFFFu; +} + +// ============================================================================ +// ASTC HDR Endpoint Quantization (CEM 11 / CEM 14 / CEM 15) +// ============================================================================ + +// Shared per-thread scratch arrays for HDR endpoint quantization (avoids per-call-site indexableTemp explosion in FXC). +static uint g_AstcHdrCodes[6]; +static uint g_AstcHdrRawV[6]; +static uint g_AstcHdrCandCodes[6]; +static uint g_AstcHdrUqV[6]; + +// Exact Khronos ASTC Spec CEM 11 (HDR RGB Direct) hardware unpacker. +// Reads 6 unquantized 8-bit endpoint values from g_AstcHdrUqV[0..5], returns hardware-reconstructed LNS endpoints in [0, 65535]. +void AstcUnpackHdrRgb(out float3 outE0Lns, out float3 outE1Lns) +{ + uint v0 = g_AstcHdrUqV[0]; + uint v1 = g_AstcHdrUqV[1]; + uint v2 = g_AstcHdrUqV[2]; + uint v3 = g_AstcHdrUqV[3]; + uint v4 = g_AstcHdrUqV[4]; + uint v5 = g_AstcHdrUqV[5]; + + uint majcomp = ((v4 & 0x80u) >> 7u) | (((v5 & 0x80u) >> 7u) << 1u); + if (majcomp == 3u) + { + outE0Lns = float3((float)(v0 << 8u), (float)(v2 << 8u), (float)((v4 & 0x7Fu) << 9u)); + outE1Lns = float3((float)(v1 << 8u), (float)(v3 << 8u), (float)((v5 & 0x7Fu) << 9u)); + return; + } + + uint modeval = ((v1 & 0x80u) >> 7u) | (((v2 & 0x80u) >> 7u) << 1u) | (((v3 & 0x80u) >> 7u) << 2u); + + uint a = v0 | ((v1 & 0x40u) << 2u); + uint b0 = v2 & 0x3Fu; + uint b1 = v3 & 0x3Fu; + uint c = v1 & 0x3Fu; + uint d0 = v4 & 0x1Fu; + uint d1 = v5 & 0x1Fu; + + uint dbits = ((modeval == 0u || modeval == 2u) ? 7u : ((modeval == 4u || modeval == 6u) ? 5u : 6u)); + + uint bit0 = (v2 >> 6u) & 1u; + uint bit1 = (v3 >> 6u) & 1u; + uint bit2 = (v4 >> 6u) & 1u; + uint bit3 = (v5 >> 6u) & 1u; + uint bit4 = (v4 >> 5u) & 1u; + uint bit5 = (v5 >> 5u) & 1u; + + uint ohmod = 1u << modeval; + if ((ohmod & 0xA4u) != 0u) a |= bit0 << 9u; + if ((ohmod & 0x08u) != 0u) a |= bit2 << 9u; + if ((ohmod & 0x50u) != 0u) a |= bit4 << 9u; + if ((ohmod & 0x50u) != 0u) a |= bit5 << 10u; + if ((ohmod & 0xA0u) != 0u) a |= bit1 << 10u; + if ((ohmod & 0xC0u) != 0u) a |= bit2 << 11u; + + if ((ohmod & 0x04u) != 0u) c |= bit1 << 6u; + if ((ohmod & 0xE8u) != 0u) c |= bit3 << 6u; + if ((ohmod & 0x20u) != 0u) c |= bit2 << 7u; + + if ((ohmod & 0x5Bu) != 0u) { b0 |= bit0 << 6u; b1 |= bit1 << 6u; } + if ((ohmod & 0x12u) != 0u) { b0 |= bit2 << 7u; b1 |= bit3 << 7u; } + + if ((ohmod & 0xAFu) != 0u) { d0 |= bit4 << 5u; d1 |= bit5 << 5u; } + if ((ohmod & 0x05u) != 0u) { d0 |= bit2 << 6u; d1 |= bit3 << 6u; } + + // Sign-extend d0 and d1 from dbits + uint sxShamt = 32u - dbits; + int d0s = (int)(d0 << sxShamt) >> (int)sxShamt; + int d1s = (int)(d1 << sxShamt) >> (int)sxShamt; + + uint valShamt = (modeval >> 1u) ^ 3u; + int ia = (int)(a << valShamt); + int ib0 = (int)(b0 << valShamt); + int ib1 = (int)(b1 << valShamt); + int ic = (int)(c << valShamt); + int id0 = d0s * (int)(1u << valShamt); + int id1 = d1s * (int)(1u << valShamt); + + int r1 = clamp(ia, 0, 4095); + int g1 = clamp(ia - ib0, 0, 4095); + int bl1 = clamp(ia - ib1, 0, 4095); + int r0 = clamp(ia - ic, 0, 4095); + int g0 = clamp(ia - ib0 - ic - id0, 0, 4095); + int bl0 = clamp(ia - ib1 - ic - id1, 0, 4095); + + if (majcomp == 1u) + { + int t0 = r0; r0 = g0; g0 = t0; + int t1 = r1; r1 = g1; g1 = t1; + } + else if (majcomp == 2u) + { + int t0 = r0; r0 = bl0; bl0 = t0; + int t1 = r1; r1 = bl1; bl1 = t1; + } + + outE0Lns = float3((float)(r0 << 4), (float)(g0 << 4), (float)(bl0 << 4)); + outE1Lns = float3((float)(r1 << 4), (float)(g1 << 4), (float)(bl1 << 4)); +} + +// Packs CEM 11 delta mode fields into 6 8-bit endpoint values in g_AstcHdrRawV[0..5]. +void AstcPackHdrRgbDeltaMode(uint majcomp, uint modeval, uint a, uint b0, uint b1, uint c, uint d0, uint d1) +{ + uint v0 = a & 0xFFu; + uint v1 = ((modeval & 1u) << 7u) | (((a >> 8u) & 1u) << 6u) | (c & 0x3Fu); + uint v2 = (((modeval >> 1u) & 1u) << 7u) | (b0 & 0x3Fu); + uint v3 = (((modeval >> 2u) & 1u) << 7u) | (b1 & 0x3Fu); + uint v4 = ((majcomp & 1u) << 7u) | (d0 & 0x1Fu); + uint v5 = (((majcomp >> 1u) & 1u) << 7u) | (d1 & 0x1Fu); + + uint bit0 = 0u, bit1 = 0u, bit2 = 0u, bit3 = 0u, bit4 = 0u, bit5 = 0u; + if (modeval == 0u) + { + bit0 = (b0 >> 6u) & 1u; bit1 = (b1 >> 6u) & 1u; + bit2 = (d0 >> 6u) & 1u; bit3 = (d1 >> 6u) & 1u; + bit4 = (d0 >> 5u) & 1u; bit5 = (d1 >> 5u) & 1u; + } + else if (modeval == 1u) + { + bit0 = (b0 >> 6u) & 1u; bit1 = (b1 >> 6u) & 1u; + bit2 = (b0 >> 7u) & 1u; bit3 = (b1 >> 7u) & 1u; + bit4 = (d0 >> 5u) & 1u; bit5 = (d1 >> 5u) & 1u; + } + else if (modeval == 2u) + { + bit0 = (a >> 9u) & 1u; bit1 = (c >> 6u) & 1u; + bit2 = (d0 >> 6u) & 1u; bit3 = (d1 >> 6u) & 1u; + bit4 = (d0 >> 5u) & 1u; bit5 = (d1 >> 5u) & 1u; + } + else if (modeval == 3u) + { + bit0 = (b0 >> 6u) & 1u; bit1 = (b1 >> 6u) & 1u; + bit2 = (a >> 9u) & 1u; bit3 = (c >> 6u) & 1u; + bit4 = (d0 >> 5u) & 1u; bit5 = (d1 >> 5u) & 1u; + } + else if (modeval == 4u) + { + bit0 = (b0 >> 6u) & 1u; bit1 = (b1 >> 6u) & 1u; + bit2 = (b0 >> 7u) & 1u; bit3 = (b1 >> 7u) & 1u; + bit4 = (a >> 9u) & 1u; bit5 = (a >> 10u) & 1u; + } + else if (modeval == 5u) + { + bit0 = (a >> 9u) & 1u; bit1 = (a >> 10u) & 1u; + bit2 = (c >> 7u) & 1u; bit3 = (c >> 6u) & 1u; + bit4 = (d0 >> 5u) & 1u; bit5 = (d1 >> 5u) & 1u; + } + else if (modeval == 6u) + { + bit0 = (b0 >> 6u) & 1u; bit1 = (b1 >> 6u) & 1u; + bit2 = (a >> 11u) & 1u; bit3 = (c >> 6u) & 1u; + bit4 = (a >> 9u) & 1u; bit5 = (a >> 10u) & 1u; + } + else + { + bit0 = (a >> 9u) & 1u; bit1 = (a >> 10u) & 1u; + bit2 = (a >> 11u) & 1u; bit3 = (c >> 6u) & 1u; + bit4 = (d0 >> 5u) & 1u; bit5 = (d1 >> 5u) & 1u; + } + + v2 |= bit0 << 6u; + v3 |= bit1 << 6u; + v4 |= (bit2 << 6u) | (bit4 << 5u); + v5 |= (bit3 << 6u) | (bit5 << 5u); + + g_AstcHdrRawV[0] = v0; g_AstcHdrRawV[1] = v1; g_AstcHdrRawV[2] = v2; + g_AstcHdrRawV[3] = v3; g_AstcHdrRawV[4] = v4; g_AstcHdrRawV[5] = v5; +} + +// Encodes HDR RGB endpoints e0, e1 (in LNS [0, 65535]) into g_AstcHdrCodes[0..5] +// using CEM_HDR_RGB_DIRECT (11): tries high-precision majcomp 0/1/2 delta modes (up to 12-bit) +// and compares exact hardware-reconstructed LNS MSE against majcomp == 3 direct mode. +void AstcQuantizeHdrRgbEndpoints( + float3 e0Lns, + float3 e1Lns, + uint epQuant, + out float3 uq0Lns, + out float3 uq1Lns) +{ + // Baseline: majcomp == 3 direct mode (always valid) + g_AstcHdrRawV[0] = (uint)clamp(floor(e0Lns.r / 256.0 + 0.5), 0.0, 255.0); + g_AstcHdrRawV[1] = (uint)clamp(floor(e1Lns.r / 256.0 + 0.5), 0.0, 255.0); + g_AstcHdrRawV[2] = (uint)clamp(floor(e0Lns.g / 256.0 + 0.5), 0.0, 255.0); + g_AstcHdrRawV[3] = (uint)clamp(floor(e1Lns.g / 256.0 + 0.5), 0.0, 255.0); + g_AstcHdrRawV[4] = 128u + (uint)clamp(floor(e0Lns.b / 512.0 + 0.5), 0.0, 127.0); + g_AstcHdrRawV[5] = 128u + (uint)clamp(floor(e1Lns.b / 512.0 + 0.5), 0.0, 127.0); + + [loop] for (uint bi = 0u; bi < 6u; ++bi) + { + uint uqTmp; + g_AstcHdrCodes[bi] = AstcQuantizeColorRange(g_AstcHdrRawV[bi], epQuant, bi >= 4u, uqTmp); + g_AstcHdrUqV[bi] = uqTmp; + } + + uq0Lns = float3((float)(g_AstcHdrUqV[0] << 8u), (float)(g_AstcHdrUqV[2] << 8u), (float)((g_AstcHdrUqV[4] & 0x7Fu) << 9u)); + uq1Lns = float3((float)(g_AstcHdrUqV[1] << 8u), (float)(g_AstcHdrUqV[3] << 8u), (float)((g_AstcHdrUqV[5] & 0x7Fu) << 9u)); + + float3 d0 = uq0Lns - e0Lns; + float3 d1 = uq1Lns - e1Lns; + float bestErr = dot(d0, d0) + dot(d1, d1); + + // High-precision majcomp 0/1/2 delta mode requires e1 to hold the overall major component. + int3 c0_12 = int3( + clamp((int)floor(e0Lns.r / 16.0 + 0.5), 0, 4095), + clamp((int)floor(e0Lns.g / 16.0 + 0.5), 0, 4095), + clamp((int)floor(e0Lns.b / 16.0 + 0.5), 0, 4095)); + int3 c1_12 = int3( + clamp((int)floor(e1Lns.r / 16.0 + 0.5), 0, 4095), + clamp((int)floor(e1Lns.g / 16.0 + 0.5), 0, 4095), + clamp((int)floor(e1Lns.b / 16.0 + 0.5), 0, 4095)); + + int max0 = max(c0_12.r, max(c0_12.g, c0_12.b)); + int max1 = max(c1_12.r, max(c1_12.g, c1_12.b)); + if (max1 < max0) + { + return; + } + + uint majcomp = 0u; + int R0 = c0_12.r, G0 = c0_12.g, B0 = c0_12.b; + int R1 = c1_12.r, G1 = c1_12.g, B1 = c1_12.b; + if (c1_12.g >= c1_12.r && c1_12.g >= c1_12.b) + { + majcomp = 1u; + R0 = c0_12.g; G0 = c0_12.r; B0 = c0_12.b; + R1 = c1_12.g; G1 = c1_12.r; B1 = c1_12.b; + } + else if (c1_12.b > c1_12.r && c1_12.b > c1_12.g) + { + majcomp = 2u; + R0 = c0_12.b; G0 = c0_12.g; B0 = c0_12.r; + R1 = c1_12.b; G1 = c1_12.g; B1 = c1_12.r; + } + + int A_12 = R1; + int B0_12 = R1 - G1; + int B1_12 = R1 - B1; + int C_12 = R1 - R0; + int D0_12 = (R0 - G0) - B0_12; + int D1_12 = (R0 - B0) - B1_12; + + // Try finest resolution modes first (modeval 7..0) and pick the first that fits. + [loop] for (uint mi = 0u; mi < 8u; ++mi) + { + uint mv = 7u - mi; + uint sh = (mv >> 1u) ^ 3u; + uint bb = (mv == 1u || mv == 4u) ? 8u : ((mv == 0u || mv == 3u || mv == 6u) ? 7u : 6u); + uint cb = (mv == 5u) ? 8u : ((mv == 2u || mv == 3u || mv == 6u || mv == 7u) ? 7u : 6u); + uint db = (mv == 0u || mv == 2u) ? 7u : ((mv == 4u || mv == 6u) ? 5u : 6u); + + int halfStep = (sh > 0u) ? (int)(1u << (sh - 1u)) : 0; + int aS = min((int)((1u << (12u - sh)) - 1u), (A_12 + halfStep) >> (int)sh); + int b0S = (B0_12 + halfStep) >> (int)sh; + int b1S = (B1_12 + halfStep) >> (int)sh; + int cS = (C_12 + halfStep) >> (int)sh; + float invStep = 1.0 / (float)(1u << sh); + int d0S = (int)floor((float)D0_12 * invStep + 0.5); + int d1S = (int)floor((float)D1_12 * invStep + 0.5); + + int dMin = -(int)(1u << (db - 1u)); + int dMax = (int)(1u << (db - 1u)) - 1; + if (b0S >= 0 && b0S < (int)(1u << bb) + && b1S >= 0 && b1S < (int)(1u << bb) + && cS >= 0 && cS < (int)(1u << cb) + && d0S >= dMin && d0S <= dMax + && d1S >= dMin && d1S <= dMax) + { + uint dMask = (1u << db) - 1u; + AstcPackHdrRgbDeltaMode(majcomp, mv, (uint)aS, (uint)b0S, (uint)b1S, (uint)cS, ((uint)d0S) & dMask, ((uint)d1S) & dMask); + + [loop] for (uint ci = 0u; ci < 6u; ++ci) + { + uint uqTmp; + g_AstcHdrCandCodes[ci] = AstcQuantizeColor(g_AstcHdrRawV[ci], epQuant, uqTmp); + g_AstcHdrUqV[ci] = uqTmp; + } + + float3 cand0, cand1; + AstcUnpackHdrRgb(cand0, cand1); + float3 cd0 = cand0 - e0Lns; + float3 cd1 = cand1 - e1Lns; + float candErr = dot(cd0, cd0) + dot(cd1, cd1); + if (candErr < bestErr) + { + [loop] for (uint cj = 0u; cj < 6u; ++cj) g_AstcHdrCodes[cj] = g_AstcHdrCandCodes[cj]; + uq0Lns = cand0; + uq1Lns = cand1; + } + break; + } + } +} + +// Encodes HDR Alpha endpoints a0, a1 (in LNS [0, 65535]) for CEM_HDR_RGBA_DIRECT (15) +// using direct modeval == 3 (bit 7 == 1 on both endpoints). +void AstcQuantizeHdrAlphaEndpoints( + float a0Lns, + float a1Lns, + uint epQuant, + out uint code0, + out uint code1, + out float uqA0Lns, + out float uqA1Lns) +{ + uint a0 = 128u + (uint)clamp(floor(a0Lns / 512.0 + 0.5), 0.0, 127.0); + uint a1 = 128u + (uint)clamp(floor(a1Lns / 512.0 + 0.5), 0.0, 127.0); + + uint uq0, uq1; + code0 = AstcQuantizeColorMin128(a0, epQuant, uq0); + code1 = AstcQuantizeColorMin128(a1, epQuant, uq1); + + uqA0Lns = (float)((uq0 & 0x7Fu) << 9u); + uqA1Lns = (float)((uq1 & 0x7Fu) << 9u); +} + +// ============================================================================ +// ASTC 2-Partition Procedural Hash (Khronos Spec Section 22.21) +// ============================================================================ + +uint AstcHash52(uint inp) +{ + inp ^= inp >> 15u; + inp *= 0xEEDE0891u; + inp ^= inp >> 5u; + inp += inp << 16u; + inp ^= inp >> 7u; + inp ^= inp >> 3u; + inp ^= inp << 6u; + inp ^= inp >> 17u; + return inp; +} + +struct AstcPart2Params +{ + uint seed1; + uint seed2; + uint seed3; + uint seed4; + uint offA; + uint offB; +}; + +// Precomputes all seed-dependent Khronos Section 22.21 2-partition hash parameters once outside pixel loops. +AstcPart2Params AstcPreparePartition2(uint seed, bool smallBlock) +{ + uint s = seed + 1024u; + uint rnum = AstcHash52(s); + + uint seed1 = (rnum & 0xFu); seed1 *= seed1; + uint seed2 = ((rnum >> 4u) & 0xFu); seed2 *= seed2; + uint seed3 = ((rnum >> 8u) & 0xFu); seed3 *= seed3; + uint seed4 = ((rnum >> 12u) & 0xFu); seed4 *= seed4; + + uint sh1, sh2; + if ((s & 1u) != 0u) + { + sh1 = ((s & 2u) != 0u) ? 4u : 5u; + sh2 = 5u; + } + else + { + sh1 = 5u; + sh2 = ((s & 2u) != 0u) ? 4u : 5u; + } + + seed1 >>= sh1; + seed2 >>= sh2; + seed3 >>= sh1; + seed4 >>= sh2; + + if (smallBlock) + { + seed1 <<= 1u; + seed2 <<= 1u; + seed3 <<= 1u; + seed4 <<= 1u; + } + + AstcPart2Params p; + p.seed1 = seed1; + p.seed2 = seed2; + p.seed3 = seed3; + p.seed4 = seed4; + p.offA = rnum >> 14u; + p.offB = rnum >> 10u; + return p; +} + +uint AstcEvalPartition2(AstcPart2Params p, uint x, uint y) +{ + uint a = (p.seed1 * x + p.seed2 * y + p.offA) & 0x3Fu; + uint b = (p.seed3 * x + p.seed4 * y + p.offB) & 0x3Fu; + return (b > a) ? 1u : 0u; +} + +// Returns partition index (0 or 1) for 2-partition ASTC block at texel (x, y). +// smallBlock must be true when (blockX * blockY) < 32 (i.e. 4x4 and 5x5). +uint AstcSelectPartition2(uint seed, uint x, uint y, bool smallBlock) +{ + return AstcEvalPartition2(AstcPreparePartition2(seed, smallBlock), x, y); +} + +// ============================================================================ +// ASTC Hardware Bilinear Weight Grid Infill (Khronos Spec Section 22.17) +// ============================================================================ + +// Computes bilinear grid coordinates (js, jt) and 4 integer weights (w00, w10, w01, w11) +// summing to 16 for texel (x, y) in a (blockX, blockY) block using a (gridW, gridH) weight grid. +void AstcComputeInfillTap( + uint x, uint y, + uint blockX, uint blockY, + uint gridW, uint gridH, + out uint js, out uint jt, + out uint4 tapWeights) +{ + uint ds = (1024u + (blockX >> 1u)) / (blockX - 1u); + uint dt = (1024u + (blockY >> 1u)) / (blockY - 1u); + uint cs = ds * x; + uint ct = dt * y; + + uint gs = (cs * (gridW - 1u) + 32u) >> 6u; + uint gt = (ct * (gridH - 1u) + 32u) >> 6u; + + js = gs >> 4u; + jt = gt >> 4u; + uint fs = gs & 15u; + uint ft = gt & 15u; + + uint w11 = (fs * ft + 8u) >> 4u; + uint w10 = fs - w11; + uint w01 = ft - w11; + uint w00 = 16u - fs - ft + w11; + + tapWeights = uint4(w00, w10, w01, w11); +} + +// Evaluates the exact ASTC hardware interpolated weight [0, 64] at texel (x, y) +// from a local unquantized grid array gridUq[36] without passing the array by value. +#define ASTC_EVAL_INFILL(gridUq, tx, ty, bx, by, gw, gh, outWeight64) \ + if ((gw) == (bx) && (gh) == (by)) \ + { \ + (outWeight64) = (gridUq)[(ty) * (gw) + (tx)]; \ + } \ + else \ + { \ + uint _js, _jt; \ + uint4 _tw; \ + AstcComputeInfillTap((tx), (ty), (bx), (by), (gw), (gh), _js, _jt, _tw); \ + uint _idx00 = _jt * (gw) + _js; \ + uint _p00 = (gridUq)[_idx00]; \ + uint _p10 = (_tw.y > 0u) ? (gridUq)[_idx00 + 1u] : 0u; \ + uint _p01 = (_tw.z > 0u) ? (gridUq)[_idx00 + (gw)] : 0u; \ + uint _p11 = (_tw.w > 0u) ? (gridUq)[_idx00 + (gw) + 1u] : 0u; \ + (outWeight64) = (_p00 * _tw.x + _p10 * _tw.y + _p01 * _tw.z + _p11 * _tw.w + 8u) >> 4u; \ + } + +#endif // ASTC_GPU_COLOR_HLSL diff --git a/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuColor.hlsl.meta b/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuColor.hlsl.meta new file mode 100644 index 0000000..debb93e --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuColor.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: ff09c5f541f7b9e3e5fd1f421494c750 +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuCore.hlsl b/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuCore.hlsl new file mode 100644 index 0000000..3ac11d8 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuCore.hlsl @@ -0,0 +1,1809 @@ +#ifndef ASTC_GPU_CORE_HLSL +#define ASTC_GPU_CORE_HLSL + +#include "AstcGpuColor.hlsl" + +#define ASTC_MODE_LDR_RGB 0u +#define ASTC_MODE_LDR_RGBA 1u +#define ASTC_MODE_LDR_NORMAL 2u +#define ASTC_MODE_HDR_RGB 3u +#define ASTC_MODE_HDR_RGBA 4u + +// Internal effective sub-modes resolved per block (HDR RGBA can auto-select CEM 11/14/15) +#define ASTC_EFF_LDR_RGB 0u // CEM 8 (6 ep) +#define ASTC_EFF_LDR_RGBA 1u // CEM 12 (8 ep) +#define ASTC_EFF_LDR_NORMAL 2u // CEM 4 (4 ep: L=G, A=R) +#define ASTC_EFF_HDR_RGB 3u // CEM 11 (6 ep: HDR RGB) +#define ASTC_EFF_HDR_RGB_LDR_ALPHA 4u // CEM 14 (8 ep: HDR RGB + LDR A) +#define ASTC_EFF_HDR_RGBA 5u // CEM 15 (8 ep: HDR RGB + HDR A) + +struct AstcCandidate +{ + uint blockMode; + uint gridW; + uint gridH; + uint wQuant; + uint epQuant; + uint isDualPlane; + uint dualPlaneChannel; + uint isTwoPart; + uint partSeed; + float error; + float4 e0; + float4 e1; + float4 e0_p1; + float4 e1_p1; +}; + +#if BLOCK_X <= 4 +#define ASTC_MAX_GRID 16 +#define ASTC_MAX_GRID_U 16u +#elif BLOCK_X <= 5 +#define ASTC_MAX_GRID 25 +#define ASTC_MAX_GRID_U 25u +#else +#define ASTC_MAX_GRID 36 +#define ASTC_MAX_GRID_U 36u +#endif + +// Shared per-thread scratch arrays: eliminates per-call-site local indexableTemp arrays +// and array-by-value copies across functions (prevents FXC/HLSLcc/DXC compile timeouts). +static float g_AstcGrid0[ASTC_MAX_GRID]; +static float g_AstcGrid1[ASTC_MAX_GRID]; +static float g_AstcDecimNum[ASTC_MAX_GRID]; +static float g_AstcDecimDen[ASTC_MAX_GRID]; +static uint g_AstcGridUq0[ASTC_MAX_GRID]; +static uint g_AstcGridUq1[ASTC_MAX_GRID]; +static uint g_AstcEpCodes[16]; +static uint g_AstcCandEpCodes[16]; +static uint g_AstcEpVals[8]; +static uint g_AstcEpCArr[8]; +static uint g_AstcEpUqArr[8]; + +// On-chip per-thread packed 4x16-bit working-pixel cache (16..144 uint2s = 128..1152 bytes per thread). +// Eliminates redundant texture loads, sRGB, and HDR LNS conversions across all 18+ fetch call sites +// and keeps FXC/HLSLcc/Metal shader compilation fast for >=8x8 kernels. +#define ASTC_ENABLE_PIXEL_CACHE 1 +static uint2 g_AstcPackedBlock[BLOCK_X * BLOCK_Y]; + +uint2 AstcPackRgba16(float4 v) +{ + uint4 u = (uint4)clamp(floor(v + 0.5), 0.0, 65535.0); + return uint2(u.x | (u.y << 16u), u.z | (u.w << 16u)); +} + +// Loads and converts one texel from _AstcSourceTex into working space (single shared sRGB + LNS path). +float4 AstcLoadWorkingPixel(uint baseX, uint baseY, uint x, uint y, uint effMode, out float impWeight) +{ + impWeight = 1.0; + + uint px = min(baseX + x, _AstcSrcWidth - 1u); + uint py = min(baseY + y, _AstcSrcHeight - 1u); + float4 raw = _AstcSourceTex.Load(int3(px, py, _AstcMipLevel)); + + if (effMode <= ASTC_EFF_LDR_NORMAL) + { + float3 rgb = (_AstcIsSRGB != 0u) ? AstcLinearToSRGB(raw.rgb) : saturate(raw.rgb); + if (effMode == ASTC_EFF_LDR_NORMAL) + { + return float4(rgb.g * 255.0, 0.0, 0.0, rgb.r * 255.0); + } + float a = (effMode == ASTC_EFF_LDR_RGB) ? 1.0 : saturate(raw.a); + if (effMode == ASTC_EFF_LDR_RGBA && _AstcUseAlphaWeight != 0u) + { + impWeight = max(a, 0.02); + } + return float4(rgb * 255.0, a * 255.0); + } + + // HDR modes: share a single branchless vectorized LNS conversion + float4 lns = AstcFloatToLns4(raw); + if (effMode == ASTC_EFF_HDR_RGB) + { + return float4(lns.rgb, 65535.0); + } + if (effMode == ASTC_EFF_HDR_RGB_LDR_ALPHA) + { + // Scale LDR alpha [0,1] into [0, 65535] to balance vector norm with LNS RGB. + return float4(lns.rgb, saturate(raw.a) * 65535.0); + } + + // ASTC_EFF_HDR_RGBA + return lns; +} + +// Fetches one texel in the encoder's working space for the current effective mode. +float4 AstcFetchWorkingPixel(uint baseX, uint baseY, uint x, uint y, uint effMode, out float impWeight) +{ +#if ASTC_ENABLE_PIXEL_CACHE + impWeight = 1.0; + uint2 packed = g_AstcPackedBlock[y * BLOCK_X + x]; + float4 cached = float4( + (float)(packed.x & 0xFFFFu), + (float)(packed.x >> 16u), + (float)(packed.y & 0xFFFFu), + (float)(packed.y >> 16u)); + if (effMode == ASTC_EFF_LDR_RGBA && _AstcUseAlphaWeight != 0u) + { + impWeight = max(cached.a * (1.0 / 255.0), 0.02); + } + return cached; +#else + return AstcLoadWorkingPixel(baseX, baseY, x, y, effMode, impWeight); +#endif +} + +// Per-channel importance weight: weights RGB by alpha when UseAlphaWeight is active, +// while always keeping Alpha at full 1.0 weight so transparent edges stay accurate. +float4 AstcGetChannelImp(uint effMode, float imp) +{ + return (effMode == ASTC_EFF_LDR_RGBA && _AstcUseAlphaWeight != 0u) + ? float4(imp, imp, imp, 1.0) + : float4(1.0, 1.0, 1.0, 1.0); +} + +float4 AstcClampWorkingColor(float4 c, uint effMode) +{ + float maxVal = (effMode >= ASTC_EFF_HDR_RGB) ? 65535.0 : 255.0; + return clamp(c, 0.0, maxVal); +} + +uint AstcGetCemForEffMode(uint effMode) +{ + if (effMode == ASTC_EFF_LDR_NORMAL) return ASTC_CEM_LDR_LUM_ALPHA_DIRECT; + if (effMode == ASTC_EFF_LDR_RGB) return ASTC_CEM_LDR_RGB_DIRECT; + if (effMode == ASTC_EFF_LDR_RGBA) return ASTC_CEM_LDR_RGBA_DIRECT; + if (effMode == ASTC_EFF_HDR_RGB) return ASTC_CEM_HDR_RGB_DIRECT; + if (effMode == ASTC_EFF_HDR_RGB_LDR_ALPHA) return ASTC_CEM_HDR_RGB_LDR_ALPHA; + return ASTC_CEM_HDR_RGBA_DIRECT; +} + +uint AstcGetEpCountForEffMode(uint effMode) +{ + if (effMode == ASTC_EFF_LDR_NORMAL) return 4u; + if (effMode == ASTC_EFF_LDR_RGB || effMode == ASTC_EFF_HDR_RGB) return 6u; + return 8u; +} + +float AstcGetChannel(float4 v, uint ch) +{ + if (ch == 0u) return v.r; + if (ch == 1u) return v.g; + if (ch == 2u) return v.b; + return v.a; +} + +float4 AstcSetChannel(float4 v, uint ch, float val) +{ + if (ch == 0u) v.r = val; + else if (ch == 1u) v.g = val; + else if (ch == 2u) v.b = val; + else v.a = val; + return v; +} + +// Channel mask for 1-plane or dual-plane (plane 0) calculations. +// excludedChannel == 4u means no channel is excluded. +float4 AstcChannelMaskEx(uint effMode, uint excludedChannel) +{ + float4 m; + if (effMode == ASTC_EFF_LDR_NORMAL) + { + m = float4(1.0, 0.0, 0.0, 1.0); + } + else if (effMode == ASTC_EFF_LDR_RGB || effMode == ASTC_EFF_HDR_RGB) + { + m = float4(1.0, 1.0, 1.0, 0.0); + } + else + { + m = float4(1.0, 1.0, 1.0, 1.0); + } + + if (excludedChannel < 4u) + { + m = AstcSetChannel(m, excludedChannel, 0.0); + } + return m; +} + +// Canonicalizes endpoint order so hardware decoding (LDR CEM 8/12 blue-contraction +// avoidance and HDR CEM 11/14/15 major-component delta modes) does not invert weights +// that were projected prior to endpoint quantization. +void AstcCanonicalizeEndpoints(uint effMode, inout float4 e0, inout float4 e1) +{ + if (effMode == ASTC_EFF_LDR_RGB || effMode == ASTC_EFF_LDR_RGBA) + { + if ((e0.r + e0.g + e0.b) > (e1.r + e1.g + e1.b)) + { + float4 tmp = e0; e0 = e1; e1 = tmp; + } + } + else if (effMode >= ASTC_EFF_HDR_RGB) + { + float maxRgb0 = max(e0.r, max(e0.g, e0.b)); + float maxRgb1 = max(e1.r, max(e1.g, e1.b)); + if (maxRgb0 > maxRgb1) + { + float4 tmp = e0; e0 = e1; e1 = tmp; + } + } +} + +// Quantizes one partition's endpoints (e0, e1) according to effMode and epQuant. +// Writes codes into g_AstcEpCodes[codeOffset..] and returns exact hardware-reconstructed uqE0, uqE1. +void AstcQuantizeEndpoints( + float4 e0, + float4 e1, + uint effMode, + uint epQuant, + uint codeOffset, + out float4 uqE0, + out float4 uqE1, + out bool swapped) +{ + uqE0 = float4(0.0, 0.0, 0.0, 255.0); + uqE1 = float4(0.0, 0.0, 0.0, 255.0); + swapped = false; + + if (effMode == ASTC_EFF_LDR_NORMAL) + { + g_AstcEpVals[0] = (uint)clamp(floor(e0.x + 0.5), 0.0, 255.0); + g_AstcEpVals[1] = (uint)clamp(floor(e1.x + 0.5), 0.0, 255.0); + g_AstcEpVals[2] = (uint)clamp(floor(e0.w + 0.5), 0.0, 255.0); + g_AstcEpVals[3] = (uint)clamp(floor(e1.w + 0.5), 0.0, 255.0); + + [loop] for (uint i = 0u; i < 4u; ++i) + { + uint uqTmp; + g_AstcEpCodes[codeOffset + i] = AstcQuantizeColor(g_AstcEpVals[i], epQuant, uqTmp); + g_AstcEpUqArr[i] = uqTmp; + } + + uqE0 = float4((float)g_AstcEpUqArr[0], 0.0, 0.0, (float)g_AstcEpUqArr[2]); + uqE1 = float4((float)g_AstcEpUqArr[1], 0.0, 0.0, (float)g_AstcEpUqArr[3]); + return; + } + + if (effMode == ASTC_EFF_LDR_RGB || effMode == ASTC_EFF_LDR_RGBA) + { + g_AstcEpVals[0] = (uint)clamp(floor(e0.r + 0.5), 0.0, 255.0); + g_AstcEpVals[1] = (uint)clamp(floor(e1.r + 0.5), 0.0, 255.0); + g_AstcEpVals[2] = (uint)clamp(floor(e0.g + 0.5), 0.0, 255.0); + g_AstcEpVals[3] = (uint)clamp(floor(e1.g + 0.5), 0.0, 255.0); + g_AstcEpVals[4] = (uint)clamp(floor(e0.b + 0.5), 0.0, 255.0); + g_AstcEpVals[5] = (uint)clamp(floor(e1.b + 0.5), 0.0, 255.0); + g_AstcEpVals[6] = (uint)clamp(floor(e0.a + 0.5), 0.0, 255.0); + g_AstcEpVals[7] = (uint)clamp(floor(e1.a + 0.5), 0.0, 255.0); + + [loop] for (uint z = 0u; z < 8u; ++z) { g_AstcEpCArr[z] = 0u; g_AstcEpUqArr[z] = 255u; } + + uint cnt = (effMode == ASTC_EFF_LDR_RGBA) ? 8u : 6u; + [loop] for (uint i = 0u; i < cnt; ++i) + { + uint uqTmp; + g_AstcEpCArr[i] = AstcQuantizeColor(g_AstcEpVals[i], epQuant, uqTmp); + g_AstcEpUqArr[i] = uqTmp; + } + + // Khronos ASTC spec: CEM 8/12 triggers blue-contraction & endpoint swap whenever (r1+g1+b1) < (r0+g0+b0). + // Guarantee s1 >= s0 so hardware always decodes direct endpoints without unexpected contraction/inversion. + if ((g_AstcEpUqArr[0] + g_AstcEpUqArr[2] + g_AstcEpUqArr[4]) > (g_AstcEpUqArr[1] + g_AstcEpUqArr[3] + g_AstcEpUqArr[5])) + { + swapped = true; + [loop] for (uint s = 0u; s < 8u; s += 2u) + { + uint tc = g_AstcEpCArr[s]; g_AstcEpCArr[s] = g_AstcEpCArr[s + 1u]; g_AstcEpCArr[s + 1u] = tc; + uint tu = g_AstcEpUqArr[s]; g_AstcEpUqArr[s] = g_AstcEpUqArr[s + 1u]; g_AstcEpUqArr[s + 1u] = tu; + } + } + + [loop] for (uint k = 0u; k < cnt; ++k) + { + g_AstcEpCodes[codeOffset + k] = g_AstcEpCArr[k]; + } + + uqE0 = float4((float)g_AstcEpUqArr[0], (float)g_AstcEpUqArr[2], (float)g_AstcEpUqArr[4], (float)g_AstcEpUqArr[6]); + uqE1 = float4((float)g_AstcEpUqArr[1], (float)g_AstcEpUqArr[3], (float)g_AstcEpUqArr[5], (float)g_AstcEpUqArr[7]); + return; + } + + // HDR RGB / HDR RGB + LDR Alpha / HDR RGBA + // Orient endpoints so e1 holds the major RGB component, enabling CEM 11 high-precision delta modes. + float maxRgb0 = max(e0.r, max(e0.g, e0.b)); + float maxRgb1 = max(e1.r, max(e1.g, e1.b)); + if (maxRgb0 > maxRgb1) + { + swapped = true; + float4 tmp = e0; e0 = e1; e1 = tmp; + } + + float3 uqRgb0, uqRgb1; + AstcQuantizeHdrRgbEndpoints(e0.rgb, e1.rgb, epQuant, uqRgb0, uqRgb1); + [loop] for (uint hi = 0u; hi < 6u; ++hi) + { + g_AstcEpCodes[codeOffset + hi] = g_AstcHdrCodes[hi]; + } + + uqE0 = float4(uqRgb0, 65535.0); + uqE1 = float4(uqRgb1, 65535.0); + + if (effMode == ASTC_EFF_HDR_RGB_LDR_ALPHA || effMode == ASTC_EFF_HDR_RGBA) + { + bool isHdrA = (effMode == ASTC_EFF_HDR_RGBA); + uint aIn0 = isHdrA + ? (128u + (uint)clamp(floor(e0.a / 512.0 + 0.5), 0.0, 127.0)) + : (uint)clamp(floor(e0.a / 257.0 + 0.5), 0.0, 255.0); + uint aIn1 = isHdrA + ? (128u + (uint)clamp(floor(e1.a / 512.0 + 0.5), 0.0, 127.0)) + : (uint)clamp(floor(e1.a / 257.0 + 0.5), 0.0, 255.0); + uint uqA0 = 0u, uqA1 = 0u; + [loop] for (uint ai = 0u; ai < 2u; ++ai) + { + uint uqTmp; + g_AstcEpCodes[codeOffset + 6u + ai] = AstcQuantizeColorRange((ai == 0u) ? aIn0 : aIn1, epQuant, isHdrA, uqTmp); + if (ai == 0u) uqA0 = uqTmp; else uqA1 = uqTmp; + } + uqE0.a = isHdrA ? (float)((uqA0 & 0x7Fu) << 9u) : (float)(uqA0 * 257u); + uqE1.a = isHdrA ? (float)((uqA1 & 0x7Fu) << 9u) : (float)(uqA1 * 257u); + } +} + +// Fits principal-axis endpoints for a single subset (partFilter == 2 means all texels). +// excludedChannel == 4u means all active channels participate; 0..3 excludes that channel for Dual-Plane plane 0. +void AstcFitSubsetEndpoints( + uint baseX, uint baseY, + uint effMode, + uint excludedChannel, + uint partSeed, + uint partFilter, + uint refineIters, + out float4 outE0, + out float4 outE1) +{ + float4 mask = AstcChannelMaskEx(effMode, excludedChannel); + bool smallBlock = (BLOCK_X * BLOCK_Y) < 32u; + + // Pass 1: per-channel weighted mean & bounds + float4 sumP = 0.0; + float4 sumW = 0.0; + float4 minC = float4(1e9, 1e9, 1e9, 1e9); + float4 maxC = float4(-1e9, -1e9, -1e9, -1e9); + + [loop] for (uint y = 0u; y < BLOCK_Y; ++y) + { + [loop] for (uint x = 0u; x < BLOCK_X; ++x) + { + if (partFilter < 2u && AstcSelectPartition2(partSeed, x, y, smallBlock) != partFilter) + continue; + + float imp; + float4 p = AstcFetchWorkingPixel(baseX, baseY, x, y, effMode, imp); + float4 chImp = AstcGetChannelImp(effMode, imp); + sumP += p * chImp; + sumW += chImp; + minC = min(minC, p); + maxC = max(maxC, p); + } + } + + if (sumW.a <= 1e-6) + { + outE0 = 0.0; + outE1 = 0.0; + return; + } + + float4 meanP = sumP / max(sumW, 1e-6); + + // Special fast exact path for 1D channels (Normal plane0 = L only) + if (effMode == ASTC_EFF_LDR_NORMAL && excludedChannel == 3u) + { + outE0 = float4(minC.x, 0.0, 0.0, minC.w); + outE1 = float4(maxC.x, 0.0, 0.0, maxC.w); + return; + } + + // Pass 2: MaxAccum principal axis (ARM astcenc style) + float4 acc0 = 0.0, acc1 = 0.0, acc2 = 0.0, acc3 = 0.0; + [loop] for (uint y2 = 0u; y2 < BLOCK_Y; ++y2) + { + [loop] for (uint x2 = 0u; x2 < BLOCK_X; ++x2) + { + if (partFilter < 2u && AstcSelectPartition2(partSeed, x2, y2, smallBlock) != partFilter) + continue; + + float imp; + float4 p = AstcFetchWorkingPixel(baseX, baseY, x2, y2, effMode, imp); + float4 chImp = AstcGetChannelImp(effMode, imp); + float4 d = (p - meanP) * mask * chImp; + acc0 += (d.x >= 0.0) ? d : -d; + acc1 += (d.y >= 0.0) ? d : -d; + acc2 += (d.z >= 0.0) ? d : -d; + acc3 += (d.w >= 0.0) ? d : -d; + } + } + + float l0 = dot(acc0, acc0); + float l1 = dot(acc1, acc1); + float l2 = dot(acc2, acc2); + float l3 = dot(acc3, acc3); + + float4 axis = acc0; + float bestL = l0; + if (l1 > bestL) { bestL = l1; axis = acc1; } + if (l2 > bestL) { bestL = l2; axis = acc2; } + if (l3 > bestL) { bestL = l3; axis = acc3; } + + if (bestL <= 1e-8) + { + outE0 = AstcClampWorkingColor(minC, effMode); + outE1 = AstcClampWorkingColor(maxC, effMode); + return; + } + + axis *= rsqrt(bestL); + + // Pass 3: Project onto principal axis for initial [minT, maxT] endpoints + float minT = 1e9; + float maxT = -1e9; + [loop] for (uint y3 = 0u; y3 < BLOCK_Y; ++y3) + { + [loop] for (uint x3 = 0u; x3 < BLOCK_X; ++x3) + { + if (partFilter < 2u && AstcSelectPartition2(partSeed, x3, y3, smallBlock) != partFilter) + continue; + + float imp; + float4 p = AstcFetchWorkingPixel(baseX, baseY, x3, y3, effMode, imp); + float t = dot((p - meanP) * mask, axis); + minT = min(minT, t); + maxT = max(maxT, t); + } + } + + float4 e0 = AstcClampWorkingColor(meanP + axis * minT, effMode); + float4 e1 = AstcClampWorkingColor(meanP + axis * maxT, effMode); + +#if !defined(ASTC_FAST_ONLY) + // Optional least-squares endpoint refinement with separate RGB (imp) and Alpha (1.0) normal equations + [loop] for (uint iter = 0u; iter < refineIters; ++iter) + { + float4 dir = (e1 - e0) * mask; + if (dot(dir, dir) <= 1e-6) break; + + float a00_rgb = 0.0, a01_rgb = 0.0, a11_rgb = 0.0; + float a00_a = 0.0, a01_a = 0.0, a11_a = 0.0; + float4 b0 = 0.0, b1 = 0.0; + + [loop] for (uint yr = 0u; yr < BLOCK_Y; ++yr) + { + [loop] for (uint xr = 0u; xr < BLOCK_X; ++xr) + { + if (partFilter < 2u && AstcSelectPartition2(partSeed, xr, yr, smallBlock) != partFilter) + continue; + + float imp; + float4 p = AstcFetchWorkingPixel(baseX, baseY, xr, yr, effMode, imp); + float4 chImp = AstcGetChannelImp(effMode, imp); + float4 wDir = dir * chImp; + float denom = dot(wDir, dir); + float w = (denom > 1e-6) ? saturate(dot((p - e0) * mask, wDir) / denom) : 0.0; + float omw = 1.0 - w; + + float wRgb = chImp.x; + a00_rgb += wRgb * omw * omw; + a01_rgb += wRgb * w * omw; + a11_rgb += wRgb * w * w; + + a00_a += omw * omw; + a01_a += w * omw; + a11_a += w * w; + + b0 += p * (chImp * omw); + b1 += p * (chImp * w); + } + } + + float detRgb = a00_rgb * a11_rgb - a01_rgb * a01_rgb; + if (detRgb > 1e-4) + { + float invDetRgb = 1.0 / detRgb; + float3 newE0Rgb = (a11_rgb * b0.rgb - a01_rgb * b1.rgb) * invDetRgb; + float3 newE1Rgb = (a00_rgb * b1.rgb - a01_rgb * b0.rgb) * invDetRgb; + e0.rgb = lerp(e0.rgb, AstcClampWorkingColor(float4(newE0Rgb, 0.0), effMode).rgb, mask.rgb); + e1.rgb = lerp(e1.rgb, AstcClampWorkingColor(float4(newE1Rgb, 0.0), effMode).rgb, mask.rgb); + } + + float detA = a00_a * a11_a - a01_a * a01_a; + if (mask.a > 0.0 && detA > 1e-4) + { + float invDetA = 1.0 / detA; + float newE0A = (a11_a * b0.a - a01_a * b1.a) * invDetA; + float newE1A = (a00_a * b1.a - a01_a * b0.a) * invDetA; + e0.a = AstcClampWorkingColor(float4(0.0, 0.0, 0.0, newE0A), effMode).a; + e1.a = AstcClampWorkingColor(float4(0.0, 0.0, 0.0, newE1A), effMode).a; + } + } +#endif + + if (excludedChannel < 4u) + { + e0 = AstcSetChannel(e0, excludedChannel, AstcGetChannel(minC, excludedChannel)); + e1 = AstcSetChannel(e1, excludedChannel, AstcGetChannel(maxC, excludedChannel)); + } + + AstcCanonicalizeEndpoints(effMode, e0, e1); + outE0 = e0; + outE1 = e1; +} + +// Projects block pixels onto (e0, e1) and decimates onto g_AstcGrid0 (gridW x gridH). +void AstcComputeWeightGrid1P( + uint baseX, uint baseY, + uint effMode, + uint excludedChannel, + float4 e0, float4 e1, + uint gridW, uint gridH) +{ + uint gridCount = gridW * gridH; + [loop] for (uint i = 0u; i < ASTC_MAX_GRID_U; ++i) + { + g_AstcGrid0[i] = 0.0; + g_AstcDecimNum[i] = 0.0; + g_AstcDecimDen[i] = 0.0; + } + + float4 mask = AstcChannelMaskEx(effMode, excludedChannel); + float4 dir = (e1 - e0) * mask; + bool exactGrid = (gridW == BLOCK_X && gridH == BLOCK_Y); + bool alphaWeightsRgbOnly = (mask.a == 0.0 && effMode == ASTC_EFF_LDR_RGBA && _AstcUseAlphaWeight != 0u); + + [loop] for (uint y = 0u; y < BLOCK_Y; ++y) + { + [loop] for (uint x = 0u; x < BLOCK_X; ++x) + { + float imp; + float4 p = AstcFetchWorkingPixel(baseX, baseY, x, y, effMode, imp); + float4 chImp = AstcGetChannelImp(effMode, imp); + float4 wDir = dir * chImp; + float denom = dot(wDir, dir); + float t = (denom > 1e-6) ? saturate(dot((p - e0) * mask, wDir) / denom) : 0.0; + + if (exactGrid) + { + g_AstcGrid0[y * gridW + x] = t; + } + else + { + uint js, jt; + uint4 tw; + AstcComputeInfillTap(x, y, BLOCK_X, BLOCK_Y, gridW, gridH, js, jt, tw); + uint idx00 = jt * gridW + js; + float decW = alphaWeightsRgbOnly ? imp : 1.0; + float f00 = (float)tw.x * decW; + float f10 = (float)tw.y * decW; + float f01 = (float)tw.z * decW; + float f11 = (float)tw.w * decW; + + g_AstcDecimNum[idx00] += f00 * t; g_AstcDecimDen[idx00] += f00; + if (tw.y > 0u) { g_AstcDecimNum[idx00 + 1u] += f10 * t; g_AstcDecimDen[idx00 + 1u] += f10; } + if (tw.z > 0u) { g_AstcDecimNum[idx00 + gridW] += f01 * t; g_AstcDecimDen[idx00 + gridW] += f01; } + if (tw.w > 0u) { g_AstcDecimNum[idx00 + gridW + 1u] += f11 * t; g_AstcDecimDen[idx00 + gridW + 1u] += f11; } + } + } + } + + if (!exactGrid) + { + [loop] for (uint k = 0u; k < gridCount; ++k) + { + g_AstcGrid0[k] = (g_AstcDecimDen[k] > 1e-6) ? saturate(g_AstcDecimNum[k] / g_AstcDecimDen[k]) : 0.0; + } + } +} + +// Projects a single channel (plane 1, CCS in 0..3) onto [c0, c1] and decimates onto g_AstcGrid1 (gridW x gridH). +void AstcComputePlane1WeightGrid( + uint baseX, uint baseY, + uint effMode, + uint plane1Channel, + float c0, float c1, + uint gridW, uint gridH) +{ + uint gridCount = gridW * gridH; + [loop] for (uint i = 0u; i < ASTC_MAX_GRID_U; ++i) + { + g_AstcGrid1[i] = 0.0; + g_AstcDecimNum[i] = 0.0; + g_AstcDecimDen[i] = 0.0; + } + + float delta = c1 - c0; + float invDelta = (abs(delta) > 1e-6) ? (1.0 / delta) : 0.0; + bool exactGrid = (gridW == BLOCK_X && gridH == BLOCK_Y); + bool weightByAlpha = (plane1Channel < 3u && effMode == ASTC_EFF_LDR_RGBA && _AstcUseAlphaWeight != 0u); + + [loop] for (uint y = 0u; y < BLOCK_Y; ++y) + { + [loop] for (uint x = 0u; x < BLOCK_X; ++x) + { + float imp; + float4 p = AstcFetchWorkingPixel(baseX, baseY, x, y, effMode, imp); + float pv = AstcGetChannel(p, plane1Channel); + float t = (abs(delta) > 1e-6) ? saturate((pv - c0) * invDelta) : 0.0; + + if (exactGrid) + { + g_AstcGrid1[y * gridW + x] = t; + } + else + { + uint js, jt; + uint4 tw; + AstcComputeInfillTap(x, y, BLOCK_X, BLOCK_Y, gridW, gridH, js, jt, tw); + uint idx00 = jt * gridW + js; + float decW = weightByAlpha ? imp : 1.0; + float f00 = (float)tw.x * decW; + float f10 = (float)tw.y * decW; + float f01 = (float)tw.z * decW; + float f11 = (float)tw.w * decW; + + g_AstcDecimNum[idx00] += f00 * t; g_AstcDecimDen[idx00] += f00; + if (tw.y > 0u) { g_AstcDecimNum[idx00 + 1u] += f10 * t; g_AstcDecimDen[idx00 + 1u] += f10; } + if (tw.z > 0u) { g_AstcDecimNum[idx00 + gridW] += f01 * t; g_AstcDecimDen[idx00 + gridW] += f01; } + if (tw.w > 0u) { g_AstcDecimNum[idx00 + gridW + 1u] += f11 * t; g_AstcDecimDen[idx00 + gridW + 1u] += f11; } + } + } + } + + if (!exactGrid) + { + [loop] for (uint k = 0u; k < gridCount; ++k) + { + g_AstcGrid1[k] = (g_AstcDecimDen[k] > 1e-6) ? saturate(g_AstcDecimNum[k] / g_AstcDecimDen[k]) : 0.0; + } + } +} + +#if !defined(ASTC_FAST_ONLY) + +// Projects 2-partition block pixels onto partition 0/1 endpoints and decimates onto g_AstcGrid0 (gridW x gridH). +void AstcComputeWeightGrid2P( + uint baseX, uint baseY, + uint effMode, + uint partSeed, + float4 e0_p0, float4 e1_p0, + float4 e0_p1, float4 e1_p1, + uint gridW, uint gridH) +{ + uint gridCount = gridW * gridH; + [loop] for (uint i = 0u; i < ASTC_MAX_GRID_U; ++i) + { + g_AstcGrid0[i] = 0.0; + g_AstcDecimNum[i] = 0.0; + g_AstcDecimDen[i] = 0.0; + } + + float4 mask = AstcChannelMaskEx(effMode, 4u); + float4 dir0 = (e1_p0 - e0_p0) * mask; + float4 dir1 = (e1_p1 - e0_p1) * mask; + + bool exactGrid = (gridW == BLOCK_X && gridH == BLOCK_Y); + bool smallBlock = (BLOCK_X * BLOCK_Y) < 32u; + AstcPart2Params p2 = AstcPreparePartition2(partSeed, smallBlock); + + [loop] for (uint y = 0u; y < BLOCK_Y; ++y) + { + [loop] for (uint x = 0u; x < BLOCK_X; ++x) + { + float imp; + float4 p = AstcFetchWorkingPixel(baseX, baseY, x, y, effMode, imp); + float4 chImp = AstcGetChannelImp(effMode, imp); + uint part = AstcEvalPartition2(p2, x, y); + float t; + if (part == 0u) + { + float4 wDir0 = dir0 * chImp; + float denom0 = dot(wDir0, dir0); + t = (denom0 > 1e-6) ? saturate(dot((p - e0_p0) * mask, wDir0) / denom0) : 0.0; + } + else + { + float4 wDir1 = dir1 * chImp; + float denom1 = dot(wDir1, dir1); + t = (denom1 > 1e-6) ? saturate(dot((p - e0_p1) * mask, wDir1) / denom1) : 0.0; + } + + if (exactGrid) + { + g_AstcGrid0[y * gridW + x] = t; + } + else + { + uint js, jt; + uint4 tw; + AstcComputeInfillTap(x, y, BLOCK_X, BLOCK_Y, gridW, gridH, js, jt, tw); + uint idx00 = jt * gridW + js; + float f00 = (float)tw.x; + float f10 = (float)tw.y; + float f01 = (float)tw.z; + float f11 = (float)tw.w; + + g_AstcDecimNum[idx00] += f00 * t; g_AstcDecimDen[idx00] += f00; + if (tw.y > 0u) { g_AstcDecimNum[idx00 + 1u] += f10 * t; g_AstcDecimDen[idx00 + 1u] += f10; } + if (tw.z > 0u) { g_AstcDecimNum[idx00 + gridW] += f01 * t; g_AstcDecimDen[idx00 + gridW] += f01; } + if (tw.w > 0u) { g_AstcDecimNum[idx00 + gridW + 1u] += f11 * t; g_AstcDecimDen[idx00 + gridW + 1u] += f11; } + } + } + } + + if (!exactGrid) + { + [loop] for (uint k = 0u; k < gridCount; ++k) + { + g_AstcGrid0[k] = (g_AstcDecimDen[k] > 1e-6) ? saturate(g_AstcDecimNum[k] / g_AstcDecimDen[k]) : 0.0; + } + } +} + +// Unified exact hardware-reconstructed candidate error evaluator for 1P (stage=0), Dual-Plane (stage=1), and 2P (stage=2). +float AstcEvalCandidateError( + uint baseX, uint baseY, + uint effMode, + uint stage, + uint ccs, + AstcPart2Params p2, + float4 e0_p0, float4 e1_p0, + float4 e0_p1, float4 e1_p1, + uint gridW, uint gridH, + uint wQuant, uint epQuant, + float bestError, + out float4 outChanErr) +{ + bool isDual = (stage == 1u); + bool isTwoP = (stage == 2u); + uint epPerPart = AstcGetEpCountForEffMode(effMode); + uint partCnt = isTwoP ? 2u : 1u; + + float4 uq0_p0 = 0.0, uq1_p0 = 0.0, uq0_p1 = 0.0, uq1_p1 = 0.0; + bool swap0 = false, swap1 = false; + [loop] for (uint pi = 0u; pi < partCnt; ++pi) + { + float4 te0 = (pi == 0u) ? e0_p0 : e0_p1; + float4 te1 = (pi == 0u) ? e1_p0 : e1_p1; + float4 uq0, uq1; + bool sw; + AstcQuantizeEndpoints(te0, te1, effMode, epQuant, pi * epPerPart, uq0, uq1, sw); + if (pi == 0u) { uq0_p0 = uq0; uq1_p0 = uq1; swap0 = sw; } + else { uq0_p1 = uq0; uq1_p1 = uq1; swap1 = sw; } + } + + uint gridCount = gridW * gridH; + [loop] for (uint i = 0u; i < ASTC_MAX_GRID_U; ++i) + { + g_AstcGridUq0[i] = 0u; + if (isDual) g_AstcGridUq1[i] = 0u; + } + [loop] for (uint k = 0u; k < gridCount; ++k) + { + uint uq0; + AstcQuantizeWeight(g_AstcGrid0[k], wQuant, uq0); + g_AstcGridUq0[k] = uq0; + if (isDual) + { + uint uq1; + AstcQuantizeWeight(g_AstcGrid1[k], wQuant, uq1); + g_AstcGridUq1[k] = uq1; + } + } + + float4 mask = AstcChannelMaskEx(effMode, 4u); + float totalErr = 0.0; + outChanErr = 0.0; + + [loop] for (uint y = 0u; y < BLOCK_Y; ++y) + { + [loop] for (uint x = 0u; x < BLOCK_X; ++x) + { + float imp; + float4 p = AstcFetchWorkingPixel(baseX, baseY, x, y, effMode, imp); + uint w0; + ASTC_EVAL_INFILL(g_AstcGridUq0, x, y, BLOCK_X, BLOCK_Y, gridW, gridH, w0); + + float4 recon; + if (isTwoP) + { + uint part = AstcEvalPartition2(p2, x, y); + uint effW0 = ((part == 0u) ? swap0 : swap1) ? (64u - w0) : w0; + recon = (part == 0u) + ? lerp(uq0_p0, uq1_p0, (float)effW0 * (1.0 / 64.0)) + : lerp(uq0_p1, uq1_p1, (float)effW0 * (1.0 / 64.0)); + } + else + { + uint effW0 = swap0 ? (64u - w0) : w0; + recon = lerp(uq0_p0, uq1_p0, (float)effW0 * (1.0 / 64.0)); + if (isDual) + { + uint w1; + ASTC_EVAL_INFILL(g_AstcGridUq1, x, y, BLOCK_X, BLOCK_Y, gridW, gridH, w1); + uint effW1 = swap0 ? (64u - w1) : w1; + float p1Val = lerp(AstcGetChannel(uq0_p0, ccs), AstcGetChannel(uq1_p0, ccs), (float)effW1 * (1.0 / 64.0)); + recon = AstcSetChannel(recon, ccs, p1Val); + } + } + + if (isDual && effMode == ASTC_EFF_LDR_NORMAL) + { + float2 nOrig = float2(p.w, p.x) * (2.0 / 255.0) - 1.0; + float zOrig = sqrt(saturate(1.0 - dot(nOrig, nOrig))); + float2 nRec = float2(recon.a, recon.r) * (2.0 / 255.0) - 1.0; + float zRec = sqrt(saturate(1.0 - dot(nRec, nRec))); + totalErr += max(0.0, 1.0 - (dot(nOrig, nRec) + zOrig * zRec)); + } + else + { + float4 diff = (p - recon) * mask; + float4 chImp = AstcGetChannelImp(effMode, imp); + float4 sq = diff * diff * chImp; + if (stage == 0u) outChanErr += sq; + totalErr += sq.r + sq.g + sq.b + sq.a; + } + } + if (totalErr >= bestError) + break; + } + return totalErr; +} + +// Fits both 2-partition subsets simultaneously in 3 shared passes (mean + covariance + projection) instead of 8 separate passes. +void AstcFitBothPartitions2P( + uint baseX, uint baseY, + uint effMode, + AstcPart2Params p2, + out float4 outE0_p0, out float4 outE1_p0, + out float4 outE0_p1, out float4 outE1_p1) +{ + float4 mask = AstcChannelMaskEx(effMode, 4u); + float4 sum0 = 0.0, sum1 = 0.0; + float4 wSum0 = 0.0, wSum1 = 0.0; + + // Pass 1: means for both partitions + [loop] for (uint y = 0u; y < BLOCK_Y; ++y) + { + [loop] for (uint x = 0u; x < BLOCK_X; ++x) + { + float imp; + float4 p = AstcFetchWorkingPixel(baseX, baseY, x, y, effMode, imp); + float4 chImp = AstcGetChannelImp(effMode, imp); + if (AstcEvalPartition2(p2, x, y) == 0u) + { + sum0 += p * chImp; + wSum0 += chImp; + } + else + { + sum1 += p * chImp; + wSum1 += chImp; + } + } + } + + float4 mean0 = sum0 / max(wSum0, 1e-6); + float4 mean1 = sum1 / max(wSum1, 1e-6); + + // Pass 2: covariance + principal axis via power iteration seed for both partitions + float4 cov0R = 0.0, cov0G = 0.0, cov0B = 0.0, cov0A = 0.0; + float4 cov1R = 0.0, cov1G = 0.0, cov1B = 0.0, cov1A = 0.0; + [loop] for (uint y2 = 0u; y2 < BLOCK_Y; ++y2) + { + [loop] for (uint x2 = 0u; x2 < BLOCK_X; ++x2) + { + float imp; + float4 p = AstcFetchWorkingPixel(baseX, baseY, x2, y2, effMode, imp); + float4 chImp = AstcGetChannelImp(effMode, imp); + if (AstcEvalPartition2(p2, x2, y2) == 0u) + { + float4 d = (p - mean0) * mask; + float4 dw = d * chImp; + cov0R += dw.r * d; cov0G += dw.g * d; cov0B += dw.b * d; cov0A += dw.a * d; + } + else + { + float4 d = (p - mean1) * mask; + float4 dw = d * chImp; + cov1R += dw.r * d; cov1G += dw.g * d; cov1B += dw.b * d; cov1A += dw.a * d; + } + } + } + + float4 axis0 = float4(cov0R.r, cov0G.g, cov0B.b, cov0A.a); + float4 axis1 = float4(cov1R.r, cov1G.g, cov1B.b, cov1A.a); + [loop] for (uint it = 0u; it < 3u; ++it) + { + float4 n0 = float4(dot(cov0R, axis0), dot(cov0G, axis0), dot(cov0B, axis0), dot(cov0A, axis0)) * mask; + float l0 = length(n0); + if (l0 > 1e-6) axis0 = n0 / l0; + + float4 n1 = float4(dot(cov1R, axis1), dot(cov1G, axis1), dot(cov1B, axis1), dot(cov1A, axis1)) * mask; + float l1 = length(n1); + if (l1 > 1e-6) axis1 = n1 / l1; + } + if (length(axis0) <= 1e-6) axis0 = mask; + if (length(axis1) <= 1e-6) axis1 = mask; + axis0 = normalize(axis0); + axis1 = normalize(axis1); + + // Pass 3: min/max projection along each partition's principal axis + float minT0 = 1e30, maxT0 = -1e30; + float minT1 = 1e30, maxT1 = -1e30; + [loop] for (uint y3 = 0u; y3 < BLOCK_Y; ++y3) + { + [loop] for (uint x3 = 0u; x3 < BLOCK_X; ++x3) + { + float imp; + float4 p = AstcFetchWorkingPixel(baseX, baseY, x3, y3, effMode, imp); + if (AstcEvalPartition2(p2, x3, y3) == 0u) + { + float t = dot((p - mean0) * mask, axis0); + minT0 = min(minT0, t); + maxT0 = max(maxT0, t); + } + else + { + float t = dot((p - mean1) * mask, axis1); + minT1 = min(minT1, t); + maxT1 = max(maxT1, t); + } + } + } + + if (minT0 > maxT0) { minT0 = 0.0; maxT0 = 0.0; } + if (minT1 > maxT1) { minT1 = 0.0; maxT1 = 0.0; } + + outE0_p0 = AstcClampWorkingColor(mean0 + axis0 * minT0, effMode); + outE1_p0 = AstcClampWorkingColor(mean0 + axis0 * maxT0, effMode); + outE0_p1 = AstcClampWorkingColor(mean1 + axis1 * minT1, effMode); + outE1_p1 = AstcClampWorkingColor(mean1 + axis1 * maxT1, effMode); + AstcCanonicalizeEndpoints(effMode, outE0_p0, outE1_p0); + AstcCanonicalizeEndpoints(effMode, outE0_p1, outE1_p1); +} + +// Unified post-quantization ideal endpoint refit for 1P single-plane and Dual-Plane blocks. +void AstcRefitEndpoints( + uint baseX, uint baseY, + uint effMode, + bool isDualPlane, + uint ccs, + uint gridW, uint gridH, + uint epQuant, + float4 curUqE0, float4 curUqE1) +{ + float4 mask = AstcChannelMaskEx(effMode, 4u); + float origErr = 0.0; + + float a00_p0 = 0.0, a01_p0 = 0.0, a11_p0 = 0.0; + float a00_p0a = 0.0, a01_p0a = 0.0, a11_p0a = 0.0; + float a00_p1 = 0.0, a01_p1 = 0.0, a11_p1 = 0.0; + float4 b0_p0 = 0.0, b1_p0 = 0.0; + float b0_p1 = 0.0, b1_p1 = 0.0; + + [loop] for (uint y = 0u; y < BLOCK_Y; ++y) + { + [loop] for (uint x = 0u; x < BLOCK_X; ++x) + { + float imp; + float4 p = AstcFetchWorkingPixel(baseX, baseY, x, y, effMode, imp); + float4 chImp = AstcGetChannelImp(effMode, imp); + uint w0_64; + ASTC_EVAL_INFILL(g_AstcGridUq0, x, y, BLOCK_X, BLOCK_Y, gridW, gridH, w0_64); + float w0 = (float)w0_64 * (1.0 / 64.0); + float omw0 = 1.0 - w0; + + float4 recon = lerp(curUqE0, curUqE1, w0); + float w1 = w0; + if (isDualPlane) + { + uint w1_64; + ASTC_EVAL_INFILL(g_AstcGridUq1, x, y, BLOCK_X, BLOCK_Y, gridW, gridH, w1_64); + w1 = (float)w1_64 * (1.0 / 64.0); + recon = AstcSetChannel(recon, ccs, lerp(AstcGetChannel(curUqE0, ccs), AstcGetChannel(curUqE1, ccs), w1)); + } + + if (isDualPlane && effMode == ASTC_EFF_LDR_NORMAL) + { + float2 nOrig = float2(p.w, p.x) * (2.0 / 255.0) - 1.0; + float zOrig = sqrt(saturate(1.0 - dot(nOrig, nOrig))); + float2 nRec = float2(recon.a, recon.r) * (2.0 / 255.0) - 1.0; + float zRec = sqrt(saturate(1.0 - dot(nRec, nRec))); + origErr += max(0.0, 1.0 - (dot(nOrig, nRec) + zOrig * zRec)); + } + else + { + float4 diff = (p - recon) * mask; + origErr += dot(diff * diff, chImp); + } + + float wRgb = chImp.x; + a00_p0 += wRgb * omw0 * omw0; + a01_p0 += wRgb * w0 * omw0; + a11_p0 += wRgb * w0 * w0; + + a00_p0a += omw0 * omw0; + a01_p0a += w0 * omw0; + a11_p0a += w0 * w0; + + b0_p0 += p * (chImp * omw0); + b1_p0 += p * (chImp * w0); + + if (isDualPlane) + { + float omw1 = 1.0 - w1; + float p1Imp = AstcGetChannel(chImp, ccs); + float p1Val = AstcGetChannel(p, ccs); + a00_p1 += p1Imp * omw1 * omw1; + a01_p1 += p1Imp * w1 * omw1; + a11_p1 += p1Imp * w1 * w1; + b0_p1 += p1Val * (p1Imp * omw1); + b1_p1 += p1Val * (p1Imp * w1); + } + } + } + + float4 refitE0 = curUqE0; + float4 refitE1 = curUqE1; + bool changed = false; + + float detP0 = a00_p0 * a11_p0 - a01_p0 * a01_p0; + if (detP0 > 1e-4) + { + float invDet = 1.0 / detP0; + refitE0.rgb = AstcClampWorkingColor(float4((a11_p0 * b0_p0.rgb - a01_p0 * b1_p0.rgb) * invDet, 0.0), effMode).rgb; + refitE1.rgb = AstcClampWorkingColor(float4((a00_p0 * b1_p0.rgb - a01_p0 * b0_p0.rgb) * invDet, 0.0), effMode).rgb; + changed = true; + } + + float detP0A = a00_p0a * a11_p0a - a01_p0a * a01_p0a; + if ((!isDualPlane || ccs != 3u) && mask.a > 0.0 && detP0A > 1e-4) + { + float invDetA = 1.0 / detP0A; + refitE0.a = AstcClampWorkingColor(float4(0.0, 0.0, 0.0, (a11_p0a * b0_p0.a - a01_p0a * b1_p0.a) * invDetA), effMode).a; + refitE1.a = AstcClampWorkingColor(float4(0.0, 0.0, 0.0, (a00_p0a * b1_p0.a - a01_p0a * b0_p0.a) * invDetA), effMode).a; + changed = true; + } + + float detP1 = a00_p1 * a11_p1 - a01_p1 * a01_p1; + if (isDualPlane && detP1 > 1e-4) + { + float invDet1 = 1.0 / detP1; + float maxVal = (effMode >= ASTC_EFF_HDR_RGB) ? 65535.0 : 255.0; + float n0 = clamp((a11_p1 * b0_p1 - a01_p1 * b1_p1) * invDet1, 0.0, maxVal); + float n1 = clamp((a00_p1 * b1_p1 - a01_p1 * b0_p1) * invDet1, 0.0, maxVal); + refitE0 = AstcSetChannel(refitE0, ccs, n0); + refitE1 = AstcSetChannel(refitE1, ccs, n1); + changed = true; + } + + if (!changed) return; + + [loop] for (uint sv = 0u; sv < 8u; ++sv) g_AstcCandEpCodes[sv] = g_AstcEpCodes[sv]; + float4 uq0, uq1; + bool dummySwapped; + AstcQuantizeEndpoints(refitE0, refitE1, effMode, epQuant, 0u, uq0, uq1, dummySwapped); + + float refitErr = 0.0; + [loop] for (uint y2 = 0u; y2 < BLOCK_Y; ++y2) + { + [loop] for (uint x2 = 0u; x2 < BLOCK_X; ++x2) + { + float imp; + float4 p = AstcFetchWorkingPixel(baseX, baseY, x2, y2, effMode, imp); + float4 chImp = AstcGetChannelImp(effMode, imp); + uint w0_64; + ASTC_EVAL_INFILL(g_AstcGridUq0, x2, y2, BLOCK_X, BLOCK_Y, gridW, gridH, w0_64); + float4 recon = lerp(uq0, uq1, (float)w0_64 * (1.0 / 64.0)); + if (isDualPlane) + { + uint w1_64; + ASTC_EVAL_INFILL(g_AstcGridUq1, x2, y2, BLOCK_X, BLOCK_Y, gridW, gridH, w1_64); + recon = AstcSetChannel(recon, ccs, lerp(AstcGetChannel(uq0, ccs), AstcGetChannel(uq1, ccs), (float)w1_64 * (1.0 / 64.0))); + } + + if (isDualPlane && effMode == ASTC_EFF_LDR_NORMAL) + { + float2 nOrig = float2(p.w, p.x) * (2.0 / 255.0) - 1.0; + float zOrig = sqrt(saturate(1.0 - dot(nOrig, nOrig))); + float2 nRec = float2(recon.a, recon.r) * (2.0 / 255.0) - 1.0; + float zRec = sqrt(saturate(1.0 - dot(nRec, nRec))); + refitErr += max(0.0, 1.0 - (dot(nOrig, nRec) + zOrig * zRec)); + } + else + { + float4 diff = (p - recon) * mask; + refitErr += dot(diff * diff, chImp); + } + } + } + + if (refitErr >= origErr) + { + [loop] for (uint ei = 0u; ei < 8u; ++ei) g_AstcEpCodes[ei] = g_AstcCandEpCodes[ei]; + } +} + +#endif // !ASTC_FAST_ONLY + +// Assembles the final winning AstcCandidate into a 128-bit physical ASTC block. +uint4 AstcAssembleBlock(uint baseX, uint baseY, uint effMode, AstcCandidate c) +{ + [loop] for (uint e = 0u; e < 16u; ++e) g_AstcEpCodes[e] = 0u; + [loop] for (uint wi = 0u; wi < 64u; ++wi) g_AstcBiseVals[wi] = 0u; + + uint epPerPart = AstcGetEpCountForEffMode(effMode); + uint cem = AstcGetCemForEffMode(effMode); + + uint gridCount = c.gridW * c.gridH; + uint totalWeights = gridCount; + + float4 uqE0 = 0.0, uqE1 = 0.0; + float4 uq0_p1 = 0.0, uq1_p1 = 0.0; +#if !defined(ASTC_FAST_ONLY) + uint partCnt = (c.isTwoPart != 0u) ? 2u : 1u; + [loop] for (uint pi = 0u; pi < partCnt; ++pi) + { + float4 te0 = (pi == 0u) ? c.e0 : c.e0_p1; + float4 te1 = (pi == 0u) ? c.e1 : c.e1_p1; + float4 tu0, tu1; + bool dummySwapped; + AstcQuantizeEndpoints(te0, te1, effMode, c.epQuant, pi * epPerPart, tu0, tu1, dummySwapped); + if (pi == 0u) { uqE0 = tu0; uqE1 = tu1; } + else { uq0_p1 = tu0; uq1_p1 = tu1; } + } +#else + bool dummySwapped; + AstcQuantizeEndpoints(c.e0, c.e1, effMode, c.epQuant, 0u, uqE0, uqE1, dummySwapped); +#endif + +#if !defined(ASTC_FAST_ONLY) + if (c.isTwoPart != 0u) + { + AstcComputeWeightGrid2P(baseX, baseY, effMode, c.partSeed, uqE0, uqE1, uq0_p1, uq1_p1, c.gridW, c.gridH); + [loop] for (uint k = 0u; k < gridCount; ++k) + { + uint dummyUq; + g_AstcBiseVals[k] = AstcQuantizeWeight(g_AstcGrid0[k], c.wQuant, dummyUq); + } + } + else +#endif + { + bool isDual = (c.isDualPlane != 0u); + uint exclCh = isDual ? c.dualPlaneChannel : 4u; + AstcComputeWeightGrid1P(baseX, baseY, effMode, exclCh, uqE0, uqE1, c.gridW, c.gridH); + if (isDual) + { + AstcComputePlane1WeightGrid(baseX, baseY, effMode, c.dualPlaneChannel, AstcGetChannel(uqE0, c.dualPlaneChannel), AstcGetChannel(uqE1, c.dualPlaneChannel), c.gridW, c.gridH); + } + +#if !defined(ASTC_FAST_ONLY) + [loop] for (uint zi = 0u; zi < ASTC_MAX_GRID_U; ++zi) + { + g_AstcGridUq0[zi] = 0u; + if (isDual) g_AstcGridUq1[zi] = 0u; + } +#endif + [loop] for (uint k = 0u; k < gridCount; ++k) + { + uint uq0; + uint code0 = AstcQuantizeWeight(g_AstcGrid0[k], c.wQuant, uq0); +#if !defined(ASTC_FAST_ONLY) + g_AstcGridUq0[k] = uq0; +#endif + if (isDual) + { + uint uq1; + g_AstcBiseVals[2u * k] = code0; + g_AstcBiseVals[2u * k + 1u] = AstcQuantizeWeight(g_AstcGrid1[k], c.wQuant, uq1); +#if !defined(ASTC_FAST_ONLY) + g_AstcGridUq1[k] = uq1; +#endif + } + else + { + g_AstcBiseVals[k] = code0; + } + } + if (isDual) totalWeights = gridCount * 2u; + +#if !defined(ASTC_FAST_ONLY) + if (_AstcQuality >= 1u) + { + AstcRefitEndpoints(baseX, baseY, effMode, isDual, c.dualPlaneChannel, c.gridW, c.gridH, c.epQuant, uqE0, uqE1); + } +#endif + } + + // Encode weights at bit 0 into wBuf, then reverse all 128 bits so weights sit at MSB descending. + uint4 wBuf = uint4(0u, 0u, 0u, 0u); + AstcEncodeBise(wBuf, 0u, c.wQuant, totalWeights); + uint4 block = AstcReverse128(wBuf); + + // Header: BlockMode (11 bits) + PartitionCount-1 (2 bits) + AstcWriteBits128(block, 0u, 11u, c.blockMode); + uint epStartBit = 17u; + uint epTotalCount = epPerPart; +#if !defined(ASTC_FAST_ONLY) + if (c.isTwoPart != 0u) + { + AstcWriteBits128(block, 11u, 2u, 1u); + AstcWriteBits128(block, 13u, 10u, c.partSeed); + // Matched CEM for both partitions: low 2 bits = 00, upper 4 bits = cem + AstcWriteBits128(block, 23u, 6u, cem << 2u); + epStartBit = 29u; + epTotalCount = epPerPart * 2u; + } + else +#endif + { + AstcWriteBits128(block, 11u, 2u, 0u); + AstcWriteBits128(block, 13u, 4u, cem); + if (c.isDualPlane != 0u) + { + uint weightBits = AstcGetBiseBitCount(totalWeights, c.wQuant); + AstcWriteBits128(block, 128u - weightBits - 2u, 2u, c.dualPlaneChannel); + } + } + [loop] for (uint ei = 0u; ei < epTotalCount; ++ei) g_AstcBiseVals[ei] = g_AstcEpCodes[ei]; + AstcEncodeBise(block, epStartBit, c.epQuant, epTotalCount); + + return block; +} + +#if !defined(ASTC_FAST_ONLY) + +void AstcTryCandidate( + uint baseX, uint baseY, uint effMode, + uint stage, uint ccs, uint partSeed, AstcPart2Params p2, + float4 e0_p0, float4 e1_p0, float4 e0_p1, float4 e1_p1, + uint bm, uint gw, uint gh, + uint wQ, uint epQ, + inout AstcCandidate best, + inout float4 bestChanErr) +{ + float4 chanErr; + float err = AstcEvalCandidateError(baseX, baseY, effMode, stage, ccs, p2, e0_p0, e1_p0, e0_p1, e1_p1, gw, gh, wQ, epQ, best.error, chanErr); + if (err < best.error) + { + best.blockMode = bm; + best.gridW = gw; + best.gridH = gh; + best.wQuant = wQ; + best.epQuant = epQ; + best.isDualPlane = (stage == 1u) ? 1u : 0u; + best.dualPlaneChannel = (stage == 1u) ? ccs : 3u; + best.isTwoPart = (stage == 2u) ? 1u : 0u; + best.partSeed = (stage == 2u) ? partSeed : 0u; + best.error = err; + best.e0 = e0_p0; + best.e1 = e1_p0; + if (stage == 2u) + { + best.e0_p1 = e0_p1; + best.e1_p1 = e1_p1; + } + if (stage == 0u) + { + bestChanErr = chanErr; + } + } +} + +// Curated 16 geometrically diverse ASTC 2-partition seeds (vertical, horizontal, diagonals, corners). +uint AstcGetCuratedSeed(uint idx) +{ + if (idx == 0u) return 16u; + if (idx == 1u) return 28u; + if (idx == 2u) return 31u; + if (idx == 3u) return 78u; + if (idx == 4u) return 17u; + if (idx == 5u) return 39u; + if (idx == 6u) return 116u; + if (idx == 7u) return 72u; + if (idx == 8u) return 107u; + if (idx == 9u) return 43u; + if (idx == 10u) return 110u; + if (idx == 11u) return 252u; + if (idx == 12u) return 61u; + if (idx == 13u) return 76u; + if (idx == 14u) return 210u; + return 137u; +} + +// Fast heuristic to select the best 2-partition seed by minimizing per-channel weighted intra-partition variance. +// Evaluates 16 curated seeds in 4 batches of 4 with hoisted AstcPreparePartition2 hash parameters. +uint AstcSelectBestSeed2P(uint baseX, uint baseY, uint effMode) +{ + float4 mask = AstcChannelMaskEx(effMode, 4u); + bool smallBlock = (BLOCK_X * BLOCK_Y) < 32u; + + uint bestSeed = 17u; + float bestScore = -1.0; + + [loop] for (uint batch = 0u; batch < 16u; batch += 4u) + { + uint seed0 = AstcGetCuratedSeed(batch + 0u); + uint seed1 = AstcGetCuratedSeed(batch + 1u); + uint seed2 = AstcGetCuratedSeed(batch + 2u); + uint seed3 = AstcGetCuratedSeed(batch + 3u); + + AstcPart2Params p0 = AstcPreparePartition2(seed0, smallBlock); + AstcPart2Params p1 = AstcPreparePartition2(seed1, smallBlock); + AstcPart2Params p2 = AstcPreparePartition2(seed2, smallBlock); + AstcPart2Params p3 = AstcPreparePartition2(seed3, smallBlock); + + float4 sumAll = 0.0; + float4 cntAll = 0.0; + + float4 s1_0 = 0.0, s1_1 = 0.0, s1_2 = 0.0, s1_3 = 0.0; + float4 c1_0 = 0.0, c1_1 = 0.0, c1_2 = 0.0, c1_3 = 0.0; + + [loop] for (uint y = 0u; y < BLOCK_Y; ++y) + { + [loop] for (uint x = 0u; x < BLOCK_X; ++x) + { + float imp; + float4 p = AstcFetchWorkingPixel(baseX, baseY, x, y, effMode, imp); + float4 chImp = AstcGetChannelImp(effMode, imp) * mask; + float4 pw = p * chImp; + sumAll += pw; + cntAll += chImp; + + if (AstcEvalPartition2(p0, x, y) != 0u) { s1_0 += pw; c1_0 += chImp; } + if (AstcEvalPartition2(p1, x, y) != 0u) { s1_1 += pw; c1_1 += chImp; } + if (AstcEvalPartition2(p2, x, y) != 0u) { s1_2 += pw; c1_2 += chImp; } + if (AstcEvalPartition2(p3, x, y) != 0u) { s1_3 += pw; c1_3 += chImp; } + } + } + + // Maximizing sum_c (s0_c^2 / c0_c + s1_c^2 / c1_c) minimizes per-channel weighted within-cluster variance. + float4 c0_0 = cntAll - c1_0; + if (dot(c0_0, mask) >= 0.5 && dot(c1_0, mask) >= 0.5) + { + float4 s0_0 = sumAll - s1_0; + float score = dot((s0_0 * s0_0) / max(c0_0, 1e-6) + (s1_0 * s1_0) / max(c1_0, 1e-6), mask); + if (score > bestScore) { bestScore = score; bestSeed = seed0; } + } + + float4 c0_1 = cntAll - c1_1; + if (dot(c0_1, mask) >= 0.5 && dot(c1_1, mask) >= 0.5) + { + float4 s0_1 = sumAll - s1_1; + float score = dot((s0_1 * s0_1) / max(c0_1, 1e-6) + (s1_1 * s1_1) / max(c1_1, 1e-6), mask); + if (score > bestScore) { bestScore = score; bestSeed = seed1; } + } + + float4 c0_2 = cntAll - c1_2; + if (dot(c0_2, mask) >= 0.5 && dot(c1_2, mask) >= 0.5) + { + float4 s0_2 = sumAll - s1_2; + float score = dot((s0_2 * s0_2) / max(c0_2, 1e-6) + (s1_2 * s1_2) / max(c1_2, 1e-6), mask); + if (score > bestScore) { bestScore = score; bestSeed = seed2; } + } + + float4 c0_3 = cntAll - c1_3; + if (dot(c0_3, mask) >= 0.5 && dot(c1_3, mask) >= 0.5) + { + float4 s0_3 = sumAll - s1_3; + float score = dot((s0_3 * s0_3) / max(c0_3, 1e-6) + (s1_3 * s1_3) / max(c1_3, 1e-6), mask); + if (score > bestScore) { bestScore = score; bestSeed = seed3; } + } + } + + return bestSeed; +} + +#endif // !ASTC_FAST_ONLY + +// Main per-block ASTC encoder entrypoint. +uint4 AstcEncodeBlock(uint blockXIdx, uint blockYIdx) +{ + uint baseX = blockXIdx * BLOCK_X; + uint baseY = blockYIdx * BLOCK_Y; + + bool isHdr = (_AstcMode == ASTC_MODE_HDR_RGB || _AstcMode == ASTC_MODE_HDR_RGBA); + + // ------------------------------------------------------------------------ + // Step 1: Scan raw block stats (Void-Extent check + HDR alpha mode resolution) + // ------------------------------------------------------------------------ + float4 rawMin = float4(1e30, 1e30, 1e30, 1e30); + float4 rawMax = float4(-1e30, -1e30, -1e30, -1e30); + float4 rawFirst = 0.0; + + [loop] for (uint y = 0u; y < BLOCK_Y; ++y) + { + [loop] for (uint x = 0u; x < BLOCK_X; ++x) + { + uint px = min(baseX + x, _AstcSrcWidth - 1u); + uint py = min(baseY + y, _AstcSrcHeight - 1u); + float4 r = _AstcSourceTex.Load(int3(px, py, _AstcMipLevel)); + if (isHdr) + { + // Sanitize NaN / Inf / negative values consistently with AstcFloatToLns4 & AstcFloatToHalfU16 + // so a single NaN at (0,0) or +Inf cannot corrupt Void-Extent detection. + r = float4( + (r.r > 0.0) ? min(r.r, 65504.0) : 0.0, + (r.g > 0.0) ? min(r.g, 65504.0) : 0.0, + (r.b > 0.0) ? min(r.b, 65504.0) : 0.0, + (r.a > 0.0) ? min(r.a, 65504.0) : 0.0); + } + if (x == 0u && y == 0u) rawFirst = r; + rawMin = min(rawMin, r); + rawMax = max(rawMax, r); + } + } + + // Resolve effective CEM mode per block + uint effMode = ASTC_EFF_LDR_RGB; + if (_AstcMode == ASTC_MODE_LDR_NORMAL) + { + effMode = ASTC_EFF_LDR_NORMAL; + } + else if (_AstcMode == ASTC_MODE_LDR_RGB) + { + effMode = ASTC_EFF_LDR_RGB; + } + else if (_AstcMode == ASTC_MODE_LDR_RGBA) + { + // Auto-promote opaque blocks to RGB CEM (6 endpoints -> higher precision!) + effMode = (rawMin.a >= (254.5 / 255.0)) ? ASTC_EFF_LDR_RGB : ASTC_EFF_LDR_RGBA; + } + else if (_AstcMode == ASTC_MODE_HDR_RGB) + { + effMode = ASTC_EFF_HDR_RGB; + } + else // ASTC_MODE_HDR_RGBA + { + if (rawMin.a >= 0.999 && rawMax.a <= 1.001) + effMode = ASTC_EFF_HDR_RGB; + else if (rawMin.a >= -1e-4 && rawMax.a <= 1.0001) + effMode = ASTC_EFF_HDR_RGB_LDR_ALPHA; + else + effMode = ASTC_EFF_HDR_RGBA; + } + + // ------------------------------------------------------------------------ + // Step 2: Void-Extent constant color fast path (lossless!) + // ------------------------------------------------------------------------ + if (!isHdr) + { + // AstcLinearToSRGB is monotonic on [0, 1], so converting min/max preserves the exact + // range in sRGB code space and prevents dark sRGB gradients from being treated as flat. + float4 cmpMin = saturate(rawMin); + float4 cmpMax = saturate(rawMax); + if (_AstcIsSRGB != 0u) + { + cmpMin.rgb = AstcLinearToSRGB(rawMin.rgb); + cmpMax.rgb = AstcLinearToSRGB(rawMax.rgb); + } + + bool isConst; + if (effMode == ASTC_EFF_LDR_NORMAL) + isConst = (cmpMax.r - cmpMin.r < (0.5 / 255.0)) && (cmpMax.g - cmpMin.g < (0.5 / 255.0)); + else if (effMode == ASTC_EFF_LDR_RGB) + isConst = all(cmpMax.rgb - cmpMin.rgb < (0.5 / 255.0)); + else + isConst = all(cmpMax - cmpMin < (0.5 / 255.0)); + + if (isConst) + { + float4 c = rawFirst; + float3 rgb = (_AstcIsSRGB != 0u) ? AstcLinearToSRGB(c.rgb) : saturate(c.rgb); + uint4 c8; + if (effMode == ASTC_EFF_LDR_NORMAL) + { + uint g8 = (uint)clamp(floor(rgb.g * 255.0 + 0.5), 0.0, 255.0); + uint r8 = (uint)clamp(floor(rgb.r * 255.0 + 0.5), 0.0, 255.0); + c8 = uint4(g8, g8, g8, r8); + } + else + { + uint a8 = (effMode == ASTC_EFF_LDR_RGB) ? 255u : (uint)clamp(floor(saturate(c.a) * 255.0 + 0.5), 0.0, 255.0); + c8 = uint4( + (uint)clamp(floor(rgb.r * 255.0 + 0.5), 0.0, 255.0), + (uint)clamp(floor(rgb.g * 255.0 + 0.5), 0.0, 255.0), + (uint)clamp(floor(rgb.b * 255.0 + 0.5), 0.0, 255.0), + a8); + } + return AstcEncodeVoidExtentLDR(c8 * 257u); + } + } + else + { + bool isConstRgb = all(rawMax.rgb - rawMin.rgb <= max(abs(rawMax.rgb) * 1e-4, 1e-5)); + bool isConstA = (effMode == ASTC_EFF_HDR_RGB) || ((rawMax.a - rawMin.a) <= max(abs(rawMax.a) * 1e-4, 1e-5)); + if (isConstRgb && isConstA) + { + uint4 f16 = uint4( + AstcFloatToHalfU16(rawFirst.r), + AstcFloatToHalfU16(rawFirst.g), + AstcFloatToHalfU16(rawFirst.b), + (effMode == ASTC_EFF_HDR_RGB) ? 0x3C00u : AstcFloatToHalfU16(rawFirst.a)); + return AstcEncodeVoidExtentHDR(f16); + } + } + +#if ASTC_ENABLE_PIXEL_CACHE + [loop] for (uint cy = 0u; cy < BLOCK_Y; ++cy) + { + [loop] for (uint cx = 0u; cx < BLOCK_X; ++cx) + { + float dummyImp; + float4 wp = AstcLoadWorkingPixel(baseX, baseY, cx, cy, effMode, dummyImp); + g_AstcPackedBlock[cy * BLOCK_X + cx] = AstcPackRgba16(wp); + } + } +#endif + + // ------------------------------------------------------------------------ + // Step 3: Normal Map Dedicated Dual-Plane Path (GGGR -> CEM 4 LA + CCS=3) + // ------------------------------------------------------------------------ + AstcCandidate best; + best.blockMode = 0x251u; + best.gridW = 4u; + best.gridH = 4u; + best.wQuant = ASTC_QUANT_12; + best.epQuant = ASTC_QUANT_256; + best.isDualPlane = 0u; + best.dualPlaneChannel = 3u; + best.isTwoPart = 0u; + best.partSeed = 0u; + best.error = 1e30; + best.e0 = 0.0; + best.e1 = 0.0; + best.e0_p1 = 0.0; + best.e1_p1 = 0.0; + + bool isNormal = (effMode == ASTC_EFF_LDR_NORMAL); + bool hasAlpha = (effMode == ASTC_EFF_LDR_RGBA || effMode == ASTC_EFF_HDR_RGB_LDR_ALPHA || effMode == ASTC_EFF_HDR_RGBA); + +#if defined(ASTC_FAST_ONLY) + uint refineIters = 0u; +#else + uint refineIters = (!isNormal && _AstcQuality >= 1u) ? 2u : 0u; +#endif + float4 e0, e1; + AstcFitSubsetEndpoints(baseX, baseY, effMode, isNormal ? 3u : 4u, 0u, 2u, refineIters, e0, e1); + +#if defined(ASTC_FAST_ONLY) + best.e0 = e0; + best.e1 = e1; + if (isNormal) + { + best.blockMode = 0x452u; best.gridW = 4u; best.gridH = 4u; best.wQuant = ASTC_QUANT_5; best.epQuant = ASTC_QUANT_256; + best.isDualPlane = 1u; best.dualPlaneChannel = 3u; + } + else if (!hasAlpha) + { +#if BLOCK_X == 4 + best.blockMode = 0x251u; best.gridW = 4u; best.gridH = 4u; best.wQuant = ASTC_QUANT_12; best.epQuant = ASTC_QUANT_256; +#else + best.blockMode = 0x0E3u; best.gridW = 5u; best.gridH = 5u; best.wQuant = ASTC_QUANT_6; best.epQuant = ASTC_QUANT_192; +#endif + } + else + { +#if BLOCK_X == 4 + best.blockMode = 0x053u; best.gridW = 4u; best.gridH = 4u; best.wQuant = ASTC_QUANT_8; best.epQuant = ASTC_QUANT_192; +#else + best.blockMode = 0x0E2u; best.gridW = 5u; best.gridH = 5u; best.wQuant = ASTC_QUANT_4; best.epQuant = ASTC_QUANT_192; +#endif + } +#else + if (_AstcQuality == 0u) + { + best.e0 = e0; + best.e1 = e1; + if (isNormal) + { + best.blockMode = 0x452u; best.gridW = 4u; best.gridH = 4u; best.wQuant = ASTC_QUANT_5; best.epQuant = ASTC_QUANT_256; + best.isDualPlane = 1u; best.dualPlaneChannel = 3u; + } + else if (!hasAlpha) + { +#if BLOCK_X == 4 + best.blockMode = 0x251u; best.gridW = 4u; best.gridH = 4u; best.wQuant = ASTC_QUANT_12; best.epQuant = ASTC_QUANT_256; +#else + best.blockMode = 0x0E3u; best.gridW = 5u; best.gridH = 5u; best.wQuant = ASTC_QUANT_6; best.epQuant = ASTC_QUANT_192; +#endif + } + else + { +#if BLOCK_X == 4 + best.blockMode = 0x053u; best.gridW = 4u; best.gridH = 4u; best.wQuant = ASTC_QUANT_8; best.epQuant = ASTC_QUANT_192; +#else + best.blockMode = 0x0E2u; best.gridW = 5u; best.gridH = 5u; best.wQuant = ASTC_QUANT_4; best.epQuant = ASTC_QUANT_192; +#endif + } + } + else + { + float4 bestChanErr = 0.0; + AstcPart2Params p2Params; + p2Params.seed1 = 0u; p2Params.seed2 = 0u; p2Params.seed3 = 0u; p2Params.seed4 = 0u; + p2Params.offA = 0u; p2Params.offB = 0u; + + // Unified 3-stage candidate search: stage 0 = 1P, stage 1 = Dual-Plane, stage 2 = 2P (High quality). + // Consolidates AstcTryCandidate / AstcEvalCandidateError / AstcComputeWeightGrid1P to a single inlined site. + [loop] for (uint stage = 0u; stage < 3u; ++stage) + { + if (stage == 0u && isNormal) continue; + if (stage == 2u && (isNormal || _AstcQuality < 2u)) continue; + + uint stageCcs = 4u; + uint stageSeed = 0u; + float4 sE0_p0 = e0, sE1_p0 = e1; + float4 sE0_p1 = 0.0, sE1_p1 = 0.0; + uint candCount = 0u; + + if (stage == 0u) + { + if (!hasAlpha) + { +#if BLOCK_X >= 8 + candCount = 12u; +#elif BLOCK_X >= 6 + candCount = 10u; +#elif BLOCK_X >= 5 + candCount = 6u; +#else + candCount = 3u; +#endif + } + else + { +#if BLOCK_X >= 6 + candCount = 8u; +#elif BLOCK_X >= 5 + candCount = 5u; +#else + candCount = 3u; +#endif + } + } + else if (stage == 1u) + { + stageCcs = 3u; + if (!isNormal) + { + stageCcs = 0u; + float maxChErr = bestChanErr.r; + if (bestChanErr.g > maxChErr) { maxChErr = bestChanErr.g; stageCcs = 1u; } + if (bestChanErr.b > maxChErr) { maxChErr = bestChanErr.b; stageCcs = 2u; } + if (hasAlpha && bestChanErr.a > maxChErr) { stageCcs = 3u; } + AstcFitSubsetEndpoints(baseX, baseY, effMode, stageCcs, 0u, 2u, 1u, sE0_p0, sE1_p0); + } +#if BLOCK_X >= 5 + candCount = isNormal ? 4u : 3u; +#else + candCount = 2u; +#endif + } + else + { + bool smallBlock = (BLOCK_X * BLOCK_Y) < 32u; + stageSeed = AstcSelectBestSeed2P(baseX, baseY, effMode); + p2Params = AstcPreparePartition2(stageSeed, smallBlock); + AstcFitBothPartitions2P(baseX, baseY, effMode, p2Params, sE0_p0, sE1_p0, sE0_p1, sE1_p1); +#if BLOCK_X >= 5 + candCount = 4u; +#else + candCount = 2u; +#endif + } + + uint cachedGW = 0u, cachedGH = 0u; + [loop] for (uint ci = 0u; ci < candCount; ++ci) + { + uint bm, gw, gh, wQ, epQ; + if (stage == 0u) + { + if (!hasAlpha) + { + if (ci == 0u) { bm = 0x251u; gw = 4u; gh = 4u; wQ = ASTC_QUANT_12; epQ = ASTC_QUANT_256; } + else if (ci == 1u) { bm = 0x242u; gw = 4u; gh = 4u; wQ = ASTC_QUANT_16; epQ = ASTC_QUANT_192; } + else if (ci == 2u) { bm = 0x252u; gw = 4u; gh = 4u; wQ = ASTC_QUANT_20; epQ = ASTC_QUANT_96; } + else if (ci == 3u) { bm = 0x0F2u; gw = 5u; gh = 5u; wQ = ASTC_QUANT_5; epQ = ASTC_QUANT_256; } + else if (ci == 4u) { bm = 0x0E3u; gw = 5u; gh = 5u; wQ = ASTC_QUANT_6; epQ = ASTC_QUANT_192; } + else if (ci == 5u) { bm = 0x0F3u; gw = 5u; gh = 5u; wQ = ASTC_QUANT_8; epQ = ASTC_QUANT_64; } + else if (ci == 6u) { bm = 0x114u; gw = 6u; gh = 6u; wQ = ASTC_QUANT_3; epQ = ASTC_QUANT_256; } + else if (ci == 7u) { bm = 0x108u; gw = 6u; gh = 6u; wQ = ASTC_QUANT_4; epQ = ASTC_QUANT_80; } + else if (ci == 8u) { bm = 0x143u; gw = 6u; gh = 4u; wQ = ASTC_QUANT_6; epQ = ASTC_QUANT_256; } + else if (ci == 9u) { bm = 0x04Fu; gw = 4u; gh = 6u; wQ = ASTC_QUANT_6; epQ = ASTC_QUANT_256; } + else if (ci == 10u){ bm = 0x046u; gw = 8u; gh = 4u; wQ = ASTC_QUANT_4; epQ = ASTC_QUANT_192; } + else { bm = 0x04Au; gw = 4u; gh = 8u; wQ = ASTC_QUANT_4; epQ = ASTC_QUANT_192; } + } + else + { + if (ci == 0u) { bm = 0x043u; gw = 4u; gh = 4u; wQ = ASTC_QUANT_6; epQ = ASTC_QUANT_256; } + else if (ci == 1u) { bm = 0x053u; gw = 4u; gh = 4u; wQ = ASTC_QUANT_8; epQ = ASTC_QUANT_192; } + else if (ci == 2u) { bm = 0x251u; gw = 4u; gh = 4u; wQ = ASTC_QUANT_12; epQ = ASTC_QUANT_96; } + else if (ci == 3u) { bm = 0x0E2u; gw = 5u; gh = 5u; wQ = ASTC_QUANT_4; epQ = ASTC_QUANT_192; } + else if (ci == 4u) { bm = 0x0F2u; gw = 5u; gh = 5u; wQ = ASTC_QUANT_5; epQ = ASTC_QUANT_80; } + else if (ci == 5u) { bm = 0x114u; gw = 6u; gh = 6u; wQ = ASTC_QUANT_3; epQ = ASTC_QUANT_96; } + else if (ci == 6u) { bm = 0x142u; gw = 6u; gh = 4u; wQ = ASTC_QUANT_4; epQ = ASTC_QUANT_192; } + else { bm = 0x04Eu; gw = 4u; gh = 6u; wQ = ASTC_QUANT_4; epQ = ASTC_QUANT_192; } + } + } + else if (stage == 1u) + { + uint4 cfg; + if (isNormal) + { + cfg = (ci == 0u) ? uint4(0x452u, 4u, ASTC_QUANT_5, ASTC_QUANT_256) + : (ci == 1u) ? uint4(0x442u, 4u, ASTC_QUANT_4, ASTC_QUANT_256) + : (ci == 2u) ? uint4(0x4F1u, 5u, ASTC_QUANT_3, ASTC_QUANT_128) + : uint4(0x4E1u, 5u, ASTC_QUANT_2, ASTC_QUANT_256); + } + else if (!hasAlpha) + { + cfg = (ci == 0u) ? uint4(0x451u, 4u, ASTC_QUANT_3, ASTC_QUANT_256) + : (ci == 1u) ? uint4(0x442u, 4u, ASTC_QUANT_4, ASTC_QUANT_160) + : uint4(0x4E1u, 5u, ASTC_QUANT_2, ASTC_QUANT_256); + } + else + { + cfg = (ci == 0u) ? uint4(0x451u, 4u, ASTC_QUANT_3, ASTC_QUANT_128) + : (ci == 1u) ? uint4(0x442u, 4u, ASTC_QUANT_4, ASTC_QUANT_48) + : uint4(0x4E1u, 5u, ASTC_QUANT_2, ASTC_QUANT_160); + } + bm = cfg.x; gw = cfg.y; gh = cfg.y; wQ = cfg.z; epQ = cfg.w; + } + else + { + uint4 cfg; + if (!hasAlpha) + { + if (ci == 0u) cfg = uint4(0x042u, 4u, ASTC_QUANT_4, ASTC_QUANT_40); + else if (ci == 1u) cfg = uint4(0x043u, 4u, ASTC_QUANT_6, ASTC_QUANT_24); + else if (ci == 2u) cfg = uint4(0x0F1u, 5u, ASTC_QUANT_3, ASTC_QUANT_24); + else cfg = uint4(0x0E2u, 5u, ASTC_QUANT_4, ASTC_QUANT_16); + } + else + { + if (ci == 0u) cfg = uint4(0x051u, 4u, ASTC_QUANT_3, ASTC_QUANT_20); + else if (ci == 1u) cfg = uint4(0x042u, 4u, ASTC_QUANT_4, ASTC_QUANT_16); + else if (ci == 2u) cfg = uint4(0x0E1u, 5u, ASTC_QUANT_2, ASTC_QUANT_24); + else cfg = uint4(0x0F1u, 5u, ASTC_QUANT_3, ASTC_QUANT_12); + } + bm = cfg.x; gw = cfg.y; gh = cfg.y; wQ = cfg.z; epQ = cfg.w; + } + + if (gw != cachedGW || gh != cachedGH) + { + if (stage == 2u) + { + AstcComputeWeightGrid2P(baseX, baseY, effMode, stageSeed, sE0_p0, sE1_p0, sE0_p1, sE1_p1, gw, gh); + } + else + { + AstcComputeWeightGrid1P(baseX, baseY, effMode, stageCcs, sE0_p0, sE1_p0, gw, gh); + if (stage == 1u) + { + AstcComputePlane1WeightGrid(baseX, baseY, effMode, stageCcs, AstcGetChannel(sE0_p0, stageCcs), AstcGetChannel(sE1_p0, stageCcs), gw, gh); + } + } + cachedGW = gw; + cachedGH = gh; + } + + AstcTryCandidate(baseX, baseY, effMode, stage, stageCcs, stageSeed, p2Params, sE0_p0, sE1_p0, sE0_p1, sE1_p1, bm, gw, gh, wQ, epQ, best, bestChanErr); + } + } + } +#endif // !ASTC_FAST_ONLY + + return AstcAssembleBlock(baseX, baseY, effMode, best); +} + +#endif // ASTC_GPU_CORE_HLSL diff --git a/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuCore.hlsl.meta b/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuCore.hlsl.meta new file mode 100644 index 0000000..89b45e2 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Gpu/Shaders/AstcGpuCore.hlsl.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 922536e721e01908a97602170f070d5a +ShaderIncludeImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/ImageExtensions.cs b/Assets/ASTC Encoder/Runtime/ImageExtensions.cs index 2cc530f..9788f97 100644 --- a/Assets/ASTC Encoder/Runtime/ImageExtensions.cs +++ b/Assets/ASTC Encoder/Runtime/ImageExtensions.cs @@ -1,10 +1,12 @@ -using System; +using System; using System.Runtime.InteropServices; using Unity.Collections; +using Unity.Collections.LowLevel.Unsafe; +using Aperture.Astcenc.Runtime.NativeAPI; namespace Aperture.Astcenc.Runtime { - public static class ImageExtensions + internal static class ImageExtensions { private static astcenc_type GetDataType(int bitness) { @@ -22,52 +24,221 @@ private static astcenc_type GetDataType(int bitness) } } - internal static void LoadFrom(this ref astcenc_image image, NativeSlice rawData, int width, int height, int bitness) where T : struct, IRawData + /// + /// Zero-copy binding for 4-channel RGBA formats whose native memory layout already matches astcenc_image. + /// Caller must ensure rawData remains valid until compression completes and pass ownsSliceMemory: false to Release(). + /// + internal static unsafe void LoadFromDirect(this ref astcenc_image image, NativeSlice rawData, int width, int height, int bitness) where T : unmanaged + { + image.LoadFromDirectPtr(rawData.GetUnsafeReadOnlyPtr(), width, height, bitness); + } + + /// + /// Zero-copy binding from an existing unmanaged pointer whose memory layout already matches 4-channel astcenc_image. + /// Caller must ensure slicePtr remains valid until compression completes and pass ownsSliceMemory: false to Release(). + /// + internal static unsafe void LoadFromDirectPtr(this ref astcenc_image image, void* slicePtr, int width, int height, int bitness) + { + if (image.data != IntPtr.Zero) + { + throw new InvalidOperationException("astcenc_image already holds allocated data; call Release() before rebinding."); + } + + IntPtr dataPtr = Marshal.AllocHGlobal(IntPtr.Size); + try + { + Marshal.WriteIntPtr(dataPtr, 0, (IntPtr)slicePtr); + } + catch + { + Marshal.FreeHGlobal(dataPtr); + throw; + } + + image.dim_x = (uint)width; + image.dim_y = (uint)height; + image.dim_z = 1; + image.data_type = GetDataType(bitness); + image.data = dataPtr; + } + + /// + /// Expands a contiguous unmanaged source buffer of packed pixels into an owned 4-channel astcenc_image. + /// + internal static unsafe void LoadFromPtr(this ref astcenc_image image, T* srcPtr, int width, int height, int bitness) where T : unmanaged, IRawData { if (image.data != IntPtr.Zero) { image.Release(); } + + int pixelCount = width * height; + int stride = (bitness / 8) * 4; + long byteCount = (long)pixelCount * stride; + IntPtr slicePtr = Marshal.AllocHGlobal((IntPtr)byteCount); + IntPtr dataPtr = IntPtr.Zero; + try + { + byte* dst = (byte*)slicePtr; + for (int i = 0; i < pixelCount; i++) + { + srcPtr[i].WriteTo(dst); + dst += stride; + } + + dataPtr = Marshal.AllocHGlobal(IntPtr.Size); + Marshal.WriteIntPtr(dataPtr, 0, slicePtr); + } + catch + { + if (dataPtr != IntPtr.Zero) + { + Marshal.FreeHGlobal(dataPtr); + } + Marshal.FreeHGlobal(slicePtr); + throw; + } + image.dim_x = (uint)width; image.dim_y = (uint)height; image.dim_z = 1; image.data_type = GetDataType(bitness); - image.data = Marshal.AllocHGlobal(IntPtr.Size); + image.data = dataPtr; + } + + internal static void LoadFrom(this ref astcenc_image image, NativeSlice rawData, int width, int height, int bitness) where T : unmanaged, IRawData + { + if (image.data != IntPtr.Zero) + { + image.Release(); + } IntPtr slicePtr = LoadData(rawData, bitness); - Marshal.WriteIntPtr(image.data, 0, slicePtr); + IntPtr dataPtr = IntPtr.Zero; + try + { + dataPtr = Marshal.AllocHGlobal(IntPtr.Size); + Marshal.WriteIntPtr(dataPtr, 0, slicePtr); + } + catch + { + if (dataPtr != IntPtr.Zero) + { + Marshal.FreeHGlobal(dataPtr); + } + Marshal.FreeHGlobal(slicePtr); + throw; + } + + image.dim_x = (uint)width; + image.dim_y = (uint)height; + image.dim_z = 1; + image.data_type = GetDataType(bitness); + image.data = dataPtr; } - internal static void Release(this ref astcenc_image image) + /// + /// Allocates an owned 4-channel output image buffer for astcenc_decompress_image. + /// + internal static void AllocateOutput(this ref astcenc_image image, int width, int height, int bitness, out IntPtr slicePtr, out int byteCount) { if (image.data != IntPtr.Zero) { - for (int i = 0; i < image.dim_z; i++) + image.Release(); + } + + int stride = (bitness / 8) * 4; + long totalBytes = (long)width * height * stride; + if (totalBytes <= 0 || totalBytes > int.MaxValue) + { + throw new OverflowException($"Decompressed image buffer size out of range: {width}x{height} ({bitness}-bit)."); + } + + byteCount = (int)totalBytes; + slicePtr = Marshal.AllocHGlobal((IntPtr)totalBytes); + IntPtr dataPtr = IntPtr.Zero; + try + { + dataPtr = Marshal.AllocHGlobal(IntPtr.Size); + Marshal.WriteIntPtr(dataPtr, 0, slicePtr); + } + catch + { + if (dataPtr != IntPtr.Zero) { - IntPtr slicePtr = Marshal.ReadIntPtr(image.data, i * IntPtr.Size); - Marshal.FreeHGlobal(slicePtr); + Marshal.FreeHGlobal(dataPtr); + } + Marshal.FreeHGlobal(slicePtr); + slicePtr = IntPtr.Zero; + byteCount = 0; + throw; + } + + image.dim_x = (uint)width; + image.dim_y = (uint)height; + image.dim_z = 1; + image.data_type = GetDataType(bitness); + image.data = dataPtr; + } + internal static void Release(this ref astcenc_image image, bool ownsSliceMemory = true) + { + if (image.data != IntPtr.Zero) + { + if (ownsSliceMemory) + { + for (int i = 0; i < image.dim_z; i++) + { + IntPtr slicePtr = Marshal.ReadIntPtr(image.data, i * IntPtr.Size); + if (slicePtr != IntPtr.Zero) + { + Marshal.FreeHGlobal(slicePtr); + } + } } Marshal.FreeHGlobal(image.data); } image.data = IntPtr.Zero; } - private static IntPtr LoadData(NativeSlice raw, int bitness) where T : struct, IRawData + private static IntPtr LoadData(NativeSlice raw, int bitness) where T : unmanaged, IRawData { - int bytes = bitness / 8; - IntPtr dataPtr = Marshal.AllocHGlobal(raw.Length * bytes * 4); - Copy(raw, dataPtr, bytes * 4); - - return dataPtr; + int stride = (bitness / 8) * 4; + long byteCount = (long)raw.Length * stride; + IntPtr dataPtr = Marshal.AllocHGlobal((IntPtr)byteCount); + try + { + Copy(raw, dataPtr, stride); + return dataPtr; + } + catch + { + Marshal.FreeHGlobal(dataPtr); + throw; + } } - private static void Copy(NativeSlice raw, IntPtr destPtr, int stride) where T : struct, IRawData + private static unsafe void Copy(NativeSlice raw, IntPtr destPtr, int stride) where T : unmanaged, IRawData { - for (int i = 0; i < raw.Length; i++) + int length = raw.Length; + byte* dst = (byte*)destPtr; + if (raw.Stride == sizeof(T)) + { + T* srcPtr = (T*)raw.GetUnsafeReadOnlyPtr(); + for (int i = 0; i < length; i++) + { + srcPtr[i].WriteTo(dst); + dst += stride; + } + } + else { - T pixel = raw[i]; - pixel.WriteTo(destPtr + i * stride); + for (int i = 0; i < length; i++) + { + T pixel = raw[i]; + pixel.WriteTo(dst); + dst += stride; + } } } } diff --git a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_api.cs b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_api.cs index 9187f61..71e05ad 100644 --- a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_api.cs +++ b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_api.cs @@ -1,16 +1,437 @@ using System; using System.Runtime.InteropServices; +namespace Aperture.Astcenc.Runtime.NativeAPI +{ public static class astcenc_api { -#if UNITY_IOS && !UNITY_EDITOR +#if UNITY_ANDROID && !UNITY_EDITOR + internal const bool IsNativeLibraryAvailable = true; + private const string NeonLibraryName = "libastcenc-neon-shared"; + private const string NoneLibraryName = "libastcenc-none-shared"; + + [DllImport(NeonLibraryName, EntryPoint = "astcenc_config_init", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_config_init_neon( + astcenc_profile profile, + uint block_x, + uint block_y, + uint block_z, + float quality, + uint flags, + ref astcenc_config config); + + [DllImport(NoneLibraryName, EntryPoint = "astcenc_config_init", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_config_init_none( + astcenc_profile profile, + uint block_x, + uint block_y, + uint block_z, + float quality, + uint flags, + ref astcenc_config config); + + [DllImport(NeonLibraryName, EntryPoint = "astcenc_context_alloc", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_context_alloc_neon( + ref astcenc_config config, + uint thread_count, + ref IntPtr context, + IntPtr parent_context); + + [DllImport(NeonLibraryName, EntryPoint = "astcenc_context_alloc", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_context_alloc_parent_neon( + IntPtr config, + uint thread_count, + ref IntPtr context, + IntPtr parent_context); + + [DllImport(NoneLibraryName, EntryPoint = "astcenc_context_alloc", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_context_alloc_none( + ref astcenc_config config, + uint thread_count, + ref IntPtr context, + IntPtr parent_context); + + [DllImport(NoneLibraryName, EntryPoint = "astcenc_context_alloc", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_context_alloc_parent_none( + IntPtr config, + uint thread_count, + ref IntPtr context, + IntPtr parent_context); + + [DllImport(NeonLibraryName, EntryPoint = "astcenc_compress_image", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_compress_image_neon( + IntPtr context, + ref astcenc_image image, + ref astcenc_swizzle swizzle, + IntPtr data_out, + UIntPtr data_len, + uint thread_index); + + [DllImport(NoneLibraryName, EntryPoint = "astcenc_compress_image", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_compress_image_none( + IntPtr context, + ref astcenc_image image, + ref astcenc_swizzle swizzle, + IntPtr data_out, + UIntPtr data_len, + uint thread_index); + + [DllImport(NeonLibraryName, EntryPoint = "astcenc_compress_reset", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_compress_reset_neon( + IntPtr context); + + [DllImport(NoneLibraryName, EntryPoint = "astcenc_compress_reset", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_compress_reset_none( + IntPtr context); + + [DllImport(NeonLibraryName, EntryPoint = "astcenc_compress_cancel", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_compress_cancel_neon( + IntPtr context); + + [DllImport(NoneLibraryName, EntryPoint = "astcenc_compress_cancel", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_compress_cancel_none( + IntPtr context); + + [DllImport(NeonLibraryName, EntryPoint = "astcenc_decompress_image", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_decompress_image_neon( + IntPtr context, + IntPtr data, + UIntPtr data_len, + ref astcenc_image image_out, + ref astcenc_swizzle swizzle, + uint thread_index); + + [DllImport(NoneLibraryName, EntryPoint = "astcenc_decompress_image", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_decompress_image_none( + IntPtr context, + IntPtr data, + UIntPtr data_len, + ref astcenc_image image_out, + ref astcenc_swizzle swizzle, + uint thread_index); + + [DllImport(NeonLibraryName, EntryPoint = "astcenc_decompress_reset", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_decompress_reset_neon( + IntPtr context); + + [DllImport(NoneLibraryName, EntryPoint = "astcenc_decompress_reset", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_decompress_reset_none( + IntPtr context); + + [DllImport(NeonLibraryName, EntryPoint = "astcenc_context_free", CallingConvention = CallingConvention.Cdecl)] + private static extern void astcenc_context_free_neon( + IntPtr context); + + [DllImport(NoneLibraryName, EntryPoint = "astcenc_context_free", CallingConvention = CallingConvention.Cdecl)] + private static extern void astcenc_context_free_none( + IntPtr context); + + /** + * Populate a codec config based on default settings. + * + * Power users can edit the returned config struct to fine tune before allocating the context. + * + * @param profile Color profile. + * @param block_x ASTC block size X dimension. + * @param block_y ASTC block size Y dimension. + * @param block_z ASTC block size Z dimension. + * @param quality Search quality preset / effort level. Either an + * @c ASTCENC_PRE_* value, or a effort level between 0 + * and 100. Performance is not linear between 0 and 100. + + * @param flags A valid set of @c ASTCENC_FLG_* flag bits. + * @param[out] config Output config struct to populate. + * + * @return @c ASTCENC_SUCCESS on success, or an error if the inputs are invalid + * either individually, or in combination. + */ + public static astcenc_error astcenc_config_init( + astcenc_profile profile, + uint block_x, + uint block_y, + uint block_z, + float quality, + uint flags, + ref astcenc_config config) + { + return IntPtr.Size == 8 + ? astcenc_config_init_neon(profile, block_x, block_y, block_z, quality, flags, ref config) + : astcenc_config_init_none(profile, block_x, block_y, block_z, quality, flags, ref config); + } + + /** + * @brief Allocate a new codec context based on a config. + * + * This function allocates all of the memory resources and threads needed by the codec. This can be + * slow, so it is recommended that contexts are reused to serially compress or decompress multiple + * images to amortize setup cost. + * + * Contexts can be allocated to support only decompression using the @c ASTCENC_FLG_DECOMPRESS_ONLY + * flag when creating the configuration. The compression functions will fail if invoked. For a + * decompress-only library build the @c ASTCENC_FLG_DECOMPRESS_ONLY flag must be set when creating + * any context. + * + * @param[in] config Codec config. + * @param thread_count Thread count to configure for. + * @param[out] context Location to store an opaque context pointer. + * @param[in] parent_context Optional parent context from which to inherit read-only data tables, or IntPtr.Zero. + * + * @return @c ASTCENC_SUCCESS on success, or an error if context creation failed. + */ + public static astcenc_error astcenc_context_alloc( + ref astcenc_config config, + uint thread_count, + ref IntPtr context, + IntPtr parent_context) + { + return IntPtr.Size == 8 + ? astcenc_context_alloc_neon(ref config, thread_count, ref context, parent_context) + : astcenc_context_alloc_none(ref config, thread_count, ref context, parent_context); + } + + public static astcenc_error astcenc_context_alloc( + IntPtr config, + uint thread_count, + ref IntPtr context, + IntPtr parent_context) + { + return IntPtr.Size == 8 + ? astcenc_context_alloc_parent_neon(config, thread_count, ref context, parent_context) + : astcenc_context_alloc_parent_none(config, thread_count, ref context, parent_context); + } + + /** + * @brief Compress an image. + * + * A single context can only compress or decompress a single image at a time. + * + * For a context configured for multi-threading, any set of the N threads can call this function. + * Work will be dynamically scheduled across the threads available. Each thread must have a unique + * @c thread_index. + * + * @param context Codec context. + * @param[in,out] image An input image, in 2D slices. + * @param swizzle Compression data swizzle, applied before compression. + * @param[out] data_out Pointer to output data array. + * @param data_len Length of the output data array. + * @param thread_index Thread index [0..N-1] of calling thread. + * + * @return @c ASTCENC_SUCCESS on success, or an error if compression failed. + */ + public static astcenc_error astcenc_compress_image( + IntPtr context, + ref astcenc_image image, + ref astcenc_swizzle swizzle, + IntPtr data_out, + UIntPtr data_len, + uint thread_index) + { + return IntPtr.Size == 8 + ? astcenc_compress_image_neon(context, ref image, ref swizzle, data_out, data_len, thread_index) + : astcenc_compress_image_none(context, ref image, ref swizzle, data_out, data_len, thread_index); + } + + /** + * @brief Reset the codec state for a new compression. + * + * The caller is responsible for synchronizing threads in the worker thread pool. This function must + * only be called when all threads have exited the @c astcenc_compress_image() function for image N, + * but before any thread enters it for image N + 1. + * + * Calling this is not required (but won't hurt), if the context is created for single threaded use. + * + * @param context Codec context. + * + * @return @c ASTCENC_SUCCESS on success, or an error if reset failed. + */ + public static astcenc_error astcenc_compress_reset( + IntPtr context) + { + return IntPtr.Size == 8 + ? astcenc_compress_reset_neon(context) + : astcenc_compress_reset_none(context); + } + + /** + * @brief Cancel any pending compression operation. + * + * @param context Codec context. + * + * @return @c ASTCENC_SUCCESS on success, or an error if cancellation failed. + */ + public static astcenc_error astcenc_compress_cancel( + IntPtr context) + { + return IntPtr.Size == 8 + ? astcenc_compress_cancel_neon(context) + : astcenc_compress_cancel_none(context); + } + + /** + * @brief Decompress an image. + * + * @param context Codec context. + * @param[in] data Pointer to compressed data. + * @param data_len Length of the compressed data array. + * @param[out] image_out Output image. + * @param[in] swizzle Decompression data swizzle, applied after decompression. + * @param thread_index Thread index [0..N-1] of calling thread. + * + * @return @c ASTCENC_SUCCESS on success, or an error if decompression failed. + */ + public static astcenc_error astcenc_decompress_image( + IntPtr context, + IntPtr data, + UIntPtr data_len, + ref astcenc_image image_out, + ref astcenc_swizzle swizzle, + uint thread_index) + { + return IntPtr.Size == 8 + ? astcenc_decompress_image_neon(context, data, data_len, ref image_out, ref swizzle, thread_index) + : astcenc_decompress_image_none(context, data, data_len, ref image_out, ref swizzle, thread_index); + } + + /** + * @brief Reset the codec state for a new decompression. + * + * @param context Codec context. + * + * @return @c ASTCENC_SUCCESS on success, or an error if reset failed. + */ + public static astcenc_error astcenc_decompress_reset( + IntPtr context) + { + return IntPtr.Size == 8 + ? astcenc_decompress_reset_neon(context) + : astcenc_decompress_reset_none(context); + } + + /** + * Free the compressor context. + * + * @param context The codec context. + */ + public static void astcenc_context_free( + IntPtr context) + { + if (IntPtr.Size == 8) + astcenc_context_free_neon(context); + else + astcenc_context_free_none(context); + } +#elif UNITY_EDITOR_WIN || (!UNITY_EDITOR && UNITY_STANDALONE_WIN) + internal const bool IsNativeLibraryAvailable = true; + private const string Avx2LibraryName = "astcenc-avx2-shared.dll"; + private const string Sse41LibraryName = "astcenc-sse4.1-shared.dll"; + private const uint PF_AVX2_INSTRUCTIONS_AVAILABLE = 40u; + + [DllImport("kernel32.dll")] + private static extern bool IsProcessorFeaturePresent(uint processorFeature); + + private static readonly bool s_UseAvx2 = ProbeAvx2Support(); + + private static bool ProbeAvx2Support() + { + try + { + if (!IsProcessorFeaturePresent(PF_AVX2_INSTRUCTIONS_AVAILABLE)) + return false; + + astcenc_config probe = new astcenc_config(); + return astcenc_config_init_avx2(astcenc_profile.ASTCENC_PRF_LDR, 4u, 4u, 1u, 0.0f, 0u, ref probe) == astcenc_error.ASTCENC_SUCCESS; + } + catch + { + return false; + } + } + + [DllImport(Avx2LibraryName, EntryPoint = "astcenc_config_init", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_config_init_avx2(astcenc_profile profile, uint block_x, uint block_y, uint block_z, float quality, uint flags, ref astcenc_config config); + [DllImport(Sse41LibraryName, EntryPoint = "astcenc_config_init", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_config_init_sse41(astcenc_profile profile, uint block_x, uint block_y, uint block_z, float quality, uint flags, ref astcenc_config config); + + [DllImport(Avx2LibraryName, EntryPoint = "astcenc_context_alloc", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_context_alloc_avx2(ref astcenc_config config, uint thread_count, ref IntPtr context, IntPtr parent_context); + [DllImport(Avx2LibraryName, EntryPoint = "astcenc_context_alloc", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_context_alloc_parent_avx2(IntPtr config, uint thread_count, ref IntPtr context, IntPtr parent_context); + [DllImport(Sse41LibraryName, EntryPoint = "astcenc_context_alloc", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_context_alloc_sse41(ref astcenc_config config, uint thread_count, ref IntPtr context, IntPtr parent_context); + [DllImport(Sse41LibraryName, EntryPoint = "astcenc_context_alloc", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_context_alloc_parent_sse41(IntPtr config, uint thread_count, ref IntPtr context, IntPtr parent_context); + + [DllImport(Avx2LibraryName, EntryPoint = "astcenc_compress_image", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_compress_image_avx2(IntPtr context, ref astcenc_image image, ref astcenc_swizzle swizzle, IntPtr data_out, UIntPtr data_len, uint thread_index); + [DllImport(Sse41LibraryName, EntryPoint = "astcenc_compress_image", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_compress_image_sse41(IntPtr context, ref astcenc_image image, ref astcenc_swizzle swizzle, IntPtr data_out, UIntPtr data_len, uint thread_index); + + [DllImport(Avx2LibraryName, EntryPoint = "astcenc_compress_reset", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_compress_reset_avx2(IntPtr context); + [DllImport(Sse41LibraryName, EntryPoint = "astcenc_compress_reset", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_compress_reset_sse41(IntPtr context); + + [DllImport(Avx2LibraryName, EntryPoint = "astcenc_compress_cancel", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_compress_cancel_avx2(IntPtr context); + [DllImport(Sse41LibraryName, EntryPoint = "astcenc_compress_cancel", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_compress_cancel_sse41(IntPtr context); + + [DllImport(Avx2LibraryName, EntryPoint = "astcenc_decompress_image", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_decompress_image_avx2(IntPtr context, IntPtr data, UIntPtr data_len, ref astcenc_image image_out, ref astcenc_swizzle swizzle, uint thread_index); + [DllImport(Sse41LibraryName, EntryPoint = "astcenc_decompress_image", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_decompress_image_sse41(IntPtr context, IntPtr data, UIntPtr data_len, ref astcenc_image image_out, ref astcenc_swizzle swizzle, uint thread_index); + + [DllImport(Avx2LibraryName, EntryPoint = "astcenc_decompress_reset", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_decompress_reset_avx2(IntPtr context); + [DllImport(Sse41LibraryName, EntryPoint = "astcenc_decompress_reset", CallingConvention = CallingConvention.Cdecl)] + private static extern astcenc_error astcenc_decompress_reset_sse41(IntPtr context); + + [DllImport(Avx2LibraryName, EntryPoint = "astcenc_context_free", CallingConvention = CallingConvention.Cdecl)] + private static extern void astcenc_context_free_avx2(IntPtr context); + [DllImport(Sse41LibraryName, EntryPoint = "astcenc_context_free", CallingConvention = CallingConvention.Cdecl)] + private static extern void astcenc_context_free_sse41(IntPtr context); + + public static astcenc_error astcenc_config_init(astcenc_profile profile, uint block_x, uint block_y, uint block_z, float quality, uint flags, ref astcenc_config config) + => s_UseAvx2 ? astcenc_config_init_avx2(profile, block_x, block_y, block_z, quality, flags, ref config) : astcenc_config_init_sse41(profile, block_x, block_y, block_z, quality, flags, ref config); + + public static astcenc_error astcenc_context_alloc(ref astcenc_config config, uint thread_count, ref IntPtr context, IntPtr parent_context) + => s_UseAvx2 ? astcenc_context_alloc_avx2(ref config, thread_count, ref context, parent_context) : astcenc_context_alloc_sse41(ref config, thread_count, ref context, parent_context); + + public static astcenc_error astcenc_context_alloc(IntPtr config, uint thread_count, ref IntPtr context, IntPtr parent_context) + => s_UseAvx2 ? astcenc_context_alloc_parent_avx2(config, thread_count, ref context, parent_context) : astcenc_context_alloc_parent_sse41(config, thread_count, ref context, parent_context); + + public static astcenc_error astcenc_compress_image(IntPtr context, ref astcenc_image image, ref astcenc_swizzle swizzle, IntPtr data_out, UIntPtr data_len, uint thread_index) + => s_UseAvx2 ? astcenc_compress_image_avx2(context, ref image, ref swizzle, data_out, data_len, thread_index) : astcenc_compress_image_sse41(context, ref image, ref swizzle, data_out, data_len, thread_index); + + public static astcenc_error astcenc_compress_reset(IntPtr context) + => s_UseAvx2 ? astcenc_compress_reset_avx2(context) : astcenc_compress_reset_sse41(context); + + public static astcenc_error astcenc_compress_cancel(IntPtr context) + => s_UseAvx2 ? astcenc_compress_cancel_avx2(context) : astcenc_compress_cancel_sse41(context); + + public static astcenc_error astcenc_decompress_image(IntPtr context, IntPtr data, UIntPtr data_len, ref astcenc_image image_out, ref astcenc_swizzle swizzle, uint thread_index) + => s_UseAvx2 ? astcenc_decompress_image_avx2(context, data, data_len, ref image_out, ref swizzle, thread_index) : astcenc_decompress_image_sse41(context, data, data_len, ref image_out, ref swizzle, thread_index); + + public static astcenc_error astcenc_decompress_reset(IntPtr context) + => s_UseAvx2 ? astcenc_decompress_reset_avx2(context) : astcenc_decompress_reset_sse41(context); + + public static void astcenc_context_free(IntPtr context) + { + if (s_UseAvx2) astcenc_context_free_avx2(context); + else astcenc_context_free_sse41(context); + } +#elif UNITY_EDITOR_OSX || UNITY_EDITOR_LINUX || (!UNITY_EDITOR && (UNITY_IOS || UNITY_STANDALONE_OSX || UNITY_STANDALONE_LINUX)) + internal const bool IsNativeLibraryAvailable = true; +#if UNITY_EDITOR_OSX + internal const string LibraryName = "libastcenc-shared"; +#elif UNITY_EDITOR_LINUX + internal const string LibraryName = "libastcenc-sse4.1-shared"; +#elif UNITY_IOS internal const string LibraryName = "__Internal"; -#elif UNITY_ANDROID && !UNITY_EDITOR - internal const string LibraryName = "libastcenc-neon-shared"; -#elif UNITY_EDITOR_OSX +#elif UNITY_STANDALONE_OSX internal const string LibraryName = "libastcenc-shared"; -#elif UNITY_EDITOR_WIN - internal const string LibraryName = "astcenc-sse4.1-shared.dll"; +#elif UNITY_STANDALONE_LINUX + internal const string LibraryName = "libastcenc-sse4.1-shared"; #endif /** @@ -54,9 +475,10 @@ public static extern astcenc_error astcenc_config_init( * decompress-only library build the @c ASTCENC_FLG_DECOMPRESS_ONLY flag must be set when creating * any context. * - * @param[in] config Codec config. - * @param thread_count Thread count to configure for. - * @param[out] context Location to store an opaque context pointer. + * @param[in] config Codec config. + * @param thread_count Thread count to configure for. + * @param[out] context Location to store an opaque context pointer. + * @param[in] parent_context Optional parent context from which to inherit read-only data tables, or IntPtr.Zero. * * @return @c ASTCENC_SUCCESS on success, or an error if context creation failed. */ @@ -64,7 +486,15 @@ public static extern astcenc_error astcenc_config_init( public static extern astcenc_error astcenc_context_alloc( ref astcenc_config config, uint thread_count, - ref IntPtr context); + ref IntPtr context, + IntPtr parent_context); + + [DllImport(LibraryName, EntryPoint = "astcenc_context_alloc", CallingConvention = CallingConvention.Cdecl)] + public static extern astcenc_error astcenc_context_alloc( + IntPtr config, + uint thread_count, + ref IntPtr context, + IntPtr parent_context); /** * @brief Compress an image. @@ -84,22 +514,13 @@ public static extern astcenc_error astcenc_context_alloc( * * @return @c ASTCENC_SUCCESS on success, or an error if compression failed. */ - //[DllImport(LibraryName, EntryPoint = "astcenc_compress_image", CallingConvention = CallingConvention.Cdecl)] - //public static extern astcenc_error astcenc_compress_image( - // IntPtr context, - // ref astcenc_image image, - // ref astcenc_swizzle swizzle, - // [In, Out] byte[] data_out, - // [MarshalAs(UnmanagedType.SysInt)] int data_len, - // uint thread_index); - [DllImport(LibraryName, EntryPoint = "astcenc_compress_image", CallingConvention = CallingConvention.Cdecl)] public static extern astcenc_error astcenc_compress_image( IntPtr context, ref astcenc_image image, ref astcenc_swizzle swizzle, IntPtr data_out, - [MarshalAs(UnmanagedType.SysInt)] int data_len, + UIntPtr data_len, uint thread_index); /** * @brief Reset the codec state for a new compression. @@ -118,6 +539,49 @@ public static extern astcenc_error astcenc_compress_image( public static extern astcenc_error astcenc_compress_reset( IntPtr context); + /** + * @brief Cancel any pending compression operation. + * + * @param context Codec context. + * + * @return @c ASTCENC_SUCCESS on success, or an error if cancellation failed. + */ + [DllImport(LibraryName, EntryPoint = "astcenc_compress_cancel", CallingConvention = CallingConvention.Cdecl)] + public static extern astcenc_error astcenc_compress_cancel( + IntPtr context); + + /** + * @brief Decompress an image. + * + * @param context Codec context. + * @param[in] data Pointer to compressed data. + * @param data_len Length of the compressed data array. + * @param[out] image_out Output image. + * @param[in] swizzle Decompression data swizzle, applied after decompression. + * @param thread_index Thread index [0..N-1] of calling thread. + * + * @return @c ASTCENC_SUCCESS on success, or an error if decompression failed. + */ + [DllImport(LibraryName, EntryPoint = "astcenc_decompress_image", CallingConvention = CallingConvention.Cdecl)] + public static extern astcenc_error astcenc_decompress_image( + IntPtr context, + IntPtr data, + UIntPtr data_len, + ref astcenc_image image_out, + ref astcenc_swizzle swizzle, + uint thread_index); + + /** + * @brief Reset the codec state for a new decompression. + * + * @param context Codec context. + * + * @return @c ASTCENC_SUCCESS on success, or an error if reset failed. + */ + [DllImport(LibraryName, EntryPoint = "astcenc_decompress_reset", CallingConvention = CallingConvention.Cdecl)] + public static extern astcenc_error astcenc_decompress_reset( + IntPtr context); + /** * Free the compressor context. * @@ -126,4 +590,57 @@ public static extern astcenc_error astcenc_compress_reset( [DllImport(LibraryName, EntryPoint = "astcenc_context_free", CallingConvention = CallingConvention.Cdecl)] public static extern void astcenc_context_free( IntPtr context); +#else + internal const bool IsNativeLibraryAvailable = false; + + public static astcenc_error astcenc_config_init( + astcenc_profile profile, + uint block_x, + uint block_y, + uint block_z, + float quality, + uint flags, + ref astcenc_config config) => astcenc_error.ASTCENC_ERR_NOT_IMPLEMENTED; + + public static astcenc_error astcenc_context_alloc( + ref astcenc_config config, + uint thread_count, + ref IntPtr context, + IntPtr parent_context) => astcenc_error.ASTCENC_ERR_NOT_IMPLEMENTED; + + public static astcenc_error astcenc_context_alloc( + IntPtr config, + uint thread_count, + ref IntPtr context, + IntPtr parent_context) => astcenc_error.ASTCENC_ERR_NOT_IMPLEMENTED; + + public static astcenc_error astcenc_compress_image( + IntPtr context, + ref astcenc_image image, + ref astcenc_swizzle swizzle, + IntPtr data_out, + UIntPtr data_len, + uint thread_index) => astcenc_error.ASTCENC_ERR_NOT_IMPLEMENTED; + + public static astcenc_error astcenc_compress_reset( + IntPtr context) => astcenc_error.ASTCENC_ERR_NOT_IMPLEMENTED; + + public static astcenc_error astcenc_compress_cancel( + IntPtr context) => astcenc_error.ASTCENC_ERR_NOT_IMPLEMENTED; + + public static astcenc_error astcenc_decompress_image( + IntPtr context, + IntPtr data, + UIntPtr data_len, + ref astcenc_image image_out, + ref astcenc_swizzle swizzle, + uint thread_index) => astcenc_error.ASTCENC_ERR_NOT_IMPLEMENTED; + + public static astcenc_error astcenc_decompress_reset( + IntPtr context) => astcenc_error.ASTCENC_ERR_NOT_IMPLEMENTED; + + public static void astcenc_context_free( + IntPtr context) { } +#endif +} } diff --git a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_config.cs b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_config.cs index d9d4503..e5461ca 100644 --- a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_config.cs +++ b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_config.cs @@ -1,5 +1,8 @@ -using System.Runtime.InteropServices; +using System; +using System.Runtime.InteropServices; +namespace Aperture.Astcenc.Runtime.NativeAPI +{ /** * @brief The config structure. * @@ -161,4 +164,18 @@ public struct astcenc_config * This option is ineffective for normal maps. */ public float tune_2plane_early_out_limit_correlation; + + /** + * @brief The config enable for the mode0 fast-path search. + * + * If this is set to TUNE_MIN_TEXELS_MODE0 or higher then the early-out fast mode0 + * search is enabled. This option is ineffective for 3D block sizes. + */ + public float tune_search_mode0_enable; + + /** + * @brief The progress callback function pointer, can be IntPtr.Zero. + */ + public IntPtr progress_callback; +} } \ No newline at end of file diff --git a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_error.cs b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_error.cs index 6d7fe71..5b4ea3a 100644 --- a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_error.cs +++ b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_error.cs @@ -1,28 +1,33 @@ -/** - * @brief A codec API error code. - */ -public enum astcenc_error +namespace Aperture.Astcenc.Runtime.NativeAPI { - /** @brief The call was successful. */ - ASTCENC_SUCCESS = 0, - /** @brief The call failed due to low memory, or undersized I/O buffers. */ - ASTCENC_ERR_OUT_OF_MEM, - /** @brief The call failed due to the build using fast math. */ - ASTCENC_ERR_BAD_CPU_FLOAT, - /** @brief The call failed due to an out-of-spec parameter. */ - ASTCENC_ERR_BAD_PARAM, - /** @brief The call failed due to an out-of-spec block size. */ - ASTCENC_ERR_BAD_BLOCK_SIZE, - /** @brief The call failed due to an out-of-spec color profile. */ - ASTCENC_ERR_BAD_PROFILE, - /** @brief The call failed due to an out-of-spec quality value. */ - ASTCENC_ERR_BAD_QUALITY, - /** @brief The call failed due to an out-of-spec component swizzle. */ - ASTCENC_ERR_BAD_SWIZZLE, - /** @brief The call failed due to an out-of-spec flag set. */ - ASTCENC_ERR_BAD_FLAGS, - /** @brief The call failed due to the context not supporting the operation. */ - ASTCENC_ERR_BAD_CONTEXT, - /** @brief The call failed due to unimplemented functionality. */ - ASTCENC_ERR_NOT_IMPLEMENTED, + /** + * @brief A codec API error code. + */ + public enum astcenc_error + { + /** @brief The call was successful. */ + ASTCENC_SUCCESS = 0, + /** @brief The call failed due to low memory, or undersized I/O buffers. */ + ASTCENC_ERR_OUT_OF_MEM, + /** @brief The call failed due to the build using fast math. */ + ASTCENC_ERR_BAD_CPU_FLOAT, + /** @brief The call failed due to an out-of-spec parameter. */ + ASTCENC_ERR_BAD_PARAM, + /** @brief The call failed due to an out-of-spec block size. */ + ASTCENC_ERR_BAD_BLOCK_SIZE, + /** @brief The call failed due to an out-of-spec color profile. */ + ASTCENC_ERR_BAD_PROFILE, + /** @brief The call failed due to an out-of-spec quality value. */ + ASTCENC_ERR_BAD_QUALITY, + /** @brief The call failed due to an out-of-spec component swizzle. */ + ASTCENC_ERR_BAD_SWIZZLE, + /** @brief The call failed due to an out-of-spec flag set. */ + ASTCENC_ERR_BAD_FLAGS, + /** @brief The call failed due to the context not supporting the operation. */ + ASTCENC_ERR_BAD_CONTEXT, + /** @brief The call failed due to unimplemented functionality. */ + ASTCENC_ERR_NOT_IMPLEMENTED, + /** @brief The call failed due to an out-of-spec decode mode flag set. */ + ASTCENC_ERR_BAD_DECODE_MODE, + } } \ No newline at end of file diff --git a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_image.cs b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_image.cs index 995b865..75913f4 100644 --- a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_image.cs +++ b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_image.cs @@ -1,27 +1,30 @@ -using System; +using System; using System.Runtime.InteropServices; -/** - * @brief An uncompressed 2D or 3D image. - * - * 3D image are passed in as an array of 2D slices. Each slice has identical - * size and color format. - */ -[StructLayout(LayoutKind.Sequential)] -public struct astcenc_image +namespace Aperture.Astcenc.Runtime.NativeAPI { - /** @brief The X dimension of the image, in texels. */ - public uint dim_x; + /** + * @brief An uncompressed 2D or 3D image. + * + * 3D image are passed in as an array of 2D slices. Each slice has identical + * size and color format. + */ + [StructLayout(LayoutKind.Sequential)] + public struct astcenc_image + { + /** @brief The X dimension of the image, in texels. */ + public uint dim_x; - /** @brief The Y dimension of the image, in texels. */ - public uint dim_y; + /** @brief The Y dimension of the image, in texels. */ + public uint dim_y; - /** @brief The Z dimension of the image, in texels. */ - public uint dim_z; + /** @brief The Z dimension of the image, in texels. */ + public uint dim_z; - /** @brief The data type per component. */ - public astcenc_type data_type; + /** @brief The data type per component. */ + public astcenc_type data_type; - /** @brief The array of 2D slices, of length @c dim_z. */ - public IntPtr data; + /** @brief The array of 2D slices, of length @c dim_z. */ + public IntPtr data; + } } \ No newline at end of file diff --git a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_profile.cs b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_profile.cs index 8f07e0b..15bcb9b 100644 --- a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_profile.cs +++ b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_profile.cs @@ -1,14 +1,17 @@ -/** - * @brief A codec color profile. - */ -public enum astcenc_profile +namespace Aperture.Astcenc.Runtime.NativeAPI { - /** @brief The LDR sRGB color profile. */ - ASTCENC_PRF_LDR_SRGB = 0, - /** @brief The LDR linear color profile. */ - ASTCENC_PRF_LDR, - /** @brief The HDR RGB with LDR alpha color profile. */ - ASTCENC_PRF_HDR_RGB_LDR_A, - /** @brief The HDR RGBA color profile. */ - ASTCENC_PRF_HDR, + /** + * @brief A codec color profile. + */ + public enum astcenc_profile + { + /** @brief The LDR sRGB color profile. */ + ASTCENC_PRF_LDR_SRGB = 0, + /** @brief The LDR linear color profile. */ + ASTCENC_PRF_LDR, + /** @brief The HDR RGB with LDR alpha color profile. */ + ASTCENC_PRF_HDR_RGB_LDR_A, + /** @brief The HDR RGBA color profile. */ + ASTCENC_PRF_HDR, + } } diff --git a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_swizzle.cs b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_swizzle.cs index a79c44c..2580e41 100644 --- a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_swizzle.cs +++ b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_swizzle.cs @@ -1,17 +1,20 @@ -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; -/** - * @brief A texel component swizzle. - */ -[StructLayout(LayoutKind.Sequential)] -public struct astcenc_swizzle +namespace Aperture.Astcenc.Runtime.NativeAPI { - /** @brief The red component selector. */ - public astcenc_swz r; - /** @brief The green component selector. */ - public astcenc_swz g; - /** @brief The blue component selector. */ - public astcenc_swz b; - /** @brief The alpha component selector. */ - public astcenc_swz a; + /** + * @brief A texel component swizzle. + */ + [StructLayout(LayoutKind.Sequential)] + public struct astcenc_swizzle + { + /** @brief The red component selector. */ + public astcenc_swz r; + /** @brief The green component selector. */ + public astcenc_swz g; + /** @brief The blue component selector. */ + public astcenc_swz b; + /** @brief The alpha component selector. */ + public astcenc_swz a; + } } \ No newline at end of file diff --git a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_swz.cs b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_swz.cs index 204bc6a..b11923c 100644 --- a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_swz.cs +++ b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_swz.cs @@ -1,20 +1,23 @@ -/** - * @brief A codec component swizzle selector. - */ -public enum astcenc_swz +namespace Aperture.Astcenc.Runtime.NativeAPI { - /** @brief Select the red component. */ - ASTCENC_SWZ_R = 0, - /** @brief Select the green component. */ - ASTCENC_SWZ_G = 1, - /** @brief Select the blue component. */ - ASTCENC_SWZ_B = 2, - /** @brief Select the alpha component. */ - ASTCENC_SWZ_A = 3, - /** @brief Use a constant zero component. */ - ASTCENC_SWZ_0 = 4, - /** @brief Use a constant one component. */ - ASTCENC_SWZ_1 = 5, - /** @brief Use a reconstructed normal vector Z component. */ - ASTCENC_SWZ_Z = 6 + /** + * @brief A codec component swizzle selector. + */ + public enum astcenc_swz + { + /** @brief Select the red component. */ + ASTCENC_SWZ_R = 0, + /** @brief Select the green component. */ + ASTCENC_SWZ_G = 1, + /** @brief Select the blue component. */ + ASTCENC_SWZ_B = 2, + /** @brief Select the alpha component. */ + ASTCENC_SWZ_A = 3, + /** @brief Use a constant zero component. */ + ASTCENC_SWZ_0 = 4, + /** @brief Use a constant one component. */ + ASTCENC_SWZ_1 = 5, + /** @brief Use a reconstructed normal vector Z component. */ + ASTCENC_SWZ_Z = 6 + } } \ No newline at end of file diff --git a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_type.cs b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_type.cs index 64e676a..6f7add0 100644 --- a/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_type.cs +++ b/Assets/ASTC Encoder/Runtime/NativeAPI/astcenc_type.cs @@ -1,12 +1,15 @@ -/** - * @brief A texel component data format. - */ -public enum astcenc_type +namespace Aperture.Astcenc.Runtime.NativeAPI { - /** @brief Unorm 8-bit data per component. */ - ASTCENC_TYPE_U8 = 0, - /** @brief 16-bit float per component. */ - ASTCENC_TYPE_F16 = 1, - /** @brief 32-bit float per component. */ - ASTCENC_TYPE_F32 = 2 + /** + * @brief A texel component data format. + */ + public enum astcenc_type + { + /** @brief Unorm 8-bit data per component. */ + ASTCENC_TYPE_U8 = 0, + /** @brief 16-bit float per component. */ + ASTCENC_TYPE_F16 = 1, + /** @brief 32-bit float per component. */ + ASTCENC_TYPE_F32 = 2 + } } \ No newline at end of file diff --git a/Assets/ASTC Encoder/Runtime/RawTextureData.cs b/Assets/ASTC Encoder/Runtime/RawTextureData.cs new file mode 100644 index 0000000..c1dff10 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/RawTextureData.cs @@ -0,0 +1,282 @@ +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +namespace Aperture.Astcenc.Runtime +{ + internal unsafe interface IRawData + { + void WriteTo(void* destPtr); + } + + internal static class RawDataConstants + { + internal const uint ByteAlphaOneMask = 0xFF000000u; + internal const ushort HalfOne = 0x3C00; + internal const uint FloatOneBits = 0x3F800000u; + internal const float InvUShortMax = 1.0f / 65535.0f; + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct R8 : IRawData + { + private byte m_R; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + *(uint*)destPtr = RawDataConstants.ByteAlphaOneMask | m_R; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct RG8 : IRawData + { + private byte m_R; + private byte m_G; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + *(uint*)destPtr = RawDataConstants.ByteAlphaOneMask | m_R | ((uint)m_G << 8); + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct RGB8 : IRawData + { + private byte m_R; + private byte m_G; + private byte m_B; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + *(uint*)destPtr = RawDataConstants.ByteAlphaOneMask | m_R | ((uint)m_G << 8) | ((uint)m_B << 16); + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct RGBA8 : IRawData + { + private byte m_R; + private byte m_G; + private byte m_B; + private byte m_A; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + *(uint*)destPtr = m_R | ((uint)m_G << 8) | ((uint)m_B << 16) | ((uint)m_A << 24); + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct R16 : IRawData + { + private ushort m_R; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + float* dst = (float*)destPtr; + dst[0] = m_R * RawDataConstants.InvUShortMax; + dst[1] = 0.0f; + dst[2] = 0.0f; + dst[3] = 1.0f; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct RG16 : IRawData + { + private ushort m_R; + private ushort m_G; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + float* dst = (float*)destPtr; + dst[0] = m_R * RawDataConstants.InvUShortMax; + dst[1] = m_G * RawDataConstants.InvUShortMax; + dst[2] = 0.0f; + dst[3] = 1.0f; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct RGB16 : IRawData + { + private ushort m_R; + private ushort m_G; + private ushort m_B; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + float* dst = (float*)destPtr; + dst[0] = m_R * RawDataConstants.InvUShortMax; + dst[1] = m_G * RawDataConstants.InvUShortMax; + dst[2] = m_B * RawDataConstants.InvUShortMax; + dst[3] = 1.0f; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct RGBA16 : IRawData + { + private ushort m_R; + private ushort m_G; + private ushort m_B; + private ushort m_A; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + float* dst = (float*)destPtr; + dst[0] = m_R * RawDataConstants.InvUShortMax; + dst[1] = m_G * RawDataConstants.InvUShortMax; + dst[2] = m_B * RawDataConstants.InvUShortMax; + dst[3] = m_A * RawDataConstants.InvUShortMax; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct R16F : IRawData + { + private ushort m_R; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + ushort* dst = (ushort*)destPtr; + dst[0] = m_R; + dst[1] = 0; + dst[2] = 0; + dst[3] = RawDataConstants.HalfOne; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct RG16F : IRawData + { + private ushort m_R; + private ushort m_G; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + ushort* dst = (ushort*)destPtr; + dst[0] = m_R; + dst[1] = m_G; + dst[2] = 0; + dst[3] = RawDataConstants.HalfOne; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct RGB16F : IRawData + { + private ushort m_R; + private ushort m_G; + private ushort m_B; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + ushort* dst = (ushort*)destPtr; + dst[0] = m_R; + dst[1] = m_G; + dst[2] = m_B; + dst[3] = RawDataConstants.HalfOne; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct RGBA16F : IRawData + { + private ushort m_R; + private ushort m_G; + private ushort m_B; + private ushort m_A; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + ushort* dst = (ushort*)destPtr; + dst[0] = m_R; + dst[1] = m_G; + dst[2] = m_B; + dst[3] = m_A; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct R32F : IRawData + { + private uint m_R; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + uint* dst = (uint*)destPtr; + dst[0] = m_R; + dst[1] = 0u; + dst[2] = 0u; + dst[3] = RawDataConstants.FloatOneBits; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct RG32F : IRawData + { + private uint m_R; + private uint m_G; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + uint* dst = (uint*)destPtr; + dst[0] = m_R; + dst[1] = m_G; + dst[2] = 0u; + dst[3] = RawDataConstants.FloatOneBits; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct RGB32F : IRawData + { + private uint m_R; + private uint m_G; + private uint m_B; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + uint* dst = (uint*)destPtr; + dst[0] = m_R; + dst[1] = m_G; + dst[2] = m_B; + dst[3] = RawDataConstants.FloatOneBits; + } + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + internal struct RGBA32F : IRawData + { + private uint m_R; + private uint m_G; + private uint m_B; + private uint m_A; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public unsafe void WriteTo(void* destPtr) + { + uint* dst = (uint*)destPtr; + dst[0] = m_R; + dst[1] = m_G; + dst[2] = m_B; + dst[3] = m_A; + } + } +} diff --git a/Assets/ASTC Encoder/Runtime/RawTexutureData.cs.meta b/Assets/ASTC Encoder/Runtime/RawTextureData.cs.meta similarity index 100% rename from Assets/ASTC Encoder/Runtime/RawTexutureData.cs.meta rename to Assets/ASTC Encoder/Runtime/RawTextureData.cs.meta diff --git a/Assets/ASTC Encoder/Runtime/RawTexutureData.cs b/Assets/ASTC Encoder/Runtime/RawTexutureData.cs deleted file mode 100644 index 2cb0728..0000000 --- a/Assets/ASTC Encoder/Runtime/RawTexutureData.cs +++ /dev/null @@ -1,775 +0,0 @@ -using System; -using System.Runtime.InteropServices; -using UnityEngine; - -namespace Aperture.Astcenc.Runtime -{ - public interface IRawData - { - void WriteTo(IntPtr destPtr); - } - - public struct R8 : IRawData - { - public float RFloat - { - get - { - return m_R / 255.0f; - } - } - private byte m_R; - - public void WriteTo(IntPtr destPtr) - { - Marshal.WriteByte(destPtr + 0, m_R); - Marshal.WriteByte(destPtr + 1, 0); - Marshal.WriteByte(destPtr + 2, 0); - Marshal.WriteByte(destPtr + 3, 0xFF); - } - } - - public struct RG8 : IRawData - { - public float RFloat - { - get - { - return m_R / 255.0f; - } - } - private byte m_R; - - public float GFloat - { - get - { - return m_G / 255.0f; - } - } - private byte m_G; - - public void WriteTo(IntPtr destPtr) - { - Marshal.WriteByte(destPtr + 0, m_R); - Marshal.WriteByte(destPtr + 1, m_G); - Marshal.WriteByte(destPtr + 2, 0); - Marshal.WriteByte(destPtr + 3, 0xFF); - } - } - - public struct RGB8 : IRawData - { - public float RFloat - { - get - { - return m_R / 255.0f; - } - } - private byte m_R; - - public float GFloat - { - get - { - return m_G / 255.0f; - } - } - private byte m_G; - - public float BFloat - { - get - { - return m_B / 255.0f; - } - } - private byte m_B; - - public void WriteTo(IntPtr destPtr) - { - Marshal.WriteByte(destPtr + 0, m_R); - Marshal.WriteByte(destPtr + 1, m_G); - Marshal.WriteByte(destPtr + 2, m_B); - Marshal.WriteByte(destPtr + 3, 0xFF); - } - } - - public struct RGBA8 : IRawData - { - public float RFloat - { - get - { - return m_R / 255.0f; - } - } - private byte m_R; - - public float GFloat - { - get - { - return m_G / 255.0f; - } - } - private byte m_G; - - public float BFloat - { - get - { - return m_B / 255.0f; - } - } - private byte m_B; - - public float AFloat - { - get - { - return m_A / 255.0f; - } - } - private byte m_A; - - public void WriteTo(IntPtr destPtr) - { - Marshal.WriteByte(destPtr + 0, m_R); - Marshal.WriteByte(destPtr + 1, m_G); - Marshal.WriteByte(destPtr + 2, m_B); - Marshal.WriteByte(destPtr + 3, m_A); - } - } - - public struct R16 : IRawData - { - internal ushort RHalf - { - get - { - return Mathf.FloatToHalf(RFloat); - } - } - - public float RFloat - { - get - { - return m_R / 65535.0f; - } - } - private ushort m_R; - - public void WriteTo(IntPtr destPtr) - { - byte[] r = BitConverter.GetBytes(RHalf); - Marshal.WriteByte(destPtr + 0, r[0]); - Marshal.WriteByte(destPtr + 1, r[1]); - - Marshal.WriteByte(destPtr + 2, 0); - Marshal.WriteByte(destPtr + 3, 0); - - Marshal.WriteByte(destPtr + 4, 0); - Marshal.WriteByte(destPtr + 5, 0); - - Marshal.WriteByte(destPtr + 6, 0x00); - Marshal.WriteByte(destPtr + 7, 0x3C); - } - } - - public struct RG16 : IRawData - { - internal ushort RHalf - { - get - { - return Mathf.FloatToHalf(RFloat); - } - } - - public float RFloat - { - get - { - return m_R / 65535.0f; - } - } - private ushort m_R; - - internal ushort GHalf - { - get - { - return Mathf.FloatToHalf(GFloat); - } - } - - public float GFloat - { - get - { - return m_G / 65535.0f; - } - } - private ushort m_G; - - public void WriteTo(IntPtr destPtr) - { - byte[] r = BitConverter.GetBytes(RHalf); - Marshal.WriteByte(destPtr + 0, r[0]); - Marshal.WriteByte(destPtr + 1, r[1]); - - byte[] g = BitConverter.GetBytes(GHalf); - Marshal.WriteByte(destPtr + 2, g[0]); - Marshal.WriteByte(destPtr + 3, g[1]); - - Marshal.WriteByte(destPtr + 4, 0); - Marshal.WriteByte(destPtr + 5, 0); - - Marshal.WriteByte(destPtr + 6, 0x00); - Marshal.WriteByte(destPtr + 7, 0x3C); - } - } - - public struct RGB16 : IRawData - { - internal ushort RHalf - { - get - { - return Mathf.FloatToHalf(RFloat); - } - } - - public float RFloat - { - get - { - return m_R / 65535.0f; - } - } - private ushort m_R; - - internal ushort GHalf - { - get - { - return Mathf.FloatToHalf(GFloat); - } - } - - public float GFloat - { - get - { - return m_G / 65535.0f; - } - } - private ushort m_G; - - internal ushort BHalf - { - get - { - return Mathf.FloatToHalf(BFloat); - } - } - - public float BFloat - { - get - { - return m_B / 65535.0f; - } - } - private ushort m_B; - - public void WriteTo(IntPtr destPtr) - { - byte[] r = BitConverter.GetBytes(RHalf); - Marshal.WriteByte(destPtr + 0, r[0]); - Marshal.WriteByte(destPtr + 1, r[1]); - - byte[] g = BitConverter.GetBytes(GHalf); - Marshal.WriteByte(destPtr + 2, g[0]); - Marshal.WriteByte(destPtr + 3, g[1]); - - byte[] b = BitConverter.GetBytes(BHalf); - Marshal.WriteByte(destPtr + 4, b[0]); - Marshal.WriteByte(destPtr + 5, b[1]); - - Marshal.WriteByte(destPtr + 6, 0x00); - Marshal.WriteByte(destPtr + 7, 0x3C); - } - } - - public struct RGBA16 : IRawData - { - internal ushort RHalf - { - get - { - return Mathf.FloatToHalf(RFloat); - } - } - - public float RFloat - { - get - { - return m_R / 65535.0f; - } - } - private ushort m_R; - - internal ushort GHalf - { - get - { - return Mathf.FloatToHalf(GFloat); - } - } - - public float GFloat - { - get - { - return m_G / 65535.0f; - } - } - private ushort m_G; - - internal ushort BHalf - { - get - { - return Mathf.FloatToHalf(BFloat); - } - } - - public float BFloat - { - get - { - return m_B / 65535.0f; - } - } - private ushort m_B; - - internal ushort AHalf - { - get - { - return Mathf.FloatToHalf(AFloat); - } - } - - public float AFloat - { - get - { - return m_A / 65535.0f; - } - } - private ushort m_A; - - public void WriteTo(IntPtr destPtr) - { - byte[] r = BitConverter.GetBytes(RHalf); - Marshal.WriteByte(destPtr + 0, r[0]); - Marshal.WriteByte(destPtr + 1, r[1]); - - byte[] g = BitConverter.GetBytes(GHalf); - Marshal.WriteByte(destPtr + 2, g[0]); - Marshal.WriteByte(destPtr + 3, g[1]); - - byte[] b = BitConverter.GetBytes(BHalf); - Marshal.WriteByte(destPtr + 4, b[0]); - Marshal.WriteByte(destPtr + 5, b[1]); - - byte[] a = BitConverter.GetBytes(AHalf); - Marshal.WriteByte(destPtr + 6, a[0]); - Marshal.WriteByte(destPtr + 7, a[1]); - } - } - - public struct R16F : IRawData - { - public float RFloat - { - get - { - return Mathf.HalfToFloat(m_R); - } - } - private ushort m_R; - - public void WriteTo(IntPtr destPtr) - { - byte[] r = BitConverter.GetBytes(m_R); - Marshal.WriteByte(destPtr + 0, r[0]); - Marshal.WriteByte(destPtr + 1, r[1]); - - Marshal.WriteByte(destPtr + 2, 0); - Marshal.WriteByte(destPtr + 3, 0); - - Marshal.WriteByte(destPtr + 4, 0); - Marshal.WriteByte(destPtr + 5, 0); - - Marshal.WriteByte(destPtr + 6, 0x00); - Marshal.WriteByte(destPtr + 7, 0x3C); - } - } - - public struct RG16F : IRawData - { - public float RFloat - { - get - { - return Mathf.HalfToFloat(m_R); - } - } - private ushort m_R; - - public float GFloat - { - get - { - return Mathf.HalfToFloat(m_G); - } - } - private ushort m_G; - - public void WriteTo(IntPtr destPtr) - { - byte[] r = BitConverter.GetBytes(m_R); - Marshal.WriteByte(destPtr + 0, r[0]); - Marshal.WriteByte(destPtr + 1, r[1]); - - byte[] g = BitConverter.GetBytes(m_G); - Marshal.WriteByte(destPtr + 2, g[0]); - Marshal.WriteByte(destPtr + 3, g[1]); - - Marshal.WriteByte(destPtr + 4, 0); - Marshal.WriteByte(destPtr + 5, 0); - - Marshal.WriteByte(destPtr + 6, 0x00); - Marshal.WriteByte(destPtr + 7, 0x3C); - } - } - - public struct RGB16F : IRawData - { - public float RFloat - { - get - { - return Mathf.HalfToFloat(m_R); - } - } - private ushort m_R; - - public float GFloat - { - get - { - return Mathf.HalfToFloat(m_G); - } - } - private ushort m_G; - - public float BFloat - { - get - { - return Mathf.HalfToFloat(m_B); - } - } - public ushort m_B; - - public void WriteTo(IntPtr destPtr) - { - byte[] r = BitConverter.GetBytes(m_R); - Marshal.WriteByte(destPtr + 0, r[0]); - Marshal.WriteByte(destPtr + 1, r[1]); - - byte[] g = BitConverter.GetBytes(m_G); - Marshal.WriteByte(destPtr + 2, g[0]); - Marshal.WriteByte(destPtr + 3, g[1]); - - byte[] b = BitConverter.GetBytes(m_B); - Marshal.WriteByte(destPtr + 4, b[0]); - Marshal.WriteByte(destPtr + 5, b[1]); - - Marshal.WriteByte(destPtr + 6, 0x00); - Marshal.WriteByte(destPtr + 7, 0x3C); - } - } - - public struct RGBA16F : IRawData - { - public float RFloat - { - get - { - return Mathf.HalfToFloat(m_R); - } - } - private ushort m_R; - - public float GFloat - { - get - { - return Mathf.HalfToFloat(m_G); - } - } - private ushort m_G; - - public float BFloat - { - get - { - return Mathf.HalfToFloat(m_B); - } - } - private ushort m_B; - - public float AFloat - { - get - { - return Mathf.HalfToFloat(m_A); - } - } - private ushort m_A; - - public void WriteTo(IntPtr destPtr) - { - byte[] r = BitConverter.GetBytes(m_R); - Marshal.WriteByte(destPtr + 0, r[0]); - Marshal.WriteByte(destPtr + 1, r[1]); - - byte[] g = BitConverter.GetBytes(m_G); - Marshal.WriteByte(destPtr + 2, g[0]); - Marshal.WriteByte(destPtr + 3, g[1]); - - byte[] b = BitConverter.GetBytes(m_B); - Marshal.WriteByte(destPtr + 4, b[0]); - Marshal.WriteByte(destPtr + 5, b[1]); - - byte[] a = BitConverter.GetBytes(m_A); - Marshal.WriteByte(destPtr + 6, a[0]); - Marshal.WriteByte(destPtr + 7, a[1]); - } - } - - public struct R32F : IRawData - { - public float RFloat - { - get - { - return BitConverter.ToSingle(BitConverter.GetBytes(m_R)); - } - } - private uint m_R; - - public void WriteTo(IntPtr destPtr) - { - byte[] r = BitConverter.GetBytes(m_R); - Marshal.WriteByte(destPtr + 0, r[0]); - Marshal.WriteByte(destPtr + 1, r[1]); - Marshal.WriteByte(destPtr + 2, r[2]); - Marshal.WriteByte(destPtr + 3, r[3]); - - Marshal.WriteByte(destPtr + 4, 0); - Marshal.WriteByte(destPtr + 5, 0); - Marshal.WriteByte(destPtr + 6, 0); - Marshal.WriteByte(destPtr + 7, 0); - - Marshal.WriteByte(destPtr + 8, 0); - Marshal.WriteByte(destPtr + 9, 0); - Marshal.WriteByte(destPtr + 10, 0); - Marshal.WriteByte(destPtr + 11, 0); - - Marshal.WriteByte(destPtr + 12, 0); - Marshal.WriteByte(destPtr + 13, 0); - Marshal.WriteByte(destPtr + 14, 0x80); - Marshal.WriteByte(destPtr + 15, 0x3F); - - } - } - - public struct RG32F : IRawData - { - public float RFloat - { - get - { - return BitConverter.ToSingle(BitConverter.GetBytes(m_R)); - } - } - private uint m_R; - - public float GFloat - { - get - { - return BitConverter.ToSingle(BitConverter.GetBytes(m_G)); - } - } - private uint m_G; - - public void WriteTo(IntPtr destPtr) - { - byte[] r = BitConverter.GetBytes(m_R); - Marshal.WriteByte(destPtr + 0, r[0]); - Marshal.WriteByte(destPtr + 1, r[1]); - Marshal.WriteByte(destPtr + 2, r[2]); - Marshal.WriteByte(destPtr + 3, r[3]); - - byte[] g = BitConverter.GetBytes(m_G); - Marshal.WriteByte(destPtr + 4, g[0]); - Marshal.WriteByte(destPtr + 5, g[1]); - Marshal.WriteByte(destPtr + 6, g[2]); - Marshal.WriteByte(destPtr + 7, g[3]); - - Marshal.WriteByte(destPtr + 8, 0); - Marshal.WriteByte(destPtr + 9, 0); - Marshal.WriteByte(destPtr + 10, 0); - Marshal.WriteByte(destPtr + 11, 0); - - Marshal.WriteByte(destPtr + 12, 0); - Marshal.WriteByte(destPtr + 13, 0); - Marshal.WriteByte(destPtr + 14, 0x80); - Marshal.WriteByte(destPtr + 15, 0x3F); - } - } - - public struct RGB32F : IRawData - { - public float RFloat - { - get - { - return BitConverter.ToSingle(BitConverter.GetBytes(m_R)); - } - } - private uint m_R; - - public float GFloat - { - get - { - return BitConverter.ToSingle(BitConverter.GetBytes(m_G)); - } - } - private uint m_G; - - public float BFloat - { - get - { - return BitConverter.ToSingle(BitConverter.GetBytes(m_B)); - } - } - private uint m_B; - - public void WriteTo(IntPtr destPtr) - { - byte[] r = BitConverter.GetBytes(m_R); - Marshal.WriteByte(destPtr + 0, r[0]); - Marshal.WriteByte(destPtr + 1, r[1]); - Marshal.WriteByte(destPtr + 2, r[2]); - Marshal.WriteByte(destPtr + 3, r[3]); - - byte[] g = BitConverter.GetBytes(m_G); - Marshal.WriteByte(destPtr + 4, g[0]); - Marshal.WriteByte(destPtr + 5, g[1]); - Marshal.WriteByte(destPtr + 6, g[2]); - Marshal.WriteByte(destPtr + 7, g[3]); - - byte[] b = BitConverter.GetBytes(m_B); - Marshal.WriteByte(destPtr + 8, b[0]); - Marshal.WriteByte(destPtr + 9, b[1]); - Marshal.WriteByte(destPtr + 10, b[2]); - Marshal.WriteByte(destPtr + 11, b[3]); - - Marshal.WriteByte(destPtr + 12, 0); - Marshal.WriteByte(destPtr + 13, 0); - Marshal.WriteByte(destPtr + 14, 0x80); - Marshal.WriteByte(destPtr + 15, 0x3F); - } - } - - public struct RGBA32F : IRawData - { - public float RFloat - { - get - { - return BitConverter.ToSingle(BitConverter.GetBytes(m_R)); - } - } - private uint m_R; - - public float GFloat - { - get - { - return BitConverter.ToSingle(BitConverter.GetBytes(m_G)); - } - } - private uint m_G; - - public float BFloat - { - get - { - return BitConverter.ToSingle(BitConverter.GetBytes(m_B)); - } - } - private uint m_B; - - public float AFloat - { - get - { - return BitConverter.ToSingle(BitConverter.GetBytes(m_A)); - } - } - private uint m_A; - - public void WriteTo(IntPtr destPtr) - { - byte[] r = BitConverter.GetBytes(m_R); - Marshal.WriteByte(destPtr + 0, r[0]); - Marshal.WriteByte(destPtr + 1, r[1]); - Marshal.WriteByte(destPtr + 2, r[2]); - Marshal.WriteByte(destPtr + 3, r[3]); - - byte[] g = BitConverter.GetBytes(m_G); - Marshal.WriteByte(destPtr + 4, g[0]); - Marshal.WriteByte(destPtr + 5, g[1]); - Marshal.WriteByte(destPtr + 6, g[2]); - Marshal.WriteByte(destPtr + 7, g[3]); - - byte[] b = BitConverter.GetBytes(m_B); - Marshal.WriteByte(destPtr + 8, b[0]); - Marshal.WriteByte(destPtr + 9, b[1]); - Marshal.WriteByte(destPtr + 10, b[2]); - Marshal.WriteByte(destPtr + 11, b[3]); - - byte[] a = BitConverter.GetBytes(m_A); - Marshal.WriteByte(destPtr + 12, a[0]); - Marshal.WriteByte(destPtr + 13, a[1]); - Marshal.WriteByte(destPtr + 14, a[2]); - Marshal.WriteByte(destPtr + 15, a[3]); - - } - } -} diff --git a/Assets/ASTC Encoder/Runtime/Resources.meta b/Assets/ASTC Encoder/Runtime/Resources.meta new file mode 100644 index 0000000..3398677 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Resources.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 0a28624339bdfaabeb2585399f59dc65 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/Resources/AstcGpuEncoder.compute b/Assets/ASTC Encoder/Runtime/Resources/AstcGpuEncoder.compute new file mode 100644 index 0000000..832c7b4 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Resources/AstcGpuEncoder.compute @@ -0,0 +1,109 @@ +#pragma editor_sync_compilation + +#pragma kernel EncodeTex4x4 ASTC_BLOCK_4X4 +#pragma kernel EncodeTex5x5 ASTC_BLOCK_5X5 +#pragma kernel EncodeTex6x6 ASTC_BLOCK_6X6 +#pragma kernel EncodeTex8x8 ASTC_BLOCK_8X8 +#pragma kernel EncodeTex10x10 ASTC_BLOCK_10X10 +#pragma kernel EncodeTex12x12 ASTC_BLOCK_12X12 + +#pragma kernel EncodeBuf4x4 ASTC_BLOCK_4X4 +#pragma kernel EncodeBuf5x5 ASTC_BLOCK_5X5 +#pragma kernel EncodeBuf6x6 ASTC_BLOCK_6X6 +#pragma kernel EncodeBuf8x8 ASTC_BLOCK_8X8 +#pragma kernel EncodeBuf10x10 ASTC_BLOCK_10X10 +#pragma kernel EncodeBuf12x12 ASTC_BLOCK_12X12 + +#pragma kernel EncodeTex4x4Fast ASTC_BLOCK_4X4 ASTC_FAST_ONLY +#pragma kernel EncodeTex5x5Fast ASTC_BLOCK_5X5 ASTC_FAST_ONLY +#pragma kernel EncodeTex6x6Fast ASTC_BLOCK_6X6 ASTC_FAST_ONLY +#pragma kernel EncodeTex8x8Fast ASTC_BLOCK_8X8 ASTC_FAST_ONLY +#pragma kernel EncodeTex10x10Fast ASTC_BLOCK_10X10 ASTC_FAST_ONLY +#pragma kernel EncodeTex12x12Fast ASTC_BLOCK_12X12 ASTC_FAST_ONLY + +#pragma kernel EncodeBuf4x4Fast ASTC_BLOCK_4X4 ASTC_FAST_ONLY +#pragma kernel EncodeBuf5x5Fast ASTC_BLOCK_5X5 ASTC_FAST_ONLY +#pragma kernel EncodeBuf6x6Fast ASTC_BLOCK_6X6 ASTC_FAST_ONLY +#pragma kernel EncodeBuf8x8Fast ASTC_BLOCK_8X8 ASTC_FAST_ONLY +#pragma kernel EncodeBuf10x10Fast ASTC_BLOCK_10X10 ASTC_FAST_ONLY +#pragma kernel EncodeBuf12x12Fast ASTC_BLOCK_12X12 ASTC_FAST_ONLY + +#if defined(ASTC_BLOCK_5X5) + #define BLOCK_X 5 + #define BLOCK_Y 5 +#elif defined(ASTC_BLOCK_6X6) + #define BLOCK_X 6 + #define BLOCK_Y 6 +#elif defined(ASTC_BLOCK_8X8) + #define BLOCK_X 8 + #define BLOCK_Y 8 +#elif defined(ASTC_BLOCK_10X10) + #define BLOCK_X 10 + #define BLOCK_Y 10 +#elif defined(ASTC_BLOCK_12X12) + #define BLOCK_X 12 + #define BLOCK_Y 12 +#else + #define BLOCK_X 4 + #define BLOCK_Y 4 +#endif + +Texture2D _AstcSourceTex; +RWTexture2D _AstcDestTex; +RWStructuredBuffer _AstcDestBuffer; + +uint _AstcSrcWidth; +uint _AstcSrcHeight; +uint _AstcMipLevel; +uint _AstcBlockCountX; +uint _AstcBlockCountY; +uint _AstcBufferBlockOffset; +uint _AstcMode; +uint _AstcIsSRGB; +uint _AstcUseAlphaWeight; +uint _AstcQuality; + +#include "../Gpu/Shaders/AstcGpuCore.hlsl" + +void DispatchToTexture(uint3 id) +{ + if (id.x >= _AstcBlockCountX || id.y >= _AstcBlockCountY) + return; + _AstcDestTex[id.xy] = AstcEncodeBlock(id.x, id.y); +} + +void DispatchToBuffer(uint3 id) +{ + if (id.x >= _AstcBlockCountX || id.y >= _AstcBlockCountY) + return; + uint outIdx = _AstcBufferBlockOffset + id.y * _AstcBlockCountX + id.x; + _AstcDestBuffer[outIdx] = AstcEncodeBlock(id.x, id.y); +} + +[numthreads(8, 8, 1)] void EncodeTex4x4(uint3 id : SV_DispatchThreadID) { DispatchToTexture(id); } +[numthreads(8, 8, 1)] void EncodeTex5x5(uint3 id : SV_DispatchThreadID) { DispatchToTexture(id); } +[numthreads(8, 8, 1)] void EncodeTex6x6(uint3 id : SV_DispatchThreadID) { DispatchToTexture(id); } +[numthreads(8, 4, 1)] void EncodeTex8x8(uint3 id : SV_DispatchThreadID) { DispatchToTexture(id); } +[numthreads(8, 4, 1)] void EncodeTex10x10(uint3 id : SV_DispatchThreadID) { DispatchToTexture(id); } +[numthreads(8, 4, 1)] void EncodeTex12x12(uint3 id : SV_DispatchThreadID) { DispatchToTexture(id); } + +[numthreads(8, 8, 1)] void EncodeBuf4x4(uint3 id : SV_DispatchThreadID) { DispatchToBuffer(id); } +[numthreads(8, 8, 1)] void EncodeBuf5x5(uint3 id : SV_DispatchThreadID) { DispatchToBuffer(id); } +[numthreads(8, 8, 1)] void EncodeBuf6x6(uint3 id : SV_DispatchThreadID) { DispatchToBuffer(id); } +[numthreads(8, 4, 1)] void EncodeBuf8x8(uint3 id : SV_DispatchThreadID) { DispatchToBuffer(id); } +[numthreads(8, 4, 1)] void EncodeBuf10x10(uint3 id : SV_DispatchThreadID) { DispatchToBuffer(id); } +[numthreads(8, 4, 1)] void EncodeBuf12x12(uint3 id : SV_DispatchThreadID) { DispatchToBuffer(id); } + +[numthreads(8, 8, 1)] void EncodeTex4x4Fast(uint3 id : SV_DispatchThreadID) { DispatchToTexture(id); } +[numthreads(8, 8, 1)] void EncodeTex5x5Fast(uint3 id : SV_DispatchThreadID) { DispatchToTexture(id); } +[numthreads(8, 8, 1)] void EncodeTex6x6Fast(uint3 id : SV_DispatchThreadID) { DispatchToTexture(id); } +[numthreads(8, 4, 1)] void EncodeTex8x8Fast(uint3 id : SV_DispatchThreadID) { DispatchToTexture(id); } +[numthreads(8, 4, 1)] void EncodeTex10x10Fast(uint3 id : SV_DispatchThreadID) { DispatchToTexture(id); } +[numthreads(8, 4, 1)] void EncodeTex12x12Fast(uint3 id : SV_DispatchThreadID) { DispatchToTexture(id); } + +[numthreads(8, 8, 1)] void EncodeBuf4x4Fast(uint3 id : SV_DispatchThreadID) { DispatchToBuffer(id); } +[numthreads(8, 8, 1)] void EncodeBuf5x5Fast(uint3 id : SV_DispatchThreadID) { DispatchToBuffer(id); } +[numthreads(8, 8, 1)] void EncodeBuf6x6Fast(uint3 id : SV_DispatchThreadID) { DispatchToBuffer(id); } +[numthreads(8, 4, 1)] void EncodeBuf8x8Fast(uint3 id : SV_DispatchThreadID) { DispatchToBuffer(id); } +[numthreads(8, 4, 1)] void EncodeBuf10x10Fast(uint3 id : SV_DispatchThreadID) { DispatchToBuffer(id); } +[numthreads(8, 4, 1)] void EncodeBuf12x12Fast(uint3 id : SV_DispatchThreadID) { DispatchToBuffer(id); } diff --git a/Assets/ASTC Encoder/Runtime/Resources/AstcGpuEncoder.compute.meta b/Assets/ASTC Encoder/Runtime/Resources/AstcGpuEncoder.compute.meta new file mode 100644 index 0000000..3484763 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Resources/AstcGpuEncoder.compute.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 5b4a4d38cbb10f5b64370264638c4454 +ComputeShaderImporter: + externalObjects: {} + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Runtime/Resources/AstcGpuMipGenerator.compute b/Assets/ASTC Encoder/Runtime/Resources/AstcGpuMipGenerator.compute new file mode 100644 index 0000000..737cd94 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Resources/AstcGpuMipGenerator.compute @@ -0,0 +1,117 @@ +#pragma editor_sync_compilation + +#pragma kernel DownsampleColor +#pragma kernel DownsampleNormal + +Texture2D _MipSrcTex; +RWTexture2D _MipDstTex; + +uint _MipSrcWidth; +uint _MipSrcHeight; +uint _MipDstWidth; +uint _MipDstHeight; +uint _MipSrcLevel; +uint _MipIsSRGBSrc; +uint _MipIsAlphaWeighted; +uint _MipIsHdr; + +float MipLinearToSRGBScalar(float c) +{ + c = saturate(c); + return (c <= 0.0031308) ? (c * 12.92) : (1.055 * pow(c, 1.0 / 2.4) - 0.055); +} + +float4 SanitizeHdr(float4 v) +{ + return float4( + (v.r > 0.0) ? min(v.r, 65504.0) : 0.0, + (v.g > 0.0) ? min(v.g, 65504.0) : 0.0, + (v.b > 0.0) ? min(v.b, 65504.0) : 0.0, + (v.a > 0.0) ? min(v.a, 65504.0) : 0.0); +} + +[numthreads(8, 8, 1)] +void DownsampleColor(uint3 id : SV_DispatchThreadID) +{ + if (id.x >= _MipDstWidth || id.y >= _MipDstHeight) + return; + + uint sx0 = id.x * 2u; + uint sy0 = id.y * 2u; + uint sxEnd = (id.x + 1u == _MipDstWidth) ? (_MipSrcWidth - 1u) : min(sx0 + 1u, _MipSrcWidth - 1u); + uint syEnd = (id.y + 1u == _MipDstHeight) ? (_MipSrcHeight - 1u) : min(sy0 + 1u, _MipSrcHeight - 1u); + + float4 sumColor = 0.0; + float3 sumWeightedRgb = 0.0; + float sumAlphaW = 0.0; + float tapCount = 0.0; + + for (uint sy = sy0; sy <= syEnd; ++sy) + { + for (uint sx = sx0; sx <= sxEnd; ++sx) + { + float4 c = _MipSrcTex.Load(int3(sx, sy, _MipSrcLevel)); + if (_MipIsHdr != 0u) + c = SanitizeHdr(c); + + sumColor += c; + if (_MipIsAlphaWeighted != 0u && _MipIsHdr == 0u) + { + float w = saturate(c.a); + sumWeightedRgb += c.rgb * w; + sumAlphaW += w; + } + tapCount += 1.0; + } + } + + float invCount = 1.0 / max(tapCount, 1.0); + float4 result; + if (_MipIsAlphaWeighted != 0u && _MipIsHdr == 0u) + { + // Premultiplied alpha-weighted box filter prevents dark fringe bleed on transparent borders. + float3 rgb = (sumAlphaW > 1e-5) ? (sumWeightedRgb / sumAlphaW) : (sumColor.rgb * invCount); + result = float4(rgb, sumAlphaW * invCount); + } + else + { + result = sumColor * invCount; + } + + _MipDstTex[id.xy] = result; +} + +float3 UnpackTangentNormal(float4 raw) +{ + float nx = (_MipIsSRGBSrc != 0u) ? MipLinearToSRGBScalar(raw.r) : saturate(raw.r); + float ny = (_MipIsSRGBSrc != 0u) ? MipLinearToSRGBScalar(raw.g) : saturate(raw.g); + float2 xy = float2(nx, ny) * 2.0 - 1.0; + float z = sqrt(saturate(1.0 - dot(xy, xy))); + return float3(xy, z); +} + +[numthreads(8, 8, 1)] +void DownsampleNormal(uint3 id : SV_DispatchThreadID) +{ + if (id.x >= _MipDstWidth || id.y >= _MipDstHeight) + return; + + uint sx0 = id.x * 2u; + uint sy0 = id.y * 2u; + uint sxEnd = (id.x + 1u == _MipDstWidth) ? (_MipSrcWidth - 1u) : min(sx0 + 1u, _MipSrcWidth - 1u); + uint syEnd = (id.y + 1u == _MipDstHeight) ? (_MipSrcHeight - 1u) : min(sy0 + 1u, _MipSrcHeight - 1u); + + float3 n = 0.0; + for (uint sy = sy0; sy <= syEnd; ++sy) + { + for (uint sx = sx0; sx <= sxEnd; ++sx) + { + n += UnpackTangentNormal(_MipSrcTex.Load(int3(sx, sy, _MipSrcLevel))); + } + } + + float len = length(n); + n = (len > 1e-5) ? (n / len) : float3(0.0, 0.0, 1.0); + float2 enc = saturate(n.xy * 0.5 + 0.5); + _MipDstTex[id.xy] = float4(enc.x, enc.y, 1.0, 1.0); +} diff --git a/Assets/ASTC Encoder/Runtime/Resources/AstcGpuMipGenerator.compute.meta b/Assets/ASTC Encoder/Runtime/Resources/AstcGpuMipGenerator.compute.meta new file mode 100644 index 0000000..778e745 --- /dev/null +++ b/Assets/ASTC Encoder/Runtime/Resources/AstcGpuMipGenerator.compute.meta @@ -0,0 +1,9 @@ +fileFormatVersion: 2 +guid: c1a7e4b28d934f56a0e1b3c5d7f92841 +ComputeShaderImporter: + externalObjects: {} + currentAPIMask: 0 + preprocessorOverride: 0 + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Samples~/BasicUsage/RuntimeAstcSample.cs b/Assets/ASTC Encoder/Samples~/BasicUsage/RuntimeAstcSample.cs new file mode 100644 index 0000000..b693a2c --- /dev/null +++ b/Assets/ASTC Encoder/Samples~/BasicUsage/RuntimeAstcSample.cs @@ -0,0 +1,88 @@ +using System.IO; +using System.Threading.Tasks; +using Aperture.Astcenc.Runtime; +using UnityEngine; + +namespace Aperture.Astcenc.Samples +{ + /// + /// Basic runtime ASTC compression sample demonstrating Auto/GPU/CPU backends, + /// async encoding, GPU mipmap generation, and persistent KTX v1 disk caching. + /// + public class RuntimeAstcSample : MonoBehaviour + { + [Header("Input")] + [Tooltip("Input texture. CPU backend requires Read/Write enabled; GPU backend also accepts non-readable textures.")] + public Texture2D inputTexture; + + [Header("Compression Settings")] + public TextureType textureType = TextureType.Default; + public BlockSize blockSize = BlockSize.ASTC_6x6; + public CompressQuality quality = CompressQuality.Fast; + public EncodeBackend backend = EncodeBackend.Auto; + public bool generateMipmaps = true; + public bool useAsync = true; + public bool useKtxDiskCache = false; + + [Header("Output (Runtime Preview)")] + public Texture2D outputTexture; + + private bool m_OwnsOutputTexture; + + private async void Start() + { + if (inputTexture == null) + { + Debug.LogWarning("[RuntimeAstcSample] Assign an inputTexture in the Inspector to run the sample."); + return; + } + + if (!Encoder.IsSupport(inputTexture, backend)) + { + Debug.LogWarning($"[RuntimeAstcSample] Input texture '{inputTexture.name}' is not supported by backend {backend}."); + return; + } + + var options = AstcCompressOptions.Default; + options.TextureType = textureType; + options.BlockSize = blockSize; + options.Quality = quality; + options.Backend = backend; + options.IncludeMipmaps = generateMipmaps || inputTexture.mipmapCount > 1; + options.GenerateMipmaps = generateMipmaps; + + if (useKtxDiskCache) + { + string cachePath = Path.Combine(Application.persistentDataPath, $"{inputTexture.name}_{blockSize}.ktx"); + outputTexture = await AstcDiskCache.LoadOrCompressAsync( + cachePath, + () => Task.FromResult(inputTexture), + options); + } + else if (useAsync) + { + outputTexture = await inputTexture.CompressToTextureAsync(options); + } + else + { + outputTexture = inputTexture.CompressToTexture(options); + } + + m_OwnsOutputTexture = outputTexture != null; + if (outputTexture != null) + { + Debug.Log($"[RuntimeAstcSample] Compressed '{inputTexture.name}' -> {outputTexture.width}x{outputTexture.height}, format={outputTexture.graphicsFormat}, mips={outputTexture.mipmapCount}"); + } + } + + private void OnDestroy() + { + if (m_OwnsOutputTexture && outputTexture != null) + { + Destroy(outputTexture); + outputTexture = null; + m_OwnsOutputTexture = false; + } + } + } +} diff --git a/Assets/ASTC Encoder/Tests.meta b/Assets/ASTC Encoder/Tests.meta new file mode 100644 index 0000000..d71e07c --- /dev/null +++ b/Assets/ASTC Encoder/Tests.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 1e6b4a9c3d724f85a20c8e51b93d64f7 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Tests/Editor.meta b/Assets/ASTC Encoder/Tests/Editor.meta new file mode 100644 index 0000000..e5f39ae --- /dev/null +++ b/Assets/ASTC Encoder/Tests/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 6d3f8c2a5e194b749a02d7e8c41b53f2 +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Tests/Editor/Aperture.Astcenc.Tests.asmdef b/Assets/ASTC Encoder/Tests/Editor/Aperture.Astcenc.Tests.asmdef new file mode 100644 index 0000000..75dbcff --- /dev/null +++ b/Assets/ASTC Encoder/Tests/Editor/Aperture.Astcenc.Tests.asmdef @@ -0,0 +1,23 @@ +{ + "name": "Aperture.Astcenc.Tests", + "rootNamespace": "Aperture.Astcenc.Tests", + "references": [ + "Aperture.Astcenc.Runtime", + "Aperture.Astcenc.Editor" + ], + "includePlatforms": [ + "Editor" + ], + "excludePlatforms": [], + "allowUnsafeCode": false, + "overrideReferences": true, + "precompiledReferences": [ + "nunit.framework.dll" + ], + "autoReferenced": false, + "defineConstraints": [ + "UNITY_INCLUDE_TESTS" + ], + "versionDefines": [], + "noEngineReferences": false +} diff --git a/Assets/ASTC Encoder/Tests/Editor/Aperture.Astcenc.Tests.asmdef.meta b/Assets/ASTC Encoder/Tests/Editor/Aperture.Astcenc.Tests.asmdef.meta new file mode 100644 index 0000000..7234f63 --- /dev/null +++ b/Assets/ASTC Encoder/Tests/Editor/Aperture.Astcenc.Tests.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 8c5a1e7d2f9446b3a109e3d7c58f24a6 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Tests/Editor/AstcEncoderTests.cs b/Assets/ASTC Encoder/Tests/Editor/AstcEncoderTests.cs new file mode 100644 index 0000000..28aeabd --- /dev/null +++ b/Assets/ASTC Encoder/Tests/Editor/AstcEncoderTests.cs @@ -0,0 +1,345 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +using System.Threading.Tasks; +using Aperture.Astcenc.Runtime; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.Experimental.Rendering; + +namespace Aperture.Astcenc.Tests +{ + /// + /// Golden EditMode verification suite covering header/KTX containers, disk caching, + /// raw pixel encoding, queue scheduling, and CPU/GPU cross-decode PSNR & normal-map accuracy. + /// + public class AstcEncoderTests + { + private static readonly BlockSize[] s_AllBlockSizes = + { + BlockSize.ASTC_4x4, + BlockSize.ASTC_5x5, + BlockSize.ASTC_6x6, + BlockSize.ASTC_8x8, + BlockSize.ASTC_10x10, + BlockSize.ASTC_12x12 + }; + + [Test] + public void AstcHeader_RoundTrip_AllBlockSizes_AndRejectsInvalid() + { + byte[] buf = new byte[AstcHeader.HeaderSize]; + uint[] dims = { 4u, 5u, 6u, 8u, 10u, 12u }; + for (int i = 0; i < dims.Length; i++) + { + AstcHeader.WriteTo(buf, 0, dims[i], dims[i], 1u, 137, 211, 1); + Assert.IsTrue(AstcHeader.TryParse(buf, 0, out uint bx, out uint by, out uint bz, out int w, out int h, out int d)); + Assert.AreEqual(dims[i], bx); + Assert.AreEqual(dims[i], by); + Assert.AreEqual(1u, bz); + Assert.AreEqual(137, w); + Assert.AreEqual(211, h); + Assert.AreEqual(1, d); + Assert.IsTrue(AstcHeader.TryMapBlockSize(bx, by, bz, out BlockSize mapped)); + Assert.AreEqual(s_AllBlockSizes[i], mapped); + } + + // Corrupt magic must fail + buf[0] = 0x00; + Assert.IsFalse(AstcHeader.TryParse(buf, 0, out _, out _, out _, out _, out _, out _)); + Assert.IsFalse(AstcHeader.TryParse(new byte[8], 0, out _, out _, out _, out _, out _, out _)); + } + + [Test] + public void KtxContainer_RoundTrip_LdrSrgbHdr_FullMipChain() + { + GraphicsFormat[] formats = + { + GraphicsFormat.RGBA_ASTC4X4_UNorm, + GraphicsFormat.RGBA_ASTC6X6_SRGB, + GraphicsFormat.RGBA_ASTC8X8_UFloat + }; + int[] blockDims = { 4, 6, 8 }; + + for (int f = 0; f < formats.Length; f++) + { + int width = 64; + int height = 64; + int mipCount = 7; + int b = blockDims[f]; + int totalBytes = 0; + for (int m = 0; m < mipCount; m++) + { + int mw = Math.Max(1, width >> m); + int mh = Math.Max(1, height >> m); + totalBytes += ((mw + b - 1) / b) * ((mh + b - 1) / b) * 16; + } + + byte[] payload = new byte[totalBytes]; + for (int i = 0; i < payload.Length; i++) + payload[i] = (byte)((i * 31 + f * 17) & 0xFF); + + IntPtr ptr = Marshal.AllocHGlobal(totalBytes); + Marshal.Copy(payload, 0, ptr, totalBytes); + using var raw = new AstcRaw(ptr, totalBytes); + + byte[] ktx = AstcKtxContainer.Encode(raw, width, height, mipCount, formats[f]); + Assert.IsNotNull(ktx); + Assert.IsTrue(AstcKtxContainer.TryDecode(ktx, out KtxAstcData decoded)); + Assert.AreEqual(width, decoded.Width); + Assert.AreEqual(height, decoded.Height); + Assert.AreEqual(mipCount, decoded.MipCount); + Assert.AreEqual(formats[f], decoded.GraphicsFormat); + Assert.AreEqual(payload.Length, decoded.RawAstcPayload.Length); + CollectionAssert.AreEqual(payload, decoded.RawAstcPayload); + } + } + + [Test] + public void KtxContainer_RejectsMalformedAndOverflowHeaders() + { + // Craft a 64-byte KTX header with huge mipLevels / dimensions to ensure TryDecode returns false cleanly without OOM or overflow. + byte[] evil = new byte[64]; + byte[] magic = { 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A }; + Buffer.BlockCopy(magic, 0, evil, 0, magic.Length); + BitConverter.GetBytes(0x04030201u).CopyTo(evil, 12); // endianness + BitConverter.GetBytes(0x93B0u).CopyTo(evil, 28); // GL_COMPRESSED_RGBA_ASTC_4x4_KHR + BitConverter.GetBytes(0x40000000u).CopyTo(evil, 36); // absurd width + BitConverter.GetBytes(0x40000000u).CopyTo(evil, 40); // absurd height + BitConverter.GetBytes(1u).CopyTo(evil, 52); // faces + BitConverter.GetBytes(0x7FFFFFFFu).CopyTo(evil, 56); // absurd mipLevels + Assert.IsFalse(AstcKtxContainer.TryDecode(evil, out _)); + + // Valid dimensions but absurd mipLevels + BitConverter.GetBytes(64u).CopyTo(evil, 36); + BitConverter.GetBytes(64u).CopyTo(evil, 40); + Assert.IsFalse(AstcKtxContainer.TryDecode(evil, out _)); + + // Valid dimensions & mipLevels = 1, but truncated payload + BitConverter.GetBytes(1u).CopyTo(evil, 56); + Assert.IsFalse(AstcKtxContainer.TryDecode(evil, out _)); + } + + [Test] + public void CompressRawPixels_CpuCrossDecode_MeetsQualityTarget() + { + if (!Encoder.IsCpuSupported) + Assert.Ignore("Native CPU astcenc library is not available on this host."); + + const int width = 64; + const int height = 64; + byte[] pixels = CreateGradientRgba8(width, height); + + var options = AstcCompressOptions.Default; + options.Backend = EncodeBackend.Cpu; + options.BlockSize = BlockSize.ASTC_6x6; + options.Quality = CompressQuality.Medium; + + using AstcRaw raw = Encoder.CompressRawPixels(pixels, width, height, GraphicsFormat.R8G8B8A8_UNorm, options); + Assert.IsNotNull(raw); + Assert.Greater(raw.Length, 0); + + byte[] decoded = Encoder.Decompress(raw, width, height, options.BlockSize, srgb: false, isHdr: false, outputBitness: 8); + Assert.IsNotNull(decoded); + Assert.AreEqual(pixels.Length, decoded.Length); + + double psnr = ComputeRgba8Psnr(pixels, decoded); + Assert.Greater(psnr, 32.0, $"Expected CPU ASTC 6x6 gradient PSNR > 32 dB, got {psnr:F2} dB"); + } + + [Test] + public void GpuCrossDecode_AllBlockSizes_AndNpot_ValidAstcBlocks() + { + if (!Encoder.IsGpuSupported || !Encoder.IsCpuSupported) + Assert.Ignore("Both GPU compute and CPU astcenc decoder are required for cross-decode test."); + + int[] sizes = { 64, 53 }; + foreach (int dim in sizes) + { + Texture2D src = CreateTestTexture(dim, dim, normalMap: false); + byte[] refBytes = CreateGradientRgba8(dim, dim); + try + { + foreach (BlockSize bs in s_AllBlockSizes) + { + var options = AstcCompressOptions.Default; + options.Backend = EncodeBackend.Gpu; + options.BlockSize = bs; + options.Quality = CompressQuality.Medium; + options.IncludeMipmaps = false; + + using AstcRaw raw = src.CompressTexture(options); + Assert.IsNotNull(raw, $"GPU compress returned null for {dim}x{dim} {bs}"); + + byte[] decoded = Encoder.Decompress(raw, dim, dim, bs, srgb: false, isHdr: false, outputBitness: 8); + Assert.IsNotNull(decoded, $"CPU cross-decode returned null for {dim}x{dim} {bs}"); + + double psnr = ComputeRgba8Psnr(refBytes, decoded); + Assert.Greater(psnr, 24.0, $"GPU cross-decode PSNR too low for {dim}x{dim} {bs}: {psnr:F2} dB"); + } + } + finally + { + UnityEngine.Object.DestroyImmediate(src); + } + } + } + + [Test] + public void GpuCrossDecode_NormalMap_LowAngularError() + { + if (!Encoder.IsGpuSupported || !Encoder.IsCpuSupported) + Assert.Ignore("Both GPU compute and CPU astcenc decoder are required for normal-map cross-decode test."); + + const int size = 64; + Texture2D normalTex = CreateTestTexture(size, size, normalMap: true); + Color[] refPixels = normalTex.GetPixels(0); + try + { + var options = AstcCompressOptions.NormalMap; + options.Backend = EncodeBackend.Gpu; + options.BlockSize = BlockSize.ASTC_6x6; + options.Quality = CompressQuality.Medium; + options.IncludeMipmaps = false; + + using AstcRaw raw = normalTex.CompressTexture(options); + Assert.IsNotNull(raw); + + byte[] decoded = Encoder.Decompress(raw, size, size, options.BlockSize, srgb: false, isHdr: false, outputBitness: 8); + Assert.IsNotNull(decoded); + + double meanDeg = ComputeMeanNormalAngularErrorDeg(refPixels, decoded); + Assert.Less(meanDeg, 3.0, $"Expected normal map mean angular error < 3.0°, got {meanDeg:F2}°"); + } + finally + { + UnityEngine.Object.DestroyImmediate(normalTex); + } + } + + [Test] + public void AstcContext_ParentTableSharing_Succeeds() + { + if (!Encoder.IsCpuSupported) + Assert.Ignore("Native CPU astcenc library is not available on this host."); + + using AstcContext parent = AstcContext.Create(GraphicsFormat.R8G8B8A8_UNorm, TextureType.Default, BlockSize.ASTC_6x6, CompressQuality.Fast, threadCount: 1); + Assert.IsNotNull(parent); + + using AstcContext child = AstcContext.Create(GraphicsFormat.R8G8B8A8_UNorm, TextureType.Default, BlockSize.ASTC_6x6, CompressQuality.Fast, threadCount: 1, parentContext: parent); + Assert.IsNotNull(child); + + Texture2D src = CreateTestTexture(32, 32, normalMap: false); + try + { + using AstcRaw raw = child.CompressTexture(src); + Assert.IsNotNull(raw); + Assert.Greater(raw.Length, 0); + } + finally + { + UnityEngine.Object.DestroyImmediate(src); + } + } + + [Test] + public void CompressionQueue_Cancellation_CancelsPendingTask() + { + using var queue = new AstcCompressionQueue(); + using var cts = new CancellationTokenSource(); + Texture2D src = CreateTestTexture(16, 16, normalMap: false); + try + { + Task task = queue.EnqueueToRaw(src, AstcCompressOptions.Default, AstcTaskPriority.Low, cts.Token); + cts.Cancel(); + queue.ProcessFrame(); + Assert.IsTrue(task.IsCanceled); + } + finally + { + UnityEngine.Object.DestroyImmediate(src); + } + } + + private static byte[] CreateGradientRgba8(int width, int height) + { + byte[] data = new byte[width * height * 4]; + for (int y = 0; y < height; y++) + { + for (int x = 0; x < width; x++) + { + int o = (y * width + x) * 4; + data[o + 0] = (byte)(x * 255 / Math.Max(1, width - 1)); + data[o + 1] = (byte)(y * 255 / Math.Max(1, height - 1)); + data[o + 2] = (byte)(((x + y) * 127) / Math.Max(1, width + height - 2)); + data[o + 3] = 255; + } + } + return data; + } + + private static Texture2D CreateTestTexture(int width, int height, bool normalMap) + { + var tex = new Texture2D(width, height, GraphicsFormat.R8G8B8A8_UNorm, TextureCreationFlags.None); + var colors = new Color[width * height]; + for (int y = 0; y < height; y++) + { + for (int x = 0; x < width; x++) + { + float u = width > 1 ? (float)x / (width - 1) : 0f; + float v = height > 1 ? (float)y / (height - 1) : 0f; + if (normalMap) + { + float nx = (u - 0.5f) * 1.2f; + float ny = (v - 0.5f) * 1.2f; + float nz = Mathf.Sqrt(Mathf.Max(0.01f, 1f - nx * nx - ny * ny)); + Vector3 n = new Vector3(nx, ny, nz).normalized; + colors[y * width + x] = new Color(n.x * 0.5f + 0.5f, n.y * 0.5f + 0.5f, n.z * 0.5f + 0.5f, 1f); + } + else + { + colors[y * width + x] = new Color(u, v, (u + v) * 0.5f, 1f); + } + } + } + tex.SetPixels(colors); + tex.Apply(false, false); + return tex; + } + + private static double ComputeRgba8Psnr(byte[] a, byte[] b) + { + double sq = 0.0; + int n = Math.Min(a.Length, b.Length); + for (int i = 0; i < n; i++) + { + double d = a[i] - b[i]; + sq += d * d; + } + double mse = n > 0 ? sq / n : 0.0; + return mse > 1e-12 ? 10.0 * Math.Log10((255.0 * 255.0) / mse) : 99.99; + } + + private static double ComputeMeanNormalAngularErrorDeg(Color[] refPixels, byte[] decodedRgba8) + { + double degSum = 0.0; + int count = refPixels.Length; + for (int i = 0; i < count; i++) + { + float ax = refPixels[i].r * 2f - 1f; + float ay = refPixels[i].g * 2f - 1f; + float az = Mathf.Sqrt(Mathf.Max(0f, 1f - ax * ax - ay * ay)); + + // ASTC Normal map stores GGGR (R/G/B = ny, A = nx) + float bx = (decodedRgba8[i * 4 + 3] / 255f) * 2f - 1f; + float by = (decodedRgba8[i * 4 + 1] / 255f) * 2f - 1f; + float bz = Mathf.Sqrt(Mathf.Max(0f, 1f - bx * bx - by * by)); + + float dot = Mathf.Clamp(ax * bx + ay * by + az * bz, -1f, 1f); + degSum += Math.Acos(dot) * (180.0 / Math.PI); + } + return count > 0 ? degSum / count : 0.0; + } + } +} diff --git a/Assets/ASTC Encoder/Tests/Editor/AstcEncoderTests.cs.meta b/Assets/ASTC Encoder/Tests/Editor/AstcEncoderTests.cs.meta new file mode 100644 index 0000000..2103dde --- /dev/null +++ b/Assets/ASTC Encoder/Tests/Editor/AstcEncoderTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 2b7e9f4a8c3145d6b028f6e1a94c73d5 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/Tests/Editor/AstcPerformanceBenchmarks.cs b/Assets/ASTC Encoder/Tests/Editor/AstcPerformanceBenchmarks.cs new file mode 100644 index 0000000..eae2a6a --- /dev/null +++ b/Assets/ASTC Encoder/Tests/Editor/AstcPerformanceBenchmarks.cs @@ -0,0 +1,142 @@ +using System.Collections.Generic; +using Aperture.Astcenc.Editor; +using Aperture.Astcenc.Runtime; +using NUnit.Framework; + +namespace Aperture.Astcenc.Tests +{ + /// + /// NUnit EditMode performance benchmark suite for Runtime-ASTC-Encoder-For-Unity. + /// Marked [Explicit] + [Category("Performance")] so regular unit-test runs stay fast. + /// Run from Unity Test Runner (select Performance category) or CLI: + /// Unity -batchmode -runTests -testPlatform EditMode -testCategory Performance -quit + /// + [TestFixture] + [Category("Performance")] + [Explicit("Performance benchmarks — run explicitly or via -testCategory Performance.")] + public class AstcPerformanceBenchmarks + { + private const int k_WarmupRuns = 2; + private const int k_Iterations = 5; + + [Test] + public void Benchmark_Gpu_EncodingMatrix() + { + if (!Encoder.IsGpuSupported) + Assert.Ignore("GPU compute ASTC backend is not supported on this device."); + + AstcBenchmarkReport report = AstcPerformanceBenchmarkRunner.CreateEmptyReport(); + List results = AstcPerformanceBenchmarkRunner.RunGpuEncodingSuite(k_WarmupRuns, k_Iterations); + report.Results.AddRange(results); + + Assert.Greater(results.Count, 0); + foreach (AstcBenchmarkMetrics r in results) + { + Assert.Greater(r.OutputBytes, 0, $"Benchmark {r.Name} produced empty output."); + Assert.Greater(r.MedianMs, 0.0, $"Benchmark {r.Name} recorded non-positive duration."); + } + + TestContext.Out.WriteLine(AstcPerformanceBenchmarkRunner.FormatMarkdownTable(report)); + } + + [Test] + public void Benchmark_Cpu_EncodingMatrix_ColdVsWarm_AndThreading() + { + if (!Encoder.IsCpuSupported) + Assert.Ignore("Native CPU astcenc library is not available on this host."); + + AstcBenchmarkReport report = AstcPerformanceBenchmarkRunner.CreateEmptyReport(); + List results = AstcPerformanceBenchmarkRunner.RunCpuEncodingSuite(1, k_Iterations); + report.Results.AddRange(results); + + Assert.Greater(results.Count, 0); + foreach (AstcBenchmarkMetrics r in results) + { + Assert.Greater(r.OutputBytes, 0, $"Benchmark {r.Name} produced empty output."); + Assert.Greater(r.MedianMs, 0.0, $"Benchmark {r.Name} recorded non-positive duration."); + } + + TestContext.Out.WriteLine(AstcPerformanceBenchmarkRunner.FormatMarkdownTable(report)); + } + + [Test] + public void Benchmark_Cpu_RawPixels_Vs_CompressRawPixelsInto() + { + if (!Encoder.IsCpuSupported) + Assert.Ignore("Native CPU astcenc library is not available on this host."); + + AstcBenchmarkReport report = AstcPerformanceBenchmarkRunner.CreateEmptyReport(); + List results = AstcPerformanceBenchmarkRunner.RunCpuRawPixelsSuite(1, k_Iterations); + report.Results.AddRange(results); + + Assert.AreEqual(2, results.Count); + foreach (AstcBenchmarkMetrics r in results) + { + Assert.Greater(r.OutputBytes, 0, $"Benchmark {r.Name} produced empty output."); + } + + TestContext.Out.WriteLine(AstcPerformanceBenchmarkRunner.FormatMarkdownTable(report)); + } + + [Test] + public void Benchmark_Cpu_Decompression() + { + if (!Encoder.IsCpuSupported) + Assert.Ignore("Native CPU astcenc library is not available on this host."); + + AstcBenchmarkReport report = AstcPerformanceBenchmarkRunner.CreateEmptyReport(); + List results = AstcPerformanceBenchmarkRunner.RunDecompressionSuite(1, k_Iterations); + report.Results.AddRange(results); + + Assert.Greater(results.Count, 0); + foreach (AstcBenchmarkMetrics r in results) + { + Assert.Greater(r.OutputBytes, 0, $"Benchmark {r.Name} produced empty output."); + } + + TestContext.Out.WriteLine(AstcPerformanceBenchmarkRunner.FormatMarkdownTable(report)); + } + + [Test] + public void Benchmark_KtxContainer_And_DiskCache() + { + if (!Encoder.IsGpuSupported && !Encoder.IsCpuSupported) + Assert.Ignore("No ASTC compression backend is available on this host."); + + AstcBenchmarkReport report = AstcPerformanceBenchmarkRunner.CreateEmptyReport(); + List results = AstcPerformanceBenchmarkRunner.RunContainerAndCacheSuite(1, k_Iterations); + report.Results.AddRange(results); + + Assert.Greater(results.Count, 0); + TestContext.Out.WriteLine(AstcPerformanceBenchmarkRunner.FormatMarkdownTable(report)); + } + + [Test] + public void Benchmark_CompressionQueue_Burst() + { + if (!Encoder.IsGpuSupported && !Encoder.IsCpuSupported) + Assert.Ignore("No ASTC compression backend is available on this host."); + + AstcBenchmarkReport report = AstcPerformanceBenchmarkRunner.CreateEmptyReport(); + List results = AstcPerformanceBenchmarkRunner.RunQueueBatchSuite(1, 3); + report.Results.AddRange(results); + + Assert.Greater(results.Count, 0); + TestContext.Out.WriteLine(AstcPerformanceBenchmarkRunner.FormatMarkdownTable(report)); + } + + [Test] + public void Benchmark_FullSuite_ExportReport() + { + AstcBenchmarkReport report = AstcPerformanceBenchmarkRunner.RunFullSuite( + warmup: k_WarmupRuns, + iterations: k_Iterations, + exportReports: true, + out string exportDir); + + Assert.Greater(report.Results.Count, 0); + TestContext.Out.WriteLine($"Exported benchmark reports to: {exportDir}"); + TestContext.Out.WriteLine(AstcPerformanceBenchmarkRunner.FormatMarkdownTable(report)); + } + } +} diff --git a/Assets/ASTC Encoder/Tests/Editor/AstcPerformanceBenchmarks.cs.meta b/Assets/ASTC Encoder/Tests/Editor/AstcPerformanceBenchmarks.cs.meta new file mode 100644 index 0000000..7b179cc --- /dev/null +++ b/Assets/ASTC Encoder/Tests/Editor/AstcPerformanceBenchmarks.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7b3e9d4a6c2148f5b209e6a41c85d312 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/ASTC Encoder/package.json b/Assets/ASTC Encoder/package.json index a26a5b1..226a6cd 100644 --- a/Assets/ASTC Encoder/package.json +++ b/Assets/ASTC Encoder/package.json @@ -1,10 +1,25 @@ { "name": "com.aperture.astcenc", "displayName": "Runtime ASTC Encoder", - "version": "1.0.0", + "version": "2.3.0", "unity": "2021.3", - "keywords": ["Texture", "ASTC", "Runtime", "astcenc"], - "description": "Compress texture to astc format at runtime.", + "keywords": ["Texture", "ASTC", "Runtime", "astcenc", "GPU", "ComputeShader", "KTX"], + "description": "High-performance runtime ASTC texture compression (GPU Compute + native ARM astc-encoder CPU), GPU mipmap generation, KTX v1 disk caching, and Editor benchmarking for Unity.", + "license": "MIT", + "documentationUrl": "https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/blob/master/docs/API.md", + "changelogUrl": "https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/blob/master/Assets/ASTC%20Encoder/CHANGELOG.md", + "licensesUrl": "https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/blob/master/Assets/ASTC%20Encoder/LICENSE.md", + "author": { + "name": "Overflowu", + "url": "https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity" + }, + "samples": [ + { + "displayName": "Basic Usage", + "description": "Runtime ASTC compression sample demonstrating Auto/GPU/CPU backends, async encoding, GPU mipmap generation, and persistent KTX v1 disk caching.", + "path": "Samples~/BasicUsage" + } + ], "dependencies": { } } \ No newline at end of file diff --git a/Assets/Editor.meta b/Assets/Editor.meta new file mode 100644 index 0000000..0dfa4d8 --- /dev/null +++ b/Assets/Editor.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 4c9e2a71d8f34b609e15a3c7f20b8d4e +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Editor/CIBuildScript.cs b/Assets/Editor/CIBuildScript.cs new file mode 100644 index 0000000..45c971b --- /dev/null +++ b/Assets/Editor/CIBuildScript.cs @@ -0,0 +1,320 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using UnityEditor; +using UnityEditor.Build.Reporting; +using UnityEngine; + +namespace Aperture.Astcenc.Editor +{ + /// + /// Command-line and Editor build entry points for multi-platform CI builds (GameCI / batchmode). + /// + public static class CIBuildScript + { + private const string E2EDefineSymbol = "ASTC_CI_E2E"; + + /// + /// Main entry point invoked by GameCI (buildMethod: Aperture.Astcenc.Editor.CIBuildScript.Build) + /// or via Unity -batchmode -quit -executeMethod Aperture.Astcenc.Editor.CIBuildScript.Build. + /// + public static void Build() + { + Dictionary args = ParseCommandLineArgs(); + + string targetName = GetArg(args, "customBuildTarget", GetArg(args, "buildTarget", EditorUserBuildSettings.activeBuildTarget.ToString())); + if (!TryParseBuildTarget(targetName, out BuildTarget buildTarget)) + { + Fail($"Unsupported buildTarget: '{targetName}'."); + return; + } + + string buildName = GetArg(args, "customBuildName", PlayerSettings.productName); + string outputPath = GetArg(args, "customBuildPath", Path.Combine("build", buildTarget.ToString(), buildName)); + string scriptingBackendArg = GetArg(args, "scriptingBackend", string.Empty); + bool enableE2ESmoke = HasFlag(args, "enableE2ESmoke"); + bool isDevelopment = HasFlag(args, "development"); + + ExecuteBuild(buildTarget, outputPath, buildName, scriptingBackendArg, enableE2ESmoke, isDevelopment); + } + + [MenuItem("Build/CI/Android (ARM64 IL2CPP)")] + public static void BuildAndroidLocal() + { + ExecuteBuild(BuildTarget.Android, "build/Android/ASTCEncoder.apk", "ASTCEncoder", "IL2CPP", enableE2ESmoke: false, isDevelopment: false); + } + + [MenuItem("Build/CI/iOS (Xcode Project)")] + public static void BuildiOSLocal() + { + ExecuteBuild(BuildTarget.iOS, "build/iOS", "ASTCEncoder", "IL2CPP", enableE2ESmoke: false, isDevelopment: false); + } + + [MenuItem("Build/CI/Windows x64 (Mono)")] + public static void BuildWindows64Local() + { + ExecuteBuild(BuildTarget.StandaloneWindows64, "build/StandaloneWindows64/ASTCEncoder.exe", "ASTCEncoder", "Mono", enableE2ESmoke: false, isDevelopment: false); + } + + [MenuItem("Build/CI/macOS Universal (Mono)")] + public static void BuildOSXLocal() + { + ExecuteBuild(BuildTarget.StandaloneOSX, "build/StandaloneOSX/ASTCEncoder.app", "ASTCEncoder", "Mono", enableE2ESmoke: false, isDevelopment: false); + } + + [MenuItem("Build/CI/Linux x64 (Mono)")] + public static void BuildLinux64Local() + { + ExecuteBuild(BuildTarget.StandaloneLinux64, "build/StandaloneLinux64/ASTCEncoder.x86_64", "ASTCEncoder", "Mono", enableE2ESmoke: false, isDevelopment: false); + } + + private static void ExecuteBuild( + BuildTarget buildTarget, + string outputPath, + string buildName, + string scriptingBackendArg, + bool enableE2ESmoke, + bool isDevelopment) + { + BuildTargetGroup targetGroup = BuildPipeline.GetBuildTargetGroup(buildTarget); + string[] scenes = EditorBuildSettings.scenes + .Where(s => s.enabled && !string.IsNullOrEmpty(s.path)) + .Select(s => s.path) + .ToArray(); + + if (scenes.Length == 0) + { + Fail("No enabled scenes found in EditorBuildSettings."); + return; + } + + ConfigurePlatformSettings(buildTarget, targetGroup, scriptingBackendArg); + + string originalDefines = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup); + if (enableE2ESmoke) + { + AddDefineSymbol(targetGroup, E2EDefineSymbol); + } + + string locationPath = NormalizeOutputPath(buildTarget, outputPath, buildName); + EnsureParentDirectory(buildTarget, locationPath); + + Debug.Log($"[CIBuildScript] Building target={buildTarget}, group={targetGroup}, backend={PlayerSettings.GetScriptingBackend(targetGroup)}, e2e={enableE2ESmoke}, output='{locationPath}'"); + + BuildPlayerOptions options = new BuildPlayerOptions + { + scenes = scenes, + locationPathName = locationPath, + target = buildTarget, + targetGroup = targetGroup, + options = isDevelopment ? BuildOptions.Development : BuildOptions.None, + }; + + try + { + BuildReport report = BuildPipeline.BuildPlayer(options); + BuildSummary summary = report.summary; + + Debug.Log($"[CIBuildScript] Build finished: result={summary.result}, errors={summary.totalErrors}, warnings={summary.totalWarnings}, size={summary.totalSize} bytes, time={summary.totalTime}"); + + if (summary.result != BuildResult.Succeeded) + { + Fail($"Build failed for {buildTarget} with result {summary.result} ({summary.totalErrors} errors)."); + } + } + finally + { + if (enableE2ESmoke) + { + PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, originalDefines); + } + } + } + + private static void ConfigurePlatformSettings(BuildTarget buildTarget, BuildTargetGroup targetGroup, string scriptingBackendArg) + { + if (string.Equals(scriptingBackendArg, "Mono", StringComparison.OrdinalIgnoreCase)) + { + PlayerSettings.SetScriptingBackend(targetGroup, ScriptingImplementation.Mono2x); + } + else if (string.Equals(scriptingBackendArg, "IL2CPP", StringComparison.OrdinalIgnoreCase)) + { + PlayerSettings.SetScriptingBackend(targetGroup, ScriptingImplementation.IL2CPP); + } + else if (buildTarget == BuildTarget.StandaloneWindows64 || buildTarget == BuildTarget.StandaloneOSX) + { +#if UNITY_EDITOR_LINUX + PlayerSettings.SetScriptingBackend(targetGroup, ScriptingImplementation.Mono2x); +#endif + } + + switch (buildTarget) + { + case BuildTarget.Android: + PlayerSettings.SetScriptingBackend(BuildTargetGroup.Android, ScriptingImplementation.IL2CPP); + PlayerSettings.Android.targetArchitectures = AndroidArchitecture.ARM64; + EditorUserBuildSettings.buildAppBundle = false; + break; + + case BuildTarget.iOS: + PlayerSettings.SetScriptingBackend(BuildTargetGroup.iOS, ScriptingImplementation.IL2CPP); + PlayerSettings.iOS.sdkVersion = iOSSdkVersion.DeviceSDK; + break; + } + } + + private static string NormalizeOutputPath(BuildTarget buildTarget, string outputPath, string buildName) + { + string normalized = outputPath.TrimEnd('/', '\\'); + switch (buildTarget) + { + case BuildTarget.Android: + if (!normalized.EndsWith(".apk", StringComparison.OrdinalIgnoreCase) && + !normalized.EndsWith(".aab", StringComparison.OrdinalIgnoreCase)) + { + normalized = Path.Combine(normalized, buildName + ".apk"); + } + break; + + case BuildTarget.StandaloneWindows64: + if (!normalized.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) + { + normalized = Path.Combine(normalized, buildName + ".exe"); + } + break; + + case BuildTarget.StandaloneOSX: + if (!normalized.EndsWith(".app", StringComparison.OrdinalIgnoreCase)) + { + normalized = Path.Combine(normalized, buildName + ".app"); + } + break; + + case BuildTarget.StandaloneLinux64: + if (Directory.Exists(normalized) || !Path.HasExtension(normalized)) + { + if (!normalized.EndsWith(buildName, StringComparison.OrdinalIgnoreCase)) + { + normalized = Path.Combine(normalized, buildName + ".x86_64"); + } + } + break; + } + + return normalized; + } + + private static void EnsureParentDirectory(BuildTarget buildTarget, string locationPath) + { + if (buildTarget == BuildTarget.iOS) + { + Directory.CreateDirectory(locationPath); + } + else + { + string dir = Path.GetDirectoryName(locationPath); + if (!string.IsNullOrEmpty(dir)) + { + Directory.CreateDirectory(dir); + } + } + } + + private static void AddDefineSymbol(BuildTargetGroup targetGroup, string symbol) + { + string existing = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup); + List symbols = existing + .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) + .Select(s => s.Trim()) + .ToList(); + + if (!symbols.Contains(symbol)) + { + symbols.Add(symbol); + PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, string.Join(";", symbols)); + } + } + + private static bool TryParseBuildTarget(string targetName, out BuildTarget buildTarget) + { + if (Enum.TryParse(targetName, ignoreCase: true, out buildTarget)) + { + return true; + } + + switch (targetName.ToLowerInvariant()) + { + case "win64": + case "windows": + case "windows64": + buildTarget = BuildTarget.StandaloneWindows64; + return true; + case "osx": + case "macos": + case "osxuniversal": + buildTarget = BuildTarget.StandaloneOSX; + return true; + case "linux": + case "linux64": + buildTarget = BuildTarget.StandaloneLinux64; + return true; + default: + return false; + } + } + + private static Dictionary ParseCommandLineArgs() + { + Dictionary result = new Dictionary(StringComparer.OrdinalIgnoreCase); + string[] args = Environment.GetCommandLineArgs(); + for (int i = 0; i < args.Length; i++) + { + string arg = args[i]; + if (!arg.StartsWith("-", StringComparison.Ordinal)) + { + continue; + } + + string key = arg.TrimStart('-'); + if (i + 1 < args.Length && !args[i + 1].StartsWith("-", StringComparison.Ordinal)) + { + result[key] = args[i + 1]; + i++; + } + else + { + result[key] = "true"; + } + } + return result; + } + + private static string GetArg(Dictionary args, string key, string defaultValue) + { + return args.TryGetValue(key, out string value) && !string.IsNullOrEmpty(value) + ? value + : defaultValue; + } + + private static bool HasFlag(Dictionary args, string key) + { + return args.TryGetValue(key, out string value) && + !string.Equals(value, "false", StringComparison.OrdinalIgnoreCase) && + !string.Equals(value, "0", StringComparison.OrdinalIgnoreCase); + } + + private static void Fail(string message) + { + Debug.LogError($"[CIBuildScript] {message}"); + if (Application.isBatchMode) + { + EditorApplication.Exit(1); + } + else + { + throw new Exception(message); + } + } + } +} diff --git a/Assets/Editor/CIBuildScript.cs.meta b/Assets/Editor/CIBuildScript.cs.meta new file mode 100644 index 0000000..7bbaa53 --- /dev/null +++ b/Assets/Editor/CIBuildScript.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 5e2a7c4b8f1940369d6e1b2c7a485f31 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/AstcE2ESmokeRunner.cs b/Assets/Scripts/AstcE2ESmokeRunner.cs new file mode 100644 index 0000000..7396ddf --- /dev/null +++ b/Assets/Scripts/AstcE2ESmokeRunner.cs @@ -0,0 +1,262 @@ +using System; +using System.IO; +using Aperture.Astcenc.Runtime; +using UnityEngine; +using UnityEngine.Experimental.Rendering; + +/// +/// Built-player end-to-end smoke test runner. +/// Activates in player builds when launched with the -astc-e2e command-line flag +/// or when built with the ASTC_CI_E2E scripting define symbol. +/// +public static class AstcE2ESmokeRunner +{ + private const string LogPrefix = "[ASTC_E2E]"; + +#if !UNITY_EDITOR + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)] + private static void RunIfRequested() + { + if (!ShouldRun()) + { + return; + } + + Debug.Log($"{LogPrefix} Starting runtime end-to-end verification on platform={Application.platform}, arch={System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture}, gfx={SystemInfo.graphicsDeviceType}"); + + try + { + VerifyIsSupport(); + VerifyAllBlockSizes(); + VerifyEncodeToAstcAndKtxRoundTrip(); + VerifyNonSquareMipmaps(); + VerifyNormalAndMultiFormats(); + VerifyInPlaceCompressIfSupported(); + + Debug.Log($"{LogPrefix} ASTC_E2E_PASSED"); + Application.Quit(0); + } + catch (Exception ex) + { + Debug.LogError($"{LogPrefix} ASTC_E2E_FAILED: {ex}"); + Application.Quit(1); + } + } + + private static bool ShouldRun() + { +#if ASTC_CI_E2E + return true; +#else + string[] args = Environment.GetCommandLineArgs(); + for (int i = 0; i < args.Length; i++) + { + if (string.Equals(args[i], "-astc-e2e", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + return false; +#endif + } +#endif + + private static void AssertTrue(bool condition, string message) + { + if (!condition) + { + throw new InvalidOperationException($"Assertion failed: {message}"); + } + } + + private static Texture2D CreateProceduralTexture(int width, int height, TextureFormat format, bool mipChain, bool linear = false) + { + Texture2D tex = new Texture2D(width, height, format, mipChain, linear); + Color[] pixels = new Color[width * height]; + for (int y = 0; y < height; y++) + { + for (int x = 0; x < width; x++) + { + pixels[y * width + x] = new Color( + (float)x / Math.Max(1, width - 1), + (float)y / Math.Max(1, height - 1), + ((x ^ y) & 0xFF) / 255.0f, + 0.75f); + } + } + tex.SetPixels(pixels); + tex.Apply(mipChain, false); + return tex; + } + + private static int ExpectedCompressedBytes(int width, int height, int mipCount, int blockDim) + { + int total = 0; + for (int i = 0; i < mipCount; i++) + { + int mw = Math.Max(1, width >> i); + int mh = Math.Max(1, height >> i); + int bx = (mw + blockDim - 1) / blockDim; + int by = (mh + blockDim - 1) / blockDim; + total += bx * by * 16; + } + return total; + } + + private static void VerifyIsSupport() + { + AssertTrue(!Encoder.IsSupport(null), "Null texture must not be supported."); + + Texture2D readable = CreateProceduralTexture(16, 16, TextureFormat.RGBA32, false); + try + { + AssertTrue(Encoder.IsSupport(readable, EncodeBackend.Cpu), "Readable RGBA32 texture must be supported on CPU backend."); + readable.Apply(false, true); + AssertTrue(!Encoder.IsSupport(readable, EncodeBackend.Cpu), "Non-readable texture must not be supported on CPU backend."); + } + finally + { + UnityEngine.Object.DestroyImmediate(readable); + } + } + + private static void VerifyAllBlockSizes() + { + (BlockSize size, int dim)[] cases = + { + (BlockSize.ASTC_4x4, 4), + (BlockSize.ASTC_5x5, 5), + (BlockSize.ASTC_6x6, 6), + (BlockSize.ASTC_8x8, 8), + (BlockSize.ASTC_10x10, 10), + (BlockSize.ASTC_12x12, 12), + }; + + Texture2D tex = CreateProceduralTexture(32, 32, TextureFormat.RGBA32, false); + try + { + foreach (var (blockSize, dim) in cases) + { + int expected = ExpectedCompressedBytes(32, 32, 1, dim); + using (AstcRaw raw = tex.CompressTexture(TextureType.Default, blockSize, CompressQuality.Fastest, backend: EncodeBackend.Cpu)) + { + AssertTrue(raw != null, $"CompressTexture returned null for {blockSize}."); + AssertTrue(raw.Length == expected, $"{blockSize}: expected {expected} bytes, got {raw.Length}."); + } + } + } + finally + { + UnityEngine.Object.DestroyImmediate(tex); + } + } + + private static void VerifyEncodeToAstcAndKtxRoundTrip() + { + const int width = 37; + const int height = 23; + Texture2D tex = CreateProceduralTexture(width, height, TextureFormat.RGBA32, false); + try + { + byte[] encoded = tex.EncodeToASTC(TextureType.Default, BlockSize.ASTC_6x6, CompressQuality.Fast, backend: EncodeBackend.Cpu); + int expectedPayload = ExpectedCompressedBytes(width, height, 1, 6); + AssertTrue(encoded != null, "EncodeToASTC returned null."); + AssertTrue(encoded.Length == AstcHeader.HeaderSize + expectedPayload, $"Expected {AstcHeader.HeaderSize + expectedPayload} bytes, got {encoded.Length}."); + + AssertTrue(AstcHeader.TryParse(encoded, 0, out uint bx, out uint by, out uint bz, out int w, out int h, out int d), "AstcHeader.TryParse failed."); + AssertTrue(bx == 6 && by == 6 && bz == 1, $"Invalid header block dims: {bx}x{by}x{bz}."); + AssertTrue(w == width && h == height && d == 1, $"Invalid header image dims: {w}x{h}x{d}."); + + string outPath = Path.Combine(Application.persistentDataPath, "astc_e2e_test.astc"); + File.WriteAllBytes(outPath, encoded); + byte[] readBack = File.ReadAllBytes(outPath); + AssertTrue(readBack.Length == encoded.Length, "Written .astc file length mismatch."); + File.Delete(outPath); + + using (AstcRaw raw = tex.CompressTexture(TextureType.Default, BlockSize.ASTC_6x6, CompressQuality.Fastest, backend: EncodeBackend.Cpu)) + { + byte[] ktx = AstcKtxContainer.Encode(raw, width, height, 1, GraphicsFormat.RGBA_ASTC6X6_UNorm); + AssertTrue(ktx != null, "KTX container encode returned null."); + AssertTrue(AstcKtxContainer.TryDecode(ktx, out KtxAstcData decoded), "KTX container decode failed."); + AssertTrue(decoded.Width == width && decoded.Height == height && decoded.MipCount == 1, "KTX decoded metadata mismatch."); + AssertTrue(decoded.RawAstcPayload.Length == raw.Length, "KTX decoded payload length mismatch."); + } + } + finally + { + UnityEngine.Object.DestroyImmediate(tex); + } + } + + private static void VerifyNonSquareMipmaps() + { + Texture2D tex = CreateProceduralTexture(64, 32, TextureFormat.RGBA32, true); + try + { + AssertTrue(tex.mipmapCount > 1, "Expected mipmapCount > 1 for mipmapped texture."); + int expected = ExpectedCompressedBytes(64, 32, tex.mipmapCount, 6); + using (AstcRaw raw = tex.CompressTexture(TextureType.Default, BlockSize.ASTC_6x6, CompressQuality.Fastest, backend: EncodeBackend.Cpu)) + { + AssertTrue(raw != null, "Mipmapped non-square CompressTexture returned null."); + AssertTrue(raw.Length == expected, $"Mipmapped non-square expected {expected} bytes, got {raw.Length}."); + } + } + finally + { + UnityEngine.Object.DestroyImmediate(tex); + } + } + + private static void VerifyNormalAndMultiFormats() + { + (TextureFormat fmt, TextureType type, bool linear)[] cases = + { + (TextureFormat.RGBA32, TextureType.Normal, true), + (TextureFormat.RGB24, TextureType.Default, false), + (TextureFormat.R8, TextureType.Default, true), + (TextureFormat.RGBAHalf, TextureType.Default, true), + (TextureFormat.RGBAFloat, TextureType.Default, true), + }; + + foreach (var (fmt, type, linear) in cases) + { + Texture2D tex = CreateProceduralTexture(16, 16, fmt, false, linear); + try + { + AssertTrue(Encoder.IsSupport(tex, EncodeBackend.Cpu), $"Expected format {fmt} ({tex.graphicsFormat}) to be supported."); + using (AstcRaw raw = tex.CompressTexture(type, BlockSize.ASTC_4x4, CompressQuality.Fastest, backend: EncodeBackend.Cpu)) + { + int expected = ExpectedCompressedBytes(16, 16, 1, 4); + AssertTrue(raw != null && raw.Length == expected, $"Format {fmt} ({type}) failed compression."); + } + } + finally + { + UnityEngine.Object.DestroyImmediate(tex); + } + } + } + + private static void VerifyInPlaceCompressIfSupported() + { + if (!SystemInfo.SupportsTextureFormat(TextureFormat.ASTC_6x6) || + !SystemInfo.IsFormatSupported(GraphicsFormat.RGBA_ASTC6X6_UNorm, FormatUsage.Sample)) + { + Debug.Log($"{LogPrefix} Skipping GPU in-place Compress check (ASTC GPU sampling unsupported in current graphics mode: {SystemInfo.graphicsDeviceType})."); + return; + } + + Texture2D tex = CreateProceduralTexture(32, 32, TextureFormat.RGBA32, false, linear: true); + try + { + bool ok = tex.Compress(TextureType.Default, BlockSize.ASTC_6x6, CompressQuality.Fastest, makeNoLongerReadable: true, backend: EncodeBackend.Auto); + AssertTrue(ok, "In-place Texture2D.Compress returned false."); + AssertTrue(tex.graphicsFormat == GraphicsFormat.RGBA_ASTC6X6_UNorm, $"Expected RGBA_ASTC6X6_UNorm, got {tex.graphicsFormat}."); + AssertTrue(!tex.isReadable, "Expected texture to be non-readable after makeNoLongerReadable=true."); + } + finally + { + UnityEngine.Object.DestroyImmediate(tex); + } + } +} diff --git a/Assets/Scripts/AstcE2ESmokeRunner.cs.meta b/Assets/Scripts/AstcE2ESmokeRunner.cs.meta new file mode 100644 index 0000000..024b570 --- /dev/null +++ b/Assets/Scripts/AstcE2ESmokeRunner.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 7b4e9c1d2a5f483091c6e8a4f2d0b317 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/AstcPlayerBenchmarkRunner.cs b/Assets/Scripts/AstcPlayerBenchmarkRunner.cs new file mode 100644 index 0000000..0aa2295 --- /dev/null +++ b/Assets/Scripts/AstcPlayerBenchmarkRunner.cs @@ -0,0 +1,873 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using Aperture.Astcenc.Runtime; +using Unity.Collections; +using UnityEngine; +using UnityEngine.Experimental.Rendering; +using Debug = UnityEngine.Debug; +using Encoder = Aperture.Astcenc.Runtime.Encoder; + +/// +/// Standalone Unity Player performance & quality benchmark runner. +/// Activates in built players when launched with -astc-benchmark and writes a structured JSON report +/// to -astc-bench-out <path> (default: astc_benchmark_report.json). +/// Ideal for running real hardware GPU (e.g., macOS Apple Silicon Metal) and CPU benchmarks in CI without Editor overhead. +/// +public static class AstcPlayerBenchmarkRunner +{ + private const string LogPrefix = "[ASTC_BENCH]"; + + [Serializable] + public sealed class PlayerBenchmarkEntry + { + public string Name; + public string Category; + public string Backend; + public string Resolution; + public string BlockSize; + public string Quality; + public int WarmupRuns; + public int Iterations; + public double MinMs; + public double MedianMs; + public double MeanMs; + public double P95Ms; + public double MaxMs; + public double ThroughputMPixPerSec; + public long GcAllocBytesPerOp; + public int OutputBytes; + public int UncompressedBytes; + public double RgbPsnrDb; + public double RgbaPsnrDb; + public double MeanNormalDeg; + public string Notes; + } + + [Serializable] + public sealed class PlayerBenchmarkReport + { + public string SchemaVersion = "1.0"; + public string TimestampUtc; + public string GitCommit; + public string UnityVersion; + public string Platform; + public string CpuModel; + public int CpuCores; + public string GpuModel; + public string GraphicsDeviceType; + public bool GpuSupported; + public bool CpuSupported; + public bool SupportsDirectCopy4x4; + public bool SupportsDirectCopy6x6; + public List Results = new List(); + } + +#if !UNITY_EDITOR + [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)] + private static void RunIfRequested() + { + if (!HasFlag("-astc-benchmark")) + return; + + string outPath = GetArgValue("-astc-bench-out", "astc_benchmark_report.json"); + int warmup = GetIntArg("-astc-bench-warmup", 2); + int iterations = GetIntArg("-astc-bench-iters", 5); + string gitCommit = GetArgValue("-astc-bench-commit", Environment.GetEnvironmentVariable("GITHUB_SHA") ?? ""); + + Debug.Log($"{LogPrefix} Starting standalone benchmark suite: platform={Application.platform}, gpu={SystemInfo.graphicsDeviceName} ({SystemInfo.graphicsDeviceType}), cpu={SystemInfo.processorType} ({Environment.ProcessorCount} cores), gpuSupported={Encoder.IsGpuSupported}, cpuSupported={Encoder.IsCpuSupported}"); + + try + { + PlayerBenchmarkReport report = RunAll(warmup, iterations, gitCommit); + string fullOutPath = Path.GetFullPath(outPath); + string dir = Path.GetDirectoryName(fullOutPath); + if (!string.IsNullOrEmpty(dir)) + Directory.CreateDirectory(dir); + + File.WriteAllText(fullOutPath, JsonUtility.ToJson(report, true), new UTF8Encoding(false)); + Debug.Log($"{LogPrefix} ASTC_BENCH_PASSED count={report.Results.Count} output={fullOutPath}"); + Application.Quit(0); + } + catch (Exception ex) + { + Debug.LogError($"{LogPrefix} ASTC_BENCH_FAILED: {ex}"); + Application.Quit(1); + } + } +#endif + + public static PlayerBenchmarkReport RunAll(int warmup, int iterations, string gitCommit = "") + { + var report = new PlayerBenchmarkReport + { + TimestampUtc = DateTime.UtcNow.ToString("O", CultureInfo.InvariantCulture), + GitCommit = gitCommit ?? string.Empty, + UnityVersion = Application.unityVersion, + Platform = Application.platform.ToString(), + CpuModel = SystemInfo.processorType, + CpuCores = Environment.ProcessorCount, + GpuModel = SystemInfo.graphicsDeviceName, + GraphicsDeviceType = SystemInfo.graphicsDeviceType.ToString(), + GpuSupported = Encoder.IsGpuSupported, + CpuSupported = Encoder.IsCpuSupported, + SupportsDirectCopy4x4 = Encoder.SupportsGpuDirectCopy(BlockSize.ASTC_4x4), + SupportsDirectCopy6x6 = Encoder.SupportsGpuDirectCopy(BlockSize.ASTC_6x6) + }; + + BlockSize[] blockSizes = { BlockSize.ASTC_4x4, BlockSize.ASTC_6x6, BlockSize.ASTC_8x8, BlockSize.ASTC_12x12 }; + + if (Encoder.IsGpuSupported) + { + foreach (BlockSize bs in blockSizes) + Encoder.PreloadGpu(bs); + } + + Texture2D tex512 = CreateProceduralColorTexture(512, 512, srgb: false, withAlpha: true, withMipmaps: false); + Texture2D tex1024 = CreateProceduralColorTexture(1024, 1024, srgb: false, withAlpha: true, withMipmaps: false); + Texture2D tex512Srgb = CreateProceduralColorTexture(512, 512, srgb: true, withAlpha: false, withMipmaps: false); + Texture2D tex512Normal = CreateProceduralNormalTexture(512, 512); + Texture2D tex512Hdr = CreateProceduralHdrTexture(512, 512); + Texture2D tex512Mip = CreateProceduralColorTexture(512, 512, srgb: false, withAlpha: true, withMipmaps: true); + + try + { + Color32[] ref512 = tex512.GetPixels32(0); + Color32[] ref1024 = tex1024.GetPixels32(0); + Color32[] refNormal512 = tex512Normal.GetPixels32(0); + + // 1. GPU vs CPU Side-by-Side Matrix (1024x1024 & 512x512 RGBA8) + CompressQuality[] q1024 = { CompressQuality.Fast, CompressQuality.Medium }; + foreach (BlockSize bs in blockSizes) + { + foreach (CompressQuality q in q1024) + { + if (Encoder.IsGpuSupported) + { + report.Results.Add(MeasureEncodeWithQuality( + name: $"GPU_RGBA8_1024_{bs}_{q}", + category: "GPU_vs_CPU_1024", + backend: "GPU", + tex: tex1024, + refPixels: ref1024, + bs: bs, + q: q, + encodeBackend: EncodeBackend.Gpu, + warmup: warmup, + iterations: iterations)); + } + + if (Encoder.IsCpuSupported) + { + report.Results.Add(MeasureEncodeWithQuality( + name: $"CPU_RGBA8_1024_{bs}_{q}", + category: "GPU_vs_CPU_1024", + backend: "CPU", + tex: tex1024, + refPixels: ref1024, + bs: bs, + q: q, + encodeBackend: EncodeBackend.Cpu, + warmup: Math.Max(1, warmup - 1), + iterations: Math.Max(3, iterations - 1))); + } + } + } + + CompressQuality[] q512 = { CompressQuality.Fast, CompressQuality.Medium, CompressQuality.Thorough }; + foreach (BlockSize bs in blockSizes) + { + foreach (CompressQuality q in q512) + { + if (Encoder.IsGpuSupported) + { + report.Results.Add(MeasureEncodeWithQuality( + name: $"GPU_RGBA8_512_{bs}_{q}", + category: "GPU_vs_CPU_512", + backend: "GPU", + tex: tex512, + refPixels: ref512, + bs: bs, + q: q, + encodeBackend: EncodeBackend.Gpu, + warmup: warmup, + iterations: iterations)); + } + + if (Encoder.IsCpuSupported) + { + report.Results.Add(MeasureEncodeWithQuality( + name: $"CPU_RGBA8_512_{bs}_{q}", + category: "GPU_vs_CPU_512", + backend: "CPU", + tex: tex512, + refPixels: ref512, + bs: bs, + q: q, + encodeBackend: EncodeBackend.Cpu, + warmup: Math.Max(1, warmup - 1), + iterations: q == CompressQuality.Thorough ? 3 : iterations)); + } + } + } + + // 2. GPU Zero-Readback DirectCopy, MipGen, sRGB, Normal, HDR + if (Encoder.IsGpuSupported) + { + // Zero-readback CompressToTexture (1024x1024 ASTC 6x6 Fast, mip0) + var direct6x6Opt = AstcCompressOptions.Default; + direct6x6Opt.Backend = EncodeBackend.Gpu; + direct6x6Opt.BlockSize = BlockSize.ASTC_6x6; + direct6x6Opt.Quality = CompressQuality.Fast; + direct6x6Opt.IncludeMipmaps = false; + + report.Results.Add(Sample( + name: "GPU_ZeroReadback_1024_6x6_Fast", + category: "GPU_ZeroReadback", + backend: "GPU", + resolution: "1024x1024", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: 1024L * 1024L, + uncompressedBytes: 1024 * 1024 * 4, + warmup: warmup, + iterations: iterations, + action: () => + { + Texture2D dst = tex1024.CompressToTexture(direct6x6Opt); + int bytes = ExpectedMipChainBytes(1024, 1024, 1, 6); + if (dst != null) UnityEngine.Object.DestroyImmediate(dst); + return dst != null ? bytes : 0; + }, + notes: Encoder.SupportsGpuDirectCopy(BlockSize.ASTC_6x6) ? "Direct CopyTexture (zero CPU readback)" : "Readback fallback")); + + // Zero-readback CompressToTexture with single-CommandBuffer GPU mipmap generation (1024x1024 + Full Mips) + var mipGenOpt = AstcCompressOptions.Default; + mipGenOpt.Backend = EncodeBackend.Gpu; + mipGenOpt.BlockSize = BlockSize.ASTC_6x6; + mipGenOpt.Quality = CompressQuality.Fast; + mipGenOpt.IncludeMipmaps = true; + mipGenOpt.GenerateMipmaps = true; + long mip1024Pixels = CalculateMipChainPixels(1024, 1024); + + report.Results.Add(Sample( + name: "GPU_ZeroReadback_MipGen_1024_6x6_Fast", + category: "GPU_ZeroReadback", + backend: "GPU", + resolution: "1024x1024+Mips", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: mip1024Pixels, + uncompressedBytes: (int)(mip1024Pixels * 4L), + warmup: warmup, + iterations: iterations, + action: () => + { + Texture2D dst = tex1024.CompressToTexture(mipGenOpt); + int bytes = ExpectedMipChainBytes(1024, 1024, 11, 6); + if (dst != null) UnityEngine.Object.DestroyImmediate(dst); + return dst != null ? bytes : 0; + }, + notes: "Single-CommandBuffer GPU MipGen + ASTC encode")); + + // Normal Map GPU vs CPU (with MeanNormalDeg) + report.Results.Add(MeasureNormalWithQuality("GPU_Normal_512_6x6_Medium", tex512Normal, refNormal512, BlockSize.ASTC_6x6, CompressQuality.Medium, EncodeBackend.Gpu, warmup, iterations)); + if (Encoder.IsCpuSupported) + { + report.Results.Add(MeasureNormalWithQuality("CPU_Normal_512_6x6_Medium", tex512Normal, refNormal512, BlockSize.ASTC_6x6, CompressQuality.Medium, EncodeBackend.Cpu, 1, iterations)); + } + + // sRGB & HDR + var srgbOpt = AstcCompressOptions.Default; + srgbOpt.Backend = EncodeBackend.Gpu; + srgbOpt.BlockSize = BlockSize.ASTC_6x6; + srgbOpt.Quality = CompressQuality.Fast; + srgbOpt.IncludeMipmaps = false; + + report.Results.Add(Sample( + name: "GPU_sRGB_512_6x6_Fast", + category: "GPU_Modes", + backend: "GPU", + resolution: "512x512", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: 512L * 512L, + uncompressedBytes: 512 * 512 * 4, + warmup: warmup, + iterations: iterations, + action: () => + { + using AstcRaw raw = tex512Srgb.CompressTexture(srgbOpt); + return raw != null ? raw.Length : 0; + })); + + var hdrOpt = AstcCompressOptions.Default; + hdrOpt.Backend = EncodeBackend.Gpu; + hdrOpt.BlockSize = BlockSize.ASTC_6x6; + hdrOpt.Quality = CompressQuality.Fast; + hdrOpt.IncludeMipmaps = false; + + report.Results.Add(Sample( + name: "GPU_HDR16F_512_6x6_Fast", + category: "GPU_Modes", + backend: "GPU", + resolution: "512x512", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: 512L * 512L, + uncompressedBytes: 512 * 512 * 8, + warmup: warmup, + iterations: iterations, + action: () => + { + using AstcRaw raw = tex512Hdr.CompressTexture(hdrOpt); + return raw != null ? raw.Length : 0; + })); + } + + // 3. CPU RawPixels vs CompressRawPixelsInto (Zero-Alloc) & Decompression + if (Encoder.IsCpuSupported) + { + const int w = 512; + const int h = 512; + int outCap = ((w + 5) / 6) * ((h + 5) / 6) * 16; + var srcNative = new NativeArray(w * h * 4, Allocator.Persistent); + var dstNative = new NativeArray(outCap, Allocator.Persistent); + try + { + for (int i = 0; i < srcNative.Length; i++) + srcNative[i] = (byte)((i * 37) & 0xFF); + + var rawOpt = AstcCompressOptions.Default; + rawOpt.Backend = EncodeBackend.Cpu; + rawOpt.BlockSize = BlockSize.ASTC_6x6; + rawOpt.Quality = CompressQuality.Fast; + rawOpt.ThreadCount = 0; + + report.Results.Add(Sample( + name: "CPU_CompressRawPixels_512_6x6_Fast", + category: "CPU_ZeroAlloc", + backend: "CPU", + resolution: "512x512", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: w * (long)h, + uncompressedBytes: w * h * 4, + warmup: 1, + iterations: iterations, + action: () => + { + using AstcRaw raw = Encoder.CompressRawPixels(srcNative, w, h, GraphicsFormat.R8G8B8A8_UNorm, rawOpt); + return raw != null ? raw.Length : 0; + })); + + report.Results.Add(Sample( + name: "CPU_CompressRawPixelsInto_512_6x6_Fast", + category: "CPU_ZeroAlloc", + backend: "CPU", + resolution: "512x512", + blockSize: "ASTC_6x6", + quality: "Fast", + totalPixels: w * (long)h, + uncompressedBytes: w * h * 4, + warmup: 1, + iterations: iterations, + action: () => + { + bool ok = Encoder.CompressRawPixelsInto(srcNative, dstNative, w, h, GraphicsFormat.R8G8B8A8_UNorm, rawOpt, out int written); + return ok ? written : 0; + }, + notes: "Zero-alloc caller-owned NativeArray + AstcContextPool")); + } + finally + { + srcNative.Dispose(); + dstNative.Dispose(); + } + + // CPU Software Decompression (512x512 ASTC_6x6) + var encOpt = AstcCompressOptions.Default; + encOpt.Backend = EncodeBackend.Cpu; + encOpt.BlockSize = BlockSize.ASTC_6x6; + encOpt.Quality = CompressQuality.Fast; + encOpt.IncludeMipmaps = false; + + using AstcRaw encoded6x6 = tex512.CompressTexture(encOpt); + if (encoded6x6 != null) + { + int decThreads = Math.Max(1, Math.Min(Environment.ProcessorCount, 4)); + report.Results.Add(Sample( + name: $"CPU_Decompress_512_6x6_{decThreads}T", + category: "CPU_Decompress", + backend: "CPU", + resolution: "512x512", + blockSize: "ASTC_6x6", + quality: "N/A", + totalPixels: w * (long)h, + uncompressedBytes: w * h * 4, + warmup: 2, + iterations: iterations, + action: () => + { + byte[] rgba = Encoder.Decompress(encoded6x6, w, h, BlockSize.ASTC_6x6, srgb: false, isHdr: false, outputBitness: 8, threadCount: decThreads); + return rgba != null ? rgba.Length : 0; + }, + notes: $"Pooled DecompressOnly ({decThreads}T)")); + } + } + + // 4. KTX Container & Disk Cache + { + var ktxOpt = AstcCompressOptions.Default; + ktxOpt.Backend = Encoder.IsGpuSupported ? EncodeBackend.Gpu : EncodeBackend.Cpu; + ktxOpt.BlockSize = BlockSize.ASTC_6x6; + ktxOpt.Quality = CompressQuality.Fast; + ktxOpt.IncludeMipmaps = true; + + using AstcRaw mipRaw = tex512Mip.CompressTexture(ktxOpt); + if (mipRaw != null) + { + int mipCount = tex512Mip.mipmapCount; + long mipPixels = CalculateMipChainPixels(512, 512); + GraphicsFormat astcFmt = Encoder.GetTargetAstcFormat(tex512Mip.graphicsFormat, BlockSize.ASTC_6x6, TextureType.Default); + byte[] ktxBytes = AstcKtxContainer.Encode(mipRaw, 512, 512, mipCount, astcFmt); + + string tempPath = Path.Combine(Path.GetTempPath(), $"astc_player_bench_{Guid.NewGuid():N}.ktx"); + try + { + File.WriteAllBytes(tempPath, ktxBytes); + report.Results.Add(Sample( + name: "DiskCache_TryLoad_512_6x6_FullMips", + category: "Container_Cache", + backend: "Disk+GPU", + resolution: "512x512+Mips", + blockSize: "ASTC_6x6", + quality: "N/A", + totalPixels: mipPixels, + uncompressedBytes: (int)(mipPixels * 4L), + warmup: 1, + iterations: iterations, + action: () => + { + Texture2D loaded = AstcDiskCache.TryLoad(tempPath, makeNoLongerReadable: true); + int ok = loaded != null ? ktxBytes.Length : 0; + if (loaded != null) UnityEngine.Object.DestroyImmediate(loaded); + return ok; + }, + notes: "Instant KTX v1 load + GPU upload")); + } + finally + { + if (File.Exists(tempPath)) + { + try { File.Delete(tempPath); } catch { } + } + } + } + } + } + finally + { + UnityEngine.Object.DestroyImmediate(tex512); + UnityEngine.Object.DestroyImmediate(tex1024); + UnityEngine.Object.DestroyImmediate(tex512Srgb); + UnityEngine.Object.DestroyImmediate(tex512Normal); + UnityEngine.Object.DestroyImmediate(tex512Hdr); + UnityEngine.Object.DestroyImmediate(tex512Mip); + } + + return report; + } + + private static PlayerBenchmarkEntry MeasureEncodeWithQuality( + string name, + string category, + string backend, + Texture2D tex, + Color32[] refPixels, + BlockSize bs, + CompressQuality q, + EncodeBackend encodeBackend, + int warmup, + int iterations) + { + int w = tex.width; + int h = tex.height; + var opt = AstcCompressOptions.Default; + opt.Backend = encodeBackend; + opt.BlockSize = bs; + opt.Quality = q; + opt.IncludeMipmaps = false; + opt.ThreadCount = 0; + + AstcRaw lastRaw = null; + try + { + PlayerBenchmarkEntry entry = Sample( + name: name, + category: category, + backend: backend, + resolution: $"{w}x{h}", + blockSize: bs.ToString(), + quality: q.ToString(), + totalPixels: (long)w * h, + uncompressedBytes: w * h * 4, + warmup: warmup, + iterations: iterations, + action: () => + { + lastRaw?.Dispose(); + lastRaw = tex.CompressTexture(opt); + return lastRaw != null ? lastRaw.Length : 0; + }); + + if (lastRaw != null && Encoder.IsCpuSupported) + { + byte[] dec = Encoder.Decompress(lastRaw, w, h, bs, srgb: false, isHdr: false, outputBitness: 8, threadCount: 0); + if (dec != null) + { + ComputePsnr(refPixels, dec, out entry.RgbPsnrDb, out entry.RgbaPsnrDb); + if (entry.RgbPsnrDb < 18.0) + { + throw new InvalidOperationException($"Benchmark '{name}' produced invalid quality: RGB PSNR={entry.RgbPsnrDb:F2} dB (< 18 dB). Check GPU shader compilation logs."); + } + } + } + + return entry; + } + finally + { + lastRaw?.Dispose(); + } + } + + private static PlayerBenchmarkEntry MeasureNormalWithQuality( + string name, + Texture2D normalTex, + Color32[] refPixels, + BlockSize bs, + CompressQuality q, + EncodeBackend encodeBackend, + int warmup, + int iterations) + { + int w = normalTex.width; + int h = normalTex.height; + var opt = AstcCompressOptions.NormalMap; + opt.Backend = encodeBackend; + opt.BlockSize = bs; + opt.Quality = q; + opt.IncludeMipmaps = false; + opt.ThreadCount = 0; + + AstcRaw lastRaw = null; + try + { + PlayerBenchmarkEntry entry = Sample( + name: name, + category: "NormalMap", + backend: encodeBackend == EncodeBackend.Gpu ? "GPU" : "CPU", + resolution: $"{w}x{h}", + blockSize: bs.ToString(), + quality: q.ToString(), + totalPixels: (long)w * h, + uncompressedBytes: w * h * 4, + warmup: warmup, + iterations: iterations, + action: () => + { + lastRaw?.Dispose(); + lastRaw = normalTex.CompressTexture(opt); + return lastRaw != null ? lastRaw.Length : 0; + }); + + if (lastRaw != null && Encoder.IsCpuSupported) + { + byte[] dec = Encoder.Decompress(lastRaw, w, h, bs, srgb: false, isHdr: false, outputBitness: 8, threadCount: 0); + if (dec != null) + { + entry.MeanNormalDeg = ComputeMeanNormalAngularErrorDeg(refPixels, dec); + if (entry.MeanNormalDeg > 15.0) + { + throw new InvalidOperationException($"Benchmark '{name}' produced invalid normal error: {entry.MeanNormalDeg:F2} deg (> 15 deg)."); + } + } + } + + return entry; + } + finally + { + lastRaw?.Dispose(); + } + } + + private static PlayerBenchmarkEntry Sample( + string name, + string category, + string backend, + string resolution, + string blockSize, + string quality, + long totalPixels, + int uncompressedBytes, + int warmup, + int iterations, + Func action, + string notes = "") + { + int effectiveWarmup = Math.Max(0, warmup); + int effectiveIters = Math.Max(1, iterations); + + int lastBytes = 0; + for (int i = 0; i < effectiveWarmup; i++) + lastBytes = action(); + + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + + double[] samples = new double[effectiveIters]; + long totalGc = 0; + var sw = new Stopwatch(); + for (int i = 0; i < effectiveIters; i++) + { + long memBefore = GC.GetTotalMemory(false); + sw.Restart(); + lastBytes = action(); + sw.Stop(); + long memAfter = GC.GetTotalMemory(false); + + samples[i] = sw.Elapsed.TotalMilliseconds; + if (memAfter > memBefore) + totalGc += (memAfter - memBefore); + } + + Array.Sort(samples); + double sum = 0.0; + for (int i = 0; i < samples.Length; i++) sum += samples[i]; + + double minMs = samples[0]; + double maxMs = samples[samples.Length - 1]; + double meanMs = sum / samples.Length; + double medianMs = (samples.Length & 1) == 1 + ? samples[samples.Length / 2] + : 0.5 * (samples[samples.Length / 2 - 1] + samples[samples.Length / 2]); + int p95Idx = Math.Min(samples.Length - 1, (int)Math.Ceiling(samples.Length * 0.95) - 1); + double p95Ms = samples[Math.Max(0, p95Idx)]; + double mpixPerSec = (medianMs > 1e-6 && totalPixels > 0) ? (totalPixels / 1e6) / (medianMs / 1000.0) : 0.0; + + return new PlayerBenchmarkEntry + { + Name = name, + Category = category, + Backend = backend, + Resolution = resolution, + BlockSize = blockSize, + Quality = quality, + WarmupRuns = effectiveWarmup, + Iterations = effectiveIters, + MinMs = minMs, + MedianMs = medianMs, + MeanMs = meanMs, + P95Ms = p95Ms, + MaxMs = maxMs, + ThroughputMPixPerSec = mpixPerSec, + GcAllocBytesPerOp = totalGc / effectiveIters, + OutputBytes = lastBytes, + UncompressedBytes = uncompressedBytes, + Notes = notes ?? string.Empty + }; + } + + private static void ComputePsnr(Color32[] refPixels, byte[] decodedRgba8, out double rgbPsnr, out double rgbaPsnr) + { + double rgbSq = 0.0; + double alphaSq = 0.0; + int count = Math.Min(refPixels.Length, decodedRgba8.Length / 4); + for (int i = 0; i < count; i++) + { + Color32 r = refPixels[i]; + int o = i * 4; + double dr = r.r - decodedRgba8[o + 0]; + double dg = r.g - decodedRgba8[o + 1]; + double db = r.b - decodedRgba8[o + 2]; + double da = r.a - decodedRgba8[o + 3]; + rgbSq += dr * dr + dg * dg + db * db; + alphaSq += da * da; + } + double rgbMse = count > 0 ? rgbSq / (count * 3.0) : 0.0; + double rgbaMse = count > 0 ? (rgbSq + alphaSq) / (count * 4.0) : 0.0; + rgbPsnr = rgbMse > 1e-12 ? 10.0 * Math.Log10((255.0 * 255.0) / rgbMse) : 99.99; + rgbaPsnr = rgbaMse > 1e-12 ? 10.0 * Math.Log10((255.0 * 255.0) / rgbaMse) : 99.99; + } + + private static double ComputeMeanNormalAngularErrorDeg(Color32[] refPixels, byte[] decodedRgba8) + { + double degSum = 0.0; + int count = Math.Min(refPixels.Length, decodedRgba8.Length / 4); + for (int i = 0; i < count; i++) + { + float ax = (refPixels[i].r / 255f) * 2f - 1f; + float ay = (refPixels[i].g / 255f) * 2f - 1f; + float az = Mathf.Sqrt(Mathf.Max(0f, 1f - ax * ax - ay * ay)); + + // ASTC Normal map stores GGGR (R/G/B = ny, A = nx) + float bx = (decodedRgba8[i * 4 + 3] / 255f) * 2f - 1f; + float by = (decodedRgba8[i * 4 + 1] / 255f) * 2f - 1f; + float bz = Mathf.Sqrt(Mathf.Max(0f, 1f - bx * bx - by * by)); + + float dot = Mathf.Clamp(ax * bx + ay * by + az * bz, -1f, 1f); + degSum += Math.Acos(dot) * (180.0 / Math.PI); + } + return count > 0 ? degSum / count : 0.0; + } + + private static long CalculateMipChainPixels(int width, int height) + { + long total = 0; + int w = width; + int h = height; + while (true) + { + total += (long)w * h; + if (w == 1 && h == 1) break; + w = Math.Max(1, w >> 1); + h = Math.Max(1, h >> 1); + } + return total; + } + + private static int ExpectedMipChainBytes(int width, int height, int mipCount, int blockDim) + { + int total = 0; + for (int i = 0; i < mipCount; i++) + { + int mw = Math.Max(1, width >> i); + int mh = Math.Max(1, height >> i); + total += ((mw + blockDim - 1) / blockDim) * ((mh + blockDim - 1) / blockDim) * 16; + } + return total; + } + + private static Texture2D CreateProceduralColorTexture(int width, int height, bool srgb, bool withAlpha, bool withMipmaps) + { + GraphicsFormat fmt = srgb ? GraphicsFormat.R8G8B8A8_SRGB : GraphicsFormat.R8G8B8A8_UNorm; + TextureCreationFlags flags = withMipmaps ? TextureCreationFlags.MipChain : TextureCreationFlags.None; + var tex = new Texture2D(width, height, fmt, flags); + var pixels = new Color32[width * height]; + for (int y = 0; y < height; y++) + { + float v = height > 1 ? (float)y / (height - 1) : 0f; + for (int x = 0; x < width; x++) + { + float u = width > 1 ? (float)x / (width - 1) : 0f; + byte r, g, b, a; + if (x < width / 4 && y < height / 4) + { + r = 96; g = 144; b = 192; a = 255; + } + else + { + float wave = 0.5f + 0.5f * Mathf.Sin((u * 18f + v * 12f) * Mathf.PI); + float checker = (((x >> 3) + (y >> 3)) & 1) == 0 ? 0.15f : -0.15f; + r = (byte)Mathf.Clamp(Mathf.RoundToInt((u * 0.7f + wave * 0.3f + checker) * 255f), 0, 255); + g = (byte)Mathf.Clamp(Mathf.RoundToInt((v * 0.7f + (1f - wave) * 0.3f - checker) * 255f), 0, 255); + b = (byte)Mathf.Clamp(Mathf.RoundToInt(((u + v) * 0.4f + wave * 0.2f) * 255f), 0, 255); + a = withAlpha + ? (byte)Mathf.Clamp(Mathf.RoundToInt((0.2f + 0.8f * Mathf.Abs(Mathf.Sin((u - v) * 4f * Mathf.PI))) * 255f), 0, 255) + : (byte)255; + } + pixels[y * width + x] = new Color32(r, g, b, a); + } + } + tex.SetPixels32(pixels); + tex.Apply(updateMipmaps: withMipmaps, makeNoLongerReadable: false); + return tex; + } + + private static Texture2D CreateProceduralNormalTexture(int width, int height) + { + var tex = new Texture2D(width, height, GraphicsFormat.R8G8B8A8_UNorm, TextureCreationFlags.None); + var pixels = new Color32[width * height]; + for (int y = 0; y < height; y++) + { + float v = height > 1 ? (float)y / (height - 1) : 0f; + for (int x = 0; x < width; x++) + { + float u = width > 1 ? (float)x / (width - 1) : 0f; + float nx = Mathf.Sin(u * 16f * Mathf.PI) * 0.45f + (u - 0.5f) * 0.5f; + float ny = Mathf.Cos(v * 16f * Mathf.PI) * 0.45f + (v - 0.5f) * 0.5f; + float nz = Mathf.Sqrt(Mathf.Max(0.05f, 1f - nx * nx - ny * ny)); + Vector3 n = new Vector3(nx, ny, nz).normalized; + pixels[y * width + x] = new Color32( + (byte)Mathf.Clamp(Mathf.RoundToInt((n.x * 0.5f + 0.5f) * 255f), 0, 255), + (byte)Mathf.Clamp(Mathf.RoundToInt((n.y * 0.5f + 0.5f) * 255f), 0, 255), + (byte)Mathf.Clamp(Mathf.RoundToInt((n.z * 0.5f + 0.5f) * 255f), 0, 255), + 255); + } + } + tex.SetPixels32(pixels); + tex.Apply(updateMipmaps: false, makeNoLongerReadable: false); + return tex; + } + + private static Texture2D CreateProceduralHdrTexture(int width, int height) + { + var tex = new Texture2D(width, height, GraphicsFormat.R16G16B16A16_SFloat, TextureCreationFlags.None); + var pixels = new Color[width * height]; + for (int y = 0; y < height; y++) + { + float v = height > 1 ? (float)y / (height - 1) : 0f; + for (int x = 0; x < width; x++) + { + float u = width > 1 ? (float)x / (width - 1) : 0f; + float hotspot = Mathf.Exp(-((u - 0.5f) * (u - 0.5f) + (v - 0.5f) * (v - 0.5f)) * 24f); + pixels[y * width + x] = new Color( + 0.1f + u * 2.0f + hotspot * 14.0f, + 0.05f + v * 1.5f + hotspot * 10.0f, + 0.2f + (1f - u) * 1.2f + hotspot * 6.0f, + 1f); + } + } + tex.SetPixels(pixels); + tex.Apply(updateMipmaps: false, makeNoLongerReadable: false); + return tex; + } + + private static bool HasFlag(string flag) + { + string[] args = Environment.GetCommandLineArgs(); + for (int i = 0; i < args.Length; i++) + { + if (string.Equals(args[i], flag, StringComparison.OrdinalIgnoreCase)) + return true; + } + return false; + } + + private static string GetArgValue(string name, string defaultValue) + { + string[] args = Environment.GetCommandLineArgs(); + for (int i = 0; i < args.Length - 1; i++) + { + if (string.Equals(args[i], name, StringComparison.OrdinalIgnoreCase)) + return args[i + 1]; + } + return defaultValue; + } + + private static int GetIntArg(string name, int defaultValue) + { + string raw = GetArgValue(name, null); + return !string.IsNullOrEmpty(raw) && int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out int v) + ? v + : defaultValue; + } +} diff --git a/Assets/Scripts/AstcPlayerBenchmarkRunner.cs.meta b/Assets/Scripts/AstcPlayerBenchmarkRunner.cs.meta new file mode 100644 index 0000000..6ff4af0 --- /dev/null +++ b/Assets/Scripts/AstcPlayerBenchmarkRunner.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 8c4e1a9d3f524b70a1c8e2f74d63a915 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/Assets/Scripts/Sample.cs b/Assets/Scripts/Sample.cs index 7efba93..77488ac 100644 --- a/Assets/Scripts/Sample.cs +++ b/Assets/Scripts/Sample.cs @@ -5,32 +5,52 @@ public class Sample : MonoBehaviour { /// - /// input texture should be read/write enabled and uncompressed + /// Input texture (CPU backend requires Read/Write enabled; GPU backend also supports non-readable textures). /// public Texture2D inputTexture; public Texture2D outputTexture; + public BlockSize blockSize = BlockSize.ASTC_6x6; + public CompressQuality quality = CompressQuality.Fast; + public EncodeBackend backend = EncodeBackend.Auto; + + private bool m_OwnsOutputTexture; void Start() { - using (AstcRaw raw = inputTexture.CompressTexture(TextureType.Default, BlockSize.ASTC_6x6, CompressQuality.Fast)) + if (inputTexture == null) + return; + + outputTexture = inputTexture.CompressToTexture( + TextureType.Default, + blockSize, + quality, + includeMipmaps: inputTexture.mipmapCount > 1, + backend: backend); + m_OwnsOutputTexture = outputTexture != null; + + byte[] fileData = inputTexture.EncodeToASTC(TextureType.Default, blockSize, quality, backend: backend); + if (fileData != null) { - if(raw != null) + string outputDir = Application.isEditor ? Application.dataPath : Application.persistentDataPath; + string filePath = Path.Combine(outputDir, "outputTexture.astc"); + try { - raw.ThrowIfDisposed(); - - outputTexture = new Texture2D(inputTexture.width, inputTexture.width, TextureFormat.ASTC_6x6, inputTexture.mipmapCount > 0, false); - outputTexture.name = inputTexture.name; - outputTexture.LoadRawTextureData(raw); - outputTexture.Apply(true, true); + File.WriteAllBytes(filePath, fileData); + } + catch (IOException ex) + { + Debug.LogError($"Failed to write ASTC file to '{filePath}': {ex.Message}"); } } + } - byte[] fileData = inputTexture.EncodeToASTC(); - string filePath = Path.Combine(Application.dataPath, "outputTexture.astc"); - using (FileStream fs = File.OpenWrite(filePath)) + void OnDestroy() + { + if (m_OwnsOutputTexture && outputTexture != null) { - fs.Write(fileData); - fs.Close(); + Destroy(outputTexture); + outputTexture = null; + m_OwnsOutputTexture = false; } } } diff --git a/Assets/outputTexture.astc b/Assets/outputTexture.astc deleted file mode 100644 index 9382b5e..0000000 Binary files a/Assets/outputTexture.astc and /dev/null differ diff --git a/Assets/outputTexture.astc.meta b/Assets/outputTexture.astc.meta deleted file mode 100644 index 2c580d1..0000000 --- a/Assets/outputTexture.astc.meta +++ /dev/null @@ -1,19 +0,0 @@ -fileFormatVersion: 2 -guid: 8be5a4c23d2b9124098b606bcc4a8b06 -IHVImageFormatImporter: - externalObjects: {} - textureSettings: - serializedVersion: 2 - filterMode: 1 - aniso: 1 - mipBias: 0 - wrapU: 0 - wrapV: 0 - wrapW: 0 - isReadable: 0 - sRGBTexture: 1 - streamingMipmaps: 0 - streamingMipmapsPriority: 0 - userData: - assetBundleName: - assetBundleVariant: diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..190de04 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 overflowu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index a89c4e5..26e846b 100644 --- a/README.md +++ b/README.md @@ -1,276 +1,226 @@ # Runtime ASTC Encoder for Unity -一个面向 Unity 的**运行时 ASTC 纹理压缩库**(Unity Package: `com.aperture.astcenc`),基于 ARM 官方开源的 [astc-encoder](https://github.com/ARM-software/astc-encoder) 交叉编译原生库,通过 C# **P/Invoke** 调用原生编码器,支持在移动端(iOS / Android)及编辑器(Windows / macOS)运行时将未压缩的 `Texture2D` 实时压缩为 ASTC 格式或导出为标准 `.astc` 文件。 +**English** | [简体中文](README_CN.md) + +[![Verify Shaders & Metadata](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/workflows/verify-shaders-and-code.yml/badge.svg)](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/workflows/verify-shaders-and-code.yml) +[![Unity Multi-Platform E2E](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/workflows/unity-multiplatform-e2e.yml/badge.svg)](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/workflows/unity-multiplatform-e2e.yml) +[![Build Native Plugins](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/workflows/build-native-plugins.yml/badge.svg)](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/workflows/build-native-plugins.yml) +![Unity 2021.3+](https://img.shields.io/badge/Unity-2021.3%2B-black?logo=unity) +![UPM v2.3.0](https://img.shields.io/badge/UPM-v2.3.0-blue) +![astc-encoder v5.7.1](https://img.shields.io/badge/astc--encoder-v5.7.1-informational) +[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](Assets/ASTC%20Encoder/LICENSE.md) + +A production-ready **runtime ASTC texture compression package** for Unity (`com.aperture.astcenc`), combining a **real-time GPU Compute Shader encoder** and a **native CPU encoder** (ARM [astc-encoder](https://github.com/ARM-software/astc-encoder) `v5.7.1`) behind a single unified `Encoder` API. --- -## 核心特性 +## Why Runtime ASTC Encoder? -- **运行时动态压缩**:无需依赖离线导入管线,可在运行时对动态生成或网络下载的 `Texture2D` 执行 ASTC 压缩,显著降低移动端显存占用。 -- **三种使用形态**: - - 原地压缩并上传 GPU(`Texture2D.Compress`) - - 获取非托管原始 ASTC 数据缓冲(`Texture2D.CompressTexture` → `AstcRaw`) - - 导出带标准 16 字节文件头的 `.astc` 字节数组(`Texture2D.EncodeToASTC`) -- **丰富的输入格式支持**:支持 24 种未压缩 `GraphicsFormat`,涵盖 **LDR(8-bit UNorm / sRGB、16-bit UNorm)** 与 **HDR(16-bit / 32-bit Float)**。 -- **贴图类型与通道自动适配**: - - 普通贴图(`TextureType.Default`):自动处理 `BGRA` 通道重排,对四通道含 Alpha 贴图自动启用 `UseAlphaWeight` 误差加权。 - - 法线贴图(`TextureType.Normal`):自动启用 `MapNormal` 角度误差优化,并采用 `GGGR` 通道重排(与 Unity 法线压缩布局一致)。 -- **完整 Mipmap 链支持**:自动计算每一级 Mipmap 的 ASTC 块数量并逐级压缩,合并为连续的原生内存块供 Unity 直接加载。 -- **零 `unsafe` 代码**:程序集配置 `allowUnsafeCode: false`,全部通过 `Marshal` 与 `NativeArray` 安全地完成托管与非托管内存交互,并通过 `IDisposable`(`AstcRaw` / `AstcHeader`)管理原生内存释放。 +- **Cut Runtime VRAM by 75–97%**: Compress downloaded UGC, procedural textures, avatars, or `RenderTexture` captures directly into ASTC (`4x4`–`12x12`) on device instead of keeping uncompressed RGBA32 in memory. +- **True Zero-Readback GPU Pipeline**: Encode `Texture2D` (including non-readable) and `RenderTexture` — with optional **single-`CommandBuffer` GPU mipmap generation** — straight into hardware ASTC textures via `CommandBuffer.CopyTexture`, including non-multiple dimensions and full mipmap chains. +- **Unified Dual-Backend (`Auto` / `Gpu` / `Cpu`)**: Defaults to `EncodeBackend.Auto`, preferring GPU when supported and falling back seamlessly to pooled native `astc-encoder` on CPU. +- **Built for Production**: Includes a frame-budgeted priority scheduler (`AstcCompressionQueue`), standard KTX v1 container & atomic disk cache (`AstcKtxContainer` / `AstcDiskCache`), zero-allocation raw buffer encoding (`CompressRawPixelsInto`), and an Editor Quality Inspector. --- -## 支持平台与原生库 +## CPU vs. GPU Backend -预编译的 `astc-encoder` 原生库位于 `Assets/ASTC Encoder/Plugins/` 目录: +| Dimension | GPU Backend (`EncodeBackend.Gpu`) | CPU Backend (`EncodeBackend.Cpu`) | +| :--- | :--- | :--- | +| **Best For** | Real-time `RenderTexture`, virtual textures, dynamic atlases, non-readable textures | Offline-grade quality, background UGC compression, software ASTC decompression | +| **Input Requirements** | Any 2D `Texture2D` (no `isReadable` needed) or non-MSAA `RenderTexture` | Readable `Texture2D` (`isReadable == true`) or raw `NativeArray` / `byte[]` | +| **Block Sizes & Formats** | All 6 (`4x4`–`12x12`), LDR / sRGB / Normal (`GGGR`) / HDR (`CEM 11/14/15`) | All 6 (`4x4`–`12x12`), 24 `GraphicsFormat`s (8/16-bit LDR, 16/32-bit HDR, Normal) | +| **Quality Range** | Real-time `Fast` → `Medium` (Dual-Plane + refit) → `Thorough` (2-Partition) | Full ARM `astc-encoder v5.7.1` range (`Fastest` ~ `Exhaustive`) | +| **CPU Readback** | **Zero readback** via `CopyTexture` (or non-blocking `AsyncGPUReadback` when bytes are requested) | Runs on worker threads / Unity Job System with pooled `AstcContext` | +| **GPU Requirement** | Compute Shaders + `R32G32B32A32_UInt` UAV | None (works everywhere native binaries are present) | -| 平台 | 架构 / 环境 | 原生库文件 | P/Invoke `LibraryName` | SIMD 加速 | -| :--- | :--- | :--- | :--- | :--- | -| **iOS** | ARM64(静态库) | `Plugins/iOS/libastcenc-neon-static.a` | `__Internal` | ARM NEON | -| **Android** | `arm64-v8a` | `Plugins/Android/arm64-v8a/libastcenc-neon-shared.so` | `libastcenc-neon-shared` | ARM NEON | -| **Android** | `armeabi-v7a` | `Plugins/Android/armeabi-v7a/libastcenc-none-shared.so` | *(见下方说明)* | None | -| **macOS Editor** | Editor / OSXUniversal | `Plugins/Mac/libastcenc-shared.dylib` | `libastcenc-shared` | — | -| **Windows Editor** | x86_64 | `Plugins/x64/astcenc-sse4.1-shared.dll` | `astcenc-sse4.1-shared.dll` | SSE4.1 | +--- -> **说明**: -> 1. 当前 `astcenc_api.cs` 中 Android 平台的 `LibraryName` 固定为 `"libastcenc-neon-shared"`,对应 `arm64-v8a` 的 `.so`;如需在 `armeabi-v7a` 设备上运行,请统一 `.so` 命名或在 `astcenc_api.cs` 中根据架构区分库名。 -> 2. 当前 `astcenc_api.cs` 中的条件编译宏仅覆盖了 `UNITY_IOS && !UNITY_EDITOR`、`UNITY_ANDROID && !UNITY_EDITOR`、`UNITY_EDITOR_OSX` 和 `UNITY_EDITOR_WIN`,不包含桌面 Standalone 构建宏。 +## Installation ---- +> **Requirements**: Unity **2021.3+** and **Git LFS** (prebuilt native binaries are stored in LFS). -## 环境要求与安装 +### Option 1: Unity Package Manager (Recommended) -- **Unity 版本**:`2021.3` 及以上(示例工程版本:`2021.3.6f1c1`) -- **Git LFS**:仓库中的预编译原生库(`.dll` / `.so` / `.a` / `.dylib`)与示例贴图(`.png`)由 **Git LFS** 管理,克隆仓库前请确保已安装并启用 Git LFS: +In Unity, open **Window → Package Manager → `+` → Add package from git URL...**: -```bash -git lfs install -git clone https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity.git +```text +https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity.git?path=/Assets/ASTC%20Encoder#v2.3.0 ``` -### 集成到现有项目 +*(Omit `#v2.3.0` to track the latest `master` branch.)* -`Assets/ASTC Encoder/` 目录本身是一个标准的 Unity Package(`com.aperture.astcenc`): +### Option 2: Local Clone / Direct Copy -- **方式一(UPM 本地 / Git 引入)**:在 Unity Package Manager 中选择 *Add package from disk...* 并指向 `Assets/ASTC Encoder/package.json`,或通过 Git URL 引入子目录: - ``` - https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity.git?path=/Assets/ASTC%20Encoder - ``` -- **方式二(直接拷贝)**:将 `Assets/ASTC Encoder` 整个目录复制到目标项目的 `Assets/` 下即可。 +```bash +git lfs install +git clone --recurse-submodules https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity.git +``` ---- +Point UPM's **Add package from disk...** to `Assets/ASTC Encoder/package.json`, or copy `Assets/ASTC Encoder/` into your project's `Assets/` folder. Its `Aperture.Astcenc.Runtime.asmdef` isolates `allowUnsafeCode` without affecting your host project. -## 快速开始 +--- -> **前置条件**:待压缩的输入 `Texture2D` 必须开启 **Read/Write Enabled**,且格式为受支持的**未压缩** `GraphicsFormat`(可通过 `Encoder.IsSupport(texture)` 在运行时检查)。 +## Quick Start -### 1. 原地压缩纹理(推荐) +All public APIs live in `Aperture.Astcenc.Runtime`. -直接将可读的未压缩 `Texture2D` 重新初始化并替换为 ASTC 格式,同时上传 GPU: +### 1. One-Shot Compression (Auto GPU → CPU Fallback) ```csharp using Aperture.Astcenc.Runtime; using UnityEngine; -public void CompressInPlace(Texture2D texture) +public Texture2D CompressTexture(Texture source) { - if (!Encoder.IsSupport(texture)) - { - Debug.LogError("Texture is not readable or format is unsupported."); - return; - } + if (!Encoder.IsSupport(source)) + return null; - bool ok = texture.Compress( + // Defaults to EncodeBackend.Auto (zero-readback GPU CopyTexture when supported) + return source.CompressToTexture( textureType: TextureType.Default, blockSize: BlockSize.ASTC_6x6, quality: CompressQuality.Fast, - makeNoLongerReadable: true - ); + includeMipmaps: true); } ``` -### 2. 压缩为原始数据 `AstcRaw` 并创建新纹理 - -适合希望保留原纹理或需要手动控制目标 `Texture2D` 生命周期的场景(务必使用 `using` 释放非托管内存): +### 2. Non-Blocking Async Compression (Mobile Recommended) ```csharp +using System.Threading.Tasks; using Aperture.Astcenc.Runtime; using UnityEngine; -public Texture2D CompressToNewTexture(Texture2D inputTexture) +public async Task CompressAsync(Texture source) { - using (AstcRaw raw = inputTexture.CompressTexture( - TextureType.Default, - BlockSize.ASTC_6x6, - CompressQuality.Fast)) - { - if (raw == null) - return null; - - Texture2D outputTexture = new Texture2D( - inputTexture.width, - inputTexture.height, - TextureFormat.ASTC_6x6, - inputTexture.mipmapCount > 1, - false); - - outputTexture.name = inputTexture.name; - outputTexture.LoadRawTextureData(raw); - outputTexture.Apply(true, true); - return outputTexture; - } + return await source.CompressToTextureAsync( + textureType: TextureType.Default, + blockSize: BlockSize.ASTC_6x6, + quality: CompressQuality.Fast, + includeMipmaps: true); } ``` -### 3. 编码并保存为 `.astc` 文件 +> For high-volume runtime streaming, use `AstcCompressionQueue` to enforce `MaxGpuTexelsPerFrame`, `MaxConcurrentCpuTasks`, priority scheduling, and single-`CommandBuffer` GPU batching. + +### 3. Zero-Readback GPU Encoding + Mipmaps / `CommandBuffer` Atlas Updates ```csharp -using System.IO; using Aperture.Astcenc.Runtime; using UnityEngine; +using UnityEngine.Rendering; -public void SaveAsAstcFile(Texture2D inputTexture, string outputPath) +public Texture2D CompressRenderTextureWithMips(RenderTexture rt) { - byte[] fileData = inputTexture.EncodeToASTC( - TextureType.Default, - BlockSize.ASTC_6x6, - CompressQuality.Medium); - - if (fileData != null) - { - File.WriteAllBytes(outputPath, fileData); - } + // Generates mipmaps and encodes every mip on GPU in a single CommandBuffer (zero CPU readback) + var options = AstcCompressOptions.Default; + options.BlockSize = BlockSize.ASTC_6x6; + options.Quality = CompressQuality.Fast; + options.GenerateMipmaps = true; + options.Backend = EncodeBackend.Gpu; + + return rt.CompressToTexture(options); +} + +public void UpdateAtlasTile(CommandBuffer cmd, Texture tileSrc, Texture2D astcAtlas, int destX, int destY) +{ + Encoder.Encode(cmd, tileSrc, astcAtlas, TextureType.Default, BlockSize.ASTC_4x4, CompressQuality.Fast, + sourceMip: 0, destMip: 0, destX: destX, destY: destY); } ``` -仓库中附带了完整示例场景 `Assets/Scenes/SampleScene.unity` 及示例脚本 `Assets/Scripts/Sample.cs`,可直接打开运行验证。 +--- + +## Supported Platforms + +| Platform | CPU Native (`astc-encoder v5.7.1`) | GPU Compute Backend | Notes | +| :--- | :--- | :--- | :--- | +| **iOS** (12.0+) | ARM64 NEON static (`__Internal`) | Metal | `Plugins/iOS/libastcenc-neon-static.a` prebuilt; CI also builds Device+Simulator `astcenc.xcframework` | +| **Android** (API 21+) | `arm64-v8a` (NEON) & `armeabi-v7a` (NONE) | Vulkan / GLES 3.1+ | `c++_static`, 16 KB page aligned, auto 32/64-bit dispatch | +| **macOS** (11.0+) | Universal (`arm64` NEON + `x86_64` SSE4.1 + `x86_64h` AVX2) | Metal | Editor & Standalone | +| **Windows x64** | **AVX2** + **SSE4.1** (runtime auto-dispatch) | D3D11 / D3D12 | Both DLLs prebuilt in `Plugins/x64/`, static `/MT` | +| **Linux x64** | SSE4.1 (CI artifact / local build script) | Vulkan / OpenGL | Built by GitHub Actions or `.github/scripts/build-linux-astcenc.sh` | +| **WebGL / Others** | Graceful fallback (`IsCpuSupported == false`) | If Compute supported | Compiles cleanly with no native plugin required | --- -## API 参考 +## Performance Benchmarks + + +Measured automatically via GitHub Actions on **`Apple Paravirtual device` (Metal) + `Apple M1 (Virtual)` (3 cores) / Unity `2021.3.6f1`** (Release Standalone Player, warmup + multi-iteration median): + +#### GPU Compute vs. CPU Encoding (`1024×1024` RGBA8) -所有对外 API 位于命名空间 `Aperture.Astcenc.Runtime` 下。 +| Block Size | Quality | GPU Median (ms) | CPU Median (ms) | GPU Speedup | GPU / CPU PSNR | VRAM Saved | +| :--- | :--- | ---: | ---: | ---: | ---: | ---: | +| **ASTC 4x4** | `Fast` | 7.66 | 253.41 | **33.1×** | 48.9 / 49.0 dB | -75.0% | +| **ASTC 4x4** | `Medium` | 41.00 | 519.59 | **12.7×** | 46.4 / 50.2 dB | -75.0% | +| **ASTC 6x6** | `Fast` | 20.34 | 371.75 | **18.3×** | 29.3 / 41.7 dB | -88.8% | +| **ASTC 6x6** | `Medium` | 57.49 | 876.38 | **15.2×** | 32.6 / 43.2 dB | -88.8% | +| **ASTC 8x8** | `Fast` | 8.51 | 836.19 | **98.2×** | 43.4 / 46.0 dB | -93.8% | +| **ASTC 8x8** | `Medium` | 37.02 | 1848.60 | **49.9×** | 44.1 / 47.9 dB | -93.8% | +| **ASTC 12x12** | `Fast` | 10.85 | 710.89 | **65.5×** | 24.7 / 27.8 dB | -97.2% | +| **ASTC 12x12** | `Medium` | 30.73 | 1254.79 | **40.8×** | 25.3 / 30.1 dB | -97.2% | -### `Encoder`(`Texture2D` 扩展方法) +#### Key Runtime Highlights -| 方法 | 说明 | -| :--- | :--- | -| `Encoder.IsSupport(Texture texture)` | 检查纹理是否满足 `isReadable` 且 `graphicsFormat` 受支持 | -| `Texture2D.Compress(textureType, blockSize, quality, makeNoLongerReadable)` | 压缩纹理并调用 `Reinitialize`、`LoadRawTextureData`、`Apply` 完成原地替换 | -| `Texture2D.CompressTexture(textureType, blockSize, quality)` | 将纹理所有 Mipmap 压缩至非托管内存,返回 `AstcRaw`(需调用 `Dispose()`) | -| `Texture2D.LoadRawTextureData(AstcRaw raw)` | 将 `AstcRaw` 中的压缩数据直接加载到目标 `Texture2D` | -| `Texture2D.EncodeToASTC(textureType, blockSize, quality)` | 压缩纹理并拼接 16 字节标准 ASTC 文件头,返回托管 `byte[]` | +| Scenario | Median / Throughput | GC Alloc | Notes | +| :--- | :--- | ---: | :--- | +| GPU Zero-Readback `CompressToTexture` (`1024×1024 6x6 Fast`) | **2.70 ms** (388.7 MP/s) | 0.0 KB | Direct `CopyTexture`, zero CPU readback | +| Single-`CommandBuffer` GPU MipGen + Encode (`1024×1024+Mips`) | **0.75 ms** (1861.7 MP/s) | 0.0 KB | Full 11-mip chain generated & encoded on GPU | +| Normal Map GGGR Encoding (`512×512 6x6 Medium`) | GPU **19.26 ms** vs CPU 319.21 ms | 0.0 KB | Mean angular error: GPU 0.27° vs CPU 0.15° | +| Zero-Alloc `CompressRawPixelsInto` (`512×512 6x6 Fast`) | **196.09 ms** (1.3 MP/s) | **4096 B** | Caller-owned `NativeArray` + `AstcContextPool` | +| KTX Disk Cache `AstcDiskCache.TryLoad` (`512×512+Mips`) | **0.66 ms** | 124.8 KB | Compress once, instant load on subsequent launches | -### 枚举与配置参数 +#### Cross-Platform Native CPU SIMD (`astc-encoder v5.7.1`, `512×512` RGBA8 `ASTC_6x6`) -- **`TextureType`**:`Default`(普通颜色贴图)、`Normal`(法线贴图) -- **`BlockSize`**(每块固定 16 字节,块越大压缩率越高): - - `ASTC_4x4` (8.00 bpp) / `ASTC_5x5` (5.12 bpp) / `ASTC_6x6` (3.56 bpp) / `ASTC_8x8` (2.00 bpp) / `ASTC_10x10` (1.28 bpp) / `ASTC_12x12` (0.89 bpp) -- **`CompressQuality`**(映射到 `astcenc` 质量参数 `0 ~ 100`): - - `Fastest` (`0`) / `Fast` (`10`) / `Medium` (`60`) / `Thorough` (`98`) / `VeryThorough` (`99`) / `Exhaustive` (`100`) -- **`CodecFlags`**:映射 `astcenc` 的编码标志位(`MapNormal`、`UseAlphaWeight`、`UsePerceptual`、`DecompressOnly`、`SelfDecompressOnly`、`MapRGBM`) +| Platform / CPU | ISA | Threads | `Fast` (ms) | `Medium` (ms) | `Fast` MP/s | Decompress (ms) | +| :--- | :--- | ---: | ---: | ---: | ---: | ---: | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `AVX2` | 4 | 40.04 | 173.18 | 6.55 | 1.28 | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `SSE4.1` | 4 | 43.90 | 180.55 | 5.97 | 1.87 | +| Darwin arm64 (`Apple M1 (Virtual)`) | `ARM64_NEON` | 3 | 34.68 | 154.93 | 7.56 | 1.51 | +| Linux x86_64 (`AMD EPYC 7763 64-Core Processor`) | `SSE4.1` | 4 | 50.48 | 197.06 | 5.19 | 2.18 | -### 支持的输入格式与目标格式映射 +> Provenance: Commit `d3223a5` · 2026-11-28 · [Full Benchmark Matrix & Regression Baseline (docs/Benchmarks.md)](docs/Benchmarks.md) · [Actions Run](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/runs/46153027417) + -| 输入 `GraphicsFormat` 类别 | 支持的具体格式 | `astcenc` 色彩配置 | 内部传输数据类型 | 目标 ASTC `GraphicsFormat` | -| :--- | :--- | :--- | :--- | :--- | -| **LDR 8-bit sRGB** | `R8` / `R8G8` / `R8G8B8` / `R8G8B8A8` / `B8G8R8` / `B8G8R8A8` (`_SRGB`) | `ASTCENC_PRF_LDR_SRGB` | `ASTCENC_TYPE_U8` | `RGBA_ASTC{N}X{N}_SRGB` | -| **LDR 8-bit Linear** | `R8` / `R8G8` / `R8G8B8` / `R8G8B8A8` / `B8G8R8` / `B8G8R8A8` (`_UNorm`) | `ASTCENC_PRF_LDR` | `ASTCENC_TYPE_U8` | `RGBA_ASTC{N}X{N}_UNorm` | -| **LDR 16-bit Linear** | `R16` / `R16G16` / `R16G16B16` / `R16G16B16A16` (`_UNorm`) | `ASTCENC_PRF_LDR` | `ASTCENC_TYPE_F16` *(归一化转换)* | `RGBA_ASTC{N}X{N}_UNorm` | -| **HDR 16-bit Float** | `R16` / `R16G16` / `R16G16B16` / `R16G16B16A16` (`_SFloat`) | `ASTCENC_PRF_HDR` | `ASTCENC_TYPE_F16` | `RGBA_ASTC{N}X{N}_UFloat` | -| **HDR 32-bit Float** | `R32` / `R32G32` / `R32G32B32` / `R32G32B32A32` (`_SFloat`) | `ASTCENC_PRF_HDR` | `ASTCENC_TYPE_F32` | `RGBA_ASTC{N}X{N}_UFloat` | +**Run Benchmarks Locally in Unity** (exports JSON / CSV / Markdown to `Logs/AstcBenchmarks/`): +- **Editor Menu**: **Window → ASTC Encoder → Run Performance Benchmark Suite** (or **Run Full Suite** in Benchmark & Inspector) +- **Test Runner**: EditMode `[Category("Performance")]` (`AstcPerformanceBenchmarks`) +- **CLI / Player**: `Unity -batchmode -projectPath . -executeMethod Aperture.Astcenc.Editor.AstcPerformanceBenchmarkRunner.RunAllFromCli -quit` or launch a built Player with `-astc-benchmark -astc-bench-out report.json` --- -## 实现原理与架构 - -项目采用清晰的分层架构,将 Unity `Texture2D` 原始像素数据经由 C# 封装层与 P/Invoke 桥接层传递给原生 `astc-encoder` 库执行压缩: - -```mermaid -flowchart TD - A["Unity Texture2D (未压缩 / 可读)"] --> B["C# 封装层 (Encoder.cs)"] - B --> C["参数推导: BlockSize / Quality / Profile / Swizzle / Flags"] - B --> D["像素提取与补齐 (RawTexutureData.cs + ImageExtensions.cs)"] - C --> E["P/Invoke 绑定层 (NativeAPI/astcenc_api.cs)"] - D --> E - E --> F["原生库 astc-encoder (.a / .so / .dylib / .dll)"] - F --> G["AstcRaw (非托管压缩数据, 含全部 Mipmap)"] - G --> H1["Texture2D.Reinitialize + LoadRawTextureData (运行时使用)"] - G --> H2["拼接 AstcHeader (16B) → .astc 文件"] -``` +## Editor Tools & Samples -### 压缩流程详解 - -1. **编码器配置与上下文初始化(`Encoder.CompressTexture`)** - - 根据 `GraphicsFormat`、`TextureType`、`BlockSize` 和 `CompressQuality` 推导出 `astcenc_profile`、`astcenc_swizzle` 和 `CodecFlags`。 - - 调用 `astcenc_config_init` 填充 `astcenc_config`,再调用 `astcenc_context_alloc` 分配单线程编码上下文(`threadCount = 1`)。 -2. **输出缓冲预分配(`Encoder.CompressRawData`)** - - 遍历全部 `mipmapCount` 级,按每级 `ceil(w / blockX) * ceil(h / blockY) * 16` 字节累加总字节数,一次性通过 `Marshal.AllocHGlobal` 分配连续非托管内存。 -3. **逐级 Mipmap 像素转换与压缩(`RawTexutureData.cs` + `ImageExtensions.cs`)** - - 通过 `Texture2D.GetRawTextureData()` 获取零拷贝 `NativeArray`,按每级像素数做 `NativeSlice` 切片。 - - `astcenc_image` 需要 4 通道交错内存布局;16 种实现了 `IRawData` 的结构体(`R8` ~ `RGBA32F`)负责将单/双/三/四通道像素统一写入非托管 4 通道缓冲(缺失的 RGB 通道补 `0`,缺失的 Alpha 通道补 `1.0` / `0xFF`;16-bit UNorm 通过 `Mathf.FloatToHalf(v / 65535f)` 转为 F16)。 - - 调用 `astcenc_compress_image` 将当前 Mipmap 直接压缩到输出缓冲的对应偏移位置,随后释放临时像素缓冲(`image.Release()`)并重置上下文状态(`astcenc_compress_reset`)。 -4. **资源回收与结果封装** - - 压缩结束后调用 `astcenc_context_free` 释放原生上下文,将输出指针封装为 `AstcRaw` 返回。 - - 若调用 `EncodeToASTC`,则通过 `AstcHeader` 写入标准 16 字节 ASTC 文件头(小端魔数 `0x5CA1AB13` + 3 字节块尺寸 + 3 × 3 字节 24-bit 图像尺寸)并与压缩数据拼接为 `byte[]`。 +- **Benchmark & Quality Inspector**: Open **Window → ASTC Encoder → Benchmark & Inspector** to compare CPU vs. GPU outputs side-by-side with decoded previews, amplified error heatmaps, PSNR / RMSE / Normal angular error, memory savings, and `.ktx` / `.astc` export. +- **EditMode Tests**: Golden cross-decoding NUnit tests are included under `Aperture.Astcenc.Tests`. +- **Sample Scene**: Open `Assets/Scenes/SampleScene.unity` (`Assets/Scripts/Sample.cs`) to switch `EncodeBackend` (`Auto` / `Gpu` / `Cpu`) directly in the Inspector. --- -## 目录结构 +## Documentation -```text -. -├── Assets/ -│ ├── ASTC Encoder/ # Unity Package (com.aperture.astcenc) -│ │ ├── package.json -│ │ ├── LICENSE.md # MIT License -│ │ ├── Third Party Notices.md # ARM astc-encoder Apache-2.0 License -│ │ ├── Plugins/ # 各平台预编译原生库 (Git LFS) -│ │ │ ├── Android/arm64-v8a/libastcenc-neon-shared.so -│ │ │ ├── Android/armeabi-v7a/libastcenc-none-shared.so -│ │ │ ├── iOS/libastcenc-neon-static.a -│ │ │ ├── Mac/libastcenc-shared.dylib -│ │ │ └── x64/astcenc-sse4.1-shared.dll -│ │ └── Runtime/ -│ │ ├── Aperture.Astcenc.Runtime.asmdef -│ │ ├── Encoder.cs # 核心压缩流程与 Texture2D 扩展方法 -│ │ ├── AstcRaw.cs # 非托管 ASTC 压缩数据封装 (IDisposable) -│ │ ├── AstcHeader.cs # 16 字节标准 .astc 文件头封装 (IDisposable) -│ │ ├── ImageExtensions.cs # astcenc_image 非托管内存填充与释放 -│ │ ├── RawTexutureData.cs # 16 种像素格式结构体与 RGBA 扩展写入 -│ │ ├── BlockSize.cs # ASTC 块尺寸枚举 -│ │ ├── CompressQuality.cs # 压缩质量预设枚举 -│ │ ├── TextureType.cs # 贴图类型枚举 (Default / Normal) -│ │ ├── CodecFlags.cs # astcenc 编码标志位枚举 -│ │ └── NativeAPI/ # astcenc C API P/Invoke 声明与结构体映射 -│ │ ├── astcenc_api.cs -│ │ ├── astcenc_config.cs -│ │ ├── astcenc_error.cs -│ │ ├── astcenc_image.cs -│ │ ├── astcenc_profile.cs -│ │ ├── astcenc_swizzle.cs -│ │ ├── astcenc_swz.cs -│ │ └── astcenc_type.cs -│ ├── Resources/ # 示例贴图 (Color.png, Normal.png) -│ ├── Scenes/SampleScene.unity # 示例场景 -│ └── Scripts/Sample.cs # 示例脚本 -├── Packages/ -├── ProjectSettings/ -└── README.md -``` +- **[API Reference](docs/API.md)** — Full `Encoder`, `AstcContext`, `AstcCompressionQueue`, `AstcKtxContainer`, `AstcDiskCache`, `AstcRaw`, 24-format mapping table, and advanced code samples (zero-alloc raw pixels, KTX caching, `.astc` export). +- **[Architecture & Implementation](docs/Architecture.md)** — Dataflow diagram, GPU Compute Shader internals, CPU context pooling & ISA dispatch, and GitHub Actions CI workflows. +- **[Performance Benchmarks](docs/Benchmarks.md)** — Full hardware-verified GPU/CPU matrix and regression baseline (`docs/benchmarks/baseline.json`). +- **[Multi-Platform CI & E2E Guide](docs/CI_E2E_GUIDE.md)** — Setup and execution guide for GameCI EditMode tests and 5-platform end-to-end builds. +- **[Changelog](Assets/ASTC%20Encoder/CHANGELOG.md)** — Version release history for `com.aperture.astcenc`. --- -## 注意事项与已知限制 +## Key Best Practices -- **主线程阻塞**:当前实现为单线程同步压缩(`threadCount = 1`),压缩大尺寸贴图或使用 `Thorough` 以上高质量档位时耗时较长,建议移动端运行时优先选用 `Fastest` 或 `Fast` 档位。 -- **非托管内存管理**:直接调用 `CompressTexture` 返回的 `AstcRaw` 持有 `Marshal.AllocHGlobal` 分配的原生内存,务必通过 `using` 或手动调用 `Dispose()` 及时释放。 -- **GC 开销**:`EncodeToASTC` 会分配托管 `byte[]` 并复制全部压缩数据,不建议在高频逻辑中使用;纯运行时纹理压缩请优先使用 `Compress` 或 `CompressTexture` + `LoadRawTextureData`。 -- **`.astc` 导出与 Mipmap**:标准 `.astc` 容器格式仅描述单层图像尺寸,若只需导出单张 `.astc` 文件,建议输入无 Mipmap 链的纹理。 +- **Dispose Unmanaged Buffers**: Always wrap `AstcRaw` and manually created `AstcContext` instances in `using`. Static CPU entry points automatically pool native contexts (call `Encoder.ReleaseCpuContextPool()` if you need to reclaim pool memory immediately). +- **Warm Up GPU Shaders**: Call `Encoder.PreloadGpu(blockSize)` during loading screens to avoid first-frame shader hitching, and `Encoder.ReleaseGpuCache()` when idle. +- **Alpha Weighting**: Enable `useAlphaWeight: true` for transparent UI/sprites/foliage; keep it `false` (default) for channel-packed maps (ORM / MRAO / masks). +- **Desktop Non-ASTC GPUs**: On Windows D3D11/D3D12 GPUs without hardware ASTC sampling, the GPU backend still exports raw bytes / `.astc` / `.ktx`; in the Unity Editor, `CompressToTexture` automatically uses software preview fallback. +- **Y-Axis Orientation**: Both backends encode in Unity's bottom-up `Texture2D` orientation (`y = 0` at bottom) with no extra flip needed for cameras or `Graphics.Blit`. --- -## 许可证 +## License & Acknowledgments -- 本项目代码采用 **MIT License**,详见 [Assets/ASTC Encoder/LICENSE.md](Assets/ASTC%20Encoder/LICENSE.md)。 -- 底层编码库 [ARM-software/astc-encoder](https://github.com/ARM-software/astc-encoder) 采用 **Apache License 2.0**,详见 [Assets/ASTC Encoder/Third Party Notices.md](Assets/ASTC%20Encoder/Third%20Party%20Notices.md)。 \ No newline at end of file +- Licensed under the **MIT License** — see [LICENSE.md](Assets/ASTC%20Encoder/LICENSE.md). +- CPU backend powered by [ARM-software/astc-encoder](https://github.com/ARM-software/astc-encoder) under the **Apache License 2.0** — see [Third Party Notices.md](Assets/ASTC%20Encoder/Third%20Party%20Notices.md). \ No newline at end of file diff --git a/README_CN.md b/README_CN.md new file mode 100644 index 0000000..19da881 --- /dev/null +++ b/README_CN.md @@ -0,0 +1,226 @@ +# Runtime ASTC Encoder for Unity + +[English](README.md) | **简体中文** + +[![Verify Shaders & Metadata](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/workflows/verify-shaders-and-code.yml/badge.svg)](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/workflows/verify-shaders-and-code.yml) +[![Unity Multi-Platform E2E](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/workflows/unity-multiplatform-e2e.yml/badge.svg)](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/workflows/unity-multiplatform-e2e.yml) +[![Build Native Plugins](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/workflows/build-native-plugins.yml/badge.svg)](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/workflows/build-native-plugins.yml) +![Unity 2021.3+](https://img.shields.io/badge/Unity-2021.3%2B-black?logo=unity) +![UPM v2.3.0](https://img.shields.io/badge/UPM-v2.3.0-blue) +![astc-encoder v5.7.1](https://img.shields.io/badge/astc--encoder-v5.7.1-informational) +[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](Assets/ASTC%20Encoder/LICENSE.md) + +面向 Unity 的**生产级运行时 ASTC 纹理压缩包**(`com.aperture.astcenc`),在统一的 `Encoder` API 下同时集成**实时 GPU Compute Shader 编码器**与**原生 CPU 编码器**(ARM [astc-encoder](https://github.com/ARM-software/astc-encoder) `v5.7.1`)。 + +--- + +## 为什么选择 Runtime ASTC Encoder? + +- **运行时显存直降 75%–97%**:在端侧将下载的 UGC 图片、程序化贴图、捏脸头像或 `RenderTexture` 截图实时压为 ASTC(`4x4`–`12x12`),告别未压缩 RGBA32 显存膨胀。 +- **真正的 GPU 零回读管线**:支持非可读 `Texture2D` 与 `RenderTexture`,可选**单条 `CommandBuffer` 内一体化 GPU Mipmap 生成 + ASTC 编码**,通过 `CommandBuffer.CopyTexture` 直拷至硬件 ASTC 纹理(兼容非整除尺寸与完整 Mipmap 链)。 +- **双后端统一切换(`Auto` / `Gpu` / `Cpu`)**:默认 `EncodeBackend.Auto`,设备支持时优先走 GPU,不支持时无缝回退至带上下文池化的原生 CPU 编码器。 +- **开箱即用的生产配套**:内置帧预算优先级调度队列(`AstcCompressionQueue`)、标准 KTX v1 容器与原子磁盘缓存(`AstcKtxContainer` / `AstcDiskCache`)、零分配原始像素直压(`CompressRawPixelsInto`)以及 Editor 质检窗口。 + +--- + +## CPU 与 GPU 后端选型 + +| 维度 | GPU 后端(`EncodeBackend.Gpu`) | CPU 后端(`EncodeBackend.Cpu`) | +| :--- | :--- | :--- | +| **最适用场景** | 实时 `RenderTexture`、虚拟纹理、动态图集更新、非可读贴图 | 离线级高画质压缩、后台线程 UGC 压缩、CPU 软件解码 | +| **输入要求** | 任意 2D `Texture2D`(无需 `isReadable`)或非 MSAA `RenderTexture` | 可读 `Texture2D`(`isReadable == true`)或原始 `NativeArray` / `byte[]` | +| **块尺寸与格式** | 全部 6 种(`4x4`–`12x12`),LDR / sRGB / Normal(`GGGR`)/ HDR(`CEM 11/14/15`) | 全部 6 种(`4x4`–`12x12`),24 种 `GraphicsFormat`(8/16-bit LDR、16/32-bit HDR、法线) | +| **画质档位** | 实时 `Fast` → `Medium`(Dual-Plane + 端点重拟合)→ `Thorough`(2-Partition) | 完整 ARM `astc-encoder v5.7.1` 档位(`Fastest` ~ `Exhaustive`) | +| **CPU 回读与并发** | `CopyTexture` **零回读**(需字节数据时走非阻塞 `AsyncGPUReadback`) | 后台线程池 / Unity Job System,静态接口自动池化复用 `AstcContext` | +| **GPU 依赖** | Compute Shader + `R32G32B32A32_UInt` UAV | 无(凡提供原生库的平台均可运行) | + +--- + +## 安装 + +> **环境要求**:Unity **2021.3+**,且需启用 **Git LFS**(预编译原生库由 LFS 管理)。 + +### 方式一:Unity Package Manager(推荐) + +在 Unity 中打开 **Window → Package Manager → `+` → Add package from git URL...**: + +```text +https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity.git?path=/Assets/ASTC%20Encoder#v2.3.0 +``` + +*(去掉 `#v2.3.0` 可直接跟踪 `master` 分支最新提交。)* + +### 方式二:本地克隆 / 直接拷贝 + +```bash +git lfs install +git clone --recurse-submodules https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity.git +``` + +在 UPM 中选择 **Add package from disk...** 指向 `Assets/ASTC Encoder/package.json`,或直接将 `Assets/ASTC Encoder/` 拷贝到工程的 `Assets/` 目录。包内 `Aperture.Astcenc.Runtime.asmdef` 独立启用 `allowUnsafeCode`,不影响宿主工程配置。 + +--- + +## 快速上手 + +所有公开 API 位于 `Aperture.Astcenc.Runtime` 命名空间。 + +### 1. 一行代码压缩(默认 Auto:优先 GPU,自动回退 CPU) + +```csharp +using Aperture.Astcenc.Runtime; +using UnityEngine; + +public Texture2D CompressTexture(Texture source) +{ + if (!Encoder.IsSupport(source)) + return null; + + // 默认 EncodeBackend.Auto(移动端支持硬件 ASTC 时走 GPU 零回读 CopyTexture) + return source.CompressToTexture( + textureType: TextureType.Default, + blockSize: BlockSize.ASTC_6x6, + quality: CompressQuality.Fast, + includeMipmaps: true); +} +``` + +### 2. 非阻塞异步压缩(移动端推荐) + +```csharp +using System.Threading.Tasks; +using Aperture.Astcenc.Runtime; +using UnityEngine; + +public async Task CompressAsync(Texture source) +{ + return await source.CompressToTextureAsync( + textureType: TextureType.Default, + blockSize: BlockSize.ASTC_6x6, + quality: CompressQuality.Fast, + includeMipmaps: true); +} +``` + +> 若存在大批量运行时流式加载,推荐使用 `AstcCompressionQueue`,支持 `MaxGpuTexelsPerFrame` 每帧像素预算、`MaxConcurrentCpuTasks` 并发上限、优先级调度与单帧单条 `CommandBuffer` GPU 合批。 + +### 3. GPU 零回读压缩 + Mipmap 生成 / `CommandBuffer` 图集更新 + +```csharp +using Aperture.Astcenc.Runtime; +using UnityEngine; +using UnityEngine.Rendering; + +public Texture2D CompressRenderTextureWithMips(RenderTexture rt) +{ + // 单条 CommandBuffer 内完成 GPU Mipmap 生成 + 全级 ASTC 编码(全程零 CPU 回读) + var options = AstcCompressOptions.Default; + options.BlockSize = BlockSize.ASTC_6x6; + options.Quality = CompressQuality.Fast; + options.GenerateMipmaps = true; + options.Backend = EncodeBackend.Gpu; + + return rt.CompressToTexture(options); +} + +public void UpdateAtlasTile(CommandBuffer cmd, Texture tileSrc, Texture2D astcAtlas, int destX, int destY) +{ + Encoder.Encode(cmd, tileSrc, astcAtlas, TextureType.Default, BlockSize.ASTC_4x4, CompressQuality.Fast, + sourceMip: 0, destMip: 0, destX: destX, destY: destY); +} +``` + +--- + +## 平台支持矩阵 + +| 平台 | CPU 原生后端(`astc-encoder v5.7.1`) | GPU Compute 后端 | 说明 | +| :--- | :--- | :--- | :--- | +| **iOS**(12.0+) | ARM64 NEON 静态库(`__Internal`) | Metal | 已内置 `Plugins/iOS/libastcenc-neon-static.a`;CI 同步产出真机+模拟器 `astcenc.xcframework` | +| **Android**(API 21+) | `arm64-v8a`(NEON)与 `armeabi-v7a`(NONE) | Vulkan / GLES 3.1+ | `c++_static`、16 KB 页对齐、运行时自动 32/64 位分派 | +| **macOS**(11.0+) | Universal(`arm64` NEON + `x86_64` SSE4.1 + `x86_64h` AVX2) | Metal | Editor & Standalone | +| **Windows x64** | **AVX2** + **SSE4.1**(运行时自动分派) | D3D11 / D3D12 | 双 DLL 已内置于 `Plugins/x64/`,静态 `/MT` 运行时 | +| **Linux x64** | SSE4.1(CI 产物 / 本地构建脚本) | Vulkan / OpenGL | 由 GitHub Actions 或 `.github/scripts/build-linux-astcenc.sh` 构建 | +| **WebGL / 其他** | 平滑降级(`IsCpuSupported == false`) | 支持 Compute 时可用 | 无需原生库即可正常编译 | + +--- + +## 性能基准测试 + + +以下数据由 GitHub Actions 在 **`Apple Paravirtual device`(Metal)+ `Apple M1 (Virtual)`(3 核) / Unity `2021.3.6f1`** 上自动实测生成(无 Editor 开销的 Standalone Player,预热 + 多次采样中位数): + +#### GPU Compute vs. CPU 编码对比(`1024×1024` RGBA8) + +| 块尺寸 | 质量 | GPU 耗时 (ms) | CPU 耗时 (ms) | GPU 加速比 | GPU / CPU PSNR | 显存节省 | +| :--- | :--- | ---: | ---: | ---: | ---: | ---: | +| **ASTC 4x4** | `Fast` | 7.66 | 253.41 | **33.1×** | 48.9 / 49.0 dB | -75.0% | +| **ASTC 4x4** | `Medium` | 41.00 | 519.59 | **12.7×** | 46.4 / 50.2 dB | -75.0% | +| **ASTC 6x6** | `Fast` | 20.34 | 371.75 | **18.3×** | 29.3 / 41.7 dB | -88.8% | +| **ASTC 6x6** | `Medium` | 57.49 | 876.38 | **15.2×** | 32.6 / 43.2 dB | -88.8% | +| **ASTC 8x8** | `Fast` | 8.51 | 836.19 | **98.2×** | 43.4 / 46.0 dB | -93.8% | +| **ASTC 8x8** | `Medium` | 37.02 | 1848.60 | **49.9×** | 44.1 / 47.9 dB | -93.8% | +| **ASTC 12x12** | `Fast` | 10.85 | 710.89 | **65.5×** | 24.7 / 27.8 dB | -97.2% | +| **ASTC 12x12** | `Medium` | 30.73 | 1254.79 | **40.8×** | 25.3 / 30.1 dB | -97.2% | + +#### 关键运行时特性实测 + +| 场景 | 中位数耗时 / 吞吐 | GC 分配 | 说明 | +| :--- | :--- | ---: | :--- | +| GPU 零回读 `CompressToTexture` (`1024×1024 6x6 Fast`) | **2.70 ms** (388.7 MP/s) | 0.0 KB | 直拷硬件 ASTC 纹理,无 CPU 回读 | +| GPU 单 CommandBuffer MipGen + 编码 (`1024×1024+Mips`) | **0.75 ms** (1861.7 MP/s) | 0.0 KB | 11 级 Mip 生成与编码一体化完成 | +| 法线贴图 GGGR 编码 (`512×512 6x6 Medium`) | GPU **19.26 ms** vs CPU 319.21 ms | 0.0 KB | 平均角度误差:GPU 0.27° vs CPU 0.15° | +| 原始像素直压 `CompressRawPixelsInto` (`512×512 6x6 Fast`) | **196.09 ms** (1.3 MP/s) | **4096 B** | 复用 NativeArray + `AstcContextPool` | +| KTX 磁盘缓存秒开 `AstcDiskCache.TryLoad` (`512×512+Mips`) | **0.66 ms** | 124.8 KB | 一次压缩,后续启动直传 GPU | + +#### 跨平台原生 CPU 指令集实测(`astc-encoder v5.7.1`,`512×512` RGBA8 `ASTC_6x6`) + +| 平台 / CPU | 指令集(ISA) | 线程 | `Fast` (ms) | `Medium` (ms) | `Fast` 吞吐 | CPU 软解 (ms) | +| :--- | :--- | ---: | ---: | ---: | ---: | ---: | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `AVX2` | 4 | 40.04 | 173.18 | 6.55 | 1.28 | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `SSE4.1` | 4 | 43.90 | 180.55 | 5.97 | 1.87 | +| Darwin arm64 (`Apple M1 (Virtual)`) | `ARM64_NEON` | 3 | 34.68 | 154.93 | 7.56 | 1.51 | +| Linux x86_64 (`AMD EPYC 7763 64-Core Processor`) | `SSE4.1` | 4 | 50.48 | 197.06 | 5.19 | 2.18 | + +> 基准溯源:Commit `d3223a5` · 2026-11-28 · [查看完整全矩阵与基线对比(docs/Benchmarks.md)](docs/Benchmarks.md) · [Actions Run](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/runs/46153027417) + + +**本地在 Unity 中运行完整基准套件**(自动导出 JSON / CSV / Markdown 至 `Logs/AstcBenchmarks/`): +- **Editor 菜单**:**Window → ASTC Encoder → Run Performance Benchmark Suite**(或在 Benchmark & Inspector 窗口点击 **Run Full Suite**) +- **Test Runner**:运行 EditMode `Performance` 分类(`AstcPerformanceBenchmarks`) +- **CLI / Player**:`Unity -batchmode -projectPath . -executeMethod Aperture.Astcenc.Editor.AstcPerformanceBenchmarkRunner.RunAllFromCli -quit`,或对编译出的 Player 传入 `-astc-benchmark -astc-bench-out report.json` + +--- + +## Editor 工具与示例 + +- **可视化对比与质检窗口**:打开 **Window → ASTC Encoder → Benchmark & Inspector**,同屏对比 CPU 与 GPU 解码结果、放大误差热力图、PSNR / RMSE / 法线角度误差与显存节省率,并支持导出 `.ktx` / `.astc`。 +- **单元测试**:内置 EditMode 交叉解码黄金测试套件(`Aperture.Astcenc.Tests`)。 +- **示例场景**:打开 `Assets/Scenes/SampleScene.unity`(`Assets/Scripts/Sample.cs`),可直接在 Inspector 中切换 `EncodeBackend`(`Auto` / `Gpu` / `Cpu`)。 + +--- + +## 进阶文档 + +- **[完整 API 参考(docs/API.md)](docs/API.md)** — `Encoder`、`AstcContext`、`AstcCompressionQueue`、`AstcKtxContainer`、`AstcDiskCache`、`AstcRaw`、24 种输入格式映射表,以及零分配原始像素直压、KTX 磁盘缓存、`.astc` 导出示例。 +- **[架构与实现细节(docs/Architecture.md)](docs/Architecture.md)** — 数据流架构图、GPU Compute Shader 算法与寄存器优化、CPU 上下文池化与指令集分派,以及 GitHub Actions CI 流水线。 +- **[完整性能基准报告(docs/Benchmarks.md)](docs/Benchmarks.md)** — 全矩阵 GPU/CPU 硬件实测数据与回归基线(`docs/benchmarks/baseline.json`)。 +- **[多平台 CI 与端到端测试指南(docs/CI_E2E_GUIDE.md)](docs/CI_E2E_GUIDE.md)** — GameCI EditMode 单元测试与 5 平台端到端构建配置说明。 +- **[更新日志(CHANGELOG.md)](Assets/ASTC%20Encoder/CHANGELOG.md)** — `com.aperture.astcenc` 版本变更记录。 + +--- + +## 使用注意事项 + +- **非托管资源释放**:`AstcRaw` 与手动创建的 `AstcContext` 请务必配合 `using` 或 `Dispose()` 释放;静态 CPU 接口已自动通过 `AstcContextPool` 复用原生上下文(如需立即回收池内存可调用 `Encoder.ReleaseCpuContextPool()`)。 +- **GPU Shader 预热**:建议在加载界面调用 `Encoder.PreloadGpu(blockSize)` 避免首帧编译卡顿,空闲时可调用 `Encoder.ReleaseGpuCache()` 释放引用。 +- **Alpha 权重开关**:透明 UI / 精灵 / 植被贴图建议传 `useAlphaWeight: true`;通道打包贴图(ORM / MRAO / Mask)请保持默认 `false`。 +- **桌面非 ASTC 显卡行为**:Windows D3D11/D3D12 等不支持硬件 ASTC 采样的显卡仍可通过 GPU 后端导出原始字节 / `.astc` / `.ktx`;在 Unity Editor 下 `CompressToTexture` 会自动走软解预览回退。 +- **Y 轴方向约定**:双后端均按 Unity `Texture2D` 自底向上(`y = 0` 在底部)直接编码,相机渲染或 `Graphics.Blit` 得到的 `RenderTexture` 无需额外翻转。 + +--- + +## 开源协议与致谢 + +- 本项目采用 **MIT License** — 详见 [LICENSE.md](Assets/ASTC%20Encoder/LICENSE.md)。 +- CPU 后端基于 [ARM-software/astc-encoder](https://github.com/ARM-software/astc-encoder)(**Apache License 2.0**)— 详见 [Third Party Notices.md](Assets/ASTC%20Encoder/Third%20Party%20Notices.md)。 diff --git a/ThirdParty/astc-encoder b/ThirdParty/astc-encoder new file mode 160000 index 0000000..0affb51 --- /dev/null +++ b/ThirdParty/astc-encoder @@ -0,0 +1 @@ +Subproject commit 0affb51aaf0e0de3a8b038fa32487d59754a1eed diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..ad777bb --- /dev/null +++ b/docs/API.md @@ -0,0 +1,189 @@ +# API Reference + +All public types reside in the `Aperture.Astcenc.Runtime` namespace. + +--- + +## `Encoder` — Unified Entry Point + +All compression methods accept `EncodeBackend` (default `EncodeBackend.Auto`: prefers GPU when supported, falls back to CPU automatically) and also provide `AstcCompressOptions` struct overloads. + +### Capability & Lifecycle + +| Method / Property | Description | +| :--- | :--- | +| `Encoder.IsCpuSupported` | Returns `true` if a native `astc-encoder` binary is available on the current platform | +| `Encoder.IsGpuSupported` | Returns `true` if the device supports Compute Shaders and `R32G32B32A32_UInt` UAV writes | +| `Encoder.SupportsGpuDirectCopy(blockSize, srgb, isHdr)` | Checks whether the GPU supports zero-readback `CopyTexture` into the target ASTC format | +| `Encoder.IsSupport(Texture texture, EncodeBackend backend = EncodeBackend.Auto)` | Validates texture compatibility for the given backend (GPU accepts non-readable `Texture2D` and non-MSAA `RenderTexture`) | +| `Encoder.GetTargetAstcFormat(sourceFormat, blockSize, textureType)` | Resolves the target ASTC `GraphicsFormat` (`TextureType.Normal` always resolves to linear `_UNorm`) | +| `Encoder.PreloadGpu(blockSize)` | Warms up Fast/Full GPU encoder kernels and the GPU mipmap generator | +| `Encoder.ReleaseGpuCache()` | Releases cached Compute Shader references | +| `Encoder.ReleaseCpuContextPool()` | Releases all cached native `AstcContext` instances held by the static CPU pool | + +### Compression & Encoding + +| Method | Description | +| :--- | :--- | +| `Texture.CompressToTexture(..., backend = EncodeBackend.Auto)` | Compresses a 2D `Texture` / `RenderTexture` into a newly allocated ASTC `Texture2D`. Uses zero-readback `CopyTexture` on GPU (including non-multiple dimensions, full mip chains, and `AstcCompressOptions.GenerateMipmaps`) | +| `Texture.CompressToTextureAsync(..., backend = EncodeBackend.Auto)` | Non-blocking version using `AsyncGPUReadback` or background CPU worker threads (supports `CancellationToken`) | +| `Texture2D.Compress(..., backend = EncodeBackend.Auto)` | In-place compression via `Reinitialize` (requires `isReadable == true`; uses GPU zero-readback when `makeNoLongerReadable == true`) | +| `Encoder.Encode(CommandBuffer cmd, source, destination, ...)` | Records GPU ASTC encoding + `CopyTexture` into a `CommandBuffer` (`sourceSlice` / `destSlice`, `sourceMip` / `destMip`, block-aligned `destX` / `destY`) for batching, Async Compute, or Virtual Texture / atlas updates | +| `Texture.CompressTexture(...)` / `CompressTextureAsync(...)` | Compresses all mip levels into unmanaged memory and returns `AstcRaw` (caller must `Dispose()`) | +| `Encoder.CompressCubemap(...)` / `CompressTexture2DArray(...)` | Compresses multi-slice `Cubemap` or `Texture2DArray` assets | +| `Encoder.CompressRawPixels(...)` / `CompressRawPixelsAsync(...)` | Compresses raw `NativeArray` or `byte[]` pixel buffers directly on CPU | +| `Encoder.CompressRawPixelsInto(..., NativeArray destination)` | Zero-allocation CPU compression directly into a caller-owned `NativeArray` (uses pooled `AstcContext`) | +| `Texture.EncodeToASTC(...)` / `EncodeToASTCAsync(...)` | Encodes mip 0 only and prepends the standard 16-byte `.astc` file header, returning `byte[]` | +| `Texture.EncodeToKTX(...)` / `EncodeToKTXAsync(...)` | Encodes all mip levels into a standard KTX v1 container (`byte[]`) preserving UNorm/sRGB/HDR metadata | + +### Decoding & Loading + +| Method | Description | +| :--- | :--- | +| `Texture2D.LoadRawTextureData(AstcRaw raw)` | Uploads unmanaged `AstcRaw` directly into a `Texture2D` without managed copies | +| `Encoder.LoadFromKTX(byte[] ktxData, ...)` | Parses a KTX v1 container and creates an ASTC `Texture2D` (automatically falls back to CPU software decompression on non-ASTC devices) | +| `Encoder.Decompress(...)` / `DecompressToTexture(...)` / `DecompressAstcFile(...)` | CPU software decompression of raw ASTC blocks or `.astc` file bytes via native `astc-encoder` | + +--- + +## High-Level Production Utilities + +### `AstcCompressionQueue` +Frame-budgeted scheduler for runtime streaming and UGC pipelines: +- Priority queues (`High`, `Normal`, `Low`) +- `MaxGpuTexelsPerFrame` GPU budget and `MaxConcurrentCpuTasks` concurrency cap +- Single-`CommandBuffer` per-frame GPU batching +- Pooled native `AstcContext` with safe `parentContext` table sharing + +### `AstcKtxContainer` & `AstcDiskCache` +- **`AstcKtxContainer`**: Reads and writes standard KTX v1 files (`Encode`, `TryDecode`, `LoadTexture`) with full mipmap chains and color-space/HDR metadata. +- **`AstcDiskCache`** (`static class`): Persistent on-disk KTX v1 cache (`TryLoad`, `TryLoadAsync`, `CompressAndSaveAsync`, `LoadOrCompressAsync`) using atomic `File.Replace` writes and zero-copy `AstcRaw` uploads. + +--- + +## `AstcContext` (Explicit Reusable CPU Context) + +All static CPU `Encoder` APIs already reuse pooled native contexts automatically via `AstcContextPool`. Use `AstcContext` directly when you want explicit lifetime ownership or custom `parentContext` sharing across workers: + +| Member | Description | +| :--- | :--- | +| `AstcContext.Create(format, textureType, blockSize, quality, threadCount, useAlphaWeight, usePerceptual, alphaScaleRadius, parentContext)` | Allocates a reusable compression context (`threadCount <= 0` auto-selects worker threads) | +| `AstcContext.CreateDecompressor(blockSize, srgb, isHdr, threadCount)` | Allocates a lightweight `DecompressOnly` context for CPU software decoding | +| `context.CompressTexture(texture, textureType)` | Synchronously compresses using this context | +| `context.CompressTextureAsync(texture, textureType, cancellationToken)` | Asynchronously compresses using this context (keep `context` alive until the `Task` completes) | +| `context.Dispose()` | Thread-safely frees the native `astcenc_context` | + +--- + +## `AstcRaw` (Unmanaged Compressed Buffer) + +- `Length`: Total compressed byte count +- `IsDisposed`: Whether the buffer has been freed +- `CopyTo(byte[] destination, int destinationOffset = 0)` / `ToArray()`: Copies bytes into a managed array +- `Dispose()`: Thread-safely frees unmanaged memory (always use `using`) + +--- + +## Configuration & Enums + +- **`AstcCompressOptions`**: Unified struct with `Default`, `NormalMap`, and `Transparent` presets; exposes `GenerateMipmaps`, `UseAlphaWeight`, `UsePerceptual`, `AlphaScaleRadius`, `UseUnityJobSystem`, and `ThreadCount`. +- **`EncodeBackend`**: `Auto` (default), `Gpu`, `Cpu`. +- **`TextureType`**: `Default` (color / ORM), `Normal` (`GGGR` swizzle, always linear `_UNorm` output). +- **`BlockSize`** (16 bytes per block, all 6 supported on both CPU and GPU): + - `ASTC_4x4` (8.00 bpp) · `ASTC_5x5` (5.12 bpp) · `ASTC_6x6` (3.56 bpp) · `ASTC_8x8` (2.00 bpp) · `ASTC_10x10` (1.28 bpp) · `ASTC_12x12` (0.89 bpp) +- **`CompressQuality`**: + - **CPU**: `Fastest` (`0`), `Fast` (`10`), `Medium` (`60`), `Thorough` (`98`), `VeryThorough` (`99`), `Exhaustive` (`100`) + - **GPU**: `Fastest`/`Fast` → lightweight `ASTC_FAST_ONLY` kernel; `Medium` → multi-BlockMode + anisotropic grids + dynamic-CCS Dual-Plane + post-quantization endpoint refit + HDR CEM 11 delta modes; `Thorough`–`Exhaustive` → adds 16-seed 2-Partition search +- **`CodecFlags`**: Maps to `astcenc 5.7.1` (`MapNormal`, `UseDecodeUnorm8`, `UseAlphaWeight`, `UsePerceptual`, `DecompressOnly`, `SelfDecompressOnly`, `MapRGBM`). + +--- + +## Supported Input Formats & Target ASTC Mapping + +| Input `GraphicsFormat` Category | Supported Formats | `astcenc` Profile | Internal Transfer | Target ASTC `GraphicsFormat` | +| :--- | :--- | :--- | :--- | :--- | +| **LDR 8-bit sRGB** | `R8` / `R8G8` / `R8G8B8` / `R8G8B8A8` / `B8G8R8` / `B8G8R8A8` (`_SRGB`) | `LDR_SRGB` (`LDR` for Normal) | `U8` (4-ch zero-copy) | `RGBA_ASTC{N}X{N}_SRGB` (`_UNorm` for Normal) | +| **LDR 8-bit Linear** | `R8` / `R8G8` / `R8G8B8` / `R8G8B8A8` / `B8G8R8` / `B8G8R8A8` (`_UNorm`) | `LDR` | `U8` (4-ch zero-copy) | `RGBA_ASTC{N}X{N}_UNorm` | +| **LDR 16-bit Linear** | `R16` / `R16G16` / `R16G16B16` / `R16G16B16A16` (`_UNorm`) | `LDR` | `F32` (preserves 16-bit precision) | `RGBA_ASTC{N}X{N}_UNorm` | +| **HDR 16-bit Float** | `R16` / `R16G16` / `R16G16B16` / `R16G16B16A16` (`_SFloat`) | `HDR` | `F16` (4-ch zero-copy) | `RGBA_ASTC{N}X{N}_UFloat` | +| **HDR 32-bit Float** | `R32` / `R32G32` / `R32G32B32` / `R32G32B32A32` (`_SFloat`) | `HDR` | `F32` (4-ch zero-copy) | `RGBA_ASTC{N}X{N}_UFloat` | + +> The GPU backend also supports additional 2D `RenderTexture` HDR formats such as `B10G11R11_UFloatPack32` and `E5B9G9R9_UFloatPack32`. + +--- + +## Advanced Examples + +### Zero-Allocation Raw Pixel Compression (CPU) + +```csharp +using Aperture.Astcenc.Runtime; +using Unity.Collections; +using UnityEngine.Experimental.Rendering; + +public bool CompressBufferZeroAlloc( + NativeArray rgbaPixels, + NativeArray astcOutput, + int width, + int height, + out int bytesWritten) +{ + var options = AstcCompressOptions.Default; + options.BlockSize = BlockSize.ASTC_6x6; + options.Quality = CompressQuality.Fast; + + return Encoder.CompressRawPixelsInto( + rgbaPixels, + astcOutput, + width, + height, + GraphicsFormat.R8G8B8A8_SRGB, + options, + out bytesWritten); +} +``` + +### KTX v1 Export & Persistent Disk Cache + +```csharp +using System.Threading.Tasks; +using Aperture.Astcenc.Runtime; +using UnityEngine; + +public async Task EncodeAndCacheAsync(Texture2D src, string cachePath) +{ + Texture2D cached = await AstcDiskCache.TryLoadAsync(cachePath); + if (cached != null) + return cached; + + var options = AstcCompressOptions.Default; + options.BlockSize = BlockSize.ASTC_6x6; + options.Quality = CompressQuality.Fast; + + // Compresses, writes KTX v1 atomically to cachePath, and returns the GPU-ready ASTC Texture2D + return await AstcDiskCache.CompressAndSaveAsync(src, cachePath, options); +} + +// Or use one-liner load-or-compress with lazy source creation: +public Task LoadOrCompressAsync(string cachePath, System.Func> loadSource) +{ + var options = AstcCompressOptions.Default; + options.BlockSize = BlockSize.ASTC_6x6; + return AstcDiskCache.LoadOrCompressAsync(cachePath, loadSource, options, destroySourceAfterCompress: true); +} +``` + +### Standard `.astc` File Export (Mip 0) + +```csharp +using System.IO; +using Aperture.Astcenc.Runtime; +using UnityEngine; + +public void SaveAstcFile(Texture2D src, string path) +{ + byte[] bytes = src.EncodeToASTC(TextureType.Default, BlockSize.ASTC_6x6, CompressQuality.Medium); + if (bytes != null) + File.WriteAllBytes(path, bytes); +} +``` diff --git a/docs/Architecture.md b/docs/Architecture.md new file mode 100644 index 0000000..4848459 --- /dev/null +++ b/docs/Architecture.md @@ -0,0 +1,75 @@ +# Architecture & Implementation Details + +## High-Level Dataflow + +```mermaid +flowchart TD + A["Unity Texture2D / RenderTexture / Raw Pixels"] --> B["Unified Entry (Encoder.cs)"] + B -->|GPU Backend| G1["AstcGpuBackend.cs"] + G1 -->|Optional| G0["AstcGpuMipGenerator.compute (Odd-NPOT + Normal Renorm)"] + G0 --> G2["AstcGpuEncoder.compute (Tableless HLSL)"] + G1 --> G2 + G2 -->|Hardware ASTC CopyTexture| G3["Zero-Readback -> ASTC Texture2D"] + G2 -->|Buffer / AsyncGPUReadback| G4["AstcRaw (Unmanaged Buffer)"] + B -->|CPU Backend| C1["AstcCpuBackend.cs + AstcContextPool.cs"] + C1 --> C2["NativeAPI P/Invoke (astc-encoder v5.7.1)"] + C2 --> G4 + G4 --> H1["Texture2D.LoadRawTextureData + Apply"] + G4 --> H2["AstcKtxContainer (.ktx) / AstcHeader (.astc)"] +``` + +--- + +## GPU Compute Shader Backend + +Located under `Assets/ASTC Encoder/Runtime/Gpu/` and `Runtime/Resources/`: + +- **Tableless Pure-ALU Encoding (`AstcGpuBise.hlsl`)**: Performs BISE quantization, unquantization, and 128-bit block packing using integer ALU instructions with no large lookup tables, keeping constant-buffer and L1 cache footprints minimal across mobile tile-based GPUs (Metal / Vulkan / GLES 3.1+) and desktop GPUs (D3D11 / D3D12). +- **Per-Block Kernel Specialization (`AstcGpuEncoder.compute` / `AstcGpuCore.hlsl`)**: + - Separate `ASTC_FAST_ONLY` kernels (`Fastest` / `Fast`) and Full kernels (`Medium`–`Exhaustive`) to avoid register bloat in real-time modes. + - Per-block `ASTC_MAX_GRID` sizing (`4x4` → 16, `5x5` → 25, `>=6x6` → 36) to cut VGPR usage. + - `[numthreads(8, 4, 1)]` occupancy tuning for `>=8x8` blocks. + - On-chip packed `RGBA8` pixel cache for `<=6x6` LDR blocks. +- **High-Quality Compression Without Redundant Scans (`AstcGpuCore.hlsl` / `AstcGpuColor.hlsl`)**: + - Lossless Void-Extent fast path for constant blocks. + - Zero-`pow()` `sqrt` sRGB approximation (`0/256` 8-bit round-trip error). + - Row-level early-exit candidate pruning. + - Same-grid continuous weight projection reuse across quantization candidates, combined 1P error + worst-channel accumulation (eliminating worst-channel rescans), merged 3-pass 2-Partition dual-subset endpoint fitting, and loop-hoisted `AstcHash52` (`AstcPreparePartition2`). + - Isotropic and anisotropic weight grids (`6x4`/`4x6`/`8x4`/`4x8`), dynamic-CCS Dual-Plane for both RGB (ORM/MRAO) and RGBA, post-quantization ideal endpoint refit, dedicated `CEM 4` + tangent-space angular-error Dual-Plane for Normal maps, and HDR `CEM 11/14/15` high-precision delta modes. +- **Zero-Readback Mipmap + CopyTexture Pipeline (`AstcGpuMipGenerator.compute` / `AstcGpuBackend.cs`)**: + - Generates the full mipmap chain (handling odd-NPOT edge texels and tangent-space normal renormalization) and encodes every mip into ASTC inside a single `CommandBuffer`. + - Uses `CommandBuffer.CopyTexture` on block coordinates (`ceil(mipW / bx) × ceil(mipH / by)`) for zero-CPU-readback uploads across both aligned and non-multiple dimensions, including full mipmap tails. + - When CPU access is requested (`CompressTextureAsync` / `EncodeToASTCAsync` / `EncodeToKTXAsync`), uses LOH-free `AsyncGPUReadback`. + +--- + +## Native CPU Backend + +Located under `Assets/ASTC Encoder/Runtime/Cpu/` and `Runtime/NativeAPI/`: + +- **Runtime ISA Dispatch (`astcenc_api.cs`)**: + - **Windows x64**: Probes AVX2 via `IsProcessorFeaturePresent(40)` at startup and binds `astcenc-avx2-shared.dll`, falling back seamlessly to `astcenc-sse4.1-shared.dll`. + - **Android**: Dispatches `libastcenc-neon-shared.so` (`arm64-v8a`) vs `libastcenc-none-shared.so` (`armeabi-v7a`) based on `IntPtr.Size == 8`. + - **macOS**: Universal dylib (`x86_64` SSE4.1 + `x86_64h` AVX2 + `arm64` NEON). + - **iOS**: Static NEON library (`__Internal`). +- **Context Pooling & `parentContext` Sharing (`AstcContextPool.cs` / `AstcContext.cs`)**: + - Thread-safe static pool eliminates per-call `astcenc_context_alloc` / `free` overhead across all static CPU APIs. + - Shares read-only block lookup tables via `astcenc 5.x` `parentContext` per `BlockSize`, with safe deferred parent disposal on `Encoder.ReleaseCpuContextPool()` or application quit. + - Supports multi-core `Parallel.For` or optional Unity Job System (`IJobParallelFor`), `CancellationToken` cancellation (`astcenc_compress_cancel`), and guaranteed `astcenc_compress_reset`. +- **Zero-Copy & Low-Memory Pixel Transfer (`ImageExtensions.cs` / `RawTextureData.cs`)**: + - 4-channel `RGBA8` / `BGRA8` / `RGBA16F` / `RGBA32F` pass `NativeSlice` read-only pointers directly in synchronous mode (zero copy). + - Asynchronous mode takes a single compact `UnsafeUtility.MemCpy` snapshot on the main thread and expands/compresses one mip level at a time on background threads (up to 8× lower peak memory for 1/2/3-channel and 16-bit formats). + - 1/2/3-channel and 16-bit UNorm formats expand via `unsafe` pointer loops with zero managed heap allocations. + +--- + +## Automated Builds, Verification & Releases (GitHub Actions) + +The repository includes five CI workflows under `.github/workflows/`: + +1. **`verify-shaders-and-code.yml`**: Manually dispatched (`workflow_dispatch`) workflow that validates HLSL/Compute shader syntax across all block sizes and verifies Unity `.meta` file completeness and GUID uniqueness. +2. **`build-native-plugins.yml`**: Builds all native `astc-encoder` binaries from `ThirdParty/astc-encoder` (Windows x64 AVX2 + SSE4.1, macOS Universal, iOS ARM64 + `astcenc.xcframework`, Android `arm64-v8a` / `armeabi-v7a` with symbol stripping and 16 KB page alignment, Linux x64 SSE4.1) and verifies exported symbols. Automatically runs on non-`master` pushes touching the submodule or workflow file, and can be manually dispatched (`commit_binaries: true` commits updated binaries and Linux `.meta` files via Git LFS). + - When upgrading `ThirdParty/astc-encoder`, verify struct layouts and signatures in `Runtime/NativeAPI/` against `ThirdParty/astc-encoder/Source/astcenc.h`. +3. **`unity-multiplatform-e2e.yml`**: Manually dispatched (`workflow_dispatch`) workflow that runs Unity EditMode tests (`Aperture.Astcenc.Tests`) and builds/executes end-to-end smoke tests across Linux x64, Windows x64, macOS Universal, Android ARM64 (emulator), and iOS ARM64 (Xcode build & link) on demand. +4. **`performance-benchmarks.yml`**: Manually dispatched (`workflow_dispatch`) workflow that runs cross-platform native CPU SIMD benchmarks and Unity Standalone Player GPU/CPU benchmarks, optionally syncing results into `README.md`, `README_CN.md`, `docs/Benchmarks.md`, and `docs/benchmarks/baseline.json`. +5. **`release-package.yml`**: Automatically triggered when a `develop` → `master` pull request is merged (also supports manual `workflow_dispatch`). Verifies resolved LFS native plugins, creates the `v` Git tag from `package.json`, packages both a UPM tarball (`com.aperture.astcenc-.tgz`) and a direct Assets `.zip` archive with SHA-256 checksums, extracts notes from `CHANGELOG.md`, and publishes a GitHub Release. diff --git a/docs/Benchmarks.md b/docs/Benchmarks.md new file mode 100644 index 0000000..4f1ec57 --- /dev/null +++ b/docs/Benchmarks.md @@ -0,0 +1,105 @@ +# Runtime ASTC Encoder — Performance Benchmarks & Regression Baseline + +- **Updated**: `2026-11-28 14:45 UTC` | **Commit**: `d3223a5` | [GitHub Actions Run](https://github.com/Overflowu/Runtime-ASTC-Encoder-For-Unity/actions/runs/46153027417) +- **Baseline Comparison**: Deltas (`Δ vs Baseline`) compare each benchmark's median latency against the previous saved snapshot in `docs/benchmarks/baseline.json` (`🚀` ≥ 5% faster, `⚠️` ≥ 15% slower). + +## 1. Unity Standalone Player (Real Hardware GPU + CPU) + +- **GPU**: `Apple Paravirtual device` (`Metal`) +- **CPU**: `Apple M1 (Virtual)` (3 cores) +- **Unity**: `2021.3.6f1` | **Platform**: `OSXPlayer` +- **GPU Direct CopyTexture**: `4x4=True`, `6x6=True` + +| Benchmark | Backend | Res | Block | Quality | Min (ms) | Median (ms) | P95 (ms) | MP/s | GC (KB) | RGB PSNR | Normal Err | Δ vs Baseline | +| :--- | :--- | :--- | :--- | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | +| `GPU_RGBA8_1024_ASTC_4x4_Fast` | GPU | 1024x1024 | ASTC_4x4 | Fast | 7.26 | **7.66** | 8.60 | 136.94 | 0.0 | 48.94 dB | — | new | +| `CPU_RGBA8_1024_ASTC_4x4_Fast` | CPU | 1024x1024 | ASTC_4x4 | Fast | 233.97 | **253.41** | 281.95 | 4.14 | 8.0 | 48.95 dB | — | new | +| `GPU_RGBA8_1024_ASTC_4x4_Medium` | GPU | 1024x1024 | ASTC_4x4 | Medium | 40.40 | **41.00** | 41.14 | 25.58 | 0.0 | 46.44 dB | — | new | +| `CPU_RGBA8_1024_ASTC_4x4_Medium` | CPU | 1024x1024 | ASTC_4x4 | Medium | 444.33 | **519.59** | 825.93 | 2.02 | 7.0 | 50.24 dB | — | new | +| `GPU_RGBA8_1024_ASTC_6x6_Fast` | GPU | 1024x1024 | ASTC_6x6 | Fast | 13.73 | **20.34** | 23.50 | 51.55 | 0.0 | 29.27 dB | — | new | +| `CPU_RGBA8_1024_ASTC_6x6_Fast` | CPU | 1024x1024 | ASTC_6x6 | Fast | 355.64 | **371.75** | 395.72 | 2.82 | 4.0 | 41.75 dB | — | new | +| `GPU_RGBA8_1024_ASTC_6x6_Medium` | GPU | 1024x1024 | ASTC_6x6 | Medium | 54.40 | **57.49** | 60.93 | 18.24 | 0.0 | 32.57 dB | — | new | +| `CPU_RGBA8_1024_ASTC_6x6_Medium` | CPU | 1024x1024 | ASTC_6x6 | Medium | 824.27 | **876.38** | 954.63 | 1.20 | 4.0 | 43.23 dB | — | new | +| `GPU_RGBA8_1024_ASTC_8x8_Fast` | GPU | 1024x1024 | ASTC_8x8 | Fast | 8.18 | **8.51** | 9.22 | 123.15 | 0.0 | 43.43 dB | — | new | +| `CPU_RGBA8_1024_ASTC_8x8_Fast` | CPU | 1024x1024 | ASTC_8x8 | Fast | 757.78 | **836.19** | 1017.42 | 1.25 | 3.0 | 45.99 dB | — | new | +| `GPU_RGBA8_1024_ASTC_8x8_Medium` | GPU | 1024x1024 | ASTC_8x8 | Medium | 36.27 | **37.02** | 40.93 | 28.32 | 0.8 | 44.05 dB | — | new | +| `CPU_RGBA8_1024_ASTC_8x8_Medium` | CPU | 1024x1024 | ASTC_8x8 | Medium | 1685.85 | **1848.60** | 2193.39 | 0.57 | 4.0 | 47.93 dB | — | new | +| `GPU_RGBA8_1024_ASTC_12x12_Fast` | GPU | 1024x1024 | ASTC_12x12 | Fast | 8.38 | **10.85** | 11.44 | 96.63 | 0.0 | 24.67 dB | — | new | +| `CPU_RGBA8_1024_ASTC_12x12_Fast` | CPU | 1024x1024 | ASTC_12x12 | Fast | 618.65 | **710.89** | 795.81 | 1.48 | 4.0 | 27.78 dB | — | new | +| `GPU_RGBA8_1024_ASTC_12x12_Medium` | GPU | 1024x1024 | ASTC_12x12 | Medium | 29.09 | **30.73** | 32.13 | 34.12 | 0.0 | 25.34 dB | — | new | +| `CPU_RGBA8_1024_ASTC_12x12_Medium` | CPU | 1024x1024 | ASTC_12x12 | Medium | 1095.57 | **1254.79** | 1345.90 | 0.84 | 4.0 | 30.08 dB | — | new | +| `GPU_RGBA8_512_ASTC_4x4_Fast` | GPU | 512x512 | ASTC_4x4 | Fast | 3.85 | **5.55** | 7.34 | 47.27 | 0.0 | 44.54 dB | — | new | +| `CPU_RGBA8_512_ASTC_4x4_Fast` | CPU | 512x512 | ASTC_4x4 | Fast | 115.25 | **148.60** | 168.08 | 1.76 | 3.2 | 44.51 dB | — | new | +| `GPU_RGBA8_512_ASTC_4x4_Medium` | GPU | 512x512 | ASTC_4x4 | Medium | 20.40 | **20.59** | 21.44 | 12.73 | 0.0 | 43.86 dB | — | new | +| `CPU_RGBA8_512_ASTC_4x4_Medium` | CPU | 512x512 | ASTC_4x4 | Medium | 254.42 | **277.40** | 387.44 | 0.95 | 3.2 | 47.81 dB | — | new | +| `GPU_RGBA8_512_ASTC_4x4_Thorough` | GPU | 512x512 | ASTC_4x4 | Thorough | 14.30 | **14.94** | 18.69 | 17.54 | 0.0 | 40.17 dB | — | new | +| `CPU_RGBA8_512_ASTC_4x4_Thorough` | CPU | 512x512 | ASTC_4x4 | Thorough | 542.45 | **593.42** | 639.67 | 0.44 | 4.0 | 51.62 dB | — | new | +| `GPU_RGBA8_512_ASTC_6x6_Fast` | GPU | 512x512 | ASTC_6x6 | Fast | 4.02 | **4.36** | 10.73 | 60.19 | 0.0 | 28.59 dB | — | new | +| `CPU_RGBA8_512_ASTC_6x6_Fast` | CPU | 512x512 | ASTC_6x6 | Fast | 136.68 | **147.53** | 157.66 | 1.78 | 3.2 | 37.20 dB | — | new | +| `GPU_RGBA8_512_ASTC_6x6_Medium` | GPU | 512x512 | ASTC_6x6 | Medium | 15.62 | **16.58** | 24.03 | 15.81 | 0.0 | 30.75 dB | — | new | +| `CPU_RGBA8_512_ASTC_6x6_Medium` | CPU | 512x512 | ASTC_6x6 | Medium | 303.94 | **321.06** | 564.12 | 0.82 | 3.2 | 38.69 dB | — | new | +| `GPU_RGBA8_512_ASTC_6x6_Thorough` | GPU | 512x512 | ASTC_6x6 | Thorough | 18.58 | **20.09** | 22.55 | 13.05 | 0.0 | 31.71 dB | — | new | +| `CPU_RGBA8_512_ASTC_6x6_Thorough` | CPU | 512x512 | ASTC_6x6 | Thorough | 668.67 | **703.41** | 732.16 | 0.37 | 4.0 | 39.10 dB | — | new | +| `GPU_RGBA8_512_ASTC_8x8_Fast` | GPU | 512x512 | ASTC_8x8 | Fast | 3.46 | **3.52** | 5.65 | 74.55 | 0.0 | 37.82 dB | — | new | +| `CPU_RGBA8_512_ASTC_8x8_Fast` | CPU | 512x512 | ASTC_8x8 | Fast | 175.76 | **229.24** | 260.96 | 1.14 | 3.2 | 41.99 dB | — | new | +| `GPU_RGBA8_512_ASTC_8x8_Medium` | GPU | 512x512 | ASTC_8x8 | Medium | 11.04 | **11.84** | 18.64 | 22.15 | 0.0 | 39.45 dB | — | new | +| `CPU_RGBA8_512_ASTC_8x8_Medium` | CPU | 512x512 | ASTC_8x8 | Medium | 327.95 | **373.93** | 389.11 | 0.70 | 3.2 | 43.14 dB | — | new | +| `GPU_RGBA8_512_ASTC_8x8_Thorough` | GPU | 512x512 | ASTC_8x8 | Thorough | 12.09 | **12.41** | 13.36 | 21.12 | 0.0 | 39.08 dB | — | new | +| `CPU_RGBA8_512_ASTC_8x8_Thorough` | CPU | 512x512 | ASTC_8x8 | Thorough | 631.27 | **675.98** | 762.20 | 0.39 | 4.0 | 47.48 dB | — | new | +| `GPU_RGBA8_512_ASTC_12x12_Fast` | GPU | 512x512 | ASTC_12x12 | Fast | 2.30 | **2.32** | 2.42 | 112.95 | 0.0 | 24.04 dB | — | new | +| `CPU_RGBA8_512_ASTC_12x12_Fast` | CPU | 512x512 | ASTC_12x12 | Fast | 136.28 | **158.24** | 171.77 | 1.66 | 3.2 | 26.31 dB | — | new | +| `GPU_RGBA8_512_ASTC_12x12_Medium` | GPU | 512x512 | ASTC_12x12 | Medium | 11.70 | **20.36** | 20.61 | 12.88 | 0.0 | 24.34 dB | — | new | +| `CPU_RGBA8_512_ASTC_12x12_Medium` | CPU | 512x512 | ASTC_12x12 | Medium | 250.49 | **308.17** | 369.28 | 0.85 | 3.2 | 27.73 dB | — | new | +| `GPU_RGBA8_512_ASTC_12x12_Thorough` | GPU | 512x512 | ASTC_12x12 | Thorough | 10.13 | **10.33** | 12.98 | 25.39 | 0.0 | 24.29 dB | — | new | +| `CPU_RGBA8_512_ASTC_12x12_Thorough` | CPU | 512x512 | ASTC_12x12 | Thorough | 519.84 | **558.45** | 592.55 | 0.47 | 4.0 | 27.42 dB | — | new | +| `GPU_ZeroReadback_1024_6x6_Fast` | GPU | 1024x1024 | ASTC_6x6 | Fast | 0.54 | **2.70** | 3.75 | 388.68 | 0.0 | — | — | new | +| `GPU_ZeroReadback_MipGen_1024_6x6_Fast` | GPU | 1024x1024+Mips | ASTC_6x6 | Fast | 0.66 | **0.75** | 1.63 | 1861.65 | 0.0 | — | — | new | +| `GPU_Normal_512_6x6_Medium` | GPU | 512x512 | ASTC_6x6 | Medium | 12.36 | **19.26** | 23.55 | 13.61 | 0.0 | — | 0.27° | new | +| `CPU_Normal_512_6x6_Medium` | CPU | 512x512 | ASTC_6x6 | Medium | 294.23 | **319.21** | 377.23 | 0.82 | 4.0 | — | 0.15° | new | +| `GPU_sRGB_512_6x6_Fast` | GPU | 512x512 | ASTC_6x6 | Fast | 4.26 | **6.57** | 10.52 | 39.88 | 0.0 | — | — | new | +| `GPU_HDR16F_512_6x6_Fast` | GPU | 512x512 | ASTC_6x6 | Fast | 0.01 | **0.01** | 0.02 | 23831.27 | 0.0 | — | — | new | +| `CPU_CompressRawPixels_512_6x6_Fast` | CPU | 512x512 | ASTC_6x6 | Fast | 171.83 | **181.33** | 191.89 | 1.45 | 4.0 | — | — | new | +| `CPU_CompressRawPixelsInto_512_6x6_Fast` | CPU | 512x512 | ASTC_6x6 | Fast | 180.29 | **196.09** | 216.09 | 1.34 | 4.0 | — | — | new | +| `CPU_Decompress_512_6x6_3T` | CPU | 512x512 | ASTC_6x6 | N/A | 1.29 | **1.55** | 7.97 | 169.35 | 416.0 | — | — | new | +| `DiskCache_TryLoad_512_6x6_FullMips` | Disk+GPU | 512x512+Mips | ASTC_6x6 | N/A | 0.33 | **0.66** | 0.98 | 529.18 | 124.8 | — | — | new | + +## 2. Cross-Platform Native CPU (`astc-encoder v5.7.1`) + +| Platform / CPU | Benchmark | ISA | Threads | Min (ms) | Median (ms) | P95 (ms) | MP/s | Δ vs Baseline | +| :--- | :--- | :--- | ---: | ---: | ---: | ---: | ---: | ---: | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_AVX2_512_ASTC_4x4_Fast_4T` | `AVX2` | 4 | 58.76 | **58.87** | 66.53 | 4.45 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_AVX2_512_ASTC_4x4_Medium_4T` | `AVX2` | 4 | 180.32 | **191.24** | 192.53 | 1.37 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_AVX2_512_ASTC_6x6_Fast_4T` | `AVX2` | 4 | 39.97 | **40.04** | 40.25 | 6.55 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_AVX2_512_ASTC_6x6_Medium_4T` | `AVX2` | 4 | 172.89 | **173.18** | 186.41 | 1.51 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_AVX2_512_ASTC_8x8_Fast_4T` | `AVX2` | 4 | 31.29 | **31.44** | 40.67 | 8.34 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_AVX2_512_ASTC_8x8_Medium_4T` | `AVX2` | 4 | 87.35 | **87.52** | 98.31 | 3.00 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_AVX2_512_ASTC_12x12_Fast_4T` | `AVX2` | 4 | 69.79 | **70.21** | 73.02 | 3.73 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_AVX2_512_ASTC_12x12_Medium_4T` | `AVX2` | 4 | 297.92 | **308.52** | 311.08 | 0.85 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_AVX2_Decompress_512_ASTC_6x6_4T` | `AVX2` | 4 | 1.24 | **1.28** | 1.37 | 204.85 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_SSE4.1_512_ASTC_4x4_Fast_4T` | `SSE4.1` | 4 | 64.67 | **65.23** | 70.17 | 4.02 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_SSE4.1_512_ASTC_4x4_Medium_4T` | `SSE4.1` | 4 | 193.89 | **200.34** | 206.89 | 1.31 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_SSE4.1_512_ASTC_6x6_Fast_4T` | `SSE4.1` | 4 | 43.82 | **43.90** | 44.26 | 5.97 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_SSE4.1_512_ASTC_6x6_Medium_4T` | `SSE4.1` | 4 | 180.35 | **180.55** | 192.34 | 1.45 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_SSE4.1_512_ASTC_8x8_Fast_4T` | `SSE4.1` | 4 | 33.93 | **34.05** | 43.32 | 7.70 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_SSE4.1_512_ASTC_8x8_Medium_4T` | `SSE4.1` | 4 | 92.35 | **93.42** | 103.63 | 2.81 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_SSE4.1_512_ASTC_12x12_Fast_4T` | `SSE4.1` | 4 | 69.49 | **69.66** | 81.05 | 3.76 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_SSE4.1_512_ASTC_12x12_Medium_4T` | `SSE4.1` | 4 | 283.73 | **296.89** | 297.93 | 0.88 | new | +| Windows AMD64 (`AMD EPYC 9V74 80-Core Processor`) | `Native_SSE4.1_Decompress_512_ASTC_6x6_4T` | `SSE4.1` | 4 | 1.84 | **1.87** | 1.99 | 140.04 | new | +| Darwin arm64 (`Apple M1 (Virtual)`) | `Native_ARM64_NEON_512_ASTC_4x4_Fast_3T` | `ARM64_NEON` | 3 | 61.30 | **73.72** | 89.83 | 3.56 | new | +| Darwin arm64 (`Apple M1 (Virtual)`) | `Native_ARM64_NEON_512_ASTC_4x4_Medium_3T` | `ARM64_NEON` | 3 | 155.97 | **186.31** | 248.39 | 1.41 | new | +| Darwin arm64 (`Apple M1 (Virtual)`) | `Native_ARM64_NEON_512_ASTC_6x6_Fast_3T` | `ARM64_NEON` | 3 | 34.40 | **34.68** | 35.09 | 7.56 | new | +| Darwin arm64 (`Apple M1 (Virtual)`) | `Native_ARM64_NEON_512_ASTC_6x6_Medium_3T` | `ARM64_NEON` | 3 | 144.50 | **154.93** | 202.13 | 1.69 | new | +| Darwin arm64 (`Apple M1 (Virtual)`) | `Native_ARM64_NEON_512_ASTC_8x8_Fast_3T` | `ARM64_NEON` | 3 | 27.69 | **28.03** | 28.47 | 9.35 | new | +| Darwin arm64 (`Apple M1 (Virtual)`) | `Native_ARM64_NEON_512_ASTC_8x8_Medium_3T` | `ARM64_NEON` | 3 | 71.27 | **71.79** | 90.55 | 3.65 | new | +| Darwin arm64 (`Apple M1 (Virtual)`) | `Native_ARM64_NEON_512_ASTC_12x12_Fast_3T` | `ARM64_NEON` | 3 | 54.55 | **55.24** | 57.33 | 4.75 | new | +| Darwin arm64 (`Apple M1 (Virtual)`) | `Native_ARM64_NEON_512_ASTC_12x12_Medium_3T` | `ARM64_NEON` | 3 | 198.91 | **232.17** | 246.13 | 1.13 | new | +| Darwin arm64 (`Apple M1 (Virtual)`) | `Native_ARM64_NEON_Decompress_512_ASTC_6x6_3T` | `ARM64_NEON` | 3 | 1.38 | **1.51** | 2.27 | 173.77 | new | +| Linux x86_64 (`AMD EPYC 7763 64-Core Processor`) | `Native_SSE4.1_512_ASTC_4x4_Fast_4T` | `SSE4.1` | 4 | 73.24 | **73.32** | 73.77 | 3.58 | new | +| Linux x86_64 (`AMD EPYC 7763 64-Core Processor`) | `Native_SSE4.1_512_ASTC_4x4_Medium_4T` | `SSE4.1` | 4 | 220.29 | **220.75** | 222.05 | 1.19 | new | +| Linux x86_64 (`AMD EPYC 7763 64-Core Processor`) | `Native_SSE4.1_512_ASTC_6x6_Fast_4T` | `SSE4.1` | 4 | 50.00 | **50.48** | 51.02 | 5.19 | new | +| Linux x86_64 (`AMD EPYC 7763 64-Core Processor`) | `Native_SSE4.1_512_ASTC_6x6_Medium_4T` | `SSE4.1` | 4 | 196.73 | **197.06** | 203.91 | 1.33 | new | +| Linux x86_64 (`AMD EPYC 7763 64-Core Processor`) | `Native_SSE4.1_512_ASTC_8x8_Fast_4T` | `SSE4.1` | 4 | 37.80 | **37.84** | 37.94 | 6.93 | new | +| Linux x86_64 (`AMD EPYC 7763 64-Core Processor`) | `Native_SSE4.1_512_ASTC_8x8_Medium_4T` | `SSE4.1` | 4 | 98.53 | **98.71** | 100.25 | 2.66 | new | +| Linux x86_64 (`AMD EPYC 7763 64-Core Processor`) | `Native_SSE4.1_512_ASTC_12x12_Fast_4T` | `SSE4.1` | 4 | 74.94 | **75.14** | 75.41 | 3.49 | new | +| Linux x86_64 (`AMD EPYC 7763 64-Core Processor`) | `Native_SSE4.1_512_ASTC_12x12_Medium_4T` | `SSE4.1` | 4 | 298.12 | **299.78** | 301.03 | 0.87 | new | +| Linux x86_64 (`AMD EPYC 7763 64-Core Processor`) | `Native_SSE4.1_Decompress_512_ASTC_6x6_4T` | `SSE4.1` | 4 | 2.15 | **2.18** | 2.21 | 120.44 | new | diff --git a/docs/CI_E2E_GUIDE.md b/docs/CI_E2E_GUIDE.md new file mode 100644 index 0000000..4e103aa --- /dev/null +++ b/docs/CI_E2E_GUIDE.md @@ -0,0 +1,31 @@ +# 多平台 Unity 构建与端到端测试指南(GitHub Actions + GameCI) + +本项目在 `master` 与 `develop` 分支配置了基于 **GitHub Actions + GameCI** 的自动化测试与多平台端到端构建流水线([`.github/workflows/unity-multiplatform-e2e.yml`](../.github/workflows/unity-multiplatform-e2e.yml)),覆盖: + +| 阶段 / 平台 | 运行环境 | 验证内容 | +| :--- | :--- | :--- | +| **Native Plugins & Linux `.so` Build** | `ubuntu-latest` | 校验 Git LFS 全部 6 个预编译原生库(含 Windows AVX2/SSE4.1)完整性、架构与导出符号;从 `ThirdParty/astc-encoder` 子模块编译 Linux x86_64 `libastcenc-sse4.1-shared.so` | +| **Unity Test Runner (EditMode)** | `ubuntu-latest` (GameCI) | 运行 `Assets/ASTC Encoder/Tests/Editor/AstcEncoderTests.cs` 黄金验证套件(ASTC/KTX 容器、磁盘缓存、队列调度、CPU 压缩/解压缩精度) | +| **Linux x64 Standalone** | `ubuntu-latest` | 构建 Linux Player 并以 `-batchmode -nographics -astc-e2e` 实际运行端到端压缩测试 | +| **Windows x64 Standalone** | `ubuntu-latest` 构建 → `windows-latest` 运行 | 跨平台构建 `.exe`,在真实 Windows Runner 上加载 AVX2/SSE4.1 DLL 执行端到端压缩测试 | +| **macOS Universal Standalone** | `ubuntu-latest` 构建 → `macos-latest` 运行 | 跨平台构建 `.app`,在真实 Apple Silicon macOS Runner 上加载通用二进制 `libastcenc-shared.dylib` 执行端到端压缩测试 | +| **Android ARM64 (IL2CPP)** | `ubuntu-latest` 构建 → `macos-latest` 模拟器运行 | 构建 ARM64 `.apk`,校验 `lib/arm64-v8a/libastcenc-neon-shared.so` 打包,并在 ARM64 Android Emulator 上安装启动校验 `adb logcat` 输出 `ASTC_E2E_PASSED` | +| **iOS ARM64 (IL2CPP)** | `ubuntu-latest` 导出 → `macos-latest` Xcode 编译 | 导出 Xcode 工程,并在 macOS Runner 上执行无签名 `xcodebuild -sdk iphoneos build`,验证 IL2CPP 编译与静态库 `libastcenc-neon-static.a` 链接 | + +--- + +## 一、配置 Unity License Secrets + +在 GitHub 仓库 **Settings → Secrets and variables → Actions** 中配置: + +- **Unity Personal(个人免费版)**: + - `UNITY_LICENSE`:`Unity_lic.ulf` 完整 XML 内容(注意新版 Unity Hub 需在 *Preferences → Licenses* 手动点击 *Add → Get a free personal license* 才会写入 `Unity_lic.ulf`,不要填入 `UnityEntitlementLicense.xml`) + - `UNITY_EMAIL`:Unity 账号邮箱 + - `UNITY_PASSWORD`:Unity 账号密码 +- **Unity Pro / Plus(序列号版)**:`UNITY_SERIAL` + `UNITY_EMAIL` + `UNITY_PASSWORD` + +--- + +## 二、触发方式 + +- **手动触发(默认)**:为节省 CI 额度,本流水线不再随 `push` / `pull_request` 自动触发。开发完成需要验证时,在 GitHub 仓库 **Actions → Unity Multi-Platform Build & E2E Tests → Run workflow** 中选择目标分支手动触发,可自定义 `unity_version`(默认 `2021.3.6f1`)和 `run_android_emulator`。 diff --git a/docs/benchmarks/baseline.json b/docs/benchmarks/baseline.json new file mode 100644 index 0000000..b4a0644 --- /dev/null +++ b/docs/benchmarks/baseline.json @@ -0,0 +1,1783 @@ +{ + "SchemaVersion": "1.0", + "TimestampUtc": "2026-11-28T14:45:33.182883+00:00", + "GitCommit": "d3223a5", + "unity": { + "SchemaVersion": "1.0", + "TimestampUtc": "2026-11-28T14:31:27.4006210Z", + "GitCommit": "d3223a509836e324829635f6c8b2fe25f893104a", + "UnityVersion": "2021.3.6f1", + "Platform": "OSXPlayer", + "CpuModel": "Apple M1 (Virtual)", + "CpuCores": 3, + "GpuModel": "Apple Paravirtual device", + "GraphicsDeviceType": "Metal", + "GpuSupported": true, + "CpuSupported": true, + "SupportsDirectCopy4x4": true, + "SupportsDirectCopy6x6": true, + "Results": [ + { + "Name": "GPU_RGBA8_1024_ASTC_4x4_Fast", + "Category": "GPU_vs_CPU_1024", + "Backend": "GPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_4x4", + "Quality": "Fast", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 7.2574000000000005, + "MedianMs": 7.6572000000000005, + "MeanMs": 7.752280000000001, + "P95Ms": 8.5983, + "MaxMs": 8.5983, + "ThroughputMPixPerSec": 136.93987358303295, + "GcAllocBytesPerOp": 0, + "OutputBytes": 1048576, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 48.93544461717621, + "RgbaPsnrDb": 46.447072388366934, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_1024_ASTC_4x4_Fast", + "Category": "GPU_vs_CPU_1024", + "Backend": "CPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_4x4", + "Quality": "Fast", + "WarmupRuns": 1, + "Iterations": 4, + "MinMs": 233.97140000000002, + "MedianMs": 253.41470000000004, + "MeanMs": 255.68827500000003, + "P95Ms": 281.95230000000004, + "MaxMs": 281.95230000000004, + "ThroughputMPixPerSec": 4.137786797687742, + "GcAllocBytesPerOp": 8192, + "OutputBytes": 1048576, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 48.953588953861356, + "RgbaPsnrDb": 47.284639762353194, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_1024_ASTC_4x4_Medium", + "Category": "GPU_vs_CPU_1024", + "Backend": "GPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_4x4", + "Quality": "Medium", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 40.400400000000005, + "MedianMs": 40.9972, + "MeanMs": 40.8319, + "P95Ms": 41.1408, + "MaxMs": 41.1408, + "ThroughputMPixPerSec": 25.57677109656269, + "GcAllocBytesPerOp": 0, + "OutputBytes": 1048576, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 46.44263612406823, + "RgbaPsnrDb": 46.385471914063544, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_1024_ASTC_4x4_Medium", + "Category": "GPU_vs_CPU_1024", + "Backend": "CPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_4x4", + "Quality": "Medium", + "WarmupRuns": 1, + "Iterations": 4, + "MinMs": 444.3315, + "MedianMs": 519.5899, + "MeanMs": 577.3600250000001, + "P95Ms": 825.9288, + "MaxMs": 825.9288, + "ThroughputMPixPerSec": 2.018083877304005, + "GcAllocBytesPerOp": 7168, + "OutputBytes": 1048576, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 50.239287043339836, + "RgbaPsnrDb": 49.86086178413393, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_1024_ASTC_6x6_Fast", + "Category": "GPU_vs_CPU_1024", + "Backend": "GPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_6x6", + "Quality": "Fast", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 13.733400000000001, + "MedianMs": 20.340600000000002, + "MeanMs": 19.591380000000004, + "P95Ms": 23.500700000000002, + "MaxMs": 23.500700000000002, + "ThroughputMPixPerSec": 51.55088837104117, + "GcAllocBytesPerOp": 0, + "OutputBytes": 467856, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 29.268915777475613, + "RgbaPsnrDb": 30.307801054984893, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_1024_ASTC_6x6_Fast", + "Category": "GPU_vs_CPU_1024", + "Backend": "CPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_6x6", + "Quality": "Fast", + "WarmupRuns": 1, + "Iterations": 4, + "MinMs": 355.6427, + "MedianMs": 371.7456, + "MeanMs": 373.71317500000004, + "P95Ms": 395.71880000000004, + "MaxMs": 395.71880000000004, + "ThroughputMPixPerSec": 2.820681670475723, + "GcAllocBytesPerOp": 4096, + "OutputBytes": 467856, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 41.74544763163109, + "RgbaPsnrDb": 40.62360856249613, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_1024_ASTC_6x6_Medium", + "Category": "GPU_vs_CPU_1024", + "Backend": "GPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_6x6", + "Quality": "Medium", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 54.402300000000004, + "MedianMs": 57.4911, + "MeanMs": 57.579660000000004, + "P95Ms": 60.931900000000006, + "MaxMs": 60.931900000000006, + "ThroughputMPixPerSec": 18.238927416591437, + "GcAllocBytesPerOp": 0, + "OutputBytes": 467856, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 32.56521584108872, + "RgbaPsnrDb": 33.413757354941964, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_1024_ASTC_6x6_Medium", + "Category": "GPU_vs_CPU_1024", + "Backend": "CPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_6x6", + "Quality": "Medium", + "WarmupRuns": 1, + "Iterations": 4, + "MinMs": 824.2666, + "MedianMs": 876.3836000000001, + "MeanMs": 882.915575, + "P95Ms": 954.6285, + "MaxMs": 954.6285, + "ThroughputMPixPerSec": 1.1964806278894309, + "GcAllocBytesPerOp": 4096, + "OutputBytes": 467856, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 43.22945859918707, + "RgbaPsnrDb": 42.109235150473275, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_1024_ASTC_8x8_Fast", + "Category": "GPU_vs_CPU_1024", + "Backend": "GPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_8x8", + "Quality": "Fast", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 8.1754, + "MedianMs": 8.5144, + "MeanMs": 8.653920000000001, + "P95Ms": 9.2192, + "MaxMs": 9.2192, + "ThroughputMPixPerSec": 123.1532462651508, + "GcAllocBytesPerOp": 0, + "OutputBytes": 262144, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 43.42779831094145, + "RgbaPsnrDb": 40.60758672519129, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_1024_ASTC_8x8_Fast", + "Category": "GPU_vs_CPU_1024", + "Backend": "CPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_8x8", + "Quality": "Fast", + "WarmupRuns": 1, + "Iterations": 4, + "MinMs": 757.7843, + "MedianMs": 836.1885500000001, + "MeanMs": 861.894325, + "P95Ms": 1017.4159000000001, + "MaxMs": 1017.4159000000001, + "ThroughputMPixPerSec": 1.2539946881597457, + "GcAllocBytesPerOp": 3072, + "OutputBytes": 262144, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 45.98779482605557, + "RgbaPsnrDb": 45.852702952852056, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_1024_ASTC_8x8_Medium", + "Category": "GPU_vs_CPU_1024", + "Backend": "GPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_8x8", + "Quality": "Medium", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 36.2685, + "MedianMs": 37.0248, + "MeanMs": 38.13978, + "P95Ms": 40.927600000000005, + "MaxMs": 40.927600000000005, + "ThroughputMPixPerSec": 28.320909228409068, + "GcAllocBytesPerOp": 819, + "OutputBytes": 262144, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 44.05044601875516, + "RgbaPsnrDb": 42.709369884547755, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_1024_ASTC_8x8_Medium", + "Category": "GPU_vs_CPU_1024", + "Backend": "CPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_8x8", + "Quality": "Medium", + "WarmupRuns": 1, + "Iterations": 4, + "MinMs": 1685.8475, + "MedianMs": 1848.6037000000001, + "MeanMs": 1894.110225, + "P95Ms": 2193.386, + "MaxMs": 2193.386, + "ThroughputMPixPerSec": 0.5672259554603293, + "GcAllocBytesPerOp": 4096, + "OutputBytes": 262144, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 47.9299764839495, + "RgbaPsnrDb": 47.546544971573674, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_1024_ASTC_12x12_Fast", + "Category": "GPU_vs_CPU_1024", + "Backend": "GPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_12x12", + "Quality": "Fast", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 8.3804, + "MedianMs": 10.851, + "MeanMs": 10.44922, + "P95Ms": 11.4383, + "MaxMs": 11.4383, + "ThroughputMPixPerSec": 96.63404294535064, + "GcAllocBytesPerOp": 0, + "OutputBytes": 118336, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 24.674982325540068, + "RgbaPsnrDb": 25.542357633894742, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_1024_ASTC_12x12_Fast", + "Category": "GPU_vs_CPU_1024", + "Backend": "CPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_12x12", + "Quality": "Fast", + "WarmupRuns": 1, + "Iterations": 4, + "MinMs": 618.6504, + "MedianMs": 710.8868, + "MeanMs": 709.057275, + "P95Ms": 795.8051, + "MaxMs": 795.8051, + "ThroughputMPixPerSec": 1.4750252782862192, + "GcAllocBytesPerOp": 4096, + "OutputBytes": 118336, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 27.781366326710703, + "RgbaPsnrDb": 28.23699482157459, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_1024_ASTC_12x12_Medium", + "Category": "GPU_vs_CPU_1024", + "Backend": "GPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_12x12", + "Quality": "Medium", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 29.087, + "MedianMs": 30.7282, + "MeanMs": 30.76426, + "P95Ms": 32.1287, + "MaxMs": 32.1287, + "ThroughputMPixPerSec": 34.12422465357554, + "GcAllocBytesPerOp": 0, + "OutputBytes": 118336, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 25.3429802507935, + "RgbaPsnrDb": 26.152520573829854, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_1024_ASTC_12x12_Medium", + "Category": "GPU_vs_CPU_1024", + "Backend": "CPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_12x12", + "Quality": "Medium", + "WarmupRuns": 1, + "Iterations": 4, + "MinMs": 1095.5699, + "MedianMs": 1254.7936, + "MeanMs": 1237.7655, + "P95Ms": 1345.9049, + "MaxMs": 1345.9049, + "ThroughputMPixPerSec": 0.8356561589093218, + "GcAllocBytesPerOp": 4096, + "OutputBytes": 118336, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 30.08341764165188, + "RgbaPsnrDb": 30.314624406359023, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_512_ASTC_4x4_Fast", + "Category": "GPU_vs_CPU_512", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_4x4", + "Quality": "Fast", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 3.8549, + "MedianMs": 5.546, + "MeanMs": 5.69054, + "P95Ms": 7.339600000000001, + "MaxMs": 7.339600000000001, + "ThroughputMPixPerSec": 47.26721961774251, + "GcAllocBytesPerOp": 0, + "OutputBytes": 262144, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 44.53700235141254, + "RgbaPsnrDb": 41.26932203173269, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_512_ASTC_4x4_Fast", + "Category": "GPU_vs_CPU_512", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_4x4", + "Quality": "Fast", + "WarmupRuns": 1, + "Iterations": 5, + "MinMs": 115.2474, + "MedianMs": 148.5983, + "MeanMs": 148.80894, + "P95Ms": 168.0774, + "MaxMs": 168.0774, + "ThroughputMPixPerSec": 1.7641117024891941, + "GcAllocBytesPerOp": 3276, + "OutputBytes": 262144, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 44.51269121516561, + "RgbaPsnrDb": 43.97984147595657, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_512_ASTC_4x4_Medium", + "Category": "GPU_vs_CPU_512", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_4x4", + "Quality": "Medium", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 20.3961, + "MedianMs": 20.5929, + "MeanMs": 20.745380000000004, + "P95Ms": 21.438100000000002, + "MaxMs": 21.438100000000002, + "ThroughputMPixPerSec": 12.729824356938556, + "GcAllocBytesPerOp": 0, + "OutputBytes": 262144, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 43.86294401381787, + "RgbaPsnrDb": 43.275775224534534, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_512_ASTC_4x4_Medium", + "Category": "GPU_vs_CPU_512", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_4x4", + "Quality": "Medium", + "WarmupRuns": 1, + "Iterations": 5, + "MinMs": 254.42360000000002, + "MedianMs": 277.3986, + "MeanMs": 303.12138, + "P95Ms": 387.4411, + "MaxMs": 387.4411, + "ThroughputMPixPerSec": 0.9450083742311605, + "GcAllocBytesPerOp": 3276, + "OutputBytes": 262144, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 47.809063278540656, + "RgbaPsnrDb": 47.62249726017032, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_512_ASTC_4x4_Thorough", + "Category": "GPU_vs_CPU_512", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_4x4", + "Quality": "Thorough", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 14.299900000000001, + "MedianMs": 14.9433, + "MeanMs": 15.5565, + "P95Ms": 18.692, + "MaxMs": 18.692, + "ThroughputMPixPerSec": 17.542577610032588, + "GcAllocBytesPerOp": 0, + "OutputBytes": 262144, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 40.16757368603386, + "RgbaPsnrDb": 40.083057035072514, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_512_ASTC_4x4_Thorough", + "Category": "GPU_vs_CPU_512", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_4x4", + "Quality": "Thorough", + "WarmupRuns": 1, + "Iterations": 3, + "MinMs": 542.447, + "MedianMs": 593.4178, + "MeanMs": 591.8444000000001, + "P95Ms": 639.6684, + "MaxMs": 639.6684, + "ThroughputMPixPerSec": 0.4417528426009465, + "GcAllocBytesPerOp": 4096, + "OutputBytes": 262144, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 51.61825196152206, + "RgbaPsnrDb": 51.34576527706316, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_512_ASTC_6x6_Fast", + "Category": "GPU_vs_CPU_512", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Fast", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 4.0154000000000005, + "MedianMs": 4.355, + "MeanMs": 6.534700000000001, + "P95Ms": 10.7311, + "MaxMs": 10.7311, + "ThroughputMPixPerSec": 60.19380022962112, + "GcAllocBytesPerOp": 0, + "OutputBytes": 118336, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 28.586939937588962, + "RgbaPsnrDb": 29.206400857941198, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_512_ASTC_6x6_Fast", + "Category": "GPU_vs_CPU_512", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Fast", + "WarmupRuns": 1, + "Iterations": 5, + "MinMs": 136.68110000000001, + "MedianMs": 147.535, + "MeanMs": 146.57762000000002, + "P95Ms": 157.6611, + "MaxMs": 157.6611, + "ThroughputMPixPerSec": 1.7768258379367607, + "GcAllocBytesPerOp": 3276, + "OutputBytes": 118336, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 37.20279527435642, + "RgbaPsnrDb": 35.929973885571734, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_512_ASTC_6x6_Medium", + "Category": "GPU_vs_CPU_512", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Medium", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 15.623700000000001, + "MedianMs": 16.5832, + "MeanMs": 19.02482, + "P95Ms": 24.0272, + "MaxMs": 24.0272, + "ThroughputMPixPerSec": 15.807805489893383, + "GcAllocBytesPerOp": 0, + "OutputBytes": 118336, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 30.75457332597972, + "RgbaPsnrDb": 31.112740704460407, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_512_ASTC_6x6_Medium", + "Category": "GPU_vs_CPU_512", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Medium", + "WarmupRuns": 1, + "Iterations": 5, + "MinMs": 303.9388, + "MedianMs": 321.06350000000003, + "MeanMs": 372.89476, + "P95Ms": 564.1246, + "MaxMs": 564.1246, + "ThroughputMPixPerSec": 0.816486458286289, + "GcAllocBytesPerOp": 3276, + "OutputBytes": 118336, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 38.69152133990712, + "RgbaPsnrDb": 37.44953450561186, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_512_ASTC_6x6_Thorough", + "Category": "GPU_vs_CPU_512", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Thorough", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 18.582700000000003, + "MedianMs": 20.090700000000002, + "MeanMs": 20.208180000000002, + "P95Ms": 22.554000000000002, + "MaxMs": 22.554000000000002, + "ThroughputMPixPerSec": 13.04802719666313, + "GcAllocBytesPerOp": 0, + "OutputBytes": 118336, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 31.71124165594157, + "RgbaPsnrDb": 31.941820212359037, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_512_ASTC_6x6_Thorough", + "Category": "GPU_vs_CPU_512", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Thorough", + "WarmupRuns": 1, + "Iterations": 3, + "MinMs": 668.6659000000001, + "MedianMs": 703.4123000000001, + "MeanMs": 701.4114333333333, + "P95Ms": 732.1561, + "MaxMs": 732.1561, + "ThroughputMPixPerSec": 0.3726747456648113, + "GcAllocBytesPerOp": 4096, + "OutputBytes": 118336, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 39.10411518365847, + "RgbaPsnrDb": 37.999660808326176, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_512_ASTC_8x8_Fast", + "Category": "GPU_vs_CPU_512", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_8x8", + "Quality": "Fast", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 3.4631000000000003, + "MedianMs": 3.5162, + "MeanMs": 4.280340000000001, + "P95Ms": 5.6505, + "MaxMs": 5.6505, + "ThroughputMPixPerSec": 74.55321085262499, + "GcAllocBytesPerOp": 0, + "OutputBytes": 65536, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 37.82328035034816, + "RgbaPsnrDb": 34.93831232955961, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_512_ASTC_8x8_Fast", + "Category": "GPU_vs_CPU_512", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_8x8", + "Quality": "Fast", + "WarmupRuns": 1, + "Iterations": 5, + "MinMs": 175.7562, + "MedianMs": 229.2415, + "MeanMs": 227.67186, + "P95Ms": 260.962, + "MaxMs": 260.962, + "ThroughputMPixPerSec": 1.1435276771439724, + "GcAllocBytesPerOp": 3276, + "OutputBytes": 65536, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 41.99044094046325, + "RgbaPsnrDb": 42.120857957278055, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_512_ASTC_8x8_Medium", + "Category": "GPU_vs_CPU_512", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_8x8", + "Quality": "Medium", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 11.0385, + "MedianMs": 11.8375, + "MeanMs": 13.002480000000002, + "P95Ms": 18.6398, + "MaxMs": 18.6398, + "ThroughputMPixPerSec": 22.14521647307286, + "GcAllocBytesPerOp": 0, + "OutputBytes": 65536, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 39.452376239565865, + "RgbaPsnrDb": 37.99502546644384, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_512_ASTC_8x8_Medium", + "Category": "GPU_vs_CPU_512", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_8x8", + "Quality": "Medium", + "WarmupRuns": 1, + "Iterations": 5, + "MinMs": 327.946, + "MedianMs": 373.92900000000003, + "MeanMs": 364.06718, + "P95Ms": 389.10900000000004, + "MaxMs": 389.10900000000004, + "ThroughputMPixPerSec": 0.7010528736738793, + "GcAllocBytesPerOp": 3276, + "OutputBytes": 65536, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 43.13611451487135, + "RgbaPsnrDb": 43.093545277332346, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_512_ASTC_8x8_Thorough", + "Category": "GPU_vs_CPU_512", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_8x8", + "Quality": "Thorough", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 12.0862, + "MedianMs": 12.4115, + "MeanMs": 12.6273, + "P95Ms": 13.3628, + "MaxMs": 13.3628, + "ThroughputMPixPerSec": 21.121057084155822, + "GcAllocBytesPerOp": 0, + "OutputBytes": 65536, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 39.081942246119404, + "RgbaPsnrDb": 37.92068444019468, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_512_ASTC_8x8_Thorough", + "Category": "GPU_vs_CPU_512", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_8x8", + "Quality": "Thorough", + "WarmupRuns": 1, + "Iterations": 3, + "MinMs": 631.2668, + "MedianMs": 675.9754, + "MeanMs": 689.8156333333333, + "P95Ms": 762.2047, + "MaxMs": 762.2047, + "ThroughputMPixPerSec": 0.38780109453687217, + "GcAllocBytesPerOp": 4096, + "OutputBytes": 65536, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 47.47967858447388, + "RgbaPsnrDb": 47.23089217200817, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_512_ASTC_12x12_Fast", + "Category": "GPU_vs_CPU_512", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_12x12", + "Quality": "Fast", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 2.3033, + "MedianMs": 2.3208, + "MeanMs": 2.3386199999999997, + "P95Ms": 2.4247, + "MaxMs": 2.4247, + "ThroughputMPixPerSec": 112.95415374008962, + "GcAllocBytesPerOp": 0, + "OutputBytes": 29584, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 24.038719926033405, + "RgbaPsnrDb": 24.210460117508077, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_512_ASTC_12x12_Fast", + "Category": "GPU_vs_CPU_512", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_12x12", + "Quality": "Fast", + "WarmupRuns": 1, + "Iterations": 5, + "MinMs": 136.28040000000001, + "MedianMs": 158.24190000000002, + "MeanMs": 154.74398, + "P95Ms": 171.7731, + "MaxMs": 171.7731, + "ThroughputMPixPerSec": 1.6566029604042922, + "GcAllocBytesPerOp": 3276, + "OutputBytes": 29584, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 26.30605487174393, + "RgbaPsnrDb": 26.510793230923678, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_512_ASTC_12x12_Medium", + "Category": "GPU_vs_CPU_512", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_12x12", + "Quality": "Medium", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 11.7005, + "MedianMs": 20.3552, + "MeanMs": 17.84424, + "P95Ms": 20.6083, + "MaxMs": 20.6083, + "ThroughputMPixPerSec": 12.878478226693915, + "GcAllocBytesPerOp": 0, + "OutputBytes": 29584, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 24.34345030501926, + "RgbaPsnrDb": 24.558534132224565, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_512_ASTC_12x12_Medium", + "Category": "GPU_vs_CPU_512", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_12x12", + "Quality": "Medium", + "WarmupRuns": 1, + "Iterations": 5, + "MinMs": 250.4934, + "MedianMs": 308.17150000000004, + "MeanMs": 304.94888000000003, + "P95Ms": 369.2776, + "MaxMs": 369.2776, + "ThroughputMPixPerSec": 0.8506432295004566, + "GcAllocBytesPerOp": 3276, + "OutputBytes": 29584, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 27.734647003620406, + "RgbaPsnrDb": 27.61937237544762, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_RGBA8_512_ASTC_12x12_Thorough", + "Category": "GPU_vs_CPU_512", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_12x12", + "Quality": "Thorough", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 10.1324, + "MedianMs": 10.325800000000001, + "MeanMs": 11.079600000000003, + "P95Ms": 12.9783, + "MaxMs": 12.9783, + "ThroughputMPixPerSec": 25.387282341319796, + "GcAllocBytesPerOp": 0, + "OutputBytes": 29584, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 24.288070214311787, + "RgbaPsnrDb": 24.50926032733177, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_RGBA8_512_ASTC_12x12_Thorough", + "Category": "GPU_vs_CPU_512", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_12x12", + "Quality": "Thorough", + "WarmupRuns": 1, + "Iterations": 3, + "MinMs": 519.839, + "MedianMs": 558.4536, + "MeanMs": 556.9486, + "P95Ms": 592.5532000000001, + "MaxMs": 592.5532000000001, + "ThroughputMPixPerSec": 0.46941052936179467, + "GcAllocBytesPerOp": 4096, + "OutputBytes": 29584, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 27.424763700284494, + "RgbaPsnrDb": 27.638260069118967, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_ZeroReadback_1024_6x6_Fast", + "Category": "GPU_ZeroReadback", + "Backend": "GPU", + "Resolution": "1024x1024", + "BlockSize": "ASTC_6x6", + "Quality": "Fast", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 0.5436, + "MedianMs": 2.6978, + "MeanMs": 2.2973800000000004, + "P95Ms": 3.7534, + "MaxMs": 3.7534, + "ThroughputMPixPerSec": 388.6781822225517, + "GcAllocBytesPerOp": 0, + "OutputBytes": 0, + "UncompressedBytes": 4194304, + "RgbPsnrDb": 0.0, + "RgbaPsnrDb": 0.0, + "MeanNormalDeg": 0.0, + "Notes": "Direct CopyTexture (zero CPU readback)" + }, + { + "Name": "GPU_ZeroReadback_MipGen_1024_6x6_Fast", + "Category": "GPU_ZeroReadback", + "Backend": "GPU", + "Resolution": "1024x1024+Mips", + "BlockSize": "ASTC_6x6", + "Quality": "Fast", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 0.6574, + "MedianMs": 0.751, + "MeanMs": 1.0459, + "P95Ms": 1.6328, + "MaxMs": 1.6328, + "ThroughputMPixPerSec": 1861.652463382157, + "GcAllocBytesPerOp": 0, + "OutputBytes": 0, + "UncompressedBytes": 5592404, + "RgbPsnrDb": 0.0, + "RgbaPsnrDb": 0.0, + "MeanNormalDeg": 0.0, + "Notes": "Single-CommandBuffer GPU MipGen + ASTC encode" + }, + { + "Name": "GPU_Normal_512_6x6_Medium", + "Category": "NormalMap", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Medium", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 12.363100000000001, + "MedianMs": 19.2589, + "MeanMs": 17.895720000000004, + "P95Ms": 23.5485, + "MaxMs": 23.5485, + "ThroughputMPixPerSec": 13.611576985186069, + "GcAllocBytesPerOp": 0, + "OutputBytes": 118336, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 0.0, + "RgbaPsnrDb": 0.0, + "MeanNormalDeg": 0.271126460396895, + "Notes": "" + }, + { + "Name": "CPU_Normal_512_6x6_Medium", + "Category": "NormalMap", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Medium", + "WarmupRuns": 1, + "Iterations": 5, + "MinMs": 294.2321, + "MedianMs": 319.2051, + "MeanMs": 328.59056, + "P95Ms": 377.23, + "MaxMs": 377.23, + "ThroughputMPixPerSec": 0.8212400115161066, + "GcAllocBytesPerOp": 4096, + "OutputBytes": 118336, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 0.0, + "RgbaPsnrDb": 0.0, + "MeanNormalDeg": 0.15044781594126685, + "Notes": "" + }, + { + "Name": "GPU_sRGB_512_6x6_Fast", + "Category": "GPU_Modes", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Fast", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 4.2633, + "MedianMs": 6.5738, + "MeanMs": 7.49838, + "P95Ms": 10.5243, + "MaxMs": 10.5243, + "ThroughputMPixPerSec": 39.877087833520946, + "GcAllocBytesPerOp": 0, + "OutputBytes": 118336, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 0.0, + "RgbaPsnrDb": 0.0, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "GPU_HDR16F_512_6x6_Fast", + "Category": "GPU_Modes", + "Backend": "GPU", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Fast", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 0.0098, + "MedianMs": 0.011000000000000001, + "MeanMs": 0.013300000000000001, + "P95Ms": 0.023200000000000002, + "MaxMs": 0.023200000000000002, + "ThroughputMPixPerSec": 23831.272727272724, + "GcAllocBytesPerOp": 0, + "OutputBytes": 0, + "UncompressedBytes": 2097152, + "RgbPsnrDb": 0.0, + "RgbaPsnrDb": 0.0, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_CompressRawPixels_512_6x6_Fast", + "Category": "CPU_ZeroAlloc", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Fast", + "WarmupRuns": 1, + "Iterations": 5, + "MinMs": 171.83110000000002, + "MedianMs": 181.3308, + "MeanMs": 182.50498000000002, + "P95Ms": 191.8865, + "MaxMs": 191.8865, + "ThroughputMPixPerSec": 1.445667255645483, + "GcAllocBytesPerOp": 4096, + "OutputBytes": 118336, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 0.0, + "RgbaPsnrDb": 0.0, + "MeanNormalDeg": 0.0, + "Notes": "" + }, + { + "Name": "CPU_CompressRawPixelsInto_512_6x6_Fast", + "Category": "CPU_ZeroAlloc", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Fast", + "WarmupRuns": 1, + "Iterations": 5, + "MinMs": 180.29340000000002, + "MedianMs": 196.0909, + "MeanMs": 200.31318000000002, + "P95Ms": 216.09220000000002, + "MaxMs": 216.09220000000002, + "ThroughputMPixPerSec": 1.3368493897473057, + "GcAllocBytesPerOp": 4096, + "OutputBytes": 118336, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 0.0, + "RgbaPsnrDb": 0.0, + "MeanNormalDeg": 0.0, + "Notes": "Zero-alloc caller-owned NativeArray + AstcContextPool" + }, + { + "Name": "CPU_Decompress_512_6x6_3T", + "Category": "CPU_Decompress", + "Backend": "CPU", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "N/A", + "WarmupRuns": 2, + "Iterations": 5, + "MinMs": 1.2926, + "MedianMs": 1.5479, + "MeanMs": 2.8080400000000005, + "P95Ms": 7.9678, + "MaxMs": 7.9678, + "ThroughputMPixPerSec": 169.35460947089604, + "GcAllocBytesPerOp": 425984, + "OutputBytes": 1048576, + "UncompressedBytes": 1048576, + "RgbPsnrDb": 0.0, + "RgbaPsnrDb": 0.0, + "MeanNormalDeg": 0.0, + "Notes": "Pooled DecompressOnly (3T)" + }, + { + "Name": "DiskCache_TryLoad_512_6x6_FullMips", + "Category": "Container_Cache", + "Backend": "Disk+GPU", + "Resolution": "512x512+Mips", + "BlockSize": "ASTC_6x6", + "Quality": "N/A", + "WarmupRuns": 1, + "Iterations": 5, + "MinMs": 0.3297, + "MedianMs": 0.6605000000000001, + "MeanMs": 0.6789400000000001, + "P95Ms": 0.9799, + "MaxMs": 0.9799, + "ThroughputMPixPerSec": 529.1824375473126, + "GcAllocBytesPerOp": 127795, + "OutputBytes": 158536, + "UncompressedBytes": 1398100, + "RgbPsnrDb": 0.0, + "RgbaPsnrDb": 0.0, + "MeanNormalDeg": 0.0, + "Notes": "Instant KTX v1 load + GPU upload" + } + ] + }, + "native": [ + { + "SchemaVersion": "1.0", + "TimestampUtc": "2026-11-28T14:07:39.502223+00:00", + "GitCommit": "d3223a509836e324829635f6c8b2fe25f893104a", + "Platform": "Windows AMD64", + "CpuModel": "AMD EPYC 9V74 80-Core Processor", + "CpuCores": 4, + "ThreadsUsed": 4, + "Results": [ + { + "Name": "Native_AVX2_512_ASTC_4x4_Fast_4T", + "Category": "Native_CPU", + "ISA": "AVX2", + "Resolution": "512x512", + "BlockSize": "ASTC_4x4", + "Quality": "Fast", + "Threads": 4, + "OutputBytes": 262144, + "MinMs": 58.763, + "MedianMs": 58.874, + "MeanMs": 61.089, + "P95Ms": 66.531, + "MaxMs": 66.531, + "ThroughputMPixPerSec": 4.453 + }, + { + "Name": "Native_AVX2_512_ASTC_4x4_Medium_4T", + "Category": "Native_CPU", + "ISA": "AVX2", + "Resolution": "512x512", + "BlockSize": "ASTC_4x4", + "Quality": "Medium", + "Threads": 4, + "OutputBytes": 262144, + "MinMs": 180.323, + "MedianMs": 191.237, + "MeanMs": 187.208, + "P95Ms": 192.525, + "MaxMs": 192.525, + "ThroughputMPixPerSec": 1.371 + }, + { + "Name": "Native_AVX2_512_ASTC_6x6_Fast_4T", + "Category": "Native_CPU", + "ISA": "AVX2", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Fast", + "Threads": 4, + "OutputBytes": 118336, + "MinMs": 39.971, + "MedianMs": 40.044, + "MeanMs": 40.107, + "P95Ms": 40.254, + "MaxMs": 40.254, + "ThroughputMPixPerSec": 6.546 + }, + { + "Name": "Native_AVX2_512_ASTC_6x6_Medium_4T", + "Category": "Native_CPU", + "ISA": "AVX2", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Medium", + "Threads": 4, + "OutputBytes": 118336, + "MinMs": 172.891, + "MedianMs": 173.18, + "MeanMs": 175.842, + "P95Ms": 186.411, + "MaxMs": 186.411, + "ThroughputMPixPerSec": 1.514 + }, + { + "Name": "Native_AVX2_512_ASTC_8x8_Fast_4T", + "Category": "Native_CPU", + "ISA": "AVX2", + "Resolution": "512x512", + "BlockSize": "ASTC_8x8", + "Quality": "Fast", + "Threads": 4, + "OutputBytes": 65536, + "MinMs": 31.294, + "MedianMs": 31.441, + "MeanMs": 33.507, + "P95Ms": 40.675, + "MaxMs": 40.675, + "ThroughputMPixPerSec": 8.338 + }, + { + "Name": "Native_AVX2_512_ASTC_8x8_Medium_4T", + "Category": "Native_CPU", + "ISA": "AVX2", + "Resolution": "512x512", + "BlockSize": "ASTC_8x8", + "Quality": "Medium", + "Threads": 4, + "OutputBytes": 65536, + "MinMs": 87.35, + "MedianMs": 87.523, + "MeanMs": 89.625, + "P95Ms": 98.315, + "MaxMs": 98.315, + "ThroughputMPixPerSec": 2.995 + }, + { + "Name": "Native_AVX2_512_ASTC_12x12_Fast_4T", + "Category": "Native_CPU", + "ISA": "AVX2", + "Resolution": "512x512", + "BlockSize": "ASTC_12x12", + "Quality": "Fast", + "Threads": 4, + "OutputBytes": 29584, + "MinMs": 69.794, + "MedianMs": 70.21, + "MeanMs": 70.842, + "P95Ms": 73.022, + "MaxMs": 73.022, + "ThroughputMPixPerSec": 3.734 + }, + { + "Name": "Native_AVX2_512_ASTC_12x12_Medium_4T", + "Category": "Native_CPU", + "ISA": "AVX2", + "Resolution": "512x512", + "BlockSize": "ASTC_12x12", + "Quality": "Medium", + "Threads": 4, + "OutputBytes": 29584, + "MinMs": 297.921, + "MedianMs": 308.518, + "MeanMs": 305.041, + "P95Ms": 311.076, + "MaxMs": 311.076, + "ThroughputMPixPerSec": 0.85 + }, + { + "Name": "Native_AVX2_Decompress_512_ASTC_6x6_4T", + "Category": "Native_CPU_Decompress", + "ISA": "AVX2", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "N/A", + "Threads": 4, + "OutputBytes": 1048576, + "MinMs": 1.244, + "MedianMs": 1.28, + "MeanMs": 1.293, + "P95Ms": 1.369, + "MaxMs": 1.369, + "ThroughputMPixPerSec": 204.848 + }, + { + "Name": "Native_SSE4.1_512_ASTC_4x4_Fast_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_4x4", + "Quality": "Fast", + "Threads": 4, + "OutputBytes": 262144, + "MinMs": 64.665, + "MedianMs": 65.233, + "MeanMs": 66.888, + "P95Ms": 70.172, + "MaxMs": 70.172, + "ThroughputMPixPerSec": 4.019 + }, + { + "Name": "Native_SSE4.1_512_ASTC_4x4_Medium_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_4x4", + "Quality": "Medium", + "Threads": 4, + "OutputBytes": 262144, + "MinMs": 193.89, + "MedianMs": 200.342, + "MeanMs": 199.998, + "P95Ms": 206.889, + "MaxMs": 206.889, + "ThroughputMPixPerSec": 1.308 + }, + { + "Name": "Native_SSE4.1_512_ASTC_6x6_Fast_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Fast", + "Threads": 4, + "OutputBytes": 118336, + "MinMs": 43.821, + "MedianMs": 43.903, + "MeanMs": 43.978, + "P95Ms": 44.255, + "MaxMs": 44.255, + "ThroughputMPixPerSec": 5.971 + }, + { + "Name": "Native_SSE4.1_512_ASTC_6x6_Medium_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Medium", + "Threads": 4, + "OutputBytes": 118336, + "MinMs": 180.349, + "MedianMs": 180.548, + "MeanMs": 183.347, + "P95Ms": 192.336, + "MaxMs": 192.336, + "ThroughputMPixPerSec": 1.452 + }, + { + "Name": "Native_SSE4.1_512_ASTC_8x8_Fast_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_8x8", + "Quality": "Fast", + "Threads": 4, + "OutputBytes": 65536, + "MinMs": 33.927, + "MedianMs": 34.053, + "MeanMs": 36.386, + "P95Ms": 43.321, + "MaxMs": 43.321, + "ThroughputMPixPerSec": 7.698 + }, + { + "Name": "Native_SSE4.1_512_ASTC_8x8_Medium_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_8x8", + "Quality": "Medium", + "Threads": 4, + "OutputBytes": 65536, + "MinMs": 92.349, + "MedianMs": 93.423, + "MeanMs": 95.138, + "P95Ms": 103.63, + "MaxMs": 103.63, + "ThroughputMPixPerSec": 2.806 + }, + { + "Name": "Native_SSE4.1_512_ASTC_12x12_Fast_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_12x12", + "Quality": "Fast", + "Threads": 4, + "OutputBytes": 29584, + "MinMs": 69.488, + "MedianMs": 69.655, + "MeanMs": 71.951, + "P95Ms": 81.051, + "MaxMs": 81.051, + "ThroughputMPixPerSec": 3.763 + }, + { + "Name": "Native_SSE4.1_512_ASTC_12x12_Medium_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_12x12", + "Quality": "Medium", + "Threads": 4, + "OutputBytes": 29584, + "MinMs": 283.726, + "MedianMs": 296.889, + "MeanMs": 294.053, + "P95Ms": 297.927, + "MaxMs": 297.927, + "ThroughputMPixPerSec": 0.883 + }, + { + "Name": "Native_SSE4.1_Decompress_512_ASTC_6x6_4T", + "Category": "Native_CPU_Decompress", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "N/A", + "Threads": 4, + "OutputBytes": 1048576, + "MinMs": 1.843, + "MedianMs": 1.872, + "MeanMs": 1.883, + "P95Ms": 1.992, + "MaxMs": 1.992, + "ThroughputMPixPerSec": 140.042 + } + ] + }, + { + "SchemaVersion": "1.0", + "TimestampUtc": "2026-11-28T14:07:36.824413+00:00", + "GitCommit": "d3223a509836e324829635f6c8b2fe25f893104a", + "Platform": "Darwin arm64", + "CpuModel": "Apple M1 (Virtual)", + "CpuCores": 3, + "ThreadsUsed": 3, + "Results": [ + { + "Name": "Native_ARM64_NEON_512_ASTC_4x4_Fast_3T", + "Category": "Native_CPU", + "ISA": "ARM64_NEON", + "Resolution": "512x512", + "BlockSize": "ASTC_4x4", + "Quality": "Fast", + "Threads": 3, + "OutputBytes": 262144, + "MinMs": 61.302, + "MedianMs": 73.717, + "MeanMs": 73.585, + "P95Ms": 89.827, + "MaxMs": 89.827, + "ThroughputMPixPerSec": 3.556 + }, + { + "Name": "Native_ARM64_NEON_512_ASTC_4x4_Medium_3T", + "Category": "Native_CPU", + "ISA": "ARM64_NEON", + "Resolution": "512x512", + "BlockSize": "ASTC_4x4", + "Quality": "Medium", + "Threads": 3, + "OutputBytes": 262144, + "MinMs": 155.975, + "MedianMs": 186.312, + "MeanMs": 199.06, + "P95Ms": 248.393, + "MaxMs": 248.393, + "ThroughputMPixPerSec": 1.407 + }, + { + "Name": "Native_ARM64_NEON_512_ASTC_6x6_Fast_3T", + "Category": "Native_CPU", + "ISA": "ARM64_NEON", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Fast", + "Threads": 3, + "OutputBytes": 118336, + "MinMs": 34.399, + "MedianMs": 34.682, + "MeanMs": 34.722, + "P95Ms": 35.095, + "MaxMs": 35.095, + "ThroughputMPixPerSec": 7.559 + }, + { + "Name": "Native_ARM64_NEON_512_ASTC_6x6_Medium_3T", + "Category": "Native_CPU", + "ISA": "ARM64_NEON", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Medium", + "Threads": 3, + "OutputBytes": 118336, + "MinMs": 144.503, + "MedianMs": 154.927, + "MeanMs": 162.468, + "P95Ms": 202.133, + "MaxMs": 202.133, + "ThroughputMPixPerSec": 1.692 + }, + { + "Name": "Native_ARM64_NEON_512_ASTC_8x8_Fast_3T", + "Category": "Native_CPU", + "ISA": "ARM64_NEON", + "Resolution": "512x512", + "BlockSize": "ASTC_8x8", + "Quality": "Fast", + "Threads": 3, + "OutputBytes": 65536, + "MinMs": 27.69, + "MedianMs": 28.028, + "MeanMs": 28.125, + "P95Ms": 28.466, + "MaxMs": 28.466, + "ThroughputMPixPerSec": 9.353 + }, + { + "Name": "Native_ARM64_NEON_512_ASTC_8x8_Medium_3T", + "Category": "Native_CPU", + "ISA": "ARM64_NEON", + "Resolution": "512x512", + "BlockSize": "ASTC_8x8", + "Quality": "Medium", + "Threads": 3, + "OutputBytes": 65536, + "MinMs": 71.271, + "MedianMs": 71.789, + "MeanMs": 76.23, + "P95Ms": 90.547, + "MaxMs": 90.547, + "ThroughputMPixPerSec": 3.652 + }, + { + "Name": "Native_ARM64_NEON_512_ASTC_12x12_Fast_3T", + "Category": "Native_CPU", + "ISA": "ARM64_NEON", + "Resolution": "512x512", + "BlockSize": "ASTC_12x12", + "Quality": "Fast", + "Threads": 3, + "OutputBytes": 29584, + "MinMs": 54.552, + "MedianMs": 55.24, + "MeanMs": 55.734, + "P95Ms": 57.326, + "MaxMs": 57.326, + "ThroughputMPixPerSec": 4.746 + }, + { + "Name": "Native_ARM64_NEON_512_ASTC_12x12_Medium_3T", + "Category": "Native_CPU", + "ISA": "ARM64_NEON", + "Resolution": "512x512", + "BlockSize": "ASTC_12x12", + "Quality": "Medium", + "Threads": 3, + "OutputBytes": 29584, + "MinMs": 198.911, + "MedianMs": 232.169, + "MeanMs": 223.726, + "P95Ms": 246.128, + "MaxMs": 246.128, + "ThroughputMPixPerSec": 1.129 + }, + { + "Name": "Native_ARM64_NEON_Decompress_512_ASTC_6x6_3T", + "Category": "Native_CPU_Decompress", + "ISA": "ARM64_NEON", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "N/A", + "Threads": 3, + "OutputBytes": 1048576, + "MinMs": 1.378, + "MedianMs": 1.509, + "MeanMs": 1.587, + "P95Ms": 2.266, + "MaxMs": 2.266, + "ThroughputMPixPerSec": 173.768 + } + ] + }, + { + "SchemaVersion": "1.0", + "TimestampUtc": "2026-11-28T14:07:47.359244+00:00", + "GitCommit": "d3223a509836e324829635f6c8b2fe25f893104a", + "Platform": "Linux x86_64", + "CpuModel": "AMD EPYC 7763 64-Core Processor", + "CpuCores": 4, + "ThreadsUsed": 4, + "Results": [ + { + "Name": "Native_SSE4.1_512_ASTC_4x4_Fast_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_4x4", + "Quality": "Fast", + "Threads": 4, + "OutputBytes": 262144, + "MinMs": 73.24, + "MedianMs": 73.321, + "MeanMs": 73.386, + "P95Ms": 73.768, + "MaxMs": 73.768, + "ThroughputMPixPerSec": 3.575 + }, + { + "Name": "Native_SSE4.1_512_ASTC_4x4_Medium_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_4x4", + "Quality": "Medium", + "Threads": 4, + "OutputBytes": 262144, + "MinMs": 220.288, + "MedianMs": 220.75, + "MeanMs": 221.086, + "P95Ms": 222.05, + "MaxMs": 222.05, + "ThroughputMPixPerSec": 1.188 + }, + { + "Name": "Native_SSE4.1_512_ASTC_6x6_Fast_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Fast", + "Threads": 4, + "OutputBytes": 118336, + "MinMs": 49.998, + "MedianMs": 50.477, + "MeanMs": 50.47, + "P95Ms": 51.025, + "MaxMs": 51.025, + "ThroughputMPixPerSec": 5.193 + }, + { + "Name": "Native_SSE4.1_512_ASTC_6x6_Medium_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "Medium", + "Threads": 4, + "OutputBytes": 118336, + "MinMs": 196.728, + "MedianMs": 197.062, + "MeanMs": 198.472, + "P95Ms": 203.908, + "MaxMs": 203.908, + "ThroughputMPixPerSec": 1.33 + }, + { + "Name": "Native_SSE4.1_512_ASTC_8x8_Fast_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_8x8", + "Quality": "Fast", + "Threads": 4, + "OutputBytes": 65536, + "MinMs": 37.801, + "MedianMs": 37.838, + "MeanMs": 37.865, + "P95Ms": 37.94, + "MaxMs": 37.94, + "ThroughputMPixPerSec": 6.928 + }, + { + "Name": "Native_SSE4.1_512_ASTC_8x8_Medium_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_8x8", + "Quality": "Medium", + "Threads": 4, + "OutputBytes": 65536, + "MinMs": 98.531, + "MedianMs": 98.711, + "MeanMs": 98.964, + "P95Ms": 100.252, + "MaxMs": 100.252, + "ThroughputMPixPerSec": 2.656 + }, + { + "Name": "Native_SSE4.1_512_ASTC_12x12_Fast_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_12x12", + "Quality": "Fast", + "Threads": 4, + "OutputBytes": 29584, + "MinMs": 74.945, + "MedianMs": 75.137, + "MeanMs": 75.161, + "P95Ms": 75.406, + "MaxMs": 75.406, + "ThroughputMPixPerSec": 3.489 + }, + { + "Name": "Native_SSE4.1_512_ASTC_12x12_Medium_4T", + "Category": "Native_CPU", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_12x12", + "Quality": "Medium", + "Threads": 4, + "OutputBytes": 29584, + "MinMs": 298.122, + "MedianMs": 299.777, + "MeanMs": 299.545, + "P95Ms": 301.034, + "MaxMs": 301.034, + "ThroughputMPixPerSec": 0.874 + }, + { + "Name": "Native_SSE4.1_Decompress_512_ASTC_6x6_4T", + "Category": "Native_CPU_Decompress", + "ISA": "SSE4.1", + "Resolution": "512x512", + "BlockSize": "ASTC_6x6", + "Quality": "N/A", + "Threads": 4, + "OutputBytes": 1048576, + "MinMs": 2.146, + "MedianMs": 2.177, + "MeanMs": 2.176, + "P95Ms": 2.213, + "MaxMs": 2.213, + "ThroughputMPixPerSec": 120.441 + } + ] + } + ] +} \ No newline at end of file