From 21e474b342f368f582f491e94999e317ae7af28a Mon Sep 17 00:00:00 2001 From: Rafael Vuijk <133344302+Rafael-SOWNet@users.noreply.github.com> Date: Fri, 30 Oct 2026 20:12:42 +0100 Subject: [PATCH 1/4] Shader source: MathS.Shaders.Hlsl and Glsl Prints expressions as straight-line HLSL or GLSL: one assignment per output, every repeated subexpression computed once into a local, and in HLSL one sincos for a sin and cos of the same argument. The use is an exact gradient or a closed-form physical law derived on the CPU and run on the GPU. The code computes the real-valued reading that Compile computes, and the tests hold the printed text to it: the same printer writes C# against helpers named as HLSL's intrinsics, Roslyn compiles that text, and it is compared with Compile at 200 points per case, each case required to have at least 50 points with a real value. What has no faithful form is declined with the node named rather than printed approximately: complex constants, Providedf, a piecewise without a final always-true case, names that are not identifiers, and nodes such as factorial and round. Integer powers above the fourth go through pow(abs(x), n) with the sign restored for odd n, since pow of a negative base is undefined in both languages, and mod is printed floored, as Modf is. No clause of Packaging.md section 4 fires: pure managed code and no new referenced assembly (KernelDependenciesTest), beside IntoLinq. No existing answer changes. Measured: UnitTests 18256 passed, 13 skipped, 0 failed (net10.0); FSharpWrapperUnitTests 134 passed; kernel builds warning-free on netstandard2.0, net8.0 and net10.0. Co-Authored-By: Claude Opus 5.5 --- Sources/.editorconfig | 9 + .../AngouriMath/Convenience/MathS.Shaders.cs | 87 ++++++ .../Compilation/IntoSource/GeneratedSource.cs | 24 ++ .../Compilation/IntoSource/ShaderSource.cs | 282 ++++++++++++++++++ Sources/Tests/UnitTests/Common/PublicApi.txt | 17 ++ .../UnitTests/Convenience/ShadersTest.cs | 158 ++++++++++ 6 files changed, 577 insertions(+) create mode 100644 Sources/AngouriMath/Convenience/MathS.Shaders.cs create mode 100644 Sources/AngouriMath/Functions/Compilation/IntoSource/GeneratedSource.cs create mode 100644 Sources/AngouriMath/Functions/Compilation/IntoSource/ShaderSource.cs create mode 100644 Sources/Tests/UnitTests/Convenience/ShadersTest.cs diff --git a/Sources/.editorconfig b/Sources/.editorconfig index 0fa875c6e..de2d5e9dc 100644 --- a/Sources/.editorconfig +++ b/Sources/.editorconfig @@ -1120,3 +1120,12 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed [AngouriMath/Functions/Output/ToString/UnicodeSpelling.cs] file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n + +[AngouriMath/Functions/Compilation/IntoSource/*.cs] +file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n + +[AngouriMath/Convenience/MathS.Shaders.cs] +file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n + +[Tests/UnitTests/Convenience/ShadersTest.cs] +file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n diff --git a/Sources/AngouriMath/Convenience/MathS.Shaders.cs b/Sources/AngouriMath/Convenience/MathS.Shaders.cs new file mode 100644 index 000000000..e46ab4a85 --- /dev/null +++ b/Sources/AngouriMath/Convenience/MathS.Shaders.cs @@ -0,0 +1,87 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using AngouriMath.Functions.Compilation.IntoSource; + +namespace AngouriMath +{ + using static Entity; + + partial class MathS + { + /// + /// Expressions printed as shader source: straight-line HLSL or GLSL that computes each + /// output once, sharing every repeated subexpression. + /// + /// + /// + /// The use is to derive on the CPU what is expensive or error-prone to derive by hand — + /// an exact gradient, a Hessian, a closed form of a physical law — and run the result + /// on the GPU. followed by one of these + /// is an analytic normal for a signed distance field. + /// + /// + /// The code computes the real-valued reading, the one Compile<double, …> + /// computes; where that has no value the shader's is NaN or unspecified, as the + /// language's own pow and sqrt leave it. A node with no faithful form — + /// a complex constant, a set, a piecewise with inputs it gives no value to — is declined + /// with the node named, never printed approximately. + /// + /// + /// Nothing is simplified. Call first if a smaller + /// form is wanted: what is printed is the expression that was given. + /// + /// + public static class Shaders + { + /// + /// HLSL statements assigning each output: float locals for the shared + /// subexpressions, then one assignment per output, in the order given. + /// + /// The target of each assignment — a variable, an + /// out parameter, a swizzle such as n.x — and the expression it gets. + /// + /// What each variable is called in the shader, such as p.x for x. A + /// variable not listed keeps its own name, which has to be an identifier. + /// + /// The source, or which subexpression could not be printed faithfully and why. + /// + /// + /// using System; + /// using System.Collections.Generic; + /// using AngouriMath; + /// + /// Entity r = "sqrt(x^2 + y^2)"; + /// var source = MathS.Shaders.Hlsl(new Dictionary<string, Entity> + /// { + /// ["g.x"] = r.Differentiate("x"), + /// ["g.y"] = r.Differentiate("y"), + /// }.ToList(), new Dictionary<Entity.Variable, string> { ["x"] = "p.x", ["y"] = "p.y" }); + /// Console.Write(source.Code); + /// + /// Prints + /// + /// float am0 = (0.5 * rsqrt(((p.x * p.x) + (p.y * p.y)))); + /// g.x = (am0 * (2.0 * p.x)); + /// g.y = (am0 * (2.0 * p.y)); + /// + /// + public static GeneratedSource Hlsl(IReadOnlyList> outputs, IReadOnlyDictionary? names = null) + => ShaderSource.Emit(SourceDialect.Hlsl, outputs, names); + + /// + /// GLSL statements assigning each output, as prints them, with + /// GLSL's names for the intrinsics that differ. + /// + /// The target of each assignment and the expression it gets. + /// What each variable is called in the shader. + /// The source, or which subexpression could not be printed faithfully and why. + public static GeneratedSource Glsl(IReadOnlyList> outputs, IReadOnlyDictionary? names = null) + => ShaderSource.Emit(SourceDialect.Glsl, outputs, names); + } + } +} diff --git a/Sources/AngouriMath/Functions/Compilation/IntoSource/GeneratedSource.cs b/Sources/AngouriMath/Functions/Compilation/IntoSource/GeneratedSource.cs new file mode 100644 index 000000000..49e4abee4 --- /dev/null +++ b/Sources/AngouriMath/Functions/Compilation/IntoSource/GeneratedSource.cs @@ -0,0 +1,24 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +namespace AngouriMath.Core +{ + /// + /// Source code printed from expressions by , or the reason it was not. + /// + /// The statements; where printing was declined. + /// The subexpression that could not be printed faithfully; on success. + /// Why it could not, in a sentence; empty on success. + public sealed record GeneratedSource(string? Code, Entity? At, string Reason) + { + /// Whether holds the source. + public bool Succeeded => Code is not null; + + /// + public override string ToString() => Code ?? $"Declined at {At}: {Reason}"; + } +} diff --git a/Sources/AngouriMath/Functions/Compilation/IntoSource/ShaderSource.cs b/Sources/AngouriMath/Functions/Compilation/IntoSource/ShaderSource.cs new file mode 100644 index 000000000..e6d8af26b --- /dev/null +++ b/Sources/AngouriMath/Functions/Compilation/IntoSource/ShaderSource.cs @@ -0,0 +1,282 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System; +using System.Globalization; +using System.Text; +using PeterO.Numbers; +using static AngouriMath.Entity; + +namespace AngouriMath.Functions.Compilation.IntoSource +{ + /// The dialects prints. + internal enum SourceDialect + { + Hlsl, + Glsl, + // C# over doubles, against helpers named as HLSL's intrinsics are, so that the exact + // text the shader dialects print can be compiled and checked against the library. + CSharpCheck, + } + + /// + /// Prints expressions as straight-line shader code: one statement per output, with every + /// subexpression that occurs more than once computed once into a local. + /// + /// + /// + /// The code computes what Compile<double, …> computes, the real-valued + /// reading: where the library's value is not real, the shader's is NaN or + /// unspecified, as the shading language's own pow and sqrt leave it. A + /// node with no faithful form in that reading — a complex constant, a set, a rounding + /// rule whose tie-breaking the languages do not agree on — is declined, naming the node, + /// rather than printed as something close. + /// + /// + /// Integer powers are multiplied out up to the fourth, and above that taken as + /// pow(abs(x), n) with the sign restored for an odd n: pow of a + /// negative base is undefined in both HLSL and GLSL, while x^5 is defined for every + /// real x. + /// + /// + internal sealed class ShaderSource + { + private readonly SourceDialect dialect; + private readonly IReadOnlyDictionary names; + private readonly Dictionary uses = new(); + private readonly Dictionary locals = new(); + private readonly HashSet sinCosDone = new(); + private readonly StringBuilder body = new(); + private int next; + + private ShaderSource(SourceDialect dialect, IReadOnlyDictionary names) + => (this.dialect, this.names) = (dialect, names); + + private sealed class Declined : Exception + { + internal Entity At { get; } + internal Declined(Entity at, string reason) : base(reason) => At = at; + } + + // Checked by hand: a regular expression would add System.Text.RegularExpressions to what + // the kernel references, which KernelDependenciesTest holds fixed. + private static bool IsIdentifier(string s) + => s.Length > 0 && !char.IsDigit(s[0]) && s.All(c => c == '_' || c < 128 && char.IsLetterOrDigit(c)); + + internal static GeneratedSource Emit(SourceDialect dialect, IReadOnlyList> outputs, IReadOnlyDictionary? names) + { + var emitter = new ShaderSource(dialect, names ?? new Dictionary()); + try + { + foreach (var output in outputs) + emitter.Count(output.Value); + var lines = new StringBuilder(); + foreach (var output in outputs) + lines.Append(output.Key).Append(" = ").Append(emitter.Value(output.Value)).Append(";\n"); + return new GeneratedSource(emitter.body.ToString() + lines, null, ""); + } + catch (Declined d) + { + return new GeneratedSource(null, d.At, d.Message); + } + } + + private string Real => dialect == SourceDialect.CSharpCheck ? "double" : "float"; + + private static bool IsLeaf(Entity e) => e is Variable or Number or Entity.Boolean; + + private void Count(Entity e) + { + if (IsLeaf(e)) + return; + uses[e] = uses.TryGetValue(e, out var n) ? n + 1 : 1; + // A repeat's children were counted on its first visit, and are computed once inside + // its local. + if (uses[e] > 1) + return; + foreach (var c in e.DirectChildren) + Count(c); + } + + private string Value(Entity e) + { + if (IsLeaf(e)) + return Leaf(e); + if (locals.TryGetValue(e, out var name)) + return name; + if (dialect != SourceDialect.Glsl && e is Sinf or Cosf && TrySinCos(e, out var sc)) + return sc; + var text = Print(e); + return uses.TryGetValue(e, out var n) && n > 1 ? Hoist(e, text, e is Statement ? "bool" : Real) : text; + } + + private string Hoist(Entity e, string text, string type) + { + var name = $"am{next++}"; + body.Append(dialect == SourceDialect.CSharpCheck ? "var" : type).Append(' ').Append(name).Append(" = ").Append(text).Append(";\n"); + locals[e] = name; + return name; + } + + // A value needed twice in one printed form, as x in x * x, goes into a local even when + // it occurs once in the expression, so that it is not computed twice. + private string Once(Entity e) + { + var text = Value(e); + return IsLeaf(e) || locals.ContainsKey(e) ? text : Hoist(e, text, Real); + } + + // sin(a) and cos(a) both wanted: HLSL computes the pair in one call. + private bool TrySinCos(Entity e, out string result) + { + var arg = e.DirectChildren[0]; + result = ""; + if (!uses.ContainsKey(new Sinf(arg)) || !uses.ContainsKey(new Cosf(arg)) || !sinCosDone.Add(arg)) + return false; + var a = Value(arg); + var (s, c) = ($"am{next++}", $"am{next++}"); + body.Append(dialect == SourceDialect.CSharpCheck + ? $"sincos({a}, out var {s}, out var {c});\n" + : $"float {s}, {c};\nsincos({a}, {s}, {c});\n"); + locals[new Sinf(arg)] = s; + locals[new Cosf(arg)] = c; + result = locals[e]; + return true; + } + + private string Leaf(Entity e) => e switch + { + Constant c when c == MathS.pi => Literal(Math.PI), + Constant c when c == MathS.e => Literal(Math.E), + Constant c => throw new Declined(c, $"the constant {c} has no literal here"), + Variable v => Name(v), + Integer i => Literal(EDecimal.FromEInteger(i.EInteger)), + Rational r => Literal(r.ERational.ToEDecimal(EContext.Binary64)), + Real { EDecimal: var d } when d.IsFinite => Literal(d), + Entity.Boolean b => (bool)b ? "true" : "false", + _ => throw new Declined(e, $"{e} is not a finite real number"), + }; + + private string Name(Variable v) + { + var name = names.TryGetValue(v, out var n) ? n : v.Name; + // A swizzle or a member such as p.x is a legitimate target name. + if (!name.Split('.').All(IsIdentifier)) + throw new Declined(v, $"{name} is not an identifier; map it to one through the names"); + if (name.Length > 2 && name.StartsWith("am") && name.Skip(2).All(char.IsDigit)) + throw new Declined(v, $"{name} is the name of a local this code declares"); + return name; + } + + private static string Literal(EDecimal d) => Literal(d.ToDouble()); + + // The shortest text that reads back as the same double, always with a point or an + // exponent, so that neither language takes it for an integer. + private static string Literal(double d) + { + var s = d.ToString("R", CultureInfo.InvariantCulture); + return s.Contains(".") || s.Contains("E") ? s.Replace("E", "e") : s + ".0"; + } + + private string Print(Entity e) => e switch + { + Sumf(var a, var b) => $"({Value(a)} + {Value(b)})", + Minusf(var a, var b) => $"({Value(a)} - {Value(b)})", + Mulf(Integer { EInteger: var k }, var b) when k.Equals(EInteger.FromInt32(-1)) => $"(-{Value(b)})", + Mulf(var a, var b) => $"({Value(a)} * {Value(b)})", + Divf(var a, var b) => $"({Value(a)} / {Value(b)})", + Powf(var b, var p) => Power(e, b, p), + // Floored, as Modf is: the remainder takes the divisor's sign, which neither + // HLSL's fmod nor C's % does. + Modf(var a, var b) => Modulo(a, b), + + Sinf(var a) => $"sin({Value(a)})", + Cosf(var a) => $"cos({Value(a)})", + Tanf(var a) => $"tan({Value(a)})", + Arcsinf(var a) => $"asin({Value(a)})", + Arccosf(var a) => $"acos({Value(a)})", + Arctanf(var a) => $"atan({Value(a)})", + Logf(Constant c, var a) when c == MathS.e => $"log({Value(a)})", + Logf(var b, var a) => $"(log({Value(a)}) / log({Value(b)}))", + Absf(var a) => $"abs({Value(a)})", + // HLSL's sign returns an int, which an arithmetic context converts back exactly. + Signumf(var a) => ToReal($"sign({Value(a)})"), + Floorf(var a) => $"floor({Value(a)})", + Ceilf(var a) => $"ceil({Value(a)})", + Maxf(var a, var b) => $"max({Value(a)}, {Value(b)})", + Minf(var a, var b) => $"min({Value(a)}, {Value(b)})", + + Piecewise pw => Cases(pw), + Greaterf(var a, var b) => $"({Value(a)} > {Value(b)})", + GreaterOrEqualf(var a, var b) => $"({Value(a)} >= {Value(b)})", + Lessf(var a, var b) => $"({Value(a)} < {Value(b)})", + LessOrEqualf(var a, var b) => $"({Value(a)} <= {Value(b)})", + Equalsf(var a, var b) => $"({Value(a)} == {Value(b)})", + Andf(var a, var b) => $"({Value(a)} && {Value(b)})", + Orf(var a, var b) => $"({Value(a)} || {Value(b)})", + Notf(var a) => $"(!{Value(a)})", + + _ => throw new Declined(e, $"{e.GetType().Name} has no faithful form in the real-valued reading"), + }; + + private string Power(Entity at, Entity b, Entity p) + { + if (b is Constant c && c == MathS.e) + return $"exp({Value(p)})"; + if (p is not Rational q) + return $"pow({Value(b)}, {Value(p)})"; + if (q is Integer { EInteger: var k } && k.CanFitInInt32()) + { + var n = k.ToInt32Checked(); + switch (n) + { + case 0: return Literal(1.0); + case 1: return Value(b); + case -1: return $"({Literal(1.0)} / {Value(b)})"; + } + var x = Once(b); + var magnitude = Math.Abs(n) switch + { + 2 => $"({x} * {x})", + 3 => $"({x} * {x} * {x})", + 4 => $"(({x} * {x}) * ({x} * {x}))", + var m when m % 2 == 0 => $"pow(abs({x}), {Literal((double)m)})", + var m => $"({ToReal($"sign({x})")} * pow(abs({x}), {Literal((double)m)}))", + }; + return n > 0 ? magnitude : $"({Literal(1.0)} / {magnitude})"; + } + if (q.ERational.CompareTo(ERational.Create(1, 2)) == 0) + return $"sqrt({Value(b)})"; + if (q.ERational.CompareTo(ERational.Create(-1, 2)) == 0) + return dialect == SourceDialect.Glsl ? $"inversesqrt({Value(b)})" : $"rsqrt({Value(b)})"; + return $"pow({Value(b)}, {Literal(q.ERational.ToEDecimal(EContext.Binary64))})"; + } + + private string ToReal(string integer) + => dialect == SourceDialect.CSharpCheck ? $"((double){integer})" : $"float({integer})"; + + private string Modulo(Entity a, Entity b) + { + var (x, y) = (Once(a), Once(b)); + return $"({x} - {y} * floor({x} / {y}))"; + } + + // A conditional per case, the last one taken as the fallback only where its condition is + // literally true: a piecewise with no case for some input has no value there, and a + // shader cannot say so. + private string Cases(Piecewise pw) + { + var cases = pw.Cases.ToList(); + if (cases.Count == 0 || cases[cases.Count - 1].Predicate != Entity.Boolean.True) + throw new Declined(pw, "a piecewise without a final case that is always true has inputs with no value"); + var text = Value(cases[cases.Count - 1].Expression); + for (var k = cases.Count - 2; k >= 0; k--) + text = $"({Value(cases[k].Predicate)} ? {Value(cases[k].Expression)} : {text})"; + return text; + } + } +} diff --git a/Sources/Tests/UnitTests/Common/PublicApi.txt b/Sources/Tests/UnitTests/Common/PublicApi.txt index 91a806ac6..bc19e0b89 100644 --- a/Sources/Tests/UnitTests/Common/PublicApi.txt +++ b/Sources/Tests/UnitTests/Common/PublicApi.txt @@ -203,6 +203,19 @@ AngouriMath.Core.FiniteSetBuilder.Remove(AngouriMath.Entity) : System.Void AngouriMath.Core.FiniteSetBuilder.ToFiniteSet() : AngouriMath.Entity+Set+FiniteSet AngouriMath.Core.FiniteSetBuilder.ctor() AngouriMath.Core.FiniteSetBuilder.ctor(System.Collections.Generic.IEnumerable) +AngouriMath.Core.GeneratedSource.$() : AngouriMath.Core.GeneratedSource +AngouriMath.Core.GeneratedSource.At { } : AngouriMath.Entity +AngouriMath.Core.GeneratedSource.Code { } : System.String +AngouriMath.Core.GeneratedSource.Deconstruct(System.String&, AngouriMath.Entity&, System.String&) : System.Void +AngouriMath.Core.GeneratedSource.Equals(AngouriMath.Core.GeneratedSource) : System.Boolean +AngouriMath.Core.GeneratedSource.Equals(System.Object) : System.Boolean +AngouriMath.Core.GeneratedSource.GetHashCode() : System.Int32 +AngouriMath.Core.GeneratedSource.Reason { } : System.String +AngouriMath.Core.GeneratedSource.Succeeded { } : System.Boolean +AngouriMath.Core.GeneratedSource.ToString() : System.String +AngouriMath.Core.GeneratedSource.ctor(System.String, AngouriMath.Entity, System.String) +AngouriMath.Core.GeneratedSource.op_Equality(AngouriMath.Core.GeneratedSource, AngouriMath.Core.GeneratedSource) : System.Boolean +AngouriMath.Core.GeneratedSource.op_Inequality(AngouriMath.Core.GeneratedSource, AngouriMath.Core.GeneratedSource) : System.Boolean AngouriMath.Core.IBinaryNode.NodeFirstChild { } : AngouriMath.Entity AngouriMath.Core.IBinaryNode.NodeSecondChild { } : AngouriMath.Entity AngouriMath.Core.IHasAbsoluteValue.Abs(TSelf) : TOut @@ -3672,6 +3685,8 @@ AngouriMath.MathS+Settings.PrecisionErrorCommon { } : AngouriMath.Convenience.Se AngouriMath.MathS+Settings.PrecisionErrorZeroRange { } : AngouriMath.Convenience.Setting AngouriMath.MathS+Settings.RefuseNonRealCompilation { } : AngouriMath.Convenience.Setting AngouriMath.MathS+Settings.UnicodeOutput { } : AngouriMath.Convenience.Setting +AngouriMath.MathS+Shaders.Glsl(System.Collections.Generic.IReadOnlyList>, System.Collections.Generic.IReadOnlyDictionary) : AngouriMath.Core.GeneratedSource +AngouriMath.MathS+Shaders.Hlsl(System.Collections.Generic.IReadOnlyList>, System.Collections.Generic.IReadOnlyDictionary) : AngouriMath.Core.GeneratedSource AngouriMath.MathS+UnsafeAndInternal.AreEqualNumerically(AngouriMath.Entity, AngouriMath.Entity) : System.Boolean AngouriMath.MathS+UnsafeAndInternal.AreEqualNumerically(AngouriMath.Entity, AngouriMath.Entity, AngouriMath.Entity[]) : System.Boolean AngouriMath.MathS+UnsafeAndInternal.CheckPoints { } : AngouriMath.Convenience.Setting @@ -3878,6 +3893,7 @@ class AngouriMath.Core.Exceptions.UnrecognizedFunctionParseException class AngouriMath.Core.Exceptions.WrongNumberOfArgumentsException class AngouriMath.Core.FastExpression class AngouriMath.Core.FiniteSetBuilder +class AngouriMath.Core.GeneratedSource class AngouriMath.Core.MatrixBuilder class AngouriMath.Core.ReasonOfFailureWhileParsing class AngouriMath.Core.ReasonOfFailureWhileParsing+InternalError @@ -4047,6 +4063,7 @@ class AngouriMath.MathS+Series class AngouriMath.MathS+Sets class AngouriMath.MathS+Settings class AngouriMath.MathS+Settings+NewtonSetting +class AngouriMath.MathS+Shaders class AngouriMath.MathS+UnsafeAndInternal class AngouriMath.MathS+Utils class AngouriMath.ProofRecording diff --git a/Sources/Tests/UnitTests/Convenience/ShadersTest.cs b/Sources/Tests/UnitTests/Convenience/ShadersTest.cs new file mode 100644 index 000000000..27d4097fb --- /dev/null +++ b/Sources/Tests/UnitTests/Convenience/ShadersTest.cs @@ -0,0 +1,158 @@ +// +// Copyright (c) 2019-2026 Angouri. +// AngouriMath is licensed under MIT. +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. +// Website: https://am.angouri.org. +// + +using System; +using System.Collections.Generic; +using System.Linq; +using AngouriMath.Core; +using AngouriMath.Extensions; +using AngouriMath.Functions.Compilation.IntoSource; +using Microsoft.CodeAnalysis.CSharp.Scripting; +using Microsoft.CodeAnalysis.Scripting; +using Xunit; +using static AngouriMath.Entity; + +namespace AngouriMath.Tests.Convenience +{ + /// + /// . The printed text itself is what is checked: the same + /// printer writes C# against helpers named as HLSL's intrinsics, that text is compiled, + /// and its values are compared with Compile<double, double, double> — so a + /// wrong operand order, a lost sign or a bad shared local shows up as a number. + /// + [Trait("Area", "Convenience")] + public sealed class ShadersTest + { + private const string Helpers = """ + static double sqrt(double x) => Math.Sqrt(x); + static double rsqrt(double x) => 1.0 / Math.Sqrt(x); + static double sin(double x) => Math.Sin(x); + static double cos(double x) => Math.Cos(x); + static double tan(double x) => Math.Tan(x); + static double asin(double x) => Math.Asin(x); + static double acos(double x) => Math.Acos(x); + static double atan(double x) => Math.Atan(x); + static double exp(double x) => Math.Exp(x); + static double log(double x) => Math.Log(x); + static double abs(double x) => Math.Abs(x); + static int sign(double x) => Math.Sign(x); + static double floor(double x) => Math.Floor(x); + static double ceil(double x) => Math.Ceiling(x); + static double max(double a, double b) => Math.Max(a, b); + static double min(double a, double b) => Math.Min(a, b); + static double pow(double a, double b) => Math.Pow(a, b); + static void sincos(double a, out double s, out double c) { s = Math.Sin(a); c = Math.Cos(a); } + """; + + private static Func Printed(Entity expr) + { + var source = ShaderSource.Emit(SourceDialect.CSharpCheck, + new[] { new KeyValuePair("r", expr) }, null); + Assert.True(source.Succeeded, source.ToString()); + var code = $"{Helpers}\nFunc F = (x, y) => {{ double r;\n{source.Code} return r; }};\nF"; + return CSharpScript.EvaluateAsync>(code, ScriptOptions.Default.WithImports("System")) + .GetAwaiter().GetResult(); + } + + [Theory] + [InlineData("x + y")] + [InlineData("x - y")] + [InlineData("y - x")] + [InlineData("x / y")] + [InlineData("-x * y")] + [InlineData("(x + y)^2 + sin(x + y)")] + [InlineData("sin(x) cos(x) + sin(x)")] + [InlineData("x^3")] + [InlineData("x^4")] + [InlineData("x^5")] + [InlineData("x^6")] + [InlineData("x^(-3)")] + [InlineData("x^(1/2)")] + [InlineData("x^(-1/2)")] + [InlineData("x^(3/2)")] + [InlineData("x^y")] + [InlineData("e^(x y)")] + [InlineData("ln(x)")] + [InlineData("log(2, x)")] + [InlineData("x mod y")] + [InlineData("abs(x) + sign(y)")] + [InlineData("floor(x) + ceil(y)")] + [InlineData("max(x, y) - min(x, y)")] + [InlineData("arcsin(x / 4) + arccos(y / 4) + arctan(x)")] + [InlineData("tan(x)")] + [InlineData("pi x + e")] + [InlineData("x / 3 + 0.25 y")] + [InlineData("derivative(sqrt(x^2 + y^2), x)")] + public void ThePrintedCodeComputesWhatCompileComputes(string input) + { + var expr = input.ToEntity(); + // Derivatives and the like are evaluated before printing, as a caller would. + if (expr is CalculusOperator) + expr = expr.Simplify(); + var printed = Printed(expr); + var compiled = expr.Compile("x", "y"); + var rng = new Random(7); + var compared = 0; + for (var k = 0; k < 200; k++) + { + var (x, y) = (rng.NextDouble() * 6 - 3, rng.NextDouble() * 6 - 3); + var (got, want) = (printed(x, y), compiled(x, y)); + if (double.IsNaN(want)) + continue; + Assert.True(Math.Abs(got - want) <= 1e-9 * Math.Max(1, Math.Abs(want)), + $"{input} at ({x}, {y}): printed {got}, compiled {want}"); + compared++; + } + // A comparison that skipped every sample would pass having checked nothing. + Assert.True(compared >= 50, $"{input}: only {compared} samples had a real value"); + } + + [Fact] + public void ARepeatedSubexpressionIsComputedOnce() + { + var source = MathS.Shaders.Hlsl(new[] { new KeyValuePair("r", "sqrt(x^2 + y^2) + 1 / sqrt(x^2 + y^2)") }); + Assert.True(source.Succeeded, source.ToString()); + Assert.Equal(1, source.Code!.Split(new[] { "sqrt(" }, StringSplitOptions.None).Length - 1); + } + + [Fact] + public void HlslUsesOneSinCos() + { + var source = MathS.Shaders.Hlsl(new[] { new KeyValuePair("r", "sin(x) * cos(x) + sin(x)") }); + Assert.Contains("sincos(x, am0, am1);", source.Code); + Assert.DoesNotContain("sin(x)", source.Code); + } + + [Fact] + public void GlslHasItsOwnNames() + { + var source = MathS.Shaders.Glsl(new[] { new KeyValuePair("r", "x^(-1/2) + sin(x) cos(x)") }); + Assert.Contains("inversesqrt(x)", source.Code); + Assert.DoesNotContain("sincos", source.Code); + } + + [Fact] + public void VariablesAreRenamed() + { + var source = MathS.Shaders.Hlsl(new[] { new KeyValuePair("n.x", "x y") }, + new Dictionary { ["x"] = "p.x", ["y"] = "SS_DEPTH" }); + Assert.Equal("n.x = (p.x * SS_DEPTH);\n", source.Code); + } + + [Theory] + [InlineData("x + i", "i")] + [InlineData("x + theta", "theta")] + [InlineData("x!", "x!")] + public void WhatHasNoFaithfulFormIsDeclined(string input, string at) + { + var names = new Dictionary { ["theta"] = "θ" }; + var source = MathS.Shaders.Hlsl(new[] { new KeyValuePair("r", input) }, names); + Assert.False(source.Succeeded); + Assert.Equal(at, source.At!.ToString()); + } + } +} From e2bf6fd3c48b266c22a10999209ad879964c40ef Mon Sep 17 00:00:00 2001 From: Rafael Vuijk <133344302+Rafael-SOWNet@users.noreply.github.com> Date: Sun, 1 Nov 2026 01:26:09 +0100 Subject: [PATCH 2/4] Shader source in the catalogue: hlsl and glsl AGENTS.md: an operation the library offers by name is an entry of the catalogue. The two queries answer what MathS.Shaders.Hlsl and Glsl answer, which CatalogueTest checks on sin(x) * cos(x), where HLSL's sincos makes the two differ. No surface offers them yet: the MCP server's Tools.NotOffered and the terminal's OneShot.notOffered list them, pointing at #2298, which proposes am_shader_source. Part of #2293. Co-Authored-By: Claude Opus 5.5 --- .../AngouriMath/Core/Operations/Catalogue.cs | 17 ++++++++++++++++- Sources/MCP/AngouriMath.Mcp/Tools.cs | 2 ++ .../AngouriMath.Terminal.Lib/OneShot.fs | 2 +- .../UnitTests/Core/Operations/CatalogueTest.cs | 6 ++++++ 4 files changed, 25 insertions(+), 2 deletions(-) diff --git a/Sources/AngouriMath/Core/Operations/Catalogue.cs b/Sources/AngouriMath/Core/Operations/Catalogue.cs index c9ef59468..d3dc3f373 100644 --- a/Sources/AngouriMath/Core/Operations/Catalogue.cs +++ b/Sources/AngouriMath/Core/Operations/Catalogue.cs @@ -139,6 +139,21 @@ internal static class Catalogue "sympy", "Writes the expression as Python code for SymPy.", static e => MathS.ToSympyCode(e)); + [ConstantField] + private static readonly Parameter TheShaderNames = new("names", "What each variable is called in the shader, such as p.x, or none to keep its own name."); + + /// . + public static Query>, IReadOnlyDictionary?, GeneratedSource>> Hlsl { get; } = new( + "hlsl", "Writes expressions as straight-line HLSL, one assignment to each named output, or names the node it has no faithful form for.", + static (outputs, names) => MathS.Shaders.Hlsl(outputs, names), + TheShaderNames); + + /// . + public static Query>, IReadOnlyDictionary?, GeneratedSource>> Glsl { get; } = new( + "glsl", "Writes expressions as straight-line GLSL, one assignment to each named output, or names the node it has no faithful form for.", + static (outputs, names) => MathS.Shaders.Glsl(outputs, names), + TheShaderNames); + /// . public static Query, Matrix?>> TruthTable { get; } = new( "truth_table", "Tabulates a statement over every assignment of true and false to its variables.", @@ -260,7 +275,7 @@ internal static class Catalogue public static IReadOnlyList All { get; } = [ Simplify, Normalize, Expand, Factorize, Differentiate, Integrate, Limit, Substitute, - Solve, SolveSystem, SolveConjunction, Evaluate, EvaluateNumerically, Variables, Alternatives, Latex, Sympy, TruthTable, SatisfyingAssignments, Series, AreEqual, + Solve, SolveSystem, SolveConjunction, Evaluate, EvaluateNumerically, Variables, Alternatives, Latex, Sympy, Hlsl, Glsl, TruthTable, SatisfyingAssignments, Series, AreEqual, ToBase, FromBase, Determinant, Inverse, Transpose, Rank, ReducedRowEchelonForm, Trace, TensorProduct, PrimeFactorization, Totient, GreatestCommonDivisor, DivisorCount, IsPrime, diff --git a/Sources/MCP/AngouriMath.Mcp/Tools.cs b/Sources/MCP/AngouriMath.Mcp/Tools.cs index a37ba2aff..903ac1b95 100644 --- a/Sources/MCP/AngouriMath.Mcp/Tools.cs +++ b/Sources/MCP/AngouriMath.Mcp/Tools.cs @@ -124,6 +124,8 @@ private static JsonObject Schema(JsonObject props, params string[] required) /// The catalogue's entries that no tool offers, by name, each with the reason. public static readonly IReadOnlyDictionary NotOffered = new Dictionary { + [Catalogue.Hlsl.Name] = "waits for am_shader_source, https://github.com/asc-community/AngouriMath/issues/2298", + [Catalogue.Glsl.Name] = "waits for am_shader_source, https://github.com/asc-community/AngouriMath/issues/2298", [Catalogue.Normalize.Name] = "am_simplify offers the whole simplification, which starts with this pass", [Catalogue.Evaluate.Name] = "am_evaluate keeps an exact value exact, simplifying rather than evaluating, and adds a numeric value beside it", }; diff --git a/Sources/Terminal/AngouriMath.Terminal.Lib/OneShot.fs b/Sources/Terminal/AngouriMath.Terminal.Lib/OneShot.fs index 2d4b461b3..d2a0e276a 100644 --- a/Sources/Terminal/AngouriMath.Terminal.Lib/OneShot.fs +++ b/Sources/Terminal/AngouriMath.Terminal.Lib/OneShot.fs @@ -68,7 +68,7 @@ let ownCommands = /// let notOffered = set [ "expand"; "factorize"; "integrate"; "limit"; "solve_system"; "solve_conjunction"; "evaluate_numerically"; "variables" - "alternatives"; "sympy"; "truth_table"; "satisfying_assignments"; "series"; "to_base"; "from_base" + "alternatives"; "sympy"; "hlsl"; "glsl"; "truth_table"; "satisfying_assignments"; "series"; "to_base"; "from_base" "determinant"; "inverse"; "transpose"; "rank"; "reduced_row_echelon_form"; "trace"; "tensor_product" "prime_factorization"; "totient"; "greatest_common_divisor"; "divisor_count"; "is_prime"; "are_equal" ] diff --git a/Sources/Tests/UnitTests/Core/Operations/CatalogueTest.cs b/Sources/Tests/UnitTests/Core/Operations/CatalogueTest.cs index f82560fd7..338ec062a 100644 --- a/Sources/Tests/UnitTests/Core/Operations/CatalogueTest.cs +++ b/Sources/Tests/UnitTests/Core/Operations/CatalogueTest.cs @@ -220,6 +220,12 @@ public void EachEntryAnswersAsTheMethodItNames() Assert.Equal(trigonometric.Alternate(2), Catalogue.Alternatives.Ask(trigonometric, 2)); Assert.Equal(square.Latexize(), Catalogue.Latex.Ask(square)); Assert.Equal(MathS.ToSympyCode(square), Catalogue.Sympy.Ask(square)); + // HLSL has sincos and GLSL does not, so the two print a sine beside its cosine differently. + KeyValuePair[] outputs = [new("r", "sin(x) * cos(x)")]; + var names = new Dictionary { [x] = "p.x" }; + Assert.Equal(MathS.Shaders.Hlsl(outputs, names), Catalogue.Hlsl.Ask(outputs, names)); + Assert.Equal(MathS.Shaders.Glsl(outputs, names), Catalogue.Glsl.Ask(outputs, names)); + Assert.NotEqual(Catalogue.Hlsl.Ask(outputs, names), Catalogue.Glsl.Ask(outputs, names)); Assert.Equal(MathS.Boolean.BuildTruthTable("a and not b", "a", "b"), Catalogue.TruthTable.Ask("a and not b", [MathS.Var("a"), MathS.Var("b")])); Assert.Equal(MathS.SolveBooleanTable("a and not b", "a", "b"), Catalogue.SatisfyingAssignments.Ask("a and not b", [MathS.Var("a"), MathS.Var("b")])); Assert.NotEqual(Catalogue.TruthTable.Ask("a and not b", [MathS.Var("a"), MathS.Var("b")]), Catalogue.SatisfyingAssignments.Ask("a and not b", [MathS.Var("a"), MathS.Var("b")])); From 391db6391380bca1e7e33c722b9e017e4b6fd722 Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Mon, 16 Nov 2026 00:37:10 +0000 Subject: [PATCH 3/4] Shader source agrees with Compile on master's nodes, and has a page The printer now checks an expression before printing anything and returns the refusal, rather than throwing and catching inside the printer. What Compile refuses, a binder (now including a product over a set) or a statement where a number is expected, is declined with Compile's own message, through Binders.Refusal and StatementPositions.Refusal, which Check now throws from. It makes the rewrites Compile makes: a matrix operation on matrices written out is the number it gives, a membership in an interval or a finite set is its comparisons, and the exponential quotient tanh is spelled as is rescaled so it does not divide an overflow by an overflow. Printed, as Compile compiles them: a rational power with an odd denominator below ten as the real root of a negative base (x^(1/3) was pow(x, 1/3), NaN at a negative x where Compile has a value); cotan, sec, csc and their inverses; conjugate, re, im and arg of a real; iverson, xor and implies. Declined with a reason: gcd and lcm (a loop), matrices and the matrix operations of a variable, membership in a set of numbers. The XML docs and Docs/Usage/Shaders.md name where the shader and Compile differ: +-inf at a zero divisor and at zero to a negative power, 1.0 for an unsimplified x^0, and pow of a negative base. The page works the exact normal of a smooth union of two spheres through, in HLSL and GLSL; docsamples runs its six samples. Part of #2293 Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + BREAKING-CHANGES.md | 17 ++ README.md | 4 + .../AngouriMath/Convenience/MathS.Shaders.cs | 30 ++- .../Docs/Contributing/Packaging.md | 1 + Sources/AngouriMath/Docs/Usage/Shaders.md | 252 ++++++++++++++++++ .../Functions/Compilation/Binders.cs | 10 +- .../Compilation/IntoSource/ShaderSource.cs | 189 +++++++++---- .../Compilation/StatementPositions.cs | 10 +- .../UnitTests/Convenience/ShadersTest.cs | 76 ++++++ 10 files changed, 538 insertions(+), 52 deletions(-) create mode 100644 Sources/AngouriMath/Docs/Usage/Shaders.md diff --git a/AGENTS.md b/AGENTS.md index 1af2d72ae..da4b0faa9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -821,6 +821,7 @@ are short, and a stale one is worse than none — if you change what a file desc | [CONTRIBUTING.md](CONTRIBUTING.md) | for humans; how to get set up and what a PR should look like | | [`Docs/Usage/Syntax.md`](Sources/AngouriMath/Docs/Usage/Syntax.md) | what the parser accepts. The grammar was the only statement of it until [#706](https://github.com/asc-community/AngouriMath/pull/706) | | [`Docs/Usage/Exceptions.md`](Sources/AngouriMath/Docs/Usage/Exceptions.md) | the exception hierarchy under `AngouriMathBaseException` | +| [`Docs/Usage/Shaders.md`](Sources/AngouriMath/Docs/Usage/Shaders.md) | `MathS.Shaders.Hlsl` and `Glsl`: a worked example, and where the printed shader and `Compile` differ | | [`Docs/Usage/Comparison.md`](Sources/AngouriMath/Docs/Usage/Comparison.md) | how we measure against Math.NET Symbolics, Symbolism and SymPy, with the versions and what each comparison does not establish | | [`Docs/References.md`](Sources/AngouriMath/Docs/References.md) | the books, papers, corpora and reference works the code and its tests draw on, with the link and what each is used for. Add a work there when it is first cited | | [`Docs/Acknowledgements.md`](Sources/AngouriMath/Docs/Acknowledgements.md) and [`Docs/Articles.md`](Sources/AngouriMath/Docs/Articles.md) | the projects AngouriMath is built with, and the maintainers' articles about it, moved from the archived AngouriMathLab | diff --git a/BREAKING-CHANGES.md b/BREAKING-CHANGES.md index 4ea4e9076..2db9400c6 100644 --- a/BREAKING-CHANGES.md +++ b/BREAKING-CHANGES.md @@ -280,6 +280,23 @@ none of the roots takes nothing out; anything else, a symbol among them, leaves | `"sum(x, x in { w : w^2 - 2 = 0 } \\ { sqrt(2) })".ToEntity().Simplify()` | `sum(x, x in { w : w ^ 2 - 2 = 0 } \ { sqrt(2) })` | `-sqrt(2)` | | `"sum(x, x in { w : w^2 - 3w + 2 = 0 } \\ { 1 })".ToEntity().Simplify()` | `sum(x, x in { w : w ^ 2 - 3 * w + 2 = 0 } \ { 1 })` | `2` | +### Shader source: `MathS.Shaders.Hlsl` and `Glsl` + +**Not silent: a new entry point.** `MathS.Shaders.Hlsl` and `MathS.Shaders.Glsl` print expressions as straight-line +HLSL or GLSL, one assignment per named output with each repeated subexpression computed once, and return a +`GeneratedSource` that holds the code or names the node it declined. The code computes what `Compile` +computes, except at a zero divisor and at zero to a power that is not positive, where `Compile` answers `NaN` and the +shader ±inf (or `1.0` for an unsimplified `x^0`). The catalogue has them as `hlsl` and `glsl`. Nothing that existed +changes. See [`Docs/Usage/Shaders.md`](Sources/AngouriMath/Docs/Usage/Shaders.md) +([#2293](https://github.com/asc-community/AngouriMath/issues/2293)). + +| Input | Was (2.7.0) | Now | +|---|---|---| +| `MathS.Shaders.Hlsl([new("r", "x^(-1/2) + sin(x) cos(x)")]).Code` | no such member | `float am0, am1;`
`sincos(x, am0, am1);`
`r = (rsqrt(x) + (am0 * am1));` | +| `MathS.Shaders.Hlsl([new("r", "x!")]).ToString()` | no such member | ``Declined at x!: `x!` has no intrinsic in HLSL or GLSL and no straight-line form`` | + +--- + ### A system row that is not a solution declines the system **Silent: a wrong row is now no answer.** With `P + Q sqrt(2) = (1 + sqrt(2))^70`, the coefficient `P - Q y` is diff --git a/README.md b/README.md index 3792bf558..24027d72d 100644 --- a/README.md +++ b/README.md @@ -453,6 +453,10 @@ False False ``` +The same expressions can be printed as HLSL or GLSL for a shader, an exact gradient for a +signed distance field for instance: see +Docs/Usage/Shaders.md. +
Multithreading diff --git a/Sources/AngouriMath/Convenience/MathS.Shaders.cs b/Sources/AngouriMath/Convenience/MathS.Shaders.cs index e46ab4a85..10267f47c 100644 --- a/Sources/AngouriMath/Convenience/MathS.Shaders.cs +++ b/Sources/AngouriMath/Convenience/MathS.Shaders.cs @@ -26,14 +26,34 @@ partial class MathS /// /// /// The code computes the real-valued reading, the one Compile<double, …> - /// computes; where that has no value the shader's is NaN or unspecified, as the - /// language's own pow and sqrt leave it. A node with no faithful form — - /// a complex constant, a set, a piecewise with inputs it gives no value to — is declined - /// with the node named, never printed approximately. + /// computes; where that has no value the shader's is NaN, an infinity or + /// unspecified, as the language's own /, pow and sqrt leave it. + /// Three of those are worth naming, because a GPU does give them a value: a division by + /// zero, a / b at b = 0, is NaN compiled and ±infinity in the + /// shader; so is zero to a negative power, x^(-2) or x^(-1/2) at x = 0, + /// printed 1.0 / (x * x) and rsqrt(x); and an unsimplified x^0 is + /// printed 1.0, which is 1 at x = 0 where compiled it is NaN. A + /// branch on every quotient would cost more than the difference is worth, so the + /// difference is documented rather than paid for. Nor is pow of a negative base + /// defined in a shader, even where the exponent is a variable that happens to be whole. + /// + /// + /// A node with no faithful form — a complex constant, a set, a piecewise with inputs it + /// gives no value to, a function with no intrinsic and no straight-line form — is declined + /// with the node named, never printed approximately; and what Compile refuses, a + /// binder or a statement where a number is expected, is declined with Compile's + /// message. /// /// /// Nothing is simplified. Call first if a smaller - /// form is wanted: what is printed is the expression that was given. + /// form is wanted: what is printed is the expression that was given. The only rewrites + /// are the ones Compile makes as well: an operation on matrices written out is + /// the number it gives, a membership in an interval or a finite set is the comparisons + /// it stands for, and (b^v + c1) / (b^v + c2), as tanh is spelled, is taken + /// as 1 + (c1 - c2) / (b^v + c2) so that it does not overflow. + /// + /// + /// The page Docs/Usage/Shaders.md works an example through. /// /// public static class Shaders diff --git a/Sources/AngouriMath/Docs/Contributing/Packaging.md b/Sources/AngouriMath/Docs/Contributing/Packaging.md index 6effd0769..a1e81eb9c 100644 --- a/Sources/AngouriMath/Docs/Contributing/Packaging.md +++ b/Sources/AngouriMath/Docs/Contributing/Packaging.md @@ -273,6 +273,7 @@ subsystem's own directory. | Gröbner bases | one inbound edge, `Functions/Continuous/Solvers/EquationSolver.cs`, and **0 public members**. Reachable from `Solve` on a system, which is a measured popular use case — **kernel** | | Boolean minimisation | reached from `Simplificator` — **kernel** | | compilation into LINQ | `System.Linq.Expressions` is in the framework, so (D) does not fire; measured AOT-clean — **kernel** | +| shader source, `MathS.Shaders` | string output, no new dependency (`KernelDependenciesTest`), and off every default path. It reads the compilers' own internal refusals and rewrites, so that it declines and computes what `Compile` does, which is (C)'s test failing: it composes the kernel — **kernel** | | quantum, and the monoid algebra it is the only consumer of | 702 lines, 0.5% of the assembly. Reached **only from `Convenience/MathS.cs`** — the facade — and by nothing in the engine. Its whole public surface is `MathS.Quantum` and its five methods. No clause fires, so the rule leaves it in the kernel; §6 says why that is the right answer despite the boundary being arguably wrong | | `MathS.ExperimentalFeatures` | 191 lines, 12 public members, kernel. The one case where a boundary would buy something real — §6 | diff --git a/Sources/AngouriMath/Docs/Usage/Shaders.md b/Sources/AngouriMath/Docs/Usage/Shaders.md new file mode 100644 index 000000000..2a9697a25 --- /dev/null +++ b/Sources/AngouriMath/Docs/Usage/Shaders.md @@ -0,0 +1,252 @@ +# Shader source + +`MathS.Shaders.Hlsl` and `MathS.Shaders.Glsl` print expressions as straight-line HLSL or GLSL: +one assignment to each output you name, with every subexpression that occurs more than once +computed once into a local. The use is to derive on the CPU what is tedious or error-prone to +derive by hand — an exact gradient, a Hessian, the closed form of a physical law — and to run +the result on the GPU. + +Both take the outputs as a list of pairs, the target of each assignment and the expression it +gets, and return a `GeneratedSource`: its `Code` is the statements, or `null` where printing was +declined, in which case `At` is the subexpression that could not be printed and `Reason` says why. + +```cs +using System.Collections.Generic; + +Entity sphere = "sqrt(x^2 + y^2 + z^2) - 1"; +var names = new Dictionary { ["x"] = "p.x", ["y"] = "p.y", ["z"] = "p.z" }; +var normal = new List> +{ + new("n.x", sphere.Differentiate("x")), + new("n.y", sphere.Differentiate("y")), + new("n.z", sphere.Differentiate("z")), +}; +Console.Write(MathS.Shaders.Hlsl(normal, names).Code); +``` + +Output: + +``` +float am0 = (0.5 * rsqrt((((p.x * p.x) + (p.y * p.y)) + (p.z * p.z)))); +n.x = (am0 * (2.0 * p.x)); +n.y = (am0 * (2.0 * p.y)); +n.z = (am0 * (2.0 * p.z)); +``` + +## A worked example: the normal of a smooth union + +A signed distance field gives, at each point, the distance to a surface. Its gradient is the +surface normal, and a ray marcher usually estimates it by finite differences, four or six extra +evaluations of the field per pixel, with an error that is worst exactly at the creases a smooth +union produces. The exact gradient costs one evaluation's worth of shared subexpressions. + +Two unit spheres, one at the origin and one at `x = 3/2`, joined by the exponential smooth +minimum with radius `k = 1/4`: + +``` +d(p) = -k ln(e^(-a/k) + e^(-b/k)), a = |p| - 1, b = |p - (3/2, 0, 0)| - 1 +``` + +`Differentiate` gives the gradient, and `Simplify` makes it smaller before it is printed — +nothing is simplified by the printer itself: + +```cs +using System.Collections.Generic; + +Entity a = "sqrt(x^2 + y^2 + z^2) - 1"; +Entity b = "sqrt((x - 3/2)^2 + y^2 + z^2) - 1"; +Entity k = "1/4"; +var d = -k * MathS.Ln(MathS.Pow(MathS.e, -a / k) + MathS.Pow(MathS.e, -b / k)); + +var names = new Dictionary { ["x"] = "p.x", ["y"] = "p.y", ["z"] = "p.z" }; +var gradient = new List> +{ + new("n.x", d.Differentiate("x").Simplify()), + new("n.y", d.Differentiate("y").Simplify()), + new("n.z", d.Differentiate("z").Simplify()), +}; +Console.Write(MathS.Shaders.Hlsl(gradient, names).Code); +``` + +Output: + +``` +float am0 = (p.y * p.y); +float am1 = (p.z * p.z); +float am2 = (((p.x * p.x) + am0) + am1); +float am3 = exp((-4.0 * (sqrt(am2) - 1.0))); +float am4 = rsqrt(am2); +float am5 = (p.x - 1.5); +float am6 = (((am5 * am5) + am0) + am1); +float am7 = exp((-4.0 * (sqrt(am6) - 1.0))); +float am8 = rsqrt(am6); +float am9 = ((am7 * am8) + (am3 * am4)); +float am10 = (am7 + am3); +n.x = (-(0.25 * ((((-(4.0 * (p.x * am3))) * am4) + ((-(4.0 * (am7 * am5))) * am8)) / (am3 + am7)))); +n.y = ((p.y * am9) / am10); +n.z = ((p.z * am9) / am10); +``` + +GLSL is the same code with GLSL's names for the intrinsics that differ — `inversesqrt` for +`rsqrt`, and no `sincos`, which HLSL uses for a sine and a cosine of one argument: + + +```cs +Console.Write(MathS.Shaders.Glsl(gradient, names).Code); +``` + +Output: + +``` +float am0 = (p.y * p.y); +float am1 = (p.z * p.z); +float am2 = (((p.x * p.x) + am0) + am1); +float am3 = exp((-4.0 * (sqrt(am2) - 1.0))); +float am4 = inversesqrt(am2); +float am5 = (p.x - 1.5); +float am6 = (((am5 * am5) + am0) + am1); +float am7 = exp((-4.0 * (sqrt(am6) - 1.0))); +float am8 = inversesqrt(am6); +float am9 = ((am7 * am8) + (am3 * am4)); +float am10 = (am7 + am3); +n.x = (-(0.25 * ((((-(4.0 * (p.x * am3))) * am4) + ((-(4.0 * (am7 * am5))) * am8)) / (am3 + am7)))); +n.y = ((p.y * am9) / am10); +n.z = ((p.z * am9) / am10); +``` + +Pasted into a shader, with `p` the point and `n` a `float3` (or `vec3`): + +```hlsl +float3 SmoothUnionNormal(float3 p) +{ + float3 n; + // ... the statements printed above ... + return normalize(n); +} +``` + +The gradient of an exact distance field already has length 1; the smooth union is not exact, +so its gradient is normalised. + +### Why `Simplify` here, and a condition `Differentiate` attaches + +`Differentiate` keeps the condition under which its answer holds. The derivative of a logarithm +divides by its argument, so the unsimplified gradient comes back as +`... provided not e^(...) + e^(...) = 0`, and a shader has no way to say "no value here": + +```cs +Entity d = "-1/4 ln(e^(-4 x) + e^(-4 y))"; +var source = MathS.Shaders.Hlsl([new("g", d.Differentiate("x"))]); +Console.WriteLine(source.Succeeded); +Console.WriteLine(source.At is Providedf); +``` + +Output: + +``` +False +True +``` + +A sum of two exponentials is never zero, so here the condition cannot fail, and `Simplify` +drops it. Where it does not, and the condition is one you know holds, give the printer the +expression without it — `((Providedf)expr).Expression` — and only then. + +## Naming the variables + +A variable keeps its own name unless `names` maps it to another, so `x` can be read from +`p.x`, a swizzle, a member or a uniform. Every name has to be an identifier, or identifiers +joined by `.`; a name that is not one, such as `θ` for `theta`, is declined. The locals the printer declares are `am0`, `am1`, ..., and a variable mapped +to one of those names is declined as well. The output names are written as given. + +```cs +using System.Collections.Generic; + +var source = MathS.Shaders.Glsl( + [new("fragColor.r", "sin(t) / 2 + 1/2")], + new Dictionary { ["t"] = "u_time" }); +Console.Write(source.Code); +``` + +Output: + +``` +fragColor.r = ((sin(u_time) / 2.0) + 0.5); +``` + +## The contract + +**It computes what `Compile` computes**, the real-valued reading of the expression. +The tests hold the printer to that: the same printer writes C# against helpers named as HLSL's +intrinsics, the text is compiled, and its value is compared with `Compile` +at 200 points per case. + +**Where `Compile` has no value, the shader's is `NaN`, an infinity, or unspecified.** Three of +those cases are worth knowing, because a GPU does give them a value: + +| at | `Compile` | the shader | +|---|---|---| +| `a / b` with `b = 0` | `NaN` | `a / b`: ±inf under IEEE 754 | +| `x^(-2)`, `x^(-1/2)` at `x = 0` | `NaN` | `1.0 / (x * x)`, `rsqrt(x)`: +inf | +| an unsimplified `x^0` at `x = 0` | `NaN` | `1.0` | + +Guarding every quotient would cost a branch per division, so the difference is documented here +rather than paid for in every shader: + +```cs +using System.Collections.Generic; + +Entity f = "1 / x"; +Console.WriteLine(f.Compile("x")(0)); +Console.Write(MathS.Shaders.Hlsl([new("r", f)]).Code); +``` + +Output: + +``` +NaN +r = (1.0 / x); +``` + +**Powers.** A whole power is multiplied out up to the fourth, `x^3` as `(x * x * x)`; above that +it is `pow(abs(x), n)`, with the sign put back for an odd `n`, because `pow` of a negative base +is undefined in HLSL and GLSL while `x^5` is defined for every real `x`. A rational power with an +odd denominator below ten is the real root of a negative base, as `Compile` takes it: `x^(1/3)` is +printed `(float(sign(x)) * pow(abs(x), 0.3333333333333333))`, which is `-2` at `x = -8`. `x^(1/2)` +and `x^(-1/2)` are `sqrt` and `rsqrt` (`inversesqrt` in GLSL), and `e^x` is `exp(x)`. A power to +a variable exponent is `pow`, and so has no value at a negative base in a shader even where the +exponent happens to be whole. + +**`mod` is floored**, as the library's `mod` is: the remainder takes the sign of the divisor, +`x - y * floor(x / y)`. HLSL's `fmod` and C's `%` truncate. + +**Nothing is simplified.** What is printed is the expression you give, so `Simplify` it first if +you want a smaller one. The only rewrites are the ones `Compile` makes as well, and each keeps the +value: an operation on matrices written out is the number it gives; a membership in an interval +or a finite set is the comparisons it stands for; and `(b^v + c1) / (b^v + c2)`, which is how +`tanh` is spelled, is taken as `1 + (c1 - c2) / (b^v + c2)`, so that `tanh(x)` is 1 for a large +`x` rather than infinity over infinity — in single precision `e^(2x)` overflows from `x = 45` on. + +**What is declined**, with the node named, rather than printed approximately: + +- a number that is not real, such as `i`, and a constant other than `pi` and `e`; +- `provided`, since a shader cannot say there is no value, and a piecewise whose last case is + not `true`, for the same reason; +- `round`, which takes a tie to the even neighbour where HLSL's and GLSL's `round` leave ties to + the implementation; +- the functions with no intrinsic and no straight-line form: the factorial and the special + functions, and `gcd` and `lcm`, which need a loop; +- sets and memberships in a set of numbers, and matrices: each output is one number, so assign a + vector's entries one by one; +- whatever `Compile` refuses — a derivative, an integral, a limit, a sum or a product left + unevaluated, or a statement where a number is expected — with the message `Compile` gives. + +```cs +Console.WriteLine(MathS.Shaders.Hlsl([new("r", "x! + 1")])); +``` + +Output: + +``` +Declined at x!: `x!` has no intrinsic in HLSL or GLSL and no straight-line form +``` diff --git a/Sources/AngouriMath/Functions/Compilation/Binders.cs b/Sources/AngouriMath/Functions/Compilation/Binders.cs index ef90cd019..395b9675d 100644 --- a/Sources/AngouriMath/Functions/Compilation/Binders.cs +++ b/Sources/AngouriMath/Functions/Compilation/Binders.cs @@ -21,14 +21,22 @@ namespace AngouriMath.Core.Compilation internal static class Binders { internal static void Check(Entity expression) + { + if (Refusal(expression) is { } refusal) + throw new UncompilableNodeException(refusal.Message); + } + + /// The first binder in and why it is refused, or null where there is none. + internal static (Entity Node, string Message)? Refusal(Entity expression) { foreach (var node in expression.Nodes) if (Kind(node) is { } kind) - throw new UncompilableNodeException( + return (node, $"`{node.Stringize()}` is {kind}, which has no compiled form. " + (node is Lambda ? "Apply it to an argument, call .Evaled or Simplify() on that, and compile the result." : "Call .Evaled or Simplify() on the expression first, and compile the result.")); + return null; } private static string? Kind(Entity node) => node switch diff --git a/Sources/AngouriMath/Functions/Compilation/IntoSource/ShaderSource.cs b/Sources/AngouriMath/Functions/Compilation/IntoSource/ShaderSource.cs index e6d8af26b..3b88d423a 100644 --- a/Sources/AngouriMath/Functions/Compilation/IntoSource/ShaderSource.cs +++ b/Sources/AngouriMath/Functions/Compilation/IntoSource/ShaderSource.cs @@ -8,6 +8,8 @@ using System; using System.Globalization; using System.Text; +using AngouriMath.Core.Compilation; +using AngouriMath.Core.Exceptions; using PeterO.Numbers; using static AngouriMath.Entity; @@ -34,13 +36,20 @@ internal enum SourceDialect /// unspecified, as the shading language's own pow and sqrt leave it. A /// node with no faithful form in that reading — a complex constant, a set, a rounding /// rule whose tie-breaking the languages do not agree on — is declined, naming the node, - /// rather than printed as something close. + /// rather than printed as something close. What Compile refuses is declined with + /// the message Compile gives. + /// + /// + /// Every expression is checked before anything is printed, so that printing has nothing + /// left to decline: the check is , and prints + /// exactly the nodes it accepts. /// /// /// Integer powers are multiplied out up to the fourth, and above that taken as /// pow(abs(x), n) with the sign restored for an odd n: pow of a /// negative base is undefined in both HLSL and GLSL, while x^5 is defined for every - /// real x. + /// real x. A rational power with an odd denominator below ten is the real root + /// of a negative base, as Compile takes it, and is printed the same way. /// /// internal sealed class ShaderSource @@ -56,12 +65,6 @@ internal sealed class ShaderSource private ShaderSource(SourceDialect dialect, IReadOnlyDictionary names) => (this.dialect, this.names) = (dialect, names); - private sealed class Declined : Exception - { - internal Entity At { get; } - internal Declined(Entity at, string reason) : base(reason) => At = at; - } - // Checked by hand: a regular expression would add System.Text.RegularExpressions to what // the kernel references, which KernelDependenciesTest holds fixed. private static bool IsIdentifier(string s) @@ -70,21 +73,103 @@ private static bool IsIdentifier(string s) internal static GeneratedSource Emit(SourceDialect dialect, IReadOnlyList> outputs, IReadOnlyDictionary? names) { var emitter = new ShaderSource(dialect, names ?? new Dictionary()); - try + var prepared = new List>(outputs.Count); + foreach (var output in outputs) { - foreach (var output in outputs) - emitter.Count(output.Value); - var lines = new StringBuilder(); - foreach (var output in outputs) - lines.Append(output.Key).Append(" = ").Append(emitter.Value(output.Value)).Append(";\n"); - return new GeneratedSource(emitter.body.ToString() + lines, null, ""); - } - catch (Declined d) - { - return new GeneratedSource(null, d.At, d.Message); + var expression = Prepared(output.Value); + if (emitter.Refusal(expression) is { } refusal) + return new GeneratedSource(null, refusal.At, refusal.Reason); + prepared.Add(new(output.Key, expression)); } + foreach (var output in prepared) + emitter.Count(output.Value); + var lines = new StringBuilder(); + foreach (var output in prepared) + lines.Append(output.Key).Append(" = ").Append(emitter.Value(output.Value)).Append(";\n"); + return new GeneratedSource(emitter.body.ToString() + lines, null, ""); + } + + // The rewrites Compile makes before compiling, so that the shader computes what it + // computes. A membership in an interval, a finite set or a union of them is the comparisons + // it stands for. A matrix operation on matrices written out is reduced to the number it gives, + // as Compile reduces it, since a shader output is a number. A quotient of one exponential + // plus a constant by the same exponential plus another, which is how tanh is spelled, is + // taken as 1 + (c1 - c2) / (b^v + c2), which does not divide an overflow by an overflow: + // in single precision e^(2x) overflows from x = 45 on. + // https://github.com/asc-community/AngouriMath/issues/2254 + private static Entity Prepared(Entity expression) + { + if (expression.Nodes.Any(node => node is Matrix)) + expression = expression.Replace(node => node switch + { + DotProductf(Matrix, Matrix) or CrossProductf(Matrix, Matrix) or Transposef(Matrix) + or Determinantf(Matrix) or Tracef(Matrix) or MatrixEntryf(Matrix, _, _) => node.InnerSimplified, + _ => node, + }); + return ExponentialQuotients.Rewritten(CompiledMembership.Rewritten(expression)); + } + + private (Entity At, string Reason)? Refusal(Entity expression) + { + if (Binders.Refusal(expression) is { } binder) + return binder; + if (StatementPositions.Refusal(expression) is { } statement) + return statement; + foreach (var node in expression.Nodes) + if (Refusal(node, NodeRefusal(node)) is { } refusal) + return refusal; + return null; + + static (Entity, string)? Refusal(Entity node, string? reason) => reason is null ? null : (node, reason); } + // Why this one node cannot be printed, or null where Print prints it. Its children are + // asked separately. + private string? NodeRefusal(Entity node) => node switch + { + Constant c when c == MathS.pi || c == MathS.e => null, + Constant c => $"the constant {c} has no literal here", + Variable v => NameRefusal(v), + Integer or Rational => null, + Real { EDecimal: var d } => d.IsFinite ? null : $"{node} is not a finite real number", + Number => $"{node} is not a real number, and the shader computes the real-valued reading", + Entity.Boolean => null, + + Sumf or Minusf or Mulf or Divf or Powf or Modf => null, + Sinf or Cosf or Tanf or Cotanf or Secantf or Cosecantf => null, + Arcsinf or Arccosf or Arctanf or Arccotanf or Arcsecantf or Arccosecantf => null, + Logf or Absf or Signumf or Floorf or Ceilf or Maxf or Minf => null, + Conjugatef or Ref or Imf or Argf => null, + Greaterf or GreaterOrEqualf or Lessf or LessOrEqualf or Equalsf => null, + Andf or Orf or Xorf or Impliesf or Notf or Iversonf => null, + Piecewise pw => pw.Cases.LastOrDefault() is { Predicate: var last } && last == Entity.Boolean.True + ? null + : "a piecewise without a final case that is always true has inputs with no value, and a shader cannot say there is none", + + Providedf => "a shader cannot say there is no value: where the condition cannot fail, give the expression without it", + Roundf => "round takes a tie to the even neighbour, and HLSL's and GLSL's round leave ties to the implementation", + Matrix => $"`{node.Stringize()}` is a matrix, and each output of a shader here is a number: assign the entries one by one", + DotProductf or CrossProductf => $"`{node.Stringize()}` is taken of vectors, and every variable of the shader is a number", + Transposef or Determinantf or Tracef or MatrixEntryf => $"`{node.Stringize()}` is taken of a matrix, and every variable of the shader is a number", + Set => $"`{node.Stringize()}` is a set, which has no value in a shader", + Set.Inf => $"`{node.Stringize()}` is a membership in a set of numbers, which has no straight-line test in a shader", + Gcdf or Lcmf => $"`{node.Stringize()}` needs Euclid's algorithm, a loop, and the shader is straight-line code", + _ => $"`{node.Stringize()}` has no intrinsic in HLSL or GLSL and no straight-line form", + }; + + private string? NameRefusal(Variable v) + { + var name = NameOf(v); + // A swizzle or a member such as p.x is a legitimate target name. + if (!name.Split('.').All(IsIdentifier)) + return $"{name} is not an identifier; map it to one through the names"; + if (name.Length > 2 && name.StartsWith("am") && name.Skip(2).All(char.IsDigit)) + return $"{name} is the name of a local this code declares"; + return null; + } + + private string NameOf(Variable v) => names.TryGetValue(v, out var n) ? n : v.Name; + private string Real => dialect == SourceDialect.CSharpCheck ? "double" : "float"; private static bool IsLeaf(Entity e) => e is Variable or Number or Entity.Boolean; @@ -152,26 +237,14 @@ private bool TrySinCos(Entity e, out string result) { Constant c when c == MathS.pi => Literal(Math.PI), Constant c when c == MathS.e => Literal(Math.E), - Constant c => throw new Declined(c, $"the constant {c} has no literal here"), - Variable v => Name(v), + Variable v => NameOf(v), Integer i => Literal(EDecimal.FromEInteger(i.EInteger)), Rational r => Literal(r.ERational.ToEDecimal(EContext.Binary64)), - Real { EDecimal: var d } when d.IsFinite => Literal(d), + Real { EDecimal: var d } => Literal(d), Entity.Boolean b => (bool)b ? "true" : "false", - _ => throw new Declined(e, $"{e} is not a finite real number"), + _ => throw new AngouriBugException($"{e} passed the shader's check and has no literal"), }; - private string Name(Variable v) - { - var name = names.TryGetValue(v, out var n) ? n : v.Name; - // A swizzle or a member such as p.x is a legitimate target name. - if (!name.Split('.').All(IsIdentifier)) - throw new Declined(v, $"{name} is not an identifier; map it to one through the names"); - if (name.Length > 2 && name.StartsWith("am") && name.Skip(2).All(char.IsDigit)) - throw new Declined(v, $"{name} is the name of a local this code declares"); - return name; - } - private static string Literal(EDecimal d) => Literal(d.ToDouble()); // The shortest text that reads back as the same double, always with a point or an @@ -182,6 +255,8 @@ private static string Literal(double d) return s.Contains(".") || s.Contains("E") ? s.Replace("E", "e") : s + ".0"; } + private string One => Literal(1.0); + private string Print(Entity e) => e switch { Sumf(var a, var b) => $"({Value(a)} + {Value(b)})", @@ -189,7 +264,7 @@ private static string Literal(double d) Mulf(Integer { EInteger: var k }, var b) when k.Equals(EInteger.FromInt32(-1)) => $"(-{Value(b)})", Mulf(var a, var b) => $"({Value(a)} * {Value(b)})", Divf(var a, var b) => $"({Value(a)} / {Value(b)})", - Powf(var b, var p) => Power(e, b, p), + Powf(var b, var p) => Power(b, p), // Floored, as Modf is: the remainder takes the divisor's sign, which neither // HLSL's fmod nor C's % does. Modf(var a, var b) => Modulo(a, b), @@ -197,9 +272,17 @@ private static string Literal(double d) Sinf(var a) => $"sin({Value(a)})", Cosf(var a) => $"cos({Value(a)})", Tanf(var a) => $"tan({Value(a)})", + // As Compile takes them: the reciprocal, and the inverse of the reciprocal, which + // gives arccotan its range (-pi/2, pi/2] with pi/2 at 0, where 1 / 0 is +inf. + Cotanf(var a) => $"({One} / tan({Value(a)}))", + Secantf(var a) => $"({One} / cos({Value(a)}))", + Cosecantf(var a) => $"({One} / sin({Value(a)}))", Arcsinf(var a) => $"asin({Value(a)})", Arccosf(var a) => $"acos({Value(a)})", Arctanf(var a) => $"atan({Value(a)})", + Arccotanf(var a) => $"atan({One} / {Value(a)})", + Arcsecantf(var a) => $"acos({One} / {Value(a)})", + Arccosecantf(var a) => $"asin({One} / {Value(a)})", Logf(Constant c, var a) when c == MathS.e => $"log({Value(a)})", Logf(var b, var a) => $"(log({Value(a)}) / log({Value(b)}))", Absf(var a) => $"abs({Value(a)})", @@ -210,6 +293,14 @@ private static string Literal(double d) Maxf(var a, var b) => $"max({Value(a)}, {Value(b)})", Minf(var a, var b) => $"min({Value(a)}, {Value(b)})", + // Of a real number, as Compile over double has them: the conjugate and the real part + // are the number, the imaginary part is 0, and the argument is pi to the left of 0 + // and 0 to the right. + Conjugatef(var a) => Value(a), + Ref(var a) => Value(a), + Imf => Literal(0.0), + Argf(var a) => $"(({Value(a)} < {Literal(0.0)}) ? {Literal(Math.PI)} : {Literal(0.0)})", + Piecewise pw => Cases(pw), Greaterf(var a, var b) => $"({Value(a)} > {Value(b)})", GreaterOrEqualf(var a, var b) => $"({Value(a)} >= {Value(b)})", @@ -218,15 +309,26 @@ private static string Literal(double d) Equalsf(var a, var b) => $"({Value(a)} == {Value(b)})", Andf(var a, var b) => $"({Value(a)} && {Value(b)})", Orf(var a, var b) => $"({Value(a)} || {Value(b)})", + Xorf(var a, var b) => $"({Value(a)} != {Value(b)})", + Impliesf(var a, var b) => $"((!{Value(a)}) || {Value(b)})", Notf(var a) => $"(!{Value(a)})", + Iversonf(var a) => $"({Value(a)} ? {One} : {Literal(0.0)})", - _ => throw new Declined(e, $"{e.GetType().Name} has no faithful form in the real-valued reading"), + _ => throw new AngouriBugException($"{e.GetType().Name} passed the shader's check and has no printed form"), }; - private string Power(Entity at, Entity b, Entity p) + private string Power(Entity b, Entity p) { if (b is Constant c && c == MathS.e) return $"exp({Value(p)})"; + // An odd denominator below ten: the real root of a negative base, with the sign of + // the base where the numerator is odd, as Compile and evaluation take it. + if (RealProducts.RealRootExponent(p) is { } ratio) + { + var x = Once(b); + var magnitude = $"pow(abs({x}), {Value(p)})"; + return ratio.Numerator.IsEven ? magnitude : $"({ToReal($"sign({x})")} * {magnitude})"; + } if (p is not Rational q) return $"pow({Value(b)}, {Value(p)})"; if (q is Integer { EInteger: var k } && k.CanFitInInt32()) @@ -234,9 +336,9 @@ private string Power(Entity at, Entity b, Entity p) var n = k.ToInt32Checked(); switch (n) { - case 0: return Literal(1.0); + case 0: return One; case 1: return Value(b); - case -1: return $"({Literal(1.0)} / {Value(b)})"; + case -1: return $"({One} / {Value(b)})"; } var x = Once(b); var magnitude = Math.Abs(n) switch @@ -247,7 +349,7 @@ private string Power(Entity at, Entity b, Entity p) var m when m % 2 == 0 => $"pow(abs({x}), {Literal((double)m)})", var m => $"({ToReal($"sign({x})")} * pow(abs({x}), {Literal((double)m)}))", }; - return n > 0 ? magnitude : $"({Literal(1.0)} / {magnitude})"; + return n > 0 ? magnitude : $"({One} / {magnitude})"; } if (q.ERational.CompareTo(ERational.Create(1, 2)) == 0) return $"sqrt({Value(b)})"; @@ -265,14 +367,11 @@ private string Modulo(Entity a, Entity b) return $"({x} - {y} * floor({x} / {y}))"; } - // A conditional per case, the last one taken as the fallback only where its condition is - // literally true: a piecewise with no case for some input has no value there, and a - // shader cannot say so. + // A conditional per case, the last one taken as the fallback: the check accepted only a + // piecewise whose last condition is literally true. private string Cases(Piecewise pw) { var cases = pw.Cases.ToList(); - if (cases.Count == 0 || cases[cases.Count - 1].Predicate != Entity.Boolean.True) - throw new Declined(pw, "a piecewise without a final case that is always true has inputs with no value"); var text = Value(cases[cases.Count - 1].Expression); for (var k = cases.Count - 2; k >= 0; k--) text = $"({Value(cases[k].Predicate)} ? {Value(cases[k].Expression)} : {text})"; diff --git a/Sources/AngouriMath/Functions/Compilation/StatementPositions.cs b/Sources/AngouriMath/Functions/Compilation/StatementPositions.cs index ab19be458..7b1984157 100644 --- a/Sources/AngouriMath/Functions/Compilation/StatementPositions.cs +++ b/Sources/AngouriMath/Functions/Compilation/StatementPositions.cs @@ -23,6 +23,13 @@ namespace AngouriMath.Core.Compilation internal static class StatementPositions { internal static void Check(Entity expression) + { + if (Refusal(expression) is { } refusal) + throw new UncompilableNodeException(refusal.Message); + } + + /// The first statement in where a number is expected and why it is refused, or null where there is none. + internal static (Entity Node, string Message)? Refusal(Entity expression) { foreach (var node in expression.Nodes) { @@ -30,10 +37,11 @@ internal static void Check(Entity expression) continue; foreach (var child in node.DirectChildren) if (IsStatementValued(child)) - throw new UncompilableNodeException( + return (child, $"`{child.Stringize()}` is a statement where `{node.Stringize()}` expects a number, and has no value there. " + $"Its truth value as a number is iverson({child.Stringize()})."); } + return null; } private static bool TakesStatements(Entity node) diff --git a/Sources/Tests/UnitTests/Convenience/ShadersTest.cs b/Sources/Tests/UnitTests/Convenience/ShadersTest.cs index 27d4097fb..abdebdd31 100644 --- a/Sources/Tests/UnitTests/Convenience/ShadersTest.cs +++ b/Sources/Tests/UnitTests/Convenience/ShadersTest.cs @@ -87,6 +87,15 @@ private static Func Printed(Entity expr) [InlineData("pi x + e")] [InlineData("x / 3 + 0.25 y")] [InlineData("derivative(sqrt(x^2 + y^2), x)")] + [InlineData("x^(1/3) + y^(2/3)")] + [InlineData("x^(-1/3) - y^(5/3)")] + [InlineData("x^(1/(1 + 2))")] + [InlineData("cotan(x) + sec(y) + cosec(x y)")] + [InlineData("arccotan(x) + arcsec(y + 4) + arccosec(x - 4)")] + [InlineData("conjugate(x) + re(y) + im(x y) + arg(x)")] + [InlineData("iverson(x > y) + iverson((x > 0) xor (y > 0)) + iverson((x > 0) implies (y > 1))")] + [InlineData("iverson(x in [-1; 1] or x in {2, 3})")] + [InlineData("tanh(x y)")] public void ThePrintedCodeComputesWhatCompileComputes(string input) { var expr = input.ToEntity(); @@ -111,6 +120,42 @@ public void ThePrintedCodeComputesWhatCompileComputes(string input) Assert.True(compared >= 50, $"{input}: only {compared} samples had a real value"); } + [Fact] + public void TanhDoesNotDivideAnOverflowByAnOverflow() + { + // e^(2x) overflows past x = 355 in double, as it does past x = 45 in a shader's float. + Entity tanh = "tanh(x)"; + var printed = Printed(tanh); + Assert.Equal(1.0, printed(400, 0)); + Assert.Equal(-1.0, printed(-400, 0)); + Assert.Equal(tanh.Compile("x", "y")(400, 0), printed(400, 0)); + } + + // The parser reduces an operation on matrices written out, so these are built as nodes, the + // way Differentiate or a substitution leaves them. + public static TheoryData MatrixOperations => new() + { + new DotProductf(MathS.Vector("x", "y"), MathS.Vector("y", "x")), + new Determinantf(MathS.Matrix(new Entity[,] { { "x", "y" }, { "1", "x" } })), + new Tracef(MathS.Matrix(new Entity[,] { { "x", "y" }, { "1", "x" } })), + (Entity)"sin(x)" + new DotProductf(new CrossProductf(MathS.Vector("x", "y", "1"), MathS.Vector("1", "y", "x")), MathS.Vector("1", "1", "1")), + }; + + [Theory] + [MemberData(nameof(MatrixOperations))] + public void AMatrixOperationOnMatricesWrittenOutIsTheNumberItGives(Entity expr) + { + var printed = Printed(expr); + var compiled = expr.Compile("x", "y"); + var rng = new Random(7); + for (var k = 0; k < 200; k++) + { + var (x, y) = (rng.NextDouble() * 6 - 3, rng.NextDouble() * 6 - 3); + var (got, want) = (printed(x, y), compiled(x, y)); + Assert.True(Math.Abs(got - want) <= 1e-9 * Math.Max(1, Math.Abs(want)), $"{expr} at ({x}, {y}): printed {got}, compiled {want}"); + } + } + [Fact] public void ARepeatedSubexpressionIsComputedOnce() { @@ -147,6 +192,18 @@ public void VariablesAreRenamed() [InlineData("x + i", "i")] [InlineData("x + theta", "theta")] [InlineData("x!", "x!")] + [InlineData("gcd(x, y) + 1", "gcd(x, y)")] + [InlineData("lcm(x, y) + 1", "lcm(x, y)")] + [InlineData("round(x)", "round(x)")] + [InlineData("x provided x > 0", "x provided x > 0")] + [InlineData("piecewise(x provided x > 0, -x provided x < 0)", "piecewise(x provided (x > 0), (-x) provided (x < 0))")] + [InlineData("x + dot(x, y)", "dot(x, y)")] + [InlineData("x + cross(x, y)", "cross(x, y)")] + [InlineData("det(x)", "det(x)")] + [InlineData("transpose(x)", "transpose(x)")] + [InlineData("[x, y]", "[x, y]")] + [InlineData("iverson(x in RR)", "x in RR")] + [InlineData("x + {1, 2}", "{ 1, 2 }")] public void WhatHasNoFaithfulFormIsDeclined(string input, string at) { var names = new Dictionary { ["theta"] = "θ" }; @@ -154,5 +211,24 @@ public void WhatHasNoFaithfulFormIsDeclined(string input, string at) Assert.False(source.Succeeded); Assert.Equal(at, source.At!.ToString()); } + + // What Compile refuses is declined with the message Compile gives. + [Theory] + [InlineData("product(x, x in {1, 2}) + y", "product(x, x in { 1, 2 })")] + [InlineData("sum(x, x in {1, 2}) + y", "sum(x, x in { 1, 2 })")] + [InlineData("x + integral(y, y)", "integral(y, y)")] + [InlineData("x + limit(y, y, 0)", "limit(y, y, 0)")] + [InlineData("sin(x > 0)", "x > 0")] + public void WhatCompileRefusesIsDeclinedWithItsMessage(string input, string at) + { + Entity expr = input; + var refusal = Assert.ThrowsAny(() => expr.Compile("x", "y")); + foreach (var source in new[] { MathS.Shaders.Hlsl([new("r", expr)]), MathS.Shaders.Glsl([new("r", expr)]) }) + { + Assert.False(source.Succeeded); + Assert.Equal(at, source.At!.ToString()); + Assert.Equal(refusal.Message, source.Reason); + } + } } } From 03ba4643f5ea2a417dd978fb0599a058ec37b950 Mon Sep 17 00:00:00 2001 From: Rafael Vuijk Date: Mon, 16 Nov 2026 00:57:18 +0000 Subject: [PATCH 4/4] Shader source is the same text whatever MathS.Settings.UnicodeOutput says The printer writes numbers with double's round-trip format and names as the caller maps them; Stringize appears only in the reason a node is declined. This pins that: four expressions printed as HLSL and GLSL with the flag off and on give the same code. Co-Authored-By: Claude Opus 5.5 --- .../Tests/UnitTests/Convenience/ShadersTest.cs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/Sources/Tests/UnitTests/Convenience/ShadersTest.cs b/Sources/Tests/UnitTests/Convenience/ShadersTest.cs index abdebdd31..bbbaa048c 100644 --- a/Sources/Tests/UnitTests/Convenience/ShadersTest.cs +++ b/Sources/Tests/UnitTests/Convenience/ShadersTest.cs @@ -156,6 +156,24 @@ public void AMatrixOperationOnMatricesWrittenOutIsTheNumberItGives(Entity expr) } } + // MathS.Settings.UnicodeOutput (#2469) respells printed expressions with glyphs; shader + // source is code, and must be the same text whatever the display setting says. + [Theory] + [InlineData("sqrt(x^2 + y^2) - 1")] + [InlineData("x^2 * y^(-3) - pi * e^(-x)")] + [InlineData("iverson(x <= y) * (x - y)^2")] + [InlineData("x mod 3 - y^(1/3)")] + public void UnicodeOutputDoesNotReachShaderSource(string input) + { + var outputs = new[] { new KeyValuePair("r", input) }; + var hlsl = MathS.Shaders.Hlsl(outputs); + var glsl = MathS.Shaders.Glsl(outputs); + Assert.True(hlsl.Succeeded && glsl.Succeeded, hlsl.ToString() + glsl.ToString()); + using var _ = MathS.Settings.UnicodeOutput.Set(true); + Assert.Equal(hlsl.Code, MathS.Shaders.Hlsl(outputs).Code); + Assert.Equal(glsl.Code, MathS.Shaders.Glsl(outputs).Code); + } + [Fact] public void ARepeatedSubexpressionIsComputedOnce() {