Skip to content

Commit ba4fc66

Browse files
committed
Feature: Precalculate constant 'sqrt(...)' expressions.
E.g. sqrt(4.0) => 2.0
1 parent 37d25f1 commit ba4fc66

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

ShaderShrinker/Shrinker.Parser/Optimizations/PerformArithmeticExtension.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,21 @@ public static bool PerformArithmetic(this SyntaxNode rootNode)
152152
}
153153
}
154154

155+
// sqrt(-1.1) => <the result>
156+
foreach (var sqrtNode in rootNode.TheTree
157+
.OfType<GlslFunctionCallSyntaxNode>()
158+
.Where(o => o.Name == "sqrt" && o.Params.IsSimpleCsv())
159+
.ToList())
160+
{
161+
var x = sqrtNode.Params.Children.Where(o => o.Token is FloatToken).Select(o => ((FloatToken)o.Token).Number).ToList();
162+
if (x.Count == 1)
163+
{
164+
sqrtNode.Params.Remove();
165+
sqrtNode.ReplaceWith(new GenericSyntaxNode(FloatToken.From(Math.Sqrt(Math.Abs(x[0])), MaxDp)));
166+
didChange = true;
167+
}
168+
}
169+
155170
// vecN(...) + <float>
156171
foreach (var vectorNode in rootNode.TheTree
157172
.OfType<GenericSyntaxNode>()

ShaderShrinker/UnitTests/ShrinkerTests.cs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1545,6 +1545,27 @@ public void CheckArithmeticWithAbsFunction(
15451545
Assert.That(rootNode.ToCode().ToSimple(), Is.EqualTo(expected));
15461546
}
15471547

1548+
[Test, Sequential]
1549+
public void CheckArithmeticWitSqrtFunction(
1550+
[Values("float f = sqrt(4.0);",
1551+
"float f = sqrt(-8.0);",
1552+
"float f; f = sqrt(sqrt(4.));")] string code,
1553+
[Values("float f = 2.;",
1554+
"float f = 2.82843;",
1555+
"float f; f = 1.41421;")] string expected)
1556+
{
1557+
var lexer = new Lexer();
1558+
lexer.Load(code);
1559+
1560+
var options = CustomOptions.None();
1561+
options.PerformArithmetic = true;
1562+
var rootNode = new Parser(lexer)
1563+
.Parse()
1564+
.Simplify(options);
1565+
1566+
Assert.That(rootNode.ToCode().ToSimple(), Is.EqualTo(expected));
1567+
}
1568+
15481569
[Test, Sequential]
15491570
public void CheckArithmeticWithVectorAndScalar(
15501571
[Values("vec2 f = vec2(1.1, 2.2) + 3.3;",

0 commit comments

Comments
 (0)