Merge origin/nibu/rtd-prototype (9a07a4b) into nibu/rtd-cut14b-hud

This commit is contained in:
Meta Vens 2026-12-06 01:55:04 +01:00
commit 154ac25157
48 changed files with 5577 additions and 1196 deletions

Binary file not shown.

Binary file not shown.

View file

@ -2,7 +2,7 @@
"name": "Sion, Valais, Switzerland",
"attribution": "Federal Office of Topography swisstopo",
"sources": [
"ch.swisstopo.swissalti3d (2m DTM, Open Government Data)",
"ch.swisstopo.swissalti3d (0.5m DTM, Open Government Data)",
"ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)"
],
"stacItems": [
@ -27,24 +27,33 @@
"swissbuildings3d_3_0_2020_1306-21",
"swissbuildings3d_3_0_2020_1306-23"
],
"demAssetHash": "a0dae3310058004e43a071290b3972ae4e0919e0958be5ec56320ea1a204c5de",
"crs": "EPSG:2056",
"originE": 2592614.0,
"originN": 1118514.0,
"centerE": 2594150.0,
"centerN": 1120050.0,
"baseElevationM": 483.41,
"minY": -5.863,
"maxY": 304.92,
"reliefM": 310.783,
"minY": -5.885,
"maxY": 304.957,
"reliefM": 310.841,
"sizeMeters": 3072.0,
"tileGrid": 6,
"tileSizeMeters": 512.0,
"gridRes": 1025,
"cellSizeMeters": 3.0,
"heightmapFormat": "float32_le_row_major",
"tileGrid": 16,
"tileSizeMeters": 192.0,
"buildingTileGrid": 6,
"buildingTileSizeMeters": 512.0,
"gridRes": 6145,
"cellSizeMeters": 0.5,
"heightmapFile": "heightmap_05m.u16z",
"heightmapFormat": "rdhm_v2_u16_zigzag_zlib",
"heightmapMinY": -5.884674072265625,
"heightmapScale": 0.004743136931210756,
"surfaceTexture": "terrain_surface.png",
"surfaceTextureSize": 2048,
"surfaceTextureSize": 4096,
"surfaceTextureFormat": "png_rgb_north_to_south_west_to_east",
"surfaceMaskTexture": "terrain_surface_mask.png",
"surfaceMaskTextureSize": 2048,
"surfaceMaskFormat": "png_rgba_rock_grass_asphalt_water",
"collisionFormat": {
"magic": "RCOL",
"version": 1,

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

After

Width:  |  Height:  |  Size: 9.7 MiB

Before After
Before After

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 MiB

View file

@ -90,12 +90,12 @@ public static class AtmosphereLutBaker
MieScattering: new Vector3(3.2e-6f, 3.2e-6f, 3.2e-6f),
MieG: 0.78f,
SolarIrradiance: 17.5f,
CalibratedSunEnergy: 1.28f,
CalibratedSunEnergy: 2.85f,
FogMaxLengthMeters: 460f,
VolumetricFogDensity: 0.0008f,
VolumetricFogDetailSpread: 2.4f,
VolumetricFogAnisotropy: 0.62f,
VolumetricFogEmissionEnergy: 0.18f,
VolumetricFogEmissionEnergy: 0f,
ValleyVolumeSize: new Vector3(3100f, 110f, 3100f),
ValleyVolumePosition: new Vector3(0f, 20f, 0f),
ValleyVolumeDensity: 0.0038f,
@ -108,7 +108,7 @@ public static class AtmosphereLutBaker
DepthFogAerialPerspective: 0.88f,
DepthFogSunScatter: 0.45f,
ShadowMaxDistance: 320f,
AmbientLightEnergy: 0.48f,
AmbientLightEnergy: 0.0f,
SunDiscIntensity: 8.5f,
MieAureoleStrength: 0.24f)
: new AtmospherePreset(
@ -120,12 +120,12 @@ public static class AtmosphereLutBaker
MieScattering: new Vector3(10.5e-6f, 8.8e-6f, 6.6e-6f),
MieG: 0.74f,
SolarIrradiance: 16.0f,
CalibratedSunEnergy: 1.42f,
CalibratedSunEnergy: 2.55f,
FogMaxLengthMeters: 380f,
VolumetricFogDensity: 0.0012f,
VolumetricFogDetailSpread: 2.2f,
VolumetricFogAnisotropy: 0.68f,
VolumetricFogEmissionEnergy: 0.22f,
VolumetricFogEmissionEnergy: 0f,
ValleyVolumeSize: new Vector3(1600f, 56f, 1600f),
ValleyVolumePosition: new Vector3(0f, 2f, 0f),
ValleyVolumeDensity: 0.0052f,
@ -138,7 +138,7 @@ public static class AtmosphereLutBaker
DepthFogAerialPerspective: 0.22f,
DepthFogSunScatter: 0.65f,
ShadowMaxDistance: 280f,
AmbientLightEnergy: 0.55f,
AmbientLightEnergy: 0.0f,
SunDiscIntensity: 8.0f,
MieAureoleStrength: 0.30f);

View file

@ -65,14 +65,24 @@ public partial class AtmosphereSystem : Node
{
BackgroundMode = Godot.Environment.BGMode.Sky,
Sky = _sky,
AmbientLightSource = Godot.Environment.AmbientSource.Sky,
AmbientLightEnergy = 0.48f,
AmbientLightSource = Godot.Environment.AmbientSource.Disabled,
AmbientLightEnergy = 0.0f,
// Option 1 (Low-Gamma): SDFGI multi-bounce + occlusion with zero flat ambient
SdfgiEnabled = true,
SdfgiUseOcclusion = true,
SdfgiReadSkyLight = true,
SdfgiBounceFeedback = 0.60f,
SdfgiCascades = 3,
SdfgiMinCellSize = 0.8f,
SdfgiYScale = Godot.Environment.SdfgiyScale.Scale75Percent,
SdfgiEnergy = 0.85f,
// AgX tonemapping preserves orange/amber combat hues while rolling off HDR emitters smoothly
TonemapMode = Godot.Environment.ToneMapper.Agx,
TonemapAgxWhite = 6.0f,
TonemapAgxContrast = 1.22f,
TonemapExposure = 1.0f,
TonemapAgxContrast = 1.50f,
TonemapExposure = 0.84f,
// Normalized additive bloom strictly above GlowHdrThreshold=1.0 (zero diffuse screen smear)
GlowEnabled = true,
@ -107,7 +117,7 @@ public partial class AtmosphereSystem : Node
VolumetricFogEnabled = true,
VolumetricFogTemporalReprojectionEnabled = true,
VolumetricFogTemporalReprojectionAmount = 0.88f,
VolumetricFogAmbientInject = 0.25f,
VolumetricFogAmbientInject = 0.0f,
VolumetricFogSkyAffect = 0.10f,
// Tier 2: Far aerial perspective (340/400m .. horizon peaks)
@ -139,6 +149,10 @@ public partial class AtmosphereSystem : Node
if (RenderingServer.GetRenderingDevice() is not null)
{
RenderingServer.GISetUseHalfResolution(true);
RenderingServer.EnvironmentSetSdfgiRayCount(RenderingServer.EnvironmentSdfgiRayCount.Count4);
RenderingServer.EnvironmentSetSdfgiFramesToConverge(RenderingServer.EnvironmentSdfgiFramesToConverge.In10Frames);
RenderingServer.EnvironmentSetSdfgiFramesToUpdateLight(RenderingServer.EnvironmentSdfgiFramesToUpdateLight.In8Frames);
_flowTexRd = new Texture3Drd();
RegisterGlobalParamIfMissing("rtd_flow_field", RenderingServer.GlobalShaderParameterType.Sampler3D, _flowTexRd);
_volumetricEffect = new VolumetricCompositorEffect(_flowTexRd, _emitterPool);
@ -196,6 +210,7 @@ public partial class AtmosphereSystem : Node
?? throw new InvalidOperationException("Failed to load res://film_grain.gdshader");
_filmGrainMat = new ShaderMaterial { Shader = grainShader };
_filmGrainMat.SetShaderParameter("grain_strength", 0.018f);
_filmGrainMat.SetShaderParameter("post_gamma", 1.32f);
_filmGrainLayer = new CanvasLayer
{
@ -249,9 +264,9 @@ public partial class AtmosphereSystem : Node
_env.VolumetricFogDensity = preset.VolumetricFogDensity;
_env.VolumetricFogDetailSpread = preset.VolumetricFogDetailSpread;
_env.VolumetricFogAnisotropy = preset.VolumetricFogAnisotropy;
_env.VolumetricFogEmissionEnergy = preset.VolumetricFogEmissionEnergy;
_env.VolumetricFogEmissionEnergy = 0f;
_env.VolumetricFogAlbedo = haze;
_env.VolumetricFogEmission = new Color(haze.R * 0.45f, haze.G * 0.45f, haze.B * 0.45f, 1.0f);
_env.VolumetricFogEmission = Colors.Black;
_valleyFog.Size = preset.ValleyVolumeSize;
_valleyFog.Position = preset.ValleyVolumePosition;
@ -259,7 +274,7 @@ public partial class AtmosphereSystem : Node
_valleyFogMat.HeightFalloff = preset.ValleyVolumeHeightFalloff;
_valleyFogMat.EdgeFade = preset.ValleyVolumeEdgeFade;
_valleyFogMat.Albedo = haze;
_valleyFogMat.Emission = new Color(haze.R * 0.35f, haze.G * 0.35f, haze.B * 0.35f, 1.0f);
_valleyFogMat.Emission = Colors.Black;
_env.FogLightColor = haze;
_env.FogDepthBegin = preset.DepthFogBegin;
@ -290,6 +305,31 @@ public partial class AtmosphereSystem : Node
_volumetricEffect?.SetEmitterPool(pool);
}
public void ApplyGraphicsSettings(GraphicsSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
EnsureInitialized();
_volumetricEffect?.ApplyGraphicsSettings(settings);
SdfgiSettingsConfig sdfgi = GraphicsSettings.GetSdfgiConfig(settings.SdfgiQuality);
_env.SdfgiEnabled = sdfgi.Enabled;
if (sdfgi.Enabled)
{
_env.SdfgiMinCellSize = sdfgi.MinCellSize;
_env.SdfgiCascades = sdfgi.Cascades;
}
if (RenderingServer.GetRenderingDevice() is not null)
{
RenderingServer.GISetUseHalfResolution(sdfgi.HalfResolution);
RenderingServer.EnvironmentSetSdfgiRayCount(
sdfgi.RayCount >= 8
? RenderingServer.EnvironmentSdfgiRayCount.Count8
: RenderingServer.EnvironmentSdfgiRayCount.Count4);
}
}
public override void _ExitTree()
{
if (_worldEnv is not null && GodotObject.IsInstanceValid(_worldEnv))

270
client/GraphicsSettings.cs Normal file
View file

@ -0,0 +1,270 @@
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace RustToDust.Client;
public enum VfxResolutionScale
{
Half = 0,
ThreeQuarter = 1,
Full = 2
}
public enum VolumetricSamples
{
Low = 0,
Medium = 1,
High = 2,
Ultra = 3
}
public enum SdfgiQuality
{
Off = 0,
Balanced = 1,
High = 2
}
public readonly record struct SdfgiSettingsConfig(
bool Enabled,
float MinCellSize,
int Cascades,
bool HalfResolution,
int RayCount);
public sealed record GraphicsSettingsData
{
[JsonPropertyName("vfxResolutionScale")]
public VfxResolutionScale VfxResolution { get; init; } = VfxResolutionScale.Half;
[JsonPropertyName("volumetricSamples")]
public VolumetricSamples VolumetricSamples { get; init; } = VolumetricSamples.Medium;
[JsonPropertyName("sdfgiQuality")]
public SdfgiQuality SdfgiQuality { get; init; } = SdfgiQuality.Balanced;
[JsonPropertyName("borderlessFullscreen")]
public bool BorderlessFullscreen { get; init; } = true;
}
/// <summary>
/// Single persisted authority for live graphics and display settings (<c>user://graphics_settings.json</c>).
/// Pure .NET so unit tests and headless runs share the exact same schema, defaults, and event flow.
/// </summary>
public sealed class GraphicsSettings
{
public const string DefaultFileName = "graphics_settings.json";
private static readonly JsonSerializerOptions JsonOptions = new()
{
WriteIndented = true,
PropertyNameCaseInsensitive = true,
Converters = { new JsonStringEnumConverter() }
};
private readonly string? _storagePath;
public GraphicsSettings(string? storagePath = null)
{
_storagePath = string.IsNullOrWhiteSpace(storagePath) ? null : storagePath;
ResetFieldsToDefaults();
}
public VfxResolutionScale VfxResolution { get; private set; }
public VolumetricSamples VolumetricSamples { get; private set; }
public SdfgiQuality SdfgiQuality { get; private set; }
public bool BorderlessFullscreen { get; private set; }
public string? StoragePath => _storagePath;
public event Action<GraphicsSettings>? Changed;
public GraphicsSettingsData ToData() => new()
{
VfxResolution = VfxResolution,
VolumetricSamples = VolumetricSamples,
SdfgiQuality = SdfgiQuality,
BorderlessFullscreen = BorderlessFullscreen
};
public static GraphicsSettings Load(string? storagePath)
{
var settings = new GraphicsSettings(storagePath);
if (string.IsNullOrWhiteSpace(storagePath))
{
return settings;
}
try
{
if (File.Exists(storagePath))
{
string json = File.ReadAllText(storagePath);
settings.LoadFromJson(json);
}
}
catch
{
settings.ResetFieldsToDefaults();
}
return settings;
}
public bool LoadFromJson(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
ResetFieldsToDefaults();
return false;
}
try
{
var parsed = JsonSerializer.Deserialize<GraphicsSettingsData>(json, JsonOptions);
if (parsed is null)
{
ResetFieldsToDefaults();
return false;
}
VfxResolution = Enum.IsDefined(parsed.VfxResolution)
? parsed.VfxResolution
: VfxResolutionScale.Half;
VolumetricSamples = Enum.IsDefined(parsed.VolumetricSamples)
? parsed.VolumetricSamples
: VolumetricSamples.Medium;
SdfgiQuality = Enum.IsDefined(parsed.SdfgiQuality)
? parsed.SdfgiQuality
: SdfgiQuality.Balanced;
BorderlessFullscreen = parsed.BorderlessFullscreen;
return true;
}
catch
{
ResetFieldsToDefaults();
return false;
}
}
public string ToJson() => JsonSerializer.Serialize(ToData(), JsonOptions);
public bool Save()
{
if (string.IsNullOrWhiteSpace(_storagePath))
{
return false;
}
try
{
string? dir = Path.GetDirectoryName(_storagePath);
if (!string.IsNullOrEmpty(dir))
{
Directory.CreateDirectory(dir);
}
string json = ToJson();
string tempPath = _storagePath + ".tmp";
File.WriteAllText(tempPath, json);
File.Move(tempPath, _storagePath, overwrite: true);
return true;
}
catch
{
return false;
}
}
public void Apply(
VfxResolutionScale vfxResolution,
VolumetricSamples volumetricSamples,
SdfgiQuality sdfgiQuality,
bool borderlessFullscreen,
bool persist = true,
bool forcePersist = false)
{
VfxResolutionScale safeRes = Enum.IsDefined(vfxResolution) ? vfxResolution : VfxResolutionScale.Half;
VolumetricSamples safeSamples = Enum.IsDefined(volumetricSamples) ? volumetricSamples : VolumetricSamples.Medium;
SdfgiQuality safeSdfgi = Enum.IsDefined(sdfgiQuality) ? sdfgiQuality : SdfgiQuality.Balanced;
bool changed = VfxResolution != safeRes
|| VolumetricSamples != safeSamples
|| SdfgiQuality != safeSdfgi
|| BorderlessFullscreen != borderlessFullscreen;
if (!changed)
{
if (persist && forcePersist)
{
Save();
}
return;
}
VfxResolution = safeRes;
VolumetricSamples = safeSamples;
SdfgiQuality = safeSdfgi;
BorderlessFullscreen = borderlessFullscreen;
if (persist)
{
Save();
}
Changed?.Invoke(this);
}
public void SetVfxResolution(VfxResolutionScale value, bool persist = true) =>
Apply(value, VolumetricSamples, SdfgiQuality, BorderlessFullscreen, persist);
public void SetVolumetricSamples(VolumetricSamples value, bool persist = true) =>
Apply(VfxResolution, value, SdfgiQuality, BorderlessFullscreen, persist);
public void SetSdfgiQuality(SdfgiQuality value, bool persist = true) =>
Apply(VfxResolution, VolumetricSamples, value, BorderlessFullscreen, persist);
public void SetBorderlessFullscreen(bool value, bool persist = true) =>
Apply(VfxResolution, VolumetricSamples, SdfgiQuality, value, persist);
public void ResetToDefaults(bool persist = true) =>
Apply(
VfxResolutionScale.Half,
VolumetricSamples.Medium,
SdfgiQuality.Balanced,
borderlessFullscreen: true,
persist: persist,
forcePersist: persist);
public static float GetResolutionScaleFactor(VfxResolutionScale scale) => scale switch
{
VfxResolutionScale.Half => 0.50f,
VfxResolutionScale.ThreeQuarter => 0.75f,
VfxResolutionScale.Full => 1.00f,
_ => 0.50f
};
public static (int MaxSteps, int MaxIter) GetVolumetricStepBudget(VolumetricSamples samples) => samples switch
{
VolumetricSamples.Low => (8, 12),
VolumetricSamples.Medium => (10, 15),
VolumetricSamples.High => (16, 24),
VolumetricSamples.Ultra => (24, 36),
_ => (10, 15)
};
public static SdfgiSettingsConfig GetSdfgiConfig(SdfgiQuality quality) => quality switch
{
SdfgiQuality.Off => new SdfgiSettingsConfig(false, 0.8f, 3, true, 4),
SdfgiQuality.Balanced => new SdfgiSettingsConfig(true, 0.8f, 3, true, 4),
SdfgiQuality.High => new SdfgiSettingsConfig(true, 0.4f, 4, false, 8),
_ => new SdfgiSettingsConfig(true, 0.8f, 3, true, 4)
};
private void ResetFieldsToDefaults()
{
VfxResolution = VfxResolutionScale.Half;
VolumetricSamples = VolumetricSamples.Medium;
SdfgiQuality = SdfgiQuality.Balanced;
BorderlessFullscreen = true;
}
}

View file

@ -17,7 +17,8 @@ public enum ClientScreenMode
ServerBrowser,
Lobby,
InMatch,
PauseOverlay
PauseOverlay,
Settings
}
/// <summary>
@ -38,12 +39,16 @@ public partial class Main : Node3D
private Hud _hud = null!;
private AtmosphereSystem _atmosphere = null!;
private MainMenu _mainMenu = null!;
private SettingsOverlay _settingsOverlay = null!;
private ServerBrowser _serverBrowser = null!;
private LobbyScreen _lobbyScreen = null!;
private GraphicsSettings _graphicsSettings = new();
private IClientArenaSession? _session;
private MatchState? _boundViewState;
private bool _wasNetConnected;
private ClientScreenMode _screenMode = ClientScreenMode.MainMenu;
private ClientScreenMode _settingsReturnMode = ClientScreenMode.MainMenu;
private bool _hasWindowOverride;
private DirectoryReporter? _directoryReporter;
private string _directoryUrl = ServerBrowser.DefaultDirectoryUrl;
private string _publicHostOverride = "auto";
@ -103,6 +108,7 @@ public partial class Main : Node3D
private readonly List<double> _perfNodeCount = new();
private readonly List<double> _perfTimeProcess = new();
private readonly List<double> _perfTimePhysicsProcess = new();
private readonly List<double> _perfViewportGpuMs = new();
private double _perfPendingStepMs;
private double _perfPendingTerrainMs;
private double _perfPendingArenaMs;
@ -121,6 +127,8 @@ public partial class Main : Node3D
public Hud Hud => _hud;
public AtmosphereSystem Atmosphere => _atmosphere;
public MainMenu MainMenuOverlay => _mainMenu;
public SettingsOverlay SettingsOverlay => _settingsOverlay;
public GraphicsSettings GraphicsSettings => _graphicsSettings;
public ServerBrowser ServerBrowserOverlay => _serverBrowser;
public LobbyScreen LobbyOverlay => _lobbyScreen;
public ArenaMapKind MapKind => _mapKind;
@ -138,9 +146,14 @@ public partial class Main : Node3D
{
ClientAssets.EnsureAssetsRootRegistered();
GetViewport().UseTaa = true;
_graphicsSettings = GraphicsSettings.Load(ResolveGraphicsSettingsPath());
ApplyGraphicsEnvOverrides(_graphicsSettings);
_graphicsSettings.Changed += OnGraphicsSettingsChanged;
_atmosphere = new AtmosphereSystem { Name = "AtmosphereSystem" };
AddChild(_atmosphere);
_atmosphere.EnsureInitialized();
_atmosphere.ApplyGraphicsSettings(_graphicsSettings);
_terrain = new TerrainRenderer { Name = "Terrain" };
AddChild(_terrain);
@ -190,8 +203,22 @@ public partial class Main : Node3D
}
};
_mainMenu.ReturnToMainMenuRequested += ReturnToMainMenu;
_mainMenu.SettingsRequested += OpenSettingsFromCurrentScreen;
AddChild(_mainMenu);
_settingsOverlay = new SettingsOverlay { Name = "SettingsOverlay" };
_settingsOverlay.SetGraphicsValues(
_graphicsSettings.VfxResolution,
_graphicsSettings.VolumetricSamples,
_graphicsSettings.SdfgiQuality,
_graphicsSettings.BorderlessFullscreen);
_settingsOverlay.GraphicsChanged += (res, samples, sdfgi, fullscreen) =>
_graphicsSettings.Apply(res, samples, sdfgi, fullscreen, persist: !IsAutomatedRun);
_settingsOverlay.ResetDefaultsRequested += () =>
_graphicsSettings.ResetToDefaults(persist: !IsAutomatedRun);
_settingsOverlay.BackRequested += CloseSettings;
AddChild(_settingsOverlay);
_serverBrowser = new ServerBrowser { Name = "ServerBrowser" };
_serverBrowser.JoinRequested += OnBrowserJoinRequested;
_serverBrowser.HostRequested += () =>
@ -327,16 +354,26 @@ public partial class Main : Node3D
}
_menuPreviewOut = System.Environment.GetEnvironmentVariable("RTD_MENU_PREVIEW_OUT");
bool hasWindowOverride = GetCliArg("--windowed", allowBareFlag: true) is not null
_hasWindowOverride = GetCliArg("--windowed", allowBareFlag: true) is not null
|| GetCliArg("--resolution", allowBareFlag: true) is not null
|| GetCliArg("-w", allowBareFlag: true) is not null;
if (!IsAutomatedRun && !hasWindowOverride)
if (!IsAutomatedRun && !_hasWindowOverride)
{
DisplayServer.WindowSetMode(DisplayServer.WindowMode.Fullscreen);
ApplyWindowMode(_graphicsSettings.BorderlessFullscreen);
}
else if (IsAutomatedRun && DisplayServer.GetName() != "headless")
else
{
DisplayServer.WindowSetFlag(DisplayServer.WindowFlags.NoFocus, true);
if (IsAutomatedRun && DisplayServer.GetName() != "headless")
{
DisplayServer.WindowSetFlag(DisplayServer.WindowFlags.NoFocus, true);
}
if (_hasWindowOverride && DisplayServer.GetName() != "headless")
{
var winMode = DisplayServer.WindowGetMode();
bool actualFullscreen = winMode == DisplayServer.WindowMode.Fullscreen
|| winMode == DisplayServer.WindowMode.ExclusiveFullscreen;
_graphicsSettings.SetBorderlessFullscreen(actualFullscreen, persist: false);
}
}
bool perfCombat = _perfTargetFrames > 0 && System.Environment.GetEnvironmentVariable("RTD_PERF_COMBAT") == "1";
@ -516,22 +553,27 @@ public partial class Main : Node3D
private void EnsureMenuSionBackdrop()
{
_menuSionData ??= SionMapLoader.Load();
_menuSionTerrain ??= TerrainField.LoadHeightmap(
_menuSionTerrain ??= TerrainField.LoadSharedHeightmap(
_menuSionData.Metadata.SizeMeters,
_menuSionData.Metadata.GridRes,
_menuSionData.Heights,
_menuSionData.Metadata.TileGrid,
_menuSionData.BaseDem,
_menuSionData.BaseDemMinY,
_menuSionData.BaseDemScale,
_menuSionData.Metadata.MinY,
_menuSionData.Metadata.MaxY,
42UL);
_terrain.Visible = false;
_terrain.Visible = true;
_sionMap.Visible = true;
_arena.Visible = false;
_dropReticleMesh.Visible = false;
_camera.Far = 4200f;
_atmosphere.ApplyMap(ArenaMapKind.Sion);
_sionMap.EnsureBuilt(_menuSionData, _menuSionTerrain);
_sionMap.EnsureBuilt(_menuSionData);
UpdateLobbyOrMenuOrbitCamera(ArenaMapKind.Sion, _menuSionTerrain);
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_menuSionTerrain, _menuSionData);
_sionMap.UpdateLod(_camera.GlobalPosition);
}
@ -561,6 +603,7 @@ public partial class Main : Node3D
case ClientScreenMode.MainMenu:
_hud.SetInputBlocked(true);
_hud.SetMatchHudActive(false);
_settingsOverlay.SetSettingsVisible(false);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.MainMenu);
@ -571,6 +614,7 @@ public partial class Main : Node3D
case ClientScreenMode.ServerBrowser:
_hud.SetInputBlocked(true);
_hud.SetMatchHudActive(false);
_settingsOverlay.SetSettingsVisible(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_lobbyScreen.SetLobbyVisible(false);
_serverBrowser.Configure(_directoryUrl, _callsign, _lastEndpoint);
@ -582,6 +626,7 @@ public partial class Main : Node3D
case ClientScreenMode.Lobby:
_hud.SetInputBlocked(true);
_hud.SetMatchHudActive(false);
_settingsOverlay.SetSettingsVisible(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(true);
@ -590,6 +635,7 @@ public partial class Main : Node3D
break;
case ClientScreenMode.InMatch:
_settingsOverlay.SetSettingsVisible(false);
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
@ -599,6 +645,7 @@ public partial class Main : Node3D
break;
case ClientScreenMode.PauseOverlay:
_settingsOverlay.SetSettingsVisible(false);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
_arena.Visible = true;
@ -607,6 +654,25 @@ public partial class Main : Node3D
_mainMenu.SetPauseContext(BuildPauseContextLine());
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.PauseOverlay);
break;
case ClientScreenMode.Settings:
_mainMenu.SetOverlayKind(MainMenu.OverlayKind.Hidden);
_serverBrowser.SetBrowserVisible(false);
_lobbyScreen.SetLobbyVisible(false);
bool showMatchBehind = _settingsReturnMode == ClientScreenMode.PauseOverlay;
_arena.Visible = showMatchBehind;
_hud.SetMatchHudActive(showMatchBehind);
if (!showMatchBehind)
{
_dropReticleMesh.Visible = false;
}
_settingsOverlay.SetGraphicsValues(
_graphicsSettings.VfxResolution,
_graphicsSettings.VolumetricSamples,
_graphicsSettings.SdfgiQuality,
_graphicsSettings.BorderlessFullscreen);
_settingsOverlay.SetSettingsVisible(true);
break;
}
SyncMouseMode();
}
@ -883,11 +949,15 @@ public partial class Main : Node3D
bool inLobby = _screenMode == ClientScreenMode.Lobby || state.Phase == MatchPhase.Lobby;
_terrain.Visible = true;
_terrain.InvalidateAll();
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(state.Terrain, state.SionMap);
if (_mapKind == ArenaMapKind.Sion && state.SionMap is not null)
{
_terrain.Visible = false;
_sionMap.Visible = true;
_sionMap.EnsureBuilt(state.SionMap, state.Terrain);
_sionMap.EnsureBuilt(state.SionMap);
if (!inLobby)
{
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
@ -897,14 +967,12 @@ public partial class Main : Node3D
{
UpdateLobbyOrMenuOrbitCamera(_mapKind, state.Terrain);
}
_terrain.UpdateTileLod(_camera.GlobalPosition);
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_sionMap.Visible = false;
_terrain.Visible = true;
_terrain.InvalidateAll();
_terrain.Sync(state.Terrain);
if (!inLobby)
{
_arena.Sync(_session, _elapsedSeconds, 0f, 1f);
@ -963,21 +1031,125 @@ public partial class Main : Node3D
}
}
private void ToggleBorderlessFullscreen()
private void OpenSettingsFromCurrentScreen()
{
if (_screenMode == ClientScreenMode.PauseOverlay || _screenMode == ClientScreenMode.MainMenu)
{
_settingsReturnMode = _screenMode;
}
SetScreenMode(ClientScreenMode.Settings);
}
private void CloseSettings()
{
if (_screenMode == ClientScreenMode.Settings)
{
SetScreenMode(_settingsReturnMode);
}
}
private void OnGraphicsSettingsChanged(GraphicsSettings settings)
{
_atmosphere.ApplyGraphicsSettings(settings);
_settingsOverlay?.SetGraphicsValues(
settings.VfxResolution,
settings.VolumetricSamples,
settings.SdfgiQuality,
settings.BorderlessFullscreen);
if (!IsAutomatedRun && DisplayServer.GetName() != "headless")
{
ApplyWindowMode(settings.BorderlessFullscreen);
}
}
private static string? ResolveGraphicsSettingsPath()
{
try
{
return ProjectSettings.GlobalizePath("user://" + GraphicsSettings.DefaultFileName);
}
catch
{
return null;
}
}
private static void ApplyGraphicsEnvOverrides(GraphicsSettings settings)
{
string? resEnv = System.Environment.GetEnvironmentVariable("RTD_VFX_RES");
if (!string.IsNullOrWhiteSpace(resEnv))
{
VfxResolutionScale? parsed = resEnv.Trim().ToLowerInvariant() switch
{
"half" or "0.5" or "0.5x" => VfxResolutionScale.Half,
"threequarter" or "three_quarter" or "high" or "0.75" or "0.75x" => VfxResolutionScale.ThreeQuarter,
"full" or "1.0" or "1.0x" or "native" => VfxResolutionScale.Full,
_ => null
};
if (parsed.HasValue)
{
settings.SetVfxResolution(parsed.Value, persist: false);
}
}
string? samplesEnv = System.Environment.GetEnvironmentVariable("RTD_VFX_SAMPLES");
if (!string.IsNullOrWhiteSpace(samplesEnv))
{
VolumetricSamples? parsed = samplesEnv.Trim().ToLowerInvariant() switch
{
"low" or "8" => VolumetricSamples.Low,
"medium" or "10" => VolumetricSamples.Medium,
"high" or "16" => VolumetricSamples.High,
"ultra" or "24" => VolumetricSamples.Ultra,
_ => null
};
if (parsed.HasValue)
{
settings.SetVolumetricSamples(parsed.Value, persist: false);
}
}
string? sdfgiEnv = System.Environment.GetEnvironmentVariable("RTD_SDFGI_QUALITY");
if (!string.IsNullOrWhiteSpace(sdfgiEnv))
{
SdfgiQuality? parsed = sdfgiEnv.Trim().ToLowerInvariant() switch
{
"off" => SdfgiQuality.Off,
"balanced" => SdfgiQuality.Balanced,
"high" => SdfgiQuality.High,
_ => null
};
if (parsed.HasValue)
{
settings.SetSdfgiQuality(parsed.Value, persist: false);
}
}
}
private static void ApplyWindowMode(bool borderlessFullscreen)
{
if (DisplayServer.GetName() == "headless")
{
return;
}
var current = DisplayServer.WindowGetMode();
bool isFullscreen = current == DisplayServer.WindowMode.Fullscreen || current == DisplayServer.WindowMode.ExclusiveFullscreen;
if (isFullscreen != borderlessFullscreen)
{
DisplayServer.WindowSetMode(borderlessFullscreen ? DisplayServer.WindowMode.Fullscreen : DisplayServer.WindowMode.Windowed);
}
}
private void ToggleBorderlessFullscreen()
{
if (IsAutomatedRun || DisplayServer.GetName() == "headless")
{
return;
}
var mode = DisplayServer.WindowGetMode();
if (mode == DisplayServer.WindowMode.Fullscreen || mode == DisplayServer.WindowMode.ExclusiveFullscreen)
{
DisplayServer.WindowSetMode(DisplayServer.WindowMode.Windowed);
}
else
{
DisplayServer.WindowSetMode(DisplayServer.WindowMode.Fullscreen);
}
bool nextFullscreen = !(mode == DisplayServer.WindowMode.Fullscreen || mode == DisplayServer.WindowMode.ExclusiveFullscreen);
DisplayServer.WindowSetMode(nextFullscreen ? DisplayServer.WindowMode.Fullscreen : DisplayServer.WindowMode.Windowed);
_graphicsSettings.SetBorderlessFullscreen(nextFullscreen, persist: !IsAutomatedRun);
}
private void SyncMouseMode()
@ -1159,6 +1331,14 @@ public partial class Main : Node3D
}
return;
}
if (_screenMode == ClientScreenMode.Settings)
{
if (key.Keycode == Key.Escape)
{
CloseSettings();
}
return;
}
if (key.Keycode == Key.F9)
{
@ -1350,19 +1530,13 @@ public partial class Main : Node3D
{
_frameEvents.Clear();
_session.DrainSimEvents(_frameEvents);
if (_mapKind == ArenaMapKind.Desert)
{
_terrain.Sync(_session.ViewState.Terrain);
}
UpdateLobbyOrMenuOrbitCamera(_mapKind, _session.ViewState.Terrain);
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
_lobbyScreen.Sync(_session);
return;
}
@ -1377,10 +1551,8 @@ public partial class Main : Node3D
}
double toMs = 1000.0 / Stopwatch.Frequency;
long tt0 = Stopwatch.GetTimestamp();
if (_mapKind == ArenaMapKind.Desert)
{
_terrain.Sync(_session.ViewState.Terrain);
}
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
long tt1 = Stopwatch.GetTimestamp();
_arena.Sync(_session, _elapsedSeconds, (float)delta, alpha);
DrainAndFanSimEvents((float)delta, alpha);
@ -1391,14 +1563,11 @@ public partial class Main : Node3D
long tc0 = Stopwatch.GetTimestamp();
UpdateCamera((float)delta, alpha);
_audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha);
_terrain.UpdateTileLod(_camera.GlobalPosition);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
long th0 = Stopwatch.GetTimestamp();
var localP = _session.LocalContender;
float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f;
@ -1431,6 +1600,10 @@ public partial class Main : Node3D
_perfNodeCount.Add(Performance.GetMonitor(Performance.Monitor.ObjectNodeCount));
_perfTimeProcess.Add(Performance.GetMonitor(Performance.Monitor.TimeProcess) * 1000.0);
_perfTimePhysicsProcess.Add(Performance.GetMonitor(Performance.Monitor.TimePhysicsProcess) * 1000.0);
if (ArenaSession.PerfEnabled)
{
_perfViewportGpuMs.Add(RenderingServer.ViewportGetMeasuredRenderTimeGpu(GetViewport().GetViewportRid()));
}
_perfFrameCount++;
if (_perfFrameCount >= _perfTargetFrames)
@ -1440,22 +1613,17 @@ public partial class Main : Node3D
}
else
{
if (_mapKind == ArenaMapKind.Desert)
{
_terrain.Sync(_session.ViewState.Terrain);
}
_terrain.UpdateTileLod(_camera.GlobalPosition);
_terrain.Sync(_session.ViewState.Terrain, _session.ViewState.SionMap);
_arena.Sync(_session, _elapsedSeconds, (float)delta, alpha);
DrainAndFanSimEvents((float)delta, alpha);
UpdateCamera((float)delta, alpha);
_audio.UpdateFrame(_session, _frameEvents, _frameFootsteps, _camera.GlobalPosition, (float)delta, alpha);
_terrain.UpdateTileLod(_camera.GlobalPosition);
if (_mapKind == ArenaMapKind.Sion)
{
_sionMap.UpdateLod(_camera.GlobalPosition);
}
else
{
_terrain.UpdateTileLod(_camera.GlobalPosition);
}
var localP = _session.LocalContender;
float coreRatio = localP.Grid.MaxCoreHp > 0f ? localP.Grid.CoreHp / localP.Grid.MaxCoreHp : 1f;
_hud.ConsumeEvents(_frameEvents, _session.LocalContenderId, coreRatio, localP.MaxThermalRatio);
@ -1529,7 +1697,7 @@ public partial class Main : Node3D
internal Color SampleCurrentMapGroundTint(float worldX, float worldZ) =>
_mapKind == ArenaMapKind.Sion
? _sionMap.SampleGroundTint(worldX, worldZ)
? _terrain.SampleGroundTint(worldX, worldZ)
: DesertDustTint;
private System.Numerics.Vector3? ResolveLiveWalkerFootWorld(bool isContender, int id, int legIndex)
@ -1586,7 +1754,7 @@ public partial class Main : Node3D
double steadyFps = steadyAvgMs > 0 ? 1000.0 / steadyAvgMs : 0;
GD.Print("=== PERF BENCHMARK SUMMARY ===");
GD.Print($"Frames={_perfFrameMs.Count} PhysicsTicks={_perfPhysicsTicks} AvgFPS={fps:F2} SteadyFPS(10..59)={steadyFps:F2} EngineFPS={Engine.GetFramesPerSecond():F1}");
GD.Print($"Frames={_perfFrameMs.Count} PhysicsTicks={_perfPhysicsTicks} AvgFPS={fps:F2} SteadyFPS(10..{_perfFrameMs.Count - 1})={steadyFps:F2} EngineFPS={Engine.GetFramesPerSecond():F1}");
GD.Print($"frameMs: avg={Avg(_perfFrameMs):F2} steadyAvg={steadyAvgMs:F2} p95={P95(_perfFrameMs):F2}");
GD.Print($"physicsStepMs/frame: avg={Avg(_perfPhysicsStepMs):F2} p95={P95(_perfPhysicsStepMs):F2}");
GD.Print($"terrainSyncMs/frame: avg={Avg(_perfTerrainSyncMs):F2} p95={P95(_perfTerrainSyncMs):F2} dirtyRebakesTotal={rebakeTotal} dirtyRebakesAvg={rebakeAvg:F2}");
@ -1607,7 +1775,17 @@ public partial class Main : Node3D
Rid vpRid = GetViewport().GetViewportRid();
double vpGpuMs = RenderingServer.ViewportGetMeasuredRenderTimeGpu(vpRid);
double vpCpuMs = RenderingServer.ViewportGetMeasuredRenderTimeCpu(vpRid);
GD.Print($"Cut10bGpuMs: total={volFx.LastTotalGpuMs:F3} flow={volFx.LastFlowGpuMs:F3} cull={volFx.LastCullGpuMs:F3} march={volFx.LastMarchGpuMs:F3} comp={volFx.LastCompGpuMs:F3} viewportGpuMs={vpGpuMs:F2} viewportCpuMs={vpCpuMs:F2}");
GD.Print($"Cut10bGpuMs: total={volFx.LastTotalGpuMs:F3} flow={volFx.LastFlowGpuMs:F3} cull={volFx.LastCullGpuMs:F3} march={volFx.LastMarchGpuMs:F3} comp={volFx.LastCompGpuMs:F3} marchSize={volFx.LastMarchSize.X}x{volFx.LastMarchSize.Y} maxSteps={volFx.CurrentMaxSteps} maxIter={volFx.CurrentMaxIter} vfxRes={_graphicsSettings.VfxResolution} volSamples={_graphicsSettings.VolumetricSamples} sdfgi={_graphicsSettings.SdfgiQuality} viewportGpuMs={vpGpuMs:F2} viewportCpuMs={vpCpuMs:F2}");
if (_perfViewportGpuMs.Count > 10)
{
var steadyGpu = new List<double>(_perfViewportGpuMs.Count - 10);
for (int i = 10; i < _perfViewportGpuMs.Count; i++) steadyGpu.Add(_perfViewportGpuMs[i]);
steadyGpu.Sort();
double gpuP50 = steadyGpu[(int)Math.Clamp(Math.Floor(steadyGpu.Count * 0.50), 0, steadyGpu.Count - 1)];
double gpuP95 = steadyGpu[(int)Math.Clamp(Math.Ceiling(steadyGpu.Count * 0.95) - 1, 0, steadyGpu.Count - 1)];
double gpuMax = steadyGpu[^1];
GD.Print($"viewportGpuMsTimeline(10..{_perfViewportGpuMs.Count - 1}): avg={Avg(steadyGpu):F2} p50={gpuP50:F2} p95={gpuP95:F2} max={gpuMax:F2}");
}
}
if (_hud?.HbCanvas is { } hb)
{
@ -1621,7 +1799,7 @@ public partial class Main : Node3D
}
if (_mapKind == ArenaMapKind.Sion)
{
GD.Print($"SionMap: chunks={_sionMap.TerrainChunkCount} tiles={_sionMap.BuildingTileCount} lod1={_sionMap.ActiveLod1TileCount} lod2={_sionMap.ActiveLod2TileCount} culled={_sionMap.CulledTileCount}");
GD.Print($"SionMap: terrainTiles={_terrain.BakedTileCount} gpuScarSlots={_terrain.ActiveGpuScarSlots} bldgTiles={_sionMap.BuildingTileCount} lod1={_sionMap.ActiveLod1TileCount} lod2={_sionMap.ActiveLod2TileCount} culled={_sionMap.CulledTileCount}");
}
foreach (var kv in _arena.AssetCache.Vehicles)
{
@ -2096,7 +2274,7 @@ public partial class Main : Node3D
var pt = new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z);
float distFromOrigin = origin.DistanceTo(pt);
if (hit.StableId < ContenderStableIdBase)
if (ArenaSession.IsStaticWorldStableId(hit.StableId))
{
if (distFromOrigin < hitDist)
{

View file

@ -51,6 +51,7 @@ public sealed partial class MainMenu : CanvasLayer
public event Action? QuitRequested;
public event Action? ResumeRequested;
public event Action? ReturnToMainMenuRequested;
public event Action? SettingsRequested;
public bool IsHostPanelOpen => _hostPanel is not null && _hostPanel.Visible;
public bool IsTextInputFocused =>
@ -256,6 +257,14 @@ public sealed partial class MainMenu : CanvasLayer
hostBtn.Pressed += () => SetHostPanelOpen(!IsHostPanelOpen);
vbox.AddChild(hostBtn);
var settingsBtn = ImperialChrome.CreateButton("SETTINGS", ImperialChrome.CyanCol, 14, 38f);
settingsBtn.Pressed += () =>
{
SetHostPanelOpen(false);
SettingsRequested?.Invoke();
};
vbox.AddChild(settingsBtn);
vbox.AddChild(ImperialChrome.MakeRule());
var quitBtn = ImperialChrome.CreateButton("QUIT", ImperialChrome.RedCol, 13, 34f);
@ -439,8 +448,8 @@ public sealed partial class MainMenu : CanvasLayer
panel.AnchorBottom = 0.5f;
panel.OffsetLeft = -190f;
panel.OffsetRight = 190f;
panel.OffsetTop = -132f;
panel.OffsetBottom = 132f;
panel.OffsetTop = -156f;
panel.OffsetBottom = 156f;
_pauseRoot.AddChild(panel);
var vbox = new VBoxContainer();
@ -457,6 +466,10 @@ public sealed partial class MainMenu : CanvasLayer
resumeBtn.Pressed += () => ResumeRequested?.Invoke();
vbox.AddChild(resumeBtn);
var settingsBtn = ImperialChrome.CreateButton("SETTINGS", ImperialChrome.CyanCol, 14, 36f);
settingsBtn.Pressed += () => SettingsRequested?.Invoke();
vbox.AddChild(settingsBtn);
var menuBtn = ImperialChrome.CreateButton("RETURN TO MAIN MENU", ImperialChrome.OrangeCol, 14, 36f);
menuBtn.Pressed += () => ReturnToMainMenuRequested?.Invoke();
vbox.AddChild(menuBtn);

407
client/SettingsOverlay.cs Normal file
View file

@ -0,0 +1,407 @@
using System;
using Godot;
namespace RustToDust.Client;
/// <summary>
/// Industrial Imperial Settings overlay with left-rail submenu navigation
/// (<b>GRAPHICS</b> active; Audio/Controls placeholders for future passes).
/// Decoupled from <see cref="GraphicsSettings"/> persistence: receives values via
/// <see cref="SetGraphicsValues"/> and emits change/reset/back events.
/// </summary>
public sealed partial class SettingsOverlay : CanvasLayer
{
public enum SettingsCategory
{
Graphics = 0
}
private Control _root = null!;
private ImperialChromePanel _panel = null!;
private Button _graphicsTabBtn = null!;
private Control _graphicsPane = null!;
private readonly Button[] _vfxResButtons = new Button[3];
private readonly Button[] _volSampleButtons = new Button[4];
private readonly Button[] _sdfgiButtons = new Button[3];
private readonly Button[] _displayModeButtons = new Button[2];
private VfxResolutionScale _vfxRes = VfxResolutionScale.Half;
private VolumetricSamples _volSamples = VolumetricSamples.Medium;
private SdfgiQuality _sdfgi = SdfgiQuality.Balanced;
private bool _borderlessFullscreen = true;
private bool _built;
public SettingsOverlay()
{
Layer = 22;
}
public event Action<VfxResolutionScale, VolumetricSamples, SdfgiQuality, bool>? GraphicsChanged;
public event Action? ResetDefaultsRequested;
public event Action? BackRequested;
public bool IsOpen => Visible;
public override void _Ready()
{
BuildUi();
SetSettingsVisible(false);
}
public void SetSettingsVisible(bool visible)
{
Visible = visible;
if (_root is not null)
{
_root.Visible = visible;
}
}
public void SetGraphicsValues(
VfxResolutionScale vfxRes,
VolumetricSamples volSamples,
SdfgiQuality sdfgi,
bool borderlessFullscreen)
{
_vfxRes = vfxRes;
_volSamples = volSamples;
_sdfgi = sdfgi;
_borderlessFullscreen = borderlessFullscreen;
if (_built)
{
RefreshSelectionVisuals();
}
}
private void BuildUi()
{
_root = new Control
{
Name = "SettingsOverlayRoot",
MouseFilter = Control.MouseFilterEnum.Stop
};
_root.SetAnchorsPreset(Control.LayoutPreset.FullRect);
AddChild(_root);
var scrim = new ColorRect
{
Color = ImperialChrome.ScrimCol,
MouseFilter = Control.MouseFilterEnum.Stop
};
scrim.SetAnchorsPreset(Control.LayoutPreset.FullRect);
_root.AddChild(scrim);
_panel = ImperialChrome.CreatePanel(
ImperialChrome.OrangeCol,
cornerLen: 18f,
borderPx: 2f,
bgAlpha: 0.94f,
padH: 22,
padV: 20);
_panel.Name = "SettingsPanel";
_panel.AnchorLeft = 0.5f;
_panel.AnchorRight = 0.5f;
_panel.AnchorTop = 0.5f;
_panel.AnchorBottom = 0.5f;
_panel.OffsetLeft = -440f;
_panel.OffsetRight = 440f;
_panel.OffsetTop = -255f;
_panel.OffsetBottom = 255f;
_root.AddChild(_panel);
var outerVbox = new VBoxContainer();
outerVbox.AddThemeConstantOverride("separation", 12);
_panel.AddChild(outerVbox);
// Header
var headerRow = new HBoxContainer();
headerRow.AddThemeConstantOverride("separation", 12);
outerVbox.AddChild(headerRow);
var titleCol = new VBoxContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill };
titleCol.AddThemeConstantOverride("separation", 2);
headerRow.AddChild(titleCol);
titleCol.AddChild(ImperialChrome.CreateLabel("SYSTEM CONFIGURATION • SUBMENU", 11, ImperialChrome.GoldCol));
titleCol.AddChild(ImperialChrome.CreateLabel("SETTINGS", 24, ImperialChrome.TextLight));
var liveBadge = ImperialChrome.CreateLabel("LIVE APPLY • NO RESTART", 11, ImperialChrome.CyanCol, HorizontalAlignment.Right);
liveBadge.VerticalAlignment = VerticalAlignment.Bottom;
headerRow.AddChild(liveBadge);
outerVbox.AddChild(ImperialChrome.MakeRule());
// Main Split: Submenu Rail + Content Pane
var split = new HBoxContainer
{
SizeFlagsVertical = Control.SizeFlags.ExpandFill
};
split.AddThemeConstantOverride("separation", 18);
outerVbox.AddChild(split);
var navCol = new VBoxContainer
{
CustomMinimumSize = new Vector2(168f, 0f)
};
navCol.AddThemeConstantOverride("separation", 8);
split.AddChild(navCol);
navCol.AddChild(ImperialChrome.CreateLabel("CATEGORIES", 10, ImperialChrome.TextMuted));
_graphicsTabBtn = ImperialChrome.CreateButton("GRAPHICS", ImperialChrome.CyanCol, 13, 38f);
StyleSegmentedButton(_graphicsTabBtn, selected: true, ImperialChrome.CyanCol);
_graphicsTabBtn.Pressed += () => SelectCategory(SettingsCategory.Graphics);
navCol.AddChild(_graphicsTabBtn);
var audioTabBtn = ImperialChrome.CreateButton("AUDIO [SOON]", ImperialChrome.BorderCol, 12, 34f);
audioTabBtn.Disabled = true;
audioTabBtn.TooltipText = "Audio controls arrive in a future pass";
navCol.AddChild(audioTabBtn);
var controlsTabBtn = ImperialChrome.CreateButton("CONTROLS [SOON]", ImperialChrome.BorderCol, 12, 34f);
controlsTabBtn.Disabled = true;
controlsTabBtn.TooltipText = "Input bindings arrive in a future pass";
navCol.AddChild(controlsTabBtn);
var vSep = new VSeparator();
vSep.AddThemeStyleboxOverride("separator", new StyleBoxLine
{
Color = new Color(ImperialChrome.BorderCol.R, ImperialChrome.BorderCol.G, ImperialChrome.BorderCol.B, 0.75f),
Thickness = 1,
Vertical = true
});
split.AddChild(vSep);
_graphicsPane = new VBoxContainer
{
Name = "GraphicsSettingsPane",
SizeFlagsHorizontal = Control.SizeFlags.ExpandFill,
SizeFlagsVertical = Control.SizeFlags.ExpandFill
};
((VBoxContainer)_graphicsPane).AddThemeConstantOverride("separation", 12);
split.AddChild(_graphicsPane);
_graphicsPane.AddChild(ImperialChrome.CreateLabel("GRAPHICS • VOLUMETRICS, GI & DISPLAY", 14, ImperialChrome.CyanCol));
// 1. VFX / Fog Resolution
AddSettingRow(
_graphicsPane,
"VFX / FOG RESOLUTION",
"Compute resolution for raymarched smoke, fireballs & plumes (Full = 1:1 native)",
new[]
{
("Half (0.5x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.Half))),
("High (0.75x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.ThreeQuarter))),
("Full (1.0x)", (Action)(() => OnGraphicsOptionSelected(vfxRes: VfxResolutionScale.Full)))
},
_vfxResButtons);
// 2. Volumetric Sample Count
AddSettingRow(
_graphicsPane,
"VOLUMETRIC SAMPLE COUNT",
"Raymarch step budget per pixel (higher = smoother volume density & gradients)",
new[]
{
("Low (8)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Low))),
("Medium (10)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Medium))),
("High (16)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.High))),
("Ultra (24)", (Action)(() => OnGraphicsOptionSelected(volSamples: VolumetricSamples.Ultra)))
},
_volSampleButtons);
// 3. Global Illumination (SDFGI)
AddSettingRow(
_graphicsPane,
"GLOBAL ILLUMINATION (SDFGI)",
"Signed-distance multi-bounce sky & terrain indirect lighting",
new[]
{
("Off", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.Off))),
("Balanced", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.Balanced))),
("High", (Action)(() => OnGraphicsOptionSelected(sdfgi: SdfgiQuality.High)))
},
_sdfgiButtons);
// 4. Display Mode
AddSettingRow(
_graphicsPane,
"DISPLAY MODE",
"Window presentation mode (also toggleable anytime via Alt+Enter or F11)",
new[]
{
("Borderless Fullscreen", (Action)(() => OnGraphicsOptionSelected(borderlessFullscreen: true))),
("Windowed", (Action)(() => OnGraphicsOptionSelected(borderlessFullscreen: false)))
},
_displayModeButtons);
outerVbox.AddChild(ImperialChrome.MakeRule());
// Footer
var footerRow = new HBoxContainer();
footerRow.AddThemeConstantOverride("separation", 10);
outerVbox.AddChild(footerRow);
var resetBtn = ImperialChrome.CreateButton("RESET DEFAULTS", ImperialChrome.GoldCol, 13, 36f);
resetBtn.CustomMinimumSize = new Vector2(180f, 36f);
resetBtn.Pressed += () => ResetDefaultsRequested?.Invoke();
footerRow.AddChild(resetBtn);
footerRow.AddChild(new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill });
var backBtn = ImperialChrome.CreateButton("BACK [ESC]", ImperialChrome.OrangeCol, 13, 36f);
backBtn.CustomMinimumSize = new Vector2(160f, 36f);
backBtn.Pressed += () => BackRequested?.Invoke();
footerRow.AddChild(backBtn);
_built = true;
RefreshSelectionVisuals();
}
private static void AddSettingRow(
Control parent,
string labelText,
string hintText,
(string Text, Action OnSelect)[] options,
Button[] targetButtons)
{
var block = new VBoxContainer();
block.AddThemeConstantOverride("separation", 4);
parent.AddChild(block);
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 12);
block.AddChild(row);
var lbl = ImperialChrome.CreateLabel(labelText, 12, ImperialChrome.TextLight);
lbl.CustomMinimumSize = new Vector2(228f, 0f);
lbl.VerticalAlignment = VerticalAlignment.Center;
row.AddChild(lbl);
var btnGroup = new HBoxContainer
{
SizeFlagsHorizontal = Control.SizeFlags.ExpandFill
};
btnGroup.AddThemeConstantOverride("separation", 6);
row.AddChild(btnGroup);
for (int i = 0; i < options.Length; i++)
{
var (text, onSelect) = options[i];
var btn = ImperialChrome.CreateButton(text, ImperialChrome.CyanCol, 12, 32f);
btn.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill;
btn.Pressed += onSelect;
btnGroup.AddChild(btn);
targetButtons[i] = btn;
}
var hint = ImperialChrome.CreateLabel(hintText, 10, ImperialChrome.TextMuted);
block.AddChild(hint);
}
private void SelectCategory(SettingsCategory category)
{
if (category == SettingsCategory.Graphics && _graphicsPane is not null)
{
_graphicsPane.Visible = true;
}
}
private void OnGraphicsOptionSelected(
VfxResolutionScale? vfxRes = null,
VolumetricSamples? volSamples = null,
SdfgiQuality? sdfgi = null,
bool? borderlessFullscreen = null)
{
VfxResolutionScale nextRes = vfxRes ?? _vfxRes;
VolumetricSamples nextSamples = volSamples ?? _volSamples;
SdfgiQuality nextSdfgi = sdfgi ?? _sdfgi;
bool nextFullscreen = borderlessFullscreen ?? _borderlessFullscreen;
if (nextRes == _vfxRes
&& nextSamples == _volSamples
&& nextSdfgi == _sdfgi
&& nextFullscreen == _borderlessFullscreen)
{
return;
}
_vfxRes = nextRes;
_volSamples = nextSamples;
_sdfgi = nextSdfgi;
_borderlessFullscreen = nextFullscreen;
RefreshSelectionVisuals();
GraphicsChanged?.Invoke(_vfxRes, _volSamples, _sdfgi, _borderlessFullscreen);
}
private void RefreshSelectionVisuals()
{
for (int i = 0; i < _vfxResButtons.Length; i++)
{
StyleSegmentedButton(_vfxResButtons[i], i == (int)_vfxRes, ImperialChrome.CyanCol);
}
for (int i = 0; i < _volSampleButtons.Length; i++)
{
StyleSegmentedButton(_volSampleButtons[i], i == (int)_volSamples, ImperialChrome.CyanCol);
}
for (int i = 0; i < _sdfgiButtons.Length; i++)
{
StyleSegmentedButton(_sdfgiButtons[i], i == (int)_sdfgi, ImperialChrome.OliveCol);
}
StyleSegmentedButton(_displayModeButtons[0], _borderlessFullscreen, ImperialChrome.OrangeCol);
StyleSegmentedButton(_displayModeButtons[1], !_borderlessFullscreen, ImperialChrome.OrangeCol);
}
private static void StyleSegmentedButton(Button btn, bool selected, Color accentColor)
{
if (selected)
{
btn.AddThemeFontSizeOverride("font_size", 12);
btn.AddThemeColorOverride("font_color", Colors.White);
btn.AddThemeColorOverride("font_hover_color", Colors.White);
btn.AddThemeColorOverride("font_pressed_color", accentColor);
var activeBox = MakeSegmentBox(
new Color(accentColor.R * 0.24f + ImperialChrome.BgPressed.R * 0.76f,
accentColor.G * 0.24f + ImperialChrome.BgPressed.G * 0.76f,
accentColor.B * 0.24f + ImperialChrome.BgPressed.B * 0.76f,
1f),
accentColor,
borderW: 2);
btn.AddThemeStyleboxOverride("normal", activeBox);
btn.AddThemeStyleboxOverride("hover", activeBox);
btn.AddThemeStyleboxOverride("pressed", activeBox);
btn.AddThemeStyleboxOverride("focus", activeBox);
}
else
{
btn.AddThemeFontSizeOverride("font_size", 12);
btn.AddThemeColorOverride("font_color", ImperialChrome.TextMuted);
btn.AddThemeColorOverride("font_hover_color", ImperialChrome.TextLight);
btn.AddThemeColorOverride("font_pressed_color", accentColor);
var normal = MakeSegmentBox(ImperialChrome.BgInner, ImperialChrome.BorderCol, borderW: 1);
var hover = MakeSegmentBox(ImperialChrome.BgHover, new Color(accentColor.R, accentColor.G, accentColor.B, 0.75f), borderW: 1);
var pressed = MakeSegmentBox(ImperialChrome.BgPressed, accentColor, borderW: 2);
btn.AddThemeStyleboxOverride("normal", normal);
btn.AddThemeStyleboxOverride("hover", hover);
btn.AddThemeStyleboxOverride("pressed", pressed);
btn.AddThemeStyleboxOverride("focus", hover);
}
}
private static StyleBoxFlat MakeSegmentBox(Color bg, Color border, int borderW)
{
var box = new StyleBoxFlat
{
BgColor = bg,
BorderColor = border,
ContentMarginLeft = 8,
ContentMarginRight = 8,
ContentMarginTop = 5,
ContentMarginBottom = 5
};
box.SetBorderWidthAll(borderW);
return box;
}
}

