diff --git a/.yamato/_triggers.yml b/.yamato/_triggers.yml index 6b9b3a3077..cf6a914bb9 100644 --- a/.yamato/_triggers.yml +++ b/.yamato/_triggers.yml @@ -46,6 +46,17 @@ #----------------------------------------------------------------------------------- +# Temporary: the LargeWorldCoordinate RelativeTo platform probe. Comment "/ci lwc-probe" on the PR to run it. +# Each job below can also be started on its own. +lwc_relativeto_probe: + name: LWC RelativeTo platform probe + dependencies: + - .yamato/desktop-standalone-tests.yml#desktop_standalone_test_testproject_win_il2cpp_6000.7 + - .yamato/console-standalone-test.yml#console_standalone_test_testproject_ps4_6000.7 + - .yamato/console-standalone-test.yml#console_standalone_test_testproject_ps5_6000.7 + triggers: + expression: pull_request.comment eq "lwc-probe" + # After some experimenting with CI setups we discovered that even though sometimes we don't need CI to run (no reason to run package tests if only Documentation is changed) there are some checks that devs may not realize but changes in seemingly unrelated files will cause their failures # This trigger was created to ensure that ALL PRs run this minimal check even when we don't need to run full tests pr_minimal_required_checks: diff --git a/.yamato/console-standalone-test.yml b/.yamato/console-standalone-test.yml index 09d6a68c09..d0c4bdc0fb 100644 --- a/.yamato/console-standalone-test.yml +++ b/.yamato/console-standalone-test.yml @@ -50,7 +50,7 @@ console_standalone_build_{{ project.name }}_{{ platform.name }}_{{ editor }}: {% endif %} commands: - unity-downloader-cli --fast --wait -u {{ editor }} -c Editor -c il2cpp -c {{ platform.name }} --arch {{ platform.architecture }} - - UnifiedTestRunner --testproject={{ project.path }} --architecture={% if platform.name == "switch" %}arm64{% else %}x64{% endif %} --scripting-backend=il2cpp --suite=playmode --platform={{ platform.standalone }} --editor-location=.Editor --artifacts-path=artifacts --player-save-path=build/players --testfilter="Unity.Netcode.RuntimeTests.*" --extra-editor-arg=-batchmode --extra-editor-arg=-nographics{% if platform.name == "switch" %} --extra-editor-arg=-overrideTextureCompression --extra-editor-arg=ForceUncompressed{% endif %} --rerun-strategy=Test --retry={{ num_test_retries }} --clean-library-on-rerun --build-only --timeout={{ test_timeout}} + - UnifiedTestRunner --testproject={{ project.path }} --architecture={% if platform.name == "switch" %}arm64{% else %}x64{% endif %} --scripting-backend=il2cpp --suite=playmode --platform={{ platform.standalone }} --editor-location=.Editor --artifacts-path=artifacts --player-save-path=build/players --testfilter="Unity.Netcode.RuntimeTests.LwcProbe" --extra-editor-arg=-batchmode --extra-editor-arg=-nographics{% if platform.name == "switch" %} --extra-editor-arg=-overrideTextureCompression --extra-editor-arg=ForceUncompressed{% endif %} --rerun-strategy=Test --retry={{ num_test_retries }} --clean-library-on-rerun --build-only --timeout={{ test_timeout}} variables: # PS4 related SCE_ORBIS_SDK_DIR: 'C:\Users\bokken\SCE\ps4_sdk_12_00' diff --git a/.yamato/desktop-standalone-tests.yml b/.yamato/desktop-standalone-tests.yml index bc53a5cb47..4ab74a6803 100644 --- a/.yamato/desktop-standalone-tests.yml +++ b/.yamato/desktop-standalone-tests.yml @@ -49,7 +49,7 @@ desktop_standalone_build_{{ project.name }}_{{ platform.name }}_{{ backend }}_{{ {% endif %} commands: - unity-downloader-cli --fast --wait -u {{ editor }} -c Editor {% if backend == "il2cpp" %} -c il2cpp {% endif %}{% if backend == "coreclr" %}{% unless coreclr_runtime_editors contains editor %} -c {{ platform.coreclr_component }} {% endunless %}{% endif %} --arch {{ platform.architecture }} - - UnifiedTestRunner --suite=playmode --platform={{ platform.standalone }} --editor-location=.Editor --testproject={{ project.path }} --scripting-backend={{ backend }} --testfilter="Unity.Netcode.RuntimeTests.*;TestProject.RuntimeTests.*" --playergraphicsapi=Null --player-save-path=build/players --artifacts-path=artifacts --extra-editor-arg=-batchmode --extra-editor-arg=-nographics --rerun-strategy=Test --retry={{ num_test_retries }} --clean-library-on-rerun --build-only --timeout={{ test_timeout }} + - UnifiedTestRunner --suite=playmode --platform={{ platform.standalone }} --editor-location=.Editor --testproject={{ project.path }} --scripting-backend={{ backend }} --testfilter="Unity.Netcode.RuntimeTests.LwcProbe" --playergraphicsapi=Null --player-save-path=build/players --artifacts-path=artifacts --extra-editor-arg=-batchmode --extra-editor-arg=-nographics --rerun-strategy=Test --retry={{ num_test_retries }} --clean-library-on-rerun --build-only --timeout={{ test_timeout }} artifacts: players: paths: diff --git a/.yamato/mobile-standalone-test.yml b/.yamato/mobile-standalone-test.yml index db9e768182..bedb205a7b 100644 --- a/.yamato/mobile-standalone-test.yml +++ b/.yamato/mobile-standalone-test.yml @@ -55,7 +55,7 @@ mobile_standalone_build_{{ project.name }}_{{ platform.name }}_{{ editor }}: UNITY_HANDLEUIINTERRUPTIONS: 1 commands: - unity-downloader-cli --fast --wait -u {{ editor }} -c Editor -c il2cpp {% if platform.base == "mac" %} -c ios {% else %} -c android {% endif %} --arch {{ platform.architecture }} - - UnifiedTestRunner --suite=playmode --platform={{ platform.standalone }} --testproject={{ project.path }} --architecture={{ platform.target_architecture }} --scripting-backend=il2cpp --editor-location=.Editor --artifacts-path=artifacts --testfilter="Unity.Netcode.RuntimeTests.*" --player-save-path=build/players --extra-editor-arg=-batchmode --extra-editor-arg=-nographics --rerun-strategy=Test --retry={{ num_test_retries }} --clean-library-on-rerun --build-only --timeout={{ test_timeout }} + - UnifiedTestRunner --suite=playmode --platform={{ platform.standalone }} --testproject={{ project.path }} --architecture={{ platform.target_architecture }} --scripting-backend=il2cpp --editor-location=.Editor --artifacts-path=artifacts --testfilter="Unity.Netcode.RuntimeTests.LwcProbe" --player-save-path=build/players --extra-editor-arg=-batchmode --extra-editor-arg=-nographics --rerun-strategy=Test --retry={{ num_test_retries }} --clean-library-on-rerun --build-only --timeout={{ test_timeout }} artifacts: players: paths: diff --git a/testproject/Assets/LwcProbe.meta b/testproject/Assets/LwcProbe.meta new file mode 100644 index 0000000000..dd0f3d0943 --- /dev/null +++ b/testproject/Assets/LwcProbe.meta @@ -0,0 +1,8 @@ +fileFormatVersion: 2 +guid: 307d4db89a1e47663f3a42c92b882b4a +folderAsset: yes +DefaultImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/testproject/Assets/LwcProbe/LwcProbe.Tests.asmdef b/testproject/Assets/LwcProbe/LwcProbe.Tests.asmdef new file mode 100644 index 0000000000..37130a5a3c --- /dev/null +++ b/testproject/Assets/LwcProbe/LwcProbe.Tests.asmdef @@ -0,0 +1,22 @@ +{ + "name": "LwcProbe.Tests", + "rootNamespace": "Unity.Netcode.RuntimeTests.LwcProbe", + "references": [ + "UnityEngine.TestRunner", + "Unity.Burst", + "Unity.Mathematics" + ], + "includePlatforms": [], + "excludePlatforms": [], + "allowUnsafeCode": true, + "overrideReferences": true, + "precompiledReferences": [ + "nunit.framework.dll" + ], + "autoReferenced": false, + "defineConstraints": [ + "UNITY_INCLUDE_TESTS" + ], + "versionDefines": [], + "noEngineReferences": false +} diff --git a/testproject/Assets/LwcProbe/LwcProbe.Tests.asmdef.meta b/testproject/Assets/LwcProbe/LwcProbe.Tests.asmdef.meta new file mode 100644 index 0000000000..462a667e14 --- /dev/null +++ b/testproject/Assets/LwcProbe/LwcProbe.Tests.asmdef.meta @@ -0,0 +1,7 @@ +fileFormatVersion: 2 +guid: 06bb7106871f4effb3b10bca8d11d0a1 +AssemblyDefinitionImporter: + externalObjects: {} + userData: + assetBundleName: + assetBundleVariant: diff --git a/testproject/Assets/LwcProbe/LwcRelativeToProbeTests.cs b/testproject/Assets/LwcProbe/LwcRelativeToProbeTests.cs new file mode 100644 index 0000000000..379564f42c --- /dev/null +++ b/testproject/Assets/LwcProbe/LwcRelativeToProbeTests.cs @@ -0,0 +1,643 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using NUnit.Framework; +using Unity.Burst; +using Unity.Collections; +using Unity.Jobs; +using Unity.Mathematics; +using UnityEngine; +using BigInteger = System.Numerics.BigInteger; +using Debug = UnityEngine.Debug; + +namespace Unity.Netcode.RuntimeTests.LwcProbe +{ + // Temporary probe for unity/unity#138277 (LargeWorldCoordinate.RelativeTo), not for merging. It runs the candidate + // RelativeTo forms as Burst jobs under FloatMode.Strict and FloatMode.Fast on each CI platform, and reports how many + // results differ from the exactly rounded difference, a hash of the result bits to compare across platforms, and + // the cost per element. The forms copy the PR's arithmetic with int3 cells in place of the internal type. + internal static class RelativeToForms + { + public const float CellSize = 1024; + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float3 Double(int3 cellA, float3 offsetA, int3 cellB, float3 offsetB) + { + return (float3)((double3)(cellA - cellB) * CellSize + ((double3)offsetA - offsetB)); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float3 TwoSum(int3 cellA, float3 offsetA, int3 cellB, float3 offsetB) + { + var difference = offsetA - offsetB; + var back = difference - offsetA; + var error = (offsetA - (difference - back)) + (-offsetB - back); + return ((float3)(cellA - cellB) * CellSize + difference) + error; + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float3 HalfCell(int3 cellA, float3 offsetA, int3 cellB, float3 offsetB) + { + var halfCells = (float3)(cellA - cellB) * (CellSize * 0.5f); + return (halfCells + offsetA) - (offsetB - halfCells); + } + + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static float3 Naive(int3 cellA, float3 offsetA, int3 cellB, float3 offsetB) + { + return (float3)(cellA - cellB) * CellSize + (offsetA - offsetB); + } + } + + internal struct Pair + { + public int3 CellA; + public float3 OffsetA; + public int3 CellB; + public float3 OffsetB; + } + + internal static class ProbeJobUtility + { + // Burst drops this call, so the flag stays 0 only when the job ran Burst-compiled. + [BurstDiscard] + public static void MarkManaged(NativeArray managed) + { + managed[0] = 1; + } + } + + [BurstCompile(FloatMode = FloatMode.Strict, CompileSynchronously = true)] + internal struct DoubleStrictJob : IJob + { + [ReadOnly] public NativeArray Pairs; + public NativeArray Results; + public NativeArray Managed; + public int Repeat; + + public void Execute() + { + ProbeJobUtility.MarkManaged(Managed); + for (int r = 0; r < Repeat; r++) + { + for (int i = 0; i < Pairs.Length; i++) + { + var p = Pairs[i]; + Results[i] = RelativeToForms.Double(p.CellA, p.OffsetA, p.CellB, p.OffsetB); + } + } + } + } + + [BurstCompile(FloatMode = FloatMode.Fast, CompileSynchronously = true)] + internal struct DoubleFastJob : IJob + { + [ReadOnly] public NativeArray Pairs; + public NativeArray Results; + public NativeArray Managed; + public int Repeat; + + public void Execute() + { + ProbeJobUtility.MarkManaged(Managed); + for (int r = 0; r < Repeat; r++) + { + for (int i = 0; i < Pairs.Length; i++) + { + var p = Pairs[i]; + Results[i] = RelativeToForms.Double(p.CellA, p.OffsetA, p.CellB, p.OffsetB); + } + } + } + } + + [BurstCompile(FloatMode = FloatMode.Strict, CompileSynchronously = true)] + internal struct TwoSumStrictJob : IJob + { + [ReadOnly] public NativeArray Pairs; + public NativeArray Results; + public NativeArray Managed; + public int Repeat; + + public void Execute() + { + ProbeJobUtility.MarkManaged(Managed); + for (int r = 0; r < Repeat; r++) + { + for (int i = 0; i < Pairs.Length; i++) + { + var p = Pairs[i]; + Results[i] = RelativeToForms.TwoSum(p.CellA, p.OffsetA, p.CellB, p.OffsetB); + } + } + } + } + + [BurstCompile(FloatMode = FloatMode.Fast, CompileSynchronously = true)] + internal struct TwoSumFastJob : IJob + { + [ReadOnly] public NativeArray Pairs; + public NativeArray Results; + public NativeArray Managed; + public int Repeat; + + public void Execute() + { + ProbeJobUtility.MarkManaged(Managed); + for (int r = 0; r < Repeat; r++) + { + for (int i = 0; i < Pairs.Length; i++) + { + var p = Pairs[i]; + Results[i] = RelativeToForms.TwoSum(p.CellA, p.OffsetA, p.CellB, p.OffsetB); + } + } + } + } + + [BurstCompile(FloatMode = FloatMode.Strict, CompileSynchronously = true)] + internal struct HalfCellStrictJob : IJob + { + [ReadOnly] public NativeArray Pairs; + public NativeArray Results; + public NativeArray Managed; + public int Repeat; + + public void Execute() + { + ProbeJobUtility.MarkManaged(Managed); + for (int r = 0; r < Repeat; r++) + { + for (int i = 0; i < Pairs.Length; i++) + { + var p = Pairs[i]; + Results[i] = RelativeToForms.HalfCell(p.CellA, p.OffsetA, p.CellB, p.OffsetB); + } + } + } + } + + [BurstCompile(FloatMode = FloatMode.Fast, CompileSynchronously = true)] + internal struct HalfCellFastJob : IJob + { + [ReadOnly] public NativeArray Pairs; + public NativeArray Results; + public NativeArray Managed; + public int Repeat; + + public void Execute() + { + ProbeJobUtility.MarkManaged(Managed); + for (int r = 0; r < Repeat; r++) + { + for (int i = 0; i < Pairs.Length; i++) + { + var p = Pairs[i]; + Results[i] = RelativeToForms.HalfCell(p.CellA, p.OffsetA, p.CellB, p.OffsetB); + } + } + } + } + + [BurstCompile(FloatMode = FloatMode.Strict, CompileSynchronously = true)] + internal struct NaiveStrictJob : IJob + { + [ReadOnly] public NativeArray Pairs; + public NativeArray Results; + public NativeArray Managed; + public int Repeat; + + public void Execute() + { + ProbeJobUtility.MarkManaged(Managed); + for (int r = 0; r < Repeat; r++) + { + for (int i = 0; i < Pairs.Length; i++) + { + var p = Pairs[i]; + Results[i] = RelativeToForms.Naive(p.CellA, p.OffsetA, p.CellB, p.OffsetB); + } + } + } + } + + [BurstCompile(FloatMode = FloatMode.Fast, CompileSynchronously = true)] + internal struct NaiveFastJob : IJob + { + [ReadOnly] public NativeArray Pairs; + public NativeArray Results; + public NativeArray Managed; + public int Repeat; + + public void Execute() + { + ProbeJobUtility.MarkManaged(Managed); + for (int r = 0; r < Repeat; r++) + { + for (int i = 0; i < Pairs.Length; i++) + { + var p = Pairs[i]; + Results[i] = RelativeToForms.Naive(p.CellA, p.OffsetA, p.CellB, p.OffsetB); + } + } + } + } + + internal class LwcRelativeToProbeTests + { + private const int k_TimingPairs = 4096; + private const int k_TimingRepeat = 2000; + private const int k_TimingSamples = 5; + + private struct Expected + { + public float Value; + public bool NonZero; + public bool UnderHalfCell; + } + + private struct Summary + { + public int Inexact; + public int Collapsed; + public int UnderHalfCellInexact; + public long MaxUlp; + public ulong Hash; + } + + private delegate void RunJob(NativeArray pairs, NativeArray results, NativeArray managed, int repeat); + + private NativeArray m_Pairs; + private Expected[] m_Expected; + private int m_UnderHalfCell; + private NativeArray m_TinyPairs; + private Expected[] m_TinyExpected; + + [Test] + public void RelativeToFormsPerFloatMode() + { + m_Pairs = ToPairs(BuildScalarCases(), out m_Expected, out m_UnderHalfCell); + m_TinyPairs = ToPairs(BuildTinyScalarCases(), out m_TinyExpected, out _); + + var report = new StringBuilder(); + report.AppendLine($"LWCPROBE platform={Application.platform} processArch={RuntimeInformation.ProcessArchitecture} pointer={IntPtr.Size * 8}bit cpu=\"{SystemInfo.processorType}\" scalars={m_Expected.Length} underHalfCell={m_UnderHalfCell} tinyScalars={m_TinyExpected.Length}"); + var failures = new StringBuilder(); + try + { + Measure(report, failures, "Double", "Strict", true, (p, r, m, n) => new DoubleStrictJob { Pairs = p, Results = r, Managed = m, Repeat = n, }.Run()); + Measure(report, failures, "Double", "Fast", true, (p, r, m, n) => new DoubleFastJob { Pairs = p, Results = r, Managed = m, Repeat = n, }.Run()); + Measure(report, failures, "TwoSum", "Strict", false, (p, r, m, n) => new TwoSumStrictJob { Pairs = p, Results = r, Managed = m, Repeat = n, }.Run()); + Measure(report, failures, "TwoSum", "Fast", false, (p, r, m, n) => new TwoSumFastJob { Pairs = p, Results = r, Managed = m, Repeat = n, }.Run()); + Measure(report, failures, "HalfCell", "Strict", false, (p, r, m, n) => new HalfCellStrictJob { Pairs = p, Results = r, Managed = m, Repeat = n, }.Run()); + Measure(report, failures, "HalfCell", "Fast", false, (p, r, m, n) => new HalfCellFastJob { Pairs = p, Results = r, Managed = m, Repeat = n, }.Run()); + Measure(report, failures, "Naive", "Strict", false, (p, r, m, n) => new NaiveStrictJob { Pairs = p, Results = r, Managed = m, Repeat = n, }.Run()); + Measure(report, failures, "Naive", "Fast", false, (p, r, m, n) => new NaiveFastJob { Pairs = p, Results = r, Managed = m, Repeat = n, }.Run()); + } + finally + { + m_Pairs.Dispose(); + m_TinyPairs.Dispose(); + } + + Debug.Log(report.ToString()); + if (failures.Length > 0) + { + Assert.Fail(failures.ToString() + report); + } + Assert.Pass(report.ToString()); + } + + private void Measure(StringBuilder report, StringBuilder failures, string form, string mode, bool mustBeExact, RunJob run) + { + var results = new NativeArray(m_Pairs.Length, Allocator.Persistent); + var managed = new NativeArray(1, Allocator.Persistent); + var timingPairs = m_Pairs.GetSubArray(m_Pairs.Length - k_TimingPairs, k_TimingPairs); + var timingResults = new NativeArray(k_TimingPairs, Allocator.Persistent); + var tinyResults = new NativeArray(m_TinyPairs.Length, Allocator.Persistent); + try + { + run(m_Pairs, results, managed, 1); + var summary = Compare(results, m_Expected); + var burst = managed[0] == 0; + + run(m_TinyPairs, tinyResults, managed, 1); + var tiny = Compare(tinyResults, m_TinyExpected); + + run(timingPairs, timingResults, managed, 1); + var best = double.MaxValue; + for (int s = 0; s < k_TimingSamples; s++) + { + var stopwatch = Stopwatch.StartNew(); + run(timingPairs, timingResults, managed, k_TimingRepeat); + stopwatch.Stop(); + best = Math.Min(best, stopwatch.Elapsed.TotalMilliseconds * 1e6 / ((double)k_TimingPairs * k_TimingRepeat)); + } + + report.AppendLine($"LWCPROBE form={form} mode={mode} burst={burst} inexact={summary.Inexact} collapsed={summary.Collapsed} underHalfCellInexact={summary.UnderHalfCellInexact}/{m_UnderHalfCell} maxUlp={summary.MaxUlp} hash=0x{summary.Hash:x16} nsPerElement={best:F3}"); + report.AppendLine($"LWCPROBE tiny form={form} mode={mode} inexact={tiny.Inexact} collapsed={tiny.Collapsed} maxUlp={tiny.MaxUlp} hash=0x{tiny.Hash:x16}"); + if (!burst) + { + failures.AppendLine($"{form}/{mode} did not run Burst-compiled, so its results say nothing about Burst."); + } + if (mustBeExact && (summary.Collapsed != 0 || summary.UnderHalfCellInexact != 0)) + { + failures.AppendLine($"{form}/{mode}: {summary.Collapsed} collapsed, {summary.UnderHalfCellInexact} inexact under half a cell apart."); + } + } + finally + { + results.Dispose(); + managed.Dispose(); + timingResults.Dispose(); + tinyResults.Dispose(); + } + } + + private static NativeArray ToPairs(List scalars, out Expected[] expected, out int underHalfCell) + { + var pairCount = scalars.Count / 3; + var pairs = new NativeArray(pairCount, Allocator.Persistent); + expected = new Expected[pairCount * 3]; + underHalfCell = 0; + for (int i = 0; i < pairCount; i++) + { + var x = scalars[3 * i]; + var y = scalars[3 * i + 1]; + var z = scalars[3 * i + 2]; + pairs[i] = new Pair + { + CellA = new int3(x.CellA, y.CellA, z.CellA), + OffsetA = new float3(x.OffsetA, y.OffsetA, z.OffsetA), + CellB = new int3(x.CellB, y.CellB, z.CellB), + OffsetB = new float3(x.OffsetB, y.OffsetB, z.OffsetB), + }; + for (int axis = 0; axis < 3; axis++) + { + expected[3 * i + axis] = ExactDifference(scalars[3 * i + axis]); + if (expected[3 * i + axis].UnderHalfCell) + { + underHalfCell++; + } + } + } + return pairs; + } + + private static Summary Compare(NativeArray results, Expected[] expectedValues) + { + var summary = new Summary { Hash = 14695981039346656037UL, }; + for (int i = 0; i < results.Length; i++) + { + var result = results[i]; + for (int axis = 0; axis < 3; axis++) + { + var got = result[axis]; + var expected = expectedValues[3 * i + axis]; + var bits = (uint)BitConverter.SingleToInt32Bits(got); + for (int b = 0; b < 4; b++) + { + summary.Hash = (summary.Hash ^ ((bits >> (8 * b)) & 0xFF)) * 1099511628211UL; + } + var ulp = Math.Abs(Ordered(expected.Value) - Ordered(got)); + if (ulp != 0) + { + summary.Inexact++; + if (expected.UnderHalfCell) + { + summary.UnderHalfCellInexact++; + } + } + // A bit test, since a denormals-are-zero player would also count a subnormal result as zero. + if (expected.NonZero && (bits & 0x7FFFFFFF) == 0) + { + summary.Collapsed++; + } + summary.MaxUlp = Math.Max(summary.MaxUlp, ulp); + } + } + return summary; + } + + private struct ScalarCase + { + public int CellA; + public float OffsetA; + public int CellB; + public float OffsetB; + } + + // Inputs come from integer operations and exact float steps, so every platform runs the same cases. Offsets below + // 2^-100 are left out: PlayStation players flush subnormals to zero, and differences of the remaining offsets + // are never subnormal. BuildTinyScalarCases reports those inputs on their own lines. + private static List BuildScalarCases() + { + var cases = new List(); + var edges = new List(); + foreach (var edge in new[] { 512f, 256f, 0f, -256f }) + { + for (int k = 0; k <= 6; k++) + { + AddOffset(edges, Step(edge, -k)); + AddOffset(edges, Step(edge, k)); + } + } + for (int k = 0; k <= 6; k++) + { + AddOffset(edges, Step(-512f, k)); + } + AddOffset(edges, 1e-30f); + AddOffset(edges, -1e-30f); + + foreach (var cellA in new[] { -30, 0, 1000, short.MaxValue - 1 }) + { + for (int d = -1; d <= 1; d++) + { + foreach (var offsetA in edges) + { + foreach (var offsetB in edges) + { + cases.Add(new ScalarCase { CellA = cellA, OffsetA = offsetA, CellB = cellA - d, OffsetB = offsetB, }); + } + } + } + } + + uint state = 20261117; + var random = cases.Count; + for (int i = 0; i < random; i++) + { + var cellA = (int)(Next(ref state) % 65536) + short.MinValue; + var cellB = Next(ref state) % 4 == 0 + ? (int)(Next(ref state) % 65536) + short.MinValue + : math.clamp(cellA + (int)(Next(ref state) % 5) - 2, short.MinValue, short.MaxValue); + cases.Add(new ScalarCase { CellA = cellA, OffsetA = RandomOffset(ref state), CellB = cellB, OffsetB = RandomOffset(ref state), }); + } + + // Pad to a whole number of float3 lanes. + while (cases.Count % 3 != 0) + { + cases.Add(new ScalarCase()); + } + return cases; + } + + private static List BuildTinyScalarCases() + { + var minNormal = BitConverter.Int32BitsToSingle(0x00800000); + var offsets = new List { 0f, 1f, -256f, }; + foreach (var magnitude in new[] { float.Epsilon, Step(0f, 6), Step(minNormal, -1), minNormal, BitConverter.Int32BitsToSingle(17 << 23), }) + { + offsets.Add(magnitude); + offsets.Add(Negate(magnitude)); + } + + var cases = new List(); + foreach (var cellA in new[] { 0, 1000 }) + { + for (int d = -1; d <= 1; d++) + { + foreach (var offsetA in offsets) + { + foreach (var offsetB in offsets) + { + cases.Add(new ScalarCase { CellA = cellA, OffsetA = offsetA, CellB = cellA - d, OffsetB = offsetB, }); + } + } + } + } + while (cases.Count % 3 != 0) + { + cases.Add(new ScalarCase()); + } + return cases; + } + + // Bit tests and bit compares only: a denormals-are-zero player treats a subnormal as equal to zero. + private static bool IsTiny(float value) + { + int bits = BitConverter.SingleToInt32Bits(value) & 0x7FFFFFFF; + return bits != 0 && bits < (27 << 23); + } + + private static float Negate(float value) + { + return BitConverter.Int32BitsToSingle(BitConverter.SingleToInt32Bits(value) ^ int.MinValue); + } + + private static void AddOffset(List offsets, float offset) + { + if (offset >= 512f || offset < -512f || IsTiny(offset)) + { + return; + } + int bits = BitConverter.SingleToInt32Bits(offset); + foreach (var existing in offsets) + { + if (BitConverter.SingleToInt32Bits(existing) == bits) + { + return; + } + } + offsets.Add(offset); + } + + private static uint Next(ref uint state) + { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + return state; + } + + // Half the offsets are spread evenly on a 2^-15 m grid, half have random bits, which reaches tiny values. + private static float RandomOffset(ref uint state) + { + if ((Next(ref state) & 1) == 0) + { + // k * 2^-15 is exact in float for |k| <= 2^24. + var k = (int)(Next(ref state) % (1u << 25)) - (1 << 24); + return k * (1f / 32768f); + } + float magnitude; + do + { + magnitude = BitConverter.Int32BitsToSingle((int)(Next(ref state) % (uint)BitConverter.SingleToInt32Bits(512f))); + } + while (IsTiny(magnitude)); + return (Next(ref state) & 1) == 0 ? magnitude : -magnitude; + } + + private static float Step(float value, int ulps) + { + return FromOrdered(Ordered(value) + ulps); + } + + private static long Ordered(float value) + { + int bits = BitConverter.SingleToInt32Bits(value); + return bits < 0 ? (long)int.MinValue - bits : bits; + } + + private static float FromOrdered(long ordered) + { + return BitConverter.Int32BitsToSingle(ordered < 0 ? (int)(int.MinValue - ordered) : (int)ordered); + } + + // The value times 2^149, so every float is an integer. + private static BigInteger Scaled(float value) + { + int bits = BitConverter.SingleToInt32Bits(value); + int exponent = (bits >> 23) & 0xFF; + long mantissa = bits & 0x7FFFFF; + if (exponent != 0) + { + mantissa |= 0x800000; + } + else + { + exponent = 1; + } + var scaled = (BigInteger)mantissa << (exponent - 1); + return bits < 0 ? -scaled : scaled; + } + + private static Expected ExactDifference(ScalarCase c) + { + var exact = ((BigInteger)(c.CellA - c.CellB) * 1024 << 149) + Scaled(c.OffsetA) - Scaled(c.OffsetB); + if (BigInteger.Abs(exact) < (BigInteger.One << 23)) + { + // Below 2^-126 the result is a whole number of 2^-149 steps, so it is a subnormal float held exactly. + // Built from bits, since the double path below flushes it to zero on a denormals-are-zero player. + var magnitude = (int)BigInteger.Abs(exact); + return new Expected + { + Value = BitConverter.Int32BitsToSingle(exact.Sign < 0 ? magnitude | int.MinValue : magnitude), + NonZero = !exact.IsZero, + UnderHalfCell = true, + }; + } + var guess = (float)((double)exact * Math.Pow(2, -149)); + var best = guess; + var bestDistance = BigInteger.Abs(exact - Scaled(guess)); + for (int k = -2; k <= 2; k++) + { + var candidate = Step(guess, k); + var distance = BigInteger.Abs(exact - Scaled(candidate)); + if (distance < bestDistance || (distance == bestDistance && (BitConverter.SingleToInt32Bits(candidate) & 1) == 0)) + { + best = candidate; + bestDistance = distance; + } + } + return new Expected + { + Value = best, + NonZero = !exact.IsZero, + UnderHalfCell = BigInteger.Abs(exact) < ((BigInteger)512 << 149), + }; + } + } +} diff --git a/testproject/Assets/LwcProbe/LwcRelativeToProbeTests.cs.meta b/testproject/Assets/LwcProbe/LwcRelativeToProbeTests.cs.meta new file mode 100644 index 0000000000..9f5f1396ec --- /dev/null +++ b/testproject/Assets/LwcProbe/LwcRelativeToProbeTests.cs.meta @@ -0,0 +1,2 @@ +fileFormatVersion: 2 +guid: f156ccafd38536c164b4b84f1b398415