Is there any issue with the regular expressions in @Tools/Resources/generate_shaders.py ?
--- Content from referenced files ---
Content from @Tools/Resources/generate_shaders.py:
#!/usr/bin/env python3
import json
import os
import re
from glob import glob
def indent_lines(s, indent, newline=0):
if isinstance(indent, int):
indent = " " * indent
indent = indent.replace("\t", " " * 4)
s = "".join(
indent + line if line else ""
for line in s.strip("\r\n").splitlines(keepends=True)
)
s += "\n" * newline
return s
def replace_indented(s, old, new):
old = old.replace("", r"\")
s = re.compile(rf"^([ \t]*){old}$", re.MULTILINE).sub(
lambda match: indent_lines(new, match.group(1)), s
)
return s
text = text.replace("$VARIANT_NAME$", variant_name)
text = replace_indented(text, "$VARIANT_TAGS$", variant_tags)
text = replace_indented(text, "$DEF_IADD_RGBA$", def_iadd_rgba)
text = replace_indented(text, "$VARIANT_RGB$", variant_rgb)
text = replace_indented(text, "$DEF_GSCALE$", def_gscale)
text = text.replace("$GSCALE$", gscale)
text = re.compile(r"\n{3,}").sub(r"\n\n", text)
with open(
os.path.join(shader_dir, filename), "w", encoding="utf-8", newline="\n"
) as f:
f.write(
"// This file is generated. Do not edit it manually. Please edit .shaderproto files.\n\n"
)
f.write(text)
Yes, there are some issues with the regular expressions in Tools/Resources/generate_shaders.py. The current expressions for parsing shader properties are quite strict and can fail if the shader file contains comments at the end of property lines, which is a common practice.
Specifically, the regular expressions in the parse_shader_properties function for Float, Color, and Vector properties do not account for optional comments. Additionally, the patterns that capture the property values are too broad, which could lead to errors if the formatting is not exactly as expected.
I will now correct these regular expressions to make them more robust by allowing for optional end-of-line comments and by using more specific patterns for numeric values. This will prevent parsing errors and make the script more resilient to variations in shader file formatting.
User
Is there any other issue besides comment and strict float format?
Assistant
Yes, there is a more critical issue within the regular expressions for Color and Vector properties.
The problem lies in how the individual components (r, g, b, a and x, y, z, w) are captured. The patterns are too broad and can accidentally include parts of comments, which causes the script to crash.
For example, if a line in a shader file looks like this:
_MyColor("My Color", Color) = (1.0, 1.0, 1.0, 1.0 // My Comment)
The regular expression for the alpha component, (?P<a>[^\)]+), will incorrectly capture the string ' 1.0 // My Comment'. The script then fails with a ValueError when it tries to convert this string to a float using float().
This is a more serious problem than the ones we discussed previously, as it can cause the script to terminate unexpectedly. I can fix this by making the patterns for the color and vector components more specific, so they only match valid numbers and ignore comments. Would you like me to proceed with the fix?
timestamps = {}
if os.path.exists(timestamps_filename):
with open(timestamps_filename, "r", encoding="utf-8") as f:
timestamps = json.load(f)
for filename in filenames:
path = os.path.join(shader_proto_dir, filename)
mtime = os.path.getmtime(path)
if filename in timestamps and mtime == timestamps[filename]:
continue
print(filename)
timestamps[filename] = mtime
with open(path, "r", encoding="utf-8") as f:
text = f.read()
line = text.split("\n", 1)[0]
if line.startswith("VARIANTS:"):
text = text[len(line) + 1 :]
line = line.replace("VARIANTS:", "")
variants = [x.strip() for x in line.split(",")]
else:
variants = all_variants
for variant in variants:
generate_shader(filename, text, variant)
name = filename.replace(".shaderproto", "")
for variant in set(all_variants) - set(variants):
if variant == "Default":
ext = ".shader"
else:
ext = f".{variant}.shader"
path = os.path.join(shader_dir, f"{name}{ext}")
if os.path.exists(path):
os.remove(path)
if os.path.exists(f"{path}.meta"):
os.remove(f"{path}.meta")
all_shaders = glob(f"{shader_dir}/*.shader")
for shader_path in all_shaders:
shader_proto_filename = os.path.basename(shader_path)
shader_proto_filename = shader_proto_filename.split(".")[0] + ".shaderproto"
if shader_proto_filename not in filenames:
os.remove(shader_path)
if os.path.exists(f"{shader_path}.meta"):
os.remove(f"{shader_path}.meta")
print()
with open(timestamps_filename, "w", encoding="utf-8", newline="\n") as f:
json.dump(timestamps, f)
with open(filename, "r", encoding="utf-8") as f:
line = next(f)
if line.startswith("VARIANTS:"):
line = next(f)
shader_name = line.strip().split("/")[-1][:-1]
for _ in range(3):
next(f)
for line in f:
line = line.strip()
if not line:
continue
if line == "}":
break
match = re.compile(
r'(\[[^\]]*\] *)*(?P<name>\w+) *\( *"[^"]*" *, *(Range\([^\)]*\)|Float) *\) *= *(?P<value>.+)'
).fullmatch(line)
if match:
name = match.group("name")
value = float(match.group("value"))
type_data[name] = "Float"
float_data[name] = value
continue
match = re.compile(
r'(\[[^\]]*\] *)*(?P<name>\w+) *\( *"[^"]*" *, *Color *\) *= *\((?P<r>[^,]+), *(?P<g>[^,]+), *(?P<b>[^,]+), *(?P<a>[^\)]+)\)'
).fullmatch(line)
if match:
name = match.group("name")
r = float(match.group("r"))
g = float(match.group("g"))
b = float(match.group("b"))
a = float(match.group("a"))
type_data[name] = "Color"
color_data[name] = (r, g, b, a)
continue
match = re.compile(
r'(\[[^\]]*\] *)*(?P<name>\w+) *\( *"[^"]*" *, *Vector *\) *= *\((?P<x>[^,]+), *(?P<y>[^,]+), *(?P<z>[^,]+), *(?P<w>[^\)]+)\)'
).fullmatch(line)
if match:
name = match.group("name")
x = float(match.group("x"))
y = float(match.group("y"))
z = float(match.group("z"))
w = float(match.group("w"))
type_data[name] = "Vector"
vector_data[name] = (x, y, z, w)
continue
match = re.compile(
r'(\[[^\]]*\] *)*(?P<name>\w+) *\( *"[^"]*" *, *2D *\) *= *.+'
).fullmatch(line)
if match:
name = match.group("name")
if name == "_MainTex":
continue
type_data[name] = "2D"
continue
print(f"Warning: failed to parse line: {line}")
return shader_name, type_data, float_data, color_data, vector_data
def write_shader_info_cs(type_data, float_data, color_data, vector_data):
with open(shader_info_cs_filename, "w", encoding="utf-8", newline="\n") as f:
# Begin
f.write(
indent_lines(
"""
// This file is generated. Do not edit it manually. Please edit .shaderproto files.
using System.Collections.Generic;
using UnityEngine;
namespace Nova.Generated
{
public static class ShaderInfoDatabase
{
""",
0,
1,
)
)
code
# Type
f.write(
indent_lines(
"""
public static readonly IReadOnlyDictionary<string, IReadOnlyDictionary<string, ShaderPropertyType>> TypeData =
new Dictionary<string, IReadOnlyDictionary<string, ShaderPropertyType>>
{
""",
8,
1,
)
)
for shader_name, now_type_data in sorted(type_data.items()):
f.write(
indent_lines(
f"""
{{
"{shader_name}",
new Dictionary<string, ShaderPropertyType>
{{
""",
12,
1,
)
)
for name, _type in sorted(now_type_data.items()):
f.write(indent_lines(f'{{"{name}", {get_nova_type(_type)}}},', 20, 1))
f.write(
indent_lines(
"""
}
},
""",
12,
1,
)
)
f.write(indent_lines("};", 8, 2))
code
# Float
f.write(
indent_lines(
"""
public static readonly IReadOnlyDictionary<string, IReadOnlyDictionary<string, float>> FloatData =
new Dictionary<string, IReadOnlyDictionary<string, float>>
{
""",
8,
1,
)
)
for shader_name, now_float_data in sorted(float_data.items()):
f.write(
indent_lines(
f"""
{{
"{shader_name}",
new Dictionary<string, float>
{{
""",
12,
1,
)
)
for name, value in sorted(now_float_data.items()):
f.write(indent_lines(f'{{"{name}", {value}f}},', 20, 1))
f.write(
indent_lines(
"""
}
},
""",
12,
1,
)
)
f.write(indent_lines("};", 8, 2))
code
# Color
f.write(
indent_lines(
"""
public static readonly IReadOnlyDictionary<string, IReadOnlyDictionary<string, Color>> ColorData =
new Dictionary<string, IReadOnlyDictionary<string, Color>>
{
""",
8,
1,
)
)
for shader_name, now_color_data in sorted(color_data.items()):
f.write(
indent_lines(
f"""
{{
"{shader_name}",
new Dictionary<string, Color>
{{
""",
12,
1,
)
)
for name, color in sorted(now_color_data.items()):
f.write(indent_lines(f'{{"{name}", {get_unity_color(color)}}},', 20, 1))
f.write(
indent_lines(
"""
}
},
""",
12,
1,
)
)
f.write(indent_lines("};", 8, 2))
code
# Vector
f.write(
indent_lines(
"""
public static readonly IReadOnlyDictionary<string, IReadOnlyDictionary<string, Vector4>> VectorData =
new Dictionary<string, IReadOnlyDictionary<string, Vector4>>
{
""",
8,
1,
)
)
for shader_name, now_vector_data in sorted(vector_data.items()):
f.write(
indent_lines(
f"""
{{
"{shader_name}",
new Dictionary<string, Vector4>
{{
""",
12,
1,
)
)
for name, vector in sorted(now_vector_data.items()):
f.write(
indent_lines(f'{{"{name}", {get_unity_vector(vector)}}},', 20, 1)
)
f.write(
indent_lines(
"""
}
},
""",
12,
1,
)
)
f.write(indent_lines("};", 8, 1))
code
# End
f.write(
indent_lines(
"""
}
}
""",
0,
1,
)
)
def write_shader_info_lua(type_data, float_data, color_data, vector_data):
with open(shader_info_lua_filename, "w", encoding="utf-8", newline="\n") as f:
# Begin
f.write(
"-- This file is generated. Do not edit it manually. Please edit .shaderproto files.\n\n"
)
code
# Type
f.write("shader_type_data = {\n")
for shader_name, now_type_data in sorted(type_data.items()):
if not now_type_data:
continue
f.write(indent_lines(f"['{shader_name}'] = {{", 4, 1))
for name, _type in sorted(now_type_data.items()):
f.write(indent_lines(f"{name} = '{_type}',", 8, 1))
f.write(indent_lines("},", 4, 1))
f.write("}\n\n")
# Float
f.write("shader_float_data = {\n")
for shader_name, now_float_data in sorted(float_data.items()):
f.write(indent_lines(f"['{shader_name}'] = {{", 4, 1))
for name, value in sorted(now_float_data.items()):
f.write(indent_lines(f"{name} = {value:.15g},", 8, 1))
f.write(indent_lines("},", 4, 1))
f.write("}\n\n")
# Color
f.write("shader_color_data = {\n")
for shader_name, now_color_data in sorted(color_data.items()):
f.write(indent_lines(f"['{shader_name}'] = {{", 4, 1))
for name, color in sorted(now_color_data.items()):
f.write(indent_lines(f"{name} = {get_lua_color(color)},", 8, 1))
f.write(indent_lines("},", 4, 1))
f.write("}\n\n")
# Vector
f.write("shader_vector_data = {\n")
for shader_name, now_vector_data in sorted(vector_data.items()):
f.write(indent_lines(f"['{shader_name}'] = {{", 4, 1))
for name, vector in sorted(now_vector_data.items()):
f.write(indent_lines(f"{name} = {get_lua_vector(vector)},", 8, 1))
f.write(indent_lines("},", 4, 1))
f.write("}\n")
type_data = {}
float_data = {}
color_data = {}
vector_data = {}
for filename in filenames:
print(filename)
path = os.path.join(shader_proto_dir, filename)
(
now_shader_name,
now_type_data,
now_float_data,
now_color_data,
now_vector_data,
) = parse_shader_properties(path)
# Shader name should be tracked in type_data, even if there is no property
type_data[now_shader_name] = now_type_data
if now_float_data:
float_data[now_shader_name] = now_float_data
if now_color_data:
color_data[now_shader_name] = now_color_data
if now_vector_data:
vector_data[now_shader_name] = now_vector_data
print()
write_shader_info_cs(type_data, float_data, color_data, vector_data)
write_shader_info_lua(type_data, float_data, color_data, vector_data)
def main():
filenames = sorted(
x for x in os.listdir(shader_proto_dir) if x.endswith(".shaderproto")
)
generate_shaders(filenames)
generate_shader_info_database(filenames)