View file

@ -7,17 +7,15 @@ using RustToDust.Core;
namespace RustToDust.Client;
/// <summary>
/// Renders the 3072m x 3072m Sion, Switzerland arena:
/// - 6x6 (512m) seam-free chunked terrain ArrayMeshes from heightmap.f32 textured with terrain_surface.png + micro-grain shader.
/// - 36 spatial building tiles swapping cleanly between LOD1 (&lt;= 650m), LOD2 (650m..2200m), and culled (&gt; 2200m),
/// with shadow casting restricted to &lt;= 450m and shared PBR materials across all tiles.
/// Renders Sion, Switzerland legacy building tiles (swapping cleanly between LOD1 &lt;= 520m, LOD2 520..2200m,
/// and culled &gt; 2200m). Terrain rendering is unified in <see cref="TerrainRenderer"/>.
/// (This class is scheduled for deletion in Cut 13c when <c>WorldCityRenderer</c> lands.)
/// </summary>
public partial class SionMapRenderer : Node3D
{
public const float Lod1DistanceM = 520f;
public const float CullDistanceM = 2200f;
public const float ShadowDistanceM = 360f;
private const int ChunkGridVerts = 129; // 128 quads per 512m chunk (4m spacing)
public const float Lod1DistanceM = 400f;
public const float CullDistanceM = 1750f;
public const float ShadowDistanceM = 280f;
private sealed class BuildingTileEntry
{
@ -30,26 +28,17 @@ public partial class SionMapRenderer : Node3D
public required MeshInstance3D Instance;
}
private const int GroundTintGridSize = 128;
private static readonly Color NeutralAlpineDustTint = new(0.56f, 0.53f, 0.46f, 1.0f);
private readonly List<MeshInstance3D> _terrainChunks = new(36);
private readonly List<BuildingTileEntry> _buildingTiles = new(36);
private readonly Dictionary<string, StandardMaterial3D> _sharedBuildingMaterials = new(StringComparer.Ordinal);
private string? _builtForDir;
private ShaderMaterial? _terrainMat;
private ImageTexture? _surfaceTex;
private Color[]? _groundTintGrid;
private float _groundTintSizeM;
public bool IsBuilt { get; private set; }
public int TerrainChunkCount => _terrainChunks.Count;
public int BuildingTileCount => _buildingTiles.Count;
public int ActiveLod1TileCount { get; private set; }
public int ActiveLod2TileCount { get; private set; }
public int CulledTileCount { get; private set; }
public void EnsureBuilt(SionMapData sion, TerrainField terrain)
public void EnsureBuilt(SionMapData sion)
{
if (IsBuilt && string.Equals(_builtForDir, sion.DirectoryPath, StringComparison.OrdinalIgnoreCase))
{
@ -58,9 +47,6 @@ public partial class SionMapRenderer : Node3D
ClearBuilt();
_builtForDir = sion.DirectoryPath;
BuildTerrainMaterial(sion);
BuildTerrainChunks(sion, terrain);
BuildBuildingTiles(sion);
IsBuilt = true;
}
@ -124,186 +110,6 @@ public partial class SionMapRenderer : Node3D
CulledTileCount = culledCount;
}
private void BuildTerrainMaterial(SionMapData sion)
{
string surfPath = Path.Combine(sion.DirectoryPath, sion.Metadata.SurfaceTexture);
if (!File.Exists(surfPath))
{
throw new FileNotFoundException($"Missing Sion terrain surface texture: {surfPath}", surfPath);
}
var img = Image.LoadFromFile(surfPath);
if (img is null || img.IsEmpty())
{
throw new InvalidOperationException($"Failed to decode Sion terrain surface texture: {surfPath}");
}
// Downsample CPU copy once for zero-readback terrain-tinted dust & impact plumes
var tintImg = (Image)img.Duplicate();
tintImg.Resize(GroundTintGridSize, GroundTintGridSize, Image.Interpolation.Bilinear);
var grid = new Color[GroundTintGridSize * GroundTintGridSize];
for (int y = 0; y < GroundTintGridSize; y++)
{
for (int x = 0; x < GroundTintGridSize; x++)
{
Color c = tintImg.GetPixel(x, y);
grid[y * GroundTintGridSize + x] = new Color(
Math.Clamp(c.R + 0.11f, 0.20f, 0.90f),
Math.Clamp(c.G + 0.11f, 0.20f, 0.88f),
Math.Clamp(c.B + 0.10f, 0.18f, 0.84f),
1.0f);
}
}
_groundTintGrid = grid;
_groundTintSizeM = sion.Metadata.SizeMeters;
img.GenerateMipmaps();
_surfaceTex = ImageTexture.CreateFromImage(img);
var shader = new Shader
{
Code = """
shader_type spatial;
render_mode cull_back, depth_draw_opaque;
uniform sampler2D surface_tex : source_color, filter_linear_mipmap, repeat_disable;
varying vec3 v_world_pos;
varying vec3 v_world_normal;
float hash21(vec2 p) {
p = fract(p * vec2(123.34, 456.21));
p += dot(p, p + 45.32);
return fract(p.x * p.y);
}
float value_noise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
float a = hash21(i);
float b = hash21(i + vec2(1.0, 0.0));
float c = hash21(i + vec2(0.0, 1.0));
float d = hash21(i + vec2(1.0, 1.0));
return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}
void vertex() {
v_world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
v_world_normal = normalize((MODEL_MATRIX * vec4(NORMAL, 0.0)).xyz);
}
void fragment() {
vec3 base_col = texture(surface_tex, UV).rgb;
// Crisp world-space micro-grain for up-close ground readability
float dist = length((INV_VIEW_MATRIX * vec4(0.0, 0.0, 0.0, 1.0)).xyz - v_world_pos);
float near_fade = clamp(1.0 - smoothstep(140.0, 480.0, dist), 0.12, 1.0);
float macro = (value_noise(v_world_pos.xz * 0.28) - 0.5) * 0.07;
float grit = (hash21(floor(v_world_pos.xz * 8.0)) - 0.5) * 0.045;
float slope = 1.0 - clamp(v_world_normal.y, 0.0, 1.0);
vec3 col = clamp(base_col * (1.0 + macro * 1.4 + grit * 1.6 * near_fade), vec3(0.0), vec3(1.0));
ALBEDO = col;
ROUGHNESS = mix(0.88, 0.96, slope);
METALLIC = 0.02;
}
"""
};
_terrainMat = new ShaderMaterial { Shader = shader };
_terrainMat.SetShaderParameter("surface_tex", _surfaceTex);
}
private void BuildTerrainChunks(SionMapData sion, TerrainField terrain)
{
int grid = sion.Metadata.TileGrid;
float sizeM = sion.Metadata.SizeMeters;
float tileSize = sion.Metadata.TileSizeMeters;
float half = sizeM * 0.5f;
int n = ChunkGridVerts;
float step = tileSize / (n - 1);
// Precompute shared index buffer for every terrain chunk (Godot ArrayMesh cull_back uses CW front-facing winding)
int quadCount = (n - 1) * (n - 1);
var indices = new int[quadCount * 6];
int ii = 0;
for (int gz = 0; gz < n - 1; gz++)
{
for (int gx = 0; gx < n - 1; gx++)
{
int i00 = gz * n + gx;
int i10 = i00 + 1;
int i01 = i00 + n;
int i11 = i01 + 1;
indices[ii++] = i00;
indices[ii++] = i10;
indices[ii++] = i01;
indices[ii++] = i10;
indices[ii++] = i11;
indices[ii++] = i01;
}
}
int vertCount = n * n;
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
float x0 = -half + tx * tileSize;
float z0 = -half + tz * tileSize;
float cx = x0 + tileSize * 0.5f;
float cz = z0 + tileSize * 0.5f;
var verts = new Vector3[vertCount];
var normals = new Vector3[vertCount];
var uvs = new Vector2[vertCount];
for (int gz = 0; gz < n; gz++)
{
float wz = z0 + gz * step;
float lx = 0f;
float lz = wz - cz;
float v = (wz + half) / sizeM;
for (int gx = 0; gx < n; gx++)
{
float wx = x0 + gx * step;
lx = wx - cx;
float h = terrain.SampleHeight(wx, wz);
var (nx, ny, nz) = terrain.SampleNormal(wx, wz);
int idx = gz * n + gx;
verts[idx] = new Vector3(lx, h, lz);
normals[idx] = new Vector3(nx, ny, nz);
uvs[idx] = new Vector2((wx + half) / sizeM, v);
}
}
var arrays = new Godot.Collections.Array();
arrays.Resize((int)Mesh.ArrayType.Max);
arrays[(int)Mesh.ArrayType.Vertex] = verts;
arrays[(int)Mesh.ArrayType.Normal] = normals;
arrays[(int)Mesh.ArrayType.TexUV] = uvs;
arrays[(int)Mesh.ArrayType.Index] = indices;
var mesh = new ArrayMesh();
mesh.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays);
var chunkNode = new MeshInstance3D
{
Name = $"SionTerrain_{tx}_{tz}",
Mesh = mesh,
MaterialOverride = _terrainMat,
Position = new Vector3(cx, 0f, cz),
CastShadow = GeometryInstance3D.ShadowCastingSetting.On
};
AddChild(chunkNode);
_terrainChunks.Add(chunkNode);
}
}
}
private void BuildBuildingTiles(SionMapData sion)
{
var tiles = sion.Metadata.Tiles;
@ -498,47 +304,8 @@ public partial class SionMapRenderer : Node3D
return (defaultKey, defMat);
}
public Color SampleGroundTint(float worldX, float worldZ)
{
Color[]? grid = _groundTintGrid;
float sizeM = _groundTintSizeM;
if (grid is null || sizeM <= 1f || !float.IsFinite(worldX) || !float.IsFinite(worldZ))
{
return NeutralAlpineDustTint;
}
float half = sizeM * 0.5f;
float u = (worldX + half) / sizeM;
float v = (worldZ + half) / sizeM;
if (u < 0f || u > 1f || v < 0f || v > 1f)
{
return NeutralAlpineDustTint;
}
float fx = u * (GroundTintGridSize - 1);
float fy = v * (GroundTintGridSize - 1);
int x0 = Math.Clamp((int)MathF.Floor(fx), 0, GroundTintGridSize - 1);
int y0 = Math.Clamp((int)MathF.Floor(fy), 0, GroundTintGridSize - 1);
int x1 = Math.Min(x0 + 1, GroundTintGridSize - 1);
int y1 = Math.Min(y0 + 1, GroundTintGridSize - 1);
float tx = fx - x0;
float ty = fy - y0;
Color c00 = grid[y0 * GroundTintGridSize + x0];
Color c10 = grid[y0 * GroundTintGridSize + x1];
Color c01 = grid[y1 * GroundTintGridSize + x0];
Color c11 = grid[y1 * GroundTintGridSize + x1];
return c00.Lerp(c10, tx).Lerp(c01.Lerp(c11, tx), ty);
}
private void ClearBuilt()
{
for (int i = 0; i < _terrainChunks.Count; i++)
{
_terrainChunks[i].QueueFree();
}
_terrainChunks.Clear();
for (int i = 0; i < _buildingTiles.Count; i++)
{
_buildingTiles[i].Instance.QueueFree();
@ -546,10 +313,6 @@ public partial class SionMapRenderer : Node3D
_buildingTiles.Clear();
_sharedBuildingMaterials.Clear();
_terrainMat = null;
_surfaceTex = null;
_groundTintGrid = null;
_groundTintSizeM = 0f;
_builtForDir = null;
IsBuilt = false;
ActiveLod1TileCount = 0;

File diff suppressed because it is too large Load diff

View file

@ -19,7 +19,7 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect
public const float FlowVoxelSizeMeters = 3.0f;
public const int TileSizeHalfRes = 16;
public const int TileStrideBytes = 112;
public const int FrameUboBytes = 256;
public const int FrameUboBytes = 272;
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct VolumetricFrameUbo
@ -37,6 +37,7 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect
public Vector4 FlowOriginVoxel;
public Vector4 FlowInvExtentDt;
public int DeltaX, DeltaY, DeltaZ, ImpulseCount;
public uint MaxSteps, MaxIter, IsFullRes, QualityPad;
}
private readonly Texture3Drd _flowTexRd;
@ -49,6 +50,8 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect
private Color _sunColor = Colors.White;
private Color _ambientColor = new(0.28f, 0.34f, 0.42f);
private float _globalExtinctionScale = 0.28f;
private VfxResolutionScale _resolutionScale = VfxResolutionScale.Half;
private VolumetricSamples _volumetricSamples = VolumetricSamples.Medium;
// Render-thread RD state
private RenderingDevice? _rd;
@ -90,6 +93,9 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect
public double LastMarchGpuMs { get; private set; }
public double LastCompGpuMs { get; private set; }
public double LastTotalGpuMs => LastFlowGpuMs + LastCullGpuMs + LastMarchGpuMs + LastCompGpuMs;
public Vector2I LastMarchSize { get; private set; }
public int CurrentMaxSteps { get; private set; } = 10;
public int CurrentMaxIter { get; private set; } = 15;
public VolumetricCompositorEffect() : this(new Texture3Drd(), new VolumetricEmitterPool())
{
@ -110,6 +116,16 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect
_emitterPool = pool ?? throw new ArgumentNullException(nameof(pool));
}
public void ApplyGraphicsSettings(GraphicsSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
lock (_atmoLock)
{
_resolutionScale = settings.VfxResolution;
_volumetricSamples = settings.VolumetricSamples;
}
}
public void SetAtmosphere(Vector3 sunDir, float sunEnergy, Color sunColor, Color ambientColor, float extinctionScale = 0.28f)
{
lock (_atmoLock)
@ -158,12 +174,40 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect
return;
}
Vector2I halfSize = new(Math.Max(1, (fullSize.X + 1) / 2), Math.Max(1, (fullSize.Y + 1) / 2));
int tilesX = Math.Max(1, (halfSize.X + TileSizeHalfRes - 1) / TileSizeHalfRes);
int tilesY = Math.Max(1, (halfSize.Y + TileSizeHalfRes - 1) / TileSizeHalfRes);
int totalTiles = tilesX * tilesY;
VfxResolutionScale resScale;
VolumetricSamples volSamples;
Vector3 sunDir;
float sunEnergy;
Color sunCol, ambCol;
float extScale;
lock (_atmoLock)
{
resScale = _resolutionScale;
volSamples = _volumetricSamples;
sunDir = _sunDir;
sunEnergy = _sunEnergy;
sunCol = _sunColor;
ambCol = _ambientColor;
extScale = _globalExtinctionScale;
}
EnsureHalfResAndTileBuffers(rd, halfSize, totalTiles);
bool isFullRes = resScale == VfxResolutionScale.Full;
float resFactor = GraphicsSettings.GetResolutionScaleFactor(resScale);
Vector2I marchSize = isFullRes
? fullSize
: new Vector2I(
Math.Max(1, (int)MathF.Round(fullSize.X * resFactor)),
Math.Max(1, (int)MathF.Round(fullSize.Y * resFactor)));
int tilesX = Math.Max(1, (marchSize.X + TileSizeHalfRes - 1) / TileSizeHalfRes);
int tilesY = Math.Max(1, (marchSize.Y + TileSizeHalfRes - 1) / TileSizeHalfRes);
int totalTiles = tilesX * tilesY;
(int maxSteps, int maxIter) = GraphicsSettings.GetVolumetricStepBudget(volSamples);
LastMarchSize = marchSize;
CurrentMaxSteps = maxSteps;
CurrentMaxIter = maxIter;
EnsureHalfResAndTileBuffers(rd, marchSize, totalTiles);
uint viewCount = Math.Max(1u, sceneData.GetViewCount());
const uint view = 0u;
@ -218,19 +262,6 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect
1f / (FlowDimY * FlowVoxelSizeMeters),
1f / (FlowDimZ * FlowVoxelSizeMeters));
Vector3 sunDir;
float sunEnergy;
Color sunCol, ambCol;
float extScale;
lock (_atmoLock)
{
sunDir = _sunDir;
sunEnergy = _sunEnergy;
sunCol = _sunColor;
ambCol = _ambientColor;
extScale = _globalExtinctionScale;
}
_frameCounter++;
var ubo = new VolumetricFrameUbo
{
@ -246,8 +277,8 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect
SunColorExt = new Vector4(sunCol.R, sunCol.G, sunCol.B, extScale),
AmbientColorFog = new Vector4(ambCol.R, ambCol.G, ambCol.B, zNear),
ViewportInfo = new Vector4(fullSize.X, fullSize.Y, zFar, emitterCount),
HalfW = (uint)halfSize.X,
HalfH = (uint)halfSize.Y,
HalfW = (uint)marchSize.X,
HalfH = (uint)marchSize.Y,
TilesX = (uint)tilesX,
FrameIndex = _frameCounter,
FlowOriginVoxel = new Vector4(flowOriginWorld.X, flowOriginWorld.Y, flowOriginWorld.Z, FlowVoxelSizeMeters),
@ -255,7 +286,11 @@ public sealed partial class VolumetricCompositorEffect : CompositorEffect
DeltaX = flowDelta.X,
DeltaY = flowDelta.Y,
DeltaZ = flowDelta.Z,
ImpulseCount = impulseCount
ImpulseCount = impulseCount,
MaxSteps = (uint)maxSteps,
MaxIter = (uint)maxIter,
IsFullRes = isFullRes ? 1u : 0u,
QualityPad = 0u
};
MemoryMarshal.Write(_uboBytes, in ubo);

