5 using System.Text.RegularExpressions;
6 using SiliconStudio.Shaders;
7 using SiliconStudio.Shaders.Parser;
9 namespace SiliconStudio.Paradox.VisualStudio.
Commands.Shaders
13 private static Regex concatenateTokensRegex =
new Regex(
@"(\w+)?\s*#(#)?\s*(\w+)");
15 private static string[] preprocessorKeywords =
new[] {
"if",
"else",
"elif",
"endif",
"define",
"undef",
"ifdef",
"ifndef",
"line",
"error",
"pragma",
"include" };
17 private static string TransformToken(
string token,
ShaderMacro[] macros = null,
bool emptyIfNotFound =
false)
19 if (macros == null)
return token;
21 foreach (var macro
in macros)
23 if (macro.Name == token)
return macro.Definition;
26 return emptyIfNotFound ? string.Empty : token;
29 private static string EscapeString(
string s)
31 return s.Replace(
"\\",
"\\\\").Replace(
"\"",
"\\\"");
34 private static string ConcatenateTokens(
string source,
ShaderMacro[] macros = null)
36 var stringBuilder =
new StringBuilder(source.Length);
41 var match = concatenateTokensRegex.Match(source, position);
44 if (!match.Success)
return source;
49 stringBuilder.Append(source, position, match.Index - position);
52 bool stringify = !match.Groups[2].Success;
54 var token = match.Groups[3].Value;
55 if (stringify && preprocessorKeywords.Contains(token))
58 stringBuilder.Append(match.Groups[0].Value);
63 stringBuilder.Append(TransformToken(match.Groups[1].Value, macros));
68 stringBuilder.Append(
'"');
70 stringBuilder.Append(EscapeString(TransformToken(token, macros,
true)));
71 stringBuilder.Append(
'"');
75 stringBuilder.Append(TransformToken(match.Groups[3].Value, macros));
80 position = match.Groups[3].Index + match.Groups[3].Length;
81 match = concatenateTokensRegex.Match(source, position);
85 stringBuilder.Append(source, position, source.Length - position);
87 return stringBuilder.ToString();
95 var preprocessedSource = ConcatenateTokens(shaderSource, macros);
96 return PreProcessor.Run(preprocessedSource, filename, macros);
Macro to be used with PreProcessor.
static string Preprocess(string shaderSource, string filename, ShaderMacro[] macros)