#!/usr/bin/env python3
#
# Copyright (C) 2016 Google, Inc.
#
# 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.

"""Compile GLSL to SPIR-V.

Depends on glslangValidator.
"""

import os
import sys
import subprocess
import struct
import re

SPIRV_MAGIC = 0x07230203
COLUMNS = 4
INDENT = 4

in_filename = sys.argv[1]
out_filename = sys.argv[2] if len(sys.argv) > 2 else None
validator = sys.argv[3] if len(sys.argv) > 3 else \
        "../../../glslang/build/install/bin/glslangValidator"

def identifierize(s):
    # translate invalid chars
    s = re.sub("[^0-9a-zA-Z_]", "_", s)
    # translate leading digits
    return re.sub("^[^a-zA-Z_]+", "_", s)

def compile_glsl(filename, tmpfile):
    # invoke glslangValidator
    try:
        args = [validator, "-V", "-H", "-o", tmpfile, filename]
        output = subprocess.check_output(args, universal_newlines=True)
    except subprocess.CalledProcessError as e:
        print(e.output, file=sys.stderr)
        exit(1)

    # read the temp file into a list of SPIR-V words
    words = []
    with open(tmpfile, "rb") as f:
        data = f.read()
        assert(len(data) and len(data) % 4 == 0)

        # determine endianness
        fmt = ("<" if data[0] == (SPIRV_MAGIC & 0xff) else ">") + "I"
        for i in range(0, len(data), 4):
            words.append(struct.unpack(fmt, data[i:(i + 4)])[0])

        assert(words[0] == SPIRV_MAGIC)


    # remove temp file
    os.remove(tmpfile)

    return (words, output.rstrip())

base = os.path.basename(in_filename)
words, comments = compile_glsl(in_filename, base + ".tmp")

literals = []
for i in range(0, len(words), COLUMNS):
    columns = ["0x%08x" % word for word in words[i:(i + COLUMNS)]]
    literals.append(" " * INDENT + ", ".join(columns) + ",")

header = """#include <stdint.h>

#if 0
%s
#endif

static const uint32_t %s[%d] = {
%s
};
""" % (comments, identifierize(base), len(words), "\n".join(literals))

if out_filename:
    with open(out_filename, "w") as f:
        print(header, end="", file=f)
else:
        print(header, end="")