View file

@ -6,6 +6,7 @@ render_mode blend_mix;
uniform sampler2D screen_tex : hint_screen_texture, filter_nearest;
uniform float grain_strength : hint_range(0.0, 0.1) = 0.018;
uniform float post_gamma : hint_range(0.5, 2.5) = 1.32;
float interleaved_gradient_noise(vec2 frag_xy, float frame_idx) {
vec2 p = frag_xy + vec2(frame_idx * 17.0, frame_idx * 31.0);
@ -14,12 +15,13 @@ float interleaved_gradient_noise(vec2 frag_xy, float frame_idx) {
void fragment() {
vec4 src = texture(screen_tex, SCREEN_UV);
vec3 graded = pow(max(src.rgb, vec3(0.0)), vec3(post_gamma));
float frame_idx = mod(floor(fract(TIME * 0.001) * 60000.0), 64.0);
float n = interleaved_gradient_noise(FRAGCOORD.xy, frame_idx);
float luma = dot(src.rgb, vec3(0.2126, 0.7152, 0.0722));
float luma = dot(graded, vec3(0.2126, 0.7152, 0.0722));
float midtone_weight = smoothstep(0.02, 0.18, luma) * (1.0 - 0.65 * smoothstep(0.65, 1.0, luma));
vec3 grained = clamp(src.rgb + vec3((n - 0.5) * 2.0 * grain_strength * midtone_weight), vec3(0.0), vec3(1.0));
vec3 grained = clamp(graded + vec3((n - 0.5) * 2.0 * grain_strength * midtone_weight), vec3(0.0), vec3(1.0));
COLOR = vec4(grained, src.a);
}

View file

@ -22,6 +22,7 @@ layout(set = 0, binding = 0, std140) uniform VolumetricFrame {
vec4 flowOriginVoxel;
vec4 flowInvExtentDt;
ivec4 flowDeltaImpulse;
uvec4 qualityParams;
} u_frame;
layout(set = 0, binding = 1, std430) readonly buffer FlowImpulseBuffer {

View file

@ -1,67 +0,0 @@
shader_type canvas_item;
render_mode blend_add;
// Encodes positive height deltas into R ([-18m, +52m] => span 70m),
// roughness delta into G, scorch/track wear into B, and ALWAYS A = 1.0
// (required for TransparentBg=false UseHdr2D=true blend equations in forward_plus).
uniform int brush_kind = 0;
uniform float height_delta = 0.0;
uniform float height_span = 70.0;
void fragment() {
vec2 uv_local = UV * 2.0 - 1.0;
float u = uv_local.x;
float v = uv_local.y;
float r2 = u * u + v * v;
if (r2 >= 1.0) {
discard;
}
float pos_dh = 0.0;
float pos_dg = 0.0;
float d_scorch = 0.0;
if (brush_kind == 0) {
// DuneRidge (positive)
float env = 1.0 - r2;
env *= env;
float ridge = max(0.0, 1.0 - u * u);
float asym = 1.0 + 0.32 * u;
pos_dh = max(0.0, height_delta) * env * (0.35 + 0.65 * ridge) * asym;
pos_dg = 0.02 * env;
} else if (brush_kind == 1) {
// Mesa
float r = sqrt(r2);
float t = clamp((1.0 - r) / 0.45, 0.0, 1.0);
float plateau = t * t * (3.0 - 2.0 * t);
pos_dh = max(0.0, height_delta) * plateau;
} else if (brush_kind == 2) {
// SalvagePad (positive part)
float env = 1.0 - r2;
env *= env;
pos_dh = max(0.0, height_delta) * env;
pos_dg = 0.03 * env;
} else if (brush_kind == 4) {
// Crater ejecta rim + slag/scorch
float r = sqrt(r2);
float depth = abs(height_delta);
float rim_t = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0));
pos_dh = 0.32 * depth * rim_t * rim_t;
pos_dg = 0.04 * (1.0 - r);
d_scorch = 0.78 * clamp(1.0 - r * 0.9, 0.0, 1.0);
} else if (brush_kind == 5) {
// Track wear
float env = 1.0 - r2;
env *= env;
d_scorch = 0.32 * env;
} else if (brush_kind == 6) {
// Scorch
float r = sqrt(r2);
float mask = clamp(1.0 - r, 0.0, 1.0);
mask = mask * mask;
pos_dg = 0.02 * mask;
d_scorch = 0.85 * mask;
}
COLOR = vec4(pos_dh / height_span, pos_dg, d_scorch, 1.0);
}

View file

@ -1,73 +0,0 @@
shader_type canvas_item;
render_mode blend_mix;
uniform int brush_kind = 0;
uniform vec3 brush_albedo = vec3(0.72, 0.53, 0.33);
uniform float height_delta = 0.0;
void fragment() {
vec2 uv_local = UV * 2.0 - 1.0;
float u = uv_local.x;
float v = uv_local.y;
float r2 = u * u + v * v;
if (r2 >= 1.0) {
discard;
}
vec3 col = brush_albedo;
float alpha = 0.0;
if (brush_kind == 0) {
// DuneRidge: windward sunlit crest vs dry wash
float env = 1.0 - r2;
env *= env;
float ridge = max(0.0, 1.0 - u * u);
col = mix(brush_albedo * 0.90, brush_albedo * 1.12, ridge);
alpha = env * 0.72;
} else if (brush_kind == 1) {
// Mesa: rust-basalt plateau + stratified skirt
float r = sqrt(r2);
float t = clamp((1.0 - r) / 0.45, 0.0, 1.0);
float plateau = t * t * (3.0 - 2.0 * t);
float cliff_band = clamp(1.0 - abs(r - 0.74) * 5.0, 0.0, 1.0);
col = mix(brush_albedo, brush_albedo * 0.68, cliff_band);
alpha = clamp(plateau + cliff_band * 0.5, 0.0, 0.94);
} else if (brush_kind == 2) {
// SalvagePad: compacted gravel & weathered concrete slab
float env = 1.0 - r2;
env *= env;
float border = smoothstep(0.75, 0.92, sqrt(r2));
col = mix(brush_albedo, vec3(0.32, 0.28, 0.24), border * 0.45);
alpha = clamp(env * 1.15, 0.0, 0.88);
} else if (brush_kind == 3) {
// Road: twin packed dirt ruts running longitudinally along u (cross-track offset abs(v))
float env = 1.0 - r2;
env *= env;
float rut = smoothstep(0.15, 0.45, abs(v)) * (1.0 - smoothstep(0.60, 0.92, abs(v)));
col = mix(brush_albedo, brush_albedo * 0.76, rut);
alpha = env * (0.45 + 0.35 * rut);
} else if (brush_kind == 4) {
// Crater: charred pit center + bright rust ejecta rim
float r = sqrt(r2);
float pit = clamp(1.0 - r / 0.62, 0.0, 1.0);
float rim = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0));
vec3 ejecta = vec3(0.62, 0.38, 0.22);
col = mix(ejecta, brush_albedo, clamp(pit * 1.3, 0.0, 1.0));
alpha = clamp(max(pit * 0.94, rim * rim * 0.72), 0.0, 0.95);
} else if (brush_kind == 5) {
// Track: twin tire ruts along local X
float env = 1.0 - r2;
env *= env;
float treads = smoothstep(0.18, 0.45, abs(v)) * (1.0 - smoothstep(0.62, 0.92, abs(v)));
col = brush_albedo;
alpha = env * treads * 0.62;
} else if (brush_kind == 6) {
// Scorch
float r = sqrt(r2);
float mask = clamp(1.0 - r, 0.0, 1.0);
col = brush_albedo;
alpha = mask * mask * 0.88;
}
COLOR = vec4(col, alpha);
}

View file

@ -1,41 +0,0 @@
shader_type canvas_item;
render_mode blend_sub;
// Encodes negative height deltas (crater pits, dry washes, road ruts, tire ruts) into R.
uniform int brush_kind = 0;
uniform float height_delta = 0.0;
uniform float height_span = 70.0;
void fragment() {
vec2 uv_local = UV * 2.0 - 1.0;
float u = uv_local.x;
float v = uv_local.y;
float r2 = u * u + v * v;
if (r2 >= 1.0) {
discard;
}
float neg_dh = 0.0;
float neg_dg = 0.0;
if (brush_kind == 0) {
// Dry wash (negative DuneRidge)
float env = 1.0 - r2;
env *= env;
float ridge = max(0.0, 1.0 - u * u);
float asym = 1.0 + 0.32 * u;
neg_dh = max(0.0, -height_delta) * env * (0.35 + 0.65 * ridge) * asym;
} else if (brush_kind == 2 || brush_kind == 3 || brush_kind == 5) {
// SalvagePad (<0), Road, Track rut
float env = 1.0 - r2;
env *= env;
neg_dh = max(0.0, -height_delta) * env;
} else if (brush_kind == 4) {
// Crater pit
float r = sqrt(r2);
float depth = abs(height_delta);
float pit_t = clamp(1.0 - r / 0.62, 0.0, 1.0);
neg_dh = depth * pit_t * pit_t * (3.0 - 2.0 * pit_t);
}
COLOR = vec4(neg_dh / height_span, neg_dg, 0.0, 1.0);
}

View file

@ -1,18 +1,29 @@
shader_type spatial;
render_mode cull_back, depth_draw_opaque;
uniform sampler2D height_tex : filter_linear, repeat_disable;
uniform sampler2D albedo_tex : source_color, filter_linear, repeat_disable;
uniform sampler2D base_dem_tex : filter_linear, repeat_disable;
uniform sampler2D base_surface_tex : source_color, filter_linear_mipmap, repeat_disable;
uniform sampler2D base_mask_tex : filter_linear_mipmap, repeat_disable;
uniform sampler2D delta_height_tex : filter_linear, repeat_disable;
uniform sampler2D delta_albedo_tex : source_color, filter_linear, repeat_disable;
uniform float dem_min_y = 0.0;
uniform float dem_scale_span = 0.0;
uniform float dem_grid_res = 6145.0;
uniform float height_min = -18.0;
uniform float height_max = 52.0;
uniform float map_size = 1536.0;
uniform float tile_origin_x = 0.0;
uniform float tile_origin_z = 0.0;
uniform float tile_size = 192.0;
uniform float inner_span = 253.0;
uniform float tex_size = 256.0;
uniform float gutter_offset = 1.5;
uniform float inner_span = 384.0;
uniform float tex_size = 388.0;
uniform float gutter_center = 2.5;
uniform float is_sion = 0.0;
uniform float tile_quads = 192.0;
uniform vec4 neighbor_quads = vec4(192.0, 192.0, 192.0, 192.0); // (-X, +X, -Z, +Z)
float decode_height(float h_norm) {
return mix(height_min, height_max, clamp(h_norm, 0.0, 1.0));
}
varying vec3 v_world_pos;
float hash21(vec2 p) {
p = fract(p * vec2(123.34, 456.21));
@ -20,37 +31,117 @@ float hash21(vec2 p) {
return fract(p.x * p.y);
}
float value_noise(vec2 p) {
vec2 i = floor(p);
vec2 f = fract(p);
vec2 u = f * f * (3.0 - 2.0 * f);
float a = hash21(i);
float b = hash21(i + vec2(1.0, 0.0));
float c = hash21(i + vec2(0.0, 1.0));
float d = hash21(i + vec2(1.0, 1.0));
return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}
vec2 to_baked_uv(vec2 mesh_uv) {
return (mesh_uv * inner_span + gutter_offset) / tex_size;
return (mesh_uv * inner_span + gutter_center) / tex_size;
}
float sample_total_height(vec2 mesh_uv) {
vec2 world_xz = vec2(tile_origin_x, tile_origin_z) + mesh_uv * tile_size;
float base_h = 0.0;
if (is_sion > 0.5) {
float max_idx = dem_grid_res - 1.0;
vec2 dem_uv = ((world_xz + map_size * 0.5) / map_size * max_idx + 0.5) / dem_grid_res;
base_h = dem_min_y + textureLod(base_dem_tex, dem_uv, 0.0).r * dem_scale_span;
}
float delta_h = textureLod(delta_height_tex, to_baked_uv(mesh_uv), 0.0).r;
return clamp(base_h + delta_h, height_min, height_max);
}
float sample_edge_snapped_height(vec2 uv) {
// Zero T-junction cracks: if an adjacent tile is coarser, snap edge vertex height
// onto the exact linear segment connecting the neighbor's coarse edge vertices.
if (uv.x < 0.0005 && neighbor_quads.x < tile_quads - 0.5) {
float nq = neighbor_quads.x;
float t = uv.y * nq;
float i0 = floor(t);
float u0 = i0 / nq;
float u1 = min(1.0, (i0 + 1.0) / nq);
return mix(sample_total_height(vec2(0.0, u0)), sample_total_height(vec2(0.0, u1)), t - i0);
}
if (uv.x > 0.9995 && neighbor_quads.y < tile_quads - 0.5) {
float nq = neighbor_quads.y;
float t = uv.y * nq;
float i0 = floor(t);
float u0 = i0 / nq;
float u1 = min(1.0, (i0 + 1.0) / nq);
return mix(sample_total_height(vec2(1.0, u0)), sample_total_height(vec2(1.0, u1)), t - i0);
}
if (uv.y < 0.0005 && neighbor_quads.z < tile_quads - 0.5) {
float nq = neighbor_quads.z;
float t = uv.x * nq;
float i0 = floor(t);
float u0 = i0 / nq;
float u1 = min(1.0, (i0 + 1.0) / nq);
return mix(sample_total_height(vec2(u0, 0.0)), sample_total_height(vec2(u1, 0.0)), t - i0);
}
if (uv.y > 0.9995 && neighbor_quads.w < tile_quads - 0.5) {
float nq = neighbor_quads.w;
float t = uv.x * nq;
float i0 = floor(t);
float u0 = i0 / nq;
float u1 = min(1.0, (i0 + 1.0) / nq);
return mix(sample_total_height(vec2(u0, 1.0)), sample_total_height(vec2(u1, 1.0)), t - i0);
}
return sample_total_height(uv);
}
void vertex() {
float h_norm = textureLod(height_tex, to_baked_uv(UV), 0.0).r;
VERTEX.y += decode_height(h_norm);
float h = sample_edge_snapped_height(UV);
VERTEX.y += h;
v_world_pos = (MODEL_MATRIX * vec4(VERTEX, 1.0)).xyz;
}
void fragment() {
vec2 uv_baked = to_baked_uv(UV);
float texel_step = 1.0 / tex_size;
float world_step = tile_size / inner_span;
float world_step = tile_size / inner_span; // 0.5m
float uv_step = world_step / tile_size;
float hL = decode_height(texture(height_tex, uv_baked - vec2(texel_step, 0.0)).r);
float hR = decode_height(texture(height_tex, uv_baked + vec2(texel_step, 0.0)).r);
float hD = decode_height(texture(height_tex, uv_baked - vec2(0.0, texel_step)).r);
float hU = decode_height(texture(height_tex, uv_baked + vec2(0.0, texel_step)).r);
float hL = sample_total_height(UV - vec2(uv_step, 0.0));
float hR = sample_total_height(UV + vec2(uv_step, 0.0));
float hD = sample_total_height(UV - vec2(0.0, uv_step));
float hU = sample_total_height(UV + vec2(0.0, uv_step));
vec3 world_normal = normalize(vec3(hL - hR, 2.0 * world_step, hD - hU));
NORMAL = normalize((VIEW_MATRIX * vec4(world_normal, 0.0)).xyz);
vec4 mat = texture(height_tex, uv_baked);
vec3 alb = texture(albedo_tex, uv_baked).rgb;
// Subtle desert sand grain so dunes read crisply under sunlight (multiplicative in linear HDR)
float grain = (hash21(floor(UV * 768.0)) - 0.5) * 0.045;
vec2 uv_baked = to_baked_uv(UV);
vec4 mat = texture(delta_height_tex, uv_baked);
vec3 delta_alb = texture(delta_albedo_tex, uv_baked).rgb;
float scorch = clamp(mat.b, 0.0, 1.0);
alb = clamp(alb * (1.0 + grain * 1.4), 0.0, 1.0) * (1.0 - 0.30 * scorch);
vec3 alb;
float rough = clamp(mat.g, 0.35, 1.0);
if (is_sion > 0.5) {
vec2 world_uv = (v_world_pos.xz + map_size * 0.5) / map_size;
vec3 base_col = texture(base_surface_tex, world_uv).rgb;
vec4 cls = texture(base_mask_tex, world_uv);
alb = mix(base_col, delta_alb, clamp(mat.a, 0.0, 1.0));
float dist = length((INV_VIEW_MATRIX * vec4(0.0, 0.0, 0.0, 1.0)).xyz - v_world_pos);
float near_fade = clamp(1.0 - smoothstep(140.0, 480.0, dist), 0.12, 1.0);
float macro = (value_noise(v_world_pos.xz * 0.28) - 0.5) * 0.07;
float grit = (hash21(floor(v_world_pos.xz * 8.0)) - 0.5) * 0.045;
alb = clamp(alb * (1.0 + macro * 1.4 + grit * 1.6 * near_fade), 0.0, 1.0) * (1.0 - 0.32 * scorch);
float base_rough = cls.r * 0.94 + cls.g * 0.90 + cls.b * 0.80 + cls.a * 0.26;
float cls_sum = max(0.001, cls.r + cls.g + cls.b + cls.a);
rough = mix(clamp(base_rough / cls_sum, 0.26, 0.96), rough, clamp(mat.a, 0.0, 1.0));
} else {
float grain = (hash21(floor(UV * 768.0)) - 0.5) * 0.045;
alb = clamp(delta_alb * (1.0 + grain * 1.4), 0.0, 1.0) * (1.0 - 0.30 * scorch);
}
ALBEDO = alb;
ROUGHNESS = clamp(mat.g, 0.35, 1.0);
ROUGHNESS = rough;
METALLIC = 0.02;
}

View file

@ -0,0 +1,176 @@
#version 450
layout(local_size_x = 8, local_size_y = 8, local_size_z = 1) in;
struct GpuBrush {
vec4 posRot; // x, z, cosR, sinR
vec4 radDelta; // invRx, invRz, heightDelta, maxRadiusSq
vec4 matColor; // albedoR, albedoG, albedoB, float(kind)
};
layout(set = 0, binding = 0, rgba16f) uniform writeonly image2D u_delta_height;
layout(set = 0, binding = 1, rgba8) uniform writeonly image2D u_delta_albedo;
layout(set = 0, binding = 2, std430) readonly buffer BrushBuffer {
GpuBrush brushes[];
} u_brushes;
layout(push_constant, std430) uniform TileBakeParams {
vec4 tileOriginAndSpan; // x=tileMinX, y=tileMinZ, z=tileSize(192), w=innerSpan(384)
vec4 baseColorAndGutter; // rgb=clearAlbedo, w=gutterStart(2.0)
uvec4 counts; // x=brushStart, y=brushCount, z=texSize(388), w=isSion
} u_params;
void main() {
ivec2 gid = ivec2(gl_GlobalInvocationID.xy);
int texSize = int(u_params.counts.z);
if (gid.x >= texSize || gid.y >= texSize) {
return;
}
float tileMinX = u_params.tileOriginAndSpan.x;
float tileMinZ = u_params.tileOriginAndSpan.y;
float tileSize = u_params.tileOriginAndSpan.z;
float innerSpan = u_params.tileOriginAndSpan.w;
float gutterStart = u_params.baseColorAndGutter.w;
float stepM = tileSize / innerSpan;
float wx = tileMinX + (float(gid.x) - gutterStart) * stepM;
float wz = tileMinZ + (float(gid.y) - gutterStart) * stepM;
bool isSion = u_params.counts.w != 0u;
uint brushStart = u_params.counts.x;
uint brushEnd = brushStart + u_params.counts.y;
float totalDh = 0.0;
float totalDg = 0.0;
float totalScorch = 0.0;
vec3 albedoAcc = u_params.baseColorAndGutter.rgb;
float deltaBlendAcc = isSion ? 0.0 : 1.0;
for (uint i = brushStart; i < brushEnd; i++) {
GpuBrush b = u_brushes.brushes[i];
float dx = wx - b.posRot.x;
float dz = wz - b.posRot.y;
if (dx * dx + dz * dz >= b.radDelta.w) {
continue;
}
float cosR = b.posRot.z;
float sinR = b.posRot.w;
float lx = dx * cosR + dz * sinR;
float lz = -dx * sinR + dz * cosR;
float u = lx * b.radDelta.x;
float v = lz * b.radDelta.y;
float r2 = u * u + v * v;
if (r2 >= 1.0) {
continue;
}
int kind = int(b.matColor.w + 0.5);
float heightDelta = b.radDelta.z;
vec3 bCol = b.matColor.rgb;
float dh = 0.0;
float dg = 0.0;
float dScorch = 0.0;
vec3 col = bCol;
float alpha = 0.0;
if (kind == 0) {
// DuneRidge
float env = 1.0 - r2;
env *= env;
float ridge = max(0.0, 1.0 - u * u);
float asym = 1.0 + 0.32 * u;
dh = heightDelta * env * (0.35 + 0.65 * ridge) * asym;
if (heightDelta > 0.0) {
dg = 0.02 * env;
}
col = mix(bCol * 0.90, bCol * 1.12, ridge);
alpha = env * 0.72;
} else if (kind == 1) {
// Mesa
float r = sqrt(r2);
float t = clamp((1.0 - r) / 0.45, 0.0, 1.0);
float plateau = t * t * (3.0 - 2.0 * t);
dh = heightDelta * plateau;
float cliffBand = clamp(1.0 - abs(r - 0.74) * 5.0, 0.0, 1.0);
col = mix(bCol, bCol * 0.68, cliffBand);
alpha = clamp(plateau + cliffBand * 0.5, 0.0, 0.94);
} else if (kind == 2) {
// SalvagePad
float env = 1.0 - r2;
env *= env;
dh = heightDelta * env;
if (heightDelta > 0.0) {
dg = 0.03 * env;
}
float border = smoothstep(0.75, 0.92, sqrt(r2));
col = mix(bCol, vec3(0.32, 0.28, 0.24), border * 0.45);
alpha = clamp(env * 1.15, 0.0, 0.88);
} else if (kind == 3) {
// Road
float env = 1.0 - r2;
env *= env;
dh = heightDelta * env;
float rut = smoothstep(0.15, 0.45, abs(v)) * (1.0 - smoothstep(0.60, 0.92, abs(v)));
col = mix(bCol, bCol * 0.76, rut);
alpha = env * (0.45 + 0.35 * rut);
} else if (kind == 4) {
// Crater
float r = sqrt(r2);
float depth = abs(heightDelta);
float pitT = clamp(1.0 - r / 0.62, 0.0, 1.0);
float pit = -depth * pitT * pitT * (3.0 - 2.0 * pitT);
float rimT = sin(3.14159265 * clamp((r - 0.55) / 0.45, 0.0, 1.0));
float rim = 0.32 * depth * rimT * rimT;
dh = pit + rim;
dg = 0.04 * (1.0 - r);
dScorch = 0.78 * clamp(1.0 - r * 0.9, 0.0, 1.0);
vec3 ejecta = isSion ? vec3(0.34, 0.31, 0.27) : vec3(0.62, 0.38, 0.22);
col = mix(ejecta, bCol, clamp(pitT * 1.3, 0.0, 1.0));
alpha = clamp(max(pitT * 0.94, rimT * rimT * 0.72), 0.0, 0.95);
} else if (kind == 5) {
// Track
float env = 1.0 - r2;
env *= env;
dh = heightDelta * env;
dScorch = 0.32 * env;
float treads = smoothstep(0.18, 0.45, abs(v)) * (1.0 - smoothstep(0.62, 0.92, abs(v)));
col = bCol;
alpha = env * treads * 0.62;
} else if (kind == 6) {
// Scorch
float r = sqrt(r2);
float mask = clamp(1.0 - r, 0.0, 1.0);
float mask2 = mask * mask;
dg = 0.02 * mask2;
dScorch = 0.85 * mask2;
col = bCol;
alpha = mask2 * 0.88;
} else if (kind == 7) {
// Rubble
float env = 1.0 - r2;
env *= env;
float mound = 0.72 + 0.28 * cos(u * 3.14159265 * 2.5);
dh = heightDelta * env * mound;
dg = 0.08 * env;
dScorch = 0.35 * env;
float chunk = fract(sin(dot(floor(vec2(wx, wz) * 1.5), vec2(12.9898, 78.233))) * 43758.5453);
col = mix(bCol * 0.80, bCol * 1.15, chunk);
alpha = clamp(env * 1.2, 0.0, 0.96);
}
totalDh += dh;
totalDg += dg;
totalScorch += dScorch;
albedoAcc = mix(albedoAcc, col, alpha);
deltaBlendAcc = max(deltaBlendAcc, alpha);
}
float roughness = clamp(0.88 + totalDg, 0.35, 1.0);
float scorch = clamp(totalScorch, 0.0, 1.0);
imageStore(u_delta_height, gid, vec4(totalDh, roughness, scorch, clamp(deltaBlendAcc, 0.0, 1.0)));
imageStore(u_delta_albedo, gid, vec4(clamp(albedoAcc, 0.0, 1.0), 1.0));
}

View file

@ -203,11 +203,11 @@ public partial class Smoke : Node
}
}
// Regression check (Finding 4): 4-tile boundary crater at (0, 0) bakes all 4 tiles on Sync#1 (<= 0.20m error on all 4 quadrants)
// and passive Track throttling preserves DirtyTileMask until all tiles are baked without skipping via _rebakeCursor.
// Regression check: 4-tile boundary crater at (0, 0) bakes all 4 tiles on Sync#1 (<= 0.20m error on all 4 quadrants)
// and passive Track throttling (MaxDirtyRebakesPerSync=4) preserves pending visual versions until all tiles are baked without skipping via _rebakeCursor.
{
// Flush any lingering track rebakes first so baseline is clean
for (int flush = 0; flush < 32 && _main.Session.ViewState.Terrain.DirtyTileMask != 0UL; flush++)
for (int flush = 0; flush < 32 && _main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) > 0; flush++)
{
_main.Terrain.Sync(_main.Session.ViewState.Terrain);
}
@ -229,8 +229,8 @@ public partial class Smoke : Node
_main.Terrain.Sync(_main.Session.ViewState.Terrain); // Sync#1
Check(_main.Terrain.DirtyRebakes == rebakes4Before + 4,
$"Expected 4-tile boundary crater at (0,0) to bake all 4 tiles on Sync#1, got {_main.Terrain.DirtyRebakes - rebakes4Before}");
Check(_main.Session.ViewState.Terrain.StructuralDirtyTileMask == 0UL,
"Expected StructuralDirtyTileMask == 0 after Sync#1 on 4-tile boundary crater");
Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 0,
"Expected 0 pending dirty tiles after Sync#1 on 4-tile boundary crater");
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
@ -252,21 +252,23 @@ public partial class Smoke : Node
}
}
// Stamp 3 passive tracks in adjacent tiles so _rebakeCursor must advance across Sync#1 and Sync#2 without skipping
// Stamp 5 passive tracks in distinct tiles so _rebakeCursor advances across Sync#1 (4) and Sync#2 (1) without skipping
int rebakesTrackBefore = _main.Terrain.DirtyRebakes;
_main.Session.ViewState.Terrain.StampTrack(-480f, -480f, 0f, 2f, 3f);
_main.Session.ViewState.Terrain.StampTrack(-288f, -480f, 0f, 2f, 3f);
_main.Session.ViewState.Terrain.StampTrack(-96f, -480f, 0f, 2f, 3f);
_main.Session.ViewState.Terrain.StampTrack(96f, -480f, 0f, 2f, 3f);
_main.Session.ViewState.Terrain.StampTrack(288f, -480f, 0f, 2f, 3f);
_main.Terrain.Sync(_main.Session.ViewState.Terrain);
Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 2,
$"Expected Sync#1 to throttle 3 passive tracks to 2 rebakes, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}");
Check(_main.Session.ViewState.Terrain.DirtyTileMask != 0UL,
"Expected DirtyTileMask to stay non-zero while 1 passive track tile remains dirty");
Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 4,
$"Expected Sync#1 to throttle 5 passive tracks to 4 rebakes, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}");
Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 1,
"Expected 1 pending dirty track tile remaining after Sync#1");
_main.Terrain.Sync(_main.Session.ViewState.Terrain);
Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 3,
$"Expected Sync#2 to bake remaining 3rd passive track tile without _rebakeCursor skip, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}");
Check(_main.Session.ViewState.Terrain.DirtyTileMask == 0UL,
"Expected DirtyTileMask == 0 after all passive track tiles baked");
Check(_main.Terrain.DirtyRebakes == rebakesTrackBefore + 5,
$"Expected Sync#2 to bake remaining 5th passive track tile without _rebakeCursor skip, got {_main.Terrain.DirtyRebakes - rebakesTrackBefore}");
Check(_main.Terrain.CountPendingDirtyVisualTiles(_main.Session.ViewState.Terrain) == 0,
"Expected 0 pending dirty tiles after all passive track tiles baked");
}
_main.SetPhysicsProcess(true);
@ -1856,9 +1858,10 @@ public partial class Smoke : Node
var sionState = _main.Session.ViewState;
Check(_main.MapKind == ArenaMapKind.Sion && sionState.MapKind == ArenaMapKind.Sion, "Expected Sion map kind after Reset");
Check(_main.SionMap.Visible && !_main.Terrain.Visible, "Expected SionMapRenderer visible and Desert TerrainRenderer hidden");
Check(_main.Terrain.Visible && _main.SionMap.Visible, "Expected unified TerrainRenderer and SionMapRenderer buildings visible on Sion");
Check(_main.Terrain.BakedTileCount == 256, $"Expected 256 unified Sion terrain tiles (16x16), got {_main.Terrain.BakedTileCount}");
Check(_main.Terrain.ActiveGpuScarSlots == 0, $"Expected 0 active GPU scar slots on clean Sion start, got {_main.Terrain.ActiveGpuScarSlots}");
Check(_main.SionMap.IsBuilt, "Expected SionMapRenderer.IsBuilt == true");
Check(_main.SionMap.TerrainChunkCount == 36, $"Expected 36 Sion terrain chunks, got {_main.SionMap.TerrainChunkCount}");
Check(_main.SionMap.BuildingTileCount == 36, $"Expected 36 Sion building tiles, got {_main.SionMap.BuildingTileCount}");
Check(_main.SionMap.ActiveLod1TileCount > 0, $"Expected > 0 LOD1 tiles near Sion spawn, got {_main.SionMap.ActiveLod1TileCount}");
Check(_main.SionMap.ActiveLod2TileCount > 0, $"Expected > 0 LOD2 tiles in Sion valley, got {_main.SionMap.ActiveLod2TileCount}");
@ -1905,14 +1908,31 @@ public partial class Smoke : Node
float disp = MathF.Sqrt((player.X - startX) * (player.X - startX) + (player.Z - startZ) * (player.Z - startZ));
Check(disp > 1.5f, $"Expected player displacement > 1.5m on Sion after 30 frames, got {disp:F2}m");
Color inBoundsTint = _main.SionMap.SampleGroundTint(player.X, player.Z);
Color outBoundsTint = _main.SionMap.SampleGroundTint(9999f, 9999f);
Color inBoundsTint = _main.Terrain.SampleGroundTint(player.X, player.Z);
Color outBoundsTint = _main.Terrain.SampleGroundTint(9999f, 9999f);
Check(float.IsFinite(inBoundsTint.R) && float.IsFinite(inBoundsTint.G) && float.IsFinite(inBoundsTint.B) && inBoundsTint.R > 0.1f,
$"Expected valid Sion SampleGroundTint at player pos, got {inBoundsTint}");
Check(MathF.Abs(outBoundsTint.R - 0.56f) < 0.01f && MathF.Abs(outBoundsTint.G - 0.53f) < 0.01f,
$"Expected neutral alpine fallback tint outside Sion bounds, got {outBoundsTint}");
GD.Print($"SMOKE INFO: Sion verified (chunks={_main.SionMap.TerrainChunkCount}, tiles={_main.SionMap.BuildingTileCount}, lod1={_main.SionMap.ActiveLod1TileCount}, lod2={_main.SionMap.ActiveLod2TileCount}, disp={disp:F2}m, tint=({inBoundsTint.R:F2},{inBoundsTint.G:F2},{inBoundsTint.B:F2}))");
// Verify live crater brush on Sion allocates sparse GPU scar slot & depresses GPU height
float sionCpuPre = sionState.Terrain.SampleHeight(player.X, player.Z);
sionState.Terrain.StampCrater(player.X, player.Z, radius: 5.0f, depth: 1.5f);
_main.Terrain.Sync(sionState.Terrain, sionState.SionMap);
Check(_main.Terrain.ActiveGpuScarSlots >= 1, $"Expected >= 1 active GPU scar slot on Sion after crater, got {_main.Terrain.ActiveGpuScarSlots}");
if (DisplayServer.GetName() != "headless")
{
await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
Check(_main.Terrain.TrySampleBakedHeight(player.X, player.Z, out float sionGpuPost),
"Expected TrySampleBakedHeight to succeed on Sion crater tile");
float sionCpuPost = sionState.Terrain.SampleHeight(player.X, player.Z);
Check(MathF.Abs(sionGpuPost - sionCpuPost) <= 0.25f,
$"Expected Sion GPU crater height ({sionGpuPost:F3}m) to match CPU ({sionCpuPost:F3}m) within 0.25m");
Check(sionGpuPost < sionCpuPre - 0.8f,
$"Expected Sion GPU crater height ({sionGpuPost:F3}m) to depress below pre-crater ({sionCpuPre:F3}m)");
}
GD.Print($"SMOKE INFO: Sion verified (terrainTiles={_main.Terrain.BakedTileCount}, gpuScarSlots={_main.Terrain.ActiveGpuScarSlots}, bldgTiles={_main.SionMap.BuildingTileCount}, lod1={_main.SionMap.ActiveLod1TileCount}, lod2={_main.SionMap.ActiveLod2TileCount}, disp={disp:F2}m, tint=({inBoundsTint.R:F2},{inBoundsTint.G:F2},{inBoundsTint.B:F2}))");
}
private async Task VerifyOrbitalDropSequenceAsync()

View file

