acdream/src/AcDream.App/Rendering/Packs/AtmosphericFrameInputs.cs
Erik 43e3abed4d fix(render): correct foliage-wind classification, receiver/caster desync, and frame binding (Campaign VM VM6 review)
Opus dual-lens review of the three VM6 commits (0930c35d, 39e8408c,
6cc5e183) found two blockers and two should-fix issues; all landed here
along with the review's nits and documentation corrections.

Blockers:
- A1: the procedural-scenery classifier tested bit 31 alone instead of
  the full top nibble (0xF000_0000 == 0x8000_0000), so it also matched
  LandblockStaticEntityIdAllocator's 0xC... namespace (fences/gates/
  building shells with a cutout subset), the 0xDA11_D0xx paperdoll id,
  and the 0xFFFF_FF01 portal-tunnel id as procedural scenery — all
  three would have swayed. ProceduralSceneryIdAllocator.IsInNamespace
  now does the exact top-nibble test; FoliageWindClassification
  delegates to it.
- A2: GroupKey (the receiver's instance-batching key) did not carry
  FoliageFlags while the caster's dedup key already did, so a scenery
  instance and a non-scenery instance sharing a mesh subset coalesced
  into one receiver InstanceGroup whose flags were last-writer-wins —
  disagreeing with the correctly-keyed caster. GroupKey now carries
  FoliageFlags, computed before key construction and set exactly once
  at group creation; the imperative re-stamp is gone, and CachedBatch's
  now-redundant FoliageFlags field is removed.

Should-fix:
- A3: the world receiver pass bound UniformAtmosphericFrame only by
  accident (leftover from the caster pass, which runs first each
  frame, since Vulkan binding state isn't reset between passes).
  DirectionalShadowFrameBinding now carries the caster's exact
  AtmosphericFrameBufferBinding and BindDirectionalShadowReceiver binds
  it explicitly.
- A4: a Setup-composed tree's opaque trunk part never got the trunk
  flag because HasCutoutSubset is cached per GfxObj part, not per
  entity. FoliageWindClassification.ComputeEntityHasCutoutSubset now
  ORs HasCutoutSubset across an entity's resolved sibling parts once
  per entity, threaded into ClassifyBatches/AddDirectionalShadowBatches
  via a new optional override parameter.

Nits: A5 hashes the per-vertex flutter seed relative to the instance
origin instead of absolute world XY (fp32 sin() precision loss at far
landblock corners), mirrored in both foliage_wind.glsl and
FoliageWindModel; A7 documents the max(maxHeight, 0.5) divide-guard as
a deliberate pseudocode divergence; A8 switches FoliageWindExclusions'
construction to ToFrozenSet() and softens the "never stale" doc
comment to "no slower than one frame behind."

Tests added: top-nibble classification (0xFFFFFFFFu now correctly
false), GroupKey inequality across entity-driven scenery/landblock-
static classification, a caster-batch test proving the same pairing
never coalesces, ComputeEntityHasCutoutSubset unit + end-to-end
two-part-Setup tests, the caster→receiver AtmosphericFrame binding
carry-through, flutter-hash translation invariance relative to
instance origin, and a Storm-wind mid-height displacement floor
guarding against a "no motion" regression.

Docs: plan VM6 body corrected to the five-row WeatherKind table, "bits
1 and 2", "all four" caster shaders, and top-nibble wording throughout;
the owner gate checklist's Rain/Storm step; the stale v1-only shader-
interface compatibility entry; semantic-bindings-v1.md's v2 members
folded into the main 192-byte block; the IA-25 register row's top-
nibble wording; AtmosphericFrameInputs.cs's ABI size reference.

foliage_wind.glsl's A5 change recompiled exactly the five shaders that
include it (mesh_atmospheric.vert, the four directional_shadow_world_*
casters) plus the manifest; no other .spv changed.

Verify: Release build 0 warnings/0 errors. App hermetic-lane filter
6,041/0 failed (no environment-specific failures this run).
RenderPackValidator 30/30. Full hermetic-filtered solution: 15,269/0
failed across 15 projects.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 01:54:36 +02:00

241 lines
8 KiB
C#

using System.Numerics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using AcDream.Core.World;
using AcDream.Plugin.Abstractions.Rendering;
namespace AcDream.App.Rendering.Packs;
/// <summary>
/// Immutable authored atmosphere and exact camera projection captured from the
/// normal world frame. This value owns no gameplay or renderer objects and is
/// valid after the wrapped world renderer returns.
/// </summary>
internal readonly record struct AtmosphericFrameInputs(
Vector2 SunScreenUv,
bool SunIsOnScreen,
float SunElevationDegrees,
Vector3 SunColor,
Vector3 SunDirection,
float SunDirectionalBrightness,
Matrix4x4 InverseViewProjection,
int ActiveDayGroup,
WeatherKind Weather,
float WeatherIntensity,
double DeltaSeconds,
int ViewportWidth,
int ViewportHeight,
bool IsOutdoor);
internal interface IAtmosphericWorldFrameSink
{
void Publish(
in RenderFrameFoundation foundation,
in WorldRenderFrame world,
int activeDayGroup);
}
/// <summary>
/// One-frame handoff between <see cref="WorldSceneRenderer"/>, which owns the
/// canonical camera build, and the post graph. Reset happens before the world
/// pass so an intentionally skipped world can never reuse a prior camera.
/// </summary>
internal sealed class AtmosphericFrameInputState : IAtmosphericWorldFrameSink
{
private RenderFrameInput _host;
private RenderFrameFoundation _foundation;
private AtmosphericFrameInputs _current;
private bool _published;
internal void BeginFrame(
in RenderFrameInput host,
in RenderFrameFoundation foundation)
{
_host = host;
_foundation = foundation;
_current = default;
_published = false;
}
public void Publish(
in RenderFrameFoundation foundation,
in WorldRenderFrame world,
int activeDayGroup)
{
Vector3 direction = SkyStateProvider.SunDirectionFromKeyframe(foundation.Sky);
Vector3 sunPoint = world.Camera.Position + (direction * 10_000f);
Vector4 clip = Vector4.Transform(
new Vector4(sunPoint, 1f),
world.Camera.ViewProjection);
bool finite = float.IsFinite(clip.X)
&& float.IsFinite(clip.Y)
&& float.IsFinite(clip.W)
&& clip.W > 1e-5f;
Vector2 uv = finite
? new Vector2(
(clip.X / clip.W * 0.5f) + 0.5f,
0.5f - (clip.Y / clip.W * 0.5f))
: new Vector2(-1f, -1f);
bool onScreen = finite
&& uv.X >= 0f && uv.X <= 1f
&& uv.Y >= 0f && uv.Y <= 1f;
Matrix4x4 inverseViewProjection = Matrix4x4.Invert(
world.Camera.ViewProjection,
out Matrix4x4 inverse)
? inverse
: Matrix4x4.Identity;
_current = new AtmosphericFrameInputs(
uv,
onScreen,
foundation.Sky.SunPitchDeg,
foundation.Sky.SunColor,
direction,
foundation.Sky.DirBright,
inverseViewProjection,
activeDayGroup,
foundation.Atmosphere.Kind,
Math.Clamp(foundation.Atmosphere.Intensity, 0f, 1f),
_host.DeltaSeconds,
_host.ViewportWidth,
_host.ViewportHeight,
IsOutdoor: world.Roots.RenderSky && !world.Roots.CameraInsideCell);
_published = true;
}
internal AtmosphericFrameInputs Snapshot()
{
if (_published)
return _current;
// A portal/login frame deliberately skipped the normal world. Preserve
// its authored colour inputs but suppress every directional effect.
return new AtmosphericFrameInputs(
new Vector2(-1f, -1f),
SunIsOnScreen: false,
_foundation.Sky.SunPitchDeg,
_foundation.Sky.SunColor,
SkyStateProvider.SunDirectionFromKeyframe(_foundation.Sky),
_foundation.Sky.DirBright,
Matrix4x4.Identity,
-1,
_foundation.Atmosphere.Kind,
Math.Clamp(_foundation.Atmosphere.Intensity, 0f, 1f),
_host.DeltaSeconds,
_host.ViewportWidth,
_host.ViewportHeight,
IsOutdoor: false);
}
}
/// <summary>
/// Shader ABI SSOT for opt-in set 3 binding 5. ABI v2 (Campaign VM VM6):
/// six std140 vec4 values, one mat4, then two more std140 vec4 values —
/// 192 bytes. The two appended members carry the foliage-wind clock/weather
/// and amplitude inputs <c>foliage_wind.glsl</c> reads; every earlier member
/// keeps its ABI v1 offset. See <see cref="RenderPackShaderAbi.AtmosphericFrameSizeBytes"/>
/// and <c>atmospheric_common.glsl</c> for the byte-level contract both
/// backends and the SPIR-V validator agree on.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal readonly struct AtmosphericFrameUniforms
{
internal const int SizeInBytes = 192;
internal AtmosphericFrameUniforms(
Vector4 sunScreen,
Vector4 sunColor,
Vector4 viewport,
Vector4 weather,
Vector4 sunDirection,
Vector4 policy,
Matrix4x4 inverseViewProjection,
Vector4 clockWind,
Vector4 windAmplitude)
{
SunScreen = sunScreen;
SunColor = sunColor;
Viewport = viewport;
Weather = weather;
SunDirection = sunDirection;
Policy = policy;
InverseViewProjection = inverseViewProjection;
ClockWind = clockWind;
WindAmplitude = windAmplitude;
}
internal readonly Vector4 SunScreen;
internal readonly Vector4 SunColor;
internal readonly Vector4 Viewport;
internal readonly Vector4 Weather;
internal readonly Vector4 SunDirection;
internal readonly Vector4 Policy;
internal readonly Matrix4x4 InverseViewProjection;
// Campaign VM VM6 ABI v2 additions — offsets 160/176.
internal readonly Vector4 ClockWind;
internal readonly Vector4 WindAmplitude;
}
/// <summary>
/// Shader ABI SSOT for opt-in set 3 binding 7. Passes assign meanings to four std140
/// vec4 values without changing the shared descriptor layout.
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal readonly struct AtmosphericPackPassUniforms
{
internal const int SizeInBytes = 64;
internal AtmosphericPackPassUniforms(
Vector4 params0,
Vector4 params1,
Vector4 params2,
Vector4 params3)
{
Params0 = params0;
Params1 = params1;
Params2 = params2;
Params3 = params3;
}
internal readonly Vector4 Params0;
internal readonly Vector4 Params1;
internal readonly Vector4 Params2;
internal readonly Vector4 Params3;
internal static AtmosphericPackPassUniforms From(Vector4 params0) =>
new(params0, Vector4.Zero, Vector4.Zero, Vector4.Zero);
}
/// <summary>
/// Shader ABI SSOT for opt-in set 3 binding 8. API v1 exposes 64 scalar values in
/// descriptor declaration order, physically grouped as sixteen std140 vec4s.
/// </summary>
[InlineArray(RenderPackShaderAbi.PackSettingScalarCapacity)]
internal struct PackSettingsUniforms
{
internal const int SizeInBytes = RenderPackShaderAbi.PackSettingsSizeBytes;
private float _element0;
internal static PackSettingsUniforms Create(
RenderPackDescriptor descriptor,
RenderQualityPreset preset,
IReadOnlyDictionary<string, string>? userSettingOverrides = null)
{
var result = new PackSettingsUniforms();
int count = Math.Min(
descriptor.Settings.Count,
RenderPackShaderAbi.PackSettingScalarCapacity);
for (int i = 0; i < count; i++)
{
RenderSettingDeclaration setting = descriptor.Settings[i];
string value = RenderPackSettingResolution.Resolve(
setting,
preset,
userSettingOverrides);
result[i] = RenderPackSettingValueCodec.TryEncode(setting, value, out float encoded)
? encoded
: 0f;
}
return result;
}
}