#!/usr/bin/python2
#
# Copyright 2017 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# generate_entry_points.py:
#   Generates the OpenGL bindings and entry point layers for ANGLE.

import sys, os, pprint, json
import xml.etree.ElementTree as etree
from datetime import date

template_entry_point_header = """// GENERATED FILE - DO NOT EDIT.
// Generated by {script_name} using data from {data_source_name}.
//
// Copyright {year} The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// entry_points_gles_{annotation_lower}_autogen.h:
//   Defines the GLES {comment} entry points.

#ifndef LIBGLESV2_ENTRY_POINTS_GLES_{annotation_upper}_AUTOGEN_H_
#define LIBGLESV2_ENTRY_POINTS_GLES_{annotation_upper}_AUTOGEN_H_

{includes}

namespace gl
{{
{entry_points}
}}  // namespace gl

#endif  // LIBGLESV2_ENTRY_POINTS_GLES_{annotation_upper}_AUTOGEN_H_
"""

template_entry_point_source = """// GENERATED FILE - DO NOT EDIT.
// Generated by {script_name} using data from {data_source_name}.
//
// Copyright {year} The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// entry_points_gles_{annotation_lower}_autogen.cpp:
//   Defines the GLES {comment} entry points.

{includes}

namespace gl
{{
{entry_points}}}  // namespace gl
"""

template_entry_points_enum_header = """// GENERATED FILE - DO NOT EDIT.
// Generated by {script_name} using data from {data_source_name}.
//
// Copyright {year} The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// entry_points_enum_autogen.h:
//   Defines the GLES entry points enumeration.

#ifndef LIBGLESV2_ENTRYPOINTSENUM_AUTOGEN_H_
#define LIBGLESV2_ENTRYPOINTSENUM_AUTOGEN_H_

namespace gl
{{
enum class EntryPoint
{{
{entry_points_list}
}};
}}  // namespace gl
#endif  // LIBGLESV2_ENTRY_POINTS_ENUM_AUTOGEN_H_
"""

template_entry_point_decl = """ANGLE_EXPORT {return_type}GL_APIENTRY {name}({params});"""

template_entry_point_def = """{return_type}GL_APIENTRY {name}({params})
{{
    EVENT("({format_params})"{comma_if_needed}{pass_params});

    Context *context = {context_getter}();
    if (context)
    {{{packed_gl_enum_conversions}
        context->gatherParams<EntryPoint::{name}>({internal_params});

        if (context->skipValidation() || Validate{name}({validate_params}))
        {{
            {return_if_needed}context->{name_lower_no_suffix}({internal_params});
        }}
    }}
{default_return_if_needed}}}
"""

def script_relative(path):
    return os.path.join(os.path.dirname(sys.argv[0]), path)

tree = etree.parse(script_relative('gl.xml'))
root = tree.getroot()
commands = root.find(".//commands[@namespace='GL']")

with open(script_relative('entry_point_packed_gl_enums.json')) as f:
    cmd_packed_gl_enums = json.loads(f.read())

def format_entry_point_decl(cmd_name, proto, params):
    return template_entry_point_decl.format(
        name = cmd_name[2:],
        return_type = proto[:-len(cmd_name)],
        params = ", ".join(params))

def type_name_sep_index(param):
    space = param.rfind(" ")
    pointer = param.rfind("*")
    return max(space, pointer)

def just_the_type(param):
    return param[:type_name_sep_index(param)]

def just_the_name(param):
    return param[type_name_sep_index(param)+1:]

def just_the_name_packed(param, reserved_set):
    name = just_the_name(param)
    if name in reserved_set:
        return name + 'Packed'
    else:
        return name

format_dict = {
    "GLbitfield": "0x%X",
    "GLboolean": "%u",
    "GLenum": "0x%X",
    "GLfloat": "%f",
    "GLint": "%d",
    "GLintptr": "%d",
    "GLsizei": "%d",
    "GLsizeiptr": "%d",
    "GLsync": "0x%0.8p",
    "GLuint": "%u",
    "GLuint64": "%llu"
}

def param_format_string(param):
    if "*" in param:
        return param + " = 0x%0.8p"
    else:
        type_only = just_the_type(param)
        if type_only not in format_dict:
            raise Exception(type_only + " is not a known type in 'format_dict'")

        return param + " = " + format_dict[type_only]

def default_return_value(cmd_name, return_type):
    if return_type == "void":
        return ""
    return "GetDefaultReturnValue<EntryPoint::" + cmd_name[2:] + ", " + return_type + ">()"

def get_context_getter_function(cmd_name):
    if cmd_name == "glGetError":
        return "GetGlobalContext"
    else:
        return "GetValidGlobalContext"