@ -26,6 +26,7 @@ layout(set = 0, binding = 0, std140) uniform VolumetricFrame {
vec4 flowOriginVoxel;
vec4 flowInvExtentDt;
ivec4 flowDeltaImpulse;
uvec4 qualityParams;
} u_frame;
layout(set = 0, binding = 1) uniform sampler2D u_depthTex;
@ -44,13 +45,14 @@ float linearizeReverseZ(float rawDepth) {
return (zN * zF) / max(1e-5, zN + rawDepth * (zF - zN));
}
float halfQuadMaxDepth(ivec2 hpx, ivec2 fullRes) {
ivec2 basePx = hpx * 2;
float marchQuadMaxDepth(ivec2 mpx, ivec2 marchRes, ivec2 fullRes) {
vec2 ratio = vec2(fullRes) / vec2(marchRes);
ivec2 px0 = clamp(ivec2(floor(vec2(mpx) * ratio)), ivec2(0), fullRes - ivec2(1));
ivec2 px1 = clamp(ivec2(ceil(vec2(mpx + ivec2(1)) * ratio)) - ivec2(1), px0, fullRes - ivec2(1));
float dMax = 0.0;
for (int dy = 0; dy < 2; dy++) {
for (int dx = 0; dx < 2; dx++) {
ivec2 sp = min(basePx + ivec2(dx, dy), fullRes - ivec2(1));
dMax = max(dMax, linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r));
for (int sy = px0.y; sy <= px1.y; sy++) {
for (int sx = px0.x; sx <= px1.x; sx++) {
dMax = max(dMax, linearizeReverseZ(texelFetch(u_depthTex, ivec2(sx, sy), 0).r));
}
}
return dMax;
@ -63,55 +65,82 @@ void main() {
return;
}
// Empty-tile fast exit: coherent across the 16x16 workgroup (32x32 full-res tile)
ivec2 tileCoord = px / 32;
uint tileIdx = uint(tileCoord.y) * u_frame.tileGridParams.z + uint(tileCoord.x);
if (u_tiles.tiles[tileIdx].count == 0u) {
return;
ivec2 marchRes = ivec2(u_frame.tileGridParams.xy);
uint tilesX = u_frame.tileGridParams.z;
bool isFullRes = u_frame.qualityParams.z != 0u;
vec4 vol;
if (isFullRes) {
ivec2 tileCoord = px / 16;
uint tileIdx = uint(tileCoord.y) * tilesX + uint(tileCoord.x);
if (u_tiles.tiles[tileIdx].count == 0u) {
return;
}
// Direct 1:1 full-res sample bypassing 2x2 bilateral upsample
vol = texelFetch(u_halfVolTex, min(px, marchRes - ivec2(1)), 0);
} else {
vec2 scaleToMarch = vec2(marchRes) / vec2(fullRes);
vec2 hCoord = (vec2(px) + vec2(0.5)) * scaleToMarch - vec2(0.5);
ivec2 h0 = clamp(ivec2(floor(hCoord)), ivec2(0), marchRes - ivec2(1));
ivec2 h1 = min(h0 + ivec2(1), marchRes - ivec2(1));
ivec2 t0 = h0 / 16;
ivec2 t1 = h1 / 16;
if (all(equal(t0, t1))) {
uint tileIdx = uint(t0.y) * tilesX + uint(t0.x);
if (u_tiles.tiles[tileIdx].count == 0u) {
return;
}
} else {
uint anyCount =
u_tiles.tiles[uint(t0.y) * tilesX + uint(t0.x)].count +
u_tiles.tiles[uint(t0.y) * tilesX + uint(t1.x)].count +
u_tiles.tiles[uint(t1.y) * tilesX + uint(t0.x)].count +
u_tiles.tiles[uint(t1.y) * tilesX + uint(t1.x)].count;
if (anyCount == 0u) {
return;
}
}
float dFull = linearizeReverseZ(texelFetch(u_depthTex, px, 0).r);
vec2 f = clamp(hCoord - vec2(h0), vec2(0.0), vec2(1.0));
float depthScale = max(0.45, 0.055 * dFull);
vec4 volSum = vec4(0.0);
float wSum = 0.0;
float wRawSum = 0.0;
float minMarchDepth = 1e9;
ivec2 offsets[4] = ivec2[4](ivec2(0, 0), ivec2(1, 0), ivec2(0, 1), ivec2(1, 1));
float spatialW[4] = float[4](
(1.0 - f.x) * (1.0 - f.y),
f.x * (1.0 - f.y),
(1.0 - f.x) * f.y,
f.x * f.y
);
for (int i = 0; i < 4; i++) {
ivec2 hp = min(h0 + offsets[i], marchRes - ivec2(1));
vec4 vSample = texelFetch(u_halfVolTex, hp, 0);
float dMarch = marchQuadMaxDepth(hp, marchRes, fullRes);
minMarchDepth = min(minMarchDepth, dMarch);
float wDepth = exp(-abs(dFull - dMarch) / depthScale);
float wRaw = spatialW[i] * wDepth;
wRawSum += wRaw;
float w = max(1e-5, wRaw);
volSum += vSample * w;
wSum += w;
}
// Thin foreground occluder (spark/edge strictly in front of ALL 4 march-res background depth taps):
// do not smear background smoke over it
if (wRawSum < 1e-3 && dFull < minMarchDepth * 0.92) {
return;
}
vol = volSum / max(1e-5, wSum);
}
ivec2 halfRes = ivec2(u_frame.tileGridParams.xy);
float dFull = linearizeReverseZ(texelFetch(u_depthTex, px, 0).r);
// 2x2 depth-aware bilateral upsample from half-res volumetric buffer
vec2 hCoord = (vec2(px) + vec2(0.5)) * 0.5 - vec2(0.5);
ivec2 h0 = clamp(ivec2(floor(hCoord)), ivec2(0), halfRes - ivec2(1));
vec2 f = clamp(hCoord - vec2(h0), vec2(0.0), vec2(1.0));
float depthScale = max(0.45, 0.055 * dFull);
vec4 volSum = vec4(0.0);
float wSum = 0.0;
float wRawSum = 0.0;
float minHalfDepth = 1e9;
ivec2 offsets[4] = ivec2[4](ivec2(0, 0), ivec2(1, 0), ivec2(0, 1), ivec2(1, 1));
float spatialW[4] = float[4](
(1.0 - f.x) * (1.0 - f.y),
f.x * (1.0 - f.y),
(1.0 - f.x) * f.y,
f.x * f.y
);
for (int i = 0; i < 4; i++) {
ivec2 hp = min(h0 + offsets[i], halfRes - ivec2(1));
vec4 vSample = texelFetch(u_halfVolTex, hp, 0);
float dHalf = halfQuadMaxDepth(hp, fullRes);
minHalfDepth = min(minHalfDepth, dHalf);
float wDepth = exp(-abs(dFull - dHalf) / depthScale);
float wRaw = spatialW[i] * wDepth;
wRawSum += wRaw;
float w = max(1e-5, wRaw);
volSum += vSample * w;
wSum += w;
}
// Thin foreground occluder (spark/edge strictly in front of ALL 4 half-res background depth taps):
// do not smear background smoke over it
if (wRawSum < 1e-3 && dFull < minHalfDepth * 0.92) {
return;
}
vec4 vol = volSum / max(1e-5, wSum);
// Skip write when completely transparent
if (vol.a > 0.999 && dot(vol.rgb, vol.rgb) < 1e-7) {
return;

View file

@ -33,6 +33,7 @@ layout(set = 0, binding = 0, std140) uniform VolumetricFrame {
vec4 flowOriginVoxel;
vec4 flowInvExtentDt;
ivec4 flowDeltaImpulse;
uvec4 qualityParams;
} u_frame;
layout(set = 0, binding = 1, std430) readonly buffer EmitterBuffer {
@ -221,12 +222,12 @@ void main() {
memoryBarrierShared();
barrier();
ivec2 halfRes = ivec2(u_frame.tileGridParams.xy);
ivec2 marchRes = ivec2(u_frame.tileGridParams.xy);
ivec2 px = ivec2(gl_GlobalInvocationID.xy);
// Empty-tile fast exit (uniform across workgroup)
if (sTileCount == 0u) {
if (all(lessThan(px, halfRes))) {
if (all(lessThan(px, marchRes))) {
imageStore(u_halfVol, px, vec4(0.0, 0.0, 0.0, 1.0));
}
return;
@ -239,22 +240,29 @@ void main() {
memoryBarrierShared();
barrier();
if (any(greaterThanEqual(px, halfRes))) {
if (any(greaterThanEqual(px, marchRes))) {
return;
}
ivec2 fullRes = ivec2(u_frame.viewportInfo.xy);
ivec2 basePx = px * 2;
bool isFullRes = u_frame.qualityParams.z != 0u;
float dMax = 0.0;
for (int dy = 0; dy < 2; dy++) {
for (int dx = 0; dx < 2; dx++) {
ivec2 sp = min(basePx + ivec2(dx, dy), fullRes - ivec2(1));
float linD = linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r);
dMax = max(dMax, linD);
if (isFullRes) {
ivec2 sp = min(px, fullRes - ivec2(1));
dMax = linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r);
} else {
vec2 ratio = vec2(fullRes) / vec2(marchRes);
ivec2 px0 = clamp(ivec2(floor(vec2(px) * ratio)), ivec2(0), fullRes - ivec2(1));
ivec2 px1 = clamp(ivec2(ceil(vec2(px + ivec2(1)) * ratio)) - ivec2(1), px0, fullRes - ivec2(1));
for (int sy = px0.y; sy <= px1.y; sy++) {
for (int sx = px0.x; sx <= px1.x; sx++) {
float linD = linearizeReverseZ(texelFetch(u_depthTex, ivec2(sx, sy), 0).r);
dMax = max(dMax, linD);
}
}
}
vec2 fullUv = (vec2(px) * 2.0 + vec2(1.0)) / vec2(fullRes);
vec2 fullUv = (vec2(px) + vec2(0.5)) / vec2(marchRes);
float invCosView;
vec3 rd = computeRayDirWorld(fullUv, invCosView);
vec3 ro = u_frame.camPosTime.xyz;
@ -313,16 +321,17 @@ void main() {
float t = 0.0;
int steps = 0;
int iter = 0;
const int MaxSteps = 10;
const int MaxIter = 15;
int maxSteps = clamp(int(u_frame.qualityParams.x), 1, 64);
int maxIter = clamp(max(int(u_frame.qualityParams.y), maxSteps * 2), 1, 96);
float stepScale = 10.0 / max(float(maxSteps), 1.0);
while ((nextIdx < hitCount || activeMask != 0u) && t < tEndMax && T >= 0.03 && steps < MaxSteps && iter < MaxIter) {
while ((nextIdx < hitCount || activeMask != 0u) && t < tEndMax && T >= 0.03 && steps < maxSteps && iter < maxIter) {
// Empty-space jump directly to nextIdx's t0 whenever no emitter is currently active
if (activeMask == 0u) {
float minNext = uintBitsToFloat(hitPack[nextIdx] & 0xFFFFFFE0u);
float nextT1 = hitT1[nextIdx];
float chord = max(0.0, nextT1 - minNext);
float dsLeap = max(0.42, 0.32 + 0.014 * minNext);
float dsLeap = max(0.16, max(0.42, 0.32 + 0.014 * minNext) * stepScale);
float jitter = ign * min(dsLeap, max(0.05, chord * 0.45));
t = min(max(t, minNext) + jitter, tEndMax - 1e-4);
if (t >= tEndMax) {
@ -330,7 +339,7 @@ void main() {
}
}
float ds = max(0.42, 0.32 + 0.014 * t);
float ds = max(0.16, max(0.42, 0.32 + 0.014 * t) * stepScale);
float tLo = t - 0.5 * ds;
float tHi = t + 0.5 * ds;
@ -486,11 +495,12 @@ void main() {
// Dense interiors stay deep velvety charcoal soot; rimBoost (1.65) applies strictly to thin outer sunlit vapor edges
float sootContour = 1.0 / (1.0 + 4.6 * rawDens);
float sunAlignment = clamp(dot(localUpOrRadial, sunDir), -1.0, 1.0);
float rimBias = 0.36 + 0.64 * max(0.0, sunAlignment) + 0.14 * (0.5 + 0.5 * sunAlignment);
float rimBias = max(0.0, sunAlignment);
float rimFactor = 1.0 + 0.65 * smoothstep(0.25, 0.72, sootContour);
vec3 sunlitEdgeTint = mix(albedo, albedo * 1.35 + vec3(0.045, 0.040, 0.036), sootContour * smoothstep(0.10, 0.78, max(0.0, sunAlignment) + phase));
float vaporEdgeFade = smoothstep(0.0, 0.08, rawDens);
vec3 scatterLum = sunlitEdgeTint * (sootContour * vaporEdgeFade * rimFactor) * (sunRad * (rimBias + phase * 2.6) + ambRad * 0.25);
vec3 skyBounce = max(0.0, localUpOrRadial.y) * 0.08 * ambRad;
vec3 scatterLum = sunlitEdgeTint * (sootContour * vaporEdgeFade * rimFactor) * (sunRad * (rimBias + phase * 2.6) + skyBounce);
// Layer 3: Sharp turbulent core-only combustion peeking through dark soot crevices
vec3 plasmaEmit = vec3(0.0);

View file

@ -33,6 +33,7 @@ layout(set = 0, binding = 0, std140) uniform VolumetricFrame {
vec4 flowOriginVoxel;
vec4 flowInvExtentDt;
ivec4 flowDeltaImpulse;
uvec4 qualityParams;
} u_frame;
layout(set = 0, binding = 1, std430) readonly buffer EmitterBuffer {
@ -76,21 +77,30 @@ void main() {
memoryBarrierShared();
barrier();
ivec2 halfRes = ivec2(u_frame.tileGridParams.xy);
ivec2 marchRes = ivec2(u_frame.tileGridParams.xy);
ivec2 fullRes = ivec2(u_frame.viewportInfo.xy);
ivec2 hx = ivec2(gl_GlobalInvocationID.xy);
ivec2 mx = ivec2(gl_GlobalInvocationID.xy);
bool isFullRes = u_frame.qualityParams.z != 0u;
float dMin = u_frame.viewportInfo.z;
float dMax = 0.0;
if (all(lessThan(hx, halfRes))) {
ivec2 basePx = hx * 2;
for (int dy = 0; dy < 2; dy++) {
for (int dx = 0; dx < 2; dx++) {
ivec2 sp = min(basePx + ivec2(dx, dy), fullRes - ivec2(1));
float rawD = texelFetch(u_depthTex, sp, 0).r;
float linD = linearizeReverseZ(rawD);
dMin = min(dMin, linD);
dMax = max(dMax, linD);
if (all(lessThan(mx, marchRes))) {
if (isFullRes) {
ivec2 sp = min(mx, fullRes - ivec2(1));
float linD = linearizeReverseZ(texelFetch(u_depthTex, sp, 0).r);
dMin = linD;
dMax = linD;
} else {
vec2 ratio = vec2(fullRes) / vec2(marchRes);
ivec2 px0 = clamp(ivec2(floor(vec2(mx) * ratio)), ivec2(0), fullRes - ivec2(1));
ivec2 px1 = clamp(ivec2(ceil(vec2(mx + ivec2(1)) * ratio)) - ivec2(1), px0, fullRes - ivec2(1));
for (int sy = px0.y; sy <= px1.y; sy++) {
for (int sx = px0.x; sx <= px1.x; sx++) {
float rawD = texelFetch(u_depthTex, ivec2(sx, sy), 0).r;
float linD = linearizeReverseZ(rawD);
dMin = min(dMin, linD);
dMax = max(dMax, linD);
}
}
}
atomicMin(sMinDepthBits, floatBitsToUint(max(0.0, dMin)));
@ -106,10 +116,8 @@ void main() {
}
// Tile frustum bounds in view space (view looks down -Z, +X right, +Y up)
vec2 tileMinPx = vec2(tileCoord * 16) * 2.0;
vec2 tileMaxPx = min(vec2((tileCoord + ivec2(1)) * 16) * 2.0, vec2(fullRes));
vec2 uv0 = tileMinPx / vec2(fullRes);
vec2 uv1 = tileMaxPx / vec2(fullRes);
vec2 uv0 = vec2(tileCoord * 16) / vec2(marchRes);
vec2 uv1 = min(vec2((tileCoord + ivec2(1)) * 16) / vec2(marchRes), vec2(1.0));
float tanY = u_frame.camUpTanHalfFov.w;
float aspect = u_frame.camRightAspect.w;

View file

@ -0,0 +1,384 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using GameCult.Caching;
using GameCult.Caching.MessagePack;
using MessagePack;
namespace RustToDust.Core
{
[MessagePackObject]
public sealed class TerrainScarEntry
{
[Key(0)] public byte Kind { get; set; }
[Key(1)] public float X { get; set; }
[Key(2)] public float Z { get; set; }
[Key(3)] public float Radius { get; set; }
[Key(4)] public float Depth { get; set; }
[Key(5)] public float Yaw { get; set; }
[Key(6)] public uint Rgb8 { get; set; }
[Key(7), CultElementId] public string ElementId { get; set; } = string.Empty;
}
[MessagePackObject]
public sealed class BuildingScarEntry
{
[Key(0)] public ushort BldgId { get; set; }
[Key(1)] public ulong CollapsedMask { get; set; }
[Key(2)] public ulong DamagedMask { get; set; }
[Key(3), CultElementId(nameof(BldgId))] public string ElementId { get; set; } = string.Empty;
}
[MessagePackObject]
public sealed class TreeScarEntry
{
[Key(0)] public ushort TreeId { get; set; }
[Key(1)] public byte State { get; set; }
[Key(2), CultElementId(nameof(TreeId))] public string ElementId { get; set; } = string.Empty;
}
[CultDocument("rtd.arena_scar_ledger", "1"), MessagePackObject]
public sealed class ArenaScarLedgerSnapshot
{
[CultName, Key(0)] public string AssetFingerprint { get; set; } = string.Empty;
[Key(1)] public List<TerrainScarEntry> Terrain { get; set; } = new();
[Key(2)] public List<BuildingScarEntry> Buildings { get; set; } = new();
[Key(3)] public List<TreeScarEntry> Trees { get; set; } = new();
[Key(4)] public uint LedgerRevision { get; set; }
}
public sealed class ArenaScarLedger
{
public const int MaxPersistentTerrainScars = 4096;
public const float CraterCoalesceRadiusMeters = TerrainField.CraterCoalesceRadiusMeters;
private readonly List<TerrainScarEntry> _terrain = new();
private readonly Dictionary<ushort, BuildingScarEntry> _buildings = new();
private readonly Dictionary<ushort, TreeScarEntry> _trees = new();
public ArenaScarLedger(string assetFingerprint = "")
{
AssetFingerprint = assetFingerprint;
}
public string AssetFingerprint { get; set; }
public uint LedgerRevision { get; private set; }
public bool IsDirty { get; set; }
public IReadOnlyList<TerrainScarEntry> Terrain => _terrain;
public IReadOnlyDictionary<ushort, BuildingScarEntry> Buildings => _buildings;
public IReadOnlyDictionary<ushort, TreeScarEntry> Trees => _trees;
public void RecordTerrainStamp(TerrainStampEvent stamp) =>
RecordTerrainStamp(stamp.Kind, stamp.X, stamp.Z, stamp.Radius, stamp.Depth, stamp.Yaw);
public void RecordTerrainStamp(byte kind, float x, float z, float radius, float depth, float yaw, uint rgb8 = 0)
{
var stampKind = (TerrainStampKind)kind;
if (stampKind == TerrainStampKind.Track)
{
return;
}
if (stampKind == TerrainStampKind.Crater)
{
radius = Math.Clamp(radius, 1.2f, 16f);
depth = Math.Clamp(MathF.Abs(depth), 0.15f, 4.5f);
}
float coalesceSq = CraterCoalesceRadiusMeters * CraterCoalesceRadiusMeters;
if (stampKind == TerrainStampKind.Crater || stampKind == TerrainStampKind.Scorch)
{
for (int i = _terrain.Count - 1; i >= 0; i--)
{
var existing = _terrain[i];
if (existing.Kind != kind)
{
continue;
}
float dx = existing.X - x;
float dz = existing.Z - z;
if (dx * dx + dz * dz < coalesceSq)
{
existing.Radius = MathF.Max(existing.Radius, radius);
existing.Depth = MathF.Max(existing.Depth, depth);
LedgerRevision++;
IsDirty = true;
return;
}
}
}
if (_terrain.Count >= MaxPersistentTerrainScars)
{
int evictIdx = -1;
for (int i = 0; i < _terrain.Count; i++)
{
if (_terrain[i].Kind == (byte)TerrainStampKind.Scorch)
{
evictIdx = i;
break;
}
}
_terrain.RemoveAt(evictIdx >= 0 ? evictIdx : 0);
}
_terrain.Add(new TerrainScarEntry
{
Kind = kind,
X = x,
Z = z,
Radius = radius,
Depth = depth,
Yaw = yaw,
Rgb8 = rgb8
});
LedgerRevision++;
IsDirty = true;
}
public void Clear()
{
_terrain.Clear();
_buildings.Clear();
_trees.Clear();
LedgerRevision++;
IsDirty = true;
}
public ArenaScarLedgerSnapshot ToSnapshot()
{
var snap = new ArenaScarLedgerSnapshot
{
AssetFingerprint = AssetFingerprint,
LedgerRevision = LedgerRevision,
Terrain = new List<TerrainScarEntry>(_terrain.Count),
Buildings = new List<BuildingScarEntry>(_buildings.Count),
Trees = new List<TreeScarEntry>(_trees.Count)
};
for (int i = 0; i < _terrain.Count; i++)
{
var t = _terrain[i];
snap.Terrain.Add(new TerrainScarEntry
{
Kind = t.Kind,
X = t.X,
Z = t.Z,
Radius = t.Radius,
Depth = t.Depth,
Yaw = t.Yaw,
Rgb8 = t.Rgb8
});
}
foreach (var b in _buildings.Values)
{
snap.Buildings.Add(new BuildingScarEntry
{
BldgId = b.BldgId,
CollapsedMask = b.CollapsedMask,
DamagedMask = b.DamagedMask
});
}
foreach (var tr in _trees.Values)
{
snap.Trees.Add(new TreeScarEntry
{
TreeId = tr.TreeId,
State = tr.State
});
}
return snap;
}
public void LoadFromSnapshot(ArenaScarLedgerSnapshot snapshot)
{
_terrain.Clear();
_buildings.Clear();
_trees.Clear();
if (!string.IsNullOrEmpty(AssetFingerprint) &&
!string.Equals(snapshot.AssetFingerprint, AssetFingerprint, StringComparison.Ordinal))
{
return;
}
for (int i = 0; i < snapshot.Terrain.Count && i < MaxPersistentTerrainScars; i++)
{
var t = snapshot.Terrain[i];
_terrain.Add(new TerrainScarEntry
{
Kind = t.Kind,
X = t.X,
Z = t.Z,
Radius = t.Radius,
Depth = t.Depth,
Yaw = t.Yaw,
Rgb8 = t.Rgb8
});
}
for (int i = 0; i < snapshot.Buildings.Count; i++)
{
var b = snapshot.Buildings[i];
_buildings[b.BldgId] = new BuildingScarEntry
{
BldgId = b.BldgId,
CollapsedMask = b.CollapsedMask,
DamagedMask = b.DamagedMask
};
}
for (int i = 0; i < snapshot.Trees.Count; i++)
{
var tr = snapshot.Trees[i];
_trees[tr.TreeId] = new TreeScarEntry
{
TreeId = tr.TreeId,
State = tr.State
};
}
LedgerRevision = snapshot.LedgerRevision;
IsDirty = false;
}
public void ApplyToTerrain(TerrainField terrain)
{
for (int i = 0; i < _terrain.Count; i++)
{
var t = _terrain[i];
switch ((TerrainStampKind)t.Kind)
{
case TerrainStampKind.Crater:
terrain.StampCrater(t.X, t.Z, t.Radius, t.Depth);
break;
case TerrainStampKind.Scorch:
terrain.StampScorch(t.X, t.Z, t.Radius);
break;
case TerrainStampKind.Rubble:
terrain.StampRubble(t.X, t.Z, t.Radius, t.Depth, t.Yaw);
break;
}
}
}
public static byte[] CompressSnapshot(ArenaScarLedgerSnapshot snapshot)
{
byte[] raw = MessagePackSerializer.Serialize(snapshot);
using var ms = new MemoryStream();
using (var zlib = new ZLibStream(ms, CompressionLevel.Optimal, leaveOpen: true))
{
zlib.Write(raw, 0, raw.Length);
}
return ms.ToArray();
}
public static ArenaScarLedgerSnapshot DecompressSnapshot(byte[] compressed)
{
using var src = new MemoryStream(compressed);
using var zlib = new ZLibStream(src, CompressionMode.Decompress);
using var dst = new MemoryStream();
zlib.CopyTo(dst);
return MessagePackSerializer.Deserialize<ArenaScarLedgerSnapshot>(dst.ToArray());
}
}
public static class ArenaScarLedgerStore
{
public static CultDocumentRegistry Registry { get; } =
CultDocumentRegistry.ForTypes(new[] { typeof(ArenaScarLedgerSnapshot) });
public static CultRecordKey LedgerKey(string profile = "default") => new("scars:" + profile);
public static string GetDefaultPath(ArenaMapKind mapKind, string profile = "default")
{
string baseDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
if (string.IsNullOrWhiteSpace(baseDir))
{
baseDir = AppContext.BaseDirectory;
}
string mapTag = mapKind == ArenaMapKind.Sion ? "sion" : "desert";
string safeProfile = string.IsNullOrWhiteSpace(profile) ? "default" : profile.Trim();
return Path.Combine(baseDir, "RustToDust", "scars", $"{mapTag}_scars_{safeProfile}.cultcache");
}
public static CultCache Open(string path, bool writable = false)
{
var options = new CultCacheOpenOptions
{
Registry = Registry,
ReadOnly = !writable,
FlushOnDispose = false,
StoreFlushOnDispose = false,
UseDirectoryStore = false
};
return CultCacheMessagePack.Create(path, options);
}
public static ArenaScarLedgerSnapshot Load(string path, string expectedAssetFingerprint)
{
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
{
return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint };
}
try
{
using var cache = Open(path, writable: false);
var records = cache.GetAll<ArenaScarLedgerSnapshot>().ToArray();
if (records.Length == 0)
{
return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint };
}
var snap = records[0];
if (!string.IsNullOrEmpty(expectedAssetFingerprint) &&
!string.Equals(snap.AssetFingerprint, expectedAssetFingerprint, StringComparison.Ordinal))
{
return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint };
}
return snap;
}
catch
{
return new ArenaScarLedgerSnapshot { AssetFingerprint = expectedAssetFingerprint };
}
}
public static void Save(string path, ArenaScarLedgerSnapshot snapshot, string profile = "default")
{
if (snapshot is null) throw new ArgumentNullException(nameof(snapshot));
if (string.IsNullOrWhiteSpace(path)) throw new ArgumentException("Path cannot be empty.", nameof(path));
string fullPath = Path.GetFullPath(path);
string dir = Path.GetDirectoryName(fullPath) ?? ".";
Directory.CreateDirectory(dir);
string workspace = fullPath + "." + Guid.NewGuid().ToString("N") + ".tmp";
string tempFile = Path.Combine(workspace, "scars.cultcache");
try
{
Directory.CreateDirectory(workspace);
using (var cache = Open(tempFile, writable: true))
{
cache.UpsertAsync(typeof(ArenaScarLedgerSnapshot), snapshot, LedgerKey(profile)).GetAwaiter().GetResult();
cache.FlushAsync().GetAwaiter().GetResult();
}
if (File.Exists(fullPath))
{
File.Replace(tempFile, fullPath, null);
}
else
{
File.Move(tempFile, fullPath);
}
}
finally
{
if (Directory.Exists(workspace))
{
Directory.Delete(workspace, recursive: true);
}
}
}
}
}

View file

@ -352,7 +352,8 @@ namespace RustToDust.Core
ArenaMapKind mapKind = ArenaMapKind.Desert,
bool skipInitialDrop = false,
bool startInLobby = false,
byte squadSize = 1)
byte squadSize = 1,
ArenaScarLedgerSnapshot? initialScars = null)
{
Seed = seed;
MapKind = mapKind;
@ -367,13 +368,21 @@ namespace RustToDust.Core
if (mapKind == ArenaMapKind.Sion)
{
SionMap = SionMapLoader.Load();
Terrain = TerrainField.LoadHeightmap(
Terrain = TerrainField.LoadSharedHeightmap(
SionMap.Metadata.SizeMeters,
SionMap.Metadata.GridRes,
SionMap.Heights,
SionMap.Metadata.TileGrid,
SionMap.BaseDem,
SionMap.BaseDemMinY,
SionMap.BaseDemScale,
SionMap.Metadata.MinY,
SionMap.Metadata.MaxY,
(ulong)seed);
ScarLedger = new ArenaScarLedger(SionMap.AssetFingerprint);
if (initialScars is not null)
{
ApplyPersistentScars(initialScars);
}
Spectators = new SpectatorRing(
seed + 101,
SpectatorRing.DefaultSpectatorCount,
@ -396,6 +405,11 @@ namespace RustToDust.Core
Spectators = new SpectatorRing(seed + 101);
var rawCover = BuildCoverBoxes();
Terrain = TerrainField.Generate((ulong)seed, rawCover);
ScarLedger = new ArenaScarLedger($"desert:{seed}");
if (initialScars is not null)
{
ApplyPersistentScars(initialScars);
}
ArenaCoverBoxes = SeatBoxesOnTerrain(rawCover, Terrain);
ArenaBoundaryBoxes = BuildBoundaryBoxes(ArenaHalfExtent, -48f, 72f);
SpawnContenders();
@ -531,7 +545,46 @@ namespace RustToDust.Core
public int? WinnerContenderId { get; set; }
public TerrainField Terrain { get; }
public ArenaScarLedger ScarLedger { get; }
public List<ContenderState> Contenders { get; } = new();
public void ApplyPersistentScars(ArenaScarLedgerSnapshot snapshot)
{
ScarLedger.LoadFromSnapshot(snapshot);
ScarLedger.ApplyToTerrain(Terrain);
}
public void ApplyTerrainStamp(TerrainStampEvent stamp, bool recordInLedger = true)
{
switch ((TerrainStampKind)stamp.Kind)
{
case TerrainStampKind.Crater:
Terrain.StampCrater(stamp.X, stamp.Z, stamp.Radius, stamp.Depth);
break;
case TerrainStampKind.Scorch:
Terrain.StampScorch(stamp.X, stamp.Z, stamp.Radius);
break;
case TerrainStampKind.Track:
Terrain.StampTrack(stamp.X, stamp.Z, stamp.Yaw, stamp.Radius, stamp.Length);
return;
case TerrainStampKind.Rubble:
Terrain.StampRubble(stamp.X, stamp.Z, stamp.Radius, stamp.Depth, stamp.Yaw);
break;
}
if (recordInLedger)
{
ScarLedger.RecordTerrainStamp(stamp);
}
}
public void RepairArenaScars()
{
Terrain.ClearDynamicScars();
ScarLedger.Clear();
}
public bool IsSolidBuildingAtXz(float x, float z, float padding = 0f) =>
SionMap is not null && SionMap.IsInsideAnyBuildingXz(x, z, padding);
public SpectatorRing Spectators { get; }
public List<GroundDrop> GroundDrops { get; } = new();
public List<TracerEvent> Tracers { get; } = new();

View file

@ -1475,8 +1475,21 @@ namespace RustToDust.Core
{
if (emitEvents && !touchSample.IsBuildingRoof)
{
_state.Terrain.StampCrater(pod.X, pod.Z, pod.PodKind == OrbitalPodKind.Contender ? 3.4f : 2.1f, 0.32f);
_state.Terrain.StampScorch(pod.X, pod.Z, pod.PodKind == OrbitalPodKind.Contender ? 4.2f : 2.6f);
_state.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = pod.X,
Z = pod.Z,
Radius = pod.PodKind == OrbitalPodKind.Contender ? 3.4f : 2.1f,
Depth = 0.32f
});
_state.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Scorch,
X = pod.X,
Z = pod.Z,
Radius = pod.PodKind == OrbitalPodKind.Contender ? 4.2f : 2.6f
});
}
// Re-sample ground height after crater stamp

View file

@ -8,7 +8,8 @@ namespace RustToDust.Core
{
Crater = 0,
Scorch = 1,
Track = 2
Track = 2,
Rubble = 3
}
public enum SlotControlReason : byte
@ -34,6 +35,7 @@ namespace RustToDust.Core
[Union(12, typeof(DropPodEvent))]
[Union(13, typeof(OrdnanceNodeEvent))]
[Union(14, typeof(MatchStartedEvent))]
[Union(17, typeof(ArenaRepairEvent))]
public interface ISimEvent
{
}
@ -323,6 +325,7 @@ namespace RustToDust.Core
[Key(15)] public LobbySnapshotDto? Lobby { get; set; }
[Key(16)] public byte SquadSize { get; set; } = 1;
[Key(17)] public byte[]? ContenderSquadIds { get; set; }
[Key(18)] public byte[]? PersistentScars { get; set; }
}
[MessagePackObject]
@ -381,6 +384,7 @@ namespace RustToDust.Core
[Union(12, typeof(LobbySnapshotMsg))]
[Union(13, typeof(ClientKeepaliveMsg))]
[Union(14, typeof(LobbySquadCmdMsg))]
[Union(15, typeof(RepairArenaCmdMsg))]
public interface ISchemaWireMessage
{
}
@ -499,6 +503,18 @@ namespace RustToDust.Core
[Key(1)] public LobbySnapshotDto Snapshot { get; set; } = new();
}
[MessagePackObject]
public sealed class ArenaRepairEvent : ISimEvent
{
[Key(0)] public uint LedgerRevision { get; set; }
}
[MessagePackObject]
public sealed class RepairArenaCmdMsg : ISchemaWireMessage
{
[Key(0)] public uint ReqSeq { get; set; }
}
[MessagePackObject]
public sealed class ClientKeepaliveMsg : ISchemaWireMessage
{

View file

@ -2,6 +2,7 @@ using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Numerics;
using System.Text.Json;
@ -29,7 +30,14 @@ namespace RustToDust.Core
float MinY,
float MaxY,
string SurfaceTexture,
IReadOnlyList<SionTileMeta> Tiles);
IReadOnlyList<SionTileMeta> Tiles,
string DemAssetHash = "",
string HeightmapFile = "heightmap_05m.u16z",
float HeightmapMinY = 0f,
float HeightmapScale = 1f,
string SurfaceMaskTexture = "terrain_surface_mask.png",
int BuildingTileGrid = 6,
float BuildingTileSizeMeters = 512f);
public readonly record struct SionBuildingAabb(
string Id,
@ -76,7 +84,7 @@ namespace RustToDust.Core
{
private const int SpatialGridRes = 64;
private readonly float[] _heights;
private readonly ushort[] _baseDem;
private readonly SionBuildingAabb[] _buildings;
private readonly List<int>[] _cellBuildings;
private readonly float[] _cellMinGroundY;
@ -87,13 +95,20 @@ namespace RustToDust.Core
internal SionMapData(
string directoryPath,
SionMetadata metadata,
float[] heights,
ushort[] baseDem,
float baseDemMinY,
float baseDemScale,
SionBuildingAabb[] buildings,
SionCollisionMesh[] collisionMeshes)
{
DirectoryPath = directoryPath;
Metadata = metadata;
_heights = heights;
_baseDem = baseDem;
BaseDemMinY = baseDemMinY;
BaseDemScale = baseDemScale;
AssetFingerprint = !string.IsNullOrWhiteSpace(metadata.DemAssetHash)
? $"sion:{metadata.DemAssetHash}"
: $"sion:{metadata.GridRes}:{metadata.CellSizeMeters:F3}";
_buildings = buildings;
CollisionMeshes = collisionMeshes;
@ -131,7 +146,11 @@ namespace RustToDust.Core
public string DirectoryPath { get; }
public SionMetadata Metadata { get; }
public ReadOnlySpan<float> Heights => _heights;
public ushort[] BaseDem => _baseDem;
public float BaseDemMinY { get; }
public float BaseDemScale { get; }
public string AssetFingerprint { get; }
public float SampleBaseDemAtIndex(int index) => BaseDemMinY + _baseDem[index] * BaseDemScale;
public IReadOnlyList<SionBuildingAabb> Buildings => _buildings;
public IReadOnlyList<SionCollisionMesh> CollisionMeshes { get; }
@ -324,12 +343,12 @@ namespace RustToDust.Core
AssetPathResolver.LocateSubdirectory(
Path.Combine("maps", "sion"),
IsValidSionDirectory,
"containing metadata.json and heightmap.f32");
"containing metadata.json and heightmap_05m.u16z");
private static bool IsValidSionDirectory(string dir) =>
Directory.Exists(dir) &&
File.Exists(Path.Combine(dir, "metadata.json")) &&
File.Exists(Path.Combine(dir, "heightmap.f32")) &&
File.Exists(Path.Combine(dir, "heightmap_05m.u16z")) &&
File.Exists(Path.Combine(dir, "buildings_manifest.json"));
public static SionMapData Load(string? sionDirectory = null)
@ -344,7 +363,12 @@ namespace RustToDust.Core
}
var meta = LoadMetadata(Path.Combine(root, "metadata.json"));
float[] heights = LoadHeightmap(Path.Combine(root, "heightmap.f32"), meta.GridRes);
string hmFile = string.IsNullOrWhiteSpace(meta.HeightmapFile) ? "heightmap_05m.u16z" : meta.HeightmapFile;
ushort[] baseDem = LoadHeightmapU16z(
Path.Combine(root, hmFile),
meta.GridRes,
out float demMinY,
out float demScale);
SionBuildingAabb[] buildings = LoadBuildingsManifest(Path.Combine(root, "buildings_manifest.json"));
var colMeshes = new SionCollisionMesh[meta.Tiles.Count];
for (int i = 0; i < meta.Tiles.Count; i++)
@ -354,7 +378,7 @@ namespace RustToDust.Core
colMeshes[i] = LoadRcolFile(colPath, t.Tx, t.Tz);
}
var data = new SionMapData(root, meta, heights, buildings, colMeshes);
var data = new SionMapData(root, meta, baseDem, demMinY, demScale, buildings, colMeshes);
lock (CacheLock)
{
Cache[root] = data;
@ -395,29 +419,82 @@ namespace RustToDust.Core
MinY: r.GetProperty("minY").GetSingle(),
MaxY: r.GetProperty("maxY").GetSingle(),
SurfaceTexture: r.GetProperty("surfaceTexture").GetString() ?? "terrain_surface.png",
Tiles: tiles);
Tiles: tiles,
DemAssetHash: r.TryGetProperty("demAssetHash", out var dh) ? (dh.GetString() ?? "") : "",
HeightmapFile: r.TryGetProperty("heightmapFile", out var hf) ? (hf.GetString() ?? "heightmap_05m.u16z") : "heightmap_05m.u16z",
HeightmapMinY: r.TryGetProperty("heightmapMinY", out var hmin) ? hmin.GetSingle() : 0f,
HeightmapScale: r.TryGetProperty("heightmapScale", out var hsc) ? hsc.GetSingle() : 1f,
SurfaceMaskTexture: r.TryGetProperty("surfaceMaskTexture", out var sm) ? (sm.GetString() ?? "terrain_surface_mask.png") : "terrain_surface_mask.png",
BuildingTileGrid: r.TryGetProperty("buildingTileGrid", out var btg) ? btg.GetInt32() : 6,
BuildingTileSizeMeters: r.TryGetProperty("buildingTileSizeMeters", out var bts) ? bts.GetSingle() : 512f);
}
private static float[] LoadHeightmap(string path, int gridRes)
private static ushort[] LoadHeightmapU16z(string path, int expectedGridRes, out float minY, out float scale)
{
byte[] raw = File.ReadAllBytes(path);
int expectedCount = gridRes * gridRes;
if (raw.Length != expectedCount * 4)
byte[] fileBytes = File.ReadAllBytes(path);
if (fileBytes.Length < 24)
{
throw new InvalidDataException(
$"Expected heightmap.f32 byte length {expectedCount * 4} ({gridRes}x{gridRes}), got {raw.Length}.");
throw new InvalidDataException($"Heightmap file '{path}' too small ({fileBytes.Length} bytes).");
}
var heights = new float[expectedCount];
ReadOnlySpan<byte> span = raw;
for (int i = 0; i < expectedCount; i++)
ReadOnlySpan<byte> hdr = fileBytes.AsSpan(0, 24);
if (hdr[0] != (byte)'R' || hdr[1] != (byte)'D' || hdr[2] != (byte)'H' || hdr[3] != (byte)'M')
{
float v = BinaryPrimitives.ReadSingleLittleEndian(span.Slice(i * 4, 4));
if (!float.IsFinite(v))
throw new InvalidDataException($"Invalid RDHM magic in '{path}'.");
}
uint version = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(4, 4));
if (version != 2)
{
throw new InvalidDataException($"Unsupported RDHM version {version} in '{path}'.");
}
int gridRes = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(8, 4)));
if (gridRes != expectedGridRes)
{
throw new InvalidDataException($"RDHM gridRes mismatch in '{path}': header={gridRes}, metadata={expectedGridRes}.");
}
minY = BinaryPrimitives.ReadSingleLittleEndian(hdr.Slice(12, 4));
scale = BinaryPrimitives.ReadSingleLittleEndian(hdr.Slice(16, 4));
int rawByteCount = checked((int)BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(20, 4)));
int expectedSamples = gridRes * gridRes;
if (rawByteCount != expectedSamples * 2)
{
throw new InvalidDataException($"RDHM rawByteCount mismatch in '{path}': {rawByteCount} != {expectedSamples * 2}.");
}
byte[] raw = new byte[rawByteCount];
using (var ms = new MemoryStream(fileBytes, 24, fileBytes.Length - 24, writable: false))
using (var zlib = new ZLibStream(ms, CompressionMode.Decompress))
{
int totalRead = 0;
while (totalRead < rawByteCount)
{
throw new InvalidDataException($"Non-finite heightmap value at index {i}: {v}");
int read = zlib.Read(raw, totalRead, rawByteCount - totalRead);
if (read <= 0)
{
throw new InvalidDataException($"Unexpected EOF decompressing RDHM payload in '{path}' at {totalRead}/{rawByteCount}.");
}
totalRead += read;
}
}
var heights = new ushort[expectedSamples];
ReadOnlySpan<byte> span = raw;
for (int r = 0; r < gridRes; r++)
{
int rowStart = r * gridRes;
ushort pred = r > 0 ? heights[(r - 1) * gridRes] : (ushort)0;
for (int c = 0; c < gridRes; c++)
{
int idx = rowStart + c;
ushort zz = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(idx * 2, 2));
short d = unchecked((short)((zz >> 1) ^ -(zz & 1)));
ushort val = unchecked((ushort)(pred + d));
heights[idx] = val;
pred = val;
}
heights[i] = v;
}
return heights;
}

View file

@ -11,7 +11,8 @@ namespace RustToDust.Core
Road,
Crater,
Track,
Scorch
Scorch,
Rubble
}
public readonly record struct TerrainBrush(
@ -34,14 +35,15 @@ namespace RustToDust.Core
{
public const float ArenaSize = 1536f;
public const float HalfExtent = 768f;
public const int TileGridCount = 8;
public const float TileSize = ArenaSize / TileGridCount; // 192m
public const int DesertTileGridCount = 8;
public const float TileSize = ArenaSize / DesertTileGridCount; // 192m
private const int AccelGridCount = 64;
private const int AccelCellCount = AccelGridCount * AccelGridCount;
public const float MinWorldHeight = -18f;
public const float MaxWorldHeight = 52f;
public const float HeightSpan = MaxWorldHeight - MinWorldHeight; // 70m
public const int MaxDynamicDecals = 256;
public const float CraterCoalesceRadiusMeters = 0.75f;
private readonly record struct BrushPrecomp(
float CosR,
@ -64,21 +66,33 @@ namespace RustToDust.Core
private readonly List<TerrainBrush> _brushes = new();
private readonly List<BrushPrecomp> _brushPrecomps = new();
private readonly List<int>[,] _tileBrushIndices = new List<int>[TileGridCount, TileGridCount];
private readonly List<int>[,] _tileBrushIndices;
private readonly List<int>[] _cellBrushIndices = new List<int>[AccelCellCount];
private readonly float[] _cellMaxHeight = new float[AccelCellCount];
private readonly float[] _cellBaseMaxHeight = new float[AccelCellCount];
private readonly Queue<int> _dynamicDecalSlots = new();
private float[]? _heightmap;
private ushort[]? _sharedU16Heights;
private float _baseMinY;
private float _baseScale;
private readonly float[]?[,] _scarredTileHeights;
private int _nextBrushId = 1;
public TerrainField(ulong seed)
public TerrainField(ulong seed, int tileGridCount = DesertTileGridCount)
{
Seed = seed;
TileVersions = new int[TileGridCount, TileGridCount];
for (int tz = 0; tz < TileGridCount; tz++)
if (tileGridCount <= 0)
{
for (int tx = 0; tx < TileGridCount; tx++)
throw new ArgumentOutOfRangeException(nameof(tileGridCount));
}
Seed = seed;
TileGridCount = tileGridCount;
StructuralTileVersions = new int[tileGridCount, tileGridCount];
VisualTileVersions = new int[tileGridCount, tileGridCount];
_tileBrushIndices = new List<int>[tileGridCount, tileGridCount];
_scarredTileHeights = new float[tileGridCount, tileGridCount][];
for (int tz = 0; tz < tileGridCount; tz++)
{
for (int tx = 0; tx < tileGridCount; tx++)
{
_tileBrushIndices[tx, tz] = new List<int>(32);
}
@ -90,6 +104,7 @@ namespace RustToDust.Core
}
public ulong Seed { get; }
public int TileGridCount { get; }
public bool IsHeightmapMode { get; private set; }
public float MapSize { get; private set; } = ArenaSize;
public float MapHalfExtent { get; private set; } = HalfExtent;
@ -98,11 +113,15 @@ namespace RustToDust.Core
public float MapMaxHeight { get; private set; } = MaxWorldHeight;
public int HeightmapRes { get; private set; }
public float HeightmapCellSize { get; private set; }
public int PhysicsTileResolution => IsHeightmapMode ? ((HeightmapRes - 1) / TileGridCount + 1) : 0;
public ushort[]? SharedU16Heights => _sharedU16Heights;
public float BaseMinY => _baseMinY;
public float BaseScale => _baseScale;
private float AccelCellSize => MapSize / AccelGridCount;
public IReadOnlyList<TerrainBrush> Brushes => _brushes;
public int[,] TileVersions { get; }
public ulong DirtyTileMask { get; private set; }
public ulong StructuralDirtyTileMask { get; private set; }
public int[,] StructuralTileVersions { get; }
public int[,] VisualTileVersions { get; }
public int[,] TileVersions => VisualTileVersions;
public static TerrainField LoadHeightmap(
float sizeMeters,
@ -125,12 +144,13 @@ namespace RustToDust.Core
throw new ArgumentException($"Expected {gridRes * gridRes} height samples, got {heights.Length}.", nameof(heights));
}
var field = new TerrainField(seed)
int tileGridCount = Math.Max(1, (int)MathF.Round(sizeMeters / TileSize));
var field = new TerrainField(seed, tileGridCount)
{
IsHeightmapMode = true,
MapSize = sizeMeters,
MapHalfExtent = sizeMeters * 0.5f,
MapTileSize = sizeMeters / TileGridCount,
MapTileSize = sizeMeters / tileGridCount,
MapMinHeight = minY - 8f,
MapMaxHeight = maxY + 4f,
HeightmapRes = gridRes,
@ -138,9 +158,58 @@ namespace RustToDust.Core
_heightmap = heights.ToArray()
};
float half = field.MapHalfExtent;
float cellSize = field.AccelCellSize;
float invDemStep = 1f / field.HeightmapCellSize;
field.InitializeAccelGridFromHeightmap(gridRes);
return field;
}
public static TerrainField LoadSharedHeightmap(
float sizeMeters,
int gridRes,
int tileGridCount,
ushort[] sharedU16Heights,
float baseMinY,
float baseScale,
float worldMinY,
float worldMaxY,
ulong seed = 0UL)
{
if (sizeMeters <= 0f || !float.IsFinite(sizeMeters))
{
throw new ArgumentOutOfRangeException(nameof(sizeMeters));
}
if (gridRes < 2)
{
throw new ArgumentOutOfRangeException(nameof(gridRes));
}
if (sharedU16Heights is null || sharedU16Heights.Length != gridRes * gridRes)
{
throw new ArgumentException($"Expected {gridRes * gridRes} u16 height samples, got {sharedU16Heights?.Length ?? 0}.", nameof(sharedU16Heights));
}
var field = new TerrainField(seed, tileGridCount)
{
IsHeightmapMode = true,
MapSize = sizeMeters,
MapHalfExtent = sizeMeters * 0.5f,
MapTileSize = sizeMeters / tileGridCount,
MapMinHeight = worldMinY - 8f,
MapMaxHeight = worldMaxY + 4f,
HeightmapRes = gridRes,
HeightmapCellSize = sizeMeters / (gridRes - 1),
_sharedU16Heights = sharedU16Heights,
_baseMinY = baseMinY,
_baseScale = baseScale
};
field.InitializeAccelGridFromHeightmap(gridRes);
return field;
}
private void InitializeAccelGridFromHeightmap(int gridRes)
{
float half = MapHalfExtent;
float cellSize = AccelCellSize;
float invDemStep = 1f / HeightmapCellSize;
for (int cz = 0; cz < AccelGridCount; cz++)
{
@ -162,7 +231,9 @@ namespace RustToDust.Core
int row = iz * gridRes;
for (int ix = ix0; ix <= ix1; ix++)
{
float h = field._heightmap[row + ix];
float h = _sharedU16Heights is not null
? _baseMinY + _sharedU16Heights[row + ix] * _baseScale
: _heightmap![row + ix];
if (h > cellMax)
{
cellMax = h;
@ -172,8 +243,8 @@ namespace RustToDust.Core
int cellIdx = cz * AccelGridCount + cx;
float boundedMax = float.IsNegativeInfinity(cellMax) ? 0f : cellMax + 0.05f;
field._cellBaseMaxHeight[cellIdx] = boundedMax;
field._cellMaxHeight[cellIdx] = boundedMax;
_cellBaseMaxHeight[cellIdx] = boundedMax;
_cellMaxHeight[cellIdx] = boundedMax;
}
}
@ -181,23 +252,12 @@ namespace RustToDust.Core
{
for (int tx = 0; tx < TileGridCount; tx++)
{
field.TileVersions[tx, tz] = 1;
field.DirtyTileMask |= 1UL << (tz * TileGridCount + tx);
StructuralTileVersions[tx, tz] = 1;
VisualTileVersions[tx, tz] = 1;
}
}
return field;
}
public void ClearDirtyMask()
{
DirtyTileMask = 0UL;
StructuralDirtyTileMask = 0UL;
}
public void ClearStructuralDirtyTile(int tx, int tz) =>
StructuralDirtyTileMask &= ~(1UL << (tz * TileGridCount + tx));
public IReadOnlyList<int> GetTileBrushIndices(int tx, int tz) => _tileBrushIndices[tx, tz];
public static TerrainField Generate(ulong seed, IReadOnlyList<ArenaBoxSpec> coverBoxes)
@ -400,12 +460,12 @@ namespace RustToDust.Core
}
// Bump all initial tile versions to 1 so clients detect initial bake needed
for (int tz = 0; tz < TileGridCount; tz++)
for (int tz = 0; tz < field.TileGridCount; tz++)
{
for (int tx = 0; tx < TileGridCount; tx++)
for (int tx = 0; tx < field.TileGridCount; tx++)
{
field.TileVersions[tx, tz] = 1;
field.DirtyTileMask |= 1UL << (tz * TileGridCount + tx);
field.StructuralTileVersions[tx, tz] = 1;
field.VisualTileVersions[tx, tz] = 1;
}
}
@ -416,6 +476,40 @@ namespace RustToDust.Core
{
float clampedR = Math.Clamp(radius, 1.2f, 16f);
float clampedDepth = Math.Clamp(MathF.Abs(depth), 0.15f, 4.5f);
const float coalesceSq = CraterCoalesceRadiusMeters * CraterCoalesceRadiusMeters;
for (int i = _brushes.Count - 1; i >= 0; i--)
{
var existing = _brushes[i];
if (existing.Kind != TerrainBrushKind.Crater || !existing.Dynamic)
{
continue;
}
float dx = existing.X - x;
float dz = existing.Z - z;
if (dx * dx + dz * dz < coalesceSq)
{
float newR = MathF.Max(existing.RadiusX, clampedR);
float existingDepth = MathF.Abs(existing.HeightDelta);
float newDepth = MathF.Max(existingDepth, clampedDepth);
if (newR > existing.RadiusX || newDepth > existingDepth)
{
UnregisterBrushFromTiles(i, in existing);
var updated = existing with
{
RadiusX = newR,
RadiusZ = newR,
HeightDelta = -newDepth
};
_brushes[i] = updated;
_brushPrecomps[i] = BrushPrecomp.From(in updated);
RegisterBrushInTiles(i, in updated, incrementTileVersion: true);
}
return;
}
}
AddBrush(new TerrainBrush(
Id: 0,
Kind: TerrainBrushKind.Crater,
@ -433,6 +527,27 @@ namespace RustToDust.Core
Dynamic: true));
}
public void StampRubble(float x, float z, float radius, float heightDelta, float yaw = 0f)
{
float clampedR = Math.Clamp(radius, 1.5f, 18f);
float clampedH = Math.Clamp(MathF.Abs(heightDelta), 0.15f, 2.5f);
AddBrush(new TerrainBrush(
Id: 0,
Kind: TerrainBrushKind.Rubble,
X: x,
Z: z,
RotationRad: yaw,
RadiusX: clampedR,
RadiusZ: clampedR,
HeightDelta: clampedH,
Roughness: 0.97f,
Metallic: 0.05f,
AlbedoR: 0.42f,
AlbedoG: 0.39f,
AlbedoB: 0.35f,
Dynamic: true));
}
public void StampTrack(float x, float z, float yaw, float width, float length)
{
SetDynamicDecal(new TerrainBrush(
@ -472,13 +587,30 @@ namespace RustToDust.Core
Dynamic: true));
}
public float SampleHeight(float x, float z)
public float SampleBaseHeight(float x, float z)
{
float half = MapHalfExtent;
float cx = Math.Clamp(x, -half, half);
float cz = Math.Clamp(z, -half, half);
float h = 0f;
if (_sharedU16Heights is not null)
{
int res = HeightmapRes;
float fx = Math.Clamp((cx + half) / HeightmapCellSize, 0f, res - 1f);
float fz = Math.Clamp((cz + half) / HeightmapCellSize, 0f, res - 1f);
int ix = Math.Clamp((int)fx, 0, res - 2);
int iz = Math.Clamp((int)fz, 0, res - 2);
float tx = Math.Clamp(fx - ix, 0f, 1f);
float tz = Math.Clamp(fz - iz, 0f, 1f);
int row0 = iz * res;
int row1 = row0 + res;
float h00 = _baseMinY + _sharedU16Heights[row0 + ix] * _baseScale;
float h10 = _baseMinY + _sharedU16Heights[row0 + ix + 1] * _baseScale;
float h01 = _baseMinY + _sharedU16Heights[row1 + ix] * _baseScale;
float h11 = _baseMinY + _sharedU16Heights[row1 + ix + 1] * _baseScale;
return (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz;
}
if (_heightmap is not null)
{
int res = HeightmapRes;
@ -494,21 +626,194 @@ namespace RustToDust.Core
float h10 = _heightmap[row0 + ix + 1];
float h01 = _heightmap[row1 + ix];
float h11 = _heightmap[row1 + ix + 1];
h = (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz;
return (h00 * (1f - tx) + h10 * tx) * (1f - tz) + (h01 * (1f - tx) + h11 * tx) * tz;
}
WorldToAccelCell(cx, cz, out int acx, out int acz);
var indices = _cellBrushIndices[acz * AccelGridCount + acx];
for (int i = 0; i < indices.Count; i++)
return 0f;
}
public float SampleHeight(float x, float z)
{
float half = MapHalfExtent;
float cx = Math.Clamp(x, -half, half);
float cz = Math.Clamp(z, -half, half);
float h = SampleBaseHeight(cx, cz);
if (_brushes.Count > 0)
{
int idx = indices[i];
var b = _brushes[idx];
h += EvaluateBrushHeightFast(in b, _brushPrecomps[idx], cx, cz);
WorldToAccelCell(cx, cz, out int acx, out int acz);
var indices = _cellBrushIndices[acz * AccelGridCount + acx];
for (int i = 0; i < indices.Count; i++)
{
int idx = indices[i];
var b = _brushes[idx];
h += EvaluateBrushHeightFast(in b, _brushPrecomps[idx], cx, cz);
}
}
return Math.Clamp(h, MapMinHeight, MapMaxHeight);
}
public void ExtractTilePhysicsHeights(int tx, int tz, Span<float> dst, out float minY, out float maxY)
{
if ((uint)tx >= (uint)TileGridCount || (uint)tz >= (uint)TileGridCount)
{
throw new ArgumentOutOfRangeException(nameof(tx));
}
if (!IsHeightmapMode)
{
throw new InvalidOperationException("ExtractTilePhysicsHeights requires heightmap mode.");
}
int samplesPerTile = (HeightmapRes - 1) / TileGridCount;
int side = samplesPerTile + 1;
int count = side * side;
if (dst.Length < count)
{
throw new ArgumentException($"Destination span too small: need {count}, got {dst.Length}.", nameof(dst));
}
int gx0 = tx * samplesPerTile;
int gz0 = tz * samplesPerTile;
var tileBrushes = _tileBrushIndices[tx, tz];
bool hasStructuralBrushes = false;
for (int i = 0; i < tileBrushes.Count; i++)
{
var k = _brushes[tileBrushes[i]].Kind;
if (k != TerrainBrushKind.Track && k != TerrainBrushKind.Scorch)
{
hasStructuralBrushes = true;
break;
}
}
float minVal = float.PositiveInfinity;
float maxVal = float.NegativeInfinity;
float half = MapHalfExtent;
float step = HeightmapCellSize;
int res = HeightmapRes;
for (int lz = 0; lz < side; lz++)
{
int gz = gz0 + lz;
int globalRow = gz * res + gx0;
int localRow = lz * side;
float wz = -half + gz * step;
for (int lx = 0; lx < side; lx++)
{
float h = _sharedU16Heights is not null
? _baseMinY + _sharedU16Heights[globalRow + lx] * _baseScale
: _heightmap![globalRow + lx];
if (hasStructuralBrushes)
{
float wx = -half + (gx0 + lx) * step;
for (int bi = 0; bi < tileBrushes.Count; bi++)
{
int bIdx = tileBrushes[bi];
var b = _brushes[bIdx];
if (b.Kind == TerrainBrushKind.Track || b.Kind == TerrainBrushKind.Scorch)
{
continue;
}
h += EvaluateBrushHeightFast(in b, _brushPrecomps[bIdx], wx, wz);
}
}
float clamped = Math.Clamp(h, MapMinHeight, MapMaxHeight);
dst[localRow + lx] = clamped;
if (clamped < minVal) minVal = clamped;
if (clamped > maxVal) maxVal = clamped;
}
}
if (hasStructuralBrushes)
{
var cached = _scarredTileHeights[tx, tz];
if (cached is null || cached.Length != count)
{
cached = new float[count];
_scarredTileHeights[tx, tz] = cached;
}
dst.Slice(0, count).CopyTo(cached);
}
else
{
_scarredTileHeights[tx, tz] = null;
}
minY = float.IsPositiveInfinity(minVal) ? 0f : minVal;
maxY = float.IsNegativeInfinity(maxVal) ? 0f : maxVal;
}
public void ClearDynamicScars()
{
if (_brushes.Count == 0)
{
return;
}
bool anyDynamic = false;
var staticBrushes = new List<TerrainBrush>(_brushes.Count);
for (int i = 0; i < _brushes.Count; i++)
{
if (_brushes[i].Dynamic)
{
anyDynamic = true;
GetBrushTileBounds(_brushes[i], out int minTx, out int maxTx, out int minTz, out int maxTz);
bool isStructural = _brushes[i].Kind != TerrainBrushKind.Track && _brushes[i].Kind != TerrainBrushKind.Scorch;
for (int tz = minTz; tz <= maxTz; tz++)
{
for (int tx = minTx; tx <= maxTx; tx++)
{
VisualTileVersions[tx, tz]++;
if (isStructural)
{
StructuralTileVersions[tx, tz]++;
}
_scarredTileHeights[tx, tz] = null;
}
}
}
else
{
staticBrushes.Add(_brushes[i]);
}
}
if (!anyDynamic)
{
return;
}
_brushes.Clear();
_brushPrecomps.Clear();
_dynamicDecalSlots.Clear();
for (int tz = 0; tz < TileGridCount; tz++)
{
for (int tx = 0; tx < TileGridCount; tx++)
{
_tileBrushIndices[tx, tz].Clear();
}
}
for (int c = 0; c < AccelCellCount; c++)
{
_cellBrushIndices[c].Clear();
_cellMaxHeight[c] = _cellBaseMaxHeight[c];
}
for (int i = 0; i < staticBrushes.Count; i++)
{
int idx = _brushes.Count;
var b = staticBrushes[i];
_brushes.Add(b);
_brushPrecomps.Add(BrushPrecomp.From(in b));
RegisterBrushInTiles(idx, in b, incrementTileVersion: false);
}
}
public (float Nx, float Ny, float Nz) SampleNormal(float x, float z)
{
const float eps = 0.5f;
@ -723,6 +1028,13 @@ namespace RustToDust.Core
float rim = (0.32f * depth) * rimT * rimT;
return pit + rim;
}
case TerrainBrushKind.Rubble:
{
float env = 1f - r2;
env *= env;
float mound = 0.72f + 0.28f * MathF.Cos(u * MathF.PI * 2.5f);
return b.HeightDelta * env * mound;
}
default:
return 0f;
}
@ -854,6 +1166,12 @@ namespace RustToDust.Core
case TerrainBrushKind.Crater:
cellMaxPositiveHeight = 0.33f * MathF.Abs(b.HeightDelta);
break;
case TerrainBrushKind.Rubble:
{
float env = 1f - minR2;
cellMaxPositiveHeight = MathF.Max(0f, b.HeightDelta) * env * env;
break;
}
default:
cellMaxPositiveHeight = 0f;
break;
@ -889,12 +1207,11 @@ namespace RustToDust.Core
_tileBrushIndices[tx, tz].Add(index);
if (incrementTileVersion)
{
TileVersions[tx, tz]++;
ulong bit = 1UL << (tz * TileGridCount + tx);
DirtyTileMask |= bit;
VisualTileVersions[tx, tz]++;
if (isStructural)
{
StructuralDirtyTileMask |= bit;
StructuralTileVersions[tx, tz]++;
_scarredTileHeights[tx, tz] = null;
}
}
}
@ -928,12 +1245,11 @@ namespace RustToDust.Core
for (int tx = minTx; tx <= maxTx; tx++)
{
_tileBrushIndices[tx, tz].Remove(index);
TileVersions[tx, tz]++;
ulong bit = 1UL << (tz * TileGridCount + tx);
DirtyTileMask |= bit;
VisualTileVersions[tx, tz]++;
if (isStructural)
{
StructuralDirtyTileMask |= bit;
StructuralTileVersions[tx, tz]++;
_scarredTileHeights[tx, tz] = null;
}
}
}
@ -997,8 +1313,8 @@ namespace RustToDust.Core
{
float nx = (x + HalfExtent) / TileSize;
float nz = (z + HalfExtent) / TileSize;
tx = Math.Clamp((int)MathF.Floor(nx), 0, TileGridCount - 1);
tz = Math.Clamp((int)MathF.Floor(nz), 0, TileGridCount - 1);
tx = Math.Clamp((int)MathF.Floor(nx), 0, DesertTileGridCount - 1);
tz = Math.Clamp((int)MathF.Floor(nz), 0, DesertTileGridCount - 1);
}
private static bool IsBrushClearOfCover(in TerrainBrush candidate, IReadOnlyList<ArenaBoxSpec> coverBoxes)

View file

@ -94,6 +94,8 @@ namespace RustToDust.Net
public bool RequestEquipCargo(int cargoIndex, string hardpointId) =>
_host.TryEquipHostCargo(cargoIndex, hardpointId);
public void RepairArenaScars() => _host.RepairArenaScars();
public void RequestNewMatch(int seed, ArenaMapKind mapKind) =>
_host.ResetMatch(seed, mapKind);
@ -114,7 +116,7 @@ namespace RustToDust.Net
public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation)
{
var hit = _host.Session.World.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z));
var hit = _host.Session.CastWorldRayClosest(origin, translation);
return new ClientRayHit(
hit.Hit,
hit.StableId,

View file

@ -52,10 +52,13 @@ namespace RustToDust.Net
private MatchState _viewState;
private Box3DSoaWorld? _predWorld;
private readonly Box3DPhysicsTileSync _predTileSync = new();
private Box3DSoaBodyHandle? _predBody;
private WalkerState? _predWalker;
private string _predChassisId = string.Empty;
public Box3DPhysicsTileSync PredTileSync => _predTileSync;
private Vector3 _predErrorPos;
private Quaternion _predErrorRot = Quaternion.Identity;
private bool _pendingChassisSwapSnap;
@ -518,7 +521,7 @@ namespace RustToDust.Net
var staticHit = _predWorld.CastRayClosest(
(origin.X, origin.Y, origin.Z),
(translation.X, translation.Y, translation.Z));
if (staticHit.Hit && staticHit.StableId < ArenaSession.ContenderStableIdBase)
if (staticHit.Hit && ArenaSession.IsStaticWorldStableId(staticHit.StableId))
{
bestFrac = staticHit.Fraction;
best = new ClientRayHit(
@ -854,6 +857,12 @@ namespace RustToDust.Net
_timeSinceLastPhysicsPodStep = 0f;
_physicsPodSteppingActive = false;
if (dto.PersistentScars is { Length: > 0 })
{
var snap = ArenaScarLedger.DecompressSnapshot(dto.PersistentScars);
_viewState.ApplyPersistentScars(snap);
}
for (int i = 0; i < dto.TerrainStamps.Count; i++)
{
ApplyTerrainStamp(dto.TerrainStamps[i]);
@ -948,12 +957,17 @@ namespace RustToDust.Net
{
_predWorld?.Dispose();
_predWorld = new Box3DSoaWorld(capacity: 256, gravityX: 0f, gravityY: -20f, gravityZ: 0f);
ArenaSession.BuildStaticArena(_predWorld, _viewState);
_predTileSync.Reset();
ArenaSession.BuildStaticArena(_predWorld, _viewState, _predTileSync, warmAllActors: false);
var local = LocalContender;
if (_viewState.Terrain.IsHeightmapMode)
{
_predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1);
}
_predBody = null;
_predWalker = null;
_predChassisId = string.Empty;
var local = LocalContender;
var q = NormalizeQuat(new Quaternion(local.CurrRotX, local.CurrRotY, local.CurrRotZ, local.CurrRotW));
SpawnLocalPredictionBody(new Vector3(local.X, local.Y, local.Z), q, Vector3.Zero, Vector3.Zero);
}
@ -1184,6 +1198,10 @@ namespace RustToDust.Net
ArenaSession.FixedDt,
injectEngineHeat: false,
world: _predWorld);
if (_viewState.Terrain.IsHeightmapMode)
{
_predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1);
}
_predWorld.Step(ArenaSession.FixedDt, subSteps);
ArenaSession.SyncContenderPoseFromLane(local, _predWorld.View, _predBody.Value.Lane, _predWalker);
}
@ -1273,6 +1291,10 @@ namespace RustToDust.Net
local.VelY = pkt.LocalVel.Y;
local.VelZ = pkt.LocalVel.Z;
local.TargetHoverAltAgl = pkt.LocalTargetHoverAltAgl;
if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode)
{
_predTileSync.SyncWindow(_predWorld, _viewState.Terrain, local.X, local.Z, halfTileRadius: 1);
}
SpawnLocalPredictionBody(pkt.LocalPos, pkt.LocalRot, pkt.LocalVel, pkt.LocalAngVel);
if (local.Lifecycle == ContenderLifecycle.Deploying &&
@ -1632,6 +1654,13 @@ namespace RustToDust.Net
case TerrainStampEvent stamp:
ApplyTerrainStamp(stamp);
break;
case ArenaRepairEvent:
_viewState.RepairArenaScars();
if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode)
{
_predTileSync.SyncWindow(_predWorld, _viewState.Terrain, LocalContender.X, LocalContender.Z, halfTileRadius: 1);
}
break;
case DropSpawnedEvent ds:
_viewState.ApplyReplicatedDropSpawned(
ds.DropId, ds.X, ds.Z,
@ -1793,17 +1822,10 @@ namespace RustToDust.Net
private void ApplyTerrainStamp(TerrainStampEvent stamp)
{
switch ((TerrainStampKind)stamp.Kind)
_viewState.ApplyTerrainStamp(stamp, recordInLedger: true);
if (_predWorld is not null && _viewState.Terrain.IsHeightmapMode)
{
case TerrainStampKind.Crater:
_viewState.Terrain.StampCrater(stamp.X, stamp.Z, stamp.Radius, stamp.Depth);
break;
case TerrainStampKind.Scorch:
_viewState.Terrain.StampScorch(stamp.X, stamp.Z, stamp.Radius);
break;
case TerrainStampKind.Track:
_viewState.Terrain.StampTrack(stamp.X, stamp.Z, stamp.Yaw, stamp.Radius, stamp.Length);
break;
_predTileSync.SyncWindow(_predWorld, _viewState.Terrain, LocalContender.X, LocalContender.Z, halfTileRadius: 1);
}
}

View file

@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Numerics;
@ -32,6 +33,8 @@ namespace RustToDust.Net
public readonly HashSet<int> SentDropIds = new();
public readonly HashSet<int> SentPodIds = new();
public readonly HashSet<int> SentOrdnanceIds = new();
public readonly HashSet<int> SentTerrainStampIndices = new();
public readonly int[,] SentTileVersions = new int[16, 16];
}
private struct EntityPvsTracker
@ -51,6 +54,11 @@ namespace RustToDust.Net
private readonly List<ISimEvent> _stepEvents = new();
private readonly List<ISimEvent> _hostPendingEvents = new();
private readonly List<TerrainStampEvent> _terrainStampHistory = new();
private readonly List<int>[,] _tileStampHistory = new List<int>[16, 16];
private readonly string? _configuredScarPath;
private readonly ArenaMapKind _initialMapKind;
private readonly bool _persistScars;
private readonly Dictionary<ArenaMapKind, ArenaScarLedgerSnapshot> _inMemoryScarsByMap = new();
private readonly int _maxHumans;
private readonly double _autoRestartSec;
private readonly bool _allowClientReset;
@ -72,6 +80,7 @@ namespace RustToDust.Net
private uint _nextPeerId = 1;
private float _roundCompletedElapsed;
private int _lastBroadcastCountdownSec = -1;
private uint _lastScarSaveTick;
private bool _disposed;
public ServerMatchHost(
@ -87,7 +96,10 @@ namespace RustToDust.Net
string serverName = "Rust to Dust",
int minHumansToStart = 1,
bool restartToLobby = false,
byte squadSize = 1)
byte squadSize = 1,
string? scarFilePath = null,
bool persistScars = false,
bool repairScarsOnStart = false)
{
_maxHumans = Math.Clamp(maxHumans, 1, MatchState.ContenderCount);
_autoRestartSec = autoRestartSec;
@ -97,6 +109,16 @@ namespace RustToDust.Net
_minHumansToStart = Math.Clamp(minHumansToStart, 1, _maxHumans);
_restartToLobby = restartToLobby;
_squadSize = (byte)Math.Clamp((int)squadSize, 1, 4);
_persistScars = persistScars;
_configuredScarPath = scarFilePath;
_initialMapKind = mapKind;
for (int tz = 0; tz < 16; tz++)
{
for (int tx = 0; tx < 16; tx++)
{
_tileStampHistory[tx, tz] = new List<int>(4);
}
}
_socket = new Socket(bindAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp)
{
@ -117,7 +139,23 @@ namespace RustToDust.Net
});
_server.PeerDisconnected += OnTransportPeerDisconnected;
_session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize);
ArenaScarLedgerSnapshot? initialScars = null;
string? initScarPath = _persistScars ? ResolveScarFilePath(_configuredScarPath, _initialMapKind, mapKind) : null;
if (_persistScars && initScarPath is not null)
{
string fp = GetAssetFingerprint(seed, mapKind);
if (repairScarsOnStart)
{
var emptySnap = new ArenaScarLedgerSnapshot { AssetFingerprint = fp };
ArenaScarLedgerStore.Save(initScarPath, emptySnap);
}
else
{
initialScars = ArenaScarLedgerStore.Load(initScarPath, fp);
}
}
_session = new ArenaSession(seed, mapKind, slot0Human: hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize, initialScars: initialScars);
if (hostContenderId.HasValue)
{
_session.SetHumanSlot(hostContenderId.Value, true, "Host");
@ -170,19 +208,65 @@ namespace RustToDust.Net
public void ResetMatch(int seed, ArenaMapKind mapKind) =>
ResetMatch(seed, mapKind, startInLobby: false);
public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby)
public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby) =>
ResetMatch(seed, mapKind, startInLobby, repairScars: false);
public void ResetMatch(int seed, ArenaMapKind mapKind, bool startInLobby, bool repairScars)
{
if (_hostContenderId.HasValue && _hostContenderId.Value >= 0 && _hostContenderId.Value < _session.State.Contenders.Count)
{
_hostCallsign = _session.State.Contenders[_hostContenderId.Value].Name;
}
ArenaMapKind prevMapKind = _session.State.MapKind;
if (repairScars && mapKind == prevMapKind)
{
_session.State.RepairArenaScars();
_inMemoryScarsByMap.Remove(mapKind);
}
_inMemoryScarsByMap[prevMapKind] = _session.State.ScarLedger.ToSnapshot();
FlushScarLedgerIfDirty();
ArenaScarLedgerSnapshot? preservedScars = null;
if (mapKind == prevMapKind)
{
preservedScars = _session.State.ScarLedger.ToSnapshot();
}
else if (repairScars)
{
_inMemoryScarsByMap.Remove(mapKind);
if (_persistScars)
{
string targetPath = ResolveScarFilePath(_configuredScarPath, _initialMapKind, mapKind);
if (!string.IsNullOrWhiteSpace(targetPath))
{
var emptySnap = new ArenaScarLedgerSnapshot { AssetFingerprint = GetAssetFingerprint(seed, mapKind) };
ArenaScarLedgerStore.Save(targetPath, emptySnap);
}
}
}
else
{
string expectedFp = GetAssetFingerprint(seed, mapKind);
if (_inMemoryScarsByMap.TryGetValue(mapKind, out var memScars) &&
string.Equals(memScars.AssetFingerprint, expectedFp, StringComparison.Ordinal))
{
preservedScars = memScars;
}
else if (_persistScars)
{
string targetPath = ResolveScarFilePath(_configuredScarPath, _initialMapKind, mapKind);
preservedScars = ArenaScarLedgerStore.Load(targetPath, expectedFp);
}
}
_session.Dispose();
_session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize);
_session = new ArenaSession(seed, mapKind, slot0Human: _hostContenderId == 0, startInLobby: startInLobby, squadSize: _squadSize, initialScars: preservedScars);
_matchGeneration++;
_simTick = 0;
_roundCompletedElapsed = 0f;
_lastBroadcastCountdownSec = -1;
_terrainStampHistory.Clear();
ClearTileStampHistory();
_stepEvents.Clear();
_hostPendingEvents.Clear();
_reconnectTokens.Clear();
@ -588,12 +672,19 @@ namespace RustToDust.Net
{
if (_stepEvents[i] is TerrainStampEvent ts)
{
int stampIdx = _terrainStampHistory.Count;
_terrainStampHistory.Add(ts);
_session.State.Terrain.MapWorldToTile(ts.X, ts.Z, out int tx, out int tz);
_tileStampHistory[tx, tz].Add(stampIdx);
}
}
FlushEventsAndPvsEnter();
BroadcastSnapshots();
if (_persistScars && (_simTick - _lastScarSaveTick) >= 1800)
{
FlushScarLedgerIfDirty();
}
try
{
_server.PollResends();
@ -700,6 +791,16 @@ namespace RustToDust.Net
}
}
break;
case RepairArenaCmdMsg:
if (_peersByEndpoint.TryGetValue(epKey, out var repPeer) && repPeer.Active && ReferenceEquals(repPeer.TransportPeer, transportPeer))
{
repPeer.LastHeardUtcMs = nowUtcMs;
if (_allowClientReset || (_hostContenderId.HasValue && _hostContenderId.Value == repPeer.AssignedContenderId))
{
RepairArenaScars();
}
}
break;
case InteractCmdMsg interactCmd:
if (_peersByEndpoint.TryGetValue(epKey, out var intPeer) && intPeer.Active && ReferenceEquals(intPeer.TransportPeer, transportPeer))
{
@ -996,6 +1097,20 @@ namespace RustToDust.Net
}
peer.SentPodIds.Clear();
peer.SentOrdnanceIds.Clear();
peer.SentTerrainStampIndices.Clear();
Array.Clear(peer.SentTileVersions);
for (int i = 0; i < _terrainStampHistory.Count; i++)
{
peer.SentTerrainStampIndices.Add(i);
}
var terrain = _session.State.Terrain;
for (int tz = 0; tz < terrain.TileGridCount; tz++)
{
for (int tx = 0; tx < terrain.TileGridCount; tx++)
{
peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz];
}
}
var activePods = _session.State.OrbitalDrop.ActivePods;
for (int i = 0; i < activePods.Count; i++)
{
@ -1187,11 +1302,9 @@ namespace RustToDust.Net
: new DropPickedUpEvent { DropId = dp.DropId, ContenderId = -1 });
}
break;
case TerrainStampEvent stamp:
if (_session.IsPointInPeerPvs(obsId, stamp.X, _session.State.Terrain.SampleHeight(stamp.X, stamp.Z) + 0.5f, stamp.Z))
{
filtered.Add(stamp);
}
case TerrainStampEvent:
// Delivered via 576m local geometry bubble sync below so distant live fire is never leaked
// while _predWorld stays 1:1 physics-synchronized before the player enters tile range.
break;
case OverheatAlertEvent oh:
if (oh.ContenderId == obsId)
@ -1306,6 +1419,8 @@ namespace RustToDust.Net
}
}
SyncPeerLocalGeometryBubble(peer, obsId, filtered);
if (enteredPvsMask != 0)
{
var activePods = _session.State.OrbitalDrop.ActivePods;
@ -1753,13 +1868,10 @@ namespace RustToDust.Net
});
}
for (int i = 0; i < _terrainStampHistory.Count; i++)
var scarSnap = _session.State.ScarLedger.ToSnapshot();
if (scarSnap.Terrain.Count > 0 || scarSnap.Buildings.Count > 0 || scarSnap.Trees.Count > 0)
{
var ts = _terrainStampHistory[i];
if (_session.IsPointInPeerPvs(forContenderId, ts.X, _session.State.Terrain.SampleHeight(ts.X, ts.Z) + 0.5f, ts.Z))
{
dto.TerrainStamps.Add(ts);
}
dto.PersistentScars = ArenaScarLedger.CompressSnapshot(scarSnap);
}
for (int i = 0; i < _session.State.Contenders.Count; i++)
@ -1865,10 +1977,166 @@ namespace RustToDust.Net
}
}
public void RepairArenaScars()
{
_session.RepairArenaScars();
_inMemoryScarsByMap.Remove(_session.State.MapKind);
_terrainStampHistory.Clear();
ClearTileStampHistory();
FlushScarLedgerIfDirty();
uint rev = _session.State.ScarLedger.LedgerRevision;
var repairEv = new ArenaRepairEvent { LedgerRevision = rev };
if (_hostContenderId.HasValue)
{
_hostPendingEvents.Add(repairEv);
}
foreach (var peer in _peersByEndpoint.Values)
{
if (!peer.Active) continue;
peer.SentTerrainStampIndices.Clear();
Array.Clear(peer.SentTileVersions);
SendSchemaToPeer(peer, new SimEventBatchMsg
{
BatchSeq = _eventBatchSeq++,
SimTick = _simTick,
SimTime = _session.State.Time,
MatchGeneration = _matchGeneration,
Events = new List<ISimEvent> { repairEv }
});
}
}
private void SyncPeerLocalGeometryBubble(ConnectedPeer peer, int obsId, List<ISimEvent> filtered)
{
if (_terrainStampHistory.Count == 0 || obsId < 0 || obsId >= _session.State.Contenders.Count)
{
return;
}
var obs = _session.State.Contenders[obsId];
var terrain = _session.State.Terrain;
terrain.MapWorldToTile(obs.X, obs.Z, out int cx, out int cz);
int grid = terrain.TileGridCount;
int minTx = Math.Max(0, cx - 4);
int maxTx = Math.Min(grid - 1, cx + 4);
int minTz = Math.Max(0, cz - 4);
int maxTz = Math.Min(grid - 1, cz + 4);
const float bubbleRadiusSq = 576f * 576f;
for (int tz = minTz; tz <= maxTz; tz++)
{
for (int tx = minTx; tx <= maxTx; tx++)
{
var list = _tileStampHistory[tx, tz];
if (list.Count == 0)
{
peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz];
continue;
}
bool allSent = true;
for (int i = 0; i < list.Count; i++)
{
int stampIdx = list[i];
if (peer.SentTerrainStampIndices.Contains(stampIdx))
{
continue;
}
var ts = _terrainStampHistory[stampIdx];
float dx = obs.X - ts.X;
float dz = obs.Z - ts.Z;
if (dx * dx + dz * dz <= bubbleRadiusSq)
{
peer.SentTerrainStampIndices.Add(stampIdx);
filtered.Add(ts);
}
else
{
allSent = false;
}
}
if (allSent)
{
peer.SentTileVersions[tx, tz] = terrain.VisualTileVersions[tx, tz];
}
}
}
}
private void ClearTileStampHistory()
{
for (int tz = 0; tz < 16; tz++)
{
for (int tx = 0; tx < 16; tx++)
{
_tileStampHistory[tx, tz].Clear();
}
}
}
public static string ResolveScarFilePath(string? configuredPath, ArenaMapKind initialMapKind, ArenaMapKind targetMapKind)
{
if (string.IsNullOrWhiteSpace(configuredPath))
{
return ArenaScarLedgerStore.GetDefaultPath(targetMapKind);
}
string mapTag = targetMapKind == ArenaMapKind.Sion ? "sion" : "desert";
if (configuredPath.EndsWith(Path.DirectorySeparatorChar) ||
configuredPath.EndsWith(Path.AltDirectorySeparatorChar) ||
Directory.Exists(configuredPath))
{
return Path.Combine(configuredPath, $"{mapTag}_scars_default.cultcache");
}
if (targetMapKind == initialMapKind)
{
return configuredPath;
}
string dir = Path.GetDirectoryName(configuredPath) ?? ".";
string fileName = Path.GetFileName(configuredPath);
string initTag = initialMapKind == ArenaMapKind.Sion ? "sion" : "desert";
if (fileName.StartsWith(initTag + "_", StringComparison.OrdinalIgnoreCase))
{
return Path.Combine(dir, mapTag + fileName.Substring(initTag.Length));
}
string stem = Path.GetFileNameWithoutExtension(fileName);
string ext = Path.GetExtension(fileName);
return Path.Combine(dir, $"{stem}.{mapTag}{ext}");
}
private static string GetAssetFingerprint(int seed, ArenaMapKind mapKind) =>
mapKind == ArenaMapKind.Sion ? SionMapLoader.Load().AssetFingerprint : $"desert:{seed}";
private void FlushScarLedgerIfDirty()
{
if (!_persistScars)
{
return;
}
string scarPath = ResolveScarFilePath(_configuredScarPath, _initialMapKind, _session.State.MapKind);
if (string.IsNullOrWhiteSpace(scarPath))
{
return;
}
if (!_session.State.ScarLedger.IsDirty && File.Exists(scarPath))
{
return;
}
ArenaScarLedgerStore.Save(scarPath, _session.State.ScarLedger.ToSnapshot());
_session.State.ScarLedger.IsDirty = false;
_lastScarSaveTick = _simTick;
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
FlushScarLedgerIfDirty();
_server.PeerDisconnected -= OnTransportPeerDisconnected;
_server.Dispose();
_socket.Dispose();

View file

@ -28,6 +28,9 @@ namespace RustToDust.Server
int minHumansToStart = TryParseInt(Environment.GetEnvironmentVariable("RTD_MIN_HUMANS"), 1);
bool restartToLobby = TryParseBool(Environment.GetEnvironmentVariable("RTD_RESTART_TO_LOBBY"), false);
int squadSize = Math.Clamp(TryParseInt(Environment.GetEnvironmentVariable("RTD_SQUAD_SIZE"), 3), 1, 4);
string? scarFilePath = Environment.GetEnvironmentVariable("RTD_SCAR_FILE");
bool persistScars = TryParseBool(Environment.GetEnvironmentVariable("RTD_PERSIST_SCARS"), true);
bool repairScars = false;
for (int i = 0; i < args.Length; i++)
{
@ -61,6 +64,10 @@ namespace RustToDust.Server
else if (a == "--restart-to-lobby") restartToLobby = true;
else if (a == "--squad-size" && i + 1 < args.Length) squadSize = Math.Clamp(TryParseInt(args[++i], squadSize), 1, 4);
else if (a.StartsWith("--squad-size=", StringComparison.Ordinal)) squadSize = Math.Clamp(TryParseInt(a.Substring("--squad-size=".Length), squadSize), 1, 4);
else if (a == "--scar-file" && i + 1 < args.Length) scarFilePath = args[++i];
else if (a.StartsWith("--scar-file=", StringComparison.Ordinal)) scarFilePath = a.Substring("--scar-file=".Length);
else if (a == "--no-persist-scars") persistScars = false;
else if (a == "--repair-scars") repairScars = true;
}
if (!IPAddress.TryParse(bindStr, out var bindIp))
@ -99,7 +106,10 @@ namespace RustToDust.Server
serverName: serverName,
minHumansToStart: minHumansToStart,
restartToLobby: restartToLobby,
squadSize: (byte)squadSize);
squadSize: (byte)squadSize,
scarFilePath: scarFilePath,
persistScars: persistScars,
repairScarsOnStart: repairScars);
host.LogMessage += msg => Console.WriteLine(msg);
static DirectoryHeartbeatSnapshot BuildSnapshot(ServerMatchHost h, string hostAddr) =>

