1#!/usr/bin/python3 2# Copyright 2021 The ANGLE Project Authors. All rights reserved. 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5# 6# create_mtl_internal_shaders.py: 7# Script to compile a metalLib into NSData, for including the compilded 8# library in the ANGLE dylib. 9 10import os 11import sys 12import json 13from datetime import datetime 14 15sys.path.append('../..') 16 17template_header_boilerplate = """// GENERATED FILE - DO NOT EDIT. 18// Generated by {script_name} 19// 20// Copyright {copyright_year} The ANGLE Project Authors. All rights reserved. 21// Use of this source code is governed by a BSD-style license that can be 22// found in the LICENSE file. 23// 24""" 25 26 27# Convert content of a file to byte array and store in a header file. 28# variable_name: name of C++ variable that will hold the file content as byte array. 29# filename: the file whose content will be converted to C++ byte array. 30# dest_src_file: destination header file that will contain the byte array. 31def append_file_as_byte_array_string(variable_name, filename, dest_src_file): 32 string = '// Generated from {0}:\n'.format(filename) 33 string += 'constexpr uint8_t {0}[]={{\n'.format(variable_name) 34 bytes_ = open(filename, "rb").read() 35 for byte in bytes_: 36 string += '0x{:02x}'.format(byte) + ", " 37 string += "\n};\n" 38 with open(dest_src_file, "a") as out_file: 39 out_file.write(string) 40 41 42# Compile metal shader. 43# compiled_file: The compiled metallib 44# variable_name: name of C++ variable that will hold the compiled binary data as a C array. 45# additional_flags: additional shader compiler flags 46# src_files: metal source files 47def gen_precompiled_shaders(compiled_file, variable_name, output_file): 48 append_file_as_byte_array_string(variable_name, compiled_file, output_file) 49 os.system('echo "constexpr size_t {0}_len=sizeof({0});" >> \"{1}\"'.format( 50 variable_name, output_file)) 51 52 53def main(): 54 input_file = sys.argv[1] 55 output_file = sys.argv[2] 56 os.chdir(sys.path[0]) 57 58 boilerplate_code = template_header_boilerplate.format( 59 script_name=sys.argv[0], copyright_year=datetime.today().year) 60 61 # -------- Compile shaders ----------- 62 # boiler plate code 63 os.system("echo \"{0}\" > \"{1}\"".format(boilerplate_code, output_file)) 64 os.system( 65 'echo "// Compiled binary for Metal default shaders.\n\n" >> \"{0}\"'.format(output_file)) 66 os.system('echo "#include <TargetConditionals.h>\n\n" >> \"{0}\"'.format(output_file)) 67 68 os.system('echo "// clang-format off" >> \"{0}\"'.format(output_file)) 69 70 gen_precompiled_shaders(input_file, 'gMetalBinaryShaders', output_file) 71 72 os.system('echo "// clang-format on" >> \"{0}\"'.format(output_file)) 73 74 75if __name__ == '__main__': 76 sys.exit(main()) 77