utils: gen-shader-headers: Add a utility to generate headers from shaders

Two simple script to generate a header that contains GLSL shaders translated
to C arrays.

Acked-by: Kieran Bingham <kieran.bingham@ideasonboard.com>
Reviewed-by: Milan Zamazal <mzamazal@redhat.com>
Signed-off-by: Bryan O'Donoghue <bryan.odonoghue@linaro.org>
Signed-off-by: Kieran Bingham <kieran.bingham@ideasonboard.com>
This commit is contained in:
Bryan O'Donoghue
2025-12-11 23:22:27 +00:00
committed by Kieran Bingham
parent 8e5a669b29
commit 19371dee41
2 changed files with 92 additions and 0 deletions

37
utils/gen-shader-header.py Executable file
View File

@@ -0,0 +1,37 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2025, Bryan O'Donoghue.
#
# Author: Bryan O'Donoghue <bryan.odonoghue@linaro.org>
#
# A Python script which takes a list of shader files and converts each of them
# into a C header.
#
import sys
try:
with open(sys.argv[2], "rb") as file:
data = file.read()
data_len = len(data)
name = sys.argv[1].replace(".", "_")
name_len = name + "_len"
j = 0
print("unsigned char const", name, "[] = {")
for ch in data:
print(f"0x{ch:02x}, ", end="")
j = (j + 1) % 16
if j == 0:
print()
if j != 0:
print()
print("};")
print()
print(f"const unsigned int {name_len}={data_len};")
except FileNotFoundError:
print(f"File {sys.argv[2]} not found", file=sys.stderr)
except IOError:
print(f"Unable to read {sys.argv[2]}", file=sys.stderr)

55
utils/gen-shader-headers.sh Executable file
View File

@@ -0,0 +1,55 @@
#!/bin/sh
set -e
usage() {
echo "Usage: $0 <src_dir> <build_dir> <output_header_name> <shader_file1> [shader_file2 ...]"
echo
echo "Generates a C header file containing hex-encoded shader data."
echo
echo "Arguments:"
echo " src_dir Path to the base of the source directory"
echo " build_dir Directory where shader files are located and header will be written"
echo " output_header_name Name of the generated header file (relative to build_dir)"
echo " shader_file(s) One or more shader files to embed in the header"
exit 1
}
if [ $# -lt 4 ]; then
echo "Error: Invalid argument count."
usage
fi
src_dir="$1"; shift
build_dir="$1"; shift
build_path=$build_dir/"$1"; shift
cat <<EOF > "$build_path"
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/* This file is auto-generated, do not edit! */
#pragma once
EOF
cat <<EOF >> "$build_path"
/*
* List the names of the shaders at the top of
* header for readability's sake
*
EOF
for file in "$@"; do
name=$(basename "$build_dir/$file" | tr '.' '_')
echo "[SHADER-GEN] $name"
echo " * unsigned char $name;" >> "$build_path"
done
echo "*/" >> "$build_path"
echo "/* Hex encoded shader data */" >> "$build_path"
for file in "$@"; do
name=$(basename "$build_dir/$file")
"$src_dir/utils/gen-shader-header.py" "$name" "$build_dir/$file" >> "$build_path"
echo >> "$build_path"
done