View file

@ -11,7 +11,7 @@ namespace RustToDust.Ymir
{
public const float FixedDt = 1f / 60f;
public const int SubStepCount = 4;
public const int WorldBodyCapacity = 384;
public const int WorldBodyCapacity = 1024;
private const ulong GroundStableId = 1;
private const ulong StaticBoxStableIdBase = 10;
@ -20,6 +20,7 @@ namespace RustToDust.Ymir
private const ulong SpectatorStableIdBase = 3000;
private readonly Box3DSoaWorld _world;
private readonly Box3DPhysicsTileSync _tileSync = new();
private readonly Dictionary<int, Box3DSoaBodyHandle> _contenderBodies = new();
private readonly Dictionary<int, Box3DSoaBodyHandle> _spectatorBodies = new();
private readonly Dictionary<int, WalkerState> _contenderWalkers = new();
@ -35,9 +36,9 @@ namespace RustToDust.Ymir
private long _forwardedPodEventId;
private bool _disposed;
public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false, bool startInLobby = false, byte squadSize = 1)
public ArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, bool slot0Human = false, bool skipInitialDrop = false, bool startInLobby = false, byte squadSize = 1, ArenaScarLedgerSnapshot? initialScars = null)
{
State = new MatchState(seed, mapKind, skipInitialDrop, startInLobby, squadSize);
State = new MatchState(seed, mapKind, skipInitialDrop, startInLobby, squadSize, initialScars);
Ordnance = new OrdnanceRuntime(this);
_spectatorPvs = new bool[MatchState.ContenderCount, State.Spectators.Spectators.Count];
_forwardedPodEventId = State.PodEvents.Count > 0 ? State.PodEvents[^1].EventId : 0;
@ -73,7 +74,7 @@ namespace RustToDust.Ymir
gravityY: -20f,
gravityZ: 0f);
BuildStaticArena(_world, State);
BuildStaticArena(_world, State, _tileSync, warmAllActors: true);
SpawnContenderBodies();
SpawnSpectatorBodies();
UpdateObserverDetectionMemories();
@ -91,8 +92,37 @@ namespace RustToDust.Ymir
public MatchState State { get; }
public OrdnanceRuntime Ordnance { get; }
public Box3DSoaWorld World => _world;
public Box3DPhysicsTileSync TileSync => _tileSync;
public bool EnableNetworkPvs { get; set; } = true;
public void RepairArenaScars()
{
State.RepairArenaScars();
if (State.Terrain.IsHeightmapMode)
{
int dirtyResidentCount = _tileSync.CountDirtyResidentTiles(State.Terrain);
if (dirtyResidentCount > 0)
{
int budget = _world.FreeBodySlots >= dirtyResidentCount + 32
? dirtyResidentCount
: 4;
_tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: budget);
}
}
}
public static bool IsStaticWorldStableId(ulong stableId) =>
stableId < ContenderStableIdBase || stableId >= Box3DPhysicsTileSync.HeightfieldTileStableIdBase;
public static bool IsStaticBuildingOrCoverStableId(ulong stableId) =>
(stableId >= StaticMeshStableIdBase && stableId < ContenderStableIdBase) ||
(stableId >= Box3DPhysicsTileSync.BuildingTileStableIdBase && stableId < Box3DPhysicsTileSync.TreeTileStableIdBase);
public Box3DSoaRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation)
{
return _world.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z));
}
public void SetHumanSlot(int contenderId, bool isHuman, string? callsign = null)
{
if (contenderId < 0 || contenderId >= State.Contenders.Count)
@ -322,6 +352,10 @@ namespace RustToDust.Ymir
_contenderBodies.Remove(contenderId);
}
_contenderWalkers.Remove(contenderId);
if (State.Terrain.IsHeightmapMode)
{
_tileSync.EnsureTileRegion(_world, State.Terrain, x, z, halfTileRadius: 1);
}
if (c.IsGroundedActive)
{
SpawnContenderBody(c);
@ -519,7 +553,7 @@ namespace RustToDust.Ymir
{
break;
}
if (hit.StableId < ContenderStableIdBase)
if (IsStaticWorldStableId(hit.StableId))
{
return false;
}
@ -659,6 +693,7 @@ namespace RustToDust.Ymir
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight);
State.OrbitalDrop.Step(FixedDt, QueryDropSurface, OnPodTouchedDown);
EnsureActivePhysicsTilesAndFlush();
ApplyPhysicsDrives();
_world.Step(FixedDt, subSteps);
SyncBodiesFromWorld();
@ -679,6 +714,7 @@ namespace RustToDust.Ymir
MatchRules.UpdateAiContenders(State, FixedDt, HasLineOfSight);
State.OrbitalDrop.Step(FixedDt, QueryDropSurface, OnPodTouchedDown);
long t2 = Stopwatch.GetTimestamp();
EnsureActivePhysicsTilesAndFlush();
ApplyPhysicsDrives();
long t3 = Stopwatch.GetTimestamp();
_world.Step(FixedDt, subSteps);
@ -734,23 +770,17 @@ namespace RustToDust.Ymir
return true;
}
public static void BuildStaticArena(Box3DSoaWorld world, MatchState state)
public static void BuildStaticArena(Box3DSoaWorld world, MatchState state, Box3DPhysicsTileSync? tileSync = null, bool warmAllActors = true)
{
if (state.MapKind == ArenaMapKind.Sion && state.SionMap is { } sion)
{
var meta = sion.Metadata;
float half = state.Terrain.MapHalfExtent;
world.AddStaticHeightField(
GroundStableId,
(-half, 0f, -half),
sion.Heights,
meta.GridRes,
meta.GridRes,
(meta.CellSizeMeters, 1.0f, meta.CellSizeMeters),
meta.MinY - 2f,
meta.MaxY + 2f,
friction: 0.15f,
restitution: 0.0f);
if (tileSync is not null && warmAllActors && state.Terrain.IsHeightmapMode)
{
Span<bool> needed = stackalloc bool[Box3DPhysicsTileSync.MaxTiles];
Span<bool> immediate = stackalloc bool[Box3DPhysicsTileSync.MaxTiles];
MarkPhysicsOccupancyTiles(state, needed, immediate);
tileSync.SyncNeededTiles(world, state.Terrain, needed, immediate);
}
ulong boxId = StaticBoxStableIdBase;
for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++)
@ -833,6 +863,17 @@ namespace RustToDust.Ymir
_contenderWalkers.Remove(c.Id);
if (c.IsGroundedActive)
{
if (State.Terrain.IsHeightmapMode)
{
if (c.IsHuman)
{
_tileSync.EnsureTileRegion(_world, State.Terrain, c.X, c.Z, halfTileRadius: 1);
}
else
{
_tileSync.EnsureTileRegion(_world, State.Terrain, c.X, c.Z, halfTileRadius: 0);
}
}
SpawnContenderBody(c);
}
}
@ -886,8 +927,77 @@ namespace RustToDust.Ymir
}
}
public DropSurfaceSample QueryDropSurface(float x, float z, float footRadius, float referenceMaxY) =>
QueryDropSurface(State, _world, x, z, footRadius, referenceMaxY);
private static void MarkPhysicsOccupancyTiles(MatchState state, Span<bool> needed, Span<bool> immediate = default)
{
needed.Clear();
if (!immediate.IsEmpty)
{
immediate.Clear();
}
var terrain = state.Terrain;
for (int i = 0; i < state.Contenders.Count; i++)
{
var c = state.Contenders[i];
if (!c.IsGroundedActive)
{
continue;
}
if (!immediate.IsEmpty)
{
Box3DPhysicsTileSync.MarkTileFootprint(terrain, immediate, c.X, c.Z, marginMeters: 0f);
}
if (c.IsHuman)
{
Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, c.X, c.Z, marginMeters: 28f);
}
else
{
Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, c.X, c.Z, marginMeters: 16f);
}
}
for (int i = 0; i < state.Spectators.Spectators.Count; i++)
{
var s = state.Spectators.Spectators[i];
if (s.Alive && s.Stance != SpectatorStance.Neutral)
{
if (!immediate.IsEmpty)
{
Box3DPhysicsTileSync.MarkTileFootprint(terrain, immediate, s.X, s.Z, marginMeters: 0f);
}
Box3DPhysicsTileSync.MarkTileFootprint(terrain, needed, s.X, s.Z, marginMeters: 8f);
}
}
for (int i = 0; i < state.OrbitalDrop.ActivePods.Count; i++)
{
var pod = state.OrbitalDrop.ActivePods[i];
if (pod.Y - terrain.SampleHeight(pod.X, pod.Z) <= 80f)
{
if (!immediate.IsEmpty)
{
Box3DPhysicsTileSync.MarkTileRegion(terrain, immediate, pod.X, pod.Z, halfTileRadius: 0);
}
Box3DPhysicsTileSync.MarkTileRegion(terrain, needed, pod.X, pod.Z, halfTileRadius: 0);
}
}
}
private void EnsureActivePhysicsTilesAndFlush()
{
if (!State.Terrain.IsHeightmapMode)
{
return;
}
Span<bool> needed = stackalloc bool[Box3DPhysicsTileSync.MaxTiles];
Span<bool> immediate = stackalloc bool[Box3DPhysicsTileSync.MaxTiles];
MarkPhysicsOccupancyTiles(State, needed, immediate);
_tileSync.SyncNeededTiles(_world, State.Terrain, needed, immediate, maxNewPrefetchPerTick: 1);
_tileSync.FlushDirtyHeightfields(_world, State.Terrain, maxTilesPerTick: 4);
}
public DropSurfaceSample QueryDropSurface(float x, float z, float footRadius, float referenceMaxY)
{
return QueryDropSurface(State, _world, x, z, footRadius, referenceMaxY);
}
public static DropSurfaceSample QueryDropSurface(
MatchState state,
@ -1430,7 +1540,8 @@ namespace RustToDust.Ymir
Vector3 toGoal = new Vector3(goalX - pos.X, 0f, goalZ - pos.Z);
float dist = toGoal.Length();
// On Sion, StaticHeightField supports settled Neutral Patrons/Exemplars directly so Box3D can sleep them.
// On Sion, StaticHeightField supports settled Neutral Patrons/Exemplars directly so Box3D can sleep them,
// provided the underlying heightfield tile is currently resident.
if (State.MapKind == ArenaMapKind.Sion &&
s.Stance == SpectatorStance.Neutral &&
s.Tier != SpectatorTier.Tourist &&
@ -1439,13 +1550,17 @@ namespace RustToDust.Ymir
angVel.LengthSquared() < 0.09f &&
up.Y > 0.90f)
{
view.ForceX[lane] = 0f;
view.ForceY[lane] = 0f;
view.ForceZ[lane] = 0f;
view.TorqueX[lane] = 0f;
view.TorqueY[lane] = 0f;
view.TorqueZ[lane] = 0f;
continue;
State.Terrain.MapWorldToTile(pos.X, pos.Z, out int stx, out int stz);
if (_tileSync.TryGetResidentHandle(stx, stz, State.Terrain.TileGridCount, out _))
{
view.ForceX[lane] = 0f;
view.ForceY[lane] = 0f;
view.ForceZ[lane] = 0f;
view.TorqueX[lane] = 0f;
view.TorqueY[lane] = 0f;
view.TorqueZ[lane] = 0f;
continue;
}
}
Vector3 desiredVel = dist > 0.5f ? Vector3.Normalize(toGoal) * MathF.Min(s.MaxSpeed, dist * 1.5f) : Vector3.Zero;
@ -3001,11 +3116,13 @@ namespace RustToDust.Ymir
State.SpawnModuleDrop(victim.X + (i - 1) * 0.9f, victim.Z + 1.2f, victim.Grid.Mounted[i].Spec);
}
State.Terrain.StampCrater(victim.X, victim.Z, radius: 5.2f, depth: 1.3f);
State.Terrain.StampScorch(victim.X, victim.Z, radius: 6.2f);
var craterEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = victim.X, Z = victim.Z, Radius = 5.2f, Depth = 1.3f };
var scorchEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = victim.X, Z = victim.Z, Radius = 6.2f };
State.ApplyTerrainStamp(craterEv, recordInLedger: true);
State.ApplyTerrainStamp(scorchEv, recordInLedger: true);
State.OrbitalDrop.OnContenderEliminated(victim);
_stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = victim.X, Z = victim.Z, Radius = 5.2f, Depth = 1.3f });
_stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = victim.X, Z = victim.Z, Radius = 6.2f });
_stepEvents.Add(craterEv);
_stepEvents.Add(scorchEv);
_stepEvents.Add(new ContenderEliminatedEvent
{
VictimId = victim.Id,
@ -3037,10 +3154,12 @@ namespace RustToDust.Ymir
State.SpawnModuleDrop(spec.X + (i - 0.5f) * 1.1f, spec.Z, drops[i]);
}
State.Terrain.StampCrater(spec.X, spec.Z, radius: 4.5f, depth: 1.1f);
State.Terrain.StampScorch(spec.X, spec.Z, radius: 5.4f);
_stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = spec.X, Z = spec.Z, Radius = 4.5f, Depth = 1.1f });
_stepEvents.Add(new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = spec.X, Z = spec.Z, Radius = 5.4f });
var specCraterEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Crater, X = spec.X, Z = spec.Z, Radius = 4.5f, Depth = 1.1f };
var specScorchEv = new TerrainStampEvent { Kind = (byte)TerrainStampKind.Scorch, X = spec.X, Z = spec.Z, Radius = 5.4f };
State.ApplyTerrainStamp(specCraterEv, recordInLedger: true);
State.ApplyTerrainStamp(specScorchEv, recordInLedger: true);
_stepEvents.Add(specCraterEv);
_stepEvents.Add(specScorchEv);
_stepEvents.Add(new SpectatorDestroyedEvent
{
SpectatorId = spec.Id,
@ -3304,26 +3423,28 @@ namespace RustToDust.Ymir
{
if (craterRadius > 0f && craterDepth > 0f)
{
State.Terrain.StampCrater(x, z, radius: craterRadius, depth: craterDepth);
_stepEvents.Add(new TerrainStampEvent
var ev = new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = x,
Z = z,
Radius = craterRadius,
Depth = craterDepth
});
};
State.ApplyTerrainStamp(ev, recordInLedger: true);
_stepEvents.Add(ev);
}
if (scorchRadius > 0f)
{
State.Terrain.StampScorch(x, z, radius: scorchRadius);
_stepEvents.Add(new TerrainStampEvent
var ev = new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Scorch,
X = x,
Z = z,
Radius = scorchRadius
});
};
State.ApplyTerrainStamp(ev, recordInLedger: true);
_stepEvents.Add(ev);
}
}

