diff --git a/.gitignore b/.gitignore index 07bda0a..4642f47 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,7 @@ __pycache__/ /out/ /scratch/ +bin/ +obj/ +.godot/ +.vs/ diff --git a/README.md b/README.md index e28e9d8..6823b5c 100644 --- a/README.md +++ b/README.md @@ -8,21 +8,54 @@ The lore lives in Weksa: `settings/rust-to-dust/` in [GameCult/Weksa](https://github.com/GameCult/Weksa) (setting, story, battle royale, aliens, language design). This repo holds no lore. -## What is here today +## What is live today (`nibu/rtd-prototype`) -Nothing runnable yet. This repo is the home for the mech work now being -prototyped: +- **`RustToDust.Core`**: + - Aetheria 2D grid chassis (`Dorsal` vehicles/quadrupeds and `Coronal` bipeds), + conductive/radiative heat transfer, trapezoidal thermal plateau curves, + localized armor + core destruction, and live cargo-to-hardpoint swapping. + - 6 playable chassis (`buggy`, `technical`, `tank`, `manticore`, `raptor`, + `paladin`), 8 human salvage modules, and 5 Imperial Tourist modules. + - Shrinking `SpectatorRing` perimeter (`Tourist`, `Patron`, and `Exemplar` + tiers with `Neutral` / `Cleared` / `Provoked` stances and Weksa-voiced + `BroadcastFeed` commentary). + - `TerrainField`: deterministic `384m x 384m` desert terrain divided into a + `4x4` (`96m x 96m`) tile grid with procedural dunes, mesas, salvage pads, + dirt roads, and runtime crater / tire-track / thermal-scorch stamping. +- **`RustToDust.Ymir`**: + - `ArenaSession` bridging `MatchState` onto Ymir's `Box3DSoaWorld` with + 4-corner spring-damper terrain support, raycast weapons, terrain crater/scorch + impacts, and AI contenders + perimeter spectators. +- **`tests/RustToDust.Tests`**: + - Behavioral xUnit suite covering Aetheria grid heat, spectator ring clearance, + Ymir vehicle driving/combat/swapping, and procedural/dynamic terrain relief. +- **`client/` (Godot 4.7.2 Mono)**: + - 3D desert client with a top-down orthographic `SubViewport` brush-to-tile PBR + + height displacement baker, procedural 3D chassis/spectator silhouettes, + tactical radar, clickable Aetheria Hardpoint & Heat schematic, and Imperial + Broadcast chyron. -- mechs kitbashed from parts with [Brokkr](https://eureka.gamecult.org/forge/GameCult/Brokkr) - (armour shells, ribs, cuts, joints, hoses, frames); -- a mechanical rig with one bone per degree of freedom, driven rams and linkages; -- generic walk and combat animation retargeted onto each chassis. +## Build, test, and run -That work currently lives on `nibu/fable-*` experiment branches in -GameCult/Brokkr and moves here as it settles. +Requires a sibling `Ymir` checkout beside `RustToDust` (or `YMIR_ROOT` set), +CMake, a C compiler, .NET SDK 8/10, and Godot 4.7.2 Mono (`--path client`). -## Planned, not live +```bash +# Run the behavioral test suite +dotnet test tests/RustToDust.Tests/RustToDust.Tests.csproj -c Release -- Mech parts library and chassis definitions. -- Rig generator and goal-space retargeting solver. -- A playable walk-and-fight prototype. +# Build the Godot 4.7.2 Mono client assembly (also builds Ymir native Box3D) +dotnet build client/RustToDust.Client.csproj -c Debug + +# Run the playable 3D client +godot --path client + +# Run the headless Godot smoke test +godot --headless --path client res://tests/Smoke.tscn +``` + +## Planned, not live yet + +- Kitbashed Brokkr mechanical rigs and goal-space walk/combat retargeting + replacing the procedural box/cylinder silhouettes. +- Multiplayer networking and audio synthesis. diff --git a/client/ArenaRenderer.cs b/client/ArenaRenderer.cs new file mode 100644 index 0000000..a4895ac --- /dev/null +++ b/client/ArenaRenderer.cs @@ -0,0 +1,766 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; +using RustToDust.Ymir; + +namespace RustToDust.Client; + +/// +/// Renders the 3D arena entities from : +/// cover ruins, shrinking Safe Circle ring, 6 distinct chassis silhouettes, +/// 3 alien spectator tiers + status halos/lock lasers, salvage drops, and weapon tracers. +/// +public partial class ArenaRenderer : Node3D +{ + private static readonly Color OlivePaint = Color.FromHtml("#9bb06a"); + private static readonly Color SignalOrange = Color.FromHtml("#e08a4a"); + private static readonly Color RivalSteel = Color.FromHtml("#6a584b"); + private static readonly Color RivalAccent = Color.FromHtml("#b64a32"); + private static readonly Color TouristGold = Color.FromHtml("#e6b838"); + private static readonly Color TouristIvory = Color.FromHtml("#f2ead8"); + private static readonly Color PatronTeal = Color.FromHtml("#2d7a78"); + private static readonly Color PatronBronze = Color.FromHtml("#a86c36"); + private static readonly Color ExemplarObsidian = Color.FromHtml("#18181d"); + private static readonly Color ExemplarCrimson = Color.FromHtml("#c92a2a"); + private static readonly Color CyanSalvage = Color.FromHtml("#44d9e8"); + private static readonly Color CoverRust = Color.FromHtml("#4d433b"); + private static readonly Color BermDark = Color.FromHtml("#2c2723"); + + private sealed class ActorVisual + { + public Node3D Root = null!; + public Node3D? AimPivot; + public StandardMaterial3D HeatMat = null!; + public MeshInstance3D? HaloMesh; + public StandardMaterial3D? HaloMat; + public MeshInstance3D? LaserMesh; + public StandardMaterial3D? LaserMat; + public string ChassisId = ""; + } + + private Node3D _staticGroup = null!; + private Node3D _actorsGroup = null!; + private Node3D _dropsGroup = null!; + private Node3D _tracersGroup = null!; + private MeshInstance3D _safeRingMesh = null!; + private ImmediateMesh _safeRingImm = null!; + + private readonly Dictionary _contenderVisuals = new(); + private readonly Dictionary _spectatorVisuals = new(); + private readonly Dictionary _dropVisuals = new(); + private readonly List _tracerPool = new(); + + private StandardMaterial3D _safeRingMat = null!; + private StandardMaterial3D _coverMat = null!; + private StandardMaterial3D _bermMat = null!; + private StandardMaterial3D _humanCrateMat = null!; + private StandardMaterial3D _imperialCrateMat = null!; + private StandardMaterial3D _cyanBeaconMat = null!; + private MatchState? _builtForState; + + public override void _Ready() + { + _staticGroup = new Node3D { Name = "StaticArena" }; + _actorsGroup = new Node3D { Name = "Actors" }; + _dropsGroup = new Node3D { Name = "GroundDrops" }; + _tracersGroup = new Node3D { Name = "Tracers" }; + AddChild(_staticGroup); + AddChild(_actorsGroup); + AddChild(_dropsGroup); + AddChild(_tracersGroup); + + _coverMat = new StandardMaterial3D { AlbedoColor = CoverRust, Roughness = 0.88f, Metallic = 0.25f }; + _bermMat = new StandardMaterial3D { AlbedoColor = BermDark, Roughness = 0.94f, Metallic = 0.1f }; + _humanCrateMat = new StandardMaterial3D { AlbedoColor = OlivePaint, Roughness = 0.65f, Metallic = 0.3f }; + _imperialCrateMat = new StandardMaterial3D + { + AlbedoColor = TouristGold, + Roughness = 0.35f, + Metallic = 0.8f, + EmissionEnabled = true, + Emission = TouristGold, + EmissionEnergyMultiplier = 1.4f + }; + _cyanBeaconMat = new StandardMaterial3D + { + AlbedoColor = CyanSalvage, + EmissionEnabled = true, + Emission = CyanSalvage, + EmissionEnergyMultiplier = 1.5f, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha + }; + _cyanBeaconMat.AlbedoColor = new Color(CyanSalvage.R, CyanSalvage.G, CyanSalvage.B, 0.72f); + + _safeRingImm = new ImmediateMesh(); + _safeRingMat = new StandardMaterial3D + { + AlbedoColor = new Color(1.0f, 0.38f, 0.14f, 0.78f), + EmissionEnabled = true, + Emission = new Color(1.0f, 0.32f, 0.08f), + EmissionEnergyMultiplier = 1.6f, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha, + ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, + CullMode = BaseMaterial3D.CullModeEnum.Disabled + }; + _safeRingMesh = new MeshInstance3D + { + Name = "SafeRing", + Mesh = _safeRingImm, + MaterialOverride = _safeRingMat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + AddChild(_safeRingMesh); + } + + public void Sync(ArenaSession session, float elapsedSeconds) + { + var state = session.State; + if (!ReferenceEquals(_builtForState, state)) + { + RebuildStaticArena(state); + ClearDynamicVisuals(); + _builtForState = state; + } + + UpdateSafeCircleRing(state.Terrain, state.Spectators.SafeRadius); + SyncContenders(session); + SyncSpectators(session, elapsedSeconds); + SyncGroundDrops(state, elapsedSeconds); + SyncTracers(state.Tracers); + } + + private void RebuildStaticArena(MatchState state) + { + ClearChildren(_staticGroup); + + for (int i = 0; i < state.ArenaCoverBoxes.Count; i++) + { + var b = state.ArenaCoverBoxes[i]; + var mesh = new MeshInstance3D + { + Mesh = new BoxMesh { Size = new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f) }, + MaterialOverride = _coverMat, + Position = new Vector3(b.X, b.Y, b.Z) + }; + _staticGroup.AddChild(mesh); + } + + for (int i = 0; i < state.ArenaBoundaryBoxes.Count; i++) + { + var b = state.ArenaBoundaryBoxes[i]; + var mesh = new MeshInstance3D + { + Mesh = new BoxMesh { Size = new Vector3(b.HalfX * 2f, b.HalfY * 2f, b.HalfZ * 2f) }, + MaterialOverride = _bermMat, + Position = new Vector3(b.X, b.Y, b.Z) + }; + _staticGroup.AddChild(mesh); + } + } + + private void ClearDynamicVisuals() + { + ClearChildren(_actorsGroup); + ClearChildren(_dropsGroup); + _contenderVisuals.Clear(); + _spectatorVisuals.Clear(); + _dropVisuals.Clear(); + } + + private void UpdateSafeCircleRing(TerrainField terrain, float safeRadius) + { + _safeRingImm.ClearSurfaces(); + _safeRingImm.SurfaceBegin(Mesh.PrimitiveType.Triangles); + + const int segments = 96; + const float halfThick = 0.65f; + float rInner = MathF.Max(2f, safeRadius - halfThick); + float rOuter = safeRadius + halfThick; + + for (int i = 0; i < segments; i++) + { + float a0 = (i / (float)segments) * MathF.Tau; + float a1 = ((i + 1) / (float)segments) * MathF.Tau; + float c0 = MathF.Cos(a0), s0 = MathF.Sin(a0); + float c1 = MathF.Cos(a1), s1 = MathF.Sin(a1); + + float x0i = c0 * rInner, z0i = s0 * rInner; + float x0o = c0 * rOuter, z0o = s0 * rOuter; + float x1i = c1 * rInner, z1i = s1 * rInner; + float x1o = c1 * rOuter, z1o = s1 * rOuter; + + float y0 = terrain.SampleHeight(c0 * safeRadius, s0 * safeRadius) + 0.42f; + float y1 = terrain.SampleHeight(c1 * safeRadius, s1 * safeRadius) + 0.42f; + + var p0i = new Vector3(x0i, y0, z0i); + var p0o = new Vector3(x0o, y0, z0o); + var p1i = new Vector3(x1i, y1, z1i); + var p1o = new Vector3(x1o, y1, z1o); + + _safeRingImm.SurfaceAddVertex(p0i); + _safeRingImm.SurfaceAddVertex(p0o); + _safeRingImm.SurfaceAddVertex(p1o); + + _safeRingImm.SurfaceAddVertex(p0i); + _safeRingImm.SurfaceAddVertex(p1o); + _safeRingImm.SurfaceAddVertex(p1i); + } + + _safeRingImm.SurfaceEnd(); + } + + private void SyncContenders(ArenaSession session) + { + var view = session.World.View; + var contenders = session.State.Contenders; + + for (int i = 0; i < contenders.Count; i++) + { + var c = contenders[i]; + if (!c.Alive) + { + if (_contenderVisuals.TryGetValue(c.Id, out var deadVis)) + { + deadVis.Root.Visible = false; + } + continue; + } + + if (!_contenderVisuals.TryGetValue(c.Id, out var vis) || vis.ChassisId != c.Grid.Spec.Id) + { + if (vis is not null) + { + vis.Root.QueueFree(); + } + vis = BuildChassisVisual( + c.Grid.Spec.Id, + primary: c.IsPlayer ? OlivePaint : RivalSteel, + accent: c.IsPlayer ? SignalOrange : RivalAccent, + isSpectator: false, + tier: SpectatorTier.Patron); + _actorsGroup.AddChild(vis.Root); + _contenderVisuals[c.Id] = vis; + } + + vis.Root.Visible = true; + var body = session.GetContenderBody(c.Id); + if (body is { } h) + { + int lane = h.Lane; + var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + vis.Root.Transform = new Transform3D(new Basis(q), pos); + } + else + { + vis.Root.Position = new Vector3(c.X, c.Y, c.Z); + vis.Root.Rotation = new Vector3(0f, c.Yaw, 0f); + } + + if (vis.AimPivot is not null) + { + float aimYawWorld = MathF.Atan2(c.AimX - c.X, c.AimZ - c.Z); + float relYaw = MatchRules.NormalizeAngle(aimYawWorld - c.Yaw); + vis.AimPivot.Rotation = new Vector3(0f, relYaw, 0f); + } + + UpdateHeatGlow(vis.HeatMat, c.Grid); + } + } + + private void SyncSpectators(ArenaSession session, float elapsedSeconds) + { + var view = session.World.View; + var specs = session.State.Spectators.Spectators; + + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive) + { + if (_spectatorVisuals.TryGetValue(s.Id, out var deadVis)) + { + deadVis.Root.Visible = false; + } + continue; + } + + if (!_spectatorVisuals.TryGetValue(s.Id, out var vis)) + { + var (primary, accent) = s.Tier switch + { + SpectatorTier.Tourist => (TouristGold, TouristIvory), + SpectatorTier.Patron => (PatronTeal, PatronBronze), + _ => (ExemplarObsidian, ExemplarCrimson) + }; + vis = BuildChassisVisual(s.Grid.Spec.Id, primary, accent, isSpectator: true, tier: s.Tier); + _actorsGroup.AddChild(vis.Root); + _spectatorVisuals[s.Id] = vis; + } + + vis.Root.Visible = true; + var body = session.GetSpectatorBody(s.Id); + Vector3 specPos; + if (body is { } h) + { + int lane = h.Lane; + specPos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); + var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); + vis.Root.Transform = new Transform3D(new Basis(q), specPos); + } + else + { + specPos = new Vector3(s.X, s.Y, s.Z); + vis.Root.Position = specPos; + vis.Root.Rotation = new Vector3(0f, s.Yaw, 0f); + } + + // Status halo + if (vis.HaloMat is not null && vis.HaloMesh is not null) + { + if (s.Stance == SpectatorStance.Neutral) + { + vis.HaloMat.AlbedoColor = new Color(0.88f, 0.65f, 0.25f, 0.45f); + vis.HaloMat.Emission = new Color(0.88f, 0.65f, 0.25f); + vis.HaloMat.EmissionEnergyMultiplier = 0.6f; + } + else if (s.Stance == SpectatorStance.Cleared) + { + vis.HaloMat.AlbedoColor = new Color(1.0f, 0.22f, 0.18f, 0.9f); + vis.HaloMat.Emission = new Color(1.0f, 0.2f, 0.15f); + vis.HaloMat.EmissionEnergyMultiplier = 2.0f; + } + else + { + float pulse = 1.6f + 1.2f * MathF.Sin(elapsedSeconds * 10f); + vis.HaloMat.AlbedoColor = new Color(1.0f, 0.1f, 0.1f, 0.95f); + vis.HaloMat.Emission = new Color(1.0f, 0.08f, 0.08f); + vis.HaloMat.EmissionEnergyMultiplier = pulse; + } + } + + // Lock-on laser beam when Cleared or Provoked + if (vis.LaserMesh is not null) + { + ContenderState? target = s.TargetContenderId.HasValue && + s.TargetContenderId.Value >= 0 && + s.TargetContenderId.Value < session.State.Contenders.Count + ? session.State.Contenders[s.TargetContenderId.Value] + : null; + + if (s.Stance != SpectatorStance.Neutral && target is { Alive: true }) + { + Vector3 start = specPos + new Vector3(0f, s.Grid.Spec.HalfHeight * 0.7f, 0f); + Vector3 end = new Vector3(target.X, target.Y + target.Grid.Spec.HalfHeight * 0.3f, target.Z); + float dist = start.DistanceTo(end); + if (dist > 0.5f) + { + vis.LaserMesh.Visible = true; + vis.LaserMesh.GlobalPosition = (start + end) * 0.5f; + vis.LaserMesh.LookAt(end, Vector3.Up); + vis.LaserMesh.Scale = new Vector3(1f, 1f, dist); + } + else + { + vis.LaserMesh.Visible = false; + } + } + else + { + vis.LaserMesh.Visible = false; + } + } + + UpdateHeatGlow(vis.HeatMat, s.Grid); + } + } + + private void SyncGroundDrops(MatchState state, float elapsedSeconds) + { + for (int i = 0; i < state.GroundDrops.Count; i++) + { + var d = state.GroundDrops[i]; + if (d.PickedUp) + { + if (_dropVisuals.TryGetValue(d.Id, out var pickedNode)) + { + pickedNode.Visible = false; + } + continue; + } + + if (!_dropVisuals.TryGetValue(d.Id, out var node)) + { + node = BuildGroundDropVisual(d, state.Terrain); + _dropsGroup.AddChild(node); + _dropVisuals[d.Id] = node; + } + + node.Visible = true; + float bob = d.Module is not null ? MathF.Sin(elapsedSeconds * 2.5f + d.Id) * 0.12f : 0f; + float baseY = state.Terrain.SampleHeight(d.X, d.Z); + node.Position = new Vector3(d.X, baseY + bob, d.Z); + if (d.Module is not null) + { + node.Rotation = new Vector3(0f, elapsedSeconds * 0.9f + d.Id, 0f); + } + } + } + + private void SyncTracers(IReadOnlyList tracers) + { + while (_tracerPool.Count < tracers.Count) + { + var mat = new StandardMaterial3D + { + ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, + EmissionEnabled = true + }; + var mesh = new MeshInstance3D + { + Mesh = new BoxMesh { Size = new Vector3(0.14f, 0.14f, 1.0f) }, + MaterialOverride = mat, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + _tracersGroup.AddChild(mesh); + _tracerPool.Add(mesh); + } + + for (int i = 0; i < _tracerPool.Count; i++) + { + var m = _tracerPool[i]; + if (i >= tracers.Count) + { + m.Visible = false; + continue; + } + + var t = tracers[i]; + var start = new Vector3(t.StartX, t.StartY, t.StartZ); + var end = new Vector3(t.EndX, t.EndY, t.EndZ); + float dist = start.DistanceTo(end); + if (dist < 0.1f) + { + m.Visible = false; + continue; + } + + m.Visible = true; + m.Position = (start + end) * 0.5f; + Vector3 dir = (end - start).Normalized(); + Vector3 up = MathF.Abs(dir.Dot(Vector3.Up)) > 0.95f ? Vector3.Right : Vector3.Up; + m.LookAt(end, up); + m.Scale = new Vector3(1f, 1f, dist); + + var col = new Color( + ((t.ColorRgba >> 24) & 0xFF) / 255f, + ((t.ColorRgba >> 16) & 0xFF) / 255f, + ((t.ColorRgba >> 8) & 0xFF) / 255f, + 1f); + if (m.MaterialOverride is StandardMaterial3D sm) + { + sm.AlbedoColor = col; + sm.Emission = col; + sm.EmissionEnergyMultiplier = 2.5f; + } + } + } + + private Node3D BuildGroundDropVisual(GroundDrop drop, TerrainField terrain) + { + var root = new Node3D { Name = $"Drop_{drop.Id}" }; + if (drop.Module is { } mod) + { + var mat = mod.IsImperial ? _imperialCrateMat : _humanCrateMat; + root.AddChild(new MeshInstance3D + { + Mesh = new BoxMesh { Size = new Vector3(1.1f, 0.8f, 1.1f) }, + MaterialOverride = mat, + Position = new Vector3(0f, 0.5f, 0f) + }); + if (mod.IsImperial) + { + root.AddChild(new MeshInstance3D + { + Mesh = new CylinderMesh { TopRadius = 0.08f, BottomRadius = 0.25f, Height = 5.5f, RadialSegments = 8 }, + MaterialOverride = _imperialCrateMat, + Position = new Vector3(0f, 3.0f, 0f) + }); + } + } + else if (drop.Chassis is { } ch) + { + var hull = BuildChassisVisual(ch.Id, new Color(0.32f, 0.35f, 0.36f), CyanSalvage, isSpectator: false, tier: SpectatorTier.Patron); + hull.Root.Position = new Vector3(0f, ch.HalfHeight * 0.85f, 0f); + hull.Root.Scale = new Vector3(0.85f, 0.85f, 0.85f); + root.AddChild(hull.Root); + + var ring = new MeshInstance3D + { + Mesh = new CylinderMesh { TopRadius = 2.6f, BottomRadius = 2.8f, Height = 0.14f, RadialSegments = 18 }, + MaterialOverride = _cyanBeaconMat, + Position = new Vector3(0f, 0.15f, 0f) + }; + root.AddChild(ring); + } + return root; + } + + private ActorVisual BuildChassisVisual( + string chassisId, + Color primary, + Color accent, + bool isSpectator, + SpectatorTier tier) + { + var root = new Node3D { Name = $"Chassis_{chassisId}" }; + var bodyMat = new StandardMaterial3D { AlbedoColor = primary, Roughness = 0.55f, Metallic = 0.45f }; + var accentMat = new StandardMaterial3D { AlbedoColor = accent, Roughness = 0.45f, Metallic = 0.55f }; + var darkMat = new StandardMaterial3D { AlbedoColor = new Color(0.14f, 0.15f, 0.14f), Roughness = 0.8f, Metallic = 0.35f }; + var heatMat = new StandardMaterial3D + { + AlbedoColor = accent, + Roughness = 0.4f, + Metallic = 0.6f, + EmissionEnabled = true, + Emission = new Color(1.0f, 0.35f, 0.1f), + EmissionEnergyMultiplier = 0.0f + }; + + var aimPivot = new Node3D { Name = "AimPivot" }; + root.AddChild(aimPivot); + + switch (chassisId) + { + case "buggy": + BuildBuggyParts(root, aimPivot, bodyMat, accentMat, darkMat, heatMat); + break; + case "technical": + BuildTechnicalParts(root, aimPivot, bodyMat, accentMat, darkMat, heatMat); + break; + case "tank": + BuildTankParts(root, aimPivot, bodyMat, accentMat, darkMat, heatMat); + break; + case "manticore": + BuildManticoreParts(root, aimPivot, bodyMat, accentMat, darkMat, heatMat); + break; + case "raptor": + case "exemplar_frame": + BuildRaptorParts(root, aimPivot, bodyMat, accentMat, darkMat, heatMat, isExemplar: chassisId == "exemplar_frame"); + break; + case "paladin": + BuildPaladinParts(root, aimPivot, bodyMat, accentMat, darkMat, heatMat, isTourist: isSpectator && tier == SpectatorTier.Tourist); + break; + default: + BuildBuggyParts(root, aimPivot, bodyMat, accentMat, darkMat, heatMat); + break; + } + + var vis = new ActorVisual + { + Root = root, + AimPivot = aimPivot, + HeatMat = heatMat, + ChassisId = chassisId + }; + + if (isSpectator) + { + var haloMat = new StandardMaterial3D + { + ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, + EmissionEnabled = true, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha + }; + var halo = new MeshInstance3D + { + Mesh = new CylinderMesh { TopRadius = 2.4f, BottomRadius = 2.4f, Height = 0.1f, RadialSegments = 16 }, + MaterialOverride = haloMat, + Position = new Vector3(0f, 3.3f, 0f), + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + root.AddChild(halo); + vis.HaloMesh = halo; + vis.HaloMat = haloMat; + + var laserMat = new StandardMaterial3D + { + AlbedoColor = new Color(1f, 0.15f, 0.15f, 0.85f), + EmissionEnabled = true, + Emission = new Color(1f, 0.12f, 0.1f), + EmissionEnergyMultiplier = 2.2f, + ShadingMode = BaseMaterial3D.ShadingModeEnum.Unshaded, + Transparency = BaseMaterial3D.TransparencyEnum.Alpha + }; + var laser = new MeshInstance3D + { + Mesh = new BoxMesh { Size = new Vector3(0.08f, 0.08f, 1.0f) }, + MaterialOverride = laserMat, + Visible = false, + CastShadow = GeometryInstance3D.ShadowCastingSetting.Off + }; + _actorsGroup.AddChild(laser); + vis.LaserMesh = laser; + vis.LaserMat = laserMat; + } + + return vis; + } + + private static void BuildBuggyParts(Node3D root, Node3D aimPivot, Material bodyMat, Material accentMat, Material darkMat, Material heatMat) + { + AddBox(root, new Vector3(1.5f, 0.45f, 2.9f), new Vector3(0f, -0.25f, 0f), bodyMat); + AddBox(root, new Vector3(1.1f, 0.45f, 1.3f), new Vector3(0f, 0.25f, -0.2f), accentMat); // rollcage canopy + AddBox(root, new Vector3(0.8f, 0.32f, 0.5f), new Vector3(0f, 0.15f, -1.35f), heatMat); // rear radiator + // 4 wheels + AddWheel(root, new Vector3(-0.98f, -0.45f, 1.05f), 0.36f, 0.32f, darkMat); + AddWheel(root, new Vector3( 0.98f, -0.45f, 1.05f), 0.36f, 0.32f, darkMat); + AddWheel(root, new Vector3(-0.98f, -0.45f, -1.05f), 0.36f, 0.32f, darkMat); + AddWheel(root, new Vector3( 0.98f, -0.45f, -1.05f), 0.36f, 0.32f, darkMat); + // Roof MG turret + aimPivot.Position = new Vector3(0f, 0.6f, 0f); + AddBox(aimPivot, new Vector3(0.45f, 0.26f, 0.55f), Vector3.Zero, darkMat); + AddBox(aimPivot, new Vector3(0.12f, 0.12f, 1.25f), new Vector3(0f, 0.04f, 0.65f), accentMat); + } + + private static void BuildTechnicalParts(Node3D root, Node3D aimPivot, Material bodyMat, Material accentMat, Material darkMat, Material heatMat) + { + AddBox(root, new Vector3(2.0f, 0.55f, 4.2f), new Vector3(0f, -0.25f, 0f), bodyMat); + AddBox(root, new Vector3(1.85f, 0.72f, 1.5f), new Vector3(0f, 0.35f, 0.85f), accentMat); // armored cab + AddBox(root, new Vector3(1.9f, 0.38f, 2.0f), new Vector3(0f, 0.20f, -0.95f), bodyMat); // bed walls + AddBox(root, new Vector3(1.2f, 0.30f, 0.4f), new Vector3(0f, 0.20f, -2.0f), heatMat); // tail radiator + AddWheel(root, new Vector3(-1.12f, -0.55f, 1.45f), 0.44f, 0.36f, darkMat); + AddWheel(root, new Vector3( 1.12f, -0.55f, 1.45f), 0.44f, 0.36f, darkMat); + AddWheel(root, new Vector3(-1.12f, -0.55f, -1.45f), 0.44f, 0.36f, darkMat); + AddWheel(root, new Vector3( 1.12f, -0.55f, -1.45f), 0.44f, 0.36f, darkMat); + aimPivot.Position = new Vector3(0f, 0.72f, -0.8f); + AddBox(aimPivot, new Vector3(0.65f, 0.4f, 0.7f), Vector3.Zero, darkMat); + AddBox(aimPivot, new Vector3(0.14f, 0.14f, 1.7f), new Vector3(-0.18f, 0.08f, 0.8f), accentMat); + AddBox(aimPivot, new Vector3(0.14f, 0.14f, 1.7f), new Vector3( 0.18f, 0.08f, 0.8f), accentMat); + } + + private static void BuildTankParts(Node3D root, Node3D aimPivot, Material bodyMat, Material accentMat, Material darkMat, Material heatMat) + { + AddBox(root, new Vector3(2.4f, 0.85f, 4.6f), new Vector3(0f, -0.2f, 0f), bodyMat); + AddBox(root, new Vector3(0.55f, 0.72f, 4.9f), new Vector3(-1.32f, -0.45f, 0f), darkMat); // left track pod + AddBox(root, new Vector3(0.55f, 0.72f, 4.9f), new Vector3( 1.32f, -0.45f, 0f), darkMat); // right track pod + AddBox(root, new Vector3(1.6f, 0.35f, 0.7f), new Vector3(0f, 0.25f, -1.7f), heatMat); // rear engine deck + aimPivot.Position = new Vector3(0f, 0.65f, 0.2f); + AddBox(aimPivot, new Vector3(1.75f, 0.68f, 2.2f), Vector3.Zero, accentMat); + AddBox(aimPivot, new Vector3(0.24f, 0.24f, 3.0f), new Vector3(0f, 0.05f, 2.0f), darkMat); // main cannon + } + + private static void BuildManticoreParts(Node3D root, Node3D aimPivot, Material bodyMat, Material accentMat, Material darkMat, Material heatMat) + { + // Wide dorsal carapace + 4 splayed articulated legs + radiator flanks + AddBox(root, new Vector3(2.2f, 0.75f, 2.8f), new Vector3(0f, 0.25f, 0f), bodyMat); + AddBox(root, new Vector3(1.3f, 0.55f, 1.2f), new Vector3(0f, 0.45f, 1.2f), accentMat); // chin armor + AddBox(root, new Vector3(0.45f, 0.45f, 1.4f), new Vector3(-1.25f, 0.45f, -0.4f), heatMat); + AddBox(root, new Vector3(0.45f, 0.45f, 1.4f), new Vector3( 1.25f, 0.45f, -0.4f), heatMat); + + Vector3[] legAnchors = + { + new(-1.35f, -0.35f, 1.25f), + new( 1.35f, -0.35f, 1.25f), + new(-1.35f, -0.35f, -1.25f), + new( 1.35f, -0.35f, -1.25f) + }; + for (int i = 0; i < legAnchors.Length; i++) + { + AddBox(root, new Vector3(0.42f, 1.35f, 0.42f), legAnchors[i], darkMat); + AddBox(root, new Vector3(0.68f, 0.26f, 0.68f), legAnchors[i] + new Vector3(0f, -0.7f, 0f), accentMat); + } + + aimPivot.Position = new Vector3(0f, 0.8f, 0.2f); + AddBox(aimPivot, new Vector3(0.9f, 0.38f, 1.0f), Vector3.Zero, darkMat); + AddBox(aimPivot, new Vector3(0.18f, 0.18f, 1.7f), new Vector3(-0.6f, 0f, 0.75f), accentMat); + AddBox(aimPivot, new Vector3(0.18f, 0.18f, 1.7f), new Vector3( 0.6f, 0f, 0.75f), accentMat); + } + + private static void BuildRaptorParts(Node3D root, Node3D aimPivot, Material bodyMat, Material accentMat, Material darkMat, Material heatMat, bool isExemplar) + { + float scale = isExemplar ? 0.78f : 1.0f; + // Tall bipedal legs + AddBox(root, new Vector3(0.42f * scale, 1.85f * scale, 0.52f * scale), new Vector3(-0.62f * scale, -0.8f * scale, 0f), darkMat); + AddBox(root, new Vector3(0.42f * scale, 1.85f * scale, 0.52f * scale), new Vector3( 0.62f * scale, -0.8f * scale, 0f), darkMat); + // Angled torso + head sensor + AddBox(root, new Vector3(1.55f * scale, 1.15f * scale, 1.25f * scale), new Vector3(0f, 0.45f * scale, 0f), bodyMat); + AddBox(root, new Vector3(0.65f * scale, 0.45f * scale, 0.85f * scale), new Vector3(0f, 1.25f * scale, 0.25f * scale), accentMat); + AddBox(root, new Vector3(0.95f * scale, 0.55f * scale, 0.35f * scale), new Vector3(0f, 0.6f * scale, -0.75f * scale), heatMat); + + aimPivot.Position = new Vector3(0f, 0.5f * scale, 0f); + AddBox(aimPivot, new Vector3(0.32f * scale, 0.35f * scale, 1.55f * scale), new Vector3(-1.05f * scale, 0f, 0.55f * scale), accentMat); + AddBox(aimPivot, new Vector3(0.32f * scale, 0.35f * scale, 1.55f * scale), new Vector3( 1.05f * scale, 0f, 0.55f * scale), accentMat); + } + + private static void BuildPaladinParts(Node3D root, Node3D aimPivot, Material bodyMat, Material accentMat, Material darkMat, Material heatMat, bool isTourist) + { + // Broad heavy bipedal silhouette + shoulder pods + chest reactor + AddBox(root, new Vector3(0.68f, 2.0f, 0.82f), new Vector3(-0.85f, -1.1f, 0f), darkMat); + AddBox(root, new Vector3(0.68f, 2.0f, 0.82f), new Vector3( 0.85f, -1.1f, 0f), darkMat); + AddBox(root, new Vector3(2.25f, 1.65f, 1.65f), new Vector3(0f, 0.45f, 0f), bodyMat); + AddBox(root, new Vector3(0.85f, 0.75f, 0.35f), new Vector3(0f, 0.55f, 0.85f), heatMat); // chest reactor + // Twin shoulder pods + AddBox(root, new Vector3(0.75f, 0.72f, 1.15f), new Vector3(-1.35f, 1.45f, 0f), accentMat); + AddBox(root, new Vector3(0.75f, 0.72f, 1.15f), new Vector3( 1.35f, 1.45f, 0f), accentMat); + + if (isTourist) + { + // Gaudy gilded luxury dome on top so Tourists are unmistakable loot pinatas + var dome = new MeshInstance3D + { + Mesh = new CylinderMesh { TopRadius = 0.5f, BottomRadius = 0.95f, Height = 0.75f, RadialSegments = 12 }, + MaterialOverride = bodyMat, + Position = new Vector3(0f, 1.65f, 0f) + }; + root.AddChild(dome); + } + + aimPivot.Position = new Vector3(0f, 0.45f, 0f); + AddBox(aimPivot, new Vector3(0.45f, 0.48f, 2.0f), new Vector3(-1.45f, 0f, 0.65f), accentMat); + AddBox(aimPivot, new Vector3(0.45f, 0.48f, 2.0f), new Vector3( 1.45f, 0f, 0.65f), accentMat); + } + + private static void AddBox(Node3D parent, Vector3 size, Vector3 pos, Material mat) + { + parent.AddChild(new MeshInstance3D + { + Mesh = new BoxMesh { Size = size }, + MaterialOverride = mat, + Position = pos + }); + } + + private static void AddWheel(Node3D parent, Vector3 pos, float radius, float width, Material mat) + { + parent.AddChild(new MeshInstance3D + { + Mesh = new CylinderMesh { TopRadius = radius, BottomRadius = radius, Height = width, RadialSegments = 12 }, + MaterialOverride = mat, + Position = pos, + Rotation = new Vector3(0f, 0f, MathF.PI * 0.5f) + }); + } + + private static void UpdateHeatGlow(StandardMaterial3D heatMat, ChassisGrid grid) + { + float maxTemp = ChassisGrid.AmbientTemp; + for (int i = 0; i < grid.Mounted.Count; i++) + { + maxTemp = MathF.Max(maxTemp, grid.Mounted[i].CurrentTemp); + } + float glow = Math.Clamp((maxTemp - 65f) / 110f, 0f, 1f); + heatMat.EmissionEnergyMultiplier = glow * 2.6f; + } + + private static void ClearChildren(Node parent) + { + for (int i = parent.GetChildCount() - 1; i >= 0; i--) + { + var child = parent.GetChild(i); + parent.RemoveChild(child); + child.QueueFree(); + } + } +} diff --git a/client/Hud.cs b/client/Hud.cs new file mode 100644 index 0000000..5e0ce22 --- /dev/null +++ b/client/Hud.cs @@ -0,0 +1,761 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; +using RustToDust.Ymir; + +namespace RustToDust.Client; + +/// +/// Rust to Dust industrial HUD: +/// - Top-Left: Chassis badge (DORSAL/CORONAL), Core HP, Speed, Contenders Alive, Safe Circle status, Pickup prompt. +/// - Top-Right: Tactical Radar (Safe Circle, RadarSignature-scaled Spectator Wall, lock lines, contenders, salvage). +/// - Bottom-Left: Live clickable Aetheria Hardpoint & Heat Schematic + Cargo Salvage Rack (Tab expands Garage details). +/// - Bottom-Center: Imperial Broadcast Chyron (Weksa commentary). +/// +public partial class Hud : CanvasLayer +{ + private static readonly Color BgDark = Color.FromHtml("#131613"); + private static readonly Color BgInner = Color.FromHtml("#1b1f1b"); + private static readonly Color BorderCol = Color.FromHtml("#3e4638"); + private static readonly Color OliveCol = Color.FromHtml("#9bb06a"); + private static readonly Color OrangeCol = Color.FromHtml("#e08a4a"); + private static readonly Color TextLight = Color.FromHtml("#e4dfd2"); + private static readonly Color TextMuted = Color.FromHtml("#989487"); + private static readonly Color CyanCol = Color.FromHtml("#44d9e8"); + private static readonly Color GoldCol = Color.FromHtml("#e6b838"); + private static readonly Color RedCol = Color.FromHtml("#d93829"); + + private readonly Func _getSession; + private readonly Action _onEquipCargo; + + private Label _chassisHeader = null!; + private Label _planeBadge = null!; + private ProgressBar _coreHpBar = null!; + private Label _coreHpLabel = null!; + private Label _statsLabel = null!; + private Label _safeLabel = null!; + private Label _promptLabel = null!; + private Label _controlsHint = null!; + + private RadarWidget _radar = null!; + private SchematicPanel _schematic = null!; + private VBoxContainer _cargoList = null!; + private Label _cargoHeader = null!; + private Label _garageDetails = null!; + private PanelContainer _bottomLeftPanel = null!; + + private VBoxContainer _chyronBox = null!; + private PanelContainer _outcomeBanner = null!; + private Label _outcomeLabel = null!; + + private int _selectedCargoIndex = -1; + private int _lastCargoHash = -1; + private bool _garageExpanded; + + public Hud(Func getSession, Action onEquipCargo) + { + _getSession = getSession; + _onEquipCargo = onEquipCargo; + Layer = 10; + } + + public bool GarageExpanded => _garageExpanded; + + public void ToggleGarage() + { + _garageExpanded = !_garageExpanded; + _garageDetails.Visible = _garageExpanded; + _schematic.CustomMinimumSize = _garageExpanded ? new Vector2(236f, 250f) : new Vector2(180f, 190f); + _schematic.QueueRedraw(); + } + + public override void _Ready() + { + BuildTopLeft(); + BuildTopRightRadar(); + BuildBottomLeftSchematic(); + BuildBottomCenterChyron(); + BuildOutcomeBanner(); + } + + public bool IsPointerOverInteractiveHud(Vector2 screenPos) + { + return _bottomLeftPanel.GetGlobalRect().HasPoint(screenPos); + } + + public void Sync(ArenaSession session) + { + var state = session.State; + var player = state.Player; + + // Top-Left Status + _chassisHeader.Text = player.Grid.Spec.Name.ToUpperInvariant(); + bool isCoronal = player.Grid.Spec.Plane == GridPlane.Coronal; + _planeBadge.Text = isCoronal ? "CORONAL" : "DORSAL"; + _planeBadge.Modulate = isCoronal ? CyanCol : OliveCol; + + _coreHpBar.MaxValue = Math.Max(1f, player.Grid.MaxCoreHp); + _coreHpBar.Value = Math.Max(0f, player.Grid.CoreHp); + _coreHpLabel.Text = $"CORE {player.Grid.CoreHp:F0} / {player.Grid.MaxCoreHp:F0}"; + + int aliveCount = 0; + for (int i = 0; i < state.Contenders.Count; i++) + { + if (state.Contenders[i].Alive) aliveCount++; + } + _statsLabel.Text = $"SPD {player.Speed:F1} m/s | ALIVE {aliveCount} / {state.Contenders.Count} | KILLS {player.Kills}"; + + float distCenter = MathF.Sqrt(player.X * player.X + player.Z * player.Z); + float outside = distCenter - state.Spectators.SafeRadius; + int cleared = state.Spectators.CountClearedFor(player.Id); + int provoked = state.Spectators.CountProvokedFor(player.Id); + + if (outside <= 0f) + { + _safeLabel.Text = $"RING SAFE ({-outside:F0}m margin)" + (provoked > 0 ? $" • {provoked} PROVOKED!" : ""); + _safeLabel.Modulate = provoked > 0 ? OrangeCol : OliveCol; + } + else + { + _safeLabel.Text = $"OUTSIDE +{outside:F0}m — {cleared} CLEARED" + (provoked > 0 ? $" / {provoked} PROVOKED!" : "!"); + _safeLabel.Modulate = RedCol; + } + + _promptLabel.Text = BuildInteractionPrompt(state, player); + _promptLabel.Visible = !string.IsNullOrEmpty(_promptLabel.Text); + + // Radar + _radar.SetState(state); + _radar.QueueRedraw(); + + // Schematic + Cargo + _schematic.SetGrid(player.Grid, _selectedCargoIndex); + _schematic.QueueRedraw(); + SyncCargoButtons(player.Grid); + + if (_garageExpanded) + { + _garageDetails.Text = BuildGarageDetails(player.Grid); + } + + // Broadcast Chyron + SyncBroadcastChyron(state.Broadcast.Lines); + + // Outcome + if (state.Phase == MatchPhase.Victory) + { + _outcomeBanner.Visible = true; + _outcomeLabel.Text = "VICTORY — LAST RIG STANDING\n[R] New Drop"; + _outcomeLabel.Modulate = OliveCol; + } + else if (state.Phase == MatchPhase.Defeat) + { + _outcomeBanner.Visible = true; + _outcomeLabel.Text = "CHASSIS DESTROYED\n[R] Redeploy"; + _outcomeLabel.Modulate = RedCol; + } + else + { + _outcomeBanner.Visible = false; + } + } + + private void BuildTopLeft() + { + var panel = CreateStyledPanel(); + panel.AnchorLeft = 0f; + panel.AnchorTop = 0f; + panel.OffsetLeft = 14f; + panel.OffsetTop = 14f; + panel.CustomMinimumSize = new Vector2(360f, 0f); + AddChild(panel); + + var vbox = new VBoxContainer { Theme = null }; + vbox.AddThemeConstantOverride("separation", 5); + panel.AddChild(vbox); + + var headRow = new HBoxContainer(); + headRow.AddThemeConstantOverride("separation", 10); + vbox.AddChild(headRow); + + _chassisHeader = new Label { Text = "DUNE BUGGY", SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; + _chassisHeader.AddThemeColorOverride("font_color", TextLight); + _chassisHeader.AddThemeFontSizeOverride("font_size", 17); + headRow.AddChild(_chassisHeader); + + _planeBadge = new Label { Text = "DORSAL" }; + _planeBadge.AddThemeFontSizeOverride("font_size", 13); + headRow.AddChild(_planeBadge); + + var hpRow = new HBoxContainer(); + hpRow.AddThemeConstantOverride("separation", 8); + vbox.AddChild(hpRow); + + _coreHpBar = new ProgressBar + { + ShowPercentage = false, + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, + CustomMinimumSize = new Vector2(180f, 16f) + }; + var barBg = new StyleBoxFlat { BgColor = BgInner, BorderColor = BorderCol }; + barBg.SetBorderWidthAll(1); + var barFill = new StyleBoxFlat { BgColor = OliveCol }; + _coreHpBar.AddThemeStyleboxOverride("background", barBg); + _coreHpBar.AddThemeStyleboxOverride("fill", barFill); + hpRow.AddChild(_coreHpBar); + + _coreHpLabel = new Label { Text = "CORE 100 / 100" }; + _coreHpLabel.AddThemeColorOverride("font_color", TextLight); + _coreHpLabel.AddThemeFontSizeOverride("font_size", 13); + hpRow.AddChild(_coreHpLabel); + + _statsLabel = new Label { Text = "SPD 0.0 m/s" }; + _statsLabel.AddThemeColorOverride("font_color", TextMuted); + _statsLabel.AddThemeFontSizeOverride("font_size", 13); + vbox.AddChild(_statsLabel); + + _safeLabel = new Label { Text = "RING SAFE" }; + _safeLabel.AddThemeFontSizeOverride("font_size", 13); + vbox.AddChild(_safeLabel); + + _promptLabel = new Label { Text = "", Visible = false }; + _promptLabel.AddThemeColorOverride("font_color", CyanCol); + _promptLabel.AddThemeFontSizeOverride("font_size", 14); + vbox.AddChild(_promptLabel); + + _controlsHint = new Label { Text = "WASD Drive | LMB Fire | E Loot/Swap | Tab Garage | R Reset" }; + _controlsHint.AddThemeColorOverride("font_color", TextMuted); + _controlsHint.AddThemeFontSizeOverride("font_size", 11); + vbox.AddChild(_controlsHint); + } + + private void BuildTopRightRadar() + { + var panel = CreateStyledPanel(); + panel.AnchorLeft = 1f; + panel.AnchorRight = 1f; + panel.AnchorTop = 0f; + panel.OffsetLeft = -246f; + panel.OffsetRight = -14f; + panel.OffsetTop = 14f; + AddChild(panel); + + var vbox = new VBoxContainer(); + vbox.AddThemeConstantOverride("separation", 4); + panel.AddChild(vbox); + + var title = new Label { Text = "GALLERY & ARENA RADAR", HorizontalAlignment = HorizontalAlignment.Center }; + title.AddThemeColorOverride("font_color", OrangeCol); + title.AddThemeFontSizeOverride("font_size", 12); + vbox.AddChild(title); + + _radar = new RadarWidget + { + CustomMinimumSize = new Vector2(214f, 214f) + }; + vbox.AddChild(_radar); + } + + private void BuildBottomLeftSchematic() + { + _bottomLeftPanel = CreateStyledPanel(); + _bottomLeftPanel.AnchorLeft = 0f; + _bottomLeftPanel.AnchorTop = 1f; + _bottomLeftPanel.AnchorBottom = 1f; + _bottomLeftPanel.OffsetLeft = 14f; + _bottomLeftPanel.OffsetTop = -248f; + _bottomLeftPanel.OffsetBottom = -14f; + AddChild(_bottomLeftPanel); + + var hbox = new HBoxContainer(); + hbox.AddThemeConstantOverride("separation", 10); + _bottomLeftPanel.AddChild(hbox); + + var leftCol = new VBoxContainer(); + leftCol.AddThemeConstantOverride("separation", 4); + hbox.AddChild(leftCol); + + var title = new Label { Text = "AETHERIA HEAT & HARDPOINTS" }; + title.AddThemeColorOverride("font_color", OrangeCol); + title.AddThemeFontSizeOverride("font_size", 12); + leftCol.AddChild(title); + + _schematic = new SchematicPanel(OnHardpointClicked) + { + CustomMinimumSize = new Vector2(180f, 190f) + }; + leftCol.AddChild(_schematic); + + var rightCol = new VBoxContainer { CustomMinimumSize = new Vector2(178f, 0f) }; + rightCol.AddThemeConstantOverride("separation", 4); + hbox.AddChild(rightCol); + + _cargoHeader = new Label { Text = "SALVAGE CARGO (0/4)" }; + _cargoHeader.AddThemeColorOverride("font_color", OliveCol); + _cargoHeader.AddThemeFontSizeOverride("font_size", 12); + rightCol.AddChild(_cargoHeader); + + _cargoList = new VBoxContainer(); + _cargoList.AddThemeConstantOverride("separation", 3); + rightCol.AddChild(_cargoList); + + _garageDetails = new Label { Visible = false, AutowrapMode = TextServer.AutowrapMode.Word }; + _garageDetails.AddThemeColorOverride("font_color", TextMuted); + _garageDetails.AddThemeFontSizeOverride("font_size", 11); + _garageDetails.CustomMinimumSize = new Vector2(200f, 0f); + hbox.AddChild(_garageDetails); + } + + private void BuildBottomCenterChyron() + { + var panel = CreateStyledPanel(); + panel.AnchorLeft = 0.5f; + panel.AnchorRight = 0.5f; + panel.AnchorTop = 1f; + panel.AnchorBottom = 1f; + panel.OffsetLeft = -150f; + panel.OffsetRight = 460f; + panel.OffsetTop = -104f; + panel.OffsetBottom = -14f; + AddChild(panel); + + var vbox = new VBoxContainer(); + vbox.AddThemeConstantOverride("separation", 3); + panel.AddChild(vbox); + + var header = new Label { Text = "IMPERIAL BROADCAST FEED" }; + header.AddThemeColorOverride("font_color", GoldCol); + header.AddThemeFontSizeOverride("font_size", 11); + vbox.AddChild(header); + + _chyronBox = new VBoxContainer(); + _chyronBox.AddThemeConstantOverride("separation", 2); + vbox.AddChild(_chyronBox); + } + + private void BuildOutcomeBanner() + { + _outcomeBanner = CreateStyledPanel(); + _outcomeBanner.AnchorLeft = 0.5f; + _outcomeBanner.AnchorRight = 0.5f; + _outcomeBanner.AnchorTop = 0.28f; + _outcomeBanner.AnchorBottom = 0.28f; + _outcomeBanner.OffsetLeft = -210f; + _outcomeBanner.OffsetRight = 210f; + _outcomeBanner.OffsetTop = -40f; + _outcomeBanner.OffsetBottom = 40f; + _outcomeBanner.Visible = false; + AddChild(_outcomeBanner); + + _outcomeLabel = new Label + { + HorizontalAlignment = HorizontalAlignment.Center, + VerticalAlignment = VerticalAlignment.Center + }; + _outcomeLabel.AddThemeFontSizeOverride("font_size", 22); + _outcomeBanner.AddChild(_outcomeLabel); + } + + private void OnHardpointClicked(string hardpointId) + { + var session = _getSession(); + if (session is null) return; + var cargo = session.State.Player.Grid.Cargo; + if (_selectedCargoIndex >= 0 && _selectedCargoIndex < cargo.Count) + { + _onEquipCargo(_selectedCargoIndex, hardpointId); + _selectedCargoIndex = -1; + _lastCargoHash = -1; + } + } + + private void SyncCargoButtons(ChassisGrid grid) + { + int hash = grid.Cargo.Count * 97 + (_selectedCargoIndex + 10); + for (int i = 0; i < grid.Cargo.Count; i++) + { + hash = HashCode.Combine(hash, grid.Cargo[i].Id); + } + if (hash == _lastCargoHash) return; + _lastCargoHash = hash; + + _cargoHeader.Text = $"SALVAGE CARGO ({grid.Cargo.Count}/{grid.Spec.CargoCapacity})"; + for (int i = _cargoList.GetChildCount() - 1; i >= 0; i--) + { + var c = _cargoList.GetChild(i); + _cargoList.RemoveChild(c); + c.QueueFree(); + } + + if (grid.Cargo.Count == 0) + { + var empty = new Label { Text = "No modules in rack.\nPress [E] near crates." }; + empty.AddThemeColorOverride("font_color", TextMuted); + empty.AddThemeFontSizeOverride("font_size", 11); + _cargoList.AddChild(empty); + return; + } + + for (int i = 0; i < grid.Cargo.Count; i++) + { + int idx = i; + var mod = grid.Cargo[i]; + var row = new HBoxContainer(); + row.AddThemeConstantOverride("separation", 4); + + var selectBtn = new Button + { + Text = $"{(mod.IsImperial ? "★ " : "")}{mod.Name}", + SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, + Alignment = HorizontalAlignment.Left + }; + selectBtn.AddThemeFontSizeOverride("font_size", 11); + if (_selectedCargoIndex == idx) + { + selectBtn.Modulate = OrangeCol; + } + else if (mod.IsImperial) + { + selectBtn.Modulate = GoldCol; + } + selectBtn.Pressed += () => + { + _selectedCargoIndex = (_selectedCargoIndex == idx) ? -1 : idx; + _lastCargoHash = -1; + }; + row.AddChild(selectBtn); + + var fitBtn = new Button { Text = "FIT" }; + fitBtn.AddThemeFontSizeOverride("font_size", 11); + fitBtn.Pressed += () => AutoFitCargo(grid, idx); + row.AddChild(fitBtn); + + _cargoList.AddChild(row); + } + } + + private void AutoFitCargo(ChassisGrid grid, int cargoIndex) + { + if (cargoIndex < 0 || cargoIndex >= grid.Cargo.Count) return; + var mod = grid.Cargo[cargoIndex]; + for (int i = 0; i < grid.Spec.Hardpoints.Length; i++) + { + var hp = grid.Spec.Hardpoints[i]; + if (ChassisGrid.CanFit(hp, mod)) + { + _onEquipCargo(cargoIndex, hp.Id); + _selectedCargoIndex = -1; + _lastCargoHash = -1; + return; + } + } + } + + private void SyncBroadcastChyron(IReadOnlyList lines) + { + for (int i = _chyronBox.GetChildCount() - 1; i >= 0; i--) + { + var c = _chyronBox.GetChild(i); + _chyronBox.RemoveChild(c); + c.QueueFree(); + } + + int start = Math.Max(0, lines.Count - 3); + for (int i = start; i < lines.Count; i++) + { + var line = lines[i]; + bool isLatest = i == lines.Count - 1; + var lbl = new Label + { + Text = $"[{line.Timestamp:00.0}s] {line.Text}", + AutowrapMode = TextServer.AutowrapMode.Word + }; + lbl.AddThemeFontSizeOverride("font_size", isLatest ? 12 : 11); + lbl.AddThemeColorOverride("font_color", isLatest ? TextLight : TextMuted); + _chyronBox.AddChild(lbl); + } + } + + private static string BuildInteractionPrompt(MatchState state, ContenderState player) + { + GroundDrop? nearest = null; + float bestD2 = MatchState.PickupRadius * MatchState.PickupRadius; + for (int i = 0; i < state.GroundDrops.Count; i++) + { + var d = state.GroundDrops[i]; + if (d.PickedUp) continue; + float dx = d.X - player.X; + float dz = d.Z - player.Z; + float d2 = dx * dx + dz * dz; + if (d2 <= bestD2) + { + bestD2 = d2; + nearest = d; + } + } + + if (nearest is null) return ""; + if (nearest.Module is { } mod) + { + return $"[E] Loot {(mod.IsImperial ? "IMPERIAL " : "")}{mod.Name}"; + } + if (nearest.Chassis is { } ch) + { + return $"[E] Swap to {ch.Name} ({ch.Plane})"; + } + return ""; + } + + private static string BuildGarageDetails(ChassisGrid grid) + { + var lines = new List + { + $"CONDUCTIVITY {grid.Spec.HullConductivity:F1} | THRUST {grid.ComputeDriveThrust():F0} N", + "MOUNTED:" + }; + for (int i = 0; i < grid.Mounted.Count; i++) + { + var m = grid.Mounted[i]; + lines.Add($"• {m.HardpointId}: {m.Spec.Name} ({m.CurrentTemp:F0}°C, {(m.CurrentPerformance * 100f):F0}%)"); + } + return string.Join("\n", lines); + } + + private static PanelContainer CreateStyledPanel() + { + var panel = new PanelContainer(); + var style = new StyleBoxFlat + { + BgColor = new Color(BgDark.R, BgDark.G, BgDark.B, 0.88f), + BorderColor = BorderCol, + ContentMarginLeft = 10, + ContentMarginRight = 10, + ContentMarginTop = 8, + ContentMarginBottom = 8 + }; + style.SetBorderWidthAll(2); + style.SetCornerRadiusAll(3); + panel.AddThemeStyleboxOverride("panel", style); + return panel; + } + + private sealed partial class RadarWidget : Control + { + private MatchState? _state; + + public void SetState(MatchState state) => _state = state; + + public override void _Draw() + { + Vector2 center = Size * 0.5f; + float radius = MathF.Min(Size.X, Size.Y) * 0.47f; + float scale = radius / MatchState.ArenaHalfExtent; + + DrawCircle(center, radius, BgInner); + DrawArc(center, radius, 0f, MathF.Tau, 48, BorderCol, 1.5f); + + if (_state is null) return; + + // Safe Circle + float safePx = _state.Spectators.SafeRadius * scale; + DrawArc(center, safePx, 0f, MathF.Tau, 56, OrangeCol, 1.6f); + + // Ground drops + for (int i = 0; i < _state.GroundDrops.Count; i++) + { + var d = _state.GroundDrops[i]; + if (d.PickedUp) continue; + var p = center + new Vector2(d.X, d.Z) * scale; + if (d.Chassis is not null) + { + DrawRect(new Rect2(p - new Vector2(2.5f, 2.5f), new Vector2(5f, 5f)), CyanCol); + } + else if (d.Module is { IsImperial: true }) + { + DrawCircle(p, 3.0f, GoldCol); + } + } + + // Spectator Wall (scaled by RadarSignature) + red target lock lines + var specs = _state.Spectators.Spectators; + for (int i = 0; i < specs.Count; i++) + { + var s = specs[i]; + if (!s.Alive) continue; + var p = center + new Vector2(s.X, s.Z) * scale; + float blipR = 1.6f + s.RadarSignature * 3.1f; + + Color col = s.Tier switch + { + SpectatorTier.Tourist => GoldCol, + SpectatorTier.Patron => PatronColor, + _ => RedCol + }; + + if (s.Stance != SpectatorStance.Neutral && s.TargetContenderId.HasValue) + { + int tid = s.TargetContenderId.Value; + if (tid >= 0 && tid < _state.Contenders.Count && _state.Contenders[tid].Alive) + { + var tgt = _state.Contenders[tid]; + var tp = center + new Vector2(tgt.X, tgt.Z) * scale; + DrawLine(p, tp, new Color(RedCol.R, RedCol.G, RedCol.B, 0.65f), 1.3f); + } + col = RedCol; + } + + DrawCircle(p, blipR, col); + } + + // Contenders + for (int i = 0; i < _state.Contenders.Count; i++) + { + var c = _state.Contenders[i]; + if (!c.Alive) continue; + var p = center + new Vector2(c.X, c.Z) * scale; + if (c.IsPlayer) + { + var dir = new Vector2(MathF.Sin(c.Yaw), MathF.Cos(c.Yaw)); + var perp = new Vector2(-dir.Y, dir.X); + var pts = new[] + { + p + dir * 6.5f, + p - dir * 4.5f + perp * 4.2f, + p - dir * 4.5f - perp * 4.2f + }; + DrawColoredPolygon(pts, OliveCol); + } + else + { + DrawCircle(p, 3.3f, OrangeCol); + } + } + } + + private static readonly Color PatronColor = Color.FromHtml("#4ba8a5"); + } + + private sealed partial class SchematicPanel : Control + { + private readonly Action _onHardpointClick; + private readonly List<(Rect2 Rect, string HardpointId)> _hitBoxes = new(); + private ChassisGrid? _grid; + private int _selectedCargoIndex = -1; + + public SchematicPanel(Action onHardpointClick) + { + _onHardpointClick = onHardpointClick; + } + + public void SetGrid(ChassisGrid grid, int selectedCargoIndex) + { + _grid = grid; + _selectedCargoIndex = selectedCargoIndex; + } + + public override void _GuiInput(InputEvent @event) + { + if (@event is InputEventMouseButton mb && mb.Pressed && mb.ButtonIndex == MouseButton.Left) + { + for (int i = 0; i < _hitBoxes.Count; i++) + { + if (_hitBoxes[i].Rect.HasPoint(mb.Position)) + { + _onHardpointClick(_hitBoxes[i].HardpointId); + AcceptEvent(); + return; + } + } + } + } + + public override void _Draw() + { + _hitBoxes.Clear(); + if (_grid is null) return; + + var spec = _grid.Spec; + float cellSize = MathF.Min((Size.X - 8f) / spec.Width, (Size.Y - 8f) / spec.Height); + float originX = (Size.X - spec.Width * cellSize) * 0.5f; + float originY = (Size.Y - spec.Height * cellSize) * 0.5f; + + for (int y = 0; y < spec.Height; y++) + { + for (int x = 0; x < spec.Width; x++) + { + if (!spec.IsActive(x, y)) continue; + var rect = new Rect2(originX + x * cellSize + 1.5f, originY + y * cellSize + 1.5f, cellSize - 3f, cellSize - 3f); + + float temp = _grid.Temperature[x, y]; + Color fill = TempToColor(temp); + DrawRect(rect, fill); + + // Armor bar at bottom of cell + float maxArm = MathF.Max(1f, _grid.MaxArmor[x, y]); + float armRatio = Math.Clamp(_grid.Armor[x, y] / maxArm, 0f, 1f); + var armRect = new Rect2(rect.Position.X + 2f, rect.End.Y - 5f, (rect.Size.X - 4f) * armRatio, 3f); + DrawRect(armRect, OliveCol); + + // Border radiator highlight + Color border = _grid.BorderCells[x, y] ? CyanCol : BorderCol; + DrawRect(rect, border, filled: false, width: _grid.BorderCells[x, y] ? 1.5f : 1.0f); + } + } + + // Hardpoints & mounted module temperature badges + ModuleSpec? selectedCargo = _selectedCargoIndex >= 0 && _selectedCargoIndex < _grid.Cargo.Count + ? _grid.Cargo[_selectedCargoIndex] + : null; + + for (int i = 0; i < spec.Hardpoints.Length; i++) + { + var hp = spec.Hardpoints[i]; + var rect = new Rect2( + originX + hp.X * cellSize + 2f, + originY + hp.Y * cellSize + 2f, + hp.Width * cellSize - 4f, + hp.Height * cellSize - 4f); + _hitBoxes.Add((rect, hp.Id)); + + bool compatible = selectedCargo is not null && ChassisGrid.CanFit(hp, selectedCargo); + Color hpBorder = compatible ? GoldCol : TextLight; + DrawRect(rect, hpBorder, filled: false, width: compatible ? 2.4f : 1.4f); + + var mounted = _grid.GetMountedOn(hp.Id); + string tag = mounted is not null + ? $"{mounted.Spec.Kind.ToString()[..1]}:{mounted.CurrentTemp:F0}°" + : hp.Kind.ToString()[..3].ToUpperInvariant(); + DrawString( + ThemeDB.FallbackFont, + rect.Position + new Vector2(3f, 13f), + tag, + HorizontalAlignment.Left, + rect.Size.X - 4f, + 10, + mounted is { Spec.IsImperial: true } ? GoldCol : TextLight); + } + } + + private static Color TempToColor(float temp) + { + if (temp < 45f) + { + float t = Math.Clamp((temp - 20f) / 25f, 0f, 1f); + return new Color(0.18f, 0.23f, 0.26f).Lerp(new Color(0.32f, 0.45f, 0.28f), t); + } + if (temp < 95f) + { + float t = Math.Clamp((temp - 45f) / 50f, 0f, 1f); + return new Color(0.32f, 0.45f, 0.28f).Lerp(new Color(0.62f, 0.69f, 0.36f), t); + } + if (temp < 140f) + { + float t = Math.Clamp((temp - 95f) / 45f, 0f, 1f); + return new Color(0.62f, 0.69f, 0.36f).Lerp(OrangeCol, t); + } + float hotT = Math.Clamp((temp - 140f) / 60f, 0f, 1f); + return OrangeCol.Lerp(RedCol, hotT); + } + } +} diff --git a/client/Main.cs b/client/Main.cs new file mode 100644 index 0000000..bf15886 --- /dev/null +++ b/client/Main.cs @@ -0,0 +1,256 @@ +using System; +using Godot; +using RustToDust.Core; +using RustToDust.Ymir; + +namespace RustToDust.Client; + +/// +/// Root Godot node for Rust to Dust. +/// Godot physics is Dummy; owns 100% of vehicle, thermal, spectator, and terrain physics at 60 Hz. +/// +public partial class Main : Node3D +{ + private TerrainRenderer _terrain = null!; + private ArenaRenderer _arena = null!; + private Camera3D _camera = null!; + private Hud _hud = null!; + private ArenaSession? _session; + + private PlayerInput? _scriptedInput; + private float _cameraDistance = 30f; + private Vector3 _cameraSmoothedTarget = Vector3.Zero; + private float _elapsedSeconds; + private bool _interactQueued; + private int _seed = 42; + + public ArenaSession Session => _session ?? throw new InvalidOperationException($"No active ArenaSession ({Failure ?? "uninitialized"})"); + public TerrainRenderer Terrain => _terrain; + public ArenaRenderer Arena => _arena; + public Hud Hud => _hud; + public string? Failure { get; private set; } + public int Seed => _seed; + + public override void _Ready() + { + SetupLightingAndSky(); + + _terrain = new TerrainRenderer { Name = "Terrain" }; + AddChild(_terrain); + + _arena = new ArenaRenderer { Name = "Arena" }; + AddChild(_arena); + + _camera = new Camera3D + { + Name = "TacticalCamera", + Current = true, + Fov = 48f, + Far = 520f + }; + AddChild(_camera); + + _hud = new Hud(() => _session, OnEquipCargo) { Name = "Hud" }; + AddChild(_hud); + + Reset(_seed); + } + + public override void _ExitTree() + { + _session?.Dispose(); + _session = null; + } + + public void Reset(int seed) + { + _seed = seed; + _session?.Dispose(); + _session = null; + Failure = null; + + try + { + _session = new ArenaSession(seed); + var p = _session.State.Player; + _cameraSmoothedTarget = new Vector3(p.X, p.Y, p.Z); + _terrain.InvalidateAll(); + _terrain.Sync(_session.State.Terrain); + _arena.Sync(_session, _elapsedSeconds); + _hud.Sync(_session); + } + catch (Exception ex) + { + Failure = ex.Message; + GD.PushError("ArenaSession startup failed: " + ex); + } + } + + public void SetScriptedInput(PlayerInput? input) => _scriptedInput = input; + + public override void _UnhandledInput(InputEvent @event) + { + if (@event is InputEventKey key && key.Pressed && !key.Echo) + { + switch (key.Keycode) + { + case Key.E: + _interactQueued = true; + break; + case Key.Tab: + _hud.ToggleGarage(); + break; + case Key.R: + Reset(_seed + 1); + break; + case Key.Escape: + Input.MouseMode = Input.MouseMode == Input.MouseModeEnum.Confined + ? Input.MouseModeEnum.Visible + : Input.MouseModeEnum.Confined; + break; + } + } + else if (@event is InputEventMouseButton mb && mb.Pressed) + { + if (mb.ButtonIndex == MouseButton.WheelUp) + { + _cameraDistance = Math.Clamp(_cameraDistance - 2.5f, 16f, 58f); + } + else if (mb.ButtonIndex == MouseButton.WheelDown) + { + _cameraDistance = Math.Clamp(_cameraDistance + 2.5f, 16f, 58f); + } + } + } + + public override void _PhysicsProcess(double delta) + { + if (_session is null) + { + return; + } + + _elapsedSeconds += (float)delta; + var input = _scriptedInput ?? GatherPlayerInput(); + _interactQueued = false; + + _session.Step(input); + _terrain.Sync(_session.State.Terrain); + _arena.Sync(_session, _elapsedSeconds); + } + + public override void _Process(double delta) + { + if (_session is null) + { + return; + } + + UpdateCamera((float)delta); + _hud.Sync(_session); + } + + private PlayerInput GatherPlayerInput() + { + float throttle = 0f; + if (Input.IsKeyPressed(Key.W) || Input.IsKeyPressed(Key.Up)) throttle += 1f; + if (Input.IsKeyPressed(Key.S) || Input.IsKeyPressed(Key.Down)) throttle -= 1f; + + float steer = 0f; + if (Input.IsKeyPressed(Key.D) || Input.IsKeyPressed(Key.Right)) steer += 1f; + if (Input.IsKeyPressed(Key.A) || Input.IsKeyPressed(Key.Left)) steer -= 1f; + + bool brake = Input.IsKeyPressed(Key.Space); + Vector2 mousePos = GetViewport().GetMousePosition(); + bool pointerOnHud = _hud.IsPointerOverInteractiveHud(mousePos); + bool fire = !pointerOnHud && Input.IsMouseButtonPressed(MouseButton.Left); + + var (aimX, aimZ) = ComputeMouseTerrainAim(mousePos); + return new PlayerInput( + Throttle: throttle, + Steer: steer, + AimWorldX: aimX, + AimWorldZ: aimZ, + Fire: fire, + InteractPickup: _interactQueued, + Brake: brake); + } + + private (float AimX, float AimZ) ComputeMouseTerrainAim(Vector2 mousePos) + { + var player = Session.State.Player; + Vector3 rayOrigin = _camera.ProjectRayOrigin(mousePos); + Vector3 rayDir = _camera.ProjectRayNormal(mousePos); + + if (Session.State.Terrain.Raycast( + rayOrigin.X, rayOrigin.Y, rayOrigin.Z, + rayDir.X, rayDir.Y, rayDir.Z, + maxDistance: 320f, + out float hx, out _, out float hz, out _)) + { + return (hx, hz); + } + + if (MathF.Abs(rayDir.Y) > 1e-4f) + { + float t = (player.Y - rayOrigin.Y) / rayDir.Y; + if (t > 0f) + { + Vector3 p = rayOrigin + rayDir * t; + return (p.X, p.Z); + } + } + + return (player.X + MathF.Sin(player.Yaw) * 25f, player.Z + MathF.Cos(player.Yaw) * 25f); + } + + private void UpdateCamera(float dt) + { + var p = Session.State.Player; + var target = new Vector3(p.X, p.Y + 1.0f, p.Z); + float blend = 1f - MathF.Exp(-dt * 9f); + _cameraSmoothedTarget = _cameraSmoothedTarget.Lerp(target, blend); + + // Angled tactical 3rd-person desert chase view + Vector3 offset = new Vector3(0f, _cameraDistance * 0.78f, -_cameraDistance * 0.72f); + _camera.GlobalPosition = _cameraSmoothedTarget + offset; + _camera.LookAt(_cameraSmoothedTarget, Vector3.Up); + } + + private void OnEquipCargo(int cargoIndex, string hardpointId) + { + _session?.TryEquipCargo(cargoIndex, hardpointId); + } + + private void SetupLightingAndSky() + { + var sun = new DirectionalLight3D + { + Name = "DesertSun", + LightColor = new Color(1.0f, 0.92f, 0.78f), + LightEnergy = 1.45f, + ShadowEnabled = true, + RotationDegrees = new Vector3(-48f, 32f, 0f) + }; + AddChild(sun); + + var skyMat = new ProceduralSkyMaterial + { + SkyTopColor = new Color(0.24f, 0.34f, 0.44f), + SkyHorizonColor = new Color(0.76f, 0.56f, 0.37f), + GroundBottomColor = new Color(0.32f, 0.22f, 0.14f), + GroundHorizonColor = new Color(0.70f, 0.50f, 0.33f) + }; + var env = new Godot.Environment + { + BackgroundMode = Godot.Environment.BGMode.Sky, + Sky = new Sky { SkyMaterial = skyMat }, + AmbientLightSource = Godot.Environment.AmbientSource.Sky, + AmbientLightEnergy = 0.55f, + FogEnabled = true, + FogLightColor = new Color(0.74f, 0.55f, 0.38f), + FogDensity = 0.0022f + }; + AddChild(new WorldEnvironment { Name = "WorldEnv", Environment = env }); + } +} diff --git a/client/Main.tscn b/client/Main.tscn new file mode 100644 index 0000000..4285746 --- /dev/null +++ b/client/Main.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://Main.cs" id="1"] + +[node name="Main" type="Node3D"] +script = ExtResource("1") diff --git a/client/NativeLibraries.cs b/client/NativeLibraries.cs new file mode 100644 index 0000000..d789a5a --- /dev/null +++ b/client/NativeLibraries.cs @@ -0,0 +1,43 @@ +using System; +using System.IO; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Godot; +using Ymir.Box3D; + +namespace RustToDust.Client; + +/// +/// Finds ymir_box3d for Ymir.Box3D's DllImports. Godot loads game assemblies into its own load context, so the +/// default probing does not look beside them. A run from the editor or --path loads the library from the +/// project's build directory; an exported run from the data folder Godot puts beside the executable. +/// +internal static class NativeLibraries +{ + private const string Library = "ymir_box3d"; + +#pragma warning disable CA2255 // application code: the resolver must exist before the first DllImport + [ModuleInitializer] + internal static void Register() => + NativeLibrary.SetDllImportResolver(typeof(Box3DSoaWorld).Assembly, Resolve); + + private static IntPtr Resolve(string name, Assembly assembly, DllImportSearchPath? searchPath) + { + if (name != Library) return IntPtr.Zero; + string dir = OS.HasFeature("template") + ? Path.Combine(Path.GetDirectoryName(OS.GetExecutablePath())!, $"data_RustToDust.Client_{Platform()}_{Arch()}") + : ProjectSettings.GlobalizePath("res://.godot/mono/temp/bin/Debug"); + string path = Path.Combine(dir, FileName()); + return File.Exists(path) && NativeLibrary.TryLoad(path, out var handle) ? handle : IntPtr.Zero; + } + + private static string FileName() => + OperatingSystem.IsWindows() ? "ymir_box3d.dll" : OperatingSystem.IsMacOS() ? "libymir_box3d.dylib" : "libymir_box3d.so"; + + private static string Platform() => + OperatingSystem.IsWindows() ? "windows" : OperatingSystem.IsMacOS() ? "macos" : "linuxbsd"; + + private static string Arch() => + RuntimeInformation.ProcessArchitecture == System.Runtime.InteropServices.Architecture.Arm64 ? "arm64" : "x86_64"; +} diff --git a/client/RustToDust.Client.csproj b/client/RustToDust.Client.csproj new file mode 100644 index 0000000..aa56926 --- /dev/null +++ b/client/RustToDust.Client.csproj @@ -0,0 +1,13 @@ + + + + net8.0 + true + enable + RustToDust.Client + RustToDust.Client + + + + + diff --git a/client/TerrainRenderer.cs b/client/TerrainRenderer.cs new file mode 100644 index 0000000..a6013be --- /dev/null +++ b/client/TerrainRenderer.cs @@ -0,0 +1,286 @@ +using System; +using System.Collections.Generic; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client; + +/// +/// Top-down orthographic SubViewport brush-to-tile PBR + displacement terrain baker. +/// Maintains a 4x4 grid of 96m x 96m terrain tiles covering [-192, +192] in X and Z. +/// Only tiles whose changed are re-baked. +/// +public partial class TerrainRenderer : Node3D +{ + private const int ViewportSize = 256; + private const float PixelsPerMeter = ViewportSize / TerrainField.TileSize; + private const float HeightSpan = TerrainField.MaxWorldHeight - TerrainField.MinWorldHeight; + private const float BaseHeightNorm = (0f - TerrainField.MinWorldHeight) / HeightSpan; + + private static readonly Color HeightClearColor = new(BaseHeightNorm, 0.88f, 0.02f, 0.0f); + private static readonly Color AlbedoClearColor = new(0.69f, 0.50f, 0.31f, 1.0f); + + private sealed class TileNode + { + public SubViewport HeightViewport = null!; + public Node2D HeightCanvas = null!; + public SubViewport AlbedoViewport = null!; + public Node2D AlbedoCanvas = null!; + public MeshInstance3D SurfaceMesh = null!; + public int BakedVersion = -1; + } + + private readonly TileNode[,] _tiles = new TileNode[TerrainField.TileGridCount, TerrainField.TileGridCount]; + private Shader _brushAddShader = null!; + private Shader _brushSubShader = null!; + private Shader _brushAlbedoShader = null!; + private Shader _surfaceShader = null!; + private TerrainField? _lastTerrain; + + public int BakedTileCount { get; private set; } + public int DirtyRebakes { get; private set; } + + public override void _Ready() + { + _brushAddShader = GD.Load("res://terrain_brush.gdshader"); + _brushSubShader = GD.Load("res://terrain_brush_sub.gdshader"); + _brushAlbedoShader = GD.Load("res://terrain_brush_albedo.gdshader"); + _surfaceShader = GD.Load("res://terrain_surface.gdshader"); + + BuildTileGrid(); + } + + public void InvalidateAll() + { + for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + { + for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + { + _tiles[tx, tz].BakedVersion = -1; + } + } + BakedTileCount = 0; + DirtyRebakes = 0; + _lastTerrain = null; + } + + public void Sync(TerrainField terrain) + { + if (!ReferenceEquals(_lastTerrain, terrain)) + { + InvalidateAll(); + _lastTerrain = terrain; + } + + for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + { + for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + { + var tile = _tiles[tx, tz]; + int version = terrain.TileVersions[tx, tz]; + if (tile.BakedVersion != version) + { + BakeTile(tx, tz, tile, terrain); + if (tile.BakedVersion < 0) + { + BakedTileCount++; + } + else + { + DirtyRebakes++; + } + tile.BakedVersion = version; + } + } + } + terrain.ClearDirtyMask(); + } + + private void BuildTileGrid() + { + for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + { + for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + { + var tile = new TileNode(); + + tile.HeightViewport = CreateOrthoViewport($"Tile_{tx}_{tz}_Height", useHdr: true, out var heightCanvas); + tile.HeightCanvas = heightCanvas; + AddChild(tile.HeightViewport); + + tile.AlbedoViewport = CreateOrthoViewport($"Tile_{tx}_{tz}_Albedo", useHdr: false, out var albedoCanvas); + tile.AlbedoCanvas = albedoCanvas; + AddChild(tile.AlbedoViewport); + + var plane = new PlaneMesh + { + Size = new Vector2(TerrainField.TileSize, TerrainField.TileSize), + SubdivideWidth = 48, + SubdivideDepth = 48 + }; + + var mat = new ShaderMaterial { Shader = _surfaceShader }; + mat.SetShaderParameter("height_tex", tile.HeightViewport.GetTexture()); + mat.SetShaderParameter("albedo_tex", tile.AlbedoViewport.GetTexture()); + mat.SetShaderParameter("height_min", TerrainField.MinWorldHeight); + mat.SetShaderParameter("height_max", TerrainField.MaxWorldHeight); + mat.SetShaderParameter("tile_size", TerrainField.TileSize); + + float centerX = -TerrainField.HalfExtent + (tx + 0.5f) * TerrainField.TileSize; + float centerZ = -TerrainField.HalfExtent + (tz + 0.5f) * TerrainField.TileSize; + + tile.SurfaceMesh = new MeshInstance3D + { + Name = $"Tile_{tx}_{tz}_Mesh", + Mesh = plane, + MaterialOverride = mat, + Position = new Vector3(centerX, 0f, centerZ), + CustomAabb = new Aabb( + new Vector3(-TerrainField.TileSize * 0.5f, TerrainField.MinWorldHeight - 2f, -TerrainField.TileSize * 0.5f), + new Vector3(TerrainField.TileSize, HeightSpan + 4f, TerrainField.TileSize)) + }; + AddChild(tile.SurfaceMesh); + + _tiles[tx, tz] = tile; + } + } + } + + private static SubViewport CreateOrthoViewport(string name, bool useHdr, out Node2D canvas) + { + var vp = new SubViewport + { + Name = name, + Size = new Vector2I(ViewportSize, ViewportSize), + Disable3D = true, + UseHdr2D = useHdr, + TransparentBg = false, + RenderTargetClearMode = SubViewport.ClearMode.Always, + RenderTargetUpdateMode = SubViewport.UpdateMode.Disabled + }; + + var cam = new Camera2D + { + AnchorMode = Camera2D.AnchorModeEnum.FixedTopLeft, + Position = Vector2.Zero, + Enabled = true + }; + vp.AddChild(cam); + + canvas = new Node2D { Name = "Canvas" }; + vp.AddChild(canvas); + return vp; + } + + private void BakeTile(int tx, int tz, TileNode tile, TerrainField terrain) + { + ClearCanvasChildren(tile.HeightCanvas); + ClearCanvasChildren(tile.AlbedoCanvas); + + // Full-tile base clear quads + tile.HeightCanvas.AddChild(new ColorRect + { + Position = Vector2.Zero, + Size = new Vector2(ViewportSize, ViewportSize), + Color = HeightClearColor + }); + tile.AlbedoCanvas.AddChild(new ColorRect + { + Position = Vector2.Zero, + Size = new Vector2(ViewportSize, ViewportSize), + Color = AlbedoClearColor + }); + + float tileMinX = -TerrainField.HalfExtent + tx * TerrainField.TileSize; + float tileMinZ = -TerrainField.HalfExtent + tz * TerrainField.TileSize; + IReadOnlyList indices = terrain.GetTileBrushIndices(tx, tz); + var brushes = terrain.Brushes; + + for (int i = 0; i < indices.Count; i++) + { + var b = brushes[indices[i]]; + if (b.RadiusX <= 0.05f || b.RadiusZ <= 0.05f) + { + continue; + } + + float px = (b.X - tileMinX) * PixelsPerMeter; + float py = (b.Z - tileMinZ) * PixelsPerMeter; + float rxPx = b.RadiusX * PixelsPerMeter; + float rzPx = b.RadiusZ * PixelsPerMeter; + int kindInt = (int)b.Kind; + + // 1. Height+Material brush pass(es) + if (b.Kind == TerrainBrushKind.Crater) + { + // Crater uses subtractive pit + additive ejecta rim/scorch + tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushSubShader, kindInt, b.HeightDelta)); + tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushAddShader, kindInt, b.HeightDelta)); + } + else if (b.Kind == TerrainBrushKind.Track) + { + tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushSubShader, kindInt, b.HeightDelta)); + tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushAddShader, kindInt, b.HeightDelta)); + } + else if (b.Kind == TerrainBrushKind.Road || b.HeightDelta < 0f) + { + tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushSubShader, kindInt, b.HeightDelta)); + } + else + { + tile.HeightCanvas.AddChild(CreateBrushQuad(px, py, rxPx, rzPx, b.RotationRad, _brushAddShader, kindInt, b.HeightDelta)); + } + + // 2. Albedo brush pass + var albedoQuad = new ColorRect + { + Position = new Vector2(px - rxPx, py - rzPx), + Size = new Vector2(rxPx * 2f, rzPx * 2f), + PivotOffset = new Vector2(rxPx, rzPx), + Rotation = b.RotationRad + }; + var albedoMat = new ShaderMaterial { Shader = _brushAlbedoShader }; + albedoMat.SetShaderParameter("brush_kind", kindInt); + albedoMat.SetShaderParameter("brush_albedo", new Vector3(b.AlbedoR, b.AlbedoG, b.AlbedoB)); + albedoMat.SetShaderParameter("height_delta", b.HeightDelta); + albedoQuad.Material = albedoMat; + tile.AlbedoCanvas.AddChild(albedoQuad); + } + + tile.HeightViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once; + tile.AlbedoViewport.RenderTargetUpdateMode = SubViewport.UpdateMode.Once; + } + + private static ColorRect CreateBrushQuad( + float px, float py, + float rxPx, float rzPx, + float rotationRad, + Shader shader, + int kindInt, + float heightDelta) + { + var quad = new ColorRect + { + Position = new Vector2(px - rxPx, py - rzPx), + Size = new Vector2(rxPx * 2f, rzPx * 2f), + PivotOffset = new Vector2(rxPx, rzPx), + Rotation = rotationRad + }; + var mat = new ShaderMaterial { Shader = shader }; + mat.SetShaderParameter("brush_kind", kindInt); + mat.SetShaderParameter("height_delta", heightDelta); + mat.SetShaderParameter("height_span", HeightSpan); + quad.Material = mat; + return quad; + } + + private static void ClearCanvasChildren(Node2D canvas) + { + for (int i = canvas.GetChildCount() - 1; i >= 0; i--) + { + var child = canvas.GetChild(i); + canvas.RemoveChild(child); + child.QueueFree(); + } + } +} diff --git a/client/project.godot b/client/project.godot new file mode 100644 index 0000000..d214e57 --- /dev/null +++ b/client/project.godot @@ -0,0 +1,33 @@ +; Engine configuration file. +; It's best edited using the editor UI and not directly, +; since the parameters that go here are not all obvious. + +config_version=5 + +[application] + +config/name="Rust to Dust" +run/main_scene="res://Main.tscn" +config/features=PackedStringArray("4.7", "C#") + +[display] + +window/size/viewport_width=1280 +window/size/viewport_height=720 +window/stretch/mode="canvas_items" + +[dotnet] + +project/assembly_name="RustToDust.Client" + +[physics] + +; Godot's physics is switched off: Ymir is the only physics world. ArenaSession ticks at 60 Hz. +3d/physics_engine="Dummy" +common/physics_ticks_per_second=60 +common/physics_interpolation=true + +[rendering] + +renderer/rendering_method="gl_compatibility" +renderer/rendering_method.mobile="gl_compatibility" diff --git a/client/terrain_brush.gdshader b/client/terrain_brush.gdshader new file mode 100644 index 0000000..b37ab9f --- /dev/null +++ b/client/terrain_brush.gdshader @@ -0,0 +1,71 @@ +shader_type canvas_item; +render_mode blend_add; + +// Encodes positive height deltas into R ([-12m, +16m] => span 28m), +// plus positive roughness delta (G), metallic (B), and scorch/wear (A). +uniform int brush_kind = 0; +uniform float height_delta = 0.0; +uniform float height_span = 28.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 dh = 0.0; + float dg = 0.0; + float db = 0.0; + float da = 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; + dh = max(0.0, height_delta) * env * (0.35 + 0.65 * ridge) * asym; + 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); + dh = max(0.0, height_delta) * plateau; + db = 0.05 * plateau; + } else if (brush_kind == 2) { + // SalvagePad (positive part) + float env = 1.0 - r2; + env *= env; + dh = max(0.0, height_delta) * env; + db = 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)); + dh = 0.32 * depth * rim_t * rim_t; + float pit_t = clamp(1.0 - r / 0.65, 0.0, 1.0); + dg = 0.04 * (1.0 - r); + db = 0.10 * pit_t; + da = 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; + da = 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; + dg = 0.02 * mask; + db = 0.08 * mask; + da = 0.85 * mask; + } + + COLOR = vec4(dh / height_span, dg, db, da); +} diff --git a/client/terrain_brush_albedo.gdshader b/client/terrain_brush_albedo.gdshader new file mode 100644 index 0000000..961cf7d --- /dev/null +++ b/client/terrain_brush_albedo.gdshader @@ -0,0 +1,73 @@ +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 + float env = 1.0 - r2; + env *= env; + float rut = smoothstep(0.15, 0.45, abs(u)) * (1.0 - smoothstep(0.60, 0.92, abs(u))); + 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); +} diff --git a/client/terrain_brush_sub.gdshader b/client/terrain_brush_sub.gdshader new file mode 100644 index 0000000..1b64ed8 --- /dev/null +++ b/client/terrain_brush_sub.gdshader @@ -0,0 +1,40 @@ +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 = 28.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; + 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, 0.0, 0.0, 0.0); +} diff --git a/client/terrain_surface.gdshader b/client/terrain_surface.gdshader new file mode 100644 index 0000000..c8f6eca --- /dev/null +++ b/client/terrain_surface.gdshader @@ -0,0 +1,48 @@ +shader_type spatial; +render_mode cull_back, depth_draw_opaque; + +uniform sampler2D height_tex : filter_linear, repeat_disable; +uniform sampler2D albedo_tex : filter_linear, repeat_disable; +uniform float height_min = -12.0; +uniform float height_max = 16.0; +uniform float tile_size = 96.0; + +float decode_height(float h_norm) { + return mix(height_min, height_max, clamp(h_norm, 0.0, 1.0)); +} + +float hash21(vec2 p) { + p = fract(p * vec2(123.34, 456.21)); + p += dot(p, p + 45.32); + return fract(p.x * p.y); +} + +void vertex() { + float h_norm = textureLod(height_tex, UV, 0.0).r; + VERTEX.y += decode_height(h_norm); +} + +void fragment() { + const float texel_step = 1.0 / 256.0; + float world_step = tile_size / 256.0; + + float hL = decode_height(texture(height_tex, UV - vec2(texel_step, 0.0)).r); + float hR = decode_height(texture(height_tex, UV + vec2(texel_step, 0.0)).r); + float hD = decode_height(texture(height_tex, UV - vec2(0.0, texel_step)).r); + float hU = decode_height(texture(height_tex, UV + vec2(0.0, texel_step)).r); + + 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); + vec3 alb = texture(albedo_tex, UV).rgb; + + // Subtle desert sand grain so dunes read crisply under sunlight + float grain = (hash21(floor(UV * 768.0)) - 0.5) * 0.045; + float scorch = clamp(mat.a, 0.0, 1.0); + alb = clamp(alb + vec3(grain), 0.0, 1.0) * (1.0 - 0.30 * scorch); + + ALBEDO = alb; + ROUGHNESS = clamp(mat.g, 0.2, 0.98); + METALLIC = clamp(mat.b, 0.0, 0.85); +} diff --git a/client/tests/Smoke.cs b/client/tests/Smoke.cs new file mode 100644 index 0000000..095c0d8 --- /dev/null +++ b/client/tests/Smoke.cs @@ -0,0 +1,121 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Godot; +using RustToDust.Core; + +namespace RustToDust.Client.Tests; + +/// +/// Headless Godot smoke test: instantiates Main, drives 60 frames with throttle + fire + crater stamp, +/// verifies terrain tile baking and Ymir physics integration, and exits with code 0 on pass. +/// godot --headless --path client res://tests/Smoke.tscn +/// +public partial class Smoke : Node +{ + private const double WatchdogSeconds = 60.0; + + private readonly List _failures = new(); + private Main _main = null!; + private bool _done; + + public override void _Ready() => _ = RunAsync(); + + public override void _Process(double delta) + { + if (!_done && Time.GetTicksMsec() > WatchdogSeconds * 1000.0) + { + Check(false, $"Smoke watchdog timed out after {WatchdogSeconds}s"); + Finish(); + } + } + + private async Task RunAsync() + { + try + { + _main = GD.Load("res://Main.tscn").Instantiate
(); + AddChild(_main); + + if (_main.Failure is { } failure) + { + Check(false, "Main failed to initialize ArenaSession: " + failure); + } + else + { + await RunScenarioAsync(); + } + } + catch (Exception ex) + { + Check(false, ex.ToString()); + } + + Finish(); + } + + private async Task RunScenarioAsync() + { + Check(Engine.PhysicsTicksPerSecond == 60, $"Expected 60 physics ticks/sec, got {Engine.PhysicsTicksPerSecond}"); + Check((string)ProjectSettings.GetSetting("physics/3d/physics_engine") == "Dummy", "Godot 3D physics_engine is not Dummy"); + Check(!_main.GetWorld3D().Space.IsValid, "Godot should have no active 3D physics space"); + Check(_main.Terrain.BakedTileCount == 16, $"Expected 16 baked terrain tiles, got {_main.Terrain.BakedTileCount}"); + + var player = _main.Session.State.Player; + float startX = player.X; + float startZ = player.Z; + + _main.SetScriptedInput(new PlayerInput( + Throttle: 1f, + Steer: 0.25f, + AimWorldX: startX + 35f, + AimWorldZ: startZ + 10f, + Fire: true, + InteractPickup: false, + Brake: false)); + + for (int i = 0; i < 60; i++) + { + await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame); + if (_main.Failure is { } f) + { + Check(false, "Session failure during physics loop: " + f); + return; + } + } + + float dx = player.X - startX; + float dz = player.Z - startZ; + float displacement = MathF.Sqrt(dx * dx + dz * dz); + Check(displacement > 3f, $"Expected player displacement > 3m after 60 frames, got {displacement:F2}m"); + Check(!float.IsNaN(player.X) && !float.IsNaN(player.Y) && !float.IsNaN(player.Z), "Player position became NaN"); + + int rebakesBefore = _main.Terrain.DirtyRebakes; + _main.Session.State.Terrain.StampCrater(-48f, -48f, radius: 5f, depth: 1.4f); + await ToSignal(GetTree(), SceneTree.SignalName.PhysicsFrame); + Check(_main.Terrain.DirtyRebakes == rebakesBefore + 1, + $"Expected 1 dirty tile rebake from isolated crater stamp, got {_main.Terrain.DirtyRebakes - rebakesBefore}"); + + _main.SetScriptedInput(null); + } + + private void Check(bool condition, string message) + { + if (!condition) + { + _failures.Add(message); + } + } + + private void Finish() + { + if (_done) return; + _done = true; + foreach (var f in _failures) + { + GD.PrintErr("SMOKE FAIL: " + f); + } + GD.Print(_failures.Count == 0 ? "SMOKE PASS" : $"SMOKE FAILED ({_failures.Count})"); + GetTree().Quit(_failures.Count == 0 ? 0 : 1); + } +} diff --git a/client/tests/Smoke.tscn b/client/tests/Smoke.tscn new file mode 100644 index 0000000..d05be64 --- /dev/null +++ b/client/tests/Smoke.tscn @@ -0,0 +1,6 @@ +[gd_scene load_steps=2 format=3] + +[ext_resource type="Script" path="res://tests/Smoke.cs" id="1"] + +[node name="Smoke" type="Node"] +script = ExtResource("1") diff --git a/src/RustToDust.Core/MatchState.cs b/src/RustToDust.Core/MatchState.cs index 184c74a..3af9efc 100644 --- a/src/RustToDust.Core/MatchState.cs +++ b/src/RustToDust.Core/MatchState.cs @@ -110,7 +110,9 @@ namespace RustToDust.Core Rng = new Random(seed); Spectators = new SpectatorRing(seed + 101); Broadcast = new BroadcastFeed(); - ArenaCoverBoxes = BuildCoverBoxes(); + var rawCover = BuildCoverBoxes(); + Terrain = TerrainField.Generate((ulong)seed, rawCover); + ArenaCoverBoxes = SeatBoxesOnTerrain(rawCover, Terrain); ArenaBoundaryBoxes = BuildBoundaryBoxes(); SpawnContenders(); @@ -123,6 +125,7 @@ namespace RustToDust.Core public float Time { get; set; } public MatchPhase Phase { get; set; } = MatchPhase.Active; + public TerrainField Terrain { get; } public List Contenders { get; } = new(); public SpectatorRing Spectators { get; } public List GroundDrops { get; } = new(); @@ -281,7 +284,7 @@ namespace RustToDust.Core SpawnModuleDrop(contender.X + 1.5f + i * 0.7f, contender.Z - 1.5f, overflow[i]); } - contender.Y = contender.Grid.Spec.HalfHeight + 0.1f; + contender.Y = Terrain.SampleHeight(contender.X, contender.Z) + contender.Grid.Spec.HalfHeight + 0.15f; Broadcast.EmitChassisSwap(Time, contender.Id, contender.Grid.Spec.Name); ChassisSwapped?.Invoke(contender); return true; @@ -298,7 +301,9 @@ namespace RustToDust.Core float z = MathF.Sin(angle) * spawnRadius; float yaw = MathF.Atan2(-x, -z); string name = i == 0 ? "Contender 01 (You)" : $"Contender {i + 1:00}"; - Contenders.Add(new ContenderState(i, name, i == 0, Catalog.CreateStarterBuggy(), x, z, yaw)); + var contender = new ContenderState(i, name, i == 0, Catalog.CreateStarterBuggy(), x, z, yaw); + contender.Y = Terrain.SampleHeight(x, z) + contender.Grid.Spec.HalfHeight + 0.15f; + Contenders.Add(contender); } } @@ -361,10 +366,22 @@ namespace RustToDust.Core }; } + private static IReadOnlyList SeatBoxesOnTerrain(IReadOnlyList raw, TerrainField terrain) + { + var seated = new ArenaBoxSpec[raw.Count]; + for (int i = 0; i < raw.Count; i++) + { + var b = raw[i]; + float groundY = terrain.SampleHeight(b.X, b.Z); + seated[i] = b with { Y = groundY + b.HalfY }; + } + return seated; + } + private static IReadOnlyList BuildBoundaryBoxes() { - const float wallY = 4f; - const float wallHalfH = 4f; + const float wallY = 2f; + const float wallHalfH = 10f; const float wallHalfThick = 2f; const float span = ArenaHalfExtent + wallHalfThick; return new ArenaBoxSpec[] diff --git a/src/RustToDust.Core/TerrainField.cs b/src/RustToDust.Core/TerrainField.cs new file mode 100644 index 0000000..b4396c3 --- /dev/null +++ b/src/RustToDust.Core/TerrainField.cs @@ -0,0 +1,564 @@ +using System; +using System.Collections.Generic; + +namespace RustToDust.Core +{ + public enum TerrainBrushKind + { + DuneRidge, + Mesa, + SalvagePad, + Road, + Crater, + Track, + Scorch + } + + public readonly record struct TerrainBrush( + int Id, + TerrainBrushKind Kind, + float X, + float Z, + float RotationRad, + float RadiusX, + float RadiusZ, + float HeightDelta, + float Roughness, + float Metallic, + float AlbedoR, + float AlbedoG, + float AlbedoB, + bool Dynamic); + + public sealed class TerrainField + { + public const float ArenaSize = 384f; + public const float HalfExtent = 192f; + public const int TileGridCount = 4; + public const float TileSize = ArenaSize / TileGridCount; // 96m + public const float MinWorldHeight = -12f; + public const float MaxWorldHeight = 16f; + public const int MaxDynamicDecals = 256; + + private readonly List _brushes = new(); + private readonly List[,] _tileBrushIndices = new List[TileGridCount, TileGridCount]; + private readonly Queue _dynamicDecalSlots = new(); + private int _nextBrushId = 1; + + public TerrainField(ulong seed) + { + Seed = seed; + TileVersions = new int[TileGridCount, TileGridCount]; + for (int tz = 0; tz < TileGridCount; tz++) + { + for (int tx = 0; tx < TileGridCount; tx++) + { + _tileBrushIndices[tx, tz] = new List(24); + } + } + } + + public ulong Seed { get; } + public IReadOnlyList Brushes => _brushes; + public int[,] TileVersions { get; } + public uint DirtyTileMask { get; private set; } + + public void ClearDirtyMask() => DirtyTileMask = 0u; + + public IReadOnlyList GetTileBrushIndices(int tx, int tz) => _tileBrushIndices[tx, tz]; + + public static TerrainField Generate(ulong seed, IReadOnlyList coverBoxes) + { + var field = new TerrainField(seed); + var rng = new Random((int)(seed ^ (seed >> 32))); + + // 1. Flat compacted salvage pads around cover ruins & center plaza (keeps cover seated cleanly near ~0m) + field.AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.SalvagePad, + X: 0f, + Z: 0f, + RotationRad: 0f, + RadiusX: 16f, + RadiusZ: 16f, + HeightDelta: 0.15f, + Roughness: 0.90f, + Metallic: 0.05f, + AlbedoR: 0.44f, + AlbedoG: 0.40f, + AlbedoB: 0.35f, + Dynamic: false)); + + for (int i = 0; i < coverBoxes.Count; i++) + { + var box = coverBoxes[i]; + float padR = MathF.Max(box.HalfX, box.HalfZ) + 7.5f; + field.AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.SalvagePad, + X: box.X, + Z: box.Z, + RotationRad: 0f, + RadiusX: padR, + RadiusZ: padR, + HeightDelta: 0.1f + (float)rng.NextDouble() * 0.25f, + Roughness: 0.92f, + Metallic: 0.04f, + AlbedoR: 0.42f, + AlbedoG: 0.38f, + AlbedoB: 0.34f, + Dynamic: false)); + } + + // 2. Dirt track ring segments around the mid-arena loop (r ~ 76..92m) + const int roadCount = 8; + for (int i = 0; i < roadCount; i++) + { + float angle = (i / (float)roadCount) * MathF.Tau + 0.18f; + float r = 82f + (float)(rng.NextDouble() * 8.0 - 4.0); + float rx = MathF.Cos(angle) * r; + float rz = MathF.Sin(angle) * r; + float tangentRot = angle + MathF.PI * 0.5f; + field.AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Road, + X: rx, + Z: rz, + RotationRad: tangentRot, + RadiusX: 9f, + RadiusZ: 34f, + HeightDelta: -0.18f, + Roughness: 0.94f, + Metallic: 0.02f, + AlbedoR: 0.56f, + AlbedoG: 0.40f, + AlbedoB: 0.25f, + Dynamic: false)); + } + + // 3. Sweeping desert dune ridges (~20 ridges + 2 dry-wash troughs), kept clear of cover boxes & center plaza + int duneCount = 0; + int attempts = 0; + while (duneCount < 20 && attempts < 240) + { + attempts++; + float x = (float)(rng.NextDouble() * 320.0 - 160.0); + float z = (float)(rng.NextDouble() * 320.0 - 160.0); + float radiusX = 14f + (float)rng.NextDouble() * 14f; + float radiusZ = 28f + (float)rng.NextDouble() * 28f; + + if (OverlapsProtectedPads(x, z, MathF.Max(radiusX, radiusZ) * 0.95f, coverBoxes)) + { + continue; + } + + bool dryWash = duneCount is 5 or 13; + float heightDelta = dryWash + ? -(1.4f + (float)rng.NextDouble() * 1.1f) + : 1.8f + (float)rng.NextDouble() * 3.1f; + + float rot = (float)(rng.NextDouble() * MathF.PI); + field.AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.DuneRidge, + X: x, + Z: z, + RotationRad: rot, + RadiusX: radiusX, + RadiusZ: radiusZ, + HeightDelta: heightDelta, + Roughness: dryWash ? 0.96f : 0.89f, + Metallic: 0.02f, + AlbedoR: dryWash ? 0.58f : 0.78f, + AlbedoG: dryWash ? 0.41f : 0.56f, + AlbedoB: dryWash ? 0.27f : 0.34f, + Dynamic: false)); + duneCount++; + } + + // 4. Terraced rust-mesa hills (~7 mesas), mainly mid/outer desert away from spawns & cover + int mesaCount = 0; + attempts = 0; + while (mesaCount < 7 && attempts < 100) + { + attempts++; + float angle = (float)(rng.NextDouble() * MathF.Tau); + float dist = 54f + (float)rng.NextDouble() * 116f; + float x = MathF.Cos(angle) * dist; + float z = MathF.Sin(angle) * dist; + float rx = 14f + (float)rng.NextDouble() * 11f; + float rz = 13f + (float)rng.NextDouble() * 11f; + + if (OverlapsProtectedPads(x, z, MathF.Max(rx, rz) + 6f, coverBoxes) || + OverlapsSpawnRing(x, z, MathF.Max(rx, rz) + 5f)) + { + continue; + } + + field.AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Mesa, + X: x, + Z: z, + RotationRad: (float)(rng.NextDouble() * MathF.PI), + RadiusX: rx, + RadiusZ: rz, + HeightDelta: 3.4f + (float)rng.NextDouble() * 3.8f, + Roughness: 0.86f, + Metallic: 0.08f, + AlbedoR: 0.48f, + AlbedoG: 0.25f, + AlbedoB: 0.17f, + Dynamic: false)); + mesaCount++; + } + + // Bump all initial tile versions to 1 so clients detect initial bake needed + for (int tz = 0; tz < TileGridCount; tz++) + { + for (int tx = 0; tx < TileGridCount; tx++) + { + field.TileVersions[tx, tz] = 1; + field.DirtyTileMask |= 1u << (tz * TileGridCount + tx); + } + } + + return field; + } + + public void StampCrater(float x, float z, float radius, float depth) + { + float clampedR = Math.Clamp(radius, 1.2f, 16f); + float clampedDepth = Math.Clamp(MathF.Abs(depth), 0.15f, 4.5f); + AddBrush(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Crater, + X: x, + Z: z, + RotationRad: 0f, + RadiusX: clampedR, + RadiusZ: clampedR, + HeightDelta: -clampedDepth, + Roughness: 0.96f, + Metallic: 0.12f, + AlbedoR: 0.15f, + AlbedoG: 0.12f, + AlbedoB: 0.10f, + Dynamic: true)); + } + + public void StampTrack(float x, float z, float yaw, float width, float length) + { + var brush = SetDynamicDecal(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Track, + X: x, + Z: z, + RotationRad: -yaw + MathF.PI * 0.5f, + RadiusX: Math.Clamp(length * 0.5f, 0.8f, 6f), + RadiusZ: Math.Clamp(width * 0.5f, 0.5f, 4f), + HeightDelta: -0.04f, + Roughness: 0.95f, + Metallic: 0.02f, + AlbedoR: 0.42f, + AlbedoG: 0.29f, + AlbedoB: 0.18f, + Dynamic: true)); + _ = brush; + } + + public void StampScorch(float x, float z, float radius) + { + float r = Math.Clamp(radius, 0.8f, 10f); + SetDynamicDecal(new TerrainBrush( + Id: 0, + Kind: TerrainBrushKind.Scorch, + X: x, + Z: z, + RotationRad: 0f, + RadiusX: r, + RadiusZ: r, + HeightDelta: 0f, + Roughness: 0.95f, + Metallic: 0.10f, + AlbedoR: 0.14f, + AlbedoG: 0.11f, + AlbedoB: 0.10f, + Dynamic: true)); + } + + public float SampleHeight(float x, float z) + { + float cx = Math.Clamp(x, -HalfExtent, HalfExtent); + float cz = Math.Clamp(z, -HalfExtent, HalfExtent); + WorldToTile(cx, cz, out int tx, out int tz); + + float h = 0f; + var indices = _tileBrushIndices[tx, tz]; + for (int i = 0; i < indices.Count; i++) + { + var b = _brushes[indices[i]]; + if (b.Kind == TerrainBrushKind.Scorch) + { + continue; + } + h += EvaluateBrushHeight(in b, cx, cz); + } + + return Math.Clamp(h, MinWorldHeight, MaxWorldHeight); + } + + public (float Nx, float Ny, float Nz) SampleNormal(float x, float z) + { + const float eps = 0.5f; + float hL = SampleHeight(x - eps, z); + float hR = SampleHeight(x + eps, z); + float hD = SampleHeight(x, z - eps); + float hU = SampleHeight(x, z + eps); + + float nx = hL - hR; + float ny = 2f * eps; + float nz = hD - hU; + float len = MathF.Sqrt(nx * nx + ny * ny + nz * nz); + if (len < 1e-5f) + { + return (0f, 1f, 0f); + } + return (nx / len, ny / len, nz / len); + } + + public bool Raycast( + float ox, float oy, float oz, + float dx, float dy, float dz, + float maxDistance, + out float hitX, out float hitY, out float hitZ, out float hitDist) + { + const float stepSize = 1.5f; + float prevT = 0f; + float prevDiff = oy - SampleHeight(ox, oz); + if (prevDiff <= 0f) + { + hitX = ox; + hitY = oy; + hitZ = oz; + hitDist = 0f; + return true; + } + + for (float t = stepSize; t <= maxDistance + stepSize; t += stepSize) + { + float ct = MathF.Min(t, maxDistance); + float px = ox + dx * ct; + float py = oy + dy * ct; + float pz = oz + dz * ct; + float diff = py - SampleHeight(px, pz); + + if (diff <= 0f) + { + // Binary refine between prevT and ct + float lo = prevT; + float hi = ct; + for (int iter = 0; iter < 5; iter++) + { + float mid = 0.5f * (lo + hi); + float mx = ox + dx * mid; + float my = oy + dy * mid; + float mz = oz + dz * mid; + if (my - SampleHeight(mx, mz) > 0f) + { + lo = mid; + } + else + { + hi = mid; + } + } + + hitDist = 0.5f * (lo + hi); + hitX = ox + dx * hitDist; + hitZ = oz + dz * hitDist; + hitY = SampleHeight(hitX, hitZ); + return true; + } + + prevT = ct; + prevDiff = diff; + if (ct >= maxDistance) + { + break; + } + } + + hitX = 0f; + hitY = 0f; + hitZ = 0f; + hitDist = maxDistance; + return false; + } + + public static float EvaluateBrushHeight(in TerrainBrush b, float worldX, float worldZ) + { + float dx = worldX - b.X; + float dz = worldZ - b.Z; + float cosR = MathF.Cos(b.RotationRad); + float sinR = MathF.Sin(b.RotationRad); + float lx = dx * cosR + dz * sinR; + float lz = -dx * sinR + dz * cosR; + + float u = lx / MathF.Max(0.1f, b.RadiusX); + float v = lz / MathF.Max(0.1f, b.RadiusZ); + float r2 = u * u + v * v; + if (r2 >= 1f) + { + return 0f; + } + + switch (b.Kind) + { + case TerrainBrushKind.DuneRidge: + { + float env = 1f - r2; + env *= env; + float ridge = MathF.Max(0f, 1f - u * u); + float asym = 1f + 0.32f * u; + return b.HeightDelta * env * (0.35f + 0.65f * ridge) * asym; + } + case TerrainBrushKind.Mesa: + { + float r = MathF.Sqrt(r2); + float t = Math.Clamp((1f - r) / 0.45f, 0f, 1f); + float plateau = t * t * (3f - 2f * t); + return b.HeightDelta * plateau; + } + case TerrainBrushKind.SalvagePad: + case TerrainBrushKind.Road: + case TerrainBrushKind.Track: + { + float env = 1f - r2; + return b.HeightDelta * env * env; + } + case TerrainBrushKind.Crater: + { + float r = MathF.Sqrt(r2); + float depth = MathF.Abs(b.HeightDelta); + float pitT = Math.Clamp(1f - r / 0.62f, 0f, 1f); + float pit = -depth * pitT * pitT * (3f - 2f * pitT); + float rimT = MathF.Sin(MathF.PI * Math.Clamp((r - 0.55f) / 0.45f, 0f, 1f)); + float rim = (0.32f * depth) * rimT * rimT; + return pit + rim; + } + default: + return 0f; + } + } + + private TerrainBrush AddBrush(TerrainBrush template) + { + var brush = template with { Id = _nextBrushId++ }; + int index = _brushes.Count; + _brushes.Add(brush); + RegisterBrushInTiles(index, in brush, incrementTileVersion: true); + return brush; + } + + private TerrainBrush SetDynamicDecal(TerrainBrush template) + { + var brush = template with { Id = _nextBrushId++ }; + if (_dynamicDecalSlots.Count >= MaxDynamicDecals) + { + int slot = _dynamicDecalSlots.Dequeue(); + var prev = _brushes[slot]; + UnregisterBrushFromTiles(slot, in prev); + _brushes[slot] = brush; + RegisterBrushInTiles(slot, in brush, incrementTileVersion: true); + _dynamicDecalSlots.Enqueue(slot); + return brush; + } + + int index = _brushes.Count; + _brushes.Add(brush); + RegisterBrushInTiles(index, in brush, incrementTileVersion: true); + _dynamicDecalSlots.Enqueue(index); + return brush; + } + + private void RegisterBrushInTiles(int index, in TerrainBrush brush, bool incrementTileVersion) + { + GetBrushTileBounds(in brush, out int minTx, out int maxTx, out int minTz, out int maxTz); + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + _tileBrushIndices[tx, tz].Add(index); + if (incrementTileVersion) + { + TileVersions[tx, tz]++; + DirtyTileMask |= 1u << (tz * TileGridCount + tx); + } + } + } + } + + private void UnregisterBrushFromTiles(int index, in TerrainBrush brush) + { + GetBrushTileBounds(in brush, out int minTx, out int maxTx, out int minTz, out int maxTz); + for (int tz = minTz; tz <= maxTz; tz++) + { + for (int tx = minTx; tx <= maxTx; tx++) + { + _tileBrushIndices[tx, tz].Remove(index); + TileVersions[tx, tz]++; + DirtyTileMask |= 1u << (tz * TileGridCount + tx); + } + } + } + + private static void GetBrushTileBounds(in TerrainBrush brush, out int minTx, out int maxTx, out int minTz, out int maxTz) + { + float extent = MathF.Sqrt(brush.RadiusX * brush.RadiusX + brush.RadiusZ * brush.RadiusZ); + float minX = brush.X - extent; + float maxX = brush.X + extent; + float minZ = brush.Z - extent; + float maxZ = brush.Z + extent; + + WorldToTile(Math.Clamp(minX, -HalfExtent, HalfExtent), Math.Clamp(minZ, -HalfExtent, HalfExtent), out minTx, out minTz); + WorldToTile(Math.Clamp(maxX, -HalfExtent, HalfExtent), Math.Clamp(maxZ, -HalfExtent, HalfExtent), out maxTx, out maxTz); + } + + public static void WorldToTile(float x, float z, out int tx, out int tz) + { + 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); + } + + private static bool OverlapsProtectedPads(float x, float z, float radius, IReadOnlyList coverBoxes) + { + // Keep center plaza clear + if (x * x + z * z < (radius + 20f) * (radius + 20f)) + { + return true; + } + + for (int i = 0; i < coverBoxes.Count; i++) + { + var c = coverBoxes[i]; + float dx = x - c.X; + float dz = z - c.Z; + float minDist = radius + MathF.Max(c.HalfX, c.HalfZ) + 9f; + if (dx * dx + dz * dz < minDist * minDist) + { + return true; + } + } + return false; + } + + private static bool OverlapsSpawnRing(float x, float z, float radius) + { + float dist = MathF.Sqrt(x * x + z * z); + return MathF.Abs(dist - 95f) < radius + 6f; + } + } +} diff --git a/src/RustToDust.Ymir/ArenaSession.cs b/src/RustToDust.Ymir/ArenaSession.cs index 6fade16..299b649 100644 --- a/src/RustToDust.Ymir/ArenaSession.cs +++ b/src/RustToDust.Ymir/ArenaSession.cs @@ -21,6 +21,7 @@ namespace RustToDust.Ymir private readonly Dictionary _contenderBodies = new(); private readonly Dictionary _spectatorBodies = new(); private readonly Dictionary _entityByStableId = new(); + private readonly float[] _trackDistAccum = new float[MatchState.ContenderCount]; private bool _disposed; public ArenaSession(int seed = 42) @@ -78,10 +79,11 @@ namespace RustToDust.Ymir private void BuildStaticArena() { - // Large 420m x 420m ground slab with top surface at y = 0 + // Safety floor slab at y = -12m below the lowest possible terrain valley; + // primary terrain support comes from 4-corner spring-damper sampling of State.Terrain. _world.AddStaticBox( GroundStableId, - (0f, -1f, 0f), + (0f, -13f, 0f), (210f, 1f, 210f), friction: 0.25f, restitution: 0.05f); @@ -126,10 +128,12 @@ namespace RustToDust.Ymir float density = spec.MassKg / MathF.Max(0.1f, volume); var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, c.Yaw); ulong stableId = ContenderStableIdBase + (ulong)c.Id; + float spawnY = State.Terrain.SampleHeight(c.X, c.Z) + spec.HalfHeight + 0.15f; + c.Y = spawnY; var handle = _world.AddBox( stableId, - (c.X, spec.HalfHeight + 0.1f, c.Z), + (c.X, spawnY, c.Z), (spec.HalfWidth, spec.HalfHeight, spec.HalfLength), density, (q.X, q.Y, q.Z, q.W), @@ -163,10 +167,12 @@ namespace RustToDust.Ymir float density = spec.MassKg / MathF.Max(0.1f, volume); var q = Quaternion.CreateFromAxisAngle(Vector3.UnitY, s.Yaw); ulong stableId = SpectatorStableIdBase + (ulong)s.Id; + float spawnY = State.Terrain.SampleHeight(s.X, s.Z) + spec.HalfHeight + 0.15f; + s.Y = spawnY; var handle = _world.AddBox( stableId, - (s.X, spec.HalfHeight + 0.1f, s.Z), + (s.X, spawnY, s.Z), (spec.HalfWidth, spec.HalfHeight, spec.HalfLength), density, (q.X, q.Y, q.Z, q.W), @@ -237,10 +243,18 @@ namespace RustToDust.Ymir continue; } + var pos = new Vector3(view.PositionX[lane], view.PositionY[lane], view.PositionZ[lane]); var q = new Quaternion(view.RotationX[lane], view.RotationY[lane], view.RotationZ[lane], view.RotationW[lane]); var vel = new Vector3(view.VelocityX[lane], view.VelocityY[lane], view.VelocityZ[lane]); var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); + ComputeTerrainSupport( + pos, q, vel, angVel, mass, c.Grid.Spec, + out Vector3 supportForce, + out Vector3 supportTorque, + out Vector3 terrainNormal, + out int groundedCorners); + var forward = Vector3.Transform(Vector3.UnitZ, q); forward.Y = 0f; if (forward.LengthSquared() < 1e-4f) forward = Vector3.UnitZ; @@ -249,18 +263,29 @@ namespace RustToDust.Ymir var right = Vector3.Cross(forward, Vector3.UnitY); var up = Vector3.Transform(Vector3.UnitY, q); + Vector3 driveForward = forward; + Vector3 driveRight = right; + if (groundedCorners > 0) + { + Vector3 fSlope = forward - terrainNormal * Vector3.Dot(forward, terrainNormal); + if (fSlope.LengthSquared() > 1e-4f) driveForward = Vector3.Normalize(fSlope); + Vector3 rSlope = right - terrainNormal * Vector3.Dot(right, terrainNormal); + if (rSlope.LengthSquared() > 1e-4f) driveRight = Vector3.Normalize(rSlope); + } + float thrust = c.Grid.ComputeDriveThrust(); float maxSpeed = MathF.Max(4f, c.Grid.Spec.MaxSpeed); - float forwardSpeed = Vector3.Dot(vel, forward); - float lateralSpeed = Vector3.Dot(vel, right); + float forwardSpeed = Vector3.Dot(vel, driveForward); + float lateralSpeed = Vector3.Dot(vel, driveRight); + float gripScale = groundedCorners > 0 ? (0.4f + 0.6f * (groundedCorners / 4f)) : 0.12f; - Vector3 force = Vector3.Zero; - // Drive thrust with smooth terminal velocity drag at MaxSpeed - force += forward * (c.ThrottleCmd * thrust - (thrust / maxSpeed) * forwardSpeed); + Vector3 force = supportForce; + // Drive thrust along slope-aligned forward with smooth terminal velocity drag at MaxSpeed + force += driveForward * (c.ThrottleCmd * thrust - (thrust / maxSpeed) * forwardSpeed) * gripScale; // Lateral tire / stride grip - force -= right * (lateralSpeed * mass * 8.5f); + force -= driveRight * (lateralSpeed * mass * 8.5f * gripScale); - if (c.BrakeCmd) + if (c.BrakeCmd && groundedCorners > 0) { var horizVel = new Vector3(vel.X, 0f, vel.Z); force -= horizVel * (mass * 7f); @@ -286,8 +311,9 @@ namespace RustToDust.Ymir float hz = view.Size2[lane]; float iy = mass * (hx * hx + hz * hz) / 3f; - Vector3 tiltAxis = Vector3.Cross(up, Vector3.UnitY); - Vector3 torque = tiltAxis * (mass * 28f) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * 6f); + Vector3 targetUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, 0.85f)); + Vector3 tiltAxis = Vector3.Cross(up, targetUp); + Vector3 torque = supportTorque + tiltAxis * (mass * 16f) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * 6f); torque.Y = iy * (targetYawVel - angVel.Y) * 8f; view.ForceX[lane] = force.X; @@ -322,11 +348,18 @@ namespace RustToDust.Ymir var angVel = new Vector3(view.AngularVelocityX[lane], view.AngularVelocityY[lane], view.AngularVelocityZ[lane]); var up = Vector3.Transform(Vector3.UnitY, q); + ComputeTerrainSupport( + pos, q, vel, angVel, mass, s.Grid.Spec, + out Vector3 supportForce, + out Vector3 supportTorque, + out Vector3 terrainNormal, + out _); + Vector3 toGoal = new Vector3(goalX - pos.X, 0f, goalZ - pos.Z); float dist = toGoal.Length(); Vector3 desiredVel = dist > 0.5f ? Vector3.Normalize(toGoal) * MathF.Min(s.MaxSpeed, dist * 1.5f) : Vector3.Zero; Vector3 horizVel = new Vector3(vel.X, 0f, vel.Z); - Vector3 force = (desiredVel - horizVel) * (mass * 4.5f); + Vector3 force = supportForce + (desiredVel - horizVel) * (mass * 4.5f); float desiredYaw = s.Stance == SpectatorStance.Neutral ? MathF.Atan2(-pos.X, -pos.Z) @@ -339,8 +372,9 @@ namespace RustToDust.Ymir float hz = view.Size2[lane]; float iy = mass * (hx * hx + hz * hz) / 3f; - Vector3 tiltAxis = Vector3.Cross(up, Vector3.UnitY); - Vector3 torque = tiltAxis * (mass * 26f) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * 6f); + Vector3 targetUp = Vector3.Normalize(Vector3.Lerp(Vector3.UnitY, terrainNormal, 0.7f)); + Vector3 tiltAxis = Vector3.Cross(up, targetUp); + Vector3 torque = supportTorque + tiltAxis * (mass * 16f) - new Vector3(angVel.X, 0f, angVel.Z) * (mass * 6f); torque.Y = iy * (Math.Clamp(yawErr * 3f, -5f, 5f) - angVel.Y) * 8f; view.ForceX[lane] = force.X; @@ -352,6 +386,57 @@ namespace RustToDust.Ymir } } + private void ComputeTerrainSupport( + Vector3 pos, + Quaternion q, + Vector3 vel, + Vector3 angVel, + float mass, + ChassisSpec spec, + out Vector3 supportForce, + out Vector3 supportTorque, + out Vector3 terrainNormal, + out int groundedCorners) + { + supportForce = Vector3.Zero; + supportTorque = Vector3.Zero; + groundedCorners = 0; + + float hx = spec.HalfWidth * 0.9f; + float hz = spec.HalfLength * 0.9f; + float bottomY = -spec.HalfHeight; + const float restTravel = 0.12f; + float kSpring = mass * 50f; + float cDamp = mass * 7.0f; + + Span corners = stackalloc Vector3[4] + { + new Vector3(-hx, bottomY, -hz), + new Vector3( hx, bottomY, -hz), + new Vector3(-hx, bottomY, hz), + new Vector3( hx, bottomY, hz) + }; + + for (int k = 0; k < 4; k++) + { + Vector3 r = Vector3.Transform(corners[k], q); + Vector3 wp = pos + r; + float gh = State.Terrain.SampleHeight(wp.X, wp.Z); + float pen = (gh + restTravel) - wp.Y; + if (pen > 0f) + { + groundedCorners++; + float vCornerY = vel.Y + Vector3.Cross(angVel, r).Y; + float fY = Math.Clamp(kSpring * pen - cDamp * vCornerY, 0f, mass * 120f); + supportForce.Y += fY; + supportTorque += Vector3.Cross(r, new Vector3(0f, fY, 0f)); + } + } + + var (nx, ny, nz) = State.Terrain.SampleNormal(pos.X, pos.Z); + terrainNormal = new Vector3(nx, ny, nz); + } + private void SyncBodiesFromWorld() { var view = _world.View; @@ -365,6 +450,8 @@ namespace RustToDust.Ymir } int lane = handle.Lane; + float prevX = c.X; + float prevZ = c.Z; c.X = view.PositionX[lane]; c.Y = view.PositionY[lane]; c.Z = view.PositionZ[lane]; @@ -374,6 +461,18 @@ namespace RustToDust.Ymir float vx = view.VelocityX[lane]; float vz = view.VelocityZ[lane]; c.Speed = MathF.Sqrt(vx * vx + vz * vz); + + float stepDist = MathF.Sqrt((c.X - prevX) * (c.X - prevX) + (c.Z - prevZ) * (c.Z - prevZ)); + float groundY = State.Terrain.SampleHeight(c.X, c.Z); + if (c.Speed > 2.0f && c.Y - c.Grid.Spec.HalfHeight <= groundY + 0.65f) + { + _trackDistAccum[i] += stepDist; + if (_trackDistAccum[i] >= 2.2f) + { + _trackDistAccum[i] = 0f; + State.Terrain.StampTrack(c.X, c.Z, c.Yaw, c.Grid.Spec.HalfWidth * 1.4f, 2.5f); + } + } } for (int i = 0; i < State.Spectators.Spectators.Count; i++) @@ -567,28 +666,47 @@ namespace RustToDust.Ymir (muzzle.X, muzzle.Y, muzzle.Z), (dir.X * range, dir.Y * range, dir.Z * range)); - Vector3 endPt = hit.Hit - ? new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z) - : muzzle + dir * range; + float boxDist = hit.Hit + ? Vector3.Distance(muzzle, new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z)) + : range; + + bool hitTerrain = State.Terrain.Raycast( + muzzle.X, muzzle.Y, muzzle.Z, + dir.X, dir.Y, dir.Z, + boxDist, + out float tx, out float ty, out float tz, out float terrainDist); + + Vector3 endPt; + if (hitTerrain && terrainDist < boxDist) + { + endPt = new Vector3(tx, ty, tz); + StampTerrainWeaponImpact(mod.Spec.Id, tx, tz, burstIndex: b); + } + else + { + endPt = hit.Hit + ? new Vector3(hit.Point.X, hit.Point.Y, hit.Point.Z) + : muzzle + dir * range; + + if (hit.Hit && hit.StableId != shooterStableId && _entityByStableId.TryGetValue(hit.StableId, out var targetRef)) + { + ApplyHitToTarget( + targetRef, + hit.Point, + mod.Spec.WeaponDamage * mod.CurrentPerformance, + mod.Spec.HeatOutput * 0.25f, + shooterContender, + shooterLabel, + isSpectatorShooter, + view); + } + } State.Tracers.Add(new TracerEvent( muzzle.X, muzzle.Y, muzzle.Z, endPt.X, endPt.Y, endPt.Z, tracerColor, 0.09f)); - - if (hit.Hit && hit.StableId != shooterStableId && _entityByStableId.TryGetValue(hit.StableId, out var targetRef)) - { - ApplyHitToTarget( - targetRef, - hit.Point, - mod.Spec.WeaponDamage * mod.CurrentPerformance, - mod.Spec.HeatOutput * 0.25f, - shooterContender, - shooterLabel, - isSpectatorShooter, - view); - } } shooterGrid.InjectHardpointHeat(mod.HardpointId, mod.Spec.HeatOutput); @@ -685,6 +803,8 @@ 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); State.Broadcast.EmitElimination(State.Time, shooterLabel, victim.Name, isSpectatorShooter); } @@ -707,9 +827,35 @@ 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); State.Broadcast.EmitElimination(State.Time, shooterLabel, $"{spec.Tier} Spectator", false); } + private void StampTerrainWeaponImpact(string weaponId, float x, float z, int burstIndex) + { + switch (weaponId) + { + case "recoilless": + State.Terrain.StampCrater(x, z, radius: 4.2f, depth: 1.05f); + State.Terrain.StampScorch(x, z, radius: 4.5f); + break; + case "gilded_lance": + State.Terrain.StampCrater(x, z, radius: 3.0f, depth: 0.70f); + State.Terrain.StampScorch(x, z, radius: 3.6f); + break; + case "flak": + if (burstIndex == 0) + { + State.Terrain.StampCrater(x, z, radius: 2.0f, depth: 0.35f); + } + break; + case "touring_plasma": + State.Terrain.StampScorch(x, z, radius: 1.3f); + break; + } + } + private static (float LocalRight, float LocalForward, float LocalHeightNorm) ComputeLocalHitCoords( (float X, float Y, float Z) hitPoint, int lane, @@ -729,7 +875,7 @@ namespace RustToDust.Ymir private float ResolveAimTargetY(float aimX, float aimZ, ulong shooterStableId) { float bestDistSq = 9f * 9f; - float bestY = 0.9f; + float bestY = State.Terrain.SampleHeight(aimX, aimZ) + 0.9f; for (int i = 0; i < State.Contenders.Count; i++) { diff --git a/tests/RustToDust.Tests/TerrainTests.cs b/tests/RustToDust.Tests/TerrainTests.cs new file mode 100644 index 0000000..080330b --- /dev/null +++ b/tests/RustToDust.Tests/TerrainTests.cs @@ -0,0 +1,143 @@ +using System; +using System.Collections.Generic; +using RustToDust.Core; +using RustToDust.Ymir; +using Xunit; + +namespace RustToDust.Tests +{ + public sealed class TerrainTests + { + [Fact] + public void Generate_ProducesDeterministicNonFlatReliefWithinBounds() + { + var emptyCover = Array.Empty(); + var a = TerrainField.Generate(42UL, emptyCover); + var b = TerrainField.Generate(42UL, emptyCover); + var c = TerrainField.Generate(999UL, emptyCover); + + float minH = float.PositiveInfinity; + float maxH = float.NegativeInfinity; + bool anyDifferentSeed = false; + + for (int gx = -160; gx <= 160; gx += 16) + { + for (int gz = -160; gz <= 160; gz += 16) + { + float ha = a.SampleHeight(gx, gz); + float hb = b.SampleHeight(gx, gz); + float hc = c.SampleHeight(gx, gz); + + Assert.Equal(ha, hb); + if (MathF.Abs(ha - hc) > 0.05f) + { + anyDifferentSeed = true; + } + + minH = MathF.Min(minH, ha); + maxH = MathF.Max(maxH, ha); + } + } + + Assert.True(maxH - minH > 2.5f, $"Expected non-flat dune/mesa relief > 2.5m span, got [{minH:F2}, {maxH:F2}]"); + Assert.InRange(minH, -4.5f, 1.0f); + Assert.InRange(maxH, 2.0f, 9.5f); + Assert.True(anyDifferentSeed, "Different seeds should generate distinct desert relief"); + } + + [Fact] + public void StampCrater_LowersCenterRaisesRimAndDirtyOnlyOverlappingTiles() + { + var terrain = TerrainField.Generate(42UL, Array.Empty()); + terrain.ClearDirtyMask(); + + // Tile (1, 1) spans X in [-96, 0), Z in [-96, 0). + // Point (-48, -48) with radius 6m is strictly inside tile (1, 1) and nowhere else. + const float cx = -48f; + const float cz = -48f; + const float radius = 6f; + const float depth = 1.6f; + + float beforeCenter = terrain.SampleHeight(cx, cz); + float beforeRim = terrain.SampleHeight(cx + radius * 0.775f, cz); + + terrain.StampCrater(cx, cz, radius, depth); + + float afterCenter = terrain.SampleHeight(cx, cz); + float afterRim = terrain.SampleHeight(cx + radius * 0.775f, cz); + + Assert.True(afterCenter < beforeCenter - 1.0f, + $"Expected crater center to drop >1.0m (before {beforeCenter:F2}, after {afterCenter:F2})"); + Assert.True(afterRim > beforeRim + 0.2f, + $"Expected crater ejecta rim to rise >0.2m (before {beforeRim:F2}, after {afterRim:F2})"); + + // Only tile (1, 1) should have incremented from version 1 to 2 + for (int tz = 0; tz < TerrainField.TileGridCount; tz++) + { + for (int tx = 0; tx < TerrainField.TileGridCount; tx++) + { + int expected = (tx == 1 && tz == 1) ? 2 : 1; + Assert.Equal(expected, terrain.TileVersions[tx, tz]); + } + } + Assert.Equal(1u << (1 * TerrainField.TileGridCount + 1), terrain.DirtyTileMask); + } + + [Fact] + public void StampTrack_BoundsDynamicDecalCount() + { + var terrain = TerrainField.Generate(7UL, Array.Empty()); + int initialCount = terrain.Brushes.Count; + + for (int i = 0; i < TerrainField.MaxDynamicDecals + 40; i++) + { + float x = -80f + (i % 40) * 4f; + float z = -80f + (i / 40) * 8f; + terrain.StampTrack(x, z, yaw: 0.4f, width: 1.6f, length: 2.5f); + } + + Assert.Equal(initialCount + TerrainField.MaxDynamicDecals, terrain.Brushes.Count); + } + + [Fact] + public void ArenaSession_BuggyDrivesAcrossDunesWithoutNanAndTracksElevation() + { + using var session = new ArenaSession(seed: 108); + var player = session.State.Player; + int initialBrushes = session.State.Terrain.Brushes.Count; + + float minGround = float.PositiveInfinity; + float maxGround = float.NegativeInfinity; + + for (int tick = 0; tick < 240; tick++) + { + // Steer gently across the desert ring + float steer = MathF.Sin(tick * 0.03f) * 0.35f; + session.Step(new PlayerInput( + Throttle: 1f, + Steer: steer, + AimWorldX: player.X + 30f, + AimWorldZ: player.Z, + Fire: false, + InteractPickup: false, + Brake: false)); + + Assert.False(float.IsNaN(player.X) || float.IsNaN(player.Y) || float.IsNaN(player.Z), + $"NaN pose at tick {tick}"); + + float gh = session.State.Terrain.SampleHeight(player.X, player.Z); + minGround = MathF.Min(minGround, gh); + maxGround = MathF.Max(maxGround, gh); + + // Chassis should remain supported near the terrain surface (never sink under -12m or rocket into orbit) + float bottomY = player.Y - player.Grid.Spec.HalfHeight; + Assert.InRange(bottomY - gh, -0.75f, 4.0f); + } + + Assert.True(session.State.Terrain.Brushes.Count > initialBrushes, + "Driving across dust should stamp tire track brushes"); + Assert.True(maxGround - minGround > 0.25f, + $"Expected buggy to traverse non-flat terrain (span {maxGround - minGround:F2}m)"); + } + } +}