#!/usr/bin/env python3
"""v0.7.11: embed the GPU upscalers' shader sources into the viewer.

Reads AMD FidelityFX FSR 1 (third_party/fsr1: ffx_a.h, ffx_fsr1.h - MIT) and
NVIDIA Image Scaling (third_party/nis: NIS_Scaler.h, NIS_Config.h - MIT),
strips comments, adapts NIS's Vulkan-style "sampler2D(texture, sampler)"
macros to plain OpenGL samplers, and writes tools/raw-recv/upscale_shaders.h:
the sources as C string literals and NIS's coefficient tables as C arrays.

    python3 tools/raw-recv/gen_upscale_shaders.py
"""
import pathlib, re

REPO = pathlib.Path(__file__).resolve().parents[2]
TP = REPO / "third_party"
OUT = REPO / "tools/raw-recv/upscale_shaders.h"


def strip_comments(src):
    src = re.sub(r"/\*.*?\*/", "", src, flags=re.S)
    out = []
    for line in src.splitlines():
        i = line.find("//")
        if i >= 0:
            line = line[:i]
        line = line.rstrip()
        if line:
            out.append(line)
    return "\n".join(out) + "\n"


def c_string(name, text):
    lines = ['static const char %s[] =' % name]
    for line in text.splitlines():
        lines.append('    "%s\\n"' % line.replace("\\", "\\\\").replace('"', '\\"'))
    lines[-1] += ";"
    return "\n".join(lines) + "\n"


ffx_a = strip_comments((TP / "fsr1/ffx_a.h").read_text())
ffx_fsr1 = strip_comments((TP / "fsr1/ffx_fsr1.h").read_text())

nis = strip_comments((TP / "nis/NIS_Scaler.h").read_text())
# OpenGL has no separate samplers: texture and sampler are one sampler2D
for old, new in [
    ("texelFetch(sampler2D(x, samplerLinearClamp), pos, 0)", "texelFetch(x, pos, 0)"),
    ("textureLod(sampler2D(x, sampler), pos, 0)", "textureLod(x, pos, 0)"),
    ("textureGather(sampler2D(x, sampler), pos, 0)", "textureGather(x, pos, 0)"),
    ("textureGather(sampler2D(x, sampler), pos, 1)", "textureGather(x, pos, 1)"),
    ("textureGather(sampler2D(x, sampler), pos, 2)", "textureGather(x, pos, 2)"),
]:
    assert old in nis, old
    nis = nis.replace(old, new)

cfg = (TP / "nis/NIS_Config.h").read_text()


def table(name):
    m = re.search(r"constexpr float %s\[kPhaseCount\]\[kFilterSize\] = \{(.*?)\};" % name, cfg, re.S)
    assert m, name
    nums = re.findall(r"-?\d+\.\d+(?:e-?\d+)?f?", m.group(1))
    assert len(nums) == 64 * 8, (name, len(nums))
    rows = []
    for r in range(64):
        rows.append("    { " + ", ".join(nums[r * 8:(r + 1) * 8]) + " },")
    return "static const float %s[64][8] = {\n%s\n};\n" % ("nis_" + name, "\n".join(rows))


OUT.write_text(
    "/* generated by gen_upscale_shaders.py - do not edit.\n"
    " * AMD FidelityFX FSR 1 (ffx_a.h, ffx_fsr1.h): Copyright (c) 2021 Advanced Micro Devices, Inc. - MIT\n"
    " * NVIDIA Image Scaling (NIS_Scaler.h, NIS_Config.h): Copyright (c) 2022 NVIDIA CORPORATION & AFFILIATES - MIT\n"
    " * (third_party/fsr1/license.txt, third_party/nis/licence.txt) */\n"
    "#pragma once\n\n"
    + c_string("up_ffx_a", ffx_a) + "\n"
    + c_string("up_ffx_fsr1", ffx_fsr1) + "\n"
    + c_string("up_nis_scaler", nis) + "\n"
    + table("coef_scale") + "\n"
    + table("coef_usm"))
print("wrote", OUT, OUT.stat().st_size, "bytes")