View file

@ -0,0 +1,429 @@
using System;
using RustToDust.Core;
using Ymir.Box3D;
namespace RustToDust.Ymir
{
public sealed class Box3DPhysicsTileSync
{
public const ulong HeightfieldTileStableIdBase = 10_000;
public const ulong BuildingTileStableIdBase = 11_000;
public const ulong TreeTileStableIdBase = 12_000;
public const int MaxTiles = 256;
private readonly Box3DSoaBodyHandle[] _residentHandles = new Box3DSoaBodyHandle[MaxTiles];
private readonly bool[] _residentFlags = new bool[MaxTiles];
private readonly int[] _syncedStructuralVersions = new int[MaxTiles];
private float[]? _scratchHeights;
public static bool IsHeightfieldTileStableId(ulong stableId) =>
stableId >= HeightfieldTileStableIdBase && stableId < HeightfieldTileStableIdBase + MaxTiles;
public int ResidentTileCount { get; private set; }
public bool TryGetResidentHandle(int tx, int tz, int tileGridCount, out Box3DSoaBodyHandle handle)
{
if ((uint)tx < (uint)tileGridCount && (uint)tz < (uint)tileGridCount)
{
int idx = tz * tileGridCount + tx;
if (_residentFlags[idx])
{
handle = _residentHandles[idx];
return true;
}
}
handle = default;
return false;
}
public void Reset()
{
Array.Clear(_residentHandles);
Array.Clear(_residentFlags);
Array.Clear(_syncedStructuralVersions);
ResidentTileCount = 0;
}
public bool EnsureTileResident(Box3DSoaWorld world, TerrainField terrain, int tx, int tz)
{
if (!terrain.IsHeightmapMode)
{
return false;
}
int grid = terrain.TileGridCount;
if ((uint)tx >= (uint)grid || (uint)tz >= (uint)grid)
{
return false;
}
int idx = tz * grid + tx;
int curVer = terrain.StructuralTileVersions[tx, tz];
if (_residentFlags[idx] && _syncedStructuralVersions[idx] == curVer)
{
return false;
}
int samplesPerTile = (terrain.HeightmapRes - 1) / grid;
int side = samplesPerTile + 1;
int sampleCount = side * side;
if (_scratchHeights is null || _scratchHeights.Length < sampleCount)
{
_scratchHeights = new float[sampleCount];
}
terrain.ExtractTilePhysicsHeights(tx, tz, _scratchHeights, out float minY, out float maxY);
if (_residentFlags[idx])
{
world.RemoveBody(_residentHandles[idx]);
ResidentTileCount--;
_residentFlags[idx] = false;
}
float originX = -terrain.MapHalfExtent + tx * terrain.MapTileSize;
float originZ = -terrain.MapHalfExtent + tz * terrain.MapTileSize;
ulong stableId = HeightfieldTileStableIdBase + (ulong)idx;
var handle = world.AddStaticHeightField(
stableId,
(originX, 0f, originZ),
_scratchHeights.AsSpan(0, sampleCount),
side,
side,
(terrain.HeightmapCellSize, 1.0f, terrain.HeightmapCellSize),
minY - 2f,
maxY + 2f,
friction: 0.15f,
restitution: 0.0f);
_residentHandles[idx] = handle;
_residentFlags[idx] = true;
_syncedStructuralVersions[idx] = curVer;
ResidentTileCount++;
return true;
}
public void EnsureTileRegion(Box3DSoaWorld world, TerrainField terrain, float worldX, float worldZ, int halfTileRadius)
{
if (!terrain.IsHeightmapMode)
{
return;
}
terrain.MapWorldToTile(worldX, worldZ, out int cx, out int cz);
int grid = terrain.TileGridCount;
int minTx = Math.Max(0, cx - halfTileRadius);
int maxTx = Math.Min(grid - 1, cx + halfTileRadius);
int minTz = Math.Max(0, cz - halfTileRadius);
int maxTz = Math.Min(grid - 1, cz + halfTileRadius);
for (int tz = minTz; tz <= maxTz; tz++)
{
for (int tx = minTx; tx <= maxTx; tx++)
{
EnsureTileResident(world, terrain, tx, tz);
}
}
}
public static void MarkTileRegion(TerrainField terrain, Span<bool> needed, float worldX, float worldZ, int halfTileRadius)
{
if (!terrain.IsHeightmapMode)
{
return;
}
terrain.MapWorldToTile(worldX, worldZ, out int cx, out int cz);
int grid = terrain.TileGridCount;
int minTx = Math.Max(0, cx - halfTileRadius);
int maxTx = Math.Min(grid - 1, cx + halfTileRadius);
int minTz = Math.Max(0, cz - halfTileRadius);
int maxTz = Math.Min(grid - 1, cz + halfTileRadius);
for (int tz = minTz; tz <= maxTz; tz++)
{
for (int tx = minTx; tx <= maxTx; tx++)
{
needed[tz * grid + tx] = true;
}
}
}
public static void MarkTileFootprint(TerrainField terrain, Span<bool> needed, float worldX, float worldZ, float marginMeters)
{
if (!terrain.IsHeightmapMode)
{
return;
}
float half = terrain.MapHalfExtent;
float r = MathF.Max(0f, marginMeters);
terrain.MapWorldToTile(Math.Clamp(worldX - r, -half, half), Math.Clamp(worldZ - r, -half, half), out int minTx, out int minTz);
terrain.MapWorldToTile(Math.Clamp(worldX + r, -half, half), Math.Clamp(worldZ + r, -half, half), out int maxTx, out int maxTz);
int grid = terrain.TileGridCount;
for (int tz = minTz; tz <= maxTz; tz++)
{
for (int tx = minTx; tx <= maxTx; tx++)
{
needed[tz * grid + tx] = true;
}
}
}
public void SyncNeededTiles(
Box3DSoaWorld world,
TerrainField terrain,
ReadOnlySpan<bool> needed,
ReadOnlySpan<bool> immediate = default,
int maxNewPrefetchPerTick = int.MaxValue)
{
if (!terrain.IsHeightmapMode)
{
return;
}
int grid = terrain.TileGridCount;
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
int idx = tz * grid + tx;
bool keep = needed[idx] || (!immediate.IsEmpty && immediate[idx]);
if (_residentFlags[idx] && !keep)
{
world.RemoveBody(_residentHandles[idx]);
_residentHandles[idx] = default;
_residentFlags[idx] = false;
_syncedStructuralVersions[idx] = 0;
ResidentTileCount--;
}
}
}
if (!immediate.IsEmpty)
{
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
int idx = tz * grid + tx;
if (immediate[idx] && !_residentFlags[idx])
{
EnsureTileResident(world, terrain, tx, tz);
}
}
}
}
int newPrefetch = 0;
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
if (newPrefetch >= maxNewPrefetchPerTick)
{
return;
}
int idx = tz * grid + tx;
if (needed[idx] && !_residentFlags[idx])
{
if (EnsureTileResident(world, terrain, tx, tz))
{
newPrefetch++;
}
}
}
}
}
public void EnsureTilesAlongRay(
Box3DSoaWorld world,
TerrainField terrain,
float ox, float oz,
float dx, float dz,
float maxDistance)
{
if (!terrain.IsHeightmapMode || maxDistance <= 0f)
{
return;
}
float half = terrain.MapHalfExtent;
float tileSize = terrain.MapTileSize;
int grid = terrain.TileGridCount;
float tMin = 0f;
float tMax = maxDistance;
if (!SlabClip(ox, dx, -half, half, ref tMin, ref tMax)) return;
if (!SlabClip(oz, dz, -half, half, ref tMin, ref tMax)) return;
float sx = ox + dx * tMin;
float sz = oz + dz * tMin;
terrain.MapWorldToTile(sx, sz, out int tx, out int tz);
float ex = ox + dx * tMax;
float ez = oz + dz * tMax;
terrain.MapWorldToTile(ex, ez, out int endTx, out int endTz);
int stepX = dx > 1e-9f ? 1 : (dx < -1e-9f ? -1 : 0);
int stepZ = dz > 1e-9f ? 1 : (dz < -1e-9f ? -1 : 0);
float tDeltaX = stepX != 0 ? tileSize / MathF.Abs(dx) : float.PositiveInfinity;
float tDeltaZ = stepZ != 0 ? tileSize / MathF.Abs(dz) : float.PositiveInfinity;
float nextBoundaryX = -half + (tx + (stepX > 0 ? 1 : 0)) * tileSize;
float nextBoundaryZ = -half + (tz + (stepZ > 0 ? 1 : 0)) * tileSize;
float tMaxX = stepX != 0 ? tMin + MathF.Max(0f, (nextBoundaryX - sx) / dx) : float.PositiveInfinity;
float tMaxZ = stepZ != 0 ? tMin + MathF.Max(0f, (nextBoundaryZ - sz) / dz) : float.PositiveInfinity;
int maxSteps = grid * 2 + 4;
for (int iter = 0; iter < maxSteps; iter++)
{
EnsureTileResident(world, terrain, tx, tz);
if (tx == endTx && tz == endTz)
{
break;
}
float curT;
if (tMaxX <= tMaxZ)
{
curT = tMaxX;
tMaxX += tDeltaX;
tx += stepX;
}
else
{
curT = tMaxZ;
tMaxZ += tDeltaZ;
tz += stepZ;
}
if ((uint)tx >= (uint)grid || (uint)tz >= (uint)grid || curT > tMax)
{
break;
}
}
if ((uint)endTx < (uint)grid && (uint)endTz < (uint)grid)
{
EnsureTileResident(world, terrain, endTx, endTz);
}
}
public int CountDirtyResidentTiles(TerrainField terrain)
{
if (!terrain.IsHeightmapMode)
{
return 0;
}
int grid = terrain.TileGridCount;
int count = 0;
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
int idx = tz * grid + tx;
if (_residentFlags[idx] && terrain.StructuralTileVersions[tx, tz] != _syncedStructuralVersions[idx])
{
count++;
}
}
}
return count;
}
public int FlushDirtyHeightfields(Box3DSoaWorld world, TerrainField terrain, int maxTilesPerTick = 4)
{
if (!terrain.IsHeightmapMode || maxTilesPerTick <= 0)
{
return 0;
}
int grid = terrain.TileGridCount;
int rebuilt = 0;
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
int idx = tz * grid + tx;
if (!_residentFlags[idx])
{
continue;
}
if (terrain.StructuralTileVersions[tx, tz] != _syncedStructuralVersions[idx])
{
if (world.FreeBodySlots < 8)
{
return rebuilt;
}
if (EnsureTileResident(world, terrain, tx, tz))
{
rebuilt++;
if (rebuilt >= maxTilesPerTick)
{
return rebuilt;
}
}
}
}
}
return rebuilt;
}
public void SyncWindow(Box3DSoaWorld world, TerrainField terrain, float centerX, float centerZ, int halfTileRadius = 1)
{
if (!terrain.IsHeightmapMode)
{
return;
}
terrain.MapWorldToTile(centerX, centerZ, out int cx, out int cz);
int grid = terrain.TileGridCount;
int minTx = Math.Max(0, cx - halfTileRadius);
int maxTx = Math.Min(grid - 1, cx + halfTileRadius);
int minTz = Math.Max(0, cz - halfTileRadius);
int maxTz = Math.Min(grid - 1, cz + halfTileRadius);
for (int tz = 0; tz < grid; tz++)
{
for (int tx = 0; tx < grid; tx++)
{
int idx = tz * grid + tx;
if (_residentFlags[idx] && (tx < minTx || tx > maxTx || tz < minTz || tz > maxTz))
{
world.RemoveBody(_residentHandles[idx]);
_residentHandles[idx] = default;
_residentFlags[idx] = false;
_syncedStructuralVersions[idx] = 0;
ResidentTileCount--;
}
}
}
for (int tz = minTz; tz <= maxTz; tz++)
{
for (int tx = minTx; tx <= maxTx; tx++)
{
EnsureTileResident(world, terrain, tx, tz);
}
}
}
private static bool SlabClip(float o, float d, float minB, float maxB, ref float tMin, ref float tMax)
{
if (MathF.Abs(d) < 1e-9f)
{
return o >= minB && o <= maxB;
}
float invD = 1f / d;
float t1 = (minB - o) * invD;
float t2 = (maxB - o) * invD;
if (t1 > t2) (t1, t2) = (t2, t1);
tMin = MathF.Max(tMin, t1);
tMax = MathF.Min(tMax, t2);
return tMax >= tMin;
}
}
}

View file

