Path: blob/master/modules/dnn/src/vkcom/shader/spirv_generator.py
16345 views
# Iterate all GLSL shaders (with suffix '.comp') in current directory.1#2# Use glslangValidator to compile them to SPIR-V shaders and write them3# into .cpp files as unsigned int array.4#5# Also generate a header file 'spv_shader.hpp' to extern declare these shaders.67import re8import os9import sys1011dir = "./"12license_decl = \13'// This file is part of OpenCV project.\n'\14'// It is subject to the license terms in the LICENSE file found in the top-level directory\n'\15'// of this distribution and at http://opencv.org/license.html.\n'\16'//\n'\17'// Copyright (C) 2018, Intel Corporation, all rights reserved.\n'\18'// Third party copyrights are property of their respective owners.\n\n'19precomp = '#include \"../../precomp.hpp\"\n'20ns_head = '\nnamespace cv { namespace dnn { namespace vkcom {\n\n'21ns_tail = '\n}}} // namespace cv::dnn::vkcom\n'2223headfile = open('spv_shader.hpp', 'w')24headfile.write(license_decl)25headfile.write('#ifndef OPENCV_DNN_SPV_SHADER_HPP\n')26headfile.write('#define OPENCV_DNN_SPV_SHADER_HPP\n\n')27headfile.write(ns_head)2829cmd_remove = ''30null_out = ''31if sys.platform.find('win32') != -1:32cmd_remove = 'del'33null_out = ' >>nul 2>nul'34elif sys.platform.find('linux') != -1:35cmd_remove = 'rm'36null_out = ' > /dev/null 2>&1'3738list = os.listdir(dir)39for i in range(0, len(list)):40if (os.path.splitext(list[i])[-1] != '.comp'):41continue42prefix = os.path.splitext(list[i])[0];43path = os.path.join(dir, list[i])444546bin_file = prefix + '.tmp'47cmd = ' glslangValidator -V ' + path + ' -S comp -o ' + bin_file48print('compiling')49if os.system(cmd) != 0:50continue;51size = os.path.getsize(bin_file)5253spv_txt_file = prefix + '.spv'54cmd = 'glslangValidator -V ' + path + ' -S comp -o ' + spv_txt_file + ' -x' + null_out55os.system(cmd)5657infile_name = spv_txt_file58outfile_name = prefix + '_spv.cpp'59array_name = prefix + '_spv'60infile = open(infile_name, 'r')61outfile = open(outfile_name, 'w')6263outfile.write(license_decl)64outfile.write(precomp)65outfile.write(ns_head)66# xxx.spv ==> xxx_spv.cpp67fmt = 'extern const unsigned int %s[%d] = {\n' % (array_name, size/4)68outfile.write(fmt)69for eachLine in infile:70if(re.match(r'^.*\/\/', eachLine)):71continue72newline = ' ' + eachLine.replace('\t','')73outfile.write(newline)74infile.close()75outfile.write("};\n")76outfile.write(ns_tail)7778# write a line into header file79fmt = 'extern const unsigned int %s[%d];\n' % (array_name, size/4)80headfile.write(fmt)8182os.system(cmd_remove + ' ' + bin_file)83os.system(cmd_remove + ' ' + spv_txt_file)8485headfile.write(ns_tail)86headfile.write('\n#endif /* OPENCV_DNN_SPV_SHADER_HPP */\n')87headfile.close();888990