# Builds the game that runs inside the Machine: the Doom engine, compiled for the browser, with the
# free game Freedoom: Phase 2 for it to play.
#
#   Engine: Crispy Doom 7.2 (https://github.com/fabiangreffrath/crispy-doom, tag crispy-doom-7.2),
#           GNU General Public License version 2 or later. Compiled from its source with one
#           addition: tools/doom/bosssave.c, which makes the saved games the Machine ships with
#           (tools/doom/saves.py runs it), hooked in by the one-line change in engine.patch. It does
#           nothing unless its own command-line options are given.
#   Game:   Freedoom 0.13.0 (https://github.com/freedoom/freedoom, release v0.13.0), a BSD-style
#           licence. Its data file is shipped compressed and otherwise untouched.
#
# Both are fetched into tools/doom/vendor/ (not kept in git):
#   git clone --depth 1 --branch crispy-doom-7.2 https://github.com/fabiangreffrath/crispy-doom.git
#   freedoom-0.13.0.zip from the Freedoom release page, unpacked into vendor/freedoom/
# Needs Emscripten (emcc) on the path. Writes public/doom/.
#
# Usage: python3 tools/doom/build.py
import gzip
import os
import re
import shutil
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor

HERE = os.path.dirname(os.path.abspath(__file__))
SRC = os.path.join(HERE, "vendor", "crispy-doom")
GAME = os.path.join(HERE, "vendor", "freedoom", "freedoom-0.13.0")
WORK = os.path.join(HERE, "vendor", "build")
OUT = os.path.join(HERE, "..", "..", "public", "doom")

CONFIG_H = """
#define PACKAGE_NAME "Crispy Doom"
#define PACKAGE_TARNAME "crispy-doom"
#define PACKAGE_VERSION "7.2.0"
#define PACKAGE_STRING "Crispy Doom 7.2.0"
#define PROGRAM_PREFIX "crispy-"
#define HAVE_DIRENT_H
#define HAVE_DECL_STRCASECMP 1
#define HAVE_DECL_STRNCASECMP 1
"""

PORTS = ["-sUSE_SDL=2", "-sUSE_SDL_MIXER=2", "-sUSE_SDL_NET=2"]


def listed(cmake, name):
    """The .c files named in a CMake list such as set(NAME ...) or add_library(name STATIC ...)."""
    text = open(cmake).read()
    m = re.search(r"(?:set\(%s|add_library\(%s STATIC)(.*?)\)" % (name, name), text, re.S)
    return [w for w in m.group(1).split() if w.endswith(".c")]


def patch():
    """Applies engine.patch to the engine's source, once."""
    diff = os.path.join(HERE, "engine.patch")
    if subprocess.run(["git", "-C", SRC, "apply", "--reverse", "--check", diff], capture_output=True).returncode == 0:
        return  # already applied
    r = subprocess.run(["git", "-C", SRC, "apply", diff], capture_output=True, text=True)
    if r.returncode:
        sys.exit("engine.patch does not apply:\n" + r.stderr)


def sources():
    files = [os.path.join(HERE, "bosssave.c")]
    top = os.path.join(SRC, "src", "CMakeLists.txt")
    for name in ("COMMON_SOURCE_FILES", "GAME_SOURCE_FILES", "DEHACKED_SOURCE_FILES"):
        files += [os.path.join(SRC, "src", f) for f in listed(top, name)]
    files += [os.path.join(SRC, "src", "doom", f) for f in listed(os.path.join(SRC, "src", "doom", "CMakeLists.txt"), "doom")]
    for lib in ("opl", "pcsound", "textscreen"):
        files += [os.path.join(SRC, lib, f) for f in listed(os.path.join(SRC, lib, "CMakeLists.txt"), lib)]
    return [f for f in files if os.path.exists(f)]


def compile_one(path):
    obj = os.path.join(WORK, os.path.relpath(path, SRC).replace(os.sep, "_").replace("..", "")[:-2] + ".o")
    if os.path.exists(obj) and os.path.getmtime(obj) > os.path.getmtime(path):
        return obj
    includes = [WORK, os.path.join(SRC, "src"), os.path.join(SRC, "src", "doom"), os.path.join(SRC, "opl"), os.path.join(SRC, "pcsound"), os.path.join(SRC, "textscreen")]
    # The engine tells a browser build by the name EMSCRIPTEN, which the compiler no longer sets
    # itself; without it the engine's sound timer waits in a loop that never lets the page breathe.
    cmd = ["emcc", "-c", "-O2", "-std=gnu99", "-w", "-DEMSCRIPTEN", *PORTS, *[f"-I{i}" for i in includes], path, "-o", obj]
    r = subprocess.run(cmd, capture_output=True, text=True)
    if r.returncode:
        sys.exit(f"{path}\n{r.stderr[-3000:]}")
    return obj


def main():
    os.makedirs(WORK, exist_ok=True)
    os.makedirs(OUT, exist_ok=True)
    with open(os.path.join(WORK, "config.h"), "w") as f:
        f.write(CONFIG_H)
    patch()
    files = sources()
    print(len(files), "source files")
    with ThreadPoolExecutor(os.cpu_count()) as pool:
        objects = list(pool.map(compile_one, files))
    link = [
        "emcc", "-O2", *PORTS, *objects, "-o", os.path.join(OUT, "engine.js"),
        "-sMODULARIZE=1", "-sEXPORT_ES6=1", "-sEXPORT_NAME=createEngine", "-sENVIRONMENT=web",
        "-sINVOKE_RUN=0", "-sEXIT_RUNTIME=1", "-sALLOW_MEMORY_GROWTH=1", "-sINITIAL_MEMORY=134217728",
        # The engine runs loops of its own that wait; this lets them give the browser its turn.
        "-sASYNCIFY=1", "-sASYNCIFY_STACK_SIZE=131072",
        # The engine calls its monsters' and weapons' routines through pointers whose argument
        # lists differ, as C of its day allowed. A browser refuses such calls unless told this.
        "-sEMULATE_FUNCTION_POINTER_CASTS=1",
        "-sEXPORTED_RUNTIME_METHODS=FS,callMain,IDBFS,JSEvents,abort", "-lidbfs.js",
        *sys.argv[1:],
    ]
    r = subprocess.run(link, capture_output=True, text=True)
    if r.returncode:
        sys.exit(r.stderr[-4000:])
    # The game's data, compressed: 28 MB as it comes, about 12 MB like this.
    with open(os.path.join(GAME, "freedoom2.wad"), "rb") as wad, gzip.open(os.path.join(OUT, "freedoom2.wad.gz"), "wb", compresslevel=9) as z:
        shutil.copyfileobj(wad, z)
    shutil.copy(os.path.join(GAME, "COPYING.txt"), os.path.join(OUT, "FREEDOOM-COPYING.txt"))
    shutil.copy(os.path.join(GAME, "CREDITS.txt"), os.path.join(OUT, "FREEDOOM-CREDITS.txt"))
    shutil.copy(os.path.join(SRC, "COPYING.md"), os.path.join(OUT, "ENGINE-COPYING.md"))
    shutil.copy(os.path.abspath(__file__), os.path.join(OUT, "build.py"))
    shutil.copy(os.path.join(HERE, "bosssave.c"), os.path.join(OUT, "bosssave.c"))
    shutil.copy(os.path.join(HERE, "engine.patch"), os.path.join(OUT, "engine.patch"))
    for f in sorted(os.listdir(OUT)):
        print(f"{os.path.getsize(os.path.join(OUT, f)) // 1024:>7} KB  {f}")


if __name__ == "__main__":
    main()