@ -8,6 +8,7 @@ namespace RustToDust.Ymir
public sealed class LocalArenaSession : IClientArenaSession
{
private readonly List<ISimEvent> _pendingEvents = new();
private readonly Dictionary<ArenaMapKind, ArenaScarLedgerSnapshot> _scarsByMap = new();
public LocalArenaSession(int seed = 42, ArenaMapKind mapKind = ArenaMapKind.Desert, string? callsign = null, bool skipInitialDrop = false, byte squadSize = 1)
{
@ -95,13 +96,21 @@ namespace RustToDust.Ymir
return ok;
}
public void RepairArenaScars()
{
Inner.RepairArenaScars();
_scarsByMap.Remove(Inner.State.MapKind);
}
public void RequestNewMatch(int seed, ArenaMapKind mapKind)
{
string? name = LocalContender.Name;
byte squadSize = Inner.State.SquadSize;
_scarsByMap[Inner.State.MapKind] = Inner.State.ScarLedger.ToSnapshot();
_scarsByMap.TryGetValue(mapKind, out var initialScars);
_pendingEvents.Clear();
Inner.Dispose();
Inner = new ArenaSession(seed, mapKind, slot0Human: true, squadSize: squadSize)
Inner = new ArenaSession(seed, mapKind, slot0Human: true, squadSize: squadSize, initialScars: initialScars)
{
EnableNetworkPvs = false
};
@ -126,7 +135,7 @@ namespace RustToDust.Ymir
public ClientRayHit CastWorldRayClosest(Vector3 origin, Vector3 translation)
{
var hit = Inner.World.CastRayClosest((origin.X, origin.Y, origin.Z), (translation.X, translation.Y, translation.Z));
var hit = Inner.CastWorldRayClosest(origin, translation);
return new ClientRayHit(
hit.Hit,
hit.StableId,

View file

@ -843,12 +843,13 @@ namespace RustToDust.Ymir
return !inst.Active;
}
bool isTerrainTile = Box3DPhysicsTileSync.IsHeightfieldTileStableId(hitStableId);
inst.Pos = boxPoint;
HandleProjectileImpact(
slotIndex,
HitTargetKind.StaticCover,
(int)hitStableId,
hitStableId,
isTerrainTile ? HitTargetKind.Terrain : HitTargetKind.StaticCover,
isTerrainTile ? -1 : (int)hitStableId,
isTerrainTile ? 0UL : hitStableId,
boxPoint,
boxNormal,
dir);
@ -1413,6 +1414,16 @@ namespace RustToDust.Ymir
continue;
}
if (Box3DPhysicsTileSync.IsHeightfieldTileStableId(rayHit.StableId))
{
hitTerrain = true;
terrainHitX = rayHit.Point.X;
terrainHitY = rayHit.Point.Y;
terrainHitZ = rayHit.Point.Z;
hitAny = false;
break;
}
hitAny = true;
hitStableId = rayHit.StableId;
hitPoint = rayHit.Point;

View file

@ -477,10 +477,10 @@ namespace RustToDust.Ymir
float rrX = x + right.X * w - fwd.X * l, rrZ = z + right.Z * w - fwd.Z * l;
float hCenter = terrain.SampleHeight(x, z);
if (terrain.SampleNormal(flX, flZ).Ny < 0.72f ||
terrain.SampleNormal(frX, frZ).Ny < 0.72f ||
terrain.SampleNormal(rlX, rlZ).Ny < 0.72f ||
terrain.SampleNormal(rrX, rrZ).Ny < 0.72f)
if (terrain.SampleNormal(flX, flZ).Ny < 0.58f ||
terrain.SampleNormal(frX, frZ).Ny < 0.58f ||
terrain.SampleNormal(rlX, rlZ).Ny < 0.58f ||
terrain.SampleNormal(rrX, rrZ).Ny < 0.58f)
{
planeCenterY = hCenter;
return centerNormal.Y >= 0.78f ? centerNormal : Vector3.UnitY;
@ -1007,6 +1007,27 @@ namespace RustToDust.Ymir
}
}
}
else if (n == 4 && view.Size2[lane] > 2.4f && terrainNormal.Y >= 0.78f)
{
float fz = view.Size2[lane] * 0.98f;
float fw = view.Size0[lane] * 0.95f;
for (int ci = -1; ci <= 1; ci++)
{
float sx = fw * ci;
float cx = comPos.X + right.X * sx + fwd.X * fz;
float cz = comPos.Z + right.Z * sx + fwd.Z * fz;
if (WalkerState.SampleTerrainNormal(terrain, cx, cz).Y >= 0.58f)
{
float ch = terrain.SampleHeight(cx, cz);
Vector3 cornerRel = right * sx + fwd * fz - up * view.Size1[lane];
float neededGroundY = (ch + 0.22f * scale - cornerRel.Y) - rideHeight;
if (neededGroundY > effectiveGroundY)
{
effectiveGroundY = MathF.Min(comGroundY + 1.15f * scale, neededGroundY);
}
}
}
}
}
float targetY = effectiveGroundY + rideHeight;
if (!activeMove && !ws.IsAirborne)

View file

@ -797,6 +797,126 @@ namespace RustToDust.Tests
"Client must receive Exemplar walker snapshot even under dense 12 quad-walker contention");
}
[Fact]
public void Cut13a_OutOfPvsHistoricalCratersSyncViaPersistentScars_AndLiveCratersEnterWithin576mBubble()
{
using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0);
var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
const float histX = 700f;
const float histZ = 700f;
float baseHistH = host.Session.State.Terrain.SampleHeight(histX, histZ);
// 1. Historical out-of-PVS crater stamped before Client A joins
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(histX, histZ, craterRadius: 6f, craterDepth: 2.0f, scorchRadius: 7f);
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
host.StepOnce(nowMs += 16);
float scarredHistH = host.Session.State.Terrain.SampleHeight(histX, histZ);
Assert.True(scarredHistH < baseHistH - 1.2f);
using var clientA = new RemoteArenaSession(ep, "Scout");
Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000));
// Out-of-PVS historical crater must be present immediately via PersistentScars
Assert.Equal(scarredHistH, clientA.ViewState.Terrain.SampleHeight(histX, histZ), precision: 3);
Assert.InRange(clientA.PredTileSync.ResidentTileCount, 1, 9);
// 2. Live crater stamped far outside 576m bubble (-700, 100 vs open-sky ~700, 100 = ~1400m apart)
int slotA = clientA.LocalContenderId;
var sion = host.Session.State.SionMap!;
float liveX = 700f, liveZ = 100f;
for (float x = 640f; x <= 760f; x += 8f)
{
if (!sion.IsInsideAnyBuildingXz(x, liveZ, padding: 10f))
{
liveX = x;
break;
}
}
float baseLiveH = host.Session.State.Terrain.SampleHeight(liveX, liveZ);
host.Session.SetContenderPose(slotA, -700f, liveZ, 0f);
host.StepOnce(nowMs += 16);
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(liveX, liveZ, craterRadius: 6f, craterDepth: 2.0f, scorchRadius: 7f);
for (int t = 0; t < 10; t++)
{
nowMs += 16;
host.StepOnce(nowMs);
clientA.PumpNetwork();
Thread.Sleep(1);
}
float hostLiveH = host.Session.State.Terrain.SampleHeight(liveX, liveZ);
Assert.True(hostLiveH < baseLiveH - 1.2f);
Assert.Equal(baseLiveH, clientA.ViewState.Terrain.SampleHeight(liveX, liveZ), precision: 3);
// 3. Client A enters 576m local geometry bubble (liveX - 450m -> dist = 450m <= 576m)
host.Session.SetContenderPose(slotA, liveX - 450f, liveZ, 0f);
Assert.True(PumpUntil(
host,
new[] { clientA },
() => MathF.Abs(clientA.ViewState.Terrain.SampleHeight(liveX, liveZ) - hostLiveH) < 0.05f,
ref nowMs,
3000),
"Client must receive live TerrainStampEvent upon entering 576m bubble before reaching _predWorld 3x3 window");
// 4. Client A steps into (liveX, liveZ) tile -> _predWorld 3x3 window matches server Box3D crater depth 1:1
host.Session.SetContenderPose(slotA, liveX - 20f, liveZ, 0f);
for (int t = 0; t < 10; t++)
{
nowMs += 16;
host.StepOnce(nowMs);
clientA.BeginRenderFrame(1.0 / 60.0, 1f);
Thread.Sleep(1);
}
Assert.InRange(clientA.PredTileSync.ResidentTileCount, 1, 9);
float rayStartY = sion.Metadata.MaxY + 25f;
float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f);
var hostHit = host.Session.CastWorldRayClosest(new Vector3(liveX, rayStartY, liveZ), new Vector3(0f, raySpanY, 0f));
var predHit = clientA.CastWorldRayClosest(new Vector3(liveX, rayStartY, liveZ), new Vector3(0f, raySpanY, 0f));
Assert.True(hostHit.Hit && predHit.Hit);
Assert.True(MathF.Abs(hostHit.Point.Y - predHit.Point.Y) < 0.05f,
$"Expected _predWorld crater impact Y ({predHit.Point.Y:F3}m) to match server ({hostHit.Point.Y:F3}m)");
}
[Fact]
public void Cut13a_OverlappingCraters_CoalesceIdenticallyAcrossLiveHostJoinerAndPostReset()
{
using var host = new ServerMatchHost(IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion, maxHumans: 12, autoRestartSec: 0);
var ep = new IPEndPoint(IPAddress.Loopback, host.BoundPort);
const float cx = -120f;
const float cz = 180f;
// Stamp 3 overlapping craters within < 0.75m (coalesce radius)
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx, cz, craterRadius: 4.0f, craterDepth: 1.1f, scorchRadius: 4.5f);
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx + 0.30f, cz - 0.20f, craterRadius: 5.8f, craterDepth: 2.2f, scorchRadius: 6.0f);
((IOrdnanceTargetSink)host.Session).StampTerrainImpact(cx - 0.15f, cz + 0.25f, craterRadius: 3.0f, craterDepth: 0.7f, scorchRadius: 3.5f);
long nowMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
host.StepOnce(nowMs += 16);
float liveHostH = host.Session.State.Terrain.SampleHeight(cx, cz);
float liveHostEdgeH = host.Session.State.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f);
using var clientA = new RemoteArenaSession(ep, "Joiner");
Assert.True(PumpUntil(host, new[] { clientA }, () => clientA.IsJoined, ref nowMs, 3000));
float clientJoinH = clientA.ViewState.Terrain.SampleHeight(cx, cz);
float clientJoinEdgeH = clientA.ViewState.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f);
Assert.True(MathF.Abs(liveHostH - clientJoinH) < 0.001f,
$"Expected liveHostH ({liveHostH:F4}) == clientJoinH ({clientJoinH:F4}) within 0.001m");
Assert.True(MathF.Abs(liveHostEdgeH - clientJoinEdgeH) < 0.001f,
$"Expected liveHostEdgeH ({liveHostEdgeH:F4}) == clientJoinEdgeH ({clientJoinEdgeH:F4}) within 0.001m");
host.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false);
float postResetHostH = host.Session.State.Terrain.SampleHeight(cx, cz);
float postResetHostEdgeH = host.Session.State.Terrain.SampleHeight(cx + 2.5f, cz - 1.5f);
Assert.True(MathF.Abs(liveHostH - postResetHostH) < 0.001f,
$"Expected liveHostH ({liveHostH:F4}) == postResetHostH ({postResetHostH:F4}) within 0.001m");
Assert.True(MathF.Abs(liveHostEdgeH - postResetHostEdgeH) < 0.001f,
$"Expected liveHostEdgeH ({liveHostEdgeH:F4}) == postResetHostEdgeH ({postResetHostEdgeH:F4}) within 0.001m");
}
[Fact]
public void RemoteArenaSession_AppliesRemoteContenderCoreHpRatioOnPvsSnapshot()
{

View file

@ -0,0 +1,158 @@
using System;
using System.IO;
using RustToDust.Client;
using Xunit;
namespace RustToDust.Tests;
public sealed class GraphicsSettingsTests
{
[Fact]
public void Defaults_MatchExpectedBaseline()
{
var settings = new GraphicsSettings();
Assert.Equal(VfxResolutionScale.Half, settings.VfxResolution);
Assert.Equal(VolumetricSamples.Medium, settings.VolumetricSamples);
Assert.Equal(SdfgiQuality.Balanced, settings.SdfgiQuality);
Assert.True(settings.BorderlessFullscreen);
Assert.Equal(0.50f, GraphicsSettings.GetResolutionScaleFactor(settings.VfxResolution));
Assert.Equal((10, 15), GraphicsSettings.GetVolumetricStepBudget(settings.VolumetricSamples));
var sdfgi = GraphicsSettings.GetSdfgiConfig(settings.SdfgiQuality);
Assert.True(sdfgi.Enabled);
Assert.Equal(0.8f, sdfgi.MinCellSize);
Assert.Equal(3, sdfgi.Cascades);
Assert.True(sdfgi.HalfResolution);
Assert.Equal(4, sdfgi.RayCount);
}
[Fact]
public void MissingOrCorruptJson_FallsBackToSafeDefaults()
{
string tempDir = Path.Combine(Path.GetTempPath(), "rtd-gfx-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
try
{
string missingPath = Path.Combine(tempDir, "missing.json");
var missingLoaded = GraphicsSettings.Load(missingPath);
Assert.Equal(VfxResolutionScale.Half, missingLoaded.VfxResolution);
Assert.Equal(VolumetricSamples.Medium, missingLoaded.VolumetricSamples);
Assert.Equal(SdfgiQuality.Balanced, missingLoaded.SdfgiQuality);
Assert.True(missingLoaded.BorderlessFullscreen);
string corruptPath = Path.Combine(tempDir, "corrupt.json");
File.WriteAllText(corruptPath, "{ this is not valid json !!!");
var corruptLoaded = GraphicsSettings.Load(corruptPath);
Assert.Equal(VfxResolutionScale.Half, corruptLoaded.VfxResolution);
Assert.Equal(VolumetricSamples.Medium, corruptLoaded.VolumetricSamples);
Assert.Equal(SdfgiQuality.Balanced, corruptLoaded.SdfgiQuality);
Assert.True(corruptLoaded.BorderlessFullscreen);
// ResetToDefaults(persist: true) must unconditionally rewrite a corrupt file even when memory equals defaults
corruptLoaded.ResetToDefaults(persist: true);
string repairedJson = File.ReadAllText(corruptPath);
Assert.DoesNotContain("not valid json", repairedJson, StringComparison.Ordinal);
var repaired = new GraphicsSettings();
Assert.True(repaired.LoadFromJson(repairedJson));
Assert.Equal(VfxResolutionScale.Half, repaired.VfxResolution);
Assert.Equal(VolumetricSamples.Medium, repaired.VolumetricSamples);
Assert.Equal(SdfgiQuality.Balanced, repaired.SdfgiQuality);
Assert.True(repaired.BorderlessFullscreen);
var outOfRange = new GraphicsSettings();
Assert.True(outOfRange.LoadFromJson("""{"vfxResolutionScale":99,"volumetricSamples":42,"sdfgiQuality":77,"borderlessFullscreen":false}"""));
Assert.Equal(VfxResolutionScale.Half, outOfRange.VfxResolution);
Assert.Equal(VolumetricSamples.Medium, outOfRange.VolumetricSamples);
Assert.Equal(SdfgiQuality.Balanced, outOfRange.SdfgiQuality);
Assert.False(outOfRange.BorderlessFullscreen);
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
}
[Fact]
public void SaveAndReload_RoundtripsAllFieldsAndFiresChanged()
{
string tempDir = Path.Combine(Path.GetTempPath(), "rtd-gfx-tests-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
try
{
string path = Path.Combine(tempDir, "graphics_settings.json");
var settings = GraphicsSettings.Load(path);
int changeEvents = 0;
settings.Changed += _ => changeEvents++;
settings.Apply(
VfxResolutionScale.Full,
VolumetricSamples.Ultra,
SdfgiQuality.High,
borderlessFullscreen: false,
persist: true);
Assert.Equal(1, changeEvents);
Assert.True(File.Exists(path));
// No-op apply must not fire duplicate Changed events
settings.Apply(
VfxResolutionScale.Full,
VolumetricSamples.Ultra,
SdfgiQuality.High,
borderlessFullscreen: false,
persist: true);
Assert.Equal(1, changeEvents);
var reloaded = GraphicsSettings.Load(path);
Assert.Equal(VfxResolutionScale.Full, reloaded.VfxResolution);
Assert.Equal(VolumetricSamples.Ultra, reloaded.VolumetricSamples);
Assert.Equal(SdfgiQuality.High, reloaded.SdfgiQuality);
Assert.False(reloaded.BorderlessFullscreen);
reloaded.ResetToDefaults(persist: true);
var afterReset = GraphicsSettings.Load(path);
Assert.Equal(VfxResolutionScale.Half, afterReset.VfxResolution);
Assert.Equal(VolumetricSamples.Medium, afterReset.VolumetricSamples);
Assert.Equal(SdfgiQuality.Balanced, afterReset.SdfgiQuality);
Assert.True(afterReset.BorderlessFullscreen);
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
}
[Fact]
public void PresetMappings_MatchSpecification()
{
Assert.Equal(0.50f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.Half));
Assert.Equal(0.75f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.ThreeQuarter));
Assert.Equal(1.00f, GraphicsSettings.GetResolutionScaleFactor(VfxResolutionScale.Full));
Assert.Equal((8, 12), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Low));
Assert.Equal((10, 15), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Medium));
Assert.Equal((16, 24), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.High));
Assert.Equal((24, 36), GraphicsSettings.GetVolumetricStepBudget(VolumetricSamples.Ultra));
Assert.False(GraphicsSettings.GetSdfgiConfig(SdfgiQuality.Off).Enabled);
var balanced = GraphicsSettings.GetSdfgiConfig(SdfgiQuality.Balanced);
Assert.True(balanced.Enabled);
Assert.Equal(0.8f, balanced.MinCellSize);
Assert.Equal(3, balanced.Cascades);
Assert.True(balanced.HalfResolution);
Assert.Equal(4, balanced.RayCount);
var high = GraphicsSettings.GetSdfgiConfig(SdfgiQuality.High);
Assert.True(high.Enabled);
Assert.Equal(0.4f, high.MinCellSize);
Assert.Equal(4, high.Cascades);
Assert.False(high.HalfResolution);
Assert.Equal(8, high.RayCount);
}
}

View file

@ -729,7 +729,7 @@ namespace RustToDust.Tests
{
nowMs += 16;
host.StepOnce(nowMs);
clientA.PumpNetwork();
clientA.PumpNetwork(nowMs);
Thread.Sleep(2);
}
Assert.True(clientA.IsJoined);
@ -746,7 +746,7 @@ namespace RustToDust.Tests
{
nowMs += 16;
host.StepOnce(nowMs);
clientA.PumpNetwork();
clientA.PumpNetwork(nowMs);
Thread.Sleep(2);
}
Assert.Equal((byte)2, host.Session.State.Contenders[0].SquadId);
@ -758,7 +758,7 @@ namespace RustToDust.Tests
{
nowMs += 16;
host.StepOnce(nowMs);
clientA.PumpNetwork();
clientA.PumpNetwork(nowMs);
if (host.Session.State.Phase == MatchPhase.Active && clientA.ViewState.Phase == MatchPhase.Active)
{
break;
@ -801,7 +801,7 @@ namespace RustToDust.Tests
{
nowMs += 16;
host.StepOnce(nowMs);
clientARejoin.PumpNetwork();
clientARejoin.PumpNetwork(nowMs);
Thread.Sleep(2);
}
Assert.True(clientARejoin.IsJoined);
@ -814,8 +814,8 @@ namespace RustToDust.Tests
{
nowMs += 16;
host.StepOnce(nowMs);
clientARejoin.PumpNetwork();
clientB.PumpNetwork();
clientARejoin.PumpNetwork(nowMs);
clientB.PumpNetwork(nowMs);
Thread.Sleep(2);
}
Assert.True(clientB.IsJoined);

View file

@ -18,6 +18,7 @@
<ItemGroup>
<Compile Include="..\..\client\WalkerFootstepTracker.cs" Link="Client\WalkerFootstepTracker.cs" />
<Compile Include="..\..\client\CameraJuiceState.cs" Link="Client\CameraJuiceState.cs" />
<Compile Include="..\..\client\GraphicsSettings.cs" Link="Client\GraphicsSettings.cs" />
</ItemGroup>
<ItemGroup>

View file

@ -1,6 +1,10 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Numerics;
using RustToDust.Core;
using RustToDust.Net;
using RustToDust.Ymir;
using Xunit;
using Ymir.Box3D;
@ -16,20 +20,24 @@ namespace RustToDust.Tests
var meta = sion.Metadata;
Assert.Equal(3072f, meta.SizeMeters);
Assert.Equal(6, meta.TileGrid);
Assert.Equal(512f, meta.TileSizeMeters);
Assert.Equal(1025, meta.GridRes);
Assert.Equal(3.0f, meta.CellSizeMeters);
Assert.Equal(16, meta.TileGrid);
Assert.Equal(192f, meta.TileSizeMeters);
Assert.Equal(6145, meta.GridRes);
Assert.Equal(0.5f, meta.CellSizeMeters);
Assert.Equal("heightmap_05m.u16z", meta.HeightmapFile);
Assert.False(string.IsNullOrWhiteSpace(meta.DemAssetHash));
Assert.Contains("swisstopo", meta.Attribution, StringComparison.OrdinalIgnoreCase);
Assert.Equal(1025 * 1025, sion.Heights.Length);
Assert.Equal(6145 * 6145, sion.BaseDem.Length);
Assert.Equal(2319, sion.Buildings.Count);
Assert.Equal(36, sion.CollisionMeshes.Count);
var terrain = TerrainField.LoadHeightmap(
meta.SizeMeters, meta.GridRes, sion.Heights, meta.MinY, meta.MaxY);
var terrain = TerrainField.LoadSharedHeightmap(
meta.SizeMeters, meta.GridRes, meta.TileGrid,
sion.BaseDem, sion.BaseDemMinY, sion.BaseDemScale,
meta.MinY, meta.MaxY);
// Verify Basilique de Valere and valley buildings align cleanly with heightmap.f32 (0.00m coordinate drift)
// Verify Basilique de Valere and valley buildings align cleanly with heightmap_05m.u16z (0.00m coordinate drift)
bool foundValere = false;
int flatAlignChecked = 0;
int closeAlignCount = 0;
@ -82,16 +90,19 @@ namespace RustToDust.Tests
{
var sion = SionMapLoader.Load();
var meta = sion.Metadata;
var terrain = TerrainField.LoadHeightmap(
meta.SizeMeters, meta.GridRes, sion.Heights, meta.MinY, meta.MaxY);
var terrain = TerrainField.LoadSharedHeightmap(
meta.SizeMeters, meta.GridRes, meta.TileGrid,
sion.BaseDem, sion.BaseDemMinY, sion.BaseDemScale,
meta.MinY, meta.MaxY);
Assert.True(terrain.IsHeightmapMode);
Assert.Equal(3072f, terrain.MapSize);
Assert.Equal(1536f, terrain.MapHalfExtent);
Assert.Equal(16, terrain.TileGridCount);
// Grid vertex exactness at (-1536, -1536) and (0, 0)
Assert.Equal(sion.Heights[0], terrain.SampleHeight(-1536f, -1536f), precision: 4);
Assert.Equal(sion.Heights[512 * 1025 + 512], terrain.SampleHeight(0f, 0f), precision: 4);
Assert.Equal(sion.SampleBaseDemAtIndex(0), terrain.SampleHeight(-1536f, -1536f), precision: 4);
Assert.Equal(sion.SampleBaseDemAtIndex(3072 * 6145 + 3072), terrain.SampleHeight(0f, 0f), precision: 4);
// Plaza spawn area is flat; Valere hill rises > 100m
var (_, plazaNy, _) = terrain.SampleNormal(-60f, 360f);
@ -126,7 +137,7 @@ namespace RustToDust.Tests
Assert.Empty(state.ArenaCoverBoxes);
Assert.Equal(MatchState.SionInitialSafeRadius, state.Spectators.SafeRadius);
// Verify StaticHeightField (1) + StaticMesh (36) exist in Ymir
// Verify lazy tiled StaticHeightField (192m tiles) + StaticMesh (36) exist in Ymir
int hfCount = 0;
int meshCount = 0;
var view = session.World.View;
@ -136,7 +147,8 @@ namespace RustToDust.Tests
if (kind == Box3DSoaKind.StaticHeightField) hfCount++;
else if (kind == Box3DSoaKind.StaticMesh) meshCount++;
}
Assert.Equal(1, hfCount);
Assert.InRange(hfCount, 1, 45);
Assert.Equal(hfCount, session.TileSync.ResidentTileCount);
Assert.Equal(36, meshCount);
// Verify zero contenders, spectators, or drops spawned inside any building
@ -225,5 +237,567 @@ namespace RustToDust.Tests
float pDisp = MathF.Sqrt((player.X - pStartX) * (player.X - pStartX) + (player.Z - pStartZ) * (player.Z - pStartZ));
Assert.True(pDisp > 5f, $"Expected player displacement > 5m on Sion after 180 ticks, got {pDisp:F2}m");
}
[Fact]
public void SionBox3DTile_CraterRebuildsLocalTileOnlyAndLeavesNeighborsIntact()
{
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true);
var terrain = session.State.Terrain;
// Tile (7, 7) spans [-192, 0) x [-192, 0); neighbor tile (8, 7) spans [0, 192) x [-192, 0).
// Pick an open-sky coordinate strictly inside tile (7, 7) away from any building footprint.
var sion = session.State.SionMap!;
float cx = -96f, cz = -96f;
bool foundSpot = false;
for (float z = -176f; z <= -16f && !foundSpot; z += 8f)
{
for (float x = -176f; x <= -16f; x += 8f)
{
if (!sion.IsInsideAnyBuildingXz(x, z, padding: 10f))
{
cx = x;
cz = z;
foundSpot = true;
break;
}
}
}
Assert.True(foundSpot, "Expected open-sky spot inside Sion tile (7, 7)");
session.TileSync.EnsureTileRegion(session.World, terrain, cx, cz, halfTileRadius: 1);
Assert.True(session.TileSync.TryGetResidentHandle(7, 7, terrain.TileGridCount, out var handleTargetBefore));
Assert.True(session.TileSync.TryGetResidentHandle(8, 7, terrain.TileGridCount, out var handleNeighborBefore));
float rayStartY = sion.Metadata.MaxY + 25f;
float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f);
var hitBefore = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f));
Assert.True(hitBefore.Hit);
Assert.Equal(Box3DPhysicsTileSync.HeightfieldTileStableIdBase + (ulong)(7 * 16 + 7), hitBefore.StableId);
// Stamp crater strictly inside tile (7, 7)
session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = cx,
Z = cz,
Radius = 6f,
Depth = 2.0f
});
int rebuilt = session.TileSync.FlushDirtyHeightfields(session.World, terrain, maxTilesPerTick: 4);
Assert.Equal(1, rebuilt);
Assert.True(session.TileSync.TryGetResidentHandle(7, 7, terrain.TileGridCount, out var handleTargetAfter));
Assert.True(session.TileSync.TryGetResidentHandle(8, 7, terrain.TileGridCount, out var handleNeighborAfter));
Assert.NotEqual(handleTargetBefore, handleTargetAfter);
Assert.Equal(handleNeighborBefore, handleNeighborAfter);
var hitAfter = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f));
Assert.True(hitAfter.Hit);
Assert.True(hitAfter.Point.Y < hitBefore.Point.Y - 1.2f,
$"Expected Box3D raycast impact height to drop in crater (before={hitBefore.Point.Y:F3}, after={hitAfter.Point.Y:F3})");
}
[Fact]
public void ArenaScarLedgerStore_PersistsCratersAndRubbleAcrossResetAndRepairsToLayer0()
{
string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-scar-test-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
string scarPath = Path.Combine(tempDir, "sion_scars_test.cultcache");
try
{
const float craterX = -120f;
const float craterZ = 180f;
const float rubbleX = 140f;
const float rubbleZ = 180f;
float baseCraterH;
float baseRubbleH;
float scarredCraterH;
float scarredRubbleH;
using (var host1 = new ServerMatchHost(
IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion,
autoRestartSec: 0, scarFilePath: scarPath, persistScars: true))
{
var state1 = host1.Session.State;
baseCraterH = state1.Terrain.SampleHeight(craterX, craterZ);
baseRubbleH = state1.Terrain.SampleHeight(rubbleX, rubbleZ);
state1.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = craterX,
Z = craterZ,
Radius = 5.5f,
Depth = 1.8f
});
state1.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Rubble,
X = rubbleX,
Z = rubbleZ,
Radius = 6.0f,
Depth = 1.2f,
Yaw = 0.4f
});
scarredCraterH = state1.Terrain.SampleHeight(craterX, craterZ);
scarredRubbleH = state1.Terrain.SampleHeight(rubbleX, rubbleZ);
Assert.True(scarredCraterH < baseCraterH - 1.2f);
Assert.True(scarredRubbleH > baseRubbleH + 0.6f);
// ResetMatch preserves scars in RAM & flushes to CultCache
host1.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false);
Assert.Equal(scarredCraterH, host1.Session.State.Terrain.SampleHeight(craterX, craterZ), precision: 3);
Assert.Equal(scarredRubbleH, host1.Session.State.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3);
}
Assert.True(File.Exists(scarPath), "Expected CultCache scar file on disk after host dispose");
using (var host2 = new ServerMatchHost(
IPAddress.Loopback, 0, seed: 44, ArenaMapKind.Sion,
autoRestartSec: 0, scarFilePath: scarPath, persistScars: true))
{
var state2 = host2.Session.State;
Assert.Equal(scarredCraterH, state2.Terrain.SampleHeight(craterX, craterZ), precision: 3);
Assert.Equal(scarredRubbleH, state2.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3);
// RepairArenaScars zeroes back to Layer 0
host2.RepairArenaScars();
Assert.Equal(baseCraterH, state2.Terrain.SampleHeight(craterX, craterZ), precision: 3);
Assert.Equal(baseRubbleH, state2.Terrain.SampleHeight(rubbleX, rubbleZ), precision: 3);
Assert.Empty(state2.ScarLedger.Terrain);
}
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
}
[Fact]
public void ValereSlopeHits_ClassifyAsTerrainNeverStaticCover_ForHitscanAndProjectile()
{
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true);
var terrain = session.State.Terrain;
var sion = session.State.SionMap!;
// Ensure Valere hill heightfield tiles are resident so Box3D heightfields are active on the slope ray
session.TileSync.EnsureTileRegion(session.World, terrain, 113f, -211f, halfTileRadius: 1);
// Find an open-sky steep Valere slope point and an unobstructed muzzle above it (zero buildings on ray)
Vector3 muzzle = default;
Vector3 dir = default;
bool foundSlope = false;
for (float sz = -290f; sz <= -175f && !foundSlope; sz += 6f)
{
for (float sx = 40f; sx <= 185f && !foundSlope; sx += 6f)
{
if (sion.IsInsideAnyBuildingXz(sx, sz, padding: 8.0f))
{
continue;
}
float sh = terrain.SampleHeight(sx, sz);
var (nx, ny, nz) = terrain.SampleNormal(sx, sz);
if (sh < 55f || ny >= 0.88f)
{
continue;
}
Vector3 slopePt = new(sx, sh, sz);
Vector3 nrm = Vector3.Normalize(new Vector3(nx, ny, nz));
Vector3 candMuzzle = slopePt + nrm * 32f + Vector3.UnitY * 8f;
Vector3 candDir = Vector3.Normalize(slopePt - candMuzzle);
float dist = Vector3.Distance(candMuzzle, slopePt) + 5f;
if (!sion.IntersectsAnyBuildingAabb(candMuzzle.X, candMuzzle.Y, candMuzzle.Z, candDir.X, candDir.Y, candDir.Z, dist) &&
terrain.Raycast(candMuzzle.X, candMuzzle.Y, candMuzzle.Z, candDir.X, candDir.Y, candDir.Z, dist, out float tx, out _, out float tz, out _) &&
!sion.IsInsideAnyBuildingXz(tx, tz, padding: 2.0f))
{
muzzle = candMuzzle;
dir = candDir;
foundSlope = true;
}
}
}
Assert.True(foundSlope, "Expected open-sky steep Valere slope ray unobstructed by buildings");
session.TileSync.EnsureTileRegion(session.World, terrain, muzzle.X, muzzle.Z, halfTileRadius: 1);
var events = new List<ISimEvent>();
session.DrainStepEvents(events);
// 1. Fire hitscan directly into Valere slope
var hitscanSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.RotaryAutocannon);
session.Ordnance.FireWeapon(new OrdnanceFireRequest(
Module: new MountedModule(hitscanSpec.Module, "hp.weapon.main", 0f),
ShooterStableId: ArenaSession.ContenderStableIdBase,
ShooterContender: session.State.Contenders[0],
ShooterLabel: "Tester",
IsSpectatorShooter: false,
ShooterEntityId: 0,
ShooterPos: muzzle,
MuzzlePos: muzzle,
AimDir: dir,
AimDist: 160f,
SpreadRad: 0f,
TargetEntityStableId: 0UL,
RootDef: hitscanSpec.RootNode,
WeaponKey: hitscanSpec.Key));
// 2. Fire ballistic projectile into Valere slope
var projSpec = ProceduralWeaponGenerator.CreateDreamWeapon(WeaponArchetypeKind.SabotSlugCannon);
session.Ordnance.FireWeapon(new OrdnanceFireRequest(
Module: new MountedModule(projSpec.Module, "hp.weapon.main", 0f),
ShooterStableId: ArenaSession.ContenderStableIdBase,
ShooterContender: session.State.Contenders[0],
ShooterLabel: "Tester",
IsSpectatorShooter: false,
ShooterEntityId: 0,
ShooterPos: muzzle,
MuzzlePos: muzzle,
AimDir: dir,
AimDist: 160f,
SpreadRad: 0f,
TargetEntityStableId: 0UL,
RootDef: projSpec.RootNode,
WeaponKey: projSpec.Key));
var impacts = new List<HitImpactEvent>();
for (int tick = 0; tick < 60; tick++)
{
session.Step();
events.Clear();
session.DrainStepEvents(events);
foreach (var ev in events)
{
if (ev is HitImpactEvent hit)
{
impacts.Add(hit);
}
}
if (impacts.Count >= 2)
{
break;
}
}
Assert.True(impacts.Count >= 2, $"Expected >= 2 slope impacts (hitscan + projectile), got {impacts.Count}");
Assert.All(impacts, h => Assert.Equal((byte)HitTargetKind.Terrain, h.TargetKind));
}
[Fact]
public void RepairArenaScars_ManyScarredTilesRebuildIncrementallyWithoutExhaustingWorldCapacity()
{
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true);
var terrain = session.State.Terrain;
// Materialize 20 resident tiles in a 5x4 grid and crater all 20
var spots = new List<(float X, float Z, float BaseH)>();
for (int tz = 5; tz <= 8; tz++)
{
for (int tx = 5; tx <= 9; tx++)
{
float wx = -terrain.MapHalfExtent + (tx + 0.5f) * terrain.MapTileSize;
float wz = -terrain.MapHalfExtent + (tz + 0.5f) * terrain.MapTileSize;
session.TileSync.EnsureTileResident(session.World, terrain, tx, tz);
float baseH = terrain.SampleHeight(wx, wz);
spots.Add((wx, wz, baseH));
session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = wx,
Z = wz,
Radius = 5f,
Depth = 1.6f
});
}
}
// Flush all 20 cratered tiles into Box3D heightfields without evicting non-actor tiles
int flushedBeforeRepair = session.TileSync.FlushDirtyHeightfields(session.World, terrain, maxTilesPerTick: 20);
Assert.Equal(20, flushedBeforeRepair);
session.World.Step(1f / 60f);
var sion = session.State.SionMap!;
var sionMeta = sion.Metadata;
(float X, float Z, float BaseH) openSpot = default;
bool foundOpenSpot = false;
foreach (var s in spots)
{
if (!sion.IsInsideAnyBuildingXz(s.X, s.Z, padding: 6f))
{
openSpot = s;
foundOpenSpot = true;
break;
}
}
Assert.True(foundOpenSpot, "Expected at least one open-sky spot among the 20 cratered tiles");
float rayStartY = sionMeta.MaxY + 25f;
float raySpanY = -(sionMeta.MaxY - sionMeta.MinY + 60f);
var hitCratered = session.CastWorldRayClosest(new Vector3(openSpot.X, rayStartY, openSpot.Z), new Vector3(0f, raySpanY, 0f));
Assert.True(hitCratered.Hit);
Assert.True(hitCratered.Point.Y < openSpot.BaseH - 1.0f,
$"Expected cratered Box3D raycast height ({hitCratered.Point.Y:F3}) well below base ({openSpot.BaseH:F3})");
int freeBeforeRepair = session.World.FreeBodySlots;
Assert.True(freeBeforeRepair >= 20 + 32);
session.RepairArenaScars();
// When FreeBodySlots >= dirtyResidentCount + 32, RepairArenaScars flushes all dirty resident tiles immediately on tick 0
Assert.True(session.World.View.Count < ArenaSession.WorldBodyCapacity - 256,
$"Expected View.Count ({session.World.View.Count}) well below WorldBodyCapacity ({ArenaSession.WorldBodyCapacity}) after repair");
Assert.Equal(0, session.TileSync.CountDirtyResidentTiles(terrain));
var hitTick0 = session.CastWorldRayClosest(new Vector3(openSpot.X, rayStartY, openSpot.Z), new Vector3(0f, raySpanY, 0f));
Assert.True(hitTick0.Hit);
Assert.True(MathF.Abs(hitTick0.Point.Y - openSpot.BaseH) < 0.05f,
$"Expected tick-0 Box3D raycast height ({hitTick0.Point.Y:F3}) to match restored base ({openSpot.BaseH:F3})");
// Step across ticks so recycled slots remain healthy without exhausting world capacity
for (int t = 0; t < 20; t++)
{
session.Step();
Assert.True(session.World.View.Count < ArenaSession.WorldBodyCapacity - 256,
$"Expected View.Count ({session.World.View.Count}) well below WorldBodyCapacity ({ArenaSession.WorldBodyCapacity}) at tick {t}");
}
foreach (var (wx, wz, baseH) in spots)
{
Assert.Equal(baseH, terrain.SampleHeight(wx, wz), precision: 3);
}
}
[Fact]
public void ServerMatchHost_SionDesertSion_PreservesSionScarsAndDoesNotClobberExplicitScarFile()
{
string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-mapswitch-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
string explicitSionPath = Path.Combine(tempDir, "sion_scars_explicit.cultcache");
try
{
const float craterX = -120f;
const float craterZ = 180f;
float sionBaseH;
float sionScarredH;
using (var host = new ServerMatchHost(
IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion,
autoRestartSec: 0, scarFilePath: explicitSionPath, persistScars: true))
{
sionBaseH = host.Session.State.Terrain.SampleHeight(craterX, craterZ);
host.Session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = craterX,
Z = craterZ,
Radius = 5.5f,
Depth = 1.8f
});
sionScarredH = host.Session.State.Terrain.SampleHeight(craterX, craterZ);
Assert.True(sionScarredH < sionBaseH - 1.2f);
// Switch Sion -> Desert: Desert must NOT inherit Sion craters, nor overwrite explicitSionPath
float desertBaseH;
host.ResetMatch(42, ArenaMapKind.Desert, startInLobby: false);
Assert.Empty(host.Session.State.ScarLedger.Terrain);
desertBaseH = host.Session.State.Terrain.SampleHeight(0f, 0f);
host.Session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = 0f,
Z = 0f,
Radius = 4.5f,
Depth = 1.4f
});
float desertScarredH = host.Session.State.Terrain.SampleHeight(0f, 0f);
Assert.True(desertScarredH < desertBaseH - 0.8f);
// Switch Desert -> Sion: Sion craters must be restored cleanly!
host.ResetMatch(43, ArenaMapKind.Sion, startInLobby: false);
Assert.Equal(sionScarredH, host.Session.State.Terrain.SampleHeight(craterX, craterZ), precision: 3);
// Verify explicitSionPath on disk still holds Sion's AssetFingerprint & crater (never clobbered by Desert)
var diskSnap = ArenaScarLedgerStore.Load(explicitSionPath, host.Session.State.SionMap!.AssetFingerprint);
Assert.Single(diskSnap.Terrain);
Assert.Equal(craterX, diskSnap.Terrain[0].X);
Assert.Equal(craterZ, diskSnap.Terrain[0].Z);
}
// Also verify LocalArenaSession & ListenHostArenaSession carry scars across rounds and Sion -> Desert -> Sion
using (var local = new LocalArenaSession(seed: 42, mapKind: ArenaMapKind.Sion, skipInitialDrop: true))
{
local.Inner.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = craterX,
Z = craterZ,
Radius = 5.5f,
Depth = 1.8f
});
local.RequestNewMatch(43, ArenaMapKind.Sion);
Assert.Equal(sionScarredH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3);
local.RequestNewMatch(42, ArenaMapKind.Desert);
Assert.Empty(local.ViewState.ScarLedger.Terrain);
local.RequestNewMatch(44, ArenaMapKind.Sion);
Assert.Equal(sionScarredH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3);
local.RepairArenaScars();
local.RequestNewMatch(45, ArenaMapKind.Sion);
Assert.Equal(sionBaseH, local.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3);
}
using (var listen = new ListenHostArenaSession(IPAddress.Loopback, 0, seed: 42, mapKind: ArenaMapKind.Sion))
{
listen.Host.Session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = craterX,
Z = craterZ,
Radius = 5.5f,
Depth = 1.8f
});
listen.RequestNewMatch(43, ArenaMapKind.Desert);
Assert.Empty(listen.ViewState.ScarLedger.Terrain);
listen.RequestNewMatch(44, ArenaMapKind.Sion);
Assert.Equal(sionScarredH, listen.ViewState.Terrain.SampleHeight(craterX, craterZ), precision: 3);
}
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
}
[Fact]
public void FlushDirtyHeightfields_RecycledFreeSlots_DoesNotWedgeAtHighViewCount()
{
using var session = new ArenaSession(seed: 42, ArenaMapKind.Sion, slot0Human: true, skipInitialDrop: true);
var terrain = session.State.Terrain;
var sion = session.State.SionMap!;
float cx = -96f, cz = -96f;
bool foundSpot = false;
for (float z = -176f; z <= -16f && !foundSpot; z += 8f)
{
for (float x = -176f; x <= -16f; x += 8f)
{
if (!sion.IsInsideAnyBuildingXz(x, z, padding: 10f))
{
cx = x;
cz = z;
foundSpot = true;
break;
}
}
}
Assert.True(foundSpot, "Expected open-sky spot inside Sion tile (7, 7)");
session.TileSync.EnsureTileRegion(session.World, terrain, cx, cz, halfTileRadius: 0);
// Push View.Count >= 1016, then remove those temporary bodies and step to recycle FreeBodySlots > 500
var tempHandles = new List<Box3DSoaBodyHandle>();
ulong nextId = 900_000UL;
while (session.World.View.Count < 1016 && session.World.FreeBodySlots > 0)
{
tempHandles.Add(session.World.AddStaticBox(nextId++, (0f, -500f, 0f), (0.5f, 0.5f, 0.5f)));
}
Assert.True(session.World.View.Count >= 1016, $"Expected View.Count >= 1016, got {session.World.View.Count}");
foreach (var h in tempHandles)
{
session.World.RemoveBody(h);
}
session.World.Step(1f / 60f);
Assert.True(session.World.View.Count >= 1016, $"Expected monotonic View.Count >= 1016, got {session.World.View.Count}");
Assert.True(session.World.FreeBodySlots > 500, $"Expected recycled FreeBodySlots > 500, got {session.World.FreeBodySlots}");
session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = cx,
Z = cz,
Radius = 6f,
Depth = 2.5f
});
int rebuilt = session.TileSync.FlushDirtyHeightfields(session.World, terrain, maxTilesPerTick: 4);
Assert.Equal(1, rebuilt);
float cpuH = terrain.SampleHeight(cx, cz);
float rayStartY = sion.Metadata.MaxY + 25f;
float raySpanY = -(sion.Metadata.MaxY - sion.Metadata.MinY + 60f);
var hit = session.CastWorldRayClosest(new Vector3(cx, rayStartY, cz), new Vector3(0f, raySpanY, 0f));
Assert.True(hit.Hit);
Assert.True(MathF.Abs(hit.Point.Y - cpuH) < 0.05f,
$"Expected Box3D raycast height ({hit.Point.Y:F3}) to match CPU height ({cpuH:F3}) within 0.05 m");
}
[Fact]
public void ServerMatchHost_ResetMatch_RepairScarsOnCrossMapSwitch_ClearsTargetOnlyAndPreservesSource()
{
string tempDir = Path.Combine(Path.GetTempPath(), "rtd-cut13a-repairswitch-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(tempDir);
string explicitSionPath = Path.Combine(tempDir, "sion_scars_explicit.cultcache");
string desertPath = ServerMatchHost.ResolveScarFilePath(explicitSionPath, ArenaMapKind.Sion, ArenaMapKind.Desert);
try
{
using var host = new ServerMatchHost(
IPAddress.Loopback, 0, seed: 42, ArenaMapKind.Sion,
autoRestartSec: 0, scarFilePath: explicitSionPath, persistScars: true);
string sionFp = host.Session.State.SionMap!.AssetFingerprint;
// Stamp Sion crater
host.Session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = -120f,
Z = 180f,
Radius = 5.5f,
Depth = 1.8f
});
// Switch to Desert and stamp Desert crater
host.ResetMatch(42, ArenaMapKind.Desert, startInLobby: false);
host.Session.State.ApplyTerrainStamp(new TerrainStampEvent
{
Kind = (byte)TerrainStampKind.Crater,
X = 0f,
Z = 0f,
Radius = 4.5f,
Depth = 1.4f
});
// Switch back to Sion, then ResetMatch(42, Desert, repairScars: true) FROM Sion
host.ResetMatch(42, ArenaMapKind.Sion, startInLobby: false);
Assert.Single(host.Session.State.ScarLedger.Terrain);
host.ResetMatch(42, ArenaMapKind.Desert, startInLobby: false, repairScars: true);
Assert.Empty(host.Session.State.ScarLedger.Terrain);
var sionDisk = ArenaScarLedgerStore.Load(explicitSionPath, sionFp);
var desertDisk = ArenaScarLedgerStore.Load(desertPath, "desert:42");
Assert.Single(sionDisk.Terrain);
Assert.Empty(desertDisk.Terrain);
}
finally
{
if (Directory.Exists(tempDir))
{
Directory.Delete(tempDir, recursive: true);
}
}
}
}
}

