shader2cpp 2.47 KB
Newer Older
1 2 3 4 5 6 7 8
#!/usr/bin/python3

from sys import stdout
from os.path import basename
from argparse import ArgumentParser
from re import sub, ASCII
from datetime import datetime

9 10 11 12 13 14
license_text = '''/*
 This Source Code Form is subject to the terms of the Mozilla Public
 License, v. 2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/'''

15 16

argparser = ArgumentParser(description='Convert a set of shaders into cpp source code')
17 18
argparser.add_argument('-e', '--extern',  default=False, action='store_true',
	help="Declare variables with external linkage.")
19 20
argparser.add_argument('-g', '--include-guard', default='',
	help="Protect the file against multiple inclusion.")
21 22
argparser.add_argument('-o', '--output', default='-',
	help="Write the output to the file output, or stdout if omitted or output is '-'.")
23 24
argparser.add_argument('-l', '--license', default=False, action='store_true',
	help="Add license header.")
25 26
argparser.add_argument('-n', '--namespace', default='',
	help="Put the output code inside NAMESPACE.")
27 28 29 30
argparser.add_argument('shaders', nargs='+')
options = argparser.parse_args()


31 32
namespaces = options.namespace.split('::')

33
out = open(options.output, 'w') if options.output != '-' else stdout
34 35
if options.extern and options.output:
	hdr_out = open(options.output.replace(".cpp", ".h"), 'w')
36 37 38 39

if options.license:
	print(license_text, file=out)

40
print("// Generated by shader2cpp.", file=out)
41 42
# Disabled because it mess with git.
#print("// {}".format(datetime.utcnow().isoformat()), file=out)
43
print(file=out)
44 45
print(file=out)

46 47 48 49 50 51
if options.include_guard:
	print("#ifndef", options.include_guard, file=out)
	print("#define", options.include_guard, file=out)
	print(file=out)
	print(file=out)

52 53
if namespaces:
	for ns in namespaces:
54 55 56
		if ns != '':
			print("namespace {}".format(ns), file=out)
			print("{", file=out)
57
	print(file=out)
58 59 60 61

for shader_file in options.shaders:
	with open(shader_file) as shader:
		var_name = sub(r'\W', '_', basename(shader_file), flags=ASCII)
62
		if options.extern:
63
			print('extern const char* {};'.format(var_name), file=hdr_out)
64 65 66
			print('const char* {} ='.format(var_name), file=out)
		else:
			print('static const char* {} ='.format(var_name), file=out)
67 68 69 70
		for line in shader:
			print('\t"{}\\n"'.format(line.rstrip()), file=out)
		print('\t"";', file=out)
		print(file=out)
71 72 73

if namespaces:
	for ns in namespaces:
74 75
		if ns != '':
			print("}", file=out)
76
	print(file=out)
77

78
if options.include_guard:
79
	print("#endif", file=out)
80

81
out.close()