def format_entry_point_def(cmd_name, proto, params):
    packed_gl_enums = cmd_packed_gl_enums.get(cmd_name, {})
    internal_params = [just_the_name_packed(param, packed_gl_enums) for param in params]
    packed_gl_enum_conversions = []
    for param in params:
        name = just_the_name(param)
        if name in packed_gl_enums:
            internal_name = name + "Packed"
            internal_type = packed_gl_enums[name]
            packed_gl_enum_conversions += ["\n        " + internal_type + " " + internal_name +" = FromGLenum<" +
                                          internal_type + ">(" + name + ");"]

    pass_params = [just_the_name(param) for param in params]
    format_params = [param_format_string(param) for param in params]
    return_type = proto[:-len(cmd_name)]
    default_return = default_return_value(cmd_name, return_type.strip())
    name_lower_no_suffix = cmd_name[2:3].lower() + cmd_name[3:]

    return template_entry_point_def.format(
        name = cmd_name[2:],
        name_lower_no_suffix = name_lower_no_suffix,
        return_type = return_type,
        params = ", ".join(params),
        internal_params = ", ".join(internal_params),
        packed_gl_enum_conversions = "".join(packed_gl_enum_conversions),
        pass_params = ", ".join(pass_params),
        comma_if_needed = ", " if len(params) > 0 else "",
        validate_params = ", ".join(["context"] + internal_params),
        format_params = ", ".join(format_params),
        return_if_needed = "" if default_return == "" else "return ",
        default_return_if_needed = "" if default_return == "" else "\n    return " + default_return + ";\n",
        context_getter = get_context_getter_function(cmd_name))

def path_to(folder, file):
    return os.path.join(script_relative(".."), "src", folder, file)

def get_entry_points(all_commands, gles_commands):

    decls = []
    defs = []

    for command in all_commands:
        proto = command.find('proto')
        cmd_name = proto.find('name').text

        if cmd_name not in gles_commands:
            continue

        param_text = ["".join(param.itertext()) for param in command.findall('param')]
        proto_text = "".join(proto.itertext())

        decls.append(format_entry_point_decl(cmd_name, proto_text, param_text))
        defs.append(format_entry_point_def(cmd_name, proto_text, param_text))

    return decls, defs

def write_file(annotation, comment, template, entry_points, suffix, includes):

    content = template.format(
        script_name = os.path.basename(sys.argv[0]),
        data_source_name = "gl.xml",
        year = date.today().year,
        annotation_lower = annotation.lower(),
        annotation_upper = annotation.upper(),
        comment = comment,
        includes = includes,
        entry_points = entry_points)

    path = path_to("libGLESv2", "entry_points_gles_{}_autogen.{}".format(
        annotation.lower(), suffix))

    with open(path, "w") as out:
        out.write(content)
        out.close()

all_commands = root.findall('commands/command')
all_cmd_names = []

template_header_includes = """#include <GLES{}/gl{}{}.h>
#include <export.h>"""

template_sources_includes = """#include "libANGLE/Context.h"
#include "libANGLE/validationES{}{}.h"
#include "libGLESv2/global_state.h"
"""

# First run through the main GLES entry points.
for major_version, minor_version in [[2, 0], [3, 0], [3, 1]]:
    annotation = "{}_{}".format(major_version, minor_version)
    comment = annotation.replace("_", ".")
    gles_xpath = ".//feature[@name='GL_ES_VERSION_{}']//command".format(annotation)
    gles_commands = [cmd.attrib['name'] for cmd in root.findall(gles_xpath)]
    all_cmd_names += gles_commands

    decls, defs = get_entry_points(all_commands, gles_commands)

    minor_if_not_zero = minor_version if minor_version != 0 else ""

    header_includes = template_header_includes.format(
        major_version, major_version, minor_if_not_zero)

    # We include the platform.h header since it undefines the conflicting MemoryBarrier macro.
    if major_version == 3 and minor_version == 1:
        header_includes += "\n#include \"common/platform.h\"\n"

    source_includes = template_sources_includes.format(major_version, minor_if_not_zero)

    write_file(annotation, comment, template_entry_point_header,
               "\n".join(decls), "h", header_includes)
    write_file(annotation, comment, template_entry_point_source,
               "\n".join(defs), "cpp", source_includes)

# TODO(jmadill): Remove manually added entry points once we auto-gen them.
all_cmd_names += ["glDrawElementsInstancedANGLE"]

sorted_cmd_names = ["Invalid"] + [cmd[2:] for cmd in sorted(all_cmd_names)]

entry_points_enum = template_entry_points_enum_header.format(
    script_name = os.path.basename(sys.argv[0]),
    data_source_name = "gl.xml",
    year = date.today().year,
    entry_points_list = ",\n".join(["    " + cmd for cmd in sorted_cmd_names]))

entry_points_enum_header_path = path_to("libANGLE", "entry_points_enum_autogen.h")
with open(entry_points_enum_header_path, "w") as out:
    out.write(entry_points_enum)
    out.close()