View file

@ -13,7 +13,7 @@ namespace RustToDust.Tests
public void Generate_ProducesDeterministicNonFlatReliefWithinBounds()
{
Assert.Equal(1536f, TerrainField.ArenaSize);
Assert.Equal(8, TerrainField.TileGridCount);
Assert.Equal(8, TerrainField.DesertTileGridCount);
Assert.Equal(192f, TerrainField.TileSize);
Assert.Equal(-18f, TerrainField.MinWorldHeight);
Assert.Equal(52f, TerrainField.MaxWorldHeight);
@ -56,7 +56,6 @@ namespace RustToDust.Tests
public void StampCrater_LowersCenterRaisesRimAndDirtyOnlyOverlappingTiles()
{
var terrain = TerrainField.Generate(42UL, Array.Empty<ArenaBoxSpec>());
terrain.ClearDirtyMask();
// Tile (3, 3) spans X in [-192, 0), Z in [-192, 0).
// Point (-96, -96) with radius 6m is strictly inside tile (3, 3) and nowhere else.
@ -79,15 +78,15 @@ namespace RustToDust.Tests
$"Expected crater ejecta rim to rise >0.2m (before {beforeRim:F2}, after {afterRim:F2})");
// Only tile (3, 3) should have incremented from version 1 to 2
for (int tz = 0; tz < TerrainField.TileGridCount; tz++)
for (int tz = 0; tz < terrain.TileGridCount; tz++)
{
for (int tx = 0; tx < TerrainField.TileGridCount; tx++)
for (int tx = 0; tx < terrain.TileGridCount; tx++)
{
int expected = (tx == 3 && tz == 3) ? 2 : 1;
Assert.Equal(expected, terrain.TileVersions[tx, tz]);
Assert.Equal(expected, terrain.StructuralTileVersions[tx, tz]);
Assert.Equal(expected, terrain.VisualTileVersions[tx, tz]);
}
}
Assert.Equal(1UL << (3 * TerrainField.TileGridCount + 3), terrain.DirtyTileMask);
}
[Fact]

View file

@ -362,7 +362,7 @@ $gCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "gear") -DestDir
$dCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "decals") -DestDir (Join-Path $stagedAssetsDir "decals") -IncludeExtensions @(".png")
$aCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "audio") -DestDir (Join-Path $stagedAssetsDir "audio") -IncludeExtensions @(".wav", ".md")
$fCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "fonts") -DestDir (Join-Path $stagedAssetsDir "fonts") -IncludeExtensions @(".ttf", ".txt", ".md")
$mCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "maps\sion") -DestDir (Join-Path $stagedAssetsDir "maps\sion") -IncludeExtensions @(".json", ".f32", ".png", ".bin", ".glb")
$mCount = Copy-FilteredTree -SourceDir (Join-Path $AssetsSrcDir "maps\sion") -DestDir (Join-Path $stagedAssetsDir "maps\sion") -IncludeExtensions @(".json", ".u16z", ".png", ".bin", ".glb")
foreach ($reqFontFile in @("Krypton.ttf", "OFL-1.1.txt", "HARFBUZZ-COPYING.txt")) {
$reqPath = Join-Path (Join-Path $stagedAssetsDir "fonts") $reqFontFile
if (-not (Test-Path $reqPath)) {

View file

@ -27,6 +27,7 @@ import struct
import urllib.parse
import urllib.request
import zipfile
import zlib
from collections import Counter, defaultdict
from pathlib import Path
@ -54,12 +55,15 @@ import tifffile
# ---------------------------------------------------------------------------
ARENA_SIZE_M = 3072.0
HALF_EXTENT_M = 1536.0
GRID_RES = 1025
CELL_SIZE_M = ARENA_SIZE_M / (GRID_RES - 1) # 3.0m exact
TILE_GRID = 6
TILE_SIZE_M = ARENA_SIZE_M / TILE_GRID # 512.0m exact
GRID_RES = 6145
CELL_SIZE_M = ARENA_SIZE_M / (GRID_RES - 1) # 0.5m exact
TILE_GRID = 16
TILE_SIZE_M = ARENA_SIZE_M / TILE_GRID # 192.0m exact
BUILDING_TILE_GRID = 6
BUILDING_TILE_SIZE_M = ARENA_SIZE_M / BUILDING_TILE_GRID # 512.0m legacy until Cut 13b
SURFACE_TEX_RES = 2048
SURFACE_TEX_RES = 4096
SURFACE_MASK_RES = 2048
# Centered around Valere & Tourbillon twin citadels to frame:
# - Valere & Tourbillon fortress hills
@ -77,8 +81,8 @@ WMS_BASE_URL = "https://wms.geo.admin.ch/"
SKIRT_DEPTH_M = 4.0
MAX_LOD1_TRIS = 275_000
MAX_TILES_GLB_BYTES = 28_000_000
MAX_SURFACE_PNG_BYTES = 3_000_000
MAX_TOTAL_ASSETS_BYTES = 40_000_000
MAX_SURFACE_PNG_BYTES = 14_000_000
MAX_TOTAL_ASSETS_BYTES = 85_000_000
# ---------------------------------------------------------------------------
@ -266,7 +270,7 @@ def acquire_swisstopo_data(
if (ek, nk) not in needed_tiles:
continue
for asset_name, asset in item.get("assets", {}).items():
if "_2_2056_5728.tif" in asset_name:
if "_0.5_2056_5728.tif" in asset_name:
prev = best_alti.get((ek, nk))
if prev is None or yr > prev[0]:
best_alti[(ek, nk)] = (yr, item["id"], asset_name, asset["href"])
@ -320,7 +324,7 @@ def acquire_swisstopo_data(
def sample_mosaic_grid(
mosaic: np.ndarray, e_origin: float, n_top: float, center_e: float, center_n: float, res: int
) -> np.ndarray:
pixel_m = 2.0
pixel_m = 0.5
step_m = ARENA_SIZE_M / (res - 1)
xs = -HALF_EXTENT_M + np.arange(res, dtype=np.float64) * step_m
zs = -HALF_EXTENT_M + np.arange(res, dtype=np.float64) * step_m
@ -337,7 +341,7 @@ def build_heightmap(
) -> tuple[np.ndarray, np.ndarray, float, float, float]:
ekms = sorted({k[0] for k in tif_paths})
nkms = sorted({k[1] for k in tif_paths}, reverse=True) # north-to-south rows
tile_px = 500
tile_px = 2000
mosaic = np.zeros((len(nkms) * tile_px, len(ekms) * tile_px), dtype=np.float32)
for ni, nk in enumerate(nkms):
@ -351,8 +355,8 @@ def build_heightmap(
n_top = (nkms[0] + 1) * 1000.0
# Grid coordinates in RustToDust:
# row iz (0..1024): Z = -1536 + iz * 3.0 (North -> South), N = center_n - Z
# col ix (0..1024): X = -1536 + ix * 3.0 (West -> East), E = center_e + X
# row iz (0..6144): Z = -1536 + iz * 0.5 (North -> South), N = center_n - Z
# col ix (0..6144): X = -1536 + ix * 0.5 (West -> East), E = center_e + X
hm_asl = sample_mosaic_grid(mosaic, e_origin, n_top, center_e, center_n, GRID_RES)
surf_dem_asl = sample_mosaic_grid(mosaic, e_origin, n_top, center_e, center_n, SURFACE_TEX_RES)
@ -362,6 +366,37 @@ def build_heightmap(
return hm_rel, surf_dem_asl, base_elev, float(hm_rel.min()), float(hm_rel.max())
def export_heightmap_u16z(hm: np.ndarray, out_path: Path) -> tuple[float, float, str]:
"""
Export 0.5m quantized heightmap as heightmap_05m.u16z:
Header (24 bytes LE):
magic="RDHM", uint32 version=2, uint32 gridRes=6145,
float32 minY, float32 scale, uint32 rawByteCount
Payload:
zlib-compressed row-wise zig-zag int16 spatial prediction residuals of uint16[gridRes*gridRes].
"""
min_y = float(np.float32(hm.min()))
max_y = float(np.float32(hm.max()))
scale = float(np.float32(max(1e-6, (max_y - min_y) / 65535.0)))
q = np.clip(np.round((hm.astype(np.float64) - min_y) / scale), 0, 65535).astype(np.uint16)
pred = np.empty_like(q)
pred[0, 0] = 0
pred[1:, 0] = q[:-1, 0]
pred[:, 1:] = q[:, :-1]
diff = (q.astype(np.int32) - pred.astype(np.int32)).astype(np.int16)
d32 = diff.astype(np.int32)
zz = (((d32 << 1) ^ (d32 >> 15)) & 0xFFFF).astype(np.uint16)
raw_bytes = np.ascontiguousarray(zz, dtype="<u2").tobytes()
compressed = zlib.compress(raw_bytes, level=6)
header = struct.pack("<4sIIffI", b"RDHM", 2, int(hm.shape[0]), min_y, scale, len(raw_bytes))
payload = header + compressed
out_path.write_bytes(payload)
dem_hash = hashlib.sha256(payload).hexdigest()
return min_y, scale, dem_hash
def acquire_wms_masks(
cache_dir: Path, e0: float, n0: float, e1: float, n1: float, res: int = SURFACE_TEX_RES
) -> dict[str, np.ndarray]:
@ -386,9 +421,18 @@ def acquire_wms_masks(
print(f" [WMS fetch] {layer} -> {dest.name}")
req = urllib.request.Request(url, headers={"User-Agent": "RustToDust-SionBaker/1.0"})
tmp = dest.with_suffix(".png.part")
with urllib.request.urlopen(req, timeout=45) as resp:
tmp.write_bytes(resp.read())
tmp.replace(dest)
try:
with urllib.request.urlopen(req, timeout=45) as resp:
tmp.write_bytes(resp.read())
tmp.replace(dest)
except Exception:
if res > 2048:
fallback = acquire_wms_masks(cache_dir, e0, n0, e1, n1, 2048)
return {
k: zoom(v, (res / v.shape[0], res / v.shape[1], 1), order=1)
for k, v in fallback.items()
}
raise
out[key] = imagecodecs.png_decode(dest.read_bytes())
return out
@ -452,13 +496,10 @@ def build_terrain_surface_texture(
fp_res_tris: list[np.ndarray],
fp_ind_tris: list[np.ndarray],
fp_fort_tris: list[np.ndarray],
) -> bytes:
) -> tuple[bytes, bytes]:
"""
Synthesize 2048x2048 RGB surface albedo PNG (< 3 MB) combining:
- Grey alpine limestone cliffs (steep Valere / Tourbillon / hillside slopes)
- Valley meadows, terraced vineyards & alpine forest slopes
- Old Town stone plazas, industrial yards, rail ballast & road/bridge network
- Rhone river & canal glacial teal-blue water tint
Synthesize 4096x4096 RGB surface albedo PNG and 2048x2048 RGBA8 surface class mask PNG
(R=rock_cliff, G=grass_vineyard, B=asphalt_gravel, A=water_channel).
"""
res = dem_asl.shape[0]
px_m = ARENA_SIZE_M / (res - 1) # 1.5m/px
@ -572,6 +613,7 @@ def build_terrain_surface_texture(
water_col = np.array([0.13, 0.27, 0.34], dtype=np.float32) + (fbm[..., None] - 0.5) * 0.03
rgb = rgb * (1.0 - water_soft[..., None] * 0.96) + water_col * (water_soft[..., None] * 0.96)
road_total = np.zeros((res, res), dtype=np.float32)
# 6. Roads, highway A9 & bridges (drawn after water so bridges span the Rhone!)
if wms_masks and "roads" in wms_masks:
r_rgba = wms_masks["roads"]
@ -586,11 +628,28 @@ def build_terrain_surface_texture(
highway_col = np.array([0.25, 0.25, 0.26], dtype=np.float32)
rgb = rgb * (1.0 - minor_soft[..., None] * 0.72) + street_col * (minor_soft[..., None] * 0.72)
rgb = rgb * (1.0 - major_soft[..., None] * 0.88) + highway_col * (major_soft[..., None] * 0.88)
road_total = np.clip(np.maximum(minor_soft, major_soft), 0.0, 1.0)
# Darken slightly under exact building footprints for subtle ambient grounding
bldg_under = (mask_res | mask_ind | mask_fort) & (normal_y > 0.75)
rgb[bldg_under] *= 0.88
# Build 2048x2048 RGBA8 surface class mask:
# R = rock_cliff, G = grass_vineyard, B = asphalt_gravel, A = water_channel
water_ch = gaussian_filter(water_mask.astype(np.float32), sigma=1.0) if np.any(water_mask) else np.zeros((res, res), dtype=np.float32)
rail_ch = gaussian_filter(binary_dilation(wms_masks["rail"][..., 3] > 50, iterations=4).astype(np.float32), sigma=1.2) if (wms_masks and "rail" in wms_masks) else np.zeros((res, res), dtype=np.float32)
asphalt_gravel = np.clip(np.maximum(road_total, np.maximum(rail_ch, np.maximum(res_soft, np.maximum(ind_soft, fort_soft)))), 0.0, 1.0)
rock_cliff = np.clip(cliff_t, 0.0, 1.0)
grass_vineyard = np.clip((1.0 - rock_cliff) * (1.0 - water_ch) * (1.0 - asphalt_gravel * 0.85), 0.0, 1.0)
mask_full = np.stack([rock_cliff, grass_vineyard, asphalt_gravel, np.clip(water_ch, 0.0, 1.0)], axis=-1)
step = max(1, res // SURFACE_MASK_RES)
if step > 1:
mask_ds = mask_full.reshape(SURFACE_MASK_RES, step, SURFACE_MASK_RES, step, 4).mean(axis=(1, 3))
else:
mask_ds = mask_full
mask_u8 = np.clip(np.round(mask_ds * 255.0), 0, 255).astype(np.uint8)
mask_png_bytes = imagecodecs.png_encode(mask_u8, level=9)
rgb_u8 = np.clip(np.round(rgb * 255.0), 0, 255).astype(np.uint8)
png_bytes = imagecodecs.png_encode(rgb_u8, level=9)
if len(png_bytes) >= MAX_SURFACE_PNG_BYTES:
@ -600,7 +659,7 @@ def build_terrain_surface_texture(
if len(png_bytes) >= MAX_SURFACE_PNG_BYTES:
rgb_u8 = (rgb_u8 & 0xFC)
png_bytes = imagecodecs.png_encode(rgb_u8, level=9)
return png_bytes
return png_bytes, mask_png_bytes
def sample_heightmap(hm: np.ndarray, x: np.ndarray | float, z: np.ndarray | float) -> np.ndarray | float:
@ -1715,6 +1774,7 @@ def main() -> None:
parser.add_argument("--cache-dir", default=os.path.join(os.environ.get("TEMP", "/tmp"), "sion-cache"))
parser.add_argument("--center-e", type=float, default=DEFAULT_CENTER_E)
parser.add_argument("--center-n", type=float, default=DEFAULT_CENTER_N)
parser.add_argument("--terrain-only", action="store_true", help="Re-bake 0.5m DEM, surface, mask & metadata.json while preserving existing tiles/ & buildings_manifest.json")
args = parser.parse_args()
repo_root = Path(args.repo_root).resolve()
@ -1725,21 +1785,23 @@ def main() -> None:
cache_dir = Path(args.cache_dir)
cache_dir.mkdir(parents=True, exist_ok=True)
# Cut obsolete single-monolith GLBs & any stale tile files before baking
for obsolete in ("sion_lod2.glb", "sion_lod1.glb"):
# Cut obsolete single-monolith GLBs & legacy float32 heightmap
for obsolete in ("sion_lod2.glb", "sion_lod1.glb", "heightmap.f32"):
obs_path = out_dir / obsolete
if obs_path.exists():
obs_path.unlink()
print(f"[Sion Baker] Removed obsolete monolith {obs_path.name}")
for stale in tiles_dir.iterdir():
if stale.is_file():
stale.unlink()
print(f"[Sion Baker] Removed obsolete {obs_path.name}")
if not args.terrain_only:
for stale in tiles_dir.iterdir():
if stale.is_file():
stale.unlink()
cE, cN = args.center_e, args.center_n
e0, n0, e1, n1 = cE - HALF_EXTENT_M, cN - HALF_EXTENT_M, cE + HALF_EXTENT_M, cN + HALF_EXTENT_M
print(
f"[Sion Baker] Arena {ARENA_SIZE_M:.0f}m x {ARENA_SIZE_M:.0f}m ({TILE_GRID}x{TILE_GRID} tiles of {TILE_SIZE_M:.0f}m) "
f"[Sion Baker] Arena {ARENA_SIZE_M:.0f}m x {ARENA_SIZE_M:.0f}m (terrain {TILE_GRID}x{TILE_GRID} @ {TILE_SIZE_M:.0f}m, "
f"bldg {BUILDING_TILE_GRID}x{BUILDING_TILE_GRID} @ {BUILDING_TILE_SIZE_M:.0f}m) "
f"EPSG:2056 center=({cE:.1f}, {cN:.1f}) bbox=[{e0:.1f}..{e1:.1f}, {n0:.1f}..{n1:.1f}]"
)
tif_paths, gdb_paths, stac_ids = acquire_swisstopo_data(cache_dir, e0, n0, e1, n1)
@ -1750,15 +1812,105 @@ def main() -> None:
except Exception as exc:
print(f" [WMS warning] Falling back to DEM-only river/road synthesis ({exc})")
print(f"[Sion Baker] Stitching & resampling swissALTI3D to {GRID_RES}x{GRID_RES} float32...")
print(f"[Sion Baker] Stitching & resampling swissALTI3D 0.5m to {GRID_RES}x{GRID_RES}...")
hm, surf_dem_asl, base_elev, min_y, max_y = build_heightmap(tif_paths, cE, cN)
hm_path = out_dir / "heightmap.f32"
hm.astype("<f4").tofile(str(hm_path))
hm_path = out_dir / "heightmap_05m.u16z"
hm_min_y, hm_scale, dem_hash = export_heightmap_u16z(hm, hm_path)
print(
f" heightmap.f32: {hm.shape}, {hm_path.stat().st_size:,} bytes, "
f"baseElevationM={base_elev:.2f}m, Y=[{min_y:.2f}, {max_y:.2f}]m (relief={max_y - min_y:.2f}m)"
f" heightmap_05m.u16z: {hm.shape}, {hm_path.stat().st_size:,} bytes, "
f"baseElevationM={base_elev:.2f}m, Y=[{min_y:.2f}, {max_y:.2f}]m (scale={hm_scale:.6f}m/step, sha256={dem_hash[:12]}...)"
)
if args.terrain_only:
meta_path = out_dir / "metadata.json"
existing_meta = json.loads(meta_path.read_text(encoding="utf-8")) if meta_path.exists() else {}
manifest_path = out_dir / "buildings_manifest.json"
manifest_data = json.loads(manifest_path.read_text(encoding="utf-8"))
fp_res_tris: list[np.ndarray] = []
fp_ind_tris: list[np.ndarray] = []
fp_fort_tris: list[np.ndarray] = []
for b in manifest_data.get("buildings", []):
cx, cz = float(b["center"][0]), float(b["center"][2])
hx, hz = float(b["size"][0]) * 0.5, float(b["size"][2]) * 0.5
gy = float(b.get("groundY", 0.0))
p0 = np.array([cx - hx, gy, cz - hz])
p1 = np.array([cx + hx, gy, cz - hz])
p2 = np.array([cx + hx, gy, cz + hz])
p3 = np.array([cx - hx, gy, cz + hz])
t1 = np.stack([p0, p1, p2], axis=0)
t2 = np.stack([p0, p2, p3], axis=0)
st = b.get("archStyle", "residential")
if st == "fortress":
fp_fort_tris.extend((t1, t2))
elif st == "industrial":
fp_ind_tris.extend((t1, t2))
else:
fp_res_tris.extend((t1, t2))
print(f"[Sion Baker] Synthesizing {SURFACE_TEX_RES}x{SURFACE_TEX_RES} terrain_surface.png + {SURFACE_MASK_RES}x{SURFACE_MASK_RES} terrain_surface_mask.png...")
surf_png, mask_png = build_terrain_surface_texture(
surf_dem_asl, base_elev, wms_masks, fp_res_tris, fp_ind_tris, fp_fort_tris
)
surf_path = out_dir / "terrain_surface.png"
surf_path.write_bytes(surf_png)
mask_path = out_dir / "terrain_surface_mask.png"
mask_path.write_bytes(mask_png)
print(f" terrain_surface.png: {len(surf_png):,} bytes ({len(surf_png)/1e6:.2f} MB)")
print(f" terrain_surface_mask.png: {len(mask_png):,} bytes ({len(mask_png)/1e6:.2f} MB)")
meta = {
"name": "Sion, Valais, Switzerland",
"attribution": "Federal Office of Topography swisstopo",
"sources": [
"ch.swisstopo.swissalti3d (0.5m DTM, Open Government Data)",
"ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)",
],
"stacItems": stac_ids,
"demAssetHash": dem_hash,
"crs": "EPSG:2056",
"originE": e0,
"originN": n0,
"centerE": cE,
"centerN": cN,
"baseElevationM": base_elev,
"minY": round(min_y, 3),
"maxY": round(max_y, 3),
"reliefM": round(max_y - min_y, 3),
"sizeMeters": ARENA_SIZE_M,
"tileGrid": TILE_GRID,
"tileSizeMeters": TILE_SIZE_M,
"buildingTileGrid": BUILDING_TILE_GRID,
"buildingTileSizeMeters": BUILDING_TILE_SIZE_M,
"gridRes": GRID_RES,
"cellSizeMeters": CELL_SIZE_M,
"heightmapFile": "heightmap_05m.u16z",
"heightmapFormat": "rdhm_v2_u16_zigzag_zlib",
"heightmapMinY": hm_min_y,
"heightmapScale": hm_scale,
"surfaceTexture": "terrain_surface.png",
"surfaceTextureSize": SURFACE_TEX_RES,
"surfaceTextureFormat": "png_rgb_north_to_south_west_to_east",
"surfaceMaskTexture": "terrain_surface_mask.png",
"surfaceMaskTextureSize": SURFACE_MASK_RES,
"surfaceMaskFormat": "png_rgba_rock_grass_asphalt_water",
"collisionFormat": existing_meta.get("collisionFormat", {}),
"rowOrder": "north_to_south_z_neg_to_pos",
"colOrder": "west_to_east_x_neg_to_pos",
"coordinateTransform": {
"X": "E - centerE (East = +X)",
"Y": "Z_asl - baseElevationM (Up = +Y)",
"Z": "-(N - centerN) (North = -Z)",
},
"tileCount": existing_meta.get("tileCount", len(existing_meta.get("tiles", []))),
"tiles": existing_meta.get("tiles", []),
}
meta_path.write_text(json.dumps(meta, indent=2), encoding="utf-8")
total_assets_bytes = sum(p.stat().st_size for p in out_dir.rglob("*") if p.is_file())
print(f"[Sion Baker] Terrain-only complete | Total assets/maps/sion = {total_assets_bytes/1e6:.2f} MB (< {MAX_TOTAL_ASSETS_BYTES/1e6:.0f} MB limit)")
if total_assets_bytes >= MAX_TOTAL_ASSETS_BYTES:
raise RuntimeError(f"Total asset budget exceeded: {total_assets_bytes} bytes >= {MAX_TOTAL_ASSETS_BYTES}")
return
# Read semantic layers across intersecting GDB tiles
print("[Sion Baker] Reading swissBUILDINGS3D 3.0 layers (Building_solid, Wall, Roof, Floor)...")
reader = OgrReader()
@ -1877,8 +2029,8 @@ def main() -> None:
bmax = all_rtd_pts.max(axis=0)
box_center = (bmin + bmax) * 0.5
tx = max(0, min(TILE_GRID - 1, int(math.floor((float(box_center[0]) + HALF_EXTENT_M) / TILE_SIZE_M))))
tz = max(0, min(TILE_GRID - 1, int(math.floor((float(box_center[2]) + HALF_EXTENT_M) / TILE_SIZE_M))))
tx = max(0, min(BUILDING_TILE_GRID - 1, int(math.floor((float(box_center[0]) + HALF_EXTENT_M) / BUILDING_TILE_SIZE_M))))
tz = max(0, min(BUILDING_TILE_GRID - 1, int(math.floor((float(box_center[2]) + HALF_EXTENT_M) / BUILDING_TILE_SIZE_M))))
tkey = (tx, tz)
tile_bldg_counts[tkey] += 1
@ -1942,16 +2094,19 @@ def main() -> None:
}
)
# Bake 2048x2048 terrain_surface.png albedo
print(f"[Sion Baker] Synthesizing {SURFACE_TEX_RES}x{SURFACE_TEX_RES} terrain_surface.png...")
surf_png = build_terrain_surface_texture(
# Bake 4096x4096 terrain_surface.png albedo + 2048x2048 terrain_surface_mask.png
print(f"[Sion Baker] Synthesizing {SURFACE_TEX_RES}x{SURFACE_TEX_RES} terrain_surface.png + {SURFACE_MASK_RES}x{SURFACE_MASK_RES} terrain_surface_mask.png...")
surf_png, mask_png = build_terrain_surface_texture(
surf_dem_asl, base_elev, wms_masks, fp_res_tris, fp_ind_tris, fp_fort_tris
)
surf_path = out_dir / "terrain_surface.png"
surf_path.write_bytes(surf_png)
mask_path = out_dir / "terrain_surface_mask.png"
mask_path.write_bytes(mask_png)
print(f" terrain_surface.png: {len(surf_png):,} bytes ({len(surf_png)/1e6:.2f} MB)")
print(f" terrain_surface_mask.png: {len(mask_png):,} bytes ({len(mask_png)/1e6:.2f} MB)")
if len(surf_png) >= MAX_SURFACE_PNG_BYTES:
raise RuntimeError(f"terrain_surface.png exceeded 3 MB budget: {len(surf_png)} bytes")
raise RuntimeError(f"terrain_surface.png exceeded budget: {len(surf_png)} bytes")
# Export per-tile LOD2 GLBs & RCOL v1 collision bins
non_empty_tiles = sorted(tile_bldg_counts.keys())
@ -1971,8 +2126,8 @@ def main() -> None:
total_lod2_bytes += l2_bytes
total_col_tris += c_tris
total_col_bytes += c_bytes
tile_cx = -HALF_EXTENT_M + (tx + 0.5) * TILE_SIZE_M
tile_cz = -HALF_EXTENT_M + (tz + 0.5) * TILE_SIZE_M
tile_cx = -HALF_EXTENT_M + (tx + 0.5) * BUILDING_TILE_SIZE_M
tile_cz = -HALF_EXTENT_M + (tz + 0.5) * BUILDING_TILE_SIZE_M
tile_stats[tkey] = {
"tx": tx,
"tz": tz,
@ -2035,8 +2190,8 @@ def main() -> None:
"coordinateSystem": "rusttodust_arena_gltf",
"attribution": "Federal Office of Topography swisstopo",
"sizeMeters": ARENA_SIZE_M,
"tileGrid": TILE_GRID,
"tileSizeMeters": TILE_SIZE_M,
"tileGrid": BUILDING_TILE_GRID,
"tileSizeMeters": BUILDING_TILE_SIZE_M,
"count": len(manifest_entries),
"classes": dict(class_counts.most_common()),
"buildings": manifest_entries,
@ -2048,10 +2203,11 @@ def main() -> None:
"name": "Sion, Valais, Switzerland",
"attribution": "Federal Office of Topography swisstopo",
"sources": [
"ch.swisstopo.swissalti3d (2m DTM, Open Government Data)",
"ch.swisstopo.swissalti3d (0.5m DTM, Open Government Data)",
"ch.swisstopo.swissbuildings3d_3_0 (LOD2 3D Buildings, Open Government Data)",
],
"stacItems": stac_ids,
"demAssetHash": dem_hash,
"crs": "EPSG:2056",
"originE": e0,
"originN": n0,
@ -2064,12 +2220,20 @@ def main() -> None:
"sizeMeters": ARENA_SIZE_M,
"tileGrid": TILE_GRID,
"tileSizeMeters": TILE_SIZE_M,
"buildingTileGrid": BUILDING_TILE_GRID,
"buildingTileSizeMeters": BUILDING_TILE_SIZE_M,
"gridRes": GRID_RES,
"cellSizeMeters": CELL_SIZE_M,
"heightmapFormat": "float32_le_row_major",
"heightmapFile": "heightmap_05m.u16z",
"heightmapFormat": "rdhm_v2_u16_zigzag_zlib",
"heightmapMinY": hm_min_y,
"heightmapScale": hm_scale,
"surfaceTexture": "terrain_surface.png",
"surfaceTextureSize": SURFACE_TEX_RES,
"surfaceTextureFormat": "png_rgb_north_to_south_west_to_east",
"surfaceMaskTexture": "terrain_surface_mask.png",
"surfaceMaskTextureSize": SURFACE_MASK_RES,
"surfaceMaskFormat": "png_rgba_rock_grass_asphalt_water",
"collisionFormat": {
"magic": "RCOL",
"version": 1,
@ -2096,7 +2260,7 @@ def main() -> None:
print(
f"[Sion Baker] Summary: {len(manifest_entries)} buildings across {len(non_empty_tiles)} tiles | "
f"LOD1+LOD2 GLBs = {combined_glb_bytes/1e6:.2f} MB (< 28 MB limit) | "
f"Total assets/maps/sion = {total_assets_bytes/1e6:.2f} MB (< 40 MB limit)"
f"Total assets/maps/sion = {total_assets_bytes/1e6:.2f} MB (< 85 MB limit)"
)
if combined_glb_bytes >= MAX_TILES_GLB_BYTES:
raise RuntimeError(f"Combined tile GLB budget exceeded: {combined_glb_bytes} bytes >= {MAX_TILES_GLB_BYTES}")