diff --git a/packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs b/packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs index 0235b322..74edd778 100644 --- a/packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs +++ b/packages/cultmath/tests/CultMath.Tests/NoiseBoundTests.cs @@ -7,9 +7,10 @@ namespace CultMath.Tests; /// /// The noise bounds (design.md, "Intervals"): iv_snoise_ball and iv_fbm_ball enclose their functions over /// a ball, a domain warp bounded by D is enclosed by enlarging the radius by D, SNOISE_LIPSCHITZ has -/// measured provenance, iv_frustum_ball encloses a screen tile's rays over a depth segment, and an -/// interval-culled march spends fewer snoise evaluations than a dense one for the same transmittance. -/// Lines starting IV-REPORT carry the numbers the cut report quotes. +/// measured provenance, iv_frustum_ball encloses a screen tile's rays over a depth segment, the bound +/// composed from an analytic envelope and the noise ball encloses the density, and a tile march over +/// fields with authored empty space is measured against a dense one for the same transmittance. Lines +/// starting IV-REPORT carry the numbers the cut report quotes. /// /// Hand mutations of iv_frustum_ball that TileBallEnclosesEveryRaySegment must kill: z0 for z1 in the /// lateral term (z0 * footprintPerDepth); |m_c| for |(m_c, 1)| in the depth term; the warp dropped. @@ -162,6 +163,49 @@ public sealed class NoiseBoundTests } } + /// + /// intervals-enclose for the composition the site and Aetheria use: over 2,000 seeded tile slices + /// (Aetheria's wells, inside the fog, the void at every grid point; N in {1, 4, 8, 16}; a camera drawn + /// per tile) the bound composed from the envelope over the slice's box, its fade, and the noise ball + /// enlarged by the warp encloses the density at 64 points of the slice, each sampled through the field's + /// own warp, with no tolerance. The void's footprint-truncated density (octave weights) is checked + /// against the same bound. + /// + [Fact] + public void EnvelopeBoundEnclosesDensity() + { + var random = new System.Random(0xE7B0); + int[] sizes = { 1, 4, 8, 16 }; + var fields = new List { FogField.Wells(FogField.AetheriaWarp), FogField.InsideFog(FogField.AetheriaWarp) }; + foreach (var rh in VoidField.HollowRadii) + foreach (var offset in VoidField.CameraOffsets) + foreach (var ramp in VoidField.Ramps) + fields.Add(new VoidField(rh, ramp, offset.Fraction, offset.Name)); + var counts = new Counts(); + for (var t = 0; t < 2000; t++) + { + var field = t % 2 == 0 ? fields[(t / 2) % 2] : fields[2 + random.Next(fields.Count - 2)]; + var tile = field.DrawTile(random, sizes[random.Next(sizes.Length)]); + var near = field.Grid[0]; + var far = field.Grid[^1]; + var z0 = Uniform(random, near, far * 0.9f); + var z1 = z0 + LogUniform(random, 1.0e-3f * far, far - z0); + var bound = field.Bound(tile, z0, z1, gated: false, counts); + for (var i = 0; i < 64; i++) + { + var m = tile.PixelSlope(random.Next(tile.N), random.Next(tile.N), random.NextSingle(), random.NextSingle()); + var z = i < 2 ? (i == 0 ? z0 : z1) : Uniform(random, z0, z1); + var density = field.Density(tile, m, z, lod: false, counts); + Assert.True(Inside(density, bound), $"{field.Name}: bound {bound} over [{z0:R}, {z1:R}] misses density {density:R} at slope {m}, depth {z:R}"); + if (field is VoidField) + { + var truncated = field.Density(tile, m, z, lod: true, counts); + Assert.True(Inside(truncated, bound), $"{field.Name}: bound {bound} misses the truncated density {truncated:R} at slope {m}, depth {z:R}"); + } + } + } + } + // ---- The Lipschitz constant ---- private static float GradientNorm(float3 p) @@ -337,147 +381,618 @@ public sealed class NoiseBoundTests } - // ---- The saving ---- + // ---- The saving: envelope-then-noise fields, marched over screen tiles ---- + + // Combined cost in snoise units: one envelope evaluation, pointwise or as an interval probe, costs this + // much. An estimate (a handful of pulses or one height-map fetch against ~150 flops of snoise); both + // counts are printed, so any other weight can be applied to them. + internal const double EnvelopeCost = 0.2; + + internal sealed class Counts + { + public long Snoise; + public long Envelope; + + public double Cost => Snoise + EnvelopeCost * Envelope; + } /// - /// The map's field shape (docs/cultmath-interval-ground-cut.md, "Density field"), in world units along - /// a ray through a slab z in [0, Depth]: coverage is two snoise of the domain-warped point, cross-faded - /// over two half-period phases; occupancy = max(0, coverage - Cutoff) * Extinction; one more snoise is - /// the detail term. The flow is a unit-bounded 2D field times FlowAmplitude, so a warp moves a point by - /// at most Warp = FlowAmplitude * Period / 2. Flow evaluations are not counted: the site reads flow from - /// a texture. Counted: three snoise per dense sample, one per interval probe. + /// One screen tile of one frame: a pinhole camera (origin and orthonormal basis; camera space looks + /// down +z and the ray of slope m is the points (m z, z)), the tile's central slope, its size N, the + /// focal length in pixels and the frame time. Every tile draws its own camera, so a probe result is + /// never carried to another frame. /// - internal sealed class SavingField + internal class Tile + { + public float3 Origin; + public float3 Right = new(1.0f, 0.0f, 0.0f); + public float3 Up = new(0.0f, 1.0f, 0.0f); + public float3 Forward = new(0.0f, 0.0f, 1.0f); + public float2 Slope; + public int N; + public float Focal; + public float Time; + + public float Half => N / (2.0f * Focal); + public float Footprint => N / (MathF.Sqrt(2.0f) * Focal); + public float2 SlopesX => new(Slope.x - Half, Slope.x + Half); + public float2 SlopesY => new(Slope.y - Half, Slope.y + Half); + + // Pixel (i, j) of the tile at sub-pixel offset (u, v) in [0, 1): its slope lies in SlopesX x SlopesY + // in float32, because (i + u) / f - N / (2f) is at most N / f - N / (2f) = N / (2f) exactly. + public float2 PixelSlope(int i, int j, float u, float v) => + Slope + new float2((i + u) / Focal - Half, (j + v) / Focal - Half); + + public float3 World(float3 c) => Origin + Right * c.x + Up * c.y + Forward * c.z; + + public float3 Camera(float3 w) + { + var d = w - Origin; + return new float3(dot(d, Right), dot(d, Up), dot(d, Forward)); + } + + public void Look(float3 forward) + { + Forward = normalize(forward); + Right = normalize(cross(new float3(0.0f, 1.0f, 0.0f), Forward)); + Up = cross(Forward, Right); + } + } + + /// + /// A field with an analytic envelope and the dense grid it is marched on. Density is the pointwise + /// field, envelope-gated (noise only where the envelope leaves the density undecided), counted. Bound + /// is the one composition of the envelope's interval over a tile slice's box and the noise ball over the + /// slice's iv_frustum_ball: an interval enclosing Density at every point of every ray of the tile in the + /// slice. A slice is provably empty iff Bound(...).y <= 0. gated is the march's form: it returns the + /// envelope's verdict without snoise when the envelope alone proves the slice empty, and attempts the + /// noise ball only when the best outcome any centre value could give would prove it; ungated, the ball + /// is always evaluated. + /// + internal abstract class Scenario + { + public required string Name { get; init; } + public float[] Grid { get; protected init; } = Array.Empty(); + public float Focal { get; init; } = 935.0f; // 1080 rows at a 60 degree vertical field of view + public float Extinction { get; init; } = 1.0f; + + public abstract Tile DrawTile(System.Random random, int n); + + public abstract float Density(Tile tile, float2 slope, float z, bool lod, Counts counts); + + public abstract float2 Bound(Tile tile, float z0, float z1, bool gated, Counts counts); + + // Cell boundaries near + (j / J)^2 (far - near): Aetheria's quadratic sample spacing + // (Assets/Shaders/Raymarching/CloudShader.shader:116). + protected static float[] Quadratic(float near, float far, int cells) => + Enumerable.Range(0, cells + 1).Select(j => near + (float)j / cells * ((float)j / cells) * (far - near)).ToArray(); + + protected static float[] Cells(float step, float end) => + Enumerable.Range(0, (int)MathF.Ceiling(end / step) + 1).Select(j => j * step).ToArray(); + } + + // iv_snoise_ball, with the snoise skipped where L r >= 2: there the bound is [-1, 1] whatever snoise(c) + // is (|snoise| < 1), so the result is the same and costs nothing. + private static float2 NoiseBall(float3 centre, float radius, Counts counts) + { + if (SNOISE_LIPSCHITZ * radius >= 2.0f) + return new float2(-1.0f, 1.0f); + counts.Snoise++; + return iv_snoise_ball(centre, radius); + } + + // The best interval any centre value could give a ball of this radius, toward low or high values; the + // gate on whether a probe can prove anything. snoise(c) > -1, so a real ball's hi is at least -1 + L r, + // and likewise its lo is at most 1 - L r. + private static float2 BestBall(float radius, bool low) + { + var e = SNOISE_LIPSCHITZ * radius; + if (e >= 2.0f) + return new float2(-1.0f, 1.0f); + return low ? new float2(-1.0f, min(-1.0f + e, 1.0f)) : new float2(max(1.0f - e, -1.0f), 1.0f); + } + + // Least and greatest distance along one axis from a box to a point, exact in float32: a coordinate in + // [lo, hi] is at least `near` and at most `far` from c, and squares, sums and sqrt are monotone. + private static (float Near, float Far) AxisDistance(float2 range, float c) => + (c < range.x ? range.x - c : c > range.y ? c - range.y : 0.0f, max(abs(range.x - c), abs(range.y - c))); + + /// + /// The noise of the fog and the void (r1's field shape): coverage is two snoise of the warped point, + /// cross-faded over two half-period phases; n = coverage + detail / 2, the detail one snoise at four + /// times the frequency. The flow is a unit-bounded 2D field times FlowAmplitude, so a phase moves a point + /// by at most Warp = FlowAmplitude * Period / 2. The flow is not counted: the site reads it from a + /// texture and Aetheria from its flow map. + /// + internal sealed class WarpedNoise + { + public required float F0 { get; init; } + public required float Warp { get; init; } + public float Period { get; init; } = 8.0f; + public float FlowFrequency { get; init; } = 1.0f / 512.0f; + public bool FlowInXY { get; init; } + + private float FlowAmplitude => Warp * 2.0f / Period; + + private float3 Flow(float3 p) + { + var q = (FlowInXY ? new float2(p.x, p.y) : new float2(p.x, p.z)) * FlowFrequency; + var v = new float2(snoise(q + new float2(17.0f, 3.0f)), snoise(q + new float2(-5.0f, 41.0f))); + v = v / max(1.0f, length(v)) * FlowAmplitude; + return FlowInXY ? new float3(v.x, v.y, 0.0f) : new float3(v.x, 0.0f, v.y); + } + + private (float W0, float Shift0, float Shift1) Phases(float time) + { + var phase0 = frac(time / Period); + var phase1 = frac(time / Period + 0.5f); + return (1.0f - abs(2.0f * phase0 - 1.0f), (phase0 - 0.5f) * Period, (phase1 - 0.5f) * Period); + } + + public float Coverage(float3 p, float time, Counts counts) + { + var (w0, shift0, shift1) = Phases(time); + var flow = Flow(p); + counts.Snoise += 2; + return w0 * snoise((p + flow * shift0) * F0) + (1.0f - w0) * snoise((p + flow * shift1) * F0); + } + + public float Detail(float3 p, Counts counts) + { + counts.Snoise++; + return snoise(p * (4.0f * F0) + 17.0f); + } + + // Both phases' warped points lie in a ball that carries the warp, so one ball encloses both snoise; + // the cross-fade is enclosed term by term with the frame's own weights. + public float2 CoverageBound(float2 ball, float time) + { + var w0 = Phases(time).W0; + return iv_add(iv_scale(ball, w0), iv_scale(ball, 1.0f - w0)); + } + + public float2 CoverageBall(float3 centre, float radius, Counts counts) => NoiseBall(centre * F0, radius * F0, counts); + + public float2 DetailBall(float3 centre, float radius, Counts counts) => NoiseBall(centre * (4.0f * F0) + 17.0f, radius * (4.0f * F0), counts); + + public float CoverageRadius(float radius) => radius * F0; + + public float DetailRadius(float radius) => radius * (4.0f * F0); + } + + /// + /// Aetheria's nebula (Assets/Shaders/Volumetric.cginc:165-221, cloudDensity :91-102) over its zone + /// height map (Assets/Scripts/ServerShared/Zone.cs:369-397 GetHeight, :426 PowerPulse), in its units + /// (Assets/Resources/Settings.asset: ZoneDepth :97-98, DefaultEnvironment :386-411). The pre-distortion + /// SDF is s(p) = p.y + h(p.xz), h >= 0 the well map: the zone bowl PowerPulse(|xz| / 2R, 2) * 64 plus, + /// per well, PowerPulse(|xz - c_b| / r_b, 16) * d_b, with r_b = 500 M^0.25, d_b = 30 M^0.175 and + /// PowerPulse(x, e) = (1 - 4x^2)^e on [0, 1/2], 0 beyond. Noise displaces only below the safety distance: + /// fade = 1 - smoothstep(0.75 S, S, s), s' = s + A fade n(warp(p)), density = max(0, (F - s') / B); the + /// patch band and the 1e-9 fill are left out. The warp moves only the noise argument; the height is read + /// at the unwarped xz, as Aetheria reads _NebulaSurfaceHeight at pos.xz. Envelope coordinates are the + /// tile's camera frame (the camera yaws about y, so horizontal distances are the world's). Extinction + /// 0.5 is the environment's (Settings.asset:397, applied at CloudShader.shader:91). + /// + internal sealed class FogField : Scenario + { + public const float Safety = 30.0f; // SafetyDistance, Settings.asset:399 + public const float FloorOffset = -20.0f; // :393 + public const float FloorBlend = 10.0f; // :394 + public const float Amplitude = 20.0f; + public const float NoiseScale = 414.2167f; // :409 + public const float AetheriaWarp = 60.0f; // Flow GlobalAmplitude 15 x Period 8 / 2, :402-405 + public const float ZoneRadius = 2000.0f; + private static readonly float2 FreeNoise = new(-1.5f, 1.5f); + + public required WarpedNoise Noise { get; init; } + public (float2 Centre, float Scale, float Exponent, float Depth)[] Bowls { get; init; } = Array.Empty<(float2, float, float, float)>(); + public required Func CameraAt { get; init; } + public required float2 SlopesY { get; init; } + + public FogField() + { + // Near 0.3 and far 1000: the ARPG scene's camera (Assets/Scenes/ARPG.unity:635-636). + Grid = Quadratic(0.3f, 1000.0f, 256); + Extinction = 0.5f; + } + + private static WarpedNoise AetheriaNoise(float warp) => new() { F0 = 1.0f / NoiseScale, Warp = warp }; + + /// (a) Height fog: no wells, the camera above the safety band at y = S + 30, rays level and up. + public static FogField HeightFog(float warp) => new() + { + Name = "(a) height fog", Noise = AetheriaNoise(warp), SlopesY = new float2(0.0f, 0.5f), + CameraAt = (random, _) => new float3(Uniform(random, -1000.0f, 1000.0f), Safety + 30.0f, Uniform(random, -1000.0f, 1000.0f)), + }; + + /// (b) Inside the fog: no wells, the camera at y = F - 10, rays level. + public static FogField InsideFog(float warp) => new() + { + Name = "(b) inside the fog", Noise = AetheriaNoise(warp), SlopesY = new float2(-0.05f, 0.05f), + CameraAt = (random, _) => new float3(Uniform(random, -1000.0f, 1000.0f), FloorOffset - 10.0f, Uniform(random, -1000.0f, 1000.0f)), + }; + + /// + /// (c) Aetheria-like: the zone bowl R = 2000 and four wells of mass 100, 1000, 10000 and 1000 at seeded + /// positions inside it; the camera at a seeded xz in the bowl, above the noise band at + /// y = max(0, S + 10 - h), gazing across with m_y in [-0.25, 0.1]. + /// + public static FogField Wells(float warp) + { + var random = new System.Random(0xA37E); + var bowls = new List<(float2, float, float, float)> { (new float2(0.0f, 0.0f), 2.0f * ZoneRadius, 2.0f, 64.0f) }; + foreach (var mass in new[] { 100.0f, 1000.0f, 10000.0f, 1000.0f }) + { + var angle = Uniform(random, 0.0f, 2.0f * MathF.PI); + var radius = ZoneRadius * MathF.Sqrt(random.NextSingle()); + bowls.Add((new float2(radius * MathF.Cos(angle), radius * MathF.Sin(angle)), 500.0f * MathF.Pow(mass, 0.25f), 16.0f, 30.0f * MathF.Pow(mass, 0.175f))); + } + + return new FogField + { + Name = "(c) Aetheria wells", Noise = AetheriaNoise(warp), Bowls = bowls.ToArray(), SlopesY = new float2(-0.25f, 0.1f), + CameraAt = (r, field) => + { + var angle = Uniform(r, 0.0f, 2.0f * MathF.PI); + var radius = ZoneRadius * MathF.Sqrt(r.NextSingle()); + var xz = new float2(radius * MathF.Cos(angle), radius * MathF.Sin(angle)); + var h = field.Height(field.Bowls.Select(b => b.Centre - xz).ToArray(), 0.0f, 0.0f); + return new float3(xz.x, max(0.0f, Safety + 10.0f - h), xz.y); + }, + }; + } + + private sealed class FogTile : Tile + { + public float2[] Centres = Array.Empty(); // bowl centres in the camera's (x, z) + } + + public override Tile DrawTile(System.Random random, int n) + { + var origin = CameraAt(random, this); + var yaw = Uniform(random, 0.0f, 2.0f * MathF.PI); + var tile = new FogTile + { + Origin = origin, N = n, Focal = Focal, Time = Uniform(random, 0.0f, 100.0f), + Slope = new float2(Uniform(random, -1.0f, 1.0f), Uniform(random, SlopesY.x, SlopesY.y)), + }; + tile.Look(new float3(MathF.Sin(yaw), 0.0f, MathF.Cos(yaw))); + tile.Centres = Bowls.Select(b => + { + var c = tile.Camera(new float3(b.Centre.x, origin.y, b.Centre.y)); + return new float2(c.x, c.z); + }).ToArray(); + return tile; + } + + private static float Pulse(float distance, float scale, float exponent) + { + var x = distance / scale; + var t = 1.0f - 4.0f * x * x; + return t <= 0.0f ? 0.0f : pow(t, exponent); + } + + // h at the camera-frame point (x, z), bowl centres in the same frame. + private float Height(float2[] centres, float x, float z) + { + var h = 0.0f; + for (var b = 0; b < Bowls.Length; b++) + { + var dx = x - centres[b].x; + var dz = z - centres[b].y; + h += Pulse(sqrt(dx * dx + dz * dz), Bowls[b].Scale, Bowls[b].Exponent) * Bowls[b].Depth; + } + + return h; + } + + // Each bowl's term over the box is [pulse(far), pulse(near)], pulse decreasing in distance; pow is + // not required to be correctly rounded, so both ends are widened by one ulp. + private float2 HeightBound(float2[] centres, float2 x, float2 z) + { + var h = iv_point(0.0f); + for (var b = 0; b < Bowls.Length; b++) + { + var (nx, fx) = AxisDistance(x, centres[b].x); + var (nz, fz) = AxisDistance(z, centres[b].y); + var near = Pulse(sqrt(nx * nx + nz * nz), Bowls[b].Scale, Bowls[b].Exponent); + var far = Pulse(sqrt(fx * fx + fz * fz), Bowls[b].Scale, Bowls[b].Exponent); + var pulse = new float2(far > 0.0f ? MathF.BitDecrement(far) : 0.0f, near > 0.0f ? MathF.BitIncrement(near) : 0.0f); + h = iv_add(h, iv_scale(pulse, Bowls[b].Depth)); + } + + return h; + } + + private static float2 Compose(float2 s, float2 fade, float2 n) + { + var displaced = iv_add(s, iv_scale(iv_mul(fade, n), Amplitude)); + return new float2(max(0.0f, (FloorOffset - displaced.y) / FloorBlend), max(0.0f, (FloorOffset - displaced.x) / FloorBlend)); + } + + public override float Density(Tile t, float2 slope, float z, bool lod, Counts counts) + { + var tile = (FogTile)t; + var x = slope.x * z; + var y = slope.y * z; + counts.Envelope++; + var s = tile.Origin.y + y + Height(tile.Centres, x, z); + var fade = 1.0f - smoothstep(0.75f * Safety, Safety, s); + if (Compose(iv_point(s), iv_point(fade), FreeNoise).y <= 0.0f) + return 0.0f; + var p = tile.World(new float3(x, y, z)); + var coverage = Noise.Coverage(p, tile.Time, counts); + if (Compose(iv_point(s), iv_point(fade), iv_add(iv_point(coverage), iv_scale(new float2(-1.0f, 1.0f), 0.5f))).y <= 0.0f) + return 0.0f; + var n = coverage + Noise.Detail(p, counts) * 0.5f; + return max(0.0f, (FloorOffset - (s + fade * n * Amplitude)) / FloorBlend); + } + + public override float2 Bound(Tile t, float z0, float z1, bool gated, Counts counts) + { + var tile = (FogTile)t; + var depth = new float2(z0, z1); + counts.Envelope++; + var height = HeightBound(tile.Centres, iv_mul(depth, tile.SlopesX), depth); + var s = iv_add(iv_add(iv_point(tile.Origin.y), iv_mul(depth, tile.SlopesY)), height); + var fade = iv_sub(iv_point(1.0f), iv_smoothstep(0.75f * Safety, Safety, s)); + var envelope = Compose(s, fade, FreeNoise); + if (gated && envelope.y <= 0.0f) + return envelope; + var ball = iv_frustum_ball(tile.Slope, z0, z1, tile.Footprint, Noise.Warp); + if (gated) + { + var provable = false; + foreach (var low in new[] { true, false }) + { + var best = iv_add(Noise.CoverageBound(BestBall(Noise.CoverageRadius(ball.w), low), tile.Time), iv_scale(BestBall(Noise.DetailRadius(ball.w), low), 0.5f)); + provable |= Compose(s, fade, best).y <= 0.0f; + } + + if (!provable) + return envelope; + } + + var centre = tile.World(new float3(ball.x, ball.y, ball.z)); + var noise = iv_add(Noise.CoverageBound(Noise.CoverageBall(centre, ball.w, counts), tile.Time), iv_scale(Noise.DetailBall(centre, ball.w, counts), 0.5f)); + return Compose(s, fade, noise); + } + } + + /// + /// (d) r1's uniform slab, kept as the worst case: the map's warped coverage field (F0 0.35, cutoff 0.25, + /// depth 12, period 4, extinction 2, flow in xy at 0.15, warp 0.05) with no envelope, so every cell is a + /// noise question. The dense sample evaluates the coverage first and the detail only where the coverage + /// passes the cutoff; ungated it would cost three snoise, as r1 counted. + /// + internal sealed class SlabField : Scenario { public const float F0 = 0.35f; public const float Cutoff = 0.25f; public const float Depth = 12.0f; - public const float Period = 4.0f; - public const float Extinction = 2.0f; - public const float FlowFrequency = 0.15f; + public const float SlabExtinction = 2.0f; + public const float SlabWarp = 0.05f; - public float Step0 { get; init; } = 0.25f; - public float Warp { get; init; } = 0.05f; + public required WarpedNoise Noise { get; init; } - public float StepDense => Step0 * 0.5f; - public float StepMax => Step0 * 8.0f; - public float FlowAmplitude => Warp * 2.0f / Period; + public SlabField() => Grid = Cells(0.125f, Depth); - public long Evaluations; - - private float2 Flow(float3 p) + public static SlabField Create(float warp) => new() { - var q = new float2(p.x, p.y) * FlowFrequency; - var v = new float2(snoise(q + new float2(17.0f, 3.0f)), snoise(q + new float2(-5.0f, 41.0f))); - return v / max(1.0f, length(v)) * FlowAmplitude; - } + Name = "(d) uniform slab", Noise = new WarpedNoise { F0 = F0, Warp = warp, Period = 4.0f, FlowFrequency = 0.15f, FlowInXY = true }, + }; - public float Density(float3 p, float time) + public override Tile DrawTile(System.Random random, int n) => new() { - var flow = Flow(p); - var phase0 = frac(time / Period); - var phase1 = frac(time / Period + 0.5f); - var w0 = 1.0f - abs(2.0f * phase0 - 1.0f); - var coverage = w0 * snoise((p + new float3(flow * ((phase0 - 0.5f) * Period), 0.0f)) * F0) - + (1.0f - w0) * snoise((p + new float3(flow * ((phase1 - 0.5f) * Period), 0.0f)) * F0); + Origin = new float3(Uniform(random, -50.0f, 50.0f), Uniform(random, -50.0f, 50.0f), 0.0f), + Slope = new float2(Uniform(random, -0.5f, 0.5f), Uniform(random, -0.5f, 0.5f)), + N = n, Focal = Focal, Time = Uniform(random, 0.0f, 100.0f), + }; + + public override float Density(Tile tile, float2 slope, float z, bool lod, Counts counts) + { + var p = tile.World(new float3(slope.x * z, slope.y * z, z)); + var coverage = Noise.Coverage(p, tile.Time, counts); + if (coverage <= Cutoff) + return 0.0f; + counts.Snoise++; var detail = 1.0f - abs(snoise(p * (4.0f * F0) + 17.0f)); - Evaluations += 3; - return max(0.0f, coverage - Cutoff) * Extinction * lerp(0.6f, 1.0f, detail); + return max(0.0f, coverage - Cutoff) * SlabExtinction * lerp(0.6f, 1.0f, detail); } - // Transmittance through the dense grid: cells of StepDense in z, one sample at each midpoint. - public float MarchDense(float3 origin, float3 direction, float time) + public override float2 Bound(Tile tile, float z0, float z1, bool gated, Counts counts) { - var transmittance = 1.0f; - for (var z = 0.0f; z < Depth && transmittance >= 0.02f; z += StepDense) - transmittance *= Integrate(origin, direction, time, z, StepDense); - return transmittance; - } - - private float Integrate(float3 origin, float3 direction, float time, float z, float step) => - exp(-Density(origin + direction * ((z + step * 0.5f) / direction.z), time) * (step / direction.z)); - - // The map's adaptive march: probe a segment with one iv_snoise_ball; provably empty skips and grows, - // maybe-dense halves down to StepDense, where the cell is integrated exactly as the dense march does. - // Steps are StepDense times powers of two, so every integrated cell is a cell of the dense grid. - public float MarchIntervals(float3 origin, float3 direction, float time) - { - var transmittance = 1.0f; - var z = 0.0f; - var step = Step0; - while (z < Depth && transmittance >= 0.02f) - { - while (z + step > Depth) - step *= 0.5f; - var centre = origin + direction * ((z + step * 0.5f) / direction.z); - var radius = step * 0.5f / direction.z + Warp; - Evaluations++; - if (iv_snoise_ball(centre * F0, radius * F0).y < Cutoff) - { - z += step; - step = min(step * 2.0f, StepMax); - } - else if (step > StepDense) - { - step *= 0.5f; - } - else - { - transmittance *= Integrate(origin, direction, time, z, step); - z += step; - } - } - - return transmittance; - } - - public (long Dense, long Intervals, float MaxDifference) Run(int rays, int seed) - { - var random = new System.Random(seed); - long dense = 0, intervals = 0; - var maxDifference = 0.0f; - for (var r = 0; r < rays; r++) - { - var origin = new float3(Uniform(random, -50.0f, 50.0f), Uniform(random, -50.0f, 50.0f), 0.0f); - var direction = normalize(new float3(Uniform(random, -0.5f, 0.5f), Uniform(random, -0.5f, 0.5f), 1.0f)); - var time = Uniform(random, 0.0f, 100.0f); - Evaluations = 0; - var a = MarchDense(origin, direction, time); - dense += Evaluations; - Evaluations = 0; - var b = MarchIntervals(origin, direction, time); - intervals += Evaluations; - maxDifference = MathF.Max(maxDifference, MathF.Abs(a - b)); - } - - return (dense, intervals, maxDifference); + var maybe = new float2(0.0f, float.MaxValue); + var ball = iv_frustum_ball(tile.Slope, z0, z1, tile.Footprint, Noise.Warp); + if (gated && Noise.CoverageBound(BestBall(Noise.CoverageRadius(ball.w), low: true), tile.Time).y > Cutoff) + return maybe; + var coverage = Noise.CoverageBound(Noise.CoverageBall(tile.World(new float3(ball.x, ball.y, ball.z)), ball.w, counts), tile.Time); + return coverage.y <= Cutoff ? new float2(0.0f, 0.0f) : maybe; } } /// - /// The interval march must reach the dense march's transmittance within 1e-3 (it integrates the same - /// cells, so any difference is a skipped cell that was not empty) with at most half its snoise - /// evaluations. Also prints the ratio over a small grid of first steps and warp bounds (300 rays each). - /// The 2x saving does not hold at SNOISE_LIPSCHITZ as measured; that is an open fork for the campaign - /// (cultmath-tapes, interval-ops cut report), so a ratio below 2 skips with the fork named rather than - /// failing or being tuned away. + /// (e) The void, the shipped scene: a cloud volume everywhere, carved by one negative pseudo-Gaussian + /// sphere. Authored knobs: hollow radius Rh (density exactly 0 inside) and ramp width S (the density + /// rises to full over [Rh, Rh + S]). The brush (1 - (d / Rc)^2)^e with CARVE = 1.5 reaches full at Rc, + /// so Rc = Rh + S, and Rh = Rc sqrt(1 - CARVE^(-1/e)) gives e = -ln CARVE / ln(1 - (Rh / Rc)^2): + /// density = K max(0, 1 - CARVE (1 - (d' / Rc)^2)^e), exactly 0 for d' <= Rh and K for d' >= Rc, + /// K = 1/30. The noise displaces the wall: fade = smoothstep(Rh - S, Rh, d), d' = d + A fade n(warp(p)), + /// A = 20, F0 = 0.01 (wavelengths 100 and 25), warp D = 10. The sun orbits the origin at radius 175 with + /// period 72 s and rests on the hollow's bottom (c_v = sun + (0, Rh - 12.5, 0)); the camera looks at + /// sun + (0, 60, 0) and, shipped, sits 120 behind the sun along the orbit tangent and 45 above it. The + /// footprint-truncated field (lod) weights octave i by w_i(z) = 1 - smoothstep(l_i / 2m, l_i / m, + /// z theta), m = 4, theta = 1 / f; the bound takes each weight over [w_i(z1), 1], which holds both the + /// truncated and the full field. The dense grid is the fixed-step reference's: cells of min(10, S / 4) + /// out to |camera - c_v| + Rc + 5 / K, past where every ray has gone opaque. /// - [Fact] - public void IntervalSkipHalvesEvaluations() + internal sealed class VoidField : Scenario { - var field = new SavingField(); - var (dense, intervals, maxDifference) = field.Run(1000, 0x5A7E); - output.WriteLine($"IV-REPORT saving: dense {dense} snoise, interval march {intervals} snoise, ratio {(double)dense / intervals:F2}; max transmittance difference {maxDifference:R} (step0 {field.Step0:R}, warp {field.Warp:R}, L {SNOISE_LIPSCHITZ:R})"); - foreach (var step0 in new[] { 0.0625f, 0.25f, 1.0f }) - foreach (var warp in new[] { 0.0f, 0.05f }) + public const float Carve = 1.5f; + public const float Amplitude = 20.0f; + public const float K = 1.0f / 30.0f; + public const float StepFootprints = 4.0f; // k + public const float OctaveFootprints = 4.0f; // m + private static readonly float2 FreeNoise = new(-1.5f, 1.5f); + + public static readonly float[] HollowRadii = { 100.0f, 200.0f, 400.0f, 1000.0f }; + public static readonly float[] Ramps = { 10.0f, 50.0f, 150.0f }; + public static readonly (string Name, float Fraction)[] CameraOffsets = { ("centred", 0.0f), ("mid", 0.5f), ("low", 0.94f) }; + + public readonly float HollowRadius; + public readonly float Ramp; + public readonly float CarveRadius; + public readonly float Exponent; + public readonly float RampStart; + public readonly float FixedStep; + public readonly float CameraFraction; // negative: the shipped camera + public readonly WarpedNoise Noise = new() { F0 = 0.01f, Warp = 10.0f }; + + private float CoarseWavelength => 1.0f / Noise.F0; + private float FineWavelength => 1.0f / (4.0f * Noise.F0); + private float Theta => 1.0f / Focal; + + [System.Diagnostics.CodeAnalysis.SetsRequiredMembers] + public VoidField(float hollowRadius, float ramp, float cameraFraction, string camera) { - var (d, i, m) = new SavingField { Step0 = step0, Warp = warp }.Run(300, 0x5A7F); - Assert.True(m <= 1.0e-3f, $"transmittance differs by {m:R} at step0 {step0:R}, warp {warp:R}"); - output.WriteLine($"IV-REPORT saving grid: step0 {step0:R} warp {warp:R}: dense {d}, interval march {i}, ratio {(double)d / i:F2}"); + HollowRadius = hollowRadius; + Ramp = ramp; + CarveRadius = hollowRadius + ramp; + Exponent = (float)(-Math.Log(Carve) / Math.Log(1.0 - (double)hollowRadius / CarveRadius * hollowRadius / CarveRadius)); + RampStart = hollowRadius - ramp; + FixedStep = min(10.0f, ramp / 4.0f); + CameraFraction = cameraFraction; + Name = $"(e) void Rh={hollowRadius:R} camera={camera} S={ramp:R}"; + var reach = cameraFraction < 0.0f ? length(new float2(120.0f, 45.0f - (hollowRadius - 12.5f))) : cameraFraction * hollowRadius; + Grid = Cells(FixedStep, reach + CarveRadius + 5.0f / K); } - Assert.True(maxDifference <= 1.0e-3f, $"transmittance differs by {maxDifference:R}"); - if (dense < 2 * intervals) - Assert.Skip($"FORK (cultmath-tapes interval-ops): the interval march saves {(double)dense / intervals:F2}x, not 2x, at SNOISE_LIPSCHITZ {SNOISE_LIPSCHITZ:R}"); + public static VoidField Shipped() => new(198.0f, 50.0f, -1.0f, "shipped"); + + private sealed class VoidTile : Tile + { + public float3 Cavity; // c_v in the camera frame + } + + public override Tile DrawTile(System.Random random, int n) + { + var time = Uniform(random, 0.0f, 72.0f); + var angle = 2.0f * MathF.PI * time / 72.0f; + var sun = new float3(175.0f * MathF.Cos(angle), 0.0f, 175.0f * MathF.Sin(angle)); + var tangent = new float3(-MathF.Sin(angle), 0.0f, MathF.Cos(angle)); + var cavity = sun + new float3(0.0f, HollowRadius - 12.5f, 0.0f); + var target = sun + new float3(0.0f, 60.0f, 0.0f); + float3 origin; + float3 forward; + if (CameraFraction < 0.0f) + { + origin = sun - tangent * 120.0f + new float3(0.0f, 45.0f, 0.0f); + forward = target - origin; + } + else + { + // The shipped camera's direction from the centre, at a fraction of this hollow's radius; + // centred, it looks along the orbit, slightly down. + origin = cavity + normalize(tangent * -120.0f + new float3(0.0f, 45.0f - (198.0f - 12.5f), 0.0f)) * (CameraFraction * HollowRadius); + forward = CameraFraction == 0.0f ? tangent * -1.0f + new float3(0.0f, -0.2f, 0.0f) : target - origin; + } + + var tile = new VoidTile + { + Origin = origin, N = n, Focal = Focal, Time = time, + Slope = new float2((random.Next(1920 / n) * n + n * 0.5f - 960.0f) / Focal, (random.Next(1080 / n) * n + n * 0.5f - 540.0f) / Focal), + }; + tile.Look(forward); + tile.Cavity = tile.Camera(cavity); + return tile; + } + + private static float Weight(float wavelength, float footprint) => + 1.0f - smoothstep(wavelength / (2.0f * OctaveFootprints), wavelength / OctaveFootprints, footprint); + + private float2 WeightBound(float wavelength, float z0, float z1) => + new(iv_sub(iv_point(1.0f), iv_smoothstep(wavelength / (2.0f * OctaveFootprints), wavelength / OctaveFootprints, new float2(z0 * Theta, z1 * Theta))).x, 1.0f); + + /// The footprint step: max(k z theta, min(S / 4, half the finest live wavelength)). + public float LodStep(float z) + { + var footprint = z * Theta; + var fine = Weight(FineWavelength, footprint) > 0.0f ? FineWavelength : Weight(CoarseWavelength, footprint) > 0.0f ? CoarseWavelength : float.PositiveInfinity; + return max(StepFootprints * footprint, min(Ramp / 4.0f, fine / 2.0f)); + } + + private float Profile(float displaced) + { + if (displaced <= HollowRadius) + return 0.0f; + var x = displaced / CarveRadius; + var g = displaced < CarveRadius ? pow(max(0.0f, 1.0f - x * x), Exponent) : 0.0f; + return K * max(0.0f, 1.0f - Carve * g); + } + + private float2 Compose(float2 d, float2 fade, float2 n) + { + var displaced = iv_add(d, iv_scale(iv_mul(fade, n), Amplitude)); + return new float2(displaced.x >= CarveRadius ? K : 0.0f, displaced.y <= HollowRadius ? 0.0f : K); + } + + public override float Density(Tile t, float2 slope, float z, bool lod, Counts counts) + { + var tile = (VoidTile)t; + var x = slope.x * z; + var y = slope.y * z; + counts.Envelope++; + var dx = x - tile.Cavity.x; + var dy = y - tile.Cavity.y; + var dz = z - tile.Cavity.z; + var d = sqrt(dx * dx + dy * dy + dz * dz); + var fade = smoothstep(RampStart, HollowRadius, d); + var free = Compose(iv_point(d), iv_point(fade), FreeNoise); + if (free.x == free.y) + return free.x; + var p = tile.World(new float3(x, y, z)); + var wc = lod ? Weight(CoarseWavelength, z * Theta) : 1.0f; + var wd = lod ? Weight(FineWavelength, z * Theta) : 1.0f; + var coverage = wc > 0.0f ? Noise.Coverage(p, tile.Time, counts) * wc : 0.0f; + var partial = Compose(iv_point(d), iv_point(fade), iv_add(iv_point(coverage), iv_scale(new float2(-wd, wd), 0.5f))); + if (partial.x == partial.y) + return partial.x; + var detail = wd > 0.0f ? Noise.Detail(p, counts) * 0.5f * wd : 0.0f; + return Profile(d + fade * (coverage + detail) * Amplitude); + } + + public override float2 Bound(Tile t, float z0, float z1, bool gated, Counts counts) + { + var tile = (VoidTile)t; + var depth = new float2(z0, z1); + counts.Envelope++; + var (nx, fx) = AxisDistance(iv_mul(depth, tile.SlopesX), tile.Cavity.x); + var (ny, fy) = AxisDistance(iv_mul(depth, tile.SlopesY), tile.Cavity.y); + var (nz, fz) = AxisDistance(depth, tile.Cavity.z); + var d = new float2(sqrt(nx * nx + ny * ny + nz * nz), sqrt(fx * fx + fy * fy + fz * fz)); + var fade = iv_smoothstep(RampStart, HollowRadius, d); + var envelope = Compose(d, fade, FreeNoise); + if (gated && envelope.y <= 0.0f) + return envelope; + var ball = iv_frustum_ball(tile.Slope, z0, z1, tile.Footprint, Noise.Warp); + var wc = WeightBound(CoarseWavelength, z0, z1); + var wd = WeightBound(FineWavelength, z0, z1); + if (gated) + { + var provable = false; + foreach (var low in new[] { true, false }) + { + var best = iv_add(iv_mul(Noise.CoverageBound(BestBall(Noise.CoverageRadius(ball.w), low), tile.Time), wc), iv_mul(iv_scale(BestBall(Noise.DetailRadius(ball.w), low), 0.5f), wd)); + provable |= Compose(d, fade, best).y <= 0.0f; + } + + if (!provable) + return envelope; + } + + var centre = tile.World(new float3(ball.x, ball.y, ball.z)); + var noise = iv_add(iv_mul(Noise.CoverageBound(Noise.CoverageBall(centre, ball.w, counts), tile.Time), wc), iv_mul(iv_scale(Noise.DetailBall(centre, ball.w, counts), 0.5f), wd)); + return Compose(d, fade, noise); + } } }